From e0761c49e1d0d6c8ff2ff5caf1e569e769c67cfd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 2 Feb 2023 10:20:54 +0000 Subject: [PATCH 0001/1297] feat: upload code coverage to codecov.io --- .github/workflows/codecov.yml | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 .github/workflows/codecov.yml diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml new file mode 100644 index 000000000..05551bafc --- /dev/null +++ b/.github/workflows/codecov.yml @@ -0,0 +1,40 @@ +name: Upload code coverage + +on: + push: + pull_request: + +env: + CARGO_TERM_COLOR: always + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - uses: dtolnay/rust-toolchain@stable + with: + toolchain: nightly + components: rustfmt, llvm-tools-preview + - name: Build + run: cargo build --release + env: + CARGO_INCREMENTAL: "0" + RUSTFLAGS: "-Cinstrument-coverage" + RUSTDOCFLAGS: "-Cinstrument-coverage" + - name: Test + run: cargo test --all-features --no-fail-fast + env: + CARGO_INCREMENTAL: "0" + RUSTFLAGS: "-Cinstrument-coverage" + RUSTDOCFLAGS: "-Cinstrument-coverage" + - name: Install grcov + run: if [[ ! -e ~/.cargo/bin/grcov ]]; then cargo install grcov; fi + - name: Run grcov + run: grcov . --binary-path target/debug/deps/ -s . -t lcov --branch --ignore-not-existing --ignore '../**' --ignore '/*' -o coverage.lcov + - uses: codecov/codecov-action@v3 + with: + files: ./coverage.lcov + flags: rust + fail_ci_if_error: true # optional (default = false) From ae5f6286a3486e9186ea27a54bee69503a5421a7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 11 Apr 2023 18:26:43 +0100 Subject: [PATCH 0002/1297] docs: [#275] crate docs for configuration package --- packages/configuration/src/lib.rs | 322 +++++++++++++++++++++++++++++- src/servers/apis/mod.rs | 4 +- src/servers/apis/server.rs | 2 +- src/tracker/mod.rs | 2 +- 4 files changed, 325 insertions(+), 5 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index d5beca236..6b051b572 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -1,3 +1,231 @@ +//! Configuration data structures for [Torrust Tracker](https://docs.rs/torrust-tracker). +//! +//! This module contains the configuration data structures for the +//! Torrust Tracker, which is a `BitTorrent` tracker server. +//! +//! The configuration is loaded from a [TOML](https://toml.io/en/) file +//! `config.toml` in the project root folder or from an environment variable +//! with the same content as the file. +//! +//! When you run the tracker without a configuration file, a new one will be +//! created with the default values, but the tracker immediately exits. You can +//! then edit the configuration file and run the tracker again. +//! +//! Configuration can not only be loaded from a file, but also from environment +//! variable `TORRUST_TRACKER_CONFIG`. This is useful when running the tracker +//! in a Docker container or environments where you do not have a persistent +//! storage or you cannot inject a configuration file. Refer to +//! [`Torrust Tracker documentation`](https://docs.rs/torrust-tracker) for more +//! information about how to pass configuration to the tracker. +//! +//! # Table of contents +//! +//! - [Sections](#sections) +//! - [Port binding](#port-binding) +//! - [TSL support](#tsl-support) +//! - [Generating self-signed certificates](#generating-self-signed-certificates) +//! - [Default configuration](#default-configuration) +//! +//! ## Sections +//! +//! Each section in the toml structure is mapped to a data structure. For +//! example, the `[http_api]` section (configuration for the tracker HTTP API) +//! is mapped to the [`HttpApi`](HttpApi) structure. +//! +//! > **NOTICE**: some sections are arrays of structures. For example, the +//! > `[[udp_trackers]]` section is an array of [`UdpTracker`](UdpTracker) since +//! > you can have multiple running UDP trackers bound to different ports. +//! +//! Please refer to the documentation of each structure for more information +//! about each section. +//! +//! - [`Core configuration`](crate::Configuration) +//! - [`HTTP API configuration`](crate::HttpApi) +//! - [`HTTP Tracker configuration`](crate::HttpTracker) +//! - [`UDP Tracker configuration`](crate::UdpTracker) +//! +//! ## Port binding +//! +//! For the API, HTTP and UDP trackers you can bind to a random port by using +//! port `0`. For example, if you want to bind to a random port on all +//! interfaces, use `0.0.0.0:0`. The OS will choose a random port but the +//! tracker will not print the port it is listening to when it starts. It just +//! says `Starting Torrust HTTP tracker server on: http://0.0.0.0:0`. It shows +//! the port used in the configuration file, and not the port the +//! tracker is actually listening to. This is a planned feature, see issue +//! [186](https://github.com/torrust/torrust-tracker/issues/186) for more +//! information. +//! +//! ## TSL support +//! +//! For the API and HTTP tracker you can enable TSL by setting `ssl_enabled` to +//! `true` and setting the paths to the certificate and key files. +//! +//! Typically, you will have a directory structure like this: +//! +//! ```text +//! storage/ +//! ├── database +//! │ └── data.db +//! └── ssl_certificates +//! ├── localhost.crt +//! └── localhost.key +//! ``` +//! +//! where you can store all the persistent data. +//! +//! Alternatively, you could setup a reverse proxy like Nginx or Apache to +//! handle the SSL/TLS part and forward the requests to the tracker. If you do +//! that, you should set [`on_reverse_proxy`](crate::Configuration::on_reverse_proxy) +//! to `true` in the configuration file. It's out of scope for this +//! documentation to explain in detail how to setup a reverse proxy, but the +//! configuration file should be something like this: +//! +//! For [NGINX](https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/): +//! +//! ```text +//! # HTTPS only (with SSL - force redirect to HTTPS) +//! +//! server { +//! listen 80; +//! server_name tracker.torrust.com; +//! +//! return 301 https://$host$request_uri; +//! } +//! +//! server { +//! listen 443; +//! server_name tracker.torrust.com; +//! +//! ssl_certificate CERT_PATH +//! ssl_certificate_key CERT_KEY_PATH; +//! +//! location / { +//! proxy_set_header X-Forwarded-For $remote_addr; +//! proxy_pass http://127.0.0.1:6969; +//! } +//! } +//! ``` +//! +//! For [Apache](https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html): +//! +//! ```text +//! # HTTPS only (with SSL - force redirect to HTTPS) +//! +//! +//! ServerAdmin webmaster@tracker.torrust.com +//! ServerName tracker.torrust.com +//! +//! +//! RewriteEngine on +//! RewriteCond %{HTTPS} off +//! RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] +//! +//! +//! +//! +//! +//! ServerAdmin webmaster@tracker.torrust.com +//! ServerName tracker.torrust.com +//! +//! +//! Order allow,deny +//! Allow from all +//! +//! +//! ProxyPreserveHost On +//! ProxyRequests Off +//! AllowEncodedSlashes NoDecode +//! +//! ProxyPass / http://localhost:3000/ +//! ProxyPassReverse / http://localhost:3000/ +//! ProxyPassReverse / http://tracker.torrust.com/ +//! +//! RequestHeader set X-Forwarded-Proto "https" +//! RequestHeader set X-Forwarded-Port "443" +//! +//! ErrorLog ${APACHE_LOG_DIR}/tracker.torrust.com-error.log +//! CustomLog ${APACHE_LOG_DIR}/tracker.torrust.com-access.log combined +//! +//! SSLCertificateFile CERT_PATH +//! SSLCertificateKeyFile CERT_KEY_PATH +//! +//! +//! ``` +//! +//! ## Generating self-signed certificates +//! +//! For testing purposes, you can use self-signed certificates. +//! +//! Refer to [Let's Encrypt - Certificates for localhost](https://letsencrypt.org/docs/certificates-for-localhost/) +//! for more information. +//! +//! Running the following command will generate a certificate (`localhost.crt`) +//! and key (`localhost.key`) file in your current directory: +//! +//! ```s +//! openssl req -x509 -out localhost.crt -keyout localhost.key \ +//! -newkey rsa:2048 -nodes -sha256 \ +//! -subj '/CN=localhost' -extensions EXT -config <( \ +//! printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth") +//! ``` +//! +//! You can then use the generated files in the configuration file: +//! +//! ```s +//! [[http_trackers]] +//! enabled = true +//! ... +//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" +//! ssl_key_path = "./storage/ssl_certificates/localhost.key" +//! +//! [http_api] +//! enabled = true +//! ... +//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" +//! ssl_key_path = "./storage/ssl_certificates/localhost.key" +//! ``` +//! +//! ## Default configuration +//! +//! The default configuration is: +//! +//! ```toml +//! log_level = "info" +//! mode = "public" +//! db_driver = "Sqlite3" +//! db_path = "./storage/database/data.db" +//! announce_interval = 120 +//! min_announce_interval = 120 +//! max_peer_timeout = 900 +//! on_reverse_proxy = false +//! external_ip = "0.0.0.0" +//! tracker_usage_statistics = true +//! persistent_torrent_completed_stat = false +//! inactive_peer_cleanup_interval = 600 +//! remove_peerless_torrents = true +//! +//! [[udp_trackers]] +//! enabled = false +//! bind_address = "0.0.0.0:6969" +//! +//! [[http_trackers]] +//! enabled = false +//! bind_address = "0.0.0.0:7070" +//! ssl_enabled = false +//! ssl_cert_path = "" +//! ssl_key_path = "" +//! +//! [http_api] +//! enabled = true +//! bind_address = "127.0.0.1:1212" +//! ssl_enabled = false +//! ssl_cert_path = "" +//! ssl_key_path = "" +//! +//! [http_api.access_tokens] +//! admin = "MyAccessToken" +//!``` use std::collections::{HashMap, HashSet}; use std::net::IpAddr; use std::panic::Location; @@ -14,38 +242,67 @@ use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; +/// Configuration for each UDP tracker. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct UdpTracker { + /// Weather the UDP tracker is enabled or not. pub enabled: bool, + /// The address the tracker will bind to. + /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to + /// listen to all interfaces, use `0.0.0.0`. If you want the operating + /// system to choose a random port, use port `0`. pub bind_address: String, } +/// Configuration for each HTTP tracker. #[serde_as] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct HttpTracker { + /// Weather the HTTP tracker is enabled or not. pub enabled: bool, + /// The address the tracker will bind to. + /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to + /// listen to all interfaces, use `0.0.0.0`. If you want the operating + /// system to choose a random port, use port `0`. pub bind_address: String, + /// Weather the HTTP tracker will use SSL or not. pub ssl_enabled: bool, + /// Path to the SSL certificate file. Only used if `ssl_enabled` is `true`. #[serde_as(as = "NoneAsEmptyString")] pub ssl_cert_path: Option, + /// Path to the SSL key file. Only used if `ssl_enabled` is `true`. #[serde_as(as = "NoneAsEmptyString")] pub ssl_key_path: Option, } +/// Configuration for the HTTP API. #[serde_as] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct HttpApi { + /// Weather the HTTP API is enabled or not. pub enabled: bool, + /// The address the tracker will bind to. + /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to + /// listen to all interfaces, use `0.0.0.0`. If you want the operating + /// system to choose a random port, use port `0`. pub bind_address: String, + /// Weather the HTTP API will use SSL or not. pub ssl_enabled: bool, + /// Path to the SSL certificate file. Only used if `ssl_enabled` is `true`. #[serde_as(as = "NoneAsEmptyString")] pub ssl_cert_path: Option, + /// Path to the SSL key file. Only used if `ssl_enabled` is `true`. #[serde_as(as = "NoneAsEmptyString")] pub ssl_key_path: Option, + /// Access tokens for the HTTP API. The key is a label identifying the + /// token and the value is the token itself. The token is used to + /// authenticate the user. All tokens are valid for all endpoints and have + /// the all permissions. pub access_tokens: HashMap, } impl HttpApi { + /// Checks if the given token is one of the token in the configuration. #[must_use] pub fn contains_token(&self, token: &str) -> bool { let tokens: HashMap = self.access_tokens.clone(); @@ -54,14 +311,24 @@ impl HttpApi { } } +/// 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, + /// Tracker mode. See [`TrackerMode`](torrust_tracker_primitives::TrackerMode) for more information. pub mode: TrackerMode, // Database configuration + /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. pub db_driver: DatabaseDriver, + /// Database connection string. The format depends on the database driver. + /// For `Sqlite3`, the format is `path/to/database.db`, for example: + /// `./storage/database/data.db`. + /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for + /// example: `root:password@localhost:3306/torrust`. pub db_path: String, /// Interval in seconds that the client should wait between sending regular @@ -88,35 +355,77 @@ pub struct Configuration { /// could lead to excessive load on the tracker or even getting banned by /// the tracker for not adhering to the rules. pub min_announce_interval: u32, + /// Weather the tracker is behind a reverse proxy or not. + /// If the tracker is behind a reverse proxy, the `X-Forwarded-For` header + /// sent from the proxy will be used to get the client's IP address. pub on_reverse_proxy: bool, + /// The external IP address of the tracker. If the client is using a + /// loopback IP address, this IP address will be used instead. If the peer + /// 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, + /// 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. + /// Refer to the [`Tracker`](https://docs.rs/torrust-tracker) for more + /// information about the collected metrics. pub tracker_usage_statistics: bool, + /// If enabled the tracker will persist the number of completed downloads. + /// That's how many times a torrent has been downloaded completely. pub persistent_torrent_completed_stat: bool, // Cleanup job configuration + /// Maximum time in seconds that a peer can be inactive before being + /// considered an inactive peer. If a peer is inactive for more than this + /// time, it will be removed from the torrent peer list. pub max_peer_timeout: u32, + /// Interval in seconds that the cleanup job will run to remove inactive + /// peers from the torrent peer list. pub inactive_peer_cleanup_interval: u64, + /// If enabled, the tracker will remove torrents that have no peers. + /// THe clean up torrent job runs every `inactive_peer_cleanup_interval` + /// seconds and it removes inactive peers. Eventually, the peer list of a + /// torrent could be empty and the torrent will be removed if this option is + /// enabled. pub remove_peerless_torrents: bool, // Server jobs configuration + /// The list of UDP trackers the tracker is running. Each UDP tracker + /// represents a UDP server that the tracker is running and it has its own + /// configuration. pub udp_trackers: Vec, + /// The list of HTTP trackers the tracker is running. Each HTTP tracker + /// represents a HTTP server that the tracker is running and it has its own + /// configuration. pub http_trackers: Vec, + /// The HTTP API configuration. pub http_api: HttpApi, } +/// Errors that can occur when loading the configuration. #[derive(Error, Debug)] pub enum Error { + /// Unable to load the configuration from the environment variable. + /// This error only occurs if there is no configuration file and the + /// `TORRUST_TRACKER_CONFIG` environment variable is not set. #[error("Unable to load from Environmental Variable: {source}")] UnableToLoadFromEnvironmentVariable { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, }, + /// If you run the tracker without providing the configuration (via the + /// `TORRUST_TRACKER_CONFIG` environment variable or configuration file), + /// the tracker will create a default configuration file but it will not + /// load it. It will return this error instead and you have to restart the + /// it. #[error("Default configuration created at: `{path}`, please review and reload tracker, {location}")] CreatedNewConfigHalt { location: &'static Location<'static>, path: String, }, + /// Unable to load the configuration from the configuration file. #[error("Failed processing the configuration: {source}")] ConfigError { source: LocatedError<'static, ConfigError> }, } @@ -176,6 +485,8 @@ impl Default for Configuration { } impl Configuration { + /// Returns the tracker public IP address id defined in the configuration, + /// and `None` otherwise. #[must_use] pub fn get_ext_ip(&self) -> Option { match &self.external_ip { @@ -187,6 +498,8 @@ impl Configuration { } } + /// Loads the configuration from the configuration file. + /// /// # Errors /// /// Will return `Err` if `path` does not exist or has a bad configuration. @@ -214,6 +527,10 @@ impl Configuration { Ok(torrust_config) } + /// Loads the configuration from the environment variable. The whole + /// configuration must be in the environment variable. It contains the same + /// configuration as the configuration file with the same format. + /// /// # Errors /// /// Will return `Err` if the environment variable does not exist or has a bad configuration. @@ -232,10 +549,13 @@ impl Configuration { } } + /// Saves the configuration to the configuration file. + /// /// # Errors /// /// Will return `Err` if `filename` does not exist or the user does not have - /// permission to read it. + /// permission to read it. Will also return `Err` if the configuration is + /// not valid or cannot be encoded to TOML. pub fn save_to_file(&self, path: &str) -> Result<(), Error> { let toml_string = toml::to_string(self).expect("Could not encode TOML value"); fs::write(path, toml_string).expect("Could not write to file!"); diff --git a/src/servers/apis/mod.rs b/src/servers/apis/mod.rs index 203f1d146..eb278bf3c 100644 --- a/src/servers/apis/mod.rs +++ b/src/servers/apis/mod.rs @@ -35,7 +35,7 @@ //! admin = "MyAccessToken" //! ``` //! -//! Refer to [torrust-tracker-configuration](https://docs.rs/torrust-tracker-configuration>) +//! Refer to [`torrust-tracker-configuration`](torrust_tracker_configuration) //! for more information about the API configuration. //! //! When you run the tracker with enabled API, you will see the following message: @@ -99,7 +99,7 @@ //! The token label is used to identify the token. All tokens have full access //! to the API. //! -//! Refer to [torrust-tracker-configuration](https://docs.rs/torrust-tracker-configuration>) +//! Refer to [`torrust-tracker-configuration`](torrust_tracker_configuration) //! for more information about the API configuration and to the //! [`auth`](crate::servers::apis::v1::middlewares::auth) middleware for more //! information about the authentication process. diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 76396cc51..91821aa79 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -140,7 +140,7 @@ impl Launcher { /// Starts the API server with graceful shutdown. /// /// If TLS is enabled in the configuration, it will start the server with - /// TLS. See [torrust-tracker-configuration](https://docs.rs/torrust-tracker-configuration>) + /// TLS. See [`torrust-tracker-configuration`](torrust_tracker_configuration) /// for more information about configuration. pub fn start( cfg: &torrust_tracker_configuration::HttpApi, diff --git a/src/tracker/mod.rs b/src/tracker/mod.rs index 03853e1aa..2cabd5a82 100644 --- a/src/tracker/mod.rs +++ b/src/tracker/mod.rs @@ -468,7 +468,7 @@ use crate::tracker::databases::Database; /// Typically, the `Tracker` is used by a higher application service that handles /// the network layer. pub struct Tracker { - /// `Tracker` configuration. See + /// `Tracker` configuration. See [`torrust-tracker-configuration`](torrust_tracker_configuration) pub config: Arc, /// A database driver implementation: [`Sqlite3`](crate::tracker::databases::sqlite) /// or [`MySQL`](crate::tracker::databases::mysql) From a109168cd30a05648bec5d6be643e9525d76032f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 12 Apr 2023 07:00:27 +0100 Subject: [PATCH 0003/1297] feat: dependabot workflow To open pull requests automatically to keep the dependencies up-to-date . --- .github/dependabot.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..8f36cb692 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: daily + target-branch: "develop" + + - package-ecosystem: cargo + directory: / + schedule: + interval: daily + target-branch: "develop" From 117dc0bbfe59ecac7ecf94751dd01d962c785c99 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 11 Apr 2023 19:34:53 +0100 Subject: [PATCH 0004/1297] docs: [#275] crate docs for locate-error package --- packages/located-error/src/lib.rs | 39 ++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs index d45517e5a..67c432528 100644 --- a/packages/located-error/src/lib.rs +++ b/packages/located-error/src/lib.rs @@ -1,11 +1,44 @@ -// https://stackoverflow.com/questions/74336993/getting-line-numbers-with-when-using-boxdyn-stderrorerror - +//! This crate provides a wrapper around an error that includes the location of +//! the error. +//! +//! ```rust +//! use std::error::Error; +//! use std::panic::Location; +//! use std::sync::Arc; +//! use torrust_tracker_located_error::{Located, LocatedError}; +//! +//! #[derive(thiserror::Error, Debug)] +//! enum TestError { +//! #[error("Test")] +//! Test, +//! } +//! +//! #[track_caller] +//! fn get_caller_location() -> Location<'static> { +//! *Location::caller() +//! } +//! +//! let e = TestError::Test; +//! +//! let b: LocatedError = Located(e).into(); +//! let l = get_caller_location(); +//! +//! assert!(b.to_string().contains("Test, src/lib.rs")); +//! ``` +//! +//! # Credits +//! +//! use std::error::Error; use std::panic::Location; use std::sync::Arc; +/// A generic wrapper around an error. +/// +/// Where `E` is the inner error (source error). pub struct Located(pub E); +/// A wrapper around an error that includes the location of the error. #[derive(Debug)] pub struct LocatedError<'a, E> where @@ -78,7 +111,7 @@ mod tests { use std::panic::Location; use super::LocatedError; - use crate::located_error::Located; + use crate::Located; #[derive(thiserror::Error, Debug)] enum TestError { From cb6fc79e316528e2f1ffd807bdb3e46c255d78ee Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 12 Apr 2023 12:10:05 +0100 Subject: [PATCH 0005/1297] fix: update dependencies --- Cargo.lock | 601 ++++++++++++++++++++++++++++++----------------------- 1 file changed, 337 insertions(+), 264 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3bc78bd67..d7053d618 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -81,13 +81,13 @@ checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" [[package]] name = "async-trait" -version = "0.1.66" +version = "0.1.68" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b84f9ebcc6c1f5b8cb160f6990096a5c127f423fcb6e1ccc46c370cbdfb75dfc" +checksum = "b9ccdd8f2a161be9bd5c023df56f1b2a0bd1d83872ae53b71a84a12c9bf6e842" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.14", ] [[package]] @@ -98,9 +98,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axum" -version = "0.6.10" +version = "0.6.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8582122b8edba2af43eaf6b80dbfd33f421b5a0eb3a3113d21bc096ac5b44faf" +checksum = "3b32c5ea3aabaf4deb5f5ced2d688ec0844c881c9e6c696a8b769a05fc691e62" dependencies = [ "async-trait", "axum-core", @@ -124,7 +124,6 @@ dependencies = [ "sync_wrapper", "tokio", "tower", - "tower-http", "tower-layer", "tower-service", ] @@ -142,9 +141,9 @@ dependencies = [ [[package]] name = "axum-core" -version = "0.3.3" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2f958c80c248b34b9a877a643811be8dbca03ca5ba827f2b63baf3a81e5fc4e" +checksum = "759fa577a247914fd3f7f76d62972792636412fbfd634cd452f6a385a74d2d2c" dependencies = [ "async-trait", "bytes", @@ -159,9 +158,9 @@ dependencies = [ [[package]] name = "axum-server" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25e4a990e1593e286b1b96e6df76da9dbcb84945a810287ca8101f1a4f000f61" +checksum = "bace45b270e36e3c27a190c65883de6dfc9f1d18c829907c127464815dc67b24" dependencies = [ "arc-swap", "bytes", @@ -278,9 +277,9 @@ dependencies = [ [[package]] name = "borsh" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40f9ca3698b2e4cb7c15571db0abc5551dca417a21ae8140460b50309bb2cc62" +checksum = "4114279215a005bc675e386011e594e1d9b800918cea18fcadadcce864a2046b" dependencies = [ "borsh-derive", "hashbrown 0.13.2", @@ -288,37 +287,37 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "598b3eacc6db9c3ee57b22707ad8f6a8d2f6d442bfe24ffeb8cbb70ca59e6a35" +checksum = "0754613691538d51f329cce9af41d7b7ca150bc973056f1156611489475f54f7" dependencies = [ "borsh-derive-internal", "borsh-schema-derive-internal", "proc-macro-crate", "proc-macro2", - "syn", + "syn 1.0.109", ] [[package]] name = "borsh-derive-internal" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "186b734fa1c9f6743e90c95d7233c9faab6360d1a96d4ffa19d9cfd1e9350f8a" +checksum = "afb438156919598d2c7bad7e1c0adf3d26ed3840dbc010db1a882a65583ca2fb" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.109", ] [[package]] name = "borsh-schema-derive-internal" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99b7ff1008316626f485991b960ade129253d4034014616b94f309a15366cc49" +checksum = "634205cc43f74a1b9046ef87c4540ebda95696ec0f315024860cad7c5b0f5ccd" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.109", ] [[package]] @@ -352,7 +351,7 @@ checksum = "e31225543cb46f81a7e224762764f4a6a0f097b1db0b175f69e8065efaa42de5" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.109", ] [[package]] @@ -390,9 +389,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.23" +version = "0.4.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f" +checksum = "4e3c5919066adf22df73762e50cffcde3a758f2a848b113b586d1f86728b673b" dependencies = [ "iana-time-zone", "js-sys", @@ -406,9 +405,9 @@ dependencies = [ [[package]] name = "clang-sys" -version = "1.6.0" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ed9a53e5d4d9c573ae844bfac6872b159cb1d1585a83b29e7a64b7eef7332a" +checksum = "c688fc74432808e3eb684cae8830a86be1d66a2bd58e1f248ed0960a590baf6f" dependencies = [ "glob", "libc", @@ -417,9 +416,9 @@ dependencies = [ [[package]] name = "cmake" -version = "0.1.49" +version = "0.1.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db34956e100b30725f2eb215f90d4871051239535632f84fea3bc92722c66b7c" +checksum = "a31c789563b815f77f4250caee12365734369f942439b7defd71e18a48197130" dependencies = [ "cc", ] @@ -471,15 +470,15 @@ dependencies = [ [[package]] name = "core-foundation-sys" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc" +checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" [[package]] name = "cpufeatures" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320" +checksum = "280a9f2d8b3a38871a3c8a46fb80db65e5e5ed97da80c4d08bf27fb63e35e181" dependencies = [ "libc", ] @@ -509,9 +508,9 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.7" +version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf2b3e8478797446514c91ef04bafcb59faba183e621ad488df88983cc14128c" +checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200" dependencies = [ "cfg-if", "crossbeam-utils", @@ -572,9 +571,9 @@ dependencies = [ [[package]] name = "cxx" -version = "1.0.92" +version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a140f260e6f3f79013b8bfc65e7ce630c9ab4388c6a89c71e07226f49487b72" +checksum = "f61f1b6389c3fe1c316bf8a4dccc90a38208354b330925bce1f74a6c4756eb93" dependencies = [ "cc", "cxxbridge-flags", @@ -584,9 +583,9 @@ dependencies = [ [[package]] name = "cxx-build" -version = "1.0.92" +version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da6383f459341ea689374bf0a42979739dc421874f112ff26f829b8040b8e613" +checksum = "12cee708e8962df2aeb38f594aae5d827c022b6460ac71a7a3e2c3c2aae5a07b" dependencies = [ "cc", "codespan-reporting", @@ -594,24 +593,24 @@ dependencies = [ "proc-macro2", "quote", "scratch", - "syn", + "syn 2.0.14", ] [[package]] name = "cxxbridge-flags" -version = "1.0.92" +version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90201c1a650e95ccff1c8c0bb5a343213bdd317c6e600a93075bca2eff54ec97" +checksum = "7944172ae7e4068c533afbb984114a56c46e9ccddda550499caa222902c7f7bb" [[package]] name = "cxxbridge-macro" -version = "1.0.92" +version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b75aed41bb2e6367cae39e6326ef817a851db13c13e4f3263714ca3cfb8de56" +checksum = "2345488264226bf682893e25de0769f3360aac9957980ec49361b083ddaa5bc5" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.14", ] [[package]] @@ -635,7 +634,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn", + "syn 1.0.109", ] [[package]] @@ -646,7 +645,7 @@ checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" dependencies = [ "darling_core", "quote", - "syn", + "syn 1.0.109", ] [[package]] @@ -659,18 +658,18 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn", + "syn 1.0.109", ] [[package]] name = "derive_utils" -version = "0.12.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7590f99468735a318c254ca9158d0c065aa9b5312896b5a043b5e39bc96f5fa2" +checksum = "dff8f6a793f528719e1ad4425a52a213ac1214ac7158c5fb97a7f50a64bfc96d" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.14", ] [[package]] @@ -718,13 +717,13 @@ dependencies = [ [[package]] name = "errno" -version = "0.2.8" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1" +checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" dependencies = [ "errno-dragonfly", "libc", - "winapi", + "windows-sys 0.48.0", ] [[package]] @@ -769,9 +768,9 @@ dependencies = [ [[package]] name = "fern" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bdd7b0849075e79ee9a1836df22c717d1eba30451796fdc631b04565dd11e2a" +checksum = "d9f0c14694cbd524c8720dd69b0e3179344f04ebb5f90f2e4a440c6ea3b2f1ee" dependencies = [ "log", ] @@ -867,7 +866,7 @@ checksum = "b83164912bb4c97cfe0772913c7af7387ee2e00cb6d4636fb65a35b3d0c8f173" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn", + "syn 1.0.109", ] [[package]] @@ -879,7 +878,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn", + "syn 1.0.109", ] [[package]] @@ -903,7 +902,7 @@ dependencies = [ "frunk_proc_macro_helpers", "proc-macro-hack", "quote", - "syn", + "syn 1.0.109", ] [[package]] @@ -914,9 +913,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" [[package]] name = "futures" -version = "0.3.26" +version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13e2792b0ff0340399d58445b88fd9770e3489eff258a4cbc1523418f12abf84" +checksum = "23342abe12aba583913b2e62f22225ff9c950774065e4bfb61a19cd9770fec40" dependencies = [ "futures-channel", "futures-core", @@ -929,9 +928,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.26" +version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e5317663a9089767a1ec00a487df42e0ca174b61b4483213ac24448e4664df5" +checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" dependencies = [ "futures-core", "futures-sink", @@ -939,15 +938,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.26" +version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec90ff4d0fe1f57d600049061dc6bb68ed03c7d2fbd697274c41805dcb3f8608" +checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" [[package]] name = "futures-executor" -version = "0.3.26" +version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8de0a35a6ab97ec8869e32a2473f4b1324459e14c29275d14b10cb1fd19b50e" +checksum = "ccecee823288125bd88b4d7f565c9e58e41858e47ab72e8ea2d64e93624386e0" dependencies = [ "futures-core", "futures-task", @@ -956,38 +955,38 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.26" +version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfb8371b6fb2aeb2d280374607aeabfc99d95c72edfe51692e42d3d7f0d08531" +checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" [[package]] name = "futures-macro" -version = "0.3.26" +version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95a73af87da33b5acf53acfebdc339fe592ecf5357ac7c0a7734ab9d8c876a70" +checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.14", ] [[package]] name = "futures-sink" -version = "0.3.26" +version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f310820bb3e8cfd46c80db4d7fb8353e15dfff853a127158425f31e0be6c8364" +checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" [[package]] name = "futures-task" -version = "0.3.26" +version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf79a1bf610b10f42aea489289c5a2c478a786509693b80cd39c44ccd936366" +checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" [[package]] name = "futures-util" -version = "0.3.26" +version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c1d6de3acfef38d2be4b1f543f553131788603495be83da675e180c8d6b7bd1" +checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" dependencies = [ "futures-channel", "futures-core", @@ -1003,9 +1002,9 @@ dependencies = [ [[package]] name = "generic-array" -version = "0.14.6" +version = "0.14.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", @@ -1013,9 +1012,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.8" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31" +checksum = "c85e1d9ab2eadba7e5040d4e09cbd6d072b76a557ad64e797c2cb9d4da21d7e4" dependencies = [ "cfg-if", "libc", @@ -1089,6 +1088,12 @@ dependencies = [ "libc", ] +[[package]] +name = "hermit-abi" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" + [[package]] name = "hex" version = "0.4.3" @@ -1117,12 +1122,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "http-range-header" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bfe8eed0a9285ef776bb792479ea3834e8b94e13d615c2f66d03dd50a435a29" - [[package]] name = "httparse" version = "1.8.0" @@ -1137,9 +1136,9 @@ checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" [[package]] name = "hyper" -version = "0.14.24" +version = "0.14.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e011372fa0b68db8350aa7a248930ecc7839bf46d8485577d69f117a75f164c" +checksum = "cc5e554ff619822309ffd57d8734d77cd5ce6238bc956f037ea06c58238c9899" dependencies = [ "bytes", "futures-channel", @@ -1174,16 +1173,16 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.53" +version = "0.1.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64c122667b287044802d6ce17ee2ddf13207ed924c712de9a66a5814d5b64765" +checksum = "0722cd7114b7de04316e7ea5456a0bbb20e4adb46fd27a3697adb812cff0f37c" dependencies = [ "android_system_properties", "core-foundation-sys", "iana-time-zone-haiku", "js-sys", "wasm-bindgen", - "winapi", + "windows", ] [[package]] @@ -1214,9 +1213,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "1.9.2" +version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" dependencies = [ "autocfg", "hashbrown 0.12.3", @@ -1234,30 +1233,30 @@ dependencies = [ [[package]] name = "io-enum" -version = "1.0.2" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4b0d47a958cb166282b4dc4840a35783e861c2b39080af846e6481ebe145eee" +checksum = "01c662c349c9c9f542e7bfd9134143beb27da4b20dfbc3b3ef5b2a5b507dafbd" dependencies = [ "derive_utils", - "quote", - "syn", + "syn 2.0.14", ] [[package]] name = "io-lifetimes" -version = "1.0.6" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfa919a82ea574332e2de6e74b4c36e74d41982b335080fa59d4ef31be20fdf3" +checksum = "9c66c74d2ae7e79a5a8f7ac924adbe38ee42a859c6539ad869eb51f0b52dc220" dependencies = [ + "hermit-abi 0.3.1", "libc", - "windows-sys 0.45.0", + "windows-sys 0.48.0", ] [[package]] name = "ipnet" -version = "2.7.1" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30e22bd8629359895450b59ea7a776c850561b96a3b1d31321c1949d9e6c9146" +checksum = "12b6ee2129af8d4fb011108c73d99a1b83a85977f23b82460c0ae2e25bb4b57f" [[package]] name = "itertools" @@ -1270,9 +1269,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.5" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440" +checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" [[package]] name = "js-sys" @@ -1381,9 +1380,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.140" +version = "0.2.141" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99227334921fae1a979cf0bfdfcc6b3e5ce376ef57e16fb6fb3ea2ed6095f80c" +checksum = "3304a64d199bb964be99741b7a14d26972741915b3649639149b2479bb46f4b5" [[package]] name = "libloading" @@ -1434,9 +1433,9 @@ checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" [[package]] name = "linux-raw-sys" -version = "0.1.4" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f051f77a7c8e6957c0696eac88f26b0117e54f52d3fc682ab19397a8812846a4" +checksum = "d59d8c75012853d2e872fb56bc8a2e53718e2cafe1a4c823143141c6d90c322f" [[package]] name = "local-ip-address" @@ -1501,9 +1500,9 @@ dependencies = [ [[package]] name = "mime" -version = "0.3.16" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" [[package]] name = "minimal-lexical" @@ -1534,9 +1533,9 @@ dependencies = [ [[package]] name = "mockall" -version = "0.11.3" +version = "0.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50e4a1c770583dac7ab5e2f6c139153b783a53a1bbee9729613f193e59828326" +checksum = "4c84490118f2ee2d74570d114f3d0493cbf02790df303d2707606c3e14e07c96" dependencies = [ "cfg-if", "downcast", @@ -1549,14 +1548,14 @@ dependencies = [ [[package]] name = "mockall_derive" -version = "0.11.3" +version = "0.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "832663583d5fa284ca8810bf7015e46c9fff9622d3cf34bd1eea5003fec06dd0" +checksum = "22ce75669015c4f47b289fd4d4f56e894e4c96003ffdf3ac51313126f94c6cbb" dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn", + "syn 1.0.109", ] [[package]] @@ -1726,7 +1725,7 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" dependencies = [ - "hermit-abi", + "hermit-abi 0.2.6", "libc", ] @@ -1747,9 +1746,9 @@ checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" [[package]] name = "openssl" -version = "0.10.45" +version = "0.10.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b102428fd03bc5edf97f62620f7298614c45cedf287c271e7ed450bbaf83f2e1" +checksum = "7e30d8bc91859781f0a943411186324d580f2bbeb71b452fe91ae344806af3f1" dependencies = [ "bitflags", "cfg-if", @@ -1762,13 +1761,13 @@ dependencies = [ [[package]] name = "openssl-macros" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b501e44f11665960c7e7fcf062c7d96a14ade4aa98116c004b2e37b5be7d736c" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.14", ] [[package]] @@ -1779,20 +1778,19 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "111.25.1+1.1.1t" +version = "111.25.2+1.1.1t" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ef9a9cc6ea7d9d5e7c4a913dc4b48d0e359eddf01af1dfec96ba7064b4aba10" +checksum = "320708a054ad9b3bf314688b5db87cf4d6683d64cfc835e2337924ae62bf4431" dependencies = [ "cc", ] [[package]] name = "openssl-sys" -version = "0.9.80" +version = "0.9.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23bbbf7854cd45b83958ebe919f0e8e516793727652e27fda10a8384cfc790b7" +checksum = "0d3d193fb1488ad46ffe3aaabc912cc931d02ee8518fe2959aea8ef52718b0c0" dependencies = [ - "autocfg", "cc", "libc", "openssl-src", @@ -1828,7 +1826,7 @@ checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" dependencies = [ "cfg-if", "libc", - "redox_syscall", + "redox_syscall 0.2.16", "smallvec", "windows-sys 0.45.0", ] @@ -1862,9 +1860,9 @@ checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" [[package]] name = "pest" -version = "2.5.6" +version = "2.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cbd939b234e95d72bc393d51788aec68aeeb5d51e748ca08ff3aad58cb722f7" +checksum = "7b1403e8401ad5dedea73c626b99758535b342502f8d1e361f4a2dd952749122" dependencies = [ "thiserror", "ucd-trie", @@ -1872,9 +1870,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.5.6" +version = "2.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a81186863f3d0a27340815be8f2078dd8050b14cd71913db9fbda795e5f707d7" +checksum = "be99c4c1d2fc2769b1d00239431d711d08f6efedcecb8b6e30707160aee99c15" dependencies = [ "pest", "pest_generator", @@ -1882,22 +1880,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.5.6" +version = "2.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75a1ef20bf3193c15ac345acb32e26b3dc3223aff4d77ae4fc5359567683796b" +checksum = "e56094789873daa36164de2e822b3888c6ae4b4f9da555a1103587658c805b1e" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn", + "syn 2.0.14", ] [[package]] name = "pest_meta" -version = "2.5.6" +version = "2.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e3b284b1f13a20dc5ebc90aff59a51b8d7137c221131b52a7260c08cbc1cc80" +checksum = "6733073c7cff3d8459fda0e42f13a047870242aed8b509fe98000928975f359e" dependencies = [ "once_cell", "pest", @@ -1921,7 +1919,7 @@ checksum = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.109", ] [[package]] @@ -1964,15 +1962,15 @@ dependencies = [ [[package]] name = "predicates-core" -version = "1.0.5" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f883590242d3c6fc5bf50299011695fa6590c2c70eac95ee1bdb9a733ad1a2" +checksum = "b794032607612e7abeb4db69adb4e33590fa6cf1149e95fd7cb00e634b92f174" [[package]] name = "predicates-tree" -version = "1.0.7" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54ff541861505aabf6ea722d2131ee980b8276e10a1297b94e896dd8b621850d" +checksum = "368ba315fb8c5052ab692e68a0eefec6ec57b23a36959c14496f0b0df2c0cecf" dependencies = [ "predicates-core", "termtree", @@ -1995,9 +1993,9 @@ checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" [[package]] name = "proc-macro2" -version = "1.0.51" +version = "1.0.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d727cae5b39d21da60fa540906919ad737832fe0b1c165da3a34d6548c849d6" +checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435" dependencies = [ "unicode-ident", ] @@ -2019,14 +2017,14 @@ checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.109", ] [[package]] name = "quote" -version = "1.0.23" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b" +checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" dependencies = [ "proc-macro2", ] @@ -2107,11 +2105,20 @@ dependencies = [ "bitflags", ] +[[package]] +name = "redox_syscall" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" +dependencies = [ + "bitflags", +] + [[package]] name = "regex" -version = "1.7.1" +version = "1.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48aaa5748ba571fb95cd2c85c09f629215d3a6ece942baa100950af03a34f733" +checksum = "8b1f693b24f6ac912f4893ef08244d70b6067480d2f1a46e950c9691e6749d1d" dependencies = [ "aho-corasick", "memchr", @@ -2120,9 +2127,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.6.28" +version = "0.6.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848" +checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "rend" @@ -2135,9 +2142,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.11.14" +version = "0.11.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21eed90ec8570952d53b772ecf8f206aa1ec9a3d76b2521c56c42973f2d91ee9" +checksum = "27b71749df584b7f4cac2c426c127a7c785a5106cc98f7a8feb044115f0fa254" dependencies = [ "base64 0.21.0", "bytes", @@ -2187,9 +2194,9 @@ dependencies = [ [[package]] name = "rkyv" -version = "0.7.40" +version = "0.7.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c30f1d45d9aa61cbc8cd1eb87705470892289bb2d01943e7803b873a57404dc3" +checksum = "21499ed91807f07ae081880aabb2ccc0235e9d88011867d984525e9a4c3cfa3e" dependencies = [ "bytecheck", "hashbrown 0.12.3", @@ -2201,13 +2208,13 @@ dependencies = [ [[package]] name = "rkyv_derive" -version = "0.7.40" +version = "0.7.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff26ed6c7c4dfc2aa9480b86a60e3c7233543a270a680e10758a507c5a4ce476" +checksum = "ac1c672430eb41556291981f45ca900a0239ad007242d1cb4b4167af842db666" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.109", ] [[package]] @@ -2247,9 +2254,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.28.1" +version = "1.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13cf35f7140155d02ba4ec3294373d513a3c7baa8364c162b030e33c61520a8" +checksum = "26bd36b60561ee1fb5ec2817f198b6fd09fa571c897a5e86d1487cfc2b096dfc" dependencies = [ "arrayvec", "borsh", @@ -2265,9 +2272,9 @@ dependencies = [ [[package]] name = "rustc-demangle" -version = "0.1.21" +version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" +checksum = "d4a36c42d1873f9a77c53bde094f9664d9891bc604a45b4798fd2c389ed12e5b" [[package]] name = "rustc-hash" @@ -2286,16 +2293,16 @@ dependencies = [ [[package]] name = "rustix" -version = "0.36.9" +version = "0.37.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd5c6ff11fecd55b40746d1995a02f2eb375bf8c00d192d521ee09f42bef37bc" +checksum = "85597d61f83914ddeba6a47b3b8ffe7365107221c2e557ed94426489fefb5f77" dependencies = [ "bitflags", "errno", "io-lifetimes", "libc", "linux-raw-sys", - "windows-sys 0.45.0", + "windows-sys 0.48.0", ] [[package]] @@ -2408,15 +2415,15 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.16" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58bc9567378fc7690d6b2addae4e60ac2eeea07becb2c64b9f218b53865cba2a" +checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" [[package]] name = "serde" -version = "1.0.154" +version = "1.0.160" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cdd151213925e7f1ab45a9bbfb129316bd00799784b174b7cc7bcd16961c49e" +checksum = "bb2f3770c8bce3bcda7e149193a069a0f4365bda1fa5cd88e03bca26afc1216c" dependencies = [ "serde_derive", ] @@ -2442,20 +2449,20 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.154" +version = "1.0.160" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fc80d722935453bcafdc2c9a73cd6fac4dc1938f0346035d84bf99fa9e33217" +checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.14", ] [[package]] name = "serde_json" -version = "1.0.94" +version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c533a59c9d8a93a09c6ab31f0fd5e5f4dd1b8fc9434804029839884765d04ea" +checksum = "d721eca97ac802aa7777b701877c8004d950fc142651367300d21c1cc0194744" dependencies = [ "itoa", "ryu", @@ -2464,22 +2471,22 @@ dependencies = [ [[package]] name = "serde_path_to_error" -version = "0.1.10" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db0969fff533976baadd92e08b1d102c5a3d8a8049eadfd69d4d1e3c5b2ed189" +checksum = "f7f05c1d5476066defcdfacce1f52fc3cae3af1d3089727100c02ae92e5abbe0" dependencies = [ "serde", ] [[package]] name = "serde_repr" -version = "0.1.11" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "395627de918015623b32e7669714206363a7fc00382bf477e72c1f7533e8eafc" +checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.14", ] [[package]] @@ -2505,9 +2512,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "2.3.0" +version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ea48c9627169d206b35905699f513f513c303ab9d964a59b44fdcf66c1d1ab7" +checksum = "331bb8c3bf9b92457ab7abecf07078c13f7d270ba490103e84e8b014490cd0b0" dependencies = [ "base64 0.13.1", "chrono", @@ -2521,14 +2528,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "2.3.0" +version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e6b7e52858f9f06c25e1c566bbb4ab428200cb3b30053ea09dc50837de7538b" +checksum = "859011bddcc11f289f07f467cc1fe01c7a941daa4d8f6c40d4d1c92eb6d9319c" dependencies = [ "darling", "proc-macro2", "quote", - "syn", + "syn 1.0.109", ] [[package]] @@ -2638,6 +2645,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "2.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcf316d5356ed6847742d036f8a39c3b8435cac10bd528a4bd461928a6ab34d5" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "0.1.2" @@ -2652,15 +2670,15 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "tempfile" -version = "3.4.0" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af18f7ae1acd354b992402e9ec5864359d693cd8a79dcbef59f76891701c1e95" +checksum = "b9fbec84f381d5795b08656e4912bec604d162bff9291d6189a78f4c8ab87998" dependencies = [ "cfg-if", "fastrand", - "redox_syscall", + "redox_syscall 0.3.5", "rustix", - "windows-sys 0.42.0", + "windows-sys 0.45.0", ] [[package]] @@ -2674,28 +2692,28 @@ dependencies = [ [[package]] name = "termtree" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95059e91184749cb66be6dc994f67f182b6d897cb3df74a5bf66b5e709295fd8" +checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.39" +version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5ab016db510546d856297882807df8da66a16fb8c4101cb8b30054b0d5b2d9c" +checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.39" +version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5420d42e90af0c38c3290abcca25b9b3bdf379fc9f55c528f53a269d9c9a267e" +checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.14", ] [[package]] @@ -2753,14 +2771,13 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.26.0" +version = "1.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03201d01c3c27a29c8a5cee5b55a93ddae1ccf6f08f65365c2c918f8c1b76f64" +checksum = "d0de47a4eecbe11f498978a9b29d792f0d2692d1dd003650c24c76510e3bc001" dependencies = [ "autocfg", "bytes", "libc", - "memchr", "mio", "num_cpus", "pin-project-lite", @@ -2772,13 +2789,13 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "1.8.2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d266c00fde287f55d3f1c3e96c500c362a2b8c695076ec180f27918820bc6df8" +checksum = "61a573bdc87985e9d6ddeed1b3d864e8a302c847e40d647746df2f1de209d1ce" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.14", ] [[package]] @@ -2827,9 +2844,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7afcae9e3f0fe2c370fd4657108972cbb2fa9db1b9f84849cefd80741b01cb6" +checksum = "b403acf6f2bb0859c93c7f0d967cb4a75a7ac552100f9322faf64dc047669b21" dependencies = [ "serde", "serde_spanned", @@ -2848,9 +2865,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.19.4" +version = "0.19.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a1eb0622d28f4b9c90adc4ea4b2b46b47663fde9ac5fafcb14a1369d5508825" +checksum = "239410c8609e8125456927e6707163a3b1fdb40561e4b803bc041f466ccfdc13" dependencies = [ "indexmap", "serde", @@ -2898,7 +2915,7 @@ dependencies = [ "serde_with", "thiserror", "tokio", - "toml 0.7.2", + "toml 0.7.3", "torrust-tracker-configuration", "torrust-tracker-located-error", "torrust-tracker-primitives", @@ -2964,25 +2981,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "tower-http" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d1d42a9b3f3ec46ba828e8d376aec14592ea199f70a06a548587ecd1c4ab658" -dependencies = [ - "bitflags", - "bytes", - "futures-core", - "futures-util", - "http", - "http-body", - "http-range-header", - "pin-project-lite", - "tower", - "tower-layer", - "tower-service", -] - [[package]] name = "tower-layer" version = "0.3.2" @@ -3047,9 +3045,9 @@ checksum = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81" [[package]] name = "unicode-bidi" -version = "0.3.11" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524b68aca1d05e03fdf03fcdce2c6c94b6daf6d16861ddaa7e4f2b6638a9052c" +checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" [[package]] name = "unicode-ident" @@ -3091,9 +3089,9 @@ dependencies = [ [[package]] name = "uuid" -version = "1.3.0" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1674845326ee10d37ca60470760d4288a6f80f304007d92e5c53bab78c9cfd79" +checksum = "5b55a3fef2a1e3b3a00ce878640918820d3c51081576ac657d23af9fc7928fdb" dependencies = [ "getrandom", ] @@ -3153,7 +3151,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn", + "syn 1.0.109", "wasm-bindgen-shared", ] @@ -3187,7 +3185,7 @@ checksum = "2aff81306fcac3c7515ad4e177f521b5c9a15f2b08f4e32d823066102f35a5f6" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 1.0.109", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -3249,19 +3247,28 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +dependencies = [ + "windows-targets 0.48.0", +] + [[package]] name = "windows-sys" version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", ] [[package]] @@ -3270,71 +3277,137 @@ version = "0.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" dependencies = [ - "windows-targets", + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.0", ] [[package]] name = "windows-targets" -version = "0.42.1" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2522491fbfcd58cc84d47aeb2958948c4b8982e9a2d8a2a35bbaed431390e7" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", ] +[[package]] +name = "windows-targets" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" +dependencies = [ + "windows_aarch64_gnullvm 0.48.0", + "windows_aarch64_msvc 0.48.0", + "windows_i686_gnu 0.48.0", + "windows_i686_msvc 0.48.0", + "windows_x86_64_gnu 0.48.0", + "windows_x86_64_gnullvm 0.48.0", + "windows_x86_64_msvc 0.48.0", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + [[package]] name = "windows_aarch64_gnullvm" -version = "0.42.1" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c9864e83243fdec7fc9c5444389dcbbfd258f745e7853198f365e3c4968a608" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" [[package]] name = "windows_aarch64_msvc" -version = "0.42.1" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c8b1b673ffc16c47a9ff48570a9d85e25d265735c503681332589af6253c6c7" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" [[package]] name = "windows_i686_gnu" -version = "0.42.1" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de3887528ad530ba7bdbb1faa8275ec7a1155a45ffa57c37993960277145d640" +checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" [[package]] name = "windows_i686_msvc" -version = "0.42.1" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf4d1122317eddd6ff351aa852118a2418ad4214e6613a50e0191f7004372605" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" [[package]] name = "windows_x86_64_gnu" -version = "0.42.1" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1040f221285e17ebccbc2591ffdc2d44ee1f9186324dd3e84e99ac68d699c45" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" [[package]] name = "windows_x86_64_gnullvm" -version = "0.42.1" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "628bfdf232daa22b0d64fdb62b09fcc36bb01f05a3939e20ab73aaf9470d0463" +checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" [[package]] name = "windows_x86_64_msvc" -version = "0.42.1" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" [[package]] name = "winnow" -version = "0.3.5" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee7b2c67f962bf5042bfd8b6a916178df33a26eec343ae064cb8e069f638fa6f" +checksum = "ae8970b36c66498d8ff1d66685dc86b91b29db0c7739899012f63a63814b4b28" dependencies = [ "memchr", ] From 776d7d9801f4b57d4d0bac25f186134695594ca1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 12 Apr 2023 12:14:42 +0100 Subject: [PATCH 0006/1297] Create SECURITY.md --- SECURITY.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..b36d27978 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,27 @@ +# Security Policy + +Thanks for helping make Torrust Tracker safe for everyone. + +## Security + +[Torrust](https://github.com/torrust) takes the security of our software products and services seriously. + +## Reporting Security Issues + +If you believe you have found a security vulnerability in any of our repositories, please report it to us through coordinated disclosure. + +**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.** + +Instead, please send an email to info[@]nautilus-cyberneering.de. + +Please include as much of the information listed below as you can to help us better understand and resolve the issue: + +- The type of issue (e.g., buffer overflow, SQL injection, or cross-site scripting) +- Full paths of source file(s) related to the manifestation of the issue +- The location of the affected source code (tag/branch/commit or direct URL) +- Any special configuration required to reproduce the issue +- Step-by-step instructions to reproduce the issue +- Proof-of-concept or exploit code (if possible) +- Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. From f78638aa93384ba6f1674574001e210e2874289e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 12 Apr 2023 13:20:07 +0100 Subject: [PATCH 0007/1297] docs: [#279] crate docs for locate-error package --- packages/primitives/src/lib.rs | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index bcd48145f..e6f8cb93b 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -1,27 +1,47 @@ +//! Primitive types for [Torrust Tracker](https://docs.rs/torrust-tracker). +//! +//! This module contains the basic data structures for the [Torrust Tracker](https://docs.rs/torrust-tracker), +//! which is a `BitTorrent` tracker server. These structures are used not only +//! by the tracker server crate, but also by other crates in the Torrust +//! ecosystem. use serde::{Deserialize, Serialize}; -// TODO: Move to the database crate once that gets its own crate. +/// The database management system used by the tracker. +/// +/// Refer to: +/// +/// - [Torrust Tracker Configuration](https://docs.rs/torrust-tracker-configuration). +/// - [Torrust Tracker](https://docs.rs/torrust-tracker). +/// +/// For more information about persistence. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, derive_more::Display, Clone)] pub enum DatabaseDriver { + // TODO: Move to the database crate once that gets its own crate. + /// The Sqlite3 database driver. Sqlite3, + /// The MySQL database driver. MySQL, } +/// The mode the tracker will run in. +/// +/// Refer to [Torrust Tracker Configuration](https://docs.rs/torrust-tracker-configuration) +/// to know how to configure the tracker to run in each mode. #[derive(Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Debug)] pub enum TrackerMode { - // Will track every new info hash and serve every peer. + /// Will track every new info hash and serve every peer. #[serde(rename = "public")] Public, - // Will only track whitelisted info hashes. + /// Will only track whitelisted info hashes. #[serde(rename = "listed")] Listed, - // Will only serve authenticated peers + /// Will only serve authenticated peers #[serde(rename = "private")] Private, - // Will only track whitelisted info hashes and serve authenticated peers + /// Will only track whitelisted info hashes and serve authenticated peers #[serde(rename = "private_listed")] PrivateListed, } From 9e6e6085725e34762d176c08da07cff05cd58a60 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 12 Apr 2023 13:47:08 +0100 Subject: [PATCH 0008/1297] docs: [#280] crate docs for test-helpers package --- packages/test-helpers/src/configuration.rs | 23 ++++++++++++++++++++-- packages/test-helpers/src/lib.rs | 3 +++ packages/test-helpers/src/random.rs | 3 +++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 0b7a269ff..437475ee2 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -1,3 +1,4 @@ +//! Tracker configuration factories for testing. use std::env; use std::net::IpAddr; @@ -6,8 +7,17 @@ use torrust_tracker_primitives::TrackerMode; use crate::random; -/// 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. +/// 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. +/// +/// > **NOTICE**: This configuration is not meant to be used in production. +/// +/// > **NOTICE**: Port 0 is used for ephemeral ports, which means that the OS +/// will assign a random free port for the tracker to use. +/// +/// > **NOTICE**: You can change the log level to `debug` to see the logs of the +/// tracker while running the tests. That can be particularly useful when +/// debugging tests. /// /// # Panics /// @@ -46,6 +56,7 @@ pub fn ephemeral() -> Configuration { config } +/// Ephemeral configuration with reverse proxy enabled. #[must_use] pub fn ephemeral_with_reverse_proxy() -> Configuration { let mut cfg = ephemeral(); @@ -55,6 +66,7 @@ pub fn ephemeral_with_reverse_proxy() -> Configuration { cfg } +/// Ephemeral configuration with reverse proxy disabled. #[must_use] pub fn ephemeral_without_reverse_proxy() -> Configuration { let mut cfg = ephemeral(); @@ -64,6 +76,7 @@ pub fn ephemeral_without_reverse_proxy() -> Configuration { cfg } +/// Ephemeral configuration with `public` mode. #[must_use] pub fn ephemeral_mode_public() -> Configuration { let mut cfg = ephemeral(); @@ -73,6 +86,7 @@ pub fn ephemeral_mode_public() -> Configuration { cfg } +/// Ephemeral configuration with `private` mode. #[must_use] pub fn ephemeral_mode_private() -> Configuration { let mut cfg = ephemeral(); @@ -82,6 +96,7 @@ pub fn ephemeral_mode_private() -> Configuration { cfg } +/// Ephemeral configuration with `listed` mode. #[must_use] pub fn ephemeral_mode_whitelisted() -> Configuration { let mut cfg = ephemeral(); @@ -91,6 +106,7 @@ pub fn ephemeral_mode_whitelisted() -> Configuration { cfg } +/// Ephemeral configuration with `private_listed` mode. #[must_use] pub fn ephemeral_mode_private_whitelisted() -> Configuration { let mut cfg = ephemeral(); @@ -100,6 +116,7 @@ pub fn ephemeral_mode_private_whitelisted() -> Configuration { cfg } +/// Ephemeral configuration with a custom external (public) IP for the tracker. #[must_use] pub fn ephemeral_with_external_ip(ip: IpAddr) -> Configuration { let mut cfg = ephemeral(); @@ -109,6 +126,8 @@ pub fn ephemeral_with_external_ip(ip: IpAddr) -> Configuration { cfg } +/// Ephemeral configuration using a wildcard IPv6 for the UDP, HTTP and API +/// services. #[must_use] pub fn ephemeral_ipv6() -> Configuration { let mut cfg = ephemeral(); diff --git a/packages/test-helpers/src/lib.rs b/packages/test-helpers/src/lib.rs index e0f350131..e66ea2adc 100644 --- a/packages/test-helpers/src/lib.rs +++ b/packages/test-helpers/src/lib.rs @@ -1,2 +1,5 @@ +//! Testing helpers for [Torrust Tracker](https://docs.rs/torrust-tracker). +//! +//! A collection of functions and types to help with testing the tracker server. pub mod configuration; pub mod random; diff --git a/packages/test-helpers/src/random.rs b/packages/test-helpers/src/random.rs index ffb2ccd6f..2133dcd29 100644 --- a/packages/test-helpers/src/random.rs +++ b/packages/test-helpers/src/random.rs @@ -1,7 +1,10 @@ +//! Random data generators for testing. use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; /// Returns a random alphanumeric string of a certain size. +/// +/// It is useful for generating random names, IDs, etc for testing. pub fn string(size: usize) -> String { thread_rng().sample_iter(&Alphanumeric).take(size).map(char::from).collect() } From f555e6888082386068bfd5f8eeb8d214f1105bf7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 12 Apr 2023 16:10:05 +0100 Subject: [PATCH 0009/1297] docs: update README --- README.md | 154 ++++++++++++++++++++++------------------------------ cSpell.json | 2 + 2 files changed, 68 insertions(+), 88 deletions(-) diff --git a/README.md b/README.md index 4e464dd68..5d74ef130 100644 --- a/README.md +++ b/README.md @@ -1,102 +1,80 @@ # Torrust Tracker -![Test](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml/badge.svg) - -## Project Description -Torrust Tracker is a lightweight but incredibly powerful and feature-rich BitTorrent tracker made using Rust. - - -### Features -* [X] Multiple UDP server and HTTP(S) server blocks for socket binding possible -* [X] Full IPv4 and IPv6 support for both UDP and HTTP(S) -* [X] Private & Whitelisted mode -* [X] Built-in API -* [X] Torrent whitelisting -* [X] Peer authentication using time-bound keys -* [X] newTrackon check supported for both HTTP, UDP, where IPv4 and IPv6 is properly handled -* [X] SQLite3 Persistent loading and saving of the torrent hashes and completed count -* [X] MySQL support added as engine option -* [X] Periodically saving added, interval can be configured - -### Implemented BEPs -* [BEP 3](https://www.bittorrent.org/beps/bep_0003.html): The BitTorrent Protocol -* [BEP 7](https://www.bittorrent.org/beps/bep_0007.html): IPv6 Support -* [BEP 15](http://www.bittorrent.org/beps/bep_0015.html): UDP Tracker Protocol for BitTorrent -* [BEP 23](http://bittorrent.org/beps/bep_0023.html): Tracker Returns Compact Peer Lists -* [BEP 27](http://bittorrent.org/beps/bep_0027.html): Private Torrents -* [BEP 41](http://bittorrent.org/beps/bep_0041.html): UDP Tracker Protocol Extensions -* [BEP 48](http://bittorrent.org/beps/bep_0048.html): Tracker Protocol Extension: Scrape + +[![Build & Release](https://github.com/torrust/torrust-tracker/actions/workflows/build_release.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/build_release.yml) [![CI](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml) [![Publish crate](https://github.com/torrust/torrust-tracker/actions/workflows/publish_crate.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/publish_crate.yml) [![Publish docker image](https://github.com/torrust/torrust-tracker/actions/workflows/publish_docker_image.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/publish_docker_image.yml) [![Test](https://github.com/torrust/torrust-tracker/actions/workflows/test.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test.yml) [![Test docker build](https://github.com/torrust/torrust-tracker/actions/workflows/test_docker.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test_docker.yml) [![Upload code coverage](https://github.com/torrust/torrust-tracker/actions/workflows/codecov.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/codecov.yml) + +Torrust Tracker is a lightweight but incredibly high-performance and feature-rich BitTorrent tracker written in [Rust](https://www.rust-lang.org/). + +It aims to provide a reliable and efficient solution for serving torrents to a vast number of peers while maintaining a high level of performance, robustness, extensibility, security, usability and with community-driven development. + +## Key Features + +* [X] Multiple UDP server and HTTP(S) server blocks for socket binding are possible. +* [X] Full IPv4 and IPv6 support for both UDP and HTTP(S). +* [X] Private & Whitelisted mode. +* [X] Built-in API. +* [X] Torrent whitelisting. +* [X] Peer authentication using time-bound keys. +* [X] [newTrackon](https://newtrackon.com/) check is supported for both HTTP and UDP, where IPv4 and IPv6 are properly handled. +* [X] SQLite3 and MySQL persistence, loading and saving of the torrent hashes and downloads completed count. +* [X] Comprehensive documentation. +* [X] A complete suite of tests. See [code coverage](https://app.codecov.io/gh/torrust/torrust-tracker) report. + +## Implemented BEPs + +* [BEP 3](https://www.bittorrent.org/beps/bep_0003.html): The BitTorrent Protocol. +* [BEP 7](https://www.bittorrent.org/beps/bep_0007.html): IPv6 Support. +* [BEP 15](http://www.bittorrent.org/beps/bep_0015.html): UDP Tracker Protocol for BitTorrent. +* [BEP 23](http://bittorrent.org/beps/bep_0023.html): Tracker Returns Compact Peer Lists. +* [BEP 27](http://bittorrent.org/beps/bep_0027.html): Private Torrents. +* [BEP 48](http://bittorrent.org/beps/bep_0048.html): Tracker Protocol Extension: Scrape. ## Getting Started -You can get the latest binaries from [releases](https://github.com/torrust/torrust-tracker/releases) or follow the install from scratch instructions below. -### Install From Scratch -1. Clone the repo. -```bash -git clone https://github.com/torrust/torrust-tracker.git -cd torrust-tracker -``` +Requirements: -2. Build the source code. -```bash -cargo build --release -``` +* Rust Stable `1.68` +* You might have problems compiling with a machine or docker container with low resources. It has been tested with docker containers with 6 CPUs, 7.5 GM of memory and 2GB of swap. + +You can follow the [documentation](https://docs.rs/torrust-tracker/) to install and use Torrust Tracker in different ways, but if you want to give it a quick try, you can use the following commands: -### Usage -* Run the torrust-tracker once to create the `config.toml` file: -```bash -./target/release/torrust-tracker +```s +git clone https://github.com/torrust/torrust-tracker.git \ + && cd torrust-tracker \ + && cargo build --release \ + && mkdir -p ./storage/database \ + && mkdir -p ./storage/ssl_certificates ``` +And then run `cargo run` twice. The first time to generate the `config.toml` file and the second time to run the tracker with the default configuration. -* Edit the newly created config.toml file according to your liking, see [configuration documentation](https://torrust.github.io/torrust-documentation/torrust-tracker/config/). Eg: -```toml -log_level = "info" -mode = "public" -db_driver = "Sqlite3" -db_path = "data.db" -announce_interval = 120 -min_announce_interval = 120 -max_peer_timeout = 900 -on_reverse_proxy = false -external_ip = "0.0.0.0" -tracker_usage_statistics = true -persistent_torrent_completed_stat = false -inactive_peer_cleanup_interval = 600 -remove_peerless_torrents = true - -[[udp_trackers]] -enabled = false -bind_address = "0.0.0.0:6969" - -[[http_trackers]] -enabled = true -bind_address = "0.0.0.0:7070" -ssl_enabled = false -ssl_cert_path = "" -ssl_key_path = "" - -[http_api] -enabled = true -bind_address = "127.0.0.1:1212" - -[http_api.access_tokens] -admin = "MyAccessToken" -``` +After running the tracker these services will be available: +* UDP tracker: `udp://127.0.0.1:6969/announce`. +* HTTP tracker: `http://127.0.0.1:6969/announce`. +* API: `http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken`. -* Run the torrust-tracker again: -```bash -./target/release/torrust-tracker -``` +## Documentation + +* [Crate documentation](https://docs.rs/torrust-tracker/). +* [API documentation](https://torrust.github.io/torrust-documentation/torrust-tracker/api/). + +## Contributing + +We welcome contributions from the community! + +How can you contribute? + +* Bug reports and feature requests. +* Code contributions. You can start by looking at the issues labeled ["good first issues"](https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). +* Documentation improvements. Check the [documentation](https://docs.rs/torrust-tracker/) and [API documentation](https://torrust.github.io/torrust-documentation/torrust-tracker/api/) for typos, errors, or missing information. +* Participation in the community. You can help by answering questions in the [discussions](https://github.com/torrust/torrust-tracker/discussions). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). -### Tracker URL -Your tracker announce URL will be **udp://{tracker-ip:port}** and/or **http://{tracker-ip:port}/announce** and/or **https://{tracker-ip:port}/announce** depending on your bindings. -In private & private_listed mode, tracker keys are added after the tracker URL like: **https://{tracker-ip:port}/announce/{key}**. +There is an ongoing discussion about the license of the project. You can follow the discussion [here](https://github.com/torrust/torrust-tracker/pull/251). -### Built-in API -Read the API documentation [here](https://torrust.github.io/torrust-documentation/torrust-tracker/api/). +## Acknowledgments -### Credits -This project was a joint effort by [Nautilus Cyberneering GmbH](https://nautilus-cyberneering.de/) and [Dutch Bits](https://dutchbits.nl). -Also thanks to [Naim A.](https://github.com/naim94a/udpt) and [greatest-ape](https://github.com/greatest-ape/aquatic) for some parts of the code. -Further added features and functions thanks to [Power2All](https://github.com/power2all). +This project was a joint effort by [Nautilus Cyberneering GmbH](https://nautilus-cyberneering.de/) and [Dutch Bits](https://dutchbits.nl). Also thanks to [Naim A.](https://github.com/naim94a/udpt) and [greatest-ape](https://github.com/greatest-ape/aquatic) for some parts of the code. Further added features and functions thanks to [Power2All](https://github.com/power2all). diff --git a/cSpell.json b/cSpell.json index f07e2bfb4..2fa80b58a 100644 --- a/cSpell.json +++ b/cSpell.json @@ -46,6 +46,7 @@ "mockall", "multimap", "myacicontext", + "Naim", "nanos", "nextest", "nocapture", @@ -79,6 +80,7 @@ "torrust", "torrustracker", "trackerid", + "Trackon", "typenum", "Unamed", "untuple", From 09da301d1612af8fff27d629fa59797bf182f937 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 13 Apr 2023 08:24:29 +0100 Subject: [PATCH 0010/1297] docs: [#295] add README to packages --- README.md | 6 +- packages/configuration/LICENSE | 661 +++++++++++++++++++++++++++++++ packages/configuration/README.md | 11 + packages/located-error/LICENSE | 661 +++++++++++++++++++++++++++++++ packages/located-error/README.md | 11 + packages/primitives/LICENSE | 661 +++++++++++++++++++++++++++++++ packages/primitives/README.md | 11 + packages/test-helpers/LICENSE | 661 +++++++++++++++++++++++++++++++ packages/test-helpers/README.md | 11 + 9 files changed, 2692 insertions(+), 2 deletions(-) create mode 100644 packages/configuration/LICENSE create mode 100644 packages/configuration/README.md create mode 100644 packages/located-error/LICENSE create mode 100644 packages/located-error/README.md create mode 100644 packages/primitives/LICENSE create mode 100644 packages/primitives/README.md create mode 100644 packages/test-helpers/LICENSE create mode 100644 packages/test-helpers/README.md diff --git a/README.md b/README.md index 5d74ef130..666868a87 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,9 @@ After running the tracker these services will be available: ## Documentation * [Crate documentation](https://docs.rs/torrust-tracker/). -* [API documentation](https://torrust.github.io/torrust-documentation/torrust-tracker/api/). +* [API `v1`](https://docs.rs/torrust-tracker/3.0.0-alpha.1/torrust_tracker/servers/apis/v1). +* [HTTP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.1/torrust_tracker/servers/http). +* [UDP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.1/torrust_tracker/servers/udp). ## Contributing @@ -66,7 +68,7 @@ How can you contribute? * Bug reports and feature requests. * Code contributions. You can start by looking at the issues labeled ["good first issues"](https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). -* Documentation improvements. Check the [documentation](https://docs.rs/torrust-tracker/) and [API documentation](https://torrust.github.io/torrust-documentation/torrust-tracker/api/) for typos, errors, or missing information. +* Documentation improvements. Check the [documentation](https://docs.rs/torrust-tracker/) and [API documentation](https://docs.rs/torrust-tracker/3.0.0-alpha.1/torrust_tracker/servers/apis/v1) for typos, errors, or missing information. * Participation in the community. You can help by answering questions in the [discussions](https://github.com/torrust/torrust-tracker/discussions). ## License diff --git a/packages/configuration/LICENSE b/packages/configuration/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/configuration/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/configuration/README.md b/packages/configuration/README.md new file mode 100644 index 000000000..ccae51d70 --- /dev/null +++ b/packages/configuration/README.md @@ -0,0 +1,11 @@ +# Torrust Tracker Configuration + +A library to provide configuration to the [Torrust Tracker](https://github.com/torrust/torrust-tracker). + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-configuration). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/located-error/LICENSE b/packages/located-error/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/located-error/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/located-error/README.md b/packages/located-error/README.md new file mode 100644 index 000000000..c3c18fa49 --- /dev/null +++ b/packages/located-error/README.md @@ -0,0 +1,11 @@ +# Torrust Tracker Located Error + +A library to provide an error decorator with the location and the source of the original error. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-located-error). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/primitives/LICENSE b/packages/primitives/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/primitives/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/primitives/README.md b/packages/primitives/README.md new file mode 100644 index 000000000..791955859 --- /dev/null +++ b/packages/primitives/README.md @@ -0,0 +1,11 @@ +# Torrust Tracker Primitives + +A library with the primitive types shared by the [Torrust Tracker](https://github.com/torrust/torrust-tracker) packages. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-primitives). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/test-helpers/LICENSE b/packages/test-helpers/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/test-helpers/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/test-helpers/README.md b/packages/test-helpers/README.md new file mode 100644 index 000000000..7389dce11 --- /dev/null +++ b/packages/test-helpers/README.md @@ -0,0 +1,11 @@ +# Torrust Tracker Configuration + +A library providing helpers for testing the [Torrust Tracker](https://github.com/torrust/torrust-tracker). + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-test-helpers). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). From aec3a4ce4967082a79036e9b147c82091d89b925 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 13 Apr 2023 09:04:32 +0100 Subject: [PATCH 0011/1297] chore(api)!: remove API endpoint without version prefix BREAKING CHANGE: API endpoints without version prefixes are no longer available. For example, `/api/stats` use `/api/v1/stats` instead. --- src/servers/apis/v1/routes.rs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs index 7b792f8a8..74778ca14 100644 --- a/src/servers/apis/v1/routes.rs +++ b/src/servers/apis/v1/routes.rs @@ -7,21 +7,7 @@ use super::context::{auth_key, stats, torrent, whitelist}; use crate::tracker::Tracker; /// Add the routes for the v1 API. -/// -/// > **NOTICE**: the old API endpoints without `v1` prefix are kept for -/// backward compatibility. For example, the `GET /api/stats` endpoint is -/// still available, but it is deprecated and will be removed in the future. -/// You should use the `GET /api/v1/stats` endpoint instead. pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { - // Without `v1` prefix. - // We keep the old API endpoints without `v1` prefix for backward compatibility. - // todo: remove when the torrust index backend is using the `v1` prefix. - let router = auth_key::routes::add(prefix, router, tracker.clone()); - let router = stats::routes::add(prefix, router, tracker.clone()); - let router = whitelist::routes::add(prefix, router, tracker.clone()); - let router = torrent::routes::add(prefix, router, tracker.clone()); - - // With `v1` prefix let v1_prefix = format!("{prefix}/v1"); let router = auth_key::routes::add(&v1_prefix, router, tracker.clone()); let router = stats::routes::add(&v1_prefix, router, tracker.clone()); From feaa1737b29336fc8348cd5cc238d53c69d98ec6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 13 Apr 2023 10:27:33 +0100 Subject: [PATCH 0012/1297] fix: test for configuration Fields were reorganized and package test were not being executed on the CI. --- packages/configuration/src/lib.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 6b051b572..e48355757 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -557,10 +557,14 @@ impl Configuration { /// permission to read it. Will also return `Err` if the configuration is /// not valid or cannot be encoded to TOML. pub fn save_to_file(&self, path: &str) -> Result<(), Error> { - let toml_string = toml::to_string(self).expect("Could not encode TOML value"); - fs::write(path, toml_string).expect("Could not write to file!"); + fs::write(path, self.to_toml()).expect("Could not write to file!"); Ok(()) } + + /// Encodes the configuration to TOML. + fn to_toml(&self) -> String { + toml::to_string(self).expect("Could not encode TOML value") + } } #[cfg(test)] @@ -575,11 +579,11 @@ mod tests { db_path = "./storage/database/data.db" announce_interval = 120 min_announce_interval = 120 - max_peer_timeout = 900 on_reverse_proxy = false external_ip = "0.0.0.0" tracker_usage_statistics = true persistent_torrent_completed_stat = false + max_peer_timeout = 900 inactive_peer_cleanup_interval = 600 remove_peerless_torrents = true From a933a6929c9ebb67bf1abd7372840be1216a2267 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 13 Apr 2023 10:28:45 +0100 Subject: [PATCH 0013/1297] ci: run tests for workspace packages Test for packages were not being executed. We need to add the `--workpspace` option: ``` cargo test --workspace ``` --- .github/workflows/test_build_release.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test_build_release.yml b/.github/workflows/test_build_release.yml index d8c25bd56..f1bc295ce 100644 --- a/.github/workflows/test_build_release.yml +++ b/.github/workflows/test_build_release.yml @@ -36,9 +36,11 @@ jobs: run: cargo clippy --all-targets -- -D clippy::pedantic - name: Test Documentation run: cargo test --doc + - name: Run Tests + run: cargo test --workspace - uses: taiki-e/install-action@cargo-llvm-cov - uses: taiki-e/install-action@nextest - - name: Run Tests + - name: Show coverage run: cargo llvm-cov nextest build: From 823537e9c2e8d004de72fae208603e19f95a4ab8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 13 Apr 2023 10:45:40 +0100 Subject: [PATCH 0014/1297] fix: [#234] remove unused dependencies And move to `[dev-dependencies]` the ones that are only used for testing. --- Cargo.lock | 61 ++----------------------------- Cargo.toml | 2 - packages/configuration/Cargo.toml | 2 + packages/located-error/Cargo.toml | 3 ++ packages/test-helpers/Cargo.toml | 1 - 5 files changed, 8 insertions(+), 61 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d7053d618..ae256a5a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -448,7 +448,7 @@ dependencies = [ "rust-ini", "serde", "serde_json", - "toml 0.5.11", + "toml", "yaml-rust", ] @@ -1982,7 +1982,7 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785" dependencies = [ - "toml 0.5.11", + "toml", ] [[package]] @@ -2489,15 +2489,6 @@ dependencies = [ "syn 2.0.14", ] -[[package]] -name = "serde_spanned" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0efd8caf556a6cebd3b285caf480045fcc1ac04f6bd786b09a6f11af30c4fcf4" -dependencies = [ - "serde", -] - [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -2842,40 +2833,6 @@ dependencies = [ "serde", ] -[[package]] -name = "toml" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b403acf6f2bb0859c93c7f0d967cb4a75a7ac552100f9322faf64dc047669b21" -dependencies = [ - "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", -] - -[[package]] -name = "toml_datetime" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622" -dependencies = [ - "serde", -] - -[[package]] -name = "toml_edit" -version = "0.19.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "239410c8609e8125456927e6707163a3b1fdb40561e4b803bc041f466ccfdc13" -dependencies = [ - "indexmap", - "serde", - "serde_spanned", - "toml_datetime", - "winnow", -] - [[package]] name = "torrust-tracker" version = "3.0.0-alpha.1" @@ -2892,7 +2849,6 @@ dependencies = [ "derive_more", "fern", "futures", - "hex", "hyper", "lazy_static", "local-ip-address", @@ -2915,7 +2871,6 @@ dependencies = [ "serde_with", "thiserror", "tokio", - "toml 0.7.3", "torrust-tracker-configuration", "torrust-tracker-located-error", "torrust-tracker-primitives", @@ -2932,7 +2887,7 @@ dependencies = [ "serde", "serde_with", "thiserror", - "toml 0.5.11", + "toml", "torrust-tracker-located-error", "torrust-tracker-primitives", "uuid", @@ -2960,7 +2915,6 @@ version = "3.0.0-alpha.1" dependencies = [ "lazy_static", "rand", - "tokio", "torrust-tracker-configuration", "torrust-tracker-primitives", ] @@ -3403,15 +3357,6 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" -[[package]] -name = "winnow" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae8970b36c66498d8ff1d66685dc86b91b29db0c7739899012f63a63814b4b28" -dependencies = [ - "memchr", -] - [[package]] name = "winreg" version = "0.10.1" diff --git a/Cargo.toml b/Cargo.toml index 4b6bcb323..13dd8d572 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,13 +18,11 @@ serde = { version = "1.0", features = ["derive"] } serde_bencode = "^0.2" serde_json = "1.0" serde_with = "2.0" -hex = "0.4" percent-encoding = "2.2" binascii = "0.1" lazy_static = "1.4" openssl = { version = "0.10", features = ["vendored"] } config = "0.13" -toml = "0.7" log = { version = "0.4", features = ["release_max_level_info"] } fern = "0.6" chrono = "0.4" diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index aade6272d..36fb6d665 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -15,4 +15,6 @@ log = { version = "0.4", features = ["release_max_level_info"] } thiserror = "1.0" torrust-tracker-primitives = { version = "3.0.0-alpha.1", path = "../primitives" } torrust-tracker-located-error = { version = "3.0.0-alpha.1", path = "../located-error" } + +[dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index f67ef340f..acd13def3 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -8,4 +8,7 @@ edition.workspace = true [dependencies] log = { version = "0.4", features = ["release_max_level_info"] } + +[dev-dependencies] thiserror = "1.0" + diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 4483f8f4d..2f876470b 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -7,7 +7,6 @@ authors.workspace = true edition.workspace = true [dependencies] -tokio = { version = "1", features = ["rt-multi-thread", "net", "sync", "macros", "signal"] } lazy_static = "1.4" rand = "0.8.5" torrust-tracker-configuration = { version = "3.0.0-alpha.1", path = "../configuration"} From 09e97a1e9a7184c3bf2f10fde1ed47ec9861b6c4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 13 Apr 2023 11:30:33 +0100 Subject: [PATCH 0015/1297] feat: [#267] remove always restart configutation for MySQL from docker compose Since the configuration is intended for development, it does not make sense. --- compose.yaml | 1 - docker/README.md | 17 ++++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/compose.yaml b/compose.yaml index d11f9c8ae..49f3055a8 100644 --- a/compose.yaml +++ b/compose.yaml @@ -22,7 +22,6 @@ services: mysql: image: mysql:8.0 command: '--default-authentication-plugin=mysql_native_password' - restart: always healthcheck: test: ['CMD-SHELL', 'mysqladmin ping -h 127.0.0.1 --password="$$(cat /run/secrets/db-password)" --silent'] interval: 3s diff --git a/docker/README.md b/docker/README.md index e5b4dfe74..e0fee61e7 100644 --- a/docker/README.md +++ b/docker/README.md @@ -19,6 +19,17 @@ storage/ ## Dev environment +When using docker you have to bind the exposed ports to the wildcard address `0.0.0.0`, so you can access the application from the host machine. + +The default API configuration uses `127.0.0.1`, so you have to change it to: + +```toml +[http_api] +bind_address = "0.0.0.0:1212" +``` + +Otherwise the API will be only accessible from inside the container. + ### With docker Build and run locally: @@ -78,7 +89,7 @@ CONTAINER ID IMAGE COMMAND CREATED STATU And you should be able to use the application, for example making a request to the API: - + You can stop the containers with: @@ -169,7 +180,7 @@ ssl_key_path = "./storage/ssl_certificates/localhost.key" If you enable the SSL certificate for the API, for example, you can load the API with this URL: - + ## Prod environment @@ -232,7 +243,7 @@ CONTAINER ID IMAGE intelligent-hawking registry.hub.docker.com/torrust/tracker:latest Running 4.236.213.57:6969->6969/udp, 4.236.213.57:1212->1212/tcp ``` -After a while, you can use the tracker API `http://4.236.213.57:1212/api/stats?token=MyAccessToken` and the UDP tracker with your BitTorrent client using this tracker announce URL `udp://4.236.213.57:6969`. +After a while, you can use the tracker API `http://4.236.213.57:1212/api/v1/stats?token=MyAccessToken` and the UDP tracker with your BitTorrent client using this tracker announce URL `udp://4.236.213.57:6969`. > NOTES: > From 77a5e233d3cc7c70afb7bb1114baa9b413fa252f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 13 Apr 2023 13:35:26 +0100 Subject: [PATCH 0016/1297] chore(deps): [#297] update workflow actions --- .github/workflows/publish_docker_image.yml | 2 +- .github/workflows/test_build_release.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/publish_docker_image.yml b/.github/workflows/publish_docker_image.yml index 20152a727..1dd65e3a7 100644 --- a/.github/workflows/publish_docker_image.yml +++ b/.github/workflows/publish_docker_image.yml @@ -73,7 +73,7 @@ jobs: uses: docker/setup-buildx-action@v2 - name: Build and push - uses: docker/build-push-action@v3 + uses: docker/build-push-action@v4 with: context: . file: ./Dockerfile diff --git a/.github/workflows/test_build_release.yml b/.github/workflows/test_build_release.yml index f1bc295ce..88234b97a 100644 --- a/.github/workflows/test_build_release.yml +++ b/.github/workflows/test_build_release.yml @@ -61,7 +61,7 @@ jobs: - name: Build Torrust Tracker run: cargo build --release - name: Upload Build Artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 with: name: torrust-tracker path: ./target/release/torrust-tracker @@ -71,7 +71,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Download Build Artifact - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v3 with: name: torrust-tracker - name: Release From dfcc4b36356fc4dce87b74e35d8eabf3f1e5a741 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 13 Apr 2023 13:50:23 +0100 Subject: [PATCH 0017/1297] chore(deps): [#297] update cargo dependencies --- Cargo.lock | 70 +++++++++++++++++++++++++++---- Cargo.toml | 4 +- packages/configuration/Cargo.toml | 2 +- 3 files changed, 64 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ae256a5a9..995d051dd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -59,9 +59,9 @@ dependencies = [ [[package]] name = "aquatic_udp_protocol" -version = "0.2.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16149f27924d42b337a637cd90a8ee2a8973bbccf32aabebce2b3c66913f947f" +checksum = "b2919b480121f7d20d247524da62bad1b6b7928bc3f50898f624b5c592727341" dependencies = [ "byteorder", "either", @@ -448,7 +448,7 @@ dependencies = [ "rust-ini", "serde", "serde_json", - "toml", + "toml 0.5.11", "yaml-rust", ] @@ -1560,9 +1560,9 @@ dependencies = [ [[package]] name = "multimap" -version = "0.8.3" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" +checksum = "70db9248a93dc36a36d9a47898caa007a32755c7ad140ec64eeeb50d5a730631" dependencies = [ "serde", ] @@ -1982,7 +1982,7 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785" dependencies = [ - "toml", + "toml 0.5.11", ] [[package]] @@ -2460,9 +2460,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.95" +version = "1.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d721eca97ac802aa7777b701877c8004d950fc142651367300d21c1cc0194744" +checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" dependencies = [ "itoa", "ryu", @@ -2489,6 +2489,15 @@ dependencies = [ "syn 2.0.14", ] +[[package]] +name = "serde_spanned" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0efd8caf556a6cebd3b285caf480045fcc1ac04f6bd786b09a6f11af30c4fcf4" +dependencies = [ + "serde", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -2833,6 +2842,40 @@ dependencies = [ "serde", ] +[[package]] +name = "toml" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b403acf6f2bb0859c93c7f0d967cb4a75a7ac552100f9322faf64dc047669b21" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.19.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "239410c8609e8125456927e6707163a3b1fdb40561e4b803bc041f466ccfdc13" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "winnow", +] + [[package]] name = "torrust-tracker" version = "3.0.0-alpha.1" @@ -2887,7 +2930,7 @@ dependencies = [ "serde", "serde_with", "thiserror", - "toml", + "toml 0.7.3", "torrust-tracker-located-error", "torrust-tracker-primitives", "uuid", @@ -3357,6 +3400,15 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" +[[package]] +name = "winnow" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae8970b36c66498d8ff1d66685dc86b91b29db0c7739899012f63a63814b4b28" +dependencies = [ + "memchr", +] + [[package]] name = "winreg" version = "0.10.1" diff --git a/Cargo.toml b/Cargo.toml index 13dd8d572..f8a59bf4c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,7 +34,7 @@ derive_more = "0.99" thiserror = "1.0" futures = "0.3" async-trait = "0.1" -aquatic_udp_protocol = "0.2" +aquatic_udp_protocol = "0.8" uuid = { version = "1", features = ["v4"] } axum = "0.6.10" axum-server = { version = "0.4", features = ["tls-rustls"] } @@ -43,7 +43,7 @@ bip_bencode = "0.4" torrust-tracker-primitives = { version = "3.0.0-alpha.1", path = "packages/primitives" } torrust-tracker-configuration = { version = "3.0.0-alpha.1", path = "packages/configuration" } torrust-tracker-located-error = { version = "3.0.0-alpha.1", path = "packages/located-error" } -multimap = "0.8" +multimap = "0.9" hyper = "0.14" [dev-dependencies] diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 36fb6d665..8ad5aa3fb 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -10,7 +10,7 @@ edition.workspace = true serde = { version = "1.0", features = ["derive"] } serde_with = "2.0" config = "0.13" -toml = "0.5" +toml = "0.7" log = { version = "0.4", features = ["release_max_level_info"] } thiserror = "1.0" torrust-tracker-primitives = { version = "3.0.0-alpha.1", path = "../primitives" } From 5e2356effba1b24fe8a640b6b57b63efcab41886 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 13 Apr 2023 15:28:36 +0100 Subject: [PATCH 0018/1297] feat: release 3.0.0-alpha.2 --- Cargo.lock | 10 +++++----- Cargo.toml | 10 +++++----- README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- src/lib.rs | 4 ++-- 6 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 995d051dd..899e8855f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2878,7 +2878,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.1" +version = "3.0.0-alpha.2" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -2923,7 +2923,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.1" +version = "3.0.0-alpha.2" dependencies = [ "config", "log", @@ -2938,7 +2938,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.1" +version = "3.0.0-alpha.2" dependencies = [ "log", "thiserror", @@ -2946,7 +2946,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.1" +version = "3.0.0-alpha.2" dependencies = [ "derive_more", "serde", @@ -2954,7 +2954,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.1" +version = "3.0.0-alpha.2" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index f8a59bf4c..51c191275 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ version.workspace = true authors = ["Nautilus Cyberneering , Mick van Dijke "] edition = "2021" repository = "https://github.com/torrust/torrust-tracker" -version = "3.0.0-alpha.1" +version = "3.0.0-alpha.2" [dependencies] tokio = { version = "1.26", features = ["rt-multi-thread", "net", "sync", "macros", "signal"] } @@ -40,9 +40,9 @@ axum = "0.6.10" axum-server = { version = "0.4", features = ["tls-rustls"] } axum-client-ip = "0.4" bip_bencode = "0.4" -torrust-tracker-primitives = { version = "3.0.0-alpha.1", path = "packages/primitives" } -torrust-tracker-configuration = { version = "3.0.0-alpha.1", path = "packages/configuration" } -torrust-tracker-located-error = { version = "3.0.0-alpha.1", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.2", path = "packages/configuration" } +torrust-tracker-located-error = { version = "3.0.0-alpha.2", path = "packages/located-error" } multimap = "0.9" hyper = "0.14" @@ -53,7 +53,7 @@ serde_urlencoded = "0.7" serde_repr = "0.1" serde_bytes = "0.11" local-ip-address = "0.5" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.1", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.2", path = "packages/test-helpers" } [workspace] members = [ diff --git a/README.md b/README.md index 666868a87..c3d0a127b 100644 --- a/README.md +++ b/README.md @@ -56,9 +56,9 @@ After running the tracker these services will be available: ## Documentation * [Crate documentation](https://docs.rs/torrust-tracker/). -* [API `v1`](https://docs.rs/torrust-tracker/3.0.0-alpha.1/torrust_tracker/servers/apis/v1). -* [HTTP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.1/torrust_tracker/servers/http). -* [UDP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.1/torrust_tracker/servers/udp). +* [API `v1`](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/apis/v1). +* [HTTP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/http). +* [UDP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/udp). ## Contributing @@ -68,7 +68,7 @@ How can you contribute? * Bug reports and feature requests. * Code contributions. You can start by looking at the issues labeled ["good first issues"](https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). -* Documentation improvements. Check the [documentation](https://docs.rs/torrust-tracker/) and [API documentation](https://docs.rs/torrust-tracker/3.0.0-alpha.1/torrust_tracker/servers/apis/v1) for typos, errors, or missing information. +* Documentation improvements. Check the [documentation](https://docs.rs/torrust-tracker/) and [API documentation](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/apis/v1) for typos, errors, or missing information. * Participation in the community. You can help by answering questions in the [discussions](https://github.com/torrust/torrust-tracker/discussions). ## License diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 8ad5aa3fb..6f9e5cbc5 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -13,8 +13,8 @@ config = "0.13" toml = "0.7" log = { version = "0.4", features = ["release_max_level_info"] } thiserror = "1.0" -torrust-tracker-primitives = { version = "3.0.0-alpha.1", path = "../primitives" } -torrust-tracker-located-error = { version = "3.0.0-alpha.1", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.2", path = "../located-error" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 2f876470b..5d360d101 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -9,5 +9,5 @@ edition.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.1", path = "../configuration"} -torrust-tracker-primitives = { version = "3.0.0-alpha.1", path = "../primitives"} +torrust-tracker-configuration = { version = "3.0.0-alpha.2", path = "../configuration"} +torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "../primitives"} diff --git a/src/lib.rs b/src/lib.rs index adcf3d1f2..e219e59e3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -110,7 +110,7 @@ //! --publish 7070:7070/tcp \ //! --publish 1212:1212/tcp \ //! --volume "$(pwd)/storage":"/app/storage" \ -//! torrust/tracker:3.0.0-alpha.1 +//! torrust/tracker:3.0.0-alpha.2 //! ``` //! //! For more information about using docker visit the [tracker docker documentation](https://github.com/torrust/torrust-tracker/tree/develop/docker). @@ -162,7 +162,7 @@ //! //! The default configuration includes one disabled UDP server, one disabled HTTP server and the enabled API. //! -//! For more information about each service and options you can visit the documentation for the [torrust-tracker-configuration crate](https://docs.rs/torrust-tracker-configuration/3.0.0-alpha.1/torrust_tracker_configuration/). +//! For more information about each service and options you can visit the documentation for the [torrust-tracker-configuration crate](https://docs.rs/torrust-tracker-configuration). //! //! Alternatively to the `config.toml` file you can use one environment variable `TORRUST_TRACKER_CONFIG` to pass the configuration to the tracker: //! From a9042596bc3851f510efd39526c94e081ac65e4f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 13 Apr 2023 15:59:56 +0100 Subject: [PATCH 0019/1297] chore(deps): [#297] update workflow actions --- .github/workflows/test_docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test_docker.yml b/.github/workflows/test_docker.yml index 0c3fc36d8..a62965878 100644 --- a/.github/workflows/test_docker.yml +++ b/.github/workflows/test_docker.yml @@ -14,7 +14,7 @@ jobs: uses: docker/setup-buildx-action@v2 - name: Build docker image - uses: docker/build-push-action@v3 + uses: docker/build-push-action@v4 with: context: . file: ./Dockerfile From 494074189122d0421dd8033fa5b5f3ecedeec8fc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 13 Apr 2023 17:08:16 +0000 Subject: [PATCH 0020/1297] chore(deps): bump h2 from 0.3.16 to 0.3.17 Bumps [h2](https://github.com/hyperium/h2) from 0.3.16 to 0.3.17. - [Release notes](https://github.com/hyperium/h2/releases) - [Changelog](https://github.com/hyperium/h2/blob/master/CHANGELOG.md) - [Commits](https://github.com/hyperium/h2/compare/v0.3.16...v0.3.17) --- updated-dependencies: - dependency-name: h2 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 899e8855f..aedc11565 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1035,9 +1035,9 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "h2" -version = "0.3.16" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5be7b54589b581f624f566bf5d8eb2bab1db736c51528720b6bd36b96b55924d" +checksum = "66b91535aa35fea1523ad1b86cb6b53c28e0ae566ba4a460f4457e936cad7c6f" dependencies = [ "bytes", "fnv", From 70a9a9e6806610a809e893793c65f12342299e3b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Apr 2023 17:29:32 +0100 Subject: [PATCH 0021/1297] fix: [#306] fix CVE-2020-26235 vulnerability By removing the `chrono` package feature that was using the `time` pacakage version with the vulnerability. --- Cargo.lock | 28 ++++------------------------ Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aedc11565..ef26f1a5b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -394,12 +394,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e3c5919066adf22df73762e50cffcde3a758f2a848b113b586d1f86728b673b" dependencies = [ "iana-time-zone", - "js-sys", "num-integer", "num-traits", "serde", - "time 0.1.45", - "wasm-bindgen", "winapi", ] @@ -1018,7 +1015,7 @@ checksum = "c85e1d9ab2eadba7e5040d4e09cbd6d072b76a557ad64e797c2cb9d4da21d7e4" dependencies = [ "cfg-if", "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi", ] [[package]] @@ -1527,7 +1524,7 @@ checksum = "5b9d9a46eff5b4ff64b45a9e316a6d1e0bc719ef429cbec4dc630684212bfdf9" dependencies = [ "libc", "log", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi", "windows-sys 0.45.0", ] @@ -1626,7 +1623,7 @@ dependencies = [ "smallvec", "subprocess", "thiserror", - "time 0.3.20", + "time", "uuid", ] @@ -2523,7 +2520,7 @@ dependencies = [ "serde", "serde_json", "serde_with_macros", - "time 0.3.20", + "time", ] [[package]] @@ -2716,17 +2713,6 @@ dependencies = [ "syn 2.0.14", ] -[[package]] -name = "time" -version = "0.1.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" -dependencies = [ - "libc", - "wasi 0.10.0+wasi-snapshot-preview1", - "winapi", -] - [[package]] name = "time" version = "0.3.20" @@ -3115,12 +3101,6 @@ dependencies = [ "try-lock", ] -[[package]] -name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" - [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" diff --git a/Cargo.toml b/Cargo.toml index 51c191275..9dba4d515 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,7 +25,7 @@ openssl = { version = "0.10", features = ["vendored"] } config = "0.13" log = { version = "0.4", features = ["release_max_level_info"] } fern = "0.6" -chrono = "0.4" +chrono = { version = "0.4.24", default-features = false, features = ["clock"] } r2d2 = "0.8" r2d2_mysql = "23.0" r2d2_sqlite = { version = "0.21", features = ["bundled"] } From 66bf35340553e67a79f8a7e03e8b212f47d5345a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 14 Apr 2023 20:04:37 +0000 Subject: [PATCH 0022/1297] chore(deps): bump hyper from 0.14.25 to 0.14.26 Bumps [hyper](https://github.com/hyperium/hyper) from 0.14.25 to 0.14.26. - [Release notes](https://github.com/hyperium/hyper/releases) - [Changelog](https://github.com/hyperium/hyper/blob/v0.14.26/CHANGELOG.md) - [Commits](https://github.com/hyperium/hyper/compare/v0.14.25...v0.14.26) --- updated-dependencies: - dependency-name: hyper dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ef26f1a5b..8c3f917b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1133,9 +1133,9 @@ checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" [[package]] name = "hyper" -version = "0.14.25" +version = "0.14.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc5e554ff619822309ffd57d8734d77cd5ce6238bc956f037ea06c58238c9899" +checksum = "ab302d72a6f11a3b910431ff93aae7e773078c769f0a3ef15fb9ec692ed147d4" dependencies = [ "bytes", "futures-channel", From fea35aec357f1b9cd6467122397feaf8f9fb4706 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 20 Apr 2023 23:19:11 +0200 Subject: [PATCH 0023/1297] clippy: add explict types to 'let_underscore_untyped' --- src/servers/apis/server.rs | 2 +- src/servers/udp/server.rs | 2 +- src/tracker/mod.rs | 4 ++-- src/tracker/peer.rs | 8 ++++---- src/tracker/torrent.rs | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 91821aa79..1e24e6655 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -124,7 +124,7 @@ impl ApiServer { .send(0) .map_err(|_| Error::Error("Task killer channel was closed.".to_string()))?; - let _ = self.state.task.await; + let _: Result<(), tokio::task::JoinError> = self.state.task.await; Ok(ApiServer { cfg: self.cfg, diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index a4f1faae8..6b4b18831 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -143,7 +143,7 @@ impl UdpServer { pub async fn stop(self) -> Result, Error> { self.state.stop_job_sender.send(1).map_err(|e| Error::Error(e.to_string()))?; - let _ = self.state.job.await; + let _: Result<(), tokio::task::JoinError> = self.state.job.await; let stopped_api_server: UdpServer = UdpServer { cfg: self.cfg, diff --git a/src/tracker/mod.rs b/src/tracker/mod.rs index 2cabd5a82..0d3263988 100644 --- a/src/tracker/mod.rs +++ b/src/tracker/mod.rs @@ -732,7 +732,7 @@ impl Tracker { // todo: move this action to a separate worker if self.config.persistent_torrent_completed_stat && stats_updated { - let _ = self + let _: Result<(), databases::error::Error> = self .database .save_persistent_torrent(info_hash, torrent_entry.completed) .await; @@ -1064,7 +1064,7 @@ impl Tracker { whitelist.clear(); for info_hash in whitelisted_torrents_from_database { - let _ = whitelist.insert(info_hash); + let _: bool = whitelist.insert(info_hash); } Ok(()) diff --git a/src/tracker/peer.rs b/src/tracker/peer.rs index a54346280..76747fea2 100644 --- a/src/tracker/peer.rs +++ b/src/tracker/peer.rs @@ -366,14 +366,14 @@ mod test { #[should_panic] fn should_fail_trying_to_instantiate_from_a_byte_slice_with_less_than_20_bytes() { let less_than_20_bytes = [0; 19]; - let _ = peer::Id::from_bytes(&less_than_20_bytes); + let _: peer::Id = peer::Id::from_bytes(&less_than_20_bytes); } #[test] #[should_panic] fn should_fail_trying_to_instantiate_from_a_byte_slice_with_more_than_20_bytes() { let more_than_20_bytes = [0; 21]; - let _ = peer::Id::from_bytes(&more_than_20_bytes); + let _: peer::Id = peer::Id::from_bytes(&more_than_20_bytes); } #[test] @@ -420,13 +420,13 @@ mod test { #[test] #[should_panic] fn should_fail_trying_to_convert_from_a_byte_vector_with_less_than_20_bytes() { - let _ = peer::Id::try_from([0; 19].to_vec()).unwrap(); + let _: peer::Id = peer::Id::try_from([0; 19].to_vec()).unwrap(); } #[test] #[should_panic] fn should_fail_trying_to_convert_from_a_byte_vector_with_more_than_20_bytes() { - let _ = peer::Id::try_from([0; 21].to_vec()).unwrap(); + let _: peer::Id = peer::Id::try_from([0; 21].to_vec()).unwrap(); } #[test] diff --git a/src/tracker/torrent.rs b/src/tracker/torrent.rs index 22deed2b4..4f7e28b6b 100644 --- a/src/tracker/torrent.rs +++ b/src/tracker/torrent.rs @@ -103,7 +103,7 @@ impl Entry { match peer.event { AnnounceEvent::Stopped => { - let _ = self.peers.remove(&peer.peer_id); + let _: Option = self.peers.remove(&peer.peer_id); } AnnounceEvent::Completed => { let peer_old = self.peers.insert(peer.peer_id, *peer); @@ -114,7 +114,7 @@ impl Entry { } } _ => { - let _ = self.peers.insert(peer.peer_id, *peer); + let _: Option = self.peers.insert(peer.peer_id, *peer); } } From 954f81d257e9e35c9947f6f9ebe7900b07c60968 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 19 Apr 2023 20:04:46 +0000 Subject: [PATCH 0024/1297] chore(deps): bump axum from 0.6.15 to 0.6.16 Bumps [axum](https://github.com/tokio-rs/axum) from 0.6.15 to 0.6.16. - [Release notes](https://github.com/tokio-rs/axum/releases) - [Changelog](https://github.com/tokio-rs/axum/blob/main/CHANGELOG.md) - [Commits](https://github.com/tokio-rs/axum/compare/axum-v0.6.15...axum-v0.6.16) --- updated-dependencies: - dependency-name: axum dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8c3f917b7..a9d8594d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -98,9 +98,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axum" -version = "0.6.15" +version = "0.6.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b32c5ea3aabaf4deb5f5ced2d688ec0844c881c9e6c696a8b769a05fc691e62" +checksum = "113713495a32dd0ab52baf5c10044725aa3aec00b31beda84218e469029b72a3" dependencies = [ "async-trait", "axum-core", diff --git a/Cargo.toml b/Cargo.toml index 9dba4d515..ffe97a8fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,7 +36,7 @@ futures = "0.3" async-trait = "0.1" aquatic_udp_protocol = "0.8" uuid = { version = "1", features = ["v4"] } -axum = "0.6.10" +axum = "0.6.16" axum-server = { version = "0.4", features = ["tls-rustls"] } axum-client-ip = "0.4" bip_bencode = "0.4" From c65f039e0dcfd796775eaf4404743197d6916b53 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 2 May 2023 09:47:39 +0100 Subject: [PATCH 0025/1297] docs: [#319] add system dependencies --- cSpell.json | 1 + src/lib.rs | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/cSpell.json b/cSpell.json index 2fa80b58a..a20812bdd 100644 --- a/cSpell.json +++ b/cSpell.json @@ -39,6 +39,7 @@ "lcov", "leecher", "leechers", + "libsqlite", "libtorrent", "Lphant", "metainfo", diff --git a/src/lib.rs b/src/lib.rs index e219e59e3..74005e339 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -68,6 +68,26 @@ //! //! ## Prerequisites //! +//! The tracker has some system dependencies: +//! +//! Since we are using the `openssl` crate with the [vendored feature](https://docs.rs/openssl/latest/openssl/#vendored), +//! enabled, you will need to install the following dependencies: +//! +//! ```text +//! sudo apt-get install pkg-config libssl-dev make +//! ``` +//! +//! If you are using `SQLite3` as database driver, you will need to install the +//! following dependency: +//! +//! ```text +//! sudo apt-get install libsqlite3-dev +//! ``` +//! +//! > **NOTICE**: those are the commands for `Ubuntu`. If you are using a +//! different OS, you will need to install the equivalent packages. Please +//! refer to the documentation of your OS. +//! //! With the default configuration you will need to create the `storage` directory: //! //! ```text From 1616ab0531a1dbb4c8912c18bc2a1780c4d9600f Mon Sep 17 00:00:00 2001 From: nyacat Date: Tue, 2 May 2023 11:43:24 +0100 Subject: [PATCH 0026/1297] docs: [#321] increase swap to avoid build errors @nyacat proposed a solution if you have problems building in a machine with low resources. I've added the solution to the docs. --- cSpell.json | 2 ++ src/lib.rs | 20 +++++++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/cSpell.json b/cSpell.json index a20812bdd..c935021c0 100644 --- a/cSpell.json +++ b/cSpell.json @@ -31,6 +31,7 @@ "hexlify", "hlocalhost", "Hydranode", + "Icelake", "incompletei", "infohash", "infohashes", @@ -90,6 +91,7 @@ "Vuze", "whitespaces", "XBTT", + "Xeon", "Xtorrent", "Xunlei", "xxxxxxxxxxxxxxxxxxxxd", diff --git a/src/lib.rs b/src/lib.rs index 74005e339..744642a3f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -64,7 +64,25 @@ //! ## Minimum requirements //! //! - Rust Stable `1.68` -//! - You might have problems compiling with a machine with low resources. Or with low resources limits on docker containers. It has been tested with docker containers with 6 CPUs, 7.5 GM of memory and 2GB of swap. +//! - You might have problems compiling with a machine with low resources. +//! +//! It has been tested with: +//! +//! Docker containers with: +//! +//! - 6 CPUs +//! - 7.5G of ram +//! - 2GB of swap +//! +//! [VM](https://github.com/torrust/torrust-tracker/issues/321) with: +//! +//! - 1 core of Intel Xeon Processor (Icelake) +//! - 1G of ram +//! - 25G of disk +//! - Debian 11 +//! - no swap by default +//! +//! Adding swap may help with compilation. See issue [#321](https://github.com/torrust/torrust-tracker/issues/321). //! //! ## Prerequisites //! From 7b0b9269890312e2dbcfcbafaa1cbae0ff91586f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 6 Jul 2023 15:56:24 +0100 Subject: [PATCH 0027/1297] fix: udpate dependencies Getting this error: ``` Compiling ident_case v1.0.1 Compiling ppv-lite86 v0.2.17 error[E0635]: unknown feature `proc_macro_span_shrink` --> /home/josecelano/.cargo/registry/src/index.crates.io-6f17d22bba15001f/proc-macro2-1.0.56/src/lib.rs:92:30 | 92 | feature(proc_macro_span, proc_macro_span_shrink) | ``` Compiling with: - rustup 1.26.0 (5af9b9484 2023-04-05) - rustc 1.72.0-nightly (839e9a6e1 2023-07-02) --- Cargo.lock | 863 ++++++++++++++++++++++------------------------------- Cargo.toml | 2 +- 2 files changed, 360 insertions(+), 505 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a9d8594d4..5e880459a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "addr2line" -version = "0.19.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a76fd60b23679b7d19bd066031410fb7e458ccc5e958eb5c325888ce4baedc97" +checksum = "f4fa78e18c64fce05e902adecd7a5eed15a5e0a3439f7b0e169f0252214865e3" dependencies = [ "gimli", ] @@ -41,13 +41,25 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "0.7.20" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac" +checksum = "43f6cb1bf222025340178f382c426f13757b2960e89779dfcb319c32542a5a41" dependencies = [ "memchr", ] +[[package]] +name = "allocator-api2" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56fc6cf8dc8c4158eed8649f9b8b0ea1518eb62b544fe9490d66fa0b349eafe9" + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + [[package]] name = "android_system_properties" version = "0.1.5" @@ -75,19 +87,19 @@ checksum = "bddcadddf5e9015d310179a59bb28c4d4b9920ad0f11e8e14dbadf654890c9a6" [[package]] name = "arrayvec" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" +checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "async-trait" -version = "0.1.68" +version = "0.1.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ccdd8f2a161be9bd5c023df56f1b2a0bd1d83872ae53b71a84a12c9bf6e842" +checksum = "a564d521dd56509c4c47480d00b80ee55f7e385ae48db5744c67ad50c92d2ebf" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.23", ] [[package]] @@ -98,9 +110,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axum" -version = "0.6.16" +version = "0.6.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "113713495a32dd0ab52baf5c10044725aa3aec00b31beda84218e469029b72a3" +checksum = "f8175979259124331c1d7bf6586ee7e0da434155e4b2d48ec2c8386281d8df39" dependencies = [ "async-trait", "axum-core", @@ -130,9 +142,9 @@ dependencies = [ [[package]] name = "axum-client-ip" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d719fabd6813392bbc10e1fe67f2977fad52791a836e51236f7e02f2482e017" +checksum = "df8e81eacc93f36480825da5f46a33b5fb2246ed024eacc9e8933425b80c5807" dependencies = [ "axum", "forwarded-header-value", @@ -178,9 +190,9 @@ dependencies = [ [[package]] name = "backtrace" -version = "0.3.67" +version = "0.3.68" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "233d376d6d185f2a3093e58f283f60f880315b6c60075b01f36b3b85154564ca" +checksum = "4319208da049c43661739c5fade2ba182f09d1dc2299b32298d3a31692b17e12" dependencies = [ "addr2line", "cc", @@ -199,15 +211,15 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "base64" -version = "0.21.0" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a" +checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" [[package]] name = "bigdecimal" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6aaf33151a6429fe9211d1b276eafdf70cdff28b071e76c0b0e1503221ea3744" +checksum = "a6773ddc0eafc0e509fb60e48dff7f450f8e674a0686ae8605e8d9901bd5eefa" dependencies = [ "num-bigint", "num-integer", @@ -328,15 +340,15 @@ checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" [[package]] name = "bumpalo" -version = "3.12.0" +version = "3.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535" +checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1" [[package]] name = "bytecheck" -version = "0.6.10" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13fe11640a23eb24562225322cd3e452b93a3d4091d62fab69c70542fcd17d1f" +checksum = "8b6372023ac861f6e6dc89c8344a8f398fb42aaba2b5dbc649ca0c0e9dbcb627" dependencies = [ "bytecheck_derive", "ptr_meta", @@ -345,9 +357,9 @@ dependencies = [ [[package]] name = "bytecheck_derive" -version = "0.6.10" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31225543cb46f81a7e224762764f4a6a0f097b1db0b175f69e8065efaa42de5" +checksum = "a7ec4c6f261935ad534c0c22dbef2201b45918860eb1c574b972bd213a76af61" dependencies = [ "proc-macro2", "quote", @@ -389,12 +401,12 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.24" +version = "0.4.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e3c5919066adf22df73762e50cffcde3a758f2a848b113b586d1f86728b673b" +checksum = "ec837a71355b28f6556dbd569b37b3f363091c0bd4b2e735674521b4c5fd9bc5" dependencies = [ + "android-tzdata", "iana-time-zone", - "num-integer", "num-traits", "serde", "winapi", @@ -420,16 +432,6 @@ dependencies = [ "cc", ] -[[package]] -name = "codespan-reporting" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" -dependencies = [ - "termcolor", - "unicode-width", -] - [[package]] name = "config" version = "0.13.3" @@ -473,9 +475,9 @@ checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" [[package]] name = "cpufeatures" -version = "0.2.6" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "280a9f2d8b3a38871a3c8a46fb80db65e5e5ed97da80c4d08bf27fb63e35e181" +checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" dependencies = [ "libc", ] @@ -526,9 +528,9 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.14" +version = "0.9.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46bd5f3f85273295a9d14aedfb86f6aadbff6d8f5295c4a9edb08e819dcf5695" +checksum = "ae211234986c545741a7dc064309f67ee1e5ad243d0e48335adc0484d960bcc7" dependencies = [ "autocfg", "cfg-if", @@ -549,9 +551,9 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.15" +version = "0.8.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b" +checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" dependencies = [ "cfg-if", ] @@ -566,55 +568,11 @@ dependencies = [ "typenum", ] -[[package]] -name = "cxx" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f61f1b6389c3fe1c316bf8a4dccc90a38208354b330925bce1f74a6c4756eb93" -dependencies = [ - "cc", - "cxxbridge-flags", - "cxxbridge-macro", - "link-cplusplus", -] - -[[package]] -name = "cxx-build" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12cee708e8962df2aeb38f594aae5d827c022b6460ac71a7a3e2c3c2aae5a07b" -dependencies = [ - "cc", - "codespan-reporting", - "once_cell", - "proc-macro2", - "quote", - "scratch", - "syn 2.0.14", -] - -[[package]] -name = "cxxbridge-flags" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7944172ae7e4068c533afbb984114a56c46e9ccddda550499caa222902c7f7bb" - -[[package]] -name = "cxxbridge-macro" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2345488264226bf682893e25de0769f3360aac9957980ec49361b083ddaa5bc5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.14", -] - [[package]] name = "darling" -version = "0.14.4" +version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850" +checksum = "0558d22a7b463ed0241e993f76f09f30b126687447751a8638587b864e4b3944" dependencies = [ "darling_core", "darling_macro", @@ -622,27 +580,27 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.14.4" +version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0" +checksum = "ab8bfa2e259f8ee1ce5e97824a3c55ec4404a0d772ca7fa96bf19f0752a046eb" dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", "strsim", - "syn 1.0.109", + "syn 2.0.23", ] [[package]] name = "darling_macro" -version = "0.14.4" +version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" +checksum = "29a358ff9f12ec09c3e61fef9b5a9902623a695a46a917b07f269bff1445611a" dependencies = [ "darling_core", "quote", - "syn 1.0.109", + "syn 2.0.23", ] [[package]] @@ -660,13 +618,13 @@ dependencies = [ [[package]] name = "derive_utils" -version = "0.13.0" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff8f6a793f528719e1ad4425a52a213ac1214ac7158c5fb97a7f50a64bfc96d" +checksum = "20ce151e1b790e3e36d767ae57691240feafe8b605e1c2fe081183d64ac1bff3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.23", ] [[package]] @@ -677,9 +635,9 @@ checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" [[package]] name = "digest" -version = "0.10.6" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", @@ -712,6 +670,12 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "equivalent" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88bffebc5d80432c9b140ee17875ff173a8ab62faad5b257da912bd2f6c1c0a1" + [[package]] name = "errno" version = "0.3.1" @@ -720,7 +684,7 @@ checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" dependencies = [ "errno-dragonfly", "libc", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -774,9 +738,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.25" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841" +checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743" dependencies = [ "crc32fast", "libz-sys", @@ -815,9 +779,9 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] name = "form_urlencoded" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8" +checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" dependencies = [ "percent-encoding", ] @@ -840,9 +804,9 @@ checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" [[package]] name = "frunk" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89c703bf50009f383a0873845357cc400a95fc535f836feddfe015d7df6e1e0" +checksum = "11a351b59e12f97b4176ee78497dff72e4276fb1ceb13e19056aca7fa0206287" dependencies = [ "frunk_core", "frunk_derives", @@ -851,55 +815,43 @@ dependencies = [ [[package]] name = "frunk_core" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a446d01a558301dca28ef43222864a9fa2bd9a2e71370f769d5d5d5ec9f3537" +checksum = "af2469fab0bd07e64ccf0ad57a1438f63160c69b2e57f04a439653d68eb558d6" [[package]] name = "frunk_derives" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b83164912bb4c97cfe0772913c7af7387ee2e00cb6d4636fb65a35b3d0c8f173" +checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 1.0.109", + "syn 2.0.23", ] [[package]] name = "frunk_proc_macro_helpers" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "015425591bbeb0f5b8a75593340f1789af428e9f887a4f1e36c0c471f067ef50" +checksum = "35b54add839292b743aeda6ebedbd8b11e93404f902c56223e51b9ec18a13d2c" dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.23", ] [[package]] name = "frunk_proc_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea01524f285deab48affffb342b97f186e657b119c3f1821ac531780e0fbfae0" -dependencies = [ - "frunk_core", - "frunk_proc_macros_impl", - "proc-macro-hack", -] - -[[package]] -name = "frunk_proc_macros_impl" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a802d974cc18ee7fe1a7868fc9ce31086294fd96ba62f8da64ecb44e92a2653" +checksum = "71b85a1d4a9a6b300b41c05e8e13ef2feca03e0334127f29eca9506a7fe13a93" dependencies = [ "frunk_core", "frunk_proc_macro_helpers", - "proc-macro-hack", "quote", - "syn 1.0.109", + "syn 2.0.23", ] [[package]] @@ -964,7 +916,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.23", ] [[package]] @@ -1009,9 +961,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.9" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c85e1d9ab2eadba7e5040d4e09cbd6d072b76a557ad64e797c2cb9d4da21d7e4" +checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" dependencies = [ "cfg-if", "libc", @@ -1020,9 +972,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.27.2" +version = "0.27.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad0a93d233ebf96623465aad4046a8d3aa4da22d4f4beba5388838c8a434bbb4" +checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e" [[package]] name = "glob" @@ -1032,9 +984,9 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "h2" -version = "0.3.17" +version = "0.3.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66b91535aa35fea1523ad1b86cb6b53c28e0ae566ba4a460f4457e936cad7c6f" +checksum = "97ec8491ebaf99c8eaa73058b045fe58073cd6be7f596ac993ced0b0a0c01049" dependencies = [ "bytes", "fnv", @@ -1042,7 +994,7 @@ dependencies = [ "futures-sink", "futures-util", "http", - "indexmap", + "indexmap 1.9.3", "slab", "tokio", "tokio-util", @@ -1068,28 +1020,29 @@ dependencies = [ ] [[package]] -name = "hashlink" -version = "0.8.1" +name = "hashbrown" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69fe1fcf8b4278d860ad0548329f892a3631fb63f82574df68275f34cdbe0ffa" +checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" dependencies = [ - "hashbrown 0.12.3", + "ahash 0.8.3", + "allocator-api2", ] [[package]] -name = "hermit-abi" -version = "0.2.6" +name = "hashlink" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" +checksum = "312f66718a2d7789ffef4f4b7b213138ed9f1eb3aa1d0d82fc99f88fb3ffd26f" dependencies = [ - "libc", + "hashbrown 0.14.0", ] [[package]] name = "hermit-abi" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" +checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" [[package]] name = "hex" @@ -1133,9 +1086,9 @@ checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" [[package]] name = "hyper" -version = "0.14.26" +version = "0.14.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab302d72a6f11a3b910431ff93aae7e773078c769f0a3ef15fb9ec692ed147d4" +checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468" dependencies = [ "bytes", "futures-channel", @@ -1170,9 +1123,9 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.56" +version = "0.1.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0722cd7114b7de04316e7ea5456a0bbb20e4adb46fd27a3697adb812cff0f37c" +checksum = "2fad5b825842d2b38bd206f3e81d6957625fd7f0a361e345c30e01a0ae2dd613" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -1184,12 +1137,11 @@ dependencies = [ [[package]] name = "iana-time-zone-haiku" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" dependencies = [ - "cxx", - "cxx-build", + "cc", ] [[package]] @@ -1200,9 +1152,9 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "idna" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6" +checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" dependencies = [ "unicode-bidi", "unicode-normalization", @@ -1219,6 +1171,16 @@ dependencies = [ "serde", ] +[[package]] +name = "indexmap" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" +dependencies = [ + "equivalent", + "hashbrown 0.14.0", +] + [[package]] name = "instant" version = "0.1.12" @@ -1230,30 +1192,30 @@ dependencies = [ [[package]] name = "io-enum" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01c662c349c9c9f542e7bfd9134143beb27da4b20dfbc3b3ef5b2a5b507dafbd" +checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.14", + "syn 2.0.23", ] [[package]] name = "io-lifetimes" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c66c74d2ae7e79a5a8f7ac924adbe38ee42a859c6539ad869eb51f0b52dc220" +checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ - "hermit-abi 0.3.1", + "hermit-abi", "libc", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] name = "ipnet" -version = "2.7.2" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12b6ee2129af8d4fb011108c73d99a1b83a85977f23b82460c0ae2e25bb4b57f" +checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" [[package]] name = "itertools" @@ -1266,15 +1228,15 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.6" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" +checksum = "62b02a5381cc465bd3041d84623d0fa3b66738b52b8e2fc3bab8ad63ab032f4a" [[package]] name = "js-sys" -version = "0.3.61" +version = "0.3.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "445dde2150c55e483f3d8416706b97ec8e8237c307e5b7b4b8dd15e6af2a0730" +checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" dependencies = [ "wasm-bindgen", ] @@ -1377,9 +1339,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.141" +version = "0.2.147" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3304a64d199bb964be99741b7a14d26972741915b3649639149b2479bb46f4b5" +checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" [[package]] name = "libloading" @@ -1404,24 +1366,15 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.8" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9702761c3935f8cc2f101793272e202c72b99da8f4224a19ddcf1279a6450bbf" +checksum = "56ee889ecc9568871456d42f603d6a0ce59ff328d291063a45cbdf0036baf6db" dependencies = [ "cc", "pkg-config", "vcpkg", ] -[[package]] -name = "link-cplusplus" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5" -dependencies = [ - "cc", -] - [[package]] name = "linked-hash-map" version = "0.5.6" @@ -1430,27 +1383,27 @@ checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" [[package]] name = "linux-raw-sys" -version = "0.3.1" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d59d8c75012853d2e872fb56bc8a2e53718e2cafe1a4c823143141c6d90c322f" +checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" [[package]] name = "local-ip-address" -version = "0.5.1" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faa9d02443a1741e9f51dafdfcbffb3863b2a89c457d762b40337d6c5153ef81" +checksum = "2815836665de176ba66deaa449ada98fdf208d84730d1a84a22cbeed6151a6fa" dependencies = [ "libc", "neli", "thiserror", - "windows-sys 0.42.0", + "windows-sys", ] [[package]] name = "lock_api" -version = "0.4.9" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" +checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16" dependencies = [ "autocfg", "scopeguard", @@ -1458,12 +1411,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.17" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" -dependencies = [ - "cfg-if", -] +checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4" [[package]] name = "lru" @@ -1488,9 +1438,9 @@ checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" [[package]] name = "memoffset" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1" +checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" dependencies = [ "autocfg", ] @@ -1509,23 +1459,22 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.6.2" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa" +checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" dependencies = [ "adler", ] [[package]] name = "mio" -version = "0.8.6" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b9d9a46eff5b4ff64b45a9e316a6d1e0bc719ef429cbec4dc630684212bfdf9" +checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2" dependencies = [ "libc", - "log", "wasi", - "windows-sys 0.45.0", + "windows-sys", ] [[package]] @@ -1656,12 +1605,27 @@ dependencies = [ [[package]] name = "neli" -version = "0.5.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9053554eb5dcb7e10d9cdab1206965bde870eed5d0d341532ca035e3ba221508" +checksum = "1100229e06604150b3becd61a4965d5c70f3be1759544ea7274166f4be41ef43" dependencies = [ "byteorder", "libc", + "log", + "neli-proc-macros", +] + +[[package]] +name = "neli-proc-macros" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c168194d373b1e134786274020dae7fc5513d565ea2ebb9bc9ff17ffb69106d4" +dependencies = [ + "either", + "proc-macro2", + "quote", + "serde", + "syn 1.0.109", ] [[package]] @@ -1718,34 +1682,34 @@ dependencies = [ [[package]] name = "num_cpus" -version = "1.15.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ - "hermit-abi 0.2.6", + "hermit-abi", "libc", ] [[package]] name = "object" -version = "0.30.3" +version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea86265d3d3dcb6a27fc51bd29a4bf387fae9d2986b823079d4986af253eb439" +checksum = "8bda667d9f2b5051b8833f59f3bf748b28ef54f850f4fcb389a252aa383866d1" dependencies = [ "memchr", ] [[package]] name = "once_cell" -version = "1.17.1" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" +checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" [[package]] name = "openssl" -version = "0.10.50" +version = "0.10.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e30d8bc91859781f0a943411186324d580f2bbeb71b452fe91ae344806af3f1" +checksum = "345df152bc43501c5eb9e4654ff05f794effb78d4efe3d53abc158baddc0703d" dependencies = [ "bitflags", "cfg-if", @@ -1764,7 +1728,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.23", ] [[package]] @@ -1775,18 +1739,18 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "111.25.2+1.1.1t" +version = "111.26.0+1.1.1u" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320708a054ad9b3bf314688b5db87cf4d6683d64cfc835e2337924ae62bf4431" +checksum = "efc62c9f12b22b8f5208c23a7200a442b2e5999f8bdf80233852122b5a4f6f37" dependencies = [ "cc", ] [[package]] name = "openssl-sys" -version = "0.9.85" +version = "0.9.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d3d193fb1488ad46ffe3aaabc912cc931d02ee8518fe2959aea8ef52718b0c0" +checksum = "374533b0e45f3a7ced10fcaeccca020e66656bc03dac384f852e4e5a7a8104a6" dependencies = [ "cc", "libc", @@ -1817,15 +1781,15 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.7" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" +checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.2.16", + "redox_syscall", "smallvec", - "windows-sys 0.45.0", + "windows-targets", ] [[package]] @@ -1851,15 +1815,15 @@ dependencies = [ [[package]] name = "percent-encoding" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" +checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" [[package]] name = "pest" -version = "2.5.7" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b1403e8401ad5dedea73c626b99758535b342502f8d1e361f4a2dd952749122" +checksum = "f73935e4d55e2abf7f130186537b19e7a4abc886a0252380b59248af473a3fc9" dependencies = [ "thiserror", "ucd-trie", @@ -1867,9 +1831,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.5.7" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be99c4c1d2fc2769b1d00239431d711d08f6efedcecb8b6e30707160aee99c15" +checksum = "aef623c9bbfa0eedf5a0efba11a5ee83209c326653ca31ff019bec3a95bfff2b" dependencies = [ "pest", "pest_generator", @@ -1877,22 +1841,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.5.7" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e56094789873daa36164de2e822b3888c6ae4b4f9da555a1103587658c805b1e" +checksum = "b3e8cba4ec22bada7fc55ffe51e2deb6a0e0db2d0b7ab0b103acc80d2510c190" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.23", ] [[package]] name = "pest_meta" -version = "2.5.7" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6733073c7cff3d8459fda0e42f13a047870242aed8b509fe98000928975f359e" +checksum = "a01f71cb40bd8bb94232df14b946909e14660e33fc05db3e50ae2a82d7ea0ca0" dependencies = [ "once_cell", "pest", @@ -1901,29 +1865,29 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.0.12" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad29a609b6bcd67fee905812e544992d216af9d755757c05ed2d0e15a74c6ecc" +checksum = "030ad2bc4db10a8944cb0d837f158bdfec4d4a4873ab701a95046770d11f8842" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.0.12" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55" +checksum = "ec2e072ecce94ec471b13398d5402c188e76ac03cf74dd1a975161b23a3f6d9c" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.23", ] [[package]] name = "pin-project-lite" -version = "0.2.9" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" +checksum = "4c40d25201921e5ff0c862a505c6557ea88568a4e3ace775ab55e93f2f4f9d57" [[package]] name = "pin-utils" @@ -1933,9 +1897,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pkg-config" -version = "0.3.26" +version = "0.3.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160" +checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" [[package]] name = "ppv-lite86" @@ -1982,17 +1946,11 @@ dependencies = [ "toml 0.5.11", ] -[[package]] -name = "proc-macro-hack" -version = "0.5.20+deprecated" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" - [[package]] name = "proc-macro2" -version = "1.0.56" +version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435" +checksum = "7b368fba921b0dce7e60f5e04ec15e565b3303972b42bcfde1d0713b881959eb" dependencies = [ "unicode-ident", ] @@ -2019,9 +1977,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.26" +version = "1.0.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" +checksum = "573015e8ab27661678357f27dc26460738fd2b6c86e46f386fde94cb5d913105" dependencies = [ "proc-macro2", ] @@ -2095,27 +2053,30 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.2.16" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" dependencies = [ "bitflags", ] [[package]] -name = "redox_syscall" -version = "0.3.5" +name = "regex" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" +checksum = "89089e897c013b3deb627116ae56a6955a72b8bed395c9526af31c9fe528b484" dependencies = [ - "bitflags", + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", ] [[package]] -name = "regex" -version = "1.7.3" +name = "regex-automata" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b1f693b24f6ac912f4893ef08244d70b6067480d2f1a46e950c9691e6749d1d" +checksum = "fa250384981ea14565685dea16a9ccc4d1c541a13f82b9c168572264d1df8c56" dependencies = [ "aho-corasick", "memchr", @@ -2124,9 +2085,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.6.29" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" +checksum = "2ab07dc67230e4a4718e70fd5c20055a4334b121f1f9db8fe63ef39ce9b8c846" [[package]] name = "rend" @@ -2139,11 +2100,11 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.11.16" +version = "0.11.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b71749df584b7f4cac2c426c127a7c785a5106cc98f7a8feb044115f0fa254" +checksum = "cde824a14b7c14f85caff81225f411faacc04a2013f41670f41443742b1c1c55" dependencies = [ - "base64 0.21.0", + "base64 0.21.2", "bytes", "encoding_rs", "futures-core", @@ -2191,23 +2152,26 @@ dependencies = [ [[package]] name = "rkyv" -version = "0.7.41" +version = "0.7.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21499ed91807f07ae081880aabb2ccc0235e9d88011867d984525e9a4c3cfa3e" +checksum = "0200c8230b013893c0b2d6213d6ec64ed2b9be2e0e016682b7224ff82cff5c58" dependencies = [ + "bitvec", "bytecheck", "hashbrown 0.12.3", "ptr_meta", "rend", "rkyv_derive", "seahash", + "tinyvec", + "uuid", ] [[package]] name = "rkyv_derive" -version = "0.7.41" +version = "0.7.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac1c672430eb41556291981f45ca900a0239ad007242d1cb4b4167af842db666" +checksum = "b2e06b915b5c230a17d7a736d1e2e63ee753c256a8614ef3f5147b13a4f5541d" dependencies = [ "proc-macro2", "quote", @@ -2251,9 +2215,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.29.1" +version = "1.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26bd36b60561ee1fb5ec2817f198b6fd09fa571c897a5e86d1487cfc2b096dfc" +checksum = "d0446843641c69436765a35a5a77088e28c2e6a12da93e84aa3ab1cd4aa5a042" dependencies = [ "arrayvec", "borsh", @@ -2269,9 +2233,9 @@ dependencies = [ [[package]] name = "rustc-demangle" -version = "0.1.22" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4a36c42d1873f9a77c53bde094f9664d9891bc604a45b4798fd2c389ed12e5b" +checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" [[package]] name = "rustc-hash" @@ -2290,16 +2254,16 @@ dependencies = [ [[package]] name = "rustix" -version = "0.37.11" +version = "0.37.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85597d61f83914ddeba6a47b3b8ffe7365107221c2e557ed94426489fefb5f77" +checksum = "4d69718bf81c6127a49dc64e44a742e8bb9213c0ff8869a22c308f84c1d4ab06" dependencies = [ "bitflags", "errno", "io-lifetimes", "libc", "linux-raw-sys", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -2316,24 +2280,24 @@ dependencies = [ [[package]] name = "rustls-pemfile" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b" +checksum = "2d3987094b1d07b653b7dfdc3f70ce9a1da9c51ac18c1b06b662e4f9a0e9f4b2" dependencies = [ - "base64 0.21.0", + "base64 0.21.2", ] [[package]] name = "rustversion" -version = "1.0.12" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f3208ce4d8448b3f3e7d168a73f5e0c43a61e32930de3bceeccedb388b6bf06" +checksum = "dc31bd9b61a32c31f9650d18add92aa83a49ba979c143eefd27fe7177b05bd5f" [[package]] name = "ryu" -version = "1.0.13" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041" +checksum = "fe232bdf6be8c8de797b22184ee71118d63780ea42ac85b61d1baa6d3b782ae9" [[package]] name = "saturating" @@ -2343,11 +2307,11 @@ checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" [[package]] name = "schannel" -version = "0.1.21" +version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3" +checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" dependencies = [ - "windows-sys 0.42.0", + "windows-sys", ] [[package]] @@ -2365,12 +2329,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" -[[package]] -name = "scratch" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1792db035ce95be60c3f8853017b3999209281c24e2ba5bc8e59bf97a0c590c1" - [[package]] name = "sct" version = "0.7.0" @@ -2389,9 +2347,9 @@ checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" [[package]] name = "security-framework" -version = "2.8.2" +version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a332be01508d814fed64bf28f798a146d73792121129962fdf335bb3c49a4254" +checksum = "1fc758eb7bffce5b308734e9b0c1468893cae9ff70ebf13e7090be8dcbcc83a8" dependencies = [ "bitflags", "core-foundation", @@ -2402,9 +2360,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.8.0" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31c9bb296072e961fcbd8853511dd39c2d8be2deb1e17c6860b1d30732b323b4" +checksum = "f51d0c0d83bec45f16480d0ce0058397a69e48fcdc52d1dc8855fb68acbd31a7" dependencies = [ "core-foundation-sys", "libc", @@ -2418,9 +2376,9 @@ checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" [[package]] name = "serde" -version = "1.0.160" +version = "1.0.166" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb2f3770c8bce3bcda7e149193a069a0f4365bda1fa5cd88e03bca26afc1216c" +checksum = "d01b7404f9d441d3ad40e6a636a7782c377d2abdbe4fa2440e2edcc2f4f10db8" dependencies = [ "serde_derive", ] @@ -2437,29 +2395,29 @@ dependencies = [ [[package]] name = "serde_bytes" -version = "0.11.9" +version = "0.11.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "416bda436f9aab92e02c8e10d49a15ddd339cea90b6e340fe51ed97abb548294" +checksum = "5a16be4fe5320ade08736447e3198294a5ea9a6d44dde6f35f0a5e06859c427a" dependencies = [ "serde", ] [[package]] name = "serde_derive" -version = "1.0.160" +version = "1.0.166" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df" +checksum = "5dd83d6dde2b6b2d466e14d9d1acce8816dedee94f735eac6395808b3483c6d6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.23", ] [[package]] name = "serde_json" -version = "1.0.96" +version = "1.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" +checksum = "0f1e14e89be7aa4c4b78bdbdc9eb5bf8517829a600ae8eaa39a6e1d960b5185c" dependencies = [ "itoa", "ryu", @@ -2468,29 +2426,30 @@ dependencies = [ [[package]] name = "serde_path_to_error" -version = "0.1.11" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7f05c1d5476066defcdfacce1f52fc3cae3af1d3089727100c02ae92e5abbe0" +checksum = "8acc4422959dd87a76cb117c191dcbffc20467f06c9100b76721dab370f24d3a" dependencies = [ + "itoa", "serde", ] [[package]] name = "serde_repr" -version = "0.1.12" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" +checksum = "1d89a8107374290037607734c0b73a85db7ed80cae314b3c5791f192a496e731" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.23", ] [[package]] name = "serde_spanned" -version = "0.6.1" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0efd8caf556a6cebd3b285caf480045fcc1ac04f6bd786b09a6f11af30c4fcf4" +checksum = "96426c9936fd7a0124915f9185ea1d20aa9445cc9821142f0a73bc9207a2e186" dependencies = [ "serde", ] @@ -2509,14 +2468,14 @@ dependencies = [ [[package]] name = "serde_with" -version = "2.3.2" +version = "2.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "331bb8c3bf9b92457ab7abecf07078c13f7d270ba490103e84e8b014490cd0b0" +checksum = "07ff71d2c147a7b57362cead5e22f772cd52f6ab31cfcd9edcd7f6aeb2a0afbe" dependencies = [ "base64 0.13.1", "chrono", "hex", - "indexmap", + "indexmap 1.9.3", "serde", "serde_json", "serde_with_macros", @@ -2525,14 +2484,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "2.3.2" +version = "2.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "859011bddcc11f289f07f467cc1fe01c7a941daa4d8f6c40d4d1c92eb6d9319c" +checksum = "881b6f881b17d13214e5d494c939ebab463d01264ce1811e9d4ac3a882e7695f" dependencies = [ "darling", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.23", ] [[package]] @@ -2548,9 +2507,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.10.6" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0" +checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8" dependencies = [ "cfg-if", "cpufeatures", @@ -2589,9 +2548,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" +checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9" [[package]] name = "socket2" @@ -2644,9 +2603,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.14" +version = "2.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcf316d5356ed6847742d036f8a39c3b8435cac10bd528a4bd461928a6ab34d5" +checksum = "59fb7d6d8281a51045d62b8eb3a7d1ce347b76f312af50cd3dc0af39c87c1737" dependencies = [ "proc-macro2", "quote", @@ -2667,24 +2626,16 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "tempfile" -version = "3.5.0" +version = "3.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9fbec84f381d5795b08656e4912bec604d162bff9291d6189a78f4c8ab87998" +checksum = "31c0432476357e58790aaa47a8efb0c5138f137343f3b5f23bd36a27e3b0a6d6" dependencies = [ + "autocfg", "cfg-if", "fastrand", - "redox_syscall 0.3.5", + "redox_syscall", "rustix", - "windows-sys 0.45.0", -] - -[[package]] -name = "termcolor" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" -dependencies = [ - "winapi-util", + "windows-sys", ] [[package]] @@ -2695,29 +2646,29 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.40" +version = "1.0.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" +checksum = "c16a64ba9387ef3fdae4f9c1a7f07a0997fce91985c0336f1ddc1822b3b37802" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.40" +version = "1.0.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" +checksum = "d14928354b01c4d6a4f0e549069adef399a284e7995c7ccca94e8a07a5346c59" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.23", ] [[package]] name = "time" -version = "0.3.20" +version = "0.3.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd0cbfecb4d19b5ea75bb31ad904eb5b9fa13f21079c3b92017ebdf4999a5890" +checksum = "ea9e1b3cf1243ae005d9e74085d4d542f3125458f3a81af210d901dcd7411efd" dependencies = [ "itoa", "serde", @@ -2727,15 +2678,15 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd" +checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb" [[package]] name = "time-macros" -version = "0.2.8" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd80a657e71da814b8e5d60d3374fc6d35045062245d80224748ae522dd76f36" +checksum = "372950940a5f07bf38dbe211d7283c9e6d7327df53794992d293e534c733d09b" dependencies = [ "time-core", ] @@ -2757,11 +2708,12 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.27.0" +version = "1.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0de47a4eecbe11f498978a9b29d792f0d2692d1dd003650c24c76510e3bc001" +checksum = "532826ff75199d5833b9d2c5fe410f29235e25704ee5f0ef599fb51c21f4a4da" dependencies = [ "autocfg", + "backtrace", "bytes", "libc", "mio", @@ -2770,18 +2722,18 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys 0.45.0", + "windows-sys", ] [[package]] name = "tokio-macros" -version = "2.0.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61a573bdc87985e9d6ddeed1b3d864e8a302c847e40d647746df2f1de209d1ce" +checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.23", ] [[package]] @@ -2807,9 +2759,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.7" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5427d89453009325de0d8f342c9490009f76e999cb7672d77e46267448f7e6b2" +checksum = "806fe8c2c87eccc8b3267cbae29ed3ab2d0bd37fca70ab622e46aaa9375ddb7d" dependencies = [ "bytes", "futures-core", @@ -2830,9 +2782,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.7.3" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b403acf6f2bb0859c93c7f0d967cb4a75a7ac552100f9322faf64dc047669b21" +checksum = "c17e963a819c331dcacd7ab957d80bc2b9a9c1e71c804826d2f283dd65306542" dependencies = [ "serde", "serde_spanned", @@ -2842,20 +2794,20 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.6.1" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.19.8" +version = "0.19.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "239410c8609e8125456927e6707163a3b1fdb40561e4b803bc041f466ccfdc13" +checksum = "c500344a19072298cd05a7224b3c0c629348b78692bf48466c5238656e315a78" dependencies = [ - "indexmap", + "indexmap 2.0.0", "serde", "serde_spanned", "toml_datetime", @@ -2916,7 +2868,7 @@ dependencies = [ "serde", "serde_with", "thiserror", - "toml 0.7.3", + "toml 0.7.6", "torrust-tracker-located-error", "torrust-tracker-primitives", "uuid", @@ -2990,9 +2942,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.30" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a" +checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" dependencies = [ "once_cell", ] @@ -3034,9 +2986,9 @@ checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" [[package]] name = "unicode-ident" -version = "1.0.8" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" +checksum = "22049a19f4a68748a168c0fc439f9516686aa045927ff767eca0a85101fb6e73" [[package]] name = "unicode-normalization" @@ -3047,12 +2999,6 @@ dependencies = [ "tinyvec", ] -[[package]] -name = "unicode-width" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" - [[package]] name = "untrusted" version = "0.7.1" @@ -3061,9 +3007,9 @@ checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" [[package]] name = "url" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643" +checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb" dependencies = [ "form_urlencoded", "idna", @@ -3072,9 +3018,9 @@ dependencies = [ [[package]] name = "uuid" -version = "1.3.1" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b55a3fef2a1e3b3a00ce878640918820d3c51081576ac657d23af9fc7928fdb" +checksum = "d023da39d1fde5a8a3fe1f3e01ca9632ada0a63e9797de55a879d6e2236277be" dependencies = [ "getrandom", ] @@ -3093,11 +3039,10 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "want" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" dependencies = [ - "log", "try-lock", ] @@ -3109,9 +3054,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31f8dcbc21f30d9b8f2ea926ecb58f6b91192c17e9d33594b3df58b2007ca53b" +checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -3119,24 +3064,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95ce90fd5bcc06af55a641a86428ee4229e44e07033963a2290a8e241607ccb9" +checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.23", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.34" +version = "0.4.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f219e0d211ba40266969f6dbdd90636da12f75bee4fc9d6c23d1260dadb51454" +checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" dependencies = [ "cfg-if", "js-sys", @@ -3146,9 +3091,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c21f77c0bedc37fd5dc21f897894a5ca01e7bb159884559461862ae90c0b4c5" +checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3156,28 +3101,28 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aff81306fcac3c7515ad4e177f521b5c9a15f2b08f4e32d823066102f35a5f6" +checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.23", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d" +checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" [[package]] name = "web-sys" -version = "0.3.61" +version = "0.3.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e33b99f4b23ba3eec1a53ac264e35a755f00e966e0065077d6027c0f575b0b97" +checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" dependencies = [ "js-sys", "wasm-bindgen", @@ -3209,15 +3154,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" -[[package]] -name = "winapi-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" -dependencies = [ - "winapi", -] - [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" @@ -3230,31 +3166,7 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" dependencies = [ - "windows-targets 0.48.0", -] - -[[package]] -name = "windows-sys" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets 0.42.2", + "windows-targets", ] [[package]] @@ -3263,117 +3175,60 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ - "windows-targets 0.48.0", + "windows-targets", ] [[package]] name = "windows-targets" -version = "0.42.2" +version = "0.48.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +checksum = "05d4b17490f70499f20b9e791dcf6a299785ce8af4d709018206dc5b4953e95f" dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] -[[package]] -name = "windows-targets" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" -dependencies = [ - "windows_aarch64_gnullvm 0.48.0", - "windows_aarch64_msvc 0.48.0", - "windows_i686_gnu 0.48.0", - "windows_i686_msvc 0.48.0", - "windows_x86_64_gnu 0.48.0", - "windows_x86_64_gnullvm 0.48.0", - "windows_x86_64_msvc 0.48.0", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" - [[package]] name = "windows_aarch64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" - [[package]] name = "windows_i686_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" -[[package]] -name = "windows_i686_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" - [[package]] name = "windows_i686_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" - [[package]] name = "windows_x86_64_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" - [[package]] name = "windows_x86_64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" - [[package]] name = "windows_x86_64_msvc" version = "0.48.0" @@ -3382,9 +3237,9 @@ checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" [[package]] name = "winnow" -version = "0.4.1" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae8970b36c66498d8ff1d66685dc86b91b29db0c7739899012f63a63814b4b28" +checksum = "ca0ace3845f0d96209f0375e6d367e3eb87eb65d27d445bdc9f1843a26f39448" dependencies = [ "memchr", ] diff --git a/Cargo.toml b/Cargo.toml index ffe97a8fd..a8dae6105 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ repository = "https://github.com/torrust/torrust-tracker" version = "3.0.0-alpha.2" [dependencies] -tokio = { version = "1.26", features = ["rt-multi-thread", "net", "sync", "macros", "signal"] } +tokio = { version = "1.29", features = ["rt-multi-thread", "net", "sync", "macros", "signal"] } serde = { version = "1.0", features = ["derive"] } serde_bencode = "^0.2" serde_json = "1.0" From b8d521347943d39bf93562e71b2aace2902eec28 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 6 Jul 2023 16:45:14 +0100 Subject: [PATCH 0028/1297] fix: clippy warnings --- packages/configuration/src/lib.rs | 4 ++++ src/servers/apis/server.rs | 12 ++++++++++++ src/servers/apis/v1/middlewares/auth.rs | 4 +++- src/servers/http/server.rs | 5 +++++ src/servers/http/v1/launcher.rs | 26 +++++++++++++++++++++++++ src/servers/signals.rs | 8 ++++++++ src/tracker/databases/driver.rs | 4 ++++ src/tracker/databases/mod.rs | 2 +- src/tracker/mod.rs | 2 +- src/tracker/services/torrent.rs | 2 +- 10 files changed, 65 insertions(+), 4 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index e48355757..f785aa976 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -556,6 +556,10 @@ impl Configuration { /// Will return `Err` if `filename` does not exist or the user does not have /// permission to read it. Will also return `Err` if the configuration is /// not valid or cannot be encoded to TOML. + /// + /// # Panics + /// + /// Will panic if the configuration cannot be written into the file. pub fn save_to_file(&self, path: &str) -> Result<(), Error> { fs::write(path, self.to_toml()).expect("Could not write to file!"); Ok(()) diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 1e24e6655..716a36c11 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -83,6 +83,10 @@ impl ApiServer { /// # Errors /// /// It would return an error if no `SocketAddr` is returned after launching the server. + /// + /// # Panics + /// + /// It would panic if the bound socket address cannot be sent back to this starter. pub async fn start(self, tracker: Arc) -> Result, Error> { let (shutdown_sender, shutdown_receiver) = tokio::sync::oneshot::channel::(); let (addr_sender, addr_receiver) = tokio::sync::oneshot::channel::(); @@ -229,6 +233,10 @@ impl Launcher { } /// Starts the API server with graceful shutdown on the current thread. +/// +/// # Panics +/// +/// It would panic if it fails to listen to shutdown signal. pub fn start(socket_addr: SocketAddr, tracker: Arc) -> impl Future> { let app = router(tracker); @@ -241,6 +249,10 @@ pub fn start(socket_addr: SocketAddr, tracker: Arc) -> impl Future( where B: Send, { - let Some(token) = params.token else { return AuthError::Unauthorized.into_response() }; + let Some(token) = params.token else { + return AuthError::Unauthorized.into_response(); + }; if !authenticate(&token, &config.http_api) { return AuthError::TokenNotValid.into_response(); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 6a46b81df..6007d212d 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -104,6 +104,11 @@ impl HttpServer> { /// # Errors /// /// It would return an error if no `SocketAddr` is returned after launching the server. + /// + /// # Panics + /// + /// It would panic spawned HTTP server launcher cannot send the bound `SocketAddr` + /// back to the main thread. pub async fn start(self, tracker: Arc) -> Result>, Error> { let (shutdown_sender, shutdown_receiver) = tokio::sync::oneshot::channel::(); let (addr_sender, addr_receiver) = tokio::sync::oneshot::channel::(); diff --git a/src/servers/http/v1/launcher.rs b/src/servers/http/v1/launcher.rs index 96dd1baac..b5faf8d46 100644 --- a/src/servers/http/v1/launcher.rs +++ b/src/servers/http/v1/launcher.rs @@ -22,6 +22,14 @@ pub enum Error { pub struct Launcher; impl Launcher { + /// It starts a new HTTP server instance from a TCP listener with graceful shutdown. + /// + /// # Panics + /// + /// Will panic if: + /// + /// - The TCP listener could not be bound. + /// - The Axum server crashes. pub fn start_from_tcp_listener_with_graceful_shutdown( tcp_listener: std::net::TcpListener, tracker: Arc, @@ -42,6 +50,14 @@ impl Launcher { }) } + /// It starts a new HTTPS server instance from a TCP listener with graceful shutdown. + /// + /// # Panics + /// + /// Will panic if: + /// + /// - The SSL certificate could not be read from the provided path or is invalid. + /// - The Axum server crashes. pub fn start_tls_from_tcp_listener_with_graceful_shutdown( tcp_listener: std::net::TcpListener, (ssl_cert_path, ssl_key_path): (String, String), @@ -114,6 +130,11 @@ impl HttpServerLauncher for Launcher { } } +/// Starts a new HTTP server instance. +/// +/// # Panics +/// +/// Panics if the server could not listen to shutdown (ctrl+c) signal. pub fn start(socket_addr: std::net::SocketAddr, tracker: Arc) -> impl Future> { let app = router(tracker); @@ -125,6 +146,11 @@ pub fn start(socket_addr: std::net::SocketAddr, tracker: Arc) -> impl F }) } +/// Starts a new HTTPS server instance. +/// +/// # Panics +/// +/// Panics if the server could not listen to shutdown (ctrl+c) signal. pub fn start_tls( socket_addr: std::net::SocketAddr, ssl_config: RustlsConfig, diff --git a/src/servers/signals.rs b/src/servers/signals.rs index f0312b886..d34cca108 100644 --- a/src/servers/signals.rs +++ b/src/servers/signals.rs @@ -2,6 +2,10 @@ use log::info; /// Resolves on `ctrl_c` or the `terminate` signal. +/// +/// # Panics +/// +/// Will panic if the `ctrl_c` or `terminate` signal resolves with an error. pub async fn global_shutdown_signal() { let ctrl_c = async { tokio::signal::ctrl_c().await.expect("failed to install Ctrl+C handler"); @@ -25,6 +29,10 @@ pub async fn global_shutdown_signal() { } /// Resolves when the `stop_receiver` or the `global_shutdown_signal()` resolves. +/// +/// # Panics +/// +/// Will panic if the `stop_receiver` resolves with an error. pub async fn shutdown_signal(stop_receiver: tokio::sync::oneshot::Receiver) { let stop = async { stop_receiver.await.expect("Failed to install stop signal.") }; diff --git a/src/tracker/databases/driver.rs b/src/tracker/databases/driver.rs index 7115bae8e..4ff9314d2 100644 --- a/src/tracker/databases/driver.rs +++ b/src/tracker/databases/driver.rs @@ -41,6 +41,10 @@ use super::{Builder, Database}; /// # Errors /// /// This function will return an error if unable to connect to the database. +/// +/// # Panics +/// +/// This function will panic if unable to create database tables. pub fn build(driver: &DatabaseDriver, db_path: &str) -> Result, Error> { let database = match driver { DatabaseDriver::Sqlite3 => Builder::::build(db_path), diff --git a/src/tracker/databases/mod.rs b/src/tracker/databases/mod.rs index 3b02415df..e0a26be23 100644 --- a/src/tracker/databases/mod.rs +++ b/src/tracker/databases/mod.rs @@ -56,7 +56,7 @@ use self::error::Error; use crate::shared::bit_torrent::info_hash::InfoHash; use crate::tracker::auth::{self, Key}; -pub(self) struct Builder +struct Builder where T: Database, { diff --git a/src/tracker/mod.rs b/src/tracker/mod.rs index 0d3263988..4d7d8d37e 100644 --- a/src/tracker/mod.rs +++ b/src/tracker/mod.rs @@ -794,7 +794,7 @@ impl Tracker { } }); } else { - for (_, torrent_entry) in torrents_lock.iter_mut() { + for torrent_entry in (*torrents_lock).values_mut() { torrent_entry.remove_inactive_peers(self.config.max_peer_timeout); } } diff --git a/src/tracker/services/torrent.rs b/src/tracker/services/torrent.rs index 3610d930c..0db044d07 100644 --- a/src/tracker/services/torrent.rs +++ b/src/tracker/services/torrent.rs @@ -99,7 +99,7 @@ pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Op let Some(torrent_entry) = torrent_entry_option else { return None; - }; + }; let (seeders, completed, leechers) = torrent_entry.get_stats(); From 61c5551e576d7ea32f431fedae7d689d64e08fa6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 6 Jul 2023 17:19:07 +0100 Subject: [PATCH 0029/1297] chore: udpate dependencies - axum: from 0.6.16 to 0.6.18 - acum-client-ip: from 0.4.0 to 0.4.1 - reqwest: from 0.11.16 to 0.11.18 --- Cargo.lock | 4 ++-- Cargo.toml | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5e880459a..9cf3cb302 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3237,9 +3237,9 @@ checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" [[package]] name = "winnow" -version = "0.4.7" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca0ace3845f0d96209f0375e6d367e3eb87eb65d27d445bdc9f1843a26f39448" +checksum = "a9482fe6ceabdf32f3966bfdd350ba69256a97c30253dc616fe0005af24f164e" dependencies = [ "memchr", ] diff --git a/Cargo.toml b/Cargo.toml index a8dae6105..fec8784d4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,9 +36,9 @@ futures = "0.3" async-trait = "0.1" aquatic_udp_protocol = "0.8" uuid = { version = "1", features = ["v4"] } -axum = "0.6.16" +axum = "0.6.18" axum-server = { version = "0.4", features = ["tls-rustls"] } -axum-client-ip = "0.4" +axum-client-ip = "0.4.1" bip_bencode = "0.4" torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "packages/primitives" } torrust-tracker-configuration = { version = "3.0.0-alpha.2", path = "packages/configuration" } @@ -48,7 +48,7 @@ hyper = "0.14" [dev-dependencies] mockall = "0.11" -reqwest = { version = "0.11", features = ["json"] } +reqwest = { version = "0.11.18", features = ["json"] } serde_urlencoded = "0.7" serde_repr = "0.1" serde_bytes = "0.11" From 0da0d23aaa65a23b00481fe1ef36012603dbf527 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Jul 2023 10:19:47 +0100 Subject: [PATCH 0030/1297] chore(deps): udpate dependencies - bump serde_with from 2.3.3 to 3.0.0 - bump r2d2_sqlite from 0.21.0 to 0.22.0 - bump reqwest from 0.11.16 to 0.11.18 - bump axum from 0.6.16 to 0.6.18 - bump axum-client-ip from 0.4.0 to 0.4.1 --- Cargo.lock | 64 +++++++++++++++++-------------- Cargo.toml | 4 +- packages/configuration/Cargo.toml | 2 +- 3 files changed, 39 insertions(+), 31 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9cf3cb302..5c72bef9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -116,7 +116,7 @@ checksum = "f8175979259124331c1d7bf6586ee7e0da434155e4b2d48ec2c8386281d8df39" dependencies = [ "async-trait", "axum-core", - "bitflags", + "bitflags 1.3.2", "bytes", "futures-util", "http", @@ -238,7 +238,7 @@ version = "0.59.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bd2a9a458e8f4304c52c43ebb0cfbd520289f8379a52e329a38afda99bf8eb8" dependencies = [ - "bitflags", + "bitflags 1.3.2", "cexpr", "clang-sys", "lazy_static", @@ -266,6 +266,12 @@ version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" +[[package]] +name = "bitflags" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "630be753d4e58660abd17930c71b647fe46c27ea6b63cc59e1e3851406972e42" + [[package]] name = "bitvec" version = "1.0.1" @@ -1355,9 +1361,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.25.2" +version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29f835d03d717946d28b1d1ed632eb6f0e24a299388ee623d0c23118d3e8a7fa" +checksum = "afc22eff61b133b115c6e8c74e818c628d6d5e7a502afea6f64dee076dd94326" dependencies = [ "cc", "pkg-config", @@ -1548,7 +1554,7 @@ dependencies = [ "base64 0.13.1", "bigdecimal", "bindgen", - "bitflags", + "bitflags 1.3.2", "bitvec", "byteorder", "bytes", @@ -1711,7 +1717,7 @@ version = "0.10.55" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "345df152bc43501c5eb9e4654ff05f794effb78d4efe3d53abc158baddc0703d" dependencies = [ - "bitflags", + "bitflags 1.3.2", "cfg-if", "foreign-types", "libc", @@ -2007,12 +2013,13 @@ dependencies = [ [[package]] name = "r2d2_sqlite" -version = "0.21.0" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4f5d0337e99cd5cacd91ffc326c6cc9d8078def459df560c4f9bf9ba4a51034" +checksum = "99f31323d6161385f385046738df520e0e8694fa74852d35891fc0be08348ddc" dependencies = [ "r2d2", "rusqlite", + "uuid", ] [[package]] @@ -2057,7 +2064,7 @@ version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" dependencies = [ - "bitflags", + "bitflags 1.3.2", ] [[package]] @@ -2185,17 +2192,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88073939a61e5b7680558e6be56b419e208420c2adb92be54921fa6b72283f1a" dependencies = [ "base64 0.13.1", - "bitflags", + "bitflags 1.3.2", "serde", ] [[package]] name = "rusqlite" -version = "0.28.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01e213bc3ecb39ac32e81e51ebe31fd888a940515173e3a18a35f8c6e896422a" +checksum = "549b9d036d571d42e6e85d1c1425e2ac83491075078ca9a15be021c56b1641f2" dependencies = [ - "bitflags", + "bitflags 2.3.3", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -2258,7 +2265,7 @@ version = "0.37.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d69718bf81c6127a49dc64e44a742e8bb9213c0ff8869a22c308f84c1d4ab06" dependencies = [ - "bitflags", + "bitflags 1.3.2", "errno", "io-lifetimes", "libc", @@ -2351,7 +2358,7 @@ version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fc758eb7bffce5b308734e9b0c1468893cae9ff70ebf13e7090be8dcbcc83a8" dependencies = [ - "bitflags", + "bitflags 1.3.2", "core-foundation", "core-foundation-sys", "libc", @@ -2376,9 +2383,9 @@ checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" [[package]] name = "serde" -version = "1.0.166" +version = "1.0.167" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d01b7404f9d441d3ad40e6a636a7782c377d2abdbe4fa2440e2edcc2f4f10db8" +checksum = "7daf513456463b42aa1d94cff7e0c24d682b429f020b9afa4f5ba5c40a22b237" dependencies = [ "serde_derive", ] @@ -2404,9 +2411,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.166" +version = "1.0.167" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dd83d6dde2b6b2d466e14d9d1acce8816dedee94f735eac6395808b3483c6d6" +checksum = "b69b106b68bc8054f0e974e70d19984040f8a5cf9215ca82626ea4853f82c4b9" dependencies = [ "proc-macro2", "quote", @@ -2468,11 +2475,11 @@ dependencies = [ [[package]] name = "serde_with" -version = "2.3.3" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07ff71d2c147a7b57362cead5e22f772cd52f6ab31cfcd9edcd7f6aeb2a0afbe" +checksum = "9f02d8aa6e3c385bf084924f660ce2a3a6bd333ba55b35e8590b321f35d88513" dependencies = [ - "base64 0.13.1", + "base64 0.21.2", "chrono", "hex", "indexmap 1.9.3", @@ -2484,9 +2491,9 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "2.3.3" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "881b6f881b17d13214e5d494c939ebab463d01264ce1811e9d4ac3a882e7695f" +checksum = "edc7d5d3932fb12ce722ee5e64dd38c504efba37567f0c402f6ca728c3b8b070" dependencies = [ "darling", "proc-macro2", @@ -2646,18 +2653,18 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.41" +version = "1.0.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c16a64ba9387ef3fdae4f9c1a7f07a0997fce91985c0336f1ddc1822b3b37802" +checksum = "a35fc5b8971143ca348fa6df4f024d4d55264f3468c71ad1c2f365b0a4d58c42" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.41" +version = "1.0.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d14928354b01c4d6a4f0e549069adef399a284e7995c7ccca94e8a07a5346c59" +checksum = "463fe12d7993d3b327787537ce8dd4dfa058de32fc2b195ef3cde03dc4771e8f" dependencies = [ "proc-macro2", "quote", @@ -3023,6 +3030,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d023da39d1fde5a8a3fe1f3e01ca9632ada0a63e9797de55a879d6e2236277be" dependencies = [ "getrandom", + "rand", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index fec8784d4..a25ead8f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ tokio = { version = "1.29", features = ["rt-multi-thread", "net", "sync", "macro serde = { version = "1.0", features = ["derive"] } serde_bencode = "^0.2" serde_json = "1.0" -serde_with = "2.0" +serde_with = "3.0" percent-encoding = "2.2" binascii = "0.1" lazy_static = "1.4" @@ -28,7 +28,7 @@ fern = "0.6" chrono = { version = "0.4.24", default-features = false, features = ["clock"] } r2d2 = "0.8" r2d2_mysql = "23.0" -r2d2_sqlite = { version = "0.21", features = ["bundled"] } +r2d2_sqlite = { version = "0.22", features = ["bundled"] } rand = "0.8" derive_more = "0.99" thiserror = "1.0" diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 6f9e5cbc5..dd4938de7 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -8,7 +8,7 @@ edition.workspace = true [dependencies] serde = { version = "1.0", features = ["derive"] } -serde_with = "2.0" +serde_with = "3.0" config = "0.13" toml = "0.7" log = { version = "0.4", features = ["release_max_level_info"] } From f256a6b201b5d5e007bfdd6666efda1c2709e452 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jul 2023 11:22:45 +0100 Subject: [PATCH 0031/1297] chore(deps): bump axum-server from 0.4.7 to 0.5.1 --- Cargo.lock | 35 +++++++++++++++++------------------ Cargo.toml | 2 +- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5c72bef9e..e7febbe95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -170,9 +170,9 @@ dependencies = [ [[package]] name = "axum-server" -version = "0.4.7" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bace45b270e36e3c27a190c65883de6dfc9f1d18c829907c127464815dc67b24" +checksum = "447f28c85900215cc1bea282f32d4a2f22d55c5a300afdfbc661c8d6a632e063" dependencies = [ "arc-swap", "bytes", @@ -2275,14 +2275,14 @@ dependencies = [ [[package]] name = "rustls" -version = "0.20.8" +version = "0.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f" +checksum = "b19faa85ecb5197342b54f987b142fb3e30d0c90da40f80ef4fa9a726e6676ed" dependencies = [ "log", "ring", + "rustls-webpki", "sct", - "webpki", ] [[package]] @@ -2294,6 +2294,16 @@ dependencies = [ "base64 0.21.2", ] +[[package]] +name = "rustls-webpki" +version = "0.101.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15f36a6828982f422756984e47912a7a51dcbc2a197aa791158f8ca61cd8204e" +dependencies = [ + "ring", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.13" @@ -2755,13 +2765,12 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.23.4" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59" +checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ "rustls", "tokio", - "webpki", ] [[package]] @@ -3136,16 +3145,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "webpki" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd" -dependencies = [ - "ring", - "untrusted", -] - [[package]] name = "winapi" version = "0.3.9" diff --git a/Cargo.toml b/Cargo.toml index a25ead8f1..1a46af194 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,7 +37,7 @@ async-trait = "0.1" aquatic_udp_protocol = "0.8" uuid = { version = "1", features = ["v4"] } axum = "0.6.18" -axum-server = { version = "0.4", features = ["tls-rustls"] } +axum-server = { version = "0.5", features = ["tls-rustls"] } axum-client-ip = "0.4.1" bip_bencode = "0.4" torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "packages/primitives" } From 402e6a15a1232e094d8443b4d68a5edf9f5ba6bb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jul 2023 11:32:37 +0100 Subject: [PATCH 0032/1297] docs: normalize license We will use the same dual license in all Torrust repos for now. We will open a new discussion to reach a community consensus. --- COPYRIGHT | 11 + Cargo.toml | 3 +- LICENSE-AGPL_3_0 | 662 ++++++++++++++++++++++++++++++ LICENSE-MIT_0 | 14 + README.md | 4 +- packages/configuration/Cargo.toml | 2 +- packages/located-error/Cargo.toml | 2 +- packages/primitives/Cargo.toml | 2 +- packages/test-helpers/Cargo.toml | 2 +- 9 files changed, 694 insertions(+), 8 deletions(-) create mode 100644 COPYRIGHT create mode 100644 LICENSE-AGPL_3_0 create mode 100644 LICENSE-MIT_0 diff --git a/COPYRIGHT b/COPYRIGHT new file mode 100644 index 000000000..6eef820ec --- /dev/null +++ b/COPYRIGHT @@ -0,0 +1,11 @@ +Copyright 2023 in the Torrust-Tracker project are retained by their contributors. No +copyright assignment is required to contribute to the Torrust-Tracker project. + +Some files include explicit copyright notices and/or license notices. + +Except as otherwise noted (below and/or in individual files), Torrust-Tracker is +licensed under the GNU Affero General Public License, Version 3.0 . This license applies to all files in the Torrust-Tracker project, except as noted below. + +Except as otherwise noted (below and/or in individual files), Torrust-Tracker is licensed under the MIT-0 license for all commits made after 5 years of merging. This license applies to the version of the files merged into the Torrust-Tracker project at the time of merging, and does not apply to subsequent updates or revisions to those files. + +The contributors to the Torrust-Tracker project disclaim all liability for any damages or losses that may arise from the use of the project. diff --git a/Cargo.toml b/Cargo.toml index 1a46af194..4f396d5b8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,12 +1,13 @@ [package] name = "torrust-tracker" description = "A feature rich BitTorrent tracker." -license = "AGPL-3.0" +license-file.workspace = true authors.workspace = true edition.workspace = true version.workspace = true [workspace.package] +license-file = "COPYRIGHT" authors = ["Nautilus Cyberneering , Mick van Dijke "] edition = "2021" repository = "https://github.com/torrust/torrust-tracker" diff --git a/LICENSE-AGPL_3_0 b/LICENSE-AGPL_3_0 new file mode 100644 index 000000000..2beb9e163 --- /dev/null +++ b/LICENSE-AGPL_3_0 @@ -0,0 +1,662 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. + diff --git a/LICENSE-MIT_0 b/LICENSE-MIT_0 new file mode 100644 index 000000000..fc06cc4fe --- /dev/null +++ b/LICENSE-MIT_0 @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index c3d0a127b..6c20ee20f 100644 --- a/README.md +++ b/README.md @@ -73,9 +73,7 @@ How can you contribute? ## License -The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). - -There is an ongoing discussion about the license of the project. You can follow the discussion [here](https://github.com/torrust/torrust-tracker/pull/251). +The project is licensed under a dual license. See [COPYRIGHT](./COPYRIGHT). ## Acknowledgments diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index dd4938de7..aca3808d2 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "torrust-tracker-configuration" description = "A library to provide configuration to the Torrust Tracker." -license = "AGPL-3.0" +license-file.workspace = true version.workspace = true authors.workspace = true edition.workspace = true diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index acd13def3..95cc1fd18 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "torrust-tracker-located-error" description = "A library to provide error decorator with the location and the source of the original error." -license = "AGPL-3.0" +license-file.workspace = true version.workspace = true authors.workspace = true edition.workspace = true diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index bba45cf5d..a2e17b63c 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "torrust-tracker-primitives" description = "A library with the primitive types shared by the Torrust tracker packages." -license = "AGPL-3.0" +license-file.workspace = true version.workspace = true authors.workspace = true edition.workspace = true diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 5d360d101..6812a90ae 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "torrust-tracker-test-helpers" description = "A library providing helpers for testing the Torrust tracker." -license = "AGPL-3.0" +license-file.workspace = true version.workspace = true authors.workspace = true edition.workspace = true From 38d1d494ebab90f8be53ec6966136f3eba57ed22 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jul 2023 11:59:28 +0100 Subject: [PATCH 0033/1297] chore(release): 3.0.0-alpha.3 --- Cargo.lock | 10 +++++----- Cargo.toml | 10 +++++----- README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- src/lib.rs | 2 +- 6 files changed, 19 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e7febbe95..20557f7c8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2832,7 +2832,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.2" +version = "3.0.0-alpha.3" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -2877,7 +2877,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.2" +version = "3.0.0-alpha.3" dependencies = [ "config", "log", @@ -2892,7 +2892,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.2" +version = "3.0.0-alpha.3" dependencies = [ "log", "thiserror", @@ -2900,7 +2900,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.2" +version = "3.0.0-alpha.3" dependencies = [ "derive_more", "serde", @@ -2908,7 +2908,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.2" +version = "3.0.0-alpha.3" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index 4f396d5b8..4b4a05a2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,7 @@ license-file = "COPYRIGHT" authors = ["Nautilus Cyberneering , Mick van Dijke "] edition = "2021" repository = "https://github.com/torrust/torrust-tracker" -version = "3.0.0-alpha.2" +version = "3.0.0-alpha.3" [dependencies] tokio = { version = "1.29", features = ["rt-multi-thread", "net", "sync", "macros", "signal"] } @@ -41,9 +41,9 @@ axum = "0.6.18" axum-server = { version = "0.5", features = ["tls-rustls"] } axum-client-ip = "0.4.1" bip_bencode = "0.4" -torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "packages/primitives" } -torrust-tracker-configuration = { version = "3.0.0-alpha.2", path = "packages/configuration" } -torrust-tracker-located-error = { version = "3.0.0-alpha.2", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.3", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.3", path = "packages/configuration" } +torrust-tracker-located-error = { version = "3.0.0-alpha.3", path = "packages/located-error" } multimap = "0.9" hyper = "0.14" @@ -54,7 +54,7 @@ serde_urlencoded = "0.7" serde_repr = "0.1" serde_bytes = "0.11" local-ip-address = "0.5" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.2", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.3", path = "packages/test-helpers" } [workspace] members = [ diff --git a/README.md b/README.md index 6c20ee20f..9d2838a88 100644 --- a/README.md +++ b/README.md @@ -56,9 +56,9 @@ After running the tracker these services will be available: ## Documentation * [Crate documentation](https://docs.rs/torrust-tracker/). -* [API `v1`](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/apis/v1). -* [HTTP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/http). -* [UDP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/udp). +* [API `v1`](https://docs.rs/torrust-tracker/3.0.0-alpha.3/torrust_tracker/servers/apis/v1). +* [HTTP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.3/torrust_tracker/servers/http). +* [UDP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.3/torrust_tracker/servers/udp). ## Contributing @@ -68,7 +68,7 @@ How can you contribute? * Bug reports and feature requests. * Code contributions. You can start by looking at the issues labeled ["good first issues"](https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). -* Documentation improvements. Check the [documentation](https://docs.rs/torrust-tracker/) and [API documentation](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/apis/v1) for typos, errors, or missing information. +* Documentation improvements. Check the [documentation](https://docs.rs/torrust-tracker/) and [API documentation](https://docs.rs/torrust-tracker/3.0.0-alpha.3/torrust_tracker/servers/apis/v1) for typos, errors, or missing information. * Participation in the community. You can help by answering questions in the [discussions](https://github.com/torrust/torrust-tracker/discussions). ## License diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index aca3808d2..d28df4798 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -13,8 +13,8 @@ config = "0.13" toml = "0.7" log = { version = "0.4", features = ["release_max_level_info"] } thiserror = "1.0" -torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "../primitives" } -torrust-tracker-located-error = { version = "3.0.0-alpha.2", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.3", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.3", path = "../located-error" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 6812a90ae..e38fcf6f6 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -9,5 +9,5 @@ edition.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.2", path = "../configuration"} -torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "../primitives"} +torrust-tracker-configuration = { version = "3.0.0-alpha.3", path = "../configuration"} +torrust-tracker-primitives = { version = "3.0.0-alpha.3", path = "../primitives"} diff --git a/src/lib.rs b/src/lib.rs index 744642a3f..d14a3ada1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -148,7 +148,7 @@ //! --publish 7070:7070/tcp \ //! --publish 1212:1212/tcp \ //! --volume "$(pwd)/storage":"/app/storage" \ -//! torrust/tracker:3.0.0-alpha.2 +//! torrust/tracker:3.0.0-alpha.3 //! ``` //! //! For more information about using docker visit the [tracker docker documentation](https://github.com/torrust/torrust-tracker/tree/develop/docker). From 358c81ea5fa40a341f253ae5fdca9949a60c4f50 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jul 2023 17:10:04 +0100 Subject: [PATCH 0034/1297] ci: fix missing doc attribute while publishing crates It fixes the warning: ``` warning: manifest has no documentation, homepage or repository. ``` --- Cargo.toml | 1 + packages/configuration/Cargo.toml | 3 ++- packages/located-error/Cargo.toml | 3 ++- packages/primitives/Cargo.toml | 3 ++- packages/test-helpers/Cargo.toml | 3 ++- 5 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4b4a05a2e..152495463 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ description = "A feature rich BitTorrent tracker." license-file.workspace = true authors.workspace = true edition.workspace = true +repository.workspace = true version.workspace = true [workspace.package] diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index d28df4798..a6cf57710 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -2,9 +2,10 @@ name = "torrust-tracker-configuration" description = "A library to provide configuration to the Torrust Tracker." license-file.workspace = true -version.workspace = true authors.workspace = true edition.workspace = true +repository.workspace = true +version.workspace = true [dependencies] serde = { version = "1.0", features = ["derive"] } diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index 95cc1fd18..19707e7e9 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -2,9 +2,10 @@ name = "torrust-tracker-located-error" description = "A library to provide error decorator with the location and the source of the original error." license-file.workspace = true -version.workspace = true authors.workspace = true edition.workspace = true +repository.workspace = true +version.workspace = true [dependencies] log = { version = "0.4", features = ["release_max_level_info"] } diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index a2e17b63c..7576e06d8 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -2,9 +2,10 @@ name = "torrust-tracker-primitives" description = "A library with the primitive types shared by the Torrust tracker packages." license-file.workspace = true -version.workspace = true authors.workspace = true edition.workspace = true +repository.workspace = true +version.workspace = true [dependencies] serde = { version = "1.0", features = ["derive"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index e38fcf6f6..e9d86a589 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -2,9 +2,10 @@ name = "torrust-tracker-test-helpers" description = "A library providing helpers for testing the Torrust tracker." license-file.workspace = true -version.workspace = true authors.workspace = true edition.workspace = true +repository.workspace = true +version.workspace = true [dependencies] lazy_static = "1.4" From 058f3ac5ba24e3f16f47d8c21c8e3a8f78a8621d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 11 Jul 2023 11:29:36 +0100 Subject: [PATCH 0035/1297] feat: create storage folder in install script --- bin/install.sh | 3 +++ config.toml.local | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/bin/install.sh b/bin/install.sh index d4314ce93..ef469a939 100755 --- a/bin/install.sh +++ b/bin/install.sh @@ -5,6 +5,9 @@ if ! [ -f "./config.toml" ]; then cp ./config.toml.local ./config.toml fi +# Generate storage directory if it does not exist +mkdir -p "./storage/database" + # Generate the sqlite database if it does not exist if ! [ -f "./storage/database/data.db" ]; then # todo: it should get the path from config.toml and only do it when we use sqlite diff --git a/config.toml.local b/config.toml.local index baf272d5a..be6a11a56 100644 --- a/config.toml.local +++ b/config.toml.local @@ -4,11 +4,11 @@ db_driver = "Sqlite3" db_path = "./storage/database/data.db" announce_interval = 120 min_announce_interval = 120 -max_peer_timeout = 900 on_reverse_proxy = false external_ip = "0.0.0.0" tracker_usage_statistics = true persistent_torrent_completed_stat = false +max_peer_timeout = 900 inactive_peer_cleanup_interval = 600 remove_peerless_torrents = true From d321ab0d039b739db2a8db73af1a00188150c80d Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 10 Feb 2023 13:55:50 +0100 Subject: [PATCH 0036/1297] refactor: remove wildcard imports from time_extent.rs --- src/shared/clock/time_extent.rs | 38 ++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/src/shared/clock/time_extent.rs b/src/shared/clock/time_extent.rs index 2f9e003be..9c20de9c1 100644 --- a/src/shared/clock/time_extent.rs +++ b/src/shared/clock/time_extent.rs @@ -285,7 +285,6 @@ pub type DefaultTimeExtentMaker = StoppedTimeExtentMaker; #[cfg(test)] mod test { - use crate::shared::clock::time_extent::{ checked_duration_from_nanos, Base, DefaultTimeExtentMaker, Extent, Make, Multiplier, Product, TimeExtent, MAX, ZERO, }; @@ -296,7 +295,8 @@ mod test { mod fn_checked_duration_from_nanos { use std::time::Duration; - use super::*; + use crate::shared::clock::time_extent::checked_duration_from_nanos; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; const NANOS_PER_SEC: u32 = 1_000_000_000; @@ -335,11 +335,9 @@ mod test { } mod time_extent { - use super::*; mod fn_default { - - use super::*; + use crate::shared::clock::time_extent::{TimeExtent, ZERO}; #[test] fn it_should_default_initialize_to_zero() { @@ -348,7 +346,8 @@ mod test { } mod fn_from_sec { - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Multiplier, TimeExtent, ZERO}; #[test] fn it_should_make_empty_for_zero() { @@ -364,7 +363,8 @@ mod test { } mod fn_new { - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Base, Extent, Multiplier, TimeExtent, ZERO}; #[test] fn it_should_make_empty_for_zero() { @@ -386,7 +386,8 @@ mod test { mod fn_increase { use std::num::IntErrorKind; - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Extent, TimeExtent, ZERO}; #[test] fn it_should_not_increase_for_zero() { @@ -413,7 +414,8 @@ mod test { mod fn_decrease { use std::num::IntErrorKind; - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Extent, TimeExtent, ZERO}; #[test] fn it_should_not_decrease_for_zero() { @@ -438,7 +440,8 @@ mod test { } mod fn_total { - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Base, Extent, Product, TimeExtent, MAX, ZERO}; #[test] fn it_should_be_zero_for_zero() { @@ -485,7 +488,8 @@ mod test { } mod fn_total_next { - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Base, Extent, Product, TimeExtent, MAX, ZERO}; #[test] fn it_should_be_zero_for_zero() { @@ -539,10 +543,11 @@ mod test { } mod make_time_extent { - use super::*; mod fn_now { - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Base, DefaultTimeExtentMaker, Make, TimeExtent}; + use crate::shared::clock::{Current, DurationSinceUnixEpoch, StoppedTime}; #[test] fn it_should_give_a_time_extent() { @@ -580,7 +585,9 @@ mod test { mod fn_now_after { use std::time::Duration; - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Base, DefaultTimeExtentMaker, Make}; + use crate::shared::clock::{Current, DurationSinceUnixEpoch, StoppedTime}; #[test] fn it_should_give_a_time_extent() { @@ -617,7 +624,8 @@ mod test { mod fn_now_before { use std::time::Duration; - use super::*; + use crate::shared::clock::time_extent::{Base, DefaultTimeExtentMaker, Make, TimeExtent}; + use crate::shared::clock::{Current, DurationSinceUnixEpoch, StoppedTime}; #[test] fn it_should_give_a_time_extent() { From eb838dd2abaff2cd7daac719b69b302513254157 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 2 Aug 2023 18:05:24 +0100 Subject: [PATCH 0037/1297] dev: tighten lint for build and clippy --- .cargo/config.toml | 20 +++++++++++ .vscode/settings.json | 21 ++++++++++-- packages/located-error/src/lib.rs | 2 +- src/servers/apis/server.rs | 2 +- .../apis/v1/context/auth_key/resources.rs | 4 +++ src/servers/http/v1/query.rs | 6 ++-- src/servers/http/v1/requests/announce.rs | 34 ++++++++----------- src/servers/http/v1/requests/scrape.rs | 10 +++--- src/servers/http/v1/responses/announce.rs | 2 +- src/servers/udp/handlers.rs | 2 ++ src/servers/udp/server.rs | 2 +- src/shared/bit_torrent/info_hash.rs | 6 ++-- src/shared/clock/time_extent.rs | 5 +-- src/tracker/mod.rs | 13 +++---- tests/servers/http/requests/announce.rs | 8 ++--- tests/servers/http/requests/scrape.rs | 4 +-- tests/servers/mod.rs | 2 -- 17 files changed, 86 insertions(+), 57 deletions(-) diff --git a/.cargo/config.toml b/.cargo/config.toml index 71480e92d..a88db5f38 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -3,3 +3,23 @@ cov = "llvm-cov" cov-lcov = "llvm-cov --lcov --output-path=./.coverage/lcov.info" cov-html = "llvm-cov --html" time = "build --timings --all-targets" + +[build] +rustflags = [ + "-D", + "warnings", + "-D", + "future-incompatible", + "-D", + "let-underscore", + "-D", + "nonstandard-style", + "-D", + "rust-2018-compatibility", + "-D", + "rust-2018-idioms", + "-D", + "rust-2021-compatibility", + "-D", + "unused", +] diff --git a/.vscode/settings.json b/.vscode/settings.json index 94f199bd6..78239b757 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,7 +2,22 @@ "[rust]": { "editor.formatOnSave": true }, - "rust-analyzer.checkOnSave.command": "clippy", - "rust-analyzer.checkOnSave.allTargets": true, - "rust-analyzer.checkOnSave.extraArgs": ["--","-W","clippy::pedantic"], + "rust-analyzer.checkOnSave": true, + "rust-analyzer.check.command": "clippy", + "rust-analyzer.check.allTargets": true, + "rust-analyzer.check.extraArgs": [ + "--", + "-D", + "clippy::correctness", + "-D", + "clippy::suspicious", + "-W", + "clippy::complexity", + "-W", + "clippy::perf", + "-W", + "clippy::style", + "-W", + "clippy::pedantic", + ], } \ No newline at end of file diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs index 67c432528..bf8618686 100644 --- a/packages/located-error/src/lib.rs +++ b/packages/located-error/src/lib.rs @@ -128,7 +128,7 @@ mod tests { fn error_should_include_location() { let e = TestError::Test; - let b: LocatedError = Located(e).into(); + let b: LocatedError<'_, TestError> = Located(e).into(); let l = get_caller_location(); assert_eq!(b.location.file(), l.file()); diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 716a36c11..778a17d90 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -128,7 +128,7 @@ impl ApiServer { .send(0) .map_err(|_| Error::Error("Task killer channel was closed.".to_string()))?; - let _: Result<(), tokio::task::JoinError> = self.state.task.await; + drop(self.state.task.await); Ok(ApiServer { cfg: self.cfg, diff --git a/src/servers/apis/v1/context/auth_key/resources.rs b/src/servers/apis/v1/context/auth_key/resources.rs index 3eeafbda0..5099fad8b 100644 --- a/src/servers/apis/v1/context/auth_key/resources.rs +++ b/src/servers/apis/v1/context/auth_key/resources.rs @@ -27,6 +27,7 @@ impl From for auth::ExpiringKey { } } +#[allow(deprecated)] impl From for AuthKey { fn from(auth_key: auth::ExpiringKey) -> Self { AuthKey { @@ -63,6 +64,7 @@ mod tests { } #[test] + #[allow(deprecated)] fn it_should_be_convertible_into_an_auth_key() { let auth_key_resource = AuthKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".to_string(), // cspell:disable-line @@ -80,6 +82,7 @@ mod tests { } #[test] + #[allow(deprecated)] fn it_should_be_convertible_from_an_auth_key() { let auth_key = auth::ExpiringKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".parse::().unwrap(), // cspell:disable-line @@ -97,6 +100,7 @@ mod tests { } #[test] + #[allow(deprecated)] fn it_should_be_convertible_into_json() { assert_eq!( serde_json::to_string(&AuthKey { diff --git a/src/servers/http/v1/query.rs b/src/servers/http/v1/query.rs index 6bbdc63e9..745796b61 100644 --- a/src/servers/http/v1/query.rs +++ b/src/servers/http/v1/query.rs @@ -137,7 +137,7 @@ impl From> for Query { } impl std::fmt::Display for Query { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let query = self .params .iter_all() @@ -185,7 +185,7 @@ impl FromStr for NameValuePair { } impl std::fmt::Display for NameValuePair { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}={}", self.name, self.value) } } @@ -208,7 +208,7 @@ impl FieldValuePairSet { } impl std::fmt::Display for FieldValuePairSet { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let query = self .pairs .iter() diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index 1cf632eb5..c330ca3bd 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -166,7 +166,7 @@ impl FromStr for Event { } impl fmt::Display for Event { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Event::Started => write!(f, "started"), Event::Stopped => write!(f, "stopped"), @@ -194,7 +194,7 @@ pub enum Compact { } impl fmt::Display for Compact { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Compact::Accepted => write!(f, "1"), Compact::NotAccepted => write!(f, "0"), @@ -264,12 +264,10 @@ fn extract_info_hash(query: &Query) -> Result })?, ) } - None => { - return Err(ParseAnnounceQueryError::MissingParam { - location: Location::caller(), - param_name: INFO_HASH.to_owned(), - }) - } + None => Err(ParseAnnounceQueryError::MissingParam { + location: Location::caller(), + param_name: INFO_HASH.to_owned(), + }), } } @@ -282,12 +280,10 @@ fn extract_peer_id(query: &Query) -> Result { source: Located(err).into(), })?, ), - None => { - return Err(ParseAnnounceQueryError::MissingParam { - location: Location::caller(), - param_name: PEER_ID.to_owned(), - }) - } + None => Err(ParseAnnounceQueryError::MissingParam { + location: Location::caller(), + param_name: PEER_ID.to_owned(), + }), } } @@ -298,12 +294,10 @@ fn extract_port(query: &Query) -> Result { param_value: raw_param.clone(), location: Location::caller(), })?), - None => { - return Err(ParseAnnounceQueryError::MissingParam { - location: Location::caller(), - param_name: PORT.to_owned(), - }) - } + None => Err(ParseAnnounceQueryError::MissingParam { + location: Location::caller(), + param_name: PORT.to_owned(), + }), } } diff --git a/src/servers/http/v1/requests/scrape.rs b/src/servers/http/v1/requests/scrape.rs index 227ea74ae..7c52b9fc4 100644 --- a/src/servers/http/v1/requests/scrape.rs +++ b/src/servers/http/v1/requests/scrape.rs @@ -74,12 +74,10 @@ fn extract_info_hashes(query: &Query) -> Result, ParseScrapeQueryE Ok(info_hashes) } - None => { - return Err(ParseScrapeQueryError::MissingParam { - location: Location::caller(), - param_name: INFO_HASH.to_owned(), - }) - } + None => Err(ParseScrapeQueryError::MissingParam { + location: Location::caller(), + param_name: INFO_HASH.to_owned(), + }), } } diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index 8fbe5df35..0cd62578a 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -116,7 +116,7 @@ pub struct Peer { impl Peer { #[must_use] - pub fn ben_map(&self) -> BencodeMut { + pub fn ben_map(&self) -> BencodeMut<'_> { ben_map! { "peer id" => ben_bytes!(self.peer_id.clone().to_vec()), "ip" => ben_bytes!(self.ip.to_string()), diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index e94e0292f..64d60e549 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -104,6 +104,7 @@ pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, t /// # Errors /// /// Will return `Error` if unable to `authenticate_request`. +#[allow(deprecated)] pub async fn authenticate(info_hash: &InfoHash, tracker: &Tracker) -> Result<(), Error> { tracker .authenticate_request(info_hash, &None) @@ -225,6 +226,7 @@ pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tra let info_hash = file.0; let swarm_metadata = file.1; + #[allow(deprecated)] let scrape_entry = if tracker.authenticate_request(info_hash, &None).await.is_ok() { #[allow(clippy::cast_possible_truncation)] TorrentScrapeStatistics { diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 6b4b18831..3bb5bd013 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -143,7 +143,7 @@ impl UdpServer { pub async fn stop(self) -> Result, Error> { self.state.stop_job_sender.send(1).map_err(|e| Error::Error(e.to_string()))?; - let _: Result<(), tokio::task::JoinError> = self.state.job.await; + drop(self.state.job.await); let stopped_api_server: UdpServer = UdpServer { cfg: self.cfg, diff --git a/src/shared/bit_torrent/info_hash.rs b/src/shared/bit_torrent/info_hash.rs index 7392c791d..20c3cb38b 100644 --- a/src/shared/bit_torrent/info_hash.rs +++ b/src/shared/bit_torrent/info_hash.rs @@ -167,7 +167,7 @@ impl InfoHash { } impl std::fmt::Display for InfoHash { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut chars = [0u8; 40]; binascii::bin2hex(&self.0, &mut chars).expect("failed to hexlify"); write!(f, "{}", std::str::from_utf8(&chars).unwrap()) @@ -195,7 +195,7 @@ impl Ord for InfoHash { impl std::cmp::PartialOrd for InfoHash { fn partial_cmp(&self, other: &InfoHash) -> Option { - self.0.partial_cmp(&other.0) + Some(self.cmp(other)) } } @@ -271,7 +271,7 @@ struct InfoHashVisitor; impl<'v> serde::de::Visitor<'v> for InfoHashVisitor { type Value = InfoHash; - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "a 40 character long hash") } diff --git a/src/shared/clock/time_extent.rs b/src/shared/clock/time_extent.rs index 9c20de9c1..a5a359e52 100644 --- a/src/shared/clock/time_extent.rs +++ b/src/shared/clock/time_extent.rs @@ -285,10 +285,7 @@ pub type DefaultTimeExtentMaker = StoppedTimeExtentMaker; #[cfg(test)] mod test { - use crate::shared::clock::time_extent::{ - checked_duration_from_nanos, Base, DefaultTimeExtentMaker, Extent, Make, Multiplier, Product, TimeExtent, MAX, ZERO, - }; - use crate::shared::clock::{Current, DurationSinceUnixEpoch, StoppedTime}; + use crate::shared::clock::time_extent::TimeExtent; const TIME_EXTENT_VAL: TimeExtent = TimeExtent::from_sec(2, &239_812_388_723); diff --git a/src/tracker/mod.rs b/src/tracker/mod.rs index 4d7d8d37e..63c8b96d6 100644 --- a/src/tracker/mod.rs +++ b/src/tracker/mod.rs @@ -732,10 +732,11 @@ impl Tracker { // todo: move this action to a separate worker if self.config.persistent_torrent_completed_stat && stats_updated { - let _: Result<(), databases::error::Error> = self - .database - .save_persistent_torrent(info_hash, torrent_entry.completed) - .await; + drop( + self.database + .save_persistent_torrent(info_hash, torrent_entry.completed) + .await, + ); } let (seeders, completed, leechers) = torrent_entry.get_stats(); @@ -966,10 +967,10 @@ impl Tracker { return Ok(()); } - return Err(Error::TorrentNotWhitelisted { + Err(Error::TorrentNotWhitelisted { info_hash: *info_hash, location: Location::caller(), - }); + }) } /// It adds a torrent to the whitelist. diff --git a/tests/servers/http/requests/announce.rs b/tests/servers/http/requests/announce.rs index 20c5ddaa7..f7f25da3e 100644 --- a/tests/servers/http/requests/announce.rs +++ b/tests/servers/http/requests/announce.rs @@ -21,7 +21,7 @@ pub struct Query { } impl fmt::Display for Query { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.build()) } } @@ -57,7 +57,7 @@ pub enum Event { } impl fmt::Display for Event { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { //Event::Started => write!(f, "started"), //Event::Stopped => write!(f, "stopped"), @@ -74,7 +74,7 @@ pub enum Compact { } impl fmt::Display for Compact { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Compact::Accepted => write!(f, "1"), Compact::NotAccepted => write!(f, "0"), @@ -163,7 +163,7 @@ pub struct QueryParams { } impl std::fmt::Display for QueryParams { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut params = vec![]; if let Some(info_hash) = &self.info_hash { diff --git a/tests/servers/http/requests/scrape.rs b/tests/servers/http/requests/scrape.rs index 9e4257d6c..264c72c33 100644 --- a/tests/servers/http/requests/scrape.rs +++ b/tests/servers/http/requests/scrape.rs @@ -10,7 +10,7 @@ pub struct Query { } impl fmt::Display for Query { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.build()) } } @@ -93,7 +93,7 @@ impl QueryParams { } impl std::fmt::Display for QueryParams { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let query = self .info_hash .iter() diff --git a/tests/servers/mod.rs b/tests/servers/mod.rs index c19f72020..7c30b6f40 100644 --- a/tests/servers/mod.rs +++ b/tests/servers/mod.rs @@ -1,5 +1,3 @@ -extern crate rand; - mod api; mod http; mod udp; From 9fac926b1fb739d8e033546b389d496dff7d97ee Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 2 Aug 2023 19:34:13 +0100 Subject: [PATCH 0038/1297] ci: overhall codecov workflow --- .github/workflows/codecov.yml | 40 ------------------------ .github/workflows/coverage.yaml | 54 +++++++++++++++++++++++++++++++++ cSpell.json | 7 +++++ 3 files changed, 61 insertions(+), 40 deletions(-) delete mode 100644 .github/workflows/codecov.yml create mode 100644 .github/workflows/coverage.yaml diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml deleted file mode 100644 index 05551bafc..000000000 --- a/.github/workflows/codecov.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: Upload code coverage - -on: - push: - pull_request: - -env: - CARGO_TERM_COLOR: always - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: nightly - components: rustfmt, llvm-tools-preview - - name: Build - run: cargo build --release - env: - CARGO_INCREMENTAL: "0" - RUSTFLAGS: "-Cinstrument-coverage" - RUSTDOCFLAGS: "-Cinstrument-coverage" - - name: Test - run: cargo test --all-features --no-fail-fast - env: - CARGO_INCREMENTAL: "0" - RUSTFLAGS: "-Cinstrument-coverage" - RUSTDOCFLAGS: "-Cinstrument-coverage" - - name: Install grcov - run: if [[ ! -e ~/.cargo/bin/grcov ]]; then cargo install grcov; fi - - name: Run grcov - run: grcov . --binary-path target/debug/deps/ -s . -t lcov --branch --ignore-not-existing --ignore '../**' --ignore '/*' -o coverage.lcov - - uses: codecov/codecov-action@v3 - with: - files: ./coverage.lcov - flags: rust - fail_ci_if_error: true # optional (default = false) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml new file mode 100644 index 000000000..d2750000a --- /dev/null +++ b/.github/workflows/coverage.yaml @@ -0,0 +1,54 @@ +name: Coverage + +on: + push: + pull_request: + +env: + CARGO_TERM_COLOR: always + +jobs: + report: + name: Report + runs-on: ubuntu-latest + env: + CARGO_INCREMENTAL: "0" + RUSTFLAGS: "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests" + RUSTDOCFLAGS: "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests" + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v3 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: nightly + components: llvm-tools-preview + + - id: cache + name: Enable Workflow Cache + uses: Swatinem/rust-cache@v2 + + - id: check + name: Run Build-Checks + run: cargo check --workspace --all-targets --all-features + + - id: test + name: Run Unit Tests + run: cargo test --workspace --all-targets --all-features + + - id: coverage + name: Generate Coverage Report + uses: alekitto/grcov@v0.2 + + - id: upload + name: Upload Coverage Report + uses: codecov/codecov-action@v3 + with: + files: ${{ steps.coverage.outputs.report }} + flag: rust + verbose: true + fail_ci_if_error: true diff --git a/cSpell.json b/cSpell.json index c935021c0..ac83bf7f7 100644 --- a/cSpell.json +++ b/cSpell.json @@ -1,5 +1,6 @@ { "words": [ + "alekitto", "appuser", "Arvid", "AUTOINCREMENT", @@ -21,12 +22,16 @@ "certbot", "chrono", "clippy", + "codecov", + "codegen", "completei", "connectionless", "dockerhub", "downloadedi", + "dtolnay", "filesd", "Freebox", + "Grcov", "hasher", "hexlify", "hlocalhost", @@ -67,6 +72,8 @@ "rngs", "routable", "rusqlite", + "RUSTDOCFLAGS", + "RUSTFLAGS", "rustfmt", "Rustls", "Seedable", From 8f39f6e476e97bb3dfe0df7181e8d80cfa2e6df7 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 3 Aug 2023 12:19:36 +0100 Subject: [PATCH 0039/1297] ci: update coverage workflow make workflow nicer add 'codecov.yml' for configuration remove 'rust' flag (will move to automatic flags in the future) --- .github/workflows/coverage.yaml | 9 +++++++-- cSpell.json | 1 + codecov.yml | 6 ++++++ 3 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 codecov.yml diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index d2750000a..08b869327 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -32,8 +32,14 @@ jobs: name: Enable Workflow Cache uses: Swatinem/rust-cache@v2 + - id: tools + name: Install Tools + uses: taiki-e/install-action@v2 + with: + tool: grcov + - id: check - name: Run Build-Checks + name: Run Build Checks run: cargo check --workspace --all-targets --all-features - id: test @@ -49,6 +55,5 @@ jobs: uses: codecov/codecov-action@v3 with: files: ${{ steps.coverage.outputs.report }} - flag: rust verbose: true fail_ci_if_error: true diff --git a/cSpell.json b/cSpell.json index ac83bf7f7..5cafa68ed 100644 --- a/cSpell.json +++ b/cSpell.json @@ -84,6 +84,7 @@ "subsec", "Swatinem", "Swiftbit", + "taiki", "thiserror", "Torrentstorm", "torrust", diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 000000000..f0878195b --- /dev/null +++ b/codecov.yml @@ -0,0 +1,6 @@ +coverage: + status: + project: + default: + target: auto + threshold: 0.5% From 8defabd531a40c09fafc73b7d57775eeb01633c1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 7 Aug 2023 17:18:28 +0100 Subject: [PATCH 0040/1297] doc: [#351] fix single-command to run demo env with docker --- bin/install-demo.sh | 27 ++++++++++ bin/install.sh | 2 + docker/README.md | 60 +++++++++++++++++------ docker/bin/{run.sh => run-local-image.sh} | 0 docker/bin/run-public-image.sh | 13 +++++ src/lib.rs | 18 +------ 6 files changed, 88 insertions(+), 32 deletions(-) create mode 100755 bin/install-demo.sh rename docker/bin/{run.sh => run-local-image.sh} (100%) create mode 100755 docker/bin/run-public-image.sh diff --git a/bin/install-demo.sh b/bin/install-demo.sh new file mode 100755 index 000000000..1b829ca1d --- /dev/null +++ b/bin/install-demo.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +# Single command to setup and run the tracker using the pre-built image. + +# Check if 'storage' directory exists +if [ -d "./storage" ]; then + echo "Warning: 'storage' directory already exists. Please remove or rename it before proceeding." + exit 1 +fi + +# Check if 'config.toml' file exists in the current directory +if [ -f "./config.toml" ]; then + echo "Warning: 'config.toml' file already exists in the root directory. Please remove or rename it before proceeding." + exit 1 +fi + +# Check if SQLite3 is installed +if ! command -v sqlite3 &> /dev/null; then + echo "Warning: SQLite3 is not installed on your system. Please install it and retry." + exit 1 +fi + +wget https://raw.githubusercontent.com/torrust/torrust-tracker/v3.0.0-alpha.3/config.toml.local -O config.toml \ + && mkdir -p ./storage/database \ + && mkdir -p ./storage/ssl_certificates \ + && touch ./storage/database/data.db \ + && echo ";" | sqlite3 ./storage/database/data.db diff --git a/bin/install.sh b/bin/install.sh index ef469a939..82ea940d0 100755 --- a/bin/install.sh +++ b/bin/install.sh @@ -1,5 +1,7 @@ #!/bin/bash +# This script is only intended to be used for local development or testing environments. + # Generate the default settings file if it does not exist if ! [ -f "./config.toml" ]; then cp ./config.toml.local ./config.toml diff --git a/docker/README.md b/docker/README.md index e0fee61e7..207dadbbc 100644 --- a/docker/README.md +++ b/docker/README.md @@ -17,6 +17,26 @@ storage/ > NOTE: you only need the `ssl_certificates` directory and certificates in case you have enabled SSL for the one HTTP tracker or the API. +## Demo environment + +You can run a single command to setup the tracker with the default +configuration and run it using the pre-built public docker image: + +```s +curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/torrust/torrust-tracker/v3.0.0-alpha.3/bin/install-demo.sh | bash +export TORRUST_TRACKER_USER_UID=1000 \ + && docker run -it \ + --user="$TORRUST_TRACKER_USER_UID" \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \ + --volume "$(pwd)/storage":"/app/storage" \ + --volume "$(pwd)/config.toml":"/app/config.toml":ro \ + torrust/tracker:3.0.0-alpha.3 +``` + +This is intended to be used to run a quick demo of the application. + ## Dev environment When using docker you have to bind the exposed ports to the wildcard address `0.0.0.0`, so you can access the application from the host machine. @@ -28,38 +48,46 @@ The default API configuration uses `127.0.0.1`, so you have to change it to: bind_address = "0.0.0.0:1212" ``` -Otherwise the API will be only accessible from inside the container. +Otherwise, the API will be only accessible from inside the container. ### With docker -Build and run locally: +Build and run locally. You can build the docker image locally: ```s docker context use default export TORRUST_TRACKER_USER_UID=1000 ./docker/bin/build.sh $TORRUST_TRACKER_USER_UID ./bin/install.sh -./docker/bin/run.sh $TORRUST_TRACKER_USER_UID +./docker/bin/run-local-image.sh $TORRUST_TRACKER_USER_UID ``` -Run using the pre-built public docker image: +Or you can run locally using the pre-built docker image: ```s +docker context use default export TORRUST_TRACKER_USER_UID=1000 -docker run -it \ - --user="$TORRUST_TRACKER_USER_UID" \ - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \ - --volume "$(pwd)/storage":"/app/storage" \ - torrust/tracker +./bin/install.sh +./docker/bin/run-public-image.sh $TORRUST_TRACKER_USER_UID ``` -> NOTES: -> -> - You have to create the SQLite DB (`data.db`) and configuration (`config.toml`) before running the tracker. See `bin/install.sh`. -> - You have to replace the user UID (`1000`) with yours. -> - Remember to switch to your default docker context `docker context use default`. +In both cases, you will need to: + +- Create the SQLite DB (`data.db`) if you are going to use SQLite. +- Create the configuration file (`config.toml`) before running the tracker. +- Replace the user UID (`1000`) with yours. + +> NOTICE: that the `./bin/install.sh` can setup the application for you. But it +uses a predefined configuration. + +Remember to switch to your default docker context `docker context use default` +and to change the API default configuration in `config.toml` to make it +available from the host machine: + +```toml +[http_api] +bind_address = "0.0.0.0:1212" +``` ### With docker-compose diff --git a/docker/bin/run.sh b/docker/bin/run-local-image.sh similarity index 100% rename from docker/bin/run.sh rename to docker/bin/run-local-image.sh diff --git a/docker/bin/run-public-image.sh b/docker/bin/run-public-image.sh new file mode 100755 index 000000000..50407f91b --- /dev/null +++ b/docker/bin/run-public-image.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +TORRUST_TRACKER_USER_UID=${TORRUST_TRACKER_USER_UID:-1000} +TORRUST_TRACKER_CONFIG=$(cat config.toml) + +docker run -it \ + --user="$TORRUST_TRACKER_USER_UID" \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \ + --env TORRUST_TRACKER_CONFIG="$TORRUST_TRACKER_CONFIG" \ + --volume "$(pwd)/storage":"/app/storage" \ + torrust/tracker \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index d14a3ada1..28bac9244 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -136,22 +136,8 @@ //! //! ## Run with docker //! -//! You can run the tracker with a pre-built docker image: -//! -//! ```text -//! mkdir -p ./storage/database \ -//! && mkdir -p ./storage/ssl_certificates \ -//! && export TORRUST_TRACKER_USER_UID=1000 \ -//! && docker run -it \ -//! --user="$TORRUST_TRACKER_USER_UID" \ -//! --publish 6969:6969/udp \ -//! --publish 7070:7070/tcp \ -//! --publish 1212:1212/tcp \ -//! --volume "$(pwd)/storage":"/app/storage" \ -//! torrust/tracker:3.0.0-alpha.3 -//! ``` -//! -//! For more information about using docker visit the [tracker docker documentation](https://github.com/torrust/torrust-tracker/tree/develop/docker). +//! You can run the tracker with a pre-built docker image. Please refer to the +//! [tracker docker documentation](https://github.com/torrust/torrust-tracker/tree/develop/docker). //! //! # Configuration //! From 5a0441b75b77a02264be725650e25adbdd839602 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 8 Aug 2023 09:42:47 +0100 Subject: [PATCH 0041/1297] docs: fix coverage badge on README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9d2838a88..b419c12c1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Torrust Tracker -[![Build & Release](https://github.com/torrust/torrust-tracker/actions/workflows/build_release.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/build_release.yml) [![CI](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml) [![Publish crate](https://github.com/torrust/torrust-tracker/actions/workflows/publish_crate.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/publish_crate.yml) [![Publish docker image](https://github.com/torrust/torrust-tracker/actions/workflows/publish_docker_image.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/publish_docker_image.yml) [![Test](https://github.com/torrust/torrust-tracker/actions/workflows/test.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test.yml) [![Test docker build](https://github.com/torrust/torrust-tracker/actions/workflows/test_docker.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test_docker.yml) [![Upload code coverage](https://github.com/torrust/torrust-tracker/actions/workflows/codecov.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/codecov.yml) +[![Build & Release](https://github.com/torrust/torrust-tracker/actions/workflows/build_release.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/build_release.yml) [![CI](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml) [![Publish crate](https://github.com/torrust/torrust-tracker/actions/workflows/publish_crate.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/publish_crate.yml) [![Publish docker image](https://github.com/torrust/torrust-tracker/actions/workflows/publish_docker_image.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/publish_docker_image.yml) [![Test](https://github.com/torrust/torrust-tracker/actions/workflows/test.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test.yml) [![Test docker build](https://github.com/torrust/torrust-tracker/actions/workflows/test_docker.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test_docker.yml) [![Coverage](https://github.com/torrust/torrust-tracker/actions/workflows/coverage.yaml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/coverage.yaml) Torrust Tracker is a lightweight but incredibly high-performance and feature-rich BitTorrent tracker written in [Rust](https://www.rust-lang.org/). From 8a79fbea235ef84039957c1500e3e12466bc6080 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 8 Aug 2023 10:22:12 +0100 Subject: [PATCH 0042/1297] refactor: [#361] extract mod for configuration --- src/bootstrap/app.rs | 31 +------------------------------ src/bootstrap/config.rs | 37 +++++++++++++++++++++++++++++++++++++ src/bootstrap/mod.rs | 1 + 3 files changed, 39 insertions(+), 30 deletions(-) create mode 100644 src/bootstrap/config.rs diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index c0e688a0d..6961e15f0 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -11,11 +11,11 @@ //! 2. Initialize static variables. //! 3. Initialize logging. //! 4. Initialize the domain tracker. -use std::env; use std::sync::Arc; use torrust_tracker_configuration::Configuration; +use super::config::initialize_configuration; use crate::bootstrap; use crate::shared::clock::static_time; use crate::shared::crypto::ephemeral_instance_keys; @@ -55,35 +55,6 @@ pub fn initialize_static() { lazy_static::initialize(&ephemeral_instance_keys::RANDOM_SEED); } -/// It loads the application configuration from the environment. -/// -/// There are two methods to inject the configuration: -/// -/// 1. By using a config file: `config.toml`. The file must be in the same folder where you are running the tracker. -/// 2. Environment variable: `TORRUST_TRACKER_CONFIG`. The variable contains the same contents as the `config.toml` file. -/// -/// Environment variable has priority over the config file. -/// -/// Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) for the configuration options. -/// -/// # Panics -/// -/// Will panic if it can't load the configuration from either -/// `./config.toml` file or the env var `TORRUST_TRACKER_CONFIG`. -#[must_use] -fn initialize_configuration() -> Configuration { - const CONFIG_PATH: &str = "./config.toml"; - const CONFIG_ENV_VAR_NAME: &str = "TORRUST_TRACKER_CONFIG"; - - if env::var(CONFIG_ENV_VAR_NAME).is_ok() { - println!("Loading configuration from env var {CONFIG_ENV_VAR_NAME}"); - Configuration::load_from_env_var(CONFIG_ENV_VAR_NAME).unwrap() - } else { - println!("Loading configuration from config file {CONFIG_PATH}"); - Configuration::load_from_file(CONFIG_PATH).unwrap() - } -} - /// It builds the domain tracker /// /// The tracker is the domain layer service. It's the entrypoint to make requests to the domain layer. diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs new file mode 100644 index 000000000..187fddd0b --- /dev/null +++ b/src/bootstrap/config.rs @@ -0,0 +1,37 @@ +//! Initialize configuration from file or env var. +//! +//! All environment variables are prefixed with `TORRUST_TRACKER_BACK_`. +use std::env; + +use torrust_tracker_configuration::Configuration; + +// Environment variables + +const CONFIG_PATH: &str = "./config.toml"; +const CONFIG_ENV_VAR_NAME: &str = "TORRUST_TRACKER_CONFIG"; + +/// It loads the application configuration from the environment. +/// +/// There are two methods to inject the configuration: +/// +/// 1. By using a config file: `config.toml`. The file must be in the same folder where you are running the tracker. +/// 2. Environment variable: `TORRUST_TRACKER_CONFIG`. The variable contains the same contents as the `config.toml` file. +/// +/// Environment variable has priority over the config file. +/// +/// Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) for the configuration options. +/// +/// # Panics +/// +/// Will panic if it can't load the configuration from either +/// `./config.toml` file or the env var `TORRUST_TRACKER_CONFIG`. +#[must_use] +pub fn initialize_configuration() -> Configuration { + if env::var(CONFIG_ENV_VAR_NAME).is_ok() { + println!("Loading configuration from env var {CONFIG_ENV_VAR_NAME}"); + Configuration::load_from_env_var(CONFIG_ENV_VAR_NAME).unwrap() + } else { + println!("Loading configuration from config file {CONFIG_PATH}"); + Configuration::load_from_file(CONFIG_PATH).unwrap() + } +} diff --git a/src/bootstrap/mod.rs b/src/bootstrap/mod.rs index e39cf3adc..22044aafd 100644 --- a/src/bootstrap/mod.rs +++ b/src/bootstrap/mod.rs @@ -6,5 +6,6 @@ //! like cleaning torrents, and other jobs because they can be enabled/disabled depending on the configuration. //! For example, you can have more than one UDP and HTTP tracker, each server is executed like a independent job. pub mod app; +pub mod config; pub mod jobs; pub mod logging; From 0adf373bca011c7985277066a7f20138785bc35f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 8 Aug 2023 10:38:43 +0100 Subject: [PATCH 0043/1297] refactor: [#361] rename constants representing env vars All of then have the ENV_VAR prefix now. Like in the Index Backend. So we can identify constants that are related to env vars. --- src/bootstrap/config.rs | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 187fddd0b..2b0740f0e 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -7,14 +7,19 @@ use torrust_tracker_configuration::Configuration; // Environment variables -const CONFIG_PATH: &str = "./config.toml"; -const CONFIG_ENV_VAR_NAME: &str = "TORRUST_TRACKER_CONFIG"; +/// The whole `config.toml` file content. It has priority over the config file. +/// Even if the file is not on the default path. +const ENV_VAR_CONFIG: &str = "TORRUST_TRACKER_CONFIG"; + +// Default values + +const ENV_VAR_DEFAULT_CONFIG_PATH: &str = "./config.toml"; /// It loads the application configuration from the environment. /// /// There are two methods to inject the configuration: /// -/// 1. By using a config file: `config.toml`. The file must be in the same folder where you are running the tracker. +/// 1. By using a config file: `config.toml`. /// 2. Environment variable: `TORRUST_TRACKER_CONFIG`. The variable contains the same contents as the `config.toml` file. /// /// Environment variable has priority over the config file. @@ -27,11 +32,13 @@ const CONFIG_ENV_VAR_NAME: &str = "TORRUST_TRACKER_CONFIG"; /// `./config.toml` file or the env var `TORRUST_TRACKER_CONFIG`. #[must_use] pub fn initialize_configuration() -> Configuration { - if env::var(CONFIG_ENV_VAR_NAME).is_ok() { - println!("Loading configuration from env var {CONFIG_ENV_VAR_NAME}"); - Configuration::load_from_env_var(CONFIG_ENV_VAR_NAME).unwrap() + if env::var(ENV_VAR_CONFIG).is_ok() { + println!("Loading configuration from env var {ENV_VAR_CONFIG}"); + + Configuration::load_from_env_var(ENV_VAR_CONFIG).unwrap() } else { - println!("Loading configuration from config file {CONFIG_PATH}"); - Configuration::load_from_file(CONFIG_PATH).unwrap() + println!("Loading configuration from config file {ENV_VAR_DEFAULT_CONFIG_PATH}"); + + Configuration::load_from_file(ENV_VAR_DEFAULT_CONFIG_PATH).unwrap() } } From 702dd1433a850090d02417b82cfb7ebc45510898 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 8 Aug 2023 10:56:45 +0100 Subject: [PATCH 0044/1297] feat: allow to change the config.toml file path Now you can change the deafult location for the config file with an env var: ``` TORRUST_IDX_BACK_CONFIG_PATH="./storage/config.toml" cargo run ``` The default location is still `./config.toml` --- packages/configuration/src/lib.rs | 5 +++-- src/bootstrap/config.rs | 14 ++++++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index f785aa976..ff604fa4e 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -512,10 +512,11 @@ impl Configuration { if Path::new(path).exists() { config = config_builder.add_source(File::with_name(path)).build()?; } else { - warn!("No config file found."); - warn!("Creating config file.."); + warn!("No config file found. Creating config file ..."); + let config = Configuration::default(); config.save_to_file(path)?; + return Err(Error::CreatedNewConfigHalt { location: Location::caller(), path: path.to_string(), diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 2b0740f0e..398d98563 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -2,6 +2,7 @@ //! //! All environment variables are prefixed with `TORRUST_TRACKER_BACK_`. use std::env; +use std::path::Path; use torrust_tracker_configuration::Configuration; @@ -11,6 +12,9 @@ use torrust_tracker_configuration::Configuration; /// Even if the file is not on the default path. const ENV_VAR_CONFIG: &str = "TORRUST_TRACKER_CONFIG"; +/// The `config.toml` file location. +pub const ENV_VAR_CONFIG_PATH: &str = "TORRUST_IDX_BACK_CONFIG_PATH"; + // Default values const ENV_VAR_DEFAULT_CONFIG_PATH: &str = "./config.toml"; @@ -37,8 +41,14 @@ pub fn initialize_configuration() -> Configuration { Configuration::load_from_env_var(ENV_VAR_CONFIG).unwrap() } else { - println!("Loading configuration from config file {ENV_VAR_DEFAULT_CONFIG_PATH}"); + let config_path = env::var(ENV_VAR_CONFIG_PATH).unwrap_or_else(|_| ENV_VAR_DEFAULT_CONFIG_PATH.to_string()); + + if Path::new(&config_path).is_file(){ + println!("Loading configuration from config file: `{config_path}`"); + } else { + println!("Creating default config file: `{config_path}`"); + } - Configuration::load_from_file(ENV_VAR_DEFAULT_CONFIG_PATH).unwrap() + Configuration::load_from_file(&config_path).expect("Error loading configuration from file") } } From 8936c6e747b7060cd01df03b711d6133fda242c6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 8 Aug 2023 11:55:26 +0100 Subject: [PATCH 0045/1297] feat!: continue running the tracker after creating default config file Instead of halting the program, not the tracker continues the execution when no config.toml file is provided and the default one is created. It shows some messages: ``` Loading configuration from configuration file: `./config.toml` ... Missing configuration file. Creating a default configuration file: `./config.toml` ... Please review the config file: `./config.toml` and restart the tracker if needed. 2023-08-08T11:56:26.957162508+01:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized. 2023-08-08T11:56:26.957931296+01:00 [torrust_tracker::bootstrap::jobs::tracker_apis][INFO] Starting Torrust APIs server on: http://127.0.0.1:1212 2023-08-08T11:56:26.958027355+01:00 [torrust_tracker::bootstrap::jobs::tracker_apis][INFO] Torrust APIs server started ``` --- packages/configuration/src/lib.rs | 42 +++++++++++-------------------- src/bootstrap/config.rs | 31 +++++++++++++++++------ 2 files changed, 37 insertions(+), 36 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index ff604fa4e..6de0e3ed7 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -228,14 +228,11 @@ //!``` use std::collections::{HashMap, HashSet}; use std::net::IpAddr; -use std::panic::Location; -use std::path::Path; use std::str::FromStr; use std::sync::Arc; use std::{env, fs}; use config::{Config, ConfigError, File, FileFormat}; -use log::warn; use serde::{Deserialize, Serialize}; use serde_with::{serde_as, NoneAsEmptyString}; use thiserror::Error; @@ -414,17 +411,6 @@ pub enum Error { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, }, - /// If you run the tracker without providing the configuration (via the - /// `TORRUST_TRACKER_CONFIG` environment variable or configuration file), - /// the tracker will create a default configuration file but it will not - /// load it. It will return this error instead and you have to restart the - /// it. - #[error("Default configuration created at: `{path}`, please review and reload tracker, {location}")] - CreatedNewConfigHalt { - location: &'static Location<'static>, - path: String, - }, - /// Unable to load the configuration from the configuration file. #[error("Failed processing the configuration: {source}")] ConfigError { source: LocatedError<'static, ConfigError> }, @@ -502,32 +488,32 @@ impl Configuration { /// /// # Errors /// - /// Will return `Err` if `path` does not exist or has a bad configuration. + /// Will return `Err` if `path` does not exist or has a bad configuration. pub fn load_from_file(path: &str) -> Result { let config_builder = Config::builder(); #[allow(unused_assignments)] let mut config = Config::default(); - if Path::new(path).exists() { - config = config_builder.add_source(File::with_name(path)).build()?; - } else { - warn!("No config file found. Creating config file ..."); - - let config = Configuration::default(); - config.save_to_file(path)?; - - return Err(Error::CreatedNewConfigHalt { - location: Location::caller(), - path: path.to_string(), - }); - } + config = config_builder.add_source(File::with_name(path)).build()?; let torrust_config: Configuration = config.try_deserialize()?; Ok(torrust_config) } + /// Saves the default configuration at the given path. + /// + /// # Errors + /// + /// Will return `Err` if `path` is not a valid path or the configuration + /// file cannot be created. + pub fn create_default_configuration_file(path: &str) -> Result { + let config = Configuration::default(); + config.save_to_file(path)?; + Ok(config) + } + /// Loads the configuration from the environment variable. The whole /// configuration must be in the environment variable. It contains the same /// configuration as the configuration file with the same format. diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 398d98563..eef3265f9 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -4,7 +4,7 @@ use std::env; use std::path::Path; -use torrust_tracker_configuration::Configuration; +use torrust_tracker_configuration::{Configuration, Error}; // Environment variables @@ -37,18 +37,33 @@ const ENV_VAR_DEFAULT_CONFIG_PATH: &str = "./config.toml"; #[must_use] pub fn initialize_configuration() -> Configuration { if env::var(ENV_VAR_CONFIG).is_ok() { - println!("Loading configuration from env var {ENV_VAR_CONFIG}"); + println!("Loading configuration from env var {ENV_VAR_CONFIG} ..."); Configuration::load_from_env_var(ENV_VAR_CONFIG).unwrap() } else { let config_path = env::var(ENV_VAR_CONFIG_PATH).unwrap_or_else(|_| ENV_VAR_DEFAULT_CONFIG_PATH.to_string()); - if Path::new(&config_path).is_file(){ - println!("Loading configuration from config file: `{config_path}`"); - } else { - println!("Creating default config file: `{config_path}`"); - } + println!("Loading configuration from configuration file: `{config_path}` ..."); - Configuration::load_from_file(&config_path).expect("Error loading configuration from file") + load_from_file_or_create_default(&config_path).unwrap() + } +} + +/// Loads the configuration from the configuration file. If the file does +/// not exist, it will create a default configuration file and return an +/// error. +/// +/// # Errors +/// +/// Will return `Err` if `path` does not exist or has a bad configuration. +fn load_from_file_or_create_default(path: &str) -> Result { + if Path::new(&path).is_file() { + Configuration::load_from_file(path) + } else { + println!("Missing configuration file."); + println!("Creating a default configuration file: `{path}` ..."); + let config = Configuration::create_default_configuration_file(path)?; + println!("Please review the config file: `{path}` and restart the tracker if needed."); + Ok(config) } } From ec7bd7d8a14e050d695941d93cd5691e28e4a4c3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 8 Aug 2023 12:25:56 +0100 Subject: [PATCH 0046/1297] fix: env var name. Wrong prefix --- src/bootstrap/config.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index eef3265f9..727bf59f7 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -13,7 +13,7 @@ use torrust_tracker_configuration::{Configuration, Error}; const ENV_VAR_CONFIG: &str = "TORRUST_TRACKER_CONFIG"; /// The `config.toml` file location. -pub const ENV_VAR_CONFIG_PATH: &str = "TORRUST_IDX_BACK_CONFIG_PATH"; +pub const ENV_VAR_CONFIG_PATH: &str = "TORRUST_TRACKER_CONFIG_PATH"; // Default values From 38eea4689ed0fd92ca0614a95c093a6981208357 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 9 Aug 2023 09:33:12 +0100 Subject: [PATCH 0047/1297] chore: update dependencies - Bump serde_with from 3.0 to 3.2 - Bump axum from 0.6.18 to 0.6.20 --- Cargo.lock | 329 +++++++++++++++--------------- Cargo.toml | 4 +- packages/configuration/Cargo.toml | 2 +- 3 files changed, 162 insertions(+), 173 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 20557f7c8..f1ae8cad0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -50,9 +50,9 @@ dependencies = [ [[package]] name = "allocator-api2" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56fc6cf8dc8c4158eed8649f9b8b0ea1518eb62b544fe9490d66fa0b349eafe9" +checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" [[package]] name = "android-tzdata" @@ -93,13 +93,13 @@ checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "async-trait" -version = "0.1.71" +version = "0.1.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a564d521dd56509c4c47480d00b80ee55f7e385ae48db5744c67ad50c92d2ebf" +checksum = "cc6dde6e4ed435a4c1ee4e73592f5ba9da2151af10076cc04858746af9352d09" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] @@ -110,9 +110,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axum" -version = "0.6.18" +version = "0.6.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8175979259124331c1d7bf6586ee7e0da434155e4b2d48ec2c8386281d8df39" +checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf" dependencies = [ "async-trait", "axum-core", @@ -386,9 +386,12 @@ checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" [[package]] name = "cc" -version = "1.0.79" +version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" +checksum = "305fe645edc1442a0fa8b6726ba61d422798d37a52e12eaecf4b022ebbb88f01" +dependencies = [ + "libc", +] [[package]] name = "cexpr" @@ -576,9 +579,9 @@ dependencies = [ [[package]] name = "darling" -version = "0.20.1" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0558d22a7b463ed0241e993f76f09f30b126687447751a8638587b864e4b3944" +checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e" dependencies = [ "darling_core", "darling_macro", @@ -586,27 +589,36 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.20.1" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab8bfa2e259f8ee1ce5e97824a3c55ec4404a0d772ca7fa96bf19f0752a046eb" +checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621" dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", "strsim", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] name = "darling_macro" -version = "0.20.1" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29a358ff9f12ec09c3e61fef9b5a9902623a695a46a917b07f269bff1445611a" +checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ "darling_core", "quote", - "syn 2.0.23", + "syn 2.0.28", +] + +[[package]] +name = "deranged" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7684a49fb1af197853ef7b2ee694bc1f5b4179556f1e5710e1760c5db6f5e929" +dependencies = [ + "serde", ] [[package]] @@ -624,13 +636,13 @@ dependencies = [ [[package]] name = "derive_utils" -version = "0.13.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20ce151e1b790e3e36d767ae57691240feafe8b605e1c2fe081183d64ac1bff3" +checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] @@ -663,9 +675,9 @@ checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" [[package]] name = "either" -version = "1.8.1" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" +checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" [[package]] name = "encoding_rs" @@ -678,15 +690,15 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88bffebc5d80432c9b140ee17875ff173a8ab62faad5b257da912bd2f6c1c0a1" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" +checksum = "6b30f669a7961ef1631673d2766cc92f52d64f7ef354d4fe0ddfd30ed52f0f4f" dependencies = [ "errno-dragonfly", "libc", @@ -726,12 +738,9 @@ checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" [[package]] name = "fastrand" -version = "1.9.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" -dependencies = [ - "instant", -] +checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764" [[package]] name = "fern" @@ -833,7 +842,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] @@ -845,7 +854,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] @@ -857,7 +866,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] @@ -922,7 +931,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] @@ -1185,15 +1194,7 @@ checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" dependencies = [ "equivalent", "hashbrown 0.14.0", -] - -[[package]] -name = "instant" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" -dependencies = [ - "cfg-if", + "serde", ] [[package]] @@ -1203,18 +1204,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.23", -] - -[[package]] -name = "io-lifetimes" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" -dependencies = [ - "hermit-abi", - "libc", - "windows-sys", + "syn 2.0.28", ] [[package]] @@ -1234,9 +1224,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.8" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b02a5381cc465bd3041d84623d0fa3b66738b52b8e2fc3bab8ad63ab032f4a" +checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" [[package]] name = "js-sys" @@ -1372,9 +1362,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.9" +version = "1.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56ee889ecc9568871456d42f603d6a0ce59ff328d291063a45cbdf0036baf6db" +checksum = "d97137b25e321a73eef1418d1d5d2eda4d77e12813f8e6dead84bc52c5870a7b" dependencies = [ "cc", "pkg-config", @@ -1389,15 +1379,15 @@ checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" [[package]] name = "linux-raw-sys" -version = "0.3.8" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" +checksum = "57bcfdad1b858c2db7c38303a6d2ad4dfaf5eb53dfeb0910128b2c26d6158503" [[package]] name = "local-ip-address" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2815836665de176ba66deaa449ada98fdf208d84730d1a84a22cbeed6151a6fa" +checksum = "885efb07efcd6ae1c6af70be7565544121424fa9e5b1c3e4b58bbbf141a58cef" dependencies = [ "libc", "neli", @@ -1432,9 +1422,9 @@ dependencies = [ [[package]] name = "matchit" -version = "0.7.0" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b87248edafb776e59e6ee64a79086f65890d3510f2c656c000bf2a7e8a0aea40" +checksum = "ed1202b2a6f884ae56f04cff409ab315c5ce26b5e58d7412e484f01fd52f52ef" [[package]] name = "memchr" @@ -1679,9 +1669,9 @@ dependencies = [ [[package]] name = "num-traits" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" dependencies = [ "autocfg", ] @@ -1713,9 +1703,9 @@ checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" [[package]] name = "openssl" -version = "0.10.55" +version = "0.10.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "345df152bc43501c5eb9e4654ff05f794effb78d4efe3d53abc158baddc0703d" +checksum = "729b745ad4a5575dd06a3e1af1414bd330ee561c01b3899eb584baeaa8def17e" dependencies = [ "bitflags 1.3.2", "cfg-if", @@ -1734,7 +1724,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] @@ -1745,18 +1735,18 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "111.26.0+1.1.1u" +version = "111.27.0+1.1.1v" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efc62c9f12b22b8f5208c23a7200a442b2e5999f8bdf80233852122b5a4f6f37" +checksum = "06e8f197c82d7511c5b014030c9b1efeda40d7d5f99d23b4ceed3524a5e63f02" dependencies = [ "cc", ] [[package]] name = "openssl-sys" -version = "0.9.90" +version = "0.9.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "374533b0e45f3a7ced10fcaeccca020e66656bc03dac384f852e4e5a7a8104a6" +checksum = "866b5f16f90776b9bb8dc1e1802ac6f0513de3a7a7465867bfbc563dc737faac" dependencies = [ "cc", "libc", @@ -1827,9 +1817,9 @@ checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" [[package]] name = "pest" -version = "2.7.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f73935e4d55e2abf7f130186537b19e7a4abc886a0252380b59248af473a3fc9" +checksum = "1acb4a4365a13f749a93f1a094a7805e5cfa0955373a9de860d962eaa3a5fe5a" dependencies = [ "thiserror", "ucd-trie", @@ -1837,9 +1827,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aef623c9bbfa0eedf5a0efba11a5ee83209c326653ca31ff019bec3a95bfff2b" +checksum = "666d00490d4ac815001da55838c500eafb0320019bbaa44444137c48b443a853" dependencies = [ "pest", "pest_generator", @@ -1847,22 +1837,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3e8cba4ec22bada7fc55ffe51e2deb6a0e0db2d0b7ab0b103acc80d2510c190" +checksum = "68ca01446f50dbda87c1786af8770d535423fa8a53aec03b8f4e3d7eb10e0929" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] name = "pest_meta" -version = "2.7.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a01f71cb40bd8bb94232df14b946909e14660e33fc05db3e50ae2a82d7ea0ca0" +checksum = "56af0a30af74d0445c0bf6d9d051c979b516a1a5af790d251daee76005420a48" dependencies = [ "once_cell", "pest", @@ -1871,29 +1861,29 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "030ad2bc4db10a8944cb0d837f158bdfec4d4a4873ab701a95046770d11f8842" +checksum = "fda4ed1c6c173e3fc7a83629421152e01d7b1f9b7f65fb301e490e8cfc656422" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec2e072ecce94ec471b13398d5402c188e76ac03cf74dd1a975161b23a3f6d9c" +checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] name = "pin-project-lite" -version = "0.2.10" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c40d25201921e5ff0c862a505c6557ea88568a4e3ace775ab55e93f2f4f9d57" +checksum = "2c516611246607d0c04186886dbb3a754368ef82c79e9827a802c6d836dd111c" [[package]] name = "pin-utils" @@ -1954,9 +1944,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.63" +version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b368fba921b0dce7e60f5e04ec15e565b3303972b42bcfde1d0713b881959eb" +checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9" dependencies = [ "unicode-ident", ] @@ -1983,9 +1973,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.29" +version = "1.0.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "573015e8ab27661678357f27dc26460738fd2b6c86e46f386fde94cb5d913105" +checksum = "50f3b39ccfb720540debaa0164757101c08ecb8d326b15358ce76a62c7e85965" dependencies = [ "proc-macro2", ] @@ -2069,9 +2059,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.9.0" +version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89089e897c013b3deb627116ae56a6955a72b8bed395c9526af31c9fe528b484" +checksum = "81bc1d4caf89fac26a70747fe603c130093b53c773888797a6329091246d651a" dependencies = [ "aho-corasick", "memchr", @@ -2081,9 +2071,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.3.0" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa250384981ea14565685dea16a9ccc4d1c541a13f82b9c168572264d1df8c56" +checksum = "fed1ceff11a1dddaee50c9dc8e4938bd106e9d89ae372f192311e7da498e3b69" dependencies = [ "aho-corasick", "memchr", @@ -2092,9 +2082,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab07dc67230e4a4718e70fd5c20055a4334b121f1f9db8fe63ef39ce9b8c846" +checksum = "e5ea92a5b6195c6ef2a0295ea818b312502c6fc94dde986c5553242e18fd4ce2" [[package]] name = "rend" @@ -2222,13 +2212,12 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.30.0" +version = "1.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0446843641c69436765a35a5a77088e28c2e6a12da93e84aa3ab1cd4aa5a042" +checksum = "4a2ab0025103a60ecaaf3abf24db1db240a4e1c15837090d2c32f625ac98abea" dependencies = [ "arrayvec", "borsh", - "bytecheck", "byteorder", "bytes", "num-traits", @@ -2261,13 +2250,12 @@ dependencies = [ [[package]] name = "rustix" -version = "0.37.23" +version = "0.38.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d69718bf81c6127a49dc64e44a742e8bb9213c0ff8869a22c308f84c1d4ab06" +checksum = "172891ebdceb05aa0005f533a6cbfca599ddd7d966f6f5d4d9b2e70478e70399" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.3.3", "errno", - "io-lifetimes", "libc", "linux-raw-sys", "windows-sys", @@ -2275,9 +2263,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.21.3" +version = "0.21.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b19faa85ecb5197342b54f987b142fb3e30d0c90da40f80ef4fa9a726e6676ed" +checksum = "1d1feddffcfcc0b33f5c6ce9a29e341e4cd59c3f78e7ee45f4a40c038b1d6cbb" dependencies = [ "log", "ring", @@ -2296,9 +2284,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.101.1" +version = "0.101.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15f36a6828982f422756984e47912a7a51dcbc2a197aa791158f8ca61cd8204e" +checksum = "261e9e0888cba427c3316e6322805653c9425240b6fd96cee7cb671ab70ab8d0" dependencies = [ "ring", "untrusted", @@ -2306,15 +2294,15 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.13" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc31bd9b61a32c31f9650d18add92aa83a49ba979c143eefd27fe7177b05bd5f" +checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" [[package]] name = "ryu" -version = "1.0.14" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe232bdf6be8c8de797b22184ee71118d63780ea42ac85b61d1baa6d3b782ae9" +checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "saturating" @@ -2342,9 +2330,9 @@ dependencies = [ [[package]] name = "scopeguard" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sct" @@ -2364,9 +2352,9 @@ checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" [[package]] name = "security-framework" -version = "2.9.1" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fc758eb7bffce5b308734e9b0c1468893cae9ff70ebf13e7090be8dcbcc83a8" +checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de" dependencies = [ "bitflags 1.3.2", "core-foundation", @@ -2377,9 +2365,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.9.0" +version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f51d0c0d83bec45f16480d0ce0058397a69e48fcdc52d1dc8855fb68acbd31a7" +checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a" dependencies = [ "core-foundation-sys", "libc", @@ -2387,15 +2375,15 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" +checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" [[package]] name = "serde" -version = "1.0.167" +version = "1.0.183" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7daf513456463b42aa1d94cff7e0c24d682b429f020b9afa4f5ba5c40a22b237" +checksum = "32ac8da02677876d532745a130fc9d8e6edfa81a269b107c5b00829b91d8eb3c" dependencies = [ "serde_derive", ] @@ -2412,29 +2400,29 @@ dependencies = [ [[package]] name = "serde_bytes" -version = "0.11.11" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a16be4fe5320ade08736447e3198294a5ea9a6d44dde6f35f0a5e06859c427a" +checksum = "ab33ec92f677585af6d88c65593ae2375adde54efdbf16d597f2cbc7a6d368ff" dependencies = [ "serde", ] [[package]] name = "serde_derive" -version = "1.0.167" +version = "1.0.183" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b69b106b68bc8054f0e974e70d19984040f8a5cf9215ca82626ea4853f82c4b9" +checksum = "aafe972d60b0b9bee71a91b92fee2d4fb3c9d7e8f6b179aa99f27203d99a4816" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] name = "serde_json" -version = "1.0.100" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f1e14e89be7aa4c4b78bdbdc9eb5bf8517829a600ae8eaa39a6e1d960b5185c" +checksum = "076066c5f1078eac5b722a31827a8832fe108bed65dfa75e233c89f8206e976c" dependencies = [ "itoa", "ryu", @@ -2443,9 +2431,9 @@ dependencies = [ [[package]] name = "serde_path_to_error" -version = "0.1.13" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8acc4422959dd87a76cb117c191dcbffc20467f06c9100b76721dab370f24d3a" +checksum = "4beec8bce849d58d06238cb50db2e1c417cfeafa4c63f692b15c82b7c80f8335" dependencies = [ "itoa", "serde", @@ -2453,13 +2441,13 @@ dependencies = [ [[package]] name = "serde_repr" -version = "0.1.14" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d89a8107374290037607734c0b73a85db7ed80cae314b3c5791f192a496e731" +checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] @@ -2485,14 +2473,15 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.0.0" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f02d8aa6e3c385bf084924f660ce2a3a6bd333ba55b35e8590b321f35d88513" +checksum = "1402f54f9a3b9e2efe71c1cea24e648acce55887983553eeb858cf3115acfd49" dependencies = [ "base64 0.21.2", "chrono", "hex", "indexmap 1.9.3", + "indexmap 2.0.0", "serde", "serde_json", "serde_with_macros", @@ -2501,14 +2490,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.0.0" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edc7d5d3932fb12ce722ee5e64dd38c504efba37567f0c402f6ca728c3b8b070" +checksum = "9197f1ad0e3c173a0222d3c4404fb04c3afe87e962bcb327af73e8301fa203c7" dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] @@ -2620,9 +2609,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.23" +version = "2.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59fb7d6d8281a51045d62b8eb3a7d1ce347b76f312af50cd3dc0af39c87c1737" +checksum = "04361975b3f5e348b2189d8dc55bc942f278b2d482a6a0365de5bdd62d351567" dependencies = [ "proc-macro2", "quote", @@ -2643,11 +2632,10 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "tempfile" -version = "3.6.0" +version = "3.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31c0432476357e58790aaa47a8efb0c5138f137343f3b5f23bd36a27e3b0a6d6" +checksum = "dc02fddf48964c42031a0b3fe0428320ecf3a73c401040fc0096f97794310651" dependencies = [ - "autocfg", "cfg-if", "fastrand", "redox_syscall", @@ -2663,30 +2651,31 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.43" +version = "1.0.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a35fc5b8971143ca348fa6df4f024d4d55264f3468c71ad1c2f365b0a4d58c42" +checksum = "611040a08a0439f8248d1990b111c95baa9c704c805fa1f62104b39655fd7f90" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.43" +version = "1.0.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "463fe12d7993d3b327787537ce8dd4dfa058de32fc2b195ef3cde03dc4771e8f" +checksum = "090198534930841fab3a5d1bb637cde49e339654e606195f8d9c76eeb081dc96" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] name = "time" -version = "0.3.22" +version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea9e1b3cf1243ae005d9e74085d4d542f3125458f3a81af210d901dcd7411efd" +checksum = "b0fdd63d58b18d663fbdf70e049f00a22c8e42be082203be7f26589213cd75ea" dependencies = [ + "deranged", "itoa", "serde", "time-core", @@ -2701,9 +2690,9 @@ checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb" [[package]] name = "time-macros" -version = "0.2.9" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "372950940a5f07bf38dbe211d7283c9e6d7327df53794992d293e534c733d09b" +checksum = "eb71511c991639bb078fd5bf97757e03914361c48100d52878b8e52b46fb92cd" dependencies = [ "time-core", ] @@ -2750,7 +2739,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", ] [[package]] @@ -2819,9 +2808,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.19.12" +version = "0.19.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c500344a19072298cd05a7224b3c0c629348b78692bf48466c5238656e315a78" +checksum = "f8123f27e969974a3dfba720fdb560be359f57b44302d280ba72e76a74480e8a" dependencies = [ "indexmap 2.0.0", "serde", @@ -2990,9 +2979,9 @@ checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" [[package]] name = "ucd-trie" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81" +checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" [[package]] name = "unicode-bidi" @@ -3002,9 +2991,9 @@ checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" [[package]] name = "unicode-ident" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22049a19f4a68748a168c0fc439f9516686aa045927ff767eca0a85101fb6e73" +checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c" [[package]] name = "unicode-normalization" @@ -3034,9 +3023,9 @@ dependencies = [ [[package]] name = "uuid" -version = "1.4.0" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d023da39d1fde5a8a3fe1f3e01ca9632ada0a63e9797de55a879d6e2236277be" +checksum = "79daa5ed5740825c40b389c5e50312b9c86df53fccd33f281df655642b43869d" dependencies = [ "getrandom", "rand", @@ -3090,7 +3079,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", "wasm-bindgen-shared", ] @@ -3124,7 +3113,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.23", + "syn 2.0.28", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -3244,9 +3233,9 @@ checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" [[package]] name = "winnow" -version = "0.4.8" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9482fe6ceabdf32f3966bfdd350ba69256a97c30253dc616fe0005af24f164e" +checksum = "acaaa1190073b2b101e15083c38ee8ec891b5e05cbee516521e94ec008f61e64" dependencies = [ "memchr", ] diff --git a/Cargo.toml b/Cargo.toml index 152495463..e87f7b972 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ tokio = { version = "1.29", features = ["rt-multi-thread", "net", "sync", "macro serde = { version = "1.0", features = ["derive"] } serde_bencode = "^0.2" serde_json = "1.0" -serde_with = "3.0" +serde_with = "3.2" percent-encoding = "2.2" binascii = "0.1" lazy_static = "1.4" @@ -38,7 +38,7 @@ futures = "0.3" async-trait = "0.1" aquatic_udp_protocol = "0.8" uuid = { version = "1", features = ["v4"] } -axum = "0.6.18" +axum = "0.6.20" axum-server = { version = "0.5", features = ["tls-rustls"] } axum-client-ip = "0.4.1" bip_bencode = "0.4" diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index a6cf57710..9b91534e9 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -9,7 +9,7 @@ version.workspace = true [dependencies] serde = { version = "1.0", features = ["derive"] } -serde_with = "3.0" +serde_with = "3.2" config = "0.13" toml = "0.7" log = { version = "0.4", features = ["release_max_level_info"] } From ba61af0f0a31268c03bbe4eab80be63006f74671 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 21 Aug 2023 16:32:47 +0200 Subject: [PATCH 0048/1297] chore: fix new clippy warning --- src/servers/apis/v1/context/auth_key/handlers.rs | 4 ++-- src/servers/apis/v1/context/whitelist/handlers.rs | 6 +++--- src/servers/http/v1/handlers/announce.rs | 4 ++-- src/servers/http/v1/handlers/scrape.rs | 2 +- src/servers/signals.rs | 6 +++--- src/servers/udp/server.rs | 4 ++-- src/tracker/mod.rs | 2 +- tests/servers/udp/client.rs | 2 +- 8 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index 57d55d4c0..85158c698 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -70,7 +70,7 @@ pub async fn delete_auth_key_handler( match Key::from_str(&seconds_valid_or_key.0) { Err(_) => invalid_auth_key_param_response(&seconds_valid_or_key.0), Ok(key) => match tracker.remove_auth_key(&key).await { - Ok(_) => ok_response(), + Ok(()) => ok_response(), Err(e) => failed_to_delete_key_response(e), }, } @@ -90,7 +90,7 @@ pub async fn delete_auth_key_handler( /// for more information about this endpoint. pub async fn reload_keys_handler(State(tracker): State>) -> Response { match tracker.load_keys_from_database().await { - Ok(_) => ok_response(), + Ok(()) => ok_response(), Err(e) => failed_to_reload_keys_response(e), } } diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/src/servers/apis/v1/context/whitelist/handlers.rs index 8e8c20b50..bd1da735e 100644 --- a/src/servers/apis/v1/context/whitelist/handlers.rs +++ b/src/servers/apis/v1/context/whitelist/handlers.rs @@ -30,7 +30,7 @@ pub async fn add_torrent_to_whitelist_handler( match InfoHash::from_str(&info_hash.0) { Err(_) => invalid_info_hash_param_response(&info_hash.0), Ok(info_hash) => match tracker.add_torrent_to_whitelist(&info_hash).await { - Ok(_) => ok_response(), + Ok(()) => ok_response(), Err(e) => failed_to_whitelist_torrent_response(e), }, } @@ -53,7 +53,7 @@ pub async fn remove_torrent_from_whitelist_handler( match InfoHash::from_str(&info_hash.0) { Err(_) => invalid_info_hash_param_response(&info_hash.0), Ok(info_hash) => match tracker.remove_torrent_from_whitelist(&info_hash).await { - Ok(_) => ok_response(), + Ok(()) => ok_response(), Err(e) => failed_to_remove_torrent_from_whitelist_response(e), }, } @@ -71,7 +71,7 @@ pub async fn remove_torrent_from_whitelist_handler( /// for more information about this endpoint. pub async fn reload_whitelist_handler(State(tracker): State>) -> Response { match tracker.load_whitelist_from_database().await { - Ok(_) => ok_response(), + Ok(()) => ok_response(), Err(e) => failed_to_reload_whitelist_response(e), } } diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 5b26b3758..0e49bd422 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -87,7 +87,7 @@ async fn handle_announce( if tracker.requires_authentication() { match maybe_key { Some(key) => match tracker.authenticate(&key).await { - Ok(_) => (), + Ok(()) => (), Err(error) => return Err(responses::error::Error::from(error)), }, None => { @@ -100,7 +100,7 @@ async fn handle_announce( // Authorization match tracker.authorize(&announce_request.info_hash).await { - Ok(_) => (), + Ok(()) => (), Err(error) => return Err(responses::error::Error::from(error)), } diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index b8c1cbea1..58b8aa84c 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -78,7 +78,7 @@ async fn handle_scrape( let return_real_scrape_data = if tracker.requires_authentication() { match maybe_key { Some(key) => match tracker.authenticate(&key).await { - Ok(_) => true, + Ok(()) => true, Err(_error) => false, }, None => false, diff --git a/src/servers/signals.rs b/src/servers/signals.rs index d34cca108..51f53738d 100644 --- a/src/servers/signals.rs +++ b/src/servers/signals.rs @@ -23,8 +23,8 @@ pub async fn global_shutdown_signal() { let terminate = std::future::pending::<()>(); tokio::select! { - _ = ctrl_c => {}, - _ = terminate => {} + () = ctrl_c => {}, + () = terminate => {} } } @@ -38,7 +38,7 @@ pub async fn shutdown_signal(stop_receiver: tokio::sync::oneshot::Receiver) tokio::select! { _ = stop => {}, - _ = global_shutdown_signal() => {} + () = global_shutdown_signal() => {} } } diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 3bb5bd013..5e5c98704 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -220,7 +220,7 @@ impl Udp { let socket = self.socket.clone(); tokio::select! { - _ = &mut shutdown_signal => { + () = &mut shutdown_signal => { info!("Stopping UDP server: {}..", self.socket.local_addr().unwrap()); break; } @@ -244,7 +244,7 @@ impl Udp { let mut cursor = Cursor::new(buffer); match response.write(&mut cursor) { - Ok(_) => { + Ok(()) => { #[allow(clippy::cast_possible_truncation)] let position = cursor.position() as usize; let inner = cursor.get_ref(); diff --git a/src/tracker/mod.rs b/src/tracker/mod.rs index 63c8b96d6..6823e8fe8 100644 --- a/src/tracker/mod.rs +++ b/src/tracker/mod.rs @@ -643,7 +643,7 @@ impl Tracker { for info_hash in info_hashes { let swarm_metadata = match self.authorize(info_hash).await { - Ok(_) => self.get_swarm_metadata(info_hash).await, + Ok(()) => self.get_swarm_metadata(info_hash).await, Err(_) => SwarmMetadata::zeroed(), }; scrape_data.add_file(info_hash, swarm_metadata); diff --git a/tests/servers/udp/client.rs b/tests/servers/udp/client.rs index 75467055e..d267adaba 100644 --- a/tests/servers/udp/client.rs +++ b/tests/servers/udp/client.rs @@ -55,7 +55,7 @@ impl UdpTrackerClient { let mut cursor = Cursor::new(request_buffer); let request_data = match request.write(&mut cursor) { - Ok(_) => { + Ok(()) => { #[allow(clippy::cast_possible_truncation)] let position = cursor.position() as usize; let inner_request_buffer = cursor.get_ref(); From 3a1ac86b306a3dcf0581bac990b0f1d41c067be3 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 21 Aug 2023 17:27:24 +0200 Subject: [PATCH 0049/1297] chore: update cargo lockfile --- Cargo.lock | 187 ++++++++++++++++++++++++++++------------------------- 1 file changed, 98 insertions(+), 89 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f1ae8cad0..32d35cbe2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -41,9 +41,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.0.2" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43f6cb1bf222025340178f382c426f13757b2960e89779dfcb319c32542a5a41" +checksum = "6748e8def348ed4d14996fa801f4122cd763fff530258cdc03f64b25f89d3a5a" dependencies = [ "memchr", ] @@ -93,13 +93,13 @@ checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "async-trait" -version = "0.1.72" +version = "0.1.73" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc6dde6e4ed435a4c1ee4e73592f5ba9da2151af10076cc04858746af9352d09" +checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -268,9 +268,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.3.3" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "630be753d4e58660abd17930c71b647fe46c27ea6b63cc59e1e3851406972e42" +checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" [[package]] name = "bitvec" @@ -386,9 +386,9 @@ checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" [[package]] name = "cc" -version = "1.0.82" +version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "305fe645edc1442a0fa8b6726ba61d422798d37a52e12eaecf4b022ebbb88f01" +checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" dependencies = [ "libc", ] @@ -598,7 +598,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -609,14 +609,14 @@ checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ "darling_core", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] name = "deranged" -version = "0.3.7" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7684a49fb1af197853ef7b2ee694bc1f5b4179556f1e5710e1760c5db6f5e929" +checksum = "f2696e8a945f658fd14dc3b87242e6b80cd0f36ff04ea560fa39082368847946" dependencies = [ "serde", ] @@ -642,7 +642,7 @@ checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" dependencies = [ "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -753,9 +753,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.26" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743" +checksum = "c6c98ee8095e9d1dcbf2fcc6d95acccb90d1c81db1e44725c6a984b1dbdfb010" dependencies = [ "crc32fast", "libz-sys", @@ -842,7 +842,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -854,7 +854,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -866,7 +866,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -931,7 +931,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -1095,9 +1095,9 @@ checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" [[package]] name = "httpdate" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" @@ -1116,7 +1116,7 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "socket2", + "socket2 0.4.9", "tokio", "tower-service", "tracing", @@ -1204,7 +1204,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -1407,9 +1407,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.19" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4" +checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" [[package]] name = "lru" @@ -1530,7 +1530,7 @@ dependencies = [ "percent-encoding", "serde", "serde_json", - "socket2", + "socket2 0.4.9", "twox-hash", "url", ] @@ -1724,7 +1724,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -1845,7 +1845,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -1876,14 +1876,14 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] name = "pin-project-lite" -version = "0.2.11" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c516611246607d0c04186886dbb3a754368ef82c79e9827a802c6d836dd111c" +checksum = "12cc1b0bf1727a77a54b6654e7b5f1af8604923edc8b81885f8ec92f9e3f0a05" [[package]] name = "pin-utils" @@ -1973,9 +1973,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.32" +version = "1.0.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50f3b39ccfb720540debaa0164757101c08ecb8d326b15358ce76a62c7e85965" +checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" dependencies = [ "proc-macro2", ] @@ -2192,7 +2192,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "549b9d036d571d42e6e85d1c1425e2ac83491075078ca9a15be021c56b1641f2" dependencies = [ - "bitflags 2.3.3", + "bitflags 2.4.0", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -2250,11 +2250,11 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.7" +version = "0.38.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "172891ebdceb05aa0005f533a6cbfca599ddd7d966f6f5d4d9b2e70478e70399" +checksum = "19ed4fa021d81c8392ce04db050a3da9a60299050b7ae1cf482d862b54a7218f" dependencies = [ - "bitflags 2.3.3", + "bitflags 2.4.0", "errno", "libc", "linux-raw-sys", @@ -2381,9 +2381,9 @@ checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" [[package]] name = "serde" -version = "1.0.183" +version = "1.0.171" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32ac8da02677876d532745a130fc9d8e6edfa81a269b107c5b00829b91d8eb3c" +checksum = "30e27d1e4fd7659406c492fd6cfaf2066ba8773de45ca75e855590f856dc34a9" dependencies = [ "serde_derive", ] @@ -2409,20 +2409,20 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.183" +version = "1.0.171" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aafe972d60b0b9bee71a91b92fee2d4fb3c9d7e8f6b179aa99f27203d99a4816" +checksum = "389894603bd18c46fa56231694f8d827779c0951a667087194cf9de94ed24682" dependencies = [ "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] name = "serde_json" -version = "1.0.104" +version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "076066c5f1078eac5b722a31827a8832fe108bed65dfa75e233c89f8206e976c" +checksum = "693151e1ac27563d6dbcec9dee9fbd5da8539b20fa14ad3752b2e6d363ace360" dependencies = [ "itoa", "ryu", @@ -2447,7 +2447,7 @@ checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -2473,9 +2473,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.2.0" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1402f54f9a3b9e2efe71c1cea24e648acce55887983553eeb858cf3115acfd49" +checksum = "1ca3b16a3d82c4088f343b7480a93550b3eabe1a358569c2dfe38bbcead07237" dependencies = [ "base64 0.21.2", "chrono", @@ -2490,14 +2490,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.2.0" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9197f1ad0e3c173a0222d3c4404fb04c3afe87e962bcb327af73e8301fa203c7" +checksum = "2e6be15c453eb305019bfa438b1593c731f36a289a7853f7707ee29e870b3b3c" dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -2568,6 +2568,16 @@ dependencies = [ "winapi", ] +[[package]] +name = "socket2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2538b18701741680e0322a2302176d3253a35388e2e62f172f64f4f16605f877" +dependencies = [ + "libc", + "windows-sys", +] + [[package]] name = "spin" version = "0.5.2" @@ -2609,9 +2619,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.28" +version = "2.0.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04361975b3f5e348b2189d8dc55bc942f278b2d482a6a0365de5bdd62d351567" +checksum = "c324c494eba9d92503e6f1ef2e6df781e78f6a7705a0202d9801b198807d518a" dependencies = [ "proc-macro2", "quote", @@ -2632,9 +2642,9 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "tempfile" -version = "3.7.1" +version = "3.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc02fddf48964c42031a0b3fe0428320ecf3a73c401040fc0096f97794310651" +checksum = "cb94d2f3cc536af71caac6b6fcebf65860b347e7ce0cc9ebe8f70d3e521054ef" dependencies = [ "cfg-if", "fastrand", @@ -2651,29 +2661,29 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.44" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "611040a08a0439f8248d1990b111c95baa9c704c805fa1f62104b39655fd7f90" +checksum = "97a802ec30afc17eee47b2855fc72e0c4cd62be9b4efe6591edde0ec5bd68d8f" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.44" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "090198534930841fab3a5d1bb637cde49e339654e606195f8d9c76eeb081dc96" +checksum = "6bb623b56e39ab7dcd4b1b98bb6c8f8d907ed255b18de254088016b27a8ee19b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] name = "time" -version = "0.3.25" +version = "0.3.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fdd63d58b18d663fbdf70e049f00a22c8e42be082203be7f26589213cd75ea" +checksum = "a79d09ac6b08c1ab3906a2f7cc2e81a0e27c7ae89c63812df75e52bef0751e07" dependencies = [ "deranged", "itoa", @@ -2690,9 +2700,9 @@ checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb" [[package]] name = "time-macros" -version = "0.2.11" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb71511c991639bb078fd5bf97757e03914361c48100d52878b8e52b46fb92cd" +checksum = "75c65469ed6b3a4809d987a41eb1dc918e9bc1d92211cbad7ae82931846f7451" dependencies = [ "time-core", ] @@ -2714,11 +2724,10 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.29.1" +version = "1.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "532826ff75199d5833b9d2c5fe410f29235e25704ee5f0ef599fb51c21f4a4da" +checksum = "17ed6077ed6cd6c74735e21f37eb16dc3935f96878b1fe961074089cc80893f9" dependencies = [ - "autocfg", "backtrace", "bytes", "libc", @@ -2726,7 +2735,7 @@ dependencies = [ "num_cpus", "pin-project-lite", "signal-hook-registry", - "socket2", + "socket2 0.5.3", "tokio-macros", "windows-sys", ] @@ -2739,7 +2748,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", ] [[package]] @@ -3079,7 +3088,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", "wasm-bindgen-shared", ] @@ -3113,7 +3122,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.28", + "syn 2.0.29", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -3176,9 +3185,9 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.48.1" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05d4b17490f70499f20b9e791dcf6a299785ce8af4d709018206dc5b4953e95f" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", @@ -3191,51 +3200,51 @@ dependencies = [ [[package]] name = "windows_aarch64_gnullvm" -version = "0.48.0" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_msvc" -version = "0.48.0" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_i686_gnu" -version = "0.48.0" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_msvc" -version = "0.48.0" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_x86_64_gnu" -version = "0.48.0" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnullvm" -version = "0.48.0" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_msvc" -version = "0.48.0" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "winnow" -version = "0.5.4" +version = "0.5.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acaaa1190073b2b101e15083c38ee8ec891b5e05cbee516521e94ec008f61e64" +checksum = "d09770118a7eb1ccaf4a594a221334119a44a814fcb0d31c5b85e83e97227a97" dependencies = [ "memchr", ] From a4ac6829a6a4cd35968231d14f09b91c8be47d6e Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 8 Aug 2023 10:58:52 +0200 Subject: [PATCH 0050/1297] dev: copy bencode into local contrib folder --- Cargo.lock | 241 ++++++++++- Cargo.toml | 3 +- contrib/bencode/Cargo.toml | 34 ++ contrib/bencode/README.md | 4 + contrib/bencode/benches/bencode_benchmark.rs | 27 ++ contrib/bencode/benches/multi_kb.bencode | 1 + contrib/bencode/src/access/bencode.rs | 120 ++++++ contrib/bencode/src/access/convert.rs | 230 +++++++++++ contrib/bencode/src/access/dict.rs | 64 +++ contrib/bencode/src/access/list.rs | 108 +++++ contrib/bencode/src/access/mod.rs | 4 + contrib/bencode/src/cow.rs | 44 ++ contrib/bencode/src/error.rs | 101 +++++ contrib/bencode/src/lib.rs | 143 +++++++ contrib/bencode/src/mutable/bencode_mut.rs | 229 +++++++++++ contrib/bencode/src/mutable/encode.rs | 67 ++++ contrib/bencode/src/mutable/mod.rs | 2 + contrib/bencode/src/reference/bencode_ref.rs | 265 ++++++++++++ contrib/bencode/src/reference/decode.rs | 398 +++++++++++++++++++ contrib/bencode/src/reference/decode_opt.rs | 55 +++ contrib/bencode/src/reference/mod.rs | 3 + contrib/bencode/test/mod.rs | 18 + src/servers/http/v1/responses/announce.rs | 2 +- src/servers/http/v1/responses/scrape.rs | 2 +- 24 files changed, 2150 insertions(+), 15 deletions(-) create mode 100644 contrib/bencode/Cargo.toml create mode 100644 contrib/bencode/README.md create mode 100644 contrib/bencode/benches/bencode_benchmark.rs create mode 100644 contrib/bencode/benches/multi_kb.bencode create mode 100644 contrib/bencode/src/access/bencode.rs create mode 100644 contrib/bencode/src/access/convert.rs create mode 100644 contrib/bencode/src/access/dict.rs create mode 100644 contrib/bencode/src/access/list.rs create mode 100644 contrib/bencode/src/access/mod.rs create mode 100644 contrib/bencode/src/cow.rs create mode 100644 contrib/bencode/src/error.rs create mode 100644 contrib/bencode/src/lib.rs create mode 100644 contrib/bencode/src/mutable/bencode_mut.rs create mode 100644 contrib/bencode/src/mutable/encode.rs create mode 100644 contrib/bencode/src/mutable/mod.rs create mode 100644 contrib/bencode/src/reference/bencode_ref.rs create mode 100644 contrib/bencode/src/reference/decode.rs create mode 100644 contrib/bencode/src/reference/decode_opt.rs create mode 100644 contrib/bencode/src/reference/mod.rs create mode 100644 contrib/bencode/test/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 32d35cbe2..f2053b043 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -69,6 +69,18 @@ dependencies = [ "libc", ] +[[package]] +name = "anes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + +[[package]] +name = "anstyle" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a30da5c5f2d5e72842e00bcb57657162cdabef0931f40e2deb9b4140440cecd" + [[package]] name = "aquatic_udp_protocol" version = "0.8.0" @@ -215,6 +227,14 @@ version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" +[[package]] +name = "bencode" +version = "1.0.0-alpha.1" +dependencies = [ + "criterion", + "error-chain", +] + [[package]] name = "bigdecimal" version = "0.3.1" @@ -251,15 +271,6 @@ dependencies = [ "shlex", ] -[[package]] -name = "bip_bencode" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6048cc5d9680544a5098a290d2845df7dae292c97687b9896b70365bad0ea416" -dependencies = [ - "error-chain", -] - [[package]] name = "bitflags" version = "1.3.2" @@ -384,6 +395,12 @@ version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + [[package]] name = "cc" version = "1.0.83" @@ -421,6 +438,33 @@ dependencies = [ "winapi", ] +[[package]] +name = "ciborium" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "effd91f6c78e5a4ace8a5d3c0b6bfaec9e2baaef55f3efc00e45fb2e477ee926" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdf919175532b369853f5d5e20b26b43112613fd6fe7aee757e35f7a44642656" + +[[package]] +name = "ciborium-ll" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "defaa24ecc093c77630e6c15e17c51f5e187bf35ee514f4e2d67baaa96dae22b" +dependencies = [ + "ciborium-io", + "half", +] + [[package]] name = "clang-sys" version = "1.6.1" @@ -432,6 +476,31 @@ dependencies = [ "libloading", ] +[[package]] +name = "clap" +version = "4.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03aef18ddf7d879c15ce20f04826ef8418101c7e528014c3eeea13321047dca3" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ce6fffb678c9b80a70b6b6de0aad31df727623a70fd9a842c30cd573e2fa98" +dependencies = [ + "anstyle", + "clap_lex", +] + +[[package]] +name = "clap_lex" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b" + [[package]] name = "cmake" version = "0.1.50" @@ -500,6 +569,42 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "criterion" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" +dependencies = [ + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot", + "is-terminal", + "itertools", + "num-traits", + "once_cell", + "oorandom", + "plotters", + "rayon", + "regex", + "serde", + "serde_derive", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" +dependencies = [ + "cast", + "itertools", +] + [[package]] name = "crossbeam" version = "0.8.2" @@ -717,11 +822,12 @@ dependencies = [ [[package]] name = "error-chain" -version = "0.11.0" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff511d5dc435d703f4971bc399647c9bc38e20cb41452e3b9feb4765419ed3f3" +checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc" dependencies = [ "backtrace", + "version_check", ] [[package]] @@ -1016,6 +1122,12 @@ dependencies = [ "tracing", ] +[[package]] +name = "half" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" + [[package]] name = "hashbrown" version = "0.12.3" @@ -1213,6 +1325,17 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" +[[package]] +name = "is-terminal" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" +dependencies = [ + "hermit-abi", + "rustix", + "windows-sys", +] + [[package]] name = "itertools" version = "0.10.5" @@ -1701,6 +1824,12 @@ version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" +[[package]] +name = "oorandom" +version = "11.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" + [[package]] name = "openssl" version = "0.10.56" @@ -1897,6 +2026,34 @@ version = "0.3.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" +[[package]] +name = "plotters" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c224ba00d7cadd4d5c660deaf2098e5e80e07846537c51f9cfa4be50c1fd45" +dependencies = [ + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "plotters-backend" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e76628b4d3a7581389a35d5b6e2139607ad7c75b17aed325f210aa91f4a9609" + +[[package]] +name = "plotters-svg" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38f6d39893cca0701371e3c27294f09797214b86f1fb951b89ade8ec04e2abab" +dependencies = [ + "plotters-backend", +] + [[package]] name = "ppv-lite86" version = "0.2.17" @@ -2048,6 +2205,28 @@ dependencies = [ "getrandom", ] +[[package]] +name = "rayon" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "num_cpus", +] + [[package]] name = "redox_syscall" version = "0.3.5" @@ -2304,6 +2483,15 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "saturating" version = "0.1.0" @@ -2707,6 +2895,16 @@ dependencies = [ "time-core", ] +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "tinyvec" version = "1.6.0" @@ -2837,8 +3035,8 @@ dependencies = [ "axum", "axum-client-ip", "axum-server", + "bencode", "binascii", - "bip_bencode", "chrono", "config", "derive_more", @@ -3052,6 +3250,16 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +[[package]] +name = "walkdir" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36df944cda56c7d8d8b7496af378e6b16de9284591917d307c9b4d313c44e698" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "want" version = "0.3.1" @@ -3159,6 +3367,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" diff --git a/Cargo.toml b/Cargo.toml index e87f7b972..a939318cd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,7 +41,7 @@ uuid = { version = "1", features = ["v4"] } axum = "0.6.20" axum-server = { version = "0.5", features = ["tls-rustls"] } axum-client-ip = "0.4.1" -bip_bencode = "0.4" +bencode = { version = "1.0.0-alpha.1", path = "contrib/bencode" } torrust-tracker-primitives = { version = "3.0.0-alpha.3", path = "packages/primitives" } torrust-tracker-configuration = { version = "3.0.0-alpha.3", path = "packages/configuration" } torrust-tracker-located-error = { version = "3.0.0-alpha.3", path = "packages/located-error" } @@ -59,6 +59,7 @@ torrust-tracker-test-helpers = { version = "3.0.0-alpha.3", path = "packages/tes [workspace] members = [ + "contrib/bencode", "packages/configuration", "packages/primitives", "packages/test-helpers", diff --git a/contrib/bencode/Cargo.toml b/contrib/bencode/Cargo.toml new file mode 100644 index 000000000..8334e270d --- /dev/null +++ b/contrib/bencode/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "bencode" +description = "Efficient decoding and encoding for bencode." +keywords = ["bencode"] +readme = "README.md" + + +authors = [ + "Nautilus Cyberneering , Andrew ", +] +categories = ["network-programming", "web-programming"] +documentation = "https://github.com/torrust/bittorrent-infrastructure-project" +edition = "2021" +homepage = "https://github.com/torrust/bittorrent-infrastructure-project" +license = "Apache-2.0" +publish = false # until we decide where to publish. +repository = "https://github.com/torrust/bittorrent-infrastructure-project" +rust-version = "1.71" +version = "1.0.0-alpha.1" + + +[dependencies] +error-chain = "0.12" + +[dev-dependencies] +criterion = "0.5" + +[[test]] +name = "test" +path = "test/mod.rs" + +[[bench]] +name = "bencode_benchmark" +harness = false \ No newline at end of file diff --git a/contrib/bencode/README.md b/contrib/bencode/README.md new file mode 100644 index 000000000..7a203082b --- /dev/null +++ b/contrib/bencode/README.md @@ -0,0 +1,4 @@ +# Bencode +This library allows for the creation and parsing of bencode encodings. + +Bencode is the binary encoding used throughout bittorrent technologies from metainfo files to DHT messages. Bencode types include integers, byte arrays, lists, and dictionaries, of which the last two can hold any bencode type (they could be recursively constructed). \ No newline at end of file diff --git a/contrib/bencode/benches/bencode_benchmark.rs b/contrib/bencode/benches/bencode_benchmark.rs new file mode 100644 index 000000000..729197d8a --- /dev/null +++ b/contrib/bencode/benches/bencode_benchmark.rs @@ -0,0 +1,27 @@ +use bencode::{BDecodeOpt, BencodeRef}; +use criterion::{black_box, criterion_group, criterion_main, Criterion}; + +const B_NESTED_LISTS: &[u8; 100] = + b"lllllllllllllllllllllllllllllllllllllllllllllllllleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; // cspell:disable-line +const MULTI_KB_BENCODE: &[u8; 30004] = include_bytes!("multi_kb.bencode"); + +fn bench_nested_lists(bencode: &[u8]) { + BencodeRef::decode(bencode, BDecodeOpt::new(50, true, true)).unwrap(); +} + +fn bench_multi_kb_bencode(bencode: &[u8]) { + BencodeRef::decode(bencode, BDecodeOpt::default()).unwrap(); +} + +fn criterion_benchmark(c: &mut Criterion) { + c.bench_function("bencode nested lists", |b| { + b.iter(|| bench_nested_lists(black_box(B_NESTED_LISTS))); + }); + + c.bench_function("bencode multi kb", |b| { + b.iter(|| bench_multi_kb_bencode(black_box(MULTI_KB_BENCODE))); + }); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/contrib/bencode/benches/multi_kb.bencode b/contrib/bencode/benches/multi_kb.bencode new file mode 100644 index 000000000..b86f2846e --- /dev/null +++ b/contrib/bencode/benches/multi_kb.bencode @@ -0,0 +1 @@ +d7:comment17:Just Some Comment10:created by12:bip_metainfo13:creation datei1496618058e4:infod5:filesld6:lengthi1024e4:pathl1:b11:small_1.txteed6:lengthi1024e4:pathl1:b12:small_10.txteed6:lengthi1024e4:pathl1:b13:small_100.txteed6:lengthi1024e4:pathl1:b12:small_11.txteed6:lengthi1024e4:pathl1:b12:small_12.txteed6:lengthi1024e4:pathl1:b12:small_13.txteed6:lengthi1024e4:pathl1:b12:small_14.txteed6:lengthi1024e4:pathl1:b12:small_15.txteed6:lengthi1024e4:pathl1:b12:small_16.txteed6:lengthi1024e4:pathl1:b12:small_17.txteed6:lengthi1024e4:pathl1:b12:small_18.txteed6:lengthi1024e4:pathl1:b12:small_19.txteed6:lengthi1024e4:pathl1:b11:small_2.txteed6:lengthi1024e4:pathl1:b12:small_20.txteed6:lengthi1024e4:pathl1:b12:small_21.txteed6:lengthi1024e4:pathl1:b12:small_22.txteed6:lengthi1024e4:pathl1:b12:small_23.txteed6:lengthi1024e4:pathl1:b12:small_24.txteed6:lengthi1024e4:pathl1:b12:small_25.txteed6:lengthi1024e4:pathl1:b12:small_26.txteed6:lengthi1024e4:pathl1:b12:small_27.txteed6:lengthi1024e4:pathl1:b12:small_28.txteed6:lengthi1024e4:pathl1:b12:small_29.txteed6:lengthi1024e4:pathl1:b11:small_3.txteed6:lengthi1024e4:pathl1:b12:small_30.txteed6:lengthi1024e4:pathl1:b12:small_31.txteed6:lengthi1024e4:pathl1:b12:small_32.txteed6:lengthi1024e4:pathl1:b12:small_33.txteed6:lengthi1024e4:pathl1:b12:small_34.txteed6:lengthi1024e4:pathl1:b12:small_35.txteed6:lengthi1024e4:pathl1:b12:small_36.txteed6:lengthi1024e4:pathl1:b12:small_37.txteed6:lengthi1024e4:pathl1:b12:small_38.txteed6:lengthi1024e4:pathl1:b12:small_39.txteed6:lengthi1024e4:pathl1:b11:small_4.txteed6:lengthi1024e4:pathl1:b12:small_40.txteed6:lengthi1024e4:pathl1:b12:small_41.txteed6:lengthi1024e4:pathl1:b12:small_42.txteed6:lengthi1024e4:pathl1:b12:small_43.txteed6:lengthi1024e4:pathl1:b12:small_44.txteed6:lengthi1024e4:pathl1:b12:small_45.txteed6:lengthi1024e4:pathl1:b12:small_46.txteed6:lengthi1024e4:pathl1:b12:small_47.txteed6:lengthi1024e4:pathl1:b12:small_48.txteed6:lengthi1024e4:pathl1:b12:small_49.txteed6:lengthi1024e4:pathl1:b11:small_5.txteed6:lengthi1024e4:pathl1:b12:small_50.txteed6:lengthi1024e4:pathl1:b12:small_51.txteed6:lengthi1024e4:pathl1:b12:small_52.txteed6:lengthi1024e4:pathl1:b12:small_53.txteed6:lengthi1024e4:pathl1:b12:small_54.txteed6:lengthi1024e4:pathl1:b12:small_55.txteed6:lengthi1024e4:pathl1:b12:small_56.txteed6:lengthi1024e4:pathl1:b12:small_57.txteed6:lengthi1024e4:pathl1:b12:small_58.txteed6:lengthi1024e4:pathl1:b12:small_59.txteed6:lengthi1024e4:pathl1:b11:small_6.txteed6:lengthi1024e4:pathl1:b12:small_60.txteed6:lengthi1024e4:pathl1:b12:small_61.txteed6:lengthi1024e4:pathl1:b12:small_62.txteed6:lengthi1024e4:pathl1:b12:small_63.txteed6:lengthi1024e4:pathl1:b12:small_64.txteed6:lengthi1024e4:pathl1:b12:small_65.txteed6:lengthi1024e4:pathl1:b12:small_66.txteed6:lengthi1024e4:pathl1:b12:small_67.txteed6:lengthi1024e4:pathl1:b12:small_68.txteed6:lengthi1024e4:pathl1:b12:small_69.txteed6:lengthi1024e4:pathl1:b11:small_7.txteed6:lengthi1024e4:pathl1:b12:small_70.txteed6:lengthi1024e4:pathl1:b12:small_71.txteed6:lengthi1024e4:pathl1:b12:small_72.txteed6:lengthi1024e4:pathl1:b12:small_73.txteed6:lengthi1024e4:pathl1:b12:small_74.txteed6:lengthi1024e4:pathl1:b12:small_75.txteed6:lengthi1024e4:pathl1:b12:small_76.txteed6:lengthi1024e4:pathl1:b12:small_77.txteed6:lengthi1024e4:pathl1:b12:small_78.txteed6:lengthi1024e4:pathl1:b12:small_79.txteed6:lengthi1024e4:pathl1:b11:small_8.txteed6:lengthi1024e4:pathl1:b12:small_80.txteed6:lengthi1024e4:pathl1:b12:small_81.txteed6:lengthi1024e4:pathl1:b12:small_82.txteed6:lengthi1024e4:pathl1:b12:small_83.txteed6:lengthi1024e4:pathl1:b12:small_84.txteed6:lengthi1024e4:pathl1:b12:small_85.txteed6:lengthi1024e4:pathl1:b12:small_86.txteed6:lengthi1024e4:pathl1:b12:small_87.txteed6:lengthi1024e4:pathl1:b12:small_88.txteed6:lengthi1024e4:pathl1:b12:small_89.txteed6:lengthi1024e4:pathl1:b11:small_9.txteed6:lengthi1024e4:pathl1:b12:small_90.txteed6:lengthi1024e4:pathl1:b12:small_91.txteed6:lengthi1024e4:pathl1:b12:small_92.txteed6:lengthi1024e4:pathl1:b12:small_93.txteed6:lengthi1024e4:pathl1:b12:small_94.txteed6:lengthi1024e4:pathl1:b12:small_95.txteed6:lengthi1024e4:pathl1:b12:small_96.txteed6:lengthi1024e4:pathl1:b12:small_97.txteed6:lengthi1024e4:pathl1:b12:small_98.txteed6:lengthi1024e4:pathl1:b12:small_99.txteed6:lengthi5368709120e4:pathl9:large.txteee4:name1:a12:piece lengthi4194304e6:pieces25620:+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+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90296e2 --- /dev/null +++ b/contrib/bencode/src/access/bencode.rs @@ -0,0 +1,120 @@ +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; + +/// Abstract representation of a `BencodeRef` object. +pub enum RefKind<'a, K, V> { + /// Bencode Integer. + Int(i64), + /// Bencode Bytes. + Bytes(&'a [u8]), + /// Bencode List. + List(&'a dyn BListAccess), + /// Bencode Dictionary. + Dict(&'a dyn BDictAccess), +} + +/// Trait for read access to some bencode type. +pub trait BRefAccess: Sized { + type BKey; + type BType: BRefAccess; + + /// Access the bencode as a `BencodeRefKind`. + fn kind(&self) -> RefKind<'_, Self::BKey, Self::BType>; + + /// Attempt to access the bencode as a `str`. + fn str(&self) -> Option<&str>; + + /// Attempt to access the bencode as an `i64`. + fn int(&self) -> Option; + + /// Attempt to access the bencode as an `[u8]`. + fn bytes(&self) -> Option<&[u8]>; + + /// Attempt to access the bencode as an `BListAccess`. + fn list(&self) -> Option<&dyn BListAccess>; + + /// Attempt to access the bencode as an `BDictAccess`. + fn dict(&self) -> Option<&dyn BDictAccess>; +} + +/// Trait for extended read access to some bencode type. +/// +/// Use this trait when you want to make sure that the lifetime of +/// the underlying buffers is tied to the lifetime of the backing +/// bencode buffer. +pub trait BRefAccessExt<'a>: BRefAccess { + /// Attempt to access the bencode as a `str`. + fn str_ext(&self) -> Option<&'a str>; + + /// Attempt to access the bencode as an `[u8]`. + fn bytes_ext(&self) -> Option<&'a [u8]>; +} + +impl<'a, T> BRefAccess for &'a T +where + T: BRefAccess, +{ + type BKey = T::BKey; + type BType = T::BType; + + fn kind(&self) -> RefKind<'_, Self::BKey, Self::BType> { + (*self).kind() + } + + fn str(&self) -> Option<&str> { + (*self).str() + } + + fn int(&self) -> Option { + (*self).int() + } + + fn bytes(&self) -> Option<&[u8]> { + (*self).bytes() + } + + fn list(&self) -> Option<&dyn BListAccess> { + (*self).list() + } + + fn dict(&self) -> Option<&dyn BDictAccess> { + (*self).dict() + } +} + +impl<'a: 'b, 'b, T> BRefAccessExt<'a> for &'b T +where + T: BRefAccessExt<'a>, +{ + fn str_ext(&self) -> Option<&'a str> { + (*self).str_ext() + } + + fn bytes_ext(&self) -> Option<&'a [u8]> { + (*self).bytes_ext() + } +} + +/// Abstract representation of a `BencodeMut` object. +pub enum MutKind<'a, K, V> { + /// Bencode Integer. + Int(i64), + /// Bencode Bytes. + Bytes(&'a [u8]), + /// Bencode List. + List(&'a mut dyn BListAccess), + /// Bencode Dictionary. + Dict(&'a mut dyn BDictAccess), +} + +/// Trait for write access to some bencode type. +pub trait BMutAccess: Sized + BRefAccess { + /// Access the bencode as a `BencodeMutKind`. + fn kind_mut(&mut self) -> MutKind<'_, Self::BKey, Self::BType>; + + /// Attempt to access the bencode as a mutable `BListAccess`. + fn list_mut(&mut self) -> Option<&mut dyn BListAccess>; + + /// Attempt to access the bencode as a mutable `BDictAccess`. + fn dict_mut(&mut self) -> Option<&mut dyn BDictAccess>; +} diff --git a/contrib/bencode/src/access/convert.rs b/contrib/bencode/src/access/convert.rs new file mode 100644 index 000000000..42b04f267 --- /dev/null +++ b/contrib/bencode/src/access/convert.rs @@ -0,0 +1,230 @@ +#![allow(clippy::missing_errors_doc)] +use crate::access::bencode::{BRefAccess, BRefAccessExt}; +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; +use crate::{BencodeConvertError, BencodeConvertErrorKind}; + +/// Trait for extended casting of bencode objects and converting conversion errors into application specific errors. +pub trait BConvertExt: BConvert { + /// See `BConvert::convert_bytes`. + fn convert_bytes_ext<'a, B, E>(&self, bencode: B, error_key: E) -> Result<&'a [u8], Self::Error> + where + B: BRefAccessExt<'a>, + E: AsRef<[u8]>, + { + bencode.bytes_ext().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Bytes".to_owned(), + })), + ) + } + + /// See `BConvert::convert_str`. + fn convert_str_ext<'a, B, E>(&self, bencode: &B, error_key: E) -> Result<&'a str, Self::Error> + where + B: BRefAccessExt<'a>, + E: AsRef<[u8]>, + { + bencode.str_ext().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "UTF-8 Bytes".to_owned(), + })), + ) + } + + /// See `BConvert::lookup_and_convert_bytes`. + fn lookup_and_convert_bytes_ext<'a, B, K1, K2>( + &self, + dictionary: &dyn BDictAccess, + key: K2, + ) -> Result<&'a [u8], Self::Error> + where + B: BRefAccessExt<'a>, + K2: AsRef<[u8]>, + { + self.convert_bytes_ext(self.lookup(dictionary, &key)?, &key) + } + + /// See `BConvert::lookup_and_convert_str`. + fn lookup_and_convert_str_ext<'a, B, K1, K2>( + &self, + dictionary: &dyn BDictAccess, + key: K2, + ) -> Result<&'a str, Self::Error> + where + B: BRefAccessExt<'a>, + K2: AsRef<[u8]>, + { + self.convert_str_ext(self.lookup(dictionary, &key)?, &key) + } +} + +/// Trait for casting bencode objects and converting conversion errors into application specific errors. +#[allow(clippy::module_name_repetitions)] +pub trait BConvert { + type Error; + + /// Convert the given conversion error into the appropriate error type. + fn handle_error(&self, error: BencodeConvertError) -> Self::Error; + + /// Attempt to convert the given bencode value into an integer. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_int(&self, bencode: B, error_key: E) -> Result + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.int().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Integer".to_owned(), + })), + ) + } + + /// Attempt to convert the given bencode value into bytes. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_bytes<'a, B, E>(&self, bencode: &'a B, error_key: E) -> Result<&'a [u8], Self::Error> + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.bytes().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Bytes".to_owned(), + })), + ) + } + + /// Attempt to convert the given bencode value into a UTF-8 string. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_str<'a, B, E>(&self, bencode: &'a B, error_key: E) -> Result<&'a str, Self::Error> + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.str().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "UTF-8 Bytes".to_owned(), + })), + ) + } + + /// Attempt to convert the given bencode value into a list. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_list<'a, B, E>(&self, bencode: &'a B, error_key: E) -> Result<&'a dyn BListAccess, Self::Error> + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.list().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "List".to_owned(), + })), + ) + } + + /// Attempt to convert the given bencode value into a dictionary. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_dict<'a, B, E>(&self, bencode: &'a B, error_key: E) -> Result<&'a dyn BDictAccess, Self::Error> + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.dict().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Dictionary".to_owned(), + })), + ) + } + + /// Look up a value in a dictionary of bencoded values using the given key. + fn lookup<'a, B, K1, K2>(&self, dictionary: &'a dyn BDictAccess, key: K2) -> Result<&'a B, Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + let key_ref = key.as_ref(); + + match dictionary.lookup(key_ref) { + Some(n) => Ok(n), + None => Err( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::MissingKey { + key: key_ref.to_owned(), + })), + ), + } + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to an integer. + fn lookup_and_convert_int(&self, dictionary: &dyn BDictAccess, key: K2) -> Result + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_int(self.lookup(dictionary, &key)?, &key) + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to a series of bytes. + fn lookup_and_convert_bytes<'a, B, K1, K2>( + &self, + dictionary: &'a dyn BDictAccess, + key: K2, + ) -> Result<&'a [u8], Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_bytes(self.lookup(dictionary, &key)?, &key) + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to a UTF-8 string. + fn lookup_and_convert_str<'a, B, K1, K2>( + &self, + dictionary: &'a dyn BDictAccess, + key: K2, + ) -> Result<&'a str, Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_str(self.lookup(dictionary, &key)?, &key) + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to a list. + fn lookup_and_convert_list<'a, B, K1, K2>( + &self, + dictionary: &'a dyn BDictAccess, + key: K2, + ) -> Result<&'a dyn BListAccess, Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_list(self.lookup(dictionary, &key)?, &key) + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to a dictionary. + fn lookup_and_convert_dict<'a, B, K1, K2>( + &self, + dictionary: &'a dyn BDictAccess, + key: K2, + ) -> Result<&'a dyn BDictAccess, Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_dict(self.lookup(dictionary, &key)?, &key) + } +} diff --git a/contrib/bencode/src/access/dict.rs b/contrib/bencode/src/access/dict.rs new file mode 100644 index 000000000..596d9535e --- /dev/null +++ b/contrib/bencode/src/access/dict.rs @@ -0,0 +1,64 @@ +use std::borrow::Cow; +use std::collections::BTreeMap; + +/// Trait for working with generic map data structures. +pub trait BDictAccess { + /// Convert the dictionary to an unordered list of key/value pairs. + fn to_list(&self) -> Vec<(&K, &V)>; + + /// Lookup a value in the dictionary. + fn lookup(&self, key: &[u8]) -> Option<&V>; + + /// Lookup a mutable value in the dictionary. + fn lookup_mut(&mut self, key: &[u8]) -> Option<&mut V>; + + /// Insert a key/value pair into the dictionary. + fn insert(&mut self, key: K, value: V) -> Option; + + /// Remove a value from the dictionary and return it. + fn remove(&mut self, key: &[u8]) -> Option; +} + +impl<'a, V> BDictAccess<&'a [u8], V> for BTreeMap<&'a [u8], V> { + fn to_list(&self) -> Vec<(&&'a [u8], &V)> { + self.iter().map(|(k, v)| (k, v)).collect() + } + + fn lookup(&self, key: &[u8]) -> Option<&V> { + self.get(key) + } + + fn lookup_mut(&mut self, key: &[u8]) -> Option<&mut V> { + self.get_mut(key) + } + + fn insert(&mut self, key: &'a [u8], value: V) -> Option { + self.insert(key, value) + } + + fn remove(&mut self, key: &[u8]) -> Option { + self.remove(key) + } +} + +impl<'a, V> BDictAccess, V> for BTreeMap, V> { + fn to_list(&self) -> Vec<(&Cow<'a, [u8]>, &V)> { + self.iter().map(|(k, v)| (k, v)).collect() + } + + fn lookup(&self, key: &[u8]) -> Option<&V> { + self.get(key) + } + + fn lookup_mut(&mut self, key: &[u8]) -> Option<&mut V> { + self.get_mut(key) + } + + fn insert(&mut self, key: Cow<'a, [u8]>, value: V) -> Option { + self.insert(key, value) + } + + fn remove(&mut self, key: &[u8]) -> Option { + self.remove(key) + } +} diff --git a/contrib/bencode/src/access/list.rs b/contrib/bencode/src/access/list.rs new file mode 100644 index 000000000..840bffa1e --- /dev/null +++ b/contrib/bencode/src/access/list.rs @@ -0,0 +1,108 @@ +use std::ops::{Index, IndexMut}; + +/// Trait for working with generic list data structures. +pub trait BListAccess { + /// Get a list element at the given index. + fn get(&self, index: usize) -> Option<&V>; + + /// Get a mutable list element at the given index. + fn get_mut(&mut self, index: usize) -> Option<&mut V>; + + /// Remove a list element at the given index. + fn remove(&mut self, index: usize) -> Option; + + /// Insert a list element at the given index. + fn insert(&mut self, index: usize, item: V); + + /// Push an element to the back of the list. + fn push(&mut self, item: V); + + /// Get the length of the list. + fn len(&self) -> usize; + + fn is_empty(&self) -> bool; +} + +impl<'a, V: 'a> Index for &'a dyn BListAccess { + type Output = V; + + fn index(&self, index: usize) -> &V { + self.get(index).unwrap() + } +} + +impl<'a, V: 'a> Index for &'a mut dyn BListAccess { + type Output = V; + + fn index(&self, index: usize) -> &V { + self.get(index).unwrap() + } +} + +impl<'a, V: 'a> IndexMut for &'a mut dyn BListAccess { + fn index_mut(&mut self, index: usize) -> &mut V { + self.get_mut(index).unwrap() + } +} + +impl<'a, V: 'a> IntoIterator for &'a dyn BListAccess { + type Item = &'a V; + type IntoIter = BListIter<'a, V>; + + fn into_iter(self) -> BListIter<'a, V> { + BListIter { index: 0, access: self } + } +} + +pub struct BListIter<'a, V> { + index: usize, + access: &'a dyn BListAccess, +} + +impl<'a, V> Iterator for BListIter<'a, V> { + type Item = &'a V; + + fn next(&mut self) -> Option<&'a V> { + let opt_next = self.access.get(self.index); + + if opt_next.is_some() { + self.index += 1; + } + + opt_next + } +} + +impl BListAccess for Vec { + fn get(&self, index: usize) -> Option<&V> { + self[..].get(index) + } + + fn get_mut(&mut self, index: usize) -> Option<&mut V> { + self[..].get_mut(index) + } + + fn remove(&mut self, index: usize) -> Option { + if index >= self[..].len() { + None + } else { + Some(Vec::remove(self, index)) + } + } + + fn insert(&mut self, index: usize, item: V) { + Vec::insert(self, index, item); + } + + fn push(&mut self, item: V) { + Vec::push(self, item); + } + + fn len(&self) -> usize { + Vec::len(self) + } + + fn is_empty(&self) -> bool { + Vec::is_empty(self) + } +} diff --git a/contrib/bencode/src/access/mod.rs b/contrib/bencode/src/access/mod.rs new file mode 100644 index 000000000..f14b032d4 --- /dev/null +++ b/contrib/bencode/src/access/mod.rs @@ -0,0 +1,4 @@ +pub mod bencode; +pub mod convert; +pub mod dict; +pub mod list; diff --git a/contrib/bencode/src/cow.rs b/contrib/bencode/src/cow.rs new file mode 100644 index 000000000..0d38c751b --- /dev/null +++ b/contrib/bencode/src/cow.rs @@ -0,0 +1,44 @@ +use std::borrow::Cow; + +/// Trait for macros to convert owned/borrowed types to `Cow`. +/// +/// This is needed because `&str` and `String` do not have `From` +/// implements into `Cow<_, [u8]>`. One solution is to just call `AsRef<[u8]>` +/// before converting. However, then when a user specifies an owned type, +/// we will implicitly borrow that; this trait prevents that so that macro +/// behavior is intuitive, so that owned types stay owned. +pub trait BCowConvert<'a> { + fn convert(self) -> Cow<'a, [u8]>; +} + +// TODO: Enable when specialization lands. +/* +impl<'a, T> BCowConvert<'a> for T where T: AsRef<[u8]> + 'a { + fn convert(self) -> Cow<'a, [u8]> { + self.into() + } +}*/ + +impl<'a> BCowConvert<'a> for &'a [u8] { + fn convert(self) -> Cow<'a, [u8]> { + self.into() + } +} + +impl<'a> BCowConvert<'a> for &'a str { + fn convert(self) -> Cow<'a, [u8]> { + self.as_bytes().into() + } +} + +impl BCowConvert<'static> for String { + fn convert(self) -> Cow<'static, [u8]> { + self.into_bytes().into() + } +} + +impl BCowConvert<'static> for Vec { + fn convert(self) -> Cow<'static, [u8]> { + self.into() + } +} diff --git a/contrib/bencode/src/error.rs b/contrib/bencode/src/error.rs new file mode 100644 index 000000000..18ebe9605 --- /dev/null +++ b/contrib/bencode/src/error.rs @@ -0,0 +1,101 @@ +use error_chain::error_chain; + +error_chain! { + types { + BencodeParseError, BencodeParseErrorKind, BencodeParseResultExt, BencodeParseResult; + } + + errors { + BytesEmpty { + pos: usize + } { + description("Incomplete Number Of Bytes") + display("Incomplete Number Of Bytes At {:?}", pos) + } + InvalidByte { + pos: usize + } { + description("Invalid Byte Found") + display("Invalid Byte Found At {:?}", pos) + } + InvalidIntNoDelimiter { + pos: usize + } { + description("Invalid Integer Found With No Delimiter") + display("Invalid Integer Found With No Delimiter At {:?}", pos) + } + InvalidIntNegativeZero { + pos: usize + } { + description("Invalid Integer Found As Negative Zero") + display("Invalid Integer Found As Negative Zero At {:?}", pos) + } + InvalidIntZeroPadding { + pos: usize + } { + description("Invalid Integer Found With Zero Padding") + display("Invalid Integer Found With Zero Padding At {:?}", pos) + } + InvalidIntParseError { + pos: usize + } { + description("Invalid Integer Found To Fail Parsing") + display("Invalid Integer Found To Fail Parsing At {:?}", pos) + } + InvalidKeyOrdering { + pos: usize, + key: Vec + } { + description("Invalid Dictionary Key Ordering Found") + display("Invalid Dictionary Key Ordering Found At {:?} For Key {:?}", pos, key) + } + InvalidKeyDuplicates { + pos: usize, + key: Vec + } { + description("Invalid Dictionary Duplicate Keys Found") + display("Invalid Dictionary Key Found At {:?} For Key {:?}", pos, key) + } + InvalidLengthNegative { + pos: usize + } { + description("Invalid Byte Length Found As Negative") + display("Invalid Byte Length Found As Negative At {:?}", pos) + } + InvalidLengthOverflow { + pos: usize + } { + description("Invalid Byte Length Found To Overflow Buffer Length") + display("Invalid Byte Length Found To Overflow Buffer Length At {:?}", pos) + } + InvalidRecursionExceeded { + pos: usize, + max: usize + } { + description("Invalid Recursion Limit Exceeded") + display("Invalid Recursion Limit Exceeded At {:?} For Limit {:?}", pos, max) + } + } +} + +error_chain! { + types { + BencodeConvertError, BencodeConvertErrorKind, BencodeConvertResultExt, BencodeConvertResult; + } + + errors { + MissingKey { + key: Vec + } { + description("Missing Key In Bencode") + display("Missing Key In Bencode For {:?}", key) + } + WrongType { + key: Vec, + expected_type: String + } { + description("Wrong Type In Bencode") + display("Wrong Type In Bencode For {:?} Expected Type {}", key, expected_type) + } + } +} diff --git a/contrib/bencode/src/lib.rs b/contrib/bencode/src/lib.rs new file mode 100644 index 000000000..103a3c371 --- /dev/null +++ b/contrib/bencode/src/lib.rs @@ -0,0 +1,143 @@ +//! Library for parsing and converting bencoded data. +//! +//! # Examples +//! +//! Decoding bencoded data: +//! +//! ```rust +//! extern crate bencode; +//! +//! use std::default::Default; +//! use bencode::{BencodeRef, BRefAccess, BDecodeOpt}; +//! +//! fn main() { +//! let data = b"d12:lucky_numberi7ee"; // cspell:disable-line +//! let bencode = BencodeRef::decode(data, BDecodeOpt::default()).unwrap(); +//! +//! assert_eq!(7, bencode.dict().unwrap().lookup("lucky_number".as_bytes()) +//! .unwrap().int().unwrap()); +//! } +//! ``` +//! +//! Encoding bencoded data: +//! +//! ```rust +//! #[macro_use] +//! extern crate bencode; +//! +//! fn main() { +//! let message = (ben_map!{ +//! "lucky_number" => ben_int!(7), +//! "lucky_string" => ben_bytes!("7") +//! }).encode(); +//! +//! let data = b"d12:lucky_numberi7e12:lucky_string1:7e"; // cspell:disable-line +//! assert_eq!(&data[..], &message[..]); +//! } +//! ``` + +mod access; +mod cow; +mod error; +mod mutable; +mod reference; + +/// Traits for implementation functionality. +pub mod inner { + pub use crate::cow::BCowConvert; +} + +/// Traits for extended functionality. +pub mod ext { + #[allow(clippy::module_name_repetitions)] + pub use crate::access::bencode::BRefAccessExt; + #[allow(clippy::module_name_repetitions)] + pub use crate::access::convert::BConvertExt; +} + +#[deprecated(since = "1.0.0", note = "use `MutKind` instead.")] +pub use crate::access::bencode::MutKind as BencodeMutKind; +#[deprecated(since = "1.0.0", note = "use `RefKind` instead.")] +pub use crate::access::bencode::RefKind as BencodeRefKind; +pub use crate::access::bencode::{BMutAccess, BRefAccess, MutKind, RefKind}; +pub use crate::access::convert::BConvert; +pub use crate::access::dict::BDictAccess; +pub use crate::access::list::BListAccess; +pub use crate::error::{ + BencodeConvertError, BencodeConvertErrorKind, BencodeConvertResult, BencodeParseError, BencodeParseErrorKind, + BencodeParseResult, +}; +pub use crate::mutable::bencode_mut::BencodeMut; +pub use crate::reference::bencode_ref::BencodeRef; +pub use crate::reference::decode_opt::BDecodeOpt; + +const BEN_END: u8 = b'e'; +const DICT_START: u8 = b'd'; +const LIST_START: u8 = b'l'; +const INT_START: u8 = b'i'; + +const BYTE_LEN_LOW: u8 = b'0'; +const BYTE_LEN_HIGH: u8 = b'9'; +const BYTE_LEN_END: u8 = b':'; + +/// Construct a `BencodeMut` map by supplying string references as keys and `BencodeMut` as values. +#[macro_export] +macro_rules! ben_map { +( $($key:expr => $val:expr),* ) => { + { + use bencode::{BMutAccess, BencodeMut}; + use bencode::inner::BCowConvert; + + let mut bencode_map = BencodeMut::new_dict(); + { + let map = bencode_map.dict_mut().unwrap(); + $( + map.insert(BCowConvert::convert($key), $val); + )* + } + + bencode_map + } + } +} + +/// Construct a `BencodeMut` list by supplying a list of `BencodeMut` values. +#[macro_export] +macro_rules! ben_list { + ( $($ben:expr),* ) => { + { + use bencode::{BencodeMut, BMutAccess}; + + let mut bencode_list = BencodeMut::new_list(); + { + let list = bencode_list.list_mut().unwrap(); + $( + list.push($ben); + )* + } + + bencode_list + } + } +} + +/// Construct `BencodeMut` bytes by supplying a type convertible to `Vec`. +#[macro_export] +macro_rules! ben_bytes { + ( $ben:expr ) => {{ + use bencode::inner::BCowConvert; + use bencode::BencodeMut; + + BencodeMut::new_bytes(BCowConvert::convert($ben)) + }}; +} + +/// Construct a `BencodeMut` integer by supplying an `i64`. +#[macro_export] +macro_rules! ben_int { + ( $ben:expr ) => {{ + use bencode::BencodeMut; + + BencodeMut::new_int($ben) + }}; +} diff --git a/contrib/bencode/src/mutable/bencode_mut.rs b/contrib/bencode/src/mutable/bencode_mut.rs new file mode 100644 index 000000000..a3f95dbbf --- /dev/null +++ b/contrib/bencode/src/mutable/bencode_mut.rs @@ -0,0 +1,229 @@ +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::str; + +use crate::access::bencode::{BMutAccess, BRefAccess, MutKind, RefKind}; +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; +use crate::mutable::encode; + +/// Bencode object that holds references to the underlying data. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub enum Inner<'a> { + /// Bencode Integer. + Int(i64), + /// Bencode Bytes. + Bytes(Cow<'a, [u8]>), + /// Bencode List. + List(Vec>), + /// Bencode Dictionary. + Dict(BTreeMap, BencodeMut<'a>>), +} + +/// `BencodeMut` object that stores references to some data. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub struct BencodeMut<'a> { + inner: Inner<'a>, +} + +impl<'a> BencodeMut<'a> { + fn new(inner: Inner<'a>) -> BencodeMut<'a> { + BencodeMut { inner } + } + + /// Create a new `BencodeMut` representing an `i64`. + #[must_use] + pub fn new_int(value: i64) -> BencodeMut<'a> { + BencodeMut::new(Inner::Int(value)) + } + + /// Create a new `BencodeMut` representing a `[u8]`. + #[must_use] + pub fn new_bytes(value: Cow<'a, [u8]>) -> BencodeMut<'a> { + BencodeMut::new(Inner::Bytes(value)) + } + + /// Create a new `BencodeMut` representing a `BListAccess`. + #[must_use] + pub fn new_list() -> BencodeMut<'a> { + BencodeMut::new(Inner::List(Vec::new())) + } + + /// Create a new `BencodeMut` representing a `BDictAccess`. + #[must_use] + pub fn new_dict() -> BencodeMut<'a> { + BencodeMut::new(Inner::Dict(BTreeMap::new())) + } + + /// Encode the `BencodeMut` into a buffer representing the bencode. + #[must_use] + pub fn encode(&self) -> Vec { + let mut buffer = Vec::new(); + + encode::encode(self, &mut buffer); + + buffer + } +} + +impl<'a> BRefAccess for BencodeMut<'a> { + type BKey = Cow<'a, [u8]>; + type BType = BencodeMut<'a>; + + fn kind<'b>(&'b self) -> RefKind<'b, Cow<'a, [u8]>, BencodeMut<'a>> { + match self.inner { + Inner::Int(n) => RefKind::Int(n), + Inner::Bytes(ref n) => RefKind::Bytes(n), + Inner::List(ref n) => RefKind::List(n), + Inner::Dict(ref n) => RefKind::Dict(n), + } + } + + fn str(&self) -> Option<&str> { + let bytes = self.bytes()?; + + match str::from_utf8(bytes) { + Ok(n) => Some(n), + Err(_) => None, + } + } + + fn int(&self) -> Option { + match self.inner { + Inner::Int(n) => Some(n), + _ => None, + } + } + + fn bytes(&self) -> Option<&[u8]> { + match self.inner { + Inner::Bytes(ref n) => Some(n.as_ref()), + _ => None, + } + } + + fn list(&self) -> Option<&dyn BListAccess>> { + match self.inner { + Inner::List(ref n) => Some(n), + _ => None, + } + } + + fn dict(&self) -> Option<&dyn BDictAccess, BencodeMut<'a>>> { + match self.inner { + Inner::Dict(ref n) => Some(n), + _ => None, + } + } +} + +impl<'a> BMutAccess for BencodeMut<'a> { + fn kind_mut<'b>(&'b mut self) -> MutKind<'b, Cow<'a, [u8]>, BencodeMut<'a>> { + match self.inner { + Inner::Int(n) => MutKind::Int(n), + Inner::Bytes(ref mut n) => MutKind::Bytes((*n).as_ref()), + Inner::List(ref mut n) => MutKind::List(n), + Inner::Dict(ref mut n) => MutKind::Dict(n), + } + } + + fn list_mut(&mut self) -> Option<&mut dyn BListAccess>> { + match self.inner { + Inner::List(ref mut n) => Some(n), + _ => None, + } + } + + fn dict_mut(&mut self) -> Option<&mut dyn BDictAccess, BencodeMut<'a>>> { + match self.inner { + Inner::Dict(ref mut n) => Some(n), + _ => None, + } + } +} + +// impl<'a> From> for BencodeMut<'a> { +// fn from(value: BencodeRef<'a>) -> Self { +// let inner = match value.kind() { +// BencodeRefKind::Int(value) => InnerBencodeMut::Int(value), +// BencodeRefKind::Bytes(value) => InnerBencodeMut::Bytes(Cow::Owned(Vec::from(value))), +// BencodeRefKind::List(value) => { +// InnerBencodeMut::List(value.clone().into_iter().map(|b| BencodeMut::from(b.clone())).collect()) +// } +// BencodeRefKind::Dict(value) => InnerBencodeMut::Dict( +// value +// .to_list() +// .into_iter() +// .map(|(key, value)| (Cow::Owned(Vec::from(*key)), BencodeMut::from(value.clone()))) +// .collect(), +// ), +// }; +// BencodeMut { inner } +// } +// } + +#[cfg(test)] +mod test { + use crate::access::bencode::BMutAccess; + use crate::mutable::bencode_mut::BencodeMut; + + #[test] + fn positive_int_encode() { + let bencode_int = BencodeMut::new_int(-560); + + let int_bytes = b"i-560e"; // cspell:disable-line + assert_eq!(&int_bytes[..], &bencode_int.encode()[..]); + } + + #[test] + fn positive_bytes_encode() { + /* cspell:disable-next-line */ + let bencode_bytes = BencodeMut::new_bytes((&b"asdasd"[..]).into()); + + let bytes_bytes = b"6:asdasd"; // cspell:disable-line + assert_eq!(&bytes_bytes[..], &bencode_bytes.encode()[..]); + } + + #[test] + fn positive_empty_list_encode() { + let bencode_list = BencodeMut::new_list(); + + let list_bytes = b"le"; // cspell:disable-line + assert_eq!(&list_bytes[..], &bencode_list.encode()[..]); + } + + #[test] + fn positive_nonempty_list_encode() { + let mut bencode_list = BencodeMut::new_list(); + + { + let list_mut = bencode_list.list_mut().unwrap(); + list_mut.push(BencodeMut::new_int(56)); + } + + let list_bytes = b"li56ee"; // cspell:disable-line + assert_eq!(&list_bytes[..], &bencode_list.encode()[..]); + } + + #[test] + fn positive_empty_dict_encode() { + let bencode_dict = BencodeMut::new_dict(); + + let dict_bytes = b"de"; // cspell:disable-line + assert_eq!(&dict_bytes[..], &bencode_dict.encode()[..]); + } + + #[test] + fn positive_nonempty_dict_encode() { + let mut bencode_dict = BencodeMut::new_dict(); + + { + let dict_mut = bencode_dict.dict_mut().unwrap(); + /* cspell:disable-next-line */ + dict_mut.insert((&b"asd"[..]).into(), BencodeMut::new_bytes((&b"asdasd"[..]).into())); + } + + let dict_bytes = b"d3:asd6:asdasde"; // cspell:disable-line + assert_eq!(&dict_bytes[..], &bencode_dict.encode()[..]); + } +} diff --git a/contrib/bencode/src/mutable/encode.rs b/contrib/bencode/src/mutable/encode.rs new file mode 100644 index 000000000..811c35816 --- /dev/null +++ b/contrib/bencode/src/mutable/encode.rs @@ -0,0 +1,67 @@ +use std::iter::Extend; + +use crate::access::bencode::{BRefAccess, RefKind}; +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; + +pub fn encode(val: T, bytes: &mut Vec) +where + T: BRefAccess, + T::BKey: AsRef<[u8]>, +{ + match val.kind() { + RefKind::Int(n) => encode_int(n, bytes), + RefKind::Bytes(n) => encode_bytes(n, bytes), + RefKind::List(n) => encode_list(n, bytes), + RefKind::Dict(n) => encode_dict(n, bytes), + } +} + +fn encode_int(val: i64, bytes: &mut Vec) { + bytes.push(crate::INT_START); + + bytes.extend(val.to_string().into_bytes()); + + bytes.push(crate::BEN_END); +} + +fn encode_bytes(list: &[u8], bytes: &mut Vec) { + bytes.extend(list.len().to_string().into_bytes()); + + bytes.push(crate::BYTE_LEN_END); + + bytes.extend(list.iter().copied()); +} + +fn encode_list(list: &dyn BListAccess, bytes: &mut Vec) +where + T: BRefAccess, + T::BKey: AsRef<[u8]>, +{ + bytes.push(crate::LIST_START); + + for i in list { + encode(i, bytes); + } + + bytes.push(crate::BEN_END); +} + +fn encode_dict(dict: &dyn BDictAccess, bytes: &mut Vec) +where + K: AsRef<[u8]>, + V: BRefAccess, + V::BKey: AsRef<[u8]>, +{ + // Need To Sort The Keys In The Map Before Encoding + let mut sort_dict = dict.to_list(); + sort_dict.sort_by(|&(a, _), &(b, _)| a.as_ref().cmp(b.as_ref())); + + bytes.push(crate::DICT_START); + // Iterate And Dictionary Encode The (String, Bencode) Pairs + for (key, value) in &sort_dict { + encode_bytes(key.as_ref(), bytes); + encode(value, bytes); + } + bytes.push(crate::BEN_END); +} diff --git a/contrib/bencode/src/mutable/mod.rs b/contrib/bencode/src/mutable/mod.rs new file mode 100644 index 000000000..329ee9f7a --- /dev/null +++ b/contrib/bencode/src/mutable/mod.rs @@ -0,0 +1,2 @@ +pub mod bencode_mut; +mod encode; diff --git a/contrib/bencode/src/reference/bencode_ref.rs b/contrib/bencode/src/reference/bencode_ref.rs new file mode 100644 index 000000000..760dd3016 --- /dev/null +++ b/contrib/bencode/src/reference/bencode_ref.rs @@ -0,0 +1,265 @@ +use std::collections::BTreeMap; +use std::str; + +use crate::access::bencode::{BRefAccess, BRefAccessExt, RefKind}; +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; +use crate::error::{BencodeParseError, BencodeParseErrorKind, BencodeParseResult}; +use crate::reference::decode; +use crate::reference::decode_opt::BDecodeOpt; + +/// Bencode object that holds references to the underlying data. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub enum Inner<'a> { + /// Bencode Integer. + Int(i64, &'a [u8]), + /// Bencode Bytes. + Bytes(&'a [u8], &'a [u8]), + /// Bencode List. + List(Vec>, &'a [u8]), + /// Bencode Dictionary. + Dict(BTreeMap<&'a [u8], BencodeRef<'a>>, &'a [u8]), +} + +impl<'a> From> for BencodeRef<'a> { + fn from(val: Inner<'a>) -> Self { + BencodeRef { inner: val } + } +} + +/// `BencodeRef` object that stores references to some buffer. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub struct BencodeRef<'a> { + inner: Inner<'a>, +} + +impl<'a> BencodeRef<'a> { + /// Decode the given bytes into a `BencodeRef` using the given decode options. + #[allow(clippy::missing_errors_doc)] + pub fn decode(bytes: &'a [u8], opts: BDecodeOpt) -> BencodeParseResult> { + // Apply try so any errors return before the eof check + let (bencode, end_pos) = decode::decode(bytes, 0, opts, 0)?; + + if end_pos != bytes.len() && opts.enforce_full_decode() { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::BytesEmpty { + pos: end_pos, + })); + } + + Ok(bencode) + } + + /// Get a byte slice of the current bencode byte representation. + #[must_use] + pub fn buffer(&self) -> &'a [u8] { + #[allow(clippy::match_same_arms)] + match self.inner { + Inner::Int(_, buffer) => buffer, + Inner::Bytes(_, buffer) => buffer, + Inner::List(_, buffer) => buffer, + Inner::Dict(_, buffer) => buffer, + } + } +} + +impl<'a> BRefAccess for BencodeRef<'a> { + type BKey = &'a [u8]; + type BType = BencodeRef<'a>; + + fn kind<'b>(&'b self) -> RefKind<'b, &'a [u8], BencodeRef<'a>> { + match self.inner { + Inner::Int(n, _) => RefKind::Int(n), + Inner::Bytes(n, _) => RefKind::Bytes(n), + Inner::List(ref n, _) => RefKind::List(n), + Inner::Dict(ref n, _) => RefKind::Dict(n), + } + } + + fn str(&self) -> Option<&str> { + self.str_ext() + } + + fn int(&self) -> Option { + match self.inner { + Inner::Int(n, _) => Some(n), + _ => None, + } + } + + fn bytes(&self) -> Option<&[u8]> { + self.bytes_ext() + } + + fn list(&self) -> Option<&dyn BListAccess>> { + match self.inner { + Inner::List(ref n, _) => Some(n), + _ => None, + } + } + + fn dict(&self) -> Option<&dyn BDictAccess<&'a [u8], BencodeRef<'a>>> { + match self.inner { + Inner::Dict(ref n, _) => Some(n), + _ => None, + } + } +} + +impl<'a> BRefAccessExt<'a> for BencodeRef<'a> { + fn str_ext(&self) -> Option<&'a str> { + let bytes = self.bytes_ext()?; + + match str::from_utf8(bytes) { + Ok(n) => Some(n), + Err(_) => None, + } + } + + fn bytes_ext(&self) -> Option<&'a [u8]> { + match self.inner { + Inner::Bytes(n, _) => Some(&n[0..]), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use std::default::Default; + + use crate::access::bencode::BRefAccess; + use crate::reference::bencode_ref::BencodeRef; + use crate::reference::decode_opt::BDecodeOpt; + + #[test] + fn positive_int_buffer() { + let int_bytes = b"i-500e"; // cspell:disable-line + let bencode = BencodeRef::decode(&int_bytes[..], BDecodeOpt::default()).unwrap(); + + assert_eq!(int_bytes, bencode.buffer()); + } + + #[test] + fn positive_bytes_buffer() { + let bytes_bytes = b"3:asd"; // cspell:disable-line + let bencode = BencodeRef::decode(&bytes_bytes[..], BDecodeOpt::default()).unwrap(); + + assert_eq!(bytes_bytes, bencode.buffer()); + } + + #[test] + fn positive_list_buffer() { + let list_bytes = b"l3:asde"; // cspell:disable-line + let bencode = BencodeRef::decode(&list_bytes[..], BDecodeOpt::default()).unwrap(); + + assert_eq!(list_bytes, bencode.buffer()); + } + + #[test] + fn positive_dict_buffer() { + let dict_bytes = b"d3:asd3:asde"; // cspell:disable-line + let bencode = BencodeRef::decode(&dict_bytes[..], BDecodeOpt::default()).unwrap(); + + assert_eq!(dict_bytes, bencode.buffer()); + } + + #[test] + fn positive_list_nested_int_buffer() { + let nested_int_bytes = b"li-500ee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_int_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_list = bencode.list().unwrap(); + let bencode_int = bencode_list.get(0).unwrap(); + + let int_bytes = b"i-500e"; // cspell:disable-line + assert_eq!(int_bytes, bencode_int.buffer()); + } + + #[test] + fn positive_dict_nested_int_buffer() { + let nested_int_bytes = b"d3:asdi-500ee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_int_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_dict = bencode.dict().unwrap(); + /* cspell:disable-next-line */ + let bencode_int = bencode_dict.lookup(&b"asd"[..]).unwrap(); + + let int_bytes = b"i-500e"; // cspell:disable-line + assert_eq!(int_bytes, bencode_int.buffer()); + } + + #[test] + fn positive_list_nested_bytes_buffer() { + let nested_bytes_bytes = b"l3:asde"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_bytes_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_list = bencode.list().unwrap(); + let bencode_bytes = bencode_list.get(0).unwrap(); + + let bytes_bytes = b"3:asd"; // cspell:disable-line + assert_eq!(bytes_bytes, bencode_bytes.buffer()); + } + + #[test] + fn positive_dict_nested_bytes_buffer() { + let nested_bytes_bytes = b"d3:asd3:asde"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_bytes_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_dict = bencode.dict().unwrap(); + /* cspell:disable-next-line */ + let bencode_bytes = bencode_dict.lookup(&b"asd"[..]).unwrap(); + + let bytes_bytes = b"3:asd"; // cspell:disable-line + assert_eq!(bytes_bytes, bencode_bytes.buffer()); + } + + #[test] + fn positive_list_nested_list_buffer() { + let nested_list_bytes = b"ll3:asdee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_list_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_list = bencode.list().unwrap(); + let bencode_list = bencode_list.get(0).unwrap(); + + let list_bytes = b"l3:asde"; // cspell:disable-line + assert_eq!(list_bytes, bencode_list.buffer()); + } + + #[test] + fn positive_dict_nested_list_buffer() { + let nested_list_bytes = b"d3:asdl3:asdee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_list_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_dict = bencode.dict().unwrap(); + /* cspell:disable-next-line */ + let bencode_list = bencode_dict.lookup(&b"asd"[..]).unwrap(); + + let list_bytes = b"l3:asde"; // cspell:disable-line + assert_eq!(list_bytes, bencode_list.buffer()); + } + + #[test] + fn positive_list_nested_dict_buffer() { + let nested_dict_bytes = b"ld3:asd3:asdee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_dict_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_list = bencode.list().unwrap(); + let bencode_dict = bencode_list.get(0).unwrap(); + + let dict_bytes = b"d3:asd3:asde"; // cspell:disable-line + assert_eq!(dict_bytes, bencode_dict.buffer()); + } + + #[test] + fn positive_dict_nested_dict_buffer() { + let nested_dict_bytes = b"d3:asdd3:asd3:asdee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_dict_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_dict = bencode.dict().unwrap(); + /* cspell:disable-next-line */ + let bencode_dict = bencode_dict.lookup(&b"asd"[..]).unwrap(); + + let dict_bytes = b"d3:asd3:asde"; // cspell:disable-line + assert_eq!(dict_bytes, bencode_dict.buffer()); + } +} diff --git a/contrib/bencode/src/reference/decode.rs b/contrib/bencode/src/reference/decode.rs new file mode 100644 index 000000000..96ab6dfbf --- /dev/null +++ b/contrib/bencode/src/reference/decode.rs @@ -0,0 +1,398 @@ +use std::collections::btree_map::Entry; +use std::collections::BTreeMap; +use std::str::{self}; + +use crate::error::{BencodeParseError, BencodeParseErrorKind, BencodeParseResult}; +use crate::reference::bencode_ref::{BencodeRef, Inner}; +use crate::reference::decode_opt::BDecodeOpt; + +pub fn decode(bytes: &[u8], pos: usize, opts: BDecodeOpt, depth: usize) -> BencodeParseResult<(BencodeRef<'_>, usize)> { + if depth >= opts.max_recursion() { + return Err(BencodeParseError::from_kind( + BencodeParseErrorKind::InvalidRecursionExceeded { pos, max: depth }, + )); + } + let curr_byte = peek_byte(bytes, pos)?; + + match curr_byte { + crate::INT_START => { + let (bencode, next_pos) = decode_int(bytes, pos + 1, crate::BEN_END)?; + Ok((Inner::Int(bencode, &bytes[pos..next_pos]).into(), next_pos)) + } + crate::LIST_START => { + let (bencode, next_pos) = decode_list(bytes, pos + 1, opts, depth)?; + Ok((Inner::List(bencode, &bytes[pos..next_pos]).into(), next_pos)) + } + crate::DICT_START => { + let (bencode, next_pos) = decode_dict(bytes, pos + 1, opts, depth)?; + Ok((Inner::Dict(bencode, &bytes[pos..next_pos]).into(), next_pos)) + } + crate::BYTE_LEN_LOW..=crate::BYTE_LEN_HIGH => { + let (bencode, next_pos) = decode_bytes(bytes, pos)?; + // Include the length digit, don't increment position + Ok((Inner::Bytes(bencode, &bytes[pos..next_pos]).into(), next_pos)) + } + _ => Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidByte { pos })), + } +} + +fn decode_int(bytes: &[u8], pos: usize, delim: u8) -> BencodeParseResult<(i64, usize)> { + let (_, begin_decode) = bytes.split_at(pos); + + let Some(relative_end_pos) = begin_decode.iter().position(|n| *n == delim) else { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntNoDelimiter { + pos, + })); + }; + let int_byte_slice = &begin_decode[..relative_end_pos]; + + if int_byte_slice.len() > 1 { + // Negative zero is not allowed (this would not be caught when converting) + if int_byte_slice[0] == b'-' && int_byte_slice[1] == b'0' { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntNegativeZero { + pos, + })); + } + + // Zero padding is illegal, and unspecified for key lengths (we disallow both) + if int_byte_slice[0] == b'0' { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntZeroPadding { + pos, + })); + } + } + + let Ok(int_str) = str::from_utf8(int_byte_slice) else { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntParseError { + pos, + })); + }; + + // Position of end of integer type, next byte is the start of the next value + let absolute_end_pos = pos + relative_end_pos; + let next_pos = absolute_end_pos + 1; + match int_str.parse::() { + Ok(n) => Ok((n, next_pos)), + Err(_) => Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntParseError { + pos, + })), + } +} + +fn decode_bytes(bytes: &[u8], pos: usize) -> BencodeParseResult<(&[u8], usize)> { + let (num_bytes, start_pos) = decode_int(bytes, pos, crate::BYTE_LEN_END)?; + + if num_bytes < 0 { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidLengthNegative { + pos, + })); + } + + // Should be safe to cast to usize (TODO: Check if cast would overflow to provide + // a more helpful error message, otherwise, parsing will probably fail with an + // unrelated message). + let num_bytes = + usize::try_from(num_bytes).map_err(|_| BencodeParseErrorKind::Msg(format!("input length is too long: {num_bytes}")))?; + + if num_bytes > bytes[start_pos..].len() { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidLengthOverflow { + pos, + })); + } + + let next_pos = start_pos + num_bytes; + Ok((&bytes[start_pos..next_pos], next_pos)) +} + +fn decode_list(bytes: &[u8], pos: usize, opts: BDecodeOpt, depth: usize) -> BencodeParseResult<(Vec>, usize)> { + let mut bencode_list = Vec::new(); + + let mut curr_pos = pos; + let mut curr_byte = peek_byte(bytes, curr_pos)?; + + while curr_byte != crate::BEN_END { + let (bencode, next_pos) = decode(bytes, curr_pos, opts, depth + 1)?; + + bencode_list.push(bencode); + + curr_pos = next_pos; + curr_byte = peek_byte(bytes, curr_pos)?; + } + + let next_pos = curr_pos + 1; + Ok((bencode_list, next_pos)) +} + +fn decode_dict( + bytes: &[u8], + pos: usize, + opts: BDecodeOpt, + depth: usize, +) -> BencodeParseResult<(BTreeMap<&[u8], BencodeRef<'_>>, usize)> { + let mut bencode_dict = BTreeMap::new(); + + let mut curr_pos = pos; + let mut curr_byte = peek_byte(bytes, curr_pos)?; + + while curr_byte != crate::BEN_END { + let (key_bytes, next_pos) = decode_bytes(bytes, curr_pos)?; + + // Spec says that the keys must be in alphabetical order + match (bencode_dict.keys().last(), opts.check_key_sort()) { + (Some(last_key), true) if key_bytes < *last_key => { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidKeyOrdering { + pos: curr_pos, + key: key_bytes.to_vec(), + })) + } + _ => (), + }; + curr_pos = next_pos; + + let (value, next_pos) = decode(bytes, curr_pos, opts, depth + 1)?; + match bencode_dict.entry(key_bytes) { + Entry::Vacant(n) => n.insert(value), + Entry::Occupied(_) => { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidKeyDuplicates { + pos: curr_pos, + key: key_bytes.to_vec(), + })) + } + }; + + curr_pos = next_pos; + curr_byte = peek_byte(bytes, curr_pos)?; + } + + let next_pos = curr_pos + 1; + Ok((bencode_dict, next_pos)) +} + +fn peek_byte(bytes: &[u8], pos: usize) -> BencodeParseResult { + bytes + .get(pos) + .copied() + .ok_or_else(|| BencodeParseError::from_kind(BencodeParseErrorKind::BytesEmpty { pos })) +} + +#[cfg(test)] +mod tests { + use std::default::Default; + + use crate::access::bencode::BRefAccess; + use crate::reference::bencode_ref::BencodeRef; + use crate::reference::decode_opt::BDecodeOpt; + + /* cSpell:disable */ + // Positive Cases + const GENERAL: &[u8] = b"d0:12:zero_len_key8:location17:udp://test.com:8011:nested dictd4:listli-500500eee6:numberi500500ee"; + const RECURSION: &[u8] = b"lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee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ei0eee8:test_key10:test_valuee"; + const LIST: &[u8] = b"l10:test_bytesi500ei0ei-500el12:nested_bytesed8:test_key10:test_valueee"; + const BYTES: &[u8] = b"5:\xC5\xE6\xBE\xE6\xF2"; + const BYTES_ZERO_LEN: &[u8] = b"0:"; + const INT: &[u8] = b"i500e"; + const INT_NEGATIVE: &[u8] = b"i-500e"; + const INT_ZERO: &[u8] = b"i0e"; + const PARTIAL: &[u8] = b"i0e_asd"; + + // Negative Cases + const BYTES_NEG_LEN: &[u8] = b"-4:test"; + const BYTES_EXTRA: &[u8] = b"l15:processed_bytese17:unprocessed_bytes"; + const BYTES_NOT_UTF8: &[u8] = b"5:\xC5\xE6\xBE\xE6\xF2"; + const INT_NAN: &[u8] = b"i500a500e"; + const INT_LEADING_ZERO: &[u8] = b"i0500e"; + const INT_DOUBLE_ZERO: &[u8] = b"i00e"; + const INT_NEGATIVE_ZERO: &[u8] = b"i-0e"; + const INT_DOUBLE_NEGATIVE: &[u8] = b"i--5e"; + const DICT_UNORDERED_KEYS: &[u8] = b"d5:z_key5:value5:a_key5:valuee"; + const DICT_DUP_KEYS_SAME_DATA: &[u8] = b"d5:a_keyi0e5:a_keyi0ee"; + const DICT_DUP_KEYS_DIFF_DATA: &[u8] = b"d5:a_keyi0e5:a_key7:a_valuee"; + /* cSpell:enable */ + + #[test] + fn positive_decode_general() { + let bencode = BencodeRef::decode(GENERAL, BDecodeOpt::default()).unwrap(); + + let ben_dict = bencode.dict().unwrap(); + assert_eq!(ben_dict.lookup("".as_bytes()).unwrap().str().unwrap(), "zero_len_key"); + assert_eq!( + ben_dict.lookup("location".as_bytes()).unwrap().str().unwrap(), + "udp://test.com:80" + ); + assert_eq!(ben_dict.lookup("number".as_bytes()).unwrap().int().unwrap(), 500_500_i64); + + let nested_dict = ben_dict.lookup("nested dict".as_bytes()).unwrap().dict().unwrap(); + let nested_list = nested_dict.lookup("list".as_bytes()).unwrap().list().unwrap(); + assert_eq!(nested_list[0].int().unwrap(), -500_500_i64); + } + + #[test] + fn positive_decode_recursion() { + BencodeRef::decode(RECURSION, BDecodeOpt::new(50, true, true)).unwrap_err(); + + // As long as we didn't overflow our call stack, we are good! + } + + #[test] + fn positive_decode_bytes_utf8() { + let bencode = BencodeRef::decode(BYTES_UTF8, BDecodeOpt::default()).unwrap(); + + assert_eq!(bencode.str().unwrap(), "valid_utf8_bytes"); + } + + #[test] + fn positive_decode_dict() { + let bencode = BencodeRef::decode(DICTIONARY, BDecodeOpt::default()).unwrap(); + let dict = bencode.dict().unwrap(); + assert_eq!(dict.lookup("test_key".as_bytes()).unwrap().str().unwrap(), "test_value"); + + let nested_dict = dict.lookup("test_dict".as_bytes()).unwrap().dict().unwrap(); + assert_eq!( + nested_dict.lookup("nested_key".as_bytes()).unwrap().str().unwrap(), + "nested_value" + ); + + let nested_list = nested_dict.lookup("nested_list".as_bytes()).unwrap().list().unwrap(); + assert_eq!(nested_list[0].int().unwrap(), 500i64); + assert_eq!(nested_list[1].int().unwrap(), -500i64); + assert_eq!(nested_list[2].int().unwrap(), 0i64); + } + + #[test] + fn positive_decode_list() { + let bencode = BencodeRef::decode(LIST, BDecodeOpt::default()).unwrap(); + let list = bencode.list().unwrap(); + + assert_eq!(list[0].str().unwrap(), "test_bytes"); + assert_eq!(list[1].int().unwrap(), 500i64); + assert_eq!(list[2].int().unwrap(), 0i64); + assert_eq!(list[3].int().unwrap(), -500i64); + + let nested_list = list[4].list().unwrap(); + assert_eq!(nested_list[0].str().unwrap(), "nested_bytes"); + + let nested_dict = list[5].dict().unwrap(); + assert_eq!( + nested_dict.lookup("test_key".as_bytes()).unwrap().str().unwrap(), + "test_value" + ); + } + + #[test] + fn positive_decode_bytes() { + let bytes = super::decode_bytes(BYTES, 0).unwrap().0; + assert_eq!(bytes.len(), 5); + assert_eq!(bytes[0] as char, 'Å'); + assert_eq!(bytes[1] as char, 'æ'); + assert_eq!(bytes[2] as char, '¾'); + assert_eq!(bytes[3] as char, 'æ'); + assert_eq!(bytes[4] as char, 'ò'); + } + + #[test] + fn positive_decode_bytes_zero_len() { + let bytes = super::decode_bytes(BYTES_ZERO_LEN, 0).unwrap().0; + assert_eq!(bytes.len(), 0); + } + + #[test] + fn positive_decode_int() { + let int_value = super::decode_int(INT, 1, crate::BEN_END).unwrap().0; + assert_eq!(int_value, 500i64); + } + + #[test] + fn positive_decode_int_negative() { + let int_value = super::decode_int(INT_NEGATIVE, 1, crate::BEN_END).unwrap().0; + assert_eq!(int_value, -500i64); + } + + #[test] + fn positive_decode_int_zero() { + let int_value = super::decode_int(INT_ZERO, 1, crate::BEN_END).unwrap().0; + assert_eq!(int_value, 0i64); + } + + #[test] + fn positive_decode_partial() { + let bencode = BencodeRef::decode(PARTIAL, BDecodeOpt::new(2, true, false)).unwrap(); + + assert_ne!(PARTIAL.len(), bencode.buffer().len()); + assert_eq!(3, bencode.buffer().len()); + } + + #[test] + fn positive_decode_dict_unordered_keys() { + BencodeRef::decode(DICT_UNORDERED_KEYS, BDecodeOpt::default()).unwrap(); + } + + #[test] + #[should_panic] + fn negative_decode_bytes_neg_len() { + BencodeRef::decode(BYTES_NEG_LEN, BDecodeOpt::default()).unwrap(); + } + + #[test] + #[should_panic] + fn negative_decode_bytes_extra() { + BencodeRef::decode(BYTES_EXTRA, BDecodeOpt::default()).unwrap(); + } + + #[test] + #[should_panic] + fn negative_decode_bytes_not_utf8() { + let bencode = BencodeRef::decode(BYTES_NOT_UTF8, BDecodeOpt::default()).unwrap(); + + bencode.str().unwrap(); + } + + #[test] + #[should_panic] + fn negative_decode_int_nan() { + super::decode_int(INT_NAN, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic] + fn negative_decode_int_leading_zero() { + super::decode_int(INT_LEADING_ZERO, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic] + fn negative_decode_int_double_zero() { + super::decode_int(INT_DOUBLE_ZERO, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic] + fn negative_decode_int_negative_zero() { + super::decode_int(INT_NEGATIVE_ZERO, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic] + fn negative_decode_int_double_negative() { + super::decode_int(INT_DOUBLE_NEGATIVE, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic] + fn negative_decode_dict_unordered_keys() { + BencodeRef::decode(DICT_UNORDERED_KEYS, BDecodeOpt::new(5, true, true)).unwrap(); + } + + #[test] + #[should_panic] + fn negative_decode_dict_dup_keys_same_data() { + BencodeRef::decode(DICT_DUP_KEYS_SAME_DATA, BDecodeOpt::default()).unwrap(); + } + + #[test] + #[should_panic] + fn negative_decode_dict_dup_keys_diff_data() { + BencodeRef::decode(DICT_DUP_KEYS_DIFF_DATA, BDecodeOpt::default()).unwrap(); + } +} diff --git a/contrib/bencode/src/reference/decode_opt.rs b/contrib/bencode/src/reference/decode_opt.rs new file mode 100644 index 000000000..ac94d0311 --- /dev/null +++ b/contrib/bencode/src/reference/decode_opt.rs @@ -0,0 +1,55 @@ +use std::default::Default; + +const DEFAULT_MAX_RECURSION: usize = 50; +const DEFAULT_CHECK_KEY_SORT: bool = false; +const DEFAULT_ENFORCE_FULL_DECODE: bool = true; + +/// Stores decoding options for modifying decode behavior. +#[derive(Copy, Clone)] +#[allow(clippy::module_name_repetitions)] +pub struct BDecodeOpt { + max_recursion: usize, + check_key_sort: bool, + enforce_full_decode: bool, +} + +impl BDecodeOpt { + /// Create a new `BDecodeOpt` object. + #[must_use] + pub fn new(max_recursion: usize, check_key_sort: bool, enforce_full_decode: bool) -> BDecodeOpt { + BDecodeOpt { + max_recursion, + check_key_sort, + enforce_full_decode, + } + } + + /// Maximum limit allowed when decoding bencode. + #[must_use] + pub fn max_recursion(&self) -> usize { + self.max_recursion + } + + /// Whether or not an error should be thrown for out of order dictionary keys. + #[must_use] + pub fn check_key_sort(&self) -> bool { + self.check_key_sort + } + + /// Whether or not we enforce that the decoded bencode must make up all of the input + /// bytes or not. + /// + /// It may be useful to disable this if for example, the input bencode is prepended to + /// some payload and you would like to disassociate it. In this case, to find where the + /// rest of the payload starts that wasn't decoded, get the bencode buffer, and call len(). + #[must_use] + pub fn enforce_full_decode(&self) -> bool { + self.enforce_full_decode + } +} + +impl Default for BDecodeOpt { + fn default() -> BDecodeOpt { + BDecodeOpt::new(DEFAULT_MAX_RECURSION, DEFAULT_CHECK_KEY_SORT, DEFAULT_ENFORCE_FULL_DECODE) + } +} diff --git a/contrib/bencode/src/reference/mod.rs b/contrib/bencode/src/reference/mod.rs new file mode 100644 index 000000000..6a0ae6e40 --- /dev/null +++ b/contrib/bencode/src/reference/mod.rs @@ -0,0 +1,3 @@ +pub mod bencode_ref; +pub mod decode; +pub mod decode_opt; diff --git a/contrib/bencode/test/mod.rs b/contrib/bencode/test/mod.rs new file mode 100644 index 000000000..c1454967d --- /dev/null +++ b/contrib/bencode/test/mod.rs @@ -0,0 +1,18 @@ +use bencode::{ben_bytes, ben_int, ben_list, ben_map}; + +#[test] +fn positive_ben_map_macro() { + let result = (ben_map! { + "key" => ben_bytes!("value") + }) + .encode(); + + assert_eq!("d3:key5:valuee".as_bytes(), &result[..]); // cspell:disable-line +} + +#[test] +fn positive_ben_list_macro() { + let result = (ben_list!(ben_int!(5))).encode(); + + assert_eq!("li5ee".as_bytes(), &result[..]); // cspell:disable-line +} diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index 0cd62578a..e7b64522c 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -7,7 +7,7 @@ use std::panic::Location; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; -use bip_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; +use bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; use serde::{self, Deserialize, Serialize}; use thiserror::Error; diff --git a/src/servers/http/v1/responses/scrape.rs b/src/servers/http/v1/responses/scrape.rs index 6610f9dc4..c2f099597 100644 --- a/src/servers/http/v1/responses/scrape.rs +++ b/src/servers/http/v1/responses/scrape.rs @@ -5,7 +5,7 @@ use std::borrow::Cow; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; -use bip_bencode::{ben_int, ben_map, BMutAccess}; +use bencode::{ben_int, ben_map, BMutAccess}; use crate::tracker::ScrapeData; From adcbf351d04c1b8b87f36d3b77634d42b2ef2493 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 7 Aug 2023 15:51:30 +0200 Subject: [PATCH 0051/1297] ci: overhaul testing workflow --- .github/workflows/test_build_release.yml | 81 ----------------- .github/workflows/testing.yaml | 109 +++++++++++++++++++++++ cSpell.json | 2 + 3 files changed, 111 insertions(+), 81 deletions(-) delete mode 100644 .github/workflows/test_build_release.yml create mode 100644 .github/workflows/testing.yaml diff --git a/.github/workflows/test_build_release.yml b/.github/workflows/test_build_release.yml deleted file mode 100644 index 88234b97a..000000000 --- a/.github/workflows/test_build_release.yml +++ /dev/null @@ -1,81 +0,0 @@ -name: CI - -# Only trigger, when the test workflow succeeded -on: [push, pull_request] - -jobs: - format: - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: nightly - components: rustfmt, clippy - - uses: Swatinem/rust-cache@v2 - - name: Check Rust Formatting - run: cargo fmt --check - - test: - needs: format - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - components: llvm-tools-preview - - uses: Swatinem/rust-cache@v2 - - name: Check Rust Code - run: cargo check --all-targets - - name: Clippy Rust Code - run: cargo clippy --all-targets -- -D clippy::pedantic - - name: Test Documentation - run: cargo test --doc - - name: Run Tests - run: cargo test --workspace - - uses: taiki-e/install-action@cargo-llvm-cov - - uses: taiki-e/install-action@nextest - - name: Show coverage - run: cargo llvm-cov nextest - - build: - needs: test - if: | - github.event_name == 'push' && - github.event.base_ref == 'refs/heads/main' && - startsWith(github.ref, 'refs/tags/v') - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - - uses: Swatinem/rust-cache@v2 - - name: Build Torrust Tracker - run: cargo build --release - - name: Upload Build Artifact - uses: actions/upload-artifact@v3 - with: - name: torrust-tracker - path: ./target/release/torrust-tracker - - release: - needs: build - runs-on: ubuntu-latest - steps: - - name: Download Build Artifact - uses: actions/download-artifact@v3 - with: - name: torrust-tracker - - name: Release - uses: softprops/action-gh-release@v1 -# with: -# files: | -# torrust-tracker diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml new file mode 100644 index 000000000..c1f85a90b --- /dev/null +++ b/.github/workflows/testing.yaml @@ -0,0 +1,109 @@ +name: Testing + +on: + push: + pull_request: + +env: + CARGO_TERM_COLOR: always + +jobs: + format: + name: Formatting + runs-on: ubuntu-latest + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v3 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: nightly + components: rustfmt + + - id: cache + name: Enable Workflow Cache + uses: Swatinem/rust-cache@v2 + + - id: format + name: Run Formatting-Checks + run: cargo fmt --check + + check: + name: Static Analysis + runs-on: ubuntu-latest + needs: format + + strategy: + matrix: + toolchain: [stable, nightly] + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v3 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: nightly + components: clippy + + - id: cache + name: Enable Workflow Cache + uses: Swatinem/rust-cache@v2 + + - id: check + name: Run Build Checks + run: cargo check --tests --benches --examples --workspace --all-targets --all-features + + - id: lint + name: Run Lint Checks + run: cargo clippy --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic + + - id: doc + name: Run Documentation Checks + run: cargo test --doc + + unit: + name: Units + runs-on: ubuntu-latest + needs: check + + strategy: + matrix: + toolchain: [stable, nightly] + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v3 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + components: llvm-tools-preview + + - id: cache + name: Enable Job Cache + uses: Swatinem/rust-cache@v2 + + - id: tools + name: Install Tools + uses: taiki-e/install-action@v2 + with: + tool: cargo-llvm-cov, cargo-nextest + + - id: test + name: Run Unit Tests + run: cargo test --tests --benches --examples --workspace --all-targets --all-features + + - id: coverage + name: Generate Coverage Report + run: cargo llvm-cov nextest --tests --benches --examples --workspace --all-targets --all-features diff --git a/cSpell.json b/cSpell.json index 5cafa68ed..8a85739e2 100644 --- a/cSpell.json +++ b/cSpell.json @@ -37,10 +37,12 @@ "hlocalhost", "Hydranode", "Icelake", + "imdl", "incompletei", "infohash", "infohashes", "infoschema", + "Intermodal", "intervali", "lcov", "leecher", From 76b270b1d6e8068574d9c2916297b7bc07fef78f Mon Sep 17 00:00:00 2001 From: Alex Wellnitz Date: Sat, 26 Aug 2023 21:44:38 +0200 Subject: [PATCH 0052/1297] #326: Add tower-http compression as middleware --- Cargo.lock | 158 ++++++++++++++++++++++++++++++++++ Cargo.toml | 1 + src/servers/apis/routes.rs | 11 ++- src/servers/http/v1/routes.rs | 2 + 4 files changed, 168 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f2053b043..789e2caec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -48,6 +48,21 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "allocator-api2" version = "0.2.16" @@ -103,6 +118,22 @@ version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" +[[package]] +name = "async-compression" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b74f44609f0f91493e3082d3734d98497e094777144380ea4db9f9905dd5b6" +dependencies = [ + "brotli", + "flate2", + "futures-core", + "memchr", + "pin-project-lite", + "tokio", + "zstd", + "zstd-safe", +] + [[package]] name = "async-trait" version = "0.1.73" @@ -349,6 +380,27 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "brotli" +version = "3.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a0b1dbcc8ae29329621f8d4f0d835787c1c38bb1401979b49d13b0b305ff68" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "2.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b6561fd3f895a11e8f72af2cb7d22e08366bebc2b6b57f7744c4bda27034744" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bufstream" version = "0.1.4" @@ -407,6 +459,7 @@ version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" dependencies = [ + "jobserver", "libc", ] @@ -1199,6 +1252,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "http-range-header" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "add0ab9360ddbd88cfeb3bd9574a1d85cfdfa14db10b3e21d3700dbc4328758f" + [[package]] name = "httparse" version = "1.8.0" @@ -1325,6 +1384,16 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" +[[package]] +name = "iri-string" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21859b667d66a4c1dacd9df0863b3efb65785474255face87f5bca39dd8407c0" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "is-terminal" version = "0.4.9" @@ -1351,6 +1420,15 @@ version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" +[[package]] +name = "jobserver" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "936cfd212a0155903bcbc060e316fb6cc7cbf2e1907329391ebadc1fe0ce77c2" +dependencies = [ + "libc", +] + [[package]] name = "js-sys" version = "0.3.64" @@ -1570,6 +1648,16 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -3068,6 +3156,7 @@ dependencies = [ "torrust-tracker-located-error", "torrust-tracker-primitives", "torrust-tracker-test-helpers", + "tower-http", "uuid", ] @@ -3128,6 +3217,36 @@ dependencies = [ "tracing", ] +[[package]] +name = "tower-http" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55ae70283aba8d2a8b411c695c437fe25b8b5e44e23e780662002fc72fb47a82" +dependencies = [ + "async-compression", + "base64 0.21.2", + "bitflags 2.4.0", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-range-header", + "httpdate", + "iri-string", + "mime", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "tokio", + "tokio-util", + "tower", + "tower-layer", + "tower-service", + "tracing", + "uuid", +] + [[package]] name = "tower-layer" version = "0.3.2" @@ -3190,6 +3309,15 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" +[[package]] +name = "unicase" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" +dependencies = [ + "version_check", +] + [[package]] name = "unicode-bidi" version = "0.3.13" @@ -3492,3 +3620,33 @@ checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" dependencies = [ "linked-hash-map", ] + +[[package]] +name = "zstd" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a27595e173641171fc74a1232b7b1c7a7cb6e18222c11e9dfb9888fa424c53c" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "6.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee98ffd0b48ee95e6c5168188e44a54550b1564d9d530ee21d5f0eaed1069581" +dependencies = [ + "libc", + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.8+zstd.1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5556e6ee25d32df2586c098bbfa278803692a20d0ab9565e049480d52707ec8c" +dependencies = [ + "cc", + "libc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml index a939318cd..22d9b2b4f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ uuid = { version = "1", features = ["v4"] } axum = "0.6.20" axum-server = { version = "0.5", features = ["tls-rustls"] } axum-client-ip = "0.4.1" +tower-http = { version= "0.4.3", features = ["full"] } bencode = { version = "1.0.0-alpha.1", path = "contrib/bencode" } torrust-tracker-primitives = { version = "3.0.0-alpha.3", path = "packages/primitives" } torrust-tracker-configuration = { version = "3.0.0-alpha.3", path = "packages/configuration" } diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index a4c4642c7..7801389f3 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -8,6 +8,7 @@ use std::sync::Arc; use axum::{middleware, Router}; +use tower_http::compression::CompressionLayer; use super::v1; use crate::tracker::Tracker; @@ -21,8 +22,10 @@ pub fn router(tracker: Arc) -> Router { let router = v1::routes::add(prefix, router, tracker.clone()); - router.layer(middleware::from_fn_with_state( - tracker.config.clone(), - v1::middlewares::auth::auth, - )) + router + .layer(middleware::from_fn_with_state( + tracker.config.clone(), + v1::middlewares::auth::auth, + )) + .layer(CompressionLayer::new()) } diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 86bdf480f..6546dcbb8 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use axum::routing::get; use axum::Router; use axum_client_ip::SecureClientIpSource; +use tower_http::compression::CompressionLayer; use super::handlers::{announce, scrape}; use crate::tracker::Tracker; @@ -23,4 +24,5 @@ pub fn router(tracker: Arc) -> Router { .route("/scrape/:key", get(scrape::handle_with_key).with_state(tracker)) // Add extension to get the client IP from the connection info .layer(SecureClientIpSource::ConnectInfo.into_extension()) + .layer(CompressionLayer::new()) } From 22bb98af388e8fe801b174786bfe0bbe49fc85c8 Mon Sep 17 00:00:00 2001 From: Alex Wellnitz Date: Sat, 26 Aug 2023 22:08:08 +0200 Subject: [PATCH 0053/1297] #326: Use only compression features of tower-http --- Cargo.lock | 38 -------------------------------------- Cargo.toml | 2 +- 2 files changed, 1 insertion(+), 39 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 789e2caec..768d0ea60 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1384,16 +1384,6 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" -[[package]] -name = "iri-string" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21859b667d66a4c1dacd9df0863b3efb65785474255face87f5bca39dd8407c0" -dependencies = [ - "memchr", - "serde", -] - [[package]] name = "is-terminal" version = "0.4.9" @@ -1648,16 +1638,6 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" -[[package]] -name = "mime_guess" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef" -dependencies = [ - "mime", - "unicase", -] - [[package]] name = "minimal-lexical" version = "0.2.1" @@ -3224,7 +3204,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55ae70283aba8d2a8b411c695c437fe25b8b5e44e23e780662002fc72fb47a82" dependencies = [ "async-compression", - "base64 0.21.2", "bitflags 2.4.0", "bytes", "futures-core", @@ -3232,19 +3211,11 @@ dependencies = [ "http", "http-body", "http-range-header", - "httpdate", - "iri-string", - "mime", - "mime_guess", - "percent-encoding", "pin-project-lite", "tokio", "tokio-util", - "tower", "tower-layer", "tower-service", - "tracing", - "uuid", ] [[package]] @@ -3309,15 +3280,6 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" -[[package]] -name = "unicase" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" -dependencies = [ - "version_check", -] - [[package]] name = "unicode-bidi" version = "0.3.13" diff --git a/Cargo.toml b/Cargo.toml index 22d9b2b4f..a265f32ef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,7 +41,7 @@ uuid = { version = "1", features = ["v4"] } axum = "0.6.20" axum-server = { version = "0.5", features = ["tls-rustls"] } axum-client-ip = "0.4.1" -tower-http = { version= "0.4.3", features = ["full"] } +tower-http = { version= "0.4.3", features = ["compression-full"] } bencode = { version = "1.0.0-alpha.1", path = "contrib/bencode" } torrust-tracker-primitives = { version = "3.0.0-alpha.3", path = "packages/primitives" } torrust-tracker-configuration = { version = "3.0.0-alpha.3", path = "packages/configuration" } From 2fa374286f90ef3c12b168889da2bd19eddb6768 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 5 Sep 2023 22:16:35 +0200 Subject: [PATCH 0054/1297] dev: add expected message to bencode panic tests --- contrib/bencode/src/reference/decode.rs | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/contrib/bencode/src/reference/decode.rs b/contrib/bencode/src/reference/decode.rs index 96ab6dfbf..d2aa180f8 100644 --- a/contrib/bencode/src/reference/decode.rs +++ b/contrib/bencode/src/reference/decode.rs @@ -329,69 +329,68 @@ mod tests { } #[test] - #[should_panic] + #[should_panic = "BencodeParseError(InvalidByte { pos: 0 }"] fn negative_decode_bytes_neg_len() { BencodeRef::decode(BYTES_NEG_LEN, BDecodeOpt::default()).unwrap(); } #[test] - #[should_panic] + #[should_panic = "BencodeParseError(BytesEmpty { pos: 20 }"] fn negative_decode_bytes_extra() { BencodeRef::decode(BYTES_EXTRA, BDecodeOpt::default()).unwrap(); } #[test] - #[should_panic] fn negative_decode_bytes_not_utf8() { let bencode = BencodeRef::decode(BYTES_NOT_UTF8, BDecodeOpt::default()).unwrap(); - bencode.str().unwrap(); + assert!(bencode.str().is_none()); } #[test] - #[should_panic] + #[should_panic = "BencodeParseError(InvalidIntParseError { pos: 1 }"] fn negative_decode_int_nan() { super::decode_int(INT_NAN, 1, crate::BEN_END).unwrap(); } #[test] - #[should_panic] + #[should_panic = "BencodeParseError(InvalidIntZeroPadding { pos: 1 }"] fn negative_decode_int_leading_zero() { super::decode_int(INT_LEADING_ZERO, 1, crate::BEN_END).unwrap(); } #[test] - #[should_panic] + #[should_panic = "BencodeParseError(InvalidIntZeroPadding { pos: 1 }"] fn negative_decode_int_double_zero() { super::decode_int(INT_DOUBLE_ZERO, 1, crate::BEN_END).unwrap(); } #[test] - #[should_panic] + #[should_panic = "BencodeParseError(InvalidIntNegativeZero { pos: 1 }"] fn negative_decode_int_negative_zero() { super::decode_int(INT_NEGATIVE_ZERO, 1, crate::BEN_END).unwrap(); } #[test] - #[should_panic] + #[should_panic = " BencodeParseError(InvalidIntParseError { pos: 1 }"] fn negative_decode_int_double_negative() { super::decode_int(INT_DOUBLE_NEGATIVE, 1, crate::BEN_END).unwrap(); } #[test] - #[should_panic] + #[should_panic = "BencodeParseError(InvalidKeyOrdering { pos: 15, key: [97, 95, 107, 101, 121] }"] fn negative_decode_dict_unordered_keys() { BencodeRef::decode(DICT_UNORDERED_KEYS, BDecodeOpt::new(5, true, true)).unwrap(); } #[test] - #[should_panic] + #[should_panic = "BencodeParseError(InvalidKeyDuplicates { pos: 18, key: [97, 95, 107, 101, 121] }"] fn negative_decode_dict_dup_keys_same_data() { BencodeRef::decode(DICT_DUP_KEYS_SAME_DATA, BDecodeOpt::default()).unwrap(); } #[test] - #[should_panic] + #[should_panic = "BencodeParseError(InvalidKeyDuplicates { pos: 18, key: [97, 95, 107, 101, 121] }"] fn negative_decode_dict_dup_keys_diff_data() { BencodeRef::decode(DICT_DUP_KEYS_DIFF_DATA, BDecodeOpt::default()).unwrap(); } From 089fb48a521f9d3439c9104b4a683c99330a9552 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 5 Sep 2023 22:24:10 +0200 Subject: [PATCH 0055/1297] dev: add should_panic expected message to tracker tests --- src/servers/udp/connection_cookie.rs | 2 +- src/tracker/peer.rs | 16 +++++++++++----- tests/servers/api/v1/contract/configuration.rs | 2 +- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs index a389388a7..4dc9896ab 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/servers/udp/connection_cookie.rs @@ -314,7 +314,7 @@ mod tests { } #[test] - #[should_panic] + #[should_panic = "InvalidConnectionId"] fn it_should_be_not_valid_after_their_last_time_extent() { let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); diff --git a/src/tracker/peer.rs b/src/tracker/peer.rs index 76747fea2..d6517f213 100644 --- a/src/tracker/peer.rs +++ b/src/tracker/peer.rs @@ -150,7 +150,13 @@ impl Id { /// Will panic if byte slice does not contains the exact amount of bytes need for the `Id`. #[must_use] pub fn from_bytes(bytes: &[u8]) -> Self { - assert_eq!(bytes.len(), PEER_ID_BYTES_LEN); + assert_eq!( + PEER_ID_BYTES_LEN, + bytes.len(), + "we are testing the equality of the constant: `PEER_ID_BYTES_LEN` ({}) and the supplied `bytes` length: {}", + PEER_ID_BYTES_LEN, + bytes.len(), + ); let mut ret = Self([0u8; PEER_ID_BYTES_LEN]); ret.0.clone_from_slice(bytes); ret @@ -363,14 +369,14 @@ mod test { } #[test] - #[should_panic] + #[should_panic = "we are testing the equality of the constant: `PEER_ID_BYTES_LEN` (20) and the supplied `bytes` length: 19"] fn should_fail_trying_to_instantiate_from_a_byte_slice_with_less_than_20_bytes() { let less_than_20_bytes = [0; 19]; let _: peer::Id = peer::Id::from_bytes(&less_than_20_bytes); } #[test] - #[should_panic] + #[should_panic = "we are testing the equality of the constant: `PEER_ID_BYTES_LEN` (20) and the supplied `bytes` length: 21"] fn should_fail_trying_to_instantiate_from_a_byte_slice_with_more_than_20_bytes() { let more_than_20_bytes = [0; 21]; let _: peer::Id = peer::Id::from_bytes(&more_than_20_bytes); @@ -418,13 +424,13 @@ mod test { } #[test] - #[should_panic] + #[should_panic = "NotEnoughBytes"] fn should_fail_trying_to_convert_from_a_byte_vector_with_less_than_20_bytes() { let _: peer::Id = peer::Id::try_from([0; 19].to_vec()).unwrap(); } #[test] - #[should_panic] + #[should_panic = "TooManyBytes"] fn should_fail_trying_to_convert_from_a_byte_vector_with_more_than_20_bytes() { let _: peer::Id = peer::Id::try_from([0; 21].to_vec()).unwrap(); } diff --git a/tests/servers/api/v1/contract/configuration.rs b/tests/servers/api/v1/contract/configuration.rs index e4b608607..9ed257c51 100644 --- a/tests/servers/api/v1/contract/configuration.rs +++ b/tests/servers/api/v1/contract/configuration.rs @@ -3,7 +3,7 @@ use torrust_tracker_test_helpers::configuration; use crate::servers::api::test_environment::stopped_test_environment; #[tokio::test] -#[should_panic] +#[should_panic = "Could not receive bind_address."] async fn should_fail_with_ssl_enabled_and_bad_ssl_config() { let mut test_env = stopped_test_environment(configuration::ephemeral()); From efd1c995becbbf7fccf730d9cfa02157ce0c022c Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 6 Sep 2023 00:28:04 +0200 Subject: [PATCH 0056/1297] test: ignore ssl config test --- tests/servers/api/v1/contract/configuration.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/servers/api/v1/contract/configuration.rs b/tests/servers/api/v1/contract/configuration.rs index 9ed257c51..cfdb59b0c 100644 --- a/tests/servers/api/v1/contract/configuration.rs +++ b/tests/servers/api/v1/contract/configuration.rs @@ -3,6 +3,7 @@ use torrust_tracker_test_helpers::configuration; use crate::servers::api::test_environment::stopped_test_environment; #[tokio::test] +#[ignore] #[should_panic = "Could not receive bind_address."] async fn should_fail_with_ssl_enabled_and_bad_ssl_config() { let mut test_env = stopped_test_environment(configuration::ephemeral()); From ebd169791c0bb13ce87124e0c64c327924821b16 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 6 Sep 2023 00:25:35 +0200 Subject: [PATCH 0057/1297] chore: update lockfile --- Cargo.lock | 245 ++++++++++++++++++++-------------------- cSpell.json | 1 + src/shared/clock/mod.rs | 6 +- 3 files changed, 127 insertions(+), 125 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 768d0ea60..bc88e9bf5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "addr2line" -version = "0.20.0" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4fa78e18c64fce05e902adecd7a5eed15a5e0a3439f7b0e169f0252214865e3" +checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" dependencies = [ "gimli", ] @@ -41,9 +41,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6748e8def348ed4d14996fa801f4122cd763fff530258cdc03f64b25f89d3a5a" +checksum = "0c378d78423fdad8089616f827526ee33c19f2fddbd5de1629152c9593ba4783" dependencies = [ "memchr", ] @@ -92,9 +92,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstyle" -version = "1.0.1" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a30da5c5f2d5e72842e00bcb57657162cdabef0931f40e2deb9b4140440cecd" +checksum = "15c4c2c83f81532e5845a733998b6971faca23490340a418e9b72a3ec9de12ea" [[package]] name = "aquatic_udp_protocol" @@ -120,9 +120,9 @@ checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "async-compression" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b74f44609f0f91493e3082d3734d98497e094777144380ea4db9f9905dd5b6" +checksum = "d495b6dc0184693324491a5ac05f559acc97bf937ab31d7a1c33dd0016be6d2b" dependencies = [ "brotli", "flate2", @@ -142,7 +142,7 @@ checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -233,9 +233,9 @@ dependencies = [ [[package]] name = "backtrace" -version = "0.3.68" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4319208da049c43661739c5fade2ba182f09d1dc2299b32298d3a31692b17e12" +checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837" dependencies = [ "addr2line", "cc", @@ -254,9 +254,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "base64" -version = "0.21.2" +version = "0.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" +checksum = "414dcefbc63d77c526a76b3afcf6fbb9b5e2791c19c3aa2297733208750c6e53" [[package]] name = "bencode" @@ -480,15 +480,15 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.26" +version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec837a71355b28f6556dbd569b37b3f363091c0bd4b2e735674521b4c5fd9bc5" +checksum = "d87d9d13be47a5b7c3907137f1290b0459a7f80efb26be8c52afb11963bccb02" dependencies = [ "android-tzdata", "iana-time-zone", "num-traits", "serde", - "winapi", + "windows-targets", ] [[package]] @@ -531,18 +531,18 @@ dependencies = [ [[package]] name = "clap" -version = "4.3.23" +version = "4.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03aef18ddf7d879c15ce20f04826ef8418101c7e528014c3eeea13321047dca3" +checksum = "6a13b88d2c62ff462f88e4a121f17a82c1af05693a2f192b5c38d14de73c19f6" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" -version = "4.3.23" +version = "4.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ce6fffb678c9b80a70b6b6de0aad31df727623a70fd9a842c30cd573e2fa98" +checksum = "2bb9faaa7c2ef94b2743a21f5a29e6f0010dff4caa69ac8e9d6cf8b6fa74da08" dependencies = [ "anstyle", "clap_lex", @@ -550,9 +550,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b" +checksum = "cd7cc57abe963c6d3b9d8be5b06ba7c8957a930305ca90304f24ef040aa6f961" [[package]] name = "cmake" @@ -756,7 +756,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -767,7 +767,7 @@ checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ "darling_core", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -800,7 +800,7 @@ checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -839,9 +839,9 @@ checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" [[package]] name = "encoding_rs" -version = "0.8.32" +version = "0.8.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071a31f4ee85403370b58aca746f01041ede6f0da2730960ad001edc2b71b394" +checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1" dependencies = [ "cfg-if", ] @@ -854,9 +854,9 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b30f669a7961ef1631673d2766cc92f52d64f7ef354d4fe0ddfd30ed52f0f4f" +checksum = "136526188508e25c6fef639d7927dfb3e0e3084488bf202267829cf7fc23dbdd" dependencies = [ "errno-dragonfly", "libc", @@ -1001,7 +1001,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -1013,7 +1013,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -1025,7 +1025,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -1090,7 +1090,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -1146,9 +1146,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.27.3" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e" +checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0" [[package]] name = "glob" @@ -1158,9 +1158,9 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "h2" -version = "0.3.20" +version = "0.3.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97ec8491ebaf99c8eaa73058b045fe58073cd6be7f596ac993ced0b0a0c01049" +checksum = "91fc23aa11be92976ef4729127f1a74adf36d8436f7816b185d18df956790833" dependencies = [ "bytes", "fnv", @@ -1211,9 +1211,9 @@ dependencies = [ [[package]] name = "hashlink" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "312f66718a2d7789ffef4f4b7b213138ed9f1eb3aa1d0d82fc99f88fb3ffd26f" +checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7" dependencies = [ "hashbrown 0.14.0", ] @@ -1375,7 +1375,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -1619,9 +1619,9 @@ checksum = "ed1202b2a6f884ae56f04cff409ab315c5ce26b5e58d7412e484f01fd52f52ef" [[package]] name = "memchr" -version = "2.5.0" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" +checksum = "8f232d6ef707e1956a43342693d2a31e72989554d58299d7a88738cc95b0d35c" [[package]] name = "memoffset" @@ -1839,9 +1839,9 @@ checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" [[package]] name = "num-bigint" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" +checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0" dependencies = [ "autocfg", "num-integer", @@ -1879,9 +1879,9 @@ dependencies = [ [[package]] name = "object" -version = "0.31.1" +version = "0.32.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bda667d9f2b5051b8833f59f3bf748b28ef54f850f4fcb389a252aa383866d1" +checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0" dependencies = [ "memchr", ] @@ -1900,11 +1900,11 @@ checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" [[package]] name = "openssl" -version = "0.10.56" +version = "0.10.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "729b745ad4a5575dd06a3e1af1414bd330ee561c01b3899eb584baeaa8def17e" +checksum = "bac25ee399abb46215765b1cb35bc0212377e58a061560d8b29b024fd0430e7c" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.4.0", "cfg-if", "foreign-types", "libc", @@ -1921,7 +1921,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -1932,18 +1932,18 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "111.27.0+1.1.1v" +version = "300.1.3+3.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06e8f197c82d7511c5b014030c9b1efeda40d7d5f99d23b4ceed3524a5e63f02" +checksum = "cd2c101a165fff9935e34def4669595ab1c7847943c42be86e21503e482be107" dependencies = [ "cc", ] [[package]] name = "openssl-sys" -version = "0.9.91" +version = "0.9.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "866b5f16f90776b9bb8dc1e1802ac6f0513de3a7a7465867bfbc563dc737faac" +checksum = "db4d56a4c0478783083cfafcc42493dd4a981d41669da64b4572a2a089b51b1d" dependencies = [ "cc", "libc", @@ -2014,19 +2014,20 @@ checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" [[package]] name = "pest" -version = "2.7.2" +version = "2.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1acb4a4365a13f749a93f1a094a7805e5cfa0955373a9de860d962eaa3a5fe5a" +checksum = "d7a4d085fd991ac8d5b05a147b437791b4260b76326baf0fc60cf7c9c27ecd33" dependencies = [ + "memchr", "thiserror", "ucd-trie", ] [[package]] name = "pest_derive" -version = "2.7.2" +version = "2.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "666d00490d4ac815001da55838c500eafb0320019bbaa44444137c48b443a853" +checksum = "a2bee7be22ce7918f641a33f08e3f43388c7656772244e2bbb2477f44cc9021a" dependencies = [ "pest", "pest_generator", @@ -2034,22 +2035,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.2" +version = "2.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ca01446f50dbda87c1786af8770d535423fa8a53aec03b8f4e3d7eb10e0929" +checksum = "d1511785c5e98d79a05e8a6bc34b4ac2168a0e3e92161862030ad84daa223141" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] name = "pest_meta" -version = "2.7.2" +version = "2.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56af0a30af74d0445c0bf6d9d051c979b516a1a5af790d251daee76005420a48" +checksum = "b42f0394d3123e33353ca5e1e89092e533d2cc490389f2bd6131c43c634ebc5f" dependencies = [ "once_cell", "pest", @@ -2073,14 +2074,14 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] name = "pin-project-lite" -version = "0.2.12" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12cc1b0bf1727a77a54b6654e7b5f1af8604923edc8b81885f8ec92f9e3f0a05" +checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" [[package]] name = "pin-utils" @@ -2306,9 +2307,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.9.3" +version = "1.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81bc1d4caf89fac26a70747fe603c130093b53c773888797a6329091246d651a" +checksum = "697061221ea1b4a94a624f67d0ae2bfe4e22b8a17b6a192afb11046542cc8c47" dependencies = [ "aho-corasick", "memchr", @@ -2318,9 +2319,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.3.6" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fed1ceff11a1dddaee50c9dc8e4938bd106e9d89ae372f192311e7da498e3b69" +checksum = "c2f401f4955220693b56f8ec66ee9c78abffd8d1c4f23dc41a23839eb88f0795" dependencies = [ "aho-corasick", "memchr", @@ -2329,9 +2330,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5ea92a5b6195c6ef2a0295ea818b312502c6fc94dde986c5553242e18fd4ce2" +checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" [[package]] name = "rend" @@ -2344,11 +2345,11 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.11.18" +version = "0.11.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cde824a14b7c14f85caff81225f411faacc04a2013f41670f41443742b1c1c55" +checksum = "3e9ad3fe7488d7e34558a2033d45a0c90b72d97b4f80705666fea71472e2e6a1" dependencies = [ - "base64 0.21.2", + "base64 0.21.3", "bytes", "encoding_rs", "futures-core", @@ -2459,13 +2460,12 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.31.0" +version = "1.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a2ab0025103a60ecaaf3abf24db1db240a4e1c15837090d2c32f625ac98abea" +checksum = "a4c4216490d5a413bc6d10fa4742bd7d4955941d062c0ef873141d6b0e7b30fd" dependencies = [ "arrayvec", "borsh", - "byteorder", "bytes", "num-traits", "rand", @@ -2497,9 +2497,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.8" +version = "0.38.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19ed4fa021d81c8392ce04db050a3da9a60299050b7ae1cf482d862b54a7218f" +checksum = "c0c3dde1fc030af041adc40e79c0e7fbcf431dd24870053d187d7c66e4b87453" dependencies = [ "bitflags 2.4.0", "errno", @@ -2510,9 +2510,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.21.6" +version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d1feddffcfcc0b33f5c6ce9a29e341e4cd59c3f78e7ee45f4a40c038b1d6cbb" +checksum = "cd8d6c9f025a446bc4d18ad9632e69aec8f287aa84499ee335599fabd20c3fd8" dependencies = [ "log", "ring", @@ -2526,14 +2526,14 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d3987094b1d07b653b7dfdc3f70ce9a1da9c51ac18c1b06b662e4f9a0e9f4b2" dependencies = [ - "base64 0.21.2", + "base64 0.21.3", ] [[package]] name = "rustls-webpki" -version = "0.101.3" +version = "0.101.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "261e9e0888cba427c3316e6322805653c9425240b6fd96cee7cb671ab70ab8d0" +checksum = "7d93931baf2d282fff8d3a532bbfd7653f734643161b87e3e01e59a04439bf0d" dependencies = [ "ring", "untrusted", @@ -2637,9 +2637,9 @@ checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" [[package]] name = "serde" -version = "1.0.171" +version = "1.0.188" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30e27d1e4fd7659406c492fd6cfaf2066ba8773de45ca75e855590f856dc34a9" +checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" dependencies = [ "serde_derive", ] @@ -2665,13 +2665,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.171" +version = "1.0.188" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389894603bd18c46fa56231694f8d827779c0951a667087194cf9de94ed24682" +checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -2703,7 +2703,7 @@ checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -2733,7 +2733,7 @@ version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ca3b16a3d82c4088f343b7480a93550b3eabe1a358569c2dfe38bbcead07237" dependencies = [ - "base64 0.21.2", + "base64 0.21.3", "chrono", "hex", "indexmap 1.9.3", @@ -2753,7 +2753,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -2780,9 +2780,9 @@ dependencies = [ [[package]] name = "shlex" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43b2853a4d09f215c24cc5489c992ce46052d359b5109343cbafbf26bc62f8a3" +checksum = "a7cee0529a6d40f580e7a5e6c495c8fbfe21b7b52795ed4bb5e62cdf92bc6380" [[package]] name = "signal-hook-registry" @@ -2801,9 +2801,9 @@ checksum = "f27f6278552951f1f2b8cf9da965d10969b2efdea95a6ec47987ab46edfe263a" [[package]] name = "slab" -version = "0.4.8" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6528351c9bc8ab22353f9d776db39a20288e8d6c37ef8cfe3317cf875eecfc2d" +checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" dependencies = [ "autocfg", ] @@ -2875,9 +2875,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.29" +version = "2.0.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c324c494eba9d92503e6f1ef2e6df781e78f6a7705a0202d9801b198807d518a" +checksum = "718fa2415bcb8d8bd775917a1bf12a7931b6dfa890753378538118181e0cb398" dependencies = [ "proc-macro2", "quote", @@ -2917,29 +2917,29 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.47" +version = "1.0.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97a802ec30afc17eee47b2855fc72e0c4cd62be9b4efe6591edde0ec5bd68d8f" +checksum = "9d6d7a740b8a666a7e828dd00da9c0dc290dff53154ea77ac109281de90589b7" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.47" +version = "1.0.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bb623b56e39ab7dcd4b1b98bb6c8f8d907ed255b18de254088016b27a8ee19b" +checksum = "49922ecae66cc8a249b77e68d1d0623c1b2c514f0060c27cdc68bd62a1219d35" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] name = "time" -version = "0.3.26" +version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a79d09ac6b08c1ab3906a2f7cc2e81a0e27c7ae89c63812df75e52bef0751e07" +checksum = "17f6bb557fd245c28e6411aa56b6403c689ad95061f50e4be16c274e70a17e48" dependencies = [ "deranged", "itoa", @@ -2956,9 +2956,9 @@ checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb" [[package]] name = "time-macros" -version = "0.2.12" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75c65469ed6b3a4809d987a41eb1dc918e9bc1d92211cbad7ae82931846f7451" +checksum = "1a942f44339478ef67935ab2bbaec2fb0322496cf3cbe84b261e06ac3814c572" dependencies = [ "time-core", ] @@ -3014,7 +3014,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", ] [[package]] @@ -3199,9 +3199,9 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55ae70283aba8d2a8b411c695c437fe25b8b5e44e23e780662002fc72fb47a82" +checksum = "61c5bb1d698276a2443e5ecfabc1008bf15a36c12e6a7176e7bf089ea9131140" dependencies = [ "async-compression", "bitflags 2.4.0", @@ -3309,9 +3309,9 @@ checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" [[package]] name = "url" -version = "2.4.0" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb" +checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5" dependencies = [ "form_urlencoded", "idna", @@ -3342,9 +3342,9 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "walkdir" -version = "2.3.3" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36df944cda56c7d8d8b7496af378e6b16de9284591917d307c9b4d313c44e698" +checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee" dependencies = [ "same-file", "winapi-util", @@ -3386,7 +3386,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", "wasm-bindgen-shared", ] @@ -3420,7 +3420,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.29", + "syn 2.0.31", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -3549,20 +3549,21 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "winnow" -version = "0.5.14" +version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d09770118a7eb1ccaf4a594a221334119a44a814fcb0d31c5b85e83e97227a97" +checksum = "7c2e3184b9c4e92ad5167ca73039d0c42476302ab603e2fec4487511f38ccefc" dependencies = [ "memchr", ] [[package]] name = "winreg" -version = "0.10.1" +version = "0.50.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" dependencies = [ - "winapi", + "cfg-if", + "windows-sys", ] [[package]] diff --git a/cSpell.json b/cSpell.json index 8a85739e2..6a68e045d 100644 --- a/cSpell.json +++ b/cSpell.json @@ -26,6 +26,7 @@ "codegen", "completei", "connectionless", + "datetime", "dockerhub", "downloadedi", "dtolnay", diff --git a/src/shared/clock/mod.rs b/src/shared/clock/mod.rs index 7a5290f49..922ca3200 100644 --- a/src/shared/clock/mod.rs +++ b/src/shared/clock/mod.rs @@ -120,7 +120,7 @@ pub fn convert_from_datetime_utc_to_timestamp(datetime_utc: &DateTime) -> D /// (this will naturally happen in 292.5 billion years) #[must_use] pub fn convert_from_timestamp_to_datetime_utc(duration: DurationSinceUnixEpoch) -> DateTime { - DateTime::::from_utc( + DateTime::::from_naive_utc_and_offset( NaiveDateTime::from_timestamp_opt( i64::try_from(duration.as_secs()).expect("Overflow of i64 seconds, very future!"), duration.subsec_nanos(), @@ -162,13 +162,13 @@ mod tests { let timestamp = DurationSinceUnixEpoch::ZERO; assert_eq!( convert_from_timestamp_to_datetime_utc(timestamp), - DateTime::::from_utc(NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), Utc) + DateTime::::from_naive_utc_and_offset(NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), Utc) ); } #[test] fn should_be_converted_from_datetime_utc() { - let datetime = DateTime::::from_utc(NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), Utc); + let datetime = DateTime::::from_naive_utc_and_offset(NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), Utc); assert_eq!( convert_from_datetime_utc_to_timestamp(&datetime), DurationSinceUnixEpoch::ZERO From 5da5a25e7416408022aec56379c0e62be132d9c1 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 31 Aug 2023 12:04:10 +0200 Subject: [PATCH 0058/1297] dev: container overhaul --- .dockerignore | 32 +- .env.local | 1 - .github/workflows/container.yaml | 125 +++++ .github/workflows/publish_docker_image.yml | 86 ---- .github/workflows/test_docker.yml | 26 -- .gitignore | 3 +- .vscode/settings.json | 42 +- Cargo.lock | 10 +- Cargo.toml | 24 +- Containerfile | 140 ++++++ Dockerfile | 80 ---- README.md | 135 ++++-- bin/install-demo.sh | 27 -- bin/install.sh | 18 - cSpell.json | 27 +- compose.yaml | 26 +- contrib/bencode/src/reference/decode.rs | 2 + contrib/dev-tools/containers/docker-build.sh | 5 + .../dev-tools/containers/docker-install.sh | 3 + .../dev-tools/containers/docker-run-local.sh | 13 + .../dev-tools/containers/docker-run-public.sh | 13 + contrib/dev-tools/init/install-local.sh | 12 + contrib/dev-tools/su-exec/LICENSE | 22 + contrib/dev-tools/su-exec/Makefile | 17 + contrib/dev-tools/su-exec/README.md | 46 ++ contrib/dev-tools/su-exec/su-exec.c | 109 +++++ docker/README.md | 289 ------------ docker/bin/build.sh | 13 - docker/bin/install.sh | 4 - docker/bin/run-local-image.sh | 13 - docker/bin/run-public-image.sh | 13 - docs/containers.md | 428 ++++++++++++++++++ packages/configuration/Cargo.toml | 4 +- packages/configuration/src/lib.rs | 130 ++++-- packages/test-helpers/Cargo.toml | 4 +- rustfmt.toml | 1 - share/container/entry_script_sh | 81 ++++ share/container/message | 2 + .../config/tracker.container.mysql.toml | 39 ++ .../config/tracker.container.sqlite3.toml | 39 ++ .../config/tracker.development.sqlite3.toml | 2 +- src/bootstrap/config.rs | 62 +-- src/lib.rs | 24 +- src/servers/apis/mod.rs | 10 +- src/servers/apis/v1/middlewares/auth.rs | 2 +- src/tracker/databases/driver.rs | 2 +- src/tracker/mod.rs | 2 +- tests/servers/http/v1/contract.rs | 27 +- 48 files changed, 1479 insertions(+), 756 deletions(-) delete mode 100644 .env.local create mode 100644 .github/workflows/container.yaml delete mode 100644 .github/workflows/publish_docker_image.yml delete mode 100644 .github/workflows/test_docker.yml create mode 100644 Containerfile delete mode 100644 Dockerfile delete mode 100755 bin/install-demo.sh delete mode 100755 bin/install.sh create mode 100755 contrib/dev-tools/containers/docker-build.sh create mode 100755 contrib/dev-tools/containers/docker-install.sh create mode 100755 contrib/dev-tools/containers/docker-run-local.sh create mode 100755 contrib/dev-tools/containers/docker-run-public.sh create mode 100755 contrib/dev-tools/init/install-local.sh create mode 100644 contrib/dev-tools/su-exec/LICENSE create mode 100644 contrib/dev-tools/su-exec/Makefile create mode 100644 contrib/dev-tools/su-exec/README.md create mode 100644 contrib/dev-tools/su-exec/su-exec.c delete mode 100644 docker/README.md delete mode 100755 docker/bin/build.sh delete mode 100755 docker/bin/install.sh delete mode 100755 docker/bin/run-local-image.sh delete mode 100755 docker/bin/run-public-image.sh create mode 100644 docs/containers.md create mode 100644 share/container/entry_script_sh create mode 100644 share/container/message create mode 100644 share/default/config/tracker.container.mysql.toml create mode 100644 share/default/config/tracker.container.sqlite3.toml rename config.toml.local => share/default/config/tracker.development.sqlite3.toml (92%) diff --git a/.dockerignore b/.dockerignore index 3d8a25cce..f42859922 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,16 +1,16 @@ -.git -.git-blame-ignore -.github -.gitignore -.vscode -bin/ -config.toml -config.toml.local -cSpell.json -data.db -docker/ -NOTICE -README.md -rustfmt.toml -storage/ -target/ +/.git +/.git-blame-ignore +/.github +/.gitignore +/.vscode +/bin/ +/tracker.* +/cSpell.json +/data.db +/docker/bin/ +/NOTICE +/README.md +/rustfmt.toml +/storage/ +/target/ +/etc/ diff --git a/.env.local b/.env.local deleted file mode 100644 index fefed56c4..000000000 --- a/.env.local +++ /dev/null @@ -1 +0,0 @@ -TORRUST_TRACKER_USER_UID=1000 \ No newline at end of file diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml new file mode 100644 index 000000000..27a2dc93c --- /dev/null +++ b/.github/workflows/container.yaml @@ -0,0 +1,125 @@ +name: Container + +on: + push: + tags-ignore: + - "!v*" + pull_request: + branches: + - "develop" + - "main" + +env: + CARGO_TERM_COLOR: always + +jobs: + test: + name: Test (Docker) + runs-on: ubuntu-latest + + steps: + - id: setup + name: Setup Toolchain + uses: docker/setup-buildx-action@v2 + + - id: build + name: Build + uses: docker/build-push-action@v4 + with: + file: ./Containerfile + push: false + load: true + tags: torrust-tracker:local + cache-from: type=gha + cache-to: type=gha,mode=max + + - id: inspect + name: Inspect + run: docker image inspect torrust-tracker:local + + - id: checkout + name: Checkout Repository + uses: actions/checkout@v3 + + - id: compose + name: Compose + run: docker compose build + + context: + name: Context + needs: test + runs-on: ubuntu-latest + + outputs: + continue: ${{ steps.check.outputs.continue }} + + steps: + - id: check + name: Check Context + run: | + if [[ "${{ github.event_name }}" == "push" && ( "${{ github.ref }}" == "refs/heads/main" || "${{ github.ref }}" == "refs/heads/develop" || "${{ github.ref }}" == "refs/heads/docker" ) ]] || + [[ "${{ github.event_name }}" == "push" && "${{ github.ref }}" =~ ^refs/tags/v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + if [[ "${{ github.repository }}" == "torrust/torrust-tracker" ]]; then + echo "Context is torrust/torrust-tracker, and push is: main, develop, docker, or a tag of v*.*.*" + echo "continue=true" >> $GITHUB_OUTPUT + fi + fi + + secrets: + name: Secrets + needs: context + environment: dockerhub-torrust + if: needs.context.outputs.continue == 'true' + runs-on: ubuntu-latest + + outputs: + continue: ${{ steps.check.outputs.continue }} + + steps: + - id: check + name: Check + env: + DOCKER_HUB_ACCESS_TOKEN: "${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}" + if: "${{ env.DOCKER_HUB_ACCESS_TOKEN != '' }}" + run: echo "continue=true" >> $GITHUB_OUTPUT + + publish: + name: Publish + environment: dockerhub-torrust + needs: secrets + if: needs.secrets.outputs.continue == 'true' + runs-on: ubuntu-latest + + steps: + - id: meta + name: Docker meta + uses: docker/metadata-action@v4 + with: + images: | + "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" + tags: | + type=ref,event=branch + type=ref,event=pr + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + + - id: login + name: Login to Docker Hub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKER_HUB_USERNAME }} + password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} + + - id: setup + name: Setup Toolchain + uses: docker/setup-buildx-action@v2 + + - name: Build and push + uses: docker/build-push-action@v4 + with: + file: ./Containerfile + push: ${{ github.event_name != 'pull_request' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/.github/workflows/publish_docker_image.yml b/.github/workflows/publish_docker_image.yml deleted file mode 100644 index 1dd65e3a7..000000000 --- a/.github/workflows/publish_docker_image.yml +++ /dev/null @@ -1,86 +0,0 @@ -name: Publish docker image - -on: - push: - branches: - - "main" - - "develop" - tags: - - "v*" - -env: - # Azure file share volume mount requires the Linux container run as root - # https://learn.microsoft.com/en-us/azure/container-instances/container-instances-volume-azure-files#limitations - # TORRUST_TRACKER_RUN_AS_USER: root - TORRUST_TRACKER_RUN_AS_USER: appuser - -jobs: - check-secret: - runs-on: ubuntu-latest - environment: dockerhub-torrust - outputs: - publish: ${{ steps.check.outputs.publish }} - steps: - - id: check - env: - DOCKER_HUB_USERNAME: "${{ secrets.DOCKER_HUB_USERNAME }}" - if: "${{ env.DOCKER_HUB_USERNAME != '' }}" - run: echo "publish=true" >> $GITHUB_OUTPUT - - test: - needs: check-secret - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - components: llvm-tools-preview - - uses: Swatinem/rust-cache@v2 - - name: Run Tests - run: cargo test - - dockerhub: - needs: test - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - environment: dockerhub-torrust - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Docker meta - id: meta - uses: docker/metadata-action@v4 - with: - images: | - # For example: torrust/tracker - "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" - tags: | - type=ref,event=branch - type=ref,event=pr - type=semver,pattern={{version}} - type=semver,pattern={{major}}.{{minor}} - - - name: Login to Docker Hub - uses: docker/login-action@v2 - with: - username: ${{ secrets.DOCKER_HUB_USERNAME }} - password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - - name: Build and push - uses: docker/build-push-action@v4 - with: - context: . - file: ./Dockerfile - build-args: | - RUN_AS_USER=${{ env.TORRUST_TRACKER_RUN_AS_USER }} - push: ${{ github.event_name != 'pull_request' }} - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max diff --git a/.github/workflows/test_docker.yml b/.github/workflows/test_docker.yml deleted file mode 100644 index a62965878..000000000 --- a/.github/workflows/test_docker.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Test docker build - -on: - push: - pull_request: - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - - name: Build docker image - uses: docker/build-push-action@v4 - with: - context: . - file: ./Dockerfile - push: false - cache-from: type=gha - cache-to: type=gha,mode=max - - - name: Build docker-compose images - run: docker compose build diff --git a/.gitignore b/.gitignore index 6b58dcb45..2d8d0b8bd 100644 --- a/.gitignore +++ b/.gitignore @@ -3,9 +3,10 @@ /.coverage/ /.idea/ /.vscode/launch.json -/config.toml +/tracker.toml /data.db /database.db /database.json.bz2 /storage/ /target +/tracker.* diff --git a/.vscode/settings.json b/.vscode/settings.json index 78239b757..3bf0969e9 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,23 +1,23 @@ { - "[rust]": { - "editor.formatOnSave": true - }, - "rust-analyzer.checkOnSave": true, - "rust-analyzer.check.command": "clippy", - "rust-analyzer.check.allTargets": true, - "rust-analyzer.check.extraArgs": [ - "--", - "-D", - "clippy::correctness", - "-D", - "clippy::suspicious", - "-W", - "clippy::complexity", - "-W", - "clippy::perf", - "-W", - "clippy::style", - "-W", - "clippy::pedantic", - ], + "[rust]": { + "editor.formatOnSave": true + }, + "rust-analyzer.checkOnSave": true, + "rust-analyzer.check.command": "clippy", + "rust-analyzer.check.allTargets": true, + "rust-analyzer.check.extraArgs": [ + "--", + "-D", + "clippy::correctness", + "-D", + "clippy::suspicious", + "-W", + "clippy::complexity", + "-W", + "clippy::perf", + "-W", + "clippy::style", + "-W", + "clippy::pedantic", + ], } \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index bc88e9bf5..0b7c9d0d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3096,7 +3096,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.3" +version = "3.0.0-alpha.4" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3142,7 +3142,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.3" +version = "3.0.0-alpha.4" dependencies = [ "config", "log", @@ -3157,7 +3157,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.3" +version = "3.0.0-alpha.4" dependencies = [ "log", "thiserror", @@ -3165,7 +3165,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.3" +version = "3.0.0-alpha.4" dependencies = [ "derive_more", "serde", @@ -3173,7 +3173,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.3" +version = "3.0.0-alpha.4" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index a265f32ef..9c94ea10d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,13 +9,21 @@ version.workspace = true [workspace.package] license-file = "COPYRIGHT" -authors = ["Nautilus Cyberneering , Mick van Dijke "] +authors = [ + "Nautilus Cyberneering , Mick van Dijke ", +] edition = "2021" repository = "https://github.com/torrust/torrust-tracker" -version = "3.0.0-alpha.3" +version = "3.0.0-alpha.4" [dependencies] -tokio = { version = "1.29", features = ["rt-multi-thread", "net", "sync", "macros", "signal"] } +tokio = { version = "1.29", features = [ + "rt-multi-thread", + "net", + "sync", + "macros", + "signal", +] } serde = { version = "1.0", features = ["derive"] } serde_bencode = "^0.2" serde_json = "1.0" @@ -41,11 +49,11 @@ uuid = { version = "1", features = ["v4"] } axum = "0.6.20" axum-server = { version = "0.5", features = ["tls-rustls"] } axum-client-ip = "0.4.1" -tower-http = { version= "0.4.3", features = ["compression-full"] } +tower-http = { version = "0.4.3", features = ["compression-full"] } bencode = { version = "1.0.0-alpha.1", path = "contrib/bencode" } -torrust-tracker-primitives = { version = "3.0.0-alpha.3", path = "packages/primitives" } -torrust-tracker-configuration = { version = "3.0.0-alpha.3", path = "packages/configuration" } -torrust-tracker-located-error = { version = "3.0.0-alpha.3", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.4", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.4", path = "packages/configuration" } +torrust-tracker-located-error = { version = "3.0.0-alpha.4", path = "packages/located-error" } multimap = "0.9" hyper = "0.14" @@ -56,7 +64,7 @@ serde_urlencoded = "0.7" serde_repr = "0.1" serde_bytes = "0.11" local-ip-address = "0.5" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.3", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.4", path = "packages/test-helpers" } [workspace] members = [ diff --git a/Containerfile b/Containerfile new file mode 100644 index 000000000..229500cd8 --- /dev/null +++ b/Containerfile @@ -0,0 +1,140 @@ +# syntax=docker/dockerfile:latest + +# Torrust Tracker + +## Builder Image +FROM rust:bookworm as chef +WORKDIR /tmp +RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash +RUN cargo binstall --no-confirm cargo-chef cargo-nextest + +## Tester Image +FROM rust:slim-bookworm as tester +WORKDIR /tmp + +RUN apt-get update; apt-get install -y curl sqlite3; apt-get autoclean +RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash +RUN cargo binstall --no-confirm cargo-nextest + +COPY ./share/ /app/share/torrust +RUN mkdir -p /app/share/torrust/default/database/; \ + sqlite3 /app/share/torrust/default/database/tracker.sqlite3.db "VACUUM;" + +## Su Exe Compile +FROM docker.io/library/gcc:bookworm as gcc +COPY ./contrib/dev-tools/su-exec/ /usr/local/src/su-exec/ +RUN cc -Wall -Werror -g /usr/local/src/su-exec/su-exec.c -o /usr/local/bin/su-exec; chmod +x /usr/local/bin/su-exec + + +## Chef Prepare (look at project and see wat we need) +FROM chef AS recipe +WORKDIR /build/src +COPY . /build/src +RUN cargo chef prepare --recipe-path /build/recipe.json + + +## Cook (debug) +FROM chef AS dependencies_debug +WORKDIR /build/src +COPY --from=recipe /build/recipe.json /build/recipe.json +RUN cargo chef cook --tests --benches --examples --workspace --all-targets --all-features --recipe-path /build/recipe.json +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/temp.tar.zst ; rm -f /build/temp.tar.zst + +## Cook (release) +FROM chef AS dependencies +WORKDIR /build/src +COPY --from=recipe /build/recipe.json /build/recipe.json +RUN cargo chef cook --tests --benches --examples --workspace --all-targets --all-features --recipe-path /build/recipe.json --release +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/temp.tar.zst --release ; rm -f /build/temp.tar.zst + + +## Build Archive (debug) +FROM dependencies_debug AS build_debug +WORKDIR /build/src +COPY . /build/src +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/torrust-tracker-debug.tar.zst + +## Build Archive (release) +FROM dependencies AS build +WORKDIR /build/src +COPY . /build/src +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/torrust-tracker.tar.zst --release + + +# Extract and Test (debug) +FROM tester as test_debug +WORKDIR /test +COPY . /test/src/ +COPY --from=build_debug \ + /build/torrust-tracker-debug.tar.zst \ + /test/torrust-tracker-debug.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --extract-to /test/src/ --no-run --archive-file /test/torrust-tracker-debug.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --target-dir-remap /test/src/target/ --cargo-metadata /test/src/target/nextest/cargo-metadata.json --binaries-metadata /test/src/target/nextest/binaries-metadata.json + +RUN mkdir -p /app/bin/; cp -l /test/src/target/debug/torrust-tracker /app/bin/torrust-tracker +RUN mkdir /app/lib/; cp -l $(realpath $(ldd /app/bin/torrust-tracker | grep "libz\.so\.1" | awk '{print $3}')) /app/lib/libz.so.1 +RUN chown -R root:root /app; chmod -R u=rw,go=r,a+X /app; chmod -R a+x /app/bin + +# Extract and Test (release) +FROM tester as test +WORKDIR /test +COPY . /test/src +COPY --from=build \ + /build/torrust-tracker.tar.zst \ + /test/torrust-tracker.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --extract-to /test/src/ --no-run --archive-file /test/torrust-tracker.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --target-dir-remap /test/src/target/ --cargo-metadata /test/src/target/nextest/cargo-metadata.json --binaries-metadata /test/src/target/nextest/binaries-metadata.json + +RUN mkdir -p /app/bin/; cp -l /test/src/target/release/torrust-tracker /app/bin/torrust-tracker +RUN mkdir -p /app/lib/; cp -l $(realpath $(ldd /app/bin/torrust-tracker | grep "libz\.so\.1" | awk '{print $3}')) /app/lib/libz.so.1 +RUN chown -R root:root /app; chmod -R u=rw,go=r,a+X /app; chmod -R a+x /app/bin + + +## Runtime +FROM gcr.io/distroless/cc-debian12:debug as runtime +RUN ["/busybox/cp", "-sp", "/busybox/sh","/busybox/cat","/busybox/ls","/busybox/env", "/bin/"] +COPY --from=gcc --chmod=0555 /usr/local/bin/su-exec /bin/su-exec + +ARG TORRUST_TRACKER_PATH_CONFIG="/etc/torrust/tracker/tracker.toml" +ARG TORRUST_TRACKER_DATABASE="sqlite3" +ARG USER_ID=1000 +ARG UDP_PORT=6969 +ARG HTTP_PORT=7070 +ARG API_PORT=1212 + +ENV TORRUST_TRACKER_PATH_CONFIG=${TORRUST_TRACKER_PATH_CONFIG} +ENV TORRUST_TRACKER_DATABASE=${TORRUST_TRACKER_DATABASE} +ENV USER_ID=${USER_ID} +ENV UDP_PORT=${UDP_PORT} +ENV HTTP_PORT=${HTTP_PORT} +ENV API_PORT=${API_PORT} +ENV TZ=Etc/UTC + +EXPOSE ${UDP_PORT}/udp +EXPOSE ${HTTP_PORT}/tcp +EXPOSE ${API_PORT}/tcp + +RUN mkdir -p /var/lib/torrust/tracker /var/log/torrust/tracker /etc/torrust/tracker + +ENV ENV=/etc/profile +COPY --chmod=0555 ./share/container/entry_script_sh /usr/local/bin/entry.sh + +VOLUME ["/var/lib/torrust/tracker","/var/log/torrust/tracker","/etc/torrust/tracker"] + +ENV RUNTIME="runtime" +ENTRYPOINT ["/usr/local/bin/entry.sh"] + + +## Torrust-Tracker (debug) +FROM runtime as debug +ENV RUNTIME="debug" +COPY --from=test_debug /app/ /usr/ +RUN env +CMD ["sh"] + +## Torrust-Tracker (release) (default) +FROM runtime as release +ENV RUNTIME="release" +COPY --from=test /app/ /usr/ +# HEALTHCHECK CMD ["/usr/bin/wget", "--no-verbose", "--tries=1", "--spider", "localhost:${API_PORT}/version"] +CMD ["/usr/bin/torrust-tracker"] diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 96d21fa84..000000000 --- a/Dockerfile +++ /dev/null @@ -1,80 +0,0 @@ -FROM clux/muslrust:stable AS chef -WORKDIR /app -RUN cargo install cargo-chef - - -FROM chef AS planner -WORKDIR /app -COPY . . -RUN cargo chef prepare --recipe-path recipe.json - - -FROM chef as development -WORKDIR /app -ARG UID=1000 -ARG RUN_AS_USER=appuser -ARG TRACKER_UDP_PORT=6969 -ARG TRACKER_HTTP_PORT=7070 -ARG TRACKER_API_PORT=1212 -# Add the app user for development -ENV USER=appuser -ENV UID=$UID -RUN adduser --uid "${UID}" "${USER}" -# Build dependencies -COPY --from=planner /app/recipe.json recipe.json -RUN cargo chef cook --recipe-path recipe.json -# Build the application -COPY . . -RUN cargo build --bin torrust-tracker -USER $RUN_AS_USER:$RUN_AS_USER -EXPOSE $TRACKER_UDP_PORT/udp -EXPOSE $TRACKER_HTTP_PORT/tcp -EXPOSE $TRACKER_API_PORT/tcp -CMD ["cargo", "run"] - - -FROM chef AS builder -WORKDIR /app -ARG UID=1000 -# Add the app user for production -ENV USER=appuser -ENV UID=$UID -RUN adduser \ - --disabled-password \ - --gecos "" \ - --home "/nonexistent" \ - --shell "/sbin/nologin" \ - --no-create-home \ - --uid "${UID}" \ - "${USER}" -# Build dependencies -COPY --from=planner /app/recipe.json recipe.json -RUN cargo chef cook --release --target x86_64-unknown-linux-musl --recipe-path recipe.json -# Build the application -COPY . . -RUN cargo build --release --target x86_64-unknown-linux-musl --bin torrust-tracker -# Strip the binary -# More info: https://github.com/LukeMathWalker/cargo-chef/issues/149 -RUN strip /app/target/x86_64-unknown-linux-musl/release/torrust-tracker - - -FROM alpine:latest -WORKDIR /app -ARG RUN_AS_USER=appuser -ARG TRACKER_UDP_PORT=6969 -ARG TRACKER_HTTP_PORT=7070 -ARG TRACKER_API_PORT=1212 -RUN apk --no-cache add ca-certificates -ENV TZ=Etc/UTC -ENV RUN_AS_USER=$RUN_AS_USER -COPY --from=builder /etc/passwd /etc/passwd -COPY --from=builder /etc/group /etc/group -COPY --from=builder --chown=$RUN_AS_USER \ - /app/target/x86_64-unknown-linux-musl/release/torrust-tracker \ - /app/torrust-tracker -RUN chown -R $RUN_AS_USER:$RUN_AS_USER /app -USER $RUN_AS_USER:$RUN_AS_USER -EXPOSE $TRACKER_UDP_PORT/udp -EXPOSE $TRACKER_HTTP_PORT/tcp -EXPOSE $TRACKER_API_PORT/tcp -ENTRYPOINT ["/app/torrust-tracker"] \ No newline at end of file diff --git a/README.md b/README.md index b419c12c1..832af0d85 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,35 @@ # Torrust Tracker -[![Build & Release](https://github.com/torrust/torrust-tracker/actions/workflows/build_release.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/build_release.yml) [![CI](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml) [![Publish crate](https://github.com/torrust/torrust-tracker/actions/workflows/publish_crate.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/publish_crate.yml) [![Publish docker image](https://github.com/torrust/torrust-tracker/actions/workflows/publish_docker_image.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/publish_docker_image.yml) [![Test](https://github.com/torrust/torrust-tracker/actions/workflows/test.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test.yml) [![Test docker build](https://github.com/torrust/torrust-tracker/actions/workflows/test_docker.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test_docker.yml) [![Coverage](https://github.com/torrust/torrust-tracker/actions/workflows/coverage.yaml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/coverage.yaml) +[![container_wf_b]][container_wf] [![coverage_wf_b]][coverage_wf] [![testing_wf_b]][testing_wf] -Torrust Tracker is a lightweight but incredibly high-performance and feature-rich BitTorrent tracker written in [Rust](https://www.rust-lang.org/). +Torrust Tracker is a lightweight but incredibly high-performance and feature-rich BitTorrent tracker written in [Rust Language][rust]. It aims to provide a reliable and efficient solution for serving torrents to a vast number of peers while maintaining a high level of performance, robustness, extensibility, security, usability and with community-driven development. +_We have a [container guide][containers.md] to get started with Docker or Podman_ + ## Key Features -* [X] Multiple UDP server and HTTP(S) server blocks for socket binding are possible. -* [X] Full IPv4 and IPv6 support for both UDP and HTTP(S). -* [X] Private & Whitelisted mode. -* [X] Built-in API. -* [X] Torrent whitelisting. -* [X] Peer authentication using time-bound keys. -* [X] [newTrackon](https://newtrackon.com/) check is supported for both HTTP and UDP, where IPv4 and IPv6 are properly handled. -* [X] SQLite3 and MySQL persistence, loading and saving of the torrent hashes and downloads completed count. -* [X] Comprehensive documentation. -* [X] A complete suite of tests. See [code coverage](https://app.codecov.io/gh/torrust/torrust-tracker) report. +* [x] Multiple UDP server and HTTP(S) server blocks for socket binding are possible. +* [x] Full IPv4 and IPv6 support for both UDP and HTTP(S). +* [x] Private & Whitelisted mode. +* [x] Built-in API. +* [x] Torrent whitelisting. +* [x] Peer authentication using time-bound keys. +* [x] [newTrackon][newtrackon] check is supported for both HTTP and UDP, where IPv4 and IPv6 are properly handled. +* [x] SQLite3 and MySQL persistence, loading and saving of the torrent hashes and downloads completed count. +* [x] Comprehensive documentation. +* [x] A complete suite of tests. See our [code coverage report][coverage]. ## Implemented BEPs -* [BEP 3](https://www.bittorrent.org/beps/bep_0003.html): The BitTorrent Protocol. -* [BEP 7](https://www.bittorrent.org/beps/bep_0007.html): IPv6 Support. -* [BEP 15](http://www.bittorrent.org/beps/bep_0015.html): UDP Tracker Protocol for BitTorrent. -* [BEP 23](http://bittorrent.org/beps/bep_0023.html): Tracker Returns Compact Peer Lists. -* [BEP 27](http://bittorrent.org/beps/bep_0027.html): Private Torrents. -* [BEP 48](http://bittorrent.org/beps/bep_0048.html): Tracker Protocol Extension: Scrape. +* [BEP 03]: The BitTorrent Protocol. +* [BEP 07]: IPv6 Support. +* [BEP 15]: UDP Tracker Protocol for BitTorrent. +* [BEP 23]: Tracker Returns Compact Peer Lists. +* [BEP 27]: Private Torrents. +* [BEP 48]: Tracker Protocol Extension: Scrape. + ## Getting Started @@ -35,19 +38,36 @@ Requirements: * Rust Stable `1.68` * You might have problems compiling with a machine or docker container with low resources. It has been tested with docker containers with 6 CPUs, 7.5 GM of memory and 2GB of swap. -You can follow the [documentation](https://docs.rs/torrust-tracker/) to install and use Torrust Tracker in different ways, but if you want to give it a quick try, you can use the following commands: +You can follow the [documentation] to install and use Torrust Tracker in different ways, but if you want to give it a quick try, you can use the following commands: ```s git clone https://github.com/torrust/torrust-tracker.git \ && cd torrust-tracker \ && cargo build --release \ - && mkdir -p ./storage/database \ - && mkdir -p ./storage/ssl_certificates + && mkdir -p ./storage/tracker/lib/database \ + && mkdir -p ./storage/tracker/lib/tls ``` -And then run `cargo run` twice. The first time to generate the `config.toml` file and the second time to run the tracker with the default configuration. +### Configuration + +The [default configuration folder: `/share/default/config`][share.default.config]: + +- Contains the [development default][src.bootstrap.config.default] i.e: [`tracker.development.sqlite3.toml`][tracker.development.sqlite3.toml]. + +- Also contains the container defaults: [`sqlite3`][tracker.container.sqlite3.toml] and [`mysql`][tracker.container.mysql.toml]. + +To override the default configuration there is two options: -After running the tracker these services will be available: +- Configure a different configuration path by setting the [`TORRUST_TRACKER_PATH_CONFIG`][src.bootstrap.config.path.config] environmental variable. + +- Supply the entire configuration via the [`TORRUST_TRACKER_CONFIG`][src.bootstrap.config.config] environmental variable. + + +> NOTE: It is recommended for production you override the `api admin token` by placing your secret in the [`ENV_VAR_API_ADMIN_TOKEN`][src.bootstrap.config.admin.token] environmental variable. + + +### Services +After running the tracker these services will be available (as defined in the default configuration): * UDP tracker: `udp://127.0.0.1:6969/announce`. * HTTP tracker: `http://127.0.0.1:6969/announce`. @@ -55,10 +75,10 @@ After running the tracker these services will be available: ## Documentation -* [Crate documentation](https://docs.rs/torrust-tracker/). -* [API `v1`](https://docs.rs/torrust-tracker/3.0.0-alpha.3/torrust_tracker/servers/apis/v1). -* [HTTP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.3/torrust_tracker/servers/http). -* [UDP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.3/torrust_tracker/servers/udp). +* [Crate documentation] +* [API `v1`] +* [HTTP Tracker] +* [UDP Tracker] ## Contributing @@ -67,14 +87,65 @@ We welcome contributions from the community! How can you contribute? * Bug reports and feature requests. -* Code contributions. You can start by looking at the issues labeled ["good first issues"](https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). -* Documentation improvements. Check the [documentation](https://docs.rs/torrust-tracker/) and [API documentation](https://docs.rs/torrust-tracker/3.0.0-alpha.3/torrust_tracker/servers/apis/v1) for typos, errors, or missing information. -* Participation in the community. You can help by answering questions in the [discussions](https://github.com/torrust/torrust-tracker/discussions). +* Code contributions. You can start by looking at the issues labeled "[good first issues]". +* Documentation improvements. Check the [documentation] and [API documentation] for typos, errors, or missing information. +* Participation in the community. You can help by answering questions in the [discussions]. ## License -The project is licensed under a dual license. See [COPYRIGHT](./COPYRIGHT). +The project is licensed under a dual license. See [COPYRIGHT]. ## Acknowledgments -This project was a joint effort by [Nautilus Cyberneering GmbH](https://nautilus-cyberneering.de/) and [Dutch Bits](https://dutchbits.nl). Also thanks to [Naim A.](https://github.com/naim94a/udpt) and [greatest-ape](https://github.com/greatest-ape/aquatic) for some parts of the code. Further added features and functions thanks to [Power2All](https://github.com/power2all). +This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [Dutch Bits]. Also thanks to [Naim A.] and [greatest-ape] for some parts of the code. Further added features and functions thanks to [Power2All]. + + + +[container_wf]: https://github.com/torrust/torrust-tracker/actions/workflows/container.yaml +[container_wf_b]: https://github.com/torrust/torrust-tracker/actions/workflows/container.yaml/badge.svg +[coverage_wf]: https://github.com/torrust/torrust-tracker/actions/workflows/coverage.yaml +[coverage_wf_b]: https://github.com/torrust/torrust-tracker/actions/workflows/coverage.yaml/badge.svg +[testing_wf]: https://github.com/torrust/torrust-tracker/actions/workflows/testing.yaml +[testing_wf_b]: https://github.com/torrust/torrust-tracker/actions/workflows/testing.yaml/badge.svg + +[rust]: https://www.rust-lang.org/ +[newtrackon]: https://newtrackon.com/ +[coverage]: https://app.codecov.io/gh/torrust/torrust-tracker + +[BEP 03]: https://www.bittorrent.org/beps/bep_0003.html +[BEP 07]: https://www.bittorrent.org/beps/bep_0007.html +[BEP 15]: http://www.bittorrent.org/beps/bep_0015.html +[BEP 23]: http://bittorrent.org/beps/bep_0023.html +[BEP 27]: http://bittorrent.org/beps/bep_0027.html +[BEP 48]: http://bittorrent.org/beps/bep_0048.html + +[containers.md]: ./docs/containers.md + +[share.default.config]: ./share/default/config/ +[tracker.development.sqlite3.toml]: ./share/default/config/tracker.development.sqlite3.toml +[src.bootstrap.config.default]: ./src/bootstrap/config.rs#L18 +[tracker.container.sqlite3.toml]: ./share/default/config/tracker.container.sqlite3.toml +[tracker.container.mysql.toml]: ./share/default/config/tracker.container.mysql.toml +[share.container.entry_script_sh.default]: ./share/container/entry_script_sh#L10 + +[src.bootstrap.config.path.config]: ./src/bootstrap/config.rs#L15 +[src.bootstrap.config.config]: ./src/bootstrap/config.rs#L11 +[src.bootstrap.config.admin.token]: ./src/bootstrap/config.rs#L12 + +[Crate documentation]: https://docs.rs/torrust-tracker/ +[API `v1`]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/apis/v1 +[HTTP Tracker]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/http +[UDP Tracker]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/udp + +[good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 +[documentation]: https://docs.rs/torrust-tracker/ +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/apis/v1 +[discussions]: https://github.com/torrust/torrust-tracker/discussions + +[COPYRIGHT]: ./COPYRIGHT + +[nautilus]: https://nautilus-cyberneering.de/ +[Dutch Bits]: https://dutchbits.nl +[Naim A.]: https://github.com/naim94a/udpt +[greatest-ape]: https://github.com/greatest-ape/aquatic +[Power2All]: https://github.com/power2all diff --git a/bin/install-demo.sh b/bin/install-demo.sh deleted file mode 100755 index 1b829ca1d..000000000 --- a/bin/install-demo.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash - -# Single command to setup and run the tracker using the pre-built image. - -# Check if 'storage' directory exists -if [ -d "./storage" ]; then - echo "Warning: 'storage' directory already exists. Please remove or rename it before proceeding." - exit 1 -fi - -# Check if 'config.toml' file exists in the current directory -if [ -f "./config.toml" ]; then - echo "Warning: 'config.toml' file already exists in the root directory. Please remove or rename it before proceeding." - exit 1 -fi - -# Check if SQLite3 is installed -if ! command -v sqlite3 &> /dev/null; then - echo "Warning: SQLite3 is not installed on your system. Please install it and retry." - exit 1 -fi - -wget https://raw.githubusercontent.com/torrust/torrust-tracker/v3.0.0-alpha.3/config.toml.local -O config.toml \ - && mkdir -p ./storage/database \ - && mkdir -p ./storage/ssl_certificates \ - && touch ./storage/database/data.db \ - && echo ";" | sqlite3 ./storage/database/data.db diff --git a/bin/install.sh b/bin/install.sh deleted file mode 100755 index 82ea940d0..000000000 --- a/bin/install.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash - -# This script is only intended to be used for local development or testing environments. - -# Generate the default settings file if it does not exist -if ! [ -f "./config.toml" ]; then - cp ./config.toml.local ./config.toml -fi - -# Generate storage directory if it does not exist -mkdir -p "./storage/database" - -# Generate the sqlite database if it does not exist -if ! [ -f "./storage/database/data.db" ]; then - # todo: it should get the path from config.toml and only do it when we use sqlite - touch ./storage/database/data.db - echo ";" | sqlite3 ./storage/database/data.db -fi diff --git a/cSpell.json b/cSpell.json index 6a68e045d..fc9db42b7 100644 --- a/cSpell.json +++ b/cSpell.json @@ -1,8 +1,10 @@ { "words": [ + "adduser", "alekitto", "appuser", "Arvid", + "autoclean", "AUTOINCREMENT", "automock", "Avicora", @@ -12,6 +14,7 @@ "bencoded", "beps", "binascii", + "binstall", "Bitflu", "bools", "bufs", @@ -26,12 +29,17 @@ "codegen", "completei", "connectionless", + "Containerfile", + "curr", + "Cyberneering", "datetime", + "distroless", "dockerhub", "downloadedi", "dtolnay", "filesd", "Freebox", + "gecos", "Grcov", "hasher", "hexlify", @@ -45,11 +53,14 @@ "infoschema", "Intermodal", "intervali", + "keyout", "lcov", "leecher", "leechers", "libsqlite", "libtorrent", + "libz", + "LOGNAME", "Lphant", "metainfo", "middlewares", @@ -58,16 +69,21 @@ "myacicontext", "Naim", "nanos", + "newkey", "nextest", "nocapture", + "nologin", + "nonroot", "Norberg", "numwant", "oneshot", "ostr", "Pando", "proot", + "proto", "Quickstart", "Rasterbar", + "realpath", "reannounce", "repr", "reqwest", @@ -80,8 +96,10 @@ "rustfmt", "Rustls", "Seedable", + "serde", "Shareaza", "sharktorrent", + "SHLVL", "socketaddr", "sqllite", "subsec", @@ -89,6 +107,7 @@ "Swiftbit", "taiki", "thiserror", + "tlsv", "Torrentstorm", "torrust", "torrustracker", @@ -100,6 +119,7 @@ "uroot", "Vagaa", "Vuze", + "Werror", "whitespaces", "XBTT", "Xeon", @@ -107,5 +127,10 @@ "Xunlei", "xxxxxxxxxxxxxxxxxxxxd", "yyyyyyyyyyyyyyyyyyyyd" + ], + "enableFiletypes": [ + "dockerfile", + "shellscript", + "toml" ] -} +} \ No newline at end of file diff --git a/compose.yaml b/compose.yaml index 49f3055a8..02f95bccc 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,12 +1,11 @@ name: torrust services: - tracker: - build: - context: . - target: development - user: ${TORRUST_TRACKER_USER_UID:-1000}:${TORRUST_TRACKER_USER_UID:-1000} + image: torrust-tracker:release tty: true + environment: + - TORRUST_TRACKER_DATABASE=${TORRUST_TRACKER_DATABASE:-mysql} + - TORRUST_TRACKER_API_ADMIN_TOKEN=${TORRUST_TRACKER_API_ADMIN_TOKEN:-MyAccessToken} networks: - server_side ports: @@ -14,19 +13,24 @@ services: - 7070:7070 - 1212:1212 volumes: - - ./:/app - - ~/.cargo:/home/appuser/.cargo + - ./storage/tracker/lib:/var/lib/torrust/tracker:Z + - ./storage/tracker/log:/var/log/torrust/tracker:Z + - ./storage/tracker/etc:/etc/torrust/tracker:Z depends_on: - mysql mysql: image: mysql:8.0 - command: '--default-authentication-plugin=mysql_native_password' + command: "--default-authentication-plugin=mysql_native_password" healthcheck: - test: ['CMD-SHELL', 'mysqladmin ping -h 127.0.0.1 --password="$$(cat /run/secrets/db-password)" --silent'] + test: + [ + "CMD-SHELL", + 'mysqladmin ping -h 127.0.0.1 --password="$$(cat /run/secrets/db-password)" --silent', + ] interval: 3s retries: 5 - start_period: 30s + start_period: 30s environment: - MYSQL_ROOT_HOST=% - MYSQL_ROOT_PASSWORD=root_secret_password @@ -44,4 +48,4 @@ networks: server_side: {} volumes: - mysql_data: {} \ No newline at end of file + mysql_data: {} diff --git a/contrib/bencode/src/reference/decode.rs b/contrib/bencode/src/reference/decode.rs index d2aa180f8..d18dffda0 100644 --- a/contrib/bencode/src/reference/decode.rs +++ b/contrib/bencode/src/reference/decode.rs @@ -1,3 +1,5 @@ +#![allow(clippy::should_panic_without_expect)] + use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::str::{self}; diff --git a/contrib/dev-tools/containers/docker-build.sh b/contrib/dev-tools/containers/docker-build.sh new file mode 100755 index 000000000..39143910f --- /dev/null +++ b/contrib/dev-tools/containers/docker-build.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +echo "Building docker image ..." + +docker build --target release --tag torrust-tracker:release --file Containerfile . diff --git a/contrib/dev-tools/containers/docker-install.sh b/contrib/dev-tools/containers/docker-install.sh new file mode 100755 index 000000000..6034e8233 --- /dev/null +++ b/contrib/dev-tools/containers/docker-install.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +./contrib/dev-tools/containers/docker-build.sh diff --git a/contrib/dev-tools/containers/docker-run-local.sh b/contrib/dev-tools/containers/docker-run-local.sh new file mode 100755 index 000000000..05e23f4a0 --- /dev/null +++ b/contrib/dev-tools/containers/docker-run-local.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +docker run -it \ + --env USER_ID"$(id -u)" \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \ + --volume ./storage/tracker/lib:/var/lib/torrust/tracker:rw \ + --volume ./storage/tracker/log:/var/log/torrust/tracker:rw \ + --volume ./storage/tracker/etc:/etc/torrust/tracker:rw \ + torrust-tracker:release diff --git a/contrib/dev-tools/containers/docker-run-public.sh b/contrib/dev-tools/containers/docker-run-public.sh new file mode 100755 index 000000000..73bcf600a --- /dev/null +++ b/contrib/dev-tools/containers/docker-run-public.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +docker run -it \ + --env USER_ID"$(id -u)" \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \ + --volume ./storage/tracker/lib:/var/lib/torrust/tracker:rw \ + --volume ./storage/tracker/log:/var/log/torrust/tracker:rw \ + --volume ./storage/tracker/etc:/etc/torrust/tracker:rw \ + torrust/tracker:latest diff --git a/contrib/dev-tools/init/install-local.sh b/contrib/dev-tools/init/install-local.sh new file mode 100755 index 000000000..f9806a0b8 --- /dev/null +++ b/contrib/dev-tools/init/install-local.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +# This script is only intended to be used for local development or testing environments. + +# Generate storage directory if it does not exist +mkdir -p ./storage/tracker/lib/database + +# Generate the sqlite database if it does not exist +if ! [ -f "./storage/tracker/lib/database/sqlite3.db" ]; then + # todo: it should get the path from tracker.toml and only do it when we use sqlite + sqlite3 ./storage/tracker/lib/database/sqlite3.db "VACUUM;" +fi diff --git a/contrib/dev-tools/su-exec/LICENSE b/contrib/dev-tools/su-exec/LICENSE new file mode 100644 index 000000000..f623b904e --- /dev/null +++ b/contrib/dev-tools/su-exec/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 ncopa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/contrib/dev-tools/su-exec/Makefile b/contrib/dev-tools/su-exec/Makefile new file mode 100644 index 000000000..bda768957 --- /dev/null +++ b/contrib/dev-tools/su-exec/Makefile @@ -0,0 +1,17 @@ + +CFLAGS ?= -Wall -Werror -g +LDFLAGS ?= + +PROG := su-exec +SRCS := $(PROG).c + +all: $(PROG) + +$(PROG): $(SRCS) + $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) + +$(PROG)-static: $(SRCS) + $(CC) $(CFLAGS) -o $@ $^ -static $(LDFLAGS) + +clean: + rm -f $(PROG) $(PROG)-static diff --git a/contrib/dev-tools/su-exec/README.md b/contrib/dev-tools/su-exec/README.md new file mode 100644 index 000000000..2b0517377 --- /dev/null +++ b/contrib/dev-tools/su-exec/README.md @@ -0,0 +1,46 @@ +# su-exec +switch user and group id, setgroups and exec + +## Purpose + +This is a simple tool that will simply execute a program with different +privileges. The program will be executed directly and not run as a child, +like su and sudo does, which avoids TTY and signal issues (see below). + +Notice that su-exec depends on being run by the root user, non-root +users do not have permission to change uid/gid. + +## Usage + +```shell +su-exec user-spec command [ arguments... ] +``` + +`user-spec` is either a user name (e.g. `nobody`) or user name and group +name separated with colon (e.g. `nobody:ftp`). Numeric uid/gid values +can be used instead of names. Example: + +```shell +$ su-exec apache:1000 /usr/sbin/httpd -f /opt/www/httpd.conf +``` + +## TTY & parent/child handling + +Notice how `su` will make `ps` be a child of a shell while `su-exec` +just executes `ps` directly. + +```shell +$ docker run -it --rm alpine:edge su postgres -c 'ps aux' +PID USER TIME COMMAND + 1 postgres 0:00 ash -c ps aux + 12 postgres 0:00 ps aux +$ docker run -it --rm -v $PWD/su-exec:/sbin/su-exec:ro alpine:edge su-exec postgres ps aux +PID USER TIME COMMAND + 1 postgres 0:00 ps aux +``` + +## Why reinvent gosu? + +This does more or less exactly the same thing as [gosu](https://github.com/tianon/gosu) +but it is only 10kb instead of 1.8MB. + diff --git a/contrib/dev-tools/su-exec/su-exec.c b/contrib/dev-tools/su-exec/su-exec.c new file mode 100644 index 000000000..499071c6e --- /dev/null +++ b/contrib/dev-tools/su-exec/su-exec.c @@ -0,0 +1,109 @@ +/* set user and group id and exec */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +static char *argv0; + +static void usage(int exitcode) +{ + printf("Usage: %s user-spec command [args]\n", argv0); + exit(exitcode); +} + +int main(int argc, char *argv[]) +{ + char *user, *group, **cmdargv; + char *end; + + uid_t uid = getuid(); + gid_t gid = getgid(); + + argv0 = argv[0]; + if (argc < 3) + usage(0); + + user = argv[1]; + group = strchr(user, ':'); + if (group) + *group++ = '\0'; + + cmdargv = &argv[2]; + + struct passwd *pw = NULL; + if (user[0] != '\0') { + uid_t nuid = strtol(user, &end, 10); + if (*end == '\0') + uid = nuid; + else { + pw = getpwnam(user); + if (pw == NULL) + err(1, "getpwnam(%s)", user); + } + } + if (pw == NULL) { + pw = getpwuid(uid); + } + if (pw != NULL) { + uid = pw->pw_uid; + gid = pw->pw_gid; + } + + setenv("HOME", pw != NULL ? pw->pw_dir : "/", 1); + + if (group && group[0] != '\0') { + /* group was specified, ignore grouplist for setgroups later */ + pw = NULL; + + gid_t ngid = strtol(group, &end, 10); + if (*end == '\0') + gid = ngid; + else { + struct group *gr = getgrnam(group); + if (gr == NULL) + err(1, "getgrnam(%s)", group); + gid = gr->gr_gid; + } + } + + if (pw == NULL) { + if (setgroups(1, &gid) < 0) + err(1, "setgroups(%i)", gid); + } else { + int ngroups = 0; + gid_t *glist = NULL; + + while (1) { + int r = getgrouplist(pw->pw_name, gid, glist, &ngroups); + + if (r >= 0) { + if (setgroups(ngroups, glist) < 0) + err(1, "setgroups"); + break; + } + + glist = realloc(glist, ngroups * sizeof(gid_t)); + if (glist == NULL) + err(1, "malloc"); + } + } + + if (setgid(gid) < 0) + err(1, "setgid(%i)", gid); + + if (setuid(uid) < 0) + err(1, "setuid(%i)", uid); + + execvp(cmdargv[0], cmdargv); + err(1, "%s", cmdargv[0]); + + return 1; +} diff --git a/docker/README.md b/docker/README.md deleted file mode 100644 index 207dadbbc..000000000 --- a/docker/README.md +++ /dev/null @@ -1,289 +0,0 @@ -# Docker - -## Requirements - -- Docker version 20.10.21 -- You need to create the `storage` directory with this structure and files: - -```s -$ tree storage/ -storage/ -├── database -│   └── data.db -└── ssl_certificates - ├── localhost.crt - └── localhost.key -``` - -> NOTE: you only need the `ssl_certificates` directory and certificates in case you have enabled SSL for the one HTTP tracker or the API. - -## Demo environment - -You can run a single command to setup the tracker with the default -configuration and run it using the pre-built public docker image: - -```s -curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/torrust/torrust-tracker/v3.0.0-alpha.3/bin/install-demo.sh | bash -export TORRUST_TRACKER_USER_UID=1000 \ - && docker run -it \ - --user="$TORRUST_TRACKER_USER_UID" \ - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \ - --volume "$(pwd)/storage":"/app/storage" \ - --volume "$(pwd)/config.toml":"/app/config.toml":ro \ - torrust/tracker:3.0.0-alpha.3 -``` - -This is intended to be used to run a quick demo of the application. - -## Dev environment - -When using docker you have to bind the exposed ports to the wildcard address `0.0.0.0`, so you can access the application from the host machine. - -The default API configuration uses `127.0.0.1`, so you have to change it to: - -```toml -[http_api] -bind_address = "0.0.0.0:1212" -``` - -Otherwise, the API will be only accessible from inside the container. - -### With docker - -Build and run locally. You can build the docker image locally: - -```s -docker context use default -export TORRUST_TRACKER_USER_UID=1000 -./docker/bin/build.sh $TORRUST_TRACKER_USER_UID -./bin/install.sh -./docker/bin/run-local-image.sh $TORRUST_TRACKER_USER_UID -``` - -Or you can run locally using the pre-built docker image: - -```s -docker context use default -export TORRUST_TRACKER_USER_UID=1000 -./bin/install.sh -./docker/bin/run-public-image.sh $TORRUST_TRACKER_USER_UID -``` - -In both cases, you will need to: - -- Create the SQLite DB (`data.db`) if you are going to use SQLite. -- Create the configuration file (`config.toml`) before running the tracker. -- Replace the user UID (`1000`) with yours. - -> NOTICE: that the `./bin/install.sh` can setup the application for you. But it -uses a predefined configuration. - -Remember to switch to your default docker context `docker context use default` -and to change the API default configuration in `config.toml` to make it -available from the host machine: - -```toml -[http_api] -bind_address = "0.0.0.0:1212" -``` - -### With docker-compose - -The docker-compose configuration includes the MySQL service configuration. If you want to use MySQL instead of SQLite you have to change your `config.toml` configuration: - -```toml -db_driver = "MySQL" -db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" -``` - -If you want to inject an environment variable into docker-compose you can use the file `.env`. There is a template `.env.local`. - -Build and run it locally: - -```s -docker compose up --build -``` - -After running the "up" command you will have two running containers: - -```s -$ docker ps -CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES -06feacb91a9e torrust-tracker "cargo run" 18 minutes ago Up 4 seconds 0.0.0.0:1212->1212/tcp, :::1212->1212/tcp, 0.0.0.0:7070->7070/tcp, :::7070->7070/tcp, 0.0.0.0:6969->6969/udp, :::6969->6969/udp torrust-tracker-1 -34d29e792ee2 mysql:8.0 "docker-entrypoint.s…" 18 minutes ago Up 5 seconds (healthy) 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp torrust-mysql-1 -``` - -And you should be able to use the application, for example making a request to the API: - - - -You can stop the containers with: - -```s -docker compose down -``` - -Additionally, you can delete all resources (containers, volumes, networks) with: - -```s -docker compose down -v -``` - -### Access Mysql with docker - -These are some useful commands for MySQL. - -Open a shell in the MySQL container using docker or docker-compose. - -```s -docker exec -it torrust-mysql-1 /bin/bash -docker compose exec mysql /bin/bash -``` - -Connect to MySQL from inside the MySQL container or from the host: - -```s -mysql -h127.0.0.1 -uroot -proot_secret_password -``` - -The when MySQL container is started the first time, it creates the database, user, and permissions needed. -If you see the error "Host is not allowed to connect to this MySQL server" you can check that users have the right permissions in the database. Make sure the user `root` and `db_user` can connect from any host (`%`). - -```s -mysql> SELECT host, user FROM mysql.user; -+-----------+------------------+ -| host | user | -+-----------+------------------+ -| % | db_user | -| % | root | -| localhost | mysql.infoschema | -| localhost | mysql.session | -| localhost | mysql.sys | -| localhost | root | -+-----------+------------------+ -6 rows in set (0.00 sec) -``` - -If the database, user or permissions are not created the reason could be the MySQL container volume can be corrupted. Delete it and start again the containers. - -### SSL Certificates - -You can use a certificate for localhost. You can create your [localhost certificate](https://letsencrypt.org/docs/certificates-for-localhost/#making-and-trusting-your-own-certificates) and use it in the `storage` folder and the configuration file (`config.toml`). For example: - -The storage folder must contain your certificates: - -```s -$ tree storage/ -storage/ -├── database -│   └── data.db -└── ssl_certificates - ├── localhost.crt - └── localhost.key -``` - -You have not enabled it in your `config.toml` file: - -```toml -... -[[http_trackers]] -enabled = true -bind_address = "0.0.0.0:7070" -ssl_enabled = true -ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -ssl_key_path = "./storage/ssl_certificates/localhost.key" - -[http_api] -enabled = true -bind_address = "0.0.0.0:1212" -ssl_enabled = true -ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -ssl_key_path = "./storage/ssl_certificates/localhost.key" -... -``` - -> NOTE: you can enable it independently for each HTTP tracker or the API. - -If you enable the SSL certificate for the API, for example, you can load the API with this URL: - - - -## Prod environment - -In this section, you will learn how to deploy the tracker to a single docker container in Azure Container Instances. - -> NOTE: Azure Container Instances is a solution when you want to run an isolated container. If you need full container orchestration, including service discovery across multiple containers, automatic scaling, and coordinated application upgrades, we recommend [Kubernetes](https://kubernetes.io/). - -Deploy to Azure Container Instance following [docker documentation](https://docs.docker.com/cloud/aci-integration/). - -You have to create the ACI context and the storage: - -```s -docker context create aci myacicontext -docker context use myacicontext -docker volume create test-volume --storage-account torrustracker -``` - -You need to create all the files needed by the application in the storage dir `storage/database`. - -And finally, you can run the container: - -```s -docker run \ - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \ - --volume torrustracker/test-volume:/app/storage \ - registry.hub.docker.com/torrust/tracker:latest -``` - -Detach from container logs when the container starts. By default, the command line stays attached and follows container logs. - -```s -docker run \ - --detach - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \latest - --volume torrustracker/test-volume:/app/storage \ - registry.hub.docker.com/torrust/tracker:latest -``` - -You should see something like this: - -```s -[+] Running 2/2 - ⠿ Group intelligent-hawking Created 5.0s - ⠿ intelligent-hawking Created 41.7s -2022-12-08T18:39:19.697869300+00:00 [torrust_tracker::logging][INFO] logging initialized. -2022-12-08T18:39:19.712651100+00:00 [torrust_tracker::jobs::udp_tracker][INFO] Starting UDP server on: 0.0.0.0:6969 -2022-12-08T18:39:19.712792700+00:00 [torrust_tracker::jobs::tracker_api][INFO] Starting Torrust API server on: 0.0.0.0:1212 -2022-12-08T18:39:19.725124+00:00 [torrust_tracker::jobs::tracker_api][INFO] Torrust API server started -``` - -You can see the container with: - -```s -$ docker ps -CONTAINER ID IMAGE COMMAND STATUS PORTS -intelligent-hawking registry.hub.docker.com/torrust/tracker:latest Running 4.236.213.57:6969->6969/udp, 4.236.213.57:1212->1212/tcp -``` - -After a while, you can use the tracker API `http://4.236.213.57:1212/api/v1/stats?token=MyAccessToken` and the UDP tracker with your BitTorrent client using this tracker announce URL `udp://4.236.213.57:6969`. - -> NOTES: -> -> - [There is no support for mounting a single file](https://docs.docker.com/cloud/aci-container-features/#persistent-volumes), or mounting a subfolder from an `Azure File Share`. -> - [ACI does not allow port mapping](https://docs.docker.com/cloud/aci-integration/#exposing-ports). -> - [Azure file share volume mount requires the Linux container run as root](https://learn.microsoft.com/en-us/azure/container-instances/container-instances-volume-azure-files#limitations). -> - It can take some minutes until the public IP for the ACI container is available. -> - You can use the Azure web UI to download files from the storage. For example, the SQLite database. -> - [It seems you can only expose web interfaces on port 80 on Azure Container Instances](https://stackoverflow.com/a/56768087/3012842). Not official documentation! - -## Links - -- [Deploying Docker containers on Azure](https://docs.docker.com/cloud/aci-integration/). -- [Docker run options for ACI containers](https://docs.docker.com/cloud/aci-container-features/). -- [Quickstart: Deploy a container instance in Azure using the Docker CLI](https://learn.microsoft.com/en-us/azure/container-instances/quickstart-docker-cli). diff --git a/docker/bin/build.sh b/docker/bin/build.sh deleted file mode 100755 index d77d1ad34..000000000 --- a/docker/bin/build.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -TORRUST_TRACKER_USER_UID=${TORRUST_TRACKER_USER_UID:-1000} -TORRUST_TRACKER_RUN_AS_USER=${TORRUST_TRACKER_RUN_AS_USER:-appuser} - -echo "Building docker image ..." -echo "TORRUST_TRACKER_USER_UID: $TORRUST_TRACKER_USER_UID" -echo "TORRUST_TRACKER_RUN_AS_USER: $TORRUST_TRACKER_RUN_AS_USER" - -docker build \ - --build-arg UID="$TORRUST_TRACKER_USER_UID" \ - --build-arg RUN_AS_USER="$TORRUST_TRACKER_RUN_AS_USER" \ - -t torrust-tracker . diff --git a/docker/bin/install.sh b/docker/bin/install.sh deleted file mode 100755 index a58969378..000000000 --- a/docker/bin/install.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash - -./docker/bin/build.sh -./bin/install.sh diff --git a/docker/bin/run-local-image.sh b/docker/bin/run-local-image.sh deleted file mode 100755 index 86465baeb..000000000 --- a/docker/bin/run-local-image.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -TORRUST_TRACKER_USER_UID=${TORRUST_TRACKER_USER_UID:-1000} -TORRUST_TRACKER_CONFIG=$(cat config.toml) - -docker run -it \ - --user="$TORRUST_TRACKER_USER_UID" \ - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \ - --env TORRUST_TRACKER_CONFIG="$TORRUST_TRACKER_CONFIG" \ - --volume "$(pwd)/storage":"/app/storage" \ - torrust-tracker diff --git a/docker/bin/run-public-image.sh b/docker/bin/run-public-image.sh deleted file mode 100755 index 50407f91b..000000000 --- a/docker/bin/run-public-image.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -TORRUST_TRACKER_USER_UID=${TORRUST_TRACKER_USER_UID:-1000} -TORRUST_TRACKER_CONFIG=$(cat config.toml) - -docker run -it \ - --user="$TORRUST_TRACKER_USER_UID" \ - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \ - --env TORRUST_TRACKER_CONFIG="$TORRUST_TRACKER_CONFIG" \ - --volume "$(pwd)/storage":"/app/storage" \ - torrust/tracker \ No newline at end of file diff --git a/docs/containers.md b/docs/containers.md new file mode 100644 index 000000000..b9aa05a7a --- /dev/null +++ b/docs/containers.md @@ -0,0 +1,428 @@ +# Containers (Docker or Podman) + +## Demo environment +It is simple to setup the tracker with the default +configuration and run it using the pre-built public docker image: + + +With Docker: + +```sh +docker run -it torrust/tracker:latest +``` + +or with Podman: + +```sh +podman run -it torrust/tracker:latest +``` + + +## Requirements +- Tested with recent versions of Docker or Podman. + +## Volumes +The [Containerfile](../Containerfile) (i.e. the Dockerfile) Defines Three Volumes: + +```Dockerfile +VOLUME ["/var/lib/torrust/tracker","/var/log/torrust/tracker","/etc/torrust/tracker"] +``` + +When instancing the container image with the `docker run` or `podman run` command, we map these volumes to the local storage: + +```s +./storage/tracker/lib -> /var/lib/torrust/tracker +./storage/tracker/log -> /var/log/torrust/tracker +./storage/tracker/etc -> /etc/torrust/tracker +``` + +> NOTE: You can adjust this mapping for your preference, however this mapping is the default in our guides and scripts. + +### Pre-Create Host-Mapped Folders: +Please run this command where you wish to run the container: + +```sh +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ +``` + +### Matching Ownership ID's of Host Storage and Container Volumes +It is important that the `torrust` user has the same uid `$(id -u)` as the host mapped folders. In our [entry script](../share/container/entry_script_sh), installed to `/usr/local/bin/entry.sh` inside the container, switches to the `torrust` user created based upon the `USER_UID` environmental variable. + +When running the container, you may use the `--env USER_ID="$(id -u)"` argument that gets the current user-id and passes to the container. + +### Mapped Tree Structure +Using the standard mapping defined above produces this following mapped tree: + +```s +storage/tracker/ +├── lib +│ ├── database +│ │   └── sqlite3.db => /var/lib/torrust/tracker/database/sqlite3.db [auto populated] +│ └── tls +│ ├── localhost.crt => /var/lib/torrust/tracker/tls/localhost.crt [user supplied] +│ └── localhost.key => /var/lib/torrust/tracker/tls/localhost.key [user supplied] +├── log => /var/log/torrust/tracker (future use) +└── etc + └── tracker.toml => /etc/torrust/tracker/tracker.toml [auto populated] +``` + +> NOTE: you only need the `tls` directory and certificates in case you have enabled SSL. + +## Building the Container + +### Clone and Change into Repository + +```sh +# Inside your dev folder +git clone https://github.com/torrust/torrust-tracker.git; cd torrust-tracker +``` + +### (Docker) Setup Context +Before starting, if you are using docker, it is helpful to reset the context to the default: + +```sh +docker context use default +``` + +### (Docker) Build + +```sh +# Release Mode +docker build --target release --tag torrust-tracker:release --file Containerfile . + +# Debug Mode +docker build --target debug --tag torrust-tracker:debug --file Containerfile . +``` + +### (Podman) Build + +```sh +# Release Mode +podman build --target release --tag torrust-tracker:release --file Containerfile . + +# Debug Mode +podman build --target debug --tag torrust-tracker:debug --file Containerfile . +``` + +## Running the Container + +### Basic Run +No arguments are needed for simply checking the container image works: + +#### (Docker) Run Basic + +```sh +# Release Mode +docker run -it torrust-tracker:release + +# Debug Mode +docker run -it torrust-tracker:debug +``` +#### (Podman) Run Basic + +```sh +# Release Mode +podman run -it torrust-tracker:release + +# Debug Mode +podman run -it torrust-tracker:debug +``` + +### Arguments +The arguments need to be placed before the image tag. i.e. + +`run [arguments] torrust-tracker:release` + +#### Environmental Variables: +Environmental variables are loaded through the `--env`, in the format `--env VAR="value"`. + +The following environmental variables can be set: + +- `TORRUST_TRACKER_PATH_CONFIG` - The in-container path to the tracker configuration file, (default: `"/etc/torrust/tracker/tracker.toml"`). +- `TORRUST_TRACKER_API_ADMIN_TOKEN` - Override of the admin token. If set, this value overrides any value set in the config. +- `TORRUST_TRACKER_DATABASE` - The database type used for the container, (options: `sqlite3`, `mysql`, default `sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. +- `TORRUST_TRACKER_CONFIG` - Load config from this environmental variable instead from a file, (i.e: `TORRUST_TRACKER_CONFIG=$(cat tracker-tracker.toml)`). +- `USER_ID` - The user id for the runtime crated `torrust` user. Please Note: This user id should match the ownership of the host-mapped volumes, (default `1000`). +- `UDP_PORT` - The port for the UDP tracker. This should match the port used in the configuration, (default `6969`). +- `HTTP_PORT` - The port for the HTTP tracker. This should match the port used in the configuration, (default `7070`). +- `API_PORT` - The port for the tracker API. This should match the port used in the configuration, (default `1212`). + + +### Sockets +Socket ports used internally within the container can be mapped to with the `--publish` argument. + +The format is: `--publish [optional_host_ip]:[host_port]:[container_port]/[optional_protocol]`, for example: `--publish 127.0.0.1:8080:80/tcp`. + +The default ports can be mapped with the following: + +```s +--publish 0.0.0.0:7070:7070/tcp \ +--publish 0.0.0.0:6969:6969/udp \ +--publish 0.0.0.0:1212:1212/tcp \ +``` + +> NOTE: Inside the container it is necessary to expose a socket with the wildcard address `0.0.0.0` so that it may be accessible from the host. Verify that the configuration that the sockets are wildcard. + +### Volumes +By default the container will use install volumes for `/var/lib/torrust/tracker`, `/var/log/torrust/tracker`, and `/etc/torrust/tracker`, however for better administration it good to make these volumes host-mapped. + +The argument to host-map volumes is `--volume`, with the format: `--volume=[host-src:]container-dest[:]`. + +The default mapping can be supplied with the following arguments: + +```s +--volume ./storage/tracker/lib:/var/lib/torrust/tracker:Z \ +--volume ./storage/tracker/log:/var/log/torrust/tracker:Z \ +--volume ./storage/tracker/etc:/etc/torrust/tracker:Z \ +``` + + +Please not the `:Z` at the end of the podman `--volume` mapping arguments, this is to give read-write permission on SELinux enabled systemd, if this doesn't work on your system, you can use `:rw` instead. + +## Complete Example: + +### With Docker + +```sh +## Setup Docker Default Context +docker context use default + +## Build Container Image +docker build --target release --tag torrust-tracker:release --file Containerfile . + +## Setup Mapped Volumes +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +## Run Torrust Tracker Container Image +docker run -it \ + --env TORRUST_TRACKER_API_ADMIN_TOKEN="MySecretToken" \ + --env USER_ID"$(id -u)" \ + --publish 0.0.0.0:7070:7070/tcp \ + --publish 0.0.0.0:6969:6969/udp \ + --publish 0.0.0.0:1212:1212/tcp \ + --volume ./storage/tracker/lib:/var/lib/torrust/tracker:Z \ + --volume ./storage/tracker/log:/var/log/torrust/tracker:Z \ + --volume ./storage/tracker/etc:/etc/torrust/tracker:Z \ + torrust-tracker:release +``` + +### With Podman + +```sh +## Build Container Image +podman build --target release --tag torrust-tracker:release --file Containerfile . + +## Setup Mapped Volumes +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +## Run Torrust Tracker Container Image +podman run -it \ + --env TORRUST_TRACKER_API_ADMIN_TOKEN="MySecretToken" \ + --env USER_ID"$(id -u)" \ + --publish 0.0.0.0:7070:7070/tcp \ + --publish 0.0.0.0:6969:6969/udp \ + --publish 0.0.0.0:1212:1212/tcp \ + --volume ./storage/tracker/lib:/var/lib/torrust/tracker:Z \ + --volume ./storage/tracker/log:/var/log/torrust/tracker:Z \ + --volume ./storage/tracker/etc:/etc/torrust/tracker:Z \ + torrust-tracker:release +``` + +## Docker Compose + +The docker-compose configuration includes the MySQL service configuration. If you want to use MySQL instead of SQLite you should verify the `/etc/torrust/tracker/tracker.toml` (i.e `./storage/tracker/etc/tracker.toml`) configuration: + +```toml +db_driver = "MySQL" +db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" +``` + +### Build and Run: + +```sh +docker build --target release --tag torrust-tracker:release --file Containerfile . + +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +USER_ID=$(id -u) \ + TORRUST_TRACKER_API_ADMIN_TOKEN="MySecretToken" \ + docker compose up --build +``` + +After running the `compose up` command you will have two running containers: + +```s +$ docker ps +CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES +06feacb91a9e torrust-tracker "cargo run" 18 minutes ago Up 4 seconds 0.0.0.0:1212->1212/tcp, :::1212->1212/tcp, 0.0.0.0:7070->7070/tcp, :::7070->7070/tcp, 0.0.0.0:6969->6969/udp, :::6969->6969/udp torrust-tracker-1 +34d29e792ee2 mysql:8.0 "docker-entrypoint.s…" 18 minutes ago Up 5 seconds (healthy) 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp torrust-mysql-1 +``` + +And you should be able to use the application, for example making a request to the API: + + + +You can stop the containers with: + +```s +docker compose down +``` + +Additionally, you can delete all resources (containers, volumes, networks) with: + +```s +docker compose down -v +``` + +### Access Mysql with docker + +These are some useful commands for MySQL. + +Open a shell in the MySQL container using docker or docker-compose. + +```s +docker exec -it torrust-mysql-1 /bin/bash +docker compose exec mysql /bin/bash +``` + +Connect to MySQL from inside the MySQL container or from the host: + +```s +mysql -h127.0.0.1 -uroot -proot_secret_password +``` + +The when MySQL container is started the first time, it creates the database, user, and permissions needed. +If you see the error "Host is not allowed to connect to this MySQL server" you can check that users have the right permissions in the database. Make sure the user `root` and `db_user` can connect from any host (`%`). + +```s +mysql> SELECT host, user FROM mysql.user; ++-----------+------------------+ +| host | user | ++-----------+------------------+ +| % | db_user | +| % | root | +| localhost | mysql.infoschema | +| localhost | mysql.session | +| localhost | mysql.sys | +| localhost | root | ++-----------+------------------+ +6 rows in set (0.00 sec) +``` + +If the database, user or permissions are not created the reason could be the MySQL container volume can be corrupted. Delete it and start again the containers. + +### SSL Certificates + +You can use a certificate for localhost. You can create your [localhost certificate](https://letsencrypt.org/docs/certificates-for-localhost/#making-and-trusting-your-own-certificates) and use it in the `storage` folder and the configuration file (`tracker.toml`). For example: + +The storage folder must contain your certificates: + +```s +storage/tracker/lib/tls + ├── localhost.crt + └── localhost.key +``` + +You have not enabled it in your `tracker.toml` file: + +```toml + +[[http_trackers]] +# ... +ssl_enabled = true +# ... + +[http_api] +# ... +ssl_enabled = true +# ... + +``` + +> NOTE: you can enable it independently for each HTTP tracker or the API. + +If you enable the SSL certificate for the API, for example, you can load the API with this URL: + + + +## Prod environment + +In this section, you will learn how to deploy the tracker to a single docker container in Azure Container Instances. + +> NOTE: Azure Container Instances is a solution when you want to run an isolated container. If you need full container orchestration, including service discovery across multiple containers, automatic scaling, and coordinated application upgrades, we recommend [Kubernetes](https://kubernetes.io/). + +Deploy to Azure Container Instance following [docker documentation](https://docs.docker.com/cloud/aci-integration/). + +You have to create the ACI context and the storage: + +```s +docker context create aci myacicontext +docker context use myacicontext +docker volume create test-volume --storage-account torrustracker +``` + +You need to create all the files needed by the application in the storage dir `storage/lib/database`. + +And finally, you can run the container: + +```s +docker run \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \ + --volume torrustracker/lib:/var/lib/torrust/tracker:rw \ + --volume torrustracker/log:/var/log/torrust/tracker:rw \ + --volume torrustracker/etc:/etc/torrust/tracker:rw \ + registry.hub.docker.com/torrust/tracker:latest +``` + +Detach from container logs when the container starts. By default, the command line stays attached and follows container logs. + +```s +docker run \ + --detach + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \latest + --volume torrustracker/lib:/var/lib/torrust/tracker:rw \ + --volume torrustracker/log:/var/log/torrust/tracker:rw \ + --volume torrustracker/etc:/etc/torrust/tracker:rw \ + registry.hub.docker.com/torrust/tracker:latest +``` + +You should see something like this: + +```s +[+] Running 2/2 + ⠿ Group intelligent-hawking Created 5.0s + ⠿ intelligent-hawking Created 41.7s +2022-12-08T18:39:19.697869300+00:00 [torrust_tracker::logging][INFO] logging initialized. +2022-12-08T18:39:19.712651100+00:00 [torrust_tracker::jobs::udp_tracker][INFO] Starting UDP server on: 0.0.0.0:6969 +2022-12-08T18:39:19.712792700+00:00 [torrust_tracker::jobs::tracker_api][INFO] Starting Torrust API server on: 0.0.0.0:1212 +2022-12-08T18:39:19.725124+00:00 [torrust_tracker::jobs::tracker_api][INFO] Torrust API server started +``` + +You can see the container with: + +```s +$ docker ps +CONTAINER ID IMAGE COMMAND STATUS PORTS +intelligent-hawking registry.hub.docker.com/torrust/tracker:latest Running 4.236.213.57:6969->6969/udp, 4.236.213.57:1212->1212/tcp +``` + +After a while, you can use the tracker API `http://4.236.213.57:1212/api/v1/stats?token=MyAccessToken` and the UDP tracker with your BitTorrent client using this tracker announce URL `udp://4.236.213.57:6969`. + +> NOTES: +> +> - [There is no support for mounting a single file](https://docs.docker.com/cloud/aci-container-features/#persistent-volumes), or mounting a subfolder from an `Azure File Share`. +> - [ACI does not allow port mapping](https://docs.docker.com/cloud/aci-integration/#exposing-ports). +> - [Azure file share volume mount requires the Linux container run as root](https://learn.microsoft.com/en-us/azure/container-instances/container-instances-volume-azure-files#limitations). +> - It can take some minutes until the public IP for the ACI container is available. +> - You can use the Azure web UI to download files from the storage. For example, the SQLite database. +> - [It seems you can only expose web interfaces on port 80 on Azure Container Instances](https://stackoverflow.com/a/56768087/3012842). Not official documentation! + +## Links + +- [Deploying Docker containers on Azure](https://docs.docker.com/cloud/aci-integration/). +- [Docker run options for ACI containers](https://docs.docker.com/cloud/aci-container-features/). +- [Quickstart: Deploy a container instance in Azure using the Docker CLI](https://learn.microsoft.com/en-us/azure/container-instances/quickstart-docker-cli). diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 9b91534e9..e3ca1d932 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -14,8 +14,8 @@ config = "0.13" toml = "0.7" log = { version = "0.4", features = ["release_max_level_info"] } thiserror = "1.0" -torrust-tracker-primitives = { version = "3.0.0-alpha.3", path = "../primitives" } -torrust-tracker-located-error = { version = "3.0.0-alpha.3", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.4", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.4", path = "../located-error" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 6de0e3ed7..059316a26 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -4,7 +4,7 @@ //! Torrust Tracker, which is a `BitTorrent` tracker server. //! //! The configuration is loaded from a [TOML](https://toml.io/en/) file -//! `config.toml` in the project root folder or from an environment variable +//! `tracker.toml` in the project root folder or from an environment variable //! with the same content as the file. //! //! When you run the tracker without a configuration file, a new one will be @@ -67,7 +67,7 @@ //! storage/ //! ├── database //! │ └── data.db -//! └── ssl_certificates +//! └── tls //! ├── localhost.crt //! └── localhost.key //! ``` @@ -176,14 +176,14 @@ //! [[http_trackers]] //! enabled = true //! ... -//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -//! ssl_key_path = "./storage/ssl_certificates/localhost.key" +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! //! [http_api] //! enabled = true //! ... -//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -//! ssl_key_path = "./storage/ssl_certificates/localhost.key" +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! ``` //! //! ## Default configuration @@ -194,7 +194,7 @@ //! log_level = "info" //! mode = "public" //! db_driver = "Sqlite3" -//! db_path = "./storage/database/data.db" +//! db_path = "./storage/tracker/lib/database/sqlite3.db" //! announce_interval = 120 //! min_announce_interval = 120 //! max_peer_timeout = 900 @@ -239,6 +239,67 @@ use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; +/// Information required for loading config +#[derive(Debug, Default, Clone)] +pub struct Info { + tracker_toml: String, + api_admin_token: Option, +} + +impl Info { + /// Build Configuration Info + /// + /// # Examples + /// + /// ``` + /// use torrust_tracker_configuration::Info; + /// + /// let result = Info::new(env_var_config, env_var_path_config, default_path_config, env_var_api_admin_token); + /// assert_eq!(result, ); + /// ``` + /// + /// # Errors + /// + /// Will return `Err` if unable to obtain a configuration. + /// + #[allow(clippy::needless_pass_by_value)] + pub fn new( + env_var_config: String, + env_var_path_config: String, + default_path_config: String, + env_var_api_admin_token: String, + ) -> Result { + let tracker_toml = if let Ok(tracker_toml) = env::var(&env_var_config) { + println!("Loading configuration from env var {env_var_config} ..."); + + tracker_toml + } else { + let config_path = if let Ok(config_path) = env::var(env_var_path_config) { + println!("Loading configuration file: `{config_path}` ..."); + + config_path + } else { + println!("Loading default configuration file: `{default_path_config}` ..."); + + default_path_config + }; + + fs::read_to_string(config_path) + .map_err(|e| Error::UnableToLoadFromConfigFile { + source: (Arc::new(e) as Arc).into(), + })? + .parse() + .map_err(|_e: std::convert::Infallible| Error::Infallible)? + }; + let api_admin_token = env::var(env_var_api_admin_token).ok(); + + Ok(Self { + tracker_toml, + api_admin_token, + }) + } +} + /// Configuration for each UDP tracker. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct UdpTracker { @@ -298,6 +359,12 @@ pub struct HttpApi { pub access_tokens: HashMap, } +impl HttpApi { + fn override_admin_token(&mut self, api_admin_token: &str) { + self.access_tokens.insert("admin".to_string(), api_admin_token.to_string()); + } +} + impl HttpApi { /// Checks if the given token is one of the token in the configuration. #[must_use] @@ -323,7 +390,7 @@ pub struct Configuration { pub db_driver: DatabaseDriver, /// Database connection string. The format depends on the database driver. /// For `Sqlite3`, the format is `path/to/database.db`, for example: - /// `./storage/database/data.db`. + /// `./storage/tracker/lib/database/sqlite3.db`. /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for /// example: `root:password@localhost:3306/torrust`. pub db_path: String, @@ -411,9 +478,17 @@ pub enum Error { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, }, + #[error("Unable to load from Config File: {source}")] + UnableToLoadFromConfigFile { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + }, + /// Unable to load the configuration from the configuration file. #[error("Failed processing the configuration: {source}")] ConfigError { source: LocatedError<'static, ConfigError> }, + + #[error("The error for errors that can never happen.")] + Infallible, } impl From for Error { @@ -431,7 +506,7 @@ impl Default for Configuration { log_level: Option::from(String::from("info")), mode: TrackerMode::Public, db_driver: DatabaseDriver::Sqlite3, - db_path: String::from("./storage/database/data.db"), + db_path: String::from("./storage/tracker/lib/database/sqlite3.db"), announce_interval: 120, min_announce_interval: 120, max_peer_timeout: 900, @@ -471,6 +546,10 @@ impl Default for Configuration { } impl Configuration { + fn override_api_admin_token(&mut self, api_admin_token: &str) { + self.http_api.override_admin_token(api_admin_token); + } + /// Returns the tracker public IP address id defined in the configuration, /// and `None` otherwise. #[must_use] @@ -514,26 +593,25 @@ impl Configuration { Ok(config) } - /// Loads the configuration from the environment variable. The whole - /// configuration must be in the environment variable. It contains the same - /// configuration as the configuration file with the same format. + /// Loads the configuration from the `Info` struct. The whole + /// configuration in toml format is included in the `info.tracker_toml` string. + /// + /// Optionally will override the admin api token. /// /// # Errors /// /// Will return `Err` if the environment variable does not exist or has a bad configuration. - pub fn load_from_env_var(config_env_var_name: &str) -> Result { - match env::var(config_env_var_name) { - Ok(config_toml) => { - let config_builder = Config::builder() - .add_source(File::from_str(&config_toml, FileFormat::Toml)) - .build()?; - let config = config_builder.try_deserialize()?; - Ok(config) - } - Err(e) => Err(Error::UnableToLoadFromEnvironmentVariable { - source: (Arc::new(e) as Arc).into(), - }), - } + pub fn load(info: &Info) -> Result { + let config_builder = Config::builder() + .add_source(File::from_str(&info.tracker_toml, FileFormat::Toml)) + .build()?; + let mut config: Configuration = config_builder.try_deserialize()?; + + if let Some(ref token) = info.api_admin_token { + config.override_api_admin_token(token); + }; + + Ok(config) } /// Saves the configuration to the configuration file. @@ -567,7 +645,7 @@ mod tests { let config = r#"log_level = "info" mode = "public" db_driver = "Sqlite3" - db_path = "./storage/database/data.db" + db_path = "./storage/tracker/lib/database/sqlite3.db" announce_interval = 120 min_announce_interval = 120 on_reverse_proxy = false diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index e9d86a589..4e6c70e66 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -10,5 +10,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.3", path = "../configuration"} -torrust-tracker-primitives = { version = "3.0.0-alpha.3", path = "../primitives"} +torrust-tracker-configuration = { version = "3.0.0-alpha.4", path = "../configuration"} +torrust-tracker-primitives = { version = "3.0.0-alpha.4", path = "../primitives"} diff --git a/rustfmt.toml b/rustfmt.toml index 3e878b271..abbed5eda 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,4 +1,3 @@ max_width = 130 imports_granularity = "Module" group_imports = "StdExternalCrate" - diff --git a/share/container/entry_script_sh b/share/container/entry_script_sh new file mode 100644 index 000000000..88a832b40 --- /dev/null +++ b/share/container/entry_script_sh @@ -0,0 +1,81 @@ +#!/bin/sh +set -x + +to_lc() { echo "$1" | tr '[:upper:]' '[:lower:]'; } +clean() { echo "$1" | tr -d -c 'a-zA-Z0-9-' ; } +cmp_lc() { [ "$(to_lc "$(clean "$1")")" = "$(to_lc "$(clean "$2")")" ]; } + + +inst() { + if [ -n "$1" ] && [ -n "$2" ] && [ -e "$1" ] && [ ! -e "$2" ]; then + install -D -m 0640 -o torrust -g torrust "$1" "$2"; fi; } + + +# Add torrust user, based upon supplied user-id. +if [ -z "$USER_ID" ] && [ "$USER_ID" -lt 1000 ]; then + echo "ERROR: USER_ID is not set, or less than 1000" + exit 1 +fi + +adduser --disabled-password --shell "/bin/sh" --uid "$USER_ID" "torrust" + +# Configure Permissions for Torrust Folders +mkdir -p /var/lib/torrust/tracker/database/ /etc/torrust/tracker/ +chown -R "${USER_ID}":"${USER_ID}" /var/lib/torrust /var/log/torrust /etc/torrust +chmod -R 2770 /var/lib/torrust /var/log/torrust /etc/torrust + + +# Install the database and config: +if [ -n "$TORRUST_TRACKER_DATABASE" ]; then + if cmp_lc "$TORRUST_TRACKER_DATABASE" "sqlite3"; then + + # Select sqlite3 empty database + default_database="/usr/share/torrust/default/database/tracker.sqlite3.db" + + # Select sqlite3 default configuration + default_config="/usr/share/torrust/default/config/tracker.container.sqlite3.toml" + + elif cmp_lc "$TORRUST_TRACKER_DATABASE" "mysql"; then + + # (no database file needed for mysql) + + # Select default mysql configuration + default_config="/usr/share/torrust/default/config/tracker.container.mysql.toml" + + else + echo "Error: Unsupported Database Type: \"$TORRUST_TRACKER_DATABASE\"." + echo "Please Note: Supported Database Types: \"sqlite3\", \"mysql\"." + exit 1 + fi +else + echo "Error: \"\$TORRUST_TRACKER_DATABASE\" was not set!"; exit 1; +fi + +install_config="/etc/torrust/tracker/tracker.toml" +install_database="/var/lib/torrust/tracker/database/sqlite3.db" + +inst "$default_config" "$install_config" +inst "$default_database" "$install_database" + +# Make Minimal Message of the Day +if cmp_lc "$RUNTIME" "runtime"; then + printf '\n in runtime \n' >> /etc/motd; +elif cmp_lc "$RUNTIME" "debug"; then + printf '\n in debug mode \n' >> /etc/motd; +elif cmp_lc "$RUNTIME" "release"; then + printf '\n in release mode \n' >> /etc/motd; +else + echo "ERROR: running in unknown mode: \"$RUNTIME\""; exit 1 +fi + +if [ -e "/usr/share/torrust/container/message" ]; then + cat "/usr/share/torrust/container/message" >> /etc/motd; chmod 0644 /etc/motd +fi + +# Load message of the day from Profile +echo '[ ! -z "$TERM" -a -r /etc/motd ] && cat /etc/motd' >> /etc/profile + +cd /home/torrust || exit 1 + +# Switch to torrust user +exec /bin/su-exec torrust "$@" diff --git a/share/container/message b/share/container/message new file mode 100644 index 000000000..cd88b44ae --- /dev/null +++ b/share/container/message @@ -0,0 +1,2 @@ + +run 'torrust-tracker' to start tracker diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml new file mode 100644 index 000000000..60da25db2 --- /dev/null +++ b/share/default/config/tracker.container.mysql.toml @@ -0,0 +1,39 @@ +log_level = "info" +mode = "public" +db_driver = "MySQL" +db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" +announce_interval = 120 +min_announce_interval = 120 +on_reverse_proxy = false +external_ip = "0.0.0.0" +tracker_usage_statistics = true +persistent_torrent_completed_stat = false +max_peer_timeout = 900 +inactive_peer_cleanup_interval = 600 +remove_peerless_torrents = true + +[[udp_trackers]] +enabled = false +bind_address = "0.0.0.0:6969" + +[[http_trackers]] +enabled = false +bind_address = "0.0.0.0:7070" +ssl_enabled = false +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + +[http_api] +enabled = true +bind_address = "0.0.0.0:1212" +ssl_enabled = false +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + + +# Please override the admin token setting the +# `TORRUST_TRACKER_API_ADMIN_TOKEN` +# environmental variable! + +[http_api.access_tokens] +admin = "MyAccessToken" diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml new file mode 100644 index 000000000..64cf75518 --- /dev/null +++ b/share/default/config/tracker.container.sqlite3.toml @@ -0,0 +1,39 @@ +log_level = "info" +mode = "public" +db_driver = "Sqlite3" +db_path = "/var/lib/torrust/tracker/database/sqlite3.db" +announce_interval = 120 +min_announce_interval = 120 +on_reverse_proxy = false +external_ip = "0.0.0.0" +tracker_usage_statistics = true +persistent_torrent_completed_stat = false +max_peer_timeout = 900 +inactive_peer_cleanup_interval = 600 +remove_peerless_torrents = true + +[[udp_trackers]] +enabled = false +bind_address = "0.0.0.0:6969" + +[[http_trackers]] +enabled = false +bind_address = "0.0.0.0:7070" +ssl_enabled = false +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + +[http_api] +enabled = true +bind_address = "0.0.0.0:1212" +ssl_enabled = false +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + + +# Please override the admin token setting the +# `TORRUST_TRACKER_API_ADMIN_TOKEN` +# environmental variable! + +[http_api.access_tokens] +admin = "MyAccessToken" diff --git a/config.toml.local b/share/default/config/tracker.development.sqlite3.toml similarity index 92% rename from config.toml.local rename to share/default/config/tracker.development.sqlite3.toml index be6a11a56..be1877469 100644 --- a/config.toml.local +++ b/share/default/config/tracker.development.sqlite3.toml @@ -1,7 +1,7 @@ log_level = "info" mode = "public" db_driver = "Sqlite3" -db_path = "./storage/database/data.db" +db_path = "./storage/tracker/lib/database/sqlite3.db" announce_interval = 120 min_announce_interval = 120 on_reverse_proxy = false diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 727bf59f7..858fd59fc 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -1,30 +1,28 @@ //! Initialize configuration from file or env var. //! //! All environment variables are prefixed with `TORRUST_TRACKER_BACK_`. -use std::env; -use std::path::Path; -use torrust_tracker_configuration::{Configuration, Error}; +use torrust_tracker_configuration::{Configuration, Info}; // Environment variables -/// The whole `config.toml` file content. It has priority over the config file. +/// The whole `tracker.toml` file content. It has priority over the config file. /// Even if the file is not on the default path. const ENV_VAR_CONFIG: &str = "TORRUST_TRACKER_CONFIG"; +const ENV_VAR_API_ADMIN_TOKEN: &str = "TORRUST_TRACKER_API_ADMIN_TOKEN"; -/// The `config.toml` file location. -pub const ENV_VAR_CONFIG_PATH: &str = "TORRUST_TRACKER_CONFIG_PATH"; +/// The `tracker.toml` file location. +pub const ENV_VAR_PATH_CONFIG: &str = "TORRUST_TRACKER_PATH_CONFIG"; // Default values - -const ENV_VAR_DEFAULT_CONFIG_PATH: &str = "./config.toml"; +pub const DEFAULT_PATH_CONFIG: &str = "./share/default/config/tracker.development.sqlite3.toml"; /// It loads the application configuration from the environment. /// /// There are two methods to inject the configuration: /// -/// 1. By using a config file: `config.toml`. -/// 2. Environment variable: `TORRUST_TRACKER_CONFIG`. The variable contains the same contents as the `config.toml` file. +/// 1. By using a config file: `tracker.toml`. +/// 2. Environment variable: `TORRUST_TRACKER_CONFIG`. The variable contains the same contents as the `tracker.toml` file. /// /// Environment variable has priority over the config file. /// @@ -33,37 +31,27 @@ const ENV_VAR_DEFAULT_CONFIG_PATH: &str = "./config.toml"; /// # Panics /// /// Will panic if it can't load the configuration from either -/// `./config.toml` file or the env var `TORRUST_TRACKER_CONFIG`. +/// `./tracker.toml` file or the env var `TORRUST_TRACKER_CONFIG`. #[must_use] pub fn initialize_configuration() -> Configuration { - if env::var(ENV_VAR_CONFIG).is_ok() { - println!("Loading configuration from env var {ENV_VAR_CONFIG} ..."); + let info = Info::new( + ENV_VAR_CONFIG.to_string(), + ENV_VAR_PATH_CONFIG.to_string(), + DEFAULT_PATH_CONFIG.to_string(), + ENV_VAR_API_ADMIN_TOKEN.to_string(), + ) + .unwrap(); + + Configuration::load(&info).unwrap() +} - Configuration::load_from_env_var(ENV_VAR_CONFIG).unwrap() - } else { - let config_path = env::var(ENV_VAR_CONFIG_PATH).unwrap_or_else(|_| ENV_VAR_DEFAULT_CONFIG_PATH.to_string()); +#[cfg(test)] +mod tests { - println!("Loading configuration from configuration file: `{config_path}` ..."); + #[test] + fn it_should_load_with_default_config() { + use crate::bootstrap::config::initialize_configuration; - load_from_file_or_create_default(&config_path).unwrap() - } -} - -/// Loads the configuration from the configuration file. If the file does -/// not exist, it will create a default configuration file and return an -/// error. -/// -/// # Errors -/// -/// Will return `Err` if `path` does not exist or has a bad configuration. -fn load_from_file_or_create_default(path: &str) -> Result { - if Path::new(&path).is_file() { - Configuration::load_from_file(path) - } else { - println!("Missing configuration file."); - println!("Creating a default configuration file: `{path}` ..."); - let config = Configuration::create_default_configuration_file(path)?; - println!("Please review the config file: `{path}` and restart the tracker if needed."); - Ok(config) + drop(initialize_configuration()); } } diff --git a/src/lib.rs b/src/lib.rs index 28bac9244..c862d373a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -112,16 +112,16 @@ //! storage/ //! ├── database //! │   └── data.db -//! └── ssl_certificates +//! └── tls //! ├── localhost.crt //! └── localhost.key //! ``` //! -//! The default configuration expects a directory `./storage/database` to be writable by the tracker process. +//! The default configuration expects a directory `./storage/tracker/lib/database` to be writable by the tracker process. //! //! By default the tracker uses `SQLite` and the database file name `data.db`. //! -//! You only need the `ssl_certificates` directory in case you are setting up SSL for the HTTP tracker or the tracker API. +//! You only need the `tls` directory in case you are setting up SSL for the HTTP tracker or the tracker API. //! Visit [`HTTP`](crate::servers::http) or [`API`](crate::servers::apis) if you want to know how you can use HTTPS. //! //! ## Install from sources @@ -130,8 +130,8 @@ //! git clone https://github.com/torrust/torrust-tracker.git \ //! && cd torrust-tracker \ //! && cargo build --release \ -//! && mkdir -p ./storage/database \ -//! && mkdir -p ./storage/ssl_certificates +//! && mkdir -p ./storage/tracker/lib/database \ +//! && mkdir -p ./storage/tracker/lib/tls //! ``` //! //! ## Run with docker @@ -142,7 +142,7 @@ //! # Configuration //! //! In order to run the tracker you need to provide the configuration. If you run the tracker without providing the configuration, -//! the tracker will generate the default configuration the first time you run it. It will generate a `config.toml` file with +//! the tracker will generate the default configuration the first time you run it. It will generate a `tracker.toml` file with //! in the root directory. //! //! The default configuration is: @@ -151,7 +151,7 @@ //! log_level = "info" //! mode = "public" //! db_driver = "Sqlite3" -//! db_path = "./storage/database/data.db" +//! db_path = "./storage/tracker/lib/database/sqlite3.db" //! announce_interval = 120 //! min_announce_interval = 120 //! max_peer_timeout = 900 @@ -188,18 +188,18 @@ //! //! For more information about each service and options you can visit the documentation for the [torrust-tracker-configuration crate](https://docs.rs/torrust-tracker-configuration). //! -//! Alternatively to the `config.toml` file you can use one environment variable `TORRUST_TRACKER_CONFIG` to pass the configuration to the tracker: +//! Alternatively to the `tracker.toml` file you can use one environment variable `TORRUST_TRACKER_CONFIG` to pass the configuration to the tracker: //! //! ```text -//! TORRUST_TRACKER_CONFIG=$(cat config.toml) +//! TORRUST_TRACKER_CONFIG=$(cat tracker.toml) //! cargo run //! ``` //! -//! In the previous example you are just setting the env var with the contents of the `config.toml` file. +//! In the previous example you are just setting the env var with the contents of the `tracker.toml` file. //! -//! The env var contains the same data as the `config.toml`. It's particularly useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/tree/develop/docker). +//! The env var contains the same data as the `tracker.toml`. It's particularly useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/tree/develop/docker). //! -//! > NOTE: The `TORRUST_TRACKER_CONFIG` env var has priority over the `config.toml` file. +//! > NOTE: The `TORRUST_TRACKER_CONFIG` env var has priority over the `tracker.toml` file. //! //! # Usage //! diff --git a/src/servers/apis/mod.rs b/src/servers/apis/mod.rs index eb278bf3c..afed9ff12 100644 --- a/src/servers/apis/mod.rs +++ b/src/servers/apis/mod.rs @@ -28,8 +28,8 @@ //! enabled = true //! bind_address = "0.0.0.0:1212" //! ssl_enabled = false -//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -//! ssl_key_path = "./storage/ssl_certificates/localhost.key" +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! //! [http_api.access_tokens] //! admin = "MyAccessToken" @@ -41,7 +41,7 @@ //! When you run the tracker with enabled API, you will see the following message: //! //! ```text -//! Loading configuration from config file ./config.toml +//! Loading configuration from config file ./tracker.toml //! 023-03-28T12:19:24.963054069+01:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized. //! ... //! 023-03-28T12:19:24.964138723+01:00 [torrust_tracker::bootstrap::jobs::tracker_apis][INFO] Starting Torrust APIs server on: http://0.0.0.0:1212 @@ -116,8 +116,8 @@ //! enabled = true //! bind_address = "0.0.0.0:1212" //! ssl_enabled = true -//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -//! ssl_key_path = "./storage/ssl_certificates/localhost.key" +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! //! [http_api.access_tokens] //! admin = "MyAccessToken" diff --git a/src/servers/apis/v1/middlewares/auth.rs b/src/servers/apis/v1/middlewares/auth.rs index 41af09031..3e8f74d0c 100644 --- a/src/servers/apis/v1/middlewares/auth.rs +++ b/src/servers/apis/v1/middlewares/auth.rs @@ -11,7 +11,7 @@ //! The token must be one of the `access_tokens` in the tracker //! [HTTP API configuration](torrust_tracker_configuration::HttpApi). //! -//! The configuration file `config.toml` contains a list of tokens: +//! The configuration file `tracker.toml` contains a list of tokens: //! //! ```toml //! [http_api.access_tokens] diff --git a/src/tracker/databases/driver.rs b/src/tracker/databases/driver.rs index 4ff9314d2..19cb7046e 100644 --- a/src/tracker/databases/driver.rs +++ b/src/tracker/databases/driver.rs @@ -18,7 +18,7 @@ use super::{Builder, Database}; /// use torrust_tracker_primitives::DatabaseDriver; /// /// let db_driver = DatabaseDriver::Sqlite3; -/// let db_path = "./storage/database/data.db".to_string(); +/// let db_path = "./storage/tracker/lib/database/sqlite3.db".to_string(); /// let database = databases::driver::build(&db_driver, &db_path); /// ``` /// diff --git a/src/tracker/mod.rs b/src/tracker/mod.rs index 6823e8fe8..040751e12 100644 --- a/src/tracker/mod.rs +++ b/src/tracker/mod.rs @@ -320,7 +320,7 @@ //! log_level = "debug" //! mode = "public" //! db_driver = "Sqlite3" -//! db_path = "./storage/database/data.db" +//! db_path = "./storage/tracker/lib/database/sqlite3.db" //! announce_interval = 120 //! min_announce_interval = 120 //! max_peer_timeout = 900 diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index b508dfc39..2e24af6b7 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -67,11 +67,12 @@ mod for_all_config_modes { // Vuze (bittorrent client) docs: // https://wiki.vuze.com/w/Announce - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV6}; use std::str::FromStr; use local_ip_address::local_ip; use reqwest::Response; + use tokio::net::TcpListener; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker::tracker::peer; use torrust_tracker_test_helpers::configuration; @@ -594,6 +595,13 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp6_connections_handled_in_statistics() { + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) + .await + .is_err() + { + return; // we cannot bind to a ipv6 socket, so we will skip this test + } + let test_env = running_test_environment::(configuration::ephemeral_ipv6()).await; Client::bind(*test_env.bind_address(), IpAddr::from_str("::1").unwrap()) @@ -651,6 +659,13 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp6_announce_requests_handled_in_statistics() { + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) + .await + .is_err() + { + return; // we cannot bind to a ipv6 socket, so we will skip this test + } + let test_env = running_test_environment::(configuration::ephemeral_ipv6()).await; Client::bind(*test_env.bind_address(), IpAddr::from_str("::1").unwrap()) @@ -830,9 +845,10 @@ mod for_all_config_modes { // Vuze (bittorrent client) docs: // https://wiki.vuze.com/w/Scrape - use std::net::IpAddr; + use std::net::{IpAddr, Ipv6Addr, SocketAddrV6}; use std::str::FromStr; + use tokio::net::TcpListener; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker::tracker::peer; use torrust_tracker_test_helpers::configuration; @@ -1027,6 +1043,13 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_ot_tcp6_scrape_requests_handled_in_statistics() { + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) + .await + .is_err() + { + return; // we cannot bind to a ipv6 socket, so we will skip this test + } + let test_env = running_test_environment::(configuration::ephemeral_ipv6()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); From 5bea92d5c62ed4bd38d1033f5ed9d4393cf4a8b6 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 6 Sep 2023 13:16:21 +0200 Subject: [PATCH 0059/1297] ci: use coverage upload token --- .github/workflows/coverage.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 08b869327..a6d639e21 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -54,6 +54,7 @@ jobs: name: Upload Coverage Report uses: codecov/codecov-action@v3 with: + token: ${{ secrets.CODECOV_TOKEN }} files: ${{ steps.coverage.outputs.report }} verbose: true fail_ci_if_error: true From 39fd63d54f671e4e95067e08fec647c4ca9d2f49 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 6 Sep 2023 16:58:53 +0200 Subject: [PATCH 0060/1297] dev: update cargo toml files --- Cargo.lock | 18 +++++++------- Cargo.toml | 24 +++++++++++++++---- contrib/bencode/Cargo.toml | 25 ++++++++++---------- contrib/bencode/benches/bencode_benchmark.rs | 2 +- contrib/bencode/src/lib.rs | 12 +++++----- contrib/bencode/test/mod.rs | 2 +- packages/configuration/Cargo.toml | 10 +++++++- packages/located-error/Cargo.toml | 11 +++++++-- packages/primitives/Cargo.toml | 10 +++++++- packages/test-helpers/Cargo.toml | 13 +++++++--- src/servers/http/v1/responses/announce.rs | 2 +- src/servers/http/v1/responses/scrape.rs | 2 +- 12 files changed, 88 insertions(+), 43 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0b7c9d0d4..fae2d9dd9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -258,14 +258,6 @@ version = "0.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "414dcefbc63d77c526a76b3afcf6fbb9b5e2791c19c3aa2297733208750c6e53" -[[package]] -name = "bencode" -version = "1.0.0-alpha.1" -dependencies = [ - "criterion", - "error-chain", -] - [[package]] name = "bigdecimal" version = "0.3.1" @@ -3103,7 +3095,6 @@ dependencies = [ "axum", "axum-client-ip", "axum-server", - "bencode", "binascii", "chrono", "config", @@ -3133,6 +3124,7 @@ dependencies = [ "thiserror", "tokio", "torrust-tracker-configuration", + "torrust-tracker-contrib-bencode", "torrust-tracker-located-error", "torrust-tracker-primitives", "torrust-tracker-test-helpers", @@ -3155,6 +3147,14 @@ dependencies = [ "uuid", ] +[[package]] +name = "torrust-tracker-contrib-bencode" +version = "3.0.0-alpha.4" +dependencies = [ + "criterion", + "error-chain", +] + [[package]] name = "torrust-tracker-located-error" version = "3.0.0-alpha.4" diff --git a/Cargo.toml b/Cargo.toml index 9c94ea10d..17c1cbbb7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,21 +1,37 @@ [package] name = "torrust-tracker" -description = "A feature rich BitTorrent tracker." -license-file.workspace = true +readme = "README.md" + authors.workspace = true +description.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +keywords.workspace = true +license-file.workspace = true +publish.workspace = true repository.workspace = true +rust-version.workspace = true version.workspace = true + [workspace.package] -license-file = "COPYRIGHT" authors = [ "Nautilus Cyberneering , Mick van Dijke ", ] +categories = ["network-programming", "web-programming"] +description = "A feature rich BitTorrent tracker." +documentation = "https://docs.rs/crate/torrust-tracker/" edition = "2021" +homepage = "https://torrust.com/" +keywords = ["bittorrent", "tracker", "file-sharing", "peer-to-peer", "torrent"] +license-file = "COPYRIGHT" +publish = true repository = "https://github.com/torrust/torrust-tracker" +rust-version = "1.72" version = "3.0.0-alpha.4" + [dependencies] tokio = { version = "1.29", features = [ "rt-multi-thread", @@ -50,7 +66,7 @@ axum = "0.6.20" axum-server = { version = "0.5", features = ["tls-rustls"] } axum-client-ip = "0.4.1" tower-http = { version = "0.4.3", features = ["compression-full"] } -bencode = { version = "1.0.0-alpha.1", path = "contrib/bencode" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.4", path = "contrib/bencode"} torrust-tracker-primitives = { version = "3.0.0-alpha.4", path = "packages/primitives" } torrust-tracker-configuration = { version = "3.0.0-alpha.4", path = "packages/configuration" } torrust-tracker-located-error = { version = "3.0.0-alpha.4", path = "packages/located-error" } diff --git a/contrib/bencode/Cargo.toml b/contrib/bencode/Cargo.toml index 8334e270d..2aed18409 100644 --- a/contrib/bencode/Cargo.toml +++ b/contrib/bencode/Cargo.toml @@ -1,22 +1,21 @@ [package] -name = "bencode" -description = "Efficient decoding and encoding for bencode." -keywords = ["bencode"] +name = "torrust-tracker-contrib-bencode" +description = "(contrib) Efficient decoding and encoding for bencode." +keywords = ["library", "contrib", "bencode"] readme = "README.md" - authors = [ "Nautilus Cyberneering , Andrew ", ] -categories = ["network-programming", "web-programming"] -documentation = "https://github.com/torrust/bittorrent-infrastructure-project" -edition = "2021" -homepage = "https://github.com/torrust/bittorrent-infrastructure-project" -license = "Apache-2.0" -publish = false # until we decide where to publish. repository = "https://github.com/torrust/bittorrent-infrastructure-project" -rust-version = "1.71" -version = "1.0.0-alpha.1" +license = "Apache-2.0" + +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +publish.workspace = true +rust-version.workspace = true +version.workspace = true [dependencies] @@ -31,4 +30,4 @@ path = "test/mod.rs" [[bench]] name = "bencode_benchmark" -harness = false \ No newline at end of file +harness = false diff --git a/contrib/bencode/benches/bencode_benchmark.rs b/contrib/bencode/benches/bencode_benchmark.rs index 729197d8a..b79bb0999 100644 --- a/contrib/bencode/benches/bencode_benchmark.rs +++ b/contrib/bencode/benches/bencode_benchmark.rs @@ -1,5 +1,5 @@ -use bencode::{BDecodeOpt, BencodeRef}; use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use torrust_tracker_contrib_bencode::{BDecodeOpt, BencodeRef}; const B_NESTED_LISTS: &[u8; 100] = b"lllllllllllllllllllllllllllllllllllllllllllllllllleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; // cspell:disable-line diff --git a/contrib/bencode/src/lib.rs b/contrib/bencode/src/lib.rs index 103a3c371..78e113b66 100644 --- a/contrib/bencode/src/lib.rs +++ b/contrib/bencode/src/lib.rs @@ -85,8 +85,8 @@ const BYTE_LEN_END: u8 = b':'; macro_rules! ben_map { ( $($key:expr => $val:expr),* ) => { { - use bencode::{BMutAccess, BencodeMut}; - use bencode::inner::BCowConvert; + use $crate::{BMutAccess, BencodeMut}; + use $crate::inner::BCowConvert; let mut bencode_map = BencodeMut::new_dict(); { @@ -106,7 +106,7 @@ macro_rules! ben_map { macro_rules! ben_list { ( $($ben:expr),* ) => { { - use bencode::{BencodeMut, BMutAccess}; + use $crate::{BencodeMut, BMutAccess}; let mut bencode_list = BencodeMut::new_list(); { @@ -125,8 +125,8 @@ macro_rules! ben_list { #[macro_export] macro_rules! ben_bytes { ( $ben:expr ) => {{ - use bencode::inner::BCowConvert; - use bencode::BencodeMut; + use $crate::inner::BCowConvert; + use $crate::BencodeMut; BencodeMut::new_bytes(BCowConvert::convert($ben)) }}; @@ -136,7 +136,7 @@ macro_rules! ben_bytes { #[macro_export] macro_rules! ben_int { ( $ben:expr ) => {{ - use bencode::BencodeMut; + use $crate::BencodeMut; BencodeMut::new_int($ben) }}; diff --git a/contrib/bencode/test/mod.rs b/contrib/bencode/test/mod.rs index c1454967d..14606c175 100644 --- a/contrib/bencode/test/mod.rs +++ b/contrib/bencode/test/mod.rs @@ -1,4 +1,4 @@ -use bencode::{ben_bytes, ben_int, ben_list, ben_map}; +use torrust_tracker_contrib_bencode::{ben_bytes, ben_int, ben_list, ben_map}; #[test] fn positive_ben_map_macro() { diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index e3ca1d932..93b45c0a7 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -1,12 +1,20 @@ [package] name = "torrust-tracker-configuration" description = "A library to provide configuration to the Torrust Tracker." -license-file.workspace = true +keywords = ["library", "config", "settings"] +readme = "README.md" + authors.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +license-file.workspace = true +publish.workspace = true repository.workspace = true +rust-version.workspace = true version.workspace = true + [dependencies] serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index 19707e7e9..ea0b1639a 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -1,15 +1,22 @@ [package] name = "torrust-tracker-located-error" description = "A library to provide error decorator with the location and the source of the original error." -license-file.workspace = true +keywords = ["library", "helper", "errors"] +readme = "README.md" + authors.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +license-file.workspace = true +publish.workspace = true repository.workspace = true +rust-version.workspace = true version.workspace = true + [dependencies] log = { version = "0.4", features = ["release_max_level_info"] } [dev-dependencies] thiserror = "1.0" - diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index 7576e06d8..9eb092e1c 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -1,12 +1,20 @@ [package] name = "torrust-tracker-primitives" description = "A library with the primitive types shared by the Torrust tracker packages." -license-file.workspace = true +keywords = ["library", "api", "primitives"] +readme = "README.md" + authors.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +license-file.workspace = true +publish.workspace = true repository.workspace = true +rust-version.workspace = true version.workspace = true + [dependencies] serde = { version = "1.0", features = ["derive"] } derive_more = "0.99" diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 4e6c70e66..91831399c 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -1,14 +1,21 @@ [package] name = "torrust-tracker-test-helpers" description = "A library providing helpers for testing the Torrust tracker." -license-file.workspace = true +keywords = ["library", "helper", "testing"] +readme = "README.md" + authors.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +license-file.workspace = true +publish.workspace = true repository.workspace = true +rust-version.workspace = true version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.4", path = "../configuration"} -torrust-tracker-primitives = { version = "3.0.0-alpha.4", path = "../primitives"} +torrust-tracker-configuration = { version = "3.0.0-alpha.4", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.4", path = "../primitives" } diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index e7b64522c..3596275f4 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -7,9 +7,9 @@ use std::panic::Location; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; -use bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; use serde::{self, Deserialize, Serialize}; use thiserror::Error; +use torrust_tracker_contrib_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; use crate::servers::http::v1::responses; use crate::tracker::{self, AnnounceData}; diff --git a/src/servers/http/v1/responses/scrape.rs b/src/servers/http/v1/responses/scrape.rs index c2f099597..9cd88b9ab 100644 --- a/src/servers/http/v1/responses/scrape.rs +++ b/src/servers/http/v1/responses/scrape.rs @@ -5,7 +5,7 @@ use std::borrow::Cow; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; -use bencode::{ben_int, ben_map, BMutAccess}; +use torrust_tracker_contrib_bencode::{ben_int, ben_map, BMutAccess}; use crate::tracker::ScrapeData; From 5160632b04ea11dd916aaecc315bb826bd4c009a Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 6 Sep 2023 16:59:09 +0200 Subject: [PATCH 0061/1297] dev: update deployment scripts --- .github/workflows/container.yaml | 16 +++-- .github/workflows/deployment.yaml | 81 +++++++++++++++++++++++++ .github/workflows/publish_crate.yml | 57 ----------------- .github/workflows/testing.yaml | 2 +- cSpell.json | 3 +- contrib/bencode/src/reference/decode.rs | 2 - 6 files changed, 96 insertions(+), 65 deletions(-) create mode 100644 .github/workflows/deployment.yaml delete mode 100644 .github/workflows/publish_crate.yml diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index 27a2dc93c..2064d0ee4 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -2,8 +2,11 @@ name: Container on: push: - tags-ignore: - - "!v*" + branches: + - "develop" + - "main" + tags: + - "v*" pull_request: branches: - "develop" @@ -17,6 +20,10 @@ jobs: name: Test (Docker) runs-on: ubuntu-latest + strategy: + matrix: + target: [debug, release] + steps: - id: setup name: Setup Toolchain @@ -29,9 +36,10 @@ jobs: file: ./Containerfile push: false load: true + target: ${{ matrix.target }} tags: torrust-tracker:local cache-from: type=gha - cache-to: type=gha,mode=max + cache-to: type=gha - id: inspect name: Inspect @@ -122,4 +130,4 @@ jobs: tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha - cache-to: type=gha,mode=max + cache-to: type=gha diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml new file mode 100644 index 000000000..6b6a64975 --- /dev/null +++ b/.github/workflows/deployment.yaml @@ -0,0 +1,81 @@ +name: Deployment + +on: + push: + tags: + - "v*" + +jobs: + secrets: + name: Secrets + needs: context + environment: dockerhub-torrust + if: needs.context.outputs.continue == 'true' + runs-on: ubuntu-latest + + outputs: + continue: ${{ steps.check.outputs.continue }} + + steps: + - id: check + name: Check + env: + CRATES_TOKEN: "${{ secrets.CRATES_TOKEN }}" + if: "${{ env.CRATES_TOKEN != '' }}" + run: echo "continue=true" >> $GITHUB_OUTPUT + + test: + name: Test + needs: secrets + if: needs.secrets.outputs.continue == 'true' + runs-on: ubuntu-latest + + strategy: + matrix: + toolchain: [stable, nightly] + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v3 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + + - id: test + name: Run Unit Tests + run: cargo test --tests --benches --examples --workspace --all-targets --all-features + + publish: + name: Publish + environment: crates-io-torrust + needs: test + if: needs.secrets.outputs.continue == 'true' + runs-on: ubuntu-latest + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v3 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: stable + + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_TOKEN }} + + - id: publish + name: Publish Crates + run: | + cargo publish -p torrust-tracker-contrib-bencode + cargo publish -p torrust-tracker-located-error + cargo publish -p torrust-tracker-primitives + cargo publish -p torrust-tracker-configuration + cargo publish -p torrust-tracker-test-helpers + cargo publish -p torrust-tracker diff --git a/.github/workflows/publish_crate.yml b/.github/workflows/publish_crate.yml deleted file mode 100644 index 4d5d0772e..000000000 --- a/.github/workflows/publish_crate.yml +++ /dev/null @@ -1,57 +0,0 @@ -name: Publish crate - -on: - push: - tags: - - "v*" - -jobs: - check-secret: - runs-on: ubuntu-latest - environment: crates-io-torrust - outputs: - publish: ${{ steps.check.outputs.publish }} - steps: - - id: check - env: - CRATES_TOKEN: "${{ secrets.CRATES_TOKEN }}" - if: "${{ env.CRATES_TOKEN != '' }}" - run: echo "publish=true" >> $GITHUB_OUTPUT - - test: - needs: check-secret - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - components: llvm-tools-preview - - uses: Swatinem/rust-cache@v2 - - name: Run Tests - run: cargo test - - publish: - needs: test - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - environment: crates-io-torrust - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Install stable toolchain - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - - - name: Publish workspace packages - run: | - cargo publish -p torrust-tracker-located-error - cargo publish -p torrust-tracker-primitives - cargo publish -p torrust-tracker-configuration - cargo publish -p torrust-tracker-test-helpers - cargo publish -p torrust-tracker - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_TOKEN }} diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index c1f85a90b..2fa52f5a4 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -50,7 +50,7 @@ jobs: name: Setup Toolchain uses: dtolnay/rust-toolchain@stable with: - toolchain: nightly + toolchain: ${{ matrix.toolchain }} components: clippy - id: cache diff --git a/cSpell.json b/cSpell.json index fc9db42b7..e4ac1d90b 100644 --- a/cSpell.json +++ b/cSpell.json @@ -33,6 +33,7 @@ "curr", "Cyberneering", "datetime", + "Dijke", "distroless", "dockerhub", "downloadedi", @@ -133,4 +134,4 @@ "shellscript", "toml" ] -} \ No newline at end of file +} diff --git a/contrib/bencode/src/reference/decode.rs b/contrib/bencode/src/reference/decode.rs index d18dffda0..d2aa180f8 100644 --- a/contrib/bencode/src/reference/decode.rs +++ b/contrib/bencode/src/reference/decode.rs @@ -1,5 +1,3 @@ -#![allow(clippy::should_panic_without_expect)] - use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::str::{self}; From c7453bfb9f9915421ab0fc0fe4fd548f8f682215 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 6 Sep 2023 16:31:08 +0000 Subject: [PATCH 0062/1297] chore(deps): bump actions/checkout from 3 to 4 Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/container.yaml | 2 +- .github/workflows/coverage.yaml | 2 +- .github/workflows/deployment.yaml | 4 ++-- .github/workflows/testing.yaml | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index 2064d0ee4..da38db71f 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -47,7 +47,7 @@ jobs: - id: checkout name: Checkout Repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 - id: compose name: Compose diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index a6d639e21..6a99fb11a 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -19,7 +19,7 @@ jobs: steps: - id: checkout name: Checkout Repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 - id: setup name: Setup Toolchain diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 6b6a64975..87bc61484 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -37,7 +37,7 @@ jobs: steps: - id: checkout name: Checkout Repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 - id: setup name: Setup Toolchain @@ -59,7 +59,7 @@ jobs: steps: - id: checkout name: Checkout Repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 - id: setup name: Setup Toolchain diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 2fa52f5a4..f138a95cc 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -15,7 +15,7 @@ jobs: steps: - id: checkout name: Checkout Repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 - id: setup name: Setup Toolchain @@ -44,7 +44,7 @@ jobs: steps: - id: checkout name: Checkout Repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 - id: setup name: Setup Toolchain @@ -81,7 +81,7 @@ jobs: steps: - id: checkout name: Checkout Repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 - id: setup name: Setup Toolchain From 509d0456c72388850e0246c39c4a606d7f5e5d38 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 6 Sep 2023 17:16:01 +0000 Subject: [PATCH 0063/1297] chore(deps): bump r2d2_mysql from 23.0.0 to 24.0.0 Bumps [r2d2_mysql](https://github.com/outersky/r2d2-mysql) from 23.0.0 to 24.0.0. - [Release notes](https://github.com/outersky/r2d2-mysql/releases) - [Changelog](https://github.com/outersky/r2d2-mysql/blob/master/CHANGELOG.md) - [Commits](https://github.com/outersky/r2d2-mysql/commits) --- updated-dependencies: - dependency-name: r2d2_mysql dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- Cargo.lock | 101 ++++++++++++++++++++++++++++++++++++++++++++--------- Cargo.toml | 2 +- 2 files changed, 86 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fae2d9dd9..0ab5ffc45 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -345,7 +345,7 @@ checksum = "0754613691538d51f329cce9af41d7b7ca150bc973056f1156611489475f54f7" dependencies = [ "borsh-derive-internal", "borsh-schema-derive-internal", - "proc-macro-crate", + "proc-macro-crate 0.1.5", "proc-macro2", "syn 1.0.109", ] @@ -1210,6 +1210,12 @@ dependencies = [ "hashbrown 0.14.0", ] +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + [[package]] name = "hermit-abi" version = "0.3.2" @@ -1596,11 +1602,11 @@ checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" [[package]] name = "lru" -version = "0.8.1" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6e8aaa3f231bb4bd57b84b2d5dc3ae7f350265df8aa96492e0bc394a1571909" +checksum = "718e8fae447df0c7e1ba7f5189829e63fd536945c8988d61444c19039f16b670" dependencies = [ - "hashbrown 0.12.3", + "hashbrown 0.13.2", ] [[package]] @@ -1694,9 +1700,9 @@ dependencies = [ [[package]] name = "mysql" -version = "23.0.1" +version = "24.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f11339ca5c251941805d51362a07823605a80586ced92914ab7de84fba813f" +checksum = "cfe2babc5f5b354eab9c0a0e40da3e69c4d77421c8b9b6ee03f97acc75bd7955" dependencies = [ "bufstream", "bytes", @@ -1713,21 +1719,39 @@ dependencies = [ "percent-encoding", "serde", "serde_json", - "socket2 0.4.9", + "socket2 0.5.3", "twox-hash", "url", ] +[[package]] +name = "mysql-common-derive" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56b0d8a0db9bf6d2213e11f2c701cb91387b0614361625ab7b9743b41aa4938f" +dependencies = [ + "darling", + "heck", + "num-bigint", + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.31", + "termcolor", + "thiserror", +] + [[package]] name = "mysql_common" -version = "0.29.2" +version = "0.30.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9006c95034ccf7b903d955f210469119f6c3477fc9c9e7a7845ce38a3e665c2a" +checksum = "57349d5a326b437989b6ee4dc8f2f34b0cc131202748414712a8e7d98952fc8c" dependencies = [ - "base64 0.13.1", + "base64 0.21.3", "bigdecimal", "bindgen", - "bitflags 1.3.2", + "bitflags 2.4.0", "bitvec", "byteorder", "bytes", @@ -1738,6 +1762,7 @@ dependencies = [ "frunk", "lazy_static", "lexical", + "mysql-common-derive", "num-bigint", "num-traits", "rand", @@ -1991,11 +2016,12 @@ checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" [[package]] name = "pem" -version = "1.1.1" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8835c273a76a90455d7344889b0964598e3316e2a79ede8e36f16bdcf2228b8" +checksum = "6b13fe415cdf3c8e44518e18a7c95a13431d9bdf6d15367d82b23c377fdd441a" dependencies = [ - "base64 0.13.1", + "base64 0.21.3", + "serde", ] [[package]] @@ -2160,6 +2186,40 @@ dependencies = [ "toml 0.5.11", ] +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + [[package]] name = "proc-macro2" version = "1.0.66" @@ -2211,9 +2271,9 @@ dependencies = [ [[package]] name = "r2d2_mysql" -version = "23.0.0" +version = "24.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9733d738ce65959a744f387bae69aa690a867e18d48e5486b171c47bc7b0c575" +checksum = "3fe5127e6c21971cdb9580f2f54cbe6d9c2226eb861036c3ca6d390c25f52574" dependencies = [ "mysql", "r2d2", @@ -2901,6 +2961,15 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "termcolor" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" +dependencies = [ + "winapi-util", +] + [[package]] name = "termtree" version = "0.4.1" diff --git a/Cargo.toml b/Cargo.toml index 17c1cbbb7..30b44bf85 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,7 +53,7 @@ log = { version = "0.4", features = ["release_max_level_info"] } fern = "0.6" chrono = { version = "0.4.24", default-features = false, features = ["clock"] } r2d2 = "0.8" -r2d2_mysql = "23.0" +r2d2_mysql = "24.0" r2d2_sqlite = { version = "0.22", features = ["bundled"] } rand = "0.8" derive_more = "0.99" From e3e111bd40baccfbc3e3ef113b38d7da6102c326 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 6 Sep 2023 21:00:18 +0200 Subject: [PATCH 0064/1297] docs: update readme --- README.md | 202 ++++++++++++++++++++++++++++++++-------------------- cSpell.json | 1 + 2 files changed, 125 insertions(+), 78 deletions(-) diff --git a/README.md b/README.md index 832af0d85..2f35e9017 100644 --- a/README.md +++ b/README.md @@ -1,95 +1,143 @@ # Torrust Tracker -[![container_wf_b]][container_wf] [![coverage_wf_b]][coverage_wf] [![testing_wf_b]][testing_wf] +[![container_wf_b]][container_wf] [![coverage_wf_b]][coverage_wf] [![deployment_wf_b]][deployment_wf] [![testing_wf_b]][testing_wf] -Torrust Tracker is a lightweight but incredibly high-performance and feature-rich BitTorrent tracker written in [Rust Language][rust]. +__Torrust Tracker__, is a [BitTorrent][bittorrent] Tracker (a service that matchmakes peers and collects statistics) written in [Rust Language][rust] and [axum] (a modern web application framework). ___This tracker aims to be respectful to established standards, (both [formal][BEP 00] and [otherwise][torrent_source_felid]).___ -It aims to provide a reliable and efficient solution for serving torrents to a vast number of peers while maintaining a high level of performance, robustness, extensibility, security, usability and with community-driven development. +> This is a [Torrust][torrust] project and is in active development. It is community supported as well as sponsored by [Nautilus Cyberneering][nautilus]. -_We have a [container guide][containers.md] to get started with Docker or Podman_ +- _We have a [container guide][containers.md] for those who wish to get started with __Docker__ or __Podman___ ## Key Features -* [x] Multiple UDP server and HTTP(S) server blocks for socket binding are possible. -* [x] Full IPv4 and IPv6 support for both UDP and HTTP(S). -* [x] Private & Whitelisted mode. -* [x] Built-in API. -* [x] Torrent whitelisting. -* [x] Peer authentication using time-bound keys. -* [x] [newTrackon][newtrackon] check is supported for both HTTP and UDP, where IPv4 and IPv6 are properly handled. -* [x] SQLite3 and MySQL persistence, loading and saving of the torrent hashes and downloads completed count. -* [x] Comprehensive documentation. -* [x] A complete suite of tests. See our [code coverage report][coverage]. +- [x] High Quality and Modern Rust Codebase. +- [x] [Documentation] Generated from Code Comments. +- [x] [Comprehensive Suit][coverage] of Unit and Functional Tests. +- [x] Good Performance in Busy Conditions. +- [x] Support for `UDP`, `HTTP`, and `TLS` Sockets. +- [x] Native `IPv4` and `IPv6` support. +- [x] Private & Whitelisted mode. +- [x] Tracker Management API. +- [x] Support [newTrackon][newtrackon] checks. +- [x] Persistent `SQLite3` or `MySQL` Databases. -## Implemented BEPs +## Implemented BitTorrent Enhancement Proposals (BEPs) +> _[Learn more about BitTorrent Enhancement Proposals][BEP 00]_ -* [BEP 03]: The BitTorrent Protocol. -* [BEP 07]: IPv6 Support. -* [BEP 15]: UDP Tracker Protocol for BitTorrent. -* [BEP 23]: Tracker Returns Compact Peer Lists. -* [BEP 27]: Private Torrents. -* [BEP 48]: Tracker Protocol Extension: Scrape. +- [BEP 03] : The BitTorrent Protocol. +- [BEP 07] : IPv6 Support. +- [BEP 15] : UDP Tracker Protocol for BitTorrent. +- [BEP 23] : Tracker Returns Compact Peer Lists. +- [BEP 27] : Private Torrents. +- [BEP 48] : Tracker Protocol Extension: Scrape. ## Getting Started -Requirements: +### Container Version -* Rust Stable `1.68` -* You might have problems compiling with a machine or docker container with low resources. It has been tested with docker containers with 6 CPUs, 7.5 GM of memory and 2GB of swap. +The Torrust Tracker is [deployed to DockerHub][dockerhub_torrust_tracker], you can run a demo immediately with the following commands: -You can follow the [documentation] to install and use Torrust Tracker in different ways, but if you want to give it a quick try, you can use the following commands: +#### Docker: -```s -git clone https://github.com/torrust/torrust-tracker.git \ - && cd torrust-tracker \ - && cargo build --release \ - && mkdir -p ./storage/tracker/lib/database \ - && mkdir -p ./storage/tracker/lib/tls +```sh +docker run -it torrust/tracker:develop ``` +> Please read our [container guide][containers.md] for more information. -### Configuration +#### Podman: -The [default configuration folder: `/share/default/config`][share.default.config]: +```sh +podman run -it torrust/tracker:develop +``` +> Please read our [container guide][containers.md] for more information. + +### Development Version + +- Please assure you have the ___[latest stable (or nightly) version of rust][rust]___. +- Please assure that you computer has enough ram. ___Recommended 16GB.___ + +#### Checkout, Test and Run: + +```sh +# Checkout repository into a new folder: +git clone https://github.com/torrust/torrust-tracker.git + +# Change into directory and create a empty database file: +cd torrust-tracker +mkdir -p ./storage/tracker/lib/database/ +touch ./storage/tracker/lib/database/sqlite3.db + +# Check all tests in application: +cargo test --tests --benches --examples --workspace --all-targets --all-features + +# Run the tracker: +cargo run +``` +#### Customization: -- Contains the [development default][src.bootstrap.config.default] i.e: [`tracker.development.sqlite3.toml`][tracker.development.sqlite3.toml]. +```sh +# Copy the default configuration into the standard location: +mkdir -p ./storage/tracker/etc/ +cp ./share/default/config/tracker.development.sqlite3.toml ./storage/tracker/etc/tracker.toml -- Also contains the container defaults: [`sqlite3`][tracker.container.sqlite3.toml] and [`mysql`][tracker.container.mysql.toml]. +# Customize the tracker configuration (for example): +vim ./storage/tracker/etc/tracker.toml -To override the default configuration there is two options: +# Run the tracker with the updated configuration: +TORRUST_TRACKER_PATH_CONFIG="./storage/tracker/etc/tracker.toml" cargo run +``` -- Configure a different configuration path by setting the [`TORRUST_TRACKER_PATH_CONFIG`][src.bootstrap.config.path.config] environmental variable. +_Optionally, you may choose to supply the entire configuration as an environmental variable:_ -- Supply the entire configuration via the [`TORRUST_TRACKER_CONFIG`][src.bootstrap.config.config] environmental variable. +```sh +# Use a configuration supplied on an environmental variable: +TORRUST_TRACKER_CONFIG=$(cat "./storage/tracker/etc/tracker.toml") cargo run +``` +_For deployment you __should__ override the `api_admin_token` by using an environmental variable:_ -> NOTE: It is recommended for production you override the `api admin token` by placing your secret in the [`ENV_VAR_API_ADMIN_TOKEN`][src.bootstrap.config.admin.token] environmental variable. +```sh +# Generate a Secret Token: +gpg --armor --gen-random 1 10 | tee ./storage/tracker/lib/tracker_api_admin_token.secret +chmod go-rwx ./storage/tracker/lib/tracker_api_admin_token.secret +# Override secret in configuration using an environmental variable: +TORRUST_TRACKER_CONFIG=$(cat "./storage/tracker/etc/tracker.toml") \ + TORRUST_TRACKER_API_ADMIN_TOKEN=$(cat "./storage/tracker/lib/tracker_api_admin_token.secret") \ + cargo run +``` + +> Please view our [crate documentation][documentation] for more detailed instructions. ### Services -After running the tracker these services will be available (as defined in the default configuration): +The following services are provided by the default configuration: + +- UDP _(tracker)_ + - `udp://127.0.0.1:6969/announce`. +- HTTP _(tracker)_ + - `http://127.0.0.1:6969/announce`. +- API _(management)_ + - `http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken`. -* UDP tracker: `udp://127.0.0.1:6969/announce`. -* HTTP tracker: `http://127.0.0.1:6969/announce`. -* API: `http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken`. ## Documentation -* [Crate documentation] -* [API `v1`] -* [HTTP Tracker] -* [UDP Tracker] +- [Management API (Version 1)][api] +- [Tracker (HTTP/TLS)][http] +- [Tracker (UDP)][udp] ## Contributing +This is an open-source community supported project.
We welcome contributions from the community! -How can you contribute? +__How can you contribute?__ -* Bug reports and feature requests. -* Code contributions. You can start by looking at the issues labeled "[good first issues]". -* Documentation improvements. Check the [documentation] and [API documentation] for typos, errors, or missing information. -* Participation in the community. You can help by answering questions in the [discussions]. +- Bug reports and feature requests. +- Code contributions. You can start by looking at the issues labeled "[good first issues]". +- Documentation improvements. Check the [documentation] and [API documentation] for typos, errors, or missing information. +- Participation in the community. You can help by answering questions in the [discussions]. ## License @@ -101,41 +149,39 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D -[container_wf]: https://github.com/torrust/torrust-tracker/actions/workflows/container.yaml -[container_wf_b]: https://github.com/torrust/torrust-tracker/actions/workflows/container.yaml/badge.svg -[coverage_wf]: https://github.com/torrust/torrust-tracker/actions/workflows/coverage.yaml -[coverage_wf_b]: https://github.com/torrust/torrust-tracker/actions/workflows/coverage.yaml/badge.svg -[testing_wf]: https://github.com/torrust/torrust-tracker/actions/workflows/testing.yaml -[testing_wf_b]: https://github.com/torrust/torrust-tracker/actions/workflows/testing.yaml/badge.svg +[container_wf]: ../../actions/workflows/container.yaml +[container_wf_b]: ../../actions/workflows/container.yaml/badge.svg +[coverage_wf]: ../../actions/workflows/coverage.yaml +[coverage_wf_b]: ../../actions/workflows/coverage.yaml/badge.svg +[deployment_wf]: ../../actions/workflows/deployment.yaml +[deployment_wf_b]: ../../actions/workflows/deployment.yaml/badge.svg +[testing_wf]: ../../actions/workflows/testing.yaml +[testing_wf_b]: ../../actions/workflows/testing.yaml/badge.svg +[bittorrent]: http://bittorrent.org/ [rust]: https://www.rust-lang.org/ +[axum]: https://github.com/tokio-rs/axum [newtrackon]: https://newtrackon.com/ [coverage]: https://app.codecov.io/gh/torrust/torrust-tracker +[torrust]: https://torrust.com/ +[dockerhub_torrust_tracker]: https://hub.docker.com/r/torrust/tracker/tags + +[torrent_source_felid]: https://github.com/qbittorrent/qBittorrent/discussions/19406 + +[BEP 00]: https://www.bittorrent.org/beps/bep_0000.html [BEP 03]: https://www.bittorrent.org/beps/bep_0003.html [BEP 07]: https://www.bittorrent.org/beps/bep_0007.html -[BEP 15]: http://www.bittorrent.org/beps/bep_0015.html -[BEP 23]: http://bittorrent.org/beps/bep_0023.html -[BEP 27]: http://bittorrent.org/beps/bep_0027.html -[BEP 48]: http://bittorrent.org/beps/bep_0048.html +[BEP 15]: https://www.bittorrent.org/beps/bep_0015.html +[BEP 23]: https://www.bittorrent.org/beps/bep_0023.html +[BEP 27]: https://www.bittorrent.org/beps/bep_0027.html +[BEP 48]: https://www.bittorrent.org/beps/bep_0048.html [containers.md]: ./docs/containers.md -[share.default.config]: ./share/default/config/ -[tracker.development.sqlite3.toml]: ./share/default/config/tracker.development.sqlite3.toml -[src.bootstrap.config.default]: ./src/bootstrap/config.rs#L18 -[tracker.container.sqlite3.toml]: ./share/default/config/tracker.container.sqlite3.toml -[tracker.container.mysql.toml]: ./share/default/config/tracker.container.mysql.toml -[share.container.entry_script_sh.default]: ./share/container/entry_script_sh#L10 - -[src.bootstrap.config.path.config]: ./src/bootstrap/config.rs#L15 -[src.bootstrap.config.config]: ./src/bootstrap/config.rs#L11 -[src.bootstrap.config.admin.token]: ./src/bootstrap/config.rs#L12 - -[Crate documentation]: https://docs.rs/torrust-tracker/ -[API `v1`]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/apis/v1 -[HTTP Tracker]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/http -[UDP Tracker]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ @@ -144,7 +190,7 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [COPYRIGHT]: ./COPYRIGHT -[nautilus]: https://nautilus-cyberneering.de/ +[nautilus]: https://github.com/orgs/Nautilus-Cyberneering/ [Dutch Bits]: https://dutchbits.nl [Naim A.]: https://github.com/naim94a/udpt [greatest-ape]: https://github.com/greatest-ape/aquatic diff --git a/cSpell.json b/cSpell.json index e4ac1d90b..a02a9b8e8 100644 --- a/cSpell.json +++ b/cSpell.json @@ -63,6 +63,7 @@ "libz", "LOGNAME", "Lphant", + "matchmakes", "metainfo", "middlewares", "mockall", From 2b5b16875c7041ccd1662aa6156a119bf95a9434 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 7 Sep 2023 09:52:04 +0200 Subject: [PATCH 0065/1297] fix: deployment workflow bugfix --- .github/workflows/deployment.yaml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 87bc61484..73c024143 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -8,9 +8,7 @@ on: jobs: secrets: name: Secrets - needs: context environment: dockerhub-torrust - if: needs.context.outputs.continue == 'true' runs-on: ubuntu-latest outputs: From 18ca78fad6a89eab90d248b038fcf7100c5a41db Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 7 Sep 2023 14:49:01 +0200 Subject: [PATCH 0066/1297] dev: vairous fixes --- .github/workflows/container.yaml | 16 ++++++++++------ docs/containers.md | 6 ++++-- share/container/message | 2 ++ 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index da38db71f..86ee8692d 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -65,11 +65,15 @@ jobs: - id: check name: Check Context run: | - if [[ "${{ github.event_name }}" == "push" && ( "${{ github.ref }}" == "refs/heads/main" || "${{ github.ref }}" == "refs/heads/develop" || "${{ github.ref }}" == "refs/heads/docker" ) ]] || - [[ "${{ github.event_name }}" == "push" && "${{ github.ref }}" =~ ^refs/tags/v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - if [[ "${{ github.repository }}" == "torrust/torrust-tracker" ]]; then - echo "Context is torrust/torrust-tracker, and push is: main, develop, docker, or a tag of v*.*.*" - echo "continue=true" >> $GITHUB_OUTPUT + if [[ "${{ github.repository }}" == "torrust/torrust-tracker" ]]; then + if [[ "${{ github.event_name }}" == "push" ]]; then + if [[ "${{ github.ref }}" == "refs/heads/main" || + "${{ github.ref }}" == "refs/heads/develop" || + "${{ github.ref }}" =~ ^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$ ]]; then + + echo "Context is torrust/torrust-tracker, and push is: main, develop, docker, or a tag with a semantic version" + echo "continue=true" >> $GITHUB_OUTPUT + fi fi fi @@ -126,7 +130,7 @@ jobs: uses: docker/build-push-action@v4 with: file: ./Containerfile - push: ${{ github.event_name != 'pull_request' }} + push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha diff --git a/docs/containers.md b/docs/containers.md index b9aa05a7a..dcf281e6e 100644 --- a/docs/containers.md +++ b/docs/containers.md @@ -196,7 +196,7 @@ mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ ## Run Torrust Tracker Container Image docker run -it \ --env TORRUST_TRACKER_API_ADMIN_TOKEN="MySecretToken" \ - --env USER_ID"$(id -u)" \ + --env USER_ID="$(id -u)" \ --publish 0.0.0.0:7070:7070/tcp \ --publish 0.0.0.0:6969:6969/udp \ --publish 0.0.0.0:1212:1212/tcp \ @@ -218,7 +218,7 @@ mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ ## Run Torrust Tracker Container Image podman run -it \ --env TORRUST_TRACKER_API_ADMIN_TOKEN="MySecretToken" \ - --env USER_ID"$(id -u)" \ + --env USER_ID="$(id -u)" \ --publish 0.0.0.0:7070:7070/tcp \ --publish 0.0.0.0:6969:6969/udp \ --publish 0.0.0.0:1212:1212/tcp \ @@ -367,6 +367,7 @@ And finally, you can run the container: ```s docker run \ + --env USER_ID="$(id -u)" \ --publish 6969:6969/udp \ --publish 7070:7070/tcp \ --publish 1212:1212/tcp \ @@ -381,6 +382,7 @@ Detach from container logs when the container starts. By default, the command li ```s docker run \ --detach + --env USER_ID="$(id -u)" \ --publish 6969:6969/udp \ --publish 7070:7070/tcp \ --publish 1212:1212/tcp \latest diff --git a/share/container/message b/share/container/message index cd88b44ae..6bfd6bfb8 100644 --- a/share/container/message +++ b/share/container/message @@ -1,2 +1,4 @@ +Lovely welcome to our Torrust Tracker Container! + run 'torrust-tracker' to start tracker From a53ee283d0f350826bdba4c2ef9ecc490d36ae57 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 10 Sep 2023 18:12:42 +0200 Subject: [PATCH 0067/1297] release: bump alpha version --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0ab5ffc45..64aed490d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3157,7 +3157,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.4" +version = "3.0.0-alpha.5" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3203,7 +3203,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.4" +version = "3.0.0-alpha.5" dependencies = [ "config", "log", @@ -3218,7 +3218,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.4" +version = "3.0.0-alpha.5" dependencies = [ "criterion", "error-chain", @@ -3226,7 +3226,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.4" +version = "3.0.0-alpha.5" dependencies = [ "log", "thiserror", @@ -3234,7 +3234,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.4" +version = "3.0.0-alpha.5" dependencies = [ "derive_more", "serde", @@ -3242,7 +3242,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.4" +version = "3.0.0-alpha.5" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index 30b44bf85..76ec97919 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,7 +29,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.4" +version = "3.0.0-alpha.5" [dependencies] @@ -66,10 +66,10 @@ axum = "0.6.20" axum-server = { version = "0.5", features = ["tls-rustls"] } axum-client-ip = "0.4.1" tower-http = { version = "0.4.3", features = ["compression-full"] } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.4", path = "contrib/bencode"} -torrust-tracker-primitives = { version = "3.0.0-alpha.4", path = "packages/primitives" } -torrust-tracker-configuration = { version = "3.0.0-alpha.4", path = "packages/configuration" } -torrust-tracker-located-error = { version = "3.0.0-alpha.4", path = "packages/located-error" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.5", path = "contrib/bencode"} +torrust-tracker-primitives = { version = "3.0.0-alpha.5", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.5", path = "packages/configuration" } +torrust-tracker-located-error = { version = "3.0.0-alpha.5", path = "packages/located-error" } multimap = "0.9" hyper = "0.14" @@ -80,7 +80,7 @@ serde_urlencoded = "0.7" serde_repr = "0.1" serde_bytes = "0.11" local-ip-address = "0.5" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.4", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.5", path = "packages/test-helpers" } [workspace] members = [ diff --git a/README.md b/README.md index 2f35e9017..7e3d246e5 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.5/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.5/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.5/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.4/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.5/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 93b45c0a7..ba2f8a466 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -22,8 +22,8 @@ config = "0.13" toml = "0.7" log = { version = "0.4", features = ["release_max_level_info"] } thiserror = "1.0" -torrust-tracker-primitives = { version = "3.0.0-alpha.4", path = "../primitives" } -torrust-tracker-located-error = { version = "3.0.0-alpha.4", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.5", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.5", path = "../located-error" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 91831399c..be3cc352d 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.4", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.4", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.5", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.5", path = "../primitives" } From 6665a059bb1668d64513b6bc61ae7c5184b0bde7 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 10 Sep 2023 17:55:19 +0200 Subject: [PATCH 0068/1297] dev: use releases branch prefix --- .github/workflows/container.yaml | 49 +++++++++++++++++++++++-------- .github/workflows/deployment.yaml | 10 +++---- 2 files changed, 42 insertions(+), 17 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index 86ee8692d..93ce87506 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -5,8 +5,7 @@ on: branches: - "develop" - "main" - tags: - - "v*" + - "releases/**/*" pull_request: branches: - "develop" @@ -60,6 +59,8 @@ jobs: outputs: continue: ${{ steps.check.outputs.continue }} + type: ${{ steps.check.outputs.type }} + version: ${{ steps.check.outputs.version }} steps: - id: check @@ -67,12 +68,25 @@ jobs: run: | if [[ "${{ github.repository }}" == "torrust/torrust-tracker" ]]; then if [[ "${{ github.event_name }}" == "push" ]]; then - if [[ "${{ github.ref }}" == "refs/heads/main" || - "${{ github.ref }}" == "refs/heads/develop" || - "${{ github.ref }}" =~ ^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$ ]]; then + if [[ "${{ github.ref }}" == "refs/heads/main" ]]; then + + echo "type=development" >> $GITHUB_OUTPUT + echo "continue=true" >> $GITHUB_OUTPUT + + fi + if [[ "${{ github.ref }}" == "refs/heads/develop" ]]; then + + echo "type=development" >> $GITHUB_OUTPUT + echo "continue=true" >> $GITHUB_OUTPUT + + fi + if [[ "${{ github.ref }}" =~ ^(refs\/heads\/releases\/)(v)(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$ ]]; then + + version=$(echo "${{ github.ref }}" | sed -n -E 's/^(refs\/heads\/releases\/)//p') + echo "version=$version" >> $GITHUB_OUTPUT + echo "type=release" >> $GITHUB_OUTPUT + echo "continue=true" >> $GITHUB_OUTPUT - echo "Context is torrust/torrust-tracker, and push is: main, develop, docker, or a tag with a semantic version" - echo "continue=true" >> $GITHUB_OUTPUT fi fi fi @@ -103,17 +117,28 @@ jobs: runs-on: ubuntu-latest steps: - - id: meta - name: Docker meta + - id: meta_development + if: needs.secrets.check.type == 'development' + name: Docker Meta (development) uses: docker/metadata-action@v4 with: images: | "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" tags: | type=ref,event=branch - type=ref,event=pr - type=semver,pattern={{version}} - type=semver,pattern={{major}}.{{minor}} + + - id: meta_release + if: needs.secrets.check.type == 'release' + name: Docker Meta (release) + uses: docker/metadata-action@v4 + with: + images: | + "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" + tags: | + type=semver,value=${{ needs.secrets.check.version }},pattern={{raw}} + type=semver,value=${{ needs.secrets.check.version }},pattern={{version}} + type=semver,value=${{ needs.secrets.check.version }},pattern=v{{major}} + type=semver,value=${{ needs.secrets.check.version }},pattern={{major}}.{{minor}} - id: login name: Login to Docker Hub diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 73c024143..e3b042fd5 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -2,8 +2,8 @@ name: Deployment on: push: - tags: - - "v*" + branches: + - "releases/**/*" jobs: secrets: @@ -18,8 +18,8 @@ jobs: - id: check name: Check env: - CRATES_TOKEN: "${{ secrets.CRATES_TOKEN }}" - if: "${{ env.CRATES_TOKEN != '' }}" + CARGO_REGISTRY_TOKEN: "${{ secrets.CARGO_REGISTRY_TOKEN }}" + if: "${{ env.CARGO_REGISTRY_TOKEN != '' }}" run: echo "continue=true" >> $GITHUB_OUTPUT test: @@ -66,7 +66,7 @@ jobs: toolchain: stable env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_TOKEN }} + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} - id: publish name: Publish Crates From d09fa65b77a330525ee4f037a06c2a1f91cdefbb Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 11 Sep 2023 10:56:44 +0200 Subject: [PATCH 0069/1297] dev: fixup container workfows bug --- .github/workflows/container.yaml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index 93ce87506..d541cc3aa 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -118,7 +118,7 @@ jobs: steps: - id: meta_development - if: needs.secrets.check.type == 'development' + if: needs.context.check.type == 'development' name: Docker Meta (development) uses: docker/metadata-action@v4 with: @@ -128,17 +128,17 @@ jobs: type=ref,event=branch - id: meta_release - if: needs.secrets.check.type == 'release' + if: needs.context.check.type == 'release' name: Docker Meta (release) uses: docker/metadata-action@v4 with: images: | "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" tags: | - type=semver,value=${{ needs.secrets.check.version }},pattern={{raw}} - type=semver,value=${{ needs.secrets.check.version }},pattern={{version}} - type=semver,value=${{ needs.secrets.check.version }},pattern=v{{major}} - type=semver,value=${{ needs.secrets.check.version }},pattern={{major}}.{{minor}} + type=semver,value=${{ needs.context.check.version }},pattern={{raw}} + type=semver,value=${{ needs.context.check.version }},pattern={{version}} + type=semver,value=${{ needs.context.check.version }},pattern=v{{major}} + type=semver,value=${{ needs.context.check.version }},pattern={{major}}.{{minor}} - id: login name: Login to Docker Hub From d9a506a54687ac6c7fda07abc4ae8bcc4ec3e5fd Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 11 Sep 2023 10:57:46 +0200 Subject: [PATCH 0070/1297] docs: draft release process document --- docs/release_process.md | 61 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 docs/release_process.md diff --git a/docs/release_process.md b/docs/release_process.md new file mode 100644 index 000000000..cc401c11a --- /dev/null +++ b/docs/release_process.md @@ -0,0 +1,61 @@ +# Torrust Tracker Release Process (draft) + +The purpose of this document is to describe the release process. + +## Overview + +Torrust Tracker is published in this order: + +1. `develop` branch is ready for publishing. +2. create `release: version (semantic version)` commit. +3. push release commit to `main` branch. +4. check all status checks succeed for `main` branch. +5. push `main` branch to `releases\v(semantic version)` branch. +6. check all status checks success for `releases\v(semantic version)` branch. +7. create signed `v(semantic version)` tag. +8. create github release from `v(semantic version)` tag. +9. merge `main` branch into `develop` branch. + +- At step `1.`, `develop` is automatically published to `dockerhub`. +- At step `3.`, `main` is automatically published to `dockerhub`. +- At step `5.`, `releases\v(semantic version)` is automatically published to `dockerhub` and `crate.io`. + +## Development Branch + +The `develop` branch, the default branch for the repository is automatically published to dockerhub with the `develop` label. This process happens automatically when a pull request is merged in, and the `container.yaml` workflow is triggered. + +## Main Branch + +The `main` branch is the staging branch for releases. + +A release commit needs to be made that prepares the repository for the release, this commit should include: + +- Changing the semantic version. +- Finalizing the release notes and changelog. + +The title of the commit should be: `release: version (semantic version)`. + +This commit should be committed upon the head of the development branch, and pushed to the `main` branch. + +Once the release has succeeded, the `main` branch should be merged back into the `develop` branch. + +## Releases Branch + +According to the patten `releases/v(semantic version)`, the `main` branch head is published to here to trigger the deployment workflows. + +The repository deployment environment for crates.io is only available for the `releases/**/*` patten of branches. + +Once the publishing workflows have succeeded; we can make the git-tag. + +## Release Tag + +Create a Signed Tag with a short message in the form `v(semantic version)` and push it to the repository. + +## Github Release + +From the newly published tag, create a Github Release using the web-interface. + + +## Merge back into development branch + +After this is all successful, the `main` branch should be merged into the `develop` branch. From 7365423eb8748a60151615b5be1a201402f1d9a7 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 11 Sep 2023 11:17:25 +0200 Subject: [PATCH 0071/1297] ci: use coverage environment --- .github/workflows/coverage.yaml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 6a99fb11a..df308e329 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -8,8 +8,27 @@ env: CARGO_TERM_COLOR: always jobs: + secrets: + name: Secrets + environment: coverage + runs-on: ubuntu-latest + + outputs: + continue: ${{ steps.check.outputs.continue }} + + steps: + - id: check + name: Check + env: + CODECOV_TOKEN: "${{ secrets.CODECOV_TOKEN }}" + if: "${{ env.CODECOV_TOKEN != '' }}" + run: echo "continue=true" >> $GITHUB_OUTPUT + report: name: Report + environment: coverage + needs: secrets + if: needs.secrets.outputs.continue == 'true' runs-on: ubuntu-latest env: CARGO_INCREMENTAL: "0" From da476a76f78a15c9e7b545ee8658705645ab8e37 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 11 Sep 2023 12:27:52 +0200 Subject: [PATCH 0072/1297] dev: debug container workflow --- .github/workflows/container.yaml | 20 +++++++++++++------- cSpell.json | 1 + 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index d541cc3aa..29e03a7fa 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -54,7 +54,6 @@ jobs: context: name: Context - needs: test runs-on: ubuntu-latest outputs: @@ -72,28 +71,35 @@ jobs: echo "type=development" >> $GITHUB_OUTPUT echo "continue=true" >> $GITHUB_OUTPUT + echo "On \`main\` Branch, Type: \`development\`" - fi - if [[ "${{ github.ref }}" == "refs/heads/develop" ]]; then + elif [[ "${{ github.ref }}" == "refs/heads/develop" ]]; then echo "type=development" >> $GITHUB_OUTPUT echo "continue=true" >> $GITHUB_OUTPUT + echo "On \`develop\` Branch, Type: \`development\`" - fi - if [[ "${{ github.ref }}" =~ ^(refs\/heads\/releases\/)(v)(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$ ]]; then + elif [[ "${{ github.ref }}" =~ ^(refs\/heads\/releases\/)(v)(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$ ]]; then version=$(echo "${{ github.ref }}" | sed -n -E 's/^(refs\/heads\/releases\/)//p') echo "version=$version" >> $GITHUB_OUTPUT echo "type=release" >> $GITHUB_OUTPUT echo "continue=true" >> $GITHUB_OUTPUT + echo "In \`releases/$version\` Branch, Type: \`release\`" + else + echo "Not Correct Branch. Will Not Continue" fi + else + echo "Not a Push Event. Will Not Continue" fi + else + echo "On a Forked Repository. Will Not Continue" fi secrets: name: Secrets - needs: context + needs: [test, context] environment: dockerhub-torrust if: needs.context.outputs.continue == 'true' runs-on: ubuntu-latest @@ -112,7 +118,7 @@ jobs: publish: name: Publish environment: dockerhub-torrust - needs: secrets + needs: [secrets, context] if: needs.secrets.outputs.continue == 'true' runs-on: ubuntu-latest diff --git a/cSpell.json b/cSpell.json index a02a9b8e8..c9b547c90 100644 --- a/cSpell.json +++ b/cSpell.json @@ -38,6 +38,7 @@ "dockerhub", "downloadedi", "dtolnay", + "elif", "filesd", "Freebox", "gecos", From e6ddda10668c49dad4b61519986b750a2654ea07 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 11 Sep 2023 15:47:52 +0200 Subject: [PATCH 0073/1297] fixup: context output --- .github/workflows/container.yaml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index 29e03a7fa..2a983f988 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -124,7 +124,7 @@ jobs: steps: - id: meta_development - if: needs.context.check.type == 'development' + if: needs.context.outputs.type == 'development' name: Docker Meta (development) uses: docker/metadata-action@v4 with: @@ -134,17 +134,17 @@ jobs: type=ref,event=branch - id: meta_release - if: needs.context.check.type == 'release' + if: needs.context.outputs.type == 'release' name: Docker Meta (release) uses: docker/metadata-action@v4 with: images: | "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" tags: | - type=semver,value=${{ needs.context.check.version }},pattern={{raw}} - type=semver,value=${{ needs.context.check.version }},pattern={{version}} - type=semver,value=${{ needs.context.check.version }},pattern=v{{major}} - type=semver,value=${{ needs.context.check.version }},pattern={{major}}.{{minor}} + type=semver,value=${{ needs.context.outputs.version }},pattern={{raw}} + type=semver,value=${{ needs.context.outputs.version }},pattern={{version}} + type=semver,value=${{ needs.context.outputs.version }},pattern=v{{major}} + type=semver,value=${{ needs.context.outputs.version }},pattern={{major}}.{{minor}} - id: login name: Login to Docker Hub From 835b499a596e109621d3636c6347347028089b56 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 12 Sep 2023 10:06:51 +0200 Subject: [PATCH 0074/1297] dev: more container workflow fixups --- .github/workflows/container.yaml | 45 +++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index 2a983f988..8fd4ca201 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -115,17 +115,16 @@ jobs: if: "${{ env.DOCKER_HUB_ACCESS_TOKEN != '' }}" run: echo "continue=true" >> $GITHUB_OUTPUT - publish: - name: Publish + publish_development: + name: Publish (Development) environment: dockerhub-torrust needs: [secrets, context] - if: needs.secrets.outputs.continue == 'true' + if: needs.secrets.outputs.continue == 'true' && needs.context.outputs.type == 'development' runs-on: ubuntu-latest steps: - - id: meta_development - if: needs.context.outputs.type == 'development' - name: Docker Meta (development) + - id: meta + name: Docker Meta uses: docker/metadata-action@v4 with: images: | @@ -133,9 +132,37 @@ jobs: tags: | type=ref,event=branch - - id: meta_release - if: needs.context.outputs.type == 'release' - name: Docker Meta (release) + - id: login + name: Login to Docker Hub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKER_HUB_USERNAME }} + password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} + + - id: setup + name: Setup Toolchain + uses: docker/setup-buildx-action@v2 + + - name: Build and push + uses: docker/build-push-action@v4 + with: + file: ./Containerfile + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha + + publish_release: + name: Publish (Release) + environment: dockerhub-torrust + needs: [secrets, context] + if: needs.secrets.outputs.continue == 'true' && needs.context.outputs.type == 'release' + runs-on: ubuntu-latest + + steps: + - id: meta + name: Docker Meta uses: docker/metadata-action@v4 with: images: | From d5d797937402bc697c34fbddc441ab08ce05060a Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 12 Sep 2023 10:32:04 +0200 Subject: [PATCH 0075/1297] dev: coverage: change to pull request target --- .github/workflows/coverage.yaml | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index df308e329..7cfd92025 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -2,7 +2,11 @@ name: Coverage on: push: - pull_request: + branches: + - develop + pull_request_target: + branches: + - develop env: CARGO_TERM_COLOR: always @@ -36,10 +40,18 @@ jobs: RUSTDOCFLAGS: "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests" steps: - - id: checkout - name: Checkout Repository + - id: checkout_push + if: github.event_name == 'push' + name: Checkout Repository (Push) uses: actions/checkout@v4 + - id: checkout_pull_request + if: github.event_name == 'pull_request' + name: Checkout Repository (Pull Request) + uses: actions/checkout@v4 + with: + ref: "refs/pull/${{ github.event.pull_request.number }}/head" + - id: setup name: Setup Toolchain uses: dtolnay/rust-toolchain@stable From 8eff67f11c2d2356700c2a9bf38c22b79c1cb488 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 12 Sep 2023 11:30:37 +0200 Subject: [PATCH 0076/1297] dev: fixup, fix event_name test --- .github/workflows/coverage.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 7cfd92025..cf7eb6f6d 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -45,9 +45,9 @@ jobs: name: Checkout Repository (Push) uses: actions/checkout@v4 - - id: checkout_pull_request - if: github.event_name == 'pull_request' - name: Checkout Repository (Pull Request) + - id: checkout_pull_request_target + if: github.event_name == 'pull_request_target' + name: Checkout Repository (Pull Request Target) uses: actions/checkout@v4 with: ref: "refs/pull/${{ github.event.pull_request.number }}/head" From d2e3757808863067787756043fdd54803afb2d05 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 12 Sep 2023 08:34:28 +0200 Subject: [PATCH 0077/1297] dev: rename database driver environmental variable from: `TORRUST_TRACKER_DATABASE` to: `TORRUST_TRACKER_DATABASE_DRIVER` --- Containerfile | 4 ++-- compose.yaml | 2 +- docs/containers.md | 2 +- share/container/entry_script_sh | 10 +++++----- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Containerfile b/Containerfile index 229500cd8..be71017db 100644 --- a/Containerfile +++ b/Containerfile @@ -96,14 +96,14 @@ RUN ["/busybox/cp", "-sp", "/busybox/sh","/busybox/cat","/busybox/ls","/busybox/ COPY --from=gcc --chmod=0555 /usr/local/bin/su-exec /bin/su-exec ARG TORRUST_TRACKER_PATH_CONFIG="/etc/torrust/tracker/tracker.toml" -ARG TORRUST_TRACKER_DATABASE="sqlite3" +ARG TORRUST_TRACKER_DATABASE_DRIVER="sqlite3" ARG USER_ID=1000 ARG UDP_PORT=6969 ARG HTTP_PORT=7070 ARG API_PORT=1212 ENV TORRUST_TRACKER_PATH_CONFIG=${TORRUST_TRACKER_PATH_CONFIG} -ENV TORRUST_TRACKER_DATABASE=${TORRUST_TRACKER_DATABASE} +ENV TORRUST_TRACKER_DATABASE_DRIVER=${TORRUST_TRACKER_DATABASE_DRIVER} ENV USER_ID=${USER_ID} ENV UDP_PORT=${UDP_PORT} ENV HTTP_PORT=${HTTP_PORT} diff --git a/compose.yaml b/compose.yaml index 02f95bccc..672ca6d0f 100644 --- a/compose.yaml +++ b/compose.yaml @@ -4,7 +4,7 @@ services: image: torrust-tracker:release tty: true environment: - - TORRUST_TRACKER_DATABASE=${TORRUST_TRACKER_DATABASE:-mysql} + - TORRUST_TRACKER_DATABASE_DRIVER=${TORRUST_TRACKER_DATABASE_DRIVER:-mysql} - TORRUST_TRACKER_API_ADMIN_TOKEN=${TORRUST_TRACKER_API_ADMIN_TOKEN:-MyAccessToken} networks: - server_side diff --git a/docs/containers.md b/docs/containers.md index dcf281e6e..737ce40a0 100644 --- a/docs/containers.md +++ b/docs/containers.md @@ -140,7 +140,7 @@ The following environmental variables can be set: - `TORRUST_TRACKER_PATH_CONFIG` - The in-container path to the tracker configuration file, (default: `"/etc/torrust/tracker/tracker.toml"`). - `TORRUST_TRACKER_API_ADMIN_TOKEN` - Override of the admin token. If set, this value overrides any value set in the config. -- `TORRUST_TRACKER_DATABASE` - The database type used for the container, (options: `sqlite3`, `mysql`, default `sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. +- `TORRUST_TRACKER_DATABASE_DRIVER` - The database type used for the container, (options: `sqlite3`, `mysql`, default `sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. - `TORRUST_TRACKER_CONFIG` - Load config from this environmental variable instead from a file, (i.e: `TORRUST_TRACKER_CONFIG=$(cat tracker-tracker.toml)`). - `USER_ID` - The user id for the runtime crated `torrust` user. Please Note: This user id should match the ownership of the host-mapped volumes, (default `1000`). - `UDP_PORT` - The port for the UDP tracker. This should match the port used in the configuration, (default `6969`). diff --git a/share/container/entry_script_sh b/share/container/entry_script_sh index 88a832b40..94dfa6b81 100644 --- a/share/container/entry_script_sh +++ b/share/container/entry_script_sh @@ -26,8 +26,8 @@ chmod -R 2770 /var/lib/torrust /var/log/torrust /etc/torrust # Install the database and config: -if [ -n "$TORRUST_TRACKER_DATABASE" ]; then - if cmp_lc "$TORRUST_TRACKER_DATABASE" "sqlite3"; then +if [ -n "$TORRUST_TRACKER_DATABASE_DRIVER" ]; then + if cmp_lc "$TORRUST_TRACKER_DATABASE_DRIVER" "sqlite3"; then # Select sqlite3 empty database default_database="/usr/share/torrust/default/database/tracker.sqlite3.db" @@ -35,7 +35,7 @@ if [ -n "$TORRUST_TRACKER_DATABASE" ]; then # Select sqlite3 default configuration default_config="/usr/share/torrust/default/config/tracker.container.sqlite3.toml" - elif cmp_lc "$TORRUST_TRACKER_DATABASE" "mysql"; then + elif cmp_lc "$TORRUST_TRACKER_DATABASE_DRIVER" "mysql"; then # (no database file needed for mysql) @@ -43,12 +43,12 @@ if [ -n "$TORRUST_TRACKER_DATABASE" ]; then default_config="/usr/share/torrust/default/config/tracker.container.mysql.toml" else - echo "Error: Unsupported Database Type: \"$TORRUST_TRACKER_DATABASE\"." + echo "Error: Unsupported Database Type: \"$TORRUST_TRACKER_DATABASE_DRIVER\"." echo "Please Note: Supported Database Types: \"sqlite3\", \"mysql\"." exit 1 fi else - echo "Error: \"\$TORRUST_TRACKER_DATABASE\" was not set!"; exit 1; + echo "Error: \"\$TORRUST_TRACKER_DATABASE_DRIVER\" was not set!"; exit 1; fi install_config="/etc/torrust/tracker/tracker.toml" From 68b199db6eacaea34c63f66cf7aacbf6d2bdbfa1 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 12 Sep 2023 12:56:03 +0200 Subject: [PATCH 0078/1297] chore: update deps --- Cargo.lock | 119 +++++++++++++++++++++++++++-------------------------- Cargo.toml | 8 ++-- 2 files changed, 64 insertions(+), 63 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 64aed490d..c6ebec05a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -92,9 +92,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstyle" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15c4c2c83f81532e5845a733998b6971faca23490340a418e9b72a3ec9de12ea" +checksum = "b84bf0a05bbb2a83e5eb6fa36bb6e87baa08193c35ff52bbf6b38d8af2890e46" [[package]] name = "aquatic_udp_protocol" @@ -120,9 +120,9 @@ checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "async-compression" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d495b6dc0184693324491a5ac05f559acc97bf937ab31d7a1c33dd0016be6d2b" +checksum = "bb42b2197bf15ccb092b62c74515dbd8b86d0effd934795f6687c93b6e679a2c" dependencies = [ "brotli", "flate2", @@ -142,7 +142,7 @@ checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -185,9 +185,9 @@ dependencies = [ [[package]] name = "axum-client-ip" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df8e81eacc93f36480825da5f46a33b5fb2246ed024eacc9e8933425b80c5807" +checksum = "1ef117890a418b7832678d9ea1e1c08456dd7b2fd1dadb9676cd6f0fe7eb4b21" dependencies = [ "axum", "forwarded-header-value", @@ -254,9 +254,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "base64" -version = "0.21.3" +version = "0.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "414dcefbc63d77c526a76b3afcf6fbb9b5e2791c19c3aa2297733208750c6e53" +checksum = "9ba43ea6f343b788c8764558649e08df62f86c6ef251fdaeb1ffd010a9ae50a2" [[package]] name = "bigdecimal" @@ -277,11 +277,11 @@ checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" [[package]] name = "bindgen" -version = "0.59.2" +version = "0.68.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bd2a9a458e8f4304c52c43ebb0cfbd520289f8379a52e329a38afda99bf8eb8" +checksum = "726e4313eb6ec35d2730258ad4e15b547ee75d6afaa1361a922e78e59b7d8078" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.4.0", "cexpr", "clang-sys", "lazy_static", @@ -292,6 +292,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", + "syn 2.0.32", ] [[package]] @@ -435,9 +436,9 @@ checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" [[package]] name = "bytes" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" +checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" [[package]] name = "cast" @@ -472,9 +473,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.29" +version = "0.4.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d87d9d13be47a5b7c3907137f1290b0459a7f80efb26be8c52afb11963bccb02" +checksum = "defd4e7873dbddba6c7c91e199c7fcb946abc4a6a4ac3195400bcfb01b5de877" dependencies = [ "android-tzdata", "iana-time-zone", @@ -748,7 +749,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -759,7 +760,7 @@ checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ "darling_core", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -792,7 +793,7 @@ checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" dependencies = [ "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -993,7 +994,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -1005,7 +1006,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -1017,7 +1018,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -1082,7 +1083,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -1373,7 +1374,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -1568,9 +1569,9 @@ checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" [[package]] name = "linux-raw-sys" -version = "0.4.5" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57bcfdad1b858c2db7c38303a6d2ad4dfaf5eb53dfeb0910128b2c26d6158503" +checksum = "1a9bad9f94746442c783ca431b22403b519cd7fbeed0533fdd6328b2f2212128" [[package]] name = "local-ip-address" @@ -1719,7 +1720,7 @@ dependencies = [ "percent-encoding", "serde", "serde_json", - "socket2 0.5.3", + "socket2 0.5.4", "twox-hash", "url", ] @@ -1737,7 +1738,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", "termcolor", "thiserror", ] @@ -1748,7 +1749,7 @@ version = "0.30.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57349d5a326b437989b6ee4dc8f2f34b0cc131202748414712a8e7d98952fc8c" dependencies = [ - "base64 0.21.3", + "base64 0.21.4", "bigdecimal", "bindgen", "bitflags 2.4.0", @@ -1938,7 +1939,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -2020,7 +2021,7 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b13fe415cdf3c8e44518e18a7c95a13431d9bdf6d15367d82b23c377fdd441a" dependencies = [ - "base64 0.21.3", + "base64 0.21.4", "serde", ] @@ -2061,7 +2062,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -2092,7 +2093,7 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -2401,7 +2402,7 @@ version = "0.11.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e9ad3fe7488d7e34558a2033d45a0c90b72d97b4f80705666fea71472e2e6a1" dependencies = [ - "base64 0.21.3", + "base64 0.21.4", "bytes", "encoding_rs", "futures-core", @@ -2549,9 +2550,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.11" +version = "0.38.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0c3dde1fc030af041adc40e79c0e7fbcf431dd24870053d187d7c66e4b87453" +checksum = "d7db8590df6dfcd144d22afd1b83b36c21a18d7cbc1dc4bb5295a8712e9eb662" dependencies = [ "bitflags 2.4.0", "errno", @@ -2578,14 +2579,14 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d3987094b1d07b653b7dfdc3f70ce9a1da9c51ac18c1b06b662e4f9a0e9f4b2" dependencies = [ - "base64 0.21.3", + "base64 0.21.4", ] [[package]] name = "rustls-webpki" -version = "0.101.4" +version = "0.101.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d93931baf2d282fff8d3a532bbfd7653f734643161b87e3e01e59a04439bf0d" +checksum = "45a27e3b59326c16e23d30aeb7a36a24cc0d29e71d68ff611cdfb4a01d013bed" dependencies = [ "ring", "untrusted", @@ -2723,14 +2724,14 @@ checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] name = "serde_json" -version = "1.0.105" +version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "693151e1ac27563d6dbcec9dee9fbd5da8539b20fa14ad3752b2e6d363ace360" +checksum = "2cc66a619ed80bf7a0f6b17dd063a84b88f6dea1813737cf469aef1d081142c2" dependencies = [ "itoa", "ryu", @@ -2755,7 +2756,7 @@ checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -2785,7 +2786,7 @@ version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ca3b16a3d82c4088f343b7480a93550b3eabe1a358569c2dfe38bbcead07237" dependencies = [ - "base64 0.21.3", + "base64 0.21.4", "chrono", "hex", "indexmap 1.9.3", @@ -2805,7 +2806,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -2878,9 +2879,9 @@ dependencies = [ [[package]] name = "socket2" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2538b18701741680e0322a2302176d3253a35388e2e62f172f64f4f16605f877" +checksum = "4031e820eb552adee9295814c0ced9e5cf38ddf1e8b7d566d6de8e2538ea989e" dependencies = [ "libc", "windows-sys", @@ -2927,9 +2928,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.31" +version = "2.0.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "718fa2415bcb8d8bd775917a1bf12a7931b6dfa890753378538118181e0cb398" +checksum = "239814284fd6f1a4ffe4ca893952cdd93c224b6a1571c9a9eadd670295c0c9e2" dependencies = [ "proc-macro2", "quote", @@ -2993,7 +2994,7 @@ checksum = "49922ecae66cc8a249b77e68d1d0623c1b2c514f0060c27cdc68bd62a1219d35" dependencies = [ "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -3062,7 +3063,7 @@ dependencies = [ "num_cpus", "pin-project-lite", "signal-hook-registry", - "socket2 0.5.3", + "socket2 0.5.4", "tokio-macros", "windows-sys", ] @@ -3075,7 +3076,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", ] [[package]] @@ -3123,9 +3124,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c17e963a819c331dcacd7ab957d80bc2b9a9c1e71c804826d2f283dd65306542" +checksum = "dd79e69d3b627db300ff956027cc6c3798cef26d22526befdfcd12feeb6d2257" dependencies = [ "serde", "serde_spanned", @@ -3144,9 +3145,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.19.14" +version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8123f27e969974a3dfba720fdb560be359f57b44302d280ba72e76a74480e8a" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ "indexmap 2.0.0", "serde", @@ -3210,7 +3211,7 @@ dependencies = [ "serde", "serde_with", "thiserror", - "toml 0.7.6", + "toml 0.7.8", "torrust-tracker-located-error", "torrust-tracker-primitives", "uuid", @@ -3455,7 +3456,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", "wasm-bindgen-shared", ] @@ -3489,7 +3490,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.31", + "syn 2.0.32", "wasm-bindgen-backend", "wasm-bindgen-shared", ] diff --git a/Cargo.toml b/Cargo.toml index 76ec97919..79f523fa3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,7 +51,7 @@ openssl = { version = "0.10", features = ["vendored"] } config = "0.13" log = { version = "0.4", features = ["release_max_level_info"] } fern = "0.6" -chrono = { version = "0.4.24", default-features = false, features = ["clock"] } +chrono = { version = "0.4", default-features = false, features = ["clock"] } r2d2 = "0.8" r2d2_mysql = "24.0" r2d2_sqlite = { version = "0.22", features = ["bundled"] } @@ -62,10 +62,10 @@ futures = "0.3" async-trait = "0.1" aquatic_udp_protocol = "0.8" uuid = { version = "1", features = ["v4"] } -axum = "0.6.20" +axum = "0.6" axum-server = { version = "0.5", features = ["tls-rustls"] } -axum-client-ip = "0.4.1" -tower-http = { version = "0.4.3", features = ["compression-full"] } +axum-client-ip = "0.4" +tower-http = { version = "0.4", features = ["compression-full"] } torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.5", path = "contrib/bencode"} torrust-tracker-primitives = { version = "3.0.0-alpha.5", path = "packages/primitives" } torrust-tracker-configuration = { version = "3.0.0-alpha.5", path = "packages/configuration" } From ea8c78f1abdcd1bfd6630cb2ff286b7afabc9d73 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 13 Sep 2023 11:05:24 +0200 Subject: [PATCH 0079/1297] release: version 3.0.0-alpha.6 --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c6ebec05a..c9da67f5b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3158,7 +3158,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.5" +version = "3.0.0-alpha.6" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3204,7 +3204,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.5" +version = "3.0.0-alpha.6" dependencies = [ "config", "log", @@ -3219,7 +3219,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.5" +version = "3.0.0-alpha.6" dependencies = [ "criterion", "error-chain", @@ -3227,7 +3227,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.5" +version = "3.0.0-alpha.6" dependencies = [ "log", "thiserror", @@ -3235,7 +3235,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.5" +version = "3.0.0-alpha.6" dependencies = [ "derive_more", "serde", @@ -3243,7 +3243,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.5" +version = "3.0.0-alpha.6" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index 79f523fa3..a26bed8da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,7 +29,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.5" +version = "3.0.0-alpha.6" [dependencies] @@ -66,10 +66,10 @@ axum = "0.6" axum-server = { version = "0.5", features = ["tls-rustls"] } axum-client-ip = "0.4" tower-http = { version = "0.4", features = ["compression-full"] } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.5", path = "contrib/bencode"} -torrust-tracker-primitives = { version = "3.0.0-alpha.5", path = "packages/primitives" } -torrust-tracker-configuration = { version = "3.0.0-alpha.5", path = "packages/configuration" } -torrust-tracker-located-error = { version = "3.0.0-alpha.5", path = "packages/located-error" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.6", path = "contrib/bencode"} +torrust-tracker-primitives = { version = "3.0.0-alpha.6", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.6", path = "packages/configuration" } +torrust-tracker-located-error = { version = "3.0.0-alpha.6", path = "packages/located-error" } multimap = "0.9" hyper = "0.14" @@ -80,7 +80,7 @@ serde_urlencoded = "0.7" serde_repr = "0.1" serde_bytes = "0.11" local-ip-address = "0.5" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.5", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.6", path = "packages/test-helpers" } [workspace] members = [ diff --git a/README.md b/README.md index 7e3d246e5..551471914 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.5/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.5/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.5/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.6/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.6/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.6/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.5/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.6/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index ba2f8a466..4a3028f18 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -22,8 +22,8 @@ config = "0.13" toml = "0.7" log = { version = "0.4", features = ["release_max_level_info"] } thiserror = "1.0" -torrust-tracker-primitives = { version = "3.0.0-alpha.5", path = "../primitives" } -torrust-tracker-located-error = { version = "3.0.0-alpha.5", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.6", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.6", path = "../located-error" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index be3cc352d..bec9bb216 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.5", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.5", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.6", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.6", path = "../primitives" } From c06dc64cd26ad3feb6698c4589fa17c535bb1231 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 13 Sep 2023 12:05:07 +0200 Subject: [PATCH 0080/1297] fixup: wrong env in deployment workflow --- .github/workflows/deployment.yaml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index e3b042fd5..43bfe4784 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -8,7 +8,7 @@ on: jobs: secrets: name: Secrets - environment: dockerhub-torrust + environment: crates-io-torrust runs-on: ubuntu-latest outputs: @@ -51,7 +51,6 @@ jobs: name: Publish environment: crates-io-torrust needs: test - if: needs.secrets.outputs.continue == 'true' runs-on: ubuntu-latest steps: From 27a7f92128dbd08f1962a2300d6b5a9935a25282 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 11:28:28 +0200 Subject: [PATCH 0081/1297] ci: fix for bug in upstream lib testing unit coverage step triggers bug in time crate on nightly: https://github.com/time-rs/time/issues/618 --- .github/workflows/testing.yaml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index f138a95cc..21c47665f 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -104,6 +104,7 @@ jobs: name: Run Unit Tests run: cargo test --tests --benches --examples --workspace --all-targets --all-features - - id: coverage - name: Generate Coverage Report - run: cargo llvm-cov nextest --tests --benches --examples --workspace --all-targets --all-features + # Temporary Disable https://github.com/time-rs/time/issues/618 + # - id: coverage + # name: Generate Coverage Report + # run: cargo llvm-cov nextest --tests --benches --examples --workspace --all-targets --all-features From 4cc4680bf18620f133cf727eb79e36111c469e18 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 08:49:04 +0200 Subject: [PATCH 0082/1297] chore: update docker workflow actions --- .github/workflows/container.yaml | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index 8fd4ca201..d107a0139 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -26,11 +26,11 @@ jobs: steps: - id: setup name: Setup Toolchain - uses: docker/setup-buildx-action@v2 + uses: docker/setup-buildx-action@v3 - id: build name: Build - uses: docker/build-push-action@v4 + uses: docker/build-push-action@v5 with: file: ./Containerfile push: false @@ -125,7 +125,7 @@ jobs: steps: - id: meta name: Docker Meta - uses: docker/metadata-action@v4 + uses: docker/metadata-action@v5 with: images: | "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" @@ -134,17 +134,17 @@ jobs: - id: login name: Login to Docker Hub - uses: docker/login-action@v2 + uses: docker/login-action@v3 with: username: ${{ secrets.DOCKER_HUB_USERNAME }} password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} - id: setup name: Setup Toolchain - uses: docker/setup-buildx-action@v2 + uses: docker/setup-buildx-action@v3 - name: Build and push - uses: docker/build-push-action@v4 + uses: docker/build-push-action@v5 with: file: ./Containerfile push: true @@ -163,7 +163,7 @@ jobs: steps: - id: meta name: Docker Meta - uses: docker/metadata-action@v4 + uses: docker/metadata-action@v5 with: images: | "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" @@ -175,17 +175,17 @@ jobs: - id: login name: Login to Docker Hub - uses: docker/login-action@v2 + uses: docker/login-action@v3 with: username: ${{ secrets.DOCKER_HUB_USERNAME }} password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} - id: setup name: Setup Toolchain - uses: docker/setup-buildx-action@v2 + uses: docker/setup-buildx-action@v3 - name: Build and push - uses: docker/build-push-action@v4 + uses: docker/build-push-action@v5 with: file: ./Containerfile push: true From 7d5acd23210c5d2bbba114f4af665d16faca907b Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 09:45:22 +0200 Subject: [PATCH 0083/1297] chore: bump codecov/codecov-action from 3 to 4 --- .github/workflows/coverage.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index cf7eb6f6d..4d4054026 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -83,7 +83,7 @@ jobs: - id: upload name: Upload Coverage Report - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: token: ${{ secrets.CODECOV_TOKEN }} files: ${{ steps.coverage.outputs.report }} From 91ff423c200bcdb59fef270de14f4a0ba1b273a5 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 09:23:11 +0200 Subject: [PATCH 0084/1297] chore: update cargo lockfile --- Cargo.lock | 74 +++++++++++++++++++++++++++--------------------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c9da67f5b..0f04f4bad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -142,7 +142,7 @@ checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -292,7 +292,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -402,9 +402,9 @@ checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" [[package]] name = "bumpalo" -version = "3.13.0" +version = "3.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1" +checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" [[package]] name = "bytecheck" @@ -524,9 +524,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.2" +version = "4.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a13b88d2c62ff462f88e4a121f17a82c1af05693a2f192b5c38d14de73c19f6" +checksum = "84ed82781cea27b43c9b106a979fe450a13a31aab0500595fb3fc06616de08e6" dependencies = [ "clap_builder", ] @@ -749,7 +749,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -760,7 +760,7 @@ checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ "darling_core", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -793,7 +793,7 @@ checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -994,7 +994,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -1006,7 +1006,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -1018,7 +1018,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -1083,7 +1083,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -1374,7 +1374,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -1525,9 +1525,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.147" +version = "0.2.148" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" +checksum = "9cdc71e17332e86d2e1d38c1f99edcb6288ee11b815fb1a4b049eaa2114d369b" [[package]] name = "libloading" @@ -1575,9 +1575,9 @@ checksum = "1a9bad9f94746442c783ca431b22403b519cd7fbeed0533fdd6328b2f2212128" [[package]] name = "local-ip-address" -version = "0.5.4" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "885efb07efcd6ae1c6af70be7565544121424fa9e5b1c3e4b58bbbf141a58cef" +checksum = "3fefe707432eb6bd4704b3dacfc87aab269d56667ad05dcd6869534e8890e767" dependencies = [ "libc", "neli", @@ -1738,7 +1738,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", "termcolor", "thiserror", ] @@ -1939,7 +1939,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -2062,7 +2062,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -2093,7 +2093,7 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -2223,9 +2223,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.66" +version = "1.0.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9" +checksum = "3d433d9f1a3e8c1263d9456598b16fec66f4acc9a74dacffd35c7bb09b3a1328" dependencies = [ "unicode-ident", ] @@ -2724,14 +2724,14 @@ checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] name = "serde_json" -version = "1.0.106" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cc66a619ed80bf7a0f6b17dd063a84b88f6dea1813737cf469aef1d081142c2" +checksum = "6b420ce6e3d8bd882e9b243c6eed35dbc9a6110c9769e74b584e0d68d1f20c65" dependencies = [ "itoa", "ryu", @@ -2756,7 +2756,7 @@ checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -2806,7 +2806,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -2928,9 +2928,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.32" +version = "2.0.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "239814284fd6f1a4ffe4ca893952cdd93c224b6a1571c9a9eadd670295c0c9e2" +checksum = "9caece70c63bfba29ec2fed841a09851b14a235c60010fa4de58089b6c025668" dependencies = [ "proc-macro2", "quote", @@ -2994,7 +2994,7 @@ checksum = "49922ecae66cc8a249b77e68d1d0623c1b2c514f0060c27cdc68bd62a1219d35" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -3076,7 +3076,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", ] [[package]] @@ -3358,9 +3358,9 @@ checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" [[package]] name = "unicode-ident" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-normalization" @@ -3456,7 +3456,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", "wasm-bindgen-shared", ] @@ -3490,7 +3490,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.32", + "syn 2.0.33", "wasm-bindgen-backend", "wasm-bindgen-shared", ] From 0ff86dab2d4d47bed25e7a9369aa782f8268a96c Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 09:38:54 +0200 Subject: [PATCH 0085/1297] chore: update cargo deps --- Cargo.lock | 21 ++++++++++++++++----- Cargo.toml | 2 +- packages/configuration/Cargo.toml | 2 +- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0f04f4bad..21b547ca8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2194,7 +2194,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" dependencies = [ "once_cell", - "toml_edit", + "toml_edit 0.19.15", ] [[package]] @@ -3124,14 +3124,14 @@ dependencies = [ [[package]] name = "toml" -version = "0.7.8" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd79e69d3b627db300ff956027cc6c3798cef26d22526befdfcd12feeb6d2257" +checksum = "c226a7bba6d859b63c92c4b4fe69c5b6b72d0cb897dbc8e6012298e6154cb56e" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit", + "toml_edit 0.20.0", ] [[package]] @@ -3148,6 +3148,17 @@ name = "toml_edit" version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap 2.0.0", + "toml_datetime", + "winnow", +] + +[[package]] +name = "toml_edit" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ff63e60a958cefbb518ae1fd6566af80d9d4be430a33f3723dfc47d1d411d95" dependencies = [ "indexmap 2.0.0", "serde", @@ -3211,7 +3222,7 @@ dependencies = [ "serde", "serde_with", "thiserror", - "toml 0.7.8", + "toml 0.8.0", "torrust-tracker-located-error", "torrust-tracker-primitives", "uuid", diff --git a/Cargo.toml b/Cargo.toml index a26bed8da..c22f68802 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,7 +66,7 @@ axum = "0.6" axum-server = { version = "0.5", features = ["tls-rustls"] } axum-client-ip = "0.4" tower-http = { version = "0.4", features = ["compression-full"] } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.6", path = "contrib/bencode"} +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.6", path = "contrib/bencode" } torrust-tracker-primitives = { version = "3.0.0-alpha.6", path = "packages/primitives" } torrust-tracker-configuration = { version = "3.0.0-alpha.6", path = "packages/configuration" } torrust-tracker-located-error = { version = "3.0.0-alpha.6", path = "packages/located-error" } diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 4a3028f18..2592268e6 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -19,7 +19,7 @@ version.workspace = true serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" config = "0.13" -toml = "0.7" +toml = "0.8" log = { version = "0.4", features = ["release_max_level_info"] } thiserror = "1.0" torrust-tracker-primitives = { version = "3.0.0-alpha.6", path = "../primitives" } From 4bd88e7e06f9ca430f634d9b3da1f8b7237011a2 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 09:44:19 +0200 Subject: [PATCH 0086/1297] style: format .toml files --- .vscode/extensions.json | 3 +- .vscode/settings.json | 5 ++ Cargo.toml | 78 ++++++++----------- contrib/bencode/Cargo.toml | 13 ++-- packages/configuration/Cargo.toml | 13 ++-- packages/located-error/Cargo.toml | 5 +- packages/primitives/Cargo.toml | 7 +- packages/test-helpers/Cargo.toml | 4 +- rustfmt.toml | 4 +- .../config/tracker.container.mysql.toml | 25 +++--- .../config/tracker.container.sqlite3.toml | 25 +++--- .../config/tracker.development.sqlite3.toml | 24 +++--- 12 files changed, 94 insertions(+), 112 deletions(-) diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 11d11a5c5..934a43eb8 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,6 +1,7 @@ { "recommendations": [ "streetsidesoftware.code-spell-checker", - "rust-lang.rust-analyzer" + "rust-lang.rust-analyzer", + "tamasfe.even-better-toml" ] } \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 3bf0969e9..661243fbe 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -20,4 +20,9 @@ "-W", "clippy::pedantic", ], + "evenBetterToml.formatter.allowedBlankLines": 1, + "evenBetterToml.formatter.columnWidth": 130, + "evenBetterToml.formatter.trailingNewline": true, + "evenBetterToml.formatter.reorderKeys": true, + "evenBetterToml.formatter.reorderArrays": true, } \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index c22f68802..705fd116a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,89 +14,73 @@ repository.workspace = true rust-version.workspace = true version.workspace = true - [workspace.package] -authors = [ - "Nautilus Cyberneering , Mick van Dijke ", -] +authors = ["Nautilus Cyberneering , Mick van Dijke "] categories = ["network-programming", "web-programming"] description = "A feature rich BitTorrent tracker." documentation = "https://docs.rs/crate/torrust-tracker/" edition = "2021" homepage = "https://torrust.com/" -keywords = ["bittorrent", "tracker", "file-sharing", "peer-to-peer", "torrent"] +keywords = ["bittorrent", "file-sharing", "peer-to-peer", "torrent", "tracker"] license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" version = "3.0.0-alpha.6" - [dependencies] -tokio = { version = "1.29", features = [ - "rt-multi-thread", - "net", - "sync", - "macros", - "signal", -] } -serde = { version = "1.0", features = ["derive"] } -serde_bencode = "^0.2" -serde_json = "1.0" -serde_with = "3.2" -percent-encoding = "2.2" +aquatic_udp_protocol = "0.8" +async-trait = "0.1" +axum = "0.6" +axum-client-ip = "0.4" +axum-server = { version = "0.5", features = ["tls-rustls"] } binascii = "0.1" -lazy_static = "1.4" -openssl = { version = "0.10", features = ["vendored"] } +chrono = { version = "0.4", default-features = false, features = ["clock"] } config = "0.13" -log = { version = "0.4", features = ["release_max_level_info"] } +derive_more = "0.99" fern = "0.6" -chrono = { version = "0.4", default-features = false, features = ["clock"] } +futures = "0.3" +hyper = "0.14" +lazy_static = "1.4" +log = { version = "0.4", features = ["release_max_level_info"] } +multimap = "0.9" +openssl = { version = "0.10", features = ["vendored"] } +percent-encoding = "2.2" r2d2 = "0.8" r2d2_mysql = "24.0" r2d2_sqlite = { version = "0.22", features = ["bundled"] } rand = "0.8" -derive_more = "0.99" +serde = { version = "1.0", features = ["derive"] } +serde_bencode = "^0.2" +serde_json = "1.0" +serde_with = "3.2" thiserror = "1.0" -futures = "0.3" -async-trait = "0.1" -aquatic_udp_protocol = "0.8" -uuid = { version = "1", features = ["v4"] } -axum = "0.6" -axum-server = { version = "0.5", features = ["tls-rustls"] } -axum-client-ip = "0.4" -tower-http = { version = "0.4", features = ["compression-full"] } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.6", path = "contrib/bencode" } -torrust-tracker-primitives = { version = "3.0.0-alpha.6", path = "packages/primitives" } +tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-configuration = { version = "3.0.0-alpha.6", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.6", path = "contrib/bencode" } torrust-tracker-located-error = { version = "3.0.0-alpha.6", path = "packages/located-error" } -multimap = "0.9" -hyper = "0.14" +torrust-tracker-primitives = { version = "3.0.0-alpha.6", path = "packages/primitives" } +tower-http = { version = "0.4", features = ["compression-full"] } +uuid = { version = "1", features = ["v4"] } [dev-dependencies] +local-ip-address = "0.5" mockall = "0.11" reqwest = { version = "0.11.18", features = ["json"] } -serde_urlencoded = "0.7" -serde_repr = "0.1" serde_bytes = "0.11" -local-ip-address = "0.5" +serde_repr = "0.1" +serde_urlencoded = "0.7" torrust-tracker-test-helpers = { version = "3.0.0-alpha.6", path = "packages/test-helpers" } [workspace] -members = [ - "contrib/bencode", - "packages/configuration", - "packages/primitives", - "packages/test-helpers", - "packages/located-error", -] +members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] [profile.dev] debug = 1 -opt-level = 1 lto = "thin" +opt-level = 1 [profile.release] debug = 1 -opt-level = 3 lto = "fat" +opt-level = 3 diff --git a/contrib/bencode/Cargo.toml b/contrib/bencode/Cargo.toml index 2aed18409..3918aa6ba 100644 --- a/contrib/bencode/Cargo.toml +++ b/contrib/bencode/Cargo.toml @@ -1,14 +1,12 @@ [package] -name = "torrust-tracker-contrib-bencode" description = "(contrib) Efficient decoding and encoding for bencode." -keywords = ["library", "contrib", "bencode"] +keywords = ["bencode", "contrib", "library"] +name = "torrust-tracker-contrib-bencode" readme = "README.md" -authors = [ - "Nautilus Cyberneering , Andrew ", -] -repository = "https://github.com/torrust/bittorrent-infrastructure-project" +authors = ["Nautilus Cyberneering , Andrew "] license = "Apache-2.0" +repository = "https://github.com/torrust/bittorrent-infrastructure-project" documentation.workspace = true edition.workspace = true @@ -17,7 +15,6 @@ publish.workspace = true rust-version.workspace = true version.workspace = true - [dependencies] error-chain = "0.12" @@ -29,5 +26,5 @@ name = "test" path = "test/mod.rs" [[bench]] -name = "bencode_benchmark" harness = false +name = "bencode_benchmark" diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 2592268e6..e5b9e31cd 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -1,7 +1,7 @@ [package] -name = "torrust-tracker-configuration" description = "A library to provide configuration to the Torrust Tracker." -keywords = ["library", "config", "settings"] +keywords = ["config", "library", "settings"] +name = "torrust-tracker-configuration" readme = "README.md" authors.workspace = true @@ -14,16 +14,15 @@ repository.workspace = true rust-version.workspace = true version.workspace = true - [dependencies] -serde = { version = "1.0", features = ["derive"] } -serde_with = "3.2" config = "0.13" -toml = "0.8" log = { version = "0.4", features = ["release_max_level_info"] } +serde = { version = "1.0", features = ["derive"] } +serde_with = "3.2" thiserror = "1.0" -torrust-tracker-primitives = { version = "3.0.0-alpha.6", path = "../primitives" } +toml = "0.8" torrust-tracker-located-error = { version = "3.0.0-alpha.6", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.6", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index ea0b1639a..b4c813df3 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -1,7 +1,7 @@ [package] -name = "torrust-tracker-located-error" description = "A library to provide error decorator with the location and the source of the original error." -keywords = ["library", "helper", "errors"] +keywords = ["errors", "helper", "library"] +name = "torrust-tracker-located-error" readme = "README.md" authors.workspace = true @@ -14,7 +14,6 @@ repository.workspace = true rust-version.workspace = true version.workspace = true - [dependencies] log = { version = "0.4", features = ["release_max_level_info"] } diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index 9eb092e1c..ce6c20ff0 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -1,7 +1,7 @@ [package] -name = "torrust-tracker-primitives" description = "A library with the primitive types shared by the Torrust tracker packages." -keywords = ["library", "api", "primitives"] +keywords = ["api", "library", "primitives"] +name = "torrust-tracker-primitives" readme = "README.md" authors.workspace = true @@ -14,7 +14,6 @@ repository.workspace = true rust-version.workspace = true version.workspace = true - [dependencies] -serde = { version = "1.0", features = ["derive"] } derive_more = "0.99" +serde = { version = "1.0", features = ["derive"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index bec9bb216..c01abed2e 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -1,7 +1,7 @@ [package] -name = "torrust-tracker-test-helpers" description = "A library providing helpers for testing the Torrust tracker." -keywords = ["library", "helper", "testing"] +keywords = ["helper", "library", "testing"] +name = "torrust-tracker-test-helpers" readme = "README.md" authors.workspace = true diff --git a/rustfmt.toml b/rustfmt.toml index abbed5eda..76046e6f4 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,3 +1,3 @@ -max_width = 130 -imports_granularity = "Module" group_imports = "StdExternalCrate" +imports_granularity = "Module" +max_width = 130 diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml index 60da25db2..fb9cbf789 100644 --- a/share/default/config/tracker.container.mysql.toml +++ b/share/default/config/tracker.container.mysql.toml @@ -1,36 +1,35 @@ -log_level = "info" -mode = "public" +announce_interval = 120 db_driver = "MySQL" db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" -announce_interval = 120 +external_ip = "0.0.0.0" +inactive_peer_cleanup_interval = 600 +log_level = "info" +max_peer_timeout = 900 min_announce_interval = 120 +mode = "public" on_reverse_proxy = false -external_ip = "0.0.0.0" -tracker_usage_statistics = true persistent_torrent_completed_stat = false -max_peer_timeout = 900 -inactive_peer_cleanup_interval = 600 remove_peerless_torrents = true +tracker_usage_statistics = true [[udp_trackers]] -enabled = false bind_address = "0.0.0.0:6969" +enabled = false [[http_trackers]] -enabled = false bind_address = "0.0.0.0:7070" -ssl_enabled = false +enabled = false ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" [http_api] -enabled = true bind_address = "0.0.0.0:1212" -ssl_enabled = false +enabled = true ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" - # Please override the admin token setting the # `TORRUST_TRACKER_API_ADMIN_TOKEN` # environmental variable! diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml index 64cf75518..54cfd4023 100644 --- a/share/default/config/tracker.container.sqlite3.toml +++ b/share/default/config/tracker.container.sqlite3.toml @@ -1,36 +1,35 @@ -log_level = "info" -mode = "public" +announce_interval = 120 db_driver = "Sqlite3" db_path = "/var/lib/torrust/tracker/database/sqlite3.db" -announce_interval = 120 +external_ip = "0.0.0.0" +inactive_peer_cleanup_interval = 600 +log_level = "info" +max_peer_timeout = 900 min_announce_interval = 120 +mode = "public" on_reverse_proxy = false -external_ip = "0.0.0.0" -tracker_usage_statistics = true persistent_torrent_completed_stat = false -max_peer_timeout = 900 -inactive_peer_cleanup_interval = 600 remove_peerless_torrents = true +tracker_usage_statistics = true [[udp_trackers]] -enabled = false bind_address = "0.0.0.0:6969" +enabled = false [[http_trackers]] -enabled = false bind_address = "0.0.0.0:7070" -ssl_enabled = false +enabled = false ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" [http_api] -enabled = true bind_address = "0.0.0.0:1212" -ssl_enabled = false +enabled = true ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" - # Please override the admin token setting the # `TORRUST_TRACKER_API_ADMIN_TOKEN` # environmental variable! diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index be1877469..20f95ac5d 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -1,33 +1,33 @@ -log_level = "info" -mode = "public" +announce_interval = 120 db_driver = "Sqlite3" db_path = "./storage/tracker/lib/database/sqlite3.db" -announce_interval = 120 +external_ip = "0.0.0.0" +inactive_peer_cleanup_interval = 600 +log_level = "info" +max_peer_timeout = 900 min_announce_interval = 120 +mode = "public" on_reverse_proxy = false -external_ip = "0.0.0.0" -tracker_usage_statistics = true persistent_torrent_completed_stat = false -max_peer_timeout = 900 -inactive_peer_cleanup_interval = 600 remove_peerless_torrents = true +tracker_usage_statistics = true [[udp_trackers]] -enabled = false bind_address = "0.0.0.0:6969" +enabled = false [[http_trackers]] -enabled = false bind_address = "0.0.0.0:7070" -ssl_enabled = false +enabled = false ssl_cert_path = "" +ssl_enabled = false ssl_key_path = "" [http_api] -enabled = true bind_address = "127.0.0.1:1212" -ssl_enabled = false +enabled = true ssl_cert_path = "" +ssl_enabled = false ssl_key_path = "" [http_api.access_tokens] From a005af2a056f9fd2fc287a855f1e2797faf00db0 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 12:49:30 +0200 Subject: [PATCH 0087/1297] Revert "chore: bump codecov/codecov-action from 3 to 4" This reverts commit 7d5acd23210c5d2bbba114f4af665d16faca907b. --- .github/workflows/coverage.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 4d4054026..cf7eb6f6d 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -83,7 +83,7 @@ jobs: - id: upload name: Upload Coverage Report - uses: codecov/codecov-action@v4 + uses: codecov/codecov-action@v3 with: token: ${{ secrets.CODECOV_TOKEN }} files: ${{ steps.coverage.outputs.report }} From ab0dd30d8282f313006c866fe2d301daf9f6a7b8 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 12:47:10 +0200 Subject: [PATCH 0088/1297] docs: update release process --- docs/release_process.md | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/docs/release_process.md b/docs/release_process.md index cc401c11a..4b58d7ca8 100644 --- a/docs/release_process.md +++ b/docs/release_process.md @@ -1,24 +1,30 @@ -# Torrust Tracker Release Process (draft) +# Torrust Tracker Release Process (draft 2) The purpose of this document is to describe the release process. ## Overview -Torrust Tracker is published in this order: +Torrust Tracker is published according to this protocol: -1. `develop` branch is ready for publishing. -2. create `release: version (semantic version)` commit. -3. push release commit to `main` branch. -4. check all status checks succeed for `main` branch. -5. push `main` branch to `releases\v(semantic version)` branch. -6. check all status checks success for `releases\v(semantic version)` branch. -7. create signed `v(semantic version)` tag. -8. create github release from `v(semantic version)` tag. -9. merge `main` branch into `develop` branch. +0. After release create new pull request into `develop` branch: + +- The `develop` branch has the (semantic version) suffix `-develop`. +- The version is bumped according to releases, new features, and breaking changes. + +- [ ] `develop` is ready for branching for a release. +- [ ] force-push develop to `staging` branch. +- [ ] commit `release: version (semantic version)`, removing the `-develop` suffix. +- [ ] create pull request to merge `staging` into `main` branch. +- [ ] check all status checks succeed for `main` branch. +- [ ] push `main` branch to `releases\v(semantic version)` branch. +- [ ] check all status checks success for `releases\v(semantic version)` branch. +- [ ] create signed `v(semantic version)` tag from `releases\v(semantic version) HEAD`. +- [ ] create github release from `v(semantic version)` tag. +- [ ] merge the `main` branch back into `develop` branch, assuring that the (semantic version) has the suffix `-develop`. - At step `1.`, `develop` is automatically published to `dockerhub`. - At step `3.`, `main` is automatically published to `dockerhub`. -- At step `5.`, `releases\v(semantic version)` is automatically published to `dockerhub` and `crate.io`. +- At step `6.`, `releases\v(semantic version)` is automatically published to `dockerhub` and `crate.io`. ## Development Branch From fc7cad0e72627046d5f39b98c74335cf31674278 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 17:30:00 +0200 Subject: [PATCH 0089/1297] chore: bump alpha version to 3.0.0-alpha.7-develop add version suffix to match release process expectations --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 21b547ca8..b67a3434f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3169,7 +3169,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.6" +version = "3.0.0-alpha.7-develop" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3215,7 +3215,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.6" +version = "3.0.0-alpha.7-develop" dependencies = [ "config", "log", @@ -3230,7 +3230,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.6" +version = "3.0.0-alpha.7-develop" dependencies = [ "criterion", "error-chain", @@ -3238,7 +3238,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.6" +version = "3.0.0-alpha.7-develop" dependencies = [ "log", "thiserror", @@ -3246,7 +3246,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.6" +version = "3.0.0-alpha.7-develop" dependencies = [ "derive_more", "serde", @@ -3254,7 +3254,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.6" +version = "3.0.0-alpha.7-develop" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index 705fd116a..6a7471550 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.6" +version = "3.0.0-alpha.7-develop" [dependencies] aquatic_udp_protocol = "0.8" @@ -56,10 +56,10 @@ serde_json = "1.0" serde_with = "3.2" thiserror = "1.0" tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-configuration = { version = "3.0.0-alpha.6", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.6", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.6", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.6", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.7-develop", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.7-develop", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.7-develop", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.7-develop", path = "packages/primitives" } tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } @@ -70,7 +70,7 @@ reqwest = { version = "0.11.18", features = ["json"] } serde_bytes = "0.11" serde_repr = "0.1" serde_urlencoded = "0.7" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.6", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.7-develop", path = "packages/test-helpers" } [workspace] members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] diff --git a/README.md b/README.md index 551471914..e8f54bb6e 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.6/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.6/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.6/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.7-develop/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.7-develop/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.7-develop/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.6/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.7-develop/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index e5b9e31cd..9057e85df 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -21,8 +21,8 @@ serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" thiserror = "1.0" toml = "0.8" -torrust-tracker-located-error = { version = "3.0.0-alpha.6", path = "../located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.6", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.7-develop", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.7-develop", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index c01abed2e..49903213d 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.6", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.6", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.7-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.7-develop", path = "../primitives" } From a9b199d908b267f786f52aa7d0675ebe2bc6fd15 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 18:34:25 +0200 Subject: [PATCH 0090/1297] release: version 3.0.0-alpha.7 --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b67a3434f..ba179c9cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3169,7 +3169,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.7" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3215,7 +3215,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.7" dependencies = [ "config", "log", @@ -3230,7 +3230,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.7" dependencies = [ "criterion", "error-chain", @@ -3238,7 +3238,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.7" dependencies = [ "log", "thiserror", @@ -3246,7 +3246,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.7" dependencies = [ "derive_more", "serde", @@ -3254,7 +3254,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.7" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index 6a7471550..ee908ed5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.7" [dependencies] aquatic_udp_protocol = "0.8" @@ -56,10 +56,10 @@ serde_json = "1.0" serde_with = "3.2" thiserror = "1.0" tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-configuration = { version = "3.0.0-alpha.7-develop", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.7-develop", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.7-develop", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.7-develop", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.7", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.7", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.7", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.7", path = "packages/primitives" } tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } @@ -70,7 +70,7 @@ reqwest = { version = "0.11.18", features = ["json"] } serde_bytes = "0.11" serde_repr = "0.1" serde_urlencoded = "0.7" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.7-develop", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.7", path = "packages/test-helpers" } [workspace] members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] diff --git a/README.md b/README.md index e8f54bb6e..51839d10f 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.7-develop/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.7-develop/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.7-develop/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.7/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.7/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.7/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.7-develop/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.7/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 9057e85df..25a4639eb 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -21,8 +21,8 @@ serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" thiserror = "1.0" toml = "0.8" -torrust-tracker-located-error = { version = "3.0.0-alpha.7-develop", path = "../located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.7-develop", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.7", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.7", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 49903213d..e4a60f5c2 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.7-develop", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.7-develop", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.7", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.7", path = "../primitives" } From 744f51a258eb731189deb909f2e9f36fd4a87247 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 20:53:00 +0200 Subject: [PATCH 0091/1297] version: bump version --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b67a3434f..976e9b55d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3169,7 +3169,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.8-develop" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3215,7 +3215,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.8-develop" dependencies = [ "config", "log", @@ -3230,7 +3230,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.8-develop" dependencies = [ "criterion", "error-chain", @@ -3238,7 +3238,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.8-develop" dependencies = [ "log", "thiserror", @@ -3246,7 +3246,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.8-develop" dependencies = [ "derive_more", "serde", @@ -3254,7 +3254,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.8-develop" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index 6a7471550..0cb119a19 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.7-develop" +version = "3.0.0-alpha.8-develop" [dependencies] aquatic_udp_protocol = "0.8" @@ -56,10 +56,10 @@ serde_json = "1.0" serde_with = "3.2" thiserror = "1.0" tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-configuration = { version = "3.0.0-alpha.7-develop", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.7-develop", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.7-develop", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.7-develop", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.8-develop", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.8-develop", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.8-develop", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.8-develop", path = "packages/primitives" } tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } @@ -70,7 +70,7 @@ reqwest = { version = "0.11.18", features = ["json"] } serde_bytes = "0.11" serde_repr = "0.1" serde_urlencoded = "0.7" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.7-develop", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.8-develop", path = "packages/test-helpers" } [workspace] members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] diff --git a/README.md b/README.md index e8f54bb6e..b5805446a 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.7-develop/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.7-develop/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.7-develop/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.8-develop/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.8-develop/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.8-develop/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.7-develop/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.8-develop/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 9057e85df..631362c07 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -21,8 +21,8 @@ serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" thiserror = "1.0" toml = "0.8" -torrust-tracker-located-error = { version = "3.0.0-alpha.7-develop", path = "../located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.7-develop", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.8-develop", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.8-develop", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 49903213d..0c85d31f6 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.7-develop", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.7-develop", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.8-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.8-develop", path = "../primitives" } From aafe394f3313eb1f23137fe66b6492485d125366 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 20:55:01 +0200 Subject: [PATCH 0092/1297] ci: fix deploymment workflow --- .github/workflows/deployment.yaml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 43bfe4784..ec349bf28 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -64,11 +64,10 @@ jobs: with: toolchain: stable - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} - - id: publish name: Publish Crates + env: + CARGO_REGISTRY_TOKEN: "${{ secrets.CARGO_REGISTRY_TOKEN }}" run: | cargo publish -p torrust-tracker-contrib-bencode cargo publish -p torrust-tracker-located-error From 4f4d1369889be18070b6509bcfc7c1f90ad4f6a8 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 20:57:38 +0200 Subject: [PATCH 0093/1297] docs: small style update to release process --- docs/release_process.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/release_process.md b/docs/release_process.md index 4b58d7ca8..e29836191 100644 --- a/docs/release_process.md +++ b/docs/release_process.md @@ -13,12 +13,12 @@ Torrust Tracker is published according to this protocol: - [ ] `develop` is ready for branching for a release. - [ ] force-push develop to `staging` branch. -- [ ] commit `release: version (semantic version)`, removing the `-develop` suffix. +- [ ] commit `release: version (semantic version)`, that removes the `-develop` suffix. - [ ] create pull request to merge `staging` into `main` branch. - [ ] check all status checks succeed for `main` branch. -- [ ] push `main` branch to `releases\v(semantic version)` branch. -- [ ] check all status checks success for `releases\v(semantic version)` branch. -- [ ] create signed `v(semantic version)` tag from `releases\v(semantic version) HEAD`. +- [ ] push `main` branch to `releases/(semantic version)` branch. +- [ ] check all status checks success for `releases/(semantic version)` branch. +- [ ] create signed `v(semantic version)` tag from `releases/(semantic version) HEAD`. - [ ] create github release from `v(semantic version)` tag. - [ ] merge the `main` branch back into `develop` branch, assuring that the (semantic version) has the suffix `-develop`. From 98261eabd67f7f835469d9eeb983e4cf80c7f2a7 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 15 Sep 2023 21:22:06 +0200 Subject: [PATCH 0094/1297] release: version 3.0.0-alpha.8 --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 976e9b55d..3c8169f50 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3169,7 +3169,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.8" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3215,7 +3215,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.8" dependencies = [ "config", "log", @@ -3230,7 +3230,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.8" dependencies = [ "criterion", "error-chain", @@ -3238,7 +3238,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.8" dependencies = [ "log", "thiserror", @@ -3246,7 +3246,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.8" dependencies = [ "derive_more", "serde", @@ -3254,7 +3254,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.8" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index 0cb119a19..f5ab5187c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.8" [dependencies] aquatic_udp_protocol = "0.8" @@ -56,10 +56,10 @@ serde_json = "1.0" serde_with = "3.2" thiserror = "1.0" tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-configuration = { version = "3.0.0-alpha.8-develop", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.8-develop", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.8-develop", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.8-develop", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.8", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.8", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.8", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.8", path = "packages/primitives" } tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } @@ -70,7 +70,7 @@ reqwest = { version = "0.11.18", features = ["json"] } serde_bytes = "0.11" serde_repr = "0.1" serde_urlencoded = "0.7" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.8-develop", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.8", path = "packages/test-helpers" } [workspace] members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] diff --git a/README.md b/README.md index b5805446a..b34168110 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.8-develop/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.8-develop/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.8-develop/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.8/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.8/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.8/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.8-develop/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.8/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 631362c07..53de593d2 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -21,8 +21,8 @@ serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" thiserror = "1.0" toml = "0.8" -torrust-tracker-located-error = { version = "3.0.0-alpha.8-develop", path = "../located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.8-develop", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.8", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.8", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 0c85d31f6..7dab50bad 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.8-develop", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.8-develop", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.8", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.8", path = "../primitives" } From 4e116f50bc5251e1abaa59d357864df339299453 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Sep 2023 12:24:28 +0200 Subject: [PATCH 0095/1297] github: add codeowners file --- .github/CODEOWNERS | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/CODEOWNERS diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..2ae8963e3 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +/.github/**/* @torrust/maintainers From 9fb75e4bb92ac5cf42a9e4b0ffa36f85cfd74b69 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Sep 2023 12:25:47 +0200 Subject: [PATCH 0096/1297] ci: secret checks were unnecessary --- .github/workflows/container.yaml | 27 +++++---------------------- .github/workflows/coverage.yaml | 18 ------------------ .github/workflows/deployment.yaml | 22 ++-------------------- 3 files changed, 7 insertions(+), 60 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index d107a0139..c33ea16c8 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -54,6 +54,7 @@ jobs: context: name: Context + needs: test runs-on: ubuntu-latest outputs: @@ -97,29 +98,11 @@ jobs: echo "On a Forked Repository. Will Not Continue" fi - secrets: - name: Secrets - needs: [test, context] - environment: dockerhub-torrust - if: needs.context.outputs.continue == 'true' - runs-on: ubuntu-latest - - outputs: - continue: ${{ steps.check.outputs.continue }} - - steps: - - id: check - name: Check - env: - DOCKER_HUB_ACCESS_TOKEN: "${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}" - if: "${{ env.DOCKER_HUB_ACCESS_TOKEN != '' }}" - run: echo "continue=true" >> $GITHUB_OUTPUT - publish_development: name: Publish (Development) environment: dockerhub-torrust - needs: [secrets, context] - if: needs.secrets.outputs.continue == 'true' && needs.context.outputs.type == 'development' + needs: context + if: needs.context.outputs.continue == 'true' && needs.context.outputs.type == 'development' runs-on: ubuntu-latest steps: @@ -156,8 +139,8 @@ jobs: publish_release: name: Publish (Release) environment: dockerhub-torrust - needs: [secrets, context] - if: needs.secrets.outputs.continue == 'true' && needs.context.outputs.type == 'release' + needs: context + if: needs.context.outputs.continue == 'true' && needs.context.outputs.type == 'release' runs-on: ubuntu-latest steps: diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index cf7eb6f6d..1e7dace66 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -12,27 +12,9 @@ env: CARGO_TERM_COLOR: always jobs: - secrets: - name: Secrets - environment: coverage - runs-on: ubuntu-latest - - outputs: - continue: ${{ steps.check.outputs.continue }} - - steps: - - id: check - name: Check - env: - CODECOV_TOKEN: "${{ secrets.CODECOV_TOKEN }}" - if: "${{ env.CODECOV_TOKEN != '' }}" - run: echo "continue=true" >> $GITHUB_OUTPUT - report: name: Report environment: coverage - needs: secrets - if: needs.secrets.outputs.continue == 'true' runs-on: ubuntu-latest env: CARGO_INCREMENTAL: "0" diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index ec349bf28..5df50a4b0 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -6,26 +6,8 @@ on: - "releases/**/*" jobs: - secrets: - name: Secrets - environment: crates-io-torrust - runs-on: ubuntu-latest - - outputs: - continue: ${{ steps.check.outputs.continue }} - - steps: - - id: check - name: Check - env: - CARGO_REGISTRY_TOKEN: "${{ secrets.CARGO_REGISTRY_TOKEN }}" - if: "${{ env.CARGO_REGISTRY_TOKEN != '' }}" - run: echo "continue=true" >> $GITHUB_OUTPUT - test: name: Test - needs: secrets - if: needs.secrets.outputs.continue == 'true' runs-on: ubuntu-latest strategy: @@ -49,7 +31,7 @@ jobs: publish: name: Publish - environment: crates-io-torrust + environment: deployment needs: test runs-on: ubuntu-latest @@ -67,7 +49,7 @@ jobs: - id: publish name: Publish Crates env: - CARGO_REGISTRY_TOKEN: "${{ secrets.CARGO_REGISTRY_TOKEN }}" + CARGO_REGISTRY_TOKEN: "${{ secrets.TORRUST_UPDATE_CARGO_REGISTRY_TOKEN }}" run: | cargo publish -p torrust-tracker-contrib-bencode cargo publish -p torrust-tracker-located-error From b990e777ca76fb0e8d135b4fa51359f809306f51 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Sep 2023 12:26:55 +0200 Subject: [PATCH 0097/1297] docs: update release process --- docs/release_process.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/release_process.md b/docs/release_process.md index e29836191..4b5e39b25 100644 --- a/docs/release_process.md +++ b/docs/release_process.md @@ -1,4 +1,4 @@ -# Torrust Tracker Release Process (draft 2) +# Torrust Tracker Release Process (v2.1.0-draft) The purpose of this document is to describe the release process. @@ -12,19 +12,20 @@ Torrust Tracker is published according to this protocol: - The version is bumped according to releases, new features, and breaking changes. - [ ] `develop` is ready for branching for a release. -- [ ] force-push develop to `staging` branch. +- [ ] force-push `develop` to `staging/main` branch. - [ ] commit `release: version (semantic version)`, that removes the `-develop` suffix. -- [ ] create pull request to merge `staging` into `main` branch. -- [ ] check all status checks succeed for `main` branch. -- [ ] push `main` branch to `releases/(semantic version)` branch. +- [ ] create pull request to merge `staging/main` into `main` branch. +- [ ] push `main` branch to `releases/v(semantic version)` branch. - [ ] check all status checks success for `releases/(semantic version)` branch. - [ ] create signed `v(semantic version)` tag from `releases/(semantic version) HEAD`. - [ ] create github release from `v(semantic version)` tag. -- [ ] merge the `main` branch back into `develop` branch, assuring that the (semantic version) has the suffix `-develop`. +- [ ] force-push `main` to `staging/develop` branch. +- [ ] commit `develop: bump version (semantic version)-develop`, that bumps the version and adds the `-develop` suffix. +- [ ] create pull request to merge `staging/develop` into `develop` branch. - At step `1.`, `develop` is automatically published to `dockerhub`. - At step `3.`, `main` is automatically published to `dockerhub`. -- At step `6.`, `releases\v(semantic version)` is automatically published to `dockerhub` and `crate.io`. +- At step `6.`, `releases/v(semantic version)` is automatically published to `dockerhub` and `crate.io`. ## Development Branch From de884dde58b73c3bf619d097fe0c5bfb83454f12 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Sep 2023 12:27:49 +0200 Subject: [PATCH 0098/1297] develop: bump version 3.0.0-alpha.9-develop --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 976e9b55d..f7f88c644 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3169,7 +3169,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.9-develop" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3215,7 +3215,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.9-develop" dependencies = [ "config", "log", @@ -3230,7 +3230,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.9-develop" dependencies = [ "criterion", "error-chain", @@ -3238,7 +3238,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.9-develop" dependencies = [ "log", "thiserror", @@ -3246,7 +3246,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.9-develop" dependencies = [ "derive_more", "serde", @@ -3254,7 +3254,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.9-develop" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index 0cb119a19..607ec3adb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.8-develop" +version = "3.0.0-alpha.9-develop" [dependencies] aquatic_udp_protocol = "0.8" @@ -56,10 +56,10 @@ serde_json = "1.0" serde_with = "3.2" thiserror = "1.0" tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-configuration = { version = "3.0.0-alpha.8-develop", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.8-develop", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.8-develop", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.8-develop", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.9-develop", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.9-develop", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.9-develop", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.9-develop", path = "packages/primitives" } tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } @@ -70,7 +70,7 @@ reqwest = { version = "0.11.18", features = ["json"] } serde_bytes = "0.11" serde_repr = "0.1" serde_urlencoded = "0.7" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.8-develop", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.9-develop", path = "packages/test-helpers" } [workspace] members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] diff --git a/README.md b/README.md index b5805446a..c07c2b7f7 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.8-develop/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.8-develop/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.8-develop/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.9-develop/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.9-develop/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.9-develop/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.8-develop/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.9-develop/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 631362c07..b9b4c50d8 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -21,8 +21,8 @@ serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" thiserror = "1.0" toml = "0.8" -torrust-tracker-located-error = { version = "3.0.0-alpha.8-develop", path = "../located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.8-develop", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.9-develop", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.9-develop", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 0c85d31f6..e367d07cd 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.8-develop", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.8-develop", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.9-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.9-develop", path = "../primitives" } From 82622c5d0f39801d1321b554a264826f9376a04d Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Sep 2023 13:10:43 +0200 Subject: [PATCH 0099/1297] chore: update cargo lockfile --- Cargo.lock | 54 +++++++++++++++++++++++++++--------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f7f88c644..afb4ef0b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -142,7 +142,7 @@ checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -292,7 +292,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -473,9 +473,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.30" +version = "0.4.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "defd4e7873dbddba6c7c91e199c7fcb946abc4a6a4ac3195400bcfb01b5de877" +checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" dependencies = [ "android-tzdata", "iana-time-zone", @@ -749,7 +749,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -760,7 +760,7 @@ checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ "darling_core", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -793,7 +793,7 @@ checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -994,7 +994,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -1006,7 +1006,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -1018,7 +1018,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -1083,7 +1083,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -1374,7 +1374,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -1738,7 +1738,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", "termcolor", "thiserror", ] @@ -1939,7 +1939,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -2062,7 +2062,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -2093,7 +2093,7 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -2724,7 +2724,7 @@ checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -2756,7 +2756,7 @@ checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -2806,7 +2806,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -2928,9 +2928,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.33" +version = "2.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9caece70c63bfba29ec2fed841a09851b14a235c60010fa4de58089b6c025668" +checksum = "59bf04c28bee9043ed9ea1e41afc0552288d3aba9c6efdd78903b802926f4879" dependencies = [ "proc-macro2", "quote", @@ -2994,7 +2994,7 @@ checksum = "49922ecae66cc8a249b77e68d1d0623c1b2c514f0060c27cdc68bd62a1219d35" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -3076,7 +3076,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", ] [[package]] @@ -3351,9 +3351,9 @@ dependencies = [ [[package]] name = "typenum" -version = "1.16.0" +version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" +checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" [[package]] name = "ucd-trie" @@ -3467,7 +3467,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", "wasm-bindgen-shared", ] @@ -3501,7 +3501,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.35", "wasm-bindgen-backend", "wasm-bindgen-shared", ] From c451a747b421c8b2157aac9ca32de77f9759b01c Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Sep 2023 13:55:28 +0200 Subject: [PATCH 0100/1297] docs: update release process --- docs/release_process.md | 103 +++++++++++++++++++++------------------- 1 file changed, 55 insertions(+), 48 deletions(-) diff --git a/docs/release_process.md b/docs/release_process.md index 4b5e39b25..1f81aea57 100644 --- a/docs/release_process.md +++ b/docs/release_process.md @@ -1,68 +1,75 @@ -# Torrust Tracker Release Process (v2.1.0-draft) +# Torrust Tracker Release Process (v2.2.0) -The purpose of this document is to describe the release process. +## Version: +> **The `[semantic version]` is bumped according to releases, new features, and breaking changes.** +> +> *The `develop` branch uses the (semantic version) suffix `-develop`.* -## Overview +## Process: -Torrust Tracker is published according to this protocol: +### 1. The `develop` branch is ready for a release. +The `develop` branch should have the version `[semantic version]-develop` that is ready to be released. -0. After release create new pull request into `develop` branch: +### 2. Stage `develop` HEAD for merging into the `main` branch: -- The `develop` branch has the (semantic version) suffix `-develop`. -- The version is bumped according to releases, new features, and breaking changes. +```sh +git fetch --all +git push --force torrust develop:staging/main +``` -- [ ] `develop` is ready for branching for a release. -- [ ] force-push `develop` to `staging/main` branch. -- [ ] commit `release: version (semantic version)`, that removes the `-develop` suffix. -- [ ] create pull request to merge `staging/main` into `main` branch. -- [ ] push `main` branch to `releases/v(semantic version)` branch. -- [ ] check all status checks success for `releases/(semantic version)` branch. -- [ ] create signed `v(semantic version)` tag from `releases/(semantic version) HEAD`. -- [ ] create github release from `v(semantic version)` tag. -- [ ] force-push `main` to `staging/develop` branch. -- [ ] commit `develop: bump version (semantic version)-develop`, that bumps the version and adds the `-develop` suffix. -- [ ] create pull request to merge `staging/develop` into `develop` branch. +### 3. Create Release Commit: -- At step `1.`, `develop` is automatically published to `dockerhub`. -- At step `3.`, `main` is automatically published to `dockerhub`. -- At step `6.`, `releases/v(semantic version)` is automatically published to `dockerhub` and `crate.io`. +```sh +git stash +git switch staging/main +# change `[semantic version]-develop` to `[semantic version]`. +git add -A +git commit -m "release: version [semantic version]" +git push torrust +``` -## Development Branch +### 4. Create and Merge Pull Request from `staging/main` into `main` branch. +This pull request merges the new version into the `main` branch. -The `develop` branch, the default branch for the repository is automatically published to dockerhub with the `develop` label. This process happens automatically when a pull request is merged in, and the `container.yaml` workflow is triggered. +### 5. Push new version from `main` HEAD to `releases/v[semantic version]` branch: -## Main Branch +```sh +git fetch --all +git push torrust main:releases/v[semantic version] +``` -The `main` branch is the staging branch for releases. +> **Check that the deployment is successful!** -A release commit needs to be made that prepares the repository for the release, this commit should include: +### 6. Create Release Tag: -- Changing the semantic version. -- Finalizing the release notes and changelog. +```sh +git switch releases/v[semantic version] +git tag --sign v[semantic version] +git push --tags torrust +``` -The title of the commit should be: `release: version (semantic version)`. +### 7. Create Release on Github from Tag. +This is for those who wish to download the source code. -This commit should be committed upon the head of the development branch, and pushed to the `main` branch. +### 8. Stage `main` HEAD for merging into the `develop` branch: +Merge release back into the develop branch. -Once the release has succeeded, the `main` branch should be merged back into the `develop` branch. +```sh +git fetch --all +git push --force torrust main:staging/develop +``` +### 9. Create Comment that bumps next development version: -## Releases Branch +```sh +git stash +git switch staging/main +# change `[semantic version]` to `(next)[semantic version]-develop`. +git add -A +git commit -m "develop: bump to version (next)[semantic version]-develop" +git push torrust +``` -According to the patten `releases/v(semantic version)`, the `main` branch head is published to here to trigger the deployment workflows. +### 10. Create and Merge Pull Request from `staging/develop` into `develop` branch. +This pull request merges the new release into the `develop` branch and bumps the version number. -The repository deployment environment for crates.io is only available for the `releases/**/*` patten of branches. -Once the publishing workflows have succeeded; we can make the git-tag. - -## Release Tag - -Create a Signed Tag with a short message in the form `v(semantic version)` and push it to the repository. - -## Github Release - -From the newly published tag, create a Github Release using the web-interface. - - -## Merge back into development branch - -After this is all successful, the `main` branch should be merged into the `develop` branch. From dd8675548a122557ca177a5f79fa2b43d105c419 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Sep 2023 15:10:51 +0200 Subject: [PATCH 0101/1297] release: version 3.0.0-alpha.9 --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index afb4ef0b8..f85b1dd02 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3169,7 +3169,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.9" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3215,7 +3215,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.9" dependencies = [ "config", "log", @@ -3230,7 +3230,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.9" dependencies = [ "criterion", "error-chain", @@ -3238,7 +3238,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.9" dependencies = [ "log", "thiserror", @@ -3246,7 +3246,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.9" dependencies = [ "derive_more", "serde", @@ -3254,7 +3254,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.9" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index 607ec3adb..f62d45799 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.9" [dependencies] aquatic_udp_protocol = "0.8" @@ -56,10 +56,10 @@ serde_json = "1.0" serde_with = "3.2" thiserror = "1.0" tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-configuration = { version = "3.0.0-alpha.9-develop", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.9-develop", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.9-develop", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.9-develop", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.9", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.9", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.9", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.9", path = "packages/primitives" } tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } @@ -70,7 +70,7 @@ reqwest = { version = "0.11.18", features = ["json"] } serde_bytes = "0.11" serde_repr = "0.1" serde_urlencoded = "0.7" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.9-develop", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.9", path = "packages/test-helpers" } [workspace] members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] diff --git a/README.md b/README.md index c07c2b7f7..b91a01e93 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.9-develop/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.9-develop/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.9-develop/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.9/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.9/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.9/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.9-develop/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.9/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index b9b4c50d8..1ce6a63a4 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -21,8 +21,8 @@ serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" thiserror = "1.0" toml = "0.8" -torrust-tracker-located-error = { version = "3.0.0-alpha.9-develop", path = "../located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.9-develop", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.9", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.9", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index e367d07cd..8ecf29676 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.9-develop", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.9-develop", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.9", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.9", path = "../primitives" } From cea471faad0c211d058eacd51dcc32d7d946c91b Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Sep 2023 16:53:35 +0200 Subject: [PATCH 0102/1297] ci: fix test in container workflow --- .github/workflows/container.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index c33ea16c8..884a15843 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -80,7 +80,7 @@ jobs: echo "continue=true" >> $GITHUB_OUTPUT echo "On \`develop\` Branch, Type: \`development\`" - elif [[ "${{ github.ref }}" =~ ^(refs\/heads\/releases\/)(v)(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$ ]]; then + elif [[ $(echo "${{ github.ref }}" | grep -P '^(refs\/heads\/releases\/)(v)(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$') ]]; then version=$(echo "${{ github.ref }}" | sed -n -E 's/^(refs\/heads\/releases\/)//p') echo "version=$version" >> $GITHUB_OUTPUT From dba065f08323fe5acb3943f5981b16a9eb0aa63a Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Sep 2023 16:56:52 +0200 Subject: [PATCH 0103/1297] docs: minor changes to release process --- docs/release_process.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/release_process.md b/docs/release_process.md index 1f81aea57..d5d945694 100644 --- a/docs/release_process.md +++ b/docs/release_process.md @@ -1,4 +1,4 @@ -# Torrust Tracker Release Process (v2.2.0) +# Torrust Tracker Release Process (v2.2.1) ## Version: > **The `[semantic version]` is bumped according to releases, new features, and breaking changes.** @@ -29,6 +29,9 @@ git push torrust ``` ### 4. Create and Merge Pull Request from `staging/main` into `main` branch. + +Pull request title format: "Release Version `[semantic version]`". + This pull request merges the new version into the `main` branch. ### 5. Push new version from `main` HEAD to `releases/v[semantic version]` branch: @@ -70,6 +73,7 @@ git push torrust ``` ### 10. Create and Merge Pull Request from `staging/develop` into `develop` branch. -This pull request merges the new release into the `develop` branch and bumps the version number. +Pull request title format: "Version `[semantic version]` was Released". +This pull request merges the new release into the `develop` branch and bumps the version number. From fc610f6f4aaae5712241dc838ea65d923d361731 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Sep 2023 16:57:59 +0200 Subject: [PATCH 0104/1297] develop: bump version 3.0.0-alpha.10-develop --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index afb4ef0b8..a82f5f421 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3169,7 +3169,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.10-develop" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3215,7 +3215,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.10-develop" dependencies = [ "config", "log", @@ -3230,7 +3230,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.10-develop" dependencies = [ "criterion", "error-chain", @@ -3238,7 +3238,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.10-develop" dependencies = [ "log", "thiserror", @@ -3246,7 +3246,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.10-develop" dependencies = [ "derive_more", "serde", @@ -3254,7 +3254,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.10-develop" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index 607ec3adb..9c236f49c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.9-develop" +version = "3.0.0-alpha.10-develop" [dependencies] aquatic_udp_protocol = "0.8" @@ -56,10 +56,10 @@ serde_json = "1.0" serde_with = "3.2" thiserror = "1.0" tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-configuration = { version = "3.0.0-alpha.9-develop", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.9-develop", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.9-develop", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.9-develop", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.10-develop", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.10-develop", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.10-develop", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.10-develop", path = "packages/primitives" } tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } @@ -70,7 +70,7 @@ reqwest = { version = "0.11.18", features = ["json"] } serde_bytes = "0.11" serde_repr = "0.1" serde_urlencoded = "0.7" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.9-develop", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.10-develop", path = "packages/test-helpers" } [workspace] members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] diff --git a/README.md b/README.md index c07c2b7f7..dbf030f9e 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.9-develop/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.9-develop/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.9-develop/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.10-develop/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.10-develop/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.10-develop/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.9-develop/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.10-develop/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index b9b4c50d8..48ef118f7 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -21,8 +21,8 @@ serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" thiserror = "1.0" toml = "0.8" -torrust-tracker-located-error = { version = "3.0.0-alpha.9-develop", path = "../located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.9-develop", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.10-develop", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.10-develop", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index e367d07cd..a1c2bad79 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.9-develop", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.9-develop", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.10-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.10-develop", path = "../primitives" } From 12ffcff58d878f4636736acf0b77ebeb5fb57ece Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Sep 2023 17:31:05 +0200 Subject: [PATCH 0105/1297] release: version 3.0.0-alpha.10 --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a82f5f421..b6b9370f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3169,7 +3169,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.10-develop" +version = "3.0.0-alpha.10" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3215,7 +3215,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.10-develop" +version = "3.0.0-alpha.10" dependencies = [ "config", "log", @@ -3230,7 +3230,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.10-develop" +version = "3.0.0-alpha.10" dependencies = [ "criterion", "error-chain", @@ -3238,7 +3238,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.10-develop" +version = "3.0.0-alpha.10" dependencies = [ "log", "thiserror", @@ -3246,7 +3246,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.10-develop" +version = "3.0.0-alpha.10" dependencies = [ "derive_more", "serde", @@ -3254,7 +3254,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.10-develop" +version = "3.0.0-alpha.10" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index 9c236f49c..abd293190 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.10-develop" +version = "3.0.0-alpha.10" [dependencies] aquatic_udp_protocol = "0.8" @@ -56,10 +56,10 @@ serde_json = "1.0" serde_with = "3.2" thiserror = "1.0" tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-configuration = { version = "3.0.0-alpha.10-develop", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.10-develop", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.10-develop", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.10-develop", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.10", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.10", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.10", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.10", path = "packages/primitives" } tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } @@ -70,7 +70,7 @@ reqwest = { version = "0.11.18", features = ["json"] } serde_bytes = "0.11" serde_repr = "0.1" serde_urlencoded = "0.7" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.10-develop", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.10", path = "packages/test-helpers" } [workspace] members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] diff --git a/README.md b/README.md index dbf030f9e..ac6a05492 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.10-develop/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.10-develop/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.10-develop/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.10/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.10/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.10/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.10-develop/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.10/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 48ef118f7..b21e64751 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -21,8 +21,8 @@ serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" thiserror = "1.0" toml = "0.8" -torrust-tracker-located-error = { version = "3.0.0-alpha.10-develop", path = "../located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.10-develop", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.10", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.10", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index a1c2bad79..170f532c8 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.10-develop", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.10-develop", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.10", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.10", path = "../primitives" } From ec8880380c58944cd45739f7eaeefb509f6759c0 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Sep 2023 23:07:52 +0200 Subject: [PATCH 0106/1297] develop: bump to version 3.0.0-alpha.11-develop --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b6b9370f4..a1a262b82 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3169,7 +3169,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.10" +version = "3.0.0-alpha.11-develop" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3215,7 +3215,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.10" +version = "3.0.0-alpha.11-develop" dependencies = [ "config", "log", @@ -3230,7 +3230,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.10" +version = "3.0.0-alpha.11-develop" dependencies = [ "criterion", "error-chain", @@ -3238,7 +3238,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.10" +version = "3.0.0-alpha.11-develop" dependencies = [ "log", "thiserror", @@ -3246,7 +3246,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.10" +version = "3.0.0-alpha.11-develop" dependencies = [ "derive_more", "serde", @@ -3254,7 +3254,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.10" +version = "3.0.0-alpha.11-develop" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index abd293190..a1b387292 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.10" +version = "3.0.0-alpha.11-develop" [dependencies] aquatic_udp_protocol = "0.8" @@ -56,10 +56,10 @@ serde_json = "1.0" serde_with = "3.2" thiserror = "1.0" tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-configuration = { version = "3.0.0-alpha.10", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.10", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.10", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.10", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.11-develop", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.11-develop", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.11-develop", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.11-develop", path = "packages/primitives" } tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } @@ -70,7 +70,7 @@ reqwest = { version = "0.11.18", features = ["json"] } serde_bytes = "0.11" serde_repr = "0.1" serde_urlencoded = "0.7" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.10", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.11-develop", path = "packages/test-helpers" } [workspace] members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] diff --git a/README.md b/README.md index ac6a05492..0aadb3a3f 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.10/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.10/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.10/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.11-develop/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.11-develop/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.11-develop/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.10/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.11-develop/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index b21e64751..bf13e457a 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -21,8 +21,8 @@ serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" thiserror = "1.0" toml = "0.8" -torrust-tracker-located-error = { version = "3.0.0-alpha.10", path = "../located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.10", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.11-develop", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.11-develop", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 170f532c8..31f6f61e6 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.10", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.10", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.11-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.11-develop", path = "../primitives" } From 4369cca0e1a1b81605912a846ac8765d5cbca36c Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 18 Sep 2023 10:42:13 +0200 Subject: [PATCH 0107/1297] release: version 3.0.0-alpha.11 --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a1a262b82..6e4f51bd0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3169,7 +3169,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.11-develop" +version = "3.0.0-alpha.11" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3215,7 +3215,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.11-develop" +version = "3.0.0-alpha.11" dependencies = [ "config", "log", @@ -3230,7 +3230,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.11-develop" +version = "3.0.0-alpha.11" dependencies = [ "criterion", "error-chain", @@ -3238,7 +3238,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.11-develop" +version = "3.0.0-alpha.11" dependencies = [ "log", "thiserror", @@ -3246,7 +3246,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.11-develop" +version = "3.0.0-alpha.11" dependencies = [ "derive_more", "serde", @@ -3254,7 +3254,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.11-develop" +version = "3.0.0-alpha.11" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index a1b387292..8c83d5834 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.11-develop" +version = "3.0.0-alpha.11" [dependencies] aquatic_udp_protocol = "0.8" @@ -56,10 +56,10 @@ serde_json = "1.0" serde_with = "3.2" thiserror = "1.0" tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-configuration = { version = "3.0.0-alpha.11-develop", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.11-develop", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.11-develop", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.11-develop", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.11", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.11", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.11", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.11", path = "packages/primitives" } tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } @@ -70,7 +70,7 @@ reqwest = { version = "0.11.18", features = ["json"] } serde_bytes = "0.11" serde_repr = "0.1" serde_urlencoded = "0.7" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.11-develop", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.11", path = "packages/test-helpers" } [workspace] members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] diff --git a/README.md b/README.md index 0aadb3a3f..e76659d5e 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.11-develop/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.11-develop/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.11-develop/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.11/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.11/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.11/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.11-develop/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.11/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index bf13e457a..cc300afe0 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -21,8 +21,8 @@ serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" thiserror = "1.0" toml = "0.8" -torrust-tracker-located-error = { version = "3.0.0-alpha.11-develop", path = "../located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.11-develop", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.11", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.11", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 31f6f61e6..85edb99af 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.11-develop", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.11-develop", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.11", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.11", path = "../primitives" } From a14bdc65a2a50ce1ce483409d17a4bba21d30863 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 18 Sep 2023 14:09:57 +0200 Subject: [PATCH 0108/1297] develop: bump to version 3.0.0-alpha.12-develop --- Cargo.lock | 12 ++++++------ Cargo.toml | 12 ++++++------ README.md | 8 ++++---- packages/configuration/Cargo.toml | 4 ++-- packages/test-helpers/Cargo.toml | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6e4f51bd0..7b6caf856 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3169,7 +3169,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.11" +version = "3.0.0-alpha.12-develop" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -3215,7 +3215,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.11" +version = "3.0.0-alpha.12-develop" dependencies = [ "config", "log", @@ -3230,7 +3230,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.11" +version = "3.0.0-alpha.12-develop" dependencies = [ "criterion", "error-chain", @@ -3238,7 +3238,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.11" +version = "3.0.0-alpha.12-develop" dependencies = [ "log", "thiserror", @@ -3246,7 +3246,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.11" +version = "3.0.0-alpha.12-develop" dependencies = [ "derive_more", "serde", @@ -3254,7 +3254,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.11" +version = "3.0.0-alpha.12-develop" dependencies = [ "lazy_static", "rand", diff --git a/Cargo.toml b/Cargo.toml index 8c83d5834..04761b07c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ license-file = "COPYRIGHT" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.11" +version = "3.0.0-alpha.12-develop" [dependencies] aquatic_udp_protocol = "0.8" @@ -56,10 +56,10 @@ serde_json = "1.0" serde_with = "3.2" thiserror = "1.0" tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-configuration = { version = "3.0.0-alpha.11", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.11", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.11", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.11", path = "packages/primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12-develop", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } @@ -70,7 +70,7 @@ reqwest = { version = "0.11.18", features = ["json"] } serde_bytes = "0.11" serde_repr = "0.1" serde_urlencoded = "0.7" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.11", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.12-develop", path = "packages/test-helpers" } [workspace] members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] diff --git a/README.md b/README.md index e76659d5e..4e244b292 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.11/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.11/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.11/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.12-develop/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.12-develop/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.12-develop/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.11/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.12-develop/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index cc300afe0..a6733ef3a 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -21,8 +21,8 @@ serde = { version = "1.0", features = ["derive"] } serde_with = "3.2" thiserror = "1.0" toml = "0.8" -torrust-tracker-located-error = { version = "3.0.0-alpha.11", path = "../located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.11", path = "../primitives" } +torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 85edb99af..2960c6fb9 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,5 +17,5 @@ version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.11", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.11", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } From f897f2f4bfb05e1f627bbc840b84c1d18c3d6726 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 18 Sep 2023 23:32:41 +0200 Subject: [PATCH 0109/1297] docs: fix docs.rs links in readme --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 4e244b292..e73829ed4 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,13 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md -[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.12-develop/torrust_tracker/servers/apis/v1 -[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.12-develop/torrust_tracker/servers/http -[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.12-develop/torrust_tracker/servers/udp +[api]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.12-develop/torrust_tracker/servers/apis/v1 +[API documentation]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT From cba4cda83610a1c28b977904ae7e4843c38999cb Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 18 Sep 2023 23:33:29 +0200 Subject: [PATCH 0110/1297] docs: fix little issues in release process --- docs/release_process.md | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/docs/release_process.md b/docs/release_process.md index d5d945694..73b0a8827 100644 --- a/docs/release_process.md +++ b/docs/release_process.md @@ -1,4 +1,4 @@ -# Torrust Tracker Release Process (v2.2.1) +# Torrust Tracker Release Process (v2.2.2) ## Version: > **The `[semantic version]` is bumped according to releases, new features, and breaking changes.** @@ -7,6 +7,20 @@ ## Process: +**Note**: this guide assumes that the your git `torrust` remote is like this: + +```sh +git remote show torrust +``` + +```s +* remote torrust + Fetch URL: git@github.com:torrust/torrust-tracker.git + Push URL: git@github.com:torrust/torrust-tracker.git +... +``` + + ### 1. The `develop` branch is ready for a release. The `develop` branch should have the version `[semantic version]-develop` that is ready to be released. @@ -22,6 +36,7 @@ git push --force torrust develop:staging/main ```sh git stash git switch staging/main +git reset --hard torrust/staging/main # change `[semantic version]-develop` to `[semantic version]`. git add -A git commit -m "release: version [semantic version]" @@ -65,7 +80,8 @@ git push --force torrust main:staging/develop ```sh git stash -git switch staging/main +git switch staging/develop +git reset --hard torrust/staging/develop # change `[semantic version]` to `(next)[semantic version]-develop`. git add -A git commit -m "develop: bump to version (next)[semantic version]-develop" From 36716f74f510ac69fb47345e51442702e7f6018d Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 19 Sep 2023 02:10:39 +0200 Subject: [PATCH 0111/1297] legal: clean up licensing documents --- COPYRIGHT | 664 +++++++++++++++++- Cargo.toml | 4 +- README.md | 30 +- .../licenses/LICENSE-AGPL_3_0 | 0 LICENSE-MIT_0 => docs/licenses/LICENSE-MIT_0 | 0 packages/configuration/Cargo.toml | 2 +- packages/located-error/Cargo.toml | 2 +- packages/primitives/Cargo.toml | 2 +- packages/test-helpers/Cargo.toml | 2 +- 9 files changed, 690 insertions(+), 16 deletions(-) rename LICENSE-AGPL_3_0 => docs/licenses/LICENSE-AGPL_3_0 (100%) rename LICENSE-MIT_0 => docs/licenses/LICENSE-MIT_0 (100%) diff --git a/COPYRIGHT b/COPYRIGHT index 6eef820ec..be3f7b28e 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -1,11 +1,661 @@ -Copyright 2023 in the Torrust-Tracker project are retained by their contributors. No -copyright assignment is required to contribute to the Torrust-Tracker project. + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 -Some files include explicit copyright notices and/or license notices. + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. -Except as otherwise noted (below and/or in individual files), Torrust-Tracker is -licensed under the GNU Affero General Public License, Version 3.0 . This license applies to all files in the Torrust-Tracker project, except as noted below. + Preamble -Except as otherwise noted (below and/or in individual files), Torrust-Tracker is licensed under the MIT-0 license for all commits made after 5 years of merging. This license applies to the version of the files merged into the Torrust-Tracker project at the time of merging, and does not apply to subsequent updates or revisions to those files. + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. -The contributors to the Torrust-Tracker project disclaim all liability for any damages or losses that may arise from the use of the project. + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/Cargo.toml b/Cargo.toml index 04761b07c..3c9354cae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ documentation.workspace = true edition.workspace = true homepage.workspace = true keywords.workspace = true -license-file.workspace = true +license.workspace = true publish.workspace = true repository.workspace = true rust-version.workspace = true @@ -22,7 +22,7 @@ documentation = "https://docs.rs/crate/torrust-tracker/" edition = "2021" homepage = "https://torrust.com/" keywords = ["bittorrent", "file-sharing", "peer-to-peer", "torrent", "tracker"] -license-file = "COPYRIGHT" +license = "AGPL-3.0-only" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" diff --git a/README.md b/README.md index e73829ed4..41a7ec40b 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,6 @@ __Torrust Tracker__, is a [BitTorrent][bittorrent] Tracker (a service that match - [BEP 27] : Private Torrents. - [BEP 48] : Tracker Protocol Extension: Scrape. - ## Getting Started ### Container Version @@ -120,7 +119,6 @@ The following services are provided by the default configuration: - API _(management)_ - `http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken`. - ## Documentation - [Management API (Version 1)][api] @@ -141,7 +139,29 @@ __How can you contribute?__ ## License -The project is licensed under a dual license. See [COPYRIGHT]. +**Copyright (c) 2023 The Torrust Developers.** + +This program is free software: you can redistribute it and/or modify it under the terms of the [GNU Affero General Public License][AGPL_3_0] as published by the [Free Software Foundation][FSF], version 3. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the [GNU Affero General Public License][AGPL_3_0] for more details. + +You should have received a copy of the *GNU Affero General Public License* along with this program. If not, see . + +Some files include explicit copyright notices and/or license notices. + +### Legacy Exception + +For prosperity, versions of Torrust Tracker that are older than five years are automatically granted the [MIT-0][MIT_0] license in addition to the existing [AGPL-3.0-only][AGPL_3_0] license. + +## Contributions + +The copyright of the Torrust Tracker is retained by the respective authors. + +**Contributors agree:** +- That all their contributions be granted a license(s) **compatible** with the [Torrust Trackers License](#License). +- That all contributors signal **clearly** and **explicitly** any other compilable licenses if they are not: *[AGPL-3.0-only with the legacy MIT-0 exception](#License)*. + +**The Torrust-Tracker project has no copyright assignment agreement.** ## Acknowledgments @@ -189,6 +209,10 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [discussions]: https://github.com/torrust/torrust-tracker/discussions [COPYRIGHT]: ./COPYRIGHT +[AGPL_3_0]: ./docs/licenses/LICENSE-AGPL_3_0 +[MIT_0]: ./docs/licenses/LICENSE-MIT_0 +[FSF]: https://www.fsf.org/ + [nautilus]: https://github.com/orgs/Nautilus-Cyberneering/ [Dutch Bits]: https://dutchbits.nl diff --git a/LICENSE-AGPL_3_0 b/docs/licenses/LICENSE-AGPL_3_0 similarity index 100% rename from LICENSE-AGPL_3_0 rename to docs/licenses/LICENSE-AGPL_3_0 diff --git a/LICENSE-MIT_0 b/docs/licenses/LICENSE-MIT_0 similarity index 100% rename from LICENSE-MIT_0 rename to docs/licenses/LICENSE-MIT_0 diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index a6733ef3a..94cf1d0f5 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -8,7 +8,7 @@ authors.workspace = true documentation.workspace = true edition.workspace = true homepage.workspace = true -license-file.workspace = true +license.workspace = true publish.workspace = true repository.workspace = true rust-version.workspace = true diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index b4c813df3..6bc219374 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -8,7 +8,7 @@ authors.workspace = true documentation.workspace = true edition.workspace = true homepage.workspace = true -license-file.workspace = true +license.workspace = true publish.workspace = true repository.workspace = true rust-version.workspace = true diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index ce6c20ff0..3fac88bef 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -8,7 +8,7 @@ authors.workspace = true documentation.workspace = true edition.workspace = true homepage.workspace = true -license-file.workspace = true +license.workspace = true publish.workspace = true repository.workspace = true rust-version.workspace = true diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 2960c6fb9..d428cbf3e 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -8,7 +8,7 @@ authors.workspace = true documentation.workspace = true edition.workspace = true homepage.workspace = true -license-file.workspace = true +license.workspace = true publish.workspace = true repository.workspace = true rust-version.workspace = true From 8a49a9497b5606b84ce67c4608ca713925b028c4 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 19 Sep 2023 11:07:18 +0200 Subject: [PATCH 0112/1297] docs: remove duplicate COPYRIGHT file --- COPYRIGHT | 661 ------------------------------------------------------ 1 file changed, 661 deletions(-) delete mode 100644 COPYRIGHT diff --git a/COPYRIGHT b/COPYRIGHT deleted file mode 100644 index be3f7b28e..000000000 --- a/COPYRIGHT +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. From bf269bcc3ee33b4512df8bc71b15fce0ec6d7cf6 Mon Sep 17 00:00:00 2001 From: Alex Wellnitz Date: Wed, 4 Oct 2023 00:36:37 +0200 Subject: [PATCH 0113/1297] fix: renaming yml to yaml --- .github/{dependabot.yml => dependabot.yaml} | 0 README.md | 1 + codecov.yml => codecov.yaml | 0 3 files changed, 1 insertion(+) rename .github/{dependabot.yml => dependabot.yaml} (100%) rename codecov.yml => codecov.yaml (100%) diff --git a/.github/dependabot.yml b/.github/dependabot.yaml similarity index 100% rename from .github/dependabot.yml rename to .github/dependabot.yaml diff --git a/README.md b/README.md index 41a7ec40b..b43db1316 100644 --- a/README.md +++ b/README.md @@ -219,3 +219,4 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [Naim A.]: https://github.com/naim94a/udpt [greatest-ape]: https://github.com/greatest-ape/aquatic [Power2All]: https://github.com/power2all + diff --git a/codecov.yml b/codecov.yaml similarity index 100% rename from codecov.yml rename to codecov.yaml From ae3fda61e9800c61555db1d822b060e6be31cfce Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 3 Oct 2023 13:58:29 +0200 Subject: [PATCH 0114/1297] chore: update dependencies --- Cargo.lock | 252 +++++++++++++++++++++++++++++------------------------ 1 file changed, 136 insertions(+), 116 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7b6caf856..142fa521e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -41,9 +41,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.0.5" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c378d78423fdad8089616f827526ee33c19f2fddbd5de1629152c9593ba4783" +checksum = "ea5d730647d4fadd988536d06fecce94b7b4f2a7efdae548f1cf4b63205518ab" dependencies = [ "memchr", ] @@ -92,9 +92,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstyle" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b84bf0a05bbb2a83e5eb6fa36bb6e87baa08193c35ff52bbf6b38d8af2890e46" +checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87" [[package]] name = "aquatic_udp_protocol" @@ -142,7 +142,7 @@ checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -292,7 +292,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -375,9 +375,9 @@ dependencies = [ [[package]] name = "brotli" -version = "3.3.4" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1a0b1dbcc8ae29329621f8d4f0d835787c1c38bb1401979b49d13b0b305ff68" +checksum = "516074a47ef4bce09577a3b379392300159ce5b1ba2e501ff1c819950066100f" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -386,9 +386,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "2.3.4" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b6561fd3f895a11e8f72af2cb7d22e08366bebc2b6b57f7744c4bda27034744" +checksum = "da74e2b81409b1b743f8f0c62cc6254afefb8b8e50bbfe3735550f7aeefa3448" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -524,18 +524,18 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.3" +version = "4.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84ed82781cea27b43c9b106a979fe450a13a31aab0500595fb3fc06616de08e6" +checksum = "d04704f56c2cde07f43e8e2c154b43f216dc5c92fc98ada720177362f953b956" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" -version = "4.4.2" +version = "4.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bb9faaa7c2ef94b2743a21f5a29e6f0010dff4caa69ac8e9d6cf8b6fa74da08" +checksum = "0e231faeaca65ebd1ea3c737966bf858971cd38c3849107aa3ea7de90a804e45" dependencies = [ "anstyle", "clap_lex", @@ -749,7 +749,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -760,7 +760,7 @@ checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ "darling_core", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -793,7 +793,7 @@ checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" dependencies = [ "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -847,9 +847,9 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.3" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "136526188508e25c6fef639d7927dfb3e0e3084488bf202267829cf7fc23dbdd" +checksum = "add4f07d43996f76ef320709726a556a9d4f965d9410d8d0271132d2f8293480" dependencies = [ "errno-dragonfly", "libc", @@ -890,9 +890,9 @@ checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" [[package]] name = "fastrand" -version = "2.0.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764" +checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" [[package]] name = "fern" @@ -994,7 +994,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -1006,7 +1006,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -1018,7 +1018,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -1083,7 +1083,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -1194,9 +1194,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.14.0" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" +checksum = "7dfda62a12f55daeae5015f81b0baea145391cb4520f86c248fc615d72640d12" dependencies = [ "ahash 0.8.3", "allocator-api2", @@ -1208,7 +1208,7 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7" dependencies = [ - "hashbrown 0.14.0", + "hashbrown 0.14.1", ] [[package]] @@ -1219,9 +1219,9 @@ checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" [[package]] name = "hermit-abi" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" +checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7" [[package]] name = "hex" @@ -1358,12 +1358,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.0.0" +version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" +checksum = "8adf3ddd720272c6ea8bf59463c04e0f93d0bbf7c5439b691bca2987e0270897" dependencies = [ "equivalent", - "hashbrown 0.14.0", + "hashbrown 0.14.1", "serde", ] @@ -1374,7 +1374,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -1569,15 +1569,15 @@ checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" [[package]] name = "linux-raw-sys" -version = "0.4.7" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a9bad9f94746442c783ca431b22403b519cd7fbeed0533fdd6328b2f2212128" +checksum = "3852614a3bd9ca9804678ba6be5e3b8ce76dfc902cae004e3e0c44051b6e88db" [[package]] name = "local-ip-address" -version = "0.5.5" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fefe707432eb6bd4704b3dacfc87aab269d56667ad05dcd6869534e8890e767" +checksum = "66357e687a569abca487dc399a9c9ac19beb3f13991ed49f00c144e02cbd42ab" dependencies = [ "libc", "neli", @@ -1612,15 +1612,15 @@ dependencies = [ [[package]] name = "matchit" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed1202b2a6f884ae56f04cff409ab315c5ce26b5e58d7412e484f01fd52f52ef" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" [[package]] name = "memchr" -version = "2.6.3" +version = "2.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f232d6ef707e1956a43342693d2a31e72989554d58299d7a88738cc95b0d35c" +checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167" [[package]] name = "memoffset" @@ -1738,7 +1738,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", "termcolor", "thiserror", ] @@ -1939,7 +1939,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -1950,9 +1950,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "300.1.3+3.1.2" +version = "300.1.5+3.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd2c101a165fff9935e34def4669595ab1c7847943c42be86e21503e482be107" +checksum = "559068e4c12950d7dcaa1857a61725c0d38d4fc03ff8e070ab31a75d6e316491" dependencies = [ "cc", ] @@ -2033,9 +2033,9 @@ checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" [[package]] name = "pest" -version = "2.7.3" +version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7a4d085fd991ac8d5b05a147b437791b4260b76326baf0fc60cf7c9c27ecd33" +checksum = "c022f1e7b65d6a24c0dbbd5fb344c66881bc01f3e5ae74a1c8100f2f985d98a4" dependencies = [ "memchr", "thiserror", @@ -2044,9 +2044,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.3" +version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2bee7be22ce7918f641a33f08e3f43388c7656772244e2bbb2477f44cc9021a" +checksum = "35513f630d46400a977c4cb58f78e1bfbe01434316e60c37d27b9ad6139c66d8" dependencies = [ "pest", "pest_generator", @@ -2054,22 +2054,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.3" +version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1511785c5e98d79a05e8a6bc34b4ac2168a0e3e92161862030ad84daa223141" +checksum = "bc9fc1b9e7057baba189b5c626e2d6f40681ae5b6eb064dc7c7834101ec8123a" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] name = "pest_meta" -version = "2.7.3" +version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b42f0394d3123e33353ca5e1e89092e533d2cc490389f2bd6131c43c634ebc5f" +checksum = "1df74e9e7ec4053ceb980e7c0c8bd3594e977fde1af91daba9c928e8e8c6708d" dependencies = [ "once_cell", "pest", @@ -2093,7 +2093,7 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -2329,9 +2329,9 @@ dependencies = [ [[package]] name = "rayon" -version = "1.7.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b" +checksum = "9c27db03db7734835b3f53954b534c91069375ce6ccaa2e065441e07d9b6cdb1" dependencies = [ "either", "rayon-core", @@ -2339,14 +2339,12 @@ dependencies = [ [[package]] name = "rayon-core" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d" +checksum = "5ce3fb6ad83f861aac485e76e1985cd109d9a3713802152be56c3b1f0e0658ed" dependencies = [ - "crossbeam-channel", "crossbeam-deque", "crossbeam-utils", - "num_cpus", ] [[package]] @@ -2360,9 +2358,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.9.5" +version = "1.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "697061221ea1b4a94a624f67d0ae2bfe4e22b8a17b6a192afb11046542cc8c47" +checksum = "ebee201405406dbf528b8b672104ae6d6d63e6d118cb10e4d51abbc7b58044ff" dependencies = [ "aho-corasick", "memchr", @@ -2372,9 +2370,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2f401f4955220693b56f8ec66ee9c78abffd8d1c4f23dc41a23839eb88f0795" +checksum = "59b23e92ee4318893fa3fe3e6fb365258efbfe6ac6ab30f090cdcbb7aa37efa9" dependencies = [ "aho-corasick", "memchr", @@ -2389,18 +2387,18 @@ checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" [[package]] name = "rend" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "581008d2099240d37fb08d77ad713bcaec2c4d89d50b5b21a8bb1996bbab68ab" +checksum = "a2571463863a6bd50c32f94402933f03457a3fbaf697a707c5be741e459f08fd" dependencies = [ "bytecheck", ] [[package]] name = "reqwest" -version = "0.11.20" +version = "0.11.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e9ad3fe7488d7e34558a2033d45a0c90b72d97b4f80705666fea71472e2e6a1" +checksum = "78fdbab6a7e1d7b13cc8ff10197f47986b41c639300cc3c8158cac7847c9bbef" dependencies = [ "base64 0.21.4", "bytes", @@ -2423,6 +2421,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", + "system-configuration", "tokio", "tokio-native-tls", "tower-service", @@ -2550,9 +2549,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.13" +version = "0.38.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7db8590df6dfcd144d22afd1b83b36c21a18d7cbc1dc4bb5295a8712e9eb662" +checksum = "d2f9da0cbd88f9f09e7814e388301c8414c51c62aa6ce1e4b5c551d49d96e531" dependencies = [ "bitflags 2.4.0", "errno", @@ -2584,9 +2583,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.101.5" +version = "0.101.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45a27e3b59326c16e23d30aeb7a36a24cc0d29e71d68ff611cdfb4a01d013bed" +checksum = "3c7d5dece342910d9ba34d259310cae3e0154b873b35408b787b59bce53d34fe" dependencies = [ "ring", "untrusted", @@ -2684,9 +2683,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" +checksum = "ad977052201c6de01a8ef2aa3378c4bd23217a056337d1d6da40468d267a4fb0" [[package]] name = "serde" @@ -2724,7 +2723,7 @@ checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -2756,7 +2755,7 @@ checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -2790,7 +2789,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.0.0", + "indexmap 2.0.2", "serde", "serde_json", "serde_with_macros", @@ -2806,14 +2805,14 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] name = "sha1" -version = "0.10.5" +version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" dependencies = [ "cfg-if", "cpufeatures", @@ -2822,9 +2821,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.10.7" +version = "0.10.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8" +checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" dependencies = [ "cfg-if", "cpufeatures", @@ -2863,9 +2862,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.11.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9" +checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a" [[package]] name = "socket2" @@ -2928,9 +2927,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.35" +version = "2.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59bf04c28bee9043ed9ea1e41afc0552288d3aba9c6efdd78903b802926f4879" +checksum = "7303ef2c05cd654186cb250d29049a24840ca25d2747c25c0381c8d9e2f582e8" dependencies = [ "proc-macro2", "quote", @@ -2943,6 +2942,27 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" +[[package]] +name = "system-configuration" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "tap" version = "1.0.1" @@ -2964,9 +2984,9 @@ dependencies = [ [[package]] name = "termcolor" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" +checksum = "6093bad37da69aab9d123a8091e4be0aa4a03e4d601ec641c327398315f62b64" dependencies = [ "winapi-util", ] @@ -2979,29 +2999,29 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.48" +version = "1.0.49" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6d7a740b8a666a7e828dd00da9c0dc290dff53154ea77ac109281de90589b7" +checksum = "1177e8c6d7ede7afde3585fd2513e611227efd6481bd78d2e82ba1ce16557ed4" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.48" +version = "1.0.49" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49922ecae66cc8a249b77e68d1d0623c1b2c514f0060c27cdc68bd62a1219d35" +checksum = "10712f02019e9288794769fba95cd6847df9874d49d871d062172f9dd41bc4cc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] name = "time" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17f6bb557fd245c28e6411aa56b6403c689ad95061f50e4be16c274e70a17e48" +checksum = "426f806f4089c493dcac0d24c29c01e2c38baf8e30f1b716ee37e83d200b18fe" dependencies = [ "deranged", "itoa", @@ -3012,15 +3032,15 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb" +checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.14" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a942f44339478ef67935ab2bbaec2fb0322496cf3cbe84b261e06ac3814c572" +checksum = "4ad70d68dba9e1f8aceda7aa6711965dfec1cac869f311a51bd08b3a2ccbce20" dependencies = [ "time-core", ] @@ -3076,7 +3096,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", ] [[package]] @@ -3101,9 +3121,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.8" +version = "0.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "806fe8c2c87eccc8b3267cbae29ed3ab2d0bd37fca70ab622e46aaa9375ddb7d" +checksum = "1d68074620f57a0b21594d9735eb2e98ab38b17f80d3fcb189fca266771ca60d" dependencies = [ "bytes", "futures-core", @@ -3124,14 +3144,14 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.0" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c226a7bba6d859b63c92c4b4fe69c5b6b72d0cb897dbc8e6012298e6154cb56e" +checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.20.0", + "toml_edit 0.20.2", ] [[package]] @@ -3149,18 +3169,18 @@ version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ - "indexmap 2.0.0", + "indexmap 2.0.2", "toml_datetime", "winnow", ] [[package]] name = "toml_edit" -version = "0.20.0" +version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ff63e60a958cefbb518ae1fd6566af80d9d4be430a33f3723dfc47d1d411d95" +checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" dependencies = [ - "indexmap 2.0.0", + "indexmap 2.0.2", "serde", "serde_spanned", "toml_datetime", @@ -3222,7 +3242,7 @@ dependencies = [ "serde", "serde_with", "thiserror", - "toml 0.8.0", + "toml 0.8.2", "torrust-tracker-located-error", "torrust-tracker-primitives", "uuid", @@ -3467,7 +3487,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", "wasm-bindgen-shared", ] @@ -3501,7 +3521,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.35", + "syn 2.0.37", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -3540,9 +3560,9 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596" dependencies = [ "winapi", ] From 4ca47a4a601feafc713b81e37aae4654992a6bc8 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 8 Oct 2023 17:12:40 +0200 Subject: [PATCH 0115/1297] fixup: ignore new clippy warning --- .vscode/settings.json | 2 +- contrib/bencode/src/access/list.rs | 8 ++++++++ contrib/bencode/src/error.rs | 2 ++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 661243fbe..038da4c18 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -18,7 +18,7 @@ "-W", "clippy::style", "-W", - "clippy::pedantic", + "clippy::pedantic" ], "evenBetterToml.formatter.allowedBlankLines": 1, "evenBetterToml.formatter.columnWidth": 130, diff --git a/contrib/bencode/src/access/list.rs b/contrib/bencode/src/access/list.rs index 840bffa1e..c6d1fc407 100644 --- a/contrib/bencode/src/access/list.rs +++ b/contrib/bencode/src/access/list.rs @@ -45,6 +45,14 @@ impl<'a, V: 'a> IndexMut for &'a mut dyn BListAccess { } } +impl<'a, V: 'a> dyn BListAccess { + pub fn iter(&'a self) -> impl Iterator { + self.into_iter() + } +} + +#[allow(unknown_lints)] +#[allow(clippy::into_iter_without_iter)] impl<'a, V: 'a> IntoIterator for &'a dyn BListAccess { type Item = &'a V; type IntoIter = BListIter<'a, V>; diff --git a/contrib/bencode/src/error.rs b/contrib/bencode/src/error.rs index 18ebe9605..54c589e3e 100644 --- a/contrib/bencode/src/error.rs +++ b/contrib/bencode/src/error.rs @@ -1,3 +1,5 @@ +#![allow(unknown_lints)] +#![allow(clippy::iter_without_into_iter)] use error_chain::error_chain; error_chain! { From be914b6719867898376a96b22dba605ca6689078 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 7 Oct 2023 10:38:40 +0200 Subject: [PATCH 0116/1297] ci: re-enable llvm-cov coverage --- .github/workflows/testing.yaml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 21c47665f..f138a95cc 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -104,7 +104,6 @@ jobs: name: Run Unit Tests run: cargo test --tests --benches --examples --workspace --all-targets --all-features - # Temporary Disable https://github.com/time-rs/time/issues/618 - # - id: coverage - # name: Generate Coverage Report - # run: cargo llvm-cov nextest --tests --benches --examples --workspace --all-targets --all-features + - id: coverage + name: Generate Coverage Report + run: cargo llvm-cov nextest --tests --benches --examples --workspace --all-targets --all-features From 050b27a3e25dc9bbe1b26c114d623e31bd6eab4d Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 11 Oct 2023 15:32:17 +0200 Subject: [PATCH 0117/1297] ci: export labels using workflow --- .github/workflows/labels.yaml | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .github/workflows/labels.yaml diff --git a/.github/workflows/labels.yaml b/.github/workflows/labels.yaml new file mode 100644 index 000000000..b78393133 --- /dev/null +++ b/.github/workflows/labels.yaml @@ -0,0 +1,12 @@ +name: Manage Labels +on: + workflow_dispatch: + +jobs: + labels: + runs-on: ubuntu-latest + + steps: + - id: export + name: Export Labels to Workflow Artifacts + uses: EndBug/export-label-config@v1 From d46633c451dac6192b8ac72c9f133b21a1269a7a Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 11 Oct 2023 17:27:11 +0200 Subject: [PATCH 0118/1297] ci: enable sync labels workflow --- .github/labels.json | 260 ++++++++++++++++++++++++++++++++++ .github/workflows/labels.yaml | 10 +- 2 files changed, 269 insertions(+), 1 deletion(-) create mode 100644 .github/labels.json diff --git a/.github/labels.json b/.github/labels.json new file mode 100644 index 000000000..25831d61d --- /dev/null +++ b/.github/labels.json @@ -0,0 +1,260 @@ +[ + { + "name": "- Admin -", + "color": "FFFFFF", + "description": "Enjoyable to Install and Setup our Software", + "aliases": [] + }, + { + "name": "- Contributor -", + "color": "FFFFFF", + "description": "Nice to support Torrust", + "aliases": [] + }, + { + "name": "- Developer -", + "color": "FFFFFF", + "description": "Torrust Improvement Experience", + "aliases": [] + }, + { + "name": "- User -", + "color": "FFFFFF", + "description": "Enjoyable to Use our Software", + "aliases": [] + }, + { + "name": "Blocked", + "color": "000000", + "description": "Has Unsatisfied Dependency", + "aliases": [] + }, + { + "name": "Bug", + "color": "a80506", + "description": "Incorrect Behavior", + "aliases": [] + }, + { + "name": "Build | Project System", + "color": "99AAAA", + "description": "Compiling and Packaging", + "aliases": [] + }, + { + "name": "Cannot Reproduce", + "color": "D3D3D3", + "description": "Inconsistent Observations", + "aliases": [] + }, + { + "name": "Code Cleanup / Refactoring", + "color": "055a8b", + "description": "Tidying and Making Neat", + "aliases": [] + }, + { + "name": "Continuous Integration", + "color": "41c6b3", + "description": "Workflows and Automation", + "aliases": [] + }, + { + "name": "Dependencies", + "color": "d4f8f6", + "description": "Related to Dependencies", + "aliases": [] + }, + { + "name": "Documentation", + "color": "3d2133", + "description": "Improves Instructions, Guides, and Notices", + "aliases": [] + }, + { + "name": "Duplicate", + "color": "cfd3d7", + "description": "Not Unique", + "aliases": [] + }, + { + "name": "Easy", + "color": "f0cff0", + "description": "Good for Newcomers", + "aliases": [] + }, + { + "name": "Enhancement / Feature Request", + "color": "c9ecbf", + "description": "Something New", + "aliases": [] + }, + { + "name": "External Tools", + "color": "a6006b", + "description": "3rd Party Systems", + "aliases": [] + }, + { + "name": "First Time Contribution", + "color": "f1e0e6", + "description": "Welcome to Torrust", + "aliases": [] + }, + { + "name": "Fixed", + "color": "8e4c42", + "description": "Not a Concern Anymore", + "aliases": [] + }, + { + "name": "Hard", + "color": "2c2c2c", + "description": "Non-Trivial", + "aliases": [] + }, + { + "name": "Help Wanted", + "color": "00896b", + "description": "More Contributions are Appreciated", + "aliases": [] + }, + { + "name": "High Priority", + "color": "ba3fbc", + "description": "Focus Required", + "aliases": [] + }, + { + "name": "Hold Merge", + "color": "9aafbe", + "description": "We are not Ready Yet", + "aliases": [] + }, + { + "name": "Installer | Package", + "color": "ed8b24", + "description": "Distribution to Users", + "aliases": [] + }, + { + "name": "Invalid", + "color": "c1c1c1", + "description": "This doesn't seem right", + "aliases": [] + }, + { + "name": "Legal", + "color": "463e60", + "description": "Licenses and other Official Documents", + "aliases": [] + }, + { + "name": "Low Priority", + "color": "43536b", + "description": "Not our Focus Now", + "aliases": [] + }, + { + "name": "Needs Feedback", + "color": "d6946c", + "description": "What dose the Community Think?", + "aliases": [] + }, + { + "name": "Needs Rebase", + "color": "FBC002", + "description": "Base Branch has Incompatibilities", + "aliases": [] + }, + { + "name": "Needs Research", + "color": "4bc021", + "description": "We Need to Know More About This", + "aliases": [] + }, + { + "name": "Optimization", + "color": "faeba8", + "description": "Make it Faster", + "aliases": [] + }, + { + "name": "Portability", + "color": "95de82", + "description": "Distribution to More Places", + "aliases": [] + }, + { + "name": "Postponed", + "color": "dadada", + "description": "For Later", + "aliases": [] + }, + { + "name": "Quality & Assurance", + "color": "eea2e8", + "description": "Relates to QA, Testing, and CI", + "aliases": [] + }, + { + "name": "Question / Discussion", + "color": "f89d00", + "description": "Community Feedback", + "aliases": [] + }, + { + "name": "Regression", + "color": "d10588", + "description": "It dose not work anymore", + "aliases": [] + }, + { + "name": "Reviewed", + "color": "f4f4ea", + "description": "This Looks Good", + "aliases": [] + }, + { + "name": "Rust", + "color": "000000", + "description": "Pull requests that update Rust code", + "aliases": [] + }, + { + "name": "Security", + "color": "650606", + "description": "Publicly Connected to Security", + "aliases": [] + }, + { + "name": "Testing", + "color": "c5def5", + "description": "Checking Torrust", + "aliases": [] + }, + { + "name": "Translations", + "color": "0c86af", + "description": "Localization and Cultural Adaptions", + "aliases": [] + }, + { + "name": "Trivial", + "color": "5f9685", + "description": "Something Easy", + "aliases": [] + }, + { + "name": "Won't Fix", + "color": "070003", + "description": "Something Not Relevant", + "aliases": [] + }, + { + "name": "Workaround Possible", + "color": "eae3e7", + "description": "You can still do it another way", + "aliases": [] + } +] \ No newline at end of file diff --git a/.github/workflows/labels.yaml b/.github/workflows/labels.yaml index b78393133..8d8cb1cba 100644 --- a/.github/workflows/labels.yaml +++ b/.github/workflows/labels.yaml @@ -1,5 +1,5 @@ name: Manage Labels -on: +on: workflow_dispatch: jobs: @@ -10,3 +10,11 @@ jobs: - id: export name: Export Labels to Workflow Artifacts uses: EndBug/export-label-config@v1 + + - id: sync + name: Apply Labels from File + uses: EndBug/label-sync@v2 + with: + config-file: .github/labels.json + delete-other-labels: true + token: ${{ secrets.UPDATE_ISSUES }} From 483cc0471f59c3c084c6f7146ccc354c1e3fc2ff Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 11 Oct 2023 19:14:03 +0200 Subject: [PATCH 0119/1297] ci: fixup labels workflow --- .github/workflows/labels.yaml | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/.github/workflows/labels.yaml b/.github/workflows/labels.yaml index 8d8cb1cba..728b2e681 100644 --- a/.github/workflows/labels.yaml +++ b/.github/workflows/labels.yaml @@ -1,16 +1,30 @@ name: Manage Labels on: workflow_dispatch: + push: + branches: + - develop + paths: + - "/.github/labels.json" jobs: - labels: + export: runs-on: ubuntu-latest steps: - - id: export + - id: backup name: Export Labels to Workflow Artifacts uses: EndBug/export-label-config@v1 + sync: + needs: export + runs-on: ubuntu-latest + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v4 + - id: sync name: Apply Labels from File uses: EndBug/label-sync@v2 From 62c6c10d98f224564685e43d5d7e5801a4adddef Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 12 Oct 2023 08:40:44 +0200 Subject: [PATCH 0120/1297] ci: improve labels workflow --- .github/dependabot.yaml | 6 ++++++ .github/labels.json | 8 +------- .github/workflows/labels.yaml | 6 ++++-- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.github/dependabot.yaml b/.github/dependabot.yaml index 8f36cb692..becfbc1df 100644 --- a/.github/dependabot.yaml +++ b/.github/dependabot.yaml @@ -5,9 +5,15 @@ updates: schedule: interval: daily target-branch: "develop" + labels: + - "Continuous Integration" + - "Dependencies" - package-ecosystem: cargo directory: / schedule: interval: daily target-branch: "develop" + labels: + - "Build | Project System" + - "Dependencies" diff --git a/.github/labels.json b/.github/labels.json index 25831d61d..3b8a2af42 100644 --- a/.github/labels.json +++ b/.github/labels.json @@ -39,7 +39,7 @@ "name": "Build | Project System", "color": "99AAAA", "description": "Compiling and Packaging", - "aliases": [] + "aliases": ["Rust"] }, { "name": "Cannot Reproduce", @@ -215,12 +215,6 @@ "description": "This Looks Good", "aliases": [] }, - { - "name": "Rust", - "color": "000000", - "description": "Pull requests that update Rust code", - "aliases": [] - }, { "name": "Security", "color": "650606", diff --git a/.github/workflows/labels.yaml b/.github/workflows/labels.yaml index 728b2e681..4d049eb0c 100644 --- a/.github/workflows/labels.yaml +++ b/.github/workflows/labels.yaml @@ -1,4 +1,4 @@ -name: Manage Labels +name: Labels on: workflow_dispatch: push: @@ -9,14 +9,16 @@ on: jobs: export: + name: Export Existing Labels runs-on: ubuntu-latest steps: - id: backup - name: Export Labels to Workflow Artifacts + name: Export to Workflow Artifact uses: EndBug/export-label-config@v1 sync: + name: Synchronize Labels from Repo needs: export runs-on: ubuntu-latest From 8f2e22ea65662f6c7cbb660837cec8228d5976aa Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 13 Oct 2023 11:23:05 +0200 Subject: [PATCH 0121/1297] ci: maintaince update for labelsync --- .github/workflows/labels.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/labels.yaml b/.github/workflows/labels.yaml index 4d049eb0c..bb8283f30 100644 --- a/.github/workflows/labels.yaml +++ b/.github/workflows/labels.yaml @@ -33,4 +33,4 @@ jobs: with: config-file: .github/labels.json delete-other-labels: true - token: ${{ secrets.UPDATE_ISSUES }} + token: ${{ secrets.UPDATE_LABELS }} From 308f490e34d31ee64774993af8d939662f6f4061 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 12 Oct 2023 10:28:18 +0200 Subject: [PATCH 0122/1297] deps: update cargo lockfile --- Cargo.lock | 130 ++++++++++++++++++++++++----------------------------- 1 file changed, 59 insertions(+), 71 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 142fa521e..ef5e1a4e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -41,9 +41,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.1.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea5d730647d4fadd988536d06fecce94b7b4f2a7efdae548f1cf4b63205518ab" +checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0" dependencies = [ "memchr", ] @@ -142,7 +142,7 @@ checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -292,7 +292,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -430,9 +430,9 @@ dependencies = [ [[package]] name = "byteorder" -version = "1.4.3" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" @@ -749,7 +749,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -760,7 +760,7 @@ checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ "darling_core", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -793,7 +793,7 @@ checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -847,25 +847,14 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.4" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "add4f07d43996f76ef320709726a556a9d4f965d9410d8d0271132d2f8293480" +checksum = "ac3e13f66a2f95e32a39eaa81f6b95d42878ca0e1db0c7543723dfe12557e860" dependencies = [ - "errno-dragonfly", "libc", "windows-sys", ] -[[package]] -name = "errno-dragonfly" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" -dependencies = [ - "cc", - "libc", -] - [[package]] name = "error-chain" version = "0.12.4" @@ -994,7 +983,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -1006,7 +995,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -1018,7 +1007,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -1083,7 +1072,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -1374,7 +1363,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -1411,9 +1400,9 @@ checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" [[package]] name = "jobserver" -version = "0.1.26" +version = "0.1.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "936cfd212a0155903bcbc060e316fb6cc7cbf2e1907329391ebadc1fe0ce77c2" +checksum = "8c37f63953c4c63420ed5fd3d6d398c719489b9f872b9fa683262f8edd363c7d" dependencies = [ "libc", ] @@ -1525,9 +1514,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.148" +version = "0.2.149" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cdc71e17332e86d2e1d38c1f99edcb6288ee11b815fb1a4b049eaa2114d369b" +checksum = "a08173bc88b7955d1b3145aa561539096c421ac8debde8cbc3612ec635fee29b" [[package]] name = "libloading" @@ -1569,9 +1558,9 @@ checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" [[package]] name = "linux-raw-sys" -version = "0.4.8" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3852614a3bd9ca9804678ba6be5e3b8ce76dfc902cae004e3e0c44051b6e88db" +checksum = "da2479e8c062e40bf0066ffa0bc823de0a9368974af99c9f6df941d2c231e03f" [[package]] name = "local-ip-address" @@ -1738,7 +1727,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", "termcolor", "thiserror", ] @@ -1878,9 +1867,9 @@ dependencies = [ [[package]] name = "num-traits" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" +checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" dependencies = [ "autocfg", ] @@ -1939,7 +1928,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -2062,7 +2051,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -2093,7 +2082,7 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -2223,9 +2212,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.67" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d433d9f1a3e8c1263d9456598b16fec66f4acc9a74dacffd35c7bb09b3a1328" +checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" dependencies = [ "unicode-ident", ] @@ -2358,9 +2347,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.9.6" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebee201405406dbf528b8b672104ae6d6d63e6d118cb10e4d51abbc7b58044ff" +checksum = "d119d7c7ca818f8a53c300863d4f87566aac09943aef5b355bb83969dae75d87" dependencies = [ "aho-corasick", "memchr", @@ -2370,9 +2359,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.3.9" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59b23e92ee4318893fa3fe3e6fb365258efbfe6ac6ab30f090cdcbb7aa37efa9" +checksum = "465c6fc0621e4abc4187a2bda0937bfd4f722c2730b29562e19689ea796c9a4b" dependencies = [ "aho-corasick", "memchr", @@ -2381,9 +2370,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.7.5" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" +checksum = "56d84fdd47036b038fc80dd333d10b6aab10d5d31f4a366e20014def75328d33" [[package]] name = "rend" @@ -2396,9 +2385,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.11.21" +version = "0.11.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78fdbab6a7e1d7b13cc8ff10197f47986b41c639300cc3c8158cac7847c9bbef" +checksum = "046cd98826c46c2ac8ddecae268eb5c2e58628688a5fc7a2643704a73faba95b" dependencies = [ "base64 0.21.4", "bytes", @@ -2549,9 +2538,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.15" +version = "0.38.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2f9da0cbd88f9f09e7814e388301c8414c51c62aa6ce1e4b5c551d49d96e531" +checksum = "5a74ee2d7c2581cd139b42447d7d9389b889bdaad3a73f1ebb16f2a3237bb19c" dependencies = [ "bitflags 2.4.0", "errno", @@ -2683,9 +2672,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.19" +version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad977052201c6de01a8ef2aa3378c4bd23217a056337d1d6da40468d267a4fb0" +checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" [[package]] name = "serde" @@ -2698,9 +2687,9 @@ dependencies = [ [[package]] name = "serde_bencode" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "934d8bdbaa0126dafaea9a8833424a211d9661897717846c6bb782349ca1c30d" +checksum = "a70dfc7b7438b99896e7f8992363ab8e2c4ba26aa5ec675d32d1c3c2c33d413e" dependencies = [ "serde", "serde_bytes", @@ -2723,7 +2712,7 @@ checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -2755,7 +2744,7 @@ checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -2805,7 +2794,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -2927,9 +2916,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.37" +version = "2.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7303ef2c05cd654186cb250d29049a24840ca25d2747c25c0381c8d9e2f582e8" +checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b" dependencies = [ "proc-macro2", "quote", @@ -3014,7 +3003,7 @@ checksum = "10712f02019e9288794769fba95cd6847df9874d49d871d062172f9dd41bc4cc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -3072,9 +3061,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.32.0" +version = "1.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17ed6077ed6cd6c74735e21f37eb16dc3935f96878b1fe961074089cc80893f9" +checksum = "4f38200e3ef7995e5ef13baec2f432a6da0aa9ac495b2c0e8f3b7eec2c92d653" dependencies = [ "backtrace", "bytes", @@ -3096,7 +3085,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", ] [[package]] @@ -3487,7 +3476,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", "wasm-bindgen-shared", ] @@ -3521,7 +3510,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.37", + "syn 2.0.38", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -3650,9 +3639,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "winnow" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c2e3184b9c4e92ad5167ca73039d0c42476302ab603e2fec4487511f38ccefc" +checksum = "037711d82167854aff2018dfd193aa0fef5370f456732f0d5a0c59b0f1b4b907" dependencies = [ "memchr", ] @@ -3706,11 +3695,10 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.0.8+zstd.1.5.5" +version = "2.0.9+zstd.1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5556e6ee25d32df2586c098bbfa278803692a20d0ab9565e049480d52707ec8c" +checksum = "9e16efa8a874a0481a574084d34cc26fdb3b99627480f785888deb6386506656" dependencies = [ "cc", - "libc", "pkg-config", ] From 7dbca2bb8ec1f9f08dca8f752369ec00a4bec429 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 12 Oct 2023 10:28:50 +0200 Subject: [PATCH 0123/1297] ci: move doc tests to unit section --- .github/workflows/testing.yaml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index f138a95cc..3ae18e4db 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -65,10 +65,6 @@ jobs: name: Run Lint Checks run: cargo clippy --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic - - id: doc - name: Run Documentation Checks - run: cargo test --doc - unit: name: Units runs-on: ubuntu-latest @@ -100,6 +96,14 @@ jobs: with: tool: cargo-llvm-cov, cargo-nextest + - id: docs + name: Build Documentation + run: cargo doc --no-deps --bins --examples --workspace --all-features + + - id: test-docs + name: Run Documentation Tests + run: cargo test --doc + - id: test name: Run Unit Tests run: cargo test --tests --benches --examples --workspace --all-targets --all-features From 417ad73d6c288374b98be2b0ff1819714ae62beb Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 12 Oct 2023 10:54:42 +0200 Subject: [PATCH 0124/1297] chore: fix doc warnings --- src/bootstrap/app.rs | 4 ++-- src/bootstrap/jobs/http_tracker.rs | 2 +- src/bootstrap/jobs/tracker_apis.rs | 2 +- src/lib.rs | 4 ++-- src/servers/apis/mod.rs | 6 +++--- .../apis/v1/context/auth_key/handlers.rs | 2 +- src/servers/apis/v1/context/stats/handlers.rs | 2 +- .../apis/v1/context/stats/responses.rs | 2 +- .../apis/v1/context/torrent/handlers.rs | 2 +- .../apis/v1/context/torrent/resources/peer.rs | 2 +- .../v1/context/torrent/resources/torrent.rs | 4 ++-- .../apis/v1/context/torrent/responses.rs | 4 ++-- src/servers/http/mod.rs | 4 ++-- src/servers/http/percent_encoding.rs | 6 +++--- .../http/v1/extractors/announce_request.rs | 6 +++--- .../http/v1/extractors/authentication_key.rs | 4 ++-- .../http/v1/extractors/client_ip_sources.rs | 2 +- .../http/v1/extractors/scrape_request.rs | 6 +++--- src/servers/http/v1/handlers/common/auth.rs | 2 +- .../http/v1/handlers/common/peer_ip.rs | 2 +- src/servers/http/v1/query.rs | 2 +- src/servers/http/v1/responses/announce.rs | 4 ++-- src/servers/http/v1/services/announce.rs | 6 +++--- src/servers/http/v1/services/scrape.rs | 6 +++--- src/servers/udp/mod.rs | 2 +- src/servers/udp/peer_builder.rs | 2 +- src/servers/udp/request.rs | 4 ++-- src/servers/udp/server.rs | 6 +++--- src/tracker/auth.rs | 8 ++++---- src/tracker/databases/mod.rs | 4 ++-- src/tracker/mod.rs | 20 +++++++++---------- src/tracker/services/statistics/mod.rs | 4 ++-- src/tracker/services/statistics/setup.rs | 2 +- src/tracker/services/torrent.rs | 10 +++++----- src/tracker/torrent.rs | 6 +++--- 35 files changed, 77 insertions(+), 77 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 6961e15f0..78c16a0a5 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -1,6 +1,6 @@ //! Setup for the main tracker application. //! -//! The [`setup`](bootstrap::app::setup) only builds the application and its dependencies but it does not start the application. +//! The [`setup`] only builds the application and its dependencies but it does not start the application. //! In fact, there is no such thing as the main application process. When the application starts, the only thing it does is //! starting a bunch of independent jobs. If you are looking for how things are started you should read [`app::start`](crate::app::start) //! function documentation. @@ -22,7 +22,7 @@ use crate::shared::crypto::ephemeral_instance_keys; use crate::tracker::services::tracker_factory; use crate::tracker::Tracker; -/// It loads the configuration from the environment and builds the main domain [`tracker`](crate::tracker::Tracker) struct. +/// It loads the configuration from the environment and builds the main domain [`Tracker`] struct. #[must_use] pub fn setup() -> (Arc, Arc) { let configuration = Arc::new(initialize_configuration()); diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index ac0161640..a38fe3a5a 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -7,7 +7,7 @@ //! //! The [`http_tracker::start_job`](crate::bootstrap::jobs::http_tracker::start_job) function spawns a new asynchronous task, //! that tasks is the "**launcher**". The "**launcher**" starts the actual server and sends a message back to the main application. -//! The main application waits until receives the message [`ServerJobStarted`](crate::bootstrap::jobs::http_tracker::ServerJobStarted) from the "**launcher**". +//! The main application waits until receives the message [`ServerJobStarted`] from the "**launcher**". //! //! The "**launcher**" is an intermediary thread that decouples the HTTP servers from the process that handles it. The HTTP could be used independently in the future. //! In that case it would not need to notify a parent process. diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 9afe4ab24..33b9b6e4a 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -11,7 +11,7 @@ //! function spawns a new asynchronous task, that tasks is the "**launcher**". //! The "**launcher**" starts the actual server and sends a message back //! to the main application. The main application waits until receives -//! the message [`ApiServerJobStarted`](crate::bootstrap::jobs::tracker_apis::ApiServerJobStarted) +//! the message [`ApiServerJobStarted`] //! from the "**launcher**". //! //! The "**launcher**" is an intermediary thread that decouples the API server diff --git a/src/lib.rs b/src/lib.rs index c862d373a..c2e70a8b1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -384,7 +384,7 @@ //! //! Torrust Tracker has four main components: //! -//! - The core [`tracker`](crate::tracker) +//! - The core [`tracker`] //! - The tracker REST [`API`](crate::servers::apis) //! - The [`UDP`](crate::servers::udp) tracker //! - The [`HTTP`](crate::servers::http) tracker @@ -402,7 +402,7 @@ //! - Statistics //! - Persistence //! -//! See [`tracker`](crate::tracker) for more details on the [`tracker`](crate::tracker) module. +//! See [`tracker`] for more details on the [`tracker`] module. //! //! ## Tracker API //! diff --git a/src/servers/apis/mod.rs b/src/servers/apis/mod.rs index afed9ff12..5f8c581d0 100644 --- a/src/servers/apis/mod.rs +++ b/src/servers/apis/mod.rs @@ -3,7 +3,7 @@ //! > **NOTICE**: This API should not be exposed directly to the internet, it is //! intended for internal use only. //! -//! Endpoints for the latest API: [v1](crate::servers::apis::v1). +//! Endpoints for the latest API: [v1]. //! //! All endpoints require an authorization token which must be set in the //! configuration before running the tracker. The default configuration uses @@ -139,13 +139,13 @@ //! //! The API is versioned and each version has its own module. //! The API server runs all the API versions on the same server using -//! the same port. Currently there is only one API version: [v1](crate::servers::apis::v1) +//! the same port. Currently there is only one API version: [v1] //! but a version [`v2`](https://github.com/torrust/torrust-tracker/issues/144) //! is planned. //! //! # Endpoints //! -//! Refer to the [v1](crate::servers::apis::v1) module for the list of available +//! Refer to the [v1] module for the list of available //! API endpoints. //! //! # Documentation diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index 85158c698..d6a2992fb 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -19,7 +19,7 @@ use crate::tracker::Tracker; /// /// It returns two types of responses: /// -/// - `200` with an json [`AuthKey`](crate::servers::apis::v1::context::auth_key::resources::AuthKey) +/// - `200` with an json [`AuthKey`] /// resource. If the key was generated successfully. /// - `500` with serialized error in debug format. If the key couldn't be /// generated. diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index dfb983f77..bb531c806 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -12,7 +12,7 @@ use crate::tracker::Tracker; /// It handles the request to get the tracker statistics. /// -/// It returns a `200` response with a json [`Stats`](crate::servers::apis::v1::context::stats::resources::Stats) +/// It returns a `200` response with a json [`Stats`] /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::stats#get-tracker-statistics) /// for more information about this endpoint. diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index a4dad77e4..e8e7cb84d 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -5,7 +5,7 @@ use axum::response::Json; use super::resources::Stats; use crate::tracker::services::statistics::TrackerMetrics; -/// `200` response that contains the [`Stats`](crate::servers::apis::v1::context::stats::resources::Stats) resource as json. +/// `200` response that contains the [`Stats`] resource as json. pub fn stats_response(tracker_metrics: TrackerMetrics) -> Json { Json(Stats::from(tracker_metrics)) } diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs index 002d4356e..1f38ab474 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/src/servers/apis/v1/context/torrent/handlers.rs @@ -51,7 +51,7 @@ pub struct PaginationParams { /// It handles the request to get a list of torrents. /// /// It returns a `200` response with a json array with -/// [`ListItem`](crate::servers::apis::v1::context::torrent::resources::torrent::ListItem) +/// [`ListItem`] /// resources. /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent#list-torrents) diff --git a/src/servers/apis/v1/context/torrent/resources/peer.rs b/src/servers/apis/v1/context/torrent/resources/peer.rs index 539637b35..4989cec52 100644 --- a/src/servers/apis/v1/context/torrent/resources/peer.rs +++ b/src/servers/apis/v1/context/torrent/resources/peer.rs @@ -6,7 +6,7 @@ use crate::tracker; /// `Peer` API resource. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct Peer { - /// The peer's ID. See [`Id`](crate::servers::apis::v1::context::torrent::resources::peer::Id). + /// The peer's ID. See [`Id`]. pub peer_id: Id, /// The peer's socket address. For example: `192.168.1.88:17548`. pub peer_addr: String, diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs index c9dbd1c02..ebebda79c 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs @@ -59,8 +59,8 @@ impl ListItem { } } -/// Maps an array of the domain type [`BasicInfo`](crate::tracker::services::torrent::BasicInfo) -/// to the API resource type [`ListItem`](crate::servers::apis::v1::context::torrent::resources::torrent::ListItem). +/// Maps an array of the domain type [`BasicInfo`] +/// to the API resource type [`ListItem`]. #[must_use] pub fn to_resource(basic_info_vec: &[BasicInfo]) -> Vec { basic_info_vec diff --git a/src/servers/apis/v1/context/torrent/responses.rs b/src/servers/apis/v1/context/torrent/responses.rs index d3be092eb..99c2fcae3 100644 --- a/src/servers/apis/v1/context/torrent/responses.rs +++ b/src/servers/apis/v1/context/torrent/responses.rs @@ -7,14 +7,14 @@ use super::resources::torrent::{ListItem, Torrent}; use crate::tracker::services::torrent::{BasicInfo, Info}; /// `200` response that contains an array of -/// [`ListItem`](crate::servers::apis::v1::context::torrent::resources::torrent::ListItem) +/// [`ListItem`] /// resources as json. pub fn torrent_list_response(basic_infos: &[BasicInfo]) -> Json> { Json(ListItem::new_vec(basic_infos)) } /// `200` response that contains a -/// [`Torrent`](crate::servers::apis::v1::context::torrent::resources::torrent::Torrent) +/// [`Torrent`] /// resources as json. pub fn torrent_info_response(info: Info) -> Json { Json(Torrent::from(info)) diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index 067e88fdd..e6dd808b6 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -78,13 +78,13 @@ //! > **NOTICE**: the `info_hash` parameter is NOT a `URL` encoded string param. //! It is percent encode of the raw `info_hash` bytes (40 bytes). URL `GET` params //! can contain any bytes, not only well-formed UTF-8. The `info_hash` is a -//! 20-byte SHA1. Check the [`percent_encoding`](crate::servers::http::percent_encoding) +//! 20-byte SHA1. Check the [`percent_encoding`] //! module to know more about the encoding. //! //! > **NOTICE**: the `peer_id` parameter is NOT a `URL` encoded string param. //! It is percent encode of the raw peer ID bytes (20 bytes). URL `GET` params //! can contain any bytes, not only well-formed UTF-8. The `info_hash` is a -//! 20-byte SHA1. Check the [`percent_encoding`](crate::servers::http::percent_encoding) +//! 20-byte SHA1. Check the [`percent_encoding`] //! module to know more about the encoding. //! //! > **NOTICE**: by default, the tracker returns the non-compact peer list when diff --git a/src/servers/http/percent_encoding.rs b/src/servers/http/percent_encoding.rs index c8f0f7f12..b674f0475 100644 --- a/src/servers/http/percent_encoding.rs +++ b/src/servers/http/percent_encoding.rs @@ -19,7 +19,7 @@ use crate::shared::bit_torrent::info_hash::{ConversionError, InfoHash}; use crate::tracker::peer::{self, IdConversionError}; /// Percent decodes a percent encoded infohash. Internally an -/// [`InfoHash`](crate::shared::bit_torrent::info_hash::InfoHash) is a 20-byte array. +/// [`InfoHash`] is a 20-byte array. /// /// For example, given the infohash `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`, /// it's percent encoded representation is `%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0`. @@ -43,7 +43,7 @@ use crate::tracker::peer::{self, IdConversionError}; /// # Errors /// /// Will return `Err` if the decoded bytes do not represent a valid -/// [`InfoHash`](crate::shared::bit_torrent::info_hash::InfoHash). +/// [`InfoHash`]. pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result { let bytes = percent_encoding::percent_decode_str(raw_info_hash).collect::>(); InfoHash::try_from(bytes) @@ -70,7 +70,7 @@ pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result Result { let bytes = percent_encoding::percent_decode_str(raw_peer_id).collect::>(); peer::Id::try_from(bytes) diff --git a/src/servers/http/v1/extractors/announce_request.rs b/src/servers/http/v1/extractors/announce_request.rs index 5d947ef91..1778f78c5 100644 --- a/src/servers/http/v1/extractors/announce_request.rs +++ b/src/servers/http/v1/extractors/announce_request.rs @@ -1,7 +1,7 @@ -//! Axum [`extractor`](axum::extract) for the [`Announce`](crate::servers::http::v1::requests::announce::Announce) +//! Axum [`extractor`](axum::extract) for the [`Announce`] //! request. //! -//! It parses the query parameters returning an [`Announce`](crate::servers::http::v1::requests::announce::Announce) +//! It parses the query parameters returning an [`Announce`] //! request. //! //! Refer to [`Announce`](crate::servers::http::v1::requests::announce) for more @@ -38,7 +38,7 @@ use crate::servers::http::v1::query::Query; use crate::servers::http::v1::requests::announce::{Announce, ParseAnnounceQueryError}; use crate::servers::http::v1::responses; -/// Extractor for the [`Announce`](crate::servers::http::v1::requests::announce::Announce) +/// Extractor for the [`Announce`] /// request. pub struct ExtractRequest(pub Announce); diff --git a/src/servers/http/v1/extractors/authentication_key.rs b/src/servers/http/v1/extractors/authentication_key.rs index 20dc1c90b..3f2a2a246 100644 --- a/src/servers/http/v1/extractors/authentication_key.rs +++ b/src/servers/http/v1/extractors/authentication_key.rs @@ -1,4 +1,4 @@ -//! Axum [`extractor`](axum::extract) to extract the authentication [`Key`](crate::tracker::auth::Key) +//! Axum [`extractor`](axum::extract) to extract the authentication [`Key`] //! from the URL path. //! //! It's only used when the tracker is running in private mode. @@ -55,7 +55,7 @@ use crate::servers::http::v1::handlers::common::auth; use crate::servers::http::v1::responses; use crate::tracker::auth::Key; -/// Extractor for the [`Key`](crate::tracker::auth::Key) struct. +/// Extractor for the [`Key`] struct. pub struct Extract(pub Key); #[derive(Deserialize)] diff --git a/src/servers/http/v1/extractors/client_ip_sources.rs b/src/servers/http/v1/extractors/client_ip_sources.rs index f04300402..18eff26b3 100644 --- a/src/servers/http/v1/extractors/client_ip_sources.rs +++ b/src/servers/http/v1/extractors/client_ip_sources.rs @@ -45,7 +45,7 @@ use axum_client_ip::RightmostXForwardedFor; use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; -/// Extractor for the [`ClientIpSources`](crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources) +/// Extractor for the [`ClientIpSources`] /// struct. pub struct Extract(pub ClientIpSources); diff --git a/src/servers/http/v1/extractors/scrape_request.rs b/src/servers/http/v1/extractors/scrape_request.rs index 63c4dba69..1437ede41 100644 --- a/src/servers/http/v1/extractors/scrape_request.rs +++ b/src/servers/http/v1/extractors/scrape_request.rs @@ -1,7 +1,7 @@ -//! Axum [`extractor`](axum::extract) for the [`Scrape`](crate::servers::http::v1::requests::scrape::Scrape) +//! Axum [`extractor`](axum::extract) for the [`Scrape`] //! request. //! -//! It parses the query parameters returning an [`Scrape`](crate::servers::http::v1::requests::scrape::Scrape) +//! It parses the query parameters returning an [`Scrape`] //! request. //! //! Refer to [`Scrape`](crate::servers::http::v1::requests::scrape) for more @@ -38,7 +38,7 @@ use crate::servers::http::v1::query::Query; use crate::servers::http::v1::requests::scrape::{ParseScrapeQueryError, Scrape}; use crate::servers::http::v1::responses; -/// Extractor for the [`Scrape`](crate::servers::http::v1::requests::scrape::Scrape) +/// Extractor for the [`Scrape`] /// request. pub struct ExtractRequest(pub Scrape); diff --git a/src/servers/http/v1/handlers/common/auth.rs b/src/servers/http/v1/handlers/common/auth.rs index f41635d69..720ed7659 100644 --- a/src/servers/http/v1/handlers/common/auth.rs +++ b/src/servers/http/v1/handlers/common/auth.rs @@ -1,5 +1,5 @@ //! HTTP server authentication error and conversion to -//! [`responses::error::Error`](crate::servers::http::v1::responses::error::Error) +//! [`responses::error::Error`] //! response. use std::panic::Location; diff --git a/src/servers/http/v1/handlers/common/peer_ip.rs b/src/servers/http/v1/handlers/common/peer_ip.rs index d65efbc79..5602bd26c 100644 --- a/src/servers/http/v1/handlers/common/peer_ip.rs +++ b/src/servers/http/v1/handlers/common/peer_ip.rs @@ -2,7 +2,7 @@ //! //! The HTTP tracker may fail to resolve the peer IP address. This module //! contains the logic to convert those -//! [`PeerIpResolutionError`](crate::servers::http::v1::services::peer_ip_resolver::PeerIpResolutionError) +//! [`PeerIpResolutionError`] //! errors into responses. use crate::servers::http::v1::responses; use crate::servers::http::v1::services::peer_ip_resolver::PeerIpResolutionError; diff --git a/src/servers/http/v1/query.rs b/src/servers/http/v1/query.rs index 745796b61..3a078daae 100644 --- a/src/servers/http/v1/query.rs +++ b/src/servers/http/v1/query.rs @@ -93,7 +93,7 @@ impl Query { } } -/// This error can be returned when parsing a [`Query`](crate::servers::http::v1::query::Query) +/// This error can be returned when parsing a [`Query`] /// from a string. #[derive(Error, Debug)] pub enum ParseQueryError { diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index 3596275f4..f45f4c824 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -91,7 +91,7 @@ pub struct NonCompact { pub peers: Vec, } -/// Peer information in the [`NonCompact`](crate::servers::http::v1::responses::announce::NonCompact) +/// Peer information in the [`NonCompact`] /// response. /// /// ```rust @@ -261,7 +261,7 @@ pub struct Compact { pub peers: Vec, } -/// Compact peer. It's used in the [`Compact`](crate::servers::http::v1::responses::announce::Compact) +/// Compact peer. It's used in the [`Compact`] /// response. /// /// _"To reduce the size of tracker responses and to reduce memory and diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 4c1b262ba..ddb3b1221 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -3,10 +3,10 @@ //! The service is responsible for handling the `announce` requests. //! //! It delegates the `announce` logic to the [`Tracker`](crate::tracker::Tracker::announce) -//! and it returns the [`AnnounceData`](crate::tracker::AnnounceData) returned -//! by the [`Tracker`](crate::tracker::Tracker). +//! and it returns the [`AnnounceData`] returned +//! by the [`Tracker`]. //! -//! It also sends an [`statistics::Event`](crate::tracker::statistics::Event) +//! It also sends an [`statistics::Event`] //! because events are specific for the HTTP tracker. use std::net::IpAddr; use std::sync::Arc; diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 240680ca3..adea28086 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -3,10 +3,10 @@ //! The service is responsible for handling the `scrape` requests. //! //! It delegates the `scrape` logic to the [`Tracker`](crate::tracker::Tracker::scrape) -//! and it returns the [`ScrapeData`](crate::tracker::ScrapeData) returned -//! by the [`Tracker`](crate::tracker::Tracker). +//! and it returns the [`ScrapeData`] returned +//! by the [`Tracker`]. //! -//! It also sends an [`statistics::Event`](crate::tracker::statistics::Event) +//! It also sends an [`statistics::Event`] //! because events are specific for the HTTP tracker. use std::net::IpAddr; use std::sync::Arc; diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index edbfd77d2..630867218 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -109,7 +109,7 @@ //! connection ID = hash(client IP + current time slot + secret seed) //! ``` //! -//! The BEP-15 recommends a two-minute time slot. Refer to [`connection_cookie`](crate::servers::udp::connection_cookie) +//! The BEP-15 recommends a two-minute time slot. Refer to [`connection_cookie`] //! for more information about the connection ID generation with this method. //! //! #### Connect Request diff --git a/src/servers/udp/peer_builder.rs b/src/servers/udp/peer_builder.rs index ac62a7ecd..7c83089bb 100644 --- a/src/servers/udp/peer_builder.rs +++ b/src/servers/udp/peer_builder.rs @@ -5,7 +5,7 @@ use super::request::AnnounceWrapper; use crate::shared::clock::{Current, Time}; use crate::tracker::peer::{Id, Peer}; -/// Extracts the [`Peer`](crate::tracker::peer::Peer) info from the +/// Extracts the [`Peer`] info from the /// announce request. /// /// # Arguments diff --git a/src/servers/udp/request.rs b/src/servers/udp/request.rs index 0afa02806..f655fd36a 100644 --- a/src/servers/udp/request.rs +++ b/src/servers/udp/request.rs @@ -9,9 +9,9 @@ use aquatic_udp_protocol::AnnounceRequest; use crate::shared::bit_torrent::info_hash::InfoHash; -/// Wrapper around [`AnnounceRequest`](aquatic_udp_protocol::request::AnnounceRequest). +/// Wrapper around [`AnnounceRequest`]. pub struct AnnounceWrapper { - /// [`AnnounceRequest`](aquatic_udp_protocol::request::AnnounceRequest) to wrap. + /// [`AnnounceRequest`] to wrap. pub announce_request: AnnounceRequest, /// Info hash of the torrent. pub info_hash: InfoHash, diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 5e5c98704..428b76fa1 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -2,9 +2,9 @@ //! //! There are two main types in this module: //! -//! - [`UdpServer`](crate::servers::udp::server::UdpServer): a controller to +//! - [`UdpServer`]: a controller to //! start and stop the server. -//! - [`Udp`](crate::servers::udp::server::Udp): the server launcher. +//! - [`Udp`]: the server launcher. //! //! The `UdpServer` is an state machine for a given configuration. This struct //! represents concrete configuration and state. It allows to start and @@ -42,7 +42,7 @@ use crate::tracker::Tracker; /// /// Some errors triggered while stopping the server are: /// -/// - The [`UdpServer`](crate::servers::udp::server::UdpServer) cannot send the +/// - The [`UdpServer`] cannot send the /// shutdown signal to the spawned UDP service thread. #[derive(Debug)] pub enum Error { diff --git a/src/tracker/auth.rs b/src/tracker/auth.rs index 466187af5..2759c8d06 100644 --- a/src/tracker/auth.rs +++ b/src/tracker/auth.rs @@ -4,7 +4,7 @@ //! Tracker keys are tokens used to authenticate the tracker clients when the tracker runs //! in `private` or `private_listed` modes. //! -//! There are services to [`generate`](crate::tracker::auth::generate) and [`verify`](crate::tracker::auth::verify) authentication keys. +//! There are services to [`generate`] and [`verify`] authentication keys. //! //! Authentication keys are used only by [`HTTP`](crate::servers::http) trackers. All keys have an expiration time, that means //! they are only valid during a period of time. After that time the expiring key will no longer be valid. @@ -53,7 +53,7 @@ use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; use crate::shared::clock::{convert_from_timestamp_to_datetime_utc, Current, DurationSinceUnixEpoch, Time, TimeNow}; #[must_use] -/// It generates a new random 32-char authentication [`ExpiringKey`](crate::tracker::auth::ExpiringKey) +/// It generates a new random 32-char authentication [`ExpiringKey`] /// /// # Panics /// @@ -73,7 +73,7 @@ pub fn generate(lifetime: Duration) -> ExpiringKey { } } -/// It verifies an [`ExpiringKey`](crate::tracker::auth::ExpiringKey). It checks if the expiration date has passed. +/// It verifies an [`ExpiringKey`]. It checks if the expiration date has passed. /// /// # Errors /// @@ -164,7 +164,7 @@ impl FromStr for Key { } } -/// Verification error. Error returned when an [`ExpiringKey`](crate::tracker::auth::ExpiringKey) cannot be verified with the [`verify(...)`](crate::tracker::auth::verify) function. +/// Verification error. Error returned when an [`ExpiringKey`] cannot be verified with the [`verify(...)`](crate::tracker::auth::verify) function. /// #[derive(Debug, Error)] #[allow(dead_code)] diff --git a/src/tracker/databases/mod.rs b/src/tracker/databases/mod.rs index e0a26be23..902880496 100644 --- a/src/tracker/databases/mod.rs +++ b/src/tracker/databases/mod.rs @@ -1,6 +1,6 @@ //! The persistence module. //! -//! Persistence is currently implemented with one [`Database`](crate::tracker::databases::Database) trait. +//! Persistence is currently implemented with one [`Database`] trait. //! //! There are two implementations of the trait (two drivers): //! @@ -115,7 +115,7 @@ pub trait Database: Sync + Send { /// It loads the torrent metrics data from the database. /// /// It returns an array of tuples with the torrent - /// [`InfoHash`](crate::shared::bit_torrent::info_hash::InfoHash) and the + /// [`InfoHash`] and the /// [`completed`](crate::tracker::torrent::Entry::completed) counter /// which is the number of times the torrent has been downloaded. /// See [`Entry::completed`](crate::tracker::torrent::Entry::completed). diff --git a/src/tracker/mod.rs b/src/tracker/mod.rs index 040751e12..94d75a8cd 100644 --- a/src/tracker/mod.rs +++ b/src/tracker/mod.rs @@ -52,7 +52,7 @@ //! The tracker responds to the peer with the list of other peers in the swarm so that //! the peer can contact them to start downloading pieces of the file from them. //! -//! Once you have instantiated the `Tracker` you can `announce` a new [`peer`](crate::tracker::peer::Peer) with: +//! Once you have instantiated the `Tracker` you can `announce` a new [`Peer`] with: //! //! ```rust,no_run //! use torrust_tracker::tracker::peer; @@ -183,7 +183,7 @@ //! //! ## Torrents //! -//! The [`torrent`](crate::tracker::torrent) module contains all the data structures stored by the `Tracker` except for peers. +//! The [`torrent`] module contains all the data structures stored by the `Tracker` except for peers. //! //! We can represent the data stored in memory internally by the `Tracker` with this JSON object: //! @@ -222,7 +222,7 @@ //! they have a full version of the torrent data, and they can provide the full data to other peers. That's why they are also known as "seeders". //! - `peers`: an indexed and orderer list of peer for the torrent. Each peer contains the data received from the peer in the `announce` request. //! -//! The [`torrent`](crate::tracker::torrent) module not only contains the original data obtained from peer via `announce` requests, it also contains +//! The [`torrent`] module not only contains the original data obtained from peer via `announce` requests, it also contains //! aggregate data that can be derived from the original data. For example: //! //! ```rust,no_run @@ -244,7 +244,7 @@ //! `SwarmStats` struct follows name conventions for `scrape` responses. See [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmStats` //! is used for the rest of cases. //! -//! Refer to [`torrent`](crate::tracker::torrent) module for more details about these data structures. +//! Refer to [`torrent`] module for more details about these data structures. //! //! ## Peers //! @@ -310,7 +310,7 @@ //! `c1277613db1d28709b034a017ab2cae4be07ae10` is the torrent infohash and `completed` contains the number of peers //! that have a full version of the torrent data, also known as seeders. //! -//! Refer to [`peer`](crate::tracker::peer) module for more information about peers. +//! Refer to [`peer`] module for more information about peers. //! //! # Configuration //! @@ -348,7 +348,7 @@ //! //! Services can include extra features like pagination, for example. //! -//! Refer to [`services`](crate::tracker::services) module for more information about services. +//! Refer to [`services`] module for more information about services. //! //! # Authentication //! @@ -363,7 +363,7 @@ //! //! To learn more about tracker authentication, refer to the following modules : //! -//! - [`auth`](crate::tracker::auth) module. +//! - [`auth`] module. //! - [`tracker`](crate::tracker) module. //! - [`http`](crate::servers::http) module. //! @@ -417,7 +417,7 @@ //! tracker.send_stats_event(statistics::Event::Tcp4Announce).await //! ``` //! -//! Refer to [`statistics`](crate::tracker::statistics) module for more information about statistics. +//! Refer to [`statistics`] module for more information about statistics. //! //! # Persistence //! @@ -430,7 +430,7 @@ //! - Torrent whitelist //! - Torrent metrics //! -//! Refer to [`databases`](crate::tracker::databases) module for more information about persistence. +//! Refer to [`databases`] module for more information about persistence. pub mod auth; pub mod databases; pub mod error; @@ -753,7 +753,7 @@ impl Tracker { } /// It calculates and returns the general `Tracker` - /// [`TorrentsMetrics`](crate::tracker::TorrentsMetrics) + /// [`TorrentsMetrics`] /// /// # Context: Tracker pub async fn get_torrents_metrics(&self) -> TorrentsMetrics { diff --git a/src/tracker/services/statistics/mod.rs b/src/tracker/services/statistics/mod.rs index 3761e38de..3ef8b52bb 100644 --- a/src/tracker/services/statistics/mod.rs +++ b/src/tracker/services/statistics/mod.rs @@ -3,7 +3,7 @@ //! It includes: //! //! - A [`factory`](crate::tracker::services::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. -//! - A [`get_metrics`](crate::tracker::services::statistics::get_metrics) service to get the [`tracker metrics`](crate::tracker::statistics::Metrics). +//! - A [`get_metrics`] service to get the [`tracker metrics`](crate::tracker::statistics::Metrics). //! //! Tracker metrics are collected using a Publisher-Subscribe pattern. //! @@ -57,7 +57,7 @@ pub struct TrackerMetrics { pub protocol_metrics: Metrics, } -/// It returns all the [`TrackerMetrics`](crate::tracker::services::statistics::TrackerMetrics) +/// It returns all the [`TrackerMetrics`] pub async fn get_metrics(tracker: Arc) -> TrackerMetrics { let torrents_metrics = tracker.get_torrents_metrics().await; let stats = tracker.get_stats().await; diff --git a/src/tracker/services/statistics/setup.rs b/src/tracker/services/statistics/setup.rs index b8d325ab4..4bf5a827a 100644 --- a/src/tracker/services/statistics/setup.rs +++ b/src/tracker/services/statistics/setup.rs @@ -1,6 +1,6 @@ //! Setup for the tracker statistics. //! -//! The [`factory`](crate::tracker::services::statistics::setup::factory) function builds the structs needed for handling the tracker metrics. +//! The [`factory`] function builds the structs needed for handling the tracker metrics. use crate::tracker::statistics; /// It builds the structs needed for handling the tracker metrics. diff --git a/src/tracker/services/torrent.rs b/src/tracker/services/torrent.rs index 0db044d07..934fa6b77 100644 --- a/src/tracker/services/torrent.rs +++ b/src/tracker/services/torrent.rs @@ -2,8 +2,8 @@ //! //! There are two services: //! -//! - [`get_torrent_info`](crate::tracker::services::torrent::get_torrent_info): it returns all the data about one torrent. -//! - [`get_torrents`](crate::tracker::services::torrent::get_torrents): it returns data about some torrent in bulk excluding the peer list. +//! - [`get_torrent_info`]: it returns all the data about one torrent. +//! - [`get_torrents`]: it returns data about some torrent in bulk excluding the peer list. use std::sync::Arc; use serde::Deserialize; @@ -29,7 +29,7 @@ pub struct Info { /// It contains only part of the information the tracker has about a torrent /// -/// It contains the same data as [Info](crate::tracker::services::torrent::Info) but without the list of peers in the swarm. +/// It contains the same data as [Info] but without the list of peers in the swarm. #[derive(Debug, PartialEq, Clone)] pub struct BasicInfo { /// The infohash of the torrent this data is related to @@ -91,7 +91,7 @@ impl Default for Pagination { } } -/// It returns all the information the tracker has about one torrent in a [Info](crate::tracker::services::torrent::Info) struct. +/// It returns all the information the tracker has about one torrent in a [Info] struct. pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Option { let db = tracker.get_torrents().await; @@ -116,7 +116,7 @@ pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Op }) } -/// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`](crate::tracker::services::torrent::BasicInfo) struct, excluding the peer list. +/// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list. pub async fn get_torrents(tracker: Arc, pagination: &Pagination) -> Vec { let db = tracker.get_torrents().await; diff --git a/src/tracker/torrent.rs b/src/tracker/torrent.rs index 4f7e28b6b..de520aeb1 100644 --- a/src/tracker/torrent.rs +++ b/src/tracker/torrent.rs @@ -2,8 +2,8 @@ //! //! There are to main data structures: //! -//! - A torrent [`Entry`](crate::tracker::torrent::Entry): it contains all the information stored by the tracker for one torrent. -//! - The [`SwarmMetadata`](crate::tracker::torrent::SwarmMetadata): it contains aggregate information that can me derived from the torrent entries. +//! - A torrent [`Entry`]: it contains all the information stored by the tracker for one torrent. +//! - The [`SwarmMetadata`]: it contains aggregate information that can me derived from the torrent entries. //! //! A "swarm" is a network of peers that are trying to download the same torrent. //! @@ -27,7 +27,7 @@ //! - The number of peers that have NOT completed downloading the torrent and are still active, that means they are actively participating in the network. //! Peer that don not have a full copy of the torrent data are called "leechers". //! -//! > **NOTICE**: that both [`SwarmMetadata`](crate::tracker::torrent::SwarmMetadata) and [`SwarmStats`](crate::tracker::torrent::SwarmStats) contain the same information. [`SwarmMetadata`](crate::tracker::torrent::SwarmMetadata) is using the names used on [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). +//! > **NOTICE**: that both [`SwarmMetadata`] and [`SwarmStats`] contain the same information. [`SwarmMetadata`] is using the names used on [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). use std::time::Duration; use aquatic_udp_protocol::AnnounceEvent; From ccfb06fbc8fe0a35aeaf4d6fdca6ce9ee4e67ec6 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 12 Oct 2023 10:55:09 +0200 Subject: [PATCH 0125/1297] ci: deny doc warnings --- .github/workflows/testing.yaml | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 3ae18e4db..f60f03e5e 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -65,6 +65,13 @@ jobs: name: Run Lint Checks run: cargo clippy --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic + - id: docs + name: Lint Documentation + env: + RUSTDOCFLAGS: "-D warnings" + run: cargo doc --no-deps --bins --examples --workspace --all-features + + unit: name: Units runs-on: ubuntu-latest @@ -96,10 +103,6 @@ jobs: with: tool: cargo-llvm-cov, cargo-nextest - - id: docs - name: Build Documentation - run: cargo doc --no-deps --bins --examples --workspace --all-features - - id: test-docs name: Run Documentation Tests run: cargo test --doc From eb428f295330150976c1deb517e432910aebf49f Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 15 Oct 2023 15:09:54 +0200 Subject: [PATCH 0126/1297] various: small updates --- .github/workflows/coverage.yaml | 4 +- .github/workflows/labels.yaml | 2 +- Cargo.lock | 74 +++++++++++++++++-------------- Cargo.toml | 68 ++++++++++++++-------------- README.md | 31 ++++++------- contrib/bencode/Cargo.toml | 4 +- packages/configuration/Cargo.toml | 12 ++--- packages/located-error/Cargo.toml | 2 +- packages/primitives/Cargo.toml | 4 +- packages/test-helpers/Cargo.toml | 4 +- 10 files changed, 104 insertions(+), 101 deletions(-) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 1e7dace66..7f5bf2946 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -53,11 +53,11 @@ jobs: - id: check name: Run Build Checks - run: cargo check --workspace --all-targets --all-features + run: cargo check --tests --benches --examples --workspace --all-targets --all-features - id: test name: Run Unit Tests - run: cargo test --workspace --all-targets --all-features + run: cargo test --tests --benches --examples --workspace --all-targets --all-features - id: coverage name: Generate Coverage Report diff --git a/.github/workflows/labels.yaml b/.github/workflows/labels.yaml index bb8283f30..97aaa0308 100644 --- a/.github/workflows/labels.yaml +++ b/.github/workflows/labels.yaml @@ -29,7 +29,7 @@ jobs: - id: sync name: Apply Labels from File - uses: EndBug/label-sync@v2 + uses: EndBug/label-sync@da00f2c11fdb78e4fae44adac2fdd713778ea3e8 with: config-file: .github/labels.json delete-other-labels: true diff --git a/Cargo.lock b/Cargo.lock index ef5e1a4e3..9df190ae5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -120,9 +120,9 @@ checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "async-compression" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb42b2197bf15ccb092b62c74515dbd8b86d0effd934795f6687c93b6e679a2c" +checksum = "f658e2baef915ba0f26f1f7c42bfb8e12f532a01f449a090ded75ae7a07e9ba2" dependencies = [ "brotli", "flate2", @@ -136,9 +136,9 @@ dependencies = [ [[package]] name = "async-trait" -version = "0.1.73" +version = "0.1.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" +checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9" dependencies = [ "proc-macro2", "quote", @@ -765,10 +765,11 @@ dependencies = [ [[package]] name = "deranged" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2696e8a945f658fd14dc3b87242e6b80cd0f36ff04ea560fa39082368847946" +checksum = "0f32d04922c60427da6f9fef14d042d9edddef64cb9d4ce0d64d0685fbeb1fd3" dependencies = [ + "powerfmt", "serde", ] @@ -894,9 +895,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.27" +version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6c98ee8095e9d1dcbf2fcc6d95acccb90d1c81db1e44725c6a984b1dbdfb010" +checksum = "46303f565772937ffe1d394a4fac6f411c6013172fadde9dcdb1e147a086940e" dependencies = [ "crc32fast", "libz-sys", @@ -2131,6 +2132,12 @@ dependencies = [ "plotters-backend", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.17" @@ -2347,9 +2354,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.0" +version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d119d7c7ca818f8a53c300863d4f87566aac09943aef5b355bb83969dae75d87" +checksum = "aaac441002f822bc9705a681810a4dd2963094b9ca0ddc41cb963a4c189189ea" dependencies = [ "aho-corasick", "memchr", @@ -2359,9 +2366,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "465c6fc0621e4abc4187a2bda0937bfd4f722c2730b29562e19689ea796c9a4b" +checksum = "5011c7e263a695dc8ca064cddb722af1be54e517a280b12a5356f98366899e5d" dependencies = [ "aho-corasick", "memchr", @@ -2370,9 +2377,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56d84fdd47036b038fc80dd333d10b6aab10d5d31f4a366e20014def75328d33" +checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" [[package]] name = "rend" @@ -2538,9 +2545,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.18" +version = "0.38.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a74ee2d7c2581cd139b42447d7d9389b889bdaad3a73f1ebb16f2a3237bb19c" +checksum = "745ecfa778e66b2b63c88a61cb36e0eea109e803b0b86bf9879fbc77c70e86ed" dependencies = [ "bitflags 2.4.0", "errno", @@ -2678,9 +2685,9 @@ checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" [[package]] name = "serde" -version = "1.0.188" +version = "1.0.189" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" +checksum = "8e422a44e74ad4001bdc8eede9a4570ab52f71190e9c076d14369f38b9200537" dependencies = [ "serde_derive", ] @@ -2706,9 +2713,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.188" +version = "1.0.189" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" +checksum = "1e48d1f918009ce3145511378cf68d613e3b3d9137d67272562080d68a2b32d5" dependencies = [ "proc-macro2", "quote", @@ -3008,12 +3015,13 @@ dependencies = [ [[package]] name = "time" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "426f806f4089c493dcac0d24c29c01e2c38baf8e30f1b716ee37e83d200b18fe" +checksum = "c4a34ab300f2dee6e562c10a046fc05e358b29f9bf92277f30c3c8d82275f6f5" dependencies = [ "deranged", "itoa", + "powerfmt", "serde", "time-core", "time-macros", @@ -3322,11 +3330,10 @@ checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" [[package]] name = "tracing" -version = "0.1.37" +version = "0.1.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +checksum = "ee2ef2af84856a50c1d430afce2fdded0a4ec7eda868db86409b4543df0797f9" dependencies = [ - "cfg-if", "log", "pin-project-lite", "tracing-core", @@ -3334,9 +3341,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.31" +version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" dependencies = [ "once_cell", ] @@ -3639,9 +3646,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "winnow" -version = "0.5.16" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711d82167854aff2018dfd193aa0fef5370f456732f0d5a0c59b0f1b4b907" +checksum = "a3b801d0e0a6726477cc207f60162da452f3a95adb368399bef20a946e06f65c" dependencies = [ "memchr", ] @@ -3676,20 +3683,19 @@ dependencies = [ [[package]] name = "zstd" -version = "0.12.4" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a27595e173641171fc74a1232b7b1c7a7cb6e18222c11e9dfb9888fa424c53c" +checksum = "bffb3309596d527cfcba7dfc6ed6052f1d39dfbd7c867aa2e865e4a449c10110" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "6.0.6" +version = "7.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee98ffd0b48ee95e6c5168188e44a54550b1564d9d530ee21d5f0eaed1069581" +checksum = "43747c7422e2924c11144d5229878b98180ef8b06cca4ab5af37afc8a8d8ea3e" dependencies = [ - "libc", "zstd-sys", ] diff --git a/Cargo.toml b/Cargo.toml index 3c9354cae..80d7d30b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,47 +29,47 @@ rust-version = "1.72" version = "3.0.0-alpha.12-develop" [dependencies] -aquatic_udp_protocol = "0.8" -async-trait = "0.1" -axum = "0.6" -axum-client-ip = "0.4" -axum-server = { version = "0.5", features = ["tls-rustls"] } -binascii = "0.1" -chrono = { version = "0.4", default-features = false, features = ["clock"] } -config = "0.13" -derive_more = "0.99" -fern = "0.6" -futures = "0.3" -hyper = "0.14" -lazy_static = "1.4" -log = { version = "0.4", features = ["release_max_level_info"] } -multimap = "0.9" -openssl = { version = "0.10", features = ["vendored"] } -percent-encoding = "2.2" -r2d2 = "0.8" -r2d2_mysql = "24.0" -r2d2_sqlite = { version = "0.22", features = ["bundled"] } -rand = "0.8" -serde = { version = "1.0", features = ["derive"] } -serde_bencode = "^0.2" -serde_json = "1.0" -serde_with = "3.2" -thiserror = "1.0" -tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +aquatic_udp_protocol = "0" +async-trait = "0" +axum = "0" +axum-client-ip = "0" +axum-server = { version = "0", features = ["tls-rustls"] } +binascii = "0" +chrono = { version = "0", default-features = false, features = ["clock"] } +config = "0" +derive_more = "0" +fern = "0" +futures = "0" +hyper = "0" +lazy_static = "1" +log = { version = "0", features = ["release_max_level_info"] } +multimap = "0" +openssl = { version = "0", features = ["vendored"] } +percent-encoding = "2" +r2d2 = "0" +r2d2_mysql = "24" +r2d2_sqlite = { version = "0", features = ["bundled"] } +rand = "0" +serde = { version = "1", features = ["derive"] } +serde_bencode = "0" +serde_json = "1" +serde_with = "3" +thiserror = "1" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "packages/configuration" } torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12-develop", path = "contrib/bencode" } torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "packages/located-error" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } -tower-http = { version = "0.4", features = ["compression-full"] } +tower-http = { version = "0", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } [dev-dependencies] -local-ip-address = "0.5" -mockall = "0.11" -reqwest = { version = "0.11.18", features = ["json"] } -serde_bytes = "0.11" -serde_repr = "0.1" -serde_urlencoded = "0.7" +local-ip-address = "0" +mockall = "0" +reqwest = { version = "0", features = ["json"] } +serde_bytes = "0" +serde_repr = "0" +serde_urlencoded = "0" torrust-tracker-test-helpers = { version = "3.0.0-alpha.12-develop", path = "packages/test-helpers" } [workspace] diff --git a/README.md b/README.md index b43db1316..e584db3c8 100644 --- a/README.md +++ b/README.md @@ -2,16 +2,14 @@ [![container_wf_b]][container_wf] [![coverage_wf_b]][coverage_wf] [![deployment_wf_b]][deployment_wf] [![testing_wf_b]][testing_wf] -__Torrust Tracker__, is a [BitTorrent][bittorrent] Tracker (a service that matchmakes peers and collects statistics) written in [Rust Language][rust] and [axum] (a modern web application framework). ___This tracker aims to be respectful to established standards, (both [formal][BEP 00] and [otherwise][torrent_source_felid]).___ +__Torrust Tracker__, is a [BitTorrent][bittorrent] Tracker that matchmakes peers and collects statistics. Written in [Rust Language][rust] with the [axum] web framework. ___This tracker aims to be respectful to established standards, (both [formal][BEP 00] and [otherwise][torrent_source_felid]).___ > This is a [Torrust][torrust] project and is in active development. It is community supported as well as sponsored by [Nautilus Cyberneering][nautilus]. -- _We have a [container guide][containers.md] for those who wish to get started with __Docker__ or __Podman___ - ## Key Features - [x] High Quality and Modern Rust Codebase. -- [x] [Documentation] Generated from Code Comments. +- [x] [Documentation][docs] Generated from Code Comments. - [x] [Comprehensive Suit][coverage] of Unit and Functional Tests. - [x] Good Performance in Busy Conditions. - [x] Support for `UDP`, `HTTP`, and `TLS` Sockets. @@ -35,7 +33,7 @@ __Torrust Tracker__, is a [BitTorrent][bittorrent] Tracker (a service that match ### Container Version -The Torrust Tracker is [deployed to DockerHub][dockerhub_torrust_tracker], you can run a demo immediately with the following commands: +The Torrust Tracker is [deployed to DockerHub][dockerhub], you can run a demo immediately with the following commands: #### Docker: @@ -126,15 +124,14 @@ The following services are provided by the default configuration: - [Tracker (UDP)][udp] ## Contributing - -This is an open-source community supported project.
-We welcome contributions from the community! +We are happy to support and welcome new people to our project. Please consider our [contributor guide][guide.md].
+This is an open-source community supported project. We welcome contributions from the community! __How can you contribute?__ - Bug reports and feature requests. - Code contributions. You can start by looking at the issues labeled "[good first issues]". -- Documentation improvements. Check the [documentation] and [API documentation] for typos, errors, or missing information. +- Documentation improvements. Check the [documentation][docs] and [API documentation][api] for typos, errors, or missing information. - Participation in the community. You can help by answering questions in the [discussions]. ## License @@ -153,8 +150,7 @@ Some files include explicit copyright notices and/or license notices. For prosperity, versions of Torrust Tracker that are older than five years are automatically granted the [MIT-0][MIT_0] license in addition to the existing [AGPL-3.0-only][AGPL_3_0] license. -## Contributions - +## Contributor Agreement The copyright of the Torrust Tracker is retained by the respective authors. **Contributors agree:** @@ -163,6 +159,8 @@ The copyright of the Torrust Tracker is retained by the respective authors. **The Torrust-Tracker project has no copyright assignment agreement.** +_We kindly ask you to take time and consider The Torrust Project [Contributor Agreement][agreement.md] in full._ + ## Acknowledgments This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [Dutch Bits]. Also thanks to [Naim A.] and [greatest-ape] for some parts of the code. Further added features and functions thanks to [Power2All]. @@ -185,7 +183,7 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [coverage]: https://app.codecov.io/gh/torrust/torrust-tracker [torrust]: https://torrust.com/ -[dockerhub_torrust_tracker]: https://hub.docker.com/r/torrust/tracker/tags +[dockerhub]: https://hub.docker.com/r/torrust/tracker/tags [torrent_source_felid]: https://github.com/qbittorrent/qBittorrent/discussions/19406 @@ -199,24 +197,23 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [containers.md]: ./docs/containers.md +[docs]: https://docs.rs/torrust-tracker/latest/ [api]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/apis/v1 [http]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/http [udp]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/udp [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 -[documentation]: https://docs.rs/torrust-tracker/ -[API documentation]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/apis/v1 [discussions]: https://github.com/torrust/torrust-tracker/discussions -[COPYRIGHT]: ./COPYRIGHT +[guide.md]: https://github.com/torrust/.github/blob/main/info/contributing.md +[agreement.md]: https://github.com/torrust/.github/blob/main/info/licensing/contributor_agreement_v01.md + [AGPL_3_0]: ./docs/licenses/LICENSE-AGPL_3_0 [MIT_0]: ./docs/licenses/LICENSE-MIT_0 [FSF]: https://www.fsf.org/ - [nautilus]: https://github.com/orgs/Nautilus-Cyberneering/ [Dutch Bits]: https://dutchbits.nl [Naim A.]: https://github.com/naim94a/udpt [greatest-ape]: https://github.com/greatest-ape/aquatic [Power2All]: https://github.com/power2all - diff --git a/contrib/bencode/Cargo.toml b/contrib/bencode/Cargo.toml index 3918aa6ba..f7bab0585 100644 --- a/contrib/bencode/Cargo.toml +++ b/contrib/bencode/Cargo.toml @@ -16,10 +16,10 @@ rust-version.workspace = true version.workspace = true [dependencies] -error-chain = "0.12" +error-chain = "0" [dev-dependencies] -criterion = "0.5" +criterion = "0" [[test]] name = "test" diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 94cf1d0f5..e373b4269 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -15,12 +15,12 @@ rust-version.workspace = true version.workspace = true [dependencies] -config = "0.13" -log = { version = "0.4", features = ["release_max_level_info"] } -serde = { version = "1.0", features = ["derive"] } -serde_with = "3.2" -thiserror = "1.0" -toml = "0.8" +config = "0" +log = { version = "0", features = ["release_max_level_info"] } +serde = { version = "1", features = ["derive"] } +serde_with = "3" +thiserror = "1" +toml = "0" torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "../located-error" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index 6bc219374..5b266934c 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -15,7 +15,7 @@ rust-version.workspace = true version.workspace = true [dependencies] -log = { version = "0.4", features = ["release_max_level_info"] } +log = { version = "0", features = ["release_max_level_info"] } [dev-dependencies] thiserror = "1.0" diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index 3fac88bef..efcce71a9 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -15,5 +15,5 @@ rust-version.workspace = true version.workspace = true [dependencies] -derive_more = "0.99" -serde = { version = "1.0", features = ["derive"] } +derive_more = "0" +serde = { version = "1", features = ["derive"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index d428cbf3e..9ae891a01 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -15,7 +15,7 @@ rust-version.workspace = true version.workspace = true [dependencies] -lazy_static = "1.4" -rand = "0.8.5" +lazy_static = "1" +rand = "0" torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } From cb914daa9e98c7414b2987c3724f63818d187455 Mon Sep 17 00:00:00 2001 From: Dan Groshev Date: Mon, 9 Oct 2023 19:23:06 +0100 Subject: [PATCH 0127/1297] feat: replace peer ID recognition with tdyne-peer-id-registry --- Cargo.lock | 63 ++++++++++++++ Cargo.toml | 2 + .../apis/v1/context/torrent/resources/peer.rs | 2 +- src/tracker/peer.rs | 86 ++----------------- 4 files changed, 73 insertions(+), 80 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9df190ae5..510e84559 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2066,6 +2066,44 @@ dependencies = [ "sha2", ] +[[package]] +name = "phf" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_shared" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project" version = "1.1.3" @@ -2847,6 +2885,12 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27f6278552951f1f2b8cf9da965d10969b2efdea95a6ec47987ab46edfe263a" +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + [[package]] name = "slab" version = "0.4.9" @@ -2965,6 +3009,23 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +[[package]] +name = "tdyne-peer-id" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dde285ba6f835045648f9d4f4703f778aaafb47421d9c5dff47be1534370c3e" + +[[package]] +name = "tdyne-peer-id-registry" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1923b2d356e080e8bee847c39b58de293309df2fe0bc9ecd859ae3210e868c25" +dependencies = [ + "phf", + "phf_codegen", + "tdyne-peer-id", +] + [[package]] name = "tempfile" version = "3.8.0" @@ -3219,6 +3280,8 @@ dependencies = [ "serde_repr", "serde_urlencoded", "serde_with", + "tdyne-peer-id", + "tdyne-peer-id-registry", "thiserror", "tokio", "torrust-tracker-configuration", diff --git a/Cargo.toml b/Cargo.toml index 80d7d30b0..ab31a9275 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,6 +54,8 @@ serde = { version = "1", features = ["derive"] } serde_bencode = "0" serde_json = "1" serde_with = "3" +tdyne-peer-id = "1" +tdyne-peer-id-registry = "0.1" thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "packages/configuration" } diff --git a/src/servers/apis/v1/context/torrent/resources/peer.rs b/src/servers/apis/v1/context/torrent/resources/peer.rs index 4989cec52..e0cab853e 100644 --- a/src/servers/apis/v1/context/torrent/resources/peer.rs +++ b/src/servers/apis/v1/context/torrent/resources/peer.rs @@ -39,7 +39,7 @@ impl From for Id { fn from(peer_id: tracker::peer::Id) -> Self { Id { id: peer_id.to_hex_string(), - client: peer_id.get_client_name().map(std::string::ToString::to_string), + client: peer_id.get_client_name(), } } } diff --git a/src/tracker/peer.rs b/src/tracker/peer.rs index d6517f213..4027799a9 100644 --- a/src/tracker/peer.rs +++ b/src/tracker/peer.rs @@ -252,81 +252,9 @@ impl Id { } #[must_use] - pub fn get_client_name(&self) -> Option<&'static str> { - if self.0[0] == b'M' { - return Some("BitTorrent"); - } - if self.0[0] == b'-' { - let name = match &self.0[1..3] { - b"AG" | b"A~" => "Ares", - b"AR" => "Arctic", - b"AV" => "Avicora", - b"AX" => "BitPump", - b"AZ" => "Azureus", - b"BB" => "BitBuddy", - b"BC" => "BitComet", - b"BF" => "Bitflu", - b"BG" => "BTG (uses Rasterbar libtorrent)", - b"BR" => "BitRocket", - b"BS" => "BTSlave", - b"BX" => "~Bittorrent X", - b"CD" => "Enhanced CTorrent", - b"CT" => "CTorrent", - b"DE" => "DelugeTorrent", - b"DP" => "Propagate Data Client", - b"EB" => "EBit", - b"ES" => "electric sheep", - b"FT" => "FoxTorrent", - b"FW" => "FrostWire", - b"FX" => "Freebox BitTorrent", - b"GS" => "GSTorrent", - b"HL" => "Halite", - b"HN" => "Hydranode", - b"KG" => "KGet", - b"KT" => "KTorrent", - b"LH" => "LH-ABC", - b"LP" => "Lphant", - b"LT" => "libtorrent", - b"lt" => "libTorrent", - b"LW" => "LimeWire", - b"MO" => "MonoTorrent", - b"MP" => "MooPolice", - b"MR" => "Miro", - b"MT" => "MoonlightTorrent", - b"NX" => "Net Transport", - b"PD" => "Pando", - b"qB" => "qBittorrent", - b"QD" => "QQDownload", - b"QT" => "Qt 4 Torrent example", - b"RT" => "Retriever", - b"S~" => "Shareaza alpha/beta", - b"SB" => "~Swiftbit", - b"SS" => "SwarmScope", - b"ST" => "SymTorrent", - b"st" => "sharktorrent", - b"SZ" => "Shareaza", - b"TN" => "TorrentDotNET", - b"TR" => "Transmission", - b"TS" => "Torrentstorm", - b"TT" => "TuoTu", - b"UL" => "uLeecher!", - b"UT" => "µTorrent", - b"UW" => "µTorrent Web", - b"VG" => "Vagaa", - b"WD" => "WebTorrent Desktop", - b"WT" => "BitLet", - b"WW" => "WebTorrent", - b"WY" => "FireTorrent", - b"XL" => "Xunlei", - b"XT" => "XanTorrent", - b"XX" => "Xtorrent", - b"ZT" => "ZipTorrent", - _ => return None, - }; - Some(name) - } else { - None - } + pub fn get_client_name(&self) -> Option { + let peer_id = tdyne_peer_id::PeerId::from(self.0); + tdyne_peer_id_registry::parse(peer_id).ok().map(|parsed| parsed.client) } } @@ -336,9 +264,9 @@ impl Serialize for Id { S: serde::Serializer, { #[derive(Serialize)] - struct PeerIdInfo<'a> { + struct PeerIdInfo { id: Option, - client: Option<&'a str>, + client: Option, } let obj = PeerIdInfo { @@ -476,7 +404,7 @@ mod test { #[test] fn it_should_be_serializable() { let torrent_peer = Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), + peer_id: peer::Id(*b"-qB0000-000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: Current::now(), uploaded: NumberOfBytes(0), @@ -490,7 +418,7 @@ mod test { let expected_raw_json = r#" { "peer_id": { - "id": "0x2d71423030303030303030303030303030303030", + "id": "0x2d7142303030302d303030303030303030303030", "client": "qBittorrent" }, "peer_addr":"126.0.0.1:8080", From 8ec0a23e68f1b5bd3c71c84358f463e609d56fac Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 7 Nov 2023 14:07:31 +0100 Subject: [PATCH 0128/1297] chore: update deps --- Cargo.lock | 416 ++++++++++++++++-------------- Cargo.toml | 2 +- packages/located-error/Cargo.toml | 2 +- 3 files changed, 220 insertions(+), 200 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 510e84559..749c0fa53 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19,9 +19,9 @@ checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "ahash" -version = "0.7.6" +version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" +checksum = "5a824f2aa7e75a0c98c5a504fceb80649e9c35265d44525b5f94de4771a395cd" dependencies = [ "getrandom", "once_cell", @@ -30,13 +30,14 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.3" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" +checksum = "91429305e9f0a25f6205c5b8e0d2db09e0708a7a6df0f42212bb56c32c8ac97a" dependencies = [ "cfg-if", "once_cell", "version_check", + "zerocopy", ] [[package]] @@ -142,7 +143,7 @@ checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -254,9 +255,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "base64" -version = "0.21.4" +version = "0.21.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ba43ea6f343b788c8764558649e08df62f86c6ef251fdaeb1ffd010a9ae50a2" +checksum = "35636a1494ede3b646cc98f74f8e62c773a38a659ebc777a2cf26b9b74171df9" [[package]] name = "bigdecimal" @@ -277,11 +278,11 @@ checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" [[package]] name = "bindgen" -version = "0.68.1" +version = "0.69.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "726e4313eb6ec35d2730258ad4e15b547ee75d6afaa1361a922e78e59b7d8078" +checksum = "9ffcebc3849946a7170a05992aac39da343a90676ab392c51a4280981d6379c2" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.4.1", "cexpr", "clang-sys", "lazy_static", @@ -292,7 +293,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -303,9 +304,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.4.0" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" +checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07" [[package]] name = "bitvec" @@ -386,9 +387,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da74e2b81409b1b743f8f0c62cc6254afefb8b8e50bbfe3735550f7aeefa3448" +checksum = "4e2e4afe60d7dd600fdd3de8d0f08c2b7ec039712e3b6137ff98b7004e82de4f" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -524,18 +525,18 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.6" +version = "4.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d04704f56c2cde07f43e8e2c154b43f216dc5c92fc98ada720177362f953b956" +checksum = "ac495e00dcec98c83465d5ad66c5c4fabd652fd6686e7c6269b117e729a6f17b" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" -version = "4.4.6" +version = "4.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e231faeaca65ebd1ea3c737966bf858971cd38c3849107aa3ea7de90a804e45" +checksum = "c77ed9a32a62e6ca27175d00d29d05ca32e396ea1eb5fb01d8256b669cec7663" dependencies = [ "anstyle", "clap_lex", @@ -543,9 +544,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.5.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd7cc57abe963c6d3b9d8be5b06ba7c8957a930305ca90304f24ef040aa6f961" +checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1" [[package]] name = "cmake" @@ -599,9 +600,9 @@ checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" [[package]] name = "cpufeatures" -version = "0.2.9" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" +checksum = "ce420fe07aecd3e67c5f910618fe65e94158f6dcc0adf44e00d69ce2bdfe0fd0" dependencies = [ "libc", ] @@ -749,7 +750,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -760,7 +761,7 @@ checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ "darling_core", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -794,7 +795,7 @@ checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -984,7 +985,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -996,7 +997,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -1008,7 +1009,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -1019,9 +1020,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" [[package]] name = "futures" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23342abe12aba583913b2e62f22225ff9c950774065e4bfb61a19cd9770fec40" +checksum = "da0290714b38af9b4a7b094b8a37086d1b4e61f2df9122c3cad2577669145335" dependencies = [ "futures-channel", "futures-core", @@ -1034,9 +1035,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" +checksum = "ff4dd66668b557604244583e3e1e1eada8c5c2e96a6d0d6653ede395b78bbacb" dependencies = [ "futures-core", "futures-sink", @@ -1044,15 +1045,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" +checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c" [[package]] name = "futures-executor" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccecee823288125bd88b4d7f565c9e58e41858e47ab72e8ea2d64e93624386e0" +checksum = "0f4fb8693db0cf099eadcca0efe2a5a22e4550f98ed16aba6c48700da29597bc" dependencies = [ "futures-core", "futures-task", @@ -1061,38 +1062,38 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" +checksum = "8bf34a163b5c4c52d0478a4d757da8fb65cabef42ba90515efee0f6f9fa45aaa" [[package]] name = "futures-macro" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" +checksum = "53b153fd91e4b0147f4aced87be237c98248656bb01050b96bf3ee89220a8ddb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] name = "futures-sink" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" +checksum = "e36d3378ee38c2a36ad710c5d30c2911d752cb941c00c72dbabfb786a7970817" [[package]] name = "futures-task" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" +checksum = "efd193069b0ddadc69c46389b740bbccdd97203899b48d09c5f7969591d6bae2" [[package]] name = "futures-util" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" +checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104" dependencies = [ "futures-channel", "futures-core", @@ -1170,7 +1171,7 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" dependencies = [ - "ahash 0.7.6", + "ahash 0.7.7", ] [[package]] @@ -1179,16 +1180,16 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" dependencies = [ - "ahash 0.8.3", + "ahash 0.8.6", ] [[package]] name = "hashbrown" -version = "0.14.1" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dfda62a12f55daeae5015f81b0baea145391cb4520f86c248fc615d72640d12" +checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156" dependencies = [ - "ahash 0.8.3", + "ahash 0.8.6", "allocator-api2", ] @@ -1198,7 +1199,7 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7" dependencies = [ - "hashbrown 0.14.1", + "hashbrown 0.14.2", ] [[package]] @@ -1276,7 +1277,7 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "socket2 0.4.9", + "socket2 0.4.10", "tokio", "tower-service", "tracing", @@ -1298,16 +1299,16 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.57" +version = "0.1.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fad5b825842d2b38bd206f3e81d6957625fd7f0a361e345c30e01a0ae2dd613" +checksum = "8326b86b6cff230b97d0d312a6c40a60726df3332e721f72a1b035f451663b20" dependencies = [ "android_system_properties", "core-foundation-sys", "iana-time-zone-haiku", "js-sys", "wasm-bindgen", - "windows", + "windows-core", ] [[package]] @@ -1348,12 +1349,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.0.2" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8adf3ddd720272c6ea8bf59463c04e0f93d0bbf7c5439b691bca2987e0270897" +checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f" dependencies = [ "equivalent", - "hashbrown 0.14.1", + "hashbrown 0.14.2", "serde", ] @@ -1364,14 +1365,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] name = "ipnet" -version = "2.8.0" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" +checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" [[package]] name = "is-terminal" @@ -1410,9 +1411,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.64" +version = "0.3.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" +checksum = "54c0c35952f67de54bb584e9fd912b3023117cbafc0a77d8f3dee1fb5f572fe8" dependencies = [ "wasm-bindgen", ] @@ -1515,9 +1516,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.149" +version = "0.2.150" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a08173bc88b7955d1b3145aa561539096c421ac8debde8cbc3612ec635fee29b" +checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c" [[package]] name = "libloading" @@ -1577,9 +1578,9 @@ dependencies = [ [[package]] name = "lock_api" -version = "0.4.10" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16" +checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" dependencies = [ "autocfg", "scopeguard", @@ -1644,9 +1645,9 @@ dependencies = [ [[package]] name = "mio" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2" +checksum = "3dce281c5e46beae905d4de1870d8b1509a9142b62eedf18b443b011ca8343d0" dependencies = [ "libc", "wasi", @@ -1682,9 +1683,9 @@ dependencies = [ [[package]] name = "multimap" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70db9248a93dc36a36d9a47898caa007a32755c7ad140ec64eeeb50d5a730631" +checksum = "e1a5d38b9b352dbd913288736af36af41c48d61b1a8cd34bcecd727561b7d511" dependencies = [ "serde", ] @@ -1710,7 +1711,7 @@ dependencies = [ "percent-encoding", "serde", "serde_json", - "socket2 0.5.4", + "socket2 0.5.5", "twox-hash", "url", ] @@ -1728,7 +1729,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", "termcolor", "thiserror", ] @@ -1739,10 +1740,10 @@ version = "0.30.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57349d5a326b437989b6ee4dc8f2f34b0cc131202748414712a8e7d98952fc8c" dependencies = [ - "base64 0.21.4", + "base64 0.21.5", "bigdecimal", "bindgen", - "bitflags 2.4.0", + "bitflags 2.4.1", "bitvec", "byteorder", "bytes", @@ -1908,11 +1909,11 @@ checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" [[package]] name = "openssl" -version = "0.10.57" +version = "0.10.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bac25ee399abb46215765b1cb35bc0212377e58a061560d8b29b024fd0430e7c" +checksum = "7a257ad03cd8fb16ad4172fedf8094451e1af1c4b70097636ef2eac9a5f0cc33" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.4.1", "cfg-if", "foreign-types", "libc", @@ -1929,7 +1930,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -1940,18 +1941,18 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "300.1.5+3.1.3" +version = "300.1.6+3.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "559068e4c12950d7dcaa1857a61725c0d38d4fc03ff8e070ab31a75d6e316491" +checksum = "439fac53e092cd7442a3660c85dde4643ab3b5bd39040912388dcdabf6b88085" dependencies = [ "cc", ] [[package]] name = "openssl-sys" -version = "0.9.93" +version = "0.9.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db4d56a4c0478783083cfafcc42493dd4a981d41669da64b4572a2a089b51b1d" +checksum = "40a4130519a360279579c2053038317e40eff64d13fd3f004f9e1b72b8a6aaf9" dependencies = [ "cc", "libc", @@ -1982,9 +1983,9 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.8" +version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447" +checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e" dependencies = [ "cfg-if", "libc", @@ -2011,7 +2012,7 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b13fe415cdf3c8e44518e18a7c95a13431d9bdf6d15367d82b23c377fdd441a" dependencies = [ - "base64 0.21.4", + "base64 0.21.5", "serde", ] @@ -2023,9 +2024,9 @@ checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" [[package]] name = "pest" -version = "2.7.4" +version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c022f1e7b65d6a24c0dbbd5fb344c66881bc01f3e5ae74a1c8100f2f985d98a4" +checksum = "ae9cee2a55a544be8b89dc6848072af97a20f2422603c10865be2a42b580fff5" dependencies = [ "memchr", "thiserror", @@ -2034,9 +2035,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.4" +version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35513f630d46400a977c4cb58f78e1bfbe01434316e60c37d27b9ad6139c66d8" +checksum = "81d78524685f5ef2a3b3bd1cafbc9fcabb036253d9b1463e726a91cd16e2dfc2" dependencies = [ "pest", "pest_generator", @@ -2044,22 +2045,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.4" +version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc9fc1b9e7057baba189b5c626e2d6f40681ae5b6eb064dc7c7834101ec8123a" +checksum = "68bd1206e71118b5356dae5ddc61c8b11e28b09ef6a31acbd15ea48a28e0c227" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] name = "pest_meta" -version = "2.7.4" +version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1df74e9e7ec4053ceb980e7c0c8bd3594e977fde1af91daba9c928e8e8c6708d" +checksum = "7c747191d4ad9e4a4ab9c8798f1e82a39affe7ef9648390b7e5548d18e099de6" dependencies = [ "once_cell", "pest", @@ -2121,7 +2122,7 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -2383,18 +2384,18 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.3.5" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "regex" -version = "1.10.1" +version = "1.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaac441002f822bc9705a681810a4dd2963094b9ca0ddc41cb963a4c189189ea" +checksum = "380b951a9c5e80ddfd6136919eef32310721aa4aacd4889a8d39124b026ab343" dependencies = [ "aho-corasick", "memchr", @@ -2404,9 +2405,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5011c7e263a695dc8ca064cddb722af1be54e517a280b12a5356f98366899e5d" +checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f" dependencies = [ "aho-corasick", "memchr", @@ -2434,7 +2435,7 @@ version = "0.11.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "046cd98826c46c2ac8ddecae268eb5c2e58628688a5fc7a2643704a73faba95b" dependencies = [ - "base64 0.21.4", + "base64 0.21.5", "bytes", "encoding_rs", "futures-core", @@ -2468,17 +2469,16 @@ dependencies = [ [[package]] name = "ring" -version = "0.16.20" +version = "0.17.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +checksum = "fb0205304757e5d899b9c2e448b867ffd03ae7f988002e47cd24954391394d0b" dependencies = [ "cc", + "getrandom", "libc", - "once_cell", "spin", "untrusted", - "web-sys", - "winapi", + "windows-sys", ] [[package]] @@ -2526,7 +2526,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "549b9d036d571d42e6e85d1c1425e2ac83491075078ca9a15be021c56b1641f2" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.4.1", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -2583,11 +2583,11 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.19" +version = "0.38.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "745ecfa778e66b2b63c88a61cb36e0eea109e803b0b86bf9879fbc77c70e86ed" +checksum = "2b426b0506e5d50a7d8dafcf2e81471400deb602392c7dd110815afb4eaf02a3" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.4.1", "errno", "libc", "linux-raw-sys", @@ -2596,9 +2596,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.21.7" +version = "0.21.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd8d6c9f025a446bc4d18ad9632e69aec8f287aa84499ee335599fabd20c3fd8" +checksum = "446e14c5cda4f3f30fe71863c34ec70f5ac79d6087097ad0bb433e1be5edf04c" dependencies = [ "log", "ring", @@ -2612,14 +2612,14 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d3987094b1d07b653b7dfdc3f70ce9a1da9c51ac18c1b06b662e4f9a0e9f4b2" dependencies = [ - "base64 0.21.4", + "base64 0.21.5", ] [[package]] name = "rustls-webpki" -version = "0.101.6" +version = "0.101.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c7d5dece342910d9ba34d259310cae3e0154b873b35408b787b59bce53d34fe" +checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" dependencies = [ "ring", "untrusted", @@ -2678,9 +2678,9 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sct" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" +checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" dependencies = [ "ring", "untrusted", @@ -2723,9 +2723,9 @@ checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" [[package]] name = "serde" -version = "1.0.189" +version = "1.0.192" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e422a44e74ad4001bdc8eede9a4570ab52f71190e9c076d14369f38b9200537" +checksum = "bca2a08484b285dcb282d0f67b26cadc0df8b19f8c12502c13d966bf9482f001" dependencies = [ "serde_derive", ] @@ -2751,20 +2751,20 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.189" +version = "1.0.192" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e48d1f918009ce3145511378cf68d613e3b3d9137d67272562080d68a2b32d5" +checksum = "d6c7207fbec9faa48073f3e3074cbe553af6ea512d7c21ba46e434e70ea9fbc1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] name = "serde_json" -version = "1.0.107" +version = "1.0.108" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b420ce6e3d8bd882e9b243c6eed35dbc9a6110c9769e74b584e0d68d1f20c65" +checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" dependencies = [ "itoa", "ryu", @@ -2783,20 +2783,20 @@ dependencies = [ [[package]] name = "serde_repr" -version = "0.1.16" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" +checksum = "3081f5ffbb02284dda55132aa26daecedd7372a42417bbbab6f14ab7d6bb9145" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] name = "serde_spanned" -version = "0.6.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96426c9936fd7a0124915f9185ea1d20aa9445cc9821142f0a73bc9207a2e186" +checksum = "12022b835073e5b11e90a14f86838ceb1c8fb0325b72416845c487ac0fa95e80" dependencies = [ "serde", ] @@ -2815,15 +2815,15 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.3.0" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ca3b16a3d82c4088f343b7480a93550b3eabe1a358569c2dfe38bbcead07237" +checksum = "64cd236ccc1b7a29e7e2739f27c0b2dd199804abc4290e32f59f3b68d6405c23" dependencies = [ - "base64 0.21.4", + "base64 0.21.5", "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.0.2", + "indexmap 2.1.0", "serde", "serde_json", "serde_with_macros", @@ -2832,14 +2832,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.3.0" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e6be15c453eb305019bfa438b1593c731f36a289a7853f7707ee29e870b3b3c" +checksum = "93634eb5f75a2323b16de4748022ac4297f9e76b6dced2be287a099f41b5e788" dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -2908,9 +2908,9 @@ checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a" [[package]] name = "socket2" -version = "0.4.9" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662" +checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d" dependencies = [ "libc", "winapi", @@ -2918,9 +2918,9 @@ dependencies = [ [[package]] name = "socket2" -version = "0.5.4" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4031e820eb552adee9295814c0ced9e5cf38ddf1e8b7d566d6de8e2538ea989e" +checksum = "7b5fac59a5cb5dd637972e5fca70daf0523c9067fcdc4842f053dae04a18f8e9" dependencies = [ "libc", "windows-sys", @@ -2928,9 +2928,9 @@ dependencies = [ [[package]] name = "spin" -version = "0.5.2" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" [[package]] name = "static_assertions" @@ -2967,9 +2967,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.38" +version = "2.0.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b" +checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" dependencies = [ "proc-macro2", "quote", @@ -3028,9 +3028,9 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.8.0" +version = "3.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb94d2f3cc536af71caac6b6fcebf65860b347e7ce0cc9ebe8f70d3e521054ef" +checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" dependencies = [ "cfg-if", "fastrand", @@ -3056,22 +3056,22 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.49" +version = "1.0.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1177e8c6d7ede7afde3585fd2513e611227efd6481bd78d2e82ba1ce16557ed4" +checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.49" +version = "1.0.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10712f02019e9288794769fba95cd6847df9874d49d871d062172f9dd41bc4cc" +checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -3141,7 +3141,7 @@ dependencies = [ "num_cpus", "pin-project-lite", "signal-hook-registry", - "socket2 0.5.4", + "socket2 0.5.5", "tokio-macros", "windows-sys", ] @@ -3154,7 +3154,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", ] [[package]] @@ -3179,9 +3179,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.9" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d68074620f57a0b21594d9735eb2e98ab38b17f80d3fcb189fca266771ca60d" +checksum = "5419f34732d9eb6ee4c3578b7989078579b7f039cbbb9ca2c4da015749371e15" dependencies = [ "bytes", "futures-core", @@ -3202,21 +3202,21 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.2" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" +checksum = "a1a195ec8c9da26928f773888e0742ca3ca1040c6cd859c919c9f59c1954ab35" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.20.2", + "toml_edit 0.21.0", ] [[package]] name = "toml_datetime" -version = "0.6.3" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" +checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" dependencies = [ "serde", ] @@ -3227,18 +3227,18 @@ version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ - "indexmap 2.0.2", + "indexmap 2.1.0", "toml_datetime", "winnow", ] [[package]] name = "toml_edit" -version = "0.20.2" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" +checksum = "d34d383cd00a163b4a5b85053df514d45bc330f6de7737edfe0a93311d1eaa03" dependencies = [ - "indexmap 2.0.2", + "indexmap 2.1.0", "serde", "serde_spanned", "toml_datetime", @@ -3302,7 +3302,7 @@ dependencies = [ "serde", "serde_with", "thiserror", - "toml 0.8.2", + "toml 0.8.8", "torrust-tracker-located-error", "torrust-tracker-primitives", "uuid", @@ -3365,7 +3365,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c5bb1d698276a2443e5ecfabc1008bf15a36c12e6a7176e7bf089ea9131140" dependencies = [ "async-compression", - "bitflags 2.4.0", + "bitflags 2.4.1", "bytes", "futures-core", "futures-util", @@ -3393,9 +3393,9 @@ checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" [[package]] name = "tracing" -version = "0.1.39" +version = "0.1.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee2ef2af84856a50c1d430afce2fdded0a4ec7eda868db86409b4543df0797f9" +checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" dependencies = [ "log", "pin-project-lite", @@ -3463,9 +3463,9 @@ dependencies = [ [[package]] name = "untrusted" -version = "0.7.1" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" @@ -3480,9 +3480,9 @@ dependencies = [ [[package]] name = "uuid" -version = "1.4.1" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79daa5ed5740825c40b389c5e50312b9c86df53fccd33f281df655642b43869d" +checksum = "88ad59a7560b41a70d191093a945f0b87bc1deeda46fb237479708a1d6b6cdfc" dependencies = [ "getrandom", "rand", @@ -3527,9 +3527,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.87" +version = "0.2.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" +checksum = "7daec296f25a1bae309c0cd5c29c4b260e510e6d813c286b19eaadf409d40fce" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -3537,24 +3537,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.87" +version = "0.2.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" +checksum = "e397f4664c0e4e428e8313a469aaa58310d302159845980fd23b0f22a847f217" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.37" +version = "0.4.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" +checksum = "9afec9963e3d0994cac82455b2b3502b81a7f40f9a0d32181f7528d9f4b43e02" dependencies = [ "cfg-if", "js-sys", @@ -3564,9 +3564,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.87" +version = "0.2.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" +checksum = "5961017b3b08ad5f3fe39f1e79877f8ee7c23c5e5fd5eb80de95abc41f1f16b2" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3574,28 +3574,28 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.87" +version = "0.2.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" +checksum = "c5353b8dab669f5e10f5bd76df26a9360c748f054f862ff5f3f8aae0c7fb3907" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.39", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.87" +version = "0.2.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" +checksum = "0d046c5d029ba91a1ed14da14dca44b68bf2f124cfbaf741c54151fdb3e0750b" [[package]] name = "web-sys" -version = "0.3.64" +version = "0.3.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" +checksum = "5db499c5f66323272151db0e666cd34f78617522fb0c1604d31a27c50c206a85" dependencies = [ "js-sys", "wasm-bindgen", @@ -3633,10 +3633,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] -name = "windows" -version = "0.48.0" +name = "windows-core" +version = "0.51.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +checksum = "f1f8cf84f35d2db49a46868f947758c7a1138116f7fac3bc844f43ade1292e64" dependencies = [ "windows-targets", ] @@ -3709,9 +3709,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "winnow" -version = "0.5.17" +version = "0.5.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3b801d0e0a6726477cc207f60162da452f3a95adb368399bef20a946e06f65c" +checksum = "829846f3e3db426d4cee4510841b71a8e58aa2a76b1132579487ae430ccd9c7b" dependencies = [ "memchr", ] @@ -3744,6 +3744,26 @@ dependencies = [ "linked-hash-map", ] +[[package]] +name = "zerocopy" +version = "0.7.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cd369a67c0edfef15010f980c3cbe45d7f651deac2cd67ce097cd801de16557" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2f140bda219a26ccc0cdb03dba58af72590c53b22642577d88a927bc5c87d6b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] + [[package]] name = "zstd" version = "0.13.0" diff --git a/Cargo.toml b/Cargo.toml index ab31a9275..fd6230f80 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,7 +55,7 @@ serde_bencode = "0" serde_json = "1" serde_with = "3" tdyne-peer-id = "1" -tdyne-peer-id-registry = "0.1" +tdyne-peer-id-registry = "0" thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "packages/configuration" } diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index 5b266934c..fa3d1d76d 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -18,4 +18,4 @@ version.workspace = true log = { version = "0", features = ["release_max_level_info"] } [dev-dependencies] -thiserror = "1.0" +thiserror = "1" From dbc8920c70f6a78abf71fc86d421828d7970bbaa Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 7 Nov 2023 14:51:28 +0100 Subject: [PATCH 0129/1297] ci: fix nightly changes --- contrib/bencode/src/access/dict.rs | 2 ++ src/servers/udp/connection_cookie.rs | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/contrib/bencode/src/access/dict.rs b/contrib/bencode/src/access/dict.rs index 596d9535e..7efe93fc3 100644 --- a/contrib/bencode/src/access/dict.rs +++ b/contrib/bencode/src/access/dict.rs @@ -21,6 +21,7 @@ pub trait BDictAccess { impl<'a, V> BDictAccess<&'a [u8], V> for BTreeMap<&'a [u8], V> { fn to_list(&self) -> Vec<(&&'a [u8], &V)> { + #[allow(clippy::map_identity)] self.iter().map(|(k, v)| (k, v)).collect() } @@ -43,6 +44,7 @@ impl<'a, V> BDictAccess<&'a [u8], V> for BTreeMap<&'a [u8], V> { impl<'a, V> BDictAccess, V> for BTreeMap, V> { fn to_list(&self) -> Vec<(&Cow<'a, [u8]>, &V)> { + #[allow(clippy::map_identity)] self.iter().map(|(k, v)| (k, v)).collect() } diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs index 4dc9896ab..19e61f14e 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/servers/udp/connection_cookie.rs @@ -173,11 +173,12 @@ mod tests { #[test] fn it_should_make_a_connection_cookie() { // Note: This constant may need to be updated in the future as the hash is not guaranteed to to be stable between versions. - const ID_COOKIE: Cookie = [23, 204, 198, 29, 48, 180, 62, 19]; + const ID_COOKIE_OLD: Cookie = [23, 204, 198, 29, 48, 180, 62, 19]; + const ID_COOKIE_NEW: Cookie = [41, 166, 45, 246, 249, 24, 108, 203]; let cookie = make(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)); - assert_eq!(cookie, ID_COOKIE); + assert!(cookie == ID_COOKIE_OLD || cookie == ID_COOKIE_NEW); } #[test] From 9c0b090ca9c3d39497c2cfbd5d1e2de621bb1ab3 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 7 Nov 2023 17:36:30 +0100 Subject: [PATCH 0130/1297] fixup: rename field for clippy --- tests/servers/http/client.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/servers/http/client.rs b/tests/servers/http/client.rs index f5cdca398..0dbdd9cf6 100644 --- a/tests/servers/http/client.rs +++ b/tests/servers/http/client.rs @@ -9,7 +9,7 @@ use super::requests::scrape; /// HTTP Tracker Client pub struct Client { server_addr: std::net::SocketAddr, - reqwest_client: ReqwestClient, + reqwest: ReqwestClient, key: Option, } @@ -25,7 +25,7 @@ impl Client { pub fn new(server_addr: std::net::SocketAddr) -> Self { Self { server_addr, - reqwest_client: reqwest::Client::builder().build().unwrap(), + reqwest: reqwest::Client::builder().build().unwrap(), key: None, } } @@ -34,7 +34,7 @@ impl Client { pub fn bind(server_addr: std::net::SocketAddr, local_address: IpAddr) -> Self { Self { server_addr, - reqwest_client: reqwest::Client::builder().local_address(local_address).build().unwrap(), + reqwest: reqwest::Client::builder().local_address(local_address).build().unwrap(), key: None, } } @@ -42,7 +42,7 @@ impl Client { pub fn authenticated(server_addr: std::net::SocketAddr, key: Key) -> Self { Self { server_addr, - reqwest_client: reqwest::Client::builder().build().unwrap(), + reqwest: reqwest::Client::builder().build().unwrap(), key: Some(key), } } @@ -61,11 +61,11 @@ impl Client { } pub async fn get(&self, path: &str) -> Response { - self.reqwest_client.get(self.build_url(path)).send().await.unwrap() + self.reqwest.get(self.build_url(path)).send().await.unwrap() } pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Response { - self.reqwest_client + self.reqwest .get(self.build_url(path)) .header(key, value) .send() From b4329f9977fcf04e4ba0d4776fa5dc5626e9e040 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 25 Sep 2023 12:57:48 +0100 Subject: [PATCH 0131/1297] ci: workflow to show the tracker contract in markdown --- .github/workflows/contract.yaml | 58 +++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 .github/workflows/contract.yaml diff --git a/.github/workflows/contract.yaml b/.github/workflows/contract.yaml new file mode 100644 index 000000000..7c9fd47bd --- /dev/null +++ b/.github/workflows/contract.yaml @@ -0,0 +1,58 @@ +name: Contract + +on: + push: + pull_request: + +env: + CARGO_TERM_COLOR: always + +jobs: + contract: + name: Contract + runs-on: ubuntu-latest + + strategy: + matrix: + toolchain: [stable, nightly] + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v4 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + components: llvm-tools-preview + + - id: cache + name: Enable Job Cache + uses: Swatinem/rust-cache@v2 + + - id: tools + name: Install Tools + uses: taiki-e/install-action@v2 + with: + tool: cargo-llvm-cov, cargo-nextest + + - id: pretty-test + name: Install pretty-test + run: cargo install cargo-pretty-test + + - id: contract + name: Run contract + run: | + cargo test --lib --bins + cargo pretty-test --lib --bins + + - id: summary + name: Generate contract Summary + run: | + echo "### Tracker Living Contract! :rocket:" >> $GITHUB_STEP_SUMMARY + cargo pretty-test --lib --bins --color=never >> $GITHUB_STEP_SUMMARY + echo '```console' >> $GITHUB_STEP_SUMMARY + echo "$OUTPUT" >> $GITHUB_STEP_SUMMARY + echo '```' >> $GITHUB_STEP_SUMMARY From f8175b557fb24d6c12fb390d73597fc8e8cc97cd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 9 Nov 2023 19:57:29 +0000 Subject: [PATCH 0132/1297] chore(deps): bump tokio from 1.33.0 to 1.34.0 Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.33.0 to 1.34.0. - [Release notes](https://github.com/tokio-rs/tokio/releases) - [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.33.0...tokio-1.34.0) --- updated-dependencies: - dependency-name: tokio dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 749c0fa53..f63fa0f34 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3130,9 +3130,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.33.0" +version = "1.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f38200e3ef7995e5ef13baec2f432a6da0aa9ac495b2c0e8f3b7eec2c92d653" +checksum = "d0c014766411e834f7af5b8f4cf46257aab4036ca95e9d2c144a10f59ad6f5b9" dependencies = [ "backtrace", "bytes", @@ -3148,9 +3148,9 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" +checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", From f7c5ace1b05e0b9da628c6a04722cb1ea937c3ee Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 23 Nov 2023 16:50:18 +0000 Subject: [PATCH 0133/1297] chore: update dependencies - bump serde from 1.0.192 to 1.0.193 - bump uuid from 1.5.0 to 1.6.1 - bump r2d2_sqlite from 0.22.0 to 0.23.0 --- Cargo.lock | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f63fa0f34..ef28303e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -869,9 +869,9 @@ dependencies = [ [[package]] name = "fallible-iterator" -version = "0.2.0" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" [[package]] name = "fallible-streaming-iterator" @@ -1532,9 +1532,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.26.0" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afc22eff61b133b115c6e8c74e818c628d6d5e7a502afea6f64dee076dd94326" +checksum = "cf4e226dcd58b4be396f7bd3c20da8fdee2911400705297ba7d2d7cc2c30f716" dependencies = [ "cc", "pkg-config", @@ -2317,9 +2317,9 @@ dependencies = [ [[package]] name = "r2d2_sqlite" -version = "0.22.0" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99f31323d6161385f385046738df520e0e8694fa74852d35891fc0be08348ddc" +checksum = "4dc290b669d30e20751e813517bbe13662d020419c5c8818ff10b6e8bb7777f6" dependencies = [ "r2d2", "rusqlite", @@ -2522,9 +2522,9 @@ dependencies = [ [[package]] name = "rusqlite" -version = "0.29.0" +version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "549b9d036d571d42e6e85d1c1425e2ac83491075078ca9a15be021c56b1641f2" +checksum = "a78046161564f5e7cd9008aff3b2990b3850dc8e0349119b98e8f251e099f24d" dependencies = [ "bitflags 2.4.1", "fallible-iterator", @@ -2723,9 +2723,9 @@ checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" [[package]] name = "serde" -version = "1.0.192" +version = "1.0.193" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bca2a08484b285dcb282d0f67b26cadc0df8b19f8c12502c13d966bf9482f001" +checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89" dependencies = [ "serde_derive", ] @@ -2751,9 +2751,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.192" +version = "1.0.193" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6c7207fbec9faa48073f3e3074cbe553af6ea512d7c21ba46e434e70ea9fbc1" +checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" dependencies = [ "proc-macro2", "quote", @@ -3480,9 +3480,9 @@ dependencies = [ [[package]] name = "uuid" -version = "1.5.0" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88ad59a7560b41a70d191093a945f0b87bc1deeda46fb237479708a1d6b6cdfc" +checksum = "5e395fcf16a7a3d8127ec99782007af141946b4795001f876d54fb0d55978560" dependencies = [ "getrandom", "rand", From b609c832ab65304c7f6847eb0bf0ad13235d5bea Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 24 Nov 2023 07:20:20 +0000 Subject: [PATCH 0134/1297] chore: update dependencies - bump percent-encoding from 2.3.0 to 2.3.1 - bump config from 0.13.3 to 0.13.4 - bump openssl from 0.10.59 to 0.10.60 --- Cargo.lock | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ef28303e8..336adb8f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -559,9 +559,9 @@ dependencies = [ [[package]] name = "config" -version = "0.13.3" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d379af7f68bfc21714c6c7dea883544201741d2ce8274bb12fa54f89507f52a7" +checksum = "23738e11972c7643e4ec947840fc463b6a571afcd3e735bdfce7d03c7a784aca" dependencies = [ "async-trait", "json5", @@ -1909,9 +1909,9 @@ checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" [[package]] name = "openssl" -version = "0.10.59" +version = "0.10.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a257ad03cd8fb16ad4172fedf8094451e1af1c4b70097636ef2eac9a5f0cc33" +checksum = "79a4c6c3a2b158f7f8f2a2fc5a969fa3a068df6fc9dbb4a43845436e3af7c800" dependencies = [ "bitflags 2.4.1", "cfg-if", @@ -1950,9 +1950,9 @@ dependencies = [ [[package]] name = "openssl-sys" -version = "0.9.95" +version = "0.9.96" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40a4130519a360279579c2053038317e40eff64d13fd3f004f9e1b72b8a6aaf9" +checksum = "3812c071ba60da8b5677cc12bcb1d42989a65553772897a7e0355545a819838f" dependencies = [ "cc", "libc", @@ -2018,9 +2018,9 @@ dependencies = [ [[package]] name = "percent-encoding" -version = "2.3.0" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" From f1c7cccf4fc55aac84b5b735bde1ded8178b4d22 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Nov 2023 14:57:59 +0000 Subject: [PATCH 0135/1297] feat: add cargo dependency reqwest It'll be used by a litle script (health check) that needs to make HTTP request. --- Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.toml b/Cargo.toml index fd6230f80..51a1ac00f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,6 +50,7 @@ r2d2 = "0" r2d2_mysql = "24" r2d2_sqlite = { version = "0", features = ["bundled"] } rand = "0" +reqwest = "0" serde = { version = "1", features = ["derive"] } serde_bencode = "0" serde_json = "1" From 0ef4e34254ca175ba861d45f58c065a55bd554c3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Nov 2023 14:59:58 +0000 Subject: [PATCH 0136/1297] feat: [#508] add new binary HTTP health check It makes a request to an HTTP endpoint to check that the service is healthy. --- Cargo.toml | 1 + src/bin/http_health_check.rs | 37 ++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 src/bin/http_health_check.rs diff --git a/Cargo.toml b/Cargo.toml index 51a1ac00f..2316a1edf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,5 @@ [package] +default-run = "torrust-tracker" name = "torrust-tracker" readme = "README.md" diff --git a/src/bin/http_health_check.rs b/src/bin/http_health_check.rs new file mode 100644 index 000000000..2c39f2a79 --- /dev/null +++ b/src/bin/http_health_check.rs @@ -0,0 +1,37 @@ +//! Minimal `curl` or `wget` to be used for container health checks. +//! +//! It's convenient to avoid using third-party libraries because: +//! +//! - They are harder to maintain. +//! - They introduce new attack vectors. +use std::{env, process}; + +#[tokio::main] +async fn main() { + let args: Vec = env::args().collect(); + if args.len() != 2 { + eprintln!("Usage: cargo run --bin health_check "); + eprintln!("Example: cargo run --bin http_health_check http://localhost:1212/api/v1/stats?token=MyAccessToken"); + std::process::exit(1); + } + + println!("Health check ..."); + + let url = &args[1].clone(); + + match reqwest::get(url).await { + Ok(response) => { + if response.status().is_success() { + println!("STATUS: {}", response.status()); + process::exit(0); + } else { + println!("Non-success status received."); + process::exit(1); + } + } + Err(err) => { + println!("ERROR: {err}"); + process::exit(1); + } + } +} \ No newline at end of file From 48ac64fff9ccc1e258d4adf257dd5223fa050796 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Nov 2023 17:30:53 +0000 Subject: [PATCH 0137/1297] feat: [#508] add container healthcheck for API --- Containerfile | 6 ++-- src/bin/http_health_check.rs | 6 ++-- src/servers/apis/routes.rs | 7 ++-- .../apis/v1/context/health_check/handlers.rs | 11 ++++++ .../apis/v1/context/health_check/mod.rs | 34 +++++++++++++++++++ .../apis/v1/context/health_check/resources.rs | 14 ++++++++ src/servers/apis/v1/context/mod.rs | 1 + tests/servers/api/v1/client.rs | 2 +- .../api/v1/contract/context/health_check.rs | 20 +++++++++++ tests/servers/api/v1/contract/context/mod.rs | 1 + 10 files changed, 94 insertions(+), 8 deletions(-) create mode 100644 src/servers/apis/v1/context/health_check/handlers.rs create mode 100644 src/servers/apis/v1/context/health_check/mod.rs create mode 100644 src/servers/apis/v1/context/health_check/resources.rs create mode 100644 tests/servers/api/v1/contract/context/health_check.rs diff --git a/Containerfile b/Containerfile index be71017db..244f7bdfc 100644 --- a/Containerfile +++ b/Containerfile @@ -85,7 +85,7 @@ COPY --from=build \ RUN cargo nextest run --workspace-remap /test/src/ --extract-to /test/src/ --no-run --archive-file /test/torrust-tracker.tar.zst RUN cargo nextest run --workspace-remap /test/src/ --target-dir-remap /test/src/target/ --cargo-metadata /test/src/target/nextest/cargo-metadata.json --binaries-metadata /test/src/target/nextest/binaries-metadata.json -RUN mkdir -p /app/bin/; cp -l /test/src/target/release/torrust-tracker /app/bin/torrust-tracker +RUN mkdir -p /app/bin/; cp -l /test/src/target/release/torrust-tracker /app/bin/torrust-tracker; cp -l /test/src/target/release/http_health_check /app/bin/http_health_check RUN mkdir -p /app/lib/; cp -l $(realpath $(ldd /app/bin/torrust-tracker | grep "libz\.so\.1" | awk '{print $3}')) /app/lib/libz.so.1 RUN chown -R root:root /app; chmod -R u=rw,go=r,a+X /app; chmod -R a+x /app/bin @@ -136,5 +136,7 @@ CMD ["sh"] FROM runtime as release ENV RUNTIME="release" COPY --from=test /app/ /usr/ -# HEALTHCHECK CMD ["/usr/bin/wget", "--no-verbose", "--tries=1", "--spider", "localhost:${API_PORT}/version"] +HEALTHCHECK --interval=5s --timeout=5s --start-period=3s --retries=3 \ + CMD /usr/bin/http_health_check http://localhost:${API_PORT}/health_check \ + || exit 1 CMD ["/usr/bin/torrust-tracker"] diff --git a/src/bin/http_health_check.rs b/src/bin/http_health_check.rs index 2c39f2a79..313f44045 100644 --- a/src/bin/http_health_check.rs +++ b/src/bin/http_health_check.rs @@ -10,8 +10,8 @@ use std::{env, process}; async fn main() { let args: Vec = env::args().collect(); if args.len() != 2 { - eprintln!("Usage: cargo run --bin health_check "); - eprintln!("Example: cargo run --bin http_health_check http://localhost:1212/api/v1/stats?token=MyAccessToken"); + eprintln!("Usage: cargo run --bin http_health_check "); + eprintln!("Example: cargo run --bin http_health_check http://127.0.0.1:1212/health_check"); std::process::exit(1); } @@ -34,4 +34,4 @@ async fn main() { process::exit(1); } } -} \ No newline at end of file +} diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 7801389f3..0740e1f6a 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -7,10 +7,12 @@ //! first path segment. For example: `/api/v1/torrents`. use std::sync::Arc; +use axum::routing::get; use axum::{middleware, Router}; use tower_http::compression::CompressionLayer; use super::v1; +use super::v1::context::health_check::handlers::health_check_handler; use crate::tracker::Tracker; /// Add all API routes to the router. @@ -18,14 +20,15 @@ use crate::tracker::Tracker; pub fn router(tracker: Arc) -> Router { let router = Router::new(); - let prefix = "/api"; + let api_url_prefix = "/api"; - let router = v1::routes::add(prefix, router, tracker.clone()); + let router = v1::routes::add(api_url_prefix, router, tracker.clone()); router .layer(middleware::from_fn_with_state( tracker.config.clone(), v1::middlewares::auth::auth, )) + .route("/health_check", get(health_check_handler)) .layer(CompressionLayer::new()) } diff --git a/src/servers/apis/v1/context/health_check/handlers.rs b/src/servers/apis/v1/context/health_check/handlers.rs new file mode 100644 index 000000000..bfbeab549 --- /dev/null +++ b/src/servers/apis/v1/context/health_check/handlers.rs @@ -0,0 +1,11 @@ +//! API handlers for the [`stats`](crate::servers::apis::v1::context::health_check) +//! API context. + +use axum::Json; + +use super::resources::{Report, Status}; + +/// Endpoint for container health check. +pub async fn health_check_handler() -> Json { + Json(Report { status: Status::Ok }) +} diff --git a/src/servers/apis/v1/context/health_check/mod.rs b/src/servers/apis/v1/context/health_check/mod.rs new file mode 100644 index 000000000..c62c5e97b --- /dev/null +++ b/src/servers/apis/v1/context/health_check/mod.rs @@ -0,0 +1,34 @@ +//! API health check endpoint. +//! +//! It is used to check is the service is running. Especially for containers. +//! +//! # Endpoints +//! +//! - [Health Check](#health-check) +//! +//! # Health Check +//! +//! `GET /health_check` +//! +//! Returns the API status. +//! +//! **Example request** +//! +//! ```bash +//! curl "http://127.0.0.1:1212/health_check" +//! ``` +//! +//! **Example response** `200` +//! +//! ```json +//! { +//! "status": "Ok", +//! } +//! ``` +//! +//! **Resource** +//! +//! Refer to the API [`Stats`](crate::servers::apis::v1::context::health_check::resources::Report) +//! resource for more information about the response attributes. +pub mod handlers; +pub mod resources; diff --git a/src/servers/apis/v1/context/health_check/resources.rs b/src/servers/apis/v1/context/health_check/resources.rs new file mode 100644 index 000000000..9830e643c --- /dev/null +++ b/src/servers/apis/v1/context/health_check/resources.rs @@ -0,0 +1,14 @@ +//! API resources for the [`stats`](crate::servers::apis::v1::context::health_check) +//! API context. +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +pub enum Status { + Ok, + Error, +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +pub struct Report { + pub status: Status, +} diff --git a/src/servers/apis/v1/context/mod.rs b/src/servers/apis/v1/context/mod.rs index 5e268a429..be67cd96a 100644 --- a/src/servers/apis/v1/context/mod.rs +++ b/src/servers/apis/v1/context/mod.rs @@ -3,6 +3,7 @@ //! Each context is a module that contains the API endpoints related to a //! specific resource group. pub mod auth_key; +pub mod health_check; pub mod stats; pub mod torrent; pub mod whitelist; diff --git a/tests/servers/api/v1/client.rs b/tests/servers/api/v1/client.rs index 2b6db2e77..61e98e742 100644 --- a/tests/servers/api/v1/client.rs +++ b/tests/servers/api/v1/client.rs @@ -101,7 +101,7 @@ impl Client { } } -async fn get(path: &str, query: Option) -> Response { +pub async fn get(path: &str, query: Option) -> Response { match query { Some(params) => reqwest::Client::builder() .build() diff --git a/tests/servers/api/v1/contract/context/health_check.rs b/tests/servers/api/v1/contract/context/health_check.rs new file mode 100644 index 000000000..3b6c98374 --- /dev/null +++ b/tests/servers/api/v1/contract/context/health_check.rs @@ -0,0 +1,20 @@ +use torrust_tracker::servers::apis::v1::context::health_check::resources::{Report, Status}; +use torrust_tracker_test_helpers::configuration; + +use crate::servers::api::test_environment::running_test_environment; +use crate::servers::api::v1::client::get; + +#[tokio::test] +async fn health_check_endpoint_should_return_status_ok_if_api_is_running() { + let test_env = running_test_environment(configuration::ephemeral()).await; + + let url = format!("http://{}/health_check", test_env.get_connection_info().bind_address); + + let response = get(&url, None).await; + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + assert_eq!(response.json::().await.unwrap(), Report { status: Status::Ok }); + + test_env.stop().await; +} diff --git a/tests/servers/api/v1/contract/context/mod.rs b/tests/servers/api/v1/contract/context/mod.rs index 6d3fb7566..032e13b0b 100644 --- a/tests/servers/api/v1/contract/context/mod.rs +++ b/tests/servers/api/v1/contract/context/mod.rs @@ -1,4 +1,5 @@ pub mod auth_key; +pub mod health_check; pub mod stats; pub mod torrent; pub mod whitelist; From e1a45a2561a78c83fc3c6b44063a0aae073ac227 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 24 Nov 2023 10:30:45 +0000 Subject: [PATCH 0138/1297] feat: [#508] Health Check API but no checks yet New Health CHeck API, but it is not checking anything yet. You can call it at: http://localhost:1313/health_check --- Containerfile | 5 +- docs/containers.md | 1 + packages/configuration/src/lib.rs | 50 +++++++++---- packages/test-helpers/src/configuration.rs | 4 + .../config/tracker.container.mysql.toml | 3 + .../config/tracker.container.sqlite3.toml | 3 + .../config/tracker.development.sqlite3.toml | 3 + src/app.rs | 18 ++++- src/bootstrap/jobs/health_check_api.rs | 74 +++++++++++++++++++ src/bootstrap/jobs/mod.rs | 1 + src/lib.rs | 29 ++++---- src/servers/health_check_api/mod.rs | 1 + src/servers/health_check_api/server.rs | 52 +++++++++++++ src/servers/mod.rs | 1 + tests/servers/health_check_api/client.rs | 5 ++ tests/servers/health_check_api/contract.rs | 22 ++++++ tests/servers/health_check_api/mod.rs | 3 + .../health_check_api/test_environment.rs | 32 ++++++++ tests/servers/mod.rs | 1 + 19 files changed, 275 insertions(+), 33 deletions(-) create mode 100644 src/bootstrap/jobs/health_check_api.rs create mode 100644 src/servers/health_check_api/mod.rs create mode 100644 src/servers/health_check_api/server.rs create mode 100644 tests/servers/health_check_api/client.rs create mode 100644 tests/servers/health_check_api/contract.rs create mode 100644 tests/servers/health_check_api/mod.rs create mode 100644 tests/servers/health_check_api/test_environment.rs diff --git a/Containerfile b/Containerfile index 244f7bdfc..8ea555c2d 100644 --- a/Containerfile +++ b/Containerfile @@ -101,6 +101,7 @@ ARG USER_ID=1000 ARG UDP_PORT=6969 ARG HTTP_PORT=7070 ARG API_PORT=1212 +ARG HEALTH_CHECK_API_PORT=1313 ENV TORRUST_TRACKER_PATH_CONFIG=${TORRUST_TRACKER_PATH_CONFIG} ENV TORRUST_TRACKER_DATABASE_DRIVER=${TORRUST_TRACKER_DATABASE_DRIVER} @@ -108,11 +109,13 @@ ENV USER_ID=${USER_ID} ENV UDP_PORT=${UDP_PORT} ENV HTTP_PORT=${HTTP_PORT} ENV API_PORT=${API_PORT} +ENV HEALTH_CHECK_API_PORT=${HEALTH_CHECK_API_PORT} ENV TZ=Etc/UTC EXPOSE ${UDP_PORT}/udp EXPOSE ${HTTP_PORT}/tcp EXPOSE ${API_PORT}/tcp +EXPOSE ${HEALTH_CHECK_API_PORT}/tcp RUN mkdir -p /var/lib/torrust/tracker /var/log/torrust/tracker /etc/torrust/tracker @@ -137,6 +140,6 @@ FROM runtime as release ENV RUNTIME="release" COPY --from=test /app/ /usr/ HEALTHCHECK --interval=5s --timeout=5s --start-period=3s --retries=3 \ - CMD /usr/bin/http_health_check http://localhost:${API_PORT}/health_check \ + CMD /usr/bin/http_health_check http://localhost:${HEALTH_CHECK_API_PORT}/health_check \ || exit 1 CMD ["/usr/bin/torrust-tracker"] diff --git a/docs/containers.md b/docs/containers.md index 737ce40a0..2b06c0f76 100644 --- a/docs/containers.md +++ b/docs/containers.md @@ -146,6 +146,7 @@ The following environmental variables can be set: - `UDP_PORT` - The port for the UDP tracker. This should match the port used in the configuration, (default `6969`). - `HTTP_PORT` - The port for the HTTP tracker. This should match the port used in the configuration, (default `7070`). - `API_PORT` - The port for the tracker API. This should match the port used in the configuration, (default `1212`). +- `HEALTH_CHECK_API_PORT` - The port for the Health Check API. This should match the port used in the configuration, (default `1313`). ### Sockets diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 059316a26..217f8a8be 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -191,40 +191,43 @@ //! The default configuration is: //! //! ```toml -//! log_level = "info" -//! mode = "public" +//! announce_interval = 120 //! db_driver = "Sqlite3" //! db_path = "./storage/tracker/lib/database/sqlite3.db" -//! announce_interval = 120 -//! min_announce_interval = 120 +//! external_ip = "0.0.0.0" +//! inactive_peer_cleanup_interval = 600 +//! log_level = "info" //! max_peer_timeout = 900 +//! min_announce_interval = 120 +//! mode = "public" //! on_reverse_proxy = false -//! external_ip = "0.0.0.0" -//! tracker_usage_statistics = true //! persistent_torrent_completed_stat = false -//! inactive_peer_cleanup_interval = 600 //! remove_peerless_torrents = true +//! tracker_usage_statistics = true //! //! [[udp_trackers]] -//! enabled = false //! bind_address = "0.0.0.0:6969" +//! enabled = false //! //! [[http_trackers]] -//! enabled = false //! bind_address = "0.0.0.0:7070" -//! ssl_enabled = false +//! enabled = false //! ssl_cert_path = "" +//! ssl_enabled = false //! ssl_key_path = "" //! //! [http_api] -//! enabled = true //! bind_address = "127.0.0.1:1212" -//! ssl_enabled = false +//! enabled = true //! ssl_cert_path = "" +//! ssl_enabled = false //! ssl_key_path = "" //! //! [http_api.access_tokens] //! admin = "MyAccessToken" +//! +//! [health_check_api] +//! bind_address = "127.0.0.1:1313" //!``` use std::collections::{HashMap, HashSet}; use std::net::IpAddr; @@ -342,7 +345,7 @@ pub struct HttpApi { /// The address the tracker will bind to. /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating - /// system to choose a random port, use port `0`. + /// system to choose a random port, use port `0`. pub bind_address: String, /// Weather the HTTP API will use SSL or not. pub ssl_enabled: bool, @@ -363,9 +366,7 @@ impl HttpApi { fn override_admin_token(&mut self, api_admin_token: &str) { self.access_tokens.insert("admin".to_string(), api_admin_token.to_string()); } -} -impl HttpApi { /// Checks if the given token is one of the token in the configuration. #[must_use] pub fn contains_token(&self, token: &str) -> bool { @@ -375,6 +376,17 @@ impl HttpApi { } } +/// Configuration for the Health Check API. +#[serde_as] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct HealthCheckApi { + /// The address the API will bind to. + /// The format is `ip:port`, for example `127.0.0.1:1313`. If you want to + /// listen to all interfaces, use `0.0.0.0`. If you want the operating + /// system to choose a random port, use port `0`. + pub bind_address: String, +} + /// Core configuration for the tracker. #[allow(clippy::struct_excessive_bools)] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)] @@ -465,6 +477,8 @@ pub struct Configuration { pub http_trackers: Vec, /// The HTTP API configuration. pub http_api: HttpApi, + /// The Health Check API configuration. + pub health_check_api: HealthCheckApi, } /// Errors that can occur when loading the configuration. @@ -529,6 +543,9 @@ impl Default for Configuration { .cloned() .collect(), }, + health_check_api: HealthCheckApi { + bind_address: String::from("127.0.0.1:1313"), + }, }; configuration.udp_trackers.push(UdpTracker { enabled: false, @@ -676,6 +693,9 @@ mod tests { [http_api.access_tokens] admin = "MyAccessToken" + + [health_check_api] + bind_address = "127.0.0.1:1313" "# .lines() .map(str::trim_start) diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 437475ee2..b41f435ec 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -37,6 +37,10 @@ pub fn ephemeral() -> Configuration { config.http_api.enabled = true; config.http_api.bind_address = format!("127.0.0.1:{}", &api_port); + // Ephemeral socket address for Health Check API + let health_check_api_port = 0u16; + config.health_check_api.bind_address = format!("127.0.0.1:{}", &health_check_api_port); + // Ephemeral socket address for UDP tracker let udp_port = 0u16; config.udp_trackers[0].enabled = true; diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml index fb9cbf789..e7714c229 100644 --- a/share/default/config/tracker.container.mysql.toml +++ b/share/default/config/tracker.container.mysql.toml @@ -36,3 +36,6 @@ ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" [http_api.access_tokens] admin = "MyAccessToken" + +[health_check_api] +bind_address = "127.0.0.1:1313" diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml index 54cfd4023..4ec055c56 100644 --- a/share/default/config/tracker.container.sqlite3.toml +++ b/share/default/config/tracker.container.sqlite3.toml @@ -36,3 +36,6 @@ ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" [http_api.access_tokens] admin = "MyAccessToken" + +[health_check_api] +bind_address = "127.0.0.1:1313" diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index 20f95ac5d..04934dd8a 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -32,3 +32,6 @@ ssl_key_path = "" [http_api.access_tokens] admin = "MyAccessToken" + +[health_check_api] +bind_address = "127.0.0.1:1313" diff --git a/src/app.rs b/src/app.rs index 3fc790a23..6478cffb8 100644 --- a/src/app.rs +++ b/src/app.rs @@ -11,7 +11,11 @@ //! - Loading data from the database when it's needed. //! - Starting some jobs depending on the configuration. //! -//! The started jobs may be: +//! Jobs executed always: +//! +//! - Health Check API +//! +//! Optional jobs: //! //! - Torrent cleaner: it removes inactive peers and (optionally) peerless torrents. //! - UDP trackers: the user can enable multiple UDP tracker on several ports. @@ -23,13 +27,16 @@ use log::warn; use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; -use crate::bootstrap::jobs::{http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; +use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; use crate::servers::http::Version; use crate::tracker; /// # Panics /// -/// Will panic if the socket address for API can't be parsed. +/// Will panic if: +/// +/// - Can't retrieve tracker keys from database. +/// - Can't load whitelist from database. pub async fn start(config: Arc, tracker: Arc) -> Vec> { let mut jobs: Vec> = Vec::new(); @@ -78,10 +85,13 @@ pub async fn start(config: Arc, tracker: Arc) - jobs.push(tracker_apis::start_job(&config.http_api, tracker.clone()).await); } - // Remove torrents without peers, every interval + // Start runners to remove torrents without peers, every interval if config.inactive_peer_cleanup_interval > 0 { jobs.push(torrent_cleanup::start_job(&config, &tracker)); } + // Start Health Check API + jobs.push(health_check_api::start_job(&config.health_check_api).await); + jobs } diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs new file mode 100644 index 000000000..29c4ce144 --- /dev/null +++ b/src/bootstrap/jobs/health_check_api.rs @@ -0,0 +1,74 @@ +//! Health Check API job starter. +//! +//! The [`health_check_api::start_job`](crate::bootstrap::jobs::health_check_api::start_job) +//! function starts the Health Check REST API. +//! +//! The [`health_check_api::start_job`](crate::bootstrap::jobs::health_check_api::start_job) +//! function spawns a new asynchronous task, that tasks is the "**launcher**". +//! The "**launcher**" starts the actual server and sends a message back +//! to the main application. The main application waits until receives +//! the message [`ApiServerJobStarted`] +//! from the "**launcher**". +//! +//! The "**launcher**" is an intermediary thread that decouples the Health Check +//! API server from the process that handles it. +//! +//! Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) +//! for the API configuration options. +use std::net::SocketAddr; + +use log::info; +use tokio::sync::oneshot; +use tokio::task::JoinHandle; +use torrust_tracker_configuration::HealthCheckApi; + +use crate::servers::health_check_api::server; + +/// This is the message that the "launcher" spawned task sends to the main +/// application process to notify the API server was successfully started. +/// +/// > **NOTICE**: it does not mean the API server is ready to receive requests. +/// It only means the new server started. It might take some time to the server +/// to be ready to accept request. +#[derive(Debug)] +pub struct ApiServerJobStarted { + pub bound_addr: SocketAddr, +} + +/// This function starts a new Health Check API server with the provided +/// configuration. +/// +/// The functions starts a new concurrent task that will run the API server. +/// This task will send a message to the main application process to notify +/// that the API server was successfully started. +/// +/// # Panics +/// +/// It would panic if unable to send the `ApiServerJobStarted` notice. +pub async fn start_job(config: &HealthCheckApi) -> JoinHandle<()> { + let bind_addr = config + .bind_address + .parse::() + .expect("Health Check API bind_address invalid."); + + let (tx, rx) = oneshot::channel::(); + + // Run the API server + let join_handle = tokio::spawn(async move { + info!("Starting Health Check API server: http://{}", bind_addr); + + let handle = server::start(bind_addr, tx); + + if let Ok(()) = handle.await { + info!("Health Check API server on http://{} stopped", bind_addr); + } + }); + + // Wait until the API server job is running + match rx.await { + Ok(_msg) => info!("Torrust Health Check API server started"), + Err(e) => panic!("the Health Check API server was dropped: {e}"), + } + + join_handle +} diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index c519a9f4b..8c85ba45b 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -6,6 +6,7 @@ //! 2. Launch all the application services as concurrent jobs. //! //! This modules contains all the functions needed to start those jobs. +pub mod health_check_api; pub mod http_tracker; pub mod torrent_cleanup; pub mod tracker_apis; diff --git a/src/lib.rs b/src/lib.rs index c2e70a8b1..8d453f177 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -148,41 +148,44 @@ //! The default configuration is: //! //! ```toml -//! log_level = "info" -//! mode = "public" +//! announce_interval = 120 //! db_driver = "Sqlite3" //! db_path = "./storage/tracker/lib/database/sqlite3.db" -//! announce_interval = 120 -//! min_announce_interval = 120 +//! external_ip = "0.0.0.0" +//! inactive_peer_cleanup_interval = 600 +//! log_level = "info" //! max_peer_timeout = 900 +//! min_announce_interval = 120 +//! mode = "public" //! on_reverse_proxy = false -//! external_ip = "0.0.0.0" -//! tracker_usage_statistics = true //! persistent_torrent_completed_stat = false -//! inactive_peer_cleanup_interval = 600 //! remove_peerless_torrents = true +//! tracker_usage_statistics = true //! //! [[udp_trackers]] -//! enabled = false //! bind_address = "0.0.0.0:6969" +//! enabled = false //! //! [[http_trackers]] -//! enabled = false //! bind_address = "0.0.0.0:7070" -//! ssl_enabled = false +//! enabled = false //! ssl_cert_path = "" +//! ssl_enabled = false //! ssl_key_path = "" //! //! [http_api] -//! enabled = true //! bind_address = "127.0.0.1:1212" -//! ssl_enabled = false +//! enabled = true //! ssl_cert_path = "" +//! ssl_enabled = false //! ssl_key_path = "" //! //! [http_api.access_tokens] //! admin = "MyAccessToken" -//! ``` +//! +//! [health_check_api] +//! bind_address = "127.0.0.1:1313" +//!``` //! //! The default configuration includes one disabled UDP server, one disabled HTTP server and the enabled API. //! diff --git a/src/servers/health_check_api/mod.rs b/src/servers/health_check_api/mod.rs new file mode 100644 index 000000000..74f47ad34 --- /dev/null +++ b/src/servers/health_check_api/mod.rs @@ -0,0 +1 @@ +pub mod server; diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs new file mode 100644 index 000000000..cbd1b8703 --- /dev/null +++ b/src/servers/health_check_api/server.rs @@ -0,0 +1,52 @@ +//! Logic to run the Health Check HTTP API server. +//! +//! This API is intended to be used by the container infrastructure to check if +//! the whole application is healthy. +use std::net::SocketAddr; + +use axum::routing::get; +use axum::{Json, Router}; +use futures::Future; +use log::info; +use serde_json::{json, Value}; +use tokio::sync::oneshot::Sender; + +use crate::bootstrap::jobs::health_check_api::ApiServerJobStarted; + +/// Starts Health Check API server. +/// +/// # Panics +/// +/// Will panic if binding to the socket address fails. +pub fn start(socket_addr: SocketAddr, tx: Sender) -> impl Future> { + let app = Router::new() + .route("/", get(|| async { Json(json!({})) })) + .route("/health_check", get(health_check_handler)); + + let server = axum::Server::bind(&socket_addr).serve(app.into_make_service()); + + let bound_addr = server.local_addr(); + + info!("Health Check API server listening on http://{}", bound_addr); + + let running = server.with_graceful_shutdown(async move { + tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); + info!("Stopping Torrust Health Check API server o http://{} ...", socket_addr); + }); + + tx.send(ApiServerJobStarted { bound_addr }) + .expect("the Health Check API server should not be dropped"); + + running +} + +/// Endpoint for container health check. +async fn health_check_handler() -> Json { + // todo: if enabled, check if the Tracker API is healthy + + // todo: if enabled, check if the HTTP Tracker is healthy + + // todo: if enabled, check if the UDP Tracker is healthy + + Json(json!({ "status": "Ok" })) +} diff --git a/src/servers/mod.rs b/src/servers/mod.rs index 38b4b70cd..077109f35 100644 --- a/src/servers/mod.rs +++ b/src/servers/mod.rs @@ -1,5 +1,6 @@ //! Servers. Services that can be started and stopped. pub mod apis; +pub mod health_check_api; pub mod http; pub mod signals; pub mod udp; diff --git a/tests/servers/health_check_api/client.rs b/tests/servers/health_check_api/client.rs new file mode 100644 index 000000000..3d8bdc7d6 --- /dev/null +++ b/tests/servers/health_check_api/client.rs @@ -0,0 +1,5 @@ +use reqwest::Response; + +pub async fn get(path: &str) -> Response { + reqwest::Client::builder().build().unwrap().get(path).send().await.unwrap() +} diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs new file mode 100644 index 000000000..575e10665 --- /dev/null +++ b/tests/servers/health_check_api/contract.rs @@ -0,0 +1,22 @@ +use torrust_tracker::servers::apis::v1::context::health_check::resources::{Report, Status}; +use torrust_tracker_test_helpers::configuration; + +use crate::servers::health_check_api::client::get; +use crate::servers::health_check_api::test_environment; + +#[tokio::test] +async fn health_check_endpoint_should_return_status_ok() { + let configuration = configuration::ephemeral(); + + let (bound_addr, test_env) = test_environment::start(&configuration.health_check_api).await; + + let url = format!("http://{bound_addr}/health_check"); + + let response = get(&url).await; + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + assert_eq!(response.json::().await.unwrap(), Report { status: Status::Ok }); + + test_env.abort(); +} diff --git a/tests/servers/health_check_api/mod.rs b/tests/servers/health_check_api/mod.rs new file mode 100644 index 000000000..89f19a334 --- /dev/null +++ b/tests/servers/health_check_api/mod.rs @@ -0,0 +1,3 @@ +pub mod client; +pub mod contract; +pub mod test_environment; diff --git a/tests/servers/health_check_api/test_environment.rs b/tests/servers/health_check_api/test_environment.rs new file mode 100644 index 000000000..6ad90eac7 --- /dev/null +++ b/tests/servers/health_check_api/test_environment.rs @@ -0,0 +1,32 @@ +use std::net::SocketAddr; + +use tokio::sync::oneshot; +use tokio::task::JoinHandle; +use torrust_tracker::bootstrap::jobs::health_check_api::ApiServerJobStarted; +use torrust_tracker::servers::health_check_api::server; +use torrust_tracker_configuration::HealthCheckApi; + +/// Start the test environment for the Health Check API. +/// It runs the API server. +pub async fn start(config: &HealthCheckApi) -> (SocketAddr, JoinHandle<()>) { + let bind_addr = config + .bind_address + .parse::() + .expect("Health Check API bind_address invalid."); + + let (tx, rx) = oneshot::channel::(); + + let join_handle = tokio::spawn(async move { + let handle = server::start(bind_addr, tx); + if let Ok(()) = handle.await { + panic!("Health Check API server on http://{bind_addr} stopped"); + } + }); + + let bound_addr = match rx.await { + Ok(msg) => msg.bound_addr, + Err(e) => panic!("the Health Check API server was dropped: {e}"), + }; + + (bound_addr, join_handle) +} diff --git a/tests/servers/mod.rs b/tests/servers/mod.rs index 7c30b6f40..65e9a665b 100644 --- a/tests/servers/mod.rs +++ b/tests/servers/mod.rs @@ -1,3 +1,4 @@ mod api; +pub mod health_check_api; mod http; mod udp; From ef296f76bf3160e219f4b842fe1d055d4c9dc308 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 24 Nov 2023 16:13:04 +0000 Subject: [PATCH 0139/1297] feat: [#508] app health check endpoint checks API The app health check endpoint checks is the API is running healthy when is enabled. --- packages/test-helpers/src/configuration.rs | 12 +++++++ src/app.rs | 2 +- src/bootstrap/jobs/health_check_api.rs | 8 +++-- src/servers/health_check_api/handlers.rs | 31 +++++++++++++++++++ src/servers/health_check_api/mod.rs | 3 ++ src/servers/health_check_api/resources.rs | 31 +++++++++++++++++++ src/servers/health_check_api/responses.rs | 11 +++++++ src/servers/health_check_api/server.rs | 25 +++++++-------- tests/servers/health_check_api/contract.rs | 10 +++--- .../health_check_api/test_environment.rs | 8 +++-- 10 files changed, 115 insertions(+), 26 deletions(-) create mode 100644 src/servers/health_check_api/handlers.rs create mode 100644 src/servers/health_check_api/resources.rs create mode 100644 src/servers/health_check_api/responses.rs diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index b41f435ec..388d0151f 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -144,3 +144,15 @@ pub fn ephemeral_ipv6() -> Configuration { cfg } + +/// Ephemeral without running any services. +#[must_use] +pub fn ephemeral_with_no_services() -> Configuration { + let mut cfg = ephemeral(); + + cfg.http_api.enabled = false; + cfg.http_trackers[0].enabled = false; + cfg.udp_trackers[0].enabled = false; + + cfg +} diff --git a/src/app.rs b/src/app.rs index 6478cffb8..e749f9c64 100644 --- a/src/app.rs +++ b/src/app.rs @@ -91,7 +91,7 @@ pub async fn start(config: Arc, tracker: Arc) - } // Start Health Check API - jobs.push(health_check_api::start_job(&config.health_check_api).await); + jobs.push(health_check_api::start_job(config).await); jobs } diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index 29c4ce144..96a703afc 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -16,11 +16,12 @@ //! Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) //! for the API configuration options. use std::net::SocketAddr; +use std::sync::Arc; use log::info; use tokio::sync::oneshot; use tokio::task::JoinHandle; -use torrust_tracker_configuration::HealthCheckApi; +use torrust_tracker_configuration::Configuration; use crate::servers::health_check_api::server; @@ -45,8 +46,9 @@ pub struct ApiServerJobStarted { /// # Panics /// /// It would panic if unable to send the `ApiServerJobStarted` notice. -pub async fn start_job(config: &HealthCheckApi) -> JoinHandle<()> { +pub async fn start_job(config: Arc) -> JoinHandle<()> { let bind_addr = config + .health_check_api .bind_address .parse::() .expect("Health Check API bind_address invalid."); @@ -57,7 +59,7 @@ pub async fn start_job(config: &HealthCheckApi) -> JoinHandle<()> { let join_handle = tokio::spawn(async move { info!("Starting Health Check API server: http://{}", bind_addr); - let handle = server::start(bind_addr, tx); + let handle = server::start(bind_addr, tx, config.clone()); if let Ok(()) = handle.await { info!("Health Check API server on http://{} stopped", bind_addr); diff --git a/src/servers/health_check_api/handlers.rs b/src/servers/health_check_api/handlers.rs new file mode 100644 index 000000000..347106d6e --- /dev/null +++ b/src/servers/health_check_api/handlers.rs @@ -0,0 +1,31 @@ +use std::sync::Arc; + +use axum::extract::State; +use axum::Json; +use torrust_tracker_configuration::Configuration; + +use super::resources::Report; +use super::responses; + +/// Endpoint for container health check. +pub(crate) async fn health_check_handler(State(config): State>) -> Json { + if config.http_api.enabled { + let health_check_url = format!("http://{}/health_check", config.http_api.bind_address); + if !get_req_is_ok(&health_check_url).await { + return responses::error(format!("API is not healthy. Health check endpoint: {health_check_url}")); + } + } + + // todo: for all HTTP Trackers, if enabled, check if is healthy + + // todo: for all UDP Trackers, if enabled, check if is healthy + + responses::ok() +} + +async fn get_req_is_ok(url: &str) -> bool { + match reqwest::get(url).await { + Ok(response) => response.status().is_success(), + Err(_err) => false, + } +} diff --git a/src/servers/health_check_api/mod.rs b/src/servers/health_check_api/mod.rs index 74f47ad34..ec608387d 100644 --- a/src/servers/health_check_api/mod.rs +++ b/src/servers/health_check_api/mod.rs @@ -1 +1,4 @@ +pub mod handlers; +pub mod resources; +pub mod responses; pub mod server; diff --git a/src/servers/health_check_api/resources.rs b/src/servers/health_check_api/resources.rs new file mode 100644 index 000000000..3fadcf456 --- /dev/null +++ b/src/servers/health_check_api/resources.rs @@ -0,0 +1,31 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +pub enum Status { + Ok, + Error, +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +pub struct Report { + pub status: Status, + pub message: String, +} + +impl Report { + #[must_use] + pub fn ok() -> Report { + Self { + status: Status::Ok, + message: String::new(), + } + } + + #[must_use] + pub fn error(message: String) -> Report { + Self { + status: Status::Error, + message, + } + } +} diff --git a/src/servers/health_check_api/responses.rs b/src/servers/health_check_api/responses.rs new file mode 100644 index 000000000..043e271db --- /dev/null +++ b/src/servers/health_check_api/responses.rs @@ -0,0 +1,11 @@ +use axum::Json; + +use super::resources::Report; + +pub fn ok() -> Json { + Json(Report::ok()) +} + +pub fn error(message: String) -> Json { + Json(Report::error(message)) +} diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index cbd1b8703..562772a87 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -3,25 +3,33 @@ //! This API is intended to be used by the container infrastructure to check if //! the whole application is healthy. use std::net::SocketAddr; +use std::sync::Arc; use axum::routing::get; use axum::{Json, Router}; use futures::Future; use log::info; -use serde_json::{json, Value}; +use serde_json::json; use tokio::sync::oneshot::Sender; +use torrust_tracker_configuration::Configuration; use crate::bootstrap::jobs::health_check_api::ApiServerJobStarted; +use crate::servers::health_check_api::handlers::health_check_handler; /// Starts Health Check API server. /// /// # Panics /// /// Will panic if binding to the socket address fails. -pub fn start(socket_addr: SocketAddr, tx: Sender) -> impl Future> { +pub fn start( + socket_addr: SocketAddr, + tx: Sender, + config: Arc, +) -> impl Future> { let app = Router::new() .route("/", get(|| async { Json(json!({})) })) - .route("/health_check", get(health_check_handler)); + .route("/health_check", get(health_check_handler)) + .with_state(config); let server = axum::Server::bind(&socket_addr).serve(app.into_make_service()); @@ -39,14 +47,3 @@ pub fn start(socket_addr: SocketAddr, tx: Sender) -> impl F running } - -/// Endpoint for container health check. -async fn health_check_handler() -> Json { - // todo: if enabled, check if the Tracker API is healthy - - // todo: if enabled, check if the HTTP Tracker is healthy - - // todo: if enabled, check if the UDP Tracker is healthy - - Json(json!({ "status": "Ok" })) -} diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index 575e10665..6b816b85f 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -1,14 +1,14 @@ -use torrust_tracker::servers::apis::v1::context::health_check::resources::{Report, Status}; +use torrust_tracker::servers::health_check_api::resources::Report; use torrust_tracker_test_helpers::configuration; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::test_environment; #[tokio::test] -async fn health_check_endpoint_should_return_status_ok() { - let configuration = configuration::ephemeral(); +async fn health_check_endpoint_should_return_status_ok_when_no_service_is_running() { + let configuration = configuration::ephemeral_with_no_services(); - let (bound_addr, test_env) = test_environment::start(&configuration.health_check_api).await; + let (bound_addr, test_env) = test_environment::start(configuration.into()).await; let url = format!("http://{bound_addr}/health_check"); @@ -16,7 +16,7 @@ async fn health_check_endpoint_should_return_status_ok() { assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); - assert_eq!(response.json::().await.unwrap(), Report { status: Status::Ok }); + assert_eq!(response.json::().await.unwrap(), Report::ok()); test_env.abort(); } diff --git a/tests/servers/health_check_api/test_environment.rs b/tests/servers/health_check_api/test_environment.rs index 6ad90eac7..46e54dc47 100644 --- a/tests/servers/health_check_api/test_environment.rs +++ b/tests/servers/health_check_api/test_environment.rs @@ -1,15 +1,17 @@ use std::net::SocketAddr; +use std::sync::Arc; use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_tracker::bootstrap::jobs::health_check_api::ApiServerJobStarted; use torrust_tracker::servers::health_check_api::server; -use torrust_tracker_configuration::HealthCheckApi; +use torrust_tracker_configuration::Configuration; /// Start the test environment for the Health Check API. /// It runs the API server. -pub async fn start(config: &HealthCheckApi) -> (SocketAddr, JoinHandle<()>) { +pub async fn start(config: Arc) -> (SocketAddr, JoinHandle<()>) { let bind_addr = config + .health_check_api .bind_address .parse::() .expect("Health Check API bind_address invalid."); @@ -17,7 +19,7 @@ pub async fn start(config: &HealthCheckApi) -> (SocketAddr, JoinHandle<()>) { let (tx, rx) = oneshot::channel::(); let join_handle = tokio::spawn(async move { - let handle = server::start(bind_addr, tx); + let handle = server::start(bind_addr, tx, config.clone()); if let Ok(()) = handle.await { panic!("Health Check API server on http://{bind_addr} stopped"); } From 742130657bc3c04b3497400207e16250433de966 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 24 Nov 2023 17:01:05 +0000 Subject: [PATCH 0140/1297] feat: [#508] add health check enpoint to HTTP tracker http://localhost:7070/health_check And call the endpoint from the general application health check endpoint: http://localhost:1313/health_check Do not call the endpoint if: - The tracker is disabled. - The tracker configuration uses port 0 only knwon after starting the socket. todo: call the enpoint also when the port is 0 in the configuration. THe service can return back to the main app the port assiged by the OS. And the app can pass that port to the global app health check handler. --- src/servers/health_check_api/handlers.rs | 46 ++++++++++++++++++-- src/servers/http/v1/handlers/health_check.rs | 18 ++++++++ src/servers/http/v1/handlers/mod.rs | 1 + src/servers/http/v1/routes.rs | 4 +- tests/servers/http/client.rs | 4 ++ tests/servers/http/v1/contract.rs | 20 +++++++++ 6 files changed, 88 insertions(+), 5 deletions(-) create mode 100644 src/servers/http/v1/handlers/health_check.rs diff --git a/src/servers/health_check_api/handlers.rs b/src/servers/health_check_api/handlers.rs index 347106d6e..0a95c3211 100644 --- a/src/servers/health_check_api/handlers.rs +++ b/src/servers/health_check_api/handlers.rs @@ -1,3 +1,4 @@ +use std::net::SocketAddr; use std::sync::Arc; use axum::extract::State; @@ -7,16 +8,53 @@ use torrust_tracker_configuration::Configuration; use super::resources::Report; use super::responses; +/// If port 0 is specified in the configuration the OS will automatically +/// assign a free port. But we do now know in from the configuration. +/// We can only know it after starting the socket. +const UNKNOWN_PORT: u16 = 0; + /// Endpoint for container health check. +/// +/// This endpoint only checks services when we know the port from the +/// configuration. If port 0 is specified in the configuration the health check +/// for that service is skipped. pub(crate) async fn health_check_handler(State(config): State>) -> Json { + // todo: when port 0 is specified in the configuration get the port from the + // running service, after starting it as we do for testing with ephemeral + // configurations. + if config.http_api.enabled { - let health_check_url = format!("http://{}/health_check", config.http_api.bind_address); - if !get_req_is_ok(&health_check_url).await { - return responses::error(format!("API is not healthy. Health check endpoint: {health_check_url}")); + let addr: SocketAddr = config.http_api.bind_address.parse().expect("invalid socket address for API"); + + if addr.port() != UNKNOWN_PORT { + let health_check_url = format!("http://{addr}/health_check"); + + if !get_req_is_ok(&health_check_url).await { + return responses::error(format!("API is not healthy. Health check endpoint: {health_check_url}")); + } } } - // todo: for all HTTP Trackers, if enabled, check if is healthy + for http_tracker_config in &config.http_trackers { + if !http_tracker_config.enabled { + continue; + } + + let addr: SocketAddr = http_tracker_config + .bind_address + .parse() + .expect("invalid socket address for HTTP tracker"); + + if addr.port() != UNKNOWN_PORT { + let health_check_url = format!("http://{addr}/health_check"); + + if !get_req_is_ok(&health_check_url).await { + return responses::error(format!( + "HTTP Tracker is not healthy. Health check endpoint: {health_check_url}" + )); + } + } + } // todo: for all UDP Trackers, if enabled, check if is healthy diff --git a/src/servers/http/v1/handlers/health_check.rs b/src/servers/http/v1/handlers/health_check.rs new file mode 100644 index 000000000..b15af6255 --- /dev/null +++ b/src/servers/http/v1/handlers/health_check.rs @@ -0,0 +1,18 @@ +use axum::Json; +use serde::{Deserialize, Serialize}; + +#[allow(clippy::unused_async)] +pub async fn handler() -> Json { + Json(Report { status: Status::Ok }) +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +pub enum Status { + Ok, + Error, +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +pub struct Report { + pub status: Status, +} diff --git a/src/servers/http/v1/handlers/mod.rs b/src/servers/http/v1/handlers/mod.rs index d78dee7d5..d7fd05838 100644 --- a/src/servers/http/v1/handlers/mod.rs +++ b/src/servers/http/v1/handlers/mod.rs @@ -7,6 +7,7 @@ use crate::tracker::error::Error; pub mod announce; pub mod common; +pub mod health_check; pub mod scrape; impl From for responses::error::Error { diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 6546dcbb8..0b6b419c1 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -6,7 +6,7 @@ use axum::Router; use axum_client_ip::SecureClientIpSource; use tower_http::compression::CompressionLayer; -use super::handlers::{announce, scrape}; +use super::handlers::{announce, health_check, scrape}; use crate::tracker::Tracker; /// It adds the routes to the router. @@ -16,6 +16,8 @@ use crate::tracker::Tracker; #[allow(clippy::needless_pass_by_value)] pub fn router(tracker: Arc) -> Router { Router::new() + // Health check + .route("/health_check", get(health_check::handler)) // Announce request .route("/announce", get(announce::handle_without_key).with_state(tracker.clone())) .route("/announce/:key", get(announce::handle_with_key).with_state(tracker.clone())) diff --git a/tests/servers/http/client.rs b/tests/servers/http/client.rs index 0dbdd9cf6..03ed9aee4 100644 --- a/tests/servers/http/client.rs +++ b/tests/servers/http/client.rs @@ -60,6 +60,10 @@ impl Client { .await } + pub async fn health_check(&self) -> Response { + self.get(&self.build_path("health_check")).await + } + pub async fn get(&self, path: &str) -> Response { self.reqwest.get(self.build_url(path)).send().await.unwrap() } diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 2e24af6b7..b19009454 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -13,6 +13,26 @@ async fn test_environment_should_be_started_and_stopped() { mod for_all_config_modes { + use torrust_tracker::servers::http::v1::handlers::health_check::{Report, Status}; + use torrust_tracker_test_helpers::configuration; + + use crate::servers::http::client::Client; + use crate::servers::http::test_environment::running_test_environment; + use crate::servers::http::v1::contract::V1; + + #[tokio::test] + async fn health_check_endpoint_should_return_ok_if_the_http_tracker_is_running() { + let test_env = running_test_environment::(configuration::ephemeral_with_reverse_proxy()).await; + + let response = Client::new(*test_env.bind_address()).health_check().await; + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + assert_eq!(response.json::().await.unwrap(), Report { status: Status::Ok }); + + test_env.stop().await; + } + mod and_running_on_reverse_proxy { use torrust_tracker_test_helpers::configuration; From 2a05590fddf79a550abab6b6c477ddf562c46669 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 24 Nov 2023 17:32:44 +0000 Subject: [PATCH 0141/1297] refactor: [#508] move UDP tracker client to production code We will use the UDP tracker connection request to check if the UDP tracker service is healthy. --- src/servers/udp/mod.rs | 6 ----- src/servers/udp/server.rs | 2 +- src/shared/bit_torrent/mod.rs | 1 + .../shared/bit_torrent}/udp/client.rs | 27 +++++++++++++++++-- src/shared/bit_torrent/udp/mod.rs | 12 +++++++++ tests/servers/udp/contract.rs | 10 +++---- tests/servers/udp/mod.rs | 6 ----- 7 files changed, 44 insertions(+), 20 deletions(-) rename {tests/servers => src/shared/bit_torrent}/udp/client.rs (79%) create mode 100644 src/shared/bit_torrent/udp/mod.rs diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index 630867218..a50fffd37 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -652,9 +652,3 @@ pub type Port = u16; /// The transaction id. A random number generated byt the peer that is used to /// match requests and responses. pub type TransactionId = i64; - -/// The maximum number of bytes in a UDP packet. -pub const MAX_PACKET_SIZE: usize = 1496; -/// A magic 64-bit integer constant defined in the protocol that is used to -/// identify the protocol. -pub const PROTOCOL_ID: i64 = 0x0417_2710_1980; diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 428b76fa1..31e87481e 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -30,7 +30,7 @@ use tokio::task::JoinHandle; use crate::servers::signals::shutdown_signal; use crate::servers::udp::handlers::handle_packet; -use crate::servers::udp::MAX_PACKET_SIZE; +use crate::shared::bit_torrent::udp::MAX_PACKET_SIZE; use crate::tracker::Tracker; /// Error that can occur when starting or stopping the UDP server. diff --git a/src/shared/bit_torrent/mod.rs b/src/shared/bit_torrent/mod.rs index eba90b4ab..872203a1f 100644 --- a/src/shared/bit_torrent/mod.rs +++ b/src/shared/bit_torrent/mod.rs @@ -69,3 +69,4 @@ //!Bencode & bdecode in your browser | pub mod common; pub mod info_hash; +pub mod udp; diff --git a/tests/servers/udp/client.rs b/src/shared/bit_torrent/udp/client.rs similarity index 79% rename from tests/servers/udp/client.rs rename to src/shared/bit_torrent/udp/client.rs index d267adaba..d5c4c9adf 100644 --- a/tests/servers/udp/client.rs +++ b/src/shared/bit_torrent/udp/client.rs @@ -3,9 +3,8 @@ use std::sync::Arc; use aquatic_udp_protocol::{Request, Response}; use tokio::net::UdpSocket; -use torrust_tracker::servers::udp::MAX_PACKET_SIZE; -use crate::servers::udp::source_address; +use crate::shared::bit_torrent::udp::{source_address, MAX_PACKET_SIZE}; #[allow(clippy::module_name_repetitions)] pub struct UdpClient { @@ -13,6 +12,9 @@ pub struct UdpClient { } impl UdpClient { + /// # Panics + /// + /// Will panic if the local address can't be bound. pub async fn bind(local_address: &str) -> Self { let socket = UdpSocket::bind(local_address).await.unwrap(); Self { @@ -20,15 +22,30 @@ impl UdpClient { } } + /// # Panics + /// + /// Will panic if can't connect to the socket. pub async fn connect(&self, remote_address: &str) { self.socket.connect(remote_address).await.unwrap(); } + /// # Panics + /// + /// Will panic if: + /// + /// - Can't write to the socket. + /// - Can't send data. pub async fn send(&self, bytes: &[u8]) -> usize { self.socket.writable().await.unwrap(); self.socket.send(bytes).await.unwrap() } + /// # Panics + /// + /// Will panic if: + /// + /// - Can't read from the socket. + /// - Can't receive data. pub async fn receive(&self, bytes: &mut [u8]) -> usize { self.socket.readable().await.unwrap(); self.socket.recv(bytes).await.unwrap() @@ -49,6 +66,9 @@ pub struct UdpTrackerClient { } impl UdpTrackerClient { + /// # Panics + /// + /// Will panic if can't write request to bytes. pub async fn send(&self, request: Request) -> usize { // Write request into a buffer let request_buffer = vec![0u8; MAX_PACKET_SIZE]; @@ -68,6 +88,9 @@ impl UdpTrackerClient { self.udp_client.send(request_data).await } + /// # Panics + /// + /// Will panic if can't create response from the received payload (bytes buffer). pub async fn receive(&self) -> Response { let mut response_buffer = [0u8; MAX_PACKET_SIZE]; diff --git a/src/shared/bit_torrent/udp/mod.rs b/src/shared/bit_torrent/udp/mod.rs new file mode 100644 index 000000000..9322ef045 --- /dev/null +++ b/src/shared/bit_torrent/udp/mod.rs @@ -0,0 +1,12 @@ +pub mod client; + +/// The maximum number of bytes in a UDP packet. +pub const MAX_PACKET_SIZE: usize = 1496; +/// A magic 64-bit integer constant defined in the protocol that is used to +/// identify the protocol. +pub const PROTOCOL_ID: i64 = 0x0417_2710_1980; + +/// Generates the source address for the UDP client +fn source_address(port: u16) -> String { + format!("127.0.0.1:{port}") +} diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 3187d9871..72124fc3f 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -6,11 +6,11 @@ use core::panic; use aquatic_udp_protocol::{ConnectRequest, ConnectionId, Response, TransactionId}; -use torrust_tracker::servers::udp::MAX_PACKET_SIZE; +use torrust_tracker::shared::bit_torrent::udp::client::{new_udp_client_connected, UdpTrackerClient}; +use torrust_tracker::shared::bit_torrent::udp::MAX_PACKET_SIZE; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_error_response; -use crate::servers::udp::client::{new_udp_client_connected, UdpTrackerClient}; use crate::servers::udp::test_environment::running_test_environment; fn empty_udp_request() -> [u8; MAX_PACKET_SIZE] { @@ -51,10 +51,10 @@ async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_req mod receiving_a_connection_request { use aquatic_udp_protocol::{ConnectRequest, TransactionId}; + use torrust_tracker::shared::bit_torrent::udp::client::new_udp_tracker_client_connected; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_connect_response; - use crate::servers::udp::client::new_udp_tracker_client_connected; use crate::servers::udp::test_environment::running_test_environment; #[tokio::test] @@ -82,10 +82,10 @@ mod receiving_an_announce_request { AnnounceEvent, AnnounceRequest, ConnectionId, InfoHash, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, TransactionId, }; + use torrust_tracker::shared::bit_torrent::udp::client::new_udp_tracker_client_connected; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_ipv4_announce_response; - use crate::servers::udp::client::new_udp_tracker_client_connected; use crate::servers::udp::contract::send_connection_request; use crate::servers::udp::test_environment::running_test_environment; @@ -124,10 +124,10 @@ mod receiving_an_announce_request { mod receiving_an_scrape_request { use aquatic_udp_protocol::{ConnectionId, InfoHash, ScrapeRequest, TransactionId}; + use torrust_tracker::shared::bit_torrent::udp::client::new_udp_tracker_client_connected; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_scrape_response; - use crate::servers::udp::client::new_udp_tracker_client_connected; use crate::servers::udp::contract::send_connection_request; use crate::servers::udp::test_environment::running_test_environment; diff --git a/tests/servers/udp/mod.rs b/tests/servers/udp/mod.rs index d39c37153..4759350dc 100644 --- a/tests/servers/udp/mod.rs +++ b/tests/servers/udp/mod.rs @@ -1,9 +1,3 @@ pub mod asserts; -pub mod client; pub mod contract; pub mod test_environment; - -/// Generates the source address for the UDP client -fn source_address(port: u16) -> String { - format!("127.0.0.1:{port}") -} From bf23479debf17b7a396ea6b0d5ac6560e31144d7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 24 Nov 2023 17:45:42 +0000 Subject: [PATCH 0142/1297] feat: [#508] add health check for UDP tracker Using the `connect` UDP request. If the UDP trackers replies to a connection request we assume is healthy. --- src/servers/health_check_api/handlers.rs | 38 +++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/src/servers/health_check_api/handlers.rs b/src/servers/health_check_api/handlers.rs index 0a95c3211..4e8f2b928 100644 --- a/src/servers/health_check_api/handlers.rs +++ b/src/servers/health_check_api/handlers.rs @@ -1,12 +1,14 @@ use std::net::SocketAddr; use std::sync::Arc; +use aquatic_udp_protocol::{ConnectRequest, Response, TransactionId}; use axum::extract::State; use axum::Json; use torrust_tracker_configuration::Configuration; use super::resources::Report; use super::responses; +use crate::shared::bit_torrent::udp::client::new_udp_tracker_client_connected; /// If port 0 is specified in the configuration the OS will automatically /// assign a free port. But we do now know in from the configuration. @@ -23,6 +25,8 @@ pub(crate) async fn health_check_handler(State(config): State // running service, after starting it as we do for testing with ephemeral // configurations. + // Health check for API + if config.http_api.enabled { let addr: SocketAddr = config.http_api.bind_address.parse().expect("invalid socket address for API"); @@ -35,6 +39,8 @@ pub(crate) async fn health_check_handler(State(config): State } } + // Health check for HTTP Trackers + for http_tracker_config in &config.http_trackers { if !http_tracker_config.enabled { continue; @@ -56,7 +62,22 @@ pub(crate) async fn health_check_handler(State(config): State } } - // todo: for all UDP Trackers, if enabled, check if is healthy + // Health check for UDP Trackers + + for udp_tracker_config in &config.udp_trackers { + if !udp_tracker_config.enabled { + continue; + } + + let addr: SocketAddr = udp_tracker_config + .bind_address + .parse() + .expect("invalid socket address for UDP tracker"); + + if addr.port() != UNKNOWN_PORT && !can_connect_to_udp_tracker(&addr.to_string()).await { + return responses::error(format!("UDP Tracker is not healthy. Can't connect to: {addr}")); + } + } responses::ok() } @@ -67,3 +88,18 @@ async fn get_req_is_ok(url: &str) -> bool { Err(_err) => false, } } + +/// Tries to connect to an UDP tracker. It returns true if it succeeded. +async fn can_connect_to_udp_tracker(url: &str) -> bool { + let client = new_udp_tracker_client_connected(url).await; + + let connect_request = ConnectRequest { + transaction_id: TransactionId(123), + }; + + client.send(connect_request.into()).await; + + let response = client.receive().await; + + matches!(response, Response::Connect(_connect_response)) +} From 5e0a686023862f22e24ea9ffea6530f5d9b83efb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 24 Nov 2023 17:57:01 +0000 Subject: [PATCH 0143/1297] refactor: [#508] extract health check methods --- src/servers/health_check_api/handlers.rs | 58 ++++++++++++++++++------ 1 file changed, 44 insertions(+), 14 deletions(-) diff --git a/src/servers/health_check_api/handlers.rs b/src/servers/health_check_api/handlers.rs index 4e8f2b928..109b89bb4 100644 --- a/src/servers/health_check_api/handlers.rs +++ b/src/servers/health_check_api/handlers.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use aquatic_udp_protocol::{ConnectRequest, Response, TransactionId}; use axum::extract::State; use axum::Json; -use torrust_tracker_configuration::Configuration; +use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, UdpTracker}; use super::resources::Report; use super::responses; @@ -21,27 +21,49 @@ const UNKNOWN_PORT: u16 = 0; /// configuration. If port 0 is specified in the configuration the health check /// for that service is skipped. pub(crate) async fn health_check_handler(State(config): State>) -> Json { + if let Some(err_response) = api_health_check(&config.http_api).await { + return err_response; + } + + if let Some(err_response) = http_trackers_health_check(&config.http_trackers).await { + return err_response; + } + + if let Some(err_response) = udp_trackers_health_check(&config.udp_trackers).await { + return err_response; + } + + responses::ok() +} + +async fn api_health_check(config: &HttpApi) -> Option> { // todo: when port 0 is specified in the configuration get the port from the // running service, after starting it as we do for testing with ephemeral // configurations. - // Health check for API - - if config.http_api.enabled { - let addr: SocketAddr = config.http_api.bind_address.parse().expect("invalid socket address for API"); + if config.enabled { + let addr: SocketAddr = config.bind_address.parse().expect("invalid socket address for API"); if addr.port() != UNKNOWN_PORT { let health_check_url = format!("http://{addr}/health_check"); if !get_req_is_ok(&health_check_url).await { - return responses::error(format!("API is not healthy. Health check endpoint: {health_check_url}")); + return Some(responses::error(format!( + "API is not healthy. Health check endpoint: {health_check_url}" + ))); } } } - // Health check for HTTP Trackers + None +} - for http_tracker_config in &config.http_trackers { +async fn http_trackers_health_check(http_trackers: &Vec) -> Option> { + // todo: when port 0 is specified in the configuration get the port from the + // running service, after starting it as we do for testing with ephemeral + // configurations. + + for http_tracker_config in http_trackers { if !http_tracker_config.enabled { continue; } @@ -55,16 +77,22 @@ pub(crate) async fn health_check_handler(State(config): State let health_check_url = format!("http://{addr}/health_check"); if !get_req_is_ok(&health_check_url).await { - return responses::error(format!( + return Some(responses::error(format!( "HTTP Tracker is not healthy. Health check endpoint: {health_check_url}" - )); + ))); } } } - // Health check for UDP Trackers + None +} + +async fn udp_trackers_health_check(udp_trackers: &Vec) -> Option> { + // todo: when port 0 is specified in the configuration get the port from the + // running service, after starting it as we do for testing with ephemeral + // configurations. - for udp_tracker_config in &config.udp_trackers { + for udp_tracker_config in udp_trackers { if !udp_tracker_config.enabled { continue; } @@ -75,11 +103,13 @@ pub(crate) async fn health_check_handler(State(config): State .expect("invalid socket address for UDP tracker"); if addr.port() != UNKNOWN_PORT && !can_connect_to_udp_tracker(&addr.to_string()).await { - return responses::error(format!("UDP Tracker is not healthy. Can't connect to: {addr}")); + return Some(responses::error(format!( + "UDP Tracker is not healthy. Can't connect to: {addr}" + ))); } } - responses::ok() + None } async fn get_req_is_ok(url: &str) -> bool { From 5ce0048b075b06d8fd2ae35cf70363a2362b6f79 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 1 Dec 2023 09:55:54 +0000 Subject: [PATCH 0144/1297] fix: disable shellcheck --- share/container/entry_script_sh | 1 + 1 file changed, 1 insertion(+) diff --git a/share/container/entry_script_sh b/share/container/entry_script_sh index 94dfa6b81..4f98e6622 100644 --- a/share/container/entry_script_sh +++ b/share/container/entry_script_sh @@ -73,6 +73,7 @@ if [ -e "/usr/share/torrust/container/message" ]; then fi # Load message of the day from Profile +# shellcheck disable=SC2016 echo '[ ! -z "$TERM" -a -r /etc/motd ] && cat /etc/motd' >> /etc/profile cd /home/torrust || exit 1 From 74511ee2a1fef85a45c5d9a13f74fc02c2766854 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 1 Dec 2023 09:56:19 +0000 Subject: [PATCH 0145/1297] feat: add script to install for development Used here: https://github.com/torrust/torrust-index-gui/blob/develop/docs/development_guide.md#run-the-tracker --- contrib/dev-tools/init/install-local.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/contrib/dev-tools/init/install-local.sh b/contrib/dev-tools/init/install-local.sh index f9806a0b8..747c357bc 100755 --- a/contrib/dev-tools/init/install-local.sh +++ b/contrib/dev-tools/init/install-local.sh @@ -7,6 +7,5 @@ mkdir -p ./storage/tracker/lib/database # Generate the sqlite database if it does not exist if ! [ -f "./storage/tracker/lib/database/sqlite3.db" ]; then - # todo: it should get the path from tracker.toml and only do it when we use sqlite - sqlite3 ./storage/tracker/lib/database/sqlite3.db "VACUUM;" + sqlite3 ./storage/tracker/lib/database/sqlite3.db "VACUUM;" fi From 5439b6e0fb36e5b933050eda284ca13bf14a694b Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 2 Dec 2023 16:34:24 +0800 Subject: [PATCH 0146/1297] chore: update deps constrained versions: - axum = "0.6" - axum-client-ip = "0.4" - tower-http = "0.4" info: ``` Updating async-compression v0.4.4 -> v0.4.5 Updating borsh v0.10.3 -> v1.2.0 Updating borsh-derive v0.10.3 -> v1.2.0 Removing borsh-derive-internal v0.10.3 Removing borsh-schema-derive-internal v0.10.3 Adding cfg_aliases v0.1.1 Updating clap v4.4.7 -> v4.4.10 Updating clap_builder v4.4.7 -> v4.4.9 Updating core-foundation v0.9.3 -> v0.9.4 Updating core-foundation-sys v0.8.4 -> v0.8.6 Updating errno v0.3.5 -> v0.3.8 Updating form_urlencoded v1.2.0 -> v1.2.1 Updating getrandom v0.2.10 -> v0.2.11 Updating gimli v0.28.0 -> v0.28.1 Updating h2 v0.3.21 -> v0.3.22 Updating hashbrown v0.14.2 -> v0.14.3 Updating http v0.2.9 -> v0.2.11 Updating idna v0.4.0 -> v0.5.0 Updating js-sys v0.3.65 -> v0.3.66 Updating linux-raw-sys v0.4.10 -> v0.4.12 Updating proc-macro-crate v0.1.5 -> v2.0.0 Updating proc-macro2 v1.0.69 -> v1.0.70 Updating ring v0.17.5 -> v0.17.6 Updating rust_decimal v1.32.0 -> v1.33.1 Updating rustix v0.38.21 -> v0.38.26 Updating rustls v0.21.8 -> v0.21.9 Updating rustls-pemfile v1.0.3 -> v1.0.4 Updating smallvec v1.11.1 -> v1.11.2 Adding syn_derive v0.1.8 Updating termcolor v1.3.0 -> v1.4.0 Adding toml_edit v0.20.7 Updating url v2.4.1 -> v2.5.0 Updating wasm-bindgen v0.2.88 -> v0.2.89 Updating wasm-bindgen-backend v0.2.88 -> v0.2.89 Updating wasm-bindgen-futures v0.4.38 -> v0.4.39 Updating wasm-bindgen-macro v0.2.88 -> v0.2.89 Updating wasm-bindgen-macro-support v0.2.88 -> v0.2.89 Updating wasm-bindgen-shared v0.2.88 -> v0.2.89 Updating web-sys v0.3.65 -> v0.3.66 Adding windows-sys v0.52.0 Adding windows-targets v0.52.0 Adding windows_aarch64_gnullvm v0.52.0 Adding windows_aarch64_msvc v0.52.0 Adding windows_i686_gnu v0.52.0 Adding windows_i686_msvc v0.52.0 Adding windows_x86_64_gnu v0.52.0 Adding windows_x86_64_gnullvm v0.52.0 Adding windows_x86_64_msvc v0.52.0 Updating zerocopy v0.7.25 -> v0.7.28 Updating zerocopy-derive v0.7.25 -> v0.7.28 ``` --- Cargo.lock | 330 ++++++++++++++++++++++++++++++++--------------------- Cargo.toml | 6 +- 2 files changed, 205 insertions(+), 131 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 336adb8f7..30a961b14 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -121,9 +121,9 @@ checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "async-compression" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f658e2baef915ba0f26f1f7c42bfb8e12f532a01f449a090ded75ae7a07e9ba2" +checksum = "bc2d0cfb2a7388d34f590e76686704c494ed7aaceed62ee1ba35cbf363abc2a5" dependencies = [ "brotli", "flate2", @@ -331,47 +331,26 @@ dependencies = [ [[package]] name = "borsh" -version = "0.10.3" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4114279215a005bc675e386011e594e1d9b800918cea18fcadadcce864a2046b" +checksum = "bf617fabf5cdbdc92f774bfe5062d870f228b80056d41180797abf48bed4056e" dependencies = [ "borsh-derive", - "hashbrown 0.13.2", + "cfg_aliases", ] [[package]] name = "borsh-derive" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0754613691538d51f329cce9af41d7b7ca150bc973056f1156611489475f54f7" -dependencies = [ - "borsh-derive-internal", - "borsh-schema-derive-internal", - "proc-macro-crate 0.1.5", - "proc-macro2", - "syn 1.0.109", -] - -[[package]] -name = "borsh-derive-internal" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afb438156919598d2c7bad7e1c0adf3d26ed3840dbc010db1a882a65583ca2fb" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "borsh-schema-derive-internal" -version = "0.10.3" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634205cc43f74a1b9046ef87c4540ebda95696ec0f315024860cad7c5b0f5ccd" +checksum = "f404657a7ea7b5249e36808dff544bc88a28f26e0ac40009f674b7a009d14be3" dependencies = [ + "once_cell", + "proc-macro-crate 2.0.0", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.39", + "syn_derive", ] [[package]] @@ -472,6 +451,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + [[package]] name = "chrono" version = "0.4.31" @@ -482,7 +467,7 @@ dependencies = [ "iana-time-zone", "num-traits", "serde", - "windows-targets", + "windows-targets 0.48.5", ] [[package]] @@ -525,18 +510,18 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.7" +version = "4.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac495e00dcec98c83465d5ad66c5c4fabd652fd6686e7c6269b117e729a6f17b" +checksum = "41fffed7514f420abec6d183b1d3acfd9099c79c3a10a06ade4f8203f1411272" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" -version = "4.4.7" +version = "4.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c77ed9a32a62e6ca27175d00d29d05ca32e396ea1eb5fb01d8256b669cec7663" +checksum = "63361bae7eef3771745f02d8d892bec2fee5f6e34af316ba556e7f97a7069ff1" dependencies = [ "anstyle", "clap_lex", @@ -584,9 +569,9 @@ checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" [[package]] name = "core-foundation" -version = "0.9.3" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" dependencies = [ "core-foundation-sys", "libc", @@ -594,9 +579,9 @@ dependencies = [ [[package]] name = "core-foundation-sys" -version = "0.8.4" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" +checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" [[package]] name = "cpufeatures" @@ -849,12 +834,12 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.5" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3e13f66a2f95e32a39eaa81f6b95d42878ca0e1db0c7543723dfe12557e860" +checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] @@ -937,9 +922,9 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] name = "form_urlencoded" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" dependencies = [ "percent-encoding", ] @@ -1119,9 +1104,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.10" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" +checksum = "fe9006bed769170c11f845cf00c7c1e9092aeb3f268e007c3e760ac68008070f" dependencies = [ "cfg-if", "libc", @@ -1130,9 +1115,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.28.0" +version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0" +checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" [[package]] name = "glob" @@ -1142,9 +1127,9 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "h2" -version = "0.3.21" +version = "0.3.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91fc23aa11be92976ef4729127f1a74adf36d8436f7816b185d18df956790833" +checksum = "4d6250322ef6e60f93f9a2162799302cd6f68f79f6e5d85c8c16f14d1d958178" dependencies = [ "bytes", "fnv", @@ -1152,7 +1137,7 @@ dependencies = [ "futures-sink", "futures-util", "http", - "indexmap 1.9.3", + "indexmap 2.1.0", "slab", "tokio", "tokio-util", @@ -1185,9 +1170,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.14.2" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156" +checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" dependencies = [ "ahash 0.8.6", "allocator-api2", @@ -1199,7 +1184,7 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7" dependencies = [ - "hashbrown 0.14.2", + "hashbrown 0.14.3", ] [[package]] @@ -1222,9 +1207,9 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "http" -version = "0.2.9" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482" +checksum = "8947b1a6fad4393052c7ba1f4cd97bed3e953a95c79c92ad9b051a04611d9fbb" dependencies = [ "bytes", "fnv", @@ -1328,9 +1313,9 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "idna" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" +checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" dependencies = [ "unicode-bidi", "unicode-normalization", @@ -1354,7 +1339,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f" dependencies = [ "equivalent", - "hashbrown 0.14.2", + "hashbrown 0.14.3", "serde", ] @@ -1382,7 +1367,7 @@ checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" dependencies = [ "hermit-abi", "rustix", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -1411,9 +1396,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.65" +version = "0.3.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54c0c35952f67de54bb584e9fd912b3023117cbafc0a77d8f3dee1fb5f572fe8" +checksum = "cee9c64da59eae3b50095c18d3e74f8b73c0b86d2792824ff01bbce68ba229ca" dependencies = [ "wasm-bindgen", ] @@ -1560,9 +1545,9 @@ checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" [[package]] name = "linux-raw-sys" -version = "0.4.10" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da2479e8c062e40bf0066ffa0bc823de0a9368974af99c9f6df941d2c231e03f" +checksum = "c4cd1a83af159aa67994778be9070f0ae1bd732942279cabb14f86f986a21456" [[package]] name = "local-ip-address" @@ -1573,7 +1558,7 @@ dependencies = [ "libc", "neli", "thiserror", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -1651,7 +1636,7 @@ checksum = "3dce281c5e46beae905d4de1870d8b1509a9142b62eedf18b443b011ca8343d0" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -1991,7 +1976,7 @@ dependencies = [ "libc", "redox_syscall", "smallvec", - "windows-targets", + "windows-targets 0.48.5", ] [[package]] @@ -2215,21 +2200,21 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "0.1.5" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" dependencies = [ - "toml 0.5.11", + "once_cell", + "toml_edit 0.19.15", ] [[package]] name = "proc-macro-crate" -version = "1.3.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +checksum = "7e8366a6159044a37876a2b9817124296703c586a5c92e2c53751fa06d8d43e8" dependencies = [ - "once_cell", - "toml_edit 0.19.15", + "toml_edit 0.20.7", ] [[package]] @@ -2258,9 +2243,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.69" +version = "1.0.70" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" +checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" dependencies = [ "unicode-ident", ] @@ -2469,16 +2454,16 @@ dependencies = [ [[package]] name = "ring" -version = "0.17.5" +version = "0.17.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb0205304757e5d899b9c2e448b867ffd03ae7f988002e47cd24954391394d0b" +checksum = "684d5e6e18f669ccebf64a92236bb7db9a34f07be010e3627368182027180866" dependencies = [ "cc", "getrandom", "libc", "spin", "untrusted", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -2546,9 +2531,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.32.0" +version = "1.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4c4216490d5a413bc6d10fa4742bd7d4955941d062c0ef873141d6b0e7b30fd" +checksum = "06676aec5ccb8fc1da723cc8c0f9a46549f21ebb8753d3915c6c41db1e7f1dc4" dependencies = [ "arrayvec", "borsh", @@ -2583,22 +2568,22 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.21" +version = "0.38.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b426b0506e5d50a7d8dafcf2e81471400deb602392c7dd110815afb4eaf02a3" +checksum = "9470c4bf8246c8daf25f9598dca807fb6510347b1e1cfa55749113850c79d88a" dependencies = [ "bitflags 2.4.1", "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] name = "rustls" -version = "0.21.8" +version = "0.21.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446e14c5cda4f3f30fe71863c34ec70f5ac79d6087097ad0bb433e1be5edf04c" +checksum = "629648aced5775d558af50b2b4c7b02983a04b312126d45eeead26e7caa498b9" dependencies = [ "log", "ring", @@ -2608,9 +2593,9 @@ dependencies = [ [[package]] name = "rustls-pemfile" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d3987094b1d07b653b7dfdc3f70ce9a1da9c51ac18c1b06b662e4f9a0e9f4b2" +checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" dependencies = [ "base64 0.21.5", ] @@ -2658,7 +2643,7 @@ version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" dependencies = [ - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -2902,9 +2887,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.11.1" +version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a" +checksum = "4dccd0940a2dcdf68d092b8cbab7dc0ad8fa938bf95787e1b916b0e3d0e8e970" [[package]] name = "socket2" @@ -2923,7 +2908,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b5fac59a5cb5dd637972e5fca70daf0523c9067fcdc4842f053dae04a18f8e9" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -2976,6 +2961,18 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn_derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1329189c02ff984e9736652b1631330da25eaa6bc639089ed4915d25446cbe7b" +dependencies = [ + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.39", +] + [[package]] name = "sync_wrapper" version = "0.1.2" @@ -3036,14 +3033,14 @@ dependencies = [ "fastrand", "redox_syscall", "rustix", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] name = "termcolor" -version = "1.3.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6093bad37da69aab9d123a8091e4be0aa4a03e4d601ec641c327398315f62b64" +checksum = "ff1bc3d3f05aff0403e8ac0d92ced918ec05b666a43f83297ccef5bea8a3d449" dependencies = [ "winapi-util", ] @@ -3143,7 +3140,7 @@ dependencies = [ "signal-hook-registry", "socket2 0.5.5", "tokio-macros", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -3232,6 +3229,17 @@ dependencies = [ "winnow", ] +[[package]] +name = "toml_edit" +version = "0.20.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" +dependencies = [ + "indexmap 2.1.0", + "toml_datetime", + "winnow", +] + [[package]] name = "toml_edit" version = "0.21.0" @@ -3469,9 +3477,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5" +checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" dependencies = [ "form_urlencoded", "idna", @@ -3527,9 +3535,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.88" +version = "0.2.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7daec296f25a1bae309c0cd5c29c4b260e510e6d813c286b19eaadf409d40fce" +checksum = "0ed0d4f68a3015cc185aff4db9506a015f4b96f95303897bfa23f846db54064e" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -3537,9 +3545,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.88" +version = "0.2.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e397f4664c0e4e428e8313a469aaa58310d302159845980fd23b0f22a847f217" +checksum = "1b56f625e64f3a1084ded111c4d5f477df9f8c92df113852fa5a374dbda78826" dependencies = [ "bumpalo", "log", @@ -3552,9 +3560,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.38" +version = "0.4.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9afec9963e3d0994cac82455b2b3502b81a7f40f9a0d32181f7528d9f4b43e02" +checksum = "ac36a15a220124ac510204aec1c3e5db8a22ab06fd6706d881dc6149f8ed9a12" dependencies = [ "cfg-if", "js-sys", @@ -3564,9 +3572,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.88" +version = "0.2.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5961017b3b08ad5f3fe39f1e79877f8ee7c23c5e5fd5eb80de95abc41f1f16b2" +checksum = "0162dbf37223cd2afce98f3d0785506dcb8d266223983e4b5b525859e6e182b2" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3574,9 +3582,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.88" +version = "0.2.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5353b8dab669f5e10f5bd76df26a9360c748f054f862ff5f3f8aae0c7fb3907" +checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283" dependencies = [ "proc-macro2", "quote", @@ -3587,15 +3595,15 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.88" +version = "0.2.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d046c5d029ba91a1ed14da14dca44b68bf2f124cfbaf741c54151fdb3e0750b" +checksum = "7ab9b36309365056cd639da3134bf87fa8f3d86008abf99e612384a6eecd459f" [[package]] name = "web-sys" -version = "0.3.65" +version = "0.3.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5db499c5f66323272151db0e666cd34f78617522fb0c1604d31a27c50c206a85" +checksum = "50c24a44ec86bb68fbecd1b3efed7e85ea5621b39b35ef2766b66cd984f8010f" dependencies = [ "js-sys", "wasm-bindgen", @@ -3638,7 +3646,7 @@ version = "0.51.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1f8cf84f35d2db49a46868f947758c7a1138116f7fac3bc844f43ade1292e64" dependencies = [ - "windows-targets", + "windows-targets 0.48.5", ] [[package]] @@ -3647,7 +3655,16 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ - "windows-targets", + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.0", ] [[package]] @@ -3656,13 +3673,28 @@ version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" +dependencies = [ + "windows_aarch64_gnullvm 0.52.0", + "windows_aarch64_msvc 0.52.0", + "windows_i686_gnu 0.52.0", + "windows_i686_msvc 0.52.0", + "windows_x86_64_gnu 0.52.0", + "windows_x86_64_gnullvm 0.52.0", + "windows_x86_64_msvc 0.52.0", ] [[package]] @@ -3671,42 +3703,84 @@ version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" + [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" + [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" +[[package]] +name = "windows_i686_gnu" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" + [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" +[[package]] +name = "windows_i686_msvc" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" + [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" + [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" + [[package]] name = "windows_x86_64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" + [[package]] name = "winnow" version = "0.5.19" @@ -3723,7 +3797,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" dependencies = [ "cfg-if", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -3746,18 +3820,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.7.25" +version = "0.7.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cd369a67c0edfef15010f980c3cbe45d7f651deac2cd67ce097cd801de16557" +checksum = "7d6f15f7ade05d2a4935e34a457b936c23dc70a05cc1d97133dc99e7a3fe0f0e" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.7.25" +version = "0.7.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2f140bda219a26ccc0cdb03dba58af72590c53b22642577d88a927bc5c87d6b" +checksum = "dbbad221e3f78500350ecbd7dfa4e63ef945c05f4c61cb7f4d3f84cd0bba649b" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 2316a1edf..5f55c6c5c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ version = "3.0.0-alpha.12-develop" [dependencies] aquatic_udp_protocol = "0" async-trait = "0" -axum = "0" -axum-client-ip = "0" +axum = "0.6" +axum-client-ip = "0.4" axum-server = { version = "0", features = ["tls-rustls"] } binascii = "0" chrono = { version = "0", default-features = false, features = ["clock"] } @@ -64,7 +64,7 @@ torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "pa torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12-develop", path = "contrib/bencode" } torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "packages/located-error" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } -tower-http = { version = "0", features = ["compression-full"] } +tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } [dev-dependencies] From 986ab64316fc2df977b58115bc8ba218ca0a896a Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 3 Dec 2023 14:49:36 +0800 Subject: [PATCH 0147/1297] dev: refactor: rename tracker mod to core --- packages/configuration/src/lib.rs | 6 +- src/app.rs | 4 +- src/bootstrap/app.rs | 4 +- src/bootstrap/jobs/http_tracker.rs | 6 +- src/bootstrap/jobs/torrent_cleanup.rs | 4 +- src/bootstrap/jobs/tracker_apis.rs | 4 +- src/bootstrap/jobs/udp_tracker.rs | 4 +- src/{tracker => core}/auth.rs | 12 ++-- src/{tracker => core}/databases/driver.rs | 6 +- src/{tracker => core}/databases/error.rs | 2 +- src/{tracker => core}/databases/mod.rs | 16 +++--- src/{tracker => core}/databases/mysql.rs | 28 +++++----- src/{tracker => core}/databases/sqlite.rs | 28 +++++----- src/{tracker => core}/error.rs | 0 src/{tracker => core}/mod.rs | 54 +++++++++--------- src/{tracker => core}/peer.rs | 10 ++-- src/{tracker => core}/services/mod.rs | 6 +- .../services/statistics/mod.rs | 24 ++++---- .../services/statistics/setup.rs | 6 +- src/{tracker => core}/services/torrent.rs | 18 +++--- src/{tracker => core}/statistics.rs | 14 ++--- src/{tracker => core}/torrent.rs | 4 +- src/lib.rs | 6 +- src/servers/apis/routes.rs | 2 +- src/servers/apis/server.rs | 8 +-- .../apis/v1/context/auth_key/handlers.rs | 4 +- .../apis/v1/context/auth_key/resources.rs | 4 +- .../apis/v1/context/auth_key/routes.rs | 2 +- src/servers/apis/v1/context/stats/handlers.rs | 4 +- .../apis/v1/context/stats/resources.rs | 8 +-- .../apis/v1/context/stats/responses.rs | 2 +- src/servers/apis/v1/context/stats/routes.rs | 2 +- .../apis/v1/context/torrent/handlers.rs | 4 +- .../apis/v1/context/torrent/resources/peer.rs | 10 ++-- .../v1/context/torrent/resources/torrent.rs | 6 +- .../apis/v1/context/torrent/responses.rs | 2 +- src/servers/apis/v1/context/torrent/routes.rs | 2 +- .../apis/v1/context/whitelist/handlers.rs | 2 +- .../apis/v1/context/whitelist/routes.rs | 2 +- src/servers/apis/v1/routes.rs | 2 +- src/servers/http/mod.rs | 12 ++-- src/servers/http/percent_encoding.rs | 10 ++-- src/servers/http/server.rs | 2 +- .../http/v1/extractors/announce_request.rs | 2 +- .../http/v1/extractors/authentication_key.rs | 2 +- src/servers/http/v1/handlers/announce.rs | 12 ++-- src/servers/http/v1/handlers/common/auth.rs | 2 +- src/servers/http/v1/handlers/mod.rs | 2 +- src/servers/http/v1/handlers/scrape.rs | 12 ++-- src/servers/http/v1/launcher.rs | 2 +- src/servers/http/v1/requests/announce.rs | 6 +- src/servers/http/v1/responses/announce.rs | 10 ++-- src/servers/http/v1/responses/scrape.rs | 10 ++-- src/servers/http/v1/routes.rs | 2 +- src/servers/http/v1/services/announce.rs | 16 +++--- src/servers/http/v1/services/scrape.rs | 14 ++--- src/servers/udp/handlers.rs | 56 +++++++++---------- src/servers/udp/mod.rs | 12 ++-- src/servers/udp/peer_builder.rs | 2 +- src/servers/udp/server.rs | 2 +- src/shared/bit_torrent/common.rs | 4 +- tests/common/app.rs | 2 +- tests/common/fixtures.rs | 2 +- tests/servers/api/mod.rs | 2 +- tests/servers/api/test_environment.rs | 4 +- .../api/v1/contract/context/auth_key.rs | 2 +- tests/servers/http/client.rs | 2 +- tests/servers/http/connection_info.rs | 2 +- tests/servers/http/requests/announce.rs | 2 +- tests/servers/http/responses/announce.rs | 2 +- tests/servers/http/test_environment.rs | 4 +- tests/servers/http/v1/contract.rs | 12 ++-- tests/servers/udp/test_environment.rs | 4 +- 73 files changed, 281 insertions(+), 283 deletions(-) rename src/{tracker => core}/auth.rs (96%) rename src/{tracker => core}/databases/driver.rs (90%) rename src/{tracker => core}/databases/error.rs (97%) rename src/{tracker => core}/databases/mod.rs (92%) rename src/{tracker => core}/databases/mysql.rs (89%) rename src/{tracker => core}/databases/sqlite.rs (90%) rename src/{tracker => core}/error.rs (100%) rename src/{tracker => core}/mod.rs (97%) rename src/{tracker => core}/peer.rs (98%) rename src/{tracker => core}/services/mod.rs (71%) rename src/{tracker => core}/services/statistics/mod.rs (81%) rename src/{tracker => core}/services/statistics/setup.rs (83%) rename src/{tracker => core}/services/torrent.rs (95%) rename src/{tracker => core}/statistics.rs (95%) rename src/{tracker => core}/torrent.rs (99%) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 217f8a8be..918d9f014 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -30,10 +30,10 @@ //! //! Each section in the toml structure is mapped to a data structure. For //! example, the `[http_api]` section (configuration for the tracker HTTP API) -//! is mapped to the [`HttpApi`](HttpApi) structure. +//! is mapped to the [`HttpApi`] structure. //! //! > **NOTICE**: some sections are arrays of structures. For example, the -//! > `[[udp_trackers]]` section is an array of [`UdpTracker`](UdpTracker) since +//! > `[[udp_trackers]]` section is an array of [`UdpTracker`] since //! > you can have multiple running UDP trackers bound to different ports. //! //! Please refer to the documentation of each structure for more information @@ -394,7 +394,7 @@ pub struct Configuration { /// Logging level. Possible values are: `Off`, `Error`, `Warn`, `Info`, /// `Debug` and `Trace`. Default is `Info`. pub log_level: Option, - /// Tracker mode. See [`TrackerMode`](torrust_tracker_primitives::TrackerMode) for more information. + /// Tracker mode. See [`TrackerMode`] for more information. pub mode: TrackerMode, // Database configuration diff --git a/src/app.rs b/src/app.rs index e749f9c64..32c12d74a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -28,8 +28,8 @@ use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; +use crate::core; use crate::servers::http::Version; -use crate::tracker; /// # Panics /// @@ -37,7 +37,7 @@ use crate::tracker; /// /// - Can't retrieve tracker keys from database. /// - Can't load whitelist from database. -pub async fn start(config: Arc, tracker: Arc) -> Vec> { +pub async fn start(config: Arc, tracker: Arc) -> Vec> { let mut jobs: Vec> = Vec::new(); // Load peer keys diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 78c16a0a5..4a6f79a96 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -17,10 +17,10 @@ use torrust_tracker_configuration::Configuration; use super::config::initialize_configuration; use crate::bootstrap; +use crate::core::services::tracker_factory; +use crate::core::Tracker; use crate::shared::clock::static_time; use crate::shared::crypto::ephemeral_instance_keys; -use crate::tracker::services::tracker_factory; -use crate::tracker::Tracker; /// It loads the configuration from the environment and builds the main domain [`Tracker`] struct. #[must_use] diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index a38fe3a5a..ecf6bd8ac 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -19,9 +19,9 @@ use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_tracker_configuration::HttpTracker; +use crate::core; use crate::servers::http::v1::launcher; use crate::servers::http::Version; -use crate::tracker; /// This is the message that the "**launcher**" spawned task sends to the main application process to notify that the HTTP server was successfully started. /// @@ -33,7 +33,7 @@ pub struct ServerJobStarted(); /// /// Right now there is only one version but in the future we could support more than one HTTP tracker version at the same time. /// This feature allows supporting breaking changes on `BitTorrent` BEPs. -pub async fn start_job(config: &HttpTracker, tracker: Arc, version: Version) -> JoinHandle<()> { +pub async fn start_job(config: &HttpTracker, tracker: Arc, version: Version) -> JoinHandle<()> { match version { Version::V1 => start_v1(config, tracker.clone()).await, } @@ -42,7 +42,7 @@ pub async fn start_job(config: &HttpTracker, tracker: Arc, ver /// # Panics /// /// It would panic if the `config::HttpTracker` struct would contain inappropriate values. -async fn start_v1(config: &HttpTracker, tracker: Arc) -> JoinHandle<()> { +async fn start_v1(config: &HttpTracker, tracker: Arc) -> JoinHandle<()> { let bind_addr = config .bind_address .parse::() diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index d48769139..d3b084d31 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -17,7 +17,7 @@ use log::info; use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; -use crate::tracker; +use crate::core; /// It starts a jobs for cleaning up the torrent data in the tracker. /// @@ -25,7 +25,7 @@ use crate::tracker; /// /// Refer to [`torrust-tracker-configuration documentation`](https://docs.rs/torrust-tracker-configuration) for more info about that option. #[must_use] -pub fn start_job(config: &Arc, tracker: &Arc) -> JoinHandle<()> { +pub fn start_job(config: &Arc, tracker: &Arc) -> JoinHandle<()> { let weak_tracker = std::sync::Arc::downgrade(tracker); let interval = config.inactive_peer_cleanup_interval; diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 33b9b6e4a..ca29d2b5f 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -28,8 +28,8 @@ use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_tracker_configuration::HttpApi; +use crate::core; use crate::servers::apis::server; -use crate::tracker; /// This is the message that the "launcher" spawned task sends to the main /// application process to notify the API server was successfully started. @@ -49,7 +49,7 @@ pub struct ApiServerJobStarted(); /// # Panics /// /// It would panic if unable to send the `ApiServerJobStarted` notice. -pub async fn start_job(config: &HttpApi, tracker: Arc) -> JoinHandle<()> { +pub async fn start_job(config: &HttpApi, tracker: Arc) -> JoinHandle<()> { let bind_addr = config .bind_address .parse::() diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 76c465a8d..9a30c9126 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -12,14 +12,14 @@ use log::{error, info, warn}; use tokio::task::JoinHandle; use torrust_tracker_configuration::UdpTracker; +use crate::core; use crate::servers::udp::server::Udp; -use crate::tracker; /// It starts a new UDP server with the provided configuration. /// /// It spawns a new asynchronous task for the new UDP server. #[must_use] -pub fn start_job(config: &UdpTracker, tracker: Arc) -> JoinHandle<()> { +pub fn start_job(config: &UdpTracker, tracker: Arc) -> JoinHandle<()> { let bind_addr = config.bind_address.clone(); tokio::spawn(async move { diff --git a/src/tracker/auth.rs b/src/core/auth.rs similarity index 96% rename from src/tracker/auth.rs rename to src/core/auth.rs index 2759c8d06..c6b772485 100644 --- a/src/tracker/auth.rs +++ b/src/core/auth.rs @@ -12,7 +12,7 @@ //! Keys are stored in this struct: //! //! ```rust,no_run -//! use torrust_tracker::tracker::auth::Key; +//! use torrust_tracker::core::auth::Key; //! use torrust_tracker::shared::clock::DurationSinceUnixEpoch; //! //! pub struct ExpiringKey { @@ -26,7 +26,7 @@ //! You can generate a new key valid for `9999` seconds and `0` nanoseconds from the current time with the following: //! //! ```rust,no_run -//! use torrust_tracker::tracker::auth; +//! use torrust_tracker::core::auth; //! use std::time::Duration; //! //! let expiring_key = auth::generate(Duration::new(9999, 0)); @@ -138,7 +138,7 @@ pub struct Key(String); /// Error returned when a key cannot be parsed from a string. /// /// ```rust,no_run -/// use torrust_tracker::tracker::auth::Key; +/// use torrust_tracker::core::auth::Key; /// use std::str::FromStr; /// /// let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; @@ -164,7 +164,7 @@ impl FromStr for Key { } } -/// Verification error. Error returned when an [`ExpiringKey`] cannot be verified with the [`verify(...)`](crate::tracker::auth::verify) function. +/// Verification error. Error returned when an [`ExpiringKey`] cannot be verified with the [`verify(...)`](crate::core::auth::verify) function. /// #[derive(Debug, Error)] #[allow(dead_code)] @@ -196,7 +196,7 @@ mod tests { mod key { use std::str::FromStr; - use crate::tracker::auth::Key; + use crate::core::auth::Key; #[test] fn should_be_parsed_from_an_string() { @@ -212,8 +212,8 @@ mod tests { use std::str::FromStr; use std::time::Duration; + use crate::core::auth; use crate::shared::clock::{Current, StoppedTime}; - use crate::tracker::auth; #[test] fn should_be_parsed_from_an_string() { diff --git a/src/tracker/databases/driver.rs b/src/core/databases/driver.rs similarity index 90% rename from src/tracker/databases/driver.rs rename to src/core/databases/driver.rs index 19cb7046e..99d96c6b1 100644 --- a/src/tracker/databases/driver.rs +++ b/src/core/databases/driver.rs @@ -1,6 +1,6 @@ //! Database driver factory. //! -//! See [`databases::driver::build`](crate::tracker::databases::driver::build) +//! See [`databases::driver::build`](crate::core::databases::driver::build) //! function for more information. use torrust_tracker_primitives::DatabaseDriver; @@ -14,7 +14,7 @@ use super::{Builder, Database}; /// Example for `SQLite3`: /// /// ```rust,no_run -/// use torrust_tracker::tracker::databases; +/// use torrust_tracker::core::databases; /// use torrust_tracker_primitives::DatabaseDriver; /// /// let db_driver = DatabaseDriver::Sqlite3; @@ -25,7 +25,7 @@ use super::{Builder, Database}; /// Example for `MySQL`: /// /// ```rust,no_run -/// use torrust_tracker::tracker::databases; +/// use torrust_tracker::core::databases; /// use torrust_tracker_primitives::DatabaseDriver; /// /// let db_driver = DatabaseDriver::MySQL; diff --git a/src/tracker/databases/error.rs b/src/core/databases/error.rs similarity index 97% rename from src/tracker/databases/error.rs rename to src/core/databases/error.rs index d89ec05de..96b0d835e 100644 --- a/src/tracker/databases/error.rs +++ b/src/core/databases/error.rs @@ -1,6 +1,6 @@ //! Database errors. //! -//! This module contains the [Database errors](crate::tracker::databases::error::Error). +//! This module contains the [Database errors](crate::core::databases::error::Error). use std::panic::Location; use std::sync::Arc; diff --git a/src/tracker/databases/mod.rs b/src/core/databases/mod.rs similarity index 92% rename from src/tracker/databases/mod.rs rename to src/core/databases/mod.rs index 902880496..14fcb6b5b 100644 --- a/src/tracker/databases/mod.rs +++ b/src/core/databases/mod.rs @@ -4,8 +4,8 @@ //! //! There are two implementations of the trait (two drivers): //! -//! - [`Mysql`](crate::tracker::databases::mysql::Mysql) -//! - [`Sqlite`](crate::tracker::databases::sqlite::Sqlite) +//! - [`Mysql`](crate::core::databases::mysql::Mysql) +//! - [`Sqlite`](crate::core::databases::sqlite::Sqlite) //! //! > **NOTICE**: There are no database migrations. If there are any changes, //! we will implemented them or provide a script to migrate to the new schema. @@ -22,7 +22,7 @@ //! ---|---|--- //! `id` | 1 | Autoincrement id //! `info_hash` | `c1277613db1d28709b034a017ab2cae4be07ae10` | `BitTorrent` infohash V1 -//! `completed` | 20 | The number of peers that have ever completed downloading the torrent associated to this entry. See [`Entry`](crate::tracker::torrent::Entry) for more information. +//! `completed` | 20 | The number of peers that have ever completed downloading the torrent associated to this entry. See [`Entry`](crate::core::torrent::Entry) for more information. //! //! > **NOTICE**: The peer list for a torrent is not persisted. Since peer have to re-announce themselves on intervals, the data is be //! regenerated again after some minutes. @@ -53,8 +53,8 @@ use std::marker::PhantomData; use async_trait::async_trait; use self::error::Error; +use crate::core::auth::{self, Key}; use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::auth::{self, Key}; struct Builder where @@ -116,9 +116,9 @@ pub trait Database: Sync + Send { /// /// It returns an array of tuples with the torrent /// [`InfoHash`] and the - /// [`completed`](crate::tracker::torrent::Entry::completed) counter + /// [`completed`](crate::core::torrent::Entry::completed) counter /// which is the number of times the torrent has been downloaded. - /// See [`Entry::completed`](crate::tracker::torrent::Entry::completed). + /// See [`Entry::completed`](crate::core::torrent::Entry::completed). /// /// # Context: Torrent Metrics /// @@ -200,8 +200,8 @@ pub trait Database: Sync + Send { /// It gets an expiring authentication key from the database. /// - /// It returns `Some(ExpiringKey)` if a [`ExpiringKey`](crate::tracker::auth::ExpiringKey) - /// with the input [`Key`](crate::tracker::auth::Key) exists, `None` otherwise. + /// It returns `Some(ExpiringKey)` if a [`ExpiringKey`](crate::core::auth::ExpiringKey) + /// with the input [`Key`](crate::core::auth::Key) exists, `None` otherwise. /// /// # Context: Authentication Keys /// diff --git a/src/tracker/databases/mysql.rs b/src/core/databases/mysql.rs similarity index 89% rename from src/tracker/databases/mysql.rs rename to src/core/databases/mysql.rs index 4419666ab..c46300829 100644 --- a/src/tracker/databases/mysql.rs +++ b/src/core/databases/mysql.rs @@ -11,9 +11,9 @@ use r2d2_mysql::MySqlConnectionManager; use torrust_tracker_primitives::DatabaseDriver; use super::{Database, Error}; +use crate::core::auth::{self, Key}; use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::auth::{self, Key}; const DRIVER: DatabaseDriver = DatabaseDriver::MySQL; @@ -25,7 +25,7 @@ pub struct Mysql { impl Database for Mysql { /// It instantiates a new `MySQL` database driver. /// - /// Refer to [`databases::Database::new`](crate::tracker::databases::Database::new). + /// Refer to [`databases::Database::new`](crate::core::databases::Database::new). /// /// # Errors /// @@ -39,7 +39,7 @@ impl Database for Mysql { Ok(Self { pool }) } - /// Refer to [`databases::Database::create_database_tables`](crate::tracker::databases::Database::create_database_tables). + /// Refer to [`databases::Database::create_database_tables`](crate::core::databases::Database::create_database_tables). fn create_database_tables(&self) -> Result<(), Error> { let create_whitelist_table = " CREATE TABLE IF NOT EXISTS whitelist ( @@ -79,7 +79,7 @@ impl Database for Mysql { Ok(()) } - /// Refer to [`databases::Database::drop_database_tables`](crate::tracker::databases::Database::drop_database_tables). + /// Refer to [`databases::Database::drop_database_tables`](crate::core::databases::Database::drop_database_tables). fn drop_database_tables(&self) -> Result<(), Error> { let drop_whitelist_table = " DROP TABLE `whitelist`;" @@ -104,7 +104,7 @@ impl Database for Mysql { Ok(()) } - /// Refer to [`databases::Database::load_persistent_torrents`](crate::tracker::databases::Database::load_persistent_torrents). + /// Refer to [`databases::Database::load_persistent_torrents`](crate::core::databases::Database::load_persistent_torrents). async fn load_persistent_torrents(&self) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -119,7 +119,7 @@ impl Database for Mysql { Ok(torrents) } - /// Refer to [`databases::Database::load_keys`](crate::tracker::databases::Database::load_keys). + /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). async fn load_keys(&self) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -134,7 +134,7 @@ impl Database for Mysql { Ok(keys) } - /// Refer to [`databases::Database::load_whitelist`](crate::tracker::databases::Database::load_whitelist). + /// Refer to [`databases::Database::load_whitelist`](crate::core::databases::Database::load_whitelist). async fn load_whitelist(&self) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -145,7 +145,7 @@ impl Database for Mysql { Ok(info_hashes) } - /// Refer to [`databases::Database::save_persistent_torrent`](crate::tracker::databases::Database::save_persistent_torrent). + /// Refer to [`databases::Database::save_persistent_torrent`](crate::core::databases::Database::save_persistent_torrent). async fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { const COMMAND : &str = "INSERT INTO torrents (info_hash, completed) VALUES (:info_hash_str, :completed) ON DUPLICATE KEY UPDATE completed = VALUES(completed)"; @@ -158,7 +158,7 @@ impl Database for Mysql { Ok(conn.exec_drop(COMMAND, params! { info_hash_str, completed })?) } - /// Refer to [`databases::Database::get_info_hash_from_whitelist`](crate::tracker::databases::Database::get_info_hash_from_whitelist). + /// Refer to [`databases::Database::get_info_hash_from_whitelist`](crate::core::databases::Database::get_info_hash_from_whitelist). async fn get_info_hash_from_whitelist(&self, info_hash: &InfoHash) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -172,7 +172,7 @@ impl Database for Mysql { Ok(info_hash) } - /// Refer to [`databases::Database::add_info_hash_to_whitelist`](crate::tracker::databases::Database::add_info_hash_to_whitelist). + /// Refer to [`databases::Database::add_info_hash_to_whitelist`](crate::core::databases::Database::add_info_hash_to_whitelist). async fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -186,7 +186,7 @@ impl Database for Mysql { Ok(1) } - /// Refer to [`databases::Database::remove_info_hash_from_whitelist`](crate::tracker::databases::Database::remove_info_hash_from_whitelist). + /// Refer to [`databases::Database::remove_info_hash_from_whitelist`](crate::core::databases::Database::remove_info_hash_from_whitelist). async fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -197,7 +197,7 @@ impl Database for Mysql { Ok(1) } - /// Refer to [`databases::Database::get_key_from_keys`](crate::tracker::databases::Database::get_key_from_keys). + /// Refer to [`databases::Database::get_key_from_keys`](crate::core::databases::Database::get_key_from_keys). async fn get_key_from_keys(&self, key: &Key) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -214,7 +214,7 @@ impl Database for Mysql { })) } - /// Refer to [`databases::Database::add_key_to_keys`](crate::tracker::databases::Database::add_key_to_keys). + /// Refer to [`databases::Database::add_key_to_keys`](crate::core::databases::Database::add_key_to_keys). async fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -229,7 +229,7 @@ impl Database for Mysql { Ok(1) } - /// Refer to [`databases::Database::remove_key_from_keys`](crate::tracker::databases::Database::remove_key_from_keys). + /// Refer to [`databases::Database::remove_key_from_keys`](crate::core::databases::Database::remove_key_from_keys). async fn remove_key_from_keys(&self, key: &Key) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; diff --git a/src/tracker/databases/sqlite.rs b/src/core/databases/sqlite.rs similarity index 90% rename from src/tracker/databases/sqlite.rs rename to src/core/databases/sqlite.rs index 1968ee049..bf2d6b8b9 100644 --- a/src/tracker/databases/sqlite.rs +++ b/src/core/databases/sqlite.rs @@ -8,9 +8,9 @@ use r2d2_sqlite::SqliteConnectionManager; use torrust_tracker_primitives::DatabaseDriver; use super::{Database, Error}; +use crate::core::auth::{self, Key}; use crate::shared::bit_torrent::info_hash::InfoHash; use crate::shared::clock::DurationSinceUnixEpoch; -use crate::tracker::auth::{self, Key}; const DRIVER: DatabaseDriver = DatabaseDriver::Sqlite3; @@ -22,7 +22,7 @@ pub struct Sqlite { impl Database for Sqlite { /// It instantiates a new `SQLite3` database driver. /// - /// Refer to [`databases::Database::new`](crate::tracker::databases::Database::new). + /// Refer to [`databases::Database::new`](crate::core::databases::Database::new). /// /// # Errors /// @@ -32,7 +32,7 @@ impl Database for Sqlite { Pool::new(cm).map_or_else(|err| Err((err, DatabaseDriver::Sqlite3).into()), |pool| Ok(Sqlite { pool })) } - /// Refer to [`databases::Database::create_database_tables`](crate::tracker::databases::Database::create_database_tables). + /// Refer to [`databases::Database::create_database_tables`](crate::core::databases::Database::create_database_tables). fn create_database_tables(&self) -> Result<(), Error> { let create_whitelist_table = " CREATE TABLE IF NOT EXISTS whitelist ( @@ -66,7 +66,7 @@ impl Database for Sqlite { Ok(()) } - /// Refer to [`databases::Database::drop_database_tables`](crate::tracker::databases::Database::drop_database_tables). + /// Refer to [`databases::Database::drop_database_tables`](crate::core::databases::Database::drop_database_tables). fn drop_database_tables(&self) -> Result<(), Error> { let drop_whitelist_table = " DROP TABLE whitelist;" @@ -89,7 +89,7 @@ impl Database for Sqlite { Ok(()) } - /// Refer to [`databases::Database::load_persistent_torrents`](crate::tracker::databases::Database::load_persistent_torrents). + /// Refer to [`databases::Database::load_persistent_torrents`](crate::core::databases::Database::load_persistent_torrents). async fn load_persistent_torrents(&self) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -110,7 +110,7 @@ impl Database for Sqlite { Ok(torrents) } - /// Refer to [`databases::Database::load_keys`](crate::tracker::databases::Database::load_keys). + /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). async fn load_keys(&self) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -131,7 +131,7 @@ impl Database for Sqlite { Ok(keys) } - /// Refer to [`databases::Database::load_whitelist`](crate::tracker::databases::Database::load_whitelist). + /// Refer to [`databases::Database::load_whitelist`](crate::core::databases::Database::load_whitelist). async fn load_whitelist(&self) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -148,7 +148,7 @@ impl Database for Sqlite { Ok(info_hashes) } - /// Refer to [`databases::Database::save_persistent_torrent`](crate::tracker::databases::Database::save_persistent_torrent). + /// Refer to [`databases::Database::save_persistent_torrent`](crate::core::databases::Database::save_persistent_torrent). async fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -167,7 +167,7 @@ impl Database for Sqlite { } } - /// Refer to [`databases::Database::get_info_hash_from_whitelist`](crate::tracker::databases::Database::get_info_hash_from_whitelist). + /// Refer to [`databases::Database::get_info_hash_from_whitelist`](crate::core::databases::Database::get_info_hash_from_whitelist). async fn get_info_hash_from_whitelist(&self, info_hash: &InfoHash) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -180,7 +180,7 @@ impl Database for Sqlite { Ok(query.map(|f| InfoHash::from_str(&f.get_unwrap::<_, String>(0)).unwrap())) } - /// Refer to [`databases::Database::add_info_hash_to_whitelist`](crate::tracker::databases::Database::add_info_hash_to_whitelist). + /// Refer to [`databases::Database::add_info_hash_to_whitelist`](crate::core::databases::Database::add_info_hash_to_whitelist). async fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -196,7 +196,7 @@ impl Database for Sqlite { } } - /// Refer to [`databases::Database::remove_info_hash_from_whitelist`](crate::tracker::databases::Database::remove_info_hash_from_whitelist). + /// Refer to [`databases::Database::remove_info_hash_from_whitelist`](crate::core::databases::Database::remove_info_hash_from_whitelist). async fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -214,7 +214,7 @@ impl Database for Sqlite { } } - /// Refer to [`databases::Database::get_key_from_keys`](crate::tracker::databases::Database::get_key_from_keys). + /// Refer to [`databases::Database::get_key_from_keys`](crate::core::databases::Database::get_key_from_keys). async fn get_key_from_keys(&self, key: &Key) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -234,7 +234,7 @@ impl Database for Sqlite { })) } - /// Refer to [`databases::Database::add_key_to_keys`](crate::tracker::databases::Database::add_key_to_keys). + /// Refer to [`databases::Database::add_key_to_keys`](crate::core::databases::Database::add_key_to_keys). async fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -253,7 +253,7 @@ impl Database for Sqlite { } } - /// Refer to [`databases::Database::remove_key_from_keys`](crate::tracker::databases::Database::remove_key_from_keys). + /// Refer to [`databases::Database::remove_key_from_keys`](crate::core::databases::Database::remove_key_from_keys). async fn remove_key_from_keys(&self, key: &Key) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; diff --git a/src/tracker/error.rs b/src/core/error.rs similarity index 100% rename from src/tracker/error.rs rename to src/core/error.rs diff --git a/src/tracker/mod.rs b/src/core/mod.rs similarity index 97% rename from src/tracker/mod.rs rename to src/core/mod.rs index 94d75a8cd..ed6ba6a8d 100644 --- a/src/tracker/mod.rs +++ b/src/core/mod.rs @@ -55,7 +55,7 @@ //! Once you have instantiated the `Tracker` you can `announce` a new [`Peer`] with: //! //! ```rust,no_run -//! use torrust_tracker::tracker::peer; +//! use torrust_tracker::core::peer; //! use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; //! use torrust_tracker::shared::clock::DurationSinceUnixEpoch; //! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; @@ -97,7 +97,7 @@ //! The returned struct is: //! //! ```rust,no_run -//! use torrust_tracker::tracker::peer::Peer; +//! use torrust_tracker::core::peer::Peer; //! //! pub struct AnnounceData { //! pub peers: Vec, @@ -251,7 +251,7 @@ //! A `Peer` is the struct used by the `Tracker` to keep peers data: //! //! ```rust,no_run -//! use torrust_tracker::tracker::peer::Id; +//! use torrust_tracker::core::peer::Id; //! use std::net::SocketAddr; //! use torrust_tracker::shared::clock::DurationSinceUnixEpoch; //! use aquatic_udp_protocol::NumberOfBytes; @@ -364,7 +364,7 @@ //! To learn more about tracker authentication, refer to the following modules : //! //! - [`auth`] module. -//! - [`tracker`](crate::tracker) module. +//! - [`core`](crate::core) module. //! - [`http`](crate::servers::http) module. //! //! # Statistics @@ -455,8 +455,8 @@ use self::auth::Key; use self::error::Error; use self::peer::Peer; use self::torrent::{SwarmMetadata, SwarmStats}; +use crate::core::databases::Database; use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::databases::Database; /// The domain layer tracker service. /// @@ -470,8 +470,8 @@ use crate::tracker::databases::Database; pub struct Tracker { /// `Tracker` configuration. See [`torrust-tracker-configuration`](torrust_tracker_configuration) pub config: Arc, - /// A database driver implementation: [`Sqlite3`](crate::tracker::databases::sqlite) - /// or [`MySQL`](crate::tracker::databases::mysql) + /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) + /// or [`MySQL`](crate::core::databases::mysql) pub database: Box, mode: TrackerMode, keys: RwLock>, @@ -1110,11 +1110,11 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; + use crate::core::peer::{self, Peer}; + use crate::core::services::tracker_factory; + use crate::core::{TorrentsMetrics, Tracker}; use crate::shared::bit_torrent::info_hash::InfoHash; use crate::shared::clock::DurationSinceUnixEpoch; - use crate::tracker::peer::{self, Peer}; - use crate::tracker::services::tracker_factory; - use crate::tracker::{TorrentsMetrics, Tracker}; fn public_tracker() -> Tracker { tracker_factory(configuration::ephemeral_mode_public().into()) @@ -1288,7 +1288,7 @@ mod tests { mod handling_an_announce_request { - use crate::tracker::tests::the_tracker::{ + use crate::core::tests::the_tracker::{ peer_ip, public_tracker, sample_info_hash, sample_peer, sample_peer_1, sample_peer_2, }; @@ -1296,7 +1296,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr}; - use crate::tracker::assign_ip_address_to_peer; + use crate::core::assign_ip_address_to_peer; #[test] fn using_the_source_ip_instead_of_the_ip_in_the_announce_request() { @@ -1312,7 +1312,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::str::FromStr; - use crate::tracker::assign_ip_address_to_peer; + use crate::core::assign_ip_address_to_peer; #[test] fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { @@ -1353,7 +1353,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::str::FromStr; - use crate::tracker::assign_ip_address_to_peer; + use crate::core::assign_ip_address_to_peer; #[test] fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { @@ -1418,7 +1418,7 @@ mod tests { mod it_should_update_the_swarm_stats_for_the_torrent { - use crate::tracker::tests::the_tracker::{ + use crate::core::tests::the_tracker::{ completed_peer, leecher, peer_ip, public_tracker, sample_info_hash, seeder, started_peer, }; @@ -1464,9 +1464,9 @@ mod tests { use std::net::{IpAddr, Ipv4Addr}; + use crate::core::tests::the_tracker::{complete_peer, incomplete_peer, public_tracker}; + use crate::core::{ScrapeData, SwarmMetadata}; use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::tests::the_tracker::{complete_peer, incomplete_peer, public_tracker}; - use crate::tracker::{ScrapeData, SwarmMetadata}; #[tokio::test] async fn it_should_return_a_zeroed_swarm_metadata_for_the_requested_file_if_the_tracker_does_not_have_that_torrent( @@ -1542,7 +1542,7 @@ mod tests { mod configured_as_whitelisted { mod handling_authorization { - use crate::tracker::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; + use crate::core::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { @@ -1569,7 +1569,7 @@ mod tests { } mod handling_the_torrent_whitelist { - use crate::tracker::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; + use crate::core::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; #[tokio::test] async fn it_should_add_a_torrent_to_the_whitelist() { @@ -1596,7 +1596,7 @@ mod tests { } mod persistence { - use crate::tracker::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; + use crate::core::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; #[tokio::test] async fn it_should_load_the_whitelist_from_the_database() { @@ -1621,12 +1621,12 @@ mod tests { mod handling_an_scrape_request { - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::tests::the_tracker::{ + use crate::core::tests::the_tracker::{ complete_peer, incomplete_peer, peer_ip, sample_info_hash, whitelisted_tracker, }; - use crate::tracker::torrent::SwarmMetadata; - use crate::tracker::ScrapeData; + use crate::core::torrent::SwarmMetadata; + use crate::core::ScrapeData; + use crate::shared::bit_torrent::info_hash::InfoHash; #[test] fn it_should_be_able_to_build_a_zeroed_scrape_data_for_a_list_of_info_hashes() { @@ -1670,8 +1670,8 @@ mod tests { use std::str::FromStr; use std::time::Duration; - use crate::tracker::auth; - use crate::tracker::tests::the_tracker::private_tracker; + use crate::core::auth; + use crate::core::tests::the_tracker::private_tracker; #[tokio::test] async fn it_should_generate_the_expiring_authentication_keys() { @@ -1767,7 +1767,7 @@ mod tests { mod handling_torrent_persistence { use aquatic_udp_protocol::AnnounceEvent; - use crate::tracker::tests::the_tracker::{sample_info_hash, sample_peer, tracker_persisting_torrents_in_database}; + use crate::core::tests::the_tracker::{sample_info_hash, sample_peer, tracker_persisting_torrents_in_database}; #[tokio::test] async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { diff --git a/src/tracker/peer.rs b/src/core/peer.rs similarity index 98% rename from src/tracker/peer.rs rename to src/core/peer.rs index 4027799a9..a64f87b66 100644 --- a/src/tracker/peer.rs +++ b/src/core/peer.rs @@ -3,7 +3,7 @@ //! A sample peer: //! //! ```rust,no_run -//! use torrust_tracker::tracker::peer; +//! use torrust_tracker::core::peer; //! use std::net::SocketAddr; //! use std::net::IpAddr; //! use std::net::Ipv4Addr; @@ -46,7 +46,7 @@ pub enum IPVersion { /// A sample peer: /// /// ```rust,no_run -/// use torrust_tracker::tracker::peer; +/// use torrust_tracker::core::peer; /// use std::net::SocketAddr; /// use std::net::IpAddr; /// use std::net::Ipv4Addr; @@ -118,7 +118,7 @@ impl Peer { /// A sample peer ID: /// /// ```rust,no_run -/// use torrust_tracker::tracker::peer; +/// use torrust_tracker::core::peer; /// /// let peer_id = peer::Id(*b"-qB00000000000000000"); /// ``` @@ -281,7 +281,7 @@ impl Serialize for Id { mod test { mod torrent_peer_id { - use crate::tracker::peer; + use crate::core::peer; #[test] fn should_be_instantiated_from_a_byte_slice() { @@ -398,8 +398,8 @@ mod test { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use serde_json::Value; + use crate::core::peer::{self, Peer}; use crate::shared::clock::{Current, Time}; - use crate::tracker::peer::{self, Peer}; #[test] fn it_should_be_serializable() { diff --git a/src/tracker/services/mod.rs b/src/core/services/mod.rs similarity index 71% rename from src/tracker/services/mod.rs rename to src/core/services/mod.rs index deb07a439..f5868fc26 100644 --- a/src/tracker/services/mod.rs +++ b/src/core/services/mod.rs @@ -2,8 +2,8 @@ //! //! There are two types of service: //! -//! - [Core tracker services](crate::tracker::services::torrent): related to the tracker main functionalities like getting info about torrents. -//! - [Services for statistics](crate::tracker::services::statistics): related to tracker metrics. Aggregate data about the tracker server. +//! - [Core tracker services](crate::core::services::torrent): related to the tracker main functionalities like getting info about torrents. +//! - [Services for statistics](crate::core::services::statistics): related to tracker metrics. Aggregate data about the tracker server. pub mod statistics; pub mod torrent; @@ -11,7 +11,7 @@ use std::sync::Arc; use torrust_tracker_configuration::Configuration; -use crate::tracker::Tracker; +use crate::core::Tracker; /// It returns a new tracker building its dependencies. /// diff --git a/src/tracker/services/statistics/mod.rs b/src/core/services/statistics/mod.rs similarity index 81% rename from src/tracker/services/statistics/mod.rs rename to src/core/services/statistics/mod.rs index 3ef8b52bb..f74df62e5 100644 --- a/src/tracker/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -2,15 +2,15 @@ //! //! It includes: //! -//! - A [`factory`](crate::tracker::services::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. -//! - A [`get_metrics`] service to get the [`tracker metrics`](crate::tracker::statistics::Metrics). +//! - A [`factory`](crate::core::services::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`get_metrics`] service to get the [`tracker metrics`](crate::core::statistics::Metrics). //! //! Tracker metrics are collected using a Publisher-Subscribe pattern. //! //! The factory function builds two structs: //! -//! - An statistics [`EventSender`](crate::tracker::statistics::EventSender) -//! - An statistics [`Repo`](crate::tracker::statistics::Repo) +//! - An statistics [`EventSender`](crate::core::statistics::EventSender) +//! - An statistics [`Repo`](crate::core::statistics::Repo) //! //! ```text //! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); @@ -21,7 +21,7 @@ //! There is an event listener that is receiving all the events and processing them with an event handler. //! Then, the event handler updates the metrics depending on the received event. //! -//! For example, if you send the event [`Event::Udp4Connect`](crate::tracker::statistics::Event::Udp4Connect): +//! For example, if you send the event [`Event::Udp4Connect`](crate::core::statistics::Event::Udp4Connect): //! //! ```text //! let result = event_sender.send_event(Event::Udp4Connect).await; @@ -40,8 +40,8 @@ pub mod setup; use std::sync::Arc; -use crate::tracker::statistics::Metrics; -use crate::tracker::{TorrentsMetrics, Tracker}; +use crate::core::statistics::Metrics; +use crate::core::{TorrentsMetrics, Tracker}; /// All the metrics collected by the tracker. #[derive(Debug, PartialEq)] @@ -88,9 +88,9 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; - use crate::tracker; - use crate::tracker::services::statistics::{get_metrics, TrackerMetrics}; - use crate::tracker::services::tracker_factory; + use crate::core; + use crate::core::services::statistics::{get_metrics, TrackerMetrics}; + use crate::core::services::tracker_factory; pub fn tracker_configuration() -> Arc { Arc::new(configuration::ephemeral()) @@ -105,8 +105,8 @@ mod tests { assert_eq!( tracker_metrics, TrackerMetrics { - torrents_metrics: tracker::TorrentsMetrics::default(), - protocol_metrics: tracker::statistics::Metrics::default(), + torrents_metrics: core::TorrentsMetrics::default(), + protocol_metrics: core::statistics::Metrics::default(), } ); } diff --git a/src/tracker/services/statistics/setup.rs b/src/core/services/statistics/setup.rs similarity index 83% rename from src/tracker/services/statistics/setup.rs rename to src/core/services/statistics/setup.rs index 4bf5a827a..37603852b 100644 --- a/src/tracker/services/statistics/setup.rs +++ b/src/core/services/statistics/setup.rs @@ -1,14 +1,14 @@ //! Setup for the tracker statistics. //! //! The [`factory`] function builds the structs needed for handling the tracker metrics. -use crate::tracker::statistics; +use crate::core::statistics; /// It builds the structs needed for handling the tracker metrics. /// /// It returns: /// -/// - An statistics [`EventSender`](crate::tracker::statistics::EventSender) that allows you to send events related to statistics. -/// - An statistics [`Repo`](crate::tracker::statistics::Repo) which is an in-memory repository for the tracker metrics. +/// - An statistics [`EventSender`](crate::core::statistics::EventSender) that allows you to send events related to statistics. +/// - An statistics [`Repo`](crate::core::statistics::Repo) which is an in-memory repository for the tracker metrics. /// /// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics /// events are sent are received but not dispatched to the handler. diff --git a/src/tracker/services/torrent.rs b/src/core/services/torrent.rs similarity index 95% rename from src/tracker/services/torrent.rs rename to src/core/services/torrent.rs index 934fa6b77..651f40cab 100644 --- a/src/tracker/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -8,9 +8,9 @@ use std::sync::Arc; use serde::Deserialize; +use crate::core::peer::Peer; +use crate::core::Tracker; use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::peer::Peer; -use crate::tracker::Tracker; /// It contains all the information the tracker has about a torrent #[derive(Debug, PartialEq)] @@ -141,8 +141,8 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use crate::core::peer; use crate::shared::clock::DurationSinceUnixEpoch; - use crate::tracker::peer; fn sample_peer() -> peer::Peer { peer::Peer { @@ -164,10 +164,10 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; + use crate::core::services::torrent::tests::sample_peer; + use crate::core::services::torrent::{get_torrent_info, Info}; + use crate::core::services::tracker_factory; use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::services::torrent::tests::sample_peer; - use crate::tracker::services::torrent::{get_torrent_info, Info}; - use crate::tracker::services::tracker_factory; pub fn tracker_configuration() -> Arc { Arc::new(configuration::ephemeral()) @@ -219,10 +219,10 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; + use crate::core::services::torrent::tests::sample_peer; + use crate::core::services::torrent::{get_torrents, BasicInfo, Pagination}; + use crate::core::services::tracker_factory; use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::services::torrent::tests::sample_peer; - use crate::tracker::services::torrent::{get_torrents, BasicInfo, Pagination}; - use crate::tracker::services::tracker_factory; pub fn tracker_configuration() -> Arc { Arc::new(configuration::ephemeral()) diff --git a/src/tracker/statistics.rs b/src/core/statistics.rs similarity index 95% rename from src/tracker/statistics.rs rename to src/core/statistics.rs index 85cc4f255..f38662cdd 100644 --- a/src/tracker/statistics.rs +++ b/src/core/statistics.rs @@ -13,10 +13,10 @@ //! //! The data is collected by using an `event-sender -> event listener` model. //! -//! The tracker uses an [`statistics::EventSender`](crate::tracker::statistics::EventSender) instance to send an event. -//! The [`statistics::Keeper`](crate::tracker::statistics::Keeper) listens to new events and uses the [`statistics::Repo`](crate::tracker::statistics::Repo) to upgrade and store metrics. +//! The tracker uses an [`statistics::EventSender`](crate::core::statistics::EventSender) instance to send an event. +//! The [`statistics::Keeper`](crate::core::statistics::Keeper) listens to new events and uses the [`statistics::Repo`](crate::core::statistics::Repo) to upgrade and store metrics. //! -//! See the [`statistics::Event`](crate::tracker::statistics::Event) enum to check which events are available. +//! See the [`statistics::Event`](crate::core::statistics::Event) enum to check which events are available. use std::sync::Arc; use async_trait::async_trait; @@ -191,10 +191,10 @@ pub trait EventSender: Sync + Send { async fn send_event(&self, event: Event) -> Option>>; } -/// An [`statistics::EventSender`](crate::tracker::statistics::EventSender) implementation. +/// An [`statistics::EventSender`](crate::core::statistics::EventSender) implementation. /// /// It uses a channel sender to send the statistic events. The channel is created by a -/// [`statistics::Keeper`](crate::tracker::statistics::Keeper) +/// [`statistics::Keeper`](crate::core::statistics::Keeper) pub struct Sender { sender: mpsc::Sender, } @@ -307,7 +307,7 @@ impl Repo { mod tests { mod stats_tracker { - use crate::tracker::statistics::{Event, Keeper, Metrics}; + use crate::core::statistics::{Event, Keeper, Metrics}; #[tokio::test] async fn should_contain_the_tracker_statistics() { @@ -331,7 +331,7 @@ mod tests { } mod event_handler { - use crate::tracker::statistics::{event_handler, Event, Repo}; + use crate::core::statistics::{event_handler, Event, Repo}; #[tokio::test] async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { diff --git a/src/tracker/torrent.rs b/src/core/torrent.rs similarity index 99% rename from src/tracker/torrent.rs rename to src/core/torrent.rs index de520aeb1..8167aa2db 100644 --- a/src/tracker/torrent.rs +++ b/src/core/torrent.rs @@ -191,9 +191,9 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use crate::core::peer; + use crate::core::torrent::Entry; use crate::shared::clock::{Current, DurationSinceUnixEpoch, Stopped, StoppedTime, Time, Working}; - use crate::tracker::peer; - use crate::tracker::torrent::Entry; struct TorrentPeerBuilder { peer: peer::Peer, diff --git a/src/lib.rs b/src/lib.rs index 8d453f177..c5f775646 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -387,7 +387,7 @@ //! //! Torrust Tracker has four main components: //! -//! - The core [`tracker`] +//! - The core tracker [`core`] //! - The tracker REST [`API`](crate::servers::apis) //! - The [`UDP`](crate::servers::udp) tracker //! - The [`HTTP`](crate::servers::http) tracker @@ -405,7 +405,7 @@ //! - Statistics //! - Persistence //! -//! See [`tracker`] for more details on the [`tracker`] module. +//! See [`core`] for more details on the [`core`] module. //! //! ## Tracker API //! @@ -471,9 +471,9 @@ //! examples on the integration and unit tests. pub mod app; pub mod bootstrap; +pub mod core; pub mod servers; pub mod shared; -pub mod tracker; #[macro_use] extern crate lazy_static; diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 0740e1f6a..49f263db3 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -13,7 +13,7 @@ use tower_http::compression::CompressionLayer; use super::v1; use super::v1::context::health_check::handlers::health_check_handler; -use crate::tracker::Tracker; +use crate::core::Tracker; /// Add all API routes to the router. #[allow(clippy::needless_pass_by_value)] diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 778a17d90..58b60638e 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -34,8 +34,8 @@ use futures::Future; use log::info; use super::routes::router; +use crate::core::Tracker; use crate::servers::signals::shutdown_signal; -use crate::tracker::Tracker; /// Errors that can occur when starting or stopping the API server. #[derive(Debug)] @@ -281,9 +281,9 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; + use crate::core; + use crate::core::statistics; use crate::servers::apis::server::ApiServer; - use crate::tracker; - use crate::tracker::statistics; fn tracker_configuration() -> Arc { Arc::new(configuration::ephemeral()) @@ -293,7 +293,7 @@ mod tests { async fn it_should_be_able_to_start_from_stopped_state_and_then_stop_again() { let cfg = tracker_configuration(); - let tracker = Arc::new(tracker::Tracker::new(cfg.clone(), None, statistics::Repo::new()).unwrap()); + let tracker = Arc::new(core::Tracker::new(cfg.clone(), None, statistics::Repo::new()).unwrap()); let stopped_api_server = ApiServer::new(cfg.http_api.clone()); diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index d6a2992fb..a6c8bf812 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -10,10 +10,10 @@ use serde::Deserialize; use super::responses::{ auth_key_response, failed_to_delete_key_response, failed_to_generate_key_response, failed_to_reload_keys_response, }; +use crate::core::auth::Key; +use crate::core::Tracker; use crate::servers::apis::v1::context::auth_key::resources::AuthKey; use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_response}; -use crate::tracker::auth::Key; -use crate::tracker::Tracker; /// It handles the request to generate a new authentication key. /// diff --git a/src/servers/apis/v1/context/auth_key/resources.rs b/src/servers/apis/v1/context/auth_key/resources.rs index 5099fad8b..f4c7f34ca 100644 --- a/src/servers/apis/v1/context/auth_key/resources.rs +++ b/src/servers/apis/v1/context/auth_key/resources.rs @@ -3,8 +3,8 @@ use std::convert::From; use serde::{Deserialize, Serialize}; +use crate::core::auth::{self, Key}; use crate::shared::clock::convert_from_iso_8601_to_timestamp; -use crate::tracker::auth::{self, Key}; /// A resource that represents an authentication key. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -43,8 +43,8 @@ mod tests { use std::time::Duration; use super::AuthKey; + use crate::core::auth::{self, Key}; use crate::shared::clock::{Current, TimeNow}; - use crate::tracker::auth::{self, Key}; struct TestTime { pub timestamp: u64, diff --git a/src/servers/apis/v1/context/auth_key/routes.rs b/src/servers/apis/v1/context/auth_key/routes.rs index 76c634e21..003ee5af4 100644 --- a/src/servers/apis/v1/context/auth_key/routes.rs +++ b/src/servers/apis/v1/context/auth_key/routes.rs @@ -12,7 +12,7 @@ use axum::routing::{get, post}; use axum::Router; use super::handlers::{delete_auth_key_handler, generate_auth_key_handler, reload_keys_handler}; -use crate::tracker::Tracker; +use crate::core::Tracker; /// It adds the routes to the router for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index bb531c806..c3be5dc7a 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -7,8 +7,8 @@ use axum::response::Json; use super::resources::Stats; use super::responses::stats_response; -use crate::tracker::services::statistics::get_metrics; -use crate::tracker::Tracker; +use crate::core::services::statistics::get_metrics; +use crate::core::Tracker; /// It handles the request to get the tracker statistics. /// diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index 355a1e448..b241c469c 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -2,7 +2,7 @@ //! API context. use serde::{Deserialize, Serialize}; -use crate::tracker::services::statistics::TrackerMetrics; +use crate::core::services::statistics::TrackerMetrics; /// It contains all the statistics generated by the tracker. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -72,9 +72,9 @@ impl From for Stats { #[cfg(test)] mod tests { use super::Stats; - use crate::tracker::services::statistics::TrackerMetrics; - use crate::tracker::statistics::Metrics; - use crate::tracker::TorrentsMetrics; + use crate::core::services::statistics::TrackerMetrics; + use crate::core::statistics::Metrics; + use crate::core::TorrentsMetrics; #[test] fn stats_resource_should_be_converted_from_tracker_metrics() { diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index e8e7cb84d..9d03ccedf 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -3,7 +3,7 @@ use axum::response::Json; use super::resources::Stats; -use crate::tracker::services::statistics::TrackerMetrics; +use crate::core::services::statistics::TrackerMetrics; /// `200` response that contains the [`Stats`] resource as json. pub fn stats_response(tracker_metrics: TrackerMetrics) -> Json { diff --git a/src/servers/apis/v1/context/stats/routes.rs b/src/servers/apis/v1/context/stats/routes.rs index 9198562dd..d8d552697 100644 --- a/src/servers/apis/v1/context/stats/routes.rs +++ b/src/servers/apis/v1/context/stats/routes.rs @@ -9,7 +9,7 @@ use axum::routing::get; use axum::Router; use super::handlers::get_stats_handler; -use crate::tracker::Tracker; +use crate::core::Tracker; /// It adds the routes to the router for the [`stats`](crate::servers::apis::v1::context::stats) API context. pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs index 1f38ab474..101a25c8d 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/src/servers/apis/v1/context/torrent/handlers.rs @@ -11,11 +11,11 @@ use serde::{de, Deserialize, Deserializer}; use super::resources::torrent::ListItem; use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; +use crate::core::services::torrent::{get_torrent_info, get_torrents, Pagination}; +use crate::core::Tracker; use crate::servers::apis::v1::responses::invalid_info_hash_param_response; use crate::servers::apis::InfoHashParam; use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::services::torrent::{get_torrent_info, get_torrents, Pagination}; -use crate::tracker::Tracker; /// It handles the request to get the torrent data. /// diff --git a/src/servers/apis/v1/context/torrent/resources/peer.rs b/src/servers/apis/v1/context/torrent/resources/peer.rs index e0cab853e..752694393 100644 --- a/src/servers/apis/v1/context/torrent/resources/peer.rs +++ b/src/servers/apis/v1/context/torrent/resources/peer.rs @@ -1,7 +1,7 @@ //! `Peer` and Peer `Id` API resources. use serde::{Deserialize, Serialize}; -use crate::tracker; +use crate::core; /// `Peer` API resource. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -35,8 +35,8 @@ pub struct Id { pub client: Option, } -impl From for Id { - fn from(peer_id: tracker::peer::Id) -> Self { +impl From for Id { + fn from(peer_id: core::peer::Id) -> Self { Id { id: peer_id.to_hex_string(), client: peer_id.get_client_name(), @@ -44,9 +44,9 @@ impl From for Id { } } -impl From for Peer { +impl From for Peer { #[allow(deprecated)] - fn from(peer: tracker::peer::Peer) -> Self { + fn from(peer: core::peer::Peer) -> Self { Peer { peer_id: Id::from(peer.peer_id), peer_addr: peer.peer_addr.to_string(), diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs index ebebda79c..74577a23e 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; use super::peer; -use crate::tracker::services::torrent::{BasicInfo, Info}; +use crate::core::services::torrent::{BasicInfo, Info}; /// `Torrent` API resource. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -103,12 +103,12 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use super::Torrent; + use crate::core::peer; + use crate::core::services::torrent::{BasicInfo, Info}; use crate::servers::apis::v1::context::torrent::resources::peer::Peer; use crate::servers::apis::v1::context::torrent::resources::torrent::ListItem; use crate::shared::bit_torrent::info_hash::InfoHash; use crate::shared::clock::DurationSinceUnixEpoch; - use crate::tracker::peer; - use crate::tracker::services::torrent::{BasicInfo, Info}; fn sample_peer() -> peer::Peer { peer::Peer { diff --git a/src/servers/apis/v1/context/torrent/responses.rs b/src/servers/apis/v1/context/torrent/responses.rs index 99c2fcae3..5daceaf94 100644 --- a/src/servers/apis/v1/context/torrent/responses.rs +++ b/src/servers/apis/v1/context/torrent/responses.rs @@ -4,7 +4,7 @@ use axum::response::{IntoResponse, Json, Response}; use serde_json::json; use super::resources::torrent::{ListItem, Torrent}; -use crate::tracker::services::torrent::{BasicInfo, Info}; +use crate::core::services::torrent::{BasicInfo, Info}; /// `200` response that contains an array of /// [`ListItem`] diff --git a/src/servers/apis/v1/context/torrent/routes.rs b/src/servers/apis/v1/context/torrent/routes.rs index 18295f2a2..6f8c28df5 100644 --- a/src/servers/apis/v1/context/torrent/routes.rs +++ b/src/servers/apis/v1/context/torrent/routes.rs @@ -10,7 +10,7 @@ use axum::routing::get; use axum::Router; use super::handlers::{get_torrent_handler, get_torrents_handler}; -use crate::tracker::Tracker; +use crate::core::Tracker; /// It adds the routes to the router for the [`torrent`](crate::servers::apis::v1::context::torrent) API context. pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/src/servers/apis/v1/context/whitelist/handlers.rs index bd1da735e..fc32f667b 100644 --- a/src/servers/apis/v1/context/whitelist/handlers.rs +++ b/src/servers/apis/v1/context/whitelist/handlers.rs @@ -9,10 +9,10 @@ use axum::response::Response; use super::responses::{ failed_to_reload_whitelist_response, failed_to_remove_torrent_from_whitelist_response, failed_to_whitelist_torrent_response, }; +use crate::core::Tracker; use crate::servers::apis::v1::responses::{invalid_info_hash_param_response, ok_response}; use crate::servers::apis::InfoHashParam; use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::Tracker; /// It handles the request to add a torrent to the whitelist. /// diff --git a/src/servers/apis/v1/context/whitelist/routes.rs b/src/servers/apis/v1/context/whitelist/routes.rs index 65d511341..e4e85181f 100644 --- a/src/servers/apis/v1/context/whitelist/routes.rs +++ b/src/servers/apis/v1/context/whitelist/routes.rs @@ -11,7 +11,7 @@ use axum::routing::{delete, get, post}; use axum::Router; use super::handlers::{add_torrent_to_whitelist_handler, reload_whitelist_handler, remove_torrent_from_whitelist_handler}; -use crate::tracker::Tracker; +use crate::core::Tracker; /// It adds the routes to the router for the [`whitelist`](crate::servers::apis::v1::context::whitelist) API context. pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs index 74778ca14..48b795573 100644 --- a/src/servers/apis/v1/routes.rs +++ b/src/servers/apis/v1/routes.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use axum::Router; use super::context::{auth_key, stats, torrent, whitelist}; -use crate::tracker::Tracker; +use crate::core::Tracker; /// Add the routes for the v1 API. pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index e6dd808b6..10666d8a5 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -206,15 +206,15 @@ //! //! ### Scrape //! -//! The `scrape` request allows a peer to get [swarm metadata](crate::tracker::torrent::SwarmMetadata) +//! The `scrape` request allows a peer to get [swarm metadata](crate::core::torrent::SwarmMetadata) //! for multiple torrents at the same time. //! -//! The response contains the [swarm metadata](crate::tracker::torrent::SwarmMetadata) +//! The response contains the [swarm metadata](crate::core::torrent::SwarmMetadata) //! for that torrent: //! -//! - [complete](crate::tracker::torrent::SwarmMetadata::complete) -//! - [downloaded](crate::tracker::torrent::SwarmMetadata::downloaded) -//! - [incomplete](crate::tracker::torrent::SwarmMetadata::incomplete) +//! - [complete](crate::core::torrent::SwarmMetadata::complete) +//! - [downloaded](crate::core::torrent::SwarmMetadata::downloaded) +//! - [incomplete](crate::core::torrent::SwarmMetadata::incomplete) //! //! **Query parameters** //! @@ -266,7 +266,7 @@ //! Where the `files` key contains a dictionary of dictionaries. The first //! dictionary key is the `info_hash` of the torrent (`iiiiiiiiiiiiiiiiiiii` in //! the example). The second level dictionary contains the -//! [swarm metadata](crate::tracker::torrent::SwarmMetadata) for that torrent. +//! [swarm metadata](crate::core::torrent::SwarmMetadata) for that torrent. //! //! If you save the response as a file and you open it with a program that //! can handle binary data you would see: diff --git a/src/servers/http/percent_encoding.rs b/src/servers/http/percent_encoding.rs index b674f0475..472b1e724 100644 --- a/src/servers/http/percent_encoding.rs +++ b/src/servers/http/percent_encoding.rs @@ -15,8 +15,8 @@ //! - //! - //! - +use crate::core::peer::{self, IdConversionError}; use crate::shared::bit_torrent::info_hash::{ConversionError, InfoHash}; -use crate::tracker::peer::{self, IdConversionError}; /// Percent decodes a percent encoded infohash. Internally an /// [`InfoHash`] is a 20-byte array. @@ -28,7 +28,7 @@ use crate::tracker::peer::{self, IdConversionError}; /// use std::str::FromStr; /// use torrust_tracker::servers::http::percent_encoding::percent_decode_info_hash; /// use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -/// use torrust_tracker::tracker::peer; +/// use torrust_tracker::core::peer; /// /// let encoded_infohash = "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0"; /// @@ -49,7 +49,7 @@ pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result Result Result Tracker { tracker_factory(configuration::ephemeral_mode_private().into()) @@ -215,9 +215,9 @@ mod tests { use std::sync::Arc; use super::{private_tracker, sample_announce_request, sample_client_ip_sources}; + use crate::core::auth; use crate::servers::http::v1::handlers::announce::handle_announce; use crate::servers::http::v1::handlers::announce::tests::assert_error_response; - use crate::tracker::auth; #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_missing() { diff --git a/src/servers/http/v1/handlers/common/auth.rs b/src/servers/http/v1/handlers/common/auth.rs index 720ed7659..f9a7796a4 100644 --- a/src/servers/http/v1/handlers/common/auth.rs +++ b/src/servers/http/v1/handlers/common/auth.rs @@ -5,8 +5,8 @@ use std::panic::Location; use thiserror::Error; +use crate::core::auth; use crate::servers::http::v1::responses; -use crate::tracker::auth; /// Authentication error. /// diff --git a/src/servers/http/v1/handlers/mod.rs b/src/servers/http/v1/handlers/mod.rs index d7fd05838..7b3a1e7c3 100644 --- a/src/servers/http/v1/handlers/mod.rs +++ b/src/servers/http/v1/handlers/mod.rs @@ -3,7 +3,7 @@ //! Refer to the generic [HTTP server documentation](crate::servers::http) for //! more information about the HTTP tracker. use super::responses; -use crate::tracker::error::Error; +use crate::core::error::Error; pub mod announce; pub mod common; diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 58b8aa84c..298d47383 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -11,14 +11,14 @@ use axum::extract::State; use axum::response::{IntoResponse, Response}; use log::debug; +use crate::core::auth::Key; +use crate::core::{ScrapeData, Tracker}; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::extractors::scrape_request::ExtractRequest; use crate::servers::http::v1::requests::scrape::Scrape; use crate::servers::http::v1::services::peer_ip_resolver::{self, ClientIpSources}; use crate::servers::http::v1::{responses, services}; -use crate::tracker::auth::Key; -use crate::tracker::{ScrapeData, Tracker}; /// It handles the `scrape` request when the HTTP tracker is configured /// to run in `public` mode. @@ -113,12 +113,12 @@ mod tests { use torrust_tracker_test_helpers::configuration; + use crate::core::services::tracker_factory; + use crate::core::Tracker; use crate::servers::http::v1::requests::scrape::Scrape; use crate::servers::http::v1::responses; use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::services::tracker_factory; - use crate::tracker::Tracker; fn private_tracker() -> Tracker { tracker_factory(configuration::ephemeral_mode_private().into()) @@ -161,8 +161,8 @@ mod tests { use std::sync::Arc; use super::{private_tracker, sample_client_ip_sources, sample_scrape_request}; + use crate::core::{auth, ScrapeData}; use crate::servers::http::v1::handlers::scrape::handle_scrape; - use crate::tracker::{auth, ScrapeData}; #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { @@ -203,8 +203,8 @@ mod tests { use std::sync::Arc; use super::{sample_client_ip_sources, sample_scrape_request, whitelisted_tracker}; + use crate::core::ScrapeData; use crate::servers::http::v1::handlers::scrape::handle_scrape; - use crate::tracker::ScrapeData; #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() { diff --git a/src/servers/http/v1/launcher.rs b/src/servers/http/v1/launcher.rs index b5faf8d46..1ae09a5f8 100644 --- a/src/servers/http/v1/launcher.rs +++ b/src/servers/http/v1/launcher.rs @@ -11,8 +11,8 @@ use futures::future::BoxFuture; use log::info; use super::routes::router; +use crate::core::Tracker; use crate::servers::http::server::HttpServerLauncher; -use crate::tracker::Tracker; #[derive(Debug)] pub enum Error { diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index c330ca3bd..7f77f727d 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -8,11 +8,11 @@ use std::str::FromStr; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; +use crate::core::peer::{self, IdConversionError}; use crate::servers::http::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; use crate::servers::http::v1::query::{ParseQueryError, Query}; use crate::servers::http::v1::responses; use crate::shared::bit_torrent::info_hash::{ConversionError, InfoHash}; -use crate::tracker::peer::{self, IdConversionError}; /// The number of bytes `downloaded`, `uploaded` or `left`. It's used in the /// `Announce` request for parameters that represent a number of bytes. @@ -34,7 +34,7 @@ const COMPACT: &str = "compact"; /// ```rust /// use torrust_tracker::servers::http::v1::requests::announce::{Announce, Compact, Event}; /// use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -/// use torrust_tracker::tracker::peer; +/// use torrust_tracker::core::peer; /// /// let request = Announce { /// // Mandatory params @@ -355,12 +355,12 @@ mod tests { mod announce_request { + use crate::core::peer; use crate::servers::http::v1::query::Query; use crate::servers::http::v1::requests::announce::{ Announce, Compact, Event, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, PEER_ID, PORT, UPLOADED, }; use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::peer; #[test] fn should_be_instantiated_from_the_url_query_with_only_the_mandatory_params() { diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index f45f4c824..8a245476b 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -11,8 +11,8 @@ use serde::{self, Deserialize, Serialize}; use thiserror::Error; use torrust_tracker_contrib_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; +use crate::core::{self, AnnounceData}; use crate::servers::http::v1::responses; -use crate::tracker::{self, AnnounceData}; /// Normal (non compact) `announce` response. /// @@ -125,8 +125,8 @@ impl Peer { } } -impl From for Peer { - fn from(peer: tracker::peer::Peer) -> Self { +impl From for Peer { + fn from(peer: core::peer::Peer) -> Self { Peer { peer_id: peer.peer_id.to_bytes(), ip: peer.peer_addr.ip(), @@ -312,8 +312,8 @@ impl CompactPeer { } } -impl From for CompactPeer { - fn from(peer: tracker::peer::Peer) -> Self { +impl From for CompactPeer { + fn from(peer: core::peer::Peer) -> Self { CompactPeer { ip: peer.peer_addr.ip(), port: peer.peer_addr.port(), diff --git a/src/servers/http/v1/responses/scrape.rs b/src/servers/http/v1/responses/scrape.rs index 9cd88b9ab..e16827824 100644 --- a/src/servers/http/v1/responses/scrape.rs +++ b/src/servers/http/v1/responses/scrape.rs @@ -7,15 +7,15 @@ use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use torrust_tracker_contrib_bencode::{ben_int, ben_map, BMutAccess}; -use crate::tracker::ScrapeData; +use crate::core::ScrapeData; /// The `Scrape` response for the HTTP tracker. /// /// ```rust /// use torrust_tracker::servers::http::v1::responses::scrape::Bencoded; /// use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -/// use torrust_tracker::tracker::torrent::SwarmMetadata; -/// use torrust_tracker::tracker::ScrapeData; +/// use torrust_tracker::core::torrent::SwarmMetadata; +/// use torrust_tracker::core::ScrapeData; /// /// let info_hash = InfoHash([0x69; 20]); /// let mut scrape_data = ScrapeData::empty(); @@ -92,10 +92,10 @@ impl IntoResponse for Bencoded { mod tests { mod scrape_response { + use crate::core::torrent::SwarmMetadata; + use crate::core::ScrapeData; use crate::servers::http::v1::responses::scrape::Bencoded; use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::tracker::torrent::SwarmMetadata; - use crate::tracker::ScrapeData; fn sample_scrape_data() -> ScrapeData { let info_hash = InfoHash([0x69; 20]); diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 0b6b419c1..20e96d7fd 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -7,7 +7,7 @@ use axum_client_ip::SecureClientIpSource; use tower_http::compression::CompressionLayer; use super::handlers::{announce, health_check, scrape}; -use crate::tracker::Tracker; +use crate::core::Tracker; /// It adds the routes to the router. /// diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index ddb3b1221..bdf8afc87 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -2,7 +2,7 @@ //! //! The service is responsible for handling the `announce` requests. //! -//! It delegates the `announce` logic to the [`Tracker`](crate::tracker::Tracker::announce) +//! It delegates the `announce` logic to the [`Tracker`](crate::core::Tracker::announce) //! and it returns the [`AnnounceData`] returned //! by the [`Tracker`]. //! @@ -11,9 +11,9 @@ use std::net::IpAddr; use std::sync::Arc; +use crate::core::peer::Peer; +use crate::core::{statistics, AnnounceData, Tracker}; use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::peer::Peer; -use crate::tracker::{statistics, AnnounceData, Tracker}; /// The HTTP tracker `announce` service. /// @@ -50,10 +50,10 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; + use crate::core::services::tracker_factory; + use crate::core::{peer, Tracker}; use crate::shared::bit_torrent::info_hash::InfoHash; use crate::shared::clock::DurationSinceUnixEpoch; - use crate::tracker::services::tracker_factory; - use crate::tracker::{peer, Tracker}; fn public_tracker() -> Tracker { tracker_factory(configuration::ephemeral_mode_public().into()) @@ -97,11 +97,11 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; + use crate::core::peer::Peer; + use crate::core::torrent::SwarmStats; + use crate::core::{statistics, AnnounceData, Tracker}; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; - use crate::tracker::peer::Peer; - use crate::tracker::torrent::SwarmStats; - use crate::tracker::{statistics, AnnounceData, Tracker}; #[tokio::test] async fn it_should_return_the_announce_data() { diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index adea28086..c2fa104de 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -2,7 +2,7 @@ //! //! The service is responsible for handling the `scrape` requests. //! -//! It delegates the `scrape` logic to the [`Tracker`](crate::tracker::Tracker::scrape) +//! It delegates the `scrape` logic to the [`Tracker`](crate::core::Tracker::scrape) //! and it returns the [`ScrapeData`] returned //! by the [`Tracker`]. //! @@ -11,8 +11,8 @@ use std::net::IpAddr; use std::sync::Arc; +use crate::core::{statistics, ScrapeData, Tracker}; use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::{statistics, ScrapeData, Tracker}; /// The HTTP tracker `scrape` service. /// @@ -63,10 +63,10 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; + use crate::core::services::tracker_factory; + use crate::core::{peer, Tracker}; use crate::shared::bit_torrent::info_hash::InfoHash; use crate::shared::clock::DurationSinceUnixEpoch; - use crate::tracker::services::tracker_factory; - use crate::tracker::{peer, Tracker}; fn public_tracker() -> Tracker { tracker_factory(configuration::ephemeral_mode_public().into()) @@ -101,12 +101,12 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_test_helpers::configuration; + use crate::core::torrent::SwarmMetadata; + use crate::core::{statistics, ScrapeData, Tracker}; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ public_tracker, sample_info_hash, sample_info_hashes, sample_peer, }; - use crate::tracker::torrent::SwarmMetadata; - use crate::tracker::{statistics, ScrapeData, Tracker}; #[tokio::test] async fn it_should_return_the_scrape_data_for_a_torrent() { @@ -193,11 +193,11 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_test_helpers::configuration; + use crate::core::{statistics, ScrapeData, Tracker}; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ public_tracker, sample_info_hash, sample_info_hashes, sample_peer, }; - use crate::tracker::{statistics, ScrapeData, Tracker}; #[tokio::test] async fn it_should_always_return_the_zeroed_scrape_data_for_a_torrent() { diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 64d60e549..1878c30e1 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -10,12 +10,12 @@ use aquatic_udp_protocol::{ use log::debug; use super::connection_cookie::{check, from_connection_id, into_connection_id, make}; +use crate::core::{statistics, Tracker}; use crate::servers::udp::error::Error; use crate::servers::udp::peer_builder; use crate::servers::udp::request::AnnounceWrapper; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::tracker::{statistics, Tracker}; /// It handles the incoming UDP packets. /// @@ -283,9 +283,9 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; + use crate::core::services::tracker_factory; + use crate::core::{peer, Tracker}; use crate::shared::clock::{Current, Time}; - use crate::tracker::services::tracker_factory; - use crate::tracker::{peer, Tracker}; fn tracker_configuration() -> Arc { Arc::new(default_testing_tracker_configuration()) @@ -396,10 +396,10 @@ mod tests { use mockall::predicate::eq; use super::{sample_ipv4_socket_address, sample_ipv6_remote_addr, tracker_configuration}; + use crate::core::{self, statistics}; use crate::servers::udp::connection_cookie::{into_connection_id, make}; use crate::servers::udp::handlers::handle_connect; use crate::servers::udp::handlers::tests::{public_tracker, sample_ipv4_remote_addr}; - use crate::tracker::{self, statistics}; fn sample_connect_request() -> ConnectRequest { ConnectRequest { @@ -457,9 +457,8 @@ mod tests { let client_socket_address = sample_ipv4_socket_address(); - let torrent_tracker = Arc::new( - tracker::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), - ); + let torrent_tracker = + Arc::new(core::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); handle_connect(client_socket_address, &sample_connect_request(), &torrent_tracker) .await .unwrap(); @@ -475,9 +474,8 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let torrent_tracker = Arc::new( - tracker::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), - ); + let torrent_tracker = + Arc::new(core::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); handle_connect(sample_ipv6_remote_addr(), &sample_connect_request(), &torrent_tracker) .await .unwrap(); @@ -567,13 +565,13 @@ mod tests { }; use mockall::predicate::eq; + use crate::core::{self, peer, statistics}; use crate::servers::udp::connection_cookie::{into_connection_id, make}; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ public_tracker, sample_ipv4_socket_address, tracker_configuration, TorrentPeerBuilder, }; - use crate::tracker::{self, peer, statistics}; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { @@ -662,7 +660,7 @@ mod tests { assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); } - async fn add_a_torrent_peer_using_ipv6(tracker: Arc) { + async fn add_a_torrent_peer_using_ipv6(tracker: Arc) { let info_hash = AquaticInfoHash([0u8; 20]); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); @@ -680,7 +678,7 @@ mod tests { .await; } - async fn announce_a_new_peer_using_ipv4(tracker: Arc) -> Response { + async fn announce_a_new_peer_using_ipv4(tracker: Arc) -> Response { let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let request = AnnounceRequestBuilder::default() .with_connection_id(into_connection_id(&make(&remote_addr))) @@ -717,7 +715,7 @@ mod tests { let stats_event_sender = Box::new(stats_event_sender_mock); let tracker = Arc::new( - tracker::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), ); handle_announce( @@ -734,11 +732,11 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; + use crate::core::peer; use crate::servers::udp::connection_cookie::{into_connection_id, make}; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{public_tracker, TorrentPeerBuilder}; - use crate::tracker::peer; #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { @@ -788,13 +786,13 @@ mod tests { }; use mockall::predicate::eq; + use crate::core::{self, peer, statistics}; use crate::servers::udp::connection_cookie::{into_connection_id, make}; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ public_tracker, sample_ipv6_remote_addr, tracker_configuration, TorrentPeerBuilder, }; - use crate::tracker::{self, peer, statistics}; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { @@ -888,7 +886,7 @@ mod tests { assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); } - async fn add_a_torrent_peer_using_ipv4(tracker: Arc) { + async fn add_a_torrent_peer_using_ipv4(tracker: Arc) { let info_hash = AquaticInfoHash([0u8; 20]); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); @@ -905,7 +903,7 @@ mod tests { .await; } - async fn announce_a_new_peer_using_ipv6(tracker: Arc) -> Response { + async fn announce_a_new_peer_using_ipv6(tracker: Arc) -> Response { let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); let client_port = 8080; @@ -945,7 +943,7 @@ mod tests { let stats_event_sender = Box::new(stats_event_sender_mock); let tracker = Arc::new( - tracker::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), ); let remote_addr = sample_ipv6_remote_addr(); @@ -963,19 +961,19 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; + use crate::core; + use crate::core::statistics::Keeper; use crate::servers::udp::connection_cookie::{into_connection_id, make}; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::TrackerConfigurationBuilder; - use crate::tracker; - use crate::tracker::statistics::Keeper; #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let configuration = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); let (stats_event_sender, stats_repository) = Keeper::new_active_instance(); let tracker = - Arc::new(tracker::Tracker::new(configuration, Some(stats_event_sender), stats_repository).unwrap()); + Arc::new(core::Tracker::new(configuration, Some(stats_event_sender), stats_repository).unwrap()); let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); @@ -1025,10 +1023,10 @@ mod tests { }; use super::TorrentPeerBuilder; + use crate::core::{self, peer}; use crate::servers::udp::connection_cookie::{into_connection_id, make}; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{public_tracker, sample_ipv4_remote_addr}; - use crate::tracker::{self, peer}; fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { TorrentScrapeStatistics { @@ -1064,7 +1062,7 @@ mod tests { ); } - async fn add_a_seeder(tracker: Arc, remote_addr: &SocketAddr, info_hash: &InfoHash) { + async fn add_a_seeder(tracker: Arc, remote_addr: &SocketAddr, info_hash: &InfoHash) { let peer_id = peer::Id([255u8; 20]); let peer = TorrentPeerBuilder::default() @@ -1088,7 +1086,7 @@ mod tests { } } - async fn add_a_sample_seeder_and_scrape(tracker: Arc) -> Response { + async fn add_a_sample_seeder_and_scrape(tracker: Arc) -> Response { let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -1237,9 +1235,9 @@ mod tests { use mockall::predicate::eq; use super::sample_scrape_request; + use crate::core::{self, statistics}; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{sample_ipv4_remote_addr, tracker_configuration}; - use crate::tracker::{self, statistics}; #[tokio::test] async fn should_send_the_upd4_scrape_event() { @@ -1253,7 +1251,7 @@ mod tests { let remote_addr = sample_ipv4_remote_addr(); let tracker = Arc::new( - tracker::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), ); handle_scrape(remote_addr, &sample_scrape_request(&remote_addr), &tracker) @@ -1269,9 +1267,9 @@ mod tests { use mockall::predicate::eq; use super::sample_scrape_request; + use crate::core::{self, statistics}; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{sample_ipv6_remote_addr, tracker_configuration}; - use crate::tracker::{self, statistics}; #[tokio::test] async fn should_send_the_upd6_scrape_event() { @@ -1285,7 +1283,7 @@ mod tests { let remote_addr = sample_ipv6_remote_addr(); let tracker = Arc::new( - tracker::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), ); handle_scrape(remote_addr, &sample_scrape_request(&remote_addr), &tracker) diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index a50fffd37..985c1cec7 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -53,7 +53,7 @@ //! supports only three types of requests: `Connect`, `Announce` and `Scrape`. //! //! Request are parsed from UDP packets using the [`aquatic_udp_protocol`](https://crates.io/crates/aquatic_udp_protocol) -//! crate and then handled by the [`Tracker`](crate::tracker::Tracker) struct. +//! crate and then handled by the [`Tracker`](crate::core::Tracker) struct. //! And then the response is also build using the [`aquatic_udp_protocol`](https://crates.io/crates/aquatic_udp_protocol) //! and converted to a UDP packet. //! @@ -467,15 +467,15 @@ //! //! ### Scrape //! -//! The `scrape` request allows a peer to get [swarm metadata](crate::tracker::torrent::SwarmMetadata) +//! The `scrape` request allows a peer to get [swarm metadata](crate::core::torrent::SwarmMetadata) //! for multiple torrents at the same time. //! -//! The response contains the [swarm metadata](crate::tracker::torrent::SwarmMetadata) +//! The response contains the [swarm metadata](crate::core::torrent::SwarmMetadata) //! for that torrent: //! -//! - [complete](crate::tracker::torrent::SwarmMetadata::complete) -//! - [downloaded](crate::tracker::torrent::SwarmMetadata::downloaded) -//! - [incomplete](crate::tracker::torrent::SwarmMetadata::incomplete) +//! - [complete](crate::core::torrent::SwarmMetadata::complete) +//! - [downloaded](crate::core::torrent::SwarmMetadata::downloaded) +//! - [incomplete](crate::core::torrent::SwarmMetadata::incomplete) //! //! > **NOTICE**: up to about 74 torrents can be scraped at once. A full scrape //! can't be done with this protocol. This is a limitation of the UDP protocol. diff --git a/src/servers/udp/peer_builder.rs b/src/servers/udp/peer_builder.rs index 7c83089bb..5168e2578 100644 --- a/src/servers/udp/peer_builder.rs +++ b/src/servers/udp/peer_builder.rs @@ -2,8 +2,8 @@ use std::net::{IpAddr, SocketAddr}; use super::request::AnnounceWrapper; +use crate::core::peer::{Id, Peer}; use crate::shared::clock::{Current, Time}; -use crate::tracker::peer::{Id, Peer}; /// Extracts the [`Peer`] info from the /// announce request. diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 31e87481e..c6b73860b 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -28,10 +28,10 @@ use log::{debug, error, info}; use tokio::net::UdpSocket; use tokio::task::JoinHandle; +use crate::core::Tracker; use crate::servers::signals::shutdown_signal; use crate::servers::udp::handlers::handle_packet; use crate::shared::bit_torrent::udp::MAX_PACKET_SIZE; -use crate::tracker::Tracker; /// Error that can occur when starting or stopping the UDP server. /// diff --git a/src/shared/bit_torrent/common.rs b/src/shared/bit_torrent/common.rs index fd52e098c..0ce345a3e 100644 --- a/src/shared/bit_torrent/common.rs +++ b/src/shared/bit_torrent/common.rs @@ -20,8 +20,8 @@ pub const MAX_SCRAPE_TORRENTS: u8 = 74; /// HTTP tracker authentication key length. /// -/// See function to [`generate`](crate::tracker::auth::generate) the -/// [`ExpiringKeys`](crate::tracker::auth::ExpiringKey) for more information. +/// See function to [`generate`](crate::core::auth::generate) the +/// [`ExpiringKeys`](crate::core::auth::ExpiringKey) for more information. pub const AUTH_KEY_LENGTH: usize = 32; #[repr(u32)] diff --git a/tests/common/app.rs b/tests/common/app.rs index ee3fba064..1b735bc86 100644 --- a/tests/common/app.rs +++ b/tests/common/app.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use torrust_tracker::bootstrap; -use torrust_tracker::tracker::Tracker; +use torrust_tracker::core::Tracker; pub fn setup_with_configuration(configuration: &Arc) -> Arc { bootstrap::app::initialize_with_configuration(configuration) diff --git a/tests/common/fixtures.rs b/tests/common/fixtures.rs index 7062c8376..9fd328d5d 100644 --- a/tests/common/fixtures.rs +++ b/tests/common/fixtures.rs @@ -1,8 +1,8 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use torrust_tracker::core::peer::{self, Id, Peer}; use torrust_tracker::shared::clock::DurationSinceUnixEpoch; -use torrust_tracker::tracker::peer::{self, Id, Peer}; pub struct PeerBuilder { peer: Peer, diff --git a/tests/servers/api/mod.rs b/tests/servers/api/mod.rs index 7022da9b4..155ac0de1 100644 --- a/tests/servers/api/mod.rs +++ b/tests/servers/api/mod.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use torrust_tracker::tracker::Tracker; +use torrust_tracker::core::Tracker; pub mod connection_info; pub mod test_environment; diff --git a/tests/servers/api/test_environment.rs b/tests/servers/api/test_environment.rs index dbb23dcfa..0501d9c56 100644 --- a/tests/servers/api/test_environment.rs +++ b/tests/servers/api/test_environment.rs @@ -1,9 +1,9 @@ use std::sync::Arc; +use torrust_tracker::core::peer::Peer; +use torrust_tracker::core::Tracker; use torrust_tracker::servers::apis::server::{ApiServer, RunningApiServer, StoppedApiServer}; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker::tracker::peer::Peer; -use torrust_tracker::tracker::Tracker; use super::connection_info::ConnectionInfo; use crate::common::app::setup_with_configuration; diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index a99272e84..4c59b4e95 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -1,6 +1,6 @@ use std::time::Duration; -use torrust_tracker::tracker::auth::Key; +use torrust_tracker::core::auth::Key; use torrust_tracker_test_helpers::configuration; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; diff --git a/tests/servers/http/client.rs b/tests/servers/http/client.rs index 03ed9aee4..288987c55 100644 --- a/tests/servers/http/client.rs +++ b/tests/servers/http/client.rs @@ -1,7 +1,7 @@ use std::net::IpAddr; use reqwest::{Client as ReqwestClient, Response}; -use torrust_tracker::tracker::auth::Key; +use torrust_tracker::core::auth::Key; use super::requests::announce::{self, Query}; use super::requests::scrape; diff --git a/tests/servers/http/connection_info.rs b/tests/servers/http/connection_info.rs index 5736271fd..f4081d60e 100644 --- a/tests/servers/http/connection_info.rs +++ b/tests/servers/http/connection_info.rs @@ -1,4 +1,4 @@ -use torrust_tracker::tracker::auth::Key; +use torrust_tracker::core::auth::Key; #[derive(Clone, Debug)] pub struct ConnectionInfo { diff --git a/tests/servers/http/requests/announce.rs b/tests/servers/http/requests/announce.rs index f7f25da3e..2cc615d0f 100644 --- a/tests/servers/http/requests/announce.rs +++ b/tests/servers/http/requests/announce.rs @@ -3,8 +3,8 @@ use std::net::{IpAddr, Ipv4Addr}; use std::str::FromStr; use serde_repr::Serialize_repr; +use torrust_tracker::core::peer::Id; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker::tracker::peer::Id; use crate::servers::http::{percent_encode_byte_array, ByteArray20}; diff --git a/tests/servers/http/responses/announce.rs b/tests/servers/http/responses/announce.rs index 8a07ebd5e..a57b41c78 100644 --- a/tests/servers/http/responses/announce.rs +++ b/tests/servers/http/responses/announce.rs @@ -1,7 +1,7 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use serde::{self, Deserialize, Serialize}; -use torrust_tracker::tracker::peer::Peer; +use torrust_tracker::core::peer::Peer; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Announce { diff --git a/tests/servers/http/test_environment.rs b/tests/servers/http/test_environment.rs index 8d0aaba02..e24e1b9a5 100644 --- a/tests/servers/http/test_environment.rs +++ b/tests/servers/http/test_environment.rs @@ -1,9 +1,9 @@ use std::sync::Arc; +use torrust_tracker::core::peer::Peer; +use torrust_tracker::core::Tracker; use torrust_tracker::servers::http::server::{HttpServer, HttpServerLauncher, RunningHttpServer, StoppedHttpServer}; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker::tracker::peer::Peer; -use torrust_tracker::tracker::Tracker; use crate::common::app::setup_with_configuration; diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index b19009454..d7f4d50cc 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -93,8 +93,8 @@ mod for_all_config_modes { use local_ip_address::local_ip; use reqwest::Response; use tokio::net::TcpListener; + use torrust_tracker::core::peer; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - use torrust_tracker::tracker::peer; use torrust_tracker_test_helpers::configuration; use crate::common::fixtures::{invalid_info_hashes, PeerBuilder}; @@ -869,8 +869,8 @@ mod for_all_config_modes { use std::str::FromStr; use tokio::net::TcpListener; + use torrust_tracker::core::peer; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - use torrust_tracker::tracker::peer; use torrust_tracker_test_helpers::configuration; use crate::common::fixtures::{invalid_info_hashes, PeerBuilder}; @@ -1147,8 +1147,8 @@ mod configured_as_whitelisted { mod receiving_an_scrape_request { use std::str::FromStr; + use torrust_tracker::core::peer; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - use torrust_tracker::tracker::peer; use torrust_tracker_test_helpers::configuration; use crate::common::fixtures::PeerBuilder; @@ -1244,8 +1244,8 @@ mod configured_as_private { use std::str::FromStr; use std::time::Duration; + use torrust_tracker::core::auth::Key; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - use torrust_tracker::tracker::auth::Key; use torrust_tracker_test_helpers::configuration; use crate::servers::http::asserts::{assert_authentication_error_response, assert_is_announce_response}; @@ -1321,9 +1321,9 @@ mod configured_as_private { use std::str::FromStr; use std::time::Duration; + use torrust_tracker::core::auth::Key; + use torrust_tracker::core::peer; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - use torrust_tracker::tracker::auth::Key; - use torrust_tracker::tracker::peer; use torrust_tracker_test_helpers::configuration; use crate::common::fixtures::PeerBuilder; diff --git a/tests/servers/udp/test_environment.rs b/tests/servers/udp/test_environment.rs index 15266d881..dfe19ac86 100644 --- a/tests/servers/udp/test_environment.rs +++ b/tests/servers/udp/test_environment.rs @@ -1,10 +1,10 @@ use std::net::SocketAddr; use std::sync::Arc; +use torrust_tracker::core::peer::Peer; +use torrust_tracker::core::Tracker; use torrust_tracker::servers::udp::server::{RunningUdpServer, StoppedUdpServer, UdpServer}; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker::tracker::peer::Peer; -use torrust_tracker::tracker::Tracker; use crate::common::app::setup_with_configuration; From 985633e17c0ac341bca72b0fe78c30a64bf97394 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 14 Dec 2023 09:45:03 +0000 Subject: [PATCH 0148/1297] feat!: [#537] move API healthcheck endpoint From: `GET /health_check` To: `GET /api/health_check` To avoid collission with HTTP Tracker health check enpoint when the API and the HTTP Tracker are using the same domain+port. For example: - API: https://tracker.com:443/api/ - HTTP tracker: https://tracker.com:443/ Old health check endpoints: - API: https://tracker.com:443/health_check - HTTP tracker: https://tracker.com:443/health_check New API health check endpoint: - API: https://tracker.com:443/api/health_check - HTTP tracker: https://tracker.com:443/health_check --- src/bin/http_health_check.rs | 2 +- src/servers/apis/routes.rs | 2 +- src/servers/apis/v1/context/health_check/mod.rs | 4 ++-- src/servers/apis/v1/routes.rs | 2 ++ src/servers/health_check_api/handlers.rs | 2 +- tests/servers/api/v1/contract/context/health_check.rs | 2 +- 6 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/bin/http_health_check.rs b/src/bin/http_health_check.rs index 313f44045..d3f1767cb 100644 --- a/src/bin/http_health_check.rs +++ b/src/bin/http_health_check.rs @@ -11,7 +11,7 @@ async fn main() { let args: Vec = env::args().collect(); if args.len() != 2 { eprintln!("Usage: cargo run --bin http_health_check "); - eprintln!("Example: cargo run --bin http_health_check http://127.0.0.1:1212/health_check"); + eprintln!("Example: cargo run --bin http_health_check http://127.0.0.1:1212/api/health_check"); std::process::exit(1); } diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 49f263db3..fef412f91 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -29,6 +29,6 @@ pub fn router(tracker: Arc) -> Router { tracker.config.clone(), v1::middlewares::auth::auth, )) - .route("/health_check", get(health_check_handler)) + .route(&format!("{api_url_prefix}/health_check"), get(health_check_handler)) .layer(CompressionLayer::new()) } diff --git a/src/servers/apis/v1/context/health_check/mod.rs b/src/servers/apis/v1/context/health_check/mod.rs index c62c5e97b..b73849511 100644 --- a/src/servers/apis/v1/context/health_check/mod.rs +++ b/src/servers/apis/v1/context/health_check/mod.rs @@ -8,14 +8,14 @@ //! //! # Health Check //! -//! `GET /health_check` +//! `GET /api/health_check` //! //! Returns the API status. //! //! **Example request** //! //! ```bash -//! curl "http://127.0.0.1:1212/health_check" +//! curl "http://127.0.0.1:1212/api/health_check" //! ``` //! //! **Example response** `200` diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs index 48b795573..3786b3532 100644 --- a/src/servers/apis/v1/routes.rs +++ b/src/servers/apis/v1/routes.rs @@ -9,8 +9,10 @@ use crate::core::Tracker; /// Add the routes for the v1 API. pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { let v1_prefix = format!("{prefix}/v1"); + let router = auth_key::routes::add(&v1_prefix, router, tracker.clone()); let router = stats::routes::add(&v1_prefix, router, tracker.clone()); let router = whitelist::routes::add(&v1_prefix, router, tracker.clone()); + torrent::routes::add(&v1_prefix, router, tracker) } diff --git a/src/servers/health_check_api/handlers.rs b/src/servers/health_check_api/handlers.rs index 109b89bb4..2f47c8607 100644 --- a/src/servers/health_check_api/handlers.rs +++ b/src/servers/health_check_api/handlers.rs @@ -45,7 +45,7 @@ async fn api_health_check(config: &HttpApi) -> Option> { let addr: SocketAddr = config.bind_address.parse().expect("invalid socket address for API"); if addr.port() != UNKNOWN_PORT { - let health_check_url = format!("http://{addr}/health_check"); + let health_check_url = format!("http://{addr}/api/health_check"); if !get_req_is_ok(&health_check_url).await { return Some(responses::error(format!( diff --git a/tests/servers/api/v1/contract/context/health_check.rs b/tests/servers/api/v1/contract/context/health_check.rs index 3b6c98374..108ae237a 100644 --- a/tests/servers/api/v1/contract/context/health_check.rs +++ b/tests/servers/api/v1/contract/context/health_check.rs @@ -8,7 +8,7 @@ use crate::servers::api::v1::client::get; async fn health_check_endpoint_should_return_status_ok_if_api_is_running() { let test_env = running_test_environment(configuration::ephemeral()).await; - let url = format!("http://{}/health_check", test_env.get_connection_info().bind_address); + let url = format!("http://{}/api/health_check", test_env.get_connection_info().bind_address); let response = get(&url, None).await; From 6087e4fa1e16e9a00a61aee470897335812b387c Mon Sep 17 00:00:00 2001 From: Warm Beer Date: Sat, 16 Dec 2023 17:21:11 +0000 Subject: [PATCH 0149/1297] feat: added benchmarking binary for torrent repository --- Cargo.lock | 97 ++++++ Cargo.toml | 6 +- .../torrent-repository-benchmarks/Cargo.toml | 21 ++ .../torrent-repository-benchmarks/src/args.rs | 15 + .../src/benches/asyn.rs | 176 ++++++++++ .../src/benches/mod.rs | 3 + .../src/benches/sync.rs | 166 ++++++++++ .../src/benches/utils.rs | 73 +++++ .../torrent-repository-benchmarks/src/lib.rs | 2 + .../torrent-repository-benchmarks/src/main.rs | 139 ++++++++ src/core/mod.rs | 133 ++++---- src/core/services/torrent.rs | 33 +- src/core/{torrent.rs => torrent/mod.rs} | 2 + src/core/torrent/repository.rs | 301 ++++++++++++++++++ tests/wrk_benchmark_announce.lua | 64 ++-- 15 files changed, 1110 insertions(+), 121 deletions(-) create mode 100644 packages/torrent-repository-benchmarks/Cargo.toml create mode 100644 packages/torrent-repository-benchmarks/src/args.rs create mode 100644 packages/torrent-repository-benchmarks/src/benches/asyn.rs create mode 100644 packages/torrent-repository-benchmarks/src/benches/mod.rs create mode 100644 packages/torrent-repository-benchmarks/src/benches/sync.rs create mode 100644 packages/torrent-repository-benchmarks/src/benches/utils.rs create mode 100644 packages/torrent-repository-benchmarks/src/lib.rs create mode 100644 packages/torrent-repository-benchmarks/src/main.rs rename src/core/{torrent.rs => torrent/mod.rs} (99%) create mode 100644 src/core/torrent/repository.rs diff --git a/Cargo.lock b/Cargo.lock index 30a961b14..4e3bb2f62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -91,12 +91,54 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" +[[package]] +name = "anstream" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab91ebe16eb252986481c5b62f6098f3b698a45e34b5b98200cf20dd2484a44" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "utf8parse", +] + [[package]] name = "anstyle" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87" +[[package]] +name = "anstyle-parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "317b9a89c1868f5ea6ff1d9539a69f45dffc21ce321ac1fd1160dfa48c8e2140" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b" +dependencies = [ + "windows-sys 0.48.0", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0699d10d2f4d628a98ee7b57b289abbc98ff3bad977cb3152709d4bf2330628" +dependencies = [ + "anstyle", + "windows-sys 0.48.0", +] + [[package]] name = "aquatic_udp_protocol" version = "0.8.0" @@ -160,6 +202,7 @@ checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf" dependencies = [ "async-trait", "axum-core", + "axum-macros", "bitflags 1.3.2", "bytes", "futures-util", @@ -212,6 +255,18 @@ dependencies = [ "tower-service", ] +[[package]] +name = "axum-macros" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdca6a10ecad987bda04e95606ef85a5417dcaac1a78455242d72e031e2b6b62" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.39", +] + [[package]] name = "axum-server" version = "0.5.1" @@ -515,6 +570,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41fffed7514f420abec6d183b1d3acfd9099c79c3a10a06ade4f8203f1411272" dependencies = [ "clap_builder", + "clap_derive", ] [[package]] @@ -523,8 +579,22 @@ version = "4.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63361bae7eef3771745f02d8d892bec2fee5f6e34af316ba556e7f97a7069ff1" dependencies = [ + "anstream", "anstyle", "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf9804afaaf59a91e75b022a30fb7229a7901f60c755489cc61c9b423b836442" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.39", ] [[package]] @@ -542,6 +612,12 @@ dependencies = [ "cc", ] +[[package]] +name = "colorchoice" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" + [[package]] name = "config" version = "0.13.4" @@ -612,6 +688,7 @@ dependencies = [ "ciborium", "clap", "criterion-plot", + "futures", "is-terminal", "itertools", "num-traits", @@ -624,6 +701,7 @@ dependencies = [ "serde_derive", "serde_json", "tinytemplate", + "tokio", "walkdir", ] @@ -3253,6 +3331,17 @@ dependencies = [ "winnow", ] +[[package]] +name = "torrust-torrent-repository-benchmarks" +version = "3.0.0-alpha.12-develop" +dependencies = [ + "aquatic_udp_protocol", + "clap", + "futures", + "tokio", + "torrust-tracker", +] + [[package]] name = "torrust-tracker" version = "3.0.0-alpha.12-develop" @@ -3265,6 +3354,7 @@ dependencies = [ "binascii", "chrono", "config", + "criterion", "derive_more", "fern", "futures", @@ -3274,6 +3364,7 @@ dependencies = [ "log", "mockall", "multimap", + "once_cell", "openssl", "percent-encoding", "r2d2", @@ -3486,6 +3577,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "utf8parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" + [[package]] name = "uuid" version = "1.6.1" diff --git a/Cargo.toml b/Cargo.toml index 5f55c6c5c..4f2abd6f5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,7 @@ version = "3.0.0-alpha.12-develop" [dependencies] aquatic_udp_protocol = "0" async-trait = "0" -axum = "0.6" +axum = { version = "0.6", features = ["macros"] } axum-client-ip = "0.4" axum-server = { version = "0", features = ["tls-rustls"] } binascii = "0" @@ -68,8 +68,10 @@ tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } [dev-dependencies] +criterion = { version = "0.5.1", features = ["async_tokio"] } local-ip-address = "0" mockall = "0" +once_cell = "1.18.0" reqwest = { version = "0", features = ["json"] } serde_bytes = "0" serde_repr = "0" @@ -77,7 +79,7 @@ serde_urlencoded = "0" torrust-tracker-test-helpers = { version = "3.0.0-alpha.12-develop", path = "packages/test-helpers" } [workspace] -members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] +members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers", "packages/torrent-repository-benchmarks"] [profile.dev] debug = 1 diff --git a/packages/torrent-repository-benchmarks/Cargo.toml b/packages/torrent-repository-benchmarks/Cargo.toml new file mode 100644 index 000000000..da9aba621 --- /dev/null +++ b/packages/torrent-repository-benchmarks/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "torrust-torrent-repository-benchmarks" +authors.workspace = true +categories.workspace = true +description.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0.8.0" +clap = { version = "4.4.8", features = ["derive"] } +futures = "0.3.29" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker = { path = "../../" } \ No newline at end of file diff --git a/packages/torrent-repository-benchmarks/src/args.rs b/packages/torrent-repository-benchmarks/src/args.rs new file mode 100644 index 000000000..3a38c55a7 --- /dev/null +++ b/packages/torrent-repository-benchmarks/src/args.rs @@ -0,0 +1,15 @@ +use clap::Parser; + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +pub struct Args { + /// Amount of benchmark worker threads + #[arg(short, long)] + pub threads: usize, + /// Amount of time in ns a thread will sleep to simulate a client response after handling a task + #[arg(short, long)] + pub sleep: Option, + /// Compare with old implementations of the torrent repository + #[arg(short, long)] + pub compare: Option, +} diff --git a/packages/torrent-repository-benchmarks/src/benches/asyn.rs b/packages/torrent-repository-benchmarks/src/benches/asyn.rs new file mode 100644 index 000000000..33f9e85fa --- /dev/null +++ b/packages/torrent-repository-benchmarks/src/benches/asyn.rs @@ -0,0 +1,176 @@ +use std::sync::Arc; +use std::time::Duration; + +use clap::Parser; +use futures::stream::FuturesUnordered; +use torrust_tracker::core::torrent::repository::TRepositoryAsync; +use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; + +use crate::args::Args; +use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; + +pub async fn async_add_one_torrent(samples: usize) -> (Duration, Duration) { + let mut results: Vec = Vec::with_capacity(samples); + + for _ in 0..samples { + let torrent_repository = Arc::new(T::new()); + + let info_hash = InfoHash([0; 20]); + + let start_time = std::time::Instant::now(); + + torrent_repository + .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) + .await; + + let result = start_time.elapsed(); + + results.push(result); + } + + get_average_and_adjusted_average_from_results(results) +} + +// Add one torrent ten thousand times in parallel (depending on the set worker threads) +pub async fn async_update_one_torrent_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: usize, +) -> (Duration, Duration) { + let args = Args::parse(); + let mut results: Vec = Vec::with_capacity(samples); + + for _ in 0..samples { + let torrent_repository = Arc::new(T::new()); + let info_hash: &'static InfoHash = &InfoHash([0; 20]); + let handles = FuturesUnordered::new(); + + // Add the torrent/peer to the torrent repository + torrent_repository + .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) + .await; + + let start_time = std::time::Instant::now(); + + for _ in 0..10_000 { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone + .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) + .await; + + if let Some(sleep_time) = args.sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + let result = start_time.elapsed(); + + results.push(result); + } + + get_average_and_adjusted_average_from_results(results) +} + +// Add ten thousand torrents in parallel (depending on the set worker threads) +pub async fn async_add_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: usize, +) -> (Duration, Duration) { + let args = Args::parse(); + let mut results: Vec = Vec::with_capacity(samples); + + for _ in 0..samples { + let torrent_repository = Arc::new(T::new()); + let info_hashes = generate_unique_info_hashes(10_000); + let handles = FuturesUnordered::new(); + + let start_time = std::time::Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone + .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) + .await; + + if let Some(sleep_time) = args.sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + let result = start_time.elapsed(); + + results.push(result); + } + + get_average_and_adjusted_average_from_results(results) +} + +// Async update ten thousand torrents in parallel (depending on the set worker threads) +pub async fn async_update_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: usize, +) -> (Duration, Duration) { + let args = Args::parse(); + let mut results: Vec = Vec::with_capacity(samples); + + for _ in 0..samples { + let torrent_repository = Arc::new(T::new()); + let info_hashes = generate_unique_info_hashes(10_000); + let handles = FuturesUnordered::new(); + + // Add the torrents/peers to the torrent repository + for info_hash in &info_hashes { + torrent_repository + .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) + .await; + } + + let start_time = std::time::Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone + .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) + .await; + + if let Some(sleep_time) = args.sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + let result = start_time.elapsed(); + + results.push(result); + } + + get_average_and_adjusted_average_from_results(results) +} diff --git a/packages/torrent-repository-benchmarks/src/benches/mod.rs b/packages/torrent-repository-benchmarks/src/benches/mod.rs new file mode 100644 index 000000000..1026aa4bf --- /dev/null +++ b/packages/torrent-repository-benchmarks/src/benches/mod.rs @@ -0,0 +1,3 @@ +pub mod asyn; +pub mod sync; +pub mod utils; diff --git a/packages/torrent-repository-benchmarks/src/benches/sync.rs b/packages/torrent-repository-benchmarks/src/benches/sync.rs new file mode 100644 index 000000000..dac7ab810 --- /dev/null +++ b/packages/torrent-repository-benchmarks/src/benches/sync.rs @@ -0,0 +1,166 @@ +use std::sync::Arc; +use std::time::Duration; + +use clap::Parser; +use futures::stream::FuturesUnordered; +use torrust_tracker::core::torrent::repository::Repository; +use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; + +use crate::args::Args; +use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; + +// Simply add one torrent +#[must_use] +pub fn add_one_torrent(samples: usize) -> (Duration, Duration) { + let mut results: Vec = Vec::with_capacity(samples); + + for _ in 0..samples { + let torrent_repository = Arc::new(T::new()); + + let info_hash = InfoHash([0; 20]); + + let start_time = std::time::Instant::now(); + + torrent_repository.update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER); + + let result = start_time.elapsed(); + + results.push(result); + } + + get_average_and_adjusted_average_from_results(results) +} + +// Add one torrent ten thousand times in parallel (depending on the set worker threads) +pub async fn update_one_torrent_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: usize, +) -> (Duration, Duration) { + let args = Args::parse(); + let mut results: Vec = Vec::with_capacity(samples); + + for _ in 0..samples { + let torrent_repository = Arc::new(T::new()); + let info_hash: &'static InfoHash = &InfoHash([0; 20]); + let handles = FuturesUnordered::new(); + + // Add the torrent/peer to the torrent repository + torrent_repository.update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER); + + let start_time = std::time::Instant::now(); + + for _ in 0..10_000 { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER); + + if let Some(sleep_time) = args.sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + let result = start_time.elapsed(); + + results.push(result); + } + + get_average_and_adjusted_average_from_results(results) +} + +// Add ten thousand torrents in parallel (depending on the set worker threads) +pub async fn add_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: usize, +) -> (Duration, Duration) { + let args = Args::parse(); + let mut results: Vec = Vec::with_capacity(samples); + + for _ in 0..samples { + let torrent_repository = Arc::new(T::new()); + let info_hashes = generate_unique_info_hashes(10_000); + let handles = FuturesUnordered::new(); + + let start_time = std::time::Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER); + + if let Some(sleep_time) = args.sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + let result = start_time.elapsed(); + + results.push(result); + } + + get_average_and_adjusted_average_from_results(results) +} + +// Update ten thousand torrents in parallel (depending on the set worker threads) +pub async fn update_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: usize, +) -> (Duration, Duration) { + let args = Args::parse(); + let mut results: Vec = Vec::with_capacity(samples); + + for _ in 0..samples { + let torrent_repository = Arc::new(T::new()); + let info_hashes = generate_unique_info_hashes(10_000); + let handles = FuturesUnordered::new(); + + // Add the torrents/peers to the torrent repository + for info_hash in &info_hashes { + torrent_repository.update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER); + } + + let start_time = std::time::Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER); + + if let Some(sleep_time) = args.sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + let result = start_time.elapsed(); + + results.push(result); + } + + get_average_and_adjusted_average_from_results(results) +} diff --git a/packages/torrent-repository-benchmarks/src/benches/utils.rs b/packages/torrent-repository-benchmarks/src/benches/utils.rs new file mode 100644 index 000000000..ef1640038 --- /dev/null +++ b/packages/torrent-repository-benchmarks/src/benches/utils.rs @@ -0,0 +1,73 @@ +use std::collections::HashSet; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::time::Duration; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use torrust_tracker::core::peer::{Id, Peer}; +use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker::shared::clock::DurationSinceUnixEpoch; + +pub const DEFAULT_PEER: Peer = Peer { + peer_id: Id([0; 20]), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::from_secs(0), + uploaded: NumberOfBytes(0), + downloaded: NumberOfBytes(0), + left: NumberOfBytes(0), + event: AnnounceEvent::Started, +}; + +#[must_use] +#[allow(clippy::missing_panics_doc)] +pub fn generate_unique_info_hashes(size: usize) -> Vec { + let mut result = HashSet::new(); + + let mut bytes = [0u8; 20]; + + #[allow(clippy::cast_possible_truncation)] + for i in 0..size { + bytes[0] = (i & 0xFF) as u8; + bytes[1] = ((i >> 8) & 0xFF) as u8; + bytes[2] = ((i >> 16) & 0xFF) as u8; + bytes[3] = ((i >> 24) & 0xFF) as u8; + + let info_hash = InfoHash(bytes); + result.insert(info_hash); + } + + assert_eq!(result.len(), size); + + result.into_iter().collect() +} + +#[must_use] +pub fn within_acceptable_range(test: &Duration, norm: &Duration) -> bool { + let test_secs = test.as_secs_f64(); + let norm_secs = norm.as_secs_f64(); + + // Calculate the upper and lower bounds for the 10% tolerance + let tolerance = norm_secs * 0.1; + + // Calculate the upper and lower limits + let upper_limit = norm_secs + tolerance; + let lower_limit = norm_secs - tolerance; + + test_secs < upper_limit && test_secs > lower_limit +} + +#[must_use] +pub fn get_average_and_adjusted_average_from_results(mut results: Vec) -> (Duration, Duration) { + #[allow(clippy::cast_possible_truncation)] + let average = results.iter().sum::() / results.len() as u32; + + results.retain(|result| within_acceptable_range(result, &average)); + + let mut adjusted_average = Duration::from_nanos(0); + + #[allow(clippy::cast_possible_truncation)] + if results.len() > 1 { + adjusted_average = results.iter().sum::() / results.len() as u32; + } + + (average, adjusted_average) +} diff --git a/packages/torrent-repository-benchmarks/src/lib.rs b/packages/torrent-repository-benchmarks/src/lib.rs new file mode 100644 index 000000000..58ebc2057 --- /dev/null +++ b/packages/torrent-repository-benchmarks/src/lib.rs @@ -0,0 +1,2 @@ +pub mod args; +pub mod benches; diff --git a/packages/torrent-repository-benchmarks/src/main.rs b/packages/torrent-repository-benchmarks/src/main.rs new file mode 100644 index 000000000..0d9db73ac --- /dev/null +++ b/packages/torrent-repository-benchmarks/src/main.rs @@ -0,0 +1,139 @@ +use clap::Parser; +use torrust_torrent_repository_benchmarks::args::Args; +use torrust_torrent_repository_benchmarks::benches::asyn::{ + async_add_multiple_torrents_in_parallel, async_add_one_torrent, async_update_multiple_torrents_in_parallel, + async_update_one_torrent_in_parallel, +}; +use torrust_torrent_repository_benchmarks::benches::sync::{ + add_multiple_torrents_in_parallel, add_one_torrent, update_multiple_torrents_in_parallel, update_one_torrent_in_parallel, +}; +use torrust_tracker::core::torrent::repository::{AsyncSync, RepositoryAsync, RepositoryAsyncSingle, Sync, SyncSingle}; + +#[allow(clippy::too_many_lines)] +#[allow(clippy::print_literal)] +fn main() { + let args = Args::parse(); + + // Add 1 to worker_threads since we need a thread that awaits the benchmark + let rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(args.threads + 1) + .enable_time() + .build() + .unwrap(); + + println!("tokio::sync::RwLock>"); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_one_torrent", + rt.block_on(async_add_one_torrent::(1_000_000)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "update_one_torrent_in_parallel", + rt.block_on(async_update_one_torrent_in_parallel::(&rt, 10)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_multiple_torrents_in_parallel", + rt.block_on(async_add_multiple_torrents_in_parallel::(&rt, 10)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "update_multiple_torrents_in_parallel", + rt.block_on(async_update_multiple_torrents_in_parallel::(&rt, 10)) + ); + + if let Some(true) = args.compare { + println!(); + + println!("std::sync::RwLock>"); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_one_torrent", + add_one_torrent::(1_000_000) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "update_one_torrent_in_parallel", + rt.block_on(update_one_torrent_in_parallel::(&rt, 10)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_multiple_torrents_in_parallel", + rt.block_on(add_multiple_torrents_in_parallel::(&rt, 10)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "update_multiple_torrents_in_parallel", + rt.block_on(update_multiple_torrents_in_parallel::(&rt, 10)) + ); + + println!(); + + println!("std::sync::RwLock>>>"); + println!("{}: Avg/AdjAvg: {:?}", "add_one_torrent", add_one_torrent::(1_000_000)); + println!( + "{}: Avg/AdjAvg: {:?}", + "update_one_torrent_in_parallel", + rt.block_on(update_one_torrent_in_parallel::(&rt, 10)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_multiple_torrents_in_parallel", + rt.block_on(add_multiple_torrents_in_parallel::(&rt, 10)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "update_multiple_torrents_in_parallel", + rt.block_on(update_multiple_torrents_in_parallel::(&rt, 10)) + ); + + println!(); + + println!("tokio::sync::RwLock>>>"); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_one_torrent", + rt.block_on(async_add_one_torrent::(1_000_000)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "update_one_torrent_in_parallel", + rt.block_on(async_update_one_torrent_in_parallel::(&rt, 10)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_multiple_torrents_in_parallel", + rt.block_on(async_add_multiple_torrents_in_parallel::(&rt, 10)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "update_multiple_torrents_in_parallel", + rt.block_on(async_update_multiple_torrents_in_parallel::(&rt, 10)) + ); + + println!(); + + println!("tokio::sync::RwLock>>>"); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_one_torrent", + rt.block_on(async_add_one_torrent::(1_000_000)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "update_one_torrent_in_parallel", + rt.block_on(async_update_one_torrent_in_parallel::(&rt, 10)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_multiple_torrents_in_parallel", + rt.block_on(async_add_multiple_torrents_in_parallel::(&rt, 10)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "update_multiple_torrents_in_parallel", + rt.block_on(async_update_multiple_torrents_in_parallel::(&rt, 10)) + ); + } +} diff --git a/src/core/mod.rs b/src/core/mod.rs index ed6ba6a8d..caac5b1ea 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -12,9 +12,9 @@ //! ```text //! Delivery layer Domain layer //! -//! HTTP tracker | +//! HTTP tracker | //! UDP tracker |> Core tracker -//! Tracker REST API | +//! Tracker REST API | //! ``` //! //! # Table of contents @@ -439,23 +439,23 @@ pub mod services; pub mod statistics; pub mod torrent; -use std::collections::btree_map::Entry; use std::collections::{BTreeMap, HashMap}; use std::net::IpAddr; use std::panic::Location; use std::sync::Arc; use std::time::Duration; +use futures::future::join_all; use tokio::sync::mpsc::error::SendError; -use tokio::sync::{RwLock, RwLockReadGuard}; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::TrackerMode; use self::auth::Key; use self::error::Error; use self::peer::Peer; -use self::torrent::{SwarmMetadata, SwarmStats}; +use self::torrent::repository::{RepositoryAsyncSingle, TRepositoryAsync}; use crate::core::databases::Database; +use crate::core::torrent::{SwarmMetadata, SwarmStats}; use crate::shared::bit_torrent::info_hash::InfoHash; /// The domain layer tracker service. @@ -472,11 +472,11 @@ pub struct Tracker { pub config: Arc, /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) /// or [`MySQL`](crate::core::databases::mysql) - pub database: Box, + pub database: Arc>, mode: TrackerMode, - keys: RwLock>, - whitelist: RwLock>, - torrents: RwLock>, + keys: tokio::sync::RwLock>, + whitelist: tokio::sync::RwLock>, + pub torrents: Arc, stats_event_sender: Option>, stats_repository: statistics::Repo, } @@ -562,16 +562,16 @@ impl Tracker { stats_event_sender: Option>, stats_repository: statistics::Repo, ) -> Result { - let database = databases::driver::build(&config.db_driver, &config.db_path)?; + let database = Arc::new(databases::driver::build(&config.db_driver, &config.db_path)?); let mode = config.mode; Ok(Tracker { config, mode, - keys: RwLock::new(std::collections::HashMap::new()), - whitelist: RwLock::new(std::collections::HashSet::new()), - torrents: RwLock::new(std::collections::BTreeMap::new()), + keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), + whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), + torrents: Arc::new(RepositoryAsyncSingle::new()), stats_event_sender, stats_repository, database, @@ -654,7 +654,8 @@ impl Tracker { /// It returns the data for a `scrape` response. async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { - let torrents = self.get_torrents().await; + let torrents = self.torrents.get_torrents().await; + match torrents.get(info_hash) { Some(torrent_entry) => torrent_entry.get_swarm_metadata(), None => SwarmMetadata::default(), @@ -672,7 +673,7 @@ impl Tracker { pub async fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { let persistent_torrents = self.database.load_persistent_torrents().await?; - let mut torrents = self.torrents.write().await; + let mut torrents = self.torrents.get_torrents_mut().await; for (info_hash, completed) in persistent_torrents { // Skip if torrent entry already exists @@ -692,7 +693,7 @@ impl Tracker { } async fn get_peers_for_peer(&self, info_hash: &InfoHash, peer: &Peer) -> Vec { - let read_lock = self.torrents.read().await; + let read_lock = self.torrents.get_torrents().await; match read_lock.get(info_hash) { None => vec![], @@ -704,7 +705,7 @@ impl Tracker { /// /// Get all torrent peers for a given torrent pub async fn get_all_torrent_peers(&self, info_hash: &InfoHash) -> Vec { - let read_lock = self.torrents.read().await; + let read_lock = self.torrents.get_torrents().await; match read_lock.get(info_hash) { None => vec![], @@ -721,79 +722,87 @@ impl Tracker { // code-review: consider splitting the function in two (command and query segregation). // `update_torrent_with_peer` and `get_stats` - let mut torrents = self.torrents.write().await; - - let torrent_entry = match torrents.entry(*info_hash) { - Entry::Vacant(vacant) => vacant.insert(torrent::Entry::new()), - Entry::Occupied(entry) => entry.into_mut(), - }; - - let stats_updated = torrent_entry.update_peer(peer); + let (stats, stats_updated) = self.torrents.update_torrent_with_peer_and_get_stats(info_hash, peer).await; - // todo: move this action to a separate worker if self.config.persistent_torrent_completed_stat && stats_updated { - drop( - self.database - .save_persistent_torrent(info_hash, torrent_entry.completed) - .await, - ); - } + let completed = stats.completed; + let info_hash = *info_hash; - let (seeders, completed, leechers) = torrent_entry.get_stats(); - - torrent::SwarmStats { - completed, - seeders, - leechers, + drop(self.database.save_persistent_torrent(&info_hash, completed).await); } - } - pub async fn get_torrents(&self) -> RwLockReadGuard<'_, BTreeMap> { - self.torrents.read().await + stats } /// It calculates and returns the general `Tracker` /// [`TorrentsMetrics`] /// /// # Context: Tracker + /// + /// # Panics + /// Panics if unable to get the torrent metrics. pub async fn get_torrents_metrics(&self) -> TorrentsMetrics { - let mut torrents_metrics = TorrentsMetrics { + let arc_torrents_metrics = Arc::new(tokio::sync::Mutex::new(TorrentsMetrics { seeders: 0, completed: 0, leechers: 0, torrents: 0, - }; + })); + + let db = self.torrents.get_torrents().await.clone(); + + let futures = db + .values() + .map(|torrent_entry| { + let torrent_entry = torrent_entry.clone(); + let torrents_metrics = arc_torrents_metrics.clone(); + + async move { + tokio::spawn(async move { + let (seeders, completed, leechers) = torrent_entry.get_stats(); + torrents_metrics.lock().await.seeders += u64::from(seeders); + torrents_metrics.lock().await.completed += u64::from(completed); + torrents_metrics.lock().await.leechers += u64::from(leechers); + torrents_metrics.lock().await.torrents += 1; + }) + .await + .expect("Error torrent_metrics spawn"); + } + }) + .collect::>(); - let db = self.get_torrents().await; + join_all(futures).await; - db.values().for_each(|torrent_entry| { - let (seeders, completed, leechers) = torrent_entry.get_stats(); - torrents_metrics.seeders += u64::from(seeders); - torrents_metrics.completed += u64::from(completed); - torrents_metrics.leechers += u64::from(leechers); - torrents_metrics.torrents += 1; - }); + let torrents_metrics = Arc::try_unwrap(arc_torrents_metrics).expect("Could not unwrap arc_torrents_metrics"); - torrents_metrics + torrents_metrics.into_inner() } /// Remove inactive peers and (optionally) peerless torrents /// /// # Context: Tracker pub async fn cleanup_torrents(&self) { - let mut torrents_lock = self.torrents.write().await; + let mut torrents_lock = self.torrents.get_torrents_mut().await; // If we don't need to remove torrents we will use the faster iter if self.config.remove_peerless_torrents { - torrents_lock.retain(|_, torrent_entry| { + let mut cleaned_torrents_map: BTreeMap = BTreeMap::new(); + + for (info_hash, torrent_entry) in &mut *torrents_lock { torrent_entry.remove_inactive_peers(self.config.max_peer_timeout); - if self.config.persistent_torrent_completed_stat { - torrent_entry.completed > 0 || !torrent_entry.peers.is_empty() - } else { - !torrent_entry.peers.is_empty() + if torrent_entry.peers.is_empty() { + continue; } - }); + + if self.config.persistent_torrent_completed_stat && torrent_entry.completed == 0 { + continue; + } + + cleaned_torrents_map.insert(*info_hash, torrent_entry.clone()); + } + + *torrents_lock = cleaned_torrents_map; } else { for torrent_entry in (*torrents_lock).values_mut() { torrent_entry.remove_inactive_peers(self.config.max_peer_timeout); @@ -1074,7 +1083,7 @@ impl Tracker { /// It return the `Tracker` [`statistics::Metrics`]. /// /// # Context: Statistics - pub async fn get_stats(&self) -> RwLockReadGuard<'_, statistics::Metrics> { + pub async fn get_stats(&self) -> tokio::sync::RwLockReadGuard<'_, statistics::Metrics> { self.stats_repository.get_stats().await } @@ -1786,11 +1795,11 @@ mod tests { assert_eq!(swarm_stats.completed, 1); // Remove the newly updated torrent from memory - tracker.torrents.write().await.remove(&info_hash); + tracker.torrents.get_torrents_mut().await.remove(&info_hash); tracker.load_torrents_from_database().await.unwrap(); - let torrents = tracker.get_torrents().await; + let torrents = tracker.torrents.get_torrents().await; assert!(torrents.contains_key(&info_hash)); let torrent_entry = torrents.get(&info_hash).unwrap(); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 651f40cab..918a80bae 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -93,7 +93,7 @@ impl Default for Pagination { /// It returns all the information the tracker has about one torrent in a [Info] struct. pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Option { - let db = tracker.get_torrents().await; + let db = tracker.torrents.get_torrents().await; let torrent_entry_option = db.get(info_hash); @@ -118,21 +118,22 @@ pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Op /// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list. pub async fn get_torrents(tracker: Arc, pagination: &Pagination) -> Vec { - let db = tracker.get_torrents().await; - - db.iter() - .map(|(info_hash, torrent_entry)| { - let (seeders, completed, leechers) = torrent_entry.get_stats(); - BasicInfo { - info_hash: *info_hash, - seeders: u64::from(seeders), - completed: u64::from(completed), - leechers: u64::from(leechers), - } - }) - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .collect() + let db = tracker.torrents.get_torrents().await; + + let mut basic_infos: Vec = vec![]; + + for (info_hash, torrent_entry) in db.iter().skip(pagination.offset as usize).take(pagination.limit as usize) { + let (seeders, completed, leechers) = torrent_entry.get_stats(); + + basic_infos.push(BasicInfo { + info_hash: *info_hash, + seeders: u64::from(seeders), + completed: u64::from(completed), + leechers: u64::from(leechers), + }); + } + + basic_infos } #[cfg(test)] diff --git a/src/core/torrent.rs b/src/core/torrent/mod.rs similarity index 99% rename from src/core/torrent.rs rename to src/core/torrent/mod.rs index 8167aa2db..a49e218a9 100644 --- a/src/core/torrent.rs +++ b/src/core/torrent/mod.rs @@ -28,6 +28,8 @@ //! Peer that don not have a full copy of the torrent data are called "leechers". //! //! > **NOTICE**: that both [`SwarmMetadata`] and [`SwarmStats`] contain the same information. [`SwarmMetadata`] is using the names used on [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). +pub mod repository; + use std::time::Duration; use aquatic_udp_protocol::AnnounceEvent; diff --git a/src/core/torrent/repository.rs b/src/core/torrent/repository.rs new file mode 100644 index 000000000..62df9b510 --- /dev/null +++ b/src/core/torrent/repository.rs @@ -0,0 +1,301 @@ +use std::sync::Arc; + +use crate::core::peer; +use crate::core::torrent::{Entry, SwarmStats}; +use crate::shared::bit_torrent::info_hash::InfoHash; + +pub trait Repository { + fn new() -> Self; + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool); +} + +pub trait TRepositoryAsync { + fn new() -> Self; + fn update_torrent_with_peer_and_get_stats( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + ) -> impl std::future::Future + Send; +} + +/// Structure that holds all torrents. Using `std::sync` locks. +pub struct Sync { + torrents: std::sync::RwLock>>>, +} + +impl Sync { + /// Returns the get torrents of this [`Sync`]. + /// + /// # Panics + /// + /// Panics if unable to read the torrent. + pub fn get_torrents( + &self, + ) -> std::sync::RwLockReadGuard<'_, std::collections::BTreeMap>>> { + self.torrents.read().expect("unable to get torrent list") + } + + /// Returns the mutable get torrents of this [`Sync`]. + /// + /// # Panics + /// + /// Panics if unable to write to the torrents list. + pub fn get_torrents_mut( + &self, + ) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap>>> { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl Repository for Sync { + fn new() -> Self { + Self { + torrents: std::sync::RwLock::new(std::collections::BTreeMap::new()), + } + } + + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { + let maybe_existing_torrent_entry = self.get_torrents().get(info_hash).cloned(); + + let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { + existing_torrent_entry + } else { + let mut torrents_lock = self.get_torrents_mut(); + let entry = torrents_lock + .entry(*info_hash) + .or_insert(Arc::new(std::sync::Mutex::new(Entry::new()))); + entry.clone() + }; + + let (stats, stats_updated) = { + let mut torrent_entry_lock = torrent_entry.lock().unwrap(); + let stats_updated = torrent_entry_lock.update_peer(peer); + let stats = torrent_entry_lock.get_stats(); + + (stats, stats_updated) + }; + + ( + SwarmStats { + completed: stats.1, + seeders: stats.0, + leechers: stats.2, + }, + stats_updated, + ) + } +} + +/// Structure that holds all torrents. Using `std::sync` locks. +pub struct SyncSingle { + torrents: std::sync::RwLock>, +} + +impl SyncSingle { + /// Returns the get torrents of this [`SyncSingle`]. + /// + /// # Panics + /// + /// Panics if unable to get torrent list. + pub fn get_torrents(&self) -> std::sync::RwLockReadGuard<'_, std::collections::BTreeMap> { + self.torrents.read().expect("unable to get torrent list") + } + + /// Returns the get torrents of this [`SyncSingle`]. + /// + /// # Panics + /// + /// Panics if unable to get writable torrent list. + pub fn get_torrents_mut(&self) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl Repository for SyncSingle { + fn new() -> Self { + Self { + torrents: std::sync::RwLock::new(std::collections::BTreeMap::new()), + } + } + + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { + let mut torrents = self.torrents.write().unwrap(); + + let torrent_entry = match torrents.entry(*info_hash) { + std::collections::btree_map::Entry::Vacant(vacant) => vacant.insert(Entry::new()), + std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), + }; + + let stats_updated = torrent_entry.update_peer(peer); + let stats = torrent_entry.get_stats(); + + ( + SwarmStats { + completed: stats.1, + seeders: stats.0, + leechers: stats.2, + }, + stats_updated, + ) + } +} + +/// Structure that holds all torrents. Using `tokio::sync` locks. +#[allow(clippy::module_name_repetitions)] +pub struct RepositoryAsync { + torrents: tokio::sync::RwLock>>>, +} + +impl TRepositoryAsync for RepositoryAsync { + fn new() -> Self { + Self { + torrents: tokio::sync::RwLock::new(std::collections::BTreeMap::new()), + } + } + + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { + let maybe_existing_torrent_entry = self.get_torrents().await.get(info_hash).cloned(); + + let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { + existing_torrent_entry + } else { + let mut torrents_lock = self.get_torrents_mut().await; + let entry = torrents_lock + .entry(*info_hash) + .or_insert(Arc::new(tokio::sync::Mutex::new(Entry::new()))); + entry.clone() + }; + + let (stats, stats_updated) = { + let mut torrent_entry_lock = torrent_entry.lock().await; + let stats_updated = torrent_entry_lock.update_peer(peer); + let stats = torrent_entry_lock.get_stats(); + + (stats, stats_updated) + }; + + ( + SwarmStats { + completed: stats.1, + seeders: stats.0, + leechers: stats.2, + }, + stats_updated, + ) + } +} + +impl RepositoryAsync { + pub async fn get_torrents( + &self, + ) -> tokio::sync::RwLockReadGuard<'_, std::collections::BTreeMap>>> { + self.torrents.read().await + } + + pub async fn get_torrents_mut( + &self, + ) -> tokio::sync::RwLockWriteGuard<'_, std::collections::BTreeMap>>> { + self.torrents.write().await + } +} + +/// Structure that holds all torrents. Using a `tokio::sync` lock for the torrents map an`std::sync`nc lock for the inner torrent entry. +pub struct AsyncSync { + torrents: tokio::sync::RwLock>>>, +} + +impl TRepositoryAsync for AsyncSync { + fn new() -> Self { + Self { + torrents: tokio::sync::RwLock::new(std::collections::BTreeMap::new()), + } + } + + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { + let maybe_existing_torrent_entry = self.get_torrents().await.get(info_hash).cloned(); + + let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { + existing_torrent_entry + } else { + let mut torrents_lock = self.get_torrents_mut().await; + let entry = torrents_lock + .entry(*info_hash) + .or_insert(Arc::new(std::sync::Mutex::new(Entry::new()))); + entry.clone() + }; + + let (stats, stats_updated) = { + let mut torrent_entry_lock = torrent_entry.lock().unwrap(); + let stats_updated = torrent_entry_lock.update_peer(peer); + let stats = torrent_entry_lock.get_stats(); + + (stats, stats_updated) + }; + + ( + SwarmStats { + completed: stats.1, + seeders: stats.0, + leechers: stats.2, + }, + stats_updated, + ) + } +} + +impl AsyncSync { + pub async fn get_torrents( + &self, + ) -> tokio::sync::RwLockReadGuard<'_, std::collections::BTreeMap>>> { + self.torrents.read().await + } + + pub async fn get_torrents_mut( + &self, + ) -> tokio::sync::RwLockWriteGuard<'_, std::collections::BTreeMap>>> { + self.torrents.write().await + } +} + +#[allow(clippy::module_name_repetitions)] +pub struct RepositoryAsyncSingle { + torrents: tokio::sync::RwLock>, +} + +impl TRepositoryAsync for RepositoryAsyncSingle { + fn new() -> Self { + Self { + torrents: tokio::sync::RwLock::new(std::collections::BTreeMap::new()), + } + } + + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { + let (stats, stats_updated) = { + let mut torrents_lock = self.torrents.write().await; + let torrent_entry = torrents_lock.entry(*info_hash).or_insert(Entry::new()); + let stats_updated = torrent_entry.update_peer(peer); + let stats = torrent_entry.get_stats(); + + (stats, stats_updated) + }; + + ( + SwarmStats { + completed: stats.1, + seeders: stats.0, + leechers: stats.2, + }, + stats_updated, + ) + } +} + +impl RepositoryAsyncSingle { + pub async fn get_torrents(&self) -> tokio::sync::RwLockReadGuard<'_, std::collections::BTreeMap> { + self.torrents.read().await + } + + pub async fn get_torrents_mut(&self) -> tokio::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { + self.torrents.write().await + } +} diff --git a/tests/wrk_benchmark_announce.lua b/tests/wrk_benchmark_announce.lua index c182f8e68..620ba2680 100644 --- a/tests/wrk_benchmark_announce.lua +++ b/tests/wrk_benchmark_announce.lua @@ -1,53 +1,35 @@ --- else the randomness would be the same every run -math.randomseed(os.time()) +function generate_unique_info_hashes(size) + local result = {} + local seen = {} -local charset = "0123456789ABCDEF" + for i = 0, size - 1 do + local bytes = {} + bytes[1] = i & 0xFF + bytes[2] = (i >> 8) & 0xFF + bytes[3] = (i >> 16) & 0xFF + bytes[4] = (i >> 24) & 0xFF -function hexToChar(hex) - local n = tonumber(hex, 16) - local f = string.char(n) - return f -end + local info_hash = bytes + local key = table.concat(info_hash, ",") -function hexStringToCharString(hex) - local ret = {} - local r - for i = 0, 19 do - local x = i * 2 - r = hex:sub(x+1, x+2) - local f = hexToChar(r) - table.insert(ret, f) + if not seen[key] then + table.insert(result, info_hash) + seen[key] = true + end end - return table.concat(ret) -end -function urlEncode(str) - str = string.gsub (str, "([^0-9a-zA-Z !'()*._~-])", -- locale independent - function (c) return string.format ("%%%02X", string.byte(c)) end) - str = string.gsub (str, " ", "+") - return str + return result end -function genHexString(length) - local ret = {} - local r - for i = 1, length do - r = math.random(1, #charset) - table.insert(ret, charset:sub(r, r)) - end - return table.concat(ret) -end +info_hashes = generate_unique_info_hashes(10000000) -function randomInfoHash() - local hexString = genHexString(40) - local str = hexStringToCharString(hexString) - return urlEncode(str) -end +index = 0 -- the request function that will run at each request request = function() - path = "/announce?info_hash=" .. randomInfoHash() .. "&peer_id=-lt0D80-a%D4%10%19%99%A6yh%9A%E1%CD%96&port=54434&uploaded=885&downloaded=0&left=0&corrupt=0&key=A78381BD&numwant=200&compact=1&no_peer_id=1&supportcrypto=1&redundant=0" - headers = {} - headers["X-Forwarded-For"] = "1.1.1.1" - return wrk.format("GET", path, headers) + path = "/announce?info_hash=" .. info_hashes[index] .. "&peer_id=-lt0D80-a%D4%10%19%99%A6yh%9A%E1%CD%96&port=54434&uploaded=885&downloaded=0&left=0&corrupt=0&key=A78381BD&numwant=200&compact=1&no_peer_id=1&supportcrypto=1&redundant=0" + index += 1 + headers = {} + headers["X-Forwarded-For"] = "1.1.1.1" + return wrk.format("GET", path, headers) end From 1735a7a4dc4fa53f36da1394bc4cd4b52eb352a6 Mon Sep 17 00:00:00 2001 From: Warm Beer Date: Thu, 21 Dec 2023 00:43:42 +0100 Subject: [PATCH 0150/1297] chore: only run contract, deployment & testing jobs in nightly rust --- .github/workflows/contract.yaml | 2 +- .github/workflows/deployment.yaml | 4 ++-- .github/workflows/testing.yaml | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/contract.yaml b/.github/workflows/contract.yaml index 7c9fd47bd..b38e0e8f5 100644 --- a/.github/workflows/contract.yaml +++ b/.github/workflows/contract.yaml @@ -14,7 +14,7 @@ jobs: strategy: matrix: - toolchain: [stable, nightly] + toolchain: [nightly] steps: - id: checkout diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 5df50a4b0..91f8d86eb 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -12,7 +12,7 @@ jobs: strategy: matrix: - toolchain: [stable, nightly] + toolchain: [nightly] steps: - id: checkout @@ -44,7 +44,7 @@ jobs: name: Setup Toolchain uses: dtolnay/rust-toolchain@stable with: - toolchain: stable + toolchain: ${{ matrix.toolchain }} - id: publish name: Publish Crates diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index f60f03e5e..d9d0c60c9 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -39,7 +39,7 @@ jobs: strategy: matrix: - toolchain: [stable, nightly] + toolchain: [nightly] steps: - id: checkout @@ -79,7 +79,7 @@ jobs: strategy: matrix: - toolchain: [stable, nightly] + toolchain: [nightly] steps: - id: checkout From ebb7d4c3094003264888d31dbe7a8831b628c9a9 Mon Sep 17 00:00:00 2001 From: Warm Beer Date: Thu, 21 Dec 2023 10:50:27 +0100 Subject: [PATCH 0151/1297] chore: make Containerfile use nightly rust --- Containerfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Containerfile b/Containerfile index 8ea555c2d..77c7da669 100644 --- a/Containerfile +++ b/Containerfile @@ -3,13 +3,13 @@ # Torrust Tracker ## Builder Image -FROM rust:bookworm as chef +FROM rustlang/rust:nightly-bookworm as chef WORKDIR /tmp RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash RUN cargo binstall --no-confirm cargo-chef cargo-nextest ## Tester Image -FROM rust:slim-bookworm as tester +FROM rustlang/rust:nightly-bookworm-slim as tester WORKDIR /tmp RUN apt-get update; apt-get install -y curl sqlite3; apt-get autoclean From 6e607c34e2ee51edf88578300ebcae10b228bc58 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 22 Dec 2023 12:37:18 +0000 Subject: [PATCH 0152/1297] feat: [#539] change log for UDP tracker From: ```s 2023-12-22T12:32:53.016911160+00:00 [torrust_tracker::servers::udp::server][INFO] Received 109 bytes 2023-12-22T12:32:53.016953899+00:00 [torrust_tracker::servers::udp::server][INFO] Sending 43 bytes ... 2023-12-22T12:32:53.017038257+00:00 [torrust_tracker::servers::udp::server][INFO] 43 bytes sent ``` To: ```s 2023-12-22T12:35:51.320114322+00:00 [UDP][INFO] "CONNECT TxID 1583189312" 2023-12-22T12:35:51.345003905+00:00 [UDP][INFO] "ANNOUNCE TxID 1583189313 IH 443c7602b4fde83d1154d6d9da48808418b181b6" 2023-12-22T12:35:51.320114322+00:00 [UDP][INFO] "SCRAPE TxID 1583189312" ```` - The target is more generic "UDP" and it will be always the same even if we rearrange the packages. - The info is more useful. It includes the request type, the transaction ID to identify the client, and the info-hash. That would allow us to extract statistics from the logs. NOTE: In the long term maybe this should be configurable. --- src/servers/udp/handlers.rs | 6 +++++- src/servers/udp/server.rs | 8 ++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 1878c30e1..39a077466 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -7,7 +7,7 @@ use aquatic_udp_protocol::{ AnnounceInterval, AnnounceRequest, AnnounceResponse, ConnectRequest, ConnectResponse, ErrorResponse, NumberOfDownloads, NumberOfPeers, Port, Request, Response, ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; -use log::debug; +use log::{debug, info}; use super::connection_cookie::{check, from_connection_id, into_connection_id, make}; use crate::core::{statistics, Tracker}; @@ -73,6 +73,7 @@ pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: /// /// This function does not ever return an error. pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, tracker: &Tracker) -> Result { + info!(target: "UDP", "\"CONNECT TxID {}\"", request.transaction_id.0); debug!("udp connect request: {:#?}", request); let connection_cookie = make(&remote_addr); @@ -136,6 +137,8 @@ pub async fn handle_announce( authenticate(&info_hash, tracker).await?; + info!(target: "UDP", "\"ANNOUNCE TxID {} IH {}\"", announce_request.transaction_id.0, info_hash.to_hex_string()); + let mut peer = peer_builder::from_request(&wrapped_announce_request, &remote_client_ip); let response = tracker.announce(&info_hash, &mut peer, &remote_client_ip).await; @@ -210,6 +213,7 @@ pub async fn handle_announce( /// /// This function does not ever return an error. pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tracker: &Tracker) -> Result { + info!(target: "UDP", "\"SCRAPE TxID {}\"", request.transaction_id.0); debug!("udp scrape request: {:#?}", request); // Convert from aquatic infohashes diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index c6b73860b..9b9a89b11 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -191,7 +191,7 @@ impl Udp { Ok((valid_bytes, remote_addr)) = socket.recv_from(&mut data) => { let payload = data[..valid_bytes].to_vec(); - info!("Received {} bytes", payload.len()); + debug!("Received {} bytes", payload.len()); debug!("From: {}", &remote_addr); debug!("Payload: {:?}", payload); @@ -227,7 +227,7 @@ impl Udp { Ok((valid_bytes, remote_addr)) = socket.recv_from(&mut data) => { let payload = data[..valid_bytes].to_vec(); - info!("Received {} bytes", payload.len()); + debug!("Received {} bytes", payload.len()); debug!("From: {}", &remote_addr); debug!("Payload: {:?}", payload); @@ -249,13 +249,13 @@ impl Udp { let position = cursor.position() as usize; let inner = cursor.get_ref(); - info!("Sending {} bytes ...", &inner[..position].len()); + debug!("Sending {} bytes ...", &inner[..position].len()); debug!("To: {:?}", &remote_addr); debug!("Payload: {:?}", &inner[..position]); Udp::send_packet(socket, &remote_addr, &inner[..position]).await; - info!("{} bytes sent", &inner[..position].len()); + debug!("{} bytes sent", &inner[..position].len()); } Err(_) => { error!("could not write response to bytes."); From ff3928e7f2c9ea6a94ae938dc03ba1dbe9c0eb00 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 22 Dec 2023 13:04:17 +0000 Subject: [PATCH 0153/1297] fix: clippy error --- contrib/bencode/src/reference/decode_opt.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/bencode/src/reference/decode_opt.rs b/contrib/bencode/src/reference/decode_opt.rs index ac94d0311..e8d9a8337 100644 --- a/contrib/bencode/src/reference/decode_opt.rs +++ b/contrib/bencode/src/reference/decode_opt.rs @@ -41,7 +41,7 @@ impl BDecodeOpt { /// /// It may be useful to disable this if for example, the input bencode is prepended to /// some payload and you would like to disassociate it. In this case, to find where the - /// rest of the payload starts that wasn't decoded, get the bencode buffer, and call len(). + /// rest of the payload starts that wasn't decoded, get the bencode buffer, and call `len()`. #[must_use] pub fn enforce_full_decode(&self) -> bool { self.enforce_full_decode From 3b8a625318463aa8681f818d41e2557ef95f7f19 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 26 Dec 2023 16:23:25 +0800 Subject: [PATCH 0154/1297] chore: update cargo deps ``` Updating crates.io index Updating anstream v0.6.4 -> v0.6.5 Updating anstyle-parse v0.2.2 -> v0.2.3 Updating anstyle-query v1.0.0 -> v1.0.2 Updating anstyle-wincon v3.0.1 -> v3.0.2 Updating async-trait v0.1.74 -> v0.1.75 Updating borsh v1.2.0 -> v1.3.0 Updating borsh-derive v1.2.0 -> v1.3.0 Updating clap v4.4.10 -> v4.4.11 Updating clap_builder v4.4.9 -> v4.4.11 Updating crossbeam v0.8.2 -> v0.8.3 Updating crossbeam-channel v0.5.8 -> v0.5.10 Updating crossbeam-deque v0.8.3 -> v0.8.4 Updating crossbeam-epoch v0.9.15 -> v0.9.17 Updating crossbeam-queue v0.3.8 -> v0.3.10 Updating crossbeam-utils v0.8.16 -> v0.8.18 Updating deranged v0.3.9 -> v0.3.10 Removing difflib v0.4.0 Removing float-cmp v0.9.0 Updating futures v0.3.29 -> v0.3.30 Updating futures-channel v0.3.29 -> v0.3.30 Updating futures-core v0.3.29 -> v0.3.30 Updating futures-executor v0.3.29 -> v0.3.30 Updating futures-io v0.3.29 -> v0.3.30 Updating futures-macro v0.3.29 -> v0.3.30 Updating futures-sink v0.3.29 -> v0.3.30 Updating futures-task v0.3.29 -> v0.3.30 Updating futures-util v0.3.29 -> v0.3.30 Updating http-body v0.4.5 -> v0.4.6 Updating hyper v0.14.27 -> v0.14.28 Adding itertools v0.11.0 Updating itoa v1.0.9 -> v1.0.10 Updating libc v0.2.150 -> v0.2.151 Removing memoffset v0.9.0 Updating mio v0.8.9 -> v0.8.10 Updating mockall v0.11.4 -> v0.12.1 Updating mockall_derive v0.11.4 -> v0.12.1 Removing normalize-line-endings v0.3.0 Updating object v0.32.1 -> v0.32.2 Updating once_cell v1.18.0 -> v1.19.0 Updating openssl v0.10.60 -> v0.10.62 Updating openssl-src v300.1.6+3.1.4 -> v300.2.1+3.2.0 Updating openssl-sys v0.9.96 -> v0.9.98 Updating pkg-config v0.3.27 -> v0.3.28 Updating predicates v2.1.5 -> v3.0.4 Updating proc-macro2 v1.0.70 -> v1.0.71 Updating reqwest v0.11.22 -> v0.11.23 Updating ring v0.17.6 -> v0.17.7 Updating rkyv v0.7.42 -> v0.7.43 Updating rkyv_derive v0.7.42 -> v0.7.43 Updating rustix v0.38.26 -> v0.38.28 Updating rustls v0.21.9 -> v0.21.10 Updating ryu v1.0.15 -> v1.0.16 Updating serde_spanned v0.6.4 -> v0.6.5 Removing socket2 v0.4.10 Updating syn v2.0.39 -> v2.0.43 Updating thiserror v1.0.50 -> v1.0.52 Updating thiserror-impl v1.0.50 -> v1.0.52 Updating time v0.3.30 -> v0.3.31 Updating time-macros v0.2.15 -> v0.2.16 Updating tokio v1.34.0 -> v1.35.1 Updating try-lock v0.2.4 -> v0.2.5 Updating unicode-bidi v0.3.13 -> v0.3.14 Updating winnow v0.5.19 -> v0.5.30 Updating zerocopy v0.7.28 -> v0.7.32 Updating zerocopy-derive v0.7.28 -> v0.7.32 ``` --- Cargo.lock | 363 ++++++++++++++++++++++++----------------------------- Cargo.toml | 2 +- 2 files changed, 165 insertions(+), 200 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4e3bb2f62..ac0e95cea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -93,9 +93,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab91ebe16eb252986481c5b62f6098f3b698a45e34b5b98200cf20dd2484a44" +checksum = "d664a92ecae85fd0a7392615844904654d1d5f5514837f471ddef4a057aba1b6" dependencies = [ "anstyle", "anstyle-parse", @@ -113,30 +113,30 @@ checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87" [[package]] name = "anstyle-parse" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "317b9a89c1868f5ea6ff1d9539a69f45dffc21ce321ac1fd1160dfa48c8e2140" +checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.0.0" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b" +checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] name = "anstyle-wincon" -version = "3.0.1" +version = "3.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0699d10d2f4d628a98ee7b57b289abbc98ff3bad977cb3152709d4bf2330628" +checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7" dependencies = [ "anstyle", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -179,13 +179,13 @@ dependencies = [ [[package]] name = "async-trait" -version = "0.1.74" +version = "0.1.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9" +checksum = "fdf6721fb0140e4f897002dd086c06f6c27775df19cfe1fccb21181a48fd2c98" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -264,7 +264,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -348,7 +348,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -386,9 +386,9 @@ dependencies = [ [[package]] name = "borsh" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf617fabf5cdbdc92f774bfe5062d870f228b80056d41180797abf48bed4056e" +checksum = "26d4d6dafc1a3bb54687538972158f07b2c948bc57d5890df22c0739098b3028" dependencies = [ "borsh-derive", "cfg_aliases", @@ -396,15 +396,15 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f404657a7ea7b5249e36808dff544bc88a28f26e0ac40009f674b7a009d14be3" +checksum = "bf4918709cc4dd777ad2b6303ed03cb37f3ca0ccede8c1b0d28ac6db8f4710e0" dependencies = [ "once_cell", "proc-macro-crate 2.0.0", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", "syn_derive", ] @@ -565,9 +565,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.10" +version = "4.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41fffed7514f420abec6d183b1d3acfd9099c79c3a10a06ade4f8203f1411272" +checksum = "bfaff671f6b22ca62406885ece523383b9b64022e341e53e009a62ebc47a45f2" dependencies = [ "clap_builder", "clap_derive", @@ -575,9 +575,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.4.9" +version = "4.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63361bae7eef3771745f02d8d892bec2fee5f6e34af316ba556e7f97a7069ff1" +checksum = "a216b506622bb1d316cd51328dce24e07bdff4a6128a47c7e7fad11878d5adbb" dependencies = [ "anstream", "anstyle", @@ -594,7 +594,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -690,7 +690,7 @@ dependencies = [ "criterion-plot", "futures", "is-terminal", - "itertools", + "itertools 0.10.5", "num-traits", "once_cell", "oorandom", @@ -712,14 +712,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" dependencies = [ "cast", - "itertools", + "itertools 0.10.5", ] [[package]] name = "crossbeam" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2801af0d36612ae591caa9568261fddce32ce6e08a7275ea334a06a4ad021a2c" +checksum = "6eb9105919ca8e40d437fc9cbb8f1975d916f1bd28afe795a48aae32a2cc8920" dependencies = [ "cfg-if", "crossbeam-channel", @@ -731,9 +731,9 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.8" +version = "0.5.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200" +checksum = "82a9b73a36529d9c47029b9fb3a6f0ea3cc916a261195352ba19e770fc1748b2" dependencies = [ "cfg-if", "crossbeam-utils", @@ -741,9 +741,9 @@ dependencies = [ [[package]] name = "crossbeam-deque" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef" +checksum = "fca89a0e215bab21874660c67903c5f143333cab1da83d041c7ded6053774751" dependencies = [ "cfg-if", "crossbeam-epoch", @@ -752,22 +752,20 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.15" +version = "0.9.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae211234986c545741a7dc064309f67ee1e5ad243d0e48335adc0484d960bcc7" +checksum = "0e3681d554572a651dda4186cd47240627c3d0114d45a95f6ad27f2f22e7548d" dependencies = [ "autocfg", "cfg-if", "crossbeam-utils", - "memoffset", - "scopeguard", ] [[package]] name = "crossbeam-queue" -version = "0.3.8" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1cfb3ea8a53f37c40dea2c7bedcbd88bdfae54f5e2175d6ecaff1c988353add" +checksum = "adc6598521bb5a83d491e8c1fe51db7296019d2ca3cb93cc6c2a20369a4d78a2" dependencies = [ "cfg-if", "crossbeam-utils", @@ -775,9 +773,9 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.16" +version = "0.8.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" +checksum = "c3a430a770ebd84726f584a90ee7f020d28db52c6d02138900f22341f866d39c" dependencies = [ "cfg-if", ] @@ -813,7 +811,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -824,14 +822,14 @@ checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ "darling_core", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] name = "deranged" -version = "0.3.9" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f32d04922c60427da6f9fef14d042d9edddef64cb9d4ce0d64d0685fbeb1fd3" +checksum = "8eb30d70a07a3b04884d2677f06bec33509dc67ca60d92949e5535352d3191dc" dependencies = [ "powerfmt", "serde", @@ -858,15 +856,9 @@ checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] -[[package]] -name = "difflib" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" - [[package]] name = "digest" version = "0.10.7" @@ -968,15 +960,6 @@ dependencies = [ "miniz_oxide", ] -[[package]] -name = "float-cmp" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" -dependencies = [ - "num-traits", -] - [[package]] name = "fnv" version = "1.0.7" @@ -1048,7 +1031,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -1060,7 +1043,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -1072,7 +1055,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -1083,9 +1066,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" [[package]] name = "futures" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0290714b38af9b4a7b094b8a37086d1b4e61f2df9122c3cad2577669145335" +checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" dependencies = [ "futures-channel", "futures-core", @@ -1098,9 +1081,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff4dd66668b557604244583e3e1e1eada8c5c2e96a6d0d6653ede395b78bbacb" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" dependencies = [ "futures-core", "futures-sink", @@ -1108,15 +1091,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" [[package]] name = "futures-executor" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f4fb8693db0cf099eadcca0efe2a5a22e4550f98ed16aba6c48700da29597bc" +checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" dependencies = [ "futures-core", "futures-task", @@ -1125,38 +1108,38 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bf34a163b5c4c52d0478a4d757da8fb65cabef42ba90515efee0f6f9fa45aaa" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" [[package]] name = "futures-macro" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53b153fd91e4b0147f4aced87be237c98248656bb01050b96bf3ee89220a8ddb" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] name = "futures-sink" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e36d3378ee38c2a36ad710c5d30c2911d752cb941c00c72dbabfb786a7970817" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" [[package]] name = "futures-task" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efd193069b0ddadc69c46389b740bbccdd97203899b48d09c5f7969591d6bae2" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" [[package]] name = "futures-util" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ "futures-channel", "futures-core", @@ -1296,9 +1279,9 @@ dependencies = [ [[package]] name = "http-body" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" +checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" dependencies = [ "bytes", "http", @@ -1325,9 +1308,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "0.14.27" +version = "0.14.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468" +checksum = "bf96e135eb83a2a8ddf766e426a841d8ddd7449d5f00d34ea02b41d2f19eef80" dependencies = [ "bytes", "futures-channel", @@ -1340,7 +1323,7 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "socket2 0.4.10", + "socket2", "tokio", "tower-service", "tracing", @@ -1428,7 +1411,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -1457,11 +1440,20 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" +dependencies = [ + "either", +] + [[package]] name = "itoa" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" +checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" [[package]] name = "jobserver" @@ -1579,9 +1571,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.150" +version = "0.2.151" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c" +checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" [[package]] name = "libloading" @@ -1676,15 +1668,6 @@ version = "2.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167" -[[package]] -name = "memoffset" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" -dependencies = [ - "autocfg", -] - [[package]] name = "mime" version = "0.3.17" @@ -1708,9 +1691,9 @@ dependencies = [ [[package]] name = "mio" -version = "0.8.9" +version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dce281c5e46beae905d4de1870d8b1509a9142b62eedf18b443b011ca8343d0" +checksum = "8f3d0b296e374a4e6f3c7b0a1f5a51d748a0d34c85e7dc48fc3fa9a87657fe09" dependencies = [ "libc", "wasi", @@ -1719,9 +1702,9 @@ dependencies = [ [[package]] name = "mockall" -version = "0.11.4" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c84490118f2ee2d74570d114f3d0493cbf02790df303d2707606c3e14e07c96" +checksum = "43766c2b5203b10de348ffe19f7e54564b64f3d6018ff7648d1e2d6d3a0f0a48" dependencies = [ "cfg-if", "downcast", @@ -1734,14 +1717,14 @@ dependencies = [ [[package]] name = "mockall_derive" -version = "0.11.4" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ce75669015c4f47b289fd4d4f56e894e4c96003ffdf3ac51313126f94c6cbb" +checksum = "af7cbce79ec385a1d4f54baa90a76401eb15d9cab93685f62e7e9f942aa00ae2" dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.43", ] [[package]] @@ -1774,7 +1757,7 @@ dependencies = [ "percent-encoding", "serde", "serde_json", - "socket2 0.5.5", + "socket2", "twox-hash", "url", ] @@ -1792,7 +1775,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", "termcolor", "thiserror", ] @@ -1903,12 +1886,6 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e9e591e719385e6ebaeb5ce5d3887f7d5676fceca6411d1925ccc95745f3d6f7" -[[package]] -name = "normalize-line-endings" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" - [[package]] name = "num-bigint" version = "0.4.4" @@ -1951,18 +1928,18 @@ dependencies = [ [[package]] name = "object" -version = "0.32.1" +version = "0.32.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0" +checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441" dependencies = [ "memchr", ] [[package]] name = "once_cell" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "oorandom" @@ -1972,9 +1949,9 @@ checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" [[package]] name = "openssl" -version = "0.10.60" +version = "0.10.62" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79a4c6c3a2b158f7f8f2a2fc5a969fa3a068df6fc9dbb4a43845436e3af7c800" +checksum = "8cde4d2d9200ad5909f8dac647e29482e07c3a35de8a13fce7c9c7747ad9f671" dependencies = [ "bitflags 2.4.1", "cfg-if", @@ -1993,7 +1970,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2004,18 +1981,18 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "300.1.6+3.1.4" +version = "300.2.1+3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439fac53e092cd7442a3660c85dde4643ab3b5bd39040912388dcdabf6b88085" +checksum = "3fe476c29791a5ca0d1273c697e96085bbabbbea2ef7afd5617e78a4b40332d3" dependencies = [ "cc", ] [[package]] name = "openssl-sys" -version = "0.9.96" +version = "0.9.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3812c071ba60da8b5677cc12bcb1d42989a65553772897a7e0355545a819838f" +checksum = "c1665caf8ab2dc9aef43d1c0023bd904633a6a05cb30b0ad59bec2ae986e57a7" dependencies = [ "cc", "libc", @@ -2116,7 +2093,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2185,7 +2162,7 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2202,9 +2179,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pkg-config" -version = "0.3.27" +version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" +checksum = "69d3587f8a9e599cc7ec2c00e331f71c4e69a5f9a4b8a6efd5b07466b9736f9a" [[package]] name = "plotters" @@ -2248,16 +2225,13 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "predicates" -version = "2.1.5" +version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59230a63c37f3e18569bdb90e4a89cbf5bf8b06fea0b84e65ea10cc4df47addd" +checksum = "6dfc28575c2e3f19cb3c73b93af36460ae898d426eba6fc15b9bd2a5220758a0" dependencies = [ - "difflib", - "float-cmp", - "itertools", - "normalize-line-endings", + "anstyle", + "itertools 0.11.0", "predicates-core", - "regex", ] [[package]] @@ -2321,9 +2295,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.70" +version = "1.0.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b" +checksum = "75cb1540fadbd5b8fbccc4dddad2734eba435053f725621c070711a14bb5f4b8" dependencies = [ "unicode-ident", ] @@ -2494,9 +2468,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.11.22" +version = "0.11.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "046cd98826c46c2ac8ddecae268eb5c2e58628688a5fc7a2643704a73faba95b" +checksum = "37b1ae8d9ac08420c66222fb9096fc5de435c3c48542bc5336c51892cffafb41" dependencies = [ "base64 0.21.5", "bytes", @@ -2532,9 +2506,9 @@ dependencies = [ [[package]] name = "ring" -version = "0.17.6" +version = "0.17.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "684d5e6e18f669ccebf64a92236bb7db9a34f07be010e3627368182027180866" +checksum = "688c63d65483050968b2a8937f7995f443e27041a0f7700aa59b0822aedebb74" dependencies = [ "cc", "getrandom", @@ -2546,12 +2520,13 @@ dependencies = [ [[package]] name = "rkyv" -version = "0.7.42" +version = "0.7.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0200c8230b013893c0b2d6213d6ec64ed2b9be2e0e016682b7224ff82cff5c58" +checksum = "527a97cdfef66f65998b5f3b637c26f5a5ec09cc52a3f9932313ac645f4190f5" dependencies = [ "bitvec", "bytecheck", + "bytes", "hashbrown 0.12.3", "ptr_meta", "rend", @@ -2563,9 +2538,9 @@ dependencies = [ [[package]] name = "rkyv_derive" -version = "0.7.42" +version = "0.7.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2e06b915b5c230a17d7a736d1e2e63ee753c256a8614ef3f5147b13a4f5541d" +checksum = "b5c462a1328c8e67e4d6dbad1eb0355dd43e8ab432c6e227a43657f16ade5033" dependencies = [ "proc-macro2", "quote", @@ -2646,9 +2621,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.26" +version = "0.38.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9470c4bf8246c8daf25f9598dca807fb6510347b1e1cfa55749113850c79d88a" +checksum = "72e572a5e8ca657d7366229cdde4bd14c4eb5499a9573d4d366fe1b599daa316" dependencies = [ "bitflags 2.4.1", "errno", @@ -2659,9 +2634,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.21.9" +version = "0.21.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "629648aced5775d558af50b2b4c7b02983a04b312126d45eeead26e7caa498b9" +checksum = "f9d5a6813c0759e4609cd494e8e725babae6a2ca7b62a5536a13daaec6fcb7ba" dependencies = [ "log", "ring", @@ -2696,9 +2671,9 @@ checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" [[package]] name = "ryu" -version = "1.0.15" +version = "1.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" +checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" [[package]] name = "same-file" @@ -2820,7 +2795,7 @@ checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2852,14 +2827,14 @@ checksum = "3081f5ffbb02284dda55132aa26daecedd7372a42417bbbab6f14ab7d6bb9145" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] name = "serde_spanned" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12022b835073e5b11e90a14f86838ceb1c8fb0325b72416845c487ac0fa95e80" +checksum = "eb3622f419d1296904700073ea6cc23ad690adbd66f13ea683df73298736f0c1" dependencies = [ "serde", ] @@ -2902,7 +2877,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -2969,16 +2944,6 @@ version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4dccd0940a2dcdf68d092b8cbab7dc0ad8fa938bf95787e1b916b0e3d0e8e970" -[[package]] -name = "socket2" -version = "0.4.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d" -dependencies = [ - "libc", - "winapi", -] - [[package]] name = "socket2" version = "0.5.5" @@ -3030,9 +2995,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.39" +version = "2.0.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" +checksum = "ee659fb5f3d355364e1f3e5bc10fb82068efbf824a1e9d1c9504244a6469ad53" dependencies = [ "proc-macro2", "quote", @@ -3048,7 +3013,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -3131,29 +3096,29 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.50" +version = "1.0.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2" +checksum = "83a48fd946b02c0a526b2e9481c8e2a17755e47039164a86c4070446e3a4614d" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.50" +version = "1.0.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" +checksum = "e7fbe9b594d6568a6a1443250a7e67d80b74e1e96f6d1715e1e21cc1888291d3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] name = "time" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4a34ab300f2dee6e562c10a046fc05e358b29f9bf92277f30c3c8d82275f6f5" +checksum = "f657ba42c3f86e7680e53c8cd3af8abbe56b5491790b46e22e19c0d57463583e" dependencies = [ "deranged", "itoa", @@ -3171,9 +3136,9 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ad70d68dba9e1f8aceda7aa6711965dfec1cac869f311a51bd08b3a2ccbce20" +checksum = "26197e33420244aeb70c3e8c78376ca46571bc4e701e4791c2cd9f57dcb3a43f" dependencies = [ "time-core", ] @@ -3205,9 +3170,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.34.0" +version = "1.35.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0c014766411e834f7af5b8f4cf46257aab4036ca95e9d2c144a10f59ad6f5b9" +checksum = "c89b4efa943be685f629b149f53829423f8f5531ea21249408e8e2f8671ec104" dependencies = [ "backtrace", "bytes", @@ -3216,7 +3181,7 @@ dependencies = [ "num_cpus", "pin-project-lite", "signal-hook-registry", - "socket2 0.5.5", + "socket2", "tokio-macros", "windows-sys 0.48.0", ] @@ -3229,7 +3194,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] @@ -3512,9 +3477,9 @@ dependencies = [ [[package]] name = "try-lock" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "twox-hash" @@ -3541,9 +3506,9 @@ checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" [[package]] name = "unicode-bidi" -version = "0.3.13" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" +checksum = "6f2528f27a9eb2b21e69c95319b30bd0efd85d09c379741b0f78ea1d86be2416" [[package]] name = "unicode-ident" @@ -3651,7 +3616,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", "wasm-bindgen-shared", ] @@ -3685,7 +3650,7 @@ checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -3880,9 +3845,9 @@ checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" [[package]] name = "winnow" -version = "0.5.19" +version = "0.5.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "829846f3e3db426d4cee4510841b71a8e58aa2a76b1132579487ae430ccd9c7b" +checksum = "9b5c3db89721d50d0e2a673f5043fc4722f76dcc352d7b1ab8b8288bed4ed2c5" dependencies = [ "memchr", ] @@ -3917,22 +3882,22 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.7.28" +version = "0.7.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d6f15f7ade05d2a4935e34a457b936c23dc70a05cc1d97133dc99e7a3fe0f0e" +checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.7.28" +version = "0.7.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbbad221e3f78500350ecbd7dfa4e63ef945c05f4c61cb7f4d3f84cd0bba649b" +checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.39", + "syn 2.0.43", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 4f2abd6f5..f2dd1fe96 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,7 +34,7 @@ aquatic_udp_protocol = "0" async-trait = "0" axum = { version = "0.6", features = ["macros"] } axum-client-ip = "0.4" -axum-server = { version = "0", features = ["tls-rustls"] } +axum-server = { version = "0.5", features = ["tls-rustls"] } binascii = "0" chrono = { version = "0", default-features = false, features = ["clock"] } config = "0" From 14cb26cebd729fb0e209eb1ab3d626f431efb83a Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 26 Dec 2023 18:20:52 +0800 Subject: [PATCH 0155/1297] chore: update deps to hyper v1 ``` Updating crates.io index Updating axum v0.6.20 -> v0.7.2 Updating axum-client-ip v0.4.2 -> v0.5.0 Updating axum-core v0.3.4 -> v0.4.1 Updating axum-macros v0.3.8 -> v0.4.0 Updating axum-server v0.5.1 -> v0.6.0 Adding h2 v0.4.0 Adding http-body-util v0.1.0 Removing http-range-header v0.3.1 Adding hyper-util v0.1.2 Updating rustls-pemfile v1.0.4 -> v2.0.0 Adding rustls-pki-types v1.1.0 Updating tower-http v0.4.4 -> v0.5.0 ``` --- Cargo.lock | 179 ++++++++++++++++++------ Cargo.toml | 10 +- src/servers/apis/server.rs | 30 ++-- src/servers/apis/v1/middlewares/auth.rs | 11 +- src/servers/health_check_api/server.rs | 22 ++- src/servers/http/v1/launcher.rs | 35 +++-- 6 files changed, 208 insertions(+), 79 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ac0e95cea..b696fc0d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -196,19 +196,20 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axum" -version = "0.6.20" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf" +checksum = "202651474fe73c62d9e0a56c6133f7a0ff1dc1c8cf7a5b03381af2a26553ac9d" dependencies = [ "async-trait", "axum-core", "axum-macros", - "bitflags 1.3.2", "bytes", "futures-util", - "http", - "http-body", - "hyper", + "http 1.0.0", + "http-body 1.0.0", + "http-body-util", + "hyper 1.1.0", + "hyper-util", "itoa", "matchit", "memchr", @@ -229,9 +230,9 @@ dependencies = [ [[package]] name = "axum-client-ip" -version = "0.4.2" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ef117890a418b7832678d9ea1e1c08456dd7b2fd1dadb9676cd6f0fe7eb4b21" +checksum = "0f5ffe4637708b326c621d5494ab6c91dcf62ee440fa6ee967d289315a9c6f81" dependencies = [ "axum", "forwarded-header-value", @@ -240,26 +241,29 @@ dependencies = [ [[package]] name = "axum-core" -version = "0.3.4" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "759fa577a247914fd3f7f76d62972792636412fbfd634cd452f6a385a74d2d2c" +checksum = "77cb22c689c44d4c07b0ab44ebc25d69d8ae601a2f28fb8d672d344178fa17aa" dependencies = [ "async-trait", "bytes", "futures-util", - "http", - "http-body", + "http 1.0.0", + "http-body 1.0.0", + "http-body-util", "mime", + "pin-project-lite", "rustversion", + "sync_wrapper", "tower-layer", "tower-service", ] [[package]] name = "axum-macros" -version = "0.3.8" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdca6a10ecad987bda04e95606ef85a5417dcaac1a78455242d72e031e2b6b62" +checksum = "5a2edad600410b905404c594e2523549f1bcd4bded1e252c8f74524ccce0b867" dependencies = [ "heck", "proc-macro2", @@ -269,21 +273,24 @@ dependencies = [ [[package]] name = "axum-server" -version = "0.5.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "447f28c85900215cc1bea282f32d4a2f22d55c5a300afdfbc661c8d6a632e063" +checksum = "c1ad46c3ec4e12f4a4b6835e173ba21c25e484c9d02b49770bf006ce5367c036" dependencies = [ "arc-swap", "bytes", "futures-util", - "http", - "http-body", - "hyper", + "http 1.0.0", + "http-body 1.0.0", + "http-body-util", + "hyper 1.1.0", + "hyper-util", "pin-project-lite", "rustls", "rustls-pemfile", "tokio", "tokio-rustls", + "tower", "tower-service", ] @@ -1197,7 +1204,26 @@ dependencies = [ "futures-core", "futures-sink", "futures-util", - "http", + "http 0.2.11", + "indexmap 2.1.0", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "h2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d308f63daf4181410c242d34c11f928dcb3aa105852019e043c9d1f4e4368a" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http 1.0.0", "indexmap 2.1.0", "slab", "tokio", @@ -1277,6 +1303,17 @@ dependencies = [ "itoa", ] +[[package]] +name = "http" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b32afd38673a8016f7c9ae69e5af41a58f81b1d31689040f2f1959594ce194ea" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + [[package]] name = "http-body" version = "0.4.6" @@ -1284,15 +1321,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" dependencies = [ "bytes", - "http", + "http 0.2.11", "pin-project-lite", ] [[package]] -name = "http-range-header" -version = "0.3.1" +name = "http-body" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" +dependencies = [ + "bytes", + "http 1.0.0", +] + +[[package]] +name = "http-body-util" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "add0ab9360ddbd88cfeb3bd9574a1d85cfdfa14db10b3e21d3700dbc4328758f" +checksum = "41cb79eb393015dadd30fc252023adb0b2400a0caee0fa2a077e6e21a551e840" +dependencies = [ + "bytes", + "futures-util", + "http 1.0.0", + "http-body 1.0.0", + "pin-project-lite", +] [[package]] name = "httparse" @@ -1316,9 +1370,9 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "h2", - "http", - "http-body", + "h2 0.3.22", + "http 0.2.11", + "http-body 0.4.6", "httparse", "httpdate", "itoa", @@ -1330,6 +1384,25 @@ dependencies = [ "want", ] +[[package]] +name = "hyper" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5aa53871fc917b1a9ed87b683a5d86db645e23acb32c2e0785a353e522fb75" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "h2 0.4.0", + "http 1.0.0", + "http-body 1.0.0", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "tokio", +] + [[package]] name = "hyper-tls" version = "0.5.0" @@ -1337,12 +1410,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" dependencies = [ "bytes", - "hyper", + "hyper 0.14.28", "native-tls", "tokio", "tokio-native-tls", ] +[[package]] +name = "hyper-util" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdea9aac0dbe5a9240d68cfd9501e2db94222c6dc06843e06640b9e07f0fdc67" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http 1.0.0", + "http-body 1.0.0", + "hyper 1.1.0", + "pin-project-lite", + "socket2", + "tokio", + "tracing", +] + [[package]] name = "iana-time-zone" version = "0.1.58" @@ -2477,10 +2568,10 @@ dependencies = [ "encoding_rs", "futures-core", "futures-util", - "h2", - "http", - "http-body", - "hyper", + "h2 0.3.22", + "http 0.2.11", + "http-body 0.4.6", + "hyper 0.14.28", "hyper-tls", "ipnet", "js-sys", @@ -2646,13 +2737,20 @@ dependencies = [ [[package]] name = "rustls-pemfile" -version = "1.0.4" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" +checksum = "35e4980fa29e4c4b212ffb3db068a564cbf560e51d3944b7c88bd8bf5bec64f4" dependencies = [ "base64 0.21.5", + "rustls-pki-types", ] +[[package]] +name = "rustls-pki-types" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9d979b3ce68192e42760c7810125eb6cf2ea10efae545a156063e61f314e2a" + [[package]] name = "rustls-webpki" version = "0.101.7" @@ -3323,7 +3421,7 @@ dependencies = [ "derive_more", "fern", "futures", - "hyper", + "hyper 1.1.0", "lazy_static", "local-ip-address", "log", @@ -3424,18 +3522,17 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.4.4" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c5bb1d698276a2443e5ecfabc1008bf15a36c12e6a7176e7bf089ea9131140" +checksum = "09e12e6351354851911bdf8c2b8f2ab15050c567d70a8b9a37ae7b8301a4080d" dependencies = [ "async-compression", "bitflags 2.4.1", "bytes", - "futures-core", "futures-util", - "http", - "http-body", - "http-range-header", + "http 1.0.0", + "http-body 1.0.0", + "http-body-util", "pin-project-lite", "tokio", "tokio-util", diff --git a/Cargo.toml b/Cargo.toml index f2dd1fe96..64f913e4f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,16 +32,16 @@ version = "3.0.0-alpha.12-develop" [dependencies] aquatic_udp_protocol = "0" async-trait = "0" -axum = { version = "0.6", features = ["macros"] } -axum-client-ip = "0.4" -axum-server = { version = "0.5", features = ["tls-rustls"] } +axum = { version = "0", features = ["macros"] } +axum-client-ip = "0" +axum-server = { version = "0", features = ["tls-rustls"] } binascii = "0" chrono = { version = "0", default-features = false, features = ["clock"] } config = "0" derive_more = "0" fern = "0" futures = "0" -hyper = "0" +hyper = "1" lazy_static = "1" log = { version = "0", features = ["release_max_level_info"] } multimap = "0" @@ -64,7 +64,7 @@ torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "pa torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12-develop", path = "contrib/bencode" } torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "packages/located-error" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } -tower-http = { version = "0.4", features = ["compression-full"] } +tower-http = { version = "0", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } [dev-dependencies] diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 58b60638e..c42083f9f 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -187,11 +187,19 @@ impl Launcher { { let app = router(tracker); + let handle = Handle::new(); + + let cloned_handle = handle.clone(); + + tokio::task::spawn(async move { + shutdown_signal.await; + cloned_handle.shutdown(); + }); + Box::pin(async { - axum::Server::from_tcp(tcp_listener) - .expect("Could not bind to tcp listener.") + axum_server::from_tcp(tcp_listener) + .handle(handle) .serve(app.into_make_service_with_connect_info::()) - .with_graceful_shutdown(shutdown_signal) .await .expect("Axum server crashed."); }) @@ -213,7 +221,7 @@ impl Launcher { let cloned_handle = handle.clone(); - tokio::task::spawn_local(async move { + tokio::task::spawn(async move { shutdown_signal.await; cloned_handle.shutdown(); }); @@ -237,15 +245,19 @@ impl Launcher { /// # Panics /// /// It would panic if it fails to listen to shutdown signal. -pub fn start(socket_addr: SocketAddr, tracker: Arc) -> impl Future> { +pub fn start(socket_addr: SocketAddr, tracker: Arc) -> impl Future> { let app = router(tracker); - let server = axum::Server::bind(&socket_addr).serve(app.into_make_service()); + let handle = Handle::new(); + let shutdown_handle = handle.clone(); - server.with_graceful_shutdown(async move { + tokio::spawn(async move { tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust APIs server on http://{} ...", socket_addr); - }) + info!("Stopping Torrust APIs server on https://{} ...", socket_addr); + shutdown_handle.shutdown(); + }); + + axum_server::bind(socket_addr).handle(handle).serve(app.into_make_service()) } /// Starts the API server with graceful shutdown and TLS on the current thread. diff --git a/src/servers/apis/v1/middlewares/auth.rs b/src/servers/apis/v1/middlewares/auth.rs index 3e8f74d0c..7749b3b34 100644 --- a/src/servers/apis/v1/middlewares/auth.rs +++ b/src/servers/apis/v1/middlewares/auth.rs @@ -40,15 +40,12 @@ pub struct QueryParams { /// Middleware for authentication using a "token" GET param. /// The token must be one of the tokens in the tracker [HTTP API configuration](torrust_tracker_configuration::HttpApi). -pub async fn auth( +pub async fn auth( State(config): State>, Query(params): Query, - request: Request, - next: Next, -) -> Response -where - B: Send, -{ + request: Request, + next: Next, +) -> Response { let Some(token) = params.token else { return AuthError::Unauthorized.into_response(); }; diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index 562772a87..d4654d617 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -7,6 +7,7 @@ use std::sync::Arc; use axum::routing::get; use axum::{Json, Router}; +use axum_server::Handle; use futures::Future; use log::info; use serde_json::json; @@ -25,23 +26,30 @@ pub fn start( socket_addr: SocketAddr, tx: Sender, config: Arc, -) -> impl Future> { +) -> impl Future> { let app = Router::new() .route("/", get(|| async { Json(json!({})) })) .route("/health_check", get(health_check_handler)) .with_state(config); - let server = axum::Server::bind(&socket_addr).serve(app.into_make_service()); + let handle = Handle::new(); + let cloned_handle = handle.clone(); - let bound_addr = server.local_addr(); + let tcp_listener = std::net::TcpListener::bind(socket_addr).expect("Could not bind tcp_listener to address."); + let bound_addr = tcp_listener + .local_addr() + .expect("Could not get local_addr from tcp_listener."); - info!("Health Check API server listening on http://{}", bound_addr); - - let running = server.with_graceful_shutdown(async move { + tokio::task::spawn(async move { tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust Health Check API server o http://{} ...", socket_addr); + info!("Stopping Torrust Health Check API server o http://{} ...", bound_addr); + cloned_handle.shutdown(); }); + let running = axum_server::from_tcp(tcp_listener) + .handle(handle) + .serve(app.into_make_service_with_connect_info::()); + tx.send(ApiServerJobStarted { bound_addr }) .expect("the Health Check API server should not be dropped"); diff --git a/src/servers/http/v1/launcher.rs b/src/servers/http/v1/launcher.rs index 1ae09a5f8..6b89e8ce7 100644 --- a/src/servers/http/v1/launcher.rs +++ b/src/servers/http/v1/launcher.rs @@ -40,11 +40,19 @@ impl Launcher { { let app = router(tracker); + let handle = Handle::new(); + + let cloned_handle = handle.clone(); + + tokio::task::spawn(async move { + shutdown_signal.await; + cloned_handle.shutdown(); + }); + Box::pin(async { - axum::Server::from_tcp(tcp_listener) - .expect("Could not bind to tcp listener.") - .serve(app.into_make_service_with_connect_info::()) - .with_graceful_shutdown(shutdown_signal) + axum_server::from_tcp(tcp_listener) + .handle(handle) + .serve(app.into_make_service_with_connect_info::()) .await .expect("Axum server crashed."); }) @@ -73,7 +81,7 @@ impl Launcher { let cloned_handle = handle.clone(); - tokio::task::spawn_local(async move { + tokio::task::spawn(async move { shutdown_signal.await; cloned_handle.shutdown(); }); @@ -135,15 +143,22 @@ impl HttpServerLauncher for Launcher { /// # Panics /// /// Panics if the server could not listen to shutdown (ctrl+c) signal. -pub fn start(socket_addr: std::net::SocketAddr, tracker: Arc) -> impl Future> { +pub fn start(socket_addr: std::net::SocketAddr, tracker: Arc) -> impl Future> { let app = router(tracker); - let server = axum::Server::bind(&socket_addr).serve(app.into_make_service_with_connect_info::()); + let handle = Handle::new(); + + let cloned_handle = handle.clone(); - server.with_graceful_shutdown(async move { + tokio::task::spawn(async move { tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust HTTP tracker server on http://{} ...", socket_addr); - }) + info!("Stopping Torrust Health Check API server o http://{} ...", socket_addr); + cloned_handle.shutdown(); + }); + + axum_server::bind(socket_addr) + .handle(handle) + .serve(app.into_make_service_with_connect_info::()) } /// Starts a new HTTPS server instance. From 922a46d7c5a8485dea05050851ceef1e3a138a5b Mon Sep 17 00:00:00 2001 From: Shrirang Borde <68811459+ShrirangB@users.noreply.github.com> Date: Tue, 26 Dec 2023 22:52:20 +0530 Subject: [PATCH 0156/1297] Update labels.json #503 Added good first issue label #503 in label.json file --- .github/labels.json | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/labels.json b/.github/labels.json index 3b8a2af42..778c0c892 100644 --- a/.github/labels.json +++ b/.github/labels.json @@ -250,5 +250,11 @@ "color": "eae3e7", "description": "You can still do it another way", "aliases": [] + }, + { + "name": "good first issue", + "color": "b0fc38", + "description": "Feel free to seek assistance when needed", + "aliases": [] } -] \ No newline at end of file +] From 911708ce841123bfd7005845fdd7abebea2de3a9 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 31 Dec 2023 22:54:44 +1100 Subject: [PATCH 0157/1297] chore: fixup clippy and spelling --- cSpell.json | 3 ++- src/core/services/torrent.rs | 4 +--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/cSpell.json b/cSpell.json index c9b547c90..d09db93b7 100644 --- a/cSpell.json +++ b/cSpell.json @@ -129,7 +129,8 @@ "Xtorrent", "Xunlei", "xxxxxxxxxxxxxxxxxxxxd", - "yyyyyyyyyyyyyyyyyyyyd" + "yyyyyyyyyyyyyyyyyyyyd", + "nvCFlJCq7fz7Qx6KoKTDiMZvns8l5Kw7" ], "enableFiletypes": [ "dockerfile", diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 918a80bae..f88cf5b50 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -97,9 +97,7 @@ pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Op let torrent_entry_option = db.get(info_hash); - let Some(torrent_entry) = torrent_entry_option else { - return None; - }; + let torrent_entry = torrent_entry_option?; let (seeders, completed, leechers) = torrent_entry.get_stats(); From f4c762b799ff3a97feb0345dce4a762864b34f40 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 31 Dec 2023 22:56:00 +1100 Subject: [PATCH 0158/1297] chore: update cargo deps ``` Updating crates.io index Updating ahash v0.8.6 -> v0.8.7 Updating async-trait v0.1.75 -> v0.1.76 Updating axum v0.7.2 -> v0.7.3 Updating axum-core v0.4.1 -> v0.4.2 Updating clap v4.4.11 -> v4.4.12 Updating clap_builder v4.4.11 -> v4.4.12 Updating deranged v0.3.10 -> v0.3.11 Updating iana-time-zone v0.1.58 -> v0.1.59 Updating is-terminal v0.4.9 -> v0.4.10 Updating memchr v2.6.4 -> v2.7.1 Updating proc-macro2 v1.0.71 -> v1.0.72 Updating schannel v0.1.22 -> v0.1.23 Updating serde_bytes v0.11.12 -> v0.11.13 Updating tempfile v3.8.1 -> v3.9.0 Updating thiserror v1.0.52 -> v1.0.53 Updating thiserror-impl v1.0.52 -> v1.0.53 Updating windows-core v0.51.1 -> v0.52.0 Updating winnow v0.5.30 -> v0.5.31 ``` --- Cargo.lock | 86 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 44 insertions(+), 42 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b696fc0d2..4e5be3291 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -30,9 +30,9 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.6" +version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91429305e9f0a25f6205c5b8e0d2db09e0708a7a6df0f42212bb56c32c8ac97a" +checksum = "77c3a9648d43b9cd48db467b3f87fdd6e146bcc88ab0180006cef2179fe11d01" dependencies = [ "cfg-if", "once_cell", @@ -179,9 +179,9 @@ dependencies = [ [[package]] name = "async-trait" -version = "0.1.75" +version = "0.1.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdf6721fb0140e4f897002dd086c06f6c27775df19cfe1fccb21181a48fd2c98" +checksum = "531b97fb4cd3dfdce92c35dedbfdc1f0b9d8091c8ca943d6dae340ef5012d514" dependencies = [ "proc-macro2", "quote", @@ -196,9 +196,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axum" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202651474fe73c62d9e0a56c6133f7a0ff1dc1c8cf7a5b03381af2a26553ac9d" +checksum = "d09dbe0e490df5da9d69b36dca48a76635288a82f92eca90024883a56202026d" dependencies = [ "async-trait", "axum-core", @@ -226,6 +226,7 @@ dependencies = [ "tower", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -241,9 +242,9 @@ dependencies = [ [[package]] name = "axum-core" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77cb22c689c44d4c07b0ab44ebc25d69d8ae601a2f28fb8d672d344178fa17aa" +checksum = "e87c8503f93e6d144ee5690907ba22db7ba79ab001a932ab99034f0fe836b3df" dependencies = [ "async-trait", "bytes", @@ -257,6 +258,7 @@ dependencies = [ "sync_wrapper", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -572,9 +574,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.11" +version = "4.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfaff671f6b22ca62406885ece523383b9b64022e341e53e009a62ebc47a45f2" +checksum = "dcfab8ba68f3668e89f6ff60f5b205cea56aa7b769451a59f34b8682f51c056d" dependencies = [ "clap_builder", "clap_derive", @@ -582,9 +584,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.4.11" +version = "4.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a216b506622bb1d316cd51328dce24e07bdff4a6128a47c7e7fad11878d5adbb" +checksum = "fb7fb5e4e979aec3be7791562fcba452f94ad85e954da024396433e0e25a79e9" dependencies = [ "anstream", "anstyle", @@ -834,9 +836,9 @@ dependencies = [ [[package]] name = "deranged" -version = "0.3.10" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eb30d70a07a3b04884d2677f06bec33509dc67ca60d92949e5535352d3191dc" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" dependencies = [ "powerfmt", "serde", @@ -1252,7 +1254,7 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" dependencies = [ - "ahash 0.8.6", + "ahash 0.8.7", ] [[package]] @@ -1261,7 +1263,7 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" dependencies = [ - "ahash 0.8.6", + "ahash 0.8.7", "allocator-api2", ] @@ -1436,9 +1438,9 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.58" +version = "0.1.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8326b86b6cff230b97d0d312a6c40a60726df3332e721f72a1b035f451663b20" +checksum = "b6a67363e2aa4443928ce15e57ebae94fd8949958fd1223c4cfc0cd473ad7539" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -1513,13 +1515,13 @@ checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" [[package]] name = "is-terminal" -version = "0.4.9" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" +checksum = "0bad00257d07be169d870ab665980b06cdb366d792ad690bf2e76876dc503455" dependencies = [ "hermit-abi", "rustix", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -1755,9 +1757,9 @@ checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" [[package]] name = "memchr" -version = "2.6.4" +version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167" +checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" [[package]] name = "mime" @@ -2386,9 +2388,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.71" +version = "1.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75cb1540fadbd5b8fbccc4dddad2734eba435053f725621c070711a14bb5f4b8" +checksum = "a293318316cf6478ec1ad2a21c49390a8d5b5eae9fab736467d93fbc0edc29c5" dependencies = [ "unicode-ident", ] @@ -2790,11 +2792,11 @@ checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" [[package]] name = "schannel" -version = "0.1.22" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" +checksum = "fbc91545643bcf3a0bbb6569265615222618bdf33ce4ffbbd13c4bbd4c093534" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -2878,9 +2880,9 @@ dependencies = [ [[package]] name = "serde_bytes" -version = "0.11.12" +version = "0.11.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab33ec92f677585af6d88c65593ae2375adde54efdbf16d597f2cbc7a6d368ff" +checksum = "8bb1879ea93538b78549031e2d54da3e901fd7e75f2e4dc758d760937b123d10" dependencies = [ "serde", ] @@ -3166,15 +3168,15 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.8.1" +version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" +checksum = "01ce4141aa927a6d1bd34a041795abd0db1cccba5d5f24b009f694bdf3a1f3fa" dependencies = [ "cfg-if", "fastrand", "redox_syscall", "rustix", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -3194,18 +3196,18 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.52" +version = "1.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83a48fd946b02c0a526b2e9481c8e2a17755e47039164a86c4070446e3a4614d" +checksum = "b2cd5904763bad08ad5513ddbb12cf2ae273ca53fa9f68e843e236ec6dfccc09" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.52" +version = "1.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7fbe9b594d6568a6a1443250a7e67d80b74e1e96f6d1715e1e21cc1888291d3" +checksum = "3dcf4a824cce0aeacd6f38ae6f24234c8e80d68632338ebaa1443b5df9e29e19" dependencies = [ "proc-macro2", "quote", @@ -3801,11 +3803,11 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-core" -version = "0.51.1" +version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1f8cf84f35d2db49a46868f947758c7a1138116f7fac3bc844f43ade1292e64" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ - "windows-targets 0.48.5", + "windows-targets 0.52.0", ] [[package]] @@ -3942,9 +3944,9 @@ checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" [[package]] name = "winnow" -version = "0.5.30" +version = "0.5.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b5c3db89721d50d0e2a673f5043fc4722f76dcc352d7b1ab8b8288bed4ed2c5" +checksum = "97a4882e6b134d6c28953a387571f1acdd3496830d5e36c5e3a1075580ea641c" dependencies = [ "memchr", ] From 46e67a86c7e2861cc924713df0e049468b434817 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 2 Jan 2024 14:33:52 +0000 Subject: [PATCH 0159/1297] refactor: [#262] split global consts for limits Current const: `crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS` `MAX_SCRAPE_TORRENTS` is the limit only for the number of torrents in a `scrape`request. New const: `crate::core::TORRENT_PEERS_LIMIT` `TORRENT_PEERS_LIMIT` is now the limit for the number of peers in an announce request (UDP and HTTP tracker). Besides, the endpoint to get the torrent details in the API does not limit the number of peers for the torrent. So the API returns all peers in the tracker. This could lead to performance issues and we might need to paginate results, but the API should either return all peers and paginate them in a new endpoint. --- src/core/mod.rs | 21 +++++--- src/core/torrent/mod.rs | 79 +++++++++++++++++++------------ src/core/torrent/repository.rs | 10 ++-- src/servers/http/mod.rs | 4 +- src/servers/udp/handlers.rs | 12 ++--- src/shared/bit_torrent/common.rs | 1 - tests/servers/http/v1/contract.rs | 8 ++-- 7 files changed, 79 insertions(+), 56 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index caac5b1ea..01dd295a2 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -458,6 +458,9 @@ use crate::core::databases::Database; use crate::core::torrent::{SwarmMetadata, SwarmStats}; use crate::shared::bit_torrent::info_hash::InfoHash; +/// The maximum number of returned peers for a torrent. +pub const TORRENT_PEERS_LIMIT: usize = 74; + /// The domain layer tracker service. /// /// Its main responsibility is to handle the `announce` and `scrape` requests. @@ -623,7 +626,7 @@ impl Tracker { let swarm_stats = self.update_torrent_with_peer_and_get_stats(info_hash, peer).await; - let peers = self.get_peers_for_peer(info_hash, peer).await; + let peers = self.get_torrent_peers_for_peer(info_hash, peer).await; AnnounceData { peers, @@ -692,24 +695,28 @@ impl Tracker { Ok(()) } - async fn get_peers_for_peer(&self, info_hash: &InfoHash, peer: &Peer) -> Vec { + async fn get_torrent_peers_for_peer(&self, info_hash: &InfoHash, peer: &Peer) -> Vec { let read_lock = self.torrents.get_torrents().await; match read_lock.get(info_hash) { None => vec![], - Some(entry) => entry.get_peers_for_peer(peer).into_iter().copied().collect(), + Some(entry) => entry + .get_peers_for_peer(peer, TORRENT_PEERS_LIMIT) + .into_iter() + .copied() + .collect(), } } /// # Context: Tracker /// /// Get all torrent peers for a given torrent - pub async fn get_all_torrent_peers(&self, info_hash: &InfoHash) -> Vec { + pub async fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec { let read_lock = self.torrents.get_torrents().await; match read_lock.get(info_hash) { None => vec![], - Some(entry) => entry.get_all_peers().into_iter().copied().collect(), + Some(entry) => entry.get_peers(TORRENT_PEERS_LIMIT).into_iter().copied().collect(), } } @@ -1253,7 +1260,7 @@ mod tests { tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; - let peers = tracker.get_all_torrent_peers(&info_hash).await; + let peers = tracker.get_torrent_peers(&info_hash).await; assert_eq!(peers, vec![peer]); } @@ -1267,7 +1274,7 @@ mod tests { tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; - let peers = tracker.get_peers_for_peer(&info_hash, &peer).await; + let peers = tracker.get_torrent_peers_for_peer(&info_hash, &peer).await; assert_eq!(peers, vec![]); } diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index a49e218a9..79828d368 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -36,7 +36,6 @@ use aquatic_udp_protocol::AnnounceEvent; use serde::{Deserialize, Serialize}; use super::peer::{self, Peer}; -use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; use crate::shared::clock::{Current, TimeNow}; /// A data structure containing all the information about a torrent in the tracker. @@ -100,7 +99,7 @@ impl Entry { /// /// The number of peers that have complete downloading is synchronously updated when peers are updated. /// That's the total torrent downloads counter. - pub fn update_peer(&mut self, peer: &peer::Peer) -> bool { + pub fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool { let mut did_torrent_stats_change: bool = false; match peer.event { @@ -123,26 +122,44 @@ impl Entry { did_torrent_stats_change } - /// Get all swarm peers, limiting the result to the maximum number of scrape - /// torrents. + /// Get all swarm peers. #[must_use] pub fn get_all_peers(&self) -> Vec<&peer::Peer> { - self.peers.values().take(MAX_SCRAPE_TORRENTS as usize).collect() + self.peers.values().collect() + } + + /// Get swarm peers, limiting the result. + #[must_use] + pub fn get_peers(&self, limit: usize) -> Vec<&peer::Peer> { + self.peers.values().take(limit).collect() + } + + /// It returns the list of peers for a given peer client. + /// + /// It filters out the input peer, typically because we want to return this + /// list of peers to that client peer. + #[must_use] + pub fn get_all_peers_for_peer(&self, client: &Peer) -> Vec<&peer::Peer> { + self.peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer.peer_addr != client.peer_addr) + .collect() } /// It returns the list of peers for a given peer client, limiting the - /// result to the maximum number of scrape torrents. + /// result. /// /// It filters out the input peer, typically because we want to return this /// list of peers to that client peer. #[must_use] - pub fn get_peers_for_peer(&self, client: &Peer) -> Vec<&peer::Peer> { + pub fn get_peers_for_peer(&self, client: &Peer, limit: usize) -> Vec<&peer::Peer> { self.peers .values() // Take peers which are not the client peer .filter(|peer| peer.peer_addr != client.peer_addr) // Limit the number of peers on the result - .take(MAX_SCRAPE_TORRENTS as usize) + .take(limit) .collect() } @@ -193,8 +210,8 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - use crate::core::peer; use crate::core::torrent::Entry; + use crate::core::{peer, TORRENT_PEERS_LIMIT}; use crate::shared::clock::{Current, DurationSinceUnixEpoch, Stopped, StoppedTime, Time, Working}; struct TorrentPeerBuilder { @@ -275,7 +292,7 @@ mod tests { let mut torrent_entry = Entry::new(); let torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.update_peer(&torrent_peer); // Add the peer + torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer assert_eq!(*torrent_entry.get_all_peers()[0], torrent_peer); assert_eq!(torrent_entry.get_all_peers().len(), 1); @@ -286,7 +303,7 @@ mod tests { let mut torrent_entry = Entry::new(); let torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.update_peer(&torrent_peer); // Add the peer + torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer assert_eq!(torrent_entry.get_all_peers(), vec![&torrent_peer]); } @@ -295,10 +312,10 @@ mod tests { fn a_peer_can_be_updated_in_a_torrent_entry() { let mut torrent_entry = Entry::new(); let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.update_peer(&torrent_peer); // Add the peer + torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer torrent_peer.event = AnnounceEvent::Completed; // Update the peer - torrent_entry.update_peer(&torrent_peer); // Update the peer in the torrent entry + torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry assert_eq!(torrent_entry.get_all_peers()[0].event, AnnounceEvent::Completed); } @@ -307,10 +324,10 @@ mod tests { fn a_peer_should_be_removed_from_a_torrent_entry_when_the_peer_announces_it_has_stopped() { let mut torrent_entry = Entry::new(); let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.update_peer(&torrent_peer); // Add the peer + torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer torrent_peer.event = AnnounceEvent::Stopped; // Update the peer - torrent_entry.update_peer(&torrent_peer); // Update the peer in the torrent entry + torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry assert_eq!(torrent_entry.get_all_peers().len(), 0); } @@ -320,10 +337,10 @@ mod tests { let mut torrent_entry = Entry::new(); let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.update_peer(&torrent_peer); // Add the peer + torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer torrent_peer.event = AnnounceEvent::Completed; // Update the peer - let stats_have_changed = torrent_entry.update_peer(&torrent_peer); // Update the peer in the torrent entry + let stats_have_changed = torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry assert!(stats_have_changed); } @@ -335,7 +352,7 @@ mod tests { let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); // Add a peer that did not exist before in the entry - let torrent_stats_have_not_changed = !torrent_entry.update_peer(&torrent_peer_announcing_complete_event); + let torrent_stats_have_not_changed = !torrent_entry.insert_or_update_peer(&torrent_peer_announcing_complete_event); assert!(torrent_stats_have_not_changed); } @@ -346,10 +363,10 @@ mod tests { let mut torrent_entry = Entry::new(); let peer_socket_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); let torrent_peer = TorrentPeerBuilder::default().with_peer_address(peer_socket_address).into(); - torrent_entry.update_peer(&torrent_peer); // Add peer + torrent_entry.insert_or_update_peer(&torrent_peer); // Add peer // Get peers excluding the one we have just added - let peers = torrent_entry.get_peers_for_peer(&torrent_peer); + let peers = torrent_entry.get_all_peers_for_peer(&torrent_peer); assert_eq!(peers.len(), 0); } @@ -364,16 +381,16 @@ mod tests { let torrent_peer_1 = TorrentPeerBuilder::default() .with_peer_address(SocketAddr::new(peer_ip, 8080)) .into(); - torrent_entry.update_peer(&torrent_peer_1); + torrent_entry.insert_or_update_peer(&torrent_peer_1); // Add peer 2 let torrent_peer_2 = TorrentPeerBuilder::default() .with_peer_address(SocketAddr::new(peer_ip, 8081)) .into(); - torrent_entry.update_peer(&torrent_peer_2); + torrent_entry.insert_or_update_peer(&torrent_peer_2); // Get peers for peer 1 - let peers = torrent_entry.get_peers_for_peer(&torrent_peer_1); + let peers = torrent_entry.get_all_peers_for_peer(&torrent_peer_1); // The peer 2 using the same IP but different port should be included assert_eq!(peers[0].peer_addr.ip(), Ipv4Addr::new(127, 0, 0, 1)); @@ -397,10 +414,10 @@ mod tests { let torrent_peer = TorrentPeerBuilder::default() .with_peer_id(peer_id_from_i32(peer_number)) .into(); - torrent_entry.update_peer(&torrent_peer); + torrent_entry.insert_or_update_peer(&torrent_peer); } - let peers = torrent_entry.get_all_peers(); + let peers = torrent_entry.get_peers(TORRENT_PEERS_LIMIT); assert_eq!(peers.len(), 74); } @@ -410,7 +427,7 @@ mod tests { let mut torrent_entry = Entry::new(); let torrent_seeder = a_torrent_seeder(); - torrent_entry.update_peer(&torrent_seeder); // Add seeder + torrent_entry.insert_or_update_peer(&torrent_seeder); // Add seeder assert_eq!(torrent_entry.get_stats().0, 1); } @@ -420,7 +437,7 @@ mod tests { let mut torrent_entry = Entry::new(); let torrent_leecher = a_torrent_leecher(); - torrent_entry.update_peer(&torrent_leecher); // Add leecher + torrent_entry.insert_or_update_peer(&torrent_leecher); // Add leecher assert_eq!(torrent_entry.get_stats().2, 1); } @@ -430,11 +447,11 @@ mod tests { ) { let mut torrent_entry = Entry::new(); let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.update_peer(&torrent_peer); // Add the peer + torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer // Announce "Completed" torrent download event. torrent_peer.event = AnnounceEvent::Completed; - torrent_entry.update_peer(&torrent_peer); // Update the peer + torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer let number_of_previously_known_peers_with_completed_torrent = torrent_entry.get_stats().1; @@ -448,7 +465,7 @@ mod tests { // Announce "Completed" torrent download event. // It's the first event announced from this peer. - torrent_entry.update_peer(&torrent_peer_announcing_complete_event); // Add the peer + torrent_entry.insert_or_update_peer(&torrent_peer_announcing_complete_event); // Add the peer let number_of_peers_with_completed_torrent = torrent_entry.get_stats().1; @@ -468,7 +485,7 @@ mod tests { let inactive_peer = TorrentPeerBuilder::default() .updated_at(timeout_seconds_before_now.sub(Duration::from_secs(1))) .into(); - torrent_entry.update_peer(&inactive_peer); // Add the peer + torrent_entry.insert_or_update_peer(&inactive_peer); // Add the peer torrent_entry.remove_inactive_peers(timeout); diff --git a/src/core/torrent/repository.rs b/src/core/torrent/repository.rs index 62df9b510..ac3d03054 100644 --- a/src/core/torrent/repository.rs +++ b/src/core/torrent/repository.rs @@ -69,7 +69,7 @@ impl Repository for Sync { let (stats, stats_updated) = { let mut torrent_entry_lock = torrent_entry.lock().unwrap(); - let stats_updated = torrent_entry_lock.update_peer(peer); + let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); let stats = torrent_entry_lock.get_stats(); (stats, stats_updated) @@ -126,7 +126,7 @@ impl Repository for SyncSingle { std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), }; - let stats_updated = torrent_entry.update_peer(peer); + let stats_updated = torrent_entry.insert_or_update_peer(peer); let stats = torrent_entry.get_stats(); ( @@ -168,7 +168,7 @@ impl TRepositoryAsync for RepositoryAsync { let (stats, stats_updated) = { let mut torrent_entry_lock = torrent_entry.lock().await; - let stats_updated = torrent_entry_lock.update_peer(peer); + let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); let stats = torrent_entry_lock.get_stats(); (stats, stats_updated) @@ -226,7 +226,7 @@ impl TRepositoryAsync for AsyncSync { let (stats, stats_updated) = { let mut torrent_entry_lock = torrent_entry.lock().unwrap(); - let stats_updated = torrent_entry_lock.update_peer(peer); + let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); let stats = torrent_entry_lock.get_stats(); (stats, stats_updated) @@ -273,7 +273,7 @@ impl TRepositoryAsync for RepositoryAsyncSingle { let (stats, stats_updated) = { let mut torrents_lock = self.torrents.write().await; let torrent_entry = torrents_lock.entry(*info_hash).or_insert(Entry::new()); - let stats_updated = torrent_entry.update_peer(peer); + let stats_updated = torrent_entry.insert_or_update_peer(peer); let stats = torrent_entry.get_stats(); (stats, stats_updated) diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index 10666d8a5..b2d232fc6 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -71,7 +71,7 @@ //! is behind a reverse proxy. //! //! > **NOTICE**: the maximum number of peers that the tracker can return is -//! `74`. Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS). +//! `74`. Defined with a hardcoded const [`TORRENT_PEERS_LIMIT`](crate::core::TORRENT_PEERS_LIMIT). //! Refer to [issue 262](https://github.com/torrust/torrust-tracker/issues/262) //! for more information about this limitation. //! @@ -237,7 +237,7 @@ //! In order to scrape multiple torrents at the same time you can pass multiple //! `info_hash` parameters: `info_hash=%81%00%0...00%00%00&info_hash=%82%00%0...00%00%00` //! -//! > **NOTICE**: the maximum number of torrent you can scrape at the same time +//! > **NOTICE**: the maximum number of torrents you can scrape at the same time //! is `74`. Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS). //! //! **Sample response** diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 39a077466..a1461a457 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -598,7 +598,7 @@ mod tests { handle_announce(remote_addr, &request, &tracker).await.unwrap(); - let peers = tracker.get_all_torrent_peers(&info_hash.0.into()).await; + let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; let expected_peer = TorrentPeerBuilder::default() .with_peer_id(peer::Id(peer_id.0)) @@ -659,7 +659,7 @@ mod tests { handle_announce(remote_addr, &request, &tracker).await.unwrap(); - let peers = tracker.get_all_torrent_peers(&info_hash.0.into()).await; + let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); } @@ -763,7 +763,7 @@ mod tests { handle_announce(remote_addr, &request, &tracker).await.unwrap(); - let peers = tracker.get_all_torrent_peers(&info_hash.0.into()).await; + let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; let external_ip_in_tracker_configuration = tracker.config.external_ip.clone().unwrap().parse::().unwrap(); @@ -820,7 +820,7 @@ mod tests { handle_announce(remote_addr, &request, &tracker).await.unwrap(); - let peers = tracker.get_all_torrent_peers(&info_hash.0.into()).await; + let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; let expected_peer = TorrentPeerBuilder::default() .with_peer_id(peer::Id(peer_id.0)) @@ -884,7 +884,7 @@ mod tests { handle_announce(remote_addr, &request, &tracker).await.unwrap(); - let peers = tracker.get_all_torrent_peers(&info_hash.0.into()).await; + let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; // When using IPv6 the tracker converts the remote client ip into a IPv4 address assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); @@ -1001,7 +1001,7 @@ mod tests { handle_announce(remote_addr, &request, &tracker).await.unwrap(); - let peers = tracker.get_all_torrent_peers(&info_hash.0.into()).await; + let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; let _external_ip_in_tracker_configuration = tracker.config.external_ip.clone().unwrap().parse::().unwrap(); diff --git a/src/shared/bit_torrent/common.rs b/src/shared/bit_torrent/common.rs index 0ce345a3e..9bf9dfd3c 100644 --- a/src/shared/bit_torrent/common.rs +++ b/src/shared/bit_torrent/common.rs @@ -5,7 +5,6 @@ use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use serde::{Deserialize, Serialize}; /// The maximum number of torrents that can be returned in an `scrape` response. -/// It's also the maximum number of peers returned in an `announce` response. /// /// The [BEP 15. UDP Tracker Protocol for `BitTorrent`](https://www.bittorrent.org/beps/bep_0015.html) /// defines this limit: diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index d7f4d50cc..9a6aa2454 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -740,7 +740,7 @@ mod for_all_config_modes { client.announce(&announce_query).await; - let peers = test_env.tracker.get_all_torrent_peers(&info_hash).await; + let peers = test_env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), client_ip); @@ -776,7 +776,7 @@ mod for_all_config_modes { client.announce(&announce_query).await; - let peers = test_env.tracker.get_all_torrent_peers(&info_hash).await; + let peers = test_env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), test_env.tracker.config.get_ext_ip().unwrap()); @@ -812,7 +812,7 @@ mod for_all_config_modes { client.announce(&announce_query).await; - let peers = test_env.tracker.get_all_torrent_peers(&info_hash).await; + let peers = test_env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), test_env.tracker.config.get_ext_ip().unwrap()); @@ -846,7 +846,7 @@ mod for_all_config_modes { ) .await; - let peers = test_env.tracker.get_all_torrent_peers(&info_hash).await; + let peers = test_env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), IpAddr::from_str("150.172.238.178").unwrap()); From d03e930c1a842f46473cf3fb0d59e2638a0abfef Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 2 Jan 2024 15:55:53 +0000 Subject: [PATCH 0160/1297] feat!: [#536] remove always-empty peer list in torrent list item It's unused. --- src/servers/apis/v1/context/torrent/resources/torrent.rs | 5 ----- tests/servers/api/v1/contract/context/torrent.rs | 3 --- 2 files changed, 8 deletions(-) diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs index 74577a23e..fc43fbb7a 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs @@ -44,9 +44,6 @@ pub struct ListItem { /// The torrent's leechers counter. Active peers that are downloading the /// torrent. pub leechers: u64, - /// The torrent's peers. It's always `None` in the struct and `null` in the - /// JSON response. - pub peers: Option>, // todo: this is always None. Remove field from endpoint? } impl ListItem { @@ -90,7 +87,6 @@ impl From for ListItem { seeders: basic_info.seeders, completed: basic_info.completed, leechers: basic_info.leechers, - peers: None, } } } @@ -156,7 +152,6 @@ mod tests { seeders: 1, completed: 2, leechers: 3, - peers: None, } ); } diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index ab497787f..3cac55e6a 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -35,7 +35,6 @@ async fn should_allow_getting_torrents() { seeders: 1, completed: 0, leechers: 0, - peers: None, // Torrent list does not include the peer list for each torrent }], ) .await; @@ -65,7 +64,6 @@ async fn should_allow_limiting_the_torrents_in_the_result() { seeders: 1, completed: 0, leechers: 0, - peers: None, // Torrent list does not include the peer list for each torrent }], ) .await; @@ -95,7 +93,6 @@ async fn should_allow_the_torrents_result_pagination() { seeders: 1, completed: 0, leechers: 0, - peers: None, // Torrent list does not include the peer list for each torrent }], ) .await; From 02b64f2922b39cb6cc24867cf2e460fd7e2c7017 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 2 Jan 2024 17:02:52 +0000 Subject: [PATCH 0161/1297] refactor: [#343] remove deprecated function --- src/core/mod.rs | 56 ------------------------------------- src/servers/udp/error.rs | 4 +++ src/servers/udp/handlers.rs | 48 +++++++++++++------------------ 3 files changed, 23 insertions(+), 85 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 01dd295a2..beb4b133d 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -909,62 +909,6 @@ impl Tracker { Ok(()) } - /// It authenticates and authorizes a UDP tracker request. - /// - /// # Context: Authentication and Authorization - /// - /// # Errors - /// - /// Will return a `torrent::Error::PeerKeyNotValid` if the `key` is not valid. - /// - /// Will return a `torrent::Error::PeerNotAuthenticated` if the `key` is `None`. - /// - /// Will return a `torrent::Error::TorrentNotWhitelisted` if the the Tracker is in listed mode and the `info_hash` is not whitelisted. - #[deprecated(since = "3.0.0", note = "please use `authenticate` and `authorize` instead")] - pub async fn authenticate_request(&self, info_hash: &InfoHash, key: &Option) -> Result<(), Error> { - // todo: this is a deprecated method. - // We're splitting authentication and authorization responsibilities. - // Use `authenticate` and `authorize` instead. - - // Authentication - - // no authentication needed in public mode - if self.is_public() { - return Ok(()); - } - - // check if auth_key is set and valid - if self.is_private() { - match key { - Some(key) => { - if let Err(e) = self.verify_auth_key(key).await { - return Err(Error::PeerKeyNotValid { - key: key.clone(), - source: (Arc::new(e) as Arc).into(), - }); - } - } - None => { - return Err(Error::PeerNotAuthenticated { - location: Location::caller(), - }); - } - } - } - - // Authorization - - // check if info_hash is whitelisted - if self.is_whitelisted() && !self.is_info_hash_whitelisted(info_hash).await { - return Err(Error::TorrentNotWhitelisted { - info_hash: *info_hash, - location: Location::caller(), - }); - } - - Ok(()) - } - /// Right now, there is only authorization when the `Tracker` runs in /// `listed` or `private_listed` modes. /// diff --git a/src/servers/udp/error.rs b/src/servers/udp/error.rs index ce59cd015..fb7bb93f3 100644 --- a/src/servers/udp/error.rs +++ b/src/servers/udp/error.rs @@ -29,4 +29,8 @@ pub enum Error { BadRequest { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, }, + + /// Error returned when tracker requires authentication. + #[error("domain tracker requires authentication but is not supported in current UDP implementation. Location: {location}")] + TrackerAuthenticationRequired { location: &'static Location<'static> }, } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index a1461a457..f3c7b58b0 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -10,7 +10,7 @@ use aquatic_udp_protocol::{ use log::{debug, info}; use super::connection_cookie::{check, from_connection_id, into_connection_id, make}; -use crate::core::{statistics, Tracker}; +use crate::core::{statistics, ScrapeData, Tracker}; use crate::servers::udp::error::Error; use crate::servers::udp::peer_builder; use crate::servers::udp::request::AnnounceWrapper; @@ -99,22 +99,6 @@ pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, t Ok(Response::from(response)) } -/// It authenticates the request. It returns an error if the peer is not allowed -/// to make the request. -/// -/// # Errors -/// -/// Will return `Error` if unable to `authenticate_request`. -#[allow(deprecated)] -pub async fn authenticate(info_hash: &InfoHash, tracker: &Tracker) -> Result<(), Error> { - tracker - .authenticate_request(info_hash, &None) - .await - .map_err(|e| Error::TrackerError { - source: (Arc::new(e) as Arc).into(), - }) -} - /// It handles the `Announce` request. Refer to [`Announce`](crate::servers::udp#announce) /// request for more information. /// @@ -128,6 +112,13 @@ pub async fn handle_announce( ) -> Result { debug!("udp announce request: {:#?}", announce_request); + // Authentication + if tracker.requires_authentication() { + return Err(Error::TrackerAuthenticationRequired { + location: Location::caller(), + }); + } + check(&remote_addr, &from_connection_id(&announce_request.connection_id))?; let wrapped_announce_request = AnnounceWrapper::new(announce_request); @@ -135,7 +126,10 @@ pub async fn handle_announce( let info_hash = wrapped_announce_request.info_hash; let remote_client_ip = remote_addr.ip(); - authenticate(&info_hash, tracker).await?; + // Authorization + tracker.authorize(&info_hash).await.map_err(|e| Error::TrackerError { + source: (Arc::new(e) as Arc).into(), + })?; info!(target: "UDP", "\"ANNOUNCE TxID {} IH {}\"", announce_request.transaction_id.0, info_hash.to_hex_string()); @@ -222,28 +216,24 @@ pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tra info_hashes.push(InfoHash(info_hash.0)); } - let scrape_data = tracker.scrape(&info_hashes).await; + let scrape_data = if tracker.requires_authentication() { + ScrapeData::zeroed(&info_hashes) + } else { + tracker.scrape(&info_hashes).await + }; let mut torrent_stats: Vec = Vec::new(); for file in &scrape_data.files { - let info_hash = file.0; let swarm_metadata = file.1; - #[allow(deprecated)] - let scrape_entry = if tracker.authenticate_request(info_hash, &None).await.is_ok() { - #[allow(clippy::cast_possible_truncation)] + #[allow(clippy::cast_possible_truncation)] + let scrape_entry = { TorrentScrapeStatistics { seeders: NumberOfPeers(i64::from(swarm_metadata.complete) as i32), completed: NumberOfDownloads(i64::from(swarm_metadata.downloaded) as i32), leechers: NumberOfPeers(i64::from(swarm_metadata.incomplete) as i32), } - } else { - TorrentScrapeStatistics { - seeders: NumberOfPeers(0), - completed: NumberOfDownloads(0), - leechers: NumberOfPeers(0), - } }; torrent_stats.push(scrape_entry); From fc9bd77e236cad3106c90aeed708760f667ea621 Mon Sep 17 00:00:00 2001 From: Warm Beer Date: Wed, 3 Jan 2024 19:29:24 +0100 Subject: [PATCH 0162/1297] refactor: preload info hashes in wrk benchmark --- tests/wrk_benchmark_announce.lua | 71 +++++++++++++++++++++++--------- 1 file changed, 52 insertions(+), 19 deletions(-) diff --git a/tests/wrk_benchmark_announce.lua b/tests/wrk_benchmark_announce.lua index 620ba2680..c0bdac48d 100644 --- a/tests/wrk_benchmark_announce.lua +++ b/tests/wrk_benchmark_announce.lua @@ -1,34 +1,67 @@ +-- else the randomness would be the same every run +math.randomseed(os.time()) + +local charset = "0123456789ABCDEF" + +function hex_to_char(hex) + local n = tonumber(hex, 16) + local f = string.char(n) + return f +end + +function hex_string_to_char_string(hex) + local ret = {} + local r + for i = 0, 19 do + local x = i * 2 + r = hex:sub(x+1, x+2) + local f = hex_to_char(r) + table.insert(ret, f) + end + return table.concat(ret) +end + +function url_encode(str) + str = string.gsub (str, "([^0-9a-zA-Z !'()*._~-])", -- locale independent + function (c) return string.format ("%%%02X", string.byte(c)) end) + str = string.gsub (str, " ", "+") + return str +end + +function gen_hex_string(length) + local ret = {} + local r + for i = 1, length do + r = math.random(1, #charset) + table.insert(ret, charset:sub(r, r)) + end + return table.concat(ret) +end + +function random_info_hash() + local hexString = gen_hex_string(40) + local str = hex_string_to_char_string(hexString) + return url_encode(str) +end + function generate_unique_info_hashes(size) local result = {} - local seen = {} - - for i = 0, size - 1 do - local bytes = {} - bytes[1] = i & 0xFF - bytes[2] = (i >> 8) & 0xFF - bytes[3] = (i >> 16) & 0xFF - bytes[4] = (i >> 24) & 0xFF - - local info_hash = bytes - local key = table.concat(info_hash, ",") - - if not seen[key] then - table.insert(result, info_hash) - seen[key] = true - end + + for i = 1, size do + result[i] = random_info_hash() end return result end -info_hashes = generate_unique_info_hashes(10000000) +info_hashes = generate_unique_info_hashes(5000000) -index = 0 +index = 1 -- the request function that will run at each request request = function() path = "/announce?info_hash=" .. info_hashes[index] .. "&peer_id=-lt0D80-a%D4%10%19%99%A6yh%9A%E1%CD%96&port=54434&uploaded=885&downloaded=0&left=0&corrupt=0&key=A78381BD&numwant=200&compact=1&no_peer_id=1&supportcrypto=1&redundant=0" - index += 1 + index = index + 1 headers = {} headers["X-Forwarded-For"] = "1.1.1.1" return wrk.format("GET", path, headers) From 541a0729634d23108c5c4945eb81469f3a5911e0 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 4 Jan 2024 02:12:34 +1100 Subject: [PATCH 0163/1297] ci: add threshold to patch changes --- codecov.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/codecov.yaml b/codecov.yaml index f0878195b..aaa25bf74 100644 --- a/codecov.yaml +++ b/codecov.yaml @@ -4,3 +4,7 @@ coverage: default: target: auto threshold: 0.5% + patch: + default: + target: auto + threshold: 0.5% From 9a0919f085cde6119d1352152f0797aebec484d9 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 4 Jan 2024 11:55:02 +1100 Subject: [PATCH 0164/1297] chore: update cargo deps ``` Updating crates.io index Updating async-trait v0.1.76 -> v0.1.77 Updating clang-sys v1.6.1 -> v1.7.0 Updating libloading v0.7.4 -> v0.8.1 Updating proc-macro2 v1.0.72 -> v1.0.75 Updating quote v1.0.33 -> v1.0.35 Updating semver v1.0.20 -> v1.0.21 Updating serde v1.0.193 -> v1.0.194 Updating serde_bytes v0.11.13 -> v0.11.14 Updating serde_derive v1.0.193 -> v1.0.194 Updating serde_json v1.0.108 -> v1.0.110 Updating serde_path_to_error v0.1.14 -> v0.1.15 Updating serde_repr v0.1.17 -> v0.1.18 Updating syn v2.0.43 -> v2.0.47 Updating thiserror v1.0.53 -> v1.0.56 Updating thiserror-impl v1.0.53 -> v1.0.56 Updating winnow v0.5.31 -> v0.5.32 ``` --- Cargo.lock | 120 ++++++++++++++++++++++++++--------------------------- 1 file changed, 60 insertions(+), 60 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4e5be3291..9b7c10f39 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -179,13 +179,13 @@ dependencies = [ [[package]] name = "async-trait" -version = "0.1.76" +version = "0.1.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "531b97fb4cd3dfdce92c35dedbfdc1f0b9d8091c8ca943d6dae340ef5012d514" +checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -270,7 +270,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -357,7 +357,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -413,7 +413,7 @@ dependencies = [ "proc-macro-crate 2.0.0", "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", "syn_derive", ] @@ -563,9 +563,9 @@ dependencies = [ [[package]] name = "clang-sys" -version = "1.6.1" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c688fc74432808e3eb684cae8830a86be1d66a2bd58e1f248ed0960a590baf6f" +checksum = "67523a3b4be3ce1989d607a828d036249522dd9c1c8de7f4dd2dae43a37369d1" dependencies = [ "glob", "libc", @@ -603,7 +603,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -820,7 +820,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -831,7 +831,7 @@ checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ "darling_core", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -865,7 +865,7 @@ checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -1040,7 +1040,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -1052,7 +1052,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -1064,7 +1064,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -1129,7 +1129,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -1504,7 +1504,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -1670,12 +1670,12 @@ checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" [[package]] name = "libloading" -version = "0.7.4" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +checksum = "c571b676ddfc9a8c12f1f3d3085a7b163966a8fd8098a90640953ce5f6170161" dependencies = [ "cfg-if", - "winapi", + "windows-sys 0.48.0", ] [[package]] @@ -1817,7 +1817,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -1868,7 +1868,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", "termcolor", "thiserror", ] @@ -2063,7 +2063,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -2186,7 +2186,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -2255,7 +2255,7 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -2388,9 +2388,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.72" +version = "1.0.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a293318316cf6478ec1ad2a21c49390a8d5b5eae9fab736467d93fbc0edc29c5" +checksum = "907a61bd0f64c2f29cd1cf1dc34d05176426a3f504a78010f08416ddb7b13708" dependencies = [ "unicode-ident", ] @@ -2417,9 +2417,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.33" +version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] @@ -2855,15 +2855,15 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.20" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" +checksum = "b97ed7a9823b74f99c7742f5336af7be5ecd3eeafcb1507d1fa93347b1d589b0" [[package]] name = "serde" -version = "1.0.193" +version = "1.0.194" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89" +checksum = "0b114498256798c94a0689e1a15fec6005dee8ac1f41de56404b67afc2a4b773" dependencies = [ "serde_derive", ] @@ -2880,29 +2880,29 @@ dependencies = [ [[package]] name = "serde_bytes" -version = "0.11.13" +version = "0.11.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bb1879ea93538b78549031e2d54da3e901fd7e75f2e4dc758d760937b123d10" +checksum = "8b8497c313fd43ab992087548117643f6fcd935cbf36f176ffda0aacf9591734" dependencies = [ "serde", ] [[package]] name = "serde_derive" -version = "1.0.193" +version = "1.0.194" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" +checksum = "a3385e45322e8f9931410f01b3031ec534c3947d0e94c18049af4d9f9907d4e0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] name = "serde_json" -version = "1.0.108" +version = "1.0.110" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" +checksum = "6fbd975230bada99c8bb618e0c365c2eefa219158d5c6c29610fd09ff1833257" dependencies = [ "itoa", "ryu", @@ -2911,9 +2911,9 @@ dependencies = [ [[package]] name = "serde_path_to_error" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4beec8bce849d58d06238cb50db2e1c417cfeafa4c63f692b15c82b7c80f8335" +checksum = "ebd154a240de39fdebcf5775d2675c204d7c13cf39a4c697be6493c8e734337c" dependencies = [ "itoa", "serde", @@ -2921,13 +2921,13 @@ dependencies = [ [[package]] name = "serde_repr" -version = "0.1.17" +version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3081f5ffbb02284dda55132aa26daecedd7372a42417bbbab6f14ab7d6bb9145" +checksum = "0b2e6b945e9d3df726b65d6ee24060aff8e3533d431f677a9695db04eff9dfdb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -2977,7 +2977,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -3095,9 +3095,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.43" +version = "2.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee659fb5f3d355364e1f3e5bc10fb82068efbf824a1e9d1c9504244a6469ad53" +checksum = "1726efe18f42ae774cc644f330953a5e7b3c3003d3edcecf18850fe9d4dd9afb" dependencies = [ "proc-macro2", "quote", @@ -3113,7 +3113,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -3196,22 +3196,22 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.53" +version = "1.0.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2cd5904763bad08ad5513ddbb12cf2ae273ca53fa9f68e843e236ec6dfccc09" +checksum = "d54378c645627613241d077a3a79db965db602882668f9136ac42af9ecb730ad" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.53" +version = "1.0.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dcf4a824cce0aeacd6f38ae6f24234c8e80d68632338ebaa1443b5df9e29e19" +checksum = "fa0faa943b50f3db30a20aa7e265dbc66076993efed8463e8de414e5d06d3471" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -3294,7 +3294,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] @@ -3715,7 +3715,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", "wasm-bindgen-shared", ] @@ -3749,7 +3749,7 @@ checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -3944,9 +3944,9 @@ checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" [[package]] name = "winnow" -version = "0.5.31" +version = "0.5.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97a4882e6b134d6c28953a387571f1acdd3496830d5e36c5e3a1075580ea641c" +checksum = "8434aeec7b290e8da5c3f0d628cb0eac6cabcb31d14bb74f779a08109a5914d6" dependencies = [ "memchr", ] @@ -3996,7 +3996,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.43", + "syn 2.0.47", ] [[package]] From 13140f60dbd461fafb2ce234c6c968d7f23052ec Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 30 Dec 2023 18:38:25 +1100 Subject: [PATCH 0165/1297] dev: cleanup service bootstraping --- packages/configuration/src/lib.rs | 4 +- packages/located-error/src/lib.rs | 8 +- src/app.rs | 16 +- src/bootstrap/jobs/health_check_api.rs | 27 +- src/bootstrap/jobs/http_tracker.rs | 111 ++++---- src/bootstrap/jobs/mod.rs | 83 ++++++ src/bootstrap/jobs/tracker_apis.rs | 87 +++--- src/bootstrap/jobs/udp_tracker.rs | 36 ++- src/core/auth.rs | 4 +- src/core/databases/error.rs | 8 +- src/servers/apis/mod.rs | 11 +- src/servers/apis/server.rs | 265 ++++++------------ src/servers/health_check_api/server.rs | 18 +- src/servers/http/server.rs | 163 +++++++---- src/servers/http/v1/launcher.rs | 188 ------------- src/servers/http/v1/mod.rs | 1 - src/servers/signals.rs | 37 ++- src/servers/udp/handlers.rs | 3 +- src/servers/udp/server.rs | 218 +++++++------- tests/servers/api/test_environment.rs | 47 +++- .../servers/api/v1/contract/configuration.rs | 31 +- .../health_check_api/test_environment.rs | 6 +- tests/servers/http/test_environment.rs | 77 ++--- tests/servers/http/v1/contract.rs | 173 ++++++------ tests/servers/udp/test_environment.rs | 17 +- 25 files changed, 804 insertions(+), 835 deletions(-) delete mode 100644 src/servers/http/v1/launcher.rs diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 918d9f014..1c0979524 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -239,7 +239,7 @@ use config::{Config, ConfigError, File, FileFormat}; use serde::{Deserialize, Serialize}; use serde_with::{serde_as, NoneAsEmptyString}; use thiserror::Error; -use torrust_tracker_located_error::{Located, LocatedError}; +use torrust_tracker_located_error::{DynError, Located, LocatedError}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; /// Information required for loading config @@ -289,7 +289,7 @@ impl Info { fs::read_to_string(config_path) .map_err(|e| Error::UnableToLoadFromConfigFile { - source: (Arc::new(e) as Arc).into(), + source: (Arc::new(e) as DynError).into(), })? .parse() .map_err(|_e: std::convert::Infallible| Error::Infallible)? diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs index bf8618686..49e135600 100644 --- a/packages/located-error/src/lib.rs +++ b/packages/located-error/src/lib.rs @@ -33,6 +33,10 @@ use std::error::Error; use std::panic::Location; use std::sync::Arc; +use log::debug; + +pub type DynError = Arc; + /// A generic wrapper around an error. /// /// Where `E` is the inner error (source error). @@ -90,13 +94,13 @@ where source: Arc::new(self.0), location: Box::new(*std::panic::Location::caller()), }; - log::debug!("{e}"); + debug!("{e}"); e } } #[allow(clippy::from_over_into)] -impl<'a> Into> for Arc { +impl<'a> Into> for DynError { #[track_caller] fn into(self) -> LocatedError<'a, dyn std::error::Error + Send + Sync> { LocatedError { diff --git a/src/app.rs b/src/app.rs index 32c12d74a..3608aa22e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -28,8 +28,7 @@ use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; -use crate::core; -use crate::servers::http::Version; +use crate::{core, servers}; /// # Panics /// @@ -68,21 +67,22 @@ pub async fn start(config: Arc, tracker: Arc) -> V udp_tracker_config.bind_address, config.mode ); } else { - jobs.push(udp_tracker::start_job(udp_tracker_config, tracker.clone())); + jobs.push(udp_tracker::start_job(udp_tracker_config, tracker.clone()).await); } } // Start the HTTP blocks for http_tracker_config in &config.http_trackers { - if !http_tracker_config.enabled { - continue; - } - jobs.push(http_tracker::start_job(http_tracker_config, tracker.clone(), Version::V1).await); + if let Some(job) = http_tracker::start_job(http_tracker_config, tracker.clone(), servers::http::Version::V1).await { + jobs.push(job); + }; } // Start HTTP API if config.http_api.enabled { - jobs.push(tracker_apis::start_job(&config.http_api, tracker.clone()).await); + if let Some(job) = tracker_apis::start_job(&config.http_api, tracker.clone(), servers::apis::Version::V1).await { + jobs.push(job); + }; } // Start runners to remove torrents without peers, every interval diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index 96a703afc..83eb77f6b 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -6,16 +6,13 @@ //! The [`health_check_api::start_job`](crate::bootstrap::jobs::health_check_api::start_job) //! function spawns a new asynchronous task, that tasks is the "**launcher**". //! The "**launcher**" starts the actual server and sends a message back -//! to the main application. The main application waits until receives -//! the message [`ApiServerJobStarted`] -//! from the "**launcher**". +//! to the main application. //! //! The "**launcher**" is an intermediary thread that decouples the Health Check //! API server from the process that handles it. //! //! Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) //! for the API configuration options. -use std::net::SocketAddr; use std::sync::Arc; use log::info; @@ -23,19 +20,9 @@ use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; +use super::Started; use crate::servers::health_check_api::server; -/// This is the message that the "launcher" spawned task sends to the main -/// application process to notify the API server was successfully started. -/// -/// > **NOTICE**: it does not mean the API server is ready to receive requests. -/// It only means the new server started. It might take some time to the server -/// to be ready to accept request. -#[derive(Debug)] -pub struct ApiServerJobStarted { - pub bound_addr: SocketAddr, -} - /// This function starts a new Health Check API server with the provided /// configuration. /// @@ -51,15 +38,15 @@ pub async fn start_job(config: Arc) -> JoinHandle<()> { .health_check_api .bind_address .parse::() - .expect("Health Check API bind_address invalid."); + .expect("it should have a valid health check bind address"); - let (tx, rx) = oneshot::channel::(); + let (tx_start, rx_start) = oneshot::channel::(); // Run the API server let join_handle = tokio::spawn(async move { info!("Starting Health Check API server: http://{}", bind_addr); - let handle = server::start(bind_addr, tx, config.clone()); + let handle = server::start(bind_addr, tx_start, config.clone()); if let Ok(()) = handle.await { info!("Health Check API server on http://{} stopped", bind_addr); @@ -67,8 +54,8 @@ pub async fn start_job(config: Arc) -> JoinHandle<()> { }); // Wait until the API server job is running - match rx.await { - Ok(_msg) => info!("Torrust Health Check API server started"), + match rx_start.await { + Ok(msg) => info!("Torrust Health Check API server started on socket: {}", msg.address), Err(e) => panic!("the Health Check API server was dropped: {e}"), } diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index ecf6bd8ac..79e01fb3d 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -7,88 +7,85 @@ //! //! The [`http_tracker::start_job`](crate::bootstrap::jobs::http_tracker::start_job) function spawns a new asynchronous task, //! that tasks is the "**launcher**". The "**launcher**" starts the actual server and sends a message back to the main application. -//! The main application waits until receives the message [`ServerJobStarted`] from the "**launcher**". //! //! The "**launcher**" is an intermediary thread that decouples the HTTP servers from the process that handles it. The HTTP could be used independently in the future. //! In that case it would not need to notify a parent process. +use std::net::SocketAddr; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use log::info; -use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_tracker_configuration::HttpTracker; +use super::make_rust_tls; use crate::core; -use crate::servers::http::v1::launcher; +use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::http::Version; -/// This is the message that the "**launcher**" spawned task sends to the main application process to notify that the HTTP server was successfully started. -/// -/// > **NOTICE**: it does not mean the HTTP server is ready to receive requests. It only means the new server started. It might take some time to the server to be ready to accept request. -#[derive(Debug)] -pub struct ServerJobStarted(); - /// It starts a new HTTP server with the provided configuration and version. /// /// Right now there is only one version but in the future we could support more than one HTTP tracker version at the same time. /// This feature allows supporting breaking changes on `BitTorrent` BEPs. -pub async fn start_job(config: &HttpTracker, tracker: Arc, version: Version) -> JoinHandle<()> { - match version { - Version::V1 => start_v1(config, tracker.clone()).await, - } -} - +/// /// # Panics /// /// It would panic if the `config::HttpTracker` struct would contain inappropriate values. -async fn start_v1(config: &HttpTracker, tracker: Arc) -> JoinHandle<()> { - let bind_addr = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); - let ssl_enabled = config.ssl_enabled; - let ssl_cert_path = config.ssl_cert_path.clone(); - let ssl_key_path = config.ssl_key_path.clone(); - - let (tx, rx) = oneshot::channel::(); - - // Run the API server - let join_handle = tokio::spawn(async move { - if !ssl_enabled { - info!("Starting Torrust HTTP tracker server on: http://{}", bind_addr); - - let handle = launcher::start(bind_addr, tracker); - - tx.send(ServerJobStarted()) - .expect("the HTTP tracker server should not be dropped"); +/// +pub async fn start_job(config: &HttpTracker, tracker: Arc, version: Version) -> Option> { + if config.enabled { + let socket = config + .bind_address + .parse::() + .expect("it should have a valid http tracker bind address"); + + let tls = make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path) + .await + .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); + + match version { + Version::V1 => Some(start_v1(socket, tls, tracker.clone()).await), + } + } else { + info!("Note: Not loading Http Tracker Service, Not Enabled in Configuration."); + None + } +} - if let Ok(()) = handle.await { - info!("Torrust HTTP tracker server on http://{} stopped", bind_addr); - } - } else if ssl_enabled && ssl_cert_path.is_some() && ssl_key_path.is_some() { - info!("Starting Torrust HTTP tracker server on: https://{}", bind_addr); +async fn start_v1(socket: SocketAddr, tls: Option, tracker: Arc) -> JoinHandle<()> { + let server = HttpServer::new(Launcher::new(socket, tls)) + .start(tracker) + .await + .expect("it should be able to start to the http tracker"); + + tokio::spawn(async move { + server + .state + .task + .await + .expect("it should be able to join to the http tracker task"); + }) +} - let ssl_config = RustlsConfig::from_pem_file(ssl_cert_path.unwrap(), ssl_key_path.unwrap()) - .await - .unwrap(); +#[cfg(test)] +mod tests { + use std::sync::Arc; - let handle = launcher::start_tls(bind_addr, ssl_config, tracker); + use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; - tx.send(ServerJobStarted()) - .expect("the HTTP tracker server should not be dropped"); + use crate::bootstrap::app::initialize_with_configuration; + use crate::bootstrap::jobs::http_tracker::start_job; + use crate::servers::http::Version; - if let Ok(()) = handle.await { - info!("Torrust HTTP tracker server on https://{} stopped", bind_addr); - } - } - }); + #[tokio::test] + async fn it_should_start_http_tracker() { + let cfg = Arc::new(ephemeral_mode_public()); + let config = &cfg.http_trackers[0]; + let tracker = initialize_with_configuration(&cfg); + let version = Version::V1; - // Wait until the HTTP tracker server job is running - match rx.await { - Ok(_msg) => info!("Torrust HTTP tracker server started"), - Err(e) => panic!("the HTTP tracker server was dropped: {e}"), + start_job(config, tracker, version) + .await + .expect("it should be able to join to the http tracker start-job"); } - - join_handle } diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 8c85ba45b..3a9936882 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -11,3 +11,86 @@ pub mod http_tracker; pub mod torrent_cleanup; pub mod tracker_apis; pub mod udp_tracker; + +/// This is the message that the "launcher" spawned task sends to the main +/// application process to notify the service was successfully started. +/// +#[derive(Debug)] +pub struct Started { + pub address: std::net::SocketAddr, +} + +pub async fn make_rust_tls(enabled: bool, cert: &Option, key: &Option) -> Option> { + if !enabled { + info!("tls not enabled"); + return None; + } + + if let (Some(cert), Some(key)) = (cert, key) { + info!("Using https: cert path: {cert}."); + info!("Using https: key path: {cert}."); + + Some( + RustlsConfig::from_pem_file(cert, key) + .await + .map_err(|err| Error::BadTlsConfig { + source: (Arc::new(err) as DynError).into(), + }), + ) + } else { + Some(Err(Error::MissingTlsConfig { + location: Location::caller(), + })) + } +} + +#[cfg(test)] +mod tests { + + use super::make_rust_tls; + + #[tokio::test] + async fn it_should_error_on_bad_tls_config() { + let (bad_cert_path, bad_key_path) = (Some("bad cert path".to_string()), Some("bad key path".to_string())); + let err = make_rust_tls(true, &bad_cert_path, &bad_key_path) + .await + .expect("tls_was_enabled") + .expect_err("bad_cert_and_key_files"); + + assert!(err + .to_string() + .contains("bad tls config: No such file or directory (os error 2)")); + } + + #[tokio::test] + async fn it_should_error_on_missing_tls_config() { + let err = make_rust_tls(true, &None, &None) + .await + .expect("tls_was_enabled") + .expect_err("missing_config"); + + assert_eq!(err.to_string(), "tls config missing"); + } +} + +use std::panic::Location; +use std::sync::Arc; + +use axum_server::tls_rustls::RustlsConfig; +use log::info; +use thiserror::Error; +use torrust_tracker_located_error::{DynError, LocatedError}; + +/// Error returned by the Bootstrap Process. +#[derive(Error, Debug)] +pub enum Error { + /// Enabled tls but missing config. + #[error("tls config missing")] + MissingTlsConfig { location: &'static Location<'static> }, + + /// Unable to parse tls Config. + #[error("bad tls config: {source}")] + BadTlsConfig { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + }, +} diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index ca29d2b5f..f454b017f 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -20,16 +20,18 @@ //! //! Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) //! for the API configuration options. +use std::net::SocketAddr; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use log::info; -use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_tracker_configuration::HttpApi; +use super::make_rust_tls; use crate::core; -use crate::servers::apis::server; +use crate::servers::apis::server::{ApiServer, Launcher}; +use crate::servers::apis::Version; /// This is the message that the "launcher" spawned task sends to the main /// application process to notify the API server was successfully started. @@ -49,51 +51,58 @@ pub struct ApiServerJobStarted(); /// # Panics /// /// It would panic if unable to send the `ApiServerJobStarted` notice. -pub async fn start_job(config: &HttpApi, tracker: Arc) -> JoinHandle<()> { - let bind_addr = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); - let ssl_enabled = config.ssl_enabled; - let ssl_cert_path = config.ssl_cert_path.clone(); - let ssl_key_path = config.ssl_key_path.clone(); - - let (tx, rx) = oneshot::channel::(); +/// +/// +pub async fn start_job(config: &HttpApi, tracker: Arc, version: Version) -> Option> { + if config.enabled { + let bind_to = config + .bind_address + .parse::() + .expect("it should have a valid tracker api bind address"); - // Run the API server - let join_handle = tokio::spawn(async move { - if !ssl_enabled { - info!("Starting Torrust APIs server on: http://{}", bind_addr); + let tls = make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path) + .await + .map(|tls| tls.expect("it should have a valid tracker api tls configuration")); - let handle = server::start(bind_addr, tracker); + match version { + Version::V1 => Some(start_v1(bind_to, tls, tracker.clone()).await), + } + } else { + info!("Note: Not loading Http Tracker Service, Not Enabled in Configuration."); + None + } +} - tx.send(ApiServerJobStarted()).expect("the API server should not be dropped"); +async fn start_v1(socket: SocketAddr, tls: Option, tracker: Arc) -> JoinHandle<()> { + let server = ApiServer::new(Launcher::new(socket, tls)) + .start(tracker) + .await + .expect("it should be able to start to the tracker api"); - if let Ok(()) = handle.await { - info!("Torrust APIs server on http://{} stopped", bind_addr); - } - } else if ssl_enabled && ssl_cert_path.is_some() && ssl_key_path.is_some() { - info!("Starting Torrust APIs server on: https://{}", bind_addr); + tokio::spawn(async move { + server.state.task.await.expect("failed to close service"); + }) +} - let ssl_config = RustlsConfig::from_pem_file(ssl_cert_path.unwrap(), ssl_key_path.unwrap()) - .await - .unwrap(); +#[cfg(test)] +mod tests { + use std::sync::Arc; - let handle = server::start_tls(bind_addr, ssl_config, tracker); + use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; - tx.send(ApiServerJobStarted()).expect("the API server should not be dropped"); + use crate::bootstrap::app::initialize_with_configuration; + use crate::bootstrap::jobs::tracker_apis::start_job; + use crate::servers::apis::Version; - if let Ok(()) = handle.await { - info!("Torrust APIs server on https://{} stopped", bind_addr); - } - } - }); + #[tokio::test] + async fn it_should_start_http_tracker() { + let cfg = Arc::new(ephemeral_mode_public()); + let config = &cfg.http_api; + let tracker = initialize_with_configuration(&cfg); + let version = Version::V1; - // Wait until the APIs server job is running - match rx.await { - Ok(_msg) => info!("Torrust APIs server started"), - Err(e) => panic!("the API server was dropped: {e}"), + start_job(config, tracker, version) + .await + .expect("it should be able to join to the tracker api start-job"); } - - join_handle } diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 9a30c9126..5911bdf95 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -8,30 +8,38 @@ //! for the configuration options. use std::sync::Arc; -use log::{error, info, warn}; use tokio::task::JoinHandle; use torrust_tracker_configuration::UdpTracker; use crate::core; -use crate::servers::udp::server::Udp; +use crate::servers::udp::server::{Launcher, UdpServer}; /// It starts a new UDP server with the provided configuration. /// /// It spawns a new asynchronous task for the new UDP server. +/// +/// # Panics +/// +/// It will panic if the API binding address is not a valid socket. +/// It will panic if it is unable to start the UDP service. +/// It will panic if the task did not finish successfully. #[must_use] -pub fn start_job(config: &UdpTracker, tracker: Arc) -> JoinHandle<()> { - let bind_addr = config.bind_address.clone(); +pub async fn start_job(config: &UdpTracker, tracker: Arc) -> JoinHandle<()> { + let bind_to = config + .bind_address + .parse::() + .expect("it should have a valid udp tracker bind address"); + + let server = UdpServer::new(Launcher::new(bind_to)) + .start(tracker) + .await + .expect("it should be able to start the udp tracker"); tokio::spawn(async move { - match Udp::new(&bind_addr).await { - Ok(udp_server) => { - info!("Starting UDP server on: udp://{}", bind_addr); - udp_server.start(tracker).await; - } - Err(e) => { - warn!("Could not start UDP tracker on: udp://{}", bind_addr); - error!("{}", e); - } - } + server + .state + .task + .await + .expect("it should be able to join to the udp tracker task"); }) } diff --git a/src/core/auth.rs b/src/core/auth.rs index c6b772485..9fc9d6e7b 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -47,7 +47,7 @@ use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; use thiserror::Error; -use torrust_tracker_located_error::LocatedError; +use torrust_tracker_located_error::{DynError, LocatedError}; use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; use crate::shared::clock::{convert_from_timestamp_to_datetime_utc, Current, DurationSinceUnixEpoch, Time, TimeNow}; @@ -185,7 +185,7 @@ pub enum Error { impl From for Error { fn from(e: r2d2_sqlite::rusqlite::Error) -> Self { Error::KeyVerificationError { - source: (Arc::new(e) as Arc).into(), + source: (Arc::new(e) as DynError).into(), } } } diff --git a/src/core/databases/error.rs b/src/core/databases/error.rs index 96b0d835e..a5179e3a4 100644 --- a/src/core/databases/error.rs +++ b/src/core/databases/error.rs @@ -5,7 +5,7 @@ use std::panic::Location; use std::sync::Arc; use r2d2_mysql::mysql::UrlError; -use torrust_tracker_located_error::{Located, LocatedError}; +use torrust_tracker_located_error::{DynError, Located, LocatedError}; use torrust_tracker_primitives::DatabaseDriver; #[derive(thiserror::Error, Debug, Clone)] @@ -59,11 +59,11 @@ impl From for Error { fn from(err: r2d2_sqlite::rusqlite::Error) -> Self { match err { r2d2_sqlite::rusqlite::Error::QueryReturnedNoRows => Error::QueryReturnedNoRows { - source: (Arc::new(err) as Arc).into(), + source: (Arc::new(err) as DynError).into(), driver: DatabaseDriver::Sqlite3, }, _ => Error::InvalidQuery { - source: (Arc::new(err) as Arc).into(), + source: (Arc::new(err) as DynError).into(), driver: DatabaseDriver::Sqlite3, }, } @@ -73,7 +73,7 @@ impl From for Error { impl From for Error { #[track_caller] fn from(err: r2d2_mysql::mysql::Error) -> Self { - let e: Arc = Arc::new(err); + let e: DynError = Arc::new(err); Error::InvalidQuery { source: e.into(), driver: DatabaseDriver::MySQL, diff --git a/src/servers/apis/mod.rs b/src/servers/apis/mod.rs index 5f8c581d0..2d4b3abe1 100644 --- a/src/servers/apis/mod.rs +++ b/src/servers/apis/mod.rs @@ -159,8 +159,6 @@ pub mod routes; pub mod server; pub mod v1; -use serde::Deserialize; - /// The info hash URL path parameter. /// /// Some API endpoints require an info hash as a path parameter. @@ -172,3 +170,12 @@ use serde::Deserialize; /// in order to provide a more specific error message. #[derive(Deserialize)] pub struct InfoHashParam(pub String); + +use serde::{Deserialize, Serialize}; + +/// The version of the HTTP Api. +#[derive(Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Debug)] +pub enum Version { + /// The `v1` version of the HTTP Api. + V1, +} diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index c42083f9f..a25e62c8f 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -24,18 +24,18 @@ /// for example, to restart it to apply new configuration changes, to remotely /// shutdown the server, etc. use std::net::SocketAddr; -use std::str::FromStr; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; +use derive_more::Constructor; use futures::future::BoxFuture; -use futures::Future; -use log::info; +use tokio::sync::oneshot::{Receiver, Sender}; use super::routes::router; +use crate::bootstrap::jobs::Started; use crate::core::Tracker; -use crate::servers::signals::shutdown_signal; +use crate::servers::signals::{graceful_shutdown, Halted}; /// Errors that can occur when starting or stopping the API server. #[derive(Debug)] @@ -58,24 +58,27 @@ pub type RunningApiServer = ApiServer; /// states: `Stopped` or `Running`. #[allow(clippy::module_name_repetitions)] pub struct ApiServer { - pub cfg: torrust_tracker_configuration::HttpApi, pub state: S, } /// The `Stopped` state of the `ApiServer` struct. -pub struct Stopped; +pub struct Stopped { + launcher: Launcher, +} /// The `Running` state of the `ApiServer` struct. pub struct Running { - pub bind_addr: SocketAddr, - task_killer: tokio::sync::oneshot::Sender, - task: tokio::task::JoinHandle<()>, + pub binding: SocketAddr, + pub halt_task: tokio::sync::oneshot::Sender, + pub task: tokio::task::JoinHandle, } impl ApiServer { #[must_use] - pub fn new(cfg: torrust_tracker_configuration::HttpApi) -> Self { - Self { cfg, state: Stopped {} } + pub fn new(launcher: Launcher) -> Self { + Self { + state: Stopped { launcher }, + } } /// Starts the API server with the given configuration. @@ -88,28 +91,20 @@ impl ApiServer { /// /// It would panic if the bound socket address cannot be sent back to this starter. pub async fn start(self, tracker: Arc) -> Result, Error> { - let (shutdown_sender, shutdown_receiver) = tokio::sync::oneshot::channel::(); - let (addr_sender, addr_receiver) = tokio::sync::oneshot::channel::(); + let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); + let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); - let configuration = self.cfg.clone(); + let launcher = self.state.launcher; let task = tokio::spawn(async move { - let (bind_addr, server) = Launcher::start(&configuration, tracker, shutdown_signal(shutdown_receiver)); - - addr_sender.send(bind_addr).expect("Could not return SocketAddr."); - - server.await; + launcher.start(tracker, tx_start, rx_halt).await; + launcher }); - let bind_address = addr_receiver - .await - .map_err(|_| Error::Error("Could not receive bind_address.".to_string()))?; - Ok(ApiServer { - cfg: self.cfg, state: Running { - bind_addr: bind_address, - task_killer: shutdown_sender, + binding: rx_start.await.expect("unable to start service").address, + halt_task: tx_halt, task, }, }) @@ -124,21 +119,24 @@ impl ApiServer { /// It would return an error if the channel for the task killer signal was closed. pub async fn stop(self) -> Result, Error> { self.state - .task_killer - .send(0) + .halt_task + .send(Halted::Normal) .map_err(|_| Error::Error("Task killer channel was closed.".to_string()))?; - drop(self.state.task.await); + let launcher = self.state.task.await.map_err(|e| Error::Error(e.to_string()))?; Ok(ApiServer { - cfg: self.cfg, - state: Stopped {}, + state: Stopped { launcher }, }) } } /// A struct responsible for starting the API server. -struct Launcher; +#[derive(Constructor, Debug)] +pub struct Launcher { + bind_to: SocketAddr, + tls: Option, +} impl Launcher { /// Starts the API server with graceful shutdown. @@ -146,175 +144,78 @@ impl Launcher { /// If TLS is enabled in the configuration, it will start the server with /// TLS. See [`torrust-tracker-configuration`](torrust_tracker_configuration) /// for more information about configuration. - pub fn start( - cfg: &torrust_tracker_configuration::HttpApi, - tracker: Arc, - shutdown_signal: F, - ) -> (SocketAddr, BoxFuture<'static, ()>) - where - F: Future + Send + 'static, - { - let addr = SocketAddr::from_str(&cfg.bind_address).expect("bind_address is not a valid SocketAddr."); - let tcp_listener = std::net::TcpListener::bind(addr).expect("Could not bind tcp_listener to address."); - let bind_addr = tcp_listener - .local_addr() - .expect("Could not get local_addr from tcp_listener."); - - if let (true, Some(ssl_cert_path), Some(ssl_key_path)) = (&cfg.ssl_enabled, &cfg.ssl_cert_path, &cfg.ssl_key_path) { - let server = Self::start_tls_with_graceful_shutdown( - tcp_listener, - (ssl_cert_path.to_string(), ssl_key_path.to_string()), - tracker, - shutdown_signal, - ); - - (bind_addr, server) - } else { - let server = Self::start_with_graceful_shutdown(tcp_listener, tracker, shutdown_signal); - - (bind_addr, server) - } - } - - /// Starts the API server with graceful shutdown. - pub fn start_with_graceful_shutdown( - tcp_listener: std::net::TcpListener, - tracker: Arc, - shutdown_signal: F, - ) -> BoxFuture<'static, ()> - where - F: Future + Send + 'static, - { - let app = router(tracker); - - let handle = Handle::new(); - - let cloned_handle = handle.clone(); - - tokio::task::spawn(async move { - shutdown_signal.await; - cloned_handle.shutdown(); - }); - - Box::pin(async { - axum_server::from_tcp(tcp_listener) - .handle(handle) - .serve(app.into_make_service_with_connect_info::()) - .await - .expect("Axum server crashed."); - }) - } - - /// Starts the API server with graceful shutdown and TLS. - pub fn start_tls_with_graceful_shutdown( - tcp_listener: std::net::TcpListener, - (ssl_cert_path, ssl_key_path): (String, String), - tracker: Arc, - shutdown_signal: F, - ) -> BoxFuture<'static, ()> - where - F: Future + Send + 'static, - { - let app = router(tracker); + /// + /// # Panics + /// + /// Will panic if unable to bind to the socket, or unable to get the address of the bound socket. + /// Will also panic if unable to send message regarding the bound socket address. + pub fn start(&self, tracker: Arc, tx_start: Sender, rx_halt: Receiver) -> BoxFuture<'static, ()> { + let router = router(tracker); + let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); + let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); let handle = Handle::new(); - let cloned_handle = handle.clone(); - - tokio::task::spawn(async move { - shutdown_signal.await; - cloned_handle.shutdown(); + tokio::task::spawn(graceful_shutdown( + handle.clone(), + rx_halt, + format!("shutting down http server on socket address: {address}"), + )); + + let tls = self.tls.clone(); + + let running = Box::pin(async { + match tls { + Some(tls) => axum_server::from_tcp_rustls(socket, tls) + .handle(handle) + .serve(router.into_make_service_with_connect_info::()) + .await + .expect("Axum server crashed."), + None => axum_server::from_tcp(socket) + .handle(handle) + .serve(router.into_make_service_with_connect_info::()) + .await + .expect("Axum server crashed."), + } }); - Box::pin(async { - let tls_config = RustlsConfig::from_pem_file(ssl_cert_path, ssl_key_path) - .await - .expect("Could not read tls cert."); + tx_start + .send(Started { address }) + .expect("the HTTP(s) Tracker service should not be dropped"); - axum_server::from_tcp_rustls(tcp_listener, tls_config) - .handle(handle) - .serve(app.into_make_service_with_connect_info::()) - .await - .expect("Axum server crashed."); - }) + running } } -/// Starts the API server with graceful shutdown on the current thread. -/// -/// # Panics -/// -/// It would panic if it fails to listen to shutdown signal. -pub fn start(socket_addr: SocketAddr, tracker: Arc) -> impl Future> { - let app = router(tracker); - - let handle = Handle::new(); - let shutdown_handle = handle.clone(); - - tokio::spawn(async move { - tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust APIs server on https://{} ...", socket_addr); - shutdown_handle.shutdown(); - }); - - axum_server::bind(socket_addr).handle(handle).serve(app.into_make_service()) -} - -/// Starts the API server with graceful shutdown and TLS on the current thread. -/// -/// # Panics -/// -/// It would panic if it fails to listen to shutdown signal. -pub fn start_tls( - socket_addr: SocketAddr, - ssl_config: RustlsConfig, - tracker: Arc, -) -> impl Future> { - let app = router(tracker); - - let handle = Handle::new(); - let shutdown_handle = handle.clone(); - - tokio::spawn(async move { - tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust APIs server on https://{} ...", socket_addr); - shutdown_handle.shutdown(); - }); - - axum_server::bind_rustls(socket_addr, ssl_config) - .handle(handle) - .serve(app.into_make_service()) -} - #[cfg(test)] mod tests { use std::sync::Arc; - use torrust_tracker_configuration::Configuration; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; - use crate::core; - use crate::core::statistics; - use crate::servers::apis::server::ApiServer; - - fn tracker_configuration() -> Arc { - Arc::new(configuration::ephemeral()) - } + use crate::bootstrap::app::initialize_with_configuration; + use crate::bootstrap::jobs::make_rust_tls; + use crate::servers::apis::server::{ApiServer, Launcher}; #[tokio::test] - async fn it_should_be_able_to_start_from_stopped_state_and_then_stop_again() { - let cfg = tracker_configuration(); - - let tracker = Arc::new(core::Tracker::new(cfg.clone(), None, statistics::Repo::new()).unwrap()); + async fn it_should_be_able_to_start_and_stop() { + let cfg = Arc::new(ephemeral_mode_public()); + let tracker = initialize_with_configuration(&cfg); + let config = &cfg.http_api; - let stopped_api_server = ApiServer::new(cfg.http_api.clone()); + let bind_to = config + .bind_address + .parse::() + .expect("Tracker API bind_address invalid."); - let running_api_server_result = stopped_api_server.start(tracker).await; - - assert!(running_api_server_result.is_ok()); + let tls = make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path) + .await + .map(|tls| tls.expect("tls config failed")); - let running_api_server = running_api_server_result.unwrap(); + let stopped = ApiServer::new(Launcher::new(bind_to, tls)); + let started = stopped.start(tracker).await.expect("it should start the server"); + let stopped = started.stop().await.expect("it should stop the server"); - assert!(running_api_server.stop().await.is_ok()); + assert_eq!(stopped.state.launcher.bind_to, bind_to); } } diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index d4654d617..fb807d09c 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -14,7 +14,7 @@ use serde_json::json; use tokio::sync::oneshot::Sender; use torrust_tracker_configuration::Configuration; -use crate::bootstrap::jobs::health_check_api::ApiServerJobStarted; +use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; /// Starts Health Check API server. @@ -23,8 +23,8 @@ use crate::servers::health_check_api::handlers::health_check_handler; /// /// Will panic if binding to the socket address fails. pub fn start( - socket_addr: SocketAddr, - tx: Sender, + address: SocketAddr, + tx: Sender, config: Arc, ) -> impl Future> { let app = Router::new() @@ -35,22 +35,20 @@ pub fn start( let handle = Handle::new(); let cloned_handle = handle.clone(); - let tcp_listener = std::net::TcpListener::bind(socket_addr).expect("Could not bind tcp_listener to address."); - let bound_addr = tcp_listener - .local_addr() - .expect("Could not get local_addr from tcp_listener."); + let socket = std::net::TcpListener::bind(address).expect("Could not bind tcp_listener to address."); + let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); tokio::task::spawn(async move { tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust Health Check API server o http://{} ...", bound_addr); + info!("Stopping Torrust Health Check API server o http://{} ...", address); cloned_handle.shutdown(); }); - let running = axum_server::from_tcp(tcp_listener) + let running = axum_server::from_tcp(socket) .handle(handle) .serve(app.into_make_service_with_connect_info::()); - tx.send(ApiServerJobStarted { bound_addr }) + tx.send(Started { address }) .expect("the Health Check API server should not be dropped"); running diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 2d8fc745f..aee2d0ac0 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -1,30 +1,17 @@ //! Module to handle the HTTP server instances. -use std::future::Future; use std::net::SocketAddr; use std::sync::Arc; +use axum_server::tls_rustls::RustlsConfig; +use axum_server::Handle; +use derive_more::Constructor; use futures::future::BoxFuture; +use tokio::sync::oneshot::{Receiver, Sender}; +use super::v1::routes::router; +use crate::bootstrap::jobs::Started; use crate::core::Tracker; -use crate::servers::signals::shutdown_signal; - -/// Trait to be implemented by a HTTP server launcher for the tracker. -/// -/// A launcher is responsible for starting the server and returning the -/// `SocketAddr` it is bound to. -#[allow(clippy::module_name_repetitions)] -pub trait HttpServerLauncher: Sync + Send { - fn new() -> Self; - - fn start_with_graceful_shutdown( - &self, - cfg: torrust_tracker_configuration::HttpTracker, - tracker: Arc, - shutdown_signal: F, - ) -> (SocketAddr, BoxFuture<'static, ()>) - where - F: Future + Send + 'static; -} +use crate::servers::signals::{graceful_shutdown, Halted}; /// Error that can occur when starting or stopping the HTTP server. /// @@ -40,17 +27,61 @@ pub trait HttpServerLauncher: Sync + Send { /// completion. #[derive(Debug)] pub enum Error { - /// Any kind of error starting or stopping the server. - Error(String), // todo: refactor to use thiserror and add more variants for specific errors. + Error(String), +} + +#[derive(Constructor, Debug)] +pub struct Launcher { + pub bind_to: SocketAddr, + pub tls: Option, +} + +impl Launcher { + fn start(&self, tracker: Arc, tx_start: Sender, rx_halt: Receiver) -> BoxFuture<'static, ()> { + let app = router(tracker); + let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); + let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); + + let handle = Handle::new(); + + tokio::task::spawn(graceful_shutdown( + handle.clone(), + rx_halt, + format!("shutting down http server on socket address: {address}"), + )); + + let tls = self.tls.clone(); + + let running = Box::pin(async { + match tls { + Some(tls) => axum_server::from_tcp_rustls(socket, tls) + .handle(handle) + .serve(app.into_make_service_with_connect_info::()) + .await + .expect("Axum server crashed."), + None => axum_server::from_tcp(socket) + .handle(handle) + .serve(app.into_make_service_with_connect_info::()) + .await + .expect("Axum server crashed."), + } + }); + + tx_start + .send(Started { address }) + .expect("the HTTP(s) Tracker service should not be dropped"); + + running + } } /// A HTTP server instance controller with no HTTP instance running. #[allow(clippy::module_name_repetitions)] -pub type StoppedHttpServer = HttpServer>; +pub type StoppedHttpServer = HttpServer; /// A HTTP server instance controller with a running HTTP instance. #[allow(clippy::module_name_repetitions)] -pub type RunningHttpServer = HttpServer>; +pub type RunningHttpServer = HttpServer; /// A HTTP server instance controller. /// @@ -69,31 +100,28 @@ pub type RunningHttpServer = HttpServer>; /// intended to persist configurations between runs. #[allow(clippy::module_name_repetitions)] pub struct HttpServer { - /// The configuration of the server that will be used every time the server - /// is started. - pub cfg: torrust_tracker_configuration::HttpTracker, /// The state of the server: `running` or `stopped`. pub state: S, } /// A stopped HTTP server state. -pub struct Stopped { - launcher: I, +pub struct Stopped { + launcher: Launcher, } /// A running HTTP server state. -pub struct Running { +pub struct Running { /// The address where the server is bound. - pub bind_addr: SocketAddr, - task_killer: tokio::sync::oneshot::Sender, - task: tokio::task::JoinHandle, + pub binding: SocketAddr, + pub halt_task: tokio::sync::oneshot::Sender, + pub task: tokio::task::JoinHandle, } -impl HttpServer> { +impl HttpServer { /// It creates a new `HttpServer` controller in `stopped` state. - pub fn new(cfg: torrust_tracker_configuration::HttpTracker, launcher: I) -> Self { + #[must_use] + pub fn new(launcher: Launcher) -> Self { Self { - cfg, state: Stopped { launcher }, } } @@ -109,57 +137,80 @@ impl HttpServer> { /// /// It would panic spawned HTTP server launcher cannot send the bound `SocketAddr` /// back to the main thread. - pub async fn start(self, tracker: Arc) -> Result>, Error> { - let (shutdown_sender, shutdown_receiver) = tokio::sync::oneshot::channel::(); - let (addr_sender, addr_receiver) = tokio::sync::oneshot::channel::(); + pub async fn start(self, tracker: Arc) -> Result, Error> { + let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); + let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); - let configuration = self.cfg.clone(); let launcher = self.state.launcher; let task = tokio::spawn(async move { - let (bind_addr, server) = - launcher.start_with_graceful_shutdown(configuration, tracker, shutdown_signal(shutdown_receiver)); - - addr_sender.send(bind_addr).expect("Could not return SocketAddr."); + let server = launcher.start(tracker, tx_start, rx_halt); server.await; launcher }); - let bind_address = addr_receiver - .await - .map_err(|_| Error::Error("Could not receive bind_address.".to_string()))?; - Ok(HttpServer { - cfg: self.cfg, state: Running { - bind_addr: bind_address, - task_killer: shutdown_sender, + binding: rx_start.await.expect("unable to start service").address, + halt_task: tx_halt, task, }, }) } } -impl HttpServer> { +impl HttpServer { /// It stops the server and returns a `HttpServer` controller in `stopped` /// state. /// /// # Errors /// /// It would return an error if the channel for the task killer signal was closed. - pub async fn stop(self) -> Result>, Error> { + pub async fn stop(self) -> Result, Error> { self.state - .task_killer - .send(0) + .halt_task + .send(Halted::Normal) .map_err(|_| Error::Error("Task killer channel was closed.".to_string()))?; let launcher = self.state.task.await.map_err(|e| Error::Error(e.to_string()))?; Ok(HttpServer { - cfg: self.cfg, state: Stopped { launcher }, }) } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; + + use crate::bootstrap::app::initialize_with_configuration; + use crate::bootstrap::jobs::make_rust_tls; + use crate::servers::http::server::{HttpServer, Launcher}; + + #[tokio::test] + async fn it_should_be_able_to_start_and_stop() { + let cfg = Arc::new(ephemeral_mode_public()); + let tracker = initialize_with_configuration(&cfg); + let config = &cfg.http_trackers[0]; + + let bind_to = config + .bind_address + .parse::() + .expect("Tracker API bind_address invalid."); + + let tls = make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path) + .await + .map(|tls| tls.expect("tls config failed")); + + let stopped = HttpServer::new(Launcher::new(bind_to, tls)); + let started = stopped.start(tracker).await.expect("it should start the server"); + let stopped = started.stop().await.expect("it should stop the server"); + + assert_eq!(stopped.state.launcher.bind_to, bind_to); + } +} diff --git a/src/servers/http/v1/launcher.rs b/src/servers/http/v1/launcher.rs deleted file mode 100644 index 6b89e8ce7..000000000 --- a/src/servers/http/v1/launcher.rs +++ /dev/null @@ -1,188 +0,0 @@ -//! Logic to start new HTTP server instances. -use std::future::Future; -use std::net::SocketAddr; -use std::str::FromStr; -use std::sync::Arc; - -use async_trait::async_trait; -use axum_server::tls_rustls::RustlsConfig; -use axum_server::Handle; -use futures::future::BoxFuture; -use log::info; - -use super::routes::router; -use crate::core::Tracker; -use crate::servers::http::server::HttpServerLauncher; - -#[derive(Debug)] -pub enum Error { - Error(String), -} - -pub struct Launcher; - -impl Launcher { - /// It starts a new HTTP server instance from a TCP listener with graceful shutdown. - /// - /// # Panics - /// - /// Will panic if: - /// - /// - The TCP listener could not be bound. - /// - The Axum server crashes. - pub fn start_from_tcp_listener_with_graceful_shutdown( - tcp_listener: std::net::TcpListener, - tracker: Arc, - shutdown_signal: F, - ) -> BoxFuture<'static, ()> - where - F: Future + Send + 'static, - { - let app = router(tracker); - - let handle = Handle::new(); - - let cloned_handle = handle.clone(); - - tokio::task::spawn(async move { - shutdown_signal.await; - cloned_handle.shutdown(); - }); - - Box::pin(async { - axum_server::from_tcp(tcp_listener) - .handle(handle) - .serve(app.into_make_service_with_connect_info::()) - .await - .expect("Axum server crashed."); - }) - } - - /// It starts a new HTTPS server instance from a TCP listener with graceful shutdown. - /// - /// # Panics - /// - /// Will panic if: - /// - /// - The SSL certificate could not be read from the provided path or is invalid. - /// - The Axum server crashes. - pub fn start_tls_from_tcp_listener_with_graceful_shutdown( - tcp_listener: std::net::TcpListener, - (ssl_cert_path, ssl_key_path): (String, String), - tracker: Arc, - shutdown_signal: F, - ) -> BoxFuture<'static, ()> - where - F: Future + Send + 'static, - { - let app = router(tracker); - - let handle = Handle::new(); - - let cloned_handle = handle.clone(); - - tokio::task::spawn(async move { - shutdown_signal.await; - cloned_handle.shutdown(); - }); - - Box::pin(async { - let tls_config = RustlsConfig::from_pem_file(ssl_cert_path, ssl_key_path) - .await - .expect("Could not read tls cert."); - - axum_server::from_tcp_rustls(tcp_listener, tls_config) - .handle(handle) - .serve(app.into_make_service_with_connect_info::()) - .await - .expect("Axum server crashed."); - }) - } -} - -#[async_trait] -impl HttpServerLauncher for Launcher { - fn new() -> Self { - Self {} - } - - fn start_with_graceful_shutdown( - &self, - cfg: torrust_tracker_configuration::HttpTracker, - tracker: Arc, - shutdown_signal: F, - ) -> (SocketAddr, BoxFuture<'static, ()>) - where - F: Future + Send + 'static, - { - let addr = SocketAddr::from_str(&cfg.bind_address).expect("bind_address is not a valid SocketAddr."); - let tcp_listener = std::net::TcpListener::bind(addr).expect("Could not bind tcp_listener to address."); - let bind_addr = tcp_listener - .local_addr() - .expect("Could not get local_addr from tcp_listener."); - - if let (true, Some(ssl_cert_path), Some(ssl_key_path)) = (cfg.ssl_enabled, &cfg.ssl_cert_path, &cfg.ssl_key_path) { - let server = Self::start_tls_from_tcp_listener_with_graceful_shutdown( - tcp_listener, - (ssl_cert_path.to_string(), ssl_key_path.to_string()), - tracker, - shutdown_signal, - ); - - (bind_addr, server) - } else { - let server = Self::start_from_tcp_listener_with_graceful_shutdown(tcp_listener, tracker, shutdown_signal); - - (bind_addr, server) - } - } -} - -/// Starts a new HTTP server instance. -/// -/// # Panics -/// -/// Panics if the server could not listen to shutdown (ctrl+c) signal. -pub fn start(socket_addr: std::net::SocketAddr, tracker: Arc) -> impl Future> { - let app = router(tracker); - - let handle = Handle::new(); - - let cloned_handle = handle.clone(); - - tokio::task::spawn(async move { - tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust Health Check API server o http://{} ...", socket_addr); - cloned_handle.shutdown(); - }); - - axum_server::bind(socket_addr) - .handle(handle) - .serve(app.into_make_service_with_connect_info::()) -} - -/// Starts a new HTTPS server instance. -/// -/// # Panics -/// -/// Panics if the server could not listen to shutdown (ctrl+c) signal. -pub fn start_tls( - socket_addr: std::net::SocketAddr, - ssl_config: RustlsConfig, - tracker: Arc, -) -> impl Future> { - let app = router(tracker); - - let handle = Handle::new(); - let shutdown_handle = handle.clone(); - - tokio::spawn(async move { - tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust HTTP tracker server on https://{} ...", socket_addr); - shutdown_handle.shutdown(); - }); - - axum_server::bind_rustls(socket_addr, ssl_config) - .handle(handle) - .serve(app.into_make_service_with_connect_info::()) -} diff --git a/src/servers/http/v1/mod.rs b/src/servers/http/v1/mod.rs index 464a7ee14..9d2745692 100644 --- a/src/servers/http/v1/mod.rs +++ b/src/servers/http/v1/mod.rs @@ -4,7 +4,6 @@ //! more information about the endpoints and their usage. pub mod extractors; pub mod handlers; -pub mod launcher; pub mod query; pub mod requests; pub mod responses; diff --git a/src/servers/signals.rs b/src/servers/signals.rs index 51f53738d..cb0675d65 100644 --- a/src/servers/signals.rs +++ b/src/servers/signals.rs @@ -1,5 +1,17 @@ //! This module contains functions to handle signals. +use std::time::Duration; + +use derive_more::Display; use log::info; +use tokio::time::sleep; + +/// This is the message that the "launcher" spawned task receives from the main +/// application process to notify the service to shutdown. +/// +#[derive(Copy, Clone, Debug, Display)] +pub enum Halted { + Normal, +} /// Resolves on `ctrl_c` or the `terminate` signal. /// @@ -33,18 +45,33 @@ pub async fn global_shutdown_signal() { /// # Panics /// /// Will panic if the `stop_receiver` resolves with an error. -pub async fn shutdown_signal(stop_receiver: tokio::sync::oneshot::Receiver) { - let stop = async { stop_receiver.await.expect("Failed to install stop signal.") }; +pub async fn shutdown_signal(rx_halt: tokio::sync::oneshot::Receiver) { + let halt = async { rx_halt.await.expect("Failed to install stop signal.") }; tokio::select! { - _ = stop => {}, + _ = halt => {}, () = global_shutdown_signal() => {} } } /// Same as `shutdown_signal()`, but shows a message when it resolves. -pub async fn shutdown_signal_with_message(stop_receiver: tokio::sync::oneshot::Receiver, message: String) { - shutdown_signal(stop_receiver).await; +pub async fn shutdown_signal_with_message(rx_halt: tokio::sync::oneshot::Receiver, message: String) { + shutdown_signal(rx_halt).await; info!("{message}"); } + +pub async fn graceful_shutdown(handle: axum_server::Handle, rx_halt: tokio::sync::oneshot::Receiver, message: String) { + shutdown_signal_with_message(rx_halt, message).await; + + info!("sending graceful shutdown signal"); + handle.graceful_shutdown(Some(Duration::from_secs(90))); + + println!("!! shuting down in 90 seconds !!"); + + loop { + sleep(Duration::from_secs(1)).await; + + info!("remaining alive connections: {}", handle.connection_count()); + } +} diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index f3c7b58b0..18a341418 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -8,6 +8,7 @@ use aquatic_udp_protocol::{ NumberOfPeers, Port, Request, Response, ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; use log::{debug, info}; +use torrust_tracker_located_error::DynError; use super::connection_cookie::{check, from_connection_id, into_connection_id, make}; use crate::core::{statistics, ScrapeData, Tracker}; @@ -46,7 +47,7 @@ pub async fn handle_packet(remote_addr: SocketAddr, payload: Vec, tracker: & // bad request Err(e) => handle_error( &Error::BadRequest { - source: (Arc::new(e) as Arc).into(), + source: (Arc::new(e) as DynError).into(), }, TransactionId(0), ), diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 9b9a89b11..a0af55101 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -17,19 +17,21 @@ //! because we want to be able to start and stop the server multiple times, and //! we want to know the bound address and the current state of the server. //! In production, the `Udp` launcher is used directly. -use std::future::Future; use std::io::Cursor; use std::net::SocketAddr; use std::sync::Arc; use aquatic_udp_protocol::Response; +use derive_more::Constructor; use futures::pin_mut; use log::{debug, error, info}; use tokio::net::UdpSocket; +use tokio::sync::oneshot::{Receiver, Sender}; use tokio::task::JoinHandle; +use crate::bootstrap::jobs::Started; use crate::core::Tracker; -use crate::servers::signals::shutdown_signal; +use crate::servers::signals::{shutdown_signal_with_message, Halted}; use crate::servers::udp::handlers::handle_packet; use crate::shared::bit_torrent::udp::MAX_PACKET_SIZE; @@ -75,29 +77,32 @@ pub type RunningUdpServer = UdpServer; /// intended to persist configurations between runs. #[allow(clippy::module_name_repetitions)] pub struct UdpServer { - /// The configuration of the server that will be used every time the server - /// is started. - pub cfg: torrust_tracker_configuration::UdpTracker, /// The state of the server: `running` or `stopped`. pub state: S, } /// A stopped UDP server state. -pub struct Stopped; + +pub struct Stopped { + launcher: Launcher, +} /// A running UDP server state. +#[derive(Debug, Constructor)] pub struct Running { /// The address where the server is bound. - pub bind_address: SocketAddr, - stop_job_sender: tokio::sync::oneshot::Sender, - job: JoinHandle<()>, + pub binding: SocketAddr, + pub halt_task: tokio::sync::oneshot::Sender, + pub task: JoinHandle, } impl UdpServer { /// Creates a new `UdpServer` instance in `stopped`state. #[must_use] - pub fn new(cfg: torrust_tracker_configuration::UdpTracker) -> Self { - Self { cfg, state: Stopped {} } + pub fn new(launcher: Launcher) -> Self { + Self { + state: Stopped { launcher }, + } } /// It starts the server and returns a `UdpServer` controller in `running` @@ -106,28 +111,32 @@ impl UdpServer { /// # Errors /// /// Will return `Err` if UDP can't bind to given bind address. + /// + /// # Panics + /// + /// It panics if unable to receive the bound socket address from service. + /// pub async fn start(self, tracker: Arc) -> Result, Error> { - let udp = Udp::new(&self.cfg.bind_address) - .await - .map_err(|e| Error::Error(e.to_string()))?; - - let bind_address = udp.socket.local_addr().map_err(|e| Error::Error(e.to_string()))?; + let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); + let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); - let (sender, receiver) = tokio::sync::oneshot::channel::(); + let launcher = self.state.launcher; - let job = tokio::spawn(async move { - udp.start_with_graceful_shutdown(tracker, shutdown_signal(receiver)).await; + let task = tokio::spawn(async move { + launcher.start(tracker, tx_start, rx_halt).await; + launcher }); let running_udp_server: UdpServer = UdpServer { - cfg: self.cfg, state: Running { - bind_address, - stop_job_sender: sender, - job, + binding: rx_start.await.expect("unable to start service").address, + halt_task: tx_halt, + task, }, }; + info!("Running UDP Tracker on Socket: {}", running_udp_server.state.binding); + Ok(running_udp_server) } } @@ -140,103 +149,96 @@ impl UdpServer { /// /// Will return `Err` if the oneshot channel to send the stop signal /// has already been called once. + /// + /// # Panics + /// + /// It panics if unable to shutdown service. pub async fn stop(self) -> Result, Error> { - self.state.stop_job_sender.send(1).map_err(|e| Error::Error(e.to_string()))?; + self.state + .halt_task + .send(Halted::Normal) + .map_err(|e| Error::Error(e.to_string()))?; - drop(self.state.job.await); + let launcher = self.state.task.await.expect("unable to shutdown service"); let stopped_api_server: UdpServer = UdpServer { - cfg: self.cfg, - state: Stopped {}, + state: Stopped { launcher }, }; Ok(stopped_api_server) } } -/// A UDP server instance launcher. -pub struct Udp { - socket: Arc, +#[derive(Constructor, Debug)] +pub struct Launcher { + bind_to: SocketAddr, } -impl Udp { - /// Creates a new `Udp` instance. - /// - /// # Errors - /// - /// Will return `Err` unable to bind to the supplied `bind_address`. - pub async fn new(bind_address: &str) -> tokio::io::Result { - let socket = UdpSocket::bind(bind_address).await?; - - Ok(Udp { - socket: Arc::new(socket), - }) - } - +impl Launcher { /// It starts the UDP server instance. /// /// # Panics /// /// It would panic if unable to resolve the `local_addr` from the supplied ´socket´. - pub async fn start(&self, tracker: Arc) { - loop { - let mut data = [0; MAX_PACKET_SIZE]; - let socket = self.socket.clone(); - - tokio::select! { - _ = tokio::signal::ctrl_c() => { - info!("Stopping UDP server: {}..", socket.local_addr().unwrap()); - break; - } - Ok((valid_bytes, remote_addr)) = socket.recv_from(&mut data) => { - let payload = data[..valid_bytes].to_vec(); - - debug!("Received {} bytes", payload.len()); - debug!("From: {}", &remote_addr); - debug!("Payload: {:?}", payload); - - let response = handle_packet(remote_addr, payload, &tracker).await; - - Udp::send_response(socket, remote_addr, response).await; - } - } - } + pub async fn start(&self, tracker: Arc, tx_start: Sender, rx_halt: Receiver) -> JoinHandle<()> { + Udp::start_with_graceful_shutdown(tracker, self.bind_to, tx_start, rx_halt).await } +} + +/// A UDP server instance launcher. +#[derive(Constructor)] +pub struct Udp; +impl Udp { /// It starts the UDP server instance with graceful shutdown. /// /// # Panics /// - /// It would panic if unable to resolve the `local_addr` from the supplied ´socket´. - async fn start_with_graceful_shutdown(&self, tracker: Arc, shutdown_signal: F) - where - F: Future, - { - // Pin the future so that it doesn't move to the first loop iteration. - pin_mut!(shutdown_signal); - - loop { - let mut data = [0; MAX_PACKET_SIZE]; - let socket = self.socket.clone(); - - tokio::select! { - () = &mut shutdown_signal => { - info!("Stopping UDP server: {}..", self.socket.local_addr().unwrap()); - break; + /// It panics if unable to bind to udp socket, and get the address from the udp socket. + /// It also panics if unable to send address of socket. + async fn start_with_graceful_shutdown( + tracker: Arc, + bind_to: SocketAddr, + tx_start: Sender, + rx_halt: Receiver, + ) -> JoinHandle<()> { + let binding = Arc::new(UdpSocket::bind(bind_to).await.expect("Could not bind to {self.socket}.")); + let address = binding.local_addr().expect("Could not get local_addr from {binding}."); + + let running = tokio::task::spawn(async move { + let halt = async move { + shutdown_signal_with_message(rx_halt, format!("Halting Http Service Bound to Socket: {address}")).await; + }; + + pin_mut!(halt); + + loop { + let mut data = [0; MAX_PACKET_SIZE]; + let binding = binding.clone(); + + tokio::select! { + () = & mut halt => {}, + + Ok((valid_bytes, remote_addr)) = binding.recv_from(&mut data) => { + let payload = data[..valid_bytes].to_vec(); + + debug!("Received {} bytes", payload.len()); + debug!("From: {}", &remote_addr); + debug!("Payload: {:?}", payload); + + let response = handle_packet(remote_addr, payload, &tracker).await; + + Udp::send_response(binding, remote_addr, response).await; + } } - Ok((valid_bytes, remote_addr)) = socket.recv_from(&mut data) => { - let payload = data[..valid_bytes].to_vec(); - - debug!("Received {} bytes", payload.len()); - debug!("From: {}", &remote_addr); - debug!("Payload: {:?}", payload); + } + }); - let response = handle_packet(remote_addr, payload, &tracker).await; + tx_start + .send(Started { address }) + .expect("the UDP Tracker service should not be dropped"); - Udp::send_response(socket, remote_addr, response).await; - } - } - } + running } async fn send_response(socket: Arc, remote_addr: SocketAddr, response: Response) { @@ -268,3 +270,31 @@ impl Udp { drop(socket.send_to(payload, remote_addr).await); } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; + + use crate::bootstrap::app::initialize_with_configuration; + use crate::servers::udp::server::{Launcher, UdpServer}; + + #[tokio::test] + async fn it_should_be_able_to_start_and_stop() { + let cfg = Arc::new(ephemeral_mode_public()); + let tracker = initialize_with_configuration(&cfg); + let config = &cfg.udp_trackers[0]; + + let bind_to = config + .bind_address + .parse::() + .expect("Tracker API bind_address invalid."); + + let stopped = UdpServer::new(Launcher::new(bind_to)); + let started = stopped.start(tracker).await.expect("it should start the server"); + let stopped = started.stop().await.expect("it should stop the server"); + + assert_eq!(stopped.state.launcher.bind_to, bind_to); + } +} diff --git a/tests/servers/api/test_environment.rs b/tests/servers/api/test_environment.rs index 0501d9c56..166bfd7d1 100644 --- a/tests/servers/api/test_environment.rs +++ b/tests/servers/api/test_environment.rs @@ -1,8 +1,12 @@ +use std::net::SocketAddr; use std::sync::Arc; +use axum_server::tls_rustls::RustlsConfig; +use futures::executor::block_on; +use torrust_tracker::bootstrap::jobs::make_rust_tls; use torrust_tracker::core::peer::Peer; use torrust_tracker::core::Tracker; -use torrust_tracker::servers::apis::server::{ApiServer, RunningApiServer, StoppedApiServer}; +use torrust_tracker::servers::apis::server::{ApiServer, Launcher, RunningApiServer, StoppedApiServer}; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use super::connection_info::ConnectionInfo; @@ -36,15 +40,27 @@ impl TestEnvironment { } impl TestEnvironment { - pub fn new_stopped(cfg: torrust_tracker_configuration::Configuration) -> Self { - let cfg = Arc::new(cfg); + pub fn new(cfg: torrust_tracker_configuration::Configuration) -> Self { + let tracker = setup_with_configuration(&Arc::new(cfg)); - let tracker = setup_with_configuration(&cfg); + let config = tracker.config.http_api.clone(); - let api_server = api_server(cfg.http_api.clone()); + let bind_to = config + .bind_address + .parse::() + .expect("Tracker API bind_address invalid."); + + let tls = block_on(make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path)) + .map(|tls| tls.expect("tls config failed")); + + Self::new_stopped(tracker, bind_to, tls) + } + + pub fn new_stopped(tracker: Arc, bind_to: SocketAddr, tls: Option) -> Self { + let api_server = api_server(Launcher::new(bind_to, tls)); Self { - cfg, + cfg: tracker.config.clone(), tracker, state: Stopped { api_server }, } @@ -60,14 +76,14 @@ impl TestEnvironment { } } - pub fn config_mut(&mut self) -> &mut torrust_tracker_configuration::HttpApi { - &mut self.state.api_server.cfg - } + // pub fn config_mut(&mut self) -> &mut torrust_tracker_configuration::HttpApi { + // &mut self.cfg.http_api + // } } impl TestEnvironment { pub async fn new_running(cfg: torrust_tracker_configuration::Configuration) -> Self { - let test_env = StoppedTestEnvironment::new_stopped(cfg); + let test_env = StoppedTestEnvironment::new(cfg); test_env.start().await } @@ -84,15 +100,16 @@ impl TestEnvironment { pub fn get_connection_info(&self) -> ConnectionInfo { ConnectionInfo { - bind_address: self.state.api_server.state.bind_addr.to_string(), - api_token: self.state.api_server.cfg.access_tokens.get("admin").cloned(), + bind_address: self.state.api_server.state.binding.to_string(), + api_token: self.cfg.http_api.access_tokens.get("admin").cloned(), } } } #[allow(clippy::module_name_repetitions)] +#[allow(dead_code)] pub fn stopped_test_environment(cfg: torrust_tracker_configuration::Configuration) -> StoppedTestEnvironment { - TestEnvironment::new_stopped(cfg) + TestEnvironment::new(cfg) } #[allow(clippy::module_name_repetitions)] @@ -100,6 +117,6 @@ pub async fn running_test_environment(cfg: torrust_tracker_configuration::Config TestEnvironment::new_running(cfg).await } -pub fn api_server(cfg: torrust_tracker_configuration::HttpApi) -> StoppedApiServer { - ApiServer::new(cfg) +pub fn api_server(launcher: Launcher) -> StoppedApiServer { + ApiServer::new(launcher) } diff --git a/tests/servers/api/v1/contract/configuration.rs b/tests/servers/api/v1/contract/configuration.rs index cfdb59b0c..a551a8b36 100644 --- a/tests/servers/api/v1/contract/configuration.rs +++ b/tests/servers/api/v1/contract/configuration.rs @@ -1,18 +1,33 @@ -use torrust_tracker_test_helpers::configuration; +// use std::sync::Arc; -use crate::servers::api::test_environment::stopped_test_environment; +// use axum_server::tls_rustls::RustlsConfig; +// use futures::executor::block_on; +// use torrust_tracker_test_helpers::configuration; + +// use crate::common::app::setup_with_configuration; +// use crate::servers::api::test_environment::stopped_test_environment; #[tokio::test] #[ignore] #[should_panic = "Could not receive bind_address."] async fn should_fail_with_ssl_enabled_and_bad_ssl_config() { - let mut test_env = stopped_test_environment(configuration::ephemeral()); + // let tracker = setup_with_configuration(&Arc::new(configuration::ephemeral())); + + // let config = tracker.config.http_api.clone(); + + // let bind_to = config + // .bind_address + // .parse::() + // .expect("Tracker API bind_address invalid."); - let cfg = test_env.config_mut(); + // let tls = + // if let (true, Some(cert), Some(key)) = (&true, &Some("bad cert path".to_string()), &Some("bad cert path".to_string())) { + // Some(block_on(RustlsConfig::from_pem_file(cert, key)).expect("Could not read tls cert.")) + // } else { + // None + // }; - cfg.ssl_enabled = true; - cfg.ssl_key_path = Some("bad key path".to_string()); - cfg.ssl_cert_path = Some("bad cert path".to_string()); + // let test_env = new_stopped(tracker, bind_to, tls); - test_env.start().await; + // test_env.start().await; } diff --git a/tests/servers/health_check_api/test_environment.rs b/tests/servers/health_check_api/test_environment.rs index 46e54dc47..554e37dbf 100644 --- a/tests/servers/health_check_api/test_environment.rs +++ b/tests/servers/health_check_api/test_environment.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use tokio::sync::oneshot; use tokio::task::JoinHandle; -use torrust_tracker::bootstrap::jobs::health_check_api::ApiServerJobStarted; +use torrust_tracker::bootstrap::jobs::Started; use torrust_tracker::servers::health_check_api::server; use torrust_tracker_configuration::Configuration; @@ -16,7 +16,7 @@ pub async fn start(config: Arc) -> (SocketAddr, JoinHandle<()>) { .parse::() .expect("Health Check API bind_address invalid."); - let (tx, rx) = oneshot::channel::(); + let (tx, rx) = oneshot::channel::(); let join_handle = tokio::spawn(async move { let handle = server::start(bind_addr, tx, config.clone()); @@ -26,7 +26,7 @@ pub async fn start(config: Arc) -> (SocketAddr, JoinHandle<()>) { }); let bound_addr = match rx.await { - Ok(msg) => msg.bound_addr, + Ok(msg) => msg.address, Err(e) => panic!("the Health Check API server was dropped: {e}"), }; diff --git a/tests/servers/http/test_environment.rs b/tests/servers/http/test_environment.rs index e24e1b9a5..73961b790 100644 --- a/tests/servers/http/test_environment.rs +++ b/tests/servers/http/test_environment.rs @@ -1,16 +1,18 @@ use std::sync::Arc; +use futures::executor::block_on; +use torrust_tracker::bootstrap::jobs::make_rust_tls; use torrust_tracker::core::peer::Peer; use torrust_tracker::core::Tracker; -use torrust_tracker::servers::http::server::{HttpServer, HttpServerLauncher, RunningHttpServer, StoppedHttpServer}; +use torrust_tracker::servers::http::server::{HttpServer, Launcher, RunningHttpServer, StoppedHttpServer}; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use crate::common::app::setup_with_configuration; #[allow(clippy::module_name_repetitions, dead_code)] -pub type StoppedTestEnvironment = TestEnvironment>; +pub type StoppedTestEnvironment = TestEnvironment; #[allow(clippy::module_name_repetitions)] -pub type RunningTestEnvironment = TestEnvironment>; +pub type RunningTestEnvironment = TestEnvironment; pub struct TestEnvironment { pub cfg: Arc, @@ -19,12 +21,12 @@ pub struct TestEnvironment { } #[allow(dead_code)] -pub struct Stopped { - http_server: StoppedHttpServer, +pub struct Stopped { + http_server: StoppedHttpServer, } -pub struct Running { - http_server: RunningHttpServer, +pub struct Running { + http_server: RunningHttpServer, } impl TestEnvironment { @@ -34,14 +36,24 @@ impl TestEnvironment { } } -impl TestEnvironment> { +impl TestEnvironment { #[allow(dead_code)] pub fn new_stopped(cfg: torrust_tracker_configuration::Configuration) -> Self { let cfg = Arc::new(cfg); let tracker = setup_with_configuration(&cfg); - let http_server = http_server(cfg.http_trackers[0].clone()); + let config = cfg.http_trackers[0].clone(); + + let bind_to = config + .bind_address + .parse::() + .expect("Tracker API bind_address invalid."); + + let tls = block_on(make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path)) + .map(|tls| tls.expect("tls config failed")); + + let http_server = HttpServer::new(Launcher::new(bind_to, tls)); Self { cfg, @@ -51,7 +63,7 @@ impl TestEnvironment> { } #[allow(dead_code)] - pub async fn start(self) -> TestEnvironment> { + pub async fn start(self) -> TestEnvironment { TestEnvironment { cfg: self.cfg, tracker: self.tracker.clone(), @@ -61,25 +73,25 @@ impl TestEnvironment> { } } - #[allow(dead_code)] - pub fn config(&self) -> &torrust_tracker_configuration::HttpTracker { - &self.state.http_server.cfg - } + // #[allow(dead_code)] + // pub fn config(&self) -> &torrust_tracker_configuration::HttpTracker { + // &self.state.http_server.cfg + // } - #[allow(dead_code)] - pub fn config_mut(&mut self) -> &mut torrust_tracker_configuration::HttpTracker { - &mut self.state.http_server.cfg - } + // #[allow(dead_code)] + // pub fn config_mut(&mut self) -> &mut torrust_tracker_configuration::HttpTracker { + // &mut self.state.http_server.cfg + // } } -impl TestEnvironment> { +impl TestEnvironment { pub async fn new_running(cfg: torrust_tracker_configuration::Configuration) -> Self { let test_env = StoppedTestEnvironment::new_stopped(cfg); test_env.start().await } - pub async fn stop(self) -> TestEnvironment> { + pub async fn stop(self) -> TestEnvironment { TestEnvironment { cfg: self.cfg, tracker: self.tracker, @@ -90,31 +102,26 @@ impl TestEnvironment> { } pub fn bind_address(&self) -> &std::net::SocketAddr { - &self.state.http_server.state.bind_addr + &self.state.http_server.state.binding } - #[allow(dead_code)] - pub fn config(&self) -> &torrust_tracker_configuration::HttpTracker { - &self.state.http_server.cfg - } + // #[allow(dead_code)] + // pub fn config(&self) -> &torrust_tracker_configuration::HttpTracker { + // &self.state.http_server.cfg + // } } #[allow(clippy::module_name_repetitions, dead_code)] -pub fn stopped_test_environment( - cfg: torrust_tracker_configuration::Configuration, -) -> StoppedTestEnvironment { +pub fn stopped_test_environment(cfg: torrust_tracker_configuration::Configuration) -> StoppedTestEnvironment { TestEnvironment::new_stopped(cfg) } #[allow(clippy::module_name_repetitions)] -pub async fn running_test_environment( - cfg: torrust_tracker_configuration::Configuration, -) -> RunningTestEnvironment { +pub async fn running_test_environment(cfg: torrust_tracker_configuration::Configuration) -> RunningTestEnvironment { TestEnvironment::new_running(cfg).await } -pub fn http_server(cfg: torrust_tracker_configuration::HttpTracker) -> StoppedHttpServer { - let http_server = I::new(); - - HttpServer::new(cfg, http_server) +#[allow(dead_code)] +pub fn http_server(launcher: Launcher) -> StoppedHttpServer { + HttpServer::new(launcher) } diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 9a6aa2454..3034847db 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -2,11 +2,9 @@ use torrust_tracker_test_helpers::configuration; use crate::servers::http::test_environment::running_test_environment; -pub type V1 = torrust_tracker::servers::http::v1::launcher::Launcher; - #[tokio::test] async fn test_environment_should_be_started_and_stopped() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; test_env.stop().await; } @@ -18,11 +16,10 @@ mod for_all_config_modes { use crate::servers::http::client::Client; use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; #[tokio::test] async fn health_check_endpoint_should_return_ok_if_the_http_tracker_is_running() { - let test_env = running_test_environment::(configuration::ephemeral_with_reverse_proxy()).await; + let test_env = running_test_environment(configuration::ephemeral_with_reverse_proxy()).await; let response = Client::new(*test_env.bind_address()).health_check().await; @@ -40,14 +37,13 @@ mod for_all_config_modes { use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; #[tokio::test] async fn should_fail_when_the_http_request_does_not_include_the_xff_http_request_header() { // If the tracker is running behind a reverse proxy, the peer IP is the // right most IP in the `X-Forwarded-For` HTTP header, which is the IP of the proxy's client. - let test_env = running_test_environment::(configuration::ephemeral_with_reverse_proxy()).await; + let test_env = running_test_environment(configuration::ephemeral_with_reverse_proxy()).await; let params = QueryBuilder::default().query().params(); @@ -60,7 +56,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_xff_http_request_header_contains_an_invalid_ip() { - let test_env = running_test_environment::(configuration::ephemeral_with_reverse_proxy()).await; + let test_env = running_test_environment(configuration::ephemeral_with_reverse_proxy()).await; let params = QueryBuilder::default().query().params(); @@ -91,7 +87,7 @@ mod for_all_config_modes { use std::str::FromStr; use local_ip_address::local_ip; - use reqwest::Response; + use reqwest::{Response, StatusCode}; use tokio::net::TcpListener; use torrust_tracker::core::peer; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; @@ -108,11 +104,16 @@ mod for_all_config_modes { use crate::servers::http::responses; use crate::servers::http::responses::announce::{Announce, CompactPeer, CompactPeerList, DictionaryPeer}; use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; + + #[tokio::test] + async fn it_should_start_and_stop() { + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + test_env.stop().await; + } #[tokio::test] async fn should_respond_if_only_the_mandatory_fields_are_provided() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; let mut params = QueryBuilder::default().query().params(); @@ -127,7 +128,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_url_query_component_is_empty() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; let response = Client::new(*test_env.bind_address()).get("announce").await; @@ -138,7 +139,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_url_query_parameters_are_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; let invalid_query_param = "a=b=c"; @@ -153,7 +154,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_a_mandatory_field_is_missing() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; // Without `info_hash` param @@ -190,7 +191,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; let mut params = QueryBuilder::default().query().params(); @@ -212,7 +213,7 @@ mod for_all_config_modes { // 1. If tracker is NOT running `on_reverse_proxy` from the remote client IP. // 2. If tracker is running `on_reverse_proxy` from `X-Forwarded-For` request HTTP header. - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; let mut params = QueryBuilder::default().query().params(); @@ -227,7 +228,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_downloaded_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; let mut params = QueryBuilder::default().query().params(); @@ -246,7 +247,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_uploaded_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; let mut params = QueryBuilder::default().query().params(); @@ -265,7 +266,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_peer_id_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; let mut params = QueryBuilder::default().query().params(); @@ -291,7 +292,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_port_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; let mut params = QueryBuilder::default().query().params(); @@ -310,7 +311,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_left_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; let mut params = QueryBuilder::default().query().params(); @@ -329,7 +330,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_event_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; let mut params = QueryBuilder::default().query().params(); @@ -356,7 +357,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_compact_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral()).await; + let test_env = running_test_environment(configuration::ephemeral()).await; let mut params = QueryBuilder::default().query().params(); @@ -375,7 +376,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_no_peers_if_the_announced_peer_is_the_first_one() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let response = Client::new(*test_env.bind_address()) .announce( @@ -402,7 +403,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_list_of_previously_announced_peers() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -442,7 +443,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_list_of_previously_announced_peers_including_peers_using_ipv4_and_ipv6() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -492,7 +493,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_consider_two_peers_to_be_the_same_when_they_have_the_same_peer_id_even_if_the_ip_is_different() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); let peer = PeerBuilder::default().build(); @@ -519,7 +520,7 @@ mod for_all_config_modes { // Tracker Returns Compact Peer Lists // https://www.bittorrent.org/beps/bep_0023.html - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -560,7 +561,7 @@ mod for_all_config_modes { // code-review: the HTTP tracker does not return the compact response by default if the "compact" // param is not provided in the announce URL. The BEP 23 suggest to do so. - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -598,7 +599,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp4_connections_handled_in_statistics() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; Client::new(*test_env.bind_address()) .announce(&QueryBuilder::default().query()) @@ -622,7 +623,7 @@ mod for_all_config_modes { return; // we cannot bind to a ipv6 socket, so we will skip this test } - let test_env = running_test_environment::(configuration::ephemeral_ipv6()).await; + let test_env = running_test_environment(configuration::ephemeral_ipv6()).await; Client::bind(*test_env.bind_address(), IpAddr::from_str("::1").unwrap()) .announce(&QueryBuilder::default().query()) @@ -641,7 +642,7 @@ mod for_all_config_modes { async fn should_not_increase_the_number_of_tcp6_connections_handled_if_the_client_is_not_using_an_ipv6_ip() { // The tracker ignores the peer address in the request param. It uses the client remote ip address. - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; Client::new(*test_env.bind_address()) .announce( @@ -662,7 +663,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp4_announce_requests_handled_in_statistics() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; Client::new(*test_env.bind_address()) .announce(&QueryBuilder::default().query()) @@ -686,7 +687,7 @@ mod for_all_config_modes { return; // we cannot bind to a ipv6 socket, so we will skip this test } - let test_env = running_test_environment::(configuration::ephemeral_ipv6()).await; + let test_env = running_test_environment(configuration::ephemeral_ipv6()).await; Client::bind(*test_env.bind_address(), IpAddr::from_str("::1").unwrap()) .announce(&QueryBuilder::default().query()) @@ -705,7 +706,7 @@ mod for_all_config_modes { async fn should_not_increase_the_number_of_tcp6_announce_requests_handled_if_the_client_is_not_using_an_ipv6_ip() { // The tracker ignores the peer address in the request param. It uses the client remote ip address. - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; Client::new(*test_env.bind_address()) .announce( @@ -726,19 +727,22 @@ mod for_all_config_modes { #[tokio::test] async fn should_assign_to_the_peer_ip_the_remote_client_ip_instead_of_the_peer_address_in_the_request_param() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); let client_ip = local_ip().unwrap(); - let client = Client::bind(*test_env.bind_address(), client_ip); - let announce_query = QueryBuilder::default() .with_info_hash(&info_hash) .with_peer_addr(&IpAddr::from_str("2.2.2.2").unwrap()) .query(); - client.announce(&announce_query).await; + { + let client = Client::bind(*test_env.bind_address(), client_ip); + let status = client.announce(&announce_query).await.status(); + + assert_eq!(status, StatusCode::OK); + } let peers = test_env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; @@ -758,7 +762,7 @@ mod for_all_config_modes { 127.0.0.1 external_ip = "2.137.87.41" */ - let test_env = running_test_environment::(configuration::ephemeral_with_external_ip( + let test_env = running_test_environment(configuration::ephemeral_with_external_ip( IpAddr::from_str("2.137.87.41").unwrap(), )) .await; @@ -767,14 +771,17 @@ mod for_all_config_modes { let loopback_ip = IpAddr::from_str("127.0.0.1").unwrap(); let client_ip = loopback_ip; - let client = Client::bind(*test_env.bind_address(), client_ip); - let announce_query = QueryBuilder::default() .with_info_hash(&info_hash) .with_peer_addr(&IpAddr::from_str("2.2.2.2").unwrap()) .query(); - client.announce(&announce_query).await; + { + let client = Client::bind(*test_env.bind_address(), client_ip); + let status = client.announce(&announce_query).await.status(); + + assert_eq!(status, StatusCode::OK); + } let peers = test_env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; @@ -794,7 +801,7 @@ mod for_all_config_modes { ::1 external_ip = "2345:0425:2CA1:0000:0000:0567:5673:23b5" */ - let test_env = running_test_environment::(configuration::ephemeral_with_external_ip( + let test_env = running_test_environment(configuration::ephemeral_with_external_ip( IpAddr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap(), )) .await; @@ -803,14 +810,17 @@ mod for_all_config_modes { let loopback_ip = IpAddr::from_str("127.0.0.1").unwrap(); let client_ip = loopback_ip; - let client = Client::bind(*test_env.bind_address(), client_ip); - let announce_query = QueryBuilder::default() .with_info_hash(&info_hash) .with_peer_addr(&IpAddr::from_str("2.2.2.2").unwrap()) .query(); - client.announce(&announce_query).await; + { + let client = Client::bind(*test_env.bind_address(), client_ip); + let status = client.announce(&announce_query).await.status(); + + assert_eq!(status, StatusCode::OK); + } let peers = test_env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; @@ -830,21 +840,25 @@ mod for_all_config_modes { 145.254.214.256 X-Forwarded-For = 145.254.214.256 on_reverse_proxy = true 145.254.214.256 */ - let test_env = running_test_environment::(configuration::ephemeral_with_reverse_proxy()).await; + let test_env = running_test_environment(configuration::ephemeral_with_reverse_proxy()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - let client = Client::new(*test_env.bind_address()); - let announce_query = QueryBuilder::default().with_info_hash(&info_hash).query(); - client - .announce_with_header( - &announce_query, - "X-Forwarded-For", - "203.0.113.195,2001:db8:85a3:8d3:1319:8a2e:370:7348,150.172.238.178", - ) - .await; + { + let client = Client::new(*test_env.bind_address()); + let status = client + .announce_with_header( + &announce_query, + "X-Forwarded-For", + "203.0.113.195,2001:db8:85a3:8d3:1319:8a2e:370:7348,150.172.238.178", + ) + .await + .status(); + + assert_eq!(status, StatusCode::OK); + } let peers = test_env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; @@ -883,12 +897,11 @@ mod for_all_config_modes { use crate::servers::http::requests::scrape::QueryBuilder; use crate::servers::http::responses::scrape::{self, File, ResponseBuilder}; use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; //#[tokio::test] #[allow(dead_code)] async fn should_fail_when_the_request_is_empty() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let response = Client::new(*test_env.bind_address()).get("scrape").await; assert_missing_query_params_for_scrape_request_error_response(response).await; @@ -898,7 +911,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let mut params = QueryBuilder::default().query().params(); @@ -915,7 +928,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_file_with_the_incomplete_peer_when_there_is_one_peer_with_bytes_pending_to_download() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -955,7 +968,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_file_with_the_complete_peer_when_there_is_one_peer_with_no_bytes_pending_to_download() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -995,7 +1008,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_a_file_with_zeroed_values_when_there_are_no_peers() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1014,7 +1027,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_accept_multiple_infohashes() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let info_hash1 = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); let info_hash2 = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); @@ -1040,7 +1053,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_ot_tcp4_scrape_requests_handled_in_statistics() { - let test_env = running_test_environment::(configuration::ephemeral_mode_public()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1070,7 +1083,7 @@ mod for_all_config_modes { return; // we cannot bind to a ipv6 socket, so we will skip this test } - let test_env = running_test_environment::(configuration::ephemeral_ipv6()).await; + let test_env = running_test_environment(configuration::ephemeral_ipv6()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1105,11 +1118,10 @@ mod configured_as_whitelisted { use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; #[tokio::test] async fn should_fail_if_the_torrent_is_not_in_the_whitelist() { - let test_env = running_test_environment::(configuration::ephemeral_mode_whitelisted()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_whitelisted()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1124,7 +1136,7 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_allow_announcing_a_whitelisted_torrent() { - let test_env = running_test_environment::(configuration::ephemeral_mode_whitelisted()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_whitelisted()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1157,11 +1169,10 @@ mod configured_as_whitelisted { use crate::servers::http::requests; use crate::servers::http::responses::scrape::{File, ResponseBuilder}; use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; #[tokio::test] async fn should_return_the_zeroed_file_when_the_requested_file_is_not_whitelisted() { - let test_env = running_test_environment::(configuration::ephemeral_mode_whitelisted()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_whitelisted()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1192,7 +1203,7 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_return_the_file_stats_when_the_requested_file_is_whitelisted() { - let test_env = running_test_environment::(configuration::ephemeral_mode_whitelisted()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_whitelisted()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1252,11 +1263,10 @@ mod configured_as_private { use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; #[tokio::test] async fn should_respond_to_authenticated_peers() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; let expiring_key = test_env.tracker.generate_auth_key(Duration::from_secs(60)).await.unwrap(); @@ -1271,7 +1281,7 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_peer_has_not_provided_the_authentication_key() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1286,7 +1296,7 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; let invalid_key = "INVALID_KEY"; @@ -1301,7 +1311,7 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_peer_cannot_be_authenticated_with_the_provided_key() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; // The tracker does not have this key let unregistered_key = Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); @@ -1332,11 +1342,10 @@ mod configured_as_private { use crate::servers::http::requests; use crate::servers::http::responses::scrape::{File, ResponseBuilder}; use crate::servers::http::test_environment::running_test_environment; - use crate::servers::http::v1::contract::V1; #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; let invalid_key = "INVALID_KEY"; @@ -1351,7 +1360,7 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_zeroed_file_when_the_client_is_not_authenticated() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1382,7 +1391,7 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_real_file_stats_when_the_client_is_authenticated() { - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1427,7 +1436,7 @@ mod configured_as_private { // There is not authentication error // code-review: should this really be this way? - let test_env = running_test_environment::(configuration::ephemeral_mode_private()).await; + let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); diff --git a/tests/servers/udp/test_environment.rs b/tests/servers/udp/test_environment.rs index dfe19ac86..bbad6d927 100644 --- a/tests/servers/udp/test_environment.rs +++ b/tests/servers/udp/test_environment.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use torrust_tracker::core::peer::Peer; use torrust_tracker::core::Tracker; -use torrust_tracker::servers::udp::server::{RunningUdpServer, StoppedUdpServer, UdpServer}; +use torrust_tracker::servers::udp::server::{Launcher, RunningUdpServer, StoppedUdpServer, UdpServer}; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use crate::common::app::setup_with_configuration; @@ -43,7 +43,14 @@ impl TestEnvironment { let tracker = setup_with_configuration(&cfg); - let udp_server = udp_server(cfg.udp_trackers[0].clone()); + let udp_cfg = cfg.udp_trackers[0].clone(); + + let bind_to = udp_cfg + .bind_address + .parse::() + .expect("Tracker API bind_address invalid."); + + let udp_server = udp_server(Launcher::new(bind_to)); Self { cfg, @@ -81,7 +88,7 @@ impl TestEnvironment { } pub fn bind_address(&self) -> SocketAddr { - self.state.udp_server.state.bind_address + self.state.udp_server.state.binding } } @@ -95,6 +102,6 @@ pub async fn running_test_environment(cfg: torrust_tracker_configuration::Config TestEnvironment::new_running(cfg).await } -pub fn udp_server(cfg: torrust_tracker_configuration::UdpTracker) -> StoppedUdpServer { - UdpServer::new(cfg) +pub fn udp_server(launcher: Launcher) -> StoppedUdpServer { + UdpServer::new(launcher) } From cf613b8a1f66cd674ac39a05cb956ce89cc12052 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 9 Jan 2024 16:01:16 +0000 Subject: [PATCH 0166/1297] fix: [#588] broken grateful shutdown for tracker API The internal halt channel was nor working becuase the sender was being droped just after starting the server. That also made the `shutdown_signal` fail. ```rust pub async fn shutdown_signal(rx_halt: tokio::sync::oneshot::Receiver) { let halt = async { match rx_halt.await { Ok(signal) => signal, Err(err) => panic!("Failed to install stop signal: {err}"), } }; tokio::select! { signal = halt => { info!("Halt signal processed: {}", signal) }, () = global_shutdown_signal() => { info!("Global shutdown signal processed") } } } ``` Since the signal branch in the `tokio::select!` was finishing the global_shutdown_signal did not work either. So you had to kill the process manually to stop the tracker. It seems Rust droped partially the `Running::halt_taks` attribute and that closed the channel. --- src/bootstrap/jobs/tracker_apis.rs | 1 + src/servers/apis/server.rs | 23 +++++++++++++++++------ src/servers/signals.rs | 11 ++++++++--- 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index f454b017f..e50a83651 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -80,6 +80,7 @@ async fn start_v1(socket: SocketAddr, tls: Option, tracker: Arc { launcher }); - Ok(ApiServer { - state: Running { - binding: rx_start.await.expect("unable to start service").address, - halt_task: tx_halt, - task, + //let address = rx_start.await.expect("unable to start service").address; + let api_server = match rx_start.await { + Ok(started) => ApiServer { + state: Running { + binding: started.address, + halt_task: tx_halt, + task, + }, }, - }) + Err(err) => { + let msg = format!("unable to start API server: {err}"); + error!("{}", msg); + panic!("{}", msg); + } + }; + + Ok(api_server) } } diff --git a/src/servers/signals.rs b/src/servers/signals.rs index cb0675d65..091982ae3 100644 --- a/src/servers/signals.rs +++ b/src/servers/signals.rs @@ -46,11 +46,16 @@ pub async fn global_shutdown_signal() { /// /// Will panic if the `stop_receiver` resolves with an error. pub async fn shutdown_signal(rx_halt: tokio::sync::oneshot::Receiver) { - let halt = async { rx_halt.await.expect("Failed to install stop signal.") }; + let halt = async { + match rx_halt.await { + Ok(signal) => signal, + Err(err) => panic!("Failed to install stop signal: {err}"), + } + }; tokio::select! { - _ = halt => {}, - () = global_shutdown_signal() => {} + signal = halt => { info!("Halt signal processed: {}", signal) }, + () = global_shutdown_signal() => { info!("Global shutdown signal processed") } } } From 53613ec31eec23f569d3895c90f77ae5105f083d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 9 Jan 2024 16:19:15 +0000 Subject: [PATCH 0167/1297] feat: start log lines with capital --- src/bootstrap/jobs/mod.rs | 2 +- src/servers/apis/server.rs | 2 +- src/servers/http/server.rs | 2 +- src/servers/signals.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 3a9936882..2c12eb40e 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -22,7 +22,7 @@ pub struct Started { pub async fn make_rust_tls(enabled: bool, cert: &Option, key: &Option) -> Option> { if !enabled { - info!("tls not enabled"); + info!("TLS not enabled"); return None; } diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index f9507b0fb..b885bf348 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -170,7 +170,7 @@ impl Launcher { tokio::task::spawn(graceful_shutdown( handle.clone(), rx_halt, - format!("shutting down http server on socket address: {address}"), + format!("Shutting down http server on socket address: {address}"), )); let tls = self.tls.clone(); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index aee2d0ac0..c3411ac06 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -47,7 +47,7 @@ impl Launcher { tokio::task::spawn(graceful_shutdown( handle.clone(), rx_halt, - format!("shutting down http server on socket address: {address}"), + format!("Shutting down http server on socket address: {address}"), )); let tls = self.tls.clone(); diff --git a/src/servers/signals.rs b/src/servers/signals.rs index 091982ae3..42fd868e8 100644 --- a/src/servers/signals.rs +++ b/src/servers/signals.rs @@ -69,7 +69,7 @@ pub async fn shutdown_signal_with_message(rx_halt: tokio::sync::oneshot::Receive pub async fn graceful_shutdown(handle: axum_server::Handle, rx_halt: tokio::sync::oneshot::Receiver, message: String) { shutdown_signal_with_message(rx_halt, message).await; - info!("sending graceful shutdown signal"); + info!("Sending graceful shutdown signal"); handle.graceful_shutdown(Some(Duration::from_secs(90))); println!("!! shuting down in 90 seconds !!"); From ac18605ee563ee4f835803012cbbc2486bc97b13 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 9 Jan 2024 16:30:30 +0000 Subject: [PATCH 0168/1297] feat: improve log when starting the API Added the URL where the API is running. ``` 2024-01-09T16:29:46.911284166+00:00 [API][INFO] API server started on http://127.0.0.1:1212 ``` Some hosting services parse the application log output to discover services. For example, GitHub Codespaces can use that into to automatically do port forwarding. Besides, it's also useful for development when you are using random ports and to see what services are you running. --- src/servers/apis/server.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index b885bf348..5df1d76fd 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -30,7 +30,7 @@ use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; use derive_more::Constructor; use futures::future::BoxFuture; -use log::error; +use log::{error, info}; use tokio::sync::oneshot::{Receiver, Sender}; use super::routes::router; @@ -102,7 +102,6 @@ impl ApiServer { launcher }); - //let address = rx_start.await.expect("unable to start service").address; let api_server = match rx_start.await { Ok(started) => ApiServer { state: Running { @@ -112,7 +111,7 @@ impl ApiServer { }, }, Err(err) => { - let msg = format!("unable to start API server: {err}"); + let msg = format!("Unable to start API server: {err}"); error!("{}", msg); panic!("{}", msg); } @@ -170,10 +169,11 @@ impl Launcher { tokio::task::spawn(graceful_shutdown( handle.clone(), rx_halt, - format!("Shutting down http server on socket address: {address}"), + format!("Shutting down tracker API server on socket address: {address}"), )); let tls = self.tls.clone(); + let protocol = if tls.is_some() { "https" } else { "http" }; let running = Box::pin(async { match tls { @@ -181,18 +181,20 @@ impl Launcher { .handle(handle) .serve(router.into_make_service_with_connect_info::()) .await - .expect("Axum server crashed."), + .expect("Axum server for tracker API crashed."), None => axum_server::from_tcp(socket) .handle(handle) .serve(router.into_make_service_with_connect_info::()) .await - .expect("Axum server crashed."), + .expect("Axum server for tracker API crashed."), } }); + info!(target: "API", "API server started on {protocol}://{}", address); + tx_start .send(Started { address }) - .expect("the HTTP(s) Tracker service should not be dropped"); + .expect("the HTTP(s) Tracker API service should not be dropped"); running } From 452b4a0cd665e3e27d0e2440ea06e30a707eac00 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 9 Jan 2024 16:55:23 +0000 Subject: [PATCH 0169/1297] feat: improve http_health_check output --- src/bin/http_health_check.rs | 2 +- src/bootstrap/jobs/health_check_api.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bin/http_health_check.rs b/src/bin/http_health_check.rs index d3f1767cb..d66d334df 100644 --- a/src/bin/http_health_check.rs +++ b/src/bin/http_health_check.rs @@ -11,7 +11,7 @@ async fn main() { let args: Vec = env::args().collect(); if args.len() != 2 { eprintln!("Usage: cargo run --bin http_health_check "); - eprintln!("Example: cargo run --bin http_health_check http://127.0.0.1:1212/api/health_check"); + eprintln!("Example: cargo run --bin http_health_check http://127.0.0.1:1313/health_check"); std::process::exit(1); } diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index 83eb77f6b..a49f612e8 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -55,7 +55,7 @@ pub async fn start_job(config: Arc) -> JoinHandle<()> { // Wait until the API server job is running match rx_start.await { - Ok(msg) => info!("Torrust Health Check API server started on socket: {}", msg.address), + Ok(msg) => info!("Torrust Health Check API server started on: http://{}", msg.address), Err(e) => panic!("the Health Check API server was dropped: {e}"), } From 9f3f949359c5dab1c537166edcea692dea5765f0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 9 Jan 2024 18:44:11 +0000 Subject: [PATCH 0170/1297] fix: [#592] halt channel closed after starting HTTP tracker --- src/bootstrap/jobs/http_tracker.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 79e01fb3d..69ff345db 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -59,6 +59,10 @@ async fn start_v1(socket: SocketAddr, tls: Option, tracker: Arc Date: Tue, 9 Jan 2024 18:50:16 +0000 Subject: [PATCH 0171/1297] feat: improve logging for HTTP tracker bootstrapping --- src/servers/http/server.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index c3411ac06..904ccdcf5 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -6,6 +6,7 @@ use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; use derive_more::Constructor; use futures::future::BoxFuture; +use log::info; use tokio::sync::oneshot::{Receiver, Sender}; use super::v1::routes::router; @@ -51,6 +52,9 @@ impl Launcher { )); let tls = self.tls.clone(); + let protocol = if tls.is_some() { "https" } else { "http" }; + + info!(target: "HTTP Tracker", "Starting on: {protocol}://{}", address); let running = Box::pin(async { match tls { @@ -67,6 +71,8 @@ impl Launcher { } }); + info!(target: "HTTP Tracker", "Started on: {protocol}://{}", address); + tx_start .send(Started { address }) .expect("the HTTP(s) Tracker service should not be dropped"); From 0c1f38982d251d1d68063be475ef123d4a4a65e3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 10 Jan 2024 15:37:29 +0000 Subject: [PATCH 0172/1297] fix: [#591] panicking after starting UDP server due to close halt channel --- cSpell.json | 5 +- src/bootstrap/jobs/udp_tracker.rs | 11 ++++ src/servers/apis/server.rs | 4 +- src/servers/http/server.rs | 2 +- src/servers/udp/server.rs | 86 ++++++++++++++++++++----------- 5 files changed, 75 insertions(+), 33 deletions(-) diff --git a/cSpell.json b/cSpell.json index d09db93b7..9602ba39b 100644 --- a/cSpell.json +++ b/cSpell.json @@ -32,6 +32,7 @@ "Containerfile", "curr", "Cyberneering", + "datagram", "datetime", "Dijke", "distroless", @@ -79,6 +80,7 @@ "nonroot", "Norberg", "numwant", + "nvCFlJCq7fz7Qx6KoKTDiMZvns8l5Kw7", "oneshot", "ostr", "Pando", @@ -129,8 +131,7 @@ "Xtorrent", "Xunlei", "xxxxxxxxxxxxxxxxxxxxd", - "yyyyyyyyyyyyyyyyyyyyd", - "nvCFlJCq7fz7Qx6KoKTDiMZvns8l5Kw7" + "yyyyyyyyyyyyyyyyyyyyd" ], "enableFiletypes": [ "dockerfile", diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 5911bdf95..20ef0c793 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -8,6 +8,7 @@ //! for the configuration options. use std::sync::Arc; +use log::debug; use tokio::task::JoinHandle; use torrust_tracker_configuration::UdpTracker; @@ -36,10 +37,20 @@ pub async fn start_job(config: &UdpTracker, tracker: Arc) -> Join .expect("it should be able to start the udp tracker"); tokio::spawn(async move { + debug!(target: "UDP Tracker", "Wait for launcher (UDP service) to finish ..."); + debug!(target: "UDP Tracker", "Is halt channel closed before waiting?: {}", server.state.halt_task.is_closed()); + + assert!( + !server.state.halt_task.is_closed(), + "Halt channel for UDP tracker should be open" + ); + server .state .task .await .expect("it should be able to join to the udp tracker task"); + + debug!(target: "UDP Tracker", "Is halt channel closed after finishing the server?: {}", server.state.halt_task.is_closed()); }) } diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 5df1d76fd..f4fdf8994 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -175,6 +175,8 @@ impl Launcher { let tls = self.tls.clone(); let protocol = if tls.is_some() { "https" } else { "http" }; + info!(target: "API", "Starting on {protocol}://{}", address); + let running = Box::pin(async { match tls { Some(tls) => axum_server::from_tcp_rustls(socket, tls) @@ -190,7 +192,7 @@ impl Launcher { } }); - info!(target: "API", "API server started on {protocol}://{}", address); + info!(target: "API", "Started on {protocol}://{}", address); tx_start .send(Started { address }) diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 904ccdcf5..0a4b687b5 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -48,7 +48,7 @@ impl Launcher { tokio::task::spawn(graceful_shutdown( handle.clone(), rx_halt, - format!("Shutting down http server on socket address: {address}"), + format!("Shutting down HTTP server on socket address: {address}"), )); let tls = self.tls.clone(); diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index a0af55101..22cdf6357 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -120,23 +120,30 @@ impl UdpServer { let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); + assert!(!tx_halt.is_closed(), "Halt channel for UDP tracker should be open"); + let launcher = self.state.launcher; let task = tokio::spawn(async move { - launcher.start(tracker, tx_start, rx_halt).await; + debug!(target: "UDP Tracker", "Launcher starting ..."); + + let starting = launcher.start(tracker, tx_start, rx_halt).await; + + starting.await.expect("UDP server should have started running"); + launcher }); + let binding = rx_start.await.expect("unable to start service").address; + let running_udp_server: UdpServer = UdpServer { state: Running { - binding: rx_start.await.expect("unable to start service").address, + binding, halt_task: tx_halt, task, }, }; - info!("Running UDP Tracker on Socket: {}", running_udp_server.state.binding); - Ok(running_udp_server) } } @@ -202,41 +209,62 @@ impl Udp { tx_start: Sender, rx_halt: Receiver, ) -> JoinHandle<()> { - let binding = Arc::new(UdpSocket::bind(bind_to).await.expect("Could not bind to {self.socket}.")); - let address = binding.local_addr().expect("Could not get local_addr from {binding}."); + let socket = Arc::new(UdpSocket::bind(bind_to).await.expect("Could not bind to {self.socket}.")); + let address = socket.local_addr().expect("Could not get local_addr from {binding}."); + + info!(target: "UDP Tracker", "Starting on: udp://{}", address); let running = tokio::task::spawn(async move { - let halt = async move { - shutdown_signal_with_message(rx_halt, format!("Halting Http Service Bound to Socket: {address}")).await; + let halt = tokio::task::spawn(async move { + debug!(target: "UDP Tracker", "Waiting for halt signal for socket address: udp://{address} ..."); + + shutdown_signal_with_message( + rx_halt, + format!("Shutting down UDP server on socket address: udp://{address}"), + ) + .await; + }); + + let listen = async move { + debug!(target: "UDP Tracker", "Waiting for packets on socket address: udp://{address} ..."); + + loop { + let mut data = [0; MAX_PACKET_SIZE]; + let socket_clone = socket.clone(); + + match socket_clone.recv_from(&mut data).await { + Ok((valid_bytes, remote_addr)) => { + let payload = data[..valid_bytes].to_vec(); + + debug!(target: "UDP Tracker", "Received {} bytes", payload.len()); + debug!(target: "UDP Tracker", "From: {}", &remote_addr); + debug!(target: "UDP Tracker", "Payload: {:?}", payload); + + let response = handle_packet(remote_addr, payload, &tracker).await; + + Udp::send_response(socket_clone, remote_addr, response).await; + } + Err(err) => { + error!("Error reading UDP datagram from socket. Error: {:?}", err); + } + } + } }; pin_mut!(halt); + pin_mut!(listen); - loop { - let mut data = [0; MAX_PACKET_SIZE]; - let binding = binding.clone(); - - tokio::select! { - () = & mut halt => {}, - - Ok((valid_bytes, remote_addr)) = binding.recv_from(&mut data) => { - let payload = data[..valid_bytes].to_vec(); - - debug!("Received {} bytes", payload.len()); - debug!("From: {}", &remote_addr); - debug!("Payload: {:?}", payload); + tx_start + .send(Started { address }) + .expect("the UDP Tracker service should not be dropped"); - let response = handle_packet(remote_addr, payload, &tracker).await; - - Udp::send_response(binding, remote_addr, response).await; - } - } + tokio::select! { + _ = & mut halt => { debug!(target: "UDP Tracker", "Halt signal spawned task stopped on address: udp://{address}"); }, + () = & mut listen => { debug!(target: "UDP Tracker", "Socket listener stopped on address: udp://{address}"); }, } }); - tx_start - .send(Started { address }) - .expect("the UDP Tracker service should not be dropped"); + info!(target: "UDP Tracker", "Started on: udp://{}", address); running } From 5fd0c849d5a3865588446a78ae8c15dc9f8263b8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 11 Jan 2024 17:12:04 +0000 Subject: [PATCH 0173/1297] chore: normalize log ouput Added targets to all services especially when they start: [HTTP Tracker], [UDP Tracker], etc. ``` Loading default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... 2024-01-11T17:12:11.134816964+00:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized. 2024-01-11T17:12:11.135473883+00:00 [UDP Tracker][INFO] Starting on: udp://0.0.0.0:6969 2024-01-11T17:12:11.135494422+00:00 [UDP Tracker][INFO] Started on: udp://0.0.0.0:6969 2024-01-11T17:12:11.135503672+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled 2024-01-11T17:12:11.135587738+00:00 [HTTP Tracker][INFO] Starting on: http://0.0.0.0:7070 2024-01-11T17:12:11.135612497+00:00 [HTTP Tracker][INFO] Started on: http://0.0.0.0:7070 2024-01-11T17:12:11.135619586+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled 2024-01-11T17:12:11.135675454+00:00 [API][INFO] Starting on http://127.0.0.1:1212 2024-01-11T17:12:11.135688443+00:00 [API][INFO] Started on http://127.0.0.1:1212 2024-01-11T17:12:11.135701143+00:00 [Health Check API][INFO] Starting on: http://127.0.0.1:1313 2024-01-11T17:12:11.135718012+00:00 [Health Check API][INFO] Started on: http://127.0.0.1:1313 ``` --- src/bootstrap/jobs/health_check_api.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index a49f612e8..9fed56435 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -44,18 +44,18 @@ pub async fn start_job(config: Arc) -> JoinHandle<()> { // Run the API server let join_handle = tokio::spawn(async move { - info!("Starting Health Check API server: http://{}", bind_addr); + info!(target: "Health Check API", "Starting on: http://{}", bind_addr); let handle = server::start(bind_addr, tx_start, config.clone()); if let Ok(()) = handle.await { - info!("Health Check API server on http://{} stopped", bind_addr); + info!(target: "Health Check API", "Stopped server running on: http://{}", bind_addr); } }); // Wait until the API server job is running match rx_start.await { - Ok(msg) => info!("Torrust Health Check API server started on: http://{}", msg.address), + Ok(msg) => info!(target: "Health Check API", "Started on: http://{}", msg.address), Err(e) => panic!("the Health Check API server was dropped: {e}"), } From cca17d5a45f00eed1a7a5e0e62d842b438d31bf1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 8 Jan 2024 16:36:52 +0000 Subject: [PATCH 0174/1297] refactor: rename `non-compact` to `normal` --- src/servers/http/v1/handlers/announce.rs | 4 +- src/servers/http/v1/responses/announce.rs | 48 ++++++++++++----------- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 0522042b1..23d8b2d6e 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -120,10 +120,10 @@ fn build_response(announce_request: &Announce, announce_data: AnnounceData) -> R match &announce_request.compact { Some(compact) => match compact { Compact::Accepted => announce::Compact::from(announce_data).into_response(), - Compact::NotAccepted => announce::NonCompact::from(announce_data).into_response(), + Compact::NotAccepted => announce::Normal::from(announce_data).into_response(), }, // Default response format non compact - None => announce::NonCompact::from(announce_data).into_response(), + None => announce::Normal::from(announce_data).into_response(), } } diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index 8a245476b..52155f171 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -20,22 +20,22 @@ use crate::servers::http::v1::responses; /// /// ```rust /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -/// use torrust_tracker::servers::http::v1::responses::announce::{NonCompact, Peer}; +/// use torrust_tracker::servers::http::v1::responses::announce::{Normal, NormalPeer}; /// -/// let response = NonCompact { +/// let response = Normal { /// interval: 111, /// interval_min: 222, /// complete: 333, /// incomplete: 444, /// peers: vec![ /// // IPV4 -/// Peer { +/// NormalPeer { /// peer_id: *b"-qB00000000000000001", /// ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 /// port: 0x7070, // 28784 /// }, /// // IPV6 -/// Peer { +/// NormalPeer { /// peer_id: *b"-qB00000000000000002", /// ip: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), /// port: 0x7070, // 28784 @@ -57,7 +57,7 @@ use crate::servers::http::v1::responses; /// Refer to [BEP 03: The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) /// for more information. #[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct NonCompact { +pub struct Normal { /// Interval in seconds that the client should wait between sending regular /// announce requests to the tracker. /// @@ -88,24 +88,24 @@ pub struct NonCompact { /// Number of non-seeder peers, aka "leechers". pub incomplete: u32, /// A list of peers. The value is a list of dictionaries. - pub peers: Vec, + pub peers: Vec, } -/// Peer information in the [`NonCompact`] +/// Peer information in the [`Normal`] /// response. /// /// ```rust /// use std::net::{IpAddr, Ipv4Addr}; -/// use torrust_tracker::servers::http::v1::responses::announce::{NonCompact, Peer}; +/// use torrust_tracker::servers::http::v1::responses::announce::{Normal, NormalPeer}; /// -/// let peer = Peer { +/// let peer = NormalPeer { /// peer_id: *b"-qB00000000000000001", /// ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 /// port: 0x7070, // 28784 /// }; /// ``` #[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct Peer { +pub struct NormalPeer { /// The peer's ID. pub peer_id: [u8; 20], /// The peer's IP address. @@ -114,7 +114,7 @@ pub struct Peer { pub port: u16, } -impl Peer { +impl NormalPeer { #[must_use] pub fn ben_map(&self) -> BencodeMut<'_> { ben_map! { @@ -125,9 +125,9 @@ impl Peer { } } -impl From for Peer { +impl From for NormalPeer { fn from(peer: core::peer::Peer) -> Self { - Peer { + NormalPeer { peer_id: peer.peer_id.to_bytes(), ip: peer.peer_addr.ip(), port: peer.peer_addr.port(), @@ -135,7 +135,7 @@ impl From for Peer { } } -impl NonCompact { +impl Normal { /// Returns the bencoded body of the non-compact response. /// /// # Panics @@ -160,15 +160,19 @@ impl NonCompact { } } -impl IntoResponse for NonCompact { +impl IntoResponse for Normal { fn into_response(self) -> Response { (StatusCode::OK, self.body()).into_response() } } -impl From for NonCompact { +impl From for Normal { fn from(domain_announce_response: AnnounceData) -> Self { - let peers: Vec = domain_announce_response.peers.iter().map(|peer| Peer::from(*peer)).collect(); + let peers: Vec = domain_announce_response + .peers + .iter() + .map(|peer| NormalPeer::from(*peer)) + .collect(); Self { interval: domain_announce_response.interval, @@ -424,7 +428,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; - use super::{NonCompact, Peer}; + use super::{Normal, NormalPeer}; use crate::servers::http::v1::responses::announce::{Compact, CompactPeer}; // Some ascii values used in tests: @@ -440,21 +444,21 @@ mod tests { // is also a valid string which makes asserts more readable. #[test] - fn non_compact_announce_response_can_be_bencoded() { - let response = NonCompact { + fn normal_announce_response_can_be_bencoded() { + let response = Normal { interval: 111, interval_min: 222, complete: 333, incomplete: 444, peers: vec![ // IPV4 - Peer { + NormalPeer { peer_id: *b"-qB00000000000000001", ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 port: 0x7070, // 28784 }, // IPV6 - Peer { + NormalPeer { peer_id: *b"-qB00000000000000002", ip: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), port: 0x7070, // 28784 From d4adfa791501b222ead98be9ab39314a52e8c77a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 8 Jan 2024 16:43:44 +0000 Subject: [PATCH 0175/1297] refactor: extract config struct `AnnouncePolicy` --- packages/configuration/src/lib.rs | 67 +++++++++----- src/servers/http/mod.rs | 2 +- src/servers/http/v1/requests/announce.rs | 2 +- src/servers/http/v1/responses/announce.rs | 103 ++++++++-------------- 4 files changed, 83 insertions(+), 91 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 1c0979524..58de94582 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -387,26 +387,9 @@ pub struct HealthCheckApi { pub bind_address: String, } -/// 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, - /// Tracker mode. See [`TrackerMode`] for more information. - pub mode: TrackerMode, - - // Database configuration - /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. - pub db_driver: DatabaseDriver, - /// Database connection string. The format depends on the database driver. - /// For `Sqlite3`, the format is `path/to/database.db`, for example: - /// `./storage/tracker/lib/database/sqlite3.db`. - /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for - /// example: `root:password@localhost:3306/torrust`. - pub db_path: String, - +/// Announce policy +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Copy)] +pub struct AnnouncePolicy { /// Interval in seconds that the client should wait between sending regular /// announce requests to the tracker. /// @@ -418,7 +401,8 @@ pub struct Configuration { /// client's initial request. It serves as a guideline for clients to know /// how often they should contact the tracker for updates on the peer list, /// while ensuring that the tracker is not overwhelmed with requests. - pub announce_interval: u32, + pub interval: u32, + /// Minimum announce interval. Clients must not reannounce more frequently /// than this. /// @@ -430,6 +414,42 @@ pub struct Configuration { /// value to prevent sending too many requests in a short period, which /// could lead to excessive load on the tracker or even getting banned by /// the tracker for not adhering to the rules. + pub interval_min: u32, +} + +impl Default for AnnouncePolicy { + fn default() -> Self { + Self { + interval: 120, + interval_min: 120, + } + } +} + +/// 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, + /// Tracker mode. See [`TrackerMode`] for more information. + pub mode: TrackerMode, + + // Database configuration + /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. + pub db_driver: DatabaseDriver, + /// Database connection string. The format depends on the database driver. + /// For `Sqlite3`, the format is `path/to/database.db`, for example: + /// `./storage/tracker/lib/database/sqlite3.db`. + /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for + /// example: `root:password@localhost:3306/torrust`. + pub db_path: String, + + /// See [`AnnouncePolicy::interval`] + pub announce_interval: u32, + + /// See [`AnnouncePolicy::interval_min`] pub min_announce_interval: u32, /// Weather the tracker is behind a reverse proxy or not. /// If the tracker is behind a reverse proxy, the `X-Forwarded-For` header @@ -516,13 +536,14 @@ impl From for Error { impl Default for Configuration { fn default() -> Self { + let announce_policy = AnnouncePolicy::default(); let mut configuration = Configuration { log_level: Option::from(String::from("info")), mode: TrackerMode::Public, db_driver: DatabaseDriver::Sqlite3, db_path: String::from("./storage/tracker/lib/database/sqlite3.db"), - announce_interval: 120, - min_announce_interval: 120, + 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")), diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index b2d232fc6..e4e42b1c3 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -152,7 +152,7 @@ //! 000000f0: 65 e //! ``` //! -//! Refer to the [`NonCompact`](crate::servers::http::v1::responses::announce::NonCompact) +//! Refer to the [`Normal`](crate::servers::http::v1::responses::announce::Normal) //! response for more information about the response. //! //! **Sample compact response** diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index 7f77f727d..f65d22929 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -180,7 +180,7 @@ impl fmt::Display for Event { /// Depending on the value of this param, the tracker will return a different /// response: /// -/// - [`NonCompact`](crate::servers::http::v1::responses::announce::NonCompact) response. +/// - [`Normal`](crate::servers::http::v1::responses::announce::Normal) response. /// - [`Compact`](crate::servers::http::v1::responses::announce::Compact) response. /// /// Refer to [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index 52155f171..b19a311d8 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -9,6 +9,7 @@ use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use serde::{self, Deserialize, Serialize}; use thiserror::Error; +use torrust_tracker_configuration::AnnouncePolicy; use torrust_tracker_contrib_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; use crate::core::{self, AnnounceData}; @@ -20,11 +21,14 @@ use crate::servers::http::v1::responses; /// /// ```rust /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +/// use torrust_tracker_configuration::AnnouncePolicy; /// use torrust_tracker::servers::http::v1::responses::announce::{Normal, NormalPeer}; /// /// let response = Normal { -/// interval: 111, -/// interval_min: 222, +/// policy: AnnouncePolicy { +/// interval: 111, +/// interval_min: 222, +/// }, /// complete: 333, /// incomplete: 444, /// peers: vec![ @@ -58,31 +62,8 @@ use crate::servers::http::v1::responses; /// for more information. #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Normal { - /// Interval in seconds that the client should wait between sending regular - /// announce requests to the tracker. - /// - /// It's a **recommended** wait time between announcements. - /// - /// This is the standard amount of time that clients should wait between - /// sending consecutive announcements to the tracker. This value is set by - /// the tracker and is typically provided in the tracker's response to a - /// client's initial request. It serves as a guideline for clients to know - /// how often they should contact the tracker for updates on the peer list, - /// while ensuring that the tracker is not overwhelmed with requests. - pub interval: u32, - /// Minimum announce interval. Clients must not reannounce more frequently - /// than this. - /// - /// It establishes the shortest allowed wait time. - /// - /// This is an optional parameter in the protocol that the tracker may - /// provide in its response. It sets a lower limit on the frequency at which - /// clients are allowed to send announcements. Clients should respect this - /// value to prevent sending too many requests in a short period, which - /// could lead to excessive load on the tracker or even getting banned by - /// the tracker for not adhering to the rules. - #[serde(rename = "min interval")] - pub interval_min: u32, + /// Announce policy + pub policy: AnnouncePolicy, /// Number of peers with the entire file, i.e. seeders. pub complete: u32, /// Number of non-seeder peers, aka "leechers". @@ -152,8 +133,8 @@ impl Normal { (ben_map! { "complete" => ben_int!(i64::from(self.complete)), "incomplete" => ben_int!(i64::from(self.incomplete)), - "interval" => ben_int!(i64::from(self.interval)), - "min interval" => ben_int!(i64::from(self.interval_min)), + "interval" => ben_int!(i64::from(self.policy.interval)), + "min interval" => ben_int!(i64::from(self.policy.interval_min)), "peers" => peers_list.clone() }) .encode() @@ -175,8 +156,10 @@ impl From for Normal { .collect(); Self { - interval: domain_announce_response.interval, - interval_min: domain_announce_response.interval_min, + policy: AnnouncePolicy { + interval: domain_announce_response.interval, + interval_min: domain_announce_response.interval_min, + }, complete: domain_announce_response.swarm_stats.seeders, incomplete: domain_announce_response.swarm_stats.leechers, peers, @@ -192,11 +175,14 @@ impl From for Normal { /// /// ```rust /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +/// use torrust_tracker_configuration::AnnouncePolicy; /// use torrust_tracker::servers::http::v1::responses::announce::{Compact, CompactPeer}; /// /// let response = Compact { -/// interval: 111, -/// interval_min: 222, +/// policy: AnnouncePolicy { +/// interval: 111, +/// interval_min: 222, +/// }, /// complete: 333, /// incomplete: 444, /// peers: vec![ @@ -232,31 +218,8 @@ impl From for Normal { /// - [BEP 07: IPv6 Tracker Extension](https://www.bittorrent.org/beps/bep_0007.html) #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Compact { - /// Interval in seconds that the client should wait between sending regular - /// announce requests to the tracker. - /// - /// It's a **recommended** wait time between announcements. - /// - /// This is the standard amount of time that clients should wait between - /// sending consecutive announcements to the tracker. This value is set by - /// the tracker and is typically provided in the tracker's response to a - /// client's initial request. It serves as a guideline for clients to know - /// how often they should contact the tracker for updates on the peer list, - /// while ensuring that the tracker is not overwhelmed with requests. - pub interval: u32, - /// Minimum announce interval. Clients must not reannounce more frequently - /// than this. - /// - /// It establishes the shortest allowed wait time. - /// - /// This is an optional parameter in the protocol that the tracker may - /// provide in its response. It sets a lower limit on the frequency at which - /// clients are allowed to send announcements. Clients should respect this - /// value to prevent sending too many requests in a short period, which - /// could lead to excessive load on the tracker or even getting banned by - /// the tracker for not adhering to the rules. - #[serde(rename = "min interval")] - pub interval_min: u32, + /// Announce policy + pub policy: AnnouncePolicy, /// Number of seeders, aka "completed". pub complete: u32, /// Number of non-seeder peers, aka "incomplete". @@ -335,8 +298,8 @@ impl Compact { let bytes = (ben_map! { "complete" => ben_int!(i64::from(self.complete)), "incomplete" => ben_int!(i64::from(self.incomplete)), - "interval" => ben_int!(i64::from(self.interval)), - "min interval" => ben_int!(i64::from(self.interval_min)), + "interval" => ben_int!(i64::from(self.policy.interval)), + "min interval" => ben_int!(i64::from(self.policy.interval_min)), "peers" => ben_bytes!(self.peers_v4_bytes()?), "peers6" => ben_bytes!(self.peers_v6_bytes()?) }) @@ -414,8 +377,10 @@ impl From for Compact { .collect(); Self { - interval: domain_announce_response.interval, - interval_min: domain_announce_response.interval_min, + policy: AnnouncePolicy { + interval: domain_announce_response.interval, + interval_min: domain_announce_response.interval_min, + }, complete: domain_announce_response.swarm_stats.seeders, incomplete: domain_announce_response.swarm_stats.leechers, peers, @@ -428,6 +393,8 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + use torrust_tracker_configuration::AnnouncePolicy; + use super::{Normal, NormalPeer}; use crate::servers::http::v1::responses::announce::{Compact, CompactPeer}; @@ -446,8 +413,10 @@ mod tests { #[test] fn normal_announce_response_can_be_bencoded() { let response = Normal { - interval: 111, - interval_min: 222, + policy: AnnouncePolicy { + interval: 111, + interval_min: 222, + }, complete: 333, incomplete: 444, peers: vec![ @@ -480,8 +449,10 @@ mod tests { #[test] fn compact_announce_response_can_be_bencoded() { let response = Compact { - interval: 111, - interval_min: 222, + policy: AnnouncePolicy { + interval: 111, + interval_min: 222, + }, complete: 333, incomplete: 444, peers: vec![ From 58a57d364022f9a63b4592d9c833a7040acb77a2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 8 Jan 2024 16:52:32 +0000 Subject: [PATCH 0176/1297] refactor: extract struct SwarmStats (da2ce7): Merge `SwarmStats` into `SwarmMetadata`. --- packages/configuration/src/lib.rs | 2 +- src/core/mod.rs | 12 ++-- src/core/torrent/mod.rs | 14 +---- src/core/torrent/repository.rs | 30 ++++----- src/servers/http/v1/responses/announce.rs | 77 +++++++++++++---------- src/servers/http/v1/services/announce.rs | 6 +- src/servers/udp/handlers.rs | 8 +-- 7 files changed, 75 insertions(+), 74 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 58de94582..6b3056e85 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -388,7 +388,7 @@ pub struct HealthCheckApi { } /// Announce policy -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Copy)] +#[derive(PartialEq, Eq, Debug, Clone, Copy)] pub struct AnnouncePolicy { /// Interval in seconds that the client should wait between sending regular /// announce requests to the tracker. diff --git a/src/core/mod.rs b/src/core/mod.rs index beb4b133d..646558d55 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -732,7 +732,7 @@ impl Tracker { let (stats, stats_updated) = self.torrents.update_torrent_with_peer_and_get_stats(info_hash, peer).await; if self.config.persistent_torrent_completed_stat && stats_updated { - let completed = stats.completed; + let completed = stats.downloaded; let info_hash = *info_hash; drop(self.database.save_persistent_torrent(&info_hash, completed).await); @@ -1390,7 +1390,7 @@ mod tests { let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; - assert_eq!(announce_data.swarm_stats.seeders, 1); + assert_eq!(announce_data.swarm_stats.complete, 1); } #[tokio::test] @@ -1401,7 +1401,7 @@ mod tests { let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; - assert_eq!(announce_data.swarm_stats.leechers, 1); + assert_eq!(announce_data.swarm_stats.incomplete, 1); } #[tokio::test] @@ -1415,7 +1415,7 @@ mod tests { let mut completed_peer = completed_peer(); let announce_data = tracker.announce(&sample_info_hash(), &mut completed_peer, &peer_ip()).await; - assert_eq!(announce_data.swarm_stats.completed, 1); + assert_eq!(announce_data.swarm_stats.downloaded, 1); } } } @@ -1739,11 +1739,11 @@ mod tests { peer.event = AnnounceEvent::Started; let swarm_stats = tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; - assert_eq!(swarm_stats.completed, 0); + assert_eq!(swarm_stats.downloaded, 0); peer.event = AnnounceEvent::Completed; let swarm_stats = tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; - assert_eq!(swarm_stats.completed, 1); + assert_eq!(swarm_stats.downloaded, 1); // Remove the newly updated torrent from memory tracker.torrents.get_torrents_mut().await.remove(&info_hash); diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index 79828d368..82e37ecb2 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -73,18 +73,8 @@ impl SwarmMetadata { } } -/// Swarm statistics for one torrent. -/// -/// See [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) -#[derive(Debug, PartialEq, Default)] -pub struct SwarmStats { - /// The number of peers that have ever completed downloading - pub completed: u32, - /// The number of active peers that have completed downloading (seeders) - pub seeders: u32, - /// The number of active peers that have not completed downloading (leechers) - pub leechers: u32, -} +/// [`SwarmStats`] has the same form as [`SwarmMetadata`] +pub type SwarmStats = SwarmMetadata; impl Entry { #[must_use] diff --git a/src/core/torrent/repository.rs b/src/core/torrent/repository.rs index ac3d03054..d4f8ee5e3 100644 --- a/src/core/torrent/repository.rs +++ b/src/core/torrent/repository.rs @@ -77,9 +77,9 @@ impl Repository for Sync { ( SwarmStats { - completed: stats.1, - seeders: stats.0, - leechers: stats.2, + downloaded: stats.1, + complete: stats.0, + incomplete: stats.2, }, stats_updated, ) @@ -131,9 +131,9 @@ impl Repository for SyncSingle { ( SwarmStats { - completed: stats.1, - seeders: stats.0, - leechers: stats.2, + downloaded: stats.1, + complete: stats.0, + incomplete: stats.2, }, stats_updated, ) @@ -176,9 +176,9 @@ impl TRepositoryAsync for RepositoryAsync { ( SwarmStats { - completed: stats.1, - seeders: stats.0, - leechers: stats.2, + downloaded: stats.1, + complete: stats.0, + incomplete: stats.2, }, stats_updated, ) @@ -234,9 +234,9 @@ impl TRepositoryAsync for AsyncSync { ( SwarmStats { - completed: stats.1, - seeders: stats.0, - leechers: stats.2, + downloaded: stats.1, + complete: stats.0, + incomplete: stats.2, }, stats_updated, ) @@ -281,9 +281,9 @@ impl TRepositoryAsync for RepositoryAsyncSingle { ( SwarmStats { - completed: stats.1, - seeders: stats.0, - leechers: stats.2, + downloaded: stats.1, + complete: stats.0, + incomplete: stats.2, }, stats_updated, ) diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index b19a311d8..14ae9156d 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -7,11 +7,11 @@ use std::panic::Location; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; -use serde::{self, Deserialize, Serialize}; use thiserror::Error; use torrust_tracker_configuration::AnnouncePolicy; use torrust_tracker_contrib_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; +use crate::core::torrent::SwarmStats; use crate::core::{self, AnnounceData}; use crate::servers::http::v1::responses; @@ -22,6 +22,7 @@ use crate::servers::http::v1::responses; /// ```rust /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; /// use torrust_tracker_configuration::AnnouncePolicy; +/// use torrust_tracker::core::torrent::SwarmStats; /// use torrust_tracker::servers::http::v1::responses::announce::{Normal, NormalPeer}; /// /// let response = Normal { @@ -29,8 +30,11 @@ use crate::servers::http::v1::responses; /// interval: 111, /// interval_min: 222, /// }, -/// complete: 333, -/// incomplete: 444, +/// stats: SwarmStats { +/// downloaded: 0, +/// complete: 333, +/// incomplete: 444, +/// }, /// peers: vec![ /// // IPV4 /// NormalPeer { @@ -60,15 +64,10 @@ use crate::servers::http::v1::responses; /// /// Refer to [BEP 03: The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) /// for more information. -#[derive(Serialize, Deserialize, Debug, PartialEq)] +#[derive(Debug, PartialEq)] pub struct Normal { - /// Announce policy pub policy: AnnouncePolicy, - /// Number of peers with the entire file, i.e. seeders. - pub complete: u32, - /// Number of non-seeder peers, aka "leechers". - pub incomplete: u32, - /// A list of peers. The value is a list of dictionaries. + pub stats: SwarmStats, pub peers: Vec, } @@ -85,7 +84,7 @@ pub struct Normal { /// port: 0x7070, // 28784 /// }; /// ``` -#[derive(Serialize, Deserialize, Debug, PartialEq)] +#[derive(Debug, PartialEq)] pub struct NormalPeer { /// The peer's ID. pub peer_id: [u8; 20], @@ -131,8 +130,8 @@ impl Normal { } (ben_map! { - "complete" => ben_int!(i64::from(self.complete)), - "incomplete" => ben_int!(i64::from(self.incomplete)), + "complete" => ben_int!(i64::from(self.stats.complete)), + "incomplete" => ben_int!(i64::from(self.stats.incomplete)), "interval" => ben_int!(i64::from(self.policy.interval)), "min interval" => ben_int!(i64::from(self.policy.interval_min)), "peers" => peers_list.clone() @@ -160,8 +159,11 @@ impl From for Normal { interval: domain_announce_response.interval, interval_min: domain_announce_response.interval_min, }, - complete: domain_announce_response.swarm_stats.seeders, - incomplete: domain_announce_response.swarm_stats.leechers, + stats: SwarmStats { + complete: domain_announce_response.swarm_stats.complete, + incomplete: domain_announce_response.swarm_stats.incomplete, + downloaded: 0, + }, peers, } } @@ -176,6 +178,7 @@ impl From for Normal { /// ```rust /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; /// use torrust_tracker_configuration::AnnouncePolicy; +/// use torrust_tracker::core::torrent::SwarmStats; /// use torrust_tracker::servers::http::v1::responses::announce::{Compact, CompactPeer}; /// /// let response = Compact { @@ -183,8 +186,11 @@ impl From for Normal { /// interval: 111, /// interval_min: 222, /// }, -/// complete: 333, -/// incomplete: 444, +/// stats: SwarmStats { +/// downloaded: 0, +/// complete: 333, +/// incomplete: 444, +/// }, /// peers: vec![ /// // IPV4 /// CompactPeer { @@ -216,15 +222,10 @@ impl From for Normal { /// /// - [BEP 23: Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) /// - [BEP 07: IPv6 Tracker Extension](https://www.bittorrent.org/beps/bep_0007.html) -#[derive(Serialize, Deserialize, Debug, PartialEq)] +#[derive(Debug, PartialEq)] pub struct Compact { - /// Announce policy pub policy: AnnouncePolicy, - /// Number of seeders, aka "completed". - pub complete: u32, - /// Number of non-seeder peers, aka "incomplete". - pub incomplete: u32, - /// Compact peer list. + pub stats: SwarmStats, pub peers: Vec, } @@ -250,7 +251,7 @@ pub struct Compact { /// /// Refer to [BEP 23: Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) /// for more information. -#[derive(Serialize, Deserialize, Debug, PartialEq)] +#[derive(Debug, PartialEq)] pub struct CompactPeer { /// The peer's IP address. pub ip: IpAddr, @@ -296,8 +297,8 @@ impl Compact { /// Will return `Err` if internally interrupted. pub fn body(&self) -> Result, Box> { let bytes = (ben_map! { - "complete" => ben_int!(i64::from(self.complete)), - "incomplete" => ben_int!(i64::from(self.incomplete)), + "complete" => ben_int!(i64::from(self.stats.complete)), + "incomplete" => ben_int!(i64::from(self.stats.incomplete)), "interval" => ben_int!(i64::from(self.policy.interval)), "min interval" => ben_int!(i64::from(self.policy.interval_min)), "peers" => ben_bytes!(self.peers_v4_bytes()?), @@ -381,8 +382,11 @@ impl From for Compact { interval: domain_announce_response.interval, interval_min: domain_announce_response.interval_min, }, - complete: domain_announce_response.swarm_stats.seeders, - incomplete: domain_announce_response.swarm_stats.leechers, + stats: SwarmStats { + complete: domain_announce_response.swarm_stats.complete, + incomplete: domain_announce_response.swarm_stats.incomplete, + downloaded: 0, + }, peers, } } @@ -396,6 +400,7 @@ mod tests { use torrust_tracker_configuration::AnnouncePolicy; use super::{Normal, NormalPeer}; + use crate::core::torrent::SwarmStats; use crate::servers::http::v1::responses::announce::{Compact, CompactPeer}; // Some ascii values used in tests: @@ -417,8 +422,11 @@ mod tests { interval: 111, interval_min: 222, }, - complete: 333, - incomplete: 444, + stats: SwarmStats { + downloaded: 0, + complete: 333, + incomplete: 444, + }, peers: vec![ // IPV4 NormalPeer { @@ -453,8 +461,11 @@ mod tests { interval: 111, interval_min: 222, }, - complete: 333, - incomplete: 444, + stats: SwarmStats { + downloaded: 0, + complete: 333, + incomplete: 444, + }, peers: vec![ // IPV4 CompactPeer { diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index bdf8afc87..547dcd35b 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -114,9 +114,9 @@ mod tests { let expected_announce_data = AnnounceData { peers: vec![], swarm_stats: SwarmStats { - completed: 0, - seeders: 1, - leechers: 0, + downloaded: 0, + complete: 1, + incomplete: 0, }, interval: tracker.config.announce_interval, interval_min: tracker.config.min_announce_interval, diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 18a341418..4e3080b37 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -152,8 +152,8 @@ pub async fn handle_announce( let announce_response = AnnounceResponse { transaction_id: wrapped_announce_request.announce_request.transaction_id, announce_interval: AnnounceInterval(i64::from(tracker.config.announce_interval) as i32), - leechers: NumberOfPeers(i64::from(response.swarm_stats.leechers) as i32), - seeders: NumberOfPeers(i64::from(response.swarm_stats.seeders) as i32), + leechers: NumberOfPeers(i64::from(response.swarm_stats.incomplete) as i32), + seeders: NumberOfPeers(i64::from(response.swarm_stats.complete) as i32), peers: response .peers .iter() @@ -177,8 +177,8 @@ pub async fn handle_announce( let announce_response = AnnounceResponse { transaction_id: wrapped_announce_request.announce_request.transaction_id, announce_interval: AnnounceInterval(i64::from(tracker.config.announce_interval) as i32), - leechers: NumberOfPeers(i64::from(response.swarm_stats.leechers) as i32), - seeders: NumberOfPeers(i64::from(response.swarm_stats.seeders) as i32), + leechers: NumberOfPeers(i64::from(response.swarm_stats.incomplete) as i32), + seeders: NumberOfPeers(i64::from(response.swarm_stats.complete) as i32), peers: response .peers .iter() From 0e6fe3309b65a674e6bcb968dde4b2e59af536d2 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 10 Jan 2024 15:52:59 +1100 Subject: [PATCH 0177/1297] dev: Announce Responce Cleanup --- Cargo.lock | 1 + Cargo.toml | 9 +- cSpell.json | 1 + packages/configuration/Cargo.toml | 1 + packages/configuration/src/lib.rs | 4 +- src/core/databases/mod.rs | 2 +- src/core/mod.rs | 34 +- src/core/peer.rs | 80 ++- src/core/torrent/mod.rs | 13 +- src/servers/http/mod.rs | 2 +- src/servers/http/v1/handlers/announce.rs | 15 +- src/servers/http/v1/requests/announce.rs | 2 +- src/servers/http/v1/responses/announce.rs | 597 +++++++----------- src/servers/http/v1/responses/mod.rs | 12 + src/servers/http/v1/services/announce.rs | 6 +- src/servers/udp/handlers.rs | 8 +- tests/common/fixtures.rs | 66 -- .../servers/api/v1/contract/context/stats.rs | 2 +- .../api/v1/contract/context/torrent.rs | 2 +- tests/servers/http/v1/contract.rs | 10 +- 20 files changed, 396 insertions(+), 471 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9b7c10f39..de630b497 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3462,6 +3462,7 @@ name = "torrust-tracker-configuration" version = "3.0.0-alpha.12-develop" dependencies = [ "config", + "derive_more", "log", "serde", "serde_with", diff --git a/Cargo.toml b/Cargo.toml index 64f913e4f..daf3c0259 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -79,7 +79,14 @@ serde_urlencoded = "0" torrust-tracker-test-helpers = { version = "3.0.0-alpha.12-develop", path = "packages/test-helpers" } [workspace] -members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers", "packages/torrent-repository-benchmarks"] +members = [ + "contrib/bencode", + "packages/configuration", + "packages/located-error", + "packages/primitives", + "packages/test-helpers", + "packages/torrent-repository-benchmarks", +] [profile.dev] debug = 1 diff --git a/cSpell.json b/cSpell.json index 9602ba39b..7b3ce4de9 100644 --- a/cSpell.json +++ b/cSpell.json @@ -50,6 +50,7 @@ "Hydranode", "Icelake", "imdl", + "impls", "incompletei", "infohash", "infohashes", diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index e373b4269..ecc8c976e 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -16,6 +16,7 @@ version.workspace = true [dependencies] config = "0" +derive_more = "0" log = { version = "0", features = ["release_max_level_info"] } serde = { version = "1", features = ["derive"] } serde_with = "3" diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 6b3056e85..a8f605289 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -236,6 +236,7 @@ use std::sync::Arc; use std::{env, fs}; use config::{Config, ConfigError, File, FileFormat}; +use derive_more::Constructor; use serde::{Deserialize, Serialize}; use serde_with::{serde_as, NoneAsEmptyString}; use thiserror::Error; @@ -388,7 +389,7 @@ pub struct HealthCheckApi { } /// Announce policy -#[derive(PartialEq, Eq, Debug, Clone, Copy)] +#[derive(PartialEq, Eq, Debug, Clone, Copy, Constructor)] pub struct AnnouncePolicy { /// Interval in seconds that the client should wait between sending regular /// announce requests to the tracker. @@ -537,6 +538,7 @@ impl From for Error { impl Default for Configuration { fn default() -> Self { let announce_policy = AnnouncePolicy::default(); + let mut configuration = Configuration { log_level: Option::from(String::from("info")), mode: TrackerMode::Public, diff --git a/src/core/databases/mod.rs b/src/core/databases/mod.rs index 14fcb6b5b..b80b11987 100644 --- a/src/core/databases/mod.rs +++ b/src/core/databases/mod.rs @@ -134,7 +134,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to save. - async fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error>; + async fn save_persistent_torrent(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error>; // Whitelist diff --git a/src/core/mod.rs b/src/core/mod.rs index 646558d55..fc44877c8 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -98,12 +98,12 @@ //! //! ```rust,no_run //! use torrust_tracker::core::peer::Peer; +//! use torrust_tracker_configuration::AnnouncePolicy; //! //! pub struct AnnounceData { //! pub peers: Vec, //! pub swarm_stats: SwarmStats, -//! pub interval: u32, // Option `announce_interval` from core tracker configuration -//! pub interval_min: u32, // Option `min_announce_interval` from core tracker configuration +//! pub policy: AnnouncePolicy, // the tracker announce policy. //! } //! //! pub struct SwarmStats { @@ -445,9 +445,10 @@ use std::panic::Location; use std::sync::Arc; use std::time::Duration; +use derive_more::Constructor; use futures::future::join_all; use tokio::sync::mpsc::error::SendError; -use torrust_tracker_configuration::Configuration; +use torrust_tracker_configuration::{AnnouncePolicy, Configuration}; use torrust_tracker_primitives::TrackerMode; use self::auth::Key; @@ -487,7 +488,7 @@ pub struct Tracker { /// Structure that holds general `Tracker` torrents metrics. /// /// Metrics are aggregate values for all torrents. -#[derive(Debug, PartialEq, Default)] +#[derive(Copy, Clone, Debug, PartialEq, Default)] pub struct TorrentsMetrics { /// Total number of seeders for all torrents pub seeders: u64, @@ -500,20 +501,14 @@ pub struct TorrentsMetrics { } /// Structure that holds the data returned by the `announce` request. -#[derive(Debug, PartialEq, Default)] +#[derive(Clone, Debug, PartialEq, Constructor, Default)] pub struct AnnounceData { /// The list of peers that are downloading the same torrent. /// It excludes the peer that made the request. pub peers: Vec, /// Swarm statistics - pub swarm_stats: SwarmStats, - /// The interval in seconds that the client should wait between sending - /// regular requests to the tracker. - /// Refer to [`announce_interval`](torrust_tracker_configuration::Configuration::announce_interval). - pub interval: u32, - /// The minimum announce interval in seconds that the client should wait. - /// Refer to [`min_announce_interval`](torrust_tracker_configuration::Configuration::min_announce_interval). - pub interval_min: u32, + pub stats: SwarmStats, + pub policy: AnnouncePolicy, } /// Structure that holds the data returned by the `scrape` request. @@ -628,11 +623,12 @@ impl Tracker { let peers = self.get_torrent_peers_for_peer(info_hash, peer).await; + let policy = AnnouncePolicy::new(self.config.announce_interval, self.config.min_announce_interval); + AnnounceData { peers, - swarm_stats, - interval: self.config.announce_interval, - interval_min: self.config.min_announce_interval, + stats: swarm_stats, + policy, } } @@ -1390,7 +1386,7 @@ mod tests { let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; - assert_eq!(announce_data.swarm_stats.complete, 1); + assert_eq!(announce_data.stats.complete, 1); } #[tokio::test] @@ -1401,7 +1397,7 @@ mod tests { let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; - assert_eq!(announce_data.swarm_stats.incomplete, 1); + assert_eq!(announce_data.stats.incomplete, 1); } #[tokio::test] @@ -1415,7 +1411,7 @@ mod tests { let mut completed_peer = completed_peer(); let announce_data = tracker.announce(&sample_info_hash(), &mut completed_peer, &peer_ip()).await; - assert_eq!(announce_data.swarm_stats.downloaded, 1); + assert_eq!(announce_data.stats.downloaded, 1); } } } diff --git a/src/core/peer.rs b/src/core/peer.rs index a64f87b66..03489ce30 100644 --- a/src/core/peer.rs +++ b/src/core/peer.rs @@ -277,9 +277,85 @@ impl Serialize for Id { } } -#[cfg(test)] -mod test { +pub mod fixture { + use std::net::SocketAddr; + + use aquatic_udp_protocol::NumberOfBytes; + + use super::{Id, Peer}; + + #[derive(PartialEq, Debug)] + + pub struct PeerBuilder { + peer: Peer, + } + + #[allow(clippy::derivable_impls)] + impl Default for PeerBuilder { + fn default() -> Self { + Self { peer: Peer::default() } + } + } + + impl PeerBuilder { + #[allow(dead_code)] + #[must_use] + pub fn with_peer_id(mut self, peer_id: &Id) -> Self { + self.peer.peer_id = *peer_id; + self + } + + #[allow(dead_code)] + #[must_use] + pub fn with_peer_addr(mut self, peer_addr: &SocketAddr) -> Self { + self.peer.peer_addr = *peer_addr; + self + } + + #[allow(dead_code)] + #[must_use] + pub fn with_bytes_pending_to_download(mut self, left: i64) -> Self { + self.peer.left = NumberOfBytes(left); + self + } + #[allow(dead_code)] + #[must_use] + pub fn with_no_bytes_pending_to_download(mut self) -> Self { + self.peer.left = NumberOfBytes(0); + self + } + + #[allow(dead_code)] + #[must_use] + pub fn build(self) -> Peer { + self.into() + } + + #[allow(dead_code)] + #[must_use] + pub fn into(self) -> Peer { + self.peer + } + } + + impl Default for Peer { + fn default() -> Self { + Self { + peer_id: Id(*b"-qB00000000000000000"), + peer_addr: std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: crate::shared::clock::DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes(0), + downloaded: NumberOfBytes(0), + left: NumberOfBytes(0), + event: aquatic_udp_protocol::AnnounceEvent::Started, + } + } + } +} + +#[cfg(test)] +pub mod test { mod torrent_peer_id { use crate::core::peer; diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index 82e37ecb2..d19a97be1 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -33,6 +33,7 @@ pub mod repository; use std::time::Duration; use aquatic_udp_protocol::AnnounceEvent; +use derive_more::Constructor; use serde::{Deserialize, Serialize}; use super::peer::{self, Peer}; @@ -56,13 +57,13 @@ pub struct Entry { /// Swarm metadata dictionary in the scrape response. /// /// See [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) -#[derive(Debug, PartialEq, Default)] +#[derive(Copy, Clone, Debug, PartialEq, Default, Constructor)] pub struct SwarmMetadata { - /// The number of peers that have ever completed downloading - pub downloaded: u32, - /// The number of active peers that have completed downloading (seeders) - pub complete: u32, - /// The number of active peers that have not completed downloading (leechers) + /// (i.e `completed`): The number of peers that have ever completed downloading + pub downloaded: u32, // + /// (i.e `seeders`): The number of active peers that have completed downloading (seeders) + pub complete: u32, //seeders + /// (i.e `leechers`): The number of active peers that have not completed downloading (leechers) pub incomplete: u32, } diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index e4e42b1c3..08a59ef90 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -152,7 +152,7 @@ //! 000000f0: 65 e //! ``` //! -//! Refer to the [`Normal`](crate::servers::http::v1::responses::announce::Normal) +//! Refer to the [`Normal`](crate::servers::http::v1::responses::announce::Normal), i.e. `Non-Compact` //! response for more information about the response. //! //! **Sample compact response** diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 23d8b2d6e..cfe422e7f 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -22,7 +22,7 @@ use crate::servers::http::v1::extractors::authentication_key::Extract as Extract use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::handlers::common::auth; use crate::servers::http::v1::requests::announce::{Announce, Compact, Event}; -use crate::servers::http::v1::responses::{self, announce}; +use crate::servers::http::v1::responses::{self}; use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; use crate::servers::http::v1::services::{self, peer_ip_resolver}; use crate::shared::clock::{Current, Time}; @@ -117,13 +117,12 @@ async fn handle_announce( } fn build_response(announce_request: &Announce, announce_data: AnnounceData) -> Response { - match &announce_request.compact { - Some(compact) => match compact { - Compact::Accepted => announce::Compact::from(announce_data).into_response(), - Compact::NotAccepted => announce::Normal::from(announce_data).into_response(), - }, - // Default response format non compact - None => announce::Normal::from(announce_data).into_response(), + if announce_request.compact.as_ref().is_some_and(|f| *f == Compact::Accepted) { + let response: responses::Announce = announce_data.into(); + response.into_response() + } else { + let response: responses::Announce = announce_data.into(); + response.into_response() } } diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index f65d22929..08dd9da29 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -180,7 +180,7 @@ impl fmt::Display for Event { /// Depending on the value of this param, the tracker will return a different /// response: /// -/// - [`Normal`](crate::servers::http::v1::responses::announce::Normal) response. +/// - [`Normal`](crate::servers::http::v1::responses::announce::Normal), i.e. a `non-compact` response. /// - [`Compact`](crate::servers::http::v1::responses::announce::Compact) response. /// /// Refer to [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index 14ae9156d..b1b474ea9 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -2,237 +2,217 @@ //! //! Data structures and logic to build the `announce` response. use std::io::Write; -use std::net::IpAddr; -use std::panic::Location; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use axum::http::StatusCode; -use axum::response::{IntoResponse, Response}; -use thiserror::Error; -use torrust_tracker_configuration::AnnouncePolicy; +use derive_more::{AsRef, Constructor, From}; use torrust_tracker_contrib_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; -use crate::core::torrent::SwarmStats; +use super::Response; +use crate::core::peer::Peer; use crate::core::{self, AnnounceData}; use crate::servers::http::v1::responses; -/// Normal (non compact) `announce` response. +/// An [`Announce`] response, that can be anything that is convertible from [`AnnounceData`]. /// -/// It's a bencoded dictionary. +/// The [`Announce`] can built from any data that implements: [`From`] and [`Into>`]. /// -/// ```rust -/// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -/// use torrust_tracker_configuration::AnnouncePolicy; -/// use torrust_tracker::core::torrent::SwarmStats; -/// use torrust_tracker::servers::http::v1::responses::announce::{Normal, NormalPeer}; +/// The two standard forms of an announce response are: [`Normal`] and [`Compact`]. /// -/// let response = Normal { -/// policy: AnnouncePolicy { -/// interval: 111, -/// interval_min: 222, -/// }, -/// stats: SwarmStats { -/// downloaded: 0, -/// complete: 333, -/// incomplete: 444, -/// }, -/// peers: vec![ -/// // IPV4 -/// NormalPeer { -/// peer_id: *b"-qB00000000000000001", -/// ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 -/// port: 0x7070, // 28784 -/// }, -/// // IPV6 -/// NormalPeer { -/// peer_id: *b"-qB00000000000000002", -/// ip: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), -/// port: 0x7070, // 28784 -/// }, -/// ], -/// }; /// -/// let bytes = response.body(); -/// -/// // The expected bencoded response. -/// let expected_bytes = b"d8:completei333e10:incompletei444e8:intervali111e12:min intervali222e5:peersld2:ip15:105.105.105.1057:peer id20:-qB000000000000000014:porti28784eed2:ip39:6969:6969:6969:6969:6969:6969:6969:69697:peer id20:-qB000000000000000024:porti28784eeee"; +/// _"To reduce the size of tracker responses and to reduce memory and +/// computational requirements in trackers, trackers may return peers as a +/// packed string rather than as a bencoded list."_ /// -/// assert_eq!( -/// String::from_utf8(bytes).unwrap(), -/// String::from_utf8(expected_bytes.to_vec()).unwrap() -/// ); -/// ``` +/// Refer to the official BEPs for more information: /// -/// Refer to [BEP 03: The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -/// for more information. -#[derive(Debug, PartialEq)] -pub struct Normal { - pub policy: AnnouncePolicy, - pub stats: SwarmStats, - pub peers: Vec, +/// - [BEP 03: The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) +/// - [BEP 23: Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) +/// - [BEP 07: IPv6 Tracker Extension](https://www.bittorrent.org/beps/bep_0007.html) + +#[derive(Debug, AsRef, PartialEq, Constructor)] +pub struct Announce +where + E: From + Into>, +{ + data: E, } -/// Peer information in the [`Normal`] -/// response. -/// -/// ```rust -/// use std::net::{IpAddr, Ipv4Addr}; -/// use torrust_tracker::servers::http::v1::responses::announce::{Normal, NormalPeer}; -/// -/// let peer = NormalPeer { -/// peer_id: *b"-qB00000000000000001", -/// ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 -/// port: 0x7070, // 28784 -/// }; -/// ``` -#[derive(Debug, PartialEq)] -pub struct NormalPeer { - /// The peer's ID. - pub peer_id: [u8; 20], - /// The peer's IP address. - pub ip: IpAddr, - /// The peer's port number. - pub port: u16, +/// Build any [`Announce`] from an [`AnnounceData`]. +impl + Into>> From for Announce { + fn from(data: AnnounceData) -> Self { + Self::new(data.into()) + } } -impl NormalPeer { - #[must_use] - pub fn ben_map(&self) -> BencodeMut<'_> { - ben_map! { - "peer id" => ben_bytes!(self.peer_id.clone().to_vec()), - "ip" => ben_bytes!(self.ip.to_string()), - "port" => ben_int!(i64::from(self.port)) - } +/// Convert any Announce [`Announce`] into a [`axum::response::Response`] +impl + Into>> axum::response::IntoResponse for Announce +where + Announce: Response, +{ + fn into_response(self) -> axum::response::Response { + axum::response::IntoResponse::into_response(self.body().map(|bytes| (StatusCode::OK, bytes))) } } -impl From for NormalPeer { - fn from(peer: core::peer::Peer) -> Self { - NormalPeer { - peer_id: peer.peer_id.to_bytes(), - ip: peer.peer_addr.ip(), - port: peer.peer_addr.port(), +/// Implement the [`Response`] for the [`Announce`]. +/// +impl + Into>> Response for Announce { + fn body(self) -> Result, responses::error::Error> { + Ok(self.data.into()) + } +} + +/// Format of the [`Normal`] (Non-Compact) Encoding +pub struct Normal { + complete: i64, + incomplete: i64, + interval: i64, + min_interval: i64, + peers: Vec, +} + +impl From for Normal { + fn from(data: AnnounceData) -> Self { + Self { + complete: data.stats.complete.into(), + incomplete: data.stats.incomplete.into(), + interval: data.policy.interval.into(), + min_interval: data.policy.interval_min.into(), + peers: data.peers.into_iter().collect(), } } } -impl Normal { - /// Returns the bencoded body of the non-compact response. - /// - /// # Panics - /// - /// Will return an error if it can't access the bencode as a mutable `BListAccess`. - #[must_use] - pub fn body(&self) -> Vec { +#[allow(clippy::from_over_into)] +impl Into> for Normal { + fn into(self) -> Vec { let mut peers_list = ben_list!(); let peers_list_mut = peers_list.list_mut().unwrap(); for peer in &self.peers { - peers_list_mut.push(peer.ben_map()); + peers_list_mut.push(peer.into()); } (ben_map! { - "complete" => ben_int!(i64::from(self.stats.complete)), - "incomplete" => ben_int!(i64::from(self.stats.incomplete)), - "interval" => ben_int!(i64::from(self.policy.interval)), - "min interval" => ben_int!(i64::from(self.policy.interval_min)), + "complete" => ben_int!(self.complete), + "incomplete" => ben_int!(self.incomplete), + "interval" => ben_int!(self.interval), + "min interval" => ben_int!(self.min_interval), "peers" => peers_list.clone() }) .encode() } } -impl IntoResponse for Normal { - fn into_response(self) -> Response { - (StatusCode::OK, self.body()).into_response() - } +/// Format of the [`Compact`] Encoding +pub struct Compact { + complete: i64, + incomplete: i64, + interval: i64, + min_interval: i64, + peers: Vec, + peers6: Vec, } -impl From for Normal { - fn from(domain_announce_response: AnnounceData) -> Self { - let peers: Vec = domain_announce_response - .peers - .iter() - .map(|peer| NormalPeer::from(*peer)) - .collect(); +impl From for Compact { + fn from(data: AnnounceData) -> Self { + let compact_peers: Vec = data.peers.into_iter().collect(); + + let (peers, peers6): (Vec>, Vec>) = + compact_peers.into_iter().collect(); + + let peers_encoded: CompactPeersEncoded = peers.into_iter().collect(); + let peers_encoded_6: CompactPeersEncoded = peers6.into_iter().collect(); Self { - policy: AnnouncePolicy { - interval: domain_announce_response.interval, - interval_min: domain_announce_response.interval_min, - }, - stats: SwarmStats { - complete: domain_announce_response.swarm_stats.complete, - incomplete: domain_announce_response.swarm_stats.incomplete, - downloaded: 0, - }, - peers, + complete: data.stats.complete.into(), + incomplete: data.stats.incomplete.into(), + interval: data.policy.interval.into(), + min_interval: data.policy.interval_min.into(), + peers: peers_encoded.0, + peers6: peers_encoded_6.0, } } } -/// Compact `announce` response. -/// -/// _"To reduce the size of tracker responses and to reduce memory and -/// computational requirements in trackers, trackers may return peers as a -/// packed string rather than as a bencoded list."_ +#[allow(clippy::from_over_into)] +impl Into> for Compact { + fn into(self) -> Vec { + (ben_map! { + "complete" => ben_int!(self.complete), + "incomplete" => ben_int!(self.incomplete), + "interval" => ben_int!(self.interval), + "min interval" => ben_int!(self.min_interval), + "peers" => ben_bytes!(self.peers), + "peers6" => ben_bytes!(self.peers6) + }) + .encode() + } +} + +/// Marker Trait for Peer Vectors +pub trait PeerEncoding: From + PartialEq {} + +impl FromIterator for Vec

{ + fn from_iter>(iter: T) -> Self { + let mut peers: Vec

= vec![]; + + for peer in iter { + peers.push(peer.into()); + } + + peers + } +} + +/// A [`NormalPeer`], for the [`Normal`] form. /// /// ```rust -/// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -/// use torrust_tracker_configuration::AnnouncePolicy; -/// use torrust_tracker::core::torrent::SwarmStats; -/// use torrust_tracker::servers::http::v1::responses::announce::{Compact, CompactPeer}; +/// use std::net::{IpAddr, Ipv4Addr}; +/// use torrust_tracker::servers::http::v1::responses::announce::{Normal, NormalPeer}; /// -/// let response = Compact { -/// policy: AnnouncePolicy { -/// interval: 111, -/// interval_min: 222, -/// }, -/// stats: SwarmStats { -/// downloaded: 0, -/// complete: 333, -/// incomplete: 444, -/// }, -/// peers: vec![ -/// // IPV4 -/// CompactPeer { -/// ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 -/// port: 0x7070, // 28784 -/// }, -/// // IPV6 -/// CompactPeer { -/// ip: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), -/// port: 0x7070, // 28784 -/// }, -/// ], +/// let peer = NormalPeer { +/// peer_id: *b"-qB00000000000000001", +/// ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 +/// port: 0x7070, // 28784 /// }; /// -/// let bytes = response.body().unwrap(); -/// -/// // The expected bencoded response. -/// let expected_bytes = -/// // cspell:disable-next-line -/// b"d8:completei333e10:incompletei444e8:intervali111e12:min intervali222e5:peers6:iiiipp6:peers618:iiiiiiiiiiiiiiiippe"; -/// -/// assert_eq!( -/// String::from_utf8(bytes).unwrap(), -/// String::from_utf8(expected_bytes.to_vec()).unwrap() -/// ); -/// ``` -/// -/// Refer to the official BEPs for more information: -/// -/// - [BEP 23: Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) -/// - [BEP 07: IPv6 Tracker Extension](https://www.bittorrent.org/beps/bep_0007.html) +/// ``` #[derive(Debug, PartialEq)] -pub struct Compact { - pub policy: AnnouncePolicy, - pub stats: SwarmStats, - pub peers: Vec, +pub struct NormalPeer { + /// The peer's ID. + pub peer_id: [u8; 20], + /// The peer's IP address. + pub ip: IpAddr, + /// The peer's port number. + pub port: u16, +} + +impl PeerEncoding for NormalPeer {} + +impl From for NormalPeer { + fn from(peer: core::peer::Peer) -> Self { + NormalPeer { + peer_id: peer.peer_id.to_bytes(), + ip: peer.peer_addr.ip(), + port: peer.peer_addr.port(), + } + } } -/// Compact peer. It's used in the [`Compact`] -/// response. +impl From<&NormalPeer> for BencodeMut<'_> { + fn from(value: &NormalPeer) -> Self { + ben_map! { + "peer id" => ben_bytes!(value.peer_id.clone().to_vec()), + "ip" => ben_bytes!(value.ip.to_string()), + "port" => ben_int!(i64::from(value.port)) + } + } +} + +/// A [`CompactPeer`], for the [`Compact`] form. /// -/// _"To reduce the size of tracker responses and to reduce memory and +/// _"To reduce the size of tracker responses and to reduce memory and /// computational requirements in trackers, trackers may return peers as a /// packed string rather than as a bencoded list."_ /// @@ -240,168 +220,107 @@ pub struct Compact { /// the peer's ID. /// /// ```rust -/// use std::net::{IpAddr, Ipv4Addr}; -/// use torrust_tracker::servers::http::v1::responses::announce::CompactPeer; +/// use std::net::{IpAddr, Ipv4Addr}; +/// use torrust_tracker::servers::http::v1::responses::announce::{Compact, CompactPeer, CompactPeerData}; /// -/// let compact_peer = CompactPeer { -/// ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 -/// port: 0x7070 // 28784 -/// }; -/// ``` +/// let peer = CompactPeer::V4(CompactPeerData { +/// ip: Ipv4Addr::new(0x69, 0x69, 0x69, 0x69), // 105.105.105.105 +/// port: 0x7070, // 28784 +/// }); +/// +/// ``` /// /// Refer to [BEP 23: Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) /// for more information. -#[derive(Debug, PartialEq)] -pub struct CompactPeer { +#[derive(Clone, Debug, PartialEq)] +pub enum CompactPeer { /// The peer's IP address. - pub ip: IpAddr, + V4(CompactPeerData), /// The peer's port number. - pub port: u16, + V6(CompactPeerData), } -impl CompactPeer { - /// Returns the compact peer as a byte vector. - /// - /// # Errors - /// - /// Will return `Err` if internally interrupted. - pub fn bytes(&self) -> Result, Box> { - let mut bytes: Vec = Vec::new(); - match self.ip { - IpAddr::V4(ip) => { - bytes.write_all(&u32::from(ip).to_be_bytes())?; - } - IpAddr::V6(ip) => { - bytes.write_all(&u128::from(ip).to_be_bytes())?; - } - } - bytes.write_all(&self.port.to_be_bytes())?; - Ok(bytes) - } -} +impl PeerEncoding for CompactPeer {} impl From for CompactPeer { fn from(peer: core::peer::Peer) -> Self { - CompactPeer { - ip: peer.peer_addr.ip(), - port: peer.peer_addr.port(), + match (peer.peer_addr.ip(), peer.peer_addr.port()) { + (IpAddr::V4(ip), port) => Self::V4(CompactPeerData { ip, port }), + (IpAddr::V6(ip), port) => Self::V6(CompactPeerData { ip, port }), } } } -impl Compact { - /// Returns the bencoded compact response as a byte vector. - /// - /// # Errors - /// - /// Will return `Err` if internally interrupted. - pub fn body(&self) -> Result, Box> { - let bytes = (ben_map! { - "complete" => ben_int!(i64::from(self.stats.complete)), - "incomplete" => ben_int!(i64::from(self.stats.incomplete)), - "interval" => ben_int!(i64::from(self.policy.interval)), - "min interval" => ben_int!(i64::from(self.policy.interval_min)), - "peers" => ben_bytes!(self.peers_v4_bytes()?), - "peers6" => ben_bytes!(self.peers_v6_bytes()?) - }) - .encode(); +/// The [`CompactPeerData`], that made with either a [`Ipv4Addr`], or [`Ipv6Addr`] along with a `port`. +/// +#[derive(Clone, Debug, PartialEq)] +pub struct CompactPeerData { + /// The peer's IP address. + pub ip: V, + /// The peer's port number. + pub port: u16, +} - Ok(bytes) - } +impl FromIterator for (Vec>, Vec>) { + fn from_iter>(iter: T) -> Self { + let mut peers_v4: Vec> = vec![]; + let mut peers_v6: Vec> = vec![]; - fn peers_v4_bytes(&self) -> Result, Box> { - let mut bytes: Vec = Vec::new(); - for compact_peer in &self.peers { - match compact_peer.ip { - IpAddr::V4(_ip) => { - let peer_bytes = compact_peer.bytes()?; - bytes.write_all(&peer_bytes)?; - } - IpAddr::V6(_) => {} + for peer in iter { + match peer { + CompactPeer::V4(peer) => peers_v4.push(peer), + CompactPeer::V6(peer6) => peers_v6.push(peer6), } } - Ok(bytes) - } - fn peers_v6_bytes(&self) -> Result, Box> { - let mut bytes: Vec = Vec::new(); - for compact_peer in &self.peers { - match compact_peer.ip { - IpAddr::V6(_ip) => { - let peer_bytes = compact_peer.bytes()?; - bytes.write_all(&peer_bytes)?; - } - IpAddr::V4(_) => {} - } - } - Ok(bytes) + (peers_v4, peers_v6) } } -/// `Compact` response serialization error. -#[derive(Error, Debug)] -pub enum CompactSerializationError { - #[error("cannot write bytes: {inner_error} in {location}")] - CannotWriteBytes { - location: &'static Location<'static>, - inner_error: String, - }, -} +#[derive(From, PartialEq)] +struct CompactPeersEncoded(Vec); -impl From for responses::error::Error { - fn from(err: CompactSerializationError) -> Self { - responses::error::Error { - failure_reason: format!("{err}"), - } - } -} +impl FromIterator> for CompactPeersEncoded { + fn from_iter>>(iter: T) -> Self { + let mut bytes: Vec = vec![]; -impl IntoResponse for Compact { - fn into_response(self) -> Response { - match self.body() { - Ok(bytes) => (StatusCode::OK, bytes).into_response(), - Err(err) => responses::error::Error::from(CompactSerializationError::CannotWriteBytes { - location: Location::caller(), - inner_error: format!("{err}"), - }) - .into_response(), + for peer in iter { + bytes + .write_all(&u32::from(peer.ip).to_be_bytes()) + .expect("it should write peer ip"); + bytes.write_all(&peer.port.to_be_bytes()).expect("it should write peer port"); } + + bytes.into() } } -impl From for Compact { - fn from(domain_announce_response: AnnounceData) -> Self { - let peers: Vec = domain_announce_response - .peers - .iter() - .map(|peer| CompactPeer::from(*peer)) - .collect(); +impl FromIterator> for CompactPeersEncoded { + fn from_iter>>(iter: T) -> Self { + let mut bytes: Vec = Vec::new(); - Self { - policy: AnnouncePolicy { - interval: domain_announce_response.interval, - interval_min: domain_announce_response.interval_min, - }, - stats: SwarmStats { - complete: domain_announce_response.swarm_stats.complete, - incomplete: domain_announce_response.swarm_stats.incomplete, - downloaded: 0, - }, - peers, + for peer in iter { + bytes + .write_all(&u128::from(peer.ip).to_be_bytes()) + .expect("it should write peer ip"); + bytes.write_all(&peer.port.to_be_bytes()).expect("it should write peer port"); } + bytes.into() } } #[cfg(test)] mod tests { - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use torrust_tracker_configuration::AnnouncePolicy; - use super::{Normal, NormalPeer}; + use crate::core::peer::fixture::PeerBuilder; + use crate::core::peer::Id; use crate::core::torrent::SwarmStats; - use crate::servers::http::v1::responses::announce::{Compact, CompactPeer}; + use crate::core::AnnounceData; + use crate::servers::http::v1::responses::announce::{Announce, Compact, Normal, Response}; // Some ascii values used in tests: // @@ -415,35 +334,32 @@ mod tests { // IP addresses and port numbers used in tests are chosen so that their bencoded representation // is also a valid string which makes asserts more readable. + fn setup_announce_data() -> AnnounceData { + let policy = AnnouncePolicy::new(111, 222); + + let peer_ipv4 = PeerBuilder::default() + .with_peer_id(&Id(*b"-qB00000000000000001")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), 0x7070)) + .build(); + + let peer_ipv6 = PeerBuilder::default() + .with_peer_id(&Id(*b"-qB00000000000000002")) + .with_peer_addr(&SocketAddr::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + 0x7070, + )) + .build(); + + let peers = vec![peer_ipv4, peer_ipv6]; + let stats = SwarmStats::new(333, 333, 444); + + AnnounceData::new(peers, stats, policy) + } + #[test] - fn normal_announce_response_can_be_bencoded() { - let response = Normal { - policy: AnnouncePolicy { - interval: 111, - interval_min: 222, - }, - stats: SwarmStats { - downloaded: 0, - complete: 333, - incomplete: 444, - }, - peers: vec![ - // IPV4 - NormalPeer { - peer_id: *b"-qB00000000000000001", - ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 - port: 0x7070, // 28784 - }, - // IPV6 - NormalPeer { - peer_id: *b"-qB00000000000000002", - ip: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - port: 0x7070, // 28784 - }, - ], - }; - - let bytes = response.body(); + fn non_compact_announce_response_can_be_bencoded() { + let response: Announce = setup_announce_data().into(); + let bytes = response.body().expect("it should encode the response"); // cspell:disable-next-line let expected_bytes = b"d8:completei333e10:incompletei444e8:intervali111e12:min intervali222e5:peersld2:ip15:105.105.105.1057:peer id20:-qB000000000000000014:porti28784eed2:ip39:6969:6969:6969:6969:6969:6969:6969:69697:peer id20:-qB000000000000000024:porti28784eeee"; @@ -456,31 +372,8 @@ mod tests { #[test] fn compact_announce_response_can_be_bencoded() { - let response = Compact { - policy: AnnouncePolicy { - interval: 111, - interval_min: 222, - }, - stats: SwarmStats { - downloaded: 0, - complete: 333, - incomplete: 444, - }, - peers: vec![ - // IPV4 - CompactPeer { - ip: IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), // 105.105.105.105 - port: 0x7070, // 28784 - }, - // IPV6 - CompactPeer { - ip: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - port: 0x7070, // 28784 - }, - ], - }; - - let bytes = response.body().unwrap(); + let response: Announce = setup_announce_data().into(); + let bytes = response.body().expect("it should encode the response"); let expected_bytes = // cspell:disable-next-line diff --git a/src/servers/http/v1/responses/mod.rs b/src/servers/http/v1/responses/mod.rs index 3c6632fed..e22879c6d 100644 --- a/src/servers/http/v1/responses/mod.rs +++ b/src/servers/http/v1/responses/mod.rs @@ -5,3 +5,15 @@ pub mod announce; pub mod error; pub mod scrape; + +pub use announce::{Announce, Compact, Normal}; + +/// Trait that defines the Announce Response Format +pub trait Response: axum::response::IntoResponse { + /// Returns the Body of the Announce Response + /// + /// # Errors + /// + /// If unable to generate the response, it will return an error. + fn body(self) -> Result, error::Error>; +} diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 547dcd35b..80dc1ca5b 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -94,6 +94,7 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; + use torrust_tracker_configuration::AnnouncePolicy; use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; @@ -113,13 +114,12 @@ mod tests { let expected_announce_data = AnnounceData { peers: vec![], - swarm_stats: SwarmStats { + stats: SwarmStats { downloaded: 0, complete: 1, incomplete: 0, }, - interval: tracker.config.announce_interval, - interval_min: tracker.config.min_announce_interval, + policy: AnnouncePolicy::default(), }; assert_eq!(announce_data, expected_announce_data); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 4e3080b37..34ebaec89 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -152,8 +152,8 @@ pub async fn handle_announce( let announce_response = AnnounceResponse { transaction_id: wrapped_announce_request.announce_request.transaction_id, announce_interval: AnnounceInterval(i64::from(tracker.config.announce_interval) as i32), - leechers: NumberOfPeers(i64::from(response.swarm_stats.incomplete) as i32), - seeders: NumberOfPeers(i64::from(response.swarm_stats.complete) as i32), + leechers: NumberOfPeers(i64::from(response.stats.incomplete) as i32), + seeders: NumberOfPeers(i64::from(response.stats.complete) as i32), peers: response .peers .iter() @@ -177,8 +177,8 @@ pub async fn handle_announce( let announce_response = AnnounceResponse { transaction_id: wrapped_announce_request.announce_request.transaction_id, announce_interval: AnnounceInterval(i64::from(tracker.config.announce_interval) as i32), - leechers: NumberOfPeers(i64::from(response.swarm_stats.incomplete) as i32), - seeders: NumberOfPeers(i64::from(response.swarm_stats.complete) as i32), + leechers: NumberOfPeers(i64::from(response.stats.incomplete) as i32), + seeders: NumberOfPeers(i64::from(response.stats.complete) as i32), peers: response .peers .iter() diff --git a/tests/common/fixtures.rs b/tests/common/fixtures.rs index 9fd328d5d..bbdebff76 100644 --- a/tests/common/fixtures.rs +++ b/tests/common/fixtures.rs @@ -1,69 +1,3 @@ -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; -use torrust_tracker::core::peer::{self, Id, Peer}; -use torrust_tracker::shared::clock::DurationSinceUnixEpoch; - -pub struct PeerBuilder { - peer: Peer, -} - -impl PeerBuilder { - #[allow(dead_code)] - pub fn default() -> PeerBuilder { - Self { - peer: default_peer_for_testing(), - } - } - - #[allow(dead_code)] - pub fn with_peer_id(mut self, peer_id: &Id) -> Self { - self.peer.peer_id = *peer_id; - self - } - - #[allow(dead_code)] - pub fn with_peer_addr(mut self, peer_addr: &SocketAddr) -> Self { - self.peer.peer_addr = *peer_addr; - self - } - - #[allow(dead_code)] - pub fn with_bytes_pending_to_download(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes(left); - self - } - - #[allow(dead_code)] - pub fn with_no_bytes_pending_to_download(mut self) -> Self { - self.peer.left = NumberOfBytes(0); - self - } - - #[allow(dead_code)] - pub fn build(self) -> Peer { - self.into() - } - - #[allow(dead_code)] - pub fn into(self) -> Peer { - self.peer - } -} - -#[allow(dead_code)] -fn default_peer_for_testing() -> Peer { - Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Started, - } -} - #[allow(dead_code)] pub fn invalid_info_hashes() -> Vec { [ diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index 45f7e604a..71738f8e5 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -1,10 +1,10 @@ use std::str::FromStr; +use torrust_tracker::core::peer::fixture::PeerBuilder; use torrust_tracker::servers::apis::v1::context::stats::resources::Stats; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; -use crate::common::fixtures::PeerBuilder; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::test_environment::running_test_environment; use crate::servers::api::v1::asserts::{assert_stats, assert_token_not_valid, assert_unauthorized}; diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index 3cac55e6a..dc91e8fc5 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -1,11 +1,11 @@ use std::str::FromStr; +use torrust_tracker::core::peer::fixture::PeerBuilder; use torrust_tracker::servers::apis::v1::context::torrent::resources::peer::Peer; use torrust_tracker::servers::apis::v1::context::torrent::resources::torrent::{self, Torrent}; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; -use crate::common::fixtures::PeerBuilder; use crate::common::http::{Query, QueryParam}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::test_environment::running_test_environment; diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 3034847db..f3d1fcef0 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -90,10 +90,11 @@ mod for_all_config_modes { use reqwest::{Response, StatusCode}; use tokio::net::TcpListener; use torrust_tracker::core::peer; + use torrust_tracker::core::peer::fixture::PeerBuilder; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; - use crate::common::fixtures::{invalid_info_hashes, PeerBuilder}; + use crate::common::fixtures::invalid_info_hashes; use crate::servers::http::asserts::{ assert_announce_response, assert_bad_announce_request_error_response, assert_cannot_parse_query_param_error_response, assert_cannot_parse_query_params_error_response, assert_compact_announce_response, assert_empty_announce_response, @@ -884,10 +885,11 @@ mod for_all_config_modes { use tokio::net::TcpListener; use torrust_tracker::core::peer; + use torrust_tracker::core::peer::fixture::PeerBuilder; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; - use crate::common::fixtures::{invalid_info_hashes, PeerBuilder}; + use crate::common::fixtures::invalid_info_hashes; use crate::servers::http::asserts::{ assert_cannot_parse_query_params_error_response, assert_missing_query_params_for_scrape_request_error_response, assert_scrape_response, @@ -1160,10 +1162,10 @@ mod configured_as_whitelisted { use std::str::FromStr; use torrust_tracker::core::peer; + use torrust_tracker::core::peer::fixture::PeerBuilder; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; - use crate::common::fixtures::PeerBuilder; use crate::servers::http::asserts::assert_scrape_response; use crate::servers::http::client::Client; use crate::servers::http::requests; @@ -1333,10 +1335,10 @@ mod configured_as_private { use torrust_tracker::core::auth::Key; use torrust_tracker::core::peer; + use torrust_tracker::core::peer::fixture::PeerBuilder; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; - use crate::common::fixtures::PeerBuilder; use crate::servers::http::asserts::{assert_authentication_error_response, assert_scrape_response}; use crate::servers::http::client::Client; use crate::servers::http::requests; From 3e2b1525e951837cf2dbe486f27ae121e8b1b262 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 16 Jan 2024 09:16:17 +0000 Subject: [PATCH 0178/1297] feat: [#604] add timeout to http_health_check binary --- src/bin/http_health_check.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/bin/http_health_check.rs b/src/bin/http_health_check.rs index d66d334df..b7c6dfa41 100644 --- a/src/bin/http_health_check.rs +++ b/src/bin/http_health_check.rs @@ -4,8 +4,11 @@ //! //! - They are harder to maintain. //! - They introduce new attack vectors. +use std::time::Duration; use std::{env, process}; +use reqwest::Client; + #[tokio::main] async fn main() { let args: Vec = env::args().collect(); @@ -19,7 +22,9 @@ async fn main() { let url = &args[1].clone(); - match reqwest::get(url).await { + let client = Client::builder().timeout(Duration::from_secs(5)).build().unwrap(); + + match client.get(url).send().await { Ok(response) => { if response.status().is_success() { println!("STATUS: {}", response.status()); From fec9716be89a0b004ab2d9c7a2dd8f27365b9a66 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 16 Jan 2024 09:50:42 +0000 Subject: [PATCH 0179/1297] feat: [#609] add timeout to UDP tracker requests --- src/servers/udp/server.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 22cdf6357..a15226bd2 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -20,6 +20,7 @@ use std::io::Cursor; use std::net::SocketAddr; use std::sync::Arc; +use std::time::Duration; use aquatic_udp_protocol::Response; use derive_more::Constructor; @@ -240,9 +241,16 @@ impl Udp { debug!(target: "UDP Tracker", "From: {}", &remote_addr); debug!(target: "UDP Tracker", "Payload: {:?}", payload); - let response = handle_packet(remote_addr, payload, &tracker).await; + let response_fut = handle_packet(remote_addr, payload, &tracker); - Udp::send_response(socket_clone, remote_addr, response).await; + match tokio::time::timeout(Duration::from_secs(5), response_fut).await { + Ok(response) => { + Udp::send_response(socket_clone, remote_addr, response).await; + } + Err(_) => { + error!("Timeout occurred while processing the UDP request."); + } + } } Err(err) => { error!("Error reading UDP datagram from socket. Error: {:?}", err); From 470e6083c507ab76fc4c6dd1a98b3cf2991ff4d3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 16 Jan 2024 12:53:31 +0000 Subject: [PATCH 0180/1297] feat: a simple HTTP tracker client command You can execute it with: ``` cargo run --bin http_tracker_client https://tracker.torrust-demo.com 9c38422213e30bff212b30c360d26f9a02136422" ``` and the output should be something like: ```json{ "complete": 1, "incomplete": 1, "interval": 300, "min interval": 300, "peers": [ { "ip": "90.XX.XX.167", "peer id": [ 45, 66, 76, 50, 52, 54, 51, 54, 51, 45, 51, 70, 41, 46, 114, 46, 68, 100, 74, 69 ], "port": 59568 } ] } ``` --- Cargo.toml | 4 +- .../config/tracker.development.sqlite3.toml | 10 +- src/bin/http_tracker_client.rs | 35 +++ src/shared/bit_torrent/mod.rs | 1 + .../bit_torrent/tracker/http/client/mod.rs | 125 ++++++++ .../tracker/http/client/requests/announce.rs | 275 ++++++++++++++++++ .../tracker/http/client/requests/mod.rs | 2 + .../tracker/http/client/requests/scrape.rs | 124 ++++++++ .../tracker/http/client/responses/announce.rs | 126 ++++++++ .../tracker/http/client/responses/error.rs | 7 + .../tracker/http/client/responses/mod.rs | 3 + .../tracker/http/client/responses/scrape.rs | 203 +++++++++++++ src/shared/bit_torrent/tracker/http/mod.rs | 26 ++ src/shared/bit_torrent/tracker/mod.rs | 1 + 14 files changed, 935 insertions(+), 7 deletions(-) create mode 100644 src/bin/http_tracker_client.rs create mode 100644 src/shared/bit_torrent/tracker/http/client/mod.rs create mode 100644 src/shared/bit_torrent/tracker/http/client/requests/announce.rs create mode 100644 src/shared/bit_torrent/tracker/http/client/requests/mod.rs create mode 100644 src/shared/bit_torrent/tracker/http/client/requests/scrape.rs create mode 100644 src/shared/bit_torrent/tracker/http/client/responses/announce.rs create mode 100644 src/shared/bit_torrent/tracker/http/client/responses/error.rs create mode 100644 src/shared/bit_torrent/tracker/http/client/responses/mod.rs create mode 100644 src/shared/bit_torrent/tracker/http/client/responses/scrape.rs create mode 100644 src/shared/bit_torrent/tracker/http/mod.rs create mode 100644 src/shared/bit_torrent/tracker/mod.rs diff --git a/Cargo.toml b/Cargo.toml index daf3c0259..671d66e98 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,8 +54,10 @@ rand = "0" reqwest = "0" serde = { version = "1", features = ["derive"] } serde_bencode = "0" +serde_bytes = "0" serde_json = "1" serde_with = "3" +serde_repr = "0" tdyne-peer-id = "1" tdyne-peer-id-registry = "0" thiserror = "1" @@ -73,8 +75,6 @@ local-ip-address = "0" mockall = "0" once_cell = "1.18.0" reqwest = { version = "0", features = ["json"] } -serde_bytes = "0" -serde_repr = "0" serde_urlencoded = "0" torrust-tracker-test-helpers = { version = "3.0.0-alpha.12-develop", path = "packages/test-helpers" } diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index 04934dd8a..e26aa6c6c 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -13,18 +13,18 @@ remove_peerless_torrents = true tracker_usage_statistics = true [[udp_trackers]] -bind_address = "0.0.0.0:6969" -enabled = false +bind_address = "0.0.0.0:0" +enabled = true [[http_trackers]] -bind_address = "0.0.0.0:7070" -enabled = false +bind_address = "0.0.0.0:0" +enabled = true ssl_cert_path = "" ssl_enabled = false ssl_key_path = "" [http_api] -bind_address = "127.0.0.1:1212" +bind_address = "127.0.0.1:0" enabled = true ssl_cert_path = "" ssl_enabled = false diff --git a/src/bin/http_tracker_client.rs b/src/bin/http_tracker_client.rs new file mode 100644 index 000000000..1f1154fa5 --- /dev/null +++ b/src/bin/http_tracker_client.rs @@ -0,0 +1,35 @@ +use std::env; +use std::str::FromStr; + +use reqwest::Url; +use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; +use torrust_tracker::shared::bit_torrent::tracker::http::client::responses::announce::Announce; +use torrust_tracker::shared::bit_torrent::tracker::http::client::Client; + +#[tokio::main] +async fn main() { + let args: Vec = env::args().collect(); + if args.len() != 3 { + eprintln!("Error: invalid number of arguments!"); + eprintln!("Usage: cargo run --bin http_tracker_client "); + eprintln!("Example: cargo run --bin http_tracker_client https://tracker.torrust-demo.com 9c38422213e30bff212b30c360d26f9a02136422"); + std::process::exit(1); + } + + let base_url = Url::parse(&args[1]).expect("arg 1 should be a valid HTTP tracker base URL"); + let info_hash = InfoHash::from_str(&args[2]).expect("arg 2 should be a valid infohash"); + + let response = Client::new(base_url) + .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) + .await; + + let body = response.bytes().await.unwrap(); + + let announce_response: Announce = serde_bencode::from_bytes(&body) + .unwrap_or_else(|_| panic!("response body should be a valid announce response, got \"{:#?}\"", &body)); + + let json = serde_json::to_string(&announce_response).expect("announce response should be a valid JSON"); + + print!("{json}"); +} diff --git a/src/shared/bit_torrent/mod.rs b/src/shared/bit_torrent/mod.rs index 872203a1f..3dcf705e4 100644 --- a/src/shared/bit_torrent/mod.rs +++ b/src/shared/bit_torrent/mod.rs @@ -69,4 +69,5 @@ //!Bencode & bdecode in your browser | pub mod common; pub mod info_hash; +pub mod tracker; pub mod udp; diff --git a/src/shared/bit_torrent/tracker/http/client/mod.rs b/src/shared/bit_torrent/tracker/http/client/mod.rs new file mode 100644 index 000000000..a75b0fec3 --- /dev/null +++ b/src/shared/bit_torrent/tracker/http/client/mod.rs @@ -0,0 +1,125 @@ +pub mod requests; +pub mod responses; + +use std::net::IpAddr; + +use requests::announce::{self, Query}; +use requests::scrape; +use reqwest::{Client as ReqwestClient, Response, Url}; + +use crate::core::auth::Key; + +/// HTTP Tracker Client +pub struct Client { + base_url: Url, + reqwest: ReqwestClient, + key: Option, +} + +/// URL components in this context: +/// +/// ```text +/// http://127.0.0.1:62304/announce/YZ....rJ?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 +/// \_____________________/\_______________/ \__________________________________________________________/ +/// | | | +/// base url path query +/// ``` +impl Client { + /// # Panics + /// + /// This method fails if the client builder fails. + #[must_use] + pub fn new(base_url: Url) -> Self { + Self { + base_url, + reqwest: reqwest::Client::builder().build().unwrap(), + key: None, + } + } + + /// Creates the new client binding it to an specific local address. + /// + /// # Panics + /// + /// This method fails if the client builder fails. + #[must_use] + pub fn bind(base_url: Url, local_address: IpAddr) -> Self { + Self { + base_url, + reqwest: reqwest::Client::builder().local_address(local_address).build().unwrap(), + key: None, + } + } + + /// # Panics + /// + /// This method fails if the client builder fails. + #[must_use] + pub fn authenticated(base_url: Url, key: Key) -> Self { + Self { + base_url, + reqwest: reqwest::Client::builder().build().unwrap(), + key: Some(key), + } + } + + pub async fn announce(&self, query: &announce::Query) -> Response { + self.get(&self.build_announce_path_and_query(query)).await + } + + pub async fn scrape(&self, query: &scrape::Query) -> Response { + self.get(&self.build_scrape_path_and_query(query)).await + } + + pub async fn announce_with_header(&self, query: &Query, key: &str, value: &str) -> Response { + self.get_with_header(&self.build_announce_path_and_query(query), key, value) + .await + } + + pub async fn health_check(&self) -> Response { + self.get(&self.build_path("health_check")).await + } + + /// # Panics + /// + /// This method fails if there was an error while sending request. + pub async fn get(&self, path: &str) -> Response { + self.reqwest.get(self.build_url(path)).send().await.unwrap() + } + + /// # Panics + /// + /// This method fails if there was an error while sending request. + pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Response { + self.reqwest + .get(self.build_url(path)) + .header(key, value) + .send() + .await + .unwrap() + } + + fn build_announce_path_and_query(&self, query: &announce::Query) -> String { + format!("{}?{query}", self.build_path("announce")) + } + + fn build_scrape_path_and_query(&self, query: &scrape::Query) -> String { + format!("{}?{query}", self.build_path("scrape")) + } + + fn build_path(&self, path: &str) -> String { + match &self.key { + Some(key) => format!("{path}/{key}"), + None => path.to_string(), + } + } + + fn build_url(&self, path: &str) -> String { + let base_url = self.base_url(); + format!("{base_url}{path}") + } + + fn base_url(&self) -> String { + self.base_url.to_string() + } +} diff --git a/src/shared/bit_torrent/tracker/http/client/requests/announce.rs b/src/shared/bit_torrent/tracker/http/client/requests/announce.rs new file mode 100644 index 000000000..6cae79888 --- /dev/null +++ b/src/shared/bit_torrent/tracker/http/client/requests/announce.rs @@ -0,0 +1,275 @@ +use std::fmt; +use std::net::{IpAddr, Ipv4Addr}; +use std::str::FromStr; + +use serde_repr::Serialize_repr; + +use crate::core::peer::Id; +use crate::shared::bit_torrent::info_hash::InfoHash; +use crate::shared::bit_torrent::tracker::http::{percent_encode_byte_array, ByteArray20}; + +pub struct Query { + pub info_hash: ByteArray20, + pub peer_addr: IpAddr, + pub downloaded: BaseTenASCII, + pub uploaded: BaseTenASCII, + pub peer_id: ByteArray20, + pub port: PortNumber, + pub left: BaseTenASCII, + pub event: Option, + pub compact: Option, +} + +impl fmt::Display for Query { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.build()) + } +} + +/// HTTP Tracker Announce Request: +/// +/// +/// +/// Some parameters in the specification are not implemented in this tracker yet. +impl Query { + /// It builds the URL query component for the announce request. + /// + /// This custom URL query params encoding is needed because `reqwest` does not allow + /// bytes arrays in query parameters. More info on this issue: + /// + /// + #[must_use] + pub fn build(&self) -> String { + self.params().to_string() + } + + #[must_use] + pub fn params(&self) -> QueryParams { + QueryParams::from(self) + } +} + +pub type BaseTenASCII = u64; +pub type PortNumber = u16; + +pub enum Event { + //Started, + //Stopped, + Completed, +} + +impl fmt::Display for Event { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + //Event::Started => write!(f, "started"), + //Event::Stopped => write!(f, "stopped"), + Event::Completed => write!(f, "completed"), + } + } +} + +#[derive(Serialize_repr, PartialEq, Debug)] +#[repr(u8)] +pub enum Compact { + Accepted = 1, + NotAccepted = 0, +} + +impl fmt::Display for Compact { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Compact::Accepted => write!(f, "1"), + Compact::NotAccepted => write!(f, "0"), + } + } +} + +pub struct QueryBuilder { + announce_query: Query, +} + +impl QueryBuilder { + /// # Panics + /// + /// Will panic if the default info-hash value is not a valid info-hash. + #[must_use] + pub fn with_default_values() -> QueryBuilder { + let default_announce_query = Query { + info_hash: InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0, // # DevSkim: ignore DS173237 + peer_addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 88)), + downloaded: 0, + uploaded: 0, + peer_id: Id(*b"-qB00000000000000001").0, + port: 17548, + left: 0, + event: Some(Event::Completed), + compact: Some(Compact::NotAccepted), + }; + Self { + announce_query: default_announce_query, + } + } + + #[must_use] + pub fn with_info_hash(mut self, info_hash: &InfoHash) -> Self { + self.announce_query.info_hash = info_hash.0; + self + } + + #[must_use] + pub fn with_peer_id(mut self, peer_id: &Id) -> Self { + self.announce_query.peer_id = peer_id.0; + self + } + + #[must_use] + pub fn with_compact(mut self, compact: Compact) -> Self { + self.announce_query.compact = Some(compact); + self + } + + #[must_use] + pub fn with_peer_addr(mut self, peer_addr: &IpAddr) -> Self { + self.announce_query.peer_addr = *peer_addr; + self + } + + #[must_use] + pub fn without_compact(mut self) -> Self { + self.announce_query.compact = None; + self + } + + #[must_use] + pub fn query(self) -> Query { + self.announce_query + } +} + +/// It contains all the GET parameters that can be used in a HTTP Announce request. +/// +/// Sample Announce URL with all the GET parameters (mandatory and optional): +/// +/// ```text +/// http://127.0.0.1:7070/announce? +/// info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 (mandatory) +/// peer_addr=192.168.1.88 +/// downloaded=0 +/// uploaded=0 +/// peer_id=%2DqB00000000000000000 (mandatory) +/// port=17548 (mandatory) +/// left=0 +/// event=completed +/// compact=0 +/// ``` +pub struct QueryParams { + pub info_hash: Option, + pub peer_addr: Option, + pub downloaded: Option, + pub uploaded: Option, + pub peer_id: Option, + pub port: Option, + pub left: Option, + pub event: Option, + pub compact: Option, +} + +impl std::fmt::Display for QueryParams { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut params = vec![]; + + if let Some(info_hash) = &self.info_hash { + params.push(("info_hash", info_hash)); + } + if let Some(peer_addr) = &self.peer_addr { + params.push(("peer_addr", peer_addr)); + } + if let Some(downloaded) = &self.downloaded { + params.push(("downloaded", downloaded)); + } + if let Some(uploaded) = &self.uploaded { + params.push(("uploaded", uploaded)); + } + if let Some(peer_id) = &self.peer_id { + params.push(("peer_id", peer_id)); + } + if let Some(port) = &self.port { + params.push(("port", port)); + } + if let Some(left) = &self.left { + params.push(("left", left)); + } + if let Some(event) = &self.event { + params.push(("event", event)); + } + if let Some(compact) = &self.compact { + params.push(("compact", compact)); + } + + let query = params + .iter() + .map(|param| format!("{}={}", param.0, param.1)) + .collect::>() + .join("&"); + + write!(f, "{query}") + } +} + +impl QueryParams { + pub fn from(announce_query: &Query) -> Self { + let event = announce_query.event.as_ref().map(std::string::ToString::to_string); + let compact = announce_query.compact.as_ref().map(std::string::ToString::to_string); + + Self { + info_hash: Some(percent_encode_byte_array(&announce_query.info_hash)), + peer_addr: Some(announce_query.peer_addr.to_string()), + downloaded: Some(announce_query.downloaded.to_string()), + uploaded: Some(announce_query.uploaded.to_string()), + peer_id: Some(percent_encode_byte_array(&announce_query.peer_id)), + port: Some(announce_query.port.to_string()), + left: Some(announce_query.left.to_string()), + event, + compact, + } + } + + pub fn remove_optional_params(&mut self) { + // todo: make them optional with the Option<...> in the AnnounceQuery struct + // if they are really optional. So that we can crete a minimal AnnounceQuery + // instead of removing the optional params afterwards. + // + // The original specification on: + // + // says only `ip` and `event` are optional. + // + // On + // says only `ip`, `numwant`, `key` and `trackerid` are optional. + // + // but the server is responding if all these params are not included. + self.peer_addr = None; + self.downloaded = None; + self.uploaded = None; + self.left = None; + self.event = None; + self.compact = None; + } + + /// # Panics + /// + /// Will panic if invalid param name is provided. + pub fn set(&mut self, param_name: &str, param_value: &str) { + match param_name { + "info_hash" => self.info_hash = Some(param_value.to_string()), + "peer_addr" => self.peer_addr = Some(param_value.to_string()), + "downloaded" => self.downloaded = Some(param_value.to_string()), + "uploaded" => self.uploaded = Some(param_value.to_string()), + "peer_id" => self.peer_id = Some(param_value.to_string()), + "port" => self.port = Some(param_value.to_string()), + "left" => self.left = Some(param_value.to_string()), + "event" => self.event = Some(param_value.to_string()), + "compact" => self.compact = Some(param_value.to_string()), + &_ => panic!("Invalid param name for announce query"), + } + } +} diff --git a/src/shared/bit_torrent/tracker/http/client/requests/mod.rs b/src/shared/bit_torrent/tracker/http/client/requests/mod.rs new file mode 100644 index 000000000..776d2dfbf --- /dev/null +++ b/src/shared/bit_torrent/tracker/http/client/requests/mod.rs @@ -0,0 +1,2 @@ +pub mod announce; +pub mod scrape; diff --git a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs new file mode 100644 index 000000000..e2563b8ed --- /dev/null +++ b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs @@ -0,0 +1,124 @@ +use std::fmt; +use std::str::FromStr; + +use crate::shared::bit_torrent::info_hash::InfoHash; +use crate::shared::bit_torrent::tracker::http::{percent_encode_byte_array, ByteArray20}; + +pub struct Query { + pub info_hash: Vec, +} + +impl fmt::Display for Query { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.build()) + } +} + +/// HTTP Tracker Scrape Request: +/// +/// +impl Query { + /// It builds the URL query component for the scrape request. + /// + /// This custom URL query params encoding is needed because `reqwest` does not allow + /// bytes arrays in query parameters. More info on this issue: + /// + /// + #[must_use] + pub fn build(&self) -> String { + self.params().to_string() + } + + #[must_use] + pub fn params(&self) -> QueryParams { + QueryParams::from(self) + } +} + +pub struct QueryBuilder { + scrape_query: Query, +} + +impl Default for QueryBuilder { + fn default() -> Self { + let default_scrape_query = Query { + info_hash: [InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0].to_vec(), // # DevSkim: ignore DS173237 + }; + Self { + scrape_query: default_scrape_query, + } + } +} + +impl QueryBuilder { + #[must_use] + pub fn with_one_info_hash(mut self, info_hash: &InfoHash) -> Self { + self.scrape_query.info_hash = [info_hash.0].to_vec(); + self + } + + #[must_use] + pub fn add_info_hash(mut self, info_hash: &InfoHash) -> Self { + self.scrape_query.info_hash.push(info_hash.0); + self + } + + #[must_use] + pub fn query(self) -> Query { + self.scrape_query + } +} + +/// It contains all the GET parameters that can be used in a HTTP Scrape request. +/// +/// The `info_hash` param is the percent encoded of the the 20-byte array info hash. +/// +/// Sample Scrape URL with all the GET parameters: +/// +/// For `IpV4`: +/// +/// ```text +/// http://127.0.0.1:7070/scrape?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 +/// ``` +/// +/// For `IpV6`: +/// +/// ```text +/// http://[::1]:7070/scrape?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 +/// ``` +/// +/// You can add as many info hashes as you want, just adding the same param again. +pub struct QueryParams { + pub info_hash: Vec, +} + +impl QueryParams { + pub fn set_one_info_hash_param(&mut self, info_hash: &str) { + self.info_hash = vec![info_hash.to_string()]; + } +} + +impl std::fmt::Display for QueryParams { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let query = self + .info_hash + .iter() + .map(|info_hash| format!("info_hash={}", &info_hash)) + .collect::>() + .join("&"); + + write!(f, "{query}") + } +} + +impl QueryParams { + pub fn from(scrape_query: &Query) -> Self { + let info_hashes = scrape_query + .info_hash + .iter() + .map(percent_encode_byte_array) + .collect::>(); + + Self { info_hash: info_hashes } + } +} diff --git a/src/shared/bit_torrent/tracker/http/client/responses/announce.rs b/src/shared/bit_torrent/tracker/http/client/responses/announce.rs new file mode 100644 index 000000000..f68c54482 --- /dev/null +++ b/src/shared/bit_torrent/tracker/http/client/responses/announce.rs @@ -0,0 +1,126 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use serde::{self, Deserialize, Serialize}; + +use crate::core::peer::Peer; + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct Announce { + pub complete: u32, + pub incomplete: u32, + pub interval: u32, + #[serde(rename = "min interval")] + pub min_interval: u32, + pub peers: Vec, // Peers using IPV4 and IPV6 +} + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct DictionaryPeer { + pub ip: String, + #[serde(rename = "peer id")] + #[serde(with = "serde_bytes")] + pub peer_id: Vec, + pub port: u16, +} + +impl From for DictionaryPeer { + fn from(peer: Peer) -> Self { + DictionaryPeer { + peer_id: peer.peer_id.to_bytes().to_vec(), + ip: peer.peer_addr.ip().to_string(), + port: peer.peer_addr.port(), + } + } +} + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct DeserializedCompact { + pub complete: u32, + pub incomplete: u32, + pub interval: u32, + #[serde(rename = "min interval")] + pub min_interval: u32, + #[serde(with = "serde_bytes")] + pub peers: Vec, +} + +impl DeserializedCompact { + /// # Errors + /// + /// Will return an error if bytes can't be deserialized. + pub fn from_bytes(bytes: &[u8]) -> Result { + serde_bencode::from_bytes::(bytes) + } +} + +#[derive(Debug, PartialEq)] +pub struct Compact { + // code-review: there could be a way to deserialize this struct directly + // by using serde instead of doing it manually. Or at least using a custom deserializer. + pub complete: u32, + pub incomplete: u32, + pub interval: u32, + pub min_interval: u32, + pub peers: CompactPeerList, +} + +#[derive(Debug, PartialEq)] +pub struct CompactPeerList { + peers: Vec, +} + +impl CompactPeerList { + #[must_use] + pub fn new(peers: Vec) -> Self { + Self { peers } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CompactPeer { + ip: Ipv4Addr, + port: u16, +} + +impl CompactPeer { + /// # Panics + /// + /// Will panic if the provided socket address is a IPv6 IP address. + /// It's not supported for compact peers. + #[must_use] + pub fn new(socket_addr: &SocketAddr) -> Self { + match socket_addr.ip() { + IpAddr::V4(ip) => Self { + ip, + port: socket_addr.port(), + }, + IpAddr::V6(_ip) => panic!("IPV6 is not supported for compact peer"), + } + } + + #[must_use] + pub fn new_from_bytes(bytes: &[u8]) -> Self { + Self { + ip: Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]), + port: u16::from_be_bytes([bytes[4], bytes[5]]), + } + } +} + +impl From for Compact { + fn from(compact_announce: DeserializedCompact) -> Self { + let mut peers = vec![]; + + for peer_bytes in compact_announce.peers.chunks_exact(6) { + peers.push(CompactPeer::new_from_bytes(peer_bytes)); + } + + Self { + complete: compact_announce.complete, + incomplete: compact_announce.incomplete, + interval: compact_announce.interval, + min_interval: compact_announce.min_interval, + peers: CompactPeerList::new(peers), + } + } +} diff --git a/src/shared/bit_torrent/tracker/http/client/responses/error.rs b/src/shared/bit_torrent/tracker/http/client/responses/error.rs new file mode 100644 index 000000000..12c53a0cf --- /dev/null +++ b/src/shared/bit_torrent/tracker/http/client/responses/error.rs @@ -0,0 +1,7 @@ +use serde::{self, Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct Error { + #[serde(rename = "failure reason")] + pub failure_reason: String, +} diff --git a/src/shared/bit_torrent/tracker/http/client/responses/mod.rs b/src/shared/bit_torrent/tracker/http/client/responses/mod.rs new file mode 100644 index 000000000..bdc689056 --- /dev/null +++ b/src/shared/bit_torrent/tracker/http/client/responses/mod.rs @@ -0,0 +1,3 @@ +pub mod announce; +pub mod error; +pub mod scrape; diff --git a/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs b/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs new file mode 100644 index 000000000..ae06841e4 --- /dev/null +++ b/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs @@ -0,0 +1,203 @@ +use std::collections::HashMap; +use std::str; + +use serde::{self, Deserialize, Serialize}; +use serde_bencode::value::Value; + +use crate::shared::bit_torrent::tracker::http::{ByteArray20, InfoHash}; + +#[derive(Debug, PartialEq, Default)] +pub struct Response { + pub files: HashMap, +} + +impl Response { + #[must_use] + pub fn with_one_file(info_hash_bytes: ByteArray20, file: File) -> Self { + let mut files: HashMap = HashMap::new(); + files.insert(info_hash_bytes, file); + Self { files } + } + + /// # Errors + /// + /// Will return an error if the deserialized bencoded response can't not be converted into a valid response. + /// + /// # Panics + /// + /// Will panic if it can't deserialize the bencoded response. + pub fn try_from_bencoded(bytes: &[u8]) -> Result { + let scrape_response: DeserializedResponse = + serde_bencode::from_bytes(bytes).expect("provided bytes should be a valid bencoded response"); + Self::try_from(scrape_response) + } +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Default)] +pub struct File { + pub complete: i64, // The number of active peers that have completed downloading + pub downloaded: i64, // The number of peers that have ever completed downloading + pub incomplete: i64, // The number of active peers that have not completed downloading +} + +impl File { + #[must_use] + pub fn zeroed() -> Self { + Self::default() + } +} + +impl TryFrom for Response { + type Error = BencodeParseError; + + fn try_from(scrape_response: DeserializedResponse) -> Result { + parse_bencoded_response(&scrape_response.files) + } +} + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +struct DeserializedResponse { + pub files: Value, +} + +#[derive(Default)] +pub struct ResponseBuilder { + response: Response, +} + +impl ResponseBuilder { + #[must_use] + pub fn add_file(mut self, info_hash_bytes: ByteArray20, file: File) -> Self { + self.response.files.insert(info_hash_bytes, file); + self + } + + #[must_use] + pub fn build(self) -> Response { + self.response + } +} + +#[derive(Debug)] +pub enum BencodeParseError { + InvalidValueExpectedDict { value: Value }, + InvalidValueExpectedInt { value: Value }, + InvalidFileField { value: Value }, + MissingFileField { field_name: String }, +} + +/// It parses a bencoded scrape response into a `Response` struct. +/// +/// For example: +/// +/// ```text +/// d5:filesd20:xxxxxxxxxxxxxxxxxxxxd8:completei11e10:downloadedi13772e10:incompletei19e +/// 20:yyyyyyyyyyyyyyyyyyyyd8:completei21e10:downloadedi206e10:incompletei20eee +/// ``` +/// +/// Response (JSON encoded for readability): +/// +/// ```text +/// { +/// 'files': { +/// 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19}, +/// 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20} +/// } +/// } +fn parse_bencoded_response(value: &Value) -> Result { + let mut files: HashMap = HashMap::new(); + + match value { + Value::Dict(dict) => { + for file_element in dict { + let info_hash_byte_vec = file_element.0; + let file_value = file_element.1; + + let file = parse_bencoded_file(file_value).unwrap(); + + files.insert(InfoHash::new(info_hash_byte_vec).bytes(), file); + } + } + _ => return Err(BencodeParseError::InvalidValueExpectedDict { value: value.clone() }), + } + + Ok(Response { files }) +} + +/// It parses a bencoded dictionary into a `File` struct. +/// +/// For example: +/// +/// +/// ```text +/// d8:completei11e10:downloadedi13772e10:incompletei19ee +/// ``` +/// +/// into: +/// +/// ```text +/// File { +/// complete: 11, +/// downloaded: 13772, +/// incomplete: 19, +/// } +/// ``` +fn parse_bencoded_file(value: &Value) -> Result { + let file = match &value { + Value::Dict(dict) => { + let mut complete = None; + let mut downloaded = None; + let mut incomplete = None; + + for file_field in dict { + let field_name = file_field.0; + + let field_value = match file_field.1 { + Value::Int(number) => Ok(*number), + _ => Err(BencodeParseError::InvalidValueExpectedInt { + value: file_field.1.clone(), + }), + }?; + + if field_name == b"complete" { + complete = Some(field_value); + } else if field_name == b"downloaded" { + downloaded = Some(field_value); + } else if field_name == b"incomplete" { + incomplete = Some(field_value); + } else { + return Err(BencodeParseError::InvalidFileField { + value: file_field.1.clone(), + }); + } + } + + if complete.is_none() { + return Err(BencodeParseError::MissingFileField { + field_name: "complete".to_string(), + }); + } + + if downloaded.is_none() { + return Err(BencodeParseError::MissingFileField { + field_name: "downloaded".to_string(), + }); + } + + if incomplete.is_none() { + return Err(BencodeParseError::MissingFileField { + field_name: "incomplete".to_string(), + }); + } + + File { + complete: complete.unwrap(), + downloaded: downloaded.unwrap(), + incomplete: incomplete.unwrap(), + } + } + _ => return Err(BencodeParseError::InvalidValueExpectedDict { value: value.clone() }), + }; + + Ok(file) +} diff --git a/src/shared/bit_torrent/tracker/http/mod.rs b/src/shared/bit_torrent/tracker/http/mod.rs new file mode 100644 index 000000000..15723c1b7 --- /dev/null +++ b/src/shared/bit_torrent/tracker/http/mod.rs @@ -0,0 +1,26 @@ +pub mod client; + +use percent_encoding::NON_ALPHANUMERIC; + +pub type ByteArray20 = [u8; 20]; + +#[must_use] +pub fn percent_encode_byte_array(bytes: &ByteArray20) -> String { + percent_encoding::percent_encode(bytes, NON_ALPHANUMERIC).to_string() +} + +pub struct InfoHash(ByteArray20); + +impl InfoHash { + #[must_use] + pub fn new(vec: &[u8]) -> Self { + let mut byte_array_20: ByteArray20 = Default::default(); + byte_array_20.clone_from_slice(vec); + Self(byte_array_20) + } + + #[must_use] + pub fn bytes(&self) -> ByteArray20 { + self.0 + } +} diff --git a/src/shared/bit_torrent/tracker/mod.rs b/src/shared/bit_torrent/tracker/mod.rs new file mode 100644 index 000000000..3883215fc --- /dev/null +++ b/src/shared/bit_torrent/tracker/mod.rs @@ -0,0 +1 @@ +pub mod http; From 129fd2f26549fec74f0bf76b4b11b2c2a3a3c9f7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 17 Jan 2024 11:08:43 +0000 Subject: [PATCH 0181/1297] refactor: move upd tracker client to follow same folder strucutre as the HTTP tracker client. --- src/servers/health_check_api/handlers.rs | 2 +- src/servers/udp/server.rs | 2 +- src/shared/bit_torrent/mod.rs | 1 - src/shared/bit_torrent/tracker/mod.rs | 1 + src/shared/bit_torrent/{ => tracker}/udp/client.rs | 2 +- src/shared/bit_torrent/{ => tracker}/udp/mod.rs | 0 tests/servers/udp/contract.rs | 10 +++++----- 7 files changed, 9 insertions(+), 9 deletions(-) rename src/shared/bit_torrent/{ => tracker}/udp/client.rs (97%) rename src/shared/bit_torrent/{ => tracker}/udp/mod.rs (100%) diff --git a/src/servers/health_check_api/handlers.rs b/src/servers/health_check_api/handlers.rs index 2f47c8607..4403676af 100644 --- a/src/servers/health_check_api/handlers.rs +++ b/src/servers/health_check_api/handlers.rs @@ -8,7 +8,7 @@ use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, UdpTrac use super::resources::Report; use super::responses; -use crate::shared::bit_torrent::udp::client::new_udp_tracker_client_connected; +use crate::shared::bit_torrent::tracker::udp::client::new_udp_tracker_client_connected; /// If port 0 is specified in the configuration the OS will automatically /// assign a free port. But we do now know in from the configuration. diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index a15226bd2..001603b08 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -34,7 +34,7 @@ use crate::bootstrap::jobs::Started; use crate::core::Tracker; use crate::servers::signals::{shutdown_signal_with_message, Halted}; use crate::servers::udp::handlers::handle_packet; -use crate::shared::bit_torrent::udp::MAX_PACKET_SIZE; +use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; /// Error that can occur when starting or stopping the UDP server. /// diff --git a/src/shared/bit_torrent/mod.rs b/src/shared/bit_torrent/mod.rs index 3dcf705e4..8074661be 100644 --- a/src/shared/bit_torrent/mod.rs +++ b/src/shared/bit_torrent/mod.rs @@ -70,4 +70,3 @@ pub mod common; pub mod info_hash; pub mod tracker; -pub mod udp; diff --git a/src/shared/bit_torrent/tracker/mod.rs b/src/shared/bit_torrent/tracker/mod.rs index 3883215fc..b08eaa622 100644 --- a/src/shared/bit_torrent/tracker/mod.rs +++ b/src/shared/bit_torrent/tracker/mod.rs @@ -1 +1,2 @@ pub mod http; +pub mod udp; diff --git a/src/shared/bit_torrent/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs similarity index 97% rename from src/shared/bit_torrent/udp/client.rs rename to src/shared/bit_torrent/tracker/udp/client.rs index d5c4c9adf..5ea982663 100644 --- a/src/shared/bit_torrent/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use aquatic_udp_protocol::{Request, Response}; use tokio::net::UdpSocket; -use crate::shared::bit_torrent::udp::{source_address, MAX_PACKET_SIZE}; +use crate::shared::bit_torrent::tracker::udp::{source_address, MAX_PACKET_SIZE}; #[allow(clippy::module_name_repetitions)] pub struct UdpClient { diff --git a/src/shared/bit_torrent/udp/mod.rs b/src/shared/bit_torrent/tracker/udp/mod.rs similarity index 100% rename from src/shared/bit_torrent/udp/mod.rs rename to src/shared/bit_torrent/tracker/udp/mod.rs diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 72124fc3f..b16a47cd3 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -6,8 +6,8 @@ use core::panic; use aquatic_udp_protocol::{ConnectRequest, ConnectionId, Response, TransactionId}; -use torrust_tracker::shared::bit_torrent::udp::client::{new_udp_client_connected, UdpTrackerClient}; -use torrust_tracker::shared::bit_torrent::udp::MAX_PACKET_SIZE; +use torrust_tracker::shared::bit_torrent::tracker::udp::client::{new_udp_client_connected, UdpTrackerClient}; +use torrust_tracker::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_error_response; @@ -51,7 +51,7 @@ async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_req mod receiving_a_connection_request { use aquatic_udp_protocol::{ConnectRequest, TransactionId}; - use torrust_tracker::shared::bit_torrent::udp::client::new_udp_tracker_client_connected; + use torrust_tracker::shared::bit_torrent::tracker::udp::client::new_udp_tracker_client_connected; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_connect_response; @@ -82,7 +82,7 @@ mod receiving_an_announce_request { AnnounceEvent, AnnounceRequest, ConnectionId, InfoHash, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, TransactionId, }; - use torrust_tracker::shared::bit_torrent::udp::client::new_udp_tracker_client_connected; + use torrust_tracker::shared::bit_torrent::tracker::udp::client::new_udp_tracker_client_connected; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_ipv4_announce_response; @@ -124,7 +124,7 @@ mod receiving_an_announce_request { mod receiving_an_scrape_request { use aquatic_udp_protocol::{ConnectionId, InfoHash, ScrapeRequest, TransactionId}; - use torrust_tracker::shared::bit_torrent::udp::client::new_udp_tracker_client_connected; + use torrust_tracker::shared::bit_torrent::tracker::udp::client::new_udp_tracker_client_connected; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_scrape_response; From 3b492570a24e87e45e22c0f0240a9ba92cb803b2 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 3 Jan 2024 15:58:40 +1100 Subject: [PATCH 0182/1297] dev: extract config from core::tracker --- packages/configuration/src/lib.rs | 18 ++---- src/bootstrap/app.rs | 12 ++-- src/bootstrap/jobs/torrent_cleanup.rs | 2 +- src/bootstrap/jobs/tracker_apis.rs | 15 +++-- src/core/mod.rs | 70 +++++++++++++++++------- src/core/services/mod.rs | 4 +- src/core/services/statistics/mod.rs | 6 +- src/core/services/torrent.rs | 22 ++++---- src/main.rs | 2 +- src/servers/apis/routes.rs | 11 ++-- src/servers/apis/server.rs | 22 ++++++-- src/servers/apis/v1/middlewares/auth.rs | 19 ++++--- src/servers/http/v1/handlers/announce.rs | 10 ++-- src/servers/http/v1/handlers/scrape.rs | 10 ++-- src/servers/http/v1/services/announce.rs | 27 +++------ src/servers/http/v1/services/scrape.rs | 42 +++----------- src/servers/udp/handlers.rs | 46 ++++++++-------- tests/servers/api/test_environment.rs | 26 ++++----- tests/servers/http/v1/contract.rs | 22 +++++--- 19 files changed, 202 insertions(+), 184 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index a8f605289..4b81aed8b 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -229,7 +229,7 @@ //! [health_check_api] //! bind_address = "127.0.0.1:1313" //!``` -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::net::IpAddr; use std::str::FromStr; use std::sync::Arc; @@ -337,6 +337,8 @@ pub struct HttpTracker { pub ssl_key_path: Option, } +pub type AccessTokens = HashMap; + /// Configuration for the HTTP API. #[serde_as] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] @@ -360,21 +362,13 @@ pub struct HttpApi { /// token and the value is the token itself. The token is used to /// authenticate the user. All tokens are valid for all endpoints and have /// the all permissions. - pub access_tokens: HashMap, + pub access_tokens: AccessTokens, } impl HttpApi { fn override_admin_token(&mut self, api_admin_token: &str) { self.access_tokens.insert("admin".to_string(), api_admin_token.to_string()); } - - /// Checks if the given token is one of the token in the configuration. - #[must_use] - pub fn contains_token(&self, token: &str) -> bool { - let tokens: HashMap = self.access_tokens.clone(); - let tokens: HashSet = tokens.into_values().collect(); - tokens.contains(token) - } } /// Configuration for the Health Check API. @@ -804,7 +798,7 @@ mod tests { fn http_api_configuration_should_check_if_it_contains_a_token() { let configuration = Configuration::default(); - assert!(configuration.http_api.contains_token("MyAccessToken")); - assert!(!configuration.http_api.contains_token("NonExistingToken")); + assert!(configuration.http_api.access_tokens.values().any(|t| t == "MyAccessToken")); + assert!(!configuration.http_api.access_tokens.values().any(|t| t == "NonExistingToken")); } } diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 4a6f79a96..09b624566 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -24,8 +24,8 @@ use crate::shared::crypto::ephemeral_instance_keys; /// It loads the configuration from the environment and builds the main domain [`Tracker`] struct. #[must_use] -pub fn setup() -> (Arc, Arc) { - let configuration = Arc::new(initialize_configuration()); +pub fn setup() -> (Configuration, Arc) { + let configuration = initialize_configuration(); let tracker = initialize_with_configuration(&configuration); (configuration, tracker) @@ -35,7 +35,7 @@ pub fn setup() -> (Arc, Arc) { /// /// The configuration may be obtained from the environment (via config file or env vars). #[must_use] -pub fn initialize_with_configuration(configuration: &Arc) -> Arc { +pub fn initialize_with_configuration(configuration: &Configuration) -> Arc { initialize_static(); initialize_logging(configuration); Arc::new(initialize_tracker(configuration)) @@ -60,13 +60,13 @@ pub fn initialize_static() { /// The tracker is the domain layer service. It's the entrypoint to make requests to the domain layer. /// It's used by other higher-level components like the UDP and HTTP trackers or the tracker API. #[must_use] -pub fn initialize_tracker(config: &Arc) -> Tracker { - tracker_factory(config.clone()) +pub fn initialize_tracker(config: &Configuration) -> Tracker { + tracker_factory(config) } /// It initializes the log level, format and channel. /// /// See [the logging setup](crate::bootstrap::logging::setup) for more info about logging. -pub fn initialize_logging(config: &Arc) { +pub fn initialize_logging(config: &Configuration) { bootstrap::logging::setup(config); } diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index d3b084d31..6647e0249 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -25,7 +25,7 @@ use crate::core; /// /// Refer to [`torrust-tracker-configuration documentation`](https://docs.rs/torrust-tracker-configuration) for more info about that option. #[must_use] -pub fn start_job(config: &Arc, tracker: &Arc) -> JoinHandle<()> { +pub fn start_job(config: &Configuration, tracker: &Arc) -> JoinHandle<()> { let weak_tracker = std::sync::Arc::downgrade(tracker); let interval = config.inactive_peer_cleanup_interval; diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index e50a83651..43cb5de8e 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -26,7 +26,7 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use log::info; use tokio::task::JoinHandle; -use torrust_tracker_configuration::HttpApi; +use torrust_tracker_configuration::{AccessTokens, HttpApi}; use super::make_rust_tls; use crate::core; @@ -64,8 +64,10 @@ pub async fn start_job(config: &HttpApi, tracker: Arc, version: V .await .map(|tls| tls.expect("it should have a valid tracker api tls configuration")); + let access_tokens = Arc::new(config.access_tokens.clone()); + match version { - Version::V1 => Some(start_v1(bind_to, tls, tracker.clone()).await), + Version::V1 => Some(start_v1(bind_to, tls, tracker.clone(), access_tokens).await), } } else { info!("Note: Not loading Http Tracker Service, Not Enabled in Configuration."); @@ -73,9 +75,14 @@ pub async fn start_job(config: &HttpApi, tracker: Arc, version: V } } -async fn start_v1(socket: SocketAddr, tls: Option, tracker: Arc) -> JoinHandle<()> { +async fn start_v1( + socket: SocketAddr, + tls: Option, + tracker: Arc, + access_tokens: Arc, +) -> JoinHandle<()> { let server = ApiServer::new(Launcher::new(socket, tls)) - .start(tracker) + .start(tracker, access_tokens) .await .expect("it should be able to start to the tracker api"); diff --git a/src/core/mod.rs b/src/core/mod.rs index fc44877c8..dac298462 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -447,6 +447,7 @@ use std::time::Duration; use derive_more::Constructor; use futures::future::join_all; +use log::debug; use tokio::sync::mpsc::error::SendError; use torrust_tracker_configuration::{AnnouncePolicy, Configuration}; use torrust_tracker_primitives::TrackerMode; @@ -472,17 +473,19 @@ pub const TORRENT_PEERS_LIMIT: usize = 74; /// Typically, the `Tracker` is used by a higher application service that handles /// the network layer. pub struct Tracker { - /// `Tracker` configuration. See [`torrust-tracker-configuration`](torrust_tracker_configuration) - pub config: Arc, + announce_policy: AnnouncePolicy, /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) /// or [`MySQL`](crate::core::databases::mysql) pub database: Arc>, mode: TrackerMode, + policy: TrackerPolicy, keys: tokio::sync::RwLock>, whitelist: tokio::sync::RwLock>, pub torrents: Arc, stats_event_sender: Option>, stats_repository: statistics::Repo, + external_ip: Option, + on_reverse_proxy: bool, } /// Structure that holds general `Tracker` torrents metrics. @@ -500,6 +503,12 @@ pub struct TorrentsMetrics { pub torrents: u64, } +#[derive(Copy, Clone, Debug, PartialEq, Default, Constructor)] +pub struct TrackerPolicy { + pub remove_peerless_torrents: bool, + pub max_peer_timeout: u32, + pub persistent_torrent_completed_stat: bool, +} /// Structure that holds the data returned by the `announce` request. #[derive(Clone, Debug, PartialEq, Constructor, Default)] pub struct AnnounceData { @@ -556,7 +565,7 @@ impl Tracker { /// /// Will return a `databases::error::Error` if unable to connect to database. The `Tracker` is responsible for the persistence. pub fn new( - config: Arc, + config: &Configuration, stats_event_sender: Option>, stats_repository: statistics::Repo, ) -> Result { @@ -565,7 +574,8 @@ impl Tracker { let mode = config.mode; Ok(Tracker { - config, + //config, + announce_policy: AnnouncePolicy::new(config.announce_interval, config.min_announce_interval), mode, keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), @@ -573,6 +583,13 @@ impl Tracker { stats_event_sender, stats_repository, database, + external_ip: config.get_ext_ip(), + policy: TrackerPolicy::new( + config.remove_peerless_torrents, + config.max_peer_timeout, + config.persistent_torrent_completed_stat, + ), + on_reverse_proxy: config.on_reverse_proxy, }) } @@ -596,6 +613,19 @@ impl Tracker { self.is_private() } + /// Returns `true` is the tracker is in whitelisted mode. + pub fn is_behind_reverse_proxy(&self) -> bool { + self.on_reverse_proxy + } + + pub fn get_announce_policy(&self) -> AnnouncePolicy { + self.announce_policy + } + + pub fn get_maybe_external_ip(&self) -> Option { + self.external_ip + } + /// It handles an announce request. /// /// # Context: Tracker @@ -617,18 +647,19 @@ impl Tracker { // we are actually handling authentication at the handlers level. So I would extract that // responsibility into another authentication service. - peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.get_ext_ip())); + debug!("Before: {peer:?}"); + peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.external_ip)); + debug!("After: {peer:?}"); - let swarm_stats = self.update_torrent_with_peer_and_get_stats(info_hash, peer).await; + // we should update the torrent and get the stats before we get the peer list. + let stats = self.update_torrent_with_peer_and_get_stats(info_hash, peer).await; let peers = self.get_torrent_peers_for_peer(info_hash, peer).await; - let policy = AnnouncePolicy::new(self.config.announce_interval, self.config.min_announce_interval); - AnnounceData { peers, - stats: swarm_stats, - policy, + stats, + policy: self.get_announce_policy(), } } @@ -727,7 +758,7 @@ impl Tracker { let (stats, stats_updated) = self.torrents.update_torrent_with_peer_and_get_stats(info_hash, peer).await; - if self.config.persistent_torrent_completed_stat && stats_updated { + if self.policy.persistent_torrent_completed_stat && stats_updated { let completed = stats.downloaded; let info_hash = *info_hash; @@ -788,17 +819,17 @@ impl Tracker { let mut torrents_lock = self.torrents.get_torrents_mut().await; // If we don't need to remove torrents we will use the faster iter - if self.config.remove_peerless_torrents { + if self.policy.remove_peerless_torrents { let mut cleaned_torrents_map: BTreeMap = BTreeMap::new(); for (info_hash, torrent_entry) in &mut *torrents_lock { - torrent_entry.remove_inactive_peers(self.config.max_peer_timeout); + torrent_entry.remove_inactive_peers(self.policy.max_peer_timeout); if torrent_entry.peers.is_empty() { continue; } - if self.config.persistent_torrent_completed_stat && torrent_entry.completed == 0 { + if self.policy.persistent_torrent_completed_stat && torrent_entry.completed == 0 { continue; } @@ -808,7 +839,7 @@ impl Tracker { *torrents_lock = cleaned_torrents_map; } else { for torrent_entry in (*torrents_lock).values_mut() { - torrent_entry.remove_inactive_peers(self.config.max_peer_timeout); + torrent_entry.remove_inactive_peers(self.policy.max_peer_timeout); } } } @@ -1061,7 +1092,6 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; - use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; @@ -1073,21 +1103,21 @@ mod tests { use crate::shared::clock::DurationSinceUnixEpoch; fn public_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_public().into()) + tracker_factory(&configuration::ephemeral_mode_public()) } fn private_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_private().into()) + tracker_factory(&configuration::ephemeral_mode_private()) } fn whitelisted_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_whitelisted().into()) + tracker_factory(&configuration::ephemeral_mode_whitelisted()) } pub fn tracker_persisting_torrents_in_database() -> Tracker { let mut configuration = configuration::ephemeral(); configuration.persistent_torrent_completed_stat = true; - tracker_factory(Arc::new(configuration)) + tracker_factory(&configuration) } fn sample_info_hash() -> InfoHash { diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index f5868fc26..76c6a36f6 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -19,12 +19,12 @@ use crate::core::Tracker; /// /// Will panic if tracker cannot be instantiated. #[must_use] -pub fn tracker_factory(config: Arc) -> Tracker { +pub fn tracker_factory(config: &Configuration) -> Tracker { // Initialize statistics let (stats_event_sender, stats_repository) = statistics::setup::factory(config.tracker_usage_statistics); // Initialize Torrust tracker - match Tracker::new(config, stats_event_sender, stats_repository) { + match Tracker::new(&Arc::new(config), stats_event_sender, stats_repository) { Ok(tracker) => tracker, Err(error) => { panic!("{}", error) diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index f74df62e5..3578c53aa 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -92,13 +92,13 @@ mod tests { use crate::core::services::statistics::{get_metrics, TrackerMetrics}; use crate::core::services::tracker_factory; - pub fn tracker_configuration() -> Arc { - Arc::new(configuration::ephemeral()) + pub fn tracker_configuration() -> Configuration { + configuration::ephemeral() } #[tokio::test] async fn the_statistics_service_should_return_the_tracker_metrics() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); + let tracker = Arc::new(tracker_factory(&tracker_configuration())); let tracker_metrics = get_metrics(tracker.clone()).await; diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index f88cf5b50..d1ab29a7f 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -168,13 +168,13 @@ mod tests { use crate::core::services::tracker_factory; use crate::shared::bit_torrent::info_hash::InfoHash; - pub fn tracker_configuration() -> Arc { - Arc::new(configuration::ephemeral()) + pub fn tracker_configuration() -> Configuration { + configuration::ephemeral() } #[tokio::test] async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); + let tracker = Arc::new(tracker_factory(&tracker_configuration())); let torrent_info = get_torrent_info( tracker.clone(), @@ -187,7 +187,7 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); + let tracker = Arc::new(tracker_factory(&tracker_configuration())); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -223,13 +223,13 @@ mod tests { use crate::core::services::tracker_factory; use crate::shared::bit_torrent::info_hash::InfoHash; - pub fn tracker_configuration() -> Arc { - Arc::new(configuration::ephemeral()) + pub fn tracker_configuration() -> Configuration { + configuration::ephemeral() } #[tokio::test] async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); + let tracker = Arc::new(tracker_factory(&tracker_configuration())); let torrents = get_torrents(tracker.clone(), &Pagination::default()).await; @@ -238,7 +238,7 @@ mod tests { #[tokio::test] async fn should_return_a_summarized_info_for_all_torrents() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); + let tracker = Arc::new(tracker_factory(&tracker_configuration())); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -262,7 +262,7 @@ mod tests { #[tokio::test] async fn should_allow_limiting_the_number_of_torrents_in_the_result() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); + let tracker = Arc::new(tracker_factory(&tracker_configuration())); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -286,7 +286,7 @@ mod tests { #[tokio::test] async fn should_allow_using_pagination_in_the_result() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); + let tracker = Arc::new(tracker_factory(&tracker_configuration())); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -319,7 +319,7 @@ mod tests { #[tokio::test] async fn should_return_torrents_ordered_by_info_hash() { - let tracker = Arc::new(tracker_factory(tracker_configuration())); + let tracker = Arc::new(tracker_factory(&tracker_configuration())); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); diff --git a/src/main.rs b/src/main.rs index 87c0fc367..5c65f8e07 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,7 @@ use torrust_tracker::{app, bootstrap}; async fn main() { let (config, tracker) = bootstrap::app::setup(); - let jobs = app::start(config.clone(), tracker.clone()).await; + let jobs = app::start(config.into(), tracker.clone()).await; // handle the signals tokio::select! { diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index fef412f91..227916335 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -9,26 +9,27 @@ use std::sync::Arc; use axum::routing::get; use axum::{middleware, Router}; +use torrust_tracker_configuration::AccessTokens; use tower_http::compression::CompressionLayer; use super::v1; use super::v1::context::health_check::handlers::health_check_handler; +use super::v1::middlewares::auth::State; use crate::core::Tracker; /// Add all API routes to the router. #[allow(clippy::needless_pass_by_value)] -pub fn router(tracker: Arc) -> Router { +pub fn router(tracker: Arc, access_tokens: Arc) -> Router { let router = Router::new(); let api_url_prefix = "/api"; let router = v1::routes::add(api_url_prefix, router, tracker.clone()); + let state = State { access_tokens }; + router - .layer(middleware::from_fn_with_state( - tracker.config.clone(), - v1::middlewares::auth::auth, - )) + .layer(middleware::from_fn_with_state(state, v1::middlewares::auth::auth)) .route(&format!("{api_url_prefix}/health_check"), get(health_check_handler)) .layer(CompressionLayer::new()) } diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index f4fdf8994..d26362f66 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -32,6 +32,7 @@ use derive_more::Constructor; use futures::future::BoxFuture; use log::{error, info}; use tokio::sync::oneshot::{Receiver, Sender}; +use torrust_tracker_configuration::AccessTokens; use super::routes::router; use crate::bootstrap::jobs::Started; @@ -91,14 +92,14 @@ impl ApiServer { /// # Panics /// /// It would panic if the bound socket address cannot be sent back to this starter. - pub async fn start(self, tracker: Arc) -> Result, Error> { + pub async fn start(self, tracker: Arc, access_tokens: Arc) -> Result, Error> { let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); let launcher = self.state.launcher; let task = tokio::spawn(async move { - launcher.start(tracker, tx_start, rx_halt).await; + launcher.start(tracker, access_tokens, tx_start, rx_halt).await; launcher }); @@ -159,8 +160,14 @@ impl Launcher { /// /// Will panic if unable to bind to the socket, or unable to get the address of the bound socket. /// Will also panic if unable to send message regarding the bound socket address. - pub fn start(&self, tracker: Arc, tx_start: Sender, rx_halt: Receiver) -> BoxFuture<'static, ()> { - let router = router(tracker); + pub fn start( + &self, + tracker: Arc, + access_tokens: Arc, + tx_start: Sender, + rx_halt: Receiver, + ) -> BoxFuture<'static, ()> { + let router = router(tracker, access_tokens); let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); @@ -227,8 +234,13 @@ mod tests { .await .map(|tls| tls.expect("tls config failed")); + let access_tokens = Arc::new(config.access_tokens.clone()); + let stopped = ApiServer::new(Launcher::new(bind_to, tls)); - let started = stopped.start(tracker).await.expect("it should start the server"); + let started = stopped + .start(tracker, access_tokens) + .await + .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); assert_eq!(stopped.state.launcher.bind_to, bind_to); diff --git a/src/servers/apis/v1/middlewares/auth.rs b/src/servers/apis/v1/middlewares/auth.rs index 7749b3b34..58219c7ca 100644 --- a/src/servers/apis/v1/middlewares/auth.rs +++ b/src/servers/apis/v1/middlewares/auth.rs @@ -23,12 +23,12 @@ //! identify the token. use std::sync::Arc; -use axum::extract::{Query, State}; +use axum::extract::{self}; use axum::http::Request; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; use serde::Deserialize; -use torrust_tracker_configuration::{Configuration, HttpApi}; +use torrust_tracker_configuration::AccessTokens; use crate::servers::apis::v1::responses::unhandled_rejection_response; @@ -38,11 +38,16 @@ pub struct QueryParams { pub token: Option, } +#[derive(Clone, Debug)] +pub struct State { + pub access_tokens: Arc, +} + /// Middleware for authentication using a "token" GET param. /// The token must be one of the tokens in the tracker [HTTP API configuration](torrust_tracker_configuration::HttpApi). pub async fn auth( - State(config): State>, - Query(params): Query, + extract::State(state): extract::State, + extract::Query(params): extract::Query, request: Request, next: Next, ) -> Response { @@ -50,7 +55,7 @@ pub async fn auth( return AuthError::Unauthorized.into_response(); }; - if !authenticate(&token, &config.http_api) { + if !authenticate(&token, &state.access_tokens) { return AuthError::TokenNotValid.into_response(); } @@ -73,8 +78,8 @@ impl IntoResponse for AuthError { } } -fn authenticate(token: &str, http_api_config: &HttpApi) -> bool { - http_api_config.contains_token(token) +fn authenticate(token: &str, tokens: &AccessTokens) -> bool { + tokens.values().any(|t| t == token) } /// `500` error response returned when the token is missing. diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index cfe422e7f..be2085613 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -104,7 +104,7 @@ async fn handle_announce( Err(error) => return Err(responses::error::Error::from(error)), } - let peer_ip = match peer_ip_resolver::invoke(tracker.config.on_reverse_proxy, client_ip_sources) { + let peer_ip = match peer_ip_resolver::invoke(tracker.is_behind_reverse_proxy(), client_ip_sources) { Ok(peer_ip) => peer_ip, Err(error) => return Err(responses::error::Error::from(error)), }; @@ -166,19 +166,19 @@ mod tests { use crate::shared::bit_torrent::info_hash::InfoHash; fn private_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_private().into()) + tracker_factory(&configuration::ephemeral_mode_private()) } fn whitelisted_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_whitelisted().into()) + tracker_factory(&configuration::ephemeral_mode_whitelisted()) } fn tracker_on_reverse_proxy() -> Tracker { - tracker_factory(configuration::ephemeral_with_reverse_proxy().into()) + tracker_factory(&configuration::ephemeral_with_reverse_proxy()) } fn tracker_not_on_reverse_proxy() -> Tracker { - tracker_factory(configuration::ephemeral_without_reverse_proxy().into()) + tracker_factory(&configuration::ephemeral_without_reverse_proxy()) } fn sample_announce_request() -> Announce { diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 298d47383..49b1aebc7 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -90,7 +90,7 @@ async fn handle_scrape( // Authorization for scrape requests is handled at the `Tracker` level // for each torrent. - let peer_ip = match peer_ip_resolver::invoke(tracker.config.on_reverse_proxy, client_ip_sources) { + let peer_ip = match peer_ip_resolver::invoke(tracker.is_behind_reverse_proxy(), client_ip_sources) { Ok(peer_ip) => peer_ip, Err(error) => return Err(responses::error::Error::from(error)), }; @@ -121,19 +121,19 @@ mod tests { use crate::shared::bit_torrent::info_hash::InfoHash; fn private_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_private().into()) + tracker_factory(&configuration::ephemeral_mode_private()) } fn whitelisted_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_whitelisted().into()) + tracker_factory(&configuration::ephemeral_mode_whitelisted()) } fn tracker_on_reverse_proxy() -> Tracker { - tracker_factory(configuration::ephemeral_with_reverse_proxy().into()) + tracker_factory(&configuration::ephemeral_with_reverse_proxy()) } fn tracker_not_on_reverse_proxy() -> Tracker { - tracker_factory(configuration::ephemeral_without_reverse_proxy().into()) + tracker_factory(&configuration::ephemeral_without_reverse_proxy()) } fn sample_scrape_request() -> Scrape { diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 80dc1ca5b..b791defd7 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -56,7 +56,7 @@ mod tests { use crate::shared::clock::DurationSinceUnixEpoch; fn public_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_public().into()) + tracker_factory(&configuration::ephemeral_mode_public()) } fn sample_info_hash() -> InfoHash { @@ -94,7 +94,6 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; - use torrust_tracker_configuration::AnnouncePolicy; use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; @@ -119,7 +118,7 @@ mod tests { complete: 1, incomplete: 0, }, - policy: AnnouncePolicy::default(), + policy: tracker.get_announce_policy(), }; assert_eq!(announce_data, expected_announce_data); @@ -135,14 +134,8 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - Tracker::new( - Arc::new(configuration::ephemeral()), - Some(stats_event_sender), - statistics::Repo::new(), - ) - .unwrap(), - ); + let tracker = + Arc::new(Tracker::new(&configuration::ephemeral(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); let mut peer = sample_peer_using_ipv4(); @@ -154,7 +147,7 @@ mod tests { configuration.external_ip = Some(IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)).to_string()); - Tracker::new(Arc::new(configuration), Some(stats_event_sender), statistics::Repo::new()).unwrap() + Tracker::new(&configuration, Some(stats_event_sender), statistics::Repo::new()).unwrap() } fn peer_with_the_ipv4_loopback_ip() -> Peer { @@ -199,14 +192,8 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - Tracker::new( - Arc::new(configuration::ephemeral()), - Some(stats_event_sender), - statistics::Repo::new(), - ) - .unwrap(), - ); + let tracker = + Arc::new(Tracker::new(&configuration::ephemeral(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); let mut peer = sample_peer_using_ipv6(); diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index c2fa104de..82ca15dc8 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -69,7 +69,7 @@ mod tests { use crate::shared::clock::DurationSinceUnixEpoch; fn public_tracker() -> Tracker { - tracker_factory(configuration::ephemeral_mode_public().into()) + tracker_factory(&configuration::ephemeral_mode_public()) } fn sample_info_hashes() -> Vec { @@ -145,14 +145,8 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - Tracker::new( - Arc::new(configuration::ephemeral()), - Some(stats_event_sender), - statistics::Repo::new(), - ) - .unwrap(), - ); + let tracker = + Arc::new(Tracker::new(&configuration::ephemeral(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); @@ -169,14 +163,8 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - Tracker::new( - Arc::new(configuration::ephemeral()), - Some(stats_event_sender), - statistics::Repo::new(), - ) - .unwrap(), - ); + let tracker = + Arc::new(Tracker::new(&configuration::ephemeral(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); @@ -228,14 +216,8 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - Tracker::new( - Arc::new(configuration::ephemeral()), - Some(stats_event_sender), - statistics::Repo::new(), - ) - .unwrap(), - ); + let tracker = + Arc::new(Tracker::new(&configuration::ephemeral(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); @@ -252,14 +234,8 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - Tracker::new( - Arc::new(configuration::ephemeral()), - Some(stats_event_sender), - statistics::Repo::new(), - ) - .unwrap(), - ); + let tracker = + Arc::new(Tracker::new(&configuration::ephemeral(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 34ebaec89..b77cd3a42 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -151,7 +151,7 @@ pub async fn handle_announce( if remote_addr.is_ipv4() { let announce_response = AnnounceResponse { transaction_id: wrapped_announce_request.announce_request.transaction_id, - announce_interval: AnnounceInterval(i64::from(tracker.config.announce_interval) as i32), + announce_interval: AnnounceInterval(i64::from(tracker.get_announce_policy().interval) as i32), leechers: NumberOfPeers(i64::from(response.stats.incomplete) as i32), seeders: NumberOfPeers(i64::from(response.stats.complete) as i32), peers: response @@ -176,7 +176,7 @@ pub async fn handle_announce( } else { let announce_response = AnnounceResponse { transaction_id: wrapped_announce_request.announce_request.transaction_id, - announce_interval: AnnounceInterval(i64::from(tracker.config.announce_interval) as i32), + announce_interval: AnnounceInterval(i64::from(tracker.get_announce_policy().interval) as i32), leechers: NumberOfPeers(i64::from(response.stats.incomplete) as i32), seeders: NumberOfPeers(i64::from(response.stats.complete) as i32), peers: response @@ -282,8 +282,8 @@ mod tests { use crate::core::{peer, Tracker}; use crate::shared::clock::{Current, Time}; - fn tracker_configuration() -> Arc { - Arc::new(default_testing_tracker_configuration()) + fn tracker_configuration() -> Configuration { + default_testing_tracker_configuration() } fn default_testing_tracker_configuration() -> Configuration { @@ -291,18 +291,18 @@ mod tests { } fn public_tracker() -> Arc { - initialized_tracker(configuration::ephemeral_mode_public().into()) + initialized_tracker(&configuration::ephemeral_mode_public()) } fn private_tracker() -> Arc { - initialized_tracker(configuration::ephemeral_mode_private().into()) + initialized_tracker(&configuration::ephemeral_mode_private()) } fn whitelisted_tracker() -> Arc { - initialized_tracker(configuration::ephemeral_mode_whitelisted().into()) + initialized_tracker(&configuration::ephemeral_mode_whitelisted()) } - fn initialized_tracker(configuration: Arc) -> Arc { + fn initialized_tracker(configuration: &Configuration) -> Arc { tracker_factory(configuration).into() } @@ -452,8 +452,9 @@ mod tests { let client_socket_address = sample_ipv4_socket_address(); - let torrent_tracker = - Arc::new(core::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); + let torrent_tracker = Arc::new( + core::Tracker::new(&tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + ); handle_connect(client_socket_address, &sample_connect_request(), &torrent_tracker) .await .unwrap(); @@ -469,8 +470,9 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let torrent_tracker = - Arc::new(core::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); + let torrent_tracker = Arc::new( + core::Tracker::new(&tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + ); handle_connect(sample_ipv6_remote_addr(), &sample_connect_request(), &torrent_tracker) .await .unwrap(); @@ -710,7 +712,7 @@ mod tests { let stats_event_sender = Box::new(stats_event_sender_mock); let tracker = Arc::new( - core::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new(&tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), ); handle_announce( @@ -756,12 +758,11 @@ mod tests { let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; - let external_ip_in_tracker_configuration = - tracker.config.external_ip.clone().unwrap().parse::().unwrap(); + let external_ip_in_tracker_configuration = tracker.get_maybe_external_ip().unwrap(); let expected_peer = TorrentPeerBuilder::default() .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(SocketAddr::new(IpAddr::V4(external_ip_in_tracker_configuration), client_port)) + .with_peer_addr(SocketAddr::new(external_ip_in_tracker_configuration, client_port)) .into(); assert_eq!(peers[0], expected_peer); @@ -938,7 +939,7 @@ mod tests { let stats_event_sender = Box::new(stats_event_sender_mock); let tracker = Arc::new( - core::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new(&tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), ); let remote_addr = sample_ipv6_remote_addr(); @@ -968,7 +969,7 @@ mod tests { let configuration = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); let (stats_event_sender, stats_repository) = Keeper::new_active_instance(); let tracker = - Arc::new(core::Tracker::new(configuration, Some(stats_event_sender), stats_repository).unwrap()); + Arc::new(core::Tracker::new(&configuration, Some(stats_event_sender), stats_repository).unwrap()); let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); @@ -994,8 +995,9 @@ mod tests { let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; - let _external_ip_in_tracker_configuration = - tracker.config.external_ip.clone().unwrap().parse::().unwrap(); + let external_ip_in_tracker_configuration = tracker.get_maybe_external_ip().unwrap(); + + assert!(external_ip_in_tracker_configuration.is_ipv6()); // There's a special type of IPv6 addresses that provide compatibility with IPv4. // The last 32 bits of these addresses represent an IPv4, and are represented like this: @@ -1246,7 +1248,7 @@ mod tests { let remote_addr = sample_ipv4_remote_addr(); let tracker = Arc::new( - core::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new(&tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), ); handle_scrape(remote_addr, &sample_scrape_request(&remote_addr), &tracker) @@ -1278,7 +1280,7 @@ mod tests { let remote_addr = sample_ipv6_remote_addr(); let tracker = Arc::new( - core::Tracker::new(tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new(&tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), ); handle_scrape(remote_addr, &sample_scrape_request(&remote_addr), &tracker) diff --git a/tests/servers/api/test_environment.rs b/tests/servers/api/test_environment.rs index 166bfd7d1..c6878c674 100644 --- a/tests/servers/api/test_environment.rs +++ b/tests/servers/api/test_environment.rs @@ -1,13 +1,12 @@ -use std::net::SocketAddr; use std::sync::Arc; -use axum_server::tls_rustls::RustlsConfig; use futures::executor::block_on; use torrust_tracker::bootstrap::jobs::make_rust_tls; use torrust_tracker::core::peer::Peer; use torrust_tracker::core::Tracker; use torrust_tracker::servers::apis::server::{ApiServer, Launcher, RunningApiServer, StoppedApiServer}; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_configuration::HttpApi; use super::connection_info::ConnectionInfo; use crate::common::app::setup_with_configuration; @@ -18,7 +17,7 @@ pub type StoppedTestEnvironment = TestEnvironment; pub type RunningTestEnvironment = TestEnvironment; pub struct TestEnvironment { - pub cfg: Arc, + pub config: Arc, pub tracker: Arc, pub state: S, } @@ -41,9 +40,10 @@ impl TestEnvironment { impl TestEnvironment { pub fn new(cfg: torrust_tracker_configuration::Configuration) -> Self { - let tracker = setup_with_configuration(&Arc::new(cfg)); + let cfg = Arc::new(cfg); + let tracker = setup_with_configuration(&cfg); - let config = tracker.config.http_api.clone(); + let config = Arc::new(cfg.http_api.clone()); let bind_to = config .bind_address @@ -53,25 +53,23 @@ impl TestEnvironment { let tls = block_on(make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path)) .map(|tls| tls.expect("tls config failed")); - Self::new_stopped(tracker, bind_to, tls) - } - - pub fn new_stopped(tracker: Arc, bind_to: SocketAddr, tls: Option) -> Self { let api_server = api_server(Launcher::new(bind_to, tls)); Self { - cfg: tracker.config.clone(), + config, tracker, state: Stopped { api_server }, } } pub async fn start(self) -> TestEnvironment { + let access_tokens = Arc::new(self.config.access_tokens.clone()); + TestEnvironment { - cfg: self.cfg, + config: self.config, tracker: self.tracker.clone(), state: Running { - api_server: self.state.api_server.start(self.tracker).await.unwrap(), + api_server: self.state.api_server.start(self.tracker, access_tokens).await.unwrap(), }, } } @@ -90,7 +88,7 @@ impl TestEnvironment { pub async fn stop(self) -> TestEnvironment { TestEnvironment { - cfg: self.cfg, + config: self.config, tracker: self.tracker, state: Stopped { api_server: self.state.api_server.stop().await.unwrap(), @@ -101,7 +99,7 @@ impl TestEnvironment { pub fn get_connection_info(&self) -> ConnectionInfo { ConnectionInfo { bind_address: self.state.api_server.state.binding.to_string(), - api_token: self.cfg.http_api.access_tokens.get("admin").cloned(), + api_token: self.config.access_tokens.get("admin").cloned(), } } } diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index f3d1fcef0..e394779ad 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -387,13 +387,15 @@ mod for_all_config_modes { ) .await; + let announce_policy = test_env.tracker.get_announce_policy(); + assert_announce_response( response, &Announce { complete: 1, // the peer for this test incomplete: 0, - interval: test_env.tracker.config.announce_interval, - min_interval: test_env.tracker.config.min_announce_interval, + interval: announce_policy.interval, + min_interval: announce_policy.interval_min, peers: vec![], }, ) @@ -426,14 +428,16 @@ mod for_all_config_modes { ) .await; + let announce_policy = test_env.tracker.get_announce_policy(); + // It should only contain the previously announced peer assert_announce_response( response, &Announce { complete: 2, incomplete: 0, - interval: test_env.tracker.config.announce_interval, - min_interval: test_env.tracker.config.min_announce_interval, + interval: announce_policy.interval, + min_interval: announce_policy.interval_min, peers: vec![DictionaryPeer::from(previously_announced_peer)], }, ) @@ -475,6 +479,8 @@ mod for_all_config_modes { ) .await; + let announce_policy = test_env.tracker.get_announce_policy(); + // The newly announced peer is not included on the response peer list, // but all the previously announced peers should be included regardless the IP version they are using. assert_announce_response( @@ -482,8 +488,8 @@ mod for_all_config_modes { &Announce { complete: 3, incomplete: 0, - interval: test_env.tracker.config.announce_interval, - min_interval: test_env.tracker.config.min_announce_interval, + interval: announce_policy.interval, + min_interval: announce_policy.interval_min, peers: vec![DictionaryPeer::from(peer_using_ipv4), DictionaryPeer::from(peer_using_ipv6)], }, ) @@ -787,7 +793,7 @@ mod for_all_config_modes { let peers = test_env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; - assert_eq!(peer_addr.ip(), test_env.tracker.config.get_ext_ip().unwrap()); + assert_eq!(peer_addr.ip(), test_env.tracker.get_maybe_external_ip().unwrap()); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); test_env.stop().await; @@ -826,7 +832,7 @@ mod for_all_config_modes { let peers = test_env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; - assert_eq!(peer_addr.ip(), test_env.tracker.config.get_ext_ip().unwrap()); + assert_eq!(peer_addr.ip(), test_env.tracker.get_maybe_external_ip().unwrap()); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); test_env.stop().await; From b310c7558f5717145f1b1aa14cf6dd7839722c45 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 5 Jan 2024 17:21:06 +1100 Subject: [PATCH 0183/1297] dev: extract config from health check --- cSpell.json | 2 + src/app.rs | 29 +++- src/bootstrap/jobs/health_check_api.rs | 9 +- src/bootstrap/jobs/http_tracker.rs | 22 ++- src/bootstrap/jobs/tracker_apis.rs | 16 +- src/bootstrap/jobs/udp_tracker.rs | 5 +- src/main.rs | 2 +- src/servers/apis/server.rs | 65 ++++++-- src/servers/health_check_api/handlers.rs | 150 ++++-------------- src/servers/health_check_api/resources.rs | 31 +++- src/servers/health_check_api/responses.rs | 10 +- src/servers/health_check_api/server.rs | 7 +- src/servers/http/server.rs | 40 ++++- src/servers/mod.rs | 1 + src/servers/registar.rs | 95 +++++++++++ src/servers/udp/server.rs | 26 ++- src/shared/bit_torrent/tracker/udp/client.rs | 26 ++- tests/servers/api/test_environment.rs | 8 +- tests/servers/health_check_api/contract.rs | 9 +- .../health_check_api/test_environment.rs | 9 +- tests/servers/http/test_environment.rs | 8 +- tests/servers/udp/test_environment.rs | 5 +- 22 files changed, 392 insertions(+), 183 deletions(-) create mode 100644 src/servers/registar.rs diff --git a/cSpell.json b/cSpell.json index 7b3ce4de9..e02c6ed87 100644 --- a/cSpell.json +++ b/cSpell.json @@ -34,6 +34,7 @@ "Cyberneering", "datagram", "datetime", + "Deque", "Dijke", "distroless", "dockerhub", @@ -91,6 +92,7 @@ "Rasterbar", "realpath", "reannounce", + "Registar", "repr", "reqwest", "rerequests", diff --git a/src/app.rs b/src/app.rs index 3608aa22e..3ec9806d3 100644 --- a/src/app.rs +++ b/src/app.rs @@ -28,6 +28,7 @@ use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; +use crate::servers::registar::Registar; use crate::{core, servers}; /// # Panics @@ -36,9 +37,11 @@ use crate::{core, servers}; /// /// - Can't retrieve tracker keys from database. /// - Can't load whitelist from database. -pub async fn start(config: Arc, tracker: Arc) -> Vec> { +pub async fn start(config: &Configuration, tracker: Arc) -> Vec> { let mut jobs: Vec> = Vec::new(); + let registar = Registar::default(); + // Load peer keys if tracker.is_private() { tracker @@ -67,31 +70,45 @@ pub async fn start(config: Arc, tracker: Arc) -> V udp_tracker_config.bind_address, config.mode ); } else { - jobs.push(udp_tracker::start_job(udp_tracker_config, tracker.clone()).await); + jobs.push(udp_tracker::start_job(udp_tracker_config, tracker.clone(), registar.give_form()).await); } } // Start the HTTP blocks for http_tracker_config in &config.http_trackers { - if let Some(job) = http_tracker::start_job(http_tracker_config, tracker.clone(), servers::http::Version::V1).await { + if let Some(job) = http_tracker::start_job( + http_tracker_config, + tracker.clone(), + registar.give_form(), + servers::http::Version::V1, + ) + .await + { jobs.push(job); }; } // Start HTTP API if config.http_api.enabled { - if let Some(job) = tracker_apis::start_job(&config.http_api, tracker.clone(), servers::apis::Version::V1).await { + if let Some(job) = tracker_apis::start_job( + &config.http_api, + tracker.clone(), + registar.give_form(), + servers::apis::Version::V1, + ) + .await + { jobs.push(job); }; } // Start runners to remove torrents without peers, every interval if config.inactive_peer_cleanup_interval > 0 { - jobs.push(torrent_cleanup::start_job(&config, &tracker)); + jobs.push(torrent_cleanup::start_job(config, &tracker)); } // Start Health Check API - jobs.push(health_check_api::start_job(config).await); + jobs.push(health_check_api::start_job(&config.health_check_api, registar.entries()).await); jobs } diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index 9fed56435..1a9815280 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -13,15 +13,15 @@ //! //! Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) //! for the API configuration options. -use std::sync::Arc; use log::info; use tokio::sync::oneshot; use tokio::task::JoinHandle; -use torrust_tracker_configuration::Configuration; +use torrust_tracker_configuration::HealthCheckApi; use super::Started; use crate::servers::health_check_api::server; +use crate::servers::registar::ServiceRegistry; /// This function starts a new Health Check API server with the provided /// configuration. @@ -33,9 +33,8 @@ use crate::servers::health_check_api::server; /// # Panics /// /// It would panic if unable to send the `ApiServerJobStarted` notice. -pub async fn start_job(config: Arc) -> JoinHandle<()> { +pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> JoinHandle<()> { let bind_addr = config - .health_check_api .bind_address .parse::() .expect("it should have a valid health check bind address"); @@ -46,7 +45,7 @@ pub async fn start_job(config: Arc) -> JoinHandle<()> { let join_handle = tokio::spawn(async move { info!(target: "Health Check API", "Starting on: http://{}", bind_addr); - let handle = server::start(bind_addr, tx_start, config.clone()); + let handle = server::start(bind_addr, tx_start, register); if let Ok(()) = handle.await { info!(target: "Health Check API", "Stopped server running on: http://{}", bind_addr); diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 69ff345db..0a0638b78 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -22,6 +22,7 @@ use super::make_rust_tls; use crate::core; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::http::Version; +use crate::servers::registar::ServiceRegistrationForm; /// It starts a new HTTP server with the provided configuration and version. /// @@ -32,7 +33,12 @@ use crate::servers::http::Version; /// /// It would panic if the `config::HttpTracker` struct would contain inappropriate values. /// -pub async fn start_job(config: &HttpTracker, tracker: Arc, version: Version) -> Option> { +pub async fn start_job( + config: &HttpTracker, + tracker: Arc, + form: ServiceRegistrationForm, + version: Version, +) -> Option> { if config.enabled { let socket = config .bind_address @@ -44,7 +50,7 @@ pub async fn start_job(config: &HttpTracker, tracker: Arc, versio .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); match version { - Version::V1 => Some(start_v1(socket, tls, tracker.clone()).await), + Version::V1 => Some(start_v1(socket, tls, tracker.clone(), form).await), } } else { info!("Note: Not loading Http Tracker Service, Not Enabled in Configuration."); @@ -52,9 +58,14 @@ pub async fn start_job(config: &HttpTracker, tracker: Arc, versio } } -async fn start_v1(socket: SocketAddr, tls: Option, tracker: Arc) -> JoinHandle<()> { +async fn start_v1( + socket: SocketAddr, + tls: Option, + tracker: Arc, + form: ServiceRegistrationForm, +) -> JoinHandle<()> { let server = HttpServer::new(Launcher::new(socket, tls)) - .start(tracker) + .start(tracker, form) .await .expect("it should be able to start to the http tracker"); @@ -80,6 +91,7 @@ mod tests { use crate::bootstrap::app::initialize_with_configuration; use crate::bootstrap::jobs::http_tracker::start_job; use crate::servers::http::Version; + use crate::servers::registar::Registar; #[tokio::test] async fn it_should_start_http_tracker() { @@ -88,7 +100,7 @@ mod tests { let tracker = initialize_with_configuration(&cfg); let version = Version::V1; - start_job(config, tracker, version) + start_job(config, tracker, Registar::default().give_form(), version) .await .expect("it should be able to join to the http tracker start-job"); } diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 43cb5de8e..ffd7c7407 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -32,6 +32,7 @@ use super::make_rust_tls; use crate::core; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::apis::Version; +use crate::servers::registar::ServiceRegistrationForm; /// This is the message that the "launcher" spawned task sends to the main /// application process to notify the API server was successfully started. @@ -53,7 +54,12 @@ pub struct ApiServerJobStarted(); /// It would panic if unable to send the `ApiServerJobStarted` notice. /// /// -pub async fn start_job(config: &HttpApi, tracker: Arc, version: Version) -> Option> { +pub async fn start_job( + config: &HttpApi, + tracker: Arc, + form: ServiceRegistrationForm, + version: Version, +) -> Option> { if config.enabled { let bind_to = config .bind_address @@ -67,7 +73,7 @@ pub async fn start_job(config: &HttpApi, tracker: Arc, version: V let access_tokens = Arc::new(config.access_tokens.clone()); match version { - Version::V1 => Some(start_v1(bind_to, tls, tracker.clone(), access_tokens).await), + Version::V1 => Some(start_v1(bind_to, tls, tracker.clone(), form, access_tokens).await), } } else { info!("Note: Not loading Http Tracker Service, Not Enabled in Configuration."); @@ -79,10 +85,11 @@ async fn start_v1( socket: SocketAddr, tls: Option, tracker: Arc, + form: ServiceRegistrationForm, access_tokens: Arc, ) -> JoinHandle<()> { let server = ApiServer::new(Launcher::new(socket, tls)) - .start(tracker, access_tokens) + .start(tracker, form, access_tokens) .await .expect("it should be able to start to the tracker api"); @@ -101,6 +108,7 @@ mod tests { use crate::bootstrap::app::initialize_with_configuration; use crate::bootstrap::jobs::tracker_apis::start_job; use crate::servers::apis::Version; + use crate::servers::registar::Registar; #[tokio::test] async fn it_should_start_http_tracker() { @@ -109,7 +117,7 @@ mod tests { let tracker = initialize_with_configuration(&cfg); let version = Version::V1; - start_job(config, tracker, version) + start_job(config, tracker, Registar::default().give_form(), version) .await .expect("it should be able to join to the tracker api start-job"); } diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 20ef0c793..275ce1381 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -13,6 +13,7 @@ use tokio::task::JoinHandle; use torrust_tracker_configuration::UdpTracker; use crate::core; +use crate::servers::registar::ServiceRegistrationForm; use crate::servers::udp::server::{Launcher, UdpServer}; /// It starts a new UDP server with the provided configuration. @@ -25,14 +26,14 @@ use crate::servers::udp::server::{Launcher, UdpServer}; /// It will panic if it is unable to start the UDP service. /// It will panic if the task did not finish successfully. #[must_use] -pub async fn start_job(config: &UdpTracker, tracker: Arc) -> JoinHandle<()> { +pub async fn start_job(config: &UdpTracker, tracker: Arc, form: ServiceRegistrationForm) -> JoinHandle<()> { let bind_to = config .bind_address .parse::() .expect("it should have a valid udp tracker bind address"); let server = UdpServer::new(Launcher::new(bind_to)) - .start(tracker) + .start(tracker, form) .await .expect("it should be able to start the udp tracker"); diff --git a/src/main.rs b/src/main.rs index 5c65f8e07..bd07f4a58 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,7 @@ use torrust_tracker::{app, bootstrap}; async fn main() { let (config, tracker) = bootstrap::app::setup(); - let jobs = app::start(config.into(), tracker.clone()).await; + let jobs = app::start(&config, tracker).await; // handle the signals tokio::select! { diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index d26362f66..8aef9744c 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -37,6 +37,7 @@ use torrust_tracker_configuration::AccessTokens; use super::routes::router; use crate::bootstrap::jobs::Started; use crate::core::Tracker; +use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{graceful_shutdown, Halted}; /// Errors that can occur when starting or stopping the API server. @@ -75,6 +76,21 @@ pub struct Running { pub task: tokio::task::JoinHandle, } +impl Running { + #[must_use] + pub fn new( + binding: SocketAddr, + halt_task: tokio::sync::oneshot::Sender, + task: tokio::task::JoinHandle, + ) -> Self { + Self { + binding, + halt_task, + task, + } + } +} + impl ApiServer { #[must_use] pub fn new(launcher: Launcher) -> Self { @@ -92,7 +108,12 @@ impl ApiServer { /// # Panics /// /// It would panic if the bound socket address cannot be sent back to this starter. - pub async fn start(self, tracker: Arc, access_tokens: Arc) -> Result, Error> { + pub async fn start( + self, + tracker: Arc, + form: ServiceRegistrationForm, + access_tokens: Arc, + ) -> Result, Error> { let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); @@ -104,13 +125,14 @@ impl ApiServer { }); let api_server = match rx_start.await { - Ok(started) => ApiServer { - state: Running { - binding: started.address, - halt_task: tx_halt, - task, - }, - }, + Ok(started) => { + form.send(ServiceRegistration::new(started.address, check_fn)) + .expect("it should be able to send service registration"); + + ApiServer { + state: Running::new(started.address, tx_halt, task), + } + } Err(err) => { let msg = format!("Unable to start API server: {err}"); error!("{}", msg); @@ -142,6 +164,27 @@ impl ApiServer { } } +/// Checks the Health by connecting to the API service endpoint. +/// +/// # Errors +/// +/// This function will return an error if unable to connect. +/// Or if there request returns an error code. +#[must_use] +pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { + let url = format!("http://{binding}/api/health_check"); + + let info = format!("checking api health check at: {url}"); + + let job = tokio::spawn(async move { + match reqwest::get(url).await { + Ok(response) => Ok(response.status().to_string()), + Err(err) => Err(err.to_string()), + } + }); + ServiceHealthCheckJob::new(*binding, info, job) +} + /// A struct responsible for starting the API server. #[derive(Constructor, Debug)] pub struct Launcher { @@ -218,6 +261,7 @@ mod tests { use crate::bootstrap::app::initialize_with_configuration; use crate::bootstrap::jobs::make_rust_tls; use crate::servers::apis::server::{ApiServer, Launcher}; + use crate::servers::registar::Registar; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { @@ -237,8 +281,11 @@ mod tests { let access_tokens = Arc::new(config.access_tokens.clone()); let stopped = ApiServer::new(Launcher::new(bind_to, tls)); + + let register = &Registar::default(); + let started = stopped - .start(tracker, access_tokens) + .start(tracker, register.give_form(), access_tokens) .await .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); diff --git a/src/servers/health_check_api/handlers.rs b/src/servers/health_check_api/handlers.rs index 4403676af..35382583e 100644 --- a/src/servers/health_check_api/handlers.rs +++ b/src/servers/health_check_api/handlers.rs @@ -1,135 +1,45 @@ -use std::net::SocketAddr; -use std::sync::Arc; +use std::collections::VecDeque; -use aquatic_udp_protocol::{ConnectRequest, Response, TransactionId}; use axum::extract::State; use axum::Json; -use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, UdpTracker}; -use super::resources::Report; +use super::resources::{CheckReport, Report}; use super::responses; -use crate::shared::bit_torrent::tracker::udp::client::new_udp_tracker_client_connected; - -/// If port 0 is specified in the configuration the OS will automatically -/// assign a free port. But we do now know in from the configuration. -/// We can only know it after starting the socket. -const UNKNOWN_PORT: u16 = 0; +use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistry}; /// Endpoint for container health check. /// -/// This endpoint only checks services when we know the port from the -/// configuration. If port 0 is specified in the configuration the health check -/// for that service is skipped. -pub(crate) async fn health_check_handler(State(config): State>) -> Json { - if let Some(err_response) = api_health_check(&config.http_api).await { - return err_response; - } - - if let Some(err_response) = http_trackers_health_check(&config.http_trackers).await { - return err_response; - } - - if let Some(err_response) = udp_trackers_health_check(&config.udp_trackers).await { - return err_response; - } - - responses::ok() -} - -async fn api_health_check(config: &HttpApi) -> Option> { - // todo: when port 0 is specified in the configuration get the port from the - // running service, after starting it as we do for testing with ephemeral - // configurations. - - if config.enabled { - let addr: SocketAddr = config.bind_address.parse().expect("invalid socket address for API"); +/// Creates a vector [`CheckReport`] from the input set of [`CheckJob`], and then builds a report from the results. +/// +pub(crate) async fn health_check_handler(State(register): State) -> Json { + #[allow(unused_assignments)] + let mut checks: VecDeque = VecDeque::new(); - if addr.port() != UNKNOWN_PORT { - let health_check_url = format!("http://{addr}/api/health_check"); + { + let mutex = register.lock(); - if !get_req_is_ok(&health_check_url).await { - return Some(responses::error(format!( - "API is not healthy. Health check endpoint: {health_check_url}" - ))); - } - } + checks = mutex.await.values().map(ServiceRegistration::spawn_check).collect(); } - None -} - -async fn http_trackers_health_check(http_trackers: &Vec) -> Option> { - // todo: when port 0 is specified in the configuration get the port from the - // running service, after starting it as we do for testing with ephemeral - // configurations. - - for http_tracker_config in http_trackers { - if !http_tracker_config.enabled { - continue; - } - - let addr: SocketAddr = http_tracker_config - .bind_address - .parse() - .expect("invalid socket address for HTTP tracker"); - - if addr.port() != UNKNOWN_PORT { - let health_check_url = format!("http://{addr}/health_check"); - - if !get_req_is_ok(&health_check_url).await { - return Some(responses::error(format!( - "HTTP Tracker is not healthy. Health check endpoint: {health_check_url}" - ))); + let jobs = checks.drain(..).map(|c| { + tokio::spawn(async move { + CheckReport { + binding: c.binding, + info: c.info.clone(), + result: c.job.await.expect("it should be able to join into the checking function"), } - } + }) + }); + + let results: Vec = futures::future::join_all(jobs) + .await + .drain(..) + .map(|r| r.expect("it should be able to connect to the job")) + .collect(); + + if results.iter().any(CheckReport::fail) { + responses::error("health check failed".to_string(), results) + } else { + responses::ok(results) } - - None -} - -async fn udp_trackers_health_check(udp_trackers: &Vec) -> Option> { - // todo: when port 0 is specified in the configuration get the port from the - // running service, after starting it as we do for testing with ephemeral - // configurations. - - for udp_tracker_config in udp_trackers { - if !udp_tracker_config.enabled { - continue; - } - - let addr: SocketAddr = udp_tracker_config - .bind_address - .parse() - .expect("invalid socket address for UDP tracker"); - - if addr.port() != UNKNOWN_PORT && !can_connect_to_udp_tracker(&addr.to_string()).await { - return Some(responses::error(format!( - "UDP Tracker is not healthy. Can't connect to: {addr}" - ))); - } - } - - None -} - -async fn get_req_is_ok(url: &str) -> bool { - match reqwest::get(url).await { - Ok(response) => response.status().is_success(), - Err(_err) => false, - } -} - -/// Tries to connect to an UDP tracker. It returns true if it succeeded. -async fn can_connect_to_udp_tracker(url: &str) -> bool { - let client = new_udp_tracker_client_connected(url).await; - - let connect_request = ConnectRequest { - transaction_id: TransactionId(123), - }; - - client.send(connect_request.into()).await; - - let response = client.receive().await; - - matches!(response, Response::Connect(_connect_response)) } diff --git a/src/servers/health_check_api/resources.rs b/src/servers/health_check_api/resources.rs index 3fadcf456..bb57cf20b 100644 --- a/src/servers/health_check_api/resources.rs +++ b/src/servers/health_check_api/resources.rs @@ -1,31 +1,54 @@ +use std::net::SocketAddr; + use serde::{Deserialize, Serialize}; -#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +#[derive(Copy, Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] pub enum Status { Ok, Error, } -#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] +pub struct CheckReport { + pub binding: SocketAddr, + pub info: String, + pub result: Result, +} + +impl CheckReport { + #[must_use] + pub fn pass(&self) -> bool { + self.result.is_ok() + } + #[must_use] + pub fn fail(&self) -> bool { + self.result.is_err() + } +} + +#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct Report { pub status: Status, pub message: String, + pub details: Vec, } impl Report { #[must_use] - pub fn ok() -> Report { + pub fn ok(details: Vec) -> Report { Self { status: Status::Ok, message: String::new(), + details, } } #[must_use] - pub fn error(message: String) -> Report { + pub fn error(message: String, details: Vec) -> Report { Self { status: Status::Error, message, + details, } } } diff --git a/src/servers/health_check_api/responses.rs b/src/servers/health_check_api/responses.rs index 043e271db..8658caeb4 100644 --- a/src/servers/health_check_api/responses.rs +++ b/src/servers/health_check_api/responses.rs @@ -1,11 +1,11 @@ use axum::Json; -use super::resources::Report; +use super::resources::{CheckReport, Report}; -pub fn ok() -> Json { - Json(Report::ok()) +pub fn ok(details: Vec) -> Json { + Json(Report::ok(details)) } -pub fn error(message: String) -> Json { - Json(Report::error(message)) +pub fn error(message: String, details: Vec) -> Json { + Json(Report::error(message, details)) } diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index fb807d09c..a7cbf4a8a 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -3,7 +3,6 @@ //! This API is intended to be used by the container infrastructure to check if //! the whole application is healthy. use std::net::SocketAddr; -use std::sync::Arc; use axum::routing::get; use axum::{Json, Router}; @@ -12,10 +11,10 @@ use futures::Future; use log::info; use serde_json::json; use tokio::sync::oneshot::Sender; -use torrust_tracker_configuration::Configuration; use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; +use crate::servers::registar::ServiceRegistry; /// Starts Health Check API server. /// @@ -25,12 +24,12 @@ use crate::servers::health_check_api::handlers::health_check_handler; pub fn start( address: SocketAddr, tx: Sender, - config: Arc, + register: ServiceRegistry, ) -> impl Future> { let app = Router::new() .route("/", get(|| async { Json(json!({})) })) .route("/health_check", get(health_check_handler)) - .with_state(config); + .with_state(register); let handle = Handle::new(); let cloned_handle = handle.clone(); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 0a4b687b5..20e57db57 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -12,6 +12,7 @@ use tokio::sync::oneshot::{Receiver, Sender}; use super::v1::routes::router; use crate::bootstrap::jobs::Started; use crate::core::Tracker; +use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{graceful_shutdown, Halted}; /// Error that can occur when starting or stopping the HTTP server. @@ -143,7 +144,7 @@ impl HttpServer { /// /// It would panic spawned HTTP server launcher cannot send the bound `SocketAddr` /// back to the main thread. - pub async fn start(self, tracker: Arc) -> Result, Error> { + pub async fn start(self, tracker: Arc, form: ServiceRegistrationForm) -> Result, Error> { let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); @@ -157,9 +158,14 @@ impl HttpServer { launcher }); + let binding = rx_start.await.expect("it should be able to start the service").address; + + form.send(ServiceRegistration::new(binding, check_fn)) + .expect("it should be able to send service registration"); + Ok(HttpServer { state: Running { - binding: rx_start.await.expect("unable to start service").address, + binding, halt_task: tx_halt, task, }, @@ -188,6 +194,28 @@ impl HttpServer { } } +/// Checks the Health by connecting to the HTTP tracker endpoint. +/// +/// # Errors +/// +/// This function will return an error if unable to connect. +/// Or if the request returns an error. +#[must_use] +pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { + let url = format!("http://{binding}/health_check"); + + let info = format!("checking http tracker health check at: {url}"); + + let job = tokio::spawn(async move { + match reqwest::get(url).await { + Ok(response) => Ok(response.status().to_string()), + Err(err) => Err(err.to_string()), + } + }); + + ServiceHealthCheckJob::new(*binding, info, job) +} + #[cfg(test)] mod tests { use std::sync::Arc; @@ -197,6 +225,7 @@ mod tests { use crate::bootstrap::app::initialize_with_configuration; use crate::bootstrap::jobs::make_rust_tls; use crate::servers::http::server::{HttpServer, Launcher}; + use crate::servers::registar::Registar; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { @@ -213,8 +242,13 @@ mod tests { .await .map(|tls| tls.expect("tls config failed")); + let register = &Registar::default(); + let stopped = HttpServer::new(Launcher::new(bind_to, tls)); - let started = stopped.start(tracker).await.expect("it should start the server"); + let started = stopped + .start(tracker, register.give_form()) + .await + .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); assert_eq!(stopped.state.launcher.bind_to, bind_to); diff --git a/src/servers/mod.rs b/src/servers/mod.rs index 077109f35..b0e222d2a 100644 --- a/src/servers/mod.rs +++ b/src/servers/mod.rs @@ -2,5 +2,6 @@ pub mod apis; pub mod health_check_api; pub mod http; +pub mod registar; pub mod signals; pub mod udp; diff --git a/src/servers/registar.rs b/src/servers/registar.rs new file mode 100644 index 000000000..0fb8d6acc --- /dev/null +++ b/src/servers/registar.rs @@ -0,0 +1,95 @@ +//! Registar. Registers Services for Health Check. + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::sync::Arc; + +use derive_more::Constructor; +use tokio::sync::Mutex; +use tokio::task::JoinHandle; + +/// A [`ServiceHeathCheckResult`] is returned by a completed health check. +pub type ServiceHeathCheckResult = Result; + +/// The [`ServiceHealthCheckJob`] has a health check job with it's metadata +/// +/// The `job` awaits a [`ServiceHeathCheckResult`]. +#[derive(Debug, Constructor)] +pub struct ServiceHealthCheckJob { + pub binding: SocketAddr, + pub info: String, + pub job: JoinHandle, +} + +/// The function specification [`FnSpawnServiceHeathCheck`]. +/// +/// A function fulfilling this specification will spawn a new [`ServiceHealthCheckJob`]. +pub type FnSpawnServiceHeathCheck = fn(&SocketAddr) -> ServiceHealthCheckJob; + +/// A [`ServiceRegistration`] is provided to the [`Registar`] for registration. +/// +/// Each registration includes a function that fulfils the [`FnSpawnServiceHeathCheck`] specification. +#[derive(Clone, Debug, Constructor)] +pub struct ServiceRegistration { + binding: SocketAddr, + check_fn: FnSpawnServiceHeathCheck, +} + +impl ServiceRegistration { + #[must_use] + pub fn spawn_check(&self) -> ServiceHealthCheckJob { + (self.check_fn)(&self.binding) + } +} + +/// A [`ServiceRegistrationForm`] will return a completed [`ServiceRegistration`] to the [`Registar`]. +pub type ServiceRegistrationForm = tokio::sync::oneshot::Sender; + +/// The [`ServiceRegistry`] contains each unique [`ServiceRegistration`] by it's [`SocketAddr`]. +pub type ServiceRegistry = Arc>>; + +/// The [`Registar`] manages the [`ServiceRegistry`]. +#[derive(Clone, Debug)] +pub struct Registar { + registry: ServiceRegistry, +} + +#[allow(clippy::derivable_impls)] +impl Default for Registar { + fn default() -> Self { + Self { + registry: ServiceRegistry::default(), + } + } +} + +impl Registar { + pub fn new(register: ServiceRegistry) -> Self { + Self { registry: register } + } + + /// Registers a Service + #[must_use] + pub fn give_form(&self) -> ServiceRegistrationForm { + let (tx, rx) = tokio::sync::oneshot::channel::(); + let register = self.clone(); + tokio::spawn(async move { + register.insert(rx).await; + }); + tx + } + + /// Inserts a listing into the registry. + async fn insert(&self, rx: tokio::sync::oneshot::Receiver) { + let listing = rx.await.expect("it should receive the listing"); + + let mut mutex = self.registry.lock().await; + mutex.insert(listing.binding, listing); + } + + /// Returns the [`ServiceRegistry`] of services + #[must_use] + pub fn entries(&self) -> ServiceRegistry { + self.registry.clone() + } +} diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 001603b08..5a1977d01 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -32,8 +32,10 @@ use tokio::task::JoinHandle; use crate::bootstrap::jobs::Started; use crate::core::Tracker; +use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{shutdown_signal_with_message, Halted}; use crate::servers::udp::handlers::handle_packet; +use crate::shared::bit_torrent::tracker::udp::client::check; use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; /// Error that can occur when starting or stopping the UDP server. @@ -117,7 +119,7 @@ impl UdpServer { /// /// It panics if unable to receive the bound socket address from service. /// - pub async fn start(self, tracker: Arc) -> Result, Error> { + pub async fn start(self, tracker: Arc, form: ServiceRegistrationForm) -> Result, Error> { let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); @@ -135,7 +137,10 @@ impl UdpServer { launcher }); - let binding = rx_start.await.expect("unable to start service").address; + let binding = rx_start.await.expect("it should be able to start the service").address; + + form.send(ServiceRegistration::new(binding, Udp::check)) + .expect("it should be able to send service registration"); let running_udp_server: UdpServer = UdpServer { state: Running { @@ -305,6 +310,15 @@ impl Udp { // doesn't matter if it reaches or not drop(socket.send_to(payload, remote_addr).await); } + + fn check(binding: &SocketAddr) -> ServiceHealthCheckJob { + let binding = *binding; + let info = format!("checking the udp tracker health check at: {binding}"); + + let job = tokio::spawn(async move { check(&binding).await }); + + ServiceHealthCheckJob::new(binding, info, job) + } } #[cfg(test)] @@ -314,6 +328,7 @@ mod tests { use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; use crate::bootstrap::app::initialize_with_configuration; + use crate::servers::registar::Registar; use crate::servers::udp::server::{Launcher, UdpServer}; #[tokio::test] @@ -327,8 +342,13 @@ mod tests { .parse::() .expect("Tracker API bind_address invalid."); + let register = &Registar::default(); + let stopped = UdpServer::new(Launcher::new(bind_to)); - let started = stopped.start(tracker).await.expect("it should start the server"); + let started = stopped + .start(tracker, register.give_form()) + .await + .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); assert_eq!(stopped.state.launcher.bind_to, bind_to); diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs index 5ea982663..f0a981c8a 100644 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -1,7 +1,8 @@ use std::io::Cursor; +use std::net::SocketAddr; use std::sync::Arc; -use aquatic_udp_protocol::{Request, Response}; +use aquatic_udp_protocol::{ConnectRequest, Request, Response, TransactionId}; use tokio::net::UdpSocket; use crate::shared::bit_torrent::tracker::udp::{source_address, MAX_PACKET_SIZE}; @@ -105,3 +106,26 @@ pub async fn new_udp_tracker_client_connected(remote_address: &str) -> UdpTracke let udp_client = new_udp_client_connected(remote_address).await; UdpTrackerClient { udp_client } } + +/// Helper Function to Check if a UDP Service is Connectable +/// +/// # Errors +/// +/// It will return an error if unable to connect to the UDP service. +pub async fn check(binding: &SocketAddr) -> Result { + let client = new_udp_tracker_client_connected(binding.to_string().as_str()).await; + + let connect_request = ConnectRequest { + transaction_id: TransactionId(123), + }; + + client.send(connect_request.into()).await; + + let response = client.receive().await; + + if matches!(response, Response::Connect(_connect_response)) { + Ok("Connected".to_string()) + } else { + Err("Did not Connect".to_string()) + } +} diff --git a/tests/servers/api/test_environment.rs b/tests/servers/api/test_environment.rs index c6878c674..080fab551 100644 --- a/tests/servers/api/test_environment.rs +++ b/tests/servers/api/test_environment.rs @@ -5,6 +5,7 @@ use torrust_tracker::bootstrap::jobs::make_rust_tls; use torrust_tracker::core::peer::Peer; use torrust_tracker::core::Tracker; use torrust_tracker::servers::apis::server::{ApiServer, Launcher, RunningApiServer, StoppedApiServer}; +use torrust_tracker::servers::registar::Registar; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker_configuration::HttpApi; @@ -69,7 +70,12 @@ impl TestEnvironment { config: self.config, tracker: self.tracker.clone(), state: Running { - api_server: self.state.api_server.start(self.tracker, access_tokens).await.unwrap(), + api_server: self + .state + .api_server + .start(self.tracker, Registar::default().give_form(), access_tokens) + .await + .unwrap(), }, } } diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index 6b816b85f..c02335d05 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -1,4 +1,5 @@ -use torrust_tracker::servers::health_check_api::resources::Report; +use torrust_tracker::servers::health_check_api::resources::{Report, Status}; +use torrust_tracker::servers::registar::Registar; use torrust_tracker_test_helpers::configuration; use crate::servers::health_check_api::client::get; @@ -8,7 +9,9 @@ use crate::servers::health_check_api::test_environment; async fn health_check_endpoint_should_return_status_ok_when_no_service_is_running() { let configuration = configuration::ephemeral_with_no_services(); - let (bound_addr, test_env) = test_environment::start(configuration.into()).await; + let registar = &Registar::default(); + + let (bound_addr, test_env) = test_environment::start(&configuration.health_check_api, registar.entries()).await; let url = format!("http://{bound_addr}/health_check"); @@ -16,7 +19,7 @@ async fn health_check_endpoint_should_return_status_ok_when_no_service_is_runnin assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); - assert_eq!(response.json::().await.unwrap(), Report::ok()); + assert_eq!(response.json::().await.unwrap().status, Status::Ok); test_env.abort(); } diff --git a/tests/servers/health_check_api/test_environment.rs b/tests/servers/health_check_api/test_environment.rs index 554e37dbf..18924e101 100644 --- a/tests/servers/health_check_api/test_environment.rs +++ b/tests/servers/health_check_api/test_environment.rs @@ -1,17 +1,16 @@ use std::net::SocketAddr; -use std::sync::Arc; use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_tracker::bootstrap::jobs::Started; use torrust_tracker::servers::health_check_api::server; -use torrust_tracker_configuration::Configuration; +use torrust_tracker::servers::registar::ServiceRegistry; +use torrust_tracker_configuration::HealthCheckApi; /// Start the test environment for the Health Check API. /// It runs the API server. -pub async fn start(config: Arc) -> (SocketAddr, JoinHandle<()>) { +pub async fn start(config: &HealthCheckApi, register: ServiceRegistry) -> (SocketAddr, JoinHandle<()>) { let bind_addr = config - .health_check_api .bind_address .parse::() .expect("Health Check API bind_address invalid."); @@ -19,7 +18,7 @@ pub async fn start(config: Arc) -> (SocketAddr, JoinHandle<()>) { let (tx, rx) = oneshot::channel::(); let join_handle = tokio::spawn(async move { - let handle = server::start(bind_addr, tx, config.clone()); + let handle = server::start(bind_addr, tx, register); if let Ok(()) = handle.await { panic!("Health Check API server on http://{bind_addr} stopped"); } diff --git a/tests/servers/http/test_environment.rs b/tests/servers/http/test_environment.rs index 73961b790..9cab40db2 100644 --- a/tests/servers/http/test_environment.rs +++ b/tests/servers/http/test_environment.rs @@ -5,6 +5,7 @@ use torrust_tracker::bootstrap::jobs::make_rust_tls; use torrust_tracker::core::peer::Peer; use torrust_tracker::core::Tracker; use torrust_tracker::servers::http::server::{HttpServer, Launcher, RunningHttpServer, StoppedHttpServer}; +use torrust_tracker::servers::registar::Registar; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use crate::common::app::setup_with_configuration; @@ -68,7 +69,12 @@ impl TestEnvironment { cfg: self.cfg, tracker: self.tracker.clone(), state: Running { - http_server: self.state.http_server.start(self.tracker).await.unwrap(), + http_server: self + .state + .http_server + .start(self.tracker, Registar::default().give_form()) + .await + .unwrap(), }, } } diff --git a/tests/servers/udp/test_environment.rs b/tests/servers/udp/test_environment.rs index bbad6d927..f272b6dd3 100644 --- a/tests/servers/udp/test_environment.rs +++ b/tests/servers/udp/test_environment.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use torrust_tracker::core::peer::Peer; use torrust_tracker::core::Tracker; +use torrust_tracker::servers::registar::Registar; use torrust_tracker::servers::udp::server::{Launcher, RunningUdpServer, StoppedUdpServer, UdpServer}; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; @@ -61,11 +62,13 @@ impl TestEnvironment { #[allow(dead_code)] pub async fn start(self) -> TestEnvironment { + let register = &Registar::default(); + TestEnvironment { cfg: self.cfg, tracker: self.tracker.clone(), state: Running { - udp_server: self.state.udp_server.start(self.tracker).await.unwrap(), + udp_server: self.state.udp_server.start(self.tracker, register.give_form()).await.unwrap(), }, } } From 3f0dcea464bb4fd7cf7424a02dcc9f9329295caf Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 7 Jan 2024 02:55:24 +1100 Subject: [PATCH 0184/1297] dev: add tests to health check --- src/bootstrap/jobs/health_check_api.rs | 5 +- src/servers/health_check_api/handlers.rs | 5 + src/servers/health_check_api/resources.rs | 10 + src/servers/health_check_api/responses.rs | 4 + src/servers/health_check_api/server.rs | 28 +- src/shared/bit_torrent/tracker/udp/client.rs | 26 +- tests/common/app.rs | 8 - tests/common/mod.rs | 1 - tests/servers/api/environment.rs | 94 ++++ tests/servers/api/mod.rs | 5 +- tests/servers/api/test_environment.rs | 126 ----- .../servers/api/v1/contract/authentication.rs | 38 +- .../servers/api/v1/contract/configuration.rs | 6 +- .../api/v1/contract/context/auth_key.rs | 124 ++-- .../api/v1/contract/context/health_check.rs | 8 +- .../servers/api/v1/contract/context/stats.rs | 33 +- .../api/v1/contract/context/torrent.rs | 98 ++-- .../api/v1/contract/context/whitelist.rs | 124 ++-- tests/servers/health_check_api/contract.rs | 308 +++++++++- tests/servers/health_check_api/environment.rs | 91 +++ tests/servers/health_check_api/mod.rs | 4 +- .../health_check_api/test_environment.rs | 33 -- tests/servers/http/environment.rs | 81 +++ tests/servers/http/mod.rs | 5 +- tests/servers/http/test_environment.rs | 133 ----- tests/servers/http/v1/contract.rs | 529 +++++++++--------- tests/servers/udp/contract.rs | 24 +- tests/servers/udp/environment.rs | 78 +++ tests/servers/udp/mod.rs | 6 +- tests/servers/udp/test_environment.rs | 110 ---- 30 files changed, 1182 insertions(+), 963 deletions(-) delete mode 100644 tests/common/app.rs create mode 100644 tests/servers/api/environment.rs delete mode 100644 tests/servers/api/test_environment.rs create mode 100644 tests/servers/health_check_api/environment.rs delete mode 100644 tests/servers/health_check_api/test_environment.rs create mode 100644 tests/servers/http/environment.rs delete mode 100644 tests/servers/http/test_environment.rs create mode 100644 tests/servers/udp/environment.rs delete mode 100644 tests/servers/udp/test_environment.rs diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index 1a9815280..7eeafe97b 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -22,6 +22,7 @@ use torrust_tracker_configuration::HealthCheckApi; use super::Started; use crate::servers::health_check_api::server; use crate::servers::registar::ServiceRegistry; +use crate::servers::signals::Halted; /// This function starts a new Health Check API server with the provided /// configuration. @@ -40,12 +41,14 @@ pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> Jo .expect("it should have a valid health check bind address"); let (tx_start, rx_start) = oneshot::channel::(); + let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); + drop(tx_halt); // Run the API server let join_handle = tokio::spawn(async move { info!(target: "Health Check API", "Starting on: http://{}", bind_addr); - let handle = server::start(bind_addr, tx_start, register); + let handle = server::start(bind_addr, tx_start, rx_halt, register); if let Ok(()) = handle.await { info!(target: "Health Check API", "Stopped server running on: http://{}", bind_addr); diff --git a/src/servers/health_check_api/handlers.rs b/src/servers/health_check_api/handlers.rs index 35382583e..944e84a1d 100644 --- a/src/servers/health_check_api/handlers.rs +++ b/src/servers/health_check_api/handlers.rs @@ -21,6 +21,11 @@ pub(crate) async fn health_check_handler(State(register): State checks = mutex.await.values().map(ServiceRegistration::spawn_check).collect(); } + // if we do not have any checks, lets return a `none` result. + if checks.is_empty() { + return responses::none(); + } + let jobs = checks.drain(..).map(|c| { tokio::spawn(async move { CheckReport { diff --git a/src/servers/health_check_api/resources.rs b/src/servers/health_check_api/resources.rs index bb57cf20b..3302fb966 100644 --- a/src/servers/health_check_api/resources.rs +++ b/src/servers/health_check_api/resources.rs @@ -6,6 +6,7 @@ use serde::{Deserialize, Serialize}; pub enum Status { Ok, Error, + None, } #[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -34,6 +35,15 @@ pub struct Report { } impl Report { + #[must_use] + pub fn none() -> Report { + Self { + status: Status::None, + message: String::new(), + details: Vec::default(), + } + } + #[must_use] pub fn ok(details: Vec) -> Report { Self { diff --git a/src/servers/health_check_api/responses.rs b/src/servers/health_check_api/responses.rs index 8658caeb4..3796d8be4 100644 --- a/src/servers/health_check_api/responses.rs +++ b/src/servers/health_check_api/responses.rs @@ -9,3 +9,7 @@ pub fn ok(details: Vec) -> Json { pub fn error(message: String, details: Vec) -> Json { Json(Report::error(message, details)) } + +pub fn none() -> Json { + Json(Report::none()) +} diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index a7cbf4a8a..ecc6fe427 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -8,13 +8,13 @@ use axum::routing::get; use axum::{Json, Router}; use axum_server::Handle; use futures::Future; -use log::info; use serde_json::json; -use tokio::sync::oneshot::Sender; +use tokio::sync::oneshot::{Receiver, Sender}; use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; use crate::servers::registar::ServiceRegistry; +use crate::servers::signals::{graceful_shutdown, Halted}; /// Starts Health Check API server. /// @@ -22,30 +22,30 @@ use crate::servers::registar::ServiceRegistry; /// /// Will panic if binding to the socket address fails. pub fn start( - address: SocketAddr, + bind_to: SocketAddr, tx: Sender, + rx_halt: Receiver, register: ServiceRegistry, ) -> impl Future> { - let app = Router::new() + let router = Router::new() .route("/", get(|| async { Json(json!({})) })) .route("/health_check", get(health_check_handler)) .with_state(register); - let handle = Handle::new(); - let cloned_handle = handle.clone(); - - let socket = std::net::TcpListener::bind(address).expect("Could not bind tcp_listener to address."); + let socket = std::net::TcpListener::bind(bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); - tokio::task::spawn(async move { - tokio::signal::ctrl_c().await.expect("Failed to listen to shutdown signal."); - info!("Stopping Torrust Health Check API server o http://{} ...", address); - cloned_handle.shutdown(); - }); + let handle = Handle::new(); + + tokio::task::spawn(graceful_shutdown( + handle.clone(), + rx_halt, + format!("shutting down http server on socket address: {address}"), + )); let running = axum_server::from_tcp(socket) .handle(handle) - .serve(app.into_make_service_with_connect_info::()); + .serve(router.into_make_service_with_connect_info::()); tx.send(Started { address }) .expect("the Health Check API server should not be dropped"); diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs index f0a981c8a..00f0b8acf 100644 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -1,9 +1,11 @@ use std::io::Cursor; use std::net::SocketAddr; use std::sync::Arc; +use std::time::Duration; use aquatic_udp_protocol::{ConnectRequest, Request, Response, TransactionId}; use tokio::net::UdpSocket; +use tokio::time; use crate::shared::bit_torrent::tracker::udp::{source_address, MAX_PACKET_SIZE}; @@ -112,6 +114,8 @@ pub async fn new_udp_tracker_client_connected(remote_address: &str) -> UdpTracke /// # Errors /// /// It will return an error if unable to connect to the UDP service. +/// +/// # Panics pub async fn check(binding: &SocketAddr) -> Result { let client = new_udp_tracker_client_connected(binding.to_string().as_str()).await; @@ -121,11 +125,23 @@ pub async fn check(binding: &SocketAddr) -> Result { client.send(connect_request.into()).await; - let response = client.receive().await; + let process = move |response| { + if matches!(response, Response::Connect(_connect_response)) { + Ok("Connected".to_string()) + } else { + Err("Did not Connect".to_string()) + } + }; + + let sleep = time::sleep(Duration::from_millis(2000)); + tokio::pin!(sleep); - if matches!(response, Response::Connect(_connect_response)) { - Ok("Connected".to_string()) - } else { - Err("Did not Connect".to_string()) + tokio::select! { + () = &mut sleep => { + Err("Timed Out".to_string()) + } + response = client.receive() => { + process(response) + } } } diff --git a/tests/common/app.rs b/tests/common/app.rs deleted file mode 100644 index 1b735bc86..000000000 --- a/tests/common/app.rs +++ /dev/null @@ -1,8 +0,0 @@ -use std::sync::Arc; - -use torrust_tracker::bootstrap; -use torrust_tracker::core::Tracker; - -pub fn setup_with_configuration(configuration: &Arc) -> Arc { - bootstrap::app::initialize_with_configuration(configuration) -} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 51a8a5b03..b57996292 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,4 +1,3 @@ -pub mod app; pub mod fixtures; pub mod http; pub mod udp; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs new file mode 100644 index 000000000..186b7ea3b --- /dev/null +++ b/tests/servers/api/environment.rs @@ -0,0 +1,94 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use futures::executor::block_on; +use torrust_tracker::bootstrap::app::initialize_with_configuration; +use torrust_tracker::bootstrap::jobs::make_rust_tls; +use torrust_tracker::core::peer::Peer; +use torrust_tracker::core::Tracker; +use torrust_tracker::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; +use torrust_tracker::servers::registar::Registar; +use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_configuration::{Configuration, HttpApi}; + +use super::connection_info::ConnectionInfo; + +pub struct Environment { + pub config: Arc, + pub tracker: Arc, + pub registar: Registar, + pub server: ApiServer, +} + +impl Environment { + /// Add a torrent to the tracker + pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &Peer) { + self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; + } +} + +impl Environment { + pub fn new(configuration: &Arc) -> Self { + let tracker = initialize_with_configuration(configuration); + + let config = Arc::new(configuration.http_api.clone()); + + let bind_to = config + .bind_address + .parse::() + .expect("Tracker API bind_address invalid."); + + let tls = block_on(make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path)) + .map(|tls| tls.expect("tls config failed")); + + let server = ApiServer::new(Launcher::new(bind_to, tls)); + + Self { + config, + tracker, + registar: Registar::default(), + server, + } + } + + pub async fn start(self) -> Environment { + let access_tokens = Arc::new(self.config.access_tokens.clone()); + + Environment { + config: self.config, + tracker: self.tracker.clone(), + registar: self.registar.clone(), + server: self + .server + .start(self.tracker, self.registar.give_form(), access_tokens) + .await + .unwrap(), + } + } +} + +impl Environment { + pub async fn new(configuration: &Arc) -> Self { + Environment::::new(configuration).start().await + } + + pub async fn stop(self) -> Environment { + Environment { + config: self.config, + tracker: self.tracker, + registar: Registar::default(), + server: self.server.stop().await.unwrap(), + } + } + + pub fn get_connection_info(&self) -> ConnectionInfo { + ConnectionInfo { + bind_address: self.server.state.binding.to_string(), + api_token: self.config.access_tokens.get("admin").cloned(), + } + } + + pub fn bind_address(&self) -> SocketAddr { + self.server.state.binding + } +} diff --git a/tests/servers/api/mod.rs b/tests/servers/api/mod.rs index 155ac0de1..9c30e316a 100644 --- a/tests/servers/api/mod.rs +++ b/tests/servers/api/mod.rs @@ -1,11 +1,14 @@ use std::sync::Arc; use torrust_tracker::core::Tracker; +use torrust_tracker::servers::apis::server; pub mod connection_info; -pub mod test_environment; +pub mod environment; pub mod v1; +pub type Started = environment::Environment; + /// It forces a database error by dropping all tables. /// That makes any query fail. /// code-review: alternatively we could inject a database mock in the future. diff --git a/tests/servers/api/test_environment.rs b/tests/servers/api/test_environment.rs deleted file mode 100644 index 080fab551..000000000 --- a/tests/servers/api/test_environment.rs +++ /dev/null @@ -1,126 +0,0 @@ -use std::sync::Arc; - -use futures::executor::block_on; -use torrust_tracker::bootstrap::jobs::make_rust_tls; -use torrust_tracker::core::peer::Peer; -use torrust_tracker::core::Tracker; -use torrust_tracker::servers::apis::server::{ApiServer, Launcher, RunningApiServer, StoppedApiServer}; -use torrust_tracker::servers::registar::Registar; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker_configuration::HttpApi; - -use super::connection_info::ConnectionInfo; -use crate::common::app::setup_with_configuration; - -#[allow(clippy::module_name_repetitions, dead_code)] -pub type StoppedTestEnvironment = TestEnvironment; -#[allow(clippy::module_name_repetitions)] -pub type RunningTestEnvironment = TestEnvironment; - -pub struct TestEnvironment { - pub config: Arc, - pub tracker: Arc, - pub state: S, -} - -#[allow(dead_code)] -pub struct Stopped { - api_server: StoppedApiServer, -} - -pub struct Running { - api_server: RunningApiServer, -} - -impl TestEnvironment { - /// Add a torrent to the tracker - pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &Peer) { - self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; - } -} - -impl TestEnvironment { - pub fn new(cfg: torrust_tracker_configuration::Configuration) -> Self { - let cfg = Arc::new(cfg); - let tracker = setup_with_configuration(&cfg); - - let config = Arc::new(cfg.http_api.clone()); - - let bind_to = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); - - let tls = block_on(make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path)) - .map(|tls| tls.expect("tls config failed")); - - let api_server = api_server(Launcher::new(bind_to, tls)); - - Self { - config, - tracker, - state: Stopped { api_server }, - } - } - - pub async fn start(self) -> TestEnvironment { - let access_tokens = Arc::new(self.config.access_tokens.clone()); - - TestEnvironment { - config: self.config, - tracker: self.tracker.clone(), - state: Running { - api_server: self - .state - .api_server - .start(self.tracker, Registar::default().give_form(), access_tokens) - .await - .unwrap(), - }, - } - } - - // pub fn config_mut(&mut self) -> &mut torrust_tracker_configuration::HttpApi { - // &mut self.cfg.http_api - // } -} - -impl TestEnvironment { - pub async fn new_running(cfg: torrust_tracker_configuration::Configuration) -> Self { - let test_env = StoppedTestEnvironment::new(cfg); - - test_env.start().await - } - - pub async fn stop(self) -> TestEnvironment { - TestEnvironment { - config: self.config, - tracker: self.tracker, - state: Stopped { - api_server: self.state.api_server.stop().await.unwrap(), - }, - } - } - - pub fn get_connection_info(&self) -> ConnectionInfo { - ConnectionInfo { - bind_address: self.state.api_server.state.binding.to_string(), - api_token: self.config.access_tokens.get("admin").cloned(), - } - } -} - -#[allow(clippy::module_name_repetitions)] -#[allow(dead_code)] -pub fn stopped_test_environment(cfg: torrust_tracker_configuration::Configuration) -> StoppedTestEnvironment { - TestEnvironment::new(cfg) -} - -#[allow(clippy::module_name_repetitions)] -pub async fn running_test_environment(cfg: torrust_tracker_configuration::Configuration) -> RunningTestEnvironment { - TestEnvironment::new_running(cfg).await -} - -pub fn api_server(launcher: Launcher) -> StoppedApiServer { - ApiServer::new(launcher) -} diff --git a/tests/servers/api/v1/contract/authentication.rs b/tests/servers/api/v1/contract/authentication.rs index fb8de1810..49981dd02 100644 --- a/tests/servers/api/v1/contract/authentication.rs +++ b/tests/servers/api/v1/contract/authentication.rs @@ -1,83 +1,83 @@ use torrust_tracker_test_helpers::configuration; use crate::common::http::{Query, QueryParam}; -use crate::servers::api::test_environment::running_test_environment; use crate::servers::api::v1::asserts::{assert_token_not_valid, assert_unauthorized}; use crate::servers::api::v1::client::Client; +use crate::servers::api::Started; #[tokio::test] async fn should_authenticate_requests_by_using_a_token_query_param() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let token = test_env.get_connection_info().api_token.unwrap(); + let token = env.get_connection_info().api_token.unwrap(); - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .get_request_with_query("stats", Query::params([QueryParam::new("token", &token)].to_vec())) .await; assert_eq!(response.status(), 200); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_authenticate_requests_when_the_token_is_missing() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .get_request_with_query("stats", Query::default()) .await; assert_unauthorized(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_authenticate_requests_when_the_token_is_empty() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .get_request_with_query("stats", Query::params([QueryParam::new("token", "")].to_vec())) .await; assert_token_not_valid(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_authenticate_requests_when_the_token_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .get_request_with_query("stats", Query::params([QueryParam::new("token", "INVALID TOKEN")].to_vec())) .await; assert_token_not_valid(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_allow_the_token_query_param_to_be_at_any_position_in_the_url_query() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let token = test_env.get_connection_info().api_token.unwrap(); + let token = env.get_connection_info().api_token.unwrap(); // At the beginning of the query component - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .get_request(&format!("torrents?token={token}&limit=1")) .await; assert_eq!(response.status(), 200); // At the end of the query component - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .get_request(&format!("torrents?limit=1&token={token}")) .await; assert_eq!(response.status(), 200); - test_env.stop().await; + env.stop().await; } diff --git a/tests/servers/api/v1/contract/configuration.rs b/tests/servers/api/v1/contract/configuration.rs index a551a8b36..4220f62d2 100644 --- a/tests/servers/api/v1/contract/configuration.rs +++ b/tests/servers/api/v1/contract/configuration.rs @@ -5,7 +5,7 @@ // use torrust_tracker_test_helpers::configuration; // use crate::common::app::setup_with_configuration; -// use crate::servers::api::test_environment::stopped_test_environment; +// use crate::servers::api::environment::stopped_environment; #[tokio::test] #[ignore] @@ -27,7 +27,7 @@ async fn should_fail_with_ssl_enabled_and_bad_ssl_config() { // None // }; - // let test_env = new_stopped(tracker, bind_to, tls); + // let env = new_stopped(tracker, bind_to, tls); - // test_env.start().await; + // env.start().await; } diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 4c59b4e95..f9630bafe 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -4,62 +4,57 @@ use torrust_tracker::core::auth::Key; use torrust_tracker_test_helpers::configuration; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; -use crate::servers::api::force_database_error; -use crate::servers::api::test_environment::running_test_environment; use crate::servers::api::v1::asserts::{ assert_auth_key_utf8, assert_failed_to_delete_key, assert_failed_to_generate_key, assert_failed_to_reload_keys, assert_invalid_auth_key_param, assert_invalid_key_duration_param, assert_ok, assert_token_not_valid, assert_unauthorized, }; use crate::servers::api::v1::client::Client; +use crate::servers::api::{force_database_error, Started}; #[tokio::test] async fn should_allow_generating_a_new_auth_key() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - let response = Client::new(test_env.get_connection_info()) - .generate_auth_key(seconds_valid) - .await; + let response = Client::new(env.get_connection_info()).generate_auth_key(seconds_valid).await; let auth_key_resource = assert_auth_key_utf8(response).await; // Verify the key with the tracker - assert!(test_env + assert!(env .tracker .verify_auth_key(&auth_key_resource.key.parse::().unwrap()) .await .is_ok()); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .generate_auth_key(seconds_valid) - .await; + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + .generate_auth_key(seconds_valid) + .await; assert_token_not_valid(response).await; - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) .generate_auth_key(seconds_valid) .await; assert_unauthorized(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_key_durations = [ // "", it returns 404 @@ -68,55 +63,53 @@ async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid( ]; for invalid_key_duration in invalid_key_durations { - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .post(&format!("key/{invalid_key_duration}")) .await; assert_invalid_key_duration_param(response, invalid_key_duration).await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_auth_key_cannot_be_generated() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - force_database_error(&test_env.tracker); + force_database_error(&env.tracker); let seconds_valid = 60; - let response = Client::new(test_env.get_connection_info()) - .generate_auth_key(seconds_valid) - .await; + let response = Client::new(env.get_connection_info()).generate_auth_key(seconds_valid).await; assert_failed_to_generate_key(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_allow_deleting_an_auth_key() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - let auth_key = test_env + let auth_key = env .tracker .generate_auth_key(Duration::from_secs(seconds_valid)) .await .unwrap(); - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .delete_auth_key(&auth_key.key.to_string()) .await; assert_ok(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_auth_keys = [ // "", it returns a 404 @@ -129,137 +122,128 @@ async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { ]; for invalid_auth_key in &invalid_auth_keys { - let response = Client::new(test_env.get_connection_info()) - .delete_auth_key(invalid_auth_key) - .await; + let response = Client::new(env.get_connection_info()).delete_auth_key(invalid_auth_key).await; assert_invalid_auth_key_param(response, invalid_auth_key).await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_auth_key_cannot_be_deleted() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - let auth_key = test_env + let auth_key = env .tracker .generate_auth_key(Duration::from_secs(seconds_valid)) .await .unwrap(); - force_database_error(&test_env.tracker); + force_database_error(&env.tracker); - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .delete_auth_key(&auth_key.key.to_string()) .await; assert_failed_to_delete_key(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; // Generate new auth key - let auth_key = test_env + let auth_key = env .tracker .generate_auth_key(Duration::from_secs(seconds_valid)) .await .unwrap(); - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .delete_auth_key(&auth_key.key.to_string()) - .await; + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + .delete_auth_key(&auth_key.key.to_string()) + .await; assert_token_not_valid(response).await; // Generate new auth key - let auth_key = test_env + let auth_key = env .tracker .generate_auth_key(Duration::from_secs(seconds_valid)) .await .unwrap(); - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) .delete_auth_key(&auth_key.key.to_string()) .await; assert_unauthorized(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_allow_reloading_keys() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - test_env - .tracker + env.tracker .generate_auth_key(Duration::from_secs(seconds_valid)) .await .unwrap(); - let response = Client::new(test_env.get_connection_info()).reload_keys().await; + let response = Client::new(env.get_connection_info()).reload_keys().await; assert_ok(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_keys_cannot_be_reloaded() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - test_env - .tracker + env.tracker .generate_auth_key(Duration::from_secs(seconds_valid)) .await .unwrap(); - force_database_error(&test_env.tracker); + force_database_error(&env.tracker); - let response = Client::new(test_env.get_connection_info()).reload_keys().await; + let response = Client::new(env.get_connection_info()).reload_keys().await; assert_failed_to_reload_keys(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_allow_reloading_keys_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - test_env - .tracker + env.tracker .generate_auth_key(Duration::from_secs(seconds_valid)) .await .unwrap(); - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .reload_keys() - .await; + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + .reload_keys() + .await; assert_token_not_valid(response).await; - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) .reload_keys() .await; assert_unauthorized(response).await; - test_env.stop().await; + env.stop().await; } diff --git a/tests/servers/api/v1/contract/context/health_check.rs b/tests/servers/api/v1/contract/context/health_check.rs index 108ae237a..d8dc3c030 100644 --- a/tests/servers/api/v1/contract/context/health_check.rs +++ b/tests/servers/api/v1/contract/context/health_check.rs @@ -1,14 +1,14 @@ use torrust_tracker::servers::apis::v1::context::health_check::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; -use crate::servers::api::test_environment::running_test_environment; use crate::servers::api::v1::client::get; +use crate::servers::api::Started; #[tokio::test] async fn health_check_endpoint_should_return_status_ok_if_api_is_running() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let url = format!("http://{}/api/health_check", test_env.get_connection_info().bind_address); + let url = format!("http://{}/api/health_check", env.get_connection_info().bind_address); let response = get(&url, None).await; @@ -16,5 +16,5 @@ async fn health_check_endpoint_should_return_status_ok_if_api_is_running() { assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); assert_eq!(response.json::().await.unwrap(), Report { status: Status::Ok }); - test_env.stop().await; + env.stop().await; } diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index 71738f8e5..54263f8b8 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -6,22 +6,21 @@ use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; -use crate::servers::api::test_environment::running_test_environment; use crate::servers::api::v1::asserts::{assert_stats, assert_token_not_valid, assert_unauthorized}; use crate::servers::api::v1::client::Client; +use crate::servers::api::Started; #[tokio::test] async fn should_allow_getting_tracker_statistics() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - test_env - .add_torrent_peer( - &InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), - &PeerBuilder::default().into(), - ) - .await; + env.add_torrent_peer( + &InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), + &PeerBuilder::default().into(), + ) + .await; - let response = Client::new(test_env.get_connection_info()).get_tracker_statistics().await; + let response = Client::new(env.get_connection_info()).get_tracker_statistics().await; assert_stats( response, @@ -46,26 +45,24 @@ async fn should_allow_getting_tracker_statistics() { ) .await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_allow_getting_tracker_statistics_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .get_tracker_statistics() - .await; + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + .get_tracker_statistics() + .await; assert_token_not_valid(response).await; - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) .get_tracker_statistics() .await; assert_unauthorized(response).await; - test_env.stop().await; + env.stop().await; } diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index dc91e8fc5..63b97b402 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -8,7 +8,6 @@ use torrust_tracker_test_helpers::configuration; use crate::common::http::{Query, QueryParam}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; -use crate::servers::api::test_environment::running_test_environment; use crate::servers::api::v1::asserts::{ assert_bad_request, assert_invalid_infohash_param, assert_not_found, assert_token_not_valid, assert_torrent_info, assert_torrent_list, assert_torrent_not_known, assert_unauthorized, @@ -17,16 +16,17 @@ use crate::servers::api::v1::client::Client; use crate::servers::api::v1::contract::fixtures::{ invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found, }; +use crate::servers::api::Started; #[tokio::test] async fn should_allow_getting_torrents() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - test_env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()).await; - let response = Client::new(test_env.get_connection_info()).get_torrents(Query::empty()).await; + let response = Client::new(env.get_connection_info()).get_torrents(Query::empty()).await; assert_torrent_list( response, @@ -39,21 +39,21 @@ async fn should_allow_getting_torrents() { ) .await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_allow_limiting_the_torrents_in_the_result() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; // torrents are ordered alphabetically by infohashes let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); - test_env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; - test_env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .get_torrents(Query::params([QueryParam::new("limit", "1")].to_vec())) .await; @@ -68,21 +68,21 @@ async fn should_allow_limiting_the_torrents_in_the_result() { ) .await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_allow_the_torrents_result_pagination() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; // torrents are ordered alphabetically by infohashes let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); - test_env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; - test_env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .get_torrents(Query::params([QueryParam::new("offset", "1")].to_vec())) .await; @@ -97,75 +97,73 @@ async fn should_allow_the_torrents_result_pagination() { ) .await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_parsed() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_offsets = [" ", "-1", "1.1", "INVALID OFFSET"]; for invalid_offset in &invalid_offsets { - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .get_torrents(Query::params([QueryParam::new("offset", invalid_offset)].to_vec())) .await; assert_bad_request(response, "Failed to deserialize query string: invalid digit found in string").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_parsed() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_limits = [" ", "-1", "1.1", "INVALID LIMIT"]; for invalid_limit in &invalid_limits { - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .get_torrents(Query::params([QueryParam::new("limit", invalid_limit)].to_vec())) .await; assert_bad_request(response, "Failed to deserialize query string: invalid digit found in string").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_allow_getting_torrents_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .get_torrents(Query::empty()) - .await; + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + .get_torrents(Query::empty()) + .await; assert_token_not_valid(response).await; - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) .get_torrents(Query::default()) .await; assert_unauthorized(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_allow_getting_a_torrent_info() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); let peer = PeerBuilder::default().into(); - test_env.add_torrent_peer(&info_hash, &peer).await; + env.add_torrent_peer(&info_hash, &peer).await; - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .get_torrent(&info_hash.to_string()) .await; @@ -181,68 +179,62 @@ async fn should_allow_getting_a_torrent_info() { ) .await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exist() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .get_torrent(&info_hash.to_string()) .await; assert_torrent_not_known(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_getting_a_torrent_info_when_the_provided_infohash_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; for invalid_infohash in &invalid_infohashes_returning_bad_request() { - let response = Client::new(test_env.get_connection_info()) - .get_torrent(invalid_infohash) - .await; + let response = Client::new(env.get_connection_info()).get_torrent(invalid_infohash).await; assert_invalid_infohash_param(response, invalid_infohash).await; } for invalid_infohash in &invalid_infohashes_returning_not_found() { - let response = Client::new(test_env.get_connection_info()) - .get_torrent(invalid_infohash) - .await; + let response = Client::new(env.get_connection_info()).get_torrent(invalid_infohash).await; assert_not_found(response).await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - test_env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()).await; - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .get_torrent(&info_hash.to_string()) - .await; + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + .get_torrent(&info_hash.to_string()) + .await; assert_token_not_valid(response).await; - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) .get_torrent(&info_hash.to_string()) .await; assert_unauthorized(response).await; - test_env.stop().await; + env.stop().await; } diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index 60ab4c901..358a4a19e 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -4,8 +4,6 @@ use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; -use crate::servers::api::force_database_error; -use crate::servers::api::test_environment::running_test_environment; use crate::servers::api::v1::asserts::{ assert_failed_to_reload_whitelist, assert_failed_to_remove_torrent_from_whitelist, assert_failed_to_whitelist_torrent, assert_invalid_infohash_param, assert_not_found, assert_ok, assert_token_not_valid, assert_unauthorized, @@ -14,35 +12,33 @@ use crate::servers::api::v1::client::Client; use crate::servers::api::v1::contract::fixtures::{ invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found, }; +use crate::servers::api::{force_database_error, Started}; #[tokio::test] async fn should_allow_whitelisting_a_torrent() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let response = Client::new(test_env.get_connection_info()) - .whitelist_a_torrent(&info_hash) - .await; + let response = Client::new(env.get_connection_info()).whitelist_a_torrent(&info_hash).await; assert_ok(response).await; assert!( - test_env - .tracker + env.tracker .is_info_hash_whitelisted(&InfoHash::from_str(&info_hash).unwrap()) .await ); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let api_client = Client::new(test_env.get_connection_info()); + let api_client = Client::new(env.get_connection_info()); let response = api_client.whitelist_a_torrent(&info_hash).await; assert_ok(response).await; @@ -50,55 +46,51 @@ async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() let response = api_client.whitelist_a_torrent(&info_hash).await; assert_ok(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .whitelist_a_torrent(&info_hash) - .await; + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + .whitelist_a_torrent(&info_hash) + .await; assert_token_not_valid(response).await; - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) .whitelist_a_torrent(&info_hash) .await; assert_unauthorized(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_torrent_cannot_be_whitelisted() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - force_database_error(&test_env.tracker); + force_database_error(&env.tracker); - let response = Client::new(test_env.get_connection_info()) - .whitelist_a_torrent(&info_hash) - .await; + let response = Client::new(env.get_connection_info()).whitelist_a_torrent(&info_hash).await; assert_failed_to_whitelist_torrent(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; for invalid_infohash in &invalid_infohashes_returning_bad_request() { - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .whitelist_a_torrent(invalid_infohash) .await; @@ -106,55 +98,55 @@ async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invali } for invalid_infohash in &invalid_infohashes_returning_not_found() { - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .whitelist_a_torrent(invalid_infohash) .await; assert_not_found(response).await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_allow_removing_a_torrent_from_the_whitelist() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - test_env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .remove_torrent_from_whitelist(&hash) .await; assert_ok(response).await; - assert!(!test_env.tracker.is_info_hash_whitelisted(&info_hash).await); + assert!(!env.tracker.is_info_hash_whitelisted(&info_hash).await); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_fail_trying_to_remove_a_non_whitelisted_torrent_from_the_whitelist() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let non_whitelisted_torrent_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .remove_torrent_from_whitelist(&non_whitelisted_torrent_hash) .await; assert_ok(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_infohash_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; for invalid_infohash in &invalid_infohashes_returning_bad_request() { - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .remove_torrent_from_whitelist(invalid_infohash) .await; @@ -162,99 +154,97 @@ async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_inf } for invalid_infohash in &invalid_infohashes_returning_not_found() { - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .remove_torrent_from_whitelist(invalid_infohash) .await; assert_not_found(response).await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - test_env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - force_database_error(&test_env.tracker); + force_database_error(&env.tracker); - let response = Client::new(test_env.get_connection_info()) + let response = Client::new(env.get_connection_info()) .remove_torrent_from_whitelist(&hash) .await; assert_failed_to_remove_torrent_from_whitelist(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthenticated_users() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - test_env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - let response = Client::new(connection_with_invalid_token( - test_env.get_connection_info().bind_address.as_str(), - )) - .remove_torrent_from_whitelist(&hash) - .await; + env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + .remove_torrent_from_whitelist(&hash) + .await; assert_token_not_valid(response).await; - test_env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - let response = Client::new(connection_with_no_token(test_env.get_connection_info().bind_address.as_str())) + env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) .remove_torrent_from_whitelist(&hash) .await; assert_unauthorized(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_allow_reload_the_whitelist_from_the_database() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - test_env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - let response = Client::new(test_env.get_connection_info()).reload_whitelist().await; + let response = Client::new(env.get_connection_info()).reload_whitelist().await; assert_ok(response).await; /* todo: this assert fails because the whitelist has not been reloaded yet. We could add a new endpoint GET /api/whitelist/:info_hash to check if a torrent is whitelisted and use that endpoint to check if the torrent is still there after reloading. assert!( - !(test_env + !(env .tracker .is_info_hash_whitelisted(&InfoHash::from_str(&info_hash).unwrap()) .await) ); */ - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - test_env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - force_database_error(&test_env.tracker); + force_database_error(&env.tracker); - let response = Client::new(test_env.get_connection_info()).reload_whitelist().await; + let response = Client::new(env.get_connection_info()).reload_whitelist().await; assert_failed_to_reload_whitelist(response).await; - test_env.stop().await; + env.stop().await; } diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index c02335d05..7b00866d3 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -3,23 +3,311 @@ use torrust_tracker::servers::registar::Registar; use torrust_tracker_test_helpers::configuration; use crate::servers::health_check_api::client::get; -use crate::servers::health_check_api::test_environment; +use crate::servers::health_check_api::Started; #[tokio::test] -async fn health_check_endpoint_should_return_status_ok_when_no_service_is_running() { +async fn health_check_endpoint_should_return_status_ok_when_there_is_no_services_registered() { let configuration = configuration::ephemeral_with_no_services(); - let registar = &Registar::default(); + let env = Started::new(&configuration.health_check_api.into(), Registar::default()).await; - let (bound_addr, test_env) = test_environment::start(&configuration.health_check_api, registar.entries()).await; - - let url = format!("http://{bound_addr}/health_check"); - - let response = get(&url).await; + let response = get(&format!("http://{}/health_check", env.state.binding)).await; assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); - assert_eq!(response.json::().await.unwrap().status, Status::Ok); - test_env.abort(); + let report = response + .json::() + .await + .expect("it should be able to get the report as json"); + + assert_eq!(report.status, Status::None); + + env.stop().await.expect("it should stop the service"); +} + +mod api { + use std::sync::Arc; + + use torrust_tracker::servers::health_check_api::resources::{Report, Status}; + use torrust_tracker_test_helpers::configuration; + + use crate::servers::api; + use crate::servers::health_check_api::client::get; + use crate::servers::health_check_api::Started; + + #[tokio::test] + pub(crate) async fn it_should_return_good_health_for_api_service() { + let configuration = Arc::new(configuration::ephemeral()); + + let service = api::Started::new(&configuration).await; + + let registar = service.registar.clone(); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Ok); + assert_eq!(report.message, String::new()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, service.bind_address()); + + assert_eq!(details.result, Ok("200 OK".to_string())); + + assert_eq!( + details.info, + format!( + "checking api health check at: http://{}/api/health_check", + service.bind_address() + ) + ); + + env.stop().await.expect("it should stop the service"); + } + + service.stop().await; + } + + #[tokio::test] + pub(crate) async fn it_should_return_error_when_api_service_was_stopped_after_registration() { + let configuration = Arc::new(configuration::ephemeral()); + + let service = api::Started::new(&configuration).await; + + let binding = service.bind_address(); + + let registar = service.registar.clone(); + + service.server.stop().await.expect("it should stop udp server"); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Error); + assert_eq!(report.message, "health check failed".to_string()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, binding); + assert!(details.result.as_ref().is_err_and(|e| e.contains("Connection refused"))); + assert_eq!( + details.info, + format!("checking api health check at: http://{binding}/api/health_check") + ); + + env.stop().await.expect("it should stop the service"); + } + } +} + +mod http { + use std::sync::Arc; + + use torrust_tracker::servers::health_check_api::resources::{Report, Status}; + use torrust_tracker_test_helpers::configuration; + + use crate::servers::health_check_api::client::get; + use crate::servers::health_check_api::Started; + use crate::servers::http; + + #[tokio::test] + pub(crate) async fn it_should_return_good_health_for_http_service() { + let configuration = Arc::new(configuration::ephemeral()); + + let service = http::Started::new(&configuration).await; + + let registar = service.registar.clone(); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Ok); + assert_eq!(report.message, String::new()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, *service.bind_address()); + assert_eq!(details.result, Ok("200 OK".to_string())); + + assert_eq!( + details.info, + format!( + "checking http tracker health check at: http://{}/health_check", + service.bind_address() + ) + ); + + env.stop().await.expect("it should stop the service"); + } + + service.stop().await; + } + + #[tokio::test] + pub(crate) async fn it_should_return_error_when_http_service_was_stopped_after_registration() { + let configuration = Arc::new(configuration::ephemeral()); + + let service = http::Started::new(&configuration).await; + + let binding = *service.bind_address(); + + let registar = service.registar.clone(); + + service.server.stop().await.expect("it should stop udp server"); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Error); + assert_eq!(report.message, "health check failed".to_string()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, binding); + assert!(details.result.as_ref().is_err_and(|e| e.contains("Connection refused"))); + assert_eq!( + details.info, + format!("checking http tracker health check at: http://{binding}/health_check") + ); + + env.stop().await.expect("it should stop the service"); + } + } +} + +mod udp { + use std::sync::Arc; + + use torrust_tracker::servers::health_check_api::resources::{Report, Status}; + use torrust_tracker_test_helpers::configuration; + + use crate::servers::health_check_api::client::get; + use crate::servers::health_check_api::Started; + use crate::servers::udp; + + #[tokio::test] + pub(crate) async fn it_should_return_good_health_for_udp_service() { + let configuration = Arc::new(configuration::ephemeral()); + + let service = udp::Started::new(&configuration).await; + + let registar = service.registar.clone(); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Ok); + assert_eq!(report.message, String::new()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, service.bind_address()); + assert_eq!(details.result, Ok("Connected".to_string())); + + assert_eq!( + details.info, + format!("checking the udp tracker health check at: {}", service.bind_address()) + ); + + env.stop().await.expect("it should stop the service"); + } + + service.stop().await; + } + + #[tokio::test] + pub(crate) async fn it_should_return_error_when_udp_service_was_stopped_after_registration() { + let configuration = Arc::new(configuration::ephemeral()); + + let service = udp::Started::new(&configuration).await; + + let binding = service.bind_address(); + + let registar = service.registar.clone(); + + service.server.stop().await.expect("it should stop udp server"); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Error); + assert_eq!(report.message, "health check failed".to_string()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, binding); + assert_eq!(details.result, Err("Timed Out".to_string())); + assert_eq!(details.info, format!("checking the udp tracker health check at: {binding}")); + + env.stop().await.expect("it should stop the service"); + } + } } diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs new file mode 100644 index 000000000..9aa3ab16d --- /dev/null +++ b/tests/servers/health_check_api/environment.rs @@ -0,0 +1,91 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use tokio::sync::oneshot::{self, Sender}; +use tokio::task::JoinHandle; +use torrust_tracker::bootstrap::jobs::Started; +use torrust_tracker::servers::health_check_api::server; +use torrust_tracker::servers::registar::Registar; +use torrust_tracker::servers::signals::{self, Halted}; +use torrust_tracker_configuration::HealthCheckApi; + +#[derive(Debug)] +pub enum Error { + Error(String), +} + +pub struct Running { + pub binding: SocketAddr, + pub halt_task: Sender, + pub task: JoinHandle, +} + +pub struct Stopped { + pub bind_to: SocketAddr, +} + +pub struct Environment { + pub registar: Registar, + pub state: S, +} + +impl Environment { + pub fn new(config: &Arc, registar: Registar) -> Self { + let bind_to = config + .bind_address + .parse::() + .expect("Tracker API bind_address invalid."); + + Self { + registar, + state: Stopped { bind_to }, + } + } + + /// Start the test environment for the Health Check API. + /// It runs the API server. + pub async fn start(self) -> Environment { + let (tx_start, rx_start) = oneshot::channel::(); + let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); + + let register = self.registar.entries(); + + let server = tokio::spawn(async move { + server::start(self.state.bind_to, tx_start, rx_halt, register) + .await + .expect("it should start the health check service"); + self.state.bind_to + }); + + let binding = rx_start.await.expect("it should send service binding").address; + + Environment { + registar: self.registar.clone(), + state: Running { + task: server, + halt_task: tx_halt, + binding, + }, + } + } +} + +impl Environment { + pub async fn new(config: &Arc, registar: Registar) -> Self { + Environment::::new(config, registar).start().await + } + + pub async fn stop(self) -> Result, Error> { + self.state + .halt_task + .send(Halted::Normal) + .map_err(|e| Error::Error(e.to_string()))?; + + let bind_to = self.state.task.await.expect("it should shutdown the service"); + + Ok(Environment { + registar: self.registar.clone(), + state: Stopped { bind_to }, + }) + } +} diff --git a/tests/servers/health_check_api/mod.rs b/tests/servers/health_check_api/mod.rs index 89f19a334..9e15c5f62 100644 --- a/tests/servers/health_check_api/mod.rs +++ b/tests/servers/health_check_api/mod.rs @@ -1,3 +1,5 @@ pub mod client; pub mod contract; -pub mod test_environment; +pub mod environment; + +pub type Started = environment::Environment; diff --git a/tests/servers/health_check_api/test_environment.rs b/tests/servers/health_check_api/test_environment.rs deleted file mode 100644 index 18924e101..000000000 --- a/tests/servers/health_check_api/test_environment.rs +++ /dev/null @@ -1,33 +0,0 @@ -use std::net::SocketAddr; - -use tokio::sync::oneshot; -use tokio::task::JoinHandle; -use torrust_tracker::bootstrap::jobs::Started; -use torrust_tracker::servers::health_check_api::server; -use torrust_tracker::servers::registar::ServiceRegistry; -use torrust_tracker_configuration::HealthCheckApi; - -/// Start the test environment for the Health Check API. -/// It runs the API server. -pub async fn start(config: &HealthCheckApi, register: ServiceRegistry) -> (SocketAddr, JoinHandle<()>) { - let bind_addr = config - .bind_address - .parse::() - .expect("Health Check API bind_address invalid."); - - let (tx, rx) = oneshot::channel::(); - - let join_handle = tokio::spawn(async move { - let handle = server::start(bind_addr, tx, register); - if let Ok(()) = handle.await { - panic!("Health Check API server on http://{bind_addr} stopped"); - } - }); - - let bound_addr = match rx.await { - Ok(msg) => msg.address, - Err(e) => panic!("the Health Check API server was dropped: {e}"), - }; - - (bound_addr, join_handle) -} diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs new file mode 100644 index 000000000..326f4e534 --- /dev/null +++ b/tests/servers/http/environment.rs @@ -0,0 +1,81 @@ +use std::sync::Arc; + +use futures::executor::block_on; +use torrust_tracker::bootstrap::app::initialize_with_configuration; +use torrust_tracker::bootstrap::jobs::make_rust_tls; +use torrust_tracker::core::peer::Peer; +use torrust_tracker::core::Tracker; +use torrust_tracker::servers::http::server::{HttpServer, Launcher, Running, Stopped}; +use torrust_tracker::servers::registar::Registar; +use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_configuration::{Configuration, HttpTracker}; + +pub struct Environment { + pub config: Arc, + pub tracker: Arc, + pub registar: Registar, + pub server: HttpServer, +} + +impl Environment { + /// Add a torrent to the tracker + pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &Peer) { + self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; + } +} + +impl Environment { + #[allow(dead_code)] + pub fn new(configuration: &Arc) -> Self { + let tracker = initialize_with_configuration(configuration); + + let config = Arc::new(configuration.http_trackers[0].clone()); + + let bind_to = config + .bind_address + .parse::() + .expect("Tracker API bind_address invalid."); + + let tls = block_on(make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path)) + .map(|tls| tls.expect("tls config failed")); + + let server = HttpServer::new(Launcher::new(bind_to, tls)); + + Self { + config, + tracker, + registar: Registar::default(), + server, + } + } + + #[allow(dead_code)] + pub async fn start(self) -> Environment { + Environment { + config: self.config, + tracker: self.tracker.clone(), + registar: self.registar.clone(), + server: self.server.start(self.tracker, self.registar.give_form()).await.unwrap(), + } + } +} + +impl Environment { + pub async fn new(configuration: &Arc) -> Self { + Environment::::new(configuration).start().await + } + + pub async fn stop(self) -> Environment { + Environment { + config: self.config, + tracker: self.tracker, + registar: Registar::default(), + + server: self.server.stop().await.unwrap(), + } + } + + pub fn bind_address(&self) -> &std::net::SocketAddr { + &self.server.state.binding + } +} diff --git a/tests/servers/http/mod.rs b/tests/servers/http/mod.rs index cb2885df0..65affc433 100644 --- a/tests/servers/http/mod.rs +++ b/tests/servers/http/mod.rs @@ -1,11 +1,14 @@ pub mod asserts; pub mod client; +pub mod environment; pub mod requests; pub mod responses; -pub mod test_environment; pub mod v1; +pub type Started = environment::Environment; + use percent_encoding::NON_ALPHANUMERIC; +use torrust_tracker::servers::http::server; pub type ByteArray20 = [u8; 20]; diff --git a/tests/servers/http/test_environment.rs b/tests/servers/http/test_environment.rs deleted file mode 100644 index 9cab40db2..000000000 --- a/tests/servers/http/test_environment.rs +++ /dev/null @@ -1,133 +0,0 @@ -use std::sync::Arc; - -use futures::executor::block_on; -use torrust_tracker::bootstrap::jobs::make_rust_tls; -use torrust_tracker::core::peer::Peer; -use torrust_tracker::core::Tracker; -use torrust_tracker::servers::http::server::{HttpServer, Launcher, RunningHttpServer, StoppedHttpServer}; -use torrust_tracker::servers::registar::Registar; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - -use crate::common::app::setup_with_configuration; - -#[allow(clippy::module_name_repetitions, dead_code)] -pub type StoppedTestEnvironment = TestEnvironment; -#[allow(clippy::module_name_repetitions)] -pub type RunningTestEnvironment = TestEnvironment; - -pub struct TestEnvironment { - pub cfg: Arc, - pub tracker: Arc, - pub state: S, -} - -#[allow(dead_code)] -pub struct Stopped { - http_server: StoppedHttpServer, -} - -pub struct Running { - http_server: RunningHttpServer, -} - -impl TestEnvironment { - /// Add a torrent to the tracker - pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &Peer) { - self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; - } -} - -impl TestEnvironment { - #[allow(dead_code)] - pub fn new_stopped(cfg: torrust_tracker_configuration::Configuration) -> Self { - let cfg = Arc::new(cfg); - - let tracker = setup_with_configuration(&cfg); - - let config = cfg.http_trackers[0].clone(); - - let bind_to = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); - - let tls = block_on(make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path)) - .map(|tls| tls.expect("tls config failed")); - - let http_server = HttpServer::new(Launcher::new(bind_to, tls)); - - Self { - cfg, - tracker, - state: Stopped { http_server }, - } - } - - #[allow(dead_code)] - pub async fn start(self) -> TestEnvironment { - TestEnvironment { - cfg: self.cfg, - tracker: self.tracker.clone(), - state: Running { - http_server: self - .state - .http_server - .start(self.tracker, Registar::default().give_form()) - .await - .unwrap(), - }, - } - } - - // #[allow(dead_code)] - // pub fn config(&self) -> &torrust_tracker_configuration::HttpTracker { - // &self.state.http_server.cfg - // } - - // #[allow(dead_code)] - // pub fn config_mut(&mut self) -> &mut torrust_tracker_configuration::HttpTracker { - // &mut self.state.http_server.cfg - // } -} - -impl TestEnvironment { - pub async fn new_running(cfg: torrust_tracker_configuration::Configuration) -> Self { - let test_env = StoppedTestEnvironment::new_stopped(cfg); - - test_env.start().await - } - - pub async fn stop(self) -> TestEnvironment { - TestEnvironment { - cfg: self.cfg, - tracker: self.tracker, - state: Stopped { - http_server: self.state.http_server.stop().await.unwrap(), - }, - } - } - - pub fn bind_address(&self) -> &std::net::SocketAddr { - &self.state.http_server.state.binding - } - - // #[allow(dead_code)] - // pub fn config(&self) -> &torrust_tracker_configuration::HttpTracker { - // &self.state.http_server.cfg - // } -} - -#[allow(clippy::module_name_repetitions, dead_code)] -pub fn stopped_test_environment(cfg: torrust_tracker_configuration::Configuration) -> StoppedTestEnvironment { - TestEnvironment::new_stopped(cfg) -} - -#[allow(clippy::module_name_repetitions)] -pub async fn running_test_environment(cfg: torrust_tracker_configuration::Configuration) -> RunningTestEnvironment { - TestEnvironment::new_running(cfg).await -} - -#[allow(dead_code)] -pub fn http_server(launcher: Launcher) -> StoppedHttpServer { - HttpServer::new(launcher) -} diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index e394779ad..be285dcd7 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -1,12 +1,12 @@ use torrust_tracker_test_helpers::configuration; -use crate::servers::http::test_environment::running_test_environment; +use crate::servers::http::Started; #[tokio::test] -async fn test_environment_should_be_started_and_stopped() { - let test_env = running_test_environment(configuration::ephemeral()).await; +async fn environment_should_be_started_and_stopped() { + let env = Started::new(&configuration::ephemeral().into()).await; - test_env.stop().await; + env.stop().await; } mod for_all_config_modes { @@ -15,19 +15,19 @@ mod for_all_config_modes { use torrust_tracker_test_helpers::configuration; use crate::servers::http::client::Client; - use crate::servers::http::test_environment::running_test_environment; + use crate::servers::http::Started; #[tokio::test] async fn health_check_endpoint_should_return_ok_if_the_http_tracker_is_running() { - let test_env = running_test_environment(configuration::ephemeral_with_reverse_proxy()).await; + let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; - let response = Client::new(*test_env.bind_address()).health_check().await; + let response = Client::new(*env.bind_address()).health_check().await; assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); assert_eq!(response.json::().await.unwrap(), Report { status: Status::Ok }); - test_env.stop().await; + env.stop().await; } mod and_running_on_reverse_proxy { @@ -36,37 +36,37 @@ mod for_all_config_modes { use crate::servers::http::asserts::assert_could_not_find_remote_address_on_x_forwarded_for_header_error_response; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; - use crate::servers::http::test_environment::running_test_environment; + use crate::servers::http::Started; #[tokio::test] async fn should_fail_when_the_http_request_does_not_include_the_xff_http_request_header() { // If the tracker is running behind a reverse proxy, the peer IP is the // right most IP in the `X-Forwarded-For` HTTP header, which is the IP of the proxy's client. - let test_env = running_test_environment(configuration::ephemeral_with_reverse_proxy()).await; + let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; let params = QueryBuilder::default().query().params(); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_could_not_find_remote_address_on_x_forwarded_for_header_error_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_xff_http_request_header_contains_an_invalid_ip() { - let test_env = running_test_environment(configuration::ephemeral_with_reverse_proxy()).await; + let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; let params = QueryBuilder::default().query().params(); - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .get_with_header(&format!("announce?{params}"), "X-Forwarded-For", "INVALID IP") .await; assert_could_not_find_remote_address_on_x_forwarded_for_header_error_response(response).await; - test_env.stop().await; + env.stop().await; } } @@ -102,60 +102,59 @@ mod for_all_config_modes { }; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::{Compact, QueryBuilder}; - use crate::servers::http::responses; use crate::servers::http::responses::announce::{Announce, CompactPeer, CompactPeerList, DictionaryPeer}; - use crate::servers::http::test_environment::running_test_environment; + use crate::servers::http::{responses, Started}; #[tokio::test] async fn it_should_start_and_stop() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; - test_env.stop().await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + env.stop().await; } #[tokio::test] async fn should_respond_if_only_the_mandatory_fields_are_provided() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); params.remove_optional_params(); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_is_announce_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_url_query_component_is_empty() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let response = Client::new(*test_env.bind_address()).get("announce").await; + let response = Client::new(*env.bind_address()).get("announce").await; assert_missing_query_params_for_announce_request_error_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_url_query_parameters_are_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_query_param = "a=b=c"; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .get(&format!("announce?{invalid_query_param}")) .await; assert_cannot_parse_query_param_error_response(response, "invalid param a=b=c").await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_a_mandatory_field_is_missing() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; // Without `info_hash` param @@ -163,7 +162,7 @@ mod for_all_config_modes { params.info_hash = None; - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "missing param info_hash").await; @@ -173,7 +172,7 @@ mod for_all_config_modes { params.peer_id = None; - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "missing param peer_id").await; @@ -183,28 +182,28 @@ mod for_all_config_modes { params.port = None; - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "missing param port").await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); for invalid_value in &invalid_info_hashes() { params.set("info_hash", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_cannot_parse_query_params_error_response(response, "").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] @@ -214,22 +213,22 @@ mod for_all_config_modes { // 1. If tracker is NOT running `on_reverse_proxy` from the remote client IP. // 2. If tracker is running `on_reverse_proxy` from `X-Forwarded-For` request HTTP header. - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); params.peer_addr = Some("INVALID-IP-ADDRESS".to_string()); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_is_announce_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_downloaded_param_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -238,17 +237,17 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("downloaded", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_uploaded_param_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -257,17 +256,17 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("uploaded", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_peer_id_param_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -283,17 +282,17 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("peer_id", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_port_param_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -302,17 +301,17 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("port", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_left_param_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -321,17 +320,17 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("left", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_event_param_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -348,17 +347,17 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("event", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_compact_param_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -367,19 +366,19 @@ mod for_all_config_modes { for invalid_value in invalid_values { params.set("compact", invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_bad_announce_request_error_response(response, "invalid param value").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_no_peers_if_the_announced_peer_is_the_first_one() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce( &QueryBuilder::default() .with_info_hash(&InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap()) @@ -387,7 +386,7 @@ mod for_all_config_modes { ) .await; - let announce_policy = test_env.tracker.get_announce_policy(); + let announce_policy = env.tracker.get_announce_policy(); assert_announce_response( response, @@ -401,12 +400,12 @@ mod for_all_config_modes { ) .await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_list_of_previously_announced_peers() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -416,10 +415,10 @@ mod for_all_config_modes { .build(); // Add the Peer 1 - test_env.add_torrent_peer(&info_hash, &previously_announced_peer).await; + env.add_torrent_peer(&info_hash, &previously_announced_peer).await; // Announce the new Peer 2. This new peer is non included on the response peer list - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce( &QueryBuilder::default() .with_info_hash(&info_hash) @@ -428,7 +427,7 @@ mod for_all_config_modes { ) .await; - let announce_policy = test_env.tracker.get_announce_policy(); + let announce_policy = env.tracker.get_announce_policy(); // It should only contain the previously announced peer assert_announce_response( @@ -443,12 +442,12 @@ mod for_all_config_modes { ) .await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_list_of_previously_announced_peers_including_peers_using_ipv4_and_ipv6() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -457,7 +456,7 @@ mod for_all_config_modes { .with_peer_id(&peer::Id(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), 8080)) .build(); - test_env.add_torrent_peer(&info_hash, &peer_using_ipv4).await; + env.add_torrent_peer(&info_hash, &peer_using_ipv4).await; // Announce a peer using IPV6 let peer_using_ipv6 = PeerBuilder::default() @@ -467,10 +466,10 @@ mod for_all_config_modes { 8080, )) .build(); - test_env.add_torrent_peer(&info_hash, &peer_using_ipv6).await; + env.add_torrent_peer(&info_hash, &peer_using_ipv6).await; // Announce the new Peer. - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce( &QueryBuilder::default() .with_info_hash(&info_hash) @@ -479,7 +478,7 @@ mod for_all_config_modes { ) .await; - let announce_policy = test_env.tracker.get_announce_policy(); + let announce_policy = env.tracker.get_announce_policy(); // The newly announced peer is not included on the response peer list, // but all the previously announced peers should be included regardless the IP version they are using. @@ -495,18 +494,18 @@ mod for_all_config_modes { ) .await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_consider_two_peers_to_be_the_same_when_they_have_the_same_peer_id_even_if_the_ip_is_different() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); let peer = PeerBuilder::default().build(); // Add a peer - test_env.add_torrent_peer(&info_hash, &peer).await; + env.add_torrent_peer(&info_hash, &peer).await; let announce_query = QueryBuilder::default() .with_info_hash(&info_hash) @@ -515,11 +514,11 @@ mod for_all_config_modes { assert_ne!(peer.peer_addr.ip(), announce_query.peer_addr); - let response = Client::new(*test_env.bind_address()).announce(&announce_query).await; + let response = Client::new(*env.bind_address()).announce(&announce_query).await; assert_empty_announce_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] @@ -527,7 +526,7 @@ mod for_all_config_modes { // Tracker Returns Compact Peer Lists // https://www.bittorrent.org/beps/bep_0023.html - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -537,10 +536,10 @@ mod for_all_config_modes { .build(); // Add the Peer 1 - test_env.add_torrent_peer(&info_hash, &previously_announced_peer).await; + env.add_torrent_peer(&info_hash, &previously_announced_peer).await; // Announce the new Peer 2 accepting compact responses - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce( &QueryBuilder::default() .with_info_hash(&info_hash) @@ -560,7 +559,7 @@ mod for_all_config_modes { assert_compact_announce_response(response, &expected_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] @@ -568,7 +567,7 @@ mod for_all_config_modes { // code-review: the HTTP tracker does not return the compact response by default if the "compact" // param is not provided in the announce URL. The BEP 23 suggest to do so. - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -578,12 +577,12 @@ mod for_all_config_modes { .build(); // Add the Peer 1 - test_env.add_torrent_peer(&info_hash, &previously_announced_peer).await; + env.add_torrent_peer(&info_hash, &previously_announced_peer).await; // Announce the new Peer 2 without passing the "compact" param // By default it should respond with the compact peer list // https://www.bittorrent.org/beps/bep_0023.html - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce( &QueryBuilder::default() .with_info_hash(&info_hash) @@ -595,7 +594,7 @@ mod for_all_config_modes { assert!(!is_a_compact_announce_response(response).await); - test_env.stop().await; + env.stop().await; } async fn is_a_compact_announce_response(response: Response) -> bool { @@ -606,19 +605,19 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp4_connections_handled_in_statistics() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; - Client::new(*test_env.bind_address()) + Client::new(*env.bind_address()) .announce(&QueryBuilder::default().query()) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.tracker.get_stats().await; assert_eq!(stats.tcp4_connections_handled, 1); drop(stats); - test_env.stop().await; + env.stop().await; } #[tokio::test] @@ -630,28 +629,28 @@ mod for_all_config_modes { return; // we cannot bind to a ipv6 socket, so we will skip this test } - let test_env = running_test_environment(configuration::ephemeral_ipv6()).await; + let env = Started::new(&configuration::ephemeral_ipv6().into()).await; - Client::bind(*test_env.bind_address(), IpAddr::from_str("::1").unwrap()) + Client::bind(*env.bind_address(), IpAddr::from_str("::1").unwrap()) .announce(&QueryBuilder::default().query()) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.tracker.get_stats().await; assert_eq!(stats.tcp6_connections_handled, 1); drop(stats); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_increase_the_number_of_tcp6_connections_handled_if_the_client_is_not_using_an_ipv6_ip() { // The tracker ignores the peer address in the request param. It uses the client remote ip address. - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; - Client::new(*test_env.bind_address()) + Client::new(*env.bind_address()) .announce( &QueryBuilder::default() .with_peer_addr(&IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1))) @@ -659,30 +658,30 @@ mod for_all_config_modes { ) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.tracker.get_stats().await; assert_eq!(stats.tcp6_connections_handled, 0); drop(stats); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_increase_the_number_of_tcp4_announce_requests_handled_in_statistics() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; - Client::new(*test_env.bind_address()) + Client::new(*env.bind_address()) .announce(&QueryBuilder::default().query()) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.tracker.get_stats().await; assert_eq!(stats.tcp4_announces_handled, 1); drop(stats); - test_env.stop().await; + env.stop().await; } #[tokio::test] @@ -694,28 +693,28 @@ mod for_all_config_modes { return; // we cannot bind to a ipv6 socket, so we will skip this test } - let test_env = running_test_environment(configuration::ephemeral_ipv6()).await; + let env = Started::new(&configuration::ephemeral_ipv6().into()).await; - Client::bind(*test_env.bind_address(), IpAddr::from_str("::1").unwrap()) + Client::bind(*env.bind_address(), IpAddr::from_str("::1").unwrap()) .announce(&QueryBuilder::default().query()) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.tracker.get_stats().await; assert_eq!(stats.tcp6_announces_handled, 1); drop(stats); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_not_increase_the_number_of_tcp6_announce_requests_handled_if_the_client_is_not_using_an_ipv6_ip() { // The tracker ignores the peer address in the request param. It uses the client remote ip address. - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; - Client::new(*test_env.bind_address()) + Client::new(*env.bind_address()) .announce( &QueryBuilder::default() .with_peer_addr(&IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1))) @@ -723,18 +722,18 @@ mod for_all_config_modes { ) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.tracker.get_stats().await; assert_eq!(stats.tcp6_announces_handled, 0); drop(stats); - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_assign_to_the_peer_ip_the_remote_client_ip_instead_of_the_peer_address_in_the_request_param() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); let client_ip = local_ip().unwrap(); @@ -745,19 +744,19 @@ mod for_all_config_modes { .query(); { - let client = Client::bind(*test_env.bind_address(), client_ip); + let client = Client::bind(*env.bind_address(), client_ip); let status = client.announce(&announce_query).await.status(); assert_eq!(status, StatusCode::OK); } - let peers = test_env.tracker.get_torrent_peers(&info_hash).await; + let peers = env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), client_ip); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); - test_env.stop().await; + env.stop().await; } #[tokio::test] @@ -768,11 +767,8 @@ mod for_all_config_modes { client <-> tracker <-> Internet 127.0.0.1 external_ip = "2.137.87.41" */ - - let test_env = running_test_environment(configuration::ephemeral_with_external_ip( - IpAddr::from_str("2.137.87.41").unwrap(), - )) - .await; + let env = + Started::new(&configuration::ephemeral_with_external_ip(IpAddr::from_str("2.137.87.41").unwrap()).into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); let loopback_ip = IpAddr::from_str("127.0.0.1").unwrap(); @@ -784,19 +780,19 @@ mod for_all_config_modes { .query(); { - let client = Client::bind(*test_env.bind_address(), client_ip); + let client = Client::bind(*env.bind_address(), client_ip); let status = client.announce(&announce_query).await.status(); assert_eq!(status, StatusCode::OK); } - let peers = test_env.tracker.get_torrent_peers(&info_hash).await; + let peers = env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; - assert_eq!(peer_addr.ip(), test_env.tracker.get_maybe_external_ip().unwrap()); + assert_eq!(peer_addr.ip(), env.tracker.get_maybe_external_ip().unwrap()); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); - test_env.stop().await; + env.stop().await; } #[tokio::test] @@ -808,9 +804,10 @@ mod for_all_config_modes { ::1 external_ip = "2345:0425:2CA1:0000:0000:0567:5673:23b5" */ - let test_env = running_test_environment(configuration::ephemeral_with_external_ip( - IpAddr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap(), - )) + let env = Started::new( + &configuration::ephemeral_with_external_ip(IpAddr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap()) + .into(), + ) .await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -823,19 +820,19 @@ mod for_all_config_modes { .query(); { - let client = Client::bind(*test_env.bind_address(), client_ip); + let client = Client::bind(*env.bind_address(), client_ip); let status = client.announce(&announce_query).await.status(); assert_eq!(status, StatusCode::OK); } - let peers = test_env.tracker.get_torrent_peers(&info_hash).await; + let peers = env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; - assert_eq!(peer_addr.ip(), test_env.tracker.get_maybe_external_ip().unwrap()); + assert_eq!(peer_addr.ip(), env.tracker.get_maybe_external_ip().unwrap()); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); - test_env.stop().await; + env.stop().await; } #[tokio::test] @@ -847,14 +844,14 @@ mod for_all_config_modes { 145.254.214.256 X-Forwarded-For = 145.254.214.256 on_reverse_proxy = true 145.254.214.256 */ - let test_env = running_test_environment(configuration::ephemeral_with_reverse_proxy()).await; + let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); let announce_query = QueryBuilder::default().with_info_hash(&info_hash).query(); { - let client = Client::new(*test_env.bind_address()); + let client = Client::new(*env.bind_address()); let status = client .announce_with_header( &announce_query, @@ -867,12 +864,12 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = test_env.tracker.get_torrent_peers(&info_hash).await; + let peers = env.tracker.get_torrent_peers(&info_hash).await; let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), IpAddr::from_str("150.172.238.178").unwrap()); - test_env.stop().await; + env.stop().await; } } @@ -901,56 +898,54 @@ mod for_all_config_modes { assert_scrape_response, }; use crate::servers::http::client::Client; - use crate::servers::http::requests; use crate::servers::http::requests::scrape::QueryBuilder; use crate::servers::http::responses::scrape::{self, File, ResponseBuilder}; - use crate::servers::http::test_environment::running_test_environment; + use crate::servers::http::{requests, Started}; //#[tokio::test] #[allow(dead_code)] async fn should_fail_when_the_request_is_empty() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; - let response = Client::new(*test_env.bind_address()).get("scrape").await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let response = Client::new(*env.bind_address()).get("scrape").await; assert_missing_query_params_for_scrape_request_error_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; let mut params = QueryBuilder::default().query().params(); for invalid_value in &invalid_info_hashes() { params.set_one_info_hash_param(invalid_value); - let response = Client::new(*test_env.bind_address()).get(&format!("announce?{params}")).await; + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; assert_cannot_parse_query_params_error_response(response, "").await; } - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_file_with_the_incomplete_peer_when_there_is_one_peer_with_bytes_pending_to_download() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) - .build(), - ) - .await; + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_bytes_pending_to_download(1) + .build(), + ) + .await; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -971,26 +966,25 @@ mod for_all_config_modes { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_file_with_the_complete_peer_when_there_is_one_peer_with_no_bytes_pending_to_download() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_no_bytes_pending_to_download() - .build(), - ) - .await; + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_no_bytes_pending_to_download() + .build(), + ) + .await; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1011,16 +1005,16 @@ mod for_all_config_modes { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_a_file_with_zeroed_values_when_there_are_no_peers() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1030,17 +1024,17 @@ mod for_all_config_modes { assert_scrape_response(response, &scrape::Response::with_one_file(info_hash.bytes(), File::zeroed())).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_accept_multiple_infohashes() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; let info_hash1 = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); let info_hash2 = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .add_info_hash(&info_hash1) @@ -1056,16 +1050,16 @@ mod for_all_config_modes { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_increase_the_number_ot_tcp4_scrape_requests_handled_in_statistics() { - let test_env = running_test_environment(configuration::ephemeral_mode_public()).await; + let env = Started::new(&configuration::ephemeral_mode_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - Client::new(*test_env.bind_address()) + Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1073,13 +1067,13 @@ mod for_all_config_modes { ) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.tracker.get_stats().await; assert_eq!(stats.tcp4_scrapes_handled, 1); drop(stats); - test_env.stop().await; + env.stop().await; } #[tokio::test] @@ -1091,11 +1085,11 @@ mod for_all_config_modes { return; // we cannot bind to a ipv6 socket, so we will skip this test } - let test_env = running_test_environment(configuration::ephemeral_ipv6()).await; + let env = Started::new(&configuration::ephemeral_ipv6().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - Client::bind(*test_env.bind_address(), IpAddr::from_str("::1").unwrap()) + Client::bind(*env.bind_address(), IpAddr::from_str("::1").unwrap()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1103,13 +1097,13 @@ mod for_all_config_modes { ) .await; - let stats = test_env.tracker.get_stats().await; + let stats = env.tracker.get_stats().await; assert_eq!(stats.tcp6_scrapes_handled, 1); drop(stats); - test_env.stop().await; + env.stop().await; } } } @@ -1125,42 +1119,41 @@ mod configured_as_whitelisted { use crate::servers::http::asserts::{assert_is_announce_response, assert_torrent_not_in_whitelist_error_response}; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; - use crate::servers::http::test_environment::running_test_environment; + use crate::servers::http::Started; #[tokio::test] async fn should_fail_if_the_torrent_is_not_in_the_whitelist() { - let test_env = running_test_environment(configuration::ephemeral_mode_whitelisted()).await; + let env = Started::new(&configuration::ephemeral_mode_whitelisted().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce(&QueryBuilder::default().with_info_hash(&info_hash).query()) .await; assert_torrent_not_in_whitelist_error_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_allow_announcing_a_whitelisted_torrent() { - let test_env = running_test_environment(configuration::ephemeral_mode_whitelisted()).await; + let env = Started::new(&configuration::ephemeral_mode_whitelisted().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - test_env - .tracker + env.tracker .add_torrent_to_whitelist(&info_hash) .await .expect("should add the torrent to the whitelist"); - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce(&QueryBuilder::default().with_info_hash(&info_hash).query()) .await; assert_is_announce_response(response).await; - test_env.stop().await; + env.stop().await; } } @@ -1174,27 +1167,25 @@ mod configured_as_whitelisted { use crate::servers::http::asserts::assert_scrape_response; use crate::servers::http::client::Client; - use crate::servers::http::requests; use crate::servers::http::responses::scrape::{File, ResponseBuilder}; - use crate::servers::http::test_environment::running_test_environment; + use crate::servers::http::{requests, Started}; #[tokio::test] async fn should_return_the_zeroed_file_when_the_requested_file_is_not_whitelisted() { - let test_env = running_test_environment(configuration::ephemeral_mode_whitelisted()).await; + let env = Started::new(&configuration::ephemeral_mode_whitelisted().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) - .build(), - ) - .await; + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_bytes_pending_to_download(1) + .build(), + ) + .await; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1206,32 +1197,30 @@ mod configured_as_whitelisted { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_file_stats_when_the_requested_file_is_whitelisted() { - let test_env = running_test_environment(configuration::ephemeral_mode_whitelisted()).await; + let env = Started::new(&configuration::ephemeral_mode_whitelisted().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) - .build(), - ) - .await; + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_bytes_pending_to_download(1) + .build(), + ) + .await; - test_env - .tracker + env.tracker .add_torrent_to_whitelist(&info_hash) .await .expect("should add the torrent to the whitelist"); - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1252,7 +1241,7 @@ mod configured_as_whitelisted { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } } } @@ -1270,45 +1259,45 @@ mod configured_as_private { use crate::servers::http::asserts::{assert_authentication_error_response, assert_is_announce_response}; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; - use crate::servers::http::test_environment::running_test_environment; + use crate::servers::http::Started; #[tokio::test] async fn should_respond_to_authenticated_peers() { - let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; + let env = Started::new(&configuration::ephemeral_mode_private().into()).await; - let expiring_key = test_env.tracker.generate_auth_key(Duration::from_secs(60)).await.unwrap(); + let expiring_key = env.tracker.generate_auth_key(Duration::from_secs(60)).await.unwrap(); - let response = Client::authenticated(*test_env.bind_address(), expiring_key.key()) + let response = Client::authenticated(*env.bind_address(), expiring_key.key()) .announce(&QueryBuilder::default().query()) .await; assert_is_announce_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_if_the_peer_has_not_provided_the_authentication_key() { - let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; + let env = Started::new(&configuration::ephemeral_mode_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .announce(&QueryBuilder::default().with_info_hash(&info_hash).query()) .await; assert_authentication_error_response(response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { - let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; + let env = Started::new(&configuration::ephemeral_mode_private().into()).await; let invalid_key = "INVALID_KEY"; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .get(&format!( "announce/{invalid_key}?info_hash=%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00&peer_addr=2.137.87.41&downloaded=0&uploaded=0&peer_id=-qB00000000000000001&port=17548&left=0&event=completed&compact=0" )) @@ -1319,18 +1308,18 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_peer_cannot_be_authenticated_with_the_provided_key() { - let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; + let env = Started::new(&configuration::ephemeral_mode_private().into()).await; // The tracker does not have this key let unregistered_key = Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - let response = Client::authenticated(*test_env.bind_address(), unregistered_key) + let response = Client::authenticated(*env.bind_address(), unregistered_key) .announce(&QueryBuilder::default().query()) .await; assert_authentication_error_response(response).await; - test_env.stop().await; + env.stop().await; } } @@ -1347,17 +1336,16 @@ mod configured_as_private { use crate::servers::http::asserts::{assert_authentication_error_response, assert_scrape_response}; use crate::servers::http::client::Client; - use crate::servers::http::requests; use crate::servers::http::responses::scrape::{File, ResponseBuilder}; - use crate::servers::http::test_environment::running_test_environment; + use crate::servers::http::{requests, Started}; #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { - let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; + let env = Started::new(&configuration::ephemeral_mode_private().into()).await; let invalid_key = "INVALID_KEY"; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .get(&format!( "scrape/{invalid_key}?info_hash=%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0" )) @@ -1368,21 +1356,20 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_zeroed_file_when_the_client_is_not_authenticated() { - let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; + let env = Started::new(&configuration::ephemeral_mode_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) - .build(), - ) - .await; + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_bytes_pending_to_download(1) + .build(), + ) + .await; - let response = Client::new(*test_env.bind_address()) + let response = Client::new(*env.bind_address()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1394,28 +1381,27 @@ mod configured_as_private { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] async fn should_return_the_real_file_stats_when_the_client_is_authenticated() { - let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; + let env = Started::new(&configuration::ephemeral_mode_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) - .build(), - ) - .await; + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_bytes_pending_to_download(1) + .build(), + ) + .await; - let expiring_key = test_env.tracker.generate_auth_key(Duration::from_secs(60)).await.unwrap(); + let expiring_key = env.tracker.generate_auth_key(Duration::from_secs(60)).await.unwrap(); - let response = Client::authenticated(*test_env.bind_address(), expiring_key.key()) + let response = Client::authenticated(*env.bind_address(), expiring_key.key()) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1436,7 +1422,7 @@ mod configured_as_private { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } #[tokio::test] @@ -1444,23 +1430,22 @@ mod configured_as_private { // There is not authentication error // code-review: should this really be this way? - let test_env = running_test_environment(configuration::ephemeral_mode_private()).await; + let env = Started::new(&configuration::ephemeral_mode_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - test_env - .add_torrent_peer( - &info_hash, - &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) - .build(), - ) - .await; + env.add_torrent_peer( + &info_hash, + &PeerBuilder::default() + .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_bytes_pending_to_download(1) + .build(), + ) + .await; let false_key: Key = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ".parse().unwrap(); - let response = Client::authenticated(*test_env.bind_address(), false_key) + let response = Client::authenticated(*env.bind_address(), false_key) .scrape( &requests::scrape::QueryBuilder::default() .with_one_info_hash(&info_hash) @@ -1472,7 +1457,7 @@ mod configured_as_private { assert_scrape_response(response, &expected_scrape_response).await; - test_env.stop().await; + env.stop().await; } } } diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index b16a47cd3..9ac585190 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -11,7 +11,7 @@ use torrust_tracker::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_error_response; -use crate::servers::udp::test_environment::running_test_environment; +use crate::servers::udp::Started; fn empty_udp_request() -> [u8; MAX_PACKET_SIZE] { [0; MAX_PACKET_SIZE] @@ -36,9 +36,9 @@ async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrac #[tokio::test] async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_request() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let client = new_udp_client_connected(&test_env.bind_address().to_string()).await; + let client = new_udp_client_connected(&env.bind_address().to_string()).await; client.send(&empty_udp_request()).await; @@ -55,13 +55,13 @@ mod receiving_a_connection_request { use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_connect_response; - use crate::servers::udp::test_environment::running_test_environment; + use crate::servers::udp::Started; #[tokio::test] async fn should_return_a_connect_response() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let client = new_udp_tracker_client_connected(&test_env.bind_address().to_string()).await; + let client = new_udp_tracker_client_connected(&env.bind_address().to_string()).await; let connect_request = ConnectRequest { transaction_id: TransactionId(123), @@ -87,13 +87,13 @@ mod receiving_an_announce_request { use crate::servers::udp::asserts::is_ipv4_announce_response; use crate::servers::udp::contract::send_connection_request; - use crate::servers::udp::test_environment::running_test_environment; + use crate::servers::udp::Started; #[tokio::test] async fn should_return_an_announce_response() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let client = new_udp_tracker_client_connected(&test_env.bind_address().to_string()).await; + let client = new_udp_tracker_client_connected(&env.bind_address().to_string()).await; let connection_id = send_connection_request(TransactionId(123), &client).await; @@ -129,13 +129,13 @@ mod receiving_an_scrape_request { use crate::servers::udp::asserts::is_scrape_response; use crate::servers::udp::contract::send_connection_request; - use crate::servers::udp::test_environment::running_test_environment; + use crate::servers::udp::Started; #[tokio::test] async fn should_return_a_scrape_response() { - let test_env = running_test_environment(configuration::ephemeral()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let client = new_udp_tracker_client_connected(&test_env.bind_address().to_string()).await; + let client = new_udp_tracker_client_connected(&env.bind_address().to_string()).await; let connection_id = send_connection_request(TransactionId(123), &client).await; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs new file mode 100644 index 000000000..26a47987e --- /dev/null +++ b/tests/servers/udp/environment.rs @@ -0,0 +1,78 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker::bootstrap::app::initialize_with_configuration; +use torrust_tracker::core::peer::Peer; +use torrust_tracker::core::Tracker; +use torrust_tracker::servers::registar::Registar; +use torrust_tracker::servers::udp::server::{Launcher, Running, Stopped, UdpServer}; +use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_configuration::{Configuration, UdpTracker}; + +pub struct Environment { + pub config: Arc, + pub tracker: Arc, + pub registar: Registar, + pub server: UdpServer, +} + +impl Environment { + /// Add a torrent to the tracker + #[allow(dead_code)] + pub async fn add_torrent(&self, info_hash: &InfoHash, peer: &Peer) { + self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; + } +} + +impl Environment { + #[allow(dead_code)] + pub fn new(configuration: &Arc) -> Self { + let tracker = initialize_with_configuration(configuration); + + let config = Arc::new(configuration.udp_trackers[0].clone()); + + let bind_to = config + .bind_address + .parse::() + .expect("Tracker API bind_address invalid."); + + let server = UdpServer::new(Launcher::new(bind_to)); + + Self { + config, + tracker, + registar: Registar::default(), + server, + } + } + + #[allow(dead_code)] + pub async fn start(self) -> Environment { + Environment { + config: self.config, + tracker: self.tracker.clone(), + registar: self.registar.clone(), + server: self.server.start(self.tracker, self.registar.give_form()).await.unwrap(), + } + } +} + +impl Environment { + pub async fn new(configuration: &Arc) -> Self { + Environment::::new(configuration).start().await + } + + #[allow(dead_code)] + pub async fn stop(self) -> Environment { + Environment { + config: self.config, + tracker: self.tracker, + registar: Registar::default(), + server: self.server.stop().await.unwrap(), + } + } + + pub fn bind_address(&self) -> SocketAddr { + self.server.state.binding + } +} diff --git a/tests/servers/udp/mod.rs b/tests/servers/udp/mod.rs index 4759350dc..b13b82240 100644 --- a/tests/servers/udp/mod.rs +++ b/tests/servers/udp/mod.rs @@ -1,3 +1,7 @@ +use torrust_tracker::servers::udp::server; + pub mod asserts; pub mod contract; -pub mod test_environment; +pub mod environment; + +pub type Started = environment::Environment; diff --git a/tests/servers/udp/test_environment.rs b/tests/servers/udp/test_environment.rs deleted file mode 100644 index f272b6dd3..000000000 --- a/tests/servers/udp/test_environment.rs +++ /dev/null @@ -1,110 +0,0 @@ -use std::net::SocketAddr; -use std::sync::Arc; - -use torrust_tracker::core::peer::Peer; -use torrust_tracker::core::Tracker; -use torrust_tracker::servers::registar::Registar; -use torrust_tracker::servers::udp::server::{Launcher, RunningUdpServer, StoppedUdpServer, UdpServer}; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - -use crate::common::app::setup_with_configuration; - -#[allow(clippy::module_name_repetitions, dead_code)] -pub type StoppedTestEnvironment = TestEnvironment; -#[allow(clippy::module_name_repetitions)] -pub type RunningTestEnvironment = TestEnvironment; - -pub struct TestEnvironment { - pub cfg: Arc, - pub tracker: Arc, - pub state: S, -} - -#[allow(dead_code)] -pub struct Stopped { - udp_server: StoppedUdpServer, -} - -pub struct Running { - udp_server: RunningUdpServer, -} - -impl TestEnvironment { - /// Add a torrent to the tracker - #[allow(dead_code)] - pub async fn add_torrent(&self, info_hash: &InfoHash, peer: &Peer) { - self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; - } -} - -impl TestEnvironment { - #[allow(dead_code)] - pub fn new_stopped(cfg: torrust_tracker_configuration::Configuration) -> Self { - let cfg = Arc::new(cfg); - - let tracker = setup_with_configuration(&cfg); - - let udp_cfg = cfg.udp_trackers[0].clone(); - - let bind_to = udp_cfg - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); - - let udp_server = udp_server(Launcher::new(bind_to)); - - Self { - cfg, - tracker, - state: Stopped { udp_server }, - } - } - - #[allow(dead_code)] - pub async fn start(self) -> TestEnvironment { - let register = &Registar::default(); - - TestEnvironment { - cfg: self.cfg, - tracker: self.tracker.clone(), - state: Running { - udp_server: self.state.udp_server.start(self.tracker, register.give_form()).await.unwrap(), - }, - } - } -} - -impl TestEnvironment { - pub async fn new_running(cfg: torrust_tracker_configuration::Configuration) -> Self { - StoppedTestEnvironment::new_stopped(cfg).start().await - } - - #[allow(dead_code)] - pub async fn stop(self) -> TestEnvironment { - TestEnvironment { - cfg: self.cfg, - tracker: self.tracker, - state: Stopped { - udp_server: self.state.udp_server.stop().await.unwrap(), - }, - } - } - - pub fn bind_address(&self) -> SocketAddr { - self.state.udp_server.state.binding - } -} - -#[allow(clippy::module_name_repetitions, dead_code)] -pub fn stopped_test_environment(cfg: torrust_tracker_configuration::Configuration) -> StoppedTestEnvironment { - TestEnvironment::new_stopped(cfg) -} - -#[allow(clippy::module_name_repetitions)] -pub async fn running_test_environment(cfg: torrust_tracker_configuration::Configuration) -> RunningTestEnvironment { - TestEnvironment::new_running(cfg).await -} - -pub fn udp_server(launcher: Launcher) -> StoppedUdpServer { - UdpServer::new(launcher) -} From bbf1be6eb9466afaa7092d14aa90cf917afcd18c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 19 Jan 2024 12:54:37 +0000 Subject: [PATCH 0185/1297] fix: don't start HTTP tracker if it's disabled This fixes this error: ``` Loading default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... 2024-01-19T12:43:24.605765751+00:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized. 2024-01-19T12:43:24.606305647+00:00 [torrust_tracker::bootstrap::jobs::http_tracker][INFO] Note: Not loading Http Tracker Service, Not Enabled in Configuration. 2024-01-19T12:43:24.606314967+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled thread 'tokio-runtime-worker' panicked at src/servers/registar.rs:84:32: it should receive the listing: RecvError(()) ``` --- src/app.rs | 4 ++++ src/servers/apis/server.rs | 12 +++++++++--- src/servers/registar.rs | 10 ++++++++-- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/app.rs b/src/app.rs index 3ec9806d3..8bdc281a6 100644 --- a/src/app.rs +++ b/src/app.rs @@ -76,6 +76,10 @@ pub async fn start(config: &Configuration, tracker: Arc) -> Vec { let launcher = self.state.launcher; let task = tokio::spawn(async move { - launcher.start(tracker, access_tokens, tx_start, rx_halt).await; + debug!(target: "API", "Starting with launcher in spawned task ..."); + + let _task = launcher.start(tracker, access_tokens, tx_start, rx_halt).await; + + debug!(target: "API", "Started with launcher in spawned task"); + launcher }); @@ -266,9 +271,10 @@ mod tests { #[tokio::test] async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_mode_public()); - let tracker = initialize_with_configuration(&cfg); let config = &cfg.http_api; + let tracker = initialize_with_configuration(&cfg); + let bind_to = config .bind_address .parse::() diff --git a/src/servers/registar.rs b/src/servers/registar.rs index 0fb8d6acc..9c23573c4 100644 --- a/src/servers/registar.rs +++ b/src/servers/registar.rs @@ -5,6 +5,7 @@ use std::net::SocketAddr; use std::sync::Arc; use derive_more::Constructor; +use log::debug; use tokio::sync::Mutex; use tokio::task::JoinHandle; @@ -81,10 +82,15 @@ impl Registar { /// Inserts a listing into the registry. async fn insert(&self, rx: tokio::sync::oneshot::Receiver) { - let listing = rx.await.expect("it should receive the listing"); + debug!("Waiting for the started service to send registration data ..."); + + let service_registration = rx + .await + .expect("it should receive the service registration from the started service"); let mut mutex = self.registry.lock().await; - mutex.insert(listing.binding, listing); + + mutex.insert(service_registration.binding, service_registration); } /// Returns the [`ServiceRegistry`] of services From 17296cdcb85bde4cad468dc662fde2fd8d70961b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 19 Jan 2024 15:18:55 +0000 Subject: [PATCH 0186/1297] fix: [#626] healt check api server shutdown This fixes: - The error: "Failed to install stop signal: channel closed" - And CRTL+C to shutdown the service --- src/bootstrap/jobs/health_check_api.rs | 20 +++++++++++++------ src/servers/health_check_api/server.rs | 5 ++++- tests/servers/health_check_api/environment.rs | 10 ++++++++++ 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index 7eeafe97b..e57d1c151 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -42,24 +42,32 @@ pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> Jo let (tx_start, rx_start) = oneshot::channel::(); let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); - drop(tx_halt); + + let protocol = "http"; // Run the API server let join_handle = tokio::spawn(async move { - info!(target: "Health Check API", "Starting on: http://{}", bind_addr); + info!(target: "Health Check API", "Starting on: {protocol}://{}", bind_addr); let handle = server::start(bind_addr, tx_start, rx_halt, register); if let Ok(()) = handle.await { - info!(target: "Health Check API", "Stopped server running on: http://{}", bind_addr); + info!(target: "Health Check API", "Stopped server running on: {protocol}://{}", bind_addr); } }); - // Wait until the API server job is running + // Wait until the server sends the started message match rx_start.await { - Ok(msg) => info!(target: "Health Check API", "Started on: http://{}", msg.address), + Ok(msg) => info!(target: "Health Check API", "Started on: {protocol}://{}", msg.address), Err(e) => panic!("the Health Check API server was dropped: {e}"), } - join_handle + // Wait until the server finishes + tokio::spawn(async move { + assert!(!tx_halt.is_closed(), "Halt channel for Health Check API should be open"); + + join_handle + .await + .expect("it should be able to join to the Health Check API server task"); + }) } diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index ecc6fe427..8ba20691f 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -8,6 +8,7 @@ use axum::routing::get; use axum::{Json, Router}; use axum_server::Handle; use futures::Future; +use log::debug; use serde_json::json; use tokio::sync::oneshot::{Receiver, Sender}; @@ -37,10 +38,12 @@ pub fn start( let handle = Handle::new(); + debug!(target: "Health Check API", "Starting service with graceful shutdown in a spawned task ..."); + tokio::task::spawn(graceful_shutdown( handle.clone(), rx_halt, - format!("shutting down http server on socket address: {address}"), + format!("Shutting down http server on socket address: {address}"), )); let running = axum_server::from_tcp(socket) diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs index 9aa3ab16d..c98784282 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/tests/servers/health_check_api/environment.rs @@ -1,6 +1,7 @@ use std::net::SocketAddr; use std::sync::Arc; +use log::debug; use tokio::sync::oneshot::{self, Sender}; use tokio::task::JoinHandle; use torrust_tracker::bootstrap::jobs::Started; @@ -50,13 +51,22 @@ impl Environment { let register = self.registar.entries(); + debug!(target: "Health Check API", "Spawning task to launch the service ..."); + let server = tokio::spawn(async move { + debug!(target: "Health Check API", "Starting the server in a spawned task ..."); + server::start(self.state.bind_to, tx_start, rx_halt, register) .await .expect("it should start the health check service"); + + debug!(target: "Health Check API", "Server started. Sending the binding {} ...", self.state.bind_to); + self.state.bind_to }); + debug!(target: "Health Check API", "Waiting for spawning task to send the binding ..."); + let binding = rx_start.await.expect("it should send service binding").address; Environment { From f0710d3554d67952611af2a5670a542f4f06a176 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 17 Jan 2024 15:35:33 +0000 Subject: [PATCH 0187/1297] feat: [#625] a new UDP tracker client You can use it with: ```console cargo run --bin udp_tracker_client 144.126.245.19:6969 9c38422213e30bff212b30c360d26f9a02136422 ``` and the output should be something like: ``` AnnounceIpv4( AnnounceResponse { transaction_id: TransactionId( -888840697, ), announce_interval: AnnounceInterval( 300, ), leechers: NumberOfPeers( 0, ), seeders: NumberOfPeers( 4, ), peers: [ ResponsePeer { ip_address: xx.yy.zz.254, port: Port( 51516, ), }, ResponsePeer { ip_address: xx.yy.zz.20, port: Port( 59448, ), }, ResponsePeer { ip_address: xx.yy.zz.224, port: Port( 58587, ), }, ], }, ) ``` --- src/bin/udp_tracker_client.rs | 154 +++++++++++++++++++ src/shared/bit_torrent/tracker/udp/client.rs | 32 +++- tests/servers/udp/contract.rs | 2 + 3 files changed, 185 insertions(+), 3 deletions(-) create mode 100644 src/bin/udp_tracker_client.rs diff --git a/src/bin/udp_tracker_client.rs b/src/bin/udp_tracker_client.rs new file mode 100644 index 000000000..41084127c --- /dev/null +++ b/src/bin/udp_tracker_client.rs @@ -0,0 +1,154 @@ +use std::env; +use std::net::{Ipv4Addr, SocketAddr}; +use std::str::FromStr; + +use aquatic_udp_protocol::common::InfoHash; +use aquatic_udp_protocol::{ + AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, Response, + TransactionId, +}; +use log::{debug, LevelFilter}; +use torrust_tracker::shared::bit_torrent::info_hash::InfoHash as TorrustInfoHash; +use torrust_tracker::shared::bit_torrent::tracker::udp::client::{UdpClient, UdpTrackerClient}; + +const ASSIGNED_BY_OS: i32 = 0; +const RANDOM_TRANSACTION_ID: i32 = -888_840_697; + +#[tokio::main] +async fn main() { + setup_logging(LevelFilter::Info); + + let (remote_socket_addr, info_hash) = parse_arguments(); + + // Configuration + let local_port = ASSIGNED_BY_OS; + let transaction_id = RANDOM_TRANSACTION_ID; + let bind_to = format!("0.0.0.0:{local_port}"); + + // Bind to local port + + debug!("Binding to: {bind_to}"); + let udp_client = UdpClient::bind(&bind_to).await; + let bound_to = udp_client.socket.local_addr().unwrap(); + debug!("Bound to: {bound_to}"); + + // Connect to remote socket + + debug!("Connecting to remote: udp://{remote_socket_addr}"); + udp_client.connect(&remote_socket_addr).await; + + let udp_tracker_client = UdpTrackerClient { udp_client }; + + let transaction_id = TransactionId(transaction_id); + + let connection_id = send_connection_request(transaction_id, &udp_tracker_client).await; + + let response = send_announce_request( + connection_id, + transaction_id, + info_hash, + Port(bound_to.port()), + &udp_tracker_client, + ) + .await; + + println!("{response:#?}"); +} + +fn setup_logging(level: LevelFilter) { + if let Err(_err) = fern::Dispatch::new() + .format(|out, message, record| { + out.finish(format_args!( + "{} [{}][{}] {}", + chrono::Local::now().format("%+"), + record.target(), + record.level(), + message + )); + }) + .level(level) + .chain(std::io::stdout()) + .apply() + { + panic!("Failed to initialize logging.") + } + + debug!("logging initialized."); +} + +fn parse_arguments() -> (String, TorrustInfoHash) { + let args: Vec = env::args().collect(); + + if args.len() != 3 { + eprintln!("Error: invalid number of arguments!"); + eprintln!("Usage: cargo run --bin udp_tracker_client "); + eprintln!("Example: cargo run --bin udp_tracker_client 144.126.245.19:6969 9c38422213e30bff212b30c360d26f9a02136422"); + std::process::exit(1); + } + + let remote_socket_addr = &args[1]; + let _valid_socket_addr = remote_socket_addr.parse::().unwrap_or_else(|_| { + panic!( + "Invalid argument: `{}`. Argument 1 should be a valid socket address. For example: `144.126.245.19:6969`.", + args[1] + ) + }); + let info_hash = TorrustInfoHash::from_str(&args[2]).unwrap_or_else(|_| { + panic!( + "Invalid argument: `{}`. Argument 2 should be a valid infohash. For example: `9c38422213e30bff212b30c360d26f9a02136422`.", + args[2] + ) + }); + + (remote_socket_addr.to_string(), info_hash) +} + +async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrackerClient) -> ConnectionId { + debug!("Sending connection request with transaction id: {transaction_id:#?}"); + + let connect_request = ConnectRequest { transaction_id }; + + client.send(connect_request.into()).await; + + let response = client.receive().await; + + debug!("connection request response:\n{response:#?}"); + + match response { + Response::Connect(connect_response) => connect_response.connection_id, + _ => panic!("error connecting to udp server. Unexpected response"), + } +} + +async fn send_announce_request( + connection_id: ConnectionId, + transaction_id: TransactionId, + info_hash: TorrustInfoHash, + port: Port, + client: &UdpTrackerClient, +) -> Response { + debug!("Sending announce request with transaction id: {transaction_id:#?}"); + + let announce_request = AnnounceRequest { + connection_id, + transaction_id, + info_hash: InfoHash(info_hash.bytes()), + peer_id: PeerId(*b"-qB00000000000000001"), + bytes_downloaded: NumberOfBytes(0i64), + bytes_uploaded: NumberOfBytes(0i64), + bytes_left: NumberOfBytes(0i64), + event: AnnounceEvent::Started, + ip_address: Some(Ipv4Addr::new(0, 0, 0, 0)), + key: PeerKey(0u32), + peers_wanted: NumberOfPeers(1i32), + port, + }; + + client.send(announce_request.into()).await; + + let response = client.receive().await; + + debug!("announce request response:\n{response:#?}"); + + response +} diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs index 00f0b8acf..959001e82 100644 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use std::time::Duration; use aquatic_udp_protocol::{ConnectRequest, Request, Response, TransactionId}; +use log::debug; use tokio::net::UdpSocket; use tokio::time; @@ -19,7 +20,12 @@ impl UdpClient { /// /// Will panic if the local address can't be bound. pub async fn bind(local_address: &str) -> Self { - let socket = UdpSocket::bind(local_address).await.unwrap(); + let valid_socket_addr = local_address + .parse::() + .unwrap_or_else(|_| panic!("{local_address} is not a valid socket address")); + + let socket = UdpSocket::bind(valid_socket_addr).await.unwrap(); + Self { socket: Arc::new(socket), } @@ -29,7 +35,14 @@ impl UdpClient { /// /// Will panic if can't connect to the socket. pub async fn connect(&self, remote_address: &str) { - self.socket.connect(remote_address).await.unwrap(); + let valid_socket_addr = remote_address + .parse::() + .unwrap_or_else(|_| panic!("{remote_address} is not a valid socket address")); + + match self.socket.connect(valid_socket_addr).await { + Ok(()) => debug!("Connected successfully"), + Err(e) => panic!("Failed to connect: {e:?}"), + } } /// # Panics @@ -39,6 +52,8 @@ impl UdpClient { /// - Can't write to the socket. /// - Can't send data. pub async fn send(&self, bytes: &[u8]) -> usize { + debug!(target: "UDP client", "send {bytes:?}"); + self.socket.writable().await.unwrap(); self.socket.send(bytes).await.unwrap() } @@ -50,8 +65,15 @@ impl UdpClient { /// - Can't read from the socket. /// - Can't receive data. pub async fn receive(&self, bytes: &mut [u8]) -> usize { + debug!(target: "UDP client", "receiving ..."); + self.socket.readable().await.unwrap(); - self.socket.recv(bytes).await.unwrap() + + let size = self.socket.recv(bytes).await.unwrap(); + + debug!(target: "UDP client", "{size} bytes received {bytes:?}"); + + size } } @@ -73,6 +95,8 @@ impl UdpTrackerClient { /// /// Will panic if can't write request to bytes. pub async fn send(&self, request: Request) -> usize { + debug!(target: "UDP tracker client", "send request {request:?}"); + // Write request into a buffer let request_buffer = vec![0u8; MAX_PACKET_SIZE]; let mut cursor = Cursor::new(request_buffer); @@ -99,6 +123,8 @@ impl UdpTrackerClient { let payload_size = self.udp_client.receive(&mut response_buffer).await; + debug!(target: "UDP tracker client", "received {payload_size} bytes. Response {response_buffer:?}"); + Response::from_bytes(&response_buffer[..payload_size], true).unwrap() } } diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 9ac585190..0eea650b8 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -118,6 +118,8 @@ mod receiving_an_announce_request { let response = client.receive().await; + println!("test response {response:?}"); + assert!(is_ipv4_announce_response(&response)); } } From 4c416e0b25272e1c67770e689c808231a3220d5b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 19 Jan 2024 15:45:01 +0000 Subject: [PATCH 0188/1297] fix: remove coverage report generation from testing workflow The coverage report is also generated in the coverage workflow. And it takes long. --- .github/workflows/testing.yaml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index d9d0c60c9..02dbb1804 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -110,7 +110,3 @@ jobs: - id: test name: Run Unit Tests run: cargo test --tests --benches --examples --workspace --all-targets --all-features - - - id: coverage - name: Generate Coverage Report - run: cargo llvm-cov nextest --tests --benches --examples --workspace --all-targets --all-features From 1b7e5b9e2cdd2085885ac07d4b10034469e94615 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 19 Jan 2024 16:39:46 +0000 Subject: [PATCH 0189/1297] feat: enable all services in dev default config - Using wildcard IPs for UDP and HTTP tracker. - Revert port 0 (unintentionally changed). Use predefined ports. --- share/default/config/tracker.development.sqlite3.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index e26aa6c6c..9304a2d51 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -13,18 +13,18 @@ remove_peerless_torrents = true tracker_usage_statistics = true [[udp_trackers]] -bind_address = "0.0.0.0:0" +bind_address = "0.0.0.0:6969" enabled = true [[http_trackers]] -bind_address = "0.0.0.0:0" +bind_address = "0.0.0.0:7070" enabled = true ssl_cert_path = "" ssl_enabled = false ssl_key_path = "" [http_api] -bind_address = "127.0.0.1:0" +bind_address = "127.0.0.1:1212" enabled = true ssl_cert_path = "" ssl_enabled = false From b2ef4e0d8c39d95f6221317a46ab14fd98248bbb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Jan 2024 10:55:14 +0000 Subject: [PATCH 0190/1297] feat: tracker checker command It runs some checks against a running tracker. --- Cargo.lock | 12 ++ Cargo.toml | 2 + share/default/config/tracker_checker.json | 11 ++ src/bin/tracker_checker.rs | 11 ++ src/checker/app.rs | 53 ++++++++ src/checker/config.rs | 152 ++++++++++++++++++++++ src/checker/console.rs | 38 ++++++ src/checker/logger.rs | 72 ++++++++++ src/checker/mod.rs | 6 + src/checker/printer.rs | 9 ++ src/checker/service.rs | 84 ++++++++++++ src/lib.rs | 1 + 12 files changed, 451 insertions(+) create mode 100644 share/default/config/tracker_checker.json create mode 100644 src/bin/tracker_checker.rs create mode 100644 src/checker/app.rs create mode 100644 src/checker/config.rs create mode 100644 src/checker/console.rs create mode 100644 src/checker/logger.rs create mode 100644 src/checker/mod.rs create mode 100644 src/checker/printer.rs create mode 100644 src/checker/service.rs diff --git a/Cargo.lock b/Cargo.lock index de630b497..1f49aa986 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -627,6 +627,16 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" +[[package]] +name = "colored" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbf2150cce219b664a8a70df7a1f933836724b503f8a413af9365b4dcc4d90b8" +dependencies = [ + "lazy_static", + "windows-sys 0.48.0", +] + [[package]] name = "config" version = "0.13.4" @@ -3418,6 +3428,7 @@ dependencies = [ "axum-server", "binascii", "chrono", + "colored", "config", "criterion", "derive_more", @@ -3454,6 +3465,7 @@ dependencies = [ "torrust-tracker-primitives", "torrust-tracker-test-helpers", "tower-http", + "url", "uuid", ] diff --git a/Cargo.toml b/Cargo.toml index 671d66e98..9b7e71905 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,6 +68,8 @@ torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "pa torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } tower-http = { version = "0", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } +colored = "2.1.0" +url = "2.5.0" [dev-dependencies] criterion = { version = "0.5.1", features = ["async_tokio"] } diff --git a/share/default/config/tracker_checker.json b/share/default/config/tracker_checker.json new file mode 100644 index 000000000..7d1453bfd --- /dev/null +++ b/share/default/config/tracker_checker.json @@ -0,0 +1,11 @@ +{ + "udp_trackers": [ + "127.0.0.1:6969" + ], + "http_trackers": [ + "http://127.0.0.1:7070" + ], + "health_checks": [ + "http://127.0.0.1:1313/health_check" + ] +} \ No newline at end of file diff --git a/src/bin/tracker_checker.rs b/src/bin/tracker_checker.rs new file mode 100644 index 000000000..3a0e0ee88 --- /dev/null +++ b/src/bin/tracker_checker.rs @@ -0,0 +1,11 @@ +//! Program to run checks against running trackers. +//! +//! ```text +//! cargo run --bin tracker_checker "./share/default/config/tracker_checker.json" +//! ``` +use torrust_tracker::checker::app; + +#[tokio::main] +async fn main() { + app::run().await; +} diff --git a/src/checker/app.rs b/src/checker/app.rs new file mode 100644 index 000000000..e92373493 --- /dev/null +++ b/src/checker/app.rs @@ -0,0 +1,53 @@ +use std::sync::Arc; + +use super::config::Configuration; +use super::console::Console; +use crate::checker::config::parse_from_json; +use crate::checker::service::Service; + +pub const NUMBER_OF_ARGUMENTS: usize = 2; + +/// # Panics +/// +/// Will panic if: +/// +/// - It can't read the json configuration file. +/// - The configuration file is invalid. +pub async fn run() { + let args = parse_arguments(); + 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 = std::env::args().collect(); + + if args.len() < NUMBER_OF_ARGUMENTS { + eprintln!("Usage: cargo run --bin tracker_checker "); + 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(), + } +} + +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)); + + parse_from_json(&file_content).expect("Invalid config format") +} diff --git a/src/checker/config.rs b/src/checker/config.rs new file mode 100644 index 000000000..aaf611bb9 --- /dev/null +++ b/src/checker/config.rs @@ -0,0 +1,152 @@ +use std::fmt; +use std::net::SocketAddr; + +use reqwest::Url as ServiceUrl; +use serde::Deserialize; +use url; + +/// It parses the configuration from a JSON format. +/// +/// # Errors +/// +/// Will return an error if the configuration is not valid. +/// +/// # Panics +/// +/// Will panic if unable to read the configuration file. +pub fn parse_from_json(json: &str) -> Result { + let plain_config: PlainConfiguration = serde_json::from_str(json).map_err(ConfigurationError::JsonParseError)?; + Configuration::try_from(plain_config) +} + +/// DTO for the configuration to serialize/deserialize configuration. +/// +/// Configuration does not need to be valid. +#[derive(Deserialize)] +struct PlainConfiguration { + pub udp_trackers: Vec, + pub http_trackers: Vec, + pub health_checks: Vec, +} + +/// Validated configuration +pub struct Configuration { + pub udp_trackers: Vec, + pub http_trackers: Vec, + pub health_checks: Vec, +} + +#[derive(Debug)] +pub enum ConfigurationError { + JsonParseError(serde_json::Error), + InvalidUdpAddress(std::net::AddrParseError), + InvalidUrl(url::ParseError), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ConfigurationError::JsonParseError(e) => write!(f, "JSON parse error: {e}"), + ConfigurationError::InvalidUdpAddress(e) => write!(f, "Invalid UDP address: {e}"), + ConfigurationError::InvalidUrl(e) => write!(f, "Invalid URL: {e}"), + } + } +} + +impl TryFrom for Configuration { + type Error = ConfigurationError; + + fn try_from(plain_config: PlainConfiguration) -> Result { + let udp_trackers = plain_config + .udp_trackers + .into_iter() + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUdpAddress)) + .collect::, _>>()?; + + let http_trackers = plain_config + .http_trackers + .into_iter() + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) + .collect::, _>>()?; + + let health_checks = plain_config + .health_checks + .into_iter() + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) + .collect::, _>>()?; + + Ok(Configuration { + udp_trackers, + http_trackers, + health_checks, + }) + } +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use super::*; + + #[test] + fn configuration_should_be_build_from_plain_serializable_configuration() { + let dto = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:8080".to_string()], + http_trackers: vec!["http://127.0.0.1:8080".to_string()], + health_checks: vec!["http://127.0.0.1:8080/health".to_string()], + }; + + let config = Configuration::try_from(dto).expect("A valid configuration"); + + assert_eq!( + config.udp_trackers, + vec![SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080)] + ); + assert_eq!( + config.http_trackers, + vec![ServiceUrl::parse("http://127.0.0.1:8080").unwrap()] + ); + assert_eq!( + config.health_checks, + vec![ServiceUrl::parse("http://127.0.0.1:8080/health").unwrap()] + ); + } + + mod building_configuration_from_plan_configuration { + use crate::checker::config::{Configuration, PlainConfiguration}; + + #[test] + fn it_should_fail_when_a_tracker_udp_address_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["invalid_address".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + assert!(Configuration::try_from(plain_config).is_err()); + } + + #[test] + fn it_should_fail_when_a_tracker_http_address_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec!["not_a_url".to_string()], + health_checks: vec![], + }; + + assert!(Configuration::try_from(plain_config).is_err()); + } + + #[test] + fn it_should_fail_when_a_health_check_http_address_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec![], + health_checks: vec!["not_a_url".to_string()], + }; + + assert!(Configuration::try_from(plain_config).is_err()); + } + } +} diff --git a/src/checker/console.rs b/src/checker/console.rs new file mode 100644 index 000000000..b55c559fc --- /dev/null +++ b/src/checker/console.rs @@ -0,0 +1,38 @@ +use super::printer::{Printer, CLEAR_SCREEN}; + +pub struct Console {} + +impl Default for Console { + fn default() -> Self { + Self::new() + } +} + +impl Console { + #[must_use] + pub fn new() -> Self { + Self {} + } +} + +impl Printer for Console { + fn clear(&self) { + self.print(CLEAR_SCREEN); + } + + fn print(&self, output: &str) { + print!("{}", &output); + } + + fn eprint(&self, output: &str) { + eprint!("{}", &output); + } + + fn println(&self, output: &str) { + println!("{}", &output); + } + + fn eprintln(&self, output: &str) { + eprintln!("{}", &output); + } +} diff --git a/src/checker/logger.rs b/src/checker/logger.rs new file mode 100644 index 000000000..3d1074e7b --- /dev/null +++ b/src/checker/logger.rs @@ -0,0 +1,72 @@ +use std::cell::RefCell; + +use super::printer::{Printer, CLEAR_SCREEN}; + +pub struct Logger { + output: RefCell, +} + +impl Default for Logger { + fn default() -> Self { + Self::new() + } +} + +impl Logger { + #[must_use] + pub fn new() -> Self { + Self { + output: RefCell::new(String::new()), + } + } + + pub fn log(&self) -> String { + self.output.borrow().clone() + } +} + +impl Printer for Logger { + fn clear(&self) { + self.print(CLEAR_SCREEN); + } + + fn print(&self, output: &str) { + *self.output.borrow_mut() = format!("{}{}", self.output.borrow(), &output); + } + + fn eprint(&self, output: &str) { + *self.output.borrow_mut() = format!("{}{}", self.output.borrow(), &output); + } + + fn println(&self, output: &str) { + self.print(&format!("{}/n", &output)); + } + + fn eprintln(&self, output: &str) { + self.eprint(&format!("{}/n", &output)); + } +} + +#[cfg(test)] +mod tests { + use crate::checker::logger::Logger; + use crate::checker::printer::{Printer, CLEAR_SCREEN}; + + #[test] + fn should_capture_the_clear_screen_command() { + let console_logger = Logger::new(); + + console_logger.clear(); + + assert_eq!(CLEAR_SCREEN, console_logger.log()); + } + + #[test] + fn should_capture_the_print_command_output() { + let console_logger = Logger::new(); + + console_logger.print("OUTPUT"); + + assert_eq!("OUTPUT", console_logger.log()); + } +} diff --git a/src/checker/mod.rs b/src/checker/mod.rs new file mode 100644 index 000000000..6a55141d5 --- /dev/null +++ b/src/checker/mod.rs @@ -0,0 +1,6 @@ +pub mod app; +pub mod config; +pub mod console; +pub mod logger; +pub mod printer; +pub mod service; diff --git a/src/checker/printer.rs b/src/checker/printer.rs new file mode 100644 index 000000000..d590dfedb --- /dev/null +++ b/src/checker/printer.rs @@ -0,0 +1,9 @@ +pub const CLEAR_SCREEN: &str = "\x1B[2J\x1B[1;1H"; + +pub trait Printer { + fn clear(&self); + fn print(&self, output: &str); + fn eprint(&self, output: &str); + fn println(&self, output: &str); + fn eprintln(&self, output: &str); +} diff --git a/src/checker/service.rs b/src/checker/service.rs new file mode 100644 index 000000000..92902debd --- /dev/null +++ b/src/checker/service.rs @@ -0,0 +1,84 @@ +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use colored::Colorize; +use reqwest::{Client, Url}; + +use super::config::Configuration; +use super::console::Console; +use crate::checker::printer::Printer; + +pub struct Service { + pub(crate) config: Arc, + pub(crate) console: Console, +} + +impl Service { + pub async fn run_checks(&self) { + self.console.println("Running checks for trackers ..."); + self.check_udp_trackers(); + self.check_http_trackers(); + self.run_health_checks().await; + } + + fn check_udp_trackers(&self) { + self.console.println("UDP trackers ..."); + + for udp_tracker in &self.config.udp_trackers { + self.check_udp_tracker(udp_tracker); + } + } + + fn check_http_trackers(&self) { + self.console.println("HTTP trackers ..."); + + for http_tracker in &self.config.http_trackers { + self.check_http_tracker(http_tracker); + } + } + + async fn run_health_checks(&self) { + self.console.println("Health checks ..."); + + for health_check_url in &self.config.health_checks { + self.run_health_check(health_check_url.clone()).await; + } + } + + fn check_udp_tracker(&self, address: &SocketAddr) { + // todo: + // - Make announce request + // - Make scrape request + self.console + .println(&format!("{} - UDP tracker at {:?} is OK (TODO)", "✓".green(), address)); + } + + fn check_http_tracker(&self, url: &Url) { + // todo: + // - Make announce request + // - Make scrape request + self.console + .println(&format!("{} - HTTP tracker at {} is OK (TODO)", "✓".green(), url)); + } + + async fn run_health_check(&self, url: Url) { + let client = Client::builder().timeout(Duration::from_secs(5)).build().unwrap(); + + match client.get(url.clone()).send().await { + Ok(response) => { + if response.status().is_success() { + self.console + .println(&format!("{} - Health API at {} is OK", "✓".green(), url)); + } else { + self.console + .eprintln(&format!("{} - Health API at {} failing: {:?}", "✗".red(), url, response)); + } + } + Err(err) => { + self.console + .eprintln(&format!("{} - Health API at {} failing: {:?}", "✗".red(), url, err)); + } + } + } +} diff --git a/src/lib.rs b/src/lib.rs index c5f775646..7b5d453a4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -471,6 +471,7 @@ //! examples on the integration and unit tests. pub mod app; pub mod bootstrap; +pub mod checker; pub mod core; pub mod servers; pub mod shared; From 72c8348559f45f936266823d576f8d8798b32d66 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 24 Jan 2024 18:17:10 +0800 Subject: [PATCH 0191/1297] udp: handle udp requests concurrently --- .github/workflows/coverage.yaml | 3 + .vscode/settings.json | 6 + Cargo.lock | 10 + Cargo.toml | 1 + cSpell.json | 2 + src/servers/udp/handlers.rs | 16 +- src/servers/udp/mod.rs | 9 + src/servers/udp/server.rs | 215 ++++++++++++------- src/shared/bit_torrent/tracker/udp/client.rs | 2 + tests/servers/udp/contract.rs | 8 + tests/servers/udp/environment.rs | 20 +- 11 files changed, 207 insertions(+), 85 deletions(-) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 7f5bf2946..06529d53d 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -55,6 +55,9 @@ jobs: name: Run Build Checks run: cargo check --tests --benches --examples --workspace --all-targets --all-features + # Run Test Locally: + # RUSTFLAGS="-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests" RUSTDOCFLAGS="-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests" CARGO_INCREMENTAL="0" RUST_BACKTRACE=1 cargo test --tests --benches --examples --workspace --all-targets --all-features + - id: test name: Run Unit Tests run: cargo test --tests --benches --examples --workspace --all-targets --all-features diff --git a/.vscode/settings.json b/.vscode/settings.json index 038da4c18..701e89ccf 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,6 +2,12 @@ "[rust]": { "editor.formatOnSave": true }, + "[ignore]": { "rust-analyzer.cargo.extraEnv" : { + "RUSTFLAGS": "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests", + "RUSTDOCFLAGS": "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests", + "CARGO_INCREMENTAL": "0", + "RUST_BACKTRACE": "1" + }}, "rust-analyzer.checkOnSave": true, "rust-analyzer.check.command": "clippy", "rust-analyzer.check.allTargets": true, diff --git a/Cargo.lock b/Cargo.lock index 1f49aa986..63dfab1c7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2621,6 +2621,15 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "ringbuf" +version = "0.4.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b8f7d58e4f67752d63318605656be063e333154aa35b70126075e9d05552979" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "rkyv" version = "0.7.43" @@ -3448,6 +3457,7 @@ dependencies = [ "r2d2_sqlite", "rand", "reqwest", + "ringbuf", "serde", "serde_bencode", "serde_bytes", diff --git a/Cargo.toml b/Cargo.toml index 9b7e71905..6fd542c2f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,6 +56,7 @@ serde = { version = "1", features = ["derive"] } serde_bencode = "0" serde_bytes = "0" serde_json = "1" +ringbuf = "0.4.0-rc.2" serde_with = "3" serde_repr = "0" tdyne-peer-id = "1" diff --git a/cSpell.json b/cSpell.json index e02c6ed87..acd46284c 100644 --- a/cSpell.json +++ b/cSpell.json @@ -94,8 +94,10 @@ "reannounce", "Registar", "repr", + "reqs", "reqwest", "rerequests", + "ringbuf", "rngs", "routable", "rusqlite", diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index b77cd3a42..65e3f5b20 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -11,6 +11,7 @@ use log::{debug, info}; use torrust_tracker_located_error::DynError; use super::connection_cookie::{check, from_connection_id, into_connection_id, make}; +use super::UdpRequest; use crate::core::{statistics, ScrapeData, Tracker}; use crate::servers::udp::error::Error; use crate::servers::udp::peer_builder; @@ -27,10 +28,13 @@ use crate::shared::bit_torrent::info_hash::InfoHash; /// type. /// /// It will return an `Error` response if the request is invalid. -pub async fn handle_packet(remote_addr: SocketAddr, payload: Vec, tracker: &Tracker) -> Response { - match Request::from_bytes(&payload[..payload.len()], MAX_SCRAPE_TORRENTS).map_err(|e| Error::InternalServer { - message: format!("{e:?}"), - location: Location::caller(), +pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc) -> Response { + debug!("Handling Packets: {udp_request:?}"); + match Request::from_bytes(&udp_request.payload[..udp_request.payload.len()], MAX_SCRAPE_TORRENTS).map_err(|e| { + Error::InternalServer { + message: format!("{e:?}"), + location: Location::caller(), + } }) { Ok(request) => { let transaction_id = match &request { @@ -39,7 +43,7 @@ pub async fn handle_packet(remote_addr: SocketAddr, payload: Vec, tracker: & Request::Scrape(scrape_request) => scrape_request.transaction_id, }; - match handle_request(request, remote_addr, tracker).await { + match handle_request(request, udp_request.from, tracker).await { Ok(response) => response, Err(e) => handle_error(&e, transaction_id), } @@ -60,6 +64,8 @@ pub async fn handle_packet(remote_addr: SocketAddr, payload: Vec, tracker: & /// /// If a error happens in the `handle_request` function, it will just return the `ServerError`. pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: &Tracker) -> Result { + debug!("Handling Request: {request:?} to: {remote_addr:?}"); + match request { Request::Connect(connect_request) => handle_connect(remote_addr, &connect_request, tracker).await, Request::Announce(announce_request) => handle_announce(remote_addr, &announce_request, tracker).await, diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index 985c1cec7..3b22aeab5 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -638,6 +638,9 @@ //! documentation by [Arvid Norberg](https://github.com/arvidn) was very //! supportive in the development of this documentation. Some descriptions were //! taken from the [libtorrent](https://www.rasterbar.com/products/libtorrent/udp_tracker_protocol.html). + +use std::net::SocketAddr; + pub mod connection_cookie; pub mod error; pub mod handlers; @@ -652,3 +655,9 @@ pub type Port = u16; /// The transaction id. A random number generated byt the peer that is used to /// match requests and responses. pub type TransactionId = i64; + +#[derive(Clone, Debug)] +pub(crate) struct UdpRequest { + payload: Vec, + from: SocketAddr, +} diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 5a1977d01..0ab50d3bd 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -20,21 +20,24 @@ use std::io::Cursor; use std::net::SocketAddr; use std::sync::Arc; -use std::time::Duration; use aquatic_udp_protocol::Response; use derive_more::Constructor; -use futures::pin_mut; -use log::{debug, error, info}; +use log::{debug, error, info, trace}; +use ringbuf::storage::Static; +use ringbuf::traits::{Consumer, Observer, RingBuffer}; +use ringbuf::LocalRb; use tokio::net::UdpSocket; -use tokio::sync::oneshot::{Receiver, Sender}; -use tokio::task::JoinHandle; +use tokio::sync::oneshot; +use tokio::task::{AbortHandle, JoinHandle}; +use tokio::{select, task}; +use super::UdpRequest; use crate::bootstrap::jobs::Started; use crate::core::Tracker; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{shutdown_signal_with_message, Halted}; -use crate::servers::udp::handlers::handle_packet; +use crate::servers::udp::handlers; use crate::shared::bit_torrent::tracker::udp::client::check; use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; @@ -125,17 +128,8 @@ impl UdpServer { assert!(!tx_halt.is_closed(), "Halt channel for UDP tracker should be open"); - let launcher = self.state.launcher; - - let task = tokio::spawn(async move { - debug!(target: "UDP Tracker", "Launcher starting ..."); - - let starting = launcher.start(tracker, tx_start, rx_halt).await; - - starting.await.expect("UDP server should have started running"); - - launcher - }); + // May need to wrap in a task to about a tokio bug. + let task = self.state.launcher.start(tracker, tx_start, rx_halt); let binding = rx_start.await.expect("it should be able to start the service").address; @@ -150,6 +144,8 @@ impl UdpServer { }, }; + trace!("Running UDP Tracker on Socket: {}", running_udp_server.state.binding); + Ok(running_udp_server) } } @@ -182,7 +178,7 @@ impl UdpServer { } } -#[derive(Constructor, Debug)] +#[derive(Constructor, Copy, Clone, Debug)] pub struct Launcher { bind_to: SocketAddr, } @@ -193,8 +189,40 @@ impl Launcher { /// # Panics /// /// It would panic if unable to resolve the `local_addr` from the supplied ´socket´. - pub async fn start(&self, tracker: Arc, tx_start: Sender, rx_halt: Receiver) -> JoinHandle<()> { - Udp::start_with_graceful_shutdown(tracker, self.bind_to, tx_start, rx_halt).await + pub fn start( + &self, + tracker: Arc, + tx_start: oneshot::Sender, + rx_halt: oneshot::Receiver, + ) -> JoinHandle { + let launcher = Launcher::new(self.bind_to); + tokio::spawn(async move { + Udp::run_with_graceful_shutdown(tracker, launcher.bind_to, tx_start, rx_halt).await; + launcher + }) + } +} + +#[derive(Default)] +struct ActiveRequests { + rb: LocalRb>, // the number of requests we handle at the same time. +} + +impl std::fmt::Debug for ActiveRequests { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let (left, right) = &self.rb.as_slices(); + let dbg = format!("capacity: {}, left: {left:?}, right: {right:?}", &self.rb.capacity()); + f.debug_struct("ActiveRequests").field("rb", &dbg).finish() + } +} + +impl Drop for ActiveRequests { + fn drop(&mut self) { + for h in self.rb.pop_iter() { + if !h.is_finished() { + h.abort(); + } + } } } @@ -209,80 +237,103 @@ impl Udp { /// /// It panics if unable to bind to udp socket, and get the address from the udp socket. /// It also panics if unable to send address of socket. - async fn start_with_graceful_shutdown( + async fn run_with_graceful_shutdown( tracker: Arc, bind_to: SocketAddr, - tx_start: Sender, - rx_halt: Receiver, - ) -> JoinHandle<()> { + tx_start: oneshot::Sender, + rx_halt: oneshot::Receiver, + ) { let socket = Arc::new(UdpSocket::bind(bind_to).await.expect("Could not bind to {self.socket}.")); let address = socket.local_addr().expect("Could not get local_addr from {binding}."); + let halt = shutdown_signal_with_message(rx_halt, format!("Halting Http Service Bound to Socket: {address}")); info!(target: "UDP Tracker", "Starting on: udp://{}", address); let running = tokio::task::spawn(async move { - let halt = tokio::task::spawn(async move { - debug!(target: "UDP Tracker", "Waiting for halt signal for socket address: udp://{address} ..."); - - shutdown_signal_with_message( - rx_halt, - format!("Shutting down UDP server on socket address: udp://{address}"), - ) - .await; - }); - - let listen = async move { - debug!(target: "UDP Tracker", "Waiting for packets on socket address: udp://{address} ..."); - - loop { - let mut data = [0; MAX_PACKET_SIZE]; - let socket_clone = socket.clone(); - - match socket_clone.recv_from(&mut data).await { - Ok((valid_bytes, remote_addr)) => { - let payload = data[..valid_bytes].to_vec(); - - debug!(target: "UDP Tracker", "Received {} bytes", payload.len()); - debug!(target: "UDP Tracker", "From: {}", &remote_addr); - debug!(target: "UDP Tracker", "Payload: {:?}", payload); - - let response_fut = handle_packet(remote_addr, payload, &tracker); - - match tokio::time::timeout(Duration::from_secs(5), response_fut).await { - Ok(response) => { - Udp::send_response(socket_clone, remote_addr, response).await; - } - Err(_) => { - error!("Timeout occurred while processing the UDP request."); - } - } - } - Err(err) => { - error!("Error reading UDP datagram from socket. Error: {:?}", err); - } + debug!(target: "UDP Tracker", "Started: Waiting for packets on socket address: udp://{address} ..."); + + let tracker = tracker.clone(); + let socket = socket.clone(); + + let reqs = &mut ActiveRequests::default(); + + // Main Waiting Loop, awaits on async [`receive_request`]. + loop { + if let Some(h) = reqs.rb.push_overwrite( + Self::do_request(Self::receive_request(socket.clone()).await, tracker.clone(), socket.clone()).abort_handle(), + ) { + if !h.is_finished() { + // the task is still running, lets yield and give it a chance to flush. + tokio::task::yield_now().await; + h.abort(); } } - }; + } + }); + + tx_start + .send(Started { address }) + .expect("the UDP Tracker service should not be dropped"); + + debug!(target: "UDP Tracker", "Started on: udp://{}", address); - pin_mut!(halt); - pin_mut!(listen); + let stop = running.abort_handle(); - tx_start - .send(Started { address }) - .expect("the UDP Tracker service should not be dropped"); + select! { + _ = running => { debug!(target: "UDP Tracker", "Socket listener stopped on address: udp://{address}"); }, + () = halt => { debug!(target: "UDP Tracker", "Halt signal spawned task stopped on address: udp://{address}"); } + } + stop.abort(); + + task::yield_now().await; // lets allow the other threads to complete. + } - tokio::select! { - _ = & mut halt => { debug!(target: "UDP Tracker", "Halt signal spawned task stopped on address: udp://{address}"); }, - () = & mut listen => { debug!(target: "UDP Tracker", "Socket listener stopped on address: udp://{address}"); }, + async fn receive_request(socket: Arc) -> Result> { + // Wait for the socket to be readable + socket.readable().await?; + + let mut buf = Vec::with_capacity(MAX_PACKET_SIZE); + + match socket.recv_buf_from(&mut buf).await { + Ok((n, from)) => { + Vec::truncate(&mut buf, n); + trace!("GOT {buf:?}"); + Ok(UdpRequest { payload: buf, from }) } - }); - info!(target: "UDP Tracker", "Started on: udp://{}", address); + Err(e) => Err(Box::new(e)), + } + } - running + fn do_request( + result: Result>, + tracker: Arc, + socket: Arc, + ) -> JoinHandle<()> { + // timeout not needed, as udp is non-blocking. + tokio::task::spawn(async move { + match result { + Ok(udp_request) => { + trace!("Received Request from: {}", udp_request.from); + Self::make_response(tracker.clone(), socket.clone(), udp_request).await; + } + Err(error) => { + debug!("error: {error}"); + } + } + }) } - async fn send_response(socket: Arc, remote_addr: SocketAddr, response: Response) { + async fn make_response(tracker: Arc, socket: Arc, udp_request: UdpRequest) { + trace!("Making Response to {udp_request:?}"); + let from = udp_request.from; + let response = handlers::handle_packet(udp_request, &tracker.clone()).await; + Self::send_response(&socket.clone(), from, response).await; + } + + async fn send_response(socket: &Arc, to: SocketAddr, response: Response) { + trace!("Sending Response: {response:?} to: {to:?}"); + let buffer = vec![0u8; MAX_PACKET_SIZE]; let mut cursor = Cursor::new(buffer); @@ -293,10 +344,10 @@ impl Udp { let inner = cursor.get_ref(); debug!("Sending {} bytes ...", &inner[..position].len()); - debug!("To: {:?}", &remote_addr); + debug!("To: {:?}", &to); debug!("Payload: {:?}", &inner[..position]); - Udp::send_packet(socket, &remote_addr, &inner[..position]).await; + Self::send_packet(socket, &to, &inner[..position]).await; debug!("{} bytes sent", &inner[..position].len()); } @@ -306,7 +357,9 @@ impl Udp { } } - async fn send_packet(socket: Arc, remote_addr: &SocketAddr, payload: &[u8]) { + async fn send_packet(socket: &Arc, remote_addr: &SocketAddr, payload: &[u8]) { + trace!("Sending Packets: {payload:?} to: {remote_addr:?}"); + // doesn't matter if it reaches or not drop(socket.send_to(payload, remote_addr).await); } @@ -324,7 +377,9 @@ impl Udp { #[cfg(test)] mod tests { use std::sync::Arc; + use std::time::Duration; + use tokio::time::sleep; use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; use crate::bootstrap::app::initialize_with_configuration; @@ -351,6 +406,8 @@ mod tests { .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); + sleep(Duration::from_secs(1)).await; + assert_eq!(stopped.state.launcher.bind_to, bind_to); } } diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs index 959001e82..23b718472 100644 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -143,6 +143,8 @@ pub async fn new_udp_tracker_client_connected(remote_address: &str) -> UdpTracke /// /// # Panics pub async fn check(binding: &SocketAddr) -> Result { + debug!("Checking Service (detail): {binding:?}."); + let client = new_udp_tracker_client_connected(binding.to_string().as_str()).await; let connect_request = ConnectRequest { diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 0eea650b8..91dca4d42 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -47,6 +47,8 @@ async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_req let response = Response::from_bytes(&buffer, true).unwrap(); assert!(is_error_response(&response, "bad request")); + + env.stop().await; } mod receiving_a_connection_request { @@ -72,6 +74,8 @@ mod receiving_a_connection_request { let response = client.receive().await; assert!(is_connect_response(&response, TransactionId(123))); + + env.stop().await; } } @@ -121,6 +125,8 @@ mod receiving_an_announce_request { println!("test response {response:?}"); assert!(is_ipv4_announce_response(&response)); + + env.stop().await; } } @@ -158,5 +164,7 @@ mod receiving_an_scrape_request { let response = client.receive().await; assert!(is_scrape_response(&response)); + + env.stop().await; } } diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 26a47987e..da7705016 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -68,7 +68,7 @@ impl Environment { config: self.config, tracker: self.tracker, registar: Registar::default(), - server: self.server.stop().await.unwrap(), + server: self.server.stop().await.expect("it stop the udp tracker service"), } } @@ -76,3 +76,21 @@ impl Environment { self.server.state.binding } } + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use tokio::time::sleep; + use torrust_tracker_test_helpers::configuration; + + use crate::servers::udp::Started; + + #[tokio::test] + async fn it_should_make_and_stop_udp_server() { + let env = Started::new(&configuration::ephemeral().into()).await; + sleep(Duration::from_secs(1)).await; + env.stop().await; + sleep(Duration::from_secs(1)).await; + } +} From 8e432057634718bf9e8efbfc7abb4f36f28a26e0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 24 Jan 2024 17:13:18 +0000 Subject: [PATCH 0192/1297] ci: [#634] new dependency to make temp dirs It will be used to store temp files during CI scripts execution. --- Cargo.lock | 1 + Cargo.toml | 1 + cSpell.json | 1 + 3 files changed, 3 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 63dfab1c7..ab270d0cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3467,6 +3467,7 @@ dependencies = [ "serde_with", "tdyne-peer-id", "tdyne-peer-id-registry", + "tempfile", "thiserror", "tokio", "torrust-tracker-configuration", diff --git a/Cargo.toml b/Cargo.toml index 6fd542c2f..3a11786f5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -71,6 +71,7 @@ tower-http = { version = "0", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } colored = "2.1.0" url = "2.5.0" +tempfile = "3.9.0" [dev-dependencies] criterion = { version = "0.5.1", features = ["async_tokio"] } diff --git a/cSpell.json b/cSpell.json index acd46284c..0a3f78fad 100644 --- a/cSpell.json +++ b/cSpell.json @@ -116,6 +116,7 @@ "Swatinem", "Swiftbit", "taiki", + "tempfile", "thiserror", "tlsv", "Torrentstorm", From 4edcd2efb262aad2c6f246c325c0ff6a0792d3fe Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 24 Jan 2024 17:14:49 +0000 Subject: [PATCH 0193/1297] ci: [#634] new script to run E2E tests It uses Rust instead of Bash. You can run it with: ``` cargo run --bin e2e_tests_runner share/default/config/tracker.e2e.container.sqlite3.toml ``` It will: - Build the tracker docker image. - Run the docker image. - Wait until the container is healthy. - Parse logs to get running services. - Build config file for the tracker_checker. - Run the tracker_checker. - Stop the container. --- .../config/tracker.e2e.container.sqlite3.toml | 41 ++++ src/bin/e2e_tests_runner.rs | 10 + src/e2e/docker.rs | 177 +++++++++++++++ src/e2e/logs_parser.rs | 114 ++++++++++ src/e2e/mod.rs | 4 + src/e2e/runner.rs | 214 ++++++++++++++++++ src/e2e/temp_dir.rs | 53 +++++ src/lib.rs | 1 + 8 files changed, 614 insertions(+) create mode 100644 share/default/config/tracker.e2e.container.sqlite3.toml create mode 100644 src/bin/e2e_tests_runner.rs create mode 100644 src/e2e/docker.rs create mode 100644 src/e2e/logs_parser.rs create mode 100644 src/e2e/mod.rs create mode 100644 src/e2e/runner.rs create mode 100644 src/e2e/temp_dir.rs diff --git a/share/default/config/tracker.e2e.container.sqlite3.toml b/share/default/config/tracker.e2e.container.sqlite3.toml new file mode 100644 index 000000000..86ffb3ffd --- /dev/null +++ b/share/default/config/tracker.e2e.container.sqlite3.toml @@ -0,0 +1,41 @@ +announce_interval = 120 +db_driver = "Sqlite3" +db_path = "/var/lib/torrust/tracker/database/sqlite3.db" +external_ip = "0.0.0.0" +inactive_peer_cleanup_interval = 600 +log_level = "info" +max_peer_timeout = 900 +min_announce_interval = 120 +mode = "public" +on_reverse_proxy = false +persistent_torrent_completed_stat = false +remove_peerless_torrents = true +tracker_usage_statistics = true + +[[udp_trackers]] +bind_address = "0.0.0.0:6969" +enabled = true + +[[http_trackers]] +bind_address = "0.0.0.0:7070" +enabled = true +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_enabled = false +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + +[http_api] +bind_address = "0.0.0.0:1212" +enabled = true +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_enabled = false +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + +# Please override the admin token setting the +# `TORRUST_TRACKER_API_ADMIN_TOKEN` +# environmental variable! + +[http_api.access_tokens] +admin = "MyAccessToken" + +[health_check_api] +bind_address = "0.0.0.0:1313" diff --git a/src/bin/e2e_tests_runner.rs b/src/bin/e2e_tests_runner.rs new file mode 100644 index 000000000..35368b612 --- /dev/null +++ b/src/bin/e2e_tests_runner.rs @@ -0,0 +1,10 @@ +//! Program to run E2E tests. +//! +//! ```text +//! cargo run --bin e2e_tests_runner share/default/config/tracker.e2e.container.sqlite3.toml +//! ``` +use torrust_tracker::e2e; + +fn main() { + e2e::runner::run(); +} diff --git a/src/e2e/docker.rs b/src/e2e/docker.rs new file mode 100644 index 000000000..419e6138a --- /dev/null +++ b/src/e2e/docker.rs @@ -0,0 +1,177 @@ +//! Docker command wrapper. +use std::io; +use std::process::{Command, Output}; +use std::thread::sleep; +use std::time::{Duration, Instant}; + +use log::debug; + +/// Docker command wrapper. +pub struct Docker {} + +pub struct RunningContainer { + pub name: String, + pub output: Output, +} + +impl Drop for RunningContainer { + /// Ensures that the temporary container is stopped and removed when the + /// struct goes out of scope. + fn drop(&mut self) { + let _unused = Docker::stop(self); + let _unused = Docker::remove(&self.name); + } +} + +impl Docker { + /// Builds a Docker image from a given Dockerfile. + /// + /// # Errors + /// + /// Will fail if the docker build command fails. + pub fn build(dockerfile: &str, tag: &str) -> io::Result<()> { + let status = Command::new("docker") + .args(["build", "-f", dockerfile, "-t", tag, "."]) + .status()?; + + if status.success() { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("Failed to build Docker image from dockerfile {dockerfile}"), + )) + } + } + + /// Runs a Docker container from a given image with multiple environment variables. + /// + /// # Arguments + /// + /// * `image` - The Docker image to run. + /// * `container` - The name for the Docker container. + /// * `env_vars` - A slice of tuples, each representing an environment variable as ("KEY", "value"). + /// + /// # Errors + /// + /// Will fail if the docker run command fails. + pub fn run(image: &str, container: &str, env_vars: &[(String, String)], ports: &[String]) -> io::Result { + let initial_args = vec![ + "run".to_string(), + "--detach".to_string(), + "--name".to_string(), + container.to_string(), + ]; + + // Add environment variables + let mut env_var_args: Vec = vec![]; + for (key, value) in env_vars { + env_var_args.push("--env".to_string()); + env_var_args.push(format!("{key}={value}")); + } + + // Add port mappings + let mut port_args: Vec = vec![]; + for port in ports { + port_args.push("--publish".to_string()); + port_args.push(port.to_string()); + } + + let args = [initial_args, env_var_args, port_args, [image.to_string()].to_vec()].concat(); + + debug!("Docker run args: {:?}", args); + + let output = Command::new("docker").args(args).output()?; + + if output.status.success() { + Ok(RunningContainer { + name: container.to_owned(), + output, + }) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("Failed to run Docker image {image}"), + )) + } + } + + /// Stops a Docker container. + /// + /// # Errors + /// + /// Will fail if the docker stop command fails. + pub fn stop(container: &RunningContainer) -> io::Result<()> { + let status = Command::new("docker").args(["stop", &container.name]).status()?; + + if status.success() { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("Failed to stop Docker container {}", container.name), + )) + } + } + + /// Removes a Docker container. + /// + /// # Errors + /// + /// Will fail if the docker rm command fails. + pub fn remove(container: &str) -> io::Result<()> { + let status = Command::new("docker").args(["rm", "-f", container]).status()?; + + if status.success() { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("Failed to remove Docker container {container}"), + )) + } + } + + /// Fetches logs from a Docker container. + /// + /// # Errors + /// + /// Will fail if the docker logs command fails. + pub fn logs(container: &str) -> io::Result { + let output = Command::new("docker").args(["logs", container]).output()?; + + if output.status.success() { + Ok(String::from_utf8_lossy(&output.stdout).to_string()) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("Failed to fetch logs from Docker container {container}"), + )) + } + } + + /// Checks if a Docker container is healthy. + #[must_use] + pub fn wait_until_is_healthy(name: &str, timeout: Duration) -> bool { + let start = Instant::now(); + + while start.elapsed() < timeout { + let Ok(output) = Command::new("docker") + .args(["ps", "-f", &format!("name={name}"), "--format", "{{.Status}}"]) + .output() + else { + return false; + }; + + let output_str = String::from_utf8_lossy(&output.stdout); + + if output_str.contains("(healthy)") { + return true; + } + + sleep(Duration::from_secs(1)); + } + + false + } +} diff --git a/src/e2e/logs_parser.rs b/src/e2e/logs_parser.rs new file mode 100644 index 000000000..1d6baa23e --- /dev/null +++ b/src/e2e/logs_parser.rs @@ -0,0 +1,114 @@ +//! Utilities to parse Torrust Tracker logs. +use serde::{Deserialize, Serialize}; + +const UDP_TRACKER_PATTERN: &str = "[UDP Tracker][INFO] Starting on: udp://"; +const HTTP_TRACKER_PATTERN: &str = "[HTTP Tracker][INFO] Starting on: "; +const HEALTH_CHECK_PATTERN: &str = "[Health Check API][INFO] Starting on: "; + +#[derive(Serialize, Deserialize, Debug, Default)] +pub struct RunningServices { + pub udp_trackers: Vec, + pub http_trackers: Vec, + pub health_checks: Vec, +} + +impl RunningServices { + /// It parses the tracker logs to extract the running services. + /// + /// For example, from this logs: + /// + /// ```text + /// Loading default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... + /// 2024-01-24T16:36:14.614898789+00:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized. + /// 2024-01-24T16:36:14.615586025+00:00 [UDP Tracker][INFO] Starting on: udp://0.0.0.0:6969 + /// 2024-01-24T16:36:14.615623705+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled + /// 2024-01-24T16:36:14.615694484+00:00 [HTTP Tracker][INFO] Starting on: http://0.0.0.0:7070 + /// 2024-01-24T16:36:14.615710534+00:00 [HTTP Tracker][INFO] Started on: http://0.0.0.0:7070 + /// 2024-01-24T16:36:14.615716574+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled + /// 2024-01-24T16:36:14.615764904+00:00 [API][INFO] Starting on http://127.0.0.1:1212 + /// 2024-01-24T16:36:14.615767264+00:00 [API][INFO] Started on http://127.0.0.1:1212 + /// 2024-01-24T16:36:14.615777574+00:00 [Health Check API][INFO] Starting on: http://127.0.0.1:1313 + /// 2024-01-24T16:36:14.615791124+00:00 [Health Check API][INFO] Started on: http://127.0.0.1:1313 + /// ``` + /// + /// It would extract these services: + /// + /// ```json + /// { + /// "udp_trackers": [ + /// "127.0.0.1:6969" + /// ], + /// "http_trackers": [ + /// "http://127.0.0.1:7070" + /// ], + /// "health_checks": [ + /// "http://127.0.0.1:1313/health_check" + /// ] + /// } + /// ``` + #[must_use] + pub fn parse_from_logs(logs: &str) -> Self { + let mut udp_trackers: Vec = Vec::new(); + let mut http_trackers: Vec = Vec::new(); + let mut health_checks: Vec = Vec::new(); + + for line in logs.lines() { + if let Some(address) = Self::extract_address_if_matches(line, UDP_TRACKER_PATTERN) { + udp_trackers.push(address); + } else if let Some(address) = Self::extract_address_if_matches(line, HTTP_TRACKER_PATTERN) { + http_trackers.push(address); + } else if let Some(address) = Self::extract_address_if_matches(line, HEALTH_CHECK_PATTERN) { + health_checks.push(format!("{address}/health_check")); + } + } + + Self { + udp_trackers, + http_trackers, + health_checks, + } + } + + fn extract_address_if_matches(line: &str, pattern: &str) -> Option { + line.find(pattern) + .map(|start| Self::replace_wildcard_ip_with_localhost(line[start + pattern.len()..].trim())) + } + + fn replace_wildcard_ip_with_localhost(address: &str) -> String { + address.replace("0.0.0.0", "127.0.0.1") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_should_parse_from_logs_with_valid_logs() { + let logs = "\ + [UDP Tracker][INFO] Starting on: udp://0.0.0.0:8080\n\ + [HTTP Tracker][INFO] Starting on: 0.0.0.0:9090\n\ + [Health Check API][INFO] Starting on: 0.0.0.0:10010"; + let running_services = RunningServices::parse_from_logs(logs); + + assert_eq!(running_services.udp_trackers, vec!["127.0.0.1:8080"]); + assert_eq!(running_services.http_trackers, vec!["127.0.0.1:9090"]); + assert_eq!(running_services.health_checks, vec!["127.0.0.1:10010/health_check"]); + } + + #[test] + fn it_should_ignore_logs_with_no_matching_lines() { + let logs = "[Other Service][INFO] Starting on: 0.0.0.0:7070"; + let running_services = RunningServices::parse_from_logs(logs); + + assert!(running_services.udp_trackers.is_empty()); + assert!(running_services.http_trackers.is_empty()); + assert!(running_services.health_checks.is_empty()); + } + + #[test] + fn it_should_replace_wildcard_ip_with_localhost() { + let address = "0.0.0.0:8080"; + assert_eq!(RunningServices::replace_wildcard_ip_with_localhost(address), "127.0.0.1:8080"); + } +} diff --git a/src/e2e/mod.rs b/src/e2e/mod.rs new file mode 100644 index 000000000..6745d49cd --- /dev/null +++ b/src/e2e/mod.rs @@ -0,0 +1,4 @@ +pub mod docker; +pub mod logs_parser; +pub mod runner; +pub mod temp_dir; diff --git a/src/e2e/runner.rs b/src/e2e/runner.rs new file mode 100644 index 000000000..eee2805a6 --- /dev/null +++ b/src/e2e/runner.rs @@ -0,0 +1,214 @@ +use std::fs::File; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::Duration; +use std::{env, io}; + +use log::{debug, info, LevelFilter}; +use rand::distributions::Alphanumeric; +use rand::Rng; + +use super::docker::RunningContainer; +use crate::e2e::docker::Docker; +use crate::e2e::logs_parser::RunningServices; +use crate::e2e::temp_dir::Handler; + +pub const NUMBER_OF_ARGUMENTS: usize = 2; +const CONTAINER_TAG: &str = "torrust-tracker:local"; +const TRACKER_CHECKER_CONFIG_FILE: &str = "tracker_checker.json"; + +pub struct Arguments { + pub tracker_config_path: String, +} + +/// Script to run E2E tests. +/// +/// # Panics +/// +/// Will panic if it can't not perform any of the operations. +pub fn run() { + setup_runner_logging(LevelFilter::Info); + + let args = parse_arguments(); + + let tracker_config = load_tracker_configuration(&args.tracker_config_path); + + build_tracker_container_image(CONTAINER_TAG); + + let temp_dir = create_temp_dir(); + + let container_name = generate_random_container_name("tracker_"); + + // code-review: if we want to use port 0 we don't know which ports we have to open. + // Besides, if we don't use port 0 we should get the port numbers from the tracker configuration. + // We could not use docker, but the intention was to create E2E tests including containerization. + let env_vars = [("TORRUST_TRACKER_CONFIG".to_string(), tracker_config.to_string())]; + let ports = [ + "6969:6969/udp".to_string(), + "7070:7070/tcp".to_string(), + "1212:1212/tcp".to_string(), + "1313:1313/tcp".to_string(), + ]; + + let container = run_tracker_container(&container_name, &env_vars, &ports); + + let running_services = parse_running_services_from_logs(&container); + + let tracker_checker_config = + serde_json::to_string_pretty(&running_services).expect("Running services should be serialized into JSON"); + + let mut tracker_checker_config_path = PathBuf::from(&temp_dir.temp_dir.path()); + tracker_checker_config_path.push(TRACKER_CHECKER_CONFIG_FILE); + + write_tracker_checker_config_file(&tracker_checker_config_path, &tracker_checker_config); + + run_tracker_checker(&tracker_checker_config_path).expect("Tracker checker should check running services"); + + // More E2E tests could be executed here in the future. For example: `cargo test ...`. + + info!("Running container `{}` will be automatically removed", container.name); +} + +fn setup_runner_logging(level: LevelFilter) { + if let Err(_err) = fern::Dispatch::new() + .format(|out, message, record| { + out.finish(format_args!( + "{} [{}][{}] {}", + chrono::Local::now().format("%+"), + record.target(), + record.level(), + message + )); + }) + .level(level) + .chain(std::io::stdout()) + .apply() + { + panic!("Failed to initialize logging.") + } + + debug!("logging initialized."); +} + +fn parse_arguments() -> Arguments { + let args: Vec = std::env::args().collect(); + + if args.len() < NUMBER_OF_ARGUMENTS { + eprintln!("Usage: cargo run --bin e2e_tests_runner "); + eprintln!("For example: cargo run --bin e2e_tests_runner ./share/default/config/tracker.e2e.container.sqlite3.toml"); + std::process::exit(1); + } + + let config_path = &args[1]; + + Arguments { + tracker_config_path: config_path.to_string(), + } +} + +fn load_tracker_configuration(tracker_config_path: &str) -> String { + info!("Reading tracker configuration from file: {} ...", tracker_config_path); + read_file(tracker_config_path) +} + +fn read_file(path: &str) -> String { + std::fs::read_to_string(path).unwrap_or_else(|_| panic!("Can't read file {path}")) +} + +fn build_tracker_container_image(tag: &str) { + info!("Building tracker container image with tag: {} ...", tag); + Docker::build("./Containerfile", tag).expect("A tracker local docker image should be built"); +} + +fn create_temp_dir() -> Handler { + debug!( + "Current dir: {:?}", + env::current_dir().expect("It should return the current dir") + ); + + let temp_dir_handler = Handler::new().expect("A temp dir should be created"); + + info!("Temp dir created: {:?}", temp_dir_handler.temp_dir); + + temp_dir_handler +} + +fn generate_random_container_name(prefix: &str) -> String { + let rand_string: String = rand::thread_rng() + .sample_iter(&Alphanumeric) + .take(20) + .map(char::from) + .collect(); + + format!("{prefix}{rand_string}") +} + +fn run_tracker_container(container_name: &str, env_vars: &[(String, String)], ports: &[String]) -> RunningContainer { + info!("Running docker tracker image: {container_name} ..."); + + let container = + Docker::run(CONTAINER_TAG, container_name, env_vars, ports).expect("A tracker local docker image should be running"); + + info!("Waiting for the container {container_name} to be healthy ..."); + + let is_healthy = Docker::wait_until_is_healthy(container_name, Duration::from_secs(10)); + + assert!(is_healthy, "Unhealthy tracker container: {container_name}"); + + debug!("Container {container_name} is healthy ..."); + + container +} + +fn parse_running_services_from_logs(container: &RunningContainer) -> RunningServices { + let logs = Docker::logs(&container.name).expect("Logs should be captured from running container"); + + debug!("Logs after starting the container:\n{logs}"); + + RunningServices::parse_from_logs(&logs) +} + +fn write_tracker_checker_config_file(config_file_path: &Path, config: &str) { + let mut file = File::create(config_file_path).expect("Tracker checker config file to be created"); + + file.write_all(config.as_bytes()) + .expect("Tracker checker config file to be written"); + + info!("Tracker checker configuration file: {:?} \n{config}", config_file_path); +} + +/// Runs the tracker checker +/// +/// ```text +/// cargo run --bin tracker_checker "./share/default/config/tracker_checker.json" +/// ``` +/// +/// # Errors +/// +/// Will return an error if the tracker checker fails. +/// +/// # Panics +/// +/// Will panic if the config path is not a valid string. +pub fn run_tracker_checker(config_path: &Path) -> io::Result<()> { + info!( + "Running tacker checker: cargo --bin tracker_checker {}", + config_path.display() + ); + + let path = config_path.to_str().expect("The path should be a valid string"); + + let status = Command::new("cargo") + .args(["run", "--bin", "tracker_checker", path]) + .status()?; + + if status.success() { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::Other, + format!("Failed to run tracker checker with config file {path}"), + )) + } +} diff --git a/src/e2e/temp_dir.rs b/src/e2e/temp_dir.rs new file mode 100644 index 000000000..8433e3059 --- /dev/null +++ b/src/e2e/temp_dir.rs @@ -0,0 +1,53 @@ +//! Temp dir which is automatically removed when it goes out of scope. +use std::path::PathBuf; +use std::{env, io}; + +use tempfile::TempDir; + +pub struct Handler { + pub temp_dir: TempDir, + pub original_dir: PathBuf, +} + +impl Handler { + /// Creates a new temporary directory and remembers the current working directory. + /// + /// # Errors + /// + /// Will error if: + /// + /// - It can't create the temp dir. + /// - It can't get the current dir. + pub fn new() -> io::Result { + let temp_dir = TempDir::new()?; + let original_dir = env::current_dir()?; + + Ok(Handler { temp_dir, original_dir }) + } + + /// Changes the current working directory to the temporary directory. + /// + /// # Errors + /// + /// Will error if it can't change the current di to the temp dir. + pub fn change_to_temp_dir(&self) -> io::Result<()> { + env::set_current_dir(self.temp_dir.path()) + } + + /// Changes the current working directory back to the original directory. + /// + /// # Errors + /// + /// Will error if it can't revert the current dir to the original one. + pub fn revert_to_original_dir(&self) -> io::Result<()> { + env::set_current_dir(&self.original_dir) + } +} + +impl Drop for Handler { + /// Ensures that the temporary directory is deleted when the struct goes out of scope. + fn drop(&mut self) { + // The temporary directory is automatically deleted when `TempDir` is dropped. + // We can add additional cleanup here if necessary. + } +} diff --git a/src/lib.rs b/src/lib.rs index 7b5d453a4..f239039bd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -473,6 +473,7 @@ pub mod app; pub mod bootstrap; pub mod checker; pub mod core; +pub mod e2e; pub mod servers; pub mod shared; From ec13fb41cfef0d68af67b44aee8c83696754a519 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 24 Jan 2024 17:17:24 +0000 Subject: [PATCH 0194/1297] ci: [#634] run E2E tests in the testing workflow --- .github/workflows/testing.yaml | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 02dbb1804..5deabd74a 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -110,3 +110,32 @@ jobs: - id: test name: Run Unit Tests run: cargo test --tests --benches --examples --workspace --all-targets --all-features + + e2e: + name: E2E + runs-on: ubuntu-latest + needs: unit + + strategy: + matrix: + toolchain: [nightly] + + steps: + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + components: llvm-tools-preview + + - id: cache + name: Enable Job Cache + uses: Swatinem/rust-cache@v2 + + - id: checkout + name: Checkout Repository + uses: actions/checkout@v4 + + - id: test + name: Run E2E Tests + run: cargo run --bin e2e_tests_runner ./share/default/config/tracker.e2e.container.sqlite3.toml From 0afab09333ce75ca4bd0a65020b77360390929b1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 26 Jan 2024 10:28:14 +0000 Subject: [PATCH 0195/1297] refactor: [#647] extract strcut RunOptions --- src/e2e/docker.rs | 12 +++++++++--- src/e2e/runner.rs | 27 ++++++++++++++------------- 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/src/e2e/docker.rs b/src/e2e/docker.rs index 419e6138a..75c67d64b 100644 --- a/src/e2e/docker.rs +++ b/src/e2e/docker.rs @@ -23,6 +23,12 @@ impl Drop for RunningContainer { } } +/// `docker run` command options. +pub struct RunOptions { + pub env_vars: Vec<(String, String)>, + pub ports: Vec, +} + impl Docker { /// Builds a Docker image from a given Dockerfile. /// @@ -55,7 +61,7 @@ impl Docker { /// # Errors /// /// Will fail if the docker run command fails. - pub fn run(image: &str, container: &str, env_vars: &[(String, String)], ports: &[String]) -> io::Result { + pub fn run(image: &str, container: &str, options: &RunOptions) -> io::Result { let initial_args = vec![ "run".to_string(), "--detach".to_string(), @@ -65,14 +71,14 @@ impl Docker { // Add environment variables let mut env_var_args: Vec = vec![]; - for (key, value) in env_vars { + for (key, value) in &options.env_vars { env_var_args.push("--env".to_string()); env_var_args.push(format!("{key}={value}")); } // Add port mappings let mut port_args: Vec = vec![]; - for port in ports { + for port in &options.ports { port_args.push("--publish".to_string()); port_args.push(port.to_string()); } diff --git a/src/e2e/runner.rs b/src/e2e/runner.rs index eee2805a6..a59659891 100644 --- a/src/e2e/runner.rs +++ b/src/e2e/runner.rs @@ -10,7 +10,7 @@ use rand::distributions::Alphanumeric; use rand::Rng; use super::docker::RunningContainer; -use crate::e2e::docker::Docker; +use crate::e2e::docker::{Docker, RunOptions}; use crate::e2e::logs_parser::RunningServices; use crate::e2e::temp_dir::Handler; @@ -43,15 +43,17 @@ pub fn run() { // code-review: if we want to use port 0 we don't know which ports we have to open. // Besides, if we don't use port 0 we should get the port numbers from the tracker configuration. // We could not use docker, but the intention was to create E2E tests including containerization. - let env_vars = [("TORRUST_TRACKER_CONFIG".to_string(), tracker_config.to_string())]; - let ports = [ - "6969:6969/udp".to_string(), - "7070:7070/tcp".to_string(), - "1212:1212/tcp".to_string(), - "1313:1313/tcp".to_string(), - ]; - - let container = run_tracker_container(&container_name, &env_vars, &ports); + let options = RunOptions { + env_vars: vec![("TORRUST_TRACKER_CONFIG".to_string(), tracker_config.to_string())], + ports: vec![ + "6969:6969/udp".to_string(), + "7070:7070/tcp".to_string(), + "1212:1212/tcp".to_string(), + "1313:1313/tcp".to_string(), + ], + }; + + let container = run_tracker_container(CONTAINER_TAG, &container_name, &options); let running_services = parse_running_services_from_logs(&container); @@ -144,11 +146,10 @@ fn generate_random_container_name(prefix: &str) -> String { format!("{prefix}{rand_string}") } -fn run_tracker_container(container_name: &str, env_vars: &[(String, String)], ports: &[String]) -> RunningContainer { +fn run_tracker_container(image: &str, container_name: &str, options: &RunOptions) -> RunningContainer { info!("Running docker tracker image: {container_name} ..."); - let container = - Docker::run(CONTAINER_TAG, container_name, env_vars, ports).expect("A tracker local docker image should be running"); + let container = Docker::run(image, container_name, options).expect("A tracker local docker image should be running"); info!("Waiting for the container {container_name} to be healthy ..."); From 670927c1c57b9381c90082af9856dfa11aba93ad Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 26 Jan 2024 10:35:10 +0000 Subject: [PATCH 0196/1297] ci: [#647] E2E tests. Make sure we run at least one service per type We want to run all services in the E2E tests env. At least one running service per type: - HTTP tracker - UDP tracker - HealthCheck endpoint --- src/e2e/runner.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/e2e/runner.rs b/src/e2e/runner.rs index a59659891..058ebed40 100644 --- a/src/e2e/runner.rs +++ b/src/e2e/runner.rs @@ -57,6 +57,8 @@ pub fn run() { let running_services = parse_running_services_from_logs(&container); + assert_there_is_at_least_one_service_per_type(&running_services); + let tracker_checker_config = serde_json::to_string_pretty(&running_services).expect("Running services should be serialized into JSON"); @@ -170,6 +172,21 @@ fn parse_running_services_from_logs(container: &RunningContainer) -> RunningServ RunningServices::parse_from_logs(&logs) } +fn assert_there_is_at_least_one_service_per_type(running_services: &RunningServices) { + assert!( + !running_services.udp_trackers.is_empty(), + "At least one UDP tracker should be enabled in E2E tests configuration" + ); + assert!( + !running_services.http_trackers.is_empty(), + "At least one HTTP tracker should be enabled in E2E tests configuration" + ); + assert!( + !running_services.health_checks.is_empty(), + "At least one Health Check should be enabled in E2E tests configuration" + ); +} + fn write_tracker_checker_config_file(config_file_path: &Path, config: &str) { let mut file = File::create(config_file_path).expect("Tracker checker config file to be created"); From ddad4a432b0602067f9d7a227d3e82e5398f8baf Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 26 Jan 2024 11:05:54 +0000 Subject: [PATCH 0197/1297] ci: [#647] E2E tests. Make sure there are not panics in logs --- src/e2e/docker.rs | 54 +++++++++++++++++++++++++++++++++++++++++++++-- src/e2e/runner.rs | 32 ++++++++++++++++++++++++++-- 2 files changed, 82 insertions(+), 4 deletions(-) diff --git a/src/e2e/docker.rs b/src/e2e/docker.rs index 75c67d64b..6eb64783a 100644 --- a/src/e2e/docker.rs +++ b/src/e2e/docker.rs @@ -18,8 +18,12 @@ impl Drop for RunningContainer { /// Ensures that the temporary container is stopped and removed when the /// struct goes out of scope. fn drop(&mut self) { - let _unused = Docker::stop(self); - let _unused = Docker::remove(&self.name); + if Docker::is_container_running(&self.name) { + let _unused = Docker::stop(self); + } + if Docker::container_exist(&self.name) { + let _unused = Docker::remove(&self.name); + } } } @@ -180,4 +184,50 @@ impl Docker { false } + + /// Checks if a Docker container is running. + /// + /// # Arguments + /// + /// * `container` - The name of the Docker container. + /// + /// # Returns + /// + /// `true` if the container is running, `false` otherwise. + #[must_use] + pub fn is_container_running(container: &str) -> bool { + match Command::new("docker") + .args(["ps", "-f", &format!("name={container}"), "--format", "{{.Names}}"]) + .output() + { + Ok(output) => { + let output_str = String::from_utf8_lossy(&output.stdout); + output_str.contains(container) + } + Err(_) => false, + } + } + + /// Checks if a Docker container exists. + /// + /// # Arguments + /// + /// * `container` - The name of the Docker container. + /// + /// # Returns + /// + /// `true` if the container exists, `false` otherwise. + #[must_use] + pub fn container_exist(container: &str) -> bool { + match Command::new("docker") + .args(["ps", "-a", "-f", &format!("name={container}"), "--format", "{{.Names}}"]) + .output() + { + Ok(output) => { + let output_str = String::from_utf8_lossy(&output.stdout); + output_str.contains(container) + } + Err(_) => false, + } + } } diff --git a/src/e2e/runner.rs b/src/e2e/runner.rs index 058ebed40..370069544 100644 --- a/src/e2e/runner.rs +++ b/src/e2e/runner.rs @@ -57,6 +57,8 @@ pub fn run() { let running_services = parse_running_services_from_logs(&container); + assert_there_are_no_panics_in_logs(&container); + assert_there_is_at_least_one_service_per_type(&running_services); let tracker_checker_config = @@ -69,9 +71,12 @@ pub fn run() { run_tracker_checker(&tracker_checker_config_path).expect("Tracker checker should check running services"); - // More E2E tests could be executed here in the future. For example: `cargo test ...`. + // More E2E tests could be added here in the future. + // For example: `cargo test ...` for only E2E tests, using this shared test env. + + stop_tracker_container(&container); - info!("Running container `{}` will be automatically removed", container.name); + remove_tracker_container(&container_name); } fn setup_runner_logging(level: LevelFilter) { @@ -164,6 +169,29 @@ fn run_tracker_container(image: &str, container_name: &str, options: &RunOptions container } +fn stop_tracker_container(container: &RunningContainer) { + info!("Stopping docker tracker image: {} ...", container.name); + Docker::stop(container).expect("Container should be stopped"); + assert_there_are_no_panics_in_logs(container); +} + +fn remove_tracker_container(container_name: &str) { + info!("Removing docker tracker image: {container_name} ..."); + Docker::remove(container_name).expect("Container should be removed"); +} + +fn assert_there_are_no_panics_in_logs(container: &RunningContainer) -> RunningServices { + let logs = Docker::logs(&container.name).expect("Logs should be captured from running container"); + + assert!( + !(logs.contains(" panicked at ") || logs.contains("RUST_BACKTRACE=1")), + "{}", + format!("Panics found is logs:\n{logs}") + ); + + RunningServices::parse_from_logs(&logs) +} + fn parse_running_services_from_logs(container: &RunningContainer) -> RunningServices { let logs = Docker::logs(&container.name).expect("Logs should be captured from running container"); From 68f71be7ccb437e6befbbc400d3c46b9ba2eabf8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 26 Jan 2024 11:22:48 +0000 Subject: [PATCH 0198/1297] refactor: [#647] E2E tests. Extract strcut TrackerContainer --- src/e2e/docker.rs | 13 ++-- src/e2e/mod.rs | 1 + src/e2e/runner.rs | 117 +++++++++-------------------- src/e2e/tracker_container.rs | 138 +++++++++++++++++++++++++++++++++++ 4 files changed, 179 insertions(+), 90 deletions(-) create mode 100644 src/e2e/tracker_container.rs diff --git a/src/e2e/docker.rs b/src/e2e/docker.rs index 6eb64783a..c024efbae 100644 --- a/src/e2e/docker.rs +++ b/src/e2e/docker.rs @@ -4,26 +4,26 @@ use std::process::{Command, Output}; use std::thread::sleep; use std::time::{Duration, Instant}; -use log::debug; +use log::{debug, info}; /// Docker command wrapper. pub struct Docker {} +#[derive(Clone, Debug)] pub struct RunningContainer { + pub image: String, pub name: String, pub output: Output, } impl Drop for RunningContainer { - /// Ensures that the temporary container is stopped and removed when the - /// struct goes out of scope. + /// Ensures that the temporary container is stopped when the struct goes out + /// of scope. fn drop(&mut self) { + info!("Dropping running container: {}", self.name); if Docker::is_container_running(&self.name) { let _unused = Docker::stop(self); } - if Docker::container_exist(&self.name) { - let _unused = Docker::remove(&self.name); - } } } @@ -95,6 +95,7 @@ impl Docker { if output.status.success() { Ok(RunningContainer { + image: image.to_owned(), name: container.to_owned(), output, }) diff --git a/src/e2e/mod.rs b/src/e2e/mod.rs index 6745d49cd..deba8971e 100644 --- a/src/e2e/mod.rs +++ b/src/e2e/mod.rs @@ -2,3 +2,4 @@ pub mod docker; pub mod logs_parser; pub mod runner; pub mod temp_dir; +pub mod tracker_container; diff --git a/src/e2e/runner.rs b/src/e2e/runner.rs index 370069544..23b534ee4 100644 --- a/src/e2e/runner.rs +++ b/src/e2e/runner.rs @@ -2,20 +2,26 @@ use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::Command; -use std::time::Duration; use std::{env, io}; use log::{debug, info, LevelFilter}; -use rand::distributions::Alphanumeric; -use rand::Rng; -use super::docker::RunningContainer; -use crate::e2e::docker::{Docker, RunOptions}; +use super::tracker_container::TrackerContainer; +use crate::e2e::docker::RunOptions; use crate::e2e::logs_parser::RunningServices; use crate::e2e::temp_dir::Handler; +/* code-review: + - We use always the same docker image name. Should we use a random image name (tag)? + - We use the name image name we use in other workflows `torrust-tracker:local`. + Should we use a different one like `torrust-tracker:e2e`? + - We remove the container after running tests but not the container image. + Should we remove the image too? +*/ + pub const NUMBER_OF_ARGUMENTS: usize = 2; -const CONTAINER_TAG: &str = "torrust-tracker:local"; +const CONTAINER_IMAGE: &str = "torrust-tracker:local"; +const CONTAINER_NAME_PREFIX: &str = "tracker_"; const TRACKER_CHECKER_CONFIG_FILE: &str = "tracker_checker.json"; pub struct Arguments { @@ -34,11 +40,9 @@ pub fn run() { let tracker_config = load_tracker_configuration(&args.tracker_config_path); - build_tracker_container_image(CONTAINER_TAG); - - let temp_dir = create_temp_dir(); + let mut tracker_container = TrackerContainer::new(CONTAINER_IMAGE, CONTAINER_NAME_PREFIX); - let container_name = generate_random_container_name("tracker_"); + tracker_container.build_image(); // code-review: if we want to use port 0 we don't know which ports we have to open. // Besides, if we don't use port 0 we should get the port numbers from the tracker configuration. @@ -53,30 +57,32 @@ pub fn run() { ], }; - let container = run_tracker_container(CONTAINER_TAG, &container_name, &options); + tracker_container.run(&options); - let running_services = parse_running_services_from_logs(&container); - - assert_there_are_no_panics_in_logs(&container); + let running_services = tracker_container.running_services(); assert_there_is_at_least_one_service_per_type(&running_services); let tracker_checker_config = serde_json::to_string_pretty(&running_services).expect("Running services should be serialized into JSON"); + let temp_dir = create_temp_dir(); + let mut tracker_checker_config_path = PathBuf::from(&temp_dir.temp_dir.path()); tracker_checker_config_path.push(TRACKER_CHECKER_CONFIG_FILE); write_tracker_checker_config_file(&tracker_checker_config_path, &tracker_checker_config); - run_tracker_checker(&tracker_checker_config_path).expect("Tracker checker should check running services"); + run_tracker_checker(&tracker_checker_config_path).expect("All tracker services should be running correctly"); // More E2E tests could be added here in the future. // For example: `cargo test ...` for only E2E tests, using this shared test env. - stop_tracker_container(&container); + tracker_container.stop(); + + tracker_container.remove(); - remove_tracker_container(&container_name); + info!("Tracker container final state:\n{:#?}", tracker_container); } fn setup_runner_logging(level: LevelFilter) { @@ -125,11 +131,6 @@ fn read_file(path: &str) -> String { std::fs::read_to_string(path).unwrap_or_else(|_| panic!("Can't read file {path}")) } -fn build_tracker_container_image(tag: &str) { - info!("Building tracker container image with tag: {} ...", tag); - Docker::build("./Containerfile", tag).expect("A tracker local docker image should be built"); -} - fn create_temp_dir() -> Handler { debug!( "Current dir: {:?}", @@ -143,63 +144,6 @@ fn create_temp_dir() -> Handler { temp_dir_handler } -fn generate_random_container_name(prefix: &str) -> String { - let rand_string: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(20) - .map(char::from) - .collect(); - - format!("{prefix}{rand_string}") -} - -fn run_tracker_container(image: &str, container_name: &str, options: &RunOptions) -> RunningContainer { - info!("Running docker tracker image: {container_name} ..."); - - let container = Docker::run(image, container_name, options).expect("A tracker local docker image should be running"); - - info!("Waiting for the container {container_name} to be healthy ..."); - - let is_healthy = Docker::wait_until_is_healthy(container_name, Duration::from_secs(10)); - - assert!(is_healthy, "Unhealthy tracker container: {container_name}"); - - debug!("Container {container_name} is healthy ..."); - - container -} - -fn stop_tracker_container(container: &RunningContainer) { - info!("Stopping docker tracker image: {} ...", container.name); - Docker::stop(container).expect("Container should be stopped"); - assert_there_are_no_panics_in_logs(container); -} - -fn remove_tracker_container(container_name: &str) { - info!("Removing docker tracker image: {container_name} ..."); - Docker::remove(container_name).expect("Container should be removed"); -} - -fn assert_there_are_no_panics_in_logs(container: &RunningContainer) -> RunningServices { - let logs = Docker::logs(&container.name).expect("Logs should be captured from running container"); - - assert!( - !(logs.contains(" panicked at ") || logs.contains("RUST_BACKTRACE=1")), - "{}", - format!("Panics found is logs:\n{logs}") - ); - - RunningServices::parse_from_logs(&logs) -} - -fn parse_running_services_from_logs(container: &RunningContainer) -> RunningServices { - let logs = Docker::logs(&container.name).expect("Logs should be captured from running container"); - - debug!("Logs after starting the container:\n{logs}"); - - RunningServices::parse_from_logs(&logs) -} - fn assert_there_is_at_least_one_service_per_type(running_services: &RunningServices) { assert!( !running_services.udp_trackers.is_empty(), @@ -216,15 +160,20 @@ fn assert_there_is_at_least_one_service_per_type(running_services: &RunningServi } fn write_tracker_checker_config_file(config_file_path: &Path, config: &str) { + info!( + "Writing Tracker Checker configuration file: {:?} \n{config}", + config_file_path + ); + let mut file = File::create(config_file_path).expect("Tracker checker config file to be created"); file.write_all(config.as_bytes()) .expect("Tracker checker config file to be written"); - - info!("Tracker checker configuration file: {:?} \n{config}", config_file_path); } -/// Runs the tracker checker +/// Runs the Tracker Checker. +/// +/// For example: /// /// ```text /// cargo run --bin tracker_checker "./share/default/config/tracker_checker.json" @@ -239,7 +188,7 @@ fn write_tracker_checker_config_file(config_file_path: &Path, config: &str) { /// Will panic if the config path is not a valid string. pub fn run_tracker_checker(config_path: &Path) -> io::Result<()> { info!( - "Running tacker checker: cargo --bin tracker_checker {}", + "Running Tracker Checker: cargo --bin tracker_checker {}", config_path.display() ); @@ -254,7 +203,7 @@ pub fn run_tracker_checker(config_path: &Path) -> io::Result<()> { } else { Err(io::Error::new( io::ErrorKind::Other, - format!("Failed to run tracker checker with config file {path}"), + format!("Failed to run Tracker Checker with config file {path}"), )) } } diff --git a/src/e2e/tracker_container.rs b/src/e2e/tracker_container.rs new file mode 100644 index 000000000..3e70942b5 --- /dev/null +++ b/src/e2e/tracker_container.rs @@ -0,0 +1,138 @@ +use std::time::Duration; + +use log::{debug, error, info}; +use rand::distributions::Alphanumeric; +use rand::Rng; + +use super::docker::{RunOptions, RunningContainer}; +use super::logs_parser::RunningServices; +use crate::e2e::docker::Docker; + +#[derive(Debug)] +pub struct TrackerContainer { + pub image: String, + pub name: String, + pub running: Option, +} + +impl Drop for TrackerContainer { + /// Ensures that the temporary container is removed when the + /// struct goes out of scope. + fn drop(&mut self) { + info!("Dropping tracker container: {}", self.name); + if Docker::container_exist(&self.name) { + let _unused = Docker::remove(&self.name); + } + } +} + +impl TrackerContainer { + #[must_use] + pub fn new(tag: &str, container_name_prefix: &str) -> Self { + Self { + image: tag.to_owned(), + name: Self::generate_random_container_name(container_name_prefix), + running: None, + } + } + + /// # Panics + /// + /// Will panic if it can't build the docker image. + pub fn build_image(&self) { + info!("Building tracker container image with tag: {} ...", self.image); + Docker::build("./Containerfile", &self.image).expect("A tracker local docker image should be built"); + } + + /// # Panics + /// + /// Will panic if it can't run the container. + pub fn run(&mut self, options: &RunOptions) { + info!("Running docker tracker image: {} ...", self.name); + + let container = Docker::run(&self.image, &self.name, options).expect("A tracker local docker image should be running"); + + info!("Waiting for the container {} to be healthy ...", self.name); + + let is_healthy = Docker::wait_until_is_healthy(&self.name, Duration::from_secs(10)); + + assert!(is_healthy, "Unhealthy tracker container: {}", &self.name); + + info!("Container {} is healthy ...", &self.name); + + self.running = Some(container); + + self.assert_there_are_no_panics_in_logs(); + } + + /// # Panics + /// + /// Will panic if it can't get the logs from the running container. + #[must_use] + pub fn running_services(&self) -> RunningServices { + let logs = Docker::logs(&self.name).expect("Logs should be captured from running container"); + + debug!("Parsing running services from logs. Logs :\n{logs}"); + + RunningServices::parse_from_logs(&logs) + } + + /// # Panics + /// + /// Will panic if it can't stop the container. + pub fn stop(&mut self) { + match &self.running { + Some(container) => { + info!("Stopping docker tracker container: {} ...", self.name); + + Docker::stop(container).expect("Container should be stopped"); + + self.assert_there_are_no_panics_in_logs(); + } + None => { + if Docker::is_container_running(&self.name) { + error!("Tracker container {} was started manually", self.name); + } else { + info!("Docker tracker container is not running: {} ...", self.name); + } + } + } + + self.running = None; + } + + /// # Panics + /// + /// Will panic if it can't remove the container. + pub fn remove(&self) { + match &self.running { + Some(_running_container) => { + error!("Can't remove running container: {} ...", self.name); + } + None => { + info!("Removing docker tracker container: {} ...", self.name); + Docker::remove(&self.name).expect("Container should be removed"); + } + } + } + + fn generate_random_container_name(prefix: &str) -> String { + let rand_string: String = rand::thread_rng() + .sample_iter(&Alphanumeric) + .take(20) + .map(char::from) + .collect(); + + format!("{prefix}{rand_string}") + } + + fn assert_there_are_no_panics_in_logs(&self) { + let logs = Docker::logs(&self.name).expect("Logs should be captured from running container"); + + assert!( + !(logs.contains(" panicked at ") || logs.contains("RUST_BACKTRACE=1")), + "{}", + format!("Panics found is logs:\n{logs}") + ); + } +} From e5cd81bdd1ab7867c240b7a91f30414f604b0318 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 26 Jan 2024 15:14:49 +0000 Subject: [PATCH 0199/1297] refactor: [#647] E2E tests. Extract function --- src/e2e/runner.rs | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/e2e/runner.rs b/src/e2e/runner.rs index 23b534ee4..818210886 100644 --- a/src/e2e/runner.rs +++ b/src/e2e/runner.rs @@ -63,16 +63,13 @@ pub fn run() { assert_there_is_at_least_one_service_per_type(&running_services); - let tracker_checker_config = - serde_json::to_string_pretty(&running_services).expect("Running services should be serialized into JSON"); - let temp_dir = create_temp_dir(); - let mut tracker_checker_config_path = PathBuf::from(&temp_dir.temp_dir.path()); - tracker_checker_config_path.push(TRACKER_CHECKER_CONFIG_FILE); - - write_tracker_checker_config_file(&tracker_checker_config_path, &tracker_checker_config); + let tracker_checker_config_path = + create_tracker_checker_config_file(&running_services, temp_dir.temp_dir.path(), TRACKER_CHECKER_CONFIG_FILE); + // todo: inject the configuration with an env variable so that we don't have + // to create the temporary directory/file. run_tracker_checker(&tracker_checker_config_path).expect("All tracker services should be running correctly"); // More E2E tests could be added here in the future. @@ -159,6 +156,18 @@ fn assert_there_is_at_least_one_service_per_type(running_services: &RunningServi ); } +fn create_tracker_checker_config_file(running_services: &RunningServices, config_path: &Path, config_name: &str) -> PathBuf { + let tracker_checker_config = + serde_json::to_string_pretty(&running_services).expect("Running services should be serialized into JSON"); + + let mut tracker_checker_config_path = PathBuf::from(&config_path); + tracker_checker_config_path.push(config_name); + + write_tracker_checker_config_file(&tracker_checker_config_path, &tracker_checker_config); + + tracker_checker_config_path +} + fn write_tracker_checker_config_file(config_file_path: &Path, config: &str) { info!( "Writing Tracker Checker configuration file: {:?} \n{config}", From f18e68cc498fa98ebb2b23b0605dd8ec60dbf579 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 26 Jan 2024 16:22:56 +0000 Subject: [PATCH 0200/1297] fix: tracker checker return error code when it fails This command: ``` cargo run --bin tracker_checker "./share/default/config/tracker_checker.json" && echo "OK" ``` should not print OK when it fails. --- src/bin/tracker_checker.rs | 2 +- src/checker/app.rs | 10 +++++++--- src/checker/service.rs | 36 +++++++++++++++++++++++++++++++----- src/e2e/runner.rs | 2 +- 4 files changed, 40 insertions(+), 10 deletions(-) diff --git a/src/bin/tracker_checker.rs b/src/bin/tracker_checker.rs index 3a0e0ee88..d2f676097 100644 --- a/src/bin/tracker_checker.rs +++ b/src/bin/tracker_checker.rs @@ -7,5 +7,5 @@ use torrust_tracker::checker::app; #[tokio::main] async fn main() { - app::run().await; + app::run().await.expect("Some checks fail"); } diff --git a/src/checker/app.rs b/src/checker/app.rs index e92373493..22ed61ba7 100644 --- a/src/checker/app.rs +++ b/src/checker/app.rs @@ -2,18 +2,22 @@ use std::sync::Arc; use super::config::Configuration; use super::console::Console; +use super::service::{CheckError, Service}; use crate::checker::config::parse_from_json; -use crate::checker::service::Service; pub const NUMBER_OF_ARGUMENTS: usize = 2; +/// # 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() { +pub async fn run() -> Result<(), Vec> { let args = parse_arguments(); let config = setup_config(&args); let console_printer = Console {}; @@ -22,7 +26,7 @@ pub async fn run() { console: console_printer, }; - service.run_checks().await; + service.run_checks().await } pub struct Arguments { diff --git a/src/checker/service.rs b/src/checker/service.rs index 92902debd..254716376 100644 --- a/src/checker/service.rs +++ b/src/checker/service.rs @@ -14,12 +14,24 @@ pub struct Service { pub(crate) console: Console, } +#[derive(Debug)] +pub enum CheckError { + UdpError, + HttpError, + HealthCheckError { url: Url }, +} + impl Service { - pub async fn run_checks(&self) { + /// # Errors + /// + /// Will return OK is all checks pass or an array with the check errors. + pub async fn run_checks(&self) -> Result<(), Vec> { self.console.println("Running checks for trackers ..."); + self.check_udp_trackers(); self.check_http_trackers(); - self.run_health_checks().await; + + self.run_health_checks().await } fn check_udp_trackers(&self) { @@ -38,11 +50,22 @@ impl Service { } } - async fn run_health_checks(&self) { + async fn run_health_checks(&self) -> Result<(), Vec> { self.console.println("Health checks ..."); + let mut check_errors = vec![]; + for health_check_url in &self.config.health_checks { - self.run_health_check(health_check_url.clone()).await; + match self.run_health_check(health_check_url.clone()).await { + Ok(()) => {} + Err(err) => check_errors.push(err), + } + } + + if check_errors.is_empty() { + Ok(()) + } else { + Err(check_errors) } } @@ -62,7 +85,7 @@ impl Service { .println(&format!("{} - HTTP tracker at {} is OK (TODO)", "✓".green(), url)); } - async fn run_health_check(&self, url: Url) { + async fn run_health_check(&self, url: Url) -> Result<(), CheckError> { let client = Client::builder().timeout(Duration::from_secs(5)).build().unwrap(); match client.get(url.clone()).send().await { @@ -70,14 +93,17 @@ impl Service { if response.status().is_success() { self.console .println(&format!("{} - Health API at {} is OK", "✓".green(), url)); + Ok(()) } else { self.console .eprintln(&format!("{} - Health API at {} failing: {:?}", "✗".red(), url, response)); + Err(CheckError::HealthCheckError { url }) } } Err(err) => { self.console .eprintln(&format!("{} - Health API at {} failing: {:?}", "✗".red(), url, err)); + Err(CheckError::HealthCheckError { url }) } } } diff --git a/src/e2e/runner.rs b/src/e2e/runner.rs index 818210886..aaac0e910 100644 --- a/src/e2e/runner.rs +++ b/src/e2e/runner.rs @@ -68,7 +68,7 @@ pub fn run() { let tracker_checker_config_path = create_tracker_checker_config_file(&running_services, temp_dir.temp_dir.path(), TRACKER_CHECKER_CONFIG_FILE); - // todo: inject the configuration with an env variable so that we don't have + // todo: inject the configuration with an env variable so that we don't have // to create the temporary directory/file. run_tracker_checker(&tracker_checker_config_path).expect("All tracker services should be running correctly"); From f4390155ccb9fe8fa91db9394c5ede0ff747e4f3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 29 Jan 2024 09:47:02 +0000 Subject: [PATCH 0201/1297] feat: [#649] add cargo dependency: clap For console commands. --- Cargo.lock | 13 +++++++------ Cargo.toml | 1 + 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ab270d0cc..6c49938de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -93,9 +93,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.5" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d664a92ecae85fd0a7392615844904654d1d5f5514837f471ddef4a057aba1b6" +checksum = "6e2e1ebcb11de5c03c67de28a7df593d32191b44939c482e97702baaaa6ab6a5" dependencies = [ "anstyle", "anstyle-parse", @@ -574,9 +574,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.12" +version = "4.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcfab8ba68f3668e89f6ff60f5b205cea56aa7b769451a59f34b8682f51c056d" +checksum = "1e578d6ec4194633722ccf9544794b71b1385c3c027efe0c55db226fc880865c" dependencies = [ "clap_builder", "clap_derive", @@ -584,9 +584,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.4.12" +version = "4.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb7fb5e4e979aec3be7791562fcba452f94ad85e954da024396433e0e25a79e9" +checksum = "4df4df40ec50c46000231c914968278b1eb05098cf8f1b3a518a95030e71d1c7" dependencies = [ "anstream", "anstyle", @@ -3437,6 +3437,7 @@ dependencies = [ "axum-server", "binascii", "chrono", + "clap", "colored", "config", "criterion", diff --git a/Cargo.toml b/Cargo.toml index 3a11786f5..4b60b8051 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -72,6 +72,7 @@ uuid = { version = "1", features = ["v4"] } colored = "2.1.0" url = "2.5.0" tempfile = "3.9.0" +clap = { version = "4.4.18", features = ["derive"]} [dev-dependencies] criterion = { version = "0.5.1", features = ["async_tokio"] } From b05e2f5cfead54bcab1b5d5fb3e7e8e223c254c1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 29 Jan 2024 09:48:04 +0000 Subject: [PATCH 0202/1297] refactor: [#649] use clap in HTTP tracker client An added scaffolding for scrape command. --- src/bin/http_tracker_client.rs | 62 ++++++++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 10 deletions(-) diff --git a/src/bin/http_tracker_client.rs b/src/bin/http_tracker_client.rs index 1f1154fa5..29127cdf4 100644 --- a/src/bin/http_tracker_client.rs +++ b/src/bin/http_tracker_client.rs @@ -1,24 +1,60 @@ -use std::env; +//! HTTP Tracker client: +//! +//! Examples: +//! +//! `Announce` request: +//! +//! ```text +//! cargo run --bin http_tracker_client announce http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! `Scrape` request: +//! +//! ```text +//! cargo run --bin http_tracker_client scrape http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` use std::str::FromStr; +use clap::{Parser, Subcommand}; use reqwest::Url; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; use torrust_tracker::shared::bit_torrent::tracker::http::client::responses::announce::Announce; use torrust_tracker::shared::bit_torrent::tracker::http::client::Client; +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand, Debug)] +enum Command { + Announce { tracker_url: String, info_hash: String }, + Scrape { tracker_url: String, info_hashes: Vec }, +} + #[tokio::main] async fn main() { - let args: Vec = env::args().collect(); - if args.len() != 3 { - eprintln!("Error: invalid number of arguments!"); - eprintln!("Usage: cargo run --bin http_tracker_client "); - eprintln!("Example: cargo run --bin http_tracker_client https://tracker.torrust-demo.com 9c38422213e30bff212b30c360d26f9a02136422"); - std::process::exit(1); + let args = Args::parse(); + + match args.command { + Command::Announce { tracker_url, info_hash } => { + announce_command(tracker_url, info_hash).await; + } + Command::Scrape { + tracker_url, + info_hashes, + } => { + scrape_command(&tracker_url, &info_hashes); + } } +} - let base_url = Url::parse(&args[1]).expect("arg 1 should be a valid HTTP tracker base URL"); - let info_hash = InfoHash::from_str(&args[2]).expect("arg 2 should be a valid infohash"); +async fn announce_command(tracker_url: String, info_hash: String) { + let base_url = Url::parse(&tracker_url).expect("Invalid HTTP tracker base URL"); + let info_hash = InfoHash::from_str(&info_hash).expect("Invalid infohash"); let response = Client::new(base_url) .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) @@ -31,5 +67,11 @@ async fn main() { let json = serde_json::to_string(&announce_response).expect("announce response should be a valid JSON"); - print!("{json}"); + println!("{json}"); +} + +fn scrape_command(tracker_url: &str, info_hashes: &[String]) { + println!("URL: {tracker_url}"); + println!("Infohashes: {info_hashes:#?}"); + todo!(); } From 415ca1c371cdff314d7998e9669c1deffd384a28 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 29 Jan 2024 10:28:49 +0000 Subject: [PATCH 0203/1297] feat: [#649] scrape req for the HTTP tracker client ```console cargo run --bin http_tracker_client scrape http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 9c38422213e30bff212b30c360d26f9a02136423 | jq ``` ```json { "9c38422213e30bff212b30c360d26f9a02136422": { "complete": 0, "downloaded": 0, "incomplete": 0 }, "9c38422213e30bff212b30c360d26f9a02136423": { "complete": 0, "downloaded": 0, "incomplete": 0 } } ``` --- src/bin/http_tracker_client.rs | 30 +++++++++++++----- .../tracker/http/client/requests/scrape.rs | 23 +++++++++++++- .../tracker/http/client/responses/scrape.rs | 31 +++++++++++++++++-- 3 files changed, 73 insertions(+), 11 deletions(-) diff --git a/src/bin/http_tracker_client.rs b/src/bin/http_tracker_client.rs index 29127cdf4..5e6db722c 100644 --- a/src/bin/http_tracker_client.rs +++ b/src/bin/http_tracker_client.rs @@ -20,7 +20,8 @@ use reqwest::Url; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; use torrust_tracker::shared::bit_torrent::tracker::http::client::responses::announce::Announce; -use torrust_tracker::shared::bit_torrent::tracker::http::client::Client; +use torrust_tracker::shared::bit_torrent::tracker::http::client::responses::scrape; +use torrust_tracker::shared::bit_torrent::tracker::http::client::{requests, Client}; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] @@ -47,14 +48,15 @@ async fn main() { tracker_url, info_hashes, } => { - scrape_command(&tracker_url, &info_hashes); + scrape_command(&tracker_url, &info_hashes).await; } } } async fn announce_command(tracker_url: String, info_hash: String) { let base_url = Url::parse(&tracker_url).expect("Invalid HTTP tracker base URL"); - let info_hash = InfoHash::from_str(&info_hash).expect("Invalid infohash"); + let info_hash = + InfoHash::from_str(&info_hash).expect("Invalid infohash. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); let response = Client::new(base_url) .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) @@ -63,15 +65,27 @@ async fn announce_command(tracker_url: String, info_hash: String) { let body = response.bytes().await.unwrap(); let announce_response: Announce = serde_bencode::from_bytes(&body) - .unwrap_or_else(|_| panic!("response body should be a valid announce response, got \"{:#?}\"", &body)); + .unwrap_or_else(|_| panic!("response body should be a valid announce response, got: \"{:#?}\"", &body)); let json = serde_json::to_string(&announce_response).expect("announce response should be a valid JSON"); println!("{json}"); } -fn scrape_command(tracker_url: &str, info_hashes: &[String]) { - println!("URL: {tracker_url}"); - println!("Infohashes: {info_hashes:#?}"); - todo!(); +async fn scrape_command(tracker_url: &str, info_hashes: &[String]) { + let base_url = Url::parse(tracker_url).expect("Invalid HTTP tracker base URL"); + + let query = requests::scrape::Query::try_from(info_hashes) + .expect("All infohashes should be valid. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); + + let response = Client::new(base_url).scrape(&query).await; + + let body = response.bytes().await.unwrap(); + + let scrape_response = scrape::Response::try_from_bencoded(&body) + .unwrap_or_else(|_| panic!("response body should be a valid scrape response, got: \"{:#?}\"", &body)); + + let json = serde_json::to_string(&scrape_response).expect("scrape response should be a valid JSON"); + + println!("{json}"); } diff --git a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs index e2563b8ed..2aecc1550 100644 --- a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs +++ b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs @@ -1,4 +1,5 @@ -use std::fmt; +use std::convert::TryFrom; +use std::fmt::{self}; use std::str::FromStr; use crate::shared::bit_torrent::info_hash::InfoHash; @@ -14,6 +15,26 @@ impl fmt::Display for Query { } } +#[derive(Debug)] +pub struct ConversionError(String); + +impl TryFrom<&[String]> for Query { + type Error = ConversionError; + + fn try_from(info_hashes: &[String]) -> Result { + let mut validated_info_hashes: Vec = Vec::new(); + + for info_hash in info_hashes { + let validated_info_hash = InfoHash::from_str(info_hash).map_err(|_| ConversionError(info_hash.clone()))?; + validated_info_hashes.push(validated_info_hash.0); + } + + Ok(Self { + info_hash: validated_info_hashes, + }) + } +} + /// HTTP Tracker Scrape Request: /// /// diff --git a/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs b/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs index ae06841e4..ee301ee7a 100644 --- a/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs +++ b/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs @@ -1,12 +1,14 @@ use std::collections::HashMap; +use std::fmt::Write; use std::str; -use serde::{self, Deserialize, Serialize}; +use serde::ser::SerializeMap; +use serde::{self, Deserialize, Serialize, Serializer}; use serde_bencode::value::Value; use crate::shared::bit_torrent::tracker::http::{ByteArray20, InfoHash}; -#[derive(Debug, PartialEq, Default)] +#[derive(Debug, PartialEq, Default, Deserialize)] pub struct Response { pub files: HashMap, } @@ -60,6 +62,31 @@ struct DeserializedResponse { pub files: Value, } +// Custom serialization for Response +impl Serialize for Response { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut map = serializer.serialize_map(Some(self.files.len()))?; + for (key, value) in &self.files { + // Convert ByteArray20 key to hex string + let hex_key = byte_array_to_hex_string(key); + map.serialize_entry(&hex_key, value)?; + } + map.end() + } +} + +// Helper function to convert ByteArray20 to hex string +fn byte_array_to_hex_string(byte_array: &ByteArray20) -> String { + let mut hex_string = String::with_capacity(byte_array.len() * 2); + for byte in byte_array { + write!(hex_string, "{byte:02x}").expect("Writing to string should never fail"); + } + hex_string +} + #[derive(Default)] pub struct ResponseBuilder { response: Response, From 271bfa853a06b53c88928667518ae56e75269f04 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 29 Jan 2024 11:04:10 +0000 Subject: [PATCH 0204/1297] feat: [#649] add cargo dep: anyhow To handle errors in console clients. --- Cargo.lock | 7 +++++++ Cargo.toml | 1 + 2 files changed, 8 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 6c49938de..1af4d5b3e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -139,6 +139,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "anyhow" +version = "1.0.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "080e9890a082662b09c1ad45f567faeeb47f22b5fb23895fbe1e651e718e25ca" + [[package]] name = "aquatic_udp_protocol" version = "0.8.0" @@ -3430,6 +3436,7 @@ dependencies = [ name = "torrust-tracker" version = "3.0.0-alpha.12-develop" dependencies = [ + "anyhow", "aquatic_udp_protocol", "async-trait", "axum", diff --git a/Cargo.toml b/Cargo.toml index 4b60b8051..a512d90b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,6 +73,7 @@ colored = "2.1.0" url = "2.5.0" tempfile = "3.9.0" clap = { version = "4.4.18", features = ["derive"]} +anyhow = "1.0.79" [dev-dependencies] criterion = { version = "0.5.1", features = ["async_tokio"] } From 0624bf209cf995749c1027c773b15fcc6b113c83 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 29 Jan 2024 11:05:09 +0000 Subject: [PATCH 0205/1297] refactor: [#649] use anyhow to handle errors in the HTTP tracker client. --- src/bin/http_tracker_client.rs | 27 +++++++++++-------- .../tracker/http/client/requests/scrape.rs | 10 +++++++ 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/src/bin/http_tracker_client.rs b/src/bin/http_tracker_client.rs index 5e6db722c..4ca194803 100644 --- a/src/bin/http_tracker_client.rs +++ b/src/bin/http_tracker_client.rs @@ -15,6 +15,7 @@ //! ``` use std::str::FromStr; +use anyhow::Context; use clap::{Parser, Subcommand}; use reqwest::Url; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; @@ -37,24 +38,25 @@ enum Command { } #[tokio::main] -async fn main() { +async fn main() -> anyhow::Result<()> { let args = Args::parse(); match args.command { Command::Announce { tracker_url, info_hash } => { - announce_command(tracker_url, info_hash).await; + announce_command(tracker_url, info_hash).await?; } Command::Scrape { tracker_url, info_hashes, } => { - scrape_command(&tracker_url, &info_hashes).await; + scrape_command(&tracker_url, &info_hashes).await?; } } + Ok(()) } -async fn announce_command(tracker_url: String, info_hash: String) { - let base_url = Url::parse(&tracker_url).expect("Invalid HTTP tracker base URL"); +async fn announce_command(tracker_url: String, info_hash: String) -> anyhow::Result<()> { + let base_url = Url::parse(&tracker_url).context("failed to parse HTTP tracker base URL")?; let info_hash = InfoHash::from_str(&info_hash).expect("Invalid infohash. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); @@ -67,16 +69,17 @@ async fn announce_command(tracker_url: String, info_hash: String) { let announce_response: Announce = serde_bencode::from_bytes(&body) .unwrap_or_else(|_| panic!("response body should be a valid announce response, got: \"{:#?}\"", &body)); - let json = serde_json::to_string(&announce_response).expect("announce response should be a valid JSON"); + let json = serde_json::to_string(&announce_response).context("failed to serialize scrape response into JSON")?; println!("{json}"); + + Ok(()) } -async fn scrape_command(tracker_url: &str, info_hashes: &[String]) { - let base_url = Url::parse(tracker_url).expect("Invalid HTTP tracker base URL"); +async fn scrape_command(tracker_url: &str, info_hashes: &[String]) -> anyhow::Result<()> { + let base_url = Url::parse(tracker_url).context("failed to parse HTTP tracker base URL")?; - let query = requests::scrape::Query::try_from(info_hashes) - .expect("All infohashes should be valid. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); + let query = requests::scrape::Query::try_from(info_hashes).context("failed to parse infohashes")?; let response = Client::new(base_url).scrape(&query).await; @@ -85,7 +88,9 @@ async fn scrape_command(tracker_url: &str, info_hashes: &[String]) { let scrape_response = scrape::Response::try_from_bencoded(&body) .unwrap_or_else(|_| panic!("response body should be a valid scrape response, got: \"{:#?}\"", &body)); - let json = serde_json::to_string(&scrape_response).expect("scrape response should be a valid JSON"); + let json = serde_json::to_string(&scrape_response).context("failed to serialize scrape response into JSON")?; println!("{json}"); + + Ok(()) } diff --git a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs index 2aecc1550..771b3a45e 100644 --- a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs +++ b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs @@ -1,4 +1,5 @@ use std::convert::TryFrom; +use std::error::Error; use std::fmt::{self}; use std::str::FromStr; @@ -16,8 +17,17 @@ impl fmt::Display for Query { } #[derive(Debug)] +#[allow(dead_code)] pub struct ConversionError(String); +impl fmt::Display for ConversionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Invalid infohash: {}", self.0) + } +} + +impl Error for ConversionError {} + impl TryFrom<&[String]> for Query { type Error = ConversionError; From 1b34d9301f783b86cf09ff502ac5611ee50b8b6f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 29 Jan 2024 12:58:28 +0000 Subject: [PATCH 0206/1297] refactor: [#654] UDP tracker client: use clap and anyhow ```console $ cargo run --bin udp_tracker_client announce 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq Compiling torrust-tracker v3.0.0-alpha.12-develop (/home/josecelano/Documents/git/committer/me/github/torrust/torrust-tracker) Finished dev [optimized + debuginfo] target(s) in 2.60s Running `target/debug/udp_tracker_client '127.0.0.1:6969' 9c38422213e30bff212b30c360d26f9a02136422` { "announce_interval": 120, "leechers": 0, "peers": [], "seeders": 1, "transaction_id": -888840697 } ``` --- src/bin/udp_tracker_client.rs | 141 +++++++++++++++++++++++----------- 1 file changed, 98 insertions(+), 43 deletions(-) diff --git a/src/bin/udp_tracker_client.rs b/src/bin/udp_tracker_client.rs index 41084127c..8d30ee0d4 100644 --- a/src/bin/udp_tracker_client.rs +++ b/src/bin/udp_tracker_client.rs @@ -1,24 +1,67 @@ -use std::env; +//! UDP Tracker client: +//! +//! Examples: +//! +//! Announce request: +//! +//! ```text +//! cargo run --bin udp_tracker_client 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! Announce response: +//! +//! ```json +//! { +//! "transaction_id": -888840697 +//! "announce_interval": 120, +//! "leechers": 0, +//! "seeders": 1, +//! "peers": [ +//! "123.123.123.123:51289" +//! ], +//! } +/// ```` use std::net::{Ipv4Addr, SocketAddr}; use std::str::FromStr; +use anyhow::Context; use aquatic_udp_protocol::common::InfoHash; +use aquatic_udp_protocol::Response::{AnnounceIpv4, AnnounceIpv6}; use aquatic_udp_protocol::{ AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, Response, TransactionId, }; +use clap::{Parser, Subcommand}; use log::{debug, LevelFilter}; +use serde_json::json; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash as TorrustInfoHash; use torrust_tracker::shared::bit_torrent::tracker::udp::client::{UdpClient, UdpTrackerClient}; const ASSIGNED_BY_OS: i32 = 0; const RANDOM_TRANSACTION_ID: i32 = -888_840_697; +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand, Debug)] +enum Command { + Announce { + #[arg(value_parser = parse_socket_addr)] + tracker_socket_addr: SocketAddr, + #[arg(value_parser = parse_info_hash)] + info_hash: TorrustInfoHash, + }, +} + #[tokio::main] -async fn main() { +async fn main() -> anyhow::Result<()> { setup_logging(LevelFilter::Info); - let (remote_socket_addr, info_hash) = parse_arguments(); + let args = Args::parse(); // Configuration let local_port = ASSIGNED_BY_OS; @@ -26,33 +69,64 @@ async fn main() { let bind_to = format!("0.0.0.0:{local_port}"); // Bind to local port - debug!("Binding to: {bind_to}"); let udp_client = UdpClient::bind(&bind_to).await; let bound_to = udp_client.socket.local_addr().unwrap(); debug!("Bound to: {bound_to}"); - // Connect to remote socket + let response = match args.command { + Command::Announce { + tracker_socket_addr, + info_hash, + } => { + debug!("Connecting to remote: udp://{tracker_socket_addr}"); - debug!("Connecting to remote: udp://{remote_socket_addr}"); - udp_client.connect(&remote_socket_addr).await; + udp_client.connect(&tracker_socket_addr.to_string()).await; - let udp_tracker_client = UdpTrackerClient { udp_client }; + let udp_tracker_client = UdpTrackerClient { udp_client }; - let transaction_id = TransactionId(transaction_id); + let transaction_id = TransactionId(transaction_id); - let connection_id = send_connection_request(transaction_id, &udp_tracker_client).await; + let connection_id = send_connection_request(transaction_id, &udp_tracker_client).await; - let response = send_announce_request( - connection_id, - transaction_id, - info_hash, - Port(bound_to.port()), - &udp_tracker_client, - ) - .await; + send_announce_request( + connection_id, + transaction_id, + info_hash, + Port(bound_to.port()), + &udp_tracker_client, + ) + .await + } + }; + + match response { + AnnounceIpv4(announce) => { + let json = json!({ + "transaction_id": announce.transaction_id.0, + "announce_interval": announce.announce_interval.0, + "leechers": announce.leechers.0, + "seeders": announce.seeders.0, + "peers": announce.peers.iter().map(|peer| format!("{}:{}", peer.ip_address, peer.port.0)).collect::>(), + }); + let pretty_json = serde_json::to_string_pretty(&json).unwrap(); + println!("{pretty_json}"); + } + AnnounceIpv6(announce) => { + let json = json!({ + "transaction_id": announce.transaction_id.0, + "announce_interval": announce.announce_interval.0, + "leechers": announce.leechers.0, + "seeders": announce.seeders.0, + "peers6": announce.peers.iter().map(|peer| format!("{}:{}", peer.ip_address, peer.port.0)).collect::>(), + }); + let pretty_json = serde_json::to_string_pretty(&json).unwrap(); + println!("{pretty_json}"); + } + _ => println!("{response:#?}"), + } - println!("{response:#?}"); + Ok(()) } fn setup_logging(level: LevelFilter) { @@ -76,31 +150,12 @@ fn setup_logging(level: LevelFilter) { debug!("logging initialized."); } -fn parse_arguments() -> (String, TorrustInfoHash) { - let args: Vec = env::args().collect(); - - if args.len() != 3 { - eprintln!("Error: invalid number of arguments!"); - eprintln!("Usage: cargo run --bin udp_tracker_client "); - eprintln!("Example: cargo run --bin udp_tracker_client 144.126.245.19:6969 9c38422213e30bff212b30c360d26f9a02136422"); - std::process::exit(1); - } +fn parse_socket_addr(s: &str) -> anyhow::Result { + s.parse().with_context(|| format!("failed to parse socket address: `{s}`")) +} - let remote_socket_addr = &args[1]; - let _valid_socket_addr = remote_socket_addr.parse::().unwrap_or_else(|_| { - panic!( - "Invalid argument: `{}`. Argument 1 should be a valid socket address. For example: `144.126.245.19:6969`.", - args[1] - ) - }); - let info_hash = TorrustInfoHash::from_str(&args[2]).unwrap_or_else(|_| { - panic!( - "Invalid argument: `{}`. Argument 2 should be a valid infohash. For example: `9c38422213e30bff212b30c360d26f9a02136422`.", - args[2] - ) - }); - - (remote_socket_addr.to_string(), info_hash) +fn parse_info_hash(s: &str) -> anyhow::Result { + TorrustInfoHash::from_str(s).map_err(|e| anyhow::Error::msg(format!("failed to parse info-hash `{s}`: {e:?}"))) } async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrackerClient) -> ConnectionId { From f4e9bdad94c0c42849cbfa0201cf4c7ab578628c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 29 Jan 2024 16:03:33 +0000 Subject: [PATCH 0207/1297] feat: [#654] UDP tracker client: scrape ```text cargo run --bin udp_tracker_client scrape 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq cargo run --bin udp_tracker_client scrape udp://localhost:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq ``` Scrape response: ```json { "transaction_id": -888840697, "torrent_stats": [ { "completed": 0, "leechers": 0, "seeders": 0 }, { "completed": 0, "leechers": 0, "seeders": 0 } ] } ``` --- cSpell.json | 1 + src/bin/udp_tracker_client.rs | 189 ++++++++++++++++++++++++++++++---- 2 files changed, 168 insertions(+), 22 deletions(-) diff --git a/cSpell.json b/cSpell.json index 0a3f78fad..aaa3229c2 100644 --- a/cSpell.json +++ b/cSpell.json @@ -1,5 +1,6 @@ { "words": [ + "Addrs", "adduser", "alekitto", "appuser", diff --git a/src/bin/udp_tracker_client.rs b/src/bin/udp_tracker_client.rs index 8d30ee0d4..2c8e63cd0 100644 --- a/src/bin/udp_tracker_client.rs +++ b/src/bin/udp_tracker_client.rs @@ -5,7 +5,7 @@ //! Announce request: //! //! ```text -//! cargo run --bin udp_tracker_client 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! cargo run --bin udp_tracker_client announce 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq //! ``` //! //! Announce response: @@ -20,22 +20,58 @@ //! "123.123.123.123:51289" //! ], //! } -/// ```` -use std::net::{Ipv4Addr, SocketAddr}; +//! ``` +//! +//! Scrape request: +//! +//! ```text +//! cargo run --bin udp_tracker_client scrape 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! Scrape response: +//! +//! ```json +//! { +//! "transaction_id": -888840697, +//! "torrent_stats": [ +//! { +//! "completed": 0, +//! "leechers": 0, +//! "seeders": 0 +//! }, +//! { +//! "completed": 0, +//! "leechers": 0, +//! "seeders": 0 +//! } +//! ] +//! } +//! ``` +//! +//! You can use an URL with instead of the socket address. For example: +//! +//! ```text +//! cargo run --bin udp_tracker_client scrape udp://localhost:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! cargo run --bin udp_tracker_client scrape udp://localhost:6969/scrape 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! The protocol (`udp://`) in the URL is mandatory. The path (`\scrape`) is optional. It always uses `\scrape`. +use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs}; use std::str::FromStr; use anyhow::Context; use aquatic_udp_protocol::common::InfoHash; -use aquatic_udp_protocol::Response::{AnnounceIpv4, AnnounceIpv6}; +use aquatic_udp_protocol::Response::{AnnounceIpv4, AnnounceIpv6, Scrape}; use aquatic_udp_protocol::{ AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, Response, - TransactionId, + ScrapeRequest, TransactionId, }; use clap::{Parser, Subcommand}; use log::{debug, LevelFilter}; use serde_json::json; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash as TorrustInfoHash; use torrust_tracker::shared::bit_torrent::tracker::udp::client::{UdpClient, UdpTrackerClient}; +use url::Url; const ASSIGNED_BY_OS: i32 = 0; const RANDOM_TRANSACTION_ID: i32 = -888_840_697; @@ -55,6 +91,12 @@ enum Command { #[arg(value_parser = parse_info_hash)] info_hash: TorrustInfoHash, }, + Scrape { + #[arg(value_parser = parse_socket_addr)] + tracker_socket_addr: SocketAddr, + #[arg(value_parser = parse_info_hash, num_args = 1..=74, value_delimiter = ' ')] + info_hashes: Vec, + }, } #[tokio::main] @@ -65,29 +107,23 @@ async fn main() -> anyhow::Result<()> { // Configuration let local_port = ASSIGNED_BY_OS; + let local_bind_to = format!("0.0.0.0:{local_port}"); let transaction_id = RANDOM_TRANSACTION_ID; - let bind_to = format!("0.0.0.0:{local_port}"); // Bind to local port - debug!("Binding to: {bind_to}"); - let udp_client = UdpClient::bind(&bind_to).await; + debug!("Binding to: {local_bind_to}"); + let udp_client = UdpClient::bind(&local_bind_to).await; let bound_to = udp_client.socket.local_addr().unwrap(); debug!("Bound to: {bound_to}"); + let transaction_id = TransactionId(transaction_id); + let response = match args.command { Command::Announce { tracker_socket_addr, info_hash, } => { - debug!("Connecting to remote: udp://{tracker_socket_addr}"); - - udp_client.connect(&tracker_socket_addr.to_string()).await; - - let udp_tracker_client = UdpTrackerClient { udp_client }; - - let transaction_id = TransactionId(transaction_id); - - let connection_id = send_connection_request(transaction_id, &udp_tracker_client).await; + let (connection_id, udp_tracker_client) = connect(&tracker_socket_addr, udp_client, transaction_id).await; send_announce_request( connection_id, @@ -98,6 +134,13 @@ async fn main() -> anyhow::Result<()> { ) .await } + Command::Scrape { + tracker_socket_addr, + info_hashes, + } => { + let (connection_id, udp_tracker_client) = connect(&tracker_socket_addr, udp_client, transaction_id).await; + send_scrape_request(connection_id, transaction_id, info_hashes, &udp_tracker_client).await + } }; match response { @@ -123,7 +166,19 @@ async fn main() -> anyhow::Result<()> { let pretty_json = serde_json::to_string_pretty(&json).unwrap(); println!("{pretty_json}"); } - _ => println!("{response:#?}"), + Scrape(scrape) => { + let json = json!({ + "transaction_id": scrape.transaction_id.0, + "torrent_stats": scrape.torrent_stats.iter().map(|torrent_scrape_statistics| json!({ + "seeders": torrent_scrape_statistics.seeders.0, + "completed": torrent_scrape_statistics.completed.0, + "leechers": torrent_scrape_statistics.leechers.0, + })).collect::>(), + }); + let pretty_json = serde_json::to_string_pretty(&json).unwrap(); + println!("{pretty_json}"); + } + _ => println!("{response:#?}"), // todo: serialize to JSON all responses. } Ok(()) @@ -150,12 +205,76 @@ fn setup_logging(level: LevelFilter) { debug!("logging initialized."); } -fn parse_socket_addr(s: &str) -> anyhow::Result { - s.parse().with_context(|| format!("failed to parse socket address: `{s}`")) +fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { + debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); + + // Check if the address is a valid URL. If so, extract the host and port. + let resolved_addr = if let Ok(url) = Url::parse(tracker_socket_addr_str) { + debug!("Tracker socket address URL: {url:?}"); + + let host = url + .host_str() + .with_context(|| format!("invalid host in URL: `{tracker_socket_addr_str}`"))? + .to_owned(); + + let port = url + .port() + .with_context(|| format!("port not found in URL: `{tracker_socket_addr_str}`"))? + .to_owned(); + + (host, port) + } else { + // If not a URL, assume it's a host:port pair. + + let parts: Vec<&str> = tracker_socket_addr_str.split(':').collect(); + + if parts.len() != 2 { + return Err(anyhow::anyhow!( + "invalid address format: `{}`. Expected format is host:port", + tracker_socket_addr_str + )); + } + + let host = parts[0].to_owned(); + + let port = parts[1] + .parse::() + .with_context(|| format!("invalid port: `{}`", parts[1]))? + .to_owned(); + + (host, port) + }; + + debug!("Resolved address: {resolved_addr:#?}"); + + // Perform DNS resolution. + let socket_addrs: Vec<_> = resolved_addr.to_socket_addrs()?.collect(); + if socket_addrs.is_empty() { + Err(anyhow::anyhow!("DNS resolution failed for `{}`", tracker_socket_addr_str)) + } else { + Ok(socket_addrs[0]) + } +} + +fn parse_info_hash(info_hash_str: &str) -> anyhow::Result { + TorrustInfoHash::from_str(info_hash_str) + .map_err(|e| anyhow::Error::msg(format!("failed to parse info-hash `{info_hash_str}`: {e:?}"))) } -fn parse_info_hash(s: &str) -> anyhow::Result { - TorrustInfoHash::from_str(s).map_err(|e| anyhow::Error::msg(format!("failed to parse info-hash `{s}`: {e:?}"))) +async fn connect( + tracker_socket_addr: &SocketAddr, + udp_client: UdpClient, + transaction_id: TransactionId, +) -> (ConnectionId, UdpTrackerClient) { + debug!("Connecting to tracker: udp://{tracker_socket_addr}"); + + udp_client.connect(&tracker_socket_addr.to_string()).await; + + let udp_tracker_client = UdpTrackerClient { udp_client }; + + let connection_id = send_connection_request(transaction_id, &udp_tracker_client).await; + + (connection_id, udp_tracker_client) } async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrackerClient) -> ConnectionId { @@ -207,3 +326,29 @@ async fn send_announce_request( response } + +async fn send_scrape_request( + connection_id: ConnectionId, + transaction_id: TransactionId, + info_hashes: Vec, + client: &UdpTrackerClient, +) -> Response { + debug!("Sending scrape request with transaction id: {transaction_id:#?}"); + + let scrape_request = ScrapeRequest { + connection_id, + transaction_id, + info_hashes: info_hashes + .iter() + .map(|torrust_info_hash| InfoHash(torrust_info_hash.bytes())) + .collect(), + }; + + client.send(scrape_request.into()).await; + + let response = client.receive().await; + + debug!("scrape request response:\n{response:#?}"); + + response +} From 8543190b242c1bece4e2b9932f74c1e3c3bc74ae Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 29 Jan 2024 18:16:42 +0000 Subject: [PATCH 0208/1297] refactor: Tracker Checker: use clap and anyhow --- src/checker/app.rs | 60 ++++++++++++++++-------------------------- src/checker/config.rs | 3 +++ src/checker/service.rs | 18 ++++++------- 3 files changed, 33 insertions(+), 48 deletions(-) diff --git a/src/checker/app.rs b/src/checker/app.rs index 22ed61ba7..66bbf1278 100644 --- a/src/checker/app.rs +++ b/src/checker/app.rs @@ -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)] +#[clap(author, version, about, long_about = None)] +struct Args { + config_path: PathBuf, +} /// # 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> { - 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> { + 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 = std::env::args().collect(); - - if args.len() < NUMBER_OF_ARGUMENTS { - eprintln!("Usage: cargo run --bin tracker_checker "); - 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 { + let file_content = + std::fs::read_to_string(&args.config_path).with_context(|| format!("can't read config file {:?}", args.config_path))?; - parse_from_json(&file_content).expect("Invalid config format") + parse_from_json(&file_content).context("invalid config format") } diff --git a/src/checker/config.rs b/src/checker/config.rs index aaf611bb9..5cfee0760 100644 --- a/src/checker/config.rs +++ b/src/checker/config.rs @@ -1,3 +1,4 @@ +use std::error::Error; use std::fmt; use std::net::SocketAddr; @@ -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 { diff --git a/src/checker/service.rs b/src/checker/service.rs index 254716376..fd93ed8c0 100644 --- a/src/checker/service.rs +++ b/src/checker/service.rs @@ -14,6 +14,8 @@ pub struct Service { pub(crate) console: Console, } +pub type CheckResult = Result<(), CheckError>; + #[derive(Debug)] pub enum CheckError { UdpError, @@ -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> { + pub async fn run_checks(&self) -> Vec { self.console.println("Running checks for trackers ..."); self.check_udp_trackers(); @@ -50,23 +52,19 @@ impl Service { } } - async fn run_health_checks(&self) -> Result<(), Vec> { + async fn run_health_checks(&self) -> Vec { 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) { From 7f43fbd78bd2b363b54dd27718d889abc508539a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jan 2024 08:32:41 +0000 Subject: [PATCH 0209/1297] chore: [656] add cargo dep feature We will need "env" clap feature to use env variables for arguments. --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index a512d90b0..1418f23dd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -72,7 +72,7 @@ uuid = { version = "1", features = ["v4"] } colored = "2.1.0" url = "2.5.0" tempfile = "3.9.0" -clap = { version = "4.4.18", features = ["derive"]} +clap = { version = "4.4.18", features = ["derive", "env"]} anyhow = "1.0.79" [dev-dependencies] From 1bab582beebc2e1b6cc845ac39ee0c7943f02d1b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jan 2024 08:33:53 +0000 Subject: [PATCH 0210/1297] feat: [#656] Tracker Checker sopports env var for config Run providing a config file path: ```text cargo run --bin tracker_checker -- --config-path "./share/default/config/tracker_checker.json" TORRUST_CHECKER_CONFIG_PATH="./share/default/config/tracker_checker.json" cargo run --bin tracker_checker ``` Run providing the configuration: ```text TORRUST_CHECKER_CONFIG=$(cat "./share/default/config/tracker_checker.json") cargo run --bin tracker_checker ``` --- src/bin/tracker_checker.rs | 11 ++++++++++- src/checker/app.rs | 29 +++++++++++++++++++++-------- src/e2e/runner.rs | 4 ++-- 3 files changed, 33 insertions(+), 11 deletions(-) diff --git a/src/bin/tracker_checker.rs b/src/bin/tracker_checker.rs index d2f676097..926a0026c 100644 --- a/src/bin/tracker_checker.rs +++ b/src/bin/tracker_checker.rs @@ -1,7 +1,16 @@ //! Program to run checks against running trackers. //! +//! Run providing a config file path: +//! +//! ```text +//! cargo run --bin tracker_checker -- --config-path "./share/default/config/tracker_checker.json" +//! TORRUST_CHECKER_CONFIG_PATH="./share/default/config/tracker_checker.json" cargo run --bin tracker_checker +//! ``` +//! +//! Run providing the configuration: +//! //! ```text -//! cargo run --bin tracker_checker "./share/default/config/tracker_checker.json" +//! TORRUST_CHECKER_CONFIG=$(cat "./share/default/config/tracker_checker.json") cargo run --bin tracker_checker //! ``` use torrust_tracker::checker::app; diff --git a/src/checker/app.rs b/src/checker/app.rs index 66bbf1278..1e91ce846 100644 --- a/src/checker/app.rs +++ b/src/checker/app.rs @@ -1,7 +1,7 @@ use std::path::PathBuf; use std::sync::Arc; -use anyhow::Context; +use anyhow::{Context, Result}; use clap::Parser; use super::config::Configuration; @@ -12,16 +12,22 @@ use crate::checker::config::parse_from_json; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] struct Args { - config_path: PathBuf, + /// Path to the JSON configuration file. + #[clap(short, long, env = "TORRUST_CHECKER_CONFIG_PATH")] + config_path: Option, + + /// Direct configuration content in JSON. + #[clap(env = "TORRUST_CHECKER_CONFIG", hide_env_values = true)] + config_content: Option, } /// # Errors /// -/// Will return an error if it can't read or parse the configuration file. -pub async fn run() -> anyhow::Result> { +/// Will return an error if the configuration was not provided. +pub async fn run() -> Result> { let args = Args::parse(); - let config = setup_config(&args)?; + let config = setup_config(args)?; let console_printer = Console {}; @@ -33,9 +39,16 @@ pub async fn run() -> anyhow::Result> { Ok(service.run_checks().await) } -fn setup_config(args: &Args) -> anyhow::Result { - let file_content = - std::fs::read_to_string(&args.config_path).with_context(|| format!("can't read config file {:?}", args.config_path))?; +fn setup_config(args: Args) -> Result { + match (args.config_path, args.config_content) { + (Some(config_path), _) => load_config_from_file(&config_path), + (_, Some(config_content)) => parse_from_json(&config_content).context("invalid config format"), + _ => Err(anyhow::anyhow!("no configuration provided")), + } +} + +fn load_config_from_file(path: &PathBuf) -> Result { + let file_content = std::fs::read_to_string(path).with_context(|| format!("can't read config file {path:?}"))?; parse_from_json(&file_content).context("invalid config format") } diff --git a/src/e2e/runner.rs b/src/e2e/runner.rs index aaac0e910..90c98608b 100644 --- a/src/e2e/runner.rs +++ b/src/e2e/runner.rs @@ -197,14 +197,14 @@ fn write_tracker_checker_config_file(config_file_path: &Path, config: &str) { /// Will panic if the config path is not a valid string. pub fn run_tracker_checker(config_path: &Path) -> io::Result<()> { info!( - "Running Tracker Checker: cargo --bin tracker_checker {}", + "Running Tracker Checker: cargo run --bin tracker_checker -- --config-path \"{}\"", config_path.display() ); let path = config_path.to_str().expect("The path should be a valid string"); let status = Command::new("cargo") - .args(["run", "--bin", "tracker_checker", path]) + .args(["run", "--bin", "tracker_checker", "--", "--config-path", path]) .status()?; if status.success() { From 392ffab67dc61ae7dc9230e2ebd290980d15d24c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jan 2024 09:30:34 +0000 Subject: [PATCH 0211/1297] refactor: [#656] E2E runner. Pass config as env var to Tracker Checker This was we don't even need a temp dir to run E2E tests. --- src/e2e/mod.rs | 2 +- src/e2e/runner.rs | 95 ++------------------------------------ src/e2e/temp_dir.rs | 53 --------------------- src/e2e/tracker_checker.rs | 25 ++++++++++ 4 files changed, 31 insertions(+), 144 deletions(-) delete mode 100644 src/e2e/temp_dir.rs create mode 100644 src/e2e/tracker_checker.rs diff --git a/src/e2e/mod.rs b/src/e2e/mod.rs index deba8971e..e4384e160 100644 --- a/src/e2e/mod.rs +++ b/src/e2e/mod.rs @@ -1,5 +1,5 @@ pub mod docker; pub mod logs_parser; pub mod runner; -pub mod temp_dir; +pub mod tracker_checker; pub mod tracker_container; diff --git a/src/e2e/runner.rs b/src/e2e/runner.rs index 90c98608b..a4bcb3aa3 100644 --- a/src/e2e/runner.rs +++ b/src/e2e/runner.rs @@ -1,15 +1,9 @@ -use std::fs::File; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::process::Command; -use std::{env, io}; - use log::{debug, info, LevelFilter}; use super::tracker_container::TrackerContainer; use crate::e2e::docker::RunOptions; use crate::e2e::logs_parser::RunningServices; -use crate::e2e::temp_dir::Handler; +use crate::e2e::tracker_checker::{self}; /* code-review: - We use always the same docker image name. Should we use a random image name (tag)? @@ -19,10 +13,9 @@ use crate::e2e::temp_dir::Handler; Should we remove the image too? */ -pub const NUMBER_OF_ARGUMENTS: usize = 2; +const NUMBER_OF_ARGUMENTS: usize = 2; const CONTAINER_IMAGE: &str = "torrust-tracker:local"; const CONTAINER_NAME_PREFIX: &str = "tracker_"; -const TRACKER_CHECKER_CONFIG_FILE: &str = "tracker_checker.json"; pub struct Arguments { pub tracker_config_path: String, @@ -63,14 +56,10 @@ pub fn run() { assert_there_is_at_least_one_service_per_type(&running_services); - let temp_dir = create_temp_dir(); - - let tracker_checker_config_path = - create_tracker_checker_config_file(&running_services, temp_dir.temp_dir.path(), TRACKER_CHECKER_CONFIG_FILE); + let tracker_checker_config = + serde_json::to_string_pretty(&running_services).expect("Running services should be serialized into JSON"); - // todo: inject the configuration with an env variable so that we don't have - // to create the temporary directory/file. - run_tracker_checker(&tracker_checker_config_path).expect("All tracker services should be running correctly"); + tracker_checker::run(&tracker_checker_config).expect("All tracker services should be running correctly"); // More E2E tests could be added here in the future. // For example: `cargo test ...` for only E2E tests, using this shared test env. @@ -128,19 +117,6 @@ fn read_file(path: &str) -> String { std::fs::read_to_string(path).unwrap_or_else(|_| panic!("Can't read file {path}")) } -fn create_temp_dir() -> Handler { - debug!( - "Current dir: {:?}", - env::current_dir().expect("It should return the current dir") - ); - - let temp_dir_handler = Handler::new().expect("A temp dir should be created"); - - info!("Temp dir created: {:?}", temp_dir_handler.temp_dir); - - temp_dir_handler -} - fn assert_there_is_at_least_one_service_per_type(running_services: &RunningServices) { assert!( !running_services.udp_trackers.is_empty(), @@ -155,64 +131,3 @@ fn assert_there_is_at_least_one_service_per_type(running_services: &RunningServi "At least one Health Check should be enabled in E2E tests configuration" ); } - -fn create_tracker_checker_config_file(running_services: &RunningServices, config_path: &Path, config_name: &str) -> PathBuf { - let tracker_checker_config = - serde_json::to_string_pretty(&running_services).expect("Running services should be serialized into JSON"); - - let mut tracker_checker_config_path = PathBuf::from(&config_path); - tracker_checker_config_path.push(config_name); - - write_tracker_checker_config_file(&tracker_checker_config_path, &tracker_checker_config); - - tracker_checker_config_path -} - -fn write_tracker_checker_config_file(config_file_path: &Path, config: &str) { - info!( - "Writing Tracker Checker configuration file: {:?} \n{config}", - config_file_path - ); - - let mut file = File::create(config_file_path).expect("Tracker checker config file to be created"); - - file.write_all(config.as_bytes()) - .expect("Tracker checker config file to be written"); -} - -/// Runs the Tracker Checker. -/// -/// For example: -/// -/// ```text -/// cargo run --bin tracker_checker "./share/default/config/tracker_checker.json" -/// ``` -/// -/// # Errors -/// -/// Will return an error if the tracker checker fails. -/// -/// # Panics -/// -/// Will panic if the config path is not a valid string. -pub fn run_tracker_checker(config_path: &Path) -> io::Result<()> { - info!( - "Running Tracker Checker: cargo run --bin tracker_checker -- --config-path \"{}\"", - config_path.display() - ); - - let path = config_path.to_str().expect("The path should be a valid string"); - - let status = Command::new("cargo") - .args(["run", "--bin", "tracker_checker", "--", "--config-path", path]) - .status()?; - - if status.success() { - Ok(()) - } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!("Failed to run Tracker Checker with config file {path}"), - )) - } -} diff --git a/src/e2e/temp_dir.rs b/src/e2e/temp_dir.rs deleted file mode 100644 index 8433e3059..000000000 --- a/src/e2e/temp_dir.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! Temp dir which is automatically removed when it goes out of scope. -use std::path::PathBuf; -use std::{env, io}; - -use tempfile::TempDir; - -pub struct Handler { - pub temp_dir: TempDir, - pub original_dir: PathBuf, -} - -impl Handler { - /// Creates a new temporary directory and remembers the current working directory. - /// - /// # Errors - /// - /// Will error if: - /// - /// - It can't create the temp dir. - /// - It can't get the current dir. - pub fn new() -> io::Result { - let temp_dir = TempDir::new()?; - let original_dir = env::current_dir()?; - - Ok(Handler { temp_dir, original_dir }) - } - - /// Changes the current working directory to the temporary directory. - /// - /// # Errors - /// - /// Will error if it can't change the current di to the temp dir. - pub fn change_to_temp_dir(&self) -> io::Result<()> { - env::set_current_dir(self.temp_dir.path()) - } - - /// Changes the current working directory back to the original directory. - /// - /// # Errors - /// - /// Will error if it can't revert the current dir to the original one. - pub fn revert_to_original_dir(&self) -> io::Result<()> { - env::set_current_dir(&self.original_dir) - } -} - -impl Drop for Handler { - /// Ensures that the temporary directory is deleted when the struct goes out of scope. - fn drop(&mut self) { - // The temporary directory is automatically deleted when `TempDir` is dropped. - // We can add additional cleanup here if necessary. - } -} diff --git a/src/e2e/tracker_checker.rs b/src/e2e/tracker_checker.rs new file mode 100644 index 000000000..edc679802 --- /dev/null +++ b/src/e2e/tracker_checker.rs @@ -0,0 +1,25 @@ +use std::io; +use std::process::Command; + +use log::info; + +/// Runs the Tracker Checker. +/// +/// # Errors +/// +/// Will return an error if the Tracker Checker fails. +pub fn run(config_content: &str) -> io::Result<()> { + info!("Running Tracker Checker: TORRUST_CHECKER_CONFIG=[config] cargo run --bin tracker_checker"); + info!("Tracker Checker config:\n{config_content}"); + + let status = Command::new("cargo") + .env("TORRUST_CHECKER_CONFIG", config_content) + .args(["run", "--bin", "tracker_checker"]) + .status()?; + + if status.success() { + Ok(()) + } else { + Err(io::Error::new(io::ErrorKind::Other, "Failed to run Tracker Checker")) + } +} From d8a9f7b358ce0b8cbf806d188a8c89abb4f54ffd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jan 2024 10:19:22 +0000 Subject: [PATCH 0212/1297] refactor: [#661] move E2E tests runner mod --- src/bin/e2e_tests_runner.rs | 6 +----- src/{ => console/ci}/e2e/docker.rs | 0 src/{ => console/ci}/e2e/logs_parser.rs | 0 src/{ => console/ci}/e2e/mod.rs | 1 + src/{ => console/ci}/e2e/runner.rs | 11 ++++++++--- src/{ => console/ci}/e2e/tracker_checker.rs | 0 src/{ => console/ci}/e2e/tracker_container.rs | 2 +- src/console/ci/mod.rs | 2 ++ src/console/clients/mod.rs | 1 + src/console/mod.rs | 3 +++ src/lib.rs | 2 +- 11 files changed, 18 insertions(+), 10 deletions(-) rename src/{ => console/ci}/e2e/docker.rs (100%) rename src/{ => console/ci}/e2e/logs_parser.rs (100%) rename src/{ => console/ci}/e2e/mod.rs (82%) rename src/{ => console/ci}/e2e/runner.rs (93%) rename src/{ => console/ci}/e2e/tracker_checker.rs (100%) rename src/{ => console/ci}/e2e/tracker_container.rs (98%) create mode 100644 src/console/ci/mod.rs create mode 100644 src/console/clients/mod.rs create mode 100644 src/console/mod.rs diff --git a/src/bin/e2e_tests_runner.rs b/src/bin/e2e_tests_runner.rs index 35368b612..b21459d2e 100644 --- a/src/bin/e2e_tests_runner.rs +++ b/src/bin/e2e_tests_runner.rs @@ -1,9 +1,5 @@ //! Program to run E2E tests. -//! -//! ```text -//! cargo run --bin e2e_tests_runner share/default/config/tracker.e2e.container.sqlite3.toml -//! ``` -use torrust_tracker::e2e; +use torrust_tracker::console::ci::e2e; fn main() { e2e::runner::run(); diff --git a/src/e2e/docker.rs b/src/console/ci/e2e/docker.rs similarity index 100% rename from src/e2e/docker.rs rename to src/console/ci/e2e/docker.rs diff --git a/src/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs similarity index 100% rename from src/e2e/logs_parser.rs rename to src/console/ci/e2e/logs_parser.rs diff --git a/src/e2e/mod.rs b/src/console/ci/e2e/mod.rs similarity index 82% rename from src/e2e/mod.rs rename to src/console/ci/e2e/mod.rs index e4384e160..58a876cbe 100644 --- a/src/e2e/mod.rs +++ b/src/console/ci/e2e/mod.rs @@ -1,3 +1,4 @@ +//! E2E tests scripts. pub mod docker; pub mod logs_parser; pub mod runner; diff --git a/src/e2e/runner.rs b/src/console/ci/e2e/runner.rs similarity index 93% rename from src/e2e/runner.rs rename to src/console/ci/e2e/runner.rs index a4bcb3aa3..1a4746800 100644 --- a/src/e2e/runner.rs +++ b/src/console/ci/e2e/runner.rs @@ -1,9 +1,14 @@ +//! Program to run E2E tests. +//! +//! ```text +//! cargo run --bin e2e_tests_runner share/default/config/tracker.e2e.container.sqlite3.toml +//! ``` use log::{debug, info, LevelFilter}; use super::tracker_container::TrackerContainer; -use crate::e2e::docker::RunOptions; -use crate::e2e::logs_parser::RunningServices; -use crate::e2e::tracker_checker::{self}; +use crate::console::ci::e2e::docker::RunOptions; +use crate::console::ci::e2e::logs_parser::RunningServices; +use crate::console::ci::e2e::tracker_checker::{self}; /* code-review: - We use always the same docker image name. Should we use a random image name (tag)? diff --git a/src/e2e/tracker_checker.rs b/src/console/ci/e2e/tracker_checker.rs similarity index 100% rename from src/e2e/tracker_checker.rs rename to src/console/ci/e2e/tracker_checker.rs diff --git a/src/e2e/tracker_container.rs b/src/console/ci/e2e/tracker_container.rs similarity index 98% rename from src/e2e/tracker_container.rs rename to src/console/ci/e2e/tracker_container.rs index 3e70942b5..5a4d11d02 100644 --- a/src/e2e/tracker_container.rs +++ b/src/console/ci/e2e/tracker_container.rs @@ -6,7 +6,7 @@ use rand::Rng; use super::docker::{RunOptions, RunningContainer}; use super::logs_parser::RunningServices; -use crate::e2e::docker::Docker; +use crate::console::ci::e2e::docker::Docker; #[derive(Debug)] pub struct TrackerContainer { diff --git a/src/console/ci/mod.rs b/src/console/ci/mod.rs new file mode 100644 index 000000000..6eac3e120 --- /dev/null +++ b/src/console/ci/mod.rs @@ -0,0 +1,2 @@ +//! Continuos integration scripts. +pub mod e2e; diff --git a/src/console/clients/mod.rs b/src/console/clients/mod.rs new file mode 100644 index 000000000..a3fd318b2 --- /dev/null +++ b/src/console/clients/mod.rs @@ -0,0 +1 @@ +//! Console clients. diff --git a/src/console/mod.rs b/src/console/mod.rs new file mode 100644 index 000000000..54ed8e415 --- /dev/null +++ b/src/console/mod.rs @@ -0,0 +1,3 @@ +//! Console apps. +pub mod ci; +pub mod clients; diff --git a/src/lib.rs b/src/lib.rs index f239039bd..398795d37 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -472,8 +472,8 @@ pub mod app; pub mod bootstrap; pub mod checker; +pub mod console; pub mod core; -pub mod e2e; pub mod servers; pub mod shared; From 0960ff269529fadff6dd9152445c7939c1cbd9f0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jan 2024 12:16:14 +0000 Subject: [PATCH 0213/1297] refactor: [#661] move Tracker Checker mod --- src/bin/tracker_checker.rs | 17 ++--------------- src/{ => console/clients}/checker/app.rs | 16 +++++++++++++++- src/{ => console/clients}/checker/config.rs | 2 +- src/{ => console/clients}/checker/console.rs | 0 src/{ => console/clients}/checker/logger.rs | 4 ++-- src/{ => console/clients}/checker/mod.rs | 0 src/{ => console/clients}/checker/printer.rs | 0 src/{ => console/clients}/checker/service.rs | 2 +- src/console/clients/mod.rs | 1 + src/lib.rs | 1 - 10 files changed, 22 insertions(+), 21 deletions(-) rename src/{ => console/clients}/checker/app.rs (73%) rename src/{ => console/clients}/checker/config.rs (98%) rename src/{ => console/clients}/checker/console.rs (100%) rename src/{ => console/clients}/checker/logger.rs (91%) rename src/{ => console/clients}/checker/mod.rs (100%) rename src/{ => console/clients}/checker/printer.rs (100%) rename src/{ => console/clients}/checker/service.rs (98%) diff --git a/src/bin/tracker_checker.rs b/src/bin/tracker_checker.rs index 926a0026c..1bda0f54f 100644 --- a/src/bin/tracker_checker.rs +++ b/src/bin/tracker_checker.rs @@ -1,18 +1,5 @@ -//! Program to run checks against running trackers. -//! -//! Run providing a config file path: -//! -//! ```text -//! cargo run --bin tracker_checker -- --config-path "./share/default/config/tracker_checker.json" -//! TORRUST_CHECKER_CONFIG_PATH="./share/default/config/tracker_checker.json" cargo run --bin tracker_checker -//! ``` -//! -//! Run providing the configuration: -//! -//! ```text -//! TORRUST_CHECKER_CONFIG=$(cat "./share/default/config/tracker_checker.json") cargo run --bin tracker_checker -//! ``` -use torrust_tracker::checker::app; +//! Program to run check running trackers. +use torrust_tracker::console::clients::checker::app; #[tokio::main] async fn main() { diff --git a/src/checker/app.rs b/src/console/clients/checker/app.rs similarity index 73% rename from src/checker/app.rs rename to src/console/clients/checker/app.rs index 1e91ce846..bca4b64dc 100644 --- a/src/checker/app.rs +++ b/src/console/clients/checker/app.rs @@ -1,3 +1,17 @@ +//! Program to run checks against running trackers. +//! +//! Run providing a config file path: +//! +//! ```text +//! cargo run --bin tracker_checker -- --config-path "./share/default/config/tracker_checker.json" +//! TORRUST_CHECKER_CONFIG_PATH="./share/default/config/tracker_checker.json" cargo run --bin tracker_checker +//! ``` +//! +//! Run providing the configuration: +//! +//! ```text +//! TORRUST_CHECKER_CONFIG=$(cat "./share/default/config/tracker_checker.json") cargo run --bin tracker_checker +//! ``` use std::path::PathBuf; use std::sync::Arc; @@ -7,7 +21,7 @@ use clap::Parser; use super::config::Configuration; use super::console::Console; use super::service::{CheckResult, Service}; -use crate::checker::config::parse_from_json; +use crate::console::clients::checker::config::parse_from_json; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] diff --git a/src/checker/config.rs b/src/console/clients/checker/config.rs similarity index 98% rename from src/checker/config.rs rename to src/console/clients/checker/config.rs index 5cfee0760..0a2c09b03 100644 --- a/src/checker/config.rs +++ b/src/console/clients/checker/config.rs @@ -117,7 +117,7 @@ mod tests { } mod building_configuration_from_plan_configuration { - use crate::checker::config::{Configuration, PlainConfiguration}; + use crate::console::clients::checker::config::{Configuration, PlainConfiguration}; #[test] fn it_should_fail_when_a_tracker_udp_address_is_invalid() { diff --git a/src/checker/console.rs b/src/console/clients/checker/console.rs similarity index 100% rename from src/checker/console.rs rename to src/console/clients/checker/console.rs diff --git a/src/checker/logger.rs b/src/console/clients/checker/logger.rs similarity index 91% rename from src/checker/logger.rs rename to src/console/clients/checker/logger.rs index 3d1074e7b..50e97189f 100644 --- a/src/checker/logger.rs +++ b/src/console/clients/checker/logger.rs @@ -49,8 +49,8 @@ impl Printer for Logger { #[cfg(test)] mod tests { - use crate::checker::logger::Logger; - use crate::checker::printer::{Printer, CLEAR_SCREEN}; + use crate::console::clients::checker::logger::Logger; + use crate::console::clients::checker::printer::{Printer, CLEAR_SCREEN}; #[test] fn should_capture_the_clear_screen_command() { diff --git a/src/checker/mod.rs b/src/console/clients/checker/mod.rs similarity index 100% rename from src/checker/mod.rs rename to src/console/clients/checker/mod.rs diff --git a/src/checker/printer.rs b/src/console/clients/checker/printer.rs similarity index 100% rename from src/checker/printer.rs rename to src/console/clients/checker/printer.rs diff --git a/src/checker/service.rs b/src/console/clients/checker/service.rs similarity index 98% rename from src/checker/service.rs rename to src/console/clients/checker/service.rs index fd93ed8c0..5f464fbd1 100644 --- a/src/checker/service.rs +++ b/src/console/clients/checker/service.rs @@ -7,7 +7,7 @@ use reqwest::{Client, Url}; use super::config::Configuration; use super::console::Console; -use crate::checker::printer::Printer; +use crate::console::clients::checker::printer::Printer; pub struct Service { pub(crate) config: Arc, diff --git a/src/console/clients/mod.rs b/src/console/clients/mod.rs index a3fd318b2..55ece612b 100644 --- a/src/console/clients/mod.rs +++ b/src/console/clients/mod.rs @@ -1 +1,2 @@ //! Console clients. +pub mod checker; diff --git a/src/lib.rs b/src/lib.rs index 398795d37..b4ad298ac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -471,7 +471,6 @@ //! examples on the integration and unit tests. pub mod app; pub mod bootstrap; -pub mod checker; pub mod console; pub mod core; pub mod servers; From b96c2c37544c2db6d7ef3c9f1fb2070dacb52eb1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jan 2024 12:25:04 +0000 Subject: [PATCH 0214/1297] refactor: [#661] move HTTP Tracker Client mod --- src/bin/http_tracker_client.rs | 95 +----------------------------- src/console/clients/http/app.rs | 100 ++++++++++++++++++++++++++++++++ src/console/clients/http/mod.rs | 1 + src/console/clients/mod.rs | 1 + 4 files changed, 105 insertions(+), 92 deletions(-) create mode 100644 src/console/clients/http/app.rs create mode 100644 src/console/clients/http/mod.rs diff --git a/src/bin/http_tracker_client.rs b/src/bin/http_tracker_client.rs index 4ca194803..0de040549 100644 --- a/src/bin/http_tracker_client.rs +++ b/src/bin/http_tracker_client.rs @@ -1,96 +1,7 @@ -//! HTTP Tracker client: -//! -//! Examples: -//! -//! `Announce` request: -//! -//! ```text -//! cargo run --bin http_tracker_client announce http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -//! -//! `Scrape` request: -//! -//! ```text -//! cargo run --bin http_tracker_client scrape http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -use std::str::FromStr; - -use anyhow::Context; -use clap::{Parser, Subcommand}; -use reqwest::Url; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; -use torrust_tracker::shared::bit_torrent::tracker::http::client::responses::announce::Announce; -use torrust_tracker::shared::bit_torrent::tracker::http::client::responses::scrape; -use torrust_tracker::shared::bit_torrent::tracker::http::client::{requests, Client}; - -#[derive(Parser, Debug)] -#[command(author, version, about, long_about = None)] -struct Args { - #[command(subcommand)] - command: Command, -} - -#[derive(Subcommand, Debug)] -enum Command { - Announce { tracker_url: String, info_hash: String }, - Scrape { tracker_url: String, info_hashes: Vec }, -} +//! Program to make request to HTTP trackers. +use torrust_tracker::console::clients::http::app; #[tokio::main] async fn main() -> anyhow::Result<()> { - let args = Args::parse(); - - match args.command { - Command::Announce { tracker_url, info_hash } => { - announce_command(tracker_url, info_hash).await?; - } - Command::Scrape { - tracker_url, - info_hashes, - } => { - scrape_command(&tracker_url, &info_hashes).await?; - } - } - Ok(()) -} - -async fn announce_command(tracker_url: String, info_hash: String) -> anyhow::Result<()> { - let base_url = Url::parse(&tracker_url).context("failed to parse HTTP tracker base URL")?; - let info_hash = - InfoHash::from_str(&info_hash).expect("Invalid infohash. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); - - let response = Client::new(base_url) - .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) - .await; - - let body = response.bytes().await.unwrap(); - - let announce_response: Announce = serde_bencode::from_bytes(&body) - .unwrap_or_else(|_| panic!("response body should be a valid announce response, got: \"{:#?}\"", &body)); - - let json = serde_json::to_string(&announce_response).context("failed to serialize scrape response into JSON")?; - - println!("{json}"); - - Ok(()) -} - -async fn scrape_command(tracker_url: &str, info_hashes: &[String]) -> anyhow::Result<()> { - let base_url = Url::parse(tracker_url).context("failed to parse HTTP tracker base URL")?; - - let query = requests::scrape::Query::try_from(info_hashes).context("failed to parse infohashes")?; - - let response = Client::new(base_url).scrape(&query).await; - - let body = response.bytes().await.unwrap(); - - let scrape_response = scrape::Response::try_from_bencoded(&body) - .unwrap_or_else(|_| panic!("response body should be a valid scrape response, got: \"{:#?}\"", &body)); - - let json = serde_json::to_string(&scrape_response).context("failed to serialize scrape response into JSON")?; - - println!("{json}"); - - Ok(()) + app::run().await } diff --git a/src/console/clients/http/app.rs b/src/console/clients/http/app.rs new file mode 100644 index 000000000..80db07231 --- /dev/null +++ b/src/console/clients/http/app.rs @@ -0,0 +1,100 @@ +//! HTTP Tracker client: +//! +//! Examples: +//! +//! `Announce` request: +//! +//! ```text +//! cargo run --bin http_tracker_client announce http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! `Scrape` request: +//! +//! ```text +//! cargo run --bin http_tracker_client scrape http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +use std::str::FromStr; + +use anyhow::Context; +use clap::{Parser, Subcommand}; +use reqwest::Url; + +use crate::shared::bit_torrent::info_hash::InfoHash; +use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; +use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; +use crate::shared::bit_torrent::tracker::http::client::responses::scrape; +use crate::shared::bit_torrent::tracker::http::client::{requests, Client}; + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand, Debug)] +enum Command { + Announce { tracker_url: String, info_hash: String }, + Scrape { tracker_url: String, info_hashes: Vec }, +} + +/// # Errors +/// +/// Will return an error if the command fails. +pub async fn run() -> anyhow::Result<()> { + let args = Args::parse(); + + match args.command { + Command::Announce { tracker_url, info_hash } => { + announce_command(tracker_url, info_hash).await?; + } + Command::Scrape { + tracker_url, + info_hashes, + } => { + scrape_command(&tracker_url, &info_hashes).await?; + } + } + + Ok(()) +} + +async fn announce_command(tracker_url: String, info_hash: String) -> anyhow::Result<()> { + let base_url = Url::parse(&tracker_url).context("failed to parse HTTP tracker base URL")?; + let info_hash = + InfoHash::from_str(&info_hash).expect("Invalid infohash. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); + + let response = Client::new(base_url) + .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) + .await; + + let body = response.bytes().await.unwrap(); + + let announce_response: Announce = serde_bencode::from_bytes(&body) + .unwrap_or_else(|_| panic!("response body should be a valid announce response, got: \"{:#?}\"", &body)); + + let json = serde_json::to_string(&announce_response).context("failed to serialize scrape response into JSON")?; + + println!("{json}"); + + Ok(()) +} + +async fn scrape_command(tracker_url: &str, info_hashes: &[String]) -> anyhow::Result<()> { + let base_url = Url::parse(tracker_url).context("failed to parse HTTP tracker base URL")?; + + let query = requests::scrape::Query::try_from(info_hashes).context("failed to parse infohashes")?; + + let response = Client::new(base_url).scrape(&query).await; + + let body = response.bytes().await.unwrap(); + + let scrape_response = scrape::Response::try_from_bencoded(&body) + .unwrap_or_else(|_| panic!("response body should be a valid scrape response, got: \"{:#?}\"", &body)); + + let json = serde_json::to_string(&scrape_response).context("failed to serialize scrape response into JSON")?; + + println!("{json}"); + + Ok(()) +} diff --git a/src/console/clients/http/mod.rs b/src/console/clients/http/mod.rs new file mode 100644 index 000000000..309be6287 --- /dev/null +++ b/src/console/clients/http/mod.rs @@ -0,0 +1 @@ +pub mod app; diff --git a/src/console/clients/mod.rs b/src/console/clients/mod.rs index 55ece612b..278b736e4 100644 --- a/src/console/clients/mod.rs +++ b/src/console/clients/mod.rs @@ -1,2 +1,3 @@ //! Console clients. pub mod checker; +pub mod http; From 47551ff5c029b6110c06d3d408528472edfc376f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jan 2024 12:36:04 +0000 Subject: [PATCH 0215/1297] refactor: [#661] move UDP Tracker Client mod --- src/bin/tracker_checker.rs | 2 +- src/bin/udp_tracker_client.rs | 353 +------------------------------- src/console/clients/mod.rs | 1 + src/console/clients/udp/app.rs | 359 +++++++++++++++++++++++++++++++++ src/console/clients/udp/mod.rs | 1 + 5 files changed, 365 insertions(+), 351 deletions(-) create mode 100644 src/console/clients/udp/app.rs create mode 100644 src/console/clients/udp/mod.rs diff --git a/src/bin/tracker_checker.rs b/src/bin/tracker_checker.rs index 1bda0f54f..87aeedeac 100644 --- a/src/bin/tracker_checker.rs +++ b/src/bin/tracker_checker.rs @@ -1,4 +1,4 @@ -//! Program to run check running trackers. +//! Program to check running trackers. use torrust_tracker::console::clients::checker::app; #[tokio::main] diff --git a/src/bin/udp_tracker_client.rs b/src/bin/udp_tracker_client.rs index 2c8e63cd0..909b296ca 100644 --- a/src/bin/udp_tracker_client.rs +++ b/src/bin/udp_tracker_client.rs @@ -1,354 +1,7 @@ -//! UDP Tracker client: -//! -//! Examples: -//! -//! Announce request: -//! -//! ```text -//! cargo run --bin udp_tracker_client announce 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -//! -//! Announce response: -//! -//! ```json -//! { -//! "transaction_id": -888840697 -//! "announce_interval": 120, -//! "leechers": 0, -//! "seeders": 1, -//! "peers": [ -//! "123.123.123.123:51289" -//! ], -//! } -//! ``` -//! -//! Scrape request: -//! -//! ```text -//! cargo run --bin udp_tracker_client scrape 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -//! -//! Scrape response: -//! -//! ```json -//! { -//! "transaction_id": -888840697, -//! "torrent_stats": [ -//! { -//! "completed": 0, -//! "leechers": 0, -//! "seeders": 0 -//! }, -//! { -//! "completed": 0, -//! "leechers": 0, -//! "seeders": 0 -//! } -//! ] -//! } -//! ``` -//! -//! You can use an URL with instead of the socket address. For example: -//! -//! ```text -//! cargo run --bin udp_tracker_client scrape udp://localhost:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! cargo run --bin udp_tracker_client scrape udp://localhost:6969/scrape 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -//! -//! The protocol (`udp://`) in the URL is mandatory. The path (`\scrape`) is optional. It always uses `\scrape`. -use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs}; -use std::str::FromStr; - -use anyhow::Context; -use aquatic_udp_protocol::common::InfoHash; -use aquatic_udp_protocol::Response::{AnnounceIpv4, AnnounceIpv6, Scrape}; -use aquatic_udp_protocol::{ - AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, Response, - ScrapeRequest, TransactionId, -}; -use clap::{Parser, Subcommand}; -use log::{debug, LevelFilter}; -use serde_json::json; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash as TorrustInfoHash; -use torrust_tracker::shared::bit_torrent::tracker::udp::client::{UdpClient, UdpTrackerClient}; -use url::Url; - -const ASSIGNED_BY_OS: i32 = 0; -const RANDOM_TRANSACTION_ID: i32 = -888_840_697; - -#[derive(Parser, Debug)] -#[command(author, version, about, long_about = None)] -struct Args { - #[command(subcommand)] - command: Command, -} - -#[derive(Subcommand, Debug)] -enum Command { - Announce { - #[arg(value_parser = parse_socket_addr)] - tracker_socket_addr: SocketAddr, - #[arg(value_parser = parse_info_hash)] - info_hash: TorrustInfoHash, - }, - Scrape { - #[arg(value_parser = parse_socket_addr)] - tracker_socket_addr: SocketAddr, - #[arg(value_parser = parse_info_hash, num_args = 1..=74, value_delimiter = ' ')] - info_hashes: Vec, - }, -} +//! Program to make request to UDP trackers. +use torrust_tracker::console::clients::udp::app; #[tokio::main] async fn main() -> anyhow::Result<()> { - setup_logging(LevelFilter::Info); - - let args = Args::parse(); - - // Configuration - let local_port = ASSIGNED_BY_OS; - let local_bind_to = format!("0.0.0.0:{local_port}"); - let transaction_id = RANDOM_TRANSACTION_ID; - - // Bind to local port - debug!("Binding to: {local_bind_to}"); - let udp_client = UdpClient::bind(&local_bind_to).await; - let bound_to = udp_client.socket.local_addr().unwrap(); - debug!("Bound to: {bound_to}"); - - let transaction_id = TransactionId(transaction_id); - - let response = match args.command { - Command::Announce { - tracker_socket_addr, - info_hash, - } => { - let (connection_id, udp_tracker_client) = connect(&tracker_socket_addr, udp_client, transaction_id).await; - - send_announce_request( - connection_id, - transaction_id, - info_hash, - Port(bound_to.port()), - &udp_tracker_client, - ) - .await - } - Command::Scrape { - tracker_socket_addr, - info_hashes, - } => { - let (connection_id, udp_tracker_client) = connect(&tracker_socket_addr, udp_client, transaction_id).await; - send_scrape_request(connection_id, transaction_id, info_hashes, &udp_tracker_client).await - } - }; - - match response { - AnnounceIpv4(announce) => { - let json = json!({ - "transaction_id": announce.transaction_id.0, - "announce_interval": announce.announce_interval.0, - "leechers": announce.leechers.0, - "seeders": announce.seeders.0, - "peers": announce.peers.iter().map(|peer| format!("{}:{}", peer.ip_address, peer.port.0)).collect::>(), - }); - let pretty_json = serde_json::to_string_pretty(&json).unwrap(); - println!("{pretty_json}"); - } - AnnounceIpv6(announce) => { - let json = json!({ - "transaction_id": announce.transaction_id.0, - "announce_interval": announce.announce_interval.0, - "leechers": announce.leechers.0, - "seeders": announce.seeders.0, - "peers6": announce.peers.iter().map(|peer| format!("{}:{}", peer.ip_address, peer.port.0)).collect::>(), - }); - let pretty_json = serde_json::to_string_pretty(&json).unwrap(); - println!("{pretty_json}"); - } - Scrape(scrape) => { - let json = json!({ - "transaction_id": scrape.transaction_id.0, - "torrent_stats": scrape.torrent_stats.iter().map(|torrent_scrape_statistics| json!({ - "seeders": torrent_scrape_statistics.seeders.0, - "completed": torrent_scrape_statistics.completed.0, - "leechers": torrent_scrape_statistics.leechers.0, - })).collect::>(), - }); - let pretty_json = serde_json::to_string_pretty(&json).unwrap(); - println!("{pretty_json}"); - } - _ => println!("{response:#?}"), // todo: serialize to JSON all responses. - } - - Ok(()) -} - -fn setup_logging(level: LevelFilter) { - if let Err(_err) = fern::Dispatch::new() - .format(|out, message, record| { - out.finish(format_args!( - "{} [{}][{}] {}", - chrono::Local::now().format("%+"), - record.target(), - record.level(), - message - )); - }) - .level(level) - .chain(std::io::stdout()) - .apply() - { - panic!("Failed to initialize logging.") - } - - debug!("logging initialized."); -} - -fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { - debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); - - // Check if the address is a valid URL. If so, extract the host and port. - let resolved_addr = if let Ok(url) = Url::parse(tracker_socket_addr_str) { - debug!("Tracker socket address URL: {url:?}"); - - let host = url - .host_str() - .with_context(|| format!("invalid host in URL: `{tracker_socket_addr_str}`"))? - .to_owned(); - - let port = url - .port() - .with_context(|| format!("port not found in URL: `{tracker_socket_addr_str}`"))? - .to_owned(); - - (host, port) - } else { - // If not a URL, assume it's a host:port pair. - - let parts: Vec<&str> = tracker_socket_addr_str.split(':').collect(); - - if parts.len() != 2 { - return Err(anyhow::anyhow!( - "invalid address format: `{}`. Expected format is host:port", - tracker_socket_addr_str - )); - } - - let host = parts[0].to_owned(); - - let port = parts[1] - .parse::() - .with_context(|| format!("invalid port: `{}`", parts[1]))? - .to_owned(); - - (host, port) - }; - - debug!("Resolved address: {resolved_addr:#?}"); - - // Perform DNS resolution. - let socket_addrs: Vec<_> = resolved_addr.to_socket_addrs()?.collect(); - if socket_addrs.is_empty() { - Err(anyhow::anyhow!("DNS resolution failed for `{}`", tracker_socket_addr_str)) - } else { - Ok(socket_addrs[0]) - } -} - -fn parse_info_hash(info_hash_str: &str) -> anyhow::Result { - TorrustInfoHash::from_str(info_hash_str) - .map_err(|e| anyhow::Error::msg(format!("failed to parse info-hash `{info_hash_str}`: {e:?}"))) -} - -async fn connect( - tracker_socket_addr: &SocketAddr, - udp_client: UdpClient, - transaction_id: TransactionId, -) -> (ConnectionId, UdpTrackerClient) { - debug!("Connecting to tracker: udp://{tracker_socket_addr}"); - - udp_client.connect(&tracker_socket_addr.to_string()).await; - - let udp_tracker_client = UdpTrackerClient { udp_client }; - - let connection_id = send_connection_request(transaction_id, &udp_tracker_client).await; - - (connection_id, udp_tracker_client) -} - -async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrackerClient) -> ConnectionId { - debug!("Sending connection request with transaction id: {transaction_id:#?}"); - - let connect_request = ConnectRequest { transaction_id }; - - client.send(connect_request.into()).await; - - let response = client.receive().await; - - debug!("connection request response:\n{response:#?}"); - - match response { - Response::Connect(connect_response) => connect_response.connection_id, - _ => panic!("error connecting to udp server. Unexpected response"), - } -} - -async fn send_announce_request( - connection_id: ConnectionId, - transaction_id: TransactionId, - info_hash: TorrustInfoHash, - port: Port, - client: &UdpTrackerClient, -) -> Response { - debug!("Sending announce request with transaction id: {transaction_id:#?}"); - - let announce_request = AnnounceRequest { - connection_id, - transaction_id, - info_hash: InfoHash(info_hash.bytes()), - peer_id: PeerId(*b"-qB00000000000000001"), - bytes_downloaded: NumberOfBytes(0i64), - bytes_uploaded: NumberOfBytes(0i64), - bytes_left: NumberOfBytes(0i64), - event: AnnounceEvent::Started, - ip_address: Some(Ipv4Addr::new(0, 0, 0, 0)), - key: PeerKey(0u32), - peers_wanted: NumberOfPeers(1i32), - port, - }; - - client.send(announce_request.into()).await; - - let response = client.receive().await; - - debug!("announce request response:\n{response:#?}"); - - response -} - -async fn send_scrape_request( - connection_id: ConnectionId, - transaction_id: TransactionId, - info_hashes: Vec, - client: &UdpTrackerClient, -) -> Response { - debug!("Sending scrape request with transaction id: {transaction_id:#?}"); - - let scrape_request = ScrapeRequest { - connection_id, - transaction_id, - info_hashes: info_hashes - .iter() - .map(|torrust_info_hash| InfoHash(torrust_info_hash.bytes())) - .collect(), - }; - - client.send(scrape_request.into()).await; - - let response = client.receive().await; - - debug!("scrape request response:\n{response:#?}"); - - response + app::run().await } diff --git a/src/console/clients/mod.rs b/src/console/clients/mod.rs index 278b736e4..8492f8ba5 100644 --- a/src/console/clients/mod.rs +++ b/src/console/clients/mod.rs @@ -1,3 +1,4 @@ //! Console clients. pub mod checker; pub mod http; +pub mod udp; diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs new file mode 100644 index 000000000..e9c8b5274 --- /dev/null +++ b/src/console/clients/udp/app.rs @@ -0,0 +1,359 @@ +//! UDP Tracker client: +//! +//! Examples: +//! +//! Announce request: +//! +//! ```text +//! cargo run --bin udp_tracker_client announce 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! Announce response: +//! +//! ```json +//! { +//! "transaction_id": -888840697 +//! "announce_interval": 120, +//! "leechers": 0, +//! "seeders": 1, +//! "peers": [ +//! "123.123.123.123:51289" +//! ], +//! } +//! ``` +//! +//! Scrape request: +//! +//! ```text +//! cargo run --bin udp_tracker_client scrape 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! Scrape response: +//! +//! ```json +//! { +//! "transaction_id": -888840697, +//! "torrent_stats": [ +//! { +//! "completed": 0, +//! "leechers": 0, +//! "seeders": 0 +//! }, +//! { +//! "completed": 0, +//! "leechers": 0, +//! "seeders": 0 +//! } +//! ] +//! } +//! ``` +//! +//! You can use an URL with instead of the socket address. For example: +//! +//! ```text +//! cargo run --bin udp_tracker_client scrape udp://localhost:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! cargo run --bin udp_tracker_client scrape udp://localhost:6969/scrape 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! The protocol (`udp://`) in the URL is mandatory. The path (`\scrape`) is optional. It always uses `\scrape`. +use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs}; +use std::str::FromStr; + +use anyhow::Context; +use aquatic_udp_protocol::common::InfoHash; +use aquatic_udp_protocol::Response::{AnnounceIpv4, AnnounceIpv6, Scrape}; +use aquatic_udp_protocol::{ + AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, Response, + ScrapeRequest, TransactionId, +}; +use clap::{Parser, Subcommand}; +use log::{debug, LevelFilter}; +use serde_json::json; +use url::Url; + +use crate::shared::bit_torrent::info_hash::InfoHash as TorrustInfoHash; +use crate::shared::bit_torrent::tracker::udp::client::{UdpClient, UdpTrackerClient}; + +const ASSIGNED_BY_OS: i32 = 0; +const RANDOM_TRANSACTION_ID: i32 = -888_840_697; + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand, Debug)] +enum Command { + Announce { + #[arg(value_parser = parse_socket_addr)] + tracker_socket_addr: SocketAddr, + #[arg(value_parser = parse_info_hash)] + info_hash: TorrustInfoHash, + }, + Scrape { + #[arg(value_parser = parse_socket_addr)] + tracker_socket_addr: SocketAddr, + #[arg(value_parser = parse_info_hash, num_args = 1..=74, value_delimiter = ' ')] + info_hashes: Vec, + }, +} + +/// # Errors +/// +/// Will return an error if the command fails. +/// +/// +pub async fn run() -> anyhow::Result<()> { + setup_logging(LevelFilter::Info); + + let args = Args::parse(); + + // Configuration + let local_port = ASSIGNED_BY_OS; + let local_bind_to = format!("0.0.0.0:{local_port}"); + let transaction_id = RANDOM_TRANSACTION_ID; + + // Bind to local port + debug!("Binding to: {local_bind_to}"); + let udp_client = UdpClient::bind(&local_bind_to).await; + let bound_to = udp_client.socket.local_addr().context("binding local address")?; + debug!("Bound to: {bound_to}"); + + let transaction_id = TransactionId(transaction_id); + + let response = match args.command { + Command::Announce { + tracker_socket_addr, + info_hash, + } => { + let (connection_id, udp_tracker_client) = connect(&tracker_socket_addr, udp_client, transaction_id).await; + + send_announce_request( + connection_id, + transaction_id, + info_hash, + Port(bound_to.port()), + &udp_tracker_client, + ) + .await + } + Command::Scrape { + tracker_socket_addr, + info_hashes, + } => { + let (connection_id, udp_tracker_client) = connect(&tracker_socket_addr, udp_client, transaction_id).await; + send_scrape_request(connection_id, transaction_id, info_hashes, &udp_tracker_client).await + } + }; + + match response { + AnnounceIpv4(announce) => { + let json = json!({ + "transaction_id": announce.transaction_id.0, + "announce_interval": announce.announce_interval.0, + "leechers": announce.leechers.0, + "seeders": announce.seeders.0, + "peers": announce.peers.iter().map(|peer| format!("{}:{}", peer.ip_address, peer.port.0)).collect::>(), + }); + let pretty_json = serde_json::to_string_pretty(&json).context("announce IPv4 response JSON serialization")?; + println!("{pretty_json}"); + } + AnnounceIpv6(announce) => { + let json = json!({ + "transaction_id": announce.transaction_id.0, + "announce_interval": announce.announce_interval.0, + "leechers": announce.leechers.0, + "seeders": announce.seeders.0, + "peers6": announce.peers.iter().map(|peer| format!("{}:{}", peer.ip_address, peer.port.0)).collect::>(), + }); + let pretty_json = serde_json::to_string_pretty(&json).context("announce IPv6 response JSON serialization")?; + println!("{pretty_json}"); + } + Scrape(scrape) => { + let json = json!({ + "transaction_id": scrape.transaction_id.0, + "torrent_stats": scrape.torrent_stats.iter().map(|torrent_scrape_statistics| json!({ + "seeders": torrent_scrape_statistics.seeders.0, + "completed": torrent_scrape_statistics.completed.0, + "leechers": torrent_scrape_statistics.leechers.0, + })).collect::>(), + }); + let pretty_json = serde_json::to_string_pretty(&json).context("scrape response JSON serialization")?; + println!("{pretty_json}"); + } + _ => println!("{response:#?}"), // todo: serialize to JSON all responses. + }; + + Ok(()) +} + +fn setup_logging(level: LevelFilter) { + if let Err(_err) = fern::Dispatch::new() + .format(|out, message, record| { + out.finish(format_args!( + "{} [{}][{}] {}", + chrono::Local::now().format("%+"), + record.target(), + record.level(), + message + )); + }) + .level(level) + .chain(std::io::stdout()) + .apply() + { + panic!("Failed to initialize logging.") + } + + debug!("logging initialized."); +} + +fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { + debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); + + // Check if the address is a valid URL. If so, extract the host and port. + let resolved_addr = if let Ok(url) = Url::parse(tracker_socket_addr_str) { + debug!("Tracker socket address URL: {url:?}"); + + let host = url + .host_str() + .with_context(|| format!("invalid host in URL: `{tracker_socket_addr_str}`"))? + .to_owned(); + + let port = url + .port() + .with_context(|| format!("port not found in URL: `{tracker_socket_addr_str}`"))? + .to_owned(); + + (host, port) + } else { + // If not a URL, assume it's a host:port pair. + + let parts: Vec<&str> = tracker_socket_addr_str.split(':').collect(); + + if parts.len() != 2 { + return Err(anyhow::anyhow!( + "invalid address format: `{}`. Expected format is host:port", + tracker_socket_addr_str + )); + } + + let host = parts[0].to_owned(); + + let port = parts[1] + .parse::() + .with_context(|| format!("invalid port: `{}`", parts[1]))? + .to_owned(); + + (host, port) + }; + + debug!("Resolved address: {resolved_addr:#?}"); + + // Perform DNS resolution. + let socket_addrs: Vec<_> = resolved_addr.to_socket_addrs()?.collect(); + if socket_addrs.is_empty() { + Err(anyhow::anyhow!("DNS resolution failed for `{}`", tracker_socket_addr_str)) + } else { + Ok(socket_addrs[0]) + } +} + +fn parse_info_hash(info_hash_str: &str) -> anyhow::Result { + TorrustInfoHash::from_str(info_hash_str) + .map_err(|e| anyhow::Error::msg(format!("failed to parse info-hash `{info_hash_str}`: {e:?}"))) +} + +async fn connect( + tracker_socket_addr: &SocketAddr, + udp_client: UdpClient, + transaction_id: TransactionId, +) -> (ConnectionId, UdpTrackerClient) { + debug!("Connecting to tracker: udp://{tracker_socket_addr}"); + + udp_client.connect(&tracker_socket_addr.to_string()).await; + + let udp_tracker_client = UdpTrackerClient { udp_client }; + + let connection_id = send_connection_request(transaction_id, &udp_tracker_client).await; + + (connection_id, udp_tracker_client) +} + +async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrackerClient) -> ConnectionId { + debug!("Sending connection request with transaction id: {transaction_id:#?}"); + + let connect_request = ConnectRequest { transaction_id }; + + client.send(connect_request.into()).await; + + let response = client.receive().await; + + debug!("connection request response:\n{response:#?}"); + + match response { + Response::Connect(connect_response) => connect_response.connection_id, + _ => panic!("error connecting to udp server. Unexpected response"), + } +} + +async fn send_announce_request( + connection_id: ConnectionId, + transaction_id: TransactionId, + info_hash: TorrustInfoHash, + port: Port, + client: &UdpTrackerClient, +) -> Response { + debug!("Sending announce request with transaction id: {transaction_id:#?}"); + + let announce_request = AnnounceRequest { + connection_id, + transaction_id, + info_hash: InfoHash(info_hash.bytes()), + peer_id: PeerId(*b"-qB00000000000000001"), + bytes_downloaded: NumberOfBytes(0i64), + bytes_uploaded: NumberOfBytes(0i64), + bytes_left: NumberOfBytes(0i64), + event: AnnounceEvent::Started, + ip_address: Some(Ipv4Addr::new(0, 0, 0, 0)), + key: PeerKey(0u32), + peers_wanted: NumberOfPeers(1i32), + port, + }; + + client.send(announce_request.into()).await; + + let response = client.receive().await; + + debug!("announce request response:\n{response:#?}"); + + response +} + +async fn send_scrape_request( + connection_id: ConnectionId, + transaction_id: TransactionId, + info_hashes: Vec, + client: &UdpTrackerClient, +) -> Response { + debug!("Sending scrape request with transaction id: {transaction_id:#?}"); + + let scrape_request = ScrapeRequest { + connection_id, + transaction_id, + info_hashes: info_hashes + .iter() + .map(|torrust_info_hash| InfoHash(torrust_info_hash.bytes())) + .collect(), + }; + + client.send(scrape_request.into()).await; + + let response = client.receive().await; + + debug!("scrape request response:\n{response:#?}"); + + response +} diff --git a/src/console/clients/udp/mod.rs b/src/console/clients/udp/mod.rs new file mode 100644 index 000000000..309be6287 --- /dev/null +++ b/src/console/clients/udp/mod.rs @@ -0,0 +1 @@ +pub mod app; From cb5bb685d8e82ab8d667015c615fa87dccefd04b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jan 2024 14:03:07 +0000 Subject: [PATCH 0216/1297] feat: [#640] Tracker Chekcer: announce check --- src/console/clients/checker/service.rs | 68 +++++++++++++++++++------- 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/src/console/clients/checker/service.rs b/src/console/clients/checker/service.rs index 5f464fbd1..02bf1926b 100644 --- a/src/console/clients/checker/service.rs +++ b/src/console/clients/checker/service.rs @@ -1,13 +1,18 @@ use std::net::SocketAddr; +use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use colored::Colorize; -use reqwest::{Client, Url}; +use reqwest::{Client as HttpClient, Url}; use super::config::Configuration; use super::console::Console; use crate::console::clients::checker::printer::Printer; +use crate::shared::bit_torrent::info_hash::InfoHash; +use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; +use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; +use crate::shared::bit_torrent::tracker::http::client::Client; pub struct Service { pub(crate) config: Arc, @@ -19,7 +24,7 @@ pub type CheckResult = Result<(), CheckError>; #[derive(Debug)] pub enum CheckError { UdpError, - HttpError, + HttpError { url: Url }, HealthCheckError { url: Url }, } @@ -30,10 +35,15 @@ impl Service { pub async fn run_checks(&self) -> Vec { self.console.println("Running checks for trackers ..."); + let mut check_results = vec![]; + self.check_udp_trackers(); - self.check_http_trackers(); - self.run_health_checks().await + self.check_http_trackers(&mut check_results).await; + + self.run_health_checks(&mut check_results).await; + + check_results } fn check_udp_trackers(&self) { @@ -44,27 +54,26 @@ impl Service { } } - fn check_http_trackers(&self) { + async fn check_http_trackers(&self, check_results: &mut Vec) { self.console.println("HTTP trackers ..."); for http_tracker in &self.config.http_trackers { - self.check_http_tracker(http_tracker); + match self.check_http_tracker(http_tracker).await { + Ok(()) => check_results.push(Ok(())), + Err(err) => check_results.push(Err(err)), + } } } - async fn run_health_checks(&self) -> Vec { + async fn run_health_checks(&self, check_results: &mut Vec) { self.console.println("Health checks ..."); - 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(()) => check_results.push(Ok(())), Err(err) => check_results.push(Err(err)), } } - - check_results } fn check_udp_tracker(&self, address: &SocketAddr) { @@ -72,19 +81,40 @@ impl Service { // - Make announce request // - Make scrape request self.console - .println(&format!("{} - UDP tracker at {:?} is OK (TODO)", "✓".green(), address)); + .println(&format!("{} - UDP tracker at udp://{:?} is OK (TODO)", "✓".green(), address)); } - fn check_http_tracker(&self, url: &Url) { - // todo: - // - Make announce request - // - Make scrape request - self.console - .println(&format!("{} - HTTP tracker at {} is OK (TODO)", "✓".green(), url)); + async fn check_http_tracker(&self, url: &Url) -> Result<(), CheckError> { + let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // # DevSkim: ignore DS173237 + let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); + + // Announce request + + let response = Client::new(url.clone()) + .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) + .await; + + if let Ok(body) = response.bytes().await { + if let Ok(_announce_response) = serde_bencode::from_bytes::(&body) { + self.console.println(&format!("{} - Announce at {} is OK", "✓".green(), url)); + + Ok(()) + } else { + self.console.println(&format!("{} - Announce at {} failing", "✗".red(), url)); + Err(CheckError::HttpError { url: url.clone() }) + } + } else { + self.console.println(&format!("{} - Announce at {} failing", "✗".red(), url)); + Err(CheckError::HttpError { url: url.clone() }) + } + + // Scrape request + + // todo } async fn run_health_check(&self, url: Url) -> Result<(), CheckError> { - let client = Client::builder().timeout(Duration::from_secs(5)).build().unwrap(); + let client = HttpClient::builder().timeout(Duration::from_secs(5)).build().unwrap(); match client.get(url.clone()).send().await { Ok(response) => { From 4456203433d7c4aef463371b2e71ce9e69d7b3c0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jan 2024 15:59:20 +0000 Subject: [PATCH 0217/1297] feat: [#640] Tracker Chekcer: scrape check --- src/console/clients/checker/service.rs | 88 ++++++++++++++----- .../tracker/http/client/requests/scrape.rs | 17 ++++ 2 files changed, 85 insertions(+), 20 deletions(-) diff --git a/src/console/clients/checker/service.rs b/src/console/clients/checker/service.rs index 02bf1926b..1cb4725e0 100644 --- a/src/console/clients/checker/service.rs +++ b/src/console/clients/checker/service.rs @@ -12,7 +12,8 @@ use crate::console::clients::checker::printer::Printer; use crate::shared::bit_torrent::info_hash::InfoHash; use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; -use crate::shared::bit_torrent::tracker::http::client::Client; +use crate::shared::bit_torrent::tracker::http::client::responses::scrape; +use crate::shared::bit_torrent::tracker::http::client::{requests, Client}; pub struct Service { pub(crate) config: Arc, @@ -58,9 +59,32 @@ impl Service { self.console.println("HTTP trackers ..."); for http_tracker in &self.config.http_trackers { - match self.check_http_tracker(http_tracker).await { - Ok(()) => check_results.push(Ok(())), - Err(err) => check_results.push(Err(err)), + let colored_tracker_url = http_tracker.to_string().yellow(); + + match self.check_http_announce(http_tracker).await { + Ok(()) => { + check_results.push(Ok(())); + self.console + .println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); + } + Err(err) => { + check_results.push(Err(err)); + self.console + .println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); + } + } + + match self.check_http_scrape(http_tracker).await { + Ok(()) => { + check_results.push(Ok(())); + self.console + .println(&format!("{} - Scrape at {} is OK", "✓".green(), colored_tracker_url)); + } + Err(err) => { + check_results.push(Err(err)); + self.console + .println(&format!("{} - Scrape at {} is failing", "✗".red(), colored_tracker_url)); + } } } } @@ -80,57 +104,81 @@ impl Service { // todo: // - Make announce request // - Make scrape request - self.console - .println(&format!("{} - UDP tracker at udp://{:?} is OK (TODO)", "✓".green(), address)); + + let colored_address = address.to_string().yellow(); + + self.console.println(&format!( + "{} - UDP tracker at udp://{} is OK ({})", + "✓".green(), + colored_address, + "TODO".red(), + )); } - async fn check_http_tracker(&self, url: &Url) -> Result<(), CheckError> { + async fn check_http_announce(&self, url: &Url) -> Result<(), CheckError> { let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // # DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); - // Announce request - let response = Client::new(url.clone()) .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) .await; if let Ok(body) = response.bytes().await { if let Ok(_announce_response) = serde_bencode::from_bytes::(&body) { - self.console.println(&format!("{} - Announce at {} is OK", "✓".green(), url)); - Ok(()) } else { - self.console.println(&format!("{} - Announce at {} failing", "✗".red(), url)); Err(CheckError::HttpError { url: url.clone() }) } } else { - self.console.println(&format!("{} - Announce at {} failing", "✗".red(), url)); Err(CheckError::HttpError { url: url.clone() }) } + } + + async fn check_http_scrape(&self, url: &Url) -> Result<(), CheckError> { + let info_hashes: Vec = vec!["9c38422213e30bff212b30c360d26f9a02136422".to_string()]; // # DevSkim: ignore DS173237 + let query = requests::scrape::Query::try_from(info_hashes).expect("a valid array of info-hashes is required"); - // Scrape request + let response = Client::new(url.clone()).scrape(&query).await; - // todo + if let Ok(body) = response.bytes().await { + if let Ok(_scrape_response) = scrape::Response::try_from_bencoded(&body) { + Ok(()) + } else { + Err(CheckError::HttpError { url: url.clone() }) + } + } else { + Err(CheckError::HttpError { url: url.clone() }) + } } async fn run_health_check(&self, url: Url) -> Result<(), CheckError> { let client = HttpClient::builder().timeout(Duration::from_secs(5)).build().unwrap(); + let colored_url = url.to_string().yellow(); + match client.get(url.clone()).send().await { Ok(response) => { if response.status().is_success() { self.console - .println(&format!("{} - Health API at {} is OK", "✓".green(), url)); + .println(&format!("{} - Health API at {} is OK", "✓".green(), colored_url)); Ok(()) } else { - self.console - .eprintln(&format!("{} - Health API at {} failing: {:?}", "✗".red(), url, response)); + self.console.eprintln(&format!( + "{} - Health API at {} is failing: {:?}", + "✗".red(), + colored_url, + response + )); Err(CheckError::HealthCheckError { url }) } } Err(err) => { - self.console - .eprintln(&format!("{} - Health API at {} failing: {:?}", "✗".red(), url, err)); + self.console.eprintln(&format!( + "{} - Health API at {} is failing: {:?}", + "✗".red(), + colored_url, + err + )); Err(CheckError::HealthCheckError { url }) } } diff --git a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs index 771b3a45e..d0268d1f8 100644 --- a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs +++ b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs @@ -45,6 +45,23 @@ impl TryFrom<&[String]> for Query { } } +impl TryFrom> for Query { + type Error = ConversionError; + + fn try_from(info_hashes: Vec) -> Result { + let mut validated_info_hashes: Vec = Vec::new(); + + for info_hash in info_hashes { + let validated_info_hash = InfoHash::from_str(&info_hash).map_err(|_| ConversionError(info_hash.clone()))?; + validated_info_hashes.push(validated_info_hash.0); + } + + Ok(Self { + info_hash: validated_info_hashes, + }) + } +} + /// HTTP Tracker Scrape Request: /// /// From e9e0ded853e5fdb807924e7ee697337aba0952e3 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 1 Feb 2024 09:14:10 +0800 Subject: [PATCH 0218/1297] chore: update deps (Cargo Lockfile) Updating crates.io index Updating anstyle v1.0.4 -> v1.0.5 Updating async-compression v0.4.5 -> v0.4.6 Updating axum v0.7.3 -> v0.7.4 Updating axum-core v0.4.2 -> v0.4.3 Updating axum-macros v0.4.0 -> v0.4.1 Updating base64 v0.21.5 -> v0.21.7 Updating bindgen v0.69.1 -> v0.69.2 Updating bitflags v2.4.1 -> v2.4.2 Updating borsh v1.3.0 -> v1.3.1 Updating borsh-derive v1.3.0 -> v1.3.1 Updating chrono v0.4.31 -> v0.4.33 Updating ciborium v0.2.1 -> v0.2.2 Updating ciborium-io v0.2.1 -> v0.2.2 Updating ciborium-ll v0.2.1 -> v0.2.2 Updating cpufeatures v0.2.11 -> v0.2.12 Updating crossbeam v0.8.3 -> v0.8.4 Updating crossbeam-channel v0.5.10 -> v0.5.11 Updating crossbeam-deque v0.8.4 -> v0.8.5 Updating crossbeam-epoch v0.9.17 -> v0.9.18 Updating crossbeam-queue v0.3.10 -> v0.3.11 Updating crossbeam-utils v0.8.18 -> v0.8.19 Adding crunchy v0.2.2 Updating darling v0.20.3 -> v0.20.5 Updating darling_core v0.20.3 -> v0.20.5 Updating darling_macro v0.20.3 -> v0.20.5 Updating derive_utils v0.13.2 -> v0.14.1 Updating getrandom v0.2.11 -> v0.2.12 Removing h2 v0.3.22 Removing h2 v0.4.0 Adding h2 v0.3.24 Adding h2 v0.4.2 Updating half v1.8.2 -> v2.3.1 Updating hermit-abi v0.3.3 -> v0.3.4 Updating hyper-util v0.1.2 -> v0.1.3 Updating indexmap v2.1.0 -> v2.2.2 Updating io-enum v1.1.1 -> v1.1.3 Removing itertools v0.11.0 Updating js-sys v0.3.66 -> v0.3.67 Updating libc v0.2.151 -> v0.2.153 Updating libz-sys v1.1.12 -> v1.1.15 Updating linux-raw-sys v0.4.12 -> v0.4.13 Updating local-ip-address v0.5.6 -> v0.5.7 Updating multimap v0.9.1 -> v0.10.0 Updating openssl v0.10.62 -> v0.10.63 Updating openssl-src v300.2.1+3.2.0 -> v300.2.2+3.2.1 Updating openssl-sys v0.9.98 -> v0.9.99 Updating pest v2.7.5 -> v2.7.6 Updating pest_derive v2.7.5 -> v2.7.6 Updating pest_generator v2.7.5 -> v2.7.6 Updating pest_meta v2.7.5 -> v2.7.6 Updating pin-project v1.1.3 -> v1.1.4 Updating pin-project-internal v1.1.3 -> v1.1.4 Updating pkg-config v0.3.28 -> v0.3.29 Updating predicates v3.0.4 -> v3.1.0 Updating proc-macro-crate v2.0.0 -> v3.1.0 Updating proc-macro2 v1.0.75 -> v1.0.78 Updating rayon v1.8.0 -> v1.8.1 Updating rayon-core v1.12.0 -> v1.12.1 Updating regex v1.10.2 -> v1.10.3 Updating regex-automata v0.4.3 -> v0.4.5 Updating reqwest v0.11.23 -> v0.11.24 Updating rust_decimal v1.33.1 -> v1.34.0 Updating rustix v0.38.28 -> v0.38.30 Adding rustls-pemfile v1.0.4 Updating serde v1.0.194 -> v1.0.196 Updating serde_derive v1.0.194 -> v1.0.196 Updating serde_json v1.0.110 -> v1.0.113 Updating serde_with v3.4.0 -> v3.6.0 Updating serde_with_macros v3.4.0 -> v3.6.0 Updating shlex v1.2.0 -> v1.3.0 Updating smallvec v1.11.2 -> v1.13.1 Updating syn v2.0.47 -> v2.0.48 Updating termcolor v1.4.0 -> v1.4.1 Updating toml v0.8.8 -> v0.8.9 Removing toml_edit v0.20.7 Removing toml_edit v0.21.0 Adding toml_edit v0.21.1 Updating tower-http v0.5.0 -> v0.5.1 Updating unicode-bidi v0.3.14 -> v0.3.15 Updating uuid v1.6.1 -> v1.7.0 Updating wasm-bindgen v0.2.89 -> v0.2.90 Updating wasm-bindgen-backend v0.2.89 -> v0.2.90 Updating wasm-bindgen-futures v0.4.39 -> v0.4.40 Updating wasm-bindgen-macro v0.2.89 -> v0.2.90 Updating wasm-bindgen-macro-support v0.2.89 -> v0.2.90 Updating wasm-bindgen-shared v0.2.89 -> v0.2.90 Updating web-sys v0.3.66 -> v0.3.67 Updating winnow v0.5.32 -> v0.5.36 --- Cargo.lock | 486 ++++++++++++++++++++++++++--------------------------- 1 file changed, 237 insertions(+), 249 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1af4d5b3e..fa1d724e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -107,9 +107,9 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87" +checksum = "2faccea4cc4ab4a667ce676a30e8ec13922a692c99bb8f5b11f1502c72e04220" [[package]] name = "anstyle-parse" @@ -169,9 +169,9 @@ checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "async-compression" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc2d0cfb2a7388d34f590e76686704c494ed7aaceed62ee1ba35cbf363abc2a5" +checksum = "a116f46a969224200a0a97f29cfd4c50e7534e4b4826bd23ea2c3c533039c82c" dependencies = [ "brotli", "flate2", @@ -191,7 +191,7 @@ checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -202,9 +202,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axum" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d09dbe0e490df5da9d69b36dca48a76635288a82f92eca90024883a56202026d" +checksum = "1236b4b292f6c4d6dc34604bb5120d85c3fe1d1aa596bd5cc52ca054d13e7b9e" dependencies = [ "async-trait", "axum-core", @@ -248,9 +248,9 @@ dependencies = [ [[package]] name = "axum-core" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e87c8503f93e6d144ee5690907ba22db7ba79ab001a932ab99034f0fe836b3df" +checksum = "a15c63fd72d41492dc4f497196f5da1fb04fb7529e631d73630d1b491e47a2e3" dependencies = [ "async-trait", "bytes", @@ -269,14 +269,14 @@ dependencies = [ [[package]] name = "axum-macros" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a2edad600410b905404c594e2523549f1bcd4bded1e252c8f74524ccce0b867" +checksum = "00c055ee2d014ae5981ce1016374e8213682aa14d9bf40e48ab48b5f3ef20eaa" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -295,7 +295,7 @@ dependencies = [ "hyper-util", "pin-project-lite", "rustls", - "rustls-pemfile", + "rustls-pemfile 2.0.0", "tokio", "tokio-rustls", "tower", @@ -325,9 +325,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "base64" -version = "0.21.5" +version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35636a1494ede3b646cc98f74f8e62c773a38a659ebc777a2cf26b9b74171df9" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" [[package]] name = "bigdecimal" @@ -348,11 +348,11 @@ checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" [[package]] name = "bindgen" -version = "0.69.1" +version = "0.69.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ffcebc3849946a7170a05992aac39da343a90676ab392c51a4280981d6379c2" +checksum = "a4c69fae65a523209d34240b60abe0c42d33d1045d445c0839d8a4894a736e2d" dependencies = [ - "bitflags 2.4.1", + "bitflags 2.4.2", "cexpr", "clang-sys", "lazy_static", @@ -363,7 +363,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -374,9 +374,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.4.1" +version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07" +checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" [[package]] name = "bitvec" @@ -401,9 +401,9 @@ dependencies = [ [[package]] name = "borsh" -version = "1.3.0" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d4d6dafc1a3bb54687538972158f07b2c948bc57d5890df22c0739098b3028" +checksum = "f58b559fd6448c6e2fd0adb5720cd98a2506594cafa4737ff98c396f3e82f667" dependencies = [ "borsh-derive", "cfg_aliases", @@ -411,15 +411,15 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.3.0" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf4918709cc4dd777ad2b6303ed03cb37f3ca0ccede8c1b0d28ac6db8f4710e0" +checksum = "7aadb5b6ccbd078890f6d7003694e33816e6b784358f18e15e7e6d9f065a57cd" dependencies = [ "once_cell", - "proc-macro-crate 2.0.0", + "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", "syn_derive", ] @@ -529,22 +529,22 @@ checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" [[package]] name = "chrono" -version = "0.4.31" +version = "0.4.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" +checksum = "9f13690e35a5e4ace198e7beea2895d29f3a9cc55015fcebe6336bd2010af9eb" dependencies = [ "android-tzdata", "iana-time-zone", "num-traits", "serde", - "windows-targets 0.48.5", + "windows-targets 0.52.0", ] [[package]] name = "ciborium" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "effd91f6c78e5a4ace8a5d3c0b6bfaec9e2baaef55f3efc00e45fb2e477ee926" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" dependencies = [ "ciborium-io", "ciborium-ll", @@ -553,15 +553,15 @@ dependencies = [ [[package]] name = "ciborium-io" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdf919175532b369853f5d5e20b26b43112613fd6fe7aee757e35f7a44642656" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" [[package]] name = "ciborium-ll" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "defaa24ecc093c77630e6c15e17c51f5e187bf35ee514f4e2d67baaa96dae22b" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" dependencies = [ "ciborium-io", "half", @@ -609,7 +609,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -686,9 +686,9 @@ checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" [[package]] name = "cpufeatures" -version = "0.2.11" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce420fe07aecd3e67c5f910618fe65e94158f6dcc0adf44e00d69ce2bdfe0fd0" +checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504" dependencies = [ "libc", ] @@ -715,7 +715,7 @@ dependencies = [ "criterion-plot", "futures", "is-terminal", - "itertools 0.10.5", + "itertools", "num-traits", "once_cell", "oorandom", @@ -737,16 +737,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" dependencies = [ "cast", - "itertools 0.10.5", + "itertools", ] [[package]] name = "crossbeam" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6eb9105919ca8e40d437fc9cbb8f1975d916f1bd28afe795a48aae32a2cc8920" +checksum = "1137cd7e7fc0fb5d3c5a8678be38ec56e819125d8d7907411fe24ccb943faca8" dependencies = [ - "cfg-if", "crossbeam-channel", "crossbeam-deque", "crossbeam-epoch", @@ -756,54 +755,52 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.10" +version = "0.5.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82a9b73a36529d9c47029b9fb3a6f0ea3cc916a261195352ba19e770fc1748b2" +checksum = "176dc175b78f56c0f321911d9c8eb2b77a78a4860b9c19db83835fea1a46649b" dependencies = [ - "cfg-if", "crossbeam-utils", ] [[package]] name = "crossbeam-deque" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fca89a0e215bab21874660c67903c5f143333cab1da83d041c7ded6053774751" +checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" dependencies = [ - "cfg-if", "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" -version = "0.9.17" +version = "0.9.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e3681d554572a651dda4186cd47240627c3d0114d45a95f6ad27f2f22e7548d" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" dependencies = [ - "autocfg", - "cfg-if", "crossbeam-utils", ] [[package]] name = "crossbeam-queue" -version = "0.3.10" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adc6598521bb5a83d491e8c1fe51db7296019d2ca3cb93cc6c2a20369a4d78a2" +checksum = "df0346b5d5e76ac2fe4e327c5fd1118d6be7c51dfb18f9b7922923f287471e35" dependencies = [ - "cfg-if", "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.18" +version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3a430a770ebd84726f584a90ee7f020d28db52c6d02138900f22341f866d39c" -dependencies = [ - "cfg-if", -] +checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345" + +[[package]] +name = "crunchy" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" [[package]] name = "crypto-common" @@ -817,9 +814,9 @@ dependencies = [ [[package]] name = "darling" -version = "0.20.3" +version = "0.20.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e" +checksum = "fc5d6b04b3fd0ba9926f945895de7d806260a2d7431ba82e7edaecb043c4c6b8" dependencies = [ "darling_core", "darling_macro", @@ -827,27 +824,27 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.20.3" +version = "0.20.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621" +checksum = "04e48a959bcd5c761246f5d090ebc2fbf7b9cd527a492b07a67510c108f1e7e3" dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", "strsim", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] name = "darling_macro" -version = "0.20.3" +version = "0.20.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" +checksum = "1d1545d67a2149e1d93b7e5c7752dce5a7426eb5d1357ddcfd89336b94444f77" dependencies = [ "darling_core", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -875,13 +872,13 @@ dependencies = [ [[package]] name = "derive_utils" -version = "0.13.2" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" +checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -1056,7 +1053,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -1068,7 +1065,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -1080,7 +1077,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -1145,7 +1142,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -1190,9 +1187,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.11" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe9006bed769170c11f845cf00c7c1e9092aeb3f268e007c3e760ac68008070f" +checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" dependencies = [ "cfg-if", "libc", @@ -1213,9 +1210,9 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "h2" -version = "0.3.22" +version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d6250322ef6e60f93f9a2162799302cd6f68f79f6e5d85c8c16f14d1d958178" +checksum = "bb2c4422095b67ee78da96fbb51a4cc413b3b25883c7717ff7ca1ab31022c9c9" dependencies = [ "bytes", "fnv", @@ -1223,7 +1220,7 @@ dependencies = [ "futures-sink", "futures-util", "http 0.2.11", - "indexmap 2.1.0", + "indexmap 2.2.2", "slab", "tokio", "tokio-util", @@ -1232,9 +1229,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.0" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1d308f63daf4181410c242d34c11f928dcb3aa105852019e043c9d1f4e4368a" +checksum = "31d030e59af851932b72ceebadf4a2b5986dba4c3b99dd2493f8273a0f151943" dependencies = [ "bytes", "fnv", @@ -1242,7 +1239,7 @@ dependencies = [ "futures-sink", "futures-util", "http 1.0.0", - "indexmap 2.1.0", + "indexmap 2.2.2", "slab", "tokio", "tokio-util", @@ -1251,9 +1248,13 @@ dependencies = [ [[package]] name = "half" -version = "1.8.2" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" +checksum = "bc52e53916c08643f1b56ec082790d1e86a32e58dc5268f897f313fbae7b4872" +dependencies = [ + "cfg-if", + "crunchy", +] [[package]] name = "hashbrown" @@ -1300,9 +1301,9 @@ checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" [[package]] name = "hermit-abi" -version = "0.3.3" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7" +checksum = "5d3d0e0f38255e7fa3cf31335b3a56f05febd18025f4db5ef7a0cfb4f8da651f" [[package]] name = "hex" @@ -1388,7 +1389,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "h2 0.3.22", + "h2 0.3.24", "http 0.2.11", "http-body 0.4.6", "httparse", @@ -1411,7 +1412,7 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "h2 0.4.0", + "h2 0.4.2", "http 1.0.0", "http-body 1.0.0", "httparse", @@ -1436,12 +1437,11 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdea9aac0dbe5a9240d68cfd9501e2db94222c6dc06843e06640b9e07f0fdc67" +checksum = "ca38ef113da30126bbff9cd1705f9273e15d45498615d138b0c20279ac7a76aa" dependencies = [ "bytes", - "futures-channel", "futures-util", "http 1.0.0", "http-body 1.0.0", @@ -1449,7 +1449,6 @@ dependencies = [ "pin-project-lite", "socket2", "tokio", - "tracing", ] [[package]] @@ -1504,9 +1503,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.1.0" +version = "2.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f" +checksum = "824b2ae422412366ba479e8111fd301f7b5faece8149317bb81925979a53f520" dependencies = [ "equivalent", "hashbrown 0.14.3", @@ -1515,12 +1514,11 @@ dependencies = [ [[package]] name = "io-enum" -version = "1.1.1" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" +checksum = "53b53d712d99a73eec59ee5e4fe6057f8052142d38eeafbbffcb06b36d738a6e" dependencies = [ "derive_utils", - "syn 2.0.47", ] [[package]] @@ -1549,15 +1547,6 @@ dependencies = [ "either", ] -[[package]] -name = "itertools" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" -dependencies = [ - "either", -] - [[package]] name = "itoa" version = "1.0.10" @@ -1575,9 +1564,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.66" +version = "0.3.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cee9c64da59eae3b50095c18d3e74f8b73c0b86d2792824ff01bbce68ba229ca" +checksum = "9a1d36f1235bc969acba30b7f5990b864423a6068a10f7c90ae8f0112e3a59d1" dependencies = [ "wasm-bindgen", ] @@ -1680,9 +1669,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.151" +version = "0.2.153" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" +checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" [[package]] name = "libloading" @@ -1707,9 +1696,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.12" +version = "1.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d97137b25e321a73eef1418d1d5d2eda4d77e12813f8e6dead84bc52c5870a7b" +checksum = "037731f5d3aaa87a5675e895b63ddff1a87624bc29f77004ea829809654e48f6" dependencies = [ "cc", "pkg-config", @@ -1724,15 +1713,15 @@ checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" [[package]] name = "linux-raw-sys" -version = "0.4.12" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4cd1a83af159aa67994778be9070f0ae1bd732942279cabb14f86f986a21456" +checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" [[package]] name = "local-ip-address" -version = "0.5.6" +version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66357e687a569abca487dc399a9c9ac19beb3f13991ed49f00c144e02cbd42ab" +checksum = "612ed4ea9ce5acfb5d26339302528a5e1e59dfed95e9e11af3c083236ff1d15d" dependencies = [ "libc", "neli", @@ -1833,14 +1822,14 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] name = "multimap" -version = "0.9.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1a5d38b9b352dbd913288736af36af41c48d61b1a8cd34bcecd727561b7d511" +checksum = "defc4c55412d89136f966bbb339008b474350e5e6e78d2714439c386b3137a03" dependencies = [ "serde", ] @@ -1884,7 +1873,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", "termcolor", "thiserror", ] @@ -1895,10 +1884,10 @@ version = "0.30.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57349d5a326b437989b6ee4dc8f2f34b0cc131202748414712a8e7d98952fc8c" dependencies = [ - "base64 0.21.5", + "base64 0.21.7", "bigdecimal", "bindgen", - "bitflags 2.4.1", + "bitflags 2.4.2", "bitvec", "byteorder", "bytes", @@ -2058,11 +2047,11 @@ checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" [[package]] name = "openssl" -version = "0.10.62" +version = "0.10.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cde4d2d9200ad5909f8dac647e29482e07c3a35de8a13fce7c9c7747ad9f671" +checksum = "15c9d69dd87a29568d4d017cfe8ec518706046a05184e5aea92d0af890b803c8" dependencies = [ - "bitflags 2.4.1", + "bitflags 2.4.2", "cfg-if", "foreign-types", "libc", @@ -2079,7 +2068,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -2090,18 +2079,18 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "300.2.1+3.2.0" +version = "300.2.2+3.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fe476c29791a5ca0d1273c697e96085bbabbbea2ef7afd5617e78a4b40332d3" +checksum = "8bbfad0063610ac26ee79f7484739e2b07555a75c42453b89263830b5c8103bc" dependencies = [ "cc", ] [[package]] name = "openssl-sys" -version = "0.9.98" +version = "0.9.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1665caf8ab2dc9aef43d1c0023bd904633a6a05cb30b0ad59bec2ae986e57a7" +checksum = "22e1bf214306098e4832460f797824c05d25aacdf896f64a985fb0fd992454ae" dependencies = [ "cc", "libc", @@ -2161,7 +2150,7 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b13fe415cdf3c8e44518e18a7c95a13431d9bdf6d15367d82b23c377fdd441a" dependencies = [ - "base64 0.21.5", + "base64 0.21.7", "serde", ] @@ -2173,9 +2162,9 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.5" +version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae9cee2a55a544be8b89dc6848072af97a20f2422603c10865be2a42b580fff5" +checksum = "1f200d8d83c44a45b21764d1916299752ca035d15ecd46faca3e9a2a2bf6ad06" dependencies = [ "memchr", "thiserror", @@ -2184,9 +2173,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.5" +version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81d78524685f5ef2a3b3bd1cafbc9fcabb036253d9b1463e726a91cd16e2dfc2" +checksum = "bcd6ab1236bbdb3a49027e920e693192ebfe8913f6d60e294de57463a493cfde" dependencies = [ "pest", "pest_generator", @@ -2194,22 +2183,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.5" +version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68bd1206e71118b5356dae5ddc61c8b11e28b09ef6a31acbd15ea48a28e0c227" +checksum = "2a31940305ffc96863a735bef7c7994a00b325a7138fdbc5bda0f1a0476d3275" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] name = "pest_meta" -version = "2.7.5" +version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c747191d4ad9e4a4ab9c8798f1e82a39affe7ef9648390b7e5548d18e099de6" +checksum = "a7ff62f5259e53b78d1af898941cdcdccfae7385cf7d793a6e55de5d05bb4b7d" dependencies = [ "once_cell", "pest", @@ -2256,22 +2245,22 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.3" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fda4ed1c6c173e3fc7a83629421152e01d7b1f9b7f65fb301e490e8cfc656422" +checksum = "0302c4a0442c456bd56f841aee5c3bfd17967563f6fadc9ceb9f9c23cf3807e0" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.3" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" +checksum = "266c042b60c9c76b8d53061e52b2e0d1116abc57cefc8c5cd671619a56ac3690" dependencies = [ "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -2288,9 +2277,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pkg-config" -version = "0.3.28" +version = "0.3.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69d3587f8a9e599cc7ec2c00e331f71c4e69a5f9a4b8a6efd5b07466b9736f9a" +checksum = "2900ede94e305130c13ddd391e0ab7cbaeb783945ae07a279c268cb05109c6cb" [[package]] name = "plotters" @@ -2334,12 +2323,11 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "predicates" -version = "3.0.4" +version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dfc28575c2e3f19cb3c73b93af36460ae898d426eba6fc15b9bd2a5220758a0" +checksum = "68b87bfd4605926cdfefc1c3b5f8fe560e3feca9d5552cf68c466d3d8236c7e8" dependencies = [ "anstyle", - "itertools 0.11.0", "predicates-core", ] @@ -2371,11 +2359,11 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "2.0.0" +version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e8366a6159044a37876a2b9817124296703c586a5c92e2c53751fa06d8d43e8" +checksum = "6d37c51ca738a55da99dc0c4a34860fd675453b8b36209178c2249bb13651284" dependencies = [ - "toml_edit 0.20.7", + "toml_edit 0.21.1", ] [[package]] @@ -2404,9 +2392,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.75" +version = "1.0.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "907a61bd0f64c2f29cd1cf1dc34d05176426a3f504a78010f08416ddb7b13708" +checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae" dependencies = [ "unicode-ident", ] @@ -2510,9 +2498,9 @@ dependencies = [ [[package]] name = "rayon" -version = "1.8.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c27db03db7734835b3f53954b534c91069375ce6ccaa2e065441e07d9b6cdb1" +checksum = "fa7237101a77a10773db45d62004a272517633fbcc3df19d96455ede1122e051" dependencies = [ "either", "rayon-core", @@ -2520,9 +2508,9 @@ dependencies = [ [[package]] name = "rayon-core" -version = "1.12.0" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ce3fb6ad83f861aac485e76e1985cd109d9a3713802152be56c3b1f0e0658ed" +checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" dependencies = [ "crossbeam-deque", "crossbeam-utils", @@ -2539,9 +2527,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.2" +version = "1.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "380b951a9c5e80ddfd6136919eef32310721aa4aacd4889a8d39124b026ab343" +checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15" dependencies = [ "aho-corasick", "memchr", @@ -2551,9 +2539,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.3" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f" +checksum = "5bb987efffd3c6d0d8f5f89510bb458559eab11e4f869acb20bf845e016259cd" dependencies = [ "aho-corasick", "memchr", @@ -2577,16 +2565,16 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.11.23" +version = "0.11.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37b1ae8d9ac08420c66222fb9096fc5de435c3c48542bc5336c51892cffafb41" +checksum = "c6920094eb85afde5e4a138be3f2de8bbdf28000f0029e72c45025a56b042251" dependencies = [ - "base64 0.21.5", + "base64 0.21.7", "bytes", "encoding_rs", "futures-core", "futures-util", - "h2 0.3.22", + "h2 0.3.24", "http 0.2.11", "http-body 0.4.6", "hyper 0.14.28", @@ -2599,9 +2587,11 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", + "rustls-pemfile 1.0.4", "serde", "serde_json", "serde_urlencoded", + "sync_wrapper", "system-configuration", "tokio", "tokio-native-tls", @@ -2682,7 +2672,7 @@ version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a78046161564f5e7cd9008aff3b2990b3850dc8e0349119b98e8f251e099f24d" dependencies = [ - "bitflags 2.4.1", + "bitflags 2.4.2", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -2702,9 +2692,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.33.1" +version = "1.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06676aec5ccb8fc1da723cc8c0f9a46549f21ebb8753d3915c6c41db1e7f1dc4" +checksum = "d7de2711cae7bdec993f4d2319352599ceb0d003e9f7900ea7c6ef4c5fc16831" dependencies = [ "arrayvec", "borsh", @@ -2739,11 +2729,11 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.28" +version = "0.38.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72e572a5e8ca657d7366229cdde4bd14c4eb5499a9573d4d366fe1b599daa316" +checksum = "322394588aaf33c24007e8bb3238ee3e4c5c09c084ab32bc73890b99ff326bca" dependencies = [ - "bitflags 2.4.1", + "bitflags 2.4.2", "errno", "libc", "linux-raw-sys", @@ -2762,13 +2752,22 @@ dependencies = [ "sct", ] +[[package]] +name = "rustls-pemfile" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" +dependencies = [ + "base64 0.21.7", +] + [[package]] name = "rustls-pemfile" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35e4980fa29e4c4b212ffb3db068a564cbf560e51d3944b7c88bd8bf5bec64f4" dependencies = [ - "base64 0.21.5", + "base64 0.21.7", "rustls-pki-types", ] @@ -2886,9 +2885,9 @@ checksum = "b97ed7a9823b74f99c7742f5336af7be5ecd3eeafcb1507d1fa93347b1d589b0" [[package]] name = "serde" -version = "1.0.194" +version = "1.0.196" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b114498256798c94a0689e1a15fec6005dee8ac1f41de56404b67afc2a4b773" +checksum = "870026e60fa08c69f064aa766c10f10b1d62db9ccd4d0abb206472bee0ce3b32" dependencies = [ "serde_derive", ] @@ -2914,20 +2913,20 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.194" +version = "1.0.196" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3385e45322e8f9931410f01b3031ec534c3947d0e94c18049af4d9f9907d4e0" +checksum = "33c85360c95e7d137454dc81d9a4ed2b8efd8fbe19cee57357b32b9771fccb67" dependencies = [ "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] name = "serde_json" -version = "1.0.110" +version = "1.0.113" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fbd975230bada99c8bb618e0c365c2eefa219158d5c6c29610fd09ff1833257" +checksum = "69801b70b1c3dac963ecb03a364ba0ceda9cf60c71cfe475e99864759c8b8a79" dependencies = [ "itoa", "ryu", @@ -2952,7 +2951,7 @@ checksum = "0b2e6b945e9d3df726b65d6ee24060aff8e3533d431f677a9695db04eff9dfdb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -2978,15 +2977,15 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.4.0" +version = "3.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64cd236ccc1b7a29e7e2739f27c0b2dd199804abc4290e32f59f3b68d6405c23" +checksum = "1b0ed1662c5a68664f45b76d18deb0e234aff37207086803165c961eb695e981" dependencies = [ - "base64 0.21.5", + "base64 0.21.7", "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.1.0", + "indexmap 2.2.2", "serde", "serde_json", "serde_with_macros", @@ -2995,14 +2994,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.4.0" +version = "3.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93634eb5f75a2323b16de4748022ac4297f9e76b6dced2be287a099f41b5e788" +checksum = "568577ff0ef47b879f736cd66740e022f3672788cdf002a05a4e609ea5a6fb15" dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -3029,9 +3028,9 @@ dependencies = [ [[package]] name = "shlex" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7cee0529a6d40f580e7a5e6c495c8fbfe21b7b52795ed4bb5e62cdf92bc6380" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "signal-hook-registry" @@ -3065,9 +3064,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.11.2" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dccd0940a2dcdf68d092b8cbab7dc0ad8fa938bf95787e1b916b0e3d0e8e970" +checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7" [[package]] name = "socket2" @@ -3120,9 +3119,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.47" +version = "2.0.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1726efe18f42ae774cc644f330953a5e7b3c3003d3edcecf18850fe9d4dd9afb" +checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f" dependencies = [ "proc-macro2", "quote", @@ -3138,7 +3137,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -3206,9 +3205,9 @@ dependencies = [ [[package]] name = "termcolor" -version = "1.4.0" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff1bc3d3f05aff0403e8ac0d92ced918ec05b666a43f83297ccef5bea8a3d449" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" dependencies = [ "winapi-util", ] @@ -3236,7 +3235,7 @@ checksum = "fa0faa943b50f3db30a20aa7e265dbc66076993efed8463e8de414e5d06d3471" dependencies = [ "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -3319,7 +3318,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] @@ -3367,14 +3366,14 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1a195ec8c9da26928f773888e0742ca3ca1040c6cd859c919c9f59c1954ab35" +checksum = "c6a4b9e8023eb94392d3dca65d717c53abc5dad49c07cb65bb8fcd87115fa325" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.21.0", + "toml_edit 0.21.1", ] [[package]] @@ -3392,29 +3391,18 @@ version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ - "indexmap 2.1.0", - "toml_datetime", - "winnow", -] - -[[package]] -name = "toml_edit" -version = "0.20.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" -dependencies = [ - "indexmap 2.1.0", + "indexmap 2.2.2", "toml_datetime", "winnow", ] [[package]] name = "toml_edit" -version = "0.21.0" +version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34d383cd00a163b4a5b85053df514d45bc330f6de7737edfe0a93311d1eaa03" +checksum = "6a8534fd7f78b5405e860340ad6575217ce99f38d4d5c8f2442cb5ecb50090e1" dependencies = [ - "indexmap 2.1.0", + "indexmap 2.2.2", "serde", "serde_spanned", "toml_datetime", @@ -3498,7 +3486,7 @@ dependencies = [ "serde", "serde_with", "thiserror", - "toml 0.8.8", + "toml 0.8.9", "torrust-tracker-located-error", "torrust-tracker-primitives", "uuid", @@ -3556,14 +3544,14 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e12e6351354851911bdf8c2b8f2ab15050c567d70a8b9a37ae7b8301a4080d" +checksum = "0da193277a4e2c33e59e09b5861580c33dd0a637c3883d0fa74ba40c0374af2e" dependencies = [ "async-compression", - "bitflags 2.4.1", + "bitflags 2.4.2", "bytes", - "futures-util", + "futures-core", "http 1.0.0", "http-body 1.0.0", "http-body-util", @@ -3637,9 +3625,9 @@ checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" [[package]] name = "unicode-bidi" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f2528f27a9eb2b21e69c95319b30bd0efd85d09c379741b0f78ea1d86be2416" +checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" [[package]] name = "unicode-ident" @@ -3681,9 +3669,9 @@ checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" [[package]] name = "uuid" -version = "1.6.1" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e395fcf16a7a3d8127ec99782007af141946b4795001f876d54fb0d55978560" +checksum = "f00cc9702ca12d3c81455259621e676d0f7251cec66a21e98fe2e9a37db93b2a" dependencies = [ "getrandom", "rand", @@ -3728,9 +3716,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.89" +version = "0.2.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ed0d4f68a3015cc185aff4db9506a015f4b96f95303897bfa23f846db54064e" +checksum = "b1223296a201415c7fad14792dbefaace9bd52b62d33453ade1c5b5f07555406" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -3738,24 +3726,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.89" +version = "0.2.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b56f625e64f3a1084ded111c4d5f477df9f8c92df113852fa5a374dbda78826" +checksum = "fcdc935b63408d58a32f8cc9738a0bffd8f05cc7c002086c6ef20b7312ad9dcd" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.39" +version = "0.4.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac36a15a220124ac510204aec1c3e5db8a22ab06fd6706d881dc6149f8ed9a12" +checksum = "bde2032aeb86bdfaecc8b261eef3cba735cc426c1f3a3416d1e0791be95fc461" dependencies = [ "cfg-if", "js-sys", @@ -3765,9 +3753,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.89" +version = "0.2.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0162dbf37223cd2afce98f3d0785506dcb8d266223983e4b5b525859e6e182b2" +checksum = "3e4c238561b2d428924c49815533a8b9121c664599558a5d9ec51f8a1740a999" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3775,28 +3763,28 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.89" +version = "0.2.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283" +checksum = "bae1abb6806dc1ad9e560ed242107c0f6c84335f1749dd4e8ddb012ebd5e25a7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.89" +version = "0.2.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ab9b36309365056cd639da3134bf87fa8f3d86008abf99e612384a6eecd459f" +checksum = "4d91413b1c31d7539ba5ef2451af3f0b833a005eb27a631cec32bc0635a8602b" [[package]] name = "web-sys" -version = "0.3.66" +version = "0.3.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50c24a44ec86bb68fbecd1b3efed7e85ea5621b39b35ef2766b66cd984f8010f" +checksum = "58cd2333b6e0be7a39605f0e255892fd7418a682d8da8fe042fe25128794d2ed" dependencies = [ "js-sys", "wasm-bindgen", @@ -3976,9 +3964,9 @@ checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" [[package]] name = "winnow" -version = "0.5.32" +version = "0.5.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8434aeec7b290e8da5c3f0d628cb0eac6cabcb31d14bb74f779a08109a5914d6" +checksum = "818ce546a11a9986bc24f93d0cdf38a8a1a400f1473ea8c82e59f6e0ffab9249" dependencies = [ "memchr", ] @@ -4028,7 +4016,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.47", + "syn 2.0.48", ] [[package]] From 3b735a7ce0e4c792a5bbafbc29e68083bb97d716 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 31 Jan 2024 12:03:20 +0000 Subject: [PATCH 0219/1297] refactor: [#639] Tracker Checker: prepare outout for UDP checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The output for the UDP tracker checks are now the same as the HTTP tracker checks. But not implemented yet (TODO). ```output Running checks for trackers ... UDP trackers ... ✓ - Announce at 127.0.0.1:6969 is OK ✓ - Scrape at 127.0.0.1:6969 is OK HTTP trackers ... ✓ - Announce at http://127.0.0.1:7070/ is OK (TODO) ✓ - Scrape at http://127.0.0.1:7070/ is OK (TODO) Health checks ... ✓ - Health API at http://127.0.0.1:1313/health_check is OK ``` --- src/console/clients/checker/service.rs | 79 +++++++++++++++++++------- 1 file changed, 58 insertions(+), 21 deletions(-) diff --git a/src/console/clients/checker/service.rs b/src/console/clients/checker/service.rs index 1cb4725e0..90dc10894 100644 --- a/src/console/clients/checker/service.rs +++ b/src/console/clients/checker/service.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use std::time::Duration; use colored::Colorize; +use log::debug; use reqwest::{Client as HttpClient, Url}; use super::config::Configuration; @@ -38,7 +39,7 @@ impl Service { let mut check_results = vec![]; - self.check_udp_trackers(); + self.check_udp_trackers(&mut check_results).await; self.check_http_trackers(&mut check_results).await; @@ -47,11 +48,44 @@ impl Service { check_results } - fn check_udp_trackers(&self) { + async fn check_udp_trackers(&self, check_results: &mut Vec) { self.console.println("UDP trackers ..."); for udp_tracker in &self.config.udp_trackers { - self.check_udp_tracker(udp_tracker); + let colored_tracker_url = udp_tracker.to_string().yellow(); + + /* todo: + - Initialize the UDP client + - Pass the connected client the the check function + - Connect to the tracker + - Make the request (announce or scrape) + */ + + match self.check_udp_announce(udp_tracker).await { + Ok(()) => { + check_results.push(Ok(())); + self.console + .println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); + } + Err(err) => { + check_results.push(Err(err)); + self.console + .println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); + } + } + + match self.check_udp_scrape(udp_tracker).await { + Ok(()) => { + check_results.push(Ok(())); + self.console + .println(&format!("{} - Scrape at {} is OK", "✓".green(), colored_tracker_url)); + } + Err(err) => { + check_results.push(Err(err)); + self.console + .println(&format!("{} - Scrape at {} is failing", "✗".red(), colored_tracker_url)); + } + } } } @@ -65,7 +99,7 @@ impl Service { Ok(()) => { check_results.push(Ok(())); self.console - .println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); + .println(&format!("{} - Announce at {} is OK (TODO)", "✓".green(), colored_tracker_url)); } Err(err) => { check_results.push(Err(err)); @@ -78,7 +112,7 @@ impl Service { Ok(()) => { check_results.push(Ok(())); self.console - .println(&format!("{} - Scrape at {} is OK", "✓".green(), colored_tracker_url)); + .println(&format!("{} - Scrape at {} is OK (TODO)", "✓".green(), colored_tracker_url)); } Err(err) => { check_results.push(Err(err)); @@ -100,26 +134,23 @@ impl Service { } } - fn check_udp_tracker(&self, address: &SocketAddr) { - // todo: - // - Make announce request - // - Make scrape request - - let colored_address = address.to_string().yellow(); + #[allow(clippy::unused_async)] + async fn check_udp_announce(&self, tracker_socket_addr: &SocketAddr) -> Result<(), CheckError> { + debug!("{tracker_socket_addr}"); + Ok(()) + } - self.console.println(&format!( - "{} - UDP tracker at udp://{} is OK ({})", - "✓".green(), - colored_address, - "TODO".red(), - )); + #[allow(clippy::unused_async)] + async fn check_udp_scrape(&self, tracker_socket_addr: &SocketAddr) -> Result<(), CheckError> { + debug!("{tracker_socket_addr}"); + Ok(()) } - async fn check_http_announce(&self, url: &Url) -> Result<(), CheckError> { + async fn check_http_announce(&self, tracker_url: &Url) -> Result<(), CheckError> { let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // # DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); - let response = Client::new(url.clone()) + let response = Client::new(tracker_url.clone()) .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) .await; @@ -127,10 +158,15 @@ impl Service { if let Ok(_announce_response) = serde_bencode::from_bytes::(&body) { Ok(()) } else { - Err(CheckError::HttpError { url: url.clone() }) + debug!("announce body {:#?}", body); + Err(CheckError::HttpError { + url: tracker_url.clone(), + }) } } else { - Err(CheckError::HttpError { url: url.clone() }) + Err(CheckError::HttpError { + url: tracker_url.clone(), + }) } } @@ -144,6 +180,7 @@ impl Service { if let Ok(_scrape_response) = scrape::Response::try_from_bencoded(&body) { Ok(()) } else { + debug!("scrape body {:#?}", body); Err(CheckError::HttpError { url: url.clone() }) } } else { From 011fdb7df19536039367bc06dfd6d6397e474626 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 31 Jan 2024 13:45:17 +0000 Subject: [PATCH 0220/1297] refactor: [#639] Tracker Checker: extract checker:Client to check UDP servers It will be used in teh Tracker Checker too. --- src/console/clients/udp/app.rs | 149 +++---------- src/console/clients/udp/checker.rs | 214 +++++++++++++++++++ src/console/clients/udp/mod.rs | 1 + src/shared/bit_torrent/tracker/udp/client.rs | 2 + 4 files changed, 241 insertions(+), 125 deletions(-) create mode 100644 src/console/clients/udp/checker.rs diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index e9c8b5274..8b1a8ca47 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -56,25 +56,21 @@ //! ``` //! //! The protocol (`udp://`) in the URL is mandatory. The path (`\scrape`) is optional. It always uses `\scrape`. -use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs}; +use std::net::{SocketAddr, ToSocketAddrs}; use std::str::FromStr; use anyhow::Context; -use aquatic_udp_protocol::common::InfoHash; use aquatic_udp_protocol::Response::{AnnounceIpv4, AnnounceIpv6, Scrape}; -use aquatic_udp_protocol::{ - AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, Response, - ScrapeRequest, TransactionId, -}; +use aquatic_udp_protocol::{Port, TransactionId}; use clap::{Parser, Subcommand}; use log::{debug, LevelFilter}; use serde_json::json; use url::Url; +use crate::console::clients::udp::checker; use crate::shared::bit_torrent::info_hash::InfoHash as TorrustInfoHash; -use crate::shared::bit_torrent::tracker::udp::client::{UdpClient, UdpTrackerClient}; -const ASSIGNED_BY_OS: i32 = 0; +const ASSIGNED_BY_OS: u16 = 0; const RANDOM_TRANSACTION_ID: i32 = -888_840_697; #[derive(Parser, Debug)] @@ -110,41 +106,36 @@ pub async fn run() -> anyhow::Result<()> { let args = Args::parse(); - // Configuration - let local_port = ASSIGNED_BY_OS; - let local_bind_to = format!("0.0.0.0:{local_port}"); - let transaction_id = RANDOM_TRANSACTION_ID; - - // Bind to local port - debug!("Binding to: {local_bind_to}"); - let udp_client = UdpClient::bind(&local_bind_to).await; - let bound_to = udp_client.socket.local_addr().context("binding local address")?; - debug!("Bound to: {bound_to}"); - - let transaction_id = TransactionId(transaction_id); - let response = match args.command { Command::Announce { tracker_socket_addr, info_hash, } => { - let (connection_id, udp_tracker_client) = connect(&tracker_socket_addr, udp_client, transaction_id).await; - - send_announce_request( - connection_id, - transaction_id, - info_hash, - Port(bound_to.port()), - &udp_tracker_client, - ) - .await + let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); + + let mut client = checker::Client::default(); + + let bound_to = client.bind_and_connect(ASSIGNED_BY_OS, &tracker_socket_addr).await?; + + let connection_id = client.send_connection_request(transaction_id).await?; + + client + .send_announce_request(connection_id, transaction_id, info_hash, Port(bound_to.port())) + .await? } Command::Scrape { tracker_socket_addr, info_hashes, } => { - let (connection_id, udp_tracker_client) = connect(&tracker_socket_addr, udp_client, transaction_id).await; - send_scrape_request(connection_id, transaction_id, info_hashes, &udp_tracker_client).await + let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); + + let mut client = checker::Client::default(); + + let _bound_to = client.bind_and_connect(ASSIGNED_BY_OS, &tracker_socket_addr).await?; + + let connection_id = client.send_connection_request(transaction_id).await?; + + client.send_scrape_request(connection_id, transaction_id, info_hashes).await? } }; @@ -265,95 +256,3 @@ fn parse_info_hash(info_hash_str: &str) -> anyhow::Result { TorrustInfoHash::from_str(info_hash_str) .map_err(|e| anyhow::Error::msg(format!("failed to parse info-hash `{info_hash_str}`: {e:?}"))) } - -async fn connect( - tracker_socket_addr: &SocketAddr, - udp_client: UdpClient, - transaction_id: TransactionId, -) -> (ConnectionId, UdpTrackerClient) { - debug!("Connecting to tracker: udp://{tracker_socket_addr}"); - - udp_client.connect(&tracker_socket_addr.to_string()).await; - - let udp_tracker_client = UdpTrackerClient { udp_client }; - - let connection_id = send_connection_request(transaction_id, &udp_tracker_client).await; - - (connection_id, udp_tracker_client) -} - -async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrackerClient) -> ConnectionId { - debug!("Sending connection request with transaction id: {transaction_id:#?}"); - - let connect_request = ConnectRequest { transaction_id }; - - client.send(connect_request.into()).await; - - let response = client.receive().await; - - debug!("connection request response:\n{response:#?}"); - - match response { - Response::Connect(connect_response) => connect_response.connection_id, - _ => panic!("error connecting to udp server. Unexpected response"), - } -} - -async fn send_announce_request( - connection_id: ConnectionId, - transaction_id: TransactionId, - info_hash: TorrustInfoHash, - port: Port, - client: &UdpTrackerClient, -) -> Response { - debug!("Sending announce request with transaction id: {transaction_id:#?}"); - - let announce_request = AnnounceRequest { - connection_id, - transaction_id, - info_hash: InfoHash(info_hash.bytes()), - peer_id: PeerId(*b"-qB00000000000000001"), - bytes_downloaded: NumberOfBytes(0i64), - bytes_uploaded: NumberOfBytes(0i64), - bytes_left: NumberOfBytes(0i64), - event: AnnounceEvent::Started, - ip_address: Some(Ipv4Addr::new(0, 0, 0, 0)), - key: PeerKey(0u32), - peers_wanted: NumberOfPeers(1i32), - port, - }; - - client.send(announce_request.into()).await; - - let response = client.receive().await; - - debug!("announce request response:\n{response:#?}"); - - response -} - -async fn send_scrape_request( - connection_id: ConnectionId, - transaction_id: TransactionId, - info_hashes: Vec, - client: &UdpTrackerClient, -) -> Response { - debug!("Sending scrape request with transaction id: {transaction_id:#?}"); - - let scrape_request = ScrapeRequest { - connection_id, - transaction_id, - info_hashes: info_hashes - .iter() - .map(|torrust_info_hash| InfoHash(torrust_info_hash.bytes())) - .collect(), - }; - - client.send(scrape_request.into()).await; - - let response = client.receive().await; - - debug!("scrape request response:\n{response:#?}"); - - response -} diff --git a/src/console/clients/udp/checker.rs b/src/console/clients/udp/checker.rs new file mode 100644 index 000000000..b35139e49 --- /dev/null +++ b/src/console/clients/udp/checker.rs @@ -0,0 +1,214 @@ +use std::net::{Ipv4Addr, SocketAddr}; + +use anyhow::Context; +use aquatic_udp_protocol::common::InfoHash; +use aquatic_udp_protocol::{ + AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, Response, + ScrapeRequest, TransactionId, +}; +use log::debug; +use thiserror::Error; + +use crate::shared::bit_torrent::info_hash::InfoHash as TorrustInfoHash; +use crate::shared::bit_torrent::tracker::udp::client::{UdpClient, UdpTrackerClient}; + +#[derive(Error, Debug)] +pub enum ClientError { + #[error("Local socket address is not bound yet. Try binding before connecting.")] + NotBound, + #[error("Not connected to remote tracker UDP socket. Try connecting before making requests.")] + NotConnected, + #[error("Unexpected response while connecting the the remote server.")] + UnexpectedConnectionResponse, +} + +/// A UDP Tracker client to make test requests (checks). +#[derive(Debug, Default)] +pub struct Client { + /// Local UDP socket. It could be 0 to assign a free port. + local_binding_address: Option, + + /// Local UDP socket after binding. It's equals to binding address if a + /// non- zero port was used. + local_bound_address: Option, + + /// Remote UDP tracker socket + remote_socket: Option, + + /// The client used to make UDP requests to the tracker. + udp_tracker_client: Option, +} + +impl Client { + /// Binds to the local socket and connects to the remote one. + /// + /// # Errors + /// + /// Will return an error if + /// + /// - It can't bound to the local socket address. + /// - It can't make a connection request successfully to the remote UDP server. + pub async fn bind_and_connect(&mut self, local_port: u16, remote_socket_addr: &SocketAddr) -> anyhow::Result { + let bound_to = self.bind(local_port).await?; + self.connect(remote_socket_addr).await?; + Ok(bound_to) + } + + /// Binds local client socket. + /// + /// # Errors + /// + /// Will return an error if it can't bound to the local address. + async fn bind(&mut self, local_port: u16) -> anyhow::Result { + let local_bind_to = format!("0.0.0.0:{local_port}"); + let binding_address = local_bind_to.parse().context("binding local address")?; + + debug!("Binding to: {local_bind_to}"); + let udp_client = UdpClient::bind(&local_bind_to).await; + + let bound_to = udp_client.socket.local_addr().context("bound local address")?; + debug!("Bound to: {bound_to}"); + + self.local_binding_address = Some(binding_address); + self.local_bound_address = Some(bound_to); + + self.udp_tracker_client = Some(UdpTrackerClient { udp_client }); + + Ok(bound_to) + } + + /// Connects to the remote server socket. + /// + /// # Errors + /// + /// Will return and error if it can't make a connection request successfully + /// to the remote UDP server. + async fn connect(&mut self, tracker_socket_addr: &SocketAddr) -> anyhow::Result<()> { + debug!("Connecting to tracker: udp://{tracker_socket_addr}"); + + match &self.udp_tracker_client { + Some(client) => { + client.udp_client.connect(&tracker_socket_addr.to_string()).await; + self.remote_socket = Some(*tracker_socket_addr); + Ok(()) + } + None => Err(ClientError::NotBound.into()), + } + } + + /// Sends a connection request to the UDP Tracker server. + /// + /// # Errors + /// + /// Will return and error if + /// + /// - It can't connect to the remote UDP socket. + /// - It can't make a connection request successfully to the remote UDP + /// server (after successfully connecting to the remote UDP socket). + /// + /// # Panics + /// + /// Will panic if it receives an unexpected response. + pub async fn send_connection_request(&self, transaction_id: TransactionId) -> anyhow::Result { + debug!("Sending connection request with transaction id: {transaction_id:#?}"); + + let connect_request = ConnectRequest { transaction_id }; + + match &self.udp_tracker_client { + Some(client) => { + client.send(connect_request.into()).await; + + let response = client.receive().await; + + debug!("connection request response:\n{response:#?}"); + + match response { + Response::Connect(connect_response) => Ok(connect_response.connection_id), + _ => Err(ClientError::UnexpectedConnectionResponse.into()), + } + } + None => Err(ClientError::NotConnected.into()), + } + } + + /// Sends an announce request to the UDP Tracker server. + /// + /// # Errors + /// + /// Will return and error if the client is not connected. You have to connect + /// before calling this function. + pub async fn send_announce_request( + &self, + connection_id: ConnectionId, + transaction_id: TransactionId, + info_hash: TorrustInfoHash, + client_port: Port, + ) -> anyhow::Result { + debug!("Sending announce request with transaction id: {transaction_id:#?}"); + + let announce_request = AnnounceRequest { + connection_id, + transaction_id, + info_hash: InfoHash(info_hash.bytes()), + peer_id: PeerId(*b"-qB00000000000000001"), + bytes_downloaded: NumberOfBytes(0i64), + bytes_uploaded: NumberOfBytes(0i64), + bytes_left: NumberOfBytes(0i64), + event: AnnounceEvent::Started, + ip_address: Some(Ipv4Addr::new(0, 0, 0, 0)), + key: PeerKey(0u32), + peers_wanted: NumberOfPeers(1i32), + port: client_port, + }; + + match &self.udp_tracker_client { + Some(client) => { + client.send(announce_request.into()).await; + + let response = client.receive().await; + + debug!("announce request response:\n{response:#?}"); + + Ok(response) + } + None => Err(ClientError::NotConnected.into()), + } + } + + /// Sends a scrape request to the UDP Tracker server. + /// + /// # Errors + /// + /// Will return and error if the client is not connected. You have to connect + /// before calling this function. + pub async fn send_scrape_request( + &self, + connection_id: ConnectionId, + transaction_id: TransactionId, + info_hashes: Vec, + ) -> anyhow::Result { + debug!("Sending scrape request with transaction id: {transaction_id:#?}"); + + let scrape_request = ScrapeRequest { + connection_id, + transaction_id, + info_hashes: info_hashes + .iter() + .map(|torrust_info_hash| InfoHash(torrust_info_hash.bytes())) + .collect(), + }; + + match &self.udp_tracker_client { + Some(client) => { + client.send(scrape_request.into()).await; + + let response = client.receive().await; + + debug!("scrape request response:\n{response:#?}"); + + Ok(response) + } + None => Err(ClientError::NotConnected.into()), + } + } +} diff --git a/src/console/clients/udp/mod.rs b/src/console/clients/udp/mod.rs index 309be6287..cd0e8bd6b 100644 --- a/src/console/clients/udp/mod.rs +++ b/src/console/clients/udp/mod.rs @@ -1 +1,2 @@ pub mod app; +pub mod checker; diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs index 23b718472..41c9def89 100644 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -11,6 +11,7 @@ use tokio::time; use crate::shared::bit_torrent::tracker::udp::{source_address, MAX_PACKET_SIZE}; #[allow(clippy::module_name_repetitions)] +#[derive(Debug)] pub struct UdpClient { pub socket: Arc, } @@ -86,6 +87,7 @@ pub async fn new_udp_client_connected(remote_address: &str) -> UdpClient { } #[allow(clippy::module_name_repetitions)] +#[derive(Debug)] pub struct UdpTrackerClient { pub udp_client: UdpClient, } From a2e123cb338d7faed4e8f35e54a6470cfbddc2ca Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 31 Jan 2024 17:57:46 +0000 Subject: [PATCH 0221/1297] refactor: [#639] UDP client. Extract command handlers --- src/console/clients/udp/app.rs | 56 +++++++++++++++++++--------------- 1 file changed, 31 insertions(+), 25 deletions(-) diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index 8b1a8ca47..e365f962b 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -60,7 +60,7 @@ use std::net::{SocketAddr, ToSocketAddrs}; use std::str::FromStr; use anyhow::Context; -use aquatic_udp_protocol::Response::{AnnounceIpv4, AnnounceIpv6, Scrape}; +use aquatic_udp_protocol::Response::{self, AnnounceIpv4, AnnounceIpv6, Scrape}; use aquatic_udp_protocol::{Port, TransactionId}; use clap::{Parser, Subcommand}; use log::{debug, LevelFilter}; @@ -110,33 +110,11 @@ pub async fn run() -> anyhow::Result<()> { Command::Announce { tracker_socket_addr, info_hash, - } => { - let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); - - let mut client = checker::Client::default(); - - let bound_to = client.bind_and_connect(ASSIGNED_BY_OS, &tracker_socket_addr).await?; - - let connection_id = client.send_connection_request(transaction_id).await?; - - client - .send_announce_request(connection_id, transaction_id, info_hash, Port(bound_to.port())) - .await? - } + } => handle_announce(&tracker_socket_addr, &info_hash).await?, Command::Scrape { tracker_socket_addr, info_hashes, - } => { - let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); - - let mut client = checker::Client::default(); - - let _bound_to = client.bind_and_connect(ASSIGNED_BY_OS, &tracker_socket_addr).await?; - - let connection_id = client.send_connection_request(transaction_id).await?; - - client.send_scrape_request(connection_id, transaction_id, info_hashes).await? - } + } => handle_scrape(&tracker_socket_addr, &info_hashes).await?, }; match response { @@ -201,6 +179,34 @@ fn setup_logging(level: LevelFilter) { debug!("logging initialized."); } +async fn handle_announce(tracker_socket_addr: &SocketAddr, info_hash: &TorrustInfoHash) -> anyhow::Result { + let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); + + let mut client = checker::Client::default(); + + let bound_to = client.bind_and_connect(ASSIGNED_BY_OS, tracker_socket_addr).await?; + + let connection_id = client.send_connection_request(transaction_id).await?; + + client + .send_announce_request(connection_id, transaction_id, *info_hash, Port(bound_to.port())) + .await +} + +async fn handle_scrape(tracker_socket_addr: &SocketAddr, info_hashes: &[TorrustInfoHash]) -> anyhow::Result { + let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); + + let mut client = checker::Client::default(); + + let _bound_to = client.bind_and_connect(ASSIGNED_BY_OS, tracker_socket_addr).await?; + + let connection_id = client.send_connection_request(transaction_id).await?; + + client + .send_scrape_request(connection_id, transaction_id, info_hashes.to_vec()) + .await +} + fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); From 1b92b77052e1f96d33648875d184f7ad78cce19d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 31 Jan 2024 18:43:28 +0000 Subject: [PATCH 0222/1297] refactor: [#639] UDP client. Extract aquatic reponses wrappers for serialization to JSON. --- src/console/clients/udp/app.rs | 65 +++++++++------------- src/console/clients/udp/mod.rs | 1 + src/console/clients/udp/responses.rs | 83 ++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+), 40 deletions(-) create mode 100644 src/console/clients/udp/responses.rs diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index e365f962b..b9e31155d 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -64,10 +64,10 @@ use aquatic_udp_protocol::Response::{self, AnnounceIpv4, AnnounceIpv6, Scrape}; use aquatic_udp_protocol::{Port, TransactionId}; use clap::{Parser, Subcommand}; use log::{debug, LevelFilter}; -use serde_json::json; use url::Url; use crate::console::clients::udp::checker; +use crate::console::clients::udp::responses::{AnnounceResponseDto, ScrapeResponseDto}; use crate::shared::bit_torrent::info_hash::InfoHash as TorrustInfoHash; const ASSIGNED_BY_OS: u16 = 0; @@ -117,45 +117,7 @@ pub async fn run() -> anyhow::Result<()> { } => handle_scrape(&tracker_socket_addr, &info_hashes).await?, }; - match response { - AnnounceIpv4(announce) => { - let json = json!({ - "transaction_id": announce.transaction_id.0, - "announce_interval": announce.announce_interval.0, - "leechers": announce.leechers.0, - "seeders": announce.seeders.0, - "peers": announce.peers.iter().map(|peer| format!("{}:{}", peer.ip_address, peer.port.0)).collect::>(), - }); - let pretty_json = serde_json::to_string_pretty(&json).context("announce IPv4 response JSON serialization")?; - println!("{pretty_json}"); - } - AnnounceIpv6(announce) => { - let json = json!({ - "transaction_id": announce.transaction_id.0, - "announce_interval": announce.announce_interval.0, - "leechers": announce.leechers.0, - "seeders": announce.seeders.0, - "peers6": announce.peers.iter().map(|peer| format!("{}:{}", peer.ip_address, peer.port.0)).collect::>(), - }); - let pretty_json = serde_json::to_string_pretty(&json).context("announce IPv6 response JSON serialization")?; - println!("{pretty_json}"); - } - Scrape(scrape) => { - let json = json!({ - "transaction_id": scrape.transaction_id.0, - "torrent_stats": scrape.torrent_stats.iter().map(|torrent_scrape_statistics| json!({ - "seeders": torrent_scrape_statistics.seeders.0, - "completed": torrent_scrape_statistics.completed.0, - "leechers": torrent_scrape_statistics.leechers.0, - })).collect::>(), - }); - let pretty_json = serde_json::to_string_pretty(&json).context("scrape response JSON serialization")?; - println!("{pretty_json}"); - } - _ => println!("{response:#?}"), // todo: serialize to JSON all responses. - }; - - Ok(()) + print_response(response) } fn setup_logging(level: LevelFilter) { @@ -207,6 +169,29 @@ async fn handle_scrape(tracker_socket_addr: &SocketAddr, info_hashes: &[TorrustI .await } +fn print_response(response: Response) -> anyhow::Result<()> { + match response { + AnnounceIpv4(response) => { + let pretty_json = serde_json::to_string_pretty(&AnnounceResponseDto::from(response)) + .context("announce IPv4 response JSON serialization")?; + println!("{pretty_json}"); + } + AnnounceIpv6(response) => { + let pretty_json = serde_json::to_string_pretty(&AnnounceResponseDto::from(response)) + .context("announce IPv6 response JSON serialization")?; + println!("{pretty_json}"); + } + Scrape(response) => { + let pretty_json = + serde_json::to_string_pretty(&ScrapeResponseDto::from(response)).context("scrape response JSON serialization")?; + println!("{pretty_json}"); + } + _ => println!("{response:#?}"), // todo: serialize to JSON all aquatic responses. + }; + + Ok(()) +} + fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); diff --git a/src/console/clients/udp/mod.rs b/src/console/clients/udp/mod.rs index cd0e8bd6b..2fcb26ed0 100644 --- a/src/console/clients/udp/mod.rs +++ b/src/console/clients/udp/mod.rs @@ -1,2 +1,3 @@ pub mod app; pub mod checker; +pub mod responses; diff --git a/src/console/clients/udp/responses.rs b/src/console/clients/udp/responses.rs new file mode 100644 index 000000000..020c7a367 --- /dev/null +++ b/src/console/clients/udp/responses.rs @@ -0,0 +1,83 @@ +//! Aquatic responses are not serializable. These are the serializable wrappers. +use std::net::{Ipv4Addr, Ipv6Addr}; + +use aquatic_udp_protocol::{AnnounceResponse, ScrapeResponse}; +use serde::Serialize; + +#[derive(Serialize)] +pub struct AnnounceResponseDto { + transaction_id: i32, + announce_interval: i32, + leechers: i32, + seeders: i32, + peers: Vec, +} + +impl From> for AnnounceResponseDto { + fn from(announce: AnnounceResponse) -> Self { + Self { + transaction_id: announce.transaction_id.0, + announce_interval: announce.announce_interval.0, + leechers: announce.leechers.0, + seeders: announce.seeders.0, + peers: announce + .peers + .iter() + .map(|peer| format!("{}:{}", peer.ip_address, peer.port.0)) + .collect::>(), + } + } +} + +impl From> for AnnounceResponseDto { + fn from(announce: AnnounceResponse) -> Self { + Self { + transaction_id: announce.transaction_id.0, + announce_interval: announce.announce_interval.0, + leechers: announce.leechers.0, + seeders: announce.seeders.0, + peers: announce + .peers + .iter() + .map(|peer| format!("{}:{}", peer.ip_address, peer.port.0)) + .collect::>(), + } + } +} + +#[derive(Serialize)] +pub struct ScrapeResponseDto { + transaction_id: i32, + torrent_stats: Vec, +} + +impl From for ScrapeResponseDto { + fn from(scrape: ScrapeResponse) -> Self { + Self { + transaction_id: scrape.transaction_id.0, + torrent_stats: scrape + .torrent_stats + .iter() + .map(|torrent_scrape_statistics| TorrentStats { + seeders: torrent_scrape_statistics.seeders.0, + completed: torrent_scrape_statistics.completed.0, + leechers: torrent_scrape_statistics.leechers.0, + }) + .collect::>(), + } + } +} + +#[derive(Serialize)] +struct Peer { + seeders: i32, + completed: i32, + leechers: i32, +} + +#[derive(Serialize)] +struct TorrentStats { + seeders: i32, + completed: i32, + leechers: i32, +} From 661b5210b05ccc7e858b070126a3174ba09da4a2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 Feb 2024 14:15:13 +0000 Subject: [PATCH 0223/1297] chore: [#639] add cargo dependency: hex_literal It allows simplifying the wasy we build InfoHashes from hex strings: ```rust let info_hash = InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237 ``` --- Cargo.lock | 7 +++++++ Cargo.toml | 1 + 2 files changed, 8 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index fa1d724e2..fc45cfc57 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1311,6 +1311,12 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hex-literal" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" + [[package]] name = "http" version = "0.2.11" @@ -3439,6 +3445,7 @@ dependencies = [ "derive_more", "fern", "futures", + "hex-literal", "hyper 1.1.0", "lazy_static", "local-ip-address", diff --git a/Cargo.toml b/Cargo.toml index 1418f23dd..bd04e1cc1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -74,6 +74,7 @@ url = "2.5.0" tempfile = "3.9.0" clap = { version = "4.4.18", features = ["derive", "env"]} anyhow = "1.0.79" +hex-literal = "0.4.1" [dev-dependencies] criterion = { version = "0.5.1", features = ["async_tokio"] } From bbfca2c184b9b75f17722cbec4cf8575d2caa09b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 Feb 2024 14:18:58 +0000 Subject: [PATCH 0224/1297] feat: [#639] Tracker Checker. Check UDP trackers This is the first working implementation. WIP. TODO: - Refactor: reorganize code: big functions, etc. - Bugs: if the UDP server is down the checker waits forever. Probably there is a missing timeout for the connection request. And in general for all requests. --- src/console/clients/checker/service.rs | 116 +++++++++++++++---------- 1 file changed, 72 insertions(+), 44 deletions(-) diff --git a/src/console/clients/checker/service.rs b/src/console/clients/checker/service.rs index 90dc10894..9ca24231f 100644 --- a/src/console/clients/checker/service.rs +++ b/src/console/clients/checker/service.rs @@ -3,19 +3,25 @@ use std::str::FromStr; use std::sync::Arc; use std::time::Duration; +use aquatic_udp_protocol::{Port, TransactionId}; use colored::Colorize; +use hex_literal::hex; use log::debug; use reqwest::{Client as HttpClient, Url}; use super::config::Configuration; use super::console::Console; use crate::console::clients::checker::printer::Printer; +use crate::console::clients::udp::checker; use crate::shared::bit_torrent::info_hash::InfoHash; use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; use crate::shared::bit_torrent::tracker::http::client::responses::scrape; use crate::shared::bit_torrent::tracker::http::client::{requests, Client}; +const ASSIGNED_BY_OS: u16 = 0; +const RANDOM_TRANSACTION_ID: i32 = -888_840_697; + pub struct Service { pub(crate) config: Arc, pub(crate) console: Console, @@ -25,7 +31,7 @@ pub type CheckResult = Result<(), CheckError>; #[derive(Debug)] pub enum CheckError { - UdpError, + UdpError { socket_addr: SocketAddr }, HttpError { url: Url }, HealthCheckError { url: Url }, } @@ -54,37 +60,63 @@ impl Service { for udp_tracker in &self.config.udp_trackers { let colored_tracker_url = udp_tracker.to_string().yellow(); - /* todo: - - Initialize the UDP client - - Pass the connected client the the check function - - Connect to the tracker - - Make the request (announce or scrape) - */ - - match self.check_udp_announce(udp_tracker).await { - Ok(()) => { - check_results.push(Ok(())); - self.console - .println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); - } - Err(err) => { - check_results.push(Err(err)); - self.console - .println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); - } + let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); + + let mut client = checker::Client::default(); + + let Ok(bound_to) = client.bind_and_connect(ASSIGNED_BY_OS, udp_tracker).await else { + check_results.push(Err(CheckError::UdpError { + socket_addr: *udp_tracker, + })); + self.console + .println(&format!("{} - Can't connect to socket {}", "✗".red(), colored_tracker_url)); + break; + }; + + let Ok(connection_id) = client.send_connection_request(transaction_id).await else { + check_results.push(Err(CheckError::UdpError { + socket_addr: *udp_tracker, + })); + self.console.println(&format!( + "{} - Can't make tracker connection request to {}", + "✗".red(), + colored_tracker_url + )); + break; + }; + + let info_hash = InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237 + + if (client + .send_announce_request(connection_id, transaction_id, info_hash, Port(bound_to.port())) + .await) + .is_ok() + { + check_results.push(Ok(())); + self.console + .println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); + } else { + let err = CheckError::UdpError { + socket_addr: *udp_tracker, + }; + check_results.push(Err(err)); + self.console + .println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); } - match self.check_udp_scrape(udp_tracker).await { - Ok(()) => { - check_results.push(Ok(())); - self.console - .println(&format!("{} - Scrape at {} is OK", "✓".green(), colored_tracker_url)); - } - Err(err) => { - check_results.push(Err(err)); - self.console - .println(&format!("{} - Scrape at {} is failing", "✗".red(), colored_tracker_url)); - } + let info_hashes = vec![InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422"))]; // # DevSkim: ignore DS173237 + + if (client.send_scrape_request(connection_id, transaction_id, info_hashes).await).is_ok() { + check_results.push(Ok(())); + self.console + .println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); + } else { + let err = CheckError::UdpError { + socket_addr: *udp_tracker, + }; + check_results.push(Err(err)); + self.console + .println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); } } } @@ -99,7 +131,7 @@ impl Service { Ok(()) => { check_results.push(Ok(())); self.console - .println(&format!("{} - Announce at {} is OK (TODO)", "✓".green(), colored_tracker_url)); + .println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); } Err(err) => { check_results.push(Err(err)); @@ -112,7 +144,7 @@ impl Service { Ok(()) => { check_results.push(Ok(())); self.console - .println(&format!("{} - Scrape at {} is OK (TODO)", "✓".green(), colored_tracker_url)); + .println(&format!("{} - Scrape at {} is OK", "✓".green(), colored_tracker_url)); } Err(err) => { check_results.push(Err(err)); @@ -134,22 +166,14 @@ impl Service { } } - #[allow(clippy::unused_async)] - async fn check_udp_announce(&self, tracker_socket_addr: &SocketAddr) -> Result<(), CheckError> { - debug!("{tracker_socket_addr}"); - Ok(()) - } - - #[allow(clippy::unused_async)] - async fn check_udp_scrape(&self, tracker_socket_addr: &SocketAddr) -> Result<(), CheckError> { - debug!("{tracker_socket_addr}"); - Ok(()) - } - async fn check_http_announce(&self, tracker_url: &Url) -> Result<(), CheckError> { let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // # DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); + // todo: HTTP request could panic.For example, if the server is not accessible. + // We should change the client to catch that error and return a `CheckError`. + // Otherwise the checking process will stop. The idea is to process all checks + // and return a final report. let response = Client::new(tracker_url.clone()) .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) .await; @@ -174,6 +198,10 @@ impl Service { let info_hashes: Vec = vec!["9c38422213e30bff212b30c360d26f9a02136422".to_string()]; // # DevSkim: ignore DS173237 let query = requests::scrape::Query::try_from(info_hashes).expect("a valid array of info-hashes is required"); + // todo: HTTP request could panic.For example, if the server is not accessible. + // We should change the client to catch that error and return a `CheckError`. + // Otherwise the checking process will stop. The idea is to process all checks + // and return a final report. let response = Client::new(url.clone()).scrape(&query).await; if let Ok(body) = response.bytes().await { From 6b74c66d35b98b161ebd8919ca994b202a7543d6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 Feb 2024 14:28:47 +0000 Subject: [PATCH 0225/1297] feat: [#639] Tracker Checker. Setup logging --- src/console/clients/checker/app.rs | 24 ++++++++++++++++++++++++ src/console/clients/checker/service.rs | 10 ++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/console/clients/checker/app.rs b/src/console/clients/checker/app.rs index bca4b64dc..82ea800d0 100644 --- a/src/console/clients/checker/app.rs +++ b/src/console/clients/checker/app.rs @@ -17,6 +17,7 @@ use std::sync::Arc; use anyhow::{Context, Result}; use clap::Parser; +use log::{debug, LevelFilter}; use super::config::Configuration; use super::console::Console; @@ -39,6 +40,8 @@ struct Args { /// /// Will return an error if the configuration was not provided. pub async fn run() -> Result> { + setup_logging(LevelFilter::Info); + let args = Args::parse(); let config = setup_config(args)?; @@ -53,6 +56,27 @@ pub async fn run() -> Result> { Ok(service.run_checks().await) } +fn setup_logging(level: LevelFilter) { + if let Err(_err) = fern::Dispatch::new() + .format(|out, message, record| { + out.finish(format_args!( + "{} [{}][{}] {}", + chrono::Local::now().format("%+"), + record.target(), + record.level(), + message + )); + }) + .level(level) + .chain(std::io::stdout()) + .apply() + { + panic!("Failed to initialize logging.") + } + + debug!("logging initialized."); +} + fn setup_config(args: Args) -> Result { match (args.config_path, args.config_content) { (Some(config_path), _) => load_config_from_file(&config_path), diff --git a/src/console/clients/checker/service.rs b/src/console/clients/checker/service.rs index 9ca24231f..40db30b90 100644 --- a/src/console/clients/checker/service.rs +++ b/src/console/clients/checker/service.rs @@ -58,12 +58,16 @@ impl Service { self.console.println("UDP trackers ..."); for udp_tracker in &self.config.udp_trackers { + debug!("UDP tracker: {:?}", udp_tracker); + let colored_tracker_url = udp_tracker.to_string().yellow(); let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); let mut client = checker::Client::default(); + debug!("Bind and connect"); + let Ok(bound_to) = client.bind_and_connect(ASSIGNED_BY_OS, udp_tracker).await else { check_results.push(Err(CheckError::UdpError { socket_addr: *udp_tracker, @@ -73,6 +77,8 @@ impl Service { break; }; + debug!("Send connection request"); + let Ok(connection_id) = client.send_connection_request(transaction_id).await else { check_results.push(Err(CheckError::UdpError { socket_addr: *udp_tracker, @@ -87,6 +93,8 @@ impl Service { let info_hash = InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237 + debug!("Send announce request"); + if (client .send_announce_request(connection_id, transaction_id, info_hash, Port(bound_to.port())) .await) @@ -104,6 +112,8 @@ impl Service { .println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); } + debug!("Send scrape request"); + let info_hashes = vec![InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422"))]; // # DevSkim: ignore DS173237 if (client.send_scrape_request(connection_id, transaction_id, info_hashes).await).is_ok() { From 592c0ddf48e3f9709e4c1bb642eb2e72dced64ce Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 Feb 2024 16:07:59 +0000 Subject: [PATCH 0226/1297] fix: add timeouts to UdpClient operations The generic UDP client does not have timeouts. When the server is down it waits forever for responses. This client has been using only for testing where the server was always up, but now it's using in production code by the Tracker Checker. For the time being, I keep the panicking behavior of the UdpClient when something is wrong. However we should return an error when the operation times out. For the Tracker Checker, it means that when the checker can't connect to a UDP server the checker is going to panic after 5 seconds. That is not the intended behavior for the checker. It should always return a full reprot of all checks. In order to implement that behavior we need to change the UdpClient to return errors. Since that's a bug refactor I open a new issue. --- src/shared/bit_torrent/tracker/udp/client.rs | 44 +++++++++++++++++--- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs index 41c9def89..11c8d8f62 100644 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -10,10 +10,18 @@ use tokio::time; use crate::shared::bit_torrent::tracker::udp::{source_address, MAX_PACKET_SIZE}; +/// Default timeout for sending and receiving packets. And waiting for sockets +/// to be readable and writable. +const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5); + #[allow(clippy::module_name_repetitions)] #[derive(Debug)] pub struct UdpClient { + /// The socket to connect to pub socket: Arc, + + /// Timeout for sending and receiving packets + pub timeout: Duration, } impl UdpClient { @@ -29,6 +37,7 @@ impl UdpClient { Self { socket: Arc::new(socket), + timeout: DEFAULT_TIMEOUT, } } @@ -53,10 +62,23 @@ impl UdpClient { /// - Can't write to the socket. /// - Can't send data. pub async fn send(&self, bytes: &[u8]) -> usize { - debug!(target: "UDP client", "send {bytes:?}"); + debug!(target: "UDP client", "sending {bytes:?} ..."); + + match time::timeout(self.timeout, self.socket.writable()).await { + Ok(writable_result) => match writable_result { + Ok(()) => (), + Err(e) => panic!("{}", format!("IO error waiting for the socket to become readable: {e:?}")), + }, + Err(e) => panic!("{}", format!("Timeout waiting for the socket to become readable: {e:?}")), + }; - self.socket.writable().await.unwrap(); - self.socket.send(bytes).await.unwrap() + match time::timeout(self.timeout, self.socket.send(bytes)).await { + Ok(send_result) => match send_result { + Ok(size) => size, + Err(e) => panic!("{}", format!("IO error during send: {e:?}")), + }, + Err(e) => panic!("{}", format!("Send operation timed out: {e:?}")), + } } /// # Panics @@ -68,9 +90,21 @@ impl UdpClient { pub async fn receive(&self, bytes: &mut [u8]) -> usize { debug!(target: "UDP client", "receiving ..."); - self.socket.readable().await.unwrap(); + match time::timeout(self.timeout, self.socket.readable()).await { + Ok(readable_result) => match readable_result { + Ok(()) => (), + Err(e) => panic!("{}", format!("IO error waiting for the socket to become readable: {e:?}")), + }, + Err(e) => panic!("{}", format!("Timeout waiting for the socket to become readable: {e:?}")), + }; - let size = self.socket.recv(bytes).await.unwrap(); + let size = match time::timeout(self.timeout, self.socket.recv(bytes)).await { + Ok(recv_result) => match recv_result { + Ok(size) => size, + Err(e) => panic!("{}", format!("IO error during send: {e:?}")), + }, + Err(e) => panic!("{}", format!("Receive operation timed out: {e:?}")), + }; debug!(target: "UDP client", "{size} bytes received {bytes:?}"); From 77c32a16a48abb2e43d411d13352371288f0d8c3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 Feb 2024 16:53:02 +0000 Subject: [PATCH 0227/1297] refactor: [#639] Tracker Checker: extract mod for UDP checks --- src/console/clients/checker/checks/health.rs | 0 src/console/clients/checker/checks/http.rs | 0 src/console/clients/checker/checks/mod.rs | 3 + src/console/clients/checker/checks/udp.rs | 87 ++++++++++++++++++++ src/console/clients/checker/mod.rs | 1 + src/console/clients/checker/service.rs | 86 +------------------ 6 files changed, 93 insertions(+), 84 deletions(-) create mode 100644 src/console/clients/checker/checks/health.rs create mode 100644 src/console/clients/checker/checks/http.rs create mode 100644 src/console/clients/checker/checks/mod.rs create mode 100644 src/console/clients/checker/checks/udp.rs diff --git a/src/console/clients/checker/checks/health.rs b/src/console/clients/checker/checks/health.rs new file mode 100644 index 000000000..e69de29bb diff --git a/src/console/clients/checker/checks/http.rs b/src/console/clients/checker/checks/http.rs new file mode 100644 index 000000000..e69de29bb diff --git a/src/console/clients/checker/checks/mod.rs b/src/console/clients/checker/checks/mod.rs new file mode 100644 index 000000000..16256595e --- /dev/null +++ b/src/console/clients/checker/checks/mod.rs @@ -0,0 +1,3 @@ +pub mod health; +pub mod http; +pub mod udp; diff --git a/src/console/clients/checker/checks/udp.rs b/src/console/clients/checker/checks/udp.rs new file mode 100644 index 000000000..890375b75 --- /dev/null +++ b/src/console/clients/checker/checks/udp.rs @@ -0,0 +1,87 @@ +use std::net::SocketAddr; + +use aquatic_udp_protocol::{Port, TransactionId}; +use colored::Colorize; +use hex_literal::hex; +use log::debug; + +use crate::console::clients::checker::console::Console; +use crate::console::clients::checker::printer::Printer; +use crate::console::clients::checker::service::{CheckError, CheckResult}; +use crate::console::clients::udp::checker; +use crate::shared::bit_torrent::info_hash::InfoHash; + +const ASSIGNED_BY_OS: u16 = 0; +const RANDOM_TRANSACTION_ID: i32 = -888_840_697; + +pub async fn run(udp_trackers: &Vec, console: &Console, check_results: &mut Vec) { + console.println("UDP trackers ..."); + + for udp_tracker in udp_trackers { + debug!("UDP tracker: {:?}", udp_tracker); + + let colored_tracker_url = udp_tracker.to_string().yellow(); + + let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); + + let mut client = checker::Client::default(); + + debug!("Bind and connect"); + + let Ok(bound_to) = client.bind_and_connect(ASSIGNED_BY_OS, udp_tracker).await else { + check_results.push(Err(CheckError::UdpError { + socket_addr: *udp_tracker, + })); + console.println(&format!("{} - Can't connect to socket {}", "✗".red(), colored_tracker_url)); + break; + }; + + debug!("Send connection request"); + + let Ok(connection_id) = client.send_connection_request(transaction_id).await else { + check_results.push(Err(CheckError::UdpError { + socket_addr: *udp_tracker, + })); + console.println(&format!( + "{} - Can't make tracker connection request to {}", + "✗".red(), + colored_tracker_url + )); + break; + }; + + let info_hash = InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237 + + debug!("Send announce request"); + + if (client + .send_announce_request(connection_id, transaction_id, info_hash, Port(bound_to.port())) + .await) + .is_ok() + { + check_results.push(Ok(())); + console.println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); + } else { + let err = CheckError::UdpError { + socket_addr: *udp_tracker, + }; + check_results.push(Err(err)); + console.println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); + } + + debug!("Send scrape request"); + + let info_hashes = vec![InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422"))]; // # DevSkim: ignore DS173237 + + if (client.send_scrape_request(connection_id, transaction_id, info_hashes).await).is_ok() { + check_results.push(Ok(())); + console.println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); + } else { + let err = CheckError::UdpError { + socket_addr: *udp_tracker, + }; + check_results.push(Err(err)); + console.println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); + } + } +} diff --git a/src/console/clients/checker/mod.rs b/src/console/clients/checker/mod.rs index 6a55141d5..d26a4a686 100644 --- a/src/console/clients/checker/mod.rs +++ b/src/console/clients/checker/mod.rs @@ -1,4 +1,5 @@ pub mod app; +pub mod checks; pub mod config; pub mod console; pub mod logger; diff --git a/src/console/clients/checker/service.rs b/src/console/clients/checker/service.rs index 40db30b90..62ac65636 100644 --- a/src/console/clients/checker/service.rs +++ b/src/console/clients/checker/service.rs @@ -3,25 +3,20 @@ use std::str::FromStr; use std::sync::Arc; use std::time::Duration; -use aquatic_udp_protocol::{Port, TransactionId}; use colored::Colorize; -use hex_literal::hex; use log::debug; use reqwest::{Client as HttpClient, Url}; +use super::checks; use super::config::Configuration; use super::console::Console; use crate::console::clients::checker::printer::Printer; -use crate::console::clients::udp::checker; use crate::shared::bit_torrent::info_hash::InfoHash; use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; use crate::shared::bit_torrent::tracker::http::client::responses::scrape; use crate::shared::bit_torrent::tracker::http::client::{requests, Client}; -const ASSIGNED_BY_OS: u16 = 0; -const RANDOM_TRANSACTION_ID: i32 = -888_840_697; - pub struct Service { pub(crate) config: Arc, pub(crate) console: Console, @@ -45,7 +40,7 @@ impl Service { let mut check_results = vec![]; - self.check_udp_trackers(&mut check_results).await; + checks::udp::run(&self.config.udp_trackers, &self.console, &mut check_results).await; self.check_http_trackers(&mut check_results).await; @@ -54,83 +49,6 @@ impl Service { check_results } - async fn check_udp_trackers(&self, check_results: &mut Vec) { - self.console.println("UDP trackers ..."); - - for udp_tracker in &self.config.udp_trackers { - debug!("UDP tracker: {:?}", udp_tracker); - - let colored_tracker_url = udp_tracker.to_string().yellow(); - - let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); - - let mut client = checker::Client::default(); - - debug!("Bind and connect"); - - let Ok(bound_to) = client.bind_and_connect(ASSIGNED_BY_OS, udp_tracker).await else { - check_results.push(Err(CheckError::UdpError { - socket_addr: *udp_tracker, - })); - self.console - .println(&format!("{} - Can't connect to socket {}", "✗".red(), colored_tracker_url)); - break; - }; - - debug!("Send connection request"); - - let Ok(connection_id) = client.send_connection_request(transaction_id).await else { - check_results.push(Err(CheckError::UdpError { - socket_addr: *udp_tracker, - })); - self.console.println(&format!( - "{} - Can't make tracker connection request to {}", - "✗".red(), - colored_tracker_url - )); - break; - }; - - let info_hash = InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237 - - debug!("Send announce request"); - - if (client - .send_announce_request(connection_id, transaction_id, info_hash, Port(bound_to.port())) - .await) - .is_ok() - { - check_results.push(Ok(())); - self.console - .println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); - } else { - let err = CheckError::UdpError { - socket_addr: *udp_tracker, - }; - check_results.push(Err(err)); - self.console - .println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); - } - - debug!("Send scrape request"); - - let info_hashes = vec![InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422"))]; // # DevSkim: ignore DS173237 - - if (client.send_scrape_request(connection_id, transaction_id, info_hashes).await).is_ok() { - check_results.push(Ok(())); - self.console - .println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); - } else { - let err = CheckError::UdpError { - socket_addr: *udp_tracker, - }; - check_results.push(Err(err)); - self.console - .println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); - } - } - } - async fn check_http_trackers(&self, check_results: &mut Vec) { self.console.println("HTTP trackers ..."); From 70924eddd06b4abd295bd57d553c6b92857eab10 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 Feb 2024 16:58:40 +0000 Subject: [PATCH 0228/1297] refactor: [#639] Tracker Checker: extract mod for HTTP checks --- src/console/clients/checker/checks/http.rs | 95 ++++++++++++++++++++++ src/console/clients/checker/service.rs | 93 +-------------------- 2 files changed, 96 insertions(+), 92 deletions(-) diff --git a/src/console/clients/checker/checks/http.rs b/src/console/clients/checker/checks/http.rs index e69de29bb..df1e9bc9a 100644 --- a/src/console/clients/checker/checks/http.rs +++ b/src/console/clients/checker/checks/http.rs @@ -0,0 +1,95 @@ +use std::str::FromStr; + +use colored::Colorize; +use log::debug; +use reqwest::Url as ServiceUrl; +use url::Url; + +use crate::console::clients::checker::console::Console; +use crate::console::clients::checker::printer::Printer; +use crate::console::clients::checker::service::{CheckError, CheckResult}; +use crate::shared::bit_torrent::info_hash::InfoHash; +use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; +use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; +use crate::shared::bit_torrent::tracker::http::client::responses::scrape; +use crate::shared::bit_torrent::tracker::http::client::{requests, Client}; + +pub async fn run(http_trackers: &Vec, console: &Console, check_results: &mut Vec) { + console.println("HTTP trackers ..."); + + for http_tracker in http_trackers { + let colored_tracker_url = http_tracker.to_string().yellow(); + + match check_http_announce(http_tracker).await { + Ok(()) => { + check_results.push(Ok(())); + console.println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); + } + Err(err) => { + check_results.push(Err(err)); + console.println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); + } + } + + match check_http_scrape(http_tracker).await { + Ok(()) => { + check_results.push(Ok(())); + console.println(&format!("{} - Scrape at {} is OK", "✓".green(), colored_tracker_url)); + } + Err(err) => { + check_results.push(Err(err)); + console.println(&format!("{} - Scrape at {} is failing", "✗".red(), colored_tracker_url)); + } + } + } +} + +async fn check_http_announce(tracker_url: &Url) -> Result<(), CheckError> { + let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // # DevSkim: ignore DS173237 + let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); + + // todo: HTTP request could panic.For example, if the server is not accessible. + // We should change the client to catch that error and return a `CheckError`. + // Otherwise the checking process will stop. The idea is to process all checks + // and return a final report. + let response = Client::new(tracker_url.clone()) + .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) + .await; + + if let Ok(body) = response.bytes().await { + if let Ok(_announce_response) = serde_bencode::from_bytes::(&body) { + Ok(()) + } else { + debug!("announce body {:#?}", body); + Err(CheckError::HttpError { + url: tracker_url.clone(), + }) + } + } else { + Err(CheckError::HttpError { + url: tracker_url.clone(), + }) + } +} + +async fn check_http_scrape(url: &Url) -> Result<(), CheckError> { + let info_hashes: Vec = vec!["9c38422213e30bff212b30c360d26f9a02136422".to_string()]; // # DevSkim: ignore DS173237 + let query = requests::scrape::Query::try_from(info_hashes).expect("a valid array of info-hashes is required"); + + // todo: HTTP request could panic.For example, if the server is not accessible. + // We should change the client to catch that error and return a `CheckError`. + // Otherwise the checking process will stop. The idea is to process all checks + // and return a final report. + let response = Client::new(url.clone()).scrape(&query).await; + + if let Ok(body) = response.bytes().await { + if let Ok(_scrape_response) = scrape::Response::try_from_bencoded(&body) { + Ok(()) + } else { + debug!("scrape body {:#?}", body); + Err(CheckError::HttpError { url: url.clone() }) + } + } else { + Err(CheckError::HttpError { url: url.clone() }) + } +} diff --git a/src/console/clients/checker/service.rs b/src/console/clients/checker/service.rs index 62ac65636..163b8f205 100644 --- a/src/console/clients/checker/service.rs +++ b/src/console/clients/checker/service.rs @@ -1,21 +1,14 @@ use std::net::SocketAddr; -use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use colored::Colorize; -use log::debug; use reqwest::{Client as HttpClient, Url}; use super::checks; use super::config::Configuration; use super::console::Console; use crate::console::clients::checker::printer::Printer; -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; -use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; -use crate::shared::bit_torrent::tracker::http::client::responses::scrape; -use crate::shared::bit_torrent::tracker::http::client::{requests, Client}; pub struct Service { pub(crate) config: Arc, @@ -42,47 +35,13 @@ impl Service { checks::udp::run(&self.config.udp_trackers, &self.console, &mut check_results).await; - self.check_http_trackers(&mut check_results).await; + checks::http::run(&self.config.http_trackers, &self.console, &mut check_results).await; self.run_health_checks(&mut check_results).await; check_results } - async fn check_http_trackers(&self, check_results: &mut Vec) { - self.console.println("HTTP trackers ..."); - - for http_tracker in &self.config.http_trackers { - let colored_tracker_url = http_tracker.to_string().yellow(); - - match self.check_http_announce(http_tracker).await { - Ok(()) => { - check_results.push(Ok(())); - self.console - .println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); - } - Err(err) => { - check_results.push(Err(err)); - self.console - .println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); - } - } - - match self.check_http_scrape(http_tracker).await { - Ok(()) => { - check_results.push(Ok(())); - self.console - .println(&format!("{} - Scrape at {} is OK", "✓".green(), colored_tracker_url)); - } - Err(err) => { - check_results.push(Err(err)); - self.console - .println(&format!("{} - Scrape at {} is failing", "✗".red(), colored_tracker_url)); - } - } - } - } - async fn run_health_checks(&self, check_results: &mut Vec) { self.console.println("Health checks ..."); @@ -94,56 +53,6 @@ impl Service { } } - async fn check_http_announce(&self, tracker_url: &Url) -> Result<(), CheckError> { - let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // # DevSkim: ignore DS173237 - let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); - - // todo: HTTP request could panic.For example, if the server is not accessible. - // We should change the client to catch that error and return a `CheckError`. - // Otherwise the checking process will stop. The idea is to process all checks - // and return a final report. - let response = Client::new(tracker_url.clone()) - .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) - .await; - - if let Ok(body) = response.bytes().await { - if let Ok(_announce_response) = serde_bencode::from_bytes::(&body) { - Ok(()) - } else { - debug!("announce body {:#?}", body); - Err(CheckError::HttpError { - url: tracker_url.clone(), - }) - } - } else { - Err(CheckError::HttpError { - url: tracker_url.clone(), - }) - } - } - - async fn check_http_scrape(&self, url: &Url) -> Result<(), CheckError> { - let info_hashes: Vec = vec!["9c38422213e30bff212b30c360d26f9a02136422".to_string()]; // # DevSkim: ignore DS173237 - let query = requests::scrape::Query::try_from(info_hashes).expect("a valid array of info-hashes is required"); - - // todo: HTTP request could panic.For example, if the server is not accessible. - // We should change the client to catch that error and return a `CheckError`. - // Otherwise the checking process will stop. The idea is to process all checks - // and return a final report. - let response = Client::new(url.clone()).scrape(&query).await; - - if let Ok(body) = response.bytes().await { - if let Ok(_scrape_response) = scrape::Response::try_from_bencoded(&body) { - Ok(()) - } else { - debug!("scrape body {:#?}", body); - Err(CheckError::HttpError { url: url.clone() }) - } - } else { - Err(CheckError::HttpError { url: url.clone() }) - } - } - async fn run_health_check(&self, url: Url) -> Result<(), CheckError> { let client = HttpClient::builder().timeout(Duration::from_secs(5)).build().unwrap(); From 873f98d872d8b0f17cb8d5b805db5d4d2a8ae954 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 Feb 2024 17:04:16 +0000 Subject: [PATCH 0229/1297] refactor: [#639] Tracker Checker: extract mod for Health checks --- src/console/clients/checker/checks/health.rs | 51 ++++++++++++++++++++ src/console/clients/checker/service.rs | 50 +------------------ 2 files changed, 53 insertions(+), 48 deletions(-) diff --git a/src/console/clients/checker/checks/health.rs b/src/console/clients/checker/checks/health.rs index e69de29bb..9c28da514 100644 --- a/src/console/clients/checker/checks/health.rs +++ b/src/console/clients/checker/checks/health.rs @@ -0,0 +1,51 @@ +use std::time::Duration; + +use colored::Colorize; +use reqwest::{Client as HttpClient, Url, Url as ServiceUrl}; + +use crate::console::clients::checker::console::Console; +use crate::console::clients::checker::printer::Printer; +use crate::console::clients::checker::service::{CheckError, CheckResult}; + +pub async fn run(health_checks: &Vec, console: &Console, check_results: &mut Vec) { + console.println("Health checks ..."); + + for health_check_url in health_checks { + match run_health_check(health_check_url.clone(), console).await { + Ok(()) => check_results.push(Ok(())), + Err(err) => check_results.push(Err(err)), + } + } +} + +async fn run_health_check(url: Url, console: &Console) -> Result<(), CheckError> { + let client = HttpClient::builder().timeout(Duration::from_secs(5)).build().unwrap(); + + let colored_url = url.to_string().yellow(); + + match client.get(url.clone()).send().await { + Ok(response) => { + if response.status().is_success() { + console.println(&format!("{} - Health API at {} is OK", "✓".green(), colored_url)); + Ok(()) + } else { + console.eprintln(&format!( + "{} - Health API at {} is failing: {:?}", + "✗".red(), + colored_url, + response + )); + Err(CheckError::HealthCheckError { url }) + } + } + Err(err) => { + console.eprintln(&format!( + "{} - Health API at {} is failing: {:?}", + "✗".red(), + colored_url, + err + )); + Err(CheckError::HealthCheckError { url }) + } + } +} diff --git a/src/console/clients/checker/service.rs b/src/console/clients/checker/service.rs index 163b8f205..94eff4a88 100644 --- a/src/console/clients/checker/service.rs +++ b/src/console/clients/checker/service.rs @@ -1,9 +1,7 @@ use std::net::SocketAddr; use std::sync::Arc; -use std::time::Duration; -use colored::Colorize; -use reqwest::{Client as HttpClient, Url}; +use reqwest::Url; use super::checks; use super::config::Configuration; @@ -37,52 +35,8 @@ impl Service { checks::http::run(&self.config.http_trackers, &self.console, &mut check_results).await; - self.run_health_checks(&mut check_results).await; + checks::health::run(&self.config.health_checks, &self.console, &mut check_results).await; check_results } - - async fn run_health_checks(&self, check_results: &mut Vec) { - self.console.println("Health checks ..."); - - for health_check_url in &self.config.health_checks { - match self.run_health_check(health_check_url.clone()).await { - Ok(()) => check_results.push(Ok(())), - Err(err) => check_results.push(Err(err)), - } - } - } - - async fn run_health_check(&self, url: Url) -> Result<(), CheckError> { - let client = HttpClient::builder().timeout(Duration::from_secs(5)).build().unwrap(); - - let colored_url = url.to_string().yellow(); - - match client.get(url.clone()).send().await { - Ok(response) => { - if response.status().is_success() { - self.console - .println(&format!("{} - Health API at {} is OK", "✓".green(), colored_url)); - Ok(()) - } else { - self.console.eprintln(&format!( - "{} - Health API at {} is failing: {:?}", - "✗".red(), - colored_url, - response - )); - Err(CheckError::HealthCheckError { url }) - } - } - Err(err) => { - self.console.eprintln(&format!( - "{} - Health API at {} is failing: {:?}", - "✗".red(), - colored_url, - err - )); - Err(CheckError::HealthCheckError { url }) - } - } - } } From 36fcee7d81ecfe8c9475388de40323dac3d7f65d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 12 Feb 2024 07:34:12 +0000 Subject: [PATCH 0230/1297] fix: [#691] unknown feature stdsimd ``` error[E0635]: unknown feature `stdsimd` --> /home/josecelano/.cargo/registry/src/index.crates.io-6f17d22bba15001f/ahash-0.7.7/src/lib.rs:33:42 | 33 | #![cfg_attr(feature = "stdsimd", feature(stdsimd))] | ^^^^^^^ Compiling aho-corasick v1.1.2 For more information about this error, try `rustc --explain E0635`. error: could not compile `ahash` (lib) due to 1 previous error warning: build failed, waiting for other jobs to finish... ``` With: ``` nightly-x86_64-unknown-linux-gnu (default) rustc 1.78.0-nightly (98aa3624b 2024-02-08) `` --- Cargo.lock | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fc45cfc57..6b04e273b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19,9 +19,9 @@ checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "ahash" -version = "0.7.7" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a824f2aa7e75a0c98c5a504fceb80649e9c35265d44525b5f94de4771a395cd" +checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" dependencies = [ "getrandom", "once_cell", @@ -30,9 +30,9 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.7" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77c3a9648d43b9cd48db467b3f87fdd6e146bcc88ab0180006cef2179fe11d01" +checksum = "42cd52102d3df161c77a887b608d7a4897d7cc112886a9537b738a887a03aaff" dependencies = [ "cfg-if", "once_cell", @@ -1262,7 +1262,7 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" dependencies = [ - "ahash 0.7.7", + "ahash 0.7.8", ] [[package]] @@ -1271,7 +1271,7 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" dependencies = [ - "ahash 0.8.7", + "ahash 0.8.8", ] [[package]] @@ -1280,7 +1280,7 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" dependencies = [ - "ahash 0.8.7", + "ahash 0.8.8", "allocator-api2", ] From 945e91f36e4391d6b30d54474c087576a697208a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 19 Feb 2024 10:28:48 +0000 Subject: [PATCH 0231/1297] chore: [#696] add cargo dependencies for logging - `tower-http` - `trace` - `tracing` --- Cargo.lock | 27 +++++++++++++++++++++++++++ Cargo.toml | 4 +++- cSpell.json | 1 + 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 6b04e273b..aae5deb9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3479,6 +3479,8 @@ dependencies = [ "torrust-tracker-primitives", "torrust-tracker-test-helpers", "tower-http", + "trace", + "tracing", "url", "uuid", ] @@ -3567,6 +3569,8 @@ dependencies = [ "tokio-util", "tower-layer", "tower-service", + "tracing", + "uuid", ] [[package]] @@ -3581,6 +3585,17 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" +[[package]] +name = "trace" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ad0c048e114d19d1140662762bfdb10682f3bc806d8be18af846600214dd9af" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "tracing" version = "0.1.40" @@ -3589,9 +3604,21 @@ checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" dependencies = [ "log", "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.48", +] + [[package]] name = "tracing-core" version = "0.1.32" diff --git a/Cargo.toml b/Cargo.toml index bd04e1cc1..83134d8f0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,7 +67,7 @@ torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "pa torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12-develop", path = "contrib/bencode" } torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "packages/located-error" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } -tower-http = { version = "0", features = ["compression-full"] } +tower-http = { version = "0", features = ["compression-full", "cors", "trace", "propagate-header", "request-id"] } uuid = { version = "1", features = ["v4"] } colored = "2.1.0" url = "2.5.0" @@ -75,6 +75,8 @@ tempfile = "3.9.0" clap = { version = "4.4.18", features = ["derive", "env"]} anyhow = "1.0.79" hex-literal = "0.4.1" +trace = "0.1.7" +tracing = "0.1.40" [dev-dependencies] criterion = { version = "0.5.1", features = ["async_tokio"] } diff --git a/cSpell.json b/cSpell.json index aaa3229c2..646037e59 100644 --- a/cSpell.json +++ b/cSpell.json @@ -117,6 +117,7 @@ "Swatinem", "Swiftbit", "taiki", + "tdyne", "tempfile", "thiserror", "tlsv", From 32727caff159f3b3200ad7e53f1f95f56cc4ef6b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 19 Feb 2024 10:30:01 +0000 Subject: [PATCH 0232/1297] feat: [#696] API, log request and responses --- src/servers/apis/routes.rs | 52 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 227916335..aed3ee19d 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -6,11 +6,20 @@ //! All the API routes have the `/api` prefix and the version number as the //! first path segment. For example: `/api/v1/torrents`. use std::sync::Arc; +use std::time::Duration; +use axum::http::{HeaderName, HeaderValue}; +use axum::response::Response; use axum::routing::get; use axum::{middleware, Router}; +use hyper::Request; use torrust_tracker_configuration::AccessTokens; use tower_http::compression::CompressionLayer; +use tower_http::propagate_header::PropagateHeaderLayer; +use tower_http::request_id::{MakeRequestId, RequestId, SetRequestIdLayer}; +use tower_http::trace::{DefaultMakeSpan, TraceLayer}; +use tracing::{Level, Span}; +use uuid::Uuid; use super::v1; use super::v1::context::health_check::handlers::health_check_handler; @@ -32,4 +41,47 @@ pub fn router(tracker: Arc, access_tokens: Arc) -> Router .layer(middleware::from_fn_with_state(state, v1::middlewares::auth::auth)) .route(&format!("{api_url_prefix}/health_check"), get(health_check_handler)) .layer(CompressionLayer::new()) + .layer(SetRequestIdLayer::x_request_id(RequestIdGenerator)) + .layer(PropagateHeaderLayer::new(HeaderName::from_static("x-request-id"))) + .layer( + TraceLayer::new_for_http() + .make_span_with(DefaultMakeSpan::new().level(Level::INFO)) + .on_request(|request: &Request, _span: &Span| { + let method = request.method().to_string(); + let uri = request.uri().to_string(); + let request_id = request + .headers() + .get("x-request-id") + .map(|v| v.to_str().unwrap_or_default()) + .unwrap_or_default(); + + tracing::span!( + target: "API", + tracing::Level::INFO, "request", method = %method, uri = %uri, request_id = %request_id); + }) + .on_response(|response: &Response, latency: Duration, _span: &Span| { + let status_code = response.status(); + let request_id = response + .headers() + .get("x-request-id") + .map(|v| v.to_str().unwrap_or_default()) + .unwrap_or_default(); + let latency_ms = latency.as_millis(); + + tracing::span!( + target: "API", + tracing::Level::INFO, "response", latency = %latency_ms, status = %status_code, request_id = %request_id); + }), + ) + .layer(SetRequestIdLayer::x_request_id(RequestIdGenerator)) +} + +#[derive(Clone, Default)] +struct RequestIdGenerator; + +impl MakeRequestId for RequestIdGenerator { + fn make_request_id(&mut self, _request: &Request) -> Option { + let id = HeaderValue::from_str(&Uuid::new_v4().to_string()).expect("UUID is a valid HTTP header value"); + Some(RequestId::new(id)) + } } From 5ccdf10a3fd814702fed72a17428fdc5b6996263 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 19 Feb 2024 10:38:12 +0000 Subject: [PATCH 0233/1297] fix: build errors `imported redundantly` --- contrib/bencode/src/mutable/encode.rs | 2 -- contrib/bencode/src/reference/bencode_ref.rs | 2 -- contrib/bencode/src/reference/decode.rs | 2 -- contrib/bencode/src/reference/decode_opt.rs | 2 -- src/console/clients/checker/config.rs | 3 +-- src/core/peer.rs | 1 - src/servers/apis/v1/context/auth_key/resources.rs | 1 - src/servers/http/v1/responses/error.rs | 2 +- src/shared/bit_torrent/tracker/http/client/requests/scrape.rs | 1 - .../bit_torrent/tracker/http/client/responses/announce.rs | 2 +- src/shared/bit_torrent/tracker/http/client/responses/error.rs | 2 +- src/shared/bit_torrent/tracker/http/client/responses/scrape.rs | 2 +- src/shared/crypto/keys.rs | 2 -- tests/servers/http/responses/announce.rs | 2 +- tests/servers/http/responses/error.rs | 2 +- tests/servers/http/responses/scrape.rs | 2 +- 16 files changed, 8 insertions(+), 22 deletions(-) diff --git a/contrib/bencode/src/mutable/encode.rs b/contrib/bencode/src/mutable/encode.rs index 811c35816..25c91b41d 100644 --- a/contrib/bencode/src/mutable/encode.rs +++ b/contrib/bencode/src/mutable/encode.rs @@ -1,5 +1,3 @@ -use std::iter::Extend; - use crate::access::bencode::{BRefAccess, RefKind}; use crate::access::dict::BDictAccess; use crate::access::list::BListAccess; diff --git a/contrib/bencode/src/reference/bencode_ref.rs b/contrib/bencode/src/reference/bencode_ref.rs index 760dd3016..a6f2c15bc 100644 --- a/contrib/bencode/src/reference/bencode_ref.rs +++ b/contrib/bencode/src/reference/bencode_ref.rs @@ -125,8 +125,6 @@ impl<'a> BRefAccessExt<'a> for BencodeRef<'a> { #[cfg(test)] mod tests { - use std::default::Default; - use crate::access::bencode::BRefAccess; use crate::reference::bencode_ref::BencodeRef; use crate::reference::decode_opt::BDecodeOpt; diff --git a/contrib/bencode/src/reference/decode.rs b/contrib/bencode/src/reference/decode.rs index d2aa180f8..d35d1b597 100644 --- a/contrib/bencode/src/reference/decode.rs +++ b/contrib/bencode/src/reference/decode.rs @@ -177,8 +177,6 @@ fn peek_byte(bytes: &[u8], pos: usize) -> BencodeParseResult { #[cfg(test)] mod tests { - use std::default::Default; - use crate::access::bencode::BRefAccess; use crate::reference::bencode_ref::BencodeRef; use crate::reference::decode_opt::BDecodeOpt; diff --git a/contrib/bencode/src/reference/decode_opt.rs b/contrib/bencode/src/reference/decode_opt.rs index e8d9a8337..8409cc72c 100644 --- a/contrib/bencode/src/reference/decode_opt.rs +++ b/contrib/bencode/src/reference/decode_opt.rs @@ -1,5 +1,3 @@ -use std::default::Default; - const DEFAULT_MAX_RECURSION: usize = 50; const DEFAULT_CHECK_KEY_SORT: bool = false; const DEFAULT_ENFORCE_FULL_DECODE: bool = true; diff --git a/src/console/clients/checker/config.rs b/src/console/clients/checker/config.rs index 0a2c09b03..6e44d889b 100644 --- a/src/console/clients/checker/config.rs +++ b/src/console/clients/checker/config.rs @@ -4,7 +4,6 @@ use std::net::SocketAddr; use reqwest::Url as ServiceUrl; use serde::Deserialize; -use url; /// It parses the configuration from a JSON format. /// @@ -88,7 +87,7 @@ impl TryFrom for Configuration { #[cfg(test)] mod tests { - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::net::{IpAddr, Ipv4Addr}; use super::*; diff --git a/src/core/peer.rs b/src/core/peer.rs index 03489ce30..16aa1fe56 100644 --- a/src/core/peer.rs +++ b/src/core/peer.rs @@ -24,7 +24,6 @@ use std::net::{IpAddr, SocketAddr}; use std::panic::Location; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; -use serde; use serde::Serialize; use thiserror::Error; diff --git a/src/servers/apis/v1/context/auth_key/resources.rs b/src/servers/apis/v1/context/auth_key/resources.rs index f4c7f34ca..99e93aaf9 100644 --- a/src/servers/apis/v1/context/auth_key/resources.rs +++ b/src/servers/apis/v1/context/auth_key/resources.rs @@ -1,5 +1,4 @@ //! API resources for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. -use std::convert::From; use serde::{Deserialize, Serialize}; diff --git a/src/servers/http/v1/responses/error.rs b/src/servers/http/v1/responses/error.rs index 606ead3b2..1cc31ad4e 100644 --- a/src/servers/http/v1/responses/error.rs +++ b/src/servers/http/v1/responses/error.rs @@ -13,7 +13,7 @@ //! code. use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; -use serde::{self, Serialize}; +use serde::Serialize; /// `Error` response for the [`HTTP tracker`](crate::servers::http). #[derive(Serialize, Debug, PartialEq)] diff --git a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs index d0268d1f8..4fa49eed6 100644 --- a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs +++ b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs @@ -1,4 +1,3 @@ -use std::convert::TryFrom; use std::error::Error; use std::fmt::{self}; use std::str::FromStr; diff --git a/src/shared/bit_torrent/tracker/http/client/responses/announce.rs b/src/shared/bit_torrent/tracker/http/client/responses/announce.rs index f68c54482..e75cc6671 100644 --- a/src/shared/bit_torrent/tracker/http/client/responses/announce.rs +++ b/src/shared/bit_torrent/tracker/http/client/responses/announce.rs @@ -1,6 +1,6 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use serde::{self, Deserialize, Serialize}; +use serde::{Deserialize, Serialize}; use crate::core::peer::Peer; diff --git a/src/shared/bit_torrent/tracker/http/client/responses/error.rs b/src/shared/bit_torrent/tracker/http/client/responses/error.rs index 12c53a0cf..00befdb54 100644 --- a/src/shared/bit_torrent/tracker/http/client/responses/error.rs +++ b/src/shared/bit_torrent/tracker/http/client/responses/error.rs @@ -1,4 +1,4 @@ -use serde::{self, Deserialize, Serialize}; +use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Error { diff --git a/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs b/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs index ee301ee7a..25a2f0a81 100644 --- a/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs +++ b/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs @@ -3,7 +3,7 @@ use std::fmt::Write; use std::str; use serde::ser::SerializeMap; -use serde::{self, Deserialize, Serialize, Serializer}; +use serde::{Deserialize, Serialize, Serializer}; use serde_bencode::value::Value; use crate::shared::bit_torrent::tracker::http::{ByteArray20, InfoHash}; diff --git a/src/shared/crypto/keys.rs b/src/shared/crypto/keys.rs index 92e180996..deb70574f 100644 --- a/src/shared/crypto/keys.rs +++ b/src/shared/crypto/keys.rs @@ -86,8 +86,6 @@ pub mod seeds { #[cfg(test)] mod tests { - use std::convert::TryInto; - use crate::shared::crypto::ephemeral_instance_keys::RANDOM_SEED; use crate::shared::crypto::keys::seeds::detail::ZEROED_TEST_SEED; use crate::shared::crypto::keys::seeds::CURRENT_SEED; diff --git a/tests/servers/http/responses/announce.rs b/tests/servers/http/responses/announce.rs index a57b41c78..968c327eb 100644 --- a/tests/servers/http/responses/announce.rs +++ b/tests/servers/http/responses/announce.rs @@ -1,6 +1,6 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use serde::{self, Deserialize, Serialize}; +use serde::{Deserialize, Serialize}; use torrust_tracker::core::peer::Peer; #[derive(Serialize, Deserialize, Debug, PartialEq)] diff --git a/tests/servers/http/responses/error.rs b/tests/servers/http/responses/error.rs index 12c53a0cf..00befdb54 100644 --- a/tests/servers/http/responses/error.rs +++ b/tests/servers/http/responses/error.rs @@ -1,4 +1,4 @@ -use serde::{self, Deserialize, Serialize}; +use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Error { diff --git a/tests/servers/http/responses/scrape.rs b/tests/servers/http/responses/scrape.rs index 221ff0a38..eadecb603 100644 --- a/tests/servers/http/responses/scrape.rs +++ b/tests/servers/http/responses/scrape.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use std::str; -use serde::{self, Deserialize, Serialize}; +use serde::{Deserialize, Serialize}; use serde_bencode::value::Value; use crate::servers::http::{ByteArray20, InfoHash}; From e0836bd323cae1cbf8c0d1a92bb1566c0bd0f892 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 19 Feb 2024 11:33:56 +0000 Subject: [PATCH 0234/1297] feat: [#700] add logs to Health Check API `````` 2024-02-19T11:30:21.061293933+00:00 [HEALTH CHECK API][INFO] request; method=GET uri=/health_check request_id=78933bbf-c4cf-4897-b972-4c0fd252159a 2024-02-19T11:30:21.070329733+00:00 [HEALTH CHECK API][INFO] response; latency=9 status=200 OK request_id=78933bbf-c4cf-4897-b972-4c0fd252159a ``` --- src/bootstrap/jobs/health_check_api.rs | 6 +- src/console/ci/e2e/logs_parser.rs | 8 +-- src/servers/health_check_api/server.rs | 58 ++++++++++++++++++- tests/servers/health_check_api/environment.rs | 8 +-- 4 files changed, 67 insertions(+), 13 deletions(-) diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index e57d1c151..eec4d81a8 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -47,18 +47,18 @@ pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> Jo // Run the API server let join_handle = tokio::spawn(async move { - info!(target: "Health Check API", "Starting on: {protocol}://{}", bind_addr); + info!(target: "HEALTH CHECK API", "Starting on: {protocol}://{}", bind_addr); let handle = server::start(bind_addr, tx_start, rx_halt, register); if let Ok(()) = handle.await { - info!(target: "Health Check API", "Stopped server running on: {protocol}://{}", bind_addr); + info!(target: "HEALTH CHECK API", "Stopped server running on: {protocol}://{}", bind_addr); } }); // Wait until the server sends the started message match rx_start.await { - Ok(msg) => info!(target: "Health Check API", "Started on: {protocol}://{}", msg.address), + Ok(msg) => info!(target: "HEALTH CHECK API", "Started on: {protocol}://{}", msg.address), Err(e) => panic!("the Health Check API server was dropped: {e}"), } diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index 1d6baa23e..82e37f7d7 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize}; const UDP_TRACKER_PATTERN: &str = "[UDP Tracker][INFO] Starting on: udp://"; const HTTP_TRACKER_PATTERN: &str = "[HTTP Tracker][INFO] Starting on: "; -const HEALTH_CHECK_PATTERN: &str = "[Health Check API][INFO] Starting on: "; +const HEALTH_CHECK_PATTERN: &str = "[HEALTH CHECK API][INFO] Starting on: "; #[derive(Serialize, Deserialize, Debug, Default)] pub struct RunningServices { @@ -27,8 +27,8 @@ impl RunningServices { /// 2024-01-24T16:36:14.615716574+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled /// 2024-01-24T16:36:14.615764904+00:00 [API][INFO] Starting on http://127.0.0.1:1212 /// 2024-01-24T16:36:14.615767264+00:00 [API][INFO] Started on http://127.0.0.1:1212 - /// 2024-01-24T16:36:14.615777574+00:00 [Health Check API][INFO] Starting on: http://127.0.0.1:1313 - /// 2024-01-24T16:36:14.615791124+00:00 [Health Check API][INFO] Started on: http://127.0.0.1:1313 + /// 2024-01-24T16:36:14.615777574+00:00 [HEALTH CHECK API][INFO] Starting on: http://127.0.0.1:1313 + /// 2024-01-24T16:36:14.615791124+00:00 [HEALTH CHECK API][INFO] Started on: http://127.0.0.1:1313 /// ``` /// /// It would extract these services: @@ -88,7 +88,7 @@ mod tests { let logs = "\ [UDP Tracker][INFO] Starting on: udp://0.0.0.0:8080\n\ [HTTP Tracker][INFO] Starting on: 0.0.0.0:9090\n\ - [Health Check API][INFO] Starting on: 0.0.0.0:10010"; + [HEALTH CHECK API][INFO] Starting on: 0.0.0.0:10010"; let running_services = RunningServices::parse_from_logs(logs); assert_eq!(running_services.udp_trackers, vec!["127.0.0.1:8080"]); diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index 8ba20691f..049f48d40 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -3,14 +3,24 @@ //! This API is intended to be used by the container infrastructure to check if //! the whole application is healthy. use std::net::SocketAddr; +use std::time::Duration; +use axum::http::{HeaderName, HeaderValue}; +use axum::response::Response; use axum::routing::get; use axum::{Json, Router}; use axum_server::Handle; use futures::Future; +use hyper::Request; use log::debug; use serde_json::json; use tokio::sync::oneshot::{Receiver, Sender}; +use tower_http::compression::CompressionLayer; +use tower_http::propagate_header::PropagateHeaderLayer; +use tower_http::request_id::{MakeRequestId, RequestId, SetRequestIdLayer}; +use tower_http::trace::{DefaultMakeSpan, TraceLayer}; +use tracing::{Level, Span}; +use uuid::Uuid; use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; @@ -31,14 +41,48 @@ pub fn start( let router = Router::new() .route("/", get(|| async { Json(json!({})) })) .route("/health_check", get(health_check_handler)) - .with_state(register); + .with_state(register) + .layer(CompressionLayer::new()) + .layer(SetRequestIdLayer::x_request_id(RequestIdGenerator)) + .layer(PropagateHeaderLayer::new(HeaderName::from_static("x-request-id"))) + .layer( + TraceLayer::new_for_http() + .make_span_with(DefaultMakeSpan::new().level(Level::INFO)) + .on_request(|request: &Request, _span: &Span| { + let method = request.method().to_string(); + let uri = request.uri().to_string(); + let request_id = request + .headers() + .get("x-request-id") + .map(|v| v.to_str().unwrap_or_default()) + .unwrap_or_default(); + + tracing::span!( + target: "HEALTH CHECK API", + tracing::Level::INFO, "request", method = %method, uri = %uri, request_id = %request_id); + }) + .on_response(|response: &Response, latency: Duration, _span: &Span| { + let status_code = response.status(); + let request_id = response + .headers() + .get("x-request-id") + .map(|v| v.to_str().unwrap_or_default()) + .unwrap_or_default(); + let latency_ms = latency.as_millis(); + + tracing::span!( + target: "HEALTH CHECK API", + tracing::Level::INFO, "response", latency = %latency_ms, status = %status_code, request_id = %request_id); + }), + ) + .layer(SetRequestIdLayer::x_request_id(RequestIdGenerator)); let socket = std::net::TcpListener::bind(bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); let handle = Handle::new(); - debug!(target: "Health Check API", "Starting service with graceful shutdown in a spawned task ..."); + debug!(target: "HEALTH CHECK API", "Starting service with graceful shutdown in a spawned task ..."); tokio::task::spawn(graceful_shutdown( handle.clone(), @@ -55,3 +99,13 @@ pub fn start( running } + +#[derive(Clone, Default)] +struct RequestIdGenerator; + +impl MakeRequestId for RequestIdGenerator { + fn make_request_id(&mut self, _request: &Request) -> Option { + let id = HeaderValue::from_str(&Uuid::new_v4().to_string()).expect("UUID is a valid HTTP header value"); + Some(RequestId::new(id)) + } +} diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs index c98784282..37344858d 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/tests/servers/health_check_api/environment.rs @@ -51,21 +51,21 @@ impl Environment { let register = self.registar.entries(); - debug!(target: "Health Check API", "Spawning task to launch the service ..."); + debug!(target: "HEALTH CHECK API", "Spawning task to launch the service ..."); let server = tokio::spawn(async move { - debug!(target: "Health Check API", "Starting the server in a spawned task ..."); + debug!(target: "HEALTH CHECK API", "Starting the server in a spawned task ..."); server::start(self.state.bind_to, tx_start, rx_halt, register) .await .expect("it should start the health check service"); - debug!(target: "Health Check API", "Server started. Sending the binding {} ...", self.state.bind_to); + debug!(target: "HEALTH CHECK API", "Server started. Sending the binding {} ...", self.state.bind_to); self.state.bind_to }); - debug!(target: "Health Check API", "Waiting for spawning task to send the binding ..."); + debug!(target: "HEALTH CHECK API", "Waiting for spawning task to send the binding ..."); let binding = rx_start.await.expect("it should send service binding").address; From 30ae6dfd94859768c4b8f9121ad260f0a5cb9f3c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 19 Feb 2024 13:01:19 +0000 Subject: [PATCH 0235/1297] feat: [#697] add logs to HTTP tracker Sample logs: ``` 2024-02-19T13:29:02.301023716+00:00 [HTTP TRACKER][INFO] request; server_socket_addr=0.0.0.0:7070 method=GET uri=/scrape?info_hash=%44%3C%76%02%B4%FD%E8%3D%11%54%D6%D9%DA%48%80%84%18%B1%81%B6 request_id=2c4aa57d-dd12-4cb8-95d1-e8193627c106 2024-02-19T13:29:02.301095545+00:00 [HTTP TRACKER][INFO] response; server_socket_addr=0.0.0.0:7070 latency=0 status=200 OK request_id=2c4aa57d-dd12-4cb8-95d1-e8193627c106 ``` --- src/console/ci/e2e/logs_parser.rs | 8 ++--- src/servers/http/server.rs | 7 ++-- src/servers/http/v1/routes.rs | 55 ++++++++++++++++++++++++++++++- 3 files changed, 62 insertions(+), 8 deletions(-) diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index 82e37f7d7..ca4d6099c 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize}; const UDP_TRACKER_PATTERN: &str = "[UDP Tracker][INFO] Starting on: udp://"; -const HTTP_TRACKER_PATTERN: &str = "[HTTP Tracker][INFO] Starting on: "; +const HTTP_TRACKER_PATTERN: &str = "[HTTP TRACKER][INFO] Starting on: "; const HEALTH_CHECK_PATTERN: &str = "[HEALTH CHECK API][INFO] Starting on: "; #[derive(Serialize, Deserialize, Debug, Default)] @@ -22,8 +22,8 @@ impl RunningServices { /// 2024-01-24T16:36:14.614898789+00:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized. /// 2024-01-24T16:36:14.615586025+00:00 [UDP Tracker][INFO] Starting on: udp://0.0.0.0:6969 /// 2024-01-24T16:36:14.615623705+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled - /// 2024-01-24T16:36:14.615694484+00:00 [HTTP Tracker][INFO] Starting on: http://0.0.0.0:7070 - /// 2024-01-24T16:36:14.615710534+00:00 [HTTP Tracker][INFO] Started on: http://0.0.0.0:7070 + /// 2024-01-24T16:36:14.615694484+00:00 [HTTP TRACKER][INFO] Starting on: http://0.0.0.0:7070 + /// 2024-01-24T16:36:14.615710534+00:00 [HTTP TRACKER][INFO] Started on: http://0.0.0.0:7070 /// 2024-01-24T16:36:14.615716574+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled /// 2024-01-24T16:36:14.615764904+00:00 [API][INFO] Starting on http://127.0.0.1:1212 /// 2024-01-24T16:36:14.615767264+00:00 [API][INFO] Started on http://127.0.0.1:1212 @@ -87,7 +87,7 @@ mod tests { fn it_should_parse_from_logs_with_valid_logs() { let logs = "\ [UDP Tracker][INFO] Starting on: udp://0.0.0.0:8080\n\ - [HTTP Tracker][INFO] Starting on: 0.0.0.0:9090\n\ + [HTTP TRACKER][INFO] Starting on: 0.0.0.0:9090\n\ [HEALTH CHECK API][INFO] Starting on: 0.0.0.0:10010"; let running_services = RunningServices::parse_from_logs(logs); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 20e57db57..decc734c5 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -40,7 +40,6 @@ pub struct Launcher { impl Launcher { fn start(&self, tracker: Arc, tx_start: Sender, rx_halt: Receiver) -> BoxFuture<'static, ()> { - let app = router(tracker); let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); @@ -55,7 +54,9 @@ impl Launcher { let tls = self.tls.clone(); let protocol = if tls.is_some() { "https" } else { "http" }; - info!(target: "HTTP Tracker", "Starting on: {protocol}://{}", address); + info!(target: "HTTP TRACKER", "Starting on: {protocol}://{}", address); + + let app = router(tracker, address); let running = Box::pin(async { match tls { @@ -72,7 +73,7 @@ impl Launcher { } }); - info!(target: "HTTP Tracker", "Started on: {protocol}://{}", address); + info!(target: "HTTP TRACKER", "Started on: {protocol}://{}", address); tx_start .send(Started { address }) diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 20e96d7fd..b972cf62f 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -1,10 +1,20 @@ //! HTTP server routes for version `v1`. +use std::net::SocketAddr; use std::sync::Arc; +use std::time::Duration; +use axum::http::{HeaderName, HeaderValue}; +use axum::response::Response; use axum::routing::get; use axum::Router; use axum_client_ip::SecureClientIpSource; +use hyper::Request; use tower_http::compression::CompressionLayer; +use tower_http::propagate_header::PropagateHeaderLayer; +use tower_http::request_id::{MakeRequestId, RequestId, SetRequestIdLayer}; +use tower_http::trace::{DefaultMakeSpan, TraceLayer}; +use tracing::{Level, Span}; +use uuid::Uuid; use super::handlers::{announce, health_check, scrape}; use crate::core::Tracker; @@ -14,7 +24,7 @@ use crate::core::Tracker; /// > **NOTICE**: it's added a layer to get the client IP from the connection /// info. The tracker could use the connection info to get the client IP. #[allow(clippy::needless_pass_by_value)] -pub fn router(tracker: Arc) -> Router { +pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { Router::new() // Health check .route("/health_check", get(health_check::handler)) @@ -27,4 +37,47 @@ pub fn router(tracker: Arc) -> Router { // Add extension to get the client IP from the connection info .layer(SecureClientIpSource::ConnectInfo.into_extension()) .layer(CompressionLayer::new()) + .layer(SetRequestIdLayer::x_request_id(RequestIdGenerator)) + .layer(PropagateHeaderLayer::new(HeaderName::from_static("x-request-id"))) + .layer( + TraceLayer::new_for_http() + .make_span_with(DefaultMakeSpan::new().level(Level::INFO)) + .on_request(move |request: &Request, _span: &Span| { + let method = request.method().to_string(); + let uri = request.uri().to_string(); + let request_id = request + .headers() + .get("x-request-id") + .map(|v| v.to_str().unwrap_or_default()) + .unwrap_or_default(); + + tracing::span!( + target:"HTTP TRACKER", + tracing::Level::INFO, "request", server_socket_addr= %server_socket_addr, method = %method, uri = %uri, request_id = %request_id); + }) + .on_response(move |response: &Response, latency: Duration, _span: &Span| { + let status_code = response.status(); + let request_id = response + .headers() + .get("x-request-id") + .map(|v| v.to_str().unwrap_or_default()) + .unwrap_or_default(); + let latency_ms = latency.as_millis(); + + tracing::span!( + target: "HTTP TRACKER", + tracing::Level::INFO, "response", server_socket_addr= %server_socket_addr, latency = %latency_ms, status = %status_code, request_id = %request_id); + }), + ) + .layer(SetRequestIdLayer::x_request_id(RequestIdGenerator)) +} + +#[derive(Clone, Default)] +struct RequestIdGenerator; + +impl MakeRequestId for RequestIdGenerator { + fn make_request_id(&mut self, _request: &Request) -> Option { + let id = HeaderValue::from_str(&Uuid::new_v4().to_string()).expect("UUID is a valid HTTP header value"); + Some(RequestId::new(id)) + } } From 4a2d902aa3dab5cf82f9999988dfee560757b537 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 19 Feb 2024 16:11:38 +0000 Subject: [PATCH 0236/1297] feat: [#698] refactor UDP logs Use `tracing` crate format: ``` 2024-02-19T17:10:05.243973520+00:00 [UDP TRACKER][INFO] request; server_socket_addr=0.0.0.0:6969 action=CONNECT transaction_id=-888840697 request_id=03b92de0-c9f8-4c40-a808-5d706ce770f4 2024-02-19T17:10:05.244016141+00:00 [UDP TRACKER][INFO] response; server_socket_addr=0.0.0.0:6969 transaction_id=-888840697 request_id=03b92de0-c9f8-4c40-a808-5d706ce770f4 2024-02-19T17:10:05.244042841+00:00 [UDP TRACKER][INFO] request; server_socket_addr=0.0.0.0:6969 action=ANNOUNCE transaction_id=-888840697 request_id=2113eb8c-61f4-476b-b3d5-02892f0a2fdb connection_id=-7190270103145546231 info_hash=9c38422213e30bff212b30c360d26f9a02136422 2024-02-19T17:10:05.244052082+00:00 [UDP TRACKER][INFO] response; server_socket_addr=0.0.0.0:6969 transaction_id=-888840697 request_id=2113eb8c-61f4-476b-b3d5-02892f0a2fdb ``` --- src/bootstrap/jobs/udp_tracker.rs | 6 +-- src/console/ci/e2e/logs_parser.rs | 6 +-- src/servers/udp/handlers.rs | 63 +++++++++++++++++++------- src/servers/udp/logging.rs | 73 +++++++++++++++++++++++++++++++ src/servers/udp/mod.rs | 1 + src/servers/udp/server.rs | 12 ++--- 6 files changed, 134 insertions(+), 27 deletions(-) create mode 100644 src/servers/udp/logging.rs diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 275ce1381..e9e4bc642 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -38,8 +38,8 @@ pub async fn start_job(config: &UdpTracker, tracker: Arc, form: S .expect("it should be able to start the udp tracker"); tokio::spawn(async move { - debug!(target: "UDP Tracker", "Wait for launcher (UDP service) to finish ..."); - debug!(target: "UDP Tracker", "Is halt channel closed before waiting?: {}", server.state.halt_task.is_closed()); + debug!(target: "UDP TRACKER", "Wait for launcher (UDP service) to finish ..."); + debug!(target: "UDP TRACKER", "Is halt channel closed before waiting?: {}", server.state.halt_task.is_closed()); assert!( !server.state.halt_task.is_closed(), @@ -52,6 +52,6 @@ pub async fn start_job(config: &UdpTracker, tracker: Arc, form: S .await .expect("it should be able to join to the udp tracker task"); - debug!(target: "UDP Tracker", "Is halt channel closed after finishing the server?: {}", server.state.halt_task.is_closed()); + debug!(target: "UDP TRACKER", "Is halt channel closed after finishing the server?: {}", server.state.halt_task.is_closed()); }) } diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index ca4d6099c..6d3349196 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -1,7 +1,7 @@ //! Utilities to parse Torrust Tracker logs. use serde::{Deserialize, Serialize}; -const UDP_TRACKER_PATTERN: &str = "[UDP Tracker][INFO] Starting on: udp://"; +const UDP_TRACKER_PATTERN: &str = "[UDP TRACKER][INFO] Starting on: udp://"; const HTTP_TRACKER_PATTERN: &str = "[HTTP TRACKER][INFO] Starting on: "; const HEALTH_CHECK_PATTERN: &str = "[HEALTH CHECK API][INFO] Starting on: "; @@ -20,7 +20,7 @@ impl RunningServices { /// ```text /// Loading default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... /// 2024-01-24T16:36:14.614898789+00:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized. - /// 2024-01-24T16:36:14.615586025+00:00 [UDP Tracker][INFO] Starting on: udp://0.0.0.0:6969 + /// 2024-01-24T16:36:14.615586025+00:00 [UDP TRACKER][INFO] Starting on: udp://0.0.0.0:6969 /// 2024-01-24T16:36:14.615623705+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled /// 2024-01-24T16:36:14.615694484+00:00 [HTTP TRACKER][INFO] Starting on: http://0.0.0.0:7070 /// 2024-01-24T16:36:14.615710534+00:00 [HTTP TRACKER][INFO] Started on: http://0.0.0.0:7070 @@ -86,7 +86,7 @@ mod tests { #[test] fn it_should_parse_from_logs_with_valid_logs() { let logs = "\ - [UDP Tracker][INFO] Starting on: udp://0.0.0.0:8080\n\ + [UDP TRACKER][INFO] Starting on: udp://0.0.0.0:8080\n\ [HTTP TRACKER][INFO] Starting on: 0.0.0.0:9090\n\ [HEALTH CHECK API][INFO] Starting on: 0.0.0.0:10010"; let running_services = RunningServices::parse_from_logs(logs); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 65e3f5b20..f8424879f 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -1,4 +1,5 @@ //! Handlers for the UDP server. +use std::fmt; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::panic::Location; use std::sync::Arc; @@ -7,13 +8,16 @@ use aquatic_udp_protocol::{ AnnounceInterval, AnnounceRequest, AnnounceResponse, ConnectRequest, ConnectResponse, ErrorResponse, NumberOfDownloads, NumberOfPeers, Port, Request, Response, ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; -use log::{debug, info}; +use log::debug; +use tokio::net::UdpSocket; use torrust_tracker_located_error::DynError; +use uuid::Uuid; use super::connection_cookie::{check, from_connection_id, into_connection_id, make}; use super::UdpRequest; use crate::core::{statistics, ScrapeData, Tracker}; use crate::servers::udp::error::Error; +use crate::servers::udp::logging::{log_bad_request, log_error_response, log_request, log_response}; use crate::servers::udp::peer_builder; use crate::servers::udp::request::AnnounceWrapper; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; @@ -28,8 +32,12 @@ use crate::shared::bit_torrent::info_hash::InfoHash; /// type. /// /// It will return an `Error` response if the request is invalid. -pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc) -> Response { +pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc, socket: Arc) -> Response { debug!("Handling Packets: {udp_request:?}"); + + let request_id = RequestId::make(&udp_request); + let server_socket_addr = socket.local_addr().expect("Could not get local_addr for socket."); + match Request::from_bytes(&udp_request.payload[..udp_request.payload.len()], MAX_SCRAPE_TORRENTS).map_err(|e| { Error::InternalServer { message: format!("{e:?}"), @@ -37,24 +45,37 @@ pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc { + log_request(&request, &request_id, &server_socket_addr); + let transaction_id = match &request { Request::Connect(connect_request) => connect_request.transaction_id, Request::Announce(announce_request) => announce_request.transaction_id, Request::Scrape(scrape_request) => scrape_request.transaction_id, }; - match handle_request(request, udp_request.from, tracker).await { + let response = match handle_request(request, udp_request.from, tracker).await { Ok(response) => response, Err(e) => handle_error(&e, transaction_id), - } + }; + + log_response(&response, &transaction_id, &request_id, &server_socket_addr); + + response + } + Err(e) => { + log_bad_request(&request_id); + + let response = handle_error( + &Error::BadRequest { + source: (Arc::new(e) as DynError).into(), + }, + TransactionId(0), + ); + + log_error_response(&request_id); + + response } - // bad request - Err(e) => handle_error( - &Error::BadRequest { - source: (Arc::new(e) as DynError).into(), - }, - TransactionId(0), - ), } } @@ -80,7 +101,6 @@ pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: /// /// This function does not ever return an error. pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, tracker: &Tracker) -> Result { - info!(target: "UDP", "\"CONNECT TxID {}\"", request.transaction_id.0); debug!("udp connect request: {:#?}", request); let connection_cookie = make(&remote_addr); @@ -138,8 +158,6 @@ pub async fn handle_announce( source: (Arc::new(e) as Arc).into(), })?; - info!(target: "UDP", "\"ANNOUNCE TxID {} IH {}\"", announce_request.transaction_id.0, info_hash.to_hex_string()); - let mut peer = peer_builder::from_request(&wrapped_announce_request, &remote_client_ip); let response = tracker.announce(&info_hash, &mut peer, &remote_client_ip).await; @@ -214,7 +232,6 @@ pub async fn handle_announce( /// /// This function does not ever return an error. pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tracker: &Tracker) -> Result { - info!(target: "UDP", "\"SCRAPE TxID {}\"", request.transaction_id.0); debug!("udp scrape request: {:#?}", request); // Convert from aquatic infohashes @@ -274,6 +291,22 @@ fn handle_error(e: &Error, transaction_id: TransactionId) -> Response { }) } +/// An identifier for a request. +#[derive(Debug, Clone)] +pub struct RequestId(Uuid); + +impl RequestId { + fn make(_request: &UdpRequest) -> RequestId { + RequestId(Uuid::new_v4()) + } +} + +impl fmt::Display for RequestId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} + #[cfg(test)] mod tests { diff --git a/src/servers/udp/logging.rs b/src/servers/udp/logging.rs new file mode 100644 index 000000000..bd1c2951b --- /dev/null +++ b/src/servers/udp/logging.rs @@ -0,0 +1,73 @@ +//! Logging for UDP Tracker requests and responses. + +use std::net::SocketAddr; + +use aquatic_udp_protocol::{Request, Response, TransactionId}; + +use super::handlers::RequestId; +use crate::shared::bit_torrent::info_hash::InfoHash; + +pub fn log_request(request: &Request, request_id: &RequestId, server_socket_addr: &SocketAddr) { + let action = map_action_name(request); + + match &request { + Request::Connect(connect_request) => { + let transaction_id = connect_request.transaction_id; + let transaction_id_str = transaction_id.0.to_string(); + + tracing::span!( + target: "UDP TRACKER", + tracing::Level::INFO, "request", server_socket_addr = %server_socket_addr, action = %action, transaction_id = %transaction_id_str, request_id = %request_id); + } + Request::Announce(announce_request) => { + let transaction_id = announce_request.transaction_id; + let transaction_id_str = transaction_id.0.to_string(); + let connection_id_str = announce_request.connection_id.0.to_string(); + let info_hash_str = InfoHash::from_bytes(&announce_request.info_hash.0).to_hex_string(); + + tracing::span!( + target: "UDP TRACKER", + tracing::Level::INFO, "request", server_socket_addr = %server_socket_addr, action = %action, transaction_id = %transaction_id_str, request_id = %request_id, connection_id = %connection_id_str, info_hash = %info_hash_str); + } + Request::Scrape(scrape_request) => { + let transaction_id = scrape_request.transaction_id; + let transaction_id_str = transaction_id.0.to_string(); + let connection_id_str = scrape_request.connection_id.0.to_string(); + + tracing::span!( + target: "UDP TRACKER", + tracing::Level::INFO, "request", server_socket_addr = %server_socket_addr, action = %action, transaction_id = %transaction_id_str, request_id = %request_id, connection_id = %connection_id_str); + } + }; +} + +fn map_action_name(udp_request: &Request) -> String { + match udp_request { + Request::Connect(_connect_request) => "CONNECT".to_owned(), + Request::Announce(_announce_request) => "ANNOUNCE".to_owned(), + Request::Scrape(_scrape_request) => "SCRAPE".to_owned(), + } +} + +pub fn log_response( + _response: &Response, + transaction_id: &TransactionId, + request_id: &RequestId, + server_socket_addr: &SocketAddr, +) { + tracing::span!( + target: "UDP TRACKER", + tracing::Level::INFO, "response", server_socket_addr = %server_socket_addr, transaction_id = %transaction_id.0.to_string(), request_id = %request_id); +} + +pub fn log_bad_request(request_id: &RequestId) { + tracing::span!( + target: "UDP TRACKER", + tracing::Level::INFO, "bad request", request_id = %request_id); +} + +pub fn log_error_response(request_id: &RequestId) { + tracing::span!( + target: "UDP TRACKER", + tracing::Level::INFO, "response", request_id = %request_id); +} diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index 3b22aeab5..8ef562086 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -644,6 +644,7 @@ use std::net::SocketAddr; pub mod connection_cookie; pub mod error; pub mod handlers; +pub mod logging; pub mod peer_builder; pub mod request; pub mod server; diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 0ab50d3bd..1326f806d 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -247,10 +247,10 @@ impl Udp { let address = socket.local_addr().expect("Could not get local_addr from {binding}."); let halt = shutdown_signal_with_message(rx_halt, format!("Halting Http Service Bound to Socket: {address}")); - info!(target: "UDP Tracker", "Starting on: udp://{}", address); + info!(target: "UDP TRACKER", "Starting on: udp://{}", address); let running = tokio::task::spawn(async move { - debug!(target: "UDP Tracker", "Started: Waiting for packets on socket address: udp://{address} ..."); + debug!(target: "UDP TRACKER", "Started: Waiting for packets on socket address: udp://{address} ..."); let tracker = tracker.clone(); let socket = socket.clone(); @@ -275,13 +275,13 @@ impl Udp { .send(Started { address }) .expect("the UDP Tracker service should not be dropped"); - debug!(target: "UDP Tracker", "Started on: udp://{}", address); + debug!(target: "UDP TRACKER", "Started on: udp://{}", address); let stop = running.abort_handle(); select! { - _ = running => { debug!(target: "UDP Tracker", "Socket listener stopped on address: udp://{address}"); }, - () = halt => { debug!(target: "UDP Tracker", "Halt signal spawned task stopped on address: udp://{address}"); } + _ = running => { debug!(target: "UDP TRACKER", "Socket listener stopped on address: udp://{address}"); }, + () = halt => { debug!(target: "UDP TRACKER", "Halt signal spawned task stopped on address: udp://{address}"); } } stop.abort(); @@ -327,7 +327,7 @@ impl Udp { async fn make_response(tracker: Arc, socket: Arc, udp_request: UdpRequest) { trace!("Making Response to {udp_request:?}"); let from = udp_request.from; - let response = handlers::handle_packet(udp_request, &tracker.clone()).await; + let response = handlers::handle_packet(udp_request, &tracker.clone(), socket.clone()).await; Self::send_response(&socket.clone(), from, response).await; } From 1bf8a823111541752dc5c1ce51aa5821195b1cea Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 22 Feb 2024 17:41:22 +0000 Subject: [PATCH 0237/1297] chore(deps): udpate dependencies ```console $ cargo update Updating crates.io index Updating ahash v0.8.8 -> v0.8.9 Updating anstream v0.6.11 -> v0.6.12 Updating anstyle v1.0.5 -> v1.0.6 Updating anyhow v1.0.79 -> v1.0.80 Removing base64 v0.13.1 Updating bindgen v0.69.2 -> v0.69.4 Updating bumpalo v3.14.0 -> v3.15.2 Updating bytecheck v0.6.11 -> v0.6.12 (latest: v0.7.0) Updating bytecheck_derive v0.6.11 -> v0.6.12 (latest: v0.7.0) Updating cc v1.0.83 -> v1.0.86 Updating chrono v0.4.33 -> v0.4.34 Updating clap v4.4.18 -> v4.5.1 Updating clap_builder v4.4.18 -> v4.5.1 Updating clap_derive v4.4.7 -> v4.5.0 Updating clap_lex v0.6.0 -> v0.7.0 Updating config v0.13.4 -> v0.14.0 Adding const-random v0.1.17 Adding const-random-macro v0.1.16 Adding convert_case v0.6.0 Updating crc32fast v1.3.2 -> v1.4.0 Updating darling v0.20.5 -> v0.20.6 Updating darling_core v0.20.5 -> v0.20.6 Updating darling_macro v0.20.5 -> v0.20.6 Updating dlv-list v0.3.0 -> v0.5.2 Updating either v1.9.0 -> v1.10.0 Updating hashlink v0.8.4 -> v0.9.0 Updating hermit-abi v0.3.4 -> v0.3.6 Updating hyper v1.1.0 -> v1.2.0 Updating iana-time-zone v0.1.59 -> v0.1.60 Updating indexmap v2.2.2 -> v2.2.3 Updating is-terminal v0.4.10 -> v0.4.12 Adding itertools v0.12.1 Removing jobserver v0.1.27 Updating js-sys v0.3.67 -> v0.3.68 Updating libsqlite3-sys v0.27.0 -> v0.28.0 Updating local-ip-address v0.5.7 -> v0.6.0 Updating miniz_oxide v0.7.1 -> v0.7.2 Adding num-conv v0.1.0 Updating num-integer v0.1.45 -> v0.1.46 Updating num-traits v0.2.17 -> v0.2.18 Updating openssl v0.10.63 -> v0.10.64 Updating openssl-src v300.2.2+3.2.1 -> v300.2.3+3.2.1 Updating openssl-sys v0.9.99 -> v0.9.101 Updating ordered-multimap v0.4.3 -> v0.6.0 (latest: v0.7.1) Removing peeking_take_while v0.1.2 Updating pest v2.7.6 -> v2.7.7 Updating pest_derive v2.7.6 -> v2.7.7 Updating pest_generator v2.7.6 -> v2.7.7 Updating pest_meta v2.7.6 -> v2.7.7 Updating pkg-config v0.3.29 -> v0.3.30 Updating r2d2_sqlite v0.23.0 -> v0.24.0 Updating rend v0.4.1 -> v0.4.2 Updating ring v0.17.7 -> v0.17.8 Updating ringbuf v0.4.0-rc.2 -> v0.3.3 Updating rkyv v0.7.43 -> v0.7.44 Updating rkyv_derive v0.7.43 -> v0.7.44 Updating ron v0.7.1 -> v0.8.1 Updating rusqlite v0.30.0 -> v0.31.0 Updating rust-ini v0.18.0 -> v0.19.0 (latest: v0.20.0) Updating rust_decimal v1.34.0 -> v1.34.3 Updating rustix v0.38.30 -> v0.38.31 Updating rustls-pemfile v2.0.0 -> v2.1.0 Updating rustls-pki-types v1.1.0 -> v1.3.0 Updating ryu v1.0.16 -> v1.0.17 Updating semver v1.0.21 -> v1.0.22 Updating serde v1.0.196 -> v1.0.197 Updating serde_derive v1.0.196 -> v1.0.197 Updating serde_json v1.0.113 -> v1.0.114 Updating serde_with v3.6.0 -> v3.6.1 Updating serde_with_macros v3.6.0 -> v3.6.1 Adding strsim v0.11.0 Updating syn v2.0.48 -> v2.0.50 Updating tempfile v3.9.0 -> v3.10.0 Updating thiserror v1.0.56 -> v1.0.57 Updating thiserror-impl v1.0.56 -> v1.0.57 Updating time v0.3.31 -> v0.3.34 Updating time-macros v0.2.16 -> v0.2.17 Adding tiny-keccak v2.0.2 Updating tokio v1.35.1 -> v1.36.0 Removing toml v0.5.11 Removing toml v0.8.9 Adding toml v0.8.10 Adding toml_edit v0.22.6 Updating unicode-normalization v0.1.22 -> v0.1.23 Adding unicode-segmentation v1.11.0 Updating wasm-bindgen v0.2.90 -> v0.2.91 Updating wasm-bindgen-backend v0.2.90 -> v0.2.91 Updating wasm-bindgen-futures v0.4.40 -> v0.4.41 Updating wasm-bindgen-macro v0.2.90 -> v0.2.91 Updating wasm-bindgen-macro-support v0.2.90 -> v0.2.91 Updating wasm-bindgen-shared v0.2.90 -> v0.2.91 Updating web-sys v0.3.67 -> v0.3.68 Updating windows-targets v0.52.0 -> v0.52.3 Updating windows_aarch64_gnullvm v0.52.0 -> v0.52.3 Updating windows_aarch64_msvc v0.52.0 -> v0.52.3 Updating windows_i686_gnu v0.52.0 -> v0.52.3 Updating windows_i686_msvc v0.52.0 -> v0.52.3 Updating windows_x86_64_gnu v0.52.0 -> v0.52.3 Updating windows_x86_64_gnullvm v0.52.0 -> v0.52.3 Updating windows_x86_64_msvc v0.52.0 -> v0.52.3 Removing winnow v0.5.36 Adding winnow v0.5.40 (latest: v0.6.2) Adding winnow v0.6.2 note: pass `--verbose` to see 52 unchanged dependencies behind latest ``` --- Cargo.lock | 621 +++++++++++++++++++++----------------- Cargo.toml | 2 +- src/servers/udp/server.rs | 6 +- 3 files changed, 346 insertions(+), 283 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aae5deb9e..e1092fefc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -30,9 +30,9 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42cd52102d3df161c77a887b608d7a4897d7cc112886a9537b738a887a03aaff" +checksum = "d713b3834d76b85304d4d525563c1276e2e30dc97cc67bfb4585a4a29fc2c89f" dependencies = [ "cfg-if", "once_cell", @@ -93,9 +93,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.11" +version = "0.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e2e1ebcb11de5c03c67de28a7df593d32191b44939c482e97702baaaa6ab6a5" +checksum = "96b09b5178381e0874812a9b157f7fe84982617e48f71f4e3235482775e5b540" dependencies = [ "anstyle", "anstyle-parse", @@ -107,9 +107,9 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.5" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2faccea4cc4ab4a667ce676a30e8ec13922a692c99bb8f5b11f1502c72e04220" +checksum = "8901269c6307e8d93993578286ac0edf7f195079ffff5ebdeea6a59ffb7e36bc" [[package]] name = "anstyle-parse" @@ -141,9 +141,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.79" +version = "1.0.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "080e9890a082662b09c1ad45f567faeeb47f22b5fb23895fbe1e651e718e25ca" +checksum = "5ad32ce52e4161730f7098c077cd2ed6229b5804ccf99e5366be1ab72a98b4e1" [[package]] name = "aquatic_udp_protocol" @@ -191,7 +191,7 @@ checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -214,7 +214,7 @@ dependencies = [ "http 1.0.0", "http-body 1.0.0", "http-body-util", - "hyper 1.1.0", + "hyper 1.2.0", "hyper-util", "itoa", "matchit", @@ -276,7 +276,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -291,11 +291,11 @@ dependencies = [ "http 1.0.0", "http-body 1.0.0", "http-body-util", - "hyper 1.1.0", + "hyper 1.2.0", "hyper-util", "pin-project-lite", "rustls", - "rustls-pemfile 2.0.0", + "rustls-pemfile 2.1.0", "tokio", "tokio-rustls", "tower", @@ -317,12 +317,6 @@ dependencies = [ "rustc-demangle", ] -[[package]] -name = "base64" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" - [[package]] name = "base64" version = "0.21.7" @@ -348,22 +342,22 @@ checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" [[package]] name = "bindgen" -version = "0.69.2" +version = "0.69.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4c69fae65a523209d34240b60abe0c42d33d1045d445c0839d8a4894a736e2d" +checksum = "a00dc851838a2120612785d195287475a3ac45514741da670b735818822129a0" dependencies = [ "bitflags 2.4.2", "cexpr", "clang-sys", + "itertools 0.12.1", "lazy_static", "lazycell", - "peeking_take_while", "proc-macro2", "quote", "regex", "rustc-hash", "shlex", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -377,6 +371,9 @@ name = "bitflags" version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" +dependencies = [ + "serde", +] [[package]] name = "bitvec" @@ -419,7 +416,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", "syn_derive", ] @@ -452,15 +449,15 @@ checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" [[package]] name = "bumpalo" -version = "3.14.0" +version = "3.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" +checksum = "a3b1be7772ee4501dba05acbe66bb1e8760f6a6c474a36035631638e4415f130" [[package]] name = "bytecheck" -version = "0.6.11" +version = "0.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b6372023ac861f6e6dc89c8344a8f398fb42aaba2b5dbc649ca0c0e9dbcb627" +checksum = "23cdc57ce23ac53c931e88a43d06d070a6fd142f2617be5855eb75efc9beb1c2" dependencies = [ "bytecheck_derive", "ptr_meta", @@ -469,9 +466,9 @@ dependencies = [ [[package]] name = "bytecheck_derive" -version = "0.6.11" +version = "0.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7ec4c6f261935ad534c0c22dbef2201b45918860eb1c574b972bd213a76af61" +checksum = "3db406d29fbcd95542e92559bed4d8ad92636d1ca8b3b72ede10b4bcc010e659" dependencies = [ "proc-macro2", "quote", @@ -498,11 +495,10 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.0.83" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" +checksum = "7f9fa1897e4325be0d68d48df6aa1a71ac2ed4d27723887e7754192705350730" dependencies = [ - "jobserver", "libc", ] @@ -529,15 +525,15 @@ checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" [[package]] name = "chrono" -version = "0.4.33" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f13690e35a5e4ace198e7beea2895d29f3a9cc55015fcebe6336bd2010af9eb" +checksum = "5bc015644b92d5890fab7489e49d21f879d5c990186827d42ec511919404f38b" dependencies = [ "android-tzdata", "iana-time-zone", "num-traits", "serde", - "windows-targets 0.52.0", + "windows-targets 0.52.3", ] [[package]] @@ -580,9 +576,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.18" +version = "4.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e578d6ec4194633722ccf9544794b71b1385c3c027efe0c55db226fc880865c" +checksum = "c918d541ef2913577a0f9566e9ce27cb35b6df072075769e0b26cb5a554520da" dependencies = [ "clap_builder", "clap_derive", @@ -590,33 +586,33 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.4.18" +version = "4.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4df4df40ec50c46000231c914968278b1eb05098cf8f1b3a518a95030e71d1c7" +checksum = "9f3e7391dad68afb0c2ede1bf619f579a3dc9c2ec67f089baa397123a2f3d1eb" dependencies = [ "anstream", "anstyle", "clap_lex", - "strsim", + "strsim 0.11.0", ] [[package]] name = "clap_derive" -version = "4.4.7" +version = "4.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9804afaaf59a91e75b022a30fb7229a7901f60c755489cc61c9b423b836442" +checksum = "307bc0538d5f0f83b8248db3087aa92fe504e4691294d0c96c0eabc33f47ba47" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] name = "clap_lex" -version = "0.6.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1" +checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" [[package]] name = "cmake" @@ -645,11 +641,12 @@ dependencies = [ [[package]] name = "config" -version = "0.13.4" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23738e11972c7643e4ec947840fc463b6a571afcd3e735bdfce7d03c7a784aca" +checksum = "7328b20597b53c2454f0b1919720c25c7339051c02b72b7e05409e00b14132be" dependencies = [ "async-trait", + "convert_case 0.6.0", "json5", "lazy_static", "nom", @@ -658,16 +655,45 @@ dependencies = [ "rust-ini", "serde", "serde_json", - "toml 0.5.11", + "toml", "yaml-rust", ] +[[package]] +name = "const-random" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aaf16c9c2c612020bcfd042e170f6e32de9b9d75adb5277cdbbd2e2c8c8299a" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom", + "once_cell", + "tiny-keccak", +] + [[package]] name = "convert_case" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" +[[package]] +name = "convert_case" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -695,9 +721,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.3.2" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" +checksum = "b3855a8a784b474f333699ef2bbca9db2c4a1f6d9088a90a2d25b1eb53111eaa" dependencies = [ "cfg-if", ] @@ -715,7 +741,7 @@ dependencies = [ "criterion-plot", "futures", "is-terminal", - "itertools", + "itertools 0.10.5", "num-traits", "once_cell", "oorandom", @@ -737,7 +763,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" dependencies = [ "cast", - "itertools", + "itertools 0.10.5", ] [[package]] @@ -814,9 +840,9 @@ dependencies = [ [[package]] name = "darling" -version = "0.20.5" +version = "0.20.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc5d6b04b3fd0ba9926f945895de7d806260a2d7431ba82e7edaecb043c4c6b8" +checksum = "c376d08ea6aa96aafe61237c7200d1241cb177b7d3a542d791f2d118e9cbb955" dependencies = [ "darling_core", "darling_macro", @@ -824,27 +850,27 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.20.5" +version = "0.20.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04e48a959bcd5c761246f5d090ebc2fbf7b9cd527a492b07a67510c108f1e7e3" +checksum = "33043dcd19068b8192064c704b3f83eb464f91f1ff527b44a4e2b08d9cdb8855" dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", - "strsim", - "syn 2.0.48", + "strsim 0.10.0", + "syn 2.0.50", ] [[package]] name = "darling_macro" -version = "0.20.5" +version = "0.20.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d1545d67a2149e1d93b7e5c7752dce5a7426eb5d1357ddcfd89336b94444f77" +checksum = "c5a91391accf613803c2a9bf9abccdbaa07c54b4244a5b64883f9c3c137c86be" dependencies = [ "darling_core", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -863,7 +889,7 @@ version = "0.99.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" dependencies = [ - "convert_case", + "convert_case 0.4.0", "proc-macro2", "quote", "rustc_version", @@ -878,7 +904,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -893,9 +919,12 @@ dependencies = [ [[package]] name = "dlv-list" -version = "0.3.0" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257" +checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f" +dependencies = [ + "const-random", +] [[package]] name = "downcast" @@ -905,9 +934,9 @@ checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" [[package]] name = "either" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" +checksum = "11157ac094ffbdde99aa67b23417ebdd801842852b500e395a45a9c0aac03e4a" [[package]] name = "encoding_rs" @@ -1053,7 +1082,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -1065,7 +1094,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -1077,7 +1106,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -1142,7 +1171,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -1220,7 +1249,7 @@ dependencies = [ "futures-sink", "futures-util", "http 0.2.11", - "indexmap 2.2.2", + "indexmap 2.2.3", "slab", "tokio", "tokio-util", @@ -1239,7 +1268,7 @@ dependencies = [ "futures-sink", "futures-util", "http 1.0.0", - "indexmap 2.2.2", + "indexmap 2.2.3", "slab", "tokio", "tokio-util", @@ -1271,7 +1300,7 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" dependencies = [ - "ahash 0.8.8", + "ahash 0.8.9", ] [[package]] @@ -1280,15 +1309,15 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" dependencies = [ - "ahash 0.8.8", + "ahash 0.8.9", "allocator-api2", ] [[package]] name = "hashlink" -version = "0.8.4" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7" +checksum = "692eaaf7f7607518dd3cef090f1474b61edc5301d8012f09579920df68b725ee" dependencies = [ "hashbrown 0.14.3", ] @@ -1301,9 +1330,9 @@ checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" [[package]] name = "hermit-abi" -version = "0.3.4" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d3d0e0f38255e7fa3cf31335b3a56f05febd18025f4db5ef7a0cfb4f8da651f" +checksum = "bd5256b483761cd23699d0da46cc6fd2ee3be420bbe6d020ae4a091e70b7e9fd" [[package]] name = "hex" @@ -1411,9 +1440,9 @@ dependencies = [ [[package]] name = "hyper" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5aa53871fc917b1a9ed87b683a5d86db645e23acb32c2e0785a353e522fb75" +checksum = "186548d73ac615b32a73aafe38fb4f56c0d340e110e5a200bcadbaf2e199263a" dependencies = [ "bytes", "futures-channel", @@ -1425,6 +1454,7 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", + "smallvec", "tokio", ] @@ -1451,7 +1481,7 @@ dependencies = [ "futures-util", "http 1.0.0", "http-body 1.0.0", - "hyper 1.1.0", + "hyper 1.2.0", "pin-project-lite", "socket2", "tokio", @@ -1459,9 +1489,9 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.59" +version = "0.1.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6a67363e2aa4443928ce15e57ebae94fd8949958fd1223c4cfc0cd473ad7539" +checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -1509,9 +1539,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.2.2" +version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824b2ae422412366ba479e8111fd301f7b5faece8149317bb81925979a53f520" +checksum = "233cf39063f058ea2caae4091bf4a3ef70a653afbc026f5c4a4135d114e3c177" dependencies = [ "equivalent", "hashbrown 0.14.3", @@ -1535,12 +1565,12 @@ checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" [[package]] name = "is-terminal" -version = "0.4.10" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bad00257d07be169d870ab665980b06cdb366d792ad690bf2e76876dc503455" +checksum = "f23ff5ef2b80d608d61efee834934d862cd92461afc0560dedf493e4c033738b" dependencies = [ "hermit-abi", - "rustix", + "libc", "windows-sys 0.52.0", ] @@ -1554,25 +1584,25 @@ dependencies = [ ] [[package]] -name = "itoa" -version = "1.0.10" +name = "itertools" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] [[package]] -name = "jobserver" -version = "0.1.27" +name = "itoa" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c37f63953c4c63420ed5fd3d6d398c719489b9f872b9fa683262f8edd363c7d" -dependencies = [ - "libc", -] +checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" [[package]] name = "js-sys" -version = "0.3.67" +version = "0.3.68" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a1d36f1235bc969acba30b7f5990b864423a6068a10f7c90ae8f0112e3a59d1" +checksum = "406cda4b368d531c842222cf9d2600a9a4acce8d29423695379c6868a143a9ee" dependencies = [ "wasm-bindgen", ] @@ -1691,9 +1721,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.27.0" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf4e226dcd58b4be396f7bd3c20da8fdee2911400705297ba7d2d7cc2c30f716" +checksum = "0c10584274047cb335c23d3e61bcef8e323adae7c5c8c760540f73610177fc3f" dependencies = [ "cc", "pkg-config", @@ -1725,9 +1755,9 @@ checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" [[package]] name = "local-ip-address" -version = "0.5.7" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "612ed4ea9ce5acfb5d26339302528a5e1e59dfed95e9e11af3c083236ff1d15d" +checksum = "f63e1499d2495be571af92e9ca9dca4e7bf26c47b87cb8d0c6100825e521dd6b" dependencies = [ "libc", "neli", @@ -1786,9 +1816,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" +checksum = "9d811f3e15f28568be3407c8e7fdb6514c1cda3cb30683f15b6a1a1dc4ea14a7" dependencies = [ "adler", ] @@ -1828,7 +1858,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -1879,7 +1909,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", "termcolor", "thiserror", ] @@ -1890,7 +1920,7 @@ version = "0.30.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57349d5a326b437989b6ee4dc8f2f34b0cc131202748414712a8e7d98952fc8c" dependencies = [ - "base64 0.21.7", + "base64", "bigdecimal", "bindgen", "bitflags 2.4.2", @@ -2001,21 +2031,26 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + [[package]] name = "num-integer" -version = "0.1.45" +version = "0.1.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" dependencies = [ - "autocfg", "num-traits", ] [[package]] name = "num-traits" -version = "0.2.17" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" +checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a" dependencies = [ "autocfg", ] @@ -2053,9 +2088,9 @@ checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" [[package]] name = "openssl" -version = "0.10.63" +version = "0.10.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15c9d69dd87a29568d4d017cfe8ec518706046a05184e5aea92d0af890b803c8" +checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f" dependencies = [ "bitflags 2.4.2", "cfg-if", @@ -2074,7 +2109,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -2085,18 +2120,18 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "300.2.2+3.2.1" +version = "300.2.3+3.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bbfad0063610ac26ee79f7484739e2b07555a75c42453b89263830b5c8103bc" +checksum = "5cff92b6f71555b61bb9315f7c64da3ca43d87531622120fea0195fc761b4843" dependencies = [ "cc", ] [[package]] name = "openssl-sys" -version = "0.9.99" +version = "0.9.101" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e1bf214306098e4832460f797824c05d25aacdf896f64a985fb0fd992454ae" +checksum = "dda2b0f344e78efc2facf7d195d098df0dd72151b26ab98da807afc26c198dff" dependencies = [ "cc", "libc", @@ -2107,12 +2142,12 @@ dependencies = [ [[package]] name = "ordered-multimap" -version = "0.4.3" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccd746e37177e1711c20dd619a1620f34f5c8b569c53590a72dedd5344d8924a" +checksum = "4ed8acf08e98e744e5384c8bc63ceb0364e68a6854187221c18df61c4797690e" dependencies = [ "dlv-list", - "hashbrown 0.12.3", + "hashbrown 0.13.2", ] [[package]] @@ -2144,19 +2179,13 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" -[[package]] -name = "peeking_take_while" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" - [[package]] name = "pem" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b13fe415cdf3c8e44518e18a7c95a13431d9bdf6d15367d82b23c377fdd441a" dependencies = [ - "base64 0.21.7", + "base64", "serde", ] @@ -2168,9 +2197,9 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.6" +version = "2.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f200d8d83c44a45b21764d1916299752ca035d15ecd46faca3e9a2a2bf6ad06" +checksum = "219c0dcc30b6a27553f9cc242972b67f75b60eb0db71f0b5462f38b058c41546" dependencies = [ "memchr", "thiserror", @@ -2179,9 +2208,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.6" +version = "2.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcd6ab1236bbdb3a49027e920e693192ebfe8913f6d60e294de57463a493cfde" +checksum = "22e1288dbd7786462961e69bfd4df7848c1e37e8b74303dbdab82c3a9cdd2809" dependencies = [ "pest", "pest_generator", @@ -2189,22 +2218,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.6" +version = "2.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a31940305ffc96863a735bef7c7994a00b325a7138fdbc5bda0f1a0476d3275" +checksum = "1381c29a877c6d34b8c176e734f35d7f7f5b3adaefe940cb4d1bb7af94678e2e" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] name = "pest_meta" -version = "2.7.6" +version = "2.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7ff62f5259e53b78d1af898941cdcdccfae7385cf7d793a6e55de5d05bb4b7d" +checksum = "d0934d6907f148c22a3acbda520c7eed243ad7487a30f51f6ce52b58b7077a8a" dependencies = [ "once_cell", "pest", @@ -2266,7 +2295,7 @@ checksum = "266c042b60c9c76b8d53061e52b2e0d1116abc57cefc8c5cd671619a56ac3690" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -2283,9 +2312,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pkg-config" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2900ede94e305130c13ddd391e0ab7cbaeb783945ae07a279c268cb05109c6cb" +checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" [[package]] name = "plotters" @@ -2457,9 +2486,9 @@ dependencies = [ [[package]] name = "r2d2_sqlite" -version = "0.23.0" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dc290b669d30e20751e813517bbe13662d020419c5c8818ff10b6e8bb7777f6" +checksum = "6a982edf65c129796dba72f8775b292ef482b40d035e827a9825b3bc07ccc5f2" dependencies = [ "r2d2", "rusqlite", @@ -2562,9 +2591,9 @@ checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" [[package]] name = "rend" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2571463863a6bd50c32f94402933f03457a3fbaf697a707c5be741e459f08fd" +checksum = "71fe3824f5629716b1589be05dacd749f6aa084c87e00e016714a8cdfccc997c" dependencies = [ "bytecheck", ] @@ -2575,7 +2604,7 @@ version = "0.11.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6920094eb85afde5e4a138be3f2de8bbdf28000f0029e72c45025a56b042251" dependencies = [ - "base64 0.21.7", + "base64", "bytes", "encoding_rs", "futures-core", @@ -2611,32 +2640,33 @@ dependencies = [ [[package]] name = "ring" -version = "0.17.7" +version = "0.17.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "688c63d65483050968b2a8937f7995f443e27041a0f7700aa59b0822aedebb74" +checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" dependencies = [ "cc", + "cfg-if", "getrandom", "libc", "spin", "untrusted", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] name = "ringbuf" -version = "0.4.0-rc.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b8f7d58e4f67752d63318605656be063e333154aa35b70126075e9d05552979" +checksum = "79abed428d1fd2a128201cec72c5f6938e2da607c6f3745f769fabea399d950a" dependencies = [ "crossbeam-utils", ] [[package]] name = "rkyv" -version = "0.7.43" +version = "0.7.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "527a97cdfef66f65998b5f3b637c26f5a5ec09cc52a3f9932313ac645f4190f5" +checksum = "5cba464629b3394fc4dbc6f940ff8f5b4ff5c7aef40f29166fd4ad12acbc99c0" dependencies = [ "bitvec", "bytecheck", @@ -2652,9 +2682,9 @@ dependencies = [ [[package]] name = "rkyv_derive" -version = "0.7.43" +version = "0.7.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5c462a1328c8e67e4d6dbad1eb0355dd43e8ab432c6e227a43657f16ade5033" +checksum = "a7dddfff8de25e6f62b9d64e6e432bf1c6736c57d20323e15ee10435fbda7c65" dependencies = [ "proc-macro2", "quote", @@ -2663,20 +2693,21 @@ dependencies = [ [[package]] name = "ron" -version = "0.7.1" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88073939a61e5b7680558e6be56b419e208420c2adb92be54921fa6b72283f1a" +checksum = "b91f7eff05f748767f183df4320a63d6936e9c6107d97c9e6bdd9784f4289c94" dependencies = [ - "base64 0.13.1", - "bitflags 1.3.2", + "base64", + "bitflags 2.4.2", "serde", + "serde_derive", ] [[package]] name = "rusqlite" -version = "0.30.0" +version = "0.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a78046161564f5e7cd9008aff3b2990b3850dc8e0349119b98e8f251e099f24d" +checksum = "b838eba278d213a8beaf485bd313fd580ca4505a00d5871caeb1457c55322cae" dependencies = [ "bitflags 2.4.2", "fallible-iterator", @@ -2688,9 +2719,9 @@ dependencies = [ [[package]] name = "rust-ini" -version = "0.18.0" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6d5f2436026b4f6e79dc829837d467cc7e9a55ee40e750d716713540715a2df" +checksum = "7e2a3bcec1f113553ef1c88aae6c020a369d03d55b58de9869a0908930385091" dependencies = [ "cfg-if", "ordered-multimap", @@ -2698,9 +2729,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.34.0" +version = "1.34.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7de2711cae7bdec993f4d2319352599ceb0d003e9f7900ea7c6ef4c5fc16831" +checksum = "b39449a79f45e8da28c57c341891b69a183044b29518bb8f86dbac9df60bb7df" dependencies = [ "arrayvec", "borsh", @@ -2735,9 +2766,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.30" +version = "0.38.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "322394588aaf33c24007e8bb3238ee3e4c5c09c084ab32bc73890b99ff326bca" +checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949" dependencies = [ "bitflags 2.4.2", "errno", @@ -2764,24 +2795,24 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" dependencies = [ - "base64 0.21.7", + "base64", ] [[package]] name = "rustls-pemfile" -version = "2.0.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35e4980fa29e4c4b212ffb3db068a564cbf560e51d3944b7c88bd8bf5bec64f4" +checksum = "3c333bb734fcdedcea57de1602543590f545f127dc8b533324318fd492c5c70b" dependencies = [ - "base64 0.21.7", + "base64", "rustls-pki-types", ] [[package]] name = "rustls-pki-types" -version = "1.1.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e9d979b3ce68192e42760c7810125eb6cf2ea10efae545a156063e61f314e2a" +checksum = "048a63e5b3ac996d78d402940b5fa47973d2d080c6c6fffa1d0f19c4445310b7" [[package]] name = "rustls-webpki" @@ -2801,9 +2832,9 @@ checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" [[package]] name = "ryu" -version = "1.0.16" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" +checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1" [[package]] name = "same-file" @@ -2885,15 +2916,15 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.21" +version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97ed7a9823b74f99c7742f5336af7be5ecd3eeafcb1507d1fa93347b1d589b0" +checksum = "92d43fe69e652f3df9bdc2b85b2854a0825b86e4fb76bc44d945137d053639ca" [[package]] name = "serde" -version = "1.0.196" +version = "1.0.197" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "870026e60fa08c69f064aa766c10f10b1d62db9ccd4d0abb206472bee0ce3b32" +checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" dependencies = [ "serde_derive", ] @@ -2919,20 +2950,20 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.196" +version = "1.0.197" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33c85360c95e7d137454dc81d9a4ed2b8efd8fbe19cee57357b32b9771fccb67" +checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] name = "serde_json" -version = "1.0.113" +version = "1.0.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69801b70b1c3dac963ecb03a364ba0ceda9cf60c71cfe475e99864759c8b8a79" +checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" dependencies = [ "itoa", "ryu", @@ -2957,7 +2988,7 @@ checksum = "0b2e6b945e9d3df726b65d6ee24060aff8e3533d431f677a9695db04eff9dfdb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -2983,16 +3014,17 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.6.0" +version = "3.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b0ed1662c5a68664f45b76d18deb0e234aff37207086803165c961eb695e981" +checksum = "15d167997bd841ec232f5b2b8e0e26606df2e7caa4c31b95ea9ca52b200bd270" dependencies = [ - "base64 0.21.7", + "base64", "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.2.2", + "indexmap 2.2.3", "serde", + "serde_derive", "serde_json", "serde_with_macros", "time", @@ -3000,14 +3032,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.6.0" +version = "3.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "568577ff0ef47b879f736cd66740e022f3672788cdf002a05a4e609ea5a6fb15" +checksum = "865f9743393e638991566a8b7a479043c2c8da94a33e0a31f18214c9cae0a64d" dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -3102,6 +3134,12 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" +[[package]] +name = "strsim" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ee073c9e4cd00e28217186dbe12796d692868f432bf2e97ee73bed0c56dfa01" + [[package]] name = "subprocess" version = "0.2.9" @@ -3125,9 +3163,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.48" +version = "2.0.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f" +checksum = "74f1bdc9872430ce9b75da68329d1c1746faf50ffac5f19e02b71e37ff881ffb" dependencies = [ "proc-macro2", "quote", @@ -3143,7 +3181,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -3198,13 +3236,12 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.9.0" +version = "3.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01ce4141aa927a6d1bd34a041795abd0db1cccba5d5f24b009f694bdf3a1f3fa" +checksum = "a365e8cd18e44762ef95d87f284f4b5cd04107fec2ff3052bd6a3e6069669e67" dependencies = [ "cfg-if", "fastrand", - "redox_syscall", "rustix", "windows-sys 0.52.0", ] @@ -3226,32 +3263,33 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.56" +version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d54378c645627613241d077a3a79db965db602882668f9136ac42af9ecb730ad" +checksum = "1e45bcbe8ed29775f228095caf2cd67af7a4ccf756ebff23a306bf3e8b47b24b" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.56" +version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa0faa943b50f3db30a20aa7e265dbc66076993efed8463e8de414e5d06d3471" +checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] name = "time" -version = "0.3.31" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f657ba42c3f86e7680e53c8cd3af8abbe56b5491790b46e22e19c0d57463583e" +checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749" dependencies = [ "deranged", "itoa", + "num-conv", "powerfmt", "serde", "time-core", @@ -3266,13 +3304,23 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26197e33420244aeb70c3e8c78376ca46571bc4e701e4791c2cd9f57dcb3a43f" +checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774" dependencies = [ + "num-conv", "time-core", ] +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + [[package]] name = "tinytemplate" version = "1.2.1" @@ -3300,9 +3348,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.35.1" +version = "1.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89b4efa943be685f629b149f53829423f8f5531ea21249408e8e2f8671ec104" +checksum = "61285f6515fa018fb2d1e46eb21223fff441ee8db5d0f1435e8ab4f5cdb80931" dependencies = [ "backtrace", "bytes", @@ -3324,7 +3372,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -3363,23 +3411,14 @@ dependencies = [ [[package]] name = "toml" -version = "0.5.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" -dependencies = [ - "serde", -] - -[[package]] -name = "toml" -version = "0.8.9" +version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6a4b9e8023eb94392d3dca65d717c53abc5dad49c07cb65bb8fcd87115fa325" +checksum = "9a9aad4a3066010876e8dcf5a8a06e70a558751117a145c6ce2b82c2e2054290" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.21.1", + "toml_edit 0.22.6", ] [[package]] @@ -3397,9 +3436,9 @@ version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ - "indexmap 2.2.2", + "indexmap 2.2.3", "toml_datetime", - "winnow", + "winnow 0.5.40", ] [[package]] @@ -3408,11 +3447,22 @@ version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8534fd7f78b5405e860340ad6575217ce99f38d4d5c8f2442cb5ecb50090e1" dependencies = [ - "indexmap 2.2.2", + "indexmap 2.2.3", + "toml_datetime", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.22.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c1b5fd4128cc8d3e0cb74d4ed9a9cc7c7284becd4df68f5f940e1ad123606f6" +dependencies = [ + "indexmap 2.2.3", "serde", "serde_spanned", "toml_datetime", - "winnow", + "winnow 0.6.2", ] [[package]] @@ -3446,7 +3496,7 @@ dependencies = [ "fern", "futures", "hex-literal", - "hyper 1.1.0", + "hyper 1.2.0", "lazy_static", "local-ip-address", "log", @@ -3495,7 +3545,7 @@ dependencies = [ "serde", "serde_with", "thiserror", - "toml 0.8.9", + "toml", "torrust-tracker-located-error", "torrust-tracker-primitives", "uuid", @@ -3616,7 +3666,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -3671,13 +3721,19 @@ checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-normalization" -version = "0.1.22" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" +checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-segmentation" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" + [[package]] name = "untrusted" version = "0.9.0" @@ -3750,9 +3806,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.90" +version = "0.2.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1223296a201415c7fad14792dbefaace9bd52b62d33453ade1c5b5f07555406" +checksum = "c1e124130aee3fb58c5bdd6b639a0509486b0338acaaae0c84a5124b0f588b7f" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -3760,24 +3816,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.90" +version = "0.2.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcdc935b63408d58a32f8cc9738a0bffd8f05cc7c002086c6ef20b7312ad9dcd" +checksum = "c9e7e1900c352b609c8488ad12639a311045f40a35491fb69ba8c12f758af70b" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.40" +version = "0.4.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde2032aeb86bdfaecc8b261eef3cba735cc426c1f3a3416d1e0791be95fc461" +checksum = "877b9c3f61ceea0e56331985743b13f3d25c406a7098d45180fb5f09bc19ed97" dependencies = [ "cfg-if", "js-sys", @@ -3787,9 +3843,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.90" +version = "0.2.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e4c238561b2d428924c49815533a8b9121c664599558a5d9ec51f8a1740a999" +checksum = "b30af9e2d358182b5c7449424f017eba305ed32a7010509ede96cdc4696c46ed" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3797,28 +3853,28 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.90" +version = "0.2.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bae1abb6806dc1ad9e560ed242107c0f6c84335f1749dd4e8ddb012ebd5e25a7" +checksum = "642f325be6301eb8107a83d12a8ac6c1e1c54345a7ef1a9261962dfefda09e66" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.90" +version = "0.2.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d91413b1c31d7539ba5ef2451af3f0b833a005eb27a631cec32bc0635a8602b" +checksum = "4f186bd2dcf04330886ce82d6f33dd75a7bfcf69ecf5763b89fcde53b6ac9838" [[package]] name = "web-sys" -version = "0.3.67" +version = "0.3.68" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58cd2333b6e0be7a39605f0e255892fd7418a682d8da8fe042fe25128794d2ed" +checksum = "96565907687f7aceb35bc5fc03770a8a0471d82e479f25832f54a0e3f4b28446" dependencies = [ "js-sys", "wasm-bindgen", @@ -3861,7 +3917,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ - "windows-targets 0.52.0", + "windows-targets 0.52.3", ] [[package]] @@ -3879,7 +3935,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.0", + "windows-targets 0.52.3", ] [[package]] @@ -3899,17 +3955,17 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" +checksum = "d380ba1dc7187569a8a9e91ed34b8ccfc33123bbacb8c0aed2d1ad7f3ef2dc5f" dependencies = [ - "windows_aarch64_gnullvm 0.52.0", - "windows_aarch64_msvc 0.52.0", - "windows_i686_gnu 0.52.0", - "windows_i686_msvc 0.52.0", - "windows_x86_64_gnu 0.52.0", - "windows_x86_64_gnullvm 0.52.0", - "windows_x86_64_msvc 0.52.0", + "windows_aarch64_gnullvm 0.52.3", + "windows_aarch64_msvc 0.52.3", + "windows_i686_gnu 0.52.3", + "windows_i686_msvc 0.52.3", + "windows_x86_64_gnu 0.52.3", + "windows_x86_64_gnullvm 0.52.3", + "windows_x86_64_msvc 0.52.3", ] [[package]] @@ -3920,9 +3976,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" +checksum = "68e5dcfb9413f53afd9c8f86e56a7b4d86d9a2fa26090ea2dc9e40fba56c6ec6" [[package]] name = "windows_aarch64_msvc" @@ -3932,9 +3988,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" +checksum = "8dab469ebbc45798319e69eebf92308e541ce46760b49b18c6b3fe5e8965b30f" [[package]] name = "windows_i686_gnu" @@ -3944,9 +4000,9 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" +checksum = "2a4e9b6a7cac734a8b4138a4e1044eac3404d8326b6c0f939276560687a033fb" [[package]] name = "windows_i686_msvc" @@ -3956,9 +4012,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" +checksum = "28b0ec9c422ca95ff34a78755cfa6ad4a51371da2a5ace67500cf7ca5f232c58" [[package]] name = "windows_x86_64_gnu" @@ -3968,9 +4024,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" +checksum = "704131571ba93e89d7cd43482277d6632589b18ecf4468f591fbae0a8b101614" [[package]] name = "windows_x86_64_gnullvm" @@ -3980,9 +4036,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" +checksum = "42079295511643151e98d61c38c0acc444e52dd42ab456f7ccfd5152e8ecf21c" [[package]] name = "windows_x86_64_msvc" @@ -3992,15 +4048,24 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" +checksum = "0770833d60a970638e989b3fa9fd2bb1aaadcf88963d1659fd7d9990196ed2d6" [[package]] name = "winnow" -version = "0.5.36" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "818ce546a11a9986bc24f93d0cdf38a8a1a400f1473ea8c82e59f6e0ffab9249" +checksum = "7a4191c47f15cc3ec71fcb4913cb83d58def65dd3787610213c649283b5ce178" dependencies = [ "memchr", ] @@ -4050,7 +4115,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 83134d8f0..26f4334f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,7 +56,7 @@ serde = { version = "1", features = ["derive"] } serde_bencode = "0" serde_bytes = "0" serde_json = "1" -ringbuf = "0.4.0-rc.2" +ringbuf = "0" serde_with = "3" serde_repr = "0" tdyne-peer-id = "1" diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 1326f806d..fbea11fac 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -24,9 +24,7 @@ use std::sync::Arc; use aquatic_udp_protocol::Response; use derive_more::Constructor; use log::{debug, error, info, trace}; -use ringbuf::storage::Static; -use ringbuf::traits::{Consumer, Observer, RingBuffer}; -use ringbuf::LocalRb; +use ringbuf::{Rb, StaticRb}; use tokio::net::UdpSocket; use tokio::sync::oneshot; use tokio::task::{AbortHandle, JoinHandle}; @@ -205,7 +203,7 @@ impl Launcher { #[derive(Default)] struct ActiveRequests { - rb: LocalRb>, // the number of requests we handle at the same time. + rb: StaticRb, // the number of requests we handle at the same time. } impl std::fmt::Debug for ActiveRequests { From 37c1fa7e56734056c892639ecbe1339fb3c40ee5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 22 Feb 2024 20:28:08 +0000 Subject: [PATCH 0238/1297] chore(deps): bump EndBug/label-sync from 2.3.2 to 2.3.3 --- .github/workflows/labels.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/labels.yaml b/.github/workflows/labels.yaml index 97aaa0308..bb8283f30 100644 --- a/.github/workflows/labels.yaml +++ b/.github/workflows/labels.yaml @@ -29,7 +29,7 @@ jobs: - id: sync name: Apply Labels from File - uses: EndBug/label-sync@da00f2c11fdb78e4fae44adac2fdd713778ea3e8 + uses: EndBug/label-sync@v2 with: config-file: .github/labels.json delete-other-labels: true From d673a594fc2218114ce9bdd05ac04f5abcdfabb3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 23 Feb 2024 06:53:33 +0000 Subject: [PATCH 0239/1297] docs: fix podman commands --- README.md | 2 +- docs/containers.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e584db3c8..74ba5e72b 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ docker run -it torrust/tracker:develop #### Podman: ```sh -podman run -it torrust/tracker:develop +podman run -it docker.io/torrust/tracker:develop ``` > Please read our [container guide][containers.md] for more information. diff --git a/docs/containers.md b/docs/containers.md index 2b06c0f76..2526b880a 100644 --- a/docs/containers.md +++ b/docs/containers.md @@ -14,7 +14,7 @@ docker run -it torrust/tracker:latest or with Podman: ```sh -podman run -it torrust/tracker:latest +podman run -it docker.io/torrust/tracker:latest ``` @@ -122,10 +122,10 @@ docker run -it torrust-tracker:debug ```sh # Release Mode -podman run -it torrust-tracker:release +podman run -it docker.io/torrust-tracker:release # Debug Mode -podman run -it torrust-tracker:debug +podman run -it docker.io/torrust-tracker:debug ``` ### Arguments @@ -226,7 +226,7 @@ podman run -it \ --volume ./storage/tracker/lib:/var/lib/torrust/tracker:Z \ --volume ./storage/tracker/log:/var/log/torrust/tracker:Z \ --volume ./storage/tracker/etc:/etc/torrust/tracker:Z \ - torrust-tracker:release + docker.io/torrust-tracker:release ``` ## Docker Compose From c348f72198c866e447f7c908f9f97f2fd8d2853f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 23 Feb 2024 07:01:33 +0000 Subject: [PATCH 0240/1297] docs: fix linter warnings in markdown --- README.md | 58 +++++++++++++++++++++++++--------------------- docs/containers.md | 27 ++++++++++++++------- 2 files changed, 49 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 74ba5e72b..18f3d361d 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,6 @@ # Torrust Tracker -[![container_wf_b]][container_wf] [![coverage_wf_b]][coverage_wf] [![deployment_wf_b]][deployment_wf] [![testing_wf_b]][testing_wf] - -__Torrust Tracker__, is a [BitTorrent][bittorrent] Tracker that matchmakes peers and collects statistics. Written in [Rust Language][rust] with the [axum] web framework. ___This tracker aims to be respectful to established standards, (both [formal][BEP 00] and [otherwise][torrent_source_felid]).___ +[![container_wf_b]][container_wf] [![coverage_wf_b]][coverage_wf] [![deployment_wf_b]][deployment_wf] [![testing_wf_b]][testing_wf]**Torrust Tracker** is a [BitTorrent][bittorrent] Tracker that matchmakes peers and collects statistics. Written in [Rust Language][rust] with the [Axum] web framework. _**This tracker aims to be respectful to established standards, (both [formal][BEP 00] and [otherwise][torrent_source_felid]).___ > This is a [Torrust][torrust] project and is in active development. It is community supported as well as sponsored by [Nautilus Cyberneering][nautilus]. @@ -20,14 +18,15 @@ __Torrust Tracker__, is a [BitTorrent][bittorrent] Tracker that matchmakes peers - [x] Persistent `SQLite3` or `MySQL` Databases. ## Implemented BitTorrent Enhancement Proposals (BEPs) +> > _[Learn more about BitTorrent Enhancement Proposals][BEP 00]_ -- [BEP 03] : The BitTorrent Protocol. -- [BEP 07] : IPv6 Support. -- [BEP 15] : UDP Tracker Protocol for BitTorrent. -- [BEP 23] : Tracker Returns Compact Peer Lists. -- [BEP 27] : Private Torrents. -- [BEP 48] : Tracker Protocol Extension: Scrape. +- [BEP 03]: The BitTorrent Protocol. +- [BEP 07]: IPv6 Support. +- [BEP 15]: UDP Tracker Protocol for BitTorrent. +- [BEP 23]: Tracker Returns Compact Peer Lists. +- [BEP 27]: Private Torrents. +- [BEP 48]: Tracker Protocol Extension: Scrape. ## Getting Started @@ -35,26 +34,28 @@ __Torrust Tracker__, is a [BitTorrent][bittorrent] Tracker that matchmakes peers The Torrust Tracker is [deployed to DockerHub][dockerhub], you can run a demo immediately with the following commands: -#### Docker: +#### Docker ```sh docker run -it torrust/tracker:develop ``` + > Please read our [container guide][containers.md] for more information. -#### Podman: +#### Podman ```sh podman run -it docker.io/torrust/tracker:develop ``` + > Please read our [container guide][containers.md] for more information. ### Development Version -- Please assure you have the ___[latest stable (or nightly) version of rust][rust]___. -- Please assure that you computer has enough ram. ___Recommended 16GB.___ +- Please ensure you have the _**[latest stable (or nightly) version of rust][rust]___. +- Please ensure that your computer has enough RAM. _**Recommended 16GB.___ -#### Checkout, Test and Run: +#### Checkout, Test and Run ```sh # Checkout repository into a new folder: @@ -71,7 +72,8 @@ cargo test --tests --benches --examples --workspace --all-targets --all-features # Run the tracker: cargo run ``` -#### Customization: + +#### Customization ```sh # Copy the default configuration into the standard location: @@ -92,7 +94,7 @@ _Optionally, you may choose to supply the entire configuration as an environment TORRUST_TRACKER_CONFIG=$(cat "./storage/tracker/etc/tracker.toml") cargo run ``` -_For deployment you __should__ override the `api_admin_token` by using an environmental variable:_ +_For deployment, you **should** override the `api_admin_token` by using an environmental variable:_ ```sh # Generate a Secret Token: @@ -105,9 +107,10 @@ TORRUST_TRACKER_CONFIG=$(cat "./storage/tracker/etc/tracker.toml") \ cargo run ``` -> Please view our [crate documentation][documentation] for more detailed instructions. +> Please view our [crate documentation][docs] for more detailed instructions. ### Services + The following services are provided by the default configuration: - UDP _(tracker)_ @@ -119,19 +122,20 @@ The following services are provided by the default configuration: ## Documentation -- [Management API (Version 1)][api] -- [Tracker (HTTP/TLS)][http] -- [Tracker (UDP)][udp] +- [Management API (Version 1)][API] +- [Tracker (HTTP/TLS)][HTTP] +- [Tracker (UDP)][UDP] ## Contributing + We are happy to support and welcome new people to our project. Please consider our [contributor guide][guide.md].
-This is an open-source community supported project. We welcome contributions from the community! +This is an open-source community-supported project. We welcome contributions from the community! -__How can you contribute?__ +**How can you contribute?** - Bug reports and feature requests. - Code contributions. You can start by looking at the issues labeled "[good first issues]". -- Documentation improvements. Check the [documentation][docs] and [API documentation][api] for typos, errors, or missing information. +- Documentation improvements. Check the [documentation][docs] and [API documentation][API] for typos, errors, or missing information. - Participation in the community. You can help by answering questions in the [discussions]. ## License @@ -151,11 +155,13 @@ Some files include explicit copyright notices and/or license notices. For prosperity, versions of Torrust Tracker that are older than five years are automatically granted the [MIT-0][MIT_0] license in addition to the existing [AGPL-3.0-only][AGPL_3_0] license. ## Contributor Agreement + The copyright of the Torrust Tracker is retained by the respective authors. **Contributors agree:** -- That all their contributions be granted a license(s) **compatible** with the [Torrust Trackers License](#License). -- That all contributors signal **clearly** and **explicitly** any other compilable licenses if they are not: *[AGPL-3.0-only with the legacy MIT-0 exception](#License)*. + +- That all their contributions be granted a license(s) **compatible** with the [Torrust Trackers License](#license). +- That all contributors signal **clearly** and **explicitly** any other compilable licenses if they are not: _[AGPL-3.0-only with the legacy MIT-0 exception](#license)_. **The Torrust-Tracker project has no copyright assignment agreement.** @@ -165,8 +171,6 @@ _We kindly ask you to take time and consider The Torrust Project [Contributor Ag This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [Dutch Bits]. Also thanks to [Naim A.] and [greatest-ape] for some parts of the code. Further added features and functions thanks to [Power2All]. - - [container_wf]: ../../actions/workflows/container.yaml [container_wf_b]: ../../actions/workflows/container.yaml/badge.svg [coverage_wf]: ../../actions/workflows/coverage.yaml diff --git a/docs/containers.md b/docs/containers.md index 2526b880a..6622e29b2 100644 --- a/docs/containers.md +++ b/docs/containers.md @@ -1,10 +1,10 @@ # Containers (Docker or Podman) ## Demo environment + It is simple to setup the tracker with the default configuration and run it using the pre-built public docker image: - With Docker: ```sh @@ -17,11 +17,12 @@ or with Podman: podman run -it docker.io/torrust/tracker:latest ``` - ## Requirements + - Tested with recent versions of Docker or Podman. ## Volumes + The [Containerfile](../Containerfile) (i.e. the Dockerfile) Defines Three Volumes: ```Dockerfile @@ -38,7 +39,8 @@ When instancing the container image with the `docker run` or `podman run` comman > NOTE: You can adjust this mapping for your preference, however this mapping is the default in our guides and scripts. -### Pre-Create Host-Mapped Folders: +### Pre-Create Host-Mapped Folders + Please run this command where you wish to run the container: ```sh @@ -46,11 +48,13 @@ mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ ``` ### Matching Ownership ID's of Host Storage and Container Volumes + It is important that the `torrust` user has the same uid `$(id -u)` as the host mapped folders. In our [entry script](../share/container/entry_script_sh), installed to `/usr/local/bin/entry.sh` inside the container, switches to the `torrust` user created based upon the `USER_UID` environmental variable. When running the container, you may use the `--env USER_ID="$(id -u)"` argument that gets the current user-id and passes to the container. ### Mapped Tree Structure + Using the standard mapping defined above produces this following mapped tree: ```s @@ -78,6 +82,7 @@ git clone https://github.com/torrust/torrust-tracker.git; cd torrust-tracker ``` ### (Docker) Setup Context + Before starting, if you are using docker, it is helpful to reset the context to the default: ```sh @@ -107,6 +112,7 @@ podman build --target debug --tag torrust-tracker:debug --file Containerfile . ## Running the Container ### Basic Run + No arguments are needed for simply checking the container image works: #### (Docker) Run Basic @@ -118,6 +124,7 @@ docker run -it torrust-tracker:release # Debug Mode docker run -it torrust-tracker:debug ``` + #### (Podman) Run Basic ```sh @@ -129,11 +136,13 @@ podman run -it docker.io/torrust-tracker:debug ``` ### Arguments + The arguments need to be placed before the image tag. i.e. `run [arguments] torrust-tracker:release` -#### Environmental Variables: +#### Environmental Variables + Environmental variables are loaded through the `--env`, in the format `--env VAR="value"`. The following environmental variables can be set: @@ -148,8 +157,8 @@ The following environmental variables can be set: - `API_PORT` - The port for the tracker API. This should match the port used in the configuration, (default `1212`). - `HEALTH_CHECK_API_PORT` - The port for the Health Check API. This should match the port used in the configuration, (default `1313`). - ### Sockets + Socket ports used internally within the container can be mapped to with the `--publish` argument. The format is: `--publish [optional_host_ip]:[host_port]:[container_port]/[optional_protocol]`, for example: `--publish 127.0.0.1:8080:80/tcp`. @@ -164,7 +173,8 @@ The default ports can be mapped with the following: > NOTE: Inside the container it is necessary to expose a socket with the wildcard address `0.0.0.0` so that it may be accessible from the host. Verify that the configuration that the sockets are wildcard. -### Volumes +### Host-mapped Volumes + By default the container will use install volumes for `/var/lib/torrust/tracker`, `/var/log/torrust/tracker`, and `/etc/torrust/tracker`, however for better administration it good to make these volumes host-mapped. The argument to host-map volumes is `--volume`, with the format: `--volume=[host-src:]container-dest[:]`. @@ -177,10 +187,9 @@ The default mapping can be supplied with the following arguments: --volume ./storage/tracker/etc:/etc/torrust/tracker:Z \ ``` - Please not the `:Z` at the end of the podman `--volume` mapping arguments, this is to give read-write permission on SELinux enabled systemd, if this doesn't work on your system, you can use `:rw` instead. -## Complete Example: +## Complete Example ### With Docker @@ -257,7 +266,7 @@ $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 06feacb91a9e torrust-tracker "cargo run" 18 minutes ago Up 4 seconds 0.0.0.0:1212->1212/tcp, :::1212->1212/tcp, 0.0.0.0:7070->7070/tcp, :::7070->7070/tcp, 0.0.0.0:6969->6969/udp, :::6969->6969/udp torrust-tracker-1 34d29e792ee2 mysql:8.0 "docker-entrypoint.s…" 18 minutes ago Up 5 seconds (healthy) 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp torrust-mysql-1 -``` +``` And you should be able to use the application, for example making a request to the API: From 5a6c968eb86dd7a4465f837cc8aeeb706beb59c0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 23 Feb 2024 08:24:14 +0000 Subject: [PATCH 0241/1297] feat: [#704] add latency to UDP tracker logs Example: ``` 2024-02-23T08:24:50.137064143+00:00 [UDP TRACKER][INFO] request; server_socket_addr=0.0.0.0:6969 action=ANNOUNCE transaction_id=-888840697 request_id=c38ab102-3ad1-48d3-8f2e-e03190d6e592 connection_id=4792797915217963415 info_hash=9c38422213e30bff212b30c360d26f9a02136422 2024-02-23T08:24:50.137075433+00:00 [UDP TRACKER][INFO] response; server_socket_addr=0.0.0.0:6969 transaction_id=-888840697 request_id=c38ab102-3ad1-48d3-8f2e-e03190d6e592 latency_ms=0 ``` --- src/servers/udp/handlers.rs | 7 ++++++- src/servers/udp/logging.rs | 17 +++++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index f8424879f..91a371a7b 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -3,6 +3,7 @@ use std::fmt; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::panic::Location; use std::sync::Arc; +use std::time::Instant; use aquatic_udp_protocol::{ AnnounceInterval, AnnounceRequest, AnnounceResponse, ConnectRequest, ConnectResponse, ErrorResponse, NumberOfDownloads, @@ -35,6 +36,8 @@ use crate::shared::bit_torrent::info_hash::InfoHash; pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc, socket: Arc) -> Response { debug!("Handling Packets: {udp_request:?}"); + let start_time = Instant::now(); + let request_id = RequestId::make(&udp_request); let server_socket_addr = socket.local_addr().expect("Could not get local_addr for socket."); @@ -58,7 +61,9 @@ pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc handle_error(&e, transaction_id), }; - log_response(&response, &transaction_id, &request_id, &server_socket_addr); + let latency = start_time.elapsed(); + + log_response(&response, &transaction_id, &request_id, &server_socket_addr, latency); response } diff --git a/src/servers/udp/logging.rs b/src/servers/udp/logging.rs index bd1c2951b..a32afc6a3 100644 --- a/src/servers/udp/logging.rs +++ b/src/servers/udp/logging.rs @@ -1,6 +1,7 @@ //! Logging for UDP Tracker requests and responses. use std::net::SocketAddr; +use std::time::Duration; use aquatic_udp_protocol::{Request, Response, TransactionId}; @@ -36,7 +37,13 @@ pub fn log_request(request: &Request, request_id: &RequestId, server_socket_addr tracing::span!( target: "UDP TRACKER", - tracing::Level::INFO, "request", server_socket_addr = %server_socket_addr, action = %action, transaction_id = %transaction_id_str, request_id = %request_id, connection_id = %connection_id_str); + tracing::Level::INFO, + "request", + server_socket_addr = %server_socket_addr, + action = %action, + transaction_id = %transaction_id_str, + request_id = %request_id, + connection_id = %connection_id_str); } }; } @@ -54,10 +61,16 @@ pub fn log_response( transaction_id: &TransactionId, request_id: &RequestId, server_socket_addr: &SocketAddr, + latency: Duration, ) { tracing::span!( target: "UDP TRACKER", - tracing::Level::INFO, "response", server_socket_addr = %server_socket_addr, transaction_id = %transaction_id.0.to_string(), request_id = %request_id); + tracing::Level::INFO, + "response", + server_socket_addr = %server_socket_addr, + transaction_id = %transaction_id.0.to_string(), + request_id = %request_id, + latency_ms = %latency.as_millis()); } pub fn log_bad_request(request_id: &RequestId) { From d4310a5d25af612601111e1fa8084733b18d18d1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 Feb 2024 11:15:45 +0000 Subject: [PATCH 0242/1297] chore(deps): udpate cargo dependencies ```console cargo update Updating crates.io index Updating bumpalo v3.15.2 -> v3.15.3 Updating cc v1.0.86 -> v1.0.88 Updating darling v0.20.6 -> v0.20.8 Updating darling_core v0.20.6 -> v0.20.8 Updating darling_macro v0.20.6 -> v0.20.8 Updating half v2.3.1 -> v2.4.0 Updating hermit-abi v0.3.6 -> v0.3.8 Updating local-ip-address v0.6.0 -> v0.6.1 Updating rustls-pki-types v1.3.0 -> v1.3.1 Updating socket2 v0.5.5 -> v0.5.6 Updating syn v2.0.50 -> v2.0.51 Updating tempfile v3.10.0 -> v3.10.1 Updating tower-http v0.5.1 -> v0.5.2 ``` --- Cargo.lock | 108 ++++++++++++++++++++++++++--------------------------- 1 file changed, 54 insertions(+), 54 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e1092fefc..53b9c9569 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -191,7 +191,7 @@ checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -276,7 +276,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -357,7 +357,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -416,7 +416,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", "syn_derive", ] @@ -449,9 +449,9 @@ checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" [[package]] name = "bumpalo" -version = "3.15.2" +version = "3.15.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3b1be7772ee4501dba05acbe66bb1e8760f6a6c474a36035631638e4415f130" +checksum = "8ea184aa71bb362a1157c896979544cc23974e08fd265f29ea96b59f0b4a555b" [[package]] name = "bytecheck" @@ -495,9 +495,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.0.86" +version = "1.0.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f9fa1897e4325be0d68d48df6aa1a71ac2ed4d27723887e7754192705350730" +checksum = "02f341c093d19155a6e41631ce5971aac4e9a868262212153124c15fa22d1cdc" dependencies = [ "libc", ] @@ -605,7 +605,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -840,9 +840,9 @@ dependencies = [ [[package]] name = "darling" -version = "0.20.6" +version = "0.20.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c376d08ea6aa96aafe61237c7200d1241cb177b7d3a542d791f2d118e9cbb955" +checksum = "54e36fcd13ed84ffdfda6f5be89b31287cbb80c439841fe69e04841435464391" dependencies = [ "darling_core", "darling_macro", @@ -850,27 +850,27 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.20.6" +version = "0.20.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33043dcd19068b8192064c704b3f83eb464f91f1ff527b44a4e2b08d9cdb8855" +checksum = "9c2cf1c23a687a1feeb728783b993c4e1ad83d99f351801977dd809b48d0a70f" dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", "strsim 0.10.0", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] name = "darling_macro" -version = "0.20.6" +version = "0.20.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5a91391accf613803c2a9bf9abccdbaa07c54b4244a5b64883f9c3c137c86be" +checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" dependencies = [ "darling_core", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -904,7 +904,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -1082,7 +1082,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -1094,7 +1094,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -1106,7 +1106,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -1171,7 +1171,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -1277,9 +1277,9 @@ dependencies = [ [[package]] name = "half" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc52e53916c08643f1b56ec082790d1e86a32e58dc5268f897f313fbae7b4872" +checksum = "b5eceaaeec696539ddaf7b333340f1af35a5aa87ae3e4f3ead0532f72affab2e" dependencies = [ "cfg-if", "crunchy", @@ -1330,9 +1330,9 @@ checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" [[package]] name = "hermit-abi" -version = "0.3.6" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd5256b483761cd23699d0da46cc6fd2ee3be420bbe6d020ae4a091e70b7e9fd" +checksum = "379dada1584ad501b383485dd706b8afb7a70fcbc7f4da7d780638a5a6124a60" [[package]] name = "hex" @@ -1755,9 +1755,9 @@ checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" [[package]] name = "local-ip-address" -version = "0.6.0" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f63e1499d2495be571af92e9ca9dca4e7bf26c47b87cb8d0c6100825e521dd6b" +checksum = "136ef34e18462b17bf39a7826f8f3bbc223341f8e83822beb8b77db9a3d49696" dependencies = [ "libc", "neli", @@ -1858,7 +1858,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -1909,7 +1909,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", "termcolor", "thiserror", ] @@ -2109,7 +2109,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -2226,7 +2226,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -2295,7 +2295,7 @@ checksum = "266c042b60c9c76b8d53061e52b2e0d1116abc57cefc8c5cd671619a56ac3690" dependencies = [ "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -2810,9 +2810,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.3.0" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "048a63e5b3ac996d78d402940b5fa47973d2d080c6c6fffa1d0f19c4445310b7" +checksum = "5ede67b28608b4c60685c7d54122d4400d90f62b40caee7700e700380a390fa8" [[package]] name = "rustls-webpki" @@ -2956,7 +2956,7 @@ checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -2988,7 +2988,7 @@ checksum = "0b2e6b945e9d3df726b65d6ee24060aff8e3533d431f677a9695db04eff9dfdb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -3039,7 +3039,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -3108,12 +3108,12 @@ checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7" [[package]] name = "socket2" -version = "0.5.5" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5fac59a5cb5dd637972e5fca70daf0523c9067fcdc4842f053dae04a18f8e9" +checksum = "05ffd9c0a93b7543e062e759284fcf5f5e3b098501104bfbdde4d404db792871" dependencies = [ "libc", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -3163,9 +3163,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.50" +version = "2.0.51" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74f1bdc9872430ce9b75da68329d1c1746faf50ffac5f19e02b71e37ff881ffb" +checksum = "6ab617d94515e94ae53b8406c628598680aa0c9587474ecbe58188f7b345d66c" dependencies = [ "proc-macro2", "quote", @@ -3181,7 +3181,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -3236,9 +3236,9 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.10.0" +version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a365e8cd18e44762ef95d87f284f4b5cd04107fec2ff3052bd6a3e6069669e67" +checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", @@ -3278,7 +3278,7 @@ checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81" dependencies = [ "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -3372,7 +3372,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -3603,9 +3603,9 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0da193277a4e2c33e59e09b5861580c33dd0a637c3883d0fa74ba40c0374af2e" +checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ "async-compression", "bitflags 2.4.2", @@ -3666,7 +3666,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] @@ -3825,7 +3825,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", "wasm-bindgen-shared", ] @@ -3859,7 +3859,7 @@ checksum = "642f325be6301eb8107a83d12a8ac6c1e1c54345a7ef1a9261962dfefda09e66" dependencies = [ "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4115,7 +4115,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.50", + "syn 2.0.51", ] [[package]] From eb8478d9101e5b4579ad1d76ede02c5f1c510d0b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 Feb 2024 16:10:06 +0000 Subject: [PATCH 0243/1297] refactor: [#714] use tower_http::request_id::MakeRequestUuid instead of a custom request UUID generator. I did not know there was already an implementation for it. --- src/servers/apis/routes.rs | 19 ++++--------------- src/servers/health_check_api/server.rs | 19 ++++--------------- src/servers/http/v1/routes.rs | 19 ++++--------------- 3 files changed, 12 insertions(+), 45 deletions(-) diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index aed3ee19d..e3d1ef446 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use std::time::Duration; -use axum::http::{HeaderName, HeaderValue}; +use axum::http::HeaderName; use axum::response::Response; use axum::routing::get; use axum::{middleware, Router}; @@ -16,10 +16,9 @@ use hyper::Request; use torrust_tracker_configuration::AccessTokens; use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; -use tower_http::request_id::{MakeRequestId, RequestId, SetRequestIdLayer}; +use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; use tracing::{Level, Span}; -use uuid::Uuid; use super::v1; use super::v1::context::health_check::handlers::health_check_handler; @@ -41,7 +40,7 @@ pub fn router(tracker: Arc, access_tokens: Arc) -> Router .layer(middleware::from_fn_with_state(state, v1::middlewares::auth::auth)) .route(&format!("{api_url_prefix}/health_check"), get(health_check_handler)) .layer(CompressionLayer::new()) - .layer(SetRequestIdLayer::x_request_id(RequestIdGenerator)) + .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) .layer(PropagateHeaderLayer::new(HeaderName::from_static("x-request-id"))) .layer( TraceLayer::new_for_http() @@ -73,15 +72,5 @@ pub fn router(tracker: Arc, access_tokens: Arc) -> Router tracing::Level::INFO, "response", latency = %latency_ms, status = %status_code, request_id = %request_id); }), ) - .layer(SetRequestIdLayer::x_request_id(RequestIdGenerator)) -} - -#[derive(Clone, Default)] -struct RequestIdGenerator; - -impl MakeRequestId for RequestIdGenerator { - fn make_request_id(&mut self, _request: &Request) -> Option { - let id = HeaderValue::from_str(&Uuid::new_v4().to_string()).expect("UUID is a valid HTTP header value"); - Some(RequestId::new(id)) - } + .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) } diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index 049f48d40..05ed605f4 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -5,7 +5,7 @@ use std::net::SocketAddr; use std::time::Duration; -use axum::http::{HeaderName, HeaderValue}; +use axum::http::HeaderName; use axum::response::Response; use axum::routing::get; use axum::{Json, Router}; @@ -17,10 +17,9 @@ use serde_json::json; use tokio::sync::oneshot::{Receiver, Sender}; use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; -use tower_http::request_id::{MakeRequestId, RequestId, SetRequestIdLayer}; +use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; use tracing::{Level, Span}; -use uuid::Uuid; use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; @@ -43,7 +42,7 @@ pub fn start( .route("/health_check", get(health_check_handler)) .with_state(register) .layer(CompressionLayer::new()) - .layer(SetRequestIdLayer::x_request_id(RequestIdGenerator)) + .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) .layer(PropagateHeaderLayer::new(HeaderName::from_static("x-request-id"))) .layer( TraceLayer::new_for_http() @@ -75,7 +74,7 @@ pub fn start( tracing::Level::INFO, "response", latency = %latency_ms, status = %status_code, request_id = %request_id); }), ) - .layer(SetRequestIdLayer::x_request_id(RequestIdGenerator)); + .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)); let socket = std::net::TcpListener::bind(bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); @@ -99,13 +98,3 @@ pub fn start( running } - -#[derive(Clone, Default)] -struct RequestIdGenerator; - -impl MakeRequestId for RequestIdGenerator { - fn make_request_id(&mut self, _request: &Request) -> Option { - let id = HeaderValue::from_str(&Uuid::new_v4().to_string()).expect("UUID is a valid HTTP header value"); - Some(RequestId::new(id)) - } -} diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index b972cf62f..05cd38713 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -3,7 +3,7 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; -use axum::http::{HeaderName, HeaderValue}; +use axum::http::HeaderName; use axum::response::Response; use axum::routing::get; use axum::Router; @@ -11,10 +11,9 @@ use axum_client_ip::SecureClientIpSource; use hyper::Request; use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; -use tower_http::request_id::{MakeRequestId, RequestId, SetRequestIdLayer}; +use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; use tracing::{Level, Span}; -use uuid::Uuid; use super::handlers::{announce, health_check, scrape}; use crate::core::Tracker; @@ -37,7 +36,7 @@ pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { // Add extension to get the client IP from the connection info .layer(SecureClientIpSource::ConnectInfo.into_extension()) .layer(CompressionLayer::new()) - .layer(SetRequestIdLayer::x_request_id(RequestIdGenerator)) + .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) .layer(PropagateHeaderLayer::new(HeaderName::from_static("x-request-id"))) .layer( TraceLayer::new_for_http() @@ -69,15 +68,5 @@ pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { tracing::Level::INFO, "response", server_socket_addr= %server_socket_addr, latency = %latency_ms, status = %status_code, request_id = %request_id); }), ) - .layer(SetRequestIdLayer::x_request_id(RequestIdGenerator)) -} - -#[derive(Clone, Default)] -struct RequestIdGenerator; - -impl MakeRequestId for RequestIdGenerator { - fn make_request_id(&mut self, _request: &Request) -> Option { - let id = HeaderValue::from_str(&Uuid::new_v4().to_string()).expect("UUID is a valid HTTP header value"); - Some(RequestId::new(id)) - } + .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) } From e77d89f848c4525a8dba7081584e6b14db732c95 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 Feb 2024 16:59:41 +0000 Subject: [PATCH 0244/1297] chore: add ADR about when to use plural for mod names --- ...ural_for_modules_containing_collections.md | 35 +++++++++++++++++++ docs/adrs/README.md | 23 ++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 docs/adrs/20240227164834_use_plural_for_modules_containing_collections.md create mode 100644 docs/adrs/README.md diff --git a/docs/adrs/20240227164834_use_plural_for_modules_containing_collections.md b/docs/adrs/20240227164834_use_plural_for_modules_containing_collections.md new file mode 100644 index 000000000..beb3cee00 --- /dev/null +++ b/docs/adrs/20240227164834_use_plural_for_modules_containing_collections.md @@ -0,0 +1,35 @@ +# Use plural for modules containing collections of types + +## Description + +In Rust, the naming conventions for module names (mod names) generally lean +towards using the singular form, rather than plurals. This practice aligns with +Rust's emphasis on clarity and precision in code organization. The idea is that +a module name should represent a single concept or functionality, which often +means using a singular noun to describe what the module contains or does. + +However, it's important to note that conventions can vary depending on the +context or the specific project. Some projects may choose to use plural forms +for module names if they feel it more accurately represents the contents of the +module. For example, a module that contains multiple implementations of a +similar concept or utility functions related to a specific theme might be named +in the plural to reflect the diversity of its contents. + +This could have some pros anc cons. For example, for a module containing types of +requests you could refer to a concrete request with `request::Announce` or +`requests::Announce`. If you read a code line `request::Announce` is probably +better. However, if you read the filed or folder name `requests`gives you a +better idea of what the modules contains. + +## Agreement + +We agree on use plural in cases where the modules contain some types with the +same type of responsibility. For example: + +- `src/servers`. +- `src/servers/http/v1/requests`. +- `src/servers/http/v1/responses`. +- `src/servers/http/v1/services`. +- Etcetera. + +We will change them progressively. diff --git a/docs/adrs/README.md b/docs/adrs/README.md new file mode 100644 index 000000000..85986fc36 --- /dev/null +++ b/docs/adrs/README.md @@ -0,0 +1,23 @@ +# Architectural Decision Records (ADRs) + +This directory contains the architectural decision records (ADRs) for the +project. ADRs are a way to document the architectural decisions made in the +project. + +More info: . + +## How to add a new record + +For the prefix: + +```s +date -u +"%Y%m%d%H%M%S" +``` + +Then you can create a new markdown file with the following format: + +```s +20230510152112_title.md +``` + +For the time being, we are not following any specific template. From f9a5f7e3462526297b92dde9d39acb1029aad220 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 11 Mar 2024 10:05:46 +0000 Subject: [PATCH 0245/1297] chore: fix linting errors --- packages/configuration/src/lib.rs | 2 +- packages/primitives/src/lib.rs | 2 +- packages/test-helpers/src/configuration.rs | 6 +++--- src/servers/udp/error.rs | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 4b81aed8b..4068c046f 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -475,7 +475,7 @@ pub struct Configuration { /// peers from the torrent peer list. pub inactive_peer_cleanup_interval: u64, /// If enabled, the tracker will remove torrents that have no peers. - /// THe clean up torrent job runs every `inactive_peer_cleanup_interval` + /// The clean up torrent job runs every `inactive_peer_cleanup_interval` /// seconds and it removes inactive peers. Eventually, the peer list of a /// torrent could be empty and the torrent will be removed if this option is /// enabled. diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index e6f8cb93b..f6a14b9e8 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -19,7 +19,7 @@ pub enum DatabaseDriver { // TODO: Move to the database crate once that gets its own crate. /// The Sqlite3 database driver. Sqlite3, - /// The MySQL database driver. + /// The `MySQL` database driver. MySQL, } diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 388d0151f..49cfdd390 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -55,7 +55,7 @@ pub fn ephemeral() -> Configuration { let temp_directory = env::temp_dir(); let random_db_id = random::string(16); let temp_file = temp_directory.join(format!("data_{random_db_id}.db")); - config.db_path = temp_file.to_str().unwrap().to_owned(); + temp_file.to_str().unwrap().clone_into(&mut config.db_path); config } @@ -138,8 +138,8 @@ pub fn ephemeral_ipv6() -> Configuration { let ipv6 = format!("[::]:{}", 0); - cfg.http_api.bind_address = ipv6.clone(); - cfg.http_trackers[0].bind_address = ipv6.clone(); + cfg.http_api.bind_address.clone_from(&ipv6); + cfg.http_trackers[0].bind_address.clone_from(&ipv6); cfg.udp_trackers[0].bind_address = ipv6; cfg diff --git a/src/servers/udp/error.rs b/src/servers/udp/error.rs index fb7bb93f3..315c9d1cf 100644 --- a/src/servers/udp/error.rs +++ b/src/servers/udp/error.rs @@ -13,7 +13,7 @@ pub enum Error { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, }, - /// Error returned from a third-party library (aquatic_udp_protocol). + /// Error returned from a third-party library (`aquatic_udp_protocol`). #[error("internal server error: {message}, {location}")] InternalServer { location: &'static Location<'static>, From 4b24256e0b7a2d36de439a69f63c626ddc279aa6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 11 Mar 2024 17:10:01 +0000 Subject: [PATCH 0246/1297] chore(deps): add cargo dependency: axum-extra We need to parse URL query parameter arrays. For example: http://127.0.0.1:1212/api/v1/torrents?token=MyAccessToken&info_hash=9c38422213e30bff212b30c360d26f9a02136422&info_hash=2b66980093bc11806fab50cb3cb41835b95a0362 ```rust pub struct QueryParams { /// The offset of the first page to return. Starts at 0. #[serde(default, deserialize_with = "empty_string_as_none")] pub offset: Option, /// The maximum number of items to return per page. #[serde(default, deserialize_with = "empty_string_as_none")] pub limit: Option, /// A list of infohashes to retrieve. #[serde(default, rename = "info_hash")] pub info_hashes: Vec, } ``` --- Cargo.lock | 36 ++++++++++++++++++++++++++++++++++++ Cargo.toml | 1 + 2 files changed, 37 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 53b9c9569..9bc13c1a7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -267,6 +267,28 @@ dependencies = [ "tracing", ] +[[package]] +name = "axum-extra" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "895ff42f72016617773af68fb90da2a9677d89c62338ec09162d4909d86fdd8f" +dependencies = [ + "axum", + "axum-core", + "bytes", + "futures-util", + "http 1.0.0", + "http-body 1.0.0", + "http-body-util", + "mime", + "pin-project-lite", + "serde", + "serde_html_form", + "tower", + "tower-layer", + "tower-service", +] + [[package]] name = "axum-macros" version = "0.4.1" @@ -2959,6 +2981,19 @@ dependencies = [ "syn 2.0.51", ] +[[package]] +name = "serde_html_form" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50437e6a58912eecc08865e35ea2e8d365fbb2db0debb1c8bb43bf1faf055f25" +dependencies = [ + "form_urlencoded", + "indexmap 2.2.3", + "itoa", + "ryu", + "serde", +] + [[package]] name = "serde_json" version = "1.0.114" @@ -3485,6 +3520,7 @@ dependencies = [ "async-trait", "axum", "axum-client-ip", + "axum-extra", "axum-server", "binascii", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 26f4334f1..36c865447 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,6 +34,7 @@ aquatic_udp_protocol = "0" async-trait = "0" axum = { version = "0", features = ["macros"] } axum-client-ip = "0" +axum-extra = { version = "0.9.2", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls"] } binascii = "0" chrono = { version = "0", default-features = false, features = ["clock"] } From d39bfc20fce259fe575c1f4c4d3e3a628e2a78b9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 11 Mar 2024 17:13:33 +0000 Subject: [PATCH 0247/1297] feat: [#725] API. Add scrape filter to torrents endpoint The torrents endppint allow getting a list of torrents provifing the infohashes: http://127.0.0.1:1212/api/v1/torrents?token=MyAccessToken&info_hash=9c38422213e30bff212b30c360d26f9a02136422&info_hash=2b66980093bc11806fab50cb3cb41835b95a0362 It's like the tracker "scrape" request. The response JSON is the same as the normal torrent list: ```json [ { "info_hash": "9c38422213e30bff212b30c360d26f9a02136422", "seeders": 1, "completed": 0, "leechers": 0 }, { "info_hash": "2b66980093bc11806fab50cb3cb41835b95a0362", "seeders": 1, "completed": 0, "leechers": 0 } ] ``` --- src/core/services/torrent.rs | 36 ++++++-- .../apis/v1/context/torrent/handlers.rs | 91 ++++++++++++++----- .../api/v1/contract/context/torrent.rs | 65 ++++++++++++- 3 files changed, 163 insertions(+), 29 deletions(-) diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index d1ab29a7f..fc24e7c4c 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -115,7 +115,7 @@ pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Op } /// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list. -pub async fn get_torrents(tracker: Arc, pagination: &Pagination) -> Vec { +pub async fn get_torrents_page(tracker: Arc, pagination: &Pagination) -> Vec { let db = tracker.torrents.get_torrents().await; let mut basic_infos: Vec = vec![]; @@ -134,6 +134,28 @@ pub async fn get_torrents(tracker: Arc, pagination: &Pagination) -> Vec basic_infos } +/// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list. +pub async fn get_torrents(tracker: Arc, info_hashes: &[InfoHash]) -> Vec { + let db = tracker.torrents.get_torrents().await; + + let mut basic_infos: Vec = vec![]; + + for info_hash in info_hashes { + if let Some(entry) = db.get(info_hash) { + let (seeders, completed, leechers) = entry.get_stats(); + + basic_infos.push(BasicInfo { + info_hash: *info_hash, + seeders: u64::from(seeders), + completed: u64::from(completed), + leechers: u64::from(leechers), + }); + } + } + + basic_infos +} + #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; @@ -219,7 +241,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::core::services::torrent::tests::sample_peer; - use crate::core::services::torrent::{get_torrents, BasicInfo, Pagination}; + use crate::core::services::torrent::{get_torrents_page, BasicInfo, Pagination}; use crate::core::services::tracker_factory; use crate::shared::bit_torrent::info_hash::InfoHash; @@ -231,7 +253,7 @@ mod tests { async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let tracker = Arc::new(tracker_factory(&tracker_configuration())); - let torrents = get_torrents(tracker.clone(), &Pagination::default()).await; + let torrents = get_torrents_page(tracker.clone(), &Pagination::default()).await; assert_eq!(torrents, vec![]); } @@ -247,7 +269,7 @@ mod tests { .update_torrent_with_peer_and_get_stats(&info_hash, &sample_peer()) .await; - let torrents = get_torrents(tracker.clone(), &Pagination::default()).await; + let torrents = get_torrents_page(tracker.clone(), &Pagination::default()).await; assert_eq!( torrents, @@ -279,7 +301,7 @@ mod tests { let offset = 0; let limit = 1; - let torrents = get_torrents(tracker.clone(), &Pagination::new(offset, limit)).await; + let torrents = get_torrents_page(tracker.clone(), &Pagination::new(offset, limit)).await; assert_eq!(torrents.len(), 1); } @@ -303,7 +325,7 @@ mod tests { let offset = 1; let limit = 4000; - let torrents = get_torrents(tracker.clone(), &Pagination::new(offset, limit)).await; + let torrents = get_torrents_page(tracker.clone(), &Pagination::new(offset, limit)).await; assert_eq!(torrents.len(), 1); assert_eq!( @@ -333,7 +355,7 @@ mod tests { .update_torrent_with_peer_and_get_stats(&info_hash2, &sample_peer()) .await; - let torrents = get_torrents(tracker.clone(), &Pagination::default()).await; + let torrents = get_torrents_page(tracker.clone(), &Pagination::default()).await; assert_eq!( torrents, diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs index 101a25c8d..dcb92dec3 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/src/servers/apis/v1/context/torrent/handlers.rs @@ -4,14 +4,15 @@ use std::fmt; use std::str::FromStr; use std::sync::Arc; -use axum::extract::{Path, Query, State}; -use axum::response::{IntoResponse, Json, Response}; +use axum::extract::{Path, State}; +use axum::response::{IntoResponse, Response}; +use axum_extra::extract::Query; use log::debug; use serde::{de, Deserialize, Deserializer}; +use thiserror::Error; -use super::resources::torrent::ListItem; use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; -use crate::core::services::torrent::{get_torrent_info, get_torrents, Pagination}; +use crate::core::services::torrent::{get_torrent_info, get_torrents, get_torrents_page, Pagination}; use crate::core::Tracker; use crate::servers::apis::v1::responses::invalid_info_hash_param_response; use crate::servers::apis::InfoHashParam; @@ -36,39 +37,87 @@ pub async fn get_torrent_handler(State(tracker): State>, Path(info_ } } -/// A container for the optional URL query pagination parameters: -/// `offset` and `limit`. +/// A container for the URL query parameters. +/// +/// Pagination: `offset` and `limit`. +/// Array of infohashes: `info_hash`. +/// +/// You can either get all torrents with pagination or get a list of torrents +/// providing a list of infohashes. For example: +/// +/// First page of torrents: +/// +/// +/// +/// +/// Only two torrents: +/// +/// +/// +/// +/// NOTICE: Pagination is ignored if array of infohashes is provided. #[derive(Deserialize, Debug)] -pub struct PaginationParams { +pub struct QueryParams { /// The offset of the first page to return. Starts at 0. #[serde(default, deserialize_with = "empty_string_as_none")] pub offset: Option, - /// The maximum number of items to return per page + /// The maximum number of items to return per page. #[serde(default, deserialize_with = "empty_string_as_none")] pub limit: Option, + /// A list of infohashes to retrieve. + #[serde(default, rename = "info_hash")] + pub info_hashes: Vec, } /// It handles the request to get a list of torrents. /// -/// It returns a `200` response with a json array with -/// [`ListItem`] -/// resources. +/// It returns a `200` response with a json array with [`crate::servers::apis::v1::context::torrent::resources::torrent::ListItem`] resources. /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent#list-torrents) /// for more information about this endpoint. -pub async fn get_torrents_handler( - State(tracker): State>, - pagination: Query, -) -> Json> { +pub async fn get_torrents_handler(State(tracker): State>, pagination: Query) -> Response { debug!("pagination: {:?}", pagination); - torrent_list_response( - &get_torrents( - tracker.clone(), - &Pagination::new_with_options(pagination.0.offset, pagination.0.limit), + if pagination.0.info_hashes.is_empty() { + torrent_list_response( + &get_torrents_page( + tracker.clone(), + &Pagination::new_with_options(pagination.0.offset, pagination.0.limit), + ) + .await, ) - .await, - ) + .into_response() + } else { + match parse_info_hashes(pagination.0.info_hashes) { + Ok(info_hashes) => torrent_list_response(&get_torrents(tracker.clone(), &info_hashes).await).into_response(), + Err(err) => match err { + QueryParamError::InvalidInfoHash { info_hash } => invalid_info_hash_param_response(&info_hash), + }, + } + } +} + +#[derive(Error, Debug)] +pub enum QueryParamError { + #[error("invalid infohash {info_hash}")] + InvalidInfoHash { info_hash: String }, +} + +fn parse_info_hashes(info_hashes_str: Vec) -> Result, QueryParamError> { + let mut info_hashes: Vec = Vec::new(); + + for info_hash_str in info_hashes_str { + match InfoHash::from_str(&info_hash_str) { + Ok(info_hash) => info_hashes.push(info_hash), + Err(_err) => { + return Err(QueryParamError::InvalidInfoHash { + info_hash: info_hash_str, + }) + } + } + } + + Ok(info_hashes) } /// Serde deserialization decorator to map empty Strings to None, diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index 63b97b402..ee701ecc4 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -19,7 +19,7 @@ use crate::servers::api::v1::contract::fixtures::{ use crate::servers::api::Started; #[tokio::test] -async fn should_allow_getting_torrents() { +async fn should_allow_getting_all_torrents() { let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); @@ -100,6 +100,48 @@ async fn should_allow_the_torrents_result_pagination() { env.stop().await; } +#[tokio::test] +async fn should_allow_getting_a_list_of_torrents_providing_infohashes() { + let env = Started::new(&configuration::ephemeral().into()).await; + + let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 + let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); // DevSkim: ignore DS173237 + + env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; + + let response = Client::new(env.get_connection_info()) + .get_torrents(Query::params( + [ + QueryParam::new("info_hash", "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d"), // DevSkim: ignore DS173237 + QueryParam::new("info_hash", "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d"), // DevSkim: ignore DS173237 + ] + .to_vec(), + )) + .await; + + assert_torrent_list( + response, + vec![ + torrent::ListItem { + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 + seeders: 1, + completed: 0, + leechers: 0, + }, + torrent::ListItem { + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 + seeders: 1, + completed: 0, + leechers: 0, + }, + ], + ) + .await; + + env.stop().await; +} + #[tokio::test] async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_parsed() { let env = Started::new(&configuration::ephemeral().into()).await; @@ -134,6 +176,27 @@ async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_p env.stop().await; } +#[tokio::test] +async fn should_fail_getting_torrents_when_the_info_hash_parameter_is_invalid() { + let env = Started::new(&configuration::ephemeral().into()).await; + + let invalid_info_hashes = [" ", "-1", "1.1", "INVALID INFO_HASH"]; + + for invalid_info_hash in &invalid_info_hashes { + let response = Client::new(env.get_connection_info()) + .get_torrents(Query::params([QueryParam::new("info_hash", invalid_info_hash)].to_vec())) + .await; + + assert_bad_request( + response, + &format!("Invalid URL: invalid infohash param: string \"{invalid_info_hash}\", expected a 40 character long string"), + ) + .await; + } + + env.stop().await; +} + #[tokio::test] async fn should_not_allow_getting_torrents_for_unauthenticated_users() { let env = Started::new(&configuration::ephemeral().into()).await; From fd0ad1bbce9c06c5f195b6885f618a409892e774 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 14 Mar 2024 16:31:21 +0000 Subject: [PATCH 0248/1297] test: [#87] remove lua script for HTTP tracker benchmarking We will use the aquatic commands to test both the HTTP and UDP trackers. --- tests/README.md | 9 ----- tests/wrk_benchmark_announce.lua | 68 -------------------------------- 2 files changed, 77 deletions(-) delete mode 100644 tests/README.md delete mode 100644 tests/wrk_benchmark_announce.lua diff --git a/tests/README.md b/tests/README.md deleted file mode 100644 index 04860056c..000000000 --- a/tests/README.md +++ /dev/null @@ -1,9 +0,0 @@ -### Running Benchmarks - -#### HTTP(S) Announce Peer + Torrent -For this benchmark we use the tool [wrk](https://github.com/wg/wrk). - -To run the benchmark using wrk, execute the following example script (change the url to your own tracker url): - - wrk -c200 -t1 -d10s -s ./wrk_benchmark_announce.lua --latency http://tracker.dutchbits.nl - diff --git a/tests/wrk_benchmark_announce.lua b/tests/wrk_benchmark_announce.lua deleted file mode 100644 index c0bdac48d..000000000 --- a/tests/wrk_benchmark_announce.lua +++ /dev/null @@ -1,68 +0,0 @@ --- else the randomness would be the same every run -math.randomseed(os.time()) - -local charset = "0123456789ABCDEF" - -function hex_to_char(hex) - local n = tonumber(hex, 16) - local f = string.char(n) - return f -end - -function hex_string_to_char_string(hex) - local ret = {} - local r - for i = 0, 19 do - local x = i * 2 - r = hex:sub(x+1, x+2) - local f = hex_to_char(r) - table.insert(ret, f) - end - return table.concat(ret) -end - -function url_encode(str) - str = string.gsub (str, "([^0-9a-zA-Z !'()*._~-])", -- locale independent - function (c) return string.format ("%%%02X", string.byte(c)) end) - str = string.gsub (str, " ", "+") - return str -end - -function gen_hex_string(length) - local ret = {} - local r - for i = 1, length do - r = math.random(1, #charset) - table.insert(ret, charset:sub(r, r)) - end - return table.concat(ret) -end - -function random_info_hash() - local hexString = gen_hex_string(40) - local str = hex_string_to_char_string(hexString) - return url_encode(str) -end - -function generate_unique_info_hashes(size) - local result = {} - - for i = 1, size do - result[i] = random_info_hash() - end - - return result -end - -info_hashes = generate_unique_info_hashes(5000000) - -index = 1 - --- the request function that will run at each request -request = function() - path = "/announce?info_hash=" .. info_hashes[index] .. "&peer_id=-lt0D80-a%D4%10%19%99%A6yh%9A%E1%CD%96&port=54434&uploaded=885&downloaded=0&left=0&corrupt=0&key=A78381BD&numwant=200&compact=1&no_peer_id=1&supportcrypto=1&redundant=0" - index = index + 1 - headers = {} - headers["X-Forwarded-For"] = "1.1.1.1" - return wrk.format("GET", path, headers) -end From d32a748e28f7fdb6a85e4f38beb9be44a070ea93 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 14 Mar 2024 17:34:28 +0000 Subject: [PATCH 0249/1297] docs: [#87] benchmarking How to run load tests using aquatic UDP load test commands. --- README.md | 4 + cSpell.json | 1 + docs/benchmarking.md | 252 ++++++++++++++++++ .../config/tracker.udp.benchmarking.toml | 37 +++ 4 files changed, 294 insertions(+) create mode 100644 docs/benchmarking.md create mode 100644 share/default/config/tracker.udp.benchmarking.toml diff --git a/README.md b/README.md index 18f3d361d..ea5078b19 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,10 @@ The following services are provided by the default configuration: - [Tracker (HTTP/TLS)][HTTP] - [Tracker (UDP)][UDP] +## Benchmarking + +- [Benchmarking](./docs/benchmarking.md) + ## Contributing We are happy to support and welcome new people to our project. Please consider our [contributor guide][guide.md].
diff --git a/cSpell.json b/cSpell.json index 646037e59..183ea31fb 100644 --- a/cSpell.json +++ b/cSpell.json @@ -50,6 +50,7 @@ "hexlify", "hlocalhost", "Hydranode", + "hyperthread", "Icelake", "imdl", "impls", diff --git a/docs/benchmarking.md b/docs/benchmarking.md new file mode 100644 index 000000000..8b455d4f9 --- /dev/null +++ b/docs/benchmarking.md @@ -0,0 +1,252 @@ +# Benchmarking + +We have two types of benchmarking: + +- E2E benchmarking running the service (HTTP or UDP tracker). +- Internal torrents repository benchmarking. + +## E2E benchmarking + +We are using the scripts provided by [aquatic](https://github.com/greatest-ape/aquatic). + +Installing both commands: + +```console +cargo install aquatic_udp_load_test +cargo install aquatic_http_load_test +``` + +### Run UDP load test + +Run the tracker with UDP service enabled on port 3000 and set log level to `error`. + +```toml +log_level = "error" + +[[udp_trackers]] +bind_address = "0.0.0.0:3000" +enabled = true +``` + +Run the load test with: + +```console +aquatic_udp_load_test +``` + +Output: + +```output +Starting client with config: Config { + server_address: 127.0.0.1:3000, + log_level: Error, + workers: 1, + duration: 0, + network: NetworkConfig { + multiple_client_ipv4s: true, + first_port: 45000, + poll_timeout: 276, + poll_event_capacity: 2877, + recv_buffer: 6000000, + }, + requests: RequestConfig { + number_of_torrents: 10000, + scrape_max_torrents: 50, + weight_connect: 0, + weight_announce: 100, + weight_scrape: 1, + torrent_gamma_shape: 0.2, + torrent_gamma_scale: 100.0, + peer_seeder_probability: 0.25, + additional_request_probability: 0.5, + }, +} + +Requests out: 32632.43/second +Responses in: 24239.33/second + - Connect responses: 7896.91 + - Announce responses: 16327.01 + - Scrape responses: 15.40 + - Error responses: 0.00 +Peers per announce response: 33.10 +``` + +### Run HTTP load test + +Run the tracker with UDP service enabled on port 3000 and set log level to `error`. + +```toml +[[udp_trackers]] +bind_address = "0.0.0.0:3000" +enabled = true +``` + +Run the load test with: + +```console +aquatic_http_load_test +``` + +Output: + +```output +Starting client with config: Config { + server_address: 127.0.0.1:3000, + log_level: Error, + num_workers: 1, + num_connections: 128, + connection_creation_interval_ms: 10, + url_suffix: "", + duration: 0, + keep_alive: true, + torrents: TorrentConfig { + number_of_torrents: 10000, + peer_seeder_probability: 0.25, + weight_announce: 5, + weight_scrape: 0, + torrent_gamma_shape: 0.2, + torrent_gamma_scale: 100.0, + }, + cpu_pinning: CpuPinningConfigDesc { + active: false, + direction: Descending, + hyperthread: System, + core_offset: 0, + }, +} +``` + +### Comparing UDP tracker with other Rust implementations + +#### Torrust UDP Tracker + +Running the tracker: + +```console +git@github.com:torrust/torrust-tracker.git +cd torrust-tracker +cargo build --release +TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" ./target/release/torrust-tracker +``` + +Running the test: `aquatic_udp_load_test`. + +```output +Requests out: 13075.56/second +Responses in: 12058.38/second + - Connect responses: 1017.18 + - Announce responses: 11035.00 + - Scrape responses: 6.20 + - Error responses: 0.00 +Peers per announce response: 41.13 +``` + +#### Aquatic UDP Tracker + +Running the tracker: + +```console +git clone git@github.com:greatest-ape/aquatic.git +cd aquatic +cargo build --release -p aquatic_udp +./target/release/aquatic_udp -c "aquatic-udp-config.toml" +./target/release/aquatic_udp -c "aquatic-udp-config.toml" +``` + +Running the test: `aquatic_udp_load_test`. + +```output +Requests out: 383873.14/second +Responses in: 383440.35/second + - Connect responses: 429.19 + - Announce responses: 379249.22 + - Scrape responses: 3761.93 + - Error responses: 0.00 +Peers per announce response: 15.33 +``` + +#### Torrust-Actix UDP Tracker + +Run the tracker with UDP service enabled on port 3000 and set log level to `error`. + +```toml +[[udp_trackers]] +bind_address = "0.0.0.0:3000" +enabled = true +``` + +```console +git clone https://github.com/Power2All/torrust-actix.git +cd torrust-actix +cargo build --release +./target/release/torrust-actix --create-config +./target/release/torrust-actix +``` + +Running the test: `aquatic_udp_load_test`. + +```output +Requests out: 3072.94/second +Responses in: 2395.15/second + - Connect responses: 556.79 + - Announce responses: 1821.16 + - Scrape responses: 17.20 + - Error responses: 0.00 +Peers per announce response: 133.88 +``` + +### Results + +Announce request per second: + +| Tracker | Announce | +|---------------|-----------| +| Aquatic | 379,249 | +| Torrust | 11,035 | +| Torrust-Actix | 1,821 | + +## Repository benchmarking + +You can run it with: + +```console +cargo run --release -p torrust-torrent-repository-benchmarks -- --threads 4 --sleep 0 --compare true +``` + +It tests the different implementation for the internal torrent storage. + +```output +tokio::sync::RwLock> +add_one_torrent: Avg/AdjAvg: (60ns, 59ns) +update_one_torrent_in_parallel: Avg/AdjAvg: (10.909457ms, 0ns) +add_multiple_torrents_in_parallel: Avg/AdjAvg: (13.88879ms, 0ns) +update_multiple_torrents_in_parallel: Avg/AdjAvg: (7.772484ms, 7.782535ms) + +std::sync::RwLock> +add_one_torrent: Avg/AdjAvg: (43ns, 39ns) +update_one_torrent_in_parallel: Avg/AdjAvg: (4.020937ms, 4.020937ms) +add_multiple_torrents_in_parallel: Avg/AdjAvg: (5.896177ms, 5.768448ms) +update_multiple_torrents_in_parallel: Avg/AdjAvg: (3.883823ms, 3.883823ms) + +std::sync::RwLock>>> +add_one_torrent: Avg/AdjAvg: (51ns, 49ns) +update_one_torrent_in_parallel: Avg/AdjAvg: (3.252314ms, 3.149109ms) +add_multiple_torrents_in_parallel: Avg/AdjAvg: (8.411094ms, 8.411094ms) +update_multiple_torrents_in_parallel: Avg/AdjAvg: (4.106086ms, 4.106086ms) + +tokio::sync::RwLock>>> +add_one_torrent: Avg/AdjAvg: (91ns, 90ns) +update_one_torrent_in_parallel: Avg/AdjAvg: (3.542378ms, 3.435695ms) +add_multiple_torrents_in_parallel: Avg/AdjAvg: (15.651172ms, 15.651172ms) +update_multiple_torrents_in_parallel: Avg/AdjAvg: (4.368189ms, 4.257572ms) + +tokio::sync::RwLock>>> +add_one_torrent: Avg/AdjAvg: (111ns, 109ns) +update_one_torrent_in_parallel: Avg/AdjAvg: (6.590677ms, 6.808535ms) +add_multiple_torrents_in_parallel: Avg/AdjAvg: (16.572217ms, 16.30488ms) +update_multiple_torrents_in_parallel: Avg/AdjAvg: (4.073221ms, 4.000122ms) +``` + +## Other considerations + +We are testing new repository implementations that allow concurrent writes. See . diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml new file mode 100644 index 000000000..182112803 --- /dev/null +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -0,0 +1,37 @@ +announce_interval = 120 +db_driver = "Sqlite3" +db_path = "./storage/tracker/lib/database/sqlite3.db" +external_ip = "0.0.0.0" +inactive_peer_cleanup_interval = 600 +log_level = "error" +max_peer_timeout = 900 +min_announce_interval = 120 +mode = "public" +on_reverse_proxy = false +persistent_torrent_completed_stat = false +remove_peerless_torrents = true +tracker_usage_statistics = true + +[[udp_trackers]] +bind_address = "0.0.0.0:3000" +enabled = true + +[[http_trackers]] +bind_address = "0.0.0.0:7070" +enabled = false +ssl_cert_path = "" +ssl_enabled = false +ssl_key_path = "" + +[http_api] +bind_address = "127.0.0.1:1212" +enabled = false +ssl_cert_path = "" +ssl_enabled = false +ssl_key_path = "" + +[http_api.access_tokens] +admin = "MyAccessToken" + +[health_check_api] +bind_address = "127.0.0.1:1313" From 45c77c33168dce1e5e8c01e82cde79dfd8842393 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 14 Mar 2024 19:37:33 +0000 Subject: [PATCH 0250/1297] fix: linter error, unused code --- src/console/clients/udp/responses.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/console/clients/udp/responses.rs b/src/console/clients/udp/responses.rs index 020c7a367..2fbc38f5f 100644 --- a/src/console/clients/udp/responses.rs +++ b/src/console/clients/udp/responses.rs @@ -68,13 +68,6 @@ impl From for ScrapeResponseDto { } } -#[derive(Serialize)] -struct Peer { - seeders: i32, - completed: i32, - leechers: i32, -} - #[derive(Serialize)] struct TorrentStats { seeders: i32, From 26215e8429b1eb69f9421220146372c5b26bacdc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 15 Mar 2024 10:20:06 +0000 Subject: [PATCH 0251/1297] docs: [#733] udpate benchmarking docs and results --- cSpell.json | 2 + docs/benchmarking.md | 239 ++++++++++-------- .../config/tracker.udp.benchmarking.toml | 2 +- 3 files changed, 132 insertions(+), 111 deletions(-) diff --git a/cSpell.json b/cSpell.json index 183ea31fb..297517980 100644 --- a/cSpell.json +++ b/cSpell.json @@ -91,6 +91,7 @@ "proot", "proto", "Quickstart", + "Radeon", "Rasterbar", "realpath", "reannounce", @@ -107,6 +108,7 @@ "RUSTFLAGS", "rustfmt", "Rustls", + "Ryzen", "Seedable", "serde", "Shareaza", diff --git a/docs/benchmarking.md b/docs/benchmarking.md index 8b455d4f9..7c82df14c 100644 --- a/docs/benchmarking.md +++ b/docs/benchmarking.md @@ -2,145 +2,124 @@ We have two types of benchmarking: -- E2E benchmarking running the service (HTTP or UDP tracker). +- E2E benchmarking running the UDP tracker. - Internal torrents repository benchmarking. ## E2E benchmarking We are using the scripts provided by [aquatic](https://github.com/greatest-ape/aquatic). -Installing both commands: +How to install both commands: ```console -cargo install aquatic_udp_load_test -cargo install aquatic_http_load_test +cargo install aquatic_udp_load_test && cargo install aquatic_http_load_test +``` + +You can also clone and build the repos. It's the way used for the results shown +in this documentation. + +```console +git clone git@github.com:greatest-ape/aquatic.git +cd aquatic +cargo build --release -p aquatic_udp_load_test ``` ### Run UDP load test -Run the tracker with UDP service enabled on port 3000 and set log level to `error`. +Run the tracker with UDP service enabled and other services disabled and set log level to `error`. ```toml log_level = "error" [[udp_trackers]] -bind_address = "0.0.0.0:3000" enabled = true ``` +Build and run the tracker: + +```console +cargo build --release +TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" ./target/release/torrust-tracker +``` + Run the load test with: ```console -aquatic_udp_load_test +./target/release/aquatic_udp_load_test ``` +> NOTICE: You need to modify the port in the `udp_load_test` crate to use `6969` and rebuild. + Output: ```output Starting client with config: Config { - server_address: 127.0.0.1:3000, + server_address: 127.0.0.1:6969, log_level: Error, workers: 1, duration: 0, + summarize_last: 0, + extra_statistics: true, network: NetworkConfig { multiple_client_ipv4s: true, - first_port: 45000, - poll_timeout: 276, - poll_event_capacity: 2877, - recv_buffer: 6000000, + sockets_per_worker: 4, + recv_buffer: 8000000, }, requests: RequestConfig { - number_of_torrents: 10000, - scrape_max_torrents: 50, - weight_connect: 0, - weight_announce: 100, + number_of_torrents: 1000000, + number_of_peers: 2000000, + scrape_max_torrents: 10, + announce_peers_wanted: 30, + weight_connect: 50, + weight_announce: 50, weight_scrape: 1, - torrent_gamma_shape: 0.2, - torrent_gamma_scale: 100.0, - peer_seeder_probability: 0.25, - additional_request_probability: 0.5, + peer_seeder_probability: 0.75, }, } -Requests out: 32632.43/second -Responses in: 24239.33/second - - Connect responses: 7896.91 - - Announce responses: 16327.01 - - Scrape responses: 15.40 +Requests out: 398367.11/second +Responses in: 358530.40/second + - Connect responses: 177567.60 + - Announce responses: 177508.08 + - Scrape responses: 3454.72 - Error responses: 0.00 -Peers per announce response: 33.10 +Peers per announce response: 0.00 +Announce responses per info hash: + - p10: 1 + - p25: 1 + - p50: 1 + - p75: 1 + - p90: 2 + - p95: 3 + - p99: 105 + - p99.9: 289 + - p100: 361 ``` -### Run HTTP load test - -Run the tracker with UDP service enabled on port 3000 and set log level to `error`. - -```toml -[[udp_trackers]] -bind_address = "0.0.0.0:3000" -enabled = true -``` - -Run the load test with: - -```console -aquatic_http_load_test -``` - -Output: +> IMPORTANT: The performance of th Torrust UDP Tracker is drastically decreased with these log levels: `info`, `debug`, `trace`. ```output -Starting client with config: Config { - server_address: 127.0.0.1:3000, - log_level: Error, - num_workers: 1, - num_connections: 128, - connection_creation_interval_ms: 10, - url_suffix: "", - duration: 0, - keep_alive: true, - torrents: TorrentConfig { - number_of_torrents: 10000, - peer_seeder_probability: 0.25, - weight_announce: 5, - weight_scrape: 0, - torrent_gamma_shape: 0.2, - torrent_gamma_scale: 100.0, - }, - cpu_pinning: CpuPinningConfigDesc { - active: false, - direction: Descending, - hyperthread: System, - core_offset: 0, - }, -} +Requests out: 40719.21/second +Responses in: 33762.72/second + - Connect responses: 16732.76 + - Announce responses: 16692.98 + - Scrape responses: 336.98 + - Error responses: 0.00 +Peers per announce response: 0.00 +Announce responses per info hash: + - p10: 1 + - p25: 1 + - p50: 1 + - p75: 1 + - p90: 7 + - p95: 14 + - p99: 27 + - p99.9: 35 + - p100: 45 ``` ### Comparing UDP tracker with other Rust implementations -#### Torrust UDP Tracker - -Running the tracker: - -```console -git@github.com:torrust/torrust-tracker.git -cd torrust-tracker -cargo build --release -TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" ./target/release/torrust-tracker -``` - -Running the test: `aquatic_udp_load_test`. - -```output -Requests out: 13075.56/second -Responses in: 12058.38/second - - Connect responses: 1017.18 - - Announce responses: 11035.00 - - Scrape responses: 6.20 - - Error responses: 0.00 -Peers per announce response: 41.13 -``` - #### Aquatic UDP Tracker Running the tracker: @@ -149,29 +128,44 @@ Running the tracker: git clone git@github.com:greatest-ape/aquatic.git cd aquatic cargo build --release -p aquatic_udp -./target/release/aquatic_udp -c "aquatic-udp-config.toml" +./target/release/aquatic_udp -p > "aquatic-udp-config.toml" ./target/release/aquatic_udp -c "aquatic-udp-config.toml" ``` -Running the test: `aquatic_udp_load_test`. +Run the load test with: + +```console +./target/release/aquatic_udp_load_test +``` ```output -Requests out: 383873.14/second -Responses in: 383440.35/second - - Connect responses: 429.19 - - Announce responses: 379249.22 - - Scrape responses: 3761.93 +Requests out: 432896.42/second +Responses in: 389577.70/second + - Connect responses: 192864.02 + - Announce responses: 192817.55 + - Scrape responses: 3896.13 - Error responses: 0.00 -Peers per announce response: 15.33 +Peers per announce response: 21.55 +Announce responses per info hash: + - p10: 1 + - p25: 1 + - p50: 1 + - p75: 1 + - p90: 2 + - p95: 3 + - p99: 105 + - p99.9: 311 + - p100: 395 ``` #### Torrust-Actix UDP Tracker -Run the tracker with UDP service enabled on port 3000 and set log level to `error`. +Run the tracker with UDP service enabled and other services disabled and set log level to `error`. ```toml +log_level = "error" + [[udp_trackers]] -bind_address = "0.0.0.0:3000" enabled = true ``` @@ -183,16 +177,32 @@ cargo build --release ./target/release/torrust-actix ``` -Running the test: `aquatic_udp_load_test`. +Run the load test with: + +```console +./target/release/aquatic_udp_load_test +``` + +> NOTICE: You need to modify the port in the `udp_load_test` crate to use `6969` and rebuild. ```output -Requests out: 3072.94/second -Responses in: 2395.15/second - - Connect responses: 556.79 - - Announce responses: 1821.16 - - Scrape responses: 17.20 +Requests out: 200953.97/second +Responses in: 180858.14/second + - Connect responses: 89517.13 + - Announce responses: 89539.67 + - Scrape responses: 1801.34 - Error responses: 0.00 -Peers per announce response: 133.88 +Peers per announce response: 1.00 +Announce responses per info hash: + - p10: 1 + - p25: 1 + - p50: 1 + - p75: 1 + - p90: 2 + - p95: 7 + - p99: 87 + - p99.9: 155 + - p100: 188 ``` ### Results @@ -201,9 +211,18 @@ Announce request per second: | Tracker | Announce | |---------------|-----------| -| Aquatic | 379,249 | -| Torrust | 11,035 | -| Torrust-Actix | 1,821 | +| Aquatic | 192,817 | +| Torrust | 177,508 | +| Torrust-Actix | 89,539 | + +Using a PC with: + +- RAM: 64GiB +- Processor: AMD Ryzen 9 7950X x 32 +- Graphics: AMD Radeon Graphics / Intel Arc A770 Graphics (DG2) +- OS: Ubuntu 23.04 +- OS Type: 64-bit +- Kernel Version: Linux 6.2.0-20-generic ## Repository benchmarking diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml index 182112803..080c67e84 100644 --- a/share/default/config/tracker.udp.benchmarking.toml +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -13,7 +13,7 @@ remove_peerless_torrents = true tracker_usage_statistics = true [[udp_trackers]] -bind_address = "0.0.0.0:3000" +bind_address = "0.0.0.0:6969" enabled = true [[http_trackers]] From b3ad652ac0782fccc149eabb0ed82e4a72227d2d Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 16 Mar 2024 04:20:17 +0800 Subject: [PATCH 0252/1297] chore: update cargo deps Updating crates.io index Updating ahash v0.8.9 -> v0.8.11 Updating anstream v0.6.12 -> v0.6.13 Updating anyhow v1.0.80 -> v1.0.81 Updating arc-swap v1.6.0 -> v1.7.0 Updating axum-client-ip v0.5.0 -> v0.5.1 Updating bumpalo v3.15.3 -> v3.15.4 Updating cc v1.0.88 -> v1.0.90 Updating chrono v0.4.34 -> v0.4.35 Updating clap v4.5.1 -> v4.5.3 Updating clap_builder v4.5.1 -> v4.5.2 Updating clap_derive v4.5.0 -> v4.5.3 Updating const-random v0.1.17 -> v0.1.18 Updating crossbeam-channel v0.5.11 -> v0.5.12 Removing h2 v0.3.24 Removing h2 v0.4.2 Adding h2 v0.3.25 (latest: v0.4.3) Adding h2 v0.4.3 Adding heck v0.5.0 Updating hermit-abi v0.3.8 -> v0.3.9 Removing http v0.2.11 Removing http v1.0.0 Adding http v0.2.12 (latest: v1.1.0) Adding http v1.1.0 Updating http-body-util v0.1.0 -> v0.1.1 Updating indexmap v2.2.3 -> v2.2.5 Adding jobserver v0.1.28 Updating js-sys v0.3.68 -> v0.3.69 Updating libloading v0.8.1 -> v0.8.3 Updating log v0.4.20 -> v0.4.21 Updating mio v0.8.10 -> v0.8.11 Updating pest v2.7.7 -> v2.7.8 Updating pest_derive v2.7.7 -> v2.7.8 Updating pest_generator v2.7.7 -> v2.7.8 Updating pest_meta v2.7.7 -> v2.7.8 Updating pin-project v1.1.4 -> v1.1.5 Updating pin-project-internal v1.1.4 -> v1.1.5 Updating proc-macro2 v1.0.78 -> v1.0.79 Updating rayon v1.8.1 -> v1.9.0 Updating regex-automata v0.4.5 -> v0.4.6 Updating reqwest v0.11.24 -> v0.11.26 Updating rustls-pemfile v2.1.0 -> v2.1.1 Updating serde_path_to_error v0.1.15 -> v0.1.16 Updating serde_with v3.6.1 -> v3.7.0 Updating serde_with_macros v3.6.1 -> v3.7.0 Updating syn v2.0.51 -> v2.0.52 Updating thiserror v1.0.57 -> v1.0.58 Updating thiserror-impl v1.0.57 -> v1.0.58 Updating toml v0.8.10 -> v0.8.11 Updating toml_edit v0.22.6 -> v0.22.7 Updating walkdir v2.4.0 -> v2.5.0 Updating wasm-bindgen v0.2.91 -> v0.2.92 Updating wasm-bindgen-backend v0.2.91 -> v0.2.92 Updating wasm-bindgen-futures v0.4.41 -> v0.4.42 Updating wasm-bindgen-macro v0.2.91 -> v0.2.92 Updating wasm-bindgen-macro-support v0.2.91 -> v0.2.92 Updating wasm-bindgen-shared v0.2.91 -> v0.2.92 Updating web-sys v0.3.68 -> v0.3.69 Updating windows-targets v0.52.3 -> v0.52.4 Updating windows_aarch64_gnullvm v0.52.3 -> v0.52.4 Updating windows_aarch64_msvc v0.52.3 -> v0.52.4 Updating windows_i686_gnu v0.52.3 -> v0.52.4 Updating windows_i686_msvc v0.52.3 -> v0.52.4 Updating windows_x86_64_gnu v0.52.3 -> v0.52.4 Updating windows_x86_64_gnullvm v0.52.3 -> v0.52.4 Updating windows_x86_64_msvc v0.52.3 -> v0.52.4 Updating winnow v0.6.2 -> v0.6.5 --- Cargo.lock | 398 +++++++++++++++++++++------------------- src/shared/clock/mod.rs | 19 +- 2 files changed, 215 insertions(+), 202 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9bc13c1a7..4cc81979d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -30,9 +30,9 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.9" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d713b3834d76b85304d4d525563c1276e2e30dc97cc67bfb4585a4a29fc2c89f" +checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" dependencies = [ "cfg-if", "once_cell", @@ -93,9 +93,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.12" +version = "0.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96b09b5178381e0874812a9b157f7fe84982617e48f71f4e3235482775e5b540" +checksum = "d96bd03f33fe50a863e394ee9718a706f988b9079b20c3784fb726e7678b62fb" dependencies = [ "anstyle", "anstyle-parse", @@ -141,9 +141,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.80" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ad32ce52e4161730f7098c077cd2ed6229b5804ccf99e5366be1ab72a98b4e1" +checksum = "0952808a6c2afd1aa8947271f3a60f1a6763c7b912d210184c5149b5cf147247" [[package]] name = "aquatic_udp_protocol" @@ -157,9 +157,9 @@ dependencies = [ [[package]] name = "arc-swap" -version = "1.6.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bddcadddf5e9015d310179a59bb28c4d4b9920ad0f11e8e14dbadf654890c9a6" +checksum = "7b3d0060af21e8d11a926981cc00c6c1541aa91dd64b9f881985c3da1094425f" [[package]] name = "arrayvec" @@ -191,7 +191,7 @@ checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -211,7 +211,7 @@ dependencies = [ "axum-macros", "bytes", "futures-util", - "http 1.0.0", + "http 1.1.0", "http-body 1.0.0", "http-body-util", "hyper 1.2.0", @@ -237,9 +237,9 @@ dependencies = [ [[package]] name = "axum-client-ip" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f5ffe4637708b326c621d5494ab6c91dcf62ee440fa6ee967d289315a9c6f81" +checksum = "5e7c467bdcd2bd982ce5c8742a1a178aba7b03db399fd18f5d5d438f5aa91cb4" dependencies = [ "axum", "forwarded-header-value", @@ -255,7 +255,7 @@ dependencies = [ "async-trait", "bytes", "futures-util", - "http 1.0.0", + "http 1.1.0", "http-body 1.0.0", "http-body-util", "mime", @@ -277,7 +277,7 @@ dependencies = [ "axum-core", "bytes", "futures-util", - "http 1.0.0", + "http 1.1.0", "http-body 1.0.0", "http-body-util", "mime", @@ -295,10 +295,10 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00c055ee2d014ae5981ce1016374e8213682aa14d9bf40e48ab48b5f3ef20eaa" dependencies = [ - "heck", + "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -310,14 +310,14 @@ dependencies = [ "arc-swap", "bytes", "futures-util", - "http 1.0.0", + "http 1.1.0", "http-body 1.0.0", "http-body-util", "hyper 1.2.0", "hyper-util", "pin-project-lite", "rustls", - "rustls-pemfile 2.1.0", + "rustls-pemfile 2.1.1", "tokio", "tokio-rustls", "tower", @@ -379,7 +379,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -438,7 +438,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", "syn_derive", ] @@ -471,9 +471,9 @@ checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" [[package]] name = "bumpalo" -version = "3.15.3" +version = "3.15.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ea184aa71bb362a1157c896979544cc23974e08fd265f29ea96b59f0b4a555b" +checksum = "7ff69b9dd49fd426c69a0db9fc04dd934cdb6645ff000864d98f7e2af8830eaa" [[package]] name = "bytecheck" @@ -517,10 +517,11 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.0.88" +version = "1.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02f341c093d19155a6e41631ce5971aac4e9a868262212153124c15fa22d1cdc" +checksum = "8cd6604a82acf3039f1144f54b8eb34e91ffba622051189e71b781822d5ee1f5" dependencies = [ + "jobserver", "libc", ] @@ -547,15 +548,15 @@ checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" [[package]] name = "chrono" -version = "0.4.34" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bc015644b92d5890fab7489e49d21f879d5c990186827d42ec511919404f38b" +checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a" dependencies = [ "android-tzdata", "iana-time-zone", "num-traits", "serde", - "windows-targets 0.52.3", + "windows-targets 0.52.4", ] [[package]] @@ -598,9 +599,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.1" +version = "4.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c918d541ef2913577a0f9566e9ce27cb35b6df072075769e0b26cb5a554520da" +checksum = "949626d00e063efc93b6dca932419ceb5432f99769911c0b995f7e884c778813" dependencies = [ "clap_builder", "clap_derive", @@ -608,9 +609,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.1" +version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f3e7391dad68afb0c2ede1bf619f579a3dc9c2ec67f089baa397123a2f3d1eb" +checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" dependencies = [ "anstream", "anstyle", @@ -620,14 +621,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.0" +version = "4.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "307bc0538d5f0f83b8248db3087aa92fe504e4691294d0c96c0eabc33f47ba47" +checksum = "90239a040c80f5e14809ca132ddc4176ab33d5e17e49691793296e3fcb34d72f" dependencies = [ - "heck", + "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -683,9 +684,9 @@ dependencies = [ [[package]] name = "const-random" -version = "0.1.17" +version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aaf16c9c2c612020bcfd042e170f6e32de9b9d75adb5277cdbbd2e2c8c8299a" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" dependencies = [ "const-random-macro", ] @@ -803,9 +804,9 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.11" +version = "0.5.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "176dc175b78f56c0f321911d9c8eb2b77a78a4860b9c19db83835fea1a46649b" +checksum = "ab3db02a9c5b5121e1e42fbdb1aeb65f5e02624cc58c43f2884c6ccac0b82f95" dependencies = [ "crossbeam-utils", ] @@ -881,7 +882,7 @@ dependencies = [ "proc-macro2", "quote", "strsim 0.10.0", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -892,7 +893,7 @@ checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" dependencies = [ "darling_core", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -926,7 +927,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -1104,7 +1105,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -1116,7 +1117,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -1128,7 +1129,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -1193,7 +1194,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -1261,17 +1262,17 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "h2" -version = "0.3.24" +version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb2c4422095b67ee78da96fbb51a4cc413b3b25883c7717ff7ca1ab31022c9c9" +checksum = "4fbd2820c5e49886948654ab546d0688ff24530286bdcf8fca3cefb16d4618eb" dependencies = [ "bytes", "fnv", "futures-core", "futures-sink", "futures-util", - "http 0.2.11", - "indexmap 2.2.3", + "http 0.2.12", + "indexmap 2.2.5", "slab", "tokio", "tokio-util", @@ -1280,17 +1281,17 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31d030e59af851932b72ceebadf4a2b5986dba4c3b99dd2493f8273a0f151943" +checksum = "51ee2dd2e4f378392eeff5d51618cd9a63166a2513846bbc55f21cfacd9199d4" dependencies = [ "bytes", "fnv", "futures-core", "futures-sink", "futures-util", - "http 1.0.0", - "indexmap 2.2.3", + "http 1.1.0", + "indexmap 2.2.5", "slab", "tokio", "tokio-util", @@ -1322,7 +1323,7 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" dependencies = [ - "ahash 0.8.9", + "ahash 0.8.11", ] [[package]] @@ -1331,7 +1332,7 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" dependencies = [ - "ahash 0.8.9", + "ahash 0.8.11", "allocator-api2", ] @@ -1350,11 +1351,17 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hermit-abi" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "379dada1584ad501b383485dd706b8afb7a70fcbc7f4da7d780638a5a6124a60" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" [[package]] name = "hex" @@ -1370,9 +1377,9 @@ checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" [[package]] name = "http" -version = "0.2.11" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8947b1a6fad4393052c7ba1f4cd97bed3e953a95c79c92ad9b051a04611d9fbb" +checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" dependencies = [ "bytes", "fnv", @@ -1381,9 +1388,9 @@ dependencies = [ [[package]] name = "http" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b32afd38673a8016f7c9ae69e5af41a58f81b1d31689040f2f1959594ce194ea" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" dependencies = [ "bytes", "fnv", @@ -1397,7 +1404,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" dependencies = [ "bytes", - "http 0.2.11", + "http 0.2.12", "pin-project-lite", ] @@ -1408,18 +1415,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" dependencies = [ "bytes", - "http 1.0.0", + "http 1.1.0", ] [[package]] name = "http-body-util" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41cb79eb393015dadd30fc252023adb0b2400a0caee0fa2a077e6e21a551e840" +checksum = "0475f8b2ac86659c21b64320d5d653f9efe42acd2a4e560073ec61a155a34f1d" dependencies = [ "bytes", - "futures-util", - "http 1.0.0", + "futures-core", + "http 1.1.0", "http-body 1.0.0", "pin-project-lite", ] @@ -1446,8 +1453,8 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "h2 0.3.24", - "http 0.2.11", + "h2 0.3.25", + "http 0.2.12", "http-body 0.4.6", "httparse", "httpdate", @@ -1469,8 +1476,8 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "h2 0.4.2", - "http 1.0.0", + "h2 0.4.3", + "http 1.1.0", "http-body 1.0.0", "httparse", "httpdate", @@ -1501,7 +1508,7 @@ checksum = "ca38ef113da30126bbff9cd1705f9273e15d45498615d138b0c20279ac7a76aa" dependencies = [ "bytes", "futures-util", - "http 1.0.0", + "http 1.1.0", "http-body 1.0.0", "hyper 1.2.0", "pin-project-lite", @@ -1561,9 +1568,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.2.3" +version = "2.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "233cf39063f058ea2caae4091bf4a3ef70a653afbc026f5c4a4135d114e3c177" +checksum = "7b0b929d511467233429c45a44ac1dcaa21ba0f5ba11e4879e6ed28ddb4f9df4" dependencies = [ "equivalent", "hashbrown 0.14.3", @@ -1620,11 +1627,20 @@ version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" +[[package]] +name = "jobserver" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab46a6e9526ddef3ae7f787c06f0f2600639ba80ea3eade3d8e670a2230f51d6" +dependencies = [ + "libc", +] + [[package]] name = "js-sys" -version = "0.3.68" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "406cda4b368d531c842222cf9d2600a9a4acce8d29423695379c6868a143a9ee" +checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" dependencies = [ "wasm-bindgen", ] @@ -1733,12 +1749,12 @@ checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" [[package]] name = "libloading" -version = "0.8.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c571b676ddfc9a8c12f1f3d3085a7b163966a8fd8098a90640953ce5f6170161" +checksum = "0c2a198fb6b0eada2a8df47933734e6d35d350665a33a3593d7164fa52c75c19" dependencies = [ "cfg-if", - "windows-sys 0.48.0", + "windows-targets 0.52.4", ] [[package]] @@ -1799,9 +1815,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.20" +version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" [[package]] name = "lru" @@ -1847,9 +1863,9 @@ dependencies = [ [[package]] name = "mio" -version = "0.8.10" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f3d0b296e374a4e6f3c7b0a1f5a51d748a0d34c85e7dc48fc3fa9a87657fe09" +checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" dependencies = [ "libc", "wasi", @@ -1880,7 +1896,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -1925,13 +1941,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56b0d8a0db9bf6d2213e11f2c701cb91387b0614361625ab7b9743b41aa4938f" dependencies = [ "darling", - "heck", + "heck 0.4.1", "num-bigint", "proc-macro-crate 1.3.1", "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", "termcolor", "thiserror", ] @@ -2131,7 +2147,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -2219,9 +2235,9 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.7" +version = "2.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "219c0dcc30b6a27553f9cc242972b67f75b60eb0db71f0b5462f38b058c41546" +checksum = "56f8023d0fb78c8e03784ea1c7f3fa36e68a723138990b8d5a47d916b651e7a8" dependencies = [ "memchr", "thiserror", @@ -2230,9 +2246,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.7" +version = "2.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e1288dbd7786462961e69bfd4df7848c1e37e8b74303dbdab82c3a9cdd2809" +checksum = "b0d24f72393fd16ab6ac5738bc33cdb6a9aa73f8b902e8fe29cf4e67d7dd1026" dependencies = [ "pest", "pest_generator", @@ -2240,22 +2256,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.7" +version = "2.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1381c29a877c6d34b8c176e734f35d7f7f5b3adaefe940cb4d1bb7af94678e2e" +checksum = "fdc17e2a6c7d0a492f0158d7a4bd66cc17280308bbaff78d5bef566dca35ab80" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] name = "pest_meta" -version = "2.7.7" +version = "2.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0934d6907f148c22a3acbda520c7eed243ad7487a30f51f6ce52b58b7077a8a" +checksum = "934cd7631c050f4674352a6e835d5f6711ffbfb9345c2fc0107155ac495ae293" dependencies = [ "once_cell", "pest", @@ -2302,22 +2318,22 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0302c4a0442c456bd56f841aee5c3bfd17967563f6fadc9ceb9f9c23cf3807e0" +checksum = "b6bf43b791c5b9e34c3d182969b4abb522f9343702850a2e57f460d00d09b4b3" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "266c042b60c9c76b8d53061e52b2e0d1116abc57cefc8c5cd671619a56ac3690" +checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -2449,9 +2465,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.78" +version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae" +checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" dependencies = [ "unicode-ident", ] @@ -2555,9 +2571,9 @@ dependencies = [ [[package]] name = "rayon" -version = "1.8.1" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7237101a77a10773db45d62004a272517633fbcc3df19d96455ede1122e051" +checksum = "e4963ed1bc86e4f3ee217022bd855b297cef07fb9eac5dfa1f788b220b49b3bd" dependencies = [ "either", "rayon-core", @@ -2596,9 +2612,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bb987efffd3c6d0d8f5f89510bb458559eab11e4f869acb20bf845e016259cd" +checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" dependencies = [ "aho-corasick", "memchr", @@ -2622,17 +2638,17 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.11.24" +version = "0.11.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6920094eb85afde5e4a138be3f2de8bbdf28000f0029e72c45025a56b042251" +checksum = "78bf93c4af7a8bb7d879d51cebe797356ff10ae8516ace542b5182d9dcac10b2" dependencies = [ "base64", "bytes", "encoding_rs", "futures-core", "futures-util", - "h2 0.3.24", - "http 0.2.11", + "h2 0.3.25", + "http 0.2.12", "http-body 0.4.6", "hyper 0.14.28", "hyper-tls", @@ -2822,9 +2838,9 @@ dependencies = [ [[package]] name = "rustls-pemfile" -version = "2.1.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c333bb734fcdedcea57de1602543590f545f127dc8b533324318fd492c5c70b" +checksum = "f48172685e6ff52a556baa527774f61fcaa884f59daf3375c62a3f1cd2549dab" dependencies = [ "base64", "rustls-pki-types", @@ -2978,7 +2994,7 @@ checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -2988,7 +3004,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50437e6a58912eecc08865e35ea2e8d365fbb2db0debb1c8bb43bf1faf055f25" dependencies = [ "form_urlencoded", - "indexmap 2.2.3", + "indexmap 2.2.5", "itoa", "ryu", "serde", @@ -3007,9 +3023,9 @@ dependencies = [ [[package]] name = "serde_path_to_error" -version = "0.1.15" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebd154a240de39fdebcf5775d2675c204d7c13cf39a4c697be6493c8e734337c" +checksum = "af99884400da37c88f5e9146b7f1fd0fbcae8f6eec4e9da38b67d05486f814a6" dependencies = [ "itoa", "serde", @@ -3023,7 +3039,7 @@ checksum = "0b2e6b945e9d3df726b65d6ee24060aff8e3533d431f677a9695db04eff9dfdb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -3049,15 +3065,15 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.6.1" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15d167997bd841ec232f5b2b8e0e26606df2e7caa4c31b95ea9ca52b200bd270" +checksum = "ee80b0e361bbf88fd2f6e242ccd19cfda072cb0faa6ae694ecee08199938569a" dependencies = [ "base64", "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.2.3", + "indexmap 2.2.5", "serde", "serde_derive", "serde_json", @@ -3067,14 +3083,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.6.1" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "865f9743393e638991566a8b7a479043c2c8da94a33e0a31f18214c9cae0a64d" +checksum = "6561dc161a9224638a31d876ccdfefbc1df91d3f3a8342eddb35f055d48c7655" dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -3198,9 +3214,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.51" +version = "2.0.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ab617d94515e94ae53b8406c628598680aa0c9587474ecbe58188f7b345d66c" +checksum = "b699d15b36d1f02c3e7c69f8ffef53de37aefae075d8488d4ba1a7788d574a07" dependencies = [ "proc-macro2", "quote", @@ -3216,7 +3232,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -3298,22 +3314,22 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.57" +version = "1.0.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e45bcbe8ed29775f228095caf2cd67af7a4ccf756ebff23a306bf3e8b47b24b" +checksum = "03468839009160513471e86a034bb2c5c0e4baae3b43f79ffc55c4a5427b3297" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.57" +version = "1.0.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81" +checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -3407,7 +3423,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -3446,14 +3462,14 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.10" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a9aad4a3066010876e8dcf5a8a06e70a558751117a145c6ce2b82c2e2054290" +checksum = "af06656561d28735e9c1cd63dfd57132c8155426aa6af24f36a00a351f88c48e" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.6", + "toml_edit 0.22.7", ] [[package]] @@ -3471,7 +3487,7 @@ version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ - "indexmap 2.2.3", + "indexmap 2.2.5", "toml_datetime", "winnow 0.5.40", ] @@ -3482,22 +3498,22 @@ version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8534fd7f78b5405e860340ad6575217ce99f38d4d5c8f2442cb5ecb50090e1" dependencies = [ - "indexmap 2.2.3", + "indexmap 2.2.5", "toml_datetime", "winnow 0.5.40", ] [[package]] name = "toml_edit" -version = "0.22.6" +version = "0.22.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c1b5fd4128cc8d3e0cb74d4ed9a9cc7c7284becd4df68f5f940e1ad123606f6" +checksum = "18769cd1cec395d70860ceb4d932812a0b4d06b1a4bb336745a4d21b9496e992" dependencies = [ - "indexmap 2.2.3", + "indexmap 2.2.5", "serde", "serde_spanned", "toml_datetime", - "winnow 0.6.2", + "winnow 0.6.5", ] [[package]] @@ -3647,7 +3663,7 @@ dependencies = [ "bitflags 2.4.2", "bytes", "futures-core", - "http 1.0.0", + "http 1.1.0", "http-body 1.0.0", "http-body-util", "pin-project-lite", @@ -3702,7 +3718,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] @@ -3817,9 +3833,9 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "walkdir" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" dependencies = [ "same-file", "winapi-util", @@ -3842,9 +3858,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.91" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1e124130aee3fb58c5bdd6b639a0509486b0338acaaae0c84a5124b0f588b7f" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -3852,24 +3868,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.91" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9e7e1900c352b609c8488ad12639a311045f40a35491fb69ba8c12f758af70b" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.41" +version = "0.4.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877b9c3f61ceea0e56331985743b13f3d25c406a7098d45180fb5f09bc19ed97" +checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0" dependencies = [ "cfg-if", "js-sys", @@ -3879,9 +3895,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.91" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b30af9e2d358182b5c7449424f017eba305ed32a7010509ede96cdc4696c46ed" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3889,28 +3905,28 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.91" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "642f325be6301eb8107a83d12a8ac6c1e1c54345a7ef1a9261962dfefda09e66" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.91" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f186bd2dcf04330886ce82d6f33dd75a7bfcf69ecf5763b89fcde53b6ac9838" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" [[package]] name = "web-sys" -version = "0.3.68" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96565907687f7aceb35bc5fc03770a8a0471d82e479f25832f54a0e3f4b28446" +checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" dependencies = [ "js-sys", "wasm-bindgen", @@ -3953,7 +3969,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ - "windows-targets 0.52.3", + "windows-targets 0.52.4", ] [[package]] @@ -3971,7 +3987,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.3", + "windows-targets 0.52.4", ] [[package]] @@ -3991,17 +4007,17 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.3" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d380ba1dc7187569a8a9e91ed34b8ccfc33123bbacb8c0aed2d1ad7f3ef2dc5f" +checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b" dependencies = [ - "windows_aarch64_gnullvm 0.52.3", - "windows_aarch64_msvc 0.52.3", - "windows_i686_gnu 0.52.3", - "windows_i686_msvc 0.52.3", - "windows_x86_64_gnu 0.52.3", - "windows_x86_64_gnullvm 0.52.3", - "windows_x86_64_msvc 0.52.3", + "windows_aarch64_gnullvm 0.52.4", + "windows_aarch64_msvc 0.52.4", + "windows_i686_gnu 0.52.4", + "windows_i686_msvc 0.52.4", + "windows_x86_64_gnu 0.52.4", + "windows_x86_64_gnullvm 0.52.4", + "windows_x86_64_msvc 0.52.4", ] [[package]] @@ -4012,9 +4028,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.3" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68e5dcfb9413f53afd9c8f86e56a7b4d86d9a2fa26090ea2dc9e40fba56c6ec6" +checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9" [[package]] name = "windows_aarch64_msvc" @@ -4024,9 +4040,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.52.3" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dab469ebbc45798319e69eebf92308e541ce46760b49b18c6b3fe5e8965b30f" +checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675" [[package]] name = "windows_i686_gnu" @@ -4036,9 +4052,9 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.52.3" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a4e9b6a7cac734a8b4138a4e1044eac3404d8326b6c0f939276560687a033fb" +checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3" [[package]] name = "windows_i686_msvc" @@ -4048,9 +4064,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.52.3" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b0ec9c422ca95ff34a78755cfa6ad4a51371da2a5ace67500cf7ca5f232c58" +checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02" [[package]] name = "windows_x86_64_gnu" @@ -4060,9 +4076,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.52.3" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "704131571ba93e89d7cd43482277d6632589b18ecf4468f591fbae0a8b101614" +checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03" [[package]] name = "windows_x86_64_gnullvm" @@ -4072,9 +4088,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.3" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42079295511643151e98d61c38c0acc444e52dd42ab456f7ccfd5152e8ecf21c" +checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177" [[package]] name = "windows_x86_64_msvc" @@ -4084,9 +4100,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.52.3" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0770833d60a970638e989b3fa9fd2bb1aaadcf88963d1659fd7d9990196ed2d6" +checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" [[package]] name = "winnow" @@ -4099,9 +4115,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.6.2" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a4191c47f15cc3ec71fcb4913cb83d58def65dd3787610213c649283b5ce178" +checksum = "dffa400e67ed5a4dd237983829e66475f0a4a26938c4b04c21baede6262215b8" dependencies = [ "memchr", ] @@ -4151,7 +4167,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.51", + "syn 2.0.52", ] [[package]] diff --git a/src/shared/clock/mod.rs b/src/shared/clock/mod.rs index 922ca3200..6d9d4112a 100644 --- a/src/shared/clock/mod.rs +++ b/src/shared/clock/mod.rs @@ -30,7 +30,7 @@ use std::num::IntErrorKind; use std::str::FromStr; use std::time::Duration; -use chrono::{DateTime, NaiveDateTime, Utc}; +use chrono::{DateTime, Utc}; /// Duration since the Unix Epoch. pub type DurationSinceUnixEpoch = Duration; @@ -120,14 +120,11 @@ pub fn convert_from_datetime_utc_to_timestamp(datetime_utc: &DateTime) -> D /// (this will naturally happen in 292.5 billion years) #[must_use] pub fn convert_from_timestamp_to_datetime_utc(duration: DurationSinceUnixEpoch) -> DateTime { - DateTime::::from_naive_utc_and_offset( - NaiveDateTime::from_timestamp_opt( - i64::try_from(duration.as_secs()).expect("Overflow of i64 seconds, very future!"), - duration.subsec_nanos(), - ) - .unwrap(), - Utc, + DateTime::from_timestamp( + i64::try_from(duration.as_secs()).expect("Overflow of i64 seconds, very future!"), + duration.subsec_nanos(), ) + .unwrap() } #[cfg(test)] @@ -150,7 +147,7 @@ mod tests { } mod timestamp { - use chrono::{DateTime, NaiveDateTime, Utc}; + use chrono::DateTime; use crate::shared::clock::{ convert_from_datetime_utc_to_timestamp, convert_from_iso_8601_to_timestamp, convert_from_timestamp_to_datetime_utc, @@ -162,13 +159,13 @@ mod tests { let timestamp = DurationSinceUnixEpoch::ZERO; assert_eq!( convert_from_timestamp_to_datetime_utc(timestamp), - DateTime::::from_naive_utc_and_offset(NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), Utc) + DateTime::from_timestamp(0, 0).unwrap() ); } #[test] fn should_be_converted_from_datetime_utc() { - let datetime = DateTime::::from_naive_utc_and_offset(NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), Utc); + let datetime = DateTime::from_timestamp(0, 0).unwrap(); assert_eq!( convert_from_datetime_utc_to_timestamp(&datetime), DurationSinceUnixEpoch::ZERO From 439821ca29451a79bb2005ba70a8a5145ee0bcbe Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 19 Mar 2024 12:49:52 +0800 Subject: [PATCH 0253/1297] dev: bugfix completed download stat --- src/core/torrent/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index d19a97be1..c4a1b0df9 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -99,8 +99,8 @@ impl Entry { } AnnounceEvent::Completed => { let peer_old = self.peers.insert(peer.peer_id, *peer); - // Don't count if peer was not previously known - if peer_old.is_some() { + // Don't count if peer was not previously known and not already completed. + if peer_old.is_some_and(|p| p.event != AnnounceEvent::Completed) { self.completed += 1; did_torrent_stats_change = true; } From 3a9c52f96ea8c9250eac786663f7a1a3e7ca6474 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 19 Mar 2024 07:26:09 +0000 Subject: [PATCH 0254/1297] fix: error messages starting UDP tracker String interpolation was not being doing well. --- src/servers/udp/server.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index fbea11fac..95c8145c1 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -203,7 +203,7 @@ impl Launcher { #[derive(Default)] struct ActiveRequests { - rb: StaticRb, // the number of requests we handle at the same time. + rb: StaticRb, // the number of requests we handle at the same time. } impl std::fmt::Debug for ActiveRequests { @@ -241,8 +241,14 @@ impl Udp { tx_start: oneshot::Sender, rx_halt: oneshot::Receiver, ) { - let socket = Arc::new(UdpSocket::bind(bind_to).await.expect("Could not bind to {self.socket}.")); - let address = socket.local_addr().expect("Could not get local_addr from {binding}."); + let socket = Arc::new( + UdpSocket::bind(bind_to) + .await + .unwrap_or_else(|_| panic!("Could not bind to {bind_to}.")), + ); + let address = socket + .local_addr() + .unwrap_or_else(|_| panic!("Could not get local_addr from {bind_to}.")); let halt = shutdown_signal_with_message(rx_halt, format!("Halting Http Service Bound to Socket: {address}")); info!(target: "UDP TRACKER", "Starting on: udp://{}", address); From 14ef16821635b0488c83f43e18e66229783da908 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 20 Mar 2024 04:09:29 +0800 Subject: [PATCH 0255/1297] dev: ci: update coverage build flags --- .github/workflows/coverage.yaml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 06529d53d..5731caf9f 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -18,8 +18,8 @@ jobs: runs-on: ubuntu-latest env: CARGO_INCREMENTAL: "0" - RUSTFLAGS: "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests" - RUSTDOCFLAGS: "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests" + RUSTFLAGS: "-Z profile -C codegen-units=1 -C opt-level=0 -C link-dead-code -C overflow-checks=off -Z panic_abort_tests -C panic=abort" + RUSTDOCFLAGS: "-Z profile -C codegen-units=1 -C opt-level=0 -C link-dead-code -C overflow-checks=off -Z panic_abort_tests -C panic=abort" steps: - id: checkout_push @@ -55,8 +55,9 @@ jobs: name: Run Build Checks run: cargo check --tests --benches --examples --workspace --all-targets --all-features - # Run Test Locally: - # RUSTFLAGS="-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests" RUSTDOCFLAGS="-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests" CARGO_INCREMENTAL="0" RUST_BACKTRACE=1 cargo test --tests --benches --examples --workspace --all-targets --all-features + - id: clean + name: Clean Build Directory + run: cargo clean - id: test name: Run Unit Tests From 8395c42b4e4cf4c2a98d4d5e51036d7352de9dce Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 20 Mar 2024 11:15:46 +0000 Subject: [PATCH 0256/1297] test: [#746] disable tracker stats for profiling --- share/default/config/tracker.udp.benchmarking.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml index 080c67e84..70298e9dc 100644 --- a/share/default/config/tracker.udp.benchmarking.toml +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -9,8 +9,8 @@ min_announce_interval = 120 mode = "public" on_reverse_proxy = false persistent_torrent_completed_stat = false -remove_peerless_torrents = true -tracker_usage_statistics = true +remove_peerless_torrents = false +tracker_usage_statistics = false [[udp_trackers]] bind_address = "0.0.0.0:6969" From cc1cbc12f5acbb8f91c2814bb9110789757c8033 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 20 Mar 2024 11:21:08 +0000 Subject: [PATCH 0257/1297] test: [#746] add a new binary for profiling --- .gitignore | 3 +- cSpell.json | 5 + src/bin/profiling.rs | 8 ++ src/console/mod.rs | 1 + src/console/profiling.rs | 202 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 src/bin/profiling.rs create mode 100644 src/console/profiling.rs diff --git a/.gitignore b/.gitignore index 2d8d0b8bd..caa527540 100644 --- a/.gitignore +++ b/.gitignore @@ -3,10 +3,11 @@ /.coverage/ /.idea/ /.vscode/launch.json -/tracker.toml /data.db /database.db /database.json.bz2 /storage/ /target /tracker.* +/tracker.toml +callgrind.out \ No newline at end of file diff --git a/cSpell.json b/cSpell.json index 297517980..d15355d56 100644 --- a/cSpell.json +++ b/cSpell.json @@ -21,6 +21,7 @@ "bufs", "Buildx", "byteorder", + "callgrind", "canonicalize", "canonicalized", "certbot", @@ -35,6 +36,7 @@ "Cyberneering", "datagram", "datetime", + "debuginfo", "Deque", "Dijke", "distroless", @@ -60,6 +62,7 @@ "infoschema", "Intermodal", "intervali", + "kcachegrind", "keyout", "lcov", "leecher", @@ -134,7 +137,9 @@ "untuple", "uroot", "Vagaa", + "valgrind", "Vuze", + "Weidendorfer", "Werror", "whitespaces", "XBTT", diff --git a/src/bin/profiling.rs b/src/bin/profiling.rs new file mode 100644 index 000000000..bc1ac6526 --- /dev/null +++ b/src/bin/profiling.rs @@ -0,0 +1,8 @@ +//! This binary is used for profiling with [valgrind](https://valgrind.org/) +//! and [kcachegrind](https://kcachegrind.github.io/). +use torrust_tracker::console::profiling::run; + +#[tokio::main] +async fn main() { + run().await; +} diff --git a/src/console/mod.rs b/src/console/mod.rs index 54ed8e415..dab338e4b 100644 --- a/src/console/mod.rs +++ b/src/console/mod.rs @@ -1,3 +1,4 @@ //! Console apps. pub mod ci; pub mod clients; +pub mod profiling; diff --git a/src/console/profiling.rs b/src/console/profiling.rs new file mode 100644 index 000000000..e0867159f --- /dev/null +++ b/src/console/profiling.rs @@ -0,0 +1,202 @@ +//! This binary is used for profiling with [valgrind](https://valgrind.org/) +//! and [kcachegrind](https://kcachegrind.github.io/). +//! +//! # Requirements +//! +//! [valgrind](https://valgrind.org/) and [kcachegrind](https://kcachegrind.github.io/). +//! +//! On Ubuntu you can install them with: +//! +//! ```text +//! sudo apt install valgrind kcachegrind +//! ``` +//! +//! > NOTICE: valgrind executes the program you wan to profile and waits until +//! it ends. Since the tracker is a service and does not end the profiling +//! binary accepts an arguments with the duration you want to run the tracker, +//! so that it terminates automatically after that period of time. +//! +//! # Run profiling +//! +//! To run the profiling you have to: +//! +//! 1. Build and run the tracker for profiling. +//! 2. Run the aquatic UDP load test tool to start collecting data in the tracker. +//! +//! Build and run the tracker for profiling: +//! +//! ```text +//! RUSTFLAGS='-g' cargo build --release --bin profiling \ +//! && export TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" \ +//! && valgrind \ +//! --tool=callgrind \ +//! --callgrind-out-file=callgrind.out \ +//! --collect-jumps=yes \ +//! --simulate-cache=yes \ +//! ./target/release/profiling 60 +//! ``` +//! +//! The output should be something like: +//! +//! ```text +//! RUSTFLAGS='-g' cargo build --release --bin profiling \ +//! && export TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" \ +//! && valgrind \ +//! --tool=callgrind \ +//! --callgrind-out-file=callgrind.out \ +//! --collect-jumps=yes \ +//! --simulate-cache=yes \ +//! ./target/release/profiling 60 +//! +//! Compiling torrust-tracker v3.0.0-alpha.12-develop (/home/developer/Documents/git/committer/me/github/torrust/torrust-tracker) +//! Finished `release` profile [optimized + debuginfo] target(s) in 1m 15s +//! ==122801== Callgrind, a call-graph generating cache profiler +//! ==122801== Copyright (C) 2002-2017, and GNU GPL'd, by Josef Weidendorfer et al. +//! ==122801== Using Valgrind-3.19.0 and LibVEX; rerun with -h for copyright info +//! ==122801== Command: ./target/release/profiling 60 +//! ==122801== +//! --122801-- warning: L3 cache found, using its data for the LL simulation. +//! ==122801== For interactive control, run 'callgrind_control -h'. +//! Loading configuration file: `./share/default/config/tracker.udp.benchmarking.toml` ... +//! Torrust successfully shutdown. +//! ==122801== +//! ==122801== Events : Ir Dr Dw I1mr D1mr D1mw ILmr DLmr DLmw +//! ==122801== Collected : 1160654816 278135882 247755311 24453652 12650490 16315690 10932 2481624 4832145 +//! ==122801== +//! ==122801== I refs: 1,160,654,816 +//! ==122801== I1 misses: 24,453,652 +//! ==122801== LLi misses: 10,932 +//! ==122801== I1 miss rate: 2.11% +//! ==122801== LLi miss rate: 0.00% +//! ==122801== +//! ==122801== D refs: 525,891,193 (278,135,882 rd + 247,755,311 wr) +//! ==122801== D1 misses: 28,966,180 ( 12,650,490 rd + 16,315,690 wr) +//! ==122801== LLd misses: 7,313,769 ( 2,481,624 rd + 4,832,145 wr) +//! ==122801== D1 miss rate: 5.5% ( 4.5% + 6.6% ) +//! ==122801== LLd miss rate: 1.4% ( 0.9% + 2.0% ) +//! ==122801== +//! ==122801== LL refs: 53,419,832 ( 37,104,142 rd + 16,315,690 wr) +//! ==122801== LL misses: 7,324,701 ( 2,492,556 rd + 4,832,145 wr) +//! ==122801== LL miss rate: 0.4% ( 0.2% + 2.0% ) +//! ``` +//! +//! > NOTICE: We are using an specific tracker configuration for profiling that +//! removes all features except the UDP tracker and sets the logging level to `error`. +//! +//! Build the aquatic UDP load test command: +//! +//! ```text +//! cd /tmp +//! git clone git@github.com:greatest-ape/aquatic.git +//! cd aquatic +//! cargo build --profile=release-debug -p aquatic_udp_load_test +//! ./target/release-debug/aquatic_udp_load_test -p > "load-test-config.toml" +//! ``` +//! +//! Modify the "load-test-config.toml" file to change the UDP tracker port from +//! `3000` to `6969`. +//! +//! Running the aquatic UDP load test command: +//! +//! ```text +//! ./target/release-debug/aquatic_udp_load_test -c "load-test-config.toml" +//! ``` +//! +//! The output should be something like this: +//! +//! ```text +//! Starting client with config: Config { +//! server_address: 127.0.0.1:6969, +//! log_level: Error, +//! workers: 1, +//! duration: 0, +//! summarize_last: 0, +//! extra_statistics: true, +//! network: NetworkConfig { +//! multiple_client_ipv4s: true, +//! sockets_per_worker: 4, +//! recv_buffer: 8000000, +//! }, +//! requests: RequestConfig { +//! number_of_torrents: 1000000, +//! number_of_peers: 2000000, +//! scrape_max_torrents: 10, +//! announce_peers_wanted: 30, +//! weight_connect: 50, +//! weight_announce: 50, +//! weight_scrape: 1, +//! peer_seeder_probability: 0.75, +//! }, +//! } +//! +//! Requests out: 45097.51/second +//! Responses in: 4212.70/second +//! - Connect responses: 2098.15 +//! - Announce responses: 2074.95 +//! - Scrape responses: 39.59 +//! - Error responses: 0.00 +//! Peers per announce response: 0.00 +//! Announce responses per info hash: +//! - p10: 1 +//! - p25: 1 +//! - p50: 1 +//! - p75: 2 +//! - p90: 3 +//! - p95: 4 +//! - p99: 6 +//! - p99.9: 8 +//! - p100: 10 +//! ``` +//! +//! After running the tracker for some seconds the tracker will automatically stop +//! and `valgrind`will write the file `callgrind.out` with the data. +//! +//! You can now analyze the collected data with: +//! +//! ```text +//! kcachegrind callgrind.out +//! ``` +use std::env; +use std::time::Duration; + +use log::info; +use tokio::time::sleep; + +use crate::{app, bootstrap}; + +pub async fn run() { + // Parse command line arguments + let args: Vec = env::args().collect(); + + // Ensure an argument for duration is provided + if args.len() != 2 { + eprintln!("Usage: {} ", args[0]); + return; + } + + // Parse duration argument + let Ok(duration_secs) = args[1].parse::() else { + eprintln!("Invalid duration provided"); + return; + }; + + let (config, tracker) = bootstrap::app::setup(); + + let jobs = app::start(&config, tracker).await; + + // Run the tracker for a fixed duration + let run_duration = sleep(Duration::from_secs(duration_secs)); + + tokio::select! { + () = run_duration => { + info!("Torrust timed shutdown.."); + }, + _ = tokio::signal::ctrl_c() => { + info!("Torrust shutting down via Ctrl+C.."); + // Await for all jobs to shutdown + futures::future::join_all(jobs).await; + } + } + + println!("Torrust successfully shutdown."); +} From 901566873d813356ae817602e427bb74803b81ec Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 20 Mar 2024 11:45:11 +0000 Subject: [PATCH 0258/1297] refactor: [#746] rename functions and extract named closures --- src/servers/udp/server.rs | 67 +++++++++++++++++++++------------------ 1 file changed, 36 insertions(+), 31 deletions(-) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 95c8145c1..98c4bf726 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -255,24 +255,7 @@ impl Udp { let running = tokio::task::spawn(async move { debug!(target: "UDP TRACKER", "Started: Waiting for packets on socket address: udp://{address} ..."); - - let tracker = tracker.clone(); - let socket = socket.clone(); - - let reqs = &mut ActiveRequests::default(); - - // Main Waiting Loop, awaits on async [`receive_request`]. - loop { - if let Some(h) = reqs.rb.push_overwrite( - Self::do_request(Self::receive_request(socket.clone()).await, tracker.clone(), socket.clone()).abort_handle(), - ) { - if !h.is_finished() { - // the task is still running, lets yield and give it a chance to flush. - tokio::task::yield_now().await; - h.abort(); - } - } - } + Self::run_udp_server(tracker, socket).await; }); tx_start @@ -292,6 +275,27 @@ impl Udp { task::yield_now().await; // lets allow the other threads to complete. } + async fn run_udp_server(tracker: Arc, socket: Arc) { + let tracker = tracker.clone(); + let socket = socket.clone(); + + let reqs = &mut ActiveRequests::default(); + + // Main Waiting Loop, awaits on async [`receive_request`]. + loop { + if let Some(h) = reqs.rb.push_overwrite( + Self::spawn_request_processor(Self::receive_request(socket.clone()).await, tracker.clone(), socket.clone()) + .abort_handle(), + ) { + if !h.is_finished() { + // the task is still running, lets yield and give it a chance to flush. + tokio::task::yield_now().await; + h.abort(); + } + } + } + } + async fn receive_request(socket: Arc) -> Result> { // Wait for the socket to be readable socket.readable().await?; @@ -309,26 +313,27 @@ impl Udp { } } - fn do_request( + fn spawn_request_processor( result: Result>, tracker: Arc, socket: Arc, ) -> JoinHandle<()> { - // timeout not needed, as udp is non-blocking. - tokio::task::spawn(async move { - match result { - Ok(udp_request) => { - trace!("Received Request from: {}", udp_request.from); - Self::make_response(tracker.clone(), socket.clone(), udp_request).await; - } - Err(error) => { - debug!("error: {error}"); - } + tokio::task::spawn(Self::process_request(result, tracker, socket)) + } + + async fn process_request(result: Result>, tracker: Arc, socket: Arc) { + match result { + Ok(udp_request) => { + trace!("Received Request from: {}", udp_request.from); + Self::process_valid_request(tracker.clone(), socket.clone(), udp_request).await; } - }) + Err(error) => { + debug!("error: {error}"); + } + } } - async fn make_response(tracker: Arc, socket: Arc, udp_request: UdpRequest) { + async fn process_valid_request(tracker: Arc, socket: Arc, udp_request: UdpRequest) { trace!("Making Response to {udp_request:?}"); let from = udp_request.from; let response = handlers::handle_packet(udp_request, &tracker.clone(), socket.clone()).await; From 1c59d89e1d34f0f51d3ee8685c2fa4e513a6a9bd Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 21 Mar 2024 03:08:03 +0800 Subject: [PATCH 0259/1297] chore: various maintenance 1. Clean-up Dependency Versions (major version only). 2. Remove Unused Dependences. 3. Add Unused Dependency Checker to Testing Workflow. 4. Coverage dose not include examples and benchmarks. --- .github/workflows/coverage.yaml | 2 +- .github/workflows/testing.yaml | 14 ++++++++ Cargo.lock | 20 ------------ Cargo.toml | 32 ++++++++----------- packages/configuration/Cargo.toml | 1 - packages/test-helpers/Cargo.toml | 1 - .../torrent-repository-benchmarks/Cargo.toml | 9 +++--- .../torrent-repository-benchmarks/README.md | 1 + 8 files changed, 35 insertions(+), 45 deletions(-) create mode 100644 packages/torrent-repository-benchmarks/README.md diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 5731caf9f..66def04bf 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -61,7 +61,7 @@ jobs: - id: test name: Run Unit Tests - run: cargo test --tests --benches --examples --workspace --all-targets --all-features + run: cargo test --tests --workspace --all-targets --all-features - id: coverage name: Generate Coverage Report diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 5deabd74a..8a54e8982 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -57,6 +57,12 @@ jobs: name: Enable Workflow Cache uses: Swatinem/rust-cache@v2 + - id: tools + name: Install Tools + uses: taiki-e/install-action@v2 + with: + tool: cargo-machete + - id: check name: Run Build Checks run: cargo check --tests --benches --examples --workspace --all-targets --all-features @@ -71,6 +77,14 @@ jobs: RUSTDOCFLAGS: "-D warnings" run: cargo doc --no-deps --bins --examples --workspace --all-features + - id: clean + name: Clean Build Directory + run: cargo clean + + - id: deps + name: Check Unused Dependencies + run: cargo machete + unit: name: Units diff --git a/Cargo.lock b/Cargo.lock index 4cc81979d..2e0912b9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -762,7 +762,6 @@ dependencies = [ "ciborium", "clap", "criterion-plot", - "futures", "is-terminal", "itertools 0.10.5", "num-traits", @@ -775,7 +774,6 @@ dependencies = [ "serde_derive", "serde_json", "tinytemplate", - "tokio", "walkdir", ] @@ -2156,15 +2154,6 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" -[[package]] -name = "openssl-src" -version = "300.2.3+3.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cff92b6f71555b61bb9315f7c64da3ca43d87531622120fea0195fc761b4843" -dependencies = [ - "cc", -] - [[package]] name = "openssl-sys" version = "0.9.101" @@ -2173,7 +2162,6 @@ checksum = "dda2b0f344e78efc2facf7d195d098df0dd72151b26ab98da807afc26c198dff" dependencies = [ "cc", "libc", - "openssl-src", "pkg-config", "vcpkg", ] @@ -3543,7 +3531,6 @@ dependencies = [ "clap", "colored", "config", - "criterion", "derive_more", "fern", "futures", @@ -3554,8 +3541,6 @@ dependencies = [ "log", "mockall", "multimap", - "once_cell", - "openssl", "percent-encoding", "r2d2", "r2d2_mysql", @@ -3568,11 +3553,8 @@ dependencies = [ "serde_bytes", "serde_json", "serde_repr", - "serde_urlencoded", - "serde_with", "tdyne-peer-id", "tdyne-peer-id-registry", - "tempfile", "thiserror", "tokio", "torrust-tracker-configuration", @@ -3593,7 +3575,6 @@ version = "3.0.0-alpha.12-develop" dependencies = [ "config", "derive_more", - "log", "serde", "serde_with", "thiserror", @@ -3631,7 +3612,6 @@ dependencies = [ name = "torrust-tracker-test-helpers" version = "3.0.0-alpha.12-develop" dependencies = [ - "lazy_static", "rand", "torrust-tracker-configuration", "torrust-tracker-primitives", diff --git a/Cargo.toml b/Cargo.toml index 36c865447..24bf78b6e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,35 +30,37 @@ rust-version = "1.72" version = "3.0.0-alpha.12-develop" [dependencies] +anyhow = "1" aquatic_udp_protocol = "0" async-trait = "0" axum = { version = "0", features = ["macros"] } axum-client-ip = "0" -axum-extra = { version = "0.9.2", features = ["query"] } +axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls"] } binascii = "0" chrono = { version = "0", default-features = false, features = ["clock"] } +clap = { version = "4", features = ["derive", "env"] } +colored = "2" config = "0" derive_more = "0" fern = "0" futures = "0" +hex-literal = "0" hyper = "1" lazy_static = "1" log = { version = "0", features = ["release_max_level_info"] } multimap = "0" -openssl = { version = "0", features = ["vendored"] } percent-encoding = "2" r2d2 = "0" r2d2_mysql = "24" r2d2_sqlite = { version = "0", features = ["bundled"] } rand = "0" -reqwest = "0" +reqwest = { version = "0", features = ["json"] } +ringbuf = "0" serde = { version = "1", features = ["derive"] } serde_bencode = "0" serde_bytes = "0" serde_json = "1" -ringbuf = "0" -serde_with = "3" serde_repr = "0" tdyne-peer-id = "1" tdyne-peer-id-registry = "0" @@ -68,24 +70,18 @@ torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "pa torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12-develop", path = "contrib/bencode" } torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "packages/located-error" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } -tower-http = { version = "0", features = ["compression-full", "cors", "trace", "propagate-header", "request-id"] } +tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } +trace = "0" +tracing = "0" +url = "2" uuid = { version = "1", features = ["v4"] } -colored = "2.1.0" -url = "2.5.0" -tempfile = "3.9.0" -clap = { version = "4.4.18", features = ["derive", "env"]} -anyhow = "1.0.79" -hex-literal = "0.4.1" -trace = "0.1.7" -tracing = "0.1.40" + +[package.metadata.cargo-machete] +ignored = ["serde_bytes"] [dev-dependencies] -criterion = { version = "0.5.1", features = ["async_tokio"] } local-ip-address = "0" mockall = "0" -once_cell = "1.18.0" -reqwest = { version = "0", features = ["json"] } -serde_urlencoded = "0" torrust-tracker-test-helpers = { version = "3.0.0-alpha.12-develop", path = "packages/test-helpers" } [workspace] diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index ecc8c976e..102177816 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -17,7 +17,6 @@ version.workspace = true [dependencies] config = "0" derive_more = "0" -log = { version = "0", features = ["release_max_level_info"] } serde = { version = "1", features = ["derive"] } serde_with = "3" thiserror = "1" diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 9ae891a01..2f10c6a0f 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -15,7 +15,6 @@ rust-version.workspace = true version.workspace = true [dependencies] -lazy_static = "1" rand = "0" torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } diff --git a/packages/torrent-repository-benchmarks/Cargo.toml b/packages/torrent-repository-benchmarks/Cargo.toml index da9aba621..e8b22f52f 100644 --- a/packages/torrent-repository-benchmarks/Cargo.toml +++ b/packages/torrent-repository-benchmarks/Cargo.toml @@ -1,12 +1,13 @@ [package] +description = "A set of benchmarks for the torrent repository" +keywords = ["benchmarking", "library", "repository", "torrent"] name = "torrust-torrent-repository-benchmarks" +readme = "README.md" + authors.workspace = true -categories.workspace = true -description.workspace = true documentation.workspace = true edition.workspace = true homepage.workspace = true -keywords.workspace = true license.workspace = true publish.workspace = true repository.workspace = true @@ -18,4 +19,4 @@ aquatic_udp_protocol = "0.8.0" clap = { version = "4.4.8", features = ["derive"] } futures = "0.3.29" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker = { path = "../../" } \ No newline at end of file +torrust-tracker = { path = "../../" } diff --git a/packages/torrent-repository-benchmarks/README.md b/packages/torrent-repository-benchmarks/README.md new file mode 100644 index 000000000..14183ea69 --- /dev/null +++ b/packages/torrent-repository-benchmarks/README.md @@ -0,0 +1 @@ +# Benchmarks of the torrent repository From d2a346a216b37d5d40408bf4d81fd84f37438f90 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 21 Mar 2024 03:12:00 +0800 Subject: [PATCH 0260/1297] chore: update deps Updating crates.io index Updating aho-corasick v1.1.2 -> v1.1.3 Updating async-trait v0.1.77 -> v0.1.78 Updating bitflags v2.4.2 -> v2.5.0 Updating brotli v3.4.0 -> v3.5.0 Removing h2 v0.3.25 Removing http v0.2.12 Removing http-body v0.4.6 Removing hyper v0.14.28 Updating hyper-tls v0.5.0 -> v0.6.0 Updating reqwest v0.11.26 -> v0.12.0 Updating rustix v0.38.31 -> v0.38.32 Updating syn v2.0.52 -> v2.0.53 Updating toml v0.8.11 -> v0.8.12 Updating toml_edit v0.22.7 -> v0.22.9 Updating uuid v1.7.0 -> v1.8.0 --- Cargo.lock | 245 ++++++++------------- tests/servers/health_check_api/contract.rs | 12 +- 2 files changed, 105 insertions(+), 152 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2e0912b9e..5722032b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -42,9 +42,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] @@ -185,13 +185,13 @@ dependencies = [ [[package]] name = "async-trait" -version = "0.1.77" +version = "0.1.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9" +checksum = "461abc97219de0eaaf81fe3ef974a540158f3d079c2ab200f891f1a2ef201e85" dependencies = [ "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -211,10 +211,10 @@ dependencies = [ "axum-macros", "bytes", "futures-util", - "http 1.1.0", - "http-body 1.0.0", + "http", + "http-body", "http-body-util", - "hyper 1.2.0", + "hyper", "hyper-util", "itoa", "matchit", @@ -255,8 +255,8 @@ dependencies = [ "async-trait", "bytes", "futures-util", - "http 1.1.0", - "http-body 1.0.0", + "http", + "http-body", "http-body-util", "mime", "pin-project-lite", @@ -277,8 +277,8 @@ dependencies = [ "axum-core", "bytes", "futures-util", - "http 1.1.0", - "http-body 1.0.0", + "http", + "http-body", "http-body-util", "mime", "pin-project-lite", @@ -298,7 +298,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -310,10 +310,10 @@ dependencies = [ "arc-swap", "bytes", "futures-util", - "http 1.1.0", - "http-body 1.0.0", + "http", + "http-body", "http-body-util", - "hyper 1.2.0", + "hyper", "hyper-util", "pin-project-lite", "rustls", @@ -368,7 +368,7 @@ version = "0.69.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a00dc851838a2120612785d195287475a3ac45514741da670b735818822129a0" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "cexpr", "clang-sys", "itertools 0.12.1", @@ -379,7 +379,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -390,9 +390,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.4.2" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" dependencies = [ "serde", ] @@ -438,15 +438,15 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", "syn_derive", ] [[package]] name = "brotli" -version = "3.4.0" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "516074a47ef4bce09577a3b379392300159ce5b1ba2e501ff1c819950066100f" +checksum = "d640d25bc63c50fb1f0b545ffd80207d2e10a4c965530809b40ba3386825c391" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -628,7 +628,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -880,7 +880,7 @@ dependencies = [ "proc-macro2", "quote", "strsim 0.10.0", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -891,7 +891,7 @@ checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" dependencies = [ "darling_core", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -925,7 +925,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -1103,7 +1103,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -1115,7 +1115,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -1127,7 +1127,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -1192,7 +1192,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -1258,25 +1258,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" -[[package]] -name = "h2" -version = "0.3.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fbd2820c5e49886948654ab546d0688ff24530286bdcf8fca3cefb16d4618eb" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http 0.2.12", - "indexmap 2.2.5", - "slab", - "tokio", - "tokio-util", - "tracing", -] - [[package]] name = "h2" version = "0.4.3" @@ -1288,7 +1269,7 @@ dependencies = [ "futures-core", "futures-sink", "futures-util", - "http 1.1.0", + "http", "indexmap 2.2.5", "slab", "tokio", @@ -1373,17 +1354,6 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" -[[package]] -name = "http" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "http" version = "1.1.0" @@ -1395,17 +1365,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" -dependencies = [ - "bytes", - "http 0.2.12", - "pin-project-lite", -] - [[package]] name = "http-body" version = "1.0.0" @@ -1413,7 +1372,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" dependencies = [ "bytes", - "http 1.1.0", + "http", ] [[package]] @@ -1424,8 +1383,8 @@ checksum = "0475f8b2ac86659c21b64320d5d653f9efe42acd2a4e560073ec61a155a34f1d" dependencies = [ "bytes", "futures-core", - "http 1.1.0", - "http-body 1.0.0", + "http", + "http-body", "pin-project-lite", ] @@ -1441,30 +1400,6 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" -[[package]] -name = "hyper" -version = "0.14.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf96e135eb83a2a8ddf766e426a841d8ddd7449d5f00d34ea02b41d2f19eef80" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2 0.3.25", - "http 0.2.12", - "http-body 0.4.6", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", - "want", -] - [[package]] name = "hyper" version = "1.2.0" @@ -1474,28 +1409,32 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "h2 0.4.3", - "http 1.1.0", - "http-body 1.0.0", + "h2", + "http", + "http-body", "httparse", "httpdate", "itoa", "pin-project-lite", "smallvec", "tokio", + "want", ] [[package]] name = "hyper-tls" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" dependencies = [ "bytes", - "hyper 0.14.28", + "http-body-util", + "hyper", + "hyper-util", "native-tls", "tokio", "tokio-native-tls", + "tower-service", ] [[package]] @@ -1505,13 +1444,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca38ef113da30126bbff9cd1705f9273e15d45498615d138b0c20279ac7a76aa" dependencies = [ "bytes", + "futures-channel", "futures-util", - "http 1.1.0", - "http-body 1.0.0", - "hyper 1.2.0", + "http", + "http-body", + "hyper", "pin-project-lite", "socket2", "tokio", + "tower", + "tower-service", + "tracing", ] [[package]] @@ -1894,7 +1837,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -1945,7 +1888,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", "termcolor", "thiserror", ] @@ -1959,7 +1902,7 @@ dependencies = [ "base64", "bigdecimal", "bindgen", - "bitflags 2.4.2", + "bitflags 2.5.0", "bitvec", "byteorder", "bytes", @@ -2128,7 +2071,7 @@ version = "0.10.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "cfg-if", "foreign-types", "libc", @@ -2145,7 +2088,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -2252,7 +2195,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -2321,7 +2264,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -2626,20 +2569,22 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.11.26" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78bf93c4af7a8bb7d879d51cebe797356ff10ae8516ace542b5182d9dcac10b2" +checksum = "58b48d98d932f4ee75e541614d32a7f44c889b72bd9c2e04d95edd135989df88" dependencies = [ "base64", "bytes", "encoding_rs", "futures-core", "futures-util", - "h2 0.3.25", - "http 0.2.12", - "http-body 0.4.6", - "hyper 0.14.28", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", "hyper-tls", + "hyper-util", "ipnet", "js-sys", "log", @@ -2724,7 +2669,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b91f7eff05f748767f183df4320a63d6936e9c6107d97c9e6bdd9784f4289c94" dependencies = [ "base64", - "bitflags 2.4.2", + "bitflags 2.5.0", "serde", "serde_derive", ] @@ -2735,7 +2680,7 @@ version = "0.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b838eba278d213a8beaf485bd313fd580ca4505a00d5871caeb1457c55322cae" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -2792,11 +2737,11 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.31" +version = "0.38.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949" +checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.5.0", "errno", "libc", "linux-raw-sys", @@ -2982,7 +2927,7 @@ checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -3027,7 +2972,7 @@ checksum = "0b2e6b945e9d3df726b65d6ee24060aff8e3533d431f677a9695db04eff9dfdb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -3078,7 +3023,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -3202,9 +3147,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.52" +version = "2.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b699d15b36d1f02c3e7c69f8ffef53de37aefae075d8488d4ba1a7788d574a07" +checksum = "7383cd0e49fff4b6b90ca5670bfd3e9d6a733b3f90c686605aa7eec8c4996032" dependencies = [ "proc-macro2", "quote", @@ -3220,7 +3165,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -3317,7 +3262,7 @@ checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -3411,7 +3356,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -3450,14 +3395,14 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.11" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af06656561d28735e9c1cd63dfd57132c8155426aa6af24f36a00a351f88c48e" +checksum = "e9dd1545e8208b4a5af1aa9bbd0b4cf7e9ea08fabc5d0a5c67fcaafa17433aa3" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.7", + "toml_edit 0.22.9", ] [[package]] @@ -3493,9 +3438,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.7" +version = "0.22.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18769cd1cec395d70860ceb4d932812a0b4d06b1a4bb336745a4d21b9496e992" +checksum = "8e40bb779c5187258fd7aad0eb68cb8706a0a81fa712fbea808ab43c4b8374c4" dependencies = [ "indexmap 2.2.5", "serde", @@ -3535,7 +3480,7 @@ dependencies = [ "fern", "futures", "hex-literal", - "hyper 1.2.0", + "hyper", "lazy_static", "local-ip-address", "log", @@ -3640,11 +3585,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ "async-compression", - "bitflags 2.4.2", + "bitflags 2.5.0", "bytes", "futures-core", - "http 1.1.0", - "http-body 1.0.0", + "http", + "http-body", "http-body-util", "pin-project-lite", "tokio", @@ -3698,7 +3643,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] @@ -3791,9 +3736,9 @@ checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" [[package]] name = "uuid" -version = "1.7.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f00cc9702ca12d3c81455259621e676d0f7251cec66a21e98fe2e9a37db93b2a" +checksum = "a183cf7feeba97b4dd1c0d46788634f6221d87fa961b305bed08c851829efcc0" dependencies = [ "getrandom", "rand", @@ -3857,7 +3802,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", "wasm-bindgen-shared", ] @@ -3891,7 +3836,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4147,7 +4092,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.52", + "syn 2.0.53", ] [[package]] diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index 7b00866d3..c893470c2 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -113,7 +113,11 @@ mod api { let details = report.details.first().expect("it should have some details"); assert_eq!(details.binding, binding); - assert!(details.result.as_ref().is_err_and(|e| e.contains("Connection refused"))); + assert!( + details.result.as_ref().is_err_and(|e| e.contains("client error (Connect)")), + "Expected to contain, \"client error (Connect)\", but have message \"{:?}\".", + details.result + ); assert_eq!( details.info, format!("checking api health check at: http://{binding}/api/health_check") @@ -210,7 +214,11 @@ mod http { let details = report.details.first().expect("it should have some details"); assert_eq!(details.binding, binding); - assert!(details.result.as_ref().is_err_and(|e| e.contains("Connection refused"))); + assert!( + details.result.as_ref().is_err_and(|e| e.contains("client error (Connect)")), + "Expected to contain, \"client error (Connect)\", but have message \"{:?}\".", + details.result + ); assert_eq!( details.info, format!("checking http tracker health check at: http://{binding}/health_check") From bfdeafc2b6ef4ff91fc234a35c58245ca927d053 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 21 Mar 2024 15:59:23 +0000 Subject: [PATCH 0261/1297] test: [#746] profiling: add configuration to generate flamegraphs You can generate a flamegprah with: ``` TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" cargo flamegraph --bin=profiling -- 60 ``` --- .gitignore | 4 +++- Cargo.toml | 4 ++++ cSpell.json | 1 + 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index caa527540..1bffb9842 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,6 @@ /target /tracker.* /tracker.toml -callgrind.out \ No newline at end of file +callgrind.out +flamegraph.svg +perf.data* \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 24bf78b6e..e6f196583 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -103,3 +103,7 @@ opt-level = 1 debug = 1 lto = "fat" opt-level = 3 + +[target.x86_64-unknown-linux-gnu] +linker = "/usr/bin/clang" +rustflags = ["-Clink-arg=-fuse-ld=lld", "-Clink-arg=-Wl,--no-rosegment"] \ No newline at end of file diff --git a/cSpell.json b/cSpell.json index d15355d56..0e98c99ef 100644 --- a/cSpell.json +++ b/cSpell.json @@ -105,6 +105,7 @@ "rerequests", "ringbuf", "rngs", + "rosegment", "routable", "rusqlite", "RUSTDOCFLAGS", From 6a7275e8b837d2b1afa7c2e64dde2ce7c94e4579 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 21 Mar 2024 16:26:46 +0000 Subject: [PATCH 0262/1297] docs: [#746] for profiling --- cSpell.json | 5 +++ docs/media/kcachegrind-screenshot.png | Bin 0 -> 597087 bytes docs/profiling.md | 59 ++++++++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 docs/media/kcachegrind-screenshot.png create mode 100644 docs/profiling.md diff --git a/cSpell.json b/cSpell.json index 0e98c99ef..16dff714e 100644 --- a/cSpell.json +++ b/cSpell.json @@ -18,6 +18,7 @@ "binstall", "Bitflu", "bools", + "Bragilevsky", "bufs", "Buildx", "byteorder", @@ -45,10 +46,12 @@ "dtolnay", "elif", "filesd", + "flamegraph", "Freebox", "gecos", "Grcov", "hasher", + "heaptrack", "hexlify", "hlocalhost", "Hydranode", @@ -139,11 +142,13 @@ "uroot", "Vagaa", "valgrind", + "Vitaly", "Vuze", "Weidendorfer", "Werror", "whitespaces", "XBTT", + "Xdebug", "Xeon", "Xtorrent", "Xunlei", diff --git a/docs/media/kcachegrind-screenshot.png b/docs/media/kcachegrind-screenshot.png new file mode 100644 index 0000000000000000000000000000000000000000..a10eb5ad67947131a10db4a0714b0f03e072d585 GIT binary patch literal 597087 zcmce8^;?u(+b$M}lysMLcXvp4cT0CSN(~?(-Cfe%G1Ag0DLM4e-R#@P_x<*MzCU2k z4;&uDnl+90yuFj^Ru=HD z+^_1A>paAj-Um;-l9nP3Nmw@HS}J;YdaI2lB_;ayh2KimTxY_;(Fhycs=WF3!p<#i zR8$nK=v&g@_y5n2gAdcfa3ueF>n-V(T~a6G4`$(M4ww;2^oYC*9_oL8>TS*Ou3PsY zGooup148zKt>`Z`y-^}&M3cM^H98F6OGERhQ$|&UDgM3hsqP#!I9}-ekHgcK?~r|P zx{SUVDSdpACcrRXuF>u<6p{BH*M5KqtMNV`>;F08pA-8;t!Q%Z@rtO6O|x5D+t4u4 z^+24^Gh@Ymn2|9oDwv4lV132apSveB|9j9Y83qOhc23T?tSn?yWF&nXP zaB$>W;W;@uy{dg08j``o!(&dBGcz-LkB&aQWuwoCtx=YEa&jVovtD`b-Es5iZ(?fd z^SIJsY+J9Xt1Ij4%a0|S-Bx)VcXsBChK}yUO#p0^^}W2jch5Bs%B!udEiNgE;tCkx z&p8g%y?r@Q5leGE7m1O)H`<#rOc4qYq|>YfRy#d_4L;TIhPf7hg-0bq9(+qB1Ij6F zto&)4bes9lz4bciki7o^y$pRiy!5Wosd$Bh>d8-p*t44)tST#u5RrGlE}aAAwX(7j zkSSMFQ~MSlFQ%%BzP`TxD(T_#Y_mS&oWixPogD)zDr#H(!=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zx<=8<71P*O!7#q_|s zT)`63Sn`cdYj>SdtbniN<>k-xxo_`||Grgol$}a^jRLN<+rc~{a@oa{$YS#S-M2W) z*Pum@b7)*!a;Y#@6U~^?8wrGj&b#nh0MSs|@eVg@m% zBRf**OD_hlV#Lk&nUF_5pQ5NnHEP?{Vsk{dgJm}g&2qz*P5+7GC6(Gv#UGh-3E0+Z z?vq=O^TpHJm?f7<+a1#-(TB5^B`XTwi)Et%R~}at%MuB>l0@jUViFdYt|LEaM>Gr= z&HjGoVD(x_Tl9TvJDQ+}fA{yt06tPZkE2CtY=Nw7-(eX`08@LmRf1c3=Oxu_@S}C|Mx$`1Y0xv9*QL#s=SA1oW*p|(ip}c zsm2M)jz=glbZ7GE+#YmWO=UjYy)3KblX<1b{o#*2%CaNmF5_#4tL-YINP-Z5slLsD9lqJP2tHx1+{`?m4%-%I~Dq7Rh+Uc8eDkM0-ABl_<( eMPX5qgx?1tO;5u$+%ufN(j~>@L@R|20{ NOTICE: You should make requests to the services you want to profile. For example, using the [UDP load test](./benchmarking.md#run-udp-load-test). + +After running the tracker with ` Date: Thu, 21 Mar 2024 19:12:35 +0000 Subject: [PATCH 0263/1297] docs: [#746] add missing flamegraph in docs --- .gitignore | 2 +- docs/media/flamegraph.svg | 491 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 492 insertions(+), 1 deletion(-) create mode 100644 docs/media/flamegraph.svg diff --git a/.gitignore b/.gitignore index 1bffb9842..c1abad7e0 100644 --- a/.gitignore +++ b/.gitignore @@ -6,10 +6,10 @@ /data.db /database.db /database.json.bz2 +/flamegraph.svg /storage/ /target /tracker.* /tracker.toml callgrind.out -flamegraph.svg perf.data* \ No newline at end of file diff --git a/docs/media/flamegraph.svg b/docs/media/flamegraph.svg new file mode 100644 index 000000000..34e7146f9 --- /dev/null +++ b/docs/media/flamegraph.svg @@ -0,0 +1,491 @@ +Flame Graph Reset ZoomSearch [unknown] (154 samples, 0.36%)[unknown] (154 samples, 0.36%)[unknown] (150 samples, 0.35%)[unknown] (149 samples, 0.35%)[unknown] (146 samples, 0.34%)[unknown] (139 samples, 0.33%)[unknown] (80 samples, 0.19%)[unknown] (80 samples, 0.19%)[unknown] (76 samples, 0.18%)[unknown] (63 samples, 0.15%)[unknown] (8 samples, 0.02%)[unknown] (8 samples, 0.02%)[unknown] (8 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (155 samples, 0.37%)profiling (174 samples, 0.41%)clone3 (17 samples, 0.04%)start_thread (16 samples, 0.04%)std::sys::pal::unix::thread::Thread::new::thread_start (15 samples, 0.04%)std::sys::pal::unix::stack_overflow::Handler::new (15 samples, 0.04%)std::sys::pal::unix::stack_overflow::imp::make_handler (15 samples, 0.04%)std::sys::pal::unix::stack_overflow::imp::get_stack (15 samples, 0.04%)__GI___mmap64 (15 samples, 0.04%)__GI___mmap64 (15 samples, 0.04%)[unknown] (15 samples, 0.04%)[unknown] (15 samples, 0.04%)[unknown] (15 samples, 0.04%)[unknown] (15 samples, 0.04%)[unknown] (15 samples, 0.04%)[unknown] (15 samples, 0.04%)[unknown] (15 samples, 0.04%)[unknown] (14 samples, 0.03%)[unknown] (12 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (14 samples, 0.03%)[[vdso]] (102 samples, 0.24%)<torrust_tracker::shared::crypto::ephemeral_instance_keys::RANDOM_SEED as core::ops::deref::Deref>::deref::__stability::LAZY (119 samples, 0.28%)<tokio::sync::batch_semaphore::Acquire as core::future::future::Future>::poll (13 samples, 0.03%)tokio::sync::batch_semaphore::Semaphore::poll_acquire (7 samples, 0.02%)[[vdso]] (63 samples, 0.15%)__GI___clock_gettime (6 samples, 0.01%)__GI___libc_write (5 samples, 0.01%)__GI___libc_write (5 samples, 0.01%)__memcpy_avx512_unaligned_erms (5 samples, 0.01%)__pow (8 samples, 0.02%)_int_malloc (18 samples, 0.04%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (60 samples, 0.14%)core::ptr::drop_in_place<core::option::Option<core::task::wake::Waker>> (28 samples, 0.07%)tokio::runtime::context::with_scheduler (10 samples, 0.02%)tokio::runtime::io::driver::Driver::turn (13 samples, 0.03%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (10 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (12 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (6 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (6 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (25 samples, 0.06%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (17 samples, 0.04%)core::sync::atomic::AtomicUsize::fetch_add (16 samples, 0.04%)core::sync::atomic::atomic_add (16 samples, 0.04%)tokio::runtime::driver::Handle::unpark (7 samples, 0.02%)tokio::runtime::driver::IoHandle::unpark (7 samples, 0.02%)[unknown] (10 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (21 samples, 0.05%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (18 samples, 0.04%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark_condvar (11 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (11 samples, 0.03%)std::sync::poison::Flag::done (16 samples, 0.04%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>,tokio::runtime::task::core::Header>>> (17 samples, 0.04%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (17 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (25 samples, 0.06%)tokio::runtime::task::list::OwnedTasks<S>::remove (23 samples, 0.05%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (22 samples, 0.05%)core::sync::atomic::AtomicUsize::compare_exchange (5 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (12 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (8 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (34 samples, 0.08%)tokio::runtime::scheduler::multi_thread::park::Parker::park (25 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Inner::park (25 samples, 0.06%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (34 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (31 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (21 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (18 samples, 0.04%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (8 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (8 samples, 0.02%)std::sync::poison::Flag::done (12 samples, 0.03%)std::thread::panicking (8 samples, 0.02%)std::panicking::panicking (8 samples, 0.02%)std::panicking::panic_count::count_is_zero (8 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (19 samples, 0.04%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (19 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::unlock (7 samples, 0.02%)core::sync::atomic::AtomicU32::swap (5 samples, 0.01%)core::sync::atomic::atomic_swap (5 samples, 0.01%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (55 samples, 0.13%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (55 samples, 0.13%)core::slice::<impl [T]>::contains (140 samples, 0.33%)<T as core::slice::cmp::SliceContains>::slice_contains (140 samples, 0.33%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (140 samples, 0.33%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.08%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (34 samples, 0.08%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (165 samples, 0.39%)tokio::loom::std::mutex::Mutex<T>::lock (6 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (167 samples, 0.39%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (20 samples, 0.05%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (20 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::unlock (20 samples, 0.05%)core::sync::atomic::AtomicU32::swap (10 samples, 0.02%)core::sync::atomic::atomic_swap (10 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (10 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (10 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (7 samples, 0.02%)core::sync::atomic::AtomicU32::compare_exchange (5 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (39 samples, 0.09%)tokio::runtime::scheduler::multi_thread::idle::State::dec_num_unparked (8 samples, 0.02%)core::sync::atomic::AtomicUsize::fetch_sub (8 samples, 0.02%)core::sync::atomic::atomic_sub (8 samples, 0.02%)tokio::runtime::scheduler::inject::shared::Shared<T>::is_empty (6 samples, 0.01%)tokio::runtime::scheduler::inject::shared::Shared<T>::len (6 samples, 0.01%)core::sync::atomic::AtomicUsize::load (6 samples, 0.01%)core::sync::atomic::atomic_load (6 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (6 samples, 0.01%)alloc::sync::Arc<T,A>::inner (6 samples, 0.01%)core::ptr::non_null::NonNull<T>::as_ref (6 samples, 0.01%)core::sync::atomic::AtomicU32::load (6 samples, 0.01%)core::sync::atomic::atomic_load (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (32 samples, 0.08%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (26 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (13 samples, 0.03%)core::sync::atomic::AtomicU64::load (7 samples, 0.02%)core::sync::atomic::atomic_load (7 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (63 samples, 0.15%)tokio::runtime::scheduler::multi_thread::worker::Context::park (299 samples, 0.71%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (108 samples, 0.26%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (13 samples, 0.03%)core::num::<impl u32>::wrapping_add (20 samples, 0.05%)core::sync::atomic::AtomicU64::compare_exchange (14 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (14 samples, 0.03%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (446 samples, 1.05%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (446 samples, 1.05%)tokio::runtime::scheduler::multi_thread::worker::run (446 samples, 1.05%)tokio::runtime::context::runtime::enter_runtime (446 samples, 1.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (446 samples, 1.05%)tokio::runtime::context::set_scheduler (446 samples, 1.05%)std::thread::local::LocalKey<T>::with (446 samples, 1.05%)std::thread::local::LocalKey<T>::try_with (446 samples, 1.05%)tokio::runtime::context::set_scheduler::{{closure}} (446 samples, 1.05%)tokio::runtime::context::scoped::Scoped<T>::set (446 samples, 1.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (446 samples, 1.05%)tokio::runtime::scheduler::multi_thread::worker::Context::run (446 samples, 1.05%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (95 samples, 0.22%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (86 samples, 0.20%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (82 samples, 0.19%)tokio::runtime::scheduler::multi_thread::queue::pack (35 samples, 0.08%)tokio::runtime::context::CONTEXT::__getit (12 samples, 0.03%)core::cell::Cell<T>::get (12 samples, 0.03%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (14 samples, 0.03%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (14 samples, 0.03%)tokio::runtime::context::set_current_task_id (14 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.03%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (480 samples, 1.13%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (479 samples, 1.13%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (9 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (9 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::poll (500 samples, 1.18%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (20 samples, 0.05%)tokio::runtime::task::core::Core<T,S>::set_stage (18 samples, 0.04%)tokio::runtime::task::core::TaskIdGuard::enter (7 samples, 0.02%)tokio::runtime::context::set_current_task_id (7 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (7 samples, 0.02%)tokio::runtime::context::set_current_task_id::{{closure}} (6 samples, 0.01%)core::cell::Cell<T>::replace (6 samples, 0.01%)core::mem::replace (6 samples, 0.01%)tokio::runtime::task::harness::poll_future (504 samples, 1.19%)std::panic::catch_unwind (504 samples, 1.19%)std::panicking::try (504 samples, 1.19%)std::panicking::try::do_call (504 samples, 1.19%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (504 samples, 1.19%)tokio::runtime::task::harness::poll_future::{{closure}} (504 samples, 1.19%)tokio::runtime::task::raw::poll (512 samples, 1.21%)tokio::runtime::task::harness::Harness<T,S>::poll (510 samples, 1.20%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (510 samples, 1.20%)tokio::runtime::task::state::State::transition_to_idle (5 samples, 0.01%)tokio::runtime::task::state::State::fetch_update_action (5 samples, 0.01%)core::array::<impl core::default::Default for [T: 32]>::default (8 samples, 0.02%)tokio::runtime::time::wheel::Wheel::poll (8 samples, 0.02%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (32 samples, 0.08%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (5 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_expiration (15 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (23 samples, 0.05%)tokio::sync::batch_semaphore::Waiter::assign_permits (7 samples, 0.02%)tokio::sync::batch_semaphore::Semaphore::add_permits_locked (16 samples, 0.04%)tokio::sync::rwlock::RwLock<T>::write::{{closure}} (32 samples, 0.08%)tokio::sync::rwlock::RwLock<T>::write::{{closure}}::{{closure}} (25 samples, 0.06%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (14 samples, 0.03%)alloc::vec::from_elem (19 samples, 0.04%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (19 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (19 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (19 samples, 0.04%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (19 samples, 0.04%)alloc::alloc::Global::alloc_impl (19 samples, 0.04%)alloc::alloc::alloc_zeroed (19 samples, 0.04%)__rdl_alloc_zeroed (19 samples, 0.04%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (19 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (58 samples, 0.14%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (32 samples, 0.08%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (7 samples, 0.02%)tokio::net::udp::UdpSocket::send_to::{{closure}} (6 samples, 0.01%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (6 samples, 0.01%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (6 samples, 0.01%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (6 samples, 0.01%)mio::net::udp::UdpSocket::send_to (6 samples, 0.01%)mio::io_source::IoSource<T>::do_io (6 samples, 0.01%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (6 samples, 0.01%)mio::net::udp::UdpSocket::send_to::{{closure}} (6 samples, 0.01%)std::net::udp::UdpSocket::send_to (6 samples, 0.01%)std::sys_common::net::UdpSocket::send_to (6 samples, 0.01%)std::sys::pal::unix::cvt (6 samples, 0.01%)[[heap]] (1,068 samples, 2.52%)[[..uuid::v4::<impl uuid::Uuid>::new_v4 (8 samples, 0.02%)uuid::rng::bytes (8 samples, 0.02%)rand::random (8 samples, 0.02%)rand::rng::Rng::gen (8 samples, 0.02%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (8 samples, 0.02%)rand::rng::Rng::gen (8 samples, 0.02%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (8 samples, 0.02%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (8 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (8 samples, 0.02%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (8 samples, 0.02%)rand_core::block::BlockRng<R>::generate_and_set (7 samples, 0.02%)[[vdso]] (104 samples, 0.25%)<alloc::string::String as core::fmt::Write>::write_str (29 samples, 0.07%)alloc::string::String::push_str (7 samples, 0.02%)alloc::vec::Vec<T,A>::extend_from_slice (7 samples, 0.02%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (7 samples, 0.02%)alloc::vec::Vec<T,A>::append_elements (7 samples, 0.02%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (7 samples, 0.02%)core::num::<impl u64>::rotate_left (9 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (23 samples, 0.05%)core::num::<impl u64>::wrapping_add (7 samples, 0.02%)core::hash::sip::u8to64_le (7 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (52 samples, 0.12%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (8 samples, 0.02%)tokio::runtime::context::CONTEXT::__getit (5 samples, 0.01%)core::cell::Cell<T>::get (5 samples, 0.01%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (9 samples, 0.02%)core::ops::function::FnMut::call_mut (7 samples, 0.02%)tokio::runtime::coop::poll_proceed (7 samples, 0.02%)tokio::runtime::context::budget (7 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (7 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (35 samples, 0.08%)tokio::io::ready::Ready::intersection (9 samples, 0.02%)tokio::io::ready::Ready::from_interest (9 samples, 0.02%)tokio::io::interest::Interest::is_readable (8 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (6 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (6 samples, 0.01%)core::result::Result<T,E>::is_err (44 samples, 0.10%)core::result::Result<T,E>::is_ok (44 samples, 0.10%)tokio::loom::std::mutex::Mutex<T>::lock (52 samples, 0.12%)std::sync::mutex::Mutex<T>::lock (49 samples, 0.12%)std::sys::sync::mutex::futex::Mutex::lock (49 samples, 0.12%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (129 samples, 0.30%)tokio::loom::std::mutex::Mutex<T>::lock (7 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (7 samples, 0.02%)<tokio::sync::batch_semaphore::Acquire as core::future::future::Future>::poll (46 samples, 0.11%)tokio::sync::batch_semaphore::Semaphore::poll_acquire (18 samples, 0.04%)core::result::Result<T,E>::is_err (6 samples, 0.01%)core::result::Result<T,E>::is_ok (6 samples, 0.01%)<tokio::sync::rwlock::write_guard::RwLockWriteGuard<T> as core::ops::drop::Drop>::drop (23 samples, 0.05%)tokio::sync::batch_semaphore::Semaphore::release (23 samples, 0.05%)tokio::loom::std::mutex::Mutex<T>::lock (13 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (13 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::lock (11 samples, 0.03%)core::sync::atomic::AtomicU32::compare_exchange (5 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (5 samples, 0.01%)__memcpy_avx512_unaligned_erms (22 samples, 0.05%)[profiling] (24 samples, 0.06%)<torrust_tracker::shared::bit_torrent::info_hash::InfoHash as core::fmt::Display>::fmt (32 samples, 0.08%)[[vdso]] (359 samples, 0.85%)__GI___libc_free (47 samples, 0.11%)arena_for_chunk (9 samples, 0.02%)arena_for_chunk (8 samples, 0.02%)heap_for_ptr (8 samples, 0.02%)__GI___libc_malloc (48 samples, 0.11%)tcache_get (7 samples, 0.02%)__GI___lll_lock_wake_private (57 samples, 0.13%)__GI___pthread_disable_asynccancel (13 samples, 0.03%)__GI_getsockname (115 samples, 0.27%)__libc_recvfrom (167 samples, 0.39%)__libc_sendto (48 samples, 0.11%)__memcmp_evex_movbe (38 samples, 0.09%)__memcpy_avx512_unaligned_erms (173 samples, 0.41%)__memset_avx512_unaligned_erms (53 samples, 0.13%)_int_free (70 samples, 0.17%)_int_malloc (151 samples, 0.36%)_int_memalign (29 samples, 0.07%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (11 samples, 0.03%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (5 samples, 0.01%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (5 samples, 0.01%)<torrust_tracker::shared::bit_torrent::info_hash::InfoHash as core::cmp::Ord>::cmp (15 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (15 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (15 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (15 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (15 samples, 0.04%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (43 samples, 0.10%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (40 samples, 0.09%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (35 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (35 samples, 0.08%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (11 samples, 0.03%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (5 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (15 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::grow_amortized (11 samples, 0.03%)alloc::raw_vec::finish_grow (19 samples, 0.04%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (7 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (7 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (7 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::d_rounds (5 samples, 0.01%)core::hash::BuildHasher::hash_one (9 samples, 0.02%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (27 samples, 0.06%)core::ptr::drop_in_place<tokio::net::udp::UdpSocket::send_to<&core::net::socket_addr::SocketAddr>::{{closure}}> (6 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (41 samples, 0.10%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}}> (8 samples, 0.02%)malloc_consolidate (35 samples, 0.08%)mio::sys::unix::waker::eventfd::WakerInternal::wake (5 samples, 0.01%)rand_chacha::guts::ChaCha::pos64 (5 samples, 0.01%)<ppv_lite86::soft::x2<W,G> as core::ops::arith::AddAssign>::add_assign (5 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::AddAssign>::add_assign (5 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::Add>::add (5 samples, 0.01%)core::core_arch::x86::avx2::_mm256_add_epi32 (5 samples, 0.01%)core::core_arch::x86::avx2::_mm256_or_si256 (8 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (10 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (10 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (6 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (6 samples, 0.01%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (6 samples, 0.01%)rand_chacha::guts::round (29 samples, 0.07%)rand_chacha::guts::refill_wide::impl_avx2 (43 samples, 0.10%)rand_chacha::guts::refill_wide::fn_impl (43 samples, 0.10%)rand_chacha::guts::refill_wide_impl (43 samples, 0.10%)tokio::runtime::context::with_scheduler (18 samples, 0.04%)std::thread::local::LocalKey<T>::try_with (6 samples, 0.01%)tokio::runtime::context::with_scheduler::{{closure}} (6 samples, 0.01%)tokio::runtime::context::scoped::Scoped<T>::with (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (6 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (7 samples, 0.02%)[unknown] (47 samples, 0.11%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (213 samples, 0.50%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (78 samples, 0.18%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (28 samples, 0.07%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (76 samples, 0.18%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (66 samples, 0.16%)core::sync::atomic::AtomicUsize::fetch_add (65 samples, 0.15%)core::sync::atomic::atomic_add (65 samples, 0.15%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::park::Parker::park (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::park::Inner::park (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (5 samples, 0.01%)tokio::runtime::coop::budget (5 samples, 0.01%)tokio::runtime::coop::with_budget (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (7 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (21 samples, 0.05%)tokio::runtime::context::CONTEXT::__getit (9 samples, 0.02%)core::cell::Cell<T>::get (9 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (10 samples, 0.02%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (10 samples, 0.02%)tokio::runtime::context::set_current_task_id (10 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (10 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (11 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (8 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (45 samples, 0.11%)core::ptr::drop_in_place<tokio::util::sharded_list::ShardGuard<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>> (8 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>>> (8 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (8 samples, 0.02%)<tokio::runtime::task::Task<S> as tokio::util::linked_list::Link>::pointers (5 samples, 0.01%)tokio::runtime::task::core::Header::get_trailer (5 samples, 0.01%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (37 samples, 0.09%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (20 samples, 0.05%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (98 samples, 0.23%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (30 samples, 0.07%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (30 samples, 0.07%)tokio::loom::std::mutex::Mutex<T>::lock (30 samples, 0.07%)std::sync::mutex::Mutex<T>::lock (30 samples, 0.07%)std::sys::sync::mutex::futex::Mutex::lock (30 samples, 0.07%)core::sync::atomic::AtomicU32::compare_exchange (30 samples, 0.07%)core::sync::atomic::atomic_compare_exchange (30 samples, 0.07%)tokio::runtime::task::raw::drop_join_handle_slow (7 samples, 0.02%)tokio::runtime::task::harness::Harness<T,S>::drop_join_handle_slow (5 samples, 0.01%)tokio::runtime::task::state::State::unset_join_interested (5 samples, 0.01%)tokio::runtime::task::state::State::fetch_update (5 samples, 0.01%)tokio::runtime::task::state::State::load (5 samples, 0.01%)core::sync::atomic::AtomicUsize::load (5 samples, 0.01%)core::sync::atomic::atomic_load (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (7 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (6 samples, 0.01%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (22 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (22 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run (22 samples, 0.05%)tokio::runtime::context::runtime::enter_runtime (22 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (22 samples, 0.05%)tokio::runtime::context::set_scheduler (22 samples, 0.05%)std::thread::local::LocalKey<T>::with (22 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (22 samples, 0.05%)tokio::runtime::context::set_scheduler::{{closure}} (22 samples, 0.05%)tokio::runtime::context::scoped::Scoped<T>::set (22 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (22 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Context::run (22 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (11 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (8 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (7 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (24 samples, 0.06%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (24 samples, 0.06%)tokio::runtime::task::raw::poll (30 samples, 0.07%)tokio::runtime::task::harness::Harness<T,S>::poll (25 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (25 samples, 0.06%)tokio::runtime::task::harness::poll_future (25 samples, 0.06%)std::panic::catch_unwind (25 samples, 0.06%)std::panicking::try (25 samples, 0.06%)std::panicking::try::do_call (25 samples, 0.06%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (25 samples, 0.06%)tokio::runtime::task::harness::poll_future::{{closure}} (25 samples, 0.06%)tokio::runtime::task::core::Core<T,S>::poll (25 samples, 0.06%)tokio::runtime::task::raw::schedule (5 samples, 0.01%)tokio::runtime::task::state::State::transition_to_idle (13 samples, 0.03%)tokio::runtime::task::state::State::fetch_update_action (13 samples, 0.03%)tokio::runtime::task::waker::clone_waker (6 samples, 0.01%)tokio::runtime::task::state::State::ref_inc (6 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (6 samples, 0.01%)core::sync::atomic::atomic_add (6 samples, 0.01%)tokio::runtime::task::waker::wake_by_val (12 samples, 0.03%)tokio::runtime::task::harness::<impl tokio::runtime::task::raw::RawTask>::wake_by_val (12 samples, 0.03%)tokio::runtime::task::state::State::transition_to_notified_by_val (7 samples, 0.02%)tokio::runtime::task::state::State::fetch_update_action (7 samples, 0.02%)tokio::runtime::time::Driver::park_internal (10 samples, 0.02%)tokio::runtime::time::wheel::level::Level::next_expiration (12 samples, 0.03%)tokio::runtime::time::wheel::Wheel::next_expiration (17 samples, 0.04%)tokio::sync::batch_semaphore::Semaphore::add_permits_locked (13 samples, 0.03%)tokio::sync::rwlock::RwLock<T>::write::{{closure}} (17 samples, 0.04%)tokio::sync::rwlock::RwLock<T>::write::{{closure}}::{{closure}} (7 samples, 0.02%)torrust_tracker::core::torrent::Entry::get_stats (15 samples, 0.04%)torrust_tracker::core::torrent::Entry::insert_or_update_peer (7 samples, 0.02%)torrust_tracker::core::torrent::repository::RepositoryAsyncSingle::get_torrents::{{closure}} (47 samples, 0.11%)tokio::sync::rwlock::RwLock<T>::read::{{closure}} (34 samples, 0.08%)tokio::sync::rwlock::RwLock<T>::read::{{closure}}::{{closure}} (30 samples, 0.07%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (8 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (8 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (8 samples, 0.02%)<core::time::Duration as core::hash::Hash>::hash (7 samples, 0.02%)<torrust_tracker::shared::clock::time_extent::TimeExtent as core::hash::Hash>::hash (9 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (24 samples, 0.06%)torrust_tracker::servers::udp::peer_builder::from_request (5 samples, 0.01%)torrust_tracker::servers::udp::request::AnnounceWrapper::new (20 samples, 0.05%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (16 samples, 0.04%)core::ptr::drop_in_place<alloc::sync::Arc<tokio::net::udp::UdpSocket>> (7 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (7 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker::core::Tracker>> (27 samples, 0.06%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (27 samples, 0.06%)core::sync::atomic::AtomicUsize::fetch_sub (27 samples, 0.06%)core::sync::atomic::atomic_sub (27 samples, 0.06%)core::ptr::drop_in_place<alloc::sync::Arc<tokio::net::udp::UdpSocket>> (17 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (17 samples, 0.04%)tokio::net::udp::UdpSocket::local_addr (6 samples, 0.01%)<tokio::io::poll_evented::PollEvented<E> as core::ops::deref::Deref>::deref (6 samples, 0.01%)core::option::Option<T>::as_ref (6 samples, 0.01%)[unknown] (6 samples, 0.01%)torrust_tracker::servers::udp::handlers::RequestId::make (9 samples, 0.02%)[unknown] (8 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (16 samples, 0.04%)torrust_tracker::core::Tracker::announce::{{closure}} (10 samples, 0.02%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (6 samples, 0.01%)<torrust_tracker::core::torrent::repository::RepositoryAsyncSingle as torrust_tracker::core::torrent::repository::TRepositoryAsync>::update_torrent_with_peer_and_get_stats::{{closure}} (6 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (6 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (34 samples, 0.08%)<T as alloc::string::ToString>::to_string (10 samples, 0.02%)core::option::Option<T>::expect (5 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (41 samples, 0.10%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (156 samples, 0.37%)torrust_tracker::servers::udp::logging::log_response (17 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (238 samples, 0.56%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (18 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (13 samples, 0.03%)tokio::net::udp::UdpSocket::send_to::{{closure}} (11 samples, 0.03%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (10 samples, 0.02%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (8 samples, 0.02%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (6 samples, 0.01%)mio::net::udp::UdpSocket::send_to (6 samples, 0.01%)mio::io_source::IoSource<T>::do_io (6 samples, 0.01%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (6 samples, 0.01%)mio::net::udp::UdpSocket::send_to::{{closure}} (6 samples, 0.01%)std::net::udp::UdpSocket::send_to (6 samples, 0.01%)std::sys_common::net::UdpSocket::send_to (6 samples, 0.01%)std::sys::pal::unix::cvt (6 samples, 0.01%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (5 samples, 0.01%)tracing::span::Span::log (12 samples, 0.03%)tracing::span::Span::record_all (15 samples, 0.04%)unlink_chunk (59 samples, 0.14%)[anon] (3,194 samples, 7.54%)[anon][[vdso]] (27 samples, 0.06%)__memcpy_avx512_unaligned_erms (35 samples, 0.08%)_int_malloc (9 samples, 0.02%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (8 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (21 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::grow_amortized (18 samples, 0.04%)syscall (5 samples, 0.01%)tokio::sync::batch_semaphore::Semaphore::add_permits_locked (5 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (10 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (10 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (10 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::d_rounds (7 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (11 samples, 0.03%)[profiling] (167 samples, 0.39%)unlink_chunk (5 samples, 0.01%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (7 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (7 samples, 0.02%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (5 samples, 0.01%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (7 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (39 samples, 0.09%)core::hash::sip::u8to64_le (11 samples, 0.03%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (13 samples, 0.03%)<core::net::socket_addr::SocketAddrV4 as core::hash::Hash>::hash (6 samples, 0.01%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (20 samples, 0.05%)core::ops::function::FnMut::call_mut (17 samples, 0.04%)tokio::runtime::coop::poll_proceed (17 samples, 0.04%)tokio::runtime::context::budget (17 samples, 0.04%)std::thread::local::LocalKey<T>::try_with (17 samples, 0.04%)tokio::runtime::context::budget::{{closure}} (11 samples, 0.03%)tokio::runtime::coop::poll_proceed::{{closure}} (11 samples, 0.03%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (40 samples, 0.09%)std::sync::poison::Flag::done (6 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (12 samples, 0.03%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (12 samples, 0.03%)std::sync::mutex::MutexGuard<T>::new (8 samples, 0.02%)std::sync::poison::Flag::guard (8 samples, 0.02%)std::thread::panicking (7 samples, 0.02%)std::panicking::panicking (7 samples, 0.02%)std::panicking::panic_count::count_is_zero (7 samples, 0.02%)core::result::Result<T,E>::is_err (20 samples, 0.05%)core::result::Result<T,E>::is_ok (20 samples, 0.05%)tokio::loom::std::mutex::Mutex<T>::lock (36 samples, 0.09%)std::sync::mutex::Mutex<T>::lock (36 samples, 0.09%)std::sys::sync::mutex::futex::Mutex::lock (28 samples, 0.07%)core::sync::atomic::AtomicU32::compare_exchange (7 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (7 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (79 samples, 0.19%)tokio::runtime::coop::poll_proceed (6 samples, 0.01%)tokio::runtime::context::budget (6 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (6 samples, 0.01%)tokio::runtime::context::budget::{{closure}} (6 samples, 0.01%)tokio::runtime::coop::poll_proceed::{{closure}} (6 samples, 0.01%)core::mem::drop (8 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::sync::batch_semaphore::Waitlist>> (7 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (7 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (6 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (7 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (7 samples, 0.02%)<tokio::sync::batch_semaphore::Acquire as core::future::future::Future>::poll (69 samples, 0.16%)tokio::sync::batch_semaphore::Semaphore::poll_acquire (40 samples, 0.09%)<tokio::sync::batch_semaphore::Acquire as core::ops::drop::Drop>::drop (5 samples, 0.01%)<tokio::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (6 samples, 0.01%)binascii::bin2hex (11 samples, 0.03%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (6 samples, 0.01%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (6 samples, 0.01%)<torrust_tracker::shared::bit_torrent::info_hash::InfoHash as core::fmt::Display>::fmt (20 samples, 0.05%)[[vdso]] (1,290 samples, 3.05%)[[v..[unknown] (99 samples, 0.23%)[unknown] (386 samples, 0.91%)[unknown] (295 samples, 0.70%)[unknown] (242 samples, 0.57%)[unknown] (152 samples, 0.36%)[unknown] (64 samples, 0.15%)[unknown] (33 samples, 0.08%)__GI___clock_gettime (35 samples, 0.08%)tokio::runtime::time::Driver::park_internal (16 samples, 0.04%)__GI___libc_free (44 samples, 0.10%)arena_for_chunk (12 samples, 0.03%)arena_for_chunk (8 samples, 0.02%)heap_for_ptr (5 samples, 0.01%)__GI___libc_malloc (46 samples, 0.11%)__GI___libc_realloc (7 samples, 0.02%)__GI___libc_write (22 samples, 0.05%)__GI___libc_write (22 samples, 0.05%)__GI___lll_lock_wait_private (17 samples, 0.04%)futex_wait (9 samples, 0.02%)__GI___lll_lock_wake_private (14 samples, 0.03%)__GI___pthread_disable_asynccancel (19 samples, 0.04%)compiler_builtins::float::conv::int_to_float::u128_to_f64_bits (19 samples, 0.04%)__floattidf (23 samples, 0.05%)compiler_builtins::float::conv::__floattidf (22 samples, 0.05%)exp_inline (18 samples, 0.04%)__ieee754_pow_fma (30 samples, 0.07%)log_inline (11 samples, 0.03%)__libc_calloc (19 samples, 0.04%)__libc_sendto (92 samples, 0.22%)__memcmp_evex_movbe (81 samples, 0.19%)__memcpy_avx512_unaligned_erms (484 samples, 1.14%)__posix_memalign (35 samples, 0.08%)__posix_memalign (24 samples, 0.06%)_mid_memalign (21 samples, 0.05%)__vdso_clock_gettime (5 samples, 0.01%)[unknown] (18 samples, 0.04%)free_perturb (5 samples, 0.01%)_int_free (305 samples, 0.72%)tcache_put (9 samples, 0.02%)[unknown] (5 samples, 0.01%)_int_malloc (235 samples, 0.55%)_int_memalign (28 samples, 0.07%)checked_request2size (7 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (6 samples, 0.01%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (6 samples, 0.01%)<torrust_tracker::shared::bit_torrent::info_hash::InfoHash as core::cmp::Ord>::cmp (20 samples, 0.05%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (20 samples, 0.05%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (20 samples, 0.05%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (20 samples, 0.05%)<u8 as core::slice::cmp::SliceOrd>::compare (20 samples, 0.05%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (8 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (55 samples, 0.13%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (52 samples, 0.12%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (51 samples, 0.12%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (51 samples, 0.12%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut,K,V,Type>::keys (6 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (10 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (6 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (5 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (5 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (10 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (9 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (9 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (9 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (19 samples, 0.04%)alloc::collections::btree::map::IntoIter<K,V,A>::dying_next (8 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Dying,K,V>::deallocating_next_unchecked (5 samples, 0.01%)alloc::collections::btree::navigate::<impl alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>>::deallocating_next_unchecked (5 samples, 0.01%)alloc::collections::btree::mem::replace (5 samples, 0.01%)core::ptr::write (5 samples, 0.01%)alloc::collections::btree::map::entry::Entry<K,V,A>::or_insert (5 samples, 0.01%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (6 samples, 0.01%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert_recursing (5 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (13 samples, 0.03%)alloc::raw_vec::RawVec<T,A>::grow_amortized (11 samples, 0.03%)alloc::raw_vec::finish_grow (22 samples, 0.05%)core::result::Result<T,E>::map_err (9 samples, 0.02%)alloc::vec::in_place_collect::<impl alloc::vec::spec_from_iter::SpecFromIter<T,I> for alloc::vec::Vec<T>>::from_iter (8 samples, 0.02%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (8 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (5 samples, 0.01%)alloc_new_heap (26 samples, 0.06%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (26 samples, 0.06%)core::fmt::Formatter::pad_integral (53 samples, 0.13%)core::fmt::Formatter::pad_integral::write_prefix (10 samples, 0.02%)core::fmt::Formatter::pad_integral (6 samples, 0.01%)core::fmt::write (11 samples, 0.03%)core::hash::BuildHasher::hash_one (8 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (8 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (8 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (8 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::d_rounds (6 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (65 samples, 0.15%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}}> (6 samples, 0.01%)epoll_wait (76 samples, 0.18%)malloc_consolidate (9 samples, 0.02%)std::sys::pal::unix::time::Timespec::new (6 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (46 samples, 0.11%)std::sys::pal::unix::time::Timespec::sub_timespec (34 samples, 0.08%)core::cmp::impls::<impl core::cmp::PartialOrd<&B> for &A>::ge (5 samples, 0.01%)core::cmp::PartialOrd::ge (5 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock_contended (17 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::spin (8 samples, 0.02%)std::sys_common::net::TcpListener::socket_addr (10 samples, 0.02%)std::sys_common::net::sockname (10 samples, 0.02%)syscall (52 samples, 0.12%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::push_back_or_overflow (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::push_back_finish (6 samples, 0.01%)tokio::runtime::context::with_scheduler (28 samples, 0.07%)std::thread::local::LocalKey<T>::try_with (19 samples, 0.04%)tokio::runtime::context::with_scheduler::{{closure}} (19 samples, 0.04%)tokio::runtime::context::scoped::Scoped<T>::with (19 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (19 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (19 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (15 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (9 samples, 0.02%)mio::poll::Poll::poll (12 samples, 0.03%)mio::sys::unix::selector::epoll::Selector::select (12 samples, 0.03%)core::option::Option<T>::map (6 samples, 0.01%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (6 samples, 0.01%)tokio::io::ready::Ready::from_mio (6 samples, 0.01%)core::sync::atomic::AtomicUsize::load (5 samples, 0.01%)core::sync::atomic::atomic_load (5 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (80 samples, 0.19%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (46 samples, 0.11%)[unknown] (41 samples, 0.10%)[unknown] (8 samples, 0.02%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (154 samples, 0.36%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (41 samples, 0.10%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (17 samples, 0.04%)core::mem::drop (10 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (10 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (10 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (8 samples, 0.02%)core::sync::atomic::AtomicU32::swap (7 samples, 0.02%)core::sync::atomic::atomic_swap (7 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (6 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (6 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (58 samples, 0.14%)std::sync::poison::Flag::done (5 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (11 samples, 0.03%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (11 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::unlock (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (512 samples, 1.21%)core::sync::atomic::AtomicUsize::fetch_add (509 samples, 1.20%)core::sync::atomic::atomic_add (509 samples, 1.20%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (550 samples, 1.30%)[unknown] (8 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (24 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark_condvar (9 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (9 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::next_remote_task (11 samples, 0.03%)std::sync::poison::Flag::done (34 samples, 0.08%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>,tokio::runtime::task::core::Header>>> (36 samples, 0.09%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (36 samples, 0.09%)core::sync::atomic::AtomicUsize::fetch_sub (9 samples, 0.02%)core::sync::atomic::atomic_sub (9 samples, 0.02%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (6 samples, 0.01%)core::result::Result<T,E>::is_err (9 samples, 0.02%)core::result::Result<T,E>::is_ok (9 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (62 samples, 0.15%)tokio::runtime::task::list::OwnedTasks<S>::remove (61 samples, 0.14%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (61 samples, 0.14%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (10 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (10 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (10 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (10 samples, 0.02%)core::ptr::drop_in_place<core::option::Option<tokio::runtime::scheduler::multi_thread::park::Parker>> (5 samples, 0.01%)core::cell::RefCell<T>::borrow_mut (6 samples, 0.01%)core::cell::RefCell<T>::try_borrow_mut (6 samples, 0.01%)core::cell::BorrowRefMut::new (6 samples, 0.01%)tokio::runtime::scheduler::defer::Defer::wake (13 samples, 0.03%)std::sys::pal::unix::futex::futex_wait (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (16 samples, 0.04%)std::sync::condvar::Condvar::wait (8 samples, 0.02%)std::sys::sync::condvar::futex::Condvar::wait (8 samples, 0.02%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (8 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (12 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (12 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (35 samples, 0.08%)tokio::runtime::driver::Driver::park (11 samples, 0.03%)tokio::runtime::driver::TimeDriver::park (11 samples, 0.03%)tokio::runtime::time::Driver::park (11 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Parker::park (66 samples, 0.16%)tokio::runtime::scheduler::multi_thread::park::Inner::park (66 samples, 0.16%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (129 samples, 0.30%)tokio::runtime::scheduler::multi_thread::worker::Core::should_notify_others (6 samples, 0.01%)core::ptr::drop_in_place<core::result::Result<tokio::runtime::coop::with_budget::ResetGuard,std::thread::local::AccessError>> (12 samples, 0.03%)core::ptr::drop_in_place<tokio::runtime::coop::with_budget::ResetGuard> (9 samples, 0.02%)<tokio::runtime::coop::with_budget::ResetGuard as core::ops::drop::Drop>::drop (9 samples, 0.02%)tokio::runtime::context::budget (9 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (9 samples, 0.02%)core::cell::RefCell<T>::borrow_mut (21 samples, 0.05%)core::cell::RefCell<T>::try_borrow_mut (21 samples, 0.05%)core::cell::BorrowRefMut::new (21 samples, 0.05%)tokio::runtime::coop::budget (46 samples, 0.11%)tokio::runtime::coop::with_budget (46 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (34 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (59 samples, 0.14%)tokio::runtime::signal::Driver::process (8 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (8 samples, 0.02%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (8 samples, 0.02%)tokio::runtime::context::set_current_task_id (8 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (8 samples, 0.02%)tokio::runtime::context::CONTEXT::__getit (8 samples, 0.02%)core::cell::Cell<T>::get (8 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (22 samples, 0.05%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (48 samples, 0.11%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (45 samples, 0.11%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (42 samples, 0.10%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (42 samples, 0.10%)tokio::runtime::task::core::Core<T,S>::set_stage (89 samples, 0.21%)core::sync::atomic::AtomicUsize::fetch_sub (6 samples, 0.01%)core::sync::atomic::atomic_sub (6 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::complete (22 samples, 0.05%)tokio::runtime::task::state::State::transition_to_terminal (11 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::dealloc (7 samples, 0.02%)core::mem::drop (6 samples, 0.01%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (6 samples, 0.01%)core::ptr::drop_in_place<tokio::util::sharded_list::ShardGuard<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>> (7 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>>> (7 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (7 samples, 0.02%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (15 samples, 0.04%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (39 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (8 samples, 0.02%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (8 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (8 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (8 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (7 samples, 0.02%)core::sync::atomic::AtomicU32::compare_exchange (7 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (7 samples, 0.02%)tokio::runtime::task::raw::drop_abort_handle (20 samples, 0.05%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (16 samples, 0.04%)tokio::runtime::task::state::State::ref_dec (16 samples, 0.04%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (5 samples, 0.01%)tokio::runtime::task::raw::drop_join_handle_slow (13 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::drop_join_handle_slow (12 samples, 0.03%)tokio::runtime::task::state::State::unset_join_interested (6 samples, 0.01%)tokio::runtime::task::state::State::fetch_update (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (10 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (10 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (10 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (10 samples, 0.02%)core::result::Result<T,E>::is_err (8 samples, 0.02%)core::result::Result<T,E>::is_ok (8 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (6 samples, 0.01%)core::result::Result<T,E>::is_err (5 samples, 0.01%)core::result::Result<T,E>::is_ok (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (7 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (7 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (7 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (7 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::park (27 samples, 0.06%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (10 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (10 samples, 0.02%)core::sync::atomic::AtomicU64::compare_exchange (10 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (10 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (34 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (60 samples, 0.14%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (44 samples, 0.10%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (106 samples, 0.25%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (106 samples, 0.25%)tokio::runtime::scheduler::multi_thread::worker::run (106 samples, 0.25%)tokio::runtime::context::runtime::enter_runtime (106 samples, 0.25%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (106 samples, 0.25%)tokio::runtime::context::set_scheduler (106 samples, 0.25%)std::thread::local::LocalKey<T>::with (106 samples, 0.25%)std::thread::local::LocalKey<T>::try_with (106 samples, 0.25%)tokio::runtime::context::set_scheduler::{{closure}} (106 samples, 0.25%)tokio::runtime::context::scoped::Scoped<T>::set (106 samples, 0.25%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (106 samples, 0.25%)tokio::runtime::scheduler::multi_thread::worker::Context::run (106 samples, 0.25%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (121 samples, 0.29%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (118 samples, 0.28%)tokio::runtime::context::CONTEXT::__getit (10 samples, 0.02%)core::cell::Cell<T>::get (10 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (12 samples, 0.03%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (12 samples, 0.03%)tokio::runtime::context::set_current_task_id (12 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (12 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::poll (136 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (15 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage (14 samples, 0.03%)tokio::runtime::task::harness::poll_future (164 samples, 0.39%)std::panic::catch_unwind (161 samples, 0.38%)std::panicking::try (161 samples, 0.38%)std::panicking::try::do_call (160 samples, 0.38%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (160 samples, 0.38%)tokio::runtime::task::harness::poll_future::{{closure}} (160 samples, 0.38%)tokio::runtime::task::core::Core<T,S>::store_output (24 samples, 0.06%)core::sync::atomic::AtomicUsize::compare_exchange (5 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (5 samples, 0.01%)tokio::runtime::task::raw::poll (213 samples, 0.50%)tokio::runtime::task::harness::Harness<T,S>::poll (211 samples, 0.50%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (207 samples, 0.49%)tokio::runtime::task::state::State::transition_to_running (40 samples, 0.09%)tokio::runtime::task::state::State::fetch_update_action (40 samples, 0.09%)tokio::runtime::task::state::State::transition_to_running::{{closure}} (5 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (5 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (8 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (8 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (5 samples, 0.01%)tokio::runtime::driver::Handle::time (6 samples, 0.01%)core::option::Option<T>::as_ref (6 samples, 0.01%)tokio::runtime::time::source::TimeSource::instant_to_tick (6 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (13 samples, 0.03%)tokio::runtime::time::source::TimeSource::now (9 samples, 0.02%)tokio::runtime::time::Driver::park_internal (42 samples, 0.10%)<alloc::vec::Vec<T,A> as core::ops::index::Index<I>>::index (5 samples, 0.01%)core::slice::index::<impl core::ops::index::Index<I> for [T]>::index (5 samples, 0.01%)<usize as core::slice::index::SliceIndex<[T]>>::index (5 samples, 0.01%)[unknown] (5 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (28 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (8 samples, 0.02%)core::num::<impl usize>::pow (8 samples, 0.02%)tokio::runtime::time::wheel::level::level_range (12 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (10 samples, 0.02%)core::num::<impl usize>::pow (10 samples, 0.02%)tokio::runtime::time::wheel::level::Level::next_expiration (61 samples, 0.14%)tokio::runtime::time::wheel::level::slot_range (11 samples, 0.03%)core::num::<impl usize>::pow (11 samples, 0.03%)tokio::runtime::time::wheel::Wheel::next_expiration (103 samples, 0.24%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::is_empty (6 samples, 0.01%)core::option::Option<T>::is_some (6 samples, 0.01%)tokio::sync::batch_semaphore::Semaphore::add_permits_locked (50 samples, 0.12%)tokio::sync::rwlock::RwLock<T>::write::{{closure}} (13 samples, 0.03%)tokio::sync::rwlock::RwLock<T>::write::{{closure}}::{{closure}} (5 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (10 samples, 0.02%)alloc::collections::btree::navigate::<impl alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>>::next_unchecked (5 samples, 0.01%)alloc::collections::btree::mem::replace (5 samples, 0.01%)alloc::collections::btree::navigate::<impl alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>>::next_unchecked::{{closure}} (5 samples, 0.01%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (7 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (7 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (6 samples, 0.01%)<core::iter::adapters::take::Take<I> as core::iter::traits::iterator::Iterator>::next (12 samples, 0.03%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::next (12 samples, 0.03%)core::iter::traits::iterator::Iterator::find (12 samples, 0.03%)core::iter::traits::iterator::Iterator::try_fold (12 samples, 0.03%)torrust_tracker::core::torrent::Entry::get_peers_for_peer (17 samples, 0.04%)core::iter::traits::iterator::Iterator::collect (14 samples, 0.03%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (14 samples, 0.03%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (14 samples, 0.03%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (14 samples, 0.03%)torrust_tracker::core::torrent::Entry::insert_or_update_peer (15 samples, 0.04%)torrust_tracker::core::torrent::repository::RepositoryAsyncSingle::get_torrents::{{closure}} (30 samples, 0.07%)tokio::sync::rwlock::RwLock<T>::read::{{closure}} (11 samples, 0.03%)tokio::sync::rwlock::RwLock<T>::read::{{closure}}::{{closure}} (9 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (14 samples, 0.03%)torrust_tracker::shared::clock::time_extent::Make::now (14 samples, 0.03%)torrust_tracker::shared::clock::working_clock::<impl torrust_tracker::shared::clock::Time for torrust_tracker::shared::clock::Clock<_>>::now (7 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (51 samples, 0.12%)core::sync::atomic::AtomicUsize::fetch_add (12 samples, 0.03%)core::sync::atomic::atomic_add (12 samples, 0.03%)core::ptr::drop_in_place<alloc::sync::Arc<tokio::net::udp::UdpSocket>> (12 samples, 0.03%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (12 samples, 0.03%)core::sync::atomic::AtomicUsize::fetch_sub (5 samples, 0.01%)core::sync::atomic::atomic_sub (5 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (180 samples, 0.43%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (38 samples, 0.09%)core::sync::atomic::AtomicUsize::fetch_add (27 samples, 0.06%)core::sync::atomic::atomic_add (27 samples, 0.06%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker::core::Tracker>> (5 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (5 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_packet (5 samples, 0.01%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer::{{closure}} (14 samples, 0.03%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (27 samples, 0.06%)<torrust_tracker::core::torrent::repository::RepositoryAsyncSingle as torrust_tracker::core::torrent::repository::TRepositoryAsync>::update_torrent_with_peer_and_get_stats::{{closure}} (18 samples, 0.04%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (123 samples, 0.29%)torrust_tracker::core::Tracker::announce::{{closure}} (103 samples, 0.24%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (6 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (158 samples, 0.37%)torrust_tracker::servers::udp::handlers::handle_scrape::{{closure}} (8 samples, 0.02%)torrust_tracker::core::Tracker::scrape::{{closure}} (7 samples, 0.02%)core::fmt::Formatter::new (7 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (19 samples, 0.04%)core::fmt::num::imp::fmt_u64 (18 samples, 0.04%)core::intrinsics::copy_nonoverlapping (6 samples, 0.01%)<T as alloc::string::ToString>::to_string (35 samples, 0.08%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (7 samples, 0.02%)core::fmt::num::imp::fmt_u64 (7 samples, 0.02%)torrust_tracker::servers::udp::logging::map_action_name (6 samples, 0.01%)alloc::str::<impl alloc::borrow::ToOwned for str>::to_owned (5 samples, 0.01%)torrust_tracker::shared::bit_torrent::info_hash::InfoHash::to_hex_string (8 samples, 0.02%)<T as alloc::string::ToString>::to_string (8 samples, 0.02%)torrust_tracker::servers::udp::logging::log_request (58 samples, 0.14%)<T as alloc::string::ToString>::to_string (7 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (273 samples, 0.64%)torrust_tracker::servers::udp::logging::log_response (16 samples, 0.04%)alloc::vec::from_elem (36 samples, 0.09%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (36 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (36 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (36 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (36 samples, 0.09%)alloc::alloc::Global::alloc_impl (36 samples, 0.09%)alloc::alloc::alloc_zeroed (36 samples, 0.09%)__rdl_alloc_zeroed (36 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (36 samples, 0.09%)core::ptr::drop_in_place<std::io::cursor::Cursor<alloc::vec::Vec<u8>>> (5 samples, 0.01%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (5 samples, 0.01%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (5 samples, 0.01%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (5 samples, 0.01%)[unknown] (11 samples, 0.03%)[unknown] (14 samples, 0.03%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (646 samples, 1.53%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (227 samples, 0.54%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (133 samples, 0.31%)tokio::net::udp::UdpSocket::send_to::{{closure}} (119 samples, 0.28%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (111 samples, 0.26%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (93 samples, 0.22%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (65 samples, 0.15%)mio::net::udp::UdpSocket::send_to (58 samples, 0.14%)mio::io_source::IoSource<T>::do_io (58 samples, 0.14%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (58 samples, 0.14%)mio::net::udp::UdpSocket::send_to::{{closure}} (58 samples, 0.14%)std::net::udp::UdpSocket::send_to (58 samples, 0.14%)std::sys_common::net::UdpSocket::send_to (56 samples, 0.13%)std::sys::pal::unix::cvt (38 samples, 0.09%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (33 samples, 0.08%)alloc::vec::Vec<T>::with_capacity (6 samples, 0.01%)alloc::vec::Vec<T,A>::with_capacity_in (6 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (5 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (5 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (49 samples, 0.12%)tokio::net::udp::UdpSocket::ready::{{closure}} (49 samples, 0.12%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (65 samples, 0.15%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (9 samples, 0.02%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (7 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (91 samples, 0.21%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (91 samples, 0.21%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (16 samples, 0.04%)tokio::task::spawn::spawn (16 samples, 0.04%)tokio::task::spawn::spawn_inner (16 samples, 0.04%)tokio::runtime::context::current::with_current (16 samples, 0.04%)std::thread::local::LocalKey<T>::try_with (16 samples, 0.04%)tokio::runtime::context::current::with_current::{{closure}} (16 samples, 0.04%)core::option::Option<T>::map (16 samples, 0.04%)tokio::task::spawn::spawn_inner::{{closure}} (16 samples, 0.04%)tokio::runtime::scheduler::Handle::spawn (16 samples, 0.04%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (16 samples, 0.04%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (16 samples, 0.04%)tokio::runtime::task::list::OwnedTasks<S>::bind (15 samples, 0.04%)tokio::runtime::task::new_task (14 samples, 0.03%)tokio::runtime::task::raw::RawTask::new (14 samples, 0.03%)tokio::runtime::task::core::Cell<T,S>::new (14 samples, 0.03%)alloc::boxed::Box<T>::new (7 samples, 0.02%)alloc::alloc::exchange_malloc (7 samples, 0.02%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (7 samples, 0.02%)alloc::alloc::Global::alloc_impl (7 samples, 0.02%)alloc::alloc::alloc (7 samples, 0.02%)__rdl_alloc (7 samples, 0.02%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (7 samples, 0.02%)std::sys::pal::unix::alloc::aligned_malloc (7 samples, 0.02%)tracing::span::Span::record_all (23 samples, 0.05%)unlink_chunk (56 samples, 0.13%)uuid::builder::Builder::with_variant (13 samples, 0.03%)[unknown] (8 samples, 0.02%)uuid::builder::Builder::from_random_bytes (17 samples, 0.04%)[unknown] (7,184 samples, 16.96%)[unknown]uuid::v4::<impl uuid::Uuid>::new_v4 (72 samples, 0.17%)uuid::rng::bytes (54 samples, 0.13%)rand::random (54 samples, 0.13%)rand::rng::Rng::gen (52 samples, 0.12%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (52 samples, 0.12%)rand::rng::Rng::gen (52 samples, 0.12%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (52 samples, 0.12%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (52 samples, 0.12%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (52 samples, 0.12%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (52 samples, 0.12%)[unknown] (24 samples, 0.06%)__GI___libc_free (12 samples, 0.03%)__GI___libc_malloc (11 samples, 0.03%)__memcmp_evex_movbe (15 samples, 0.04%)__memcpy_avx512_unaligned_erms (15 samples, 0.04%)_int_free (14 samples, 0.03%)_int_malloc (36 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (6 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::grow_amortized (5 samples, 0.01%)[unknown] (5 samples, 0.01%)[unknown] (5 samples, 0.01%)[unknown] (5 samples, 0.01%)[unknown] (5 samples, 0.01%)[unknown] (5 samples, 0.01%)__malloc_arena_thread_freeres (7 samples, 0.02%)tcache_thread_shutdown (7 samples, 0.02%)__GI___libc_free (7 samples, 0.02%)_int_free (7 samples, 0.02%)heap_trim (7 samples, 0.02%)shrink_heap (7 samples, 0.02%)__GI_madvise (7 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (7 samples, 0.02%)advise_stack_range (12 samples, 0.03%)__GI_madvise (12 samples, 0.03%)[unknown] (12 samples, 0.03%)[unknown] (12 samples, 0.03%)[unknown] (12 samples, 0.03%)[unknown] (12 samples, 0.03%)[unknown] (12 samples, 0.03%)[unknown] (12 samples, 0.03%)[unknown] (12 samples, 0.03%)[unknown] (11 samples, 0.03%)[unknown] (11 samples, 0.03%)[unknown] (11 samples, 0.03%)[unknown] (11 samples, 0.03%)[unknown] (11 samples, 0.03%)std::sync::condvar::Condvar::wait_timeout (33 samples, 0.08%)std::sys::sync::condvar::futex::Condvar::wait_timeout (33 samples, 0.08%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (33 samples, 0.08%)std::sys::pal::unix::futex::futex_wait (33 samples, 0.08%)syscall (32 samples, 0.08%)[unknown] (32 samples, 0.08%)[unknown] (32 samples, 0.08%)[unknown] (32 samples, 0.08%)[unknown] (32 samples, 0.08%)[unknown] (32 samples, 0.08%)[unknown] (32 samples, 0.08%)[unknown] (32 samples, 0.08%)[unknown] (32 samples, 0.08%)[unknown] (32 samples, 0.08%)[unknown] (31 samples, 0.07%)[unknown] (31 samples, 0.07%)[unknown] (24 samples, 0.06%)[unknown] (24 samples, 0.06%)[unknown] (16 samples, 0.04%)[unknown] (12 samples, 0.03%)[unknown] (12 samples, 0.03%)[unknown] (12 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (45 samples, 0.11%)std::sync::mutex::Mutex<T>::lock (45 samples, 0.11%)std::sys::sync::mutex::futex::Mutex::lock (45 samples, 0.11%)std::sys::sync::mutex::futex::Mutex::lock_contended (45 samples, 0.11%)std::sys::pal::unix::futex::futex_wait (45 samples, 0.11%)syscall (45 samples, 0.11%)[unknown] (45 samples, 0.11%)[unknown] (45 samples, 0.11%)[unknown] (45 samples, 0.11%)[unknown] (45 samples, 0.11%)[unknown] (45 samples, 0.11%)[unknown] (44 samples, 0.10%)[unknown] (44 samples, 0.10%)[unknown] (44 samples, 0.10%)[unknown] (44 samples, 0.10%)[unknown] (42 samples, 0.10%)[unknown] (34 samples, 0.08%)[unknown] (27 samples, 0.06%)[unknown] (21 samples, 0.05%)[unknown] (9 samples, 0.02%)[unknown] (9 samples, 0.02%)[unknown] (5 samples, 0.01%)[[vdso]] (149 samples, 0.35%)__ieee754_pow_fma (6 samples, 0.01%)std::f64::<impl f64>::powf (168 samples, 0.40%)__pow (163 samples, 0.38%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (186 samples, 0.44%)std::time::Instant::now (5 samples, 0.01%)std::sys::pal::unix::time::Instant::now (5 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (5 samples, 0.01%)__GI___clock_gettime (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_processing_scheduled_tasks (11 samples, 0.03%)std::time::Instant::now (11 samples, 0.03%)std::sys::pal::unix::time::Instant::now (11 samples, 0.03%)std::sys::pal::unix::time::Timespec::now (6 samples, 0.01%)__GI___clock_gettime (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (21 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (16 samples, 0.04%)tokio::runtime::scheduler::multi_thread::park::Parker::park_timeout (16 samples, 0.04%)tokio::runtime::driver::Driver::park_timeout (16 samples, 0.04%)tokio::runtime::driver::TimeDriver::park_timeout (16 samples, 0.04%)tokio::runtime::time::Driver::park_timeout (16 samples, 0.04%)tokio::runtime::time::Driver::park_internal (14 samples, 0.03%)tokio::runtime::io::driver::Driver::turn (14 samples, 0.03%)mio::poll::Poll::poll (14 samples, 0.03%)mio::sys::unix::selector::epoll::Selector::select (14 samples, 0.03%)epoll_wait (14 samples, 0.03%)[unknown] (14 samples, 0.03%)[unknown] (14 samples, 0.03%)[unknown] (14 samples, 0.03%)[unknown] (14 samples, 0.03%)[unknown] (12 samples, 0.03%)[unknown] (11 samples, 0.03%)[unknown] (7 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (11 samples, 0.03%)alloc::sync::Arc<T,A>::inner (11 samples, 0.03%)core::ptr::non_null::NonNull<T>::as_ref (11 samples, 0.03%)core::result::Result<T,E>::is_ok (6 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<()>> (5 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (5 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::unlock (5 samples, 0.01%)core::bool::<impl bool>::then (8 samples, 0.02%)std::sys::pal::unix::futex::futex_wait (2,806 samples, 6.63%)std::sys:..syscall (2,774 samples, 6.55%)syscall[unknown] (2,721 samples, 6.42%)[unknown][unknown] (2,688 samples, 6.35%)[unknown][unknown] (2,633 samples, 6.22%)[unknown][unknown] (2,595 samples, 6.13%)[unknown][unknown] (2,514 samples, 5.94%)[unknown][unknown] (2,379 samples, 5.62%)[unknow..[unknown] (2,149 samples, 5.07%)[unkno..[unknown] (1,931 samples, 4.56%)[unkn..[unknown] (1,811 samples, 4.28%)[unkn..[unknown] (1,582 samples, 3.74%)[unk..[unknown] (1,264 samples, 2.98%)[un..[unknown] (954 samples, 2.25%)[..[unknown] (635 samples, 1.50%)[unknown] (334 samples, 0.79%)[unknown] (250 samples, 0.59%)[unknown] (186 samples, 0.44%)[unknown] (154 samples, 0.36%)[unknown] (28 samples, 0.07%)core::result::Result<T,E>::is_err (34 samples, 0.08%)core::result::Result<T,E>::is_ok (34 samples, 0.08%)std::sync::condvar::Condvar::wait (2,843 samples, 6.71%)std::sync..std::sys::sync::condvar::futex::Condvar::wait (2,843 samples, 6.71%)std::sys:..std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (2,843 samples, 6.71%)std::sys:..std::sys::sync::mutex::futex::Mutex::lock (37 samples, 0.09%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (2,863 samples, 6.76%)tokio::ru..tokio::loom::std::mutex::Mutex<T>::lock (11 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (6 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (6 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (6 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (6 samples, 0.01%)core::array::<impl core::default::Default for [T: 32]>::default (15 samples, 0.04%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (7 samples, 0.02%)<alloc::vec::Vec<T,A> as core::ops::index::Index<I>>::index (5 samples, 0.01%)core::slice::index::<impl core::ops::index::Index<I> for [T]>::index (5 samples, 0.01%)<usize as core::slice::index::SliceIndex<[T]>>::index (5 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (6 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_expiration (14 samples, 0.03%)tokio::runtime::time::wheel::Wheel::next_expiration (37 samples, 0.09%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::is_empty (5 samples, 0.01%)core::option::Option<T>::is_some (5 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (65 samples, 0.15%)core::option::Option<T>::map (18 samples, 0.04%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (20 samples, 0.05%)core::result::Result<T,E>::map (7 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (7 samples, 0.02%)[[vdso]] (17 samples, 0.04%)[unknown] (3,290 samples, 7.77%)[unknown][unknown] (3,266 samples, 7.71%)[unknown][unknown] (3,253 samples, 7.68%)[unknown][unknown] (3,203 samples, 7.56%)[unknown][unknown] (3,044 samples, 7.19%)[unknown][unknown] (2,959 samples, 6.99%)[unknown][unknown] (2,283 samples, 5.39%)[unknow..[unknown] (1,822 samples, 4.30%)[unkn..[unknown] (1,568 samples, 3.70%)[unk..[unknown] (1,352 samples, 3.19%)[un..[unknown] (910 samples, 2.15%)[..[unknown] (688 samples, 1.62%)[unknown] (498 samples, 1.18%)[unknown] (326 samples, 0.77%)[unknown] (119 samples, 0.28%)[unknown] (101 samples, 0.24%)[unknown] (65 samples, 0.15%)[unknown] (61 samples, 0.14%)[unknown] (20 samples, 0.05%)mio::poll::Poll::poll (3,385 samples, 7.99%)mio::poll::..mio::sys::unix::selector::epoll::Selector::select (3,385 samples, 7.99%)mio::sys::u..epoll_wait (3,364 samples, 7.94%)epoll_wait__GI___pthread_disable_asynccancel (13 samples, 0.03%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (46 samples, 0.11%)tokio::util::bit::Pack::pack (34 samples, 0.08%)core::result::Result<T,E>::is_err (7 samples, 0.02%)core::result::Result<T,E>::is_ok (7 samples, 0.02%)tokio::runtime::io::driver::Driver::turn (3,497 samples, 8.26%)tokio::runt..tokio::runtime::io::scheduled_io::ScheduledIo::wake (40 samples, 0.09%)tokio::loom::std::mutex::Mutex<T>::lock (13 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (13 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::lock (12 samples, 0.03%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (7 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (7 samples, 0.02%)tokio::time::clock::Clock::now (6 samples, 0.01%)tokio::time::clock::now (6 samples, 0.01%)std::time::Instant::now (6 samples, 0.01%)std::sys::pal::unix::time::Instant::now (6 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (5 samples, 0.01%)__GI___clock_gettime (5 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_expiration (6 samples, 0.01%)tokio::runtime::time::source::TimeSource::now (10 samples, 0.02%)tokio::time::clock::Clock::now (10 samples, 0.02%)tokio::time::clock::now (10 samples, 0.02%)std::time::Instant::now (10 samples, 0.02%)std::sys::pal::unix::time::Instant::now (10 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (10 samples, 0.02%)tokio::runtime::time::wheel::Wheel::next_expiration (7 samples, 0.02%)tokio::runtime::time::Driver::park_internal (3,528 samples, 8.33%)tokio::runti..tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (3,603 samples, 8.51%)tokio::runti..tokio::runtime::driver::Driver::park (3,602 samples, 8.50%)tokio::runti..tokio::runtime::driver::TimeDriver::park (3,602 samples, 8.50%)tokio::runti..tokio::runtime::time::Driver::park (3,602 samples, 8.50%)tokio::runti..tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (6,494 samples, 15.33%)tokio::runtime::schedul..tokio::runtime::scheduler::multi_thread::park::Parker::park (6,484 samples, 15.31%)tokio::runtime::schedul..tokio::runtime::scheduler::multi_thread::park::Inner::park (6,484 samples, 15.31%)tokio::runtime::schedul..core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (11 samples, 0.03%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (11 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::unlock (11 samples, 0.03%)std::sync::mutex::MutexGuard<T>::new (19 samples, 0.04%)std::sync::poison::Flag::guard (19 samples, 0.04%)std::thread::panicking (19 samples, 0.04%)std::panicking::panicking (19 samples, 0.04%)std::panicking::panic_count::count_is_zero (19 samples, 0.04%)core::sync::atomic::AtomicUsize::load (18 samples, 0.04%)core::sync::atomic::atomic_load (18 samples, 0.04%)core::result::Result<T,E>::is_err (24 samples, 0.06%)core::result::Result<T,E>::is_ok (24 samples, 0.06%)core::sync::atomic::AtomicU32::compare_exchange (18 samples, 0.04%)core::sync::atomic::atomic_compare_exchange (18 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (92 samples, 0.22%)tokio::loom::std::mutex::Mutex<T>::lock (73 samples, 0.17%)std::sync::mutex::Mutex<T>::lock (72 samples, 0.17%)std::sys::sync::mutex::futex::Mutex::lock (53 samples, 0.13%)std::sys::sync::mutex::futex::Mutex::lock_contended (11 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::spin (5 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (5 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (5 samples, 0.01%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (52 samples, 0.12%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (52 samples, 0.12%)core::slice::<impl [T]>::contains (141 samples, 0.33%)<T as core::slice::cmp::SliceContains>::slice_contains (141 samples, 0.33%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (141 samples, 0.33%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (36 samples, 0.09%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (36 samples, 0.09%)std::sync::mutex::MutexGuard<T>::new (5 samples, 0.01%)std::sync::poison::Flag::guard (5 samples, 0.01%)std::thread::panicking (5 samples, 0.01%)std::panicking::panicking (5 samples, 0.01%)std::panicking::panic_count::count_is_zero (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (157 samples, 0.37%)tokio::loom::std::mutex::Mutex<T>::lock (11 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (11 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::lock (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (166 samples, 0.39%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (12 samples, 0.03%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (12 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::unlock (11 samples, 0.03%)core::result::Result<T,E>::is_err (15 samples, 0.04%)core::result::Result<T,E>::is_ok (15 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (30 samples, 0.07%)std::sync::mutex::Mutex<T>::lock (29 samples, 0.07%)std::sys::sync::mutex::futex::Mutex::lock (29 samples, 0.07%)std::sys::sync::mutex::futex::Mutex::lock_contended (10 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::spin (7 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (48 samples, 0.11%)tokio::runtime::scheduler::multi_thread::idle::State::dec_num_unparked (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (8 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (7 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (5 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (8 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (7 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (7 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock_contended (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (28 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (16 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (16 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (6,882 samples, 16.25%)tokio::runtime::scheduler..tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (85 samples, 0.20%)core::cell::RefCell<T>::borrow_mut (8 samples, 0.02%)core::cell::RefCell<T>::try_borrow_mut (8 samples, 0.02%)core::cell::BorrowRefMut::new (8 samples, 0.02%)__memcpy_avx512_unaligned_erms (45 samples, 0.11%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (88 samples, 0.21%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (88 samples, 0.21%)__memcpy_avx512_unaligned_erms (87 samples, 0.21%)std::panic::catch_unwind (137 samples, 0.32%)std::panicking::try (137 samples, 0.32%)std::panicking::try::do_call (137 samples, 0.32%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (137 samples, 0.32%)core::ops::function::FnOnce::call_once (137 samples, 0.32%)tokio::runtime::task::harness::Harness<T,S>::complete::{{closure}} (137 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (137 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::set_stage (135 samples, 0.32%)<core::num::nonzero::NonZero<T> as core::cmp::PartialEq>::eq (5 samples, 0.01%)core::cmp::impls::<impl core::cmp::PartialEq for u64>::eq (5 samples, 0.01%)std::sync::poison::Flag::done (6 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>,tokio::runtime::task::core::Header>>> (7 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (7 samples, 0.02%)core::result::Result<T,E>::is_err (70 samples, 0.17%)core::result::Result<T,E>::is_ok (70 samples, 0.17%)tokio::runtime::task::harness::Harness<T,S>::complete (240 samples, 0.57%)tokio::runtime::task::harness::Harness<T,S>::release (103 samples, 0.24%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (101 samples, 0.24%)tokio::runtime::task::list::OwnedTasks<S>::remove (98 samples, 0.23%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (88 samples, 0.21%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (75 samples, 0.18%)tokio::loom::std::mutex::Mutex<T>::lock (74 samples, 0.17%)std::sync::mutex::Mutex<T>::lock (74 samples, 0.17%)std::sys::sync::mutex::futex::Mutex::lock (73 samples, 0.17%)tokio::runtime::task::harness::cancel_task (11 samples, 0.03%)std::panic::catch_unwind (11 samples, 0.03%)std::panicking::try (11 samples, 0.03%)std::panicking::try::do_call (11 samples, 0.03%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (11 samples, 0.03%)core::ops::function::FnOnce::call_once (11 samples, 0.03%)tokio::runtime::task::harness::cancel_task::{{closure}} (11 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (11 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::set_stage (11 samples, 0.03%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (10 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (10 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (10 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::core::Tracker> (10 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker::core::torrent::repository::RepositoryAsyncSingle>> (10 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (10 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (10 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::core::torrent::repository::RepositoryAsyncSingle> (10 samples, 0.02%)core::ptr::drop_in_place<tokio::sync::rwlock::RwLock<alloc::collections::btree::map::BTreeMap<torrust_tracker::shared::bit_torrent::info_hash::InfoHash,torrust_tracker::core::torrent::Entry>>> (10 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<alloc::collections::btree::map::BTreeMap<torrust_tracker::shared::bit_torrent::info_hash::InfoHash,torrust_tracker::core::torrent::Entry>>> (10 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker::shared::bit_torrent::info_hash::InfoHash,torrust_tracker::core::torrent::Entry>> (10 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (10 samples, 0.02%)core::mem::drop (10 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker::shared::bit_torrent::info_hash::InfoHash,torrust_tracker::core::torrent::Entry>> (10 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (10 samples, 0.02%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,NodeType>,alloc::collections::btree::node::marker::KV>::drop_key_val (8 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::assume_init_drop (8 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::core::torrent::Entry> (8 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker::core::peer::Id,torrust_tracker::core::peer::Peer>> (8 samples, 0.02%)__GI___libc_free (8 samples, 0.02%)_int_free (8 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (20 samples, 0.05%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (15 samples, 0.04%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (10 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (14 samples, 0.03%)core::sync::atomic::AtomicUsize::fetch_add (13 samples, 0.03%)core::sync::atomic::atomic_add (13 samples, 0.03%)__memcpy_avx512_unaligned_erms (20 samples, 0.05%)core::ptr::drop_in_place<alloc::sync::Arc<tokio::net::udp::UdpSocket>> (22 samples, 0.05%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (22 samples, 0.05%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker::core::Tracker>> (28 samples, 0.07%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (28 samples, 0.07%)core::cmp::Ord::min (7 samples, 0.02%)core::cmp::min_by (7 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (15 samples, 0.04%)core::slice::index::<impl core::ops::index::Index<I> for [T]>::index (8 samples, 0.02%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::index (8 samples, 0.02%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (8 samples, 0.02%)<core::ops::range::Range<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (8 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (16 samples, 0.04%)std::io::cursor::Cursor<T>::remaining_slice (6 samples, 0.01%)core::slice::index::<impl core::ops::index::Index<I> for [T]>::index (5 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::index (5 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (5 samples, 0.01%)<core::ops::range::Range<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (5 samples, 0.01%)byteorder::io::ReadBytesExt::read_i32 (16 samples, 0.04%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (16 samples, 0.04%)std::io::impls::<impl std::io::Read for &[u8]>::read_exact (10 samples, 0.02%)byteorder::io::ReadBytesExt::read_i64 (8 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (8 samples, 0.02%)aquatic_udp_protocol::request::Request::from_bytes (136 samples, 0.32%)__GI___lll_lock_wait_private (6 samples, 0.01%)__GI___lll_lock_wake_private (351 samples, 0.83%)[unknown] (330 samples, 0.78%)[unknown] (328 samples, 0.77%)[unknown] (311 samples, 0.73%)[unknown] (282 samples, 0.67%)[unknown] (264 samples, 0.62%)[unknown] (157 samples, 0.37%)[unknown] (129 samples, 0.30%)[unknown] (56 samples, 0.13%)[unknown] (47 samples, 0.11%)[unknown] (22 samples, 0.05%)[unknown] (11 samples, 0.03%)[unknown] (7 samples, 0.02%)[unknown] (7 samples, 0.02%)__GI___lll_lock_wait_private (664 samples, 1.57%)futex_wait (646 samples, 1.53%)[unknown] (631 samples, 1.49%)[unknown] (622 samples, 1.47%)[unknown] (619 samples, 1.46%)[unknown] (605 samples, 1.43%)[unknown] (578 samples, 1.36%)[unknown] (544 samples, 1.28%)[unknown] (488 samples, 1.15%)[unknown] (351 samples, 0.83%)[unknown] (326 samples, 0.77%)[unknown] (284 samples, 0.67%)[unknown] (227 samples, 0.54%)[unknown] (163 samples, 0.38%)[unknown] (103 samples, 0.24%)[unknown] (34 samples, 0.08%)[unknown] (31 samples, 0.07%)[unknown] (23 samples, 0.05%)[unknown] (21 samples, 0.05%)[unknown] (7 samples, 0.02%)_int_free (788 samples, 1.86%)_..__GI___libc_free (1,148 samples, 2.71%)__..core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (1,177 samples, 2.78%)co..core::ptr::drop_in_place<alloc::vec::Vec<u8>> (1,177 samples, 2.78%)co..core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (1,177 samples, 2.78%)co..<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (1,177 samples, 2.78%)<a..<alloc::alloc::Global as core::alloc::Allocator>::deallocate (1,177 samples, 2.78%)<a..alloc::alloc::dealloc (1,177 samples, 2.78%)al..__rdl_dealloc (1,177 samples, 2.78%)__..std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (1,177 samples, 2.78%)st..tracing::span::Span::record_all (28 samples, 0.07%)unlink_chunk (27 samples, 0.06%)core::result::Result<T,E>::expect (30 samples, 0.07%)core::result::Result<T,E>::map_err (6 samples, 0.01%)std::time::Instant::elapsed (18 samples, 0.04%)std::time::Instant::now (9 samples, 0.02%)std::sys::pal::unix::time::Instant::now (9 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (9 samples, 0.02%)__GI___clock_gettime (9 samples, 0.02%)std::sys::pal::unix::cvt (6 samples, 0.01%)__GI_getsockname (1,369 samples, 3.23%)__G..[unknown] (1,334 samples, 3.15%)[un..[unknown] (1,330 samples, 3.14%)[un..[unknown] (1,271 samples, 3.00%)[un..[unknown] (1,256 samples, 2.97%)[un..[unknown] (1,067 samples, 2.52%)[u..[unknown] (826 samples, 1.95%)[..[unknown] (410 samples, 0.97%)[unknown] (85 samples, 0.20%)[unknown] (27 samples, 0.06%)[unknown] (27 samples, 0.06%)[unknown] (25 samples, 0.06%)[unknown] (23 samples, 0.05%)[unknown] (11 samples, 0.03%)[unknown] (5 samples, 0.01%)tokio::net::udp::UdpSocket::local_addr (1,381 samples, 3.26%)tok..mio::net::udp::UdpSocket::local_addr (1,381 samples, 3.26%)mio..std::net::tcp::TcpListener::local_addr (1,381 samples, 3.26%)std..std::sys_common::net::TcpListener::socket_addr (1,381 samples, 3.26%)std..std::sys_common::net::sockname (1,379 samples, 3.26%)std..std::sys_common::net::TcpListener::socket_addr::{{closure}} (1,373 samples, 3.24%)std..[[vdso]] (28 samples, 0.07%)rand_chacha::guts::ChaCha::pos64 (20 samples, 0.05%)<ppv_lite86::soft::x2<W,G> as core::ops::arith::AddAssign>::add_assign (6 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::AddAssign>::add_assign (6 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::Add>::add (6 samples, 0.01%)core::core_arch::x86::avx2::_mm256_add_epi32 (6 samples, 0.01%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (5 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (5 samples, 0.01%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (5 samples, 0.01%)rand_chacha::guts::round (23 samples, 0.05%)<rand_chacha::chacha::ChaCha12Core as rand_core::block::BlockRngCore>::generate (79 samples, 0.19%)rand_chacha::guts::ChaCha::refill4 (79 samples, 0.19%)rand_chacha::guts::refill_wide::impl_avx2 (49 samples, 0.12%)rand_chacha::guts::refill_wide::fn_impl (49 samples, 0.12%)rand_chacha::guts::refill_wide_impl (49 samples, 0.12%)torrust_tracker::servers::udp::handlers::RequestId::make (88 samples, 0.21%)uuid::v4::<impl uuid::Uuid>::new_v4 (87 samples, 0.21%)uuid::rng::bytes (87 samples, 0.21%)rand::random (87 samples, 0.21%)rand::rng::Rng::gen (87 samples, 0.21%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (87 samples, 0.21%)rand::rng::Rng::gen (87 samples, 0.21%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (87 samples, 0.21%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (87 samples, 0.21%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (87 samples, 0.21%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (87 samples, 0.21%)rand_core::block::BlockRng<R>::generate_and_set (81 samples, 0.19%)<rand::rngs::adapter::reseeding::ReseedingCore<R,Rsdr> as rand_core::block::BlockRngCore>::generate (81 samples, 0.19%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (7 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (7 samples, 0.02%)__memcmp_evex_movbe (34 samples, 0.08%)<torrust_tracker::shared::bit_torrent::info_hash::InfoHash as core::cmp::Ord>::cmp (72 samples, 0.17%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (72 samples, 0.17%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (72 samples, 0.17%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (72 samples, 0.17%)<u8 as core::slice::cmp::SliceOrd>::compare (72 samples, 0.17%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (10 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (104 samples, 0.25%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (104 samples, 0.25%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (98 samples, 0.23%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (98 samples, 0.23%)core::iter::traits::iterator::Iterator::collect (12 samples, 0.03%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (12 samples, 0.03%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (12 samples, 0.03%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (8 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (8 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (8 samples, 0.02%)tokio::sync::batch_semaphore::Waiter::assign_permits (5 samples, 0.01%)syscall (5 samples, 0.01%)[unknown] (5 samples, 0.01%)[unknown] (5 samples, 0.01%)[unknown] (5 samples, 0.01%)tokio::runtime::task::raw::RawTask::schedule (10 samples, 0.02%)tokio::runtime::task::raw::schedule (10 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::schedule (10 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task (10 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::with_current (10 samples, 0.02%)tokio::runtime::context::with_scheduler (10 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (10 samples, 0.02%)tokio::runtime::context::with_scheduler::{{closure}} (10 samples, 0.02%)tokio::runtime::context::scoped::Scoped<T>::with (10 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (10 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (10 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (10 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (10 samples, 0.02%)core::ptr::drop_in_place<tokio::sync::rwlock::read_guard::RwLockReadGuard<alloc::collections::btree::map::BTreeMap<torrust_tracker::shared::bit_torrent::info_hash::InfoHash,torrust_tracker::core::torrent::Entry>>> (20 samples, 0.05%)tokio::sync::batch_semaphore::Semaphore::add_permits_locked (18 samples, 0.04%)tokio::util::wake_list::WakeList::wake_all (11 samples, 0.03%)core::task::wake::Waker::wake (11 samples, 0.03%)tokio::runtime::task::waker::wake_by_val (11 samples, 0.03%)tokio::runtime::task::harness::<impl tokio::runtime::task::raw::RawTask>::wake_by_val (11 samples, 0.03%)torrust_tracker::core::torrent::Entry::get_peers_for_peer (5 samples, 0.01%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer::{{closure}} (158 samples, 0.37%)torrust_tracker::core::torrent::repository::RepositoryAsyncSingle::get_torrents::{{closure}} (16 samples, 0.04%)tokio::sync::rwlock::RwLock<T>::read::{{closure}} (16 samples, 0.04%)tokio::sync::rwlock::RwLock<T>::read::{{closure}}::{{closure}} (16 samples, 0.04%)<tokio::sync::batch_semaphore::Acquire as core::future::future::Future>::poll (16 samples, 0.04%)tokio::sync::batch_semaphore::Semaphore::poll_acquire (14 samples, 0.03%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (8 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (13 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (13 samples, 0.03%)core::slice::iter::Iter<T>::post_inc_start (5 samples, 0.01%)core::ptr::non_null::NonNull<T>::add (5 samples, 0.01%)__memcmp_evex_movbe (20 samples, 0.05%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (15 samples, 0.04%)<torrust_tracker::shared::bit_torrent::info_hash::InfoHash as core::cmp::Ord>::cmp (45 samples, 0.11%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (45 samples, 0.11%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (45 samples, 0.11%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (45 samples, 0.11%)<u8 as core::slice::cmp::SliceOrd>::compare (45 samples, 0.11%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (116 samples, 0.27%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (114 samples, 0.27%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (108 samples, 0.26%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (108 samples, 0.26%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut,K,V,Type>::keys (6 samples, 0.01%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (8 samples, 0.02%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert_recursing (8 samples, 0.02%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert (6 samples, 0.01%)syscall (16 samples, 0.04%)[unknown] (15 samples, 0.04%)[unknown] (14 samples, 0.03%)[unknown] (11 samples, 0.03%)[unknown] (11 samples, 0.03%)[unknown] (11 samples, 0.03%)[unknown] (10 samples, 0.02%)[unknown] (9 samples, 0.02%)[unknown] (6 samples, 0.01%)[unknown] (5 samples, 0.01%)tokio::runtime::context::with_scheduler (8 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (7 samples, 0.02%)tokio::runtime::context::with_scheduler::{{closure}} (6 samples, 0.01%)tokio::runtime::context::scoped::Scoped<T>::with (6 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (5 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (8 samples, 0.02%)core::sync::atomic::atomic_add (8 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (9 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (9 samples, 0.02%)tokio::runtime::context::with_scheduler (40 samples, 0.09%)std::thread::local::LocalKey<T>::try_with (40 samples, 0.09%)tokio::runtime::context::with_scheduler::{{closure}} (40 samples, 0.09%)tokio::runtime::context::scoped::Scoped<T>::with (40 samples, 0.09%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (40 samples, 0.09%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (40 samples, 0.09%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (40 samples, 0.09%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (40 samples, 0.09%)tokio::runtime::task::waker::wake_by_val (44 samples, 0.10%)tokio::runtime::task::harness::<impl tokio::runtime::task::raw::RawTask>::wake_by_val (44 samples, 0.10%)tokio::runtime::task::raw::RawTask::schedule (44 samples, 0.10%)tokio::runtime::task::raw::schedule (43 samples, 0.10%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::schedule (42 samples, 0.10%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task (42 samples, 0.10%)tokio::runtime::scheduler::multi_thread::worker::with_current (42 samples, 0.10%)tokio::sync::batch_semaphore::Semaphore::add_permits_locked (59 samples, 0.14%)tokio::util::wake_list::WakeList::wake_all (46 samples, 0.11%)core::task::wake::Waker::wake (46 samples, 0.11%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count (7 samples, 0.02%)core::iter::traits::iterator::Iterator::sum (7 samples, 0.02%)<usize as core::iter::traits::accum::Sum>::sum (7 samples, 0.02%)<core::iter::adapters::map::Map<I,F> as core::iter::traits::iterator::Iterator>::fold (7 samples, 0.02%)core::iter::traits::iterator::Iterator::fold (7 samples, 0.02%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (7 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (7 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (7 samples, 0.02%)core::ptr::drop_in_place<tokio::sync::rwlock::write_guard::RwLockWriteGuard<alloc::collections::btree::map::BTreeMap<torrust_tracker::shared::bit_torrent::info_hash::InfoHash,torrust_tracker::core::torrent::Entry>>> (82 samples, 0.19%)torrust_tracker::core::torrent::Entry::insert_or_update_peer (22 samples, 0.05%)torrust_tracker::core::torrent::Entry::get_stats (20 samples, 0.05%)tokio::runtime::coop::poll_proceed (5 samples, 0.01%)tokio::runtime::context::budget (5 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (5 samples, 0.01%)tokio::runtime::context::budget::{{closure}} (5 samples, 0.01%)tokio::runtime::coop::poll_proceed::{{closure}} (5 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (11 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (11 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::lock (10 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock_contended (6 samples, 0.01%)<tokio::sync::batch_semaphore::Acquire as core::future::future::Future>::poll (28 samples, 0.07%)tokio::sync::batch_semaphore::Semaphore::poll_acquire (19 samples, 0.04%)tokio::sync::rwlock::RwLock<T>::write::{{closure}} (29 samples, 0.07%)tokio::sync::rwlock::RwLock<T>::write::{{closure}}::{{closure}} (29 samples, 0.07%)_int_malloc (7 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (9 samples, 0.02%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (8 samples, 0.02%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Owned,K,V,alloc::collections::btree::node::marker::Leaf>::new_leaf (8 samples, 0.02%)alloc::collections::btree::node::LeafNode<K,V>::new (8 samples, 0.02%)alloc::boxed::Box<T,A>::new_uninit_in (8 samples, 0.02%)alloc::boxed::Box<T,A>::try_new_uninit_in (8 samples, 0.02%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (8 samples, 0.02%)alloc::alloc::Global::alloc_impl (8 samples, 0.02%)alloc::alloc::alloc (8 samples, 0.02%)__rdl_alloc (8 samples, 0.02%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (8 samples, 0.02%)__GI___libc_malloc (8 samples, 0.02%)torrust_tracker::core::torrent::Entry::insert_or_update_peer (13 samples, 0.03%)torrust_tracker::core::Tracker::announce::{{closure}} (416 samples, 0.98%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (253 samples, 0.60%)<torrust_tracker::core::torrent::repository::RepositoryAsyncSingle as torrust_tracker::core::torrent::repository::TRepositoryAsync>::update_torrent_with_peer_and_get_stats::{{closure}} (252 samples, 0.60%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (6 samples, 0.01%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (9 samples, 0.02%)<core::time::Nanoseconds as core::hash::Hash>::hash (10 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (10 samples, 0.02%)core::hash::Hasher::write_u32 (10 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (10 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (10 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (9 samples, 0.02%)<core::time::Duration as core::hash::Hash>::hash (20 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (10 samples, 0.02%)core::hash::Hasher::write_u64 (10 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (10 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (10 samples, 0.02%)<torrust_tracker::shared::clock::time_extent::TimeExtent as core::hash::Hash>::hash (31 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for u64>::hash (11 samples, 0.03%)core::hash::Hasher::write_u64 (11 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (11 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (11 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (11 samples, 0.03%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (5 samples, 0.01%)core::array::<impl core::hash::Hash for [T: N]>::hash (22 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (22 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (18 samples, 0.04%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (18 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (18 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (17 samples, 0.04%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (60 samples, 0.14%)core::num::<impl u128>::checked_div (10 samples, 0.02%)[[vdso]] (10 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::check (79 samples, 0.19%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (18 samples, 0.04%)torrust_tracker::shared::clock::time_extent::Make::now (18 samples, 0.04%)torrust_tracker::shared::clock::working_clock::<impl torrust_tracker::shared::clock::Time for torrust_tracker::shared::clock::Clock<_>>::now (8 samples, 0.02%)std::time::SystemTime::now (5 samples, 0.01%)std::sys::pal::unix::time::SystemTime::now (5 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (7 samples, 0.02%)core::array::<impl core::hash::Hash for [T: N]>::hash (6 samples, 0.01%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (6 samples, 0.01%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (6 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (6 samples, 0.01%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (6 samples, 0.01%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (6 samples, 0.01%)torrust_tracker::servers::udp::peer_builder::from_request (5 samples, 0.01%)torrust_tracker::shared::clock::working_clock::<impl torrust_tracker::shared::clock::Time for torrust_tracker::shared::clock::Clock<_>>::now (5 samples, 0.01%)std::time::SystemTime::now (5 samples, 0.01%)std::sys::pal::unix::time::SystemTime::now (5 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (5 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (516 samples, 1.22%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (10 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (8 samples, 0.02%)<core::time::Nanoseconds as core::hash::Hash>::hash (9 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (9 samples, 0.02%)core::hash::Hasher::write_u32 (9 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (9 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (9 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (5 samples, 0.01%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (12 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (23 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (14 samples, 0.03%)core::hash::Hasher::write_u64 (14 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (14 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (14 samples, 0.03%)<torrust_tracker::shared::clock::time_extent::TimeExtent as core::hash::Hash>::hash (34 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u64>::hash (11 samples, 0.03%)core::hash::Hasher::write_u64 (11 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (11 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (11 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (11 samples, 0.03%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (6 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (62 samples, 0.15%)core::array::<impl core::hash::Hash for [T: N]>::hash (18 samples, 0.04%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (18 samples, 0.04%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (16 samples, 0.04%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (16 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (16 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (15 samples, 0.04%)core::hash::sip::u8to64_le (5 samples, 0.01%)core::num::<impl u128>::checked_div (5 samples, 0.01%)[[vdso]] (5 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (77 samples, 0.18%)torrust_tracker::servers::udp::connection_cookie::make (76 samples, 0.18%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (14 samples, 0.03%)torrust_tracker::shared::clock::time_extent::Make::now (13 samples, 0.03%)torrust_tracker::shared::clock::working_clock::<impl torrust_tracker::shared::clock::Time for torrust_tracker::shared::clock::Clock<_>>::now (8 samples, 0.02%)std::time::SystemTime::now (7 samples, 0.02%)std::sys::pal::unix::time::SystemTime::now (7 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (5 samples, 0.01%)__GI___clock_gettime (5 samples, 0.01%)torrust_tracker::core::ScrapeData::add_file (5 samples, 0.01%)std::collections::hash::map::HashMap<K,V,S>::insert (5 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (5 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (9 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (9 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (8 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (8 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (620 samples, 1.46%)torrust_tracker::servers::udp::handlers::handle_scrape::{{closure}} (17 samples, 0.04%)torrust_tracker::core::Tracker::scrape::{{closure}} (16 samples, 0.04%)torrust_tracker::core::Tracker::get_swarm_metadata::{{closure}} (11 samples, 0.03%)core::fmt::Formatter::new (5 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (5 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve (5 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (5 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::grow_amortized (5 samples, 0.01%)alloc::raw_vec::finish_grow (5 samples, 0.01%)<alloc::string::String as core::fmt::Write>::write_str (7 samples, 0.02%)alloc::string::String::push_str (7 samples, 0.02%)alloc::vec::Vec<T,A>::extend_from_slice (7 samples, 0.02%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (7 samples, 0.02%)alloc::vec::Vec<T,A>::append_elements (7 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (29 samples, 0.07%)core::fmt::num::imp::fmt_u64 (28 samples, 0.07%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (15 samples, 0.04%)core::fmt::num::imp::fmt_u64 (14 samples, 0.03%)<T as alloc::string::ToString>::to_string (55 samples, 0.13%)core::option::Option<T>::expect (9 samples, 0.02%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (8 samples, 0.02%)alloc::alloc::dealloc (8 samples, 0.02%)__rdl_dealloc (8 samples, 0.02%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (8 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (12 samples, 0.03%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (12 samples, 0.03%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (12 samples, 0.03%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (12 samples, 0.03%)torrust_tracker::servers::udp::logging::map_action_name (7 samples, 0.02%)binascii::bin2hex (13 samples, 0.03%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (6 samples, 0.01%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (6 samples, 0.01%)core::fmt::write (6 samples, 0.01%)torrust_tracker::shared::bit_torrent::info_hash::InfoHash::to_hex_string (32 samples, 0.08%)<T as alloc::string::ToString>::to_string (32 samples, 0.08%)<torrust_tracker::shared::bit_torrent::info_hash::InfoHash as core::fmt::Display>::fmt (31 samples, 0.07%)core::fmt::Formatter::write_fmt (17 samples, 0.04%)core::str::converts::from_utf8 (8 samples, 0.02%)core::str::validations::run_utf8_validation (6 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (127 samples, 0.30%)alloc::vec::Vec<T,A>::reserve (8 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (8 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (8 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::grow_amortized (8 samples, 0.02%)alloc::raw_vec::finish_grow (7 samples, 0.02%)[[vdso]] (5 samples, 0.01%)<alloc::string::String as core::fmt::Write>::write_str (12 samples, 0.03%)alloc::string::String::push_str (12 samples, 0.03%)alloc::vec::Vec<T,A>::extend_from_slice (12 samples, 0.03%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (12 samples, 0.03%)alloc::vec::Vec<T,A>::append_elements (12 samples, 0.03%)[[vdso]] (8 samples, 0.02%)<T as alloc::string::ToString>::to_string (36 samples, 0.09%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (31 samples, 0.07%)core::fmt::num::imp::fmt_u64 (29 samples, 0.07%)core::option::Option<T>::expect (6 samples, 0.01%)core::ptr::drop_in_place<alloc::string::String> (5 samples, 0.01%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (5 samples, 0.01%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (5 samples, 0.01%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (5 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (3,697 samples, 8.73%)torrust_trac..torrust_tracker::servers::udp::logging::log_response (72 samples, 0.17%)tracing_core::field::display (5 samples, 0.01%)__GI___lll_lock_wake_private (6 samples, 0.01%)[unknown] (5 samples, 0.01%)[unknown] (5 samples, 0.01%)[unknown] (6 samples, 0.01%)[unknown] (6 samples, 0.01%)[unknown] (6 samples, 0.01%)[unknown] (6 samples, 0.01%)[unknown] (6 samples, 0.01%)[unknown] (6 samples, 0.01%)[unknown] (6 samples, 0.01%)[unknown] (5 samples, 0.01%)sysmalloc (23 samples, 0.05%)grow_heap (16 samples, 0.04%)__GI_mprotect (15 samples, 0.04%)[unknown] (15 samples, 0.04%)[unknown] (14 samples, 0.03%)[unknown] (14 samples, 0.03%)[unknown] (14 samples, 0.03%)[unknown] (13 samples, 0.03%)[unknown] (12 samples, 0.03%)[unknown] (10 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (6 samples, 0.01%)__libc_calloc (86 samples, 0.20%)_int_malloc (74 samples, 0.17%)__memcpy_avx512_unaligned_erms (10 samples, 0.02%)__memset_avx512_unaligned_erms (9 samples, 0.02%)alloc::vec::from_elem (110 samples, 0.26%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (110 samples, 0.26%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (110 samples, 0.26%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (110 samples, 0.26%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (109 samples, 0.26%)alloc::alloc::Global::alloc_impl (109 samples, 0.26%)alloc::alloc::alloc_zeroed (109 samples, 0.26%)__rdl_alloc_zeroed (109 samples, 0.26%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (109 samples, 0.26%)byteorder::io::WriteBytesExt::write_i32 (18 samples, 0.04%)std::io::Write::write_all (14 samples, 0.03%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (14 samples, 0.03%)std::io::cursor::vec_write (14 samples, 0.03%)std::io::cursor::vec_write_unchecked (10 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::copy_from (10 samples, 0.02%)core::intrinsics::copy (10 samples, 0.02%)aquatic_udp_protocol::response::Response::write (44 samples, 0.10%)_int_free (57 samples, 0.13%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (76 samples, 0.18%)alloc::alloc::dealloc (76 samples, 0.18%)__rdl_dealloc (76 samples, 0.18%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (76 samples, 0.18%)__GI___libc_free (76 samples, 0.18%)core::ptr::drop_in_place<std::io::cursor::Cursor<alloc::vec::Vec<u8>>> (77 samples, 0.18%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (77 samples, 0.18%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (77 samples, 0.18%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (77 samples, 0.18%)std::io::cursor::Cursor<T>::new (5 samples, 0.01%)core::ptr::drop_in_place<tokio::net::udp::UdpSocket::send_to<&core::net::socket_addr::SocketAddr>::{{closure}}> (5 samples, 0.01%)<F as core::future::into_future::IntoFuture>::into_future (6 samples, 0.01%)<core::future::ready::Ready<T> as core::future::future::Future>::poll (6 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (49 samples, 0.12%)tokio::io::ready::Ready::intersection (9 samples, 0.02%)tokio::io::ready::Ready::from_interest (9 samples, 0.02%)tokio::io::interest::Interest::is_readable (6 samples, 0.01%)[unknown] (9,280 samples, 21.91%)[unknown][unknown] (9,225 samples, 21.78%)[unknown][unknown] (9,186 samples, 21.69%)[unknown][unknown] (9,178 samples, 21.67%)[unknown][unknown] (8,810 samples, 20.80%)[unknown][unknown] (8,693 samples, 20.53%)[unknown][unknown] (8,408 samples, 19.85%)[unknown][unknown] (7,899 samples, 18.65%)[unknown][unknown] (7,670 samples, 18.11%)[unknown][unknown] (7,204 samples, 17.01%)[unknown][unknown] (6,378 samples, 15.06%)[unknown][unknown] (5,353 samples, 12.64%)[unknown][unknown] (4,967 samples, 11.73%)[unknown][unknown] (4,431 samples, 10.46%)[unknown][unknown] (4,170 samples, 9.85%)[unknown][unknown] (3,514 samples, 8.30%)[unknown][unknown] (3,283 samples, 7.75%)[unknown][unknown] (3,155 samples, 7.45%)[unknown][unknown] (2,925 samples, 6.91%)[unknown][unknown] (2,830 samples, 6.68%)[unknown][unknown] (2,515 samples, 5.94%)[unknown][unknown] (2,384 samples, 5.63%)[unknow..[unknown] (1,991 samples, 4.70%)[unkn..[unknown] (1,407 samples, 3.32%)[un..[unknown] (1,100 samples, 2.60%)[u..[unknown] (942 samples, 2.22%)[..[unknown] (909 samples, 2.15%)[..[unknown] (805 samples, 1.90%)[..[unknown] (609 samples, 1.44%)[unknown] (533 samples, 1.26%)[unknown] (391 samples, 0.92%)[unknown] (109 samples, 0.26%)[unknown] (23 samples, 0.05%)[unknown] (19 samples, 0.04%)[unknown] (6 samples, 0.01%)__libc_sendto (9,358 samples, 22.10%)__libc_sendto__GI___pthread_disable_asynccancel (22 samples, 0.05%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (9,377 samples, 22.14%)tokio::net::udp::UdpSocket::send_to..mio::net::udp::UdpSocket::send_to (9,377 samples, 22.14%)mio::net::udp::UdpSocket::send_tomio::io_source::IoSource<T>::do_io (9,377 samples, 22.14%)mio::io_source::IoSource<T>::do_iomio::sys::unix::stateless_io_source::IoSourceState::do_io (9,377 samples, 22.14%)mio::sys::unix::stateless_io_source..mio::net::udp::UdpSocket::send_to::{{closure}} (9,377 samples, 22.14%)mio::net::udp::UdpSocket::send_to::..std::net::udp::UdpSocket::send_to (9,377 samples, 22.14%)std::net::udp::UdpSocket::send_tostd::sys_common::net::UdpSocket::send_to (9,377 samples, 22.14%)std::sys_common::net::UdpSocket::se..std::sys::pal::unix::cvt (18 samples, 0.04%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (14 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (38 samples, 0.09%)std::sync::mutex::Mutex<T>::lock (38 samples, 0.09%)std::sys::sync::mutex::futex::Mutex::lock (37 samples, 0.09%)core::result::Result<T,E>::is_err (36 samples, 0.09%)core::result::Result<T,E>::is_ok (36 samples, 0.09%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (41 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (9,803 samples, 23.15%)torrust_tracker::servers::udp::server..torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (9,540 samples, 22.53%)torrust_tracker::servers::udp::serve..tokio::net::udp::UdpSocket::send_to::{{closure}} (9,513 samples, 22.46%)tokio::net::udp::UdpSocket::send_to:..tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (9,485 samples, 22.40%)tokio::net::udp::UdpSocket::send_to..tokio::runtime::io::registration::Registration::async_io::{{closure}} (9,477 samples, 22.38%)tokio::runtime::io::registration::R..tokio::runtime::io::registration::Registration::readiness::{{closure}} (44 samples, 0.10%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (42 samples, 0.10%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (42 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (13,858 samples, 32.72%)torrust_tracker::servers::udp::server::Udp::process_r..torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (13,677 samples, 32.29%)torrust_tracker::servers::udp::server::Udp::process_..<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (41 samples, 0.10%)core::sync::atomic::AtomicUsize::fetch_add (41 samples, 0.10%)core::sync::atomic::atomic_add (41 samples, 0.10%)__GI___lll_lock_wake_private (65 samples, 0.15%)[unknown] (54 samples, 0.13%)[unknown] (53 samples, 0.13%)[unknown] (49 samples, 0.12%)[unknown] (48 samples, 0.11%)[unknown] (42 samples, 0.10%)[unknown] (14 samples, 0.03%)[unknown] (9 samples, 0.02%)__GI___lll_lock_wait_private (91 samples, 0.21%)futex_wait (88 samples, 0.21%)[unknown] (87 samples, 0.21%)[unknown] (85 samples, 0.20%)[unknown] (84 samples, 0.20%)[unknown] (84 samples, 0.20%)[unknown] (81 samples, 0.19%)[unknown] (78 samples, 0.18%)[unknown] (68 samples, 0.16%)[unknown] (41 samples, 0.10%)[unknown] (38 samples, 0.09%)[unknown] (32 samples, 0.08%)[unknown] (25 samples, 0.06%)[unknown] (16 samples, 0.04%)[unknown] (12 samples, 0.03%)[unknown] (6 samples, 0.01%)[unknown] (5 samples, 0.01%)[unknown] (5 samples, 0.01%)_int_free (141 samples, 0.33%)__GI___libc_free (212 samples, 0.50%)syscall (5 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Core<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (8 samples, 0.02%)tokio::runtime::task::harness::Harness<T,S>::dealloc (9 samples, 0.02%)core::mem::drop (9 samples, 0.02%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (9 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (9 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::abort::AbortHandle> (246 samples, 0.58%)<tokio::runtime::task::abort::AbortHandle as core::ops::drop::Drop>::drop (246 samples, 0.58%)tokio::runtime::task::raw::RawTask::drop_abort_handle (245 samples, 0.58%)tokio::runtime::task::raw::drop_abort_handle (15 samples, 0.04%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (13 samples, 0.03%)tokio::runtime::task::state::State::ref_dec (13 samples, 0.03%)core::result::Result<T,E>::is_ok (5 samples, 0.01%)tokio::runtime::task::raw::drop_join_handle_slow (5 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::drop_join_handle_slow (5 samples, 0.01%)tokio::runtime::task::raw::RawTask::drop_join_handle_slow (9 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::join::JoinHandle<()>> (19 samples, 0.04%)<tokio::runtime::task::join::JoinHandle<T> as core::ops::drop::Drop>::drop (19 samples, 0.04%)tokio::runtime::task::state::State::drop_join_handle_fast (5 samples, 0.01%)core::sync::atomic::AtomicUsize::compare_exchange_weak (5 samples, 0.01%)core::sync::atomic::atomic_compare_exchange_weak (5 samples, 0.01%)ringbuf::ring_buffer::base::RbBase::is_full (8 samples, 0.02%)ringbuf::ring_buffer::base::RbBase::vacant_len (5 samples, 0.01%)ringbuf::ring_buffer::rb::Rb::push_overwrite (19 samples, 0.04%)ringbuf::ring_buffer::rb::Rb::push (7 samples, 0.02%)ringbuf::producer::Producer<T,R>::push (7 samples, 0.02%)tokio::runtime::task::join::JoinHandle<T>::abort_handle (6 samples, 0.01%)tokio::runtime::task::raw::RawTask::ref_inc (6 samples, 0.01%)tokio::runtime::task::state::State::ref_inc (6 samples, 0.01%)__GI___lll_lock_wait_private (81 samples, 0.19%)futex_wait (79 samples, 0.19%)[unknown] (75 samples, 0.18%)[unknown] (74 samples, 0.17%)[unknown] (74 samples, 0.17%)[unknown] (72 samples, 0.17%)[unknown] (70 samples, 0.17%)[unknown] (66 samples, 0.16%)[unknown] (60 samples, 0.14%)[unknown] (28 samples, 0.07%)[unknown] (24 samples, 0.06%)[unknown] (21 samples, 0.05%)[unknown] (17 samples, 0.04%)[unknown] (10 samples, 0.02%)[unknown] (7 samples, 0.02%)__GI___lll_lock_wake_private (96 samples, 0.23%)[unknown] (90 samples, 0.21%)[unknown] (88 samples, 0.21%)[unknown] (85 samples, 0.20%)[unknown] (80 samples, 0.19%)[unknown] (75 samples, 0.18%)[unknown] (51 samples, 0.12%)[unknown] (46 samples, 0.11%)[unknown] (20 samples, 0.05%)[unknown] (16 samples, 0.04%)[unknown] (8 samples, 0.02%)malloc_consolidate (71 samples, 0.17%)sysmalloc (18 samples, 0.04%)grow_heap (13 samples, 0.03%)__GI_mprotect (13 samples, 0.03%)[unknown] (13 samples, 0.03%)[unknown] (13 samples, 0.03%)[unknown] (13 samples, 0.03%)[unknown] (13 samples, 0.03%)[unknown] (13 samples, 0.03%)[unknown] (10 samples, 0.02%)[unknown] (10 samples, 0.02%)[unknown] (9 samples, 0.02%)[unknown] (8 samples, 0.02%)_int_malloc (206 samples, 0.49%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (60 samples, 0.14%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (15 samples, 0.04%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (13 samples, 0.03%)alloc::vec::Vec<T>::with_capacity (402 samples, 0.95%)alloc::vec::Vec<T,A>::with_capacity_in (402 samples, 0.95%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (402 samples, 0.95%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (402 samples, 0.95%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (402 samples, 0.95%)alloc::alloc::Global::alloc_impl (402 samples, 0.95%)alloc::alloc::alloc (402 samples, 0.95%)__rdl_alloc (402 samples, 0.95%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (402 samples, 0.95%)__GI___libc_malloc (402 samples, 0.95%)core::ptr::drop_in_place<alloc::sync::Arc<tokio::net::udp::UdpSocket>> (19 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (19 samples, 0.04%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (24 samples, 0.06%)tokio::io::ready::Ready::intersection (5 samples, 0.01%)tokio::io::ready::Ready::from_interest (5 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (5 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (55 samples, 0.13%)tokio::net::udp::UdpSocket::ready::{{closure}} (54 samples, 0.13%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (27 samples, 0.06%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (23 samples, 0.05%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (20 samples, 0.05%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (6 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (13 samples, 0.03%)[unknown] (2,299 samples, 5.43%)[unknow..[unknown] (2,285 samples, 5.40%)[unknow..[unknown] (2,266 samples, 5.35%)[unknow..[unknown] (2,243 samples, 5.30%)[unkno..[unknown] (2,045 samples, 4.83%)[unkno..[unknown] (1,928 samples, 4.55%)[unkn..[unknown] (1,828 samples, 4.32%)[unkn..[unknown] (1,505 samples, 3.55%)[unk..[unknown] (1,087 samples, 2.57%)[u..[unknown] (1,002 samples, 2.37%)[u..[unknown] (677 samples, 1.60%)[unknown] (563 samples, 1.33%)[unknown] (354 samples, 0.84%)[unknown] (167 samples, 0.39%)[unknown] (50 samples, 0.12%)[unknown] (12 samples, 0.03%)__libc_recvfrom (2,332 samples, 5.51%)__libc_..__GI___pthread_disable_asynccancel (6 samples, 0.01%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (2,365 samples, 5.58%)tokio::..mio::net::udp::UdpSocket::recv_from (2,352 samples, 5.55%)mio::ne..mio::io_source::IoSource<T>::do_io (2,352 samples, 5.55%)mio::io..mio::sys::unix::stateless_io_source::IoSourceState::do_io (2,352 samples, 5.55%)mio::sy..mio::net::udp::UdpSocket::recv_from::{{closure}} (2,352 samples, 5.55%)mio::ne..std::net::udp::UdpSocket::recv_from (2,352 samples, 5.55%)std::ne..std::sys_common::net::UdpSocket::recv_from (2,352 samples, 5.55%)std::sy..std::sys::pal::unix::net::Socket::recv_from (2,352 samples, 5.55%)std::sy..std::sys::pal::unix::net::Socket::recv_from_with_flags (2,352 samples, 5.55%)std::sy..std::sys_common::net::sockaddr_to_addr (14 samples, 0.03%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (9 samples, 0.02%)_int_malloc (6 samples, 0.01%)__GI___libc_malloc (5 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (2,972 samples, 7.02%)torrust_t..tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (2,479 samples, 5.85%)tokio::..tokio::runtime::io::registration::Registration::async_io::{{closure}} (2,478 samples, 5.85%)tokio::..tokio::runtime::io::registration::Registration::readiness::{{closure}} (25 samples, 0.06%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (15 samples, 0.04%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (6 samples, 0.01%)__memcpy_avx512_unaligned_erms (26 samples, 0.06%)tokio::runtime::context::CONTEXT::__getit (5 samples, 0.01%)core::cell::Cell<T>::get (5 samples, 0.01%)__memcpy_avx512_unaligned_erms (256 samples, 0.60%)core::cell::RefCell<T>::borrow (12 samples, 0.03%)core::cell::RefCell<T>::try_borrow (12 samples, 0.03%)core::cell::BorrowRef::new (12 samples, 0.03%)core::cell::is_reading (8 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (5 samples, 0.01%)__memcpy_avx512_unaligned_erms (70 samples, 0.17%)syscall (364 samples, 0.86%)[unknown] (343 samples, 0.81%)[unknown] (341 samples, 0.81%)[unknown] (329 samples, 0.78%)[unknown] (316 samples, 0.75%)[unknown] (306 samples, 0.72%)[unknown] (240 samples, 0.57%)[unknown] (219 samples, 0.52%)[unknown] (145 samples, 0.34%)[unknown] (102 samples, 0.24%)[unknown] (49 samples, 0.12%)[unknown] (26 samples, 0.06%)[unknown] (15 samples, 0.04%)[unknown] (15 samples, 0.04%)core::ptr::drop_in_place<core::option::Option<tokio::runtime::task::Notified<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (5 samples, 0.01%)core::sync::atomic::AtomicU32::store (5 samples, 0.01%)core::sync::atomic::atomic_store (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::push_back_finish (10 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::push_back_or_overflow (12 samples, 0.03%)tokio::runtime::context::with_scheduler (40 samples, 0.09%)std::thread::local::LocalKey<T>::try_with (37 samples, 0.09%)tokio::runtime::context::with_scheduler::{{closure}} (36 samples, 0.09%)tokio::runtime::context::scoped::Scoped<T>::with (35 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (35 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (35 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (32 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (8 samples, 0.02%)alloc::vec::Vec<T,A>::pop (6 samples, 0.01%)std::sync::mutex::MutexGuard<T>::new (9 samples, 0.02%)std::sync::poison::Flag::guard (9 samples, 0.02%)std::thread::panicking (8 samples, 0.02%)std::panicking::panicking (8 samples, 0.02%)std::panicking::panic_count::count_is_zero (8 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (19 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (19 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (10 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock_contended (5 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (265 samples, 0.63%)core::sync::atomic::atomic_add (265 samples, 0.63%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (309 samples, 0.73%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (280 samples, 0.66%)tokio::runtime::scheduler::multi_thread::idle::State::num_unparked (10 samples, 0.02%)__GI___libc_write (84 samples, 0.20%)__GI___libc_write (84 samples, 0.20%)[unknown] (83 samples, 0.20%)[unknown] (83 samples, 0.20%)[unknown] (83 samples, 0.20%)[unknown] (76 samples, 0.18%)[unknown] (70 samples, 0.17%)[unknown] (67 samples, 0.16%)[unknown] (57 samples, 0.13%)[unknown] (40 samples, 0.09%)[unknown] (40 samples, 0.09%)[unknown] (33 samples, 0.08%)[unknown] (28 samples, 0.07%)[unknown] (15 samples, 0.04%)[unknown] (11 samples, 0.03%)[unknown] (10 samples, 0.02%)[unknown] (7 samples, 0.02%)[unknown] (5 samples, 0.01%)tokio::runtime::driver::Handle::unpark (85 samples, 0.20%)tokio::runtime::driver::IoHandle::unpark (85 samples, 0.20%)tokio::runtime::io::driver::Handle::unpark (85 samples, 0.20%)mio::waker::Waker::wake (85 samples, 0.20%)mio::sys::unix::waker::fdbased::Waker::wake (85 samples, 0.20%)mio::sys::unix::waker::eventfd::WakerInternal::wake (85 samples, 0.20%)<&std::fs::File as std::io::Write>::write (85 samples, 0.20%)std::sys::pal::unix::fs::File::write (85 samples, 0.20%)std::sys::pal::unix::fd::FileDesc::write (85 samples, 0.20%)tokio::runtime::context::with_scheduler (805 samples, 1.90%)t..std::thread::local::LocalKey<T>::try_with (805 samples, 1.90%)s..tokio::runtime::context::with_scheduler::{{closure}} (805 samples, 1.90%)t..tokio::runtime::context::scoped::Scoped<T>::with (805 samples, 1.90%)t..tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (805 samples, 1.90%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (805 samples, 1.90%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (801 samples, 1.89%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (801 samples, 1.89%)t..tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (88 samples, 0.21%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (88 samples, 0.21%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_option_task_without_yield (836 samples, 1.97%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task (836 samples, 1.97%)t..tokio::runtime::scheduler::multi_thread::worker::with_current (836 samples, 1.97%)t..core::ptr::drop_in_place<tokio::util::sharded_list::ShardGuard<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>> (15 samples, 0.04%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>>> (15 samples, 0.04%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (15 samples, 0.04%)std::sync::poison::Flag::done (15 samples, 0.04%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (20 samples, 0.05%)<tokio::runtime::task::Task<S> as tokio::util::sharded_list::ShardedListItem>::get_shard_id (6 samples, 0.01%)tokio::runtime::task::core::Header::get_id (6 samples, 0.01%)core::result::Result<T,E>::is_err (45 samples, 0.11%)core::result::Result<T,E>::is_ok (45 samples, 0.11%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (122 samples, 0.29%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (95 samples, 0.22%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (89 samples, 0.21%)tokio::loom::std::mutex::Mutex<T>::lock (86 samples, 0.20%)std::sync::mutex::Mutex<T>::lock (86 samples, 0.20%)std::sys::sync::mutex::futex::Mutex::lock (85 samples, 0.20%)core::sync::atomic::AtomicU32::compare_exchange (40 samples, 0.09%)core::sync::atomic::atomic_compare_exchange (40 samples, 0.09%)__memcpy_avx512_unaligned_erms (61 samples, 0.14%)__GI___lll_lock_wake_private (13 samples, 0.03%)__memcpy_avx512_unaligned_erms (26 samples, 0.06%)__memcpy_avx512_unaligned_erms (7 samples, 0.02%)__GI___lll_lock_wait_private (94 samples, 0.22%)futex_wait (93 samples, 0.22%)[unknown] (93 samples, 0.22%)[unknown] (93 samples, 0.22%)[unknown] (91 samples, 0.21%)[unknown] (91 samples, 0.21%)[unknown] (90 samples, 0.21%)[unknown] (86 samples, 0.20%)[unknown] (79 samples, 0.19%)[unknown] (41 samples, 0.10%)[unknown] (38 samples, 0.09%)[unknown] (30 samples, 0.07%)[unknown] (26 samples, 0.06%)[unknown] (20 samples, 0.05%)[unknown] (11 samples, 0.03%)__GI___lll_lock_wake_private (151 samples, 0.36%)[unknown] (140 samples, 0.33%)[unknown] (138 samples, 0.33%)[unknown] (133 samples, 0.31%)[unknown] (127 samples, 0.30%)[unknown] (123 samples, 0.29%)[unknown] (85 samples, 0.20%)[unknown] (75 samples, 0.18%)[unknown] (39 samples, 0.09%)[unknown] (25 samples, 0.06%)[unknown] (19 samples, 0.04%)[unknown] (9 samples, 0.02%)[unknown] (8 samples, 0.02%)[unknown] (8 samples, 0.02%)_int_free (21 samples, 0.05%)[unknown] (117 samples, 0.28%)[unknown] (112 samples, 0.26%)[unknown] (108 samples, 0.26%)[unknown] (104 samples, 0.25%)[unknown] (101 samples, 0.24%)[unknown] (94 samples, 0.22%)[unknown] (88 samples, 0.21%)[unknown] (80 samples, 0.19%)[unknown] (72 samples, 0.17%)[unknown] (55 samples, 0.13%)[unknown] (43 samples, 0.10%)[unknown] (30 samples, 0.07%)[unknown] (9 samples, 0.02%)sysmalloc (326 samples, 0.77%)grow_heap (201 samples, 0.47%)__GI_mprotect (200 samples, 0.47%)[unknown] (198 samples, 0.47%)[unknown] (195 samples, 0.46%)[unknown] (192 samples, 0.45%)[unknown] (192 samples, 0.45%)[unknown] (187 samples, 0.44%)[unknown] (178 samples, 0.42%)[unknown] (162 samples, 0.38%)[unknown] (139 samples, 0.33%)[unknown] (120 samples, 0.28%)[unknown] (91 samples, 0.21%)[unknown] (62 samples, 0.15%)[unknown] (34 samples, 0.08%)[unknown] (13 samples, 0.03%)core::option::Option<T>::map (1,857 samples, 4.38%)core:..tokio::task::spawn::spawn_inner::{{closure}} (1,857 samples, 4.38%)tokio..tokio::runtime::scheduler::Handle::spawn (1,857 samples, 4.38%)tokio..tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (1,857 samples, 4.38%)tokio..tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (1,856 samples, 4.38%)tokio..tokio::runtime::task::list::OwnedTasks<S>::bind (935 samples, 2.21%)t..tokio::runtime::task::new_task (803 samples, 1.90%)t..tokio::runtime::task::raw::RawTask::new (803 samples, 1.90%)t..tokio::runtime::task::core::Cell<T,S>::new (803 samples, 1.90%)t..alloc::boxed::Box<T>::new (737 samples, 1.74%)alloc::alloc::exchange_malloc (697 samples, 1.65%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (693 samples, 1.64%)alloc::alloc::Global::alloc_impl (693 samples, 1.64%)alloc::alloc::alloc (693 samples, 1.64%)__rdl_alloc (693 samples, 1.64%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (693 samples, 1.64%)std::sys::pal::unix::alloc::aligned_malloc (693 samples, 1.64%)__posix_memalign (684 samples, 1.62%)__posix_memalign (683 samples, 1.61%)_mid_memalign (683 samples, 1.61%)_int_memalign (423 samples, 1.00%)_int_malloc (395 samples, 0.93%)unlink_chunk (8 samples, 0.02%)tokio::runtime::context::current::with_current (2,163 samples, 5.11%)tokio:..std::thread::local::LocalKey<T>::try_with (2,163 samples, 5.11%)std::t..tokio::runtime::context::current::with_current::{{closure}} (2,128 samples, 5.02%)tokio:..tokio::task::spawn::spawn (2,169 samples, 5.12%)tokio:..tokio::task::spawn::spawn_inner (2,169 samples, 5.12%)tokio:..tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (19,388 samples, 45.78%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (19,388 samples, 45.78%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (5,501 samples, 12.99%)torrust_tracker::ser..torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (5,501 samples, 12.99%)torrust_tracker::ser..torrust_tracker::servers::udp::server::Udp::spawn_request_processor (2,174 samples, 5.13%)torrus..torrust_tracker::servers::udp::server::Udp::process_request (5 samples, 0.01%)__memcpy_avx512_unaligned_erms (5 samples, 0.01%)__memcpy_avx512_unaligned_erms (212 samples, 0.50%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (217 samples, 0.51%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (217 samples, 0.51%)tokio::runtime::task::core::Core<T,S>::poll (19,613 samples, 46.31%)tokio::runtime::task::core::Core<T,S>::polltokio::runtime::task::core::Core<T,S>::drop_future_or_output (225 samples, 0.53%)tokio::runtime::task::core::Core<T,S>::set_stage (225 samples, 0.53%)__memcpy_avx512_unaligned_erms (103 samples, 0.24%)__memcpy_avx512_unaligned_erms (170 samples, 0.40%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (176 samples, 0.42%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (175 samples, 0.41%)tokio::runtime::task::harness::poll_future (19,897 samples, 46.98%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (19,897 samples, 46.98%)std::panic::catch_unwindstd::panicking::try (19,897 samples, 46.98%)std::panicking::trystd::panicking::try::do_call (19,897 samples, 46.98%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (19,897 samples, 46.98%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce..tokio::runtime::task::harness::poll_future::{{closure}} (19,897 samples, 46.98%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::store_output (284 samples, 0.67%)tokio::runtime::task::core::Core<T,S>::set_stage (283 samples, 0.67%)tokio::runtime::coop::budget (20,267 samples, 47.85%)tokio::runtime::coop::budgettokio::runtime::coop::with_budget (20,267 samples, 47.85%)tokio::runtime::coop::with_budgettokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (20,263 samples, 47.84%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}}tokio::runtime::task::LocalNotified<S>::run (20,262 samples, 47.84%)tokio::runtime::task::LocalNotified<S>::runtokio::runtime::task::raw::RawTask::poll (20,262 samples, 47.84%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (20,196 samples, 47.69%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (20,187 samples, 47.66%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (19,945 samples, 47.09%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::task::state::State::transition_to_running (36 samples, 0.09%)tokio::runtime::task::state::State::fetch_update_action (36 samples, 0.09%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (9 samples, 0.02%)syscall (665 samples, 1.57%)[unknown] (643 samples, 1.52%)[unknown] (638 samples, 1.51%)[unknown] (583 samples, 1.38%)[unknown] (558 samples, 1.32%)[unknown] (537 samples, 1.27%)[unknown] (435 samples, 1.03%)[unknown] (392 samples, 0.93%)[unknown] (332 samples, 0.78%)[unknown] (205 samples, 0.48%)[unknown] (110 samples, 0.26%)[unknown] (21 samples, 0.05%)[unknown] (7 samples, 0.02%)[unknown] (7 samples, 0.02%)alloc::vec::Vec<T,A>::pop (9 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (11 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (10 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (7 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock_contended (5 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::spin (5 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (132 samples, 0.31%)core::sync::atomic::AtomicUsize::fetch_add (132 samples, 0.31%)core::sync::atomic::atomic_add (132 samples, 0.31%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (154 samples, 0.36%)[unknown] (231 samples, 0.55%)[unknown] (228 samples, 0.54%)[unknown] (218 samples, 0.51%)[unknown] (215 samples, 0.51%)[unknown] (197 samples, 0.47%)[unknown] (192 samples, 0.45%)[unknown] (163 samples, 0.38%)[unknown] (99 samples, 0.23%)[unknown] (92 samples, 0.22%)[unknown] (73 samples, 0.17%)[unknown] (67 samples, 0.16%)[unknown] (35 samples, 0.08%)[unknown] (31 samples, 0.07%)[unknown] (22 samples, 0.05%)[unknown] (16 samples, 0.04%)[unknown] (10 samples, 0.02%)[unknown] (8 samples, 0.02%)__GI___libc_write (245 samples, 0.58%)__GI___libc_write (245 samples, 0.58%)mio::sys::unix::waker::eventfd::WakerInternal::wake (246 samples, 0.58%)<&std::fs::File as std::io::Write>::write (246 samples, 0.58%)std::sys::pal::unix::fs::File::write (246 samples, 0.58%)std::sys::pal::unix::fd::FileDesc::write (246 samples, 0.58%)tokio::runtime::driver::Handle::unpark (264 samples, 0.62%)tokio::runtime::driver::IoHandle::unpark (264 samples, 0.62%)tokio::runtime::io::driver::Handle::unpark (264 samples, 0.62%)mio::waker::Waker::wake (263 samples, 0.62%)mio::sys::unix::waker::fdbased::Waker::wake (263 samples, 0.62%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (17 samples, 0.04%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (17 samples, 0.04%)tokio::runtime::driver::Handle::unpark (17 samples, 0.04%)tokio::runtime::driver::IoHandle::unpark (17 samples, 0.04%)[unknown] (15 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (21,372 samples, 50.46%)tokio::runtime::scheduler::multi_thread::worker::Context::run_tasktokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (1,087 samples, 2.57%)to..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (1,087 samples, 2.57%)to..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (1,087 samples, 2.57%)to..tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (268 samples, 0.63%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (267 samples, 0.63%)core::option::Option<T>::or_else (8 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (8 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (8 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (9 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (19 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (17 samples, 0.04%)alloc::sync::Arc<T,A>::inner (17 samples, 0.04%)core::ptr::non_null::NonNull<T>::as_ref (17 samples, 0.04%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (40 samples, 0.09%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (40 samples, 0.09%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (40 samples, 0.09%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (15 samples, 0.04%)alloc::sync::Arc<T,A>::inner (15 samples, 0.04%)core::ptr::non_null::NonNull<T>::as_ref (15 samples, 0.04%)core::num::<impl u32>::wrapping_sub (42 samples, 0.10%)core::sync::atomic::AtomicU64::load (17 samples, 0.04%)core::sync::atomic::atomic_load (17 samples, 0.04%)tokio::loom::std::atomic_u32::AtomicU32::unsync_load (13 samples, 0.03%)core::sync::atomic::AtomicU32::load (13 samples, 0.03%)core::sync::atomic::atomic_load (13 samples, 0.03%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (23 samples, 0.05%)alloc::sync::Arc<T,A>::inner (23 samples, 0.05%)core::ptr::non_null::NonNull<T>::as_ref (23 samples, 0.05%)core::num::<impl u32>::wrapping_add (8 samples, 0.02%)core::num::<impl u32>::wrapping_sub (16 samples, 0.04%)core::sync::atomic::AtomicU32::load (19 samples, 0.04%)core::sync::atomic::atomic_load (19 samples, 0.04%)core::sync::atomic::AtomicU64::load (46 samples, 0.11%)core::sync::atomic::atomic_load (46 samples, 0.11%)tokio::runtime::scheduler::multi_thread::queue::pack (33 samples, 0.08%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (306 samples, 0.72%)tokio::runtime::scheduler::multi_thread::queue::unpack (58 samples, 0.14%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (419 samples, 0.99%)tokio::runtime::scheduler::multi_thread::queue::unpack (10 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_searching (41 samples, 0.10%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_searching (11 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (898 samples, 2.12%)t..tokio::util::rand::FastRand::fastrand_n (8 samples, 0.02%)tokio::util::rand::FastRand::fastrand (8 samples, 0.02%)std::panic::catch_unwind (29,494 samples, 69.64%)std::panic::catch_unwindstd::panicking::try (29,494 samples, 69.64%)std::panicking::trystd::panicking::try::do_call (29,494 samples, 69.64%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (29,494 samples, 69.64%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncestd::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}} (29,494 samples, 69.64%)std::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}}std::sys_common::backtrace::__rust_begin_short_backtrace (29,494 samples, 69.64%)std::sys_common::backtrace::__rust_begin_short_backtracetokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}} (29,494 samples, 69.64%)tokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}}tokio::runtime::blocking::pool::Inner::run (29,494 samples, 69.64%)tokio::runtime::blocking::pool::Inner::runtokio::runtime::blocking::pool::Task::run (29,415 samples, 69.45%)tokio::runtime::blocking::pool::Task::runtokio::runtime::task::UnownedTask<S>::run (29,415 samples, 69.45%)tokio::runtime::task::UnownedTask<S>::runtokio::runtime::task::raw::RawTask::poll (29,415 samples, 69.45%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (29,415 samples, 69.45%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (29,415 samples, 69.45%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (29,415 samples, 69.45%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::task::harness::poll_future (29,415 samples, 69.45%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (29,415 samples, 69.45%)std::panic::catch_unwindstd::panicking::try (29,415 samples, 69.45%)std::panicking::trystd::panicking::try::do_call (29,415 samples, 69.45%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (29,415 samples, 69.45%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncetokio::runtime::task::harness::poll_future::{{closure}} (29,415 samples, 69.45%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::poll (29,415 samples, 69.45%)tokio::runtime::task::core::Core<T,S>::polltokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (29,415 samples, 69.45%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (29,415 samples, 69.45%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (29,415 samples, 69.45%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::polltokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (29,415 samples, 69.45%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}}tokio::runtime::scheduler::multi_thread::worker::run (29,415 samples, 69.45%)tokio::runtime::scheduler::multi_thread::worker::runtokio::runtime::context::runtime::enter_runtime (29,415 samples, 69.45%)tokio::runtime::context::runtime::enter_runtimetokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (29,415 samples, 69.45%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}tokio::runtime::context::set_scheduler (29,415 samples, 69.45%)tokio::runtime::context::set_schedulerstd::thread::local::LocalKey<T>::with (29,415 samples, 69.45%)std::thread::local::LocalKey<T>::withstd::thread::local::LocalKey<T>::try_with (29,415 samples, 69.45%)std::thread::local::LocalKey<T>::try_withtokio::runtime::context::set_scheduler::{{closure}} (29,415 samples, 69.45%)tokio::runtime::context::set_scheduler::{{closure}}tokio::runtime::context::scoped::Scoped<T>::set (29,415 samples, 69.45%)tokio::runtime::context::scoped::Scoped<T>::settokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (29,415 samples, 69.45%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}}tokio::runtime::scheduler::multi_thread::worker::Context::run (29,415 samples, 69.45%)tokio::runtime::scheduler::multi_thread::worker::Context::run<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (29,496 samples, 69.64%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (29,496 samples, 69.64%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_oncecore::ops::function::FnOnce::call_once{{vtable.shim}} (29,496 samples, 69.64%)core::ops::function::FnOnce::call_once{{vtable.shim}}std::thread::Builder::spawn_unchecked_::{{closure}} (29,496 samples, 69.64%)std::thread::Builder::spawn_unchecked_::{{closure}}__GI_munmap (26 samples, 0.06%)[unknown] (26 samples, 0.06%)[unknown] (26 samples, 0.06%)[unknown] (26 samples, 0.06%)[unknown] (26 samples, 0.06%)[unknown] (26 samples, 0.06%)[unknown] (26 samples, 0.06%)[unknown] (25 samples, 0.06%)[unknown] (23 samples, 0.05%)[unknown] (19 samples, 0.04%)[unknown] (19 samples, 0.04%)[unknown] (18 samples, 0.04%)[unknown] (13 samples, 0.03%)[unknown] (12 samples, 0.03%)[unknown] (5 samples, 0.01%)clone3 (29,548 samples, 69.77%)clone3start_thread (29,548 samples, 69.77%)start_threadstd::sys::pal::unix::thread::Thread::new::thread_start (29,523 samples, 69.71%)std::sys::pal::unix::thread::Thread::new::thread_startcore::ptr::drop_in_place<std::sys::pal::unix::stack_overflow::Handler> (27 samples, 0.06%)<std::sys::pal::unix::stack_overflow::Handler as core::ops::drop::Drop>::drop (27 samples, 0.06%)std::sys::pal::unix::stack_overflow::imp::drop_handler (27 samples, 0.06%)core::fmt::Formatter::pad_integral (7 samples, 0.02%)rand_chacha::guts::round (6 samples, 0.01%)rand_chacha::guts::refill_wide::impl_avx2 (8 samples, 0.02%)rand_chacha::guts::refill_wide::fn_impl (8 samples, 0.02%)rand_chacha::guts::refill_wide_impl (8 samples, 0.02%)[unknown] (5 samples, 0.01%)core::ptr::drop_in_place<core::result::Result<tokio::runtime::coop::with_budget::ResetGuard,std::thread::local::AccessError>> (5 samples, 0.01%)core::cell::RefCell<T>::borrow_mut (12 samples, 0.03%)core::cell::RefCell<T>::try_borrow_mut (12 samples, 0.03%)core::cell::BorrowRefMut::new (12 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (20 samples, 0.05%)tokio::runtime::coop::budget (20 samples, 0.05%)tokio::runtime::coop::with_budget (20 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (15 samples, 0.04%)std::sys::pal::unix::time::Timespec::now (36 samples, 0.09%)std::sys::pal::unix::time::Timespec::sub_timespec (16 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (12 samples, 0.03%)core::array::<impl core::default::Default for [T: 32]>::default (6 samples, 0.01%)std::sys_common::thread_info::set (19 samples, 0.04%)std::thread::local::LocalKey<T>::with (19 samples, 0.04%)std::thread::local::LocalKey<T>::try_with (19 samples, 0.04%)std::sys_common::thread_info::THREAD_INFO::__getit (19 samples, 0.04%)std::sys::thread_local::fast_local::Key<T>::register_dtor (19 samples, 0.04%)__cxa_thread_atexit_impl (19 samples, 0.04%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (19 samples, 0.04%)syscall (5 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (14 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (14 samples, 0.03%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::run (13 samples, 0.03%)tokio::runtime::context::runtime::enter_runtime (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (13 samples, 0.03%)tokio::runtime::context::set_scheduler (13 samples, 0.03%)std::thread::local::LocalKey<T>::with (13 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (13 samples, 0.03%)tokio::runtime::context::set_scheduler::{{closure}} (13 samples, 0.03%)tokio::runtime::context::scoped::Scoped<T>::set (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (5 samples, 0.01%)tokio::runtime::task::raw::poll (19 samples, 0.04%)tokio::runtime::task::harness::Harness<T,S>::poll (18 samples, 0.04%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (18 samples, 0.04%)tokio::runtime::task::harness::poll_future (18 samples, 0.04%)std::panic::catch_unwind (18 samples, 0.04%)std::panicking::try (18 samples, 0.04%)std::panicking::try::do_call (18 samples, 0.04%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (18 samples, 0.04%)tokio::runtime::task::harness::poll_future::{{closure}} (18 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::poll (18 samples, 0.04%)torrust_tracker::servers::http::v1::routes::router::{{closure}}::__CALLSITE::META (5 samples, 0.01%)__libc_calloc (23 samples, 0.05%)__memcpy_avx512_unaligned_erms (75 samples, 0.18%)_int_free (61 samples, 0.14%)[unknown] (37 samples, 0.09%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE::META (170 samples, 0.40%)__GI___lll_lock_wait_private (39 samples, 0.09%)futex_wait (25 samples, 0.06%)futex_fatal_error (16 samples, 0.04%)__memcpy_avx512_unaligned_erms (90 samples, 0.21%)_int_malloc (8 samples, 0.02%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE (144 samples, 0.34%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (10 samples, 0.02%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (13 samples, 0.03%)<torrust_tracker::core::torrent::repository::RepositoryAsyncSingle as torrust_tracker::core::torrent::repository::TRepositoryAsync>::update_torrent_with_peer_and_get_stats::{{closure}} (12 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (31 samples, 0.07%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (22 samples, 0.05%)torrust_tracker::core::Tracker::announce::{{closure}} (17 samples, 0.04%)<T as alloc::string::ToString>::to_string (5 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (7 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (46 samples, 0.11%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (55 samples, 0.13%)ringbuf::ring_buffer::rb::Rb::push_overwrite (5 samples, 0.01%)__GI___libc_malloc (12 samples, 0.03%)alloc::vec::Vec<T>::with_capacity (21 samples, 0.05%)alloc::vec::Vec<T,A>::with_capacity_in (21 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (21 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (21 samples, 0.05%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (21 samples, 0.05%)alloc::alloc::Global::alloc_impl (21 samples, 0.05%)alloc::alloc::alloc (21 samples, 0.05%)__rdl_alloc (21 samples, 0.05%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (21 samples, 0.05%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (20 samples, 0.05%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (20 samples, 0.05%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (20 samples, 0.05%)_int_malloc (13 samples, 0.03%)tokio::net::udp::UdpSocket::readable::{{closure}} (8 samples, 0.02%)tokio::net::udp::UdpSocket::ready::{{closure}} (7 samples, 0.02%)[unknown] (10 samples, 0.02%)[unknown] (13 samples, 0.03%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (69 samples, 0.16%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (37 samples, 0.09%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (37 samples, 0.09%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (22 samples, 0.05%)mio::net::udp::UdpSocket::recv_from (21 samples, 0.05%)mio::io_source::IoSource<T>::do_io (21 samples, 0.05%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (21 samples, 0.05%)mio::net::udp::UdpSocket::recv_from::{{closure}} (21 samples, 0.05%)std::net::udp::UdpSocket::recv_from (21 samples, 0.05%)std::sys_common::net::UdpSocket::recv_from (21 samples, 0.05%)std::sys::pal::unix::net::Socket::recv_from (21 samples, 0.05%)std::sys::pal::unix::net::Socket::recv_from_with_flags (21 samples, 0.05%)core::mem::zeroed (8 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::zeroed (8 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::write_bytes (8 samples, 0.02%)core::intrinsics::write_bytes (8 samples, 0.02%)[unknown] (8 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_option_task_without_yield (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::with_current (13 samples, 0.03%)tokio::runtime::context::with_scheduler (13 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (13 samples, 0.03%)tokio::runtime::context::with_scheduler::{{closure}} (13 samples, 0.03%)tokio::runtime::context::scoped::Scoped<T>::with (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (13 samples, 0.03%)tokio::runtime::driver::Handle::unpark (13 samples, 0.03%)tokio::runtime::driver::IoHandle::unpark (13 samples, 0.03%)tokio::runtime::io::driver::Handle::unpark (13 samples, 0.03%)mio::waker::Waker::wake (13 samples, 0.03%)mio::sys::unix::waker::fdbased::Waker::wake (13 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (12 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (12 samples, 0.03%)tokio::runtime::driver::Handle::unpark (12 samples, 0.03%)tokio::runtime::driver::IoHandle::unpark (12 samples, 0.03%)[unknown] (10 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (105 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (105 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (22 samples, 0.05%)tokio::task::spawn::spawn (22 samples, 0.05%)tokio::task::spawn::spawn_inner (22 samples, 0.05%)tokio::runtime::context::current::with_current (22 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (22 samples, 0.05%)tokio::runtime::context::current::with_current::{{closure}} (22 samples, 0.05%)core::option::Option<T>::map (22 samples, 0.05%)tokio::task::spawn::spawn_inner::{{closure}} (22 samples, 0.05%)tokio::runtime::scheduler::Handle::spawn (22 samples, 0.05%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (22 samples, 0.05%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (22 samples, 0.05%)tokio::runtime::task::list::OwnedTasks<S>::bind (9 samples, 0.02%)tokio::runtime::task::new_task (5 samples, 0.01%)tokio::runtime::task::raw::RawTask::new (5 samples, 0.01%)tokio::runtime::task::core::Cell<T,S>::new (5 samples, 0.01%)all (42,352 samples, 100%)tokio-runtime-w (42,171 samples, 99.57%)tokio-runtime-w \ No newline at end of file From fbd046904536c96682dfc8f0accbe92ea754e5a1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 21 Mar 2024 19:13:44 +0000 Subject: [PATCH 0264/1297] fix: revert number of active UDP request to previous value It was pushed accidentally trying different configurations for benchmarking. --- src/servers/udp/server.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 98c4bf726..7086b6ab7 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -203,7 +203,7 @@ impl Launcher { #[derive(Default)] struct ActiveRequests { - rb: StaticRb, // the number of requests we handle at the same time. + rb: StaticRb, // the number of requests we handle at the same time. } impl std::fmt::Debug for ActiveRequests { From 5c0047aadfb08c05f9ba603fb139b29b69924954 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 25 Mar 2024 11:21:03 +0800 Subject: [PATCH 0265/1297] dev: refactor torrent repository extracted async and sync implementations --- cSpell.json | 1 + .../src/benches/asyn.rs | 41 ++- .../src/benches/sync.rs | 42 +-- .../torrent-repository-benchmarks/src/main.rs | 50 +-- src/core/mod.rs | 8 +- src/core/services/torrent.rs | 1 + src/core/torrent/mod.rs | 7 +- src/core/torrent/repository.rs | 301 ------------------ src/core/torrent/repository_asyn.rs | 188 +++++++++++ src/core/torrent/repository_sync.rs | 122 +++++++ tests/servers/health_check_api/environment.rs | 1 + tests/servers/http/responses/scrape.rs | 4 + 12 files changed, 402 insertions(+), 364 deletions(-) delete mode 100644 src/core/torrent/repository.rs create mode 100644 src/core/torrent/repository_asyn.rs create mode 100644 src/core/torrent/repository_sync.rs diff --git a/cSpell.json b/cSpell.json index 16dff714e..6d8b68c92 100644 --- a/cSpell.json +++ b/cSpell.json @@ -5,6 +5,7 @@ "alekitto", "appuser", "Arvid", + "asyn", "autoclean", "AUTOINCREMENT", "automock", diff --git a/packages/torrent-repository-benchmarks/src/benches/asyn.rs b/packages/torrent-repository-benchmarks/src/benches/asyn.rs index 33f9e85fa..9482d821c 100644 --- a/packages/torrent-repository-benchmarks/src/benches/asyn.rs +++ b/packages/torrent-repository-benchmarks/src/benches/asyn.rs @@ -3,17 +3,20 @@ use std::time::Duration; use clap::Parser; use futures::stream::FuturesUnordered; -use torrust_tracker::core::torrent::repository::TRepositoryAsync; +use torrust_tracker::core::torrent::repository_asyn::{RepositoryAsync, RepositoryTokioRwLock}; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use crate::args::Args; use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; -pub async fn async_add_one_torrent(samples: usize) -> (Duration, Duration) { +pub async fn async_add_one_torrent(samples: usize) -> (Duration, Duration) +where + RepositoryTokioRwLock: RepositoryAsync, +{ let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(T::new()); + let torrent_repository = Arc::new(RepositoryTokioRwLock::::default()); let info_hash = InfoHash([0; 20]); @@ -32,15 +35,16 @@ pub async fn async_add_one_torrent( } // Add one torrent ten thousand times in parallel (depending on the set worker threads) -pub async fn async_update_one_torrent_in_parallel( - runtime: &tokio::runtime::Runtime, - samples: usize, -) -> (Duration, Duration) { +pub async fn async_update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +where + T: Send + Sync + 'static, + RepositoryTokioRwLock: RepositoryAsync, +{ let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(T::new()); + let torrent_repository = Arc::new(RepositoryTokioRwLock::::default()); let info_hash: &'static InfoHash = &InfoHash([0; 20]); let handles = FuturesUnordered::new(); @@ -81,15 +85,16 @@ pub async fn async_update_one_torrent_in_parallel( - runtime: &tokio::runtime::Runtime, - samples: usize, -) -> (Duration, Duration) { +pub async fn async_add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +where + T: Send + Sync + 'static, + RepositoryTokioRwLock: RepositoryAsync, +{ let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(T::new()); + let torrent_repository = Arc::new(RepositoryTokioRwLock::::default()); let info_hashes = generate_unique_info_hashes(10_000); let handles = FuturesUnordered::new(); @@ -125,15 +130,19 @@ pub async fn async_add_multiple_torrents_in_parallel( +pub async fn async_update_multiple_torrents_in_parallel( runtime: &tokio::runtime::Runtime, samples: usize, -) -> (Duration, Duration) { +) -> (Duration, Duration) +where + T: Send + Sync + 'static, + RepositoryTokioRwLock: RepositoryAsync, +{ let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(T::new()); + let torrent_repository = Arc::new(RepositoryTokioRwLock::::default()); let info_hashes = generate_unique_info_hashes(10_000); let handles = FuturesUnordered::new(); diff --git a/packages/torrent-repository-benchmarks/src/benches/sync.rs b/packages/torrent-repository-benchmarks/src/benches/sync.rs index dac7ab810..c37fa9f4a 100644 --- a/packages/torrent-repository-benchmarks/src/benches/sync.rs +++ b/packages/torrent-repository-benchmarks/src/benches/sync.rs @@ -3,7 +3,7 @@ use std::time::Duration; use clap::Parser; use futures::stream::FuturesUnordered; -use torrust_tracker::core::torrent::repository::Repository; +use torrust_tracker::core::torrent::repository_sync::{RepositoryStdRwLock, RepositorySync}; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use crate::args::Args; @@ -11,11 +11,14 @@ use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjuste // Simply add one torrent #[must_use] -pub fn add_one_torrent(samples: usize) -> (Duration, Duration) { +pub fn add_one_torrent(samples: usize) -> (Duration, Duration) +where + RepositoryStdRwLock: RepositorySync, +{ let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(T::new()); + let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); let info_hash = InfoHash([0; 20]); @@ -32,15 +35,16 @@ pub fn add_one_torrent(samples: usize) -> } // Add one torrent ten thousand times in parallel (depending on the set worker threads) -pub async fn update_one_torrent_in_parallel( - runtime: &tokio::runtime::Runtime, - samples: usize, -) -> (Duration, Duration) { +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +where + T: Send + Sync + 'static, + RepositoryStdRwLock: RepositorySync, +{ let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(T::new()); + let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); let info_hash: &'static InfoHash = &InfoHash([0; 20]); let handles = FuturesUnordered::new(); @@ -77,15 +81,16 @@ pub async fn update_one_torrent_in_parallel( - runtime: &tokio::runtime::Runtime, - samples: usize, -) -> (Duration, Duration) { +pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +where + T: Send + Sync + 'static, + RepositoryStdRwLock: RepositorySync, +{ let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(T::new()); + let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); let info_hashes = generate_unique_info_hashes(10_000); let handles = FuturesUnordered::new(); @@ -119,15 +124,16 @@ pub async fn add_multiple_torrents_in_parallel( - runtime: &tokio::runtime::Runtime, - samples: usize, -) -> (Duration, Duration) { +pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +where + T: Send + Sync + 'static, + RepositoryStdRwLock: RepositorySync, +{ let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(T::new()); + let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); let info_hashes = generate_unique_info_hashes(10_000); let handles = FuturesUnordered::new(); diff --git a/packages/torrent-repository-benchmarks/src/main.rs b/packages/torrent-repository-benchmarks/src/main.rs index 0d9db73ac..eab8e3803 100644 --- a/packages/torrent-repository-benchmarks/src/main.rs +++ b/packages/torrent-repository-benchmarks/src/main.rs @@ -7,7 +7,7 @@ use torrust_torrent_repository_benchmarks::benches::asyn::{ use torrust_torrent_repository_benchmarks::benches::sync::{ add_multiple_torrents_in_parallel, add_one_torrent, update_multiple_torrents_in_parallel, update_one_torrent_in_parallel, }; -use torrust_tracker::core::torrent::repository::{AsyncSync, RepositoryAsync, RepositoryAsyncSingle, Sync, SyncSingle}; +use torrust_tracker::core::torrent::{Entry, EntryMutexStd, EntryMutexTokio}; #[allow(clippy::too_many_lines)] #[allow(clippy::print_literal)] @@ -25,67 +25,67 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(async_add_one_torrent::(1_000_000)) + rt.block_on(async_add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(async_update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(async_update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(async_add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(async_add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(async_update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(async_update_multiple_torrents_in_parallel::(&rt, 10)) ); if let Some(true) = args.compare { println!(); println!("std::sync::RwLock>"); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_one_torrent", - add_one_torrent::(1_000_000) - ); + println!("{}: Avg/AdjAvg: {:?}", "add_one_torrent", add_one_torrent::(1_000_000)); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(update_multiple_torrents_in_parallel::(&rt, 10)) ); println!(); println!("std::sync::RwLock>>>"); - println!("{}: Avg/AdjAvg: {:?}", "add_one_torrent", add_one_torrent::(1_000_000)); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_one_torrent", + add_one_torrent::(1_000_000) + ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(update_multiple_torrents_in_parallel::(&rt, 10)) ); println!(); @@ -94,22 +94,22 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(async_add_one_torrent::(1_000_000)) + rt.block_on(async_add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(async_update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(async_update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(async_add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(async_add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(async_update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(async_update_multiple_torrents_in_parallel::(&rt, 10)) ); println!(); @@ -118,22 +118,22 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(async_add_one_torrent::(1_000_000)) + rt.block_on(async_add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(async_update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(async_update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(async_add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(async_add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(async_update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(async_update_multiple_torrents_in_parallel::(&rt, 10)) ); } } diff --git a/src/core/mod.rs b/src/core/mod.rs index dac298462..c392ead75 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -455,7 +455,8 @@ use torrust_tracker_primitives::TrackerMode; use self::auth::Key; use self::error::Error; use self::peer::Peer; -use self::torrent::repository::{RepositoryAsyncSingle, TRepositoryAsync}; +use self::torrent::repository_asyn::{RepositoryAsync, RepositoryTokioRwLock}; +use self::torrent::Entry; use crate::core::databases::Database; use crate::core::torrent::{SwarmMetadata, SwarmStats}; use crate::shared::bit_torrent::info_hash::InfoHash; @@ -481,7 +482,7 @@ pub struct Tracker { policy: TrackerPolicy, keys: tokio::sync::RwLock>, whitelist: tokio::sync::RwLock>, - pub torrents: Arc, + pub torrents: Arc>, stats_event_sender: Option>, stats_repository: statistics::Repo, external_ip: Option, @@ -579,7 +580,7 @@ impl Tracker { mode, keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), - torrents: Arc::new(RepositoryAsyncSingle::new()), + torrents: Arc::new(RepositoryTokioRwLock::::default()), stats_event_sender, stats_repository, database, @@ -1754,6 +1755,7 @@ mod tests { use aquatic_udp_protocol::AnnounceEvent; use crate::core::tests::the_tracker::{sample_info_hash, sample_peer, tracker_persisting_torrents_in_database}; + use crate::core::torrent::repository_asyn::RepositoryAsync; #[tokio::test] async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index fc24e7c4c..eca6cbf3b 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -9,6 +9,7 @@ use std::sync::Arc; use serde::Deserialize; use crate::core::peer::Peer; +use crate::core::torrent::repository_asyn::RepositoryAsync; use crate::core::Tracker; use crate::shared::bit_torrent::info_hash::InfoHash; diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index c4a1b0df9..b5ebb1054 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -28,8 +28,10 @@ //! Peer that don not have a full copy of the torrent data are called "leechers". //! //! > **NOTICE**: that both [`SwarmMetadata`] and [`SwarmStats`] contain the same information. [`SwarmMetadata`] is using the names used on [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). -pub mod repository; +pub mod repository_asyn; +pub mod repository_sync; +use std::sync::Arc; use std::time::Duration; use aquatic_udp_protocol::AnnounceEvent; @@ -53,6 +55,9 @@ pub struct Entry { pub completed: u32, } +pub type EntryMutexTokio = Arc>; +pub type EntryMutexStd = Arc>; + /// Swarm statistics for one torrent. /// Swarm metadata dictionary in the scrape response. /// diff --git a/src/core/torrent/repository.rs b/src/core/torrent/repository.rs deleted file mode 100644 index d4f8ee5e3..000000000 --- a/src/core/torrent/repository.rs +++ /dev/null @@ -1,301 +0,0 @@ -use std::sync::Arc; - -use crate::core::peer; -use crate::core::torrent::{Entry, SwarmStats}; -use crate::shared::bit_torrent::info_hash::InfoHash; - -pub trait Repository { - fn new() -> Self; - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool); -} - -pub trait TRepositoryAsync { - fn new() -> Self; - fn update_torrent_with_peer_and_get_stats( - &self, - info_hash: &InfoHash, - peer: &peer::Peer, - ) -> impl std::future::Future + Send; -} - -/// Structure that holds all torrents. Using `std::sync` locks. -pub struct Sync { - torrents: std::sync::RwLock>>>, -} - -impl Sync { - /// Returns the get torrents of this [`Sync`]. - /// - /// # Panics - /// - /// Panics if unable to read the torrent. - pub fn get_torrents( - &self, - ) -> std::sync::RwLockReadGuard<'_, std::collections::BTreeMap>>> { - self.torrents.read().expect("unable to get torrent list") - } - - /// Returns the mutable get torrents of this [`Sync`]. - /// - /// # Panics - /// - /// Panics if unable to write to the torrents list. - pub fn get_torrents_mut( - &self, - ) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap>>> { - self.torrents.write().expect("unable to get writable torrent list") - } -} - -impl Repository for Sync { - fn new() -> Self { - Self { - torrents: std::sync::RwLock::new(std::collections::BTreeMap::new()), - } - } - - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { - let maybe_existing_torrent_entry = self.get_torrents().get(info_hash).cloned(); - - let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { - existing_torrent_entry - } else { - let mut torrents_lock = self.get_torrents_mut(); - let entry = torrents_lock - .entry(*info_hash) - .or_insert(Arc::new(std::sync::Mutex::new(Entry::new()))); - entry.clone() - }; - - let (stats, stats_updated) = { - let mut torrent_entry_lock = torrent_entry.lock().unwrap(); - let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); - let stats = torrent_entry_lock.get_stats(); - - (stats, stats_updated) - }; - - ( - SwarmStats { - downloaded: stats.1, - complete: stats.0, - incomplete: stats.2, - }, - stats_updated, - ) - } -} - -/// Structure that holds all torrents. Using `std::sync` locks. -pub struct SyncSingle { - torrents: std::sync::RwLock>, -} - -impl SyncSingle { - /// Returns the get torrents of this [`SyncSingle`]. - /// - /// # Panics - /// - /// Panics if unable to get torrent list. - pub fn get_torrents(&self) -> std::sync::RwLockReadGuard<'_, std::collections::BTreeMap> { - self.torrents.read().expect("unable to get torrent list") - } - - /// Returns the get torrents of this [`SyncSingle`]. - /// - /// # Panics - /// - /// Panics if unable to get writable torrent list. - pub fn get_torrents_mut(&self) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { - self.torrents.write().expect("unable to get writable torrent list") - } -} - -impl Repository for SyncSingle { - fn new() -> Self { - Self { - torrents: std::sync::RwLock::new(std::collections::BTreeMap::new()), - } - } - - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { - let mut torrents = self.torrents.write().unwrap(); - - let torrent_entry = match torrents.entry(*info_hash) { - std::collections::btree_map::Entry::Vacant(vacant) => vacant.insert(Entry::new()), - std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), - }; - - let stats_updated = torrent_entry.insert_or_update_peer(peer); - let stats = torrent_entry.get_stats(); - - ( - SwarmStats { - downloaded: stats.1, - complete: stats.0, - incomplete: stats.2, - }, - stats_updated, - ) - } -} - -/// Structure that holds all torrents. Using `tokio::sync` locks. -#[allow(clippy::module_name_repetitions)] -pub struct RepositoryAsync { - torrents: tokio::sync::RwLock>>>, -} - -impl TRepositoryAsync for RepositoryAsync { - fn new() -> Self { - Self { - torrents: tokio::sync::RwLock::new(std::collections::BTreeMap::new()), - } - } - - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { - let maybe_existing_torrent_entry = self.get_torrents().await.get(info_hash).cloned(); - - let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { - existing_torrent_entry - } else { - let mut torrents_lock = self.get_torrents_mut().await; - let entry = torrents_lock - .entry(*info_hash) - .or_insert(Arc::new(tokio::sync::Mutex::new(Entry::new()))); - entry.clone() - }; - - let (stats, stats_updated) = { - let mut torrent_entry_lock = torrent_entry.lock().await; - let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); - let stats = torrent_entry_lock.get_stats(); - - (stats, stats_updated) - }; - - ( - SwarmStats { - downloaded: stats.1, - complete: stats.0, - incomplete: stats.2, - }, - stats_updated, - ) - } -} - -impl RepositoryAsync { - pub async fn get_torrents( - &self, - ) -> tokio::sync::RwLockReadGuard<'_, std::collections::BTreeMap>>> { - self.torrents.read().await - } - - pub async fn get_torrents_mut( - &self, - ) -> tokio::sync::RwLockWriteGuard<'_, std::collections::BTreeMap>>> { - self.torrents.write().await - } -} - -/// Structure that holds all torrents. Using a `tokio::sync` lock for the torrents map an`std::sync`nc lock for the inner torrent entry. -pub struct AsyncSync { - torrents: tokio::sync::RwLock>>>, -} - -impl TRepositoryAsync for AsyncSync { - fn new() -> Self { - Self { - torrents: tokio::sync::RwLock::new(std::collections::BTreeMap::new()), - } - } - - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { - let maybe_existing_torrent_entry = self.get_torrents().await.get(info_hash).cloned(); - - let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { - existing_torrent_entry - } else { - let mut torrents_lock = self.get_torrents_mut().await; - let entry = torrents_lock - .entry(*info_hash) - .or_insert(Arc::new(std::sync::Mutex::new(Entry::new()))); - entry.clone() - }; - - let (stats, stats_updated) = { - let mut torrent_entry_lock = torrent_entry.lock().unwrap(); - let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); - let stats = torrent_entry_lock.get_stats(); - - (stats, stats_updated) - }; - - ( - SwarmStats { - downloaded: stats.1, - complete: stats.0, - incomplete: stats.2, - }, - stats_updated, - ) - } -} - -impl AsyncSync { - pub async fn get_torrents( - &self, - ) -> tokio::sync::RwLockReadGuard<'_, std::collections::BTreeMap>>> { - self.torrents.read().await - } - - pub async fn get_torrents_mut( - &self, - ) -> tokio::sync::RwLockWriteGuard<'_, std::collections::BTreeMap>>> { - self.torrents.write().await - } -} - -#[allow(clippy::module_name_repetitions)] -pub struct RepositoryAsyncSingle { - torrents: tokio::sync::RwLock>, -} - -impl TRepositoryAsync for RepositoryAsyncSingle { - fn new() -> Self { - Self { - torrents: tokio::sync::RwLock::new(std::collections::BTreeMap::new()), - } - } - - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { - let (stats, stats_updated) = { - let mut torrents_lock = self.torrents.write().await; - let torrent_entry = torrents_lock.entry(*info_hash).or_insert(Entry::new()); - let stats_updated = torrent_entry.insert_or_update_peer(peer); - let stats = torrent_entry.get_stats(); - - (stats, stats_updated) - }; - - ( - SwarmStats { - downloaded: stats.1, - complete: stats.0, - incomplete: stats.2, - }, - stats_updated, - ) - } -} - -impl RepositoryAsyncSingle { - pub async fn get_torrents(&self) -> tokio::sync::RwLockReadGuard<'_, std::collections::BTreeMap> { - self.torrents.read().await - } - - pub async fn get_torrents_mut(&self) -> tokio::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { - self.torrents.write().await - } -} diff --git a/src/core/torrent/repository_asyn.rs b/src/core/torrent/repository_asyn.rs new file mode 100644 index 000000000..ac3724c3b --- /dev/null +++ b/src/core/torrent/repository_asyn.rs @@ -0,0 +1,188 @@ +use std::sync::Arc; + +use super::{EntryMutexStd, EntryMutexTokio}; +use crate::core::peer; +use crate::core::torrent::{Entry, SwarmStats}; +use crate::shared::bit_torrent::info_hash::InfoHash; + +pub trait RepositoryAsync: Default { + fn update_torrent_with_peer_and_get_stats( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + ) -> impl std::future::Future + Send; + + fn get_torrents<'a>( + &'a self, + ) -> impl std::future::Future>> + Send + where + std::collections::BTreeMap: 'a; + + fn get_torrents_mut<'a>( + &'a self, + ) -> impl std::future::Future>> + Send + where + std::collections::BTreeMap: 'a; +} + +pub struct RepositoryTokioRwLock { + torrents: tokio::sync::RwLock>, +} + +impl RepositoryAsync for RepositoryTokioRwLock { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { + let maybe_existing_torrent_entry = self.get_torrents().await.get(info_hash).cloned(); + + let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { + existing_torrent_entry + } else { + let mut torrents_lock = self.get_torrents_mut().await; + let entry = torrents_lock + .entry(*info_hash) + .or_insert(Arc::new(tokio::sync::Mutex::new(Entry::new()))); + entry.clone() + }; + + let (stats, stats_updated) = { + let mut torrent_entry_lock = torrent_entry.lock().await; + let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); + let stats = torrent_entry_lock.get_stats(); + + (stats, stats_updated) + }; + + ( + SwarmStats { + downloaded: stats.1, + complete: stats.0, + incomplete: stats.2, + }, + stats_updated, + ) + } + + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl Default for RepositoryTokioRwLock { + fn default() -> Self { + Self { + torrents: tokio::sync::RwLock::default(), + } + } +} + +impl RepositoryAsync for RepositoryTokioRwLock { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { + let maybe_existing_torrent_entry = self.get_torrents().await.get(info_hash).cloned(); + + let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { + existing_torrent_entry + } else { + let mut torrents_lock = self.get_torrents_mut().await; + let entry = torrents_lock + .entry(*info_hash) + .or_insert(Arc::new(std::sync::Mutex::new(Entry::new()))); + entry.clone() + }; + + let (stats, stats_updated) = { + let mut torrent_entry_lock = torrent_entry.lock().unwrap(); + let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); + let stats = torrent_entry_lock.get_stats(); + + (stats, stats_updated) + }; + + ( + SwarmStats { + downloaded: stats.1, + complete: stats.0, + incomplete: stats.2, + }, + stats_updated, + ) + } + + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl Default for RepositoryTokioRwLock { + fn default() -> Self { + Self { + torrents: tokio::sync::RwLock::default(), + } + } +} + +impl RepositoryAsync for RepositoryTokioRwLock { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { + let (stats, stats_updated) = { + let mut torrents_lock = self.torrents.write().await; + let torrent_entry = torrents_lock.entry(*info_hash).or_insert(Entry::new()); + let stats_updated = torrent_entry.insert_or_update_peer(peer); + let stats = torrent_entry.get_stats(); + + (stats, stats_updated) + }; + + ( + SwarmStats { + downloaded: stats.1, + complete: stats.0, + incomplete: stats.2, + }, + stats_updated, + ) + } + + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>(&'a self) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl Default for RepositoryTokioRwLock { + fn default() -> Self { + Self { + torrents: tokio::sync::RwLock::default(), + } + } +} diff --git a/src/core/torrent/repository_sync.rs b/src/core/torrent/repository_sync.rs new file mode 100644 index 000000000..76fc36fa2 --- /dev/null +++ b/src/core/torrent/repository_sync.rs @@ -0,0 +1,122 @@ +use std::sync::{Arc, RwLock}; + +use super::EntryMutexStd; +use crate::core::peer; +use crate::core::torrent::{Entry, SwarmStats}; +use crate::shared::bit_torrent::info_hash::InfoHash; + +pub trait RepositorySync: Default { + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool); + + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a; + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a; +} + +pub struct RepositoryStdRwLock { + torrents: std::sync::RwLock>, +} + +impl RepositorySync for RepositoryStdRwLock { + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { + let maybe_existing_torrent_entry = self.get_torrents().get(info_hash).cloned(); + + let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { + existing_torrent_entry + } else { + let mut torrents_lock = self.get_torrents_mut(); + let entry = torrents_lock + .entry(*info_hash) + .or_insert(Arc::new(std::sync::Mutex::new(Entry::new()))); + entry.clone() + }; + + let (stats, stats_updated) = { + let mut torrent_entry_lock = torrent_entry.lock().unwrap(); + let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); + let stats = torrent_entry_lock.get_stats(); + + (stats, stats_updated) + }; + + ( + SwarmStats { + downloaded: stats.1, + complete: stats.0, + incomplete: stats.2, + }, + stats_updated, + ) + } + + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl Default for RepositoryStdRwLock { + fn default() -> Self { + Self { + torrents: RwLock::default(), + } + } +} + +impl RepositorySync for RepositoryStdRwLock { + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { + let mut torrents = self.torrents.write().unwrap(); + + let torrent_entry = match torrents.entry(*info_hash) { + std::collections::btree_map::Entry::Vacant(vacant) => vacant.insert(Entry::new()), + std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), + }; + + let stats_updated = torrent_entry.insert_or_update_peer(peer); + let stats = torrent_entry.get_stats(); + + ( + SwarmStats { + downloaded: stats.1, + complete: stats.0, + incomplete: stats.2, + }, + stats_updated, + ) + } + + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl Default for RepositoryStdRwLock { + fn default() -> Self { + Self { + torrents: RwLock::default(), + } + } +} diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs index 37344858d..0856985d5 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/tests/servers/health_check_api/environment.rs @@ -12,6 +12,7 @@ use torrust_tracker_configuration::HealthCheckApi; #[derive(Debug)] pub enum Error { + #[allow(dead_code)] Error(String), } diff --git a/tests/servers/http/responses/scrape.rs b/tests/servers/http/responses/scrape.rs index eadecb603..fc741cbf4 100644 --- a/tests/servers/http/responses/scrape.rs +++ b/tests/servers/http/responses/scrape.rs @@ -73,9 +73,13 @@ impl ResponseBuilder { #[derive(Debug)] pub enum BencodeParseError { + #[allow(dead_code)] InvalidValueExpectedDict { value: Value }, + #[allow(dead_code)] InvalidValueExpectedInt { value: Value }, + #[allow(dead_code)] InvalidFileField { value: Value }, + #[allow(dead_code)] MissingFileField { field_name: String }, } From 48ce42624dea8321d93375a7f57b37aeab3280ed Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 10 Feb 2024 07:31:20 +0800 Subject: [PATCH 0266/1297] dev: bench torrent/repository add sync_asyn variant --- .../src/benches/asyn.rs | 20 +- .../src/benches/mod.rs | 1 + .../src/benches/sync.rs | 9 +- .../src/benches/sync_asyn.rs | 185 ++++++++++++++++++ .../torrent-repository-benchmarks/src/main.rs | 76 ++++--- src/core/mod.rs | 2 +- src/core/torrent/mod.rs | 13 ++ src/core/torrent/repository_asyn.rs | 21 +- src/core/torrent/repository_sync.rs | 69 ++++++- 9 files changed, 335 insertions(+), 61 deletions(-) create mode 100644 packages/torrent-repository-benchmarks/src/benches/sync_asyn.rs diff --git a/packages/torrent-repository-benchmarks/src/benches/asyn.rs b/packages/torrent-repository-benchmarks/src/benches/asyn.rs index 9482d821c..d36de9695 100644 --- a/packages/torrent-repository-benchmarks/src/benches/asyn.rs +++ b/packages/torrent-repository-benchmarks/src/benches/asyn.rs @@ -4,14 +4,15 @@ use std::time::Duration; use clap::Parser; use futures::stream::FuturesUnordered; use torrust_tracker::core::torrent::repository_asyn::{RepositoryAsync, RepositoryTokioRwLock}; +use torrust_tracker::core::torrent::UpdateTorrentAsync; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use crate::args::Args; use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; -pub async fn async_add_one_torrent(samples: usize) -> (Duration, Duration) +pub async fn add_one_torrent(samples: usize) -> (Duration, Duration) where - RepositoryTokioRwLock: RepositoryAsync, + RepositoryTokioRwLock: RepositoryAsync + UpdateTorrentAsync, { let mut results: Vec = Vec::with_capacity(samples); @@ -35,10 +36,10 @@ where } // Add one torrent ten thousand times in parallel (depending on the set worker threads) -pub async fn async_update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where T: Send + Sync + 'static, - RepositoryTokioRwLock: RepositoryAsync, + RepositoryTokioRwLock: RepositoryAsync + UpdateTorrentAsync, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); @@ -85,10 +86,10 @@ where } // Add ten thousand torrents in parallel (depending on the set worker threads) -pub async fn async_add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where T: Send + Sync + 'static, - RepositoryTokioRwLock: RepositoryAsync, + RepositoryTokioRwLock: RepositoryAsync + UpdateTorrentAsync, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); @@ -130,13 +131,10 @@ where } // Async update ten thousand torrents in parallel (depending on the set worker threads) -pub async fn async_update_multiple_torrents_in_parallel( - runtime: &tokio::runtime::Runtime, - samples: usize, -) -> (Duration, Duration) +pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where T: Send + Sync + 'static, - RepositoryTokioRwLock: RepositoryAsync, + RepositoryTokioRwLock: RepositoryAsync + UpdateTorrentAsync, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); diff --git a/packages/torrent-repository-benchmarks/src/benches/mod.rs b/packages/torrent-repository-benchmarks/src/benches/mod.rs index 1026aa4bf..7450f4bcc 100644 --- a/packages/torrent-repository-benchmarks/src/benches/mod.rs +++ b/packages/torrent-repository-benchmarks/src/benches/mod.rs @@ -1,3 +1,4 @@ pub mod asyn; pub mod sync; +pub mod sync_asyn; pub mod utils; diff --git a/packages/torrent-repository-benchmarks/src/benches/sync.rs b/packages/torrent-repository-benchmarks/src/benches/sync.rs index c37fa9f4a..3dee93421 100644 --- a/packages/torrent-repository-benchmarks/src/benches/sync.rs +++ b/packages/torrent-repository-benchmarks/src/benches/sync.rs @@ -4,6 +4,7 @@ use std::time::Duration; use clap::Parser; use futures::stream::FuturesUnordered; use torrust_tracker::core::torrent::repository_sync::{RepositoryStdRwLock, RepositorySync}; +use torrust_tracker::core::torrent::UpdateTorrentSync; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use crate::args::Args; @@ -13,7 +14,7 @@ use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjuste #[must_use] pub fn add_one_torrent(samples: usize) -> (Duration, Duration) where - RepositoryStdRwLock: RepositorySync, + RepositoryStdRwLock: RepositorySync + UpdateTorrentSync, { let mut results: Vec = Vec::with_capacity(samples); @@ -38,7 +39,7 @@ where pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where T: Send + Sync + 'static, - RepositoryStdRwLock: RepositorySync, + RepositoryStdRwLock: RepositorySync + UpdateTorrentSync, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); @@ -84,7 +85,7 @@ where pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where T: Send + Sync + 'static, - RepositoryStdRwLock: RepositorySync, + RepositoryStdRwLock: RepositorySync + UpdateTorrentSync, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); @@ -127,7 +128,7 @@ where pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where T: Send + Sync + 'static, - RepositoryStdRwLock: RepositorySync, + RepositoryStdRwLock: RepositorySync + UpdateTorrentSync, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); diff --git a/packages/torrent-repository-benchmarks/src/benches/sync_asyn.rs b/packages/torrent-repository-benchmarks/src/benches/sync_asyn.rs new file mode 100644 index 000000000..11ce6ed0c --- /dev/null +++ b/packages/torrent-repository-benchmarks/src/benches/sync_asyn.rs @@ -0,0 +1,185 @@ +use std::sync::Arc; +use std::time::Duration; + +use clap::Parser; +use futures::stream::FuturesUnordered; +use torrust_tracker::core::torrent::repository_sync::{RepositoryStdRwLock, RepositorySync}; +use torrust_tracker::core::torrent::UpdateTorrentAsync; +use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; + +use crate::args::Args; +use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; + +// Simply add one torrent +#[must_use] +pub async fn add_one_torrent(samples: usize) -> (Duration, Duration) +where + RepositoryStdRwLock: RepositorySync + UpdateTorrentAsync, +{ + let mut results: Vec = Vec::with_capacity(samples); + + for _ in 0..samples { + let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); + + let info_hash = InfoHash([0; 20]); + + let start_time = std::time::Instant::now(); + + torrent_repository + .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) + .await; + + let result = start_time.elapsed(); + + results.push(result); + } + + get_average_and_adjusted_average_from_results(results) +} + +// Add one torrent ten thousand times in parallel (depending on the set worker threads) +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +where + T: Send + Sync + 'static, + RepositoryStdRwLock: RepositorySync + UpdateTorrentAsync, +{ + let args = Args::parse(); + let mut results: Vec = Vec::with_capacity(samples); + + for _ in 0..samples { + let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); + let info_hash: &'static InfoHash = &InfoHash([0; 20]); + let handles = FuturesUnordered::new(); + + // Add the torrent/peer to the torrent repository + torrent_repository + .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) + .await; + + let start_time = std::time::Instant::now(); + + for _ in 0..10_000 { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone + .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) + .await; + + if let Some(sleep_time) = args.sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + let result = start_time.elapsed(); + + results.push(result); + } + + get_average_and_adjusted_average_from_results(results) +} + +// Add ten thousand torrents in parallel (depending on the set worker threads) +pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +where + T: Send + Sync + 'static, + RepositoryStdRwLock: RepositorySync + UpdateTorrentAsync, +{ + let args = Args::parse(); + let mut results: Vec = Vec::with_capacity(samples); + + for _ in 0..samples { + let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); + let info_hashes = generate_unique_info_hashes(10_000); + let handles = FuturesUnordered::new(); + + let start_time = std::time::Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone + .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) + .await; + + if let Some(sleep_time) = args.sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + let result = start_time.elapsed(); + + results.push(result); + } + + get_average_and_adjusted_average_from_results(results) +} + +// Update ten thousand torrents in parallel (depending on the set worker threads) +pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +where + T: Send + Sync + 'static, + RepositoryStdRwLock: RepositorySync + UpdateTorrentAsync, +{ + let args = Args::parse(); + let mut results: Vec = Vec::with_capacity(samples); + + for _ in 0..samples { + let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); + let info_hashes = generate_unique_info_hashes(10_000); + let handles = FuturesUnordered::new(); + + // Add the torrents/peers to the torrent repository + for info_hash in &info_hashes { + torrent_repository + .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) + .await; + } + + let start_time = std::time::Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone + .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) + .await; + + if let Some(sleep_time) = args.sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + let result = start_time.elapsed(); + + results.push(result); + } + + get_average_and_adjusted_average_from_results(results) +} diff --git a/packages/torrent-repository-benchmarks/src/main.rs b/packages/torrent-repository-benchmarks/src/main.rs index eab8e3803..4a293b832 100644 --- a/packages/torrent-repository-benchmarks/src/main.rs +++ b/packages/torrent-repository-benchmarks/src/main.rs @@ -1,12 +1,6 @@ use clap::Parser; use torrust_torrent_repository_benchmarks::args::Args; -use torrust_torrent_repository_benchmarks::benches::asyn::{ - async_add_multiple_torrents_in_parallel, async_add_one_torrent, async_update_multiple_torrents_in_parallel, - async_update_one_torrent_in_parallel, -}; -use torrust_torrent_repository_benchmarks::benches::sync::{ - add_multiple_torrents_in_parallel, add_one_torrent, update_multiple_torrents_in_parallel, update_one_torrent_in_parallel, -}; +use torrust_torrent_repository_benchmarks::benches::{asyn, sync, sync_asyn}; use torrust_tracker::core::torrent::{Entry, EntryMutexStd, EntryMutexTokio}; #[allow(clippy::too_many_lines)] @@ -25,43 +19,47 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(async_add_one_torrent::(1_000_000)) + rt.block_on(asyn::add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(async_update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(async_add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(async_update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) ); if let Some(true) = args.compare { println!(); println!("std::sync::RwLock>"); - println!("{}: Avg/AdjAvg: {:?}", "add_one_torrent", add_one_torrent::(1_000_000)); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_one_torrent", + sync::add_one_torrent::(1_000_000) + ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(sync::update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(sync::add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(sync::update_multiple_torrents_in_parallel::(&rt, 10)) ); println!(); @@ -70,22 +68,46 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - add_one_torrent::(1_000_000) + sync::add_one_torrent::(1_000_000) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "update_one_torrent_in_parallel", + rt.block_on(sync::update_one_torrent_in_parallel::(&rt, 10)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_multiple_torrents_in_parallel", + rt.block_on(sync::add_multiple_torrents_in_parallel::(&rt, 10)) + ); + println!( + "{}: Avg/AdjAvg: {:?}", + "update_multiple_torrents_in_parallel", + rt.block_on(sync::update_multiple_torrents_in_parallel::(&rt, 10)) + ); + + println!(); + + println!("std::sync::RwLock>>>"); + println!( + "{}: Avg/AdjAvg: {:?}", + "add_one_torrent", + rt.block_on(sync_asyn::add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(sync_asyn::update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(sync_asyn::add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(sync_asyn::update_multiple_torrents_in_parallel::(&rt, 10)) ); println!(); @@ -94,22 +116,22 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(async_add_one_torrent::(1_000_000)) + rt.block_on(asyn::add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(async_update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(async_add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(async_update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) ); println!(); @@ -118,22 +140,22 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(async_add_one_torrent::(1_000_000)) + rt.block_on(asyn::add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(async_update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(async_add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(async_update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) ); } } diff --git a/src/core/mod.rs b/src/core/mod.rs index c392ead75..56b30f955 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -456,7 +456,7 @@ use self::auth::Key; use self::error::Error; use self::peer::Peer; use self::torrent::repository_asyn::{RepositoryAsync, RepositoryTokioRwLock}; -use self::torrent::Entry; +use self::torrent::{Entry, UpdateTorrentAsync}; use crate::core::databases::Database; use crate::core::torrent::{SwarmMetadata, SwarmStats}; use crate::shared::bit_torrent::info_hash::InfoHash; diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index b5ebb1054..49c1f61f8 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -39,8 +39,21 @@ use derive_more::Constructor; use serde::{Deserialize, Serialize}; use super::peer::{self, Peer}; +use crate::shared::bit_torrent::info_hash::InfoHash; use crate::shared::clock::{Current, TimeNow}; +pub trait UpdateTorrentSync { + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool); +} + +pub trait UpdateTorrentAsync { + fn update_torrent_with_peer_and_get_stats( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + ) -> impl std::future::Future + Send; +} + /// A data structure containing all the information about a torrent in the tracker. /// /// This is the tracker entry for a given torrent and contains the swarm data, diff --git a/src/core/torrent/repository_asyn.rs b/src/core/torrent/repository_asyn.rs index ac3724c3b..ad10f85b4 100644 --- a/src/core/torrent/repository_asyn.rs +++ b/src/core/torrent/repository_asyn.rs @@ -1,17 +1,11 @@ use std::sync::Arc; -use super::{EntryMutexStd, EntryMutexTokio}; +use super::{EntryMutexStd, EntryMutexTokio, UpdateTorrentAsync}; use crate::core::peer; use crate::core::torrent::{Entry, SwarmStats}; use crate::shared::bit_torrent::info_hash::InfoHash; pub trait RepositoryAsync: Default { - fn update_torrent_with_peer_and_get_stats( - &self, - info_hash: &InfoHash, - peer: &peer::Peer, - ) -> impl std::future::Future + Send; - fn get_torrents<'a>( &'a self, ) -> impl std::future::Future>> + Send @@ -28,8 +22,7 @@ pub trait RepositoryAsync: Default { pub struct RepositoryTokioRwLock { torrents: tokio::sync::RwLock>, } - -impl RepositoryAsync for RepositoryTokioRwLock { +impl UpdateTorrentAsync for RepositoryTokioRwLock { async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { let maybe_existing_torrent_entry = self.get_torrents().await.get(info_hash).cloned(); @@ -60,7 +53,9 @@ impl RepositoryAsync for RepositoryTokioRwLock stats_updated, ) } +} +impl RepositoryAsync for RepositoryTokioRwLock { async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> where std::collections::BTreeMap: 'a, @@ -86,7 +81,7 @@ impl Default for RepositoryTokioRwLock { } } -impl RepositoryAsync for RepositoryTokioRwLock { +impl UpdateTorrentAsync for RepositoryTokioRwLock { async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { let maybe_existing_torrent_entry = self.get_torrents().await.get(info_hash).cloned(); @@ -117,7 +112,9 @@ impl RepositoryAsync for RepositoryTokioRwLock { stats_updated, ) } +} +impl RepositoryAsync for RepositoryTokioRwLock { async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> where std::collections::BTreeMap: 'a, @@ -143,7 +140,7 @@ impl Default for RepositoryTokioRwLock { } } -impl RepositoryAsync for RepositoryTokioRwLock { +impl UpdateTorrentAsync for RepositoryTokioRwLock { async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { let (stats, stats_updated) = { let mut torrents_lock = self.torrents.write().await; @@ -163,7 +160,9 @@ impl RepositoryAsync for RepositoryTokioRwLock { stats_updated, ) } +} +impl RepositoryAsync for RepositoryTokioRwLock { async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> where std::collections::BTreeMap: 'a, diff --git a/src/core/torrent/repository_sync.rs b/src/core/torrent/repository_sync.rs index 76fc36fa2..3b01eb8be 100644 --- a/src/core/torrent/repository_sync.rs +++ b/src/core/torrent/repository_sync.rs @@ -1,13 +1,11 @@ use std::sync::{Arc, RwLock}; -use super::EntryMutexStd; +use super::{EntryMutexStd, EntryMutexTokio, UpdateTorrentAsync, UpdateTorrentSync}; use crate::core::peer; use crate::core::torrent::{Entry, SwarmStats}; use crate::shared::bit_torrent::info_hash::InfoHash; pub trait RepositorySync: Default { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool); - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> where std::collections::BTreeMap: 'a; @@ -21,7 +19,62 @@ pub struct RepositoryStdRwLock { torrents: std::sync::RwLock>, } -impl RepositorySync for RepositoryStdRwLock { +impl UpdateTorrentAsync for RepositoryStdRwLock { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { + let maybe_existing_torrent_entry = self.get_torrents().get(info_hash).cloned(); + + let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { + existing_torrent_entry + } else { + let mut torrents_lock = self.get_torrents_mut(); + let entry = torrents_lock + .entry(*info_hash) + .or_insert(Arc::new(tokio::sync::Mutex::new(Entry::new()))); + entry.clone() + }; + + let (stats, stats_updated) = { + let mut torrent_entry_lock = torrent_entry.lock().await; + let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); + let stats = torrent_entry_lock.get_stats(); + + (stats, stats_updated) + }; + + ( + SwarmStats { + downloaded: stats.1, + complete: stats.0, + incomplete: stats.2, + }, + stats_updated, + ) + } +} +impl RepositorySync for RepositoryStdRwLock { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl Default for RepositoryStdRwLock { + fn default() -> Self { + Self { + torrents: RwLock::default(), + } + } +} +impl UpdateTorrentSync for RepositoryStdRwLock { fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { let maybe_existing_torrent_entry = self.get_torrents().get(info_hash).cloned(); @@ -52,7 +105,8 @@ impl RepositorySync for RepositoryStdRwLock { stats_updated, ) } - +} +impl RepositorySync for RepositoryStdRwLock { fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> where std::collections::BTreeMap: 'a, @@ -76,7 +130,7 @@ impl Default for RepositoryStdRwLock { } } -impl RepositorySync for RepositoryStdRwLock { +impl UpdateTorrentSync for RepositoryStdRwLock { fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { let mut torrents = self.torrents.write().unwrap(); @@ -97,7 +151,8 @@ impl RepositorySync for RepositoryStdRwLock { stats_updated, ) } - +} +impl RepositorySync for RepositoryStdRwLock { fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> where std::collections::BTreeMap: 'a, From 1025125572b99504b0b882d7b54e7179d4ef25e9 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 10 Feb 2024 16:21:37 +0800 Subject: [PATCH 0267/1297] dev: create torrent repo trait and extract entry --- Cargo.lock | 4 +- cSpell.json | 1 + .../src/benches/asyn.rs | 19 +- .../src/benches/sync.rs | 12 +- .../src/benches/sync_asyn.rs | 12 +- .../torrent-repository-benchmarks/src/main.rs | 34 +- src/core/databases/mod.rs | 4 +- src/core/mod.rs | 154 ++----- src/core/peer.rs | 53 +++ src/core/services/torrent.rs | 55 ++- src/core/torrent/entry.rs | 241 +++++++++++ src/core/torrent/mod.rs | 219 ++-------- src/core/torrent/repository/mod.rs | 30 ++ src/core/torrent/repository/std_sync.rs | 365 +++++++++++++++++ src/core/torrent/repository/tokio_sync.rs | 378 ++++++++++++++++++ src/core/torrent/repository_asyn.rs | 187 --------- src/core/torrent/repository_sync.rs | 177 -------- .../apis/v1/context/torrent/handlers.rs | 2 +- src/servers/http/v1/responses/announce.rs | 11 +- src/servers/http/v1/services/announce.rs | 4 +- src/servers/udp/handlers.rs | 7 +- 21 files changed, 1222 insertions(+), 747 deletions(-) create mode 100644 src/core/torrent/entry.rs create mode 100644 src/core/torrent/repository/mod.rs create mode 100644 src/core/torrent/repository/std_sync.rs create mode 100644 src/core/torrent/repository/tokio_sync.rs delete mode 100644 src/core/torrent/repository_asyn.rs delete mode 100644 src/core/torrent/repository_sync.rs diff --git a/Cargo.lock b/Cargo.lock index 5722032b8..26fb919af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3086,9 +3086,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "socket2" diff --git a/cSpell.json b/cSpell.json index 6d8b68c92..da11cd29a 100644 --- a/cSpell.json +++ b/cSpell.json @@ -36,6 +36,7 @@ "Containerfile", "curr", "Cyberneering", + "dashmap", "datagram", "datetime", "debuginfo", diff --git a/packages/torrent-repository-benchmarks/src/benches/asyn.rs b/packages/torrent-repository-benchmarks/src/benches/asyn.rs index d36de9695..737a99f3c 100644 --- a/packages/torrent-repository-benchmarks/src/benches/asyn.rs +++ b/packages/torrent-repository-benchmarks/src/benches/asyn.rs @@ -3,8 +3,8 @@ use std::time::Duration; use clap::Parser; use futures::stream::FuturesUnordered; -use torrust_tracker::core::torrent::repository_asyn::{RepositoryAsync, RepositoryTokioRwLock}; -use torrust_tracker::core::torrent::UpdateTorrentAsync; +use torrust_tracker::core::torrent::repository::tokio_sync::RepositoryTokioRwLock; +use torrust_tracker::core::torrent::repository::UpdateTorrentAsync; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use crate::args::Args; @@ -12,7 +12,8 @@ use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjuste pub async fn add_one_torrent(samples: usize) -> (Duration, Duration) where - RepositoryTokioRwLock: RepositoryAsync + UpdateTorrentAsync, + T: Default, + RepositoryTokioRwLock: UpdateTorrentAsync + Default, { let mut results: Vec = Vec::with_capacity(samples); @@ -38,8 +39,8 @@ where // Add one torrent ten thousand times in parallel (depending on the set worker threads) pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - T: Send + Sync + 'static, - RepositoryTokioRwLock: RepositoryAsync + UpdateTorrentAsync, + T: Default + Send + Sync + 'static, + RepositoryTokioRwLock: UpdateTorrentAsync + Default, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); @@ -88,8 +89,8 @@ where // Add ten thousand torrents in parallel (depending on the set worker threads) pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - T: Send + Sync + 'static, - RepositoryTokioRwLock: RepositoryAsync + UpdateTorrentAsync, + T: Default + Send + Sync + 'static, + RepositoryTokioRwLock: UpdateTorrentAsync + Default, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); @@ -133,8 +134,8 @@ where // Async update ten thousand torrents in parallel (depending on the set worker threads) pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - T: Send + Sync + 'static, - RepositoryTokioRwLock: RepositoryAsync + UpdateTorrentAsync, + T: Default + Send + Sync + 'static, + RepositoryTokioRwLock: UpdateTorrentAsync + Default, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); diff --git a/packages/torrent-repository-benchmarks/src/benches/sync.rs b/packages/torrent-repository-benchmarks/src/benches/sync.rs index 3dee93421..ea694a38c 100644 --- a/packages/torrent-repository-benchmarks/src/benches/sync.rs +++ b/packages/torrent-repository-benchmarks/src/benches/sync.rs @@ -3,8 +3,8 @@ use std::time::Duration; use clap::Parser; use futures::stream::FuturesUnordered; -use torrust_tracker::core::torrent::repository_sync::{RepositoryStdRwLock, RepositorySync}; -use torrust_tracker::core::torrent::UpdateTorrentSync; +use torrust_tracker::core::torrent::repository::std_sync::RepositoryStdRwLock; +use torrust_tracker::core::torrent::repository::UpdateTorrentSync; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use crate::args::Args; @@ -14,7 +14,7 @@ use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjuste #[must_use] pub fn add_one_torrent(samples: usize) -> (Duration, Duration) where - RepositoryStdRwLock: RepositorySync + UpdateTorrentSync, + RepositoryStdRwLock: UpdateTorrentSync + Default, { let mut results: Vec = Vec::with_capacity(samples); @@ -39,7 +39,7 @@ where pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where T: Send + Sync + 'static, - RepositoryStdRwLock: RepositorySync + UpdateTorrentSync, + RepositoryStdRwLock: UpdateTorrentSync + Default, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); @@ -85,7 +85,7 @@ where pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where T: Send + Sync + 'static, - RepositoryStdRwLock: RepositorySync + UpdateTorrentSync, + RepositoryStdRwLock: UpdateTorrentSync + Default, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); @@ -128,7 +128,7 @@ where pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where T: Send + Sync + 'static, - RepositoryStdRwLock: RepositorySync + UpdateTorrentSync, + RepositoryStdRwLock: UpdateTorrentSync + Default, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); diff --git a/packages/torrent-repository-benchmarks/src/benches/sync_asyn.rs b/packages/torrent-repository-benchmarks/src/benches/sync_asyn.rs index 11ce6ed0c..8efed9856 100644 --- a/packages/torrent-repository-benchmarks/src/benches/sync_asyn.rs +++ b/packages/torrent-repository-benchmarks/src/benches/sync_asyn.rs @@ -3,8 +3,8 @@ use std::time::Duration; use clap::Parser; use futures::stream::FuturesUnordered; -use torrust_tracker::core::torrent::repository_sync::{RepositoryStdRwLock, RepositorySync}; -use torrust_tracker::core::torrent::UpdateTorrentAsync; +use torrust_tracker::core::torrent::repository::std_sync::RepositoryStdRwLock; +use torrust_tracker::core::torrent::repository::UpdateTorrentAsync; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use crate::args::Args; @@ -14,7 +14,7 @@ use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjuste #[must_use] pub async fn add_one_torrent(samples: usize) -> (Duration, Duration) where - RepositoryStdRwLock: RepositorySync + UpdateTorrentAsync, + RepositoryStdRwLock: UpdateTorrentAsync + Default, { let mut results: Vec = Vec::with_capacity(samples); @@ -41,7 +41,7 @@ where pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where T: Send + Sync + 'static, - RepositoryStdRwLock: RepositorySync + UpdateTorrentAsync, + RepositoryStdRwLock: UpdateTorrentAsync + Default, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); @@ -91,7 +91,7 @@ where pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where T: Send + Sync + 'static, - RepositoryStdRwLock: RepositorySync + UpdateTorrentAsync, + RepositoryStdRwLock: UpdateTorrentAsync + Default, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); @@ -136,7 +136,7 @@ where pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where T: Send + Sync + 'static, - RepositoryStdRwLock: RepositorySync + UpdateTorrentAsync, + RepositoryStdRwLock: UpdateTorrentAsync + Default, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); diff --git a/packages/torrent-repository-benchmarks/src/main.rs b/packages/torrent-repository-benchmarks/src/main.rs index 4a293b832..d7291afe2 100644 --- a/packages/torrent-repository-benchmarks/src/main.rs +++ b/packages/torrent-repository-benchmarks/src/main.rs @@ -1,7 +1,7 @@ use clap::Parser; use torrust_torrent_repository_benchmarks::args::Args; use torrust_torrent_repository_benchmarks::benches::{asyn, sync, sync_asyn}; -use torrust_tracker::core::torrent::{Entry, EntryMutexStd, EntryMutexTokio}; +use torrust_tracker::core::torrent::entry::{Entry, MutexStd, MutexTokio}; #[allow(clippy::too_many_lines)] #[allow(clippy::print_literal)] @@ -68,22 +68,22 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - sync::add_one_torrent::(1_000_000) + sync::add_one_torrent::(1_000_000) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(sync::update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(sync::update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(sync::add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(sync::add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(sync::update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(sync::update_multiple_torrents_in_parallel::(&rt, 10)) ); println!(); @@ -92,22 +92,22 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(sync_asyn::add_one_torrent::(1_000_000)) + rt.block_on(sync_asyn::add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(sync_asyn::update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(sync_asyn::update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(sync_asyn::add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(sync_asyn::add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(sync_asyn::update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(sync_asyn::update_multiple_torrents_in_parallel::(&rt, 10)) ); println!(); @@ -116,22 +116,22 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(asyn::add_one_torrent::(1_000_000)) + rt.block_on(asyn::add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) ); println!(); @@ -140,22 +140,22 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(asyn::add_one_torrent::(1_000_000)) + rt.block_on(asyn::add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) ); } } diff --git a/src/core/databases/mod.rs b/src/core/databases/mod.rs index b80b11987..b3dcdd48e 100644 --- a/src/core/databases/mod.rs +++ b/src/core/databases/mod.rs @@ -56,6 +56,8 @@ use self::error::Error; use crate::core::auth::{self, Key}; use crate::shared::bit_torrent::info_hash::InfoHash; +pub type PersistentTorrents = Vec<(InfoHash, u32)>; + struct Builder where T: Database, @@ -125,7 +127,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to load. - async fn load_persistent_torrents(&self) -> Result, Error>; + async fn load_persistent_torrents(&self) -> Result; /// It saves the torrent metrics data into the database. /// diff --git a/src/core/mod.rs b/src/core/mod.rs index 56b30f955..b070f90db 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -102,11 +102,11 @@ //! //! pub struct AnnounceData { //! pub peers: Vec, -//! pub swarm_stats: SwarmStats, +//! pub swarm_stats: SwarmMetadata, //! pub policy: AnnouncePolicy, // the tracker announce policy. //! } //! -//! pub struct SwarmStats { +//! pub struct SwarmMetadata { //! pub completed: u32, // The number of peers that have ever completed downloading //! pub seeders: u32, // The number of active peers that have completed downloading (seeders) //! pub leechers: u32, // The number of active peers that have not completed downloading (leechers) @@ -232,16 +232,11 @@ //! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) //! } //! -//! pub struct SwarmStats { -//! pub completed: u32, // The number of peers that have ever completed downloading -//! pub seeders: u32, // The number of active peers that have completed downloading (seeders) -//! pub leechers: u32, // The number of active peers that have not completed downloading (leechers) -//! } //! ``` //! //! > **NOTICE**: that `complete` or `completed` peers are the peers that have completed downloading, but only the active ones are considered "seeders". //! -//! `SwarmStats` struct follows name conventions for `scrape` responses. See [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmStats` +//! `SwarmMetadata` struct follows name conventions for `scrape` responses. See [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmMetadata` //! is used for the rest of cases. //! //! Refer to [`torrent`] module for more details about these data structures. @@ -439,14 +434,13 @@ pub mod services; pub mod statistics; pub mod torrent; -use std::collections::{BTreeMap, HashMap}; +use std::collections::HashMap; use std::net::IpAddr; use std::panic::Location; use std::sync::Arc; use std::time::Duration; use derive_more::Constructor; -use futures::future::join_all; use log::debug; use tokio::sync::mpsc::error::SendError; use torrust_tracker_configuration::{AnnouncePolicy, Configuration}; @@ -455,10 +449,11 @@ use torrust_tracker_primitives::TrackerMode; use self::auth::Key; use self::error::Error; use self::peer::Peer; -use self::torrent::repository_asyn::{RepositoryAsync, RepositoryTokioRwLock}; -use self::torrent::{Entry, UpdateTorrentAsync}; +use self::torrent::entry::{Entry, ReadInfo, ReadPeers}; +use self::torrent::repository::tokio_sync::RepositoryTokioRwLock; +use self::torrent::repository::{Repository, UpdateTorrentAsync}; use crate::core::databases::Database; -use crate::core::torrent::{SwarmMetadata, SwarmStats}; +use crate::core::torrent::SwarmMetadata; use crate::shared::bit_torrent::info_hash::InfoHash; /// The maximum number of returned peers for a torrent. @@ -515,9 +510,9 @@ pub struct TrackerPolicy { pub struct AnnounceData { /// The list of peers that are downloading the same torrent. /// It excludes the peer that made the request. - pub peers: Vec, + pub peers: Vec>, /// Swarm statistics - pub stats: SwarmStats, + pub stats: SwarmMetadata, pub policy: AnnouncePolicy, } @@ -685,10 +680,8 @@ impl Tracker { /// It returns the data for a `scrape` response. async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { - let torrents = self.torrents.get_torrents().await; - - match torrents.get(info_hash) { - Some(torrent_entry) => torrent_entry.get_swarm_metadata(), + match self.torrents.get(info_hash).await { + Some(torrent_entry) => torrent_entry.get_stats(), None => SwarmMetadata::default(), } } @@ -704,47 +697,25 @@ impl Tracker { pub async fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { let persistent_torrents = self.database.load_persistent_torrents().await?; - let mut torrents = self.torrents.get_torrents_mut().await; - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(&info_hash) { - continue; - } - - let torrent_entry = torrent::Entry { - peers: BTreeMap::default(), - completed, - }; - - torrents.insert(info_hash, torrent_entry); - } + self.torrents.import_persistent(&persistent_torrents).await; Ok(()) } - async fn get_torrent_peers_for_peer(&self, info_hash: &InfoHash, peer: &Peer) -> Vec { - let read_lock = self.torrents.get_torrents().await; - - match read_lock.get(info_hash) { + async fn get_torrent_peers_for_peer(&self, info_hash: &InfoHash, peer: &Peer) -> Vec> { + match self.torrents.get(info_hash).await { None => vec![], - Some(entry) => entry - .get_peers_for_peer(peer, TORRENT_PEERS_LIMIT) - .into_iter() - .copied() - .collect(), + Some(entry) => entry.get_peers_for_peer(peer, Some(TORRENT_PEERS_LIMIT)), } } /// # Context: Tracker /// /// Get all torrent peers for a given torrent - pub async fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec { - let read_lock = self.torrents.get_torrents().await; - - match read_lock.get(info_hash) { + pub async fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { + match self.torrents.get(info_hash).await { None => vec![], - Some(entry) => entry.get_peers(TORRENT_PEERS_LIMIT).into_iter().copied().collect(), + Some(entry) => entry.get_peers(Some(TORRENT_PEERS_LIMIT)), } } @@ -753,11 +724,15 @@ impl Tracker { /// needed for a `announce` request response. /// /// # Context: Tracker - pub async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> torrent::SwarmStats { + pub async fn update_torrent_with_peer_and_get_stats( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + ) -> torrent::SwarmMetadata { // code-review: consider splitting the function in two (command and query segregation). // `update_torrent_with_peer` and `get_stats` - let (stats, stats_updated) = self.torrents.update_torrent_with_peer_and_get_stats(info_hash, peer).await; + let (stats_updated, stats) = self.torrents.update_torrent_with_peer_and_get_stats(info_hash, peer).await; if self.policy.persistent_torrent_completed_stat && stats_updated { let completed = stats.downloaded; @@ -777,71 +752,18 @@ impl Tracker { /// # Panics /// Panics if unable to get the torrent metrics. pub async fn get_torrents_metrics(&self) -> TorrentsMetrics { - let arc_torrents_metrics = Arc::new(tokio::sync::Mutex::new(TorrentsMetrics { - seeders: 0, - completed: 0, - leechers: 0, - torrents: 0, - })); - - let db = self.torrents.get_torrents().await.clone(); - - let futures = db - .values() - .map(|torrent_entry| { - let torrent_entry = torrent_entry.clone(); - let torrents_metrics = arc_torrents_metrics.clone(); - - async move { - tokio::spawn(async move { - let (seeders, completed, leechers) = torrent_entry.get_stats(); - torrents_metrics.lock().await.seeders += u64::from(seeders); - torrents_metrics.lock().await.completed += u64::from(completed); - torrents_metrics.lock().await.leechers += u64::from(leechers); - torrents_metrics.lock().await.torrents += 1; - }) - .await - .expect("Error torrent_metrics spawn"); - } - }) - .collect::>(); - - join_all(futures).await; - - let torrents_metrics = Arc::try_unwrap(arc_torrents_metrics).expect("Could not unwrap arc_torrents_metrics"); - - torrents_metrics.into_inner() + self.torrents.get_metrics().await } /// Remove inactive peers and (optionally) peerless torrents /// /// # Context: Tracker pub async fn cleanup_torrents(&self) { - let mut torrents_lock = self.torrents.get_torrents_mut().await; - // If we don't need to remove torrents we will use the faster iter if self.policy.remove_peerless_torrents { - let mut cleaned_torrents_map: BTreeMap = BTreeMap::new(); - - for (info_hash, torrent_entry) in &mut *torrents_lock { - torrent_entry.remove_inactive_peers(self.policy.max_peer_timeout); - - if torrent_entry.peers.is_empty() { - continue; - } - - if self.policy.persistent_torrent_completed_stat && torrent_entry.completed == 0 { - continue; - } - - cleaned_torrents_map.insert(*info_hash, torrent_entry.clone()); - } - - *torrents_lock = cleaned_torrents_map; + self.torrents.remove_peerless_torrents(&self.policy).await; } else { - for torrent_entry in (*torrents_lock).values_mut() { - torrent_entry.remove_inactive_peers(self.policy.max_peer_timeout); - } + self.torrents.remove_inactive_peers(self.policy.max_peer_timeout).await; } } @@ -1093,6 +1015,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; + use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; @@ -1233,7 +1156,7 @@ mod tests { let peers = tracker.get_torrent_peers(&info_hash).await; - assert_eq!(peers, vec![peer]); + assert_eq!(peers, vec![Arc::new(peer)]); } #[tokio::test] @@ -1275,6 +1198,8 @@ mod tests { mod handling_an_announce_request { + use std::sync::Arc; + use crate::core::tests::the_tracker::{ peer_ip, public_tracker, sample_info_hash, sample_peer, sample_peer_1, sample_peer_2, }; @@ -1400,7 +1325,7 @@ mod tests { let mut peer = sample_peer_2(); let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; - assert_eq!(announce_data.peers, vec![previously_announced_peer]); + assert_eq!(announce_data.peers, vec![Arc::new(previously_announced_peer)]); } mod it_should_update_the_swarm_stats_for_the_torrent { @@ -1755,7 +1680,7 @@ mod tests { use aquatic_udp_protocol::AnnounceEvent; use crate::core::tests::the_tracker::{sample_info_hash, sample_peer, tracker_persisting_torrents_in_database}; - use crate::core::torrent::repository_asyn::RepositoryAsync; + use crate::core::torrent::repository::Repository; #[tokio::test] async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { @@ -1774,14 +1699,15 @@ mod tests { assert_eq!(swarm_stats.downloaded, 1); // Remove the newly updated torrent from memory - tracker.torrents.get_torrents_mut().await.remove(&info_hash); + tracker.torrents.remove(&info_hash).await; tracker.load_torrents_from_database().await.unwrap(); - let torrents = tracker.torrents.get_torrents().await; - assert!(torrents.contains_key(&info_hash)); - - let torrent_entry = torrents.get(&info_hash).unwrap(); + let torrent_entry = tracker + .torrents + .get(&info_hash) + .await + .expect("it should be able to get entry"); // It persists the number of completed peers. assert_eq!(torrent_entry.completed, 1); diff --git a/src/core/peer.rs b/src/core/peer.rs index 16aa1fe56..eb2b7b759 100644 --- a/src/core/peer.rs +++ b/src/core/peer.rs @@ -22,6 +22,7 @@ //! ``` use std::net::{IpAddr, SocketAddr}; use std::panic::Location; +use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use serde::Serialize; @@ -85,6 +86,58 @@ pub struct Peer { pub event: AnnounceEvent, } +pub trait ReadInfo { + fn is_seeder(&self) -> bool; + fn get_event(&self) -> AnnounceEvent; + fn get_id(&self) -> Id; + fn get_updated(&self) -> DurationSinceUnixEpoch; + fn get_address(&self) -> SocketAddr; +} + +impl ReadInfo for Peer { + fn is_seeder(&self) -> bool { + self.left.0 <= 0 && self.event != AnnounceEvent::Stopped + } + + fn get_event(&self) -> AnnounceEvent { + self.event + } + + fn get_id(&self) -> Id { + self.peer_id + } + + fn get_updated(&self) -> DurationSinceUnixEpoch { + self.updated + } + + fn get_address(&self) -> SocketAddr { + self.peer_addr + } +} + +impl ReadInfo for Arc { + fn is_seeder(&self) -> bool { + self.left.0 <= 0 && self.event != AnnounceEvent::Stopped + } + + fn get_event(&self) -> AnnounceEvent { + self.event + } + + fn get_id(&self) -> Id { + self.peer_id + } + + fn get_updated(&self) -> DurationSinceUnixEpoch { + self.updated + } + + fn get_address(&self) -> SocketAddr { + self.peer_addr + } +} + impl Peer { #[must_use] pub fn is_seeder(&self) -> bool { diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index eca6cbf3b..b265066f0 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -9,7 +9,8 @@ use std::sync::Arc; use serde::Deserialize; use crate::core::peer::Peer; -use crate::core::torrent::repository_asyn::RepositoryAsync; +use crate::core::torrent::entry::{self, ReadInfo}; +use crate::core::torrent::repository::Repository; use crate::core::Tracker; use crate::shared::bit_torrent::info_hash::InfoHash; @@ -94,41 +95,37 @@ impl Default for Pagination { /// It returns all the information the tracker has about one torrent in a [Info] struct. pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Option { - let db = tracker.torrents.get_torrents().await; - - let torrent_entry_option = db.get(info_hash); + let torrent_entry_option = tracker.torrents.get(info_hash).await; let torrent_entry = torrent_entry_option?; - let (seeders, completed, leechers) = torrent_entry.get_stats(); + let stats = entry::ReadInfo::get_stats(&torrent_entry); - let peers = torrent_entry.get_all_peers(); + let peers = entry::ReadPeers::get_peers(&torrent_entry, None); let peers = Some(peers.iter().map(|peer| (**peer)).collect()); Some(Info { info_hash: *info_hash, - seeders: u64::from(seeders), - completed: u64::from(completed), - leechers: u64::from(leechers), + seeders: u64::from(stats.complete), + completed: u64::from(stats.downloaded), + leechers: u64::from(stats.incomplete), peers, }) } /// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list. -pub async fn get_torrents_page(tracker: Arc, pagination: &Pagination) -> Vec { - let db = tracker.torrents.get_torrents().await; - +pub async fn get_torrents_page(tracker: Arc, pagination: Option<&Pagination>) -> Vec { let mut basic_infos: Vec = vec![]; - for (info_hash, torrent_entry) in db.iter().skip(pagination.offset as usize).take(pagination.limit as usize) { - let (seeders, completed, leechers) = torrent_entry.get_stats(); + for (info_hash, torrent_entry) in tracker.torrents.get_paginated(pagination).await { + let stats = entry::ReadInfo::get_stats(&torrent_entry); basic_infos.push(BasicInfo { - info_hash: *info_hash, - seeders: u64::from(seeders), - completed: u64::from(completed), - leechers: u64::from(leechers), + info_hash, + seeders: u64::from(stats.complete), + completed: u64::from(stats.downloaded), + leechers: u64::from(stats.incomplete), }); } @@ -137,19 +134,15 @@ pub async fn get_torrents_page(tracker: Arc, pagination: &Pagination) - /// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list. pub async fn get_torrents(tracker: Arc, info_hashes: &[InfoHash]) -> Vec { - let db = tracker.torrents.get_torrents().await; - let mut basic_infos: Vec = vec![]; for info_hash in info_hashes { - if let Some(entry) = db.get(info_hash) { - let (seeders, completed, leechers) = entry.get_stats(); - + if let Some(stats) = tracker.torrents.get(info_hash).await.map(|t| t.get_stats()) { basic_infos.push(BasicInfo { info_hash: *info_hash, - seeders: u64::from(seeders), - completed: u64::from(completed), - leechers: u64::from(leechers), + seeders: u64::from(stats.complete), + completed: u64::from(stats.downloaded), + leechers: u64::from(stats.incomplete), }); } } @@ -254,7 +247,7 @@ mod tests { async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let tracker = Arc::new(tracker_factory(&tracker_configuration())); - let torrents = get_torrents_page(tracker.clone(), &Pagination::default()).await; + let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; assert_eq!(torrents, vec![]); } @@ -270,7 +263,7 @@ mod tests { .update_torrent_with_peer_and_get_stats(&info_hash, &sample_peer()) .await; - let torrents = get_torrents_page(tracker.clone(), &Pagination::default()).await; + let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; assert_eq!( torrents, @@ -302,7 +295,7 @@ mod tests { let offset = 0; let limit = 1; - let torrents = get_torrents_page(tracker.clone(), &Pagination::new(offset, limit)).await; + let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::new(offset, limit))).await; assert_eq!(torrents.len(), 1); } @@ -326,7 +319,7 @@ mod tests { let offset = 1; let limit = 4000; - let torrents = get_torrents_page(tracker.clone(), &Pagination::new(offset, limit)).await; + let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::new(offset, limit))).await; assert_eq!(torrents.len(), 1); assert_eq!( @@ -356,7 +349,7 @@ mod tests { .update_torrent_with_peer_and_get_stats(&info_hash2, &sample_peer()) .await; - let torrents = get_torrents_page(tracker.clone(), &Pagination::default()).await; + let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; assert_eq!( torrents, diff --git a/src/core/torrent/entry.rs b/src/core/torrent/entry.rs new file mode 100644 index 000000000..619cce9b3 --- /dev/null +++ b/src/core/torrent/entry.rs @@ -0,0 +1,241 @@ +use std::fmt::Debug; +use std::sync::Arc; +use std::time::Duration; + +use aquatic_udp_protocol::AnnounceEvent; +use serde::{Deserialize, Serialize}; + +use super::SwarmMetadata; +use crate::core::peer::{self, ReadInfo as _}; +use crate::core::TrackerPolicy; +use crate::shared::clock::{Current, TimeNow}; + +/// A data structure containing all the information about a torrent in the tracker. +/// +/// This is the tracker entry for a given torrent and contains the swarm data, +/// that's the list of all the peers trying to download the same torrent. +/// The tracker keeps one entry like this for every torrent. +#[derive(Serialize, Deserialize, Clone, Debug, Default)] +pub struct Entry { + /// The swarm: a network of peers that are all trying to download the torrent associated to this entry + #[serde(skip)] + pub peers: std::collections::BTreeMap>, + /// The number of peers that have ever completed downloading the torrent associated to this entry + pub completed: u32, +} + +pub type MutexStd = Arc>; +pub type MutexTokio = Arc>; + +pub trait ReadInfo { + /// It returns the swarm metadata (statistics) as a struct: + /// + /// `(seeders, completed, leechers)` + fn get_stats(&self) -> SwarmMetadata; + + /// Returns True if Still a Valid Entry according to the Tracker Policy + fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool; +} + +pub trait ReadPeers { + /// Get all swarm peers, optionally limiting the result. + fn get_peers(&self, limit: Option) -> Vec>; + + /// It returns the list of peers for a given peer client, optionally limiting the + /// result. + /// + /// It filters out the input peer, typically because we want to return this + /// list of peers to that client peer. + fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec>; +} + +pub trait ReadAsync { + /// Get all swarm peers, optionally limiting the result. + fn get_peers(&self, limit: Option) -> impl std::future::Future>> + Send; + + /// It returns the list of peers for a given peer client, optionally limiting the + /// result. + /// + /// It filters out the input peer, typically because we want to return this + /// list of peers to that client peer. + fn get_peers_for_peer( + &self, + client: &peer::Peer, + limit: Option, + ) -> impl std::future::Future>> + Send; +} + +pub trait Update { + /// It updates a peer and returns true if the number of complete downloads have increased. + /// + /// The number of peers that have complete downloading is synchronously updated when peers are updated. + /// That's the total torrent downloads counter. + fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool; + + // It preforms a combined operation of `insert_or_update_peer` and `get_stats`. + fn insert_or_update_peer_and_get_stats(&mut self, peer: &peer::Peer) -> (bool, SwarmMetadata); + + /// It removes peer from the swarm that have not been updated for more than `max_peer_timeout` seconds + fn remove_inactive_peers(&mut self, max_peer_timeout: u32); +} + +pub trait UpdateSync { + fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool; + fn insert_or_update_peer_and_get_stats(&self, peer: &peer::Peer) -> (bool, SwarmMetadata); + fn remove_inactive_peers(&self, max_peer_timeout: u32); +} + +pub trait UpdateAsync { + fn insert_or_update_peer(&self, peer: &peer::Peer) -> impl std::future::Future + Send; + + fn insert_or_update_peer_and_get_stats( + &self, + peer: &peer::Peer, + ) -> impl std::future::Future + std::marker::Send; + + fn remove_inactive_peers(&self, max_peer_timeout: u32) -> impl std::future::Future + Send; +} + +impl ReadInfo for Entry { + #[allow(clippy::cast_possible_truncation)] + fn get_stats(&self) -> SwarmMetadata { + let complete: u32 = self.peers.values().filter(|peer| peer.is_seeder()).count() as u32; + let incomplete: u32 = self.peers.len() as u32 - complete; + + SwarmMetadata { + downloaded: self.completed, + complete, + incomplete, + } + } + + fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool { + if policy.persistent_torrent_completed_stat && self.completed > 0 { + return true; + } + + if policy.remove_peerless_torrents && self.peers.is_empty() { + return false; + } + + true + } +} + +impl ReadPeers for Entry { + fn get_peers(&self, limit: Option) -> Vec> { + match limit { + Some(limit) => self.peers.values().take(limit).cloned().collect(), + None => self.peers.values().cloned().collect(), + } + } + + fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec> { + match limit { + Some(limit) => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer.get_address() != client.get_address()) + // Limit the number of peers on the result + .take(limit) + .cloned() + .collect(), + None => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer.get_address() != client.get_address()) + .cloned() + .collect(), + } + } +} + +impl ReadPeers for MutexStd { + fn get_peers(&self, limit: Option) -> Vec> { + self.lock().expect("it should get lock").get_peers(limit) + } + + fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec> { + self.lock().expect("it should get lock").get_peers_for_peer(client, limit) + } +} + +impl ReadAsync for MutexTokio { + async fn get_peers(&self, limit: Option) -> Vec> { + self.lock().await.get_peers(limit) + } + + async fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec> { + self.lock().await.get_peers_for_peer(client, limit) + } +} + +impl Update for Entry { + fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool { + let mut did_torrent_stats_change: bool = false; + + match peer.get_event() { + AnnounceEvent::Stopped => { + drop(self.peers.remove(&peer.get_id())); + } + AnnounceEvent::Completed => { + let peer_old = self.peers.insert(peer.get_id(), Arc::new(*peer)); + // Don't count if peer was not previously known and not already completed. + if peer_old.is_some_and(|p| p.event != AnnounceEvent::Completed) { + self.completed += 1; + did_torrent_stats_change = true; + } + } + _ => { + drop(self.peers.insert(peer.get_id(), Arc::new(*peer))); + } + } + + did_torrent_stats_change + } + + fn insert_or_update_peer_and_get_stats(&mut self, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let changed = self.insert_or_update_peer(peer); + let stats = self.get_stats(); + (changed, stats) + } + + fn remove_inactive_peers(&mut self, max_peer_timeout: u32) { + let current_cutoff = Current::sub(&Duration::from_secs(u64::from(max_peer_timeout))).unwrap_or_default(); + self.peers.retain(|_, peer| peer.get_updated() > current_cutoff); + } +} + +impl UpdateSync for MutexStd { + fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool { + self.lock().expect("it should lock the entry").insert_or_update_peer(peer) + } + + fn insert_or_update_peer_and_get_stats(&self, peer: &peer::Peer) -> (bool, SwarmMetadata) { + self.lock() + .expect("it should lock the entry") + .insert_or_update_peer_and_get_stats(peer) + } + + fn remove_inactive_peers(&self, max_peer_timeout: u32) { + self.lock() + .expect("it should lock the entry") + .remove_inactive_peers(max_peer_timeout); + } +} + +impl UpdateAsync for MutexTokio { + async fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool { + self.lock().await.insert_or_update_peer(peer) + } + + async fn insert_or_update_peer_and_get_stats(&self, peer: &peer::Peer) -> (bool, SwarmMetadata) { + self.lock().await.insert_or_update_peer_and_get_stats(peer) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + self.lock().await.remove_inactive_peers(max_peer_timeout); + } +} diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index 49c1f61f8..608765cf8 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -27,49 +27,11 @@ //! - The number of peers that have NOT completed downloading the torrent and are still active, that means they are actively participating in the network. //! Peer that don not have a full copy of the torrent data are called "leechers". //! -//! > **NOTICE**: that both [`SwarmMetadata`] and [`SwarmStats`] contain the same information. [`SwarmMetadata`] is using the names used on [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). -pub mod repository_asyn; -pub mod repository_sync; +//! > **NOTICE**: that both [`SwarmMetadata`] and [`SwarmMetadata`] contain the same information. [`SwarmMetadata`] is using the names used on [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). +pub mod entry; +pub mod repository; -use std::sync::Arc; -use std::time::Duration; - -use aquatic_udp_protocol::AnnounceEvent; use derive_more::Constructor; -use serde::{Deserialize, Serialize}; - -use super::peer::{self, Peer}; -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::shared::clock::{Current, TimeNow}; - -pub trait UpdateTorrentSync { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool); -} - -pub trait UpdateTorrentAsync { - fn update_torrent_with_peer_and_get_stats( - &self, - info_hash: &InfoHash, - peer: &peer::Peer, - ) -> impl std::future::Future + Send; -} - -/// A data structure containing all the information about a torrent in the tracker. -/// -/// This is the tracker entry for a given torrent and contains the swarm data, -/// that's the list of all the peers trying to download the same torrent. -/// The tracker keeps one entry like this for every torrent. -#[derive(Serialize, Deserialize, Clone, Debug)] -pub struct Entry { - /// The swarm: a network of peers that are all trying to download the torrent associated to this entry - #[serde(skip)] - pub peers: std::collections::BTreeMap, - /// The number of peers that have ever completed downloading the torrent associated to this entry - pub completed: u32, -} - -pub type EntryMutexTokio = Arc>; -pub type EntryMutexStd = Arc>; /// Swarm statistics for one torrent. /// Swarm metadata dictionary in the scrape response. @@ -92,122 +54,6 @@ impl SwarmMetadata { } } -/// [`SwarmStats`] has the same form as [`SwarmMetadata`] -pub type SwarmStats = SwarmMetadata; - -impl Entry { - #[must_use] - pub fn new() -> Entry { - Entry { - peers: std::collections::BTreeMap::new(), - completed: 0, - } - } - - /// It updates a peer and returns true if the number of complete downloads have increased. - /// - /// The number of peers that have complete downloading is synchronously updated when peers are updated. - /// That's the total torrent downloads counter. - pub fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool { - let mut did_torrent_stats_change: bool = false; - - match peer.event { - AnnounceEvent::Stopped => { - let _: Option = self.peers.remove(&peer.peer_id); - } - AnnounceEvent::Completed => { - let peer_old = self.peers.insert(peer.peer_id, *peer); - // Don't count if peer was not previously known and not already completed. - if peer_old.is_some_and(|p| p.event != AnnounceEvent::Completed) { - self.completed += 1; - did_torrent_stats_change = true; - } - } - _ => { - let _: Option = self.peers.insert(peer.peer_id, *peer); - } - } - - did_torrent_stats_change - } - - /// Get all swarm peers. - #[must_use] - pub fn get_all_peers(&self) -> Vec<&peer::Peer> { - self.peers.values().collect() - } - - /// Get swarm peers, limiting the result. - #[must_use] - pub fn get_peers(&self, limit: usize) -> Vec<&peer::Peer> { - self.peers.values().take(limit).collect() - } - - /// It returns the list of peers for a given peer client. - /// - /// It filters out the input peer, typically because we want to return this - /// list of peers to that client peer. - #[must_use] - pub fn get_all_peers_for_peer(&self, client: &Peer) -> Vec<&peer::Peer> { - self.peers - .values() - // Take peers which are not the client peer - .filter(|peer| peer.peer_addr != client.peer_addr) - .collect() - } - - /// It returns the list of peers for a given peer client, limiting the - /// result. - /// - /// It filters out the input peer, typically because we want to return this - /// list of peers to that client peer. - #[must_use] - pub fn get_peers_for_peer(&self, client: &Peer, limit: usize) -> Vec<&peer::Peer> { - self.peers - .values() - // Take peers which are not the client peer - .filter(|peer| peer.peer_addr != client.peer_addr) - // Limit the number of peers on the result - .take(limit) - .collect() - } - - /// It returns the swarm metadata (statistics) as a tuple: - /// - /// `(seeders, completed, leechers)` - #[allow(clippy::cast_possible_truncation)] - #[must_use] - pub fn get_stats(&self) -> (u32, u32, u32) { - let seeders: u32 = self.peers.values().filter(|peer| peer.is_seeder()).count() as u32; - let leechers: u32 = self.peers.len() as u32 - seeders; - (seeders, self.completed, leechers) - } - - /// It returns the swarm metadata (statistics) as an struct - #[must_use] - pub fn get_swarm_metadata(&self) -> SwarmMetadata { - // code-review: consider using always this function instead of `get_stats`. - let (seeders, completed, leechers) = self.get_stats(); - SwarmMetadata { - complete: seeders, - downloaded: completed, - incomplete: leechers, - } - } - - /// It removes peer from the swarm that have not been updated for more than `max_peer_timeout` seconds - pub fn remove_inactive_peers(&mut self, max_peer_timeout: u32) { - let current_cutoff = Current::sub(&Duration::from_secs(u64::from(max_peer_timeout))).unwrap_or_default(); - self.peers.retain(|_, peer| peer.updated > current_cutoff); - } -} - -impl Default for Entry { - fn default() -> Self { - Self::new() - } -} - #[cfg(test)] mod tests { @@ -215,11 +61,12 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::ops::Sub; + use std::sync::Arc; use std::time::Duration; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - use crate::core::torrent::Entry; + use crate::core::torrent::entry::{self, ReadInfo, ReadPeers, Update}; use crate::core::{peer, TORRENT_PEERS_LIMIT}; use crate::shared::clock::{Current, DurationSinceUnixEpoch, Stopped, StoppedTime, Time, Working}; @@ -291,59 +138,59 @@ mod tests { #[test] fn the_default_torrent_entry_should_contain_an_empty_list_of_peers() { - let torrent_entry = Entry::new(); + let torrent_entry = entry::Entry::default(); - assert_eq!(torrent_entry.get_all_peers().len(), 0); + assert_eq!(torrent_entry.get_peers(None).len(), 0); } #[test] fn a_new_peer_can_be_added_to_a_torrent_entry() { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - assert_eq!(*torrent_entry.get_all_peers()[0], torrent_peer); - assert_eq!(torrent_entry.get_all_peers().len(), 1); + assert_eq!(*torrent_entry.get_peers(None)[0], torrent_peer); + assert_eq!(torrent_entry.get_peers(None).len(), 1); } #[test] fn a_torrent_entry_should_contain_the_list_of_peers_that_were_added_to_the_torrent() { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - assert_eq!(torrent_entry.get_all_peers(), vec![&torrent_peer]); + assert_eq!(torrent_entry.get_peers(None), vec![Arc::new(torrent_peer)]); } #[test] fn a_peer_can_be_updated_in_a_torrent_entry() { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let mut torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer torrent_peer.event = AnnounceEvent::Completed; // Update the peer torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry - assert_eq!(torrent_entry.get_all_peers()[0].event, AnnounceEvent::Completed); + assert_eq!(torrent_entry.get_peers(None)[0].event, AnnounceEvent::Completed); } #[test] fn a_peer_should_be_removed_from_a_torrent_entry_when_the_peer_announces_it_has_stopped() { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let mut torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer torrent_peer.event = AnnounceEvent::Stopped; // Update the peer torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry - assert_eq!(torrent_entry.get_all_peers().len(), 0); + assert_eq!(torrent_entry.get_peers(None).len(), 0); } #[test] fn torrent_stats_change_when_a_previously_known_peer_announces_it_has_completed_the_torrent() { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let mut torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -357,7 +204,7 @@ mod tests { #[test] fn torrent_stats_should_not_change_when_a_peer_announces_it_has_completed_the_torrent_if_it_is_the_first_announce_from_the_peer( ) { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); // Add a peer that did not exist before in the entry @@ -369,20 +216,20 @@ mod tests { #[test] fn a_torrent_entry_should_return_the_list_of_peers_for_a_given_peer_filtering_out_the_client_that_is_making_the_request() { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let peer_socket_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); let torrent_peer = TorrentPeerBuilder::default().with_peer_address(peer_socket_address).into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add peer // Get peers excluding the one we have just added - let peers = torrent_entry.get_all_peers_for_peer(&torrent_peer); + let peers = torrent_entry.get_peers_for_peer(&torrent_peer, None); assert_eq!(peers.len(), 0); } #[test] fn two_peers_with_the_same_ip_but_different_port_should_be_considered_different_peers() { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let peer_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); @@ -399,7 +246,7 @@ mod tests { torrent_entry.insert_or_update_peer(&torrent_peer_2); // Get peers for peer 1 - let peers = torrent_entry.get_all_peers_for_peer(&torrent_peer_1); + let peers = torrent_entry.get_peers_for_peer(&torrent_peer_1, None); // The peer 2 using the same IP but different port should be included assert_eq!(peers[0].peer_addr.ip(), Ipv4Addr::new(127, 0, 0, 1)); @@ -416,7 +263,7 @@ mod tests { #[test] fn the_tracker_should_limit_the_list_of_peers_to_74_when_clients_scrape_torrents() { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); // We add one more peer than the scrape limit for peer_number in 1..=74 + 1 { @@ -426,35 +273,35 @@ mod tests { torrent_entry.insert_or_update_peer(&torrent_peer); } - let peers = torrent_entry.get_peers(TORRENT_PEERS_LIMIT); + let peers = torrent_entry.get_peers(Some(TORRENT_PEERS_LIMIT)); assert_eq!(peers.len(), 74); } #[test] fn torrent_stats_should_have_the_number_of_seeders_for_a_torrent() { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let torrent_seeder = a_torrent_seeder(); torrent_entry.insert_or_update_peer(&torrent_seeder); // Add seeder - assert_eq!(torrent_entry.get_stats().0, 1); + assert_eq!(torrent_entry.get_stats().complete, 1); } #[test] fn torrent_stats_should_have_the_number_of_leechers_for_a_torrent() { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let torrent_leecher = a_torrent_leecher(); torrent_entry.insert_or_update_peer(&torrent_leecher); // Add leecher - assert_eq!(torrent_entry.get_stats().2, 1); + assert_eq!(torrent_entry.get_stats().incomplete, 1); } #[test] fn torrent_stats_should_have_the_number_of_peers_that_having_announced_at_least_two_events_the_latest_one_is_the_completed_event( ) { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let mut torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -462,28 +309,28 @@ mod tests { torrent_peer.event = AnnounceEvent::Completed; torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer - let number_of_previously_known_peers_with_completed_torrent = torrent_entry.get_stats().1; + let number_of_previously_known_peers_with_completed_torrent = torrent_entry.get_stats().complete; assert_eq!(number_of_previously_known_peers_with_completed_torrent, 1); } #[test] fn torrent_stats_should_not_include_a_peer_in_the_completed_counter_if_the_peer_has_announced_only_one_event() { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); // Announce "Completed" torrent download event. // It's the first event announced from this peer. torrent_entry.insert_or_update_peer(&torrent_peer_announcing_complete_event); // Add the peer - let number_of_peers_with_completed_torrent = torrent_entry.get_stats().1; + let number_of_peers_with_completed_torrent = torrent_entry.get_stats().downloaded; assert_eq!(number_of_peers_with_completed_torrent, 0); } #[test] fn a_torrent_entry_should_remove_a_peer_not_updated_after_a_timeout_in_seconds() { - let mut torrent_entry = Entry::new(); + let mut torrent_entry = entry::Entry::default(); let timeout = 120u32; diff --git a/src/core/torrent/repository/mod.rs b/src/core/torrent/repository/mod.rs new file mode 100644 index 000000000..3af33aebe --- /dev/null +++ b/src/core/torrent/repository/mod.rs @@ -0,0 +1,30 @@ +use super::SwarmMetadata; +use crate::core::databases::PersistentTorrents; +use crate::core::services::torrent::Pagination; +use crate::core::{peer, TorrentsMetrics, TrackerPolicy}; +use crate::shared::bit_torrent::info_hash::InfoHash; + +pub mod std_sync; +pub mod tokio_sync; + +pub trait Repository: Default { + fn get(&self, key: &InfoHash) -> impl std::future::Future> + Send; + fn get_metrics(&self) -> impl std::future::Future + Send; + fn get_paginated(&self, pagination: Option<&Pagination>) -> impl std::future::Future> + Send; + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) -> impl std::future::Future + Send; + fn remove(&self, key: &InfoHash) -> impl std::future::Future> + Send; + fn remove_inactive_peers(&self, max_peer_timeout: u32) -> impl std::future::Future + Send; + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> impl std::future::Future + Send; +} + +pub trait UpdateTorrentSync { + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata); +} + +pub trait UpdateTorrentAsync { + fn update_torrent_with_peer_and_get_stats( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + ) -> impl std::future::Future + Send; +} diff --git a/src/core/torrent/repository/std_sync.rs b/src/core/torrent/repository/std_sync.rs new file mode 100644 index 000000000..ba38db6ed --- /dev/null +++ b/src/core/torrent/repository/std_sync.rs @@ -0,0 +1,365 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use futures::executor::block_on; +use futures::future::join_all; + +use super::{Repository, UpdateTorrentAsync, UpdateTorrentSync}; +use crate::core::databases::PersistentTorrents; +use crate::core::services::torrent::Pagination; +use crate::core::torrent::entry::{Entry, ReadInfo, Update, UpdateAsync, UpdateSync}; +use crate::core::torrent::{entry, SwarmMetadata}; +use crate::core::{peer, TorrentsMetrics}; +use crate::shared::bit_torrent::info_hash::InfoHash; + +#[derive(Default)] +pub struct RepositoryStdRwLock { + torrents: std::sync::RwLock>, +} + +impl RepositoryStdRwLock { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl UpdateTorrentAsync for RepositoryStdRwLock { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let maybe_existing_torrent_entry = self.get_torrents().get(info_hash).cloned(); + + let torrent_entry = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { + existing_torrent_entry + } else { + let mut torrents_lock = self.get_torrents_mut(); + let entry = torrents_lock.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + torrent_entry.insert_or_update_peer_and_get_stats(peer).await + } +} +impl Repository for RepositoryStdRwLock { + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexTokio)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let db = self.get_torrents(); + let metrics: Arc> = Arc::default(); + + let futures = db.values().map(|e| { + let metrics = metrics.clone(); + let entry = e.clone(); + + tokio::spawn(async move { + let stats = entry.lock().await.get_stats(); + metrics.lock().await.seeders += u64::from(stats.complete); + metrics.lock().await.completed += u64::from(stats.downloaded); + metrics.lock().await.leechers += u64::from(stats.incomplete); + metrics.lock().await.torrents += 1; + }) + }); + + block_on(join_all(futures)); + + *metrics.blocking_lock_owned() + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut db = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if db.contains_key(info_hash) { + continue; + } + + let entry = entry::MutexTokio::new( + Entry { + peers: BTreeMap::default(), + completed: *completed, + } + .into(), + ); + + db.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + let db = self.get_torrents(); + + let futures = db.values().map(|e| { + let entry = e.clone(); + tokio::spawn(async move { entry.lock().await.remove_inactive_peers(max_peer_timeout) }) + }); + + block_on(join_all(futures)); + } + + async fn remove_peerless_torrents(&self, policy: &crate::core::TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.blocking_lock().is_not_zombie(policy)); + } +} + +impl RepositoryStdRwLock { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl UpdateTorrentSync for RepositoryStdRwLock { + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let maybe_existing_torrent_entry = self.get_torrents().get(info_hash).cloned(); + + let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { + existing_torrent_entry + } else { + let mut torrents_lock = self.get_torrents_mut(); + let entry = torrents_lock + .entry(*info_hash) + .or_insert(Arc::new(std::sync::Mutex::new(Entry::default()))); + entry.clone() + }; + + torrent_entry.insert_or_update_peer_and_get_stats(peer) + } +} +impl Repository for RepositoryStdRwLock { + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let db = self.get_torrents(); + let metrics: Arc> = Arc::default(); + + let futures = db.values().map(|e| { + let metrics = metrics.clone(); + let entry = e.clone(); + + tokio::spawn(async move { + let stats = entry.lock().expect("it should lock the entry").get_stats(); + metrics.lock().await.seeders += u64::from(stats.complete); + metrics.lock().await.completed += u64::from(stats.downloaded); + metrics.lock().await.leechers += u64::from(stats.incomplete); + metrics.lock().await.torrents += 1; + }) + }); + + block_on(join_all(futures)); + + *metrics.blocking_lock_owned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexStd)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = entry::MutexStd::new( + Entry { + peers: BTreeMap::default(), + completed: *completed, + } + .into(), + ); + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + let db = self.get_torrents(); + + let futures = db.values().map(|e| { + let entry = e.clone(); + tokio::spawn(async move { + entry + .lock() + .expect("it should get lock for entry") + .remove_inactive_peers(max_peer_timeout); + }) + }); + + block_on(join_all(futures)); + } + + async fn remove_peerless_torrents(&self, policy: &crate::core::TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.lock().expect("it should lock entry").is_not_zombie(policy)); + } +} + +impl RepositoryStdRwLock { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("it should get the read lock") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("it should get the write lock") + } +} + +impl UpdateTorrentSync for RepositoryStdRwLock { + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let mut torrents = self.torrents.write().unwrap(); + + let torrent_entry = match torrents.entry(*info_hash) { + std::collections::btree_map::Entry::Vacant(vacant) => vacant.insert(Entry::default()), + std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), + }; + + torrent_entry.insert_or_update_peer_and_get_stats(peer) + } +} +impl Repository for RepositoryStdRwLock { + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let db = self.get_torrents(); + let metrics: Arc> = Arc::default(); + + let futures = db.values().map(|e| { + let metrics = metrics.clone(); + let entry = e.clone(); + + tokio::spawn(async move { + let stats = entry.get_stats(); + metrics.lock().await.seeders += u64::from(stats.complete); + metrics.lock().await.completed += u64::from(stats.downloaded); + metrics.lock().await.leechers += u64::from(stats.incomplete); + metrics.lock().await.torrents += 1; + }) + }); + + block_on(join_all(futures)); + + *metrics.blocking_lock_owned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, Entry)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = Entry { + peers: BTreeMap::default(), + completed: *completed, + }; + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + let mut db = self.get_torrents_mut(); + + drop(db.values_mut().map(|e| e.remove_inactive_peers(max_peer_timeout))); + } + + async fn remove_peerless_torrents(&self, policy: &crate::core::TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.is_not_zombie(policy)); + } +} diff --git a/src/core/torrent/repository/tokio_sync.rs b/src/core/torrent/repository/tokio_sync.rs new file mode 100644 index 000000000..83edf1188 --- /dev/null +++ b/src/core/torrent/repository/tokio_sync.rs @@ -0,0 +1,378 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use futures::future::join_all; + +use super::{Repository, UpdateTorrentAsync}; +use crate::core::databases::PersistentTorrents; +use crate::core::services::torrent::Pagination; +use crate::core::torrent::entry::{Entry, ReadInfo, Update, UpdateAsync, UpdateSync}; +use crate::core::torrent::{entry, SwarmMetadata}; +use crate::core::{peer, TorrentsMetrics, TrackerPolicy}; +use crate::shared::bit_torrent::info_hash::InfoHash; + +#[derive(Default)] +pub struct RepositoryTokioRwLock { + torrents: tokio::sync::RwLock>, +} + +impl RepositoryTokioRwLock { + async fn get_torrents<'a>( + &'a self, + ) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl UpdateTorrentAsync for RepositoryTokioRwLock { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let maybe_torrent; + { + let db = self.torrents.read().await; + maybe_torrent = db.get(info_hash).cloned(); + } + + let torrent = if let Some(torrent) = maybe_torrent { + torrent + } else { + let entry = entry::MutexTokio::default(); + let mut db = self.torrents.write().await; + db.insert(*info_hash, entry.clone()); + entry + }; + + torrent.insert_or_update_peer_and_get_stats(peer).await + } +} + +impl Repository for RepositoryTokioRwLock { + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexTokio)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let db = self.get_torrents().await; + let metrics: Arc> = Arc::default(); + + let futures = db.values().map(|e| { + let metrics = metrics.clone(); + let entry = e.clone(); + + tokio::spawn(async move { + let stats = entry.lock().await.get_stats(); + metrics.lock().await.seeders += u64::from(stats.complete); + metrics.lock().await.completed += u64::from(stats.downloaded); + metrics.lock().await.leechers += u64::from(stats.incomplete); + metrics.lock().await.torrents += 1; + }) + }); + + join_all(futures).await; + + *metrics.lock_owned().await + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut db = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if db.contains_key(info_hash) { + continue; + } + + let entry = entry::MutexTokio::new( + Entry { + peers: BTreeMap::default(), + completed: *completed, + } + .into(), + ); + + db.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + let db = self.get_torrents().await; + + let futures = db.values().map(|e| { + let entry = e.clone(); + tokio::spawn(async move { entry.lock().await.remove_inactive_peers(max_peer_timeout) }) + }); + + join_all(futures).await; + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.blocking_lock().is_not_zombie(policy)); + } +} + +impl RepositoryTokioRwLock { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl UpdateTorrentAsync for RepositoryTokioRwLock { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let maybe_torrent; + { + let db = self.torrents.read().await; + maybe_torrent = db.get(info_hash).cloned(); + } + + let torrent = if let Some(torrent) = maybe_torrent { + torrent + } else { + let entry = entry::MutexStd::default(); + let mut db = self.torrents.write().await; + db.insert(*info_hash, entry.clone()); + entry + }; + + torrent.insert_or_update_peer_and_get_stats(peer) + } +} + +impl Repository for RepositoryTokioRwLock { + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexStd)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let db = self.get_torrents().await; + let metrics: Arc> = Arc::default(); + + let futures = db.values().map(|e| { + let metrics = metrics.clone(); + let entry = e.clone(); + + tokio::spawn(async move { + let stats = entry.lock().expect("it should lock the entry").get_stats(); + metrics.lock().await.seeders += u64::from(stats.complete); + metrics.lock().await.completed += u64::from(stats.downloaded); + metrics.lock().await.leechers += u64::from(stats.incomplete); + metrics.lock().await.torrents += 1; + }) + }); + + join_all(futures).await; + + *metrics.lock_owned().await + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = entry::MutexStd::new( + Entry { + peers: BTreeMap::default(), + completed: *completed, + } + .into(), + ); + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + let db = self.get_torrents().await; + + let futures = db.values().map(|e| { + let entry = e.clone(); + tokio::spawn(async move { + entry + .lock() + .expect("it should get lock for entry") + .remove_inactive_peers(max_peer_timeout); + }) + }); + + join_all(futures).await; + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.lock().expect("it should lock entry").is_not_zombie(policy)); + } +} + +impl RepositoryTokioRwLock { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>(&'a self) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl UpdateTorrentAsync for RepositoryTokioRwLock { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let mut db = self.torrents.write().await; + + let torrent = db.entry(*info_hash).or_insert(Entry::default()); + + torrent.insert_or_update_peer_and_get_stats(peer) + } +} + +impl Repository for RepositoryTokioRwLock { + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, Entry)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let db = self.get_torrents().await; + let metrics: Arc> = Arc::default(); + + let futures = db.values().map(|e| { + let metrics = metrics.clone(); + let entry = e.clone(); + + tokio::spawn(async move { + let stats = entry.get_stats(); + metrics.lock().await.seeders += u64::from(stats.complete); + metrics.lock().await.completed += u64::from(stats.downloaded); + metrics.lock().await.leechers += u64::from(stats.incomplete); + metrics.lock().await.torrents += 1; + }) + }); + + join_all(futures).await; + + *metrics.lock_owned().await + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = Entry { + peers: BTreeMap::default(), + completed: *completed, + }; + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + let mut db = self.get_torrents_mut().await; + + drop(db.values_mut().map(|e| e.remove_inactive_peers(max_peer_timeout))); + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.is_not_zombie(policy)); + } +} diff --git a/src/core/torrent/repository_asyn.rs b/src/core/torrent/repository_asyn.rs deleted file mode 100644 index ad10f85b4..000000000 --- a/src/core/torrent/repository_asyn.rs +++ /dev/null @@ -1,187 +0,0 @@ -use std::sync::Arc; - -use super::{EntryMutexStd, EntryMutexTokio, UpdateTorrentAsync}; -use crate::core::peer; -use crate::core::torrent::{Entry, SwarmStats}; -use crate::shared::bit_torrent::info_hash::InfoHash; - -pub trait RepositoryAsync: Default { - fn get_torrents<'a>( - &'a self, - ) -> impl std::future::Future>> + Send - where - std::collections::BTreeMap: 'a; - - fn get_torrents_mut<'a>( - &'a self, - ) -> impl std::future::Future>> + Send - where - std::collections::BTreeMap: 'a; -} - -pub struct RepositoryTokioRwLock { - torrents: tokio::sync::RwLock>, -} -impl UpdateTorrentAsync for RepositoryTokioRwLock { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { - let maybe_existing_torrent_entry = self.get_torrents().await.get(info_hash).cloned(); - - let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { - existing_torrent_entry - } else { - let mut torrents_lock = self.get_torrents_mut().await; - let entry = torrents_lock - .entry(*info_hash) - .or_insert(Arc::new(tokio::sync::Mutex::new(Entry::new()))); - entry.clone() - }; - - let (stats, stats_updated) = { - let mut torrent_entry_lock = torrent_entry.lock().await; - let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); - let stats = torrent_entry_lock.get_stats(); - - (stats, stats_updated) - }; - - ( - SwarmStats { - downloaded: stats.1, - complete: stats.0, - incomplete: stats.2, - }, - stats_updated, - ) - } -} - -impl RepositoryAsync for RepositoryTokioRwLock { - async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().await - } - - async fn get_torrents_mut<'a>( - &'a self, - ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().await - } -} - -impl Default for RepositoryTokioRwLock { - fn default() -> Self { - Self { - torrents: tokio::sync::RwLock::default(), - } - } -} - -impl UpdateTorrentAsync for RepositoryTokioRwLock { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { - let maybe_existing_torrent_entry = self.get_torrents().await.get(info_hash).cloned(); - - let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { - existing_torrent_entry - } else { - let mut torrents_lock = self.get_torrents_mut().await; - let entry = torrents_lock - .entry(*info_hash) - .or_insert(Arc::new(std::sync::Mutex::new(Entry::new()))); - entry.clone() - }; - - let (stats, stats_updated) = { - let mut torrent_entry_lock = torrent_entry.lock().unwrap(); - let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); - let stats = torrent_entry_lock.get_stats(); - - (stats, stats_updated) - }; - - ( - SwarmStats { - downloaded: stats.1, - complete: stats.0, - incomplete: stats.2, - }, - stats_updated, - ) - } -} - -impl RepositoryAsync for RepositoryTokioRwLock { - async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().await - } - - async fn get_torrents_mut<'a>( - &'a self, - ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().await - } -} - -impl Default for RepositoryTokioRwLock { - fn default() -> Self { - Self { - torrents: tokio::sync::RwLock::default(), - } - } -} - -impl UpdateTorrentAsync for RepositoryTokioRwLock { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { - let (stats, stats_updated) = { - let mut torrents_lock = self.torrents.write().await; - let torrent_entry = torrents_lock.entry(*info_hash).or_insert(Entry::new()); - let stats_updated = torrent_entry.insert_or_update_peer(peer); - let stats = torrent_entry.get_stats(); - - (stats, stats_updated) - }; - - ( - SwarmStats { - downloaded: stats.1, - complete: stats.0, - incomplete: stats.2, - }, - stats_updated, - ) - } -} - -impl RepositoryAsync for RepositoryTokioRwLock { - async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().await - } - - async fn get_torrents_mut<'a>(&'a self) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().await - } -} - -impl Default for RepositoryTokioRwLock { - fn default() -> Self { - Self { - torrents: tokio::sync::RwLock::default(), - } - } -} diff --git a/src/core/torrent/repository_sync.rs b/src/core/torrent/repository_sync.rs deleted file mode 100644 index 3b01eb8be..000000000 --- a/src/core/torrent/repository_sync.rs +++ /dev/null @@ -1,177 +0,0 @@ -use std::sync::{Arc, RwLock}; - -use super::{EntryMutexStd, EntryMutexTokio, UpdateTorrentAsync, UpdateTorrentSync}; -use crate::core::peer; -use crate::core::torrent::{Entry, SwarmStats}; -use crate::shared::bit_torrent::info_hash::InfoHash; - -pub trait RepositorySync: Default { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a; - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a; -} - -pub struct RepositoryStdRwLock { - torrents: std::sync::RwLock>, -} - -impl UpdateTorrentAsync for RepositoryStdRwLock { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { - let maybe_existing_torrent_entry = self.get_torrents().get(info_hash).cloned(); - - let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { - existing_torrent_entry - } else { - let mut torrents_lock = self.get_torrents_mut(); - let entry = torrents_lock - .entry(*info_hash) - .or_insert(Arc::new(tokio::sync::Mutex::new(Entry::new()))); - entry.clone() - }; - - let (stats, stats_updated) = { - let mut torrent_entry_lock = torrent_entry.lock().await; - let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); - let stats = torrent_entry_lock.get_stats(); - - (stats, stats_updated) - }; - - ( - SwarmStats { - downloaded: stats.1, - complete: stats.0, - incomplete: stats.2, - }, - stats_updated, - ) - } -} -impl RepositorySync for RepositoryStdRwLock { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().expect("unable to get torrent list") - } - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().expect("unable to get writable torrent list") - } -} - -impl Default for RepositoryStdRwLock { - fn default() -> Self { - Self { - torrents: RwLock::default(), - } - } -} -impl UpdateTorrentSync for RepositoryStdRwLock { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { - let maybe_existing_torrent_entry = self.get_torrents().get(info_hash).cloned(); - - let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { - existing_torrent_entry - } else { - let mut torrents_lock = self.get_torrents_mut(); - let entry = torrents_lock - .entry(*info_hash) - .or_insert(Arc::new(std::sync::Mutex::new(Entry::new()))); - entry.clone() - }; - - let (stats, stats_updated) = { - let mut torrent_entry_lock = torrent_entry.lock().unwrap(); - let stats_updated = torrent_entry_lock.insert_or_update_peer(peer); - let stats = torrent_entry_lock.get_stats(); - - (stats, stats_updated) - }; - - ( - SwarmStats { - downloaded: stats.1, - complete: stats.0, - incomplete: stats.2, - }, - stats_updated, - ) - } -} -impl RepositorySync for RepositoryStdRwLock { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().expect("unable to get torrent list") - } - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().expect("unable to get writable torrent list") - } -} - -impl Default for RepositoryStdRwLock { - fn default() -> Self { - Self { - torrents: RwLock::default(), - } - } -} - -impl UpdateTorrentSync for RepositoryStdRwLock { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) { - let mut torrents = self.torrents.write().unwrap(); - - let torrent_entry = match torrents.entry(*info_hash) { - std::collections::btree_map::Entry::Vacant(vacant) => vacant.insert(Entry::new()), - std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), - }; - - let stats_updated = torrent_entry.insert_or_update_peer(peer); - let stats = torrent_entry.get_stats(); - - ( - SwarmStats { - downloaded: stats.1, - complete: stats.0, - incomplete: stats.2, - }, - stats_updated, - ) - } -} -impl RepositorySync for RepositoryStdRwLock { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().expect("unable to get torrent list") - } - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().expect("unable to get writable torrent list") - } -} - -impl Default for RepositoryStdRwLock { - fn default() -> Self { - Self { - torrents: RwLock::default(), - } - } -} diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs index dcb92dec3..999580da7 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/src/servers/apis/v1/context/torrent/handlers.rs @@ -82,7 +82,7 @@ pub async fn get_torrents_handler(State(tracker): State>, paginatio torrent_list_response( &get_torrents_page( tracker.clone(), - &Pagination::new_with_options(pagination.0.offset, pagination.0.limit), + Some(&Pagination::new_with_options(pagination.0.offset, pagination.0.limit)), ) .await, ) diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index b1b474ea9..619632ae4 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -79,7 +79,7 @@ impl From for Normal { incomplete: data.stats.incomplete.into(), interval: data.policy.interval.into(), min_interval: data.policy.interval_min.into(), - peers: data.peers.into_iter().collect(), + peers: data.peers.iter().map(AsRef::as_ref).copied().collect(), } } } @@ -116,7 +116,7 @@ pub struct Compact { impl From for Compact { fn from(data: AnnounceData) -> Self { - let compact_peers: Vec = data.peers.into_iter().collect(); + let compact_peers: Vec = data.peers.iter().map(AsRef::as_ref).copied().collect(); let (peers, peers6): (Vec>, Vec>) = compact_peers.into_iter().collect(); @@ -313,12 +313,13 @@ impl FromIterator> for CompactPeersEncoded { mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; use torrust_tracker_configuration::AnnouncePolicy; use crate::core::peer::fixture::PeerBuilder; use crate::core::peer::Id; - use crate::core::torrent::SwarmStats; + use crate::core::torrent::SwarmMetadata; use crate::core::AnnounceData; use crate::servers::http::v1::responses::announce::{Announce, Compact, Normal, Response}; @@ -350,8 +351,8 @@ mod tests { )) .build(); - let peers = vec![peer_ipv4, peer_ipv6]; - let stats = SwarmStats::new(333, 333, 444); + let peers = vec![Arc::new(peer_ipv4), Arc::new(peer_ipv6)]; + let stats = SwarmMetadata::new(333, 333, 444); AnnounceData::new(peers, stats, policy) } diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index b791defd7..b53697eed 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -98,7 +98,7 @@ mod tests { use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; use crate::core::peer::Peer; - use crate::core::torrent::SwarmStats; + use crate::core::torrent::SwarmMetadata; use crate::core::{statistics, AnnounceData, Tracker}; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; @@ -113,7 +113,7 @@ mod tests { let expected_announce_data = AnnounceData { peers: vec![], - stats: SwarmStats { + stats: SwarmMetadata { downloaded: 0, complete: 1, incomplete: 0, diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 91a371a7b..f42e11424 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -642,7 +642,7 @@ mod tests { .with_peer_addr(SocketAddr::new(IpAddr::V4(client_ip), client_port)) .into(); - assert_eq!(peers[0], expected_peer); + assert_eq!(peers[0], Arc::new(expected_peer)); } #[tokio::test] @@ -770,6 +770,7 @@ mod tests { mod from_a_loopback_ip { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; @@ -809,7 +810,7 @@ mod tests { .with_peer_addr(SocketAddr::new(external_ip_in_tracker_configuration, client_port)) .into(); - assert_eq!(peers[0], expected_peer); + assert_eq!(peers[0], Arc::new(expected_peer)); } } } @@ -863,7 +864,7 @@ mod tests { .with_peer_addr(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); - assert_eq!(peers[0], expected_peer); + assert_eq!(peers[0], Arc::new(expected_peer)); } #[tokio::test] From 4b2d6fefc2840b93cb23c9fa7a3fdd34a4ee0f9b Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 11 Feb 2024 13:30:39 +0800 Subject: [PATCH 0268/1297] dev: extract repo implementations and benchmarks --- .../src/benches/asyn.rs | 30 +- .../src/benches/mod.rs | 1 - .../src/benches/sync.rs | 29 +- .../src/benches/sync_asyn.rs | 185 --------- .../torrent-repository-benchmarks/src/main.rs | 89 +++-- src/core/mod.rs | 17 +- src/core/services/torrent.rs | 8 +- src/core/torrent/entry.rs | 74 +++- src/core/torrent/mod.rs | 41 +- src/core/torrent/repository/mod.rs | 20 +- src/core/torrent/repository/rw_lock_std.rs | 122 ++++++ .../repository/rw_lock_std_mutex_std.rs | 143 +++++++ .../repository/rw_lock_std_mutex_tokio.rs | 141 +++++++ src/core/torrent/repository/rw_lock_tokio.rs | 124 ++++++ .../repository/rw_lock_tokio_mutex_std.rs | 146 +++++++ .../repository/rw_lock_tokio_mutex_tokio.rs | 144 +++++++ src/core/torrent/repository/std_sync.rs | 365 ----------------- src/core/torrent/repository/tokio_sync.rs | 378 ------------------ 18 files changed, 1015 insertions(+), 1042 deletions(-) delete mode 100644 packages/torrent-repository-benchmarks/src/benches/sync_asyn.rs create mode 100644 src/core/torrent/repository/rw_lock_std.rs create mode 100644 src/core/torrent/repository/rw_lock_std_mutex_std.rs create mode 100644 src/core/torrent/repository/rw_lock_std_mutex_tokio.rs create mode 100644 src/core/torrent/repository/rw_lock_tokio.rs create mode 100644 src/core/torrent/repository/rw_lock_tokio_mutex_std.rs create mode 100644 src/core/torrent/repository/rw_lock_tokio_mutex_tokio.rs delete mode 100644 src/core/torrent/repository/std_sync.rs delete mode 100644 src/core/torrent/repository/tokio_sync.rs diff --git a/packages/torrent-repository-benchmarks/src/benches/asyn.rs b/packages/torrent-repository-benchmarks/src/benches/asyn.rs index 737a99f3c..dffd31682 100644 --- a/packages/torrent-repository-benchmarks/src/benches/asyn.rs +++ b/packages/torrent-repository-benchmarks/src/benches/asyn.rs @@ -1,24 +1,21 @@ -use std::sync::Arc; use std::time::Duration; use clap::Parser; use futures::stream::FuturesUnordered; -use torrust_tracker::core::torrent::repository::tokio_sync::RepositoryTokioRwLock; use torrust_tracker::core::torrent::repository::UpdateTorrentAsync; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use crate::args::Args; use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; -pub async fn add_one_torrent(samples: usize) -> (Duration, Duration) +pub async fn add_one_torrent(samples: usize) -> (Duration, Duration) where - T: Default, - RepositoryTokioRwLock: UpdateTorrentAsync + Default, + V: UpdateTorrentAsync + Default, { let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(RepositoryTokioRwLock::::default()); + let torrent_repository = V::default(); let info_hash = InfoHash([0; 20]); @@ -37,16 +34,15 @@ where } // Add one torrent ten thousand times in parallel (depending on the set worker threads) -pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - T: Default + Send + Sync + 'static, - RepositoryTokioRwLock: UpdateTorrentAsync + Default, + V: UpdateTorrentAsync + Default + Clone + Send + Sync + 'static, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(RepositoryTokioRwLock::::default()); + let torrent_repository = V::default(); let info_hash: &'static InfoHash = &InfoHash([0; 20]); let handles = FuturesUnordered::new(); @@ -87,16 +83,15 @@ where } // Add ten thousand torrents in parallel (depending on the set worker threads) -pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - T: Default + Send + Sync + 'static, - RepositoryTokioRwLock: UpdateTorrentAsync + Default, + V: UpdateTorrentAsync + Default + Clone + Send + Sync + 'static, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(RepositoryTokioRwLock::::default()); + let torrent_repository = V::default(); let info_hashes = generate_unique_info_hashes(10_000); let handles = FuturesUnordered::new(); @@ -132,16 +127,15 @@ where } // Async update ten thousand torrents in parallel (depending on the set worker threads) -pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - T: Default + Send + Sync + 'static, - RepositoryTokioRwLock: UpdateTorrentAsync + Default, + V: UpdateTorrentAsync + Default + Clone + Send + Sync + 'static, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(RepositoryTokioRwLock::::default()); + let torrent_repository = V::default(); let info_hashes = generate_unique_info_hashes(10_000); let handles = FuturesUnordered::new(); diff --git a/packages/torrent-repository-benchmarks/src/benches/mod.rs b/packages/torrent-repository-benchmarks/src/benches/mod.rs index 7450f4bcc..1026aa4bf 100644 --- a/packages/torrent-repository-benchmarks/src/benches/mod.rs +++ b/packages/torrent-repository-benchmarks/src/benches/mod.rs @@ -1,4 +1,3 @@ pub mod asyn; pub mod sync; -pub mod sync_asyn; pub mod utils; diff --git a/packages/torrent-repository-benchmarks/src/benches/sync.rs b/packages/torrent-repository-benchmarks/src/benches/sync.rs index ea694a38c..04385bc55 100644 --- a/packages/torrent-repository-benchmarks/src/benches/sync.rs +++ b/packages/torrent-repository-benchmarks/src/benches/sync.rs @@ -1,9 +1,7 @@ -use std::sync::Arc; use std::time::Duration; use clap::Parser; use futures::stream::FuturesUnordered; -use torrust_tracker::core::torrent::repository::std_sync::RepositoryStdRwLock; use torrust_tracker::core::torrent::repository::UpdateTorrentSync; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; @@ -12,14 +10,14 @@ use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjuste // Simply add one torrent #[must_use] -pub fn add_one_torrent(samples: usize) -> (Duration, Duration) +pub fn add_one_torrent(samples: usize) -> (Duration, Duration) where - RepositoryStdRwLock: UpdateTorrentSync + Default, + V: UpdateTorrentSync + Default, { let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); + let torrent_repository = V::default(); let info_hash = InfoHash([0; 20]); @@ -36,16 +34,15 @@ where } // Add one torrent ten thousand times in parallel (depending on the set worker threads) -pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - T: Send + Sync + 'static, - RepositoryStdRwLock: UpdateTorrentSync + Default, + V: UpdateTorrentSync + Default + Clone + Send + Sync + 'static, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); + let torrent_repository = V::default(); let info_hash: &'static InfoHash = &InfoHash([0; 20]); let handles = FuturesUnordered::new(); @@ -82,16 +79,15 @@ where } // Add ten thousand torrents in parallel (depending on the set worker threads) -pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - T: Send + Sync + 'static, - RepositoryStdRwLock: UpdateTorrentSync + Default, + V: UpdateTorrentSync + Default + Clone + Send + Sync + 'static, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); + let torrent_repository = V::default(); let info_hashes = generate_unique_info_hashes(10_000); let handles = FuturesUnordered::new(); @@ -125,16 +121,15 @@ where } // Update ten thousand torrents in parallel (depending on the set worker threads) -pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - T: Send + Sync + 'static, - RepositoryStdRwLock: UpdateTorrentSync + Default, + V: UpdateTorrentSync + Default + Clone + Send + Sync + 'static, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); + let torrent_repository = V::default(); let info_hashes = generate_unique_info_hashes(10_000); let handles = FuturesUnordered::new(); diff --git a/packages/torrent-repository-benchmarks/src/benches/sync_asyn.rs b/packages/torrent-repository-benchmarks/src/benches/sync_asyn.rs deleted file mode 100644 index 8efed9856..000000000 --- a/packages/torrent-repository-benchmarks/src/benches/sync_asyn.rs +++ /dev/null @@ -1,185 +0,0 @@ -use std::sync::Arc; -use std::time::Duration; - -use clap::Parser; -use futures::stream::FuturesUnordered; -use torrust_tracker::core::torrent::repository::std_sync::RepositoryStdRwLock; -use torrust_tracker::core::torrent::repository::UpdateTorrentAsync; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; - -use crate::args::Args; -use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; - -// Simply add one torrent -#[must_use] -pub async fn add_one_torrent(samples: usize) -> (Duration, Duration) -where - RepositoryStdRwLock: UpdateTorrentAsync + Default, -{ - let mut results: Vec = Vec::with_capacity(samples); - - for _ in 0..samples { - let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); - - let info_hash = InfoHash([0; 20]); - - let start_time = std::time::Instant::now(); - - torrent_repository - .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) - .await; - - let result = start_time.elapsed(); - - results.push(result); - } - - get_average_and_adjusted_average_from_results(results) -} - -// Add one torrent ten thousand times in parallel (depending on the set worker threads) -pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) -where - T: Send + Sync + 'static, - RepositoryStdRwLock: UpdateTorrentAsync + Default, -{ - let args = Args::parse(); - let mut results: Vec = Vec::with_capacity(samples); - - for _ in 0..samples { - let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); - let info_hash: &'static InfoHash = &InfoHash([0; 20]); - let handles = FuturesUnordered::new(); - - // Add the torrent/peer to the torrent repository - torrent_repository - .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) - .await; - - let start_time = std::time::Instant::now(); - - for _ in 0..10_000 { - let torrent_repository_clone = torrent_repository.clone(); - - let handle = runtime.spawn(async move { - torrent_repository_clone - .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) - .await; - - if let Some(sleep_time) = args.sleep { - let start_time = std::time::Instant::now(); - - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); - - handles.push(handle); - } - - // Await all tasks - futures::future::join_all(handles).await; - - let result = start_time.elapsed(); - - results.push(result); - } - - get_average_and_adjusted_average_from_results(results) -} - -// Add ten thousand torrents in parallel (depending on the set worker threads) -pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) -where - T: Send + Sync + 'static, - RepositoryStdRwLock: UpdateTorrentAsync + Default, -{ - let args = Args::parse(); - let mut results: Vec = Vec::with_capacity(samples); - - for _ in 0..samples { - let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); - let info_hashes = generate_unique_info_hashes(10_000); - let handles = FuturesUnordered::new(); - - let start_time = std::time::Instant::now(); - - for info_hash in info_hashes { - let torrent_repository_clone = torrent_repository.clone(); - - let handle = runtime.spawn(async move { - torrent_repository_clone - .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) - .await; - - if let Some(sleep_time) = args.sleep { - let start_time = std::time::Instant::now(); - - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); - - handles.push(handle); - } - - // Await all tasks - futures::future::join_all(handles).await; - - let result = start_time.elapsed(); - - results.push(result); - } - - get_average_and_adjusted_average_from_results(results) -} - -// Update ten thousand torrents in parallel (depending on the set worker threads) -pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) -where - T: Send + Sync + 'static, - RepositoryStdRwLock: UpdateTorrentAsync + Default, -{ - let args = Args::parse(); - let mut results: Vec = Vec::with_capacity(samples); - - for _ in 0..samples { - let torrent_repository = Arc::new(RepositoryStdRwLock::::default()); - let info_hashes = generate_unique_info_hashes(10_000); - let handles = FuturesUnordered::new(); - - // Add the torrents/peers to the torrent repository - for info_hash in &info_hashes { - torrent_repository - .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) - .await; - } - - let start_time = std::time::Instant::now(); - - for info_hash in info_hashes { - let torrent_repository_clone = torrent_repository.clone(); - - let handle = runtime.spawn(async move { - torrent_repository_clone - .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) - .await; - - if let Some(sleep_time) = args.sleep { - let start_time = std::time::Instant::now(); - - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); - - handles.push(handle); - } - - // Await all tasks - futures::future::join_all(handles).await; - - let result = start_time.elapsed(); - - results.push(result); - } - - get_average_and_adjusted_average_from_results(results) -} diff --git a/packages/torrent-repository-benchmarks/src/main.rs b/packages/torrent-repository-benchmarks/src/main.rs index d7291afe2..b935cea43 100644 --- a/packages/torrent-repository-benchmarks/src/main.rs +++ b/packages/torrent-repository-benchmarks/src/main.rs @@ -1,7 +1,12 @@ +use std::sync::Arc; + use clap::Parser; use torrust_torrent_repository_benchmarks::args::Args; -use torrust_torrent_repository_benchmarks::benches::{asyn, sync, sync_asyn}; -use torrust_tracker::core::torrent::entry::{Entry, MutexStd, MutexTokio}; +use torrust_torrent_repository_benchmarks::benches::{asyn, sync}; +use torrust_tracker::core::torrent::{ + TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, + TorrentsRwLockTokioMutexTokio, +}; #[allow(clippy::too_many_lines)] #[allow(clippy::print_literal)] @@ -15,147 +20,167 @@ fn main() { .build() .unwrap(); - println!("tokio::sync::RwLock>"); + println!("TorrentsRwLockTokio"); println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(asyn::add_one_torrent::(1_000_000)) + rt.block_on(asyn::add_one_torrent::>(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_one_torrent_in_parallel::>(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::add_multiple_torrents_in_parallel::>(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_multiple_torrents_in_parallel::>( + &rt, 10 + )) ); if let Some(true) = args.compare { println!(); - println!("std::sync::RwLock>"); + println!("TorrentsRwLockStd"); println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - sync::add_one_torrent::(1_000_000) + sync::add_one_torrent::>(1_000_000) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(sync::update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(sync::update_one_torrent_in_parallel::>(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(sync::add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(sync::add_multiple_torrents_in_parallel::>(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(sync::update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(sync::update_multiple_torrents_in_parallel::>(&rt, 10)) ); println!(); - println!("std::sync::RwLock>>>"); + println!("TorrentsRwLockStdMutexStd"); println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - sync::add_one_torrent::(1_000_000) + sync::add_one_torrent::>(1_000_000) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(sync::update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(sync::update_one_torrent_in_parallel::>( + &rt, 10 + )) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(sync::add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(sync::add_multiple_torrents_in_parallel::>( + &rt, 10 + )) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(sync::update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(sync::update_multiple_torrents_in_parallel::>( + &rt, 10 + )) ); println!(); - println!("std::sync::RwLock>>>"); + println!("TorrentsRwLockStdMutexTokio"); println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(sync_asyn::add_one_torrent::(1_000_000)) + rt.block_on(asyn::add_one_torrent::>(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(sync_asyn::update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_one_torrent_in_parallel::>( + &rt, 10 + )) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(sync_asyn::add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::add_multiple_torrents_in_parallel::>( + &rt, 10 + )) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(sync_asyn::update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_multiple_torrents_in_parallel::>(&rt, 10)) ); println!(); - println!("tokio::sync::RwLock>>>"); + println!("TorrentsRwLockTokioMutexStd"); println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(asyn::add_one_torrent::(1_000_000)) + rt.block_on(asyn::add_one_torrent::>(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_one_torrent_in_parallel::>( + &rt, 10 + )) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::add_multiple_torrents_in_parallel::>( + &rt, 10 + )) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_multiple_torrents_in_parallel::>(&rt, 10)) ); println!(); - println!("tokio::sync::RwLock>>>"); + println!("TorrentsRwLockTokioMutexTokio"); println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(asyn::add_one_torrent::(1_000_000)) + rt.block_on(asyn::add_one_torrent::>(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_one_torrent_in_parallel::>( + &rt, 10 + )) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::add_multiple_torrents_in_parallel::>( + &rt, 10 + )) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) + rt.block_on(asyn::update_multiple_torrents_in_parallel::>(&rt, 10)) ); } } diff --git a/src/core/mod.rs b/src/core/mod.rs index b070f90db..15d7b9c39 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -449,9 +449,9 @@ use torrust_tracker_primitives::TrackerMode; use self::auth::Key; use self::error::Error; use self::peer::Peer; -use self::torrent::entry::{Entry, ReadInfo, ReadPeers}; -use self::torrent::repository::tokio_sync::RepositoryTokioRwLock; -use self::torrent::repository::{Repository, UpdateTorrentAsync}; +use self::torrent::entry::{ReadInfo, ReadPeers}; +use self::torrent::repository::{Repository, UpdateTorrentSync}; +use self::torrent::Torrents; use crate::core::databases::Database; use crate::core::torrent::SwarmMetadata; use crate::shared::bit_torrent::info_hash::InfoHash; @@ -477,7 +477,7 @@ pub struct Tracker { policy: TrackerPolicy, keys: tokio::sync::RwLock>, whitelist: tokio::sync::RwLock>, - pub torrents: Arc>, + pub torrents: Arc, stats_event_sender: Option>, stats_repository: statistics::Repo, external_ip: Option, @@ -575,7 +575,7 @@ impl Tracker { mode, keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), - torrents: Arc::new(RepositoryTokioRwLock::::default()), + torrents: Arc::default(), stats_event_sender, stats_repository, database, @@ -732,7 +732,7 @@ impl Tracker { // code-review: consider splitting the function in two (command and query segregation). // `update_torrent_with_peer` and `get_stats` - let (stats_updated, stats) = self.torrents.update_torrent_with_peer_and_get_stats(info_hash, peer).await; + let (stats_updated, stats) = self.torrents.update_torrent_with_peer_and_get_stats(info_hash, peer); if self.policy.persistent_torrent_completed_stat && stats_updated { let completed = stats.downloaded; @@ -1680,6 +1680,7 @@ mod tests { use aquatic_udp_protocol::AnnounceEvent; use crate::core::tests::the_tracker::{sample_info_hash, sample_peer, tracker_persisting_torrents_in_database}; + use crate::core::torrent::entry::ReadInfo; use crate::core::torrent::repository::Repository; #[tokio::test] @@ -1710,10 +1711,10 @@ mod tests { .expect("it should be able to get entry"); // It persists the number of completed peers. - assert_eq!(torrent_entry.completed, 1); + assert_eq!(torrent_entry.get_stats().downloaded, 1); // It does not persist the peers - assert!(torrent_entry.peers.is_empty()); + assert!(torrent_entry.peers_is_empty()); } } } diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index b265066f0..78dab12c4 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use serde::Deserialize; use crate::core::peer::Peer; -use crate::core::torrent::entry::{self, ReadInfo}; +use crate::core::torrent::entry::{ReadInfo, ReadPeers}; use crate::core::torrent::repository::Repository; use crate::core::Tracker; use crate::shared::bit_torrent::info_hash::InfoHash; @@ -99,9 +99,9 @@ pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Op let torrent_entry = torrent_entry_option?; - let stats = entry::ReadInfo::get_stats(&torrent_entry); + let stats = torrent_entry.get_stats(); - let peers = entry::ReadPeers::get_peers(&torrent_entry, None); + let peers = torrent_entry.get_peers(None); let peers = Some(peers.iter().map(|peer| (**peer)).collect()); @@ -119,7 +119,7 @@ pub async fn get_torrents_page(tracker: Arc, pagination: Option<&Pagina let mut basic_infos: Vec = vec![]; for (info_hash, torrent_entry) in tracker.torrents.get_paginated(pagination).await { - let stats = entry::ReadInfo::get_stats(&torrent_entry); + let stats = torrent_entry.get_stats(); basic_infos.push(BasicInfo { info_hash, diff --git a/src/core/torrent/entry.rs b/src/core/torrent/entry.rs index 619cce9b3..815abd4fb 100644 --- a/src/core/torrent/entry.rs +++ b/src/core/torrent/entry.rs @@ -19,11 +19,11 @@ use crate::shared::clock::{Current, TimeNow}; pub struct Entry { /// The swarm: a network of peers that are all trying to download the torrent associated to this entry #[serde(skip)] - pub peers: std::collections::BTreeMap>, + pub(crate) peers: std::collections::BTreeMap>, /// The number of peers that have ever completed downloading the torrent associated to this entry - pub completed: u32, + pub(crate) completed: u32, } - +pub type Single = Entry; pub type MutexStd = Arc>; pub type MutexTokio = Arc>; @@ -35,6 +35,23 @@ pub trait ReadInfo { /// Returns True if Still a Valid Entry according to the Tracker Policy fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool; + + /// Returns True if the Peers is Empty + fn peers_is_empty(&self) -> bool; +} + +/// Same as [`ReadInfo`], but async. +pub trait ReadInfoAsync { + /// It returns the swarm metadata (statistics) as a struct: + /// + /// `(seeders, completed, leechers)` + fn get_stats(&self) -> impl std::future::Future + Send; + + /// Returns True if Still a Valid Entry according to the Tracker Policy + fn is_not_zombie(&self, policy: &TrackerPolicy) -> impl std::future::Future + Send; + + /// Returns True if the Peers is Empty + fn peers_is_empty(&self) -> impl std::future::Future + Send; } pub trait ReadPeers { @@ -49,15 +66,10 @@ pub trait ReadPeers { fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec>; } -pub trait ReadAsync { - /// Get all swarm peers, optionally limiting the result. +/// Same as [`ReadPeers`], but async. +pub trait ReadPeersAsync { fn get_peers(&self, limit: Option) -> impl std::future::Future>> + Send; - /// It returns the list of peers for a given peer client, optionally limiting the - /// result. - /// - /// It filters out the input peer, typically because we want to return this - /// list of peers to that client peer. fn get_peers_for_peer( &self, client: &peer::Peer, @@ -79,12 +91,14 @@ pub trait Update { fn remove_inactive_peers(&mut self, max_peer_timeout: u32); } +/// Same as [`Update`], except not `mut`. pub trait UpdateSync { fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool; fn insert_or_update_peer_and_get_stats(&self, peer: &peer::Peer) -> (bool, SwarmMetadata); fn remove_inactive_peers(&self, max_peer_timeout: u32); } +/// Same as [`Update`], except not `mut` and async. pub trait UpdateAsync { fn insert_or_update_peer(&self, peer: &peer::Peer) -> impl std::future::Future + Send; @@ -96,7 +110,7 @@ pub trait UpdateAsync { fn remove_inactive_peers(&self, max_peer_timeout: u32) -> impl std::future::Future + Send; } -impl ReadInfo for Entry { +impl ReadInfo for Single { #[allow(clippy::cast_possible_truncation)] fn get_stats(&self) -> SwarmMetadata { let complete: u32 = self.peers.values().filter(|peer| peer.is_seeder()).count() as u32; @@ -120,9 +134,41 @@ impl ReadInfo for Entry { true } + + fn peers_is_empty(&self) -> bool { + self.peers.is_empty() + } +} + +impl ReadInfo for MutexStd { + fn get_stats(&self) -> SwarmMetadata { + self.lock().expect("it should get a lock").get_stats() + } + + fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool { + self.lock().expect("it should get a lock").is_not_zombie(policy) + } + + fn peers_is_empty(&self) -> bool { + self.lock().expect("it should get a lock").peers_is_empty() + } +} + +impl ReadInfoAsync for MutexTokio { + async fn get_stats(&self) -> SwarmMetadata { + self.lock().await.get_stats() + } + + async fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool { + self.lock().await.is_not_zombie(policy) + } + + async fn peers_is_empty(&self) -> bool { + self.lock().await.peers_is_empty() + } } -impl ReadPeers for Entry { +impl ReadPeers for Single { fn get_peers(&self, limit: Option) -> Vec> { match limit { Some(limit) => self.peers.values().take(limit).cloned().collect(), @@ -162,7 +208,7 @@ impl ReadPeers for MutexStd { } } -impl ReadAsync for MutexTokio { +impl ReadPeersAsync for MutexTokio { async fn get_peers(&self, limit: Option) -> Vec> { self.lock().await.get_peers(limit) } @@ -172,7 +218,7 @@ impl ReadAsync for MutexTokio { } } -impl Update for Entry { +impl Update for Single { fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool { let mut did_torrent_stats_change: bool = false; diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index 608765cf8..bfe068337 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -11,8 +11,6 @@ //! That's the most valuable information the peer want to get from the tracker, because it allows them to //! start downloading torrent from those peers. //! -//! > **NOTICE**: that both swarm data (torrent entries) and swarm metadata (aggregate counters) are related to only one torrent. -//! //! The "swarm metadata" contains aggregate data derived from the torrent entries. There two types of data: //! //! - For **active peers**: metrics related to the current active peers in the swarm. @@ -33,6 +31,15 @@ pub mod repository; use derive_more::Constructor; +pub type Torrents = TorrentsRwLockStdMutexStd; // Currently Used + +pub type TorrentsRwLockStd = repository::RwLockStd; +pub type TorrentsRwLockStdMutexStd = repository::RwLockStd; +pub type TorrentsRwLockStdMutexTokio = repository::RwLockStd; +pub type TorrentsRwLockTokio = repository::RwLockTokio; +pub type TorrentsRwLockTokioMutexStd = repository::RwLockTokio; +pub type TorrentsRwLockTokioMutexTokio = repository::RwLockTokio; + /// Swarm statistics for one torrent. /// Swarm metadata dictionary in the scrape response. /// @@ -138,14 +145,14 @@ mod tests { #[test] fn the_default_torrent_entry_should_contain_an_empty_list_of_peers() { - let torrent_entry = entry::Entry::default(); + let torrent_entry = entry::Single::default(); assert_eq!(torrent_entry.get_peers(None).len(), 0); } #[test] fn a_new_peer_can_be_added_to_a_torrent_entry() { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -156,7 +163,7 @@ mod tests { #[test] fn a_torrent_entry_should_contain_the_list_of_peers_that_were_added_to_the_torrent() { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -166,7 +173,7 @@ mod tests { #[test] fn a_peer_can_be_updated_in_a_torrent_entry() { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let mut torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -178,7 +185,7 @@ mod tests { #[test] fn a_peer_should_be_removed_from_a_torrent_entry_when_the_peer_announces_it_has_stopped() { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let mut torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -190,7 +197,7 @@ mod tests { #[test] fn torrent_stats_change_when_a_previously_known_peer_announces_it_has_completed_the_torrent() { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let mut torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -204,7 +211,7 @@ mod tests { #[test] fn torrent_stats_should_not_change_when_a_peer_announces_it_has_completed_the_torrent_if_it_is_the_first_announce_from_the_peer( ) { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); // Add a peer that did not exist before in the entry @@ -216,7 +223,7 @@ mod tests { #[test] fn a_torrent_entry_should_return_the_list_of_peers_for_a_given_peer_filtering_out_the_client_that_is_making_the_request() { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let peer_socket_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); let torrent_peer = TorrentPeerBuilder::default().with_peer_address(peer_socket_address).into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add peer @@ -229,7 +236,7 @@ mod tests { #[test] fn two_peers_with_the_same_ip_but_different_port_should_be_considered_different_peers() { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let peer_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); @@ -263,7 +270,7 @@ mod tests { #[test] fn the_tracker_should_limit_the_list_of_peers_to_74_when_clients_scrape_torrents() { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); // We add one more peer than the scrape limit for peer_number in 1..=74 + 1 { @@ -280,7 +287,7 @@ mod tests { #[test] fn torrent_stats_should_have_the_number_of_seeders_for_a_torrent() { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let torrent_seeder = a_torrent_seeder(); torrent_entry.insert_or_update_peer(&torrent_seeder); // Add seeder @@ -290,7 +297,7 @@ mod tests { #[test] fn torrent_stats_should_have_the_number_of_leechers_for_a_torrent() { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let torrent_leecher = a_torrent_leecher(); torrent_entry.insert_or_update_peer(&torrent_leecher); // Add leecher @@ -301,7 +308,7 @@ mod tests { #[test] fn torrent_stats_should_have_the_number_of_peers_that_having_announced_at_least_two_events_the_latest_one_is_the_completed_event( ) { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let mut torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -316,7 +323,7 @@ mod tests { #[test] fn torrent_stats_should_not_include_a_peer_in_the_completed_counter_if_the_peer_has_announced_only_one_event() { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); // Announce "Completed" torrent download event. @@ -330,7 +337,7 @@ mod tests { #[test] fn a_torrent_entry_should_remove_a_peer_not_updated_after_a_timeout_in_seconds() { - let mut torrent_entry = entry::Entry::default(); + let mut torrent_entry = entry::Single::default(); let timeout = 120u32; diff --git a/src/core/torrent/repository/mod.rs b/src/core/torrent/repository/mod.rs index 3af33aebe..1c4ce8ae9 100644 --- a/src/core/torrent/repository/mod.rs +++ b/src/core/torrent/repository/mod.rs @@ -4,10 +4,14 @@ use crate::core::services::torrent::Pagination; use crate::core::{peer, TorrentsMetrics, TrackerPolicy}; use crate::shared::bit_torrent::info_hash::InfoHash; -pub mod std_sync; -pub mod tokio_sync; +pub mod rw_lock_std; +pub mod rw_lock_std_mutex_std; +pub mod rw_lock_std_mutex_tokio; +pub mod rw_lock_tokio; +pub mod rw_lock_tokio_mutex_std; +pub mod rw_lock_tokio_mutex_tokio; -pub trait Repository: Default { +pub trait Repository: Default + 'static { fn get(&self, key: &InfoHash) -> impl std::future::Future> + Send; fn get_metrics(&self) -> impl std::future::Future + Send; fn get_paginated(&self, pagination: Option<&Pagination>) -> impl std::future::Future> + Send; @@ -28,3 +32,13 @@ pub trait UpdateTorrentAsync { peer: &peer::Peer, ) -> impl std::future::Future + Send; } + +#[derive(Default)] +pub struct RwLockTokio { + torrents: tokio::sync::RwLock>, +} + +#[derive(Default)] +pub struct RwLockStd { + torrents: std::sync::RwLock>, +} diff --git a/src/core/torrent/repository/rw_lock_std.rs b/src/core/torrent/repository/rw_lock_std.rs new file mode 100644 index 000000000..9b3915bcb --- /dev/null +++ b/src/core/torrent/repository/rw_lock_std.rs @@ -0,0 +1,122 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use futures::future::join_all; + +use super::{Repository, UpdateTorrentSync}; +use crate::core::databases::PersistentTorrents; +use crate::core::services::torrent::Pagination; +use crate::core::torrent::entry::{self, ReadInfo, Update}; +use crate::core::torrent::{SwarmMetadata, TorrentsRwLockStd}; +use crate::core::{peer, TorrentsMetrics}; +use crate::shared::bit_torrent::info_hash::InfoHash; + +impl TorrentsRwLockStd { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("it should get the read lock") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("it should get the write lock") + } +} + +impl UpdateTorrentSync for TorrentsRwLockStd { + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let mut db = self.get_torrents_mut(); + + let entry = db.entry(*info_hash).or_insert(entry::Single::default()); + + entry.insert_or_update_peer_and_get_stats(peer) + } +} + +impl UpdateTorrentSync for Arc { + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + self.as_ref().update_torrent_with_peer_and_get_stats(info_hash, peer) + } +} + +impl Repository for TorrentsRwLockStd { + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let metrics: Arc> = Arc::default(); + + let mut handles = Vec::>::default(); + + for e in self.get_torrents().values() { + let entry = e.clone(); + let metrics = metrics.clone(); + handles.push(tokio::task::spawn(async move { + let stats = entry.get_stats(); + metrics.lock().await.seeders += u64::from(stats.complete); + metrics.lock().await.completed += u64::from(stats.downloaded); + metrics.lock().await.leechers += u64::from(stats.incomplete); + metrics.lock().await.torrents += 1; + })); + } + + join_all(handles).await; + + *metrics.lock_owned().await + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::Single)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = entry::Single { + peers: BTreeMap::default(), + completed: *completed, + }; + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + let mut db = self.get_torrents_mut(); + + drop(db.values_mut().map(|e| e.remove_inactive_peers(max_peer_timeout))); + } + + async fn remove_peerless_torrents(&self, policy: &crate::core::TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.is_not_zombie(policy)); + } +} diff --git a/src/core/torrent/repository/rw_lock_std_mutex_std.rs b/src/core/torrent/repository/rw_lock_std_mutex_std.rs new file mode 100644 index 000000000..5a9a38f77 --- /dev/null +++ b/src/core/torrent/repository/rw_lock_std_mutex_std.rs @@ -0,0 +1,143 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use futures::future::join_all; + +use super::{Repository, UpdateTorrentSync}; +use crate::core::databases::PersistentTorrents; +use crate::core::services::torrent::Pagination; +use crate::core::torrent::entry::{ReadInfo, Update, UpdateSync}; +use crate::core::torrent::{entry, SwarmMetadata, TorrentsRwLockStdMutexStd}; +use crate::core::{peer, TorrentsMetrics}; +use crate::shared::bit_torrent::info_hash::InfoHash; + +impl TorrentsRwLockStdMutexStd { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl UpdateTorrentSync for TorrentsRwLockStdMutexStd { + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let maybe_entry = self.get_torrents().get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut(); + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.insert_or_update_peer_and_get_stats(peer) + } +} + +impl UpdateTorrentSync for Arc { + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + self.as_ref().update_torrent_with_peer_and_get_stats(info_hash, peer) + } +} + +impl Repository for TorrentsRwLockStdMutexStd { + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let metrics: Arc> = Arc::default(); + + // todo:: replace with a ring buffer + let mut handles = Vec::>::default(); + + for e in self.get_torrents().values() { + let entry = e.clone(); + let metrics = metrics.clone(); + handles.push(tokio::task::spawn(async move { + let stats = entry.lock().expect("it should get the lock").get_stats(); + metrics.lock().await.seeders += u64::from(stats.complete); + metrics.lock().await.completed += u64::from(stats.downloaded); + metrics.lock().await.leechers += u64::from(stats.incomplete); + metrics.lock().await.torrents += 1; + })); + } + + join_all(handles).await; + + *metrics.lock_owned().await + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexStd)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = entry::MutexStd::new( + entry::Single { + peers: BTreeMap::default(), + completed: *completed, + } + .into(), + ); + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + // todo:: replace with a ring buffer + let mut handles = Vec::>::default(); + + for e in self.get_torrents().values() { + let entry = e.clone(); + handles.push(tokio::task::spawn(async move { + entry + .lock() + .expect("it should get lock for entry") + .remove_inactive_peers(max_peer_timeout); + })); + } + + join_all(handles).await; + } + + async fn remove_peerless_torrents(&self, policy: &crate::core::TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.lock().expect("it should lock entry").is_not_zombie(policy)); + } +} diff --git a/src/core/torrent/repository/rw_lock_std_mutex_tokio.rs b/src/core/torrent/repository/rw_lock_std_mutex_tokio.rs new file mode 100644 index 000000000..1feb41e3e --- /dev/null +++ b/src/core/torrent/repository/rw_lock_std_mutex_tokio.rs @@ -0,0 +1,141 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use futures::future::join_all; + +use super::{Repository, UpdateTorrentAsync}; +use crate::core::databases::PersistentTorrents; +use crate::core::services::torrent::Pagination; +use crate::core::torrent::entry::{ReadInfo, Update, UpdateAsync}; +use crate::core::torrent::{entry, SwarmMetadata, TorrentsRwLockStdMutexTokio}; +use crate::core::{peer, TorrentsMetrics}; +use crate::shared::bit_torrent::info_hash::InfoHash; + +impl TorrentsRwLockStdMutexTokio { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl UpdateTorrentAsync for TorrentsRwLockStdMutexTokio { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let maybe_entry = self.get_torrents().get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut(); + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.insert_or_update_peer_and_get_stats(peer).await + } +} + +impl UpdateTorrentAsync for Arc { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + self.as_ref().update_torrent_with_peer_and_get_stats(info_hash, peer).await + } +} + +impl Repository for TorrentsRwLockStdMutexTokio { + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexTokio)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let metrics: Arc> = Arc::default(); + + // todo:: replace with a ring buffer + let mut handles = Vec::>::default(); + + for e in self.get_torrents().values() { + let entry = e.clone(); + let metrics = metrics.clone(); + handles.push(tokio::task::spawn(async move { + let stats = entry.lock().await.get_stats(); + metrics.lock().await.seeders += u64::from(stats.complete); + metrics.lock().await.completed += u64::from(stats.downloaded); + metrics.lock().await.leechers += u64::from(stats.incomplete); + metrics.lock().await.torrents += 1; + })); + } + + join_all(handles).await; + + *metrics.lock_owned().await + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut db = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if db.contains_key(info_hash) { + continue; + } + + let entry = entry::MutexTokio::new( + entry::Single { + peers: BTreeMap::default(), + completed: *completed, + } + .into(), + ); + + db.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + // todo:: replace with a ring buffer + + let mut handles = Vec::>::default(); + + for e in self.get_torrents().values() { + let entry = e.clone(); + handles.push(tokio::task::spawn(async move { + entry.lock().await.remove_inactive_peers(max_peer_timeout); + })); + } + + join_all(handles).await; + } + + async fn remove_peerless_torrents(&self, policy: &crate::core::TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.blocking_lock().is_not_zombie(policy)); + } +} diff --git a/src/core/torrent/repository/rw_lock_tokio.rs b/src/core/torrent/repository/rw_lock_tokio.rs new file mode 100644 index 000000000..3d633a837 --- /dev/null +++ b/src/core/torrent/repository/rw_lock_tokio.rs @@ -0,0 +1,124 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use futures::future::join_all; + +use super::{Repository, UpdateTorrentAsync}; +use crate::core::databases::PersistentTorrents; +use crate::core::services::torrent::Pagination; +use crate::core::torrent::entry::{self, ReadInfo, Update}; +use crate::core::torrent::{SwarmMetadata, TorrentsRwLockTokio}; +use crate::core::{peer, TorrentsMetrics, TrackerPolicy}; +use crate::shared::bit_torrent::info_hash::InfoHash; + +impl TorrentsRwLockTokio { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl UpdateTorrentAsync for TorrentsRwLockTokio { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let mut db = self.get_torrents_mut().await; + + let entry = db.entry(*info_hash).or_insert(entry::Single::default()); + + entry.insert_or_update_peer_and_get_stats(peer) + } +} + +impl UpdateTorrentAsync for Arc { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + self.as_ref().update_torrent_with_peer_and_get_stats(info_hash, peer).await + } +} + +impl Repository for TorrentsRwLockTokio { + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::Single)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let metrics: Arc> = Arc::default(); + + let mut handles = Vec::>::default(); + + for e in self.get_torrents().await.values() { + let entry = e.clone(); + let metrics = metrics.clone(); + handles.push(tokio::task::spawn(async move { + let stats = entry.get_stats(); + metrics.lock().await.seeders += u64::from(stats.complete); + metrics.lock().await.completed += u64::from(stats.downloaded); + metrics.lock().await.leechers += u64::from(stats.incomplete); + metrics.lock().await.torrents += 1; + })); + } + + join_all(handles).await; + + *metrics.lock_owned().await + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = entry::Single { + peers: BTreeMap::default(), + completed: *completed, + }; + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + let mut db = self.get_torrents_mut().await; + + drop(db.values_mut().map(|e| e.remove_inactive_peers(max_peer_timeout))); + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.is_not_zombie(policy)); + } +} diff --git a/src/core/torrent/repository/rw_lock_tokio_mutex_std.rs b/src/core/torrent/repository/rw_lock_tokio_mutex_std.rs new file mode 100644 index 000000000..3888c40b0 --- /dev/null +++ b/src/core/torrent/repository/rw_lock_tokio_mutex_std.rs @@ -0,0 +1,146 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use futures::future::join_all; + +use super::{Repository, UpdateTorrentAsync}; +use crate::core::databases::PersistentTorrents; +use crate::core::services::torrent::Pagination; +use crate::core::torrent::entry::{ReadInfo, Update, UpdateSync}; +use crate::core::torrent::{entry, SwarmMetadata, TorrentsRwLockTokioMutexStd}; +use crate::core::{peer, TorrentsMetrics, TrackerPolicy}; +use crate::shared::bit_torrent::info_hash::InfoHash; + +impl TorrentsRwLockTokioMutexStd { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl UpdateTorrentAsync for TorrentsRwLockTokioMutexStd { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut().await; + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.insert_or_update_peer_and_get_stats(peer) + } +} + +impl UpdateTorrentAsync for Arc { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + self.as_ref().update_torrent_with_peer_and_get_stats(info_hash, peer).await + } +} + +impl Repository for TorrentsRwLockTokioMutexStd { + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexStd)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let metrics: Arc> = Arc::default(); + + // todo:: replace with a ring buffer + + let mut handles = Vec::>::default(); + + for e in self.get_torrents().await.values() { + let entry = e.clone(); + let metrics = metrics.clone(); + handles.push(tokio::task::spawn(async move { + let stats = entry.lock().expect("it should get a lock").get_stats(); + metrics.lock().await.seeders += u64::from(stats.complete); + metrics.lock().await.completed += u64::from(stats.downloaded); + metrics.lock().await.leechers += u64::from(stats.incomplete); + metrics.lock().await.torrents += 1; + })); + } + + join_all(handles).await; + + *metrics.lock_owned().await + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = entry::MutexStd::new( + entry::Single { + peers: BTreeMap::default(), + completed: *completed, + } + .into(), + ); + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + // todo:: replace with a ring buffer + let mut handles = Vec::>::default(); + + for e in self.get_torrents().await.values() { + let entry = e.clone(); + handles.push(tokio::task::spawn(async move { + entry + .lock() + .expect("it should get lock for entry") + .remove_inactive_peers(max_peer_timeout); + })); + } + + join_all(handles).await; + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.lock().expect("it should lock entry").is_not_zombie(policy)); + } +} diff --git a/src/core/torrent/repository/rw_lock_tokio_mutex_tokio.rs b/src/core/torrent/repository/rw_lock_tokio_mutex_tokio.rs new file mode 100644 index 000000000..49e08d90c --- /dev/null +++ b/src/core/torrent/repository/rw_lock_tokio_mutex_tokio.rs @@ -0,0 +1,144 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use futures::future::join_all; + +use super::{Repository, UpdateTorrentAsync}; +use crate::core::databases::PersistentTorrents; +use crate::core::services::torrent::Pagination; +use crate::core::torrent::entry::{self, ReadInfo, Update, UpdateAsync}; +use crate::core::torrent::{SwarmMetadata, TorrentsRwLockTokioMutexTokio}; +use crate::core::{peer, TorrentsMetrics, TrackerPolicy}; +use crate::shared::bit_torrent::info_hash::InfoHash; + +impl TorrentsRwLockTokioMutexTokio { + async fn get_torrents<'a>( + &'a self, + ) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl UpdateTorrentAsync for TorrentsRwLockTokioMutexTokio { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut().await; + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.insert_or_update_peer_and_get_stats(peer).await + } +} + +impl UpdateTorrentAsync for Arc { + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + self.as_ref().update_torrent_with_peer_and_get_stats(info_hash, peer).await + } +} + +impl Repository for TorrentsRwLockTokioMutexTokio { + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexTokio)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let metrics: Arc> = Arc::default(); + + // todo:: replace with a ring buffer + let mut handles = Vec::>::default(); + + for e in self.get_torrents().await.values() { + let entry = e.clone(); + let metrics = metrics.clone(); + handles.push(tokio::task::spawn(async move { + let stats = entry.lock().await.get_stats(); + metrics.lock().await.seeders += u64::from(stats.complete); + metrics.lock().await.completed += u64::from(stats.downloaded); + metrics.lock().await.leechers += u64::from(stats.incomplete); + metrics.lock().await.torrents += 1; + })); + } + + join_all(handles).await; + + *metrics.lock_owned().await + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut db = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if db.contains_key(info_hash) { + continue; + } + + let entry = entry::MutexTokio::new( + entry::Single { + peers: BTreeMap::default(), + completed: *completed, + } + .into(), + ); + + db.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, max_peer_timeout: u32) { + // todo:: replace with a ring buffer + let mut handles = Vec::>::default(); + + for e in self.get_torrents().await.values() { + let entry = e.clone(); + handles.push(tokio::task::spawn(async move { + entry.lock().await.remove_inactive_peers(max_peer_timeout); + })); + } + + join_all(handles).await; + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.blocking_lock().is_not_zombie(policy)); + } +} diff --git a/src/core/torrent/repository/std_sync.rs b/src/core/torrent/repository/std_sync.rs deleted file mode 100644 index ba38db6ed..000000000 --- a/src/core/torrent/repository/std_sync.rs +++ /dev/null @@ -1,365 +0,0 @@ -use std::collections::BTreeMap; -use std::sync::Arc; - -use futures::executor::block_on; -use futures::future::join_all; - -use super::{Repository, UpdateTorrentAsync, UpdateTorrentSync}; -use crate::core::databases::PersistentTorrents; -use crate::core::services::torrent::Pagination; -use crate::core::torrent::entry::{Entry, ReadInfo, Update, UpdateAsync, UpdateSync}; -use crate::core::torrent::{entry, SwarmMetadata}; -use crate::core::{peer, TorrentsMetrics}; -use crate::shared::bit_torrent::info_hash::InfoHash; - -#[derive(Default)] -pub struct RepositoryStdRwLock { - torrents: std::sync::RwLock>, -} - -impl RepositoryStdRwLock { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().expect("unable to get torrent list") - } - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().expect("unable to get writable torrent list") - } -} - -impl UpdateTorrentAsync for RepositoryStdRwLock { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let maybe_existing_torrent_entry = self.get_torrents().get(info_hash).cloned(); - - let torrent_entry = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { - existing_torrent_entry - } else { - let mut torrents_lock = self.get_torrents_mut(); - let entry = torrents_lock.entry(*info_hash).or_insert(Arc::default()); - entry.clone() - }; - - torrent_entry.insert_or_update_peer_and_get_stats(peer).await - } -} -impl Repository for RepositoryStdRwLock { - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents(); - db.get(key).cloned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexTokio)> { - let db = self.get_torrents(); - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn get_metrics(&self) -> TorrentsMetrics { - let db = self.get_torrents(); - let metrics: Arc> = Arc::default(); - - let futures = db.values().map(|e| { - let metrics = metrics.clone(); - let entry = e.clone(); - - tokio::spawn(async move { - let stats = entry.lock().await.get_stats(); - metrics.lock().await.seeders += u64::from(stats.complete); - metrics.lock().await.completed += u64::from(stats.downloaded); - metrics.lock().await.leechers += u64::from(stats.incomplete); - metrics.lock().await.torrents += 1; - }) - }); - - block_on(join_all(futures)); - - *metrics.blocking_lock_owned() - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut db = self.get_torrents_mut(); - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if db.contains_key(info_hash) { - continue; - } - - let entry = entry::MutexTokio::new( - Entry { - peers: BTreeMap::default(), - completed: *completed, - } - .into(), - ); - - db.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut(); - db.remove(key) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - let db = self.get_torrents(); - - let futures = db.values().map(|e| { - let entry = e.clone(); - tokio::spawn(async move { entry.lock().await.remove_inactive_peers(max_peer_timeout) }) - }); - - block_on(join_all(futures)); - } - - async fn remove_peerless_torrents(&self, policy: &crate::core::TrackerPolicy) { - let mut db = self.get_torrents_mut(); - - db.retain(|_, e| e.blocking_lock().is_not_zombie(policy)); - } -} - -impl RepositoryStdRwLock { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().expect("unable to get torrent list") - } - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().expect("unable to get writable torrent list") - } -} - -impl UpdateTorrentSync for RepositoryStdRwLock { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let maybe_existing_torrent_entry = self.get_torrents().get(info_hash).cloned(); - - let torrent_entry: Arc> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry { - existing_torrent_entry - } else { - let mut torrents_lock = self.get_torrents_mut(); - let entry = torrents_lock - .entry(*info_hash) - .or_insert(Arc::new(std::sync::Mutex::new(Entry::default()))); - entry.clone() - }; - - torrent_entry.insert_or_update_peer_and_get_stats(peer) - } -} -impl Repository for RepositoryStdRwLock { - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents(); - db.get(key).cloned() - } - - async fn get_metrics(&self) -> TorrentsMetrics { - let db = self.get_torrents(); - let metrics: Arc> = Arc::default(); - - let futures = db.values().map(|e| { - let metrics = metrics.clone(); - let entry = e.clone(); - - tokio::spawn(async move { - let stats = entry.lock().expect("it should lock the entry").get_stats(); - metrics.lock().await.seeders += u64::from(stats.complete); - metrics.lock().await.completed += u64::from(stats.downloaded); - metrics.lock().await.leechers += u64::from(stats.incomplete); - metrics.lock().await.torrents += 1; - }) - }); - - block_on(join_all(futures)); - - *metrics.blocking_lock_owned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexStd)> { - let db = self.get_torrents(); - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut torrents = self.get_torrents_mut(); - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(info_hash) { - continue; - } - - let entry = entry::MutexStd::new( - Entry { - peers: BTreeMap::default(), - completed: *completed, - } - .into(), - ); - - torrents.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut(); - db.remove(key) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - let db = self.get_torrents(); - - let futures = db.values().map(|e| { - let entry = e.clone(); - tokio::spawn(async move { - entry - .lock() - .expect("it should get lock for entry") - .remove_inactive_peers(max_peer_timeout); - }) - }); - - block_on(join_all(futures)); - } - - async fn remove_peerless_torrents(&self, policy: &crate::core::TrackerPolicy) { - let mut db = self.get_torrents_mut(); - - db.retain(|_, e| e.lock().expect("it should lock entry").is_not_zombie(policy)); - } -} - -impl RepositoryStdRwLock { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().expect("it should get the read lock") - } - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().expect("it should get the write lock") - } -} - -impl UpdateTorrentSync for RepositoryStdRwLock { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let mut torrents = self.torrents.write().unwrap(); - - let torrent_entry = match torrents.entry(*info_hash) { - std::collections::btree_map::Entry::Vacant(vacant) => vacant.insert(Entry::default()), - std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), - }; - - torrent_entry.insert_or_update_peer_and_get_stats(peer) - } -} -impl Repository for RepositoryStdRwLock { - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents(); - db.get(key).cloned() - } - - async fn get_metrics(&self) -> TorrentsMetrics { - let db = self.get_torrents(); - let metrics: Arc> = Arc::default(); - - let futures = db.values().map(|e| { - let metrics = metrics.clone(); - let entry = e.clone(); - - tokio::spawn(async move { - let stats = entry.get_stats(); - metrics.lock().await.seeders += u64::from(stats.complete); - metrics.lock().await.completed += u64::from(stats.downloaded); - metrics.lock().await.leechers += u64::from(stats.incomplete); - metrics.lock().await.torrents += 1; - }) - }); - - block_on(join_all(futures)); - - *metrics.blocking_lock_owned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, Entry)> { - let db = self.get_torrents(); - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut torrents = self.get_torrents_mut(); - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(info_hash) { - continue; - } - - let entry = Entry { - peers: BTreeMap::default(), - completed: *completed, - }; - - torrents.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut(); - db.remove(key) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - let mut db = self.get_torrents_mut(); - - drop(db.values_mut().map(|e| e.remove_inactive_peers(max_peer_timeout))); - } - - async fn remove_peerless_torrents(&self, policy: &crate::core::TrackerPolicy) { - let mut db = self.get_torrents_mut(); - - db.retain(|_, e| e.is_not_zombie(policy)); - } -} diff --git a/src/core/torrent/repository/tokio_sync.rs b/src/core/torrent/repository/tokio_sync.rs deleted file mode 100644 index 83edf1188..000000000 --- a/src/core/torrent/repository/tokio_sync.rs +++ /dev/null @@ -1,378 +0,0 @@ -use std::collections::BTreeMap; -use std::sync::Arc; - -use futures::future::join_all; - -use super::{Repository, UpdateTorrentAsync}; -use crate::core::databases::PersistentTorrents; -use crate::core::services::torrent::Pagination; -use crate::core::torrent::entry::{Entry, ReadInfo, Update, UpdateAsync, UpdateSync}; -use crate::core::torrent::{entry, SwarmMetadata}; -use crate::core::{peer, TorrentsMetrics, TrackerPolicy}; -use crate::shared::bit_torrent::info_hash::InfoHash; - -#[derive(Default)] -pub struct RepositoryTokioRwLock { - torrents: tokio::sync::RwLock>, -} - -impl RepositoryTokioRwLock { - async fn get_torrents<'a>( - &'a self, - ) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().await - } - - async fn get_torrents_mut<'a>( - &'a self, - ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().await - } -} - -impl UpdateTorrentAsync for RepositoryTokioRwLock { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let maybe_torrent; - { - let db = self.torrents.read().await; - maybe_torrent = db.get(info_hash).cloned(); - } - - let torrent = if let Some(torrent) = maybe_torrent { - torrent - } else { - let entry = entry::MutexTokio::default(); - let mut db = self.torrents.write().await; - db.insert(*info_hash, entry.clone()); - entry - }; - - torrent.insert_or_update_peer_and_get_stats(peer).await - } -} - -impl Repository for RepositoryTokioRwLock { - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents().await; - db.get(key).cloned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexTokio)> { - let db = self.get_torrents().await; - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn get_metrics(&self) -> TorrentsMetrics { - let db = self.get_torrents().await; - let metrics: Arc> = Arc::default(); - - let futures = db.values().map(|e| { - let metrics = metrics.clone(); - let entry = e.clone(); - - tokio::spawn(async move { - let stats = entry.lock().await.get_stats(); - metrics.lock().await.seeders += u64::from(stats.complete); - metrics.lock().await.completed += u64::from(stats.downloaded); - metrics.lock().await.leechers += u64::from(stats.incomplete); - metrics.lock().await.torrents += 1; - }) - }); - - join_all(futures).await; - - *metrics.lock_owned().await - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut db = self.get_torrents_mut().await; - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if db.contains_key(info_hash) { - continue; - } - - let entry = entry::MutexTokio::new( - Entry { - peers: BTreeMap::default(), - completed: *completed, - } - .into(), - ); - - db.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut().await; - db.remove(key) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - let db = self.get_torrents().await; - - let futures = db.values().map(|e| { - let entry = e.clone(); - tokio::spawn(async move { entry.lock().await.remove_inactive_peers(max_peer_timeout) }) - }); - - join_all(futures).await; - } - - async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - let mut db = self.get_torrents_mut().await; - - db.retain(|_, e| e.blocking_lock().is_not_zombie(policy)); - } -} - -impl RepositoryTokioRwLock { - async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().await - } - - async fn get_torrents_mut<'a>( - &'a self, - ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().await - } -} - -impl UpdateTorrentAsync for RepositoryTokioRwLock { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let maybe_torrent; - { - let db = self.torrents.read().await; - maybe_torrent = db.get(info_hash).cloned(); - } - - let torrent = if let Some(torrent) = maybe_torrent { - torrent - } else { - let entry = entry::MutexStd::default(); - let mut db = self.torrents.write().await; - db.insert(*info_hash, entry.clone()); - entry - }; - - torrent.insert_or_update_peer_and_get_stats(peer) - } -} - -impl Repository for RepositoryTokioRwLock { - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents().await; - db.get(key).cloned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexStd)> { - let db = self.get_torrents().await; - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn get_metrics(&self) -> TorrentsMetrics { - let db = self.get_torrents().await; - let metrics: Arc> = Arc::default(); - - let futures = db.values().map(|e| { - let metrics = metrics.clone(); - let entry = e.clone(); - - tokio::spawn(async move { - let stats = entry.lock().expect("it should lock the entry").get_stats(); - metrics.lock().await.seeders += u64::from(stats.complete); - metrics.lock().await.completed += u64::from(stats.downloaded); - metrics.lock().await.leechers += u64::from(stats.incomplete); - metrics.lock().await.torrents += 1; - }) - }); - - join_all(futures).await; - - *metrics.lock_owned().await - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut torrents = self.get_torrents_mut().await; - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(info_hash) { - continue; - } - - let entry = entry::MutexStd::new( - Entry { - peers: BTreeMap::default(), - completed: *completed, - } - .into(), - ); - - torrents.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut().await; - db.remove(key) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - let db = self.get_torrents().await; - - let futures = db.values().map(|e| { - let entry = e.clone(); - tokio::spawn(async move { - entry - .lock() - .expect("it should get lock for entry") - .remove_inactive_peers(max_peer_timeout); - }) - }); - - join_all(futures).await; - } - - async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - let mut db = self.get_torrents_mut().await; - - db.retain(|_, e| e.lock().expect("it should lock entry").is_not_zombie(policy)); - } -} - -impl RepositoryTokioRwLock { - async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().await - } - - async fn get_torrents_mut<'a>(&'a self) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().await - } -} - -impl UpdateTorrentAsync for RepositoryTokioRwLock { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let mut db = self.torrents.write().await; - - let torrent = db.entry(*info_hash).or_insert(Entry::default()); - - torrent.insert_or_update_peer_and_get_stats(peer) - } -} - -impl Repository for RepositoryTokioRwLock { - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents().await; - db.get(key).cloned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, Entry)> { - let db = self.get_torrents().await; - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn get_metrics(&self) -> TorrentsMetrics { - let db = self.get_torrents().await; - let metrics: Arc> = Arc::default(); - - let futures = db.values().map(|e| { - let metrics = metrics.clone(); - let entry = e.clone(); - - tokio::spawn(async move { - let stats = entry.get_stats(); - metrics.lock().await.seeders += u64::from(stats.complete); - metrics.lock().await.completed += u64::from(stats.downloaded); - metrics.lock().await.leechers += u64::from(stats.incomplete); - metrics.lock().await.torrents += 1; - }) - }); - - join_all(futures).await; - - *metrics.lock_owned().await - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut torrents = self.get_torrents_mut().await; - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(info_hash) { - continue; - } - - let entry = Entry { - peers: BTreeMap::default(), - completed: *completed, - }; - - torrents.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut().await; - db.remove(key) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - let mut db = self.get_torrents_mut().await; - - drop(db.values_mut().map(|e| e.remove_inactive_peers(max_peer_timeout))); - } - - async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - let mut db = self.get_torrents_mut().await; - - db.retain(|_, e| e.is_not_zombie(policy)); - } -} From 9a43815d00ed13e6867d07b64881d4a5391e64aa Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 13 Feb 2024 15:23:57 +0800 Subject: [PATCH 0269/1297] dev: move torrent/repository to packages --- .vscode/settings.json | 1 + Cargo.lock | 31 +- Cargo.toml | 6 +- cSpell.json | 4 + packages/configuration/src/lib.rs | 7 + packages/primitives/Cargo.toml | 4 + packages/primitives/src/announce_event.rs | 43 +++ packages/primitives/src/info_hash.rs | 165 ++++++++++ packages/primitives/src/lib.rs | 37 +++ packages/primitives/src/pagination.rs | 50 +++ {src/core => packages/primitives/src}/peer.rs | 186 +++++------- packages/primitives/src/swarm_metadata.rs | 22 ++ packages/primitives/src/torrent_metrics.rs | 25 ++ .../torrent-repository-benchmarks/Cargo.toml | 22 -- .../torrent-repository-benchmarks/README.md | 1 - .../torrent-repository-benchmarks/src/lib.rs | 2 - packages/torrent-repository/Cargo.toml | 24 ++ packages/torrent-repository/README.md | 11 + .../benches/helpers}/args.rs | 0 .../benches/helpers}/asyn.rs | 34 ++- .../benches/helpers}/mod.rs | 1 + .../benches/helpers}/sync.rs | 34 ++- .../benches/helpers}/utils.rs | 8 +- .../benches/repository-benchmark.rs} | 65 ++-- packages/torrent-repository/src/entry/mod.rs | 98 ++++++ .../torrent-repository/src/entry/mutex_std.rs | 50 +++ .../src/entry/mutex_tokio.rs | 46 +++ .../torrent-repository/src/entry/single.rs | 105 +++++++ packages/torrent-repository/src/lib.rs | 15 + .../torrent-repository/src}/repository/mod.rs | 32 +- .../src/repository/rw_lock_std.rs | 112 +++++++ .../src/repository/rw_lock_std_mutex_std.rs | 123 ++++++++ .../src/repository/rw_lock_std_mutex_tokio.rs | 131 ++++++++ .../src/repository/rw_lock_tokio.rs | 113 +++++++ .../src/repository/rw_lock_tokio_mutex_std.rs | 124 ++++++++ .../repository/rw_lock_tokio_mutex_tokio.rs | 124 ++++++++ src/bootstrap/jobs/torrent_cleanup.rs | 2 +- src/console/clients/checker/checks/http.rs | 2 +- src/console/clients/checker/checks/udp.rs | 2 +- src/console/clients/http/app.rs | 2 +- src/console/clients/udp/app.rs | 2 +- src/console/clients/udp/checker.rs | 2 +- src/core/auth.rs | 5 +- src/core/databases/mod.rs | 11 +- src/core/databases/mysql.rs | 2 +- src/core/databases/sqlite.rs | 5 +- src/core/error.rs | 3 +- src/core/mod.rs | 169 ++++++----- src/core/peer_tests.rs | 43 +++ src/core/services/statistics/mod.rs | 9 +- src/core/services/torrent.rs | 77 +---- src/core/torrent/entry.rs | 287 ------------------ src/core/torrent/mod.rs | 88 ++---- src/core/torrent/repository/rw_lock_std.rs | 122 -------- .../repository/rw_lock_std_mutex_std.rs | 143 --------- .../repository/rw_lock_std_mutex_tokio.rs | 141 --------- src/core/torrent/repository/rw_lock_tokio.rs | 124 -------- .../repository/rw_lock_tokio_mutex_std.rs | 146 --------- .../repository/rw_lock_tokio_mutex_tokio.rs | 144 --------- .../apis/v1/context/stats/resources.rs | 3 +- .../apis/v1/context/torrent/handlers.rs | 5 +- .../apis/v1/context/torrent/resources/peer.rs | 46 ++- .../v1/context/torrent/resources/torrent.rs | 16 +- .../apis/v1/context/whitelist/handlers.rs | 2 +- src/servers/http/mod.rs | 12 +- src/servers/http/percent_encoding.rs | 23 +- .../http/v1/extractors/announce_request.rs | 5 +- .../http/v1/extractors/scrape_request.rs | 3 +- src/servers/http/v1/handlers/announce.rs | 30 +- src/servers/http/v1/handlers/scrape.rs | 2 +- src/servers/http/v1/requests/announce.rs | 17 +- src/servers/http/v1/requests/scrape.rs | 7 +- src/servers/http/v1/responses/announce.rs | 41 +-- src/servers/http/v1/responses/scrape.rs | 9 +- src/servers/http/v1/services/announce.rs | 21 +- src/servers/http/v1/services/scrape.rs | 13 +- src/servers/udp/handlers.rs | 30 +- src/servers/udp/logging.rs | 2 +- src/servers/udp/mod.rs | 14 +- src/servers/udp/peer_builder.rs | 20 +- src/servers/udp/request.rs | 3 +- src/shared/bit_torrent/common.rs | 21 -- src/shared/bit_torrent/info_hash.rs | 169 ++--------- .../tracker/http/client/requests/announce.rs | 8 +- .../tracker/http/client/requests/scrape.rs | 3 +- .../tracker/http/client/responses/announce.rs | 7 +- src/shared/clock/mod.rs | 4 +- src/shared/clock/time_extent.rs | 12 +- src/shared/clock/utils.rs | 10 - tests/servers/api/environment.rs | 6 +- .../servers/api/v1/contract/context/stats.rs | 4 +- .../api/v1/contract/context/torrent.rs | 4 +- .../api/v1/contract/context/whitelist.rs | 2 +- tests/servers/http/environment.rs | 6 +- tests/servers/http/requests/announce.rs | 8 +- tests/servers/http/requests/scrape.rs | 2 +- tests/servers/http/responses/announce.rs | 6 +- tests/servers/http/v1/contract.rs | 36 +-- tests/servers/udp/environment.rs | 6 +- 99 files changed, 2072 insertions(+), 1953 deletions(-) create mode 100644 packages/primitives/src/announce_event.rs create mode 100644 packages/primitives/src/info_hash.rs create mode 100644 packages/primitives/src/pagination.rs rename {src/core => packages/primitives/src}/peer.rs (83%) create mode 100644 packages/primitives/src/swarm_metadata.rs create mode 100644 packages/primitives/src/torrent_metrics.rs delete mode 100644 packages/torrent-repository-benchmarks/Cargo.toml delete mode 100644 packages/torrent-repository-benchmarks/README.md delete mode 100644 packages/torrent-repository-benchmarks/src/lib.rs create mode 100644 packages/torrent-repository/Cargo.toml create mode 100644 packages/torrent-repository/README.md rename packages/{torrent-repository-benchmarks/src => torrent-repository/benches/helpers}/args.rs (100%) rename packages/{torrent-repository-benchmarks/src/benches => torrent-repository/benches/helpers}/asyn.rs (81%) rename packages/{torrent-repository-benchmarks/src/benches => torrent-repository/benches/helpers}/mod.rs (75%) rename packages/{torrent-repository-benchmarks/src/benches => torrent-repository/benches/helpers}/sync.rs (81%) rename packages/{torrent-repository-benchmarks/src/benches => torrent-repository/benches/helpers}/utils.rs (89%) rename packages/{torrent-repository-benchmarks/src/main.rs => torrent-repository/benches/repository-benchmark.rs} (71%) create mode 100644 packages/torrent-repository/src/entry/mod.rs create mode 100644 packages/torrent-repository/src/entry/mutex_std.rs create mode 100644 packages/torrent-repository/src/entry/mutex_tokio.rs create mode 100644 packages/torrent-repository/src/entry/single.rs create mode 100644 packages/torrent-repository/src/lib.rs rename {src/core/torrent => packages/torrent-repository/src}/repository/mod.rs (57%) create mode 100644 packages/torrent-repository/src/repository/rw_lock_std.rs create mode 100644 packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs create mode 100644 packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs create mode 100644 packages/torrent-repository/src/repository/rw_lock_tokio.rs create mode 100644 packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs create mode 100644 packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs create mode 100644 src/core/peer_tests.rs delete mode 100644 src/core/torrent/entry.rs delete mode 100644 src/core/torrent/repository/rw_lock_std.rs delete mode 100644 src/core/torrent/repository/rw_lock_std_mutex_std.rs delete mode 100644 src/core/torrent/repository/rw_lock_std_mutex_tokio.rs delete mode 100644 src/core/torrent/repository/rw_lock_tokio.rs delete mode 100644 src/core/torrent/repository/rw_lock_tokio_mutex_std.rs delete mode 100644 src/core/torrent/repository/rw_lock_tokio_mutex_tokio.rs diff --git a/.vscode/settings.json b/.vscode/settings.json index 701e89ccf..caa48dd01 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -31,4 +31,5 @@ "evenBetterToml.formatter.trailingNewline": true, "evenBetterToml.formatter.reorderKeys": true, "evenBetterToml.formatter.reorderArrays": true, + } \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 26fb919af..8ec922448 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3449,17 +3449,6 @@ dependencies = [ "winnow 0.6.5", ] -[[package]] -name = "torrust-torrent-repository-benchmarks" -version = "3.0.0-alpha.12-develop" -dependencies = [ - "aquatic_udp_protocol", - "clap", - "futures", - "tokio", - "torrust-tracker", -] - [[package]] name = "torrust-tracker" version = "3.0.0-alpha.12-develop" @@ -3471,7 +3460,6 @@ dependencies = [ "axum-client-ip", "axum-extra", "axum-server", - "binascii", "chrono", "clap", "colored", @@ -3498,8 +3486,6 @@ dependencies = [ "serde_bytes", "serde_json", "serde_repr", - "tdyne-peer-id", - "tdyne-peer-id-registry", "thiserror", "tokio", "torrust-tracker-configuration", @@ -3507,6 +3493,7 @@ dependencies = [ "torrust-tracker-located-error", "torrust-tracker-primitives", "torrust-tracker-test-helpers", + "torrust-tracker-torrent-repository", "tower-http", "trace", "tracing", @@ -3549,8 +3536,12 @@ dependencies = [ name = "torrust-tracker-primitives" version = "3.0.0-alpha.12-develop" dependencies = [ + "binascii", "derive_more", "serde", + "tdyne-peer-id", + "tdyne-peer-id-registry", + "thiserror", ] [[package]] @@ -3562,6 +3553,18 @@ dependencies = [ "torrust-tracker-primitives", ] +[[package]] +name = "torrust-tracker-torrent-repository" +version = "3.0.0-alpha.12-develop" +dependencies = [ + "clap", + "futures", + "serde", + "tokio", + "torrust-tracker-configuration", + "torrust-tracker-primitives", +] + [[package]] name = "tower" version = "0.4.13" diff --git a/Cargo.toml b/Cargo.toml index e6f196583..9610fffc2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,7 +37,6 @@ axum = { version = "0", features = ["macros"] } axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls"] } -binascii = "0" chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } colored = "2" @@ -62,14 +61,13 @@ serde_bencode = "0" serde_bytes = "0" serde_json = "1" serde_repr = "0" -tdyne-peer-id = "1" -tdyne-peer-id-registry = "0" thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "packages/configuration" } torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12-develop", path = "contrib/bencode" } torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "packages/located-error" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-alpha.12-develop", path = "packages/torrent-repository" } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } trace = "0" tracing = "0" @@ -91,7 +89,7 @@ members = [ "packages/located-error", "packages/primitives", "packages/test-helpers", - "packages/torrent-repository-benchmarks", + "packages/torrent-repository" ] [profile.dev] diff --git a/cSpell.json b/cSpell.json index da11cd29a..6d5f71b85 100644 --- a/cSpell.json +++ b/cSpell.json @@ -50,6 +50,7 @@ "filesd", "flamegraph", "Freebox", + "Frostegård", "gecos", "Grcov", "hasher", @@ -68,6 +69,7 @@ "Intermodal", "intervali", "kcachegrind", + "Joakim", "keyout", "lcov", "leecher", @@ -96,6 +98,7 @@ "oneshot", "ostr", "Pando", + "peekable", "proot", "proto", "Quickstart", @@ -109,6 +112,7 @@ "reqwest", "rerequests", "ringbuf", + "ringsize", "rngs", "rosegment", "routable", diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 4068c046f..b3b146717 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -243,6 +243,13 @@ use thiserror::Error; use torrust_tracker_located_error::{DynError, Located, LocatedError}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; +#[derive(Copy, Clone, Debug, PartialEq, Default, Constructor)] +pub struct TrackerPolicy { + pub remove_peerless_torrents: bool, + pub max_peer_timeout: u32, + pub persistent_torrent_completed_stat: bool, +} + /// Information required for loading config #[derive(Debug, Default, Clone)] pub struct Info { diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index efcce71a9..3b2406a69 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -16,4 +16,8 @@ version.workspace = true [dependencies] derive_more = "0" +thiserror = "1" +binascii = "0" serde = { version = "1", features = ["derive"] } +tdyne-peer-id = "1" +tdyne-peer-id-registry = "0" \ No newline at end of file diff --git a/packages/primitives/src/announce_event.rs b/packages/primitives/src/announce_event.rs new file mode 100644 index 000000000..16e47da99 --- /dev/null +++ b/packages/primitives/src/announce_event.rs @@ -0,0 +1,43 @@ +//! Copyright (c) 2020-2023 Joakim Frostegård and The Torrust Developers +//! +//! Distributed under Apache 2.0 license + +use serde::{Deserialize, Serialize}; + +/// Announce events. Described on the +/// [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) +#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, Serialize, Deserialize)] +pub enum AnnounceEvent { + /// The peer has started downloading the torrent. + Started, + /// The peer has ceased downloading the torrent. + Stopped, + /// The peer has completed downloading the torrent. + Completed, + /// This is one of the announcements done at regular intervals. + None, +} + +impl AnnounceEvent { + #[inline] + #[must_use] + pub fn from_i32(i: i32) -> Self { + match i { + 1 => Self::Completed, + 2 => Self::Started, + 3 => Self::Stopped, + _ => Self::None, + } + } + + #[inline] + #[must_use] + pub fn to_i32(&self) -> i32 { + match self { + AnnounceEvent::None => 0, + AnnounceEvent::Completed => 1, + AnnounceEvent::Started => 2, + AnnounceEvent::Stopped => 3, + } + } +} diff --git a/packages/primitives/src/info_hash.rs b/packages/primitives/src/info_hash.rs new file mode 100644 index 000000000..46ae6283e --- /dev/null +++ b/packages/primitives/src/info_hash.rs @@ -0,0 +1,165 @@ +use std::panic::Location; + +use thiserror::Error; + +/// `BitTorrent` Info Hash v1 +#[derive(PartialEq, Eq, Hash, Clone, Copy, Default, Debug)] +pub struct InfoHash(pub [u8; 20]); + +pub const INFO_HASH_BYTES_LEN: usize = 20; + +impl InfoHash { + /// Create a new `InfoHash` from a byte slice. + /// + /// # Panics + /// + /// Will panic if byte slice does not contains the exact amount of bytes need for the `InfoHash`. + #[must_use] + pub fn from_bytes(bytes: &[u8]) -> Self { + assert_eq!(bytes.len(), INFO_HASH_BYTES_LEN); + let mut ret = Self([0u8; INFO_HASH_BYTES_LEN]); + ret.0.clone_from_slice(bytes); + ret + } + + /// Returns the `InfoHash` internal byte array. + #[must_use] + pub fn bytes(&self) -> [u8; 20] { + self.0 + } + + /// Returns the `InfoHash` as a hex string. + #[must_use] + pub fn to_hex_string(&self) -> String { + self.to_string() + } +} + +impl Ord for InfoHash { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.0.cmp(&other.0) + } +} + +impl std::cmp::PartialOrd for InfoHash { + fn partial_cmp(&self, other: &InfoHash) -> Option { + Some(self.cmp(other)) + } +} + +impl std::fmt::Display for InfoHash { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut chars = [0u8; 40]; + binascii::bin2hex(&self.0, &mut chars).expect("failed to hexlify"); + write!(f, "{}", std::str::from_utf8(&chars).unwrap()) + } +} + +impl std::str::FromStr for InfoHash { + type Err = binascii::ConvertError; + + fn from_str(s: &str) -> Result { + let mut i = Self([0u8; 20]); + if s.len() != 40 { + return Err(binascii::ConvertError::InvalidInputLength); + } + binascii::hex2bin(s.as_bytes(), &mut i.0)?; + Ok(i) + } +} + +impl std::convert::From<&[u8]> for InfoHash { + fn from(data: &[u8]) -> InfoHash { + assert_eq!(data.len(), 20); + let mut ret = InfoHash([0u8; 20]); + ret.0.clone_from_slice(data); + ret + } +} + +impl std::convert::From<[u8; 20]> for InfoHash { + fn from(val: [u8; 20]) -> Self { + InfoHash(val) + } +} + +/// Errors that can occur when converting from a `Vec` to an `InfoHash`. +#[derive(Error, Debug)] +pub enum ConversionError { + /// Not enough bytes for infohash. An infohash is 20 bytes. + #[error("not enough bytes for infohash: {message} {location}")] + NotEnoughBytes { + location: &'static Location<'static>, + message: String, + }, + /// Too many bytes for infohash. An infohash is 20 bytes. + #[error("too many bytes for infohash: {message} {location}")] + TooManyBytes { + location: &'static Location<'static>, + message: String, + }, +} + +impl TryFrom> for InfoHash { + type Error = ConversionError; + + fn try_from(bytes: Vec) -> Result { + if bytes.len() < INFO_HASH_BYTES_LEN { + return Err(ConversionError::NotEnoughBytes { + location: Location::caller(), + message: format! {"got {} bytes, expected {}", bytes.len(), INFO_HASH_BYTES_LEN}, + }); + } + if bytes.len() > INFO_HASH_BYTES_LEN { + return Err(ConversionError::TooManyBytes { + location: Location::caller(), + message: format! {"got {} bytes, expected {}", bytes.len(), INFO_HASH_BYTES_LEN}, + }); + } + Ok(Self::from_bytes(&bytes)) + } +} + +impl serde::ser::Serialize for InfoHash { + fn serialize(&self, serializer: S) -> Result { + let mut buffer = [0u8; 40]; + let bytes_out = binascii::bin2hex(&self.0, &mut buffer).ok().unwrap(); + let str_out = std::str::from_utf8(bytes_out).unwrap(); + serializer.serialize_str(str_out) + } +} + +impl<'de> serde::de::Deserialize<'de> for InfoHash { + fn deserialize>(des: D) -> Result { + des.deserialize_str(InfoHashVisitor) + } +} + +struct InfoHashVisitor; + +impl<'v> serde::de::Visitor<'v> for InfoHashVisitor { + type Value = InfoHash; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "a 40 character long hash") + } + + fn visit_str(self, v: &str) -> Result { + if v.len() != 40 { + return Err(serde::de::Error::invalid_value( + serde::de::Unexpected::Str(v), + &"a 40 character long string", + )); + } + + let mut res = InfoHash([0u8; 20]); + + if binascii::hex2bin(v.as_bytes(), &mut res.0).is_err() { + return Err(serde::de::Error::invalid_value( + serde::de::Unexpected::Str(v), + &"a hexadecimal string", + )); + }; + Ok(res) + } +} diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index f6a14b9e8..664c0c82d 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -4,8 +4,43 @@ //! which is a `BitTorrent` tracker server. These structures are used not only //! by the tracker server crate, but also by other crates in the Torrust //! ecosystem. +use std::time::Duration; + +use info_hash::InfoHash; use serde::{Deserialize, Serialize}; +pub mod announce_event; +pub mod info_hash; +pub mod pagination; +pub mod peer; +pub mod swarm_metadata; +pub mod torrent_metrics; + +/// Duration since the Unix Epoch. +pub type DurationSinceUnixEpoch = Duration; + +/// Serializes a `DurationSinceUnixEpoch` as a Unix timestamp in milliseconds. +/// # Errors +/// +/// Will return `serde::Serializer::Error` if unable to serialize the `unix_time_value`. +pub fn ser_unix_time_value(unix_time_value: &DurationSinceUnixEpoch, ser: S) -> Result { + #[allow(clippy::cast_possible_truncation)] + ser.serialize_u64(unix_time_value.as_millis() as u64) +} + +/// IP version used by the peer to connect to the tracker: IPv4 or IPv6 +#[derive(PartialEq, Eq, Debug)] +pub enum IPVersion { + /// + IPv4, + /// + IPv6, +} + +/// Number of bytes downloaded, uploaded or pending to download (left) by the peer. +#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, Serialize, Deserialize)] +pub struct NumberOfBytes(pub i64); + /// The database management system used by the tracker. /// /// Refer to: @@ -23,6 +58,8 @@ pub enum DatabaseDriver { MySQL, } +pub type PersistentTorrents = Vec<(InfoHash, u32)>; + /// The mode the tracker will run in. /// /// Refer to [Torrust Tracker Configuration](https://docs.rs/torrust-tracker-configuration) diff --git a/packages/primitives/src/pagination.rs b/packages/primitives/src/pagination.rs new file mode 100644 index 000000000..ab7dcfe2b --- /dev/null +++ b/packages/primitives/src/pagination.rs @@ -0,0 +1,50 @@ +use serde::Deserialize; + +/// A struct to keep information about the page when results are being paginated +#[derive(Deserialize, Copy, Clone, Debug, PartialEq)] +pub struct Pagination { + /// The page number, starting at 0 + pub offset: u32, + /// Page size. The number of results per page + pub limit: u32, +} + +impl Pagination { + #[must_use] + pub fn new(offset: u32, limit: u32) -> Self { + Self { offset, limit } + } + + #[must_use] + pub fn new_with_options(offset_option: Option, limit_option: Option) -> Self { + let offset = match offset_option { + Some(offset) => offset, + None => Pagination::default_offset(), + }; + let limit = match limit_option { + Some(offset) => offset, + None => Pagination::default_limit(), + }; + + Self { offset, limit } + } + + #[must_use] + pub fn default_offset() -> u32 { + 0 + } + + #[must_use] + pub fn default_limit() -> u32 { + 4000 + } +} + +impl Default for Pagination { + fn default() -> Self { + Self { + offset: Self::default_offset(), + limit: Self::default_limit(), + } + } +} diff --git a/src/core/peer.rs b/packages/primitives/src/peer.rs similarity index 83% rename from src/core/peer.rs rename to packages/primitives/src/peer.rs index eb2b7b759..5fb9e525f 100644 --- a/src/core/peer.rs +++ b/packages/primitives/src/peer.rs @@ -3,12 +3,12 @@ //! A sample peer: //! //! ```rust,no_run -//! use torrust_tracker::core::peer; +//! use torrust_tracker_primitives::peer; //! use std::net::SocketAddr; //! use std::net::IpAddr; //! use std::net::Ipv4Addr; -//! use torrust_tracker::shared::clock::DurationSinceUnixEpoch; -//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; +//! //! //! peer::Peer { //! peer_id: peer::Id(*b"-qB00000000000000000"), @@ -20,38 +20,26 @@ //! event: AnnounceEvent::Started, //! }; //! ``` + use std::net::{IpAddr, SocketAddr}; -use std::panic::Location; use std::sync::Arc; -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use serde::Serialize; -use thiserror::Error; -use crate::shared::bit_torrent::common::{AnnounceEventDef, NumberOfBytesDef}; -use crate::shared::clock::utils::ser_unix_time_value; -use crate::shared::clock::DurationSinceUnixEpoch; - -/// IP version used by the peer to connect to the tracker: IPv4 or IPv6 -#[derive(PartialEq, Eq, Debug)] -pub enum IPVersion { - /// - IPv4, - /// - IPv6, -} +use crate::announce_event::AnnounceEvent; +use crate::{ser_unix_time_value, DurationSinceUnixEpoch, IPVersion, NumberOfBytes}; /// Peer struct used by the core `Tracker`. /// /// A sample peer: /// /// ```rust,no_run -/// use torrust_tracker::core::peer; +/// use torrust_tracker_primitives::peer; /// use std::net::SocketAddr; /// use std::net::IpAddr; /// use std::net::Ipv4Addr; -/// use torrust_tracker::shared::clock::DurationSinceUnixEpoch; -/// use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +/// use torrust_tracker_primitives::DurationSinceUnixEpoch; +/// /// /// peer::Peer { /// peer_id: peer::Id(*b"-qB00000000000000000"), @@ -73,16 +61,12 @@ pub struct Peer { #[serde(serialize_with = "ser_unix_time_value")] pub updated: DurationSinceUnixEpoch, /// The total amount of bytes uploaded by this peer so far - #[serde(with = "NumberOfBytesDef")] pub uploaded: NumberOfBytes, /// The total amount of bytes downloaded by this peer so far - #[serde(with = "NumberOfBytesDef")] pub downloaded: NumberOfBytes, /// The number of bytes this peer still has to download - #[serde(with = "NumberOfBytesDef")] pub left: NumberOfBytes, /// This is an optional key which maps to started, completed, or stopped (or empty, which is the same as not being present). - #[serde(with = "AnnounceEventDef")] pub event: AnnounceEvent, } @@ -162,22 +146,9 @@ impl Peer { } } -/// Peer ID. A 20-byte array. -/// -/// A string of length 20 which this downloader uses as its id. -/// Each downloader generates its own id at random at the start of a new download. -/// -/// A sample peer ID: -/// -/// ```rust,no_run -/// use torrust_tracker::core::peer; -/// -/// let peer_id = peer::Id(*b"-qB00000000000000000"); -/// ``` -#[derive(PartialEq, Eq, Hash, Clone, Debug, PartialOrd, Ord, Copy)] -pub struct Id(pub [u8; 20]); +use std::panic::Location; -const PEER_ID_BYTES_LEN: usize = 20; +use thiserror::Error; /// Error returned when trying to convert an invalid peer id from another type. /// @@ -196,30 +167,6 @@ pub enum IdConversionError { }, } -impl Id { - /// # Panics - /// - /// Will panic if byte slice does not contains the exact amount of bytes need for the `Id`. - #[must_use] - pub fn from_bytes(bytes: &[u8]) -> Self { - assert_eq!( - PEER_ID_BYTES_LEN, - bytes.len(), - "we are testing the equality of the constant: `PEER_ID_BYTES_LEN` ({}) and the supplied `bytes` length: {}", - PEER_ID_BYTES_LEN, - bytes.len(), - ); - let mut ret = Self([0u8; PEER_ID_BYTES_LEN]); - ret.0.clone_from_slice(bytes); - ret - } - - #[must_use] - pub fn to_bytes(&self) -> [u8; 20] { - self.0 - } -} - impl From<[u8; 20]> for Id { fn from(bytes: [u8; 20]) -> Self { Id(bytes) @@ -263,7 +210,47 @@ impl std::fmt::Display for Id { } } +/// Peer ID. A 20-byte array. +/// +/// A string of length 20 which this downloader uses as its id. +/// Each downloader generates its own id at random at the start of a new download. +/// +/// A sample peer ID: +/// +/// ```rust,no_run +/// use torrust_tracker_primitives::peer; +/// +/// let peer_id = peer::Id(*b"-qB00000000000000000"); +/// ``` +/// +#[derive(PartialEq, Eq, Hash, Clone, Debug, PartialOrd, Ord, Copy)] +pub struct Id(pub [u8; 20]); + +pub const PEER_ID_BYTES_LEN: usize = 20; + impl Id { + /// # Panics + /// + /// Will panic if byte slice does not contains the exact amount of bytes need for the `Id`. + #[must_use] + pub fn from_bytes(bytes: &[u8]) -> Self { + assert_eq!( + PEER_ID_BYTES_LEN, + bytes.len(), + "we are testing the equality of the constant: `PEER_ID_BYTES_LEN` ({}) and the supplied `bytes` length: {}", + PEER_ID_BYTES_LEN, + bytes.len(), + ); + let mut ret = Self([0u8; PEER_ID_BYTES_LEN]); + ret.0.clone_from_slice(bytes); + ret + } + + #[must_use] + pub fn to_bytes(&self) -> [u8; 20] { + self.0 + } + #[must_use] /// Converts to hex string. /// @@ -329,12 +316,27 @@ impl Serialize for Id { } } +/// Marker Trait for Peer Vectors +pub trait Encoding: From + PartialEq {} + +impl FromIterator for Vec

{ + fn from_iter>(iter: T) -> Self { + let mut peers: Vec

= vec![]; + + for peer in iter { + peers.push(peer.into()); + } + + peers + } +} + pub mod fixture { use std::net::SocketAddr; - use aquatic_udp_protocol::NumberOfBytes; - use super::{Id, Peer}; + use crate::announce_event::AnnounceEvent; + use crate::{DurationSinceUnixEpoch, NumberOfBytes}; #[derive(PartialEq, Debug)] @@ -396,11 +398,11 @@ pub mod fixture { Self { peer_id: Id(*b"-qB00000000000000000"), peer_addr: std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: crate::shared::clock::DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes(0), downloaded: NumberOfBytes(0), left: NumberOfBytes(0), - event: aquatic_udp_protocol::AnnounceEvent::Started, + event: AnnounceEvent::Started, } } } @@ -409,7 +411,7 @@ pub mod fixture { #[cfg(test)] pub mod test { mod torrent_peer_id { - use crate::core::peer; + use crate::peer; #[test] fn should_be_instantiated_from_a_byte_slice() { @@ -518,50 +520,4 @@ pub mod test { assert_eq!(peer::Id(*b"-qB00000000000000000").to_bytes(), *b"-qB00000000000000000"); } } - - mod torrent_peer { - - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - use serde_json::Value; - - use crate::core::peer::{self, Peer}; - use crate::shared::clock::{Current, Time}; - - #[test] - fn it_should_be_serializable() { - let torrent_peer = Peer { - peer_id: peer::Id(*b"-qB0000-000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: Current::now(), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Started, - }; - - let raw_json = serde_json::to_string(&torrent_peer).unwrap(); - - let expected_raw_json = r#" - { - "peer_id": { - "id": "0x2d7142303030302d303030303030303030303030", - "client": "qBittorrent" - }, - "peer_addr":"126.0.0.1:8080", - "updated":0, - "uploaded":0, - "downloaded":0, - "left":0, - "event":"Started" - } - "#; - - assert_eq!( - serde_json::from_str::(&raw_json).unwrap(), - serde_json::from_str::(expected_raw_json).unwrap() - ); - } - } } diff --git a/packages/primitives/src/swarm_metadata.rs b/packages/primitives/src/swarm_metadata.rs new file mode 100644 index 000000000..ca880b54d --- /dev/null +++ b/packages/primitives/src/swarm_metadata.rs @@ -0,0 +1,22 @@ +use derive_more::Constructor; + +/// Swarm statistics for one torrent. +/// Swarm metadata dictionary in the scrape response. +/// +/// See [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) +#[derive(Copy, Clone, Debug, PartialEq, Default, Constructor)] +pub struct SwarmMetadata { + /// (i.e `completed`): The number of peers that have ever completed downloading + pub downloaded: u32, // + /// (i.e `seeders`): The number of active peers that have completed downloading (seeders) + pub complete: u32, //seeders + /// (i.e `leechers`): The number of active peers that have not completed downloading (leechers) + pub incomplete: u32, +} + +impl SwarmMetadata { + #[must_use] + pub fn zeroed() -> Self { + Self::default() + } +} diff --git a/packages/primitives/src/torrent_metrics.rs b/packages/primitives/src/torrent_metrics.rs new file mode 100644 index 000000000..c60507171 --- /dev/null +++ b/packages/primitives/src/torrent_metrics.rs @@ -0,0 +1,25 @@ +use std::ops::AddAssign; + +/// Structure that holds general `Tracker` torrents metrics. +/// +/// Metrics are aggregate values for all torrents. +#[derive(Copy, Clone, Debug, PartialEq, Default)] +pub struct TorrentsMetrics { + /// Total number of seeders for all torrents + pub seeders: u64, + /// Total number of peers that have ever completed downloading for all torrents. + pub completed: u64, + /// Total number of leechers for all torrents. + pub leechers: u64, + /// Total number of torrents. + pub torrents: u64, +} + +impl AddAssign for TorrentsMetrics { + fn add_assign(&mut self, rhs: Self) { + self.seeders += rhs.seeders; + self.completed += rhs.completed; + self.leechers += rhs.leechers; + self.torrents += rhs.torrents; + } +} diff --git a/packages/torrent-repository-benchmarks/Cargo.toml b/packages/torrent-repository-benchmarks/Cargo.toml deleted file mode 100644 index e8b22f52f..000000000 --- a/packages/torrent-repository-benchmarks/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -description = "A set of benchmarks for the torrent repository" -keywords = ["benchmarking", "library", "repository", "torrent"] -name = "torrust-torrent-repository-benchmarks" -readme = "README.md" - -authors.workspace = true -documentation.workspace = true -edition.workspace = true -homepage.workspace = true -license.workspace = true -publish.workspace = true -repository.workspace = true -rust-version.workspace = true -version.workspace = true - -[dependencies] -aquatic_udp_protocol = "0.8.0" -clap = { version = "4.4.8", features = ["derive"] } -futures = "0.3.29" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker = { path = "../../" } diff --git a/packages/torrent-repository-benchmarks/README.md b/packages/torrent-repository-benchmarks/README.md deleted file mode 100644 index 14183ea69..000000000 --- a/packages/torrent-repository-benchmarks/README.md +++ /dev/null @@ -1 +0,0 @@ -# Benchmarks of the torrent repository diff --git a/packages/torrent-repository-benchmarks/src/lib.rs b/packages/torrent-repository-benchmarks/src/lib.rs deleted file mode 100644 index 58ebc2057..000000000 --- a/packages/torrent-repository-benchmarks/src/lib.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod args; -pub mod benches; diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml new file mode 100644 index 000000000..0df82a2c6 --- /dev/null +++ b/packages/torrent-repository/Cargo.toml @@ -0,0 +1,24 @@ +[package] +description = "A library to provide error decorator with the location and the source of the original error." +keywords = ["torrents", "repository", "library"] +name = "torrust-tracker-torrent-repository" +readme = "README.md" + +authors.workspace = true +categories.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +clap = { version = "4.4.8", features = ["derive"] } +futures = "0.3.29" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } +torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } +serde = { version = "1", features = ["derive"] } diff --git a/packages/torrent-repository/README.md b/packages/torrent-repository/README.md new file mode 100644 index 000000000..98d7d922b --- /dev/null +++ b/packages/torrent-repository/README.md @@ -0,0 +1,11 @@ +# Torrust Tracker Configuration + +A library to provide torrent repository to the [Torrust Tracker](https://github.com/torrust/torrust-tracker). + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-torrent-repository). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/torrent-repository-benchmarks/src/args.rs b/packages/torrent-repository/benches/helpers/args.rs similarity index 100% rename from packages/torrent-repository-benchmarks/src/args.rs rename to packages/torrent-repository/benches/helpers/args.rs diff --git a/packages/torrent-repository-benchmarks/src/benches/asyn.rs b/packages/torrent-repository/benches/helpers/asyn.rs similarity index 81% rename from packages/torrent-repository-benchmarks/src/benches/asyn.rs rename to packages/torrent-repository/benches/helpers/asyn.rs index dffd31682..4fb37104f 100644 --- a/packages/torrent-repository-benchmarks/src/benches/asyn.rs +++ b/packages/torrent-repository/benches/helpers/asyn.rs @@ -1,16 +1,17 @@ +use std::sync::Arc; use std::time::Duration; use clap::Parser; use futures::stream::FuturesUnordered; -use torrust_tracker::core::torrent::repository::UpdateTorrentAsync; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_torrent_repository::repository::RepositoryAsync; -use crate::args::Args; -use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; +use super::args::Args; +use super::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; -pub async fn add_one_torrent(samples: usize) -> (Duration, Duration) +pub async fn add_one_torrent(samples: usize) -> (Duration, Duration) where - V: UpdateTorrentAsync + Default, + V: RepositoryAsync + Default, { let mut results: Vec = Vec::with_capacity(samples); @@ -34,15 +35,16 @@ where } // Add one torrent ten thousand times in parallel (depending on the set worker threads) -pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - V: UpdateTorrentAsync + Default + Clone + Send + Sync + 'static, + V: RepositoryAsync + Default, + Arc: Clone + Send + Sync + 'static, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = V::default(); + let torrent_repository = Arc::::default(); let info_hash: &'static InfoHash = &InfoHash([0; 20]); let handles = FuturesUnordered::new(); @@ -83,15 +85,16 @@ where } // Add ten thousand torrents in parallel (depending on the set worker threads) -pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - V: UpdateTorrentAsync + Default + Clone + Send + Sync + 'static, + V: RepositoryAsync + Default, + Arc: Clone + Send + Sync + 'static, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = V::default(); + let torrent_repository = Arc::::default(); let info_hashes = generate_unique_info_hashes(10_000); let handles = FuturesUnordered::new(); @@ -127,15 +130,16 @@ where } // Async update ten thousand torrents in parallel (depending on the set worker threads) -pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - V: UpdateTorrentAsync + Default + Clone + Send + Sync + 'static, + V: RepositoryAsync + Default, + Arc: Clone + Send + Sync + 'static, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = V::default(); + let torrent_repository = Arc::::default(); let info_hashes = generate_unique_info_hashes(10_000); let handles = FuturesUnordered::new(); diff --git a/packages/torrent-repository-benchmarks/src/benches/mod.rs b/packages/torrent-repository/benches/helpers/mod.rs similarity index 75% rename from packages/torrent-repository-benchmarks/src/benches/mod.rs rename to packages/torrent-repository/benches/helpers/mod.rs index 1026aa4bf..758c123bd 100644 --- a/packages/torrent-repository-benchmarks/src/benches/mod.rs +++ b/packages/torrent-repository/benches/helpers/mod.rs @@ -1,3 +1,4 @@ +pub mod args; pub mod asyn; pub mod sync; pub mod utils; diff --git a/packages/torrent-repository-benchmarks/src/benches/sync.rs b/packages/torrent-repository/benches/helpers/sync.rs similarity index 81% rename from packages/torrent-repository-benchmarks/src/benches/sync.rs rename to packages/torrent-repository/benches/helpers/sync.rs index 04385bc55..aa2f8188a 100644 --- a/packages/torrent-repository-benchmarks/src/benches/sync.rs +++ b/packages/torrent-repository/benches/helpers/sync.rs @@ -1,18 +1,19 @@ +use std::sync::Arc; use std::time::Duration; use clap::Parser; use futures::stream::FuturesUnordered; -use torrust_tracker::core::torrent::repository::UpdateTorrentSync; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_torrent_repository::repository::Repository; -use crate::args::Args; -use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; +use super::args::Args; +use super::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; // Simply add one torrent #[must_use] -pub fn add_one_torrent(samples: usize) -> (Duration, Duration) +pub fn add_one_torrent(samples: usize) -> (Duration, Duration) where - V: UpdateTorrentSync + Default, + V: Repository + Default, { let mut results: Vec = Vec::with_capacity(samples); @@ -34,15 +35,16 @@ where } // Add one torrent ten thousand times in parallel (depending on the set worker threads) -pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - V: UpdateTorrentSync + Default + Clone + Send + Sync + 'static, + V: Repository + Default, + Arc: Clone + Send + Sync + 'static, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = V::default(); + let torrent_repository = Arc::::default(); let info_hash: &'static InfoHash = &InfoHash([0; 20]); let handles = FuturesUnordered::new(); @@ -79,15 +81,16 @@ where } // Add ten thousand torrents in parallel (depending on the set worker threads) -pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - V: UpdateTorrentSync + Default + Clone + Send + Sync + 'static, + V: Repository + Default, + Arc: Clone + Send + Sync + 'static, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = V::default(); + let torrent_repository = Arc::::default(); let info_hashes = generate_unique_info_hashes(10_000); let handles = FuturesUnordered::new(); @@ -121,15 +124,16 @@ where } // Update ten thousand torrents in parallel (depending on the set worker threads) -pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) where - V: UpdateTorrentSync + Default + Clone + Send + Sync + 'static, + V: Repository + Default, + Arc: Clone + Send + Sync + 'static, { let args = Args::parse(); let mut results: Vec = Vec::with_capacity(samples); for _ in 0..samples { - let torrent_repository = V::default(); + let torrent_repository = Arc::::default(); let info_hashes = generate_unique_info_hashes(10_000); let handles = FuturesUnordered::new(); diff --git a/packages/torrent-repository-benchmarks/src/benches/utils.rs b/packages/torrent-repository/benches/helpers/utils.rs similarity index 89% rename from packages/torrent-repository-benchmarks/src/benches/utils.rs rename to packages/torrent-repository/benches/helpers/utils.rs index ef1640038..aed9f40cf 100644 --- a/packages/torrent-repository-benchmarks/src/benches/utils.rs +++ b/packages/torrent-repository/benches/helpers/utils.rs @@ -2,10 +2,10 @@ use std::collections::HashSet; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::time::Duration; -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; -use torrust_tracker::core::peer::{Id, Peer}; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -use torrust_tracker::shared::clock::DurationSinceUnixEpoch; +use torrust_tracker_primitives::announce_event::AnnounceEvent; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer::{Id, Peer}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfBytes}; pub const DEFAULT_PEER: Peer = Peer { peer_id: Id([0; 20]), diff --git a/packages/torrent-repository-benchmarks/src/main.rs b/packages/torrent-repository/benches/repository-benchmark.rs similarity index 71% rename from packages/torrent-repository-benchmarks/src/main.rs rename to packages/torrent-repository/benches/repository-benchmark.rs index b935cea43..bff34b256 100644 --- a/packages/torrent-repository-benchmarks/src/main.rs +++ b/packages/torrent-repository/benches/repository-benchmark.rs @@ -1,13 +1,14 @@ -use std::sync::Arc; +mod helpers; use clap::Parser; -use torrust_torrent_repository_benchmarks::args::Args; -use torrust_torrent_repository_benchmarks::benches::{asyn, sync}; -use torrust_tracker::core::torrent::{ +use torrust_tracker_torrent_repository::{ TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, }; +use crate::helpers::args::Args; +use crate::helpers::{asyn, sync}; + #[allow(clippy::too_many_lines)] #[allow(clippy::print_literal)] fn main() { @@ -24,24 +25,22 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(asyn::add_one_torrent::>(1_000_000)) + rt.block_on(asyn::add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::>(&rt, 10)) + rt.block_on(asyn::update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::>(&rt, 10)) + rt.block_on(asyn::add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::>( - &rt, 10 - )) + rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) ); if let Some(true) = args.compare { @@ -51,22 +50,22 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - sync::add_one_torrent::>(1_000_000) + sync::add_one_torrent::(1_000_000) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(sync::update_one_torrent_in_parallel::>(&rt, 10)) + rt.block_on(sync::update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(sync::add_multiple_torrents_in_parallel::>(&rt, 10)) + rt.block_on(sync::add_multiple_torrents_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(sync::update_multiple_torrents_in_parallel::>(&rt, 10)) + rt.block_on(sync::update_multiple_torrents_in_parallel::(&rt, 10)) ); println!(); @@ -75,26 +74,24 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - sync::add_one_torrent::>(1_000_000) + sync::add_one_torrent::(1_000_000) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(sync::update_one_torrent_in_parallel::>( - &rt, 10 - )) + rt.block_on(sync::update_one_torrent_in_parallel::(&rt, 10)) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(sync::add_multiple_torrents_in_parallel::>( + rt.block_on(sync::add_multiple_torrents_in_parallel::( &rt, 10 )) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(sync::update_multiple_torrents_in_parallel::>( + rt.block_on(sync::update_multiple_torrents_in_parallel::( &rt, 10 )) ); @@ -105,26 +102,28 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(asyn::add_one_torrent::>(1_000_000)) + rt.block_on(asyn::add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::>( + rt.block_on(asyn::update_one_torrent_in_parallel::( &rt, 10 )) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::>( + rt.block_on(asyn::add_multiple_torrents_in_parallel::( &rt, 10 )) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::>(&rt, 10)) + rt.block_on(asyn::update_multiple_torrents_in_parallel::( + &rt, 10 + )) ); println!(); @@ -133,26 +132,28 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(asyn::add_one_torrent::>(1_000_000)) + rt.block_on(asyn::add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::>( + rt.block_on(asyn::update_one_torrent_in_parallel::( &rt, 10 )) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::>( + rt.block_on(asyn::add_multiple_torrents_in_parallel::( &rt, 10 )) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::>(&rt, 10)) + rt.block_on(asyn::update_multiple_torrents_in_parallel::( + &rt, 10 + )) ); println!(); @@ -161,26 +162,26 @@ fn main() { println!( "{}: Avg/AdjAvg: {:?}", "add_one_torrent", - rt.block_on(asyn::add_one_torrent::>(1_000_000)) + rt.block_on(asyn::add_one_torrent::(1_000_000)) ); println!( "{}: Avg/AdjAvg: {:?}", "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::>( + rt.block_on(asyn::update_one_torrent_in_parallel::( &rt, 10 )) ); println!( "{}: Avg/AdjAvg: {:?}", "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::>( + rt.block_on(asyn::add_multiple_torrents_in_parallel::( &rt, 10 )) ); println!( "{}: Avg/AdjAvg: {:?}", "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::>(&rt, 10)) + rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) ); } } diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs new file mode 100644 index 000000000..04aa597df --- /dev/null +++ b/packages/torrent-repository/src/entry/mod.rs @@ -0,0 +1,98 @@ +use std::fmt::Debug; +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +pub mod mutex_std; +pub mod mutex_tokio; +pub mod single; + +pub trait Entry { + /// It returns the swarm metadata (statistics) as a struct: + /// + /// `(seeders, completed, leechers)` + fn get_stats(&self) -> SwarmMetadata; + + /// Returns True if Still a Valid Entry according to the Tracker Policy + fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool; + + /// Returns True if the Peers is Empty + fn peers_is_empty(&self) -> bool; + + /// Returns the number of Peers + fn get_peers_len(&self) -> usize; + + /// Get all swarm peers, optionally limiting the result. + fn get_peers(&self, limit: Option) -> Vec>; + + /// It returns the list of peers for a given peer client, optionally limiting the + /// result. + /// + /// It filters out the input peer, typically because we want to return this + /// list of peers to that client peer. + fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec>; + + /// It updates a peer and returns true if the number of complete downloads have increased. + /// + /// The number of peers that have complete downloading is synchronously updated when peers are updated. + /// That's the total torrent downloads counter. + fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool; + + // It preforms a combined operation of `insert_or_update_peer` and `get_stats`. + fn insert_or_update_peer_and_get_stats(&mut self, peer: &peer::Peer) -> (bool, SwarmMetadata); + + /// It removes peer from the swarm that have not been updated for more than `current_cutoff` seconds + fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch); +} + +#[allow(clippy::module_name_repetitions)] +pub trait EntrySync { + fn get_stats(&self) -> SwarmMetadata; + fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool; + fn peers_is_empty(&self) -> bool; + fn get_peers_len(&self) -> usize; + fn get_peers(&self, limit: Option) -> Vec>; + fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec>; + fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool; + fn insert_or_update_peer_and_get_stats(&self, peer: &peer::Peer) -> (bool, SwarmMetadata); + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); +} + +#[allow(clippy::module_name_repetitions)] +pub trait EntryAsync { + fn get_stats(self) -> impl std::future::Future + Send; + + #[allow(clippy::wrong_self_convention)] + fn is_not_zombie(self, policy: &TrackerPolicy) -> impl std::future::Future + Send; + fn peers_is_empty(self) -> impl std::future::Future + Send; + fn get_peers_len(self) -> impl std::future::Future + Send; + fn get_peers(self, limit: Option) -> impl std::future::Future>> + Send; + fn get_peers_for_peer( + self, + client: &peer::Peer, + limit: Option, + ) -> impl std::future::Future>> + Send; + fn insert_or_update_peer(self, peer: &peer::Peer) -> impl std::future::Future + Send; + fn insert_or_update_peer_and_get_stats( + self, + peer: &peer::Peer, + ) -> impl std::future::Future + std::marker::Send; + fn remove_inactive_peers(self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; +} + +/// A data structure containing all the information about a torrent in the tracker. +/// +/// This is the tracker entry for a given torrent and contains the swarm data, +/// that's the list of all the peers trying to download the same torrent. +/// The tracker keeps one entry like this for every torrent. +#[derive(Serialize, Deserialize, Clone, Debug, Default)] +pub struct Torrent { + /// The swarm: a network of peers that are all trying to download the torrent associated to this entry + #[serde(skip)] + pub(crate) peers: std::collections::BTreeMap>, + /// The number of peers that have ever completed downloading the torrent associated to this entry + pub(crate) completed: u32, +} diff --git a/packages/torrent-repository/src/entry/mutex_std.rs b/packages/torrent-repository/src/entry/mutex_std.rs new file mode 100644 index 000000000..df6228317 --- /dev/null +++ b/packages/torrent-repository/src/entry/mutex_std.rs @@ -0,0 +1,50 @@ +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use super::{Entry, EntrySync}; +use crate::EntryMutexStd; + +impl EntrySync for EntryMutexStd { + fn get_stats(&self) -> SwarmMetadata { + self.lock().expect("it should get a lock").get_stats() + } + + fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool { + self.lock().expect("it should get a lock").is_not_zombie(policy) + } + + fn peers_is_empty(&self) -> bool { + self.lock().expect("it should get a lock").peers_is_empty() + } + + fn get_peers_len(&self) -> usize { + self.lock().expect("it should get a lock").get_peers_len() + } + + fn get_peers(&self, limit: Option) -> Vec> { + self.lock().expect("it should get lock").get_peers(limit) + } + + fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec> { + self.lock().expect("it should get lock").get_peers_for_peer(client, limit) + } + + fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool { + self.lock().expect("it should lock the entry").insert_or_update_peer(peer) + } + + fn insert_or_update_peer_and_get_stats(&self, peer: &peer::Peer) -> (bool, SwarmMetadata) { + self.lock() + .expect("it should lock the entry") + .insert_or_update_peer_and_get_stats(peer) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + self.lock() + .expect("it should lock the entry") + .remove_inactive_peers(current_cutoff); + } +} diff --git a/packages/torrent-repository/src/entry/mutex_tokio.rs b/packages/torrent-repository/src/entry/mutex_tokio.rs new file mode 100644 index 000000000..c4d13fb43 --- /dev/null +++ b/packages/torrent-repository/src/entry/mutex_tokio.rs @@ -0,0 +1,46 @@ +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use super::{Entry, EntryAsync}; +use crate::EntryMutexTokio; + +impl EntryAsync for EntryMutexTokio { + async fn get_stats(self) -> SwarmMetadata { + self.lock().await.get_stats() + } + + async fn is_not_zombie(self, policy: &TrackerPolicy) -> bool { + self.lock().await.is_not_zombie(policy) + } + + async fn peers_is_empty(self) -> bool { + self.lock().await.peers_is_empty() + } + + async fn get_peers_len(self) -> usize { + self.lock().await.get_peers_len() + } + + async fn get_peers(self, limit: Option) -> Vec> { + self.lock().await.get_peers(limit) + } + + async fn get_peers_for_peer(self, client: &peer::Peer, limit: Option) -> Vec> { + self.lock().await.get_peers_for_peer(client, limit) + } + + async fn insert_or_update_peer(self, peer: &peer::Peer) -> bool { + self.lock().await.insert_or_update_peer(peer) + } + + async fn insert_or_update_peer_and_get_stats(self, peer: &peer::Peer) -> (bool, SwarmMetadata) { + self.lock().await.insert_or_update_peer_and_get_stats(peer) + } + + async fn remove_inactive_peers(self, current_cutoff: DurationSinceUnixEpoch) { + self.lock().await.remove_inactive_peers(current_cutoff); + } +} diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs new file mode 100644 index 000000000..7a5cf6240 --- /dev/null +++ b/packages/torrent-repository/src/entry/single.rs @@ -0,0 +1,105 @@ +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::announce_event::AnnounceEvent; +use torrust_tracker_primitives::peer::{self}; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::Entry; +use crate::EntrySingle; + +impl Entry for EntrySingle { + #[allow(clippy::cast_possible_truncation)] + fn get_stats(&self) -> SwarmMetadata { + let complete: u32 = self.peers.values().filter(|peer| peer.is_seeder()).count() as u32; + let incomplete: u32 = self.peers.len() as u32 - complete; + + SwarmMetadata { + downloaded: self.completed, + complete, + incomplete, + } + } + + fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool { + if policy.persistent_torrent_completed_stat && self.completed > 0 { + return true; + } + + if policy.remove_peerless_torrents && self.peers.is_empty() { + return false; + } + + true + } + + fn peers_is_empty(&self) -> bool { + self.peers.is_empty() + } + + fn get_peers_len(&self) -> usize { + self.peers.len() + } + fn get_peers(&self, limit: Option) -> Vec> { + match limit { + Some(limit) => self.peers.values().take(limit).cloned().collect(), + None => self.peers.values().cloned().collect(), + } + } + + fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec> { + match limit { + Some(limit) => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != peer::ReadInfo::get_address(client)) + // Limit the number of peers on the result + .take(limit) + .cloned() + .collect(), + None => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != peer::ReadInfo::get_address(client)) + .cloned() + .collect(), + } + } + + fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool { + let mut did_torrent_stats_change: bool = false; + + match peer::ReadInfo::get_event(peer) { + AnnounceEvent::Stopped => { + drop(self.peers.remove(&peer::ReadInfo::get_id(peer))); + } + AnnounceEvent::Completed => { + let peer_old = self.peers.insert(peer::ReadInfo::get_id(peer), Arc::new(*peer)); + // Don't count if peer was not previously known and not already completed. + if peer_old.is_some_and(|p| p.event != AnnounceEvent::Completed) { + self.completed += 1; + did_torrent_stats_change = true; + } + } + _ => { + drop(self.peers.insert(peer::ReadInfo::get_id(peer), Arc::new(*peer))); + } + } + + did_torrent_stats_change + } + + fn insert_or_update_peer_and_get_stats(&mut self, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let changed = self.insert_or_update_peer(peer); + let stats = self.get_stats(); + (changed, stats) + } + + fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + self.peers + .retain(|_, peer| peer::ReadInfo::get_updated(peer) > current_cutoff); + } +} diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs new file mode 100644 index 000000000..903e1405e --- /dev/null +++ b/packages/torrent-repository/src/lib.rs @@ -0,0 +1,15 @@ +use std::sync::Arc; + +pub mod entry; +pub mod repository; + +pub type EntrySingle = entry::Torrent; +pub type EntryMutexStd = Arc>; +pub type EntryMutexTokio = Arc>; + +pub type TorrentsRwLockStd = repository::RwLockStd; +pub type TorrentsRwLockStdMutexStd = repository::RwLockStd; +pub type TorrentsRwLockStdMutexTokio = repository::RwLockStd; +pub type TorrentsRwLockTokio = repository::RwLockTokio; +pub type TorrentsRwLockTokioMutexStd = repository::RwLockTokio; +pub type TorrentsRwLockTokioMutexTokio = repository::RwLockTokio; diff --git a/src/core/torrent/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs similarity index 57% rename from src/core/torrent/repository/mod.rs rename to packages/torrent-repository/src/repository/mod.rs index 1c4ce8ae9..b46771163 100644 --- a/src/core/torrent/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -1,8 +1,9 @@ -use super::SwarmMetadata; -use crate::core::databases::PersistentTorrents; -use crate::core::services::torrent::Pagination; -use crate::core::{peer, TorrentsMetrics, TrackerPolicy}; -use crate::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; pub mod rw_lock_std; pub mod rw_lock_std_mutex_std; @@ -12,20 +13,25 @@ pub mod rw_lock_tokio_mutex_std; pub mod rw_lock_tokio_mutex_tokio; pub trait Repository: Default + 'static { + fn get(&self, key: &InfoHash) -> Option; + fn get_metrics(&self) -> TorrentsMetrics; + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, T)>; + fn import_persistent(&self, persistent_torrents: &PersistentTorrents); + fn remove(&self, key: &InfoHash) -> Option; + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); + fn remove_peerless_torrents(&self, policy: &TrackerPolicy); + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata); +} + +#[allow(clippy::module_name_repetitions)] +pub trait RepositoryAsync: Default + 'static { fn get(&self, key: &InfoHash) -> impl std::future::Future> + Send; fn get_metrics(&self) -> impl std::future::Future + Send; fn get_paginated(&self, pagination: Option<&Pagination>) -> impl std::future::Future> + Send; fn import_persistent(&self, persistent_torrents: &PersistentTorrents) -> impl std::future::Future + Send; fn remove(&self, key: &InfoHash) -> impl std::future::Future> + Send; - fn remove_inactive_peers(&self, max_peer_timeout: u32) -> impl std::future::Future + Send; + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> impl std::future::Future + Send; -} - -pub trait UpdateTorrentSync { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata); -} - -pub trait UpdateTorrentAsync { fn update_torrent_with_peer_and_get_stats( &self, info_hash: &InfoHash, diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs new file mode 100644 index 000000000..bacef623d --- /dev/null +++ b/packages/torrent-repository/src/repository/rw_lock_std.rs @@ -0,0 +1,112 @@ +use std::collections::BTreeMap; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; + +use super::Repository; +use crate::entry::Entry; +use crate::{EntrySingle, TorrentsRwLockStd}; + +impl TorrentsRwLockStd { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("it should get the read lock") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("it should get the write lock") + } +} + +impl Repository for TorrentsRwLockStd +where + EntrySingle: Entry, +{ + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let mut db = self.get_torrents_mut(); + + let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); + + entry.insert_or_update_peer_and_get_stats(peer) + } + + fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + fn get_metrics(&self) -> TorrentsMetrics { + let mut metrics = TorrentsMetrics::default(); + + for entry in self.get_torrents().values() { + let stats = entry.get_stats(); + metrics.seeders += u64::from(stats.complete); + metrics.completed += u64::from(stats.downloaded); + metrics.leechers += u64::from(stats.incomplete); + metrics.torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = EntrySingle { + peers: BTreeMap::default(), + completed: *completed, + }; + + torrents.insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let mut db = self.get_torrents_mut(); + let entries = db.values_mut(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.is_not_zombie(policy)); + } +} diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs new file mode 100644 index 000000000..9fca82ba8 --- /dev/null +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs @@ -0,0 +1,123 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; + +use super::Repository; +use crate::entry::{Entry, EntrySync}; +use crate::{EntryMutexStd, EntrySingle, TorrentsRwLockStdMutexStd}; + +impl TorrentsRwLockStdMutexStd { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl Repository for TorrentsRwLockStdMutexStd +where + EntryMutexStd: EntrySync, + EntrySingle: Entry, +{ + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let maybe_entry = self.get_torrents().get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut(); + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.insert_or_update_peer_and_get_stats(peer) + } + + fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + fn get_metrics(&self) -> TorrentsMetrics { + let mut metrics = TorrentsMetrics::default(); + + for entry in self.get_torrents().values() { + let stats = entry.lock().expect("it should get a lock").get_stats(); + metrics.seeders += u64::from(stats.complete); + metrics.completed += u64::from(stats.downloaded); + metrics.leechers += u64::from(stats.incomplete); + metrics.torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexStd::new( + EntrySingle { + peers: BTreeMap::default(), + completed: *completed, + } + .into(), + ); + + torrents.insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let db = self.get_torrents(); + let entries = db.values().cloned(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.lock().expect("it should lock entry").is_not_zombie(policy)); + } +} diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs new file mode 100644 index 000000000..b9fb54469 --- /dev/null +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs @@ -0,0 +1,131 @@ +use std::collections::BTreeMap; +use std::pin::Pin; +use std::sync::Arc; + +use futures::future::join_all; +use futures::{Future, FutureExt}; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; + +use super::RepositoryAsync; +use crate::entry::{Entry, EntryAsync}; +use crate::{EntryMutexTokio, EntrySingle, TorrentsRwLockStdMutexTokio}; + +impl TorrentsRwLockStdMutexTokio { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl RepositoryAsync for TorrentsRwLockStdMutexTokio +where + EntryMutexTokio: EntryAsync, + EntrySingle: Entry, +{ + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let maybe_entry = self.get_torrents().get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut(); + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.insert_or_update_peer_and_get_stats(peer).await + } + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexTokio)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let mut metrics = TorrentsMetrics::default(); + + let entries: Vec<_> = self.get_torrents().values().cloned().collect(); + + for entry in entries { + let stats = entry.lock().await.get_stats(); + metrics.seeders += u64::from(stats.complete); + metrics.completed += u64::from(stats.downloaded); + metrics.leechers += u64::from(stats.incomplete); + metrics.torrents += 1; + } + + metrics + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut db = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if db.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexTokio::new( + EntrySingle { + peers: BTreeMap::default(), + completed: *completed, + } + .into(), + ); + + db.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let handles: Vec + Send>>>; + { + let db = self.get_torrents(); + handles = db + .values() + .cloned() + .map(|e| e.remove_inactive_peers(current_cutoff).boxed()) + .collect(); + } + join_all(handles).await; + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.blocking_lock().is_not_zombie(policy)); + } +} diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs new file mode 100644 index 000000000..d0b7ec751 --- /dev/null +++ b/packages/torrent-repository/src/repository/rw_lock_tokio.rs @@ -0,0 +1,113 @@ +use std::collections::BTreeMap; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; + +use super::RepositoryAsync; +use crate::entry::Entry; +use crate::{EntrySingle, TorrentsRwLockTokio}; + +impl TorrentsRwLockTokio { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl RepositoryAsync for TorrentsRwLockTokio +where + EntrySingle: Entry, +{ + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let mut db = self.get_torrents_mut().await; + + let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); + + entry.insert_or_update_peer_and_get_stats(peer) + } + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let mut metrics = TorrentsMetrics::default(); + + for entry in self.get_torrents().await.values() { + let stats = entry.get_stats(); + metrics.seeders += u64::from(stats.complete); + metrics.completed += u64::from(stats.downloaded); + metrics.leechers += u64::from(stats.incomplete); + metrics.torrents += 1; + } + + metrics + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = EntrySingle { + peers: BTreeMap::default(), + completed: *completed, + }; + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let mut db = self.get_torrents_mut().await; + let entries = db.values_mut(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff); + } + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.is_not_zombie(policy)); + } +} diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs new file mode 100644 index 000000000..f800d2001 --- /dev/null +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs @@ -0,0 +1,124 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; + +use super::RepositoryAsync; +use crate::entry::{Entry, EntrySync}; +use crate::{EntryMutexStd, EntrySingle, TorrentsRwLockTokioMutexStd}; + +impl TorrentsRwLockTokioMutexStd { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl RepositoryAsync for TorrentsRwLockTokioMutexStd +where + EntryMutexStd: EntrySync, + EntrySingle: Entry, +{ + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut().await; + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.insert_or_update_peer_and_get_stats(peer) + } + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let mut metrics = TorrentsMetrics::default(); + + for entry in self.get_torrents().await.values() { + let stats = entry.get_stats(); + metrics.seeders += u64::from(stats.complete); + metrics.completed += u64::from(stats.downloaded); + metrics.leechers += u64::from(stats.incomplete); + metrics.torrents += 1; + } + + metrics + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexStd::new( + EntrySingle { + peers: BTreeMap::default(), + completed: *completed, + } + .into(), + ); + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let db = self.get_torrents().await; + let entries = db.values().cloned(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff); + } + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.lock().expect("it should lock entry").is_not_zombie(policy)); + } +} diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs new file mode 100644 index 000000000..7ce2cc74c --- /dev/null +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -0,0 +1,124 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; + +use super::RepositoryAsync; +use crate::entry::{Entry, EntryAsync}; +use crate::{EntryMutexTokio, EntrySingle, TorrentsRwLockTokioMutexTokio}; + +impl TorrentsRwLockTokioMutexTokio { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl RepositoryAsync for TorrentsRwLockTokioMutexTokio +where + EntryMutexTokio: EntryAsync, + EntrySingle: Entry, +{ + async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut().await; + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.insert_or_update_peer_and_get_stats(peer).await + } + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexTokio)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> TorrentsMetrics { + let mut metrics = TorrentsMetrics::default(); + + for entry in self.get_torrents().await.values().cloned() { + let stats = entry.get_stats().await; + metrics.seeders += u64::from(stats.complete); + metrics.completed += u64::from(stats.downloaded); + metrics.leechers += u64::from(stats.incomplete); + metrics.torrents += 1; + } + + metrics + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut db = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if db.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexTokio::new( + EntrySingle { + peers: BTreeMap::default(), + completed: *completed, + } + .into(), + ); + + db.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let db = self.get_torrents().await; + let entries = db.values().cloned(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff).await; + } + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.blocking_lock().is_not_zombie(policy)); + } +} diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index 6647e0249..300813430 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -44,7 +44,7 @@ pub fn start_job(config: &Configuration, tracker: &Arc) -> JoinHa if let Some(tracker) = weak_tracker.upgrade() { let start_time = Utc::now().time(); info!("Cleaning up torrents.."); - tracker.cleanup_torrents().await; + tracker.cleanup_torrents(); info!("Cleaned up torrents in: {}ms", (Utc::now().time() - start_time).num_milliseconds()); } else { break; diff --git a/src/console/clients/checker/checks/http.rs b/src/console/clients/checker/checks/http.rs index df1e9bc9a..501696df4 100644 --- a/src/console/clients/checker/checks/http.rs +++ b/src/console/clients/checker/checks/http.rs @@ -3,12 +3,12 @@ use std::str::FromStr; use colored::Colorize; use log::debug; use reqwest::Url as ServiceUrl; +use torrust_tracker_primitives::info_hash::InfoHash; use url::Url; use crate::console::clients::checker::console::Console; use crate::console::clients::checker::printer::Printer; use crate::console::clients::checker::service::{CheckError, CheckResult}; -use crate::shared::bit_torrent::info_hash::InfoHash; use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; use crate::shared::bit_torrent::tracker::http::client::responses::scrape; diff --git a/src/console/clients/checker/checks/udp.rs b/src/console/clients/checker/checks/udp.rs index 890375b75..47a2a1a00 100644 --- a/src/console/clients/checker/checks/udp.rs +++ b/src/console/clients/checker/checks/udp.rs @@ -4,12 +4,12 @@ use aquatic_udp_protocol::{Port, TransactionId}; use colored::Colorize; use hex_literal::hex; use log::debug; +use torrust_tracker_primitives::info_hash::InfoHash; use crate::console::clients::checker::console::Console; use crate::console::clients::checker::printer::Printer; use crate::console::clients::checker::service::{CheckError, CheckResult}; use crate::console::clients::udp::checker; -use crate::shared::bit_torrent::info_hash::InfoHash; const ASSIGNED_BY_OS: u16 = 0; const RANDOM_TRANSACTION_ID: i32 = -888_840_697; diff --git a/src/console/clients/http/app.rs b/src/console/clients/http/app.rs index 80db07231..511fb6628 100644 --- a/src/console/clients/http/app.rs +++ b/src/console/clients/http/app.rs @@ -18,8 +18,8 @@ use std::str::FromStr; use anyhow::Context; use clap::{Parser, Subcommand}; use reqwest::Url; +use torrust_tracker_primitives::info_hash::InfoHash; -use crate::shared::bit_torrent::info_hash::InfoHash; use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; use crate::shared::bit_torrent::tracker::http::client::responses::scrape; diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index b9e31155d..540a25f30 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -64,11 +64,11 @@ use aquatic_udp_protocol::Response::{self, AnnounceIpv4, AnnounceIpv6, Scrape}; use aquatic_udp_protocol::{Port, TransactionId}; use clap::{Parser, Subcommand}; use log::{debug, LevelFilter}; +use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; use url::Url; use crate::console::clients::udp::checker; use crate::console::clients::udp::responses::{AnnounceResponseDto, ScrapeResponseDto}; -use crate::shared::bit_torrent::info_hash::InfoHash as TorrustInfoHash; const ASSIGNED_BY_OS: u16 = 0; const RANDOM_TRANSACTION_ID: i32 = -888_840_697; diff --git a/src/console/clients/udp/checker.rs b/src/console/clients/udp/checker.rs index b35139e49..12b8d764c 100644 --- a/src/console/clients/udp/checker.rs +++ b/src/console/clients/udp/checker.rs @@ -8,8 +8,8 @@ use aquatic_udp_protocol::{ }; use log::debug; use thiserror::Error; +use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; -use crate::shared::bit_torrent::info_hash::InfoHash as TorrustInfoHash; use crate::shared::bit_torrent::tracker::udp::client::{UdpClient, UdpTrackerClient}; #[derive(Error, Debug)] diff --git a/src/core/auth.rs b/src/core/auth.rs index 9fc9d6e7b..a7bb91aa4 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -13,7 +13,7 @@ //! //! ```rust,no_run //! use torrust_tracker::core::auth::Key; -//! use torrust_tracker::shared::clock::DurationSinceUnixEpoch; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; //! //! pub struct ExpiringKey { //! /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` @@ -48,9 +48,10 @@ use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; use thiserror::Error; use torrust_tracker_located_error::{DynError, LocatedError}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; -use crate::shared::clock::{convert_from_timestamp_to_datetime_utc, Current, DurationSinceUnixEpoch, Time, TimeNow}; +use crate::shared::clock::{convert_from_timestamp_to_datetime_utc, Current, Time, TimeNow}; #[must_use] /// It generates a new random 32-char authentication [`ExpiringKey`] diff --git a/src/core/databases/mod.rs b/src/core/databases/mod.rs index b3dcdd48e..b708ef4dc 100644 --- a/src/core/databases/mod.rs +++ b/src/core/databases/mod.rs @@ -22,7 +22,7 @@ //! ---|---|--- //! `id` | 1 | Autoincrement id //! `info_hash` | `c1277613db1d28709b034a017ab2cae4be07ae10` | `BitTorrent` infohash V1 -//! `completed` | 20 | The number of peers that have ever completed downloading the torrent associated to this entry. See [`Entry`](crate::core::torrent::Entry) for more information. +//! `completed` | 20 | The number of peers that have ever completed downloading the torrent associated to this entry. See [`Entry`](torrust_tracker_torrent_repository::entry::Entry) for more information. //! //! > **NOTICE**: The peer list for a torrent is not persisted. Since peer have to re-announce themselves on intervals, the data is be //! regenerated again after some minutes. @@ -51,12 +51,11 @@ pub mod sqlite; use std::marker::PhantomData; use async_trait::async_trait; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::PersistentTorrents; use self::error::Error; use crate::core::auth::{self, Key}; -use crate::shared::bit_torrent::info_hash::InfoHash; - -pub type PersistentTorrents = Vec<(InfoHash, u32)>; struct Builder where @@ -118,9 +117,9 @@ pub trait Database: Sync + Send { /// /// It returns an array of tuples with the torrent /// [`InfoHash`] and the - /// [`completed`](crate::core::torrent::Entry::completed) counter + /// [`completed`](torrust_tracker_torrent_repository::entry::Entry::completed) counter /// which is the number of times the torrent has been downloaded. - /// See [`Entry::completed`](crate::core::torrent::Entry::completed). + /// See [`Entry::completed`](torrust_tracker_torrent_repository::entry::Entry::completed). /// /// # Context: Torrent Metrics /// diff --git a/src/core/databases/mysql.rs b/src/core/databases/mysql.rs index c46300829..e37cdd9bf 100644 --- a/src/core/databases/mysql.rs +++ b/src/core/databases/mysql.rs @@ -8,12 +8,12 @@ use r2d2::Pool; use r2d2_mysql::mysql::prelude::Queryable; use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MySqlConnectionManager; +use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::DatabaseDriver; use super::{Database, Error}; use crate::core::auth::{self, Key}; use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; -use crate::shared::bit_torrent::info_hash::InfoHash; const DRIVER: DatabaseDriver = DatabaseDriver::MySQL; diff --git a/src/core/databases/sqlite.rs b/src/core/databases/sqlite.rs index bf2d6b8b9..5a3ac144a 100644 --- a/src/core/databases/sqlite.rs +++ b/src/core/databases/sqlite.rs @@ -5,12 +5,11 @@ use std::str::FromStr; use async_trait::async_trait; use r2d2::Pool; use r2d2_sqlite::SqliteConnectionManager; -use torrust_tracker_primitives::DatabaseDriver; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::{DatabaseDriver, DurationSinceUnixEpoch}; use super::{Database, Error}; use crate::core::auth::{self, Key}; -use crate::shared::bit_torrent::info_hash::InfoHash; -use crate::shared::clock::DurationSinceUnixEpoch; const DRIVER: DatabaseDriver = DatabaseDriver::Sqlite3; diff --git a/src/core/error.rs b/src/core/error.rs index f1e622673..a826de349 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -9,6 +9,7 @@ use std::panic::Location; use torrust_tracker_located_error::LocatedError; +use torrust_tracker_primitives::info_hash::InfoHash; /// Authentication or authorization error returned by the core `Tracker` #[derive(thiserror::Error, Debug, Clone)] @@ -25,7 +26,7 @@ pub enum Error { // Authorization errors #[error("The torrent: {info_hash}, is not whitelisted, {location}")] TorrentNotWhitelisted { - info_hash: crate::shared::bit_torrent::info_hash::InfoHash, + info_hash: InfoHash, location: &'static Location<'static>, }, } diff --git a/src/core/mod.rs b/src/core/mod.rs index 15d7b9c39..f94c46543 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -52,13 +52,13 @@ //! The tracker responds to the peer with the list of other peers in the swarm so that //! the peer can contact them to start downloading pieces of the file from them. //! -//! Once you have instantiated the `Tracker` you can `announce` a new [`Peer`] with: +//! Once you have instantiated the `Tracker` you can `announce` a new [`peer::Peer`] with: //! //! ```rust,no_run -//! use torrust_tracker::core::peer; -//! use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -//! use torrust_tracker::shared::clock::DurationSinceUnixEpoch; -//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +//! use torrust_tracker_primitives::peer; +//! use torrust_tracker_primitives::info_hash::InfoHash; +//! use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfBytes}; +//! use torrust_tracker_primitives::announce_event::AnnounceEvent; //! use std::net::SocketAddr; //! use std::net::IpAddr; //! use std::net::Ipv4Addr; @@ -97,11 +97,11 @@ //! The returned struct is: //! //! ```rust,no_run -//! use torrust_tracker::core::peer::Peer; +//! use torrust_tracker_primitives::peer; //! use torrust_tracker_configuration::AnnouncePolicy; //! //! pub struct AnnounceData { -//! pub peers: Vec, +//! pub peers: Vec, //! pub swarm_stats: SwarmMetadata, //! pub policy: AnnouncePolicy, // the tracker announce policy. //! } @@ -136,7 +136,7 @@ //! The returned struct is: //! //! ```rust,no_run -//! use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +//! use torrust_tracker_primitives::info_hash::InfoHash; //! use std::collections::HashMap; //! //! pub struct ScrapeData { @@ -165,7 +165,7 @@ //! There are two data structures for infohashes: byte arrays and hex strings: //! //! ```rust,no_run -//! use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +//! use torrust_tracker_primitives::info_hash::InfoHash; //! use std::str::FromStr; //! //! let info_hash: InfoHash = [255u8; 20].into(); @@ -246,14 +246,14 @@ //! A `Peer` is the struct used by the `Tracker` to keep peers data: //! //! ```rust,no_run -//! use torrust_tracker::core::peer::Id; +//! use torrust_tracker_primitives::peer; //! use std::net::SocketAddr; -//! use torrust_tracker::shared::clock::DurationSinceUnixEpoch; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; //! use aquatic_udp_protocol::NumberOfBytes; //! use aquatic_udp_protocol::AnnounceEvent; //! //! pub struct Peer { -//! pub peer_id: Id, // The peer ID +//! pub peer_id: peer::Id, // The peer ID //! pub peer_addr: SocketAddr, // Peer socket address //! pub updated: DurationSinceUnixEpoch, // Last time (timestamp) when the peer was updated //! pub uploaded: NumberOfBytes, // Number of bytes the peer has uploaded so far @@ -429,11 +429,12 @@ pub mod auth; pub mod databases; pub mod error; -pub mod peer; pub mod services; pub mod statistics; pub mod torrent; +pub mod peer_tests; + use std::collections::HashMap; use std::net::IpAddr; use std::panic::Location; @@ -443,18 +444,19 @@ use std::time::Duration; use derive_more::Constructor; use log::debug; use tokio::sync::mpsc::error::SendError; -use torrust_tracker_configuration::{AnnouncePolicy, Configuration}; -use torrust_tracker_primitives::TrackerMode; +use torrust_tracker_configuration::{AnnouncePolicy, Configuration, TrackerPolicy}; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, TrackerMode}; +use torrust_tracker_torrent_repository::entry::EntrySync; +use torrust_tracker_torrent_repository::repository::Repository; use self::auth::Key; use self::error::Error; -use self::peer::Peer; -use self::torrent::entry::{ReadInfo, ReadPeers}; -use self::torrent::repository::{Repository, UpdateTorrentSync}; use self::torrent::Torrents; use crate::core::databases::Database; -use crate::core::torrent::SwarmMetadata; -use crate::shared::bit_torrent::info_hash::InfoHash; +use crate::shared::clock::{self, TimeNow}; /// The maximum number of returned peers for a torrent. pub const TORRENT_PEERS_LIMIT: usize = 74; @@ -484,33 +486,12 @@ pub struct Tracker { on_reverse_proxy: bool, } -/// Structure that holds general `Tracker` torrents metrics. -/// -/// Metrics are aggregate values for all torrents. -#[derive(Copy, Clone, Debug, PartialEq, Default)] -pub struct TorrentsMetrics { - /// Total number of seeders for all torrents - pub seeders: u64, - /// Total number of peers that have ever completed downloading for all torrents. - pub completed: u64, - /// Total number of leechers for all torrents. - pub leechers: u64, - /// Total number of torrents. - pub torrents: u64, -} - -#[derive(Copy, Clone, Debug, PartialEq, Default, Constructor)] -pub struct TrackerPolicy { - pub remove_peerless_torrents: bool, - pub max_peer_timeout: u32, - pub persistent_torrent_completed_stat: bool, -} /// Structure that holds the data returned by the `announce` request. #[derive(Clone, Debug, PartialEq, Constructor, Default)] pub struct AnnounceData { /// The list of peers that are downloading the same torrent. /// It excludes the peer that made the request. - pub peers: Vec>, + pub peers: Vec>, /// Swarm statistics pub stats: SwarmMetadata, pub policy: AnnouncePolicy, @@ -627,7 +608,7 @@ impl Tracker { /// # Context: Tracker /// /// BEP 03: [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html). - pub async fn announce(&self, info_hash: &InfoHash, peer: &mut Peer, remote_client_ip: &IpAddr) -> AnnounceData { + pub async fn announce(&self, info_hash: &InfoHash, peer: &mut peer::Peer, remote_client_ip: &IpAddr) -> AnnounceData { // code-review: maybe instead of mutating the peer we could just return // a tuple with the new peer and the announce data: (Peer, AnnounceData). // It could even be a different struct: `StoredPeer` or `PublicPeer`. @@ -650,7 +631,7 @@ impl Tracker { // we should update the torrent and get the stats before we get the peer list. let stats = self.update_torrent_with_peer_and_get_stats(info_hash, peer).await; - let peers = self.get_torrent_peers_for_peer(info_hash, peer).await; + let peers = self.get_torrent_peers_for_peer(info_hash, peer); AnnounceData { peers, @@ -669,7 +650,7 @@ impl Tracker { for info_hash in info_hashes { let swarm_metadata = match self.authorize(info_hash).await { - Ok(()) => self.get_swarm_metadata(info_hash).await, + Ok(()) => self.get_swarm_metadata(info_hash), Err(_) => SwarmMetadata::zeroed(), }; scrape_data.add_file(info_hash, swarm_metadata); @@ -679,8 +660,8 @@ impl Tracker { } /// It returns the data for a `scrape` response. - async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { - match self.torrents.get(info_hash).await { + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { + match self.torrents.get(info_hash) { Some(torrent_entry) => torrent_entry.get_stats(), None => SwarmMetadata::default(), } @@ -697,13 +678,13 @@ impl Tracker { pub async fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { let persistent_torrents = self.database.load_persistent_torrents().await?; - self.torrents.import_persistent(&persistent_torrents).await; + self.torrents.import_persistent(&persistent_torrents); Ok(()) } - async fn get_torrent_peers_for_peer(&self, info_hash: &InfoHash, peer: &Peer) -> Vec> { - match self.torrents.get(info_hash).await { + fn get_torrent_peers_for_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> Vec> { + match self.torrents.get(info_hash) { None => vec![], Some(entry) => entry.get_peers_for_peer(peer, Some(TORRENT_PEERS_LIMIT)), } @@ -712,8 +693,8 @@ impl Tracker { /// # Context: Tracker /// /// Get all torrent peers for a given torrent - pub async fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { - match self.torrents.get(info_hash).await { + pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { + match self.torrents.get(info_hash) { None => vec![], Some(entry) => entry.get_peers(Some(TORRENT_PEERS_LIMIT)), } @@ -724,11 +705,7 @@ impl Tracker { /// needed for a `announce` request response. /// /// # Context: Tracker - pub async fn update_torrent_with_peer_and_get_stats( - &self, - info_hash: &InfoHash, - peer: &peer::Peer, - ) -> torrent::SwarmMetadata { + pub async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { // code-review: consider splitting the function in two (command and query segregation). // `update_torrent_with_peer` and `get_stats` @@ -751,19 +728,21 @@ impl Tracker { /// /// # Panics /// Panics if unable to get the torrent metrics. - pub async fn get_torrents_metrics(&self) -> TorrentsMetrics { - self.torrents.get_metrics().await + pub fn get_torrents_metrics(&self) -> TorrentsMetrics { + self.torrents.get_metrics() } /// Remove inactive peers and (optionally) peerless torrents /// /// # Context: Tracker - pub async fn cleanup_torrents(&self) { + pub fn cleanup_torrents(&self) { // If we don't need to remove torrents we will use the faster iter if self.policy.remove_peerless_torrents { - self.torrents.remove_peerless_torrents(&self.policy).await; + self.torrents.remove_peerless_torrents(&self.policy); } else { - self.torrents.remove_inactive_peers(self.policy.max_peer_timeout).await; + let current_cutoff = + clock::Current::sub(&Duration::from_secs(u64::from(self.policy.max_peer_timeout))).unwrap_or_default(); + self.torrents.remove_inactive_peers(current_cutoff); } } @@ -1017,14 +996,15 @@ mod tests { use std::str::FromStr; use std::sync::Arc; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_primitives::announce_event::AnnounceEvent; + use torrust_tracker_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; use crate::core::peer::{self, Peer}; use crate::core::services::tracker_factory; use crate::core::{TorrentsMetrics, Tracker}; - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::shared::clock::DurationSinceUnixEpoch; + use crate::shared::bit_torrent::info_hash::fixture::gen_seeded_infohash; fn public_tracker() -> Tracker { tracker_factory(&configuration::ephemeral_mode_public()) @@ -1132,7 +1112,7 @@ mod tests { async fn should_collect_torrent_metrics() { let tracker = public_tracker(); - let torrents_metrics = tracker.get_torrents_metrics().await; + let torrents_metrics = tracker.get_torrents_metrics(); assert_eq!( torrents_metrics, @@ -1154,7 +1134,7 @@ mod tests { tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; - let peers = tracker.get_torrent_peers(&info_hash).await; + let peers = tracker.get_torrent_peers(&info_hash); assert_eq!(peers, vec![Arc::new(peer)]); } @@ -1168,7 +1148,7 @@ mod tests { tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; - let peers = tracker.get_torrent_peers_for_peer(&info_hash, &peer).await; + let peers = tracker.get_torrent_peers_for_peer(&info_hash, &peer); assert_eq!(peers, vec![]); } @@ -1181,7 +1161,7 @@ mod tests { .update_torrent_with_peer_and_get_stats(&sample_info_hash(), &leecher()) .await; - let torrent_metrics = tracker.get_torrents_metrics().await; + let torrent_metrics = tracker.get_torrents_metrics(); assert_eq!( torrent_metrics, @@ -1194,6 +1174,34 @@ mod tests { ); } + #[tokio::test] + async fn it_should_get_many_the_torrent_metrics() { + let tracker = public_tracker(); + + let start_time = std::time::Instant::now(); + for i in 0..1_000_000 { + tracker + .update_torrent_with_peer_and_get_stats(&gen_seeded_infohash(&i), &leecher()) + .await; + } + let result_a = start_time.elapsed(); + + let start_time = std::time::Instant::now(); + let torrent_metrics = tracker.get_torrents_metrics(); + let result_b = start_time.elapsed(); + + assert_eq!( + (torrent_metrics), + (TorrentsMetrics { + seeders: 0, + completed: 0, + leechers: 1_000_000, + torrents: 1_000_000, + }), + "{result_a:?} {result_b:?}" + ); + } + mod for_all_config_modes { mod handling_an_announce_request { @@ -1376,9 +1384,10 @@ mod tests { use std::net::{IpAddr, Ipv4Addr}; + use torrust_tracker_primitives::info_hash::InfoHash; + use crate::core::tests::the_tracker::{complete_peer, incomplete_peer, public_tracker}; use crate::core::{ScrapeData, SwarmMetadata}; - use crate::shared::bit_torrent::info_hash::InfoHash; #[tokio::test] async fn it_should_return_a_zeroed_swarm_metadata_for_the_requested_file_if_the_tracker_does_not_have_that_torrent( @@ -1533,12 +1542,13 @@ mod tests { mod handling_an_scrape_request { + use torrust_tracker_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use crate::core::tests::the_tracker::{ complete_peer, incomplete_peer, peer_ip, sample_info_hash, whitelisted_tracker, }; - use crate::core::torrent::SwarmMetadata; use crate::core::ScrapeData; - use crate::shared::bit_torrent::info_hash::InfoHash; #[test] fn it_should_be_able_to_build_a_zeroed_scrape_data_for_a_list_of_info_hashes() { @@ -1677,11 +1687,12 @@ mod tests { } mod handling_torrent_persistence { - use aquatic_udp_protocol::AnnounceEvent; + + use torrust_tracker_primitives::announce_event::AnnounceEvent; + use torrust_tracker_torrent_repository::entry::EntrySync; + use torrust_tracker_torrent_repository::repository::Repository; use crate::core::tests::the_tracker::{sample_info_hash, sample_peer, tracker_persisting_torrents_in_database}; - use crate::core::torrent::entry::ReadInfo; - use crate::core::torrent::repository::Repository; #[tokio::test] async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { @@ -1700,15 +1711,11 @@ mod tests { assert_eq!(swarm_stats.downloaded, 1); // Remove the newly updated torrent from memory - tracker.torrents.remove(&info_hash).await; + tracker.torrents.remove(&info_hash); tracker.load_torrents_from_database().await.unwrap(); - let torrent_entry = tracker - .torrents - .get(&info_hash) - .await - .expect("it should be able to get entry"); + let torrent_entry = tracker.torrents.get(&info_hash).expect("it should be able to get entry"); // It persists the number of completed peers. assert_eq!(torrent_entry.get_stats().downloaded, 1); diff --git a/src/core/peer_tests.rs b/src/core/peer_tests.rs new file mode 100644 index 000000000..9e5b4be01 --- /dev/null +++ b/src/core/peer_tests.rs @@ -0,0 +1,43 @@ +#![cfg(test)] + +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use torrust_tracker_primitives::announce_event::AnnounceEvent; +use torrust_tracker_primitives::{peer, NumberOfBytes}; + +use crate::shared::clock::{self, Time}; + +#[test] +fn it_should_be_serializable() { + let torrent_peer = peer::Peer { + peer_id: peer::Id(*b"-qB0000-000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: clock::Current::now(), + uploaded: NumberOfBytes(0), + downloaded: NumberOfBytes(0), + left: NumberOfBytes(0), + event: AnnounceEvent::Started, + }; + + let raw_json = serde_json::to_string(&torrent_peer).unwrap(); + + let expected_raw_json = r#" + { + "peer_id": { + "id": "0x2d7142303030302d303030303030303030303030", + "client": "qBittorrent" + }, + "peer_addr":"126.0.0.1:8080", + "updated":0, + "uploaded":0, + "downloaded":0, + "left":0, + "event":"Started" + } + "#; + + assert_eq!( + serde_json::from_str::(&raw_json).unwrap(), + serde_json::from_str::(expected_raw_json).unwrap() + ); +} diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 3578c53aa..ee1c0c4fa 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -40,8 +40,10 @@ pub mod setup; use std::sync::Arc; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use crate::core::statistics::Metrics; -use crate::core::{TorrentsMetrics, Tracker}; +use crate::core::Tracker; /// All the metrics collected by the tracker. #[derive(Debug, PartialEq)] @@ -59,7 +61,7 @@ pub struct TrackerMetrics { /// It returns all the [`TrackerMetrics`] pub async fn get_metrics(tracker: Arc) -> TrackerMetrics { - let torrents_metrics = tracker.get_torrents_metrics().await; + let torrents_metrics = tracker.get_torrents_metrics(); let stats = tracker.get_stats().await; TrackerMetrics { @@ -86,6 +88,7 @@ mod tests { use std::sync::Arc; use torrust_tracker_configuration::Configuration; + use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; use crate::core; @@ -105,7 +108,7 @@ mod tests { assert_eq!( tracker_metrics, TrackerMetrics { - torrents_metrics: core::TorrentsMetrics::default(), + torrents_metrics: TorrentsMetrics::default(), protocol_metrics: core::statistics::Metrics::default(), } ); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 78dab12c4..ce44af3a8 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -6,13 +6,13 @@ //! - [`get_torrents`]: it returns data about some torrent in bulk excluding the peer list. use std::sync::Arc; -use serde::Deserialize; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::peer; +use torrust_tracker_torrent_repository::entry::EntrySync; +use torrust_tracker_torrent_repository::repository::Repository; -use crate::core::peer::Peer; -use crate::core::torrent::entry::{ReadInfo, ReadPeers}; -use crate::core::torrent::repository::Repository; use crate::core::Tracker; -use crate::shared::bit_torrent::info_hash::InfoHash; /// It contains all the information the tracker has about a torrent #[derive(Debug, PartialEq)] @@ -26,7 +26,7 @@ pub struct Info { /// The total number of leechers for this torrent. Peers that actively downloading this torrent pub leechers: u64, /// The swarm: the list of peers that are actively trying to download or serving this torrent - pub peers: Option>, + pub peers: Option>, } /// It contains only part of the information the tracker has about a torrent @@ -44,58 +44,9 @@ pub struct BasicInfo { pub leechers: u64, } -/// A struct to keep information about the page when results are being paginated -#[derive(Deserialize)] -pub struct Pagination { - /// The page number, starting at 0 - pub offset: u32, - /// Page size. The number of results per page - pub limit: u32, -} - -impl Pagination { - #[must_use] - pub fn new(offset: u32, limit: u32) -> Self { - Self { offset, limit } - } - - #[must_use] - pub fn new_with_options(offset_option: Option, limit_option: Option) -> Self { - let offset = match offset_option { - Some(offset) => offset, - None => Pagination::default_offset(), - }; - let limit = match limit_option { - Some(offset) => offset, - None => Pagination::default_limit(), - }; - - Self { offset, limit } - } - - #[must_use] - pub fn default_offset() -> u32 { - 0 - } - - #[must_use] - pub fn default_limit() -> u32 { - 4000 - } -} - -impl Default for Pagination { - fn default() -> Self { - Self { - offset: Self::default_offset(), - limit: Self::default_limit(), - } - } -} - /// It returns all the information the tracker has about one torrent in a [Info] struct. pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Option { - let torrent_entry_option = tracker.torrents.get(info_hash).await; + let torrent_entry_option = tracker.torrents.get(info_hash); let torrent_entry = torrent_entry_option?; @@ -118,7 +69,7 @@ pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Op pub async fn get_torrents_page(tracker: Arc, pagination: Option<&Pagination>) -> Vec { let mut basic_infos: Vec = vec![]; - for (info_hash, torrent_entry) in tracker.torrents.get_paginated(pagination).await { + for (info_hash, torrent_entry) in tracker.torrents.get_paginated(pagination) { let stats = torrent_entry.get_stats(); basic_infos.push(BasicInfo { @@ -137,7 +88,7 @@ pub async fn get_torrents(tracker: Arc, info_hashes: &[InfoHash]) -> Ve let mut basic_infos: Vec = vec![]; for info_hash in info_hashes { - if let Some(stats) = tracker.torrents.get(info_hash).await.map(|t| t.get_stats()) { + if let Some(stats) = tracker.torrents.get(info_hash).map(|t| t.get_stats()) { basic_infos.push(BasicInfo { info_hash: *info_hash, seeders: u64::from(stats.complete), @@ -154,10 +105,8 @@ pub async fn get_torrents(tracker: Arc, info_hashes: &[InfoHash]) -> Ve mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - - use crate::core::peer; - use crate::shared::clock::DurationSinceUnixEpoch; + use torrust_tracker_primitives::announce_event::AnnounceEvent; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; fn sample_peer() -> peer::Peer { peer::Peer { @@ -177,12 +126,12 @@ mod tests { use std::sync::Arc; use torrust_tracker_configuration::Configuration; + use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::core::services::torrent::tests::sample_peer; use crate::core::services::torrent::{get_torrent_info, Info}; use crate::core::services::tracker_factory; - use crate::shared::bit_torrent::info_hash::InfoHash; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -232,12 +181,12 @@ mod tests { use std::sync::Arc; use torrust_tracker_configuration::Configuration; + use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::core::services::torrent::tests::sample_peer; use crate::core::services::torrent::{get_torrents_page, BasicInfo, Pagination}; use crate::core::services::tracker_factory; - use crate::shared::bit_torrent::info_hash::InfoHash; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() diff --git a/src/core/torrent/entry.rs b/src/core/torrent/entry.rs deleted file mode 100644 index 815abd4fb..000000000 --- a/src/core/torrent/entry.rs +++ /dev/null @@ -1,287 +0,0 @@ -use std::fmt::Debug; -use std::sync::Arc; -use std::time::Duration; - -use aquatic_udp_protocol::AnnounceEvent; -use serde::{Deserialize, Serialize}; - -use super::SwarmMetadata; -use crate::core::peer::{self, ReadInfo as _}; -use crate::core::TrackerPolicy; -use crate::shared::clock::{Current, TimeNow}; - -/// A data structure containing all the information about a torrent in the tracker. -/// -/// This is the tracker entry for a given torrent and contains the swarm data, -/// that's the list of all the peers trying to download the same torrent. -/// The tracker keeps one entry like this for every torrent. -#[derive(Serialize, Deserialize, Clone, Debug, Default)] -pub struct Entry { - /// The swarm: a network of peers that are all trying to download the torrent associated to this entry - #[serde(skip)] - pub(crate) peers: std::collections::BTreeMap>, - /// The number of peers that have ever completed downloading the torrent associated to this entry - pub(crate) completed: u32, -} -pub type Single = Entry; -pub type MutexStd = Arc>; -pub type MutexTokio = Arc>; - -pub trait ReadInfo { - /// It returns the swarm metadata (statistics) as a struct: - /// - /// `(seeders, completed, leechers)` - fn get_stats(&self) -> SwarmMetadata; - - /// Returns True if Still a Valid Entry according to the Tracker Policy - fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool; - - /// Returns True if the Peers is Empty - fn peers_is_empty(&self) -> bool; -} - -/// Same as [`ReadInfo`], but async. -pub trait ReadInfoAsync { - /// It returns the swarm metadata (statistics) as a struct: - /// - /// `(seeders, completed, leechers)` - fn get_stats(&self) -> impl std::future::Future + Send; - - /// Returns True if Still a Valid Entry according to the Tracker Policy - fn is_not_zombie(&self, policy: &TrackerPolicy) -> impl std::future::Future + Send; - - /// Returns True if the Peers is Empty - fn peers_is_empty(&self) -> impl std::future::Future + Send; -} - -pub trait ReadPeers { - /// Get all swarm peers, optionally limiting the result. - fn get_peers(&self, limit: Option) -> Vec>; - - /// It returns the list of peers for a given peer client, optionally limiting the - /// result. - /// - /// It filters out the input peer, typically because we want to return this - /// list of peers to that client peer. - fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec>; -} - -/// Same as [`ReadPeers`], but async. -pub trait ReadPeersAsync { - fn get_peers(&self, limit: Option) -> impl std::future::Future>> + Send; - - fn get_peers_for_peer( - &self, - client: &peer::Peer, - limit: Option, - ) -> impl std::future::Future>> + Send; -} - -pub trait Update { - /// It updates a peer and returns true if the number of complete downloads have increased. - /// - /// The number of peers that have complete downloading is synchronously updated when peers are updated. - /// That's the total torrent downloads counter. - fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool; - - // It preforms a combined operation of `insert_or_update_peer` and `get_stats`. - fn insert_or_update_peer_and_get_stats(&mut self, peer: &peer::Peer) -> (bool, SwarmMetadata); - - /// It removes peer from the swarm that have not been updated for more than `max_peer_timeout` seconds - fn remove_inactive_peers(&mut self, max_peer_timeout: u32); -} - -/// Same as [`Update`], except not `mut`. -pub trait UpdateSync { - fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool; - fn insert_or_update_peer_and_get_stats(&self, peer: &peer::Peer) -> (bool, SwarmMetadata); - fn remove_inactive_peers(&self, max_peer_timeout: u32); -} - -/// Same as [`Update`], except not `mut` and async. -pub trait UpdateAsync { - fn insert_or_update_peer(&self, peer: &peer::Peer) -> impl std::future::Future + Send; - - fn insert_or_update_peer_and_get_stats( - &self, - peer: &peer::Peer, - ) -> impl std::future::Future + std::marker::Send; - - fn remove_inactive_peers(&self, max_peer_timeout: u32) -> impl std::future::Future + Send; -} - -impl ReadInfo for Single { - #[allow(clippy::cast_possible_truncation)] - fn get_stats(&self) -> SwarmMetadata { - let complete: u32 = self.peers.values().filter(|peer| peer.is_seeder()).count() as u32; - let incomplete: u32 = self.peers.len() as u32 - complete; - - SwarmMetadata { - downloaded: self.completed, - complete, - incomplete, - } - } - - fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool { - if policy.persistent_torrent_completed_stat && self.completed > 0 { - return true; - } - - if policy.remove_peerless_torrents && self.peers.is_empty() { - return false; - } - - true - } - - fn peers_is_empty(&self) -> bool { - self.peers.is_empty() - } -} - -impl ReadInfo for MutexStd { - fn get_stats(&self) -> SwarmMetadata { - self.lock().expect("it should get a lock").get_stats() - } - - fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool { - self.lock().expect("it should get a lock").is_not_zombie(policy) - } - - fn peers_is_empty(&self) -> bool { - self.lock().expect("it should get a lock").peers_is_empty() - } -} - -impl ReadInfoAsync for MutexTokio { - async fn get_stats(&self) -> SwarmMetadata { - self.lock().await.get_stats() - } - - async fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool { - self.lock().await.is_not_zombie(policy) - } - - async fn peers_is_empty(&self) -> bool { - self.lock().await.peers_is_empty() - } -} - -impl ReadPeers for Single { - fn get_peers(&self, limit: Option) -> Vec> { - match limit { - Some(limit) => self.peers.values().take(limit).cloned().collect(), - None => self.peers.values().cloned().collect(), - } - } - - fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec> { - match limit { - Some(limit) => self - .peers - .values() - // Take peers which are not the client peer - .filter(|peer| peer.get_address() != client.get_address()) - // Limit the number of peers on the result - .take(limit) - .cloned() - .collect(), - None => self - .peers - .values() - // Take peers which are not the client peer - .filter(|peer| peer.get_address() != client.get_address()) - .cloned() - .collect(), - } - } -} - -impl ReadPeers for MutexStd { - fn get_peers(&self, limit: Option) -> Vec> { - self.lock().expect("it should get lock").get_peers(limit) - } - - fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec> { - self.lock().expect("it should get lock").get_peers_for_peer(client, limit) - } -} - -impl ReadPeersAsync for MutexTokio { - async fn get_peers(&self, limit: Option) -> Vec> { - self.lock().await.get_peers(limit) - } - - async fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec> { - self.lock().await.get_peers_for_peer(client, limit) - } -} - -impl Update for Single { - fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool { - let mut did_torrent_stats_change: bool = false; - - match peer.get_event() { - AnnounceEvent::Stopped => { - drop(self.peers.remove(&peer.get_id())); - } - AnnounceEvent::Completed => { - let peer_old = self.peers.insert(peer.get_id(), Arc::new(*peer)); - // Don't count if peer was not previously known and not already completed. - if peer_old.is_some_and(|p| p.event != AnnounceEvent::Completed) { - self.completed += 1; - did_torrent_stats_change = true; - } - } - _ => { - drop(self.peers.insert(peer.get_id(), Arc::new(*peer))); - } - } - - did_torrent_stats_change - } - - fn insert_or_update_peer_and_get_stats(&mut self, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let changed = self.insert_or_update_peer(peer); - let stats = self.get_stats(); - (changed, stats) - } - - fn remove_inactive_peers(&mut self, max_peer_timeout: u32) { - let current_cutoff = Current::sub(&Duration::from_secs(u64::from(max_peer_timeout))).unwrap_or_default(); - self.peers.retain(|_, peer| peer.get_updated() > current_cutoff); - } -} - -impl UpdateSync for MutexStd { - fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool { - self.lock().expect("it should lock the entry").insert_or_update_peer(peer) - } - - fn insert_or_update_peer_and_get_stats(&self, peer: &peer::Peer) -> (bool, SwarmMetadata) { - self.lock() - .expect("it should lock the entry") - .insert_or_update_peer_and_get_stats(peer) - } - - fn remove_inactive_peers(&self, max_peer_timeout: u32) { - self.lock() - .expect("it should lock the entry") - .remove_inactive_peers(max_peer_timeout); - } -} - -impl UpdateAsync for MutexTokio { - async fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool { - self.lock().await.insert_or_update_peer(peer) - } - - async fn insert_or_update_peer_and_get_stats(&self, peer: &peer::Peer) -> (bool, SwarmMetadata) { - self.lock().await.insert_or_update_peer_and_get_stats(peer) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - self.lock().await.remove_inactive_peers(max_peer_timeout); - } -} diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index bfe068337..b5a2b4c07 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -2,8 +2,8 @@ //! //! There are to main data structures: //! -//! - A torrent [`Entry`]: it contains all the information stored by the tracker for one torrent. -//! - The [`SwarmMetadata`]: it contains aggregate information that can me derived from the torrent entries. +//! - A torrent [`Entry`](torrust_tracker_torrent_repository::entry::Entry): it contains all the information stored by the tracker for one torrent. +//! - The [`SwarmMetadata`](torrust_tracker_primitives::swarm_metadata::SwarmMetadata): it contains aggregate information that can me derived from the torrent entries. //! //! A "swarm" is a network of peers that are trying to download the same torrent. //! @@ -25,42 +25,11 @@ //! - The number of peers that have NOT completed downloading the torrent and are still active, that means they are actively participating in the network. //! Peer that don not have a full copy of the torrent data are called "leechers". //! -//! > **NOTICE**: that both [`SwarmMetadata`] and [`SwarmMetadata`] contain the same information. [`SwarmMetadata`] is using the names used on [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). -pub mod entry; -pub mod repository; -use derive_more::Constructor; +use torrust_tracker_torrent_repository::TorrentsRwLockStdMutexStd; pub type Torrents = TorrentsRwLockStdMutexStd; // Currently Used -pub type TorrentsRwLockStd = repository::RwLockStd; -pub type TorrentsRwLockStdMutexStd = repository::RwLockStd; -pub type TorrentsRwLockStdMutexTokio = repository::RwLockStd; -pub type TorrentsRwLockTokio = repository::RwLockTokio; -pub type TorrentsRwLockTokioMutexStd = repository::RwLockTokio; -pub type TorrentsRwLockTokioMutexTokio = repository::RwLockTokio; - -/// Swarm statistics for one torrent. -/// Swarm metadata dictionary in the scrape response. -/// -/// See [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) -#[derive(Copy, Clone, Debug, PartialEq, Default, Constructor)] -pub struct SwarmMetadata { - /// (i.e `completed`): The number of peers that have ever completed downloading - pub downloaded: u32, // - /// (i.e `seeders`): The number of active peers that have completed downloading (seeders) - pub complete: u32, //seeders - /// (i.e `leechers`): The number of active peers that have not completed downloading (leechers) - pub incomplete: u32, -} - -impl SwarmMetadata { - #[must_use] - pub fn zeroed() -> Self { - Self::default() - } -} - #[cfg(test)] mod tests { @@ -71,11 +40,13 @@ mod tests { use std::sync::Arc; use std::time::Duration; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_primitives::announce_event::AnnounceEvent; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; + use torrust_tracker_torrent_repository::entry::Entry; + use torrust_tracker_torrent_repository::EntrySingle; - use crate::core::torrent::entry::{self, ReadInfo, ReadPeers, Update}; - use crate::core::{peer, TORRENT_PEERS_LIMIT}; - use crate::shared::clock::{Current, DurationSinceUnixEpoch, Stopped, StoppedTime, Time, Working}; + use crate::core::TORRENT_PEERS_LIMIT; + use crate::shared::clock::{self, StoppedTime, Time, TimeNow}; struct TorrentPeerBuilder { peer: peer::Peer, @@ -86,7 +57,7 @@ mod tests { let default_peer = peer::Peer { peer_id: peer::Id([0u8; 20]), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), - updated: Current::now(), + updated: clock::Current::now(), uploaded: NumberOfBytes(0), downloaded: NumberOfBytes(0), left: NumberOfBytes(0), @@ -145,14 +116,14 @@ mod tests { #[test] fn the_default_torrent_entry_should_contain_an_empty_list_of_peers() { - let torrent_entry = entry::Single::default(); + let torrent_entry = EntrySingle::default(); assert_eq!(torrent_entry.get_peers(None).len(), 0); } #[test] fn a_new_peer_can_be_added_to_a_torrent_entry() { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -163,7 +134,7 @@ mod tests { #[test] fn a_torrent_entry_should_contain_the_list_of_peers_that_were_added_to_the_torrent() { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -173,7 +144,7 @@ mod tests { #[test] fn a_peer_can_be_updated_in_a_torrent_entry() { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let mut torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -185,7 +156,7 @@ mod tests { #[test] fn a_peer_should_be_removed_from_a_torrent_entry_when_the_peer_announces_it_has_stopped() { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let mut torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -197,7 +168,7 @@ mod tests { #[test] fn torrent_stats_change_when_a_previously_known_peer_announces_it_has_completed_the_torrent() { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let mut torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -211,7 +182,7 @@ mod tests { #[test] fn torrent_stats_should_not_change_when_a_peer_announces_it_has_completed_the_torrent_if_it_is_the_first_announce_from_the_peer( ) { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); // Add a peer that did not exist before in the entry @@ -223,7 +194,7 @@ mod tests { #[test] fn a_torrent_entry_should_return_the_list_of_peers_for_a_given_peer_filtering_out_the_client_that_is_making_the_request() { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let peer_socket_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); let torrent_peer = TorrentPeerBuilder::default().with_peer_address(peer_socket_address).into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add peer @@ -236,7 +207,7 @@ mod tests { #[test] fn two_peers_with_the_same_ip_but_different_port_should_be_considered_different_peers() { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let peer_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); @@ -270,7 +241,7 @@ mod tests { #[test] fn the_tracker_should_limit_the_list_of_peers_to_74_when_clients_scrape_torrents() { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); // We add one more peer than the scrape limit for peer_number in 1..=74 + 1 { @@ -287,7 +258,7 @@ mod tests { #[test] fn torrent_stats_should_have_the_number_of_seeders_for_a_torrent() { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let torrent_seeder = a_torrent_seeder(); torrent_entry.insert_or_update_peer(&torrent_seeder); // Add seeder @@ -297,7 +268,7 @@ mod tests { #[test] fn torrent_stats_should_have_the_number_of_leechers_for_a_torrent() { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let torrent_leecher = a_torrent_leecher(); torrent_entry.insert_or_update_peer(&torrent_leecher); // Add leecher @@ -308,7 +279,7 @@ mod tests { #[test] fn torrent_stats_should_have_the_number_of_peers_that_having_announced_at_least_two_events_the_latest_one_is_the_completed_event( ) { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let mut torrent_peer = TorrentPeerBuilder::default().into(); torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer @@ -323,7 +294,7 @@ mod tests { #[test] fn torrent_stats_should_not_include_a_peer_in_the_completed_counter_if_the_peer_has_announced_only_one_event() { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); // Announce "Completed" torrent download event. @@ -337,12 +308,12 @@ mod tests { #[test] fn a_torrent_entry_should_remove_a_peer_not_updated_after_a_timeout_in_seconds() { - let mut torrent_entry = entry::Single::default(); + let mut torrent_entry = EntrySingle::default(); let timeout = 120u32; - let now = Working::now(); - Stopped::local_set(&now); + let now = clock::Working::now(); + clock::Stopped::local_set(&now); let timeout_seconds_before_now = now.sub(Duration::from_secs(u64::from(timeout))); let inactive_peer = TorrentPeerBuilder::default() @@ -350,9 +321,10 @@ mod tests { .into(); torrent_entry.insert_or_update_peer(&inactive_peer); // Add the peer - torrent_entry.remove_inactive_peers(timeout); + let current_cutoff = clock::Current::sub(&Duration::from_secs(u64::from(timeout))).unwrap_or_default(); + torrent_entry.remove_inactive_peers(current_cutoff); - assert_eq!(torrent_entry.peers.len(), 0); + assert_eq!(torrent_entry.get_peers_len(), 0); } } } diff --git a/src/core/torrent/repository/rw_lock_std.rs b/src/core/torrent/repository/rw_lock_std.rs deleted file mode 100644 index 9b3915bcb..000000000 --- a/src/core/torrent/repository/rw_lock_std.rs +++ /dev/null @@ -1,122 +0,0 @@ -use std::collections::BTreeMap; -use std::sync::Arc; - -use futures::future::join_all; - -use super::{Repository, UpdateTorrentSync}; -use crate::core::databases::PersistentTorrents; -use crate::core::services::torrent::Pagination; -use crate::core::torrent::entry::{self, ReadInfo, Update}; -use crate::core::torrent::{SwarmMetadata, TorrentsRwLockStd}; -use crate::core::{peer, TorrentsMetrics}; -use crate::shared::bit_torrent::info_hash::InfoHash; - -impl TorrentsRwLockStd { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().expect("it should get the read lock") - } - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().expect("it should get the write lock") - } -} - -impl UpdateTorrentSync for TorrentsRwLockStd { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let mut db = self.get_torrents_mut(); - - let entry = db.entry(*info_hash).or_insert(entry::Single::default()); - - entry.insert_or_update_peer_and_get_stats(peer) - } -} - -impl UpdateTorrentSync for Arc { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - self.as_ref().update_torrent_with_peer_and_get_stats(info_hash, peer) - } -} - -impl Repository for TorrentsRwLockStd { - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents(); - db.get(key).cloned() - } - - async fn get_metrics(&self) -> TorrentsMetrics { - let metrics: Arc> = Arc::default(); - - let mut handles = Vec::>::default(); - - for e in self.get_torrents().values() { - let entry = e.clone(); - let metrics = metrics.clone(); - handles.push(tokio::task::spawn(async move { - let stats = entry.get_stats(); - metrics.lock().await.seeders += u64::from(stats.complete); - metrics.lock().await.completed += u64::from(stats.downloaded); - metrics.lock().await.leechers += u64::from(stats.incomplete); - metrics.lock().await.torrents += 1; - })); - } - - join_all(handles).await; - - *metrics.lock_owned().await - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::Single)> { - let db = self.get_torrents(); - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut torrents = self.get_torrents_mut(); - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(info_hash) { - continue; - } - - let entry = entry::Single { - peers: BTreeMap::default(), - completed: *completed, - }; - - torrents.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut(); - db.remove(key) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - let mut db = self.get_torrents_mut(); - - drop(db.values_mut().map(|e| e.remove_inactive_peers(max_peer_timeout))); - } - - async fn remove_peerless_torrents(&self, policy: &crate::core::TrackerPolicy) { - let mut db = self.get_torrents_mut(); - - db.retain(|_, e| e.is_not_zombie(policy)); - } -} diff --git a/src/core/torrent/repository/rw_lock_std_mutex_std.rs b/src/core/torrent/repository/rw_lock_std_mutex_std.rs deleted file mode 100644 index 5a9a38f77..000000000 --- a/src/core/torrent/repository/rw_lock_std_mutex_std.rs +++ /dev/null @@ -1,143 +0,0 @@ -use std::collections::BTreeMap; -use std::sync::Arc; - -use futures::future::join_all; - -use super::{Repository, UpdateTorrentSync}; -use crate::core::databases::PersistentTorrents; -use crate::core::services::torrent::Pagination; -use crate::core::torrent::entry::{ReadInfo, Update, UpdateSync}; -use crate::core::torrent::{entry, SwarmMetadata, TorrentsRwLockStdMutexStd}; -use crate::core::{peer, TorrentsMetrics}; -use crate::shared::bit_torrent::info_hash::InfoHash; - -impl TorrentsRwLockStdMutexStd { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().expect("unable to get torrent list") - } - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().expect("unable to get writable torrent list") - } -} - -impl UpdateTorrentSync for TorrentsRwLockStdMutexStd { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let maybe_entry = self.get_torrents().get(info_hash).cloned(); - - let entry = if let Some(entry) = maybe_entry { - entry - } else { - let mut db = self.get_torrents_mut(); - let entry = db.entry(*info_hash).or_insert(Arc::default()); - entry.clone() - }; - - entry.insert_or_update_peer_and_get_stats(peer) - } -} - -impl UpdateTorrentSync for Arc { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - self.as_ref().update_torrent_with_peer_and_get_stats(info_hash, peer) - } -} - -impl Repository for TorrentsRwLockStdMutexStd { - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents(); - db.get(key).cloned() - } - - async fn get_metrics(&self) -> TorrentsMetrics { - let metrics: Arc> = Arc::default(); - - // todo:: replace with a ring buffer - let mut handles = Vec::>::default(); - - for e in self.get_torrents().values() { - let entry = e.clone(); - let metrics = metrics.clone(); - handles.push(tokio::task::spawn(async move { - let stats = entry.lock().expect("it should get the lock").get_stats(); - metrics.lock().await.seeders += u64::from(stats.complete); - metrics.lock().await.completed += u64::from(stats.downloaded); - metrics.lock().await.leechers += u64::from(stats.incomplete); - metrics.lock().await.torrents += 1; - })); - } - - join_all(handles).await; - - *metrics.lock_owned().await - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexStd)> { - let db = self.get_torrents(); - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut torrents = self.get_torrents_mut(); - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(info_hash) { - continue; - } - - let entry = entry::MutexStd::new( - entry::Single { - peers: BTreeMap::default(), - completed: *completed, - } - .into(), - ); - - torrents.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut(); - db.remove(key) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - // todo:: replace with a ring buffer - let mut handles = Vec::>::default(); - - for e in self.get_torrents().values() { - let entry = e.clone(); - handles.push(tokio::task::spawn(async move { - entry - .lock() - .expect("it should get lock for entry") - .remove_inactive_peers(max_peer_timeout); - })); - } - - join_all(handles).await; - } - - async fn remove_peerless_torrents(&self, policy: &crate::core::TrackerPolicy) { - let mut db = self.get_torrents_mut(); - - db.retain(|_, e| e.lock().expect("it should lock entry").is_not_zombie(policy)); - } -} diff --git a/src/core/torrent/repository/rw_lock_std_mutex_tokio.rs b/src/core/torrent/repository/rw_lock_std_mutex_tokio.rs deleted file mode 100644 index 1feb41e3e..000000000 --- a/src/core/torrent/repository/rw_lock_std_mutex_tokio.rs +++ /dev/null @@ -1,141 +0,0 @@ -use std::collections::BTreeMap; -use std::sync::Arc; - -use futures::future::join_all; - -use super::{Repository, UpdateTorrentAsync}; -use crate::core::databases::PersistentTorrents; -use crate::core::services::torrent::Pagination; -use crate::core::torrent::entry::{ReadInfo, Update, UpdateAsync}; -use crate::core::torrent::{entry, SwarmMetadata, TorrentsRwLockStdMutexTokio}; -use crate::core::{peer, TorrentsMetrics}; -use crate::shared::bit_torrent::info_hash::InfoHash; - -impl TorrentsRwLockStdMutexTokio { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().expect("unable to get torrent list") - } - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().expect("unable to get writable torrent list") - } -} - -impl UpdateTorrentAsync for TorrentsRwLockStdMutexTokio { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let maybe_entry = self.get_torrents().get(info_hash).cloned(); - - let entry = if let Some(entry) = maybe_entry { - entry - } else { - let mut db = self.get_torrents_mut(); - let entry = db.entry(*info_hash).or_insert(Arc::default()); - entry.clone() - }; - - entry.insert_or_update_peer_and_get_stats(peer).await - } -} - -impl UpdateTorrentAsync for Arc { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - self.as_ref().update_torrent_with_peer_and_get_stats(info_hash, peer).await - } -} - -impl Repository for TorrentsRwLockStdMutexTokio { - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents(); - db.get(key).cloned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexTokio)> { - let db = self.get_torrents(); - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn get_metrics(&self) -> TorrentsMetrics { - let metrics: Arc> = Arc::default(); - - // todo:: replace with a ring buffer - let mut handles = Vec::>::default(); - - for e in self.get_torrents().values() { - let entry = e.clone(); - let metrics = metrics.clone(); - handles.push(tokio::task::spawn(async move { - let stats = entry.lock().await.get_stats(); - metrics.lock().await.seeders += u64::from(stats.complete); - metrics.lock().await.completed += u64::from(stats.downloaded); - metrics.lock().await.leechers += u64::from(stats.incomplete); - metrics.lock().await.torrents += 1; - })); - } - - join_all(handles).await; - - *metrics.lock_owned().await - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut db = self.get_torrents_mut(); - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if db.contains_key(info_hash) { - continue; - } - - let entry = entry::MutexTokio::new( - entry::Single { - peers: BTreeMap::default(), - completed: *completed, - } - .into(), - ); - - db.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut(); - db.remove(key) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - // todo:: replace with a ring buffer - - let mut handles = Vec::>::default(); - - for e in self.get_torrents().values() { - let entry = e.clone(); - handles.push(tokio::task::spawn(async move { - entry.lock().await.remove_inactive_peers(max_peer_timeout); - })); - } - - join_all(handles).await; - } - - async fn remove_peerless_torrents(&self, policy: &crate::core::TrackerPolicy) { - let mut db = self.get_torrents_mut(); - - db.retain(|_, e| e.blocking_lock().is_not_zombie(policy)); - } -} diff --git a/src/core/torrent/repository/rw_lock_tokio.rs b/src/core/torrent/repository/rw_lock_tokio.rs deleted file mode 100644 index 3d633a837..000000000 --- a/src/core/torrent/repository/rw_lock_tokio.rs +++ /dev/null @@ -1,124 +0,0 @@ -use std::collections::BTreeMap; -use std::sync::Arc; - -use futures::future::join_all; - -use super::{Repository, UpdateTorrentAsync}; -use crate::core::databases::PersistentTorrents; -use crate::core::services::torrent::Pagination; -use crate::core::torrent::entry::{self, ReadInfo, Update}; -use crate::core::torrent::{SwarmMetadata, TorrentsRwLockTokio}; -use crate::core::{peer, TorrentsMetrics, TrackerPolicy}; -use crate::shared::bit_torrent::info_hash::InfoHash; - -impl TorrentsRwLockTokio { - async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().await - } - - async fn get_torrents_mut<'a>( - &'a self, - ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().await - } -} - -impl UpdateTorrentAsync for TorrentsRwLockTokio { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let mut db = self.get_torrents_mut().await; - - let entry = db.entry(*info_hash).or_insert(entry::Single::default()); - - entry.insert_or_update_peer_and_get_stats(peer) - } -} - -impl UpdateTorrentAsync for Arc { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - self.as_ref().update_torrent_with_peer_and_get_stats(info_hash, peer).await - } -} - -impl Repository for TorrentsRwLockTokio { - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents().await; - db.get(key).cloned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::Single)> { - let db = self.get_torrents().await; - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn get_metrics(&self) -> TorrentsMetrics { - let metrics: Arc> = Arc::default(); - - let mut handles = Vec::>::default(); - - for e in self.get_torrents().await.values() { - let entry = e.clone(); - let metrics = metrics.clone(); - handles.push(tokio::task::spawn(async move { - let stats = entry.get_stats(); - metrics.lock().await.seeders += u64::from(stats.complete); - metrics.lock().await.completed += u64::from(stats.downloaded); - metrics.lock().await.leechers += u64::from(stats.incomplete); - metrics.lock().await.torrents += 1; - })); - } - - join_all(handles).await; - - *metrics.lock_owned().await - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut torrents = self.get_torrents_mut().await; - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(info_hash) { - continue; - } - - let entry = entry::Single { - peers: BTreeMap::default(), - completed: *completed, - }; - - torrents.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut().await; - db.remove(key) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - let mut db = self.get_torrents_mut().await; - - drop(db.values_mut().map(|e| e.remove_inactive_peers(max_peer_timeout))); - } - - async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - let mut db = self.get_torrents_mut().await; - - db.retain(|_, e| e.is_not_zombie(policy)); - } -} diff --git a/src/core/torrent/repository/rw_lock_tokio_mutex_std.rs b/src/core/torrent/repository/rw_lock_tokio_mutex_std.rs deleted file mode 100644 index 3888c40b0..000000000 --- a/src/core/torrent/repository/rw_lock_tokio_mutex_std.rs +++ /dev/null @@ -1,146 +0,0 @@ -use std::collections::BTreeMap; -use std::sync::Arc; - -use futures::future::join_all; - -use super::{Repository, UpdateTorrentAsync}; -use crate::core::databases::PersistentTorrents; -use crate::core::services::torrent::Pagination; -use crate::core::torrent::entry::{ReadInfo, Update, UpdateSync}; -use crate::core::torrent::{entry, SwarmMetadata, TorrentsRwLockTokioMutexStd}; -use crate::core::{peer, TorrentsMetrics, TrackerPolicy}; -use crate::shared::bit_torrent::info_hash::InfoHash; - -impl TorrentsRwLockTokioMutexStd { - async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().await - } - - async fn get_torrents_mut<'a>( - &'a self, - ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().await - } -} - -impl UpdateTorrentAsync for TorrentsRwLockTokioMutexStd { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); - - let entry = if let Some(entry) = maybe_entry { - entry - } else { - let mut db = self.get_torrents_mut().await; - let entry = db.entry(*info_hash).or_insert(Arc::default()); - entry.clone() - }; - - entry.insert_or_update_peer_and_get_stats(peer) - } -} - -impl UpdateTorrentAsync for Arc { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - self.as_ref().update_torrent_with_peer_and_get_stats(info_hash, peer).await - } -} - -impl Repository for TorrentsRwLockTokioMutexStd { - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents().await; - db.get(key).cloned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexStd)> { - let db = self.get_torrents().await; - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn get_metrics(&self) -> TorrentsMetrics { - let metrics: Arc> = Arc::default(); - - // todo:: replace with a ring buffer - - let mut handles = Vec::>::default(); - - for e in self.get_torrents().await.values() { - let entry = e.clone(); - let metrics = metrics.clone(); - handles.push(tokio::task::spawn(async move { - let stats = entry.lock().expect("it should get a lock").get_stats(); - metrics.lock().await.seeders += u64::from(stats.complete); - metrics.lock().await.completed += u64::from(stats.downloaded); - metrics.lock().await.leechers += u64::from(stats.incomplete); - metrics.lock().await.torrents += 1; - })); - } - - join_all(handles).await; - - *metrics.lock_owned().await - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut torrents = self.get_torrents_mut().await; - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(info_hash) { - continue; - } - - let entry = entry::MutexStd::new( - entry::Single { - peers: BTreeMap::default(), - completed: *completed, - } - .into(), - ); - - torrents.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut().await; - db.remove(key) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - // todo:: replace with a ring buffer - let mut handles = Vec::>::default(); - - for e in self.get_torrents().await.values() { - let entry = e.clone(); - handles.push(tokio::task::spawn(async move { - entry - .lock() - .expect("it should get lock for entry") - .remove_inactive_peers(max_peer_timeout); - })); - } - - join_all(handles).await; - } - - async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - let mut db = self.get_torrents_mut().await; - - db.retain(|_, e| e.lock().expect("it should lock entry").is_not_zombie(policy)); - } -} diff --git a/src/core/torrent/repository/rw_lock_tokio_mutex_tokio.rs b/src/core/torrent/repository/rw_lock_tokio_mutex_tokio.rs deleted file mode 100644 index 49e08d90c..000000000 --- a/src/core/torrent/repository/rw_lock_tokio_mutex_tokio.rs +++ /dev/null @@ -1,144 +0,0 @@ -use std::collections::BTreeMap; -use std::sync::Arc; - -use futures::future::join_all; - -use super::{Repository, UpdateTorrentAsync}; -use crate::core::databases::PersistentTorrents; -use crate::core::services::torrent::Pagination; -use crate::core::torrent::entry::{self, ReadInfo, Update, UpdateAsync}; -use crate::core::torrent::{SwarmMetadata, TorrentsRwLockTokioMutexTokio}; -use crate::core::{peer, TorrentsMetrics, TrackerPolicy}; -use crate::shared::bit_torrent::info_hash::InfoHash; - -impl TorrentsRwLockTokioMutexTokio { - async fn get_torrents<'a>( - &'a self, - ) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().await - } - - async fn get_torrents_mut<'a>( - &'a self, - ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().await - } -} - -impl UpdateTorrentAsync for TorrentsRwLockTokioMutexTokio { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); - - let entry = if let Some(entry) = maybe_entry { - entry - } else { - let mut db = self.get_torrents_mut().await; - let entry = db.entry(*info_hash).or_insert(Arc::default()); - entry.clone() - }; - - entry.insert_or_update_peer_and_get_stats(peer).await - } -} - -impl UpdateTorrentAsync for Arc { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { - self.as_ref().update_torrent_with_peer_and_get_stats(info_hash, peer).await - } -} - -impl Repository for TorrentsRwLockTokioMutexTokio { - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents().await; - db.get(key).cloned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, entry::MutexTokio)> { - let db = self.get_torrents().await; - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn get_metrics(&self) -> TorrentsMetrics { - let metrics: Arc> = Arc::default(); - - // todo:: replace with a ring buffer - let mut handles = Vec::>::default(); - - for e in self.get_torrents().await.values() { - let entry = e.clone(); - let metrics = metrics.clone(); - handles.push(tokio::task::spawn(async move { - let stats = entry.lock().await.get_stats(); - metrics.lock().await.seeders += u64::from(stats.complete); - metrics.lock().await.completed += u64::from(stats.downloaded); - metrics.lock().await.leechers += u64::from(stats.incomplete); - metrics.lock().await.torrents += 1; - })); - } - - join_all(handles).await; - - *metrics.lock_owned().await - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut db = self.get_torrents_mut().await; - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if db.contains_key(info_hash) { - continue; - } - - let entry = entry::MutexTokio::new( - entry::Single { - peers: BTreeMap::default(), - completed: *completed, - } - .into(), - ); - - db.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut().await; - db.remove(key) - } - - async fn remove_inactive_peers(&self, max_peer_timeout: u32) { - // todo:: replace with a ring buffer - let mut handles = Vec::>::default(); - - for e in self.get_torrents().await.values() { - let entry = e.clone(); - handles.push(tokio::task::spawn(async move { - entry.lock().await.remove_inactive_peers(max_peer_timeout); - })); - } - - join_all(handles).await; - } - - async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - let mut db = self.get_torrents_mut().await; - - db.retain(|_, e| e.blocking_lock().is_not_zombie(policy)); - } -} diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index b241c469c..48ac660cf 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -71,10 +71,11 @@ impl From for Stats { #[cfg(test)] mod tests { + use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use super::Stats; use crate::core::services::statistics::TrackerMetrics; use crate::core::statistics::Metrics; - use crate::core::TorrentsMetrics; #[test] fn stats_resource_should_be_converted_from_tracker_metrics() { diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs index 999580da7..15f70c8b6 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/src/servers/apis/v1/context/torrent/handlers.rs @@ -10,13 +10,14 @@ use axum_extra::extract::Query; use log::debug; use serde::{de, Deserialize, Deserializer}; use thiserror::Error; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; -use crate::core::services::torrent::{get_torrent_info, get_torrents, get_torrents_page, Pagination}; +use crate::core::services::torrent::{get_torrent_info, get_torrents, get_torrents_page}; use crate::core::Tracker; use crate::servers::apis::v1::responses::invalid_info_hash_param_response; use crate::servers::apis::InfoHashParam; -use crate::shared::bit_torrent::info_hash::InfoHash; /// It handles the request to get the torrent data. /// diff --git a/src/servers/apis/v1/context/torrent/resources/peer.rs b/src/servers/apis/v1/context/torrent/resources/peer.rs index 752694393..e7a0802c1 100644 --- a/src/servers/apis/v1/context/torrent/resources/peer.rs +++ b/src/servers/apis/v1/context/torrent/resources/peer.rs @@ -1,7 +1,7 @@ //! `Peer` and Peer `Id` API resources. +use derive_more::From; use serde::{Deserialize, Serialize}; - -use crate::core; +use torrust_tracker_primitives::peer; /// `Peer` API resource. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -22,7 +22,7 @@ pub struct Peer { /// The peer's left bytes (pending to download). pub left: i64, /// The peer's event: `started`, `stopped`, `completed`. - /// See [`AnnounceEventDef`](crate::shared::bit_torrent::common::AnnounceEventDef). + /// See [`AnnounceEvent`](torrust_tracker_primitives::announce_event::AnnounceEvent). pub event: String, } @@ -35,8 +35,8 @@ pub struct Id { pub client: Option, } -impl From for Id { - fn from(peer_id: core::peer::Id) -> Self { +impl From for Id { + fn from(peer_id: peer::Id) -> Self { Id { id: peer_id.to_hex_string(), client: peer_id.get_client_name(), @@ -44,18 +44,32 @@ impl From for Id { } } -impl From for Peer { - #[allow(deprecated)] - fn from(peer: core::peer::Peer) -> Self { +impl From for Peer { + fn from(value: peer::Peer) -> Self { + #[allow(deprecated)] Peer { - peer_id: Id::from(peer.peer_id), - peer_addr: peer.peer_addr.to_string(), - updated: peer.updated.as_millis(), - updated_milliseconds_ago: peer.updated.as_millis(), - uploaded: peer.uploaded.0, - downloaded: peer.downloaded.0, - left: peer.left.0, - event: format!("{:?}", peer.event), + peer_id: Id::from(value.peer_id), + peer_addr: value.peer_addr.to_string(), + updated: value.updated.as_millis(), + updated_milliseconds_ago: value.updated.as_millis(), + uploaded: value.uploaded.0, + downloaded: value.downloaded.0, + left: value.left.0, + event: format!("{:?}", value.event), + } + } +} + +#[derive(From, PartialEq, Default)] +pub struct Vector(pub Vec); + +impl FromIterator for Vector { + fn from_iter>(iter: T) -> Self { + let mut peers = Vector::default(); + + for i in iter { + peers.0.push(i.into()); } + peers } } diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs index fc43fbb7a..2f1ace5c9 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs @@ -6,7 +6,6 @@ //! the JSON response. use serde::{Deserialize, Serialize}; -use super::peer; use crate::core::services::torrent::{BasicInfo, Info}; /// `Torrent` API resource. @@ -68,14 +67,16 @@ pub fn to_resource(basic_info_vec: &[BasicInfo]) -> Vec { impl From for Torrent { fn from(info: Info) -> Self { + let peers: Option = info.peers.map(|peers| peers.into_iter().collect()); + + let peers: Option> = peers.map(|peers| peers.0); + Self { info_hash: info.info_hash.to_string(), seeders: info.seeders, completed: info.completed, leechers: info.leechers, - peers: info - .peers - .map(|peers| peers.iter().map(|peer| peer::Peer::from(*peer)).collect()), + peers, } } } @@ -96,15 +97,14 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_primitives::announce_event::AnnounceEvent; + use torrust_tracker_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; use super::Torrent; - use crate::core::peer; use crate::core::services::torrent::{BasicInfo, Info}; use crate::servers::apis::v1::context::torrent::resources::peer::Peer; use crate::servers::apis::v1::context::torrent::resources::torrent::ListItem; - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::shared::clock::DurationSinceUnixEpoch; fn sample_peer() -> peer::Peer { peer::Peer { diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/src/servers/apis/v1/context/whitelist/handlers.rs index fc32f667b..c88f8cc1d 100644 --- a/src/servers/apis/v1/context/whitelist/handlers.rs +++ b/src/servers/apis/v1/context/whitelist/handlers.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use axum::extract::{Path, State}; use axum::response::Response; +use torrust_tracker_primitives::info_hash::InfoHash; use super::responses::{ failed_to_reload_whitelist_response, failed_to_remove_torrent_from_whitelist_response, failed_to_whitelist_torrent_response, @@ -12,7 +13,6 @@ use super::responses::{ use crate::core::Tracker; use crate::servers::apis::v1::responses::{invalid_info_hash_param_response, ok_response}; use crate::servers::apis::InfoHashParam; -use crate::shared::bit_torrent::info_hash::InfoHash; /// It handles the request to add a torrent to the whitelist. /// diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index 08a59ef90..6e8b5a40e 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -206,15 +206,15 @@ //! //! ### Scrape //! -//! The `scrape` request allows a peer to get [swarm metadata](crate::core::torrent::SwarmMetadata) +//! The `scrape` request allows a peer to get [swarm metadata](torrust_tracker_primitives::swarm_metadata::SwarmMetadata) //! for multiple torrents at the same time. //! -//! The response contains the [swarm metadata](crate::core::torrent::SwarmMetadata) +//! The response contains the [swarm metadata](torrust_tracker_primitives::swarm_metadata::SwarmMetadata) //! for that torrent: //! -//! - [complete](crate::core::torrent::SwarmMetadata::complete) -//! - [downloaded](crate::core::torrent::SwarmMetadata::downloaded) -//! - [incomplete](crate::core::torrent::SwarmMetadata::incomplete) +//! - [complete](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::complete) +//! - [downloaded](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::downloaded) +//! - [incomplete](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::incomplete) //! //! **Query parameters** //! @@ -266,7 +266,7 @@ //! Where the `files` key contains a dictionary of dictionaries. The first //! dictionary key is the `info_hash` of the torrent (`iiiiiiiiiiiiiiiiiiii` in //! the example). The second level dictionary contains the -//! [swarm metadata](crate::core::torrent::SwarmMetadata) for that torrent. +//! [swarm metadata](torrust_tracker_primitives::swarm_metadata::SwarmMetadata) for that torrent. //! //! If you save the response as a file and you open it with a program that //! can handle binary data you would see: diff --git a/src/servers/http/percent_encoding.rs b/src/servers/http/percent_encoding.rs index 472b1e724..90f4b9a43 100644 --- a/src/servers/http/percent_encoding.rs +++ b/src/servers/http/percent_encoding.rs @@ -15,8 +15,8 @@ //! - //! - //! - -use crate::core::peer::{self, IdConversionError}; -use crate::shared::bit_torrent::info_hash::{ConversionError, InfoHash}; +use torrust_tracker_primitives::info_hash::{self, InfoHash}; +use torrust_tracker_primitives::peer; /// Percent decodes a percent encoded infohash. Internally an /// [`InfoHash`] is a 20-byte array. @@ -27,8 +27,8 @@ use crate::shared::bit_torrent::info_hash::{ConversionError, InfoHash}; /// ```rust /// use std::str::FromStr; /// use torrust_tracker::servers::http::percent_encoding::percent_decode_info_hash; -/// use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -/// use torrust_tracker::core::peer; +/// use torrust_tracker_primitives::info_hash::InfoHash; +/// use torrust_tracker_primitives::peer; /// /// let encoded_infohash = "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0"; /// @@ -44,12 +44,12 @@ use crate::shared::bit_torrent::info_hash::{ConversionError, InfoHash}; /// /// Will return `Err` if the decoded bytes do not represent a valid /// [`InfoHash`]. -pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result { +pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result { let bytes = percent_encoding::percent_decode_str(raw_info_hash).collect::>(); InfoHash::try_from(bytes) } -/// Percent decodes a percent encoded peer id. Internally a peer [`Id`](crate::core::peer::Id) +/// Percent decodes a percent encoded peer id. Internally a peer [`Id`](peer::Id) /// is a 20-byte array. /// /// For example, given the peer id `*b"-qB00000000000000000"`, @@ -58,8 +58,8 @@ pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result Result Result { +pub fn percent_decode_peer_id(raw_peer_id: &str) -> Result { let bytes = percent_encoding::percent_decode_str(raw_peer_id).collect::>(); peer::Id::try_from(bytes) } @@ -80,9 +80,10 @@ pub fn percent_decode_peer_id(raw_peer_id: &str) -> Result) -> Result) -> Result R /// /// It ignores the peer address in the announce request params. #[must_use] -fn peer_from_request(announce_request: &Announce, peer_ip: &IpAddr) -> Peer { - Peer { +fn peer_from_request(announce_request: &Announce, peer_ip: &IpAddr) -> peer::Peer { + peer::Peer { peer_id: announce_request.peer_id, peer_addr: SocketAddr::new(*peer_ip, announce_request.port), updated: Current::now(), uploaded: NumberOfBytes(announce_request.uploaded.unwrap_or(0)), downloaded: NumberOfBytes(announce_request.downloaded.unwrap_or(0)), left: NumberOfBytes(announce_request.left.unwrap_or(0)), - event: map_to_aquatic_event(&announce_request.event), + event: map_to_torrust_event(&announce_request.event), } } -fn map_to_aquatic_event(event: &Option) -> AnnounceEvent { +#[must_use] +pub fn map_to_aquatic_event(event: &Option) -> aquatic_udp_protocol::AnnounceEvent { match event { Some(event) => match &event { Event::Started => aquatic_udp_protocol::AnnounceEvent::Started, @@ -153,17 +154,30 @@ fn map_to_aquatic_event(event: &Option) -> AnnounceEvent { } } +#[must_use] +pub fn map_to_torrust_event(event: &Option) -> AnnounceEvent { + match event { + Some(event) => match &event { + Event::Started => AnnounceEvent::Started, + Event::Stopped => AnnounceEvent::Stopped, + Event::Completed => AnnounceEvent::Completed, + }, + None => AnnounceEvent::None, + } +} + #[cfg(test)] mod tests { + use torrust_tracker_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::peer; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; - use crate::core::{peer, Tracker}; + use crate::core::Tracker; use crate::servers::http::v1::requests::announce::Announce; use crate::servers::http::v1::responses; use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; - use crate::shared::bit_torrent::info_hash::InfoHash; fn private_tracker() -> Tracker { tracker_factory(&configuration::ephemeral_mode_private()) diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 49b1aebc7..d6b39cc53 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -111,6 +111,7 @@ mod tests { use std::net::IpAddr; use std::str::FromStr; + use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; @@ -118,7 +119,6 @@ mod tests { use crate::servers::http::v1::requests::scrape::Scrape; use crate::servers::http::v1::responses; use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; - use crate::shared::bit_torrent::info_hash::InfoHash; fn private_tracker() -> Tracker { tracker_factory(&configuration::ephemeral_mode_private()) diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index 08dd9da29..39a6c1846 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -7,12 +7,12 @@ use std::str::FromStr; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; +use torrust_tracker_primitives::info_hash::{self, InfoHash}; +use torrust_tracker_primitives::peer; -use crate::core::peer::{self, IdConversionError}; use crate::servers::http::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; use crate::servers::http::v1::query::{ParseQueryError, Query}; use crate::servers::http::v1::responses; -use crate::shared::bit_torrent::info_hash::{ConversionError, InfoHash}; /// The number of bytes `downloaded`, `uploaded` or `left`. It's used in the /// `Announce` request for parameters that represent a number of bytes. @@ -33,8 +33,8 @@ const COMPACT: &str = "compact"; /// /// ```rust /// use torrust_tracker::servers::http::v1::requests::announce::{Announce, Compact, Event}; -/// use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -/// use torrust_tracker::core::peer; +/// use torrust_tracker_primitives::info_hash::InfoHash; +/// use torrust_tracker_primitives::peer; /// /// let request = Announce { /// // Mandatory params @@ -119,14 +119,14 @@ pub enum ParseAnnounceQueryError { InvalidInfoHashParam { param_name: String, param_value: String, - source: LocatedError<'static, ConversionError>, + source: LocatedError<'static, info_hash::ConversionError>, }, /// The `peer_id` is invalid. #[error("invalid param value {param_value} for {param_name} in {source}")] InvalidPeerIdParam { param_name: String, param_value: String, - source: LocatedError<'static, IdConversionError>, + source: LocatedError<'static, peer::IdConversionError>, }, } @@ -355,12 +355,13 @@ mod tests { mod announce_request { - use crate::core::peer; + use torrust_tracker_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::peer; + use crate::servers::http::v1::query::Query; use crate::servers::http::v1::requests::announce::{ Announce, Compact, Event, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, PEER_ID, PORT, UPLOADED, }; - use crate::shared::bit_torrent::info_hash::InfoHash; #[test] fn should_be_instantiated_from_the_url_query_with_only_the_mandatory_params() { diff --git a/src/servers/http/v1/requests/scrape.rs b/src/servers/http/v1/requests/scrape.rs index 7c52b9fc4..19f6e35a6 100644 --- a/src/servers/http/v1/requests/scrape.rs +++ b/src/servers/http/v1/requests/scrape.rs @@ -5,11 +5,11 @@ use std::panic::Location; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; +use torrust_tracker_primitives::info_hash::{self, InfoHash}; use crate::servers::http::percent_encoding::percent_decode_info_hash; use crate::servers::http::v1::query::Query; use crate::servers::http::v1::responses; -use crate::shared::bit_torrent::info_hash::{ConversionError, InfoHash}; pub type NumberOfBytes = i64; @@ -34,7 +34,7 @@ pub enum ParseScrapeQueryError { InvalidInfoHashParam { param_name: String, param_value: String, - source: LocatedError<'static, ConversionError>, + source: LocatedError<'static, info_hash::ConversionError>, }, } @@ -86,9 +86,10 @@ mod tests { mod scrape_request { + use torrust_tracker_primitives::info_hash::InfoHash; + use crate::servers::http::v1::query::Query; use crate::servers::http::v1::requests::scrape::{Scrape, INFO_HASH}; - use crate::shared::bit_torrent::info_hash::InfoHash; #[test] fn should_be_instantiated_from_the_url_query_with_only_one_infohash() { diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index 619632ae4..134da919e 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -7,10 +7,10 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use axum::http::StatusCode; use derive_more::{AsRef, Constructor, From}; use torrust_tracker_contrib_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; +use torrust_tracker_primitives::peer; use super::Response; -use crate::core::peer::Peer; -use crate::core::{self, AnnounceData}; +use crate::core::AnnounceData; use crate::servers::http::v1::responses; /// An [`Announce`] response, that can be anything that is convertible from [`AnnounceData`]. @@ -150,21 +150,6 @@ impl Into> for Compact { } } -/// Marker Trait for Peer Vectors -pub trait PeerEncoding: From + PartialEq {} - -impl FromIterator for Vec

{ - fn from_iter>(iter: T) -> Self { - let mut peers: Vec

= vec![]; - - for peer in iter { - peers.push(peer.into()); - } - - peers - } -} - /// A [`NormalPeer`], for the [`Normal`] form. /// /// ```rust @@ -188,10 +173,10 @@ pub struct NormalPeer { pub port: u16, } -impl PeerEncoding for NormalPeer {} +impl peer::Encoding for NormalPeer {} -impl From for NormalPeer { - fn from(peer: core::peer::Peer) -> Self { +impl From for NormalPeer { + fn from(peer: peer::Peer) -> Self { NormalPeer { peer_id: peer.peer_id.to_bytes(), ip: peer.peer_addr.ip(), @@ -240,10 +225,10 @@ pub enum CompactPeer { V6(CompactPeerData), } -impl PeerEncoding for CompactPeer {} +impl peer::Encoding for CompactPeer {} -impl From for CompactPeer { - fn from(peer: core::peer::Peer) -> Self { +impl From for CompactPeer { + fn from(peer: peer::Peer) -> Self { match (peer.peer_addr.ip(), peer.peer_addr.port()) { (IpAddr::V4(ip), port) => Self::V4(CompactPeerData { ip, port }), (IpAddr::V6(ip), port) => Self::V6(CompactPeerData { ip, port }), @@ -316,10 +301,10 @@ mod tests { use std::sync::Arc; use torrust_tracker_configuration::AnnouncePolicy; + use torrust_tracker_primitives::peer; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::core::peer::fixture::PeerBuilder; - use crate::core::peer::Id; - use crate::core::torrent::SwarmMetadata; use crate::core::AnnounceData; use crate::servers::http::v1::responses::announce::{Announce, Compact, Normal, Response}; @@ -339,12 +324,12 @@ mod tests { let policy = AnnouncePolicy::new(111, 222); let peer_ipv4 = PeerBuilder::default() - .with_peer_id(&Id(*b"-qB00000000000000001")) + .with_peer_id(&peer::Id(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), 0x7070)) .build(); let peer_ipv6 = PeerBuilder::default() - .with_peer_id(&Id(*b"-qB00000000000000002")) + .with_peer_id(&peer::Id(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), 0x7070, diff --git a/src/servers/http/v1/responses/scrape.rs b/src/servers/http/v1/responses/scrape.rs index e16827824..11f361028 100644 --- a/src/servers/http/v1/responses/scrape.rs +++ b/src/servers/http/v1/responses/scrape.rs @@ -13,8 +13,8 @@ use crate::core::ScrapeData; /// /// ```rust /// use torrust_tracker::servers::http::v1::responses::scrape::Bencoded; -/// use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; -/// use torrust_tracker::core::torrent::SwarmMetadata; +/// use torrust_tracker_primitives::info_hash::InfoHash; +/// use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; /// use torrust_tracker::core::ScrapeData; /// /// let info_hash = InfoHash([0x69; 20]); @@ -92,10 +92,11 @@ impl IntoResponse for Bencoded { mod tests { mod scrape_response { - use crate::core::torrent::SwarmMetadata; + use torrust_tracker_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use crate::core::ScrapeData; use crate::servers::http::v1::responses::scrape::Bencoded; - use crate::shared::bit_torrent::info_hash::InfoHash; fn sample_scrape_data() -> ScrapeData { let info_hash = InfoHash([0x69; 20]); diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index b53697eed..b37081045 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -11,9 +11,10 @@ use std::net::IpAddr; use std::sync::Arc; -use crate::core::peer::Peer; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer; + use crate::core::{statistics, AnnounceData, Tracker}; -use crate::shared::bit_torrent::info_hash::InfoHash; /// The HTTP tracker `announce` service. /// @@ -25,7 +26,7 @@ use crate::shared::bit_torrent::info_hash::InfoHash; /// > **NOTICE**: as the HTTP tracker does not requires a connection request /// like the UDP tracker, the number of TCP connections is incremented for /// each `announce` request. -pub async fn invoke(tracker: Arc, info_hash: InfoHash, peer: &mut Peer) -> AnnounceData { +pub async fn invoke(tracker: Arc, info_hash: InfoHash, peer: &mut peer::Peer) -> AnnounceData { let original_peer_ip = peer.peer_addr.ip(); // The tracker could change the original peer ip @@ -47,13 +48,13 @@ pub async fn invoke(tracker: Arc, info_hash: InfoHash, peer: &mut Peer) mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_primitives::announce_event::AnnounceEvent; + use torrust_tracker_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; - use crate::core::{peer, Tracker}; - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::shared::clock::DurationSinceUnixEpoch; + use crate::core::Tracker; fn public_tracker() -> Tracker { tracker_factory(&configuration::ephemeral_mode_public()) @@ -94,11 +95,11 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; + use torrust_tracker_primitives::peer; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; - use crate::core::peer::Peer; - use crate::core::torrent::SwarmMetadata; use crate::core::{statistics, AnnounceData, Tracker}; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; @@ -150,7 +151,7 @@ mod tests { Tracker::new(&configuration, Some(stats_event_sender), statistics::Repo::new()).unwrap() } - fn peer_with_the_ipv4_loopback_ip() -> Peer { + fn peer_with_the_ipv4_loopback_ip() -> peer::Peer { let loopback_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let mut peer = sample_peer(); peer.peer_addr = SocketAddr::new(loopback_ip, 8080); diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 82ca15dc8..18b57f479 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -11,8 +11,9 @@ use std::net::IpAddr; use std::sync::Arc; +use torrust_tracker_primitives::info_hash::InfoHash; + use crate::core::{statistics, ScrapeData, Tracker}; -use crate::shared::bit_torrent::info_hash::InfoHash; /// The HTTP tracker `scrape` service. /// @@ -60,13 +61,13 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_primitives::announce_event::AnnounceEvent; + use torrust_tracker_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; - use crate::core::{peer, Tracker}; - use crate::shared::bit_torrent::info_hash::InfoHash; - use crate::shared::clock::DurationSinceUnixEpoch; + use crate::core::Tracker; fn public_tracker() -> Tracker { tracker_factory(&configuration::ephemeral_mode_public()) @@ -99,9 +100,9 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; - use crate::core::torrent::SwarmMetadata; use crate::core::{statistics, ScrapeData, Tracker}; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index f42e11424..8f6e6d8b4 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -12,6 +12,7 @@ use aquatic_udp_protocol::{ use log::debug; use tokio::net::UdpSocket; use torrust_tracker_located_error::DynError; +use torrust_tracker_primitives::info_hash::InfoHash; use uuid::Uuid; use super::connection_cookie::{check, from_connection_id, into_connection_id, make}; @@ -22,7 +23,6 @@ use crate::servers::udp::logging::{log_bad_request, log_error_response, log_requ use crate::servers::udp::peer_builder; use crate::servers::udp::request::AnnounceWrapper; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; -use crate::shared::bit_torrent::info_hash::InfoHash; /// It handles the incoming UDP packets. /// @@ -318,12 +318,13 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_configuration::Configuration; + use torrust_tracker_primitives::announce_event::AnnounceEvent; + use torrust_tracker_primitives::{peer, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; - use crate::core::{peer, Tracker}; + use crate::core::Tracker; use crate::shared::clock::{Current, Time}; fn tracker_configuration() -> Configuration { @@ -605,8 +606,9 @@ mod tests { Response, ResponsePeer, }; use mockall::predicate::eq; + use torrust_tracker_primitives::peer; - use crate::core::{self, peer, statistics}; + use crate::core::{self, statistics}; use crate::servers::udp::connection_cookie::{into_connection_id, make}; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; @@ -635,7 +637,7 @@ mod tests { handle_announce(remote_addr, &request, &tracker).await.unwrap(); - let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; + let peers = tracker.get_torrent_peers(&info_hash.0.into()); let expected_peer = TorrentPeerBuilder::default() .with_peer_id(peer::Id(peer_id.0)) @@ -696,7 +698,7 @@ mod tests { handle_announce(remote_addr, &request, &tracker).await.unwrap(); - let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; + let peers = tracker.get_torrent_peers(&info_hash.0.into()); assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); } @@ -773,8 +775,8 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; + use torrust_tracker_primitives::peer; - use crate::core::peer; use crate::servers::udp::connection_cookie::{into_connection_id, make}; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; @@ -801,7 +803,7 @@ mod tests { handle_announce(remote_addr, &request, &tracker).await.unwrap(); - let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; + let peers = tracker.get_torrent_peers(&info_hash.0.into()); let external_ip_in_tracker_configuration = tracker.get_maybe_external_ip().unwrap(); @@ -826,8 +828,9 @@ mod tests { Response, ResponsePeer, }; use mockall::predicate::eq; + use torrust_tracker_primitives::peer; - use crate::core::{self, peer, statistics}; + use crate::core::{self, statistics}; use crate::servers::udp::connection_cookie::{into_connection_id, make}; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; @@ -857,7 +860,7 @@ mod tests { handle_announce(remote_addr, &request, &tracker).await.unwrap(); - let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; + let peers = tracker.get_torrent_peers(&info_hash.0.into()); let expected_peer = TorrentPeerBuilder::default() .with_peer_id(peer::Id(peer_id.0)) @@ -921,7 +924,7 @@ mod tests { handle_announce(remote_addr, &request, &tracker).await.unwrap(); - let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; + let peers = tracker.get_torrent_peers(&info_hash.0.into()); // When using IPv6 the tracker converts the remote client ip into a IPv4 address assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); @@ -1038,7 +1041,7 @@ mod tests { handle_announce(remote_addr, &request, &tracker).await.unwrap(); - let peers = tracker.get_torrent_peers(&info_hash.0.into()).await; + let peers = tracker.get_torrent_peers(&info_hash.0.into()); let external_ip_in_tracker_configuration = tracker.get_maybe_external_ip().unwrap(); @@ -1063,9 +1066,10 @@ mod tests { InfoHash, NumberOfDownloads, NumberOfPeers, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; + use torrust_tracker_primitives::peer; use super::TorrentPeerBuilder; - use crate::core::{self, peer}; + use crate::core::{self}; use crate::servers::udp::connection_cookie::{into_connection_id, make}; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{public_tracker, sample_ipv4_remote_addr}; diff --git a/src/servers/udp/logging.rs b/src/servers/udp/logging.rs index a32afc6a3..9bbb48f6a 100644 --- a/src/servers/udp/logging.rs +++ b/src/servers/udp/logging.rs @@ -4,9 +4,9 @@ use std::net::SocketAddr; use std::time::Duration; use aquatic_udp_protocol::{Request, Response, TransactionId}; +use torrust_tracker_primitives::info_hash::InfoHash; use super::handlers::RequestId; -use crate::shared::bit_torrent::info_hash::InfoHash; pub fn log_request(request: &Request, request_id: &RequestId, server_socket_addr: &SocketAddr) { let action = map_action_name(request); diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index 8ef562086..fa4e8e926 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -62,7 +62,7 @@ //! ``` //! //! For the `Announce` request there is a wrapper struct [`AnnounceWrapper`](crate::servers::udp::request::AnnounceWrapper). -//! It was added to add an extra field with the internal [`InfoHash`](crate::shared::bit_torrent::info_hash::InfoHash) struct. +//! It was added to add an extra field with the internal [`InfoHash`](torrust_tracker_primitives::info_hash::InfoHash) struct. //! //! ### Connect //! @@ -345,7 +345,7 @@ //! packet. //! //! We are using a wrapper struct for the aquatic [`AnnounceRequest`](aquatic_udp_protocol::request::AnnounceRequest) -//! struct, because we have our internal [`InfoHash`](crate::shared::bit_torrent::info_hash::InfoHash) +//! struct, because we have our internal [`InfoHash`](torrust_tracker_primitives::info_hash::InfoHash) //! struct. //! //! ```text @@ -467,15 +467,15 @@ //! //! ### Scrape //! -//! The `scrape` request allows a peer to get [swarm metadata](crate::core::torrent::SwarmMetadata) +//! The `scrape` request allows a peer to get [swarm metadata](torrust_tracker_primitives::swarm_metadata::SwarmMetadata) //! for multiple torrents at the same time. //! -//! The response contains the [swarm metadata](crate::core::torrent::SwarmMetadata) +//! The response contains the [swarm metadata](torrust_tracker_primitives::swarm_metadata::SwarmMetadata) //! for that torrent: //! -//! - [complete](crate::core::torrent::SwarmMetadata::complete) -//! - [downloaded](crate::core::torrent::SwarmMetadata::downloaded) -//! - [incomplete](crate::core::torrent::SwarmMetadata::incomplete) +//! - [complete](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::complete) +//! - [downloaded](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::downloaded) +//! - [incomplete](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::incomplete) //! //! > **NOTICE**: up to about 74 torrents can be scraped at once. A full scrape //! can't be done with this protocol. This is a limitation of the UDP protocol. diff --git a/src/servers/udp/peer_builder.rs b/src/servers/udp/peer_builder.rs index 5168e2578..8c8fa10a5 100644 --- a/src/servers/udp/peer_builder.rs +++ b/src/servers/udp/peer_builder.rs @@ -1,11 +1,13 @@ //! Logic to extract the peer info from the announce request. use std::net::{IpAddr, SocketAddr}; +use torrust_tracker_primitives::announce_event::AnnounceEvent; +use torrust_tracker_primitives::{peer, NumberOfBytes}; + use super::request::AnnounceWrapper; -use crate::core::peer::{Id, Peer}; use crate::shared::clock::{Current, Time}; -/// Extracts the [`Peer`] info from the +/// Extracts the [`peer::Peer`] info from the /// announce request. /// /// # Arguments @@ -14,14 +16,14 @@ use crate::shared::clock::{Current, Time}; /// * `peer_ip` - The real IP address of the peer, not the one in the announce /// request. #[must_use] -pub fn from_request(announce_wrapper: &AnnounceWrapper, peer_ip: &IpAddr) -> Peer { - Peer { - peer_id: Id(announce_wrapper.announce_request.peer_id.0), +pub fn from_request(announce_wrapper: &AnnounceWrapper, peer_ip: &IpAddr) -> peer::Peer { + peer::Peer { + peer_id: peer::Id(announce_wrapper.announce_request.peer_id.0), peer_addr: SocketAddr::new(*peer_ip, announce_wrapper.announce_request.port.0), updated: Current::now(), - uploaded: announce_wrapper.announce_request.bytes_uploaded, - downloaded: announce_wrapper.announce_request.bytes_downloaded, - left: announce_wrapper.announce_request.bytes_left, - event: announce_wrapper.announce_request.event, + uploaded: NumberOfBytes(announce_wrapper.announce_request.bytes_uploaded.0), + downloaded: NumberOfBytes(announce_wrapper.announce_request.bytes_downloaded.0), + left: NumberOfBytes(announce_wrapper.announce_request.bytes_left.0), + event: AnnounceEvent::from_i32(announce_wrapper.announce_request.event.to_i32()), } } diff --git a/src/servers/udp/request.rs b/src/servers/udp/request.rs index f655fd36a..e172e03b1 100644 --- a/src/servers/udp/request.rs +++ b/src/servers/udp/request.rs @@ -6,8 +6,7 @@ //! Some of the type in this module are wrappers around the types in the //! `aquatic_udp_protocol` crate. use aquatic_udp_protocol::AnnounceRequest; - -use crate::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_primitives::info_hash::InfoHash; /// Wrapper around [`AnnounceRequest`]. pub struct AnnounceWrapper { diff --git a/src/shared/bit_torrent/common.rs b/src/shared/bit_torrent/common.rs index 9bf9dfd3c..9625b88e7 100644 --- a/src/shared/bit_torrent/common.rs +++ b/src/shared/bit_torrent/common.rs @@ -1,7 +1,6 @@ //! `BitTorrent` protocol primitive types //! //! [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use serde::{Deserialize, Serialize}; /// The maximum number of torrents that can be returned in an `scrape` response. @@ -33,23 +32,3 @@ enum Actions { Scrape = 2, Error = 3, } - -/// Announce events. Described on the -/// [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -#[derive(Serialize, Deserialize)] -#[serde(remote = "AnnounceEvent")] -pub enum AnnounceEventDef { - /// The peer has started downloading the torrent. - Started, - /// The peer has ceased downloading the torrent. - Stopped, - /// The peer has completed downloading the torrent. - Completed, - /// This is one of the announcements done at regular intervals. - None, -} - -/// Number of bytes downloaded, uploaded or pending to download (left) by the peer. -#[derive(Serialize, Deserialize)] -#[serde(remote = "NumberOfBytes")] -pub struct NumberOfBytesDef(pub i64); diff --git a/src/shared/bit_torrent/info_hash.rs b/src/shared/bit_torrent/info_hash.rs index 20c3cb38b..506c37758 100644 --- a/src/shared/bit_torrent/info_hash.rs +++ b/src/shared/bit_torrent/info_hash.rs @@ -129,169 +129,38 @@ //! You can hash that byte string with //! //! The result is a 20-char string: `5452869BE36F9F3350CCEE6B4544E7E76CAAADAB` -use std::panic::Location; -use thiserror::Error; +use torrust_tracker_primitives::info_hash::InfoHash; -/// `BitTorrent` Info Hash v1 -#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] -pub struct InfoHash(pub [u8; 20]); +pub mod fixture { + use std::hash::{DefaultHasher, Hash, Hasher}; -const INFO_HASH_BYTES_LEN: usize = 20; + use super::InfoHash; -impl InfoHash { - /// Create a new `InfoHash` from a byte slice. + /// Generate as semi-stable pseudo-random infohash /// - /// # Panics + /// Note: If the [`DefaultHasher`] implementation changes + /// so will the resulting info-hashes. /// - /// Will panic if byte slice does not contains the exact amount of bytes need for the `InfoHash`. - #[must_use] - pub fn from_bytes(bytes: &[u8]) -> Self { - assert_eq!(bytes.len(), INFO_HASH_BYTES_LEN); - let mut ret = Self([0u8; INFO_HASH_BYTES_LEN]); - ret.0.clone_from_slice(bytes); - ret - } - - /// Returns the `InfoHash` internal byte array. - #[must_use] - pub fn bytes(&self) -> [u8; 20] { - self.0 - } - - /// Returns the `InfoHash` as a hex string. + /// The results should not be relied upon between versions. #[must_use] - pub fn to_hex_string(&self) -> String { - self.to_string() - } -} - -impl std::fmt::Display for InfoHash { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let mut chars = [0u8; 40]; - binascii::bin2hex(&self.0, &mut chars).expect("failed to hexlify"); - write!(f, "{}", std::str::from_utf8(&chars).unwrap()) - } -} - -impl std::str::FromStr for InfoHash { - type Err = binascii::ConvertError; - - fn from_str(s: &str) -> Result { - let mut i = Self([0u8; 20]); - if s.len() != 40 { - return Err(binascii::ConvertError::InvalidInputLength); - } - binascii::hex2bin(s.as_bytes(), &mut i.0)?; - Ok(i) - } -} - -impl Ord for InfoHash { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.0.cmp(&other.0) - } -} - -impl std::cmp::PartialOrd for InfoHash { - fn partial_cmp(&self, other: &InfoHash) -> Option { - Some(self.cmp(other)) - } -} + pub fn gen_seeded_infohash(seed: &u64) -> InfoHash { + let mut buf_a: [[u8; 8]; 4] = Default::default(); + let mut buf_b = InfoHash::default(); -impl std::convert::From<&[u8]> for InfoHash { - fn from(data: &[u8]) -> InfoHash { - assert_eq!(data.len(), 20); - let mut ret = InfoHash([0u8; 20]); - ret.0.clone_from_slice(data); - ret - } -} - -impl std::convert::From<[u8; 20]> for InfoHash { - fn from(val: [u8; 20]) -> Self { - InfoHash(val) - } -} - -/// Errors that can occur when converting from a `Vec` to an `InfoHash`. -#[derive(Error, Debug)] -pub enum ConversionError { - /// Not enough bytes for infohash. An infohash is 20 bytes. - #[error("not enough bytes for infohash: {message} {location}")] - NotEnoughBytes { - location: &'static Location<'static>, - message: String, - }, - /// Too many bytes for infohash. An infohash is 20 bytes. - #[error("too many bytes for infohash: {message} {location}")] - TooManyBytes { - location: &'static Location<'static>, - message: String, - }, -} - -impl TryFrom> for InfoHash { - type Error = ConversionError; + let mut hasher = DefaultHasher::new(); + seed.hash(&mut hasher); - fn try_from(bytes: Vec) -> Result { - if bytes.len() < INFO_HASH_BYTES_LEN { - return Err(ConversionError::NotEnoughBytes { - location: Location::caller(), - message: format! {"got {} bytes, expected {}", bytes.len(), INFO_HASH_BYTES_LEN}, - }); - } - if bytes.len() > INFO_HASH_BYTES_LEN { - return Err(ConversionError::TooManyBytes { - location: Location::caller(), - message: format! {"got {} bytes, expected {}", bytes.len(), INFO_HASH_BYTES_LEN}, - }); + for u in &mut buf_a { + seed.hash(&mut hasher); + *u = hasher.finish().to_le_bytes(); } - Ok(Self::from_bytes(&bytes)) - } -} -impl serde::ser::Serialize for InfoHash { - fn serialize(&self, serializer: S) -> Result { - let mut buffer = [0u8; 40]; - let bytes_out = binascii::bin2hex(&self.0, &mut buffer).ok().unwrap(); - let str_out = std::str::from_utf8(bytes_out).unwrap(); - serializer.serialize_str(str_out) - } -} - -impl<'de> serde::de::Deserialize<'de> for InfoHash { - fn deserialize>(des: D) -> Result { - des.deserialize_str(InfoHashVisitor) - } -} - -struct InfoHashVisitor; - -impl<'v> serde::de::Visitor<'v> for InfoHashVisitor { - type Value = InfoHash; - - fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(formatter, "a 40 character long hash") - } - - fn visit_str(self, v: &str) -> Result { - if v.len() != 40 { - return Err(serde::de::Error::invalid_value( - serde::de::Unexpected::Str(v), - &"a 40 character long string", - )); + for (a, b) in buf_a.iter().flat_map(|a| a.iter()).zip(buf_b.0.iter_mut()) { + *b = *a; } - let mut res = InfoHash([0u8; 20]); - - if binascii::hex2bin(v.as_bytes(), &mut res.0).is_err() { - return Err(serde::de::Error::invalid_value( - serde::de::Unexpected::Str(v), - &"a hexadecimal string", - )); - }; - Ok(res) + buf_b } } diff --git a/src/shared/bit_torrent/tracker/http/client/requests/announce.rs b/src/shared/bit_torrent/tracker/http/client/requests/announce.rs index 6cae79888..b872e76e9 100644 --- a/src/shared/bit_torrent/tracker/http/client/requests/announce.rs +++ b/src/shared/bit_torrent/tracker/http/client/requests/announce.rs @@ -3,9 +3,9 @@ use std::net::{IpAddr, Ipv4Addr}; use std::str::FromStr; use serde_repr::Serialize_repr; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer; -use crate::core::peer::Id; -use crate::shared::bit_torrent::info_hash::InfoHash; use crate::shared::bit_torrent::tracker::http::{percent_encode_byte_array, ByteArray20}; pub struct Query { @@ -99,7 +99,7 @@ impl QueryBuilder { peer_addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 88)), downloaded: 0, uploaded: 0, - peer_id: Id(*b"-qB00000000000000001").0, + peer_id: peer::Id(*b"-qB00000000000000001").0, port: 17548, left: 0, event: Some(Event::Completed), @@ -117,7 +117,7 @@ impl QueryBuilder { } #[must_use] - pub fn with_peer_id(mut self, peer_id: &Id) -> Self { + pub fn with_peer_id(mut self, peer_id: &peer::Id) -> Self { self.announce_query.peer_id = peer_id.0; self } diff --git a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs index 4fa49eed6..4d12fc2d2 100644 --- a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs +++ b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs @@ -2,7 +2,8 @@ use std::error::Error; use std::fmt::{self}; use std::str::FromStr; -use crate::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_primitives::info_hash::InfoHash; + use crate::shared::bit_torrent::tracker::http::{percent_encode_byte_array, ByteArray20}; pub struct Query { diff --git a/src/shared/bit_torrent/tracker/http/client/responses/announce.rs b/src/shared/bit_torrent/tracker/http/client/responses/announce.rs index e75cc6671..15ec446cb 100644 --- a/src/shared/bit_torrent/tracker/http/client/responses/announce.rs +++ b/src/shared/bit_torrent/tracker/http/client/responses/announce.rs @@ -1,8 +1,7 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use serde::{Deserialize, Serialize}; - -use crate::core::peer::Peer; +use torrust_tracker_primitives::peer; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Announce { @@ -23,8 +22,8 @@ pub struct DictionaryPeer { pub port: u16, } -impl From for DictionaryPeer { - fn from(peer: Peer) -> Self { +impl From for DictionaryPeer { + fn from(peer: peer::Peer) -> Self { DictionaryPeer { peer_id: peer.peer_id.to_bytes().to_vec(), ip: peer.peer_addr.ip().to_string(), diff --git a/src/shared/clock/mod.rs b/src/shared/clock/mod.rs index 6d9d4112a..a73878466 100644 --- a/src/shared/clock/mod.rs +++ b/src/shared/clock/mod.rs @@ -31,9 +31,7 @@ use std::str::FromStr; use std::time::Duration; use chrono::{DateTime, Utc}; - -/// Duration since the Unix Epoch. -pub type DurationSinceUnixEpoch = Duration; +use torrust_tracker_primitives::DurationSinceUnixEpoch; /// Clock types. #[derive(Debug)] diff --git a/src/shared/clock/time_extent.rs b/src/shared/clock/time_extent.rs index a5a359e52..168224eda 100644 --- a/src/shared/clock/time_extent.rs +++ b/src/shared/clock/time_extent.rs @@ -542,9 +542,11 @@ mod test { mod make_time_extent { mod fn_now { + use torrust_tracker_primitives::DurationSinceUnixEpoch; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; use crate::shared::clock::time_extent::{Base, DefaultTimeExtentMaker, Make, TimeExtent}; - use crate::shared::clock::{Current, DurationSinceUnixEpoch, StoppedTime}; + use crate::shared::clock::{Current, StoppedTime}; #[test] fn it_should_give_a_time_extent() { @@ -582,9 +584,11 @@ mod test { mod fn_now_after { use std::time::Duration; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; use crate::shared::clock::time_extent::{Base, DefaultTimeExtentMaker, Make}; - use crate::shared::clock::{Current, DurationSinceUnixEpoch, StoppedTime}; + use crate::shared::clock::{Current, StoppedTime}; #[test] fn it_should_give_a_time_extent() { @@ -621,8 +625,10 @@ mod test { mod fn_now_before { use std::time::Duration; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + use crate::shared::clock::time_extent::{Base, DefaultTimeExtentMaker, Make, TimeExtent}; - use crate::shared::clock::{Current, DurationSinceUnixEpoch, StoppedTime}; + use crate::shared::clock::{Current, StoppedTime}; #[test] fn it_should_give_a_time_extent() { diff --git a/src/shared/clock/utils.rs b/src/shared/clock/utils.rs index 94d88d288..8b1378917 100644 --- a/src/shared/clock/utils.rs +++ b/src/shared/clock/utils.rs @@ -1,11 +1 @@ -//! It contains helper functions related to time. -use super::DurationSinceUnixEpoch; -/// Serializes a `DurationSinceUnixEpoch` as a Unix timestamp in milliseconds. -/// # Errors -/// -/// Will return `serde::Serializer::Error` if unable to serialize the `unix_time_value`. -pub fn ser_unix_time_value(unix_time_value: &DurationSinceUnixEpoch, ser: S) -> Result { - #[allow(clippy::cast_possible_truncation)] - ser.serialize_u64(unix_time_value.as_millis() as u64) -} diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 186b7ea3b..8d91f3ae8 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -4,12 +4,12 @@ use std::sync::Arc; use futures::executor::block_on; use torrust_tracker::bootstrap::app::initialize_with_configuration; use torrust_tracker::bootstrap::jobs::make_rust_tls; -use torrust_tracker::core::peer::Peer; use torrust_tracker::core::Tracker; use torrust_tracker::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker::servers::registar::Registar; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker_configuration::{Configuration, HttpApi}; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer; use super::connection_info::ConnectionInfo; @@ -22,7 +22,7 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker - pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &Peer) { + pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; } } diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index 54263f8b8..af6587673 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -1,8 +1,8 @@ use std::str::FromStr; -use torrust_tracker::core::peer::fixture::PeerBuilder; use torrust_tracker::servers::apis::v1::context::stats::resources::Stats; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index ee701ecc4..d54935f80 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -1,9 +1,9 @@ use std::str::FromStr; -use torrust_tracker::core::peer::fixture::PeerBuilder; use torrust_tracker::servers::apis::v1::context::torrent::resources::peer::Peer; use torrust_tracker::servers::apis::v1::context::torrent::resources::torrent::{self, Torrent}; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use crate::common::http::{Query, QueryParam}; diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index 358a4a19e..29064ec9e 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -1,6 +1,6 @@ use std::str::FromStr; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 326f4e534..5638713aa 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -3,12 +3,12 @@ use std::sync::Arc; use futures::executor::block_on; use torrust_tracker::bootstrap::app::initialize_with_configuration; use torrust_tracker::bootstrap::jobs::make_rust_tls; -use torrust_tracker::core::peer::Peer; use torrust_tracker::core::Tracker; use torrust_tracker::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker::servers::registar::Registar; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker_configuration::{Configuration, HttpTracker}; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer; pub struct Environment { pub config: Arc, @@ -19,7 +19,7 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker - pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &Peer) { + pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; } } diff --git a/tests/servers/http/requests/announce.rs b/tests/servers/http/requests/announce.rs index 2cc615d0f..061990621 100644 --- a/tests/servers/http/requests/announce.rs +++ b/tests/servers/http/requests/announce.rs @@ -3,8 +3,8 @@ use std::net::{IpAddr, Ipv4Addr}; use std::str::FromStr; use serde_repr::Serialize_repr; -use torrust_tracker::core::peer::Id; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer; use crate::servers::http::{percent_encode_byte_array, ByteArray20}; @@ -93,7 +93,7 @@ impl QueryBuilder { peer_addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 88)), downloaded: 0, uploaded: 0, - peer_id: Id(*b"-qB00000000000000001").0, + peer_id: peer::Id(*b"-qB00000000000000001").0, port: 17548, left: 0, event: Some(Event::Completed), @@ -109,7 +109,7 @@ impl QueryBuilder { self } - pub fn with_peer_id(mut self, peer_id: &Id) -> Self { + pub fn with_peer_id(mut self, peer_id: &peer::Id) -> Self { self.announce_query.peer_id = peer_id.0; self } diff --git a/tests/servers/http/requests/scrape.rs b/tests/servers/http/requests/scrape.rs index 264c72c33..f66605855 100644 --- a/tests/servers/http/requests/scrape.rs +++ b/tests/servers/http/requests/scrape.rs @@ -1,7 +1,7 @@ use std::fmt; use std::str::FromStr; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; +use torrust_tracker_primitives::info_hash::InfoHash; use crate::servers::http::{percent_encode_byte_array, ByteArray20}; diff --git a/tests/servers/http/responses/announce.rs b/tests/servers/http/responses/announce.rs index 968c327eb..2b49b4405 100644 --- a/tests/servers/http/responses/announce.rs +++ b/tests/servers/http/responses/announce.rs @@ -1,7 +1,7 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use serde::{Deserialize, Serialize}; -use torrust_tracker::core::peer::Peer; +use torrust_tracker_primitives::peer; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Announce { @@ -22,8 +22,8 @@ pub struct DictionaryPeer { pub port: u16, } -impl From for DictionaryPeer { - fn from(peer: Peer) -> Self { +impl From for DictionaryPeer { + fn from(peer: peer::Peer) -> Self { DictionaryPeer { peer_id: peer.peer_id.to_bytes().to_vec(), ip: peer.peer_addr.ip().to_string(), diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index be285dcd7..a7962db0f 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -89,9 +89,9 @@ mod for_all_config_modes { use local_ip_address::local_ip; use reqwest::{Response, StatusCode}; use tokio::net::TcpListener; - use torrust_tracker::core::peer; - use torrust_tracker::core::peer::fixture::PeerBuilder; - use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; + use torrust_tracker_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::peer; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use crate::common::fixtures::invalid_info_hashes; @@ -750,7 +750,7 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.tracker.get_torrent_peers(&info_hash).await; + let peers = env.tracker.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), client_ip); @@ -786,7 +786,7 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.tracker.get_torrent_peers(&info_hash).await; + let peers = env.tracker.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), env.tracker.get_maybe_external_ip().unwrap()); @@ -826,7 +826,7 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.tracker.get_torrent_peers(&info_hash).await; + let peers = env.tracker.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), env.tracker.get_maybe_external_ip().unwrap()); @@ -864,7 +864,7 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.tracker.get_torrent_peers(&info_hash).await; + let peers = env.tracker.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), IpAddr::from_str("150.172.238.178").unwrap()); @@ -887,9 +887,9 @@ mod for_all_config_modes { use std::str::FromStr; use tokio::net::TcpListener; - use torrust_tracker::core::peer; - use torrust_tracker::core::peer::fixture::PeerBuilder; - use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; + use torrust_tracker_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::peer; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use crate::common::fixtures::invalid_info_hashes; @@ -1113,7 +1113,7 @@ mod configured_as_whitelisted { mod and_receiving_an_announce_request { use std::str::FromStr; - use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; + use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::servers::http::asserts::{assert_is_announce_response, assert_torrent_not_in_whitelist_error_response}; @@ -1160,9 +1160,9 @@ mod configured_as_whitelisted { mod receiving_an_scrape_request { use std::str::FromStr; - use torrust_tracker::core::peer; - use torrust_tracker::core::peer::fixture::PeerBuilder; - use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; + use torrust_tracker_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::peer; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use crate::servers::http::asserts::assert_scrape_response; @@ -1253,7 +1253,7 @@ mod configured_as_private { use std::time::Duration; use torrust_tracker::core::auth::Key; - use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; + use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::servers::http::asserts::{assert_authentication_error_response, assert_is_announce_response}; @@ -1329,9 +1329,9 @@ mod configured_as_private { use std::time::Duration; use torrust_tracker::core::auth::Key; - use torrust_tracker::core::peer; - use torrust_tracker::core::peer::fixture::PeerBuilder; - use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; + use torrust_tracker_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::peer; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use crate::servers::http::asserts::{assert_authentication_error_response, assert_scrape_response}; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index da7705016..12f4aeb9e 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -2,12 +2,12 @@ use std::net::SocketAddr; use std::sync::Arc; use torrust_tracker::bootstrap::app::initialize_with_configuration; -use torrust_tracker::core::peer::Peer; use torrust_tracker::core::Tracker; use torrust_tracker::servers::registar::Registar; use torrust_tracker::servers::udp::server::{Launcher, Running, Stopped, UdpServer}; -use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker_configuration::{Configuration, UdpTracker}; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer; pub struct Environment { pub config: Arc, @@ -19,7 +19,7 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker #[allow(dead_code)] - pub async fn add_torrent(&self, info_hash: &InfoHash, peer: &Peer) { + pub async fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; } } From 03883c00d606ba0e5d23849852b1aad7be3c1e03 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 3 Mar 2024 03:56:06 +0800 Subject: [PATCH 0270/1297] dev: repository benchmark uses criterion --- Cargo.lock | 4 +- packages/torrent-repository/Cargo.toml | 8 +- .../benches/helpers/args.rs | 15 -- .../benches/helpers/asyn.rs | 199 ++++++++---------- .../torrent-repository/benches/helpers/mod.rs | 1 - .../benches/helpers/sync.rs | 179 +++++++--------- .../benches/helpers/utils.rs | 33 --- .../benches/repository-benchmark.rs | 187 ---------------- .../benches/repository_benchmark.rs | 191 +++++++++++++++++ 9 files changed, 363 insertions(+), 454 deletions(-) delete mode 100644 packages/torrent-repository/benches/helpers/args.rs delete mode 100644 packages/torrent-repository/benches/repository-benchmark.rs create mode 100644 packages/torrent-repository/benches/repository_benchmark.rs diff --git a/Cargo.lock b/Cargo.lock index 8ec922448..b8437326c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -762,6 +762,7 @@ dependencies = [ "ciborium", "clap", "criterion-plot", + "futures", "is-terminal", "itertools 0.10.5", "num-traits", @@ -774,6 +775,7 @@ dependencies = [ "serde_derive", "serde_json", "tinytemplate", + "tokio", "walkdir", ] @@ -3557,7 +3559,7 @@ dependencies = [ name = "torrust-tracker-torrent-repository" version = "3.0.0-alpha.12-develop" dependencies = [ - "clap", + "criterion", "futures", "serde", "tokio", diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 0df82a2c6..b53b9a15e 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -16,9 +16,15 @@ rust-version.workspace = true version.workspace = true [dependencies] -clap = { version = "4.4.8", features = ["derive"] } futures = "0.3.29" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } serde = { version = "1", features = ["derive"] } + +[dev-dependencies] +criterion = { version = "0", features = ["async_tokio"] } + +[[bench]] +harness = false +name = "repository_benchmark" diff --git a/packages/torrent-repository/benches/helpers/args.rs b/packages/torrent-repository/benches/helpers/args.rs deleted file mode 100644 index 3a38c55a7..000000000 --- a/packages/torrent-repository/benches/helpers/args.rs +++ /dev/null @@ -1,15 +0,0 @@ -use clap::Parser; - -#[derive(Parser, Debug)] -#[command(author, version, about, long_about = None)] -pub struct Args { - /// Amount of benchmark worker threads - #[arg(short, long)] - pub threads: usize, - /// Amount of time in ns a thread will sleep to simulate a client response after handling a task - #[arg(short, long)] - pub sleep: Option, - /// Compare with old implementations of the torrent repository - #[arg(short, long)] - pub compare: Option, -} diff --git a/packages/torrent-repository/benches/helpers/asyn.rs b/packages/torrent-repository/benches/helpers/asyn.rs index 4fb37104f..80f70cdc2 100644 --- a/packages/torrent-repository/benches/helpers/asyn.rs +++ b/packages/torrent-repository/benches/helpers/asyn.rs @@ -1,182 +1,155 @@ use std::sync::Arc; -use std::time::Duration; +use std::time::{Duration, Instant}; -use clap::Parser; use futures::stream::FuturesUnordered; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_torrent_repository::repository::RepositoryAsync; -use super::args::Args; -use super::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; +use super::utils::{generate_unique_info_hashes, DEFAULT_PEER}; -pub async fn add_one_torrent(samples: usize) -> (Duration, Duration) +pub async fn add_one_torrent(samples: u64) -> Duration where V: RepositoryAsync + Default, { - let mut results: Vec = Vec::with_capacity(samples); + let start = Instant::now(); for _ in 0..samples { let torrent_repository = V::default(); let info_hash = InfoHash([0; 20]); - let start_time = std::time::Instant::now(); - torrent_repository .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) .await; - - let result = start_time.elapsed(); - - results.push(result); } - get_average_and_adjusted_average_from_results(results) + start.elapsed() } // Add one torrent ten thousand times in parallel (depending on the set worker threads) -pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: u64, sleep: Option) -> Duration where V: RepositoryAsync + Default, Arc: Clone + Send + Sync + 'static, { - let args = Args::parse(); - let mut results: Vec = Vec::with_capacity(samples); - - for _ in 0..samples { - let torrent_repository = Arc::::default(); - let info_hash: &'static InfoHash = &InfoHash([0; 20]); - let handles = FuturesUnordered::new(); - - // Add the torrent/peer to the torrent repository - torrent_repository - .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) - .await; + let torrent_repository = Arc::::default(); + let info_hash: &'static InfoHash = &InfoHash([0; 20]); + let handles = FuturesUnordered::new(); - let start_time = std::time::Instant::now(); + // Add the torrent/peer to the torrent repository + torrent_repository + .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) + .await; - for _ in 0..10_000 { - let torrent_repository_clone = torrent_repository.clone(); + let start = Instant::now(); - let handle = runtime.spawn(async move { - torrent_repository_clone - .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) - .await; - - if let Some(sleep_time) = args.sleep { - let start_time = std::time::Instant::now(); - - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); + for _ in 0..samples { + let torrent_repository_clone = torrent_repository.clone(); - handles.push(handle); - } + let handle = runtime.spawn(async move { + torrent_repository_clone + .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) + .await; - // Await all tasks - futures::future::join_all(handles).await; + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); - let result = start_time.elapsed(); + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); - results.push(result); + handles.push(handle); } - get_average_and_adjusted_average_from_results(results) + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() } // Add ten thousand torrents in parallel (depending on the set worker threads) -pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn add_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: u64, + sleep: Option, +) -> Duration where V: RepositoryAsync + Default, Arc: Clone + Send + Sync + 'static, { - let args = Args::parse(); - let mut results: Vec = Vec::with_capacity(samples); - - for _ in 0..samples { - let torrent_repository = Arc::::default(); - let info_hashes = generate_unique_info_hashes(10_000); - let handles = FuturesUnordered::new(); - - let start_time = std::time::Instant::now(); + let torrent_repository = Arc::::default(); + let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in a usize")); + let handles = FuturesUnordered::new(); - for info_hash in info_hashes { - let torrent_repository_clone = torrent_repository.clone(); + let start = Instant::now(); - let handle = runtime.spawn(async move { - torrent_repository_clone - .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) - .await; + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); - if let Some(sleep_time) = args.sleep { - let start_time = std::time::Instant::now(); - - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); - - handles.push(handle); - } + let handle = runtime.spawn(async move { + torrent_repository_clone + .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) + .await; - // Await all tasks - futures::future::join_all(handles).await; + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); - let result = start_time.elapsed(); + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); - results.push(result); + handles.push(handle); } - get_average_and_adjusted_average_from_results(results) + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() } // Async update ten thousand torrents in parallel (depending on the set worker threads) -pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: u64, + sleep: Option, +) -> Duration where V: RepositoryAsync + Default, Arc: Clone + Send + Sync + 'static, { - let args = Args::parse(); - let mut results: Vec = Vec::with_capacity(samples); - - for _ in 0..samples { - let torrent_repository = Arc::::default(); - let info_hashes = generate_unique_info_hashes(10_000); - let handles = FuturesUnordered::new(); - - // Add the torrents/peers to the torrent repository - for info_hash in &info_hashes { - torrent_repository - .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) - .await; - } + let torrent_repository = Arc::::default(); + let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in usize")); + let handles = FuturesUnordered::new(); - let start_time = std::time::Instant::now(); - - for info_hash in info_hashes { - let torrent_repository_clone = torrent_repository.clone(); - - let handle = runtime.spawn(async move { - torrent_repository_clone - .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) - .await; + // Add the torrents/peers to the torrent repository + for info_hash in &info_hashes { + torrent_repository + .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) + .await; + } - if let Some(sleep_time) = args.sleep { - let start_time = std::time::Instant::now(); + let start = Instant::now(); - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); - handles.push(handle); - } + let handle = runtime.spawn(async move { + torrent_repository_clone + .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) + .await; - // Await all tasks - futures::future::join_all(handles).await; + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); - let result = start_time.elapsed(); + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); - results.push(result); + handles.push(handle); } - get_average_and_adjusted_average_from_results(results) + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() } diff --git a/packages/torrent-repository/benches/helpers/mod.rs b/packages/torrent-repository/benches/helpers/mod.rs index 758c123bd..1026aa4bf 100644 --- a/packages/torrent-repository/benches/helpers/mod.rs +++ b/packages/torrent-repository/benches/helpers/mod.rs @@ -1,4 +1,3 @@ -pub mod args; pub mod asyn; pub mod sync; pub mod utils; diff --git a/packages/torrent-repository/benches/helpers/sync.rs b/packages/torrent-repository/benches/helpers/sync.rs index aa2f8188a..0523f4141 100644 --- a/packages/torrent-repository/benches/helpers/sync.rs +++ b/packages/torrent-repository/benches/helpers/sync.rs @@ -1,172 +1,145 @@ use std::sync::Arc; -use std::time::Duration; +use std::time::{Duration, Instant}; -use clap::Parser; use futures::stream::FuturesUnordered; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_torrent_repository::repository::Repository; -use super::args::Args; -use super::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER}; +use super::utils::{generate_unique_info_hashes, DEFAULT_PEER}; // Simply add one torrent #[must_use] -pub fn add_one_torrent(samples: usize) -> (Duration, Duration) +pub fn add_one_torrent(samples: u64) -> Duration where V: Repository + Default, { - let mut results: Vec = Vec::with_capacity(samples); + let start = Instant::now(); for _ in 0..samples { let torrent_repository = V::default(); let info_hash = InfoHash([0; 20]); - let start_time = std::time::Instant::now(); - torrent_repository.update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER); - - let result = start_time.elapsed(); - - results.push(result); } - get_average_and_adjusted_average_from_results(results) + start.elapsed() } // Add one torrent ten thousand times in parallel (depending on the set worker threads) -pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: u64, sleep: Option) -> Duration where V: Repository + Default, Arc: Clone + Send + Sync + 'static, { - let args = Args::parse(); - let mut results: Vec = Vec::with_capacity(samples); - - for _ in 0..samples { - let torrent_repository = Arc::::default(); - let info_hash: &'static InfoHash = &InfoHash([0; 20]); - let handles = FuturesUnordered::new(); - - // Add the torrent/peer to the torrent repository - torrent_repository.update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER); + let torrent_repository = Arc::::default(); + let info_hash: &'static InfoHash = &InfoHash([0; 20]); + let handles = FuturesUnordered::new(); - let start_time = std::time::Instant::now(); + // Add the torrent/peer to the torrent repository + torrent_repository.update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER); - for _ in 0..10_000 { - let torrent_repository_clone = torrent_repository.clone(); + let start = Instant::now(); - let handle = runtime.spawn(async move { - torrent_repository_clone.update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER); - - if let Some(sleep_time) = args.sleep { - let start_time = std::time::Instant::now(); - - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); + for _ in 0..samples { + let torrent_repository_clone = torrent_repository.clone(); - handles.push(handle); - } + let handle = runtime.spawn(async move { + torrent_repository_clone.update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER); - // Await all tasks - futures::future::join_all(handles).await; + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); - let result = start_time.elapsed(); + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); - results.push(result); + handles.push(handle); } - get_average_and_adjusted_average_from_results(results) + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() } // Add ten thousand torrents in parallel (depending on the set worker threads) -pub async fn add_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn add_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: u64, + sleep: Option, +) -> Duration where V: Repository + Default, Arc: Clone + Send + Sync + 'static, { - let args = Args::parse(); - let mut results: Vec = Vec::with_capacity(samples); - - for _ in 0..samples { - let torrent_repository = Arc::::default(); - let info_hashes = generate_unique_info_hashes(10_000); - let handles = FuturesUnordered::new(); + let torrent_repository = Arc::::default(); + let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in a usize")); + let handles = FuturesUnordered::new(); - let start_time = std::time::Instant::now(); + let start = Instant::now(); - for info_hash in info_hashes { - let torrent_repository_clone = torrent_repository.clone(); + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); - let handle = runtime.spawn(async move { - torrent_repository_clone.update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER); + let handle = runtime.spawn(async move { + torrent_repository_clone.update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER); - if let Some(sleep_time) = args.sleep { - let start_time = std::time::Instant::now(); + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); - handles.push(handle); - } - - // Await all tasks - futures::future::join_all(handles).await; - - let result = start_time.elapsed(); - - results.push(result); + handles.push(handle); } - get_average_and_adjusted_average_from_results(results) + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() } // Update ten thousand torrents in parallel (depending on the set worker threads) -pub async fn update_multiple_torrents_in_parallel(runtime: &tokio::runtime::Runtime, samples: usize) -> (Duration, Duration) +pub async fn update_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: u64, + sleep: Option, +) -> Duration where V: Repository + Default, Arc: Clone + Send + Sync + 'static, { - let args = Args::parse(); - let mut results: Vec = Vec::with_capacity(samples); - - for _ in 0..samples { - let torrent_repository = Arc::::default(); - let info_hashes = generate_unique_info_hashes(10_000); - let handles = FuturesUnordered::new(); + let torrent_repository = Arc::::default(); + let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in usize")); + let handles = FuturesUnordered::new(); - // Add the torrents/peers to the torrent repository - for info_hash in &info_hashes { - torrent_repository.update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER); - } - - let start_time = std::time::Instant::now(); - - for info_hash in info_hashes { - let torrent_repository_clone = torrent_repository.clone(); - - let handle = runtime.spawn(async move { - torrent_repository_clone.update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER); + // Add the torrents/peers to the torrent repository + for info_hash in &info_hashes { + torrent_repository.update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER); + } - if let Some(sleep_time) = args.sleep { - let start_time = std::time::Instant::now(); + let start = Instant::now(); - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); - handles.push(handle); - } + let handle = runtime.spawn(async move { + torrent_repository_clone.update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER); - // Await all tasks - futures::future::join_all(handles).await; + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); - let result = start_time.elapsed(); + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); - results.push(result); + handles.push(handle); } - get_average_and_adjusted_average_from_results(results) + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() } diff --git a/packages/torrent-repository/benches/helpers/utils.rs b/packages/torrent-repository/benches/helpers/utils.rs index aed9f40cf..170194806 100644 --- a/packages/torrent-repository/benches/helpers/utils.rs +++ b/packages/torrent-repository/benches/helpers/utils.rs @@ -1,6 +1,5 @@ use std::collections::HashSet; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use std::time::Duration; use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::info_hash::InfoHash; @@ -39,35 +38,3 @@ pub fn generate_unique_info_hashes(size: usize) -> Vec { result.into_iter().collect() } - -#[must_use] -pub fn within_acceptable_range(test: &Duration, norm: &Duration) -> bool { - let test_secs = test.as_secs_f64(); - let norm_secs = norm.as_secs_f64(); - - // Calculate the upper and lower bounds for the 10% tolerance - let tolerance = norm_secs * 0.1; - - // Calculate the upper and lower limits - let upper_limit = norm_secs + tolerance; - let lower_limit = norm_secs - tolerance; - - test_secs < upper_limit && test_secs > lower_limit -} - -#[must_use] -pub fn get_average_and_adjusted_average_from_results(mut results: Vec) -> (Duration, Duration) { - #[allow(clippy::cast_possible_truncation)] - let average = results.iter().sum::() / results.len() as u32; - - results.retain(|result| within_acceptable_range(result, &average)); - - let mut adjusted_average = Duration::from_nanos(0); - - #[allow(clippy::cast_possible_truncation)] - if results.len() > 1 { - adjusted_average = results.iter().sum::() / results.len() as u32; - } - - (average, adjusted_average) -} diff --git a/packages/torrent-repository/benches/repository-benchmark.rs b/packages/torrent-repository/benches/repository-benchmark.rs deleted file mode 100644 index bff34b256..000000000 --- a/packages/torrent-repository/benches/repository-benchmark.rs +++ /dev/null @@ -1,187 +0,0 @@ -mod helpers; - -use clap::Parser; -use torrust_tracker_torrent_repository::{ - TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, - TorrentsRwLockTokioMutexTokio, -}; - -use crate::helpers::args::Args; -use crate::helpers::{asyn, sync}; - -#[allow(clippy::too_many_lines)] -#[allow(clippy::print_literal)] -fn main() { - let args = Args::parse(); - - // Add 1 to worker_threads since we need a thread that awaits the benchmark - let rt = tokio::runtime::Builder::new_multi_thread() - .worker_threads(args.threads + 1) - .enable_time() - .build() - .unwrap(); - - println!("TorrentsRwLockTokio"); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_one_torrent", - rt.block_on(asyn::add_one_torrent::(1_000_000)) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::(&rt, 10)) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::(&rt, 10)) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) - ); - - if let Some(true) = args.compare { - println!(); - - println!("TorrentsRwLockStd"); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_one_torrent", - sync::add_one_torrent::(1_000_000) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "update_one_torrent_in_parallel", - rt.block_on(sync::update_one_torrent_in_parallel::(&rt, 10)) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_multiple_torrents_in_parallel", - rt.block_on(sync::add_multiple_torrents_in_parallel::(&rt, 10)) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "update_multiple_torrents_in_parallel", - rt.block_on(sync::update_multiple_torrents_in_parallel::(&rt, 10)) - ); - - println!(); - - println!("TorrentsRwLockStdMutexStd"); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_one_torrent", - sync::add_one_torrent::(1_000_000) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "update_one_torrent_in_parallel", - rt.block_on(sync::update_one_torrent_in_parallel::(&rt, 10)) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_multiple_torrents_in_parallel", - rt.block_on(sync::add_multiple_torrents_in_parallel::( - &rt, 10 - )) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "update_multiple_torrents_in_parallel", - rt.block_on(sync::update_multiple_torrents_in_parallel::( - &rt, 10 - )) - ); - - println!(); - - println!("TorrentsRwLockStdMutexTokio"); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_one_torrent", - rt.block_on(asyn::add_one_torrent::(1_000_000)) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::( - &rt, 10 - )) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::( - &rt, 10 - )) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::( - &rt, 10 - )) - ); - - println!(); - - println!("TorrentsRwLockTokioMutexStd"); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_one_torrent", - rt.block_on(asyn::add_one_torrent::(1_000_000)) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::( - &rt, 10 - )) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::( - &rt, 10 - )) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::( - &rt, 10 - )) - ); - - println!(); - - println!("TorrentsRwLockTokioMutexTokio"); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_one_torrent", - rt.block_on(asyn::add_one_torrent::(1_000_000)) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "update_one_torrent_in_parallel", - rt.block_on(asyn::update_one_torrent_in_parallel::( - &rt, 10 - )) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "add_multiple_torrents_in_parallel", - rt.block_on(asyn::add_multiple_torrents_in_parallel::( - &rt, 10 - )) - ); - println!( - "{}: Avg/AdjAvg: {:?}", - "update_multiple_torrents_in_parallel", - rt.block_on(asyn::update_multiple_torrents_in_parallel::(&rt, 10)) - ); - } -} diff --git a/packages/torrent-repository/benches/repository_benchmark.rs b/packages/torrent-repository/benches/repository_benchmark.rs new file mode 100644 index 000000000..a3684c8e2 --- /dev/null +++ b/packages/torrent-repository/benches/repository_benchmark.rs @@ -0,0 +1,191 @@ +use std::time::Duration; + +mod helpers; + +use criterion::{criterion_group, criterion_main, Criterion}; +use torrust_tracker_torrent_repository::{ + TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, + TorrentsRwLockTokioMutexTokio, +}; + +use crate::helpers::{asyn, sync}; + +fn add_one_torrent(c: &mut Criterion) { + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("add_one_torrent"); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_millis(1000)); + + group.bench_function("RwLockStd", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.bench_function("RwLockStdMutexStd", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.bench_function("RwLockStdMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(asyn::add_one_torrent::); + }); + + group.bench_function("RwLockTokio", |b| { + b.to_async(&rt).iter_custom(asyn::add_one_torrent::); + }); + + group.bench_function("RwLockTokioMutexStd", |b| { + b.to_async(&rt) + .iter_custom(asyn::add_one_torrent::); + }); + + group.bench_function("RwLockTokioMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(asyn::add_one_torrent::); + }); + + group.finish(); +} + +fn add_multiple_torrents_in_parallel(c: &mut Criterion) { + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("add_multiple_torrents_in_parallel"); + + //group.sampling_mode(criterion::SamplingMode::Flat); + //group.sample_size(10); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_millis(1000)); + + group.bench_function("RwLockStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.finish(); +} + +fn update_one_torrent_in_parallel(c: &mut Criterion) { + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("update_one_torrent_in_parallel"); + + //group.sampling_mode(criterion::SamplingMode::Flat); + //group.sample_size(10); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_millis(1000)); + + group.bench_function("RwLockStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.finish(); +} + +fn update_multiple_torrents_in_parallel(c: &mut Criterion) { + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("update_multiple_torrents_in_parallel"); + + //group.sampling_mode(criterion::SamplingMode::Flat); + //group.sample_size(10); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_millis(1000)); + + group.bench_function("RwLockStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexTokio", |b| { + b.to_async(&rt).iter_custom(|iters| { + asyn::update_multiple_torrents_in_parallel::(&rt, iters, None) + }); + }); + + group.finish(); +} + +criterion_group!( + benches, + add_one_torrent, + add_multiple_torrents_in_parallel, + update_one_torrent_in_parallel, + update_multiple_torrents_in_parallel +); +criterion_main!(benches); From 3e0745b757f80ac0b5efce0e7c9459c8218cee73 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 17 Mar 2024 11:23:25 +0800 Subject: [PATCH 0271/1297] dev: extract clock to new package --- Cargo.lock | 54 ++- Cargo.toml | 1 + cSpell.json | 2 + packages/clock/Cargo.toml | 24 ++ packages/clock/README.md | 11 + packages/clock/src/clock/mod.rs | 72 ++++ packages/clock/src/clock/stopped/mod.rs | 210 ++++++++++ packages/clock/src/clock/working/mod.rs | 18 + packages/clock/src/conv/mod.rs | 82 ++++ packages/clock/src/lib.rs | 53 +++ .../clock/src/static_time/mod.rs | 0 .../clock/src/time_extent/mod.rs | 99 +++-- packages/clock/tests/clock/mod.rs | 16 + packages/clock/tests/integration.rs | 19 + packages/configuration/src/lib.rs | 3 + packages/torrent-repository/Cargo.toml | 5 +- packages/torrent-repository/src/entry/mod.rs | 6 +- .../torrent-repository/src/entry/single.rs | 299 +++++++++++++ packages/torrent-repository/src/lib.rs | 13 + src/bootstrap/app.rs | 2 +- src/core/auth.rs | 20 +- src/core/databases/mod.rs | 4 +- src/core/mod.rs | 15 +- src/core/peer_tests.rs | 8 +- src/core/torrent/mod.rs | 298 +------------ src/lib.rs | 24 ++ .../apis/v1/context/auth_key/resources.rs | 15 +- src/servers/http/mod.rs | 2 +- src/servers/http/v1/handlers/announce.rs | 5 +- src/servers/udp/connection_cookie.rs | 24 +- src/servers/udp/handlers.rs | 5 +- src/servers/udp/peer_builder.rs | 5 +- src/shared/clock/mod.rs | 393 ------------------ src/shared/clock/utils.rs | 1 - src/shared/mod.rs | 2 - tests/common/clock.rs | 16 + tests/common/mod.rs | 1 + tests/integration.rs | 13 + 38 files changed, 1050 insertions(+), 790 deletions(-) create mode 100644 packages/clock/Cargo.toml create mode 100644 packages/clock/README.md create mode 100644 packages/clock/src/clock/mod.rs create mode 100644 packages/clock/src/clock/stopped/mod.rs create mode 100644 packages/clock/src/clock/working/mod.rs create mode 100644 packages/clock/src/conv/mod.rs create mode 100644 packages/clock/src/lib.rs rename src/shared/clock/static_time.rs => packages/clock/src/static_time/mod.rs (100%) rename src/shared/clock/time_extent.rs => packages/clock/src/time_extent/mod.rs (85%) create mode 100644 packages/clock/tests/clock/mod.rs create mode 100644 packages/clock/tests/integration.rs delete mode 100644 src/shared/clock/mod.rs delete mode 100644 src/shared/clock/utils.rs create mode 100644 tests/common/clock.rs diff --git a/Cargo.lock b/Cargo.lock index b8437326c..e28278abb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1209,6 +1209,12 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" +[[package]] +name = "futures-timer" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" + [[package]] name = "futures-util" version = "0.3.30" @@ -2560,6 +2566,12 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" +[[package]] +name = "relative-path" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e898588f33fdd5b9420719948f9f2a32c922a246964576f71ba7f24f80610fbc" + [[package]] name = "rend" version = "0.4.2" @@ -2676,6 +2688,35 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "rstest" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97eeab2f3c0a199bc4be135c36c924b6590b88c377d416494288c14f2db30199" +dependencies = [ + "futures", + "futures-timer", + "rstest_macros", + "rustc_version", +] + +[[package]] +name = "rstest_macros" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d428f8247852f894ee1be110b375111b586d4fa431f6c46e64ba5a0dcccbe605" +dependencies = [ + "cfg-if", + "glob", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version", + "syn 2.0.53", + "unicode-ident", +] + [[package]] name = "rusqlite" version = "0.31.0" @@ -3490,6 +3531,7 @@ dependencies = [ "serde_repr", "thiserror", "tokio", + "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-contrib-bencode", "torrust-tracker-located-error", @@ -3503,6 +3545,15 @@ dependencies = [ "uuid", ] +[[package]] +name = "torrust-tracker-clock" +version = "3.0.0-alpha.12-develop" +dependencies = [ + "chrono", + "lazy_static", + "torrust-tracker-primitives", +] + [[package]] name = "torrust-tracker-configuration" version = "3.0.0-alpha.12-develop" @@ -3561,8 +3612,9 @@ version = "3.0.0-alpha.12-develop" dependencies = [ "criterion", "futures", - "serde", + "rstest", "tokio", + "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-primitives", ] diff --git a/Cargo.toml b/Cargo.toml index 9610fffc2..99b7a334a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -64,6 +64,7 @@ serde_repr = "0" thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "packages/configuration" } +torrust-tracker-clock = { version = "3.0.0-alpha.12-develop", path = "packages/clock" } torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12-develop", path = "contrib/bencode" } torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "packages/located-error" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } diff --git a/cSpell.json b/cSpell.json index 6d5f71b85..1e276dbc2 100644 --- a/cSpell.json +++ b/cSpell.json @@ -34,6 +34,7 @@ "completei", "connectionless", "Containerfile", + "conv", "curr", "Cyberneering", "dashmap", @@ -116,6 +117,7 @@ "rngs", "rosegment", "routable", + "rstest", "rusqlite", "RUSTDOCFLAGS", "RUSTFLAGS", diff --git a/packages/clock/Cargo.toml b/packages/clock/Cargo.toml new file mode 100644 index 000000000..d7192b6e4 --- /dev/null +++ b/packages/clock/Cargo.toml @@ -0,0 +1,24 @@ +[package] +description = "A library to a clock for the torrust tracker." +keywords = ["library", "clock", "torrents"] +name = "torrust-tracker-clock" +readme = "README.md" + +authors.workspace = true +categories.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +lazy_static = "1" +chrono = { version = "0", default-features = false, features = ["clock"] } + +torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } + +[dev-dependencies] diff --git a/packages/clock/README.md b/packages/clock/README.md new file mode 100644 index 000000000..bfdd7808f --- /dev/null +++ b/packages/clock/README.md @@ -0,0 +1,11 @@ +# Torrust Tracker Clock + +A library to provide a working and mockable clock for the [Torrust Tracker](https://github.com/torrust/torrust-tracker). + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-torrent-clock). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/clock/src/clock/mod.rs b/packages/clock/src/clock/mod.rs new file mode 100644 index 000000000..50afbc9db --- /dev/null +++ b/packages/clock/src/clock/mod.rs @@ -0,0 +1,72 @@ +use std::time::Duration; + +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use self::stopped::StoppedClock; +use self::working::WorkingClock; + +pub mod stopped; +pub mod working; + +/// A generic structure that represents a clock. +/// +/// It can be either the working clock (production) or the stopped clock +/// (testing). It implements the `Time` trait, which gives you the current time. +#[derive(Debug)] +pub struct Clock { + clock: std::marker::PhantomData, +} + +/// The working clock. It returns the current time. +pub type Working = Clock; +/// The stopped clock. It returns always the same fixed time. +pub type Stopped = Clock; + +/// Trait for types that can be used as a timestamp clock. +pub trait Time: Sized { + fn now() -> DurationSinceUnixEpoch; + + fn dbg_clock_type() -> String; + + #[must_use] + fn now_add(add_time: &Duration) -> Option { + Self::now().checked_add(*add_time) + } + #[must_use] + fn now_sub(sub_time: &Duration) -> Option { + Self::now().checked_sub(*sub_time) + } +} + +#[cfg(test)] +mod tests { + use std::any::TypeId; + use std::time::Duration; + + use crate::clock::{self, Stopped, Time, Working}; + use crate::CurrentClock; + + #[test] + fn it_should_be_the_stopped_clock_as_default_when_testing() { + // We are testing, so we should default to the fixed time. + assert_eq!(TypeId::of::(), TypeId::of::()); + assert_eq!(Stopped::now(), CurrentClock::now()); + } + + #[test] + fn it_should_have_different_times() { + assert_ne!(TypeId::of::(), TypeId::of::()); + assert_ne!(Stopped::now(), Working::now()); + } + + #[test] + fn it_should_use_stopped_time_for_testing() { + assert_eq!(CurrentClock::dbg_clock_type(), "Stopped".to_owned()); + + let time = CurrentClock::now(); + std::thread::sleep(Duration::from_millis(50)); + let time_2 = CurrentClock::now(); + + assert_eq!(time, time_2); + } +} diff --git a/packages/clock/src/clock/stopped/mod.rs b/packages/clock/src/clock/stopped/mod.rs new file mode 100644 index 000000000..57655ab75 --- /dev/null +++ b/packages/clock/src/clock/stopped/mod.rs @@ -0,0 +1,210 @@ +/// Trait for types that can be used as a timestamp clock stopped +/// at a given time. + +#[allow(clippy::module_name_repetitions)] +pub struct StoppedClock {} + +#[allow(clippy::module_name_repetitions)] +pub trait Stopped: clock::Time { + /// It sets the clock to a given time. + fn local_set(unix_time: &DurationSinceUnixEpoch); + + /// It sets the clock to the Unix Epoch. + fn local_set_to_unix_epoch() { + Self::local_set(&DurationSinceUnixEpoch::ZERO); + } + + /// It sets the clock to the time the application started. + fn local_set_to_app_start_time(); + + /// It sets the clock to the current system time. + fn local_set_to_system_time_now(); + + /// It adds a `Duration` to the clock. + /// + /// # Errors + /// + /// Will return `IntErrorKind` if `duration` would overflow the internal `Duration`. + fn local_add(duration: &Duration) -> Result<(), IntErrorKind>; + + /// It subtracts a `Duration` from the clock. + /// # Errors + /// + /// Will return `IntErrorKind` if `duration` would underflow the internal `Duration`. + fn local_sub(duration: &Duration) -> Result<(), IntErrorKind>; + + /// It resets the clock to default fixed time that is application start time (or the unix epoch when testing). + fn local_reset(); +} + +use std::num::IntErrorKind; +use std::time::Duration; + +use super::{DurationSinceUnixEpoch, Time}; +use crate::clock; + +impl Time for clock::Stopped { + fn now() -> DurationSinceUnixEpoch { + detail::FIXED_TIME.with(|time| { + return *time.borrow(); + }) + } + + fn dbg_clock_type() -> String { + "Stopped".to_owned() + } +} + +impl Stopped for clock::Stopped { + fn local_set(unix_time: &DurationSinceUnixEpoch) { + detail::FIXED_TIME.with(|time| { + *time.borrow_mut() = *unix_time; + }); + } + + fn local_set_to_app_start_time() { + Self::local_set(&detail::get_app_start_time()); + } + + fn local_set_to_system_time_now() { + Self::local_set(&detail::get_app_start_time()); + } + + fn local_add(duration: &Duration) -> Result<(), IntErrorKind> { + detail::FIXED_TIME.with(|time| { + let time_borrowed = *time.borrow(); + *time.borrow_mut() = match time_borrowed.checked_add(*duration) { + Some(time) => time, + None => { + return Err(IntErrorKind::PosOverflow); + } + }; + Ok(()) + }) + } + + fn local_sub(duration: &Duration) -> Result<(), IntErrorKind> { + detail::FIXED_TIME.with(|time| { + let time_borrowed = *time.borrow(); + *time.borrow_mut() = match time_borrowed.checked_sub(*duration) { + Some(time) => time, + None => { + return Err(IntErrorKind::NegOverflow); + } + }; + Ok(()) + }) + } + + fn local_reset() { + Self::local_set(&detail::get_default_fixed_time()); + } +} + +#[cfg(test)] +mod tests { + use std::thread; + use std::time::Duration; + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::clock::stopped::Stopped as _; + use crate::clock::{Stopped, Time, Working}; + + #[test] + fn it_should_default_to_zero_when_testing() { + assert_eq!(Stopped::now(), DurationSinceUnixEpoch::ZERO); + } + + #[test] + fn it_should_possible_to_set_the_time() { + // Check we start with ZERO. + assert_eq!(Stopped::now(), Duration::ZERO); + + // Set to Current Time and Check + let timestamp = Working::now(); + Stopped::local_set(×tamp); + assert_eq!(Stopped::now(), timestamp); + + // Elapse the Current Time and Check + Stopped::local_add(×tamp).unwrap(); + assert_eq!(Stopped::now(), timestamp + timestamp); + + // Reset to ZERO and Check + Stopped::local_reset(); + assert_eq!(Stopped::now(), Duration::ZERO); + } + + #[test] + fn it_should_default_to_zero_on_thread_exit() { + assert_eq!(Stopped::now(), Duration::ZERO); + let after5 = Working::now_add(&Duration::from_secs(5)).unwrap(); + Stopped::local_set(&after5); + assert_eq!(Stopped::now(), after5); + + let t = thread::spawn(move || { + // each thread starts out with the initial value of ZERO + assert_eq!(Stopped::now(), Duration::ZERO); + + // and gets set to the current time. + let timestamp = Working::now(); + Stopped::local_set(×tamp); + assert_eq!(Stopped::now(), timestamp); + }); + + // wait for the thread to complete and bail out on panic + t.join().unwrap(); + + // we retain our original value of current time + 5sec despite the child thread + assert_eq!(Stopped::now(), after5); + + // Reset to ZERO and Check + Stopped::local_reset(); + assert_eq!(Stopped::now(), Duration::ZERO); + } +} + +mod detail { + use std::cell::RefCell; + use std::time::SystemTime; + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::static_time; + + thread_local!(pub static FIXED_TIME: RefCell = RefCell::new(get_default_fixed_time())); + + pub fn get_app_start_time() -> DurationSinceUnixEpoch { + (*static_time::TIME_AT_APP_START) + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + } + + #[cfg(not(test))] + pub fn get_default_fixed_time() -> DurationSinceUnixEpoch { + get_app_start_time() + } + + #[cfg(test)] + pub fn get_default_fixed_time() -> DurationSinceUnixEpoch { + DurationSinceUnixEpoch::ZERO + } + + #[cfg(test)] + mod tests { + use std::time::Duration; + + use crate::clock::stopped::detail::{get_app_start_time, get_default_fixed_time}; + + #[test] + fn it_should_get_the_zero_start_time_when_testing() { + assert_eq!(get_default_fixed_time(), Duration::ZERO); + } + + #[test] + fn it_should_get_app_start_time() { + const TIME_AT_WRITING_THIS_TEST: Duration = Duration::new(1_662_983_731, 22312); + assert!(get_app_start_time() > TIME_AT_WRITING_THIS_TEST); + } + } +} diff --git a/packages/clock/src/clock/working/mod.rs b/packages/clock/src/clock/working/mod.rs new file mode 100644 index 000000000..6d0b4dcf7 --- /dev/null +++ b/packages/clock/src/clock/working/mod.rs @@ -0,0 +1,18 @@ +use std::time::SystemTime; + +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::clock; + +#[allow(clippy::module_name_repetitions)] +pub struct WorkingClock; + +impl clock::Time for clock::Working { + fn now() -> DurationSinceUnixEpoch { + SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap() + } + + fn dbg_clock_type() -> String { + "Working".to_owned() + } +} diff --git a/packages/clock/src/conv/mod.rs b/packages/clock/src/conv/mod.rs new file mode 100644 index 000000000..f70950c38 --- /dev/null +++ b/packages/clock/src/conv/mod.rs @@ -0,0 +1,82 @@ +use std::str::FromStr; + +use chrono::{DateTime, Utc}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +/// It converts a string in ISO 8601 format to a timestamp. +/// For example, the string `1970-01-01T00:00:00.000Z` which is the Unix Epoch +/// will be converted to a timestamp of 0: `DurationSinceUnixEpoch::ZERO`. +/// +/// # Panics +/// +/// Will panic if the input time cannot be converted to `DateTime::`, internally using the `i64` type. +/// (this will naturally happen in 292.5 billion years) +#[must_use] +pub fn convert_from_iso_8601_to_timestamp(iso_8601: &str) -> DurationSinceUnixEpoch { + convert_from_datetime_utc_to_timestamp(&DateTime::::from_str(iso_8601).unwrap()) +} + +/// It converts a `DateTime::` to a timestamp. +/// For example, the `DateTime::` of the Unix Epoch will be converted to a +/// timestamp of 0: `DurationSinceUnixEpoch::ZERO`. +/// +/// # Panics +/// +/// Will panic if the input time overflows the `u64` type. +/// (this will naturally happen in 584.9 billion years) +#[must_use] +pub fn convert_from_datetime_utc_to_timestamp(datetime_utc: &DateTime) -> DurationSinceUnixEpoch { + DurationSinceUnixEpoch::from_secs(u64::try_from(datetime_utc.timestamp()).expect("Overflow of u64 seconds, very future!")) +} + +/// It converts a timestamp to a `DateTime::`. +/// For example, the timestamp of 0: `DurationSinceUnixEpoch::ZERO` will be +/// converted to the `DateTime::` of the Unix Epoch. +/// +/// # Panics +/// +/// Will panic if the input time overflows the `u64` seconds overflows the `i64` type. +/// (this will naturally happen in 292.5 billion years) +#[must_use] +pub fn convert_from_timestamp_to_datetime_utc(duration: DurationSinceUnixEpoch) -> DateTime { + DateTime::from_timestamp( + i64::try_from(duration.as_secs()).expect("Overflow of i64 seconds, very future!"), + duration.subsec_nanos(), + ) + .unwrap() +} + +#[cfg(test)] + +mod tests { + use chrono::DateTime; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::conv::{ + convert_from_datetime_utc_to_timestamp, convert_from_iso_8601_to_timestamp, convert_from_timestamp_to_datetime_utc, + }; + + #[test] + fn should_be_converted_to_datetime_utc() { + let timestamp = DurationSinceUnixEpoch::ZERO; + assert_eq!( + convert_from_timestamp_to_datetime_utc(timestamp), + DateTime::from_timestamp(0, 0).unwrap() + ); + } + + #[test] + fn should_be_converted_from_datetime_utc() { + let datetime = DateTime::from_timestamp(0, 0).unwrap(); + assert_eq!( + convert_from_datetime_utc_to_timestamp(&datetime), + DurationSinceUnixEpoch::ZERO + ); + } + + #[test] + fn should_be_converted_from_datetime_utc_in_iso_8601() { + let iso_8601 = "1970-01-01T00:00:00.000Z".to_string(); + assert_eq!(convert_from_iso_8601_to_timestamp(&iso_8601), DurationSinceUnixEpoch::ZERO); + } +} diff --git a/packages/clock/src/lib.rs b/packages/clock/src/lib.rs new file mode 100644 index 000000000..9fc67cb54 --- /dev/null +++ b/packages/clock/src/lib.rs @@ -0,0 +1,53 @@ +//! Time related functions and types. +//! +//! It's usually a good idea to control where the time comes from +//! in an application so that it can be mocked for testing and it can be +//! controlled in production so we get the intended behavior without +//! relying on the specific time zone for the underlying system. +//! +//! Clocks use the type `DurationSinceUnixEpoch` which is a +//! `std::time::Duration` since the Unix Epoch (timestamp). +//! +//! ```text +//! Local time: lun 2023-03-27 16:12:00 WEST +//! Universal time: lun 2023-03-27 15:12:00 UTC +//! Time zone: Atlantic/Canary (WEST, +0100) +//! Timestamp: 1679929914 +//! Duration: 1679929914.10167426 +//! ``` +//! +//! > **NOTICE**: internally the `Duration` is stores it's main unit as seconds in a `u64` and it will +//! overflow in 584.9 billion years. +//! +//! > **NOTICE**: the timestamp does not depend on the time zone. That gives you +//! the ability to use the clock regardless of the underlying system time zone +//! configuration. See [Unix time Wikipedia entry](https://en.wikipedia.org/wiki/Unix_time). + +pub mod clock; +pub mod conv; +pub mod static_time; +pub mod time_extent; + +#[macro_use] +extern crate lazy_static; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; + +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type DefaultTimeExtentMaker = time_extent::WorkingTimeExtentMaker; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type DefaultTimeExtentMaker = time_extent::StoppedTimeExtentMaker; diff --git a/src/shared/clock/static_time.rs b/packages/clock/src/static_time/mod.rs similarity index 100% rename from src/shared/clock/static_time.rs rename to packages/clock/src/static_time/mod.rs diff --git a/src/shared/clock/time_extent.rs b/packages/clock/src/time_extent/mod.rs similarity index 85% rename from src/shared/clock/time_extent.rs rename to packages/clock/src/time_extent/mod.rs index 168224eda..c51849f21 100644 --- a/src/shared/clock/time_extent.rs +++ b/packages/clock/src/time_extent/mod.rs @@ -65,7 +65,7 @@ use std::num::{IntErrorKind, TryFromIntError}; use std::time::Duration; -use super::{Stopped, TimeNow, Type, Working}; +use crate::clock::{self, Stopped, Working}; /// This trait defines the operations that can be performed on a `TimeExtent`. pub trait Extent: Sized + Default { @@ -199,10 +199,10 @@ impl Extent for TimeExtent { /// It gives you the time in time extents. pub trait Make: Sized where - Clock: TimeNow, + Clock: clock::Time, { /// It gives you the current time extent (with a certain increment) for - /// the current time. It gets the current timestamp front he `Clock`. + /// the current time. It gets the current timestamp front the `Clock`. /// /// For example: /// @@ -223,12 +223,12 @@ where }) } - /// Same as [`now`](crate::shared::clock::time_extent::Make::now), but it + /// Same as [`now`](crate::time_extent::Make::now), but it /// will add an extra duration to the current time before calculating the /// time extent. It gives you a time extent for a time in the future. #[must_use] fn now_after(increment: &Base, add_time: &Duration) -> Option> { - match Clock::add(add_time) { + match Clock::now_add(add_time) { None => None, Some(time) => time .as_nanos() @@ -240,12 +240,12 @@ where } } - /// Same as [`now`](crate::shared::clock::time_extent::Make::now), but it + /// Same as [`now`](crate::time_extent::Make::now), but it /// will subtract a duration to the current time before calculating the /// time extent. It gives you a time extent for a time in the past. #[must_use] fn now_before(increment: &Base, sub_time: &Duration) -> Option> { - match Clock::sub(sub_time) { + match Clock::now_sub(sub_time) { None => None, Some(time) => time .as_nanos() @@ -262,38 +262,30 @@ where /// /// It's a clock which measures time in `TimeExtents`. #[derive(Debug)] -pub struct Maker {} +pub struct Maker { + clock: std::marker::PhantomData, +} /// A `TimeExtent` maker which makes `TimeExtents` from the `Working` clock. -pub type WorkingTimeExtentMaker = Maker<{ Type::WorkingClock as usize }>; +pub type WorkingTimeExtentMaker = Maker; /// A `TimeExtent` maker which makes `TimeExtents` from the `Stopped` clock. -pub type StoppedTimeExtentMaker = Maker<{ Type::StoppedClock as usize }>; - -impl Make for WorkingTimeExtentMaker {} -impl Make for StoppedTimeExtentMaker {} +pub type StoppedTimeExtentMaker = Maker; -/// The default `TimeExtent` maker. It is `WorkingTimeExtentMaker` in production -/// and `StoppedTimeExtentMaker` in tests. -#[cfg(not(test))] -pub type DefaultTimeExtentMaker = WorkingTimeExtentMaker; - -/// The default `TimeExtent` maker. It is `WorkingTimeExtentMaker` in production -/// and `StoppedTimeExtentMaker` in tests. -#[cfg(test)] -pub type DefaultTimeExtentMaker = StoppedTimeExtentMaker; +impl Make for WorkingTimeExtentMaker {} +impl Make for StoppedTimeExtentMaker {} #[cfg(test)] mod test { - use crate::shared::clock::time_extent::TimeExtent; + use crate::time_extent::TimeExtent; const TIME_EXTENT_VAL: TimeExtent = TimeExtent::from_sec(2, &239_812_388_723); mod fn_checked_duration_from_nanos { use std::time::Duration; - use crate::shared::clock::time_extent::checked_duration_from_nanos; - use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::time_extent::checked_duration_from_nanos; + use crate::time_extent::test::TIME_EXTENT_VAL; const NANOS_PER_SEC: u32 = 1_000_000_000; @@ -334,7 +326,7 @@ mod test { mod time_extent { mod fn_default { - use crate::shared::clock::time_extent::{TimeExtent, ZERO}; + use crate::time_extent::{TimeExtent, ZERO}; #[test] fn it_should_default_initialize_to_zero() { @@ -343,8 +335,8 @@ mod test { } mod fn_from_sec { - use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; - use crate::shared::clock::time_extent::{Multiplier, TimeExtent, ZERO}; + use crate::time_extent::test::TIME_EXTENT_VAL; + use crate::time_extent::{Multiplier, TimeExtent, ZERO}; #[test] fn it_should_make_empty_for_zero() { @@ -360,8 +352,8 @@ mod test { } mod fn_new { - use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; - use crate::shared::clock::time_extent::{Base, Extent, Multiplier, TimeExtent, ZERO}; + use crate::time_extent::test::TIME_EXTENT_VAL; + use crate::time_extent::{Base, Extent, Multiplier, TimeExtent, ZERO}; #[test] fn it_should_make_empty_for_zero() { @@ -383,8 +375,8 @@ mod test { mod fn_increase { use std::num::IntErrorKind; - use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; - use crate::shared::clock::time_extent::{Extent, TimeExtent, ZERO}; + use crate::time_extent::test::TIME_EXTENT_VAL; + use crate::time_extent::{Extent, TimeExtent, ZERO}; #[test] fn it_should_not_increase_for_zero() { @@ -411,8 +403,8 @@ mod test { mod fn_decrease { use std::num::IntErrorKind; - use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; - use crate::shared::clock::time_extent::{Extent, TimeExtent, ZERO}; + use crate::time_extent::test::TIME_EXTENT_VAL; + use crate::time_extent::{Extent, TimeExtent, ZERO}; #[test] fn it_should_not_decrease_for_zero() { @@ -437,8 +429,8 @@ mod test { } mod fn_total { - use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; - use crate::shared::clock::time_extent::{Base, Extent, Product, TimeExtent, MAX, ZERO}; + use crate::time_extent::test::TIME_EXTENT_VAL; + use crate::time_extent::{Base, Extent, Product, TimeExtent, MAX, ZERO}; #[test] fn it_should_be_zero_for_zero() { @@ -485,8 +477,8 @@ mod test { } mod fn_total_next { - use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; - use crate::shared::clock::time_extent::{Base, Extent, Product, TimeExtent, MAX, ZERO}; + use crate::time_extent::test::TIME_EXTENT_VAL; + use crate::time_extent::{Base, Extent, Product, TimeExtent, MAX, ZERO}; #[test] fn it_should_be_zero_for_zero() { @@ -544,9 +536,10 @@ mod test { mod fn_now { use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; - use crate::shared::clock::time_extent::{Base, DefaultTimeExtentMaker, Make, TimeExtent}; - use crate::shared::clock::{Current, StoppedTime}; + use crate::clock::stopped::Stopped as _; + use crate::time_extent::test::TIME_EXTENT_VAL; + use crate::time_extent::{Base, Make, TimeExtent}; + use crate::{CurrentClock, DefaultTimeExtentMaker}; #[test] fn it_should_give_a_time_extent() { @@ -558,7 +551,7 @@ mod test { } ); - Current::local_set(&DurationSinceUnixEpoch::from_secs(TIME_EXTENT_VAL.amount * 2)); + CurrentClock::local_set(&DurationSinceUnixEpoch::from_secs(TIME_EXTENT_VAL.amount * 2)); assert_eq!( DefaultTimeExtentMaker::now(&TIME_EXTENT_VAL.increment).unwrap().unwrap(), @@ -573,7 +566,7 @@ mod test { #[test] fn it_should_fail_if_amount_exceeds_bounds() { - Current::local_set(&DurationSinceUnixEpoch::MAX); + CurrentClock::local_set(&DurationSinceUnixEpoch::MAX); assert_eq!( DefaultTimeExtentMaker::now(&Base::from_millis(1)).unwrap().unwrap_err(), u64::try_from(u128::MAX).unwrap_err() @@ -586,9 +579,10 @@ mod test { use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; - use crate::shared::clock::time_extent::{Base, DefaultTimeExtentMaker, Make}; - use crate::shared::clock::{Current, StoppedTime}; + use crate::clock::stopped::Stopped as _; + use crate::time_extent::test::TIME_EXTENT_VAL; + use crate::time_extent::{Base, Make}; + use crate::{CurrentClock, DefaultTimeExtentMaker}; #[test] fn it_should_give_a_time_extent() { @@ -607,13 +601,13 @@ mod test { fn it_should_fail_for_zero() { assert_eq!(DefaultTimeExtentMaker::now_after(&Base::ZERO, &Duration::ZERO), None); - Current::local_set(&DurationSinceUnixEpoch::MAX); + CurrentClock::local_set(&DurationSinceUnixEpoch::MAX); assert_eq!(DefaultTimeExtentMaker::now_after(&Base::ZERO, &Duration::MAX), None); } #[test] fn it_should_fail_if_amount_exceeds_bounds() { - Current::local_set(&DurationSinceUnixEpoch::MAX); + CurrentClock::local_set(&DurationSinceUnixEpoch::MAX); assert_eq!( DefaultTimeExtentMaker::now_after(&Base::from_millis(1), &Duration::ZERO) .unwrap() @@ -627,12 +621,13 @@ mod test { use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::shared::clock::time_extent::{Base, DefaultTimeExtentMaker, Make, TimeExtent}; - use crate::shared::clock::{Current, StoppedTime}; + use crate::clock::stopped::Stopped as _; + use crate::time_extent::{Base, Make, TimeExtent}; + use crate::{CurrentClock, DefaultTimeExtentMaker}; #[test] fn it_should_give_a_time_extent() { - Current::local_set(&DurationSinceUnixEpoch::MAX); + CurrentClock::local_set(&DurationSinceUnixEpoch::MAX); assert_eq!( DefaultTimeExtentMaker::now_before( @@ -657,7 +652,7 @@ mod test { #[test] fn it_should_fail_if_amount_exceeds_bounds() { - Current::local_set(&DurationSinceUnixEpoch::MAX); + CurrentClock::local_set(&DurationSinceUnixEpoch::MAX); assert_eq!( DefaultTimeExtentMaker::now_before(&Base::from_millis(1), &Duration::ZERO) .unwrap() diff --git a/packages/clock/tests/clock/mod.rs b/packages/clock/tests/clock/mod.rs new file mode 100644 index 000000000..5d94bb83d --- /dev/null +++ b/packages/clock/tests/clock/mod.rs @@ -0,0 +1,16 @@ +use std::time::Duration; + +use torrust_tracker_clock::clock::Time; + +use crate::CurrentClock; + +#[test] +fn it_should_use_stopped_time_for_testing() { + assert_eq!(CurrentClock::dbg_clock_type(), "Stopped".to_owned()); + + let time = CurrentClock::now(); + std::thread::sleep(Duration::from_millis(50)); + let time_2 = CurrentClock::now(); + + assert_eq!(time, time_2); +} diff --git a/packages/clock/tests/integration.rs b/packages/clock/tests/integration.rs new file mode 100644 index 000000000..fa500227a --- /dev/null +++ b/packages/clock/tests/integration.rs @@ -0,0 +1,19 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` + +//mod common; +mod clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = torrust_tracker_clock::clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = torrust_tracker_clock::clock::Stopped; diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index b3b146717..549c73a31 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -243,6 +243,9 @@ use thiserror::Error; use torrust_tracker_located_error::{DynError, Located, LocatedError}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; +/// The maximum number of returned peers for a torrent. +pub const TORRENT_PEERS_LIMIT: usize = 74; + #[derive(Copy, Clone, Debug, PartialEq, Default, Constructor)] pub struct TrackerPolicy { pub remove_peerless_torrents: bool, diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index b53b9a15e..c36ae1440 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -1,5 +1,5 @@ [package] -description = "A library to provide error decorator with the location and the source of the original error." +description = "A library that provides a repository of torrents files and their peers." keywords = ["torrents", "repository", "library"] name = "torrust-tracker-torrent-repository" readme = "README.md" @@ -20,10 +20,11 @@ futures = "0.3.29" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } -serde = { version = "1", features = ["derive"] } +torrust-tracker-clock = { version = "3.0.0-alpha.12-develop", path = "../clock" } [dev-dependencies] criterion = { version = "0", features = ["async_tokio"] } +rstest = "0" [[bench]] harness = false diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index 04aa597df..11352a8fa 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -1,7 +1,7 @@ use std::fmt::Debug; use std::sync::Arc; -use serde::{Deserialize, Serialize}; +//use serde::{Deserialize, Serialize}; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; @@ -88,10 +88,10 @@ pub trait EntryAsync { /// This is the tracker entry for a given torrent and contains the swarm data, /// that's the list of all the peers trying to download the same torrent. /// The tracker keeps one entry like this for every torrent. -#[derive(Serialize, Deserialize, Clone, Debug, Default)] +#[derive(Clone, Debug, Default)] pub struct Torrent { /// The swarm: a network of peers that are all trying to download the torrent associated to this entry - #[serde(skip)] + // #[serde(skip)] pub(crate) peers: std::collections::BTreeMap>, /// The number of peers that have ever completed downloading the torrent associated to this entry pub(crate) completed: u32, diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs index 7a5cf6240..85fdc6cf0 100644 --- a/packages/torrent-repository/src/entry/single.rs +++ b/packages/torrent-repository/src/entry/single.rs @@ -103,3 +103,302 @@ impl Entry for EntrySingle { .retain(|_, peer| peer::ReadInfo::get_updated(peer) > current_cutoff); } } + +#[cfg(test)] +mod tests { + mod torrent_entry { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::ops::Sub; + use std::sync::Arc; + use std::time::Duration; + + use torrust_tracker_clock::clock::stopped::Stopped as _; + use torrust_tracker_clock::clock::{self, Time}; + use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; + use torrust_tracker_primitives::announce_event::AnnounceEvent; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; + + use crate::entry::Entry; + use crate::{CurrentClock, EntrySingle}; + + struct TorrentPeerBuilder { + peer: peer::Peer, + } + + impl TorrentPeerBuilder { + pub fn default() -> TorrentPeerBuilder { + let default_peer = peer::Peer { + peer_id: peer::Id([0u8; 20]), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), + updated: CurrentClock::now(), + uploaded: NumberOfBytes(0), + downloaded: NumberOfBytes(0), + left: NumberOfBytes(0), + event: AnnounceEvent::Started, + }; + TorrentPeerBuilder { peer: default_peer } + } + + pub fn with_event_completed(mut self) -> Self { + self.peer.event = AnnounceEvent::Completed; + self + } + + pub fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { + self.peer.peer_addr = peer_addr; + self + } + + pub fn with_peer_id(mut self, peer_id: peer::Id) -> Self { + self.peer.peer_id = peer_id; + self + } + + pub fn with_number_of_bytes_left(mut self, left: i64) -> Self { + self.peer.left = NumberOfBytes(left); + self + } + + pub fn updated_at(mut self, updated: DurationSinceUnixEpoch) -> Self { + self.peer.updated = updated; + self + } + + pub fn into(self) -> peer::Peer { + self.peer + } + } + + /// A torrent seeder is a peer with 0 bytes left to download which + /// has not announced it has stopped + fn a_torrent_seeder() -> peer::Peer { + TorrentPeerBuilder::default() + .with_number_of_bytes_left(0) + .with_event_completed() + .into() + } + + /// A torrent leecher is a peer that is not a seeder. + /// Leecher: left > 0 OR event = Stopped + fn a_torrent_leecher() -> peer::Peer { + TorrentPeerBuilder::default() + .with_number_of_bytes_left(1) + .with_event_completed() + .into() + } + + #[test] + fn the_default_torrent_entry_should_contain_an_empty_list_of_peers() { + let torrent_entry = EntrySingle::default(); + + assert_eq!(torrent_entry.get_peers(None).len(), 0); + } + + #[test] + fn a_new_peer_can_be_added_to_a_torrent_entry() { + let mut torrent_entry = EntrySingle::default(); + let torrent_peer = TorrentPeerBuilder::default().into(); + + torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer + + assert_eq!(*torrent_entry.get_peers(None)[0], torrent_peer); + assert_eq!(torrent_entry.get_peers(None).len(), 1); + } + + #[test] + fn a_torrent_entry_should_contain_the_list_of_peers_that_were_added_to_the_torrent() { + let mut torrent_entry = EntrySingle::default(); + let torrent_peer = TorrentPeerBuilder::default().into(); + + torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer + + assert_eq!(torrent_entry.get_peers(None), vec![Arc::new(torrent_peer)]); + } + + #[test] + fn a_peer_can_be_updated_in_a_torrent_entry() { + let mut torrent_entry = EntrySingle::default(); + let mut torrent_peer = TorrentPeerBuilder::default().into(); + torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer + + torrent_peer.event = AnnounceEvent::Completed; // Update the peer + torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry + + assert_eq!(torrent_entry.get_peers(None)[0].event, AnnounceEvent::Completed); + } + + #[test] + fn a_peer_should_be_removed_from_a_torrent_entry_when_the_peer_announces_it_has_stopped() { + let mut torrent_entry = EntrySingle::default(); + let mut torrent_peer = TorrentPeerBuilder::default().into(); + torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer + + torrent_peer.event = AnnounceEvent::Stopped; // Update the peer + torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry + + assert_eq!(torrent_entry.get_peers(None).len(), 0); + } + + #[test] + fn torrent_stats_change_when_a_previously_known_peer_announces_it_has_completed_the_torrent() { + let mut torrent_entry = EntrySingle::default(); + let mut torrent_peer = TorrentPeerBuilder::default().into(); + + torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer + + torrent_peer.event = AnnounceEvent::Completed; // Update the peer + let stats_have_changed = torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry + + assert!(stats_have_changed); + } + + #[test] + fn torrent_stats_should_not_change_when_a_peer_announces_it_has_completed_the_torrent_if_it_is_the_first_announce_from_the_peer( + ) { + let mut torrent_entry = EntrySingle::default(); + let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); + + // Add a peer that did not exist before in the entry + let torrent_stats_have_not_changed = !torrent_entry.insert_or_update_peer(&torrent_peer_announcing_complete_event); + + assert!(torrent_stats_have_not_changed); + } + + #[test] + fn a_torrent_entry_should_return_the_list_of_peers_for_a_given_peer_filtering_out_the_client_that_is_making_the_request() + { + let mut torrent_entry = EntrySingle::default(); + let peer_socket_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); + let torrent_peer = TorrentPeerBuilder::default().with_peer_address(peer_socket_address).into(); + torrent_entry.insert_or_update_peer(&torrent_peer); // Add peer + + // Get peers excluding the one we have just added + let peers = torrent_entry.get_peers_for_peer(&torrent_peer, None); + + assert_eq!(peers.len(), 0); + } + + #[test] + fn two_peers_with_the_same_ip_but_different_port_should_be_considered_different_peers() { + let mut torrent_entry = EntrySingle::default(); + + let peer_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); + + // Add peer 1 + let torrent_peer_1 = TorrentPeerBuilder::default() + .with_peer_address(SocketAddr::new(peer_ip, 8080)) + .into(); + torrent_entry.insert_or_update_peer(&torrent_peer_1); + + // Add peer 2 + let torrent_peer_2 = TorrentPeerBuilder::default() + .with_peer_address(SocketAddr::new(peer_ip, 8081)) + .into(); + torrent_entry.insert_or_update_peer(&torrent_peer_2); + + // Get peers for peer 1 + let peers = torrent_entry.get_peers_for_peer(&torrent_peer_1, None); + + // The peer 2 using the same IP but different port should be included + assert_eq!(peers[0].peer_addr.ip(), Ipv4Addr::new(127, 0, 0, 1)); + assert_eq!(peers[0].peer_addr.port(), 8081); + } + + fn peer_id_from_i32(number: i32) -> peer::Id { + let peer_id = number.to_le_bytes(); + peer::Id([ + 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, peer_id[0], peer_id[1], + peer_id[2], peer_id[3], + ]) + } + + #[test] + fn the_tracker_should_limit_the_list_of_peers_to_74_when_clients_scrape_torrents() { + let mut torrent_entry = EntrySingle::default(); + + // We add one more peer than the scrape limit + for peer_number in 1..=74 + 1 { + let torrent_peer = TorrentPeerBuilder::default() + .with_peer_id(peer_id_from_i32(peer_number)) + .into(); + torrent_entry.insert_or_update_peer(&torrent_peer); + } + + let peers = torrent_entry.get_peers(Some(TORRENT_PEERS_LIMIT)); + + assert_eq!(peers.len(), 74); + } + + #[test] + fn torrent_stats_should_have_the_number_of_seeders_for_a_torrent() { + let mut torrent_entry = EntrySingle::default(); + let torrent_seeder = a_torrent_seeder(); + + torrent_entry.insert_or_update_peer(&torrent_seeder); // Add seeder + + assert_eq!(torrent_entry.get_stats().complete, 1); + } + + #[test] + fn torrent_stats_should_have_the_number_of_leechers_for_a_torrent() { + let mut torrent_entry = EntrySingle::default(); + let torrent_leecher = a_torrent_leecher(); + + torrent_entry.insert_or_update_peer(&torrent_leecher); // Add leecher + + assert_eq!(torrent_entry.get_stats().incomplete, 1); + } + + #[test] + fn torrent_stats_should_have_the_number_of_peers_that_having_announced_at_least_two_events_the_latest_one_is_the_completed_event( + ) { + let mut torrent_entry = EntrySingle::default(); + let mut torrent_peer = TorrentPeerBuilder::default().into(); + torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer + + // Announce "Completed" torrent download event. + torrent_peer.event = AnnounceEvent::Completed; + torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer + + let number_of_previously_known_peers_with_completed_torrent = torrent_entry.get_stats().complete; + + assert_eq!(number_of_previously_known_peers_with_completed_torrent, 1); + } + + #[test] + fn torrent_stats_should_not_include_a_peer_in_the_completed_counter_if_the_peer_has_announced_only_one_event() { + let mut torrent_entry = EntrySingle::default(); + let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); + + // Announce "Completed" torrent download event. + // It's the first event announced from this peer. + torrent_entry.insert_or_update_peer(&torrent_peer_announcing_complete_event); // Add the peer + + let number_of_peers_with_completed_torrent = torrent_entry.get_stats().downloaded; + + assert_eq!(number_of_peers_with_completed_torrent, 0); + } + + #[test] + fn a_torrent_entry_should_remove_a_peer_not_updated_after_a_timeout_in_seconds() { + let mut torrent_entry = EntrySingle::default(); + + let timeout = 120u32; + + let now = clock::Working::now(); + clock::Stopped::local_set(&now); + + let timeout_seconds_before_now = now.sub(Duration::from_secs(u64::from(timeout))); + let inactive_peer = TorrentPeerBuilder::default() + .updated_at(timeout_seconds_before_now.sub(Duration::from_secs(1))) + .into(); + torrent_entry.insert_or_update_peer(&inactive_peer); // Add the peer + + let current_cutoff = CurrentClock::now_sub(&Duration::from_secs(u64::from(timeout))).unwrap_or_default(); + torrent_entry.remove_inactive_peers(current_cutoff); + + assert_eq!(torrent_entry.get_peers_len(), 0); + } + } +} diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 903e1405e..8bb1b6def 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,5 +1,7 @@ use std::sync::Arc; +use torrust_tracker_clock::clock; + pub mod entry; pub mod repository; @@ -13,3 +15,14 @@ pub type TorrentsRwLockStdMutexTokio = repository::RwLockStd; pub type TorrentsRwLockTokio = repository::RwLockTokio; pub type TorrentsRwLockTokioMutexStd = repository::RwLockTokio; pub type TorrentsRwLockTokioMutexTokio = repository::RwLockTokio; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 09b624566..396e63682 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -13,13 +13,13 @@ //! 4. Initialize the domain tracker. use std::sync::Arc; +use torrust_tracker_clock::static_time; use torrust_tracker_configuration::Configuration; use super::config::initialize_configuration; use crate::bootstrap; use crate::core::services::tracker_factory; use crate::core::Tracker; -use crate::shared::clock::static_time; use crate::shared::crypto::ephemeral_instance_keys; /// It loads the configuration from the environment and builds the main domain [`Tracker`] struct. diff --git a/src/core/auth.rs b/src/core/auth.rs index a7bb91aa4..b5326a373 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -47,11 +47,13 @@ use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; use thiserror::Error; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; use torrust_tracker_located_error::{DynError, LocatedError}; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; -use crate::shared::clock::{convert_from_timestamp_to_datetime_utc, Current, Time, TimeNow}; +use crate::CurrentClock; #[must_use] /// It generates a new random 32-char authentication [`ExpiringKey`] @@ -70,7 +72,7 @@ pub fn generate(lifetime: Duration) -> ExpiringKey { ExpiringKey { key: random_id.parse::().unwrap(), - valid_until: Current::add(&lifetime).unwrap(), + valid_until: CurrentClock::now_add(&lifetime).unwrap(), } } @@ -82,7 +84,7 @@ pub fn generate(lifetime: Duration) -> ExpiringKey { /// /// Will return `Error::KeyInvalid` if `auth_key.valid_until` is past the `None`. pub fn verify(auth_key: &ExpiringKey) -> Result<(), Error> { - let current_time: DurationSinceUnixEpoch = Current::now(); + let current_time: DurationSinceUnixEpoch = CurrentClock::now(); if auth_key.valid_until < current_time { Err(Error::KeyExpired { @@ -213,8 +215,10 @@ mod tests { use std::str::FromStr; use std::time::Duration; + use torrust_tracker_clock::clock; + use torrust_tracker_clock::clock::stopped::Stopped as _; + use crate::core::auth; - use crate::shared::clock::{Current, StoppedTime}; #[test] fn should_be_parsed_from_an_string() { @@ -228,7 +232,7 @@ mod tests { #[test] fn should_be_displayed() { // Set the time to the current time. - Current::local_set_to_unix_epoch(); + clock::Stopped::local_set_to_unix_epoch(); let expiring_key = auth::generate(Duration::from_secs(0)); @@ -248,18 +252,18 @@ mod tests { #[test] fn should_be_generate_and_verified() { // Set the time to the current time. - Current::local_set_to_system_time_now(); + clock::Stopped::local_set_to_system_time_now(); // Make key that is valid for 19 seconds. let expiring_key = auth::generate(Duration::from_secs(19)); // Mock the time has passed 10 sec. - Current::local_add(&Duration::from_secs(10)).unwrap(); + clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); assert!(auth::verify(&expiring_key).is_ok()); // Mock the time has passed another 10 sec. - Current::local_add(&Duration::from_secs(10)).unwrap(); + clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); assert!(auth::verify(&expiring_key).is_err()); } diff --git a/src/core/databases/mod.rs b/src/core/databases/mod.rs index b708ef4dc..20a45cf83 100644 --- a/src/core/databases/mod.rs +++ b/src/core/databases/mod.rs @@ -117,9 +117,9 @@ pub trait Database: Sync + Send { /// /// It returns an array of tuples with the torrent /// [`InfoHash`] and the - /// [`completed`](torrust_tracker_torrent_repository::entry::Entry::completed) counter + /// [`completed`](torrust_tracker_torrent_repository::entry::Torrent::completed) counter /// which is the number of times the torrent has been downloaded. - /// See [`Entry::completed`](torrust_tracker_torrent_repository::entry::Entry::completed). + /// See [`Entry::completed`](torrust_tracker_torrent_repository::entry::Torrent::completed). /// /// # Context: Torrent Metrics /// diff --git a/src/core/mod.rs b/src/core/mod.rs index f94c46543..21cd1b501 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -444,7 +444,8 @@ use std::time::Duration; use derive_more::Constructor; use log::debug; use tokio::sync::mpsc::error::SendError; -use torrust_tracker_configuration::{AnnouncePolicy, Configuration, TrackerPolicy}; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_configuration::{AnnouncePolicy, Configuration, TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; @@ -456,10 +457,7 @@ use self::auth::Key; use self::error::Error; use self::torrent::Torrents; use crate::core::databases::Database; -use crate::shared::clock::{self, TimeNow}; - -/// The maximum number of returned peers for a torrent. -pub const TORRENT_PEERS_LIMIT: usize = 74; +use crate::CurrentClock; /// The domain layer tracker service. /// @@ -741,7 +739,7 @@ impl Tracker { self.torrents.remove_peerless_torrents(&self.policy); } else { let current_cutoff = - clock::Current::sub(&Duration::from_secs(u64::from(self.policy.max_peer_timeout))).unwrap_or_default(); + CurrentClock::now_sub(&Duration::from_secs(u64::from(self.policy.max_peer_timeout))).unwrap_or_default(); self.torrents.remove_inactive_peers(current_cutoff); } } @@ -1592,8 +1590,11 @@ mod tests { use std::str::FromStr; use std::time::Duration; + use torrust_tracker_clock::clock::Time; + use crate::core::auth; use crate::core::tests::the_tracker::private_tracker; + use crate::CurrentClock; #[tokio::test] async fn it_should_generate_the_expiring_authentication_keys() { @@ -1601,7 +1602,7 @@ mod tests { let key = tracker.generate_auth_key(Duration::from_secs(100)).await.unwrap(); - assert_eq!(key.valid_until, Duration::from_secs(100)); + assert_eq!(key.valid_until, CurrentClock::now_add(&Duration::from_secs(100)).unwrap()); } #[tokio::test] diff --git a/src/core/peer_tests.rs b/src/core/peer_tests.rs index 9e5b4be01..d30d73db3 100644 --- a/src/core/peer_tests.rs +++ b/src/core/peer_tests.rs @@ -2,17 +2,21 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use torrust_tracker_clock::clock::stopped::Stopped as _; +use torrust_tracker_clock::clock::{self, Time}; use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::{peer, NumberOfBytes}; -use crate::shared::clock::{self, Time}; +use crate::CurrentClock; #[test] fn it_should_be_serializable() { + clock::Stopped::local_set_to_unix_epoch(); + let torrent_peer = peer::Peer { peer_id: peer::Id(*b"-qB0000-000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: clock::Current::now(), + updated: CurrentClock::now(), uploaded: NumberOfBytes(0), downloaded: NumberOfBytes(0), left: NumberOfBytes(0), diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index b5a2b4c07..2b3f9cbf7 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -31,300 +31,4 @@ use torrust_tracker_torrent_repository::TorrentsRwLockStdMutexStd; pub type Torrents = TorrentsRwLockStdMutexStd; // Currently Used #[cfg(test)] -mod tests { - - mod torrent_entry { - - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::ops::Sub; - use std::sync::Arc; - use std::time::Duration; - - use torrust_tracker_primitives::announce_event::AnnounceEvent; - use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; - use torrust_tracker_torrent_repository::entry::Entry; - use torrust_tracker_torrent_repository::EntrySingle; - - use crate::core::TORRENT_PEERS_LIMIT; - use crate::shared::clock::{self, StoppedTime, Time, TimeNow}; - - struct TorrentPeerBuilder { - peer: peer::Peer, - } - - impl TorrentPeerBuilder { - pub fn default() -> TorrentPeerBuilder { - let default_peer = peer::Peer { - peer_id: peer::Id([0u8; 20]), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), - updated: clock::Current::now(), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Started, - }; - TorrentPeerBuilder { peer: default_peer } - } - - pub fn with_event_completed(mut self) -> Self { - self.peer.event = AnnounceEvent::Completed; - self - } - - pub fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { - self.peer.peer_addr = peer_addr; - self - } - - pub fn with_peer_id(mut self, peer_id: peer::Id) -> Self { - self.peer.peer_id = peer_id; - self - } - - pub fn with_number_of_bytes_left(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes(left); - self - } - - pub fn updated_at(mut self, updated: DurationSinceUnixEpoch) -> Self { - self.peer.updated = updated; - self - } - - pub fn into(self) -> peer::Peer { - self.peer - } - } - - /// A torrent seeder is a peer with 0 bytes left to download which - /// has not announced it has stopped - fn a_torrent_seeder() -> peer::Peer { - TorrentPeerBuilder::default() - .with_number_of_bytes_left(0) - .with_event_completed() - .into() - } - - /// A torrent leecher is a peer that is not a seeder. - /// Leecher: left > 0 OR event = Stopped - fn a_torrent_leecher() -> peer::Peer { - TorrentPeerBuilder::default() - .with_number_of_bytes_left(1) - .with_event_completed() - .into() - } - - #[test] - fn the_default_torrent_entry_should_contain_an_empty_list_of_peers() { - let torrent_entry = EntrySingle::default(); - - assert_eq!(torrent_entry.get_peers(None).len(), 0); - } - - #[test] - fn a_new_peer_can_be_added_to_a_torrent_entry() { - let mut torrent_entry = EntrySingle::default(); - let torrent_peer = TorrentPeerBuilder::default().into(); - - torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - - assert_eq!(*torrent_entry.get_peers(None)[0], torrent_peer); - assert_eq!(torrent_entry.get_peers(None).len(), 1); - } - - #[test] - fn a_torrent_entry_should_contain_the_list_of_peers_that_were_added_to_the_torrent() { - let mut torrent_entry = EntrySingle::default(); - let torrent_peer = TorrentPeerBuilder::default().into(); - - torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - - assert_eq!(torrent_entry.get_peers(None), vec![Arc::new(torrent_peer)]); - } - - #[test] - fn a_peer_can_be_updated_in_a_torrent_entry() { - let mut torrent_entry = EntrySingle::default(); - let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - - torrent_peer.event = AnnounceEvent::Completed; // Update the peer - torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry - - assert_eq!(torrent_entry.get_peers(None)[0].event, AnnounceEvent::Completed); - } - - #[test] - fn a_peer_should_be_removed_from_a_torrent_entry_when_the_peer_announces_it_has_stopped() { - let mut torrent_entry = EntrySingle::default(); - let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - - torrent_peer.event = AnnounceEvent::Stopped; // Update the peer - torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry - - assert_eq!(torrent_entry.get_peers(None).len(), 0); - } - - #[test] - fn torrent_stats_change_when_a_previously_known_peer_announces_it_has_completed_the_torrent() { - let mut torrent_entry = EntrySingle::default(); - let mut torrent_peer = TorrentPeerBuilder::default().into(); - - torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - - torrent_peer.event = AnnounceEvent::Completed; // Update the peer - let stats_have_changed = torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry - - assert!(stats_have_changed); - } - - #[test] - fn torrent_stats_should_not_change_when_a_peer_announces_it_has_completed_the_torrent_if_it_is_the_first_announce_from_the_peer( - ) { - let mut torrent_entry = EntrySingle::default(); - let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); - - // Add a peer that did not exist before in the entry - let torrent_stats_have_not_changed = !torrent_entry.insert_or_update_peer(&torrent_peer_announcing_complete_event); - - assert!(torrent_stats_have_not_changed); - } - - #[test] - fn a_torrent_entry_should_return_the_list_of_peers_for_a_given_peer_filtering_out_the_client_that_is_making_the_request() - { - let mut torrent_entry = EntrySingle::default(); - let peer_socket_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); - let torrent_peer = TorrentPeerBuilder::default().with_peer_address(peer_socket_address).into(); - torrent_entry.insert_or_update_peer(&torrent_peer); // Add peer - - // Get peers excluding the one we have just added - let peers = torrent_entry.get_peers_for_peer(&torrent_peer, None); - - assert_eq!(peers.len(), 0); - } - - #[test] - fn two_peers_with_the_same_ip_but_different_port_should_be_considered_different_peers() { - let mut torrent_entry = EntrySingle::default(); - - let peer_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); - - // Add peer 1 - let torrent_peer_1 = TorrentPeerBuilder::default() - .with_peer_address(SocketAddr::new(peer_ip, 8080)) - .into(); - torrent_entry.insert_or_update_peer(&torrent_peer_1); - - // Add peer 2 - let torrent_peer_2 = TorrentPeerBuilder::default() - .with_peer_address(SocketAddr::new(peer_ip, 8081)) - .into(); - torrent_entry.insert_or_update_peer(&torrent_peer_2); - - // Get peers for peer 1 - let peers = torrent_entry.get_peers_for_peer(&torrent_peer_1, None); - - // The peer 2 using the same IP but different port should be included - assert_eq!(peers[0].peer_addr.ip(), Ipv4Addr::new(127, 0, 0, 1)); - assert_eq!(peers[0].peer_addr.port(), 8081); - } - - fn peer_id_from_i32(number: i32) -> peer::Id { - let peer_id = number.to_le_bytes(); - peer::Id([ - 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, peer_id[0], peer_id[1], - peer_id[2], peer_id[3], - ]) - } - - #[test] - fn the_tracker_should_limit_the_list_of_peers_to_74_when_clients_scrape_torrents() { - let mut torrent_entry = EntrySingle::default(); - - // We add one more peer than the scrape limit - for peer_number in 1..=74 + 1 { - let torrent_peer = TorrentPeerBuilder::default() - .with_peer_id(peer_id_from_i32(peer_number)) - .into(); - torrent_entry.insert_or_update_peer(&torrent_peer); - } - - let peers = torrent_entry.get_peers(Some(TORRENT_PEERS_LIMIT)); - - assert_eq!(peers.len(), 74); - } - - #[test] - fn torrent_stats_should_have_the_number_of_seeders_for_a_torrent() { - let mut torrent_entry = EntrySingle::default(); - let torrent_seeder = a_torrent_seeder(); - - torrent_entry.insert_or_update_peer(&torrent_seeder); // Add seeder - - assert_eq!(torrent_entry.get_stats().complete, 1); - } - - #[test] - fn torrent_stats_should_have_the_number_of_leechers_for_a_torrent() { - let mut torrent_entry = EntrySingle::default(); - let torrent_leecher = a_torrent_leecher(); - - torrent_entry.insert_or_update_peer(&torrent_leecher); // Add leecher - - assert_eq!(torrent_entry.get_stats().incomplete, 1); - } - - #[test] - fn torrent_stats_should_have_the_number_of_peers_that_having_announced_at_least_two_events_the_latest_one_is_the_completed_event( - ) { - let mut torrent_entry = EntrySingle::default(); - let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - - // Announce "Completed" torrent download event. - torrent_peer.event = AnnounceEvent::Completed; - torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer - - let number_of_previously_known_peers_with_completed_torrent = torrent_entry.get_stats().complete; - - assert_eq!(number_of_previously_known_peers_with_completed_torrent, 1); - } - - #[test] - fn torrent_stats_should_not_include_a_peer_in_the_completed_counter_if_the_peer_has_announced_only_one_event() { - let mut torrent_entry = EntrySingle::default(); - let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); - - // Announce "Completed" torrent download event. - // It's the first event announced from this peer. - torrent_entry.insert_or_update_peer(&torrent_peer_announcing_complete_event); // Add the peer - - let number_of_peers_with_completed_torrent = torrent_entry.get_stats().downloaded; - - assert_eq!(number_of_peers_with_completed_torrent, 0); - } - - #[test] - fn a_torrent_entry_should_remove_a_peer_not_updated_after_a_timeout_in_seconds() { - let mut torrent_entry = EntrySingle::default(); - - let timeout = 120u32; - - let now = clock::Working::now(); - clock::Stopped::local_set(&now); - - let timeout_seconds_before_now = now.sub(Duration::from_secs(u64::from(timeout))); - let inactive_peer = TorrentPeerBuilder::default() - .updated_at(timeout_seconds_before_now.sub(Duration::from_secs(1))) - .into(); - torrent_entry.insert_or_update_peer(&inactive_peer); // Add the peer - - let current_cutoff = clock::Current::sub(&Duration::from_secs(u64::from(timeout))).unwrap_or_default(); - torrent_entry.remove_inactive_peers(current_cutoff); - - assert_eq!(torrent_entry.get_peers_len(), 0); - } - } -} +mod tests {} diff --git a/src/lib.rs b/src/lib.rs index b4ad298ac..064f50eb6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -469,6 +469,9 @@ //! //! In addition to the production code documentation you can find a lot of //! examples on the integration and unit tests. + +use torrust_tracker_clock::{clock, time_extent}; + pub mod app; pub mod bootstrap; pub mod console; @@ -478,3 +481,24 @@ pub mod shared; #[macro_use] extern crate lazy_static; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; + +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type DefaultTimeExtentMaker = time_extent::WorkingTimeExtentMaker; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type DefaultTimeExtentMaker = time_extent::StoppedTimeExtentMaker; diff --git a/src/servers/apis/v1/context/auth_key/resources.rs b/src/servers/apis/v1/context/auth_key/resources.rs index 99e93aaf9..3671438c2 100644 --- a/src/servers/apis/v1/context/auth_key/resources.rs +++ b/src/servers/apis/v1/context/auth_key/resources.rs @@ -1,9 +1,9 @@ //! API resources for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. use serde::{Deserialize, Serialize}; +use torrust_tracker_clock::conv::convert_from_iso_8601_to_timestamp; use crate::core::auth::{self, Key}; -use crate::shared::clock::convert_from_iso_8601_to_timestamp; /// A resource that represents an authentication key. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -41,9 +41,12 @@ impl From for AuthKey { mod tests { use std::time::Duration; + use torrust_tracker_clock::clock::stopped::Stopped as _; + use torrust_tracker_clock::clock::{self, Time}; + use super::AuthKey; use crate::core::auth::{self, Key}; - use crate::shared::clock::{Current, TimeNow}; + use crate::CurrentClock; struct TestTime { pub timestamp: u64, @@ -65,6 +68,8 @@ mod tests { #[test] #[allow(deprecated)] fn it_should_be_convertible_into_an_auth_key() { + clock::Stopped::local_set_to_unix_epoch(); + let auth_key_resource = AuthKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".to_string(), // cspell:disable-line valid_until: one_hour_after_unix_epoch().timestamp, @@ -75,7 +80,7 @@ mod tests { auth::ExpiringKey::from(auth_key_resource), auth::ExpiringKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".parse::().unwrap(), // cspell:disable-line - valid_until: Current::add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap() + valid_until: CurrentClock::now_add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap() } ); } @@ -83,9 +88,11 @@ mod tests { #[test] #[allow(deprecated)] fn it_should_be_convertible_from_an_auth_key() { + clock::Stopped::local_set_to_unix_epoch(); + let auth_key = auth::ExpiringKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".parse::().unwrap(), // cspell:disable-line - valid_until: Current::add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap(), + valid_until: CurrentClock::now_add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap(), }; assert_eq!( diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index 6e8b5a40e..3ef85e600 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -71,7 +71,7 @@ //! is behind a reverse proxy. //! //! > **NOTICE**: the maximum number of peers that the tracker can return is -//! `74`. Defined with a hardcoded const [`TORRENT_PEERS_LIMIT`](crate::core::TORRENT_PEERS_LIMIT). +//! `74`. Defined with a hardcoded const [`TORRENT_PEERS_LIMIT`](torrust_tracker_configuration::TORRENT_PEERS_LIMIT). //! Refer to [issue 262](https://github.com/torrust/torrust-tracker/issues/262) //! for more information about this limitation. //! diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 215acbad8..e9198f20c 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -12,6 +12,7 @@ use std::sync::Arc; use axum::extract::State; use axum::response::{IntoResponse, Response}; use log::debug; +use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::{peer, NumberOfBytes}; @@ -25,7 +26,7 @@ use crate::servers::http::v1::requests::announce::{Announce, Compact, Event}; use crate::servers::http::v1::responses::{self}; use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; use crate::servers::http::v1::services::{self, peer_ip_resolver}; -use crate::shared::clock::{Current, Time}; +use crate::CurrentClock; /// It handles the `announce` request when the HTTP tracker does not require /// authentication (no PATH `key` parameter required). @@ -134,7 +135,7 @@ fn peer_from_request(announce_request: &Announce, peer_ip: &IpAddr) -> peer::Pee peer::Peer { peer_id: announce_request.peer_id, peer_addr: SocketAddr::new(*peer_ip, announce_request.port), - updated: Current::now(), + updated: CurrentClock::now(), uploaded: NumberOfBytes(announce_request.uploaded.unwrap_or(0)), downloaded: NumberOfBytes(announce_request.downloaded.unwrap_or(0)), left: NumberOfBytes(announce_request.left.unwrap_or(0)), diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs index 19e61f14e..49ea6261b 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/servers/udp/connection_cookie.rs @@ -70,9 +70,9 @@ use std::net::SocketAddr; use std::panic::Location; use aquatic_udp_protocol::ConnectionId; +use torrust_tracker_clock::time_extent::{Extent, TimeExtent}; use super::error::Error; -use crate::shared::clock::time_extent::{Extent, TimeExtent}; pub type Cookie = [u8; 8]; @@ -133,9 +133,11 @@ mod cookie_builder { use std::hash::{Hash, Hasher}; use std::net::SocketAddr; + use torrust_tracker_clock::time_extent::{Extent, Make, TimeExtent}; + use super::{Cookie, SinceUnixEpochTimeExtent, COOKIE_LIFETIME}; - use crate::shared::clock::time_extent::{DefaultTimeExtentMaker, Extent, Make, TimeExtent}; use crate::shared::crypto::keys::seeds::{Current, Keeper}; + use crate::DefaultTimeExtentMaker; pub(super) fn get_last_time_extent() -> SinceUnixEpochTimeExtent { DefaultTimeExtentMaker::now(&COOKIE_LIFETIME.increment) @@ -162,10 +164,12 @@ mod cookie_builder { mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use torrust_tracker_clock::clock::stopped::Stopped as _; + use torrust_tracker_clock::clock::{self}; + use torrust_tracker_clock::time_extent::{self, Extent}; + use super::cookie_builder::{self}; use crate::servers::udp::connection_cookie::{check, make, Cookie, COOKIE_LIFETIME}; - use crate::shared::clock::time_extent::{self, Extent}; - use crate::shared::clock::{Stopped, StoppedTime}; // #![feature(const_socketaddr)] // const REMOTE_ADDRESS_IPV4_ZERO: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); @@ -176,6 +180,8 @@ mod tests { const ID_COOKIE_OLD: Cookie = [23, 204, 198, 29, 48, 180, 62, 19]; const ID_COOKIE_NEW: Cookie = [41, 166, 45, 246, 249, 24, 108, 203]; + clock::Stopped::local_set_to_unix_epoch(); + let cookie = make(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)); assert!(cookie == ID_COOKIE_OLD || cookie == ID_COOKIE_NEW); @@ -276,7 +282,7 @@ mod tests { let cookie = make(&remote_address); - Stopped::local_add(&COOKIE_LIFETIME.increment).unwrap(); + clock::Stopped::local_add(&COOKIE_LIFETIME.increment).unwrap(); let cookie_next = make(&remote_address); @@ -298,7 +304,7 @@ mod tests { let cookie = make(&remote_address); - Stopped::local_add(&COOKIE_LIFETIME.increment).unwrap(); + clock::Stopped::local_add(&COOKIE_LIFETIME.increment).unwrap(); check(&remote_address, &cookie).unwrap(); } @@ -307,9 +313,11 @@ mod tests { fn it_should_be_valid_for_the_last_time_extent() { let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); + clock::Stopped::local_set_to_unix_epoch(); + let cookie = make(&remote_address); - Stopped::local_set(&COOKIE_LIFETIME.total().unwrap().unwrap()); + clock::Stopped::local_set(&COOKIE_LIFETIME.total().unwrap().unwrap()); check(&remote_address, &cookie).unwrap(); } @@ -321,7 +329,7 @@ mod tests { let cookie = make(&remote_address); - Stopped::local_set(&COOKIE_LIFETIME.total_next().unwrap().unwrap()); + clock::Stopped::local_set(&COOKIE_LIFETIME.total_next().unwrap().unwrap()); check(&remote_address, &cookie).unwrap(); } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 8f6e6d8b4..59aec0ff3 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -318,6 +318,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; + use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::{peer, NumberOfBytes}; @@ -325,7 +326,7 @@ mod tests { use crate::core::services::tracker_factory; use crate::core::Tracker; - use crate::shared::clock::{Current, Time}; + use crate::CurrentClock; fn tracker_configuration() -> Configuration { default_testing_tracker_configuration() @@ -376,7 +377,7 @@ mod tests { let default_peer = peer::Peer { peer_id: peer::Id([255u8; 20]), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: Current::now(), + updated: CurrentClock::now(), uploaded: NumberOfBytes(0), downloaded: NumberOfBytes(0), left: NumberOfBytes(0), diff --git a/src/servers/udp/peer_builder.rs b/src/servers/udp/peer_builder.rs index 8c8fa10a5..f7eb935a0 100644 --- a/src/servers/udp/peer_builder.rs +++ b/src/servers/udp/peer_builder.rs @@ -1,11 +1,12 @@ //! Logic to extract the peer info from the announce request. use std::net::{IpAddr, SocketAddr}; +use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::{peer, NumberOfBytes}; use super::request::AnnounceWrapper; -use crate::shared::clock::{Current, Time}; +use crate::CurrentClock; /// Extracts the [`peer::Peer`] info from the /// announce request. @@ -20,7 +21,7 @@ pub fn from_request(announce_wrapper: &AnnounceWrapper, peer_ip: &IpAddr) -> pee peer::Peer { peer_id: peer::Id(announce_wrapper.announce_request.peer_id.0), peer_addr: SocketAddr::new(*peer_ip, announce_wrapper.announce_request.port.0), - updated: Current::now(), + updated: CurrentClock::now(), uploaded: NumberOfBytes(announce_wrapper.announce_request.bytes_uploaded.0), downloaded: NumberOfBytes(announce_wrapper.announce_request.bytes_downloaded.0), left: NumberOfBytes(announce_wrapper.announce_request.bytes_left.0), diff --git a/src/shared/clock/mod.rs b/src/shared/clock/mod.rs deleted file mode 100644 index a73878466..000000000 --- a/src/shared/clock/mod.rs +++ /dev/null @@ -1,393 +0,0 @@ -//! Time related functions and types. -//! -//! It's usually a good idea to control where the time comes from -//! in an application so that it can be mocked for testing and it can be -//! controlled in production so we get the intended behavior without -//! relying on the specific time zone for the underlying system. -//! -//! Clocks use the type `DurationSinceUnixEpoch` which is a -//! `std::time::Duration` since the Unix Epoch (timestamp). -//! -//! ```text -//! Local time: lun 2023-03-27 16:12:00 WEST -//! Universal time: lun 2023-03-27 15:12:00 UTC -//! Time zone: Atlantic/Canary (WEST, +0100) -//! Timestamp: 1679929914 -//! Duration: 1679929914.10167426 -//! ``` -//! -//! > **NOTICE**: internally the `Duration` is stores it's main unit as seconds in a `u64` and it will -//! overflow in 584.9 billion years. -//! -//! > **NOTICE**: the timestamp does not depend on the time zone. That gives you -//! the ability to use the clock regardless of the underlying system time zone -//! configuration. See [Unix time Wikipedia entry](https://en.wikipedia.org/wiki/Unix_time). -pub mod static_time; -pub mod time_extent; -pub mod utils; - -use std::num::IntErrorKind; -use std::str::FromStr; -use std::time::Duration; - -use chrono::{DateTime, Utc}; -use torrust_tracker_primitives::DurationSinceUnixEpoch; - -/// Clock types. -#[derive(Debug)] -pub enum Type { - /// Clock that returns the current time. - WorkingClock, - /// Clock that returns always the same fixed time. - StoppedClock, -} - -/// A generic structure that represents a clock. -/// -/// It can be either the working clock (production) or the stopped clock -/// (testing). It implements the `Time` trait, which gives you the current time. -#[derive(Debug)] -pub struct Clock; - -/// The working clock. It returns the current time. -pub type Working = Clock<{ Type::WorkingClock as usize }>; -/// The stopped clock. It returns always the same fixed time. -pub type Stopped = Clock<{ Type::StoppedClock as usize }>; - -/// The current clock. Defined at compilation time. -/// It can be either the working clock (production) or the stopped clock (testing). -#[cfg(not(test))] -pub type Current = Working; - -/// The current clock. Defined at compilation time. -/// It can be either the working clock (production) or the stopped clock (testing). -#[cfg(test)] -pub type Current = Stopped; - -/// Trait for types that can be used as a timestamp clock. -pub trait Time: Sized { - fn now() -> DurationSinceUnixEpoch; -} - -/// Trait for types that can be manipulate the current time in order to -/// get time in the future or in the past after or before a duration of time. -pub trait TimeNow: Time { - #[must_use] - fn add(add_time: &Duration) -> Option { - Self::now().checked_add(*add_time) - } - #[must_use] - fn sub(sub_time: &Duration) -> Option { - Self::now().checked_sub(*sub_time) - } -} - -/// It converts a string in ISO 8601 format to a timestamp. -/// For example, the string `1970-01-01T00:00:00.000Z` which is the Unix Epoch -/// will be converted to a timestamp of 0: `DurationSinceUnixEpoch::ZERO`. -/// -/// # Panics -/// -/// Will panic if the input time cannot be converted to `DateTime::`, internally using the `i64` type. -/// (this will naturally happen in 292.5 billion years) -#[must_use] -pub fn convert_from_iso_8601_to_timestamp(iso_8601: &str) -> DurationSinceUnixEpoch { - convert_from_datetime_utc_to_timestamp(&DateTime::::from_str(iso_8601).unwrap()) -} - -/// It converts a `DateTime::` to a timestamp. -/// For example, the `DateTime::` of the Unix Epoch will be converted to a -/// timestamp of 0: `DurationSinceUnixEpoch::ZERO`. -/// -/// # Panics -/// -/// Will panic if the input time overflows the `u64` type. -/// (this will naturally happen in 584.9 billion years) -#[must_use] -pub fn convert_from_datetime_utc_to_timestamp(datetime_utc: &DateTime) -> DurationSinceUnixEpoch { - DurationSinceUnixEpoch::from_secs(u64::try_from(datetime_utc.timestamp()).expect("Overflow of u64 seconds, very future!")) -} - -/// It converts a timestamp to a `DateTime::`. -/// For example, the timestamp of 0: `DurationSinceUnixEpoch::ZERO` will be -/// converted to the `DateTime::` of the Unix Epoch. -/// -/// # Panics -/// -/// Will panic if the input time overflows the `u64` seconds overflows the `i64` type. -/// (this will naturally happen in 292.5 billion years) -#[must_use] -pub fn convert_from_timestamp_to_datetime_utc(duration: DurationSinceUnixEpoch) -> DateTime { - DateTime::from_timestamp( - i64::try_from(duration.as_secs()).expect("Overflow of i64 seconds, very future!"), - duration.subsec_nanos(), - ) - .unwrap() -} - -#[cfg(test)] -mod tests { - use std::any::TypeId; - - use crate::shared::clock::{Current, Stopped, Time, Working}; - - #[test] - fn it_should_be_the_stopped_clock_as_default_when_testing() { - // We are testing, so we should default to the fixed time. - assert_eq!(TypeId::of::(), TypeId::of::()); - assert_eq!(Stopped::now(), Current::now()); - } - - #[test] - fn it_should_have_different_times() { - assert_ne!(TypeId::of::(), TypeId::of::()); - assert_ne!(Stopped::now(), Working::now()); - } - - mod timestamp { - use chrono::DateTime; - - use crate::shared::clock::{ - convert_from_datetime_utc_to_timestamp, convert_from_iso_8601_to_timestamp, convert_from_timestamp_to_datetime_utc, - DurationSinceUnixEpoch, - }; - - #[test] - fn should_be_converted_to_datetime_utc() { - let timestamp = DurationSinceUnixEpoch::ZERO; - assert_eq!( - convert_from_timestamp_to_datetime_utc(timestamp), - DateTime::from_timestamp(0, 0).unwrap() - ); - } - - #[test] - fn should_be_converted_from_datetime_utc() { - let datetime = DateTime::from_timestamp(0, 0).unwrap(); - assert_eq!( - convert_from_datetime_utc_to_timestamp(&datetime), - DurationSinceUnixEpoch::ZERO - ); - } - - #[test] - fn should_be_converted_from_datetime_utc_in_iso_8601() { - let iso_8601 = "1970-01-01T00:00:00.000Z".to_string(); - assert_eq!(convert_from_iso_8601_to_timestamp(&iso_8601), DurationSinceUnixEpoch::ZERO); - } - } -} - -mod working_clock { - use std::time::SystemTime; - - use super::{DurationSinceUnixEpoch, Time, TimeNow, Working}; - - impl Time for Working { - fn now() -> DurationSinceUnixEpoch { - SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap() - } - } - - impl TimeNow for Working {} -} - -/// Trait for types that can be used as a timestamp clock stopped -/// at a given time. -pub trait StoppedTime: TimeNow { - /// It sets the clock to a given time. - fn local_set(unix_time: &DurationSinceUnixEpoch); - - /// It sets the clock to the Unix Epoch. - fn local_set_to_unix_epoch() { - Self::local_set(&DurationSinceUnixEpoch::ZERO); - } - - /// It sets the clock to the time the application started. - fn local_set_to_app_start_time(); - - /// It sets the clock to the current system time. - fn local_set_to_system_time_now(); - - /// It adds a `Duration` to the clock. - /// - /// # Errors - /// - /// Will return `IntErrorKind` if `duration` would overflow the internal `Duration`. - fn local_add(duration: &Duration) -> Result<(), IntErrorKind>; - - /// It subtracts a `Duration` from the clock. - /// # Errors - /// - /// Will return `IntErrorKind` if `duration` would underflow the internal `Duration`. - fn local_sub(duration: &Duration) -> Result<(), IntErrorKind>; - - /// It resets the clock to default fixed time that is application start time (or the unix epoch when testing). - fn local_reset(); -} - -mod stopped_clock { - use std::num::IntErrorKind; - use std::time::Duration; - - use super::{DurationSinceUnixEpoch, Stopped, StoppedTime, Time, TimeNow}; - - impl Time for Stopped { - fn now() -> DurationSinceUnixEpoch { - detail::FIXED_TIME.with(|time| { - return *time.borrow(); - }) - } - } - - impl TimeNow for Stopped {} - - impl StoppedTime for Stopped { - fn local_set(unix_time: &DurationSinceUnixEpoch) { - detail::FIXED_TIME.with(|time| { - *time.borrow_mut() = *unix_time; - }); - } - - fn local_set_to_app_start_time() { - Self::local_set(&detail::get_app_start_time()); - } - - fn local_set_to_system_time_now() { - Self::local_set(&detail::get_app_start_time()); - } - - fn local_add(duration: &Duration) -> Result<(), IntErrorKind> { - detail::FIXED_TIME.with(|time| { - let time_borrowed = *time.borrow(); - *time.borrow_mut() = match time_borrowed.checked_add(*duration) { - Some(time) => time, - None => { - return Err(IntErrorKind::PosOverflow); - } - }; - Ok(()) - }) - } - - fn local_sub(duration: &Duration) -> Result<(), IntErrorKind> { - detail::FIXED_TIME.with(|time| { - let time_borrowed = *time.borrow(); - *time.borrow_mut() = match time_borrowed.checked_sub(*duration) { - Some(time) => time, - None => { - return Err(IntErrorKind::NegOverflow); - } - }; - Ok(()) - }) - } - - fn local_reset() { - Self::local_set(&detail::get_default_fixed_time()); - } - } - - #[cfg(test)] - mod tests { - use std::thread; - use std::time::Duration; - - use crate::shared::clock::{DurationSinceUnixEpoch, Stopped, StoppedTime, Time, TimeNow, Working}; - - #[test] - fn it_should_default_to_zero_when_testing() { - assert_eq!(Stopped::now(), DurationSinceUnixEpoch::ZERO); - } - - #[test] - fn it_should_possible_to_set_the_time() { - // Check we start with ZERO. - assert_eq!(Stopped::now(), Duration::ZERO); - - // Set to Current Time and Check - let timestamp = Working::now(); - Stopped::local_set(×tamp); - assert_eq!(Stopped::now(), timestamp); - - // Elapse the Current Time and Check - Stopped::local_add(×tamp).unwrap(); - assert_eq!(Stopped::now(), timestamp + timestamp); - - // Reset to ZERO and Check - Stopped::local_reset(); - assert_eq!(Stopped::now(), Duration::ZERO); - } - - #[test] - fn it_should_default_to_zero_on_thread_exit() { - assert_eq!(Stopped::now(), Duration::ZERO); - let after5 = Working::add(&Duration::from_secs(5)).unwrap(); - Stopped::local_set(&after5); - assert_eq!(Stopped::now(), after5); - - let t = thread::spawn(move || { - // each thread starts out with the initial value of ZERO - assert_eq!(Stopped::now(), Duration::ZERO); - - // and gets set to the current time. - let timestamp = Working::now(); - Stopped::local_set(×tamp); - assert_eq!(Stopped::now(), timestamp); - }); - - // wait for the thread to complete and bail out on panic - t.join().unwrap(); - - // we retain our original value of current time + 5sec despite the child thread - assert_eq!(Stopped::now(), after5); - - // Reset to ZERO and Check - Stopped::local_reset(); - assert_eq!(Stopped::now(), Duration::ZERO); - } - } - - mod detail { - use std::cell::RefCell; - use std::time::SystemTime; - - use crate::shared::clock::{static_time, DurationSinceUnixEpoch}; - - pub fn get_app_start_time() -> DurationSinceUnixEpoch { - (*static_time::TIME_AT_APP_START) - .duration_since(SystemTime::UNIX_EPOCH) - .unwrap() - } - - #[cfg(not(test))] - pub fn get_default_fixed_time() -> DurationSinceUnixEpoch { - get_app_start_time() - } - - #[cfg(test)] - pub fn get_default_fixed_time() -> DurationSinceUnixEpoch { - DurationSinceUnixEpoch::ZERO - } - - thread_local!(pub static FIXED_TIME: RefCell = RefCell::new(get_default_fixed_time())); - - #[cfg(test)] - mod tests { - use std::time::Duration; - - use crate::shared::clock::stopped_clock::detail::{get_app_start_time, get_default_fixed_time}; - - #[test] - fn it_should_get_the_zero_start_time_when_testing() { - assert_eq!(get_default_fixed_time(), Duration::ZERO); - } - - #[test] - fn it_should_get_app_start_time() { - const TIME_AT_WRITING_THIS_TEST: Duration = Duration::new(1_662_983_731, 22312); - assert!(get_app_start_time() > TIME_AT_WRITING_THIS_TEST); - } - } - } -} diff --git a/src/shared/clock/utils.rs b/src/shared/clock/utils.rs deleted file mode 100644 index 8b1378917..000000000 --- a/src/shared/clock/utils.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/shared/mod.rs b/src/shared/mod.rs index f016ba913..8c95effe1 100644 --- a/src/shared/mod.rs +++ b/src/shared/mod.rs @@ -1,8 +1,6 @@ //! Modules with generic logic used by several modules. //! //! - [`bit_torrent`]: `BitTorrent` protocol related logic. -//! - [`clock`]: Times services. //! - [`crypto`]: Encryption related logic. pub mod bit_torrent; -pub mod clock; pub mod crypto; diff --git a/tests/common/clock.rs b/tests/common/clock.rs new file mode 100644 index 000000000..5d94bb83d --- /dev/null +++ b/tests/common/clock.rs @@ -0,0 +1,16 @@ +use std::time::Duration; + +use torrust_tracker_clock::clock::Time; + +use crate::CurrentClock; + +#[test] +fn it_should_use_stopped_time_for_testing() { + assert_eq!(CurrentClock::dbg_clock_type(), "Stopped".to_owned()); + + let time = CurrentClock::now(); + std::thread::sleep(Duration::from_millis(50)); + let time_2 = CurrentClock::now(); + + assert_eq!(time, time_2); +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index b57996292..281c1fb9c 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,3 +1,4 @@ +pub mod clock; pub mod fixtures; pub mod http; pub mod udp; diff --git a/tests/integration.rs b/tests/integration.rs index 5d66d9074..8e3d46826 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -3,5 +3,18 @@ //! ```text //! cargo test --test integration //! ``` + +use torrust_tracker_clock::clock; mod common; mod servers; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; From e18cae46e74f2f38bdbd2ee064b3c986c01ed7f6 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 25 Mar 2024 12:12:46 +0800 Subject: [PATCH 0272/1297] dev: torrent repository cleanups --- cSpell.json | 1 + packages/configuration/src/lib.rs | 2 +- packages/primitives/src/announce_event.rs | 2 +- packages/primitives/src/info_hash.rs | 19 + packages/primitives/src/lib.rs | 5 +- packages/primitives/src/pagination.rs | 8 +- packages/primitives/src/peer.rs | 24 +- packages/primitives/src/torrent_metrics.rs | 12 +- packages/torrent-repository/src/entry/mod.rs | 31 +- .../torrent-repository/src/entry/mutex_std.rs | 17 +- .../src/entry/mutex_tokio.rs | 25 +- .../torrent-repository/src/entry/single.rs | 324 +----------------- .../torrent-repository/src/repository/mod.rs | 38 +- .../src/repository/rw_lock_std.rs | 12 +- .../src/repository/rw_lock_std_mutex_std.rs | 10 +- .../src/repository/rw_lock_std_mutex_tokio.rs | 30 +- .../src/repository/rw_lock_tokio.rs | 10 +- .../src/repository/rw_lock_tokio_mutex_std.rs | 10 +- .../repository/rw_lock_tokio_mutex_tokio.rs | 22 +- src/core/databases/mod.rs | 4 +- src/core/databases/mysql.rs | 6 +- src/core/databases/sqlite.rs | 11 +- src/core/mod.rs | 20 +- src/core/torrent/mod.rs | 3 - .../apis/v1/context/stats/resources.rs | 12 +- src/servers/udp/handlers.rs | 63 ++-- 26 files changed, 259 insertions(+), 462 deletions(-) diff --git a/cSpell.json b/cSpell.json index 1e276dbc2..bbcba98a7 100644 --- a/cSpell.json +++ b/cSpell.json @@ -100,6 +100,7 @@ "ostr", "Pando", "peekable", + "peerlist", "proot", "proto", "Quickstart", diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 549c73a31..ca873f3cd 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -246,7 +246,7 @@ use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; /// The maximum number of returned peers for a torrent. pub const TORRENT_PEERS_LIMIT: usize = 74; -#[derive(Copy, Clone, Debug, PartialEq, Default, Constructor)] +#[derive(Copy, Clone, Debug, PartialEq, Constructor)] pub struct TrackerPolicy { pub remove_peerless_torrents: bool, pub max_peer_timeout: u32, diff --git a/packages/primitives/src/announce_event.rs b/packages/primitives/src/announce_event.rs index 16e47da99..3bd560084 100644 --- a/packages/primitives/src/announce_event.rs +++ b/packages/primitives/src/announce_event.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; /// Announce events. Described on the /// [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, Serialize, Deserialize)] +#[derive(Hash, Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub enum AnnounceEvent { /// The peer has started downloading the torrent. Started, diff --git a/packages/primitives/src/info_hash.rs b/packages/primitives/src/info_hash.rs index 46ae6283e..a07cc41a2 100644 --- a/packages/primitives/src/info_hash.rs +++ b/packages/primitives/src/info_hash.rs @@ -1,3 +1,4 @@ +use std::hash::{DefaultHasher, Hash, Hasher}; use std::panic::Location; use thiserror::Error; @@ -77,6 +78,24 @@ impl std::convert::From<&[u8]> for InfoHash { } } +/// for testing +impl std::convert::From<&DefaultHasher> for InfoHash { + fn from(data: &DefaultHasher) -> InfoHash { + let n = data.finish().to_le_bytes(); + InfoHash([ + n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[0], n[1], n[2], + n[3], + ]) + } +} + +impl std::convert::From<&i32> for InfoHash { + fn from(n: &i32) -> InfoHash { + let n = n.to_le_bytes(); + InfoHash([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, n[0], n[1], n[2], n[3]]) + } +} + impl std::convert::From<[u8; 20]> for InfoHash { fn from(val: [u8; 20]) -> Self { InfoHash(val) diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index 664c0c82d..aeb4d0d4e 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -4,6 +4,7 @@ //! which is a `BitTorrent` tracker server. These structures are used not only //! by the tracker server crate, but also by other crates in the Torrust //! ecosystem. +use std::collections::BTreeMap; use std::time::Duration; use info_hash::InfoHash; @@ -38,7 +39,7 @@ pub enum IPVersion { } /// Number of bytes downloaded, uploaded or pending to download (left) by the peer. -#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, Serialize, Deserialize)] +#[derive(Hash, Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub struct NumberOfBytes(pub i64); /// The database management system used by the tracker. @@ -58,7 +59,7 @@ pub enum DatabaseDriver { MySQL, } -pub type PersistentTorrents = Vec<(InfoHash, u32)>; +pub type PersistentTorrents = BTreeMap; /// The mode the tracker will run in. /// diff --git a/packages/primitives/src/pagination.rs b/packages/primitives/src/pagination.rs index ab7dcfe2b..96b5ad662 100644 --- a/packages/primitives/src/pagination.rs +++ b/packages/primitives/src/pagination.rs @@ -1,7 +1,8 @@ +use derive_more::Constructor; use serde::Deserialize; /// A struct to keep information about the page when results are being paginated -#[derive(Deserialize, Copy, Clone, Debug, PartialEq)] +#[derive(Deserialize, Copy, Clone, Debug, PartialEq, Constructor)] pub struct Pagination { /// The page number, starting at 0 pub offset: u32, @@ -10,11 +11,6 @@ pub struct Pagination { } impl Pagination { - #[must_use] - pub fn new(offset: u32, limit: u32) -> Self { - Self { offset, limit } - } - #[must_use] pub fn new_with_options(offset_option: Option, limit_option: Option) -> Self { let offset = match offset_option { diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index 5fb9e525f..f5b009f2a 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -51,7 +51,7 @@ use crate::{ser_unix_time_value, DurationSinceUnixEpoch, IPVersion, NumberOfByte /// event: AnnounceEvent::Started, /// }; /// ``` -#[derive(PartialEq, Eq, Debug, Clone, Serialize, Copy)] +#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Peer { /// ID used by the downloader peer pub peer_id: Id, @@ -173,6 +173,16 @@ impl From<[u8; 20]> for Id { } } +impl From for Id { + fn from(number: i32) -> Self { + let peer_id = number.to_le_bytes(); + Id::from([ + 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, peer_id[0], peer_id[1], peer_id[2], + peer_id[3], + ]) + } +} + impl TryFrom> for Id { type Error = IdConversionError; @@ -332,7 +342,7 @@ impl FromIterator for Vec

{ } pub mod fixture { - use std::net::SocketAddr; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use super::{Id, Peer}; use crate::announce_event::AnnounceEvent; @@ -396,8 +406,8 @@ pub mod fixture { impl Default for Peer { fn default() -> Self { Self { - peer_id: Id(*b"-qB00000000000000000"), - peer_addr: std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::new(126, 0, 0, 1)), 8080), + peer_id: Id::default(), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes(0), downloaded: NumberOfBytes(0), @@ -406,6 +416,12 @@ pub mod fixture { } } } + + impl Default for Id { + fn default() -> Self { + Self(*b"-qB00000000000000000") + } + } } #[cfg(test)] diff --git a/packages/primitives/src/torrent_metrics.rs b/packages/primitives/src/torrent_metrics.rs index c60507171..02de02954 100644 --- a/packages/primitives/src/torrent_metrics.rs +++ b/packages/primitives/src/torrent_metrics.rs @@ -6,20 +6,20 @@ use std::ops::AddAssign; #[derive(Copy, Clone, Debug, PartialEq, Default)] pub struct TorrentsMetrics { /// Total number of seeders for all torrents - pub seeders: u64, + pub complete: u64, /// Total number of peers that have ever completed downloading for all torrents. - pub completed: u64, + pub downloaded: u64, /// Total number of leechers for all torrents. - pub leechers: u64, + pub incomplete: u64, /// Total number of torrents. pub torrents: u64, } impl AddAssign for TorrentsMetrics { fn add_assign(&mut self, rhs: Self) { - self.seeders += rhs.seeders; - self.completed += rhs.completed; - self.leechers += rhs.leechers; + self.complete += rhs.complete; + self.downloaded += rhs.downloaded; + self.incomplete += rhs.incomplete; self.torrents += rhs.torrents; } } diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index 11352a8fa..4c39af829 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -1,4 +1,5 @@ use std::fmt::Debug; +use std::net::SocketAddr; use std::sync::Arc; //use serde::{Deserialize, Serialize}; @@ -17,7 +18,7 @@ pub trait Entry { fn get_stats(&self) -> SwarmMetadata; /// Returns True if Still a Valid Entry according to the Tracker Policy - fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool; + fn is_good(&self, policy: &TrackerPolicy) -> bool; /// Returns True if the Peers is Empty fn peers_is_empty(&self) -> bool; @@ -33,7 +34,7 @@ pub trait Entry { /// /// It filters out the input peer, typically because we want to return this /// list of peers to that client peer. - fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec>; + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec>; /// It updates a peer and returns true if the number of complete downloads have increased. /// @@ -51,11 +52,11 @@ pub trait Entry { #[allow(clippy::module_name_repetitions)] pub trait EntrySync { fn get_stats(&self) -> SwarmMetadata; - fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool; + fn is_good(&self, policy: &TrackerPolicy) -> bool; fn peers_is_empty(&self) -> bool; fn get_peers_len(&self) -> usize; fn get_peers(&self, limit: Option) -> Vec>; - fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec>; + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec>; fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool; fn insert_or_update_peer_and_get_stats(&self, peer: &peer::Peer) -> (bool, SwarmMetadata); fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); @@ -63,16 +64,14 @@ pub trait EntrySync { #[allow(clippy::module_name_repetitions)] pub trait EntryAsync { - fn get_stats(self) -> impl std::future::Future + Send; - - #[allow(clippy::wrong_self_convention)] - fn is_not_zombie(self, policy: &TrackerPolicy) -> impl std::future::Future + Send; - fn peers_is_empty(self) -> impl std::future::Future + Send; - fn get_peers_len(self) -> impl std::future::Future + Send; - fn get_peers(self, limit: Option) -> impl std::future::Future>> + Send; - fn get_peers_for_peer( - self, - client: &peer::Peer, + fn get_stats(&self) -> impl std::future::Future + Send; + fn check_good(self, policy: &TrackerPolicy) -> impl std::future::Future + Send; + fn peers_is_empty(&self) -> impl std::future::Future + Send; + fn get_peers_len(&self) -> impl std::future::Future + Send; + fn get_peers(&self, limit: Option) -> impl std::future::Future>> + Send; + fn get_peers_for_client( + &self, + client: &SocketAddr, limit: Option, ) -> impl std::future::Future>> + Send; fn insert_or_update_peer(self, peer: &peer::Peer) -> impl std::future::Future + Send; @@ -88,11 +87,11 @@ pub trait EntryAsync { /// This is the tracker entry for a given torrent and contains the swarm data, /// that's the list of all the peers trying to download the same torrent. /// The tracker keeps one entry like this for every torrent. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Torrent { /// The swarm: a network of peers that are all trying to download the torrent associated to this entry // #[serde(skip)] pub(crate) peers: std::collections::BTreeMap>, /// The number of peers that have ever completed downloading the torrent associated to this entry - pub(crate) completed: u32, + pub(crate) downloaded: u32, } diff --git a/packages/torrent-repository/src/entry/mutex_std.rs b/packages/torrent-repository/src/entry/mutex_std.rs index df6228317..b4b823909 100644 --- a/packages/torrent-repository/src/entry/mutex_std.rs +++ b/packages/torrent-repository/src/entry/mutex_std.rs @@ -1,3 +1,4 @@ +use std::net::SocketAddr; use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; @@ -5,15 +6,15 @@ use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use super::{Entry, EntrySync}; -use crate::EntryMutexStd; +use crate::{EntryMutexStd, EntrySingle}; impl EntrySync for EntryMutexStd { fn get_stats(&self) -> SwarmMetadata { self.lock().expect("it should get a lock").get_stats() } - fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool { - self.lock().expect("it should get a lock").is_not_zombie(policy) + fn is_good(&self, policy: &TrackerPolicy) -> bool { + self.lock().expect("it should get a lock").is_good(policy) } fn peers_is_empty(&self) -> bool { @@ -28,8 +29,8 @@ impl EntrySync for EntryMutexStd { self.lock().expect("it should get lock").get_peers(limit) } - fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec> { - self.lock().expect("it should get lock").get_peers_for_peer(client, limit) + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.lock().expect("it should get lock").get_peers_for_client(client, limit) } fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool { @@ -48,3 +49,9 @@ impl EntrySync for EntryMutexStd { .remove_inactive_peers(current_cutoff); } } + +impl From for EntryMutexStd { + fn from(entry: EntrySingle) -> Self { + Arc::new(std::sync::Mutex::new(entry)) + } +} diff --git a/packages/torrent-repository/src/entry/mutex_tokio.rs b/packages/torrent-repository/src/entry/mutex_tokio.rs index c4d13fb43..34f4a4e92 100644 --- a/packages/torrent-repository/src/entry/mutex_tokio.rs +++ b/packages/torrent-repository/src/entry/mutex_tokio.rs @@ -1,3 +1,4 @@ +use std::net::SocketAddr; use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; @@ -5,31 +6,31 @@ use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use super::{Entry, EntryAsync}; -use crate::EntryMutexTokio; +use crate::{EntryMutexTokio, EntrySingle}; impl EntryAsync for EntryMutexTokio { - async fn get_stats(self) -> SwarmMetadata { + async fn get_stats(&self) -> SwarmMetadata { self.lock().await.get_stats() } - async fn is_not_zombie(self, policy: &TrackerPolicy) -> bool { - self.lock().await.is_not_zombie(policy) + async fn check_good(self, policy: &TrackerPolicy) -> bool { + self.lock().await.is_good(policy) } - async fn peers_is_empty(self) -> bool { + async fn peers_is_empty(&self) -> bool { self.lock().await.peers_is_empty() } - async fn get_peers_len(self) -> usize { + async fn get_peers_len(&self) -> usize { self.lock().await.get_peers_len() } - async fn get_peers(self, limit: Option) -> Vec> { + async fn get_peers(&self, limit: Option) -> Vec> { self.lock().await.get_peers(limit) } - async fn get_peers_for_peer(self, client: &peer::Peer, limit: Option) -> Vec> { - self.lock().await.get_peers_for_peer(client, limit) + async fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.lock().await.get_peers_for_client(client, limit) } async fn insert_or_update_peer(self, peer: &peer::Peer) -> bool { @@ -44,3 +45,9 @@ impl EntryAsync for EntryMutexTokio { self.lock().await.remove_inactive_peers(current_cutoff); } } + +impl From for EntryMutexTokio { + fn from(entry: EntrySingle) -> Self { + Arc::new(tokio::sync::Mutex::new(entry)) + } +} diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs index 85fdc6cf0..c1041e9a2 100644 --- a/packages/torrent-repository/src/entry/single.rs +++ b/packages/torrent-repository/src/entry/single.rs @@ -1,3 +1,4 @@ +use std::net::SocketAddr; use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; @@ -16,14 +17,14 @@ impl Entry for EntrySingle { let incomplete: u32 = self.peers.len() as u32 - complete; SwarmMetadata { - downloaded: self.completed, + downloaded: self.downloaded, complete, incomplete, } } - fn is_not_zombie(&self, policy: &TrackerPolicy) -> bool { - if policy.persistent_torrent_completed_stat && self.completed > 0 { + fn is_good(&self, policy: &TrackerPolicy) -> bool { + if policy.persistent_torrent_completed_stat && self.downloaded > 0 { return true; } @@ -48,13 +49,13 @@ impl Entry for EntrySingle { } } - fn get_peers_for_peer(&self, client: &peer::Peer, limit: Option) -> Vec> { + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { match limit { Some(limit) => self .peers .values() // Take peers which are not the client peer - .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != peer::ReadInfo::get_address(client)) + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *client) // Limit the number of peers on the result .take(limit) .cloned() @@ -63,25 +64,25 @@ impl Entry for EntrySingle { .peers .values() // Take peers which are not the client peer - .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != peer::ReadInfo::get_address(client)) + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *client) .cloned() .collect(), } } fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool { - let mut did_torrent_stats_change: bool = false; + let mut downloaded_stats_updated: bool = false; match peer::ReadInfo::get_event(peer) { AnnounceEvent::Stopped => { drop(self.peers.remove(&peer::ReadInfo::get_id(peer))); } AnnounceEvent::Completed => { - let peer_old = self.peers.insert(peer::ReadInfo::get_id(peer), Arc::new(*peer)); + let previous = self.peers.insert(peer::ReadInfo::get_id(peer), Arc::new(*peer)); // Don't count if peer was not previously known and not already completed. - if peer_old.is_some_and(|p| p.event != AnnounceEvent::Completed) { - self.completed += 1; - did_torrent_stats_change = true; + if previous.is_some_and(|p| p.event != AnnounceEvent::Completed) { + self.downloaded += 1; + downloaded_stats_updated = true; } } _ => { @@ -89,7 +90,7 @@ impl Entry for EntrySingle { } } - did_torrent_stats_change + downloaded_stats_updated } fn insert_or_update_peer_and_get_stats(&mut self, peer: &peer::Peer) -> (bool, SwarmMetadata) { @@ -103,302 +104,3 @@ impl Entry for EntrySingle { .retain(|_, peer| peer::ReadInfo::get_updated(peer) > current_cutoff); } } - -#[cfg(test)] -mod tests { - mod torrent_entry { - - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::ops::Sub; - use std::sync::Arc; - use std::time::Duration; - - use torrust_tracker_clock::clock::stopped::Stopped as _; - use torrust_tracker_clock::clock::{self, Time}; - use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; - use torrust_tracker_primitives::announce_event::AnnounceEvent; - use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; - - use crate::entry::Entry; - use crate::{CurrentClock, EntrySingle}; - - struct TorrentPeerBuilder { - peer: peer::Peer, - } - - impl TorrentPeerBuilder { - pub fn default() -> TorrentPeerBuilder { - let default_peer = peer::Peer { - peer_id: peer::Id([0u8; 20]), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), - updated: CurrentClock::now(), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Started, - }; - TorrentPeerBuilder { peer: default_peer } - } - - pub fn with_event_completed(mut self) -> Self { - self.peer.event = AnnounceEvent::Completed; - self - } - - pub fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { - self.peer.peer_addr = peer_addr; - self - } - - pub fn with_peer_id(mut self, peer_id: peer::Id) -> Self { - self.peer.peer_id = peer_id; - self - } - - pub fn with_number_of_bytes_left(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes(left); - self - } - - pub fn updated_at(mut self, updated: DurationSinceUnixEpoch) -> Self { - self.peer.updated = updated; - self - } - - pub fn into(self) -> peer::Peer { - self.peer - } - } - - /// A torrent seeder is a peer with 0 bytes left to download which - /// has not announced it has stopped - fn a_torrent_seeder() -> peer::Peer { - TorrentPeerBuilder::default() - .with_number_of_bytes_left(0) - .with_event_completed() - .into() - } - - /// A torrent leecher is a peer that is not a seeder. - /// Leecher: left > 0 OR event = Stopped - fn a_torrent_leecher() -> peer::Peer { - TorrentPeerBuilder::default() - .with_number_of_bytes_left(1) - .with_event_completed() - .into() - } - - #[test] - fn the_default_torrent_entry_should_contain_an_empty_list_of_peers() { - let torrent_entry = EntrySingle::default(); - - assert_eq!(torrent_entry.get_peers(None).len(), 0); - } - - #[test] - fn a_new_peer_can_be_added_to_a_torrent_entry() { - let mut torrent_entry = EntrySingle::default(); - let torrent_peer = TorrentPeerBuilder::default().into(); - - torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - - assert_eq!(*torrent_entry.get_peers(None)[0], torrent_peer); - assert_eq!(torrent_entry.get_peers(None).len(), 1); - } - - #[test] - fn a_torrent_entry_should_contain_the_list_of_peers_that_were_added_to_the_torrent() { - let mut torrent_entry = EntrySingle::default(); - let torrent_peer = TorrentPeerBuilder::default().into(); - - torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - - assert_eq!(torrent_entry.get_peers(None), vec![Arc::new(torrent_peer)]); - } - - #[test] - fn a_peer_can_be_updated_in_a_torrent_entry() { - let mut torrent_entry = EntrySingle::default(); - let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - - torrent_peer.event = AnnounceEvent::Completed; // Update the peer - torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry - - assert_eq!(torrent_entry.get_peers(None)[0].event, AnnounceEvent::Completed); - } - - #[test] - fn a_peer_should_be_removed_from_a_torrent_entry_when_the_peer_announces_it_has_stopped() { - let mut torrent_entry = EntrySingle::default(); - let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - - torrent_peer.event = AnnounceEvent::Stopped; // Update the peer - torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry - - assert_eq!(torrent_entry.get_peers(None).len(), 0); - } - - #[test] - fn torrent_stats_change_when_a_previously_known_peer_announces_it_has_completed_the_torrent() { - let mut torrent_entry = EntrySingle::default(); - let mut torrent_peer = TorrentPeerBuilder::default().into(); - - torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - - torrent_peer.event = AnnounceEvent::Completed; // Update the peer - let stats_have_changed = torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer in the torrent entry - - assert!(stats_have_changed); - } - - #[test] - fn torrent_stats_should_not_change_when_a_peer_announces_it_has_completed_the_torrent_if_it_is_the_first_announce_from_the_peer( - ) { - let mut torrent_entry = EntrySingle::default(); - let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); - - // Add a peer that did not exist before in the entry - let torrent_stats_have_not_changed = !torrent_entry.insert_or_update_peer(&torrent_peer_announcing_complete_event); - - assert!(torrent_stats_have_not_changed); - } - - #[test] - fn a_torrent_entry_should_return_the_list_of_peers_for_a_given_peer_filtering_out_the_client_that_is_making_the_request() - { - let mut torrent_entry = EntrySingle::default(); - let peer_socket_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); - let torrent_peer = TorrentPeerBuilder::default().with_peer_address(peer_socket_address).into(); - torrent_entry.insert_or_update_peer(&torrent_peer); // Add peer - - // Get peers excluding the one we have just added - let peers = torrent_entry.get_peers_for_peer(&torrent_peer, None); - - assert_eq!(peers.len(), 0); - } - - #[test] - fn two_peers_with_the_same_ip_but_different_port_should_be_considered_different_peers() { - let mut torrent_entry = EntrySingle::default(); - - let peer_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); - - // Add peer 1 - let torrent_peer_1 = TorrentPeerBuilder::default() - .with_peer_address(SocketAddr::new(peer_ip, 8080)) - .into(); - torrent_entry.insert_or_update_peer(&torrent_peer_1); - - // Add peer 2 - let torrent_peer_2 = TorrentPeerBuilder::default() - .with_peer_address(SocketAddr::new(peer_ip, 8081)) - .into(); - torrent_entry.insert_or_update_peer(&torrent_peer_2); - - // Get peers for peer 1 - let peers = torrent_entry.get_peers_for_peer(&torrent_peer_1, None); - - // The peer 2 using the same IP but different port should be included - assert_eq!(peers[0].peer_addr.ip(), Ipv4Addr::new(127, 0, 0, 1)); - assert_eq!(peers[0].peer_addr.port(), 8081); - } - - fn peer_id_from_i32(number: i32) -> peer::Id { - let peer_id = number.to_le_bytes(); - peer::Id([ - 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, peer_id[0], peer_id[1], - peer_id[2], peer_id[3], - ]) - } - - #[test] - fn the_tracker_should_limit_the_list_of_peers_to_74_when_clients_scrape_torrents() { - let mut torrent_entry = EntrySingle::default(); - - // We add one more peer than the scrape limit - for peer_number in 1..=74 + 1 { - let torrent_peer = TorrentPeerBuilder::default() - .with_peer_id(peer_id_from_i32(peer_number)) - .into(); - torrent_entry.insert_or_update_peer(&torrent_peer); - } - - let peers = torrent_entry.get_peers(Some(TORRENT_PEERS_LIMIT)); - - assert_eq!(peers.len(), 74); - } - - #[test] - fn torrent_stats_should_have_the_number_of_seeders_for_a_torrent() { - let mut torrent_entry = EntrySingle::default(); - let torrent_seeder = a_torrent_seeder(); - - torrent_entry.insert_or_update_peer(&torrent_seeder); // Add seeder - - assert_eq!(torrent_entry.get_stats().complete, 1); - } - - #[test] - fn torrent_stats_should_have_the_number_of_leechers_for_a_torrent() { - let mut torrent_entry = EntrySingle::default(); - let torrent_leecher = a_torrent_leecher(); - - torrent_entry.insert_or_update_peer(&torrent_leecher); // Add leecher - - assert_eq!(torrent_entry.get_stats().incomplete, 1); - } - - #[test] - fn torrent_stats_should_have_the_number_of_peers_that_having_announced_at_least_two_events_the_latest_one_is_the_completed_event( - ) { - let mut torrent_entry = EntrySingle::default(); - let mut torrent_peer = TorrentPeerBuilder::default().into(); - torrent_entry.insert_or_update_peer(&torrent_peer); // Add the peer - - // Announce "Completed" torrent download event. - torrent_peer.event = AnnounceEvent::Completed; - torrent_entry.insert_or_update_peer(&torrent_peer); // Update the peer - - let number_of_previously_known_peers_with_completed_torrent = torrent_entry.get_stats().complete; - - assert_eq!(number_of_previously_known_peers_with_completed_torrent, 1); - } - - #[test] - fn torrent_stats_should_not_include_a_peer_in_the_completed_counter_if_the_peer_has_announced_only_one_event() { - let mut torrent_entry = EntrySingle::default(); - let torrent_peer_announcing_complete_event = TorrentPeerBuilder::default().with_event_completed().into(); - - // Announce "Completed" torrent download event. - // It's the first event announced from this peer. - torrent_entry.insert_or_update_peer(&torrent_peer_announcing_complete_event); // Add the peer - - let number_of_peers_with_completed_torrent = torrent_entry.get_stats().downloaded; - - assert_eq!(number_of_peers_with_completed_torrent, 0); - } - - #[test] - fn a_torrent_entry_should_remove_a_peer_not_updated_after_a_timeout_in_seconds() { - let mut torrent_entry = EntrySingle::default(); - - let timeout = 120u32; - - let now = clock::Working::now(); - clock::Stopped::local_set(&now); - - let timeout_seconds_before_now = now.sub(Duration::from_secs(u64::from(timeout))); - let inactive_peer = TorrentPeerBuilder::default() - .updated_at(timeout_seconds_before_now.sub(Duration::from_secs(1))) - .into(); - torrent_entry.insert_or_update_peer(&inactive_peer); // Add the peer - - let current_cutoff = CurrentClock::now_sub(&Duration::from_secs(u64::from(timeout))).unwrap_or_default(); - torrent_entry.remove_inactive_peers(current_cutoff); - - assert_eq!(torrent_entry.get_peers_len(), 0); - } - } -} diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs index b46771163..494040c9d 100644 --- a/packages/torrent-repository/src/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -12,7 +12,9 @@ pub mod rw_lock_tokio; pub mod rw_lock_tokio_mutex_std; pub mod rw_lock_tokio_mutex_tokio; -pub trait Repository: Default + 'static { +use std::fmt::Debug; + +pub trait Repository: Debug + Default + Sized + 'static { fn get(&self, key: &InfoHash) -> Option; fn get_metrics(&self) -> TorrentsMetrics; fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, T)>; @@ -24,7 +26,7 @@ pub trait Repository: Default + 'static { } #[allow(clippy::module_name_repetitions)] -pub trait RepositoryAsync: Default + 'static { +pub trait RepositoryAsync: Debug + Default + Sized + 'static { fn get(&self, key: &InfoHash) -> impl std::future::Future> + Send; fn get_metrics(&self) -> impl std::future::Future + Send; fn get_paginated(&self, pagination: Option<&Pagination>) -> impl std::future::Future> + Send; @@ -39,12 +41,36 @@ pub trait RepositoryAsync: Default + 'static { ) -> impl std::future::Future + Send; } -#[derive(Default)] +#[derive(Default, Debug)] +pub struct RwLockStd { + torrents: std::sync::RwLock>, +} + +#[derive(Default, Debug)] pub struct RwLockTokio { torrents: tokio::sync::RwLock>, } -#[derive(Default)] -pub struct RwLockStd { - torrents: std::sync::RwLock>, +impl RwLockStd { + /// # Panics + /// + /// Panics if unable to get a lock. + pub fn write( + &self, + ) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { + self.torrents.write().expect("it should get lock") + } +} + +impl RwLockTokio { + pub fn write( + &self, + ) -> impl std::future::Future< + Output = tokio::sync::RwLockWriteGuard< + '_, + std::collections::BTreeMap, + >, + > { + self.torrents.write() + } } diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs index bacef623d..9d7f29416 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std.rs @@ -49,9 +49,9 @@ where for entry in self.get_torrents().values() { let stats = entry.get_stats(); - metrics.seeders += u64::from(stats.complete); - metrics.completed += u64::from(stats.downloaded); - metrics.leechers += u64::from(stats.incomplete); + metrics.complete += u64::from(stats.complete); + metrics.downloaded += u64::from(stats.downloaded); + metrics.incomplete += u64::from(stats.incomplete); metrics.torrents += 1; } @@ -75,7 +75,7 @@ where fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { let mut torrents = self.get_torrents_mut(); - for (info_hash, completed) in persistent_torrents { + for (info_hash, downloaded) in persistent_torrents { // Skip if torrent entry already exists if torrents.contains_key(info_hash) { continue; @@ -83,7 +83,7 @@ where let entry = EntrySingle { peers: BTreeMap::default(), - completed: *completed, + downloaded: *downloaded, }; torrents.insert(*info_hash, entry); @@ -107,6 +107,6 @@ where fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { let mut db = self.get_torrents_mut(); - db.retain(|_, e| e.is_not_zombie(policy)); + db.retain(|_, e| e.is_good(policy)); } } diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs index 9fca82ba8..0b65234e3 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs @@ -57,9 +57,9 @@ where for entry in self.get_torrents().values() { let stats = entry.lock().expect("it should get a lock").get_stats(); - metrics.seeders += u64::from(stats.complete); - metrics.completed += u64::from(stats.downloaded); - metrics.leechers += u64::from(stats.incomplete); + metrics.complete += u64::from(stats.complete); + metrics.downloaded += u64::from(stats.downloaded); + metrics.incomplete += u64::from(stats.incomplete); metrics.torrents += 1; } @@ -92,7 +92,7 @@ where let entry = EntryMutexStd::new( EntrySingle { peers: BTreeMap::default(), - completed: *completed, + downloaded: *completed, } .into(), ); @@ -118,6 +118,6 @@ where fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { let mut db = self.get_torrents_mut(); - db.retain(|_, e| e.lock().expect("it should lock entry").is_not_zombie(policy)); + db.retain(|_, e| e.lock().expect("it should lock entry").is_good(policy)); } } diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs index b9fb54469..5394abb6a 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs @@ -1,4 +1,5 @@ use std::collections::BTreeMap; +use std::iter::zip; use std::pin::Pin; use std::sync::Arc; @@ -75,9 +76,9 @@ where for entry in entries { let stats = entry.lock().await.get_stats(); - metrics.seeders += u64::from(stats.complete); - metrics.completed += u64::from(stats.downloaded); - metrics.leechers += u64::from(stats.incomplete); + metrics.complete += u64::from(stats.complete); + metrics.downloaded += u64::from(stats.downloaded); + metrics.incomplete += u64::from(stats.incomplete); metrics.torrents += 1; } @@ -96,7 +97,7 @@ where let entry = EntryMutexTokio::new( EntrySingle { peers: BTreeMap::default(), - completed: *completed, + downloaded: *completed, } .into(), ); @@ -124,8 +125,27 @@ where } async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let handles: Vec> + Send>>>; + + { + let db = self.get_torrents(); + + handles = zip(db.keys().copied(), db.values().cloned()) + .map(|(infohash, torrent)| { + torrent + .check_good(policy) + .map(move |good| if good { None } else { Some(infohash) }) + .boxed() + }) + .collect::>(); + } + + let not_good = join_all(handles).await; + let mut db = self.get_torrents_mut(); - db.retain(|_, e| e.blocking_lock().is_not_zombie(policy)); + for remove in not_good.into_iter().flatten() { + drop(db.remove(&remove)); + } } } diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs index d0b7ec751..fa84e2451 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio.rs @@ -64,9 +64,9 @@ where for entry in self.get_torrents().await.values() { let stats = entry.get_stats(); - metrics.seeders += u64::from(stats.complete); - metrics.completed += u64::from(stats.downloaded); - metrics.leechers += u64::from(stats.incomplete); + metrics.complete += u64::from(stats.complete); + metrics.downloaded += u64::from(stats.downloaded); + metrics.incomplete += u64::from(stats.incomplete); metrics.torrents += 1; } @@ -84,7 +84,7 @@ where let entry = EntrySingle { peers: BTreeMap::default(), - completed: *completed, + downloaded: *completed, }; torrents.insert(*info_hash, entry); @@ -108,6 +108,6 @@ where async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { let mut db = self.get_torrents_mut().await; - db.retain(|_, e| e.is_not_zombie(policy)); + db.retain(|_, e| e.is_good(policy)); } } diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs index f800d2001..fbbc51a09 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs @@ -72,9 +72,9 @@ where for entry in self.get_torrents().await.values() { let stats = entry.get_stats(); - metrics.seeders += u64::from(stats.complete); - metrics.completed += u64::from(stats.downloaded); - metrics.leechers += u64::from(stats.incomplete); + metrics.complete += u64::from(stats.complete); + metrics.downloaded += u64::from(stats.downloaded); + metrics.incomplete += u64::from(stats.incomplete); metrics.torrents += 1; } @@ -93,7 +93,7 @@ where let entry = EntryMutexStd::new( EntrySingle { peers: BTreeMap::default(), - completed: *completed, + downloaded: *completed, } .into(), ); @@ -119,6 +119,6 @@ where async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { let mut db = self.get_torrents_mut().await; - db.retain(|_, e| e.lock().expect("it should lock entry").is_not_zombie(policy)); + db.retain(|_, e| e.lock().expect("it should lock entry").is_good(policy)); } } diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs index 7ce2cc74c..bc7fd61e8 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -70,11 +70,11 @@ where async fn get_metrics(&self) -> TorrentsMetrics { let mut metrics = TorrentsMetrics::default(); - for entry in self.get_torrents().await.values().cloned() { + for entry in self.get_torrents().await.values() { let stats = entry.get_stats().await; - metrics.seeders += u64::from(stats.complete); - metrics.completed += u64::from(stats.downloaded); - metrics.leechers += u64::from(stats.incomplete); + metrics.complete += u64::from(stats.complete); + metrics.downloaded += u64::from(stats.downloaded); + metrics.incomplete += u64::from(stats.incomplete); metrics.torrents += 1; } @@ -93,7 +93,7 @@ where let entry = EntryMutexTokio::new( EntrySingle { peers: BTreeMap::default(), - completed: *completed, + downloaded: *completed, } .into(), ); @@ -119,6 +119,16 @@ where async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { let mut db = self.get_torrents_mut().await; - db.retain(|_, e| e.blocking_lock().is_not_zombie(policy)); + let mut not_good = Vec::::default(); + + for (&infohash, torrent) in db.iter() { + if !torrent.clone().check_good(policy).await { + not_good.push(infohash); + } + } + + for remove in not_good { + drop(db.remove(&remove)); + } } } diff --git a/src/core/databases/mod.rs b/src/core/databases/mod.rs index 20a45cf83..c08aed76a 100644 --- a/src/core/databases/mod.rs +++ b/src/core/databases/mod.rs @@ -117,9 +117,9 @@ pub trait Database: Sync + Send { /// /// It returns an array of tuples with the torrent /// [`InfoHash`] and the - /// [`completed`](torrust_tracker_torrent_repository::entry::Torrent::completed) counter + /// [`downloaded`](torrust_tracker_torrent_repository::entry::Torrent::downloaded) counter /// which is the number of times the torrent has been downloaded. - /// See [`Entry::completed`](torrust_tracker_torrent_repository::entry::Torrent::completed). + /// See [`Entry::downloaded`](torrust_tracker_torrent_repository::entry::Torrent::downloaded). /// /// # Context: Torrent Metrics /// diff --git a/src/core/databases/mysql.rs b/src/core/databases/mysql.rs index e37cdd9bf..ca95fa0b9 100644 --- a/src/core/databases/mysql.rs +++ b/src/core/databases/mysql.rs @@ -9,7 +9,7 @@ use r2d2_mysql::mysql::prelude::Queryable; use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MySqlConnectionManager; use torrust_tracker_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::DatabaseDriver; +use torrust_tracker_primitives::{DatabaseDriver, PersistentTorrents}; use super::{Database, Error}; use crate::core::auth::{self, Key}; @@ -105,7 +105,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::load_persistent_torrents`](crate::core::databases::Database::load_persistent_torrents). - async fn load_persistent_torrents(&self) -> Result, Error> { + async fn load_persistent_torrents(&self) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let torrents = conn.query_map( @@ -116,7 +116,7 @@ impl Database for Mysql { }, )?; - Ok(torrents) + Ok(torrents.iter().copied().collect()) } /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). diff --git a/src/core/databases/sqlite.rs b/src/core/databases/sqlite.rs index 5a3ac144a..53a01f80c 100644 --- a/src/core/databases/sqlite.rs +++ b/src/core/databases/sqlite.rs @@ -6,7 +6,7 @@ use async_trait::async_trait; use r2d2::Pool; use r2d2_sqlite::SqliteConnectionManager; use torrust_tracker_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::{DatabaseDriver, DurationSinceUnixEpoch}; +use torrust_tracker_primitives::{DatabaseDriver, DurationSinceUnixEpoch, PersistentTorrents}; use super::{Database, Error}; use crate::core::auth::{self, Key}; @@ -89,7 +89,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::load_persistent_torrents`](crate::core::databases::Database::load_persistent_torrents). - async fn load_persistent_torrents(&self) -> Result, Error> { + async fn load_persistent_torrents(&self) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT info_hash, completed FROM torrents")?; @@ -101,12 +101,7 @@ impl Database for Sqlite { Ok((info_hash, completed)) })?; - //torrent_iter?; - //let torrent_iter = torrent_iter.unwrap(); - - let torrents: Vec<(InfoHash, u32)> = torrent_iter.filter_map(std::result::Result::ok).collect(); - - Ok(torrents) + Ok(torrent_iter.filter_map(std::result::Result::ok).collect()) } /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). diff --git a/src/core/mod.rs b/src/core/mod.rs index 21cd1b501..6628426c1 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -684,7 +684,7 @@ impl Tracker { fn get_torrent_peers_for_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> Vec> { match self.torrents.get(info_hash) { None => vec![], - Some(entry) => entry.get_peers_for_peer(peer, Some(TORRENT_PEERS_LIMIT)), + Some(entry) => entry.get_peers_for_client(&peer.peer_addr, Some(TORRENT_PEERS_LIMIT)), } } @@ -1115,9 +1115,9 @@ mod tests { assert_eq!( torrents_metrics, TorrentsMetrics { - seeders: 0, - completed: 0, - leechers: 0, + complete: 0, + downloaded: 0, + incomplete: 0, torrents: 0 } ); @@ -1164,9 +1164,9 @@ mod tests { assert_eq!( torrent_metrics, TorrentsMetrics { - seeders: 0, - completed: 0, - leechers: 1, + complete: 0, + downloaded: 0, + incomplete: 1, torrents: 1, } ); @@ -1191,9 +1191,9 @@ mod tests { assert_eq!( (torrent_metrics), (TorrentsMetrics { - seeders: 0, - completed: 0, - leechers: 1_000_000, + complete: 0, + downloaded: 0, + incomplete: 1_000_000, torrents: 1_000_000, }), "{result_a:?} {result_b:?}" diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index 2b3f9cbf7..ab78de683 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -29,6 +29,3 @@ use torrust_tracker_torrent_repository::TorrentsRwLockStdMutexStd; pub type Torrents = TorrentsRwLockStdMutexStd; // Currently Used - -#[cfg(test)] -mod tests {} diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index 48ac660cf..9e8ab6bab 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -50,9 +50,9 @@ impl From for Stats { fn from(metrics: TrackerMetrics) -> Self { Self { torrents: metrics.torrents_metrics.torrents, - seeders: metrics.torrents_metrics.seeders, - completed: metrics.torrents_metrics.completed, - leechers: metrics.torrents_metrics.leechers, + seeders: metrics.torrents_metrics.complete, + completed: metrics.torrents_metrics.downloaded, + leechers: metrics.torrents_metrics.incomplete, tcp4_connections_handled: metrics.protocol_metrics.tcp4_connections_handled, tcp4_announces_handled: metrics.protocol_metrics.tcp4_announces_handled, tcp4_scrapes_handled: metrics.protocol_metrics.tcp4_scrapes_handled, @@ -82,9 +82,9 @@ mod tests { assert_eq!( Stats::from(TrackerMetrics { torrents_metrics: TorrentsMetrics { - seeders: 1, - completed: 2, - leechers: 3, + complete: 1, + downloaded: 2, + incomplete: 3, torrents: 4 }, protocol_metrics: Metrics { diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 59aec0ff3..2d5038ec3 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -320,7 +320,6 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Configuration; - use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::{peer, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; @@ -368,39 +367,41 @@ mod tests { SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) } - struct TorrentPeerBuilder { + #[derive(Debug, Default)] + pub struct TorrentPeerBuilder { peer: peer::Peer, } impl TorrentPeerBuilder { - pub fn default() -> TorrentPeerBuilder { - let default_peer = peer::Peer { - peer_id: peer::Id([255u8; 20]), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: CurrentClock::now(), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), - event: AnnounceEvent::Started, - }; - TorrentPeerBuilder { peer: default_peer } + #[must_use] + pub fn new() -> Self { + Self { + peer: peer::Peer { + updated: CurrentClock::now(), + ..Default::default() + }, + } } - pub fn with_peer_id(mut self, peer_id: peer::Id) -> Self { - self.peer.peer_id = peer_id; + #[must_use] + pub fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { + self.peer.peer_addr = peer_addr; self } - pub fn with_peer_addr(mut self, peer_addr: SocketAddr) -> Self { - self.peer.peer_addr = peer_addr; + #[must_use] + pub fn with_peer_id(mut self, peer_id: peer::Id) -> Self { + self.peer.peer_id = peer_id; self } - pub fn with_bytes_left(mut self, left: i64) -> Self { + #[must_use] + pub fn with_number_of_bytes_left(mut self, left: i64) -> Self { self.peer.left = NumberOfBytes(left); self } + #[must_use] pub fn into(self) -> peer::Peer { self.peer } @@ -640,9 +641,9 @@ mod tests { let peers = tracker.get_torrent_peers(&info_hash.0.into()); - let expected_peer = TorrentPeerBuilder::default() + let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(SocketAddr::new(IpAddr::V4(client_ip), client_port)) + .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip), client_port)) .into(); assert_eq!(peers[0], Arc::new(expected_peer)); @@ -712,9 +713,9 @@ mod tests { let client_port = 8080; let peer_id = AquaticPeerId([255u8; 20]); - let peer_using_ipv6 = TorrentPeerBuilder::default() + let peer_using_ipv6 = TorrentPeerBuilder::new() .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) + .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); tracker @@ -808,9 +809,9 @@ mod tests { let external_ip_in_tracker_configuration = tracker.get_maybe_external_ip().unwrap(); - let expected_peer = TorrentPeerBuilder::default() + let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(SocketAddr::new(external_ip_in_tracker_configuration, client_port)) + .with_peer_address(SocketAddr::new(external_ip_in_tracker_configuration, client_port)) .into(); assert_eq!(peers[0], Arc::new(expected_peer)); @@ -863,9 +864,9 @@ mod tests { let peers = tracker.get_torrent_peers(&info_hash.0.into()); - let expected_peer = TorrentPeerBuilder::default() + let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) + .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); assert_eq!(peers[0], Arc::new(expected_peer)); @@ -938,9 +939,9 @@ mod tests { let client_port = 8080; let peer_id = AquaticPeerId([255u8; 20]); - let peer_using_ipv4 = TorrentPeerBuilder::default() + let peer_using_ipv4 = TorrentPeerBuilder::new() .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) + .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) .into(); tracker @@ -1112,10 +1113,10 @@ mod tests { async fn add_a_seeder(tracker: Arc, remote_addr: &SocketAddr, info_hash: &InfoHash) { let peer_id = peer::Id([255u8; 20]); - let peer = TorrentPeerBuilder::default() + let peer = TorrentPeerBuilder::new() .with_peer_id(peer::Id(peer_id.0)) - .with_peer_addr(*remote_addr) - .with_bytes_left(0) + .with_peer_address(*remote_addr) + .with_number_of_bytes_left(0) .into(); tracker From 3414e2abea16ff79a1150aa432c6563612735d79 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 25 Mar 2024 12:13:09 +0800 Subject: [PATCH 0273/1297] dev: torrent repository tests --- Cargo.lock | 419 ++++++++++++++- packages/torrent-repository/Cargo.toml | 1 + .../torrent-repository/tests/common/mod.rs | 3 + .../torrent-repository/tests/common/repo.rs | 147 +++++ .../tests/common/torrent.rs | 89 ++++ .../tests/common/torrent_peer_builder.rs | 88 +++ .../torrent-repository/tests/entry/mod.rs | 433 +++++++++++++++ .../torrent-repository/tests/integration.rs | 22 + .../tests/repository/mod.rs | 504 ++++++++++++++++++ 9 files changed, 1700 insertions(+), 6 deletions(-) create mode 100644 packages/torrent-repository/tests/common/mod.rs create mode 100644 packages/torrent-repository/tests/common/repo.rs create mode 100644 packages/torrent-repository/tests/common/torrent.rs create mode 100644 packages/torrent-repository/tests/common/torrent_peer_builder.rs create mode 100644 packages/torrent-repository/tests/entry/mod.rs create mode 100644 packages/torrent-repository/tests/integration.rs create mode 100644 packages/torrent-repository/tests/repository/mod.rs diff --git a/Cargo.lock b/Cargo.lock index e28278abb..0bdd83b9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -167,6 +167,40 @@ version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" +[[package]] +name = "async-attributes" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3203e79f4dd9bdda415ed03cf14dae5a2bf775c683a00f94e9cd1faf0f596e5" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "async-channel" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" +dependencies = [ + "concurrent-queue", + "event-listener 2.5.3", + "futures-core", +] + +[[package]] +name = "async-channel" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28243a43d821d11341ab73c80bed182dc015c514b951616cf79bd4af39af0c3" +dependencies = [ + "concurrent-queue", + "event-listener 5.2.0", + "event-listener-strategy 0.5.0", + "futures-core", + "pin-project-lite", +] + [[package]] name = "async-compression" version = "0.4.6" @@ -183,6 +217,128 @@ dependencies = [ "zstd-safe", ] +[[package]] +name = "async-executor" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17ae5ebefcc48e7452b4987947920dac9450be1110cadf34d1b8c116bdbaf97c" +dependencies = [ + "async-lock 3.3.0", + "async-task", + "concurrent-queue", + "fastrand 2.0.1", + "futures-lite 2.3.0", + "slab", +] + +[[package]] +name = "async-global-executor" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" +dependencies = [ + "async-channel 2.2.0", + "async-executor", + "async-io 2.3.2", + "async-lock 3.3.0", + "blocking", + "futures-lite 2.3.0", + "once_cell", + "tokio", +] + +[[package]] +name = "async-io" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af" +dependencies = [ + "async-lock 2.8.0", + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-lite 1.13.0", + "log", + "parking", + "polling 2.8.0", + "rustix 0.37.27", + "slab", + "socket2 0.4.10", + "waker-fn", +] + +[[package]] +name = "async-io" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcccb0f599cfa2f8ace422d3555572f47424da5648a4382a9dd0310ff8210884" +dependencies = [ + "async-lock 3.3.0", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite 2.3.0", + "parking", + "polling 3.6.0", + "rustix 0.38.32", + "slab", + "tracing", + "windows-sys 0.52.0", +] + +[[package]] +name = "async-lock" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b" +dependencies = [ + "event-listener 2.5.3", +] + +[[package]] +name = "async-lock" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d034b430882f8381900d3fe6f0aaa3ad94f2cb4ac519b429692a1bc2dda4ae7b" +dependencies = [ + "event-listener 4.0.3", + "event-listener-strategy 0.4.0", + "pin-project-lite", +] + +[[package]] +name = "async-std" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62565bb4402e926b29953c785397c6dc0391b7b446e45008b0049eb43cec6f5d" +dependencies = [ + "async-attributes", + "async-channel 1.9.0", + "async-global-executor", + "async-io 1.13.0", + "async-lock 2.8.0", + "crossbeam-utils", + "futures-channel", + "futures-core", + "futures-io", + "futures-lite 1.13.0", + "gloo-timers", + "kv-log-macro", + "log", + "memchr", + "once_cell", + "pin-project-lite", + "pin-utils", + "slab", + "wasm-bindgen-futures", +] + +[[package]] +name = "async-task" +version = "4.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbb36e985947064623dbd357f727af08ffd077f93d696782f3c56365fa2e2799" + [[package]] name = "async-trait" version = "0.1.78" @@ -194,6 +350,12 @@ dependencies = [ "syn 2.0.53", ] +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "autocfg" version = "1.1.0" @@ -418,6 +580,22 @@ dependencies = [ "generic-array", ] +[[package]] +name = "blocking" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a37913e8dc4ddcc604f0c6d3bf2887c995153af3611de9e23c352b44c1b9118" +dependencies = [ + "async-channel 2.2.0", + "async-lock 3.3.0", + "async-task", + "fastrand 2.0.1", + "futures-io", + "futures-lite 2.3.0", + "piper", + "tracing", +] + [[package]] name = "borsh" version = "1.3.1" @@ -662,6 +840,15 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "concurrent-queue" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d16048cd947b08fa32c24458a22f5dc5e835264f689f4f5653210c69fd107363" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "config" version = "0.14.0" @@ -996,6 +1183,54 @@ dependencies = [ "version_check", ] +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + +[[package]] +name = "event-listener" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b215c49b2b248c855fb73579eb1f4f26c38ffdc12973e20e07b91d78d5646e" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b5fb89194fa3cad959b833185b3063ba881dbfc7030680b314250779fb4cc91" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "958e4d70b6d5e81971bebec42271ec641e7ff4e170a6fa605f2b8a8b65cb97d3" +dependencies = [ + "event-listener 4.0.3", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "feedafcaa9b749175d5ac357452a9d41ea2911da598fde46ce1fe02c37751291" +dependencies = [ + "event-listener 5.2.0", + "pin-project-lite", +] + [[package]] name = "fallible-iterator" version = "0.3.0" @@ -1008,6 +1243,15 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" +[[package]] +name = "fastrand" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" +dependencies = [ + "instant", +] + [[package]] name = "fastrand" version = "2.0.1" @@ -1186,6 +1430,34 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" +[[package]] +name = "futures-lite" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce" +dependencies = [ + "fastrand 1.9.0", + "futures-core", + "futures-io", + "memchr", + "parking", + "pin-project-lite", + "waker-fn", +] + +[[package]] +name = "futures-lite" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" +dependencies = [ + "fastrand 2.0.1", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-macro" version = "0.3.30" @@ -1266,6 +1538,18 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" +[[package]] +name = "gloo-timers" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b995a66bb87bebce9a0f4a95aed01daca4872c050bfcb21653361c03bc35e5c" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + [[package]] name = "h2" version = "0.4.3" @@ -1458,7 +1742,7 @@ dependencies = [ "http-body", "hyper", "pin-project-lite", - "socket2", + "socket2 0.5.6", "tokio", "tower", "tower-service", @@ -1526,6 +1810,15 @@ dependencies = [ "serde", ] +[[package]] +name = "instant" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" +dependencies = [ + "cfg-if", +] + [[package]] name = "io-enum" version = "1.1.3" @@ -1535,6 +1828,17 @@ dependencies = [ "derive_utils", ] +[[package]] +name = "io-lifetimes" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" +dependencies = [ + "hermit-abi", + "libc", + "windows-sys 0.48.0", +] + [[package]] name = "ipnet" version = "2.9.0" @@ -1605,6 +1909,15 @@ dependencies = [ "serde", ] +[[package]] +name = "kv-log-macro" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f" +dependencies = [ + "log", +] + [[package]] name = "lazy_static" version = "1.4.0" @@ -1734,6 +2047,12 @@ version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" +[[package]] +name = "linux-raw-sys" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" + [[package]] name = "linux-raw-sys" version = "0.4.13" @@ -1767,6 +2086,9 @@ name = "log" version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" +dependencies = [ + "value-bag", +] [[package]] name = "lru" @@ -1878,7 +2200,7 @@ dependencies = [ "percent-encoding", "serde", "serde_json", - "socket2", + "socket2 0.5.6", "twox-hash", "url", ] @@ -2127,6 +2449,12 @@ dependencies = [ "hashbrown 0.13.2", ] +[[package]] +name = "parking" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb813b8af86854136c6922af0598d719255ecb2179515e6e7730d468f05c9cae" + [[package]] name = "parking_lot" version = "0.12.1" @@ -2287,6 +2615,17 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "piper" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "668d31b1c4eba19242f2088b2bf3316b82ca31082a8335764db4e083db7485d4" +dependencies = [ + "atomic-waker", + "fastrand 2.0.1", + "futures-io", +] + [[package]] name = "pkg-config" version = "0.3.30" @@ -2321,6 +2660,37 @@ dependencies = [ "plotters-backend", ] +[[package]] +name = "polling" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b2d323e8ca7996b3e23126511a523f7e62924d93ecd5ae73b333815b0eb3dce" +dependencies = [ + "autocfg", + "bitflags 1.3.2", + "cfg-if", + "concurrent-queue", + "libc", + "log", + "pin-project-lite", + "windows-sys 0.48.0", +] + +[[package]] +name = "polling" +version = "3.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0c976a60b2d7e99d6f229e414670a9b85d13ac305cc6d1e9c134de58c5aaaf6" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 0.38.32", + "tracing", + "windows-sys 0.52.0", +] + [[package]] name = "powerfmt" version = "0.2.0" @@ -2778,6 +3148,20 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "0.37.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fea8ca367a3a01fe35e6943c400addf443c0f57670e6ec51196f71a4b8762dd2" +dependencies = [ + "bitflags 1.3.2", + "errno", + "io-lifetimes", + "libc", + "linux-raw-sys 0.3.8", + "windows-sys 0.48.0", +] + [[package]] name = "rustix" version = "0.38.32" @@ -2787,7 +3171,7 @@ dependencies = [ "bitflags 2.5.0", "errno", "libc", - "linux-raw-sys", + "linux-raw-sys 0.4.13", "windows-sys 0.52.0", ] @@ -3133,6 +3517,16 @@ version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" +[[package]] +name = "socket2" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "socket2" version = "0.5.6" @@ -3268,8 +3662,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", - "fastrand", - "rustix", + "fastrand 2.0.1", + "rustix 0.38.32", "windows-sys 0.52.0", ] @@ -3386,7 +3780,7 @@ dependencies = [ "num_cpus", "pin-project-lite", "signal-hook-registry", - "socket2", + "socket2 0.5.6", "tokio-macros", "windows-sys 0.48.0", ] @@ -3610,6 +4004,7 @@ dependencies = [ name = "torrust-tracker-torrent-repository" version = "3.0.0-alpha.12-develop" dependencies = [ + "async-std", "criterion", "futures", "rstest", @@ -3801,6 +4196,12 @@ dependencies = [ "rand", ] +[[package]] +name = "value-bag" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74797339c3b98616c009c7c3eb53a0ce41e85c8ec66bd3db96ed132d20cfdee8" + [[package]] name = "vcpkg" version = "0.2.15" @@ -3813,6 +4214,12 @@ version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +[[package]] +name = "waker-fn" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c4517f54858c779bbcbf228f4fca63d121bf85fbecb2dc578cdf4a39395690" + [[package]] name = "walkdir" version = "2.5.0" diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index c36ae1440..4cea8767f 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -25,6 +25,7 @@ torrust-tracker-clock = { version = "3.0.0-alpha.12-develop", path = "../clock" [dev-dependencies] criterion = { version = "0", features = ["async_tokio"] } rstest = "0" +async-std = {version = "1", features = ["attributes", "tokio1"] } [[bench]] harness = false diff --git a/packages/torrent-repository/tests/common/mod.rs b/packages/torrent-repository/tests/common/mod.rs new file mode 100644 index 000000000..efdf7f742 --- /dev/null +++ b/packages/torrent-repository/tests/common/mod.rs @@ -0,0 +1,3 @@ +pub mod repo; +pub mod torrent; +pub mod torrent_peer_builder; diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs new file mode 100644 index 000000000..3a4b53d2f --- /dev/null +++ b/packages/torrent-repository/tests/common/repo.rs @@ -0,0 +1,147 @@ +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_torrent_repository::repository::{Repository as _, RepositoryAsync as _}; +use torrust_tracker_torrent_repository::{ + EntrySingle, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, + TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, +}; + +#[derive(Debug)] +pub(crate) enum Repo { + Std(TorrentsRwLockStd), + StdMutexStd(TorrentsRwLockStdMutexStd), + StdMutexTokio(TorrentsRwLockStdMutexTokio), + Tokio(TorrentsRwLockTokio), + TokioMutexStd(TorrentsRwLockTokioMutexStd), + TokioMutexTokio(TorrentsRwLockTokioMutexTokio), +} + +impl Repo { + pub(crate) async fn get(&self, key: &InfoHash) -> Option { + match self { + Repo::Std(repo) => repo.get(key), + Repo::StdMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), + Repo::StdMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), + Repo::Tokio(repo) => repo.get(key).await, + Repo::TokioMutexStd(repo) => Some(repo.get(key).await?.lock().unwrap().clone()), + Repo::TokioMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), + } + } + pub(crate) async fn get_metrics(&self) -> TorrentsMetrics { + match self { + Repo::Std(repo) => repo.get_metrics(), + Repo::StdMutexStd(repo) => repo.get_metrics(), + Repo::StdMutexTokio(repo) => repo.get_metrics().await, + Repo::Tokio(repo) => repo.get_metrics().await, + Repo::TokioMutexStd(repo) => repo.get_metrics().await, + Repo::TokioMutexTokio(repo) => repo.get_metrics().await, + } + } + pub(crate) async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { + match self { + Repo::Std(repo) => repo.get_paginated(pagination), + Repo::StdMutexStd(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) + .collect(), + Repo::StdMutexTokio(repo) => { + let mut v: Vec<(InfoHash, EntrySingle)> = vec![]; + + for (i, t) in repo.get_paginated(pagination).await { + v.push((i, t.lock().await.clone())); + } + v + } + Repo::Tokio(repo) => repo.get_paginated(pagination).await, + Repo::TokioMutexStd(repo) => repo + .get_paginated(pagination) + .await + .iter() + .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) + .collect(), + Repo::TokioMutexTokio(repo) => { + let mut v: Vec<(InfoHash, EntrySingle)> = vec![]; + + for (i, t) in repo.get_paginated(pagination).await { + v.push((i, t.lock().await.clone())); + } + v + } + } + } + pub(crate) async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + match self { + Repo::Std(repo) => repo.import_persistent(persistent_torrents), + Repo::StdMutexStd(repo) => repo.import_persistent(persistent_torrents), + Repo::StdMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, + Repo::Tokio(repo) => repo.import_persistent(persistent_torrents).await, + Repo::TokioMutexStd(repo) => repo.import_persistent(persistent_torrents).await, + Repo::TokioMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, + } + } + pub(crate) async fn remove(&self, key: &InfoHash) -> Option { + match self { + Repo::Std(repo) => repo.remove(key), + Repo::StdMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), + Repo::StdMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), + Repo::Tokio(repo) => repo.remove(key).await, + Repo::TokioMutexStd(repo) => Some(repo.remove(key).await?.lock().unwrap().clone()), + Repo::TokioMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), + } + } + pub(crate) async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + match self { + Repo::Std(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::StdMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::StdMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::Tokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::TokioMutexStd(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::TokioMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + } + } + pub(crate) async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + match self { + Repo::Std(repo) => repo.remove_peerless_torrents(policy), + Repo::StdMutexStd(repo) => repo.remove_peerless_torrents(policy), + Repo::StdMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, + Repo::Tokio(repo) => repo.remove_peerless_torrents(policy).await, + Repo::TokioMutexStd(repo) => repo.remove_peerless_torrents(policy).await, + Repo::TokioMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, + } + } + pub(crate) async fn update_torrent_with_peer_and_get_stats( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + ) -> (bool, SwarmMetadata) { + match self { + Repo::Std(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), + Repo::StdMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), + Repo::StdMutexTokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, + Repo::Tokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, + Repo::TokioMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, + Repo::TokioMutexTokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, + } + } + pub(crate) async fn insert(&self, info_hash: &InfoHash, torrent: EntrySingle) -> Option { + match self { + Repo::Std(repo) => repo.write().insert(*info_hash, torrent), + Repo::StdMutexStd(repo) => Some(repo.write().insert(*info_hash, torrent.into())?.lock().unwrap().clone()), + Repo::StdMutexTokio(repo) => { + let r = repo.write().insert(*info_hash, torrent.into()); + match r { + Some(t) => Some(t.lock().await.clone()), + None => None, + } + } + Repo::Tokio(repo) => repo.write().await.insert(*info_hash, torrent), + Repo::TokioMutexStd(repo) => Some(repo.write().await.insert(*info_hash, torrent.into())?.lock().unwrap().clone()), + Repo::TokioMutexTokio(repo) => Some(repo.write().await.insert(*info_hash, torrent.into())?.lock().await.clone()), + } + } +} diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs new file mode 100644 index 000000000..33264c443 --- /dev/null +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -0,0 +1,89 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; +use torrust_tracker_torrent_repository::entry::{Entry as _, EntryAsync as _, EntrySync as _}; +use torrust_tracker_torrent_repository::{EntryMutexStd, EntryMutexTokio, EntrySingle}; + +#[derive(Debug, Clone)] +pub(crate) enum Torrent { + Single(EntrySingle), + MutexStd(EntryMutexStd), + MutexTokio(EntryMutexTokio), +} + +impl Torrent { + pub(crate) async fn get_stats(&self) -> SwarmMetadata { + match self { + Torrent::Single(entry) => entry.get_stats(), + Torrent::MutexStd(entry) => entry.get_stats(), + Torrent::MutexTokio(entry) => entry.clone().get_stats().await, + } + } + + pub(crate) async fn is_good(&self, policy: &TrackerPolicy) -> bool { + match self { + Torrent::Single(entry) => entry.is_good(policy), + Torrent::MutexStd(entry) => entry.is_good(policy), + Torrent::MutexTokio(entry) => entry.clone().check_good(policy).await, + } + } + + pub(crate) async fn peers_is_empty(&self) -> bool { + match self { + Torrent::Single(entry) => entry.peers_is_empty(), + Torrent::MutexStd(entry) => entry.peers_is_empty(), + Torrent::MutexTokio(entry) => entry.clone().peers_is_empty().await, + } + } + + pub(crate) async fn get_peers_len(&self) -> usize { + match self { + Torrent::Single(entry) => entry.get_peers_len(), + Torrent::MutexStd(entry) => entry.get_peers_len(), + Torrent::MutexTokio(entry) => entry.clone().get_peers_len().await, + } + } + + pub(crate) async fn get_peers(&self, limit: Option) -> Vec> { + match self { + Torrent::Single(entry) => entry.get_peers(limit), + Torrent::MutexStd(entry) => entry.get_peers(limit), + Torrent::MutexTokio(entry) => entry.clone().get_peers(limit).await, + } + } + + pub(crate) async fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + match self { + Torrent::Single(entry) => entry.get_peers_for_client(client, limit), + Torrent::MutexStd(entry) => entry.get_peers_for_client(client, limit), + Torrent::MutexTokio(entry) => entry.clone().get_peers_for_client(client, limit).await, + } + } + + pub(crate) async fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool { + match self { + Torrent::Single(entry) => entry.insert_or_update_peer(peer), + Torrent::MutexStd(entry) => entry.insert_or_update_peer(peer), + Torrent::MutexTokio(entry) => entry.clone().insert_or_update_peer(peer).await, + } + } + + pub(crate) async fn insert_or_update_peer_and_get_stats(&mut self, peer: &peer::Peer) -> (bool, SwarmMetadata) { + match self { + Torrent::Single(entry) => entry.insert_or_update_peer_and_get_stats(peer), + Torrent::MutexStd(entry) => entry.insert_or_update_peer_and_get_stats(peer), + Torrent::MutexTokio(entry) => entry.clone().insert_or_update_peer_and_get_stats(peer).await, + } + } + + pub(crate) async fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + match self { + Torrent::Single(entry) => entry.remove_inactive_peers(current_cutoff), + Torrent::MutexStd(entry) => entry.remove_inactive_peers(current_cutoff), + Torrent::MutexTokio(entry) => entry.clone().remove_inactive_peers(current_cutoff).await, + } + } +} diff --git a/packages/torrent-repository/tests/common/torrent_peer_builder.rs b/packages/torrent-repository/tests/common/torrent_peer_builder.rs new file mode 100644 index 000000000..3a4e61ed2 --- /dev/null +++ b/packages/torrent-repository/tests/common/torrent_peer_builder.rs @@ -0,0 +1,88 @@ +use std::net::SocketAddr; + +use torrust_tracker_clock::clock::Time; +use torrust_tracker_primitives::announce_event::AnnounceEvent; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; + +use crate::CurrentClock; + +#[derive(Debug, Default)] +struct TorrentPeerBuilder { + peer: peer::Peer, +} + +#[allow(dead_code)] +impl TorrentPeerBuilder { + #[must_use] + fn new() -> Self { + Self { + peer: peer::Peer { + updated: CurrentClock::now(), + ..Default::default() + }, + } + } + + #[must_use] + fn with_event_completed(mut self) -> Self { + self.peer.event = AnnounceEvent::Completed; + self + } + + #[must_use] + fn with_event_started(mut self) -> Self { + self.peer.event = AnnounceEvent::Started; + self + } + + #[must_use] + fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { + self.peer.peer_addr = peer_addr; + self + } + + #[must_use] + fn with_peer_id(mut self, peer_id: peer::Id) -> Self { + self.peer.peer_id = peer_id; + self + } + + #[must_use] + fn with_number_of_bytes_left(mut self, left: i64) -> Self { + self.peer.left = NumberOfBytes(left); + self + } + + #[must_use] + fn updated_at(mut self, updated: DurationSinceUnixEpoch) -> Self { + self.peer.updated = updated; + self + } + + #[must_use] + fn into(self) -> peer::Peer { + self.peer + } +} + +/// A torrent seeder is a peer with 0 bytes left to download which +/// has not announced it has stopped +#[must_use] +pub fn a_completed_peer(id: i32) -> peer::Peer { + TorrentPeerBuilder::new() + .with_number_of_bytes_left(0) + .with_event_completed() + .with_peer_id(id.into()) + .into() +} + +/// A torrent leecher is a peer that is not a seeder. +/// Leecher: left > 0 OR event = Stopped +#[must_use] +pub fn a_started_peer(id: i32) -> peer::Peer { + TorrentPeerBuilder::new() + .with_number_of_bytes_left(1) + .with_event_started() + .with_peer_id(id.into()) + .into() +} diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs new file mode 100644 index 000000000..c39bef636 --- /dev/null +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -0,0 +1,433 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::ops::Sub; +use std::time::Duration; + +use rstest::{fixture, rstest}; +use torrust_tracker_clock::clock::stopped::Stopped as _; +use torrust_tracker_clock::clock::{self, Time as _}; +use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; +use torrust_tracker_primitives::announce_event::AnnounceEvent; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::{peer, NumberOfBytes}; +use torrust_tracker_torrent_repository::{EntryMutexStd, EntryMutexTokio, EntrySingle}; + +use crate::common::torrent::Torrent; +use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; +use crate::CurrentClock; + +#[fixture] +fn single() -> Torrent { + Torrent::Single(EntrySingle::default()) +} +#[fixture] +fn standard_mutex() -> Torrent { + Torrent::MutexStd(EntryMutexStd::default()) +} + +#[fixture] +fn mutex_tokio() -> Torrent { + Torrent::MutexTokio(EntryMutexTokio::default()) +} + +#[fixture] +fn policy_none() -> TrackerPolicy { + TrackerPolicy::new(false, 0, false) +} + +#[fixture] +fn policy_persist() -> TrackerPolicy { + TrackerPolicy::new(false, 0, true) +} + +#[fixture] +fn policy_remove() -> TrackerPolicy { + TrackerPolicy::new(true, 0, false) +} + +#[fixture] +fn policy_remove_persist() -> TrackerPolicy { + TrackerPolicy::new(true, 0, true) +} + +pub enum Makes { + Empty, + Started, + Completed, + Downloaded, + Three, +} + +async fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { + match makes { + Makes::Empty => vec![], + Makes::Started => { + let peer = a_started_peer(1); + torrent.insert_or_update_peer(&peer).await; + vec![peer] + } + Makes::Completed => { + let peer = a_completed_peer(2); + torrent.insert_or_update_peer(&peer).await; + vec![peer] + } + Makes::Downloaded => { + let mut peer = a_started_peer(3); + torrent.insert_or_update_peer(&peer).await; + peer.event = AnnounceEvent::Completed; + peer.left = NumberOfBytes(0); + torrent.insert_or_update_peer(&peer).await; + vec![peer] + } + Makes::Three => { + let peer_1 = a_started_peer(1); + torrent.insert_or_update_peer(&peer_1).await; + + let peer_2 = a_completed_peer(2); + torrent.insert_or_update_peer(&peer_2).await; + + let mut peer_3 = a_started_peer(3); + torrent.insert_or_update_peer(&peer_3).await; + peer_3.event = AnnounceEvent::Completed; + peer_3.left = NumberOfBytes(0); + torrent.insert_or_update_peer(&peer_3).await; + vec![peer_1, peer_2, peer_3] + } + } +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[tokio::test] +async fn it_should_be_empty_by_default( + #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + + assert_eq!(torrent.get_peers_len().await, 0); +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_check_if_entry_is_good( + #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[case] makes: &Makes, + #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, +) { + make(&mut torrent, makes).await; + + let has_peers = !torrent.peers_is_empty().await; + let has_downloads = torrent.get_stats().await.downloaded != 0; + + match (policy.remove_peerless_torrents, policy.persistent_torrent_completed_stat) { + // remove torrents without peers, and keep completed download stats + (true, true) => match (has_peers, has_downloads) { + // no peers, but has downloads + // peers, with or without downloads + (false, true) | (true, true | false) => assert!(torrent.is_good(&policy).await), + // no peers and no downloads + (false, false) => assert!(!torrent.is_good(&policy).await), + }, + // remove torrents without peers and drop completed download stats + (true, false) => match (has_peers, has_downloads) { + // peers, with or without downloads + (true, true | false) => assert!(torrent.is_good(&policy).await), + // no peers and with or without downloads + (false, true | false) => assert!(!torrent.is_good(&policy).await), + }, + // keep torrents without peers, but keep or drop completed download stats + (false, true | false) => assert!(torrent.is_good(&policy).await), + } +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_get_peers_for_torrent_entry( + #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + let peers = make(&mut torrent, makes).await; + + let torrent_peers = torrent.get_peers(None).await; + + assert_eq!(torrent_peers.len(), peers.len()); + + for peer in torrent_peers { + assert!(peers.contains(&peer)); + } +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_update_a_peer( + #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + + // Make and insert a new peer. + let mut peer = a_started_peer(-1); + torrent.insert_or_update_peer(&peer).await; + + // Get the Inserted Peer by Id. + let peers = torrent.get_peers(None).await; + let original = peers + .iter() + .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) + .expect("it should find peer by id"); + + assert_eq!(original.event, AnnounceEvent::Started, "it should be as created"); + + // Announce "Completed" torrent download event. + peer.event = AnnounceEvent::Completed; + torrent.insert_or_update_peer(&peer).await; + + // Get the Updated Peer by Id. + let peers = torrent.get_peers(None).await; + let updated = peers + .iter() + .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) + .expect("it should find peer by id"); + + assert_eq!(updated.event, AnnounceEvent::Completed, "it should be updated"); +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_remove_a_peer_upon_stopped_announcement( + #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + use torrust_tracker_primitives::peer::ReadInfo as _; + + make(&mut torrent, makes).await; + + let mut peer = a_started_peer(-1); + + torrent.insert_or_update_peer(&peer).await; + + // The started peer should be inserted. + let peers = torrent.get_peers(None).await; + let original = peers + .iter() + .find(|p| p.get_id() == peer.get_id()) + .expect("it should find peer by id"); + + assert_eq!(original.event, AnnounceEvent::Started); + + // Change peer to "Stopped" and insert. + peer.event = AnnounceEvent::Stopped; + torrent.insert_or_update_peer(&peer).await; + + // It should be removed now. + let peers = torrent.get_peers(None).await; + + assert_eq!( + peers.iter().find(|p| p.get_id() == peer.get_id()), + None, + "it should be removed" + ); +} + +#[rstest] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloaded_statistic( + #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + let downloaded = torrent.get_stats().await.downloaded; + + let peers = torrent.get_peers(None).await; + let mut peer = **peers.first().expect("there should be a peer"); + + let is_already_completed = peer.event == AnnounceEvent::Completed; + + // Announce "Completed" torrent download event. + peer.event = AnnounceEvent::Completed; + + let (updated, stats) = torrent.insert_or_update_peer_and_get_stats(&peer).await; + + if is_already_completed { + assert!(!updated); + assert_eq!(stats.downloaded, downloaded); + } else { + assert!(updated); + assert_eq!(stats.downloaded, downloaded + 1); + } +} + +#[rstest] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_update_a_peer_as_a_seeder( + #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + let peers = make(&mut torrent, makes).await; + let completed = u32::try_from(peers.iter().filter(|p| p.is_seeder()).count()).expect("it_should_not_be_so_many"); + + let peers = torrent.get_peers(None).await; + let mut peer = **peers.first().expect("there should be a peer"); + + let is_already_non_left = peer.left == NumberOfBytes(0); + + // Set Bytes Left to Zero + peer.left = NumberOfBytes(0); + let (_, stats) = torrent.insert_or_update_peer_and_get_stats(&peer).await; // Add the peer + + if is_already_non_left { + // it was already complete + assert_eq!(stats.complete, completed); + } else { + // now it is complete + assert_eq!(stats.complete, completed + 1); + } +} + +#[rstest] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_update_a_peer_as_incomplete( + #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + let peers = make(&mut torrent, makes).await; + let incomplete = u32::try_from(peers.iter().filter(|p| !p.is_seeder()).count()).expect("it should not be so many"); + + let peers = torrent.get_peers(None).await; + let mut peer = **peers.first().expect("there should be a peer"); + + let completed_already = peer.left == NumberOfBytes(0); + + // Set Bytes Left to no Zero + peer.left = NumberOfBytes(1); + let (_, stats) = torrent.insert_or_update_peer_and_get_stats(&peer).await; // Add the peer + + if completed_already { + // now it is incomplete + assert_eq!(stats.incomplete, incomplete + 1); + } else { + // was already incomplete + assert_eq!(stats.incomplete, incomplete); + } +} + +#[rstest] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_get_peers_excluding_the_client_socket( + #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + + let peers = torrent.get_peers(None).await; + let mut peer = **peers.first().expect("there should be a peer"); + + let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8081); + + // for this test, we should not already use this socket. + assert_ne!(peer.peer_addr, socket); + + // it should get the peer as it dose not share the socket. + assert!(torrent.get_peers_for_client(&socket, None).await.contains(&peer.into())); + + // set the address to the socket. + peer.peer_addr = socket; + torrent.insert_or_update_peer(&peer).await; // Add peer + + // It should not include the peer that has the same socket. + assert!(!torrent.get_peers_for_client(&socket, None).await.contains(&peer.into())); +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_limit_the_number_of_peers_returned( + #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + + // We add one more peer than the scrape limit + for peer_number in 1..=74 + 1 { + let mut peer = a_started_peer(1); + peer.peer_id = peer::Id::from(peer_number); + torrent.insert_or_update_peer(&peer).await; + } + + let peers = torrent.get_peers(Some(TORRENT_PEERS_LIMIT)).await; + + assert_eq!(peers.len(), 74); +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_remove_inactive_peers_beyond_cutoff( + #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + const TIMEOUT: Duration = Duration::from_secs(120); + const EXPIRE: Duration = Duration::from_secs(121); + + let peers = make(&mut torrent, makes).await; + + let mut peer = a_completed_peer(-1); + + let now = clock::Working::now(); + clock::Stopped::local_set(&now); + + peer.updated = now.sub(EXPIRE); + + torrent.insert_or_update_peer(&peer).await; + + assert_eq!(torrent.get_peers_len().await, peers.len() + 1); + + let current_cutoff = CurrentClock::now_sub(&TIMEOUT).unwrap_or_default(); + torrent.remove_inactive_peers(current_cutoff).await; + + assert_eq!(torrent.get_peers_len().await, peers.len()); +} diff --git a/packages/torrent-repository/tests/integration.rs b/packages/torrent-repository/tests/integration.rs new file mode 100644 index 000000000..5aab67b03 --- /dev/null +++ b/packages/torrent-repository/tests/integration.rs @@ -0,0 +1,22 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` + +use torrust_tracker_clock::clock; + +pub mod common; +mod entry; +mod repository; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs new file mode 100644 index 000000000..7ffe17dd7 --- /dev/null +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -0,0 +1,504 @@ +use std::collections::{BTreeMap, HashSet}; +use std::hash::{DefaultHasher, Hash, Hasher}; + +use rstest::{fixture, rstest}; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::announce_event::AnnounceEvent; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::{NumberOfBytes, PersistentTorrents}; +use torrust_tracker_torrent_repository::entry::Entry as _; +use torrust_tracker_torrent_repository::repository::{RwLockStd, RwLockTokio}; +use torrust_tracker_torrent_repository::EntrySingle; + +use crate::common::repo::Repo; +use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; + +#[fixture] +fn standard() -> Repo { + Repo::Std(RwLockStd::default()) +} +#[fixture] +fn standard_mutex() -> Repo { + Repo::StdMutexStd(RwLockStd::default()) +} + +#[fixture] +fn standard_tokio() -> Repo { + Repo::StdMutexTokio(RwLockStd::default()) +} + +#[fixture] +fn tokio_std() -> Repo { + Repo::Tokio(RwLockTokio::default()) +} +#[fixture] +fn tokio_mutex() -> Repo { + Repo::TokioMutexStd(RwLockTokio::default()) +} + +#[fixture] +fn tokio_tokio() -> Repo { + Repo::TokioMutexTokio(RwLockTokio::default()) +} + +type Entries = Vec<(InfoHash, EntrySingle)>; + +#[fixture] +fn empty() -> Entries { + vec![] +} + +#[fixture] +fn default() -> Entries { + vec![(InfoHash::default(), EntrySingle::default())] +} + +#[fixture] +fn started() -> Entries { + let mut torrent = EntrySingle::default(); + torrent.insert_or_update_peer(&a_started_peer(1)); + vec![(InfoHash::default(), torrent)] +} + +#[fixture] +fn completed() -> Entries { + let mut torrent = EntrySingle::default(); + torrent.insert_or_update_peer(&a_completed_peer(2)); + vec![(InfoHash::default(), torrent)] +} + +#[fixture] +fn downloaded() -> Entries { + let mut torrent = EntrySingle::default(); + let mut peer = a_started_peer(3); + torrent.insert_or_update_peer(&peer); + peer.event = AnnounceEvent::Completed; + peer.left = NumberOfBytes(0); + torrent.insert_or_update_peer(&peer); + vec![(InfoHash::default(), torrent)] +} + +#[fixture] +fn three() -> Entries { + let mut started = EntrySingle::default(); + let started_h = &mut DefaultHasher::default(); + started.insert_or_update_peer(&a_started_peer(1)); + started.hash(started_h); + + let mut completed = EntrySingle::default(); + let completed_h = &mut DefaultHasher::default(); + completed.insert_or_update_peer(&a_completed_peer(2)); + completed.hash(completed_h); + + let mut downloaded = EntrySingle::default(); + let downloaded_h = &mut DefaultHasher::default(); + let mut downloaded_peer = a_started_peer(3); + downloaded.insert_or_update_peer(&downloaded_peer); + downloaded_peer.event = AnnounceEvent::Completed; + downloaded_peer.left = NumberOfBytes(0); + downloaded.insert_or_update_peer(&downloaded_peer); + downloaded.hash(downloaded_h); + + vec![ + (InfoHash::from(&started_h.clone()), started), + (InfoHash::from(&completed_h.clone()), completed), + (InfoHash::from(&downloaded_h.clone()), downloaded), + ] +} + +#[fixture] +fn many_out_of_order() -> Entries { + let mut entries: HashSet<(InfoHash, EntrySingle)> = HashSet::default(); + + for i in 0..408 { + let mut entry = EntrySingle::default(); + entry.insert_or_update_peer(&a_started_peer(i)); + + entries.insert((InfoHash::from(&i), entry)); + } + + // we keep the random order from the hashed set for the vector. + entries.iter().map(|(i, e)| (*i, e.clone())).collect() +} + +#[fixture] +fn many_hashed_in_order() -> Entries { + let mut entries: BTreeMap = BTreeMap::default(); + + for i in 0..408 { + let mut entry = EntrySingle::default(); + entry.insert_or_update_peer(&a_started_peer(i)); + + let hash: &mut DefaultHasher = &mut DefaultHasher::default(); + hash.write_i32(i); + + entries.insert(InfoHash::from(&hash.clone()), entry); + } + + // We return the entries in-order from from the b-tree map. + entries.iter().map(|(i, e)| (*i, e.clone())).collect() +} + +#[fixture] +fn persistent_empty() -> PersistentTorrents { + PersistentTorrents::default() +} + +#[fixture] +fn persistent_single() -> PersistentTorrents { + let hash = &mut DefaultHasher::default(); + + hash.write_u8(1); + let t = [(InfoHash::from(&hash.clone()), 0_u32)]; + + t.iter().copied().collect() +} + +#[fixture] +fn persistent_three() -> PersistentTorrents { + let hash = &mut DefaultHasher::default(); + + hash.write_u8(1); + let info_1 = InfoHash::from(&hash.clone()); + hash.write_u8(2); + let info_2 = InfoHash::from(&hash.clone()); + hash.write_u8(3); + let info_3 = InfoHash::from(&hash.clone()); + + let t = [(info_1, 1_u32), (info_2, 2_u32), (info_3, 3_u32)]; + + t.iter().copied().collect() +} + +async fn make(repo: &Repo, entries: &Entries) { + for (info_hash, entry) in entries { + repo.insert(info_hash, entry.clone()).await; + } +} + +#[fixture] +fn paginated_limit_zero() -> Pagination { + Pagination::new(0, 0) +} + +#[fixture] +fn paginated_limit_one() -> Pagination { + Pagination::new(0, 1) +} + +#[fixture] +fn paginated_limit_one_offset_one() -> Pagination { + Pagination::new(1, 1) +} + +#[fixture] +fn policy_none() -> TrackerPolicy { + TrackerPolicy::new(false, 0, false) +} + +#[fixture] +fn policy_persist() -> TrackerPolicy { + TrackerPolicy::new(false, 0, true) +} + +#[fixture] +fn policy_remove() -> TrackerPolicy { + TrackerPolicy::new(true, 0, false) +} + +#[fixture] +fn policy_remove_persist() -> TrackerPolicy { + TrackerPolicy::new(true, 0, true) +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_get_a_torrent_entry( + #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[case] entries: Entries, +) { + make(&repo, &entries).await; + + if let Some((info_hash, torrent)) = entries.first() { + assert_eq!(repo.get(info_hash).await, Some(torrent.clone())); + } else { + assert_eq!(repo.get(&InfoHash::default()).await, None); + } +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( + #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[case] entries: Entries, + many_out_of_order: Entries, +) { + make(&repo, &entries).await; + + let entries_a = repo.get_paginated(None).await.iter().map(|(i, _)| *i).collect::>(); + + make(&repo, &many_out_of_order).await; + + let entries_b = repo.get_paginated(None).await.iter().map(|(i, _)| *i).collect::>(); + + let is_equal = entries_b.iter().take(entries_a.len()).copied().collect::>() == entries_a; + + let is_sorted = entries_b.windows(2).all(|w| w[0] <= w[1]); + + assert!( + is_equal || is_sorted, + "The order is unstable: {is_equal}, or is sorted {is_sorted}." + ); +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_get_paginated( + #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[case] entries: Entries, + #[values(paginated_limit_zero(), paginated_limit_one(), paginated_limit_one_offset_one())] paginated: Pagination, +) { + make(&repo, &entries).await; + + let mut info_hashes = repo.get_paginated(None).await.iter().map(|(i, _)| *i).collect::>(); + info_hashes.sort(); + + match paginated { + // it should return empty if limit is zero. + Pagination { limit: 0, .. } => assert_eq!(repo.get_paginated(Some(&paginated)).await, vec![]), + + // it should return a single entry if the limit is one. + Pagination { limit: 1, offset: 0 } => { + if info_hashes.is_empty() { + assert_eq!(repo.get_paginated(Some(&paginated)).await.len(), 0); + } else { + let page = repo.get_paginated(Some(&paginated)).await; + assert_eq!(page.len(), 1); + assert_eq!(page.first().map(|(i, _)| i), info_hashes.first()); + } + } + + // it should return the only the second entry if both the limit and the offset are one. + Pagination { limit: 1, offset: 1 } => { + if info_hashes.len() > 1 { + let page = repo.get_paginated(Some(&paginated)).await; + assert_eq!(page.len(), 1); + assert_eq!(page[0].0, info_hashes[1]); + } + } + // the other cases are not yet tested. + _ => {} + } +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_get_metrics( + #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[case] entries: Entries, +) { + use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + + make(&repo, &entries).await; + + let mut metrics = TorrentsMetrics::default(); + + for (_, torrent) in entries { + let stats = torrent.get_stats(); + + metrics.torrents += 1; + metrics.incomplete += u64::from(stats.incomplete); + metrics.complete += u64::from(stats.complete); + metrics.downloaded += u64::from(stats.downloaded); + } + + assert_eq!(repo.get_metrics().await, metrics); +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_import_persistent_torrents( + #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[case] entries: Entries, + #[values(persistent_empty(), persistent_single(), persistent_three())] persistent_torrents: PersistentTorrents, +) { + make(&repo, &entries).await; + + let mut downloaded = repo.get_metrics().await.downloaded; + persistent_torrents.iter().for_each(|(_, d)| downloaded += u64::from(*d)); + + repo.import_persistent(&persistent_torrents).await; + + assert_eq!(repo.get_metrics().await.downloaded, downloaded); + + for (entry, _) in persistent_torrents { + assert!(repo.get(&entry).await.is_some()); + } +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_remove_an_entry( + #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[case] entries: Entries, +) { + make(&repo, &entries).await; + + for (info_hash, torrent) in entries { + assert_eq!(repo.get(&info_hash).await, Some(torrent.clone())); + assert_eq!(repo.remove(&info_hash).await, Some(torrent)); + + assert_eq!(repo.get(&info_hash).await, None); + assert_eq!(repo.remove(&info_hash).await, None); + } + + assert_eq!(repo.get_metrics().await.torrents, 0); +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_remove_inactive_peers( + #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[case] entries: Entries, +) { + use std::ops::Sub as _; + use std::time::Duration; + + use torrust_tracker_clock::clock::stopped::Stopped as _; + use torrust_tracker_clock::clock::{self, Time as _}; + use torrust_tracker_primitives::peer; + + use crate::CurrentClock; + + const TIMEOUT: Duration = Duration::from_secs(120); + const EXPIRE: Duration = Duration::from_secs(121); + + make(&repo, &entries).await; + + let info_hash: InfoHash; + let mut peer: peer::Peer; + + // Generate a new infohash and peer. + { + let hash = &mut DefaultHasher::default(); + hash.write_u8(255); + info_hash = InfoHash::from(&hash.clone()); + peer = a_completed_peer(-1); + } + + // Set the last updated time of the peer to be 121 seconds ago. + { + let now = clock::Working::now(); + clock::Stopped::local_set(&now); + + peer.updated = now.sub(EXPIRE); + } + + // Insert the infohash and peer into the repository + // and verify there is an extra torrent entry. + { + repo.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; + assert_eq!(repo.get_metrics().await.torrents, entries.len() as u64 + 1); + } + + // Verify that this new peer was inserted into the repository. + { + let entry = repo.get(&info_hash).await.expect("it_should_get_some"); + assert!(entry.get_peers(None).contains(&peer.into())); + } + + // Remove peers that have not been updated since the timeout (120 seconds ago). + { + repo.remove_inactive_peers(CurrentClock::now_sub(&TIMEOUT).expect("it should get a time passed")) + .await; + } + + // Verify that the this peer was removed from the repository. + { + let entry = repo.get(&info_hash).await.expect("it_should_get_some"); + assert!(!entry.get_peers(None).contains(&peer.into())); + } +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_remove_peerless_torrents( + #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[case] entries: Entries, + #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, +) { + make(&repo, &entries).await; + + repo.remove_peerless_torrents(&policy).await; + + let torrents = repo.get_paginated(None).await; + + for (_, entry) in torrents { + assert!(entry.is_good(&policy)); + } +} From 9e23ec99185795d634d264d08f1e4604b356cdbf Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 26 Mar 2024 05:35:44 +0800 Subject: [PATCH 0274/1297] chore: update deps Updating crates.io index Updating arc-swap v1.7.0 -> v1.7.1 Updating async-trait v0.1.78 -> v0.1.79 Updating axum v0.7.4 -> v0.7.5 Updating axum-extra v0.9.2 -> v0.9.3 Updating backtrace v0.3.69 -> v0.3.71 Updating bytes v1.5.0 -> v1.6.0 Updating clap v4.5.3 -> v4.5.4 Updating clap_derive v4.5.3 -> v4.5.4 Updating fastrand v2.0.1 -> v2.0.2 Updating indexmap v2.2.5 -> v2.2.6 Updating libz-sys v1.1.15 -> v1.1.16 Updating rayon v1.9.0 -> v1.10.0 Updating regex v1.10.3 -> v1.10.4 Updating reqwest v0.12.0 -> v0.12.2 Updating rustls-pki-types v1.3.1 -> v1.4.0 Updating syn v2.0.53 -> v2.0.55 Adding sync_wrapper v1.0.0 --- Cargo.lock | 155 +++++++++++---------- tests/servers/health_check_api/contract.rs | 14 +- 2 files changed, 91 insertions(+), 78 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0bdd83b9b..e77b5de6d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -157,9 +157,9 @@ dependencies = [ [[package]] name = "arc-swap" -version = "1.7.0" +version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b3d0060af21e8d11a926981cc00c6c1541aa91dd64b9f881985c3da1094425f" +checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457" [[package]] name = "arrayvec" @@ -226,7 +226,7 @@ dependencies = [ "async-lock 3.3.0", "async-task", "concurrent-queue", - "fastrand 2.0.1", + "fastrand 2.0.2", "futures-lite 2.3.0", "slab", ] @@ -341,13 +341,13 @@ checksum = "fbb36e985947064623dbd357f727af08ffd077f93d696782f3c56365fa2e2799" [[package]] name = "async-trait" -version = "0.1.78" +version = "0.1.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "461abc97219de0eaaf81fe3ef974a540158f3d079c2ab200f891f1a2ef201e85" +checksum = "a507401cad91ec6a857ed5513a2073c82a9b9048762b885bb98655b306964681" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -364,9 +364,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axum" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1236b4b292f6c4d6dc34604bb5120d85c3fe1d1aa596bd5cc52ca054d13e7b9e" +checksum = "3a6c9af12842a67734c9a2e355436e5d03b22383ed60cf13cd0c18fbfe3dcbcf" dependencies = [ "async-trait", "axum-core", @@ -389,7 +389,7 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", - "sync_wrapper", + "sync_wrapper 1.0.0", "tokio", "tower", "tower-layer", @@ -423,7 +423,7 @@ dependencies = [ "mime", "pin-project-lite", "rustversion", - "sync_wrapper", + "sync_wrapper 0.1.2", "tower-layer", "tower-service", "tracing", @@ -431,9 +431,9 @@ dependencies = [ [[package]] name = "axum-extra" -version = "0.9.2" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "895ff42f72016617773af68fb90da2a9677d89c62338ec09162d4909d86fdd8f" +checksum = "0be6ea09c9b96cb5076af0de2e383bd2bc0c18f827cf1967bdd353e0b910d733" dependencies = [ "axum", "axum-core", @@ -449,6 +449,7 @@ dependencies = [ "tower", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -460,7 +461,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -488,9 +489,9 @@ dependencies = [ [[package]] name = "backtrace" -version = "0.3.69" +version = "0.3.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837" +checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d" dependencies = [ "addr2line", "cc", @@ -541,7 +542,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -589,7 +590,7 @@ dependencies = [ "async-channel 2.2.0", "async-lock 3.3.0", "async-task", - "fastrand 2.0.1", + "fastrand 2.0.2", "futures-io", "futures-lite 2.3.0", "piper", @@ -616,7 +617,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", "syn_derive", ] @@ -683,9 +684,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.5.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" +checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" [[package]] name = "cast" @@ -777,9 +778,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.3" +version = "4.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "949626d00e063efc93b6dca932419ceb5432f99769911c0b995f7e884c778813" +checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" dependencies = [ "clap_builder", "clap_derive", @@ -799,14 +800,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.3" +version = "4.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90239a040c80f5e14809ca132ddc4176ab33d5e17e49691793296e3fcb34d72f" +checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -1069,7 +1070,7 @@ dependencies = [ "proc-macro2", "quote", "strsim 0.10.0", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -1080,7 +1081,7 @@ checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" dependencies = [ "darling_core", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -1114,7 +1115,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -1254,9 +1255,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.0.1" +version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +checksum = "658bd65b1cf4c852a3cc96f18a8ce7b5640f6b703f905c7d74532294c2a63984" [[package]] name = "fern" @@ -1349,7 +1350,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -1361,7 +1362,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -1373,7 +1374,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -1451,7 +1452,7 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" dependencies = [ - "fastrand 2.0.1", + "fastrand 2.0.2", "futures-core", "futures-io", "parking", @@ -1466,7 +1467,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -1562,7 +1563,7 @@ dependencies = [ "futures-sink", "futures-util", "http", - "indexmap 2.2.5", + "indexmap 2.2.6", "slab", "tokio", "tokio-util", @@ -1801,9 +1802,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.2.5" +version = "2.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b0b929d511467233429c45a44ac1dcaa21ba0f5ba11e4879e6ed28ddb4f9df4" +checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" dependencies = [ "equivalent", "hashbrown 0.14.3", @@ -2032,9 +2033,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.15" +version = "1.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037731f5d3aaa87a5675e895b63ddff1a87624bc29f77004ea829809654e48f6" +checksum = "5e143b5e666b2695d28f6bca6497720813f699c9602dd7f5cac91008b8ada7f9" dependencies = [ "cc", "pkg-config", @@ -2167,7 +2168,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -2218,7 +2219,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", "termcolor", "thiserror", ] @@ -2418,7 +2419,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -2531,7 +2532,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -2600,7 +2601,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -2622,7 +2623,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "668d31b1c4eba19242f2088b2bf3316b82ca31082a8335764db4e083db7485d4" dependencies = [ "atomic-waker", - "fastrand 2.0.1", + "fastrand 2.0.2", "futures-io", ] @@ -2880,9 +2881,9 @@ dependencies = [ [[package]] name = "rayon" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4963ed1bc86e4f3ee217022bd855b297cef07fb9eac5dfa1f788b220b49b3bd" +checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" dependencies = [ "either", "rayon-core", @@ -2909,9 +2910,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.3" +version = "1.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15" +checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c" dependencies = [ "aho-corasick", "memchr", @@ -2953,9 +2954,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.0" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58b48d98d932f4ee75e541614d32a7f44c889b72bd9c2e04d95edd135989df88" +checksum = "2d66674f2b6fb864665eea7a3c1ac4e3dfacd2fda83cf6f935a612e01b0e3338" dependencies = [ "base64", "bytes", @@ -2981,7 +2982,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "sync_wrapper", + "sync_wrapper 0.1.2", "system-configuration", "tokio", "tokio-native-tls", @@ -3083,7 +3084,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.53", + "syn 2.0.55", "unicode-ident", ] @@ -3208,9 +3209,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.3.1" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ede67b28608b4c60685c7d54122d4400d90f62b40caee7700e700380a390fa8" +checksum = "868e20fada228fefaf6b652e00cc73623d54f8171e7352c18bb281571f2d92da" [[package]] name = "rustls-webpki" @@ -3354,7 +3355,7 @@ checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -3364,7 +3365,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50437e6a58912eecc08865e35ea2e8d365fbb2db0debb1c8bb43bf1faf055f25" dependencies = [ "form_urlencoded", - "indexmap 2.2.5", + "indexmap 2.2.6", "itoa", "ryu", "serde", @@ -3399,7 +3400,7 @@ checksum = "0b2e6b945e9d3df726b65d6ee24060aff8e3533d431f677a9695db04eff9dfdb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -3433,7 +3434,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.2.5", + "indexmap 2.2.6", "serde", "serde_derive", "serde_json", @@ -3450,7 +3451,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -3584,9 +3585,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.53" +version = "2.0.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7383cd0e49fff4b6b90ca5670bfd3e9d6a733b3f90c686605aa7eec8c4996032" +checksum = "002a1b3dbf967edfafc32655d0f377ab0bb7b994aa1d32c8cc7e9b8bf3ebb8f0" dependencies = [ "proc-macro2", "quote", @@ -3602,7 +3603,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -3611,6 +3612,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" +[[package]] +name = "sync_wrapper" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384595c11a4e2969895cad5a8c4029115f5ab956a9e5ef4de79d11a426e5f20c" + [[package]] name = "system-configuration" version = "0.5.1" @@ -3662,7 +3669,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", - "fastrand 2.0.1", + "fastrand 2.0.2", "rustix 0.38.32", "windows-sys 0.52.0", ] @@ -3699,7 +3706,7 @@ checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -3793,7 +3800,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -3857,7 +3864,7 @@ version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ - "indexmap 2.2.5", + "indexmap 2.2.6", "toml_datetime", "winnow 0.5.40", ] @@ -3868,7 +3875,7 @@ version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8534fd7f78b5405e860340ad6575217ce99f38d4d5c8f2442cb5ecb50090e1" dependencies = [ - "indexmap 2.2.5", + "indexmap 2.2.6", "toml_datetime", "winnow 0.5.40", ] @@ -3879,7 +3886,7 @@ version = "0.22.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e40bb779c5187258fd7aad0eb68cb8706a0a81fa712fbea808ab43c4b8374c4" dependencies = [ - "indexmap 2.2.5", + "indexmap 2.2.6", "serde", "serde_spanned", "toml_datetime", @@ -4095,7 +4102,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] @@ -4266,7 +4273,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", "wasm-bindgen-shared", ] @@ -4300,7 +4307,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4556,7 +4563,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.53", + "syn 2.0.55", ] [[package]] diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index c893470c2..3c3c13151 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -114,8 +114,11 @@ mod api { assert_eq!(details.binding, binding); assert!( - details.result.as_ref().is_err_and(|e| e.contains("client error (Connect)")), - "Expected to contain, \"client error (Connect)\", but have message \"{:?}\".", + details + .result + .as_ref() + .is_err_and(|e| e.contains("error sending request for url")), + "Expected to contain, \"error sending request for url\", but have message \"{:?}\".", details.result ); assert_eq!( @@ -215,8 +218,11 @@ mod http { assert_eq!(details.binding, binding); assert!( - details.result.as_ref().is_err_and(|e| e.contains("client error (Connect)")), - "Expected to contain, \"client error (Connect)\", but have message \"{:?}\".", + details + .result + .as_ref() + .is_err_and(|e| e.contains("error sending request for url")), + "Expected to contain, \"error sending request for url\", but have message \"{:?}\".", details.result ); assert_eq!( From 0999aa07412559501a35dd9e4b3ed701b36f33bf Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 26 Mar 2024 10:27:55 +0800 Subject: [PATCH 0275/1297] dev: ci: enable rust stable workflows * also change container to use rust-stable --- .github/workflows/contract.yaml | 2 +- .github/workflows/deployment.yaml | 2 +- .github/workflows/testing.yaml | 6 +++--- Containerfile | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/contract.yaml b/.github/workflows/contract.yaml index b38e0e8f5..2777417e3 100644 --- a/.github/workflows/contract.yaml +++ b/.github/workflows/contract.yaml @@ -14,7 +14,7 @@ jobs: strategy: matrix: - toolchain: [nightly] + toolchain: [nightly, stable] steps: - id: checkout diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 91f8d86eb..2a0f174f7 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -12,7 +12,7 @@ jobs: strategy: matrix: - toolchain: [nightly] + toolchain: [nightly, stable] steps: - id: checkout diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 8a54e8982..620670f97 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -39,7 +39,7 @@ jobs: strategy: matrix: - toolchain: [nightly] + toolchain: [nightly, stable] steps: - id: checkout @@ -93,7 +93,7 @@ jobs: strategy: matrix: - toolchain: [nightly] + toolchain: [nightly, stable] steps: - id: checkout @@ -132,7 +132,7 @@ jobs: strategy: matrix: - toolchain: [nightly] + toolchain: [nightly, stable] steps: - id: setup diff --git a/Containerfile b/Containerfile index 77c7da669..590b0a13b 100644 --- a/Containerfile +++ b/Containerfile @@ -3,13 +3,13 @@ # Torrust Tracker ## Builder Image -FROM rustlang/rust:nightly-bookworm as chef +FROM docker.io/library/rust:bookworm as chef WORKDIR /tmp RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash RUN cargo binstall --no-confirm cargo-chef cargo-nextest ## Tester Image -FROM rustlang/rust:nightly-bookworm-slim as tester +FROM docker.io/library/rust:slim-bookworm as tester WORKDIR /tmp RUN apt-get update; apt-get install -y curl sqlite3; apt-get autoclean From 3ac4aa5516269fdf7b2258efdfd56a99d120d508 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Apr 2024 13:35:12 +0100 Subject: [PATCH 0276/1297] docs: [#768] udpate profiling docs --- .cargo/config.toml | 1 + Cargo.toml | 6 +- cSpell.json | 8 +- docs/media/flamegraph.svg | 4 +- .../flamegraph_generated_withput_sudo.svg | 491 ++++++++++++++++++ docs/profiling.md | 75 ++- flamegraph_generated_withput_sudo.svg | 491 ++++++++++++++++++ 7 files changed, 1069 insertions(+), 7 deletions(-) create mode 100644 docs/media/flamegraph_generated_withput_sudo.svg create mode 100644 flamegraph_generated_withput_sudo.svg diff --git a/.cargo/config.toml b/.cargo/config.toml index a88db5f38..34d6230b9 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -23,3 +23,4 @@ rustflags = [ "-D", "unused", ] + diff --git a/Cargo.toml b/Cargo.toml index 99b7a334a..d045b945a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -103,6 +103,6 @@ debug = 1 lto = "fat" opt-level = 3 -[target.x86_64-unknown-linux-gnu] -linker = "/usr/bin/clang" -rustflags = ["-Clink-arg=-fuse-ld=lld", "-Clink-arg=-Wl,--no-rosegment"] \ No newline at end of file +[profile.release-debug] +inherits = "release" +debug = true \ No newline at end of file diff --git a/cSpell.json b/cSpell.json index bbcba98a7..0ee2f8306 100644 --- a/cSpell.json +++ b/cSpell.json @@ -21,6 +21,7 @@ "bools", "Bragilevsky", "bufs", + "buildid", "Buildx", "byteorder", "callgrind", @@ -69,9 +70,12 @@ "infoschema", "Intermodal", "intervali", - "kcachegrind", "Joakim", + "kallsyms", + "kcachegrind", + "kexec", "keyout", + "kptr", "lcov", "leecher", "leechers", @@ -83,6 +87,7 @@ "matchmakes", "metainfo", "middlewares", + "misresolved", "mockall", "multimap", "myacicontext", @@ -152,6 +157,7 @@ "Vagaa", "valgrind", "Vitaly", + "vmlinux", "Vuze", "Weidendorfer", "Werror", diff --git a/docs/media/flamegraph.svg b/docs/media/flamegraph.svg index 34e7146f9..58387ee06 100644 --- a/docs/media/flamegraph.svg +++ b/docs/media/flamegraph.svg @@ -1,4 +1,4 @@ - \ No newline at end of file diff --git a/docs/media/flamegraph_generated_withput_sudo.svg b/docs/media/flamegraph_generated_withput_sudo.svg new file mode 100644 index 000000000..84c00ffe3 --- /dev/null +++ b/docs/media/flamegraph_generated_withput_sudo.svg @@ -0,0 +1,491 @@ +Flame Graph Reset ZoomSearch [unknown] (188 samples, 0.14%)[unknown] (187 samples, 0.14%)[unknown] (186 samples, 0.14%)[unknown] (178 samples, 0.14%)[unknown] (172 samples, 0.13%)[unknown] (158 samples, 0.12%)[unknown] (158 samples, 0.12%)[unknown] (125 samples, 0.10%)[unknown] (102 samples, 0.08%)[unknown] (93 samples, 0.07%)[unknown] (92 samples, 0.07%)[unknown] (41 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (29 samples, 0.02%)[unknown] (25 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (15 samples, 0.01%)__GI___mmap64 (18 samples, 0.01%)__GI___mmap64 (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (17 samples, 0.01%)profiling (214 samples, 0.16%)clone3 (22 samples, 0.02%)start_thread (22 samples, 0.02%)std::sys::pal::unix::thread::Thread::new::thread_start (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::Handler::new (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::imp::make_handler (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::imp::get_stack (19 samples, 0.01%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (30 samples, 0.02%)[[vdso]] (93 samples, 0.07%)<torrust_tracker::shared::crypto::ephemeral_instance_keys::RANDOM_SEED as core::ops::deref::Deref>::deref::__stability::LAZY (143 samples, 0.11%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (31 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<BorrowType,K,V>::init_front (21 samples, 0.02%)[[vdso]] (91 samples, 0.07%)__GI___clock_gettime (14 samples, 0.01%)_int_malloc (53 samples, 0.04%)epoll_wait (254 samples, 0.19%)tokio::runtime::context::with_scheduler (28 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.01%)tokio::runtime::context::with_scheduler::{{closure}} (14 samples, 0.01%)core::option::Option<T>::map (17 samples, 0.01%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (17 samples, 0.01%)mio::poll::Poll::poll (27 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select (27 samples, 0.02%)tokio::runtime::io::driver::Driver::turn (54 samples, 0.04%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (26 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (17 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (71 samples, 0.05%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (65 samples, 0.05%)core::sync::atomic::AtomicUsize::fetch_add (65 samples, 0.05%)core::sync::atomic::atomic_add (65 samples, 0.05%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (31 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark_condvar (18 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (49 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (33 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (93 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Parker::park (75 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Inner::park (75 samples, 0.06%)core::cell::RefCell<T>::borrow_mut (18 samples, 0.01%)core::cell::RefCell<T>::try_borrow_mut (18 samples, 0.01%)core::cell::BorrowRefMut::new (18 samples, 0.01%)tokio::runtime::coop::budget (26 samples, 0.02%)tokio::runtime::coop::with_budget (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (96 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (27 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (18 samples, 0.01%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (35 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (14 samples, 0.01%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (90 samples, 0.07%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (90 samples, 0.07%)core::slice::<impl [T]>::contains (220 samples, 0.17%)<T as core::slice::cmp::SliceContains>::slice_contains (220 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (220 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (54 samples, 0.04%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (54 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (240 samples, 0.18%)tokio::runtime::scheduler::multi_thread::idle::Idle::unpark_worker_by_id (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (265 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Context::park (284 samples, 0.22%)core::option::Option<T>::or_else (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (40 samples, 0.03%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (17 samples, 0.01%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (17 samples, 0.01%)core::num::<impl u32>::wrapping_add (17 samples, 0.01%)core::sync::atomic::AtomicU64::compare_exchange (26 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (129 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (128 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (119 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::pack (39 samples, 0.03%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run (613 samples, 0.47%)tokio::runtime::context::runtime::enter_runtime (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (613 samples, 0.47%)tokio::runtime::context::set_scheduler (613 samples, 0.47%)std::thread::local::LocalKey<T>::with (613 samples, 0.47%)std::thread::local::LocalKey<T>::try_with (613 samples, 0.47%)tokio::runtime::context::set_scheduler::{{closure}} (613 samples, 0.47%)tokio::runtime::context::scoped::Scoped<T>::set (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::Context::run (613 samples, 0.47%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (777 samples, 0.59%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (776 samples, 0.59%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (16 samples, 0.01%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (16 samples, 0.01%)tokio::runtime::context::set_current_task_id (16 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (16 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (20 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (20 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::poll (835 samples, 0.64%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (56 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage (46 samples, 0.04%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (897 samples, 0.68%)tokio::runtime::task::harness::poll_future::{{closure}} (897 samples, 0.68%)tokio::runtime::task::core::Core<T,S>::store_output (62 samples, 0.05%)tokio::runtime::task::harness::poll_future (930 samples, 0.71%)std::panic::catch_unwind (927 samples, 0.71%)std::panicking::try (927 samples, 0.71%)std::panicking::try::do_call (925 samples, 0.70%)core::mem::manually_drop::ManuallyDrop<T>::take (28 samples, 0.02%)core::ptr::read (28 samples, 0.02%)tokio::runtime::task::raw::poll (938 samples, 0.71%)tokio::runtime::task::harness::Harness<T,S>::poll (934 samples, 0.71%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (934 samples, 0.71%)core::array::<impl core::default::Default for [T: 32]>::default (26 samples, 0.02%)tokio::runtime::time::Inner::lock (16 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (15 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::time::wheel::Wheel::poll (25 samples, 0.02%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (98 samples, 0.07%)tokio::runtime::time::Driver::park_internal (51 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (15 samples, 0.01%)<F as core::future::into_future::IntoFuture>::into_future (16 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (24 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (46 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (131 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (24 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (14 samples, 0.01%)core::sync::atomic::AtomicU32::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (39 samples, 0.03%)std::sync::rwlock::RwLock<T>::read (34 samples, 0.03%)std::sys::sync::rwlock::futex::RwLock::read (32 samples, 0.02%)[[heap]] (2,361 samples, 1.80%)[..[[vdso]] (313 samples, 0.24%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (41 samples, 0.03%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (16 samples, 0.01%)<alloc::string::String as core::fmt::Write>::write_str (67 samples, 0.05%)alloc::string::String::push_str (18 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (18 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (18 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (18 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (36 samples, 0.03%)core::num::<impl u64>::rotate_left (28 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (60 samples, 0.05%)core::num::<impl u64>::wrapping_add (14 samples, 0.01%)core::hash::sip::u8to64_le (60 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (184 samples, 0.14%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (15 samples, 0.01%)tokio::runtime::context::CONTEXT::__getit (19 samples, 0.01%)core::cell::Cell<T>::get (17 samples, 0.01%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (26 samples, 0.02%)core::ops::function::FnMut::call_mut (21 samples, 0.02%)tokio::runtime::coop::poll_proceed (21 samples, 0.02%)tokio::runtime::context::budget (21 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (21 samples, 0.02%)[unknown] (18 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (195 samples, 0.15%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (14 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (14 samples, 0.01%)core::result::Result<T,E>::is_err (18 samples, 0.01%)core::result::Result<T,E>::is_ok (18 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (46 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (39 samples, 0.03%)core::sync::atomic::AtomicU32::compare_exchange (19 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (19 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (245 samples, 0.19%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (26 samples, 0.02%)[[vdso]] (748 samples, 0.57%)[profiling] (34 samples, 0.03%)core::fmt::write (31 samples, 0.02%)__GI___clock_gettime (29 samples, 0.02%)__GI___libc_free (131 samples, 0.10%)arena_for_chunk (20 samples, 0.02%)arena_for_chunk (19 samples, 0.01%)heap_for_ptr (19 samples, 0.01%)heap_max_size (14 samples, 0.01%)__GI___libc_malloc (114 samples, 0.09%)__GI___libc_realloc (15 samples, 0.01%)__GI___lll_lock_wake_private (22 samples, 0.02%)__GI___pthread_disable_asynccancel (66 samples, 0.05%)__GI_getsockname (249 samples, 0.19%)__libc_calloc (15 samples, 0.01%)__libc_recvfrom (23 samples, 0.02%)__libc_sendto (130 samples, 0.10%)__memcmp_evex_movbe (451 samples, 0.34%)__memcpy_avx512_unaligned_erms (426 samples, 0.32%)__memset_avx512_unaligned_erms (215 samples, 0.16%)__posix_memalign (17 samples, 0.01%)_int_free (418 samples, 0.32%)tcache_put (24 samples, 0.02%)_int_malloc (385 samples, 0.29%)_int_memalign (31 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (26 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (15 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (15 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (15 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (54 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::grow_one (15 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (96 samples, 0.07%)alloc::raw_vec::RawVec<T,A>::grow_amortized (66 samples, 0.05%)core::num::<impl usize>::checked_add (18 samples, 0.01%)core::num::<impl usize>::overflowing_add (18 samples, 0.01%)alloc::raw_vec::finish_grow (74 samples, 0.06%)alloc::sync::Arc<T,A>::drop_slow (16 samples, 0.01%)core::mem::drop (14 samples, 0.01%)core::fmt::Formatter::pad_integral (14 samples, 0.01%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (93 samples, 0.07%)core::ptr::drop_in_place<tokio::net::udp::UdpSocket::send_to<&core::net::socket_addr::SocketAddr>::{{closure}}> (23 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (188 samples, 0.14%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_announce::{{closure}}> (30 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_connect::{{closure}}> (22 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_packet::{{closure}}> (20 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}}> (19 samples, 0.01%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::send_response::{{closure}}> (22 samples, 0.02%)malloc_consolidate (24 samples, 0.02%)core::core_arch::x86::avx2::_mm256_or_si256 (15 samples, 0.01%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (17 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (17 samples, 0.01%)rand_chacha::guts::round (66 samples, 0.05%)rand_chacha::guts::refill_wide::impl_avx2 (99 samples, 0.08%)rand_chacha::guts::refill_wide::fn_impl (98 samples, 0.07%)rand_chacha::guts::refill_wide_impl (98 samples, 0.07%)std::io::error::Error::kind (14 samples, 0.01%)[unknown] (42 samples, 0.03%)[unknown] (14 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (490 samples, 0.37%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (211 samples, 0.16%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (84 samples, 0.06%)tokio::runtime::task::core::Header::get_owner_id (18 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (18 samples, 0.01%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (20 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::remove (19 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (31 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (29 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (108 samples, 0.08%)tokio::runtime::task::core::TaskIdGuard::enter (14 samples, 0.01%)tokio::runtime::context::set_current_task_id (14 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::complete (21 samples, 0.02%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (32 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (54 samples, 0.04%)tokio::runtime::task::raw::drop_abort_handle (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (17 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (22 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (22 samples, 0.02%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (79 samples, 0.06%)core::slice::<impl [T]>::contains (178 samples, 0.14%)<T as core::slice::cmp::SliceContains>::slice_contains (178 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (178 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (40 samples, 0.03%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (40 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (216 samples, 0.16%)tokio::loom::std::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (219 samples, 0.17%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (29 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (29 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (54 samples, 0.04%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (18 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (18 samples, 0.01%)core::sync::atomic::AtomicU32::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (113 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (51 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (31 samples, 0.02%)core::sync::atomic::AtomicU64::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (447 samples, 0.34%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (174 samples, 0.13%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (19 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (489 samples, 0.37%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (489 samples, 0.37%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run (484 samples, 0.37%)tokio::runtime::context::runtime::enter_runtime (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (484 samples, 0.37%)tokio::runtime::context::set_scheduler (484 samples, 0.37%)std::thread::local::LocalKey<T>::with (484 samples, 0.37%)std::thread::local::LocalKey<T>::try_with (484 samples, 0.37%)tokio::runtime::context::set_scheduler::{{closure}} (484 samples, 0.37%)tokio::runtime::context::scoped::Scoped<T>::set (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Context::run (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (24 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (20 samples, 0.02%)tokio::runtime::task::raw::poll (515 samples, 0.39%)tokio::runtime::task::harness::Harness<T,S>::poll (493 samples, 0.38%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (493 samples, 0.38%)tokio::runtime::task::harness::poll_future (493 samples, 0.38%)std::panic::catch_unwind (493 samples, 0.38%)std::panicking::try (493 samples, 0.38%)std::panicking::try::do_call (493 samples, 0.38%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (493 samples, 0.38%)tokio::runtime::task::harness::poll_future::{{closure}} (493 samples, 0.38%)tokio::runtime::task::core::Core<T,S>::poll (493 samples, 0.38%)tokio::runtime::time::wheel::Wheel::next_expiration (16 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (27 samples, 0.02%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (15 samples, 0.01%)torrust_tracker::core::Tracker::send_stats_event::{{closure}} (44 samples, 0.03%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (15 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::d_rounds (29 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (74 samples, 0.06%)torrust_tracker::servers::udp::peer_builder::from_request (17 samples, 0.01%)torrust_tracker::servers::udp::request::AnnounceWrapper::new (51 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (54 samples, 0.04%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (58 samples, 0.04%)torrust_tracker::core::Tracker::announce::{{closure}} (70 samples, 0.05%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (113 samples, 0.09%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (175 samples, 0.13%)<T as alloc::string::ToString>::to_string (38 samples, 0.03%)core::option::Option<T>::expect (56 samples, 0.04%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (18 samples, 0.01%)<T as alloc::string::ToString>::to_string (18 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (180 samples, 0.14%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (468 samples, 0.36%)torrust_tracker::servers::udp::logging::log_response (38 samples, 0.03%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (669 samples, 0.51%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (152 samples, 0.12%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (147 samples, 0.11%)tokio::net::udp::UdpSocket::send_to::{{closure}} (138 samples, 0.11%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (119 samples, 0.09%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (75 samples, 0.06%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (39 samples, 0.03%)mio::net::udp::UdpSocket::send_to (39 samples, 0.03%)mio::io_source::IoSource<T>::do_io (39 samples, 0.03%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (39 samples, 0.03%)mio::net::udp::UdpSocket::send_to::{{closure}} (39 samples, 0.03%)std::net::udp::UdpSocket::send_to (39 samples, 0.03%)std::sys_common::net::UdpSocket::send_to (39 samples, 0.03%)std::sys::pal::unix::cvt (39 samples, 0.03%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (39 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_stats (15 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (14 samples, 0.01%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count::to_usize::{{closure}} (33 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats::{{closure}} (33 samples, 0.03%)torrust_tracker_primitives::peer::Peer::is_seeder (33 samples, 0.03%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count (75 samples, 0.06%)core::iter::traits::iterator::Iterator::sum (75 samples, 0.06%)<usize as core::iter::traits::accum::Sum>::sum (75 samples, 0.06%)<core::iter::adapters::map::Map<I,F> as core::iter::traits::iterator::Iterator>::fold (75 samples, 0.06%)core::iter::traits::iterator::Iterator::fold (75 samples, 0.06%)core::iter::adapters::map::map_fold::{{closure}} (34 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (104 samples, 0.08%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (24 samples, 0.02%)core::mem::drop (15 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (15 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (15 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (15 samples, 0.01%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (215 samples, 0.16%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (198 samples, 0.15%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (89 samples, 0.07%)core::option::Option<T>::is_some_and (32 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (31 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (30 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (30 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (26 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.03%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (58 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (58 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (58 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (58 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (58 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (20 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (238 samples, 0.18%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (236 samples, 0.18%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (208 samples, 0.16%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (208 samples, 0.16%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (282 samples, 0.21%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (67 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (53 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (53 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (22 samples, 0.02%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (22 samples, 0.02%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (22 samples, 0.02%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (22 samples, 0.02%)<u8 as core::slice::cmp::SliceOrd>::compare (22 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (18 samples, 0.01%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (23 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (23 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (43 samples, 0.03%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (43 samples, 0.03%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (43 samples, 0.03%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (43 samples, 0.03%)<u8 as core::slice::cmp::SliceOrd>::compare (43 samples, 0.03%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (17 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (151 samples, 0.12%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (145 samples, 0.11%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (137 samples, 0.10%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (137 samples, 0.10%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (266 samples, 0.20%)core::sync::atomic::AtomicU32::load (27 samples, 0.02%)core::sync::atomic::atomic_load (27 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (38 samples, 0.03%)std::sync::rwlock::RwLock<T>::read (37 samples, 0.03%)std::sys::sync::rwlock::futex::RwLock::read (36 samples, 0.03%)tracing::span::Span::log (16 samples, 0.01%)tracing::span::Span::record_all (70 samples, 0.05%)unlink_chunk (139 samples, 0.11%)rand::rng::Rng::gen (30 samples, 0.02%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (30 samples, 0.02%)rand::rng::Rng::gen (30 samples, 0.02%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (30 samples, 0.02%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (30 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (30 samples, 0.02%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (30 samples, 0.02%)rand_core::block::BlockRng<R>::generate_and_set (28 samples, 0.02%)[anon] (8,759 samples, 6.67%)[anon]uuid::v4::<impl uuid::Uuid>::new_v4 (32 samples, 0.02%)uuid::rng::bytes (32 samples, 0.02%)rand::random (32 samples, 0.02%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (15 samples, 0.01%)_int_free (338 samples, 0.26%)tcache_put (18 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (22 samples, 0.02%)hashbrown::raw::h2 (14 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (23 samples, 0.02%)hashbrown::raw::RawTableInner::find_or_find_insert_slot_inner (17 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (25 samples, 0.02%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (15 samples, 0.01%)[profiling] (545 samples, 0.42%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (32 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (22 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (16 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (30 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (28 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (83 samples, 0.06%)alloc::string::String::push_str (57 samples, 0.04%)alloc::vec::Vec<T,A>::extend_from_slice (57 samples, 0.04%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (57 samples, 0.04%)alloc::vec::Vec<T,A>::append_elements (57 samples, 0.04%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (20 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (41 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (151 samples, 0.12%)core::hash::sip::u8to64_le (50 samples, 0.04%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (33 samples, 0.03%)tokio::runtime::context::CONTEXT::__getit (35 samples, 0.03%)core::cell::Cell<T>::get (33 samples, 0.03%)[unknown] (20 samples, 0.02%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (75 samples, 0.06%)core::ops::function::FnMut::call_mut (66 samples, 0.05%)tokio::runtime::coop::poll_proceed (66 samples, 0.05%)tokio::runtime::context::budget (66 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (66 samples, 0.05%)tokio::runtime::context::budget::{{closure}} (27 samples, 0.02%)tokio::runtime::coop::poll_proceed::{{closure}} (27 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (110 samples, 0.08%)[unknown] (15 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (27 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (27 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (14 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (84 samples, 0.06%)std::sync::mutex::Mutex<T>::lock (70 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock (59 samples, 0.04%)core::sync::atomic::AtomicU32::compare_exchange (55 samples, 0.04%)core::sync::atomic::atomic_compare_exchange (55 samples, 0.04%)[unknown] (33 samples, 0.03%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (214 samples, 0.16%)__memcpy_avx512_unaligned_erms (168 samples, 0.13%)[profiling] (171 samples, 0.13%)binascii::bin2hex (77 samples, 0.06%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (280 samples, 0.21%)[unknown] (317 samples, 0.24%)[[vdso]] (2,648 samples, 2.02%)[..[unknown] (669 samples, 0.51%)[unknown] (396 samples, 0.30%)[unknown] (251 samples, 0.19%)[unknown] (65 samples, 0.05%)[unknown] (30 samples, 0.02%)[unknown] (21 samples, 0.02%)__GI___clock_gettime (56 samples, 0.04%)arena_for_chunk (72 samples, 0.05%)arena_for_chunk (62 samples, 0.05%)heap_for_ptr (49 samples, 0.04%)heap_max_size (28 samples, 0.02%)__GI___libc_free (194 samples, 0.15%)arena_for_chunk (19 samples, 0.01%)checked_request2size (24 samples, 0.02%)__GI___libc_malloc (220 samples, 0.17%)tcache_get (44 samples, 0.03%)__GI___libc_write (25 samples, 0.02%)__GI___libc_write (14 samples, 0.01%)__GI___pthread_disable_asynccancel (97 samples, 0.07%)core::num::<impl u128>::leading_zeros (15 samples, 0.01%)compiler_builtins::float::conv::int_to_float::u128_to_f64_bits (72 samples, 0.05%)__floattidf (90 samples, 0.07%)compiler_builtins::float::conv::__floattidf (86 samples, 0.07%)exp_inline (40 samples, 0.03%)log_inline (64 samples, 0.05%)__ieee754_pow_fma (114 samples, 0.09%)__libc_calloc (106 samples, 0.08%)__libc_recvfrom (252 samples, 0.19%)__libc_sendto (133 samples, 0.10%)__memcmp_evex_movbe (137 samples, 0.10%)__memcpy_avx512_unaligned_erms (1,399 samples, 1.07%)__posix_memalign (172 samples, 0.13%)__posix_memalign (80 samples, 0.06%)_mid_memalign (71 samples, 0.05%)arena_for_chunk (14 samples, 0.01%)__pow (18 samples, 0.01%)__vdso_clock_gettime (40 samples, 0.03%)[unknown] (24 samples, 0.02%)_int_free (462 samples, 0.35%)tcache_put (54 samples, 0.04%)[unknown] (14 samples, 0.01%)_int_malloc (508 samples, 0.39%)_int_memalign (68 samples, 0.05%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (54 samples, 0.04%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (14 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (78 samples, 0.06%)alloc::raw_vec::RawVec<T,A>::grow_amortized (73 samples, 0.06%)alloc::raw_vec::finish_grow (91 samples, 0.07%)core::result::Result<T,E>::map_err (31 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Weak<ring::ec::curve25519::ed25519::signing::Ed25519KeyPair,&alloc::alloc::Global>> (16 samples, 0.01%)<alloc::sync::Weak<T,A> as core::ops::drop::Drop>::drop (16 samples, 0.01%)core::mem::drop (18 samples, 0.01%)alloc::sync::Arc<T,A>::drop_slow (21 samples, 0.02%)alloc_new_heap (49 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (49 samples, 0.04%)core::fmt::Formatter::pad_integral (40 samples, 0.03%)core::fmt::Formatter::pad_integral::write_prefix (19 samples, 0.01%)core::fmt::write (20 samples, 0.02%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (155 samples, 0.12%)core::ptr::drop_in_place<core::option::Option<core::task::wake::Waker>> (71 samples, 0.05%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (245 samples, 0.19%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_announce::{{closure}}> (33 samples, 0.03%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}}> (37 samples, 0.03%)core::str::converts::from_utf8 (33 samples, 0.03%)core::str::validations::run_utf8_validation (20 samples, 0.02%)epoll_wait (31 samples, 0.02%)hashbrown::map::HashMap<K,V,S,A>::insert (17 samples, 0.01%)rand_chacha::guts::refill_wide (19 samples, 0.01%)std_detect::detect::arch::x86::__is_feature_detected::avx2 (17 samples, 0.01%)std_detect::detect::check_for (17 samples, 0.01%)std_detect::detect::cache::test (17 samples, 0.01%)std_detect::detect::cache::Cache::test (17 samples, 0.01%)core::sync::atomic::AtomicUsize::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)std::sys::pal::unix::time::Timespec::new (29 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (132 samples, 0.10%)core::cmp::impls::<impl core::cmp::PartialOrd<&B> for &A>::ge (22 samples, 0.02%)core::cmp::PartialOrd::ge (22 samples, 0.02%)std::sys::pal::unix::time::Timespec::sub_timespec (67 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock_contended (18 samples, 0.01%)std::sys_common::net::TcpListener::socket_addr (29 samples, 0.02%)std::sys_common::net::sockname (28 samples, 0.02%)syscall (552 samples, 0.42%)core::ptr::drop_in_place<core::cell::RefMut<core::option::Option<alloc::boxed::Box<tokio::runtime::scheduler::multi_thread::worker::Core>>>> (74 samples, 0.06%)core::ptr::drop_in_place<core::cell::BorrowRefMut> (74 samples, 0.06%)<core::cell::BorrowRefMut as core::ops::drop::Drop>::drop (74 samples, 0.06%)core::cell::Cell<T>::set (74 samples, 0.06%)core::cell::Cell<T>::replace (74 samples, 0.06%)core::mem::replace (74 samples, 0.06%)core::ptr::write (74 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::push_back_or_overflow (14 samples, 0.01%)tokio::runtime::context::with_scheduler (176 samples, 0.13%)std::thread::local::LocalKey<T>::try_with (152 samples, 0.12%)tokio::runtime::context::with_scheduler::{{closure}} (151 samples, 0.12%)tokio::runtime::context::scoped::Scoped<T>::with (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (71 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (16 samples, 0.01%)core::option::Option<T>::map (19 samples, 0.01%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (24 samples, 0.02%)mio::poll::Poll::poll (53 samples, 0.04%)mio::sys::unix::selector::epoll::Selector::select (53 samples, 0.04%)core::result::Result<T,E>::map (28 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (28 samples, 0.02%)tokio::io::ready::Ready::from_mio (14 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (126 samples, 0.10%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (18 samples, 0.01%)[unknown] (51 samples, 0.04%)[unknown] (100 samples, 0.08%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (326 samples, 0.25%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (205 samples, 0.16%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (77 samples, 0.06%)[unknown] (26 samples, 0.02%)<tokio::util::linked_list::DrainFilter<T,F> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (396 samples, 0.30%)tokio::loom::std::mutex::Mutex<T>::lock (18 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (573 samples, 0.44%)core::sync::atomic::AtomicUsize::fetch_add (566 samples, 0.43%)core::sync::atomic::atomic_add (566 samples, 0.43%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (635 samples, 0.48%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (25 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::next_remote_task (44 samples, 0.03%)tokio::runtime::scheduler::inject::shared::Shared<T>::is_empty (21 samples, 0.02%)tokio::runtime::scheduler::inject::shared::Shared<T>::len (21 samples, 0.02%)core::sync::atomic::AtomicUsize::load (21 samples, 0.02%)core::sync::atomic::atomic_load (21 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id (32 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (32 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (32 samples, 0.02%)std::sync::poison::Flag::done (32 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>,tokio::runtime::task::core::Header>>> (43 samples, 0.03%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (43 samples, 0.03%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (123 samples, 0.09%)tokio::runtime::task::list::OwnedTasks<S>::remove (117 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (80 samples, 0.06%)tokio::runtime::scheduler::defer::Defer::wake (17 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (46 samples, 0.04%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (71 samples, 0.05%)std::sync::condvar::Condvar::wait (56 samples, 0.04%)std::sys::sync::condvar::futex::Condvar::wait (56 samples, 0.04%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (56 samples, 0.04%)core::sync::atomic::AtomicUsize::compare_exchange (37 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (37 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (138 samples, 0.11%)tokio::runtime::driver::Driver::park (77 samples, 0.06%)tokio::runtime::driver::TimeDriver::park (77 samples, 0.06%)tokio::runtime::time::Driver::park (75 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Parker::park (266 samples, 0.20%)tokio::runtime::scheduler::multi_thread::park::Inner::park (266 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (432 samples, 0.33%)tokio::runtime::scheduler::multi_thread::worker::Core::should_notify_others (26 samples, 0.02%)core::cell::RefCell<T>::borrow_mut (94 samples, 0.07%)core::cell::RefCell<T>::try_borrow_mut (94 samples, 0.07%)core::cell::BorrowRefMut::new (94 samples, 0.07%)tokio::runtime::coop::budget (142 samples, 0.11%)tokio::runtime::coop::with_budget (142 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (121 samples, 0.09%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (44 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (208 samples, 0.16%)tokio::runtime::signal::Driver::process (30 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (46 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (46 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (35 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::set_stage (75 samples, 0.06%)core::sync::atomic::AtomicUsize::fetch_xor (76 samples, 0.06%)core::sync::atomic::atomic_xor (76 samples, 0.06%)tokio::runtime::task::state::State::transition_to_complete (79 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::complete (113 samples, 0.09%)tokio::runtime::task::state::State::transition_to_terminal (18 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::dealloc (28 samples, 0.02%)core::mem::drop (18 samples, 0.01%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (18 samples, 0.01%)core::ptr::drop_in_place<tokio::util::sharded_list::ShardGuard<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>> (16 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>>> (16 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (16 samples, 0.01%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (53 samples, 0.04%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (21 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (113 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (15 samples, 0.01%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (15 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (15 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (15 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (14 samples, 0.01%)tokio::runtime::task::raw::drop_abort_handle (82 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (23 samples, 0.02%)tokio::runtime::task::state::State::ref_dec (23 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::task::raw::drop_join_handle_slow (34 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::drop_join_handle_slow (32 samples, 0.02%)tokio::runtime::task::state::State::unset_join_interested (23 samples, 0.02%)tokio::runtime::task::state::State::fetch_update (23 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (43 samples, 0.03%)core::num::<impl u32>::wrapping_add (23 samples, 0.02%)core::option::Option<T>::or_else (37 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (36 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (36 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (38 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (59 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (45 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (132 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (63 samples, 0.05%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run (290 samples, 0.22%)tokio::runtime::context::runtime::enter_runtime (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (290 samples, 0.22%)tokio::runtime::context::set_scheduler (290 samples, 0.22%)std::thread::local::LocalKey<T>::with (290 samples, 0.22%)std::thread::local::LocalKey<T>::try_with (290 samples, 0.22%)tokio::runtime::context::set_scheduler::{{closure}} (290 samples, 0.22%)tokio::runtime::context::scoped::Scoped<T>::set (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::Context::run (290 samples, 0.22%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (327 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (322 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::poll (333 samples, 0.25%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (342 samples, 0.26%)tokio::runtime::task::harness::poll_future::{{closure}} (342 samples, 0.26%)tokio::runtime::task::harness::poll_future (348 samples, 0.27%)std::panic::catch_unwind (347 samples, 0.26%)std::panicking::try (347 samples, 0.26%)std::panicking::try::do_call (347 samples, 0.26%)core::sync::atomic::AtomicUsize::compare_exchange (18 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (18 samples, 0.01%)tokio::runtime::task::state::State::transition_to_running (47 samples, 0.04%)tokio::runtime::task::state::State::fetch_update_action (47 samples, 0.04%)tokio::runtime::task::state::State::transition_to_running::{{closure}} (19 samples, 0.01%)tokio::runtime::task::raw::poll (427 samples, 0.33%)tokio::runtime::task::harness::Harness<T,S>::poll (408 samples, 0.31%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (407 samples, 0.31%)tokio::runtime::task::state::State::transition_to_idle (17 samples, 0.01%)core::array::<impl core::default::Default for [T: 32]>::default (21 samples, 0.02%)tokio::runtime::time::wheel::Wheel::poll (14 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (72 samples, 0.05%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (23 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (15 samples, 0.01%)tokio::runtime::time::source::TimeSource::now (14 samples, 0.01%)tokio::runtime::time::Driver::park_internal (155 samples, 0.12%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (96 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (35 samples, 0.03%)core::num::<impl usize>::pow (35 samples, 0.03%)tokio::runtime::time::wheel::level::level_range (39 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (33 samples, 0.03%)core::num::<impl usize>::pow (33 samples, 0.03%)tokio::runtime::time::wheel::level::Level::next_expiration (208 samples, 0.16%)tokio::runtime::time::wheel::level::slot_range (48 samples, 0.04%)core::num::<impl usize>::pow (48 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (277 samples, 0.21%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::is_empty (18 samples, 0.01%)core::option::Option<T>::is_some (18 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (50 samples, 0.04%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (37 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (27 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (19 samples, 0.01%)core::iter::traits::iterator::Iterator::collect (17 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (17 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (17 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (17 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (20 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (20 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (20 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (62 samples, 0.05%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (40 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (27 samples, 0.02%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (17 samples, 0.01%)torrust_tracker::servers::udp::peer_builder::from_request (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (19 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (355 samples, 0.27%)<F as core::future::into_future::IntoFuture>::into_future (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (37 samples, 0.03%)core::sync::atomic::AtomicUsize::fetch_add (25 samples, 0.02%)core::sync::atomic::atomic_add (25 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet (14 samples, 0.01%)core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (20 samples, 0.02%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)core::result::Result<T,E>::map_err (16 samples, 0.01%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (136 samples, 0.10%)torrust_tracker::core::Tracker::announce::{{closure}} (173 samples, 0.13%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (267 samples, 0.20%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (30 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (423 samples, 0.32%)core::fmt::Formatter::new (26 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (80 samples, 0.06%)core::fmt::num::imp::fmt_u64 (58 samples, 0.04%)core::intrinsics::copy_nonoverlapping (15 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (74 samples, 0.06%)core::fmt::num::imp::fmt_u64 (70 samples, 0.05%)<T as alloc::string::ToString>::to_string (207 samples, 0.16%)core::option::Option<T>::expect (19 samples, 0.01%)core::ptr::drop_in_place<alloc::string::String> (18 samples, 0.01%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (18 samples, 0.01%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (18 samples, 0.01%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (18 samples, 0.01%)torrust_tracker::servers::udp::logging::map_action_name (25 samples, 0.02%)alloc::str::<impl alloc::borrow::ToOwned for str>::to_owned (14 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (345 samples, 0.26%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (18 samples, 0.01%)core::fmt::num::imp::fmt_u64 (14 samples, 0.01%)<T as alloc::string::ToString>::to_string (35 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (1,067 samples, 0.81%)torrust_tracker::servers::udp::logging::log_response (72 samples, 0.05%)alloc::vec::from_elem (68 samples, 0.05%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (68 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (68 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (68 samples, 0.05%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (68 samples, 0.05%)alloc::alloc::Global::alloc_impl (68 samples, 0.05%)alloc::alloc::alloc_zeroed (68 samples, 0.05%)__rdl_alloc_zeroed (68 samples, 0.05%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (68 samples, 0.05%)[unknown] (48 samples, 0.04%)[unknown] (16 samples, 0.01%)[unknown] (28 samples, 0.02%)std::sys::pal::unix::cvt (134 samples, 0.10%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (134 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (1,908 samples, 1.45%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (504 samples, 0.38%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (382 samples, 0.29%)tokio::net::udp::UdpSocket::send_to::{{closure}} (344 samples, 0.26%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (332 samples, 0.25%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (304 samples, 0.23%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (215 samples, 0.16%)mio::net::udp::UdpSocket::send_to (185 samples, 0.14%)mio::io_source::IoSource<T>::do_io (185 samples, 0.14%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (185 samples, 0.14%)mio::net::udp::UdpSocket::send_to::{{closure}} (185 samples, 0.14%)std::net::udp::UdpSocket::send_to (185 samples, 0.14%)std::sys_common::net::UdpSocket::send_to (169 samples, 0.13%)alloc::vec::Vec<T>::with_capacity (17 samples, 0.01%)alloc::vec::Vec<T,A>::with_capacity_in (17 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (104 samples, 0.08%)tokio::net::udp::UdpSocket::ready::{{closure}} (85 samples, 0.06%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (190 samples, 0.14%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (49 samples, 0.04%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (28 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (330 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (327 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (92 samples, 0.07%)tokio::task::spawn::spawn (92 samples, 0.07%)tokio::task::spawn::spawn_inner (92 samples, 0.07%)tokio::runtime::context::current::with_current (92 samples, 0.07%)std::thread::local::LocalKey<T>::try_with (92 samples, 0.07%)tokio::runtime::context::current::with_current::{{closure}} (92 samples, 0.07%)core::option::Option<T>::map (92 samples, 0.07%)tokio::task::spawn::spawn_inner::{{closure}} (92 samples, 0.07%)tokio::runtime::scheduler::Handle::spawn (92 samples, 0.07%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (92 samples, 0.07%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (92 samples, 0.07%)tokio::runtime::task::list::OwnedTasks<S>::bind (90 samples, 0.07%)tokio::runtime::task::new_task (89 samples, 0.07%)tokio::runtime::task::raw::RawTask::new (89 samples, 0.07%)tokio::runtime::task::core::Cell<T,S>::new (89 samples, 0.07%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (34 samples, 0.03%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (27 samples, 0.02%)alloc::sync::Arc<T>::new (21 samples, 0.02%)alloc::boxed::Box<T>::new (21 samples, 0.02%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (152 samples, 0.12%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (125 samples, 0.10%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (88 samples, 0.07%)core::option::Option<T>::is_some_and (18 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (17 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (17 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (17 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (22 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (22 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (17 samples, 0.01%)std::sync::rwlock::RwLock<T>::read (16 samples, 0.01%)std::sys::sync::rwlock::futex::RwLock::read (16 samples, 0.01%)tracing::span::Span::log (26 samples, 0.02%)core::fmt::Arguments::new_v1 (15 samples, 0.01%)tracing_core::span::Record::is_empty (34 samples, 0.03%)tracing_core::field::ValueSet::is_empty (34 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::all (22 samples, 0.02%)tracing_core::field::ValueSet::is_empty::{{closure}} (18 samples, 0.01%)core::option::Option<T>::is_none (16 samples, 0.01%)core::option::Option<T>::is_some (16 samples, 0.01%)tracing::span::Span::record_all (143 samples, 0.11%)unlink_chunk (185 samples, 0.14%)uuid::builder::Builder::with_variant (48 samples, 0.04%)[unknown] (40 samples, 0.03%)uuid::builder::Builder::from_random_bytes (77 samples, 0.06%)uuid::builder::Builder::with_version (29 samples, 0.02%)[unknown] (24 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (161 samples, 0.12%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (161 samples, 0.12%)[unknown] (92 samples, 0.07%)rand::rng::Rng::gen (162 samples, 0.12%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (162 samples, 0.12%)rand::rng::Rng::gen (162 samples, 0.12%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (162 samples, 0.12%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (162 samples, 0.12%)[unknown] (18,233 samples, 13.89%)[unknown]uuid::v4::<impl uuid::Uuid>::new_v4 (270 samples, 0.21%)uuid::rng::bytes (190 samples, 0.14%)rand::random (190 samples, 0.14%)__memcpy_avx512_unaligned_erms (69 samples, 0.05%)_int_free (23 samples, 0.02%)_int_malloc (23 samples, 0.02%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)advise_stack_range (31 samples, 0.02%)__GI_madvise (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (29 samples, 0.02%)[unknown] (28 samples, 0.02%)[unknown] (28 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (17 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (31 samples, 0.02%)syscall (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (29 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (17 samples, 0.01%)std::sync::condvar::Condvar::wait_timeout (35 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_timeout (35 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (35 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (56 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (56 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (56 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (56 samples, 0.04%)std::sys::pal::unix::futex::futex_wait (56 samples, 0.04%)syscall (56 samples, 0.04%)[unknown] (56 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (53 samples, 0.04%)[unknown] (52 samples, 0.04%)[unknown] (46 samples, 0.04%)[unknown] (39 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (15 samples, 0.01%)[[vdso]] (26 samples, 0.02%)[[vdso]] (263 samples, 0.20%)__ieee754_pow_fma (26 samples, 0.02%)__pow (314 samples, 0.24%)std::f64::<impl f64>::powf (345 samples, 0.26%)__GI___clock_gettime (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (416 samples, 0.32%)std::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_processing_scheduled_tasks (24 samples, 0.02%)std::time::Instant::now (18 samples, 0.01%)std::sys::pal::unix::time::Instant::now (18 samples, 0.01%)mio::poll::Poll::poll (102 samples, 0.08%)mio::sys::unix::selector::epoll::Selector::select (102 samples, 0.08%)epoll_wait (99 samples, 0.08%)[unknown] (92 samples, 0.07%)[unknown] (91 samples, 0.07%)[unknown] (91 samples, 0.07%)[unknown] (88 samples, 0.07%)[unknown] (85 samples, 0.06%)[unknown] (84 samples, 0.06%)[unknown] (43 samples, 0.03%)[unknown] (29 samples, 0.02%)[unknown] (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (125 samples, 0.10%)tokio::runtime::scheduler::multi_thread::park::Parker::park_timeout (125 samples, 0.10%)tokio::runtime::driver::Driver::park_timeout (125 samples, 0.10%)tokio::runtime::driver::TimeDriver::park_timeout (125 samples, 0.10%)tokio::runtime::time::Driver::park_timeout (125 samples, 0.10%)tokio::runtime::time::Driver::park_internal (116 samples, 0.09%)tokio::runtime::io::driver::Driver::turn (116 samples, 0.09%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (148 samples, 0.11%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (111 samples, 0.08%)alloc::sync::Arc<T,A>::inner (111 samples, 0.08%)core::ptr::non_null::NonNull<T>::as_ref (111 samples, 0.08%)core::sync::atomic::AtomicUsize::compare_exchange (16 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (16 samples, 0.01%)core::bool::<impl bool>::then (88 samples, 0.07%)std::sys::pal::unix::futex::futex_wait (13,339 samples, 10.16%)std::sys::pal::..syscall (13,003 samples, 9.90%)syscall[unknown] (12,895 samples, 9.82%)[unknown][unknown] (12,759 samples, 9.72%)[unknown][unknown] (12,313 samples, 9.38%)[unknown][unknown] (12,032 samples, 9.16%)[unknown][unknown] (11,734 samples, 8.94%)[unknown][unknown] (11,209 samples, 8.54%)[unknown][unknown] (10,265 samples, 7.82%)[unknown][unknown] (9,345 samples, 7.12%)[unknown][unknown] (8,623 samples, 6.57%)[unknown][unknown] (7,744 samples, 5.90%)[unknow..[unknown] (5,922 samples, 4.51%)[unkn..[unknown] (4,459 samples, 3.40%)[un..[unknown] (2,808 samples, 2.14%)[..[unknown] (1,275 samples, 0.97%)[unknown] (1,022 samples, 0.78%)[unknown] (738 samples, 0.56%)[unknown] (607 samples, 0.46%)[unknown] (155 samples, 0.12%)core::result::Result<T,E>::is_err (77 samples, 0.06%)core::result::Result<T,E>::is_ok (77 samples, 0.06%)std::sync::condvar::Condvar::wait (13,429 samples, 10.23%)std::sync::cond..std::sys::sync::condvar::futex::Condvar::wait (13,428 samples, 10.23%)std::sys::sync:..std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (13,428 samples, 10.23%)std::sys::sync:..std::sys::sync::mutex::futex::Mutex::lock (89 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (13,508 samples, 10.29%)tokio::runtime:..tokio::loom::std::mutex::Mutex<T>::lock (64 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (31 samples, 0.02%)core::sync::atomic::AtomicU32::compare_exchange (30 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (30 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (38 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Parker::park (34 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park (34 samples, 0.03%)core::array::<impl core::default::Default for [T: 32]>::default (17 samples, 0.01%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (19 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (33 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (15 samples, 0.01%)core::num::<impl usize>::pow (15 samples, 0.01%)tokio::runtime::time::wheel::level::level_range (17 samples, 0.01%)tokio::runtime::time::wheel::level::slot_range (15 samples, 0.01%)core::num::<impl usize>::pow (15 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_expiration (95 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (41 samples, 0.03%)core::num::<impl usize>::pow (41 samples, 0.03%)tokio::runtime::time::wheel::Wheel::next_expiration (129 samples, 0.10%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (202 samples, 0.15%)tokio::runtime::time::wheel::Wheel::poll_at (17 samples, 0.01%)tokio::runtime::time::wheel::Wheel::next_expiration (15 samples, 0.01%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (38 samples, 0.03%)core::option::Option<T>::map (38 samples, 0.03%)core::result::Result<T,E>::map (31 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (31 samples, 0.02%)alloc::vec::Vec<T,A>::set_len (17 samples, 0.01%)[[vdso]] (28 samples, 0.02%)[unknown] (11,031 samples, 8.40%)[unknown][unknown] (10,941 samples, 8.33%)[unknown][unknown] (10,850 samples, 8.26%)[unknown][unknown] (10,691 samples, 8.14%)[unknown][unknown] (10,070 samples, 7.67%)[unknown][unknown] (9,737 samples, 7.42%)[unknown][unknown] (7,659 samples, 5.83%)[unknow..[unknown] (6,530 samples, 4.97%)[unkno..[unknown] (5,633 samples, 4.29%)[unkn..[unknown] (5,055 samples, 3.85%)[unk..[unknown] (4,046 samples, 3.08%)[un..[unknown] (2,911 samples, 2.22%)[..[unknown] (2,115 samples, 1.61%)[unknown] (1,226 samples, 0.93%)[unknown] (455 samples, 0.35%)[unknown] (408 samples, 0.31%)[unknown] (249 samples, 0.19%)[unknown] (202 samples, 0.15%)[unknown] (100 samples, 0.08%)mio::poll::Poll::poll (11,328 samples, 8.63%)mio::poll::P..mio::sys::unix::selector::epoll::Selector::select (11,328 samples, 8.63%)mio::sys::un..epoll_wait (11,229 samples, 8.55%)epoll_wait__GI___pthread_disable_asynccancel (50 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (47 samples, 0.04%)tokio::util::bit::Pack::pack (38 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (25 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (23 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (19 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (11,595 samples, 8.83%)tokio::runti..tokio::runtime::io::scheduled_io::ScheduledIo::wake (175 samples, 0.13%)__GI___clock_gettime (15 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (18 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (26 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (26 samples, 0.02%)tokio::time::clock::Clock::now (20 samples, 0.02%)tokio::time::clock::now (20 samples, 0.02%)std::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Instant::now (20 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (17 samples, 0.01%)tokio::runtime::time::Driver::park_internal (11,686 samples, 8.90%)tokio::runtim..tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (11,957 samples, 9.11%)tokio::runtim..tokio::runtime::driver::Driver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::driver::TimeDriver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::time::Driver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::scheduler::multi_thread::park::Parker::park (25,502 samples, 19.42%)tokio::runtime::scheduler::mul..tokio::runtime::scheduler::multi_thread::park::Inner::park (25,502 samples, 19.42%)tokio::runtime::scheduler::mul..tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (25,547 samples, 19.46%)tokio::runtime::scheduler::mul..core::result::Result<T,E>::is_err (14 samples, 0.01%)core::result::Result<T,E>::is_ok (14 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (45 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (45 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (84 samples, 0.06%)std::sync::mutex::Mutex<T>::lock (81 samples, 0.06%)std::sys::sync::mutex::futex::Mutex::lock (73 samples, 0.06%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (122 samples, 0.09%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (90 samples, 0.07%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (90 samples, 0.07%)core::slice::<impl [T]>::contains (241 samples, 0.18%)<T as core::slice::cmp::SliceContains>::slice_contains (241 samples, 0.18%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (241 samples, 0.18%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (75 samples, 0.06%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (75 samples, 0.06%)core::sync::atomic::AtomicU32::compare_exchange (20 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (283 samples, 0.22%)tokio::loom::std::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (24 samples, 0.02%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (33 samples, 0.03%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (33 samples, 0.03%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (33 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::unpark_worker_by_id (98 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (401 samples, 0.31%)alloc::vec::Vec<T,A>::push (14 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (15 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (15 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::unlock (14 samples, 0.01%)core::result::Result<T,E>::is_err (15 samples, 0.01%)core::result::Result<T,E>::is_ok (15 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (22 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (22 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (63 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (62 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock (59 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (106 samples, 0.08%)tokio::runtime::scheduler::multi_thread::idle::State::dec_num_unparked (14 samples, 0.01%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (21 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (17 samples, 0.01%)alloc::sync::Arc<T,A>::inner (17 samples, 0.01%)core::ptr::non_null::NonNull<T>::as_ref (17 samples, 0.01%)core::sync::atomic::AtomicU32::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (68 samples, 0.05%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (51 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (33 samples, 0.03%)core::sync::atomic::AtomicU64::load (16 samples, 0.01%)core::sync::atomic::atomic_load (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (106 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::park (26,672 samples, 20.31%)tokio::runtime::scheduler::multi..tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (272 samples, 0.21%)tokio::runtime::scheduler::multi_thread::worker::Core::has_tasks (33 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::has_tasks (24 samples, 0.02%)tokio::runtime::context::budget (18 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (18 samples, 0.01%)syscall (61 samples, 0.05%)__memcpy_avx512_unaligned_erms (172 samples, 0.13%)__memcpy_avx512_unaligned_erms (224 samples, 0.17%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (228 samples, 0.17%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (228 samples, 0.17%)std::panic::catch_unwind (415 samples, 0.32%)std::panicking::try (415 samples, 0.32%)std::panicking::try::do_call (415 samples, 0.32%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (415 samples, 0.32%)core::ops::function::FnOnce::call_once (415 samples, 0.32%)tokio::runtime::task::harness::Harness<T,S>::complete::{{closure}} (415 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (415 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::set_stage (410 samples, 0.31%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (27 samples, 0.02%)core::result::Result<T,E>::is_err (43 samples, 0.03%)core::result::Result<T,E>::is_ok (43 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::complete (570 samples, 0.43%)tokio::runtime::task::harness::Harness<T,S>::release (155 samples, 0.12%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (152 samples, 0.12%)tokio::runtime::task::list::OwnedTasks<S>::remove (152 samples, 0.12%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (103 samples, 0.08%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (65 samples, 0.05%)tokio::loom::std::mutex::Mutex<T>::lock (58 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (58 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (54 samples, 0.04%)std::io::stdio::stderr::INSTANCE (17 samples, 0.01%)tokio::runtime::coop::budget (26 samples, 0.02%)tokio::runtime::coop::with_budget (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (35 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (70 samples, 0.05%)__memcpy_avx512_unaligned_erms (42 samples, 0.03%)core::cmp::Ord::min (22 samples, 0.02%)core::cmp::min_by (22 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (27 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (30 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (24 samples, 0.02%)core::slice::index::<impl core::ops::index::Index<I> for [T]>::index (19 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::index (19 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (19 samples, 0.01%)<core::ops::range::Range<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (19 samples, 0.01%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (44 samples, 0.03%)std::io::impls::<impl std::io::Read for &[u8]>::read_exact (20 samples, 0.02%)byteorder::io::ReadBytesExt::read_i32 (46 samples, 0.04%)core::cmp::Ord::min (14 samples, 0.01%)core::cmp::min_by (14 samples, 0.01%)std::io::cursor::Cursor<T>::remaining_slice (19 samples, 0.01%)byteorder::io::ReadBytesExt::read_i64 (24 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (24 samples, 0.02%)aquatic_udp_protocol::request::Request::from_bytes (349 samples, 0.27%)__GI___lll_lock_wake_private (148 samples, 0.11%)[unknown] (139 samples, 0.11%)[unknown] (137 samples, 0.10%)[unknown] (123 samples, 0.09%)[unknown] (111 samples, 0.08%)[unknown] (98 samples, 0.07%)[unknown] (42 samples, 0.03%)[unknown] (30 samples, 0.02%)__GI___lll_lock_wait_private (553 samples, 0.42%)futex_wait (541 samples, 0.41%)[unknown] (536 samples, 0.41%)[unknown] (531 samples, 0.40%)[unknown] (524 samples, 0.40%)[unknown] (515 samples, 0.39%)[unknown] (498 samples, 0.38%)[unknown] (470 samples, 0.36%)[unknown] (435 samples, 0.33%)[unknown] (350 samples, 0.27%)[unknown] (327 samples, 0.25%)[unknown] (290 samples, 0.22%)[unknown] (222 samples, 0.17%)[unknown] (160 samples, 0.12%)[unknown] (104 samples, 0.08%)[unknown] (33 samples, 0.03%)[unknown] (25 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (703 samples, 0.54%)__GI___libc_free (866 samples, 0.66%)tracing::span::Span::record_all (30 samples, 0.02%)unlink_chunk (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (899 samples, 0.68%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (899 samples, 0.68%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (899 samples, 0.68%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (899 samples, 0.68%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (899 samples, 0.68%)alloc::alloc::dealloc (899 samples, 0.68%)__rdl_dealloc (899 samples, 0.68%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (899 samples, 0.68%)core::result::Result<T,E>::expect (91 samples, 0.07%)core::result::Result<T,E>::map_err (28 samples, 0.02%)[[vdso]] (28 samples, 0.02%)__GI___clock_gettime (47 samples, 0.04%)std::time::Instant::elapsed (67 samples, 0.05%)std::time::Instant::now (54 samples, 0.04%)std::sys::pal::unix::time::Instant::now (54 samples, 0.04%)std::sys::pal::unix::time::Timespec::now (53 samples, 0.04%)std::sys::pal::unix::cvt (23 samples, 0.02%)__GI_getsockname (3,792 samples, 2.89%)__..[unknown] (3,714 samples, 2.83%)[u..[unknown] (3,661 samples, 2.79%)[u..[unknown] (3,557 samples, 2.71%)[u..[unknown] (3,416 samples, 2.60%)[u..[unknown] (2,695 samples, 2.05%)[..[unknown] (2,063 samples, 1.57%)[unknown] (891 samples, 0.68%)[unknown] (270 samples, 0.21%)[unknown] (99 samples, 0.08%)[unknown] (94 samples, 0.07%)[unknown] (84 samples, 0.06%)[unknown] (77 samples, 0.06%)[unknown] (25 samples, 0.02%)[unknown] (16 samples, 0.01%)std::sys_common::net::TcpListener::socket_addr::{{closure}} (3,800 samples, 2.89%)st..tokio::net::udp::UdpSocket::local_addr (3,838 samples, 2.92%)to..mio::net::udp::UdpSocket::local_addr (3,838 samples, 2.92%)mi..std::net::tcp::TcpListener::local_addr (3,838 samples, 2.92%)st..std::sys_common::net::TcpListener::socket_addr (3,838 samples, 2.92%)st..std::sys_common::net::sockname (3,835 samples, 2.92%)st..[[vdso]] (60 samples, 0.05%)rand_chacha::guts::ChaCha::pos64 (168 samples, 0.13%)<ppv_lite86::soft::x2<W,G> as core::ops::arith::AddAssign>::add_assign (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::AddAssign>::add_assign (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::Add>::add (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_add_epi32 (26 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_or_si256 (29 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (31 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (31 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (18 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (18 samples, 0.01%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (18 samples, 0.01%)rand_chacha::guts::round (118 samples, 0.09%)rand_chacha::guts::refill_wide::impl_avx2 (312 samples, 0.24%)rand_chacha::guts::refill_wide::fn_impl (312 samples, 0.24%)rand_chacha::guts::refill_wide_impl (312 samples, 0.24%)<rand_chacha::chacha::ChaCha12Core as rand_core::block::BlockRngCore>::generate (384 samples, 0.29%)rand_chacha::guts::ChaCha::refill4 (384 samples, 0.29%)rand::rng::Rng::gen (432 samples, 0.33%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (432 samples, 0.33%)rand::rng::Rng::gen (432 samples, 0.33%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (432 samples, 0.33%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (432 samples, 0.33%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (432 samples, 0.33%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (432 samples, 0.33%)rand_core::block::BlockRng<R>::generate_and_set (392 samples, 0.30%)<rand::rngs::adapter::reseeding::ReseedingCore<R,Rsdr> as rand_core::block::BlockRngCore>::generate (392 samples, 0.30%)torrust_tracker::servers::udp::handlers::RequestId::make (440 samples, 0.34%)uuid::v4::<impl uuid::Uuid>::new_v4 (436 samples, 0.33%)uuid::rng::bytes (435 samples, 0.33%)rand::random (435 samples, 0.33%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (34 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (22 samples, 0.02%)core::iter::traits::iterator::Iterator::collect (16 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (16 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (16 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (16 samples, 0.01%)<core::iter::adapters::cloned::Cloned<I> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)<core::iter::adapters::take::Take<I> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::next (15 samples, 0.01%)core::iter::traits::iterator::Iterator::find (15 samples, 0.01%)core::iter::traits::iterator::Iterator::try_fold (15 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (31 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.03%)core::slice::iter::Iter<T>::post_inc_start (14 samples, 0.01%)core::ptr::non_null::NonNull<T>::add (14 samples, 0.01%)__memcmp_evex_movbe (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (26 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (165 samples, 0.13%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (165 samples, 0.13%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (165 samples, 0.13%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (165 samples, 0.13%)<u8 as core::slice::cmp::SliceOrd>::compare (165 samples, 0.13%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (339 samples, 0.26%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (308 samples, 0.23%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (308 samples, 0.23%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (342 samples, 0.26%)std::sys::sync::rwlock::futex::RwLock::spin_read (25 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_until (25 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read_contended (28 samples, 0.02%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (436 samples, 0.33%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (397 samples, 0.30%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (29 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (29 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (29 samples, 0.02%)__memcmp_evex_movbe (31 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (52 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (52 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (52 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (52 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (52 samples, 0.04%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (103 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (102 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (96 samples, 0.07%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (96 samples, 0.07%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (72 samples, 0.05%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.08%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.08%)core::slice::iter::Iter<T>::post_inc_start (32 samples, 0.02%)core::ptr::non_null::NonNull<T>::add (32 samples, 0.02%)__memcmp_evex_movbe (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (81 samples, 0.06%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (271 samples, 0.21%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (271 samples, 0.21%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (271 samples, 0.21%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (271 samples, 0.21%)<u8 as core::slice::cmp::SliceOrd>::compare (271 samples, 0.21%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (610 samples, 0.46%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (566 samples, 0.43%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (566 samples, 0.43%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut,K,V,Type>::keys (18 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (616 samples, 0.47%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::KV>::split (15 samples, 0.01%)alloc::collections::btree::map::entry::Entry<K,V,A>::or_insert (46 samples, 0.04%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (45 samples, 0.03%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert_recursing (40 samples, 0.03%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert (27 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (29 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (20 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (120 samples, 0.09%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (118 samples, 0.09%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Owned,K,V,alloc::collections::btree::node::marker::Leaf>::new_leaf (118 samples, 0.09%)alloc::collections::btree::node::LeafNode<K,V>::new (118 samples, 0.09%)alloc::boxed::Box<T,A>::new_uninit_in (118 samples, 0.09%)alloc::boxed::Box<T,A>::try_new_uninit_in (118 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (118 samples, 0.09%)alloc::alloc::Global::alloc_impl (118 samples, 0.09%)alloc::alloc::alloc (118 samples, 0.09%)__rdl_alloc (118 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (118 samples, 0.09%)__GI___libc_malloc (118 samples, 0.09%)_int_malloc (107 samples, 0.08%)_int_malloc (28 samples, 0.02%)__GI___libc_malloc (32 samples, 0.02%)__rdl_alloc (36 samples, 0.03%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (36 samples, 0.03%)alloc::sync::Arc<T>::new (42 samples, 0.03%)alloc::boxed::Box<T>::new (42 samples, 0.03%)alloc::alloc::exchange_malloc (39 samples, 0.03%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (39 samples, 0.03%)alloc::alloc::Global::alloc_impl (39 samples, 0.03%)alloc::alloc::alloc (39 samples, 0.03%)core::mem::drop (15 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (15 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (15 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (15 samples, 0.01%)__GI___libc_free (39 samples, 0.03%)_int_free (37 samples, 0.03%)get_max_fast (16 samples, 0.01%)core::option::Option<T>::is_some_and (50 samples, 0.04%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (50 samples, 0.04%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (50 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (50 samples, 0.04%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (290 samples, 0.22%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (284 samples, 0.22%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (255 samples, 0.19%)std::sys::sync::rwlock::futex::RwLock::spin_read (16 samples, 0.01%)std::sys::sync::rwlock::futex::RwLock::spin_until (16 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (21 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (21 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (21 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read_contended (21 samples, 0.02%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (1,147 samples, 0.87%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (1,144 samples, 0.87%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents_mut (32 samples, 0.02%)std::sync::rwlock::RwLock<T>::write (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::write (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::write_contended (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_write (28 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_until (28 samples, 0.02%)torrust_tracker::core::Tracker::announce::{{closure}} (1,597 samples, 1.22%)<core::net::socket_addr::SocketAddrV4 as core::hash::Hash>::hash (14 samples, 0.01%)<core::net::ip_addr::Ipv4Addr as core::hash::Hash>::hash (14 samples, 0.01%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (29 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (24 samples, 0.02%)<core::time::Nanoseconds as core::hash::Hash>::hash (25 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (25 samples, 0.02%)core::hash::Hasher::write_u32 (25 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (25 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (25 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (36 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (37 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (37 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (64 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (39 samples, 0.03%)core::hash::Hasher::write_u64 (39 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (122 samples, 0.09%)core::hash::impls::<impl core::hash::Hash for u64>::hash (58 samples, 0.04%)core::hash::Hasher::write_u64 (58 samples, 0.04%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (58 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (58 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (57 samples, 0.04%)core::hash::sip::u8to64_le (23 samples, 0.02%)core::hash::Hasher::write_length_prefix (27 samples, 0.02%)core::hash::Hasher::write_usize (27 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (16 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (246 samples, 0.19%)core::array::<impl core::hash::Hash for [T: N]>::hash (93 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (93 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (66 samples, 0.05%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (62 samples, 0.05%)core::hash::sip::u8to64_le (17 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::check (285 samples, 0.22%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (36 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (36 samples, 0.03%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (24 samples, 0.02%)std::time::SystemTime::now (19 samples, 0.01%)std::sys::pal::unix::time::SystemTime::now (19 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (1,954 samples, 1.49%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (24 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (18 samples, 0.01%)<core::time::Nanoseconds as core::hash::Hash>::hash (20 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (20 samples, 0.02%)core::hash::Hasher::write_u32 (20 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (20 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (20 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (44 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (65 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (45 samples, 0.03%)core::hash::Hasher::write_u64 (45 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (45 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (45 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (105 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u64>::hash (40 samples, 0.03%)core::hash::Hasher::write_u64 (40 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (40 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (40 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (39 samples, 0.03%)core::hash::Hasher::write_length_prefix (34 samples, 0.03%)core::hash::Hasher::write_usize (34 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (34 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (34 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (33 samples, 0.03%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (231 samples, 0.18%)core::array::<impl core::hash::Hash for [T: N]>::hash (100 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (100 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (66 samples, 0.05%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (61 samples, 0.05%)core::hash::sip::u8to64_le (16 samples, 0.01%)_int_free (16 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (270 samples, 0.21%)torrust_tracker::servers::udp::connection_cookie::make (268 samples, 0.20%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (36 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (35 samples, 0.03%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (31 samples, 0.02%)std::time::SystemTime::now (26 samples, 0.02%)std::sys::pal::unix::time::SystemTime::now (26 samples, 0.02%)torrust_tracker::core::ScrapeData::add_file (19 samples, 0.01%)std::collections::hash::map::HashMap<K,V,S>::insert (19 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (19 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (16 samples, 0.01%)hashbrown::raw::RawTable<T,A>::reserve (16 samples, 0.01%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (17 samples, 0.01%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (17 samples, 0.01%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (17 samples, 0.01%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (17 samples, 0.01%)<u8 as core::slice::cmp::SliceOrd>::compare (17 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (53 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (53 samples, 0.04%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (2,336 samples, 1.78%)t..torrust_tracker::servers::udp::handlers::handle_scrape::{{closure}} (101 samples, 0.08%)torrust_tracker::core::Tracker::scrape::{{closure}} (90 samples, 0.07%)torrust_tracker::core::Tracker::get_swarm_metadata (68 samples, 0.05%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (64 samples, 0.05%)alloc::raw_vec::finish_grow (19 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::grow_amortized (21 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (23 samples, 0.02%)alloc::string::String::push_str (23 samples, 0.02%)alloc::vec::Vec<T,A>::extend_from_slice (23 samples, 0.02%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (23 samples, 0.02%)alloc::vec::Vec<T,A>::append_elements (23 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (85 samples, 0.06%)core::fmt::num::imp::fmt_u64 (78 samples, 0.06%)<alloc::string::String as core::fmt::Write>::write_str (15 samples, 0.01%)alloc::string::String::push_str (15 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (15 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (15 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (15 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (37 samples, 0.03%)core::fmt::num::imp::fmt_u64 (36 samples, 0.03%)<T as alloc::string::ToString>::to_string (141 samples, 0.11%)core::option::Option<T>::expect (34 samples, 0.03%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (28 samples, 0.02%)alloc::alloc::dealloc (28 samples, 0.02%)__rdl_dealloc (28 samples, 0.02%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (28 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (55 samples, 0.04%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (55 samples, 0.04%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (55 samples, 0.04%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (55 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::current_memory (20 samples, 0.02%)torrust_tracker::servers::udp::logging::map_action_name (16 samples, 0.01%)binascii::bin2hex (51 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (16 samples, 0.01%)core::fmt::write (25 samples, 0.02%)core::fmt::rt::Argument::fmt (15 samples, 0.01%)core::fmt::Formatter::write_fmt (87 samples, 0.07%)core::str::converts::from_utf8 (43 samples, 0.03%)core::str::validations::run_utf8_validation (37 samples, 0.03%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (161 samples, 0.12%)<T as alloc::string::ToString>::to_string (161 samples, 0.12%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (156 samples, 0.12%)torrust_tracker::servers::udp::logging::log_request (479 samples, 0.36%)[[vdso]] (51 samples, 0.04%)alloc::raw_vec::finish_grow (56 samples, 0.04%)alloc::vec::Vec<T,A>::reserve (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::reserve (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::grow_amortized (64 samples, 0.05%)<alloc::string::String as core::fmt::Write>::write_str (65 samples, 0.05%)alloc::string::String::push_str (65 samples, 0.05%)alloc::vec::Vec<T,A>::extend_from_slice (65 samples, 0.05%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (65 samples, 0.05%)alloc::vec::Vec<T,A>::append_elements (65 samples, 0.05%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (114 samples, 0.09%)core::fmt::num::imp::fmt_u64 (110 samples, 0.08%)<T as alloc::string::ToString>::to_string (132 samples, 0.10%)core::option::Option<T>::expect (20 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (22 samples, 0.02%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (22 samples, 0.02%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (22 samples, 0.02%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (22 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (8,883 samples, 6.77%)torrust_t..torrust_tracker::servers::udp::logging::log_response (238 samples, 0.18%)__GI___lll_lock_wait_private (14 samples, 0.01%)futex_wait (14 samples, 0.01%)__GI___lll_lock_wake_private (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (17 samples, 0.01%)_int_malloc (191 samples, 0.15%)__libc_calloc (238 samples, 0.18%)__memcpy_avx512_unaligned_erms (34 samples, 0.03%)alloc::vec::from_elem (316 samples, 0.24%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (316 samples, 0.24%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (316 samples, 0.24%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (316 samples, 0.24%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (312 samples, 0.24%)alloc::alloc::Global::alloc_impl (312 samples, 0.24%)alloc::alloc::alloc_zeroed (312 samples, 0.24%)__rdl_alloc_zeroed (312 samples, 0.24%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (312 samples, 0.24%)byteorder::ByteOrder::write_i32 (18 samples, 0.01%)<byteorder::BigEndian as byteorder::ByteOrder>::write_u32 (18 samples, 0.01%)core::num::<impl u32>::to_be_bytes (18 samples, 0.01%)core::num::<impl u32>::to_be (18 samples, 0.01%)core::num::<impl u32>::swap_bytes (18 samples, 0.01%)byteorder::io::WriteBytesExt::write_i32 (89 samples, 0.07%)std::io::Write::write_all (71 samples, 0.05%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (71 samples, 0.05%)std::io::cursor::vec_write (71 samples, 0.05%)std::io::cursor::vec_write_unchecked (51 samples, 0.04%)core::ptr::mut_ptr::<impl *mut T>::copy_from (51 samples, 0.04%)core::intrinsics::copy (51 samples, 0.04%)aquatic_udp_protocol::response::Response::write (227 samples, 0.17%)byteorder::io::WriteBytesExt::write_i64 (28 samples, 0.02%)std::io::Write::write_all (21 samples, 0.02%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (21 samples, 0.02%)std::io::cursor::vec_write (21 samples, 0.02%)std::io::cursor::vec_write_unchecked (21 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::copy_from (21 samples, 0.02%)core::intrinsics::copy (21 samples, 0.02%)__GI___lll_lock_wake_private (17 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (14 samples, 0.01%)__GI___lll_lock_wait_private (16 samples, 0.01%)futex_wait (15 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (136 samples, 0.10%)__GI___libc_free (206 samples, 0.16%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (211 samples, 0.16%)alloc::alloc::dealloc (211 samples, 0.16%)__rdl_dealloc (211 samples, 0.16%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (211 samples, 0.16%)core::ptr::drop_in_place<std::io::cursor::Cursor<alloc::vec::Vec<u8>>> (224 samples, 0.17%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (224 samples, 0.17%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (224 samples, 0.17%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (224 samples, 0.17%)std::io::cursor::Cursor<T>::new (56 samples, 0.04%)tokio::io::ready::Ready::intersection (23 samples, 0.02%)tokio::io::ready::Ready::from_interest (23 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (83 samples, 0.06%)[unknown] (32,674 samples, 24.88%)[unknown][unknown] (32,402 samples, 24.68%)[unknown][unknown] (32,272 samples, 24.58%)[unknown][unknown] (32,215 samples, 24.54%)[unknown][unknown] (31,174 samples, 23.74%)[unknown][unknown] (30,794 samples, 23.45%)[unknown][unknown] (30,036 samples, 22.88%)[unknown][unknown] (28,639 samples, 21.81%)[unknown][unknown] (27,908 samples, 21.25%)[unknown][unknown] (26,013 samples, 19.81%)[unknown][unknown] (23,181 samples, 17.65%)[unknown][unknown] (19,559 samples, 14.90%)[unknown][unknown] (18,052 samples, 13.75%)[unknown][unknown] (15,794 samples, 12.03%)[unknown][unknown] (14,740 samples, 11.23%)[unknown][unknown] (12,486 samples, 9.51%)[unknown][unknown] (11,317 samples, 8.62%)[unknown][unknown] (10,725 samples, 8.17%)[unknown][unknown] (10,017 samples, 7.63%)[unknown][unknown] (9,713 samples, 7.40%)[unknown][unknown] (8,432 samples, 6.42%)[unknown][unknown] (8,062 samples, 6.14%)[unknown][unknown] (6,973 samples, 5.31%)[unknow..[unknown] (5,328 samples, 4.06%)[unk..[unknown] (4,352 samples, 3.31%)[un..[unknown] (3,786 samples, 2.88%)[u..[unknown] (3,659 samples, 2.79%)[u..[unknown] (3,276 samples, 2.50%)[u..[unknown] (2,417 samples, 1.84%)[..[unknown] (2,115 samples, 1.61%)[unknown] (1,610 samples, 1.23%)[unknown] (422 samples, 0.32%)[unknown] (84 samples, 0.06%)[unknown] (69 samples, 0.05%)__GI___pthread_disable_asynccancel (67 samples, 0.05%)__libc_sendto (32,896 samples, 25.05%)__libc_sendtotokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (32,981 samples, 25.12%)tokio::net::udp::UdpSocket::send_to_addr..mio::net::udp::UdpSocket::send_to (32,981 samples, 25.12%)mio::net::udp::UdpSocket::send_tomio::io_source::IoSource<T>::do_io (32,981 samples, 25.12%)mio::io_source::IoSource<T>::do_iomio::sys::unix::stateless_io_source::IoSourceState::do_io (32,981 samples, 25.12%)mio::sys::unix::stateless_io_source::IoS..mio::net::udp::UdpSocket::send_to::{{closure}} (32,981 samples, 25.12%)mio::net::udp::UdpSocket::send_to::{{clo..std::net::udp::UdpSocket::send_to (32,981 samples, 25.12%)std::net::udp::UdpSocket::send_tostd::sys_common::net::UdpSocket::send_to (32,981 samples, 25.12%)std::sys_common::net::UdpSocket::send_tostd::sys::pal::unix::cvt (85 samples, 0.06%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (44,349 samples, 33.78%)torrust_tracker::servers::udp::server::Udp::process_req..torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (43,412 samples, 33.06%)torrust_tracker::servers::udp::server::Udp::process_va..torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (34,320 samples, 26.14%)torrust_tracker::servers::udp::server::Udp..torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (33,360 samples, 25.41%)torrust_tracker::servers::udp::server::Ud..tokio::net::udp::UdpSocket::send_to::{{closure}} (33,227 samples, 25.31%)tokio::net::udp::UdpSocket::send_to::{{c..tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (33,142 samples, 25.24%)tokio::net::udp::UdpSocket::send_to_addr..tokio::runtime::io::registration::Registration::async_io::{{closure}} (33,115 samples, 25.22%)tokio::runtime::io::registration::Regist..tokio::runtime::io::registration::Registration::readiness::{{closure}} (28 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (18 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (15 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (14 samples, 0.01%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (15 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (15 samples, 0.01%)core::sync::atomic::atomic_add (15 samples, 0.01%)__GI___lll_lock_wait_private (16 samples, 0.01%)futex_wait (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (135 samples, 0.10%)__GI___libc_free (147 samples, 0.11%)syscall (22 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Core<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (15 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::dealloc (24 samples, 0.02%)core::mem::drop (24 samples, 0.02%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (24 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (24 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::abort::AbortHandle> (262 samples, 0.20%)<tokio::runtime::task::abort::AbortHandle as core::ops::drop::Drop>::drop (262 samples, 0.20%)tokio::runtime::task::raw::RawTask::drop_abort_handle (256 samples, 0.19%)tokio::runtime::task::raw::drop_abort_handle (59 samples, 0.04%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (50 samples, 0.04%)tokio::runtime::task::state::State::ref_dec (50 samples, 0.04%)tokio::runtime::task::raw::RawTask::drop_join_handle_slow (16 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::join::JoinHandle<()>> (47 samples, 0.04%)<tokio::runtime::task::join::JoinHandle<T> as core::ops::drop::Drop>::drop (47 samples, 0.04%)tokio::runtime::task::state::State::drop_join_handle_fast (19 samples, 0.01%)core::sync::atomic::AtomicUsize::compare_exchange_weak (19 samples, 0.01%)core::sync::atomic::atomic_compare_exchange_weak (19 samples, 0.01%)ringbuf::ring_buffer::base::RbBase::is_full (14 samples, 0.01%)<ringbuf::ring_buffer::shared::SharedRb<T,C> as ringbuf::ring_buffer::base::RbBase<T>>::head (14 samples, 0.01%)core::sync::atomic::AtomicUsize::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)ringbuf::consumer::Consumer<T,R>::advance (29 samples, 0.02%)ringbuf::ring_buffer::base::RbRead::advance_head (29 samples, 0.02%)ringbuf::ring_buffer::rb::Rb::pop (50 samples, 0.04%)ringbuf::consumer::Consumer<T,R>::pop (50 samples, 0.04%)ringbuf::producer::Producer<T,R>::advance (23 samples, 0.02%)ringbuf::ring_buffer::base::RbWrite::advance_tail (23 samples, 0.02%)core::num::nonzero::<impl core::ops::arith::Rem<core::num::nonzero::NonZero<usize>> for usize>::rem (19 samples, 0.01%)ringbuf::ring_buffer::rb::Rb::push_overwrite (107 samples, 0.08%)ringbuf::ring_buffer::rb::Rb::push (43 samples, 0.03%)ringbuf::producer::Producer<T,R>::push (43 samples, 0.03%)tokio::runtime::task::abort::AbortHandle::is_finished (84 samples, 0.06%)tokio::runtime::task::state::Snapshot::is_complete (84 samples, 0.06%)tokio::runtime::task::join::JoinHandle<T>::abort_handle (17 samples, 0.01%)tokio::runtime::task::raw::RawTask::ref_inc (17 samples, 0.01%)tokio::runtime::task::state::State::ref_inc (17 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (14 samples, 0.01%)core::sync::atomic::atomic_add (14 samples, 0.01%)__GI___lll_lock_wake_private (22 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)malloc_consolidate (95 samples, 0.07%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (76 samples, 0.06%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (31 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (26 samples, 0.02%)_int_malloc (282 samples, 0.21%)__GI___libc_malloc (323 samples, 0.25%)alloc::vec::Vec<T>::with_capacity (326 samples, 0.25%)alloc::vec::Vec<T,A>::with_capacity_in (326 samples, 0.25%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (324 samples, 0.25%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (324 samples, 0.25%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (324 samples, 0.25%)alloc::alloc::Global::alloc_impl (324 samples, 0.25%)alloc::alloc::alloc (324 samples, 0.25%)__rdl_alloc (324 samples, 0.25%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (324 samples, 0.25%)tokio::io::ready::Ready::intersection (24 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (199 samples, 0.15%)tokio::util::bit::Pack::unpack (16 samples, 0.01%)tokio::util::bit::unpack (16 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (19 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (17 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (16 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (222 samples, 0.17%)tokio::net::udp::UdpSocket::ready::{{closure}} (222 samples, 0.17%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (50 samples, 0.04%)std::io::error::repr_bitpacked::Repr::data (14 samples, 0.01%)std::io::error::repr_bitpacked::decode_repr (14 samples, 0.01%)std::io::error::Error::kind (16 samples, 0.01%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (14 samples, 0.01%)[unknown] (8,756 samples, 6.67%)[unknown][unknown] (8,685 samples, 6.61%)[unknown][unknown] (8,574 samples, 6.53%)[unknown][unknown] (8,415 samples, 6.41%)[unknown][unknown] (7,686 samples, 5.85%)[unknow..[unknown] (7,239 samples, 5.51%)[unknow..[unknown] (6,566 samples, 5.00%)[unkno..[unknown] (5,304 samples, 4.04%)[unk..[unknown] (4,008 samples, 3.05%)[un..[unknown] (3,571 samples, 2.72%)[u..[unknown] (2,375 samples, 1.81%)[..[unknown] (1,844 samples, 1.40%)[unknown] (1,030 samples, 0.78%)[unknown] (344 samples, 0.26%)[unknown] (113 samples, 0.09%)__libc_recvfrom (8,903 samples, 6.78%)__libc_re..__GI___pthread_disable_asynccancel (22 samples, 0.02%)std::sys::pal::unix::cvt (20 samples, 0.02%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (9,005 samples, 6.86%)tokio::ne..mio::net::udp::UdpSocket::recv_from (8,964 samples, 6.83%)mio::net:..mio::io_source::IoSource<T>::do_io (8,964 samples, 6.83%)mio::io_s..mio::sys::unix::stateless_io_source::IoSourceState::do_io (8,964 samples, 6.83%)mio::sys:..mio::net::udp::UdpSocket::recv_from::{{closure}} (8,964 samples, 6.83%)mio::net:..std::net::udp::UdpSocket::recv_from (8,964 samples, 6.83%)std::net:..std::sys_common::net::UdpSocket::recv_from (8,964 samples, 6.83%)std::sys_..std::sys::pal::unix::net::Socket::recv_from (8,964 samples, 6.83%)std::sys:..std::sys::pal::unix::net::Socket::recv_from_with_flags (8,964 samples, 6.83%)std::sys:..std::sys_common::net::sockaddr_to_addr (23 samples, 0.02%)tokio::runtime::io::registration::Registration::clear_readiness (18 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::clear_readiness (18 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (32 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (9,967 samples, 7.59%)torrust_tr..tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (9,291 samples, 7.08%)tokio::ne..tokio::runtime::io::registration::Registration::async_io::{{closure}} (9,287 samples, 7.07%)tokio::ru..tokio::runtime::io::registration::Registration::readiness::{{closure}} (45 samples, 0.03%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (41 samples, 0.03%)__memcpy_avx512_unaligned_erms (424 samples, 0.32%)__memcpy_avx512_unaligned_erms (493 samples, 0.38%)__memcpy_avx512_unaligned_erms (298 samples, 0.23%)syscall (1,105 samples, 0.84%)[unknown] (1,095 samples, 0.83%)[unknown] (1,091 samples, 0.83%)[unknown] (1,049 samples, 0.80%)[unknown] (998 samples, 0.76%)[unknown] (907 samples, 0.69%)[unknown] (710 samples, 0.54%)[unknown] (635 samples, 0.48%)[unknown] (538 samples, 0.41%)[unknown] (358 samples, 0.27%)[unknown] (256 samples, 0.19%)[unknown] (153 samples, 0.12%)[unknown] (96 samples, 0.07%)[unknown] (81 samples, 0.06%)tokio::runtime::context::with_scheduler (36 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (31 samples, 0.02%)tokio::runtime::context::with_scheduler::{{closure}} (27 samples, 0.02%)tokio::runtime::context::scoped::Scoped<T>::with (27 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (25 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (15 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (340 samples, 0.26%)core::sync::atomic::atomic_add (340 samples, 0.26%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (354 samples, 0.27%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (367 samples, 0.28%)[unknown] (95 samples, 0.07%)[unknown] (93 samples, 0.07%)[unknown] (92 samples, 0.07%)[unknown] (90 samples, 0.07%)[unknown] (82 samples, 0.06%)[unknown] (73 samples, 0.06%)[unknown] (63 samples, 0.05%)[unknown] (44 samples, 0.03%)[unknown] (40 samples, 0.03%)[unknown] (35 samples, 0.03%)[unknown] (30 samples, 0.02%)[unknown] (22 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (17 samples, 0.01%)tokio::runtime::driver::Handle::unpark (99 samples, 0.08%)tokio::runtime::driver::IoHandle::unpark (99 samples, 0.08%)tokio::runtime::io::driver::Handle::unpark (99 samples, 0.08%)mio::waker::Waker::wake (99 samples, 0.08%)mio::sys::unix::waker::fdbased::Waker::wake (99 samples, 0.08%)mio::sys::unix::waker::eventfd::WakerInternal::wake (99 samples, 0.08%)<&std::fs::File as std::io::Write>::write (99 samples, 0.08%)std::sys::pal::unix::fs::File::write (99 samples, 0.08%)std::sys::pal::unix::fd::FileDesc::write (99 samples, 0.08%)__GI___libc_write (99 samples, 0.08%)__GI___libc_write (99 samples, 0.08%)tokio::runtime::context::with_scheduler (1,615 samples, 1.23%)std::thread::local::LocalKey<T>::try_with (1,613 samples, 1.23%)tokio::runtime::context::with_scheduler::{{closure}} (1,612 samples, 1.23%)tokio::runtime::context::scoped::Scoped<T>::with (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (1,609 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (1,609 samples, 1.23%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (101 samples, 0.08%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (101 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_option_task_without_yield (1,647 samples, 1.25%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task (1,646 samples, 1.25%)tokio::runtime::scheduler::multi_thread::worker::with_current (1,646 samples, 1.25%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (23 samples, 0.02%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (18 samples, 0.01%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (104 samples, 0.08%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (60 samples, 0.05%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (57 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (49 samples, 0.04%)core::sync::atomic::AtomicU32::compare_exchange (38 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (38 samples, 0.03%)__memcpy_avx512_unaligned_erms (162 samples, 0.12%)__memcpy_avx512_unaligned_erms (34 samples, 0.03%)__GI___lll_lock_wake_private (127 samples, 0.10%)[unknown] (125 samples, 0.10%)[unknown] (124 samples, 0.09%)[unknown] (119 samples, 0.09%)[unknown] (110 samples, 0.08%)[unknown] (106 samples, 0.08%)[unknown] (87 samples, 0.07%)[unknown] (82 samples, 0.06%)[unknown] (51 samples, 0.04%)[unknown] (27 samples, 0.02%)[unknown] (19 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (77 samples, 0.06%)[unknown] (1,207 samples, 0.92%)[unknown] (1,146 samples, 0.87%)[unknown] (1,126 samples, 0.86%)[unknown] (1,091 samples, 0.83%)[unknown] (1,046 samples, 0.80%)[unknown] (962 samples, 0.73%)[unknown] (914 samples, 0.70%)[unknown] (848 samples, 0.65%)[unknown] (774 samples, 0.59%)[unknown] (580 samples, 0.44%)[unknown] (456 samples, 0.35%)[unknown] (305 samples, 0.23%)[unknown] (85 samples, 0.06%)__GI_mprotect (2,474 samples, 1.88%)_..[unknown] (2,457 samples, 1.87%)[..[unknown] (2,440 samples, 1.86%)[..[unknown] (2,436 samples, 1.86%)[..[unknown] (2,435 samples, 1.85%)[..[unknown] (2,360 samples, 1.80%)[..[unknown] (2,203 samples, 1.68%)[unknown] (1,995 samples, 1.52%)[unknown] (1,709 samples, 1.30%)[unknown] (1,524 samples, 1.16%)[unknown] (1,193 samples, 0.91%)[unknown] (865 samples, 0.66%)[unknown] (539 samples, 0.41%)[unknown] (259 samples, 0.20%)[unknown] (80 samples, 0.06%)[unknown] (29 samples, 0.02%)sysmalloc (3,786 samples, 2.88%)sy..grow_heap (2,509 samples, 1.91%)g.._int_malloc (4,038 samples, 3.08%)_in..unlink_chunk (31 samples, 0.02%)alloc::alloc::exchange_malloc (4,335 samples, 3.30%)all..<alloc::alloc::Global as core::alloc::Allocator>::allocate (4,329 samples, 3.30%)<al..alloc::alloc::Global::alloc_impl (4,329 samples, 3.30%)all..alloc::alloc::alloc (4,329 samples, 3.30%)all..__rdl_alloc (4,329 samples, 3.30%)__r..std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (4,329 samples, 3.30%)std..std::sys::pal::unix::alloc::aligned_malloc (4,329 samples, 3.30%)std..__posix_memalign (4,297 samples, 3.27%)__p..__posix_memalign (4,297 samples, 3.27%)__p.._mid_memalign (4,297 samples, 3.27%)_mi.._int_memalign (4,149 samples, 3.16%)_in..sysmalloc (18 samples, 0.01%)core::option::Option<T>::map (6,666 samples, 5.08%)core::..tokio::task::spawn::spawn_inner::{{closure}} (6,665 samples, 5.08%)tokio:..tokio::runtime::scheduler::Handle::spawn (6,665 samples, 5.08%)tokio:..tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (6,664 samples, 5.08%)tokio:..tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (6,661 samples, 5.07%)tokio:..tokio::runtime::task::list::OwnedTasks<S>::bind (4,692 samples, 3.57%)toki..tokio::runtime::task::new_task (4,579 samples, 3.49%)tok..tokio::runtime::task::raw::RawTask::new (4,579 samples, 3.49%)tok..tokio::runtime::task::core::Cell<T,S>::new (4,579 samples, 3.49%)tok..alloc::boxed::Box<T>::new (4,389 samples, 3.34%)all..tokio::runtime::context::current::with_current (7,636 samples, 5.82%)tokio::..std::thread::local::LocalKey<T>::try_with (7,635 samples, 5.81%)std::th..tokio::runtime::context::current::with_current::{{closure}} (7,188 samples, 5.47%)tokio::..tokio::task::spawn::spawn (7,670 samples, 5.84%)tokio::..tokio::task::spawn::spawn_inner (7,670 samples, 5.84%)tokio::..tokio::runtime::task::id::Id::next (24 samples, 0.02%)core::sync::atomic::AtomicU64::fetch_add (24 samples, 0.02%)core::sync::atomic::atomic_add (24 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (62,691 samples, 47.75%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (62,691 samples, 47.75%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (18,228 samples, 13.88%)torrust_tracker::serv..torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (18,226 samples, 13.88%)torrust_tracker::serv..torrust_tracker::servers::udp::server::Udp::spawn_request_processor (7,679 samples, 5.85%)torrust..__memcpy_avx512_unaligned_erms (38 samples, 0.03%)__memcpy_avx512_unaligned_erms (407 samples, 0.31%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (411 samples, 0.31%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (411 samples, 0.31%)tokio::runtime::task::core::Core<T,S>::poll (63,150 samples, 48.10%)tokio::runtime::task::core::Core<T,S>::polltokio::runtime::task::core::Core<T,S>::drop_future_or_output (459 samples, 0.35%)tokio::runtime::task::core::Core<T,S>::set_stage (459 samples, 0.35%)__memcpy_avx512_unaligned_erms (16 samples, 0.01%)__memcpy_avx512_unaligned_erms (398 samples, 0.30%)__memcpy_avx512_unaligned_erms (325 samples, 0.25%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (330 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (330 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::set_stage (731 samples, 0.56%)tokio::runtime::task::harness::poll_future (63,908 samples, 48.67%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (63,908 samples, 48.67%)std::panic::catch_unwindstd::panicking::try (63,908 samples, 48.67%)std::panicking::trystd::panicking::try::do_call (63,908 samples, 48.67%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (63,908 samples, 48.67%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()..tokio::runtime::task::harness::poll_future::{{closure}} (63,908 samples, 48.67%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::store_output (758 samples, 0.58%)tokio::runtime::coop::budget (65,027 samples, 49.53%)tokio::runtime::coop::budgettokio::runtime::coop::with_budget (65,027 samples, 49.53%)tokio::runtime::coop::with_budgettokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (65,009 samples, 49.51%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}}tokio::runtime::task::LocalNotified<S>::run (65,003 samples, 49.51%)tokio::runtime::task::LocalNotified<S>::runtokio::runtime::task::raw::RawTask::poll (65,003 samples, 49.51%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (64,538 samples, 49.15%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (64,493 samples, 49.12%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (63,919 samples, 48.68%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (93 samples, 0.07%)syscall (2,486 samples, 1.89%)s..[unknown] (2,424 samples, 1.85%)[..[unknown] (2,416 samples, 1.84%)[..[unknown] (2,130 samples, 1.62%)[unknown] (2,013 samples, 1.53%)[unknown] (1,951 samples, 1.49%)[unknown] (1,589 samples, 1.21%)[unknown] (1,415 samples, 1.08%)[unknown] (1,217 samples, 0.93%)[unknown] (820 samples, 0.62%)[unknown] (564 samples, 0.43%)[unknown] (360 samples, 0.27%)[unknown] (244 samples, 0.19%)[unknown] (194 samples, 0.15%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (339 samples, 0.26%)core::sync::atomic::AtomicUsize::fetch_add (337 samples, 0.26%)core::sync::atomic::atomic_add (337 samples, 0.26%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (364 samples, 0.28%)[unknown] (154 samples, 0.12%)[unknown] (152 samples, 0.12%)[unknown] (143 samples, 0.11%)[unknown] (139 samples, 0.11%)[unknown] (131 samples, 0.10%)[unknown] (123 samples, 0.09%)[unknown] (110 samples, 0.08%)[unknown] (80 samples, 0.06%)[unknown] (74 samples, 0.06%)[unknown] (65 samples, 0.05%)[unknown] (64 samples, 0.05%)[unknown] (47 samples, 0.04%)[unknown] (44 samples, 0.03%)[unknown] (43 samples, 0.03%)[unknown] (40 samples, 0.03%)[unknown] (26 samples, 0.02%)[unknown] (20 samples, 0.02%)__GI___libc_write (158 samples, 0.12%)__GI___libc_write (158 samples, 0.12%)mio::sys::unix::waker::eventfd::WakerInternal::wake (159 samples, 0.12%)<&std::fs::File as std::io::Write>::write (159 samples, 0.12%)std::sys::pal::unix::fs::File::write (159 samples, 0.12%)std::sys::pal::unix::fd::FileDesc::write (159 samples, 0.12%)tokio::runtime::driver::Handle::unpark (168 samples, 0.13%)tokio::runtime::driver::IoHandle::unpark (168 samples, 0.13%)tokio::runtime::io::driver::Handle::unpark (168 samples, 0.13%)mio::waker::Waker::wake (165 samples, 0.13%)mio::sys::unix::waker::fdbased::Waker::wake (165 samples, 0.13%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (68,159 samples, 51.91%)tokio::runtime::scheduler::multi_thread::worker::Context::run_tasktokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (3,024 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (3,023 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (3,022 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (171 samples, 0.13%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (171 samples, 0.13%)core::option::Option<T>::or_else (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::tune_global_queue_interval (53 samples, 0.04%)tokio::runtime::scheduler::multi_thread::stats::Stats::tuned_global_queue_interval (53 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (107 samples, 0.08%)__GI___libc_free (17 samples, 0.01%)_int_free (17 samples, 0.01%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Dying,K,V>::deallocating_end (18 samples, 0.01%)alloc::collections::btree::navigate::<impl alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>>::deallocating_end (18 samples, 0.01%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::LeafOrInternal>::deallocate_and_ascend (18 samples, 0.01%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (18 samples, 0.01%)alloc::alloc::dealloc (18 samples, 0.01%)__rdl_dealloc (18 samples, 0.01%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (18 samples, 0.01%)alloc::collections::btree::map::IntoIter<K,V,A>::dying_next (19 samples, 0.01%)tokio::runtime::task::Task<S>::shutdown (26 samples, 0.02%)tokio::runtime::task::raw::RawTask::shutdown (26 samples, 0.02%)tokio::runtime::task::raw::shutdown (26 samples, 0.02%)tokio::runtime::task::harness::Harness<T,S>::shutdown (26 samples, 0.02%)tokio::runtime::task::harness::cancel_task (26 samples, 0.02%)std::panic::catch_unwind (26 samples, 0.02%)std::panicking::try (26 samples, 0.02%)std::panicking::try::do_call (26 samples, 0.02%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (26 samples, 0.02%)core::ops::function::FnOnce::call_once (26 samples, 0.02%)tokio::runtime::task::harness::cancel_task::{{closure}} (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (26 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (26 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::core::Tracker> (26 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)core::ptr::drop_in_place<std::sync::rwlock::RwLock<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)core::mem::drop (26 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,NodeType>,alloc::collections::btree::node::marker::KV>::drop_key_val (24 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::assume_init_drop (24 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (24 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (21 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>> (20 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<torrust_tracker_torrent_repository::entry::Torrent>> (20 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker_torrent_repository::entry::Torrent> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::peer::Id,alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (20 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)core::mem::drop (20 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker_primitives::peer::Id,alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (20 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::pre_shutdown (33 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::close_and_shutdown_all (33 samples, 0.03%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (114 samples, 0.09%)alloc::sync::Arc<T,A>::inner (114 samples, 0.09%)core::ptr::non_null::NonNull<T>::as_ref (114 samples, 0.09%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (108 samples, 0.08%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (108 samples, 0.08%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (106 samples, 0.08%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (49 samples, 0.04%)alloc::sync::Arc<T,A>::inner (49 samples, 0.04%)core::ptr::non_null::NonNull<T>::as_ref (49 samples, 0.04%)core::num::<impl u32>::wrapping_sub (132 samples, 0.10%)core::sync::atomic::AtomicU64::load (40 samples, 0.03%)core::sync::atomic::atomic_load (40 samples, 0.03%)tokio::loom::std::atomic_u32::AtomicU32::unsync_load (48 samples, 0.04%)core::sync::atomic::AtomicU32::load (48 samples, 0.04%)core::sync::atomic::atomic_load (48 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (65 samples, 0.05%)alloc::sync::Arc<T,A>::inner (65 samples, 0.05%)core::ptr::non_null::NonNull<T>::as_ref (65 samples, 0.05%)core::num::<impl u32>::wrapping_sub (50 samples, 0.04%)core::sync::atomic::AtomicU32::load (55 samples, 0.04%)core::sync::atomic::atomic_load (55 samples, 0.04%)core::sync::atomic::AtomicU64::load (80 samples, 0.06%)core::sync::atomic::atomic_load (80 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::pack (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (666 samples, 0.51%)tokio::runtime::scheduler::multi_thread::queue::unpack (147 samples, 0.11%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (1,036 samples, 0.79%)tokio::runtime::scheduler::multi_thread::queue::unpack (46 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_searching (49 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_searching (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (2,414 samples, 1.84%)t..tokio::util::rand::FastRand::fastrand_n (24 samples, 0.02%)tokio::util::rand::FastRand::fastrand (24 samples, 0.02%)std::sys_common::backtrace::__rust_begin_short_backtrace (98,136 samples, 74.74%)std::sys_common::backtrace::__rust_begin_short_backtracetokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}} (98,136 samples, 74.74%)tokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}}tokio::runtime::blocking::pool::Inner::run (98,136 samples, 74.74%)tokio::runtime::blocking::pool::Inner::runtokio::runtime::blocking::pool::Task::run (98,042 samples, 74.67%)tokio::runtime::blocking::pool::Task::runtokio::runtime::task::UnownedTask<S>::run (98,042 samples, 74.67%)tokio::runtime::task::UnownedTask<S>::runtokio::runtime::task::raw::RawTask::poll (98,042 samples, 74.67%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (98,042 samples, 74.67%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (98,042 samples, 74.67%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (98,042 samples, 74.67%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::task::harness::poll_future (98,042 samples, 74.67%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (98,042 samples, 74.67%)std::panic::catch_unwindstd::panicking::try (98,042 samples, 74.67%)std::panicking::trystd::panicking::try::do_call (98,042 samples, 74.67%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (98,042 samples, 74.67%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncetokio::runtime::task::harness::poll_future::{{closure}} (98,042 samples, 74.67%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::poll (98,042 samples, 74.67%)tokio::runtime::task::core::Core<T,S>::polltokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (98,042 samples, 74.67%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (98,042 samples, 74.67%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (98,042 samples, 74.67%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::polltokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}}tokio::runtime::scheduler::multi_thread::worker::run (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::runtokio::runtime::context::runtime::enter_runtime (98,042 samples, 74.67%)tokio::runtime::context::runtime::enter_runtimetokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}tokio::runtime::context::set_scheduler (98,042 samples, 74.67%)tokio::runtime::context::set_schedulerstd::thread::local::LocalKey<T>::with (98,042 samples, 74.67%)std::thread::local::LocalKey<T>::withstd::thread::local::LocalKey<T>::try_with (98,042 samples, 74.67%)std::thread::local::LocalKey<T>::try_withtokio::runtime::context::set_scheduler::{{closure}} (98,042 samples, 74.67%)tokio::runtime::context::set_scheduler::{{closure}}tokio::runtime::context::scoped::Scoped<T>::set (98,042 samples, 74.67%)tokio::runtime::context::scoped::Scoped<T>::settokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}}tokio::runtime::scheduler::multi_thread::worker::Context::run (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::Context::runstd::panic::catch_unwind (98,137 samples, 74.74%)std::panic::catch_unwindstd::panicking::try (98,137 samples, 74.74%)std::panicking::trystd::panicking::try::do_call (98,137 samples, 74.74%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (98,137 samples, 74.74%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncestd::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}} (98,137 samples, 74.74%)std::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}}<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (98,139 samples, 74.74%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (98,139 samples, 74.74%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_oncecore::ops::function::FnOnce::call_once{{vtable.shim}} (98,139 samples, 74.74%)core::ops::function::FnOnce::call_once{{vtable.shim}}std::thread::Builder::spawn_unchecked_::{{closure}} (98,139 samples, 74.74%)std::thread::Builder::spawn_unchecked_::{{closure}}clone3 (98,205 samples, 74.79%)clone3start_thread (98,205 samples, 74.79%)start_threadstd::sys::pal::unix::thread::Thread::new::thread_start (98,158 samples, 74.76%)std::sys::pal::unix::thread::Thread::new::thread_startcore::ptr::drop_in_place<std::sys::pal::unix::stack_overflow::Handler> (19 samples, 0.01%)<std::sys::pal::unix::stack_overflow::Handler as core::ops::drop::Drop>::drop (19 samples, 0.01%)std::sys::pal::unix::stack_overflow::imp::drop_handler (19 samples, 0.01%)__GI_munmap (19 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (17 samples, 0.01%)[unknown] (16 samples, 0.01%)core::fmt::Formatter::pad_integral (112 samples, 0.09%)core::fmt::Formatter::pad_integral::write_prefix (59 samples, 0.04%)core::fmt::Formatter::pad_integral (16 samples, 0.01%)core::fmt::write (20 samples, 0.02%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (19 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (51 samples, 0.04%)rand_chacha::guts::round (18 samples, 0.01%)rand_chacha::guts::refill_wide::impl_avx2 (26 samples, 0.02%)rand_chacha::guts::refill_wide::fn_impl (26 samples, 0.02%)rand_chacha::guts::refill_wide_impl (26 samples, 0.02%)rand_chacha::guts::refill_wide (14 samples, 0.01%)std_detect::detect::arch::x86::__is_feature_detected::avx2 (14 samples, 0.01%)std_detect::detect::check_for (14 samples, 0.01%)std_detect::detect::cache::test (14 samples, 0.01%)std_detect::detect::cache::Cache::test (14 samples, 0.01%)core::sync::atomic::AtomicUsize::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)core::cell::RefCell<T>::borrow_mut (81 samples, 0.06%)core::cell::RefCell<T>::try_borrow_mut (81 samples, 0.06%)core::cell::BorrowRefMut::new (81 samples, 0.06%)std::sys::pal::unix::time::Timespec::now (164 samples, 0.12%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (106 samples, 0.08%)tokio::runtime::coop::budget (105 samples, 0.08%)tokio::runtime::coop::with_budget (105 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (96 samples, 0.07%)std::sys::pal::unix::time::Timespec::sub_timespec (35 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::lock_contended (15 samples, 0.01%)syscall (90 samples, 0.07%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (21 samples, 0.02%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run (61 samples, 0.05%)tokio::runtime::context::runtime::enter_runtime (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (61 samples, 0.05%)tokio::runtime::context::set_scheduler (61 samples, 0.05%)std::thread::local::LocalKey<T>::with (61 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (61 samples, 0.05%)tokio::runtime::context::set_scheduler::{{closure}} (61 samples, 0.05%)tokio::runtime::context::scoped::Scoped<T>::set (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Context::run (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (19 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (17 samples, 0.01%)tokio::runtime::context::CONTEXT::__getit (14 samples, 0.01%)core::cell::Cell<T>::get (14 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (22 samples, 0.02%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (22 samples, 0.02%)tokio::runtime::context::set_current_task_id (22 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (22 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (112 samples, 0.09%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (111 samples, 0.08%)tokio::runtime::task::harness::poll_future (125 samples, 0.10%)std::panic::catch_unwind (125 samples, 0.10%)std::panicking::try (125 samples, 0.10%)std::panicking::try::do_call (125 samples, 0.10%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (125 samples, 0.10%)tokio::runtime::task::harness::poll_future::{{closure}} (125 samples, 0.10%)tokio::runtime::task::core::Core<T,S>::poll (125 samples, 0.10%)tokio::runtime::task::raw::poll (157 samples, 0.12%)tokio::runtime::task::harness::Harness<T,S>::poll (135 samples, 0.10%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (135 samples, 0.10%)tokio::runtime::time::Driver::park_internal (15 samples, 0.01%)torrust_tracker::bootstrap::logging::INIT (17 samples, 0.01%)__memcpy_avx512_unaligned_erms (397 samples, 0.30%)_int_free (24 samples, 0.02%)_int_malloc (132 samples, 0.10%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE::META (570 samples, 0.43%)__GI___lll_lock_wait_private (22 samples, 0.02%)futex_wait (14 samples, 0.01%)__memcpy_avx512_unaligned_erms (299 samples, 0.23%)_int_free (16 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE (361 samples, 0.27%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (41 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (23 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (53 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (14 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (63 samples, 0.05%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (21 samples, 0.02%)__GI___libc_malloc (18 samples, 0.01%)alloc::vec::Vec<T>::with_capacity (116 samples, 0.09%)alloc::vec::Vec<T,A>::with_capacity_in (116 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (116 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (116 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (116 samples, 0.09%)alloc::alloc::Global::alloc_impl (116 samples, 0.09%)alloc::alloc::alloc (116 samples, 0.09%)__rdl_alloc (116 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (116 samples, 0.09%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (53 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (53 samples, 0.04%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (53 samples, 0.04%)_int_malloc (21 samples, 0.02%)[unknown] (36 samples, 0.03%)[unknown] (16 samples, 0.01%)core::mem::zeroed (27 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::zeroed (27 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::write_bytes (27 samples, 0.02%)core::intrinsics::write_bytes (27 samples, 0.02%)[unknown] (27 samples, 0.02%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (64 samples, 0.05%)mio::net::udp::UdpSocket::recv_from (49 samples, 0.04%)mio::io_source::IoSource<T>::do_io (49 samples, 0.04%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (49 samples, 0.04%)mio::net::udp::UdpSocket::recv_from::{{closure}} (49 samples, 0.04%)std::net::udp::UdpSocket::recv_from (49 samples, 0.04%)std::sys_common::net::UdpSocket::recv_from (49 samples, 0.04%)std::sys::pal::unix::net::Socket::recv_from (49 samples, 0.04%)std::sys::pal::unix::net::Socket::recv_from_with_flags (49 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (271 samples, 0.21%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (143 samples, 0.11%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (141 samples, 0.11%)tokio::runtime::io::registration::Registration::clear_readiness (15 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::clear_readiness (15 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (15 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (359 samples, 0.27%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (346 samples, 0.26%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (39 samples, 0.03%)tokio::task::spawn::spawn (39 samples, 0.03%)tokio::task::spawn::spawn_inner (39 samples, 0.03%)tokio::runtime::context::current::with_current (39 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (39 samples, 0.03%)tokio::runtime::context::current::with_current::{{closure}} (39 samples, 0.03%)core::option::Option<T>::map (39 samples, 0.03%)tokio::task::spawn::spawn_inner::{{closure}} (39 samples, 0.03%)tokio::runtime::scheduler::Handle::spawn (39 samples, 0.03%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (39 samples, 0.03%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (39 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::bind (34 samples, 0.03%)all (131,301 samples, 100%)tokio-runtime-w (131,061 samples, 99.82%)tokio-runtime-w \ No newline at end of file diff --git a/docs/profiling.md b/docs/profiling.md index 7c28367ce..26e5b786e 100644 --- a/docs/profiling.md +++ b/docs/profiling.md @@ -2,12 +2,85 @@ ## Using flamegraph +### Requirements + +You need to install some dependencies. For Ubuntu you can run: + ```console -TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" cargo flamegraph --bin=profiling -- 60 +sudo apt-get install clang lld +``` + +You also need to uncomment these lines in the cargo [config.toml](./../.cargo/config.toml) file. + +```toml +[target.x86_64-unknown-linux-gnu] +linker = "/usr/bin/clang" +rustflags = ["-Clink-arg=-fuse-ld=lld", "-Clink-arg=-Wl,--no-rosegment"] +``` + +Follow the [flamegraph](https://github.com/flamegraph-rs/flamegraph) instructions for installation. + +Apart from running the tracker you will need to run some request if you want to profile services while they are processing requests. + +You can use the aquatic [UDP load test](https://github.com/greatest-ape/aquatic/tree/master/crates/udp_load_test) script. + +### Generate flamegraph + +To generate the graph you will need to: + +1. Build the tracker for profiling. +2. Run the aquatic UDP load test. +3. Run the tracker with flamegraph and profiling configuration. + +```console +cargo build --profile=release-debug --bin=profiling +./target/release/aquatic_udp_load_test -c "load-test-config.toml" +sudo TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" /home/USER/.cargo/bin/flamegraph -- ./target/release-debug/profiling 60 +``` + +__NOTICE__: You need to install the `aquatic_udp_load_test` program. + +The output should be like the following: + +```output +Loading configuration file: `./share/default/config/tracker.udp.benchmarking.toml` ... +Torrust successfully shutdown. +[ perf record: Woken up 23377 times to write data ] +Warning: +Processed 533730 events and lost 3 chunks! + +Check IO/CPU overload! + +[ perf record: Captured and wrote 5899.806 MB perf.data (373239 samples) ] +writing flamegraph to "flamegraph.svg" ``` ![flamegraph](./media/flamegraph.svg) +__NOTICE__: You need to provide the absolute path for the installed `flamegraph` app if you use sudo. Replace `/home/USER/.cargo/bin/flamegraph` with the location of your installed `flamegraph` app. You can run it without sudo but you can get a warning message like the following: + +```output +WARNING: Kernel address maps (/proc/{kallsyms,modules}) are restricted, +check /proc/sys/kernel/kptr_restrict and /proc/sys/kernel/perf_event_paranoid. + +Samples in kernel functions may not be resolved if a suitable vmlinux +file is not found in the buildid cache or in the vmlinux path. + +Samples in kernel modules won't be resolved at all. + +If some relocation was applied (e.g. kexec) symbols may be misresolved +even with a suitable vmlinux or kallsyms file. + +Couldn't record kernel reference relocation symbol +Symbol resolution may be skewed if relocation was used (e.g. kexec). +Check /proc/kallsyms permission or run as root. +Loading configuration file: `./share/default/config/tracker.udp.benchmarking.toml` ... +``` + +And some bars in the graph will have the `unknown` label. + +![flamegraph generated without sudo](./media/flamegraph_generated_withput_sudo.svg) + ## Using valgrind and kcachegrind You need to: diff --git a/flamegraph_generated_withput_sudo.svg b/flamegraph_generated_withput_sudo.svg new file mode 100644 index 000000000..84c00ffe3 --- /dev/null +++ b/flamegraph_generated_withput_sudo.svg @@ -0,0 +1,491 @@ +Flame Graph Reset ZoomSearch [unknown] (188 samples, 0.14%)[unknown] (187 samples, 0.14%)[unknown] (186 samples, 0.14%)[unknown] (178 samples, 0.14%)[unknown] (172 samples, 0.13%)[unknown] (158 samples, 0.12%)[unknown] (158 samples, 0.12%)[unknown] (125 samples, 0.10%)[unknown] (102 samples, 0.08%)[unknown] (93 samples, 0.07%)[unknown] (92 samples, 0.07%)[unknown] (41 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (29 samples, 0.02%)[unknown] (25 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (15 samples, 0.01%)__GI___mmap64 (18 samples, 0.01%)__GI___mmap64 (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (17 samples, 0.01%)profiling (214 samples, 0.16%)clone3 (22 samples, 0.02%)start_thread (22 samples, 0.02%)std::sys::pal::unix::thread::Thread::new::thread_start (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::Handler::new (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::imp::make_handler (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::imp::get_stack (19 samples, 0.01%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (30 samples, 0.02%)[[vdso]] (93 samples, 0.07%)<torrust_tracker::shared::crypto::ephemeral_instance_keys::RANDOM_SEED as core::ops::deref::Deref>::deref::__stability::LAZY (143 samples, 0.11%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (31 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<BorrowType,K,V>::init_front (21 samples, 0.02%)[[vdso]] (91 samples, 0.07%)__GI___clock_gettime (14 samples, 0.01%)_int_malloc (53 samples, 0.04%)epoll_wait (254 samples, 0.19%)tokio::runtime::context::with_scheduler (28 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.01%)tokio::runtime::context::with_scheduler::{{closure}} (14 samples, 0.01%)core::option::Option<T>::map (17 samples, 0.01%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (17 samples, 0.01%)mio::poll::Poll::poll (27 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select (27 samples, 0.02%)tokio::runtime::io::driver::Driver::turn (54 samples, 0.04%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (26 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (17 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (71 samples, 0.05%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (65 samples, 0.05%)core::sync::atomic::AtomicUsize::fetch_add (65 samples, 0.05%)core::sync::atomic::atomic_add (65 samples, 0.05%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (31 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark_condvar (18 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (49 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (33 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (93 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Parker::park (75 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Inner::park (75 samples, 0.06%)core::cell::RefCell<T>::borrow_mut (18 samples, 0.01%)core::cell::RefCell<T>::try_borrow_mut (18 samples, 0.01%)core::cell::BorrowRefMut::new (18 samples, 0.01%)tokio::runtime::coop::budget (26 samples, 0.02%)tokio::runtime::coop::with_budget (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (96 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (27 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (18 samples, 0.01%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (35 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (14 samples, 0.01%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (90 samples, 0.07%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (90 samples, 0.07%)core::slice::<impl [T]>::contains (220 samples, 0.17%)<T as core::slice::cmp::SliceContains>::slice_contains (220 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (220 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (54 samples, 0.04%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (54 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (240 samples, 0.18%)tokio::runtime::scheduler::multi_thread::idle::Idle::unpark_worker_by_id (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (265 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Context::park (284 samples, 0.22%)core::option::Option<T>::or_else (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (40 samples, 0.03%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (17 samples, 0.01%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (17 samples, 0.01%)core::num::<impl u32>::wrapping_add (17 samples, 0.01%)core::sync::atomic::AtomicU64::compare_exchange (26 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (129 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (128 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (119 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::pack (39 samples, 0.03%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run (613 samples, 0.47%)tokio::runtime::context::runtime::enter_runtime (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (613 samples, 0.47%)tokio::runtime::context::set_scheduler (613 samples, 0.47%)std::thread::local::LocalKey<T>::with (613 samples, 0.47%)std::thread::local::LocalKey<T>::try_with (613 samples, 0.47%)tokio::runtime::context::set_scheduler::{{closure}} (613 samples, 0.47%)tokio::runtime::context::scoped::Scoped<T>::set (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::Context::run (613 samples, 0.47%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (777 samples, 0.59%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (776 samples, 0.59%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (16 samples, 0.01%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (16 samples, 0.01%)tokio::runtime::context::set_current_task_id (16 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (16 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (20 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (20 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::poll (835 samples, 0.64%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (56 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage (46 samples, 0.04%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (897 samples, 0.68%)tokio::runtime::task::harness::poll_future::{{closure}} (897 samples, 0.68%)tokio::runtime::task::core::Core<T,S>::store_output (62 samples, 0.05%)tokio::runtime::task::harness::poll_future (930 samples, 0.71%)std::panic::catch_unwind (927 samples, 0.71%)std::panicking::try (927 samples, 0.71%)std::panicking::try::do_call (925 samples, 0.70%)core::mem::manually_drop::ManuallyDrop<T>::take (28 samples, 0.02%)core::ptr::read (28 samples, 0.02%)tokio::runtime::task::raw::poll (938 samples, 0.71%)tokio::runtime::task::harness::Harness<T,S>::poll (934 samples, 0.71%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (934 samples, 0.71%)core::array::<impl core::default::Default for [T: 32]>::default (26 samples, 0.02%)tokio::runtime::time::Inner::lock (16 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (15 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::time::wheel::Wheel::poll (25 samples, 0.02%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (98 samples, 0.07%)tokio::runtime::time::Driver::park_internal (51 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (15 samples, 0.01%)<F as core::future::into_future::IntoFuture>::into_future (16 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (24 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (46 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (131 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (24 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (14 samples, 0.01%)core::sync::atomic::AtomicU32::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (39 samples, 0.03%)std::sync::rwlock::RwLock<T>::read (34 samples, 0.03%)std::sys::sync::rwlock::futex::RwLock::read (32 samples, 0.02%)[[heap]] (2,361 samples, 1.80%)[..[[vdso]] (313 samples, 0.24%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (41 samples, 0.03%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (16 samples, 0.01%)<alloc::string::String as core::fmt::Write>::write_str (67 samples, 0.05%)alloc::string::String::push_str (18 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (18 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (18 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (18 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (36 samples, 0.03%)core::num::<impl u64>::rotate_left (28 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (60 samples, 0.05%)core::num::<impl u64>::wrapping_add (14 samples, 0.01%)core::hash::sip::u8to64_le (60 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (184 samples, 0.14%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (15 samples, 0.01%)tokio::runtime::context::CONTEXT::__getit (19 samples, 0.01%)core::cell::Cell<T>::get (17 samples, 0.01%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (26 samples, 0.02%)core::ops::function::FnMut::call_mut (21 samples, 0.02%)tokio::runtime::coop::poll_proceed (21 samples, 0.02%)tokio::runtime::context::budget (21 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (21 samples, 0.02%)[unknown] (18 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (195 samples, 0.15%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (14 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (14 samples, 0.01%)core::result::Result<T,E>::is_err (18 samples, 0.01%)core::result::Result<T,E>::is_ok (18 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (46 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (39 samples, 0.03%)core::sync::atomic::AtomicU32::compare_exchange (19 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (19 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (245 samples, 0.19%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (26 samples, 0.02%)[[vdso]] (748 samples, 0.57%)[profiling] (34 samples, 0.03%)core::fmt::write (31 samples, 0.02%)__GI___clock_gettime (29 samples, 0.02%)__GI___libc_free (131 samples, 0.10%)arena_for_chunk (20 samples, 0.02%)arena_for_chunk (19 samples, 0.01%)heap_for_ptr (19 samples, 0.01%)heap_max_size (14 samples, 0.01%)__GI___libc_malloc (114 samples, 0.09%)__GI___libc_realloc (15 samples, 0.01%)__GI___lll_lock_wake_private (22 samples, 0.02%)__GI___pthread_disable_asynccancel (66 samples, 0.05%)__GI_getsockname (249 samples, 0.19%)__libc_calloc (15 samples, 0.01%)__libc_recvfrom (23 samples, 0.02%)__libc_sendto (130 samples, 0.10%)__memcmp_evex_movbe (451 samples, 0.34%)__memcpy_avx512_unaligned_erms (426 samples, 0.32%)__memset_avx512_unaligned_erms (215 samples, 0.16%)__posix_memalign (17 samples, 0.01%)_int_free (418 samples, 0.32%)tcache_put (24 samples, 0.02%)_int_malloc (385 samples, 0.29%)_int_memalign (31 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (26 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (15 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (15 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (15 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (54 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::grow_one (15 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (96 samples, 0.07%)alloc::raw_vec::RawVec<T,A>::grow_amortized (66 samples, 0.05%)core::num::<impl usize>::checked_add (18 samples, 0.01%)core::num::<impl usize>::overflowing_add (18 samples, 0.01%)alloc::raw_vec::finish_grow (74 samples, 0.06%)alloc::sync::Arc<T,A>::drop_slow (16 samples, 0.01%)core::mem::drop (14 samples, 0.01%)core::fmt::Formatter::pad_integral (14 samples, 0.01%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (93 samples, 0.07%)core::ptr::drop_in_place<tokio::net::udp::UdpSocket::send_to<&core::net::socket_addr::SocketAddr>::{{closure}}> (23 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (188 samples, 0.14%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_announce::{{closure}}> (30 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_connect::{{closure}}> (22 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_packet::{{closure}}> (20 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}}> (19 samples, 0.01%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::send_response::{{closure}}> (22 samples, 0.02%)malloc_consolidate (24 samples, 0.02%)core::core_arch::x86::avx2::_mm256_or_si256 (15 samples, 0.01%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (17 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (17 samples, 0.01%)rand_chacha::guts::round (66 samples, 0.05%)rand_chacha::guts::refill_wide::impl_avx2 (99 samples, 0.08%)rand_chacha::guts::refill_wide::fn_impl (98 samples, 0.07%)rand_chacha::guts::refill_wide_impl (98 samples, 0.07%)std::io::error::Error::kind (14 samples, 0.01%)[unknown] (42 samples, 0.03%)[unknown] (14 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (490 samples, 0.37%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (211 samples, 0.16%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (84 samples, 0.06%)tokio::runtime::task::core::Header::get_owner_id (18 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (18 samples, 0.01%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (20 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::remove (19 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (31 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (29 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (108 samples, 0.08%)tokio::runtime::task::core::TaskIdGuard::enter (14 samples, 0.01%)tokio::runtime::context::set_current_task_id (14 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::complete (21 samples, 0.02%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (32 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (54 samples, 0.04%)tokio::runtime::task::raw::drop_abort_handle (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (17 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (22 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (22 samples, 0.02%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (79 samples, 0.06%)core::slice::<impl [T]>::contains (178 samples, 0.14%)<T as core::slice::cmp::SliceContains>::slice_contains (178 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (178 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (40 samples, 0.03%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (40 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (216 samples, 0.16%)tokio::loom::std::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (219 samples, 0.17%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (29 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (29 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (54 samples, 0.04%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (18 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (18 samples, 0.01%)core::sync::atomic::AtomicU32::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (113 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (51 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (31 samples, 0.02%)core::sync::atomic::AtomicU64::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (447 samples, 0.34%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (174 samples, 0.13%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (19 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (489 samples, 0.37%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (489 samples, 0.37%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run (484 samples, 0.37%)tokio::runtime::context::runtime::enter_runtime (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (484 samples, 0.37%)tokio::runtime::context::set_scheduler (484 samples, 0.37%)std::thread::local::LocalKey<T>::with (484 samples, 0.37%)std::thread::local::LocalKey<T>::try_with (484 samples, 0.37%)tokio::runtime::context::set_scheduler::{{closure}} (484 samples, 0.37%)tokio::runtime::context::scoped::Scoped<T>::set (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Context::run (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (24 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (20 samples, 0.02%)tokio::runtime::task::raw::poll (515 samples, 0.39%)tokio::runtime::task::harness::Harness<T,S>::poll (493 samples, 0.38%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (493 samples, 0.38%)tokio::runtime::task::harness::poll_future (493 samples, 0.38%)std::panic::catch_unwind (493 samples, 0.38%)std::panicking::try (493 samples, 0.38%)std::panicking::try::do_call (493 samples, 0.38%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (493 samples, 0.38%)tokio::runtime::task::harness::poll_future::{{closure}} (493 samples, 0.38%)tokio::runtime::task::core::Core<T,S>::poll (493 samples, 0.38%)tokio::runtime::time::wheel::Wheel::next_expiration (16 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (27 samples, 0.02%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (15 samples, 0.01%)torrust_tracker::core::Tracker::send_stats_event::{{closure}} (44 samples, 0.03%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (15 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::d_rounds (29 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (74 samples, 0.06%)torrust_tracker::servers::udp::peer_builder::from_request (17 samples, 0.01%)torrust_tracker::servers::udp::request::AnnounceWrapper::new (51 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (54 samples, 0.04%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (58 samples, 0.04%)torrust_tracker::core::Tracker::announce::{{closure}} (70 samples, 0.05%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (113 samples, 0.09%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (175 samples, 0.13%)<T as alloc::string::ToString>::to_string (38 samples, 0.03%)core::option::Option<T>::expect (56 samples, 0.04%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (18 samples, 0.01%)<T as alloc::string::ToString>::to_string (18 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (180 samples, 0.14%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (468 samples, 0.36%)torrust_tracker::servers::udp::logging::log_response (38 samples, 0.03%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (669 samples, 0.51%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (152 samples, 0.12%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (147 samples, 0.11%)tokio::net::udp::UdpSocket::send_to::{{closure}} (138 samples, 0.11%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (119 samples, 0.09%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (75 samples, 0.06%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (39 samples, 0.03%)mio::net::udp::UdpSocket::send_to (39 samples, 0.03%)mio::io_source::IoSource<T>::do_io (39 samples, 0.03%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (39 samples, 0.03%)mio::net::udp::UdpSocket::send_to::{{closure}} (39 samples, 0.03%)std::net::udp::UdpSocket::send_to (39 samples, 0.03%)std::sys_common::net::UdpSocket::send_to (39 samples, 0.03%)std::sys::pal::unix::cvt (39 samples, 0.03%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (39 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_stats (15 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (14 samples, 0.01%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count::to_usize::{{closure}} (33 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats::{{closure}} (33 samples, 0.03%)torrust_tracker_primitives::peer::Peer::is_seeder (33 samples, 0.03%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count (75 samples, 0.06%)core::iter::traits::iterator::Iterator::sum (75 samples, 0.06%)<usize as core::iter::traits::accum::Sum>::sum (75 samples, 0.06%)<core::iter::adapters::map::Map<I,F> as core::iter::traits::iterator::Iterator>::fold (75 samples, 0.06%)core::iter::traits::iterator::Iterator::fold (75 samples, 0.06%)core::iter::adapters::map::map_fold::{{closure}} (34 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (104 samples, 0.08%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (24 samples, 0.02%)core::mem::drop (15 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (15 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (15 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (15 samples, 0.01%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (215 samples, 0.16%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (198 samples, 0.15%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (89 samples, 0.07%)core::option::Option<T>::is_some_and (32 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (31 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (30 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (30 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (26 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.03%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (58 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (58 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (58 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (58 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (58 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (20 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (238 samples, 0.18%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (236 samples, 0.18%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (208 samples, 0.16%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (208 samples, 0.16%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (282 samples, 0.21%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (67 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (53 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (53 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (22 samples, 0.02%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (22 samples, 0.02%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (22 samples, 0.02%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (22 samples, 0.02%)<u8 as core::slice::cmp::SliceOrd>::compare (22 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (18 samples, 0.01%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (23 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (23 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (43 samples, 0.03%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (43 samples, 0.03%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (43 samples, 0.03%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (43 samples, 0.03%)<u8 as core::slice::cmp::SliceOrd>::compare (43 samples, 0.03%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (17 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (151 samples, 0.12%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (145 samples, 0.11%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (137 samples, 0.10%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (137 samples, 0.10%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (266 samples, 0.20%)core::sync::atomic::AtomicU32::load (27 samples, 0.02%)core::sync::atomic::atomic_load (27 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (38 samples, 0.03%)std::sync::rwlock::RwLock<T>::read (37 samples, 0.03%)std::sys::sync::rwlock::futex::RwLock::read (36 samples, 0.03%)tracing::span::Span::log (16 samples, 0.01%)tracing::span::Span::record_all (70 samples, 0.05%)unlink_chunk (139 samples, 0.11%)rand::rng::Rng::gen (30 samples, 0.02%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (30 samples, 0.02%)rand::rng::Rng::gen (30 samples, 0.02%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (30 samples, 0.02%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (30 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (30 samples, 0.02%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (30 samples, 0.02%)rand_core::block::BlockRng<R>::generate_and_set (28 samples, 0.02%)[anon] (8,759 samples, 6.67%)[anon]uuid::v4::<impl uuid::Uuid>::new_v4 (32 samples, 0.02%)uuid::rng::bytes (32 samples, 0.02%)rand::random (32 samples, 0.02%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (15 samples, 0.01%)_int_free (338 samples, 0.26%)tcache_put (18 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (22 samples, 0.02%)hashbrown::raw::h2 (14 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (23 samples, 0.02%)hashbrown::raw::RawTableInner::find_or_find_insert_slot_inner (17 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (25 samples, 0.02%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (15 samples, 0.01%)[profiling] (545 samples, 0.42%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (32 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (22 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (16 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (30 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (28 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (83 samples, 0.06%)alloc::string::String::push_str (57 samples, 0.04%)alloc::vec::Vec<T,A>::extend_from_slice (57 samples, 0.04%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (57 samples, 0.04%)alloc::vec::Vec<T,A>::append_elements (57 samples, 0.04%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (20 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (41 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (151 samples, 0.12%)core::hash::sip::u8to64_le (50 samples, 0.04%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (33 samples, 0.03%)tokio::runtime::context::CONTEXT::__getit (35 samples, 0.03%)core::cell::Cell<T>::get (33 samples, 0.03%)[unknown] (20 samples, 0.02%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (75 samples, 0.06%)core::ops::function::FnMut::call_mut (66 samples, 0.05%)tokio::runtime::coop::poll_proceed (66 samples, 0.05%)tokio::runtime::context::budget (66 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (66 samples, 0.05%)tokio::runtime::context::budget::{{closure}} (27 samples, 0.02%)tokio::runtime::coop::poll_proceed::{{closure}} (27 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (110 samples, 0.08%)[unknown] (15 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (27 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (27 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (14 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (84 samples, 0.06%)std::sync::mutex::Mutex<T>::lock (70 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock (59 samples, 0.04%)core::sync::atomic::AtomicU32::compare_exchange (55 samples, 0.04%)core::sync::atomic::atomic_compare_exchange (55 samples, 0.04%)[unknown] (33 samples, 0.03%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (214 samples, 0.16%)__memcpy_avx512_unaligned_erms (168 samples, 0.13%)[profiling] (171 samples, 0.13%)binascii::bin2hex (77 samples, 0.06%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (280 samples, 0.21%)[unknown] (317 samples, 0.24%)[[vdso]] (2,648 samples, 2.02%)[..[unknown] (669 samples, 0.51%)[unknown] (396 samples, 0.30%)[unknown] (251 samples, 0.19%)[unknown] (65 samples, 0.05%)[unknown] (30 samples, 0.02%)[unknown] (21 samples, 0.02%)__GI___clock_gettime (56 samples, 0.04%)arena_for_chunk (72 samples, 0.05%)arena_for_chunk (62 samples, 0.05%)heap_for_ptr (49 samples, 0.04%)heap_max_size (28 samples, 0.02%)__GI___libc_free (194 samples, 0.15%)arena_for_chunk (19 samples, 0.01%)checked_request2size (24 samples, 0.02%)__GI___libc_malloc (220 samples, 0.17%)tcache_get (44 samples, 0.03%)__GI___libc_write (25 samples, 0.02%)__GI___libc_write (14 samples, 0.01%)__GI___pthread_disable_asynccancel (97 samples, 0.07%)core::num::<impl u128>::leading_zeros (15 samples, 0.01%)compiler_builtins::float::conv::int_to_float::u128_to_f64_bits (72 samples, 0.05%)__floattidf (90 samples, 0.07%)compiler_builtins::float::conv::__floattidf (86 samples, 0.07%)exp_inline (40 samples, 0.03%)log_inline (64 samples, 0.05%)__ieee754_pow_fma (114 samples, 0.09%)__libc_calloc (106 samples, 0.08%)__libc_recvfrom (252 samples, 0.19%)__libc_sendto (133 samples, 0.10%)__memcmp_evex_movbe (137 samples, 0.10%)__memcpy_avx512_unaligned_erms (1,399 samples, 1.07%)__posix_memalign (172 samples, 0.13%)__posix_memalign (80 samples, 0.06%)_mid_memalign (71 samples, 0.05%)arena_for_chunk (14 samples, 0.01%)__pow (18 samples, 0.01%)__vdso_clock_gettime (40 samples, 0.03%)[unknown] (24 samples, 0.02%)_int_free (462 samples, 0.35%)tcache_put (54 samples, 0.04%)[unknown] (14 samples, 0.01%)_int_malloc (508 samples, 0.39%)_int_memalign (68 samples, 0.05%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (54 samples, 0.04%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (14 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (78 samples, 0.06%)alloc::raw_vec::RawVec<T,A>::grow_amortized (73 samples, 0.06%)alloc::raw_vec::finish_grow (91 samples, 0.07%)core::result::Result<T,E>::map_err (31 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Weak<ring::ec::curve25519::ed25519::signing::Ed25519KeyPair,&alloc::alloc::Global>> (16 samples, 0.01%)<alloc::sync::Weak<T,A> as core::ops::drop::Drop>::drop (16 samples, 0.01%)core::mem::drop (18 samples, 0.01%)alloc::sync::Arc<T,A>::drop_slow (21 samples, 0.02%)alloc_new_heap (49 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (49 samples, 0.04%)core::fmt::Formatter::pad_integral (40 samples, 0.03%)core::fmt::Formatter::pad_integral::write_prefix (19 samples, 0.01%)core::fmt::write (20 samples, 0.02%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (155 samples, 0.12%)core::ptr::drop_in_place<core::option::Option<core::task::wake::Waker>> (71 samples, 0.05%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (245 samples, 0.19%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_announce::{{closure}}> (33 samples, 0.03%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}}> (37 samples, 0.03%)core::str::converts::from_utf8 (33 samples, 0.03%)core::str::validations::run_utf8_validation (20 samples, 0.02%)epoll_wait (31 samples, 0.02%)hashbrown::map::HashMap<K,V,S,A>::insert (17 samples, 0.01%)rand_chacha::guts::refill_wide (19 samples, 0.01%)std_detect::detect::arch::x86::__is_feature_detected::avx2 (17 samples, 0.01%)std_detect::detect::check_for (17 samples, 0.01%)std_detect::detect::cache::test (17 samples, 0.01%)std_detect::detect::cache::Cache::test (17 samples, 0.01%)core::sync::atomic::AtomicUsize::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)std::sys::pal::unix::time::Timespec::new (29 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (132 samples, 0.10%)core::cmp::impls::<impl core::cmp::PartialOrd<&B> for &A>::ge (22 samples, 0.02%)core::cmp::PartialOrd::ge (22 samples, 0.02%)std::sys::pal::unix::time::Timespec::sub_timespec (67 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock_contended (18 samples, 0.01%)std::sys_common::net::TcpListener::socket_addr (29 samples, 0.02%)std::sys_common::net::sockname (28 samples, 0.02%)syscall (552 samples, 0.42%)core::ptr::drop_in_place<core::cell::RefMut<core::option::Option<alloc::boxed::Box<tokio::runtime::scheduler::multi_thread::worker::Core>>>> (74 samples, 0.06%)core::ptr::drop_in_place<core::cell::BorrowRefMut> (74 samples, 0.06%)<core::cell::BorrowRefMut as core::ops::drop::Drop>::drop (74 samples, 0.06%)core::cell::Cell<T>::set (74 samples, 0.06%)core::cell::Cell<T>::replace (74 samples, 0.06%)core::mem::replace (74 samples, 0.06%)core::ptr::write (74 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::push_back_or_overflow (14 samples, 0.01%)tokio::runtime::context::with_scheduler (176 samples, 0.13%)std::thread::local::LocalKey<T>::try_with (152 samples, 0.12%)tokio::runtime::context::with_scheduler::{{closure}} (151 samples, 0.12%)tokio::runtime::context::scoped::Scoped<T>::with (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (71 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (16 samples, 0.01%)core::option::Option<T>::map (19 samples, 0.01%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (24 samples, 0.02%)mio::poll::Poll::poll (53 samples, 0.04%)mio::sys::unix::selector::epoll::Selector::select (53 samples, 0.04%)core::result::Result<T,E>::map (28 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (28 samples, 0.02%)tokio::io::ready::Ready::from_mio (14 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (126 samples, 0.10%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (18 samples, 0.01%)[unknown] (51 samples, 0.04%)[unknown] (100 samples, 0.08%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (326 samples, 0.25%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (205 samples, 0.16%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (77 samples, 0.06%)[unknown] (26 samples, 0.02%)<tokio::util::linked_list::DrainFilter<T,F> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (396 samples, 0.30%)tokio::loom::std::mutex::Mutex<T>::lock (18 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (573 samples, 0.44%)core::sync::atomic::AtomicUsize::fetch_add (566 samples, 0.43%)core::sync::atomic::atomic_add (566 samples, 0.43%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (635 samples, 0.48%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (25 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::next_remote_task (44 samples, 0.03%)tokio::runtime::scheduler::inject::shared::Shared<T>::is_empty (21 samples, 0.02%)tokio::runtime::scheduler::inject::shared::Shared<T>::len (21 samples, 0.02%)core::sync::atomic::AtomicUsize::load (21 samples, 0.02%)core::sync::atomic::atomic_load (21 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id (32 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (32 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (32 samples, 0.02%)std::sync::poison::Flag::done (32 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>,tokio::runtime::task::core::Header>>> (43 samples, 0.03%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (43 samples, 0.03%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (123 samples, 0.09%)tokio::runtime::task::list::OwnedTasks<S>::remove (117 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (80 samples, 0.06%)tokio::runtime::scheduler::defer::Defer::wake (17 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (46 samples, 0.04%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (71 samples, 0.05%)std::sync::condvar::Condvar::wait (56 samples, 0.04%)std::sys::sync::condvar::futex::Condvar::wait (56 samples, 0.04%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (56 samples, 0.04%)core::sync::atomic::AtomicUsize::compare_exchange (37 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (37 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (138 samples, 0.11%)tokio::runtime::driver::Driver::park (77 samples, 0.06%)tokio::runtime::driver::TimeDriver::park (77 samples, 0.06%)tokio::runtime::time::Driver::park (75 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Parker::park (266 samples, 0.20%)tokio::runtime::scheduler::multi_thread::park::Inner::park (266 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (432 samples, 0.33%)tokio::runtime::scheduler::multi_thread::worker::Core::should_notify_others (26 samples, 0.02%)core::cell::RefCell<T>::borrow_mut (94 samples, 0.07%)core::cell::RefCell<T>::try_borrow_mut (94 samples, 0.07%)core::cell::BorrowRefMut::new (94 samples, 0.07%)tokio::runtime::coop::budget (142 samples, 0.11%)tokio::runtime::coop::with_budget (142 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (121 samples, 0.09%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (44 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (208 samples, 0.16%)tokio::runtime::signal::Driver::process (30 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (46 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (46 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (35 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::set_stage (75 samples, 0.06%)core::sync::atomic::AtomicUsize::fetch_xor (76 samples, 0.06%)core::sync::atomic::atomic_xor (76 samples, 0.06%)tokio::runtime::task::state::State::transition_to_complete (79 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::complete (113 samples, 0.09%)tokio::runtime::task::state::State::transition_to_terminal (18 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::dealloc (28 samples, 0.02%)core::mem::drop (18 samples, 0.01%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (18 samples, 0.01%)core::ptr::drop_in_place<tokio::util::sharded_list::ShardGuard<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>> (16 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>>> (16 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (16 samples, 0.01%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (53 samples, 0.04%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (21 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (113 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (15 samples, 0.01%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (15 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (15 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (15 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (14 samples, 0.01%)tokio::runtime::task::raw::drop_abort_handle (82 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (23 samples, 0.02%)tokio::runtime::task::state::State::ref_dec (23 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::task::raw::drop_join_handle_slow (34 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::drop_join_handle_slow (32 samples, 0.02%)tokio::runtime::task::state::State::unset_join_interested (23 samples, 0.02%)tokio::runtime::task::state::State::fetch_update (23 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (43 samples, 0.03%)core::num::<impl u32>::wrapping_add (23 samples, 0.02%)core::option::Option<T>::or_else (37 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (36 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (36 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (38 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (59 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (45 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (132 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (63 samples, 0.05%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run (290 samples, 0.22%)tokio::runtime::context::runtime::enter_runtime (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (290 samples, 0.22%)tokio::runtime::context::set_scheduler (290 samples, 0.22%)std::thread::local::LocalKey<T>::with (290 samples, 0.22%)std::thread::local::LocalKey<T>::try_with (290 samples, 0.22%)tokio::runtime::context::set_scheduler::{{closure}} (290 samples, 0.22%)tokio::runtime::context::scoped::Scoped<T>::set (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::Context::run (290 samples, 0.22%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (327 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (322 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::poll (333 samples, 0.25%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (342 samples, 0.26%)tokio::runtime::task::harness::poll_future::{{closure}} (342 samples, 0.26%)tokio::runtime::task::harness::poll_future (348 samples, 0.27%)std::panic::catch_unwind (347 samples, 0.26%)std::panicking::try (347 samples, 0.26%)std::panicking::try::do_call (347 samples, 0.26%)core::sync::atomic::AtomicUsize::compare_exchange (18 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (18 samples, 0.01%)tokio::runtime::task::state::State::transition_to_running (47 samples, 0.04%)tokio::runtime::task::state::State::fetch_update_action (47 samples, 0.04%)tokio::runtime::task::state::State::transition_to_running::{{closure}} (19 samples, 0.01%)tokio::runtime::task::raw::poll (427 samples, 0.33%)tokio::runtime::task::harness::Harness<T,S>::poll (408 samples, 0.31%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (407 samples, 0.31%)tokio::runtime::task::state::State::transition_to_idle (17 samples, 0.01%)core::array::<impl core::default::Default for [T: 32]>::default (21 samples, 0.02%)tokio::runtime::time::wheel::Wheel::poll (14 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (72 samples, 0.05%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (23 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (15 samples, 0.01%)tokio::runtime::time::source::TimeSource::now (14 samples, 0.01%)tokio::runtime::time::Driver::park_internal (155 samples, 0.12%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (96 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (35 samples, 0.03%)core::num::<impl usize>::pow (35 samples, 0.03%)tokio::runtime::time::wheel::level::level_range (39 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (33 samples, 0.03%)core::num::<impl usize>::pow (33 samples, 0.03%)tokio::runtime::time::wheel::level::Level::next_expiration (208 samples, 0.16%)tokio::runtime::time::wheel::level::slot_range (48 samples, 0.04%)core::num::<impl usize>::pow (48 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (277 samples, 0.21%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::is_empty (18 samples, 0.01%)core::option::Option<T>::is_some (18 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (50 samples, 0.04%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (37 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (27 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (19 samples, 0.01%)core::iter::traits::iterator::Iterator::collect (17 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (17 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (17 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (17 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (20 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (20 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (20 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (62 samples, 0.05%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (40 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (27 samples, 0.02%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (17 samples, 0.01%)torrust_tracker::servers::udp::peer_builder::from_request (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (19 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (355 samples, 0.27%)<F as core::future::into_future::IntoFuture>::into_future (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (37 samples, 0.03%)core::sync::atomic::AtomicUsize::fetch_add (25 samples, 0.02%)core::sync::atomic::atomic_add (25 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet (14 samples, 0.01%)core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (20 samples, 0.02%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)core::result::Result<T,E>::map_err (16 samples, 0.01%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (136 samples, 0.10%)torrust_tracker::core::Tracker::announce::{{closure}} (173 samples, 0.13%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (267 samples, 0.20%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (30 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (423 samples, 0.32%)core::fmt::Formatter::new (26 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (80 samples, 0.06%)core::fmt::num::imp::fmt_u64 (58 samples, 0.04%)core::intrinsics::copy_nonoverlapping (15 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (74 samples, 0.06%)core::fmt::num::imp::fmt_u64 (70 samples, 0.05%)<T as alloc::string::ToString>::to_string (207 samples, 0.16%)core::option::Option<T>::expect (19 samples, 0.01%)core::ptr::drop_in_place<alloc::string::String> (18 samples, 0.01%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (18 samples, 0.01%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (18 samples, 0.01%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (18 samples, 0.01%)torrust_tracker::servers::udp::logging::map_action_name (25 samples, 0.02%)alloc::str::<impl alloc::borrow::ToOwned for str>::to_owned (14 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (345 samples, 0.26%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (18 samples, 0.01%)core::fmt::num::imp::fmt_u64 (14 samples, 0.01%)<T as alloc::string::ToString>::to_string (35 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (1,067 samples, 0.81%)torrust_tracker::servers::udp::logging::log_response (72 samples, 0.05%)alloc::vec::from_elem (68 samples, 0.05%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (68 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (68 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (68 samples, 0.05%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (68 samples, 0.05%)alloc::alloc::Global::alloc_impl (68 samples, 0.05%)alloc::alloc::alloc_zeroed (68 samples, 0.05%)__rdl_alloc_zeroed (68 samples, 0.05%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (68 samples, 0.05%)[unknown] (48 samples, 0.04%)[unknown] (16 samples, 0.01%)[unknown] (28 samples, 0.02%)std::sys::pal::unix::cvt (134 samples, 0.10%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (134 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (1,908 samples, 1.45%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (504 samples, 0.38%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (382 samples, 0.29%)tokio::net::udp::UdpSocket::send_to::{{closure}} (344 samples, 0.26%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (332 samples, 0.25%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (304 samples, 0.23%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (215 samples, 0.16%)mio::net::udp::UdpSocket::send_to (185 samples, 0.14%)mio::io_source::IoSource<T>::do_io (185 samples, 0.14%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (185 samples, 0.14%)mio::net::udp::UdpSocket::send_to::{{closure}} (185 samples, 0.14%)std::net::udp::UdpSocket::send_to (185 samples, 0.14%)std::sys_common::net::UdpSocket::send_to (169 samples, 0.13%)alloc::vec::Vec<T>::with_capacity (17 samples, 0.01%)alloc::vec::Vec<T,A>::with_capacity_in (17 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (104 samples, 0.08%)tokio::net::udp::UdpSocket::ready::{{closure}} (85 samples, 0.06%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (190 samples, 0.14%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (49 samples, 0.04%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (28 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (330 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (327 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (92 samples, 0.07%)tokio::task::spawn::spawn (92 samples, 0.07%)tokio::task::spawn::spawn_inner (92 samples, 0.07%)tokio::runtime::context::current::with_current (92 samples, 0.07%)std::thread::local::LocalKey<T>::try_with (92 samples, 0.07%)tokio::runtime::context::current::with_current::{{closure}} (92 samples, 0.07%)core::option::Option<T>::map (92 samples, 0.07%)tokio::task::spawn::spawn_inner::{{closure}} (92 samples, 0.07%)tokio::runtime::scheduler::Handle::spawn (92 samples, 0.07%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (92 samples, 0.07%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (92 samples, 0.07%)tokio::runtime::task::list::OwnedTasks<S>::bind (90 samples, 0.07%)tokio::runtime::task::new_task (89 samples, 0.07%)tokio::runtime::task::raw::RawTask::new (89 samples, 0.07%)tokio::runtime::task::core::Cell<T,S>::new (89 samples, 0.07%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (34 samples, 0.03%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (27 samples, 0.02%)alloc::sync::Arc<T>::new (21 samples, 0.02%)alloc::boxed::Box<T>::new (21 samples, 0.02%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (152 samples, 0.12%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (125 samples, 0.10%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (88 samples, 0.07%)core::option::Option<T>::is_some_and (18 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (17 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (17 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (17 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (22 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (22 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (17 samples, 0.01%)std::sync::rwlock::RwLock<T>::read (16 samples, 0.01%)std::sys::sync::rwlock::futex::RwLock::read (16 samples, 0.01%)tracing::span::Span::log (26 samples, 0.02%)core::fmt::Arguments::new_v1 (15 samples, 0.01%)tracing_core::span::Record::is_empty (34 samples, 0.03%)tracing_core::field::ValueSet::is_empty (34 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::all (22 samples, 0.02%)tracing_core::field::ValueSet::is_empty::{{closure}} (18 samples, 0.01%)core::option::Option<T>::is_none (16 samples, 0.01%)core::option::Option<T>::is_some (16 samples, 0.01%)tracing::span::Span::record_all (143 samples, 0.11%)unlink_chunk (185 samples, 0.14%)uuid::builder::Builder::with_variant (48 samples, 0.04%)[unknown] (40 samples, 0.03%)uuid::builder::Builder::from_random_bytes (77 samples, 0.06%)uuid::builder::Builder::with_version (29 samples, 0.02%)[unknown] (24 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (161 samples, 0.12%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (161 samples, 0.12%)[unknown] (92 samples, 0.07%)rand::rng::Rng::gen (162 samples, 0.12%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (162 samples, 0.12%)rand::rng::Rng::gen (162 samples, 0.12%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (162 samples, 0.12%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (162 samples, 0.12%)[unknown] (18,233 samples, 13.89%)[unknown]uuid::v4::<impl uuid::Uuid>::new_v4 (270 samples, 0.21%)uuid::rng::bytes (190 samples, 0.14%)rand::random (190 samples, 0.14%)__memcpy_avx512_unaligned_erms (69 samples, 0.05%)_int_free (23 samples, 0.02%)_int_malloc (23 samples, 0.02%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)advise_stack_range (31 samples, 0.02%)__GI_madvise (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (29 samples, 0.02%)[unknown] (28 samples, 0.02%)[unknown] (28 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (17 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (31 samples, 0.02%)syscall (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (29 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (17 samples, 0.01%)std::sync::condvar::Condvar::wait_timeout (35 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_timeout (35 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (35 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (56 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (56 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (56 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (56 samples, 0.04%)std::sys::pal::unix::futex::futex_wait (56 samples, 0.04%)syscall (56 samples, 0.04%)[unknown] (56 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (53 samples, 0.04%)[unknown] (52 samples, 0.04%)[unknown] (46 samples, 0.04%)[unknown] (39 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (15 samples, 0.01%)[[vdso]] (26 samples, 0.02%)[[vdso]] (263 samples, 0.20%)__ieee754_pow_fma (26 samples, 0.02%)__pow (314 samples, 0.24%)std::f64::<impl f64>::powf (345 samples, 0.26%)__GI___clock_gettime (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (416 samples, 0.32%)std::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_processing_scheduled_tasks (24 samples, 0.02%)std::time::Instant::now (18 samples, 0.01%)std::sys::pal::unix::time::Instant::now (18 samples, 0.01%)mio::poll::Poll::poll (102 samples, 0.08%)mio::sys::unix::selector::epoll::Selector::select (102 samples, 0.08%)epoll_wait (99 samples, 0.08%)[unknown] (92 samples, 0.07%)[unknown] (91 samples, 0.07%)[unknown] (91 samples, 0.07%)[unknown] (88 samples, 0.07%)[unknown] (85 samples, 0.06%)[unknown] (84 samples, 0.06%)[unknown] (43 samples, 0.03%)[unknown] (29 samples, 0.02%)[unknown] (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (125 samples, 0.10%)tokio::runtime::scheduler::multi_thread::park::Parker::park_timeout (125 samples, 0.10%)tokio::runtime::driver::Driver::park_timeout (125 samples, 0.10%)tokio::runtime::driver::TimeDriver::park_timeout (125 samples, 0.10%)tokio::runtime::time::Driver::park_timeout (125 samples, 0.10%)tokio::runtime::time::Driver::park_internal (116 samples, 0.09%)tokio::runtime::io::driver::Driver::turn (116 samples, 0.09%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (148 samples, 0.11%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (111 samples, 0.08%)alloc::sync::Arc<T,A>::inner (111 samples, 0.08%)core::ptr::non_null::NonNull<T>::as_ref (111 samples, 0.08%)core::sync::atomic::AtomicUsize::compare_exchange (16 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (16 samples, 0.01%)core::bool::<impl bool>::then (88 samples, 0.07%)std::sys::pal::unix::futex::futex_wait (13,339 samples, 10.16%)std::sys::pal::..syscall (13,003 samples, 9.90%)syscall[unknown] (12,895 samples, 9.82%)[unknown][unknown] (12,759 samples, 9.72%)[unknown][unknown] (12,313 samples, 9.38%)[unknown][unknown] (12,032 samples, 9.16%)[unknown][unknown] (11,734 samples, 8.94%)[unknown][unknown] (11,209 samples, 8.54%)[unknown][unknown] (10,265 samples, 7.82%)[unknown][unknown] (9,345 samples, 7.12%)[unknown][unknown] (8,623 samples, 6.57%)[unknown][unknown] (7,744 samples, 5.90%)[unknow..[unknown] (5,922 samples, 4.51%)[unkn..[unknown] (4,459 samples, 3.40%)[un..[unknown] (2,808 samples, 2.14%)[..[unknown] (1,275 samples, 0.97%)[unknown] (1,022 samples, 0.78%)[unknown] (738 samples, 0.56%)[unknown] (607 samples, 0.46%)[unknown] (155 samples, 0.12%)core::result::Result<T,E>::is_err (77 samples, 0.06%)core::result::Result<T,E>::is_ok (77 samples, 0.06%)std::sync::condvar::Condvar::wait (13,429 samples, 10.23%)std::sync::cond..std::sys::sync::condvar::futex::Condvar::wait (13,428 samples, 10.23%)std::sys::sync:..std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (13,428 samples, 10.23%)std::sys::sync:..std::sys::sync::mutex::futex::Mutex::lock (89 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (13,508 samples, 10.29%)tokio::runtime:..tokio::loom::std::mutex::Mutex<T>::lock (64 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (31 samples, 0.02%)core::sync::atomic::AtomicU32::compare_exchange (30 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (30 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (38 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Parker::park (34 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park (34 samples, 0.03%)core::array::<impl core::default::Default for [T: 32]>::default (17 samples, 0.01%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (19 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (33 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (15 samples, 0.01%)core::num::<impl usize>::pow (15 samples, 0.01%)tokio::runtime::time::wheel::level::level_range (17 samples, 0.01%)tokio::runtime::time::wheel::level::slot_range (15 samples, 0.01%)core::num::<impl usize>::pow (15 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_expiration (95 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (41 samples, 0.03%)core::num::<impl usize>::pow (41 samples, 0.03%)tokio::runtime::time::wheel::Wheel::next_expiration (129 samples, 0.10%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (202 samples, 0.15%)tokio::runtime::time::wheel::Wheel::poll_at (17 samples, 0.01%)tokio::runtime::time::wheel::Wheel::next_expiration (15 samples, 0.01%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (38 samples, 0.03%)core::option::Option<T>::map (38 samples, 0.03%)core::result::Result<T,E>::map (31 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (31 samples, 0.02%)alloc::vec::Vec<T,A>::set_len (17 samples, 0.01%)[[vdso]] (28 samples, 0.02%)[unknown] (11,031 samples, 8.40%)[unknown][unknown] (10,941 samples, 8.33%)[unknown][unknown] (10,850 samples, 8.26%)[unknown][unknown] (10,691 samples, 8.14%)[unknown][unknown] (10,070 samples, 7.67%)[unknown][unknown] (9,737 samples, 7.42%)[unknown][unknown] (7,659 samples, 5.83%)[unknow..[unknown] (6,530 samples, 4.97%)[unkno..[unknown] (5,633 samples, 4.29%)[unkn..[unknown] (5,055 samples, 3.85%)[unk..[unknown] (4,046 samples, 3.08%)[un..[unknown] (2,911 samples, 2.22%)[..[unknown] (2,115 samples, 1.61%)[unknown] (1,226 samples, 0.93%)[unknown] (455 samples, 0.35%)[unknown] (408 samples, 0.31%)[unknown] (249 samples, 0.19%)[unknown] (202 samples, 0.15%)[unknown] (100 samples, 0.08%)mio::poll::Poll::poll (11,328 samples, 8.63%)mio::poll::P..mio::sys::unix::selector::epoll::Selector::select (11,328 samples, 8.63%)mio::sys::un..epoll_wait (11,229 samples, 8.55%)epoll_wait__GI___pthread_disable_asynccancel (50 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (47 samples, 0.04%)tokio::util::bit::Pack::pack (38 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (25 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (23 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (19 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (11,595 samples, 8.83%)tokio::runti..tokio::runtime::io::scheduled_io::ScheduledIo::wake (175 samples, 0.13%)__GI___clock_gettime (15 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (18 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (26 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (26 samples, 0.02%)tokio::time::clock::Clock::now (20 samples, 0.02%)tokio::time::clock::now (20 samples, 0.02%)std::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Instant::now (20 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (17 samples, 0.01%)tokio::runtime::time::Driver::park_internal (11,686 samples, 8.90%)tokio::runtim..tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (11,957 samples, 9.11%)tokio::runtim..tokio::runtime::driver::Driver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::driver::TimeDriver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::time::Driver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::scheduler::multi_thread::park::Parker::park (25,502 samples, 19.42%)tokio::runtime::scheduler::mul..tokio::runtime::scheduler::multi_thread::park::Inner::park (25,502 samples, 19.42%)tokio::runtime::scheduler::mul..tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (25,547 samples, 19.46%)tokio::runtime::scheduler::mul..core::result::Result<T,E>::is_err (14 samples, 0.01%)core::result::Result<T,E>::is_ok (14 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (45 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (45 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (84 samples, 0.06%)std::sync::mutex::Mutex<T>::lock (81 samples, 0.06%)std::sys::sync::mutex::futex::Mutex::lock (73 samples, 0.06%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (122 samples, 0.09%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (90 samples, 0.07%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (90 samples, 0.07%)core::slice::<impl [T]>::contains (241 samples, 0.18%)<T as core::slice::cmp::SliceContains>::slice_contains (241 samples, 0.18%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (241 samples, 0.18%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (75 samples, 0.06%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (75 samples, 0.06%)core::sync::atomic::AtomicU32::compare_exchange (20 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (283 samples, 0.22%)tokio::loom::std::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (24 samples, 0.02%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (33 samples, 0.03%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (33 samples, 0.03%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (33 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::unpark_worker_by_id (98 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (401 samples, 0.31%)alloc::vec::Vec<T,A>::push (14 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (15 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (15 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::unlock (14 samples, 0.01%)core::result::Result<T,E>::is_err (15 samples, 0.01%)core::result::Result<T,E>::is_ok (15 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (22 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (22 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (63 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (62 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock (59 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (106 samples, 0.08%)tokio::runtime::scheduler::multi_thread::idle::State::dec_num_unparked (14 samples, 0.01%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (21 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (17 samples, 0.01%)alloc::sync::Arc<T,A>::inner (17 samples, 0.01%)core::ptr::non_null::NonNull<T>::as_ref (17 samples, 0.01%)core::sync::atomic::AtomicU32::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (68 samples, 0.05%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (51 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (33 samples, 0.03%)core::sync::atomic::AtomicU64::load (16 samples, 0.01%)core::sync::atomic::atomic_load (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (106 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::park (26,672 samples, 20.31%)tokio::runtime::scheduler::multi..tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (272 samples, 0.21%)tokio::runtime::scheduler::multi_thread::worker::Core::has_tasks (33 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::has_tasks (24 samples, 0.02%)tokio::runtime::context::budget (18 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (18 samples, 0.01%)syscall (61 samples, 0.05%)__memcpy_avx512_unaligned_erms (172 samples, 0.13%)__memcpy_avx512_unaligned_erms (224 samples, 0.17%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (228 samples, 0.17%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (228 samples, 0.17%)std::panic::catch_unwind (415 samples, 0.32%)std::panicking::try (415 samples, 0.32%)std::panicking::try::do_call (415 samples, 0.32%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (415 samples, 0.32%)core::ops::function::FnOnce::call_once (415 samples, 0.32%)tokio::runtime::task::harness::Harness<T,S>::complete::{{closure}} (415 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (415 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::set_stage (410 samples, 0.31%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (27 samples, 0.02%)core::result::Result<T,E>::is_err (43 samples, 0.03%)core::result::Result<T,E>::is_ok (43 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::complete (570 samples, 0.43%)tokio::runtime::task::harness::Harness<T,S>::release (155 samples, 0.12%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (152 samples, 0.12%)tokio::runtime::task::list::OwnedTasks<S>::remove (152 samples, 0.12%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (103 samples, 0.08%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (65 samples, 0.05%)tokio::loom::std::mutex::Mutex<T>::lock (58 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (58 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (54 samples, 0.04%)std::io::stdio::stderr::INSTANCE (17 samples, 0.01%)tokio::runtime::coop::budget (26 samples, 0.02%)tokio::runtime::coop::with_budget (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (35 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (70 samples, 0.05%)__memcpy_avx512_unaligned_erms (42 samples, 0.03%)core::cmp::Ord::min (22 samples, 0.02%)core::cmp::min_by (22 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (27 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (30 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (24 samples, 0.02%)core::slice::index::<impl core::ops::index::Index<I> for [T]>::index (19 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::index (19 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (19 samples, 0.01%)<core::ops::range::Range<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (19 samples, 0.01%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (44 samples, 0.03%)std::io::impls::<impl std::io::Read for &[u8]>::read_exact (20 samples, 0.02%)byteorder::io::ReadBytesExt::read_i32 (46 samples, 0.04%)core::cmp::Ord::min (14 samples, 0.01%)core::cmp::min_by (14 samples, 0.01%)std::io::cursor::Cursor<T>::remaining_slice (19 samples, 0.01%)byteorder::io::ReadBytesExt::read_i64 (24 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (24 samples, 0.02%)aquatic_udp_protocol::request::Request::from_bytes (349 samples, 0.27%)__GI___lll_lock_wake_private (148 samples, 0.11%)[unknown] (139 samples, 0.11%)[unknown] (137 samples, 0.10%)[unknown] (123 samples, 0.09%)[unknown] (111 samples, 0.08%)[unknown] (98 samples, 0.07%)[unknown] (42 samples, 0.03%)[unknown] (30 samples, 0.02%)__GI___lll_lock_wait_private (553 samples, 0.42%)futex_wait (541 samples, 0.41%)[unknown] (536 samples, 0.41%)[unknown] (531 samples, 0.40%)[unknown] (524 samples, 0.40%)[unknown] (515 samples, 0.39%)[unknown] (498 samples, 0.38%)[unknown] (470 samples, 0.36%)[unknown] (435 samples, 0.33%)[unknown] (350 samples, 0.27%)[unknown] (327 samples, 0.25%)[unknown] (290 samples, 0.22%)[unknown] (222 samples, 0.17%)[unknown] (160 samples, 0.12%)[unknown] (104 samples, 0.08%)[unknown] (33 samples, 0.03%)[unknown] (25 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (703 samples, 0.54%)__GI___libc_free (866 samples, 0.66%)tracing::span::Span::record_all (30 samples, 0.02%)unlink_chunk (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (899 samples, 0.68%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (899 samples, 0.68%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (899 samples, 0.68%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (899 samples, 0.68%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (899 samples, 0.68%)alloc::alloc::dealloc (899 samples, 0.68%)__rdl_dealloc (899 samples, 0.68%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (899 samples, 0.68%)core::result::Result<T,E>::expect (91 samples, 0.07%)core::result::Result<T,E>::map_err (28 samples, 0.02%)[[vdso]] (28 samples, 0.02%)__GI___clock_gettime (47 samples, 0.04%)std::time::Instant::elapsed (67 samples, 0.05%)std::time::Instant::now (54 samples, 0.04%)std::sys::pal::unix::time::Instant::now (54 samples, 0.04%)std::sys::pal::unix::time::Timespec::now (53 samples, 0.04%)std::sys::pal::unix::cvt (23 samples, 0.02%)__GI_getsockname (3,792 samples, 2.89%)__..[unknown] (3,714 samples, 2.83%)[u..[unknown] (3,661 samples, 2.79%)[u..[unknown] (3,557 samples, 2.71%)[u..[unknown] (3,416 samples, 2.60%)[u..[unknown] (2,695 samples, 2.05%)[..[unknown] (2,063 samples, 1.57%)[unknown] (891 samples, 0.68%)[unknown] (270 samples, 0.21%)[unknown] (99 samples, 0.08%)[unknown] (94 samples, 0.07%)[unknown] (84 samples, 0.06%)[unknown] (77 samples, 0.06%)[unknown] (25 samples, 0.02%)[unknown] (16 samples, 0.01%)std::sys_common::net::TcpListener::socket_addr::{{closure}} (3,800 samples, 2.89%)st..tokio::net::udp::UdpSocket::local_addr (3,838 samples, 2.92%)to..mio::net::udp::UdpSocket::local_addr (3,838 samples, 2.92%)mi..std::net::tcp::TcpListener::local_addr (3,838 samples, 2.92%)st..std::sys_common::net::TcpListener::socket_addr (3,838 samples, 2.92%)st..std::sys_common::net::sockname (3,835 samples, 2.92%)st..[[vdso]] (60 samples, 0.05%)rand_chacha::guts::ChaCha::pos64 (168 samples, 0.13%)<ppv_lite86::soft::x2<W,G> as core::ops::arith::AddAssign>::add_assign (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::AddAssign>::add_assign (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::Add>::add (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_add_epi32 (26 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_or_si256 (29 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (31 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (31 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (18 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (18 samples, 0.01%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (18 samples, 0.01%)rand_chacha::guts::round (118 samples, 0.09%)rand_chacha::guts::refill_wide::impl_avx2 (312 samples, 0.24%)rand_chacha::guts::refill_wide::fn_impl (312 samples, 0.24%)rand_chacha::guts::refill_wide_impl (312 samples, 0.24%)<rand_chacha::chacha::ChaCha12Core as rand_core::block::BlockRngCore>::generate (384 samples, 0.29%)rand_chacha::guts::ChaCha::refill4 (384 samples, 0.29%)rand::rng::Rng::gen (432 samples, 0.33%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (432 samples, 0.33%)rand::rng::Rng::gen (432 samples, 0.33%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (432 samples, 0.33%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (432 samples, 0.33%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (432 samples, 0.33%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (432 samples, 0.33%)rand_core::block::BlockRng<R>::generate_and_set (392 samples, 0.30%)<rand::rngs::adapter::reseeding::ReseedingCore<R,Rsdr> as rand_core::block::BlockRngCore>::generate (392 samples, 0.30%)torrust_tracker::servers::udp::handlers::RequestId::make (440 samples, 0.34%)uuid::v4::<impl uuid::Uuid>::new_v4 (436 samples, 0.33%)uuid::rng::bytes (435 samples, 0.33%)rand::random (435 samples, 0.33%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (34 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (22 samples, 0.02%)core::iter::traits::iterator::Iterator::collect (16 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (16 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (16 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (16 samples, 0.01%)<core::iter::adapters::cloned::Cloned<I> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)<core::iter::adapters::take::Take<I> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::next (15 samples, 0.01%)core::iter::traits::iterator::Iterator::find (15 samples, 0.01%)core::iter::traits::iterator::Iterator::try_fold (15 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (31 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.03%)core::slice::iter::Iter<T>::post_inc_start (14 samples, 0.01%)core::ptr::non_null::NonNull<T>::add (14 samples, 0.01%)__memcmp_evex_movbe (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (26 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (165 samples, 0.13%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (165 samples, 0.13%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (165 samples, 0.13%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (165 samples, 0.13%)<u8 as core::slice::cmp::SliceOrd>::compare (165 samples, 0.13%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (339 samples, 0.26%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (308 samples, 0.23%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (308 samples, 0.23%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (342 samples, 0.26%)std::sys::sync::rwlock::futex::RwLock::spin_read (25 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_until (25 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read_contended (28 samples, 0.02%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (436 samples, 0.33%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (397 samples, 0.30%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (29 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (29 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (29 samples, 0.02%)__memcmp_evex_movbe (31 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (52 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (52 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (52 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (52 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (52 samples, 0.04%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (103 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (102 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (96 samples, 0.07%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (96 samples, 0.07%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (72 samples, 0.05%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.08%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.08%)core::slice::iter::Iter<T>::post_inc_start (32 samples, 0.02%)core::ptr::non_null::NonNull<T>::add (32 samples, 0.02%)__memcmp_evex_movbe (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (81 samples, 0.06%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (271 samples, 0.21%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (271 samples, 0.21%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (271 samples, 0.21%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (271 samples, 0.21%)<u8 as core::slice::cmp::SliceOrd>::compare (271 samples, 0.21%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (610 samples, 0.46%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (566 samples, 0.43%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (566 samples, 0.43%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut,K,V,Type>::keys (18 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (616 samples, 0.47%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::KV>::split (15 samples, 0.01%)alloc::collections::btree::map::entry::Entry<K,V,A>::or_insert (46 samples, 0.04%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (45 samples, 0.03%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert_recursing (40 samples, 0.03%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert (27 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (29 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (20 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (120 samples, 0.09%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (118 samples, 0.09%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Owned,K,V,alloc::collections::btree::node::marker::Leaf>::new_leaf (118 samples, 0.09%)alloc::collections::btree::node::LeafNode<K,V>::new (118 samples, 0.09%)alloc::boxed::Box<T,A>::new_uninit_in (118 samples, 0.09%)alloc::boxed::Box<T,A>::try_new_uninit_in (118 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (118 samples, 0.09%)alloc::alloc::Global::alloc_impl (118 samples, 0.09%)alloc::alloc::alloc (118 samples, 0.09%)__rdl_alloc (118 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (118 samples, 0.09%)__GI___libc_malloc (118 samples, 0.09%)_int_malloc (107 samples, 0.08%)_int_malloc (28 samples, 0.02%)__GI___libc_malloc (32 samples, 0.02%)__rdl_alloc (36 samples, 0.03%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (36 samples, 0.03%)alloc::sync::Arc<T>::new (42 samples, 0.03%)alloc::boxed::Box<T>::new (42 samples, 0.03%)alloc::alloc::exchange_malloc (39 samples, 0.03%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (39 samples, 0.03%)alloc::alloc::Global::alloc_impl (39 samples, 0.03%)alloc::alloc::alloc (39 samples, 0.03%)core::mem::drop (15 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (15 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (15 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (15 samples, 0.01%)__GI___libc_free (39 samples, 0.03%)_int_free (37 samples, 0.03%)get_max_fast (16 samples, 0.01%)core::option::Option<T>::is_some_and (50 samples, 0.04%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (50 samples, 0.04%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (50 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (50 samples, 0.04%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (290 samples, 0.22%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (284 samples, 0.22%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (255 samples, 0.19%)std::sys::sync::rwlock::futex::RwLock::spin_read (16 samples, 0.01%)std::sys::sync::rwlock::futex::RwLock::spin_until (16 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (21 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (21 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (21 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read_contended (21 samples, 0.02%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (1,147 samples, 0.87%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (1,144 samples, 0.87%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents_mut (32 samples, 0.02%)std::sync::rwlock::RwLock<T>::write (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::write (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::write_contended (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_write (28 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_until (28 samples, 0.02%)torrust_tracker::core::Tracker::announce::{{closure}} (1,597 samples, 1.22%)<core::net::socket_addr::SocketAddrV4 as core::hash::Hash>::hash (14 samples, 0.01%)<core::net::ip_addr::Ipv4Addr as core::hash::Hash>::hash (14 samples, 0.01%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (29 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (24 samples, 0.02%)<core::time::Nanoseconds as core::hash::Hash>::hash (25 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (25 samples, 0.02%)core::hash::Hasher::write_u32 (25 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (25 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (25 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (36 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (37 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (37 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (64 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (39 samples, 0.03%)core::hash::Hasher::write_u64 (39 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (122 samples, 0.09%)core::hash::impls::<impl core::hash::Hash for u64>::hash (58 samples, 0.04%)core::hash::Hasher::write_u64 (58 samples, 0.04%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (58 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (58 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (57 samples, 0.04%)core::hash::sip::u8to64_le (23 samples, 0.02%)core::hash::Hasher::write_length_prefix (27 samples, 0.02%)core::hash::Hasher::write_usize (27 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (16 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (246 samples, 0.19%)core::array::<impl core::hash::Hash for [T: N]>::hash (93 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (93 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (66 samples, 0.05%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (62 samples, 0.05%)core::hash::sip::u8to64_le (17 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::check (285 samples, 0.22%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (36 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (36 samples, 0.03%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (24 samples, 0.02%)std::time::SystemTime::now (19 samples, 0.01%)std::sys::pal::unix::time::SystemTime::now (19 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (1,954 samples, 1.49%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (24 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (18 samples, 0.01%)<core::time::Nanoseconds as core::hash::Hash>::hash (20 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (20 samples, 0.02%)core::hash::Hasher::write_u32 (20 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (20 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (20 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (44 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (65 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (45 samples, 0.03%)core::hash::Hasher::write_u64 (45 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (45 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (45 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (105 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u64>::hash (40 samples, 0.03%)core::hash::Hasher::write_u64 (40 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (40 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (40 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (39 samples, 0.03%)core::hash::Hasher::write_length_prefix (34 samples, 0.03%)core::hash::Hasher::write_usize (34 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (34 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (34 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (33 samples, 0.03%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (231 samples, 0.18%)core::array::<impl core::hash::Hash for [T: N]>::hash (100 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (100 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (66 samples, 0.05%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (61 samples, 0.05%)core::hash::sip::u8to64_le (16 samples, 0.01%)_int_free (16 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (270 samples, 0.21%)torrust_tracker::servers::udp::connection_cookie::make (268 samples, 0.20%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (36 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (35 samples, 0.03%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (31 samples, 0.02%)std::time::SystemTime::now (26 samples, 0.02%)std::sys::pal::unix::time::SystemTime::now (26 samples, 0.02%)torrust_tracker::core::ScrapeData::add_file (19 samples, 0.01%)std::collections::hash::map::HashMap<K,V,S>::insert (19 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (19 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (16 samples, 0.01%)hashbrown::raw::RawTable<T,A>::reserve (16 samples, 0.01%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (17 samples, 0.01%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (17 samples, 0.01%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (17 samples, 0.01%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (17 samples, 0.01%)<u8 as core::slice::cmp::SliceOrd>::compare (17 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (53 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (53 samples, 0.04%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (2,336 samples, 1.78%)t..torrust_tracker::servers::udp::handlers::handle_scrape::{{closure}} (101 samples, 0.08%)torrust_tracker::core::Tracker::scrape::{{closure}} (90 samples, 0.07%)torrust_tracker::core::Tracker::get_swarm_metadata (68 samples, 0.05%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (64 samples, 0.05%)alloc::raw_vec::finish_grow (19 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::grow_amortized (21 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (23 samples, 0.02%)alloc::string::String::push_str (23 samples, 0.02%)alloc::vec::Vec<T,A>::extend_from_slice (23 samples, 0.02%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (23 samples, 0.02%)alloc::vec::Vec<T,A>::append_elements (23 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (85 samples, 0.06%)core::fmt::num::imp::fmt_u64 (78 samples, 0.06%)<alloc::string::String as core::fmt::Write>::write_str (15 samples, 0.01%)alloc::string::String::push_str (15 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (15 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (15 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (15 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (37 samples, 0.03%)core::fmt::num::imp::fmt_u64 (36 samples, 0.03%)<T as alloc::string::ToString>::to_string (141 samples, 0.11%)core::option::Option<T>::expect (34 samples, 0.03%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (28 samples, 0.02%)alloc::alloc::dealloc (28 samples, 0.02%)__rdl_dealloc (28 samples, 0.02%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (28 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (55 samples, 0.04%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (55 samples, 0.04%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (55 samples, 0.04%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (55 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::current_memory (20 samples, 0.02%)torrust_tracker::servers::udp::logging::map_action_name (16 samples, 0.01%)binascii::bin2hex (51 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (16 samples, 0.01%)core::fmt::write (25 samples, 0.02%)core::fmt::rt::Argument::fmt (15 samples, 0.01%)core::fmt::Formatter::write_fmt (87 samples, 0.07%)core::str::converts::from_utf8 (43 samples, 0.03%)core::str::validations::run_utf8_validation (37 samples, 0.03%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (161 samples, 0.12%)<T as alloc::string::ToString>::to_string (161 samples, 0.12%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (156 samples, 0.12%)torrust_tracker::servers::udp::logging::log_request (479 samples, 0.36%)[[vdso]] (51 samples, 0.04%)alloc::raw_vec::finish_grow (56 samples, 0.04%)alloc::vec::Vec<T,A>::reserve (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::reserve (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::grow_amortized (64 samples, 0.05%)<alloc::string::String as core::fmt::Write>::write_str (65 samples, 0.05%)alloc::string::String::push_str (65 samples, 0.05%)alloc::vec::Vec<T,A>::extend_from_slice (65 samples, 0.05%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (65 samples, 0.05%)alloc::vec::Vec<T,A>::append_elements (65 samples, 0.05%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (114 samples, 0.09%)core::fmt::num::imp::fmt_u64 (110 samples, 0.08%)<T as alloc::string::ToString>::to_string (132 samples, 0.10%)core::option::Option<T>::expect (20 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (22 samples, 0.02%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (22 samples, 0.02%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (22 samples, 0.02%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (22 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (8,883 samples, 6.77%)torrust_t..torrust_tracker::servers::udp::logging::log_response (238 samples, 0.18%)__GI___lll_lock_wait_private (14 samples, 0.01%)futex_wait (14 samples, 0.01%)__GI___lll_lock_wake_private (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (17 samples, 0.01%)_int_malloc (191 samples, 0.15%)__libc_calloc (238 samples, 0.18%)__memcpy_avx512_unaligned_erms (34 samples, 0.03%)alloc::vec::from_elem (316 samples, 0.24%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (316 samples, 0.24%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (316 samples, 0.24%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (316 samples, 0.24%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (312 samples, 0.24%)alloc::alloc::Global::alloc_impl (312 samples, 0.24%)alloc::alloc::alloc_zeroed (312 samples, 0.24%)__rdl_alloc_zeroed (312 samples, 0.24%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (312 samples, 0.24%)byteorder::ByteOrder::write_i32 (18 samples, 0.01%)<byteorder::BigEndian as byteorder::ByteOrder>::write_u32 (18 samples, 0.01%)core::num::<impl u32>::to_be_bytes (18 samples, 0.01%)core::num::<impl u32>::to_be (18 samples, 0.01%)core::num::<impl u32>::swap_bytes (18 samples, 0.01%)byteorder::io::WriteBytesExt::write_i32 (89 samples, 0.07%)std::io::Write::write_all (71 samples, 0.05%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (71 samples, 0.05%)std::io::cursor::vec_write (71 samples, 0.05%)std::io::cursor::vec_write_unchecked (51 samples, 0.04%)core::ptr::mut_ptr::<impl *mut T>::copy_from (51 samples, 0.04%)core::intrinsics::copy (51 samples, 0.04%)aquatic_udp_protocol::response::Response::write (227 samples, 0.17%)byteorder::io::WriteBytesExt::write_i64 (28 samples, 0.02%)std::io::Write::write_all (21 samples, 0.02%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (21 samples, 0.02%)std::io::cursor::vec_write (21 samples, 0.02%)std::io::cursor::vec_write_unchecked (21 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::copy_from (21 samples, 0.02%)core::intrinsics::copy (21 samples, 0.02%)__GI___lll_lock_wake_private (17 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (14 samples, 0.01%)__GI___lll_lock_wait_private (16 samples, 0.01%)futex_wait (15 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (136 samples, 0.10%)__GI___libc_free (206 samples, 0.16%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (211 samples, 0.16%)alloc::alloc::dealloc (211 samples, 0.16%)__rdl_dealloc (211 samples, 0.16%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (211 samples, 0.16%)core::ptr::drop_in_place<std::io::cursor::Cursor<alloc::vec::Vec<u8>>> (224 samples, 0.17%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (224 samples, 0.17%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (224 samples, 0.17%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (224 samples, 0.17%)std::io::cursor::Cursor<T>::new (56 samples, 0.04%)tokio::io::ready::Ready::intersection (23 samples, 0.02%)tokio::io::ready::Ready::from_interest (23 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (83 samples, 0.06%)[unknown] (32,674 samples, 24.88%)[unknown][unknown] (32,402 samples, 24.68%)[unknown][unknown] (32,272 samples, 24.58%)[unknown][unknown] (32,215 samples, 24.54%)[unknown][unknown] (31,174 samples, 23.74%)[unknown][unknown] (30,794 samples, 23.45%)[unknown][unknown] (30,036 samples, 22.88%)[unknown][unknown] (28,639 samples, 21.81%)[unknown][unknown] (27,908 samples, 21.25%)[unknown][unknown] (26,013 samples, 19.81%)[unknown][unknown] (23,181 samples, 17.65%)[unknown][unknown] (19,559 samples, 14.90%)[unknown][unknown] (18,052 samples, 13.75%)[unknown][unknown] (15,794 samples, 12.03%)[unknown][unknown] (14,740 samples, 11.23%)[unknown][unknown] (12,486 samples, 9.51%)[unknown][unknown] (11,317 samples, 8.62%)[unknown][unknown] (10,725 samples, 8.17%)[unknown][unknown] (10,017 samples, 7.63%)[unknown][unknown] (9,713 samples, 7.40%)[unknown][unknown] (8,432 samples, 6.42%)[unknown][unknown] (8,062 samples, 6.14%)[unknown][unknown] (6,973 samples, 5.31%)[unknow..[unknown] (5,328 samples, 4.06%)[unk..[unknown] (4,352 samples, 3.31%)[un..[unknown] (3,786 samples, 2.88%)[u..[unknown] (3,659 samples, 2.79%)[u..[unknown] (3,276 samples, 2.50%)[u..[unknown] (2,417 samples, 1.84%)[..[unknown] (2,115 samples, 1.61%)[unknown] (1,610 samples, 1.23%)[unknown] (422 samples, 0.32%)[unknown] (84 samples, 0.06%)[unknown] (69 samples, 0.05%)__GI___pthread_disable_asynccancel (67 samples, 0.05%)__libc_sendto (32,896 samples, 25.05%)__libc_sendtotokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (32,981 samples, 25.12%)tokio::net::udp::UdpSocket::send_to_addr..mio::net::udp::UdpSocket::send_to (32,981 samples, 25.12%)mio::net::udp::UdpSocket::send_tomio::io_source::IoSource<T>::do_io (32,981 samples, 25.12%)mio::io_source::IoSource<T>::do_iomio::sys::unix::stateless_io_source::IoSourceState::do_io (32,981 samples, 25.12%)mio::sys::unix::stateless_io_source::IoS..mio::net::udp::UdpSocket::send_to::{{closure}} (32,981 samples, 25.12%)mio::net::udp::UdpSocket::send_to::{{clo..std::net::udp::UdpSocket::send_to (32,981 samples, 25.12%)std::net::udp::UdpSocket::send_tostd::sys_common::net::UdpSocket::send_to (32,981 samples, 25.12%)std::sys_common::net::UdpSocket::send_tostd::sys::pal::unix::cvt (85 samples, 0.06%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (44,349 samples, 33.78%)torrust_tracker::servers::udp::server::Udp::process_req..torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (43,412 samples, 33.06%)torrust_tracker::servers::udp::server::Udp::process_va..torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (34,320 samples, 26.14%)torrust_tracker::servers::udp::server::Udp..torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (33,360 samples, 25.41%)torrust_tracker::servers::udp::server::Ud..tokio::net::udp::UdpSocket::send_to::{{closure}} (33,227 samples, 25.31%)tokio::net::udp::UdpSocket::send_to::{{c..tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (33,142 samples, 25.24%)tokio::net::udp::UdpSocket::send_to_addr..tokio::runtime::io::registration::Registration::async_io::{{closure}} (33,115 samples, 25.22%)tokio::runtime::io::registration::Regist..tokio::runtime::io::registration::Registration::readiness::{{closure}} (28 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (18 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (15 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (14 samples, 0.01%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (15 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (15 samples, 0.01%)core::sync::atomic::atomic_add (15 samples, 0.01%)__GI___lll_lock_wait_private (16 samples, 0.01%)futex_wait (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (135 samples, 0.10%)__GI___libc_free (147 samples, 0.11%)syscall (22 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Core<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (15 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::dealloc (24 samples, 0.02%)core::mem::drop (24 samples, 0.02%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (24 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (24 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::abort::AbortHandle> (262 samples, 0.20%)<tokio::runtime::task::abort::AbortHandle as core::ops::drop::Drop>::drop (262 samples, 0.20%)tokio::runtime::task::raw::RawTask::drop_abort_handle (256 samples, 0.19%)tokio::runtime::task::raw::drop_abort_handle (59 samples, 0.04%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (50 samples, 0.04%)tokio::runtime::task::state::State::ref_dec (50 samples, 0.04%)tokio::runtime::task::raw::RawTask::drop_join_handle_slow (16 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::join::JoinHandle<()>> (47 samples, 0.04%)<tokio::runtime::task::join::JoinHandle<T> as core::ops::drop::Drop>::drop (47 samples, 0.04%)tokio::runtime::task::state::State::drop_join_handle_fast (19 samples, 0.01%)core::sync::atomic::AtomicUsize::compare_exchange_weak (19 samples, 0.01%)core::sync::atomic::atomic_compare_exchange_weak (19 samples, 0.01%)ringbuf::ring_buffer::base::RbBase::is_full (14 samples, 0.01%)<ringbuf::ring_buffer::shared::SharedRb<T,C> as ringbuf::ring_buffer::base::RbBase<T>>::head (14 samples, 0.01%)core::sync::atomic::AtomicUsize::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)ringbuf::consumer::Consumer<T,R>::advance (29 samples, 0.02%)ringbuf::ring_buffer::base::RbRead::advance_head (29 samples, 0.02%)ringbuf::ring_buffer::rb::Rb::pop (50 samples, 0.04%)ringbuf::consumer::Consumer<T,R>::pop (50 samples, 0.04%)ringbuf::producer::Producer<T,R>::advance (23 samples, 0.02%)ringbuf::ring_buffer::base::RbWrite::advance_tail (23 samples, 0.02%)core::num::nonzero::<impl core::ops::arith::Rem<core::num::nonzero::NonZero<usize>> for usize>::rem (19 samples, 0.01%)ringbuf::ring_buffer::rb::Rb::push_overwrite (107 samples, 0.08%)ringbuf::ring_buffer::rb::Rb::push (43 samples, 0.03%)ringbuf::producer::Producer<T,R>::push (43 samples, 0.03%)tokio::runtime::task::abort::AbortHandle::is_finished (84 samples, 0.06%)tokio::runtime::task::state::Snapshot::is_complete (84 samples, 0.06%)tokio::runtime::task::join::JoinHandle<T>::abort_handle (17 samples, 0.01%)tokio::runtime::task::raw::RawTask::ref_inc (17 samples, 0.01%)tokio::runtime::task::state::State::ref_inc (17 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (14 samples, 0.01%)core::sync::atomic::atomic_add (14 samples, 0.01%)__GI___lll_lock_wake_private (22 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)malloc_consolidate (95 samples, 0.07%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (76 samples, 0.06%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (31 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (26 samples, 0.02%)_int_malloc (282 samples, 0.21%)__GI___libc_malloc (323 samples, 0.25%)alloc::vec::Vec<T>::with_capacity (326 samples, 0.25%)alloc::vec::Vec<T,A>::with_capacity_in (326 samples, 0.25%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (324 samples, 0.25%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (324 samples, 0.25%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (324 samples, 0.25%)alloc::alloc::Global::alloc_impl (324 samples, 0.25%)alloc::alloc::alloc (324 samples, 0.25%)__rdl_alloc (324 samples, 0.25%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (324 samples, 0.25%)tokio::io::ready::Ready::intersection (24 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (199 samples, 0.15%)tokio::util::bit::Pack::unpack (16 samples, 0.01%)tokio::util::bit::unpack (16 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (19 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (17 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (16 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (222 samples, 0.17%)tokio::net::udp::UdpSocket::ready::{{closure}} (222 samples, 0.17%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (50 samples, 0.04%)std::io::error::repr_bitpacked::Repr::data (14 samples, 0.01%)std::io::error::repr_bitpacked::decode_repr (14 samples, 0.01%)std::io::error::Error::kind (16 samples, 0.01%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (14 samples, 0.01%)[unknown] (8,756 samples, 6.67%)[unknown][unknown] (8,685 samples, 6.61%)[unknown][unknown] (8,574 samples, 6.53%)[unknown][unknown] (8,415 samples, 6.41%)[unknown][unknown] (7,686 samples, 5.85%)[unknow..[unknown] (7,239 samples, 5.51%)[unknow..[unknown] (6,566 samples, 5.00%)[unkno..[unknown] (5,304 samples, 4.04%)[unk..[unknown] (4,008 samples, 3.05%)[un..[unknown] (3,571 samples, 2.72%)[u..[unknown] (2,375 samples, 1.81%)[..[unknown] (1,844 samples, 1.40%)[unknown] (1,030 samples, 0.78%)[unknown] (344 samples, 0.26%)[unknown] (113 samples, 0.09%)__libc_recvfrom (8,903 samples, 6.78%)__libc_re..__GI___pthread_disable_asynccancel (22 samples, 0.02%)std::sys::pal::unix::cvt (20 samples, 0.02%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (9,005 samples, 6.86%)tokio::ne..mio::net::udp::UdpSocket::recv_from (8,964 samples, 6.83%)mio::net:..mio::io_source::IoSource<T>::do_io (8,964 samples, 6.83%)mio::io_s..mio::sys::unix::stateless_io_source::IoSourceState::do_io (8,964 samples, 6.83%)mio::sys:..mio::net::udp::UdpSocket::recv_from::{{closure}} (8,964 samples, 6.83%)mio::net:..std::net::udp::UdpSocket::recv_from (8,964 samples, 6.83%)std::net:..std::sys_common::net::UdpSocket::recv_from (8,964 samples, 6.83%)std::sys_..std::sys::pal::unix::net::Socket::recv_from (8,964 samples, 6.83%)std::sys:..std::sys::pal::unix::net::Socket::recv_from_with_flags (8,964 samples, 6.83%)std::sys:..std::sys_common::net::sockaddr_to_addr (23 samples, 0.02%)tokio::runtime::io::registration::Registration::clear_readiness (18 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::clear_readiness (18 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (32 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (9,967 samples, 7.59%)torrust_tr..tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (9,291 samples, 7.08%)tokio::ne..tokio::runtime::io::registration::Registration::async_io::{{closure}} (9,287 samples, 7.07%)tokio::ru..tokio::runtime::io::registration::Registration::readiness::{{closure}} (45 samples, 0.03%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (41 samples, 0.03%)__memcpy_avx512_unaligned_erms (424 samples, 0.32%)__memcpy_avx512_unaligned_erms (493 samples, 0.38%)__memcpy_avx512_unaligned_erms (298 samples, 0.23%)syscall (1,105 samples, 0.84%)[unknown] (1,095 samples, 0.83%)[unknown] (1,091 samples, 0.83%)[unknown] (1,049 samples, 0.80%)[unknown] (998 samples, 0.76%)[unknown] (907 samples, 0.69%)[unknown] (710 samples, 0.54%)[unknown] (635 samples, 0.48%)[unknown] (538 samples, 0.41%)[unknown] (358 samples, 0.27%)[unknown] (256 samples, 0.19%)[unknown] (153 samples, 0.12%)[unknown] (96 samples, 0.07%)[unknown] (81 samples, 0.06%)tokio::runtime::context::with_scheduler (36 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (31 samples, 0.02%)tokio::runtime::context::with_scheduler::{{closure}} (27 samples, 0.02%)tokio::runtime::context::scoped::Scoped<T>::with (27 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (25 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (15 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (340 samples, 0.26%)core::sync::atomic::atomic_add (340 samples, 0.26%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (354 samples, 0.27%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (367 samples, 0.28%)[unknown] (95 samples, 0.07%)[unknown] (93 samples, 0.07%)[unknown] (92 samples, 0.07%)[unknown] (90 samples, 0.07%)[unknown] (82 samples, 0.06%)[unknown] (73 samples, 0.06%)[unknown] (63 samples, 0.05%)[unknown] (44 samples, 0.03%)[unknown] (40 samples, 0.03%)[unknown] (35 samples, 0.03%)[unknown] (30 samples, 0.02%)[unknown] (22 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (17 samples, 0.01%)tokio::runtime::driver::Handle::unpark (99 samples, 0.08%)tokio::runtime::driver::IoHandle::unpark (99 samples, 0.08%)tokio::runtime::io::driver::Handle::unpark (99 samples, 0.08%)mio::waker::Waker::wake (99 samples, 0.08%)mio::sys::unix::waker::fdbased::Waker::wake (99 samples, 0.08%)mio::sys::unix::waker::eventfd::WakerInternal::wake (99 samples, 0.08%)<&std::fs::File as std::io::Write>::write (99 samples, 0.08%)std::sys::pal::unix::fs::File::write (99 samples, 0.08%)std::sys::pal::unix::fd::FileDesc::write (99 samples, 0.08%)__GI___libc_write (99 samples, 0.08%)__GI___libc_write (99 samples, 0.08%)tokio::runtime::context::with_scheduler (1,615 samples, 1.23%)std::thread::local::LocalKey<T>::try_with (1,613 samples, 1.23%)tokio::runtime::context::with_scheduler::{{closure}} (1,612 samples, 1.23%)tokio::runtime::context::scoped::Scoped<T>::with (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (1,609 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (1,609 samples, 1.23%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (101 samples, 0.08%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (101 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_option_task_without_yield (1,647 samples, 1.25%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task (1,646 samples, 1.25%)tokio::runtime::scheduler::multi_thread::worker::with_current (1,646 samples, 1.25%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (23 samples, 0.02%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (18 samples, 0.01%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (104 samples, 0.08%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (60 samples, 0.05%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (57 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (49 samples, 0.04%)core::sync::atomic::AtomicU32::compare_exchange (38 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (38 samples, 0.03%)__memcpy_avx512_unaligned_erms (162 samples, 0.12%)__memcpy_avx512_unaligned_erms (34 samples, 0.03%)__GI___lll_lock_wake_private (127 samples, 0.10%)[unknown] (125 samples, 0.10%)[unknown] (124 samples, 0.09%)[unknown] (119 samples, 0.09%)[unknown] (110 samples, 0.08%)[unknown] (106 samples, 0.08%)[unknown] (87 samples, 0.07%)[unknown] (82 samples, 0.06%)[unknown] (51 samples, 0.04%)[unknown] (27 samples, 0.02%)[unknown] (19 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (77 samples, 0.06%)[unknown] (1,207 samples, 0.92%)[unknown] (1,146 samples, 0.87%)[unknown] (1,126 samples, 0.86%)[unknown] (1,091 samples, 0.83%)[unknown] (1,046 samples, 0.80%)[unknown] (962 samples, 0.73%)[unknown] (914 samples, 0.70%)[unknown] (848 samples, 0.65%)[unknown] (774 samples, 0.59%)[unknown] (580 samples, 0.44%)[unknown] (456 samples, 0.35%)[unknown] (305 samples, 0.23%)[unknown] (85 samples, 0.06%)__GI_mprotect (2,474 samples, 1.88%)_..[unknown] (2,457 samples, 1.87%)[..[unknown] (2,440 samples, 1.86%)[..[unknown] (2,436 samples, 1.86%)[..[unknown] (2,435 samples, 1.85%)[..[unknown] (2,360 samples, 1.80%)[..[unknown] (2,203 samples, 1.68%)[unknown] (1,995 samples, 1.52%)[unknown] (1,709 samples, 1.30%)[unknown] (1,524 samples, 1.16%)[unknown] (1,193 samples, 0.91%)[unknown] (865 samples, 0.66%)[unknown] (539 samples, 0.41%)[unknown] (259 samples, 0.20%)[unknown] (80 samples, 0.06%)[unknown] (29 samples, 0.02%)sysmalloc (3,786 samples, 2.88%)sy..grow_heap (2,509 samples, 1.91%)g.._int_malloc (4,038 samples, 3.08%)_in..unlink_chunk (31 samples, 0.02%)alloc::alloc::exchange_malloc (4,335 samples, 3.30%)all..<alloc::alloc::Global as core::alloc::Allocator>::allocate (4,329 samples, 3.30%)<al..alloc::alloc::Global::alloc_impl (4,329 samples, 3.30%)all..alloc::alloc::alloc (4,329 samples, 3.30%)all..__rdl_alloc (4,329 samples, 3.30%)__r..std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (4,329 samples, 3.30%)std..std::sys::pal::unix::alloc::aligned_malloc (4,329 samples, 3.30%)std..__posix_memalign (4,297 samples, 3.27%)__p..__posix_memalign (4,297 samples, 3.27%)__p.._mid_memalign (4,297 samples, 3.27%)_mi.._int_memalign (4,149 samples, 3.16%)_in..sysmalloc (18 samples, 0.01%)core::option::Option<T>::map (6,666 samples, 5.08%)core::..tokio::task::spawn::spawn_inner::{{closure}} (6,665 samples, 5.08%)tokio:..tokio::runtime::scheduler::Handle::spawn (6,665 samples, 5.08%)tokio:..tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (6,664 samples, 5.08%)tokio:..tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (6,661 samples, 5.07%)tokio:..tokio::runtime::task::list::OwnedTasks<S>::bind (4,692 samples, 3.57%)toki..tokio::runtime::task::new_task (4,579 samples, 3.49%)tok..tokio::runtime::task::raw::RawTask::new (4,579 samples, 3.49%)tok..tokio::runtime::task::core::Cell<T,S>::new (4,579 samples, 3.49%)tok..alloc::boxed::Box<T>::new (4,389 samples, 3.34%)all..tokio::runtime::context::current::with_current (7,636 samples, 5.82%)tokio::..std::thread::local::LocalKey<T>::try_with (7,635 samples, 5.81%)std::th..tokio::runtime::context::current::with_current::{{closure}} (7,188 samples, 5.47%)tokio::..tokio::task::spawn::spawn (7,670 samples, 5.84%)tokio::..tokio::task::spawn::spawn_inner (7,670 samples, 5.84%)tokio::..tokio::runtime::task::id::Id::next (24 samples, 0.02%)core::sync::atomic::AtomicU64::fetch_add (24 samples, 0.02%)core::sync::atomic::atomic_add (24 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (62,691 samples, 47.75%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (62,691 samples, 47.75%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (18,228 samples, 13.88%)torrust_tracker::serv..torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (18,226 samples, 13.88%)torrust_tracker::serv..torrust_tracker::servers::udp::server::Udp::spawn_request_processor (7,679 samples, 5.85%)torrust..__memcpy_avx512_unaligned_erms (38 samples, 0.03%)__memcpy_avx512_unaligned_erms (407 samples, 0.31%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (411 samples, 0.31%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (411 samples, 0.31%)tokio::runtime::task::core::Core<T,S>::poll (63,150 samples, 48.10%)tokio::runtime::task::core::Core<T,S>::polltokio::runtime::task::core::Core<T,S>::drop_future_or_output (459 samples, 0.35%)tokio::runtime::task::core::Core<T,S>::set_stage (459 samples, 0.35%)__memcpy_avx512_unaligned_erms (16 samples, 0.01%)__memcpy_avx512_unaligned_erms (398 samples, 0.30%)__memcpy_avx512_unaligned_erms (325 samples, 0.25%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (330 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (330 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::set_stage (731 samples, 0.56%)tokio::runtime::task::harness::poll_future (63,908 samples, 48.67%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (63,908 samples, 48.67%)std::panic::catch_unwindstd::panicking::try (63,908 samples, 48.67%)std::panicking::trystd::panicking::try::do_call (63,908 samples, 48.67%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (63,908 samples, 48.67%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()..tokio::runtime::task::harness::poll_future::{{closure}} (63,908 samples, 48.67%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::store_output (758 samples, 0.58%)tokio::runtime::coop::budget (65,027 samples, 49.53%)tokio::runtime::coop::budgettokio::runtime::coop::with_budget (65,027 samples, 49.53%)tokio::runtime::coop::with_budgettokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (65,009 samples, 49.51%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}}tokio::runtime::task::LocalNotified<S>::run (65,003 samples, 49.51%)tokio::runtime::task::LocalNotified<S>::runtokio::runtime::task::raw::RawTask::poll (65,003 samples, 49.51%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (64,538 samples, 49.15%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (64,493 samples, 49.12%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (63,919 samples, 48.68%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (93 samples, 0.07%)syscall (2,486 samples, 1.89%)s..[unknown] (2,424 samples, 1.85%)[..[unknown] (2,416 samples, 1.84%)[..[unknown] (2,130 samples, 1.62%)[unknown] (2,013 samples, 1.53%)[unknown] (1,951 samples, 1.49%)[unknown] (1,589 samples, 1.21%)[unknown] (1,415 samples, 1.08%)[unknown] (1,217 samples, 0.93%)[unknown] (820 samples, 0.62%)[unknown] (564 samples, 0.43%)[unknown] (360 samples, 0.27%)[unknown] (244 samples, 0.19%)[unknown] (194 samples, 0.15%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (339 samples, 0.26%)core::sync::atomic::AtomicUsize::fetch_add (337 samples, 0.26%)core::sync::atomic::atomic_add (337 samples, 0.26%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (364 samples, 0.28%)[unknown] (154 samples, 0.12%)[unknown] (152 samples, 0.12%)[unknown] (143 samples, 0.11%)[unknown] (139 samples, 0.11%)[unknown] (131 samples, 0.10%)[unknown] (123 samples, 0.09%)[unknown] (110 samples, 0.08%)[unknown] (80 samples, 0.06%)[unknown] (74 samples, 0.06%)[unknown] (65 samples, 0.05%)[unknown] (64 samples, 0.05%)[unknown] (47 samples, 0.04%)[unknown] (44 samples, 0.03%)[unknown] (43 samples, 0.03%)[unknown] (40 samples, 0.03%)[unknown] (26 samples, 0.02%)[unknown] (20 samples, 0.02%)__GI___libc_write (158 samples, 0.12%)__GI___libc_write (158 samples, 0.12%)mio::sys::unix::waker::eventfd::WakerInternal::wake (159 samples, 0.12%)<&std::fs::File as std::io::Write>::write (159 samples, 0.12%)std::sys::pal::unix::fs::File::write (159 samples, 0.12%)std::sys::pal::unix::fd::FileDesc::write (159 samples, 0.12%)tokio::runtime::driver::Handle::unpark (168 samples, 0.13%)tokio::runtime::driver::IoHandle::unpark (168 samples, 0.13%)tokio::runtime::io::driver::Handle::unpark (168 samples, 0.13%)mio::waker::Waker::wake (165 samples, 0.13%)mio::sys::unix::waker::fdbased::Waker::wake (165 samples, 0.13%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (68,159 samples, 51.91%)tokio::runtime::scheduler::multi_thread::worker::Context::run_tasktokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (3,024 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (3,023 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (3,022 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (171 samples, 0.13%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (171 samples, 0.13%)core::option::Option<T>::or_else (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::tune_global_queue_interval (53 samples, 0.04%)tokio::runtime::scheduler::multi_thread::stats::Stats::tuned_global_queue_interval (53 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (107 samples, 0.08%)__GI___libc_free (17 samples, 0.01%)_int_free (17 samples, 0.01%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Dying,K,V>::deallocating_end (18 samples, 0.01%)alloc::collections::btree::navigate::<impl alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>>::deallocating_end (18 samples, 0.01%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::LeafOrInternal>::deallocate_and_ascend (18 samples, 0.01%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (18 samples, 0.01%)alloc::alloc::dealloc (18 samples, 0.01%)__rdl_dealloc (18 samples, 0.01%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (18 samples, 0.01%)alloc::collections::btree::map::IntoIter<K,V,A>::dying_next (19 samples, 0.01%)tokio::runtime::task::Task<S>::shutdown (26 samples, 0.02%)tokio::runtime::task::raw::RawTask::shutdown (26 samples, 0.02%)tokio::runtime::task::raw::shutdown (26 samples, 0.02%)tokio::runtime::task::harness::Harness<T,S>::shutdown (26 samples, 0.02%)tokio::runtime::task::harness::cancel_task (26 samples, 0.02%)std::panic::catch_unwind (26 samples, 0.02%)std::panicking::try (26 samples, 0.02%)std::panicking::try::do_call (26 samples, 0.02%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (26 samples, 0.02%)core::ops::function::FnOnce::call_once (26 samples, 0.02%)tokio::runtime::task::harness::cancel_task::{{closure}} (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (26 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (26 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::core::Tracker> (26 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)core::ptr::drop_in_place<std::sync::rwlock::RwLock<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)core::mem::drop (26 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,NodeType>,alloc::collections::btree::node::marker::KV>::drop_key_val (24 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::assume_init_drop (24 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (24 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (21 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>> (20 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<torrust_tracker_torrent_repository::entry::Torrent>> (20 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker_torrent_repository::entry::Torrent> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::peer::Id,alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (20 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)core::mem::drop (20 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker_primitives::peer::Id,alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (20 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::pre_shutdown (33 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::close_and_shutdown_all (33 samples, 0.03%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (114 samples, 0.09%)alloc::sync::Arc<T,A>::inner (114 samples, 0.09%)core::ptr::non_null::NonNull<T>::as_ref (114 samples, 0.09%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (108 samples, 0.08%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (108 samples, 0.08%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (106 samples, 0.08%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (49 samples, 0.04%)alloc::sync::Arc<T,A>::inner (49 samples, 0.04%)core::ptr::non_null::NonNull<T>::as_ref (49 samples, 0.04%)core::num::<impl u32>::wrapping_sub (132 samples, 0.10%)core::sync::atomic::AtomicU64::load (40 samples, 0.03%)core::sync::atomic::atomic_load (40 samples, 0.03%)tokio::loom::std::atomic_u32::AtomicU32::unsync_load (48 samples, 0.04%)core::sync::atomic::AtomicU32::load (48 samples, 0.04%)core::sync::atomic::atomic_load (48 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (65 samples, 0.05%)alloc::sync::Arc<T,A>::inner (65 samples, 0.05%)core::ptr::non_null::NonNull<T>::as_ref (65 samples, 0.05%)core::num::<impl u32>::wrapping_sub (50 samples, 0.04%)core::sync::atomic::AtomicU32::load (55 samples, 0.04%)core::sync::atomic::atomic_load (55 samples, 0.04%)core::sync::atomic::AtomicU64::load (80 samples, 0.06%)core::sync::atomic::atomic_load (80 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::pack (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (666 samples, 0.51%)tokio::runtime::scheduler::multi_thread::queue::unpack (147 samples, 0.11%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (1,036 samples, 0.79%)tokio::runtime::scheduler::multi_thread::queue::unpack (46 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_searching (49 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_searching (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (2,414 samples, 1.84%)t..tokio::util::rand::FastRand::fastrand_n (24 samples, 0.02%)tokio::util::rand::FastRand::fastrand (24 samples, 0.02%)std::sys_common::backtrace::__rust_begin_short_backtrace (98,136 samples, 74.74%)std::sys_common::backtrace::__rust_begin_short_backtracetokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}} (98,136 samples, 74.74%)tokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}}tokio::runtime::blocking::pool::Inner::run (98,136 samples, 74.74%)tokio::runtime::blocking::pool::Inner::runtokio::runtime::blocking::pool::Task::run (98,042 samples, 74.67%)tokio::runtime::blocking::pool::Task::runtokio::runtime::task::UnownedTask<S>::run (98,042 samples, 74.67%)tokio::runtime::task::UnownedTask<S>::runtokio::runtime::task::raw::RawTask::poll (98,042 samples, 74.67%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (98,042 samples, 74.67%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (98,042 samples, 74.67%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (98,042 samples, 74.67%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::task::harness::poll_future (98,042 samples, 74.67%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (98,042 samples, 74.67%)std::panic::catch_unwindstd::panicking::try (98,042 samples, 74.67%)std::panicking::trystd::panicking::try::do_call (98,042 samples, 74.67%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (98,042 samples, 74.67%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncetokio::runtime::task::harness::poll_future::{{closure}} (98,042 samples, 74.67%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::poll (98,042 samples, 74.67%)tokio::runtime::task::core::Core<T,S>::polltokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (98,042 samples, 74.67%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (98,042 samples, 74.67%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (98,042 samples, 74.67%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::polltokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}}tokio::runtime::scheduler::multi_thread::worker::run (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::runtokio::runtime::context::runtime::enter_runtime (98,042 samples, 74.67%)tokio::runtime::context::runtime::enter_runtimetokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}tokio::runtime::context::set_scheduler (98,042 samples, 74.67%)tokio::runtime::context::set_schedulerstd::thread::local::LocalKey<T>::with (98,042 samples, 74.67%)std::thread::local::LocalKey<T>::withstd::thread::local::LocalKey<T>::try_with (98,042 samples, 74.67%)std::thread::local::LocalKey<T>::try_withtokio::runtime::context::set_scheduler::{{closure}} (98,042 samples, 74.67%)tokio::runtime::context::set_scheduler::{{closure}}tokio::runtime::context::scoped::Scoped<T>::set (98,042 samples, 74.67%)tokio::runtime::context::scoped::Scoped<T>::settokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}}tokio::runtime::scheduler::multi_thread::worker::Context::run (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::Context::runstd::panic::catch_unwind (98,137 samples, 74.74%)std::panic::catch_unwindstd::panicking::try (98,137 samples, 74.74%)std::panicking::trystd::panicking::try::do_call (98,137 samples, 74.74%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (98,137 samples, 74.74%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncestd::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}} (98,137 samples, 74.74%)std::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}}<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (98,139 samples, 74.74%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (98,139 samples, 74.74%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_oncecore::ops::function::FnOnce::call_once{{vtable.shim}} (98,139 samples, 74.74%)core::ops::function::FnOnce::call_once{{vtable.shim}}std::thread::Builder::spawn_unchecked_::{{closure}} (98,139 samples, 74.74%)std::thread::Builder::spawn_unchecked_::{{closure}}clone3 (98,205 samples, 74.79%)clone3start_thread (98,205 samples, 74.79%)start_threadstd::sys::pal::unix::thread::Thread::new::thread_start (98,158 samples, 74.76%)std::sys::pal::unix::thread::Thread::new::thread_startcore::ptr::drop_in_place<std::sys::pal::unix::stack_overflow::Handler> (19 samples, 0.01%)<std::sys::pal::unix::stack_overflow::Handler as core::ops::drop::Drop>::drop (19 samples, 0.01%)std::sys::pal::unix::stack_overflow::imp::drop_handler (19 samples, 0.01%)__GI_munmap (19 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (17 samples, 0.01%)[unknown] (16 samples, 0.01%)core::fmt::Formatter::pad_integral (112 samples, 0.09%)core::fmt::Formatter::pad_integral::write_prefix (59 samples, 0.04%)core::fmt::Formatter::pad_integral (16 samples, 0.01%)core::fmt::write (20 samples, 0.02%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (19 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (51 samples, 0.04%)rand_chacha::guts::round (18 samples, 0.01%)rand_chacha::guts::refill_wide::impl_avx2 (26 samples, 0.02%)rand_chacha::guts::refill_wide::fn_impl (26 samples, 0.02%)rand_chacha::guts::refill_wide_impl (26 samples, 0.02%)rand_chacha::guts::refill_wide (14 samples, 0.01%)std_detect::detect::arch::x86::__is_feature_detected::avx2 (14 samples, 0.01%)std_detect::detect::check_for (14 samples, 0.01%)std_detect::detect::cache::test (14 samples, 0.01%)std_detect::detect::cache::Cache::test (14 samples, 0.01%)core::sync::atomic::AtomicUsize::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)core::cell::RefCell<T>::borrow_mut (81 samples, 0.06%)core::cell::RefCell<T>::try_borrow_mut (81 samples, 0.06%)core::cell::BorrowRefMut::new (81 samples, 0.06%)std::sys::pal::unix::time::Timespec::now (164 samples, 0.12%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (106 samples, 0.08%)tokio::runtime::coop::budget (105 samples, 0.08%)tokio::runtime::coop::with_budget (105 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (96 samples, 0.07%)std::sys::pal::unix::time::Timespec::sub_timespec (35 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::lock_contended (15 samples, 0.01%)syscall (90 samples, 0.07%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (21 samples, 0.02%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run (61 samples, 0.05%)tokio::runtime::context::runtime::enter_runtime (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (61 samples, 0.05%)tokio::runtime::context::set_scheduler (61 samples, 0.05%)std::thread::local::LocalKey<T>::with (61 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (61 samples, 0.05%)tokio::runtime::context::set_scheduler::{{closure}} (61 samples, 0.05%)tokio::runtime::context::scoped::Scoped<T>::set (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Context::run (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (19 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (17 samples, 0.01%)tokio::runtime::context::CONTEXT::__getit (14 samples, 0.01%)core::cell::Cell<T>::get (14 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (22 samples, 0.02%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (22 samples, 0.02%)tokio::runtime::context::set_current_task_id (22 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (22 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (112 samples, 0.09%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (111 samples, 0.08%)tokio::runtime::task::harness::poll_future (125 samples, 0.10%)std::panic::catch_unwind (125 samples, 0.10%)std::panicking::try (125 samples, 0.10%)std::panicking::try::do_call (125 samples, 0.10%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (125 samples, 0.10%)tokio::runtime::task::harness::poll_future::{{closure}} (125 samples, 0.10%)tokio::runtime::task::core::Core<T,S>::poll (125 samples, 0.10%)tokio::runtime::task::raw::poll (157 samples, 0.12%)tokio::runtime::task::harness::Harness<T,S>::poll (135 samples, 0.10%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (135 samples, 0.10%)tokio::runtime::time::Driver::park_internal (15 samples, 0.01%)torrust_tracker::bootstrap::logging::INIT (17 samples, 0.01%)__memcpy_avx512_unaligned_erms (397 samples, 0.30%)_int_free (24 samples, 0.02%)_int_malloc (132 samples, 0.10%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE::META (570 samples, 0.43%)__GI___lll_lock_wait_private (22 samples, 0.02%)futex_wait (14 samples, 0.01%)__memcpy_avx512_unaligned_erms (299 samples, 0.23%)_int_free (16 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE (361 samples, 0.27%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (41 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (23 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (53 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (14 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (63 samples, 0.05%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (21 samples, 0.02%)__GI___libc_malloc (18 samples, 0.01%)alloc::vec::Vec<T>::with_capacity (116 samples, 0.09%)alloc::vec::Vec<T,A>::with_capacity_in (116 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (116 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (116 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (116 samples, 0.09%)alloc::alloc::Global::alloc_impl (116 samples, 0.09%)alloc::alloc::alloc (116 samples, 0.09%)__rdl_alloc (116 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (116 samples, 0.09%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (53 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (53 samples, 0.04%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (53 samples, 0.04%)_int_malloc (21 samples, 0.02%)[unknown] (36 samples, 0.03%)[unknown] (16 samples, 0.01%)core::mem::zeroed (27 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::zeroed (27 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::write_bytes (27 samples, 0.02%)core::intrinsics::write_bytes (27 samples, 0.02%)[unknown] (27 samples, 0.02%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (64 samples, 0.05%)mio::net::udp::UdpSocket::recv_from (49 samples, 0.04%)mio::io_source::IoSource<T>::do_io (49 samples, 0.04%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (49 samples, 0.04%)mio::net::udp::UdpSocket::recv_from::{{closure}} (49 samples, 0.04%)std::net::udp::UdpSocket::recv_from (49 samples, 0.04%)std::sys_common::net::UdpSocket::recv_from (49 samples, 0.04%)std::sys::pal::unix::net::Socket::recv_from (49 samples, 0.04%)std::sys::pal::unix::net::Socket::recv_from_with_flags (49 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (271 samples, 0.21%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (143 samples, 0.11%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (141 samples, 0.11%)tokio::runtime::io::registration::Registration::clear_readiness (15 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::clear_readiness (15 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (15 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (359 samples, 0.27%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (346 samples, 0.26%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (39 samples, 0.03%)tokio::task::spawn::spawn (39 samples, 0.03%)tokio::task::spawn::spawn_inner (39 samples, 0.03%)tokio::runtime::context::current::with_current (39 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (39 samples, 0.03%)tokio::runtime::context::current::with_current::{{closure}} (39 samples, 0.03%)core::option::Option<T>::map (39 samples, 0.03%)tokio::task::spawn::spawn_inner::{{closure}} (39 samples, 0.03%)tokio::runtime::scheduler::Handle::spawn (39 samples, 0.03%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (39 samples, 0.03%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (39 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::bind (34 samples, 0.03%)all (131,301 samples, 100%)tokio-runtime-w (131,061 samples, 99.82%)tokio-runtime-w \ No newline at end of file From 608585eaf65a08df28fbeb82400647fd15f78a25 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 4 Apr 2024 17:12:43 +0100 Subject: [PATCH 0277/1297] chore: add new cargo dependency: crossbeam-skiplist It will be used to create a new torrent repository implementation that allos adding torrents in parallel. That could be potencially faster than BTreeMap in a write intensive context. --- Cargo.lock | 12 ++++++++++++ Cargo.toml | 5 +++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e77b5de6d..74d9aaafd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1027,6 +1027,16 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-skiplist" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df29de440c58ca2cc6e587ec3d22347551a32435fbde9d2bff64e78a9ffa151b" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.19" @@ -3908,6 +3918,7 @@ dependencies = [ "clap", "colored", "config", + "crossbeam-skiplist", "derive_more", "fern", "futures", @@ -4013,6 +4024,7 @@ version = "3.0.0-alpha.12-develop" dependencies = [ "async-std", "criterion", + "crossbeam-skiplist", "futures", "rstest", "tokio", diff --git a/Cargo.toml b/Cargo.toml index d045b945a..8c1df0685 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } colored = "2" config = "0" +crossbeam-skiplist = "0.1" derive_more = "0" fern = "0" futures = "0" @@ -63,8 +64,8 @@ serde_json = "1" serde_repr = "0" thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "packages/configuration" } torrust-tracker-clock = { version = "3.0.0-alpha.12-develop", path = "packages/clock" } +torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "packages/configuration" } torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12-develop", path = "contrib/bencode" } torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "packages/located-error" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } @@ -105,4 +106,4 @@ opt-level = 3 [profile.release-debug] inherits = "release" -debug = true \ No newline at end of file +debug = true From 642d6be04ae968a2b170ede2c379183a792bd782 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 4 Apr 2024 17:14:43 +0100 Subject: [PATCH 0278/1297] feat: new torrent repository using crossbeam_skiplist::SkipMap SkipMap is an ordered map based on a lock-free skip list. It's al alternative to BTreeMap which supports concurrent access across multiple threads. One of the performance problems with the current solution is we can only add one torrent at the time because threads need to lock the whole BTreeMap. The SkipMap should avoid that problem. More info about SkiMap: https://docs.rs/crossbeam-skiplist/latest/crossbeam_skiplist/struct.SkipMap.html#method.remove The aquatic UDP load test was executed with the current implementation and the new one: Current Implementation: Requests out: 397287.37/second Responses in: 357549.15/second - Connect responses: 177073.94 - Announce responses: 176905.36 - Scrape responses: 3569.85 - Error responses: 0.00 Peers per announce response: 0.00 Announce responses per info hash: - p10: 1 - p25: 1 - p50: 1 - p75: 1 - p90: 2 - p95: 3 - p99: 104 - p99.9: 287 - p100: 371 New Implementation: Requests out: 396788.68/second Responses in: 357105.27/second - Connect responses: 176662.91 - Announce responses: 176863.44 - Scrape responses: 3578.91 - Error responses: 0.00 Peers per announce response: 0.00 Announce responses per info hash: - p10: 1 - p25: 1 - p50: 1 - p75: 1 - p90: 2 - p95: 3 - p99: 105 - p99.9: 287 - p100: 351 The result is pretty similar but the benchmarking for the repository using criterios shows that this implementations is a litle bit better than the current one. --- cSpell.json | 1 + packages/torrent-repository/Cargo.toml | 5 +- .../benches/repository_benchmark.rs | 21 +++- packages/torrent-repository/src/lib.rs | 3 + .../torrent-repository/src/repository/mod.rs | 1 + .../src/repository/skip_map_mutex_std.rs | 106 ++++++++++++++++++ src/core/torrent/mod.rs | 5 +- 7 files changed, 137 insertions(+), 5 deletions(-) create mode 100644 packages/torrent-repository/src/repository/skip_map_mutex_std.rs diff --git a/cSpell.json b/cSpell.json index 0ee2f8306..0480590af 100644 --- a/cSpell.json +++ b/cSpell.json @@ -135,6 +135,7 @@ "Shareaza", "sharktorrent", "SHLVL", + "skiplist", "socketaddr", "sqllite", "subsec", diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 4cea8767f..5f1a20d32 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -16,11 +16,12 @@ rust-version.workspace = true version.workspace = true [dependencies] +crossbeam-skiplist = "0.1" futures = "0.3.29" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } -torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } torrust-tracker-clock = { version = "3.0.0-alpha.12-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } [dev-dependencies] criterion = { version = "0", features = ["async_tokio"] } diff --git a/packages/torrent-repository/benches/repository_benchmark.rs b/packages/torrent-repository/benches/repository_benchmark.rs index a3684c8e2..65608c86c 100644 --- a/packages/torrent-repository/benches/repository_benchmark.rs +++ b/packages/torrent-repository/benches/repository_benchmark.rs @@ -5,7 +5,7 @@ mod helpers; use criterion::{criterion_group, criterion_main, Criterion}; use torrust_tracker_torrent_repository::{ TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, - TorrentsRwLockTokioMutexTokio, + TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexStd, }; use crate::helpers::{asyn, sync}; @@ -45,6 +45,10 @@ fn add_one_torrent(c: &mut Criterion) { .iter_custom(asyn::add_one_torrent::); }); + group.bench_function("SkipMapMutexStd", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + group.finish(); } @@ -89,6 +93,11 @@ fn add_multiple_torrents_in_parallel(c: &mut Criterion) { .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); }); + group.bench_function("SkipMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + group.finish(); } @@ -133,6 +142,11 @@ fn update_one_torrent_in_parallel(c: &mut Criterion) { .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); }); + group.bench_function("SkipMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + group.finish(); } @@ -178,6 +192,11 @@ fn update_multiple_torrents_in_parallel(c: &mut Criterion) { }); }); + group.bench_function("SkipMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + group.finish(); } diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 8bb1b6def..f7c19624c 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use repository::skip_map_mutex_std::CrossbeamSkipList; use torrust_tracker_clock::clock; pub mod entry; @@ -16,6 +17,8 @@ pub type TorrentsRwLockTokio = repository::RwLockTokio; pub type TorrentsRwLockTokioMutexStd = repository::RwLockTokio; pub type TorrentsRwLockTokioMutexTokio = repository::RwLockTokio; +pub type TorrentsSkipMapMutexStd = CrossbeamSkipList; + /// This code needs to be copied into each crate. /// Working version, for production. #[cfg(not(test))] diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs index 494040c9d..7ede1f87a 100644 --- a/packages/torrent-repository/src/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -11,6 +11,7 @@ pub mod rw_lock_std_mutex_tokio; pub mod rw_lock_tokio; pub mod rw_lock_tokio_mutex_std; pub mod rw_lock_tokio_mutex_tokio; +pub mod skip_map_mutex_std; use std::fmt::Debug; diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs new file mode 100644 index 000000000..aa1f43826 --- /dev/null +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -0,0 +1,106 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use crossbeam_skiplist::SkipMap; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; + +use super::Repository; +use crate::entry::{Entry, EntrySync}; +use crate::{EntryMutexStd, EntrySingle}; + +#[derive(Default, Debug)] +pub struct CrossbeamSkipList { + torrents: SkipMap, +} + +impl Repository for CrossbeamSkipList +where + EntryMutexStd: EntrySync, + EntrySingle: Entry, +{ + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); + entry.value().insert_or_update_peer_and_get_stats(peer) + } + + fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.torrents.get(key); + maybe_entry.map(|entry| entry.value().clone()) + } + + fn get_metrics(&self) -> TorrentsMetrics { + let mut metrics = TorrentsMetrics::default(); + + for entry in &self.torrents { + let stats = entry.value().lock().expect("it should get a lock").get_stats(); + metrics.complete += u64::from(stats.complete); + metrics.downloaded += u64::from(stats.downloaded); + metrics.incomplete += u64::from(stats.incomplete); + metrics.torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + match pagination { + Some(pagination) => self + .torrents + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .torrents + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + for (info_hash, completed) in persistent_torrents { + if self.torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexStd::new( + EntrySingle { + peers: BTreeMap::default(), + downloaded: *completed, + } + .into(), + ); + + // Since SkipMap is lock-free the torrent could have been inserted + // after checking if it exists. + self.torrents.get_or_insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|entry| entry.value().clone()) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { + entry.value().remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + for entry in &self.torrents { + if entry.value().is_good(policy) { + continue; + } + + entry.remove(); + } + } +} diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index ab78de683..5d42e8b4d 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -26,6 +26,7 @@ //! Peer that don not have a full copy of the torrent data are called "leechers". //! -use torrust_tracker_torrent_repository::TorrentsRwLockStdMutexStd; +use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; -pub type Torrents = TorrentsRwLockStdMutexStd; // Currently Used +//pub type Torrents = TorrentsRwLockStdMutexStd; // Currently Used +pub type Torrents = TorrentsSkipMapMutexStd; // Currently Used From eec20247e146b0b822e86061943f4c899c93658f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 5 Apr 2024 18:27:17 +0100 Subject: [PATCH 0279/1297] chore: ignore crossbeam-skiplist crate in cargo-machete It's been used in the src/packages/torrent-repository package. --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 8c1df0685..f440799cc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -77,7 +77,7 @@ url = "2" uuid = { version = "1", features = ["v4"] } [package.metadata.cargo-machete] -ignored = ["serde_bytes"] +ignored = ["serde_bytes", "crossbeam-skiplist"] [dev-dependencies] local-ip-address = "0" From 098928592f821cb2aa779746d6e40b71703c529b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 5 Apr 2024 18:29:24 +0100 Subject: [PATCH 0280/1297] refactor: separate torrent repository trait from implementations There are now more implementations. --- packages/torrent-repository/src/lib.rs | 14 ++++---- .../torrent-repository/src/repository/mod.rs | 34 ------------------- .../src/repository/rw_lock_std.rs | 16 +++++++++ .../src/repository/rw_lock_tokio.rs | 18 ++++++++++ .../tests/repository/mod.rs | 3 +- src/core/torrent/mod.rs | 2 -- 6 files changed, 44 insertions(+), 43 deletions(-) diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index f7c19624c..ccaf579e3 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,5 +1,7 @@ use std::sync::Arc; +use repository::rw_lock_std::RwLockStd; +use repository::rw_lock_tokio::RwLockTokio; use repository::skip_map_mutex_std::CrossbeamSkipList; use torrust_tracker_clock::clock; @@ -10,12 +12,12 @@ pub type EntrySingle = entry::Torrent; pub type EntryMutexStd = Arc>; pub type EntryMutexTokio = Arc>; -pub type TorrentsRwLockStd = repository::RwLockStd; -pub type TorrentsRwLockStdMutexStd = repository::RwLockStd; -pub type TorrentsRwLockStdMutexTokio = repository::RwLockStd; -pub type TorrentsRwLockTokio = repository::RwLockTokio; -pub type TorrentsRwLockTokioMutexStd = repository::RwLockTokio; -pub type TorrentsRwLockTokioMutexTokio = repository::RwLockTokio; +pub type TorrentsRwLockStd = RwLockStd; +pub type TorrentsRwLockStdMutexStd = RwLockStd; +pub type TorrentsRwLockStdMutexTokio = RwLockStd; +pub type TorrentsRwLockTokio = RwLockTokio; +pub type TorrentsRwLockTokioMutexStd = RwLockTokio; +pub type TorrentsRwLockTokioMutexTokio = RwLockTokio; pub type TorrentsSkipMapMutexStd = CrossbeamSkipList; diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs index 7ede1f87a..975a876d8 100644 --- a/packages/torrent-repository/src/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -41,37 +41,3 @@ pub trait RepositoryAsync: Debug + Default + Sized + 'static { peer: &peer::Peer, ) -> impl std::future::Future + Send; } - -#[derive(Default, Debug)] -pub struct RwLockStd { - torrents: std::sync::RwLock>, -} - -#[derive(Default, Debug)] -pub struct RwLockTokio { - torrents: tokio::sync::RwLock>, -} - -impl RwLockStd { - /// # Panics - /// - /// Panics if unable to get a lock. - pub fn write( - &self, - ) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { - self.torrents.write().expect("it should get lock") - } -} - -impl RwLockTokio { - pub fn write( - &self, - ) -> impl std::future::Future< - Output = tokio::sync::RwLockWriteGuard< - '_, - std::collections::BTreeMap, - >, - > { - self.torrents.write() - } -} diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs index 9d7f29416..e9074a271 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std.rs @@ -11,6 +11,22 @@ use super::Repository; use crate::entry::Entry; use crate::{EntrySingle, TorrentsRwLockStd}; +#[derive(Default, Debug)] +pub struct RwLockStd { + pub(crate) torrents: std::sync::RwLock>, +} + +impl RwLockStd { + /// # Panics + /// + /// Panics if unable to get a lock. + pub fn write( + &self, + ) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { + self.torrents.write().expect("it should get lock") + } +} + impl TorrentsRwLockStd { fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> where diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs index fa84e2451..d84074eaf 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio.rs @@ -11,6 +11,24 @@ use super::RepositoryAsync; use crate::entry::Entry; use crate::{EntrySingle, TorrentsRwLockTokio}; +#[derive(Default, Debug)] +pub struct RwLockTokio { + pub(crate) torrents: tokio::sync::RwLock>, +} + +impl RwLockTokio { + pub fn write( + &self, + ) -> impl std::future::Future< + Output = tokio::sync::RwLockWriteGuard< + '_, + std::collections::BTreeMap, + >, + > { + self.torrents.write() + } +} + impl TorrentsRwLockTokio { async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> where diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 7ffe17dd7..117f3c0a6 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -8,7 +8,8 @@ use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::{NumberOfBytes, PersistentTorrents}; use torrust_tracker_torrent_repository::entry::Entry as _; -use torrust_tracker_torrent_repository::repository::{RwLockStd, RwLockTokio}; +use torrust_tracker_torrent_repository::repository::rw_lock_std::RwLockStd; +use torrust_tracker_torrent_repository::repository::rw_lock_tokio::RwLockTokio; use torrust_tracker_torrent_repository::EntrySingle; use crate::common::repo::Repo; diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index 5d42e8b4d..286a7e047 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -25,8 +25,6 @@ //! - The number of peers that have NOT completed downloading the torrent and are still active, that means they are actively participating in the network. //! Peer that don not have a full copy of the torrent data are called "leechers". //! - use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; -//pub type Torrents = TorrentsRwLockStdMutexStd; // Currently Used pub type Torrents = TorrentsSkipMapMutexStd; // Currently Used From 12f54e703e78af677fbd4456c359f580e83b1c44 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 8 Apr 2024 14:07:15 +0100 Subject: [PATCH 0281/1297] test: add tests for new torrent repository using SkipMap --- .../src/repository/skip_map_mutex_std.rs | 2 +- .../torrent-repository/tests/common/repo.rs | 165 +++++++++++------- .../tests/repository/mod.rs | 108 ++++++++++-- 3 files changed, 193 insertions(+), 82 deletions(-) diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index aa1f43826..0c0127b15 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -15,7 +15,7 @@ use crate::{EntryMutexStd, EntrySingle}; #[derive(Default, Debug)] pub struct CrossbeamSkipList { - torrents: SkipMap, + pub torrents: SkipMap, } impl Repository for CrossbeamSkipList diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 3a4b53d2f..5a86aa3cf 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -7,49 +7,54 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent use torrust_tracker_torrent_repository::repository::{Repository as _, RepositoryAsync as _}; use torrust_tracker_torrent_repository::{ EntrySingle, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, - TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, + TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexStd, }; #[derive(Debug)] pub(crate) enum Repo { - Std(TorrentsRwLockStd), - StdMutexStd(TorrentsRwLockStdMutexStd), - StdMutexTokio(TorrentsRwLockStdMutexTokio), - Tokio(TorrentsRwLockTokio), - TokioMutexStd(TorrentsRwLockTokioMutexStd), - TokioMutexTokio(TorrentsRwLockTokioMutexTokio), + RwLockStd(TorrentsRwLockStd), + RwLockStdMutexStd(TorrentsRwLockStdMutexStd), + RwLockStdMutexTokio(TorrentsRwLockStdMutexTokio), + RwLockTokio(TorrentsRwLockTokio), + RwLockTokioMutexStd(TorrentsRwLockTokioMutexStd), + RwLockTokioMutexTokio(TorrentsRwLockTokioMutexTokio), + SkipMapMutexStd(TorrentsSkipMapMutexStd), } impl Repo { pub(crate) async fn get(&self, key: &InfoHash) -> Option { match self { - Repo::Std(repo) => repo.get(key), - Repo::StdMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), - Repo::StdMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), - Repo::Tokio(repo) => repo.get(key).await, - Repo::TokioMutexStd(repo) => Some(repo.get(key).await?.lock().unwrap().clone()), - Repo::TokioMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), + Repo::RwLockStd(repo) => repo.get(key), + Repo::RwLockStdMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), + Repo::RwLockStdMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), + Repo::RwLockTokio(repo) => repo.get(key).await, + Repo::RwLockTokioMutexStd(repo) => Some(repo.get(key).await?.lock().unwrap().clone()), + Repo::RwLockTokioMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), + Repo::SkipMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), } } + pub(crate) async fn get_metrics(&self) -> TorrentsMetrics { match self { - Repo::Std(repo) => repo.get_metrics(), - Repo::StdMutexStd(repo) => repo.get_metrics(), - Repo::StdMutexTokio(repo) => repo.get_metrics().await, - Repo::Tokio(repo) => repo.get_metrics().await, - Repo::TokioMutexStd(repo) => repo.get_metrics().await, - Repo::TokioMutexTokio(repo) => repo.get_metrics().await, + Repo::RwLockStd(repo) => repo.get_metrics(), + Repo::RwLockStdMutexStd(repo) => repo.get_metrics(), + Repo::RwLockStdMutexTokio(repo) => repo.get_metrics().await, + Repo::RwLockTokio(repo) => repo.get_metrics().await, + Repo::RwLockTokioMutexStd(repo) => repo.get_metrics().await, + Repo::RwLockTokioMutexTokio(repo) => repo.get_metrics().await, + Repo::SkipMapMutexStd(repo) => repo.get_metrics(), } } + pub(crate) async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { match self { - Repo::Std(repo) => repo.get_paginated(pagination), - Repo::StdMutexStd(repo) => repo + Repo::RwLockStd(repo) => repo.get_paginated(pagination), + Repo::RwLockStdMutexStd(repo) => repo .get_paginated(pagination) .iter() .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) .collect(), - Repo::StdMutexTokio(repo) => { + Repo::RwLockStdMutexTokio(repo) => { let mut v: Vec<(InfoHash, EntrySingle)> = vec![]; for (i, t) in repo.get_paginated(pagination).await { @@ -57,14 +62,14 @@ impl Repo { } v } - Repo::Tokio(repo) => repo.get_paginated(pagination).await, - Repo::TokioMutexStd(repo) => repo + Repo::RwLockTokio(repo) => repo.get_paginated(pagination).await, + Repo::RwLockTokioMutexStd(repo) => repo .get_paginated(pagination) .await .iter() .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) .collect(), - Repo::TokioMutexTokio(repo) => { + Repo::RwLockTokioMutexTokio(repo) => { let mut v: Vec<(InfoHash, EntrySingle)> = vec![]; for (i, t) in repo.get_paginated(pagination).await { @@ -72,76 +77,102 @@ impl Repo { } v } + Repo::SkipMapMutexStd(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) + .collect(), } } + pub(crate) async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { match self { - Repo::Std(repo) => repo.import_persistent(persistent_torrents), - Repo::StdMutexStd(repo) => repo.import_persistent(persistent_torrents), - Repo::StdMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, - Repo::Tokio(repo) => repo.import_persistent(persistent_torrents).await, - Repo::TokioMutexStd(repo) => repo.import_persistent(persistent_torrents).await, - Repo::TokioMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, + Repo::RwLockStd(repo) => repo.import_persistent(persistent_torrents), + Repo::RwLockStdMutexStd(repo) => repo.import_persistent(persistent_torrents), + Repo::RwLockStdMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, + Repo::RwLockTokio(repo) => repo.import_persistent(persistent_torrents).await, + Repo::RwLockTokioMutexStd(repo) => repo.import_persistent(persistent_torrents).await, + Repo::RwLockTokioMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, + Repo::SkipMapMutexStd(repo) => repo.import_persistent(persistent_torrents), } } + pub(crate) async fn remove(&self, key: &InfoHash) -> Option { match self { - Repo::Std(repo) => repo.remove(key), - Repo::StdMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), - Repo::StdMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), - Repo::Tokio(repo) => repo.remove(key).await, - Repo::TokioMutexStd(repo) => Some(repo.remove(key).await?.lock().unwrap().clone()), - Repo::TokioMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), + Repo::RwLockStd(repo) => repo.remove(key), + Repo::RwLockStdMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), + Repo::RwLockStdMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), + Repo::RwLockTokio(repo) => repo.remove(key).await, + Repo::RwLockTokioMutexStd(repo) => Some(repo.remove(key).await?.lock().unwrap().clone()), + Repo::RwLockTokioMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), + Repo::SkipMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), } } + pub(crate) async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { match self { - Repo::Std(repo) => repo.remove_inactive_peers(current_cutoff), - Repo::StdMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), - Repo::StdMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, - Repo::Tokio(repo) => repo.remove_inactive_peers(current_cutoff).await, - Repo::TokioMutexStd(repo) => repo.remove_inactive_peers(current_cutoff).await, - Repo::TokioMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::RwLockStd(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::RwLockStdMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::RwLockStdMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::RwLockTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::RwLockTokioMutexStd(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::RwLockTokioMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::SkipMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), } } + pub(crate) async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { match self { - Repo::Std(repo) => repo.remove_peerless_torrents(policy), - Repo::StdMutexStd(repo) => repo.remove_peerless_torrents(policy), - Repo::StdMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, - Repo::Tokio(repo) => repo.remove_peerless_torrents(policy).await, - Repo::TokioMutexStd(repo) => repo.remove_peerless_torrents(policy).await, - Repo::TokioMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, + Repo::RwLockStd(repo) => repo.remove_peerless_torrents(policy), + Repo::RwLockStdMutexStd(repo) => repo.remove_peerless_torrents(policy), + Repo::RwLockStdMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, + Repo::RwLockTokio(repo) => repo.remove_peerless_torrents(policy).await, + Repo::RwLockTokioMutexStd(repo) => repo.remove_peerless_torrents(policy).await, + Repo::RwLockTokioMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, + Repo::SkipMapMutexStd(repo) => repo.remove_peerless_torrents(policy), } } + pub(crate) async fn update_torrent_with_peer_and_get_stats( &self, info_hash: &InfoHash, peer: &peer::Peer, ) -> (bool, SwarmMetadata) { match self { - Repo::Std(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), - Repo::StdMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), - Repo::StdMutexTokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, - Repo::Tokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, - Repo::TokioMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, - Repo::TokioMutexTokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, + Repo::RwLockStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), + Repo::RwLockStdMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), + Repo::RwLockStdMutexTokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, + Repo::RwLockTokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, + Repo::RwLockTokioMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, + Repo::RwLockTokioMutexTokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, + Repo::SkipMapMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), } } + pub(crate) async fn insert(&self, info_hash: &InfoHash, torrent: EntrySingle) -> Option { match self { - Repo::Std(repo) => repo.write().insert(*info_hash, torrent), - Repo::StdMutexStd(repo) => Some(repo.write().insert(*info_hash, torrent.into())?.lock().unwrap().clone()), - Repo::StdMutexTokio(repo) => { - let r = repo.write().insert(*info_hash, torrent.into()); - match r { - Some(t) => Some(t.lock().await.clone()), - None => None, - } + Repo::RwLockStd(repo) => { + repo.write().insert(*info_hash, torrent); } - Repo::Tokio(repo) => repo.write().await.insert(*info_hash, torrent), - Repo::TokioMutexStd(repo) => Some(repo.write().await.insert(*info_hash, torrent.into())?.lock().unwrap().clone()), - Repo::TokioMutexTokio(repo) => Some(repo.write().await.insert(*info_hash, torrent.into())?.lock().await.clone()), - } + Repo::RwLockStdMutexStd(repo) => { + repo.write().insert(*info_hash, torrent.into()); + } + Repo::RwLockStdMutexTokio(repo) => { + repo.write().insert(*info_hash, torrent.into()); + } + Repo::RwLockTokio(repo) => { + repo.write().await.insert(*info_hash, torrent); + } + Repo::RwLockTokioMutexStd(repo) => { + repo.write().await.insert(*info_hash, torrent.into()); + } + Repo::RwLockTokioMutexTokio(repo) => { + repo.write().await.insert(*info_hash, torrent.into()); + } + Repo::SkipMapMutexStd(repo) => { + repo.torrents.insert(*info_hash, torrent.into()); + } + }; + self.get(info_hash).await } } diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 117f3c0a6..ab9648584 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -10,6 +10,7 @@ use torrust_tracker_primitives::{NumberOfBytes, PersistentTorrents}; use torrust_tracker_torrent_repository::entry::Entry as _; use torrust_tracker_torrent_repository::repository::rw_lock_std::RwLockStd; use torrust_tracker_torrent_repository::repository::rw_lock_tokio::RwLockTokio; +use torrust_tracker_torrent_repository::repository::skip_map_mutex_std::CrossbeamSkipList; use torrust_tracker_torrent_repository::EntrySingle; use crate::common::repo::Repo; @@ -17,30 +18,37 @@ use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; #[fixture] fn standard() -> Repo { - Repo::Std(RwLockStd::default()) + Repo::RwLockStd(RwLockStd::default()) } + #[fixture] fn standard_mutex() -> Repo { - Repo::StdMutexStd(RwLockStd::default()) + Repo::RwLockStdMutexStd(RwLockStd::default()) } #[fixture] fn standard_tokio() -> Repo { - Repo::StdMutexTokio(RwLockStd::default()) + Repo::RwLockStdMutexTokio(RwLockStd::default()) } #[fixture] fn tokio_std() -> Repo { - Repo::Tokio(RwLockTokio::default()) + Repo::RwLockTokio(RwLockTokio::default()) } + #[fixture] fn tokio_mutex() -> Repo { - Repo::TokioMutexStd(RwLockTokio::default()) + Repo::RwLockTokioMutexStd(RwLockTokio::default()) } #[fixture] fn tokio_tokio() -> Repo { - Repo::TokioMutexTokio(RwLockTokio::default()) + Repo::RwLockTokioMutexTokio(RwLockTokio::default()) +} + +#[fixture] +fn skip_list_std() -> Repo { + Repo::SkipMapMutexStd(CrossbeamSkipList::default()) } type Entries = Vec<(InfoHash, EntrySingle)>; @@ -224,7 +232,16 @@ fn policy_remove_persist() -> TrackerPolicy { #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_get_a_torrent_entry( - #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_std() + )] + repo: Repo, #[case] entries: Entries, ) { make(&repo, &entries).await; @@ -247,7 +264,16 @@ async fn it_should_get_a_torrent_entry( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( - #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_std() + )] + repo: Repo, #[case] entries: Entries, many_out_of_order: Entries, ) { @@ -280,7 +306,16 @@ async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_get_paginated( - #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_std() + )] + repo: Repo, #[case] entries: Entries, #[values(paginated_limit_zero(), paginated_limit_one(), paginated_limit_one_offset_one())] paginated: Pagination, ) { @@ -328,7 +363,16 @@ async fn it_should_get_paginated( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_get_metrics( - #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_std() + )] + repo: Repo, #[case] entries: Entries, ) { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; @@ -360,7 +404,16 @@ async fn it_should_get_metrics( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_import_persistent_torrents( - #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_std() + )] + repo: Repo, #[case] entries: Entries, #[values(persistent_empty(), persistent_single(), persistent_three())] persistent_torrents: PersistentTorrents, ) { @@ -389,7 +442,16 @@ async fn it_should_import_persistent_torrents( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_remove_an_entry( - #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_std() + )] + repo: Repo, #[case] entries: Entries, ) { make(&repo, &entries).await; @@ -416,7 +478,16 @@ async fn it_should_remove_an_entry( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_remove_inactive_peers( - #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_std() + )] + repo: Repo, #[case] entries: Entries, ) { use std::ops::Sub as _; @@ -489,7 +560,16 @@ async fn it_should_remove_inactive_peers( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_remove_peerless_torrents( - #[values(standard(), standard_mutex(), standard_tokio(), tokio_std(), tokio_mutex(), tokio_tokio())] repo: Repo, + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_std() + )] + repo: Repo, #[case] entries: Entries, #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, ) { From 537349376e4b5cc1d8b0347e2806ceef7a5e9353 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 8 Apr 2024 16:39:06 +0100 Subject: [PATCH 0282/1297] chore(deps): update dependencies ```output cargo update Updating crates.io index Updating async-compression v0.4.6 -> v0.4.8 Updating async-executor v1.8.0 -> v1.10.0 Updating autocfg v1.1.0 -> v1.2.0 Adding base64 v0.22.0 Updating borsh v1.3.1 -> v1.4.0 Updating borsh-derive v1.3.1 -> v1.4.0 Updating brotli v3.5.0 -> v4.0.0 Updating brotli-decompressor v2.5.1 -> v3.0.0 Updating bumpalo v3.15.4 -> v3.16.0 Updating cc v1.0.90 -> v1.0.91 Updating chrono v0.4.35 -> v0.4.37 Updating event-listener v5.2.0 -> v5.3.0 Updating event-listener-strategy v0.5.0 -> v0.5.1 Updating getrandom v0.2.12 -> v0.2.14 Updating h2 v0.4.3 -> v0.4.4 Updating half v2.4.0 -> v2.4.1 Updating itoa v1.0.10 -> v1.0.11 Updating memchr v2.7.1 -> v2.7.2 Updating openssl-sys v0.9.101 -> v0.9.102 Updating pest v2.7.8 -> v2.7.9 Updating pest_derive v2.7.8 -> v2.7.9 Updating pest_generator v2.7.8 -> v2.7.9 Updating pest_meta v2.7.8 -> v2.7.9 Updating pin-project-lite v0.2.13 -> v0.2.14 Updating regex-syntax v0.8.2 -> v0.8.3 Updating reqwest v0.12.2 -> v0.12.3 Updating rust_decimal v1.34.3 -> v1.35.0 Removing rustls-pemfile v1.0.4 Removing rustls-pemfile v2.1.1 Adding rustls-pemfile v2.1.2 Updating rustls-pki-types v1.4.0 -> v1.4.1 Updating rustversion v1.0.14 -> v1.0.15 Updating security-framework v2.9.2 -> v2.10.0 Updating security-framework-sys v2.9.1 -> v2.10.0 Updating serde_html_form v0.2.5 -> v0.2.6 Updating serde_json v1.0.114 -> v1.0.115 Updating strsim v0.11.0 -> v0.11.1 Updating syn v2.0.55 -> v2.0.58 Updating sync_wrapper v1.0.0 -> v1.0.1 Updating tokio v1.36.0 -> v1.37.0 Updating winreg v0.50.0 -> v0.52.0 Updating zstd v0.13.0 -> v0.13.1 Updating zstd-safe v7.0.0 -> v7.1.0 Updating zstd-sys v2.0.9+zstd.1.5.5 -> v2.0.10+zstd.1.5.6 ``` --- Cargo.lock | 261 ++++++++++++++++++++++++++--------------------------- 1 file changed, 129 insertions(+), 132 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 74d9aaafd..853d21533 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -195,17 +195,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f28243a43d821d11341ab73c80bed182dc015c514b951616cf79bd4af39af0c3" dependencies = [ "concurrent-queue", - "event-listener 5.2.0", - "event-listener-strategy 0.5.0", + "event-listener 5.3.0", + "event-listener-strategy 0.5.1", "futures-core", "pin-project-lite", ] [[package]] name = "async-compression" -version = "0.4.6" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a116f46a969224200a0a97f29cfd4c50e7534e4b4826bd23ea2c3c533039c82c" +checksum = "07dbbf24db18d609b1462965249abdf49129ccad073ec257da372adc83259c60" dependencies = [ "brotli", "flate2", @@ -219,9 +219,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.8.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17ae5ebefcc48e7452b4987947920dac9450be1110cadf34d1b8c116bdbaf97c" +checksum = "5f98c37cf288e302c16ef6c8472aad1e034c6c84ce5ea7b8101c98eb4a802fee" dependencies = [ "async-lock 3.3.0", "async-task", @@ -347,7 +347,7 @@ checksum = "a507401cad91ec6a857ed5513a2073c82a9b9048762b885bb98655b306964681" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -358,9 +358,9 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" +checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80" [[package]] name = "axum" @@ -389,7 +389,7 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", - "sync_wrapper 1.0.0", + "sync_wrapper 1.0.1", "tokio", "tower", "tower-layer", @@ -461,7 +461,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -480,7 +480,7 @@ dependencies = [ "hyper-util", "pin-project-lite", "rustls", - "rustls-pemfile 2.1.1", + "rustls-pemfile", "tokio", "tokio-rustls", "tower", @@ -508,6 +508,12 @@ version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" +[[package]] +name = "base64" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9475866fec1451be56a3c2400fd081ff546538961565ccb5b7142cbd22bc7a51" + [[package]] name = "bigdecimal" version = "0.3.1" @@ -542,7 +548,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -599,9 +605,9 @@ dependencies = [ [[package]] name = "borsh" -version = "1.3.1" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f58b559fd6448c6e2fd0adb5720cd98a2506594cafa4737ff98c396f3e82f667" +checksum = "0901fc8eb0aca4c83be0106d6f2db17d86a08dfc2c25f0e84464bf381158add6" dependencies = [ "borsh-derive", "cfg_aliases", @@ -609,23 +615,23 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.3.1" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aadb5b6ccbd078890f6d7003694e33816e6b784358f18e15e7e6d9f065a57cd" +checksum = "51670c3aa053938b0ee3bd67c3817e471e626151131b934038e83c5bf8de48f5" dependencies = [ "once_cell", "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", "syn_derive", ] [[package]] name = "brotli" -version = "3.5.0" +version = "4.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d640d25bc63c50fb1f0b545ffd80207d2e10a4c965530809b40ba3386825c391" +checksum = "125740193d7fee5cc63ab9e16c2fdc4e07c74ba755cc53b327d6ea029e9fc569" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -634,9 +640,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "2.5.1" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e2e4afe60d7dd600fdd3de8d0f08c2b7ec039712e3b6137ff98b7004e82de4f" +checksum = "65622a320492e09b5e0ac436b14c54ff68199bac392d0e89a6832c4518eea525" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -650,9 +656,9 @@ checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" [[package]] name = "bumpalo" -version = "3.15.4" +version = "3.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ff69b9dd49fd426c69a0db9fc04dd934cdb6645ff000864d98f7e2af8830eaa" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" [[package]] name = "bytecheck" @@ -696,9 +702,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.0.90" +version = "1.0.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cd6604a82acf3039f1144f54b8eb34e91ffba622051189e71b781822d5ee1f5" +checksum = "1fd97381a8cc6493395a5afc4c691c1084b3768db713b73aa215217aa245d153" dependencies = [ "jobserver", "libc", @@ -727,9 +733,9 @@ checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" [[package]] name = "chrono" -version = "0.4.35" +version = "0.4.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a" +checksum = "8a0d04d43504c61aa6c7531f1871dd0d418d91130162063b789da00fd7057a5e" dependencies = [ "android-tzdata", "iana-time-zone", @@ -795,7 +801,7 @@ dependencies = [ "anstream", "anstyle", "clap_lex", - "strsim 0.11.0", + "strsim 0.11.1", ] [[package]] @@ -807,7 +813,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -1080,7 +1086,7 @@ dependencies = [ "proc-macro2", "quote", "strsim 0.10.0", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -1091,7 +1097,7 @@ checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" dependencies = [ "darling_core", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -1125,7 +1131,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -1213,9 +1219,9 @@ dependencies = [ [[package]] name = "event-listener" -version = "5.2.0" +version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b5fb89194fa3cad959b833185b3063ba881dbfc7030680b314250779fb4cc91" +checksum = "6d9944b8ca13534cdfb2800775f8dd4902ff3fc75a50101466decadfdf322a24" dependencies = [ "concurrent-queue", "parking", @@ -1234,11 +1240,11 @@ dependencies = [ [[package]] name = "event-listener-strategy" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "feedafcaa9b749175d5ac357452a9d41ea2911da598fde46ce1fe02c37751291" +checksum = "332f51cb23d20b0de8458b86580878211da09bcd4503cb579c225b3d124cabb3" dependencies = [ - "event-listener 5.2.0", + "event-listener 5.3.0", "pin-project-lite", ] @@ -1360,7 +1366,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -1372,7 +1378,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -1384,7 +1390,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -1477,7 +1483,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -1528,9 +1534,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.12" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" +checksum = "94b22e06ecb0110981051723910cbf0b5f5e09a2062dd7663334ee79a9d1286c" dependencies = [ "cfg-if", "libc", @@ -1563,9 +1569,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51ee2dd2e4f378392eeff5d51618cd9a63166a2513846bbc55f21cfacd9199d4" +checksum = "816ec7294445779408f36fe57bc5b7fc1cf59664059096c65f905c1c61f58069" dependencies = [ "bytes", "fnv", @@ -1582,9 +1588,9 @@ dependencies = [ [[package]] name = "half" -version = "2.4.0" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5eceaaeec696539ddaf7b333340f1af35a5aa87ae3e4f3ead0532f72affab2e" +checksum = "6dd08c532ae367adf81c312a4580bc67f1d0fe8bc9c460520283f4c0ff277888" dependencies = [ "cfg-if", "crunchy", @@ -1887,9 +1893,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "jobserver" @@ -2118,9 +2124,9 @@ checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" [[package]] name = "memchr" -version = "2.7.1" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" +checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" [[package]] name = "mime" @@ -2178,7 +2184,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -2229,7 +2235,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", "termcolor", "thiserror", ] @@ -2240,7 +2246,7 @@ version = "0.30.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57349d5a326b437989b6ee4dc8f2f34b0cc131202748414712a8e7d98952fc8c" dependencies = [ - "base64", + "base64 0.21.7", "bigdecimal", "bindgen", "bitflags 2.5.0", @@ -2429,7 +2435,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -2440,9 +2446,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-sys" -version = "0.9.101" +version = "0.9.102" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dda2b0f344e78efc2facf7d195d098df0dd72151b26ab98da807afc26c198dff" +checksum = "c597637d56fbc83893a35eb0dd04b2b8e7a50c91e64e9493e398b5df4fb45fa2" dependencies = [ "cc", "libc", @@ -2501,7 +2507,7 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b13fe415cdf3c8e44518e18a7c95a13431d9bdf6d15367d82b23c377fdd441a" dependencies = [ - "base64", + "base64 0.21.7", "serde", ] @@ -2513,9 +2519,9 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.8" +version = "2.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56f8023d0fb78c8e03784ea1c7f3fa36e68a723138990b8d5a47d916b651e7a8" +checksum = "311fb059dee1a7b802f036316d790138c613a4e8b180c822e3925a662e9f0c95" dependencies = [ "memchr", "thiserror", @@ -2524,9 +2530,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.8" +version = "2.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0d24f72393fd16ab6ac5738bc33cdb6a9aa73f8b902e8fe29cf4e67d7dd1026" +checksum = "f73541b156d32197eecda1a4014d7f868fd2bcb3c550d5386087cfba442bf69c" dependencies = [ "pest", "pest_generator", @@ -2534,22 +2540,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.8" +version = "2.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdc17e2a6c7d0a492f0158d7a4bd66cc17280308bbaff78d5bef566dca35ab80" +checksum = "c35eeed0a3fab112f75165fdc026b3913f4183133f19b49be773ac9ea966e8bd" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] name = "pest_meta" -version = "2.7.8" +version = "2.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "934cd7631c050f4674352a6e835d5f6711ffbfb9345c2fc0107155ac495ae293" +checksum = "2adbf29bb9776f28caece835398781ab24435585fe0d4dc1374a61db5accedca" dependencies = [ "once_cell", "pest", @@ -2611,14 +2617,14 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] name = "pin-project-lite" -version = "0.2.13" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" +checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" [[package]] name = "pin-utils" @@ -2943,9 +2949,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" +checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" [[package]] name = "relative-path" @@ -2964,11 +2970,11 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.2" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d66674f2b6fb864665eea7a3c1ac4e3dfacd2fda83cf6f935a612e01b0e3338" +checksum = "3e6cc1e89e689536eb5aeede61520e874df5a4707df811cd5da4aa5fbb2aae19" dependencies = [ - "base64", + "base64 0.22.0", "bytes", "encoding_rs", "futures-core", @@ -2988,7 +2994,7 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", - "rustls-pemfile 1.0.4", + "rustls-pemfile", "serde", "serde_json", "serde_urlencoded", @@ -3063,7 +3069,7 @@ version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b91f7eff05f748767f183df4320a63d6936e9c6107d97c9e6bdd9784f4289c94" dependencies = [ - "base64", + "base64 0.21.7", "bitflags 2.5.0", "serde", "serde_derive", @@ -3094,7 +3100,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.55", + "syn 2.0.58", "unicode-ident", ] @@ -3124,9 +3130,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.34.3" +version = "1.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39449a79f45e8da28c57c341891b69a183044b29518bb8f86dbac9df60bb7df" +checksum = "1790d1c4c0ca81211399e0e0af16333276f375209e71a37b67698a373db5b47a" dependencies = [ "arrayvec", "borsh", @@ -3200,28 +3206,19 @@ dependencies = [ [[package]] name = "rustls-pemfile" -version = "1.0.4" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" +checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d" dependencies = [ - "base64", -] - -[[package]] -name = "rustls-pemfile" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f48172685e6ff52a556baa527774f61fcaa884f59daf3375c62a3f1cd2549dab" -dependencies = [ - "base64", + "base64 0.22.0", "rustls-pki-types", ] [[package]] name = "rustls-pki-types" -version = "1.4.0" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "868e20fada228fefaf6b652e00cc73623d54f8171e7352c18bb281571f2d92da" +checksum = "ecd36cc4259e3e4514335c4a138c6b43171a8d61d8f5c9348f9fc7529416f247" [[package]] name = "rustls-webpki" @@ -3235,9 +3232,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.14" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" +checksum = "80af6f9131f277a45a3fba6ce8e2258037bb0477a67e610d3c1fe046ab31de47" [[package]] name = "ryu" @@ -3302,9 +3299,9 @@ checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" [[package]] name = "security-framework" -version = "2.9.2" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de" +checksum = "770452e37cad93e0a50d5abc3990d2bc351c36d0328f86cefec2f2fb206eaef6" dependencies = [ "bitflags 1.3.2", "core-foundation", @@ -3315,9 +3312,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.9.1" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a" +checksum = "41f3cc463c0ef97e11c3461a9d3787412d30e8e7eb907c79180c4a57bf7c04ef" dependencies = [ "core-foundation-sys", "libc", @@ -3365,14 +3362,14 @@ checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] name = "serde_html_form" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50437e6a58912eecc08865e35ea2e8d365fbb2db0debb1c8bb43bf1faf055f25" +checksum = "8de514ef58196f1fc96dcaef80fe6170a1ce6215df9687a93fe8300e773fefc5" dependencies = [ "form_urlencoded", "indexmap 2.2.6", @@ -3383,9 +3380,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.114" +version = "1.0.115" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" +checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd" dependencies = [ "itoa", "ryu", @@ -3410,7 +3407,7 @@ checksum = "0b2e6b945e9d3df726b65d6ee24060aff8e3533d431f677a9695db04eff9dfdb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -3440,7 +3437,7 @@ version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee80b0e361bbf88fd2f6e242ccd19cfda072cb0faa6ae694ecee08199938569a" dependencies = [ - "base64", + "base64 0.21.7", "chrono", "hex", "indexmap 1.9.3", @@ -3461,7 +3458,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -3568,9 +3565,9 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] name = "strsim" -version = "0.11.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ee073c9e4cd00e28217186dbe12796d692868f432bf2e97ee73bed0c56dfa01" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "subprocess" @@ -3595,9 +3592,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.55" +version = "2.0.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "002a1b3dbf967edfafc32655d0f377ab0bb7b994aa1d32c8cc7e9b8bf3ebb8f0" +checksum = "44cfb93f38070beee36b3fef7d4f5a16f27751d94b187b666a5cc5e9b0d30687" dependencies = [ "proc-macro2", "quote", @@ -3613,7 +3610,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -3624,9 +3621,9 @@ checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" [[package]] name = "sync_wrapper" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384595c11a4e2969895cad5a8c4029115f5ab956a9e5ef4de79d11a426e5f20c" +checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" [[package]] name = "system-configuration" @@ -3716,7 +3713,7 @@ checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -3786,9 +3783,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.36.0" +version = "1.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61285f6515fa018fb2d1e46eb21223fff441ee8db5d0f1435e8ab4f5cdb80931" +checksum = "1adbebffeca75fcfd058afa480fb6c0b81e165a0323f9c9d39c9697e37c46787" dependencies = [ "backtrace", "bytes", @@ -3810,7 +3807,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -4114,7 +4111,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] @@ -4285,7 +4282,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", "wasm-bindgen-shared", ] @@ -4319,7 +4316,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4532,9 +4529,9 @@ dependencies = [ [[package]] name = "winreg" -version = "0.50.0" +version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" +checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5" dependencies = [ "cfg-if", "windows-sys 0.48.0", @@ -4575,32 +4572,32 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.55", + "syn 2.0.58", ] [[package]] name = "zstd" -version = "0.13.0" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bffb3309596d527cfcba7dfc6ed6052f1d39dfbd7c867aa2e865e4a449c10110" +checksum = "2d789b1514203a1120ad2429eae43a7bd32b90976a7bb8a05f7ec02fa88cc23a" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "7.0.0" +version = "7.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43747c7422e2924c11144d5229878b98180ef8b06cca4ab5af37afc8a8d8ea3e" +checksum = "1cd99b45c6bc03a018c8b8a86025678c87e55526064e38f9df301989dce7ec0a" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.0.9+zstd.1.5.5" +version = "2.0.10+zstd.1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e16efa8a874a0481a574084d34cc26fdb3b99627480f785888deb6386506656" +checksum = "c253a4914af5bafc8fa8c86ee400827e83cf6ec01195ec1f1ed8441bf00d65aa" dependencies = [ "cc", "pkg-config", From 78b46c41a5c50f5016f745634fe5101969e5a828 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 9 Apr 2024 13:24:41 +0100 Subject: [PATCH 0283/1297] chore(deps): add cargo dependency: dashmap It will be used to create a new torrent repository implementation, using a DashMap for the torrent list. DashMap crate: https://crates.io/crates/dashmap --- Cargo.lock | 15 +++++++++++++++ Cargo.toml | 1 + cSpell.json | 1 + packages/torrent-repository/Cargo.toml | 1 + 4 files changed, 18 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 853d21533..6b9be523c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1100,6 +1100,19 @@ dependencies = [ "syn 2.0.58", ] +[[package]] +name = "dashmap" +version = "5.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +dependencies = [ + "cfg-if", + "hashbrown 0.14.3", + "lock_api", + "once_cell", + "parking_lot_core", +] + [[package]] name = "deranged" version = "0.3.11" @@ -3916,6 +3929,7 @@ dependencies = [ "colored", "config", "crossbeam-skiplist", + "dashmap", "derive_more", "fern", "futures", @@ -4022,6 +4036,7 @@ dependencies = [ "async-std", "criterion", "crossbeam-skiplist", + "dashmap", "futures", "rstest", "tokio", diff --git a/Cargo.toml b/Cargo.toml index f440799cc..dfb06168d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,7 @@ clap = { version = "4", features = ["derive", "env"] } colored = "2" config = "0" crossbeam-skiplist = "0.1" +dashmap = "5.5.3" derive_more = "0" fern = "0" futures = "0" diff --git a/cSpell.json b/cSpell.json index 0480590af..24ef6b0a0 100644 --- a/cSpell.json +++ b/cSpell.json @@ -163,6 +163,7 @@ "Weidendorfer", "Werror", "whitespaces", + "Xacrimon", "XBTT", "Xdebug", "Xeon", diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 5f1a20d32..6bc8bfcdd 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -17,6 +17,7 @@ version.workspace = true [dependencies] crossbeam-skiplist = "0.1" +dashmap = "5.5.3" futures = "0.3.29" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-alpha.12-develop", path = "../clock" } From 00ee9db340c5274a63aa5f321e3bd5064e967b6c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 9 Apr 2024 14:17:10 +0100 Subject: [PATCH 0284/1297] feat: [#565] new torrent repository implementation usind DashMap It's not enabled as the deafult repository becuase DashMap does not return the items in order. Some tests fail: ``` output failures: ---- core::services::torrent::tests::searching_for_torrents::should_return_torrents_ordered_by_info_hash stdout ---- thread 'core::services::torrent::tests::searching_for_torrents::should_return_torrents_ordered_by_info_hash' panicked at src/core/services/torrent.rs:303:13: assertion `left == right` failed left: [BasicInfo { info_hash: InfoHash([158, 2, 23, 208, 250, 113, 200, 115, 50, 205, 139, 249, 219, 234, 188, 178, 194, 207, 60, 77]), seeders: 1, completed: 0, leechers: 0 }, BasicInfo { info_hash: InfoHash([3, 132, 5, 72, 100, 58, 242, 167, 182, 58, 159, 92, 188, 163, 72, 188, 113, 80, 202, 58]), seeders: 1, completed: 0, leechers: 0 }] right: [BasicInfo { info_hash: InfoHash([3, 132, 5, 72, 100, 58, 242, 167, 182, 58, 159, 92, 188, 163, 72, 188, 113, 80, 202, 58]), seeders: 1, completed: 0, leechers: 0 }, BasicInfo { info_hash: InfoHash([158, 2, 23, 208, 250, 113, 200, 115, 50, 205, 139, 249, 219, 234, 188, 178, 194, 207, 60, 77]), seeders: 1, completed: 0, leechers: 0 }] note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: core::services::torrent::tests::searching_for_torrents::should_return_torrents_ordered_by_info_hash test result: FAILED. 212 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.18s error: test failed, to rerun pass `--lib` ``` On the other hand, to use it, a new data strcuture should be added to the repo: An Index with sorted torrents by Infohash The API uses pagination returning torrents in alphabetically order by InfoHash. Adding such an Index would probably decrease the performace of this repository implementation. And it's performace looks similar to the current SkipMap implementation. SkipMap performace with Aquatic UDP load test: ``` Requests out: 396788.68/second Responses in: 357105.27/second - Connect responses: 176662.91 - Announce responses: 176863.44 - Scrape responses: 3578.91 - Error responses: 0.00 Peers per announce response: 0.00 Announce responses per info hash: - p10: 1 - p25: 1 - p50: 1 - p75: 1 - p90: 2 - p95: 3 - p99: 105 - p99.9: 287 - p100: 351 ``` DashMap performace with Aquatic UDP load test: ``` Requests out: 410658.38/second Responses in: 365892.86/second - Connect responses: 181258.91 - Announce responses: 181005.95 - Scrape responses: 3628.00 - Error responses: 0.00 Peers per announce response: 0.00 Announce responses per info hash: - p10: 1 - p25: 1 - p50: 1 - p75: 1 - p90: 2 - p95: 3 - p99: 104 - p99.9: 295 - p100: 363 ``` --- .../benches/repository_benchmark.rs | 23 +++- packages/torrent-repository/src/lib.rs | 2 + .../src/repository/dash_map_mutex_std.rs | 106 ++++++++++++++++++ .../torrent-repository/src/repository/mod.rs | 1 + .../torrent-repository/tests/common/repo.rs | 20 +++- .../tests/repository/mod.rs | 30 +++-- 6 files changed, 170 insertions(+), 12 deletions(-) create mode 100644 packages/torrent-repository/src/repository/dash_map_mutex_std.rs diff --git a/packages/torrent-repository/benches/repository_benchmark.rs b/packages/torrent-repository/benches/repository_benchmark.rs index 65608c86c..58cd70d9a 100644 --- a/packages/torrent-repository/benches/repository_benchmark.rs +++ b/packages/torrent-repository/benches/repository_benchmark.rs @@ -4,8 +4,8 @@ mod helpers; use criterion::{criterion_group, criterion_main, Criterion}; use torrust_tracker_torrent_repository::{ - TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, - TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexStd, + TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, + TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexStd, }; use crate::helpers::{asyn, sync}; @@ -49,6 +49,10 @@ fn add_one_torrent(c: &mut Criterion) { b.iter_custom(sync::add_one_torrent::); }); + group.bench_function("DashMapMutexStd", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + group.finish(); } @@ -98,6 +102,11 @@ fn add_multiple_torrents_in_parallel(c: &mut Criterion) { .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); }); + group.bench_function("DashMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + group.finish(); } @@ -147,6 +156,11 @@ fn update_one_torrent_in_parallel(c: &mut Criterion) { .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); }); + group.bench_function("DashMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + group.finish(); } @@ -197,6 +211,11 @@ fn update_multiple_torrents_in_parallel(c: &mut Criterion) { .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); }); + group.bench_function("DashMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + group.finish(); } diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index ccaf579e3..7a6d209b9 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use repository::dash_map_mutex_std::XacrimonDashMap; use repository::rw_lock_std::RwLockStd; use repository::rw_lock_tokio::RwLockTokio; use repository::skip_map_mutex_std::CrossbeamSkipList; @@ -20,6 +21,7 @@ pub type TorrentsRwLockTokioMutexStd = RwLockTokio; pub type TorrentsRwLockTokioMutexTokio = RwLockTokio; pub type TorrentsSkipMapMutexStd = CrossbeamSkipList; +pub type TorrentsDashMapMutexStd = XacrimonDashMap; /// This code needs to be copied into each crate. /// Working version, for production. diff --git a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs new file mode 100644 index 000000000..67c47973e --- /dev/null +++ b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs @@ -0,0 +1,106 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use dashmap::DashMap; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; + +use super::Repository; +use crate::entry::{Entry, EntrySync}; +use crate::{EntryMutexStd, EntrySingle}; + +#[derive(Default, Debug)] +pub struct XacrimonDashMap { + pub torrents: DashMap, +} + +impl Repository for XacrimonDashMap +where + EntryMutexStd: EntrySync, + EntrySingle: Entry, +{ + fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + if let Some(entry) = self.torrents.get(info_hash) { + entry.insert_or_update_peer_and_get_stats(peer) + } else { + let _unused = self.torrents.insert(*info_hash, Arc::default()); + + match self.torrents.get(info_hash) { + Some(entry) => entry.insert_or_update_peer_and_get_stats(peer), + None => (false, SwarmMetadata::zeroed()), + } + } + } + + fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.torrents.get(key); + maybe_entry.map(|entry| entry.clone()) + } + + fn get_metrics(&self) -> TorrentsMetrics { + let mut metrics = TorrentsMetrics::default(); + + for entry in &self.torrents { + let stats = entry.value().lock().expect("it should get a lock").get_stats(); + metrics.complete += u64::from(stats.complete); + metrics.downloaded += u64::from(stats.downloaded); + metrics.incomplete += u64::from(stats.incomplete); + metrics.torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + match pagination { + Some(pagination) => self + .torrents + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .torrents + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + for (info_hash, completed) in persistent_torrents { + if self.torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexStd::new( + EntrySingle { + peers: BTreeMap::default(), + downloaded: *completed, + } + .into(), + ); + + self.torrents.insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|(_key, value)| value.clone()) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { + entry.value().remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + self.torrents.retain(|_, entry| entry.is_good(policy)); + } +} diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs index 975a876d8..c7c64c54a 100644 --- a/packages/torrent-repository/src/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -5,6 +5,7 @@ use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +pub mod dash_map_mutex_std; pub mod rw_lock_std; pub mod rw_lock_std_mutex_std; pub mod rw_lock_std_mutex_tokio; diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 5a86aa3cf..5a6eddf97 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -6,8 +6,8 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use torrust_tracker_torrent_repository::repository::{Repository as _, RepositoryAsync as _}; use torrust_tracker_torrent_repository::{ - EntrySingle, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, - TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexStd, + EntrySingle, TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, + TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexStd, }; #[derive(Debug)] @@ -19,6 +19,7 @@ pub(crate) enum Repo { RwLockTokioMutexStd(TorrentsRwLockTokioMutexStd), RwLockTokioMutexTokio(TorrentsRwLockTokioMutexTokio), SkipMapMutexStd(TorrentsSkipMapMutexStd), + DashMapMutexStd(TorrentsDashMapMutexStd), } impl Repo { @@ -31,6 +32,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => Some(repo.get(key).await?.lock().unwrap().clone()), Repo::RwLockTokioMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), Repo::SkipMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), + Repo::DashMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), } } @@ -43,6 +45,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.get_metrics().await, Repo::RwLockTokioMutexTokio(repo) => repo.get_metrics().await, Repo::SkipMapMutexStd(repo) => repo.get_metrics(), + Repo::DashMapMutexStd(repo) => repo.get_metrics(), } } @@ -82,6 +85,11 @@ impl Repo { .iter() .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) .collect(), + Repo::DashMapMutexStd(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) + .collect(), } } @@ -94,6 +102,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.import_persistent(persistent_torrents).await, Repo::RwLockTokioMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, Repo::SkipMapMutexStd(repo) => repo.import_persistent(persistent_torrents), + Repo::DashMapMutexStd(repo) => repo.import_persistent(persistent_torrents), } } @@ -106,6 +115,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => Some(repo.remove(key).await?.lock().unwrap().clone()), Repo::RwLockTokioMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), Repo::SkipMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), + Repo::DashMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), } } @@ -118,6 +128,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.remove_inactive_peers(current_cutoff).await, Repo::RwLockTokioMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, Repo::SkipMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::DashMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), } } @@ -130,6 +141,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.remove_peerless_torrents(policy).await, Repo::RwLockTokioMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, Repo::SkipMapMutexStd(repo) => repo.remove_peerless_torrents(policy), + Repo::DashMapMutexStd(repo) => repo.remove_peerless_torrents(policy), } } @@ -146,6 +158,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, Repo::RwLockTokioMutexTokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, Repo::SkipMapMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), + Repo::DashMapMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), } } @@ -172,6 +185,9 @@ impl Repo { Repo::SkipMapMutexStd(repo) => { repo.torrents.insert(*info_hash, torrent.into()); } + Repo::DashMapMutexStd(repo) => { + repo.torrents.insert(*info_hash, torrent.into()); + } }; self.get(info_hash).await } diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index ab9648584..1854b89ac 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -8,6 +8,7 @@ use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::{NumberOfBytes, PersistentTorrents}; use torrust_tracker_torrent_repository::entry::Entry as _; +use torrust_tracker_torrent_repository::repository::dash_map_mutex_std::XacrimonDashMap; use torrust_tracker_torrent_repository::repository::rw_lock_std::RwLockStd; use torrust_tracker_torrent_repository::repository::rw_lock_tokio::RwLockTokio; use torrust_tracker_torrent_repository::repository::skip_map_mutex_std::CrossbeamSkipList; @@ -51,6 +52,11 @@ fn skip_list_std() -> Repo { Repo::SkipMapMutexStd(CrossbeamSkipList::default()) } +#[fixture] +fn dash_map_std() -> Repo { + Repo::DashMapMutexStd(XacrimonDashMap::default()) +} + type Entries = Vec<(InfoHash, EntrySingle)>; #[fixture] @@ -239,7 +245,8 @@ async fn it_should_get_a_torrent_entry( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std() + skip_list_std(), + dash_map_std() )] repo: Repo, #[case] entries: Entries, @@ -271,7 +278,8 @@ async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std() + skip_list_std(), + dash_map_std() )] repo: Repo, #[case] entries: Entries, @@ -313,7 +321,8 @@ async fn it_should_get_paginated( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std() + skip_list_std(), + dash_map_std() )] repo: Repo, #[case] entries: Entries, @@ -370,7 +379,8 @@ async fn it_should_get_metrics( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std() + skip_list_std(), + dash_map_std() )] repo: Repo, #[case] entries: Entries, @@ -411,7 +421,8 @@ async fn it_should_import_persistent_torrents( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std() + skip_list_std(), + dash_map_std() )] repo: Repo, #[case] entries: Entries, @@ -449,7 +460,8 @@ async fn it_should_remove_an_entry( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std() + skip_list_std(), + dash_map_std() )] repo: Repo, #[case] entries: Entries, @@ -485,7 +497,8 @@ async fn it_should_remove_inactive_peers( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std() + skip_list_std(), + dash_map_std() )] repo: Repo, #[case] entries: Entries, @@ -567,7 +580,8 @@ async fn it_should_remove_peerless_torrents( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std() + skip_list_std(), + dash_map_std() )] repo: Repo, #[case] entries: Entries, From 1e76c1700cd1cb5e69e01df34dfe19a7a9828153 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 9 Apr 2024 16:35:35 +0100 Subject: [PATCH 0285/1297] chore: add dashmap cargo dep to cargp machete It's only used for benchmarking. --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index dfb06168d..ef0c39d4b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -78,7 +78,7 @@ url = "2" uuid = { version = "1", features = ["v4"] } [package.metadata.cargo-machete] -ignored = ["serde_bytes", "crossbeam-skiplist"] +ignored = ["serde_bytes", "crossbeam-skiplist", "dashmap"] [dev-dependencies] local-ip-address = "0" From 4030fd12b575c039dbb1507fbe99e0aaec58fd5f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 9 Apr 2024 17:12:07 +0100 Subject: [PATCH 0286/1297] fix: torrent repository tests. DashMap is not ordered DashMap implementation does not support returning torrent ordered, so we have to skip those tests for this reporitoy implementation. --- packages/torrent-repository/tests/repository/mod.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 1854b89ac..a6784bf57 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -278,8 +278,7 @@ async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std(), - dash_map_std() + skip_list_std() )] repo: Repo, #[case] entries: Entries, @@ -321,8 +320,7 @@ async fn it_should_get_paginated( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std(), - dash_map_std() + skip_list_std() )] repo: Repo, #[case] entries: Entries, From aa4bfbaf5496de32a02bc1d23779ba200974f2a0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 12 Apr 2024 15:54:49 +0100 Subject: [PATCH 0287/1297] refactor: segregate command and query for announce request This changes the API of the torrent repository. The method: ``` fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata); ``` is replaced with: ``` fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer); fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option; ``` The performance is not affected. Benchmaring is still using both methods in order to simulate `announce` requests. 1. The interface is simpler (command/query segregation. 2. In the long-term: - Returning swarm metadata in the announce request could be optional. The announce request process would be faster if the tracker does not have to mantain the swarm data. This is not likely to happen becuase the scrape request needs this metadata. - New repository performance improvements could be implemented. This allow decoupling peer lists from swarm metadata. The repository internally can have two data strcutures one for the peer list and another for the swarm metatada. Both using different locks. --- .../benches/helpers/asyn.rs | 34 +++++------ .../benches/helpers/sync.rs | 22 +++++-- packages/torrent-repository/src/entry/mod.rs | 20 ++---- .../torrent-repository/src/entry/mutex_std.rs | 14 ++--- .../src/entry/mutex_tokio.rs | 12 ++-- .../torrent-repository/src/entry/single.rs | 10 +-- .../src/repository/dash_map_mutex_std.rs | 16 ++--- .../torrent-repository/src/repository/mod.rs | 10 ++- .../src/repository/rw_lock_std.rs | 10 ++- .../src/repository/rw_lock_std_mutex_std.rs | 12 +++- .../src/repository/rw_lock_std_mutex_tokio.rs | 16 ++++- .../src/repository/rw_lock_tokio.rs | 11 +++- .../src/repository/rw_lock_tokio_mutex_std.rs | 11 +++- .../repository/rw_lock_tokio_mutex_tokio.rs | 14 ++++- .../src/repository/skip_map_mutex_std.rs | 10 ++- .../torrent-repository/tests/common/repo.rs | 43 +++++++------ .../tests/common/torrent.rs | 22 +++---- .../torrent-repository/tests/entry/mod.rs | 41 +++++++------ .../tests/repository/mod.rs | 40 ++++++++---- src/core/mod.rs | 61 +++++++++++-------- src/core/services/torrent.rs | 38 ++++-------- src/servers/udp/handlers.rs | 12 +--- tests/servers/api/environment.rs | 2 +- tests/servers/http/environment.rs | 2 +- tests/servers/udp/environment.rs | 2 +- 25 files changed, 259 insertions(+), 226 deletions(-) diff --git a/packages/torrent-repository/benches/helpers/asyn.rs b/packages/torrent-repository/benches/helpers/asyn.rs index 80f70cdc2..1c6d9d915 100644 --- a/packages/torrent-repository/benches/helpers/asyn.rs +++ b/packages/torrent-repository/benches/helpers/asyn.rs @@ -18,9 +18,9 @@ where let info_hash = InfoHash([0; 20]); - torrent_repository - .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) - .await; + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER).await; + + torrent_repository.get_swarm_metadata(&info_hash).await; } start.elapsed() @@ -37,9 +37,9 @@ where let handles = FuturesUnordered::new(); // Add the torrent/peer to the torrent repository - torrent_repository - .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) - .await; + torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER).await; + + torrent_repository.get_swarm_metadata(info_hash).await; let start = Instant::now(); @@ -47,9 +47,9 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone - .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) - .await; + torrent_repository_clone.upsert_peer(info_hash, &DEFAULT_PEER).await; + + torrent_repository_clone.get_swarm_metadata(info_hash).await; if let Some(sleep_time) = sleep { let start_time = std::time::Instant::now(); @@ -87,9 +87,9 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone - .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) - .await; + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER).await; + + torrent_repository_clone.get_swarm_metadata(&info_hash).await; if let Some(sleep_time) = sleep { let start_time = std::time::Instant::now(); @@ -123,9 +123,8 @@ where // Add the torrents/peers to the torrent repository for info_hash in &info_hashes { - torrent_repository - .update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER) - .await; + torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER).await; + torrent_repository.get_swarm_metadata(info_hash).await; } let start = Instant::now(); @@ -134,9 +133,8 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone - .update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER) - .await; + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER).await; + torrent_repository_clone.get_swarm_metadata(&info_hash).await; if let Some(sleep_time) = sleep { let start_time = std::time::Instant::now(); diff --git a/packages/torrent-repository/benches/helpers/sync.rs b/packages/torrent-repository/benches/helpers/sync.rs index 0523f4141..63fccfc77 100644 --- a/packages/torrent-repository/benches/helpers/sync.rs +++ b/packages/torrent-repository/benches/helpers/sync.rs @@ -20,7 +20,9 @@ where let info_hash = InfoHash([0; 20]); - torrent_repository.update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER); + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER); + + torrent_repository.get_swarm_metadata(&info_hash); } start.elapsed() @@ -37,7 +39,9 @@ where let handles = FuturesUnordered::new(); // Add the torrent/peer to the torrent repository - torrent_repository.update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER); + torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER); + + torrent_repository.get_swarm_metadata(info_hash); let start = Instant::now(); @@ -45,7 +49,9 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone.update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER); + torrent_repository_clone.upsert_peer(info_hash, &DEFAULT_PEER); + + torrent_repository_clone.get_swarm_metadata(info_hash); if let Some(sleep_time) = sleep { let start_time = std::time::Instant::now(); @@ -83,7 +89,9 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone.update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER); + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER); + + torrent_repository_clone.get_swarm_metadata(&info_hash); if let Some(sleep_time) = sleep { let start_time = std::time::Instant::now(); @@ -117,7 +125,8 @@ where // Add the torrents/peers to the torrent repository for info_hash in &info_hashes { - torrent_repository.update_torrent_with_peer_and_get_stats(info_hash, &DEFAULT_PEER); + torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER); + torrent_repository.get_swarm_metadata(info_hash); } let start = Instant::now(); @@ -126,7 +135,8 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone.update_torrent_with_peer_and_get_stats(&info_hash, &DEFAULT_PEER); + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER); + torrent_repository_clone.get_swarm_metadata(&info_hash); if let Some(sleep_time) = sleep { let start_time = std::time::Instant::now(); diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index 4c39af829..d72ff254b 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -15,7 +15,7 @@ pub trait Entry { /// It returns the swarm metadata (statistics) as a struct: /// /// `(seeders, completed, leechers)` - fn get_stats(&self) -> SwarmMetadata; + fn get_swarm_metadata(&self) -> SwarmMetadata; /// Returns True if Still a Valid Entry according to the Tracker Policy fn is_good(&self, policy: &TrackerPolicy) -> bool; @@ -40,10 +40,7 @@ pub trait Entry { /// /// The number of peers that have complete downloading is synchronously updated when peers are updated. /// That's the total torrent downloads counter. - fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool; - - // It preforms a combined operation of `insert_or_update_peer` and `get_stats`. - fn insert_or_update_peer_and_get_stats(&mut self, peer: &peer::Peer) -> (bool, SwarmMetadata); + fn upsert_peer(&mut self, peer: &peer::Peer) -> bool; /// It removes peer from the swarm that have not been updated for more than `current_cutoff` seconds fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch); @@ -51,20 +48,19 @@ pub trait Entry { #[allow(clippy::module_name_repetitions)] pub trait EntrySync { - fn get_stats(&self) -> SwarmMetadata; + fn get_swarm_metadata(&self) -> SwarmMetadata; fn is_good(&self, policy: &TrackerPolicy) -> bool; fn peers_is_empty(&self) -> bool; fn get_peers_len(&self) -> usize; fn get_peers(&self, limit: Option) -> Vec>; fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec>; - fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool; - fn insert_or_update_peer_and_get_stats(&self, peer: &peer::Peer) -> (bool, SwarmMetadata); + fn upsert_peer(&self, peer: &peer::Peer) -> bool; fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); } #[allow(clippy::module_name_repetitions)] pub trait EntryAsync { - fn get_stats(&self) -> impl std::future::Future + Send; + fn get_swarm_metadata(&self) -> impl std::future::Future + Send; fn check_good(self, policy: &TrackerPolicy) -> impl std::future::Future + Send; fn peers_is_empty(&self) -> impl std::future::Future + Send; fn get_peers_len(&self) -> impl std::future::Future + Send; @@ -74,11 +70,7 @@ pub trait EntryAsync { client: &SocketAddr, limit: Option, ) -> impl std::future::Future>> + Send; - fn insert_or_update_peer(self, peer: &peer::Peer) -> impl std::future::Future + Send; - fn insert_or_update_peer_and_get_stats( - self, - peer: &peer::Peer, - ) -> impl std::future::Future + std::marker::Send; + fn upsert_peer(self, peer: &peer::Peer) -> impl std::future::Future + Send; fn remove_inactive_peers(self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; } diff --git a/packages/torrent-repository/src/entry/mutex_std.rs b/packages/torrent-repository/src/entry/mutex_std.rs index b4b823909..990d8ab76 100644 --- a/packages/torrent-repository/src/entry/mutex_std.rs +++ b/packages/torrent-repository/src/entry/mutex_std.rs @@ -9,8 +9,8 @@ use super::{Entry, EntrySync}; use crate::{EntryMutexStd, EntrySingle}; impl EntrySync for EntryMutexStd { - fn get_stats(&self) -> SwarmMetadata { - self.lock().expect("it should get a lock").get_stats() + fn get_swarm_metadata(&self) -> SwarmMetadata { + self.lock().expect("it should get a lock").get_swarm_metadata() } fn is_good(&self, policy: &TrackerPolicy) -> bool { @@ -33,14 +33,8 @@ impl EntrySync for EntryMutexStd { self.lock().expect("it should get lock").get_peers_for_client(client, limit) } - fn insert_or_update_peer(&self, peer: &peer::Peer) -> bool { - self.lock().expect("it should lock the entry").insert_or_update_peer(peer) - } - - fn insert_or_update_peer_and_get_stats(&self, peer: &peer::Peer) -> (bool, SwarmMetadata) { - self.lock() - .expect("it should lock the entry") - .insert_or_update_peer_and_get_stats(peer) + fn upsert_peer(&self, peer: &peer::Peer) -> bool { + self.lock().expect("it should lock the entry").upsert_peer(peer) } fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { diff --git a/packages/torrent-repository/src/entry/mutex_tokio.rs b/packages/torrent-repository/src/entry/mutex_tokio.rs index 34f4a4e92..c5363e51a 100644 --- a/packages/torrent-repository/src/entry/mutex_tokio.rs +++ b/packages/torrent-repository/src/entry/mutex_tokio.rs @@ -9,8 +9,8 @@ use super::{Entry, EntryAsync}; use crate::{EntryMutexTokio, EntrySingle}; impl EntryAsync for EntryMutexTokio { - async fn get_stats(&self) -> SwarmMetadata { - self.lock().await.get_stats() + async fn get_swarm_metadata(&self) -> SwarmMetadata { + self.lock().await.get_swarm_metadata() } async fn check_good(self, policy: &TrackerPolicy) -> bool { @@ -33,12 +33,8 @@ impl EntryAsync for EntryMutexTokio { self.lock().await.get_peers_for_client(client, limit) } - async fn insert_or_update_peer(self, peer: &peer::Peer) -> bool { - self.lock().await.insert_or_update_peer(peer) - } - - async fn insert_or_update_peer_and_get_stats(self, peer: &peer::Peer) -> (bool, SwarmMetadata) { - self.lock().await.insert_or_update_peer_and_get_stats(peer) + async fn upsert_peer(self, peer: &peer::Peer) -> bool { + self.lock().await.upsert_peer(peer) } async fn remove_inactive_peers(self, current_cutoff: DurationSinceUnixEpoch) { diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs index c1041e9a2..a38b54023 100644 --- a/packages/torrent-repository/src/entry/single.rs +++ b/packages/torrent-repository/src/entry/single.rs @@ -12,7 +12,7 @@ use crate::EntrySingle; impl Entry for EntrySingle { #[allow(clippy::cast_possible_truncation)] - fn get_stats(&self) -> SwarmMetadata { + fn get_swarm_metadata(&self) -> SwarmMetadata { let complete: u32 = self.peers.values().filter(|peer| peer.is_seeder()).count() as u32; let incomplete: u32 = self.peers.len() as u32 - complete; @@ -70,7 +70,7 @@ impl Entry for EntrySingle { } } - fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool { + fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { let mut downloaded_stats_updated: bool = false; match peer::ReadInfo::get_event(peer) { @@ -93,12 +93,6 @@ impl Entry for EntrySingle { downloaded_stats_updated } - fn insert_or_update_peer_and_get_stats(&mut self, peer: &peer::Peer) -> (bool, SwarmMetadata) { - let changed = self.insert_or_update_peer(peer); - let stats = self.get_stats(); - (changed, stats) - } - fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { self.peers .retain(|_, peer| peer::ReadInfo::get_updated(peer) > current_cutoff); diff --git a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs index 67c47973e..b398b09dc 100644 --- a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs @@ -23,19 +23,21 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { if let Some(entry) = self.torrents.get(info_hash) { - entry.insert_or_update_peer_and_get_stats(peer) + entry.upsert_peer(peer); } else { let _unused = self.torrents.insert(*info_hash, Arc::default()); - - match self.torrents.get(info_hash) { - Some(entry) => entry.insert_or_update_peer_and_get_stats(peer), - None => (false, SwarmMetadata::zeroed()), + if let Some(entry) = self.torrents.get(info_hash) { + entry.upsert_peer(peer); } } } + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) + } + fn get(&self, key: &InfoHash) -> Option { let maybe_entry = self.torrents.get(key); maybe_entry.map(|entry| entry.clone()) @@ -45,7 +47,7 @@ where let mut metrics = TorrentsMetrics::default(); for entry in &self.torrents { - let stats = entry.value().lock().expect("it should get a lock").get_stats(); + let stats = entry.value().lock().expect("it should get a lock").get_swarm_metadata(); metrics.complete += u64::from(stats.complete); metrics.downloaded += u64::from(stats.downloaded); metrics.incomplete += u64::from(stats.incomplete); diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs index c7c64c54a..f198288f8 100644 --- a/packages/torrent-repository/src/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -24,7 +24,8 @@ pub trait Repository: Debug + Default + Sized + 'static { fn remove(&self, key: &InfoHash) -> Option; fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); fn remove_peerless_torrents(&self, policy: &TrackerPolicy); - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata); + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer); + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option; } #[allow(clippy::module_name_repetitions)] @@ -36,9 +37,6 @@ pub trait RepositoryAsync: Debug + Default + Sized + 'static { fn remove(&self, key: &InfoHash) -> impl std::future::Future> + Send; fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> impl std::future::Future + Send; - fn update_torrent_with_peer_and_get_stats( - &self, - info_hash: &InfoHash, - peer: &peer::Peer, - ) -> impl std::future::Future + Send; + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> impl std::future::Future + Send; + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> impl std::future::Future> + Send; } diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs index e9074a271..af48428e4 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std.rs @@ -47,12 +47,16 @@ impl Repository for TorrentsRwLockStd where EntrySingle: Entry, { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { let mut db = self.get_torrents_mut(); let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); - entry.insert_or_update_peer_and_get_stats(peer) + entry.upsert_peer(peer); + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.get(info_hash).map(|entry| entry.get_swarm_metadata()) } fn get(&self, key: &InfoHash) -> Option { @@ -64,7 +68,7 @@ where let mut metrics = TorrentsMetrics::default(); for entry in self.get_torrents().values() { - let stats = entry.get_stats(); + let stats = entry.get_swarm_metadata(); metrics.complete += u64::from(stats.complete); metrics.downloaded += u64::from(stats.downloaded); metrics.incomplete += u64::from(stats.incomplete); diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs index 0b65234e3..74cdc4475 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs @@ -33,7 +33,7 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { let maybe_entry = self.get_torrents().get(info_hash).cloned(); let entry = if let Some(entry) = maybe_entry { @@ -44,7 +44,13 @@ where entry.clone() }; - entry.insert_or_update_peer_and_get_stats(peer) + entry.upsert_peer(peer); + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.get_torrents() + .get(info_hash) + .map(super::super::entry::EntrySync::get_swarm_metadata) } fn get(&self, key: &InfoHash) -> Option { @@ -56,7 +62,7 @@ where let mut metrics = TorrentsMetrics::default(); for entry in self.get_torrents().values() { - let stats = entry.lock().expect("it should get a lock").get_stats(); + let stats = entry.lock().expect("it should get a lock").get_swarm_metadata(); metrics.complete += u64::from(stats.complete); metrics.downloaded += u64::from(stats.downloaded); metrics.incomplete += u64::from(stats.incomplete); diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs index 5394abb6a..83ac02c91 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs @@ -37,7 +37,7 @@ where EntryMutexTokio: EntryAsync, EntrySingle: Entry, { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { let maybe_entry = self.get_torrents().get(info_hash).cloned(); let entry = if let Some(entry) = maybe_entry { @@ -48,8 +48,18 @@ where entry.clone() }; - entry.insert_or_update_peer_and_get_stats(peer).await + entry.upsert_peer(peer).await; } + + async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + let maybe_entry = self.get_torrents().get(info_hash).cloned(); + + match maybe_entry { + Some(entry) => Some(entry.get_swarm_metadata().await), + None => None, + } + } + async fn get(&self, key: &InfoHash) -> Option { let db = self.get_torrents(); db.get(key).cloned() @@ -75,7 +85,7 @@ where let entries: Vec<_> = self.get_torrents().values().cloned().collect(); for entry in entries { - let stats = entry.lock().await.get_stats(); + let stats = entry.lock().await.get_swarm_metadata(); metrics.complete += u64::from(stats.complete); metrics.downloaded += u64::from(stats.downloaded); metrics.incomplete += u64::from(stats.incomplete); diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs index d84074eaf..b95f1e31e 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio.rs @@ -51,13 +51,18 @@ impl RepositoryAsync for TorrentsRwLockTokio where EntrySingle: Entry, { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { let mut db = self.get_torrents_mut().await; let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); - entry.insert_or_update_peer_and_get_stats(peer) + entry.upsert_peer(peer); } + + async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.get(info_hash).await.map(|entry| entry.get_swarm_metadata()) + } + async fn get(&self, key: &InfoHash) -> Option { let db = self.get_torrents().await; db.get(key).cloned() @@ -81,7 +86,7 @@ where let mut metrics = TorrentsMetrics::default(); for entry in self.get_torrents().await.values() { - let stats = entry.get_stats(); + let stats = entry.get_swarm_metadata(); metrics.complete += u64::from(stats.complete); metrics.downloaded += u64::from(stats.downloaded); metrics.incomplete += u64::from(stats.incomplete); diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs index fbbc51a09..bde959940 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs @@ -35,7 +35,7 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); let entry = if let Some(entry) = maybe_entry { @@ -46,8 +46,13 @@ where entry.clone() }; - entry.insert_or_update_peer_and_get_stats(peer) + entry.upsert_peer(peer); } + + async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.get(info_hash).await.map(|entry| entry.get_swarm_metadata()) + } + async fn get(&self, key: &InfoHash) -> Option { let db = self.get_torrents().await; db.get(key).cloned() @@ -71,7 +76,7 @@ where let mut metrics = TorrentsMetrics::default(); for entry in self.get_torrents().await.values() { - let stats = entry.get_stats(); + let stats = entry.get_swarm_metadata(); metrics.complete += u64::from(stats.complete); metrics.downloaded += u64::from(stats.downloaded); metrics.incomplete += u64::from(stats.incomplete); diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs index bc7fd61e8..1d002e317 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -35,7 +35,7 @@ where EntryMutexTokio: EntryAsync, EntrySingle: Entry, { - async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); let entry = if let Some(entry) = maybe_entry { @@ -46,8 +46,16 @@ where entry.clone() }; - entry.insert_or_update_peer_and_get_stats(peer).await + entry.upsert_peer(peer).await; } + + async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + match self.get(info_hash).await { + Some(entry) => Some(entry.get_swarm_metadata().await), + None => None, + } + } + async fn get(&self, key: &InfoHash) -> Option { let db = self.get_torrents().await; db.get(key).cloned() @@ -71,7 +79,7 @@ where let mut metrics = TorrentsMetrics::default(); for entry in self.get_torrents().await.values() { - let stats = entry.get_stats().await; + let stats = entry.get_swarm_metadata().await; metrics.complete += u64::from(stats.complete); metrics.downloaded += u64::from(stats.downloaded); metrics.incomplete += u64::from(stats.incomplete); diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index 0c0127b15..ef3e7e478 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -23,9 +23,13 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (bool, SwarmMetadata) { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); - entry.value().insert_or_update_peer_and_get_stats(peer) + entry.value().upsert_peer(peer); + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) } fn get(&self, key: &InfoHash) -> Option { @@ -37,7 +41,7 @@ where let mut metrics = TorrentsMetrics::default(); for entry in &self.torrents { - let stats = entry.value().lock().expect("it should get a lock").get_stats(); + let stats = entry.value().lock().expect("it should get a lock").get_swarm_metadata(); metrics.complete += u64::from(stats.complete); metrics.downloaded += u64::from(stats.downloaded); metrics.incomplete += u64::from(stats.incomplete); diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 5a6eddf97..7c245fe04 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -23,6 +23,32 @@ pub(crate) enum Repo { } impl Repo { + pub(crate) async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + match self { + Repo::RwLockStd(repo) => repo.upsert_peer(info_hash, peer), + Repo::RwLockStdMutexStd(repo) => repo.upsert_peer(info_hash, peer), + Repo::RwLockStdMutexTokio(repo) => repo.upsert_peer(info_hash, peer).await, + Repo::RwLockTokio(repo) => repo.upsert_peer(info_hash, peer).await, + Repo::RwLockTokioMutexStd(repo) => repo.upsert_peer(info_hash, peer).await, + Repo::RwLockTokioMutexTokio(repo) => repo.upsert_peer(info_hash, peer).await, + Repo::SkipMapMutexStd(repo) => repo.upsert_peer(info_hash, peer), + Repo::DashMapMutexStd(repo) => repo.upsert_peer(info_hash, peer), + } + } + + pub(crate) async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + match self { + Repo::RwLockStd(repo) => repo.get_swarm_metadata(info_hash), + Repo::RwLockStdMutexStd(repo) => repo.get_swarm_metadata(info_hash), + Repo::RwLockStdMutexTokio(repo) => repo.get_swarm_metadata(info_hash).await, + Repo::RwLockTokio(repo) => repo.get_swarm_metadata(info_hash).await, + Repo::RwLockTokioMutexStd(repo) => repo.get_swarm_metadata(info_hash).await, + Repo::RwLockTokioMutexTokio(repo) => repo.get_swarm_metadata(info_hash).await, + Repo::SkipMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), + Repo::DashMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), + } + } + pub(crate) async fn get(&self, key: &InfoHash) -> Option { match self { Repo::RwLockStd(repo) => repo.get(key), @@ -145,23 +171,6 @@ impl Repo { } } - pub(crate) async fn update_torrent_with_peer_and_get_stats( - &self, - info_hash: &InfoHash, - peer: &peer::Peer, - ) -> (bool, SwarmMetadata) { - match self { - Repo::RwLockStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), - Repo::RwLockStdMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), - Repo::RwLockStdMutexTokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, - Repo::RwLockTokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, - Repo::RwLockTokioMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, - Repo::RwLockTokioMutexTokio(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer).await, - Repo::SkipMapMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), - Repo::DashMapMutexStd(repo) => repo.update_torrent_with_peer_and_get_stats(info_hash, peer), - } - } - pub(crate) async fn insert(&self, info_hash: &InfoHash, torrent: EntrySingle) -> Option { match self { Repo::RwLockStd(repo) => { diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index 33264c443..c0699479e 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -17,9 +17,9 @@ pub(crate) enum Torrent { impl Torrent { pub(crate) async fn get_stats(&self) -> SwarmMetadata { match self { - Torrent::Single(entry) => entry.get_stats(), - Torrent::MutexStd(entry) => entry.get_stats(), - Torrent::MutexTokio(entry) => entry.clone().get_stats().await, + Torrent::Single(entry) => entry.get_swarm_metadata(), + Torrent::MutexStd(entry) => entry.get_swarm_metadata(), + Torrent::MutexTokio(entry) => entry.clone().get_swarm_metadata().await, } } @@ -63,19 +63,11 @@ impl Torrent { } } - pub(crate) async fn insert_or_update_peer(&mut self, peer: &peer::Peer) -> bool { + pub(crate) async fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { match self { - Torrent::Single(entry) => entry.insert_or_update_peer(peer), - Torrent::MutexStd(entry) => entry.insert_or_update_peer(peer), - Torrent::MutexTokio(entry) => entry.clone().insert_or_update_peer(peer).await, - } - } - - pub(crate) async fn insert_or_update_peer_and_get_stats(&mut self, peer: &peer::Peer) -> (bool, SwarmMetadata) { - match self { - Torrent::Single(entry) => entry.insert_or_update_peer_and_get_stats(peer), - Torrent::MutexStd(entry) => entry.insert_or_update_peer_and_get_stats(peer), - Torrent::MutexTokio(entry) => entry.clone().insert_or_update_peer_and_get_stats(peer).await, + Torrent::Single(entry) => entry.upsert_peer(peer), + Torrent::MutexStd(entry) => entry.upsert_peer(peer), + Torrent::MutexTokio(entry) => entry.clone().upsert_peer(peer).await, } } diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index c39bef636..3c564c6f8 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -62,34 +62,34 @@ async fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { Makes::Empty => vec![], Makes::Started => { let peer = a_started_peer(1); - torrent.insert_or_update_peer(&peer).await; + torrent.upsert_peer(&peer).await; vec![peer] } Makes::Completed => { let peer = a_completed_peer(2); - torrent.insert_or_update_peer(&peer).await; + torrent.upsert_peer(&peer).await; vec![peer] } Makes::Downloaded => { let mut peer = a_started_peer(3); - torrent.insert_or_update_peer(&peer).await; + torrent.upsert_peer(&peer).await; peer.event = AnnounceEvent::Completed; peer.left = NumberOfBytes(0); - torrent.insert_or_update_peer(&peer).await; + torrent.upsert_peer(&peer).await; vec![peer] } Makes::Three => { let peer_1 = a_started_peer(1); - torrent.insert_or_update_peer(&peer_1).await; + torrent.upsert_peer(&peer_1).await; let peer_2 = a_completed_peer(2); - torrent.insert_or_update_peer(&peer_2).await; + torrent.upsert_peer(&peer_2).await; let mut peer_3 = a_started_peer(3); - torrent.insert_or_update_peer(&peer_3).await; + torrent.upsert_peer(&peer_3).await; peer_3.event = AnnounceEvent::Completed; peer_3.left = NumberOfBytes(0); - torrent.insert_or_update_peer(&peer_3).await; + torrent.upsert_peer(&peer_3).await; vec![peer_1, peer_2, peer_3] } } @@ -182,7 +182,7 @@ async fn it_should_update_a_peer( // Make and insert a new peer. let mut peer = a_started_peer(-1); - torrent.insert_or_update_peer(&peer).await; + torrent.upsert_peer(&peer).await; // Get the Inserted Peer by Id. let peers = torrent.get_peers(None).await; @@ -195,7 +195,7 @@ async fn it_should_update_a_peer( // Announce "Completed" torrent download event. peer.event = AnnounceEvent::Completed; - torrent.insert_or_update_peer(&peer).await; + torrent.upsert_peer(&peer).await; // Get the Updated Peer by Id. let peers = torrent.get_peers(None).await; @@ -224,7 +224,7 @@ async fn it_should_remove_a_peer_upon_stopped_announcement( let mut peer = a_started_peer(-1); - torrent.insert_or_update_peer(&peer).await; + torrent.upsert_peer(&peer).await; // The started peer should be inserted. let peers = torrent.get_peers(None).await; @@ -237,7 +237,7 @@ async fn it_should_remove_a_peer_upon_stopped_announcement( // Change peer to "Stopped" and insert. peer.event = AnnounceEvent::Stopped; - torrent.insert_or_update_peer(&peer).await; + torrent.upsert_peer(&peer).await; // It should be removed now. let peers = torrent.get_peers(None).await; @@ -270,13 +270,12 @@ async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloade // Announce "Completed" torrent download event. peer.event = AnnounceEvent::Completed; - let (updated, stats) = torrent.insert_or_update_peer_and_get_stats(&peer).await; + torrent.upsert_peer(&peer).await; + let stats = torrent.get_stats().await; if is_already_completed { - assert!(!updated); assert_eq!(stats.downloaded, downloaded); } else { - assert!(updated); assert_eq!(stats.downloaded, downloaded + 1); } } @@ -301,7 +300,8 @@ async fn it_should_update_a_peer_as_a_seeder( // Set Bytes Left to Zero peer.left = NumberOfBytes(0); - let (_, stats) = torrent.insert_or_update_peer_and_get_stats(&peer).await; // Add the peer + torrent.upsert_peer(&peer).await; + let stats = torrent.get_stats().await; if is_already_non_left { // it was already complete @@ -332,7 +332,8 @@ async fn it_should_update_a_peer_as_incomplete( // Set Bytes Left to no Zero peer.left = NumberOfBytes(1); - let (_, stats) = torrent.insert_or_update_peer_and_get_stats(&peer).await; // Add the peer + torrent.upsert_peer(&peer).await; + let stats = torrent.get_stats().await; if completed_already { // now it is incomplete @@ -368,7 +369,7 @@ async fn it_should_get_peers_excluding_the_client_socket( // set the address to the socket. peer.peer_addr = socket; - torrent.insert_or_update_peer(&peer).await; // Add peer + torrent.upsert_peer(&peer).await; // Add peer // It should not include the peer that has the same socket. assert!(!torrent.get_peers_for_client(&socket, None).await.contains(&peer.into())); @@ -391,7 +392,7 @@ async fn it_should_limit_the_number_of_peers_returned( for peer_number in 1..=74 + 1 { let mut peer = a_started_peer(1); peer.peer_id = peer::Id::from(peer_number); - torrent.insert_or_update_peer(&peer).await; + torrent.upsert_peer(&peer).await; } let peers = torrent.get_peers(Some(TORRENT_PEERS_LIMIT)).await; @@ -422,7 +423,7 @@ async fn it_should_remove_inactive_peers_beyond_cutoff( peer.updated = now.sub(EXPIRE); - torrent.insert_or_update_peer(&peer).await; + torrent.upsert_peer(&peer).await; assert_eq!(torrent.get_peers_len().await, peers.len() + 1); diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index a6784bf57..fde34467e 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -6,6 +6,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{NumberOfBytes, PersistentTorrents}; use torrust_tracker_torrent_repository::entry::Entry as _; use torrust_tracker_torrent_repository::repository::dash_map_mutex_std::XacrimonDashMap; @@ -72,14 +73,14 @@ fn default() -> Entries { #[fixture] fn started() -> Entries { let mut torrent = EntrySingle::default(); - torrent.insert_or_update_peer(&a_started_peer(1)); + torrent.upsert_peer(&a_started_peer(1)); vec![(InfoHash::default(), torrent)] } #[fixture] fn completed() -> Entries { let mut torrent = EntrySingle::default(); - torrent.insert_or_update_peer(&a_completed_peer(2)); + torrent.upsert_peer(&a_completed_peer(2)); vec![(InfoHash::default(), torrent)] } @@ -87,10 +88,10 @@ fn completed() -> Entries { fn downloaded() -> Entries { let mut torrent = EntrySingle::default(); let mut peer = a_started_peer(3); - torrent.insert_or_update_peer(&peer); + torrent.upsert_peer(&peer); peer.event = AnnounceEvent::Completed; peer.left = NumberOfBytes(0); - torrent.insert_or_update_peer(&peer); + torrent.upsert_peer(&peer); vec![(InfoHash::default(), torrent)] } @@ -98,21 +99,21 @@ fn downloaded() -> Entries { fn three() -> Entries { let mut started = EntrySingle::default(); let started_h = &mut DefaultHasher::default(); - started.insert_or_update_peer(&a_started_peer(1)); + started.upsert_peer(&a_started_peer(1)); started.hash(started_h); let mut completed = EntrySingle::default(); let completed_h = &mut DefaultHasher::default(); - completed.insert_or_update_peer(&a_completed_peer(2)); + completed.upsert_peer(&a_completed_peer(2)); completed.hash(completed_h); let mut downloaded = EntrySingle::default(); let downloaded_h = &mut DefaultHasher::default(); let mut downloaded_peer = a_started_peer(3); - downloaded.insert_or_update_peer(&downloaded_peer); + downloaded.upsert_peer(&downloaded_peer); downloaded_peer.event = AnnounceEvent::Completed; downloaded_peer.left = NumberOfBytes(0); - downloaded.insert_or_update_peer(&downloaded_peer); + downloaded.upsert_peer(&downloaded_peer); downloaded.hash(downloaded_h); vec![ @@ -128,7 +129,7 @@ fn many_out_of_order() -> Entries { for i in 0..408 { let mut entry = EntrySingle::default(); - entry.insert_or_update_peer(&a_started_peer(i)); + entry.upsert_peer(&a_started_peer(i)); entries.insert((InfoHash::from(&i), entry)); } @@ -143,7 +144,7 @@ fn many_hashed_in_order() -> Entries { for i in 0..408 { let mut entry = EntrySingle::default(); - entry.insert_or_update_peer(&a_started_peer(i)); + entry.upsert_peer(&a_started_peer(i)); let hash: &mut DefaultHasher = &mut DefaultHasher::default(); hash.write_i32(i); @@ -390,7 +391,7 @@ async fn it_should_get_metrics( let mut metrics = TorrentsMetrics::default(); for (_, torrent) in entries { - let stats = torrent.get_stats(); + let stats = torrent.get_swarm_metadata(); metrics.torrents += 1; metrics.incomplete += u64::from(stats.incomplete); @@ -537,10 +538,25 @@ async fn it_should_remove_inactive_peers( // Insert the infohash and peer into the repository // and verify there is an extra torrent entry. { - repo.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; + repo.upsert_peer(&info_hash, &peer).await; assert_eq!(repo.get_metrics().await.torrents, entries.len() as u64 + 1); } + // Insert the infohash and peer into the repository + // and verify the swarm metadata was updated. + { + repo.upsert_peer(&info_hash, &peer).await; + let stats = repo.get_swarm_metadata(&info_hash).await; + assert_eq!( + stats, + Some(SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }) + ); + } + // Verify that this new peer was inserted into the repository. { let entry = repo.get(&info_hash).await.expect("it_should_get_some"); diff --git a/src/core/mod.rs b/src/core/mod.rs index 6628426c1..83813a863 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -626,10 +626,9 @@ impl Tracker { peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.external_ip)); debug!("After: {peer:?}"); - // we should update the torrent and get the stats before we get the peer list. - let stats = self.update_torrent_with_peer_and_get_stats(info_hash, peer).await; + let stats = self.upsert_peer_and_get_stats(info_hash, peer).await; - let peers = self.get_torrent_peers_for_peer(info_hash, peer); + let peers = self.get_peers_for(info_hash, peer); AnnounceData { peers, @@ -660,7 +659,7 @@ impl Tracker { /// It returns the data for a `scrape` response. fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { match self.torrents.get(info_hash) { - Some(torrent_entry) => torrent_entry.get_stats(), + Some(torrent_entry) => torrent_entry.get_swarm_metadata(), None => SwarmMetadata::default(), } } @@ -681,7 +680,7 @@ impl Tracker { Ok(()) } - fn get_torrent_peers_for_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> Vec> { + fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer) -> Vec> { match self.torrents.get(info_hash) { None => vec![], Some(entry) => entry.get_peers_for_client(&peer.peer_addr, Some(TORRENT_PEERS_LIMIT)), @@ -703,20 +702,36 @@ impl Tracker { /// needed for a `announce` request response. /// /// # Context: Tracker - pub async fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { - // code-review: consider splitting the function in two (command and query segregation). - // `update_torrent_with_peer` and `get_stats` + pub async fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { + let swarm_metadata_before = match self.torrents.get_swarm_metadata(info_hash) { + Some(swarm_metadata) => swarm_metadata, + None => SwarmMetadata::zeroed(), + }; - let (stats_updated, stats) = self.torrents.update_torrent_with_peer_and_get_stats(info_hash, peer); + self.torrents.upsert_peer(info_hash, peer); - if self.policy.persistent_torrent_completed_stat && stats_updated { - let completed = stats.downloaded; + let swarm_metadata_after = match self.torrents.get_swarm_metadata(info_hash) { + Some(swarm_metadata) => swarm_metadata, + None => SwarmMetadata::zeroed(), + }; + + if swarm_metadata_before != swarm_metadata_after { + self.persist_stats(info_hash, &swarm_metadata_after).await; + } + + swarm_metadata_after + } + + /// It stores the torrents stats into the database (if persistency is enabled). + /// + /// # Context: Tracker + async fn persist_stats(&self, info_hash: &InfoHash, swarm_metadata: &SwarmMetadata) { + if self.policy.persistent_torrent_completed_stat { + let completed = swarm_metadata.downloaded; let info_hash = *info_hash; drop(self.database.save_persistent_torrent(&info_hash, completed).await); } - - stats } /// It calculates and returns the general `Tracker` @@ -1130,7 +1145,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; + tracker.upsert_peer_and_get_stats(&info_hash, &peer).await; let peers = tracker.get_torrent_peers(&info_hash); @@ -1144,9 +1159,9 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; + tracker.upsert_peer_and_get_stats(&info_hash, &peer).await; - let peers = tracker.get_torrent_peers_for_peer(&info_hash, &peer); + let peers = tracker.get_peers_for(&info_hash, &peer); assert_eq!(peers, vec![]); } @@ -1155,9 +1170,7 @@ mod tests { async fn it_should_return_the_torrent_metrics() { let tracker = public_tracker(); - tracker - .update_torrent_with_peer_and_get_stats(&sample_info_hash(), &leecher()) - .await; + tracker.upsert_peer_and_get_stats(&sample_info_hash(), &leecher()).await; let torrent_metrics = tracker.get_torrents_metrics(); @@ -1178,9 +1191,7 @@ mod tests { let start_time = std::time::Instant::now(); for i in 0..1_000_000 { - tracker - .update_torrent_with_peer_and_get_stats(&gen_seeded_infohash(&i), &leecher()) - .await; + tracker.upsert_peer_and_get_stats(&gen_seeded_infohash(&i), &leecher()).await; } let result_a = start_time.elapsed(); @@ -1704,11 +1715,11 @@ mod tests { let mut peer = sample_peer(); peer.event = AnnounceEvent::Started; - let swarm_stats = tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; + let swarm_stats = tracker.upsert_peer_and_get_stats(&info_hash, &peer).await; assert_eq!(swarm_stats.downloaded, 0); peer.event = AnnounceEvent::Completed; - let swarm_stats = tracker.update_torrent_with_peer_and_get_stats(&info_hash, &peer).await; + let swarm_stats = tracker.upsert_peer_and_get_stats(&info_hash, &peer).await; assert_eq!(swarm_stats.downloaded, 1); // Remove the newly updated torrent from memory @@ -1719,7 +1730,7 @@ mod tests { let torrent_entry = tracker.torrents.get(&info_hash).expect("it should be able to get entry"); // It persists the number of completed peers. - assert_eq!(torrent_entry.get_stats().downloaded, 1); + assert_eq!(torrent_entry.get_swarm_metadata().downloaded, 1); // It does not persist the peers assert!(torrent_entry.peers_is_empty()); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index ce44af3a8..9cba5de25 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -50,7 +50,7 @@ pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Op let torrent_entry = torrent_entry_option?; - let stats = torrent_entry.get_stats(); + let stats = torrent_entry.get_swarm_metadata(); let peers = torrent_entry.get_peers(None); @@ -70,7 +70,7 @@ pub async fn get_torrents_page(tracker: Arc, pagination: Option<&Pagina let mut basic_infos: Vec = vec![]; for (info_hash, torrent_entry) in tracker.torrents.get_paginated(pagination) { - let stats = torrent_entry.get_stats(); + let stats = torrent_entry.get_swarm_metadata(); basic_infos.push(BasicInfo { info_hash, @@ -88,7 +88,7 @@ pub async fn get_torrents(tracker: Arc, info_hashes: &[InfoHash]) -> Ve let mut basic_infos: Vec = vec![]; for info_hash in info_hashes { - if let Some(stats) = tracker.torrents.get(info_hash).map(|t| t.get_stats()) { + if let Some(stats) = tracker.torrents.get(info_hash).map(|t| t.get_swarm_metadata()) { basic_infos.push(BasicInfo { info_hash: *info_hash, seeders: u64::from(stats.complete), @@ -156,9 +156,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - tracker - .update_torrent_with_peer_and_get_stats(&info_hash, &sample_peer()) - .await; + tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()).await; let torrent_info = get_torrent_info(tracker.clone(), &info_hash).await.unwrap(); @@ -208,9 +206,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - tracker - .update_torrent_with_peer_and_get_stats(&info_hash, &sample_peer()) - .await; + tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()).await; let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -234,12 +230,8 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - tracker - .update_torrent_with_peer_and_get_stats(&info_hash1, &sample_peer()) - .await; - tracker - .update_torrent_with_peer_and_get_stats(&info_hash2, &sample_peer()) - .await; + tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()).await; + tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()).await; let offset = 0; let limit = 1; @@ -258,12 +250,8 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - tracker - .update_torrent_with_peer_and_get_stats(&info_hash1, &sample_peer()) - .await; - tracker - .update_torrent_with_peer_and_get_stats(&info_hash2, &sample_peer()) - .await; + tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()).await; + tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()).await; let offset = 1; let limit = 4000; @@ -288,15 +276,11 @@ mod tests { let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - tracker - .update_torrent_with_peer_and_get_stats(&info_hash1, &sample_peer()) - .await; + tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()).await; let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - tracker - .update_torrent_with_peer_and_get_stats(&info_hash2, &sample_peer()) - .await; + tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()).await; let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 2d5038ec3..122e666a8 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -718,9 +718,7 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); - tracker - .update_torrent_with_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv6) - .await; + tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv6).await; } async fn announce_a_new_peer_using_ipv4(tracker: Arc) -> Response { @@ -944,9 +942,7 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) .into(); - tracker - .update_torrent_with_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv4) - .await; + tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv4).await; } async fn announce_a_new_peer_using_ipv6(tracker: Arc) -> Response { @@ -1119,9 +1115,7 @@ mod tests { .with_number_of_bytes_left(0) .into(); - tracker - .update_torrent_with_peer_and_get_stats(&info_hash.0.into(), &peer) - .await; + tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer).await; } fn build_scrape_request(remote_addr: &SocketAddr, info_hash: &InfoHash) -> ScrapeRequest { diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 8d91f3ae8..dec4ccff2 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -23,7 +23,7 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; + self.tracker.upsert_peer_and_get_stats(info_hash, peer).await; } } diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 5638713aa..f00da293e 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -20,7 +20,7 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; + self.tracker.upsert_peer_and_get_stats(info_hash, peer).await; } } diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 12f4aeb9e..6ced1dbb7 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -20,7 +20,7 @@ impl Environment { /// Add a torrent to the tracker #[allow(dead_code)] pub async fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { - self.tracker.update_torrent_with_peer_and_get_stats(info_hash, peer).await; + self.tracker.upsert_peer_and_get_stats(info_hash, peer).await; } } From 5fa01e76a2d17337e450e2c54c41a473ee215353 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 15 Apr 2024 08:50:47 +0100 Subject: [PATCH 0288/1297] chore(deps): update dependencies ```output Updating crates.io index Updating allocator-api2 v0.2.16 -> v0.2.18 Updating anyhow v1.0.81 -> v1.0.82 Updating async-channel v2.2.0 -> v2.2.1 Updating async-executor v1.10.0 -> v1.11.0 Updating async-trait v0.1.79 -> v0.1.80 Updating axum-client-ip v0.5.1 -> v0.6.0 Updating cc v1.0.91 -> v1.0.94 Updating either v1.10.0 -> v1.11.0 Updating encoding_rs v0.8.33 -> v0.8.34 Updating jobserver v0.1.28 -> v0.1.30 Updating proc-macro2 v1.0.79 -> v1.0.80 Updating quote v1.0.35 -> v1.0.36 Updating rstest v0.18.2 -> v0.19.0 Updating rstest_macros v0.18.2 -> v0.19.0 Updating serde_repr v0.1.18 -> v0.1.19 Updating syn v2.0.58 -> v2.0.59 Updating time v0.3.34 -> v0.3.36 Updating time-macros v0.2.17 -> v0.2.18 Updating windows-targets v0.52.4 -> v0.52.5 Updating windows_aarch64_gnullvm v0.52.4 -> v0.52.5 Updating windows_aarch64_msvc v0.52.4 -> v0.52.5 Updating windows_i686_gnu v0.52.4 -> v0.52.5 Adding windows_i686_gnullvm v0.52.5 Updating windows_i686_msvc v0.52.4 -> v0.52.5 Updating windows_x86_64_gnu v0.52.4 -> v0.52.5 Updating windows_x86_64_gnullvm v0.52.4 -> v0.52.5 Updating windows_x86_64_msvc v0.52.4 -> v0.52.5 Updating winnow v0.6.5 -> v0.6.6 ``` --- Cargo.lock | 200 +++++++++++++++++++++++++++-------------------------- 1 file changed, 103 insertions(+), 97 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6b9be523c..f13ed1482 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -66,9 +66,9 @@ dependencies = [ [[package]] name = "allocator-api2" -version = "0.2.16" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" +checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" [[package]] name = "android-tzdata" @@ -141,9 +141,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.81" +version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0952808a6c2afd1aa8947271f3a60f1a6763c7b912d210184c5149b5cf147247" +checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519" [[package]] name = "aquatic_udp_protocol" @@ -190,9 +190,9 @@ dependencies = [ [[package]] name = "async-channel" -version = "2.2.0" +version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28243a43d821d11341ab73c80bed182dc015c514b951616cf79bd4af39af0c3" +checksum = "136d4d23bcc79e27423727b36823d86233aad06dfea531837b038394d11e9928" dependencies = [ "concurrent-queue", "event-listener 5.3.0", @@ -219,11 +219,10 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f98c37cf288e302c16ef6c8472aad1e034c6c84ce5ea7b8101c98eb4a802fee" +checksum = "b10202063978b3351199d68f8b22c4e47e4b1b822f8d43fd862d5ea8c006b29a" dependencies = [ - "async-lock 3.3.0", "async-task", "concurrent-queue", "fastrand 2.0.2", @@ -237,7 +236,7 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" dependencies = [ - "async-channel 2.2.0", + "async-channel 2.2.1", "async-executor", "async-io 2.3.2", "async-lock 3.3.0", @@ -341,13 +340,13 @@ checksum = "fbb36e985947064623dbd357f727af08ffd077f93d696782f3c56365fa2e2799" [[package]] name = "async-trait" -version = "0.1.79" +version = "0.1.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a507401cad91ec6a857ed5513a2073c82a9b9048762b885bb98655b306964681" +checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -399,9 +398,9 @@ dependencies = [ [[package]] name = "axum-client-ip" -version = "0.5.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e7c467bdcd2bd982ce5c8742a1a178aba7b03db399fd18f5d5d438f5aa91cb4" +checksum = "72188bed20deb981f3a4a9fe674e5980fd9e9c2bd880baa94715ad5d60d64c67" dependencies = [ "axum", "forwarded-header-value", @@ -461,7 +460,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -548,7 +547,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -593,7 +592,7 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a37913e8dc4ddcc604f0c6d3bf2887c995153af3611de9e23c352b44c1b9118" dependencies = [ - "async-channel 2.2.0", + "async-channel 2.2.1", "async-lock 3.3.0", "async-task", "fastrand 2.0.2", @@ -623,7 +622,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", "syn_derive", ] @@ -702,9 +701,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.0.91" +version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd97381a8cc6493395a5afc4c691c1084b3768db713b73aa215217aa245d153" +checksum = "17f6e324229dc011159fcc089755d1e2e216a90d43a7dea6853ca740b84f35e7" dependencies = [ "jobserver", "libc", @@ -741,7 +740,7 @@ dependencies = [ "iana-time-zone", "num-traits", "serde", - "windows-targets 0.52.4", + "windows-targets 0.52.5", ] [[package]] @@ -813,7 +812,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -1086,7 +1085,7 @@ dependencies = [ "proc-macro2", "quote", "strsim 0.10.0", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -1097,7 +1096,7 @@ checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" dependencies = [ "darling_core", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -1144,7 +1143,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -1174,15 +1173,15 @@ checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" [[package]] name = "either" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11157ac094ffbdde99aa67b23417ebdd801842852b500e395a45a9c0aac03e4a" +checksum = "a47c1c47d2f5964e29c61246e81db715514cd532db6b5116a25ea3c03d6780a2" [[package]] name = "encoding_rs" -version = "0.8.33" +version = "0.8.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1" +checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59" dependencies = [ "cfg-if", ] @@ -1379,7 +1378,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -1391,7 +1390,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -1403,7 +1402,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -1496,7 +1495,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -1912,9 +1911,9 @@ checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "jobserver" -version = "0.1.28" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab46a6e9526ddef3ae7f787c06f0f2600639ba80ea3eade3d8e670a2230f51d6" +checksum = "685a7d121ee3f65ae4fddd72b25a04bb36b6af81bc0828f7d5434c0fe60fa3a2" dependencies = [ "libc", ] @@ -2046,7 +2045,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c2a198fb6b0eada2a8df47933734e6d35d350665a33a3593d7164fa52c75c19" dependencies = [ "cfg-if", - "windows-targets 0.52.4", + "windows-targets 0.52.5", ] [[package]] @@ -2197,7 +2196,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -2248,7 +2247,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", "termcolor", "thiserror", ] @@ -2448,7 +2447,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -2561,7 +2560,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -2630,7 +2629,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -2804,9 +2803,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.79" +version = "1.0.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" +checksum = "a56dea16b0a29e94408b9aa5e2940a4eedbd128a1ba20e8f7ae60fd3d465af0e" dependencies = [ "unicode-ident", ] @@ -2833,9 +2832,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.35" +version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] @@ -3090,9 +3089,9 @@ dependencies = [ [[package]] name = "rstest" -version = "0.18.2" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97eeab2f3c0a199bc4be135c36c924b6590b88c377d416494288c14f2db30199" +checksum = "9d5316d2a1479eeef1ea21e7f9ddc67c191d497abc8fc3ba2467857abbb68330" dependencies = [ "futures", "futures-timer", @@ -3102,9 +3101,9 @@ dependencies = [ [[package]] name = "rstest_macros" -version = "0.18.2" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d428f8247852f894ee1be110b375111b586d4fa431f6c46e64ba5a0dcccbe605" +checksum = "04a9df72cc1f67020b0d63ad9bfe4a323e459ea7eb68e03bd9824db49f9a4c25" dependencies = [ "cfg-if", "glob", @@ -3113,7 +3112,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.58", + "syn 2.0.59", "unicode-ident", ] @@ -3375,7 +3374,7 @@ checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -3414,13 +3413,13 @@ dependencies = [ [[package]] name = "serde_repr" -version = "0.1.18" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b2e6b945e9d3df726b65d6ee24060aff8e3533d431f677a9695db04eff9dfdb" +checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -3471,7 +3470,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -3605,9 +3604,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.58" +version = "2.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44cfb93f38070beee36b3fef7d4f5a16f27751d94b187b666a5cc5e9b0d30687" +checksum = "4a6531ffc7b071655e4ce2e04bd464c4830bb585a61cabb96cf808f05172615a" dependencies = [ "proc-macro2", "quote", @@ -3623,7 +3622,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -3726,14 +3725,14 @@ checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] name = "time" -version = "0.3.34" +version = "0.3.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" dependencies = [ "deranged", "itoa", @@ -3752,9 +3751,9 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.17" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" dependencies = [ "num-conv", "time-core", @@ -3820,7 +3819,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -3910,7 +3909,7 @@ dependencies = [ "serde", "serde_spanned", "toml_datetime", - "winnow 0.6.5", + "winnow 0.6.6", ] [[package]] @@ -4126,7 +4125,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] @@ -4297,7 +4296,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", "wasm-bindgen-shared", ] @@ -4331,7 +4330,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4389,7 +4388,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ - "windows-targets 0.52.4", + "windows-targets 0.52.5", ] [[package]] @@ -4407,7 +4406,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.4", + "windows-targets 0.52.5", ] [[package]] @@ -4427,17 +4426,18 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.4" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" dependencies = [ - "windows_aarch64_gnullvm 0.52.4", - "windows_aarch64_msvc 0.52.4", - "windows_i686_gnu 0.52.4", - "windows_i686_msvc 0.52.4", - "windows_x86_64_gnu 0.52.4", - "windows_x86_64_gnullvm 0.52.4", - "windows_x86_64_msvc 0.52.4", + "windows_aarch64_gnullvm 0.52.5", + "windows_aarch64_msvc 0.52.5", + "windows_i686_gnu 0.52.5", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.5", + "windows_x86_64_gnu 0.52.5", + "windows_x86_64_gnullvm 0.52.5", + "windows_x86_64_msvc 0.52.5", ] [[package]] @@ -4448,9 +4448,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.4" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" [[package]] name = "windows_aarch64_msvc" @@ -4460,9 +4460,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.52.4" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" [[package]] name = "windows_i686_gnu" @@ -4472,9 +4472,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.52.4" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" [[package]] name = "windows_i686_msvc" @@ -4484,9 +4490,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.52.4" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" [[package]] name = "windows_x86_64_gnu" @@ -4496,9 +4502,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.52.4" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" [[package]] name = "windows_x86_64_gnullvm" @@ -4508,9 +4514,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.4" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" [[package]] name = "windows_x86_64_msvc" @@ -4520,9 +4526,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.52.4" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" [[package]] name = "winnow" @@ -4535,9 +4541,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.6.5" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dffa400e67ed5a4dd237983829e66475f0a4a26938c4b04c21baede6262215b8" +checksum = "f0c976aaaa0e1f90dbb21e9587cdaf1d9679a1cde8875c0d6bd83ab96a208352" dependencies = [ "memchr", ] @@ -4587,7 +4593,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.58", + "syn 2.0.59", ] [[package]] From 4a567cd631cc6bdd220904b1af6fdf524192769b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 15 Apr 2024 17:39:50 +0100 Subject: [PATCH 0289/1297] refactor: extract PeerList Extract a type for a collection of peers. The performance adter the exatract is similar: ```output Requests out: 415067.21/second Responses in: 369397.08/second - Connect responses: 183049.81 - Announce responses: 182717.15 - Scrape responses: 3630.12 - Error responses: 0.00 Peers per announce response: 0.00 Announce responses per info hash: - p10: 1 - p25: 1 - p50: 1 - p75: 1 - p90: 2 - p95: 3 - p99: 104 - p99.9: 297 - p100: 375 ``` --- packages/torrent-repository/src/entry/mod.rs | 68 ++++++++++++++++++- .../torrent-repository/src/entry/single.rs | 32 ++------- .../src/repository/dash_map_mutex_std.rs | 5 +- .../src/repository/rw_lock_std.rs | 6 +- .../src/repository/rw_lock_std_mutex_std.rs | 5 +- .../src/repository/rw_lock_std_mutex_tokio.rs | 5 +- .../src/repository/rw_lock_tokio.rs | 6 +- .../src/repository/rw_lock_tokio_mutex_std.rs | 5 +- .../repository/rw_lock_tokio_mutex_tokio.rs | 5 +- .../src/repository/skip_map_mutex_std.rs | 5 +- 10 files changed, 88 insertions(+), 54 deletions(-) diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index d72ff254b..ee80305ee 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -82,8 +82,72 @@ pub trait EntryAsync { #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Torrent { /// The swarm: a network of peers that are all trying to download the torrent associated to this entry - // #[serde(skip)] - pub(crate) peers: std::collections::BTreeMap>, + pub(crate) peers: PeerList, /// The number of peers that have ever completed downloading the torrent associated to this entry pub(crate) downloaded: u32, } + +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct PeerList { + peers: std::collections::BTreeMap>, +} + +impl PeerList { + fn len(&self) -> usize { + self.peers.len() + } + + fn is_empty(&self) -> bool { + self.peers.is_empty() + } + + fn insert(&mut self, key: peer::Id, value: Arc) -> Option> { + self.peers.insert(key, value) + } + + fn remove(&mut self, key: &peer::Id) -> Option> { + self.peers.remove(key) + } + + fn retain(&mut self, f: F) + where + F: FnMut(&peer::Id, &mut Arc) -> bool, + { + self.peers.retain(f); + } + + fn seeders_and_leechers(&self) -> (usize, usize) { + let seeders = self.peers.values().filter(|peer| peer.is_seeder()).count(); + let leechers = self.len() - seeders; + + (seeders, leechers) + } + + fn get_peers(&self, limit: Option) -> Vec> { + match limit { + Some(limit) => self.peers.values().take(limit).cloned().collect(), + None => self.peers.values().cloned().collect(), + } + } + + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + match limit { + Some(limit) => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *client) + // Limit the number of peers on the result + .take(limit) + .cloned() + .collect(), + None => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *client) + .cloned() + .collect(), + } + } +} diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs index a38b54023..36d04c3cf 100644 --- a/packages/torrent-repository/src/entry/single.rs +++ b/packages/torrent-repository/src/entry/single.rs @@ -13,13 +13,12 @@ use crate::EntrySingle; impl Entry for EntrySingle { #[allow(clippy::cast_possible_truncation)] fn get_swarm_metadata(&self) -> SwarmMetadata { - let complete: u32 = self.peers.values().filter(|peer| peer.is_seeder()).count() as u32; - let incomplete: u32 = self.peers.len() as u32 - complete; + let (seeders, leechers) = self.peers.seeders_and_leechers(); SwarmMetadata { downloaded: self.downloaded, - complete, - incomplete, + complete: seeders as u32, + incomplete: leechers as u32, } } @@ -42,32 +41,13 @@ impl Entry for EntrySingle { fn get_peers_len(&self) -> usize { self.peers.len() } + fn get_peers(&self, limit: Option) -> Vec> { - match limit { - Some(limit) => self.peers.values().take(limit).cloned().collect(), - None => self.peers.values().cloned().collect(), - } + self.peers.get_peers(limit) } fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { - match limit { - Some(limit) => self - .peers - .values() - // Take peers which are not the client peer - .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *client) - // Limit the number of peers on the result - .take(limit) - .cloned() - .collect(), - None => self - .peers - .values() - // Take peers which are not the client peer - .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *client) - .cloned() - .collect(), - } + self.peers.get_peers_for_client(client, limit) } fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { diff --git a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs index b398b09dc..2aba7e54f 100644 --- a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs @@ -1,4 +1,3 @@ -use std::collections::BTreeMap; use std::sync::Arc; use dashmap::DashMap; @@ -10,7 +9,7 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::Repository; -use crate::entry::{Entry, EntrySync}; +use crate::entry::{Entry, EntrySync, PeerList}; use crate::{EntryMutexStd, EntrySingle}; #[derive(Default, Debug)] @@ -82,7 +81,7 @@ where let entry = EntryMutexStd::new( EntrySingle { - peers: BTreeMap::default(), + peers: PeerList::default(), downloaded: *completed, } .into(), diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs index af48428e4..7d8055fca 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std.rs @@ -1,5 +1,3 @@ -use std::collections::BTreeMap; - use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; @@ -8,7 +6,7 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::Repository; -use crate::entry::Entry; +use crate::entry::{Entry, PeerList}; use crate::{EntrySingle, TorrentsRwLockStd}; #[derive(Default, Debug)] @@ -102,7 +100,7 @@ where } let entry = EntrySingle { - peers: BTreeMap::default(), + peers: PeerList::default(), downloaded: *downloaded, }; diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs index 74cdc4475..629f3484e 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs @@ -1,4 +1,3 @@ -use std::collections::BTreeMap; use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; @@ -9,7 +8,7 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::Repository; -use crate::entry::{Entry, EntrySync}; +use crate::entry::{Entry, EntrySync, PeerList}; use crate::{EntryMutexStd, EntrySingle, TorrentsRwLockStdMutexStd}; impl TorrentsRwLockStdMutexStd { @@ -97,7 +96,7 @@ where let entry = EntryMutexStd::new( EntrySingle { - peers: BTreeMap::default(), + peers: PeerList::default(), downloaded: *completed, } .into(), diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs index 83ac02c91..3cc0f53a1 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs @@ -1,4 +1,3 @@ -use std::collections::BTreeMap; use std::iter::zip; use std::pin::Pin; use std::sync::Arc; @@ -13,7 +12,7 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::RepositoryAsync; -use crate::entry::{Entry, EntryAsync}; +use crate::entry::{Entry, EntryAsync, PeerList}; use crate::{EntryMutexTokio, EntrySingle, TorrentsRwLockStdMutexTokio}; impl TorrentsRwLockStdMutexTokio { @@ -106,7 +105,7 @@ where let entry = EntryMutexTokio::new( EntrySingle { - peers: BTreeMap::default(), + peers: PeerList::default(), downloaded: *completed, } .into(), diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs index b95f1e31e..0a481fdde 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio.rs @@ -1,5 +1,3 @@ -use std::collections::BTreeMap; - use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; @@ -8,7 +6,7 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::RepositoryAsync; -use crate::entry::Entry; +use crate::entry::{Entry, PeerList}; use crate::{EntrySingle, TorrentsRwLockTokio}; #[derive(Default, Debug)] @@ -106,7 +104,7 @@ where } let entry = EntrySingle { - peers: BTreeMap::default(), + peers: PeerList::default(), downloaded: *completed, }; diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs index bde959940..d3b17c2d2 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs @@ -1,4 +1,3 @@ -use std::collections::BTreeMap; use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; @@ -9,7 +8,7 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::RepositoryAsync; -use crate::entry::{Entry, EntrySync}; +use crate::entry::{Entry, EntrySync, PeerList}; use crate::{EntryMutexStd, EntrySingle, TorrentsRwLockTokioMutexStd}; impl TorrentsRwLockTokioMutexStd { @@ -97,7 +96,7 @@ where let entry = EntryMutexStd::new( EntrySingle { - peers: BTreeMap::default(), + peers: PeerList::default(), downloaded: *completed, } .into(), diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs index 1d002e317..875a890ea 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -1,4 +1,3 @@ -use std::collections::BTreeMap; use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; @@ -9,7 +8,7 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::RepositoryAsync; -use crate::entry::{Entry, EntryAsync}; +use crate::entry::{Entry, EntryAsync, PeerList}; use crate::{EntryMutexTokio, EntrySingle, TorrentsRwLockTokioMutexTokio}; impl TorrentsRwLockTokioMutexTokio { @@ -100,7 +99,7 @@ where let entry = EntryMutexTokio::new( EntrySingle { - peers: BTreeMap::default(), + peers: PeerList::default(), downloaded: *completed, } .into(), diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index ef3e7e478..b3c71a4de 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -1,4 +1,3 @@ -use std::collections::BTreeMap; use std::sync::Arc; use crossbeam_skiplist::SkipMap; @@ -10,7 +9,7 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::Repository; -use crate::entry::{Entry, EntrySync}; +use crate::entry::{Entry, EntrySync, PeerList}; use crate::{EntryMutexStd, EntrySingle}; #[derive(Default, Debug)] @@ -76,7 +75,7 @@ where let entry = EntryMutexStd::new( EntrySingle { - peers: BTreeMap::default(), + peers: PeerList::default(), downloaded: *completed, } .into(), From 922afda1e689faa62a54cb29ccc6bd7619a4f018 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 15 Apr 2024 17:48:08 +0100 Subject: [PATCH 0290/1297] refactor: rename field from peers to swarm --- packages/torrent-repository/src/entry/mod.rs | 4 ++-- .../torrent-repository/src/entry/single.rs | 20 +++++++++---------- .../src/repository/dash_map_mutex_std.rs | 2 +- .../src/repository/rw_lock_std.rs | 2 +- .../src/repository/rw_lock_std_mutex_std.rs | 2 +- .../src/repository/rw_lock_std_mutex_tokio.rs | 2 +- .../src/repository/rw_lock_tokio.rs | 2 +- .../src/repository/rw_lock_tokio_mutex_std.rs | 2 +- .../repository/rw_lock_tokio_mutex_tokio.rs | 2 +- .../src/repository/skip_map_mutex_std.rs | 2 +- 10 files changed, 20 insertions(+), 20 deletions(-) diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index ee80305ee..648ded98a 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -81,8 +81,8 @@ pub trait EntryAsync { /// The tracker keeps one entry like this for every torrent. #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Torrent { - /// The swarm: a network of peers that are all trying to download the torrent associated to this entry - pub(crate) peers: PeerList, + /// A network of peers that are all trying to download the torrent associated to this entry + pub(crate) swarm: PeerList, /// The number of peers that have ever completed downloading the torrent associated to this entry pub(crate) downloaded: u32, } diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs index 36d04c3cf..169ee2fbb 100644 --- a/packages/torrent-repository/src/entry/single.rs +++ b/packages/torrent-repository/src/entry/single.rs @@ -13,7 +13,7 @@ use crate::EntrySingle; impl Entry for EntrySingle { #[allow(clippy::cast_possible_truncation)] fn get_swarm_metadata(&self) -> SwarmMetadata { - let (seeders, leechers) = self.peers.seeders_and_leechers(); + let (seeders, leechers) = self.swarm.seeders_and_leechers(); SwarmMetadata { downloaded: self.downloaded, @@ -27,7 +27,7 @@ impl Entry for EntrySingle { return true; } - if policy.remove_peerless_torrents && self.peers.is_empty() { + if policy.remove_peerless_torrents && self.swarm.is_empty() { return false; } @@ -35,19 +35,19 @@ impl Entry for EntrySingle { } fn peers_is_empty(&self) -> bool { - self.peers.is_empty() + self.swarm.is_empty() } fn get_peers_len(&self) -> usize { - self.peers.len() + self.swarm.len() } fn get_peers(&self, limit: Option) -> Vec> { - self.peers.get_peers(limit) + self.swarm.get_peers(limit) } fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { - self.peers.get_peers_for_client(client, limit) + self.swarm.get_peers_for_client(client, limit) } fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { @@ -55,10 +55,10 @@ impl Entry for EntrySingle { match peer::ReadInfo::get_event(peer) { AnnounceEvent::Stopped => { - drop(self.peers.remove(&peer::ReadInfo::get_id(peer))); + drop(self.swarm.remove(&peer::ReadInfo::get_id(peer))); } AnnounceEvent::Completed => { - let previous = self.peers.insert(peer::ReadInfo::get_id(peer), Arc::new(*peer)); + let previous = self.swarm.insert(peer::ReadInfo::get_id(peer), Arc::new(*peer)); // Don't count if peer was not previously known and not already completed. if previous.is_some_and(|p| p.event != AnnounceEvent::Completed) { self.downloaded += 1; @@ -66,7 +66,7 @@ impl Entry for EntrySingle { } } _ => { - drop(self.peers.insert(peer::ReadInfo::get_id(peer), Arc::new(*peer))); + drop(self.swarm.insert(peer::ReadInfo::get_id(peer), Arc::new(*peer))); } } @@ -74,7 +74,7 @@ impl Entry for EntrySingle { } fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { - self.peers + self.swarm .retain(|_, peer| peer::ReadInfo::get_updated(peer) > current_cutoff); } } diff --git a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs index 2aba7e54f..7bc60dbc6 100644 --- a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs @@ -81,7 +81,7 @@ where let entry = EntryMutexStd::new( EntrySingle { - peers: PeerList::default(), + swarm: PeerList::default(), downloaded: *completed, } .into(), diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs index 7d8055fca..800b1b31f 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std.rs @@ -100,7 +100,7 @@ where } let entry = EntrySingle { - peers: PeerList::default(), + swarm: PeerList::default(), downloaded: *downloaded, }; diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs index 629f3484e..9fefc9115 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs @@ -96,7 +96,7 @@ where let entry = EntryMutexStd::new( EntrySingle { - peers: PeerList::default(), + swarm: PeerList::default(), downloaded: *completed, } .into(), diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs index 3cc0f53a1..31ccf2a50 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs @@ -105,7 +105,7 @@ where let entry = EntryMutexTokio::new( EntrySingle { - peers: PeerList::default(), + swarm: PeerList::default(), downloaded: *completed, } .into(), diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs index 0a481fdde..0987b064a 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio.rs @@ -104,7 +104,7 @@ where } let entry = EntrySingle { - peers: PeerList::default(), + swarm: PeerList::default(), downloaded: *completed, }; diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs index d3b17c2d2..77a82e445 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs @@ -96,7 +96,7 @@ where let entry = EntryMutexStd::new( EntrySingle { - peers: PeerList::default(), + swarm: PeerList::default(), downloaded: *completed, } .into(), diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs index 875a890ea..fc7608010 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -99,7 +99,7 @@ where let entry = EntryMutexTokio::new( EntrySingle { - peers: PeerList::default(), + swarm: PeerList::default(), downloaded: *completed, } .into(), diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index b3c71a4de..7f84dae2a 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -75,7 +75,7 @@ where let entry = EntryMutexStd::new( EntrySingle { - peers: PeerList::default(), + swarm: PeerList::default(), downloaded: *completed, } .into(), From 42f1b309a68d746f221ed377133cb9f2fa5e6208 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 15 Apr 2024 17:58:20 +0100 Subject: [PATCH 0291/1297] refactor: extract mod peer_list --- packages/torrent-repository/src/entry/mod.rs | 69 +---------------- .../torrent-repository/src/entry/peer_list.rs | 74 +++++++++++++++++++ .../src/repository/dash_map_mutex_std.rs | 3 +- .../src/repository/rw_lock_std.rs | 3 +- .../src/repository/rw_lock_std_mutex_std.rs | 3 +- .../src/repository/rw_lock_std_mutex_tokio.rs | 3 +- .../src/repository/rw_lock_tokio.rs | 3 +- .../src/repository/rw_lock_tokio_mutex_std.rs | 3 +- .../repository/rw_lock_tokio_mutex_tokio.rs | 3 +- .../src/repository/skip_map_mutex_std.rs | 3 +- 10 files changed, 93 insertions(+), 74 deletions(-) create mode 100644 packages/torrent-repository/src/entry/peer_list.rs diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index 648ded98a..40fa4efd5 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -2,13 +2,15 @@ use std::fmt::Debug; use std::net::SocketAddr; use std::sync::Arc; -//use serde::{Deserialize, Serialize}; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; +use self::peer_list::PeerList; + pub mod mutex_std; pub mod mutex_tokio; +pub mod peer_list; pub mod single; pub trait Entry { @@ -86,68 +88,3 @@ pub struct Torrent { /// The number of peers that have ever completed downloading the torrent associated to this entry pub(crate) downloaded: u32, } - -#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct PeerList { - peers: std::collections::BTreeMap>, -} - -impl PeerList { - fn len(&self) -> usize { - self.peers.len() - } - - fn is_empty(&self) -> bool { - self.peers.is_empty() - } - - fn insert(&mut self, key: peer::Id, value: Arc) -> Option> { - self.peers.insert(key, value) - } - - fn remove(&mut self, key: &peer::Id) -> Option> { - self.peers.remove(key) - } - - fn retain(&mut self, f: F) - where - F: FnMut(&peer::Id, &mut Arc) -> bool, - { - self.peers.retain(f); - } - - fn seeders_and_leechers(&self) -> (usize, usize) { - let seeders = self.peers.values().filter(|peer| peer.is_seeder()).count(); - let leechers = self.len() - seeders; - - (seeders, leechers) - } - - fn get_peers(&self, limit: Option) -> Vec> { - match limit { - Some(limit) => self.peers.values().take(limit).cloned().collect(), - None => self.peers.values().cloned().collect(), - } - } - - fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { - match limit { - Some(limit) => self - .peers - .values() - // Take peers which are not the client peer - .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *client) - // Limit the number of peers on the result - .take(limit) - .cloned() - .collect(), - None => self - .peers - .values() - // Take peers which are not the client peer - .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *client) - .cloned() - .collect(), - } - } -} diff --git a/packages/torrent-repository/src/entry/peer_list.rs b/packages/torrent-repository/src/entry/peer_list.rs new file mode 100644 index 000000000..4af9b1d77 --- /dev/null +++ b/packages/torrent-repository/src/entry/peer_list.rs @@ -0,0 +1,74 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_primitives::peer; + +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct PeerList { + peers: std::collections::BTreeMap>, +} + +impl PeerList { + #[must_use] + pub fn len(&self) -> usize { + self.peers.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.peers.is_empty() + } + + pub fn insert(&mut self, key: peer::Id, value: Arc) -> Option> { + self.peers.insert(key, value) + } + + pub fn remove(&mut self, key: &peer::Id) -> Option> { + self.peers.remove(key) + } + + pub fn retain(&mut self, f: F) + where + F: FnMut(&peer::Id, &mut Arc) -> bool, + { + self.peers.retain(f); + } + + #[must_use] + pub fn seeders_and_leechers(&self) -> (usize, usize) { + let seeders = self.peers.values().filter(|peer| peer.is_seeder()).count(); + let leechers = self.len() - seeders; + + (seeders, leechers) + } + + #[must_use] + pub fn get_peers(&self, limit: Option) -> Vec> { + match limit { + Some(limit) => self.peers.values().take(limit).cloned().collect(), + None => self.peers.values().cloned().collect(), + } + } + + #[must_use] + pub fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + match limit { + Some(limit) => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *client) + // Limit the number of peers on the result + .take(limit) + .cloned() + .collect(), + None => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *client) + .cloned() + .collect(), + } + } +} diff --git a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs index 7bc60dbc6..a38205205 100644 --- a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs @@ -9,7 +9,8 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::Repository; -use crate::entry::{Entry, EntrySync, PeerList}; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntrySync}; use crate::{EntryMutexStd, EntrySingle}; #[derive(Default, Debug)] diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs index 800b1b31f..0d96a2375 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std.rs @@ -6,7 +6,8 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::Repository; -use crate::entry::{Entry, PeerList}; +use crate::entry::peer_list::PeerList; +use crate::entry::Entry; use crate::{EntrySingle, TorrentsRwLockStd}; #[derive(Default, Debug)] diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs index 9fefc9115..76d5e8f1e 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs @@ -8,7 +8,8 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::Repository; -use crate::entry::{Entry, EntrySync, PeerList}; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntrySync}; use crate::{EntryMutexStd, EntrySingle, TorrentsRwLockStdMutexStd}; impl TorrentsRwLockStdMutexStd { diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs index 31ccf2a50..e527d6b59 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs @@ -12,7 +12,8 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::RepositoryAsync; -use crate::entry::{Entry, EntryAsync, PeerList}; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntryAsync}; use crate::{EntryMutexTokio, EntrySingle, TorrentsRwLockStdMutexTokio}; impl TorrentsRwLockStdMutexTokio { diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs index 0987b064a..c360106b8 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio.rs @@ -6,7 +6,8 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::RepositoryAsync; -use crate::entry::{Entry, PeerList}; +use crate::entry::peer_list::PeerList; +use crate::entry::Entry; use crate::{EntrySingle, TorrentsRwLockTokio}; #[derive(Default, Debug)] diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs index 77a82e445..9fce79b44 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs @@ -8,7 +8,8 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::RepositoryAsync; -use crate::entry::{Entry, EntrySync, PeerList}; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntrySync}; use crate::{EntryMutexStd, EntrySingle, TorrentsRwLockTokioMutexStd}; impl TorrentsRwLockTokioMutexStd { diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs index fc7608010..c7e0d4054 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -8,7 +8,8 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::RepositoryAsync; -use crate::entry::{Entry, EntryAsync, PeerList}; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntryAsync}; use crate::{EntryMutexTokio, EntrySingle, TorrentsRwLockTokioMutexTokio}; impl TorrentsRwLockTokioMutexTokio { diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index 7f84dae2a..bc9ecd066 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -9,7 +9,8 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; use super::Repository; -use crate::entry::{Entry, EntrySync, PeerList}; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntrySync}; use crate::{EntryMutexStd, EntrySingle}; #[derive(Default, Debug)] From 40182b49e0c221ed85fb78f4243cc180cc96ed1e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 16 Apr 2024 12:00:28 +0100 Subject: [PATCH 0292/1297] test: add tests for PeerList type --- packages/primitives/src/peer.rs | 39 +++ .../torrent-repository/src/entry/peer_list.rs | 249 ++++++++++++++++-- .../torrent-repository/src/entry/single.rs | 11 +- 3 files changed, 276 insertions(+), 23 deletions(-) diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index f5b009f2a..ab7559508 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -362,6 +362,38 @@ pub mod fixture { } impl PeerBuilder { + #[allow(dead_code)] + #[must_use] + pub fn seeder() -> Self { + let peer = Peer { + peer_id: Id(*b"-qB00000000000000001"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes(0), + downloaded: NumberOfBytes(0), + left: NumberOfBytes(0), + event: AnnounceEvent::Completed, + }; + + Self { peer } + } + + #[allow(dead_code)] + #[must_use] + pub fn leecher() -> Self { + let peer = Peer { + peer_id: Id(*b"-qB00000000000000002"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes(0), + downloaded: NumberOfBytes(0), + left: NumberOfBytes(10), + event: AnnounceEvent::Started, + }; + + Self { peer } + } + #[allow(dead_code)] #[must_use] pub fn with_peer_id(mut self, peer_id: &Id) -> Self { @@ -390,6 +422,13 @@ pub mod fixture { self } + #[allow(dead_code)] + #[must_use] + pub fn last_updated_on(mut self, updated: DurationSinceUnixEpoch) -> Self { + self.peer.updated = updated; + self + } + #[allow(dead_code)] #[must_use] pub fn build(self) -> Peer { diff --git a/packages/torrent-repository/src/entry/peer_list.rs b/packages/torrent-repository/src/entry/peer_list.rs index 4af9b1d77..3f69edbb5 100644 --- a/packages/torrent-repository/src/entry/peer_list.rs +++ b/packages/torrent-repository/src/entry/peer_list.rs @@ -1,7 +1,13 @@ +//! A peer list. use std::net::SocketAddr; use std::sync::Arc; -use torrust_tracker_primitives::peer; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +// code-review: the current implementation uses the peer Id as the ``BTreeMap`` +// key. That would allow adding two identical peers except for the Id. +// For example, two peers with the same socket address but a different peer Id +// would be allowed. That would lead to duplicated peers in the tracker responses. #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct PeerList { @@ -19,31 +25,26 @@ impl PeerList { self.peers.is_empty() } - pub fn insert(&mut self, key: peer::Id, value: Arc) -> Option> { - self.peers.insert(key, value) + pub fn upsert(&mut self, value: Arc) -> Option> { + self.peers.insert(value.peer_id, value) } pub fn remove(&mut self, key: &peer::Id) -> Option> { self.peers.remove(key) } - pub fn retain(&mut self, f: F) - where - F: FnMut(&peer::Id, &mut Arc) -> bool, - { - self.peers.retain(f); + pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + self.peers + .retain(|_, peer| peer::ReadInfo::get_updated(peer) > current_cutoff); } #[must_use] - pub fn seeders_and_leechers(&self) -> (usize, usize) { - let seeders = self.peers.values().filter(|peer| peer.is_seeder()).count(); - let leechers = self.len() - seeders; - - (seeders, leechers) + pub fn get(&self, peer_id: &peer::Id) -> Option<&Arc> { + self.peers.get(peer_id) } #[must_use] - pub fn get_peers(&self, limit: Option) -> Vec> { + pub fn get_all(&self, limit: Option) -> Vec> { match limit { Some(limit) => self.peers.values().take(limit).cloned().collect(), None => self.peers.values().cloned().collect(), @@ -51,13 +52,21 @@ impl PeerList { } #[must_use] - pub fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + pub fn seeders_and_leechers(&self) -> (usize, usize) { + let seeders = self.peers.values().filter(|peer| peer.is_seeder()).count(); + let leechers = self.len() - seeders; + + (seeders, leechers) + } + + #[must_use] + pub fn get_peers_excluding_addr(&self, peer_addr: &SocketAddr, limit: Option) -> Vec> { match limit { Some(limit) => self .peers .values() // Take peers which are not the client peer - .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *client) + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *peer_addr) // Limit the number of peers on the result .take(limit) .cloned() @@ -66,9 +75,215 @@ impl PeerList { .peers .values() // Take peers which are not the client peer - .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *client) + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *peer_addr) .cloned() .collect(), } } } + +#[cfg(test)] +mod tests { + + mod it_should { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::peer::{self}; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::entry::peer_list::PeerList; + + #[test] + fn be_empty_when_no_peers_have_been_inserted() { + let peer_list = PeerList::default(); + + assert!(peer_list.is_empty()); + } + + #[test] + fn have_zero_length_when_no_peers_have_been_inserted() { + let peer_list = PeerList::default(); + + assert_eq!(peer_list.len(), 0); + } + + #[test] + fn allow_inserting_a_new_peer() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + assert_eq!(peer_list.upsert(peer.into()), None); + } + + #[test] + fn allow_updating_a_preexisting_peer() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + assert_eq!(peer_list.upsert(peer.into()), Some(Arc::new(peer))); + } + + #[test] + fn allow_getting_all_peers() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + assert_eq!(peer_list.get_all(None), [Arc::new(peer)]); + } + + #[test] + fn allow_getting_one_peer_by_id() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + assert_eq!(peer_list.get(&peer.peer_id), Some(Arc::new(peer)).as_ref()); + } + + #[test] + fn increase_the_number_of_peers_after_inserting_a_new_one() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + assert_eq!(peer_list.len(), 1); + } + + #[test] + fn decrease_the_number_of_peers_after_removing_one() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + peer_list.remove(&peer.peer_id); + + assert!(peer_list.is_empty()); + } + + #[test] + fn allow_removing_an_existing_peer() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + peer_list.remove(&peer.peer_id); + + assert_eq!(peer_list.get(&peer.peer_id), None); + } + + #[test] + fn allow_getting_all_peers_excluding_peers_with_a_given_address() { + let mut peer_list = PeerList::default(); + + let peer1 = PeerBuilder::default() + .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .build(); + peer_list.upsert(peer1.into()); + + let peer2 = PeerBuilder::default() + .with_peer_id(&peer::Id(*b"-qB00000000000000002")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) + .build(); + peer_list.upsert(peer2.into()); + + assert_eq!(peer_list.get_peers_excluding_addr(&peer2.peer_addr, None), [Arc::new(peer1)]); + } + + #[test] + fn return_the_number_of_seeders_in_the_list() { + let mut peer_list = PeerList::default(); + + let seeder = PeerBuilder::seeder().build(); + let leecher = PeerBuilder::leecher().build(); + + peer_list.upsert(seeder.into()); + peer_list.upsert(leecher.into()); + + let (seeders, _leechers) = peer_list.seeders_and_leechers(); + + assert_eq!(seeders, 1); + } + + #[test] + fn return_the_number_of_leechers_in_the_list() { + let mut peer_list = PeerList::default(); + + let seeder = PeerBuilder::seeder().build(); + let leecher = PeerBuilder::leecher().build(); + + peer_list.upsert(seeder.into()); + peer_list.upsert(leecher.into()); + + let (_seeders, leechers) = peer_list.seeders_and_leechers(); + + assert_eq!(leechers, 1); + } + + #[test] + fn remove_inactive_peers() { + let mut peer_list = PeerList::default(); + let one_second = DurationSinceUnixEpoch::new(1, 0); + + // Insert the peer + let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); + let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); + peer_list.upsert(peer.into()); + + // Remove peers not updated since one second after inserting the peer + peer_list.remove_inactive_peers(last_update_time + one_second); + + assert_eq!(peer_list.len(), 0); + } + + #[test] + fn not_remove_active_peers() { + let mut peer_list = PeerList::default(); + let one_second = DurationSinceUnixEpoch::new(1, 0); + + // Insert the peer + let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); + let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); + peer_list.upsert(peer.into()); + + // Remove peers not updated since one second before inserting the peer. + peer_list.remove_inactive_peers(last_update_time - one_second); + + assert_eq!(peer_list.len(), 1); + } + + #[test] + fn allow_inserting_two_identical_peers_except_for_the_id() { + let mut peer_list = PeerList::default(); + + let peer1 = PeerBuilder::default() + .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .build(); + peer_list.upsert(peer1.into()); + + let peer2 = PeerBuilder::default() + .with_peer_id(&peer::Id(*b"-qB00000000000000002")) + .build(); + peer_list.upsert(peer2.into()); + + assert_eq!(peer_list.len(), 2); + } + } +} diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs index 169ee2fbb..a01124454 100644 --- a/packages/torrent-repository/src/entry/single.rs +++ b/packages/torrent-repository/src/entry/single.rs @@ -43,11 +43,11 @@ impl Entry for EntrySingle { } fn get_peers(&self, limit: Option) -> Vec> { - self.swarm.get_peers(limit) + self.swarm.get_all(limit) } fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { - self.swarm.get_peers_for_client(client, limit) + self.swarm.get_peers_excluding_addr(client, limit) } fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { @@ -58,7 +58,7 @@ impl Entry for EntrySingle { drop(self.swarm.remove(&peer::ReadInfo::get_id(peer))); } AnnounceEvent::Completed => { - let previous = self.swarm.insert(peer::ReadInfo::get_id(peer), Arc::new(*peer)); + let previous = self.swarm.upsert(Arc::new(*peer)); // Don't count if peer was not previously known and not already completed. if previous.is_some_and(|p| p.event != AnnounceEvent::Completed) { self.downloaded += 1; @@ -66,7 +66,7 @@ impl Entry for EntrySingle { } } _ => { - drop(self.swarm.insert(peer::ReadInfo::get_id(peer), Arc::new(*peer))); + drop(self.swarm.upsert(Arc::new(*peer))); } } @@ -74,7 +74,6 @@ impl Entry for EntrySingle { } fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { - self.swarm - .retain(|_, peer| peer::ReadInfo::get_updated(peer) > current_cutoff); + self.swarm.remove_inactive_peers(current_cutoff); } } From 5750e2c22d52dfa976150e363d3f400b93efd31e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 16 Apr 2024 14:16:13 +0100 Subject: [PATCH 0293/1297] chore(deps): add dependency parking_lot It provides implementations of Mutex and RwLock that are smaller, faster and more flexible than those in the Rust standard library. It will be used to check if a new torrent repo implementation using these lock is faster. --- Cargo.lock | 2 ++ Cargo.toml | 1 + packages/torrent-repository/Cargo.toml | 1 + 3 files changed, 4 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index f13ed1482..dc6db21c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3939,6 +3939,7 @@ dependencies = [ "log", "mockall", "multimap", + "parking_lot", "percent-encoding", "r2d2", "r2d2_mysql", @@ -4037,6 +4038,7 @@ dependencies = [ "crossbeam-skiplist", "dashmap", "futures", + "parking_lot", "rstest", "tokio", "torrust-tracker-clock", diff --git a/Cargo.toml b/Cargo.toml index ef0c39d4b..57c18453b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,6 +51,7 @@ hyper = "1" lazy_static = "1" log = { version = "0", features = ["release_max_level_info"] } multimap = "0" +parking_lot = "0.12.1" percent-encoding = "2" r2d2 = "0" r2d2_mysql = "24" diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 6bc8bfcdd..937ec11e2 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -19,6 +19,7 @@ version.workspace = true crossbeam-skiplist = "0.1" dashmap = "5.5.3" futures = "0.3.29" +parking_lot = "0.12.1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-alpha.12-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } From 9258ac0cf2b42530950e7cd0cd40792b45c8f7b9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 16 Apr 2024 14:21:10 +0100 Subject: [PATCH 0294/1297] feat: new torrent repo implementation using parking_lot RwLock --- .../benches/repository_benchmark.rs | 22 ++++- packages/torrent-repository/src/entry/mod.rs | 1 + .../src/entry/mutex_parking_lot.rs | 49 ++++++++++ packages/torrent-repository/src/lib.rs | 7 ++ .../src/repository/skip_map_mutex_std.rs | 93 ++++++++++++++++++- .../torrent-repository/tests/common/repo.rs | 18 ++++ .../tests/common/torrent.rs | 11 ++- .../torrent-repository/tests/entry/mod.rs | 34 +++---- .../tests/repository/mod.rs | 31 +++++-- 9 files changed, 238 insertions(+), 28 deletions(-) create mode 100644 packages/torrent-repository/src/entry/mutex_parking_lot.rs diff --git a/packages/torrent-repository/benches/repository_benchmark.rs b/packages/torrent-repository/benches/repository_benchmark.rs index 58cd70d9a..75e7fd5b8 100644 --- a/packages/torrent-repository/benches/repository_benchmark.rs +++ b/packages/torrent-repository/benches/repository_benchmark.rs @@ -5,7 +5,7 @@ mod helpers; use criterion::{criterion_group, criterion_main, Criterion}; use torrust_tracker_torrent_repository::{ TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, - TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexStd, + TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexStd, TorrentsSkipMapRwLockParkingLot, }; use crate::helpers::{asyn, sync}; @@ -49,6 +49,10 @@ fn add_one_torrent(c: &mut Criterion) { b.iter_custom(sync::add_one_torrent::); }); + group.bench_function("SkipMapRwLockParkingLot", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + group.bench_function("DashMapMutexStd", |b| { b.iter_custom(sync::add_one_torrent::); }); @@ -102,6 +106,11 @@ fn add_multiple_torrents_in_parallel(c: &mut Criterion) { .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); }); + group.bench_function("SkipMapRwLockParkingLot", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + group.bench_function("DashMapMutexStd", |b| { b.to_async(&rt) .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); @@ -156,6 +165,11 @@ fn update_one_torrent_in_parallel(c: &mut Criterion) { .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); }); + group.bench_function("SkipMapRwLockParkingLot", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + group.bench_function("DashMapMutexStd", |b| { b.to_async(&rt) .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); @@ -211,6 +225,12 @@ fn update_multiple_torrents_in_parallel(c: &mut Criterion) { .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); }); + group.bench_function("SkipMapRwLockParkingLot", |b| { + b.to_async(&rt).iter_custom(|iters| { + sync::update_multiple_torrents_in_parallel::(&rt, iters, None) + }); + }); + group.bench_function("DashMapMutexStd", |b| { b.to_async(&rt) .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index 40fa4efd5..dbe1416be 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -8,6 +8,7 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use self::peer_list::PeerList; +pub mod mutex_parking_lot; pub mod mutex_std; pub mod mutex_tokio; pub mod peer_list; diff --git a/packages/torrent-repository/src/entry/mutex_parking_lot.rs b/packages/torrent-repository/src/entry/mutex_parking_lot.rs new file mode 100644 index 000000000..ef0e958d5 --- /dev/null +++ b/packages/torrent-repository/src/entry/mutex_parking_lot.rs @@ -0,0 +1,49 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use super::{Entry, EntrySync}; +use crate::{EntryRwLockParkingLot, EntrySingle}; + +impl EntrySync for EntryRwLockParkingLot { + fn get_swarm_metadata(&self) -> SwarmMetadata { + self.read().get_swarm_metadata() + } + + fn is_good(&self, policy: &TrackerPolicy) -> bool { + self.read().is_good(policy) + } + + fn peers_is_empty(&self) -> bool { + self.read().peers_is_empty() + } + + fn get_peers_len(&self) -> usize { + self.read().get_peers_len() + } + + fn get_peers(&self, limit: Option) -> Vec> { + self.read().get_peers(limit) + } + + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.read().get_peers_for_client(client, limit) + } + + fn upsert_peer(&self, peer: &peer::Peer) -> bool { + self.write().upsert_peer(peer) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + self.write().remove_inactive_peers(current_cutoff); + } +} + +impl From for EntryRwLockParkingLot { + fn from(entry: EntrySingle) -> Self { + Arc::new(parking_lot::RwLock::new(entry)) + } +} diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 7a6d209b9..5d3a7ed45 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -9,9 +9,14 @@ use torrust_tracker_clock::clock; pub mod entry; pub mod repository; +// Repo Entries + pub type EntrySingle = entry::Torrent; pub type EntryMutexStd = Arc>; pub type EntryMutexTokio = Arc>; +pub type EntryRwLockParkingLot = Arc>; + +// Repos pub type TorrentsRwLockStd = RwLockStd; pub type TorrentsRwLockStdMutexStd = RwLockStd; @@ -21,6 +26,8 @@ pub type TorrentsRwLockTokioMutexStd = RwLockTokio; pub type TorrentsRwLockTokioMutexTokio = RwLockTokio; pub type TorrentsSkipMapMutexStd = CrossbeamSkipList; +pub type TorrentsSkipMapRwLockParkingLot = CrossbeamSkipList; + pub type TorrentsDashMapMutexStd = XacrimonDashMap; /// This code needs to be copied into each crate. diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index bc9ecd066..0a2a566e7 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -11,7 +11,7 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent use super::Repository; use crate::entry::peer_list::PeerList; use crate::entry::{Entry, EntrySync}; -use crate::{EntryMutexStd, EntrySingle}; +use crate::{EntryMutexStd, EntryRwLockParkingLot, EntrySingle}; #[derive(Default, Debug)] pub struct CrossbeamSkipList { @@ -108,3 +108,94 @@ where } } } + +impl Repository for CrossbeamSkipList +where + EntryRwLockParkingLot: EntrySync, + EntrySingle: Entry, +{ + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); + entry.value().upsert_peer(peer); + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) + } + + fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.torrents.get(key); + maybe_entry.map(|entry| entry.value().clone()) + } + + fn get_metrics(&self) -> TorrentsMetrics { + let mut metrics = TorrentsMetrics::default(); + + for entry in &self.torrents { + let stats = entry.value().read().get_swarm_metadata(); + metrics.complete += u64::from(stats.complete); + metrics.downloaded += u64::from(stats.downloaded); + metrics.incomplete += u64::from(stats.incomplete); + metrics.torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryRwLockParkingLot)> { + match pagination { + Some(pagination) => self + .torrents + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .torrents + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + for (info_hash, completed) in persistent_torrents { + if self.torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryRwLockParkingLot::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + // Since SkipMap is lock-free the torrent could have been inserted + // after checking if it exists. + self.torrents.get_or_insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|entry| entry.value().clone()) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { + entry.value().remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + for entry in &self.torrents { + if entry.value().is_good(policy) { + continue; + } + + entry.remove(); + } + } +} diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 7c245fe04..c5da6258d 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -8,6 +8,7 @@ use torrust_tracker_torrent_repository::repository::{Repository as _, Repository use torrust_tracker_torrent_repository::{ EntrySingle, TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexStd, + TorrentsSkipMapRwLockParkingLot, }; #[derive(Debug)] @@ -19,6 +20,7 @@ pub(crate) enum Repo { RwLockTokioMutexStd(TorrentsRwLockTokioMutexStd), RwLockTokioMutexTokio(TorrentsRwLockTokioMutexTokio), SkipMapMutexStd(TorrentsSkipMapMutexStd), + SkipMapRwLockParkingLot(TorrentsSkipMapRwLockParkingLot), DashMapMutexStd(TorrentsDashMapMutexStd), } @@ -32,6 +34,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.upsert_peer(info_hash, peer).await, Repo::RwLockTokioMutexTokio(repo) => repo.upsert_peer(info_hash, peer).await, Repo::SkipMapMutexStd(repo) => repo.upsert_peer(info_hash, peer), + Repo::SkipMapRwLockParkingLot(repo) => repo.upsert_peer(info_hash, peer), Repo::DashMapMutexStd(repo) => repo.upsert_peer(info_hash, peer), } } @@ -45,6 +48,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.get_swarm_metadata(info_hash).await, Repo::RwLockTokioMutexTokio(repo) => repo.get_swarm_metadata(info_hash).await, Repo::SkipMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), + Repo::SkipMapRwLockParkingLot(repo) => repo.get_swarm_metadata(info_hash), Repo::DashMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), } } @@ -58,6 +62,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => Some(repo.get(key).await?.lock().unwrap().clone()), Repo::RwLockTokioMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), Repo::SkipMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), + Repo::SkipMapRwLockParkingLot(repo) => Some(repo.get(key)?.read().clone()), Repo::DashMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), } } @@ -71,6 +76,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.get_metrics().await, Repo::RwLockTokioMutexTokio(repo) => repo.get_metrics().await, Repo::SkipMapMutexStd(repo) => repo.get_metrics(), + Repo::SkipMapRwLockParkingLot(repo) => repo.get_metrics(), Repo::DashMapMutexStd(repo) => repo.get_metrics(), } } @@ -111,6 +117,11 @@ impl Repo { .iter() .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) .collect(), + Repo::SkipMapRwLockParkingLot(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.read().clone())) + .collect(), Repo::DashMapMutexStd(repo) => repo .get_paginated(pagination) .iter() @@ -128,6 +139,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.import_persistent(persistent_torrents).await, Repo::RwLockTokioMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, Repo::SkipMapMutexStd(repo) => repo.import_persistent(persistent_torrents), + Repo::SkipMapRwLockParkingLot(repo) => repo.import_persistent(persistent_torrents), Repo::DashMapMutexStd(repo) => repo.import_persistent(persistent_torrents), } } @@ -141,6 +153,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => Some(repo.remove(key).await?.lock().unwrap().clone()), Repo::RwLockTokioMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), Repo::SkipMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), + Repo::SkipMapRwLockParkingLot(repo) => Some(repo.remove(key)?.write().clone()), Repo::DashMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), } } @@ -154,6 +167,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.remove_inactive_peers(current_cutoff).await, Repo::RwLockTokioMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, Repo::SkipMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::SkipMapRwLockParkingLot(repo) => repo.remove_inactive_peers(current_cutoff), Repo::DashMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), } } @@ -167,6 +181,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.remove_peerless_torrents(policy).await, Repo::RwLockTokioMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, Repo::SkipMapMutexStd(repo) => repo.remove_peerless_torrents(policy), + Repo::SkipMapRwLockParkingLot(repo) => repo.remove_peerless_torrents(policy), Repo::DashMapMutexStd(repo) => repo.remove_peerless_torrents(policy), } } @@ -194,6 +209,9 @@ impl Repo { Repo::SkipMapMutexStd(repo) => { repo.torrents.insert(*info_hash, torrent.into()); } + Repo::SkipMapRwLockParkingLot(repo) => { + repo.torrents.insert(*info_hash, torrent.into()); + } Repo::DashMapMutexStd(repo) => { repo.torrents.insert(*info_hash, torrent.into()); } diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index c0699479e..f672d14ef 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -5,13 +5,14 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_torrent_repository::entry::{Entry as _, EntryAsync as _, EntrySync as _}; -use torrust_tracker_torrent_repository::{EntryMutexStd, EntryMutexTokio, EntrySingle}; +use torrust_tracker_torrent_repository::{EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle}; #[derive(Debug, Clone)] pub(crate) enum Torrent { Single(EntrySingle), MutexStd(EntryMutexStd), MutexTokio(EntryMutexTokio), + RwLockParkingLot(EntryRwLockParkingLot), } impl Torrent { @@ -20,6 +21,7 @@ impl Torrent { Torrent::Single(entry) => entry.get_swarm_metadata(), Torrent::MutexStd(entry) => entry.get_swarm_metadata(), Torrent::MutexTokio(entry) => entry.clone().get_swarm_metadata().await, + Torrent::RwLockParkingLot(entry) => entry.clone().get_swarm_metadata(), } } @@ -28,6 +30,7 @@ impl Torrent { Torrent::Single(entry) => entry.is_good(policy), Torrent::MutexStd(entry) => entry.is_good(policy), Torrent::MutexTokio(entry) => entry.clone().check_good(policy).await, + Torrent::RwLockParkingLot(entry) => entry.is_good(policy), } } @@ -36,6 +39,7 @@ impl Torrent { Torrent::Single(entry) => entry.peers_is_empty(), Torrent::MutexStd(entry) => entry.peers_is_empty(), Torrent::MutexTokio(entry) => entry.clone().peers_is_empty().await, + Torrent::RwLockParkingLot(entry) => entry.peers_is_empty(), } } @@ -44,6 +48,7 @@ impl Torrent { Torrent::Single(entry) => entry.get_peers_len(), Torrent::MutexStd(entry) => entry.get_peers_len(), Torrent::MutexTokio(entry) => entry.clone().get_peers_len().await, + Torrent::RwLockParkingLot(entry) => entry.get_peers_len(), } } @@ -52,6 +57,7 @@ impl Torrent { Torrent::Single(entry) => entry.get_peers(limit), Torrent::MutexStd(entry) => entry.get_peers(limit), Torrent::MutexTokio(entry) => entry.clone().get_peers(limit).await, + Torrent::RwLockParkingLot(entry) => entry.get_peers(limit), } } @@ -60,6 +66,7 @@ impl Torrent { Torrent::Single(entry) => entry.get_peers_for_client(client, limit), Torrent::MutexStd(entry) => entry.get_peers_for_client(client, limit), Torrent::MutexTokio(entry) => entry.clone().get_peers_for_client(client, limit).await, + Torrent::RwLockParkingLot(entry) => entry.get_peers_for_client(client, limit), } } @@ -68,6 +75,7 @@ impl Torrent { Torrent::Single(entry) => entry.upsert_peer(peer), Torrent::MutexStd(entry) => entry.upsert_peer(peer), Torrent::MutexTokio(entry) => entry.clone().upsert_peer(peer).await, + Torrent::RwLockParkingLot(entry) => entry.upsert_peer(peer), } } @@ -76,6 +84,7 @@ impl Torrent { Torrent::Single(entry) => entry.remove_inactive_peers(current_cutoff), Torrent::MutexStd(entry) => entry.remove_inactive_peers(current_cutoff), Torrent::MutexTokio(entry) => entry.clone().remove_inactive_peers(current_cutoff).await, + Torrent::RwLockParkingLot(entry) => entry.remove_inactive_peers(current_cutoff), } } } diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index 3c564c6f8..aa3126000 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -9,7 +9,7 @@ use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::{peer, NumberOfBytes}; -use torrust_tracker_torrent_repository::{EntryMutexStd, EntryMutexTokio, EntrySingle}; +use torrust_tracker_torrent_repository::{EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle}; use crate::common::torrent::Torrent; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; @@ -20,7 +20,7 @@ fn single() -> Torrent { Torrent::Single(EntrySingle::default()) } #[fixture] -fn standard_mutex() -> Torrent { +fn mutex_std() -> Torrent { Torrent::MutexStd(EntryMutexStd::default()) } @@ -29,6 +29,11 @@ fn mutex_tokio() -> Torrent { Torrent::MutexTokio(EntryMutexTokio::default()) } +#[fixture] +fn rw_lock_parking_lot() -> Torrent { + Torrent::RwLockParkingLot(EntryRwLockParkingLot::default()) +} + #[fixture] fn policy_none() -> TrackerPolicy { TrackerPolicy::new(false, 0, false) @@ -99,7 +104,7 @@ async fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { #[case::empty(&Makes::Empty)] #[tokio::test] async fn it_should_be_empty_by_default( - #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { make(&mut torrent, makes).await; @@ -115,7 +120,7 @@ async fn it_should_be_empty_by_default( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_check_if_entry_is_good( - #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, ) { @@ -153,7 +158,7 @@ async fn it_should_check_if_entry_is_good( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_get_peers_for_torrent_entry( - #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { let peers = make(&mut torrent, makes).await; @@ -174,10 +179,7 @@ async fn it_should_get_peers_for_torrent_entry( #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_update_a_peer( - #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, - #[case] makes: &Makes, -) { +async fn it_should_update_a_peer(#[values(single(), mutex_std(), mutex_tokio())] mut torrent: Torrent, #[case] makes: &Makes) { make(&mut torrent, makes).await; // Make and insert a new peer. @@ -215,7 +217,7 @@ async fn it_should_update_a_peer( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_remove_a_peer_upon_stopped_announcement( - #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { use torrust_tracker_primitives::peer::ReadInfo as _; @@ -256,7 +258,7 @@ async fn it_should_remove_a_peer_upon_stopped_announcement( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloaded_statistic( - #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { make(&mut torrent, makes).await; @@ -287,7 +289,7 @@ async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloade #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_update_a_peer_as_a_seeder( - #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { let peers = make(&mut torrent, makes).await; @@ -319,7 +321,7 @@ async fn it_should_update_a_peer_as_a_seeder( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_update_a_peer_as_incomplete( - #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { let peers = make(&mut torrent, makes).await; @@ -351,7 +353,7 @@ async fn it_should_update_a_peer_as_incomplete( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_get_peers_excluding_the_client_socket( - #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { make(&mut torrent, makes).await; @@ -383,7 +385,7 @@ async fn it_should_get_peers_excluding_the_client_socket( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_limit_the_number_of_peers_returned( - #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { make(&mut torrent, makes).await; @@ -408,7 +410,7 @@ async fn it_should_limit_the_number_of_peers_returned( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_remove_inactive_peers_beyond_cutoff( - #[values(single(), standard_mutex(), mutex_tokio())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { const TIMEOUT: Duration = Duration::from_secs(120); diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index fde34467e..ac53e6510 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -49,10 +49,15 @@ fn tokio_tokio() -> Repo { } #[fixture] -fn skip_list_std() -> Repo { +fn skip_list_mutex_std() -> Repo { Repo::SkipMapMutexStd(CrossbeamSkipList::default()) } +#[fixture] +fn skip_list_rw_lock_parking_lot() -> Repo { + Repo::SkipMapRwLockParkingLot(CrossbeamSkipList::default()) +} + #[fixture] fn dash_map_std() -> Repo { Repo::DashMapMutexStd(XacrimonDashMap::default()) @@ -246,7 +251,8 @@ async fn it_should_get_a_torrent_entry( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std(), + skip_list_mutex_std(), + skip_list_rw_lock_parking_lot(), dash_map_std() )] repo: Repo, @@ -279,7 +285,8 @@ async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std() + skip_list_mutex_std(), + skip_list_rw_lock_parking_lot() )] repo: Repo, #[case] entries: Entries, @@ -321,7 +328,8 @@ async fn it_should_get_paginated( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std() + skip_list_mutex_std(), + skip_list_rw_lock_parking_lot() )] repo: Repo, #[case] entries: Entries, @@ -378,7 +386,8 @@ async fn it_should_get_metrics( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std(), + skip_list_mutex_std(), + skip_list_rw_lock_parking_lot(), dash_map_std() )] repo: Repo, @@ -420,7 +429,8 @@ async fn it_should_import_persistent_torrents( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std(), + skip_list_mutex_std(), + skip_list_rw_lock_parking_lot(), dash_map_std() )] repo: Repo, @@ -459,7 +469,8 @@ async fn it_should_remove_an_entry( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std(), + skip_list_mutex_std(), + skip_list_rw_lock_parking_lot(), dash_map_std() )] repo: Repo, @@ -496,7 +507,8 @@ async fn it_should_remove_inactive_peers( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std(), + skip_list_mutex_std(), + skip_list_rw_lock_parking_lot(), dash_map_std() )] repo: Repo, @@ -594,7 +606,8 @@ async fn it_should_remove_peerless_torrents( tokio_std(), tokio_mutex(), tokio_tokio(), - skip_list_std(), + skip_list_mutex_std(), + skip_list_rw_lock_parking_lot(), dash_map_std() )] repo: Repo, From 0fa396cc34ae457ff2855bd339317b3b1dc15672 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 16 Apr 2024 16:18:44 +0100 Subject: [PATCH 0295/1297] chore(deps): add parking_lot to cargo machete It's used for benchmarking in the torrent-repository workspace package. --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 57c18453b..94889cbf0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -79,7 +79,7 @@ url = "2" uuid = { version = "1", features = ["v4"] } [package.metadata.cargo-machete] -ignored = ["serde_bytes", "crossbeam-skiplist", "dashmap"] +ignored = ["serde_bytes", "crossbeam-skiplist", "dashmap", "parking_lot"] [dev-dependencies] local-ip-address = "0" From 0058e72550d827da08071b63961ce78596d758e1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 16 Apr 2024 16:28:38 +0100 Subject: [PATCH 0296/1297] feat: new torrent repo implementation using parking_lot Mutex --- .../benches/repository_benchmark.rs | 23 ++++- packages/torrent-repository/src/entry/mod.rs | 1 + .../src/entry/mutex_parking_lot.rs | 24 ++--- .../src/entry/rw_lock_parking_lot.rs | 49 ++++++++++ packages/torrent-repository/src/lib.rs | 2 + .../src/repository/skip_map_mutex_std.rs | 93 ++++++++++++++++++- .../torrent-repository/tests/common/repo.rs | 21 ++++- .../tests/common/torrent.rs | 13 ++- .../torrent-repository/tests/entry/mod.rs | 29 +++--- .../tests/repository/mod.rs | 13 +++ 10 files changed, 240 insertions(+), 28 deletions(-) create mode 100644 packages/torrent-repository/src/entry/rw_lock_parking_lot.rs diff --git a/packages/torrent-repository/benches/repository_benchmark.rs b/packages/torrent-repository/benches/repository_benchmark.rs index 75e7fd5b8..4e50f1454 100644 --- a/packages/torrent-repository/benches/repository_benchmark.rs +++ b/packages/torrent-repository/benches/repository_benchmark.rs @@ -5,7 +5,8 @@ mod helpers; use criterion::{criterion_group, criterion_main, Criterion}; use torrust_tracker_torrent_repository::{ TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, - TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexStd, TorrentsSkipMapRwLockParkingLot, + TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexParkingLot, TorrentsSkipMapMutexStd, + TorrentsSkipMapRwLockParkingLot, }; use crate::helpers::{asyn, sync}; @@ -49,6 +50,10 @@ fn add_one_torrent(c: &mut Criterion) { b.iter_custom(sync::add_one_torrent::); }); + group.bench_function("SkipMapMutexParkingLot", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + group.bench_function("SkipMapRwLockParkingLot", |b| { b.iter_custom(sync::add_one_torrent::); }); @@ -106,6 +111,11 @@ fn add_multiple_torrents_in_parallel(c: &mut Criterion) { .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); }); + group.bench_function("SkipMapMutexParkingLot", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + group.bench_function("SkipMapRwLockParkingLot", |b| { b.to_async(&rt) .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); @@ -165,6 +175,11 @@ fn update_one_torrent_in_parallel(c: &mut Criterion) { .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); }); + group.bench_function("SkipMapMutexParkingLot", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + group.bench_function("SkipMapRwLockParkingLot", |b| { b.to_async(&rt) .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); @@ -225,6 +240,12 @@ fn update_multiple_torrents_in_parallel(c: &mut Criterion) { .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); }); + group.bench_function("SkipMapMutexParkingLot", |b| { + b.to_async(&rt).iter_custom(|iters| { + sync::update_multiple_torrents_in_parallel::(&rt, iters, None) + }); + }); + group.bench_function("SkipMapRwLockParkingLot", |b| { b.to_async(&rt).iter_custom(|iters| { sync::update_multiple_torrents_in_parallel::(&rt, iters, None) diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index dbe1416be..b811d3262 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -12,6 +12,7 @@ pub mod mutex_parking_lot; pub mod mutex_std; pub mod mutex_tokio; pub mod peer_list; +pub mod rw_lock_parking_lot; pub mod single; pub trait Entry { diff --git a/packages/torrent-repository/src/entry/mutex_parking_lot.rs b/packages/torrent-repository/src/entry/mutex_parking_lot.rs index ef0e958d5..4f3921ea7 100644 --- a/packages/torrent-repository/src/entry/mutex_parking_lot.rs +++ b/packages/torrent-repository/src/entry/mutex_parking_lot.rs @@ -6,44 +6,44 @@ use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use super::{Entry, EntrySync}; -use crate::{EntryRwLockParkingLot, EntrySingle}; +use crate::{EntryMutexParkingLot, EntrySingle}; -impl EntrySync for EntryRwLockParkingLot { +impl EntrySync for EntryMutexParkingLot { fn get_swarm_metadata(&self) -> SwarmMetadata { - self.read().get_swarm_metadata() + self.lock().get_swarm_metadata() } fn is_good(&self, policy: &TrackerPolicy) -> bool { - self.read().is_good(policy) + self.lock().is_good(policy) } fn peers_is_empty(&self) -> bool { - self.read().peers_is_empty() + self.lock().peers_is_empty() } fn get_peers_len(&self) -> usize { - self.read().get_peers_len() + self.lock().get_peers_len() } fn get_peers(&self, limit: Option) -> Vec> { - self.read().get_peers(limit) + self.lock().get_peers(limit) } fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { - self.read().get_peers_for_client(client, limit) + self.lock().get_peers_for_client(client, limit) } fn upsert_peer(&self, peer: &peer::Peer) -> bool { - self.write().upsert_peer(peer) + self.lock().upsert_peer(peer) } fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - self.write().remove_inactive_peers(current_cutoff); + self.lock().remove_inactive_peers(current_cutoff); } } -impl From for EntryRwLockParkingLot { +impl From for EntryMutexParkingLot { fn from(entry: EntrySingle) -> Self { - Arc::new(parking_lot::RwLock::new(entry)) + Arc::new(parking_lot::Mutex::new(entry)) } } diff --git a/packages/torrent-repository/src/entry/rw_lock_parking_lot.rs b/packages/torrent-repository/src/entry/rw_lock_parking_lot.rs new file mode 100644 index 000000000..ef0e958d5 --- /dev/null +++ b/packages/torrent-repository/src/entry/rw_lock_parking_lot.rs @@ -0,0 +1,49 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use super::{Entry, EntrySync}; +use crate::{EntryRwLockParkingLot, EntrySingle}; + +impl EntrySync for EntryRwLockParkingLot { + fn get_swarm_metadata(&self) -> SwarmMetadata { + self.read().get_swarm_metadata() + } + + fn is_good(&self, policy: &TrackerPolicy) -> bool { + self.read().is_good(policy) + } + + fn peers_is_empty(&self) -> bool { + self.read().peers_is_empty() + } + + fn get_peers_len(&self) -> usize { + self.read().get_peers_len() + } + + fn get_peers(&self, limit: Option) -> Vec> { + self.read().get_peers(limit) + } + + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.read().get_peers_for_client(client, limit) + } + + fn upsert_peer(&self, peer: &peer::Peer) -> bool { + self.write().upsert_peer(peer) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + self.write().remove_inactive_peers(current_cutoff); + } +} + +impl From for EntryRwLockParkingLot { + fn from(entry: EntrySingle) -> Self { + Arc::new(parking_lot::RwLock::new(entry)) + } +} diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 5d3a7ed45..a8955808e 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -14,6 +14,7 @@ pub mod repository; pub type EntrySingle = entry::Torrent; pub type EntryMutexStd = Arc>; pub type EntryMutexTokio = Arc>; +pub type EntryMutexParkingLot = Arc>; pub type EntryRwLockParkingLot = Arc>; // Repos @@ -26,6 +27,7 @@ pub type TorrentsRwLockTokioMutexStd = RwLockTokio; pub type TorrentsRwLockTokioMutexTokio = RwLockTokio; pub type TorrentsSkipMapMutexStd = CrossbeamSkipList; +pub type TorrentsSkipMapMutexParkingLot = CrossbeamSkipList; pub type TorrentsSkipMapRwLockParkingLot = CrossbeamSkipList; pub type TorrentsDashMapMutexStd = XacrimonDashMap; diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index 0a2a566e7..9960b0c30 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -11,7 +11,7 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent use super::Repository; use crate::entry::peer_list::PeerList; use crate::entry::{Entry, EntrySync}; -use crate::{EntryMutexStd, EntryRwLockParkingLot, EntrySingle}; +use crate::{EntryMutexParkingLot, EntryMutexStd, EntryRwLockParkingLot, EntrySingle}; #[derive(Default, Debug)] pub struct CrossbeamSkipList { @@ -199,3 +199,94 @@ where } } } + +impl Repository for CrossbeamSkipList +where + EntryMutexParkingLot: EntrySync, + EntrySingle: Entry, +{ + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); + entry.value().upsert_peer(peer); + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) + } + + fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.torrents.get(key); + maybe_entry.map(|entry| entry.value().clone()) + } + + fn get_metrics(&self) -> TorrentsMetrics { + let mut metrics = TorrentsMetrics::default(); + + for entry in &self.torrents { + let stats = entry.value().lock().get_swarm_metadata(); + metrics.complete += u64::from(stats.complete); + metrics.downloaded += u64::from(stats.downloaded); + metrics.incomplete += u64::from(stats.incomplete); + metrics.torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexParkingLot)> { + match pagination { + Some(pagination) => self + .torrents + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .torrents + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + for (info_hash, completed) in persistent_torrents { + if self.torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexParkingLot::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + // Since SkipMap is lock-free the torrent could have been inserted + // after checking if it exists. + self.torrents.get_or_insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|entry| entry.value().clone()) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { + entry.value().remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + for entry in &self.torrents { + if entry.value().is_good(policy) { + continue; + } + + entry.remove(); + } + } +} diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index c5da6258d..f317d0d17 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -7,8 +7,8 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent use torrust_tracker_torrent_repository::repository::{Repository as _, RepositoryAsync as _}; use torrust_tracker_torrent_repository::{ EntrySingle, TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, - TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexStd, - TorrentsSkipMapRwLockParkingLot, + TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexParkingLot, + TorrentsSkipMapMutexStd, TorrentsSkipMapRwLockParkingLot, }; #[derive(Debug)] @@ -20,6 +20,7 @@ pub(crate) enum Repo { RwLockTokioMutexStd(TorrentsRwLockTokioMutexStd), RwLockTokioMutexTokio(TorrentsRwLockTokioMutexTokio), SkipMapMutexStd(TorrentsSkipMapMutexStd), + SkipMapMutexParkingLot(TorrentsSkipMapMutexParkingLot), SkipMapRwLockParkingLot(TorrentsSkipMapRwLockParkingLot), DashMapMutexStd(TorrentsDashMapMutexStd), } @@ -34,6 +35,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.upsert_peer(info_hash, peer).await, Repo::RwLockTokioMutexTokio(repo) => repo.upsert_peer(info_hash, peer).await, Repo::SkipMapMutexStd(repo) => repo.upsert_peer(info_hash, peer), + Repo::SkipMapMutexParkingLot(repo) => repo.upsert_peer(info_hash, peer), Repo::SkipMapRwLockParkingLot(repo) => repo.upsert_peer(info_hash, peer), Repo::DashMapMutexStd(repo) => repo.upsert_peer(info_hash, peer), } @@ -48,6 +50,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.get_swarm_metadata(info_hash).await, Repo::RwLockTokioMutexTokio(repo) => repo.get_swarm_metadata(info_hash).await, Repo::SkipMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), + Repo::SkipMapMutexParkingLot(repo) => repo.get_swarm_metadata(info_hash), Repo::SkipMapRwLockParkingLot(repo) => repo.get_swarm_metadata(info_hash), Repo::DashMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), } @@ -62,6 +65,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => Some(repo.get(key).await?.lock().unwrap().clone()), Repo::RwLockTokioMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), Repo::SkipMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), + Repo::SkipMapMutexParkingLot(repo) => Some(repo.get(key)?.lock().clone()), Repo::SkipMapRwLockParkingLot(repo) => Some(repo.get(key)?.read().clone()), Repo::DashMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), } @@ -76,6 +80,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.get_metrics().await, Repo::RwLockTokioMutexTokio(repo) => repo.get_metrics().await, Repo::SkipMapMutexStd(repo) => repo.get_metrics(), + Repo::SkipMapMutexParkingLot(repo) => repo.get_metrics(), Repo::SkipMapRwLockParkingLot(repo) => repo.get_metrics(), Repo::DashMapMutexStd(repo) => repo.get_metrics(), } @@ -117,6 +122,11 @@ impl Repo { .iter() .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) .collect(), + Repo::SkipMapMutexParkingLot(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.lock().clone())) + .collect(), Repo::SkipMapRwLockParkingLot(repo) => repo .get_paginated(pagination) .iter() @@ -139,6 +149,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.import_persistent(persistent_torrents).await, Repo::RwLockTokioMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, Repo::SkipMapMutexStd(repo) => repo.import_persistent(persistent_torrents), + Repo::SkipMapMutexParkingLot(repo) => repo.import_persistent(persistent_torrents), Repo::SkipMapRwLockParkingLot(repo) => repo.import_persistent(persistent_torrents), Repo::DashMapMutexStd(repo) => repo.import_persistent(persistent_torrents), } @@ -153,6 +164,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => Some(repo.remove(key).await?.lock().unwrap().clone()), Repo::RwLockTokioMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), Repo::SkipMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), + Repo::SkipMapMutexParkingLot(repo) => Some(repo.remove(key)?.lock().clone()), Repo::SkipMapRwLockParkingLot(repo) => Some(repo.remove(key)?.write().clone()), Repo::DashMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), } @@ -167,6 +179,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.remove_inactive_peers(current_cutoff).await, Repo::RwLockTokioMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, Repo::SkipMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::SkipMapMutexParkingLot(repo) => repo.remove_inactive_peers(current_cutoff), Repo::SkipMapRwLockParkingLot(repo) => repo.remove_inactive_peers(current_cutoff), Repo::DashMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), } @@ -181,6 +194,7 @@ impl Repo { Repo::RwLockTokioMutexStd(repo) => repo.remove_peerless_torrents(policy).await, Repo::RwLockTokioMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, Repo::SkipMapMutexStd(repo) => repo.remove_peerless_torrents(policy), + Repo::SkipMapMutexParkingLot(repo) => repo.remove_peerless_torrents(policy), Repo::SkipMapRwLockParkingLot(repo) => repo.remove_peerless_torrents(policy), Repo::DashMapMutexStd(repo) => repo.remove_peerless_torrents(policy), } @@ -209,6 +223,9 @@ impl Repo { Repo::SkipMapMutexStd(repo) => { repo.torrents.insert(*info_hash, torrent.into()); } + Repo::SkipMapMutexParkingLot(repo) => { + repo.torrents.insert(*info_hash, torrent.into()); + } Repo::SkipMapRwLockParkingLot(repo) => { repo.torrents.insert(*info_hash, torrent.into()); } diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index f672d14ef..abcf5525e 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -5,13 +5,16 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_torrent_repository::entry::{Entry as _, EntryAsync as _, EntrySync as _}; -use torrust_tracker_torrent_repository::{EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle}; +use torrust_tracker_torrent_repository::{ + EntryMutexParkingLot, EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle, +}; #[derive(Debug, Clone)] pub(crate) enum Torrent { Single(EntrySingle), MutexStd(EntryMutexStd), MutexTokio(EntryMutexTokio), + MutexParkingLot(EntryMutexParkingLot), RwLockParkingLot(EntryRwLockParkingLot), } @@ -21,6 +24,7 @@ impl Torrent { Torrent::Single(entry) => entry.get_swarm_metadata(), Torrent::MutexStd(entry) => entry.get_swarm_metadata(), Torrent::MutexTokio(entry) => entry.clone().get_swarm_metadata().await, + Torrent::MutexParkingLot(entry) => entry.clone().get_swarm_metadata(), Torrent::RwLockParkingLot(entry) => entry.clone().get_swarm_metadata(), } } @@ -30,6 +34,7 @@ impl Torrent { Torrent::Single(entry) => entry.is_good(policy), Torrent::MutexStd(entry) => entry.is_good(policy), Torrent::MutexTokio(entry) => entry.clone().check_good(policy).await, + Torrent::MutexParkingLot(entry) => entry.is_good(policy), Torrent::RwLockParkingLot(entry) => entry.is_good(policy), } } @@ -39,6 +44,7 @@ impl Torrent { Torrent::Single(entry) => entry.peers_is_empty(), Torrent::MutexStd(entry) => entry.peers_is_empty(), Torrent::MutexTokio(entry) => entry.clone().peers_is_empty().await, + Torrent::MutexParkingLot(entry) => entry.peers_is_empty(), Torrent::RwLockParkingLot(entry) => entry.peers_is_empty(), } } @@ -48,6 +54,7 @@ impl Torrent { Torrent::Single(entry) => entry.get_peers_len(), Torrent::MutexStd(entry) => entry.get_peers_len(), Torrent::MutexTokio(entry) => entry.clone().get_peers_len().await, + Torrent::MutexParkingLot(entry) => entry.get_peers_len(), Torrent::RwLockParkingLot(entry) => entry.get_peers_len(), } } @@ -57,6 +64,7 @@ impl Torrent { Torrent::Single(entry) => entry.get_peers(limit), Torrent::MutexStd(entry) => entry.get_peers(limit), Torrent::MutexTokio(entry) => entry.clone().get_peers(limit).await, + Torrent::MutexParkingLot(entry) => entry.get_peers(limit), Torrent::RwLockParkingLot(entry) => entry.get_peers(limit), } } @@ -66,6 +74,7 @@ impl Torrent { Torrent::Single(entry) => entry.get_peers_for_client(client, limit), Torrent::MutexStd(entry) => entry.get_peers_for_client(client, limit), Torrent::MutexTokio(entry) => entry.clone().get_peers_for_client(client, limit).await, + Torrent::MutexParkingLot(entry) => entry.get_peers_for_client(client, limit), Torrent::RwLockParkingLot(entry) => entry.get_peers_for_client(client, limit), } } @@ -75,6 +84,7 @@ impl Torrent { Torrent::Single(entry) => entry.upsert_peer(peer), Torrent::MutexStd(entry) => entry.upsert_peer(peer), Torrent::MutexTokio(entry) => entry.clone().upsert_peer(peer).await, + Torrent::MutexParkingLot(entry) => entry.upsert_peer(peer), Torrent::RwLockParkingLot(entry) => entry.upsert_peer(peer), } } @@ -84,6 +94,7 @@ impl Torrent { Torrent::Single(entry) => entry.remove_inactive_peers(current_cutoff), Torrent::MutexStd(entry) => entry.remove_inactive_peers(current_cutoff), Torrent::MutexTokio(entry) => entry.clone().remove_inactive_peers(current_cutoff).await, + Torrent::MutexParkingLot(entry) => entry.remove_inactive_peers(current_cutoff), Torrent::RwLockParkingLot(entry) => entry.remove_inactive_peers(current_cutoff), } } diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index aa3126000..3b9f3e3ad 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -9,7 +9,9 @@ use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::{peer, NumberOfBytes}; -use torrust_tracker_torrent_repository::{EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle}; +use torrust_tracker_torrent_repository::{ + EntryMutexParkingLot, EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle, +}; use crate::common::torrent::Torrent; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; @@ -29,6 +31,11 @@ fn mutex_tokio() -> Torrent { Torrent::MutexTokio(EntryMutexTokio::default()) } +#[fixture] +fn mutex_parking_lot() -> Torrent { + Torrent::MutexParkingLot(EntryMutexParkingLot::default()) +} + #[fixture] fn rw_lock_parking_lot() -> Torrent { Torrent::RwLockParkingLot(EntryRwLockParkingLot::default()) @@ -104,7 +111,7 @@ async fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { #[case::empty(&Makes::Empty)] #[tokio::test] async fn it_should_be_empty_by_default( - #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { make(&mut torrent, makes).await; @@ -120,7 +127,7 @@ async fn it_should_be_empty_by_default( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_check_if_entry_is_good( - #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, ) { @@ -158,7 +165,7 @@ async fn it_should_check_if_entry_is_good( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_get_peers_for_torrent_entry( - #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { let peers = make(&mut torrent, makes).await; @@ -217,7 +224,7 @@ async fn it_should_update_a_peer(#[values(single(), mutex_std(), mutex_tokio())] #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_remove_a_peer_upon_stopped_announcement( - #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { use torrust_tracker_primitives::peer::ReadInfo as _; @@ -258,7 +265,7 @@ async fn it_should_remove_a_peer_upon_stopped_announcement( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloaded_statistic( - #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { make(&mut torrent, makes).await; @@ -289,7 +296,7 @@ async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloade #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_update_a_peer_as_a_seeder( - #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { let peers = make(&mut torrent, makes).await; @@ -321,7 +328,7 @@ async fn it_should_update_a_peer_as_a_seeder( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_update_a_peer_as_incomplete( - #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { let peers = make(&mut torrent, makes).await; @@ -353,7 +360,7 @@ async fn it_should_update_a_peer_as_incomplete( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_get_peers_excluding_the_client_socket( - #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { make(&mut torrent, makes).await; @@ -385,7 +392,7 @@ async fn it_should_get_peers_excluding_the_client_socket( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_limit_the_number_of_peers_returned( - #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { make(&mut torrent, makes).await; @@ -410,7 +417,7 @@ async fn it_should_limit_the_number_of_peers_returned( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_remove_inactive_peers_beyond_cutoff( - #[values(single(), mutex_std(), mutex_tokio(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, ) { const TIMEOUT: Duration = Duration::from_secs(120); diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index ac53e6510..dd9893cc9 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -53,6 +53,11 @@ fn skip_list_mutex_std() -> Repo { Repo::SkipMapMutexStd(CrossbeamSkipList::default()) } +#[fixture] +fn skip_list_mutex_parking_lot() -> Repo { + Repo::SkipMapMutexParkingLot(CrossbeamSkipList::default()) +} + #[fixture] fn skip_list_rw_lock_parking_lot() -> Repo { Repo::SkipMapRwLockParkingLot(CrossbeamSkipList::default()) @@ -252,6 +257,7 @@ async fn it_should_get_a_torrent_entry( tokio_mutex(), tokio_tokio(), skip_list_mutex_std(), + skip_list_mutex_parking_lot(), skip_list_rw_lock_parking_lot(), dash_map_std() )] @@ -286,6 +292,7 @@ async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( tokio_mutex(), tokio_tokio(), skip_list_mutex_std(), + skip_list_mutex_parking_lot(), skip_list_rw_lock_parking_lot() )] repo: Repo, @@ -329,6 +336,7 @@ async fn it_should_get_paginated( tokio_mutex(), tokio_tokio(), skip_list_mutex_std(), + skip_list_mutex_parking_lot(), skip_list_rw_lock_parking_lot() )] repo: Repo, @@ -387,6 +395,7 @@ async fn it_should_get_metrics( tokio_mutex(), tokio_tokio(), skip_list_mutex_std(), + skip_list_mutex_parking_lot(), skip_list_rw_lock_parking_lot(), dash_map_std() )] @@ -430,6 +439,7 @@ async fn it_should_import_persistent_torrents( tokio_mutex(), tokio_tokio(), skip_list_mutex_std(), + skip_list_mutex_parking_lot(), skip_list_rw_lock_parking_lot(), dash_map_std() )] @@ -470,6 +480,7 @@ async fn it_should_remove_an_entry( tokio_mutex(), tokio_tokio(), skip_list_mutex_std(), + skip_list_mutex_parking_lot(), skip_list_rw_lock_parking_lot(), dash_map_std() )] @@ -508,6 +519,7 @@ async fn it_should_remove_inactive_peers( tokio_mutex(), tokio_tokio(), skip_list_mutex_std(), + skip_list_mutex_parking_lot(), skip_list_rw_lock_parking_lot(), dash_map_std() )] @@ -607,6 +619,7 @@ async fn it_should_remove_peerless_torrents( tokio_mutex(), tokio_tokio(), skip_list_mutex_std(), + skip_list_mutex_parking_lot(), skip_list_rw_lock_parking_lot(), dash_map_std() )] From 87c9834ed31dc89af2b41aa0ec21101bdf648fda Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 19 Apr 2024 08:13:21 +0100 Subject: [PATCH 0297/1297] chore(deps): update dependencies ```ouput Updating crates.io index Updating chrono v0.4.37 -> v0.4.38 Updating hyper v1.2.0 -> v1.3.1 Updating proc-macro2 v1.0.80 -> v1.0.81 Updating serde v1.0.197 -> v1.0.198 Updating serde_derive v1.0.197 -> v1.0.198 Updating serde_json v1.0.115 -> v1.0.116 Updating syn v2.0.59 -> v2.0.60 Updating toml_edit v0.22.9 -> v0.22.11 ``` --- Cargo.lock | 90 +++++++++++++++++++++++++++--------------------------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index dc6db21c1..70ac685a1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -346,7 +346,7 @@ checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca" dependencies = [ "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -460,7 +460,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -547,7 +547,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -622,7 +622,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", "syn_derive", ] @@ -732,9 +732,9 @@ checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" [[package]] name = "chrono" -version = "0.4.37" +version = "0.4.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a0d04d43504c61aa6c7531f1871dd0d418d91130162063b789da00fd7057a5e" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" dependencies = [ "android-tzdata", "iana-time-zone", @@ -812,7 +812,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -1085,7 +1085,7 @@ dependencies = [ "proc-macro2", "quote", "strsim 0.10.0", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -1096,7 +1096,7 @@ checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" dependencies = [ "darling_core", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -1143,7 +1143,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -1378,7 +1378,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -1390,7 +1390,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -1402,7 +1402,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -1495,7 +1495,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -1723,9 +1723,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.2.0" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "186548d73ac615b32a73aafe38fb4f56c0d340e110e5a200bcadbaf2e199263a" +checksum = "fe575dd17d0862a9a33781c8c4696a55c320909004a67a00fb286ba8b1bc496d" dependencies = [ "bytes", "futures-channel", @@ -2196,7 +2196,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -2247,7 +2247,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", "termcolor", "thiserror", ] @@ -2447,7 +2447,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -2560,7 +2560,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -2629,7 +2629,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -2803,9 +2803,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.80" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a56dea16b0a29e94408b9aa5e2940a4eedbd128a1ba20e8f7ae60fd3d465af0e" +checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba" dependencies = [ "unicode-ident", ] @@ -3112,7 +3112,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.59", + "syn 2.0.60", "unicode-ident", ] @@ -3340,9 +3340,9 @@ checksum = "92d43fe69e652f3df9bdc2b85b2854a0825b86e4fb76bc44d945137d053639ca" [[package]] name = "serde" -version = "1.0.197" +version = "1.0.198" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" +checksum = "9846a40c979031340571da2545a4e5b7c4163bdae79b301d5f86d03979451fcc" dependencies = [ "serde_derive", ] @@ -3368,13 +3368,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.197" +version = "1.0.198" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" +checksum = "e88edab869b01783ba905e7d0153f9fc1a6505a96e4ad3018011eedb838566d9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -3392,9 +3392,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.115" +version = "1.0.116" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd" +checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813" dependencies = [ "itoa", "ryu", @@ -3419,7 +3419,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -3470,7 +3470,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -3604,9 +3604,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.59" +version = "2.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a6531ffc7b071655e4ce2e04bd464c4830bb585a61cabb96cf808f05172615a" +checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3" dependencies = [ "proc-macro2", "quote", @@ -3622,7 +3622,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -3725,7 +3725,7 @@ checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -3819,7 +3819,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -3865,7 +3865,7 @@ dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.9", + "toml_edit 0.22.11", ] [[package]] @@ -3901,9 +3901,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.9" +version = "0.22.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e40bb779c5187258fd7aad0eb68cb8706a0a81fa712fbea808ab43c4b8374c4" +checksum = "fb686a972ccef8537b39eead3968b0e8616cb5040dbb9bba93007c8e07c9215f" dependencies = [ "indexmap 2.2.6", "serde", @@ -4127,7 +4127,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] @@ -4298,7 +4298,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", "wasm-bindgen-shared", ] @@ -4332,7 +4332,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4595,7 +4595,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.59", + "syn 2.0.60", ] [[package]] From b3015968ab9b95077a0a5626901a7ee570e6a8aa Mon Sep 17 00:00:00 2001 From: ngthhu Date: Wed, 24 Apr 2024 15:27:39 +0700 Subject: [PATCH 0298/1297] chore:[#674] Tracker Checker: Ouput in JSON --- Cargo.lock | 1 + Cargo.toml | 2 +- src/console/clients/checker/checks/health.rs | 53 +++++++++---------- src/console/clients/checker/checks/http.rs | 30 +++++++---- src/console/clients/checker/checks/mod.rs | 1 + src/console/clients/checker/checks/structs.rs | 12 +++++ src/console/clients/checker/checks/udp.rs | 42 +++++++++------ src/console/clients/checker/service.rs | 13 +++-- 8 files changed, 95 insertions(+), 59 deletions(-) create mode 100644 src/console/clients/checker/checks/structs.rs diff --git a/Cargo.lock b/Cargo.lock index 70ac685a1..f71275517 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3396,6 +3396,7 @@ version = "1.0.116" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813" dependencies = [ + "indexmap 2.2.6", "itoa", "ryu", "serde", diff --git a/Cargo.toml b/Cargo.toml index 94889cbf0..e201f5ba9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,7 +62,7 @@ ringbuf = "0" serde = { version = "1", features = ["derive"] } serde_bencode = "0" serde_bytes = "0" -serde_json = "1" +serde_json = { version = "1", features = ["preserve_order"] } serde_repr = "0" thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } diff --git a/src/console/clients/checker/checks/health.rs b/src/console/clients/checker/checks/health.rs index 9c28da514..bc545510b 100644 --- a/src/console/clients/checker/checks/health.rs +++ b/src/console/clients/checker/checks/health.rs @@ -1,51 +1,50 @@ use std::time::Duration; -use colored::Colorize; use reqwest::{Client as HttpClient, Url, Url as ServiceUrl}; -use crate::console::clients::checker::console::Console; -use crate::console::clients::checker::printer::Printer; use crate::console::clients::checker::service::{CheckError, CheckResult}; -pub async fn run(health_checks: &Vec, console: &Console, check_results: &mut Vec) { - console.println("Health checks ..."); +use super::structs::{CheckerOutput, Status}; + +#[allow(clippy::missing_panics_doc)] +pub async fn run(health_checks: &Vec, check_results: &mut Vec) -> Vec { + let mut health_checkers: Vec = Vec::new(); for health_check_url in health_checks { - match run_health_check(health_check_url.clone(), console).await { - Ok(()) => check_results.push(Ok(())), - Err(err) => check_results.push(Err(err)), + let mut health_checker = CheckerOutput { + url: health_check_url.to_string(), + status: Status { + code: String::new(), + message: String::new(), + }, + }; + match run_health_check(health_check_url.clone()).await { + Ok(()) => { + check_results.push(Ok(())); + health_checker.status.code = "ok".to_string(); + } + Err(err) => { + check_results.push(Err(err)); + health_checker.status.code = "error".to_string(); + health_checker.status.message = "Health API is failing.".to_string(); + } } + health_checkers.push(health_checker); } + health_checkers } -async fn run_health_check(url: Url, console: &Console) -> Result<(), CheckError> { +async fn run_health_check(url: Url) -> Result<(), CheckError> { let client = HttpClient::builder().timeout(Duration::from_secs(5)).build().unwrap(); - let colored_url = url.to_string().yellow(); - match client.get(url.clone()).send().await { Ok(response) => { if response.status().is_success() { - console.println(&format!("{} - Health API at {} is OK", "✓".green(), colored_url)); Ok(()) } else { - console.eprintln(&format!( - "{} - Health API at {} is failing: {:?}", - "✗".red(), - colored_url, - response - )); Err(CheckError::HealthCheckError { url }) } } - Err(err) => { - console.eprintln(&format!( - "{} - Health API at {} is failing: {:?}", - "✗".red(), - colored_url, - err - )); - Err(CheckError::HealthCheckError { url }) - } + Err(_) => Err(CheckError::HealthCheckError { url }), } } diff --git a/src/console/clients/checker/checks/http.rs b/src/console/clients/checker/checks/http.rs index 501696df4..f65674ceb 100644 --- a/src/console/clients/checker/checks/http.rs +++ b/src/console/clients/checker/checks/http.rs @@ -1,47 +1,57 @@ use std::str::FromStr; -use colored::Colorize; use log::debug; use reqwest::Url as ServiceUrl; use torrust_tracker_primitives::info_hash::InfoHash; use url::Url; -use crate::console::clients::checker::console::Console; -use crate::console::clients::checker::printer::Printer; use crate::console::clients::checker::service::{CheckError, CheckResult}; use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; use crate::shared::bit_torrent::tracker::http::client::responses::scrape; use crate::shared::bit_torrent::tracker::http::client::{requests, Client}; -pub async fn run(http_trackers: &Vec, console: &Console, check_results: &mut Vec) { - console.println("HTTP trackers ..."); +use super::structs::{CheckerOutput, Status}; + +#[allow(clippy::missing_panics_doc)] +pub async fn run(http_trackers: &Vec, check_results: &mut Vec) -> Vec { + let mut http_checkers: Vec = Vec::new(); for http_tracker in http_trackers { - let colored_tracker_url = http_tracker.to_string().yellow(); + let mut http_checker = CheckerOutput { + url: http_tracker.to_string(), + status: Status { + code: String::new(), + message: String::new(), + }, + }; match check_http_announce(http_tracker).await { Ok(()) => { check_results.push(Ok(())); - console.println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); + http_checker.status.code = "ok".to_string(); } Err(err) => { check_results.push(Err(err)); - console.println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); + http_checker.status.code = "error".to_string(); + http_checker.status.message = "Announce is failing.".to_string(); } } match check_http_scrape(http_tracker).await { Ok(()) => { check_results.push(Ok(())); - console.println(&format!("{} - Scrape at {} is OK", "✓".green(), colored_tracker_url)); + http_checker.status.code = "ok".to_string(); } Err(err) => { check_results.push(Err(err)); - console.println(&format!("{} - Scrape at {} is failing", "✗".red(), colored_tracker_url)); + http_checker.status.code = "error".to_string(); + http_checker.status.message = "Scrape is failing.".to_string(); } } + http_checkers.push(http_checker); } + http_checkers } async fn check_http_announce(tracker_url: &Url) -> Result<(), CheckError> { diff --git a/src/console/clients/checker/checks/mod.rs b/src/console/clients/checker/checks/mod.rs index 16256595e..f8b03f749 100644 --- a/src/console/clients/checker/checks/mod.rs +++ b/src/console/clients/checker/checks/mod.rs @@ -1,3 +1,4 @@ pub mod health; pub mod http; +pub mod structs; pub mod udp; diff --git a/src/console/clients/checker/checks/structs.rs b/src/console/clients/checker/checks/structs.rs new file mode 100644 index 000000000..d28e20c04 --- /dev/null +++ b/src/console/clients/checker/checks/structs.rs @@ -0,0 +1,12 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub struct Status { + pub code: String, + pub message: String, +} +#[derive(Serialize, Deserialize)] +pub struct CheckerOutput { + pub url: String, + pub status: Status, +} diff --git a/src/console/clients/checker/checks/udp.rs b/src/console/clients/checker/checks/udp.rs index 47a2a1a00..e9a777a8d 100644 --- a/src/console/clients/checker/checks/udp.rs +++ b/src/console/clients/checker/checks/udp.rs @@ -1,26 +1,32 @@ use std::net::SocketAddr; use aquatic_udp_protocol::{Port, TransactionId}; -use colored::Colorize; use hex_literal::hex; use log::debug; use torrust_tracker_primitives::info_hash::InfoHash; -use crate::console::clients::checker::console::Console; -use crate::console::clients::checker::printer::Printer; use crate::console::clients::checker::service::{CheckError, CheckResult}; use crate::console::clients::udp::checker; +use crate::console::clients::checker::checks::structs::{CheckerOutput, Status}; + const ASSIGNED_BY_OS: u16 = 0; const RANDOM_TRANSACTION_ID: i32 = -888_840_697; -pub async fn run(udp_trackers: &Vec, console: &Console, check_results: &mut Vec) { - console.println("UDP trackers ..."); +#[allow(clippy::missing_panics_doc)] +pub async fn run(udp_trackers: &Vec, check_results: &mut Vec) -> Vec { + let mut udp_checkers: Vec = Vec::new(); for udp_tracker in udp_trackers { - debug!("UDP tracker: {:?}", udp_tracker); + let mut checker_output = CheckerOutput { + url: udp_tracker.to_string(), + status: Status { + code: String::new(), + message: String::new(), + }, + }; - let colored_tracker_url = udp_tracker.to_string().yellow(); + debug!("UDP tracker: {:?}", udp_tracker); let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); @@ -32,7 +38,8 @@ pub async fn run(udp_trackers: &Vec, console: &Console, check_result check_results.push(Err(CheckError::UdpError { socket_addr: *udp_tracker, })); - console.println(&format!("{} - Can't connect to socket {}", "✗".red(), colored_tracker_url)); + checker_output.status.code = "error".to_string(); + checker_output.status.message = "Can't connect to socket.".to_string(); break; }; @@ -42,11 +49,8 @@ pub async fn run(udp_trackers: &Vec, console: &Console, check_result check_results.push(Err(CheckError::UdpError { socket_addr: *udp_tracker, })); - console.println(&format!( - "{} - Can't make tracker connection request to {}", - "✗".red(), - colored_tracker_url - )); + checker_output.status.code = "error".to_string(); + checker_output.status.message = "Can't make tracker connection request.".to_string(); break; }; @@ -60,13 +64,14 @@ pub async fn run(udp_trackers: &Vec, console: &Console, check_result .is_ok() { check_results.push(Ok(())); - console.println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); + checker_output.status.code = "ok".to_string(); } else { let err = CheckError::UdpError { socket_addr: *udp_tracker, }; check_results.push(Err(err)); - console.println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); + checker_output.status.code = "error".to_string(); + checker_output.status.message = "Announce is failing.".to_string(); } debug!("Send scrape request"); @@ -75,13 +80,16 @@ pub async fn run(udp_trackers: &Vec, console: &Console, check_result if (client.send_scrape_request(connection_id, transaction_id, info_hashes).await).is_ok() { check_results.push(Ok(())); - console.println(&format!("{} - Announce at {} is OK", "✓".green(), colored_tracker_url)); + checker_output.status.code = "ok".to_string(); } else { let err = CheckError::UdpError { socket_addr: *udp_tracker, }; check_results.push(Err(err)); - console.println(&format!("{} - Announce at {} is failing", "✗".red(), colored_tracker_url)); + checker_output.status.code = "error".to_string(); + checker_output.status.message = "Scrape is failing.".to_string(); } + udp_checkers.push(checker_output); } + udp_checkers } diff --git a/src/console/clients/checker/service.rs b/src/console/clients/checker/service.rs index 94eff4a88..fd97342cc 100644 --- a/src/console/clients/checker/service.rs +++ b/src/console/clients/checker/service.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use reqwest::Url; -use super::checks; +use super::checks::{self}; use super::config::Configuration; use super::console::Console; use crate::console::clients::checker::printer::Printer; @@ -26,16 +26,21 @@ impl Service { /// # Errors /// /// Will return OK is all checks pass or an array with the check errors. + #[allow(clippy::missing_panics_doc)] pub async fn run_checks(&self) -> Vec { self.console.println("Running checks for trackers ..."); let mut check_results = vec![]; - checks::udp::run(&self.config.udp_trackers, &self.console, &mut check_results).await; + let udp_checkers = checks::udp::run(&self.config.udp_trackers, &mut check_results).await; - checks::http::run(&self.config.http_trackers, &self.console, &mut check_results).await; + let http_checkers = checks::http::run(&self.config.http_trackers, &mut check_results).await; - checks::health::run(&self.config.health_checks, &self.console, &mut check_results).await; + let health_checkers = checks::health::run(&self.config.health_checks, &mut check_results).await; + + let json_output = + serde_json::json!({ "udp_trackers": udp_checkers, "http_trackers": http_checkers, "health_checks": health_checkers }); + self.console.println(&serde_json::to_string_pretty(&json_output).unwrap()); check_results } From 7de4fbcf727e0b2484c80c5385dca78aba20446b Mon Sep 17 00:00:00 2001 From: ngthhu Date: Wed, 24 Apr 2024 21:25:30 +0700 Subject: [PATCH 0299/1297] format fix --- src/console/clients/checker/checks/health.rs | 3 +-- src/console/clients/checker/checks/http.rs | 3 +-- src/console/clients/checker/checks/udp.rs | 3 +-- src/console/clients/checker/service.rs | 2 -- 4 files changed, 3 insertions(+), 8 deletions(-) diff --git a/src/console/clients/checker/checks/health.rs b/src/console/clients/checker/checks/health.rs index bc545510b..47eec4cbd 100644 --- a/src/console/clients/checker/checks/health.rs +++ b/src/console/clients/checker/checks/health.rs @@ -2,9 +2,8 @@ use std::time::Duration; use reqwest::{Client as HttpClient, Url, Url as ServiceUrl}; -use crate::console::clients::checker::service::{CheckError, CheckResult}; - use super::structs::{CheckerOutput, Status}; +use crate::console::clients::checker::service::{CheckError, CheckResult}; #[allow(clippy::missing_panics_doc)] pub async fn run(health_checks: &Vec, check_results: &mut Vec) -> Vec { diff --git a/src/console/clients/checker/checks/http.rs b/src/console/clients/checker/checks/http.rs index f65674ceb..e0b14b480 100644 --- a/src/console/clients/checker/checks/http.rs +++ b/src/console/clients/checker/checks/http.rs @@ -5,14 +5,13 @@ use reqwest::Url as ServiceUrl; use torrust_tracker_primitives::info_hash::InfoHash; use url::Url; +use super::structs::{CheckerOutput, Status}; use crate::console::clients::checker::service::{CheckError, CheckResult}; use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; use crate::shared::bit_torrent::tracker::http::client::responses::scrape; use crate::shared::bit_torrent::tracker::http::client::{requests, Client}; -use super::structs::{CheckerOutput, Status}; - #[allow(clippy::missing_panics_doc)] pub async fn run(http_trackers: &Vec, check_results: &mut Vec) -> Vec { let mut http_checkers: Vec = Vec::new(); diff --git a/src/console/clients/checker/checks/udp.rs b/src/console/clients/checker/checks/udp.rs index e9a777a8d..48f72edf9 100644 --- a/src/console/clients/checker/checks/udp.rs +++ b/src/console/clients/checker/checks/udp.rs @@ -5,11 +5,10 @@ use hex_literal::hex; use log::debug; use torrust_tracker_primitives::info_hash::InfoHash; +use crate::console::clients::checker::checks::structs::{CheckerOutput, Status}; use crate::console::clients::checker::service::{CheckError, CheckResult}; use crate::console::clients::udp::checker; -use crate::console::clients::checker::checks::structs::{CheckerOutput, Status}; - const ASSIGNED_BY_OS: u16 = 0; const RANDOM_TRANSACTION_ID: i32 = -888_840_697; diff --git a/src/console/clients/checker/service.rs b/src/console/clients/checker/service.rs index fd97342cc..16483e92e 100644 --- a/src/console/clients/checker/service.rs +++ b/src/console/clients/checker/service.rs @@ -28,8 +28,6 @@ impl Service { /// Will return OK is all checks pass or an array with the check errors. #[allow(clippy::missing_panics_doc)] pub async fn run_checks(&self) -> Vec { - self.console.println("Running checks for trackers ..."); - let mut check_results = vec![]; let udp_checkers = checks::udp::run(&self.config.udp_trackers, &mut check_results).await; From b27f002ac6e2fb21142bc21c1eb6580544c1bf2f Mon Sep 17 00:00:00 2001 From: ngthhu Date: Wed, 24 Apr 2024 23:00:27 +0700 Subject: [PATCH 0300/1297] remove unused dependencies --- Cargo.lock | 11 ----------- Cargo.toml | 1 - 2 files changed, 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f71275517..44f9db17c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -836,16 +836,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" -[[package]] -name = "colored" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbf2150cce219b664a8a70df7a1f933836724b503f8a413af9365b4dcc4d90b8" -dependencies = [ - "lazy_static", - "windows-sys 0.48.0", -] - [[package]] name = "concurrent-queue" version = "2.4.0" @@ -3926,7 +3916,6 @@ dependencies = [ "axum-server", "chrono", "clap", - "colored", "config", "crossbeam-skiplist", "dashmap", diff --git a/Cargo.toml b/Cargo.toml index e201f5ba9..0e37b7ad0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,7 +39,6 @@ axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls"] } chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } -colored = "2" config = "0" crossbeam-skiplist = "0.1" dashmap = "5.5.3" From effca568032eaffcdb9d3f984000b238962ce438 Mon Sep 17 00:00:00 2001 From: ngthhu Date: Thu, 25 Apr 2024 17:22:01 +0700 Subject: [PATCH 0301/1297] refactor: [#681] udp return errors instead of panicking --- src/console/clients/udp/checker.rs | 16 +- src/shared/bit_torrent/tracker/udp/client.rs | 215 +++++++++++-------- tests/servers/udp/contract.rs | 71 ++++-- 3 files changed, 193 insertions(+), 109 deletions(-) diff --git a/src/console/clients/udp/checker.rs b/src/console/clients/udp/checker.rs index 12b8d764c..9b2a9011e 100644 --- a/src/console/clients/udp/checker.rs +++ b/src/console/clients/udp/checker.rs @@ -64,7 +64,7 @@ impl Client { let binding_address = local_bind_to.parse().context("binding local address")?; debug!("Binding to: {local_bind_to}"); - let udp_client = UdpClient::bind(&local_bind_to).await; + let udp_client = UdpClient::bind(&local_bind_to).await?; let bound_to = udp_client.socket.local_addr().context("bound local address")?; debug!("Bound to: {bound_to}"); @@ -88,7 +88,7 @@ impl Client { match &self.udp_tracker_client { Some(client) => { - client.udp_client.connect(&tracker_socket_addr.to_string()).await; + client.udp_client.connect(&tracker_socket_addr.to_string()).await?; self.remote_socket = Some(*tracker_socket_addr); Ok(()) } @@ -116,9 +116,9 @@ impl Client { match &self.udp_tracker_client { Some(client) => { - client.send(connect_request.into()).await; + client.send(connect_request.into()).await?; - let response = client.receive().await; + let response = client.receive().await?; debug!("connection request response:\n{response:#?}"); @@ -163,9 +163,9 @@ impl Client { match &self.udp_tracker_client { Some(client) => { - client.send(announce_request.into()).await; + client.send(announce_request.into()).await?; - let response = client.receive().await; + let response = client.receive().await?; debug!("announce request response:\n{response:#?}"); @@ -200,9 +200,9 @@ impl Client { match &self.udp_tracker_client { Some(client) => { - client.send(scrape_request.into()).await; + client.send(scrape_request.into()).await?; - let response = client.receive().await; + let response = client.receive().await?; debug!("scrape request response:\n{response:#?}"); diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs index 11c8d8f62..9af9571bc 100644 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -1,8 +1,10 @@ +use core::result::Result::{Err, Ok}; use std::io::Cursor; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; +use anyhow::{anyhow, Context, Result}; use aquatic_udp_protocol::{ConnectRequest, Request, Response, TransactionId}; use log::debug; use tokio::net::UdpSocket; @@ -25,99 +27,120 @@ pub struct UdpClient { } impl UdpClient { - /// # Panics + /// # Errors + /// + /// Will return error if the local address can't be bound. /// - /// Will panic if the local address can't be bound. - pub async fn bind(local_address: &str) -> Self { - let valid_socket_addr = local_address + pub async fn bind(local_address: &str) -> Result { + let socket_addr = local_address .parse::() - .unwrap_or_else(|_| panic!("{local_address} is not a valid socket address")); + .context(format!("{local_address} is not a valid socket address"))?; - let socket = UdpSocket::bind(valid_socket_addr).await.unwrap(); + let socket = UdpSocket::bind(socket_addr).await?; - Self { + let udp_client = Self { socket: Arc::new(socket), timeout: DEFAULT_TIMEOUT, - } + }; + Ok(udp_client) } - /// # Panics + /// # Errors /// - /// Will panic if can't connect to the socket. - pub async fn connect(&self, remote_address: &str) { - let valid_socket_addr = remote_address + /// Will return error if can't connect to the socket. + pub async fn connect(&self, remote_address: &str) -> Result<()> { + let socket_addr = remote_address .parse::() - .unwrap_or_else(|_| panic!("{remote_address} is not a valid socket address")); + .context(format!("{remote_address} is not a valid socket address"))?; - match self.socket.connect(valid_socket_addr).await { - Ok(()) => debug!("Connected successfully"), - Err(e) => panic!("Failed to connect: {e:?}"), + match self.socket.connect(socket_addr).await { + Ok(()) => { + debug!("Connected successfully"); + Ok(()) + } + Err(e) => Err(anyhow!("Failed to connect: {e:?}")), } } - /// # Panics + /// # Errors /// - /// Will panic if: + /// Will return error if: /// /// - Can't write to the socket. /// - Can't send data. - pub async fn send(&self, bytes: &[u8]) -> usize { + pub async fn send(&self, bytes: &[u8]) -> Result { debug!(target: "UDP client", "sending {bytes:?} ..."); match time::timeout(self.timeout, self.socket.writable()).await { - Ok(writable_result) => match writable_result { - Ok(()) => (), - Err(e) => panic!("{}", format!("IO error waiting for the socket to become readable: {e:?}")), - }, - Err(e) => panic!("{}", format!("Timeout waiting for the socket to become readable: {e:?}")), + Ok(writable_result) => { + match writable_result { + Ok(()) => (), + Err(e) => return Err(anyhow!("IO error waiting for the socket to become readable: {e:?}")), + }; + } + Err(e) => return Err(anyhow!("Timeout waiting for the socket to become readable: {e:?}")), }; match time::timeout(self.timeout, self.socket.send(bytes)).await { Ok(send_result) => match send_result { - Ok(size) => size, - Err(e) => panic!("{}", format!("IO error during send: {e:?}")), + Ok(size) => Ok(size), + Err(e) => Err(anyhow!("IO error during send: {e:?}")), }, - Err(e) => panic!("{}", format!("Send operation timed out: {e:?}")), + Err(e) => Err(anyhow!("Send operation timed out: {e:?}")), } } - /// # Panics + /// # Errors /// - /// Will panic if: + /// Will return error if: /// /// - Can't read from the socket. /// - Can't receive data. - pub async fn receive(&self, bytes: &mut [u8]) -> usize { + /// + /// # Panics + /// + pub async fn receive(&self, bytes: &mut [u8]) -> Result { debug!(target: "UDP client", "receiving ..."); match time::timeout(self.timeout, self.socket.readable()).await { - Ok(readable_result) => match readable_result { - Ok(()) => (), - Err(e) => panic!("{}", format!("IO error waiting for the socket to become readable: {e:?}")), - }, - Err(e) => panic!("{}", format!("Timeout waiting for the socket to become readable: {e:?}")), + Ok(readable_result) => { + match readable_result { + Ok(()) => (), + Err(e) => return Err(anyhow!("IO error waiting for the socket to become readable: {e:?}")), + }; + } + Err(e) => return Err(anyhow!("Timeout waiting for the socket to become readable: {e:?}")), }; - let size = match time::timeout(self.timeout, self.socket.recv(bytes)).await { + let size_result = match time::timeout(self.timeout, self.socket.recv(bytes)).await { Ok(recv_result) => match recv_result { - Ok(size) => size, - Err(e) => panic!("{}", format!("IO error during send: {e:?}")), + Ok(size) => Ok(size), + Err(e) => Err(anyhow!("IO error during send: {e:?}")), }, - Err(e) => panic!("{}", format!("Receive operation timed out: {e:?}")), + Err(e) => Err(anyhow!("Receive operation timed out: {e:?}")), }; - debug!(target: "UDP client", "{size} bytes received {bytes:?}"); - - size + if size_result.is_ok() { + let size = size_result.as_ref().unwrap(); + debug!(target: "UDP client", "{size} bytes received {bytes:?}"); + size_result + } else { + size_result + } } } /// Creates a new `UdpClient` connected to a Udp server -pub async fn new_udp_client_connected(remote_address: &str) -> UdpClient { +/// +/// # Errors +/// +/// Will return any errors present in the call stack +/// +pub async fn new_udp_client_connected(remote_address: &str) -> Result { let port = 0; // Let OS choose an unused port. - let client = UdpClient::bind(&source_address(port)).await; - client.connect(remote_address).await; - client + let client = UdpClient::bind(&source_address(port)).await?; + client.connect(remote_address).await?; + Ok(client) } #[allow(clippy::module_name_repetitions)] @@ -127,85 +150,103 @@ pub struct UdpTrackerClient { } impl UdpTrackerClient { - /// # Panics + /// # Errors /// - /// Will panic if can't write request to bytes. - pub async fn send(&self, request: Request) -> usize { + /// Will return error if can't write request to bytes. + pub async fn send(&self, request: Request) -> Result { debug!(target: "UDP tracker client", "send request {request:?}"); // Write request into a buffer let request_buffer = vec![0u8; MAX_PACKET_SIZE]; let mut cursor = Cursor::new(request_buffer); - let request_data = match request.write(&mut cursor) { + let request_data_result = match request.write(&mut cursor) { Ok(()) => { #[allow(clippy::cast_possible_truncation)] let position = cursor.position() as usize; let inner_request_buffer = cursor.get_ref(); // Return slice which contains written request data - &inner_request_buffer[..position] + Ok(&inner_request_buffer[..position]) } - Err(e) => panic!("could not write request to bytes: {e}."), + Err(e) => Err(anyhow!("could not write request to bytes: {e}.")), }; + let request_data = request_data_result?; + self.udp_client.send(request_data).await } - /// # Panics + /// # Errors /// - /// Will panic if can't create response from the received payload (bytes buffer). - pub async fn receive(&self) -> Response { + /// Will return error if can't create response from the received payload (bytes buffer). + pub async fn receive(&self) -> Result { let mut response_buffer = [0u8; MAX_PACKET_SIZE]; - let payload_size = self.udp_client.receive(&mut response_buffer).await; + let payload_size = self.udp_client.receive(&mut response_buffer).await?; debug!(target: "UDP tracker client", "received {payload_size} bytes. Response {response_buffer:?}"); - Response::from_bytes(&response_buffer[..payload_size], true).unwrap() + let response = Response::from_bytes(&response_buffer[..payload_size], true)?; + + Ok(response) } } /// Creates a new `UdpTrackerClient` connected to a Udp Tracker server -pub async fn new_udp_tracker_client_connected(remote_address: &str) -> UdpTrackerClient { - let udp_client = new_udp_client_connected(remote_address).await; - UdpTrackerClient { udp_client } +/// +/// # Errors +/// +/// Will return any errors present in the call stack +/// +pub async fn new_udp_tracker_client_connected(remote_address: &str) -> Result { + let udp_client = new_udp_client_connected(remote_address).await?; + let udp_tracker_client = UdpTrackerClient { udp_client }; + Ok(udp_tracker_client) } /// Helper Function to Check if a UDP Service is Connectable /// -/// # Errors +/// # Panics /// /// It will return an error if unable to connect to the UDP service. /// -/// # Panics +/// # Errors +/// pub async fn check(binding: &SocketAddr) -> Result { debug!("Checking Service (detail): {binding:?}."); - let client = new_udp_tracker_client_connected(binding.to_string().as_str()).await; - - let connect_request = ConnectRequest { - transaction_id: TransactionId(123), - }; - - client.send(connect_request.into()).await; - - let process = move |response| { - if matches!(response, Response::Connect(_connect_response)) { - Ok("Connected".to_string()) - } else { - Err("Did not Connect".to_string()) - } - }; - - let sleep = time::sleep(Duration::from_millis(2000)); - tokio::pin!(sleep); - - tokio::select! { - () = &mut sleep => { - Err("Timed Out".to_string()) - } - response = client.receive() => { - process(response) + match new_udp_tracker_client_connected(binding.to_string().as_str()).await { + Ok(client) => { + let connect_request = ConnectRequest { + transaction_id: TransactionId(123), + }; + + // client.send() return usize, but doesn't use here + match client.send(connect_request.into()).await { + Ok(_) => (), + Err(e) => debug!("Error: {e:?}."), + }; + + let process = move |response| { + if matches!(response, Response::Connect(_connect_response)) { + Ok("Connected".to_string()) + } else { + Err("Did not Connect".to_string()) + } + }; + + let sleep = time::sleep(Duration::from_millis(2000)); + tokio::pin!(sleep); + + tokio::select! { + () = &mut sleep => { + Err("Timed Out".to_string()) + } + response = client.receive() => { + process(response.unwrap()) + } + } } + Err(e) => Err(format!("{e:?}")), } } diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 91dca4d42..56e400f84 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -24,9 +24,15 @@ fn empty_buffer() -> [u8; MAX_PACKET_SIZE] { async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrackerClient) -> ConnectionId { let connect_request = ConnectRequest { transaction_id }; - client.send(connect_request.into()).await; + match client.send(connect_request.into()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + }; - let response = client.receive().await; + let response = match client.receive().await { + Ok(response) => response, + Err(err) => panic!("{err}"), + }; match response { Response::Connect(connect_response) => connect_response.connection_id, @@ -38,12 +44,22 @@ async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrac async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_request() { let env = Started::new(&configuration::ephemeral().into()).await; - let client = new_udp_client_connected(&env.bind_address().to_string()).await; + let client = match new_udp_client_connected(&env.bind_address().to_string()).await { + Ok(udp_client) => udp_client, + Err(err) => panic!("{err}"), + }; - client.send(&empty_udp_request()).await; + match client.send(&empty_udp_request()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + }; let mut buffer = empty_buffer(); - client.receive(&mut buffer).await; + match client.receive(&mut buffer).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + }; + let response = Response::from_bytes(&buffer, true).unwrap(); assert!(is_error_response(&response, "bad request")); @@ -63,15 +79,24 @@ mod receiving_a_connection_request { async fn should_return_a_connect_response() { let env = Started::new(&configuration::ephemeral().into()).await; - let client = new_udp_tracker_client_connected(&env.bind_address().to_string()).await; + let client = match new_udp_tracker_client_connected(&env.bind_address().to_string()).await { + Ok(udp_tracker_client) => udp_tracker_client, + Err(err) => panic!("{err}"), + }; let connect_request = ConnectRequest { transaction_id: TransactionId(123), }; - client.send(connect_request.into()).await; + match client.send(connect_request.into()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + }; - let response = client.receive().await; + let response = match client.receive().await { + Ok(response) => response, + Err(err) => panic!("{err}"), + }; assert!(is_connect_response(&response, TransactionId(123))); @@ -97,7 +122,10 @@ mod receiving_an_announce_request { async fn should_return_an_announce_response() { let env = Started::new(&configuration::ephemeral().into()).await; - let client = new_udp_tracker_client_connected(&env.bind_address().to_string()).await; + let client = match new_udp_tracker_client_connected(&env.bind_address().to_string()).await { + Ok(udp_tracker_client) => udp_tracker_client, + Err(err) => panic!("{err}"), + }; let connection_id = send_connection_request(TransactionId(123), &client).await; @@ -118,9 +146,15 @@ mod receiving_an_announce_request { port: Port(client.udp_client.socket.local_addr().unwrap().port()), }; - client.send(announce_request.into()).await; + match client.send(announce_request.into()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + }; - let response = client.receive().await; + let response = match client.receive().await { + Ok(response) => response, + Err(err) => panic!("{err}"), + }; println!("test response {response:?}"); @@ -143,7 +177,10 @@ mod receiving_an_scrape_request { async fn should_return_a_scrape_response() { let env = Started::new(&configuration::ephemeral().into()).await; - let client = new_udp_tracker_client_connected(&env.bind_address().to_string()).await; + let client = match new_udp_tracker_client_connected(&env.bind_address().to_string()).await { + Ok(udp_tracker_client) => udp_tracker_client, + Err(err) => panic!("{err}"), + }; let connection_id = send_connection_request(TransactionId(123), &client).await; @@ -159,9 +196,15 @@ mod receiving_an_scrape_request { info_hashes, }; - client.send(scrape_request.into()).await; + match client.send(scrape_request.into()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + }; - let response = client.receive().await; + let response = match client.receive().await { + Ok(response) => response, + Err(err) => panic!("{err}"), + }; assert!(is_scrape_response(&response)); From 895efe9c4154a6883008e9cf26592f3fed38602d Mon Sep 17 00:00:00 2001 From: ngthhu Date: Thu, 2 May 2024 16:02:42 +0700 Subject: [PATCH 0302/1297] refactor: [#680] http return errors instead of panicking --- src/console/clients/checker/checks/http.rs | 22 +++++- src/console/clients/http/app.rs | 10 +-- .../bit_torrent/tracker/http/client/mod.rs | 72 ++++++++++--------- 3 files changed, 63 insertions(+), 41 deletions(-) diff --git a/src/console/clients/checker/checks/http.rs b/src/console/clients/checker/checks/http.rs index e0b14b480..e526b5e57 100644 --- a/src/console/clients/checker/checks/http.rs +++ b/src/console/clients/checker/checks/http.rs @@ -61,9 +61,19 @@ async fn check_http_announce(tracker_url: &Url) -> Result<(), CheckError> { // We should change the client to catch that error and return a `CheckError`. // Otherwise the checking process will stop. The idea is to process all checks // and return a final report. - let response = Client::new(tracker_url.clone()) + let Ok(client) = Client::new(tracker_url.clone()) else { + return Err(CheckError::HttpError { + url: (tracker_url.to_owned()), + }); + }; + let Ok(response) = client .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) - .await; + .await + else { + return Err(CheckError::HttpError { + url: (tracker_url.to_owned()), + }); + }; if let Ok(body) = response.bytes().await { if let Ok(_announce_response) = serde_bencode::from_bytes::(&body) { @@ -89,7 +99,13 @@ async fn check_http_scrape(url: &Url) -> Result<(), CheckError> { // We should change the client to catch that error and return a `CheckError`. // Otherwise the checking process will stop. The idea is to process all checks // and return a final report. - let response = Client::new(url.clone()).scrape(&query).await; + + let Ok(client) = Client::new(url.clone()) else { + return Err(CheckError::HttpError { url: (url.to_owned()) }); + }; + let Ok(response) = client.scrape(&query).await else { + return Err(CheckError::HttpError { url: (url.to_owned()) }); + }; if let Ok(body) = response.bytes().await { if let Ok(_scrape_response) = scrape::Response::try_from_bencoded(&body) { diff --git a/src/console/clients/http/app.rs b/src/console/clients/http/app.rs index 511fb6628..8fc9db0c3 100644 --- a/src/console/clients/http/app.rs +++ b/src/console/clients/http/app.rs @@ -64,11 +64,11 @@ async fn announce_command(tracker_url: String, info_hash: String) -> anyhow::Res let info_hash = InfoHash::from_str(&info_hash).expect("Invalid infohash. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); - let response = Client::new(base_url) + let response = Client::new(base_url)? .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) - .await; + .await?; - let body = response.bytes().await.unwrap(); + let body = response.bytes().await?; let announce_response: Announce = serde_bencode::from_bytes(&body) .unwrap_or_else(|_| panic!("response body should be a valid announce response, got: \"{:#?}\"", &body)); @@ -85,9 +85,9 @@ async fn scrape_command(tracker_url: &str, info_hashes: &[String]) -> anyhow::Re let query = requests::scrape::Query::try_from(info_hashes).context("failed to parse infohashes")?; - let response = Client::new(base_url).scrape(&query).await; + let response = Client::new(base_url)?.scrape(&query).await?; - let body = response.bytes().await.unwrap(); + let body = response.bytes().await?; let scrape_response = scrape::Response::try_from_bencoded(&body) .unwrap_or_else(|_| panic!("response body should be a valid scrape response, got: \"{:#?}\"", &body)); diff --git a/src/shared/bit_torrent/tracker/http/client/mod.rs b/src/shared/bit_torrent/tracker/http/client/mod.rs index a75b0fec3..f5b1b3310 100644 --- a/src/shared/bit_torrent/tracker/http/client/mod.rs +++ b/src/shared/bit_torrent/tracker/http/client/mod.rs @@ -3,6 +3,7 @@ pub mod responses; use std::net::IpAddr; +use anyhow::{anyhow, Result}; use requests::announce::{self, Query}; use requests::scrape; use reqwest::{Client as ReqwestClient, Response, Url}; @@ -25,78 +26,83 @@ pub struct Client { /// base url path query /// ``` impl Client { - /// # Panics + /// # Errors /// /// This method fails if the client builder fails. - #[must_use] - pub fn new(base_url: Url) -> Self { - Self { + pub fn new(base_url: Url) -> Result { + let reqwest = reqwest::Client::builder().build()?; + Ok(Self { base_url, - reqwest: reqwest::Client::builder().build().unwrap(), + reqwest, key: None, - } + }) } /// Creates the new client binding it to an specific local address. /// - /// # Panics + /// # Errors /// /// This method fails if the client builder fails. - #[must_use] - pub fn bind(base_url: Url, local_address: IpAddr) -> Self { - Self { + pub fn bind(base_url: Url, local_address: IpAddr) -> Result { + let reqwest = reqwest::Client::builder().local_address(local_address).build()?; + Ok(Self { base_url, - reqwest: reqwest::Client::builder().local_address(local_address).build().unwrap(), + reqwest, key: None, - } + }) } - /// # Panics + /// # Errors /// /// This method fails if the client builder fails. - #[must_use] - pub fn authenticated(base_url: Url, key: Key) -> Self { - Self { + pub fn authenticated(base_url: Url, key: Key) -> Result { + let reqwest = reqwest::Client::builder().build()?; + Ok(Self { base_url, - reqwest: reqwest::Client::builder().build().unwrap(), + reqwest, key: Some(key), - } + }) } - pub async fn announce(&self, query: &announce::Query) -> Response { + /// # Errors + pub async fn announce(&self, query: &announce::Query) -> Result { self.get(&self.build_announce_path_and_query(query)).await } - pub async fn scrape(&self, query: &scrape::Query) -> Response { + /// # Errors + pub async fn scrape(&self, query: &scrape::Query) -> Result { self.get(&self.build_scrape_path_and_query(query)).await } - pub async fn announce_with_header(&self, query: &Query, key: &str, value: &str) -> Response { + /// # Errors + pub async fn announce_with_header(&self, query: &Query, key: &str, value: &str) -> Result { self.get_with_header(&self.build_announce_path_and_query(query), key, value) .await } - pub async fn health_check(&self) -> Response { + /// # Errors + pub async fn health_check(&self) -> Result { self.get(&self.build_path("health_check")).await } - /// # Panics + /// # Errors /// /// This method fails if there was an error while sending request. - pub async fn get(&self, path: &str) -> Response { - self.reqwest.get(self.build_url(path)).send().await.unwrap() + pub async fn get(&self, path: &str) -> Result { + match self.reqwest.get(self.build_url(path)).send().await { + Ok(response) => Ok(response), + Err(err) => Err(anyhow!("{err}")), + } } - /// # Panics + /// # Errors /// /// This method fails if there was an error while sending request. - pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Response { - self.reqwest - .get(self.build_url(path)) - .header(key, value) - .send() - .await - .unwrap() + pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Result { + match self.reqwest.get(self.build_url(path)).header(key, value).send().await { + Ok(response) => Ok(response), + Err(err) => Err(anyhow!("{err}")), + } } fn build_announce_path_and_query(&self, query: &announce::Query) -> String { From 75518570ae086ada07bbce6d077475a67461b944 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 6 May 2024 08:03:56 +0100 Subject: [PATCH 0303/1297] chore(deps): update dependencies --- Cargo.lock | 279 +++++++++++++++++++++++++++-------------------------- Cargo.toml | 4 +- 2 files changed, 144 insertions(+), 139 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 44f9db17c..143ba1aac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -93,47 +93,48 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.13" +version = "0.6.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d96bd03f33fe50a863e394ee9718a706f988b9079b20c3784fb726e7678b62fb" +checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", + "is_terminal_polyfill", "utf8parse", ] [[package]] name = "anstyle" -version = "1.0.6" +version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8901269c6307e8d93993578286ac0edf7f195079ffff5ebdeea6a59ffb7e36bc" +checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b" [[package]] name = "anstyle-parse" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c" +checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648" +checksum = "a64c907d4e79225ac72e2a354c9ce84d50ebb4586dee56c82b3ee73004f537f5" dependencies = [ "windows-sys 0.52.0", ] [[package]] name = "anstyle-wincon" -version = "3.0.2" +version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7" +checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19" dependencies = [ "anstyle", "windows-sys 0.52.0", @@ -196,16 +197,16 @@ checksum = "136d4d23bcc79e27423727b36823d86233aad06dfea531837b038394d11e9928" dependencies = [ "concurrent-queue", "event-listener 5.3.0", - "event-listener-strategy 0.5.1", + "event-listener-strategy 0.5.2", "futures-core", "pin-project-lite", ] [[package]] name = "async-compression" -version = "0.4.8" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07dbbf24db18d609b1462965249abdf49129ccad073ec257da372adc83259c60" +checksum = "4e9eabd7a98fe442131a17c316bd9349c43695e49e730c3c8e12cfb5f4da2693" dependencies = [ "brotli", "flate2", @@ -225,7 +226,7 @@ checksum = "b10202063978b3351199d68f8b22c4e47e4b1b822f8d43fd862d5ea8c006b29a" dependencies = [ "async-task", "concurrent-queue", - "fastrand 2.0.2", + "fastrand 2.1.0", "futures-lite 2.3.0", "slab", ] @@ -278,8 +279,8 @@ dependencies = [ "futures-io", "futures-lite 2.3.0", "parking", - "polling 3.6.0", - "rustix 0.38.32", + "polling 3.7.0", + "rustix 0.38.34", "slab", "tracing", "windows-sys 0.52.0", @@ -334,9 +335,9 @@ dependencies = [ [[package]] name = "async-task" -version = "4.7.0" +version = "4.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbb36e985947064623dbd357f727af08ffd077f93d696782f3c56365fa2e2799" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" [[package]] name = "async-trait" @@ -357,9 +358,9 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80" +checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" [[package]] name = "axum" @@ -509,9 +510,9 @@ checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" [[package]] name = "base64" -version = "0.22.0" +version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9475866fec1451be56a3c2400fd081ff546538961565ccb5b7142cbd22bc7a51" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "bigdecimal" @@ -588,25 +589,23 @@ dependencies = [ [[package]] name = "blocking" -version = "1.5.1" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a37913e8dc4ddcc604f0c6d3bf2887c995153af3611de9e23c352b44c1b9118" +checksum = "495f7104e962b7356f0aeb34247aca1fe7d2e783b346582db7f2904cb5717e88" dependencies = [ "async-channel 2.2.1", "async-lock 3.3.0", "async-task", - "fastrand 2.0.2", "futures-io", "futures-lite 2.3.0", "piper", - "tracing", ] [[package]] name = "borsh" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0901fc8eb0aca4c83be0106d6f2db17d86a08dfc2c25f0e84464bf381158add6" +checksum = "dbe5b10e214954177fb1dc9fbd20a1a2608fe99e6c832033bdc7cea287a20d77" dependencies = [ "borsh-derive", "cfg_aliases", @@ -614,9 +613,9 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51670c3aa053938b0ee3bd67c3817e471e626151131b934038e83c5bf8de48f5" +checksum = "d7a8646f94ab393e43e8b35a2558b1624bed28b97ee09c5d15456e3c9463f46d" dependencies = [ "once_cell", "proc-macro-crate 3.1.0", @@ -628,9 +627,9 @@ dependencies = [ [[package]] name = "brotli" -version = "4.0.0" +version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "125740193d7fee5cc63ab9e16c2fdc4e07c74ba755cc53b327d6ea029e9fc569" +checksum = "19483b140a7ac7174d34b5a581b406c64f84da5409d3e09cf4fff604f9270e67" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -639,9 +638,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "3.0.0" +version = "4.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65622a320492e09b5e0ac436b14c54ff68199bac392d0e89a6832c4518eea525" +checksum = "e6221fe77a248b9117d431ad93761222e1cf8ff282d9d1d5d9f53d6299a1cf76" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -701,12 +700,13 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.0.94" +version = "1.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17f6e324229dc011159fcc089755d1e2e216a90d43a7dea6853ca740b84f35e7" +checksum = "065a29261d53ba54260972629f9ca6bffa69bac13cd1fed61420f7fa68b9f8bd" dependencies = [ "jobserver", "libc", + "once_cell", ] [[package]] @@ -832,15 +832,15 @@ dependencies = [ [[package]] name = "colorchoice" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" +checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" [[package]] name = "concurrent-queue" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d16048cd947b08fa32c24458a22f5dc5e835264f689f4f5653210c69fd107363" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" dependencies = [ "crossbeam-utils", ] @@ -1096,7 +1096,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" dependencies = [ "cfg-if", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "lock_api", "once_cell", "parking_lot_core", @@ -1242,9 +1242,9 @@ dependencies = [ [[package]] name = "event-listener-strategy" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "332f51cb23d20b0de8458b86580878211da09bcd4503cb579c225b3d124cabb3" +checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" dependencies = [ "event-listener 5.3.0", "pin-project-lite", @@ -1273,9 +1273,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.0.2" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658bd65b1cf4c852a3cc96f18a8ce7b5640f6b703f905c7d74532294c2a63984" +checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "fern" @@ -1288,9 +1288,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.28" +version = "1.0.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46303f565772937ffe1d394a4fac6f411c6013172fadde9dcdb1e147a086940e" +checksum = "5f54427cfd1c7829e2a139fcefea601bf088ebca651d2bf53ebc600eac295dae" dependencies = [ "crc32fast", "libz-sys", @@ -1470,7 +1470,7 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" dependencies = [ - "fastrand 2.0.2", + "fastrand 2.1.0", "futures-core", "futures-io", "parking", @@ -1618,9 +1618,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.14.3" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ "ahash 0.8.11", "allocator-api2", @@ -1632,7 +1632,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "692eaaf7f7607518dd3cef090f1474b61edc5301d8012f09579920df68b725ee" dependencies = [ - "hashbrown 0.14.3", + "hashbrown 0.14.5", ] [[package]] @@ -1761,7 +1761,7 @@ dependencies = [ "http-body", "hyper", "pin-project-lite", - "socket2 0.5.6", + "socket2 0.5.7", "tokio", "tower", "tower-service", @@ -1825,7 +1825,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" dependencies = [ "equivalent", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "serde", ] @@ -1875,6 +1875,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" + [[package]] name = "itertools" version = "0.10.5" @@ -1901,9 +1907,9 @@ checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "jobserver" -version = "0.1.30" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "685a7d121ee3f65ae4fddd72b25a04bb36b6af81bc0828f7d5434c0fe60fa3a2" +checksum = "d2b099aaa34a9751c5bf0878add70444e1ed2dd73f347be99003d4577277de6e" dependencies = [ "libc", ] @@ -2024,9 +2030,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.153" +version = "0.2.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" +checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346" [[package]] name = "libloading" @@ -2092,9 +2098,9 @@ dependencies = [ [[package]] name = "lock_api" -version = "0.4.11" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" dependencies = [ "autocfg", "scopeguard", @@ -2219,7 +2225,7 @@ dependencies = [ "percent-encoding", "serde", "serde_json", - "socket2 0.5.6", + "socket2 0.5.7", "twox-hash", "url", ] @@ -2376,9 +2382,9 @@ dependencies = [ [[package]] name = "num-traits" -version = "0.2.18" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", ] @@ -2476,9 +2482,9 @@ checksum = "bb813b8af86854136c6922af0598d719255ecb2179515e6e7730d468f05c9cae" [[package]] name = "parking_lot" -version = "0.12.1" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +checksum = "7e4af0ca4f6caed20e900d564c242b8e5d4903fdacf31d3daf527b66fe6f42fb" dependencies = [ "lock_api", "parking_lot_core", @@ -2486,15 +2492,15 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.9" +version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", "redox_syscall", "smallvec", - "windows-targets 0.48.5", + "windows-targets 0.52.5", ] [[package]] @@ -2521,9 +2527,9 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.9" +version = "2.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "311fb059dee1a7b802f036316d790138c613a4e8b180c822e3925a662e9f0c95" +checksum = "560131c633294438da9f7c4b08189194b20946c8274c6b9e38881a7874dc8ee8" dependencies = [ "memchr", "thiserror", @@ -2532,9 +2538,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.9" +version = "2.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f73541b156d32197eecda1a4014d7f868fd2bcb3c550d5386087cfba442bf69c" +checksum = "26293c9193fbca7b1a3bf9b79dc1e388e927e6cacaa78b4a3ab705a1d3d41459" dependencies = [ "pest", "pest_generator", @@ -2542,9 +2548,9 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.9" +version = "2.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c35eeed0a3fab112f75165fdc026b3913f4183133f19b49be773ac9ea966e8bd" +checksum = "3ec22af7d3fb470a85dd2ca96b7c577a1eb4ef6f1683a9fe9a8c16e136c04687" dependencies = [ "pest", "pest_meta", @@ -2555,9 +2561,9 @@ dependencies = [ [[package]] name = "pest_meta" -version = "2.7.9" +version = "2.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2adbf29bb9776f28caece835398781ab24435585fe0d4dc1374a61db5accedca" +checksum = "d7a240022f37c361ec1878d646fc5b7d7c4d28d5946e1a80ad5a7a4f4ca0bdcd" dependencies = [ "once_cell", "pest", @@ -2641,7 +2647,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "668d31b1c4eba19242f2088b2bf3316b82ca31082a8335764db4e083db7485d4" dependencies = [ "atomic-waker", - "fastrand 2.0.2", + "fastrand 2.1.0", "futures-io", ] @@ -2697,15 +2703,15 @@ dependencies = [ [[package]] name = "polling" -version = "3.6.0" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0c976a60b2d7e99d6f229e414670a9b85d13ac305cc6d1e9c134de58c5aaaf6" +checksum = "645493cf344456ef24219d02a768cf1fb92ddf8c92161679ae3d91b91a637be3" dependencies = [ "cfg-if", "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 0.38.32", + "rustix 0.38.34", "tracing", "windows-sys 0.52.0", ] @@ -2919,11 +2925,11 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.4.1" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +checksum = "469052894dcb553421e483e4209ee581a45100d31b4018de03e5a7ad86374a7e" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.5.0", ] [[package]] @@ -2957,9 +2963,9 @@ checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" [[package]] name = "relative-path" -version = "1.9.2" +version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e898588f33fdd5b9420719948f9f2a32c922a246964576f71ba7f24f80610fbc" +checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" [[package]] name = "rend" @@ -2972,11 +2978,11 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.3" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e6cc1e89e689536eb5aeede61520e874df5a4707df811cd5da4aa5fbb2aae19" +checksum = "566cafdd92868e0939d3fb961bd0dc25fcfaaed179291093b3d43e6b3150ea10" dependencies = [ - "base64 0.22.0", + "base64 0.22.1", "bytes", "encoding_rs", "futures-core", @@ -3183,9 +3189,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.32" +version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89" +checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ "bitflags 2.5.0", "errno", @@ -3196,9 +3202,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.21.10" +version = "0.21.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d5a6813c0759e4609cd494e8e725babae6a2ca7b62a5536a13daaec6fcb7ba" +checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" dependencies = [ "log", "ring", @@ -3212,15 +3218,15 @@ version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d" dependencies = [ - "base64 0.22.0", + "base64 0.22.1", "rustls-pki-types", ] [[package]] name = "rustls-pki-types" -version = "1.4.1" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecd36cc4259e3e4514335c4a138c6b43171a8d61d8f5c9348f9fc7529416f247" +checksum = "beb461507cee2c2ff151784c52762cf4d9ff6a61f3e80968600ed24fa837fa54" [[package]] name = "rustls-webpki" @@ -3301,11 +3307,11 @@ checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" [[package]] name = "security-framework" -version = "2.10.0" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "770452e37cad93e0a50d5abc3990d2bc351c36d0328f86cefec2f2fb206eaef6" +checksum = "c627723fd09706bacdb5cf41499e95098555af3c3c29d014dc3c458ef6be11c0" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.5.0", "core-foundation", "core-foundation-sys", "libc", @@ -3314,9 +3320,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.10.0" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f3cc463c0ef97e11c3461a9d3787412d30e8e7eb907c79180c4a57bf7c04ef" +checksum = "317936bbbd05227752583946b9e66d7ce3b489f84e11a94a510b4437fef407d7" dependencies = [ "core-foundation-sys", "libc", @@ -3330,9 +3336,9 @@ checksum = "92d43fe69e652f3df9bdc2b85b2854a0825b86e4fb76bc44d945137d053639ca" [[package]] name = "serde" -version = "1.0.198" +version = "1.0.200" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9846a40c979031340571da2545a4e5b7c4163bdae79b301d5f86d03979451fcc" +checksum = "ddc6f9cc94d67c0e21aaf7eda3a010fd3af78ebf6e096aa6e2e13c79749cce4f" dependencies = [ "serde_derive", ] @@ -3358,9 +3364,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.198" +version = "1.0.200" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e88edab869b01783ba905e7d0153f9fc1a6505a96e4ad3018011eedb838566d9" +checksum = "856f046b9400cee3c8c94ed572ecdb752444c24528c035cd35882aad6f492bcb" dependencies = [ "proc-macro2", "quote", @@ -3436,11 +3442,11 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.7.0" +version = "3.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee80b0e361bbf88fd2f6e242ccd19cfda072cb0faa6ae694ecee08199938569a" +checksum = "0ad483d2ab0149d5a5ebcd9972a3852711e0153d863bf5a5d0391d28883c4a20" dependencies = [ - "base64 0.21.7", + "base64 0.22.1", "chrono", "hex", "indexmap 1.9.3", @@ -3454,9 +3460,9 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.7.0" +version = "3.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6561dc161a9224638a31d876ccdfefbc1df91d3f3a8342eddb35f055d48c7655" +checksum = "65569b702f41443e8bc8bbb1c5779bd0450bbe723b56198980e80ec45780bce2" dependencies = [ "darling", "proc-macro2", @@ -3494,9 +3500,9 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "signal-hook-registry" -version = "1.4.1" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" +checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" dependencies = [ "libc", ] @@ -3540,9 +3546,9 @@ dependencies = [ [[package]] name = "socket2" -version = "0.5.6" +version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05ffd9c0a93b7543e062e759284fcf5f5e3b098501104bfbdde4d404db792871" +checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" dependencies = [ "libc", "windows-sys 0.52.0", @@ -3679,8 +3685,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", - "fastrand 2.0.2", - "rustix 0.38.32", + "fastrand 2.1.0", + "rustix 0.38.34", "windows-sys 0.52.0", ] @@ -3701,18 +3707,18 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.58" +version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03468839009160513471e86a034bb2c5c0e4baae3b43f79ffc55c4a5427b3297" +checksum = "f0126ad08bff79f29fc3ae6a55cc72352056dfff61e3ff8bb7129476d44b23aa" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.58" +version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" +checksum = "d1cd413b5d558b4c5bf3680e324a6fa5014e7b7c067a51e69dbdf47eb7148b66" dependencies = [ "proc-macro2", "quote", @@ -3797,7 +3803,7 @@ dependencies = [ "num_cpus", "pin-project-lite", "signal-hook-registry", - "socket2 0.5.6", + "socket2 0.5.7", "tokio-macros", "windows-sys 0.48.0", ] @@ -3835,16 +3841,15 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.10" +version = "0.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5419f34732d9eb6ee4c3578b7989078579b7f039cbbb9ca2c4da015749371e15" +checksum = "9cf6b47b3771c49ac75ad09a6162f53ad4b8088b76ac60e8ec1455b31a189fe1" dependencies = [ "bytes", "futures-core", "futures-sink", "pin-project-lite", "tokio", - "tracing", ] [[package]] @@ -3856,7 +3861,7 @@ dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.11", + "toml_edit 0.22.12", ] [[package]] @@ -3892,15 +3897,15 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.11" +version = "0.22.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb686a972ccef8537b39eead3968b0e8616cb5040dbb9bba93007c8e07c9215f" +checksum = "d3328d4f68a705b2a4498da1d580585d39a6510f98318a2cec3018a7ec61ddef" dependencies = [ "indexmap 2.2.6", "serde", "serde_spanned", "toml_datetime", - "winnow 0.6.6", + "winnow 0.6.8", ] [[package]] @@ -4220,9 +4225,9 @@ dependencies = [ [[package]] name = "value-bag" -version = "1.8.1" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74797339c3b98616c009c7c3eb53a0ce41e85c8ec66bd3db96ed132d20cfdee8" +checksum = "5a84c137d37ab0142f0f2ddfe332651fdbf252e7b7dbb4e67b6c1f1b2e925101" [[package]] name = "vcpkg" @@ -4361,11 +4366,11 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596" +checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b" dependencies = [ - "winapi", + "windows-sys 0.52.0", ] [[package]] @@ -4533,9 +4538,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.6.6" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0c976aaaa0e1f90dbb21e9587cdaf1d9679a1cde8875c0d6bd83ab96a208352" +checksum = "c3c52e9c97a68071b23e836c9380edae937f17b9c4667bd021973efc689f618d" dependencies = [ "memchr", ] @@ -4570,18 +4575,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.7.32" +version = "0.7.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be" +checksum = "087eca3c1eaf8c47b94d02790dd086cd594b912d2043d4de4bfdd466b3befb7c" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.7.32" +version = "0.7.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" +checksum = "6f4b6c273f496d8fd4eaf18853e6b448760225dc030ff2c485a786859aea6393" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 0e37b7ad0..486c41230 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,7 +31,7 @@ version = "3.0.0-alpha.12-develop" [dependencies] anyhow = "1" -aquatic_udp_protocol = "0" +aquatic_udp_protocol = "0.8" async-trait = "0" axum = { version = "0", features = ["macros"] } axum-client-ip = "0" @@ -57,7 +57,7 @@ r2d2_mysql = "24" r2d2_sqlite = { version = "0", features = ["bundled"] } rand = "0" reqwest = { version = "0", features = ["json"] } -ringbuf = "0" +ringbuf = "0.3.3" serde = { version = "1", features = ["derive"] } serde_bencode = "0" serde_bytes = "0" From 801d91363a7570efef75d4aede39b961564963d1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 May 2024 10:05:48 +0100 Subject: [PATCH 0304/1297] chore(deps): bump aquatic_udp_protocol from 0.8.0 to 0.9.0 --- Cargo.lock | 65 +++++++- Cargo.toml | 3 +- cSpell.json | 3 +- src/console/clients/checker/checks/udp.rs | 4 +- src/console/clients/udp/app.rs | 6 +- src/console/clients/udp/checker.rs | 19 +-- src/console/clients/udp/responses.rs | 38 ++--- src/servers/udp/connection_cookie.rs | 8 +- src/servers/udp/handlers.rs | 152 ++++++++++--------- src/servers/udp/peer_builder.rs | 17 ++- src/servers/udp/request.rs | 2 +- src/servers/udp/server.rs | 2 +- src/shared/bit_torrent/tracker/udp/client.rs | 7 +- tests/servers/udp/contract.rs | 35 ++--- 14 files changed, 225 insertions(+), 136 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 143ba1aac..b7f592666 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -146,14 +146,30 @@ version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519" +[[package]] +name = "aquatic_peer_id" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0732a73df221dcb25713849c6ebaf57b85355f669716652a7466f688cc06f25" +dependencies = [ + "compact_str", + "hex", + "quickcheck", + "regex", + "serde", + "zerocopy", +] + [[package]] name = "aquatic_udp_protocol" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2919b480121f7d20d247524da62bad1b6b7928bc3f50898f624b5c592727341" +checksum = "0af90e5162f5fcbde33524128f08dc52a779f32512d5f8692eadd4b55c89389e" dependencies = [ + "aquatic_peer_id", "byteorder", "either", + "zerocopy", ] [[package]] @@ -698,6 +714,15 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" +[[package]] +name = "castaway" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a17ed5635fc8536268e5d4de1e22e81ac34419e5f052d4d51f4e01dcc263fcc" +dependencies = [ + "rustversion", +] + [[package]] name = "cc" version = "1.0.96" @@ -836,6 +861,19 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" +[[package]] +name = "compact_str" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f86b9c4c00838774a6d902ef931eff7470720c51d90c2e32cfe15dc304737b3f" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "ryu", + "static_assertions", +] + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -1176,6 +1214,16 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "env_logger" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3" +dependencies = [ + "log", + "regex", +] + [[package]] name = "equivalent" version = "1.0.1" @@ -2826,6 +2874,17 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "quickcheck" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "588f6378e4dd99458b60ec275b4477add41ce4fa9f64dcba6f15adccb19b50d6" +dependencies = [ + "env_logger", + "log", + "rand", +] + [[package]] name = "quote" version = "1.0.36" @@ -3961,6 +4020,7 @@ dependencies = [ "tracing", "url", "uuid", + "zerocopy", ] [[package]] @@ -4579,6 +4639,7 @@ version = "0.7.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "087eca3c1eaf8c47b94d02790dd086cd594b912d2043d4de4bfdd466b3befb7c" dependencies = [ + "byteorder", "zerocopy-derive", ] diff --git a/Cargo.toml b/Cargo.toml index 486c41230..63735450e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,7 +31,7 @@ version = "3.0.0-alpha.12-develop" [dependencies] anyhow = "1" -aquatic_udp_protocol = "0.8" +aquatic_udp_protocol = "0" async-trait = "0" axum = { version = "0", features = ["macros"] } axum-client-ip = "0" @@ -76,6 +76,7 @@ trace = "0" tracing = "0" url = "2" uuid = { version = "1", features = ["v4"] } +zerocopy = "0.7.33" [package.metadata.cargo-machete] ignored = ["serde_bytes", "crossbeam-skiplist", "dashmap", "parking_lot"] diff --git a/cSpell.json b/cSpell.json index 24ef6b0a0..2473e9c33 100644 --- a/cSpell.json +++ b/cSpell.json @@ -170,7 +170,8 @@ "Xtorrent", "Xunlei", "xxxxxxxxxxxxxxxxxxxxd", - "yyyyyyyyyyyyyyyyyyyyd" + "yyyyyyyyyyyyyyyyyyyyd", + "zerocopy" ], "enableFiletypes": [ "dockerfile", diff --git a/src/console/clients/checker/checks/udp.rs b/src/console/clients/checker/checks/udp.rs index 48f72edf9..6458190d4 100644 --- a/src/console/clients/checker/checks/udp.rs +++ b/src/console/clients/checker/checks/udp.rs @@ -27,7 +27,7 @@ pub async fn run(udp_trackers: &Vec, check_results: &mut Vec, check_results: &mut Vec anyhow::Result { - let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); + let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); let mut client = checker::Client::default(); @@ -151,12 +151,12 @@ async fn handle_announce(tracker_socket_addr: &SocketAddr, info_hash: &TorrustIn let connection_id = client.send_connection_request(transaction_id).await?; client - .send_announce_request(connection_id, transaction_id, *info_hash, Port(bound_to.port())) + .send_announce_request(connection_id, transaction_id, *info_hash, Port(bound_to.port().into())) .await } async fn handle_scrape(tracker_socket_addr: &SocketAddr, info_hashes: &[TorrustInfoHash]) -> anyhow::Result { - let transaction_id = TransactionId(RANDOM_TRANSACTION_ID); + let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); let mut client = checker::Client::default(); diff --git a/src/console/clients/udp/checker.rs b/src/console/clients/udp/checker.rs index 9b2a9011e..d51492041 100644 --- a/src/console/clients/udp/checker.rs +++ b/src/console/clients/udp/checker.rs @@ -3,8 +3,8 @@ use std::net::{Ipv4Addr, SocketAddr}; use anyhow::Context; use aquatic_udp_protocol::common::InfoHash; use aquatic_udp_protocol::{ - AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, Response, - ScrapeRequest, TransactionId, + AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, + PeerId, PeerKey, Port, Response, ScrapeRequest, TransactionId, }; use log::debug; use thiserror::Error; @@ -148,16 +148,17 @@ impl Client { let announce_request = AnnounceRequest { connection_id, + action_placeholder: AnnounceActionPlaceholder::default(), transaction_id, info_hash: InfoHash(info_hash.bytes()), peer_id: PeerId(*b"-qB00000000000000001"), - bytes_downloaded: NumberOfBytes(0i64), - bytes_uploaded: NumberOfBytes(0i64), - bytes_left: NumberOfBytes(0i64), - event: AnnounceEvent::Started, - ip_address: Some(Ipv4Addr::new(0, 0, 0, 0)), - key: PeerKey(0u32), - peers_wanted: NumberOfPeers(1i32), + bytes_downloaded: NumberOfBytes(0i64.into()), + bytes_uploaded: NumberOfBytes(0i64.into()), + bytes_left: NumberOfBytes(0i64.into()), + event: AnnounceEvent::Started.into(), + ip_address: Ipv4Addr::new(0, 0, 0, 0).into(), + key: PeerKey::new(0i32), + peers_wanted: NumberOfPeers(1i32.into()), port: client_port, }; diff --git a/src/console/clients/udp/responses.rs b/src/console/clients/udp/responses.rs index 2fbc38f5f..8ea1a978b 100644 --- a/src/console/clients/udp/responses.rs +++ b/src/console/clients/udp/responses.rs @@ -1,7 +1,7 @@ //! Aquatic responses are not serializable. These are the serializable wrappers. use std::net::{Ipv4Addr, Ipv6Addr}; -use aquatic_udp_protocol::{AnnounceResponse, ScrapeResponse}; +use aquatic_udp_protocol::{AnnounceResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse}; use serde::Serialize; #[derive(Serialize)] @@ -13,33 +13,33 @@ pub struct AnnounceResponseDto { peers: Vec, } -impl From> for AnnounceResponseDto { - fn from(announce: AnnounceResponse) -> Self { +impl From> for AnnounceResponseDto { + fn from(announce: AnnounceResponse) -> Self { Self { - transaction_id: announce.transaction_id.0, - announce_interval: announce.announce_interval.0, - leechers: announce.leechers.0, - seeders: announce.seeders.0, + transaction_id: announce.fixed.transaction_id.0.into(), + announce_interval: announce.fixed.announce_interval.0.into(), + leechers: announce.fixed.leechers.0.into(), + seeders: announce.fixed.seeders.0.into(), peers: announce .peers .iter() - .map(|peer| format!("{}:{}", peer.ip_address, peer.port.0)) + .map(|peer| format!("{}:{}", Ipv4Addr::from(peer.ip_address), peer.port.0)) .collect::>(), } } } -impl From> for AnnounceResponseDto { - fn from(announce: AnnounceResponse) -> Self { +impl From> for AnnounceResponseDto { + fn from(announce: AnnounceResponse) -> Self { Self { - transaction_id: announce.transaction_id.0, - announce_interval: announce.announce_interval.0, - leechers: announce.leechers.0, - seeders: announce.seeders.0, + transaction_id: announce.fixed.transaction_id.0.into(), + announce_interval: announce.fixed.announce_interval.0.into(), + leechers: announce.fixed.leechers.0.into(), + seeders: announce.fixed.seeders.0.into(), peers: announce .peers .iter() - .map(|peer| format!("{}:{}", peer.ip_address, peer.port.0)) + .map(|peer| format!("{}:{}", Ipv6Addr::from(peer.ip_address), peer.port.0)) .collect::>(), } } @@ -54,14 +54,14 @@ pub struct ScrapeResponseDto { impl From for ScrapeResponseDto { fn from(scrape: ScrapeResponse) -> Self { Self { - transaction_id: scrape.transaction_id.0, + transaction_id: scrape.transaction_id.0.into(), torrent_stats: scrape .torrent_stats .iter() .map(|torrent_scrape_statistics| TorrentStats { - seeders: torrent_scrape_statistics.seeders.0, - completed: torrent_scrape_statistics.completed.0, - leechers: torrent_scrape_statistics.leechers.0, + seeders: torrent_scrape_statistics.seeders.0.into(), + completed: torrent_scrape_statistics.completed.0.into(), + leechers: torrent_scrape_statistics.leechers.0.into(), }) .collect::>(), } diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs index 49ea6261b..af3a28702 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/servers/udp/connection_cookie.rs @@ -71,6 +71,8 @@ use std::panic::Location; use aquatic_udp_protocol::ConnectionId; use torrust_tracker_clock::time_extent::{Extent, TimeExtent}; +use zerocopy::network_endian::I64; +use zerocopy::AsBytes; use super::error::Error; @@ -83,13 +85,15 @@ pub const COOKIE_LIFETIME: TimeExtent = TimeExtent::from_sec(2, &60); /// Converts a connection ID into a connection cookie. #[must_use] pub fn from_connection_id(connection_id: &ConnectionId) -> Cookie { - connection_id.0.to_le_bytes() + let mut cookie = [0u8; 8]; + connection_id.write_to(&mut cookie); + cookie } /// Converts a connection cookie into a connection ID. #[must_use] pub fn into_connection_id(connection_cookie: &Cookie) -> ConnectionId { - ConnectionId(i64::from_le_bytes(*connection_cookie)) + ConnectionId(I64::new(i64::from_be_bytes(*connection_cookie))) } /// Generates a new connection cookie. diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 122e666a8..876f4c9fe 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -1,19 +1,21 @@ //! Handlers for the UDP server. use std::fmt; -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::net::{IpAddr, SocketAddr}; use std::panic::Location; use std::sync::Arc; use std::time::Instant; use aquatic_udp_protocol::{ - AnnounceInterval, AnnounceRequest, AnnounceResponse, ConnectRequest, ConnectResponse, ErrorResponse, NumberOfDownloads, - NumberOfPeers, Port, Request, Response, ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, + AnnounceInterval, AnnounceRequest, AnnounceResponse, AnnounceResponseFixedData, ConnectRequest, ConnectResponse, + ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfDownloads, NumberOfPeers, Port, Request, Response, ResponsePeer, + ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; use log::debug; use tokio::net::UdpSocket; use torrust_tracker_located_error::DynError; use torrust_tracker_primitives::info_hash::InfoHash; use uuid::Uuid; +use zerocopy::network_endian::I32; use super::connection_cookie::{check, from_connection_id, into_connection_id, make}; use super::UdpRequest; @@ -41,7 +43,7 @@ pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc { - ip_address: ip, - port: Port(peer.peer_addr.port()), + Some(ResponsePeer:: { + ip_address: ip.into(), + port: Port(peer.peer_addr.port().into()), }) } else { None @@ -204,18 +208,20 @@ pub async fn handle_announce( Ok(Response::from(announce_response)) } else { let announce_response = AnnounceResponse { - transaction_id: wrapped_announce_request.announce_request.transaction_id, - announce_interval: AnnounceInterval(i64::from(tracker.get_announce_policy().interval) as i32), - leechers: NumberOfPeers(i64::from(response.stats.incomplete) as i32), - seeders: NumberOfPeers(i64::from(response.stats.complete) as i32), + fixed: AnnounceResponseFixedData { + transaction_id: wrapped_announce_request.announce_request.transaction_id, + announce_interval: AnnounceInterval(I32::new(i64::from(tracker.get_announce_policy().interval) as i32)), + leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), + seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), + }, peers: response .peers .iter() .filter_map(|peer| { if let IpAddr::V6(ip) = peer.peer_addr.ip() { - Some(ResponsePeer:: { - ip_address: ip, - port: Port(peer.peer_addr.port()), + Some(ResponsePeer:: { + ip_address: ip.into(), + port: Port(peer.peer_addr.port().into()), }) } else { None @@ -259,9 +265,9 @@ pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tra #[allow(clippy::cast_possible_truncation)] let scrape_entry = { TorrentScrapeStatistics { - seeders: NumberOfPeers(i64::from(swarm_metadata.complete) as i32), - completed: NumberOfDownloads(i64::from(swarm_metadata.downloaded) as i32), - leechers: NumberOfPeers(i64::from(swarm_metadata.incomplete) as i32), + seeders: NumberOfPeers(I32::new(i64::from(swarm_metadata.complete) as i32)), + completed: NumberOfDownloads(I32::new(i64::from(swarm_metadata.downloaded) as i32)), + leechers: NumberOfPeers(I32::new(i64::from(swarm_metadata.incomplete) as i32)), } }; @@ -445,14 +451,14 @@ mod tests { fn sample_connect_request() -> ConnectRequest { ConnectRequest { - transaction_id: TransactionId(0i32), + transaction_id: TransactionId(0i32.into()), } } #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { let request = ConnectRequest { - transaction_id: TransactionId(0i32), + transaction_id: TransactionId(0i32.into()), }; let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker()) @@ -471,7 +477,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { let request = ConnectRequest { - transaction_id: TransactionId(0i32), + transaction_id: TransactionId(0i32.into()), }; let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker()) @@ -529,10 +535,11 @@ mod tests { mod announce_request { use std::net::Ipv4Addr; + use std::num::NonZeroU16; use aquatic_udp_protocol::{ - AnnounceEvent, AnnounceRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId as AquaticPeerId, PeerKey, Port, - TransactionId, + AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectionId, NumberOfBytes, NumberOfPeers, + PeerId as AquaticPeerId, PeerKey, Port, TransactionId, }; use crate::servers::udp::connection_cookie::{into_connection_id, make}; @@ -550,17 +557,18 @@ mod tests { let default_request = AnnounceRequest { connection_id: into_connection_id(&make(&sample_ipv4_remote_addr())), - transaction_id: TransactionId(0i32), + action_placeholder: AnnounceActionPlaceholder::default(), + transaction_id: TransactionId(0i32.into()), info_hash: info_hash_aquatic, peer_id: AquaticPeerId([255u8; 20]), - bytes_downloaded: NumberOfBytes(0i64), - bytes_uploaded: NumberOfBytes(0i64), - bytes_left: NumberOfBytes(0i64), - event: AnnounceEvent::Started, - ip_address: Some(client_ip), - key: PeerKey(0u32), - peers_wanted: NumberOfPeers(1i32), - port: Port(client_port), + bytes_downloaded: NumberOfBytes(0i64.into()), + bytes_uploaded: NumberOfBytes(0i64.into()), + bytes_left: NumberOfBytes(0i64.into()), + event: AnnounceEvent::Started.into(), + ip_address: client_ip.into(), + key: PeerKey::new(0i32), + peers_wanted: NumberOfPeers::new(1i32), + port: Port::new(NonZeroU16::new(client_port).expect("a non-zero client port")), }; AnnounceRequestBuilder { request: default_request, @@ -583,12 +591,12 @@ mod tests { } pub fn with_ip_address(mut self, ip_address: Ipv4Addr) -> Self { - self.request.ip_address = Some(ip_address); + self.request.ip_address = ip_address.into(); self } pub fn with_port(mut self, port: u16) -> Self { - self.request.port = Port(port); + self.request.port = Port(port.into()); self } @@ -600,23 +608,23 @@ mod tests { mod using_ipv4 { use std::future; - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::{ - AnnounceInterval, AnnounceResponse, InfoHash as AquaticInfoHash, NumberOfPeers, PeerId as AquaticPeerId, - Response, ResponsePeer, + AnnounceInterval, AnnounceResponse, InfoHash as AquaticInfoHash, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfPeers, + PeerId as AquaticPeerId, Response, ResponsePeer, }; use mockall::predicate::eq; use torrust_tracker_primitives::peer; use crate::core::{self, statistics}; use crate::servers::udp::connection_cookie::{into_connection_id, make}; - use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ public_tracker, sample_ipv4_socket_address, tracker_configuration, TorrentPeerBuilder, }; + use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { @@ -659,14 +667,16 @@ mod tests { let response = handle_announce(remote_addr, &request, &public_tracker()).await.unwrap(); - let empty_peer_vector: Vec> = vec![]; + let empty_peer_vector: Vec> = vec![]; assert_eq!( response, Response::from(AnnounceResponse { - transaction_id: request.transaction_id, - announce_interval: AnnounceInterval(120i32), - leechers: NumberOfPeers(0i32), - seeders: NumberOfPeers(1i32), + fixed: AnnounceResponseFixedData { + transaction_id: request.transaction_id, + announce_interval: AnnounceInterval(120i32.into()), + leechers: NumberOfPeers(0i32.into()), + seeders: NumberOfPeers(1i32.into()), + }, peers: empty_peer_vector }) ); @@ -739,7 +749,7 @@ mod tests { let response = announce_a_new_peer_using_ipv4(tracker.clone()).await; // The response should not contain the peer using IPV6 - let peers: Option>> = match response { + let peers: Option>> = match response { Response::AnnounceIpv6(announce_response) => Some(announce_response.peers), _ => None, }; @@ -820,23 +830,23 @@ mod tests { mod using_ipv6 { use std::future; - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::{ - AnnounceInterval, AnnounceResponse, InfoHash as AquaticInfoHash, NumberOfPeers, PeerId as AquaticPeerId, - Response, ResponsePeer, + AnnounceInterval, AnnounceResponse, InfoHash as AquaticInfoHash, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfPeers, + PeerId as AquaticPeerId, Response, ResponsePeer, }; use mockall::predicate::eq; use torrust_tracker_primitives::peer; use crate::core::{self, statistics}; use crate::servers::udp::connection_cookie::{into_connection_id, make}; - use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ public_tracker, sample_ipv6_remote_addr, tracker_configuration, TorrentPeerBuilder, }; + use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { @@ -883,14 +893,16 @@ mod tests { let response = handle_announce(remote_addr, &request, &public_tracker()).await.unwrap(); - let empty_peer_vector: Vec> = vec![]; + let empty_peer_vector: Vec> = vec![]; assert_eq!( response, Response::from(AnnounceResponse { - transaction_id: request.transaction_id, - announce_interval: AnnounceInterval(120i32), - leechers: NumberOfPeers(0i32), - seeders: NumberOfPeers(1i32), + fixed: AnnounceResponseFixedData { + transaction_id: request.transaction_id, + announce_interval: AnnounceInterval(120i32.into()), + leechers: NumberOfPeers(0i32.into()), + seeders: NumberOfPeers(1i32.into()), + }, peers: empty_peer_vector }) ); @@ -966,7 +978,7 @@ mod tests { let response = announce_a_new_peer_using_ipv6(tracker.clone()).await; // The response should not contain the peer using IPV4 - let peers: Option>> = match response { + let peers: Option>> = match response { Response::AnnounceIpv4(announce_response) => Some(announce_response.peers), _ => None, }; @@ -1074,9 +1086,9 @@ mod tests { fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { TorrentScrapeStatistics { - seeders: NumberOfPeers(0), - completed: NumberOfDownloads(0), - leechers: NumberOfPeers(0), + seeders: NumberOfPeers(0.into()), + completed: NumberOfDownloads(0.into()), + leechers: NumberOfPeers(0.into()), } } @@ -1089,7 +1101,7 @@ mod tests { let request = ScrapeRequest { connection_id: into_connection_id(&make(&remote_addr)), - transaction_id: TransactionId(0i32), + transaction_id: TransactionId(0i32.into()), info_hashes, }; @@ -1123,7 +1135,7 @@ mod tests { ScrapeRequest { connection_id: into_connection_id(&make(remote_addr)), - transaction_id: TransactionId(0i32), + transaction_id: TransactionId::new(0i32), info_hashes, } } @@ -1159,9 +1171,9 @@ mod tests { let torrent_stats = match_scrape_response(add_a_sample_seeder_and_scrape(tracker.clone()).await); let expected_torrent_stats = vec![TorrentScrapeStatistics { - seeders: NumberOfPeers(1), - completed: NumberOfDownloads(0), - leechers: NumberOfPeers(0), + seeders: NumberOfPeers(1.into()), + completed: NumberOfDownloads(0.into()), + leechers: NumberOfPeers(0.into()), }]; assert_eq!(torrent_stats.unwrap().torrent_stats, expected_torrent_stats); @@ -1232,9 +1244,9 @@ mod tests { let torrent_stats = match_scrape_response(handle_scrape(remote_addr, &request, &tracker).await.unwrap()).unwrap(); let expected_torrent_stats = vec![TorrentScrapeStatistics { - seeders: NumberOfPeers(1), - completed: NumberOfDownloads(0), - leechers: NumberOfPeers(0), + seeders: NumberOfPeers(1.into()), + completed: NumberOfDownloads(0.into()), + leechers: NumberOfPeers(0.into()), }]; assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); @@ -1265,7 +1277,7 @@ mod tests { ScrapeRequest { connection_id: into_connection_id(&make(remote_addr)), - transaction_id: TransactionId(0i32), + transaction_id: TransactionId(0i32.into()), info_hashes, } } diff --git a/src/servers/udp/peer_builder.rs b/src/servers/udp/peer_builder.rs index f7eb935a0..104f42a73 100644 --- a/src/servers/udp/peer_builder.rs +++ b/src/servers/udp/peer_builder.rs @@ -18,13 +18,20 @@ use crate::CurrentClock; /// request. #[must_use] pub fn from_request(announce_wrapper: &AnnounceWrapper, peer_ip: &IpAddr) -> peer::Peer { + let announce_event = match aquatic_udp_protocol::AnnounceEvent::from(announce_wrapper.announce_request.event) { + aquatic_udp_protocol::AnnounceEvent::Started => AnnounceEvent::Started, + aquatic_udp_protocol::AnnounceEvent::Stopped => AnnounceEvent::Stopped, + aquatic_udp_protocol::AnnounceEvent::Completed => AnnounceEvent::Completed, + aquatic_udp_protocol::AnnounceEvent::None => AnnounceEvent::None, + }; + peer::Peer { peer_id: peer::Id(announce_wrapper.announce_request.peer_id.0), - peer_addr: SocketAddr::new(*peer_ip, announce_wrapper.announce_request.port.0), + peer_addr: SocketAddr::new(*peer_ip, announce_wrapper.announce_request.port.0.into()), updated: CurrentClock::now(), - uploaded: NumberOfBytes(announce_wrapper.announce_request.bytes_uploaded.0), - downloaded: NumberOfBytes(announce_wrapper.announce_request.bytes_downloaded.0), - left: NumberOfBytes(announce_wrapper.announce_request.bytes_left.0), - event: AnnounceEvent::from_i32(announce_wrapper.announce_request.event.to_i32()), + uploaded: NumberOfBytes(announce_wrapper.announce_request.bytes_uploaded.0.into()), + downloaded: NumberOfBytes(announce_wrapper.announce_request.bytes_downloaded.0.into()), + left: NumberOfBytes(announce_wrapper.announce_request.bytes_left.0.into()), + event: announce_event, } } diff --git a/src/servers/udp/request.rs b/src/servers/udp/request.rs index e172e03b1..f95fec07a 100644 --- a/src/servers/udp/request.rs +++ b/src/servers/udp/request.rs @@ -21,7 +21,7 @@ impl AnnounceWrapper { #[must_use] pub fn new(announce_request: &AnnounceRequest) -> Self { AnnounceWrapper { - announce_request: announce_request.clone(), + announce_request: *announce_request, info_hash: InfoHash(announce_request.info_hash.0), } } diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 7086b6ab7..dc1bccde3 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -346,7 +346,7 @@ impl Udp { let buffer = vec![0u8; MAX_PACKET_SIZE]; let mut cursor = Cursor::new(buffer); - match response.write(&mut cursor) { + match response.write_bytes(&mut cursor) { Ok(()) => { #[allow(clippy::cast_possible_truncation)] let position = cursor.position() as usize; diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs index 9af9571bc..81209efb6 100644 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -9,6 +9,7 @@ use aquatic_udp_protocol::{ConnectRequest, Request, Response, TransactionId}; use log::debug; use tokio::net::UdpSocket; use tokio::time; +use zerocopy::network_endian::I32; use crate::shared::bit_torrent::tracker::udp::{source_address, MAX_PACKET_SIZE}; @@ -160,7 +161,7 @@ impl UdpTrackerClient { let request_buffer = vec![0u8; MAX_PACKET_SIZE]; let mut cursor = Cursor::new(request_buffer); - let request_data_result = match request.write(&mut cursor) { + let request_data_result = match request.write_bytes(&mut cursor) { Ok(()) => { #[allow(clippy::cast_possible_truncation)] let position = cursor.position() as usize; @@ -186,7 +187,7 @@ impl UdpTrackerClient { debug!(target: "UDP tracker client", "received {payload_size} bytes. Response {response_buffer:?}"); - let response = Response::from_bytes(&response_buffer[..payload_size], true)?; + let response = Response::parse_bytes(&response_buffer[..payload_size], true)?; Ok(response) } @@ -218,7 +219,7 @@ pub async fn check(binding: &SocketAddr) -> Result { match new_udp_tracker_client_connected(binding.to_string().as_str()).await { Ok(client) => { let connect_request = ConnectRequest { - transaction_id: TransactionId(123), + transaction_id: TransactionId(I32::new(123)), }; // client.send() return usize, but doesn't use here diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 56e400f84..7abd6092c 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -60,7 +60,7 @@ async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_req Err(err) => panic!("{err}"), }; - let response = Response::from_bytes(&buffer, true).unwrap(); + let response = Response::parse_bytes(&buffer, true).unwrap(); assert!(is_error_response(&response, "bad request")); @@ -85,7 +85,7 @@ mod receiving_a_connection_request { }; let connect_request = ConnectRequest { - transaction_id: TransactionId(123), + transaction_id: TransactionId::new(123), }; match client.send(connect_request.into()).await { @@ -98,7 +98,7 @@ mod receiving_a_connection_request { Err(err) => panic!("{err}"), }; - assert!(is_connect_response(&response, TransactionId(123))); + assert!(is_connect_response(&response, TransactionId::new(123))); env.stop().await; } @@ -108,8 +108,8 @@ mod receiving_an_announce_request { use std::net::Ipv4Addr; use aquatic_udp_protocol::{ - AnnounceEvent, AnnounceRequest, ConnectionId, InfoHash, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, - TransactionId, + AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectionId, InfoHash, NumberOfBytes, NumberOfPeers, PeerId, + PeerKey, Port, TransactionId, }; use torrust_tracker::shared::bit_torrent::tracker::udp::client::new_udp_tracker_client_connected; use torrust_tracker_test_helpers::configuration; @@ -127,23 +127,24 @@ mod receiving_an_announce_request { Err(err) => panic!("{err}"), }; - let connection_id = send_connection_request(TransactionId(123), &client).await; + let connection_id = send_connection_request(TransactionId::new(123), &client).await; // Send announce request let announce_request = AnnounceRequest { connection_id: ConnectionId(connection_id.0), - transaction_id: TransactionId(123i32), + action_placeholder: AnnounceActionPlaceholder::default(), + transaction_id: TransactionId::new(123i32), info_hash: InfoHash([0u8; 20]), peer_id: PeerId([255u8; 20]), - bytes_downloaded: NumberOfBytes(0i64), - bytes_uploaded: NumberOfBytes(0i64), - bytes_left: NumberOfBytes(0i64), - event: AnnounceEvent::Started, - ip_address: Some(Ipv4Addr::new(0, 0, 0, 0)), - key: PeerKey(0u32), - peers_wanted: NumberOfPeers(1i32), - port: Port(client.udp_client.socket.local_addr().unwrap().port()), + bytes_downloaded: NumberOfBytes(0i64.into()), + bytes_uploaded: NumberOfBytes(0i64.into()), + bytes_left: NumberOfBytes(0i64.into()), + event: AnnounceEvent::Started.into(), + ip_address: Ipv4Addr::new(0, 0, 0, 0).into(), + key: PeerKey::new(0i32), + peers_wanted: NumberOfPeers(1i32.into()), + port: Port(client.udp_client.socket.local_addr().unwrap().port().into()), }; match client.send(announce_request.into()).await { @@ -182,7 +183,7 @@ mod receiving_an_scrape_request { Err(err) => panic!("{err}"), }; - let connection_id = send_connection_request(TransactionId(123), &client).await; + let connection_id = send_connection_request(TransactionId::new(123), &client).await; // Send scrape request @@ -192,7 +193,7 @@ mod receiving_an_scrape_request { let scrape_request = ScrapeRequest { connection_id: ConnectionId(connection_id.0), - transaction_id: TransactionId(123i32), + transaction_id: TransactionId::new(123i32), info_hashes, }; From be51d2fa98ed83921be6828c685e1ca4b8a9382e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 May 2024 11:16:40 +0100 Subject: [PATCH 0305/1297] chore(deps): bump ringbuf from 0.3.3 to 0.4.0 --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- src/servers/udp/server.rs | 3 ++- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b7f592666..f43e85be1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3094,9 +3094,9 @@ dependencies = [ [[package]] name = "ringbuf" -version = "0.3.3" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79abed428d1fd2a128201cec72c5f6938e2da607c6f3745f769fabea399d950a" +checksum = "2542bc32f4c763f52a2eb375cb0b76c5aa5771f569af74299e84dca51d988a2f" dependencies = [ "crossbeam-utils", ] diff --git a/Cargo.toml b/Cargo.toml index 63735450e..cbfdc7697 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,7 +57,7 @@ r2d2_mysql = "24" r2d2_sqlite = { version = "0", features = ["bundled"] } rand = "0" reqwest = { version = "0", features = ["json"] } -ringbuf = "0.3.3" +ringbuf = "0" serde = { version = "1", features = ["derive"] } serde_bencode = "0" serde_bytes = "0" diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index dc1bccde3..70cf8f01d 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -24,7 +24,8 @@ use std::sync::Arc; use aquatic_udp_protocol::Response; use derive_more::Constructor; use log::{debug, error, info, trace}; -use ringbuf::{Rb, StaticRb}; +use ringbuf::traits::{Consumer, Observer, RingBuffer}; +use ringbuf::StaticRb; use tokio::net::UdpSocket; use tokio::sync::oneshot; use tokio::task::{AbortHandle, JoinHandle}; From 62d4a209b048f120f5969fcd3fb7fb100b87f0a2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 May 2024 11:44:40 +0100 Subject: [PATCH 0306/1297] chore(deps): update dependencies ```output cargo update Updating crates.io index Locking 14 packages to latest compatible versions Updating anyhow v1.0.82 -> v1.0.83 Updating cc v1.0.96 -> v1.0.97 Updating getrandom v0.2.14 -> v0.2.15 Updating num-bigint v0.4.4 -> v0.4.5 Updating proc-macro2 v1.0.81 -> v1.0.82 Updating rustls-pki-types v1.5.0 -> v1.6.0 Updating rustversion v1.0.15 -> v1.0.16 Updating ryu v1.0.17 -> v1.0.18 Updating semver v1.0.22 -> v1.0.23 Updating syn v2.0.60 -> v2.0.61 Updating thiserror v1.0.59 -> v1.0.60 Updating thiserror-impl v1.0.59 -> v1.0.60 Updating zerocopy v0.7.33 -> v0.7.34 Updating zerocopy-derive v0.7.33 -> v0.7.34 ``` --- Cargo.lock | 113 ++++++++++++++++++++++++++--------------------------- 1 file changed, 56 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f43e85be1..d4282c158 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -142,9 +142,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.82" +version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519" +checksum = "25bdb32cbbdce2b519a9cd7df3a678443100e265d5e25ca763b7572a5104f5f3" [[package]] name = "aquatic_peer_id" @@ -363,7 +363,7 @@ checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -477,7 +477,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -564,7 +564,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -637,7 +637,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", "syn_derive", ] @@ -725,9 +725,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.96" +version = "1.0.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "065a29261d53ba54260972629f9ca6bffa69bac13cd1fed61420f7fa68b9f8bd" +checksum = "099a5357d84c4c61eb35fc8eafa9a79a902c2f76911e5747ced4e032edd8d9b4" dependencies = [ "jobserver", "libc", @@ -837,7 +837,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -1113,7 +1113,7 @@ dependencies = [ "proc-macro2", "quote", "strsim 0.10.0", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -1124,7 +1124,7 @@ checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" dependencies = [ "darling_core", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -1171,7 +1171,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -1416,7 +1416,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -1428,7 +1428,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -1440,7 +1440,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -1533,7 +1533,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -1584,9 +1584,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.14" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94b22e06ecb0110981051723910cbf0b5f5e09a2062dd7663334ee79a9d1286c" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", @@ -2240,7 +2240,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -2291,7 +2291,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", "termcolor", "thiserror", ] @@ -2404,11 +2404,10 @@ checksum = "e9e591e719385e6ebaeb5ce5d3887f7d5676fceca6411d1925ccc95745f3d6f7" [[package]] name = "num-bigint" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0" +checksum = "c165a9ab64cf766f73521c0dd2cfdff64f488b8f0b3e621face3462d3db536d7" dependencies = [ - "autocfg", "num-integer", "num-traits", ] @@ -2491,7 +2490,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -2604,7 +2603,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -2673,7 +2672,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -2847,9 +2846,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.81" +version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba" +checksum = "8ad3d49ab951a01fbaafe34f2ec74122942fe18a3f9814c3268f1bb72042131b" dependencies = [ "unicode-ident", ] @@ -3167,7 +3166,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.60", + "syn 2.0.61", "unicode-ident", ] @@ -3283,9 +3282,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.5.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "beb461507cee2c2ff151784c52762cf4d9ff6a61f3e80968600ed24fa837fa54" +checksum = "51f344d206c5e1b010eec27349b815a4805f70a778895959d70b74b9b529b30a" [[package]] name = "rustls-webpki" @@ -3299,15 +3298,15 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.15" +version = "1.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80af6f9131f277a45a3fba6ce8e2258037bb0477a67e610d3c1fe046ab31de47" +checksum = "092474d1a01ea8278f69e6a358998405fae5b8b963ddaeb2b0b04a128bf1dfb0" [[package]] name = "ryu" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1" +checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" [[package]] name = "same-file" @@ -3389,9 +3388,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d43fe69e652f3df9bdc2b85b2854a0825b86e4fb76bc44d945137d053639ca" +checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" @@ -3429,7 +3428,7 @@ checksum = "856f046b9400cee3c8c94ed572ecdb752444c24528c035cd35882aad6f492bcb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -3475,7 +3474,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -3526,7 +3525,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -3660,9 +3659,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.60" +version = "2.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3" +checksum = "c993ed8ccba56ae856363b1845da7266a7cb78e1d146c8a32d54b45a8b831fc9" dependencies = [ "proc-macro2", "quote", @@ -3678,7 +3677,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -3766,22 +3765,22 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.59" +version = "1.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0126ad08bff79f29fc3ae6a55cc72352056dfff61e3ff8bb7129476d44b23aa" +checksum = "579e9083ca58dd9dcf91a9923bb9054071b9ebbd800b342194c9feb0ee89fc18" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.59" +version = "1.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1cd413b5d558b4c5bf3680e324a6fa5014e7b7c067a51e69dbdf47eb7148b66" +checksum = "e2470041c06ec3ac1ab38d0356a6119054dedaea53e12fbefc0de730a1c08524" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -3875,7 +3874,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -4182,7 +4181,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -4353,7 +4352,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", "wasm-bindgen-shared", ] @@ -4387,7 +4386,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4635,9 +4634,9 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.7.33" +version = "0.7.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "087eca3c1eaf8c47b94d02790dd086cd594b912d2043d4de4bfdd466b3befb7c" +checksum = "ae87e3fcd617500e5d106f0380cf7b77f3c6092aae37191433159dda23cfb087" dependencies = [ "byteorder", "zerocopy-derive", @@ -4645,13 +4644,13 @@ dependencies = [ [[package]] name = "zerocopy-derive" -version = "0.7.33" +version = "0.7.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f4b6c273f496d8fd4eaf18853e6b448760225dc030ff2c485a786859aea6393" +checksum = "15e934569e47891f7d9411f1a451d947a60e000ab3bd24fbb970f000387d1b3b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] From e3143f779c40e590cfbdcfd34ee3d972f94ca1b3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 May 2024 12:25:48 +0100 Subject: [PATCH 0307/1297] feat: log aborted UDP requests This will add a warning to the lofs when a UDP request is aborted. --- src/servers/udp/server.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 70cf8f01d..fc2d02a59 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -291,7 +291,14 @@ impl Udp { if !h.is_finished() { // the task is still running, lets yield and give it a chance to flush. tokio::task::yield_now().await; + h.abort(); + + let server_socket_addr = socket.local_addr().expect("Could not get local_addr for socket."); + + tracing::span!( + target: "UDP TRACKER", + tracing::Level::WARN, "request-aborted", server_socket_addr = %server_socket_addr); } } } From 3dee03ea0d6b911e58a51cf5fded5d4a0efc9f6d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 May 2024 17:48:09 +0100 Subject: [PATCH 0308/1297] docs: udpate installation docs --- README.md | 4 ++++ src/lib.rs | 70 ++++++++++++++++++++++++++++++++++++++---------------- 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index ea5078b19..8431c00e4 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,10 @@ The following services are provided by the default configuration: ## Documentation +You can read the [latest documentation][docs] from . + +Some specific sections: + - [Management API (Version 1)][API] - [Tracker (HTTP/TLS)][HTTP] - [Tracker (UDP)][UDP] diff --git a/src/lib.rs b/src/lib.rs index 064f50eb6..22bc133e1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -109,29 +109,47 @@ //! With the default configuration you will need to create the `storage` directory: //! //! ```text -//! storage/ -//! ├── database -//! │   └── data.db -//! └── tls -//! ├── localhost.crt -//! └── localhost.key +//! ./storage/ +//! └── tracker +//! ├── etc +//! ├── lib +//! │   ├── database +//! │   │   └── sqlite3.db +//! │   └── tls +//! └── log //! ``` //! //! The default configuration expects a directory `./storage/tracker/lib/database` to be writable by the tracker process. //! -//! By default the tracker uses `SQLite` and the database file name `data.db`. +//! By default the tracker uses `SQLite` and the database file name `sqlite3.db`. //! //! You only need the `tls` directory in case you are setting up SSL for the HTTP tracker or the tracker API. //! Visit [`HTTP`](crate::servers::http) or [`API`](crate::servers::apis) if you want to know how you can use HTTPS. //! //! ## Install from sources //! +//! First, you need to create a folder to clone the repository. +//! +//! ```text +//! cd /tmp +//! mkdir torrust +//! ``` +//! //! ```text //! git clone https://github.com/torrust/torrust-tracker.git \ //! && cd torrust-tracker \ //! && cargo build --release \ +//! && mkdir -p ./storage/tracker/etc \ //! && mkdir -p ./storage/tracker/lib/database \ -//! && mkdir -p ./storage/tracker/lib/tls +//! && mkdir -p ./storage/tracker/lib/tls \ +//! && mkdir -p ./storage/tracker/log +//! ``` +//! +//! To run the tracker we will have to use the command "cargo run" this will +//! compile and after being compiled it will start running the tracker. +//! +//! ```text +//! cargo run //! ``` //! //! ## Run with docker @@ -141,9 +159,10 @@ //! //! # Configuration //! -//! In order to run the tracker you need to provide the configuration. If you run the tracker without providing the configuration, -//! the tracker will generate the default configuration the first time you run it. It will generate a `tracker.toml` file with -//! in the root directory. +//! In order to run the tracker you need to provide the configuration. If you +//! run the tracker without providing the configuration, the tracker will +//! generate the default configuration the first time you run it. It will +//! generate a `tracker.toml` file with in the root directory. //! //! The default configuration is: //! @@ -187,26 +206,37 @@ //! bind_address = "127.0.0.1:1313" //!``` //! -//! The default configuration includes one disabled UDP server, one disabled HTTP server and the enabled API. +//! The default configuration includes one disabled UDP server, one disabled +//! HTTP server and the enabled API. //! -//! For more information about each service and options you can visit the documentation for the [torrust-tracker-configuration crate](https://docs.rs/torrust-tracker-configuration). +//! For more information about each service and options you can visit the +//! documentation for the [torrust-tracker-configuration crate](https://docs.rs/torrust-tracker-configuration). //! -//! Alternatively to the `tracker.toml` file you can use one environment variable `TORRUST_TRACKER_CONFIG` to pass the configuration to the tracker: +//! Alternatively to the `tracker.toml` file you can use one environment +//! variable `TORRUST_TRACKER_CONFIG` to pass the configuration to the tracker: //! //! ```text -//! TORRUST_TRACKER_CONFIG=$(cat tracker.toml) -//! cargo run +//! TORRUST_TRACKER_CONFIG=$(cat ./share/default/config/tracker.development.sqlite3.toml) ./target/release/torrust-tracker //! ``` //! -//! In the previous example you are just setting the env var with the contents of the `tracker.toml` file. +//! In the previous example you are just setting the env var with the contents +//! of the `tracker.toml` file. +//! +//! The env var contains the same data as the `tracker.toml`. It's particularly +//! useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/tree/develop/docker). +//! +//! > NOTICE: The `TORRUST_TRACKER_CONFIG` env var has priority over the `tracker.toml` file. //! -//! The env var contains the same data as the `tracker.toml`. It's particularly useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/tree/develop/docker). +//! By default, if you don’t specify any `tracker.toml` file, the application +//! will use `./share/default/config/tracker.development.sqlite3.toml`. //! -//! > NOTE: The `TORRUST_TRACKER_CONFIG` env var has priority over the `tracker.toml` file. +//! > IMPORTANT: Every time you change the configuration you need to restart the +//! service. //! //! # Usage //! -//! Running the tracker with the default configuration and enabling the UDP and HTTP trackers will expose the services on these URLs: +//! Running the tracker with the default configuration and enabling the UDP and +//! HTTP trackers will expose the services on these URLs: //! //! - REST API: //! - UDP tracker: From cddc4dee7c8de35b543b8aeefb741f8882ccb27e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 May 2024 18:22:01 +0100 Subject: [PATCH 0309/1297] chore(deps): bump rustc-demangle v0.1.23 -> v0.1.24 --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d4282c158..bd0e36c3a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3212,9 +3212,9 @@ dependencies = [ [[package]] name = "rustc-demangle" -version = "0.1.23" +version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" +checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" [[package]] name = "rustc-hash" From 6f02aeb7e97c1d990df916514b0737f8b5e67f26 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 May 2024 12:15:41 +0100 Subject: [PATCH 0310/1297] docs: fix profiling docs - Remove unnecessary file - Fix filename typo --- ... => flamegraph_generated_without_sudo.svg} | 0 docs/profiling.md | 2 +- flamegraph_generated_withput_sudo.svg | 491 ------------------ 3 files changed, 1 insertion(+), 492 deletions(-) rename docs/media/{flamegraph_generated_withput_sudo.svg => flamegraph_generated_without_sudo.svg} (100%) delete mode 100644 flamegraph_generated_withput_sudo.svg diff --git a/docs/media/flamegraph_generated_withput_sudo.svg b/docs/media/flamegraph_generated_without_sudo.svg similarity index 100% rename from docs/media/flamegraph_generated_withput_sudo.svg rename to docs/media/flamegraph_generated_without_sudo.svg diff --git a/docs/profiling.md b/docs/profiling.md index 26e5b786e..406560f3c 100644 --- a/docs/profiling.md +++ b/docs/profiling.md @@ -79,7 +79,7 @@ Loading configuration file: `./share/default/config/tracker.udp.benchmarking.tom And some bars in the graph will have the `unknown` label. -![flamegraph generated without sudo](./media/flamegraph_generated_withput_sudo.svg) +![flamegraph generated without sudo](./media/flamegraph_generated_without_sudo.svg) ## Using valgrind and kcachegrind diff --git a/flamegraph_generated_withput_sudo.svg b/flamegraph_generated_withput_sudo.svg deleted file mode 100644 index 84c00ffe3..000000000 --- a/flamegraph_generated_withput_sudo.svg +++ /dev/null @@ -1,491 +0,0 @@ -Flame Graph Reset ZoomSearch [unknown] (188 samples, 0.14%)[unknown] (187 samples, 0.14%)[unknown] (186 samples, 0.14%)[unknown] (178 samples, 0.14%)[unknown] (172 samples, 0.13%)[unknown] (158 samples, 0.12%)[unknown] (158 samples, 0.12%)[unknown] (125 samples, 0.10%)[unknown] (102 samples, 0.08%)[unknown] (93 samples, 0.07%)[unknown] (92 samples, 0.07%)[unknown] (41 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (29 samples, 0.02%)[unknown] (25 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (15 samples, 0.01%)__GI___mmap64 (18 samples, 0.01%)__GI___mmap64 (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (17 samples, 0.01%)profiling (214 samples, 0.16%)clone3 (22 samples, 0.02%)start_thread (22 samples, 0.02%)std::sys::pal::unix::thread::Thread::new::thread_start (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::Handler::new (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::imp::make_handler (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::imp::get_stack (19 samples, 0.01%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (30 samples, 0.02%)[[vdso]] (93 samples, 0.07%)<torrust_tracker::shared::crypto::ephemeral_instance_keys::RANDOM_SEED as core::ops::deref::Deref>::deref::__stability::LAZY (143 samples, 0.11%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (31 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<BorrowType,K,V>::init_front (21 samples, 0.02%)[[vdso]] (91 samples, 0.07%)__GI___clock_gettime (14 samples, 0.01%)_int_malloc (53 samples, 0.04%)epoll_wait (254 samples, 0.19%)tokio::runtime::context::with_scheduler (28 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.01%)tokio::runtime::context::with_scheduler::{{closure}} (14 samples, 0.01%)core::option::Option<T>::map (17 samples, 0.01%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (17 samples, 0.01%)mio::poll::Poll::poll (27 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select (27 samples, 0.02%)tokio::runtime::io::driver::Driver::turn (54 samples, 0.04%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (26 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (17 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (71 samples, 0.05%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (65 samples, 0.05%)core::sync::atomic::AtomicUsize::fetch_add (65 samples, 0.05%)core::sync::atomic::atomic_add (65 samples, 0.05%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (31 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark_condvar (18 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (49 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (33 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (93 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Parker::park (75 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Inner::park (75 samples, 0.06%)core::cell::RefCell<T>::borrow_mut (18 samples, 0.01%)core::cell::RefCell<T>::try_borrow_mut (18 samples, 0.01%)core::cell::BorrowRefMut::new (18 samples, 0.01%)tokio::runtime::coop::budget (26 samples, 0.02%)tokio::runtime::coop::with_budget (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (96 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (27 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (18 samples, 0.01%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (35 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (14 samples, 0.01%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (90 samples, 0.07%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (90 samples, 0.07%)core::slice::<impl [T]>::contains (220 samples, 0.17%)<T as core::slice::cmp::SliceContains>::slice_contains (220 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (220 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (54 samples, 0.04%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (54 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (240 samples, 0.18%)tokio::runtime::scheduler::multi_thread::idle::Idle::unpark_worker_by_id (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (265 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Context::park (284 samples, 0.22%)core::option::Option<T>::or_else (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (40 samples, 0.03%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (17 samples, 0.01%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (17 samples, 0.01%)core::num::<impl u32>::wrapping_add (17 samples, 0.01%)core::sync::atomic::AtomicU64::compare_exchange (26 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (129 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (128 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (119 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::pack (39 samples, 0.03%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run (613 samples, 0.47%)tokio::runtime::context::runtime::enter_runtime (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (613 samples, 0.47%)tokio::runtime::context::set_scheduler (613 samples, 0.47%)std::thread::local::LocalKey<T>::with (613 samples, 0.47%)std::thread::local::LocalKey<T>::try_with (613 samples, 0.47%)tokio::runtime::context::set_scheduler::{{closure}} (613 samples, 0.47%)tokio::runtime::context::scoped::Scoped<T>::set (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::Context::run (613 samples, 0.47%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (777 samples, 0.59%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (776 samples, 0.59%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (16 samples, 0.01%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (16 samples, 0.01%)tokio::runtime::context::set_current_task_id (16 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (16 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (20 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (20 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::poll (835 samples, 0.64%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (56 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage (46 samples, 0.04%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (897 samples, 0.68%)tokio::runtime::task::harness::poll_future::{{closure}} (897 samples, 0.68%)tokio::runtime::task::core::Core<T,S>::store_output (62 samples, 0.05%)tokio::runtime::task::harness::poll_future (930 samples, 0.71%)std::panic::catch_unwind (927 samples, 0.71%)std::panicking::try (927 samples, 0.71%)std::panicking::try::do_call (925 samples, 0.70%)core::mem::manually_drop::ManuallyDrop<T>::take (28 samples, 0.02%)core::ptr::read (28 samples, 0.02%)tokio::runtime::task::raw::poll (938 samples, 0.71%)tokio::runtime::task::harness::Harness<T,S>::poll (934 samples, 0.71%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (934 samples, 0.71%)core::array::<impl core::default::Default for [T: 32]>::default (26 samples, 0.02%)tokio::runtime::time::Inner::lock (16 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (15 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::time::wheel::Wheel::poll (25 samples, 0.02%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (98 samples, 0.07%)tokio::runtime::time::Driver::park_internal (51 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (15 samples, 0.01%)<F as core::future::into_future::IntoFuture>::into_future (16 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (24 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (46 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (131 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (24 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (14 samples, 0.01%)core::sync::atomic::AtomicU32::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (39 samples, 0.03%)std::sync::rwlock::RwLock<T>::read (34 samples, 0.03%)std::sys::sync::rwlock::futex::RwLock::read (32 samples, 0.02%)[[heap]] (2,361 samples, 1.80%)[..[[vdso]] (313 samples, 0.24%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (41 samples, 0.03%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (16 samples, 0.01%)<alloc::string::String as core::fmt::Write>::write_str (67 samples, 0.05%)alloc::string::String::push_str (18 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (18 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (18 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (18 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (36 samples, 0.03%)core::num::<impl u64>::rotate_left (28 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (60 samples, 0.05%)core::num::<impl u64>::wrapping_add (14 samples, 0.01%)core::hash::sip::u8to64_le (60 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (184 samples, 0.14%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (15 samples, 0.01%)tokio::runtime::context::CONTEXT::__getit (19 samples, 0.01%)core::cell::Cell<T>::get (17 samples, 0.01%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (26 samples, 0.02%)core::ops::function::FnMut::call_mut (21 samples, 0.02%)tokio::runtime::coop::poll_proceed (21 samples, 0.02%)tokio::runtime::context::budget (21 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (21 samples, 0.02%)[unknown] (18 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (195 samples, 0.15%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (14 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (14 samples, 0.01%)core::result::Result<T,E>::is_err (18 samples, 0.01%)core::result::Result<T,E>::is_ok (18 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (46 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (39 samples, 0.03%)core::sync::atomic::AtomicU32::compare_exchange (19 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (19 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (245 samples, 0.19%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (26 samples, 0.02%)[[vdso]] (748 samples, 0.57%)[profiling] (34 samples, 0.03%)core::fmt::write (31 samples, 0.02%)__GI___clock_gettime (29 samples, 0.02%)__GI___libc_free (131 samples, 0.10%)arena_for_chunk (20 samples, 0.02%)arena_for_chunk (19 samples, 0.01%)heap_for_ptr (19 samples, 0.01%)heap_max_size (14 samples, 0.01%)__GI___libc_malloc (114 samples, 0.09%)__GI___libc_realloc (15 samples, 0.01%)__GI___lll_lock_wake_private (22 samples, 0.02%)__GI___pthread_disable_asynccancel (66 samples, 0.05%)__GI_getsockname (249 samples, 0.19%)__libc_calloc (15 samples, 0.01%)__libc_recvfrom (23 samples, 0.02%)__libc_sendto (130 samples, 0.10%)__memcmp_evex_movbe (451 samples, 0.34%)__memcpy_avx512_unaligned_erms (426 samples, 0.32%)__memset_avx512_unaligned_erms (215 samples, 0.16%)__posix_memalign (17 samples, 0.01%)_int_free (418 samples, 0.32%)tcache_put (24 samples, 0.02%)_int_malloc (385 samples, 0.29%)_int_memalign (31 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (26 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (15 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (15 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (15 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (54 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::grow_one (15 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (96 samples, 0.07%)alloc::raw_vec::RawVec<T,A>::grow_amortized (66 samples, 0.05%)core::num::<impl usize>::checked_add (18 samples, 0.01%)core::num::<impl usize>::overflowing_add (18 samples, 0.01%)alloc::raw_vec::finish_grow (74 samples, 0.06%)alloc::sync::Arc<T,A>::drop_slow (16 samples, 0.01%)core::mem::drop (14 samples, 0.01%)core::fmt::Formatter::pad_integral (14 samples, 0.01%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (93 samples, 0.07%)core::ptr::drop_in_place<tokio::net::udp::UdpSocket::send_to<&core::net::socket_addr::SocketAddr>::{{closure}}> (23 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (188 samples, 0.14%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_announce::{{closure}}> (30 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_connect::{{closure}}> (22 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_packet::{{closure}}> (20 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}}> (19 samples, 0.01%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::send_response::{{closure}}> (22 samples, 0.02%)malloc_consolidate (24 samples, 0.02%)core::core_arch::x86::avx2::_mm256_or_si256 (15 samples, 0.01%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (17 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (17 samples, 0.01%)rand_chacha::guts::round (66 samples, 0.05%)rand_chacha::guts::refill_wide::impl_avx2 (99 samples, 0.08%)rand_chacha::guts::refill_wide::fn_impl (98 samples, 0.07%)rand_chacha::guts::refill_wide_impl (98 samples, 0.07%)std::io::error::Error::kind (14 samples, 0.01%)[unknown] (42 samples, 0.03%)[unknown] (14 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (490 samples, 0.37%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (211 samples, 0.16%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (84 samples, 0.06%)tokio::runtime::task::core::Header::get_owner_id (18 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (18 samples, 0.01%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (20 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::remove (19 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (31 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (29 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (108 samples, 0.08%)tokio::runtime::task::core::TaskIdGuard::enter (14 samples, 0.01%)tokio::runtime::context::set_current_task_id (14 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::complete (21 samples, 0.02%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (32 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (54 samples, 0.04%)tokio::runtime::task::raw::drop_abort_handle (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (17 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (22 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (22 samples, 0.02%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (79 samples, 0.06%)core::slice::<impl [T]>::contains (178 samples, 0.14%)<T as core::slice::cmp::SliceContains>::slice_contains (178 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (178 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (40 samples, 0.03%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (40 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (216 samples, 0.16%)tokio::loom::std::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (219 samples, 0.17%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (29 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (29 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (54 samples, 0.04%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (18 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (18 samples, 0.01%)core::sync::atomic::AtomicU32::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (113 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (51 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (31 samples, 0.02%)core::sync::atomic::AtomicU64::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (447 samples, 0.34%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (174 samples, 0.13%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (19 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (489 samples, 0.37%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (489 samples, 0.37%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run (484 samples, 0.37%)tokio::runtime::context::runtime::enter_runtime (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (484 samples, 0.37%)tokio::runtime::context::set_scheduler (484 samples, 0.37%)std::thread::local::LocalKey<T>::with (484 samples, 0.37%)std::thread::local::LocalKey<T>::try_with (484 samples, 0.37%)tokio::runtime::context::set_scheduler::{{closure}} (484 samples, 0.37%)tokio::runtime::context::scoped::Scoped<T>::set (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Context::run (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (24 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (20 samples, 0.02%)tokio::runtime::task::raw::poll (515 samples, 0.39%)tokio::runtime::task::harness::Harness<T,S>::poll (493 samples, 0.38%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (493 samples, 0.38%)tokio::runtime::task::harness::poll_future (493 samples, 0.38%)std::panic::catch_unwind (493 samples, 0.38%)std::panicking::try (493 samples, 0.38%)std::panicking::try::do_call (493 samples, 0.38%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (493 samples, 0.38%)tokio::runtime::task::harness::poll_future::{{closure}} (493 samples, 0.38%)tokio::runtime::task::core::Core<T,S>::poll (493 samples, 0.38%)tokio::runtime::time::wheel::Wheel::next_expiration (16 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (27 samples, 0.02%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (15 samples, 0.01%)torrust_tracker::core::Tracker::send_stats_event::{{closure}} (44 samples, 0.03%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (15 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::d_rounds (29 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (74 samples, 0.06%)torrust_tracker::servers::udp::peer_builder::from_request (17 samples, 0.01%)torrust_tracker::servers::udp::request::AnnounceWrapper::new (51 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (54 samples, 0.04%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (58 samples, 0.04%)torrust_tracker::core::Tracker::announce::{{closure}} (70 samples, 0.05%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (113 samples, 0.09%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (175 samples, 0.13%)<T as alloc::string::ToString>::to_string (38 samples, 0.03%)core::option::Option<T>::expect (56 samples, 0.04%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (18 samples, 0.01%)<T as alloc::string::ToString>::to_string (18 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (180 samples, 0.14%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (468 samples, 0.36%)torrust_tracker::servers::udp::logging::log_response (38 samples, 0.03%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (669 samples, 0.51%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (152 samples, 0.12%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (147 samples, 0.11%)tokio::net::udp::UdpSocket::send_to::{{closure}} (138 samples, 0.11%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (119 samples, 0.09%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (75 samples, 0.06%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (39 samples, 0.03%)mio::net::udp::UdpSocket::send_to (39 samples, 0.03%)mio::io_source::IoSource<T>::do_io (39 samples, 0.03%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (39 samples, 0.03%)mio::net::udp::UdpSocket::send_to::{{closure}} (39 samples, 0.03%)std::net::udp::UdpSocket::send_to (39 samples, 0.03%)std::sys_common::net::UdpSocket::send_to (39 samples, 0.03%)std::sys::pal::unix::cvt (39 samples, 0.03%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (39 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_stats (15 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (14 samples, 0.01%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count::to_usize::{{closure}} (33 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats::{{closure}} (33 samples, 0.03%)torrust_tracker_primitives::peer::Peer::is_seeder (33 samples, 0.03%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count (75 samples, 0.06%)core::iter::traits::iterator::Iterator::sum (75 samples, 0.06%)<usize as core::iter::traits::accum::Sum>::sum (75 samples, 0.06%)<core::iter::adapters::map::Map<I,F> as core::iter::traits::iterator::Iterator>::fold (75 samples, 0.06%)core::iter::traits::iterator::Iterator::fold (75 samples, 0.06%)core::iter::adapters::map::map_fold::{{closure}} (34 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (104 samples, 0.08%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (24 samples, 0.02%)core::mem::drop (15 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (15 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (15 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (15 samples, 0.01%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (215 samples, 0.16%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (198 samples, 0.15%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (89 samples, 0.07%)core::option::Option<T>::is_some_and (32 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (31 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (30 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (30 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (26 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.03%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (58 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (58 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (58 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (58 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (58 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (20 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (238 samples, 0.18%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (236 samples, 0.18%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (208 samples, 0.16%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (208 samples, 0.16%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (282 samples, 0.21%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (67 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (53 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (53 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (22 samples, 0.02%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (22 samples, 0.02%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (22 samples, 0.02%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (22 samples, 0.02%)<u8 as core::slice::cmp::SliceOrd>::compare (22 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (18 samples, 0.01%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (23 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (23 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (43 samples, 0.03%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (43 samples, 0.03%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (43 samples, 0.03%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (43 samples, 0.03%)<u8 as core::slice::cmp::SliceOrd>::compare (43 samples, 0.03%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (17 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (151 samples, 0.12%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (145 samples, 0.11%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (137 samples, 0.10%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (137 samples, 0.10%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (266 samples, 0.20%)core::sync::atomic::AtomicU32::load (27 samples, 0.02%)core::sync::atomic::atomic_load (27 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (38 samples, 0.03%)std::sync::rwlock::RwLock<T>::read (37 samples, 0.03%)std::sys::sync::rwlock::futex::RwLock::read (36 samples, 0.03%)tracing::span::Span::log (16 samples, 0.01%)tracing::span::Span::record_all (70 samples, 0.05%)unlink_chunk (139 samples, 0.11%)rand::rng::Rng::gen (30 samples, 0.02%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (30 samples, 0.02%)rand::rng::Rng::gen (30 samples, 0.02%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (30 samples, 0.02%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (30 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (30 samples, 0.02%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (30 samples, 0.02%)rand_core::block::BlockRng<R>::generate_and_set (28 samples, 0.02%)[anon] (8,759 samples, 6.67%)[anon]uuid::v4::<impl uuid::Uuid>::new_v4 (32 samples, 0.02%)uuid::rng::bytes (32 samples, 0.02%)rand::random (32 samples, 0.02%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (15 samples, 0.01%)_int_free (338 samples, 0.26%)tcache_put (18 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (22 samples, 0.02%)hashbrown::raw::h2 (14 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (23 samples, 0.02%)hashbrown::raw::RawTableInner::find_or_find_insert_slot_inner (17 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (25 samples, 0.02%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (15 samples, 0.01%)[profiling] (545 samples, 0.42%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (32 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (22 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (16 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (30 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (28 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (83 samples, 0.06%)alloc::string::String::push_str (57 samples, 0.04%)alloc::vec::Vec<T,A>::extend_from_slice (57 samples, 0.04%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (57 samples, 0.04%)alloc::vec::Vec<T,A>::append_elements (57 samples, 0.04%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (20 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (41 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (151 samples, 0.12%)core::hash::sip::u8to64_le (50 samples, 0.04%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (33 samples, 0.03%)tokio::runtime::context::CONTEXT::__getit (35 samples, 0.03%)core::cell::Cell<T>::get (33 samples, 0.03%)[unknown] (20 samples, 0.02%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (75 samples, 0.06%)core::ops::function::FnMut::call_mut (66 samples, 0.05%)tokio::runtime::coop::poll_proceed (66 samples, 0.05%)tokio::runtime::context::budget (66 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (66 samples, 0.05%)tokio::runtime::context::budget::{{closure}} (27 samples, 0.02%)tokio::runtime::coop::poll_proceed::{{closure}} (27 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (110 samples, 0.08%)[unknown] (15 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (27 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (27 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (14 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (84 samples, 0.06%)std::sync::mutex::Mutex<T>::lock (70 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock (59 samples, 0.04%)core::sync::atomic::AtomicU32::compare_exchange (55 samples, 0.04%)core::sync::atomic::atomic_compare_exchange (55 samples, 0.04%)[unknown] (33 samples, 0.03%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (214 samples, 0.16%)__memcpy_avx512_unaligned_erms (168 samples, 0.13%)[profiling] (171 samples, 0.13%)binascii::bin2hex (77 samples, 0.06%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (280 samples, 0.21%)[unknown] (317 samples, 0.24%)[[vdso]] (2,648 samples, 2.02%)[..[unknown] (669 samples, 0.51%)[unknown] (396 samples, 0.30%)[unknown] (251 samples, 0.19%)[unknown] (65 samples, 0.05%)[unknown] (30 samples, 0.02%)[unknown] (21 samples, 0.02%)__GI___clock_gettime (56 samples, 0.04%)arena_for_chunk (72 samples, 0.05%)arena_for_chunk (62 samples, 0.05%)heap_for_ptr (49 samples, 0.04%)heap_max_size (28 samples, 0.02%)__GI___libc_free (194 samples, 0.15%)arena_for_chunk (19 samples, 0.01%)checked_request2size (24 samples, 0.02%)__GI___libc_malloc (220 samples, 0.17%)tcache_get (44 samples, 0.03%)__GI___libc_write (25 samples, 0.02%)__GI___libc_write (14 samples, 0.01%)__GI___pthread_disable_asynccancel (97 samples, 0.07%)core::num::<impl u128>::leading_zeros (15 samples, 0.01%)compiler_builtins::float::conv::int_to_float::u128_to_f64_bits (72 samples, 0.05%)__floattidf (90 samples, 0.07%)compiler_builtins::float::conv::__floattidf (86 samples, 0.07%)exp_inline (40 samples, 0.03%)log_inline (64 samples, 0.05%)__ieee754_pow_fma (114 samples, 0.09%)__libc_calloc (106 samples, 0.08%)__libc_recvfrom (252 samples, 0.19%)__libc_sendto (133 samples, 0.10%)__memcmp_evex_movbe (137 samples, 0.10%)__memcpy_avx512_unaligned_erms (1,399 samples, 1.07%)__posix_memalign (172 samples, 0.13%)__posix_memalign (80 samples, 0.06%)_mid_memalign (71 samples, 0.05%)arena_for_chunk (14 samples, 0.01%)__pow (18 samples, 0.01%)__vdso_clock_gettime (40 samples, 0.03%)[unknown] (24 samples, 0.02%)_int_free (462 samples, 0.35%)tcache_put (54 samples, 0.04%)[unknown] (14 samples, 0.01%)_int_malloc (508 samples, 0.39%)_int_memalign (68 samples, 0.05%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (54 samples, 0.04%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (14 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (78 samples, 0.06%)alloc::raw_vec::RawVec<T,A>::grow_amortized (73 samples, 0.06%)alloc::raw_vec::finish_grow (91 samples, 0.07%)core::result::Result<T,E>::map_err (31 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Weak<ring::ec::curve25519::ed25519::signing::Ed25519KeyPair,&alloc::alloc::Global>> (16 samples, 0.01%)<alloc::sync::Weak<T,A> as core::ops::drop::Drop>::drop (16 samples, 0.01%)core::mem::drop (18 samples, 0.01%)alloc::sync::Arc<T,A>::drop_slow (21 samples, 0.02%)alloc_new_heap (49 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (49 samples, 0.04%)core::fmt::Formatter::pad_integral (40 samples, 0.03%)core::fmt::Formatter::pad_integral::write_prefix (19 samples, 0.01%)core::fmt::write (20 samples, 0.02%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (155 samples, 0.12%)core::ptr::drop_in_place<core::option::Option<core::task::wake::Waker>> (71 samples, 0.05%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (245 samples, 0.19%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_announce::{{closure}}> (33 samples, 0.03%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}}> (37 samples, 0.03%)core::str::converts::from_utf8 (33 samples, 0.03%)core::str::validations::run_utf8_validation (20 samples, 0.02%)epoll_wait (31 samples, 0.02%)hashbrown::map::HashMap<K,V,S,A>::insert (17 samples, 0.01%)rand_chacha::guts::refill_wide (19 samples, 0.01%)std_detect::detect::arch::x86::__is_feature_detected::avx2 (17 samples, 0.01%)std_detect::detect::check_for (17 samples, 0.01%)std_detect::detect::cache::test (17 samples, 0.01%)std_detect::detect::cache::Cache::test (17 samples, 0.01%)core::sync::atomic::AtomicUsize::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)std::sys::pal::unix::time::Timespec::new (29 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (132 samples, 0.10%)core::cmp::impls::<impl core::cmp::PartialOrd<&B> for &A>::ge (22 samples, 0.02%)core::cmp::PartialOrd::ge (22 samples, 0.02%)std::sys::pal::unix::time::Timespec::sub_timespec (67 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock_contended (18 samples, 0.01%)std::sys_common::net::TcpListener::socket_addr (29 samples, 0.02%)std::sys_common::net::sockname (28 samples, 0.02%)syscall (552 samples, 0.42%)core::ptr::drop_in_place<core::cell::RefMut<core::option::Option<alloc::boxed::Box<tokio::runtime::scheduler::multi_thread::worker::Core>>>> (74 samples, 0.06%)core::ptr::drop_in_place<core::cell::BorrowRefMut> (74 samples, 0.06%)<core::cell::BorrowRefMut as core::ops::drop::Drop>::drop (74 samples, 0.06%)core::cell::Cell<T>::set (74 samples, 0.06%)core::cell::Cell<T>::replace (74 samples, 0.06%)core::mem::replace (74 samples, 0.06%)core::ptr::write (74 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::push_back_or_overflow (14 samples, 0.01%)tokio::runtime::context::with_scheduler (176 samples, 0.13%)std::thread::local::LocalKey<T>::try_with (152 samples, 0.12%)tokio::runtime::context::with_scheduler::{{closure}} (151 samples, 0.12%)tokio::runtime::context::scoped::Scoped<T>::with (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (71 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (16 samples, 0.01%)core::option::Option<T>::map (19 samples, 0.01%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (24 samples, 0.02%)mio::poll::Poll::poll (53 samples, 0.04%)mio::sys::unix::selector::epoll::Selector::select (53 samples, 0.04%)core::result::Result<T,E>::map (28 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (28 samples, 0.02%)tokio::io::ready::Ready::from_mio (14 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (126 samples, 0.10%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (18 samples, 0.01%)[unknown] (51 samples, 0.04%)[unknown] (100 samples, 0.08%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (326 samples, 0.25%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (205 samples, 0.16%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (77 samples, 0.06%)[unknown] (26 samples, 0.02%)<tokio::util::linked_list::DrainFilter<T,F> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (396 samples, 0.30%)tokio::loom::std::mutex::Mutex<T>::lock (18 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (573 samples, 0.44%)core::sync::atomic::AtomicUsize::fetch_add (566 samples, 0.43%)core::sync::atomic::atomic_add (566 samples, 0.43%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (635 samples, 0.48%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (25 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::next_remote_task (44 samples, 0.03%)tokio::runtime::scheduler::inject::shared::Shared<T>::is_empty (21 samples, 0.02%)tokio::runtime::scheduler::inject::shared::Shared<T>::len (21 samples, 0.02%)core::sync::atomic::AtomicUsize::load (21 samples, 0.02%)core::sync::atomic::atomic_load (21 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id (32 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (32 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (32 samples, 0.02%)std::sync::poison::Flag::done (32 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>,tokio::runtime::task::core::Header>>> (43 samples, 0.03%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (43 samples, 0.03%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (123 samples, 0.09%)tokio::runtime::task::list::OwnedTasks<S>::remove (117 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (80 samples, 0.06%)tokio::runtime::scheduler::defer::Defer::wake (17 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (46 samples, 0.04%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (71 samples, 0.05%)std::sync::condvar::Condvar::wait (56 samples, 0.04%)std::sys::sync::condvar::futex::Condvar::wait (56 samples, 0.04%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (56 samples, 0.04%)core::sync::atomic::AtomicUsize::compare_exchange (37 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (37 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (138 samples, 0.11%)tokio::runtime::driver::Driver::park (77 samples, 0.06%)tokio::runtime::driver::TimeDriver::park (77 samples, 0.06%)tokio::runtime::time::Driver::park (75 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Parker::park (266 samples, 0.20%)tokio::runtime::scheduler::multi_thread::park::Inner::park (266 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (432 samples, 0.33%)tokio::runtime::scheduler::multi_thread::worker::Core::should_notify_others (26 samples, 0.02%)core::cell::RefCell<T>::borrow_mut (94 samples, 0.07%)core::cell::RefCell<T>::try_borrow_mut (94 samples, 0.07%)core::cell::BorrowRefMut::new (94 samples, 0.07%)tokio::runtime::coop::budget (142 samples, 0.11%)tokio::runtime::coop::with_budget (142 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (121 samples, 0.09%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (44 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (208 samples, 0.16%)tokio::runtime::signal::Driver::process (30 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (46 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (46 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (35 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::set_stage (75 samples, 0.06%)core::sync::atomic::AtomicUsize::fetch_xor (76 samples, 0.06%)core::sync::atomic::atomic_xor (76 samples, 0.06%)tokio::runtime::task::state::State::transition_to_complete (79 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::complete (113 samples, 0.09%)tokio::runtime::task::state::State::transition_to_terminal (18 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::dealloc (28 samples, 0.02%)core::mem::drop (18 samples, 0.01%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (18 samples, 0.01%)core::ptr::drop_in_place<tokio::util::sharded_list::ShardGuard<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>> (16 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>>> (16 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (16 samples, 0.01%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (53 samples, 0.04%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (21 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (113 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (15 samples, 0.01%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (15 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (15 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (15 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (14 samples, 0.01%)tokio::runtime::task::raw::drop_abort_handle (82 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (23 samples, 0.02%)tokio::runtime::task::state::State::ref_dec (23 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::task::raw::drop_join_handle_slow (34 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::drop_join_handle_slow (32 samples, 0.02%)tokio::runtime::task::state::State::unset_join_interested (23 samples, 0.02%)tokio::runtime::task::state::State::fetch_update (23 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (43 samples, 0.03%)core::num::<impl u32>::wrapping_add (23 samples, 0.02%)core::option::Option<T>::or_else (37 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (36 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (36 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (38 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (59 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (45 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (132 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (63 samples, 0.05%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run (290 samples, 0.22%)tokio::runtime::context::runtime::enter_runtime (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (290 samples, 0.22%)tokio::runtime::context::set_scheduler (290 samples, 0.22%)std::thread::local::LocalKey<T>::with (290 samples, 0.22%)std::thread::local::LocalKey<T>::try_with (290 samples, 0.22%)tokio::runtime::context::set_scheduler::{{closure}} (290 samples, 0.22%)tokio::runtime::context::scoped::Scoped<T>::set (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::Context::run (290 samples, 0.22%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (327 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (322 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::poll (333 samples, 0.25%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (342 samples, 0.26%)tokio::runtime::task::harness::poll_future::{{closure}} (342 samples, 0.26%)tokio::runtime::task::harness::poll_future (348 samples, 0.27%)std::panic::catch_unwind (347 samples, 0.26%)std::panicking::try (347 samples, 0.26%)std::panicking::try::do_call (347 samples, 0.26%)core::sync::atomic::AtomicUsize::compare_exchange (18 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (18 samples, 0.01%)tokio::runtime::task::state::State::transition_to_running (47 samples, 0.04%)tokio::runtime::task::state::State::fetch_update_action (47 samples, 0.04%)tokio::runtime::task::state::State::transition_to_running::{{closure}} (19 samples, 0.01%)tokio::runtime::task::raw::poll (427 samples, 0.33%)tokio::runtime::task::harness::Harness<T,S>::poll (408 samples, 0.31%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (407 samples, 0.31%)tokio::runtime::task::state::State::transition_to_idle (17 samples, 0.01%)core::array::<impl core::default::Default for [T: 32]>::default (21 samples, 0.02%)tokio::runtime::time::wheel::Wheel::poll (14 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (72 samples, 0.05%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (23 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (15 samples, 0.01%)tokio::runtime::time::source::TimeSource::now (14 samples, 0.01%)tokio::runtime::time::Driver::park_internal (155 samples, 0.12%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (96 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (35 samples, 0.03%)core::num::<impl usize>::pow (35 samples, 0.03%)tokio::runtime::time::wheel::level::level_range (39 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (33 samples, 0.03%)core::num::<impl usize>::pow (33 samples, 0.03%)tokio::runtime::time::wheel::level::Level::next_expiration (208 samples, 0.16%)tokio::runtime::time::wheel::level::slot_range (48 samples, 0.04%)core::num::<impl usize>::pow (48 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (277 samples, 0.21%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::is_empty (18 samples, 0.01%)core::option::Option<T>::is_some (18 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (50 samples, 0.04%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (37 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (27 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (19 samples, 0.01%)core::iter::traits::iterator::Iterator::collect (17 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (17 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (17 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (17 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (20 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (20 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (20 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (62 samples, 0.05%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (40 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (27 samples, 0.02%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (17 samples, 0.01%)torrust_tracker::servers::udp::peer_builder::from_request (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (19 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (355 samples, 0.27%)<F as core::future::into_future::IntoFuture>::into_future (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (37 samples, 0.03%)core::sync::atomic::AtomicUsize::fetch_add (25 samples, 0.02%)core::sync::atomic::atomic_add (25 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet (14 samples, 0.01%)core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (20 samples, 0.02%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)core::result::Result<T,E>::map_err (16 samples, 0.01%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (136 samples, 0.10%)torrust_tracker::core::Tracker::announce::{{closure}} (173 samples, 0.13%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (267 samples, 0.20%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (30 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (423 samples, 0.32%)core::fmt::Formatter::new (26 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (80 samples, 0.06%)core::fmt::num::imp::fmt_u64 (58 samples, 0.04%)core::intrinsics::copy_nonoverlapping (15 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (74 samples, 0.06%)core::fmt::num::imp::fmt_u64 (70 samples, 0.05%)<T as alloc::string::ToString>::to_string (207 samples, 0.16%)core::option::Option<T>::expect (19 samples, 0.01%)core::ptr::drop_in_place<alloc::string::String> (18 samples, 0.01%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (18 samples, 0.01%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (18 samples, 0.01%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (18 samples, 0.01%)torrust_tracker::servers::udp::logging::map_action_name (25 samples, 0.02%)alloc::str::<impl alloc::borrow::ToOwned for str>::to_owned (14 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (345 samples, 0.26%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (18 samples, 0.01%)core::fmt::num::imp::fmt_u64 (14 samples, 0.01%)<T as alloc::string::ToString>::to_string (35 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (1,067 samples, 0.81%)torrust_tracker::servers::udp::logging::log_response (72 samples, 0.05%)alloc::vec::from_elem (68 samples, 0.05%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (68 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (68 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (68 samples, 0.05%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (68 samples, 0.05%)alloc::alloc::Global::alloc_impl (68 samples, 0.05%)alloc::alloc::alloc_zeroed (68 samples, 0.05%)__rdl_alloc_zeroed (68 samples, 0.05%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (68 samples, 0.05%)[unknown] (48 samples, 0.04%)[unknown] (16 samples, 0.01%)[unknown] (28 samples, 0.02%)std::sys::pal::unix::cvt (134 samples, 0.10%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (134 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (1,908 samples, 1.45%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (504 samples, 0.38%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (382 samples, 0.29%)tokio::net::udp::UdpSocket::send_to::{{closure}} (344 samples, 0.26%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (332 samples, 0.25%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (304 samples, 0.23%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (215 samples, 0.16%)mio::net::udp::UdpSocket::send_to (185 samples, 0.14%)mio::io_source::IoSource<T>::do_io (185 samples, 0.14%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (185 samples, 0.14%)mio::net::udp::UdpSocket::send_to::{{closure}} (185 samples, 0.14%)std::net::udp::UdpSocket::send_to (185 samples, 0.14%)std::sys_common::net::UdpSocket::send_to (169 samples, 0.13%)alloc::vec::Vec<T>::with_capacity (17 samples, 0.01%)alloc::vec::Vec<T,A>::with_capacity_in (17 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (104 samples, 0.08%)tokio::net::udp::UdpSocket::ready::{{closure}} (85 samples, 0.06%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (190 samples, 0.14%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (49 samples, 0.04%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (28 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (330 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (327 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (92 samples, 0.07%)tokio::task::spawn::spawn (92 samples, 0.07%)tokio::task::spawn::spawn_inner (92 samples, 0.07%)tokio::runtime::context::current::with_current (92 samples, 0.07%)std::thread::local::LocalKey<T>::try_with (92 samples, 0.07%)tokio::runtime::context::current::with_current::{{closure}} (92 samples, 0.07%)core::option::Option<T>::map (92 samples, 0.07%)tokio::task::spawn::spawn_inner::{{closure}} (92 samples, 0.07%)tokio::runtime::scheduler::Handle::spawn (92 samples, 0.07%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (92 samples, 0.07%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (92 samples, 0.07%)tokio::runtime::task::list::OwnedTasks<S>::bind (90 samples, 0.07%)tokio::runtime::task::new_task (89 samples, 0.07%)tokio::runtime::task::raw::RawTask::new (89 samples, 0.07%)tokio::runtime::task::core::Cell<T,S>::new (89 samples, 0.07%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (34 samples, 0.03%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (27 samples, 0.02%)alloc::sync::Arc<T>::new (21 samples, 0.02%)alloc::boxed::Box<T>::new (21 samples, 0.02%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (152 samples, 0.12%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (125 samples, 0.10%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (88 samples, 0.07%)core::option::Option<T>::is_some_and (18 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (17 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (17 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (17 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (22 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (22 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (17 samples, 0.01%)std::sync::rwlock::RwLock<T>::read (16 samples, 0.01%)std::sys::sync::rwlock::futex::RwLock::read (16 samples, 0.01%)tracing::span::Span::log (26 samples, 0.02%)core::fmt::Arguments::new_v1 (15 samples, 0.01%)tracing_core::span::Record::is_empty (34 samples, 0.03%)tracing_core::field::ValueSet::is_empty (34 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::all (22 samples, 0.02%)tracing_core::field::ValueSet::is_empty::{{closure}} (18 samples, 0.01%)core::option::Option<T>::is_none (16 samples, 0.01%)core::option::Option<T>::is_some (16 samples, 0.01%)tracing::span::Span::record_all (143 samples, 0.11%)unlink_chunk (185 samples, 0.14%)uuid::builder::Builder::with_variant (48 samples, 0.04%)[unknown] (40 samples, 0.03%)uuid::builder::Builder::from_random_bytes (77 samples, 0.06%)uuid::builder::Builder::with_version (29 samples, 0.02%)[unknown] (24 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (161 samples, 0.12%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (161 samples, 0.12%)[unknown] (92 samples, 0.07%)rand::rng::Rng::gen (162 samples, 0.12%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (162 samples, 0.12%)rand::rng::Rng::gen (162 samples, 0.12%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (162 samples, 0.12%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (162 samples, 0.12%)[unknown] (18,233 samples, 13.89%)[unknown]uuid::v4::<impl uuid::Uuid>::new_v4 (270 samples, 0.21%)uuid::rng::bytes (190 samples, 0.14%)rand::random (190 samples, 0.14%)__memcpy_avx512_unaligned_erms (69 samples, 0.05%)_int_free (23 samples, 0.02%)_int_malloc (23 samples, 0.02%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)advise_stack_range (31 samples, 0.02%)__GI_madvise (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (29 samples, 0.02%)[unknown] (28 samples, 0.02%)[unknown] (28 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (17 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (31 samples, 0.02%)syscall (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (29 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (17 samples, 0.01%)std::sync::condvar::Condvar::wait_timeout (35 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_timeout (35 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (35 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (56 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (56 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (56 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (56 samples, 0.04%)std::sys::pal::unix::futex::futex_wait (56 samples, 0.04%)syscall (56 samples, 0.04%)[unknown] (56 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (53 samples, 0.04%)[unknown] (52 samples, 0.04%)[unknown] (46 samples, 0.04%)[unknown] (39 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (15 samples, 0.01%)[[vdso]] (26 samples, 0.02%)[[vdso]] (263 samples, 0.20%)__ieee754_pow_fma (26 samples, 0.02%)__pow (314 samples, 0.24%)std::f64::<impl f64>::powf (345 samples, 0.26%)__GI___clock_gettime (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (416 samples, 0.32%)std::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_processing_scheduled_tasks (24 samples, 0.02%)std::time::Instant::now (18 samples, 0.01%)std::sys::pal::unix::time::Instant::now (18 samples, 0.01%)mio::poll::Poll::poll (102 samples, 0.08%)mio::sys::unix::selector::epoll::Selector::select (102 samples, 0.08%)epoll_wait (99 samples, 0.08%)[unknown] (92 samples, 0.07%)[unknown] (91 samples, 0.07%)[unknown] (91 samples, 0.07%)[unknown] (88 samples, 0.07%)[unknown] (85 samples, 0.06%)[unknown] (84 samples, 0.06%)[unknown] (43 samples, 0.03%)[unknown] (29 samples, 0.02%)[unknown] (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (125 samples, 0.10%)tokio::runtime::scheduler::multi_thread::park::Parker::park_timeout (125 samples, 0.10%)tokio::runtime::driver::Driver::park_timeout (125 samples, 0.10%)tokio::runtime::driver::TimeDriver::park_timeout (125 samples, 0.10%)tokio::runtime::time::Driver::park_timeout (125 samples, 0.10%)tokio::runtime::time::Driver::park_internal (116 samples, 0.09%)tokio::runtime::io::driver::Driver::turn (116 samples, 0.09%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (148 samples, 0.11%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (111 samples, 0.08%)alloc::sync::Arc<T,A>::inner (111 samples, 0.08%)core::ptr::non_null::NonNull<T>::as_ref (111 samples, 0.08%)core::sync::atomic::AtomicUsize::compare_exchange (16 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (16 samples, 0.01%)core::bool::<impl bool>::then (88 samples, 0.07%)std::sys::pal::unix::futex::futex_wait (13,339 samples, 10.16%)std::sys::pal::..syscall (13,003 samples, 9.90%)syscall[unknown] (12,895 samples, 9.82%)[unknown][unknown] (12,759 samples, 9.72%)[unknown][unknown] (12,313 samples, 9.38%)[unknown][unknown] (12,032 samples, 9.16%)[unknown][unknown] (11,734 samples, 8.94%)[unknown][unknown] (11,209 samples, 8.54%)[unknown][unknown] (10,265 samples, 7.82%)[unknown][unknown] (9,345 samples, 7.12%)[unknown][unknown] (8,623 samples, 6.57%)[unknown][unknown] (7,744 samples, 5.90%)[unknow..[unknown] (5,922 samples, 4.51%)[unkn..[unknown] (4,459 samples, 3.40%)[un..[unknown] (2,808 samples, 2.14%)[..[unknown] (1,275 samples, 0.97%)[unknown] (1,022 samples, 0.78%)[unknown] (738 samples, 0.56%)[unknown] (607 samples, 0.46%)[unknown] (155 samples, 0.12%)core::result::Result<T,E>::is_err (77 samples, 0.06%)core::result::Result<T,E>::is_ok (77 samples, 0.06%)std::sync::condvar::Condvar::wait (13,429 samples, 10.23%)std::sync::cond..std::sys::sync::condvar::futex::Condvar::wait (13,428 samples, 10.23%)std::sys::sync:..std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (13,428 samples, 10.23%)std::sys::sync:..std::sys::sync::mutex::futex::Mutex::lock (89 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (13,508 samples, 10.29%)tokio::runtime:..tokio::loom::std::mutex::Mutex<T>::lock (64 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (31 samples, 0.02%)core::sync::atomic::AtomicU32::compare_exchange (30 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (30 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (38 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Parker::park (34 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park (34 samples, 0.03%)core::array::<impl core::default::Default for [T: 32]>::default (17 samples, 0.01%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (19 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (33 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (15 samples, 0.01%)core::num::<impl usize>::pow (15 samples, 0.01%)tokio::runtime::time::wheel::level::level_range (17 samples, 0.01%)tokio::runtime::time::wheel::level::slot_range (15 samples, 0.01%)core::num::<impl usize>::pow (15 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_expiration (95 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (41 samples, 0.03%)core::num::<impl usize>::pow (41 samples, 0.03%)tokio::runtime::time::wheel::Wheel::next_expiration (129 samples, 0.10%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (202 samples, 0.15%)tokio::runtime::time::wheel::Wheel::poll_at (17 samples, 0.01%)tokio::runtime::time::wheel::Wheel::next_expiration (15 samples, 0.01%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (38 samples, 0.03%)core::option::Option<T>::map (38 samples, 0.03%)core::result::Result<T,E>::map (31 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (31 samples, 0.02%)alloc::vec::Vec<T,A>::set_len (17 samples, 0.01%)[[vdso]] (28 samples, 0.02%)[unknown] (11,031 samples, 8.40%)[unknown][unknown] (10,941 samples, 8.33%)[unknown][unknown] (10,850 samples, 8.26%)[unknown][unknown] (10,691 samples, 8.14%)[unknown][unknown] (10,070 samples, 7.67%)[unknown][unknown] (9,737 samples, 7.42%)[unknown][unknown] (7,659 samples, 5.83%)[unknow..[unknown] (6,530 samples, 4.97%)[unkno..[unknown] (5,633 samples, 4.29%)[unkn..[unknown] (5,055 samples, 3.85%)[unk..[unknown] (4,046 samples, 3.08%)[un..[unknown] (2,911 samples, 2.22%)[..[unknown] (2,115 samples, 1.61%)[unknown] (1,226 samples, 0.93%)[unknown] (455 samples, 0.35%)[unknown] (408 samples, 0.31%)[unknown] (249 samples, 0.19%)[unknown] (202 samples, 0.15%)[unknown] (100 samples, 0.08%)mio::poll::Poll::poll (11,328 samples, 8.63%)mio::poll::P..mio::sys::unix::selector::epoll::Selector::select (11,328 samples, 8.63%)mio::sys::un..epoll_wait (11,229 samples, 8.55%)epoll_wait__GI___pthread_disable_asynccancel (50 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (47 samples, 0.04%)tokio::util::bit::Pack::pack (38 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (25 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (23 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (19 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (11,595 samples, 8.83%)tokio::runti..tokio::runtime::io::scheduled_io::ScheduledIo::wake (175 samples, 0.13%)__GI___clock_gettime (15 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (18 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (26 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (26 samples, 0.02%)tokio::time::clock::Clock::now (20 samples, 0.02%)tokio::time::clock::now (20 samples, 0.02%)std::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Instant::now (20 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (17 samples, 0.01%)tokio::runtime::time::Driver::park_internal (11,686 samples, 8.90%)tokio::runtim..tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (11,957 samples, 9.11%)tokio::runtim..tokio::runtime::driver::Driver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::driver::TimeDriver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::time::Driver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::scheduler::multi_thread::park::Parker::park (25,502 samples, 19.42%)tokio::runtime::scheduler::mul..tokio::runtime::scheduler::multi_thread::park::Inner::park (25,502 samples, 19.42%)tokio::runtime::scheduler::mul..tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (25,547 samples, 19.46%)tokio::runtime::scheduler::mul..core::result::Result<T,E>::is_err (14 samples, 0.01%)core::result::Result<T,E>::is_ok (14 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (45 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (45 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (84 samples, 0.06%)std::sync::mutex::Mutex<T>::lock (81 samples, 0.06%)std::sys::sync::mutex::futex::Mutex::lock (73 samples, 0.06%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (122 samples, 0.09%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (90 samples, 0.07%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (90 samples, 0.07%)core::slice::<impl [T]>::contains (241 samples, 0.18%)<T as core::slice::cmp::SliceContains>::slice_contains (241 samples, 0.18%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (241 samples, 0.18%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (75 samples, 0.06%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (75 samples, 0.06%)core::sync::atomic::AtomicU32::compare_exchange (20 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (283 samples, 0.22%)tokio::loom::std::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (24 samples, 0.02%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (33 samples, 0.03%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (33 samples, 0.03%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (33 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::unpark_worker_by_id (98 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (401 samples, 0.31%)alloc::vec::Vec<T,A>::push (14 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (15 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (15 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::unlock (14 samples, 0.01%)core::result::Result<T,E>::is_err (15 samples, 0.01%)core::result::Result<T,E>::is_ok (15 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (22 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (22 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (63 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (62 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock (59 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (106 samples, 0.08%)tokio::runtime::scheduler::multi_thread::idle::State::dec_num_unparked (14 samples, 0.01%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (21 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (17 samples, 0.01%)alloc::sync::Arc<T,A>::inner (17 samples, 0.01%)core::ptr::non_null::NonNull<T>::as_ref (17 samples, 0.01%)core::sync::atomic::AtomicU32::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (68 samples, 0.05%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (51 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (33 samples, 0.03%)core::sync::atomic::AtomicU64::load (16 samples, 0.01%)core::sync::atomic::atomic_load (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (106 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::park (26,672 samples, 20.31%)tokio::runtime::scheduler::multi..tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (272 samples, 0.21%)tokio::runtime::scheduler::multi_thread::worker::Core::has_tasks (33 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::has_tasks (24 samples, 0.02%)tokio::runtime::context::budget (18 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (18 samples, 0.01%)syscall (61 samples, 0.05%)__memcpy_avx512_unaligned_erms (172 samples, 0.13%)__memcpy_avx512_unaligned_erms (224 samples, 0.17%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (228 samples, 0.17%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (228 samples, 0.17%)std::panic::catch_unwind (415 samples, 0.32%)std::panicking::try (415 samples, 0.32%)std::panicking::try::do_call (415 samples, 0.32%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (415 samples, 0.32%)core::ops::function::FnOnce::call_once (415 samples, 0.32%)tokio::runtime::task::harness::Harness<T,S>::complete::{{closure}} (415 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (415 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::set_stage (410 samples, 0.31%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (27 samples, 0.02%)core::result::Result<T,E>::is_err (43 samples, 0.03%)core::result::Result<T,E>::is_ok (43 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::complete (570 samples, 0.43%)tokio::runtime::task::harness::Harness<T,S>::release (155 samples, 0.12%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (152 samples, 0.12%)tokio::runtime::task::list::OwnedTasks<S>::remove (152 samples, 0.12%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (103 samples, 0.08%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (65 samples, 0.05%)tokio::loom::std::mutex::Mutex<T>::lock (58 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (58 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (54 samples, 0.04%)std::io::stdio::stderr::INSTANCE (17 samples, 0.01%)tokio::runtime::coop::budget (26 samples, 0.02%)tokio::runtime::coop::with_budget (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (35 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (70 samples, 0.05%)__memcpy_avx512_unaligned_erms (42 samples, 0.03%)core::cmp::Ord::min (22 samples, 0.02%)core::cmp::min_by (22 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (27 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (30 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (24 samples, 0.02%)core::slice::index::<impl core::ops::index::Index<I> for [T]>::index (19 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::index (19 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (19 samples, 0.01%)<core::ops::range::Range<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (19 samples, 0.01%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (44 samples, 0.03%)std::io::impls::<impl std::io::Read for &[u8]>::read_exact (20 samples, 0.02%)byteorder::io::ReadBytesExt::read_i32 (46 samples, 0.04%)core::cmp::Ord::min (14 samples, 0.01%)core::cmp::min_by (14 samples, 0.01%)std::io::cursor::Cursor<T>::remaining_slice (19 samples, 0.01%)byteorder::io::ReadBytesExt::read_i64 (24 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (24 samples, 0.02%)aquatic_udp_protocol::request::Request::from_bytes (349 samples, 0.27%)__GI___lll_lock_wake_private (148 samples, 0.11%)[unknown] (139 samples, 0.11%)[unknown] (137 samples, 0.10%)[unknown] (123 samples, 0.09%)[unknown] (111 samples, 0.08%)[unknown] (98 samples, 0.07%)[unknown] (42 samples, 0.03%)[unknown] (30 samples, 0.02%)__GI___lll_lock_wait_private (553 samples, 0.42%)futex_wait (541 samples, 0.41%)[unknown] (536 samples, 0.41%)[unknown] (531 samples, 0.40%)[unknown] (524 samples, 0.40%)[unknown] (515 samples, 0.39%)[unknown] (498 samples, 0.38%)[unknown] (470 samples, 0.36%)[unknown] (435 samples, 0.33%)[unknown] (350 samples, 0.27%)[unknown] (327 samples, 0.25%)[unknown] (290 samples, 0.22%)[unknown] (222 samples, 0.17%)[unknown] (160 samples, 0.12%)[unknown] (104 samples, 0.08%)[unknown] (33 samples, 0.03%)[unknown] (25 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (703 samples, 0.54%)__GI___libc_free (866 samples, 0.66%)tracing::span::Span::record_all (30 samples, 0.02%)unlink_chunk (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (899 samples, 0.68%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (899 samples, 0.68%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (899 samples, 0.68%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (899 samples, 0.68%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (899 samples, 0.68%)alloc::alloc::dealloc (899 samples, 0.68%)__rdl_dealloc (899 samples, 0.68%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (899 samples, 0.68%)core::result::Result<T,E>::expect (91 samples, 0.07%)core::result::Result<T,E>::map_err (28 samples, 0.02%)[[vdso]] (28 samples, 0.02%)__GI___clock_gettime (47 samples, 0.04%)std::time::Instant::elapsed (67 samples, 0.05%)std::time::Instant::now (54 samples, 0.04%)std::sys::pal::unix::time::Instant::now (54 samples, 0.04%)std::sys::pal::unix::time::Timespec::now (53 samples, 0.04%)std::sys::pal::unix::cvt (23 samples, 0.02%)__GI_getsockname (3,792 samples, 2.89%)__..[unknown] (3,714 samples, 2.83%)[u..[unknown] (3,661 samples, 2.79%)[u..[unknown] (3,557 samples, 2.71%)[u..[unknown] (3,416 samples, 2.60%)[u..[unknown] (2,695 samples, 2.05%)[..[unknown] (2,063 samples, 1.57%)[unknown] (891 samples, 0.68%)[unknown] (270 samples, 0.21%)[unknown] (99 samples, 0.08%)[unknown] (94 samples, 0.07%)[unknown] (84 samples, 0.06%)[unknown] (77 samples, 0.06%)[unknown] (25 samples, 0.02%)[unknown] (16 samples, 0.01%)std::sys_common::net::TcpListener::socket_addr::{{closure}} (3,800 samples, 2.89%)st..tokio::net::udp::UdpSocket::local_addr (3,838 samples, 2.92%)to..mio::net::udp::UdpSocket::local_addr (3,838 samples, 2.92%)mi..std::net::tcp::TcpListener::local_addr (3,838 samples, 2.92%)st..std::sys_common::net::TcpListener::socket_addr (3,838 samples, 2.92%)st..std::sys_common::net::sockname (3,835 samples, 2.92%)st..[[vdso]] (60 samples, 0.05%)rand_chacha::guts::ChaCha::pos64 (168 samples, 0.13%)<ppv_lite86::soft::x2<W,G> as core::ops::arith::AddAssign>::add_assign (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::AddAssign>::add_assign (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::Add>::add (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_add_epi32 (26 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_or_si256 (29 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (31 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (31 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (18 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (18 samples, 0.01%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (18 samples, 0.01%)rand_chacha::guts::round (118 samples, 0.09%)rand_chacha::guts::refill_wide::impl_avx2 (312 samples, 0.24%)rand_chacha::guts::refill_wide::fn_impl (312 samples, 0.24%)rand_chacha::guts::refill_wide_impl (312 samples, 0.24%)<rand_chacha::chacha::ChaCha12Core as rand_core::block::BlockRngCore>::generate (384 samples, 0.29%)rand_chacha::guts::ChaCha::refill4 (384 samples, 0.29%)rand::rng::Rng::gen (432 samples, 0.33%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (432 samples, 0.33%)rand::rng::Rng::gen (432 samples, 0.33%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (432 samples, 0.33%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (432 samples, 0.33%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (432 samples, 0.33%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (432 samples, 0.33%)rand_core::block::BlockRng<R>::generate_and_set (392 samples, 0.30%)<rand::rngs::adapter::reseeding::ReseedingCore<R,Rsdr> as rand_core::block::BlockRngCore>::generate (392 samples, 0.30%)torrust_tracker::servers::udp::handlers::RequestId::make (440 samples, 0.34%)uuid::v4::<impl uuid::Uuid>::new_v4 (436 samples, 0.33%)uuid::rng::bytes (435 samples, 0.33%)rand::random (435 samples, 0.33%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (34 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (22 samples, 0.02%)core::iter::traits::iterator::Iterator::collect (16 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (16 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (16 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (16 samples, 0.01%)<core::iter::adapters::cloned::Cloned<I> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)<core::iter::adapters::take::Take<I> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::next (15 samples, 0.01%)core::iter::traits::iterator::Iterator::find (15 samples, 0.01%)core::iter::traits::iterator::Iterator::try_fold (15 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (31 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.03%)core::slice::iter::Iter<T>::post_inc_start (14 samples, 0.01%)core::ptr::non_null::NonNull<T>::add (14 samples, 0.01%)__memcmp_evex_movbe (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (26 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (165 samples, 0.13%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (165 samples, 0.13%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (165 samples, 0.13%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (165 samples, 0.13%)<u8 as core::slice::cmp::SliceOrd>::compare (165 samples, 0.13%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (339 samples, 0.26%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (308 samples, 0.23%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (308 samples, 0.23%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (342 samples, 0.26%)std::sys::sync::rwlock::futex::RwLock::spin_read (25 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_until (25 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read_contended (28 samples, 0.02%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (436 samples, 0.33%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (397 samples, 0.30%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (29 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (29 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (29 samples, 0.02%)__memcmp_evex_movbe (31 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (52 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (52 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (52 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (52 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (52 samples, 0.04%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (103 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (102 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (96 samples, 0.07%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (96 samples, 0.07%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (72 samples, 0.05%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.08%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.08%)core::slice::iter::Iter<T>::post_inc_start (32 samples, 0.02%)core::ptr::non_null::NonNull<T>::add (32 samples, 0.02%)__memcmp_evex_movbe (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (81 samples, 0.06%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (271 samples, 0.21%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (271 samples, 0.21%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (271 samples, 0.21%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (271 samples, 0.21%)<u8 as core::slice::cmp::SliceOrd>::compare (271 samples, 0.21%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (610 samples, 0.46%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (566 samples, 0.43%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (566 samples, 0.43%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut,K,V,Type>::keys (18 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (616 samples, 0.47%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::KV>::split (15 samples, 0.01%)alloc::collections::btree::map::entry::Entry<K,V,A>::or_insert (46 samples, 0.04%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (45 samples, 0.03%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert_recursing (40 samples, 0.03%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert (27 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (29 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (20 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (120 samples, 0.09%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (118 samples, 0.09%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Owned,K,V,alloc::collections::btree::node::marker::Leaf>::new_leaf (118 samples, 0.09%)alloc::collections::btree::node::LeafNode<K,V>::new (118 samples, 0.09%)alloc::boxed::Box<T,A>::new_uninit_in (118 samples, 0.09%)alloc::boxed::Box<T,A>::try_new_uninit_in (118 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (118 samples, 0.09%)alloc::alloc::Global::alloc_impl (118 samples, 0.09%)alloc::alloc::alloc (118 samples, 0.09%)__rdl_alloc (118 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (118 samples, 0.09%)__GI___libc_malloc (118 samples, 0.09%)_int_malloc (107 samples, 0.08%)_int_malloc (28 samples, 0.02%)__GI___libc_malloc (32 samples, 0.02%)__rdl_alloc (36 samples, 0.03%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (36 samples, 0.03%)alloc::sync::Arc<T>::new (42 samples, 0.03%)alloc::boxed::Box<T>::new (42 samples, 0.03%)alloc::alloc::exchange_malloc (39 samples, 0.03%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (39 samples, 0.03%)alloc::alloc::Global::alloc_impl (39 samples, 0.03%)alloc::alloc::alloc (39 samples, 0.03%)core::mem::drop (15 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (15 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (15 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (15 samples, 0.01%)__GI___libc_free (39 samples, 0.03%)_int_free (37 samples, 0.03%)get_max_fast (16 samples, 0.01%)core::option::Option<T>::is_some_and (50 samples, 0.04%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (50 samples, 0.04%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (50 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (50 samples, 0.04%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (290 samples, 0.22%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (284 samples, 0.22%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (255 samples, 0.19%)std::sys::sync::rwlock::futex::RwLock::spin_read (16 samples, 0.01%)std::sys::sync::rwlock::futex::RwLock::spin_until (16 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (21 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (21 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (21 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read_contended (21 samples, 0.02%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (1,147 samples, 0.87%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (1,144 samples, 0.87%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents_mut (32 samples, 0.02%)std::sync::rwlock::RwLock<T>::write (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::write (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::write_contended (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_write (28 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_until (28 samples, 0.02%)torrust_tracker::core::Tracker::announce::{{closure}} (1,597 samples, 1.22%)<core::net::socket_addr::SocketAddrV4 as core::hash::Hash>::hash (14 samples, 0.01%)<core::net::ip_addr::Ipv4Addr as core::hash::Hash>::hash (14 samples, 0.01%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (29 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (24 samples, 0.02%)<core::time::Nanoseconds as core::hash::Hash>::hash (25 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (25 samples, 0.02%)core::hash::Hasher::write_u32 (25 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (25 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (25 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (36 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (37 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (37 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (64 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (39 samples, 0.03%)core::hash::Hasher::write_u64 (39 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (122 samples, 0.09%)core::hash::impls::<impl core::hash::Hash for u64>::hash (58 samples, 0.04%)core::hash::Hasher::write_u64 (58 samples, 0.04%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (58 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (58 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (57 samples, 0.04%)core::hash::sip::u8to64_le (23 samples, 0.02%)core::hash::Hasher::write_length_prefix (27 samples, 0.02%)core::hash::Hasher::write_usize (27 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (16 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (246 samples, 0.19%)core::array::<impl core::hash::Hash for [T: N]>::hash (93 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (93 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (66 samples, 0.05%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (62 samples, 0.05%)core::hash::sip::u8to64_le (17 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::check (285 samples, 0.22%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (36 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (36 samples, 0.03%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (24 samples, 0.02%)std::time::SystemTime::now (19 samples, 0.01%)std::sys::pal::unix::time::SystemTime::now (19 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (1,954 samples, 1.49%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (24 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (18 samples, 0.01%)<core::time::Nanoseconds as core::hash::Hash>::hash (20 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (20 samples, 0.02%)core::hash::Hasher::write_u32 (20 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (20 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (20 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (44 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (65 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (45 samples, 0.03%)core::hash::Hasher::write_u64 (45 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (45 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (45 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (105 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u64>::hash (40 samples, 0.03%)core::hash::Hasher::write_u64 (40 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (40 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (40 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (39 samples, 0.03%)core::hash::Hasher::write_length_prefix (34 samples, 0.03%)core::hash::Hasher::write_usize (34 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (34 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (34 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (33 samples, 0.03%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (231 samples, 0.18%)core::array::<impl core::hash::Hash for [T: N]>::hash (100 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (100 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (66 samples, 0.05%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (61 samples, 0.05%)core::hash::sip::u8to64_le (16 samples, 0.01%)_int_free (16 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (270 samples, 0.21%)torrust_tracker::servers::udp::connection_cookie::make (268 samples, 0.20%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (36 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (35 samples, 0.03%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (31 samples, 0.02%)std::time::SystemTime::now (26 samples, 0.02%)std::sys::pal::unix::time::SystemTime::now (26 samples, 0.02%)torrust_tracker::core::ScrapeData::add_file (19 samples, 0.01%)std::collections::hash::map::HashMap<K,V,S>::insert (19 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (19 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (16 samples, 0.01%)hashbrown::raw::RawTable<T,A>::reserve (16 samples, 0.01%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (17 samples, 0.01%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (17 samples, 0.01%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (17 samples, 0.01%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (17 samples, 0.01%)<u8 as core::slice::cmp::SliceOrd>::compare (17 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (53 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (53 samples, 0.04%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (2,336 samples, 1.78%)t..torrust_tracker::servers::udp::handlers::handle_scrape::{{closure}} (101 samples, 0.08%)torrust_tracker::core::Tracker::scrape::{{closure}} (90 samples, 0.07%)torrust_tracker::core::Tracker::get_swarm_metadata (68 samples, 0.05%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (64 samples, 0.05%)alloc::raw_vec::finish_grow (19 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::grow_amortized (21 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (23 samples, 0.02%)alloc::string::String::push_str (23 samples, 0.02%)alloc::vec::Vec<T,A>::extend_from_slice (23 samples, 0.02%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (23 samples, 0.02%)alloc::vec::Vec<T,A>::append_elements (23 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (85 samples, 0.06%)core::fmt::num::imp::fmt_u64 (78 samples, 0.06%)<alloc::string::String as core::fmt::Write>::write_str (15 samples, 0.01%)alloc::string::String::push_str (15 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (15 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (15 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (15 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (37 samples, 0.03%)core::fmt::num::imp::fmt_u64 (36 samples, 0.03%)<T as alloc::string::ToString>::to_string (141 samples, 0.11%)core::option::Option<T>::expect (34 samples, 0.03%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (28 samples, 0.02%)alloc::alloc::dealloc (28 samples, 0.02%)__rdl_dealloc (28 samples, 0.02%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (28 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (55 samples, 0.04%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (55 samples, 0.04%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (55 samples, 0.04%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (55 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::current_memory (20 samples, 0.02%)torrust_tracker::servers::udp::logging::map_action_name (16 samples, 0.01%)binascii::bin2hex (51 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (16 samples, 0.01%)core::fmt::write (25 samples, 0.02%)core::fmt::rt::Argument::fmt (15 samples, 0.01%)core::fmt::Formatter::write_fmt (87 samples, 0.07%)core::str::converts::from_utf8 (43 samples, 0.03%)core::str::validations::run_utf8_validation (37 samples, 0.03%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (161 samples, 0.12%)<T as alloc::string::ToString>::to_string (161 samples, 0.12%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (156 samples, 0.12%)torrust_tracker::servers::udp::logging::log_request (479 samples, 0.36%)[[vdso]] (51 samples, 0.04%)alloc::raw_vec::finish_grow (56 samples, 0.04%)alloc::vec::Vec<T,A>::reserve (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::reserve (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::grow_amortized (64 samples, 0.05%)<alloc::string::String as core::fmt::Write>::write_str (65 samples, 0.05%)alloc::string::String::push_str (65 samples, 0.05%)alloc::vec::Vec<T,A>::extend_from_slice (65 samples, 0.05%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (65 samples, 0.05%)alloc::vec::Vec<T,A>::append_elements (65 samples, 0.05%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (114 samples, 0.09%)core::fmt::num::imp::fmt_u64 (110 samples, 0.08%)<T as alloc::string::ToString>::to_string (132 samples, 0.10%)core::option::Option<T>::expect (20 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (22 samples, 0.02%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (22 samples, 0.02%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (22 samples, 0.02%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (22 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (8,883 samples, 6.77%)torrust_t..torrust_tracker::servers::udp::logging::log_response (238 samples, 0.18%)__GI___lll_lock_wait_private (14 samples, 0.01%)futex_wait (14 samples, 0.01%)__GI___lll_lock_wake_private (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (17 samples, 0.01%)_int_malloc (191 samples, 0.15%)__libc_calloc (238 samples, 0.18%)__memcpy_avx512_unaligned_erms (34 samples, 0.03%)alloc::vec::from_elem (316 samples, 0.24%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (316 samples, 0.24%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (316 samples, 0.24%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (316 samples, 0.24%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (312 samples, 0.24%)alloc::alloc::Global::alloc_impl (312 samples, 0.24%)alloc::alloc::alloc_zeroed (312 samples, 0.24%)__rdl_alloc_zeroed (312 samples, 0.24%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (312 samples, 0.24%)byteorder::ByteOrder::write_i32 (18 samples, 0.01%)<byteorder::BigEndian as byteorder::ByteOrder>::write_u32 (18 samples, 0.01%)core::num::<impl u32>::to_be_bytes (18 samples, 0.01%)core::num::<impl u32>::to_be (18 samples, 0.01%)core::num::<impl u32>::swap_bytes (18 samples, 0.01%)byteorder::io::WriteBytesExt::write_i32 (89 samples, 0.07%)std::io::Write::write_all (71 samples, 0.05%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (71 samples, 0.05%)std::io::cursor::vec_write (71 samples, 0.05%)std::io::cursor::vec_write_unchecked (51 samples, 0.04%)core::ptr::mut_ptr::<impl *mut T>::copy_from (51 samples, 0.04%)core::intrinsics::copy (51 samples, 0.04%)aquatic_udp_protocol::response::Response::write (227 samples, 0.17%)byteorder::io::WriteBytesExt::write_i64 (28 samples, 0.02%)std::io::Write::write_all (21 samples, 0.02%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (21 samples, 0.02%)std::io::cursor::vec_write (21 samples, 0.02%)std::io::cursor::vec_write_unchecked (21 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::copy_from (21 samples, 0.02%)core::intrinsics::copy (21 samples, 0.02%)__GI___lll_lock_wake_private (17 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (14 samples, 0.01%)__GI___lll_lock_wait_private (16 samples, 0.01%)futex_wait (15 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (136 samples, 0.10%)__GI___libc_free (206 samples, 0.16%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (211 samples, 0.16%)alloc::alloc::dealloc (211 samples, 0.16%)__rdl_dealloc (211 samples, 0.16%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (211 samples, 0.16%)core::ptr::drop_in_place<std::io::cursor::Cursor<alloc::vec::Vec<u8>>> (224 samples, 0.17%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (224 samples, 0.17%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (224 samples, 0.17%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (224 samples, 0.17%)std::io::cursor::Cursor<T>::new (56 samples, 0.04%)tokio::io::ready::Ready::intersection (23 samples, 0.02%)tokio::io::ready::Ready::from_interest (23 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (83 samples, 0.06%)[unknown] (32,674 samples, 24.88%)[unknown][unknown] (32,402 samples, 24.68%)[unknown][unknown] (32,272 samples, 24.58%)[unknown][unknown] (32,215 samples, 24.54%)[unknown][unknown] (31,174 samples, 23.74%)[unknown][unknown] (30,794 samples, 23.45%)[unknown][unknown] (30,036 samples, 22.88%)[unknown][unknown] (28,639 samples, 21.81%)[unknown][unknown] (27,908 samples, 21.25%)[unknown][unknown] (26,013 samples, 19.81%)[unknown][unknown] (23,181 samples, 17.65%)[unknown][unknown] (19,559 samples, 14.90%)[unknown][unknown] (18,052 samples, 13.75%)[unknown][unknown] (15,794 samples, 12.03%)[unknown][unknown] (14,740 samples, 11.23%)[unknown][unknown] (12,486 samples, 9.51%)[unknown][unknown] (11,317 samples, 8.62%)[unknown][unknown] (10,725 samples, 8.17%)[unknown][unknown] (10,017 samples, 7.63%)[unknown][unknown] (9,713 samples, 7.40%)[unknown][unknown] (8,432 samples, 6.42%)[unknown][unknown] (8,062 samples, 6.14%)[unknown][unknown] (6,973 samples, 5.31%)[unknow..[unknown] (5,328 samples, 4.06%)[unk..[unknown] (4,352 samples, 3.31%)[un..[unknown] (3,786 samples, 2.88%)[u..[unknown] (3,659 samples, 2.79%)[u..[unknown] (3,276 samples, 2.50%)[u..[unknown] (2,417 samples, 1.84%)[..[unknown] (2,115 samples, 1.61%)[unknown] (1,610 samples, 1.23%)[unknown] (422 samples, 0.32%)[unknown] (84 samples, 0.06%)[unknown] (69 samples, 0.05%)__GI___pthread_disable_asynccancel (67 samples, 0.05%)__libc_sendto (32,896 samples, 25.05%)__libc_sendtotokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (32,981 samples, 25.12%)tokio::net::udp::UdpSocket::send_to_addr..mio::net::udp::UdpSocket::send_to (32,981 samples, 25.12%)mio::net::udp::UdpSocket::send_tomio::io_source::IoSource<T>::do_io (32,981 samples, 25.12%)mio::io_source::IoSource<T>::do_iomio::sys::unix::stateless_io_source::IoSourceState::do_io (32,981 samples, 25.12%)mio::sys::unix::stateless_io_source::IoS..mio::net::udp::UdpSocket::send_to::{{closure}} (32,981 samples, 25.12%)mio::net::udp::UdpSocket::send_to::{{clo..std::net::udp::UdpSocket::send_to (32,981 samples, 25.12%)std::net::udp::UdpSocket::send_tostd::sys_common::net::UdpSocket::send_to (32,981 samples, 25.12%)std::sys_common::net::UdpSocket::send_tostd::sys::pal::unix::cvt (85 samples, 0.06%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (44,349 samples, 33.78%)torrust_tracker::servers::udp::server::Udp::process_req..torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (43,412 samples, 33.06%)torrust_tracker::servers::udp::server::Udp::process_va..torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (34,320 samples, 26.14%)torrust_tracker::servers::udp::server::Udp..torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (33,360 samples, 25.41%)torrust_tracker::servers::udp::server::Ud..tokio::net::udp::UdpSocket::send_to::{{closure}} (33,227 samples, 25.31%)tokio::net::udp::UdpSocket::send_to::{{c..tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (33,142 samples, 25.24%)tokio::net::udp::UdpSocket::send_to_addr..tokio::runtime::io::registration::Registration::async_io::{{closure}} (33,115 samples, 25.22%)tokio::runtime::io::registration::Regist..tokio::runtime::io::registration::Registration::readiness::{{closure}} (28 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (18 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (15 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (14 samples, 0.01%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (15 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (15 samples, 0.01%)core::sync::atomic::atomic_add (15 samples, 0.01%)__GI___lll_lock_wait_private (16 samples, 0.01%)futex_wait (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (135 samples, 0.10%)__GI___libc_free (147 samples, 0.11%)syscall (22 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Core<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (15 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::dealloc (24 samples, 0.02%)core::mem::drop (24 samples, 0.02%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (24 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (24 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::abort::AbortHandle> (262 samples, 0.20%)<tokio::runtime::task::abort::AbortHandle as core::ops::drop::Drop>::drop (262 samples, 0.20%)tokio::runtime::task::raw::RawTask::drop_abort_handle (256 samples, 0.19%)tokio::runtime::task::raw::drop_abort_handle (59 samples, 0.04%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (50 samples, 0.04%)tokio::runtime::task::state::State::ref_dec (50 samples, 0.04%)tokio::runtime::task::raw::RawTask::drop_join_handle_slow (16 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::join::JoinHandle<()>> (47 samples, 0.04%)<tokio::runtime::task::join::JoinHandle<T> as core::ops::drop::Drop>::drop (47 samples, 0.04%)tokio::runtime::task::state::State::drop_join_handle_fast (19 samples, 0.01%)core::sync::atomic::AtomicUsize::compare_exchange_weak (19 samples, 0.01%)core::sync::atomic::atomic_compare_exchange_weak (19 samples, 0.01%)ringbuf::ring_buffer::base::RbBase::is_full (14 samples, 0.01%)<ringbuf::ring_buffer::shared::SharedRb<T,C> as ringbuf::ring_buffer::base::RbBase<T>>::head (14 samples, 0.01%)core::sync::atomic::AtomicUsize::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)ringbuf::consumer::Consumer<T,R>::advance (29 samples, 0.02%)ringbuf::ring_buffer::base::RbRead::advance_head (29 samples, 0.02%)ringbuf::ring_buffer::rb::Rb::pop (50 samples, 0.04%)ringbuf::consumer::Consumer<T,R>::pop (50 samples, 0.04%)ringbuf::producer::Producer<T,R>::advance (23 samples, 0.02%)ringbuf::ring_buffer::base::RbWrite::advance_tail (23 samples, 0.02%)core::num::nonzero::<impl core::ops::arith::Rem<core::num::nonzero::NonZero<usize>> for usize>::rem (19 samples, 0.01%)ringbuf::ring_buffer::rb::Rb::push_overwrite (107 samples, 0.08%)ringbuf::ring_buffer::rb::Rb::push (43 samples, 0.03%)ringbuf::producer::Producer<T,R>::push (43 samples, 0.03%)tokio::runtime::task::abort::AbortHandle::is_finished (84 samples, 0.06%)tokio::runtime::task::state::Snapshot::is_complete (84 samples, 0.06%)tokio::runtime::task::join::JoinHandle<T>::abort_handle (17 samples, 0.01%)tokio::runtime::task::raw::RawTask::ref_inc (17 samples, 0.01%)tokio::runtime::task::state::State::ref_inc (17 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (14 samples, 0.01%)core::sync::atomic::atomic_add (14 samples, 0.01%)__GI___lll_lock_wake_private (22 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)malloc_consolidate (95 samples, 0.07%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (76 samples, 0.06%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (31 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (26 samples, 0.02%)_int_malloc (282 samples, 0.21%)__GI___libc_malloc (323 samples, 0.25%)alloc::vec::Vec<T>::with_capacity (326 samples, 0.25%)alloc::vec::Vec<T,A>::with_capacity_in (326 samples, 0.25%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (324 samples, 0.25%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (324 samples, 0.25%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (324 samples, 0.25%)alloc::alloc::Global::alloc_impl (324 samples, 0.25%)alloc::alloc::alloc (324 samples, 0.25%)__rdl_alloc (324 samples, 0.25%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (324 samples, 0.25%)tokio::io::ready::Ready::intersection (24 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (199 samples, 0.15%)tokio::util::bit::Pack::unpack (16 samples, 0.01%)tokio::util::bit::unpack (16 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (19 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (17 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (16 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (222 samples, 0.17%)tokio::net::udp::UdpSocket::ready::{{closure}} (222 samples, 0.17%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (50 samples, 0.04%)std::io::error::repr_bitpacked::Repr::data (14 samples, 0.01%)std::io::error::repr_bitpacked::decode_repr (14 samples, 0.01%)std::io::error::Error::kind (16 samples, 0.01%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (14 samples, 0.01%)[unknown] (8,756 samples, 6.67%)[unknown][unknown] (8,685 samples, 6.61%)[unknown][unknown] (8,574 samples, 6.53%)[unknown][unknown] (8,415 samples, 6.41%)[unknown][unknown] (7,686 samples, 5.85%)[unknow..[unknown] (7,239 samples, 5.51%)[unknow..[unknown] (6,566 samples, 5.00%)[unkno..[unknown] (5,304 samples, 4.04%)[unk..[unknown] (4,008 samples, 3.05%)[un..[unknown] (3,571 samples, 2.72%)[u..[unknown] (2,375 samples, 1.81%)[..[unknown] (1,844 samples, 1.40%)[unknown] (1,030 samples, 0.78%)[unknown] (344 samples, 0.26%)[unknown] (113 samples, 0.09%)__libc_recvfrom (8,903 samples, 6.78%)__libc_re..__GI___pthread_disable_asynccancel (22 samples, 0.02%)std::sys::pal::unix::cvt (20 samples, 0.02%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (9,005 samples, 6.86%)tokio::ne..mio::net::udp::UdpSocket::recv_from (8,964 samples, 6.83%)mio::net:..mio::io_source::IoSource<T>::do_io (8,964 samples, 6.83%)mio::io_s..mio::sys::unix::stateless_io_source::IoSourceState::do_io (8,964 samples, 6.83%)mio::sys:..mio::net::udp::UdpSocket::recv_from::{{closure}} (8,964 samples, 6.83%)mio::net:..std::net::udp::UdpSocket::recv_from (8,964 samples, 6.83%)std::net:..std::sys_common::net::UdpSocket::recv_from (8,964 samples, 6.83%)std::sys_..std::sys::pal::unix::net::Socket::recv_from (8,964 samples, 6.83%)std::sys:..std::sys::pal::unix::net::Socket::recv_from_with_flags (8,964 samples, 6.83%)std::sys:..std::sys_common::net::sockaddr_to_addr (23 samples, 0.02%)tokio::runtime::io::registration::Registration::clear_readiness (18 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::clear_readiness (18 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (32 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (9,967 samples, 7.59%)torrust_tr..tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (9,291 samples, 7.08%)tokio::ne..tokio::runtime::io::registration::Registration::async_io::{{closure}} (9,287 samples, 7.07%)tokio::ru..tokio::runtime::io::registration::Registration::readiness::{{closure}} (45 samples, 0.03%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (41 samples, 0.03%)__memcpy_avx512_unaligned_erms (424 samples, 0.32%)__memcpy_avx512_unaligned_erms (493 samples, 0.38%)__memcpy_avx512_unaligned_erms (298 samples, 0.23%)syscall (1,105 samples, 0.84%)[unknown] (1,095 samples, 0.83%)[unknown] (1,091 samples, 0.83%)[unknown] (1,049 samples, 0.80%)[unknown] (998 samples, 0.76%)[unknown] (907 samples, 0.69%)[unknown] (710 samples, 0.54%)[unknown] (635 samples, 0.48%)[unknown] (538 samples, 0.41%)[unknown] (358 samples, 0.27%)[unknown] (256 samples, 0.19%)[unknown] (153 samples, 0.12%)[unknown] (96 samples, 0.07%)[unknown] (81 samples, 0.06%)tokio::runtime::context::with_scheduler (36 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (31 samples, 0.02%)tokio::runtime::context::with_scheduler::{{closure}} (27 samples, 0.02%)tokio::runtime::context::scoped::Scoped<T>::with (27 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (25 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (15 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (340 samples, 0.26%)core::sync::atomic::atomic_add (340 samples, 0.26%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (354 samples, 0.27%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (367 samples, 0.28%)[unknown] (95 samples, 0.07%)[unknown] (93 samples, 0.07%)[unknown] (92 samples, 0.07%)[unknown] (90 samples, 0.07%)[unknown] (82 samples, 0.06%)[unknown] (73 samples, 0.06%)[unknown] (63 samples, 0.05%)[unknown] (44 samples, 0.03%)[unknown] (40 samples, 0.03%)[unknown] (35 samples, 0.03%)[unknown] (30 samples, 0.02%)[unknown] (22 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (17 samples, 0.01%)tokio::runtime::driver::Handle::unpark (99 samples, 0.08%)tokio::runtime::driver::IoHandle::unpark (99 samples, 0.08%)tokio::runtime::io::driver::Handle::unpark (99 samples, 0.08%)mio::waker::Waker::wake (99 samples, 0.08%)mio::sys::unix::waker::fdbased::Waker::wake (99 samples, 0.08%)mio::sys::unix::waker::eventfd::WakerInternal::wake (99 samples, 0.08%)<&std::fs::File as std::io::Write>::write (99 samples, 0.08%)std::sys::pal::unix::fs::File::write (99 samples, 0.08%)std::sys::pal::unix::fd::FileDesc::write (99 samples, 0.08%)__GI___libc_write (99 samples, 0.08%)__GI___libc_write (99 samples, 0.08%)tokio::runtime::context::with_scheduler (1,615 samples, 1.23%)std::thread::local::LocalKey<T>::try_with (1,613 samples, 1.23%)tokio::runtime::context::with_scheduler::{{closure}} (1,612 samples, 1.23%)tokio::runtime::context::scoped::Scoped<T>::with (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (1,609 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (1,609 samples, 1.23%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (101 samples, 0.08%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (101 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_option_task_without_yield (1,647 samples, 1.25%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task (1,646 samples, 1.25%)tokio::runtime::scheduler::multi_thread::worker::with_current (1,646 samples, 1.25%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (23 samples, 0.02%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (18 samples, 0.01%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (104 samples, 0.08%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (60 samples, 0.05%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (57 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (49 samples, 0.04%)core::sync::atomic::AtomicU32::compare_exchange (38 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (38 samples, 0.03%)__memcpy_avx512_unaligned_erms (162 samples, 0.12%)__memcpy_avx512_unaligned_erms (34 samples, 0.03%)__GI___lll_lock_wake_private (127 samples, 0.10%)[unknown] (125 samples, 0.10%)[unknown] (124 samples, 0.09%)[unknown] (119 samples, 0.09%)[unknown] (110 samples, 0.08%)[unknown] (106 samples, 0.08%)[unknown] (87 samples, 0.07%)[unknown] (82 samples, 0.06%)[unknown] (51 samples, 0.04%)[unknown] (27 samples, 0.02%)[unknown] (19 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (77 samples, 0.06%)[unknown] (1,207 samples, 0.92%)[unknown] (1,146 samples, 0.87%)[unknown] (1,126 samples, 0.86%)[unknown] (1,091 samples, 0.83%)[unknown] (1,046 samples, 0.80%)[unknown] (962 samples, 0.73%)[unknown] (914 samples, 0.70%)[unknown] (848 samples, 0.65%)[unknown] (774 samples, 0.59%)[unknown] (580 samples, 0.44%)[unknown] (456 samples, 0.35%)[unknown] (305 samples, 0.23%)[unknown] (85 samples, 0.06%)__GI_mprotect (2,474 samples, 1.88%)_..[unknown] (2,457 samples, 1.87%)[..[unknown] (2,440 samples, 1.86%)[..[unknown] (2,436 samples, 1.86%)[..[unknown] (2,435 samples, 1.85%)[..[unknown] (2,360 samples, 1.80%)[..[unknown] (2,203 samples, 1.68%)[unknown] (1,995 samples, 1.52%)[unknown] (1,709 samples, 1.30%)[unknown] (1,524 samples, 1.16%)[unknown] (1,193 samples, 0.91%)[unknown] (865 samples, 0.66%)[unknown] (539 samples, 0.41%)[unknown] (259 samples, 0.20%)[unknown] (80 samples, 0.06%)[unknown] (29 samples, 0.02%)sysmalloc (3,786 samples, 2.88%)sy..grow_heap (2,509 samples, 1.91%)g.._int_malloc (4,038 samples, 3.08%)_in..unlink_chunk (31 samples, 0.02%)alloc::alloc::exchange_malloc (4,335 samples, 3.30%)all..<alloc::alloc::Global as core::alloc::Allocator>::allocate (4,329 samples, 3.30%)<al..alloc::alloc::Global::alloc_impl (4,329 samples, 3.30%)all..alloc::alloc::alloc (4,329 samples, 3.30%)all..__rdl_alloc (4,329 samples, 3.30%)__r..std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (4,329 samples, 3.30%)std..std::sys::pal::unix::alloc::aligned_malloc (4,329 samples, 3.30%)std..__posix_memalign (4,297 samples, 3.27%)__p..__posix_memalign (4,297 samples, 3.27%)__p.._mid_memalign (4,297 samples, 3.27%)_mi.._int_memalign (4,149 samples, 3.16%)_in..sysmalloc (18 samples, 0.01%)core::option::Option<T>::map (6,666 samples, 5.08%)core::..tokio::task::spawn::spawn_inner::{{closure}} (6,665 samples, 5.08%)tokio:..tokio::runtime::scheduler::Handle::spawn (6,665 samples, 5.08%)tokio:..tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (6,664 samples, 5.08%)tokio:..tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (6,661 samples, 5.07%)tokio:..tokio::runtime::task::list::OwnedTasks<S>::bind (4,692 samples, 3.57%)toki..tokio::runtime::task::new_task (4,579 samples, 3.49%)tok..tokio::runtime::task::raw::RawTask::new (4,579 samples, 3.49%)tok..tokio::runtime::task::core::Cell<T,S>::new (4,579 samples, 3.49%)tok..alloc::boxed::Box<T>::new (4,389 samples, 3.34%)all..tokio::runtime::context::current::with_current (7,636 samples, 5.82%)tokio::..std::thread::local::LocalKey<T>::try_with (7,635 samples, 5.81%)std::th..tokio::runtime::context::current::with_current::{{closure}} (7,188 samples, 5.47%)tokio::..tokio::task::spawn::spawn (7,670 samples, 5.84%)tokio::..tokio::task::spawn::spawn_inner (7,670 samples, 5.84%)tokio::..tokio::runtime::task::id::Id::next (24 samples, 0.02%)core::sync::atomic::AtomicU64::fetch_add (24 samples, 0.02%)core::sync::atomic::atomic_add (24 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (62,691 samples, 47.75%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (62,691 samples, 47.75%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (18,228 samples, 13.88%)torrust_tracker::serv..torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (18,226 samples, 13.88%)torrust_tracker::serv..torrust_tracker::servers::udp::server::Udp::spawn_request_processor (7,679 samples, 5.85%)torrust..__memcpy_avx512_unaligned_erms (38 samples, 0.03%)__memcpy_avx512_unaligned_erms (407 samples, 0.31%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (411 samples, 0.31%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (411 samples, 0.31%)tokio::runtime::task::core::Core<T,S>::poll (63,150 samples, 48.10%)tokio::runtime::task::core::Core<T,S>::polltokio::runtime::task::core::Core<T,S>::drop_future_or_output (459 samples, 0.35%)tokio::runtime::task::core::Core<T,S>::set_stage (459 samples, 0.35%)__memcpy_avx512_unaligned_erms (16 samples, 0.01%)__memcpy_avx512_unaligned_erms (398 samples, 0.30%)__memcpy_avx512_unaligned_erms (325 samples, 0.25%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (330 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (330 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::set_stage (731 samples, 0.56%)tokio::runtime::task::harness::poll_future (63,908 samples, 48.67%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (63,908 samples, 48.67%)std::panic::catch_unwindstd::panicking::try (63,908 samples, 48.67%)std::panicking::trystd::panicking::try::do_call (63,908 samples, 48.67%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (63,908 samples, 48.67%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()..tokio::runtime::task::harness::poll_future::{{closure}} (63,908 samples, 48.67%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::store_output (758 samples, 0.58%)tokio::runtime::coop::budget (65,027 samples, 49.53%)tokio::runtime::coop::budgettokio::runtime::coop::with_budget (65,027 samples, 49.53%)tokio::runtime::coop::with_budgettokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (65,009 samples, 49.51%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}}tokio::runtime::task::LocalNotified<S>::run (65,003 samples, 49.51%)tokio::runtime::task::LocalNotified<S>::runtokio::runtime::task::raw::RawTask::poll (65,003 samples, 49.51%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (64,538 samples, 49.15%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (64,493 samples, 49.12%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (63,919 samples, 48.68%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (93 samples, 0.07%)syscall (2,486 samples, 1.89%)s..[unknown] (2,424 samples, 1.85%)[..[unknown] (2,416 samples, 1.84%)[..[unknown] (2,130 samples, 1.62%)[unknown] (2,013 samples, 1.53%)[unknown] (1,951 samples, 1.49%)[unknown] (1,589 samples, 1.21%)[unknown] (1,415 samples, 1.08%)[unknown] (1,217 samples, 0.93%)[unknown] (820 samples, 0.62%)[unknown] (564 samples, 0.43%)[unknown] (360 samples, 0.27%)[unknown] (244 samples, 0.19%)[unknown] (194 samples, 0.15%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (339 samples, 0.26%)core::sync::atomic::AtomicUsize::fetch_add (337 samples, 0.26%)core::sync::atomic::atomic_add (337 samples, 0.26%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (364 samples, 0.28%)[unknown] (154 samples, 0.12%)[unknown] (152 samples, 0.12%)[unknown] (143 samples, 0.11%)[unknown] (139 samples, 0.11%)[unknown] (131 samples, 0.10%)[unknown] (123 samples, 0.09%)[unknown] (110 samples, 0.08%)[unknown] (80 samples, 0.06%)[unknown] (74 samples, 0.06%)[unknown] (65 samples, 0.05%)[unknown] (64 samples, 0.05%)[unknown] (47 samples, 0.04%)[unknown] (44 samples, 0.03%)[unknown] (43 samples, 0.03%)[unknown] (40 samples, 0.03%)[unknown] (26 samples, 0.02%)[unknown] (20 samples, 0.02%)__GI___libc_write (158 samples, 0.12%)__GI___libc_write (158 samples, 0.12%)mio::sys::unix::waker::eventfd::WakerInternal::wake (159 samples, 0.12%)<&std::fs::File as std::io::Write>::write (159 samples, 0.12%)std::sys::pal::unix::fs::File::write (159 samples, 0.12%)std::sys::pal::unix::fd::FileDesc::write (159 samples, 0.12%)tokio::runtime::driver::Handle::unpark (168 samples, 0.13%)tokio::runtime::driver::IoHandle::unpark (168 samples, 0.13%)tokio::runtime::io::driver::Handle::unpark (168 samples, 0.13%)mio::waker::Waker::wake (165 samples, 0.13%)mio::sys::unix::waker::fdbased::Waker::wake (165 samples, 0.13%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (68,159 samples, 51.91%)tokio::runtime::scheduler::multi_thread::worker::Context::run_tasktokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (3,024 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (3,023 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (3,022 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (171 samples, 0.13%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (171 samples, 0.13%)core::option::Option<T>::or_else (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::tune_global_queue_interval (53 samples, 0.04%)tokio::runtime::scheduler::multi_thread::stats::Stats::tuned_global_queue_interval (53 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (107 samples, 0.08%)__GI___libc_free (17 samples, 0.01%)_int_free (17 samples, 0.01%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Dying,K,V>::deallocating_end (18 samples, 0.01%)alloc::collections::btree::navigate::<impl alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>>::deallocating_end (18 samples, 0.01%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::LeafOrInternal>::deallocate_and_ascend (18 samples, 0.01%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (18 samples, 0.01%)alloc::alloc::dealloc (18 samples, 0.01%)__rdl_dealloc (18 samples, 0.01%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (18 samples, 0.01%)alloc::collections::btree::map::IntoIter<K,V,A>::dying_next (19 samples, 0.01%)tokio::runtime::task::Task<S>::shutdown (26 samples, 0.02%)tokio::runtime::task::raw::RawTask::shutdown (26 samples, 0.02%)tokio::runtime::task::raw::shutdown (26 samples, 0.02%)tokio::runtime::task::harness::Harness<T,S>::shutdown (26 samples, 0.02%)tokio::runtime::task::harness::cancel_task (26 samples, 0.02%)std::panic::catch_unwind (26 samples, 0.02%)std::panicking::try (26 samples, 0.02%)std::panicking::try::do_call (26 samples, 0.02%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (26 samples, 0.02%)core::ops::function::FnOnce::call_once (26 samples, 0.02%)tokio::runtime::task::harness::cancel_task::{{closure}} (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (26 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (26 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::core::Tracker> (26 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)core::ptr::drop_in_place<std::sync::rwlock::RwLock<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)core::mem::drop (26 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,NodeType>,alloc::collections::btree::node::marker::KV>::drop_key_val (24 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::assume_init_drop (24 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (24 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (21 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>> (20 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<torrust_tracker_torrent_repository::entry::Torrent>> (20 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker_torrent_repository::entry::Torrent> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::peer::Id,alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (20 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)core::mem::drop (20 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker_primitives::peer::Id,alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (20 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::pre_shutdown (33 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::close_and_shutdown_all (33 samples, 0.03%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (114 samples, 0.09%)alloc::sync::Arc<T,A>::inner (114 samples, 0.09%)core::ptr::non_null::NonNull<T>::as_ref (114 samples, 0.09%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (108 samples, 0.08%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (108 samples, 0.08%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (106 samples, 0.08%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (49 samples, 0.04%)alloc::sync::Arc<T,A>::inner (49 samples, 0.04%)core::ptr::non_null::NonNull<T>::as_ref (49 samples, 0.04%)core::num::<impl u32>::wrapping_sub (132 samples, 0.10%)core::sync::atomic::AtomicU64::load (40 samples, 0.03%)core::sync::atomic::atomic_load (40 samples, 0.03%)tokio::loom::std::atomic_u32::AtomicU32::unsync_load (48 samples, 0.04%)core::sync::atomic::AtomicU32::load (48 samples, 0.04%)core::sync::atomic::atomic_load (48 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (65 samples, 0.05%)alloc::sync::Arc<T,A>::inner (65 samples, 0.05%)core::ptr::non_null::NonNull<T>::as_ref (65 samples, 0.05%)core::num::<impl u32>::wrapping_sub (50 samples, 0.04%)core::sync::atomic::AtomicU32::load (55 samples, 0.04%)core::sync::atomic::atomic_load (55 samples, 0.04%)core::sync::atomic::AtomicU64::load (80 samples, 0.06%)core::sync::atomic::atomic_load (80 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::pack (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (666 samples, 0.51%)tokio::runtime::scheduler::multi_thread::queue::unpack (147 samples, 0.11%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (1,036 samples, 0.79%)tokio::runtime::scheduler::multi_thread::queue::unpack (46 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_searching (49 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_searching (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (2,414 samples, 1.84%)t..tokio::util::rand::FastRand::fastrand_n (24 samples, 0.02%)tokio::util::rand::FastRand::fastrand (24 samples, 0.02%)std::sys_common::backtrace::__rust_begin_short_backtrace (98,136 samples, 74.74%)std::sys_common::backtrace::__rust_begin_short_backtracetokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}} (98,136 samples, 74.74%)tokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}}tokio::runtime::blocking::pool::Inner::run (98,136 samples, 74.74%)tokio::runtime::blocking::pool::Inner::runtokio::runtime::blocking::pool::Task::run (98,042 samples, 74.67%)tokio::runtime::blocking::pool::Task::runtokio::runtime::task::UnownedTask<S>::run (98,042 samples, 74.67%)tokio::runtime::task::UnownedTask<S>::runtokio::runtime::task::raw::RawTask::poll (98,042 samples, 74.67%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (98,042 samples, 74.67%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (98,042 samples, 74.67%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (98,042 samples, 74.67%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::task::harness::poll_future (98,042 samples, 74.67%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (98,042 samples, 74.67%)std::panic::catch_unwindstd::panicking::try (98,042 samples, 74.67%)std::panicking::trystd::panicking::try::do_call (98,042 samples, 74.67%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (98,042 samples, 74.67%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncetokio::runtime::task::harness::poll_future::{{closure}} (98,042 samples, 74.67%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::poll (98,042 samples, 74.67%)tokio::runtime::task::core::Core<T,S>::polltokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (98,042 samples, 74.67%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (98,042 samples, 74.67%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (98,042 samples, 74.67%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::polltokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}}tokio::runtime::scheduler::multi_thread::worker::run (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::runtokio::runtime::context::runtime::enter_runtime (98,042 samples, 74.67%)tokio::runtime::context::runtime::enter_runtimetokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}tokio::runtime::context::set_scheduler (98,042 samples, 74.67%)tokio::runtime::context::set_schedulerstd::thread::local::LocalKey<T>::with (98,042 samples, 74.67%)std::thread::local::LocalKey<T>::withstd::thread::local::LocalKey<T>::try_with (98,042 samples, 74.67%)std::thread::local::LocalKey<T>::try_withtokio::runtime::context::set_scheduler::{{closure}} (98,042 samples, 74.67%)tokio::runtime::context::set_scheduler::{{closure}}tokio::runtime::context::scoped::Scoped<T>::set (98,042 samples, 74.67%)tokio::runtime::context::scoped::Scoped<T>::settokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}}tokio::runtime::scheduler::multi_thread::worker::Context::run (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::Context::runstd::panic::catch_unwind (98,137 samples, 74.74%)std::panic::catch_unwindstd::panicking::try (98,137 samples, 74.74%)std::panicking::trystd::panicking::try::do_call (98,137 samples, 74.74%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (98,137 samples, 74.74%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncestd::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}} (98,137 samples, 74.74%)std::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}}<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (98,139 samples, 74.74%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (98,139 samples, 74.74%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_oncecore::ops::function::FnOnce::call_once{{vtable.shim}} (98,139 samples, 74.74%)core::ops::function::FnOnce::call_once{{vtable.shim}}std::thread::Builder::spawn_unchecked_::{{closure}} (98,139 samples, 74.74%)std::thread::Builder::spawn_unchecked_::{{closure}}clone3 (98,205 samples, 74.79%)clone3start_thread (98,205 samples, 74.79%)start_threadstd::sys::pal::unix::thread::Thread::new::thread_start (98,158 samples, 74.76%)std::sys::pal::unix::thread::Thread::new::thread_startcore::ptr::drop_in_place<std::sys::pal::unix::stack_overflow::Handler> (19 samples, 0.01%)<std::sys::pal::unix::stack_overflow::Handler as core::ops::drop::Drop>::drop (19 samples, 0.01%)std::sys::pal::unix::stack_overflow::imp::drop_handler (19 samples, 0.01%)__GI_munmap (19 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (17 samples, 0.01%)[unknown] (16 samples, 0.01%)core::fmt::Formatter::pad_integral (112 samples, 0.09%)core::fmt::Formatter::pad_integral::write_prefix (59 samples, 0.04%)core::fmt::Formatter::pad_integral (16 samples, 0.01%)core::fmt::write (20 samples, 0.02%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (19 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (51 samples, 0.04%)rand_chacha::guts::round (18 samples, 0.01%)rand_chacha::guts::refill_wide::impl_avx2 (26 samples, 0.02%)rand_chacha::guts::refill_wide::fn_impl (26 samples, 0.02%)rand_chacha::guts::refill_wide_impl (26 samples, 0.02%)rand_chacha::guts::refill_wide (14 samples, 0.01%)std_detect::detect::arch::x86::__is_feature_detected::avx2 (14 samples, 0.01%)std_detect::detect::check_for (14 samples, 0.01%)std_detect::detect::cache::test (14 samples, 0.01%)std_detect::detect::cache::Cache::test (14 samples, 0.01%)core::sync::atomic::AtomicUsize::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)core::cell::RefCell<T>::borrow_mut (81 samples, 0.06%)core::cell::RefCell<T>::try_borrow_mut (81 samples, 0.06%)core::cell::BorrowRefMut::new (81 samples, 0.06%)std::sys::pal::unix::time::Timespec::now (164 samples, 0.12%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (106 samples, 0.08%)tokio::runtime::coop::budget (105 samples, 0.08%)tokio::runtime::coop::with_budget (105 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (96 samples, 0.07%)std::sys::pal::unix::time::Timespec::sub_timespec (35 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::lock_contended (15 samples, 0.01%)syscall (90 samples, 0.07%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (21 samples, 0.02%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run (61 samples, 0.05%)tokio::runtime::context::runtime::enter_runtime (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (61 samples, 0.05%)tokio::runtime::context::set_scheduler (61 samples, 0.05%)std::thread::local::LocalKey<T>::with (61 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (61 samples, 0.05%)tokio::runtime::context::set_scheduler::{{closure}} (61 samples, 0.05%)tokio::runtime::context::scoped::Scoped<T>::set (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Context::run (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (19 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (17 samples, 0.01%)tokio::runtime::context::CONTEXT::__getit (14 samples, 0.01%)core::cell::Cell<T>::get (14 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (22 samples, 0.02%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (22 samples, 0.02%)tokio::runtime::context::set_current_task_id (22 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (22 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (112 samples, 0.09%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (111 samples, 0.08%)tokio::runtime::task::harness::poll_future (125 samples, 0.10%)std::panic::catch_unwind (125 samples, 0.10%)std::panicking::try (125 samples, 0.10%)std::panicking::try::do_call (125 samples, 0.10%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (125 samples, 0.10%)tokio::runtime::task::harness::poll_future::{{closure}} (125 samples, 0.10%)tokio::runtime::task::core::Core<T,S>::poll (125 samples, 0.10%)tokio::runtime::task::raw::poll (157 samples, 0.12%)tokio::runtime::task::harness::Harness<T,S>::poll (135 samples, 0.10%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (135 samples, 0.10%)tokio::runtime::time::Driver::park_internal (15 samples, 0.01%)torrust_tracker::bootstrap::logging::INIT (17 samples, 0.01%)__memcpy_avx512_unaligned_erms (397 samples, 0.30%)_int_free (24 samples, 0.02%)_int_malloc (132 samples, 0.10%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE::META (570 samples, 0.43%)__GI___lll_lock_wait_private (22 samples, 0.02%)futex_wait (14 samples, 0.01%)__memcpy_avx512_unaligned_erms (299 samples, 0.23%)_int_free (16 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE (361 samples, 0.27%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (41 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (23 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (53 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (14 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (63 samples, 0.05%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (21 samples, 0.02%)__GI___libc_malloc (18 samples, 0.01%)alloc::vec::Vec<T>::with_capacity (116 samples, 0.09%)alloc::vec::Vec<T,A>::with_capacity_in (116 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (116 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (116 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (116 samples, 0.09%)alloc::alloc::Global::alloc_impl (116 samples, 0.09%)alloc::alloc::alloc (116 samples, 0.09%)__rdl_alloc (116 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (116 samples, 0.09%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (53 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (53 samples, 0.04%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (53 samples, 0.04%)_int_malloc (21 samples, 0.02%)[unknown] (36 samples, 0.03%)[unknown] (16 samples, 0.01%)core::mem::zeroed (27 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::zeroed (27 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::write_bytes (27 samples, 0.02%)core::intrinsics::write_bytes (27 samples, 0.02%)[unknown] (27 samples, 0.02%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (64 samples, 0.05%)mio::net::udp::UdpSocket::recv_from (49 samples, 0.04%)mio::io_source::IoSource<T>::do_io (49 samples, 0.04%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (49 samples, 0.04%)mio::net::udp::UdpSocket::recv_from::{{closure}} (49 samples, 0.04%)std::net::udp::UdpSocket::recv_from (49 samples, 0.04%)std::sys_common::net::UdpSocket::recv_from (49 samples, 0.04%)std::sys::pal::unix::net::Socket::recv_from (49 samples, 0.04%)std::sys::pal::unix::net::Socket::recv_from_with_flags (49 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (271 samples, 0.21%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (143 samples, 0.11%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (141 samples, 0.11%)tokio::runtime::io::registration::Registration::clear_readiness (15 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::clear_readiness (15 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (15 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (359 samples, 0.27%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (346 samples, 0.26%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (39 samples, 0.03%)tokio::task::spawn::spawn (39 samples, 0.03%)tokio::task::spawn::spawn_inner (39 samples, 0.03%)tokio::runtime::context::current::with_current (39 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (39 samples, 0.03%)tokio::runtime::context::current::with_current::{{closure}} (39 samples, 0.03%)core::option::Option<T>::map (39 samples, 0.03%)tokio::task::spawn::spawn_inner::{{closure}} (39 samples, 0.03%)tokio::runtime::scheduler::Handle::spawn (39 samples, 0.03%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (39 samples, 0.03%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (39 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::bind (34 samples, 0.03%)all (131,301 samples, 100%)tokio-runtime-w (131,061 samples, 99.82%)tokio-runtime-w \ No newline at end of file From 9e01f7fa750c023507522a43f2ec70fc5fca64a6 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 7 May 2024 20:01:15 +0200 Subject: [PATCH 0311/1297] dev: fix udp ring-buffer not looping My previous version would be limited to a single thread, as `push_overwrite` would keep on returning the last element when the ring-buffer was full. Now the ring-buffer is pre-filled and is looped over with a mutating iterator. New handles are progressively swapped-in when the old entries are finished. Note: I think that this implementation can be replaced with a standard vector with the same effect. --- src/servers/udp/server.rs | 77 +++++++++++++++++++++++++++++++++------ 1 file changed, 66 insertions(+), 11 deletions(-) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index fc2d02a59..f7092f377 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -24,7 +24,7 @@ use std::sync::Arc; use aquatic_udp_protocol::Response; use derive_more::Constructor; use log::{debug, error, info, trace}; -use ringbuf::traits::{Consumer, Observer, RingBuffer}; +use ringbuf::traits::{Consumer, Observer, Producer}; use ringbuf::StaticRb; use tokio::net::UdpSocket; use tokio::sync::oneshot; @@ -202,11 +202,23 @@ impl Launcher { } } -#[derive(Default)] struct ActiveRequests { rb: StaticRb, // the number of requests we handle at the same time. } +impl ActiveRequests { + /// Creates a new [`ActiveRequests`] filled with finished tasks. + async fn new() -> Self { + let mut rb = StaticRb::default(); + + let () = while rb.try_push(tokio::task::spawn_blocking(|| ()).abort_handle()).is_ok() {}; + + task::yield_now().await; + + Self { rb } + } +} + impl std::fmt::Debug for ActiveRequests { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let (left, right) = &self.rb.as_slices(); @@ -280,15 +292,22 @@ impl Udp { let tracker = tracker.clone(); let socket = socket.clone(); - let reqs = &mut ActiveRequests::default(); + let reqs = &mut ActiveRequests::new().await; - // Main Waiting Loop, awaits on async [`receive_request`]. loop { - if let Some(h) = reqs.rb.push_overwrite( - Self::spawn_request_processor(Self::receive_request(socket.clone()).await, tracker.clone(), socket.clone()) - .abort_handle(), - ) { - if !h.is_finished() { + task::yield_now().await; + for h in reqs.rb.iter_mut() { + if h.is_finished() { + std::mem::swap( + h, + &mut Self::spawn_request_processor( + Self::receive_request(socket.clone()).await, + tracker.clone(), + socket.clone(), + ) + .abort_handle(), + ); + } else { // the task is still running, lets yield and give it a chance to flush. tokio::task::yield_now().await; @@ -299,6 +318,9 @@ impl Udp { tracing::span!( target: "UDP TRACKER", tracing::Level::WARN, "request-aborted", server_socket_addr = %server_socket_addr); + + // force-break a single thread, then loop again. + break; } } } @@ -396,13 +418,46 @@ mod tests { use std::sync::Arc; use std::time::Duration; - use tokio::time::sleep; + use ringbuf::traits::{Consumer, Observer, RingBuffer}; use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; + use super::ActiveRequests; use crate::bootstrap::app::initialize_with_configuration; use crate::servers::registar::Registar; use crate::servers::udp::server::{Launcher, UdpServer}; + #[tokio::test] + async fn it_should_return_to_the_start_of_the_ring_buffer() { + let mut a_req = ActiveRequests::new().await; + + tokio::time::sleep(Duration::from_millis(10)).await; + + let mut count: usize = 0; + let cap: usize = a_req.rb.capacity().into(); + + // Add a single pending task to check that the ring-buffer is looping correctly. + a_req + .rb + .push_overwrite(tokio::task::spawn(std::future::pending::<()>()).abort_handle()); + + count += 1; + + for _ in 0..2 { + for h in a_req.rb.iter() { + let first = count % cap; + println!("{count},{first},{}", h.is_finished()); + + if first == 0 { + assert!(!h.is_finished()); + } else { + assert!(h.is_finished()); + } + + count += 1; + } + } + } + #[tokio::test] async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_mode_public()); @@ -423,7 +478,7 @@ mod tests { .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); - sleep(Duration::from_secs(1)).await; + tokio::time::sleep(Duration::from_secs(1)).await; assert_eq!(stopped.state.launcher.bind_to, bind_to); } From 7da52b1c796b17ebf8208185115eb0f566e61b03 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Apr 2024 12:24:31 +0100 Subject: [PATCH 0312/1297] chore(deps): add dependency figment It will replace the custom code for configuration inyection. --- Cargo.lock | 37 +++++++++++++++++++++++++++++++++++++ Cargo.toml | 1 + 2 files changed, 38 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index bd0e36c3a..5972c250a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -366,6 +366,15 @@ dependencies = [ "syn 2.0.61", ] +[[package]] +name = "atomic" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d818003e740b63afc82337e3160717f4f63078720a810b7b903e70a5d1d2994" +dependencies = [ + "bytemuck", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -696,6 +705,12 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "bytemuck" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d6d68c57235a3a081186990eca2867354726650f42f7516ca50c28d6281fd15" + [[package]] name = "byteorder" version = "1.5.0" @@ -1334,6 +1349,18 @@ dependencies = [ "log", ] +[[package]] +name = "figment" +version = "0.10.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d032832d74006f99547004d49410a4b4218e4c33382d56ca3ff89df74f86b953" +dependencies = [ + "atomic", + "serde", + "uncased", + "version_check", +] + [[package]] name = "flate2" version = "1.0.30" @@ -3984,6 +4011,7 @@ dependencies = [ "dashmap", "derive_more", "fern", + "figment", "futures", "hex-literal", "hyper", @@ -4222,6 +4250,15 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" +[[package]] +name = "uncased" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" +dependencies = [ + "version_check", +] + [[package]] name = "unicode-bidi" version = "0.3.15" diff --git a/Cargo.toml b/Cargo.toml index cbfdc7697..2be3455b8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,6 +44,7 @@ crossbeam-skiplist = "0.1" dashmap = "5.5.3" derive_more = "0" fern = "0" +figment = "0.10.18" futures = "0" hex-literal = "0" hyper = "1" From f0e07217a52dddfcfd0170370db1177f7b31abe1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Apr 2024 12:56:44 +0100 Subject: [PATCH 0313/1297] test: remove broken example in rustdoc --- packages/configuration/src/lib.rs | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index ca873f3cd..660a90701 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -229,6 +229,8 @@ //! [health_check_api] //! bind_address = "127.0.0.1:1313" //!``` +pub mod v1; + use std::collections::HashMap; use std::net::IpAddr; use std::str::FromStr; @@ -263,15 +265,6 @@ pub struct Info { impl Info { /// Build Configuration Info /// - /// # Examples - /// - /// ``` - /// use torrust_tracker_configuration::Info; - /// - /// let result = Info::new(env_var_config, env_var_path_config, default_path_config, env_var_api_admin_token); - /// assert_eq!(result, ); - /// ``` - /// /// # Errors /// /// Will return `Err` if unable to obtain a configuration. From 157807ca3144ef69de344f0570e9571c4f0e9492 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Apr 2024 12:57:54 +0100 Subject: [PATCH 0314/1297] chore(deps): enable figment features: env, toml, test --- Cargo.lock | 53 +++++++++++++++++++++++++++++++ packages/configuration/Cargo.toml | 1 + 2 files changed, 54 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 5972c250a..600914da7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1356,7 +1356,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d032832d74006f99547004d49410a4b4218e4c33382d56ca3ff89df74f86b953" dependencies = [ "atomic", + "parking_lot", + "pear", "serde", + "tempfile", + "toml", "uncased", "version_check", ] @@ -1904,6 +1908,12 @@ dependencies = [ "serde", ] +[[package]] +name = "inlinable_string" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" + [[package]] name = "instant" version = "0.1.12" @@ -2583,6 +2593,29 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" +[[package]] +name = "pear" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdeeaa00ce488657faba8ebf44ab9361f9365a97bd39ffb8a60663f57ff4b467" +dependencies = [ + "inlinable_string", + "pear_codegen", + "yansi", +] + +[[package]] +name = "pear_codegen" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bab5b985dc082b345f812b7df84e1bef27e7207b39e448439ba8bd69c93f147" +dependencies = [ + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn 2.0.60", +] + [[package]] name = "pem" version = "2.0.1" @@ -2880,6 +2913,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.60", + "version_check", + "yansi", +] + [[package]] name = "ptr_meta" version = "0.1.4" @@ -4065,6 +4111,7 @@ version = "3.0.0-alpha.12-develop" dependencies = [ "config", "derive_more", + "figment", "serde", "serde_with", "thiserror", @@ -4669,6 +4716,12 @@ dependencies = [ "linked-hash-map", ] +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + [[package]] name = "zerocopy" version = "0.7.34" diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 102177816..e5335d416 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -17,6 +17,7 @@ version.workspace = true [dependencies] config = "0" derive_more = "0" +figment = { version = "0.10.18", features = ["env", "test", "toml"] } serde = { version = "1", features = ["derive"] } serde_with = "3" thiserror = "1" From 636e779242e15965c8bbdefbb1142c3356dfa4b6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Apr 2024 14:00:20 +0100 Subject: [PATCH 0315/1297] refactor: create new configuration v1 mod with figment - Clone config strcuctures into a new mod `v1`. - Introduce versioning for configuration API. - Split config sections into submodules. TODO: - Still using root mod types in production. - Not using figment to build config in production. --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 600914da7..1b4c2a4e7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2613,7 +2613,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.60", + "syn 2.0.61", ] [[package]] @@ -2921,7 +2921,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.60", + "syn 2.0.61", "version_check", "yansi", ] From e7d344c5f8af51cfff7af4abf71db3a08f039096 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Apr 2024 14:00:20 +0100 Subject: [PATCH 0316/1297] refactor: create new configuration v1 mod with figment - Clone config strcuctures into a new mod `v1`. - Introduce versioning for configuration API. - Split config sections into submodules. TODO: - Still using root mod types in production. - Not using figment to build config in production. --- .../configuration/src/v1/health_check_api.rs | 13 + packages/configuration/src/v1/http_tracker.rs | 23 + packages/configuration/src/v1/mod.rs | 433 ++++++++++++++++++ packages/configuration/src/v1/tracker_api.rs | 32 ++ packages/configuration/src/v1/udp_tracker.rs | 12 + 5 files changed, 513 insertions(+) create mode 100644 packages/configuration/src/v1/health_check_api.rs create mode 100644 packages/configuration/src/v1/http_tracker.rs create mode 100644 packages/configuration/src/v1/mod.rs create mode 100644 packages/configuration/src/v1/tracker_api.rs create mode 100644 packages/configuration/src/v1/udp_tracker.rs diff --git a/packages/configuration/src/v1/health_check_api.rs b/packages/configuration/src/v1/health_check_api.rs new file mode 100644 index 000000000..f7b15249c --- /dev/null +++ b/packages/configuration/src/v1/health_check_api.rs @@ -0,0 +1,13 @@ +use serde::{Deserialize, Serialize}; +use serde_with::serde_as; + +/// Configuration for the Health Check API. +#[serde_as] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct HealthCheckApi { + /// The address the API will bind to. + /// The format is `ip:port`, for example `127.0.0.1:1313`. If you want to + /// listen to all interfaces, use `0.0.0.0`. If you want the operating + /// system to choose a random port, use port `0`. + pub bind_address: String, +} diff --git a/packages/configuration/src/v1/http_tracker.rs b/packages/configuration/src/v1/http_tracker.rs new file mode 100644 index 000000000..4c88feb9c --- /dev/null +++ b/packages/configuration/src/v1/http_tracker.rs @@ -0,0 +1,23 @@ +use serde::{Deserialize, Serialize}; +use serde_with::{serde_as, NoneAsEmptyString}; + +/// Configuration for each HTTP tracker. +#[serde_as] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct HttpTracker { + /// Weather the HTTP tracker is enabled or not. + pub enabled: bool, + /// The address the tracker will bind to. + /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to + /// listen to all interfaces, use `0.0.0.0`. If you want the operating + /// system to choose a random port, use port `0`. + pub bind_address: String, + /// Weather the HTTP tracker will use SSL or not. + pub ssl_enabled: bool, + /// Path to the SSL certificate file. Only used if `ssl_enabled` is `true`. + #[serde_as(as = "NoneAsEmptyString")] + pub ssl_cert_path: Option, + /// Path to the SSL key file. Only used if `ssl_enabled` is `true`. + #[serde_as(as = "NoneAsEmptyString")] + pub ssl_key_path: Option, +} diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs new file mode 100644 index 000000000..815d74e40 --- /dev/null +++ b/packages/configuration/src/v1/mod.rs @@ -0,0 +1,433 @@ +//! Configuration data structures for [Torrust Tracker](https://docs.rs/torrust-tracker). +//! +//! This module contains the configuration data structures for the +//! Torrust Tracker, which is a `BitTorrent` tracker server. +//! +//! The configuration is loaded from a [TOML](https://toml.io/en/) file +//! `tracker.toml` in the project root folder or from an environment variable +//! with the same content as the file. +//! +//! Configuration can not only be loaded from a file, but also from an +//! environment variable `TORRUST_TRACKER_CONFIG`. This is useful when running +//! the tracker in a Docker container or environments where you do not have a +//! persistent storage or you cannot inject a configuration file. Refer to +//! [`Torrust Tracker documentation`](https://docs.rs/torrust-tracker) for more +//! information about how to pass configuration to the tracker. +//! +//! When you run the tracker without providing the configuration via a file or +//! env var, the default configuration is used. +//! +//! # Table of contents +//! +//! - [Sections](#sections) +//! - [Port binding](#port-binding) +//! - [TSL support](#tsl-support) +//! - [Generating self-signed certificates](#generating-self-signed-certificates) +//! - [Default configuration](#default-configuration) +//! +//! ## Sections +//! +//! Each section in the toml structure is mapped to a data structure. For +//! example, the `[http_api]` section (configuration for the tracker HTTP API) +//! is mapped to the [`HttpApi`] structure. +//! +//! > **NOTICE**: some sections are arrays of structures. For example, the +//! > `[[udp_trackers]]` section is an array of [`UdpTracker`] since +//! > you can have multiple running UDP trackers bound to different ports. +//! +//! Please refer to the documentation of each structure for more information +//! about each section. +//! +//! - [`Core configuration`](crate::v1::Configuration) +//! - [`HTTP API configuration`](crate::v1::tracker_api::HttpApi) +//! - [`HTTP Tracker configuration`](crate::v1::http_tracker::HttpTracker) +//! - [`UDP Tracker configuration`](crate::v1::udp_tracker::UdpTracker) +//! - [`Health Check API configuration`](crate::v1::health_check_api::HealthCheckApi) +//! +//! ## Port binding +//! +//! For the API, HTTP and UDP trackers you can bind to a random port by using +//! port `0`. For example, if you want to bind to a random port on all +//! interfaces, use `0.0.0.0:0`. The OS will choose a random free port. +//! +//! ## TSL support +//! +//! For the API and HTTP tracker you can enable TSL by setting `ssl_enabled` to +//! `true` and setting the paths to the certificate and key files. +//! +//! Typically, you will have a `storage` directory like the following: +//! +//! ```text +//! storage/ +//! ├── config.toml +//! └── tracker +//! ├── etc +//! │ └── tracker.toml +//! ├── lib +//! │ ├── database +//! │ │ ├── sqlite3.db +//! │ │ └── sqlite.db +//! │ └── tls +//! │ ├── localhost.crt +//! │ └── localhost.key +//! └── log +//! ``` +//! +//! where the application stores all the persistent data. +//! +//! Alternatively, you could setup a reverse proxy like Nginx or Apache to +//! handle the SSL/TLS part and forward the requests to the tracker. If you do +//! that, you should set [`on_reverse_proxy`](crate::Configuration::on_reverse_proxy) +//! to `true` in the configuration file. It's out of scope for this +//! documentation to explain in detail how to setup a reverse proxy, but the +//! configuration file should be something like this: +//! +//! For [NGINX](https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/): +//! +//! ```text +//! # HTTPS only (with SSL - force redirect to HTTPS) +//! +//! server { +//! listen 80; +//! server_name tracker.torrust.com; +//! +//! return 301 https://$host$request_uri; +//! } +//! +//! server { +//! listen 443; +//! server_name tracker.torrust.com; +//! +//! ssl_certificate CERT_PATH +//! ssl_certificate_key CERT_KEY_PATH; +//! +//! location / { +//! proxy_set_header X-Forwarded-For $remote_addr; +//! proxy_pass http://127.0.0.1:6969; +//! } +//! } +//! ``` +//! +//! For [Apache](https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html): +//! +//! ```text +//! # HTTPS only (with SSL - force redirect to HTTPS) +//! +//! +//! ServerAdmin webmaster@tracker.torrust.com +//! ServerName tracker.torrust.com +//! +//! +//! RewriteEngine on +//! RewriteCond %{HTTPS} off +//! RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] +//! +//! +//! +//! +//! +//! ServerAdmin webmaster@tracker.torrust.com +//! ServerName tracker.torrust.com +//! +//! +//! Order allow,deny +//! Allow from all +//! +//! +//! ProxyPreserveHost On +//! ProxyRequests Off +//! AllowEncodedSlashes NoDecode +//! +//! ProxyPass / http://localhost:3000/ +//! ProxyPassReverse / http://localhost:3000/ +//! ProxyPassReverse / http://tracker.torrust.com/ +//! +//! RequestHeader set X-Forwarded-Proto "https" +//! RequestHeader set X-Forwarded-Port "443" +//! +//! ErrorLog ${APACHE_LOG_DIR}/tracker.torrust.com-error.log +//! CustomLog ${APACHE_LOG_DIR}/tracker.torrust.com-access.log combined +//! +//! SSLCertificateFile CERT_PATH +//! SSLCertificateKeyFile CERT_KEY_PATH +//! +//! +//! ``` +//! +//! ## Generating self-signed certificates +//! +//! For testing purposes, you can use self-signed certificates. +//! +//! Refer to [Let's Encrypt - Certificates for localhost](https://letsencrypt.org/docs/certificates-for-localhost/) +//! for more information. +//! +//! Running the following command will generate a certificate (`localhost.crt`) +//! and key (`localhost.key`) file in your current directory: +//! +//! ```s +//! openssl req -x509 -out localhost.crt -keyout localhost.key \ +//! -newkey rsa:2048 -nodes -sha256 \ +//! -subj '/CN=localhost' -extensions EXT -config <( \ +//! printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth") +//! ``` +//! +//! You can then use the generated files in the configuration file: +//! +//! ```s +//! [[http_trackers]] +//! enabled = true +//! ... +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" +//! +//! [http_api] +//! enabled = true +//! ... +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" +//! ``` +//! +//! ## Default configuration +//! +//! The default configuration is: +//! +//! ```toml +//! log_level = "info" +//! mode = "public" +//! db_driver = "Sqlite3" +//! db_path = "./storage/tracker/lib/database/sqlite3.db" +//! announce_interval = 120 +//! min_announce_interval = 120 +//! on_reverse_proxy = false +//! external_ip = "0.0.0.0" +//! tracker_usage_statistics = true +//! persistent_torrent_completed_stat = false +//! max_peer_timeout = 900 +//! inactive_peer_cleanup_interval = 600 +//! remove_peerless_torrents = true +//! +//! [[udp_trackers]] +//! enabled = false +//! bind_address = "0.0.0.0:6969" +//! +//! [[http_trackers]] +//! enabled = false +//! bind_address = "0.0.0.0:7070" +//! ssl_enabled = false +//! ssl_cert_path = "" +//! ssl_key_path = "" +//! +//! [http_api] +//! enabled = true +//! bind_address = "127.0.0.1:1212" +//! ssl_enabled = false +//! ssl_cert_path = "" +//! ssl_key_path = "" +//! +//! [http_api.access_tokens] +//! admin = "MyAccessToken" +//! [health_check_api] +//! bind_address = "127.0.0.1:1313" +//!``` +pub mod health_check_api; +pub mod http_tracker; +pub mod tracker_api; +pub mod udp_tracker; + +use serde::{Deserialize, Serialize}; +use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; + +use self::health_check_api::HealthCheckApi; +use self::http_tracker::HttpTracker; +use self::tracker_api::HttpApi; +use self::udp_tracker::UdpTracker; +use crate::AnnouncePolicy; + +/// 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, + /// Tracker mode. See [`TrackerMode`] for more information. + pub mode: TrackerMode, + + // Database configuration + /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. + pub db_driver: DatabaseDriver, + /// Database connection string. The format depends on the database driver. + /// For `Sqlite3`, the format is `path/to/database.db`, for example: + /// `./storage/tracker/lib/database/sqlite3.db`. + /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for + /// example: `root:password@localhost:3306/torrust`. + pub db_path: String, + + /// See [`AnnouncePolicy::interval`] + pub announce_interval: u32, + + /// See [`AnnouncePolicy::interval_min`] + pub min_announce_interval: u32, + /// Weather the tracker is behind a reverse proxy or not. + /// If the tracker is behind a reverse proxy, the `X-Forwarded-For` header + /// sent from the proxy will be used to get the client's IP address. + pub on_reverse_proxy: bool, + /// The external IP address of the tracker. If the client is using a + /// loopback IP address, this IP address will be used instead. If the peer + /// 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, + /// 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. + /// Refer to the [`Tracker`](https://docs.rs/torrust-tracker) for more + /// information about the collected metrics. + pub tracker_usage_statistics: bool, + /// If enabled the tracker will persist the number of completed downloads. + /// That's how many times a torrent has been downloaded completely. + pub persistent_torrent_completed_stat: bool, + + // Cleanup job configuration + /// Maximum time in seconds that a peer can be inactive before being + /// considered an inactive peer. If a peer is inactive for more than this + /// time, it will be removed from the torrent peer list. + pub max_peer_timeout: u32, + /// Interval in seconds that the cleanup job will run to remove inactive + /// peers from the torrent peer list. + pub inactive_peer_cleanup_interval: u64, + /// If enabled, the tracker will remove torrents that have no peers. + /// The clean up torrent job runs every `inactive_peer_cleanup_interval` + /// seconds and it removes inactive peers. Eventually, the peer list of a + /// torrent could be empty and the torrent will be removed if this option is + /// enabled. + pub remove_peerless_torrents: bool, + + // Server jobs configuration + /// The list of UDP trackers the tracker is running. Each UDP tracker + /// represents a UDP server that the tracker is running and it has its own + /// configuration. + pub udp_trackers: Vec, + /// The list of HTTP trackers the tracker is running. Each HTTP tracker + /// represents a HTTP server that the tracker is running and it has its own + /// configuration. + pub http_trackers: Vec, + /// The HTTP API configuration. + pub http_api: HttpApi, + /// The Health Check API configuration. + pub health_check_api: HealthCheckApi, +} + +impl Default for Configuration { + fn default() -> Self { + let announce_policy = AnnouncePolicy::default(); + + let mut configuration = Configuration { + log_level: Option::from(String::from("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")), + tracker_usage_statistics: true, + persistent_torrent_completed_stat: false, + inactive_peer_cleanup_interval: 600, + remove_peerless_torrents: true, + udp_trackers: Vec::new(), + http_trackers: Vec::new(), + http_api: HttpApi { + enabled: true, + bind_address: String::from("127.0.0.1:1212"), + ssl_enabled: false, + ssl_cert_path: None, + ssl_key_path: None, + access_tokens: [(String::from("admin"), String::from("MyAccessToken"))] + .iter() + .cloned() + .collect(), + }, + health_check_api: HealthCheckApi { + bind_address: String::from("127.0.0.1:1313"), + }, + }; + configuration.udp_trackers.push(UdpTracker { + enabled: false, + bind_address: String::from("0.0.0.0:6969"), + }); + configuration.http_trackers.push(HttpTracker { + enabled: false, + bind_address: String::from("0.0.0.0:7070"), + ssl_enabled: false, + ssl_cert_path: None, + ssl_key_path: None, + }); + configuration + } +} + +#[cfg(test)] +mod tests { + use figment::providers::{Format, Toml}; + use figment::Figment; + + use crate::v1::Configuration; + + #[test] + fn configuration_should_be_loaded_from_a_toml_config_file() { + figment::Jail::expect_with(|jail| { + jail.create_file( + "Config.toml", + r#" + log_level = "info" + mode = "public" + db_driver = "Sqlite3" + db_path = "./storage/tracker/lib/database/sqlite3.db" + announce_interval = 120 + min_announce_interval = 120 + on_reverse_proxy = false + external_ip = "0.0.0.0" + tracker_usage_statistics = true + persistent_torrent_completed_stat = false + max_peer_timeout = 900 + inactive_peer_cleanup_interval = 600 + remove_peerless_torrents = true + + [[udp_trackers]] + enabled = false + bind_address = "0.0.0.0:6969" + + [[http_trackers]] + enabled = false + bind_address = "0.0.0.0:7070" + ssl_enabled = false + ssl_cert_path = "" + ssl_key_path = "" + + [http_api] + enabled = true + bind_address = "127.0.0.1:1212" + ssl_enabled = false + ssl_cert_path = "" + ssl_key_path = "" + + [http_api.access_tokens] + admin = "MyAccessToken" + + [health_check_api] + bind_address = "127.0.0.1:1313" + "#, + )?; + + let figment = Figment::new().merge(Toml::file("Config.toml")); + + let config: Configuration = figment.extract()?; + + assert_eq!(config, Configuration::default()); + + Ok(()) + }); + } +} diff --git a/packages/configuration/src/v1/tracker_api.rs b/packages/configuration/src/v1/tracker_api.rs new file mode 100644 index 000000000..6cda9b437 --- /dev/null +++ b/packages/configuration/src/v1/tracker_api.rs @@ -0,0 +1,32 @@ +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; +use serde_with::{serde_as, NoneAsEmptyString}; + +pub type AccessTokens = HashMap; + +/// Configuration for the HTTP API. +#[serde_as] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct HttpApi { + /// Weather the HTTP API is enabled or not. + pub enabled: bool, + /// The address the tracker will bind to. + /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to + /// listen to all interfaces, use `0.0.0.0`. If you want the operating + /// system to choose a random port, use port `0`. + pub bind_address: String, + /// Weather the HTTP API will use SSL or not. + pub ssl_enabled: bool, + /// Path to the SSL certificate file. Only used if `ssl_enabled` is `true`. + #[serde_as(as = "NoneAsEmptyString")] + pub ssl_cert_path: Option, + /// Path to the SSL key file. Only used if `ssl_enabled` is `true`. + #[serde_as(as = "NoneAsEmptyString")] + pub ssl_key_path: Option, + /// Access tokens for the HTTP API. The key is a label identifying the + /// token and the value is the token itself. The token is used to + /// authenticate the user. All tokens are valid for all endpoints and have + /// the all permissions. + pub access_tokens: AccessTokens, +} diff --git a/packages/configuration/src/v1/udp_tracker.rs b/packages/configuration/src/v1/udp_tracker.rs new file mode 100644 index 000000000..b304054c3 --- /dev/null +++ b/packages/configuration/src/v1/udp_tracker.rs @@ -0,0 +1,12 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct UdpTracker { + /// Weather the UDP tracker is enabled or not. + pub enabled: bool, + /// The address the tracker will bind to. + /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to + /// listen to all interfaces, use `0.0.0.0`. If you want the operating + /// system to choose a random port, use port `0`. + pub bind_address: String, +} From 002fb306087919c874d0d3296d0306a083eb62f6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 May 2024 12:57:14 +0100 Subject: [PATCH 0317/1297] refactor: reexport config versioned config types This is part of the migration to Figment in the configuration. This expose new versioned types (version 1). However, those types still used the old Config crate. Replacement by Figment has not been done yet. --- packages/configuration/src/lib.rs | 536 +------------------ packages/configuration/src/v1/mod.rs | 109 +++- packages/configuration/src/v1/tracker_api.rs | 6 + 3 files changed, 123 insertions(+), 528 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 660a90701..666500189 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -3,251 +3,29 @@ //! This module contains the configuration data structures for the //! Torrust Tracker, which is a `BitTorrent` tracker server. //! -//! The configuration is loaded from a [TOML](https://toml.io/en/) file -//! `tracker.toml` in the project root folder or from an environment variable -//! with the same content as the file. -//! -//! When you run the tracker without a configuration file, a new one will be -//! created with the default values, but the tracker immediately exits. You can -//! then edit the configuration file and run the tracker again. -//! -//! Configuration can not only be loaded from a file, but also from environment -//! variable `TORRUST_TRACKER_CONFIG`. This is useful when running the tracker -//! in a Docker container or environments where you do not have a persistent -//! storage or you cannot inject a configuration file. Refer to -//! [`Torrust Tracker documentation`](https://docs.rs/torrust-tracker) for more -//! information about how to pass configuration to the tracker. -//! -//! # Table of contents -//! -//! - [Sections](#sections) -//! - [Port binding](#port-binding) -//! - [TSL support](#tsl-support) -//! - [Generating self-signed certificates](#generating-self-signed-certificates) -//! - [Default configuration](#default-configuration) -//! -//! ## Sections -//! -//! Each section in the toml structure is mapped to a data structure. For -//! example, the `[http_api]` section (configuration for the tracker HTTP API) -//! is mapped to the [`HttpApi`] structure. -//! -//! > **NOTICE**: some sections are arrays of structures. For example, the -//! > `[[udp_trackers]]` section is an array of [`UdpTracker`] since -//! > you can have multiple running UDP trackers bound to different ports. -//! -//! Please refer to the documentation of each structure for more information -//! about each section. -//! -//! - [`Core configuration`](crate::Configuration) -//! - [`HTTP API configuration`](crate::HttpApi) -//! - [`HTTP Tracker configuration`](crate::HttpTracker) -//! - [`UDP Tracker configuration`](crate::UdpTracker) -//! -//! ## Port binding -//! -//! For the API, HTTP and UDP trackers you can bind to a random port by using -//! port `0`. For example, if you want to bind to a random port on all -//! interfaces, use `0.0.0.0:0`. The OS will choose a random port but the -//! tracker will not print the port it is listening to when it starts. It just -//! says `Starting Torrust HTTP tracker server on: http://0.0.0.0:0`. It shows -//! the port used in the configuration file, and not the port the -//! tracker is actually listening to. This is a planned feature, see issue -//! [186](https://github.com/torrust/torrust-tracker/issues/186) for more -//! information. -//! -//! ## TSL support -//! -//! For the API and HTTP tracker you can enable TSL by setting `ssl_enabled` to -//! `true` and setting the paths to the certificate and key files. -//! -//! Typically, you will have a directory structure like this: -//! -//! ```text -//! storage/ -//! ├── database -//! │ └── data.db -//! └── tls -//! ├── localhost.crt -//! └── localhost.key -//! ``` -//! -//! where you can store all the persistent data. -//! -//! Alternatively, you could setup a reverse proxy like Nginx or Apache to -//! handle the SSL/TLS part and forward the requests to the tracker. If you do -//! that, you should set [`on_reverse_proxy`](crate::Configuration::on_reverse_proxy) -//! to `true` in the configuration file. It's out of scope for this -//! documentation to explain in detail how to setup a reverse proxy, but the -//! configuration file should be something like this: -//! -//! For [NGINX](https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/): -//! -//! ```text -//! # HTTPS only (with SSL - force redirect to HTTPS) -//! -//! server { -//! listen 80; -//! server_name tracker.torrust.com; -//! -//! return 301 https://$host$request_uri; -//! } -//! -//! server { -//! listen 443; -//! server_name tracker.torrust.com; -//! -//! ssl_certificate CERT_PATH -//! ssl_certificate_key CERT_KEY_PATH; -//! -//! location / { -//! proxy_set_header X-Forwarded-For $remote_addr; -//! proxy_pass http://127.0.0.1:6969; -//! } -//! } -//! ``` -//! -//! For [Apache](https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html): -//! -//! ```text -//! # HTTPS only (with SSL - force redirect to HTTPS) -//! -//! -//! ServerAdmin webmaster@tracker.torrust.com -//! ServerName tracker.torrust.com -//! -//! -//! RewriteEngine on -//! RewriteCond %{HTTPS} off -//! RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] -//! -//! -//! -//! -//! -//! ServerAdmin webmaster@tracker.torrust.com -//! ServerName tracker.torrust.com -//! -//! -//! Order allow,deny -//! Allow from all -//! -//! -//! ProxyPreserveHost On -//! ProxyRequests Off -//! AllowEncodedSlashes NoDecode -//! -//! ProxyPass / http://localhost:3000/ -//! ProxyPassReverse / http://localhost:3000/ -//! ProxyPassReverse / http://tracker.torrust.com/ -//! -//! RequestHeader set X-Forwarded-Proto "https" -//! RequestHeader set X-Forwarded-Port "443" -//! -//! ErrorLog ${APACHE_LOG_DIR}/tracker.torrust.com-error.log -//! CustomLog ${APACHE_LOG_DIR}/tracker.torrust.com-access.log combined -//! -//! SSLCertificateFile CERT_PATH -//! SSLCertificateKeyFile CERT_KEY_PATH -//! -//! -//! ``` -//! -//! ## Generating self-signed certificates -//! -//! For testing purposes, you can use self-signed certificates. -//! -//! Refer to [Let's Encrypt - Certificates for localhost](https://letsencrypt.org/docs/certificates-for-localhost/) -//! for more information. -//! -//! Running the following command will generate a certificate (`localhost.crt`) -//! and key (`localhost.key`) file in your current directory: -//! -//! ```s -//! openssl req -x509 -out localhost.crt -keyout localhost.key \ -//! -newkey rsa:2048 -nodes -sha256 \ -//! -subj '/CN=localhost' -extensions EXT -config <( \ -//! printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth") -//! ``` -//! -//! You can then use the generated files in the configuration file: -//! -//! ```s -//! [[http_trackers]] -//! enabled = true -//! ... -//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" -//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" -//! -//! [http_api] -//! enabled = true -//! ... -//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" -//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" -//! ``` -//! -//! ## Default configuration -//! -//! The default configuration is: -//! -//! ```toml -//! announce_interval = 120 -//! db_driver = "Sqlite3" -//! db_path = "./storage/tracker/lib/database/sqlite3.db" -//! external_ip = "0.0.0.0" -//! inactive_peer_cleanup_interval = 600 -//! log_level = "info" -//! max_peer_timeout = 900 -//! min_announce_interval = 120 -//! mode = "public" -//! on_reverse_proxy = false -//! persistent_torrent_completed_stat = false -//! remove_peerless_torrents = true -//! tracker_usage_statistics = true -//! -//! [[udp_trackers]] -//! bind_address = "0.0.0.0:6969" -//! enabled = false -//! -//! [[http_trackers]] -//! bind_address = "0.0.0.0:7070" -//! enabled = false -//! ssl_cert_path = "" -//! ssl_enabled = false -//! ssl_key_path = "" -//! -//! [http_api] -//! bind_address = "127.0.0.1:1212" -//! enabled = true -//! ssl_cert_path = "" -//! ssl_enabled = false -//! ssl_key_path = "" -//! -//! [http_api.access_tokens] -//! admin = "MyAccessToken" -//! -//! [health_check_api] -//! bind_address = "127.0.0.1:1313" -//!``` +//! The current version for configuration is [`v1`](crate::v1). pub mod v1; use std::collections::HashMap; -use std::net::IpAddr; -use std::str::FromStr; use std::sync::Arc; use std::{env, fs}; -use config::{Config, ConfigError, File, FileFormat}; +use config::ConfigError; use derive_more::Constructor; -use serde::{Deserialize, Serialize}; -use serde_with::{serde_as, NoneAsEmptyString}; use thiserror::Error; use torrust_tracker_located_error::{DynError, Located, LocatedError}; -use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; /// The maximum number of returned peers for a torrent. pub const TORRENT_PEERS_LIMIT: usize = 74; +pub type Configuration = v1::Configuration; +pub type UdpTracker = v1::udp_tracker::UdpTracker; +pub type HttpTracker = v1::http_tracker::HttpTracker; +pub type HttpApi = v1::tracker_api::HttpApi; +pub type HealthCheckApi = v1::health_check_api::HealthCheckApi; + +pub type AccessTokens = HashMap; + #[derive(Copy, Clone, Debug, PartialEq, Constructor)] pub struct TrackerPolicy { pub remove_peerless_torrents: bool, @@ -307,84 +85,6 @@ impl Info { } } -/// Configuration for each UDP tracker. -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] -pub struct UdpTracker { - /// Weather the UDP tracker is enabled or not. - pub enabled: bool, - /// The address the tracker will bind to. - /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to - /// listen to all interfaces, use `0.0.0.0`. If you want the operating - /// system to choose a random port, use port `0`. - pub bind_address: String, -} - -/// Configuration for each HTTP tracker. -#[serde_as] -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] -pub struct HttpTracker { - /// Weather the HTTP tracker is enabled or not. - pub enabled: bool, - /// The address the tracker will bind to. - /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to - /// listen to all interfaces, use `0.0.0.0`. If you want the operating - /// system to choose a random port, use port `0`. - pub bind_address: String, - /// Weather the HTTP tracker will use SSL or not. - pub ssl_enabled: bool, - /// Path to the SSL certificate file. Only used if `ssl_enabled` is `true`. - #[serde_as(as = "NoneAsEmptyString")] - pub ssl_cert_path: Option, - /// Path to the SSL key file. Only used if `ssl_enabled` is `true`. - #[serde_as(as = "NoneAsEmptyString")] - pub ssl_key_path: Option, -} - -pub type AccessTokens = HashMap; - -/// Configuration for the HTTP API. -#[serde_as] -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] -pub struct HttpApi { - /// Weather the HTTP API is enabled or not. - pub enabled: bool, - /// The address the tracker will bind to. - /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to - /// listen to all interfaces, use `0.0.0.0`. If you want the operating - /// system to choose a random port, use port `0`. - pub bind_address: String, - /// Weather the HTTP API will use SSL or not. - pub ssl_enabled: bool, - /// Path to the SSL certificate file. Only used if `ssl_enabled` is `true`. - #[serde_as(as = "NoneAsEmptyString")] - pub ssl_cert_path: Option, - /// Path to the SSL key file. Only used if `ssl_enabled` is `true`. - #[serde_as(as = "NoneAsEmptyString")] - pub ssl_key_path: Option, - /// Access tokens for the HTTP API. The key is a label identifying the - /// token and the value is the token itself. The token is used to - /// authenticate the user. All tokens are valid for all endpoints and have - /// the all permissions. - pub access_tokens: AccessTokens, -} - -impl HttpApi { - fn override_admin_token(&mut self, api_admin_token: &str) { - self.access_tokens.insert("admin".to_string(), api_admin_token.to_string()); - } -} - -/// Configuration for the Health Check API. -#[serde_as] -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] -pub struct HealthCheckApi { - /// The address the API will bind to. - /// The format is `ip:port`, for example `127.0.0.1:1313`. If you want to - /// listen to all interfaces, use `0.0.0.0`. If you want the operating - /// system to choose a random port, use port `0`. - pub bind_address: String, -} - /// Announce policy #[derive(PartialEq, Eq, Debug, Clone, Copy, Constructor)] pub struct AnnouncePolicy { @@ -424,81 +124,6 @@ impl Default for AnnouncePolicy { } } -/// 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, - /// Tracker mode. See [`TrackerMode`] for more information. - pub mode: TrackerMode, - - // Database configuration - /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. - pub db_driver: DatabaseDriver, - /// Database connection string. The format depends on the database driver. - /// For `Sqlite3`, the format is `path/to/database.db`, for example: - /// `./storage/tracker/lib/database/sqlite3.db`. - /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for - /// example: `root:password@localhost:3306/torrust`. - pub db_path: String, - - /// See [`AnnouncePolicy::interval`] - pub announce_interval: u32, - - /// See [`AnnouncePolicy::interval_min`] - pub min_announce_interval: u32, - /// Weather the tracker is behind a reverse proxy or not. - /// If the tracker is behind a reverse proxy, the `X-Forwarded-For` header - /// sent from the proxy will be used to get the client's IP address. - pub on_reverse_proxy: bool, - /// The external IP address of the tracker. If the client is using a - /// loopback IP address, this IP address will be used instead. If the peer - /// 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, - /// 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. - /// Refer to the [`Tracker`](https://docs.rs/torrust-tracker) for more - /// information about the collected metrics. - pub tracker_usage_statistics: bool, - /// If enabled the tracker will persist the number of completed downloads. - /// That's how many times a torrent has been downloaded completely. - pub persistent_torrent_completed_stat: bool, - - // Cleanup job configuration - /// Maximum time in seconds that a peer can be inactive before being - /// considered an inactive peer. If a peer is inactive for more than this - /// time, it will be removed from the torrent peer list. - pub max_peer_timeout: u32, - /// Interval in seconds that the cleanup job will run to remove inactive - /// peers from the torrent peer list. - pub inactive_peer_cleanup_interval: u64, - /// If enabled, the tracker will remove torrents that have no peers. - /// The clean up torrent job runs every `inactive_peer_cleanup_interval` - /// seconds and it removes inactive peers. Eventually, the peer list of a - /// torrent could be empty and the torrent will be removed if this option is - /// enabled. - pub remove_peerless_torrents: bool, - - // Server jobs configuration - /// The list of UDP trackers the tracker is running. Each UDP tracker - /// represents a UDP server that the tracker is running and it has its own - /// configuration. - pub udp_trackers: Vec, - /// The list of HTTP trackers the tracker is running. Each HTTP tracker - /// represents a HTTP server that the tracker is running and it has its own - /// configuration. - pub http_trackers: Vec, - /// The HTTP API configuration. - pub http_api: HttpApi, - /// The Health Check API configuration. - pub health_check_api: HealthCheckApi, -} - /// Errors that can occur when loading the configuration. #[derive(Error, Debug)] pub enum Error { @@ -532,147 +157,6 @@ impl From for Error { } } -impl Default for Configuration { - fn default() -> Self { - let announce_policy = AnnouncePolicy::default(); - - let mut configuration = Configuration { - log_level: Option::from(String::from("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")), - tracker_usage_statistics: true, - persistent_torrent_completed_stat: false, - inactive_peer_cleanup_interval: 600, - remove_peerless_torrents: true, - udp_trackers: Vec::new(), - http_trackers: Vec::new(), - http_api: HttpApi { - enabled: true, - bind_address: String::from("127.0.0.1:1212"), - ssl_enabled: false, - ssl_cert_path: None, - ssl_key_path: None, - access_tokens: [(String::from("admin"), String::from("MyAccessToken"))] - .iter() - .cloned() - .collect(), - }, - health_check_api: HealthCheckApi { - bind_address: String::from("127.0.0.1:1313"), - }, - }; - configuration.udp_trackers.push(UdpTracker { - enabled: false, - bind_address: String::from("0.0.0.0:6969"), - }); - configuration.http_trackers.push(HttpTracker { - enabled: false, - bind_address: String::from("0.0.0.0:7070"), - ssl_enabled: false, - ssl_cert_path: None, - ssl_key_path: None, - }); - configuration - } -} - -impl Configuration { - fn override_api_admin_token(&mut self, api_admin_token: &str) { - self.http_api.override_admin_token(api_admin_token); - } - - /// Returns the tracker public IP address id defined in the configuration, - /// and `None` otherwise. - #[must_use] - pub fn get_ext_ip(&self) -> Option { - match &self.external_ip { - None => None, - Some(external_ip) => match IpAddr::from_str(external_ip) { - Ok(external_ip) => Some(external_ip), - Err(_) => None, - }, - } - } - - /// Loads the configuration from the configuration file. - /// - /// # Errors - /// - /// Will return `Err` if `path` does not exist or has a bad configuration. - pub fn load_from_file(path: &str) -> Result { - let config_builder = Config::builder(); - - #[allow(unused_assignments)] - let mut config = Config::default(); - - config = config_builder.add_source(File::with_name(path)).build()?; - - let torrust_config: Configuration = config.try_deserialize()?; - - Ok(torrust_config) - } - - /// Saves the default configuration at the given path. - /// - /// # Errors - /// - /// Will return `Err` if `path` is not a valid path or the configuration - /// file cannot be created. - pub fn create_default_configuration_file(path: &str) -> Result { - let config = Configuration::default(); - config.save_to_file(path)?; - Ok(config) - } - - /// Loads the configuration from the `Info` struct. The whole - /// configuration in toml format is included in the `info.tracker_toml` string. - /// - /// Optionally will override the admin api token. - /// - /// # Errors - /// - /// Will return `Err` if the environment variable does not exist or has a bad configuration. - pub fn load(info: &Info) -> Result { - let config_builder = Config::builder() - .add_source(File::from_str(&info.tracker_toml, FileFormat::Toml)) - .build()?; - let mut config: Configuration = config_builder.try_deserialize()?; - - if let Some(ref token) = info.api_admin_token { - config.override_api_admin_token(token); - }; - - Ok(config) - } - - /// Saves the configuration to the configuration file. - /// - /// # Errors - /// - /// Will return `Err` if `filename` does not exist or the user does not have - /// permission to read it. Will also return `Err` if the configuration is - /// not valid or cannot be encoded to TOML. - /// - /// # Panics - /// - /// Will panic if the configuration cannot be written into the file. - pub fn save_to_file(&self, path: &str) -> Result<(), Error> { - fs::write(path, self.to_toml()).expect("Could not write to file!"); - Ok(()) - } - - /// Encodes the configuration to TOML. - fn to_toml(&self) -> String { - toml::to_string(self).expect("Could not encode TOML value") - } -} - #[cfg(test)] mod tests { use crate::Configuration; diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 815d74e40..486d2c300 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -1,4 +1,5 @@ -//! Configuration data structures for [Torrust Tracker](https://docs.rs/torrust-tracker). +//! Version `1` for [Torrust Tracker](https://docs.rs/torrust-tracker) +//! configuration data structures. //! //! This module contains the configuration data structures for the //! Torrust Tracker, which is a `BitTorrent` tracker server. @@ -234,6 +235,11 @@ pub mod http_tracker; pub mod tracker_api; pub mod udp_tracker; +use std::fs; +use std::net::IpAddr; +use std::str::FromStr; + +use config::{Config, File, FileFormat}; use serde::{Deserialize, Serialize}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; @@ -241,7 +247,7 @@ use self::health_check_api::HealthCheckApi; use self::http_tracker::HttpTracker; use self::tracker_api::HttpApi; use self::udp_tracker::UdpTracker; -use crate::AnnouncePolicy; +use crate::{AnnouncePolicy, Error, Info}; /// Core configuration for the tracker. #[allow(clippy::struct_excessive_bools)] @@ -368,6 +374,105 @@ impl Default for Configuration { } } +impl Configuration { + fn override_api_admin_token(&mut self, api_admin_token: &str) { + self.http_api.override_admin_token(api_admin_token); + } + + /// Returns the tracker public IP address id defined in the configuration, + /// and `None` otherwise. + #[must_use] + pub fn get_ext_ip(&self) -> Option { + match &self.external_ip { + None => None, + Some(external_ip) => match IpAddr::from_str(external_ip) { + Ok(external_ip) => Some(external_ip), + Err(_) => None, + }, + } + } + + /// Loads the configuration from the configuration file. + /// + /// # Errors + /// + /// Will return `Err` if `path` does not exist or has a bad configuration. + pub fn load_from_file(path: &str) -> Result { + // todo: use Figment + + let config_builder = Config::builder(); + + #[allow(unused_assignments)] + let mut config = Config::default(); + + config = config_builder.add_source(File::with_name(path)).build()?; + + let torrust_config: Configuration = config.try_deserialize()?; + + Ok(torrust_config) + } + + /// Saves the default configuration at the given path. + /// + /// # Errors + /// + /// Will return `Err` if `path` is not a valid path or the configuration + /// file cannot be created. + pub fn create_default_configuration_file(path: &str) -> Result { + // todo: use Figment + + let config = Configuration::default(); + config.save_to_file(path)?; + Ok(config) + } + + /// Loads the configuration from the `Info` struct. The whole + /// configuration in toml format is included in the `info.tracker_toml` string. + /// + /// Optionally will override the admin api token. + /// + /// # Errors + /// + /// Will return `Err` if the environment variable does not exist or has a bad configuration. + pub fn load(info: &Info) -> Result { + // todo: use Figment + + let config_builder = Config::builder() + .add_source(File::from_str(&info.tracker_toml, FileFormat::Toml)) + .build()?; + let mut config: Configuration = config_builder.try_deserialize()?; + + if let Some(ref token) = info.api_admin_token { + config.override_api_admin_token(token); + }; + + Ok(config) + } + + /// Saves the configuration to the configuration file. + /// + /// # Errors + /// + /// Will return `Err` if `filename` does not exist or the user does not have + /// permission to read it. Will also return `Err` if the configuration is + /// not valid or cannot be encoded to TOML. + /// + /// # Panics + /// + /// Will panic if the configuration cannot be written into the file. + pub fn save_to_file(&self, path: &str) -> Result<(), Error> { + // todo: use Figment + + fs::write(path, self.to_toml()).expect("Could not write to file!"); + Ok(()) + } + + /// Encodes the configuration to TOML. + fn to_toml(&self) -> String { + toml::to_string(self).expect("Could not encode TOML value") + } +} + #[cfg(test)] mod tests { use figment::providers::{Format, Toml}; diff --git a/packages/configuration/src/v1/tracker_api.rs b/packages/configuration/src/v1/tracker_api.rs index 6cda9b437..51f11a14d 100644 --- a/packages/configuration/src/v1/tracker_api.rs +++ b/packages/configuration/src/v1/tracker_api.rs @@ -30,3 +30,9 @@ pub struct HttpApi { /// the all permissions. pub access_tokens: AccessTokens, } + +impl HttpApi { + pub fn override_admin_token(&mut self, api_admin_token: &str) { + self.access_tokens.insert("admin".to_string(), api_admin_token.to_string()); + } +} From 265d89d1e8cfd318919e793bbfeceb5b3556cbcb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 May 2024 13:54:07 +0100 Subject: [PATCH 0318/1297] refactor: replace Config by Figment in Configuration implementation This replaces the crate `config` with `figment` in the Configuration implementation. --- packages/configuration/src/lib.rs | 13 +++++++------ packages/configuration/src/v1/mod.rs | 28 ++++++++-------------------- 2 files changed, 15 insertions(+), 26 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 666500189..78b62442c 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -10,10 +10,9 @@ use std::collections::HashMap; use std::sync::Arc; use std::{env, fs}; -use config::ConfigError; use derive_more::Constructor; use thiserror::Error; -use torrust_tracker_located_error::{DynError, Located, LocatedError}; +use torrust_tracker_located_error::{DynError, LocatedError}; /// The maximum number of returned peers for a torrent. pub const TORRENT_PEERS_LIMIT: usize = 74; @@ -142,17 +141,19 @@ pub enum Error { /// Unable to load the configuration from the configuration file. #[error("Failed processing the configuration: {source}")] - ConfigError { source: LocatedError<'static, ConfigError> }, + ConfigError { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + }, #[error("The error for errors that can never happen.")] Infallible, } -impl From for Error { +impl From for Error { #[track_caller] - fn from(err: ConfigError) -> Self { + fn from(err: figment::Error) -> Self { Self::ConfigError { - source: Located(err).into(), + source: (Arc::new(err) as DynError).into(), } } } diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 486d2c300..6c044c462 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -239,7 +239,8 @@ use std::fs; use std::net::IpAddr; use std::str::FromStr; -use config::{Config, File, FileFormat}; +use figment::providers::{Format, Toml}; +use figment::Figment; use serde::{Deserialize, Serialize}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; @@ -398,18 +399,11 @@ impl Configuration { /// /// Will return `Err` if `path` does not exist or has a bad configuration. pub fn load_from_file(path: &str) -> Result { - // todo: use Figment + let figment = Figment::new().merge(Toml::file(path)); - let config_builder = Config::builder(); + let config: Configuration = figment.extract()?; - #[allow(unused_assignments)] - let mut config = Config::default(); - - config = config_builder.add_source(File::with_name(path)).build()?; - - let torrust_config: Configuration = config.try_deserialize()?; - - Ok(torrust_config) + Ok(config) } /// Saves the default configuration at the given path. @@ -419,8 +413,6 @@ impl Configuration { /// Will return `Err` if `path` is not a valid path or the configuration /// file cannot be created. pub fn create_default_configuration_file(path: &str) -> Result { - // todo: use Figment - let config = Configuration::default(); config.save_to_file(path)?; Ok(config) @@ -435,12 +427,9 @@ impl Configuration { /// /// Will return `Err` if the environment variable does not exist or has a bad configuration. pub fn load(info: &Info) -> Result { - // todo: use Figment + let figment = Figment::new().merge(Toml::string(&info.tracker_toml)); - let config_builder = Config::builder() - .add_source(File::from_str(&info.tracker_toml, FileFormat::Toml)) - .build()?; - let mut config: Configuration = config_builder.try_deserialize()?; + let mut config: Configuration = figment.extract()?; if let Some(ref token) = info.api_admin_token { config.override_api_admin_token(token); @@ -461,14 +450,13 @@ impl Configuration { /// /// Will panic if the configuration cannot be written into the file. pub fn save_to_file(&self, path: &str) -> Result<(), Error> { - // todo: use Figment - fs::write(path, self.to_toml()).expect("Could not write to file!"); Ok(()) } /// Encodes the configuration to TOML. fn to_toml(&self) -> String { + // code-review: do we need to use Figment also to serialize into toml? toml::to_string(self).expect("Could not encode TOML value") } } From 5bd94940d7230948fed44c6d0b6cae0c1da9810e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 May 2024 15:36:27 +0100 Subject: [PATCH 0319/1297] chore: remove unused config dependenciy It was replaced by `figment`. --- Cargo.lock | 195 +----------------------------- Cargo.toml | 7 +- packages/configuration/Cargo.toml | 1 - 3 files changed, 4 insertions(+), 199 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1b4c2a4e7..0bbf0205a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -587,9 +587,6 @@ name = "bitflags" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" -dependencies = [ - "serde", -] [[package]] name = "bitvec" @@ -898,61 +895,12 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "config" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7328b20597b53c2454f0b1919720c25c7339051c02b72b7e05409e00b14132be" -dependencies = [ - "async-trait", - "convert_case 0.6.0", - "json5", - "lazy_static", - "nom", - "pathdiff", - "ron", - "rust-ini", - "serde", - "serde_json", - "toml", - "yaml-rust", -] - -[[package]] -name = "const-random" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" -dependencies = [ - "const-random-macro", -] - -[[package]] -name = "const-random-macro" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" -dependencies = [ - "getrandom", - "once_cell", - "tiny-keccak", -] - [[package]] name = "convert_case" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" -[[package]] -name = "convert_case" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca" -dependencies = [ - "unicode-segmentation", -] - [[package]] name = "core-foundation" version = "0.9.4" @@ -1171,7 +1119,7 @@ version = "0.99.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" dependencies = [ - "convert_case 0.4.0", + "convert_case", "proc-macro2", "quote", "rustc_version", @@ -1199,15 +1147,6 @@ dependencies = [ "crypto-common", ] -[[package]] -name = "dlv-list" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f" -dependencies = [ - "const-random", -] - [[package]] name = "downcast" version = "0.11.0" @@ -2008,17 +1947,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "json5" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96b0db21af676c1ce64250b5f40f3ce2cf27e4e47cb91ed91eb6fe9350b430c1" -dependencies = [ - "pest", - "pest_derive", - "serde", -] - [[package]] name = "kv-log-macro" version = "1.0.7" @@ -2151,12 +2079,6 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "linked-hash-map" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" - [[package]] name = "linux-raw-sys" version = "0.3.8" @@ -2548,16 +2470,6 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "ordered-multimap" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ed8acf08e98e744e5384c8bc63ceb0364e68a6854187221c18df61c4797690e" -dependencies = [ - "dlv-list", - "hashbrown 0.13.2", -] - [[package]] name = "parking" version = "2.2.0" @@ -2587,12 +2499,6 @@ dependencies = [ "windows-targets 0.52.5", ] -[[package]] -name = "pathdiff" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" - [[package]] name = "pear" version = "0.2.9" @@ -2632,51 +2538,6 @@ version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" -[[package]] -name = "pest" -version = "2.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "560131c633294438da9f7c4b08189194b20946c8274c6b9e38881a7874dc8ee8" -dependencies = [ - "memchr", - "thiserror", - "ucd-trie", -] - -[[package]] -name = "pest_derive" -version = "2.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26293c9193fbca7b1a3bf9b79dc1e388e927e6cacaa78b4a3ab705a1d3d41459" -dependencies = [ - "pest", - "pest_generator", -] - -[[package]] -name = "pest_generator" -version = "2.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ec22af7d3fb470a85dd2ca96b7c577a1eb4ef6f1683a9fe9a8c16e136c04687" -dependencies = [ - "pest", - "pest_meta", - "proc-macro2", - "quote", - "syn 2.0.61", -] - -[[package]] -name = "pest_meta" -version = "2.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7a240022f37c361ec1878d646fc5b7d7c4d28d5946e1a80ad5a7a4f4ca0bdcd" -dependencies = [ - "once_cell", - "pest", - "sha2", -] - [[package]] name = "phf" version = "0.11.2" @@ -3202,18 +3063,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "ron" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b91f7eff05f748767f183df4320a63d6936e9c6107d97c9e6bdd9784f4289c94" -dependencies = [ - "base64 0.21.7", - "bitflags 2.5.0", - "serde", - "serde_derive", -] - [[package]] name = "rstest" version = "0.19.0" @@ -3257,16 +3106,6 @@ dependencies = [ "smallvec", ] -[[package]] -name = "rust-ini" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e2a3bcec1f113553ef1c88aae6c020a369d03d55b58de9869a0908930385091" -dependencies = [ - "cfg-if", - "ordered-multimap", -] - [[package]] name = "rust_decimal" version = "1.35.0" @@ -3887,15 +3726,6 @@ dependencies = [ "time-core", ] -[[package]] -name = "tiny-keccak" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" -dependencies = [ - "crunchy", -] - [[package]] name = "tinytemplate" version = "1.2.1" @@ -4052,7 +3882,6 @@ dependencies = [ "axum-server", "chrono", "clap", - "config", "crossbeam-skiplist", "dashmap", "derive_more", @@ -4109,7 +3938,6 @@ dependencies = [ name = "torrust-tracker-configuration" version = "3.0.0-alpha.12-develop" dependencies = [ - "config", "derive_more", "figment", "serde", @@ -4291,12 +4119,6 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" -[[package]] -name = "ucd-trie" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" - [[package]] name = "uncased" version = "0.9.10" @@ -4327,12 +4149,6 @@ dependencies = [ "tinyvec", ] -[[package]] -name = "unicode-segmentation" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" - [[package]] name = "untrusted" version = "0.9.0" @@ -4707,15 +4523,6 @@ dependencies = [ "tap", ] -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] - [[package]] name = "yansi" version = "1.0.1" diff --git a/Cargo.toml b/Cargo.toml index 2be3455b8..d7aa9a31c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,7 +39,6 @@ axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls"] } chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } -config = "0" crossbeam-skiplist = "0.1" dashmap = "5.5.3" derive_more = "0" @@ -80,7 +79,7 @@ uuid = { version = "1", features = ["v4"] } zerocopy = "0.7.33" [package.metadata.cargo-machete] -ignored = ["serde_bytes", "crossbeam-skiplist", "dashmap", "parking_lot"] +ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_bytes"] [dev-dependencies] local-ip-address = "0" @@ -94,7 +93,7 @@ members = [ "packages/located-error", "packages/primitives", "packages/test-helpers", - "packages/torrent-repository" + "packages/torrent-repository", ] [profile.dev] @@ -108,5 +107,5 @@ lto = "fat" opt-level = 3 [profile.release-debug] -inherits = "release" debug = true +inherits = "release" diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index e5335d416..a033dcea1 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -15,7 +15,6 @@ rust-version.workspace = true version.workspace = true [dependencies] -config = "0" derive_more = "0" figment = { version = "0.10.18", features = ["env", "test", "toml"] } serde = { version = "1", features = ["derive"] } From 146b77d86f86b62fc50014586ab19a1848edbc1b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 May 2024 16:38:09 +0100 Subject: [PATCH 0320/1297] feat: enable overwrite Configuration values using env vars Enable Figment ability to overwrite all config options with env vars. We are currently overwriting only this value: ```toml [http_api.access_tokens] admin = "MyAccessToken" ``` With the env var `TORRUST_TRACKER_API_ADMIN_TOKEN`. The name we gave to the env var does nto follow Figment convention which is `TORRUST_TRACKER_HTTP_API.ACCESS_TOKENS.ADMIN`. We have to keep both options until we remove the old one in the rest of the code. --- packages/configuration/src/v1/mod.rs | 138 ++++++++++++++++++--------- 1 file changed, 91 insertions(+), 47 deletions(-) diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 6c044c462..562eb569e 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -239,7 +239,7 @@ use std::fs; use std::net::IpAddr; use std::str::FromStr; -use figment::providers::{Format, Toml}; +use figment::providers::{Env, Format, Toml}; use figment::Figment; use serde::{Deserialize, Serialize}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; @@ -400,6 +400,16 @@ impl Configuration { /// Will return `Err` if `path` does not exist or has a bad configuration. pub fn load_from_file(path: &str) -> Result { let figment = Figment::new().merge(Toml::file(path)); + //.merge(Env::prefixed("TORRUST_TRACKER_")); + + // code-review: merging values from env vars makes the test + // "configuration_should_be_loaded_from_a_toml_config_file" fail. + // + // It's because this line in a new test: + // + // jail.set_env("TORRUST_TRACKER_HTTP_API.ACCESS_TOKENS.ADMIN", "NewToken"); + // + // It seems env vars are shared between tests. let config: Configuration = figment.extract()?; @@ -427,7 +437,9 @@ impl Configuration { /// /// Will return `Err` if the environment variable does not exist or has a bad configuration. pub fn load(info: &Info) -> Result { - let figment = Figment::new().merge(Toml::string(&info.tracker_toml)); + let figment = Figment::new() + .merge(Toml::string(&info.tracker_toml)) + .merge(Env::prefixed("TORRUST_TRACKER_")); let mut config: Configuration = figment.extract()?; @@ -463,58 +475,67 @@ impl Configuration { #[cfg(test)] mod tests { - use figment::providers::{Format, Toml}; + use figment::providers::{Env, Format, Toml}; use figment::Figment; use crate::v1::Configuration; + #[cfg(test)] + fn default_config_toml() -> String { + let config = r#"log_level = "info" + mode = "public" + db_driver = "Sqlite3" + db_path = "./storage/tracker/lib/database/sqlite3.db" + announce_interval = 120 + min_announce_interval = 120 + on_reverse_proxy = false + external_ip = "0.0.0.0" + tracker_usage_statistics = true + persistent_torrent_completed_stat = false + max_peer_timeout = 900 + inactive_peer_cleanup_interval = 600 + remove_peerless_torrents = true + + [[udp_trackers]] + enabled = false + bind_address = "0.0.0.0:6969" + + [[http_trackers]] + enabled = false + bind_address = "0.0.0.0:7070" + ssl_enabled = false + ssl_cert_path = "" + ssl_key_path = "" + + [http_api] + enabled = true + bind_address = "127.0.0.1:1212" + ssl_enabled = false + ssl_cert_path = "" + ssl_key_path = "" + + [http_api.access_tokens] + admin = "MyAccessToken" + + [health_check_api] + bind_address = "127.0.0.1:1313" + "# + .lines() + .map(str::trim_start) + .collect::>() + .join("\n"); + config + } + #[test] fn configuration_should_be_loaded_from_a_toml_config_file() { figment::Jail::expect_with(|jail| { - jail.create_file( - "Config.toml", - r#" - log_level = "info" - mode = "public" - db_driver = "Sqlite3" - db_path = "./storage/tracker/lib/database/sqlite3.db" - announce_interval = 120 - min_announce_interval = 120 - on_reverse_proxy = false - external_ip = "0.0.0.0" - tracker_usage_statistics = true - persistent_torrent_completed_stat = false - max_peer_timeout = 900 - inactive_peer_cleanup_interval = 600 - remove_peerless_torrents = true - - [[udp_trackers]] - enabled = false - bind_address = "0.0.0.0:6969" - - [[http_trackers]] - enabled = false - bind_address = "0.0.0.0:7070" - ssl_enabled = false - ssl_cert_path = "" - ssl_key_path = "" - - [http_api] - enabled = true - bind_address = "127.0.0.1:1212" - ssl_enabled = false - ssl_cert_path = "" - ssl_key_path = "" - - [http_api.access_tokens] - admin = "MyAccessToken" - - [health_check_api] - bind_address = "127.0.0.1:1313" - "#, - )?; - - let figment = Figment::new().merge(Toml::file("Config.toml")); + jail.create_file("Config.toml", &default_config_toml())?; + + // todo: replace with Configuration method + let figment = Figment::new() + .merge(Toml::file("Config.toml")) + .merge(Env::prefixed("TORRUST_TRACKER_")); let config: Configuration = figment.extract()?; @@ -523,4 +544,27 @@ mod tests { Ok(()) }); } + + #[test] + fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin() { + figment::Jail::expect_with(|jail| { + jail.create_file("Config.toml", &default_config_toml())?; + + jail.set_env("TORRUST_TRACKER_HTTP_API.ACCESS_TOKENS.ADMIN", "NewToken"); + + // todo: replace with Configuration method + let figment = Figment::new() + .merge(Toml::file("Config.toml")) + .merge(Env::prefixed("TORRUST_TRACKER_")); + + let config: Configuration = figment.extract()?; + + assert_eq!( + config.http_api.access_tokens.get("admin"), + Some("NewToken".to_owned()).as_ref() + ); + + Ok(()) + }); + } } From 632c8baad3ad47934872a40f1f6da5c721325e75 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 May 2024 17:06:06 +0100 Subject: [PATCH 0321/1297] refactor: move Configuration unit test to inner mods --- packages/configuration/src/lib.rs | 133 ------------------- packages/configuration/src/v1/mod.rs | 91 +++++++------ packages/configuration/src/v1/tracker_api.rs | 29 ++++ 3 files changed, 80 insertions(+), 173 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 78b62442c..20912990a 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -157,136 +157,3 @@ impl From for Error { } } } - -#[cfg(test)] -mod tests { - use crate::Configuration; - - #[cfg(test)] - fn default_config_toml() -> String { - let config = r#"log_level = "info" - mode = "public" - db_driver = "Sqlite3" - db_path = "./storage/tracker/lib/database/sqlite3.db" - announce_interval = 120 - min_announce_interval = 120 - on_reverse_proxy = false - external_ip = "0.0.0.0" - tracker_usage_statistics = true - persistent_torrent_completed_stat = false - max_peer_timeout = 900 - inactive_peer_cleanup_interval = 600 - remove_peerless_torrents = true - - [[udp_trackers]] - enabled = false - bind_address = "0.0.0.0:6969" - - [[http_trackers]] - enabled = false - bind_address = "0.0.0.0:7070" - ssl_enabled = false - ssl_cert_path = "" - ssl_key_path = "" - - [http_api] - enabled = true - bind_address = "127.0.0.1:1212" - ssl_enabled = false - ssl_cert_path = "" - ssl_key_path = "" - - [http_api.access_tokens] - admin = "MyAccessToken" - - [health_check_api] - bind_address = "127.0.0.1:1313" - "# - .lines() - .map(str::trim_start) - .collect::>() - .join("\n"); - config - } - - #[test] - fn configuration_should_have_default_values() { - let configuration = Configuration::default(); - - let toml = toml::to_string(&configuration).expect("Could not encode TOML value"); - - assert_eq!(toml, default_config_toml()); - } - - #[test] - fn configuration_should_contain_the_external_ip() { - let configuration = Configuration::default(); - - assert_eq!(configuration.external_ip, Some(String::from("0.0.0.0"))); - } - - #[test] - fn configuration_should_be_saved_in_a_toml_config_file() { - use std::{env, fs}; - - use uuid::Uuid; - - // Build temp config file path - let temp_directory = env::temp_dir(); - let temp_file = temp_directory.join(format!("test_config_{}.toml", Uuid::new_v4())); - - // Convert to argument type for Configuration::save_to_file - let config_file_path = temp_file; - let path = config_file_path.to_string_lossy().to_string(); - - let default_configuration = Configuration::default(); - - default_configuration - .save_to_file(&path) - .expect("Could not save configuration to file"); - - let contents = fs::read_to_string(&path).expect("Something went wrong reading the file"); - - assert_eq!(contents, default_config_toml()); - } - - #[cfg(test)] - fn create_temp_config_file_with_default_config() -> String { - use std::env; - use std::fs::File; - use std::io::Write; - - use uuid::Uuid; - - // Build temp config file path - let temp_directory = env::temp_dir(); - let temp_file = temp_directory.join(format!("test_config_{}.toml", Uuid::new_v4())); - - // Convert to argument type for Configuration::load_from_file - let config_file_path = temp_file.clone(); - let path = config_file_path.to_string_lossy().to_string(); - - // Write file contents - let mut file = File::create(temp_file).unwrap(); - writeln!(&mut file, "{}", default_config_toml()).unwrap(); - - path - } - - #[test] - fn configuration_should_be_loaded_from_a_toml_config_file() { - let config_file_path = create_temp_config_file_with_default_config(); - - let configuration = Configuration::load_from_file(&config_file_path).expect("Could not load configuration from file"); - - assert_eq!(configuration, Configuration::default()); - } - - #[test] - fn http_api_configuration_should_check_if_it_contains_a_token() { - let configuration = Configuration::default(); - - assert!(configuration.http_api.access_tokens.values().any(|t| t == "MyAccessToken")); - assert!(!configuration.http_api.access_tokens.values().any(|t| t == "NonExistingToken")); - } -} diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 562eb569e..4413ed7c4 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -345,17 +345,7 @@ impl Default for Configuration { remove_peerless_torrents: true, udp_trackers: Vec::new(), http_trackers: Vec::new(), - http_api: HttpApi { - enabled: true, - bind_address: String::from("127.0.0.1:1212"), - ssl_enabled: false, - ssl_cert_path: None, - ssl_key_path: None, - access_tokens: [(String::from("admin"), String::from("MyAccessToken"))] - .iter() - .cloned() - .collect(), - }, + http_api: HttpApi::default(), health_check_api: HealthCheckApi { bind_address: String::from("127.0.0.1:1313"), }, @@ -399,17 +389,9 @@ impl Configuration { /// /// Will return `Err` if `path` does not exist or has a bad configuration. pub fn load_from_file(path: &str) -> Result { - let figment = Figment::new().merge(Toml::file(path)); - //.merge(Env::prefixed("TORRUST_TRACKER_")); - - // code-review: merging values from env vars makes the test - // "configuration_should_be_loaded_from_a_toml_config_file" fail. - // - // It's because this line in a new test: - // - // jail.set_env("TORRUST_TRACKER_HTTP_API.ACCESS_TOKENS.ADMIN", "NewToken"); - // - // It seems env vars are shared between tests. + let figment = Figment::new() + .merge(Toml::file(path)) + .merge(Env::prefixed("TORRUST_TRACKER_")); let config: Configuration = figment.extract()?; @@ -475,8 +457,6 @@ impl Configuration { #[cfg(test)] mod tests { - use figment::providers::{Env, Format, Toml}; - use figment::Figment; use crate::v1::Configuration; @@ -527,19 +507,55 @@ mod tests { config } + #[test] + fn configuration_should_have_default_values() { + let configuration = Configuration::default(); + + let toml = toml::to_string(&configuration).expect("Could not encode TOML value"); + + assert_eq!(toml, default_config_toml()); + } + + #[test] + fn configuration_should_contain_the_external_ip() { + let configuration = Configuration::default(); + + assert_eq!(configuration.external_ip, Some(String::from("0.0.0.0"))); + } + + #[test] + fn configuration_should_be_saved_in_a_toml_config_file() { + use std::{env, fs}; + + use uuid::Uuid; + + // Build temp config file path + let temp_directory = env::temp_dir(); + let temp_file = temp_directory.join(format!("test_config_{}.toml", Uuid::new_v4())); + + // Convert to argument type for Configuration::save_to_file + let config_file_path = temp_file; + let path = config_file_path.to_string_lossy().to_string(); + + let default_configuration = Configuration::default(); + + default_configuration + .save_to_file(&path) + .expect("Could not save configuration to file"); + + let contents = fs::read_to_string(&path).expect("Something went wrong reading the file"); + + assert_eq!(contents, default_config_toml()); + } + #[test] fn configuration_should_be_loaded_from_a_toml_config_file() { figment::Jail::expect_with(|jail| { - jail.create_file("Config.toml", &default_config_toml())?; - - // todo: replace with Configuration method - let figment = Figment::new() - .merge(Toml::file("Config.toml")) - .merge(Env::prefixed("TORRUST_TRACKER_")); + jail.create_file("tracker.toml", &default_config_toml())?; - let config: Configuration = figment.extract()?; + let configuration = Configuration::load_from_file("tracker.toml").expect("Could not load configuration from file"); - assert_eq!(config, Configuration::default()); + assert_eq!(configuration, Configuration::default()); Ok(()) }); @@ -548,19 +564,14 @@ mod tests { #[test] fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin() { figment::Jail::expect_with(|jail| { - jail.create_file("Config.toml", &default_config_toml())?; + jail.create_file("tracker.toml", &default_config_toml())?; jail.set_env("TORRUST_TRACKER_HTTP_API.ACCESS_TOKENS.ADMIN", "NewToken"); - // todo: replace with Configuration method - let figment = Figment::new() - .merge(Toml::file("Config.toml")) - .merge(Env::prefixed("TORRUST_TRACKER_")); - - let config: Configuration = figment.extract()?; + let configuration = Configuration::load_from_file("tracker.toml").expect("Could not load configuration from file"); assert_eq!( - config.http_api.access_tokens.get("admin"), + configuration.http_api.access_tokens.get("admin"), Some("NewToken".to_owned()).as_ref() ); diff --git a/packages/configuration/src/v1/tracker_api.rs b/packages/configuration/src/v1/tracker_api.rs index 51f11a14d..8749478c8 100644 --- a/packages/configuration/src/v1/tracker_api.rs +++ b/packages/configuration/src/v1/tracker_api.rs @@ -31,8 +31,37 @@ pub struct HttpApi { pub access_tokens: AccessTokens, } +impl Default for HttpApi { + fn default() -> Self { + Self { + enabled: true, + bind_address: String::from("127.0.0.1:1212"), + ssl_enabled: false, + ssl_cert_path: None, + ssl_key_path: None, + access_tokens: [(String::from("admin"), String::from("MyAccessToken"))] + .iter() + .cloned() + .collect(), + } + } +} + impl HttpApi { pub fn override_admin_token(&mut self, api_admin_token: &str) { self.access_tokens.insert("admin".to_string(), api_admin_token.to_string()); } } + +#[cfg(test)] +mod tests { + use crate::v1::tracker_api::HttpApi; + + #[test] + fn http_api_configuration_should_check_if_it_contains_a_token() { + let configuration = HttpApi::default(); + + assert!(configuration.access_tokens.values().any(|t| t == "MyAccessToken")); + assert!(!configuration.access_tokens.values().any(|t| t == "NonExistingToken")); + } +} From b3a1442ee808f2b50296e455880a0d767b56f599 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 May 2024 18:01:23 +0100 Subject: [PATCH 0322/1297] refactor!: remove unused method in Configuration --- packages/configuration/src/v1/mod.rs | 34 +++++++++++----------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 4413ed7c4..dbb6eb7c0 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -383,21 +383,6 @@ impl Configuration { } } - /// Loads the configuration from the configuration file. - /// - /// # Errors - /// - /// Will return `Err` if `path` does not exist or has a bad configuration. - pub fn load_from_file(path: &str) -> Result { - let figment = Figment::new() - .merge(Toml::file(path)) - .merge(Env::prefixed("TORRUST_TRACKER_")); - - let config: Configuration = figment.extract()?; - - Ok(config) - } - /// Saves the default configuration at the given path. /// /// # Errors @@ -459,6 +444,7 @@ impl Configuration { mod tests { use crate::v1::Configuration; + use crate::Info; #[cfg(test)] fn default_config_toml() -> String { @@ -550,10 +536,13 @@ mod tests { #[test] fn configuration_should_be_loaded_from_a_toml_config_file() { - figment::Jail::expect_with(|jail| { - jail.create_file("tracker.toml", &default_config_toml())?; + figment::Jail::expect_with(|_jail| { + let info = Info { + tracker_toml: default_config_toml(), + api_admin_token: None, + }; - let configuration = Configuration::load_from_file("tracker.toml").expect("Could not load configuration from file"); + let configuration = Configuration::load(&info).expect("Could not load configuration from file"); assert_eq!(configuration, Configuration::default()); @@ -564,11 +553,14 @@ mod tests { #[test] fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin() { figment::Jail::expect_with(|jail| { - jail.create_file("tracker.toml", &default_config_toml())?; - jail.set_env("TORRUST_TRACKER_HTTP_API.ACCESS_TOKENS.ADMIN", "NewToken"); - let configuration = Configuration::load_from_file("tracker.toml").expect("Could not load configuration from file"); + let info = Info { + tracker_toml: default_config_toml(), + api_admin_token: None, + }; + + let configuration = Configuration::load(&info).expect("Could not load configuration from file"); assert_eq!( configuration.http_api.access_tokens.get("admin"), From caae725578a253d9c73b85c9d4b8cb97f0ad66b3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 9 May 2024 08:15:35 +0100 Subject: [PATCH 0323/1297] feat: use double underscore to split config env var names For example, the env var `TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN` would be the config option: ``` [http_api.access_tokens] admin = "MyAccessToken" ``` It uses `__` double underscore becuase dots are not allowed in Bash names. See: https://www.gnu.org/software/bash/manual/bash.html#Definitions ``` name A word consisting solely of letters, numbers, and underscores, and beginning with a letter or underscore. Names are used as shell variable and function names. Also referred to as an identifier. ``` --- packages/configuration/src/v1/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index dbb6eb7c0..88b9565bd 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -406,7 +406,7 @@ impl Configuration { pub fn load(info: &Info) -> Result { let figment = Figment::new() .merge(Toml::string(&info.tracker_toml)) - .merge(Env::prefixed("TORRUST_TRACKER_")); + .merge(Env::prefixed("TORRUST_TRACKER__").split("__")); let mut config: Configuration = figment.extract()?; @@ -553,7 +553,7 @@ mod tests { #[test] fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin() { figment::Jail::expect_with(|jail| { - jail.set_env("TORRUST_TRACKER_HTTP_API.ACCESS_TOKENS.ADMIN", "NewToken"); + jail.set_env("TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN", "NewToken"); let info = Info { tracker_toml: default_config_toml(), From 69d793986605ff058a44a5ad4cba86f9ab50d360 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 9 May 2024 13:00:31 +0100 Subject: [PATCH 0324/1297] refactor: implement Default for Configuration sections --- .../configuration/src/v1/health_check_api.rs | 8 ++++++++ packages/configuration/src/v1/http_tracker.rs | 12 ++++++++++++ packages/configuration/src/v1/mod.rs | 17 +++-------------- packages/configuration/src/v1/udp_tracker.rs | 8 ++++++++ 4 files changed, 31 insertions(+), 14 deletions(-) diff --git a/packages/configuration/src/v1/health_check_api.rs b/packages/configuration/src/v1/health_check_api.rs index f7b15249c..1c2cd073a 100644 --- a/packages/configuration/src/v1/health_check_api.rs +++ b/packages/configuration/src/v1/health_check_api.rs @@ -11,3 +11,11 @@ pub struct HealthCheckApi { /// system to choose a random port, use port `0`. pub bind_address: String, } + +impl Default for HealthCheckApi { + fn default() -> Self { + Self { + bind_address: String::from("127.0.0.1:1313"), + } + } +} diff --git a/packages/configuration/src/v1/http_tracker.rs b/packages/configuration/src/v1/http_tracker.rs index 4c88feb9c..c2d5928e2 100644 --- a/packages/configuration/src/v1/http_tracker.rs +++ b/packages/configuration/src/v1/http_tracker.rs @@ -21,3 +21,15 @@ pub struct HttpTracker { #[serde_as(as = "NoneAsEmptyString")] pub ssl_key_path: Option, } + +impl Default for HttpTracker { + fn default() -> Self { + Self { + enabled: false, + bind_address: String::from("0.0.0.0:7070"), + ssl_enabled: false, + ssl_cert_path: None, + ssl_key_path: None, + } + } +} diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 88b9565bd..07d8a7194 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -346,21 +346,10 @@ impl Default for Configuration { udp_trackers: Vec::new(), http_trackers: Vec::new(), http_api: HttpApi::default(), - health_check_api: HealthCheckApi { - bind_address: String::from("127.0.0.1:1313"), - }, + health_check_api: HealthCheckApi::default(), }; - configuration.udp_trackers.push(UdpTracker { - enabled: false, - bind_address: String::from("0.0.0.0:6969"), - }); - configuration.http_trackers.push(HttpTracker { - enabled: false, - bind_address: String::from("0.0.0.0:7070"), - ssl_enabled: false, - ssl_cert_path: None, - ssl_key_path: None, - }); + configuration.udp_trackers.push(UdpTracker::default()); + configuration.http_trackers.push(HttpTracker::default()); configuration } } diff --git a/packages/configuration/src/v1/udp_tracker.rs b/packages/configuration/src/v1/udp_tracker.rs index b304054c3..254272bdd 100644 --- a/packages/configuration/src/v1/udp_tracker.rs +++ b/packages/configuration/src/v1/udp_tracker.rs @@ -10,3 +10,11 @@ pub struct UdpTracker { /// system to choose a random port, use port `0`. pub bind_address: String, } +impl Default for UdpTracker { + fn default() -> Self { + Self { + enabled: false, + bind_address: String::from("0.0.0.0:6969"), + } + } +} From b0c2f9f435f9a6c8b033fd70f1f0a69049709cd9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 9 May 2024 13:07:36 +0100 Subject: [PATCH 0325/1297] docs: update env var name in toml config template files --- share/default/config/tracker.container.mysql.toml | 8 ++++---- share/default/config/tracker.container.sqlite3.toml | 8 ++++---- share/default/config/tracker.development.sqlite3.toml | 4 ++++ share/default/config/tracker.e2e.container.sqlite3.toml | 8 ++++---- share/default/config/tracker.udp.benchmarking.toml | 4 ++++ 5 files changed, 20 insertions(+), 12 deletions(-) diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml index e7714c229..f2db06228 100644 --- a/share/default/config/tracker.container.mysql.toml +++ b/share/default/config/tracker.container.mysql.toml @@ -30,11 +30,11 @@ ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" -# Please override the admin token setting the -# `TORRUST_TRACKER_API_ADMIN_TOKEN` -# environmental variable! - [http_api.access_tokens] +# Please override the admin token setting the environmental variable: +# `TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN` +# The old variable name is deprecated: +# `TORRUST_TRACKER_API_ADMIN_TOKEN` admin = "MyAccessToken" [health_check_api] diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml index 4ec055c56..4a3ba03b6 100644 --- a/share/default/config/tracker.container.sqlite3.toml +++ b/share/default/config/tracker.container.sqlite3.toml @@ -30,11 +30,11 @@ ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" -# Please override the admin token setting the -# `TORRUST_TRACKER_API_ADMIN_TOKEN` -# environmental variable! - [http_api.access_tokens] +# Please override the admin token setting the environmental variable: +# `TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN` +# The old variable name is deprecated: +# `TORRUST_TRACKER_API_ADMIN_TOKEN` admin = "MyAccessToken" [health_check_api] diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index 9304a2d51..62e5b478e 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -31,6 +31,10 @@ ssl_enabled = false ssl_key_path = "" [http_api.access_tokens] +# Please override the admin token setting the environmental variable: +# `TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN` +# The old variable name is deprecated: +# `TORRUST_TRACKER_API_ADMIN_TOKEN` admin = "MyAccessToken" [health_check_api] diff --git a/share/default/config/tracker.e2e.container.sqlite3.toml b/share/default/config/tracker.e2e.container.sqlite3.toml index 86ffb3ffd..3738704b5 100644 --- a/share/default/config/tracker.e2e.container.sqlite3.toml +++ b/share/default/config/tracker.e2e.container.sqlite3.toml @@ -30,11 +30,11 @@ ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" -# Please override the admin token setting the -# `TORRUST_TRACKER_API_ADMIN_TOKEN` -# environmental variable! - [http_api.access_tokens] +# Please override the admin token setting the environmental variable: +# `TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN` +# The old variable name is deprecated: +# `TORRUST_TRACKER_API_ADMIN_TOKEN` admin = "MyAccessToken" [health_check_api] diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml index 70298e9dc..1e951d8fc 100644 --- a/share/default/config/tracker.udp.benchmarking.toml +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -31,6 +31,10 @@ ssl_enabled = false ssl_key_path = "" [http_api.access_tokens] +# Please override the admin token setting the environmental variable: +# `TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN` +# The old variable name is deprecated: +# `TORRUST_TRACKER_API_ADMIN_TOKEN` admin = "MyAccessToken" [health_check_api] From 43942ce2b0fca425558e715d7d556ce9307b0ef5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 9 May 2024 13:26:46 +0100 Subject: [PATCH 0326/1297] tests: add test for configuration with deprecated env var name Until it's updated in this repor and the Index repo you can overwrite the admin token using the new env var name and the old one (deprecated): - New: `TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN` - Old (deprecated): `TORRUST_TRACKER_API_ADMIN_TOKEN` THe new one uses exactly the strcuture and atribute names in the toml file, using `__` as the separator for levels. We can remove the test when we remove the deprecated name. --- packages/configuration/src/v1/mod.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 07d8a7194..8d5c123fe 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -540,7 +540,7 @@ mod tests { } #[test] - fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin() { + fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin_with_env_var() { figment::Jail::expect_with(|jail| { jail.set_env("TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN", "NewToken"); @@ -559,4 +559,23 @@ mod tests { Ok(()) }); } + + #[test] + fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin_with_the_deprecated_env_var_name() { + figment::Jail::expect_with(|_jail| { + let info = Info { + tracker_toml: default_config_toml(), + api_admin_token: Some("NewToken".to_owned()), + }; + + let configuration = Configuration::load(&info).expect("Could not load configuration from file"); + + assert_eq!( + configuration.http_api.access_tokens.get("admin"), + Some("NewToken".to_owned()).as_ref() + ); + + Ok(()) + }); + } } From 0252f308183e8ea53988907e7553eda8952ebdc7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 9 May 2024 13:47:22 +0100 Subject: [PATCH 0327/1297] feat: allow users not to provide config option with default values Now, you are able to run the tracler like this: ``` TORRUST_TRACKER_CONFIG="" cargo run ``` Default values will be used for the missing values in the provided configuration. In that case, none of the values have been provided, so it will use default values for all options. --- packages/configuration/src/v1/mod.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 8d5c123fe..25aa587b3 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -239,7 +239,7 @@ use std::fs; use std::net::IpAddr; use std::str::FromStr; -use figment::providers::{Env, Format, Toml}; +use figment::providers::{Env, Format, Serialized, Toml}; use figment::Figment; use serde::{Deserialize, Serialize}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; @@ -393,7 +393,7 @@ impl Configuration { /// /// Will return `Err` if the environment variable does not exist or has a bad configuration. pub fn load(info: &Info) -> Result { - let figment = Figment::new() + let figment = Figment::from(Serialized::defaults(Configuration::default())) .merge(Toml::string(&info.tracker_toml)) .merge(Env::prefixed("TORRUST_TRACKER__").split("__")); @@ -523,6 +523,24 @@ mod tests { assert_eq!(contents, default_config_toml()); } + #[test] + fn configuration_should_use_the_default_values_when_an_empty_configuration_is_provided_by_the_user() { + figment::Jail::expect_with(|_jail| { + let empty_configuration = String::new(); + + let info = Info { + tracker_toml: empty_configuration, + api_admin_token: None, + }; + + let configuration = Configuration::load(&info).expect("Could not load configuration from file"); + + assert_eq!(configuration, Configuration::default()); + + Ok(()) + }); + } + #[test] fn configuration_should_be_loaded_from_a_toml_config_file() { figment::Jail::expect_with(|_jail| { From 384e9f820ea685d6f4d2cc9639b83df478b6b359 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 9 May 2024 17:19:30 +0100 Subject: [PATCH 0328/1297] refactor: [#852] eenrich field types in HealthCheckApi config struct --- packages/configuration/src/v1/health_check_api.rs | 6 ++++-- packages/test-helpers/src/configuration.rs | 4 ++-- src/bootstrap/jobs/health_check_api.rs | 5 +---- tests/servers/health_check_api/environment.rs | 5 +---- 4 files changed, 8 insertions(+), 12 deletions(-) diff --git a/packages/configuration/src/v1/health_check_api.rs b/packages/configuration/src/v1/health_check_api.rs index 1c2cd073a..b8bfd2c1b 100644 --- a/packages/configuration/src/v1/health_check_api.rs +++ b/packages/configuration/src/v1/health_check_api.rs @@ -1,3 +1,5 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use serde::{Deserialize, Serialize}; use serde_with::serde_as; @@ -9,13 +11,13 @@ pub struct HealthCheckApi { /// The format is `ip:port`, for example `127.0.0.1:1313`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating /// system to choose a random port, use port `0`. - pub bind_address: String, + pub bind_address: SocketAddr, } impl Default for HealthCheckApi { fn default() -> Self { Self { - bind_address: String::from("127.0.0.1:1313"), + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1313), } } } diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 49cfdd390..c1ee95197 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -1,6 +1,6 @@ //! Tracker configuration factories for testing. use std::env; -use std::net::IpAddr; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::TrackerMode; @@ -39,7 +39,7 @@ pub fn ephemeral() -> Configuration { // Ephemeral socket address for Health Check API let health_check_api_port = 0u16; - config.health_check_api.bind_address = format!("127.0.0.1:{}", &health_check_api_port); + config.health_check_api.bind_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), health_check_api_port); // Ephemeral socket address for UDP tracker let udp_port = 0u16; diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index eec4d81a8..fdedaa3e9 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -35,10 +35,7 @@ use crate::servers::signals::Halted; /// /// It would panic if unable to send the `ApiServerJobStarted` notice. pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> JoinHandle<()> { - let bind_addr = config - .bind_address - .parse::() - .expect("it should have a valid health check bind address"); + let bind_addr = config.bind_address; let (tx_start, rx_start) = oneshot::channel::(); let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs index 0856985d5..c200beaeb 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/tests/servers/health_check_api/environment.rs @@ -33,10 +33,7 @@ pub struct Environment { impl Environment { pub fn new(config: &Arc, registar: Registar) -> Self { - let bind_to = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); + let bind_to = config.bind_address; Self { registar, From 1475eadd25e7fbf208523f72f49188d3f28173c2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 10 May 2024 11:12:53 +0100 Subject: [PATCH 0329/1297] refactor: [#852] eenrich field types in UdpTracker config struct --- packages/configuration/src/v1/udp_tracker.rs | 6 ++++-- packages/test-helpers/src/configuration.rs | 10 +++++----- src/bootstrap/jobs/udp_tracker.rs | 5 +---- src/servers/udp/server.rs | 9 +++------ tests/servers/udp/environment.rs | 5 +---- 5 files changed, 14 insertions(+), 21 deletions(-) diff --git a/packages/configuration/src/v1/udp_tracker.rs b/packages/configuration/src/v1/udp_tracker.rs index 254272bdd..1f772164e 100644 --- a/packages/configuration/src/v1/udp_tracker.rs +++ b/packages/configuration/src/v1/udp_tracker.rs @@ -1,3 +1,5 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] @@ -8,13 +10,13 @@ pub struct UdpTracker { /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating /// system to choose a random port, use port `0`. - pub bind_address: String, + pub bind_address: SocketAddr, } impl Default for UdpTracker { fn default() -> Self { Self { enabled: false, - bind_address: String::from("0.0.0.0:6969"), + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 6969), } } } diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index c1ee95197..c28cf553e 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -1,6 +1,6 @@ //! Tracker configuration factories for testing. use std::env; -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::TrackerMode; @@ -44,7 +44,7 @@ pub fn ephemeral() -> Configuration { // Ephemeral socket address for UDP tracker let udp_port = 0u16; config.udp_trackers[0].enabled = true; - config.udp_trackers[0].bind_address = format!("127.0.0.1:{}", &udp_port); + config.udp_trackers[0].bind_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), udp_port); // Ephemeral socket address for HTTP tracker let http_port = 0u16; @@ -136,10 +136,10 @@ pub fn ephemeral_with_external_ip(ip: IpAddr) -> Configuration { pub fn ephemeral_ipv6() -> Configuration { let mut cfg = ephemeral(); - let ipv6 = format!("[::]:{}", 0); + let ipv6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), 0); - cfg.http_api.bind_address.clone_from(&ipv6); - cfg.http_trackers[0].bind_address.clone_from(&ipv6); + cfg.http_api.bind_address.clone_from(&ipv6.to_string()); + cfg.http_trackers[0].bind_address.clone_from(&ipv6.to_string()); cfg.udp_trackers[0].bind_address = ipv6; cfg diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index e9e4bc642..bb1cdb492 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -27,10 +27,7 @@ use crate::servers::udp::server::{Launcher, UdpServer}; /// It will panic if the task did not finish successfully. #[must_use] pub async fn start_job(config: &UdpTracker, tracker: Arc, form: ServiceRegistrationForm) -> JoinHandle<()> { - let bind_to = config - .bind_address - .parse::() - .expect("it should have a valid udp tracker bind address"); + let bind_to = config.bind_address; let server = UdpServer::new(Launcher::new(bind_to)) .start(tracker, form) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index f7092f377..b02b9802d 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -463,19 +463,16 @@ mod tests { let cfg = Arc::new(ephemeral_mode_public()); let tracker = initialize_with_configuration(&cfg); let config = &cfg.udp_trackers[0]; - - let bind_to = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); - + let bind_to = config.bind_address; let register = &Registar::default(); let stopped = UdpServer::new(Launcher::new(bind_to)); + let started = stopped .start(tracker, register.give_form()) .await .expect("it should start the server"); + let stopped = started.stop().await.expect("it should stop the server"); tokio::time::sleep(Duration::from_secs(1)).await; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 6ced1dbb7..c1fecbdd3 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -31,10 +31,7 @@ impl Environment { let config = Arc::new(configuration.udp_trackers[0].clone()); - let bind_to = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); + let bind_to = config.bind_address; let server = UdpServer::new(Launcher::new(bind_to)); From fc191f7b6f8eef730665f16739e016ed1b4b5820 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 10 May 2024 11:26:04 +0100 Subject: [PATCH 0330/1297] refactor: [#852] enrich field types in HttpTracker config struct If the next major config version the `TslConfig` shoud always contain valid file paths and the whole field should be optional in the parent strcut `HttpTracker`: ```rust pub struct HttpTracker { pub enabled: bool, pub bind_address: SocketAddr, pub ssl_enabled: bool, #[serde(flatten)] pub tsl_config: Optional, } pub struct TslConfig { pub ssl_cert_path: PathBuf, pub ssl_key_path: PathBuf, } ``` That mean, the user could provide it or not, but if it's provided file paths can't be empty. --- packages/configuration/src/lib.rs | 13 +++++++++++ packages/configuration/src/v1/http_tracker.rs | 22 +++++++++---------- packages/test-helpers/src/configuration.rs | 4 ++-- src/bootstrap/jobs/http_tracker.rs | 15 +++++++------ src/servers/http/server.rs | 17 +++++++------- tests/servers/http/environment.rs | 13 ++++++----- 6 files changed, 50 insertions(+), 34 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 20912990a..f1e316f10 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -11,6 +11,8 @@ use std::sync::Arc; use std::{env, fs}; use derive_more::Constructor; +use serde::{Deserialize, Serialize}; +use serde_with::{serde_as, NoneAsEmptyString}; use thiserror::Error; use torrust_tracker_located_error::{DynError, LocatedError}; @@ -157,3 +159,14 @@ impl From for Error { } } } + +#[serde_as] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Default)] +pub struct TslConfig { + /// Path to the SSL certificate file. + #[serde_as(as = "NoneAsEmptyString")] + pub ssl_cert_path: Option, + /// Path to the SSL key file. + #[serde_as(as = "NoneAsEmptyString")] + pub ssl_key_path: Option, +} diff --git a/packages/configuration/src/v1/http_tracker.rs b/packages/configuration/src/v1/http_tracker.rs index c2d5928e2..57b2d83a1 100644 --- a/packages/configuration/src/v1/http_tracker.rs +++ b/packages/configuration/src/v1/http_tracker.rs @@ -1,5 +1,9 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use serde::{Deserialize, Serialize}; -use serde_with::{serde_as, NoneAsEmptyString}; +use serde_with::serde_as; + +use crate::TslConfig; /// Configuration for each HTTP tracker. #[serde_as] @@ -11,25 +15,21 @@ pub struct HttpTracker { /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating /// system to choose a random port, use port `0`. - pub bind_address: String, + pub bind_address: SocketAddr, /// Weather the HTTP tracker will use SSL or not. pub ssl_enabled: bool, - /// Path to the SSL certificate file. Only used if `ssl_enabled` is `true`. - #[serde_as(as = "NoneAsEmptyString")] - pub ssl_cert_path: Option, - /// Path to the SSL key file. Only used if `ssl_enabled` is `true`. - #[serde_as(as = "NoneAsEmptyString")] - pub ssl_key_path: Option, + /// TSL config. Only used if `ssl_enabled` is true. + #[serde(flatten)] + pub tsl_config: TslConfig, } impl Default for HttpTracker { fn default() -> Self { Self { enabled: false, - bind_address: String::from("0.0.0.0:7070"), + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 7070), ssl_enabled: false, - ssl_cert_path: None, - ssl_key_path: None, + tsl_config: TslConfig::default(), } } } diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index c28cf553e..e6f53f85b 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -49,7 +49,7 @@ pub fn ephemeral() -> Configuration { // Ephemeral socket address for HTTP tracker let http_port = 0u16; config.http_trackers[0].enabled = true; - config.http_trackers[0].bind_address = format!("127.0.0.1:{}", &http_port); + config.http_trackers[0].bind_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), http_port); // Ephemeral sqlite database let temp_directory = env::temp_dir(); @@ -139,7 +139,7 @@ pub fn ephemeral_ipv6() -> Configuration { let ipv6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), 0); cfg.http_api.bind_address.clone_from(&ipv6.to_string()); - cfg.http_trackers[0].bind_address.clone_from(&ipv6.to_string()); + cfg.http_trackers[0].bind_address.clone_from(&ipv6); cfg.udp_trackers[0].bind_address = ipv6; cfg diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 0a0638b78..88d643149 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -40,14 +40,15 @@ pub async fn start_job( version: Version, ) -> Option> { if config.enabled { - let socket = config - .bind_address - .parse::() - .expect("it should have a valid http tracker bind address"); + let socket = config.bind_address; - let tls = make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path) - .await - .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); + let tls = make_rust_tls( + config.ssl_enabled, + &config.tsl_config.ssl_cert_path, + &config.tsl_config.ssl_key_path, + ) + .await + .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); match version { Version::V1 => Some(start_v1(socket, tls, tracker.clone(), form).await), diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index decc734c5..5791708ec 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -234,14 +234,15 @@ mod tests { let tracker = initialize_with_configuration(&cfg); let config = &cfg.http_trackers[0]; - let bind_to = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); - - let tls = make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path) - .await - .map(|tls| tls.expect("tls config failed")); + let bind_to = config.bind_address; + + let tls = make_rust_tls( + config.ssl_enabled, + &config.tsl_config.ssl_cert_path, + &config.tsl_config.ssl_key_path, + ) + .await + .map(|tls| tls.expect("tls config failed")); let register = &Registar::default(); diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index f00da293e..e3aa6641e 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -31,13 +31,14 @@ impl Environment { let config = Arc::new(configuration.http_trackers[0].clone()); - let bind_to = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); + let bind_to = config.bind_address; - let tls = block_on(make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path)) - .map(|tls| tls.expect("tls config failed")); + let tls = block_on(make_rust_tls( + config.ssl_enabled, + &config.tsl_config.ssl_cert_path, + &config.tsl_config.ssl_key_path, + )) + .map(|tls| tls.expect("tls config failed")); let server = HttpServer::new(Launcher::new(bind_to, tls)); From a2e718bb1d56b5977f53bed0e10b677db4b4e63e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 10 May 2024 12:00:24 +0100 Subject: [PATCH 0331/1297] chore(deps): add dependency camino We are using `String` to represent a filepath. We are refactoring to enrich types in configuration. Filepath should be represented with `PathBuf` but it allows non UTF-8 chars, so it can't be serialized. Since we need to serialize config options (toml, json) is valid UTF-8 strings, we need a type that represents a valid fileptah but also is a valid UTF-8 strings. That makes impossible to use non-UTF8 fielpath. It seems that's a restriction accepted for a lot of projects including Rust `cargo`. --- Cargo.lock | 11 +++++++++++ Cargo.toml | 1 + cSpell.json | 1 + packages/configuration/Cargo.toml | 1 + 4 files changed, 14 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 0bbf0205a..e54601bcf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -720,6 +720,15 @@ version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" +[[package]] +name = "camino" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59e92b5a388f549b863a7bea62612c09f24c8393560709a54558a9abdfb3b9c" +dependencies = [ + "serde", +] + [[package]] name = "cast" version = "0.3.0" @@ -3880,6 +3889,7 @@ dependencies = [ "axum-client-ip", "axum-extra", "axum-server", + "camino", "chrono", "clap", "crossbeam-skiplist", @@ -3938,6 +3948,7 @@ dependencies = [ name = "torrust-tracker-configuration" version = "3.0.0-alpha.12-develop" dependencies = [ + "camino", "derive_more", "figment", "serde", diff --git a/Cargo.toml b/Cargo.toml index d7aa9a31c..60652b160 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,7 @@ axum = { version = "0", features = ["macros"] } axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls"] } +camino = { version = "1.1.6", features = ["serde"] } chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } crossbeam-skiplist = "0.1" diff --git a/cSpell.json b/cSpell.json index 2473e9c33..bd6c9d489 100644 --- a/cSpell.json +++ b/cSpell.json @@ -25,6 +25,7 @@ "Buildx", "byteorder", "callgrind", + "camino", "canonicalize", "canonicalized", "certbot", diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index a033dcea1..bac2132d5 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -15,6 +15,7 @@ rust-version.workspace = true version.workspace = true [dependencies] +camino = { version = "1.1.6", features = ["serde"] } derive_more = "0" figment = { version = "0.10.18", features = ["env", "test", "toml"] } serde = { version = "1", features = ["derive"] } From 3997cfa256a944b30b55f2d94ae5dbcf0670a696 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 10 May 2024 12:06:32 +0100 Subject: [PATCH 0332/1297] refactor: [#852] eenrich field types in TslConfig config struct --- packages/configuration/src/lib.rs | 5 +++-- src/bootstrap/jobs/http_tracker.rs | 4 ++-- src/bootstrap/jobs/mod.rs | 31 +++++++++++++++++++++++++++++- src/servers/http/server.rs | 4 ++-- tests/servers/http/environment.rs | 4 ++-- 5 files changed, 39 insertions(+), 9 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index f1e316f10..239803f47 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -10,6 +10,7 @@ use std::collections::HashMap; use std::sync::Arc; use std::{env, fs}; +use camino::Utf8PathBuf; use derive_more::Constructor; use serde::{Deserialize, Serialize}; use serde_with::{serde_as, NoneAsEmptyString}; @@ -165,8 +166,8 @@ impl From for Error { pub struct TslConfig { /// Path to the SSL certificate file. #[serde_as(as = "NoneAsEmptyString")] - pub ssl_cert_path: Option, + pub ssl_cert_path: Option, /// Path to the SSL key file. #[serde_as(as = "NoneAsEmptyString")] - pub ssl_key_path: Option, + pub ssl_key_path: Option, } diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 88d643149..d9e8bdabe 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -18,7 +18,7 @@ use log::info; use tokio::task::JoinHandle; use torrust_tracker_configuration::HttpTracker; -use super::make_rust_tls; +use super::make_rust_tls_from_path_buf; use crate::core; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::http::Version; @@ -42,7 +42,7 @@ pub async fn start_job( if config.enabled { let socket = config.bind_address; - let tls = make_rust_tls( + let tls = make_rust_tls_from_path_buf( config.ssl_enabled, &config.tsl_config.ssl_cert_path, &config.tsl_config.ssl_key_path, diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 2c12eb40e..dd855f7c6 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -28,7 +28,35 @@ pub async fn make_rust_tls(enabled: bool, cert: &Option, key: &Option, + key: &Option, +) -> Option> { + if !enabled { + info!("TLS not enabled"); + return None; + } + + if let (Some(cert), Some(key)) = (cert, key) { + info!("Using https: cert path: {cert}."); + info!("Using https: key path: {key}."); Some( RustlsConfig::from_pem_file(cert, key) @@ -77,6 +105,7 @@ use std::panic::Location; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; +use camino::Utf8PathBuf; use log::info; use thiserror::Error; use torrust_tracker_located_error::{DynError, LocatedError}; diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 5791708ec..a6f96634f 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -224,7 +224,7 @@ mod tests { use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; use crate::bootstrap::app::initialize_with_configuration; - use crate::bootstrap::jobs::make_rust_tls; + use crate::bootstrap::jobs::make_rust_tls_from_path_buf; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::registar::Registar; @@ -236,7 +236,7 @@ mod tests { let bind_to = config.bind_address; - let tls = make_rust_tls( + let tls = make_rust_tls_from_path_buf( config.ssl_enabled, &config.tsl_config.ssl_cert_path, &config.tsl_config.ssl_key_path, diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index e3aa6641e..e662cea7c 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use futures::executor::block_on; use torrust_tracker::bootstrap::app::initialize_with_configuration; -use torrust_tracker::bootstrap::jobs::make_rust_tls; +use torrust_tracker::bootstrap::jobs::make_rust_tls_from_path_buf; use torrust_tracker::core::Tracker; use torrust_tracker::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker::servers::registar::Registar; @@ -33,7 +33,7 @@ impl Environment { let bind_to = config.bind_address; - let tls = block_on(make_rust_tls( + let tls = block_on(make_rust_tls_from_path_buf( config.ssl_enabled, &config.tsl_config.ssl_cert_path, &config.tsl_config.ssl_key_path, From ceb30747cec6372b5244f797ad032c7db8c03d6b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 10 May 2024 12:49:57 +0100 Subject: [PATCH 0333/1297] refactor: [#852] enrich field types in HttpApi config struct --- packages/configuration/src/v1/tracker_api.rs | 23 ++++--- packages/test-helpers/src/configuration.rs | 4 +- src/bootstrap/jobs/http_tracker.rs | 12 ++-- src/bootstrap/jobs/mod.rs | 68 ++++++++------------ src/bootstrap/jobs/tracker_apis.rs | 7 +- src/servers/apis/server.rs | 7 +- src/servers/http/server.rs | 12 ++-- tests/servers/api/environment.rs | 8 +-- tests/servers/http/environment.rs | 9 +-- 9 files changed, 56 insertions(+), 94 deletions(-) diff --git a/packages/configuration/src/v1/tracker_api.rs b/packages/configuration/src/v1/tracker_api.rs index 8749478c8..5089c496a 100644 --- a/packages/configuration/src/v1/tracker_api.rs +++ b/packages/configuration/src/v1/tracker_api.rs @@ -1,7 +1,10 @@ use std::collections::HashMap; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use serde::{Deserialize, Serialize}; -use serde_with::{serde_as, NoneAsEmptyString}; +use serde_with::serde_as; + +use crate::TslConfig; pub type AccessTokens = HashMap; @@ -15,19 +18,16 @@ pub struct HttpApi { /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating /// system to choose a random port, use port `0`. - pub bind_address: String, + pub bind_address: SocketAddr, /// Weather the HTTP API will use SSL or not. pub ssl_enabled: bool, - /// Path to the SSL certificate file. Only used if `ssl_enabled` is `true`. - #[serde_as(as = "NoneAsEmptyString")] - pub ssl_cert_path: Option, - /// Path to the SSL key file. Only used if `ssl_enabled` is `true`. - #[serde_as(as = "NoneAsEmptyString")] - pub ssl_key_path: Option, + /// TSL config. Only used if `ssl_enabled` is true. + #[serde(flatten)] + pub tsl_config: TslConfig, /// Access tokens for the HTTP API. The key is a label identifying the /// token and the value is the token itself. The token is used to /// authenticate the user. All tokens are valid for all endpoints and have - /// the all permissions. + /// all permissions. pub access_tokens: AccessTokens, } @@ -35,10 +35,9 @@ impl Default for HttpApi { fn default() -> Self { Self { enabled: true, - bind_address: String::from("127.0.0.1:1212"), + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1212), ssl_enabled: false, - ssl_cert_path: None, - ssl_key_path: None, + tsl_config: TslConfig::default(), access_tokens: [(String::from("admin"), String::from("MyAccessToken"))] .iter() .cloned() diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index e6f53f85b..08f570dc6 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -35,7 +35,7 @@ pub fn ephemeral() -> Configuration { // Ephemeral socket address for API let api_port = 0u16; config.http_api.enabled = true; - config.http_api.bind_address = format!("127.0.0.1:{}", &api_port); + config.http_api.bind_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), api_port); // Ephemeral socket address for Health Check API let health_check_api_port = 0u16; @@ -138,7 +138,7 @@ pub fn ephemeral_ipv6() -> Configuration { let ipv6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), 0); - cfg.http_api.bind_address.clone_from(&ipv6.to_string()); + cfg.http_api.bind_address.clone_from(&ipv6); cfg.http_trackers[0].bind_address.clone_from(&ipv6); cfg.udp_trackers[0].bind_address = ipv6; diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index d9e8bdabe..d8a976b98 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -18,7 +18,7 @@ use log::info; use tokio::task::JoinHandle; use torrust_tracker_configuration::HttpTracker; -use super::make_rust_tls_from_path_buf; +use super::make_rust_tls; use crate::core; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::http::Version; @@ -42,13 +42,9 @@ pub async fn start_job( if config.enabled { let socket = config.bind_address; - let tls = make_rust_tls_from_path_buf( - config.ssl_enabled, - &config.tsl_config.ssl_cert_path, - &config.tsl_config.ssl_key_path, - ) - .await - .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); + let tls = make_rust_tls(config.ssl_enabled, &config.tsl_config) + .await + .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); match version { Version::V1 => Some(start_v1(socket, tls, tracker.clone(), form).await), diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index dd855f7c6..d288989b5 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -20,41 +20,13 @@ pub struct Started { pub address: std::net::SocketAddr, } -pub async fn make_rust_tls(enabled: bool, cert: &Option, key: &Option) -> Option> { +pub async fn make_rust_tls(enabled: bool, tsl_config: &TslConfig) -> Option> { if !enabled { info!("TLS not enabled"); return None; } - if let (Some(cert), Some(key)) = (cert, key) { - info!("Using https: cert path: {cert}."); - info!("Using https: key path: {key}."); - - Some( - RustlsConfig::from_pem_file(cert, key) - .await - .map_err(|err| Error::BadTlsConfig { - source: (Arc::new(err) as DynError).into(), - }), - ) - } else { - Some(Err(Error::MissingTlsConfig { - location: Location::caller(), - })) - } -} - -pub async fn make_rust_tls_from_path_buf( - enabled: bool, - cert: &Option, - key: &Option, -) -> Option> { - if !enabled { - info!("TLS not enabled"); - return None; - } - - if let (Some(cert), Some(key)) = (cert, key) { + if let (Some(cert), Some(key)) = (tsl_config.ssl_cert_path.clone(), tsl_config.ssl_key_path.clone()) { info!("Using https: cert path: {cert}."); info!("Using https: key path: {key}."); @@ -75,15 +47,23 @@ pub async fn make_rust_tls_from_path_buf( #[cfg(test)] mod tests { + use camino::Utf8PathBuf; + use torrust_tracker_configuration::TslConfig; + use super::make_rust_tls; #[tokio::test] async fn it_should_error_on_bad_tls_config() { - let (bad_cert_path, bad_key_path) = (Some("bad cert path".to_string()), Some("bad key path".to_string())); - let err = make_rust_tls(true, &bad_cert_path, &bad_key_path) - .await - .expect("tls_was_enabled") - .expect_err("bad_cert_and_key_files"); + let err = make_rust_tls( + true, + &TslConfig { + ssl_cert_path: Some(Utf8PathBuf::from("bad cert path")), + ssl_key_path: Some(Utf8PathBuf::from("bad key path")), + }, + ) + .await + .expect("tls_was_enabled") + .expect_err("bad_cert_and_key_files"); assert!(err .to_string() @@ -91,11 +71,17 @@ mod tests { } #[tokio::test] - async fn it_should_error_on_missing_tls_config() { - let err = make_rust_tls(true, &None, &None) - .await - .expect("tls_was_enabled") - .expect_err("missing_config"); + async fn it_should_error_on_missing_cert_or_key_paths() { + let err = make_rust_tls( + true, + &TslConfig { + ssl_cert_path: None, + ssl_key_path: None, + }, + ) + .await + .expect("tls_was_enabled") + .expect_err("missing_config"); assert_eq!(err.to_string(), "tls config missing"); } @@ -105,9 +91,9 @@ use std::panic::Location; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; -use camino::Utf8PathBuf; use log::info; use thiserror::Error; +use torrust_tracker_configuration::TslConfig; use torrust_tracker_located_error::{DynError, LocatedError}; /// Error returned by the Bootstrap Process. diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index ffd7c7407..120c960ef 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -61,12 +61,9 @@ pub async fn start_job( version: Version, ) -> Option> { if config.enabled { - let bind_to = config - .bind_address - .parse::() - .expect("it should have a valid tracker api bind address"); + let bind_to = config.bind_address; - let tls = make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path) + let tls = make_rust_tls(config.ssl_enabled, &config.tsl_config) .await .map(|tls| tls.expect("it should have a valid tracker api tls configuration")); diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index e72890557..9317d6ec0 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -275,12 +275,9 @@ mod tests { let tracker = initialize_with_configuration(&cfg); - let bind_to = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); + let bind_to = config.bind_address; - let tls = make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path) + let tls = make_rust_tls(config.ssl_enabled, &config.tsl_config) .await .map(|tls| tls.expect("tls config failed")); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index a6f96634f..7c8148f22 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -224,7 +224,7 @@ mod tests { use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; use crate::bootstrap::app::initialize_with_configuration; - use crate::bootstrap::jobs::make_rust_tls_from_path_buf; + use crate::bootstrap::jobs::make_rust_tls; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::registar::Registar; @@ -236,13 +236,9 @@ mod tests { let bind_to = config.bind_address; - let tls = make_rust_tls_from_path_buf( - config.ssl_enabled, - &config.tsl_config.ssl_cert_path, - &config.tsl_config.ssl_key_path, - ) - .await - .map(|tls| tls.expect("tls config failed")); + let tls = make_rust_tls(config.ssl_enabled, &config.tsl_config) + .await + .map(|tls| tls.expect("tls config failed")); let register = &Registar::default(); diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index dec4ccff2..cacde8af9 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -33,13 +33,9 @@ impl Environment { let config = Arc::new(configuration.http_api.clone()); - let bind_to = config - .bind_address - .parse::() - .expect("Tracker API bind_address invalid."); + let bind_to = config.bind_address; - let tls = block_on(make_rust_tls(config.ssl_enabled, &config.ssl_cert_path, &config.ssl_key_path)) - .map(|tls| tls.expect("tls config failed")); + let tls = block_on(make_rust_tls(config.ssl_enabled, &config.tsl_config)).map(|tls| tls.expect("tls config failed")); let server = ApiServer::new(Launcher::new(bind_to, tls)); diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index e662cea7c..61837c40f 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use futures::executor::block_on; use torrust_tracker::bootstrap::app::initialize_with_configuration; -use torrust_tracker::bootstrap::jobs::make_rust_tls_from_path_buf; +use torrust_tracker::bootstrap::jobs::make_rust_tls; use torrust_tracker::core::Tracker; use torrust_tracker::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker::servers::registar::Registar; @@ -33,12 +33,7 @@ impl Environment { let bind_to = config.bind_address; - let tls = block_on(make_rust_tls_from_path_buf( - config.ssl_enabled, - &config.tsl_config.ssl_cert_path, - &config.tsl_config.ssl_key_path, - )) - .map(|tls| tls.expect("tls config failed")); + let tls = block_on(make_rust_tls(config.ssl_enabled, &config.tsl_config)).map(|tls| tls.expect("tls config failed")); let server = HttpServer::new(Launcher::new(bind_to, tls)); From 7519ecc70052555dcaf9b59f533327d190649cd6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 10 May 2024 13:47:47 +0100 Subject: [PATCH 0334/1297] refactor: [#852] enrich field types in Configuration struct --- packages/configuration/src/lib.rs | 17 +++++++++++++++ packages/configuration/src/v1/mod.rs | 25 +++++++++------------- packages/test-helpers/src/configuration.rs | 6 +++--- src/bootstrap/logging.rs | 14 ++++++++---- src/servers/apis/mod.rs | 4 ++-- src/servers/http/v1/services/announce.rs | 5 +++-- src/servers/udp/handlers.rs | 2 +- 7 files changed, 46 insertions(+), 27 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 239803f47..85867816c 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -171,3 +171,20 @@ pub struct TslConfig { #[serde_as(as = "NoneAsEmptyString")] pub ssl_key_path: Option, } + +#[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, +} diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 25aa587b3..643235c03 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -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; @@ -248,7 +247,7 @@ 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)] @@ -256,7 +255,7 @@ use crate::{AnnouncePolicy, Error, Info}; pub struct Configuration { /// Logging level. Possible values are: `Off`, `Error`, `Warn`, `Info`, /// `Debug` and `Trace`. Default is `Info`. - pub log_level: Option, + pub log_level: Option, /// Tracker mode. See [`TrackerMode`] for more information. pub mode: TrackerMode, @@ -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, + pub external_ip: Option, /// 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. @@ -330,7 +329,7 @@ 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"), @@ -338,7 +337,7 @@ impl Default for Configuration { 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, @@ -363,13 +362,7 @@ impl Configuration { /// and `None` otherwise. #[must_use] pub fn get_ext_ip(&self) -> Option { - 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. @@ -432,6 +425,8 @@ impl Configuration { #[cfg(test)] mod tests { + use std::net::{IpAddr, Ipv4Addr}; + use crate::v1::Configuration; use crate::Info; @@ -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] diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 08f570dc6..0c7cc533a 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -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; @@ -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() }; @@ -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 } diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index 97e26919d..b71079b57 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -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(); @@ -31,10 +30,17 @@ pub fn setup(cfg: &Configuration) { }); } -fn config_level_or_default(log_level: &Option) -> LevelFilter { +fn config_level_or_default(log_level: &Option) -> 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, + }, } } diff --git a/src/servers/apis/mod.rs b/src/servers/apis/mod.rs index 2d4b3abe1..ef37026fe 100644 --- a/src/servers/apis/mod.rs +++ b/src/servers/apis/mod.rs @@ -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. //! diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index b37081045..5a0ae40e4 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -145,8 +145,9 @@ mod tests { fn tracker_with_an_ipv6_external_ip(stats_event_sender: Box) -> 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() } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 876f4c9fe..d8ca4680c 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -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 } From b545b33c17b3f71591a98dba9aeab84294cd1a62 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 10 May 2024 15:59:58 +0100 Subject: [PATCH 0335/1297] refactor: [#852] extract Core configuration type --- packages/configuration/src/lib.rs | 4 +- packages/configuration/src/v1/core.rs | 88 +++++++++++++++ packages/configuration/src/v1/mod.rs | 101 +++--------------- packages/test-helpers/src/configuration.rs | 23 ++-- src/app.rs | 6 +- src/bootstrap/jobs/torrent_cleanup.rs | 4 +- src/bootstrap/logging.rs | 2 +- src/core/mod.rs | 16 +-- src/core/services/mod.rs | 2 +- .../http/v1/extractors/client_ip_sources.rs | 2 +- src/servers/http/v1/services/announce.rs | 2 +- src/servers/udp/handlers.rs | 2 +- 12 files changed, 134 insertions(+), 118 deletions(-) create mode 100644 packages/configuration/src/v1/core.rs diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 85867816c..fdc021480 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -3,7 +3,7 @@ //! This module contains the configuration data structures for the //! Torrust Tracker, which is a `BitTorrent` tracker server. //! -//! The current version for configuration is [`v1`](crate::v1). +//! The current version for configuration is [`v1`]. pub mod v1; use std::collections::HashMap; @@ -172,7 +172,7 @@ pub struct TslConfig { pub ssl_key_path: Option, } -#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] +#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Clone)] #[serde(rename_all = "lowercase")] pub enum LogLevel { /// A level lower than all log levels. diff --git a/packages/configuration/src/v1/core.rs b/packages/configuration/src/v1/core.rs new file mode 100644 index 000000000..ed9074194 --- /dev/null +++ b/packages/configuration/src/v1/core.rs @@ -0,0 +1,88 @@ +use std::net::{IpAddr, Ipv4Addr}; + +use serde::{Deserialize, Serialize}; +use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; + +use crate::{AnnouncePolicy, LogLevel}; + +#[allow(clippy::struct_excessive_bools)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct Core { + /// Logging level. Possible values are: `Off`, `Error`, `Warn`, `Info`, + /// `Debug` and `Trace`. Default is `Info`. + pub log_level: Option, + /// Tracker mode. See [`TrackerMode`] for more information. + pub mode: TrackerMode, + + // Database configuration + /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. + pub db_driver: DatabaseDriver, + /// Database connection string. The format depends on the database driver. + /// For `Sqlite3`, the format is `path/to/database.db`, for example: + /// `./storage/tracker/lib/database/sqlite3.db`. + /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for + /// example: `root:password@localhost:3306/torrust`. + pub db_path: String, + + /// See [`AnnouncePolicy::interval`] + pub announce_interval: u32, + + /// See [`AnnouncePolicy::interval_min`] + pub min_announce_interval: u32, + /// Weather the tracker is behind a reverse proxy or not. + /// If the tracker is behind a reverse proxy, the `X-Forwarded-For` header + /// sent from the proxy will be used to get the client's IP address. + pub on_reverse_proxy: bool, + /// The external IP address of the tracker. If the client is using a + /// loopback IP address, this IP address will be used instead. If the peer + /// 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, + /// 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. + /// Refer to the [`Tracker`](https://docs.rs/torrust-tracker) for more + /// information about the collected metrics. + pub tracker_usage_statistics: bool, + /// If enabled the tracker will persist the number of completed downloads. + /// That's how many times a torrent has been downloaded completely. + pub persistent_torrent_completed_stat: bool, + + // Cleanup job configuration + /// Maximum time in seconds that a peer can be inactive before being + /// considered an inactive peer. If a peer is inactive for more than this + /// time, it will be removed from the torrent peer list. + pub max_peer_timeout: u32, + /// Interval in seconds that the cleanup job will run to remove inactive + /// peers from the torrent peer list. + pub inactive_peer_cleanup_interval: u64, + /// If enabled, the tracker will remove torrents that have no peers. + /// The clean up torrent job runs every `inactive_peer_cleanup_interval` + /// seconds and it removes inactive peers. Eventually, the peer list of a + /// torrent could be empty and the torrent will be removed if this option is + /// enabled. + pub remove_peerless_torrents: bool, +} + +impl Default for Core { + fn default() -> Self { + let announce_policy = AnnouncePolicy::default(); + + Self { + 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(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))), + tracker_usage_statistics: true, + persistent_torrent_completed_stat: false, + inactive_peer_cleanup_interval: 600, + remove_peerless_torrents: true, + } + } +} diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 643235c03..d19fedc87 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -78,7 +78,7 @@ //! //! Alternatively, you could setup a reverse proxy like Nginx or Apache to //! handle the SSL/TLS part and forward the requests to the tracker. If you do -//! that, you should set [`on_reverse_proxy`](crate::Configuration::on_reverse_proxy) +//! that, you should set [`on_reverse_proxy`](crate::v1::core::Core::on_reverse_proxy) //! to `true` in the configuration file. It's out of scope for this //! documentation to explain in detail how to setup a reverse proxy, but the //! configuration file should be something like this: @@ -230,86 +230,32 @@ //! [health_check_api] //! bind_address = "127.0.0.1:1313" //!``` +pub mod core; pub mod health_check_api; pub mod http_tracker; pub mod tracker_api; pub mod udp_tracker; use std::fs; -use std::net::{IpAddr, Ipv4Addr}; +use std::net::IpAddr; use figment::providers::{Env, Format, Serialized, Toml}; use figment::Figment; use serde::{Deserialize, Serialize}; -use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; +use self::core::Core; 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, LogLevel}; +use crate::{Error, Info}; /// 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, - /// Tracker mode. See [`TrackerMode`] for more information. - pub mode: TrackerMode, - - // Database configuration - /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. - pub db_driver: DatabaseDriver, - /// Database connection string. The format depends on the database driver. - /// For `Sqlite3`, the format is `path/to/database.db`, for example: - /// `./storage/tracker/lib/database/sqlite3.db`. - /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for - /// example: `root:password@localhost:3306/torrust`. - pub db_path: String, - - /// See [`AnnouncePolicy::interval`] - pub announce_interval: u32, - - /// See [`AnnouncePolicy::interval_min`] - pub min_announce_interval: u32, - /// Weather the tracker is behind a reverse proxy or not. - /// If the tracker is behind a reverse proxy, the `X-Forwarded-For` header - /// sent from the proxy will be used to get the client's IP address. - pub on_reverse_proxy: bool, - /// The external IP address of the tracker. If the client is using a - /// loopback IP address, this IP address will be used instead. If the peer - /// 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, - /// 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. - /// Refer to the [`Tracker`](https://docs.rs/torrust-tracker) for more - /// information about the collected metrics. - pub tracker_usage_statistics: bool, - /// If enabled the tracker will persist the number of completed downloads. - /// That's how many times a torrent has been downloaded completely. - pub persistent_torrent_completed_stat: bool, - - // Cleanup job configuration - /// Maximum time in seconds that a peer can be inactive before being - /// considered an inactive peer. If a peer is inactive for more than this - /// time, it will be removed from the torrent peer list. - pub max_peer_timeout: u32, - /// Interval in seconds that the cleanup job will run to remove inactive - /// peers from the torrent peer list. - pub inactive_peer_cleanup_interval: u64, - /// If enabled, the tracker will remove torrents that have no peers. - /// The clean up torrent job runs every `inactive_peer_cleanup_interval` - /// seconds and it removes inactive peers. Eventually, the peer list of a - /// torrent could be empty and the torrent will be removed if this option is - /// enabled. - pub remove_peerless_torrents: bool, - - // Server jobs configuration + /// Core configuration. + #[serde(flatten)] + pub core: Core, /// The list of UDP trackers the tracker is running. Each UDP tracker /// represents a UDP server that the tracker is running and it has its own /// configuration. @@ -326,30 +272,13 @@ pub struct Configuration { impl Default for Configuration { fn default() -> Self { - let announce_policy = AnnouncePolicy::default(); - - let mut configuration = Configuration { - 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(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))), - tracker_usage_statistics: true, - persistent_torrent_completed_stat: false, - inactive_peer_cleanup_interval: 600, - remove_peerless_torrents: true, - udp_trackers: Vec::new(), - http_trackers: Vec::new(), + Self { + core: Core::default(), + udp_trackers: vec![UdpTracker::default()], + http_trackers: vec![HttpTracker::default()], http_api: HttpApi::default(), health_check_api: HealthCheckApi::default(), - }; - configuration.udp_trackers.push(UdpTracker::default()); - configuration.http_trackers.push(HttpTracker::default()); - configuration + } } } @@ -362,7 +291,7 @@ impl Configuration { /// and `None` otherwise. #[must_use] pub fn get_ext_ip(&self) -> Option { - self.external_ip.as_ref().map(|external_ip| *external_ip) + self.core.external_ip.as_ref().map(|external_ip| *external_ip) } /// Saves the default configuration at the given path. @@ -490,7 +419,7 @@ mod tests { fn configuration_should_contain_the_external_ip() { let configuration = Configuration::default(); - assert_eq!(configuration.external_ip, Some(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)))); + assert_eq!(configuration.core.external_ip, Some(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)))); } #[test] diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 0c7cc533a..86ed57b9e 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -27,10 +27,9 @@ pub fn ephemeral() -> Configuration { // todo: disable services that are not needed. // For example: a test for the UDP tracker should disable the API and HTTP tracker. - let mut config = Configuration { - log_level: Some(LogLevel::Off), // Change to `debug` for tests debugging - ..Default::default() - }; + let mut config = Configuration::default(); + + config.core.log_level = Some(LogLevel::Off); // Change to `debug` for tests debugging // Ephemeral socket address for API let api_port = 0u16; @@ -55,7 +54,7 @@ pub fn ephemeral() -> Configuration { let temp_directory = env::temp_dir(); let random_db_id = random::string(16); let temp_file = temp_directory.join(format!("data_{random_db_id}.db")); - temp_file.to_str().unwrap().clone_into(&mut config.db_path); + temp_file.to_str().unwrap().clone_into(&mut config.core.db_path); config } @@ -65,7 +64,7 @@ pub fn ephemeral() -> Configuration { pub fn ephemeral_with_reverse_proxy() -> Configuration { let mut cfg = ephemeral(); - cfg.on_reverse_proxy = true; + cfg.core.on_reverse_proxy = true; cfg } @@ -75,7 +74,7 @@ pub fn ephemeral_with_reverse_proxy() -> Configuration { pub fn ephemeral_without_reverse_proxy() -> Configuration { let mut cfg = ephemeral(); - cfg.on_reverse_proxy = false; + cfg.core.on_reverse_proxy = false; cfg } @@ -85,7 +84,7 @@ pub fn ephemeral_without_reverse_proxy() -> Configuration { pub fn ephemeral_mode_public() -> Configuration { let mut cfg = ephemeral(); - cfg.mode = TrackerMode::Public; + cfg.core.mode = TrackerMode::Public; cfg } @@ -95,7 +94,7 @@ pub fn ephemeral_mode_public() -> Configuration { pub fn ephemeral_mode_private() -> Configuration { let mut cfg = ephemeral(); - cfg.mode = TrackerMode::Private; + cfg.core.mode = TrackerMode::Private; cfg } @@ -105,7 +104,7 @@ pub fn ephemeral_mode_private() -> Configuration { pub fn ephemeral_mode_whitelisted() -> Configuration { let mut cfg = ephemeral(); - cfg.mode = TrackerMode::Listed; + cfg.core.mode = TrackerMode::Listed; cfg } @@ -115,7 +114,7 @@ pub fn ephemeral_mode_whitelisted() -> Configuration { pub fn ephemeral_mode_private_whitelisted() -> Configuration { let mut cfg = ephemeral(); - cfg.mode = TrackerMode::PrivateListed; + cfg.core.mode = TrackerMode::PrivateListed; cfg } @@ -125,7 +124,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); + cfg.core.external_ip = Some(ip); cfg } diff --git a/src/app.rs b/src/app.rs index 8bdc281a6..fcb01a696 100644 --- a/src/app.rs +++ b/src/app.rs @@ -67,7 +67,7 @@ pub async fn start(config: &Configuration, tracker: Arc) -> Vec) -> Vec 0 { - jobs.push(torrent_cleanup::start_job(config, &tracker)); + if config.core.inactive_peer_cleanup_interval > 0 { + jobs.push(torrent_cleanup::start_job(&config.core, &tracker)); } // Start Health Check API diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index 300813430..bd3b2e332 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -15,7 +15,7 @@ use std::sync::Arc; use chrono::Utc; use log::info; use tokio::task::JoinHandle; -use torrust_tracker_configuration::Configuration; +use torrust_tracker_configuration::v1::core::Core; use crate::core; @@ -25,7 +25,7 @@ use crate::core; /// /// Refer to [`torrust-tracker-configuration documentation`](https://docs.rs/torrust-tracker-configuration) for more info about that option. #[must_use] -pub fn start_job(config: &Configuration, tracker: &Arc) -> JoinHandle<()> { +pub fn start_job(config: &Core, tracker: &Arc) -> JoinHandle<()> { let weak_tracker = std::sync::Arc::downgrade(tracker); let interval = config.inactive_peer_cleanup_interval; diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index b71079b57..5c7e93811 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -19,7 +19,7 @@ static INIT: Once = Once::new(); /// It redirects the log info to the standard output with the log level defined in the configuration pub fn setup(cfg: &Configuration) { - let level = config_level_or_default(&cfg.log_level); + let level = config_level_or_default(&cfg.core.log_level); if level == log::LevelFilter::Off { return; diff --git a/src/core/mod.rs b/src/core/mod.rs index 83813a863..dbaf27e22 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -544,13 +544,13 @@ impl Tracker { stats_event_sender: Option>, stats_repository: statistics::Repo, ) -> Result { - let database = Arc::new(databases::driver::build(&config.db_driver, &config.db_path)?); + let database = Arc::new(databases::driver::build(&config.core.db_driver, &config.core.db_path)?); - let mode = config.mode; + let mode = config.core.mode; Ok(Tracker { //config, - announce_policy: AnnouncePolicy::new(config.announce_interval, config.min_announce_interval), + announce_policy: AnnouncePolicy::new(config.core.announce_interval, config.core.min_announce_interval), mode, keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), @@ -560,11 +560,11 @@ impl Tracker { database, external_ip: config.get_ext_ip(), policy: TrackerPolicy::new( - config.remove_peerless_torrents, - config.max_peer_timeout, - config.persistent_torrent_completed_stat, + config.core.remove_peerless_torrents, + config.core.max_peer_timeout, + config.core.persistent_torrent_completed_stat, ), - on_reverse_proxy: config.on_reverse_proxy, + on_reverse_proxy: config.core.on_reverse_proxy, }) } @@ -1033,7 +1033,7 @@ mod tests { pub fn tracker_persisting_torrents_in_database() -> Tracker { let mut configuration = configuration::ephemeral(); - configuration.persistent_torrent_completed_stat = true; + configuration.core.persistent_torrent_completed_stat = true; tracker_factory(&configuration) } diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index 76c6a36f6..dec143568 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -21,7 +21,7 @@ use crate::core::Tracker; #[must_use] pub fn tracker_factory(config: &Configuration) -> Tracker { // Initialize statistics - let (stats_event_sender, stats_repository) = statistics::setup::factory(config.tracker_usage_statistics); + let (stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); // Initialize Torrust tracker match Tracker::new(&Arc::new(config), stats_event_sender, stats_repository) { diff --git a/src/servers/http/v1/extractors/client_ip_sources.rs b/src/servers/http/v1/extractors/client_ip_sources.rs index 18eff26b3..1c6cdc636 100644 --- a/src/servers/http/v1/extractors/client_ip_sources.rs +++ b/src/servers/http/v1/extractors/client_ip_sources.rs @@ -16,7 +16,7 @@ //! the tracker will use the `X-Forwarded-For` header to get the client IP //! address. //! -//! See [`torrust_tracker_configuration::Configuration::on_reverse_proxy`]. +//! See [`torrust_tracker_configuration::Configuration::core.on_reverse_proxy`]. //! //! The tracker can also be configured to run without a reverse proxy. In this //! case, the tracker will use the IP address from the connection info. diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 5a0ae40e4..9529f954c 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -145,7 +145,7 @@ mod tests { fn tracker_with_an_ipv6_external_ip(stats_event_sender: Box) -> Tracker { let mut configuration = configuration::ephemeral(); - configuration.external_ip = Some(IpAddr::V6(Ipv6Addr::new( + configuration.core.external_ip = Some(IpAddr::V6(Ipv6Addr::new( 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, ))); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index d8ca4680c..d6d7a1065 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -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().parse().expect("valid IP address")); + self.configuration.core.external_ip = Some(external_ip.to_owned().parse().expect("valid IP address")); self } From ae77ebc50f2286e4c23b3f539759ebe4d5a908d1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 10 May 2024 17:05:48 +0100 Subject: [PATCH 0336/1297] refactor: tracker core service only needs the core config --- src/core/mod.rs | 21 +++++------ src/core/services/mod.rs | 2 +- src/servers/http/v1/services/announce.rs | 22 +++++++++--- src/servers/http/v1/services/scrape.rs | 40 ++++++++++++++++----- src/servers/udp/handlers.rs | 44 ++++++++++++++++++++---- 5 files changed, 98 insertions(+), 31 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index dbaf27e22..18a6028f7 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -445,7 +445,8 @@ use derive_more::Constructor; use log::debug; use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; -use torrust_tracker_configuration::{AnnouncePolicy, Configuration, TrackerPolicy, TORRENT_PEERS_LIMIT}; +use torrust_tracker_configuration::v1::core::Core; +use torrust_tracker_configuration::{AnnouncePolicy, TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; @@ -540,17 +541,17 @@ impl Tracker { /// /// Will return a `databases::error::Error` if unable to connect to database. The `Tracker` is responsible for the persistence. pub fn new( - config: &Configuration, + config: &Core, stats_event_sender: Option>, stats_repository: statistics::Repo, ) -> Result { - let database = Arc::new(databases::driver::build(&config.core.db_driver, &config.core.db_path)?); + let database = Arc::new(databases::driver::build(&config.db_driver, &config.db_path)?); - let mode = config.core.mode; + let mode = config.mode; Ok(Tracker { //config, - announce_policy: AnnouncePolicy::new(config.core.announce_interval, config.core.min_announce_interval), + announce_policy: AnnouncePolicy::new(config.announce_interval, config.min_announce_interval), mode, keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), @@ -558,13 +559,13 @@ impl Tracker { stats_event_sender, stats_repository, database, - external_ip: config.get_ext_ip(), + external_ip: config.external_ip, policy: TrackerPolicy::new( - config.core.remove_peerless_torrents, - config.core.max_peer_timeout, - config.core.persistent_torrent_completed_stat, + config.remove_peerless_torrents, + config.max_peer_timeout, + config.persistent_torrent_completed_stat, ), - on_reverse_proxy: config.core.on_reverse_proxy, + on_reverse_proxy: config.on_reverse_proxy, }) } diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index dec143568..166f40df4 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -24,7 +24,7 @@ pub fn tracker_factory(config: &Configuration) -> Tracker { let (stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); // Initialize Torrust tracker - match Tracker::new(&Arc::new(config), stats_event_sender, stats_repository) { + match Tracker::new(&Arc::new(config).core, stats_event_sender, stats_repository) { Ok(tracker) => tracker, Err(error) => { panic!("{}", error) diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 9529f954c..e3bef3973 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -135,8 +135,14 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = - Arc::new(Tracker::new(&configuration::ephemeral(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); + let tracker = Arc::new( + Tracker::new( + &configuration::ephemeral().core, + Some(stats_event_sender), + statistics::Repo::new(), + ) + .unwrap(), + ); let mut peer = sample_peer_using_ipv4(); @@ -149,7 +155,7 @@ mod tests { 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, ))); - Tracker::new(&configuration, Some(stats_event_sender), statistics::Repo::new()).unwrap() + Tracker::new(&configuration.core, Some(stats_event_sender), statistics::Repo::new()).unwrap() } fn peer_with_the_ipv4_loopback_ip() -> peer::Peer { @@ -194,8 +200,14 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = - Arc::new(Tracker::new(&configuration::ephemeral(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); + let tracker = Arc::new( + Tracker::new( + &configuration::ephemeral().core, + Some(stats_event_sender), + statistics::Repo::new(), + ) + .unwrap(), + ); let mut peer = sample_peer_using_ipv6(); diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 18b57f479..a6a40186f 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -146,8 +146,14 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = - Arc::new(Tracker::new(&configuration::ephemeral(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); + let tracker = Arc::new( + Tracker::new( + &configuration::ephemeral().core, + Some(stats_event_sender), + statistics::Repo::new(), + ) + .unwrap(), + ); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); @@ -164,8 +170,14 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = - Arc::new(Tracker::new(&configuration::ephemeral(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); + let tracker = Arc::new( + Tracker::new( + &configuration::ephemeral().core, + Some(stats_event_sender), + statistics::Repo::new(), + ) + .unwrap(), + ); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); @@ -217,8 +229,14 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = - Arc::new(Tracker::new(&configuration::ephemeral(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); + let tracker = Arc::new( + Tracker::new( + &configuration::ephemeral().core, + Some(stats_event_sender), + statistics::Repo::new(), + ) + .unwrap(), + ); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); @@ -235,8 +253,14 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = - Arc::new(Tracker::new(&configuration::ephemeral(), Some(stats_event_sender), statistics::Repo::new()).unwrap()); + let tracker = Arc::new( + Tracker::new( + &configuration::ephemeral().core, + Some(stats_event_sender), + statistics::Repo::new(), + ) + .unwrap(), + ); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index d6d7a1065..fee00a0bd 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -506,7 +506,12 @@ mod tests { let client_socket_address = sample_ipv4_socket_address(); let torrent_tracker = Arc::new( - core::Tracker::new(&tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new( + &tracker_configuration().core, + Some(stats_event_sender), + statistics::Repo::new(), + ) + .unwrap(), ); handle_connect(client_socket_address, &sample_connect_request(), &torrent_tracker) .await @@ -524,7 +529,12 @@ mod tests { let stats_event_sender = Box::new(stats_event_sender_mock); let torrent_tracker = Arc::new( - core::Tracker::new(&tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new( + &tracker_configuration().core, + Some(stats_event_sender), + statistics::Repo::new(), + ) + .unwrap(), ); handle_connect(sample_ipv6_remote_addr(), &sample_connect_request(), &torrent_tracker) .await @@ -768,7 +778,12 @@ mod tests { let stats_event_sender = Box::new(stats_event_sender_mock); let tracker = Arc::new( - core::Tracker::new(&tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new( + &tracker_configuration().core, + Some(stats_event_sender), + statistics::Repo::new(), + ) + .unwrap(), ); handle_announce( @@ -997,7 +1012,12 @@ mod tests { let stats_event_sender = Box::new(stats_event_sender_mock); let tracker = Arc::new( - core::Tracker::new(&tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new( + &tracker_configuration().core, + Some(stats_event_sender), + statistics::Repo::new(), + ) + .unwrap(), ); let remote_addr = sample_ipv6_remote_addr(); @@ -1027,7 +1047,7 @@ mod tests { let configuration = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); let (stats_event_sender, stats_repository) = Keeper::new_active_instance(); let tracker = - Arc::new(core::Tracker::new(&configuration, Some(stats_event_sender), stats_repository).unwrap()); + Arc::new(core::Tracker::new(&configuration.core, Some(stats_event_sender), stats_repository).unwrap()); let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); @@ -1305,7 +1325,12 @@ mod tests { let remote_addr = sample_ipv4_remote_addr(); let tracker = Arc::new( - core::Tracker::new(&tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new( + &tracker_configuration().core, + Some(stats_event_sender), + statistics::Repo::new(), + ) + .unwrap(), ); handle_scrape(remote_addr, &sample_scrape_request(&remote_addr), &tracker) @@ -1337,7 +1362,12 @@ mod tests { let remote_addr = sample_ipv6_remote_addr(); let tracker = Arc::new( - core::Tracker::new(&tracker_configuration(), Some(stats_event_sender), statistics::Repo::new()).unwrap(), + core::Tracker::new( + &tracker_configuration().core, + Some(stats_event_sender), + statistics::Repo::new(), + ) + .unwrap(), ); handle_scrape(remote_addr, &sample_scrape_request(&remote_addr), &tracker) From 445bd5361607d8dcf78fcab48450a8d10c6753b3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 13 May 2024 14:10:09 +0100 Subject: [PATCH 0337/1297] feat: define only non-defaults in toml config templates After implementing the configuration with Figment, it's now possible to omit values if they have a default value. Therefore we don't need to add all options in templates. We only need to add values that are overwriting deffault values. --- packages/configuration/src/lib.rs | 28 ++++++- packages/configuration/src/v1/core.rs | 83 ++++++++++++++++--- .../configuration/src/v1/health_check_api.rs | 9 +- packages/configuration/src/v1/http_tracker.rs | 24 +++++- packages/configuration/src/v1/tracker_api.rs | 35 ++++++-- packages/configuration/src/v1/udp_tracker.rs | 16 +++- .../config/tracker.container.mysql.toml | 31 ------- .../config/tracker.container.sqlite3.toml | 32 ------- .../config/tracker.development.sqlite3.toml | 36 -------- .../config/tracker.e2e.container.sqlite3.toml | 28 ------- .../config/tracker.udp.benchmarking.toml | 32 ------- 11 files changed, 169 insertions(+), 185 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index fdc021480..c393623df 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -120,12 +120,22 @@ pub struct AnnouncePolicy { impl Default for AnnouncePolicy { fn default() -> Self { Self { - interval: 120, - interval_min: 120, + interval: Self::default_interval(), + interval_min: Self::default_interval_min(), } } } +impl AnnouncePolicy { + fn default_interval() -> u32 { + 120 + } + + fn default_interval_min() -> u32 { + 120 + } +} + /// Errors that can occur when loading the configuration. #[derive(Error, Debug)] pub enum Error { @@ -166,12 +176,26 @@ impl From for Error { pub struct TslConfig { /// Path to the SSL certificate file. #[serde_as(as = "NoneAsEmptyString")] + #[serde(default = "TslConfig::default_ssl_cert_path")] pub ssl_cert_path: Option, /// Path to the SSL key file. #[serde_as(as = "NoneAsEmptyString")] + #[serde(default = "TslConfig::default_ssl_key_path")] pub ssl_key_path: Option, } +impl TslConfig { + #[allow(clippy::unnecessary_wraps)] + fn default_ssl_cert_path() -> Option { + Some(Utf8PathBuf::new()) + } + + #[allow(clippy::unnecessary_wraps)] + fn default_ssl_key_path() -> Option { + Some(Utf8PathBuf::new()) + } +} + #[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Clone)] #[serde(rename_all = "lowercase")] pub enum LogLevel { diff --git a/packages/configuration/src/v1/core.rs b/packages/configuration/src/v1/core.rs index ed9074194..5d00c67ab 100644 --- a/packages/configuration/src/v1/core.rs +++ b/packages/configuration/src/v1/core.rs @@ -10,58 +10,71 @@ use crate::{AnnouncePolicy, LogLevel}; pub struct Core { /// Logging level. Possible values are: `Off`, `Error`, `Warn`, `Info`, /// `Debug` and `Trace`. Default is `Info`. + #[serde(default = "Core::default_log_level")] pub log_level: Option, /// Tracker mode. See [`TrackerMode`] for more information. + #[serde(default = "Core::default_mode")] pub mode: TrackerMode, // Database configuration /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. + #[serde(default = "Core::default_db_driver")] pub db_driver: DatabaseDriver, /// Database connection string. The format depends on the database driver. /// For `Sqlite3`, the format is `path/to/database.db`, for example: /// `./storage/tracker/lib/database/sqlite3.db`. /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for /// example: `root:password@localhost:3306/torrust`. + #[serde(default = "Core::default_db_path")] pub db_path: String, /// See [`AnnouncePolicy::interval`] + #[serde(default = "AnnouncePolicy::default_interval")] pub announce_interval: u32, /// See [`AnnouncePolicy::interval_min`] + #[serde(default = "AnnouncePolicy::default_interval_min")] pub min_announce_interval: u32, /// Weather the tracker is behind a reverse proxy or not. /// If the tracker is behind a reverse proxy, the `X-Forwarded-For` header /// sent from the proxy will be used to get the client's IP address. + #[serde(default = "Core::default_on_reverse_proxy")] pub on_reverse_proxy: bool, /// The external IP address of the tracker. If the client is using a /// loopback IP address, this IP address will be used instead. If the peer /// 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. + #[serde(default = "Core::default_external_ip")] pub external_ip: Option, /// 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. /// Refer to the [`Tracker`](https://docs.rs/torrust-tracker) for more /// information about the collected metrics. + #[serde(default = "Core::default_tracker_usage_statistics")] pub tracker_usage_statistics: bool, /// If enabled the tracker will persist the number of completed downloads. /// That's how many times a torrent has been downloaded completely. + #[serde(default = "Core::default_persistent_torrent_completed_stat")] pub persistent_torrent_completed_stat: bool, // Cleanup job configuration /// Maximum time in seconds that a peer can be inactive before being /// considered an inactive peer. If a peer is inactive for more than this /// time, it will be removed from the torrent peer list. + #[serde(default = "Core::default_max_peer_timeout")] pub max_peer_timeout: u32, /// Interval in seconds that the cleanup job will run to remove inactive /// peers from the torrent peer list. + #[serde(default = "Core::default_inactive_peer_cleanup_interval")] pub inactive_peer_cleanup_interval: u64, /// If enabled, the tracker will remove torrents that have no peers. /// The clean up torrent job runs every `inactive_peer_cleanup_interval` /// seconds and it removes inactive peers. Eventually, the peer list of a /// torrent could be empty and the torrent will be removed if this option is /// enabled. + #[serde(default = "Core::default_remove_peerless_torrents")] pub remove_peerless_torrents: bool, } @@ -70,19 +83,67 @@ impl Default for Core { let announce_policy = AnnouncePolicy::default(); Self { - log_level: Some(LogLevel::Info), - mode: TrackerMode::Public, - db_driver: DatabaseDriver::Sqlite3, - db_path: String::from("./storage/tracker/lib/database/sqlite3.db"), + log_level: Self::default_log_level(), + mode: Self::default_mode(), + db_driver: Self::default_db_driver(), + db_path: Self::default_db_path(), announce_interval: announce_policy.interval, min_announce_interval: announce_policy.interval_min, - max_peer_timeout: 900, - on_reverse_proxy: false, - 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, - remove_peerless_torrents: true, + max_peer_timeout: Self::default_max_peer_timeout(), + on_reverse_proxy: Self::default_on_reverse_proxy(), + external_ip: Self::default_external_ip(), + tracker_usage_statistics: Self::default_tracker_usage_statistics(), + persistent_torrent_completed_stat: Self::default_persistent_torrent_completed_stat(), + inactive_peer_cleanup_interval: Self::default_inactive_peer_cleanup_interval(), + remove_peerless_torrents: Self::default_remove_peerless_torrents(), } } } + +impl Core { + #[allow(clippy::unnecessary_wraps)] + fn default_log_level() -> Option { + Some(LogLevel::Info) + } + + fn default_mode() -> TrackerMode { + TrackerMode::Public + } + + fn default_db_driver() -> DatabaseDriver { + DatabaseDriver::Sqlite3 + } + + fn default_db_path() -> String { + String::from("./storage/tracker/lib/database/sqlite3.db") + } + + fn default_on_reverse_proxy() -> bool { + false + } + + #[allow(clippy::unnecessary_wraps)] + fn default_external_ip() -> Option { + Some(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))) + } + + fn default_tracker_usage_statistics() -> bool { + true + } + + fn default_persistent_torrent_completed_stat() -> bool { + false + } + + fn default_max_peer_timeout() -> u32 { + 900 + } + + fn default_inactive_peer_cleanup_interval() -> u64 { + 600 + } + + fn default_remove_peerless_torrents() -> bool { + true + } +} diff --git a/packages/configuration/src/v1/health_check_api.rs b/packages/configuration/src/v1/health_check_api.rs index b8bfd2c1b..61178fa80 100644 --- a/packages/configuration/src/v1/health_check_api.rs +++ b/packages/configuration/src/v1/health_check_api.rs @@ -11,13 +11,20 @@ pub struct HealthCheckApi { /// The format is `ip:port`, for example `127.0.0.1:1313`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating /// system to choose a random port, use port `0`. + #[serde(default = "HealthCheckApi::default_bind_address")] pub bind_address: SocketAddr, } impl Default for HealthCheckApi { fn default() -> Self { Self { - bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1313), + bind_address: Self::default_bind_address(), } } } + +impl HealthCheckApi { + fn default_bind_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1313) + } +} diff --git a/packages/configuration/src/v1/http_tracker.rs b/packages/configuration/src/v1/http_tracker.rs index 57b2d83a1..b1fe1437b 100644 --- a/packages/configuration/src/v1/http_tracker.rs +++ b/packages/configuration/src/v1/http_tracker.rs @@ -10,26 +10,44 @@ use crate::TslConfig; #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct HttpTracker { /// Weather the HTTP tracker is enabled or not. + #[serde(default = "HttpTracker::default_enabled")] pub enabled: bool, /// The address the tracker will bind to. /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating /// system to choose a random port, use port `0`. + #[serde(default = "HttpTracker::default_bind_address")] pub bind_address: SocketAddr, /// Weather the HTTP tracker will use SSL or not. + #[serde(default = "HttpTracker::default_ssl_enabled")] pub ssl_enabled: bool, /// TSL config. Only used if `ssl_enabled` is true. #[serde(flatten)] + #[serde(default = "TslConfig::default")] pub tsl_config: TslConfig, } impl Default for HttpTracker { fn default() -> Self { Self { - enabled: false, - bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 7070), - ssl_enabled: false, + enabled: Self::default_enabled(), + bind_address: Self::default_bind_address(), + ssl_enabled: Self::default_ssl_enabled(), tsl_config: TslConfig::default(), } } } + +impl HttpTracker { + fn default_enabled() -> bool { + false + } + + fn default_bind_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 7070) + } + + fn default_ssl_enabled() -> bool { + false + } +} diff --git a/packages/configuration/src/v1/tracker_api.rs b/packages/configuration/src/v1/tracker_api.rs index 5089c496a..c2e3e5ee9 100644 --- a/packages/configuration/src/v1/tracker_api.rs +++ b/packages/configuration/src/v1/tracker_api.rs @@ -13,40 +13,61 @@ pub type AccessTokens = HashMap; #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct HttpApi { /// Weather the HTTP API is enabled or not. + #[serde(default = "HttpApi::default_enabled")] pub enabled: bool, /// The address the tracker will bind to. /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating /// system to choose a random port, use port `0`. + #[serde(default = "HttpApi::default_bind_address")] pub bind_address: SocketAddr, /// Weather the HTTP API will use SSL or not. + #[serde(default = "HttpApi::default_ssl_enabled")] pub ssl_enabled: bool, /// TSL config. Only used if `ssl_enabled` is true. #[serde(flatten)] + #[serde(default = "TslConfig::default")] pub tsl_config: TslConfig, /// Access tokens for the HTTP API. The key is a label identifying the /// token and the value is the token itself. The token is used to /// authenticate the user. All tokens are valid for all endpoints and have /// all permissions. + #[serde(default = "HttpApi::default_access_tokens")] pub access_tokens: AccessTokens, } impl Default for HttpApi { fn default() -> Self { Self { - enabled: true, - bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1212), - ssl_enabled: false, + enabled: Self::default_enabled(), + bind_address: Self::default_bind_address(), + ssl_enabled: Self::default_ssl_enabled(), tsl_config: TslConfig::default(), - access_tokens: [(String::from("admin"), String::from("MyAccessToken"))] - .iter() - .cloned() - .collect(), + access_tokens: Self::default_access_tokens(), } } } impl HttpApi { + fn default_enabled() -> bool { + true + } + + fn default_bind_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1212) + } + + fn default_ssl_enabled() -> bool { + false + } + + fn default_access_tokens() -> AccessTokens { + [(String::from("admin"), String::from("MyAccessToken"))] + .iter() + .cloned() + .collect() + } + pub fn override_admin_token(&mut self, api_admin_token: &str) { self.access_tokens.insert("admin".to_string(), api_admin_token.to_string()); } diff --git a/packages/configuration/src/v1/udp_tracker.rs b/packages/configuration/src/v1/udp_tracker.rs index 1f772164e..f8387202e 100644 --- a/packages/configuration/src/v1/udp_tracker.rs +++ b/packages/configuration/src/v1/udp_tracker.rs @@ -5,18 +5,30 @@ use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct UdpTracker { /// Weather the UDP tracker is enabled or not. + #[serde(default = "UdpTracker::default_enabled")] pub enabled: bool, /// The address the tracker will bind to. /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating /// system to choose a random port, use port `0`. + #[serde(default = "UdpTracker::default_bind_address")] pub bind_address: SocketAddr, } impl Default for UdpTracker { fn default() -> Self { Self { - enabled: false, - bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 6969), + enabled: Self::default_enabled(), + bind_address: Self::default_bind_address(), } } } + +impl UdpTracker { + fn default_enabled() -> bool { + false + } + + fn default_bind_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 6969) + } +} diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml index f2db06228..7678327ab 100644 --- a/share/default/config/tracker.container.mysql.toml +++ b/share/default/config/tracker.container.mysql.toml @@ -1,41 +1,10 @@ -announce_interval = 120 db_driver = "MySQL" db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" -external_ip = "0.0.0.0" -inactive_peer_cleanup_interval = 600 -log_level = "info" -max_peer_timeout = 900 -min_announce_interval = 120 -mode = "public" -on_reverse_proxy = false -persistent_torrent_completed_stat = false -remove_peerless_torrents = true -tracker_usage_statistics = true - -[[udp_trackers]] -bind_address = "0.0.0.0:6969" -enabled = false [[http_trackers]] -bind_address = "0.0.0.0:7070" -enabled = false ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" -ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" [http_api] -bind_address = "0.0.0.0:1212" -enabled = true ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" -ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" - -[http_api.access_tokens] -# Please override the admin token setting the environmental variable: -# `TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN` -# The old variable name is deprecated: -# `TORRUST_TRACKER_API_ADMIN_TOKEN` -admin = "MyAccessToken" - -[health_check_api] -bind_address = "127.0.0.1:1313" diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml index 4a3ba03b6..da8259286 100644 --- a/share/default/config/tracker.container.sqlite3.toml +++ b/share/default/config/tracker.container.sqlite3.toml @@ -1,41 +1,9 @@ -announce_interval = 120 -db_driver = "Sqlite3" db_path = "/var/lib/torrust/tracker/database/sqlite3.db" -external_ip = "0.0.0.0" -inactive_peer_cleanup_interval = 600 -log_level = "info" -max_peer_timeout = 900 -min_announce_interval = 120 -mode = "public" -on_reverse_proxy = false -persistent_torrent_completed_stat = false -remove_peerless_torrents = true -tracker_usage_statistics = true - -[[udp_trackers]] -bind_address = "0.0.0.0:6969" -enabled = false [[http_trackers]] -bind_address = "0.0.0.0:7070" -enabled = false ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" -ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" [http_api] -bind_address = "0.0.0.0:1212" -enabled = true ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" -ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" - -[http_api.access_tokens] -# Please override the admin token setting the environmental variable: -# `TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN` -# The old variable name is deprecated: -# `TORRUST_TRACKER_API_ADMIN_TOKEN` -admin = "MyAccessToken" - -[health_check_api] -bind_address = "127.0.0.1:1313" diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index 62e5b478e..bf6478492 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -1,41 +1,5 @@ -announce_interval = 120 -db_driver = "Sqlite3" -db_path = "./storage/tracker/lib/database/sqlite3.db" -external_ip = "0.0.0.0" -inactive_peer_cleanup_interval = 600 -log_level = "info" -max_peer_timeout = 900 -min_announce_interval = 120 -mode = "public" -on_reverse_proxy = false -persistent_torrent_completed_stat = false -remove_peerless_torrents = true -tracker_usage_statistics = true - [[udp_trackers]] -bind_address = "0.0.0.0:6969" enabled = true [[http_trackers]] -bind_address = "0.0.0.0:7070" -enabled = true -ssl_cert_path = "" -ssl_enabled = false -ssl_key_path = "" - -[http_api] -bind_address = "127.0.0.1:1212" enabled = true -ssl_cert_path = "" -ssl_enabled = false -ssl_key_path = "" - -[http_api.access_tokens] -# Please override the admin token setting the environmental variable: -# `TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN` -# The old variable name is deprecated: -# `TORRUST_TRACKER_API_ADMIN_TOKEN` -admin = "MyAccessToken" - -[health_check_api] -bind_address = "127.0.0.1:1313" diff --git a/share/default/config/tracker.e2e.container.sqlite3.toml b/share/default/config/tracker.e2e.container.sqlite3.toml index 3738704b5..e7d8fa279 100644 --- a/share/default/config/tracker.e2e.container.sqlite3.toml +++ b/share/default/config/tracker.e2e.container.sqlite3.toml @@ -1,41 +1,13 @@ -announce_interval = 120 -db_driver = "Sqlite3" db_path = "/var/lib/torrust/tracker/database/sqlite3.db" -external_ip = "0.0.0.0" -inactive_peer_cleanup_interval = 600 -log_level = "info" -max_peer_timeout = 900 -min_announce_interval = 120 -mode = "public" -on_reverse_proxy = false -persistent_torrent_completed_stat = false -remove_peerless_torrents = true -tracker_usage_statistics = true [[udp_trackers]] -bind_address = "0.0.0.0:6969" enabled = true [[http_trackers]] -bind_address = "0.0.0.0:7070" enabled = true ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" -ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" [http_api] -bind_address = "0.0.0.0:1212" -enabled = true ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" -ssl_enabled = false ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" - -[http_api.access_tokens] -# Please override the admin token setting the environmental variable: -# `TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN` -# The old variable name is deprecated: -# `TORRUST_TRACKER_API_ADMIN_TOKEN` -admin = "MyAccessToken" - -[health_check_api] -bind_address = "0.0.0.0:1313" diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml index 1e951d8fc..00f62628b 100644 --- a/share/default/config/tracker.udp.benchmarking.toml +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -1,41 +1,9 @@ -announce_interval = 120 -db_driver = "Sqlite3" -db_path = "./storage/tracker/lib/database/sqlite3.db" -external_ip = "0.0.0.0" -inactive_peer_cleanup_interval = 600 log_level = "error" -max_peer_timeout = 900 -min_announce_interval = 120 -mode = "public" -on_reverse_proxy = false -persistent_torrent_completed_stat = false remove_peerless_torrents = false tracker_usage_statistics = false [[udp_trackers]] -bind_address = "0.0.0.0:6969" enabled = true -[[http_trackers]] -bind_address = "0.0.0.0:7070" -enabled = false -ssl_cert_path = "" -ssl_enabled = false -ssl_key_path = "" - [http_api] -bind_address = "127.0.0.1:1212" enabled = false -ssl_cert_path = "" -ssl_enabled = false -ssl_key_path = "" - -[http_api.access_tokens] -# Please override the admin token setting the environmental variable: -# `TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN` -# The old variable name is deprecated: -# `TORRUST_TRACKER_API_ADMIN_TOKEN` -admin = "MyAccessToken" - -[health_check_api] -bind_address = "127.0.0.1:1313" From cf1bfb11ad8a2d92d9e47b065ab2580e596c23ce Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 14 May 2024 07:35:38 +0100 Subject: [PATCH 0338/1297] chore(deps): update dependencies ```ouput Updating crates.io index Locking 13 packages to latest compatible versions Removing allocator-api2 v0.2.18 Updating async-channel v2.2.1 -> v2.3.0 Updating async-compression v0.4.9 -> v0.4.10 Updating brotli v5.0.0 -> v6.0.0 Updating bytemuck v1.15.0 -> v1.16.0 Updating errno v0.3.8 -> v0.3.9 Updating hashlink v0.9.0 -> v0.9.1 Updating piper v0.2.1 -> v0.2.2 Updating rustls-pki-types v1.6.0 -> v1.7.0 Updating serde v1.0.200 -> v1.0.201 Updating serde_derive v1.0.200 -> v1.0.201 Updating serde_json v1.0.116 -> v1.0.117 Updating syn v2.0.61 -> v2.0.63 Updating waker-fn v1.1.1 -> v1.2.0 ``` --- Cargo.lock | 121 +++++++++++++++++++++++++---------------------------- 1 file changed, 57 insertions(+), 64 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e54601bcf..446477aac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -64,12 +64,6 @@ dependencies = [ "alloc-no-stdlib", ] -[[package]] -name = "allocator-api2" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" - [[package]] name = "android-tzdata" version = "0.1.1" @@ -207,9 +201,9 @@ dependencies = [ [[package]] name = "async-channel" -version = "2.2.1" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "136d4d23bcc79e27423727b36823d86233aad06dfea531837b038394d11e9928" +checksum = "9f2776ead772134d55b62dd45e59a79e21612d85d0af729b8b7d3967d601a62a" dependencies = [ "concurrent-queue", "event-listener 5.3.0", @@ -220,9 +214,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.9" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e9eabd7a98fe442131a17c316bd9349c43695e49e730c3c8e12cfb5f4da2693" +checksum = "9c90a406b4495d129f00461241616194cb8a032c8d1c53c657f0961d5f8e0498" dependencies = [ "brotli", "flate2", @@ -253,7 +247,7 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" dependencies = [ - "async-channel 2.2.1", + "async-channel 2.3.0", "async-executor", "async-io 2.3.2", "async-lock 3.3.0", @@ -363,7 +357,7 @@ checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -486,7 +480,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -573,7 +567,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -615,7 +609,7 @@ version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "495f7104e962b7356f0aeb34247aca1fe7d2e783b346582db7f2904cb5717e88" dependencies = [ - "async-channel 2.2.1", + "async-channel 2.3.0", "async-lock 3.3.0", "async-task", "futures-io", @@ -643,15 +637,15 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", "syn_derive", ] [[package]] name = "brotli" -version = "5.0.0" +version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19483b140a7ac7174d34b5a581b406c64f84da5409d3e09cf4fff604f9270e67" +checksum = "74f7971dbd9326d58187408ab83117d8ac1bb9c17b085fdacd1cf2f598719b6b" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -704,9 +698,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.15.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6d68c57235a3a081186990eca2867354726650f42f7516ca50c28d6281fd15" +checksum = "78834c15cb5d5efe3452d58b1e8ba890dd62d21907f867f383358198e56ebca5" [[package]] name = "byteorder" @@ -858,7 +852,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -1085,7 +1079,7 @@ dependencies = [ "proc-macro2", "quote", "strsim 0.10.0", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -1096,7 +1090,7 @@ checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" dependencies = [ "darling_core", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -1143,7 +1137,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -1195,9 +1189,9 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245" +checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" dependencies = [ "libc", "windows-sys 0.52.0", @@ -1395,7 +1389,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -1407,7 +1401,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -1419,7 +1413,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -1512,7 +1506,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -1650,14 +1644,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ "ahash 0.8.11", - "allocator-api2", ] [[package]] name = "hashlink" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "692eaaf7f7607518dd3cef090f1474b61edc5301d8012f09579920df68b725ee" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" dependencies = [ "hashbrown 0.14.5", ] @@ -2208,7 +2201,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -2259,7 +2252,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", "termcolor", "thiserror", ] @@ -2458,7 +2451,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -2528,7 +2521,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -2602,7 +2595,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -2619,9 +2612,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "piper" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "668d31b1c4eba19242f2088b2bf3316b82ca31082a8335764db4e083db7485d4" +checksum = "464db0c665917b13ebb5d453ccdec4add5658ee1adc7affc7677615356a8afaf" dependencies = [ "atomic-waker", "fastrand 2.1.0", @@ -2791,7 +2784,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", "version_check", "yansi", ] @@ -3097,7 +3090,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.61", + "syn 2.0.63", "unicode-ident", ] @@ -3203,9 +3196,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.6.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51f344d206c5e1b010eec27349b815a4805f70a778895959d70b74b9b529b30a" +checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d" [[package]] name = "rustls-webpki" @@ -3315,9 +3308,9 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" -version = "1.0.200" +version = "1.0.201" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddc6f9cc94d67c0e21aaf7eda3a010fd3af78ebf6e096aa6e2e13c79749cce4f" +checksum = "780f1cebed1629e4753a1a38a3c72d30b97ec044f0aef68cb26650a3c5cf363c" dependencies = [ "serde_derive", ] @@ -3343,13 +3336,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.200" +version = "1.0.201" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "856f046b9400cee3c8c94ed572ecdb752444c24528c035cd35882aad6f492bcb" +checksum = "c5e405930b9796f1c00bee880d03fc7e0bb4b9a11afc776885ffe84320da2865" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -3367,9 +3360,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.116" +version = "1.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813" +checksum = "455182ea6142b14f93f4bc5320a2b31c1f266b66a4a5c858b013302a5d8cbfc3" dependencies = [ "indexmap 2.2.6", "itoa", @@ -3395,7 +3388,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -3446,7 +3439,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -3580,9 +3573,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.61" +version = "2.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c993ed8ccba56ae856363b1845da7266a7cb78e1d146c8a32d54b45a8b831fc9" +checksum = "bf5be731623ca1a1fb7d8be6f261a3be6d3e2337b8a1f97be944d020c8fcb704" dependencies = [ "proc-macro2", "quote", @@ -3598,7 +3591,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -3701,7 +3694,7 @@ checksum = "e2470041c06ec3ac1ab38d0356a6119054dedaea53e12fbefc0de730a1c08524" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -3786,7 +3779,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -4095,7 +4088,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] @@ -4213,9 +4206,9 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "waker-fn" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c4517f54858c779bbcbf228f4fca63d121bf85fbecb2dc578cdf4a39395690" +checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" [[package]] name = "walkdir" @@ -4263,7 +4256,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", "wasm-bindgen-shared", ] @@ -4297,7 +4290,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4558,7 +4551,7 @@ checksum = "15e934569e47891f7d9411f1a451d947a60e000ab3bd24fbb970f000387d1b3b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.63", ] [[package]] From da6a21eac969c96005f2b5b4deb0b1ea91926951 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 14 May 2024 10:22:56 +0100 Subject: [PATCH 0339/1297] refactor: [#855] show toml file location in Figment errors Before this commit we loaded configuration in Figment always using a Toml string even if the configuration cames from a toml file. WHen there is an error Figment does not show the file location and that's one of the main advantages of using Figment. All errors point to the primary source of the configuration option. This commit fixes that problem leting Figment to load the configuration from the file when the user provides a file. Sample error: ``` Loading configuration from default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... thread 'main' panicked at src/bootstrap/config.rs:45:32: called `Result::unwrap()` on an `Err` value: ConfigError { source: LocatedError { source: Error { tag: Tag(Default, 2), profile: Some(Profile(Uncased { string: "default" })), metadata: Some(Metadata { name: "TOML file", source: Some(File("/home/developer/torrust/torrust-tracker/./share/default/config/tracker.development.sqlite3.toml")), provide_location: Some(Location { file: "packages/configuration/src/v1/mod.rs", line: 330, col: 18 }), interpolater: }), path: [], kind: Message("TOML parse error at line 2, column 15\n |\n2 | enabled = truee\n | ^\nexpected newline, `#`\n"), prev: None }, location: Location { file: "packages/configuration/src/v1/mod.rs", line: 334, col: 41 } } } note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` Notice how the file path is included is the error: `/home/developer/torrust/torrust-tracker/./share/default/config/tracker.development.sqlite3.toml` --- packages/configuration/src/lib.rs | 47 ++++++++---------- packages/configuration/src/v1/mod.rs | 71 +++++++++++++++++++++++----- 2 files changed, 79 insertions(+), 39 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index c393623df..9a00e6bbc 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -7,8 +7,8 @@ pub mod v1; use std::collections::HashMap; +use std::env; use std::sync::Arc; -use std::{env, fs}; use camino::Utf8PathBuf; use derive_more::Constructor; @@ -38,7 +38,8 @@ pub struct TrackerPolicy { /// Information required for loading config #[derive(Debug, Default, Clone)] pub struct Info { - tracker_toml: String, + config_toml: Option, + config_toml_path: String, api_admin_token: Option, } @@ -51,38 +52,30 @@ impl Info { /// #[allow(clippy::needless_pass_by_value)] pub fn new( - env_var_config: String, - env_var_path_config: String, - default_path_config: String, + env_var_config_toml: String, + env_var_config_toml_path: String, + default_config_toml_path: String, env_var_api_admin_token: String, ) -> Result { - let tracker_toml = if let Ok(tracker_toml) = env::var(&env_var_config) { - println!("Loading configuration from env var {env_var_config} ..."); + let config_toml = if let Ok(config_toml) = env::var(env_var_config_toml) { + println!("Loading configuration from environment variable {config_toml} ..."); + Some(config_toml) + } else { + None + }; - tracker_toml + let config_toml_path = if let Ok(config_toml_path) = env::var(env_var_config_toml_path) { + println!("Loading configuration from file: `{config_toml_path}` ..."); + config_toml_path } else { - let config_path = if let Ok(config_path) = env::var(env_var_path_config) { - println!("Loading configuration file: `{config_path}` ..."); - - config_path - } else { - println!("Loading default configuration file: `{default_path_config}` ..."); - - default_path_config - }; - - fs::read_to_string(config_path) - .map_err(|e| Error::UnableToLoadFromConfigFile { - source: (Arc::new(e) as DynError).into(), - })? - .parse() - .map_err(|_e: std::convert::Infallible| Error::Infallible)? + println!("Loading configuration from default configuration file: `{default_config_toml_path}` ..."); + default_config_toml_path }; - let api_admin_token = env::var(env_var_api_admin_token).ok(); Ok(Self { - tracker_toml, - api_admin_token, + config_toml, + config_toml_path, + api_admin_token: env::var(env_var_api_admin_token).ok(), }) } } diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index d19fedc87..8e15d65ca 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -250,6 +250,11 @@ use self::tracker_api::HttpApi; use self::udp_tracker::UdpTracker; use crate::{Error, Info}; +/// Prefix for env vars that overwrite configuration options. +const CONFIG_OVERRIDE_PREFIX: &str = "TORRUST_TRACKER_CONFIG_OVERRIDE_"; +/// Path separator in env var names for nested values in configuration. +const CONFIG_OVERRIDE_SEPARATOR: &str = "__"; + /// Core configuration for the tracker. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)] pub struct Configuration { @@ -315,9 +320,16 @@ impl Configuration { /// /// Will return `Err` if the environment variable does not exist or has a bad configuration. pub fn load(info: &Info) -> Result { - let figment = Figment::from(Serialized::defaults(Configuration::default())) - .merge(Toml::string(&info.tracker_toml)) - .merge(Env::prefixed("TORRUST_TRACKER__").split("__")); + let figment = if let Some(config_toml) = &info.config_toml { + // Config in env var has priority over config file path + Figment::from(Serialized::defaults(Configuration::default())) + .merge(Toml::string(config_toml)) + .merge(Env::prefixed(CONFIG_OVERRIDE_PREFIX).split(CONFIG_OVERRIDE_SEPARATOR)) + } else { + Figment::from(Serialized::defaults(Configuration::default())) + .merge(Toml::file(&info.config_toml_path)) + .merge(Env::prefixed(CONFIG_OVERRIDE_PREFIX).split(CONFIG_OVERRIDE_SEPARATOR)) + }; let mut config: Configuration = figment.extract()?; @@ -449,11 +461,14 @@ mod tests { #[test] fn configuration_should_use_the_default_values_when_an_empty_configuration_is_provided_by_the_user() { - figment::Jail::expect_with(|_jail| { + figment::Jail::expect_with(|jail| { + jail.create_file("tracker.toml", "")?; + let empty_configuration = String::new(); let info = Info { - tracker_toml: empty_configuration, + config_toml: Some(empty_configuration), + config_toml_path: "tracker.toml".to_string(), api_admin_token: None, }; @@ -466,28 +481,59 @@ mod tests { } #[test] - fn configuration_should_be_loaded_from_a_toml_config_file() { + fn default_configuration_could_be_overwritten_from_a_single_env_var_with_toml_contents() { figment::Jail::expect_with(|_jail| { + let config_toml = r#" + db_path = "OVERWRITTEN DEFAULT DB PATH" + "# + .to_string(); + let info = Info { - tracker_toml: default_config_toml(), + config_toml: Some(config_toml), + config_toml_path: String::new(), api_admin_token: None, }; let configuration = Configuration::load(&info).expect("Could not load configuration from file"); - assert_eq!(configuration, Configuration::default()); + assert_eq!(configuration.core.db_path, "OVERWRITTEN DEFAULT DB PATH".to_string()); + + Ok(()) + }); + } + + #[test] + fn default_configuration_could_be_overwritten_from_a_toml_config_file() { + figment::Jail::expect_with(|jail| { + jail.create_file( + "tracker.toml", + r#" + db_path = "OVERWRITTEN DEFAULT DB PATH" + "#, + )?; + + let info = Info { + config_toml: None, + config_toml_path: "tracker.toml".to_string(), + api_admin_token: None, + }; + + let configuration = Configuration::load(&info).expect("Could not load configuration from file"); + + assert_eq!(configuration.core.db_path, "OVERWRITTEN DEFAULT DB PATH".to_string()); Ok(()) }); } #[test] - fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin_with_env_var() { + fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin_with_an_env_var() { figment::Jail::expect_with(|jail| { - jail.set_env("TORRUST_TRACKER__HTTP_API__ACCESS_TOKENS__ADMIN", "NewToken"); + jail.set_env("TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN", "NewToken"); let info = Info { - tracker_toml: default_config_toml(), + config_toml: Some(default_config_toml()), + config_toml_path: String::new(), api_admin_token: None, }; @@ -506,7 +552,8 @@ mod tests { fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin_with_the_deprecated_env_var_name() { figment::Jail::expect_with(|_jail| { let info = Info { - tracker_toml: default_config_toml(), + config_toml: Some(default_config_toml()), + config_toml_path: String::new(), api_admin_token: Some("NewToken".to_owned()), }; From 4de5e7d32efd1277138ef1b92602204cdf5f8375 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 14 May 2024 10:39:20 +0100 Subject: [PATCH 0340/1297] refactor: move config env vars to configuration package --- packages/configuration/src/lib.rs | 24 ++++++++++++++++++------ src/bootstrap/config.rs | 22 ++-------------------- 2 files changed, 20 insertions(+), 26 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 9a00e6bbc..588feb87e 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -20,6 +20,19 @@ use torrust_tracker_located_error::{DynError, LocatedError}; /// The maximum number of returned peers for a torrent. pub const TORRENT_PEERS_LIMIT: usize = 74; +// Environment variables + +/// The whole `tracker.toml` file content. It has priority over the config file. +/// Even if the file is not on the default path. +const ENV_VAR_CONFIG: &str = "TORRUST_TRACKER_CONFIG"; + +/// The `tracker.toml` file location. +pub const ENV_VAR_PATH_CONFIG: &str = "TORRUST_TRACKER_PATH_CONFIG"; + +/// Env var to overwrite API admin token. +/// Deprecated: use `TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN`. +const ENV_VAR_API_ADMIN_TOKEN: &str = "TORRUST_TRACKER_API_ADMIN_TOKEN"; + pub type Configuration = v1::Configuration; pub type UdpTracker = v1::udp_tracker::UdpTracker; pub type HttpTracker = v1::http_tracker::HttpTracker; @@ -51,12 +64,11 @@ impl Info { /// Will return `Err` if unable to obtain a configuration. /// #[allow(clippy::needless_pass_by_value)] - pub fn new( - env_var_config_toml: String, - env_var_config_toml_path: String, - default_config_toml_path: String, - env_var_api_admin_token: String, - ) -> Result { + pub fn new(default_config_toml_path: String) -> Result { + let env_var_config_toml = ENV_VAR_CONFIG.to_string(); + let env_var_config_toml_path = ENV_VAR_PATH_CONFIG.to_string(); + let env_var_api_admin_token = ENV_VAR_API_ADMIN_TOKEN.to_string(); + let config_toml = if let Ok(config_toml) = env::var(env_var_config_toml) { println!("Loading configuration from environment variable {config_toml} ..."); Some(config_toml) diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 858fd59fc..03dfd9a2f 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -4,17 +4,6 @@ use torrust_tracker_configuration::{Configuration, Info}; -// Environment variables - -/// The whole `tracker.toml` file content. It has priority over the config file. -/// Even if the file is not on the default path. -const ENV_VAR_CONFIG: &str = "TORRUST_TRACKER_CONFIG"; -const ENV_VAR_API_ADMIN_TOKEN: &str = "TORRUST_TRACKER_API_ADMIN_TOKEN"; - -/// The `tracker.toml` file location. -pub const ENV_VAR_PATH_CONFIG: &str = "TORRUST_TRACKER_PATH_CONFIG"; - -// Default values pub const DEFAULT_PATH_CONFIG: &str = "./share/default/config/tracker.development.sqlite3.toml"; /// It loads the application configuration from the environment. @@ -34,15 +23,8 @@ pub const DEFAULT_PATH_CONFIG: &str = "./share/default/config/tracker.developmen /// `./tracker.toml` file or the env var `TORRUST_TRACKER_CONFIG`. #[must_use] pub fn initialize_configuration() -> Configuration { - let info = Info::new( - ENV_VAR_CONFIG.to_string(), - ENV_VAR_PATH_CONFIG.to_string(), - DEFAULT_PATH_CONFIG.to_string(), - ENV_VAR_API_ADMIN_TOKEN.to_string(), - ) - .unwrap(); - - Configuration::load(&info).unwrap() + let info = Info::new(DEFAULT_PATH_CONFIG.to_string()).expect("info to load configuration is not valid"); + Configuration::load(&info).expect("configuration should be loaded from provided info") } #[cfg(test)] From ef15e0b42adf46d8c5b5fed9bedf01b56662f1b4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 14 May 2024 13:46:58 +0100 Subject: [PATCH 0341/1297] refactor: [#851] rename env vars ``` TORRUST_TRACKER_BACK_ -> TORRUST_TRACKER_ TORRUST_TRACKER_DATABASE_DRIVER -> TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER TORRUST_TRACKER_API_ADMIN_TOKEN -> TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN TORRUST_TRACKER_CONFIG -> TORRUST_TRACKER_CONFIG_TOML TORRUST_TRACKER_PATH_CONFIG -> TORRUST_TRACKER_CONFIG_TOML_PATH ``` DB_DRIVER values: `MySQL`, `Sqlite3`. Removed lowercase values `mysql` and `sqlite3` used in containers. Some enums use lowercase. This is a braking change for container but not for configuration. IN the future we could use lowercase also in the configuration. --- Containerfile | 8 ++++---- README.md | 8 ++++---- compose.yaml | 4 ++-- docs/benchmarking.md | 2 +- docs/containers.md | 14 +++++++------- docs/profiling.md | 4 ++-- packages/configuration/src/lib.rs | 15 +++++++-------- packages/configuration/src/v1/mod.rs | 2 +- packages/primitives/src/lib.rs | 4 +++- share/container/entry_script_sh | 20 ++++++++++---------- src/bootstrap/config.rs | 6 +++--- src/console/ci/e2e/runner.rs | 2 +- src/console/profiling.rs | 4 ++-- src/lib.rs | 6 +++--- 14 files changed, 50 insertions(+), 49 deletions(-) diff --git a/Containerfile b/Containerfile index 590b0a13b..79fae692f 100644 --- a/Containerfile +++ b/Containerfile @@ -95,16 +95,16 @@ FROM gcr.io/distroless/cc-debian12:debug as runtime RUN ["/busybox/cp", "-sp", "/busybox/sh","/busybox/cat","/busybox/ls","/busybox/env", "/bin/"] COPY --from=gcc --chmod=0555 /usr/local/bin/su-exec /bin/su-exec -ARG TORRUST_TRACKER_PATH_CONFIG="/etc/torrust/tracker/tracker.toml" -ARG TORRUST_TRACKER_DATABASE_DRIVER="sqlite3" +ARG TORRUST_TRACKER_CONFIG_TOML_PATH="/etc/torrust/tracker/tracker.toml" +ARG TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER="Sqlite3" ARG USER_ID=1000 ARG UDP_PORT=6969 ARG HTTP_PORT=7070 ARG API_PORT=1212 ARG HEALTH_CHECK_API_PORT=1313 -ENV TORRUST_TRACKER_PATH_CONFIG=${TORRUST_TRACKER_PATH_CONFIG} -ENV TORRUST_TRACKER_DATABASE_DRIVER=${TORRUST_TRACKER_DATABASE_DRIVER} +ENV TORRUST_TRACKER_CONFIG_TOML_PATH=${TORRUST_TRACKER_CONFIG_TOML_PATH} +ENV TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER} ENV USER_ID=${USER_ID} ENV UDP_PORT=${UDP_PORT} ENV HTTP_PORT=${HTTP_PORT} diff --git a/README.md b/README.md index 8431c00e4..754d2d5b7 100644 --- a/README.md +++ b/README.md @@ -84,14 +84,14 @@ cp ./share/default/config/tracker.development.sqlite3.toml ./storage/tracker/etc vim ./storage/tracker/etc/tracker.toml # Run the tracker with the updated configuration: -TORRUST_TRACKER_PATH_CONFIG="./storage/tracker/etc/tracker.toml" cargo run +TORRUST_TRACKER_CONFIG_TOML_PATH="./storage/tracker/etc/tracker.toml" cargo run ``` _Optionally, you may choose to supply the entire configuration as an environmental variable:_ ```sh # Use a configuration supplied on an environmental variable: -TORRUST_TRACKER_CONFIG=$(cat "./storage/tracker/etc/tracker.toml") cargo run +TORRUST_TRACKER_CONFIG_TOML=$(cat "./storage/tracker/etc/tracker.toml") cargo run ``` _For deployment, you **should** override the `api_admin_token` by using an environmental variable:_ @@ -102,8 +102,8 @@ gpg --armor --gen-random 1 10 | tee ./storage/tracker/lib/tracker_api_admin_toke chmod go-rwx ./storage/tracker/lib/tracker_api_admin_token.secret # Override secret in configuration using an environmental variable: -TORRUST_TRACKER_CONFIG=$(cat "./storage/tracker/etc/tracker.toml") \ - TORRUST_TRACKER_API_ADMIN_TOKEN=$(cat "./storage/tracker/lib/tracker_api_admin_token.secret") \ +TORRUST_TRACKER_CONFIG_TOML=$(cat "./storage/tracker/etc/tracker.toml") \ + TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN=$(cat "./storage/tracker/lib/tracker_api_admin_token.secret") \ cargo run ``` diff --git a/compose.yaml b/compose.yaml index 672ca6d0f..1d425c743 100644 --- a/compose.yaml +++ b/compose.yaml @@ -4,8 +4,8 @@ services: image: torrust-tracker:release tty: true environment: - - TORRUST_TRACKER_DATABASE_DRIVER=${TORRUST_TRACKER_DATABASE_DRIVER:-mysql} - - TORRUST_TRACKER_API_ADMIN_TOKEN=${TORRUST_TRACKER_API_ADMIN_TOKEN:-MyAccessToken} + - TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER:-MySQL} + - TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN=${TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN:-MyAccessToken} networks: - server_side ports: diff --git a/docs/benchmarking.md b/docs/benchmarking.md index 7c82df14c..2a3f1f8b0 100644 --- a/docs/benchmarking.md +++ b/docs/benchmarking.md @@ -39,7 +39,7 @@ Build and run the tracker: ```console cargo build --release -TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" ./target/release/torrust-tracker +TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.udp.benchmarking.toml" ./target/release/torrust-tracker ``` Run the load test with: diff --git a/docs/containers.md b/docs/containers.md index 6622e29b2..a0ba59d4b 100644 --- a/docs/containers.md +++ b/docs/containers.md @@ -147,10 +147,10 @@ Environmental variables are loaded through the `--env`, in the format `--env VAR The following environmental variables can be set: -- `TORRUST_TRACKER_PATH_CONFIG` - The in-container path to the tracker configuration file, (default: `"/etc/torrust/tracker/tracker.toml"`). -- `TORRUST_TRACKER_API_ADMIN_TOKEN` - Override of the admin token. If set, this value overrides any value set in the config. -- `TORRUST_TRACKER_DATABASE_DRIVER` - The database type used for the container, (options: `sqlite3`, `mysql`, default `sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. -- `TORRUST_TRACKER_CONFIG` - Load config from this environmental variable instead from a file, (i.e: `TORRUST_TRACKER_CONFIG=$(cat tracker-tracker.toml)`). +- `TORRUST_TRACKER_CONFIG_TOML_PATH` - The in-container path to the tracker configuration file, (default: `"/etc/torrust/tracker/tracker.toml"`). +- `TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN` - Override of the admin token. If set, this value overrides any value set in the config. +- `TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER` - The database type used for the container, (options: `Sqlite3`, `MySQL`, default `Sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. +- `TORRUST_TRACKER_CONFIG_TOML` - Load config from this environmental variable instead from a file, (i.e: `TORRUST_TRACKER_CONFIG_TOML=$(cat tracker-tracker.toml)`). - `USER_ID` - The user id for the runtime crated `torrust` user. Please Note: This user id should match the ownership of the host-mapped volumes, (default `1000`). - `UDP_PORT` - The port for the UDP tracker. This should match the port used in the configuration, (default `6969`). - `HTTP_PORT` - The port for the HTTP tracker. This should match the port used in the configuration, (default `7070`). @@ -205,7 +205,7 @@ mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ ## Run Torrust Tracker Container Image docker run -it \ - --env TORRUST_TRACKER_API_ADMIN_TOKEN="MySecretToken" \ + --env TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN="MySecretToken" \ --env USER_ID="$(id -u)" \ --publish 0.0.0.0:7070:7070/tcp \ --publish 0.0.0.0:6969:6969/udp \ @@ -227,7 +227,7 @@ mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ ## Run Torrust Tracker Container Image podman run -it \ - --env TORRUST_TRACKER_API_ADMIN_TOKEN="MySecretToken" \ + --env TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN="MySecretToken" \ --env USER_ID="$(id -u)" \ --publish 0.0.0.0:7070:7070/tcp \ --publish 0.0.0.0:6969:6969/udp \ @@ -255,7 +255,7 @@ docker build --target release --tag torrust-tracker:release --file Containerfile mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ USER_ID=$(id -u) \ - TORRUST_TRACKER_API_ADMIN_TOKEN="MySecretToken" \ + TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN="MySecretToken" \ docker compose up --build ``` diff --git a/docs/profiling.md b/docs/profiling.md index 406560f3c..8038f9e77 100644 --- a/docs/profiling.md +++ b/docs/profiling.md @@ -35,7 +35,7 @@ To generate the graph you will need to: ```console cargo build --profile=release-debug --bin=profiling ./target/release/aquatic_udp_load_test -c "load-test-config.toml" -sudo TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" /home/USER/.cargo/bin/flamegraph -- ./target/release-debug/profiling 60 +sudo TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.udp.benchmarking.toml" /home/USER/.cargo/bin/flamegraph -- ./target/release-debug/profiling 60 ``` __NOTICE__: You need to install the `aquatic_udp_load_test` program. @@ -92,7 +92,7 @@ Build and the binary for profiling: ```console RUSTFLAGS='-g' cargo build --release --bin profiling \ - && export TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" \ + && export TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.udp.benchmarking.toml" \ && valgrind \ --tool=callgrind \ --callgrind-out-file=callgrind.out \ diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 588feb87e..b79081a13 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -24,14 +24,13 @@ pub const TORRENT_PEERS_LIMIT: usize = 74; /// The whole `tracker.toml` file content. It has priority over the config file. /// Even if the file is not on the default path. -const ENV_VAR_CONFIG: &str = "TORRUST_TRACKER_CONFIG"; +const ENV_VAR_CONFIG_TOML: &str = "TORRUST_TRACKER_CONFIG_TOML"; /// The `tracker.toml` file location. -pub const ENV_VAR_PATH_CONFIG: &str = "TORRUST_TRACKER_PATH_CONFIG"; +pub const ENV_VAR_CONFIG_TOML_PATH: &str = "TORRUST_TRACKER_CONFIG_TOML_PATH"; /// Env var to overwrite API admin token. -/// Deprecated: use `TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN`. -const ENV_VAR_API_ADMIN_TOKEN: &str = "TORRUST_TRACKER_API_ADMIN_TOKEN"; +const ENV_VAR_HTTP_API_ACCESS_TOKENS_ADMIN: &str = "TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN"; pub type Configuration = v1::Configuration; pub type UdpTracker = v1::udp_tracker::UdpTracker; @@ -65,9 +64,9 @@ impl Info { /// #[allow(clippy::needless_pass_by_value)] pub fn new(default_config_toml_path: String) -> Result { - let env_var_config_toml = ENV_VAR_CONFIG.to_string(); - let env_var_config_toml_path = ENV_VAR_PATH_CONFIG.to_string(); - let env_var_api_admin_token = ENV_VAR_API_ADMIN_TOKEN.to_string(); + let env_var_config_toml = ENV_VAR_CONFIG_TOML.to_string(); + let env_var_config_toml_path = ENV_VAR_CONFIG_TOML_PATH.to_string(); + let env_var_api_admin_token = ENV_VAR_HTTP_API_ACCESS_TOKENS_ADMIN.to_string(); let config_toml = if let Ok(config_toml) = env::var(env_var_config_toml) { println!("Loading configuration from environment variable {config_toml} ..."); @@ -146,7 +145,7 @@ impl AnnouncePolicy { pub enum Error { /// Unable to load the configuration from the environment variable. /// This error only occurs if there is no configuration file and the - /// `TORRUST_TRACKER_CONFIG` environment variable is not set. + /// `TORRUST_TRACKER_CONFIG_TOML` environment variable is not set. #[error("Unable to load from Environmental Variable: {source}")] UnableToLoadFromEnvironmentVariable { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 8e15d65ca..b9d75c71d 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -9,7 +9,7 @@ //! with the same content as the file. //! //! Configuration can not only be loaded from a file, but also from an -//! environment variable `TORRUST_TRACKER_CONFIG`. This is useful when running +//! environment variable `TORRUST_TRACKER_CONFIG_TOML`. This is useful when running //! the tracker in a Docker container or environments where you do not have a //! persistent storage or you cannot inject a configuration file. Refer to //! [`Torrust Tracker documentation`](https://docs.rs/torrust-tracker) for more diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index aeb4d0d4e..47a837a9b 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -52,7 +52,9 @@ pub struct NumberOfBytes(pub i64); /// For more information about persistence. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, derive_more::Display, Clone)] pub enum DatabaseDriver { - // TODO: Move to the database crate once that gets its own crate. + // TODO: + // - Move to the database crate once that gets its own crate. + // - Rename serialized values to lowercase: `sqlite3` and `mysql`. /// The Sqlite3 database driver. Sqlite3, /// The `MySQL` database driver. diff --git a/share/container/entry_script_sh b/share/container/entry_script_sh index 4f98e6622..8c704ea67 100644 --- a/share/container/entry_script_sh +++ b/share/container/entry_script_sh @@ -26,29 +26,29 @@ chmod -R 2770 /var/lib/torrust /var/log/torrust /etc/torrust # Install the database and config: -if [ -n "$TORRUST_TRACKER_DATABASE_DRIVER" ]; then - if cmp_lc "$TORRUST_TRACKER_DATABASE_DRIVER" "sqlite3"; then +if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER" ]; then + if cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER" "Sqlite3"; then - # Select sqlite3 empty database + # Select Sqlite3 empty database default_database="/usr/share/torrust/default/database/tracker.sqlite3.db" - # Select sqlite3 default configuration + # Select Sqlite3 default configuration default_config="/usr/share/torrust/default/config/tracker.container.sqlite3.toml" - elif cmp_lc "$TORRUST_TRACKER_DATABASE_DRIVER" "mysql"; then + elif cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER" "MySQL"; then - # (no database file needed for mysql) + # (no database file needed for MySQL) - # Select default mysql configuration + # Select default MySQL configuration default_config="/usr/share/torrust/default/config/tracker.container.mysql.toml" else - echo "Error: Unsupported Database Type: \"$TORRUST_TRACKER_DATABASE_DRIVER\"." - echo "Please Note: Supported Database Types: \"sqlite3\", \"mysql\"." + echo "Error: Unsupported Database Type: \"$TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER\"." + echo "Please Note: Supported Database Types: \"Sqlite3\", \"MySQL\"." exit 1 fi else - echo "Error: \"\$TORRUST_TRACKER_DATABASE_DRIVER\" was not set!"; exit 1; + echo "Error: \"\$TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER\" was not set!"; exit 1; fi install_config="/etc/torrust/tracker/tracker.toml" diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 03dfd9a2f..6b607bd6f 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -1,6 +1,6 @@ //! Initialize configuration from file or env var. //! -//! All environment variables are prefixed with `TORRUST_TRACKER_BACK_`. +//! All environment variables are prefixed with `TORRUST_TRACKER_`. use torrust_tracker_configuration::{Configuration, Info}; @@ -11,7 +11,7 @@ pub const DEFAULT_PATH_CONFIG: &str = "./share/default/config/tracker.developmen /// There are two methods to inject the configuration: /// /// 1. By using a config file: `tracker.toml`. -/// 2. Environment variable: `TORRUST_TRACKER_CONFIG`. The variable contains the same contents as the `tracker.toml` file. +/// 2. Environment variable: `TORRUST_TRACKER_CONFIG_TOML`. The variable contains the same contents as the `tracker.toml` file. /// /// Environment variable has priority over the config file. /// @@ -20,7 +20,7 @@ pub const DEFAULT_PATH_CONFIG: &str = "./share/default/config/tracker.developmen /// # Panics /// /// Will panic if it can't load the configuration from either -/// `./tracker.toml` file or the env var `TORRUST_TRACKER_CONFIG`. +/// `./tracker.toml` file or the env var `TORRUST_TRACKER_CONFIG_TOML`. #[must_use] pub fn initialize_configuration() -> Configuration { let info = Info::new(DEFAULT_PATH_CONFIG.to_string()).expect("info to load configuration is not valid"); diff --git a/src/console/ci/e2e/runner.rs b/src/console/ci/e2e/runner.rs index 1a4746800..945a87033 100644 --- a/src/console/ci/e2e/runner.rs +++ b/src/console/ci/e2e/runner.rs @@ -46,7 +46,7 @@ pub fn run() { // Besides, if we don't use port 0 we should get the port numbers from the tracker configuration. // We could not use docker, but the intention was to create E2E tests including containerization. let options = RunOptions { - env_vars: vec![("TORRUST_TRACKER_CONFIG".to_string(), tracker_config.to_string())], + env_vars: vec![("TORRUST_TRACKER_CONFIG_TOML".to_string(), tracker_config.to_string())], ports: vec![ "6969:6969/udp".to_string(), "7070:7070/tcp".to_string(), diff --git a/src/console/profiling.rs b/src/console/profiling.rs index e0867159f..52e11913f 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -27,7 +27,7 @@ //! //! ```text //! RUSTFLAGS='-g' cargo build --release --bin profiling \ -//! && export TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" \ +//! && export TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.udp.benchmarking.toml" \ //! && valgrind \ //! --tool=callgrind \ //! --callgrind-out-file=callgrind.out \ @@ -40,7 +40,7 @@ //! //! ```text //! RUSTFLAGS='-g' cargo build --release --bin profiling \ -//! && export TORRUST_TRACKER_PATH_CONFIG="./share/default/config/tracker.udp.benchmarking.toml" \ +//! && export TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.udp.benchmarking.toml" \ //! && valgrind \ //! --tool=callgrind \ //! --callgrind-out-file=callgrind.out \ diff --git a/src/lib.rs b/src/lib.rs index 22bc133e1..6fd5da15f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -213,10 +213,10 @@ //! documentation for the [torrust-tracker-configuration crate](https://docs.rs/torrust-tracker-configuration). //! //! Alternatively to the `tracker.toml` file you can use one environment -//! variable `TORRUST_TRACKER_CONFIG` to pass the configuration to the tracker: +//! variable `TORRUST_TRACKER_CONFIG_TOML` to pass the configuration to the tracker: //! //! ```text -//! TORRUST_TRACKER_CONFIG=$(cat ./share/default/config/tracker.development.sqlite3.toml) ./target/release/torrust-tracker +//! TORRUST_TRACKER_CONFIG_TOML=$(cat ./share/default/config/tracker.development.sqlite3.toml) ./target/release/torrust-tracker //! ``` //! //! In the previous example you are just setting the env var with the contents @@ -225,7 +225,7 @@ //! The env var contains the same data as the `tracker.toml`. It's particularly //! useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/tree/develop/docker). //! -//! > NOTICE: The `TORRUST_TRACKER_CONFIG` env var has priority over the `tracker.toml` file. +//! > NOTICE: The `TORRUST_TRACKER_CONFIG_TOML` env var has priority over the `tracker.toml` file. //! //! By default, if you don’t specify any `tracker.toml` file, the application //! will use `./share/default/config/tracker.development.sqlite3.toml`. From a4d2adfe8bd5f5c9dd4fd866e0f89b2b3c404154 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 14 May 2024 15:27:37 +0100 Subject: [PATCH 0342/1297] feat!: remove deprecated env var The env var `TORRUST_TRACKER_API_ADMIN_TOKEN` was replaced with `TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN`. After the migration to Figment all configuration options can be overwritten. --- packages/configuration/src/lib.rs | 6 ----- packages/configuration/src/v1/mod.rs | 34 +--------------------------- 2 files changed, 1 insertion(+), 39 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index b79081a13..62792c271 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -29,9 +29,6 @@ const ENV_VAR_CONFIG_TOML: &str = "TORRUST_TRACKER_CONFIG_TOML"; /// The `tracker.toml` file location. pub const ENV_VAR_CONFIG_TOML_PATH: &str = "TORRUST_TRACKER_CONFIG_TOML_PATH"; -/// Env var to overwrite API admin token. -const ENV_VAR_HTTP_API_ACCESS_TOKENS_ADMIN: &str = "TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN"; - pub type Configuration = v1::Configuration; pub type UdpTracker = v1::udp_tracker::UdpTracker; pub type HttpTracker = v1::http_tracker::HttpTracker; @@ -52,7 +49,6 @@ pub struct TrackerPolicy { pub struct Info { config_toml: Option, config_toml_path: String, - api_admin_token: Option, } impl Info { @@ -66,7 +62,6 @@ impl Info { pub fn new(default_config_toml_path: String) -> Result { let env_var_config_toml = ENV_VAR_CONFIG_TOML.to_string(); let env_var_config_toml_path = ENV_VAR_CONFIG_TOML_PATH.to_string(); - let env_var_api_admin_token = ENV_VAR_HTTP_API_ACCESS_TOKENS_ADMIN.to_string(); let config_toml = if let Ok(config_toml) = env::var(env_var_config_toml) { println!("Loading configuration from environment variable {config_toml} ..."); @@ -86,7 +81,6 @@ impl Info { Ok(Self { config_toml, config_toml_path, - api_admin_token: env::var(env_var_api_admin_token).ok(), }) } } diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index b9d75c71d..8d45270b8 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -288,10 +288,6 @@ impl Default for Configuration { } impl Configuration { - fn override_api_admin_token(&mut self, api_admin_token: &str) { - self.http_api.override_admin_token(api_admin_token); - } - /// Returns the tracker public IP address id defined in the configuration, /// and `None` otherwise. #[must_use] @@ -331,11 +327,7 @@ impl Configuration { .merge(Env::prefixed(CONFIG_OVERRIDE_PREFIX).split(CONFIG_OVERRIDE_SEPARATOR)) }; - let mut config: Configuration = figment.extract()?; - - if let Some(ref token) = info.api_admin_token { - config.override_api_admin_token(token); - }; + let config: Configuration = figment.extract()?; Ok(config) } @@ -469,7 +461,6 @@ mod tests { let info = Info { config_toml: Some(empty_configuration), config_toml_path: "tracker.toml".to_string(), - api_admin_token: None, }; let configuration = Configuration::load(&info).expect("Could not load configuration from file"); @@ -491,7 +482,6 @@ mod tests { let info = Info { config_toml: Some(config_toml), config_toml_path: String::new(), - api_admin_token: None, }; let configuration = Configuration::load(&info).expect("Could not load configuration from file"); @@ -515,7 +505,6 @@ mod tests { let info = Info { config_toml: None, config_toml_path: "tracker.toml".to_string(), - api_admin_token: None, }; let configuration = Configuration::load(&info).expect("Could not load configuration from file"); @@ -534,27 +523,6 @@ mod tests { let info = Info { config_toml: Some(default_config_toml()), config_toml_path: String::new(), - api_admin_token: None, - }; - - let configuration = Configuration::load(&info).expect("Could not load configuration from file"); - - assert_eq!( - configuration.http_api.access_tokens.get("admin"), - Some("NewToken".to_owned()).as_ref() - ); - - Ok(()) - }); - } - - #[test] - fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin_with_the_deprecated_env_var_name() { - figment::Jail::expect_with(|_jail| { - let info = Info { - config_toml: Some(default_config_toml()), - config_toml_path: String::new(), - api_admin_token: Some("NewToken".to_owned()), }; let configuration = Configuration::load(&info).expect("Could not load configuration from file"); From e1e107123a09893e08b0443ac9750cf6a3e6987f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 14 May 2024 17:27:08 +0100 Subject: [PATCH 0343/1297] docs: update README - Fix missing line break after badgets. - Add roadmap draft. --- README.md | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 754d2d5b7..ebd7c357b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # Torrust Tracker -[![container_wf_b]][container_wf] [![coverage_wf_b]][coverage_wf] [![deployment_wf_b]][deployment_wf] [![testing_wf_b]][testing_wf]**Torrust Tracker** is a [BitTorrent][bittorrent] Tracker that matchmakes peers and collects statistics. Written in [Rust Language][rust] with the [Axum] web framework. _**This tracker aims to be respectful to established standards, (both [formal][BEP 00] and [otherwise][torrent_source_felid]).___ +[![container_wf_b]][container_wf] [![coverage_wf_b]][coverage_wf] [![deployment_wf_b]][deployment_wf] [![testing_wf_b]][testing_wf] + +**Torrust Tracker** is a [BitTorrent][bittorrent] Tracker that matchmakes peers and collects statistics. Written in [Rust Language][rust] with the [Axum] web framework. **This tracker aims to be respectful to established standards, (both [formal][BEP 00] and [otherwise][torrent_source_felid]).** > This is a [Torrust][torrust] project and is in active development. It is community supported as well as sponsored by [Nautilus Cyberneering][nautilus]. @@ -17,6 +19,44 @@ - [x] Support [newTrackon][newtrackon] checks. - [x] Persistent `SQLite3` or `MySQL` Databases. +## Roadmap + +Persistence: + +- [ ] Support other databases. + +Integrations: + +- [ ] Webhooks. + +Administration: + +- [ ] Improve categories and tag management. +- [ ] User management: list, search and ban users. +- [ ] Full-private mode. +- [ ] User statistics. + +Users: + +- [ ] Reset or change the password. +- [ ] User profile. +- [ ] Invitation system. +- [ ] User moderation. +- [ ] Add torrent providing only the info-hash. +- [ ] Improve search. + +Torrents: + +- [ ] Change the source field. +- [ ] Change the creator field. +- [ ] Implement BEP 19: WebSeed - HTTP/FTP Seeding (GetRight style). +- [ ] Implement BEP 32: BitTorrent DHT Extensions for IPv6. + +Others: + +- [ ] Multi-tracker +- [ ] Multi-language + ## Implemented BitTorrent Enhancement Proposals (BEPs) > > _[Learn more about BitTorrent Enhancement Proposals][BEP 00]_ From 80fc8d6b4d7b120b11984bbe229c6c7860da3909 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 14 May 2024 18:01:47 +0100 Subject: [PATCH 0344/1297] docs: udpate roadmap in README I copied the Index roadmap isntead of the tracker one by mistake. --- README.md | 42 ++++++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index ebd7c357b..f83dbd936 100644 --- a/README.md +++ b/README.md @@ -21,41 +21,39 @@ ## Roadmap +Core: + +- [ ] New option `want_ip_from_query_string`. See . +- [ ] Permanent keys. See . +- [ ] Peer and torrents specific statistics. See . + Persistence: -- [ ] Support other databases. +- [ ] Support other databases like PostgreSQL. -Integrations: +Performance: -- [ ] Webhooks. +- [ ] More optimizations. See . -Administration: +Protocols: -- [ ] Improve categories and tag management. -- [ ] User management: list, search and ban users. -- [ ] Full-private mode. -- [ ] User statistics. +- [ ] WebTorrent. -Users: +Integrations: -- [ ] Reset or change the password. -- [ ] User profile. -- [ ] Invitation system. -- [ ] User moderation. -- [ ] Add torrent providing only the info-hash. -- [ ] Improve search. +- [ ] Monitoring (Prometheus). -Torrents: +Utils: -- [ ] Change the source field. -- [ ] Change the creator field. -- [ ] Implement BEP 19: WebSeed - HTTP/FTP Seeding (GetRight style). -- [ ] Implement BEP 32: BitTorrent DHT Extensions for IPv6. +- [ ] Tracker client. +- [ ] Tracker checker. Others: -- [ ] Multi-tracker -- [ ] Multi-language +- [ ] Support for Windows. +- [ ] Docker images for other architectures. + + ## Implemented BitTorrent Enhancement Proposals (BEPs) > From dadc216e8a3a75316f735d6b3debdab08d8e595a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 May 2024 12:25:58 +0100 Subject: [PATCH 0345/1297] chore(deps): add cargo dependencies needed for axum timeouts We want to add timeouts for the Axum server configuration, in order to close HTTP connections when the client doesn't send any request after opening a HTTP connection. --- Cargo.lock | 5 +++++ Cargo.toml | 5 +++++ cSpell.json | 4 ++++ 3 files changed, 14 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 446477aac..523ea575d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3891,8 +3891,11 @@ dependencies = [ "fern", "figment", "futures", + "futures-util", "hex-literal", + "http-body", "hyper", + "hyper-util", "lazy_static", "local-ip-address", "log", @@ -3900,6 +3903,7 @@ dependencies = [ "multimap", "parking_lot", "percent-encoding", + "pin-project-lite", "r2d2", "r2d2_mysql", "r2d2_sqlite", @@ -3920,6 +3924,7 @@ dependencies = [ "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-tracker-torrent-repository", + "tower", "tower-http", "trace", "tracing", diff --git a/Cargo.toml b/Cargo.toml index 60652b160..5183c6067 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,13 +46,17 @@ derive_more = "0" fern = "0" figment = "0.10.18" futures = "0" +futures-util = "0.3.30" hex-literal = "0" +http-body = "1.0.0" hyper = "1" +hyper-util = { version = "0.1.3", features = ["http1", "http2", "tokio"] } lazy_static = "1" log = { version = "0", features = ["release_max_level_info"] } multimap = "0" parking_lot = "0.12.1" percent-encoding = "2" +pin-project-lite = "0.2.14" r2d2 = "0" r2d2_mysql = "24" r2d2_sqlite = { version = "0", features = ["bundled"] } @@ -72,6 +76,7 @@ torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12-develop", path = " torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "packages/located-error" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } torrust-tracker-torrent-repository = { version = "3.0.0-alpha.12-develop", path = "packages/torrent-repository" } +tower = { version = "0.4.13", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } trace = "0" tracing = "0" diff --git a/cSpell.json b/cSpell.json index bd6c9d489..2b5cf55bf 100644 --- a/cSpell.json +++ b/cSpell.json @@ -50,6 +50,7 @@ "downloadedi", "dtolnay", "elif", + "Eray", "filesd", "flamegraph", "Freebox", @@ -73,6 +74,7 @@ "intervali", "Joakim", "kallsyms", + "Karatay", "kcachegrind", "kexec", "keyout", @@ -107,6 +109,7 @@ "Pando", "peekable", "peerlist", + "programatik", "proot", "proto", "Quickstart", @@ -137,6 +140,7 @@ "sharktorrent", "SHLVL", "skiplist", + "slowloris", "socketaddr", "sqllite", "subsec", From 112b76d79da76381d4ee8f04828c74a438d83308 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 May 2024 12:27:50 +0100 Subject: [PATCH 0346/1297] fix: [#612] add timeout for time waiting for the first API requests Adds a timeout for the Tracker API for the time the server waits for the first request from the client after openning a new HTTP connection. --- src/servers/apis/server.rs | 9 +- src/servers/custom_axum_server.rs | 275 ++++++++++++++++++++++++++++++ src/servers/mod.rs | 1 + 3 files changed, 282 insertions(+), 3 deletions(-) create mode 100644 src/servers/custom_axum_server.rs diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 9317d6ec0..57d2629ae 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -37,6 +37,7 @@ use torrust_tracker_configuration::AccessTokens; use super::routes::router; use crate::bootstrap::jobs::Started; use crate::core::Tracker; +use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{graceful_shutdown, Halted}; @@ -177,7 +178,7 @@ impl ApiServer { /// Or if there request returns an error code. #[must_use] pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { - let url = format!("http://{binding}/api/health_check"); + let url = format!("http://{binding}/api/health_check"); // DevSkim: ignore DS137138 let info = format!("checking api health check at: {url}"); @@ -234,13 +235,15 @@ impl Launcher { let running = Box::pin(async { match tls { - Some(tls) => axum_server::from_tcp_rustls(socket, tls) + Some(tls) => custom_axum_server::from_tcp_rustls_with_timeouts(socket, tls) .handle(handle) + .acceptor(TimeoutAcceptor) .serve(router.into_make_service_with_connect_info::()) .await .expect("Axum server for tracker API crashed."), - None => axum_server::from_tcp(socket) + None => custom_axum_server::from_tcp_with_timeouts(socket) .handle(handle) + .acceptor(TimeoutAcceptor) .serve(router.into_make_service_with_connect_info::()) .await .expect("Axum server for tracker API crashed."), diff --git a/src/servers/custom_axum_server.rs b/src/servers/custom_axum_server.rs new file mode 100644 index 000000000..5705ef24e --- /dev/null +++ b/src/servers/custom_axum_server.rs @@ -0,0 +1,275 @@ +//! Wrapper for Axum server to add timeouts. +//! +//! Copyright (c) Eray Karatay ([@programatik29](https://github.com/programatik29)). +//! +//! See: . +//! +//! If a client opens a HTTP connection and it does not send any requests, the +//! connection is closed after a timeout. You can test it with: +//! +//! ```text +//! telnet 127.0.0.1 1212 +//! Trying 127.0.0.1... +//! Connected to 127.0.0.1. +//! Escape character is '^]'. +//! Connection closed by foreign host. +//! ``` +//! +//! If you want to know more about Axum and timeouts see . +use std::future::Ready; +use std::io::ErrorKind; +use std::net::TcpListener; +use std::pin::Pin; +use std::task::{Context, Poll}; +use std::time::Duration; + +use axum_server::accept::Accept; +use axum_server::tls_rustls::{RustlsAcceptor, RustlsConfig}; +use axum_server::Server; +use futures_util::{ready, Future}; +use http_body::{Body, Frame}; +use hyper::Response; +use hyper_util::rt::TokioTimer; +use pin_project_lite::pin_project; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; +use tokio::time::{Instant, Sleep}; +use tower::Service; + +const HTTP1_HEADER_READ_TIMEOUT: Duration = Duration::from_secs(5); +const HTTP2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(5); +const HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(5); + +#[must_use] +pub fn from_tcp_with_timeouts(socket: TcpListener) -> Server { + add_timeouts(axum_server::from_tcp(socket)) +} + +#[must_use] +pub fn from_tcp_rustls_with_timeouts(socket: TcpListener, tls: RustlsConfig) -> Server { + add_timeouts(axum_server::from_tcp_rustls(socket, tls)) +} + +fn add_timeouts(mut server: Server) -> Server { + server.http_builder().http1().timer(TokioTimer::new()); + server.http_builder().http2().timer(TokioTimer::new()); + + server.http_builder().http1().header_read_timeout(HTTP1_HEADER_READ_TIMEOUT); + server + .http_builder() + .http2() + .keep_alive_timeout(HTTP2_KEEP_ALIVE_TIMEOUT) + .keep_alive_interval(HTTP2_KEEP_ALIVE_INTERVAL); + + server +} + +#[derive(Clone)] +pub struct TimeoutAcceptor; + +impl Accept for TimeoutAcceptor { + type Stream = TimeoutStream; + type Service = TimeoutService; + type Future = Ready>; + + fn accept(&self, stream: I, service: S) -> Self::Future { + let (tx, rx) = mpsc::unbounded_channel(); + + let stream = TimeoutStream::new(stream, HTTP1_HEADER_READ_TIMEOUT, rx); + let service = TimeoutService::new(service, tx); + + std::future::ready(Ok((stream, service))) + } +} + +#[derive(Clone)] +pub struct TimeoutService { + inner: S, + sender: UnboundedSender, +} + +impl TimeoutService { + fn new(inner: S, sender: UnboundedSender) -> Self { + Self { inner, sender } + } +} + +impl Service for TimeoutService +where + S: Service>, +{ + type Response = Response>; + type Error = S::Error; + type Future = TimeoutServiceFuture; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.inner.poll_ready(cx) + } + + fn call(&mut self, req: Request) -> Self::Future { + // send timer wait signal + let _ = self.sender.send(TimerSignal::Wait); + + TimeoutServiceFuture::new(self.inner.call(req), self.sender.clone()) + } +} + +pin_project! { + pub struct TimeoutServiceFuture { + #[pin] + inner: F, + sender: Option>, + } +} + +impl TimeoutServiceFuture { + fn new(inner: F, sender: UnboundedSender) -> Self { + Self { + inner, + sender: Some(sender), + } + } +} + +impl Future for TimeoutServiceFuture +where + F: Future, E>>, +{ + type Output = Result>, E>; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let this = self.project(); + this.inner.poll(cx).map(|result| { + result.map(|response| { + response.map(|body| TimeoutBody::new(body, this.sender.take().expect("future polled after ready"))) + }) + }) + } +} + +enum TimerSignal { + Wait, + Reset, +} + +pin_project! { + pub struct TimeoutBody { + #[pin] + inner: B, + sender: UnboundedSender, + } +} + +impl TimeoutBody { + fn new(inner: B, sender: UnboundedSender) -> Self { + Self { inner, sender } + } +} + +impl Body for TimeoutBody { + type Data = B::Data; + type Error = B::Error; + + fn poll_frame(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll, Self::Error>>> { + let this = self.project(); + let option = ready!(this.inner.poll_frame(cx)); + + if option.is_none() { + let _ = this.sender.send(TimerSignal::Reset); + } + + Poll::Ready(option) + } + + fn is_end_stream(&self) -> bool { + let is_end_stream = self.inner.is_end_stream(); + + if is_end_stream { + let _ = self.sender.send(TimerSignal::Reset); + } + + is_end_stream + } + + fn size_hint(&self) -> http_body::SizeHint { + self.inner.size_hint() + } +} + +pub struct TimeoutStream { + inner: IO, + // hyper requires unpin + sleep: Pin>, + duration: Duration, + waiting: bool, + receiver: UnboundedReceiver, + finished: bool, +} + +impl TimeoutStream { + fn new(inner: IO, duration: Duration, receiver: UnboundedReceiver) -> Self { + Self { + inner, + sleep: Box::pin(tokio::time::sleep(duration)), + duration, + waiting: false, + receiver, + finished: false, + } + } +} + +impl AsyncRead for TimeoutStream { + fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll> { + if !self.finished { + match Pin::new(&mut self.receiver).poll_recv(cx) { + // reset the timer + Poll::Ready(Some(TimerSignal::Reset)) => { + self.waiting = false; + + let deadline = Instant::now() + self.duration; + self.sleep.as_mut().reset(deadline); + } + // enter waiting mode (for response body last chunk) + Poll::Ready(Some(TimerSignal::Wait)) => self.waiting = true, + Poll::Ready(None) => self.finished = true, + Poll::Pending => (), + } + } + + if !self.waiting { + // return error if timer is elapsed + if let Poll::Ready(()) = self.sleep.as_mut().poll(cx) { + return Poll::Ready(Err(std::io::Error::new(ErrorKind::TimedOut, "request header read timed out"))); + } + } + + Pin::new(&mut self.inner).poll_read(cx, buf) + } +} + +impl AsyncWrite for TimeoutStream { + fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { + Pin::new(&mut self.inner).poll_write(cx, buf) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_flush(cx) + } + + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_shutdown(cx) + } + + fn poll_write_vectored( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[std::io::IoSlice<'_>], + ) -> Poll> { + Pin::new(&mut self.inner).poll_write_vectored(cx, bufs) + } + + fn is_write_vectored(&self) -> bool { + self.inner.is_write_vectored() + } +} diff --git a/src/servers/mod.rs b/src/servers/mod.rs index b0e222d2a..0c9cc5dd8 100644 --- a/src/servers/mod.rs +++ b/src/servers/mod.rs @@ -1,5 +1,6 @@ //! Servers. Services that can be started and stopped. pub mod apis; +pub mod custom_axum_server; pub mod health_check_api; pub mod http; pub mod registar; From 9e42a1a452804f1f14f5e6a99c38bdccabbc5001 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 May 2024 12:51:25 +0100 Subject: [PATCH 0347/1297] feat: [#612] tower middleware to apply timeouts to requests --- src/servers/apis/routes.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index e3d1ef446..087bcfa4a 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -8,12 +8,15 @@ use std::sync::Arc; use std::time::Duration; +use axum::error_handling::HandleErrorLayer; use axum::http::HeaderName; use axum::response::Response; use axum::routing::get; -use axum::{middleware, Router}; -use hyper::Request; +use axum::{middleware, BoxError, Router}; +use hyper::{Request, StatusCode}; use torrust_tracker_configuration::AccessTokens; +use tower::timeout::TimeoutLayer; +use tower::ServiceBuilder; use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; @@ -25,6 +28,8 @@ use super::v1::context::health_check::handlers::health_check_handler; use super::v1::middlewares::auth::State; use crate::core::Tracker; +const TIMEOUT: Duration = Duration::from_secs(5); + /// Add all API routes to the router. #[allow(clippy::needless_pass_by_value)] pub fn router(tracker: Arc, access_tokens: Arc) -> Router { @@ -73,4 +78,11 @@ pub fn router(tracker: Arc, access_tokens: Arc) -> Router }), ) .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) + .layer( + ServiceBuilder::new() + // this middleware goes above `TimeoutLayer` because it will receive + // errors returned by `TimeoutLayer` + .layer(HandleErrorLayer::new(|_: BoxError| async { StatusCode::REQUEST_TIMEOUT })) + .layer(TimeoutLayer::new(TIMEOUT)), + ) } From 23d5e5e14d93d66dd51ec5095b3d3e199e727db3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 May 2024 15:31:15 +0100 Subject: [PATCH 0348/1297] fix: [#613] add timeout for time waiting for the first HTTP tracker request Adds a timeout to the HTTP tracker for the time the server waits for the first request from the client after openning a new HTTP connection. It also adds a tower middleware for timeouts in requests. --- src/servers/http/server.rs | 7 +++++-- src/servers/http/v1/routes.rs | 16 ++++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 7c8148f22..a68f7d16c 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -12,6 +12,7 @@ use tokio::sync::oneshot::{Receiver, Sender}; use super::v1::routes::router; use crate::bootstrap::jobs::Started; use crate::core::Tracker; +use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{graceful_shutdown, Halted}; @@ -60,13 +61,15 @@ impl Launcher { let running = Box::pin(async { match tls { - Some(tls) => axum_server::from_tcp_rustls(socket, tls) + Some(tls) => custom_axum_server::from_tcp_rustls_with_timeouts(socket, tls) .handle(handle) + .acceptor(TimeoutAcceptor) .serve(app.into_make_service_with_connect_info::()) .await .expect("Axum server crashed."), - None => axum_server::from_tcp(socket) + None => custom_axum_server::from_tcp_with_timeouts(socket) .handle(handle) + .acceptor(TimeoutAcceptor) .serve(app.into_make_service_with_connect_info::()) .await .expect("Axum server crashed."), diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 05cd38713..c54da51a3 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -3,12 +3,15 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; +use axum::error_handling::HandleErrorLayer; use axum::http::HeaderName; use axum::response::Response; use axum::routing::get; -use axum::Router; +use axum::{BoxError, Router}; use axum_client_ip::SecureClientIpSource; -use hyper::Request; +use hyper::{Request, StatusCode}; +use tower::timeout::TimeoutLayer; +use tower::ServiceBuilder; use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; @@ -18,6 +21,8 @@ use tracing::{Level, Span}; use super::handlers::{announce, health_check, scrape}; use crate::core::Tracker; +const TIMEOUT: Duration = Duration::from_secs(5); + /// It adds the routes to the router. /// /// > **NOTICE**: it's added a layer to get the client IP from the connection @@ -69,4 +74,11 @@ pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { }), ) .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) + .layer( + ServiceBuilder::new() + // this middleware goes above `TimeoutLayer` because it will receive + // errors returned by `TimeoutLayer` + .layer(HandleErrorLayer::new(|_: BoxError| async { StatusCode::REQUEST_TIMEOUT })) + .layer(TimeoutLayer::new(TIMEOUT)), + ) } From 23c52b191c62ca39b7b9947f3167b4bd6cf8fbae Mon Sep 17 00:00:00 2001 From: Gabriel Grondin Date: Sun, 19 May 2024 19:34:08 +0200 Subject: [PATCH 0349/1297] Fix REAADME HTTP port --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f83dbd936..306a8620c 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ The following services are provided by the default configuration: - UDP _(tracker)_ - `udp://127.0.0.1:6969/announce`. - HTTP _(tracker)_ - - `http://127.0.0.1:6969/announce`. + - `http://127.0.0.1:7070/announce`. - API _(management)_ - `http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken`. From 9be936622b5199d12f022aa197927aaf15a09915 Mon Sep 17 00:00:00 2001 From: Gabriel GRONDIN Date: Mon, 20 May 2024 18:12:54 +0200 Subject: [PATCH 0350/1297] Fix and improved bootstrap jobs module test. On O.S. with different language than english the BadTlsConfig source error message will differ from the compared one. This will fix this issue by matching the enum itself instead of relying on a string compare. --- src/bootstrap/jobs/mod.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index d288989b5..e20d243c6 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -50,7 +50,7 @@ mod tests { use camino::Utf8PathBuf; use torrust_tracker_configuration::TslConfig; - use super::make_rust_tls; + use super::{make_rust_tls, Error}; #[tokio::test] async fn it_should_error_on_bad_tls_config() { @@ -65,9 +65,7 @@ mod tests { .expect("tls_was_enabled") .expect_err("bad_cert_and_key_files"); - assert!(err - .to_string() - .contains("bad tls config: No such file or directory (os error 2)")); + assert!(matches!(err, Error::BadTlsConfig { source: _ })); } #[tokio::test] @@ -83,7 +81,7 @@ mod tests { .expect("tls_was_enabled") .expect_err("missing_config"); - assert_eq!(err.to_string(), "tls config missing"); + assert!(matches!(err, Error::MissingTlsConfig { location: _ })); } } From 932e66e14533ea15f3acff526b852e8ecafb938b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 May 2024 15:44:08 +0100 Subject: [PATCH 0351/1297] feat: [#870] add privacy methods to the TrackerMode The tracker mode can be: - Public (Non-whitelisted) - Listed (Whitelisted) - Private (Non-whitelisted) - PrivateListed (Whitelisted) They should have been two different flags (in my opinion): - Visibility: public or private - Whitelisted: true or false So we would have the same four convinations: - Not whitelisted: - Public - Private - Whitelisted - Public - Private That's a pending refactor. For this commits, the goal is just to align this enum with what we added to the Index so we can use this enum in the Index via the primmitives crate. --- packages/primitives/src/lib.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index 47a837a9b..aa3af27e3 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -85,3 +85,21 @@ pub enum TrackerMode { #[serde(rename = "private_listed")] PrivateListed, } + +impl Default for TrackerMode { + fn default() -> Self { + Self::Public + } +} + +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() + } +} From 74d8f7918bd6c25c8dea8d208659ec6a3199bead Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 May 2024 16:05:39 +0100 Subject: [PATCH 0352/1297] feat: [#870] remove Copy trait from TrackerMode --- packages/primitives/src/lib.rs | 2 +- src/core/mod.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index aa3af27e3..eccd220f9 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -67,7 +67,7 @@ pub type PersistentTorrents = BTreeMap; /// /// Refer to [Torrust Tracker Configuration](https://docs.rs/torrust-tracker-configuration) /// to know how to configure the tracker to run in each mode. -#[derive(Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Debug)] +#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)] pub enum TrackerMode { /// Will track every new info hash and serve every peer. #[serde(rename = "public")] diff --git a/src/core/mod.rs b/src/core/mod.rs index 18a6028f7..2b61e3031 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -547,7 +547,7 @@ impl Tracker { ) -> Result { let database = Arc::new(databases::driver::build(&config.db_driver, &config.db_path)?); - let mode = config.mode; + let mode = config.mode.clone(); Ok(Tracker { //config, From 0c9da2f48b04e149991f5cc9a86b25ee8d2ceb43 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 May 2024 16:19:20 +0100 Subject: [PATCH 0353/1297] feat: [#870] implement traits Dispaly and FromStr for TrackerMode --- packages/primitives/src/lib.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index eccd220f9..454635e8d 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -5,6 +5,8 @@ //! by the tracker server crate, but also by other crates in the Torrust //! ecosystem. use std::collections::BTreeMap; +use std::fmt; +use std::str::FromStr; use std::time::Duration; use info_hash::InfoHash; @@ -92,6 +94,32 @@ impl Default for TrackerMode { } } +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 { + 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 { From 9e71e718afd420266cbc1e1e43dcce073e0f8e3f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 31 May 2024 09:23:18 +0100 Subject: [PATCH 0354/1297] chore(deps): update dependencies ```output $ cargo update Updating crates.io index Updating addr2line v0.21.0 -> v0.22.0 (latest: v0.23.0) Updating anyhow v1.0.83 -> v1.0.86 Updating async-channel v2.3.0 -> v2.3.1 Updating async-compression v0.4.10 -> v0.4.11 Updating async-executor v1.11.0 -> v1.12.0 Updating backtrace v0.3.71 -> v0.3.72 Updating blocking v1.6.0 -> v1.6.1 Updating brotli-decompressor v4.0.0 -> v4.0.1 Updating camino v1.1.6 -> v1.1.7 Updating cc v1.0.97 -> v1.0.98 Updating clang-sys v1.7.0 -> v1.8.1 Updating crc32fast v1.4.0 -> v1.4.2 Updating crossbeam-channel v0.5.12 -> v0.5.13 Updating crossbeam-utils v0.8.19 -> v0.8.20 Updating darling v0.20.8 -> v0.20.9 Updating darling_core v0.20.8 -> v0.20.9 Updating darling_macro v0.20.8 -> v0.20.9 Updating either v1.11.0 -> v1.12.0 Updating event-listener v5.3.0 -> v5.3.1 Updating figment v0.10.18 -> v0.10.19 Updating gimli v0.28.1 -> v0.29.0 (latest: v0.30.0) Updating h2 v0.4.4 -> v0.4.5 Updating hyper-util v0.1.3 -> v0.1.5 Updating instant v0.1.12 -> v0.1.13 Updating libc v0.2.154 -> v0.2.155 Updating libz-sys v1.1.16 -> v1.1.18 Updating linux-raw-sys v0.4.13 -> v0.4.14 (latest: v0.6.4) Updating miniz_oxide v0.7.2 -> v0.7.3 Updating native-tls v0.2.11 -> v0.2.12 Updating object v0.32.2 -> v0.35.0 (latest: v0.36.0) Updating parking_lot v0.12.2 -> v0.12.3 Updating plotters v0.3.5 -> v0.3.6 Updating plotters-backend v0.3.5 -> v0.3.6 Updating plotters-svg v0.3.5 -> v0.3.6 Updating proc-macro2 v1.0.82 -> v1.0.84 Updating ringbuf v0.4.0 -> v0.4.1 Updating rstest v0.19.0 -> v0.20.0 Updating rstest_macros v0.19.0 -> v0.20.0 Updating rustversion v1.0.16 -> v1.0.17 Updating serde v1.0.201 -> v1.0.203 Updating serde_derive v1.0.201 -> v1.0.203 Updating serde_spanned v0.6.5 -> v0.6.6 Removing strsim v0.10.0 Updating syn v2.0.63 -> v2.0.66 Updating thiserror v1.0.60 -> v1.0.61 Updating thiserror-impl v1.0.60 -> v1.0.61 Updating tokio v1.37.0 -> v1.38.0 Updating tokio-macros v2.2.0 -> v2.3.0 Updating toml v0.8.12 -> v0.8.13 Updating toml_datetime v0.6.5 -> v0.6.6 Updating toml_edit v0.22.12 -> v0.22.13 Updating winnow v0.6.8 -> v0.6.9 ``` --- Cargo.lock | 290 ++++++++++++++++++++++++++--------------------------- 1 file changed, 141 insertions(+), 149 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 523ea575d..4e08b1b4d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "addr2line" -version = "0.21.0" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" +checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" dependencies = [ "gimli", ] @@ -136,9 +136,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.83" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25bdb32cbbdce2b519a9cd7df3a678443100e265d5e25ca763b7572a5104f5f3" +checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" [[package]] name = "aquatic_peer_id" @@ -201,12 +201,11 @@ dependencies = [ [[package]] name = "async-channel" -version = "2.3.0" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f2776ead772134d55b62dd45e59a79e21612d85d0af729b8b7d3967d601a62a" +checksum = "89b47800b0be77592da0afd425cc03468052844aff33b84e33cc696f64e77b6a" dependencies = [ "concurrent-queue", - "event-listener 5.3.0", "event-listener-strategy 0.5.2", "futures-core", "pin-project-lite", @@ -214,9 +213,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.10" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c90a406b4495d129f00461241616194cb8a032c8d1c53c657f0961d5f8e0498" +checksum = "cd066d0b4ef8ecb03a55319dc13aa6910616d0f44008a045bb1835af830abff5" dependencies = [ "brotli", "flate2", @@ -230,9 +229,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b10202063978b3351199d68f8b22c4e47e4b1b822f8d43fd862d5ea8c006b29a" +checksum = "c8828ec6e544c02b0d6691d21ed9f9218d0384a82542855073c2a3f58304aaf0" dependencies = [ "async-task", "concurrent-queue", @@ -247,7 +246,7 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" dependencies = [ - "async-channel 2.3.0", + "async-channel 2.3.1", "async-executor", "async-io 2.3.2", "async-lock 3.3.0", @@ -357,7 +356,7 @@ checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -480,7 +479,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -508,9 +507,9 @@ dependencies = [ [[package]] name = "backtrace" -version = "0.3.71" +version = "0.3.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d" +checksum = "17c6a35df3749d2e8bb1b7b21a976d82b15548788d2735b9d82f329268f71a11" dependencies = [ "addr2line", "cc", @@ -567,7 +566,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -605,12 +604,11 @@ dependencies = [ [[package]] name = "blocking" -version = "1.6.0" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "495f7104e962b7356f0aeb34247aca1fe7d2e783b346582db7f2904cb5717e88" +checksum = "703f41c54fc768e63e091340b424302bb1c29ef4aa0c7f10fe849dfb114d29ea" dependencies = [ - "async-channel 2.3.0", - "async-lock 3.3.0", + "async-channel 2.3.1", "async-task", "futures-io", "futures-lite 2.3.0", @@ -637,7 +635,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", "syn_derive", ] @@ -654,9 +652,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "4.0.0" +version = "4.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6221fe77a248b9117d431ad93761222e1cf8ff282d9d1d5d9f53d6299a1cf76" +checksum = "9a45bd2e4095a8b518033b128020dd4a55aab1c0a381ba4404a472630f4bc362" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -716,9 +714,9 @@ checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" [[package]] name = "camino" -version = "1.1.6" +version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c59e92b5a388f549b863a7bea62612c09f24c8393560709a54558a9abdfb3b9c" +checksum = "e0ec6b951b160caa93cc0c7b209e5a3bff7aae9062213451ac99493cd844c239" dependencies = [ "serde", ] @@ -740,9 +738,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.97" +version = "1.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "099a5357d84c4c61eb35fc8eafa9a79a902c2f76911e5747ced4e032edd8d9b4" +checksum = "41c270e7540d725e65ac7f1b212ac8ce349719624d7bcff99f8e2e488e8cf03f" dependencies = [ "jobserver", "libc", @@ -812,9 +810,9 @@ dependencies = [ [[package]] name = "clang-sys" -version = "1.7.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67523a3b4be3ce1989d607a828d036249522dd9c1c8de7f4dd2dae43a37369d1" +checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" dependencies = [ "glob", "libc", @@ -840,7 +838,7 @@ dependencies = [ "anstream", "anstyle", "clap_lex", - "strsim 0.11.1", + "strsim", ] [[package]] @@ -852,7 +850,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -931,9 +929,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.4.0" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3855a8a784b474f333699ef2bbca9db2c4a1f6d9088a90a2d25b1eb53111eaa" +checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" dependencies = [ "cfg-if", ] @@ -991,9 +989,9 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.12" +version = "0.5.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab3db02a9c5b5121e1e42fbdb1aeb65f5e02624cc58c43f2884c6ccac0b82f95" +checksum = "33480d6946193aa8033910124896ca395333cae7e2d1113d1fef6c3272217df2" dependencies = [ "crossbeam-utils", ] @@ -1038,9 +1036,9 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.19" +version = "0.8.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345" +checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" [[package]] name = "crunchy" @@ -1060,9 +1058,9 @@ dependencies = [ [[package]] name = "darling" -version = "0.20.8" +version = "0.20.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54e36fcd13ed84ffdfda6f5be89b31287cbb80c439841fe69e04841435464391" +checksum = "83b2eb4d90d12bdda5ed17de686c2acb4c57914f8f921b8da7e112b5a36f3fe1" dependencies = [ "darling_core", "darling_macro", @@ -1070,27 +1068,27 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.20.8" +version = "0.20.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c2cf1c23a687a1feeb728783b993c4e1ad83d99f351801977dd809b48d0a70f" +checksum = "622687fe0bac72a04e5599029151f5796111b90f1baaa9b544d807a5e31cd120" dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", - "strsim 0.10.0", - "syn 2.0.63", + "strsim", + "syn 2.0.66", ] [[package]] name = "darling_macro" -version = "0.20.8" +version = "0.20.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" +checksum = "733cabb43482b1a1b53eee8583c2b9e8684d592215ea83efd305dd31bc2f0178" dependencies = [ "darling_core", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -1137,7 +1135,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -1158,9 +1156,9 @@ checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" [[package]] name = "either" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a47c1c47d2f5964e29c61246e81db715514cd532db6b5116a25ea3c03d6780a2" +checksum = "3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385b58b" [[package]] name = "encoding_rs" @@ -1226,9 +1224,9 @@ dependencies = [ [[package]] name = "event-listener" -version = "5.3.0" +version = "5.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d9944b8ca13534cdfb2800775f8dd4902ff3fc75a50101466decadfdf322a24" +checksum = "6032be9bd27023a771701cc49f9f053c751055f71efb2e0ae5c15809093675ba" dependencies = [ "concurrent-queue", "parking", @@ -1251,7 +1249,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" dependencies = [ - "event-listener 5.3.0", + "event-listener 5.3.1", "pin-project-lite", ] @@ -1293,9 +1291,9 @@ dependencies = [ [[package]] name = "figment" -version = "0.10.18" +version = "0.10.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d032832d74006f99547004d49410a4b4218e4c33382d56ca3ff89df74f86b953" +checksum = "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3" dependencies = [ "atomic", "parking_lot", @@ -1389,7 +1387,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -1401,7 +1399,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -1413,7 +1411,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -1506,7 +1504,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -1568,9 +1566,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.28.1" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" +checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" [[package]] name = "glob" @@ -1592,15 +1590,15 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "816ec7294445779408f36fe57bc5b7fc1cf59664059096c65f905c1c61f58069" +checksum = "fa82e28a107a8cc405f0839610bdc9b15f1e25ec7d696aa5cf173edbcb1486ab" dependencies = [ + "atomic-waker", "bytes", "fnv", "futures-core", "futures-sink", - "futures-util", "http", "indexmap 2.2.6", "slab", @@ -1770,9 +1768,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.3" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca38ef113da30126bbff9cd1705f9273e15d45498615d138b0c20279ac7a76aa" +checksum = "7b875924a60b96e5d7b9ae7b066540b1dd1cbd90d1828f54c92e02a283351c56" dependencies = [ "bytes", "futures-channel", @@ -1857,9 +1855,9 @@ checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" [[package]] name = "instant" -version = "0.1.12" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" dependencies = [ "cfg-if", ] @@ -2045,9 +2043,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.154" +version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "libloading" @@ -2072,9 +2070,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.16" +version = "1.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e143b5e666b2695d28f6bca6497720813f699c9602dd7f5cac91008b8ada7f9" +checksum = "c15da26e5af7e25c90b37a2d75cdbf940cf4a55316de9d84c679c9b8bfabf82e" dependencies = [ "cc", "pkg-config", @@ -2089,9 +2087,9 @@ checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" [[package]] name = "linux-raw-sys" -version = "0.4.13" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" +checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "local-ip-address" @@ -2159,9 +2157,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d811f3e15f28568be3407c8e7fdb6514c1cda3cb30683f15b6a1a1dc4ea14a7" +checksum = "87dfd01fe195c66b572b37921ad8803d010623c0aca821bea2302239d155cdae" dependencies = [ "adler", ] @@ -2201,7 +2199,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -2252,7 +2250,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", "termcolor", "thiserror", ] @@ -2306,11 +2304,10 @@ dependencies = [ [[package]] name = "native-tls" -version = "0.2.11" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" +checksum = "a8614eb2c83d59d1c8cc974dd3f920198647674a0a035e1af1fa58707e317466" dependencies = [ - "lazy_static", "libc", "log", "openssl", @@ -2409,9 +2406,9 @@ dependencies = [ [[package]] name = "object" -version = "0.32.2" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441" +checksum = "b8ec7ab813848ba4522158d5517a6093db1ded27575b070f4177b8d12b41db5e" dependencies = [ "memchr", ] @@ -2451,7 +2448,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -2480,9 +2477,9 @@ checksum = "bb813b8af86854136c6922af0598d719255ecb2179515e6e7730d468f05c9cae" [[package]] name = "parking_lot" -version = "0.12.2" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e4af0ca4f6caed20e900d564c242b8e5d4903fdacf31d3daf527b66fe6f42fb" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" dependencies = [ "lock_api", "parking_lot_core", @@ -2521,7 +2518,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -2595,7 +2592,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -2629,9 +2626,9 @@ checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" [[package]] name = "plotters" -version = "0.3.5" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2c224ba00d7cadd4d5c660deaf2098e5e80e07846537c51f9cfa4be50c1fd45" +checksum = "a15b6eccb8484002195a3e44fe65a4ce8e93a625797a063735536fd59cb01cf3" dependencies = [ "num-traits", "plotters-backend", @@ -2642,15 +2639,15 @@ dependencies = [ [[package]] name = "plotters-backend" -version = "0.3.5" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e76628b4d3a7581389a35d5b6e2139607ad7c75b17aed325f210aa91f4a9609" +checksum = "414cec62c6634ae900ea1c56128dfe87cf63e7caece0852ec76aba307cebadb7" [[package]] name = "plotters-svg" -version = "0.3.5" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38f6d39893cca0701371e3c27294f09797214b86f1fb951b89ade8ec04e2abab" +checksum = "81b30686a7d9c3e010b84284bdd26a29f2138574f52f5eb6f794fc0ad924e705" dependencies = [ "plotters-backend", ] @@ -2769,9 +2766,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.82" +version = "1.0.84" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ad3d49ab951a01fbaafe34f2ec74122942fe18a3f9814c3268f1bb72042131b" +checksum = "ec96c6a92621310b51366f1e28d05ef11489516e93be030060e5fc12024a49d6" dependencies = [ "unicode-ident", ] @@ -2784,7 +2781,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", "version_check", "yansi", ] @@ -3029,9 +3026,9 @@ dependencies = [ [[package]] name = "ringbuf" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2542bc32f4c763f52a2eb375cb0b76c5aa5771f569af74299e84dca51d988a2f" +checksum = "5c65e4c865bc3d2e3294493dff0acf7e6c259d066e34e22059fa9c39645c3636" dependencies = [ "crossbeam-utils", ] @@ -3067,9 +3064,9 @@ dependencies = [ [[package]] name = "rstest" -version = "0.19.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d5316d2a1479eeef1ea21e7f9ddc67c191d497abc8fc3ba2467857abbb68330" +checksum = "27059f51958c5f8496a6f79511e7c0ac396dd815dc8894e9b6e2efb5779cf6f0" dependencies = [ "futures", "futures-timer", @@ -3079,18 +3076,19 @@ dependencies = [ [[package]] name = "rstest_macros" -version = "0.19.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04a9df72cc1f67020b0d63ad9bfe4a323e459ea7eb68e03bd9824db49f9a4c25" +checksum = "e6132d64df104c0b3ea7a6ad7766a43f587bd773a4a9cf4cd59296d426afaf3a" dependencies = [ "cfg-if", "glob", + "proc-macro-crate 3.1.0", "proc-macro2", "quote", "regex", "relative-path", "rustc_version", - "syn 2.0.63", + "syn 2.0.66", "unicode-ident", ] @@ -3168,7 +3166,7 @@ dependencies = [ "bitflags 2.5.0", "errno", "libc", - "linux-raw-sys 0.4.13", + "linux-raw-sys 0.4.14", "windows-sys 0.52.0", ] @@ -3212,9 +3210,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.16" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "092474d1a01ea8278f69e6a358998405fae5b8b963ddaeb2b0b04a128bf1dfb0" +checksum = "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6" [[package]] name = "ryu" @@ -3308,9 +3306,9 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" -version = "1.0.201" +version = "1.0.203" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "780f1cebed1629e4753a1a38a3c72d30b97ec044f0aef68cb26650a3c5cf363c" +checksum = "7253ab4de971e72fb7be983802300c30b5a7f0c2e56fab8abfc6a214307c0094" dependencies = [ "serde_derive", ] @@ -3336,13 +3334,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.201" +version = "1.0.203" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e405930b9796f1c00bee880d03fc7e0bb4b9a11afc776885ffe84320da2865" +checksum = "500cbc0ebeb6f46627f50f3f5811ccf6bf00643be300b4c3eabc0ef55dc5b5ba" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -3388,14 +3386,14 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] name = "serde_spanned" -version = "0.6.5" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb3622f419d1296904700073ea6cc23ad690adbd66f13ea683df73298736f0c1" +checksum = "79e674e01f999af37c49f70a6ede167a8a60b2503e56c5599532a65baa5969a0" dependencies = [ "serde", ] @@ -3439,7 +3437,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -3538,12 +3536,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - [[package]] name = "strsim" version = "0.11.1" @@ -3573,9 +3565,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.63" +version = "2.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf5be731623ca1a1fb7d8be6f261a3be6d3e2337b8a1f97be944d020c8fcb704" +checksum = "c42f3f41a2de00b01c0aaad383c5a45241efc8b2d1eda5661812fda5f3cdcff5" dependencies = [ "proc-macro2", "quote", @@ -3591,7 +3583,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -3679,22 +3671,22 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.60" +version = "1.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "579e9083ca58dd9dcf91a9923bb9054071b9ebbd800b342194c9feb0ee89fc18" +checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.60" +version = "1.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2470041c06ec3ac1ab38d0356a6119054dedaea53e12fbefc0de730a1c08524" +checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -3755,9 +3747,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.37.0" +version = "1.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1adbebffeca75fcfd058afa480fb6c0b81e165a0323f9c9d39c9697e37c46787" +checksum = "ba4f4a02a7a80d6f274636f0aa95c7e383b912d41fe721a31f29e29698585a4a" dependencies = [ "backtrace", "bytes", @@ -3773,13 +3765,13 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" +checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -3817,21 +3809,21 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.12" +version = "0.8.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9dd1545e8208b4a5af1aa9bbd0b4cf7e9ea08fabc5d0a5c67fcaafa17433aa3" +checksum = "a4e43f8cc456c9704c851ae29c67e17ef65d2c30017c17a9765b89c382dc8bba" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.12", + "toml_edit 0.22.13", ] [[package]] name = "toml_datetime" -version = "0.6.5" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" +checksum = "4badfd56924ae69bcc9039335b2e017639ce3f9b001c393c1b2d1ef846ce2cbf" dependencies = [ "serde", ] @@ -3860,15 +3852,15 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.12" +version = "0.22.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3328d4f68a705b2a4498da1d580585d39a6510f98318a2cec3018a7ec61ddef" +checksum = "c127785850e8c20836d49732ae6abfa47616e60bf9d9f57c43c250361a9db96c" dependencies = [ "indexmap 2.2.6", "serde", "serde_spanned", "toml_datetime", - "winnow 0.6.8", + "winnow 0.6.9", ] [[package]] @@ -4093,7 +4085,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] @@ -4261,7 +4253,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", "wasm-bindgen-shared", ] @@ -4295,7 +4287,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4506,9 +4498,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.6.8" +version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3c52e9c97a68071b23e836c9380edae937f17b9c4667bd021973efc689f618d" +checksum = "86c949fede1d13936a99f14fafd3e76fd642b556dd2ce96287fbe2e0151bfac6" dependencies = [ "memchr", ] @@ -4556,7 +4548,7 @@ checksum = "15e934569e47891f7d9411f1a451d947a60e000ab3bd24fbb970f000387d1b3b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.63", + "syn 2.0.66", ] [[package]] From a3df726c9108f658274ac2d2870b3767b0398401 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 31 May 2024 09:50:57 +0100 Subject: [PATCH 0355/1297] fix: clippy errors --- cSpell.json | 1 + packages/clock/src/lib.rs | 6 +- packages/test-helpers/src/configuration.rs | 6 +- src/bootstrap/jobs/http_tracker.rs | 2 +- src/bootstrap/jobs/tracker_apis.rs | 8 +- src/bootstrap/jobs/udp_tracker.rs | 4 +- src/console/clients/udp/checker.rs | 2 +- src/console/profiling.rs | 8 +- src/core/databases/mod.rs | 4 +- src/core/mod.rs | 8 +- src/core/torrent/mod.rs | 6 +- src/lib.rs | 6 +- src/servers/apis/mod.rs | 22 ++-- .../apis/v1/context/auth_key/handlers.rs | 2 +- src/servers/apis/v1/context/auth_key/mod.rs | 10 +- .../v1/context/torrent/resources/torrent.rs | 4 +- .../apis/v1/context/whitelist/handlers.rs | 4 +- src/servers/apis/v1/context/whitelist/mod.rs | 8 +- src/servers/apis/v1/mod.rs | 2 +- src/servers/http/mod.rs | 54 ++++----- src/servers/http/server.rs | 6 +- .../http/v1/extractors/authentication_key.rs | 6 +- src/servers/http/v1/requests/announce.rs | 8 +- src/servers/http/v1/responses/error.rs | 4 +- src/servers/http/v1/routes.rs | 2 +- src/servers/http/v1/services/announce.rs | 4 +- src/servers/http/v1/services/scrape.rs | 4 +- src/servers/udp/connection_cookie.rs | 10 +- src/servers/udp/handlers.rs | 3 +- src/servers/udp/mod.rs | 108 +++++++++--------- src/servers/udp/peer_builder.rs | 3 +- src/servers/udp/server.rs | 10 +- 32 files changed, 165 insertions(+), 170 deletions(-) diff --git a/cSpell.json b/cSpell.json index 2b5cf55bf..ef807f035 100644 --- a/cSpell.json +++ b/cSpell.json @@ -64,6 +64,7 @@ "Hydranode", "hyperthread", "Icelake", + "iiiiiiiiiiiiiiiiiiiid", "imdl", "impls", "incompletei", diff --git a/packages/clock/src/lib.rs b/packages/clock/src/lib.rs index 9fc67cb54..295d22c16 100644 --- a/packages/clock/src/lib.rs +++ b/packages/clock/src/lib.rs @@ -17,11 +17,11 @@ //! ``` //! //! > **NOTICE**: internally the `Duration` is stores it's main unit as seconds in a `u64` and it will -//! overflow in 584.9 billion years. +//! > overflow in 584.9 billion years. //! //! > **NOTICE**: the timestamp does not depend on the time zone. That gives you -//! the ability to use the clock regardless of the underlying system time zone -//! configuration. See [Unix time Wikipedia entry](https://en.wikipedia.org/wiki/Unix_time). +//! > the ability to use the clock regardless of the underlying system time zone +//! > configuration. See [Unix time Wikipedia entry](https://en.wikipedia.org/wiki/Unix_time). pub mod clock; pub mod conv; diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 86ed57b9e..15ecd5280 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -13,11 +13,11 @@ use crate::random; /// > **NOTICE**: This configuration is not meant to be used in production. /// /// > **NOTICE**: Port 0 is used for ephemeral ports, which means that the OS -/// will assign a random free port for the tracker to use. +/// > will assign a random free port for the tracker to use. /// /// > **NOTICE**: You can change the log level to `debug` to see the logs of the -/// tracker while running the tests. That can be particularly useful when -/// debugging tests. +/// > tracker while running the tests. That can be particularly useful when +/// > debugging tests. /// /// # Panics /// diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index d8a976b98..9ae8995fc 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -3,7 +3,7 @@ //! The function [`http_tracker::start_job`](crate::bootstrap::jobs::http_tracker::start_job) starts a new HTTP tracker server. //! //! > **NOTICE**: the application can launch more than one HTTP tracker on different ports. -//! Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) for the configuration options. +//! > Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) for the configuration options. //! //! The [`http_tracker::start_job`](crate::bootstrap::jobs::http_tracker::start_job) function spawns a new asynchronous task, //! that tasks is the "**launcher**". The "**launcher**" starts the actual server and sends a message back to the main application. diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 120c960ef..834574edb 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -4,8 +4,8 @@ //! function starts a the HTTP tracker REST API. //! //! > **NOTICE**: that even thought there is only one job the API has different -//! versions. API consumers can choose which version to use. The API version is -//! part of the URL, for example: `http://localhost:1212/api/v1/stats`. +//! > versions. API consumers can choose which version to use. The API version is +//! > part of the URL, for example: `http://localhost:1212/api/v1/stats`. //! //! The [`tracker_apis::start_job`](crate::bootstrap::jobs::tracker_apis::start_job) //! function spawns a new asynchronous task, that tasks is the "**launcher**". @@ -38,8 +38,8 @@ use crate::servers::registar::ServiceRegistrationForm; /// application process to notify the API server was successfully started. /// /// > **NOTICE**: it does not mean the API server is ready to receive requests. -/// It only means the new server started. It might take some time to the server -/// to be ready to accept request. +/// > It only means the new server started. It might take some time to the server +/// > to be ready to accept request. #[derive(Debug)] pub struct ApiServerJobStarted(); diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index bb1cdb492..853cb7461 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -4,8 +4,8 @@ //! function starts a new UDP tracker server. //! //! > **NOTICE**: that the application can launch more than one UDP tracker -//! on different ports. Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) -//! for the configuration options. +//! > on different ports. Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) +//! > for the configuration options. use std::sync::Arc; use log::debug; diff --git a/src/console/clients/udp/checker.rs b/src/console/clients/udp/checker.rs index d51492041..37928f0df 100644 --- a/src/console/clients/udp/checker.rs +++ b/src/console/clients/udp/checker.rs @@ -104,7 +104,7 @@ impl Client { /// /// - It can't connect to the remote UDP socket. /// - It can't make a connection request successfully to the remote UDP - /// server (after successfully connecting to the remote UDP socket). + /// server (after successfully connecting to the remote UDP socket). /// /// # Panics /// diff --git a/src/console/profiling.rs b/src/console/profiling.rs index 52e11913f..d77e55966 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -12,9 +12,9 @@ //! ``` //! //! > NOTICE: valgrind executes the program you wan to profile and waits until -//! it ends. Since the tracker is a service and does not end the profiling -//! binary accepts an arguments with the duration you want to run the tracker, -//! so that it terminates automatically after that period of time. +//! > it ends. Since the tracker is a service and does not end the profiling +//! > binary accepts an arguments with the duration you want to run the tracker, +//! > so that it terminates automatically after that period of time. //! //! # Run profiling //! @@ -81,7 +81,7 @@ //! ``` //! //! > NOTICE: We are using an specific tracker configuration for profiling that -//! removes all features except the UDP tracker and sets the logging level to `error`. +//! > removes all features except the UDP tracker and sets the logging level to `error`. //! //! Build the aquatic UDP load test command: //! diff --git a/src/core/databases/mod.rs b/src/core/databases/mod.rs index c08aed76a..e3fb9ad60 100644 --- a/src/core/databases/mod.rs +++ b/src/core/databases/mod.rs @@ -8,7 +8,7 @@ //! - [`Sqlite`](crate::core::databases::sqlite::Sqlite) //! //! > **NOTICE**: There are no database migrations. If there are any changes, -//! we will implemented them or provide a script to migrate to the new schema. +//! > we will implemented them or provide a script to migrate to the new schema. //! //! The persistent objects are: //! @@ -25,7 +25,7 @@ //! `completed` | 20 | The number of peers that have ever completed downloading the torrent associated to this entry. See [`Entry`](torrust_tracker_torrent_repository::entry::Entry) for more information. //! //! > **NOTICE**: The peer list for a torrent is not persisted. Since peer have to re-announce themselves on intervals, the data is be -//! regenerated again after some minutes. +//! > regenerated again after some minutes. //! //! # Torrent whitelist //! diff --git a/src/core/mod.rs b/src/core/mod.rs index 2b61e3031..e81ad2a94 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -219,7 +219,7 @@ //! The torrent entry has two attributes: //! //! - `completed`: which is hte number of peers that have completed downloading the torrent file/s. As they have completed downloading, -//! they have a full version of the torrent data, and they can provide the full data to other peers. That's why they are also known as "seeders". +//! they have a full version of the torrent data, and they can provide the full data to other peers. That's why they are also known as "seeders". //! - `peers`: an indexed and orderer list of peer for the torrent. Each peer contains the data received from the peer in the `announce` request. //! //! The [`torrent`] module not only contains the original data obtained from peer via `announce` requests, it also contains @@ -401,7 +401,7 @@ //! - `scrapes_handled`: number of `scrape` handled requests by the tracker //! //! > **NOTICE**: as the HTTP tracker does not have an specific `connection` request like the UDP tracker, `connections_handled` are -//! increased on every `announce` and `scrape` requests. +//! > increased on every `announce` and `scrape` requests. //! //! The tracker exposes an event sender API that allows the tracker users to send events. When a higher application service handles a //! `connection` , `announce` or `scrape` requests, it notifies the `Tracker` by sending statistics events. @@ -467,8 +467,8 @@ use crate::CurrentClock; /// authentication and other services. /// /// > **NOTICE**: the `Tracker` is not responsible for handling the network layer. -/// Typically, the `Tracker` is used by a higher application service that handles -/// the network layer. +/// > Typically, the `Tracker` is used by a higher application service that handles +/// > the network layer. pub struct Tracker { announce_policy: AnnouncePolicy, /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index 286a7e047..38311864b 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -20,10 +20,10 @@ //! //! - The number of peers that have completed downloading the torrent since the tracker started collecting metrics. //! - The number of peers that have completed downloading the torrent and are still active, that means they are actively participating in the network, -//! by announcing themselves periodically to the tracker. Since they have completed downloading they have a full copy of the torrent data. Peers with a -//! full copy of the data are called "seeders". +//! by announcing themselves periodically to the tracker. Since they have completed downloading they have a full copy of the torrent data. Peers with a +//! full copy of the data are called "seeders". //! - The number of peers that have NOT completed downloading the torrent and are still active, that means they are actively participating in the network. -//! Peer that don not have a full copy of the torrent data are called "leechers". +//! Peer that don not have a full copy of the torrent data are called "leechers". //! use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; diff --git a/src/lib.rs b/src/lib.rs index 6fd5da15f..39d0b5b3d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -103,8 +103,8 @@ //! ``` //! //! > **NOTICE**: those are the commands for `Ubuntu`. If you are using a -//! different OS, you will need to install the equivalent packages. Please -//! refer to the documentation of your OS. +//! > different OS, you will need to install the equivalent packages. Please +//! > refer to the documentation of your OS. //! //! With the default configuration you will need to create the `storage` directory: //! @@ -231,7 +231,7 @@ //! will use `./share/default/config/tracker.development.sqlite3.toml`. //! //! > IMPORTANT: Every time you change the configuration you need to restart the -//! service. +//! > service. //! //! # Usage //! diff --git a/src/servers/apis/mod.rs b/src/servers/apis/mod.rs index ef37026fe..47d40c654 100644 --- a/src/servers/apis/mod.rs +++ b/src/servers/apis/mod.rs @@ -1,7 +1,7 @@ //! The tracker REST API with all its versions. //! //! > **NOTICE**: This API should not be exposed directly to the internet, it is -//! intended for internal use only. +//! > intended for internal use only. //! //! Endpoints for the latest API: [v1]. //! @@ -124,16 +124,16 @@ //! ``` //! //! > **NOTICE**: If you are using a reverse proxy like NGINX, you can skip this -//! step and use NGINX for the SSL instead. See -//! [other alternatives to Nginx/certbot](https://github.com/torrust/torrust-tracker/discussions/131) +//! > step and use NGINX for the SSL instead. See +//! > [other alternatives to Nginx/certbot](https://github.com/torrust/torrust-tracker/discussions/131) //! //! > **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::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. +//! > 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::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. //! //! # Versioning //! @@ -153,8 +153,8 @@ //! If you want to contribute to this documentation you can [open a new pull request](https://github.com/torrust/torrust-tracker/pulls). //! //! > **NOTICE**: we are using [curl](https://curl.se/) in the API examples. -//! And you have to use quotes around the URL in order to avoid unexpected -//! errors. For example: `curl "http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken"`. +//! > And you have to use quotes around the URL in order to avoid unexpected +//! > errors. For example: `curl "http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken"`. pub mod routes; pub mod server; pub mod v1; diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index a6c8bf812..792d9507e 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -46,7 +46,7 @@ pub async fn generate_auth_key_handler(State(tracker): State>, Path /// /// - `POST /api/v1/key/120`. It will generate a new key valid for two minutes. /// - `DELETE /api/v1/key/xqD6NWH9TcKrOCwDmqcdH5hF5RrbL0A6`. It will delete the -/// key `xqD6NWH9TcKrOCwDmqcdH5hF5RrbL0A6`. +/// key `xqD6NWH9TcKrOCwDmqcdH5hF5RrbL0A6`. /// /// > **NOTICE**: this may change in the future, in the [API v2](https://github.com/torrust/torrust-tracker/issues/144). #[derive(Deserialize)] diff --git a/src/servers/apis/v1/context/auth_key/mod.rs b/src/servers/apis/v1/context/auth_key/mod.rs index 11bc8a43f..330249b58 100644 --- a/src/servers/apis/v1/context/auth_key/mod.rs +++ b/src/servers/apis/v1/context/auth_key/mod.rs @@ -51,9 +51,9 @@ //! ``` //! //! > **NOTICE**: `valid_until` and `expiry_time` represent the same time. -//! `valid_until` is the number of seconds since the Unix epoch -//! ([timestamp](https://en.wikipedia.org/wiki/Timestamp)), while `expiry_time` -//! is the human-readable time ([ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html)). +//! > `valid_until` is the number of seconds since the Unix epoch +//! > ([timestamp](https://en.wikipedia.org/wiki/Timestamp)), while `expiry_time` +//! > is the human-readable time ([ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html)). //! //! **Resource** //! @@ -96,8 +96,8 @@ //! ``` //! //! > **NOTICE**: a `500` status code will be returned and the body is not a -//! valid JSON. It's a text body containing the serialized-to-display error -//! message. +//! > valid JSON. It's a text body containing the serialized-to-display error +//! > message. //! //! # Reload authentication keys //! diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs index 2f1ace5c9..0d65b3eb6 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs @@ -2,8 +2,8 @@ //! //! - `Torrent` is the full torrent resource. //! - `ListItem` is a list item resource on a torrent list. `ListItem` does -//! include a `peers` field but it is always `None` in the struct and `null` in -//! the JSON response. +//! include a `peers` field but it is always `None` in the struct and `null` in +//! the JSON response. use serde::{Deserialize, Serialize}; use crate::core::services::torrent::{BasicInfo, Info}; diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/src/servers/apis/v1/context/whitelist/handlers.rs index c88f8cc1d..32e434918 100644 --- a/src/servers/apis/v1/context/whitelist/handlers.rs +++ b/src/servers/apis/v1/context/whitelist/handlers.rs @@ -42,7 +42,7 @@ pub async fn add_torrent_to_whitelist_handler( /// /// - `200` response with a [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) in json. /// - `500` with serialized error in debug format if the torrent couldn't be -/// removed from the whitelisted. +/// removed from the whitelisted. /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#remove-a-torrent-from-the-whitelist) /// for more information about this endpoint. @@ -65,7 +65,7 @@ pub async fn remove_torrent_from_whitelist_handler( /// /// - `200` response with a [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) in json. /// - `500` with serialized error in debug format if the torrent whitelist -/// couldn't be reloaded from the database. +/// couldn't be reloaded from the database. /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#reload-the-whitelist) /// for more information about this endpoint. diff --git a/src/servers/apis/v1/context/whitelist/mod.rs b/src/servers/apis/v1/context/whitelist/mod.rs index 2bb35ef65..79da43fdc 100644 --- a/src/servers/apis/v1/context/whitelist/mod.rs +++ b/src/servers/apis/v1/context/whitelist/mod.rs @@ -11,12 +11,12 @@ //! torrents in the whitelist. The whitelist can be updated using the API. //! //! > **NOTICE**: the whitelist is only used when the tracker is configured to -//! in `listed` or `private_listed` modes. Refer to the -//! [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) -//! to know how to enable the those modes. +//! > in `listed` or `private_listed` modes. Refer to the +//! > [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) +//! > to know how to enable the those modes. //! //! > **NOTICE**: if the tracker is not running in `listed` or `private_listed` -//! modes the requests to the whitelist API will be ignored. +//! > modes the requests to the whitelist API will be ignored. //! //! # Endpoints //! diff --git a/src/servers/apis/v1/mod.rs b/src/servers/apis/v1/mod.rs index 213ee9335..372ae0ff9 100644 --- a/src/servers/apis/v1/mod.rs +++ b/src/servers/apis/v1/mod.rs @@ -12,7 +12,7 @@ //! > **NOTICE**: //! - The authentication keys are only used by the HTTP tracker. //! - The whitelist is only used when the tracker is running in `listed` or -//! `private_listed` mode. +//! `private_listed` mode. //! //! Refer to the [authentication middleware](crate::servers::apis::v1::middlewares::auth) //! for more information about the authentication process. diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index 3ef85e600..e50e3c351 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -39,7 +39,7 @@ //! **Query parameters** //! //! > **NOTICE**: you can click on the parameter name to see a full description -//! after extracting and parsing the parameter from the URL query component. +//! > after extracting and parsing the parameter from the URL query component. //! //! Parameter | Type | Description | Required | Default | Example //! ---|---|---|---|---|--- @@ -58,40 +58,40 @@ //! request for more information about the parameters. //! //! > **NOTICE**: the [BEP 03](https://www.bittorrent.org/beps/bep_0003.html) -//! defines only the `ip` and `event` parameters as optional. However, the -//! tracker assigns default values to the optional parameters if they are not -//! provided. +//! > defines only the `ip` and `event` parameters as optional. However, the +//! > tracker assigns default values to the optional parameters if they are not +//! > provided. //! //! > **NOTICE**: the `peer_addr` parameter is not part of the original -//! specification. But the peer IP was added in the -//! [UDP Tracker protocol](https://www.bittorrent.org/beps/bep_0015.html). It is -//! used to provide the peer's IP address to the tracker, but it is ignored by -//! the tracker. The tracker uses the IP address of the peer that sent the -//! request or the right-most-ip in the `X-Forwarded-For` header if the tracker -//! is behind a reverse proxy. +//! > specification. But the peer IP was added in the +//! > [UDP Tracker protocol](https://www.bittorrent.org/beps/bep_0015.html). It is +//! > used to provide the peer's IP address to the tracker, but it is ignored by +//! > the tracker. The tracker uses the IP address of the peer that sent the +//! > request or the right-most-ip in the `X-Forwarded-For` header if the tracker +//! > is behind a reverse proxy. //! //! > **NOTICE**: the maximum number of peers that the tracker can return is -//! `74`. Defined with a hardcoded const [`TORRENT_PEERS_LIMIT`](torrust_tracker_configuration::TORRENT_PEERS_LIMIT). -//! Refer to [issue 262](https://github.com/torrust/torrust-tracker/issues/262) -//! for more information about this limitation. +//! > `74`. Defined with a hardcoded const [`TORRENT_PEERS_LIMIT`](torrust_tracker_configuration::TORRENT_PEERS_LIMIT). +//! > Refer to [issue 262](https://github.com/torrust/torrust-tracker/issues/262) +//! > for more information about this limitation. //! //! > **NOTICE**: the `info_hash` parameter is NOT a `URL` encoded string param. -//! It is percent encode of the raw `info_hash` bytes (40 bytes). URL `GET` params -//! can contain any bytes, not only well-formed UTF-8. The `info_hash` is a -//! 20-byte SHA1. Check the [`percent_encoding`] -//! module to know more about the encoding. +//! > It is percent encode of the raw `info_hash` bytes (40 bytes). URL `GET` params +//! > can contain any bytes, not only well-formed UTF-8. The `info_hash` is a +//! > 20-byte SHA1. Check the [`percent_encoding`] +//! > module to know more about the encoding. //! //! > **NOTICE**: the `peer_id` parameter is NOT a `URL` encoded string param. -//! It is percent encode of the raw peer ID bytes (20 bytes). URL `GET` params -//! can contain any bytes, not only well-formed UTF-8. The `info_hash` is a -//! 20-byte SHA1. Check the [`percent_encoding`] -//! module to know more about the encoding. +//! > It is percent encode of the raw peer ID bytes (20 bytes). URL `GET` params +//! > can contain any bytes, not only well-formed UTF-8. The `info_hash` is a +//! > 20-byte SHA1. Check the [`percent_encoding`] +//! > module to know more about the encoding. //! //! > **NOTICE**: by default, the tracker returns the non-compact peer list when -//! no `compact` parameter is provided or is empty. The -//! [BEP 23](https://www.bittorrent.org/beps/bep_0023.html) suggests to do the -//! opposite. The tracker should return the compact peer list by default and -//! return the non-compact peer list if the `compact` parameter is `0`. +//! > no `compact` parameter is provided or is empty. The +//! > [BEP 23](https://www.bittorrent.org/beps/bep_0023.html) suggests to do the +//! > opposite. The tracker should return the compact peer list by default and +//! > return the non-compact peer list if the `compact` parameter is `0`. //! //! **Sample announce URL** //! @@ -223,7 +223,7 @@ //! [`info_hash`](crate::servers::http::v1::requests::scrape::Scrape::info_hashes) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` //! //! > **NOTICE**: you can scrape multiple torrents at the same time by passing -//! multiple `info_hash` parameters. +//! > multiple `info_hash` parameters. //! //! Refer to the [`Scrape`](crate::servers::http::v1::requests::scrape::Scrape) //! request for more information about the parameters. @@ -238,7 +238,7 @@ //! `info_hash` parameters: `info_hash=%81%00%0...00%00%00&info_hash=%82%00%0...00%00%00` //! //! > **NOTICE**: the maximum number of torrents you can scrape at the same time -//! is `74`. Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS). +//! > is `74`. Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS). //! //! **Sample response** //! diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index a68f7d16c..33e20a84e 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -27,7 +27,7 @@ use crate::servers::signals::{graceful_shutdown, Halted}; /// /// - The channel to send the shutdown signal to the server is closed. /// - The task to shutdown the server on the spawned server failed to execute to -/// completion. +/// completion. #[derive(Debug)] pub enum Error { Error(String), @@ -107,8 +107,8 @@ pub type RunningHttpServer = HttpServer; /// server but always keeping the same configuration. /// /// > **NOTICE**: if the configurations changes after running the server it will -/// reset to the initial value after stopping the server. This struct is not -/// intended to persist configurations between runs. +/// > reset to the initial value after stopping the server. This struct is not +/// > intended to persist configurations between runs. #[allow(clippy::module_name_repetitions)] pub struct HttpServer { /// The state of the server: `running` or `stopped`. diff --git a/src/servers/http/v1/extractors/authentication_key.rs b/src/servers/http/v1/extractors/authentication_key.rs index b8d3e7d50..985e32371 100644 --- a/src/servers/http/v1/extractors/authentication_key.rs +++ b/src/servers/http/v1/extractors/authentication_key.rs @@ -39,9 +39,9 @@ //! ``` //! //! > **NOTICE**: the returned HTTP status code is always `200` for authentication errors. -//! Neither [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -//! nor [The Private Torrents](https://www.bittorrent.org/beps/bep_0027.html) -//! specifications specify any HTTP status code for authentication errors. +//! > Neither [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) +//! > nor [The Private Torrents](https://www.bittorrent.org/beps/bep_0027.html) +//! > specifications specify any HTTP status code for authentication errors. use std::panic::Location; use axum::async_trait; diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index 39a6c1846..83cc7ddf9 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -51,12 +51,12 @@ const COMPACT: &str = "compact"; /// ``` /// /// > **NOTICE**: The [BEP 03. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -/// specifies that only the peer `IP` and `event`are optional. However, the -/// tracker defines default values for some of the mandatory params. +/// > specifies that only the peer `IP` and `event`are optional. However, the +/// > tracker defines default values for some of the mandatory params. /// /// > **NOTICE**: The struct does not contain the `IP` of the peer. It's not -/// mandatory and it's not used by the tracker. The `IP` is obtained from the -/// request itself. +/// > mandatory and it's not used by the tracker. The `IP` is obtained from the +/// > request itself. #[derive(Debug, PartialEq)] pub struct Announce { // Mandatory params diff --git a/src/servers/http/v1/responses/error.rs b/src/servers/http/v1/responses/error.rs index 1cc31ad4e..c406c797a 100644 --- a/src/servers/http/v1/responses/error.rs +++ b/src/servers/http/v1/responses/error.rs @@ -9,8 +9,8 @@ //! why the query failed, and no other keys are required."_ //! //! > **NOTICE**: error responses are bencoded and always have a `200 OK` status -//! code. The official `BitTorrent` specification does not specify the status -//! code. +//! > code. The official `BitTorrent` specification does not specify the status +//! > code. use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use serde::Serialize; diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index c54da51a3..14641dc1d 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -26,7 +26,7 @@ const TIMEOUT: Duration = Duration::from_secs(5); /// It adds the routes to the router. /// /// > **NOTICE**: it's added a layer to get the client IP from the connection -/// info. The tracker could use the connection info to get the client IP. +/// > info. The tracker could use the connection info to get the client IP. #[allow(clippy::needless_pass_by_value)] pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { Router::new() diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index e3bef3973..253140fbc 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -24,8 +24,8 @@ use crate::core::{statistics, AnnounceData, Tracker}; /// - The number of TCP `announce` requests handled by the HTTP tracker. /// /// > **NOTICE**: as the HTTP tracker does not requires a connection request -/// like the UDP tracker, the number of TCP connections is incremented for -/// each `announce` request. +/// > like the UDP tracker, the number of TCP connections is incremented for +/// > each `announce` request. pub async fn invoke(tracker: Arc, info_hash: InfoHash, peer: &mut peer::Peer) -> AnnounceData { let original_peer_ip = peer.peer_addr.ip(); diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index a6a40186f..bf9fbd933 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -23,8 +23,8 @@ use crate::core::{statistics, ScrapeData, Tracker}; /// - The number of TCP `scrape` requests handled by the HTTP tracker. /// /// > **NOTICE**: as the HTTP tracker does not requires a connection request -/// like the UDP tracker, the number of TCP connections is incremented for -/// each `scrape` request. +/// > like the UDP tracker, the number of TCP connections is incremented for +/// > each `scrape` request. pub async fn invoke(tracker: &Arc, info_hashes: &Vec, original_peer_ip: &IpAddr) -> ScrapeData { let scrape_data = tracker.scrape(info_hashes).await; diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs index af3a28702..c15ad114c 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/servers/udp/connection_cookie.rs @@ -46,10 +46,10 @@ //! Peer C connects at timestamp 180 slot 1 -> connection ID will be valid from timestamp 180 to 360 //! ``` //! > **NOTICE**: connection ID is always the same for a given peer -//! (socket address) and time slot. +//! > (socket address) and time slot. //! //! > **NOTICE**: connection ID will be valid for two time extents, **not two -//! minutes**. It'll be valid for the the current time extent and the next one. +//! > minutes**. It'll be valid for the the current time extent and the next one. //! //! Refer to [`Connect`](crate::servers::udp#connect) for more information about //! the connection process. @@ -62,10 +62,8 @@ //! //! ## Disadvantages //! -//! - It's not very flexible. The connection ID is only valid for a certain -//! amount of time. -//! - It's not very accurate. The connection ID is valid for more than two -//! minutes. +//! - It's not very flexible. The connection ID is only valid for a certain amount of time. +//! - It's not very accurate. The connection ID is valid for more than two minutes. use std::net::SocketAddr; use std::panic::Location; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index fee00a0bd..4064cf041 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -31,8 +31,7 @@ use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; /// It's responsible for: /// /// - Parsing the incoming packet. -/// - Delegating the request to the correct handler depending on the request -/// type. +/// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc, socket: Arc) -> Response { diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index fa4e8e926..3062a4393 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -5,7 +5,7 @@ //! The UDP tracker is a simple UDP server that responds to these requests: //! //! - `Connect`: used to get a connection ID which must be provided on each -//! request in order to avoid spoofing the source address of the UDP packets. +//! request in order to avoid spoofing the source address of the UDP packets. //! - `Announce`: used to announce the presence of a peer to the tracker. //! - `Scrape`: used to get information about a torrent. //! @@ -22,10 +22,10 @@ //! for more information about the UDP tracker protocol. //! //! > **NOTICE**: [BEP-41](https://www.bittorrent.org/beps/bep_0041.html) is not -//! implemented yet. +//! > implemented yet. //! //! > **NOTICE**: we are using the [`aquatic_udp_protocol`](https://crates.io/crates/aquatic_udp_protocol) -//! crate so requests and responses are handled by it. +//! > crate so requests and responses are handled by it. //! //! > **NOTICE**: all values are send in network byte order ([big endian](https://en.wikipedia.org/wiki/Endianness)). //! @@ -83,23 +83,23 @@ //! spoofing can be explained as follows: //! //! 1. No connection state: Unlike TCP, UDP is a connectionless protocol, -//! meaning that it does not establish a connection between two endpoints before -//! exchanging data. As a result, it is more susceptible to IP spoofing, where -//! an attacker sends packets with a forged source IP address, tricking the -//! receiver into believing that they are coming from a legitimate source. +//! meaning that it does not establish a connection between two endpoints before +//! exchanging data. As a result, it is more susceptible to IP spoofing, where +//! an attacker sends packets with a forged source IP address, tricking the +//! receiver into believing that they are coming from a legitimate source. //! //! 2. Mitigating IP spoofing: To mitigate IP spoofing in the UDP tracker -//! protocol, a connection ID is used. When a client wants to interact with a -//! tracker, it sends a "connect" request to the tracker, which, in turn, -//! responds with a unique connection ID. This connection ID must be included in -//! all subsequent requests from the client to the tracker. +//! protocol, a connection ID is used. When a client wants to interact with a +//! tracker, it sends a "connect" request to the tracker, which, in turn, +//! responds with a unique connection ID. This connection ID must be included in +//! all subsequent requests from the client to the tracker. //! //! 3. Validating requests: By requiring the connection ID, the tracker can -//! verify that the requests are coming from the same client that initially sent -//! the "connect" request. If an attacker attempts to spoof the client's IP -//! address, they would also need to know the valid connection ID to be accepted -//! by the tracker. This makes it significantly more challenging for an attacker -//! to spoof IP addresses and disrupt the P2P network. +//! verify that the requests are coming from the same client that initially sent +//! the "connect" request. If an attacker attempts to spoof the client's IP +//! address, they would also need to know the valid connection ID to be accepted +//! by the tracker. This makes it significantly more challenging for an attacker +//! to spoof IP addresses and disrupt the P2P network. //! //! There are different ways to generate a connection ID. The most common way is //! to generate a time bound secret. The secret is generated using a time based @@ -161,9 +161,9 @@ //! 8 | [`i32`](std::i64) | `connection_id` | Generated by the tracker to authenticate the client. | `0xC5_58_7C_09_08_48_D8_37` | `-4226491872051668937` //! //! > **NOTICE**: the `connection_id` is used when further information is -//! exchanged with the tracker, to identify the client. This `connection_id` can -//! be reused for multiple requests, but if it's cached for too long, it will -//! not be valid anymore. +//! > exchanged with the tracker, to identify the client. This `connection_id` can +//! > be reused for multiple requests, but if it's cached for too long, it will +//! > not be valid anymore. //! //! > **NOTICE**: `Hex` column is a signed 2's complement. //! @@ -243,41 +243,41 @@ //! circumstances might include: //! //! 1. Network Address Translation (NAT): In cases where a peer is behind a NAT, -//! the private IP address of the peer is not directly routable over the -//! internet. The NAT device translates the private IP address to a public one -//! when sending packets to the tracker. The public IP address is what the -//! tracker sees as the source IP of the incoming request. However, if the peer -//! provides its private IP address in the announce request, the tracker can use -//! this information to facilitate communication between peers in the same -//! private network. +//! the private IP address of the peer is not directly routable over the +//! internet. The NAT device translates the private IP address to a public one +//! when sending packets to the tracker. The public IP address is what the +//! tracker sees as the source IP of the incoming request. However, if the peer +//! provides its private IP address in the announce request, the tracker can use +//! this information to facilitate communication between peers in the same +//! private network. //! //! 2. Proxy or VPN usage: If a peer uses a proxy or VPN service to connect to -//! the tracker, the source IP address seen by the tracker will be the one -//! assigned by the proxy or VPN server. In this case, if the peer provides its -//! actual IP address in the announce request, the tracker can use it to -//! establish a direct connection with other peers, bypassing the proxy or VPN -//! server. This might improve performance or help in cases where some peers -//! cannot connect to the proxy or VPN server. +//! the tracker, the source IP address seen by the tracker will be the one +//! assigned by the proxy or VPN server. In this case, if the peer provides its +//! actual IP address in the announce request, the tracker can use it to +//! establish a direct connection with other peers, bypassing the proxy or VPN +//! server. This might improve performance or help in cases where some peers +//! cannot connect to the proxy or VPN server. //! //! 3. Tracker is behind a NAT, firewall, proxy, VPN, or load balancer: In cases -//! where the tracker is behind a NAT, firewall, proxy, VPN, or load balancer, -//! the source IP address of the incoming request will be the public IP address -//! of the NAT, firewall, proxy, VPN, or load balancer. If the peer provides its -//! private IP address in the announce request, the tracker can use this -//! information to establish a direct connection with the peer. +//! where the tracker is behind a NAT, firewall, proxy, VPN, or load balancer, +//! the source IP address of the incoming request will be the public IP address +//! of the NAT, firewall, proxy, VPN, or load balancer. If the peer provides its +//! private IP address in the announce request, the tracker can use this +//! information to establish a direct connection with the peer. //! //! It's important to note that using the provided IP address can pose security //! risks, as malicious peers might spoof their IP addresses in the announce //! request to perform various types of attacks. //! //! > **NOTICE**: The current tracker behavior is to ignore the IP address -//! provided by the peer, and use the source IP address of the incoming request, -//! when the tracker is not running behind a proxy, and to use the right-most IP -//! address in the `X-Forwarded-For` header when the tracker is running behind a -//! proxy. +//! > provided by the peer, and use the source IP address of the incoming request, +//! > when the tracker is not running behind a proxy, and to use the right-most IP +//! > address in the `X-Forwarded-For` header when the tracker is running behind a +//! > proxy. //! //! > **NOTICE**: The tracker also changes the peer IP address to the tracker -//! external IP when the peer is using a loopback IP address. +//! > external IP when the peer is using a loopback IP address. //! //! **Sample announce request (UDP packet)** //! @@ -317,11 +317,11 @@ //! 101 | N bytes | | | | //! //! > **NOTICE**: bytes after offset 98 are part of the [BEP-41. UDP Tracker Protocol Extensions](https://www.bittorrent.org/beps/bep_0041.html). -//! There are three options defined for byte 98: `0x0` (`EndOfOptions`), `0x1` (`NOP`) and `0x2` (`URLData`). +//! > There are three options defined for byte 98: `0x0` (`EndOfOptions`), `0x1` (`NOP`) and `0x2` (`URLData`). //! //! > **NOTICE**: `num_want` is being ignored by the tracker. Refer to -//! [issue 262](https://github.com/torrust/torrust-tracker/issues/262) for more -//! information. +//! > [issue 262](https://github.com/torrust/torrust-tracker/issues/262) for more +//! > information. //! //! **Announce request (parsed struct)** //! @@ -342,7 +342,7 @@ //! `port` | [`Port`](aquatic_udp_protocol::common::Port) | `17548` //! //! > **NOTICE**: the `peers_wanted` field is the `num_want` field in the UDP -//! packet. +//! > packet. //! //! We are using a wrapper struct for the aquatic [`AnnounceRequest`](aquatic_udp_protocol::request::AnnounceRequest) //! struct, because we have our internal [`InfoHash`](torrust_tracker_primitives::info_hash::InfoHash) @@ -374,7 +374,7 @@ //! > **NOTICE**: `Hex` column is a signed 2's complement. //! //! > **NOTICE**: `IP address` should always be set to 0 when the peer is using -//! `IPv6`. +//! > `IPv6`. //! //! **Sample announce response (UDP packet)** //! @@ -413,7 +413,7 @@ //! ``` //! //! > **NOTICE**: there are 6 bytes per peer (4 bytes for the `IPv4` address and -//! 2 bytes for the TCP port). +//! > 2 bytes for the TCP port). //! //! UDP packet fields (`IPv4` peer list): //! @@ -433,7 +433,7 @@ //! ``` //! //! > **NOTICE**: there are 18 bytes per peer (16 bytes for the `IPv6` address and -//! 2 bytes for the TCP port). +//! > 2 bytes for the TCP port). //! //! UDP packet fields (`IPv6` peer list): //! @@ -446,7 +446,7 @@ //! > **NOTICE**: `Hex` column is a signed 2's complement. //! //! > **NOTICE**: the peer list does not include the peer that sent the announce -//! request. +//! > request. //! //! **Announce response (struct)** //! @@ -478,10 +478,10 @@ //! - [incomplete](torrust_tracker_primitives::swarm_metadata::SwarmMetadata::incomplete) //! //! > **NOTICE**: up to about 74 torrents can be scraped at once. A full scrape -//! can't be done with this protocol. This is a limitation of the UDP protocol. -//! Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS). -//! Refer to [issue 262](https://github.com/torrust/torrust-tracker/issues/262) -//! for more information about this limitation. +//! > can't be done with this protocol. This is a limitation of the UDP protocol. +//! > Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS). +//! > Refer to [issue 262](https://github.com/torrust/torrust-tracker/issues/262) +//! > for more information about this limitation. //! //! #### Scrape Request //! diff --git a/src/servers/udp/peer_builder.rs b/src/servers/udp/peer_builder.rs index 104f42a73..e54a23443 100644 --- a/src/servers/udp/peer_builder.rs +++ b/src/servers/udp/peer_builder.rs @@ -14,8 +14,7 @@ use crate::CurrentClock; /// # Arguments /// /// * `announce_wrapper` - The announce request to extract the peer info from. -/// * `peer_ip` - The real IP address of the peer, not the one in the announce -/// request. +/// * `peer_ip` - The real IP address of the peer, not the one in the announce request. #[must_use] pub fn from_request(announce_wrapper: &AnnounceWrapper, peer_ip: &IpAddr) -> peer::Peer { let announce_event = match aquatic_udp_protocol::AnnounceEvent::from(announce_wrapper.announce_request.event) { diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index b02b9802d..be4c36d40 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -2,8 +2,7 @@ //! //! There are two main types in this module: //! -//! - [`UdpServer`]: a controller to -//! start and stop the server. +//! - [`UdpServer`]: a controller to start and stop the server. //! - [`Udp`]: the server launcher. //! //! The `UdpServer` is an state machine for a given configuration. This struct @@ -49,8 +48,7 @@ use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; /// /// Some errors triggered while stopping the server are: /// -/// - The [`UdpServer`] cannot send the -/// shutdown signal to the spawned UDP service thread. +/// - The [`UdpServer`] cannot send the shutdown signal to the spawned UDP service thread. #[derive(Debug)] pub enum Error { /// Any kind of error starting or stopping the server. @@ -78,8 +76,8 @@ pub type RunningUdpServer = UdpServer; /// server but always keeping the same configuration. /// /// > **NOTICE**: if the configurations changes after running the server it will -/// reset to the initial value after stopping the server. This struct is not -/// intended to persist configurations between runs. +/// > reset to the initial value after stopping the server. This struct is not +/// > intended to persist configurations between runs. #[allow(clippy::module_name_repetitions)] pub struct UdpServer { /// The state of the server: `running` or `stopped`. From 4de7793f79c4731e33e139fb26183747fac080fc Mon Sep 17 00:00:00 2001 From: Mario Date: Mon, 20 May 2024 17:22:03 +0200 Subject: [PATCH 0356/1297] feat: [#670] new JSON serialization for connect and error aquatic responses --- src/console/clients/udp/app.rs | 15 ++++++++++--- src/console/clients/udp/responses.rs | 32 +++++++++++++++++++++++++++- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index f07044d09..9621cec52 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -60,7 +60,7 @@ use std::net::{SocketAddr, ToSocketAddrs}; use std::str::FromStr; use anyhow::Context; -use aquatic_udp_protocol::Response::{self, AnnounceIpv4, AnnounceIpv6, Scrape}; +use aquatic_udp_protocol::Response::{self, AnnounceIpv4, AnnounceIpv6, Connect, Error, Scrape}; use aquatic_udp_protocol::{Port, TransactionId}; use clap::{Parser, Subcommand}; use log::{debug, LevelFilter}; @@ -68,7 +68,7 @@ use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; use url::Url; use crate::console::clients::udp::checker; -use crate::console::clients::udp::responses::{AnnounceResponseDto, ScrapeResponseDto}; +use crate::console::clients::udp::responses::{AnnounceResponseDto, ConnectResponseDto, ErrorResponseDto, ScrapeResponseDto}; const ASSIGNED_BY_OS: u16 = 0; const RANDOM_TRANSACTION_ID: i32 = -888_840_697; @@ -171,6 +171,11 @@ async fn handle_scrape(tracker_socket_addr: &SocketAddr, info_hashes: &[TorrustI fn print_response(response: Response) -> anyhow::Result<()> { match response { + Connect(response) => { + let pretty_json = serde_json::to_string_pretty(&ConnectResponseDto::from(response)) + .context("connect response JSON serialization")?; + println!("{pretty_json}"); + } AnnounceIpv4(response) => { let pretty_json = serde_json::to_string_pretty(&AnnounceResponseDto::from(response)) .context("announce IPv4 response JSON serialization")?; @@ -186,7 +191,11 @@ fn print_response(response: Response) -> anyhow::Result<()> { serde_json::to_string_pretty(&ScrapeResponseDto::from(response)).context("scrape response JSON serialization")?; println!("{pretty_json}"); } - _ => println!("{response:#?}"), // todo: serialize to JSON all aquatic responses. + Error(response) => { + let pretty_json = + serde_json::to_string_pretty(&ErrorResponseDto::from(response)).context("error response JSON serialization")?; + println!("{pretty_json}"); + } }; Ok(()) diff --git a/src/console/clients/udp/responses.rs b/src/console/clients/udp/responses.rs index 8ea1a978b..eb6b386fd 100644 --- a/src/console/clients/udp/responses.rs +++ b/src/console/clients/udp/responses.rs @@ -1,9 +1,24 @@ //! Aquatic responses are not serializable. These are the serializable wrappers. use std::net::{Ipv4Addr, Ipv6Addr}; -use aquatic_udp_protocol::{AnnounceResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse}; +use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse}; use serde::Serialize; +#[derive(Serialize)] +pub struct ConnectResponseDto { + transaction_id: i32, + connection_id: i64, +} + +impl From for ConnectResponseDto { + fn from(connect: ConnectResponse) -> Self { + Self { + transaction_id: connect.transaction_id.0.into(), + connection_id: connect.connection_id.0.into(), + } + } +} + #[derive(Serialize)] pub struct AnnounceResponseDto { transaction_id: i32, @@ -68,6 +83,21 @@ impl From for ScrapeResponseDto { } } +#[derive(Serialize)] +pub struct ErrorResponseDto { + transaction_id: i32, + message: String, +} + +impl From for ErrorResponseDto { + fn from(error: ErrorResponse) -> Self { + Self { + transaction_id: error.transaction_id.0.into(), + message: error.message.to_string(), + } + } +} + #[derive(Serialize)] struct TorrentStats { seeders: i32, From 625db48761f7272d1467d62afc45e2a5d3f720eb Mon Sep 17 00:00:00 2001 From: Mario Date: Mon, 27 May 2024 15:54:56 +0200 Subject: [PATCH 0357/1297] refactor: [#670] new trait for printing responses in JSON format and enum for Dto wrapper --- src/console/clients/udp/responses.rs | 37 ++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/console/clients/udp/responses.rs b/src/console/clients/udp/responses.rs index eb6b386fd..5a39a04d4 100644 --- a/src/console/clients/udp/responses.rs +++ b/src/console/clients/udp/responses.rs @@ -1,9 +1,46 @@ //! Aquatic responses are not serializable. These are the serializable wrappers. use std::net::{Ipv4Addr, Ipv6Addr}; +use anyhow::Context; +use aquatic_udp_protocol::Response::{self}; use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse}; use serde::Serialize; +pub trait DtoToJson { + fn print_response(&self) -> anyhow::Result<()> + where + Self: Serialize, + { + let pretty_json = serde_json::to_string_pretty(self).context("response JSON serialization")?; + println!("{pretty_json}"); + + Ok(()) + } +} + +#[derive(Serialize)] +pub enum ResponseDto { + Connect(ConnectResponseDto), + AnnounceIpv4(AnnounceResponseDto), + AnnounceIpv6(AnnounceResponseDto), + Scrape(ScrapeResponseDto), + Error(ErrorResponseDto), +} + +impl From for ResponseDto { + fn from(response: Response) -> Self { + match response { + Response::Connect(response) => ResponseDto::Connect(ConnectResponseDto::from(response)), + Response::AnnounceIpv4(response) => ResponseDto::AnnounceIpv4(AnnounceResponseDto::from(response)), + Response::AnnounceIpv6(response) => ResponseDto::AnnounceIpv6(AnnounceResponseDto::from(response)), + Response::Scrape(response) => ResponseDto::Scrape(ScrapeResponseDto::from(response)), + Response::Error(response) => ResponseDto::Error(ErrorResponseDto::from(response)), + } + } +} + +impl DtoToJson for ResponseDto {} + #[derive(Serialize)] pub struct ConnectResponseDto { transaction_id: i32, From 08e87ca01f7bc8b8bf1ae72e1e4c442adfa3356b Mon Sep 17 00:00:00 2001 From: Mario Date: Mon, 27 May 2024 15:59:10 +0200 Subject: [PATCH 0358/1297] refactor: [#670] new print_response function from trait implemented --- src/console/clients/udp/app.rs | 40 ++++------------------------------ 1 file changed, 4 insertions(+), 36 deletions(-) diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index 9621cec52..1675fd9ed 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -60,15 +60,14 @@ use std::net::{SocketAddr, ToSocketAddrs}; use std::str::FromStr; use anyhow::Context; -use aquatic_udp_protocol::Response::{self, AnnounceIpv4, AnnounceIpv6, Connect, Error, Scrape}; -use aquatic_udp_protocol::{Port, TransactionId}; +use aquatic_udp_protocol::{Port, Response, TransactionId}; use clap::{Parser, Subcommand}; use log::{debug, LevelFilter}; use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; use url::Url; use crate::console::clients::udp::checker; -use crate::console::clients::udp::responses::{AnnounceResponseDto, ConnectResponseDto, ErrorResponseDto, ScrapeResponseDto}; +use crate::console::clients::udp::responses::{DtoToJson, ResponseDto}; const ASSIGNED_BY_OS: u16 = 0; const RANDOM_TRANSACTION_ID: i32 = -888_840_697; @@ -117,7 +116,8 @@ pub async fn run() -> anyhow::Result<()> { } => handle_scrape(&tracker_socket_addr, &info_hashes).await?, }; - print_response(response) + let response_dto: ResponseDto = response.into(); + response_dto.print_response() } fn setup_logging(level: LevelFilter) { @@ -169,38 +169,6 @@ async fn handle_scrape(tracker_socket_addr: &SocketAddr, info_hashes: &[TorrustI .await } -fn print_response(response: Response) -> anyhow::Result<()> { - match response { - Connect(response) => { - let pretty_json = serde_json::to_string_pretty(&ConnectResponseDto::from(response)) - .context("connect response JSON serialization")?; - println!("{pretty_json}"); - } - AnnounceIpv4(response) => { - let pretty_json = serde_json::to_string_pretty(&AnnounceResponseDto::from(response)) - .context("announce IPv4 response JSON serialization")?; - println!("{pretty_json}"); - } - AnnounceIpv6(response) => { - let pretty_json = serde_json::to_string_pretty(&AnnounceResponseDto::from(response)) - .context("announce IPv6 response JSON serialization")?; - println!("{pretty_json}"); - } - Scrape(response) => { - let pretty_json = - serde_json::to_string_pretty(&ScrapeResponseDto::from(response)).context("scrape response JSON serialization")?; - println!("{pretty_json}"); - } - Error(response) => { - let pretty_json = - serde_json::to_string_pretty(&ErrorResponseDto::from(response)).context("error response JSON serialization")?; - println!("{pretty_json}"); - } - }; - - Ok(()) -} - fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); From 74f4cb0aaf5de8ea0e9c09833f2e98f27e80ade3 Mon Sep 17 00:00:00 2001 From: Mario Date: Mon, 27 May 2024 17:29:17 +0200 Subject: [PATCH 0359/1297] refactor: [#670] added error message for pint_response function --- src/console/clients/udp/responses.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/console/clients/udp/responses.rs b/src/console/clients/udp/responses.rs index 5a39a04d4..83e4da506 100644 --- a/src/console/clients/udp/responses.rs +++ b/src/console/clients/udp/responses.rs @@ -7,6 +7,10 @@ use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv use serde::Serialize; pub trait DtoToJson { + /// # Errors + /// + /// Will return an error if serialization fails. + /// fn print_response(&self) -> anyhow::Result<()> where Self: Serialize, From 5a529cc4c8676177820a8e3770c49573f152a479 Mon Sep 17 00:00:00 2001 From: Mario Date: Tue, 4 Jun 2024 00:43:25 +0200 Subject: [PATCH 0360/1297] refactor: [#670] new mod for responses logic and refactors to json serialization trait --- src/console/clients/udp/app.rs | 9 +++++-- .../udp/{responses.rs => responses/dto.rs} | 19 --------------- src/console/clients/udp/responses/json.rs | 24 +++++++++++++++++++ src/console/clients/udp/responses/mod.rs | 2 ++ 4 files changed, 33 insertions(+), 21 deletions(-) rename src/console/clients/udp/{responses.rs => responses/dto.rs} (90%) create mode 100644 src/console/clients/udp/responses/json.rs create mode 100644 src/console/clients/udp/responses/mod.rs diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index 1675fd9ed..b4d08b26d 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -67,7 +67,8 @@ use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; use url::Url; use crate::console::clients::udp::checker; -use crate::console::clients::udp::responses::{DtoToJson, ResponseDto}; +use crate::console::clients::udp::responses::dto::ResponseDto; +use crate::console::clients::udp::responses::json::ToJson; const ASSIGNED_BY_OS: u16 = 0; const RANDOM_TRANSACTION_ID: i32 = -888_840_697; @@ -117,7 +118,11 @@ pub async fn run() -> anyhow::Result<()> { }; let response_dto: ResponseDto = response.into(); - response_dto.print_response() + let response_json = response_dto.to_json_string()?; + + print!("{response_json}"); + + Ok(()) } fn setup_logging(level: LevelFilter) { diff --git a/src/console/clients/udp/responses.rs b/src/console/clients/udp/responses/dto.rs similarity index 90% rename from src/console/clients/udp/responses.rs rename to src/console/clients/udp/responses/dto.rs index 83e4da506..989231061 100644 --- a/src/console/clients/udp/responses.rs +++ b/src/console/clients/udp/responses/dto.rs @@ -1,27 +1,10 @@ //! Aquatic responses are not serializable. These are the serializable wrappers. use std::net::{Ipv4Addr, Ipv6Addr}; -use anyhow::Context; use aquatic_udp_protocol::Response::{self}; use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse}; use serde::Serialize; -pub trait DtoToJson { - /// # Errors - /// - /// Will return an error if serialization fails. - /// - fn print_response(&self) -> anyhow::Result<()> - where - Self: Serialize, - { - let pretty_json = serde_json::to_string_pretty(self).context("response JSON serialization")?; - println!("{pretty_json}"); - - Ok(()) - } -} - #[derive(Serialize)] pub enum ResponseDto { Connect(ConnectResponseDto), @@ -43,8 +26,6 @@ impl From for ResponseDto { } } -impl DtoToJson for ResponseDto {} - #[derive(Serialize)] pub struct ConnectResponseDto { transaction_id: i32, diff --git a/src/console/clients/udp/responses/json.rs b/src/console/clients/udp/responses/json.rs new file mode 100644 index 000000000..1e25acac2 --- /dev/null +++ b/src/console/clients/udp/responses/json.rs @@ -0,0 +1,24 @@ +use anyhow::Context; +use serde::Serialize; + +use super::dto::ResponseDto; + +pub trait ToJson { + /// + /// Returns a string with the JSON serialized version of the response + /// + /// # Errors + /// + /// Will return an error if serialization fails. + /// + fn to_json_string(&self) -> anyhow::Result + where + Self: Serialize, + { + let pretty_json = serde_json::to_string_pretty(self).context("response JSON serialization")?; + + Ok(pretty_json) + } +} + +impl ToJson for ResponseDto {} diff --git a/src/console/clients/udp/responses/mod.rs b/src/console/clients/udp/responses/mod.rs new file mode 100644 index 000000000..e6d2e5e51 --- /dev/null +++ b/src/console/clients/udp/responses/mod.rs @@ -0,0 +1,2 @@ +pub mod dto; +pub mod json; From 32416ee2239942891896260e9dfc4e0bf31d9ad1 Mon Sep 17 00:00:00 2001 From: Mario Date: Tue, 4 Jun 2024 12:32:35 +0200 Subject: [PATCH 0361/1297] refactor: [#670] changed DTOs and variable names --- src/console/clients/udp/app.rs | 6 ++-- src/console/clients/udp/responses/dto.rs | 42 +++++++++++------------ src/console/clients/udp/responses/json.rs | 4 +-- 3 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index b4d08b26d..d2c986cd9 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -67,7 +67,7 @@ use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; use url::Url; use crate::console::clients::udp::checker; -use crate::console::clients::udp::responses::dto::ResponseDto; +use crate::console::clients::udp::responses::dto::SerializableResponse; use crate::console::clients::udp::responses::json::ToJson; const ASSIGNED_BY_OS: u16 = 0; @@ -117,8 +117,8 @@ pub async fn run() -> anyhow::Result<()> { } => handle_scrape(&tracker_socket_addr, &info_hashes).await?, }; - let response_dto: ResponseDto = response.into(); - let response_json = response_dto.to_json_string()?; + let response: SerializableResponse = response.into(); + let response_json = response.to_json_string()?; print!("{response_json}"); diff --git a/src/console/clients/udp/responses/dto.rs b/src/console/clients/udp/responses/dto.rs index 989231061..93320b0f7 100644 --- a/src/console/clients/udp/responses/dto.rs +++ b/src/console/clients/udp/responses/dto.rs @@ -6,33 +6,33 @@ use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv use serde::Serialize; #[derive(Serialize)] -pub enum ResponseDto { - Connect(ConnectResponseDto), - AnnounceIpv4(AnnounceResponseDto), - AnnounceIpv6(AnnounceResponseDto), - Scrape(ScrapeResponseDto), - Error(ErrorResponseDto), +pub enum SerializableResponse { + Connect(ConnectSerializableResponse), + AnnounceIpv4(AnnounceSerializableResponse), + AnnounceIpv6(AnnounceSerializableResponse), + Scrape(ScrapeSerializableResponse), + Error(ErrorSerializableResponse), } -impl From for ResponseDto { +impl From for SerializableResponse { fn from(response: Response) -> Self { match response { - Response::Connect(response) => ResponseDto::Connect(ConnectResponseDto::from(response)), - Response::AnnounceIpv4(response) => ResponseDto::AnnounceIpv4(AnnounceResponseDto::from(response)), - Response::AnnounceIpv6(response) => ResponseDto::AnnounceIpv6(AnnounceResponseDto::from(response)), - Response::Scrape(response) => ResponseDto::Scrape(ScrapeResponseDto::from(response)), - Response::Error(response) => ResponseDto::Error(ErrorResponseDto::from(response)), + Response::Connect(response) => SerializableResponse::Connect(ConnectSerializableResponse::from(response)), + Response::AnnounceIpv4(response) => SerializableResponse::AnnounceIpv4(AnnounceSerializableResponse::from(response)), + Response::AnnounceIpv6(response) => SerializableResponse::AnnounceIpv6(AnnounceSerializableResponse::from(response)), + Response::Scrape(response) => SerializableResponse::Scrape(ScrapeSerializableResponse::from(response)), + Response::Error(response) => SerializableResponse::Error(ErrorSerializableResponse::from(response)), } } } #[derive(Serialize)] -pub struct ConnectResponseDto { +pub struct ConnectSerializableResponse { transaction_id: i32, connection_id: i64, } -impl From for ConnectResponseDto { +impl From for ConnectSerializableResponse { fn from(connect: ConnectResponse) -> Self { Self { transaction_id: connect.transaction_id.0.into(), @@ -42,7 +42,7 @@ impl From for ConnectResponseDto { } #[derive(Serialize)] -pub struct AnnounceResponseDto { +pub struct AnnounceSerializableResponse { transaction_id: i32, announce_interval: i32, leechers: i32, @@ -50,7 +50,7 @@ pub struct AnnounceResponseDto { peers: Vec, } -impl From> for AnnounceResponseDto { +impl From> for AnnounceSerializableResponse { fn from(announce: AnnounceResponse) -> Self { Self { transaction_id: announce.fixed.transaction_id.0.into(), @@ -66,7 +66,7 @@ impl From> for AnnounceResponseDto { } } -impl From> for AnnounceResponseDto { +impl From> for AnnounceSerializableResponse { fn from(announce: AnnounceResponse) -> Self { Self { transaction_id: announce.fixed.transaction_id.0.into(), @@ -83,12 +83,12 @@ impl From> for AnnounceResponseDto { } #[derive(Serialize)] -pub struct ScrapeResponseDto { +pub struct ScrapeSerializableResponse { transaction_id: i32, torrent_stats: Vec, } -impl From for ScrapeResponseDto { +impl From for ScrapeSerializableResponse { fn from(scrape: ScrapeResponse) -> Self { Self { transaction_id: scrape.transaction_id.0.into(), @@ -106,12 +106,12 @@ impl From for ScrapeResponseDto { } #[derive(Serialize)] -pub struct ErrorResponseDto { +pub struct ErrorSerializableResponse { transaction_id: i32, message: String, } -impl From for ErrorResponseDto { +impl From for ErrorSerializableResponse { fn from(error: ErrorResponse) -> Self { Self { transaction_id: error.transaction_id.0.into(), diff --git a/src/console/clients/udp/responses/json.rs b/src/console/clients/udp/responses/json.rs index 1e25acac2..74558c8f5 100644 --- a/src/console/clients/udp/responses/json.rs +++ b/src/console/clients/udp/responses/json.rs @@ -1,7 +1,7 @@ use anyhow::Context; use serde::Serialize; -use super::dto::ResponseDto; +use super::dto::SerializableResponse; pub trait ToJson { /// @@ -21,4 +21,4 @@ pub trait ToJson { } } -impl ToJson for ResponseDto {} +impl ToJson for SerializableResponse {} From 0157d96cd29bc79f1396d34088f6d109d6a59d61 Mon Sep 17 00:00:00 2001 From: Mario Date: Tue, 4 Jun 2024 13:16:47 +0200 Subject: [PATCH 0362/1297] refactor:[#670] fix clippy errors --- src/console/clients/udp/responses/json.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/console/clients/udp/responses/json.rs b/src/console/clients/udp/responses/json.rs index 74558c8f5..5d2bd6b89 100644 --- a/src/console/clients/udp/responses/json.rs +++ b/src/console/clients/udp/responses/json.rs @@ -3,6 +3,7 @@ use serde::Serialize; use super::dto::SerializableResponse; +#[allow(clippy::module_name_repetitions)] pub trait ToJson { /// /// Returns a string with the JSON serialized version of the response From f5d843b29e828c712845405a927c07ad867aea3c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jun 2024 07:50:42 +0100 Subject: [PATCH 0363/1297] docs: add benchmarking to torrent repo README --- packages/torrent-repository/README.md | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/packages/torrent-repository/README.md b/packages/torrent-repository/README.md index 98d7d922b..ffc71f1d7 100644 --- a/packages/torrent-repository/README.md +++ b/packages/torrent-repository/README.md @@ -1,6 +1,27 @@ -# Torrust Tracker Configuration +# Torrust Tracker Torrent Repository -A library to provide torrent repository to the [Torrust Tracker](https://github.com/torrust/torrust-tracker). +A library to provide a torrent repository to the [Torrust Tracker](https://github.com/torrust/torrust-tracker). + +## Benchmarking + +```console +cargo bench -p torrust-tracker-torrent-repository +``` + +Example partial output: + +```output + Running benches/repository_benchmark.rs (target/release/deps/repository_benchmark-a9b0013c8d09c3c3) +add_one_torrent/RwLockStd + time: [63.057 ns 63.242 ns 63.506 ns] +Found 12 outliers among 100 measurements (12.00%) + 2 (2.00%) low severe + 2 (2.00%) low mild + 2 (2.00%) high mild + 6 (6.00%) high severe +add_one_torrent/RwLockStdMutexStd + time: [62.505 ns 63.077 ns 63.817 ns] +``` ## Documentation From 6e87d3e1a37d94fd3886a7420214a6e4746c7215 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jun 2024 08:02:30 +0100 Subject: [PATCH 0364/1297] chore(deps): update dependencies ```output cargo update Updating crates.io index Locking 23 packages to latest compatible versions Updating anstyle-query v1.0.3 -> v1.1.0 Updating async-io v2.3.2 -> v2.3.3 Updating async-lock v3.3.0 -> v3.4.0 Updating borsh v1.5.0 -> v1.5.1 Updating borsh-derive v1.5.0 -> v1.5.1 Updating cc v1.0.98 -> v1.0.99 Updating cfg_aliases v0.1.1 -> v0.2.1 Updating clap v4.5.4 -> v4.5.6 Updating clap_builder v4.5.2 -> v4.5.6 Updating clap_derive v4.5.4 -> v4.5.5 Updating clap_lex v0.7.0 -> v0.7.1 Removing event-listener v4.0.3 Removing event-listener-strategy v0.4.0 Updating piper v0.2.2 -> v0.2.3 Updating polling v3.7.0 -> v3.7.1 Updating proc-macro2 v1.0.84 -> v1.0.85 Updating regex v1.10.4 -> v1.10.5 Updating regex-automata v0.4.6 -> v0.4.7 Updating regex-syntax v0.8.3 -> v0.8.4 Updating rstest v0.20.0 -> v0.21.0 Updating rstest_macros v0.20.0 -> v0.21.0 Updating toml v0.8.13 -> v0.8.14 Updating toml_edit v0.22.13 -> v0.22.14 Updating utf8parse v0.2.1 -> v0.2.2 Updating winnow v0.6.9 -> v0.6.13 ``` --- Cargo.lock | 131 ++++++++++++++++++++++------------------------------- 1 file changed, 55 insertions(+), 76 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4e08b1b4d..d3f5766d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -117,9 +117,9 @@ dependencies = [ [[package]] name = "anstyle-query" -version = "1.0.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a64c907d4e79225ac72e2a354c9ce84d50ebb4586dee56c82b3ee73004f537f5" +checksum = "ad186efb764318d35165f1758e7dcef3b10628e26d41a44bc5550652e6804391" dependencies = [ "windows-sys 0.52.0", ] @@ -206,7 +206,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89b47800b0be77592da0afd425cc03468052844aff33b84e33cc696f64e77b6a" dependencies = [ "concurrent-queue", - "event-listener-strategy 0.5.2", + "event-listener-strategy", "futures-core", "pin-project-lite", ] @@ -248,8 +248,8 @@ checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" dependencies = [ "async-channel 2.3.1", "async-executor", - "async-io 2.3.2", - "async-lock 3.3.0", + "async-io 2.3.3", + "async-lock 3.4.0", "blocking", "futures-lite 2.3.0", "once_cell", @@ -278,17 +278,17 @@ dependencies = [ [[package]] name = "async-io" -version = "2.3.2" +version = "2.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcccb0f599cfa2f8ace422d3555572f47424da5648a4382a9dd0310ff8210884" +checksum = "0d6baa8f0178795da0e71bc42c9e5d13261aac7ee549853162e66a241ba17964" dependencies = [ - "async-lock 3.3.0", + "async-lock 3.4.0", "cfg-if", "concurrent-queue", "futures-io", "futures-lite 2.3.0", "parking", - "polling 3.7.0", + "polling 3.7.1", "rustix 0.38.34", "slab", "tracing", @@ -306,12 +306,12 @@ dependencies = [ [[package]] name = "async-lock" -version = "3.3.0" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d034b430882f8381900d3fe6f0aaa3ad94f2cb4ac519b429692a1bc2dda4ae7b" +checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" dependencies = [ - "event-listener 4.0.3", - "event-listener-strategy 0.4.0", + "event-listener 5.3.1", + "event-listener-strategy", "pin-project-lite", ] @@ -617,9 +617,9 @@ dependencies = [ [[package]] name = "borsh" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbe5b10e214954177fb1dc9fbd20a1a2608fe99e6c832033bdc7cea287a20d77" +checksum = "a6362ed55def622cddc70a4746a68554d7b687713770de539e59a739b249f8ed" dependencies = [ "borsh-derive", "cfg_aliases", @@ -627,9 +627,9 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7a8646f94ab393e43e8b35a2558b1624bed28b97ee09c5d15456e3c9463f46d" +checksum = "c3ef8005764f53cd4dca619f5bf64cafd4664dada50ece25e4d81de54c80cc0b" dependencies = [ "once_cell", "proc-macro-crate 3.1.0", @@ -738,9 +738,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.98" +version = "1.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41c270e7540d725e65ac7f1b212ac8ce349719624d7bcff99f8e2e488e8cf03f" +checksum = "96c51067fd44124faa7f870b4b1c969379ad32b2ba805aa959430ceaa384f695" dependencies = [ "jobserver", "libc", @@ -764,9 +764,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cfg_aliases" -version = "0.1.1" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "chrono" @@ -821,9 +821,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.4" +version = "4.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" +checksum = "a9689a29b593160de5bc4aacab7b5d54fb52231de70122626c178e6a368994c7" dependencies = [ "clap_builder", "clap_derive", @@ -831,9 +831,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.2" +version = "4.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" +checksum = "2e5387378c84f6faa26890ebf9f0a92989f8873d4d380467bcd0d8d8620424df" dependencies = [ "anstream", "anstyle", @@ -843,9 +843,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.4" +version = "4.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64" +checksum = "c780290ccf4fb26629baa7a1081e68ced113f1d3ec302fa5948f1c381ebf06c6" dependencies = [ "heck 0.5.0", "proc-macro2", @@ -855,9 +855,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" +checksum = "4b82cf0babdbd58558212896d1a4272303a57bdb245c2bf1147185fb45640e70" [[package]] name = "cmake" @@ -1211,17 +1211,6 @@ version = "2.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" -[[package]] -name = "event-listener" -version = "4.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b215c49b2b248c855fb73579eb1f4f26c38ffdc12973e20e07b91d78d5646e" -dependencies = [ - "concurrent-queue", - "parking", - "pin-project-lite", -] - [[package]] name = "event-listener" version = "5.3.1" @@ -1233,16 +1222,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "event-listener-strategy" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "958e4d70b6d5e81971bebec42271ec641e7ff4e170a6fa605f2b8a8b65cb97d3" -dependencies = [ - "event-listener 4.0.3", - "pin-project-lite", -] - [[package]] name = "event-listener-strategy" version = "0.5.2" @@ -2609,9 +2588,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "piper" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "464db0c665917b13ebb5d453ccdec4add5658ee1adc7affc7677615356a8afaf" +checksum = "ae1d5c74c9876f070d3e8fd503d748c7d974c3e48da8f41350fa5222ef9b4391" dependencies = [ "atomic-waker", "fastrand 2.1.0", @@ -2670,9 +2649,9 @@ dependencies = [ [[package]] name = "polling" -version = "3.7.0" +version = "3.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "645493cf344456ef24219d02a768cf1fb92ddf8c92161679ae3d91b91a637be3" +checksum = "5e6a007746f34ed64099e88783b0ae369eaa3da6392868ba262e2af9b8fbaea1" dependencies = [ "cfg-if", "concurrent-queue", @@ -2766,9 +2745,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.84" +version = "1.0.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec96c6a92621310b51366f1e28d05ef11489516e93be030060e5fc12024a49d6" +checksum = "22244ce15aa966053a896d1accb3a6e68469b97c7f33f284b99f0d576879fc23" dependencies = [ "unicode-ident", ] @@ -2925,9 +2904,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.4" +version = "1.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c" +checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f" dependencies = [ "aho-corasick", "memchr", @@ -2937,9 +2916,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" +checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" dependencies = [ "aho-corasick", "memchr", @@ -2948,9 +2927,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" +checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" [[package]] name = "relative-path" @@ -3064,9 +3043,9 @@ dependencies = [ [[package]] name = "rstest" -version = "0.20.0" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27059f51958c5f8496a6f79511e7c0ac396dd815dc8894e9b6e2efb5779cf6f0" +checksum = "9afd55a67069d6e434a95161415f5beeada95a01c7b815508a82dcb0e1593682" dependencies = [ "futures", "futures-timer", @@ -3076,9 +3055,9 @@ dependencies = [ [[package]] name = "rstest_macros" -version = "0.20.0" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6132d64df104c0b3ea7a6ad7766a43f587bd773a4a9cf4cd59296d426afaf3a" +checksum = "4165dfae59a39dd41d8dec720d3cbfbc71f69744efb480a3920f5d4e0cc6798d" dependencies = [ "cfg-if", "glob", @@ -3809,14 +3788,14 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.13" +version = "0.8.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4e43f8cc456c9704c851ae29c67e17ef65d2c30017c17a9765b89c382dc8bba" +checksum = "6f49eb2ab21d2f26bd6db7bf383edc527a7ebaee412d17af4d40fdccd442f335" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.13", + "toml_edit 0.22.14", ] [[package]] @@ -3852,15 +3831,15 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.13" +version = "0.22.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c127785850e8c20836d49732ae6abfa47616e60bf9d9f57c43c250361a9db96c" +checksum = "f21c7aaf97f1bd9ca9d4f9e73b0a6c74bd5afef56f2bc931943a6e1c37e04e38" dependencies = [ "indexmap 2.2.6", "serde", "serde_spanned", "toml_datetime", - "winnow 0.6.9", + "winnow 0.6.13", ] [[package]] @@ -4169,9 +4148,9 @@ dependencies = [ [[package]] name = "utf8parse" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" @@ -4498,9 +4477,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.6.9" +version = "0.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86c949fede1d13936a99f14fafd3e76fd642b556dd2ce96287fbe2e0151bfac6" +checksum = "59b5e5f6c299a3c7890b876a2a587f3115162487e704907d9b6cd29473052ba1" dependencies = [ "memchr", ] From 3ccc0e41599dff371e4f8bc49eaa4d972b2f3627 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jun 2024 15:12:08 +0100 Subject: [PATCH 0365/1297] chore(deps): add cargo dependency tracing We will move from `log` to `tracing` crate. --- Cargo.lock | 82 +++++++++++++++++++++++++++++++ Cargo.toml | 1 + packages/located-error/Cargo.toml | 1 + 3 files changed, 84 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index d3f5766d5..ab7512536 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2339,6 +2339,16 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e9e591e719385e6ebaeb5ce5d3887f7d5676fceca6411d1925ccc95745f3d6f7" +[[package]] +name = "nu-ansi-term" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" +dependencies = [ + "overload", + "winapi", +] + [[package]] name = "num-bigint" version = "0.4.5" @@ -2448,6 +2458,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "overload" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" + [[package]] name = "parking" version = "2.2.0" @@ -3441,6 +3457,15 @@ dependencies = [ "digest", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "1.3.0" @@ -3668,6 +3693,16 @@ dependencies = [ "syn 2.0.66", ] +[[package]] +name = "thread_local" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" +dependencies = [ + "cfg-if", + "once_cell", +] + [[package]] name = "time" version = "0.3.36" @@ -3899,6 +3934,7 @@ dependencies = [ "tower-http", "trace", "tracing", + "tracing-subscriber", "url", "uuid", "zerocopy", @@ -3943,6 +3979,7 @@ version = "3.0.0-alpha.12-develop" dependencies = [ "log", "thiserror", + "tracing", ] [[package]] @@ -4074,6 +4111,45 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-serde" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc6b213177105856957181934e4920de57730fc69bf42c37ee5bb664d406d9e1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b" +dependencies = [ + "nu-ansi-term", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing-core", + "tracing-log", + "tracing-serde", ] [[package]] @@ -4162,6 +4238,12 @@ dependencies = [ "rand", ] +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + [[package]] name = "value-bag" version = "1.9.0" diff --git a/Cargo.toml b/Cargo.toml index 5183c6067..6166831e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -80,6 +80,7 @@ tower = { version = "0.4.13", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } trace = "0" tracing = "0" +tracing-subscriber = { version = "0.3.18", features = ["json"] } url = "2" uuid = { version = "1", features = ["v4"] } zerocopy = "0.7.33" diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index fa3d1d76d..f34f9bc88 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -16,6 +16,7 @@ version.workspace = true [dependencies] log = { version = "0", features = ["release_max_level_info"] } +tracing = "0.1.40" [dev-dependencies] thiserror = "1" From 6e06b2e7aaeacb5307e494e28c4f45f08a96892b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jun 2024 15:30:25 +0100 Subject: [PATCH 0366/1297] refactor: [#884] move from log to tracing crate --- packages/located-error/src/lib.rs | 2 +- src/app.rs | 2 +- src/bootstrap/jobs/health_check_api.rs | 2 +- src/bootstrap/jobs/http_tracker.rs | 2 +- src/bootstrap/jobs/mod.rs | 2 +- src/bootstrap/jobs/torrent_cleanup.rs | 2 +- src/bootstrap/jobs/tracker_apis.rs | 2 +- src/bootstrap/jobs/udp_tracker.rs | 2 +- src/bootstrap/logging.rs | 73 ++++++++++++------- src/console/ci/e2e/docker.rs | 2 +- src/console/ci/e2e/logs_parser.rs | 34 ++++----- src/console/ci/e2e/runner.rs | 27 ++----- src/console/ci/e2e/tracker_checker.rs | 2 +- src/console/ci/e2e/tracker_container.rs | 2 +- src/console/clients/checker/app.rs | 27 ++----- src/console/clients/checker/checks/http.rs | 2 +- src/console/clients/checker/checks/udp.rs | 2 +- src/console/clients/udp/app.rs | 27 ++----- src/console/clients/udp/checker.rs | 2 +- src/console/profiling.rs | 2 +- src/core/auth.rs | 2 +- src/core/databases/mysql.rs | 2 +- src/core/mod.rs | 2 +- src/core/statistics.rs | 2 +- src/main.rs | 2 +- src/servers/apis/server.rs | 2 +- .../apis/v1/context/torrent/handlers.rs | 2 +- src/servers/health_check_api/server.rs | 3 +- src/servers/http/server.rs | 2 +- src/servers/http/v1/handlers/announce.rs | 2 +- src/servers/http/v1/handlers/scrape.rs | 2 +- src/servers/registar.rs | 2 +- src/servers/signals.rs | 2 +- src/servers/udp/handlers.rs | 2 +- src/servers/udp/server.rs | 2 +- src/shared/bit_torrent/tracker/udp/client.rs | 2 +- tests/servers/health_check_api/environment.rs | 2 +- 37 files changed, 112 insertions(+), 141 deletions(-) diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs index 49e135600..bfd4d4a86 100644 --- a/packages/located-error/src/lib.rs +++ b/packages/located-error/src/lib.rs @@ -33,7 +33,7 @@ use std::error::Error; use std::panic::Location; use std::sync::Arc; -use log::debug; +use tracing::debug; pub type DynError = Arc; diff --git a/src/app.rs b/src/app.rs index fcb01a696..b41f4098e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -23,9 +23,9 @@ //! - Tracker REST API: the tracker API can be enabled/disabled. use std::sync::Arc; -use log::warn; use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; +use tracing::warn; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; use crate::servers::registar::Registar; diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index fdedaa3e9..c22a4cf95 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -14,10 +14,10 @@ //! Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) //! for the API configuration options. -use log::info; use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_tracker_configuration::HealthCheckApi; +use tracing::info; use super::Started; use crate::servers::health_check_api::server; diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 9ae8995fc..e9eb6bc16 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -14,9 +14,9 @@ use std::net::SocketAddr; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; -use log::info; use tokio::task::JoinHandle; use torrust_tracker_configuration::HttpTracker; +use tracing::info; use super::make_rust_tls; use crate::core; diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index e20d243c6..316e5746c 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -89,10 +89,10 @@ use std::panic::Location; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; -use log::info; use thiserror::Error; use torrust_tracker_configuration::TslConfig; use torrust_tracker_located_error::{DynError, LocatedError}; +use tracing::info; /// Error returned by the Bootstrap Process. #[derive(Error, Debug)] diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index bd3b2e332..992e7e644 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -13,9 +13,9 @@ use std::sync::Arc; use chrono::Utc; -use log::info; use tokio::task::JoinHandle; use torrust_tracker_configuration::v1::core::Core; +use tracing::info; use crate::core; diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 834574edb..3c1f13255 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -24,9 +24,9 @@ use std::net::SocketAddr; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; -use log::info; use tokio::task::JoinHandle; use torrust_tracker_configuration::{AccessTokens, HttpApi}; +use tracing::info; use super::make_rust_tls; use crate::core; diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 853cb7461..2c09e6de2 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -8,9 +8,9 @@ //! > for the configuration options. use std::sync::Arc; -use log::debug; use tokio::task::JoinHandle; use torrust_tracker_configuration::UdpTracker; +use tracing::debug; use crate::core; use crate::servers::registar::ServiceRegistrationForm; diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index 5c7e93811..914ede0c4 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -12,55 +12,72 @@ //! Refer to the [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) to know how to change log settings. use std::sync::Once; -use log::{info, LevelFilter}; use torrust_tracker_configuration::{Configuration, LogLevel}; +use tracing::info; +use tracing::level_filters::LevelFilter; static INIT: Once = Once::new(); /// It redirects the log info to the standard output with the log level defined in the configuration pub fn setup(cfg: &Configuration) { - let level = config_level_or_default(&cfg.core.log_level); + let tracing_level = config_level_or_default(&cfg.core.log_level); - if level == log::LevelFilter::Off { + if tracing_level == LevelFilter::OFF { return; } INIT.call_once(|| { - stdout_config(level); + tracing_stdout_init(tracing_level, &TraceStyle::Default); }); } fn config_level_or_default(log_level: &Option) -> LevelFilter { match log_level { - None => log::LevelFilter::Info, + None => LevelFilter::INFO, 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, + LogLevel::Off => LevelFilter::OFF, + LogLevel::Error => LevelFilter::ERROR, + LogLevel::Warn => LevelFilter::WARN, + LogLevel::Info => LevelFilter::INFO, + LogLevel::Debug => LevelFilter::DEBUG, + LogLevel::Trace => LevelFilter::TRACE, }, } } -fn stdout_config(level: LevelFilter) { - if let Err(_err) = fern::Dispatch::new() - .format(|out, message, record| { - out.finish(format_args!( - "{} [{}][{}] {}", - chrono::Local::now().format("%+"), - record.target(), - record.level(), - message - )); - }) - .level(level) - .chain(std::io::stdout()) - .apply() - { - panic!("Failed to initialize logging.") - } +fn tracing_stdout_init(filter: LevelFilter, style: &TraceStyle) { + let builder = tracing_subscriber::fmt().with_max_level(filter); + + let () = match style { + TraceStyle::Default => builder.init(), + TraceStyle::Pretty(display_filename) => builder.pretty().with_file(*display_filename).init(), + TraceStyle::Compact => builder.compact().init(), + TraceStyle::Json => builder.json().init(), + }; info!("logging initialized."); } + +#[derive(Debug)] +pub enum TraceStyle { + Default, + Pretty(bool), + Compact, + Json, +} + +impl std::fmt::Display for TraceStyle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let style = match self { + TraceStyle::Default => "Default Style", + TraceStyle::Pretty(path) => match path { + true => "Pretty Style with File Paths", + false => "Pretty Style without File Paths", + }, + TraceStyle::Compact => "Compact Style", + TraceStyle::Json => "Json Format", + }; + + f.write_str(style) + } +} diff --git a/src/console/ci/e2e/docker.rs b/src/console/ci/e2e/docker.rs index c024efbae..26b7f7708 100644 --- a/src/console/ci/e2e/docker.rs +++ b/src/console/ci/e2e/docker.rs @@ -4,7 +4,7 @@ use std::process::{Command, Output}; use std::thread::sleep; use std::time::{Duration, Instant}; -use log::{debug, info}; +use tracing::{debug, info}; /// Docker command wrapper. pub struct Docker {} diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index 6d3349196..2d215a569 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -1,9 +1,9 @@ //! Utilities to parse Torrust Tracker logs. use serde::{Deserialize, Serialize}; -const UDP_TRACKER_PATTERN: &str = "[UDP TRACKER][INFO] Starting on: udp://"; -const HTTP_TRACKER_PATTERN: &str = "[HTTP TRACKER][INFO] Starting on: "; -const HEALTH_CHECK_PATTERN: &str = "[HEALTH CHECK API][INFO] Starting on: "; +const UDP_TRACKER_PATTERN: &str = "INFO UDP TRACKER: Starting on: udp://"; +const HTTP_TRACKER_PATTERN: &str = "INFO HTTP TRACKER: Starting on: "; +const HEALTH_CHECK_PATTERN: &str = "INFO HEALTH CHECK API: Starting on: "; #[derive(Serialize, Deserialize, Debug, Default)] pub struct RunningServices { @@ -18,17 +18,17 @@ impl RunningServices { /// For example, from this logs: /// /// ```text - /// Loading default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... - /// 2024-01-24T16:36:14.614898789+00:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized. - /// 2024-01-24T16:36:14.615586025+00:00 [UDP TRACKER][INFO] Starting on: udp://0.0.0.0:6969 - /// 2024-01-24T16:36:14.615623705+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled - /// 2024-01-24T16:36:14.615694484+00:00 [HTTP TRACKER][INFO] Starting on: http://0.0.0.0:7070 - /// 2024-01-24T16:36:14.615710534+00:00 [HTTP TRACKER][INFO] Started on: http://0.0.0.0:7070 - /// 2024-01-24T16:36:14.615716574+00:00 [torrust_tracker::bootstrap::jobs][INFO] TLS not enabled - /// 2024-01-24T16:36:14.615764904+00:00 [API][INFO] Starting on http://127.0.0.1:1212 - /// 2024-01-24T16:36:14.615767264+00:00 [API][INFO] Started on http://127.0.0.1:1212 - /// 2024-01-24T16:36:14.615777574+00:00 [HEALTH CHECK API][INFO] Starting on: http://127.0.0.1:1313 - /// 2024-01-24T16:36:14.615791124+00:00 [HEALTH CHECK API][INFO] Started on: http://127.0.0.1:1313 + /// Loading configuration from default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... + /// 2024-06-10T14:26:10.040894Z INFO torrust_tracker::bootstrap::logging: logging initialized. + /// 2024-06-10T14:26:10.041363Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 + /// 2024-06-10T14:26:10.041386Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + /// 2024-06-10T14:26:10.041420Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070 + /// 2024-06-10T14:26:10.041516Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 + /// 2024-06-10T14:26:10.041521Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + /// 2024-06-10T14:26:10.041611Z INFO API: Starting on http://127.0.0.1:1212 + /// 2024-06-10T14:26:10.041614Z INFO API: Started on http://127.0.0.1:1212 + /// 2024-06-10T14:26:10.041623Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 + /// 2024-06-10T14:26:10.041657Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 /// ``` /// /// It would extract these services: @@ -86,9 +86,9 @@ mod tests { #[test] fn it_should_parse_from_logs_with_valid_logs() { let logs = "\ - [UDP TRACKER][INFO] Starting on: udp://0.0.0.0:8080\n\ - [HTTP TRACKER][INFO] Starting on: 0.0.0.0:9090\n\ - [HEALTH CHECK API][INFO] Starting on: 0.0.0.0:10010"; + INFO UDP TRACKER: Starting on: udp://0.0.0.0:8080\n\ + INFO HTTP TRACKER: Starting on: 0.0.0.0:9090\n\ + INFO HEALTH CHECK API: Starting on: 0.0.0.0:10010"; let running_services = RunningServices::parse_from_logs(logs); assert_eq!(running_services.udp_trackers, vec!["127.0.0.1:8080"]); diff --git a/src/console/ci/e2e/runner.rs b/src/console/ci/e2e/runner.rs index 945a87033..c44ce464e 100644 --- a/src/console/ci/e2e/runner.rs +++ b/src/console/ci/e2e/runner.rs @@ -3,7 +3,8 @@ //! ```text //! cargo run --bin e2e_tests_runner share/default/config/tracker.e2e.container.sqlite3.toml //! ``` -use log::{debug, info, LevelFilter}; +use tracing::info; +use tracing::level_filters::LevelFilter; use super::tracker_container::TrackerContainer; use crate::console::ci::e2e::docker::RunOptions; @@ -32,7 +33,7 @@ pub struct Arguments { /// /// Will panic if it can't not perform any of the operations. pub fn run() { - setup_runner_logging(LevelFilter::Info); + tracing_stdout_init(LevelFilter::INFO); let args = parse_arguments(); @@ -76,25 +77,9 @@ pub fn run() { info!("Tracker container final state:\n{:#?}", tracker_container); } -fn setup_runner_logging(level: LevelFilter) { - if let Err(_err) = fern::Dispatch::new() - .format(|out, message, record| { - out.finish(format_args!( - "{} [{}][{}] {}", - chrono::Local::now().format("%+"), - record.target(), - record.level(), - message - )); - }) - .level(level) - .chain(std::io::stdout()) - .apply() - { - panic!("Failed to initialize logging.") - } - - debug!("logging initialized."); +fn tracing_stdout_init(filter: LevelFilter) { + tracing_subscriber::fmt().with_max_level(filter).init(); + info!("logging initialized."); } fn parse_arguments() -> Arguments { diff --git a/src/console/ci/e2e/tracker_checker.rs b/src/console/ci/e2e/tracker_checker.rs index edc679802..b2fd7df2e 100644 --- a/src/console/ci/e2e/tracker_checker.rs +++ b/src/console/ci/e2e/tracker_checker.rs @@ -1,7 +1,7 @@ use std::io; use std::process::Command; -use log::info; +use tracing::info; /// Runs the Tracker Checker. /// diff --git a/src/console/ci/e2e/tracker_container.rs b/src/console/ci/e2e/tracker_container.rs index 5a4d11d02..0cb4fec7c 100644 --- a/src/console/ci/e2e/tracker_container.rs +++ b/src/console/ci/e2e/tracker_container.rs @@ -1,8 +1,8 @@ use std::time::Duration; -use log::{debug, error, info}; use rand::distributions::Alphanumeric; use rand::Rng; +use tracing::{debug, error, info}; use super::docker::{RunOptions, RunningContainer}; use super::logs_parser::RunningServices; diff --git a/src/console/clients/checker/app.rs b/src/console/clients/checker/app.rs index 82ea800d0..84802688d 100644 --- a/src/console/clients/checker/app.rs +++ b/src/console/clients/checker/app.rs @@ -17,7 +17,8 @@ use std::sync::Arc; use anyhow::{Context, Result}; use clap::Parser; -use log::{debug, LevelFilter}; +use tracing::info; +use tracing::level_filters::LevelFilter; use super::config::Configuration; use super::console::Console; @@ -40,7 +41,7 @@ struct Args { /// /// Will return an error if the configuration was not provided. pub async fn run() -> Result> { - setup_logging(LevelFilter::Info); + tracing_stdout_init(LevelFilter::INFO); let args = Args::parse(); @@ -56,25 +57,9 @@ pub async fn run() -> Result> { Ok(service.run_checks().await) } -fn setup_logging(level: LevelFilter) { - if let Err(_err) = fern::Dispatch::new() - .format(|out, message, record| { - out.finish(format_args!( - "{} [{}][{}] {}", - chrono::Local::now().format("%+"), - record.target(), - record.level(), - message - )); - }) - .level(level) - .chain(std::io::stdout()) - .apply() - { - panic!("Failed to initialize logging.") - } - - debug!("logging initialized."); +fn tracing_stdout_init(filter: LevelFilter) { + tracing_subscriber::fmt().with_max_level(filter).init(); + info!("logging initialized."); } fn setup_config(args: Args) -> Result { diff --git a/src/console/clients/checker/checks/http.rs b/src/console/clients/checker/checks/http.rs index e526b5e57..57f8c3015 100644 --- a/src/console/clients/checker/checks/http.rs +++ b/src/console/clients/checker/checks/http.rs @@ -1,8 +1,8 @@ use std::str::FromStr; -use log::debug; use reqwest::Url as ServiceUrl; use torrust_tracker_primitives::info_hash::InfoHash; +use tracing::debug; use url::Url; use super::structs::{CheckerOutput, Status}; diff --git a/src/console/clients/checker/checks/udp.rs b/src/console/clients/checker/checks/udp.rs index 6458190d4..072aa5ca7 100644 --- a/src/console/clients/checker/checks/udp.rs +++ b/src/console/clients/checker/checks/udp.rs @@ -2,8 +2,8 @@ use std::net::SocketAddr; use aquatic_udp_protocol::{Port, TransactionId}; use hex_literal::hex; -use log::debug; use torrust_tracker_primitives::info_hash::InfoHash; +use tracing::debug; use crate::console::clients::checker::checks::structs::{CheckerOutput, Status}; use crate::console::clients::checker::service::{CheckError, CheckResult}; diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index d2c986cd9..c780157f4 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -62,8 +62,9 @@ use std::str::FromStr; use anyhow::Context; use aquatic_udp_protocol::{Port, Response, TransactionId}; use clap::{Parser, Subcommand}; -use log::{debug, LevelFilter}; use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; +use tracing::level_filters::LevelFilter; +use tracing::{debug, info}; use url::Url; use crate::console::clients::udp::checker; @@ -102,7 +103,7 @@ enum Command { /// /// pub async fn run() -> anyhow::Result<()> { - setup_logging(LevelFilter::Info); + tracing_stdout_init(LevelFilter::INFO); let args = Args::parse(); @@ -125,25 +126,9 @@ pub async fn run() -> anyhow::Result<()> { Ok(()) } -fn setup_logging(level: LevelFilter) { - if let Err(_err) = fern::Dispatch::new() - .format(|out, message, record| { - out.finish(format_args!( - "{} [{}][{}] {}", - chrono::Local::now().format("%+"), - record.target(), - record.level(), - message - )); - }) - .level(level) - .chain(std::io::stdout()) - .apply() - { - panic!("Failed to initialize logging.") - } - - debug!("logging initialized."); +fn tracing_stdout_init(filter: LevelFilter) { + tracing_subscriber::fmt().with_max_level(filter).init(); + info!("logging initialized."); } async fn handle_announce(tracker_socket_addr: &SocketAddr, info_hash: &TorrustInfoHash) -> anyhow::Result { diff --git a/src/console/clients/udp/checker.rs b/src/console/clients/udp/checker.rs index 37928f0df..afde63d12 100644 --- a/src/console/clients/udp/checker.rs +++ b/src/console/clients/udp/checker.rs @@ -6,9 +6,9 @@ use aquatic_udp_protocol::{ AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, Response, ScrapeRequest, TransactionId, }; -use log::debug; use thiserror::Error; use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; +use tracing::debug; use crate::shared::bit_torrent::tracker::udp::client::{UdpClient, UdpTrackerClient}; diff --git a/src/console/profiling.rs b/src/console/profiling.rs index d77e55966..c95354d6f 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -159,8 +159,8 @@ use std::env; use std::time::Duration; -use log::info; use tokio::time::sleep; +use tracing::info; use crate::{app, bootstrap}; diff --git a/src/core/auth.rs b/src/core/auth.rs index b5326a373..94d455d7e 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -42,7 +42,6 @@ use std::sync::Arc; use std::time::Duration; use derive_more::Display; -use log::debug; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; @@ -51,6 +50,7 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; use torrust_tracker_located_error::{DynError, LocatedError}; use torrust_tracker_primitives::DurationSinceUnixEpoch; +use tracing::debug; use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; use crate::CurrentClock; diff --git a/src/core/databases/mysql.rs b/src/core/databases/mysql.rs index ca95fa0b9..ebb002d31 100644 --- a/src/core/databases/mysql.rs +++ b/src/core/databases/mysql.rs @@ -3,13 +3,13 @@ use std::str::FromStr; use std::time::Duration; use async_trait::async_trait; -use log::debug; use r2d2::Pool; use r2d2_mysql::mysql::prelude::Queryable; use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MySqlConnectionManager; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{DatabaseDriver, PersistentTorrents}; +use tracing::debug; use super::{Database, Error}; use crate::core::auth::{self, Key}; diff --git a/src/core/mod.rs b/src/core/mod.rs index e81ad2a94..6af28199f 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -442,7 +442,6 @@ use std::sync::Arc; use std::time::Duration; use derive_more::Constructor; -use log::debug; use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::v1::core::Core; @@ -453,6 +452,7 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, TrackerMode}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; +use tracing::debug; use self::auth::Key; use self::error::Error; diff --git a/src/core/statistics.rs b/src/core/statistics.rs index f38662cdd..d7192f5d1 100644 --- a/src/core/statistics.rs +++ b/src/core/statistics.rs @@ -20,11 +20,11 @@ use std::sync::Arc; use async_trait::async_trait; -use log::debug; #[cfg(test)] use mockall::{automock, predicate::str}; use tokio::sync::mpsc::error::SendError; use tokio::sync::{mpsc, RwLock, RwLockReadGuard}; +use tracing::debug; const CHANNEL_BUFFER_SIZE: usize = 65_535; diff --git a/src/main.rs b/src/main.rs index bd07f4a58..bad1fdb1e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,5 @@ -use log::info; use torrust_tracker::{app, bootstrap}; +use tracing::info; #[tokio::main] async fn main() { diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 57d2629ae..7c5b8983b 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -30,9 +30,9 @@ use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; use derive_more::Constructor; use futures::future::BoxFuture; -use log::{debug, error, info}; use tokio::sync::oneshot::{Receiver, Sender}; use torrust_tracker_configuration::AccessTokens; +use tracing::{debug, error, info}; use super::routes::router; use crate::bootstrap::jobs::Started; diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs index 15f70c8b6..b2418c689 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/src/servers/apis/v1/context/torrent/handlers.rs @@ -7,11 +7,11 @@ use std::sync::Arc; use axum::extract::{Path, State}; use axum::response::{IntoResponse, Response}; use axum_extra::extract::Query; -use log::debug; use serde::{de, Deserialize, Deserializer}; use thiserror::Error; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; +use tracing::debug; use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; use crate::core::services::torrent::{get_torrent_info, get_torrents, get_torrents_page}; diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index 05ed605f4..f03753573 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -12,14 +12,13 @@ use axum::{Json, Router}; use axum_server::Handle; use futures::Future; use hyper::Request; -use log::debug; use serde_json::json; use tokio::sync::oneshot::{Receiver, Sender}; use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; -use tracing::{Level, Span}; +use tracing::{debug, Level, Span}; use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 33e20a84e..5c33fc8fa 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -6,8 +6,8 @@ use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; use derive_more::Constructor; use futures::future::BoxFuture; -use log::info; use tokio::sync::oneshot::{Receiver, Sender}; +use tracing::info; use super::v1::routes::router; use crate::bootstrap::jobs::Started; diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index e9198f20c..0b009f700 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -11,10 +11,10 @@ use std::sync::Arc; use axum::extract::State; use axum::response::{IntoResponse, Response}; -use log::debug; use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::{peer, NumberOfBytes}; +use tracing::debug; use crate::core::auth::Key; use crate::core::{AnnounceData, Tracker}; diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index d6b39cc53..172607637 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use axum::extract::State; use axum::response::{IntoResponse, Response}; -use log::debug; +use tracing::debug; use crate::core::auth::Key; use crate::core::{ScrapeData, Tracker}; diff --git a/src/servers/registar.rs b/src/servers/registar.rs index 9c23573c4..6058595ba 100644 --- a/src/servers/registar.rs +++ b/src/servers/registar.rs @@ -5,9 +5,9 @@ use std::net::SocketAddr; use std::sync::Arc; use derive_more::Constructor; -use log::debug; use tokio::sync::Mutex; use tokio::task::JoinHandle; +use tracing::debug; /// A [`ServiceHeathCheckResult`] is returned by a completed health check. pub type ServiceHeathCheckResult = Result; diff --git a/src/servers/signals.rs b/src/servers/signals.rs index 42fd868e8..0a1a06312 100644 --- a/src/servers/signals.rs +++ b/src/servers/signals.rs @@ -2,8 +2,8 @@ use std::time::Duration; use derive_more::Display; -use log::info; use tokio::time::sleep; +use tracing::info; /// This is the message that the "launcher" spawned task receives from the main /// application process to notify the service to shutdown. diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 4064cf041..858d6606c 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -10,10 +10,10 @@ use aquatic_udp_protocol::{ ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfDownloads, NumberOfPeers, Port, Request, Response, ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; -use log::debug; use tokio::net::UdpSocket; use torrust_tracker_located_error::DynError; use torrust_tracker_primitives::info_hash::InfoHash; +use tracing::debug; use uuid::Uuid; use zerocopy::network_endian::I32; diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index be4c36d40..dd30d9d6d 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -22,13 +22,13 @@ use std::sync::Arc; use aquatic_udp_protocol::Response; use derive_more::Constructor; -use log::{debug, error, info, trace}; use ringbuf::traits::{Consumer, Observer, Producer}; use ringbuf::StaticRb; use tokio::net::UdpSocket; use tokio::sync::oneshot; use tokio::task::{AbortHandle, JoinHandle}; use tokio::{select, task}; +use tracing::{debug, error, info, trace}; use super::UdpRequest; use crate::bootstrap::jobs::Started; diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs index 81209efb6..45b51ad35 100644 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -6,9 +6,9 @@ use std::time::Duration; use anyhow::{anyhow, Context, Result}; use aquatic_udp_protocol::{ConnectRequest, Request, Response, TransactionId}; -use log::debug; use tokio::net::UdpSocket; use tokio::time; +use tracing::debug; use zerocopy::network_endian::I32; use crate::shared::bit_torrent::tracker::udp::{source_address, MAX_PACKET_SIZE}; diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs index c200beaeb..a50ad5156 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/tests/servers/health_check_api/environment.rs @@ -1,7 +1,6 @@ use std::net::SocketAddr; use std::sync::Arc; -use log::debug; use tokio::sync::oneshot::{self, Sender}; use tokio::task::JoinHandle; use torrust_tracker::bootstrap::jobs::Started; @@ -9,6 +8,7 @@ use torrust_tracker::servers::health_check_api::server; use torrust_tracker::servers::registar::Registar; use torrust_tracker::servers::signals::{self, Halted}; use torrust_tracker_configuration::HealthCheckApi; +use tracing::debug; #[derive(Debug)] pub enum Error { From 69f100ab7d38cde396546ea3b1a34f7c718bd62d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jun 2024 17:01:40 +0100 Subject: [PATCH 0367/1297] refactor: [#884] move from log to tracing crate --- packages/configuration/src/lib.rs | 2 +- .../config/tracker.e2e.container.sqlite3.toml | 4 + src/bootstrap/logging.rs | 2 +- src/console/ci/e2e/docker.rs | 2 + src/console/ci/e2e/logs_parser.rs | 73 +++++++++++++------ src/console/ci/e2e/runner.rs | 7 +- src/console/ci/e2e/tracker_container.rs | 4 +- src/console/clients/checker/app.rs | 2 +- src/console/clients/udp/app.rs | 2 +- src/servers/udp/server.rs | 2 +- 10 files changed, 70 insertions(+), 30 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 62792c271..46ece96ab 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -64,7 +64,7 @@ impl Info { let env_var_config_toml_path = ENV_VAR_CONFIG_TOML_PATH.to_string(); let config_toml = if let Ok(config_toml) = env::var(env_var_config_toml) { - println!("Loading configuration from environment variable {config_toml} ..."); + println!("Loading configuration from environment variable:\n {config_toml}"); Some(config_toml) } else { None diff --git a/share/default/config/tracker.e2e.container.sqlite3.toml b/share/default/config/tracker.e2e.container.sqlite3.toml index e7d8fa279..767b56116 100644 --- a/share/default/config/tracker.e2e.container.sqlite3.toml +++ b/share/default/config/tracker.e2e.container.sqlite3.toml @@ -11,3 +11,7 @@ ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" [http_api] ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + +[health_check_api] +# Must be bound to wildcard IP to be accessible from outside the container +bind_address = "0.0.0.0:1313" diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index 914ede0c4..5194f06ea 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -46,7 +46,7 @@ fn config_level_or_default(log_level: &Option) -> LevelFilter { } fn tracing_stdout_init(filter: LevelFilter, style: &TraceStyle) { - let builder = tracing_subscriber::fmt().with_max_level(filter); + let builder = tracing_subscriber::fmt().with_max_level(filter).with_ansi(false); let () = match style { TraceStyle::Default => builder.init(), diff --git a/src/console/ci/e2e/docker.rs b/src/console/ci/e2e/docker.rs index 26b7f7708..32a0c3e56 100644 --- a/src/console/ci/e2e/docker.rs +++ b/src/console/ci/e2e/docker.rs @@ -176,6 +176,8 @@ impl Docker { let output_str = String::from_utf8_lossy(&output.stdout); + info!("Waiting until container is healthy: {:?}", output_str); + if output_str.contains("(healthy)") { return true; } diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index 2d215a569..a9277524e 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -1,9 +1,9 @@ //! Utilities to parse Torrust Tracker logs. use serde::{Deserialize, Serialize}; -const UDP_TRACKER_PATTERN: &str = "INFO UDP TRACKER: Starting on: udp://"; -const HTTP_TRACKER_PATTERN: &str = "INFO HTTP TRACKER: Starting on: "; -const HEALTH_CHECK_PATTERN: &str = "INFO HEALTH CHECK API: Starting on: "; +const UDP_TRACKER_PATTERN: &str = "UDP TRACKER: Started on: udp://"; +const HTTP_TRACKER_PATTERN: &str = "HTTP TRACKER: Started on: "; +const HEALTH_CHECK_PATTERN: &str = "HEALTH CHECK API: Started on: "; #[derive(Serialize, Deserialize, Debug, Default)] pub struct RunningServices { @@ -19,16 +19,17 @@ impl RunningServices { /// /// ```text /// Loading configuration from default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... - /// 2024-06-10T14:26:10.040894Z INFO torrust_tracker::bootstrap::logging: logging initialized. - /// 2024-06-10T14:26:10.041363Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 - /// 2024-06-10T14:26:10.041386Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled - /// 2024-06-10T14:26:10.041420Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070 - /// 2024-06-10T14:26:10.041516Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 - /// 2024-06-10T14:26:10.041521Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled - /// 2024-06-10T14:26:10.041611Z INFO API: Starting on http://127.0.0.1:1212 - /// 2024-06-10T14:26:10.041614Z INFO API: Started on http://127.0.0.1:1212 - /// 2024-06-10T14:26:10.041623Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 - /// 2024-06-10T14:26:10.041657Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 + /// 2024-06-10T14:59:57.973525Z INFO torrust_tracker::bootstrap::logging: logging initialized. + /// 2024-06-10T14:59:57.974306Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 + /// 2024-06-10T14:59:57.974316Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 + /// 2024-06-10T14:59:57.974332Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + /// 2024-06-10T14:59:57.974366Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070 + /// 2024-06-10T14:59:57.974513Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 + /// 2024-06-10T14:59:57.974521Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + /// 2024-06-10T14:59:57.974615Z INFO API: Starting on http://127.0.0.1:1212 + /// 2024-06-10T14:59:57.974618Z INFO API: Started on http://127.0.0.1:1212 + /// 2024-06-10T14:59:57.974643Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 + /// 2024-06-10T14:59:57.974760Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 /// ``` /// /// It would extract these services: @@ -46,6 +47,9 @@ impl RunningServices { /// ] /// } /// ``` + /// + /// NOTICE: Using colors in the console output could affect this method + /// due to the hidden control chars. #[must_use] pub fn parse_from_logs(logs: &str) -> Self { let mut udp_trackers: Vec = Vec::new(); @@ -85,20 +89,45 @@ mod tests { #[test] fn it_should_parse_from_logs_with_valid_logs() { - let logs = "\ - INFO UDP TRACKER: Starting on: udp://0.0.0.0:8080\n\ - INFO HTTP TRACKER: Starting on: 0.0.0.0:9090\n\ - INFO HEALTH CHECK API: Starting on: 0.0.0.0:10010"; - let running_services = RunningServices::parse_from_logs(logs); + let log = r#" + Loading configuration from environment variable db_path = "/var/lib/torrust/tracker/database/sqlite3.db" + + [[udp_trackers]] + enabled = true + + [[http_trackers]] + enabled = true + ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" + ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + + [http_api] + ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" + ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + ... + Loading configuration from file: `/etc/torrust/tracker/tracker.toml` ... + 2024-06-10T15:09:54.411031Z INFO torrust_tracker::bootstrap::logging: logging initialized. + 2024-06-10T15:09:54.415084Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 + 2024-06-10T15:09:54.415091Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 + 2024-06-10T15:09:54.415104Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + 2024-06-10T15:09:54.415130Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070 + 2024-06-10T15:09:54.415266Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 + 2024-06-10T15:09:54.415275Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + 2024-06-10T15:09:54.415403Z INFO API: Starting on http://127.0.0.1:1212 + 2024-06-10T15:09:54.415411Z INFO API: Started on http://127.0.0.1:1212 + 2024-06-10T15:09:54.415430Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 + 2024-06-10T15:09:54.415472Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 + "#; + + let running_services = RunningServices::parse_from_logs(log); - assert_eq!(running_services.udp_trackers, vec!["127.0.0.1:8080"]); - assert_eq!(running_services.http_trackers, vec!["127.0.0.1:9090"]); - assert_eq!(running_services.health_checks, vec!["127.0.0.1:10010/health_check"]); + assert_eq!(running_services.udp_trackers, vec!["127.0.0.1:6969"]); + assert_eq!(running_services.http_trackers, vec!["http://127.0.0.1:7070"]); + assert_eq!(running_services.health_checks, vec!["http://127.0.0.1:1313/health_check"]); } #[test] fn it_should_ignore_logs_with_no_matching_lines() { - let logs = "[Other Service][INFO] Starting on: 0.0.0.0:7070"; + let logs = "[Other Service][INFO] Started on: 0.0.0.0:7070"; let running_services = RunningServices::parse_from_logs(logs); assert!(running_services.udp_trackers.is_empty()); diff --git a/src/console/ci/e2e/runner.rs b/src/console/ci/e2e/runner.rs index c44ce464e..aeb28b777 100644 --- a/src/console/ci/e2e/runner.rs +++ b/src/console/ci/e2e/runner.rs @@ -60,6 +60,11 @@ pub fn run() { let running_services = tracker_container.running_services(); + info!( + "Running services:\n {}", + serde_json::to_string_pretty(&running_services).expect("running services to be serializable to JSON") + ); + assert_there_is_at_least_one_service_per_type(&running_services); let tracker_checker_config = @@ -78,7 +83,7 @@ pub fn run() { } fn tracing_stdout_init(filter: LevelFilter) { - tracing_subscriber::fmt().with_max_level(filter).init(); + tracing_subscriber::fmt().with_max_level(filter).with_ansi(false).init(); info!("logging initialized."); } diff --git a/src/console/ci/e2e/tracker_container.rs b/src/console/ci/e2e/tracker_container.rs index 0cb4fec7c..dc7036faa 100644 --- a/src/console/ci/e2e/tracker_container.rs +++ b/src/console/ci/e2e/tracker_container.rs @@ -2,7 +2,7 @@ use std::time::Duration; use rand::distributions::Alphanumeric; use rand::Rng; -use tracing::{debug, error, info}; +use tracing::{error, info}; use super::docker::{RunOptions, RunningContainer}; use super::logs_parser::RunningServices; @@ -72,7 +72,7 @@ impl TrackerContainer { pub fn running_services(&self) -> RunningServices { let logs = Docker::logs(&self.name).expect("Logs should be captured from running container"); - debug!("Parsing running services from logs. Logs :\n{logs}"); + info!("Parsing running services from logs. Logs :\n{logs}"); RunningServices::parse_from_logs(&logs) } diff --git a/src/console/clients/checker/app.rs b/src/console/clients/checker/app.rs index 84802688d..ade1d4820 100644 --- a/src/console/clients/checker/app.rs +++ b/src/console/clients/checker/app.rs @@ -58,7 +58,7 @@ pub async fn run() -> Result> { } fn tracing_stdout_init(filter: LevelFilter) { - tracing_subscriber::fmt().with_max_level(filter).init(); + tracing_subscriber::fmt().with_max_level(filter).with_ansi(false).init(); info!("logging initialized."); } diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index c780157f4..323fca1b6 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -127,7 +127,7 @@ pub async fn run() -> anyhow::Result<()> { } fn tracing_stdout_init(filter: LevelFilter) { - tracing_subscriber::fmt().with_max_level(filter).init(); + tracing_subscriber::fmt().with_max_level(filter).with_ansi(false).init(); info!("logging initialized."); } diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index dd30d9d6d..b2c72258d 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -273,7 +273,7 @@ impl Udp { .send(Started { address }) .expect("the UDP Tracker service should not be dropped"); - debug!(target: "UDP TRACKER", "Started on: udp://{}", address); + info!(target: "UDP TRACKER", "Started on: udp://{}", address); let stop = running.abort_handle(); From 7de259524724bc0036e075b4ee4df1d9fefd53c9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jun 2024 17:04:15 +0100 Subject: [PATCH 0368/1297] chore(deps): [#884] remove unused crate log We have moved to tracing crate. --- Cargo.lock | 2 -- Cargo.toml | 1 - packages/located-error/Cargo.toml | 1 - 3 files changed, 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ab7512536..c71ee890d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3904,7 +3904,6 @@ dependencies = [ "hyper-util", "lazy_static", "local-ip-address", - "log", "mockall", "multimap", "parking_lot", @@ -3977,7 +3976,6 @@ dependencies = [ name = "torrust-tracker-located-error" version = "3.0.0-alpha.12-develop" dependencies = [ - "log", "thiserror", "tracing", ] diff --git a/Cargo.toml b/Cargo.toml index 6166831e2..94ad9a02c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,7 +52,6 @@ http-body = "1.0.0" hyper = "1" hyper-util = { version = "0.1.3", features = ["http1", "http2", "tokio"] } lazy_static = "1" -log = { version = "0", features = ["release_max_level_info"] } multimap = "0" parking_lot = "0.12.1" percent-encoding = "2" diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index f34f9bc88..4b2c73178 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -15,7 +15,6 @@ rust-version.workspace = true version.workspace = true [dependencies] -log = { version = "0", features = ["release_max_level_info"] } tracing = "0.1.40" [dev-dependencies] From d6fd11a0b736a4e20abfdea02cb84c79c64f7168 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jun 2024 17:23:55 +0100 Subject: [PATCH 0369/1297] test: [#884] add test for parsing array of services from app logs The tracker can run multiple UDP or HTTP trackers. We parse the services from app output but there was not test for multiple services of the same type (UDP or HTTP tracker). --- src/console/ci/e2e/logs_parser.rs | 72 +++++++++++++++++++------------ 1 file changed, 45 insertions(+), 27 deletions(-) diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index a9277524e..2a1876a11 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -19,17 +19,19 @@ impl RunningServices { /// /// ```text /// Loading configuration from default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... - /// 2024-06-10T14:59:57.973525Z INFO torrust_tracker::bootstrap::logging: logging initialized. - /// 2024-06-10T14:59:57.974306Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 - /// 2024-06-10T14:59:57.974316Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 - /// 2024-06-10T14:59:57.974332Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled - /// 2024-06-10T14:59:57.974366Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070 - /// 2024-06-10T14:59:57.974513Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 - /// 2024-06-10T14:59:57.974521Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled - /// 2024-06-10T14:59:57.974615Z INFO API: Starting on http://127.0.0.1:1212 - /// 2024-06-10T14:59:57.974618Z INFO API: Started on http://127.0.0.1:1212 - /// 2024-06-10T14:59:57.974643Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 - /// 2024-06-10T14:59:57.974760Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 + /// 2024-06-10T16:07:39.989540Z INFO torrust_tracker::bootstrap::logging: logging initialized. + /// 2024-06-10T16:07:39.990205Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6868 + /// 2024-06-10T16:07:39.990215Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6868 + /// 2024-06-10T16:07:39.990244Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 + /// 2024-06-10T16:07:39.990255Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 + /// 2024-06-10T16:07:39.990261Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + /// 2024-06-10T16:07:39.990303Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070 + /// 2024-06-10T16:07:39.990439Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 + /// 2024-06-10T16:07:39.990448Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + /// 2024-06-10T16:07:39.990563Z INFO API: Starting on http://127.0.0.1:1212 + /// 2024-06-10T16:07:39.990565Z INFO API: Started on http://127.0.0.1:1212 + /// 2024-06-10T16:07:39.990577Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 + /// 2024-06-10T16:07:39.990638Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 /// ``` /// /// It would extract these services: @@ -48,7 +50,7 @@ impl RunningServices { /// } /// ``` /// - /// NOTICE: Using colors in the console output could affect this method + /// NOTICE: Using colors in the console output could affect this method /// due to the hidden control chars. #[must_use] pub fn parse_from_logs(logs: &str) -> Self { @@ -89,7 +91,7 @@ mod tests { #[test] fn it_should_parse_from_logs_with_valid_logs() { - let log = r#" + let logs = r#" Loading configuration from environment variable db_path = "/var/lib/torrust/tracker/database/sqlite3.db" [[udp_trackers]] @@ -103,22 +105,22 @@ mod tests { [http_api] ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" - ... - Loading configuration from file: `/etc/torrust/tracker/tracker.toml` ... - 2024-06-10T15:09:54.411031Z INFO torrust_tracker::bootstrap::logging: logging initialized. - 2024-06-10T15:09:54.415084Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 - 2024-06-10T15:09:54.415091Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 - 2024-06-10T15:09:54.415104Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled - 2024-06-10T15:09:54.415130Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070 - 2024-06-10T15:09:54.415266Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 - 2024-06-10T15:09:54.415275Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled - 2024-06-10T15:09:54.415403Z INFO API: Starting on http://127.0.0.1:1212 - 2024-06-10T15:09:54.415411Z INFO API: Started on http://127.0.0.1:1212 - 2024-06-10T15:09:54.415430Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 - 2024-06-10T15:09:54.415472Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 + + Loading configuration from default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... + 2024-06-10T16:07:39.989540Z INFO torrust_tracker::bootstrap::logging: logging initialized. + 2024-06-10T16:07:39.990244Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 + 2024-06-10T16:07:39.990255Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 + 2024-06-10T16:07:39.990261Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + 2024-06-10T16:07:39.990303Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070 + 2024-06-10T16:07:39.990439Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 + 2024-06-10T16:07:39.990448Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled + 2024-06-10T16:07:39.990563Z INFO API: Starting on http://127.0.0.1:1212 + 2024-06-10T16:07:39.990565Z INFO API: Started on http://127.0.0.1:1212 + 2024-06-10T16:07:39.990577Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 + 2024-06-10T16:07:39.990638Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 "#; - let running_services = RunningServices::parse_from_logs(log); + let running_services = RunningServices::parse_from_logs(logs); assert_eq!(running_services.udp_trackers, vec!["127.0.0.1:6969"]); assert_eq!(running_services.http_trackers, vec!["http://127.0.0.1:7070"]); @@ -128,6 +130,7 @@ mod tests { #[test] fn it_should_ignore_logs_with_no_matching_lines() { let logs = "[Other Service][INFO] Started on: 0.0.0.0:7070"; + let running_services = RunningServices::parse_from_logs(logs); assert!(running_services.udp_trackers.is_empty()); @@ -135,6 +138,21 @@ mod tests { assert!(running_services.health_checks.is_empty()); } + #[test] + fn it_should_parse_multiple_services() { + let logs = " + 2024-06-10T16:07:39.990205Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6868 + 2024-06-10T16:07:39.990215Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6868 + + 2024-06-10T16:07:39.990244Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 + 2024-06-10T16:07:39.990255Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 + "; + + let running_services = RunningServices::parse_from_logs(logs); + + assert_eq!(running_services.udp_trackers, vec!["127.0.0.1:6868", "127.0.0.1:6969"]); + } + #[test] fn it_should_replace_wildcard_ip_with_localhost() { let address = "0.0.0.0:8080"; From ec88dbfffdeac08bbc3aa69de90ffad9e2711023 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jun 2024 17:24:25 +0100 Subject: [PATCH 0370/1297] chore(deps): remove unused dependencies log and fern We have moved from crate log to tracing. --- Cargo.lock | 10 ---------- Cargo.toml | 1 - 2 files changed, 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c71ee890d..36508e261 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1259,15 +1259,6 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" -[[package]] -name = "fern" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9f0c14694cbd524c8720dd69b0e3179344f04ebb5f90f2e4a440c6ea3b2f1ee" -dependencies = [ - "log", -] - [[package]] name = "figment" version = "0.10.19" @@ -3894,7 +3885,6 @@ dependencies = [ "crossbeam-skiplist", "dashmap", "derive_more", - "fern", "figment", "futures", "futures-util", diff --git a/Cargo.toml b/Cargo.toml index 94ad9a02c..418bcb3ed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,7 +43,6 @@ clap = { version = "4", features = ["derive", "env"] } crossbeam-skiplist = "0.1" dashmap = "5.5.3" derive_more = "0" -fern = "0" figment = "0.10.18" futures = "0" futures-util = "0.3.30" From c08de7519498ea8495fb3d200ae918a4c4076f7f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Jun 2024 18:35:10 +0100 Subject: [PATCH 0371/1297] refactor: [#659] use clap and anyhow in E2E test runner You can execute the E2E runner with: ```bash cargo run --bin e2e_tests_runner -- --config-toml-path "./share/default/config/tracker.e2e.container.sqlite3.toml" ``` Or: ```bash TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.e2e.container.sqlite3.toml" cargo run --bin e2e_tests_runner ``` Or: ```bash TORRUST_TRACKER_CONFIG_TOML=$(cat "./share/default/config/tracker.e2e.container.sqlite3.toml") cargo run --bin e2e_tests_runner ``` --- .github/workflows/testing.yaml | 2 +- src/bin/e2e_tests_runner.rs | 4 +- src/console/ci/e2e/runner.rs | 85 +++++++++++++++++++++++----------- 3 files changed, 61 insertions(+), 30 deletions(-) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 620670f97..abe6f0a60 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -152,4 +152,4 @@ jobs: - id: test name: Run E2E Tests - run: cargo run --bin e2e_tests_runner ./share/default/config/tracker.e2e.container.sqlite3.toml + run: cargo run --bin e2e_tests_runner -- --config-toml-path "./share/default/config/tracker.e2e.container.sqlite3.toml" diff --git a/src/bin/e2e_tests_runner.rs b/src/bin/e2e_tests_runner.rs index b21459d2e..eb91c0d86 100644 --- a/src/bin/e2e_tests_runner.rs +++ b/src/bin/e2e_tests_runner.rs @@ -1,6 +1,6 @@ //! Program to run E2E tests. use torrust_tracker::console::ci::e2e; -fn main() { - e2e::runner::run(); +fn main() -> anyhow::Result<()> { + e2e::runner::run() } diff --git a/src/console/ci/e2e/runner.rs b/src/console/ci/e2e/runner.rs index aeb28b777..a80b65ce2 100644 --- a/src/console/ci/e2e/runner.rs +++ b/src/console/ci/e2e/runner.rs @@ -1,8 +1,26 @@ //! Program to run E2E tests. //! +//! You can execute it with (passing a TOML config file path): +//! +//! ```text +//! cargo run --bin e2e_tests_runner -- --config-toml-path "./share/default/config/tracker.e2e.container.sqlite3.toml" +//! ``` +//! +//! Or: +//! //! ```text -//! cargo run --bin e2e_tests_runner share/default/config/tracker.e2e.container.sqlite3.toml +//! TORRUST_TRACKER_CONFIG_TOML_PATH="./share/default/config/tracker.e2e.container.sqlite3.toml" cargo run --bin e2e_tests_runner" //! ``` +//! +//! You can execute it with (directly passing TOML config): +//! +//! ```text +//! TORRUST_TRACKER_CONFIG_TOML=$(cat "./share/default/config/tracker.e2e.container.sqlite3.toml") cargo run --bin e2e_tests_runner +//! ``` +use std::path::PathBuf; + +use anyhow::Context; +use clap::Parser; use tracing::info; use tracing::level_filters::LevelFilter; @@ -19,25 +37,38 @@ use crate::console::ci::e2e::tracker_checker::{self}; Should we remove the image too? */ -const NUMBER_OF_ARGUMENTS: usize = 2; const CONTAINER_IMAGE: &str = "torrust-tracker:local"; const CONTAINER_NAME_PREFIX: &str = "tracker_"; -pub struct Arguments { - pub tracker_config_path: String, +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + /// Path to the JSON configuration file. + #[clap(short, long, env = "TORRUST_TRACKER_CONFIG_TOML_PATH")] + config_toml_path: Option, + + /// Direct configuration content in JSON. + #[clap(env = "TORRUST_TRACKER_CONFIG_TOML", hide_env_values = true)] + config_toml: Option, } /// Script to run E2E tests. /// +/// # Errors +/// +/// Will return an error if it can't load the tracker configuration from arguments. +/// /// # Panics /// /// Will panic if it can't not perform any of the operations. -pub fn run() { +pub fn run() -> anyhow::Result<()> { tracing_stdout_init(LevelFilter::INFO); - let args = parse_arguments(); + let args = Args::parse(); - let tracker_config = load_tracker_configuration(&args.tracker_config_path); + let tracker_config = load_tracker_configuration(&args)?; + + info!("tracker config:\n{tracker_config}"); let mut tracker_container = TrackerContainer::new(CONTAINER_IMAGE, CONTAINER_NAME_PREFIX); @@ -80,36 +111,36 @@ pub fn run() { tracker_container.remove(); info!("Tracker container final state:\n{:#?}", tracker_container); + + Ok(()) } fn tracing_stdout_init(filter: LevelFilter) { tracing_subscriber::fmt().with_max_level(filter).with_ansi(false).init(); - info!("logging initialized."); + info!("Logging initialized."); } -fn parse_arguments() -> Arguments { - let args: Vec = std::env::args().collect(); - - if args.len() < NUMBER_OF_ARGUMENTS { - eprintln!("Usage: cargo run --bin e2e_tests_runner "); - eprintln!("For example: cargo run --bin e2e_tests_runner ./share/default/config/tracker.e2e.container.sqlite3.toml"); - std::process::exit(1); - } - - let config_path = &args[1]; - - Arguments { - tracker_config_path: config_path.to_string(), +fn load_tracker_configuration(args: &Args) -> anyhow::Result { + match (args.config_toml_path.clone(), args.config_toml.clone()) { + (Some(config_path), _) => { + info!( + "Reading tracker configuration from file: {} ...", + config_path.to_string_lossy() + ); + load_config_from_file(&config_path) + } + (_, Some(config_content)) => { + info!("Reading tracker configuration from env var ..."); + Ok(config_content) + } + _ => Err(anyhow::anyhow!("No configuration provided")), } } -fn load_tracker_configuration(tracker_config_path: &str) -> String { - info!("Reading tracker configuration from file: {} ...", tracker_config_path); - read_file(tracker_config_path) -} +fn load_config_from_file(path: &PathBuf) -> anyhow::Result { + let config = std::fs::read_to_string(path).with_context(|| format!("CSan't read config file {path:?}"))?; -fn read_file(path: &str) -> String { - std::fs::read_to_string(path).unwrap_or_else(|_| panic!("Can't read file {path}")) + Ok(config) } fn assert_there_is_at_least_one_service_per_type(running_services: &RunningServices) { From f8a9976ec90481bedbc9eedbd4a38a42d7163bfe Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 12 Jun 2024 14:40:22 +0100 Subject: [PATCH 0372/1297] docs: [#770] update benchmarking docs We are now using criterion to benchmark the torrent repository implementations. --- docs/benchmarking.md | 96 ++++++++++++------ ...ry-implementations-benchmarking-report.png | Bin 0 -> 630867 bytes 2 files changed, 63 insertions(+), 33 deletions(-) create mode 100644 docs/media/torrent-repository-implementations-benchmarking-report.png diff --git a/docs/benchmarking.md b/docs/benchmarking.md index 2a3f1f8b0..1758e0de4 100644 --- a/docs/benchmarking.md +++ b/docs/benchmarking.md @@ -96,7 +96,7 @@ Announce responses per info hash: - p100: 361 ``` -> IMPORTANT: The performance of th Torrust UDP Tracker is drastically decreased with these log levels: `info`, `debug`, `trace`. +> IMPORTANT: The performance of the Torrust UDP Tracker is drastically decreased with these log levels: `info`, `debug`, `trace`. ```output Requests out: 40719.21/second @@ -226,46 +226,76 @@ Using a PC with: ## Repository benchmarking +### Requirements + +You need to install the `gnuplot` package. + +```console +sudo apt install gnuplot +``` + +### Run + You can run it with: ```console -cargo run --release -p torrust-torrent-repository-benchmarks -- --threads 4 --sleep 0 --compare true +cargo bench -p torrust-tracker-torrent-repository ``` -It tests the different implementation for the internal torrent storage. +It tests the different implementations for the internal torrent storage. The output should be something like this: ```output -tokio::sync::RwLock> -add_one_torrent: Avg/AdjAvg: (60ns, 59ns) -update_one_torrent_in_parallel: Avg/AdjAvg: (10.909457ms, 0ns) -add_multiple_torrents_in_parallel: Avg/AdjAvg: (13.88879ms, 0ns) -update_multiple_torrents_in_parallel: Avg/AdjAvg: (7.772484ms, 7.782535ms) - -std::sync::RwLock> -add_one_torrent: Avg/AdjAvg: (43ns, 39ns) -update_one_torrent_in_parallel: Avg/AdjAvg: (4.020937ms, 4.020937ms) -add_multiple_torrents_in_parallel: Avg/AdjAvg: (5.896177ms, 5.768448ms) -update_multiple_torrents_in_parallel: Avg/AdjAvg: (3.883823ms, 3.883823ms) - -std::sync::RwLock>>> -add_one_torrent: Avg/AdjAvg: (51ns, 49ns) -update_one_torrent_in_parallel: Avg/AdjAvg: (3.252314ms, 3.149109ms) -add_multiple_torrents_in_parallel: Avg/AdjAvg: (8.411094ms, 8.411094ms) -update_multiple_torrents_in_parallel: Avg/AdjAvg: (4.106086ms, 4.106086ms) - -tokio::sync::RwLock>>> -add_one_torrent: Avg/AdjAvg: (91ns, 90ns) -update_one_torrent_in_parallel: Avg/AdjAvg: (3.542378ms, 3.435695ms) -add_multiple_torrents_in_parallel: Avg/AdjAvg: (15.651172ms, 15.651172ms) -update_multiple_torrents_in_parallel: Avg/AdjAvg: (4.368189ms, 4.257572ms) - -tokio::sync::RwLock>>> -add_one_torrent: Avg/AdjAvg: (111ns, 109ns) -update_one_torrent_in_parallel: Avg/AdjAvg: (6.590677ms, 6.808535ms) -add_multiple_torrents_in_parallel: Avg/AdjAvg: (16.572217ms, 16.30488ms) -update_multiple_torrents_in_parallel: Avg/AdjAvg: (4.073221ms, 4.000122ms) + Running benches/repository_benchmark.rs (target/release/deps/repository_benchmark-2f7830898bbdfba4) +add_one_torrent/RwLockStd + time: [60.936 ns 61.383 ns 61.764 ns] +Found 24 outliers among 100 measurements (24.00%) + 15 (15.00%) high mild + 9 (9.00%) high severe +add_one_torrent/RwLockStdMutexStd + time: [60.829 ns 60.937 ns 61.053 ns] +Found 1 outliers among 100 measurements (1.00%) + 1 (1.00%) high severe +add_one_torrent/RwLockStdMutexTokio + time: [96.034 ns 96.243 ns 96.545 ns] +Found 6 outliers among 100 measurements (6.00%) + 4 (4.00%) high mild + 2 (2.00%) high severe +add_one_torrent/RwLockTokio + time: [108.25 ns 108.66 ns 109.06 ns] +Found 2 outliers among 100 measurements (2.00%) + 2 (2.00%) low mild +add_one_torrent/RwLockTokioMutexStd + time: [109.03 ns 109.11 ns 109.19 ns] +Found 4 outliers among 100 measurements (4.00%) + 1 (1.00%) low mild + 1 (1.00%) high mild + 2 (2.00%) high severe +Benchmarking add_one_torrent/RwLockTokioMutexTokio: Collecting 100 samples in estimated 1.0003 s (7.1M iterationsadd_one_torrent/RwLockTokioMutexTokio + time: [139.64 ns 140.11 ns 140.62 ns] +``` + +After running it you should have a new directory containing the criterion reports: + +```console +target/criterion/ +├── add_multiple_torrents_in_parallel +├── add_one_torrent +├── report +├── update_multiple_torrents_in_parallel +└── update_one_torrent_in_parallel ``` +You can see one report for each of the operations we are considering for benchmarking: + +- Add multiple torrents in parallel. +- Add one torrent. +- Update multiple torrents in parallel. +- Update one torrent in parallel. + +Each report look like the following: + +![Torrent repository implementations benchmarking report](./media/torrent-repository-implementations-benchmarking-report.png) + ## Other considerations -We are testing new repository implementations that allow concurrent writes. See . +If you are interested in knowing more about the tracker performance or contribute to improve its performance you ca join the [performance optimizations discussion](https://github.com/torrust/torrust-tracker/discussions/774). diff --git a/docs/media/torrent-repository-implementations-benchmarking-report.png b/docs/media/torrent-repository-implementations-benchmarking-report.png new file mode 100644 index 0000000000000000000000000000000000000000..ee87c6d42292b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SN%p1p literal 0 HcmV?d00001 From 322b976a087535c1710f15d87684f70f7787e150 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Jun 2024 15:38:06 +0100 Subject: [PATCH 0373/1297] chore(deps): update dependencies ```s cargo update Updating crates.io index Locking 35 packages to latest compatible versions Updating backtrace v0.3.72 -> v0.3.73 Updating clap v4.5.6 -> v4.5.7 Updating clap_builder v4.5.6 -> v4.5.7 Adding displaydoc v0.2.4 Updating http-body-util v0.1.1 -> v0.1.2 Updating httparse v1.8.0 -> v1.9.3 Adding icu_collections v1.5.0 Adding icu_locid v1.5.0 Adding icu_locid_transform v1.5.0 Adding icu_locid_transform_data v1.5.0 Adding icu_normalizer v1.5.0 Adding icu_normalizer_data v1.5.0 Adding icu_properties v1.5.0 Adding icu_properties_data v1.5.0 Adding icu_provider v1.5.0 Adding icu_provider_macros v1.5.0 Updating idna v0.5.0 -> v1.0.0 Adding litemap v0.7.3 Updating memchr v2.7.2 -> v2.7.4 Updating object v0.35.0 -> v0.36.0 Updating redox_syscall v0.5.1 -> v0.5.2 Adding stable_deref_trait v1.2.0 Adding synstructure v0.13.1 Adding tinystr v0.7.6 Removing unicode-bidi v0.3.15 Removing unicode-normalization v0.1.23 Updating url v2.5.0 -> v2.5.1 Adding utf16_iter v1.0.5 Adding utf8_iter v1.0.4 Adding write16 v1.0.0 Adding writeable v0.5.5 Adding yoke v0.7.4 Adding yoke-derive v0.7.4 Adding zerofrom v0.1.4 Adding zerofrom-derive v0.1.4 Adding zerovec v0.10.2 Adding zerovec-derive v0.10.2 ``` --- Cargo.lock | 316 ++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 278 insertions(+), 38 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 36508e261..1c10516b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -507,9 +507,9 @@ dependencies = [ [[package]] name = "backtrace" -version = "0.3.72" +version = "0.3.73" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17c6a35df3749d2e8bb1b7b21a976d82b15548788d2735b9d82f329268f71a11" +checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" dependencies = [ "addr2line", "cc", @@ -821,9 +821,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.6" +version = "4.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9689a29b593160de5bc4aacab7b5d54fb52231de70122626c178e6a368994c7" +checksum = "5db83dced34638ad474f39f250d7fea9598bdd239eaced1bdf45d597da0f433f" dependencies = [ "clap_builder", "clap_derive", @@ -831,9 +831,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.6" +version = "4.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e5387378c84f6faa26890ebf9f0a92989f8873d4d380467bcd0d8d8620424df" +checksum = "f7e204572485eb3fbf28f871612191521df159bc3e15a9f5064c66dba3a8c05f" dependencies = [ "anstream", "anstyle", @@ -1148,6 +1148,17 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "displaydoc" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] + [[package]] name = "downcast" version = "0.11.0" @@ -1676,12 +1687,12 @@ dependencies = [ [[package]] name = "http-body-util" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0475f8b2ac86659c21b64320d5d653f9efe42acd2a4e560073ec61a155a34f1d" +checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" dependencies = [ "bytes", - "futures-core", + "futures-util", "http", "http-body", "pin-project-lite", @@ -1689,9 +1700,9 @@ dependencies = [ [[package]] name = "httparse" -version = "1.8.0" +version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" +checksum = "d0e7a4dd27b9476dc40cb050d3632d3bba3a70ddbff012285f7f8559a1e7e545" [[package]] name = "httpdate" @@ -1779,6 +1790,124 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_collections" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locid" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locid_transform" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_locid_transform_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locid_transform_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" + +[[package]] +name = "icu_normalizer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" + +[[package]] +name = "icu_properties" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f8ac670d7422d7f76b32e17a5db556510825b29ec9154f235977c9caba61036" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locid_transform", + "icu_properties_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" + +[[package]] +name = "icu_provider" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_provider_macros", + "stable_deref_trait", + "tinystr", + "writeable", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_provider_macros" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -1787,12 +1916,14 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "idna" -version = "0.5.0" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" +checksum = "4716a3a0933a1d01c2f72450e89596eb51dd34ef3c211ccd875acdf1f8fe47ed" dependencies = [ - "unicode-bidi", - "unicode-normalization", + "icu_normalizer", + "icu_properties", + "smallvec", + "utf8_iter", ] [[package]] @@ -2061,6 +2192,12 @@ version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" +[[package]] +name = "litemap" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" + [[package]] name = "local-ip-address" version = "0.6.1" @@ -2109,9 +2246,9 @@ checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" [[package]] name = "memchr" -version = "2.7.2" +version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "mime" @@ -2386,9 +2523,9 @@ dependencies = [ [[package]] name = "object" -version = "0.35.0" +version = "0.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8ec7ab813848ba4522158d5517a6093db1ded27575b070f4177b8d12b41db5e" +checksum = "576dfe1fc8f9df304abb159d767a29d0476f7750fbf8aa7ad07816004a207434" dependencies = [ "memchr", ] @@ -2902,9 +3039,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "469052894dcb553421e483e4209ee581a45100d31b4018de03e5a7ad86374a7e" +checksum = "c82cf8cff14456045f55ec4241383baeff27af886adb72ffb2162f99911de0fd" dependencies = [ "bitflags 2.5.0", ] @@ -3525,6 +3662,12 @@ version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + [[package]] name = "static_assertions" version = "1.1.0" @@ -3593,6 +3736,17 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" +[[package]] +name = "synstructure" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] + [[package]] name = "system-configuration" version = "0.5.1" @@ -3725,6 +3879,16 @@ dependencies = [ "time-core", ] +[[package]] +name = "tinystr" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tinytemplate" version = "1.2.1" @@ -4172,27 +4336,12 @@ dependencies = [ "version_check", ] -[[package]] -name = "unicode-bidi" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" - [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" -[[package]] -name = "unicode-normalization" -version = "0.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" -dependencies = [ - "tinyvec", -] - [[package]] name = "untrusted" version = "0.9.0" @@ -4201,15 +4350,27 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" +checksum = "f7c25da092f0a868cdf09e8674cd3b7ef3a7d92a24253e663a2fb85e2496de56" dependencies = [ "form_urlencoded", "idna", "percent-encoding", ] +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "utf8parse" version = "0.2.2" @@ -4564,6 +4725,18 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" + [[package]] name = "wyz" version = "0.5.1" @@ -4579,6 +4752,30 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" +[[package]] +name = "yoke" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" +dependencies = [ + "serde", + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.7.34" @@ -4600,6 +4797,49 @@ dependencies = [ "syn 2.0.66", ] +[[package]] +name = "zerofrom" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", + "synstructure", +] + +[[package]] +name = "zerovec" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb2cc8827d6c0994478a15c53f374f46fbd41bea663d809b14744bc42e6b109c" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97cf56601ee5052b4417d90c8755c6683473c926039908196cf35d99f893ebe7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] + [[package]] name = "zstd" version = "0.13.1" From a88082aa40c99a1d59082b396210e3f2e39f68df Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Jun 2024 16:22:43 +0100 Subject: [PATCH 0374/1297] fix: [#893] enable color in logs --- src/bootstrap/logging.rs | 2 +- src/console/ci/e2e/logs_parser.rs | 57 +++++++++++++++++++++++++----- src/console/ci/e2e/runner.rs | 2 +- src/console/clients/checker/app.rs | 2 +- src/console/clients/udp/app.rs | 2 +- 5 files changed, 52 insertions(+), 13 deletions(-) diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index 5194f06ea..14756565f 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -46,7 +46,7 @@ fn config_level_or_default(log_level: &Option) -> LevelFilter { } fn tracing_stdout_init(filter: LevelFilter, style: &TraceStyle) { - let builder = tracing_subscriber::fmt().with_max_level(filter).with_ansi(false); + let builder = tracing_subscriber::fmt().with_max_level(filter).with_ansi(true); let () = match style { TraceStyle::Default => builder.init(), diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index 2a1876a11..ff4028f80 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -1,9 +1,16 @@ //! Utilities to parse Torrust Tracker logs. use serde::{Deserialize, Serialize}; -const UDP_TRACKER_PATTERN: &str = "UDP TRACKER: Started on: udp://"; -const HTTP_TRACKER_PATTERN: &str = "HTTP TRACKER: Started on: "; -const HEALTH_CHECK_PATTERN: &str = "HEALTH CHECK API: Started on: "; +const INFO_LOG_LEVEL: &str = "INFO"; + +const UDP_TRACKER_TARGET: &str = "UDP TRACKER"; +const UDP_TRACKER_SOCKET_ADDR_START_PATTERN: &str = "Started on: udp://"; + +const HTTP_TRACKER_TARGET: &str = "HTTP TRACKER"; +const HTTP_TRACKER_URL_START_PATTERN: &str = "Started on: "; + +const HEALTH_CHECK_TARGET: &str = "HEALTH CHECK API"; +const HEALTH_CHECK_URL_START_PATTERN: &str = "Started on: "; #[derive(Serialize, Deserialize, Debug, Default)] pub struct RunningServices { @@ -59,11 +66,11 @@ impl RunningServices { let mut health_checks: Vec = Vec::new(); for line in logs.lines() { - if let Some(address) = Self::extract_address_if_matches(line, UDP_TRACKER_PATTERN) { + if let Some(address) = Self::extract_udp_tracker_url(line) { udp_trackers.push(address); - } else if let Some(address) = Self::extract_address_if_matches(line, HTTP_TRACKER_PATTERN) { + } else if let Some(address) = Self::extract_http_tracker_url(line) { http_trackers.push(address); - } else if let Some(address) = Self::extract_address_if_matches(line, HEALTH_CHECK_PATTERN) { + } else if let Some(address) = Self::extract_health_check_api_url(line) { health_checks.push(format!("{address}/health_check")); } } @@ -75,9 +82,32 @@ impl RunningServices { } } - fn extract_address_if_matches(line: &str, pattern: &str) -> Option { - line.find(pattern) - .map(|start| Self::replace_wildcard_ip_with_localhost(line[start + pattern.len()..].trim())) + fn extract_udp_tracker_url(line: &str) -> Option { + if !line.contains(INFO_LOG_LEVEL) || !line.contains(UDP_TRACKER_TARGET) { + return None; + }; + + line.find(UDP_TRACKER_SOCKET_ADDR_START_PATTERN).map(|start| { + Self::replace_wildcard_ip_with_localhost(line[start + UDP_TRACKER_SOCKET_ADDR_START_PATTERN.len()..].trim()) + }) + } + + fn extract_http_tracker_url(line: &str) -> Option { + if !line.contains(INFO_LOG_LEVEL) || !line.contains(HTTP_TRACKER_TARGET) { + return None; + }; + + line.find(HTTP_TRACKER_URL_START_PATTERN) + .map(|start| Self::replace_wildcard_ip_with_localhost(line[start + HTTP_TRACKER_URL_START_PATTERN.len()..].trim())) + } + + fn extract_health_check_api_url(line: &str) -> Option { + if !line.contains(INFO_LOG_LEVEL) || !line.contains(HEALTH_CHECK_TARGET) { + return None; + }; + + line.find(HEALTH_CHECK_URL_START_PATTERN) + .map(|start| Self::replace_wildcard_ip_with_localhost(line[start + HEALTH_CHECK_URL_START_PATTERN.len()..].trim())) } fn replace_wildcard_ip_with_localhost(address: &str) -> String { @@ -127,6 +157,15 @@ mod tests { assert_eq!(running_services.health_checks, vec!["http://127.0.0.1:1313/health_check"]); } + #[test] + fn it_should_support_colored_output() { + let logs = "\x1b[2m2024-06-14T14:40:13.028824Z\x1b[0m \x1b[33mINFO\x1b[0m \x1b[2mUDP TRACKER\x1b[0m: \x1b[37mStarted on: udp://0.0.0.0:6969\x1b[0m"; + + let running_services = RunningServices::parse_from_logs(logs); + + assert_eq!(running_services.udp_trackers, vec!["127.0.0.1:6969"]); + } + #[test] fn it_should_ignore_logs_with_no_matching_lines() { let logs = "[Other Service][INFO] Started on: 0.0.0.0:7070"; diff --git a/src/console/ci/e2e/runner.rs b/src/console/ci/e2e/runner.rs index a80b65ce2..a3d61894e 100644 --- a/src/console/ci/e2e/runner.rs +++ b/src/console/ci/e2e/runner.rs @@ -116,7 +116,7 @@ pub fn run() -> anyhow::Result<()> { } fn tracing_stdout_init(filter: LevelFilter) { - tracing_subscriber::fmt().with_max_level(filter).with_ansi(false).init(); + tracing_subscriber::fmt().with_max_level(filter).init(); info!("Logging initialized."); } diff --git a/src/console/clients/checker/app.rs b/src/console/clients/checker/app.rs index ade1d4820..84802688d 100644 --- a/src/console/clients/checker/app.rs +++ b/src/console/clients/checker/app.rs @@ -58,7 +58,7 @@ pub async fn run() -> Result> { } fn tracing_stdout_init(filter: LevelFilter) { - tracing_subscriber::fmt().with_max_level(filter).with_ansi(false).init(); + tracing_subscriber::fmt().with_max_level(filter).init(); info!("logging initialized."); } diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index 323fca1b6..c780157f4 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -127,7 +127,7 @@ pub async fn run() -> anyhow::Result<()> { } fn tracing_stdout_init(filter: LevelFilter) { - tracing_subscriber::fmt().with_max_level(filter).with_ansi(false).init(); + tracing_subscriber::fmt().with_max_level(filter).init(); info!("logging initialized."); } From a293373bb271d543bf0f03ef0ebb3807148b55d7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Jun 2024 16:36:14 +0100 Subject: [PATCH 0375/1297] chore(deps): add cargo dependency regex To parse cargo logs. --- Cargo.lock | 1 + Cargo.toml | 1 + 2 files changed, 2 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 1c10516b2..7a54063bf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4067,6 +4067,7 @@ dependencies = [ "r2d2_mysql", "r2d2_sqlite", "rand", + "regex", "reqwest", "ringbuf", "serde", diff --git a/Cargo.toml b/Cargo.toml index 418bcb3ed..8b58154ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,6 +59,7 @@ r2d2 = "0" r2d2_mysql = "24" r2d2_sqlite = { version = "0", features = ["bundled"] } rand = "0" +regex = "1.10.5" reqwest = { version = "0", features = ["json"] } ringbuf = "0" serde = { version = "1", features = ["derive"] } From eb928bcd041ba9942b777d150bf86b95b07829c8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Jun 2024 16:44:32 +0100 Subject: [PATCH 0376/1297] fix: [#893] enable color for logs It was disabled becuase parsing lgos to extract the services URLs was not working due to hidden color chars. This changes the parser to ignore color chars. --- src/console/ci/e2e/logs_parser.rs | 77 ++++++++++++++----------------- 1 file changed, 34 insertions(+), 43 deletions(-) diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index ff4028f80..a4024f29d 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -1,16 +1,11 @@ //! Utilities to parse Torrust Tracker logs. +use regex::Regex; use serde::{Deserialize, Serialize}; const INFO_LOG_LEVEL: &str = "INFO"; - -const UDP_TRACKER_TARGET: &str = "UDP TRACKER"; -const UDP_TRACKER_SOCKET_ADDR_START_PATTERN: &str = "Started on: udp://"; - -const HTTP_TRACKER_TARGET: &str = "HTTP TRACKER"; -const HTTP_TRACKER_URL_START_PATTERN: &str = "Started on: "; - -const HEALTH_CHECK_TARGET: &str = "HEALTH CHECK API"; -const HEALTH_CHECK_URL_START_PATTERN: &str = "Started on: "; +const UDP_TRACKER_LOG_TARGET: &str = "UDP TRACKER"; +const HTTP_TRACKER_LOG_TARGET: &str = "HTTP TRACKER"; +const HEALTH_CHECK_API_LOG_TARGET: &str = "HEALTH CHECK API"; #[derive(Serialize, Deserialize, Debug, Default)] pub struct RunningServices { @@ -59,19 +54,43 @@ impl RunningServices { /// /// NOTICE: Using colors in the console output could affect this method /// due to the hidden control chars. + /// + /// # Panics + /// + /// Will panic is the regular expression to parse the services can't be compiled. #[must_use] pub fn parse_from_logs(logs: &str) -> Self { let mut udp_trackers: Vec = Vec::new(); let mut http_trackers: Vec = Vec::new(); let mut health_checks: Vec = Vec::new(); + let udp_re = Regex::new(r"Started on: udp://([0-9.]+:[0-9]+)").unwrap(); + let http_re = Regex::new(r"Started on: (https?://[0-9.]+:[0-9]+)").unwrap(); // DevSkim: ignore DS137138 + let health_re = Regex::new(r"Started on: (https?://[0-9.]+:[0-9]+)").unwrap(); // DevSkim: ignore DS137138 + let ansi_escape_re = Regex::new(r"\x1b\[[0-9;]*m").unwrap(); + for line in logs.lines() { - if let Some(address) = Self::extract_udp_tracker_url(line) { - udp_trackers.push(address); - } else if let Some(address) = Self::extract_http_tracker_url(line) { - http_trackers.push(address); - } else if let Some(address) = Self::extract_health_check_api_url(line) { - health_checks.push(format!("{address}/health_check")); + let clean_line = ansi_escape_re.replace_all(line, ""); + + if !line.contains(INFO_LOG_LEVEL) { + continue; + }; + + if line.contains(UDP_TRACKER_LOG_TARGET) { + if let Some(captures) = udp_re.captures(&clean_line) { + let address = Self::replace_wildcard_ip_with_localhost(&captures[1]); + udp_trackers.push(address); + } + } else if line.contains(HTTP_TRACKER_LOG_TARGET) { + if let Some(captures) = http_re.captures(&clean_line) { + let address = Self::replace_wildcard_ip_with_localhost(&captures[1]); + http_trackers.push(address); + } + } else if line.contains(HEALTH_CHECK_API_LOG_TARGET) { + if let Some(captures) = health_re.captures(&clean_line) { + let address = format!("{}/health_check", Self::replace_wildcard_ip_with_localhost(&captures[1])); + health_checks.push(address); + } } } @@ -82,34 +101,6 @@ impl RunningServices { } } - fn extract_udp_tracker_url(line: &str) -> Option { - if !line.contains(INFO_LOG_LEVEL) || !line.contains(UDP_TRACKER_TARGET) { - return None; - }; - - line.find(UDP_TRACKER_SOCKET_ADDR_START_PATTERN).map(|start| { - Self::replace_wildcard_ip_with_localhost(line[start + UDP_TRACKER_SOCKET_ADDR_START_PATTERN.len()..].trim()) - }) - } - - fn extract_http_tracker_url(line: &str) -> Option { - if !line.contains(INFO_LOG_LEVEL) || !line.contains(HTTP_TRACKER_TARGET) { - return None; - }; - - line.find(HTTP_TRACKER_URL_START_PATTERN) - .map(|start| Self::replace_wildcard_ip_with_localhost(line[start + HTTP_TRACKER_URL_START_PATTERN.len()..].trim())) - } - - fn extract_health_check_api_url(line: &str) -> Option { - if !line.contains(INFO_LOG_LEVEL) || !line.contains(HEALTH_CHECK_TARGET) { - return None; - }; - - line.find(HEALTH_CHECK_URL_START_PATTERN) - .map(|start| Self::replace_wildcard_ip_with_localhost(line[start + HEALTH_CHECK_URL_START_PATTERN.len()..].trim())) - } - fn replace_wildcard_ip_with_localhost(address: &str) -> String { address.replace("0.0.0.0", "127.0.0.1") } From 3c715fbbf7fd4d1e934361064972ae676e94ee95 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Jun 2024 10:24:25 +0100 Subject: [PATCH 0377/1297] fix: [#898] docker build error: failed to load bitcode of module criterion Command: ``` docker build --target release --tag torrust-tracker:release --file Containerfile . ``` Error: ```s => ERROR [build 3/3] RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive- 56.8s ------ > [build 3/3] RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/torrust-tracker.tar.zst --release: 0.674 Compiling torrust-tracker-located-error v3.0.0-alpha.12-develop (/build/src/packages/located-error) 0.675 Compiling torrust-tracker-primitives v3.0.0-alpha.12-develop (/build/src/packages/primitives) 0.679 Compiling torrust-tracker-contrib-bencode v3.0.0-alpha.12-develop (/build/src/contrib/bencode) 0.763 Compiling torrust-tracker-configuration v3.0.0-alpha.12-develop (/build/src/packages/configuration) 0.763 Compiling torrust-tracker-clock v3.0.0-alpha.12-develop (/build/src/packages/clock) 0.936 Compiling torrust-tracker-torrent-repository v3.0.0-alpha.12-develop (/build/src/packages/torrent-repository) 0.936 Compiling torrust-tracker-test-helpers v3.0.0-alpha.12-develop (/build/src/packages/test-helpers) 1.181 Compiling torrust-tracker v3.0.0-alpha.12-develop (/build/src) 1.891 warning: Invalid value (Producer: 'LLVM18.1.7-rust-1.79.0-stable' Reader: 'LLVM 18.1.7-rust-1.79.0-stable') 1.891 1.891 error: failed to load bitcode of module "criterion-af9a3f7183f1573d.criterion.b69900c842eb33fa-cgu.08.rcgu.o": 1.891 1.991 warning: `torrust-tracker-contrib-bencode` (bench "bencode_benchmark") generated 1 warning 1.991 error: could not compile `torrust-tracker-contrib-bencode` (bench "bencode_benchmark") due to 1 previous error; 1 warning emitted 1.991 warning: build failed, waiting for other jobs to finish... 3.936 warning: `torrust-tracker-torrent-repository` (bench "repository_benchmark") generated 1 warning (1 duplicate) 3.936 error: could not compile `torrust-tracker-torrent-repository` (bench "repository_benchmark") due to 1 previous error; 1 warning emitted 56.80 error: command `/usr/local/rustup/toolchains/1.79.0-x86_64-unknown-linux-gnu/bin/cargo test --no-run --message-format json-render-diagnostics --workspace --examples --tests --benches --all-targets --all-features --release` exited with code 101 ------ Containerfile:61 -------------------- 59 | WORKDIR /build/src 60 | COPY . /build/src 61 | >>> RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/torrust-tracker.tar.zst --release 62 | 63 | -------------------- ERROR: failed to solve: process "/bin/sh -c cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/torrust-tracker.tar.zst --release" did not complete successfully: exit code: 101 ``` - Docker: version 25.0.2, build 29cf629 - Rust: nightly-x86_64-unknown-linux-gnu (default). rustc 1.81.0-nightly (d7f6ebace 2024-06-16) --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 8b58154ec..072a21a7e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -104,7 +104,7 @@ members = [ [profile.dev] debug = 1 -lto = "thin" +lto = "fat" opt-level = 1 [profile.release] From ef9461a5b98d59f081935185074245da483d3f2b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Jun 2024 09:48:17 +0100 Subject: [PATCH 0378/1297] feat!: [#878] extract logging and core section in toml config files --- Containerfile | 4 +-- compose.yaml | 2 +- docs/benchmarking.md | 2 ++ docs/containers.md | 2 +- packages/configuration/src/v1/core.rs | 19 ++++++------- packages/configuration/src/v1/logging.rs | 27 +++++++++++++++++++ packages/configuration/src/v1/mod.rs | 21 +++++++++++++-- packages/test-helpers/src/configuration.rs | 2 +- share/container/entry_script_sh | 10 +++---- .../config/tracker.container.mysql.toml | 1 + .../config/tracker.container.sqlite3.toml | 1 + .../config/tracker.e2e.container.sqlite3.toml | 1 + .../config/tracker.udp.benchmarking.toml | 3 +++ src/bootstrap/logging.rs | 2 +- src/core/mod.rs | 3 +++ src/lib.rs | 5 +++- 16 files changed, 80 insertions(+), 25 deletions(-) create mode 100644 packages/configuration/src/v1/logging.rs diff --git a/Containerfile b/Containerfile index 79fae692f..cdd70e337 100644 --- a/Containerfile +++ b/Containerfile @@ -96,7 +96,7 @@ RUN ["/busybox/cp", "-sp", "/busybox/sh","/busybox/cat","/busybox/ls","/busybox/ COPY --from=gcc --chmod=0555 /usr/local/bin/su-exec /bin/su-exec ARG TORRUST_TRACKER_CONFIG_TOML_PATH="/etc/torrust/tracker/tracker.toml" -ARG TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER="Sqlite3" +ARG TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER="Sqlite3" ARG USER_ID=1000 ARG UDP_PORT=6969 ARG HTTP_PORT=7070 @@ -104,7 +104,7 @@ ARG API_PORT=1212 ARG HEALTH_CHECK_API_PORT=1313 ENV TORRUST_TRACKER_CONFIG_TOML_PATH=${TORRUST_TRACKER_CONFIG_TOML_PATH} -ENV TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER} +ENV TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER} ENV USER_ID=${USER_ID} ENV UDP_PORT=${UDP_PORT} ENV HTTP_PORT=${HTTP_PORT} diff --git a/compose.yaml b/compose.yaml index 1d425c743..a02302a26 100644 --- a/compose.yaml +++ b/compose.yaml @@ -4,7 +4,7 @@ services: image: torrust-tracker:release tty: true environment: - - TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER:-MySQL} + - TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER:-MySQL} - TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN=${TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN:-MyAccessToken} networks: - server_side diff --git a/docs/benchmarking.md b/docs/benchmarking.md index 1758e0de4..67b680fdc 100644 --- a/docs/benchmarking.md +++ b/docs/benchmarking.md @@ -29,6 +29,7 @@ cargo build --release -p aquatic_udp_load_test Run the tracker with UDP service enabled and other services disabled and set log level to `error`. ```toml +[logging] log_level = "error" [[udp_trackers]] @@ -163,6 +164,7 @@ Announce responses per info hash: Run the tracker with UDP service enabled and other services disabled and set log level to `error`. ```toml +[logging] log_level = "error" [[udp_trackers]] diff --git a/docs/containers.md b/docs/containers.md index a0ba59d4b..ff15cd7cc 100644 --- a/docs/containers.md +++ b/docs/containers.md @@ -149,7 +149,7 @@ The following environmental variables can be set: - `TORRUST_TRACKER_CONFIG_TOML_PATH` - The in-container path to the tracker configuration file, (default: `"/etc/torrust/tracker/tracker.toml"`). - `TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN` - Override of the admin token. If set, this value overrides any value set in the config. -- `TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER` - The database type used for the container, (options: `Sqlite3`, `MySQL`, default `Sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. +- `TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER` - The database type used for the container, (options: `Sqlite3`, `MySQL`, default `Sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. - `TORRUST_TRACKER_CONFIG_TOML` - Load config from this environmental variable instead from a file, (i.e: `TORRUST_TRACKER_CONFIG_TOML=$(cat tracker-tracker.toml)`). - `USER_ID` - The user id for the runtime crated `torrust` user. Please Note: This user id should match the ownership of the host-mapped volumes, (default `1000`). - `UDP_PORT` - The port for the UDP tracker. This should match the port used in the configuration, (default `6969`). diff --git a/packages/configuration/src/v1/core.rs b/packages/configuration/src/v1/core.rs index 5d00c67ab..ae66f54fa 100644 --- a/packages/configuration/src/v1/core.rs +++ b/packages/configuration/src/v1/core.rs @@ -3,15 +3,11 @@ use std::net::{IpAddr, Ipv4Addr}; use serde::{Deserialize, Serialize}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; -use crate::{AnnouncePolicy, LogLevel}; +use crate::AnnouncePolicy; #[allow(clippy::struct_excessive_bools)] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct Core { - /// Logging level. Possible values are: `Off`, `Error`, `Warn`, `Info`, - /// `Debug` and `Trace`. Default is `Info`. - #[serde(default = "Core::default_log_level")] - pub log_level: Option, /// Tracker mode. See [`TrackerMode`] for more information. #[serde(default = "Core::default_mode")] pub mode: TrackerMode, @@ -20,6 +16,7 @@ pub struct Core { /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. #[serde(default = "Core::default_db_driver")] pub db_driver: DatabaseDriver, + /// Database connection string. The format depends on the database driver. /// For `Sqlite3`, the format is `path/to/database.db`, for example: /// `./storage/tracker/lib/database/sqlite3.db`. @@ -35,11 +32,13 @@ pub struct Core { /// See [`AnnouncePolicy::interval_min`] #[serde(default = "AnnouncePolicy::default_interval_min")] pub min_announce_interval: u32, + /// Weather the tracker is behind a reverse proxy or not. /// If the tracker is behind a reverse proxy, the `X-Forwarded-For` header /// sent from the proxy will be used to get the client's IP address. #[serde(default = "Core::default_on_reverse_proxy")] pub on_reverse_proxy: bool, + /// The external IP address of the tracker. If the client is using a /// loopback IP address, this IP address will be used instead. If the peer /// is using a loopback IP address, the tracker assumes that the peer is @@ -47,6 +46,7 @@ pub struct Core { /// address instead. #[serde(default = "Core::default_external_ip")] pub external_ip: Option, + /// 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. @@ -54,6 +54,7 @@ pub struct Core { /// information about the collected metrics. #[serde(default = "Core::default_tracker_usage_statistics")] pub tracker_usage_statistics: bool, + /// If enabled the tracker will persist the number of completed downloads. /// That's how many times a torrent has been downloaded completely. #[serde(default = "Core::default_persistent_torrent_completed_stat")] @@ -65,10 +66,12 @@ pub struct Core { /// time, it will be removed from the torrent peer list. #[serde(default = "Core::default_max_peer_timeout")] pub max_peer_timeout: u32, + /// Interval in seconds that the cleanup job will run to remove inactive /// peers from the torrent peer list. #[serde(default = "Core::default_inactive_peer_cleanup_interval")] pub inactive_peer_cleanup_interval: u64, + /// If enabled, the tracker will remove torrents that have no peers. /// The clean up torrent job runs every `inactive_peer_cleanup_interval` /// seconds and it removes inactive peers. Eventually, the peer list of a @@ -83,7 +86,6 @@ impl Default for Core { let announce_policy = AnnouncePolicy::default(); Self { - log_level: Self::default_log_level(), mode: Self::default_mode(), db_driver: Self::default_db_driver(), db_path: Self::default_db_path(), @@ -101,11 +103,6 @@ impl Default for Core { } impl Core { - #[allow(clippy::unnecessary_wraps)] - fn default_log_level() -> Option { - Some(LogLevel::Info) - } - fn default_mode() -> TrackerMode { TrackerMode::Public } diff --git a/packages/configuration/src/v1/logging.rs b/packages/configuration/src/v1/logging.rs new file mode 100644 index 000000000..c85564a05 --- /dev/null +++ b/packages/configuration/src/v1/logging.rs @@ -0,0 +1,27 @@ +use serde::{Deserialize, Serialize}; + +use crate::LogLevel; + +#[allow(clippy::struct_excessive_bools)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct Logging { + /// Logging level. Possible values are: `Off`, `Error`, `Warn`, `Info`, + /// `Debug` and `Trace`. Default is `Info`. + #[serde(default = "Logging::default_log_level")] + pub log_level: Option, +} + +impl Default for Logging { + fn default() -> Self { + Self { + log_level: Self::default_log_level(), + } + } +} + +impl Logging { + #[allow(clippy::unnecessary_wraps)] + fn default_log_level() -> Option { + Some(LogLevel::Info) + } +} diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 8d45270b8..809970506 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -193,7 +193,10 @@ //! The default configuration is: //! //! ```toml +//! [logging] //! log_level = "info" +//! +//! [core] //! mode = "public" //! db_driver = "Sqlite3" //! db_path = "./storage/tracker/lib/database/sqlite3.db" @@ -233,6 +236,7 @@ pub mod core; pub mod health_check_api; pub mod http_tracker; +pub mod logging; pub mod tracker_api; pub mod udp_tracker; @@ -241,6 +245,7 @@ use std::net::IpAddr; use figment::providers::{Env, Format, Serialized, Toml}; use figment::Figment; +use logging::Logging; use serde::{Deserialize, Serialize}; use self::core::Core; @@ -258,19 +263,25 @@ const CONFIG_OVERRIDE_SEPARATOR: &str = "__"; /// Core configuration for the tracker. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)] pub struct Configuration { + /// Logging configuration + pub logging: Logging, + /// Core configuration. - #[serde(flatten)] pub core: Core, + /// The list of UDP trackers the tracker is running. Each UDP tracker /// represents a UDP server that the tracker is running and it has its own /// configuration. pub udp_trackers: Vec, + /// The list of HTTP trackers the tracker is running. Each HTTP tracker /// represents a HTTP server that the tracker is running and it has its own /// configuration. pub http_trackers: Vec, + /// The HTTP API configuration. pub http_api: HttpApi, + /// The Health Check API configuration. pub health_check_api: HealthCheckApi, } @@ -278,6 +289,7 @@ pub struct Configuration { impl Default for Configuration { fn default() -> Self { Self { + logging: Logging::default(), core: Core::default(), udp_trackers: vec![UdpTracker::default()], http_trackers: vec![HttpTracker::default()], @@ -365,7 +377,10 @@ mod tests { #[cfg(test)] fn default_config_toml() -> String { - let config = r#"log_level = "info" + let config = r#"[logging] + log_level = "info" + + [core] mode = "public" db_driver = "Sqlite3" db_path = "./storage/tracker/lib/database/sqlite3.db" @@ -475,6 +490,7 @@ mod tests { fn default_configuration_could_be_overwritten_from_a_single_env_var_with_toml_contents() { figment::Jail::expect_with(|_jail| { let config_toml = r#" + [core] db_path = "OVERWRITTEN DEFAULT DB PATH" "# .to_string(); @@ -498,6 +514,7 @@ mod tests { jail.create_file( "tracker.toml", r#" + [core] db_path = "OVERWRITTEN DEFAULT DB PATH" "#, )?; diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 15ecd5280..c35d0a851 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -29,7 +29,7 @@ pub fn ephemeral() -> Configuration { let mut config = Configuration::default(); - config.core.log_level = Some(LogLevel::Off); // Change to `debug` for tests debugging + config.logging.log_level = Some(LogLevel::Off); // Change to `debug` for tests debugging // Ephemeral socket address for API let api_port = 0u16; diff --git a/share/container/entry_script_sh b/share/container/entry_script_sh index 8c704ea67..51df717c6 100644 --- a/share/container/entry_script_sh +++ b/share/container/entry_script_sh @@ -26,8 +26,8 @@ chmod -R 2770 /var/lib/torrust /var/log/torrust /etc/torrust # Install the database and config: -if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER" ]; then - if cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER" "Sqlite3"; then +if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER" ]; then + if cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER" "Sqlite3"; then # Select Sqlite3 empty database default_database="/usr/share/torrust/default/database/tracker.sqlite3.db" @@ -35,7 +35,7 @@ if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER" ]; then # Select Sqlite3 default configuration default_config="/usr/share/torrust/default/config/tracker.container.sqlite3.toml" - elif cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER" "MySQL"; then + elif cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER" "MySQL"; then # (no database file needed for MySQL) @@ -43,12 +43,12 @@ if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER" ]; then default_config="/usr/share/torrust/default/config/tracker.container.mysql.toml" else - echo "Error: Unsupported Database Type: \"$TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER\"." + echo "Error: Unsupported Database Type: \"$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER\"." echo "Please Note: Supported Database Types: \"Sqlite3\", \"MySQL\"." exit 1 fi else - echo "Error: \"\$TORRUST_TRACKER_CONFIG_OVERRIDE_DB_DRIVER\" was not set!"; exit 1; + echo "Error: \"\$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER\" was not set!"; exit 1; fi install_config="/etc/torrust/tracker/tracker.toml" diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml index 7678327ab..617450562 100644 --- a/share/default/config/tracker.container.mysql.toml +++ b/share/default/config/tracker.container.mysql.toml @@ -1,3 +1,4 @@ +[core] db_driver = "MySQL" db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml index da8259286..01ca655c3 100644 --- a/share/default/config/tracker.container.sqlite3.toml +++ b/share/default/config/tracker.container.sqlite3.toml @@ -1,3 +1,4 @@ +[core] db_path = "/var/lib/torrust/tracker/database/sqlite3.db" [[http_trackers]] diff --git a/share/default/config/tracker.e2e.container.sqlite3.toml b/share/default/config/tracker.e2e.container.sqlite3.toml index 767b56116..60d7a798a 100644 --- a/share/default/config/tracker.e2e.container.sqlite3.toml +++ b/share/default/config/tracker.e2e.container.sqlite3.toml @@ -1,3 +1,4 @@ +[core] db_path = "/var/lib/torrust/tracker/database/sqlite3.db" [[udp_trackers]] diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml index 00f62628b..cd193c40a 100644 --- a/share/default/config/tracker.udp.benchmarking.toml +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -1,4 +1,7 @@ +[logging] log_level = "error" + +[core] remove_peerless_torrents = false tracker_usage_statistics = false diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index 14756565f..f6868602d 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -20,7 +20,7 @@ static INIT: Once = Once::new(); /// It redirects the log info to the standard output with the log level defined in the configuration pub fn setup(cfg: &Configuration) { - let tracing_level = config_level_or_default(&cfg.core.log_level); + let tracing_level = config_level_or_default(&cfg.logging.log_level); if tracing_level == LevelFilter::OFF { return; diff --git a/src/core/mod.rs b/src/core/mod.rs index 6af28199f..1b60ad6f9 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -312,7 +312,10 @@ //! You can control the behavior of this module with the module settings: //! //! ```toml +//! [logging] //! log_level = "debug" +//! +//! [core] //! mode = "public" //! db_driver = "Sqlite3" //! db_path = "./storage/tracker/lib/database/sqlite3.db" diff --git a/src/lib.rs b/src/lib.rs index 39d0b5b3d..2ed88a68b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -167,12 +167,15 @@ //! The default configuration is: //! //! ```toml +//! [logging] +//! log_level = "info" +//! +//! [core] //! announce_interval = 120 //! db_driver = "Sqlite3" //! db_path = "./storage/tracker/lib/database/sqlite3.db" //! external_ip = "0.0.0.0" //! inactive_peer_cleanup_interval = 600 -//! log_level = "info" //! max_peer_timeout = 900 //! min_announce_interval = 120 //! mode = "public" From 77dd938f807cbf7d2e423f2ee584ca7b75287f10 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Jun 2024 16:08:23 +0100 Subject: [PATCH 0379/1297] feat!: [#878] make log_level config value mandatory Althought, it has a default value `info` so you can omit it in the TOML config file. --- packages/configuration/src/v1/logging.rs | 7 +++---- packages/test-helpers/src/configuration.rs | 2 +- src/bootstrap/logging.rs | 19 ++++++++----------- 3 files changed, 12 insertions(+), 16 deletions(-) diff --git a/packages/configuration/src/v1/logging.rs b/packages/configuration/src/v1/logging.rs index c85564a05..e33522db4 100644 --- a/packages/configuration/src/v1/logging.rs +++ b/packages/configuration/src/v1/logging.rs @@ -8,7 +8,7 @@ pub struct Logging { /// Logging level. Possible values are: `Off`, `Error`, `Warn`, `Info`, /// `Debug` and `Trace`. Default is `Info`. #[serde(default = "Logging::default_log_level")] - pub log_level: Option, + pub log_level: LogLevel, } impl Default for Logging { @@ -20,8 +20,7 @@ impl Default for Logging { } impl Logging { - #[allow(clippy::unnecessary_wraps)] - fn default_log_level() -> Option { - Some(LogLevel::Info) + fn default_log_level() -> LogLevel { + LogLevel::Info } } diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index c35d0a851..f70bebcf7 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -29,7 +29,7 @@ pub fn ephemeral() -> Configuration { let mut config = Configuration::default(); - config.logging.log_level = Some(LogLevel::Off); // Change to `debug` for tests debugging + config.logging.log_level = LogLevel::Off; // Change to `debug` for tests debugging // Ephemeral socket address for API let api_port = 0u16; diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index f6868602d..649495dc7 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -20,7 +20,7 @@ static INIT: Once = Once::new(); /// It redirects the log info to the standard output with the log level defined in the configuration pub fn setup(cfg: &Configuration) { - let tracing_level = config_level_or_default(&cfg.logging.log_level); + let tracing_level = map_to_tracing_level_filter(&cfg.logging.log_level); if tracing_level == LevelFilter::OFF { return; @@ -31,17 +31,14 @@ pub fn setup(cfg: &Configuration) { }); } -fn config_level_or_default(log_level: &Option) -> LevelFilter { +fn map_to_tracing_level_filter(log_level: &LogLevel) -> LevelFilter { match log_level { - None => LevelFilter::INFO, - 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, - }, + LogLevel::Off => LevelFilter::OFF, + LogLevel::Error => LevelFilter::ERROR, + LogLevel::Warn => LevelFilter::WARN, + LogLevel::Info => LevelFilter::INFO, + LogLevel::Debug => LevelFilter::DEBUG, + LogLevel::Trace => LevelFilter::TRACE, } } From 2f94f6caa5673b898d7873b4570f4c87a26be15f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Jun 2024 16:39:01 +0100 Subject: [PATCH 0380/1297] feat!: [#878] extract database section in core config section --- Containerfile | 4 +- compose.yaml | 2 +- docs/containers.md | 7 ++-- packages/configuration/src/v1/core.rs | 29 ++++---------- packages/configuration/src/v1/database.rs | 38 +++++++++++++++++++ packages/configuration/src/v1/mod.rs | 25 +++++++----- packages/test-helpers/src/configuration.rs | 2 +- share/container/entry_script_sh | 10 ++--- .../config/tracker.container.mysql.toml | 6 +-- .../config/tracker.container.sqlite3.toml | 4 +- .../config/tracker.e2e.container.sqlite3.toml | 4 +- src/console/ci/e2e/logs_parser.rs | 18 +-------- src/core/mod.rs | 8 ++-- src/lib.rs | 6 ++- 14 files changed, 92 insertions(+), 71 deletions(-) create mode 100644 packages/configuration/src/v1/database.rs diff --git a/Containerfile b/Containerfile index cdd70e337..d55d2f300 100644 --- a/Containerfile +++ b/Containerfile @@ -96,7 +96,7 @@ RUN ["/busybox/cp", "-sp", "/busybox/sh","/busybox/cat","/busybox/ls","/busybox/ COPY --from=gcc --chmod=0555 /usr/local/bin/su-exec /bin/su-exec ARG TORRUST_TRACKER_CONFIG_TOML_PATH="/etc/torrust/tracker/tracker.toml" -ARG TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER="Sqlite3" +ARG TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER="Sqlite3" ARG USER_ID=1000 ARG UDP_PORT=6969 ARG HTTP_PORT=7070 @@ -104,7 +104,7 @@ ARG API_PORT=1212 ARG HEALTH_CHECK_API_PORT=1313 ENV TORRUST_TRACKER_CONFIG_TOML_PATH=${TORRUST_TRACKER_CONFIG_TOML_PATH} -ENV TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER} +ENV TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER} ENV USER_ID=${USER_ID} ENV UDP_PORT=${UDP_PORT} ENV HTTP_PORT=${HTTP_PORT} diff --git a/compose.yaml b/compose.yaml index a02302a26..cab5c6d5e 100644 --- a/compose.yaml +++ b/compose.yaml @@ -4,7 +4,7 @@ services: image: torrust-tracker:release tty: true environment: - - TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER:-MySQL} + - TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER:-MySQL} - TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN=${TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN:-MyAccessToken} networks: - server_side diff --git a/docs/containers.md b/docs/containers.md index ff15cd7cc..1a1ea2f0d 100644 --- a/docs/containers.md +++ b/docs/containers.md @@ -149,7 +149,7 @@ The following environmental variables can be set: - `TORRUST_TRACKER_CONFIG_TOML_PATH` - The in-container path to the tracker configuration file, (default: `"/etc/torrust/tracker/tracker.toml"`). - `TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN` - Override of the admin token. If set, this value overrides any value set in the config. -- `TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER` - The database type used for the container, (options: `Sqlite3`, `MySQL`, default `Sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. +- `TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER` - The database type used for the container, (options: `Sqlite3`, `MySQL`, default `Sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. - `TORRUST_TRACKER_CONFIG_TOML` - Load config from this environmental variable instead from a file, (i.e: `TORRUST_TRACKER_CONFIG_TOML=$(cat tracker-tracker.toml)`). - `USER_ID` - The user id for the runtime crated `torrust` user. Please Note: This user id should match the ownership of the host-mapped volumes, (default `1000`). - `UDP_PORT` - The port for the UDP tracker. This should match the port used in the configuration, (default `6969`). @@ -243,8 +243,9 @@ podman run -it \ The docker-compose configuration includes the MySQL service configuration. If you want to use MySQL instead of SQLite you should verify the `/etc/torrust/tracker/tracker.toml` (i.e `./storage/tracker/etc/tracker.toml`) configuration: ```toml -db_driver = "MySQL" -db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" +[core.database] +driver = "MySQL" +path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" ``` ### Build and Run: diff --git a/packages/configuration/src/v1/core.rs b/packages/configuration/src/v1/core.rs index ae66f54fa..17ac36ee0 100644 --- a/packages/configuration/src/v1/core.rs +++ b/packages/configuration/src/v1/core.rs @@ -1,8 +1,9 @@ use std::net::{IpAddr, Ipv4Addr}; use serde::{Deserialize, Serialize}; -use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; +use torrust_tracker_primitives::TrackerMode; +use crate::v1::database::Database; use crate::AnnouncePolicy; #[allow(clippy::struct_excessive_bools)] @@ -12,18 +13,9 @@ pub struct Core { #[serde(default = "Core::default_mode")] pub mode: TrackerMode, - // Database configuration - /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. - #[serde(default = "Core::default_db_driver")] - pub db_driver: DatabaseDriver, - - /// Database connection string. The format depends on the database driver. - /// For `Sqlite3`, the format is `path/to/database.db`, for example: - /// `./storage/tracker/lib/database/sqlite3.db`. - /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for - /// example: `root:password@localhost:3306/torrust`. - #[serde(default = "Core::default_db_path")] - pub db_path: String, + // Database configuration. + #[serde(default = "Core::default_database")] + pub database: Database, /// See [`AnnouncePolicy::interval`] #[serde(default = "AnnouncePolicy::default_interval")] @@ -87,8 +79,7 @@ impl Default for Core { Self { mode: Self::default_mode(), - db_driver: Self::default_db_driver(), - db_path: Self::default_db_path(), + database: Self::default_database(), announce_interval: announce_policy.interval, min_announce_interval: announce_policy.interval_min, max_peer_timeout: Self::default_max_peer_timeout(), @@ -107,12 +98,8 @@ impl Core { TrackerMode::Public } - fn default_db_driver() -> DatabaseDriver { - DatabaseDriver::Sqlite3 - } - - fn default_db_path() -> String { - String::from("./storage/tracker/lib/database/sqlite3.db") + fn default_database() -> Database { + Database::default() } fn default_on_reverse_proxy() -> bool { diff --git a/packages/configuration/src/v1/database.rs b/packages/configuration/src/v1/database.rs new file mode 100644 index 000000000..b029175ce --- /dev/null +++ b/packages/configuration/src/v1/database.rs @@ -0,0 +1,38 @@ +use serde::{Deserialize, Serialize}; +use torrust_tracker_primitives::DatabaseDriver; + +#[allow(clippy::struct_excessive_bools)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct Database { + // Database configuration + /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. + #[serde(default = "Database::default_driver")] + pub driver: DatabaseDriver, + + /// Database connection string. The format depends on the database driver. + /// For `Sqlite3`, the format is `path/to/database.db`, for example: + /// `./storage/tracker/lib/database/sqlite3.db`. + /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for + /// example: `root:password@localhost:3306/torrust`. + #[serde(default = "Database::default_path")] + pub path: String, +} + +impl Default for Database { + fn default() -> Self { + Self { + driver: Self::default_driver(), + path: Self::default_path(), + } + } +} + +impl Database { + fn default_driver() -> DatabaseDriver { + DatabaseDriver::Sqlite3 + } + + fn default_path() -> String { + String::from("./storage/tracker/lib/database/sqlite3.db") + } +} diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 809970506..5b3cad3ea 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -198,8 +198,6 @@ //! //! [core] //! mode = "public" -//! db_driver = "Sqlite3" -//! db_path = "./storage/tracker/lib/database/sqlite3.db" //! announce_interval = 120 //! min_announce_interval = 120 //! on_reverse_proxy = false @@ -210,6 +208,10 @@ //! inactive_peer_cleanup_interval = 600 //! remove_peerless_torrents = true //! +//! [core.database] +//! driver = "Sqlite3" +//! path = "./storage/tracker/lib/database/sqlite3.db" +//! //! [[udp_trackers]] //! enabled = false //! bind_address = "0.0.0.0:6969" @@ -234,6 +236,7 @@ //! bind_address = "127.0.0.1:1313" //!``` pub mod core; +pub mod database; pub mod health_check_api; pub mod http_tracker; pub mod logging; @@ -382,8 +385,6 @@ mod tests { [core] mode = "public" - db_driver = "Sqlite3" - db_path = "./storage/tracker/lib/database/sqlite3.db" announce_interval = 120 min_announce_interval = 120 on_reverse_proxy = false @@ -394,6 +395,10 @@ mod tests { inactive_peer_cleanup_interval = 600 remove_peerless_torrents = true + [core.database] + driver = "Sqlite3" + path = "./storage/tracker/lib/database/sqlite3.db" + [[udp_trackers]] enabled = false bind_address = "0.0.0.0:6969" @@ -490,8 +495,8 @@ mod tests { fn default_configuration_could_be_overwritten_from_a_single_env_var_with_toml_contents() { figment::Jail::expect_with(|_jail| { let config_toml = r#" - [core] - db_path = "OVERWRITTEN DEFAULT DB PATH" + [core.database] + path = "OVERWRITTEN DEFAULT DB PATH" "# .to_string(); @@ -502,7 +507,7 @@ mod tests { let configuration = Configuration::load(&info).expect("Could not load configuration from file"); - assert_eq!(configuration.core.db_path, "OVERWRITTEN DEFAULT DB PATH".to_string()); + assert_eq!(configuration.core.database.path, "OVERWRITTEN DEFAULT DB PATH".to_string()); Ok(()) }); @@ -514,8 +519,8 @@ mod tests { jail.create_file( "tracker.toml", r#" - [core] - db_path = "OVERWRITTEN DEFAULT DB PATH" + [core.database] + path = "OVERWRITTEN DEFAULT DB PATH" "#, )?; @@ -526,7 +531,7 @@ mod tests { let configuration = Configuration::load(&info).expect("Could not load configuration from file"); - assert_eq!(configuration.core.db_path, "OVERWRITTEN DEFAULT DB PATH".to_string()); + assert_eq!(configuration.core.database.path, "OVERWRITTEN DEFAULT DB PATH".to_string()); Ok(()) }); diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index f70bebcf7..fe05407d9 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -54,7 +54,7 @@ pub fn ephemeral() -> Configuration { let temp_directory = env::temp_dir(); let random_db_id = random::string(16); let temp_file = temp_directory.join(format!("data_{random_db_id}.db")); - temp_file.to_str().unwrap().clone_into(&mut config.core.db_path); + temp_file.to_str().unwrap().clone_into(&mut config.core.database.path); config } diff --git a/share/container/entry_script_sh b/share/container/entry_script_sh index 51df717c6..0668114fd 100644 --- a/share/container/entry_script_sh +++ b/share/container/entry_script_sh @@ -26,8 +26,8 @@ chmod -R 2770 /var/lib/torrust /var/log/torrust /etc/torrust # Install the database and config: -if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER" ]; then - if cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER" "Sqlite3"; then +if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" ]; then + if cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" "Sqlite3"; then # Select Sqlite3 empty database default_database="/usr/share/torrust/default/database/tracker.sqlite3.db" @@ -35,7 +35,7 @@ if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER" ]; then # Select Sqlite3 default configuration default_config="/usr/share/torrust/default/config/tracker.container.sqlite3.toml" - elif cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER" "MySQL"; then + elif cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" "MySQL"; then # (no database file needed for MySQL) @@ -43,12 +43,12 @@ if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER" ]; then default_config="/usr/share/torrust/default/config/tracker.container.mysql.toml" else - echo "Error: Unsupported Database Type: \"$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER\"." + echo "Error: Unsupported Database Type: \"$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER\"." echo "Please Note: Supported Database Types: \"Sqlite3\", \"MySQL\"." exit 1 fi else - echo "Error: \"\$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DB_DRIVER\" was not set!"; exit 1; + echo "Error: \"\$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER\" was not set!"; exit 1; fi install_config="/etc/torrust/tracker/tracker.toml" diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml index 617450562..75cc57b64 100644 --- a/share/default/config/tracker.container.mysql.toml +++ b/share/default/config/tracker.container.mysql.toml @@ -1,6 +1,6 @@ -[core] -db_driver = "MySQL" -db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" +[core.database] +driver = "MySQL" +path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" [[http_trackers]] ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml index 01ca655c3..433e36127 100644 --- a/share/default/config/tracker.container.sqlite3.toml +++ b/share/default/config/tracker.container.sqlite3.toml @@ -1,5 +1,5 @@ -[core] -db_path = "/var/lib/torrust/tracker/database/sqlite3.db" +[core.database] +path = "/var/lib/torrust/tracker/database/sqlite3.db" [[http_trackers]] ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" diff --git a/share/default/config/tracker.e2e.container.sqlite3.toml b/share/default/config/tracker.e2e.container.sqlite3.toml index 60d7a798a..b8adedefb 100644 --- a/share/default/config/tracker.e2e.container.sqlite3.toml +++ b/share/default/config/tracker.e2e.container.sqlite3.toml @@ -1,5 +1,5 @@ -[core] -db_path = "/var/lib/torrust/tracker/database/sqlite3.db" +[core.database] +path = "/var/lib/torrust/tracker/database/sqlite3.db" [[udp_trackers]] enabled = true diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index a4024f29d..4886786de 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -112,21 +112,7 @@ mod tests { #[test] fn it_should_parse_from_logs_with_valid_logs() { - let logs = r#" - Loading configuration from environment variable db_path = "/var/lib/torrust/tracker/database/sqlite3.db" - - [[udp_trackers]] - enabled = true - - [[http_trackers]] - enabled = true - ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" - ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" - - [http_api] - ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" - ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" - + let logs = r" Loading configuration from default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... 2024-06-10T16:07:39.989540Z INFO torrust_tracker::bootstrap::logging: logging initialized. 2024-06-10T16:07:39.990244Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 @@ -139,7 +125,7 @@ mod tests { 2024-06-10T16:07:39.990565Z INFO API: Started on http://127.0.0.1:1212 2024-06-10T16:07:39.990577Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 2024-06-10T16:07:39.990638Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 - "#; + "; let running_services = RunningServices::parse_from_logs(logs); diff --git a/src/core/mod.rs b/src/core/mod.rs index 1b60ad6f9..c5171ab58 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -317,8 +317,6 @@ //! //! [core] //! mode = "public" -//! db_driver = "Sqlite3" -//! db_path = "./storage/tracker/lib/database/sqlite3.db" //! announce_interval = 120 //! min_announce_interval = 120 //! max_peer_timeout = 900 @@ -328,6 +326,10 @@ //! persistent_torrent_completed_stat = true //! inactive_peer_cleanup_interval = 600 //! remove_peerless_torrents = false +//! +//! [core.database] +//! driver = "Sqlite3" +//! path = "./storage/tracker/lib/database/sqlite3.db" //! ``` //! //! Refer to the [`configuration` module documentation](https://docs.rs/torrust-tracker-configuration) to get more information about all options. @@ -548,7 +550,7 @@ impl Tracker { stats_event_sender: Option>, stats_repository: statistics::Repo, ) -> Result { - let database = Arc::new(databases::driver::build(&config.db_driver, &config.db_path)?); + let database = Arc::new(databases::driver::build(&config.database.driver, &config.database.path)?); let mode = config.mode.clone(); diff --git a/src/lib.rs b/src/lib.rs index 2ed88a68b..b94da4717 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -172,8 +172,6 @@ //! //! [core] //! announce_interval = 120 -//! db_driver = "Sqlite3" -//! db_path = "./storage/tracker/lib/database/sqlite3.db" //! external_ip = "0.0.0.0" //! inactive_peer_cleanup_interval = 600 //! max_peer_timeout = 900 @@ -184,6 +182,10 @@ //! remove_peerless_torrents = true //! tracker_usage_statistics = true //! +//! [core.database] +//! driver = "Sqlite3" +//! path = "./storage/tracker/lib/database/sqlite3.db" +//! //! [[udp_trackers]] //! bind_address = "0.0.0.0:6969" //! enabled = false From edc706cc146035d586e86741da7b1df1db4bd08d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Jun 2024 16:59:42 +0100 Subject: [PATCH 0381/1297] feat!: [#878] extract net section in core config section --- packages/configuration/src/v1/core.rs | 55 ++++++++-------------- packages/configuration/src/v1/mod.rs | 34 ++++++++----- packages/configuration/src/v1/network.rs | 41 ++++++++++++++++ packages/test-helpers/src/configuration.rs | 6 +-- src/core/mod.rs | 16 ++++--- src/lib.rs | 6 ++- src/servers/http/v1/services/announce.rs | 2 +- src/servers/udp/handlers.rs | 2 +- 8 files changed, 99 insertions(+), 63 deletions(-) create mode 100644 packages/configuration/src/v1/network.rs diff --git a/packages/configuration/src/v1/core.rs b/packages/configuration/src/v1/core.rs index 17ac36ee0..5d8ab0b33 100644 --- a/packages/configuration/src/v1/core.rs +++ b/packages/configuration/src/v1/core.rs @@ -1,8 +1,7 @@ -use std::net::{IpAddr, Ipv4Addr}; - use serde::{Deserialize, Serialize}; use torrust_tracker_primitives::TrackerMode; +use super::network::Network; use crate::v1::database::Database; use crate::AnnouncePolicy; @@ -13,10 +12,6 @@ pub struct Core { #[serde(default = "Core::default_mode")] pub mode: TrackerMode, - // Database configuration. - #[serde(default = "Core::default_database")] - pub database: Database, - /// See [`AnnouncePolicy::interval`] #[serde(default = "AnnouncePolicy::default_interval")] pub announce_interval: u32, @@ -25,20 +20,6 @@ pub struct Core { #[serde(default = "AnnouncePolicy::default_interval_min")] pub min_announce_interval: u32, - /// Weather the tracker is behind a reverse proxy or not. - /// If the tracker is behind a reverse proxy, the `X-Forwarded-For` header - /// sent from the proxy will be used to get the client's IP address. - #[serde(default = "Core::default_on_reverse_proxy")] - pub on_reverse_proxy: bool, - - /// The external IP address of the tracker. If the client is using a - /// loopback IP address, this IP address will be used instead. If the peer - /// 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. - #[serde(default = "Core::default_external_ip")] - pub external_ip: Option, - /// 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. @@ -71,6 +52,14 @@ pub struct Core { /// enabled. #[serde(default = "Core::default_remove_peerless_torrents")] pub remove_peerless_torrents: bool, + + // Database configuration. + #[serde(default = "Core::default_database")] + pub database: Database, + + // Network configuration. + #[serde(default = "Core::default_network")] + pub net: Network, } impl Default for Core { @@ -79,16 +68,15 @@ impl Default for Core { Self { mode: Self::default_mode(), - database: Self::default_database(), announce_interval: announce_policy.interval, min_announce_interval: announce_policy.interval_min, max_peer_timeout: Self::default_max_peer_timeout(), - on_reverse_proxy: Self::default_on_reverse_proxy(), - external_ip: Self::default_external_ip(), tracker_usage_statistics: Self::default_tracker_usage_statistics(), persistent_torrent_completed_stat: Self::default_persistent_torrent_completed_stat(), inactive_peer_cleanup_interval: Self::default_inactive_peer_cleanup_interval(), remove_peerless_torrents: Self::default_remove_peerless_torrents(), + database: Self::default_database(), + net: Self::default_network(), } } } @@ -98,19 +86,6 @@ impl Core { TrackerMode::Public } - fn default_database() -> Database { - Database::default() - } - - fn default_on_reverse_proxy() -> bool { - false - } - - #[allow(clippy::unnecessary_wraps)] - fn default_external_ip() -> Option { - Some(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))) - } - fn default_tracker_usage_statistics() -> bool { true } @@ -130,4 +105,12 @@ impl Core { fn default_remove_peerless_torrents() -> bool { true } + + fn default_database() -> Database { + Database::default() + } + + fn default_network() -> Network { + Network::default() + } } diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 5b3cad3ea..d96e1335c 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -200,17 +200,19 @@ //! mode = "public" //! announce_interval = 120 //! min_announce_interval = 120 -//! on_reverse_proxy = false -//! external_ip = "0.0.0.0" //! tracker_usage_statistics = true //! persistent_torrent_completed_stat = false //! max_peer_timeout = 900 //! inactive_peer_cleanup_interval = 600 //! remove_peerless_torrents = true //! -//! [core.database] -//! driver = "Sqlite3" -//! path = "./storage/tracker/lib/database/sqlite3.db" +//! [core.database] +//! driver = "Sqlite3" +//! path = "./storage/tracker/lib/database/sqlite3.db" +//! +//! [core.net] +//! external_ip = "0.0.0.0" +//! on_reverse_proxy = false //! //! [[udp_trackers]] //! enabled = false @@ -240,6 +242,7 @@ pub mod database; pub mod health_check_api; pub mod http_tracker; pub mod logging; +pub mod network; pub mod tracker_api; pub mod udp_tracker; @@ -307,7 +310,7 @@ impl Configuration { /// and `None` otherwise. #[must_use] pub fn get_ext_ip(&self) -> Option { - self.core.external_ip.as_ref().map(|external_ip| *external_ip) + self.core.net.external_ip.as_ref().map(|external_ip| *external_ip) } /// Saves the default configuration at the given path. @@ -387,18 +390,20 @@ mod tests { mode = "public" announce_interval = 120 min_announce_interval = 120 - on_reverse_proxy = false - external_ip = "0.0.0.0" tracker_usage_statistics = true persistent_torrent_completed_stat = false max_peer_timeout = 900 inactive_peer_cleanup_interval = 600 remove_peerless_torrents = true - [core.database] - driver = "Sqlite3" - path = "./storage/tracker/lib/database/sqlite3.db" - + [core.database] + driver = "Sqlite3" + path = "./storage/tracker/lib/database/sqlite3.db" + + [core.net] + external_ip = "0.0.0.0" + on_reverse_proxy = false + [[udp_trackers]] enabled = false bind_address = "0.0.0.0:6969" @@ -443,7 +448,10 @@ mod tests { fn configuration_should_contain_the_external_ip() { let configuration = Configuration::default(); - assert_eq!(configuration.core.external_ip, Some(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)))); + assert_eq!( + configuration.core.net.external_ip, + Some(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))) + ); } #[test] diff --git a/packages/configuration/src/v1/network.rs b/packages/configuration/src/v1/network.rs new file mode 100644 index 000000000..8e53d419c --- /dev/null +++ b/packages/configuration/src/v1/network.rs @@ -0,0 +1,41 @@ +use std::net::{IpAddr, Ipv4Addr}; + +use serde::{Deserialize, Serialize}; + +#[allow(clippy::struct_excessive_bools)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] +pub struct Network { + /// The external IP address of the tracker. If the client is using a + /// loopback IP address, this IP address will be used instead. If the peer + /// 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. + #[serde(default = "Network::default_external_ip")] + pub external_ip: Option, + + /// Weather the tracker is behind a reverse proxy or not. + /// If the tracker is behind a reverse proxy, the `X-Forwarded-For` header + /// sent from the proxy will be used to get the client's IP address. + #[serde(default = "Network::default_on_reverse_proxy")] + pub on_reverse_proxy: bool, +} + +impl Default for Network { + fn default() -> Self { + Self { + external_ip: Self::default_external_ip(), + on_reverse_proxy: Self::default_on_reverse_proxy(), + } + } +} + +impl Network { + #[allow(clippy::unnecessary_wraps)] + fn default_external_ip() -> Option { + Some(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))) + } + + fn default_on_reverse_proxy() -> bool { + false + } +} diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index fe05407d9..9c6c0fe11 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -64,7 +64,7 @@ pub fn ephemeral() -> Configuration { pub fn ephemeral_with_reverse_proxy() -> Configuration { let mut cfg = ephemeral(); - cfg.core.on_reverse_proxy = true; + cfg.core.net.on_reverse_proxy = true; cfg } @@ -74,7 +74,7 @@ pub fn ephemeral_with_reverse_proxy() -> Configuration { pub fn ephemeral_without_reverse_proxy() -> Configuration { let mut cfg = ephemeral(); - cfg.core.on_reverse_proxy = false; + cfg.core.net.on_reverse_proxy = false; cfg } @@ -124,7 +124,7 @@ pub fn ephemeral_mode_private_whitelisted() -> Configuration { pub fn ephemeral_with_external_ip(ip: IpAddr) -> Configuration { let mut cfg = ephemeral(); - cfg.core.external_ip = Some(ip); + cfg.core.net.external_ip = Some(ip); cfg } diff --git a/src/core/mod.rs b/src/core/mod.rs index c5171ab58..f4eb2c335 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -320,16 +320,18 @@ //! announce_interval = 120 //! min_announce_interval = 120 //! max_peer_timeout = 900 -//! on_reverse_proxy = false -//! external_ip = "2.137.87.41" //! tracker_usage_statistics = true //! persistent_torrent_completed_stat = true //! inactive_peer_cleanup_interval = 600 //! remove_peerless_torrents = false //! -//! [core.database] -//! driver = "Sqlite3" -//! path = "./storage/tracker/lib/database/sqlite3.db" +//! [core.database] +//! driver = "Sqlite3" +//! path = "./storage/tracker/lib/database/sqlite3.db" +//! +//! [core.net] +//! on_reverse_proxy = false +//! external_ip = "2.137.87.41" //! ``` //! //! Refer to the [`configuration` module documentation](https://docs.rs/torrust-tracker-configuration) to get more information about all options. @@ -564,13 +566,13 @@ impl Tracker { stats_event_sender, stats_repository, database, - external_ip: config.external_ip, + external_ip: config.net.external_ip, policy: TrackerPolicy::new( config.remove_peerless_torrents, config.max_peer_timeout, config.persistent_torrent_completed_stat, ), - on_reverse_proxy: config.on_reverse_proxy, + on_reverse_proxy: config.net.on_reverse_proxy, }) } diff --git a/src/lib.rs b/src/lib.rs index b94da4717..bf9257123 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -172,12 +172,10 @@ //! //! [core] //! announce_interval = 120 -//! external_ip = "0.0.0.0" //! inactive_peer_cleanup_interval = 600 //! max_peer_timeout = 900 //! min_announce_interval = 120 //! mode = "public" -//! on_reverse_proxy = false //! persistent_torrent_completed_stat = false //! remove_peerless_torrents = true //! tracker_usage_statistics = true @@ -186,6 +184,10 @@ //! driver = "Sqlite3" //! path = "./storage/tracker/lib/database/sqlite3.db" //! +//! [core.net] +//! external_ip = "0.0.0.0" +//! on_reverse_proxy = false +//! //! [[udp_trackers]] //! bind_address = "0.0.0.0:6969" //! enabled = false diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 253140fbc..eee5e4688 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -151,7 +151,7 @@ mod tests { fn tracker_with_an_ipv6_external_ip(stats_event_sender: Box) -> Tracker { let mut configuration = configuration::ephemeral(); - configuration.core.external_ip = Some(IpAddr::V6(Ipv6Addr::new( + configuration.core.net.external_ip = Some(IpAddr::V6(Ipv6Addr::new( 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, ))); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 858d6606c..36825f084 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -425,7 +425,7 @@ mod tests { } pub fn with_external_ip(mut self, external_ip: &str) -> Self { - self.configuration.core.external_ip = Some(external_ip.to_owned().parse().expect("valid IP address")); + self.configuration.core.net.external_ip = Some(external_ip.to_owned().parse().expect("valid IP address")); self } From fc046e0441302c3af8db3a1b1173d38e4383369e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Jun 2024 17:21:03 +0100 Subject: [PATCH 0382/1297] feat!: [#878] extract announce_policy section in core config section --- packages/configuration/src/lib.rs | 4 +++- packages/configuration/src/v1/core.rs | 21 +++++++++------------ packages/configuration/src/v1/mod.rs | 12 ++++++++---- src/core/mod.rs | 14 ++++++++------ src/lib.rs | 18 ++++++++++-------- 5 files changed, 38 insertions(+), 31 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 46ece96ab..3b719f742 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -86,7 +86,7 @@ impl Info { } /// Announce policy -#[derive(PartialEq, Eq, Debug, Clone, Copy, Constructor)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Copy, Constructor)] pub struct AnnouncePolicy { /// Interval in seconds that the client should wait between sending regular /// announce requests to the tracker. @@ -99,6 +99,7 @@ pub struct AnnouncePolicy { /// client's initial request. It serves as a guideline for clients to know /// how often they should contact the tracker for updates on the peer list, /// while ensuring that the tracker is not overwhelmed with requests. + #[serde(default = "AnnouncePolicy::default_interval")] pub interval: u32, /// Minimum announce interval. Clients must not reannounce more frequently @@ -112,6 +113,7 @@ pub struct AnnouncePolicy { /// value to prevent sending too many requests in a short period, which /// could lead to excessive load on the tracker or even getting banned by /// the tracker for not adhering to the rules. + #[serde(default = "AnnouncePolicy::default_interval_min")] pub interval_min: u32, } diff --git a/packages/configuration/src/v1/core.rs b/packages/configuration/src/v1/core.rs index 5d8ab0b33..266da21ed 100644 --- a/packages/configuration/src/v1/core.rs +++ b/packages/configuration/src/v1/core.rs @@ -12,14 +12,6 @@ pub struct Core { #[serde(default = "Core::default_mode")] pub mode: TrackerMode, - /// See [`AnnouncePolicy::interval`] - #[serde(default = "AnnouncePolicy::default_interval")] - pub announce_interval: u32, - - /// See [`AnnouncePolicy::interval_min`] - #[serde(default = "AnnouncePolicy::default_interval_min")] - pub min_announce_interval: u32, - /// 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. @@ -53,6 +45,10 @@ pub struct Core { #[serde(default = "Core::default_remove_peerless_torrents")] pub remove_peerless_torrents: bool, + // Announce policy configuration. + #[serde(default = "Core::default_announce_policy")] + pub announce_policy: AnnouncePolicy, + // Database configuration. #[serde(default = "Core::default_database")] pub database: Database, @@ -64,17 +60,14 @@ pub struct Core { impl Default for Core { fn default() -> Self { - let announce_policy = AnnouncePolicy::default(); - Self { mode: Self::default_mode(), - announce_interval: announce_policy.interval, - min_announce_interval: announce_policy.interval_min, max_peer_timeout: Self::default_max_peer_timeout(), tracker_usage_statistics: Self::default_tracker_usage_statistics(), persistent_torrent_completed_stat: Self::default_persistent_torrent_completed_stat(), inactive_peer_cleanup_interval: Self::default_inactive_peer_cleanup_interval(), remove_peerless_torrents: Self::default_remove_peerless_torrents(), + announce_policy: Self::default_announce_policy(), database: Self::default_database(), net: Self::default_network(), } @@ -106,6 +99,10 @@ impl Core { true } + fn default_announce_policy() -> AnnouncePolicy { + AnnouncePolicy::default() + } + fn default_database() -> Database { Database::default() } diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index d96e1335c..d2f2a3012 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -198,14 +198,16 @@ //! //! [core] //! mode = "public" -//! announce_interval = 120 -//! min_announce_interval = 120 //! tracker_usage_statistics = true //! persistent_torrent_completed_stat = false //! max_peer_timeout = 900 //! inactive_peer_cleanup_interval = 600 //! remove_peerless_torrents = true //! +//! [core.announce_policy] +//! interval = 120 +//! interval_min = 120 +//! //! [core.database] //! driver = "Sqlite3" //! path = "./storage/tracker/lib/database/sqlite3.db" @@ -388,14 +390,16 @@ mod tests { [core] mode = "public" - announce_interval = 120 - min_announce_interval = 120 tracker_usage_statistics = true persistent_torrent_completed_stat = false max_peer_timeout = 900 inactive_peer_cleanup_interval = 600 remove_peerless_torrents = true + [core.announce_policy] + interval = 120 + interval_min = 120 + [core.database] driver = "Sqlite3" path = "./storage/tracker/lib/database/sqlite3.db" diff --git a/src/core/mod.rs b/src/core/mod.rs index f4eb2c335..77f7099af 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -113,10 +113,10 @@ //! } //! //! // Core tracker configuration -//! pub struct Configuration { +//! pub struct AnnounceInterval { //! // ... -//! pub announce_interval: u32, // Interval in seconds that the client should wait between sending regular announce requests to the tracker -//! pub min_announce_interval: u32, // Minimum announce interval. Clients must not reannounce more frequently than this +//! pub interval: u32, // Interval in seconds that the client should wait between sending regular announce requests to the tracker +//! pub interval_min: u32, // Minimum announce interval. Clients must not reannounce more frequently than this //! // ... //! } //! ``` @@ -317,14 +317,16 @@ //! //! [core] //! mode = "public" -//! announce_interval = 120 -//! min_announce_interval = 120 //! max_peer_timeout = 900 //! tracker_usage_statistics = true //! persistent_torrent_completed_stat = true //! inactive_peer_cleanup_interval = 600 //! remove_peerless_torrents = false //! +//! [core.announce_policy] +//! interval = 120 +//! interval_min = 120 +//! //! [core.database] //! driver = "Sqlite3" //! path = "./storage/tracker/lib/database/sqlite3.db" @@ -558,7 +560,7 @@ impl Tracker { Ok(Tracker { //config, - announce_policy: AnnouncePolicy::new(config.announce_interval, config.min_announce_interval), + announce_policy: config.announce_policy, mode, keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), diff --git a/src/lib.rs b/src/lib.rs index bf9257123..5c0fd4b56 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -171,22 +171,24 @@ //! log_level = "info" //! //! [core] -//! announce_interval = 120 //! inactive_peer_cleanup_interval = 600 //! max_peer_timeout = 900 -//! min_announce_interval = 120 //! mode = "public" //! persistent_torrent_completed_stat = false //! remove_peerless_torrents = true //! tracker_usage_statistics = true //! -//! [core.database] -//! driver = "Sqlite3" -//! path = "./storage/tracker/lib/database/sqlite3.db" +//! [core.announce_policy] +//! interval = 120 +//! interval_min = 120 //! -//! [core.net] -//! external_ip = "0.0.0.0" -//! on_reverse_proxy = false +//! [core.database] +//! driver = "Sqlite3" +//! path = "./storage/tracker/lib/database/sqlite3.db" +//! +//! [core.net] +//! external_ip = "0.0.0.0" +//! on_reverse_proxy = false //! //! [[udp_trackers]] //! bind_address = "0.0.0.0:6969" From 7b2f75724494c883c8e0d6faae9153c4ab47a562 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Jun 2024 18:19:57 +0100 Subject: [PATCH 0383/1297] feat!: [#878] extract tracker_policy section in core config section --- packages/configuration/src/lib.rs | 44 ++++++++++++++++++- packages/configuration/src/v1/core.rs | 40 +++-------------- packages/configuration/src/v1/mod.rs | 12 +++-- .../torrent-repository/tests/entry/mod.rs | 8 ++-- .../tests/repository/mod.rs | 8 ++-- src/core/mod.rs | 16 +++---- src/lib.rs | 6 ++- 7 files changed, 76 insertions(+), 58 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 3b719f742..594a283db 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -37,11 +37,51 @@ pub type HealthCheckApi = v1::health_check_api::HealthCheckApi; pub type AccessTokens = HashMap; -#[derive(Copy, Clone, Debug, PartialEq, Constructor)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Constructor)] pub struct TrackerPolicy { - pub remove_peerless_torrents: bool, + // Cleanup job configuration + /// Maximum time in seconds that a peer can be inactive before being + /// considered an inactive peer. If a peer is inactive for more than this + /// time, it will be removed from the torrent peer list. + #[serde(default = "TrackerPolicy::default_max_peer_timeout")] pub max_peer_timeout: u32, + + /// If enabled the tracker will persist the number of completed downloads. + /// That's how many times a torrent has been downloaded completely. + #[serde(default = "TrackerPolicy::default_persistent_torrent_completed_stat")] pub persistent_torrent_completed_stat: bool, + + /// If enabled, the tracker will remove torrents that have no peers. + /// The clean up torrent job runs every `inactive_peer_cleanup_interval` + /// seconds and it removes inactive peers. Eventually, the peer list of a + /// torrent could be empty and the torrent will be removed if this option is + /// enabled. + #[serde(default = "TrackerPolicy::default_remove_peerless_torrents")] + pub remove_peerless_torrents: bool, +} + +impl Default for TrackerPolicy { + fn default() -> Self { + Self { + max_peer_timeout: Self::default_max_peer_timeout(), + persistent_torrent_completed_stat: Self::default_persistent_torrent_completed_stat(), + remove_peerless_torrents: Self::default_remove_peerless_torrents(), + } + } +} + +impl TrackerPolicy { + fn default_max_peer_timeout() -> u32 { + 900 + } + + fn default_persistent_torrent_completed_stat() -> bool { + false + } + + fn default_remove_peerless_torrents() -> bool { + true + } } /// Information required for loading config diff --git a/packages/configuration/src/v1/core.rs b/packages/configuration/src/v1/core.rs index 266da21ed..49fdf2a80 100644 --- a/packages/configuration/src/v1/core.rs +++ b/packages/configuration/src/v1/core.rs @@ -3,7 +3,7 @@ use torrust_tracker_primitives::TrackerMode; use super::network::Network; use crate::v1::database::Database; -use crate::AnnouncePolicy; +use crate::{AnnouncePolicy, TrackerPolicy}; #[allow(clippy::struct_excessive_bools)] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] @@ -20,30 +20,14 @@ pub struct Core { #[serde(default = "Core::default_tracker_usage_statistics")] pub tracker_usage_statistics: bool, - /// If enabled the tracker will persist the number of completed downloads. - /// That's how many times a torrent has been downloaded completely. - #[serde(default = "Core::default_persistent_torrent_completed_stat")] - pub persistent_torrent_completed_stat: bool, - - // Cleanup job configuration - /// Maximum time in seconds that a peer can be inactive before being - /// considered an inactive peer. If a peer is inactive for more than this - /// time, it will be removed from the torrent peer list. - #[serde(default = "Core::default_max_peer_timeout")] - pub max_peer_timeout: u32, - /// Interval in seconds that the cleanup job will run to remove inactive /// peers from the torrent peer list. #[serde(default = "Core::default_inactive_peer_cleanup_interval")] pub inactive_peer_cleanup_interval: u64, - /// If enabled, the tracker will remove torrents that have no peers. - /// The clean up torrent job runs every `inactive_peer_cleanup_interval` - /// seconds and it removes inactive peers. Eventually, the peer list of a - /// torrent could be empty and the torrent will be removed if this option is - /// enabled. - #[serde(default = "Core::default_remove_peerless_torrents")] - pub remove_peerless_torrents: bool, + // Tracker policy configuration. + #[serde(default = "Core::default_tracker_policy")] + pub tracker_policy: TrackerPolicy, // Announce policy configuration. #[serde(default = "Core::default_announce_policy")] @@ -62,11 +46,9 @@ impl Default for Core { fn default() -> Self { Self { mode: Self::default_mode(), - max_peer_timeout: Self::default_max_peer_timeout(), tracker_usage_statistics: Self::default_tracker_usage_statistics(), - persistent_torrent_completed_stat: Self::default_persistent_torrent_completed_stat(), inactive_peer_cleanup_interval: Self::default_inactive_peer_cleanup_interval(), - remove_peerless_torrents: Self::default_remove_peerless_torrents(), + tracker_policy: Self::default_tracker_policy(), announce_policy: Self::default_announce_policy(), database: Self::default_database(), net: Self::default_network(), @@ -83,20 +65,12 @@ impl Core { true } - fn default_persistent_torrent_completed_stat() -> bool { - false - } - - fn default_max_peer_timeout() -> u32 { - 900 - } - fn default_inactive_peer_cleanup_interval() -> u64 { 600 } - fn default_remove_peerless_torrents() -> bool { - true + fn default_tracker_policy() -> TrackerPolicy { + TrackerPolicy::default() } fn default_announce_policy() -> AnnouncePolicy { diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index d2f2a3012..19499cd4a 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -199,9 +199,11 @@ //! [core] //! mode = "public" //! tracker_usage_statistics = true -//! persistent_torrent_completed_stat = false -//! max_peer_timeout = 900 //! inactive_peer_cleanup_interval = 600 +//! +//! [core.tracker_policy] +//! max_peer_timeout = 900 +//! persistent_torrent_completed_stat = false //! remove_peerless_torrents = true //! //! [core.announce_policy] @@ -391,9 +393,11 @@ mod tests { [core] mode = "public" tracker_usage_statistics = true - persistent_torrent_completed_stat = false - max_peer_timeout = 900 inactive_peer_cleanup_interval = 600 + + [core.tracker_policy] + max_peer_timeout = 900 + persistent_torrent_completed_stat = false remove_peerless_torrents = true [core.announce_policy] diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index 3b9f3e3ad..fdbe211b3 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -43,22 +43,22 @@ fn rw_lock_parking_lot() -> Torrent { #[fixture] fn policy_none() -> TrackerPolicy { - TrackerPolicy::new(false, 0, false) + TrackerPolicy::new(0, false, false) } #[fixture] fn policy_persist() -> TrackerPolicy { - TrackerPolicy::new(false, 0, true) + TrackerPolicy::new(0, true, false) } #[fixture] fn policy_remove() -> TrackerPolicy { - TrackerPolicy::new(true, 0, false) + TrackerPolicy::new(0, false, true) } #[fixture] fn policy_remove_persist() -> TrackerPolicy { - TrackerPolicy::new(true, 0, true) + TrackerPolicy::new(0, true, true) } pub enum Makes { diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index dd9893cc9..b10f4a64a 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -220,22 +220,22 @@ fn paginated_limit_one_offset_one() -> Pagination { #[fixture] fn policy_none() -> TrackerPolicy { - TrackerPolicy::new(false, 0, false) + TrackerPolicy::new(0, false, false) } #[fixture] fn policy_persist() -> TrackerPolicy { - TrackerPolicy::new(false, 0, true) + TrackerPolicy::new(0, true, false) } #[fixture] fn policy_remove() -> TrackerPolicy { - TrackerPolicy::new(true, 0, false) + TrackerPolicy::new(0, false, true) } #[fixture] fn policy_remove_persist() -> TrackerPolicy { - TrackerPolicy::new(true, 0, true) + TrackerPolicy::new(0, true, true) } #[rstest] diff --git a/src/core/mod.rs b/src/core/mod.rs index 77f7099af..bd7ce4883 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -317,11 +317,13 @@ //! //! [core] //! mode = "public" -//! max_peer_timeout = 900 //! tracker_usage_statistics = true -//! persistent_torrent_completed_stat = true //! inactive_peer_cleanup_interval = 600 -//! remove_peerless_torrents = false +//! +//! [core.tracker_policy] +//! max_peer_timeout = 900 +//! persistent_torrent_completed_stat = false +//! remove_peerless_torrents = true //! //! [core.announce_policy] //! interval = 120 @@ -569,11 +571,7 @@ impl Tracker { stats_repository, database, external_ip: config.net.external_ip, - policy: TrackerPolicy::new( - config.remove_peerless_torrents, - config.max_peer_timeout, - config.persistent_torrent_completed_stat, - ), + policy: config.tracker_policy.clone(), on_reverse_proxy: config.net.on_reverse_proxy, }) } @@ -1043,7 +1041,7 @@ mod tests { pub fn tracker_persisting_torrents_in_database() -> Tracker { let mut configuration = configuration::ephemeral(); - configuration.core.persistent_torrent_completed_stat = true; + configuration.core.tracker_policy.persistent_torrent_completed_stat = true; tracker_factory(&configuration) } diff --git a/src/lib.rs b/src/lib.rs index 5c0fd4b56..c059f6df7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -172,11 +172,13 @@ //! //! [core] //! inactive_peer_cleanup_interval = 600 -//! max_peer_timeout = 900 //! mode = "public" +//! tracker_usage_statistics = true +//! +//! [core.tracker_policy] +//! max_peer_timeout = 900 //! persistent_torrent_completed_stat = false //! remove_peerless_torrents = true -//! tracker_usage_statistics = true //! //! [core.announce_policy] //! interval = 120 From c5cc9fd6a461ad439fb81b405ecbe652d82fd4fb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Jun 2024 19:34:56 +0100 Subject: [PATCH 0384/1297] feat: [#878] extract tsl_config in toml config TSL configuration for HTTP trackers and the Tracker API is still optional. However, when it's provided is enabled. The `ssl_enabled` field was removed. You can remove the whole `tsl_config` to disable TSL. If you want to kee a copy in the TOML file you can just comment the lines. ```toml [[http_trackers]] ... [http_trackers.tsl_config] ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" ssl_key_path = "./storage/tracker/lib/tls/localhost.key" [http_api] ... [http_api.tsl_config] ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" ssl_key_path = "./storage/tracker/lib/tls/localhost.key" ``` --- Cargo.toml | 2 +- docs/containers.md | 23 +++--- packages/configuration/Cargo.toml | 2 +- packages/configuration/src/lib.rs | 17 +++-- packages/configuration/src/v1/http_tracker.rs | 19 +++-- packages/configuration/src/v1/mod.rs | 20 ++---- packages/configuration/src/v1/tracker_api.rs | 19 +++-- .../config/tracker.container.mysql.toml | 8 +-- .../config/tracker.container.sqlite3.toml | 8 --- .../config/tracker.e2e.container.sqlite3.toml | 6 -- src/bootstrap/jobs/http_tracker.rs | 2 +- src/bootstrap/jobs/mod.rs | 70 +++++++++---------- src/bootstrap/jobs/tracker_apis.rs | 2 +- src/lib.rs | 9 --- src/servers/apis/mod.rs | 12 ++-- src/servers/apis/server.rs | 2 +- src/servers/http/server.rs | 2 +- tests/servers/api/environment.rs | 2 +- tests/servers/http/environment.rs | 2 +- 19 files changed, 92 insertions(+), 135 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 072a21a7e..c22c3dd45 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,7 +37,7 @@ axum = { version = "0", features = ["macros"] } axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls"] } -camino = { version = "1.1.6", features = ["serde"] } +camino = { version = "1.1.6", features = ["serde", "serde1"] } chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } crossbeam-skiplist = "0.1" diff --git a/docs/containers.md b/docs/containers.md index 1a1ea2f0d..82c67c26e 100644 --- a/docs/containers.md +++ b/docs/containers.md @@ -330,24 +330,23 @@ The storage folder must contain your certificates: ```s storage/tracker/lib/tls - ├── localhost.crt - └── localhost.key + ├── localhost.crt + └── localhost.key +storage/http_api/lib/tls + ├── localhost.crt + └── localhost.key ``` You have not enabled it in your `tracker.toml` file: ```toml +[http_trackers.tsl_config] +ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +ssl_key_path = "./storage/tracker/lib/tls/localhost.key" -[[http_trackers]] -# ... -ssl_enabled = true -# ... - -[http_api] -# ... -ssl_enabled = true -# ... - +[http_api.tsl_config] +ssl_cert_path = "./storage/http_api/lib/tls/localhost.crt" +ssl_key_path = "./storage/http_api/lib/tls/localhost.key" ``` > NOTE: you can enable it independently for each HTTP tracker or the API. diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index bac2132d5..53e4e4cfa 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -15,7 +15,7 @@ rust-version.workspace = true version.workspace = true [dependencies] -camino = { version = "1.1.6", features = ["serde"] } +camino = { version = "1.1.6", features = ["serde", "serde1"] } derive_more = "0" figment = { version = "0.10.18", features = ["env", "test", "toml"] } serde = { version = "1", features = ["derive"] } diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 594a283db..c8c91443a 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -13,7 +13,7 @@ use std::sync::Arc; use camino::Utf8PathBuf; use derive_more::Constructor; use serde::{Deserialize, Serialize}; -use serde_with::{serde_as, NoneAsEmptyString}; +use serde_with::serde_as; use thiserror::Error; use torrust_tracker_located_error::{DynError, LocatedError}; @@ -215,24 +215,23 @@ impl From for Error { #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Default)] pub struct TslConfig { /// Path to the SSL certificate file. - #[serde_as(as = "NoneAsEmptyString")] #[serde(default = "TslConfig::default_ssl_cert_path")] - pub ssl_cert_path: Option, + pub ssl_cert_path: Utf8PathBuf, + /// Path to the SSL key file. - #[serde_as(as = "NoneAsEmptyString")] #[serde(default = "TslConfig::default_ssl_key_path")] - pub ssl_key_path: Option, + pub ssl_key_path: Utf8PathBuf, } impl TslConfig { #[allow(clippy::unnecessary_wraps)] - fn default_ssl_cert_path() -> Option { - Some(Utf8PathBuf::new()) + fn default_ssl_cert_path() -> Utf8PathBuf { + Utf8PathBuf::new() } #[allow(clippy::unnecessary_wraps)] - fn default_ssl_key_path() -> Option { - Some(Utf8PathBuf::new()) + fn default_ssl_key_path() -> Utf8PathBuf { + Utf8PathBuf::new() } } diff --git a/packages/configuration/src/v1/http_tracker.rs b/packages/configuration/src/v1/http_tracker.rs index b1fe1437b..fed2282a5 100644 --- a/packages/configuration/src/v1/http_tracker.rs +++ b/packages/configuration/src/v1/http_tracker.rs @@ -12,19 +12,17 @@ pub struct HttpTracker { /// Weather the HTTP tracker is enabled or not. #[serde(default = "HttpTracker::default_enabled")] pub enabled: bool, + /// The address the tracker will bind to. /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating /// system to choose a random port, use port `0`. #[serde(default = "HttpTracker::default_bind_address")] pub bind_address: SocketAddr, - /// Weather the HTTP tracker will use SSL or not. - #[serde(default = "HttpTracker::default_ssl_enabled")] - pub ssl_enabled: bool, - /// TSL config. Only used if `ssl_enabled` is true. - #[serde(flatten)] - #[serde(default = "TslConfig::default")] - pub tsl_config: TslConfig, + + /// TSL config. + #[serde(default = "HttpTracker::default_tsl_config")] + pub tsl_config: Option, } impl Default for HttpTracker { @@ -32,8 +30,7 @@ impl Default for HttpTracker { Self { enabled: Self::default_enabled(), bind_address: Self::default_bind_address(), - ssl_enabled: Self::default_ssl_enabled(), - tsl_config: TslConfig::default(), + tsl_config: Self::default_tsl_config(), } } } @@ -47,7 +44,7 @@ impl HttpTracker { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 7070) } - fn default_ssl_enabled() -> bool { - false + fn default_tsl_config() -> Option { + None } } diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 19499cd4a..603be85d2 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -176,14 +176,16 @@ //! //! ```s //! [[http_trackers]] -//! enabled = true //! ... +//! +//! [http_trackers.tsl_config] //! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" //! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! //! [http_api] -//! enabled = true //! ... +//! +//! [http_api.tsl_config] //! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" //! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! ``` @@ -225,16 +227,10 @@ //! [[http_trackers]] //! enabled = false //! bind_address = "0.0.0.0:7070" -//! ssl_enabled = false -//! ssl_cert_path = "" -//! ssl_key_path = "" //! //! [http_api] //! enabled = true //! bind_address = "127.0.0.1:1212" -//! ssl_enabled = false -//! ssl_cert_path = "" -//! ssl_key_path = "" //! //! [http_api.access_tokens] //! admin = "MyAccessToken" @@ -419,16 +415,10 @@ mod tests { [[http_trackers]] enabled = false bind_address = "0.0.0.0:7070" - ssl_enabled = false - ssl_cert_path = "" - ssl_key_path = "" - + [http_api] enabled = true bind_address = "127.0.0.1:1212" - ssl_enabled = false - ssl_cert_path = "" - ssl_key_path = "" [http_api.access_tokens] admin = "MyAccessToken" diff --git a/packages/configuration/src/v1/tracker_api.rs b/packages/configuration/src/v1/tracker_api.rs index c2e3e5ee9..42794ad18 100644 --- a/packages/configuration/src/v1/tracker_api.rs +++ b/packages/configuration/src/v1/tracker_api.rs @@ -15,19 +15,18 @@ pub struct HttpApi { /// Weather the HTTP API is enabled or not. #[serde(default = "HttpApi::default_enabled")] pub enabled: bool, + /// The address the tracker will bind to. /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating /// system to choose a random port, use port `0`. #[serde(default = "HttpApi::default_bind_address")] pub bind_address: SocketAddr, - /// Weather the HTTP API will use SSL or not. - #[serde(default = "HttpApi::default_ssl_enabled")] - pub ssl_enabled: bool, + /// TSL config. Only used if `ssl_enabled` is true. - #[serde(flatten)] - #[serde(default = "TslConfig::default")] - pub tsl_config: TslConfig, + #[serde(default = "HttpApi::default_tsl_config")] + pub tsl_config: Option, + /// Access tokens for the HTTP API. The key is a label identifying the /// token and the value is the token itself. The token is used to /// authenticate the user. All tokens are valid for all endpoints and have @@ -41,8 +40,7 @@ impl Default for HttpApi { Self { enabled: Self::default_enabled(), bind_address: Self::default_bind_address(), - ssl_enabled: Self::default_ssl_enabled(), - tsl_config: TslConfig::default(), + tsl_config: Self::default_tsl_config(), access_tokens: Self::default_access_tokens(), } } @@ -57,8 +55,9 @@ impl HttpApi { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1212) } - fn default_ssl_enabled() -> bool { - false + #[allow(clippy::unnecessary_wraps)] + fn default_tsl_config() -> Option { + None } fn default_access_tokens() -> AccessTokens { diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml index 75cc57b64..70ee8b500 100644 --- a/share/default/config/tracker.container.mysql.toml +++ b/share/default/config/tracker.container.mysql.toml @@ -3,9 +3,5 @@ driver = "MySQL" path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" [[http_trackers]] -ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" -ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" - -[http_api] -ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" -ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" +bind_address = "0.0.0.0:7070" +enabled = true diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml index 433e36127..f7bb6b8bb 100644 --- a/share/default/config/tracker.container.sqlite3.toml +++ b/share/default/config/tracker.container.sqlite3.toml @@ -1,10 +1,2 @@ [core.database] path = "/var/lib/torrust/tracker/database/sqlite3.db" - -[[http_trackers]] -ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" -ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" - -[http_api] -ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" -ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" diff --git a/share/default/config/tracker.e2e.container.sqlite3.toml b/share/default/config/tracker.e2e.container.sqlite3.toml index b8adedefb..744d267fd 100644 --- a/share/default/config/tracker.e2e.container.sqlite3.toml +++ b/share/default/config/tracker.e2e.container.sqlite3.toml @@ -6,12 +6,6 @@ enabled = true [[http_trackers]] enabled = true -ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" -ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" - -[http_api] -ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" -ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" [health_check_api] # Must be bound to wildcard IP to be accessible from outside the container diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index e9eb6bc16..05bfe2341 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -42,7 +42,7 @@ pub async fn start_job( if config.enabled { let socket = config.bind_address; - let tls = make_rust_tls(config.ssl_enabled, &config.tsl_config) + let tls = make_rust_tls(&config.tsl_config) .await .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 316e5746c..f42a843f4 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -20,27 +20,33 @@ pub struct Started { pub address: std::net::SocketAddr, } -pub async fn make_rust_tls(enabled: bool, tsl_config: &TslConfig) -> Option> { - if !enabled { - info!("TLS not enabled"); - return None; - } +pub async fn make_rust_tls(opt_tsl_config: &Option) -> Option> { + match opt_tsl_config { + Some(tsl_config) => { + let cert = tsl_config.ssl_cert_path.clone(); + let key = tsl_config.ssl_key_path.clone(); - if let (Some(cert), Some(key)) = (tsl_config.ssl_cert_path.clone(), tsl_config.ssl_key_path.clone()) { - info!("Using https: cert path: {cert}."); - info!("Using https: key path: {key}."); - - Some( - RustlsConfig::from_pem_file(cert, key) - .await - .map_err(|err| Error::BadTlsConfig { - source: (Arc::new(err) as DynError).into(), - }), - ) - } else { - Some(Err(Error::MissingTlsConfig { - location: Location::caller(), - })) + if !cert.exists() || !key.exists() { + return Some(Err(Error::MissingTlsConfig { + location: Location::caller(), + })); + } + + info!("Using https: cert path: {cert}."); + info!("Using https: key path: {key}."); + + Some( + RustlsConfig::from_pem_file(cert, key) + .await + .map_err(|err| Error::BadTlsConfig { + source: (Arc::new(err) as DynError).into(), + }), + ) + } + None => { + info!("TLS not enabled"); + None + } } } @@ -54,29 +60,23 @@ mod tests { #[tokio::test] async fn it_should_error_on_bad_tls_config() { - let err = make_rust_tls( - true, - &TslConfig { - ssl_cert_path: Some(Utf8PathBuf::from("bad cert path")), - ssl_key_path: Some(Utf8PathBuf::from("bad key path")), - }, - ) + let err = make_rust_tls(&Some(TslConfig { + ssl_cert_path: Utf8PathBuf::from("bad cert path"), + ssl_key_path: Utf8PathBuf::from("bad key path"), + })) .await .expect("tls_was_enabled") .expect_err("bad_cert_and_key_files"); - assert!(matches!(err, Error::BadTlsConfig { source: _ })); + assert!(matches!(err, Error::MissingTlsConfig { location: _ })); } #[tokio::test] async fn it_should_error_on_missing_cert_or_key_paths() { - let err = make_rust_tls( - true, - &TslConfig { - ssl_cert_path: None, - ssl_key_path: None, - }, - ) + let err = make_rust_tls(&Some(TslConfig { + ssl_cert_path: Utf8PathBuf::from(""), + ssl_key_path: Utf8PathBuf::from(""), + })) .await .expect("tls_was_enabled") .expect_err("missing_config"); diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 3c1f13255..c3b12d7a1 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -63,7 +63,7 @@ pub async fn start_job( if config.enabled { let bind_to = config.bind_address; - let tls = make_rust_tls(config.ssl_enabled, &config.tsl_config) + let tls = make_rust_tls(&config.tsl_config) .await .map(|tls| tls.expect("it should have a valid tracker api tls configuration")); diff --git a/src/lib.rs b/src/lib.rs index c059f6df7..7f8c70a47 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -199,16 +199,10 @@ //! [[http_trackers]] //! bind_address = "0.0.0.0:7070" //! enabled = false -//! ssl_cert_path = "" -//! ssl_enabled = false -//! ssl_key_path = "" //! //! [http_api] //! bind_address = "127.0.0.1:1212" //! enabled = true -//! ssl_cert_path = "" -//! ssl_enabled = false -//! ssl_key_path = "" //! //! [http_api.access_tokens] //! admin = "MyAccessToken" @@ -261,9 +255,6 @@ //! [http_api] //! enabled = true //! bind_address = "127.0.0.1:1212" -//! ssl_enabled = false -//! ssl_cert_path = "" -//! ssl_key_path = "" //! ``` //! //! By default it's enabled on port `1212`. You also need to add access tokens in the configuration: diff --git a/src/servers/apis/mod.rs b/src/servers/apis/mod.rs index 47d40c654..02b93efa6 100644 --- a/src/servers/apis/mod.rs +++ b/src/servers/apis/mod.rs @@ -27,7 +27,8 @@ //! [http_api] //! enabled = true //! bind_address = "0.0.0.0:1212" -//! ssl_enabled = false +//! +//! [http_api.tsl_config] //! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" //! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! @@ -106,16 +107,15 @@ //! //! # Setup SSL (optional) //! -//! The API server supports SSL. You can enable it by setting the -//! [`ssl_enabled`](torrust_tracker_configuration::HttpApi::ssl_enabled) option -//! to `true` in the configuration file -//! ([`http_api`](torrust_tracker_configuration::HttpApi) section). +//! The API server supports SSL. You can enable it by adding the `tsl_config` +//! section to the configuration. //! //! ```toml //! [http_api] //! enabled = true //! bind_address = "0.0.0.0:1212" -//! ssl_enabled = true +//! +//! [http_api.tsl_config] //! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" //! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 7c5b8983b..74dc89692 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -280,7 +280,7 @@ mod tests { let bind_to = config.bind_address; - let tls = make_rust_tls(config.ssl_enabled, &config.tsl_config) + let tls = make_rust_tls(&config.tsl_config) .await .map(|tls| tls.expect("tls config failed")); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 5c33fc8fa..bbe0c3cc1 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -239,7 +239,7 @@ mod tests { let bind_to = config.bind_address; - let tls = make_rust_tls(config.ssl_enabled, &config.tsl_config) + let tls = make_rust_tls(&config.tsl_config) .await .map(|tls| tls.expect("tls config failed")); diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index cacde8af9..8f84620dd 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -35,7 +35,7 @@ impl Environment { let bind_to = config.bind_address; - let tls = block_on(make_rust_tls(config.ssl_enabled, &config.tsl_config)).map(|tls| tls.expect("tls config failed")); + let tls = block_on(make_rust_tls(&config.tsl_config)).map(|tls| tls.expect("tls config failed")); let server = ApiServer::new(Launcher::new(bind_to, tls)); diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 61837c40f..6e80569ec 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -33,7 +33,7 @@ impl Environment { let bind_to = config.bind_address; - let tls = block_on(make_rust_tls(config.ssl_enabled, &config.tsl_config)).map(|tls| tls.expect("tls config failed")); + let tls = block_on(make_rust_tls(&config.tsl_config)).map(|tls| tls.expect("tls config failed")); let server = HttpServer::new(Launcher::new(bind_to, tls)); From 50bef25af092414b46d13ce393dacc22b4f9a2cf Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Jun 2024 08:36:57 +0100 Subject: [PATCH 0385/1297] feat: remove ambiguous log entry It remvoes this line: ``` 2024-06-17T18:52:49.196708Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled ``` becuase it doesn't specifu which service the TSl is not enabled for. On the other hand, the output already indicates whether the service is runnig on HTTP or HTTPs: ``` 2024-06-18T07:37:58.595692Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 ``` --- src/bootstrap/jobs/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index f42a843f4..87a607720 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -44,7 +44,6 @@ pub async fn make_rust_tls(opt_tsl_config: &Option) -> Option { - info!("TLS not enabled"); None } } From 06ad5dabe82ebef947b8b54c19ac9a74eca33335 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Jun 2024 10:11:11 +0100 Subject: [PATCH 0386/1297] feat!: [#878] remove enabled fields in config By default all services are disabled. If the service section is missing in the TOML config file it means the service is disabled. From: ```toml [[udp_trackers]] enabled = false bind_address = "0.0.0.0:6969" ``` To: ```toml ``` The `http_api` section has been disabled by default becuase there is no way to override it to disable it, if it's enabled by default. You nned to explicitly enabled the API now. --- docs/benchmarking.md | 4 +- packages/configuration/src/v1/http_tracker.rs | 9 --- packages/configuration/src/v1/mod.rs | 47 ++--------- packages/configuration/src/v1/tracker_api.rs | 9 --- packages/configuration/src/v1/udp_tracker.rs | 8 -- packages/test-helpers/src/configuration.rs | 39 ++++++--- .../config/tracker.container.mysql.toml | 16 +++- .../config/tracker.container.sqlite3.toml | 14 ++++ .../config/tracker.development.sqlite3.toml | 10 ++- .../config/tracker.e2e.container.sqlite3.toml | 10 ++- .../config/tracker.udp.benchmarking.toml | 5 +- src/app.rs | 81 ++++++++++--------- src/bootstrap/jobs/http_tracker.rs | 21 ++--- src/bootstrap/jobs/mod.rs | 4 +- src/bootstrap/jobs/tracker_apis.rs | 22 ++--- src/lib.rs | 21 +---- src/servers/apis/mod.rs | 2 - src/servers/apis/server.rs | 2 +- src/servers/http/server.rs | 5 +- src/servers/udp/server.rs | 3 +- tests/servers/api/environment.rs | 2 +- tests/servers/http/environment.rs | 7 +- tests/servers/udp/environment.rs | 4 +- 23 files changed, 156 insertions(+), 189 deletions(-) diff --git a/docs/benchmarking.md b/docs/benchmarking.md index 67b680fdc..ce3b69057 100644 --- a/docs/benchmarking.md +++ b/docs/benchmarking.md @@ -33,7 +33,7 @@ Run the tracker with UDP service enabled and other services disabled and set log log_level = "error" [[udp_trackers]] -enabled = true +bind_address = "0.0.0.0:6969" ``` Build and run the tracker: @@ -168,7 +168,7 @@ Run the tracker with UDP service enabled and other services disabled and set log log_level = "error" [[udp_trackers]] -enabled = true +bind_address = "0.0.0.0:6969" ``` ```console diff --git a/packages/configuration/src/v1/http_tracker.rs b/packages/configuration/src/v1/http_tracker.rs index fed2282a5..42ec02bf2 100644 --- a/packages/configuration/src/v1/http_tracker.rs +++ b/packages/configuration/src/v1/http_tracker.rs @@ -9,10 +9,6 @@ use crate::TslConfig; #[serde_as] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct HttpTracker { - /// Weather the HTTP tracker is enabled or not. - #[serde(default = "HttpTracker::default_enabled")] - pub enabled: bool, - /// The address the tracker will bind to. /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating @@ -28,7 +24,6 @@ pub struct HttpTracker { impl Default for HttpTracker { fn default() -> Self { Self { - enabled: Self::default_enabled(), bind_address: Self::default_bind_address(), tsl_config: Self::default_tsl_config(), } @@ -36,10 +31,6 @@ impl Default for HttpTracker { } impl HttpTracker { - fn default_enabled() -> bool { - false - } - fn default_bind_address() -> SocketAddr { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 7070) } diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 603be85d2..546f55b6e 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -220,16 +220,7 @@ //! external_ip = "0.0.0.0" //! on_reverse_proxy = false //! -//! [[udp_trackers]] -//! enabled = false -//! bind_address = "0.0.0.0:6969" -//! -//! [[http_trackers]] -//! enabled = false -//! bind_address = "0.0.0.0:7070" -//! //! [http_api] -//! enabled = true //! bind_address = "127.0.0.1:1212" //! //! [http_api.access_tokens] @@ -267,7 +258,7 @@ const CONFIG_OVERRIDE_PREFIX: &str = "TORRUST_TRACKER_CONFIG_OVERRIDE_"; const CONFIG_OVERRIDE_SEPARATOR: &str = "__"; /// Core configuration for the tracker. -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Default)] pub struct Configuration { /// Logging configuration pub logging: Logging, @@ -278,33 +269,20 @@ pub struct Configuration { /// The list of UDP trackers the tracker is running. Each UDP tracker /// represents a UDP server that the tracker is running and it has its own /// configuration. - pub udp_trackers: Vec, + pub udp_trackers: Option>, /// The list of HTTP trackers the tracker is running. Each HTTP tracker /// represents a HTTP server that the tracker is running and it has its own /// configuration. - pub http_trackers: Vec, + pub http_trackers: Option>, /// The HTTP API configuration. - pub http_api: HttpApi, + pub http_api: Option, /// The Health Check API configuration. pub health_check_api: HealthCheckApi, } -impl Default for Configuration { - fn default() -> Self { - Self { - logging: Logging::default(), - core: Core::default(), - udp_trackers: vec![UdpTracker::default()], - http_trackers: vec![HttpTracker::default()], - http_api: HttpApi::default(), - health_check_api: HealthCheckApi::default(), - } - } -} - impl Configuration { /// Returns the tracker public IP address id defined in the configuration, /// and `None` otherwise. @@ -408,21 +386,6 @@ mod tests { external_ip = "0.0.0.0" on_reverse_proxy = false - [[udp_trackers]] - enabled = false - bind_address = "0.0.0.0:6969" - - [[http_trackers]] - enabled = false - bind_address = "0.0.0.0:7070" - - [http_api] - enabled = true - bind_address = "127.0.0.1:1212" - - [http_api.access_tokens] - admin = "MyAccessToken" - [health_check_api] bind_address = "127.0.0.1:1313" "# @@ -556,7 +519,7 @@ mod tests { let configuration = Configuration::load(&info).expect("Could not load configuration from file"); assert_eq!( - configuration.http_api.access_tokens.get("admin"), + configuration.http_api.unwrap().access_tokens.get("admin"), Some("NewToken".to_owned()).as_ref() ); diff --git a/packages/configuration/src/v1/tracker_api.rs b/packages/configuration/src/v1/tracker_api.rs index 42794ad18..302a4ee95 100644 --- a/packages/configuration/src/v1/tracker_api.rs +++ b/packages/configuration/src/v1/tracker_api.rs @@ -12,10 +12,6 @@ pub type AccessTokens = HashMap; #[serde_as] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct HttpApi { - /// Weather the HTTP API is enabled or not. - #[serde(default = "HttpApi::default_enabled")] - pub enabled: bool, - /// The address the tracker will bind to. /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating @@ -38,7 +34,6 @@ pub struct HttpApi { impl Default for HttpApi { fn default() -> Self { Self { - enabled: Self::default_enabled(), bind_address: Self::default_bind_address(), tsl_config: Self::default_tsl_config(), access_tokens: Self::default_access_tokens(), @@ -47,10 +42,6 @@ impl Default for HttpApi { } impl HttpApi { - fn default_enabled() -> bool { - true - } - fn default_bind_address() -> SocketAddr { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1212) } diff --git a/packages/configuration/src/v1/udp_tracker.rs b/packages/configuration/src/v1/udp_tracker.rs index f8387202e..b3d420d72 100644 --- a/packages/configuration/src/v1/udp_tracker.rs +++ b/packages/configuration/src/v1/udp_tracker.rs @@ -4,9 +4,6 @@ use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct UdpTracker { - /// Weather the UDP tracker is enabled or not. - #[serde(default = "UdpTracker::default_enabled")] - pub enabled: bool, /// The address the tracker will bind to. /// The format is `ip:port`, for example `0.0.0.0:6969`. If you want to /// listen to all interfaces, use `0.0.0.0`. If you want the operating @@ -17,17 +14,12 @@ pub struct UdpTracker { impl Default for UdpTracker { fn default() -> Self { Self { - enabled: Self::default_enabled(), bind_address: Self::default_bind_address(), } } } impl UdpTracker { - fn default_enabled() -> bool { - false - } - fn default_bind_address() -> SocketAddr { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 6969) } diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 9c6c0fe11..646617b32 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -2,7 +2,7 @@ use std::env; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; -use torrust_tracker_configuration::{Configuration, LogLevel}; +use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, LogLevel, UdpTracker}; use torrust_tracker_primitives::TrackerMode; use crate::random; @@ -33,8 +33,10 @@ pub fn ephemeral() -> Configuration { // Ephemeral socket address for API let api_port = 0u16; - config.http_api.enabled = true; - config.http_api.bind_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), api_port); + config.http_api = Some(HttpApi { + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), api_port), + ..Default::default() + }); // Ephemeral socket address for Health Check API let health_check_api_port = 0u16; @@ -42,13 +44,16 @@ pub fn ephemeral() -> Configuration { // Ephemeral socket address for UDP tracker let udp_port = 0u16; - config.udp_trackers[0].enabled = true; - config.udp_trackers[0].bind_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), udp_port); + config.udp_trackers = Some(vec![UdpTracker { + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), udp_port), + }]); // Ephemeral socket address for HTTP tracker let http_port = 0u16; - config.http_trackers[0].enabled = true; - config.http_trackers[0].bind_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), http_port); + config.http_trackers = Some(vec![HttpTracker { + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), http_port), + tsl_config: None, + }]); // Ephemeral sqlite database let temp_directory = env::temp_dir(); @@ -137,9 +142,17 @@ pub fn ephemeral_ipv6() -> Configuration { let ipv6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), 0); - cfg.http_api.bind_address.clone_from(&ipv6); - cfg.http_trackers[0].bind_address.clone_from(&ipv6); - cfg.udp_trackers[0].bind_address = ipv6; + if let Some(ref mut http_api) = cfg.http_api { + http_api.bind_address.clone_from(&ipv6); + }; + + if let Some(ref mut http_trackers) = cfg.http_trackers { + http_trackers[0].bind_address.clone_from(&ipv6); + } + + if let Some(ref mut udp_trackers) = cfg.udp_trackers { + udp_trackers[0].bind_address.clone_from(&ipv6); + } cfg } @@ -149,9 +162,9 @@ pub fn ephemeral_ipv6() -> Configuration { pub fn ephemeral_with_no_services() -> Configuration { let mut cfg = ephemeral(); - cfg.http_api.enabled = false; - cfg.http_trackers[0].enabled = false; - cfg.udp_trackers[0].enabled = false; + cfg.http_api = None; + cfg.http_trackers = None; + cfg.udp_trackers = None; cfg } diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml index 70ee8b500..68cc8db8a 100644 --- a/share/default/config/tracker.container.mysql.toml +++ b/share/default/config/tracker.container.mysql.toml @@ -2,6 +2,16 @@ driver = "MySQL" path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" -[[http_trackers]] -bind_address = "0.0.0.0:7070" -enabled = true +# Uncomment to enable services + +#[[udp_trackers]] +#bind_address = "0.0.0.0:6969" + +#[[http_trackers]] +#bind_address = "0.0.0.0:7070" + +#[http_api] +#bind_address = "0.0.0.0:1212" + +#[http_api.access_tokens] +#admin = "MyAccessToken" diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml index f7bb6b8bb..63e169a70 100644 --- a/share/default/config/tracker.container.sqlite3.toml +++ b/share/default/config/tracker.container.sqlite3.toml @@ -1,2 +1,16 @@ [core.database] path = "/var/lib/torrust/tracker/database/sqlite3.db" + +# Uncomment to enable services + +#[[udp_trackers]] +#bind_address = "0.0.0.0:6969" + +#[[http_trackers]] +#bind_address = "0.0.0.0:7070" + +#[http_api] +#bind_address = "0.0.0.0:1212" + +#[http_api.access_tokens] +#admin = "MyAccessToken" diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index bf6478492..84754794e 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -1,5 +1,11 @@ [[udp_trackers]] -enabled = true +bind_address = "0.0.0.0:6969" [[http_trackers]] -enabled = true +bind_address = "0.0.0.0:7070" + +[http_api] +bind_address = "0.0.0.0:1212" + +[http_api.access_tokens] +admin = "MyAccessToken" diff --git a/share/default/config/tracker.e2e.container.sqlite3.toml b/share/default/config/tracker.e2e.container.sqlite3.toml index 744d267fd..fb33a8e32 100644 --- a/share/default/config/tracker.e2e.container.sqlite3.toml +++ b/share/default/config/tracker.e2e.container.sqlite3.toml @@ -2,10 +2,16 @@ path = "/var/lib/torrust/tracker/database/sqlite3.db" [[udp_trackers]] -enabled = true +bind_address = "0.0.0.0:6969" [[http_trackers]] -enabled = true +bind_address = "0.0.0.0:7070" + +[http_api] +bind_address = "0.0.0.0:1212" + +[http_api.access_tokens] +admin = "MyAccessToken" [health_check_api] # Must be bound to wildcard IP to be accessible from outside the container diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml index cd193c40a..d9361cf10 100644 --- a/share/default/config/tracker.udp.benchmarking.toml +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -6,7 +6,4 @@ remove_peerless_torrents = false tracker_usage_statistics = false [[udp_trackers]] -enabled = true - -[http_api] -enabled = false +bind_address = "0.0.0.0:6969" diff --git a/src/app.rs b/src/app.rs index b41f4098e..f6a909002 100644 --- a/src/app.rs +++ b/src/app.rs @@ -25,7 +25,7 @@ use std::sync::Arc; use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; -use tracing::warn; +use tracing::{info, warn}; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; use crate::servers::registar::Registar; @@ -59,51 +59,56 @@ pub async fn start(config: &Configuration, tracker: Arc) -> Vec { + for udp_tracker_config in udp_trackers { + if tracker.is_private() { + warn!( + "Could not start UDP tracker on: {} while in {:?}. UDP is not safe for private trackers!", + udp_tracker_config.bind_address, config.core.mode + ); + } else { + jobs.push(udp_tracker::start_job(udp_tracker_config, tracker.clone(), registar.give_form()).await); + } + } } + None => info!("No UDP blocks in configuration"), } // Start the HTTP blocks - for http_tracker_config in &config.http_trackers { - if !http_tracker_config.enabled { - continue; + match &config.http_trackers { + Some(http_trackers) => { + for http_tracker_config in http_trackers { + if let Some(job) = http_tracker::start_job( + http_tracker_config, + tracker.clone(), + registar.give_form(), + servers::http::Version::V1, + ) + .await + { + jobs.push(job); + }; + } } - - if let Some(job) = http_tracker::start_job( - http_tracker_config, - tracker.clone(), - registar.give_form(), - servers::http::Version::V1, - ) - .await - { - jobs.push(job); - }; + None => info!("No HTTP blocks in configuration"), } // Start HTTP API - if config.http_api.enabled { - if let Some(job) = tracker_apis::start_job( - &config.http_api, - tracker.clone(), - registar.give_form(), - servers::apis::Version::V1, - ) - .await - { - jobs.push(job); - }; + match &config.http_api { + Some(http_api_config) => { + if let Some(job) = tracker_apis::start_job( + http_api_config, + tracker.clone(), + registar.give_form(), + servers::apis::Version::V1, + ) + .await + { + jobs.push(job); + }; + } + None => info!("No API block in configuration"), } // Start runners to remove torrents without peers, every interval diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 05bfe2341..fed4e5347 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -16,7 +16,6 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; use torrust_tracker_configuration::HttpTracker; -use tracing::info; use super::make_rust_tls; use crate::core; @@ -39,19 +38,14 @@ pub async fn start_job( form: ServiceRegistrationForm, version: Version, ) -> Option> { - if config.enabled { - let socket = config.bind_address; + let socket = config.bind_address; - let tls = make_rust_tls(&config.tsl_config) - .await - .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); + let tls = make_rust_tls(&config.tsl_config) + .await + .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); - match version { - Version::V1 => Some(start_v1(socket, tls, tracker.clone(), form).await), - } - } else { - info!("Note: Not loading Http Tracker Service, Not Enabled in Configuration."); - None + match version { + Version::V1 => Some(start_v1(socket, tls, tracker.clone(), form).await), } } @@ -93,7 +87,8 @@ mod tests { #[tokio::test] async fn it_should_start_http_tracker() { let cfg = Arc::new(ephemeral_mode_public()); - let config = &cfg.http_trackers[0]; + let http_tracker = cfg.http_trackers.clone().expect("missing HTTP tracker configuration"); + let config = &http_tracker[0]; let tracker = initialize_with_configuration(&cfg); let version = Version::V1; diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 87a607720..79a4347ef 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -43,9 +43,7 @@ pub async fn make_rust_tls(opt_tsl_config: &Option) -> Option { - None - } + None => None, } } diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index c3b12d7a1..2067e5b0c 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -26,7 +26,6 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; use torrust_tracker_configuration::{AccessTokens, HttpApi}; -use tracing::info; use super::make_rust_tls; use crate::core; @@ -60,21 +59,16 @@ pub async fn start_job( form: ServiceRegistrationForm, version: Version, ) -> Option> { - if config.enabled { - let bind_to = config.bind_address; + let bind_to = config.bind_address; - let tls = make_rust_tls(&config.tsl_config) - .await - .map(|tls| tls.expect("it should have a valid tracker api tls configuration")); + let tls = make_rust_tls(&config.tsl_config) + .await + .map(|tls| tls.expect("it should have a valid tracker api tls configuration")); - let access_tokens = Arc::new(config.access_tokens.clone()); + let access_tokens = Arc::new(config.access_tokens.clone()); - match version { - Version::V1 => Some(start_v1(bind_to, tls, tracker.clone(), form, access_tokens).await), - } - } else { - info!("Note: Not loading Http Tracker Service, Not Enabled in Configuration."); - None + match version { + Version::V1 => Some(start_v1(bind_to, tls, tracker.clone(), form, access_tokens).await), } } @@ -110,7 +104,7 @@ mod tests { #[tokio::test] async fn it_should_start_http_tracker() { let cfg = Arc::new(ephemeral_mode_public()); - let config = &cfg.http_api; + let config = &cfg.http_api.clone().unwrap(); let tracker = initialize_with_configuration(&cfg); let version = Version::V1; diff --git a/src/lib.rs b/src/lib.rs index 7f8c70a47..cf2834418 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -192,21 +192,6 @@ //! external_ip = "0.0.0.0" //! on_reverse_proxy = false //! -//! [[udp_trackers]] -//! bind_address = "0.0.0.0:6969" -//! enabled = false -//! -//! [[http_trackers]] -//! bind_address = "0.0.0.0:7070" -//! enabled = false -//! -//! [http_api] -//! bind_address = "127.0.0.1:1212" -//! enabled = true -//! -//! [http_api.access_tokens] -//! admin = "MyAccessToken" -//! //! [health_check_api] //! bind_address = "127.0.0.1:1313" //!``` @@ -253,8 +238,10 @@ //! //! ```toml //! [http_api] -//! enabled = true //! bind_address = "127.0.0.1:1212" +//! +//! [http_api.access_tokens] +//! admin = "MyAccessToken" //! ``` //! //! By default it's enabled on port `1212`. You also need to add access tokens in the configuration: @@ -310,7 +297,6 @@ //! //! ```toml //! [[http_trackers]] -//! enabled = true //! bind_address = "0.0.0.0:7070" //! ``` //! @@ -405,7 +391,6 @@ //! //! ```toml //! [[udp_trackers]] -//! enabled = true //! bind_address = "0.0.0.0:6969" //! ``` //! diff --git a/src/servers/apis/mod.rs b/src/servers/apis/mod.rs index 02b93efa6..6dae66c2d 100644 --- a/src/servers/apis/mod.rs +++ b/src/servers/apis/mod.rs @@ -25,7 +25,6 @@ //! //! ```toml //! [http_api] -//! enabled = true //! bind_address = "0.0.0.0:1212" //! //! [http_api.tsl_config] @@ -112,7 +111,6 @@ //! //! ```toml //! [http_api] -//! enabled = true //! bind_address = "0.0.0.0:1212" //! //! [http_api.tsl_config] diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 74dc89692..246660ab1 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -274,7 +274,7 @@ mod tests { #[tokio::test] async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_mode_public()); - let config = &cfg.http_api; + let config = &cfg.http_api.clone().unwrap(); let tracker = initialize_with_configuration(&cfg); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index bbe0c3cc1..5798f7c10 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -206,7 +206,7 @@ impl HttpServer { /// Or if the request returns an error. #[must_use] pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { - let url = format!("http://{binding}/health_check"); + let url = format!("http://{binding}/health_check"); // DevSkim: ignore DS137138 let info = format!("checking http tracker health check at: {url}"); @@ -235,7 +235,8 @@ mod tests { async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_mode_public()); let tracker = initialize_with_configuration(&cfg); - let config = &cfg.http_trackers[0]; + let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); + let config = &http_trackers[0]; let bind_to = config.bind_address; diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index b2c72258d..f36f7df45 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -460,7 +460,8 @@ mod tests { async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_mode_public()); let tracker = initialize_with_configuration(&cfg); - let config = &cfg.udp_trackers[0]; + let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); + let config = &udp_trackers[0]; let bind_to = config.bind_address; let register = &Registar::default(); diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 8f84620dd..dc2f70a76 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -31,7 +31,7 @@ impl Environment { pub fn new(configuration: &Arc) -> Self { let tracker = initialize_with_configuration(configuration); - let config = Arc::new(configuration.http_api.clone()); + let config = Arc::new(configuration.http_api.clone().expect("missing API configuration")); let bind_to = config.bind_address; diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 6e80569ec..2133ed6d0 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -29,7 +29,12 @@ impl Environment { pub fn new(configuration: &Arc) -> Self { let tracker = initialize_with_configuration(configuration); - let config = Arc::new(configuration.http_trackers[0].clone()); + let http_tracker = configuration + .http_trackers + .clone() + .expect("missing HTTP tracker configuration"); + + let config = Arc::new(http_tracker[0].clone()); let bind_to = config.bind_address; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index c1fecbdd3..1ba038c70 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -29,7 +29,9 @@ impl Environment { pub fn new(configuration: &Arc) -> Self { let tracker = initialize_with_configuration(configuration); - let config = Arc::new(configuration.udp_trackers[0].clone()); + let udp_tracker = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); + + let config = Arc::new(udp_tracker[0].clone()); let bind_to = config.bind_address; From 0bcca80fe6b570d874c2fd49d763221778b70912 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Jun 2024 10:51:26 +0100 Subject: [PATCH 0387/1297] chore(deps): update dependencies ```console cargo update Updating crates.io index Locking 18 packages to latest compatible versions Updating bytemuck v1.16.0 -> v1.16.1 Updating derive_more v0.99.17 -> v0.99.18 Removing displaydoc v0.2.4 Adding hermit-abi v0.4.0 Updating httparse v1.9.3 -> v1.9.4 Adding hyper-rustls v0.27.2 Removing icu_collections v1.5.0 Removing icu_locid v1.5.0 Removing icu_locid_transform v1.5.0 Removing icu_locid_transform_data v1.5.0 Removing icu_normalizer v1.5.0 Removing icu_normalizer_data v1.5.0 Removing icu_properties v1.5.0 Removing icu_properties_data v1.5.0 Removing icu_provider v1.5.0 Removing icu_provider_macros v1.5.0 Downgrading idna v1.0.0 -> v0.5.0 (latest: v1.0.1) Removing litemap v0.7.3 Updating miniz_oxide v0.7.3 -> v0.7.4 Updating polling v3.7.1 -> v3.7.2 Updating reqwest v0.12.4 -> v0.12.5 Adding rustls v0.23.10 Adding rustls-webpki v0.102.4 Removing stable_deref_trait v1.2.0 Adding subtle v2.5.0 Removing synstructure v0.13.1 Removing tinystr v0.7.6 Adding tokio-rustls v0.26.0 Adding unicode-bidi v0.3.15 Adding unicode-normalization v0.1.23 Updating url v2.5.1 -> v2.5.2 Removing utf16_iter v1.0.5 Removing utf8_iter v1.0.4 Removing write16 v1.0.0 Removing writeable v0.5.5 Removing yoke v0.7.4 Removing yoke-derive v0.7.4 Removing zerofrom v0.1.4 Removing zerofrom-derive v0.1.4 Adding zeroize v1.8.1 Removing zerovec v0.10.2 Removing zerovec-derive v0.10.2 Updating zstd-sys v2.0.10+zstd.1.5.6 -> v2.0.11+zstd.1.5.6 ``` --- Cargo.lock | 397 +++++++++++++++-------------------------------------- 1 file changed, 114 insertions(+), 283 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7a54063bf..94fbe7d87 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -288,7 +288,7 @@ dependencies = [ "futures-io", "futures-lite 2.3.0", "parking", - "polling 3.7.1", + "polling 3.7.2", "rustix 0.38.34", "slab", "tracing", @@ -497,10 +497,10 @@ dependencies = [ "hyper", "hyper-util", "pin-project-lite", - "rustls", + "rustls 0.21.12", "rustls-pemfile", "tokio", - "tokio-rustls", + "tokio-rustls 0.24.1", "tower", "tower-service", ] @@ -696,9 +696,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.16.0" +version = "1.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78834c15cb5d5efe3452d58b1e8ba890dd62d21907f867f383358198e56ebca5" +checksum = "b236fc92302c97ed75b38da1f4917b5cdda4984745740f153a5d3059e48d725e" [[package]] name = "byteorder" @@ -1116,15 +1116,15 @@ dependencies = [ [[package]] name = "derive_more" -version = "0.99.17" +version = "0.99.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" +checksum = "5f33878137e4dafd7fa914ad4e259e18a4e8e532b9617a2d0150262bf53abfce" dependencies = [ "convert_case", "proc-macro2", "quote", "rustc_version", - "syn 1.0.109", + "syn 2.0.66", ] [[package]] @@ -1148,17 +1148,6 @@ dependencies = [ "crypto-common", ] -[[package]] -name = "displaydoc" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.66", -] - [[package]] name = "downcast" version = "0.11.0" @@ -1652,6 +1641,12 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" +[[package]] +name = "hermit-abi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" + [[package]] name = "hex" version = "0.4.3" @@ -1700,9 +1695,9 @@ dependencies = [ [[package]] name = "httparse" -version = "1.9.3" +version = "1.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0e7a4dd27b9476dc40cb050d3632d3bba3a70ddbff012285f7f8559a1e7e545" +checksum = "0fcc0b4a115bf80b728eb8ea024ad5bd707b615bfed49e0665b6e0f86fd082d9" [[package]] name = "httpdate" @@ -1731,6 +1726,23 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-rustls" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ee4be2c948921a1a5320b629c4193916ed787a7f7f293fd3f7f5a6c9de74155" +dependencies = [ + "futures-util", + "http", + "hyper", + "hyper-util", + "rustls 0.23.10", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.26.0", + "tower-service", +] + [[package]] name = "hyper-tls" version = "0.6.0" @@ -1790,124 +1802,6 @@ dependencies = [ "cc", ] -[[package]] -name = "icu_collections" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locid" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_locid_transform" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" -dependencies = [ - "displaydoc", - "icu_locid", - "icu_locid_transform_data", - "icu_provider", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_locid_transform_data" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" - -[[package]] -name = "icu_normalizer" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "utf16_iter", - "utf8_iter", - "write16", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" - -[[package]] -name = "icu_properties" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f8ac670d7422d7f76b32e17a5db556510825b29ec9154f235977c9caba61036" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_locid_transform", - "icu_properties_data", - "icu_provider", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" - -[[package]] -name = "icu_provider" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" -dependencies = [ - "displaydoc", - "icu_locid", - "icu_provider_macros", - "stable_deref_trait", - "tinystr", - "writeable", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_provider_macros" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.66", -] - [[package]] name = "ident_case" version = "1.0.1" @@ -1916,14 +1810,12 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "idna" -version = "1.0.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4716a3a0933a1d01c2f72450e89596eb51dd34ef3c211ccd875acdf1f8fe47ed" +checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" dependencies = [ - "icu_normalizer", - "icu_properties", - "smallvec", - "utf8_iter", + "unicode-bidi", + "unicode-normalization", ] [[package]] @@ -1978,7 +1870,7 @@ version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ - "hermit-abi", + "hermit-abi 0.3.9", "libc", "windows-sys 0.48.0", ] @@ -1995,7 +1887,7 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f23ff5ef2b80d608d61efee834934d862cd92461afc0560dedf493e4c033738b" dependencies = [ - "hermit-abi", + "hermit-abi 0.3.9", "libc", "windows-sys 0.52.0", ] @@ -2192,12 +2084,6 @@ version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" -[[package]] -name = "litemap" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" - [[package]] name = "local-ip-address" version = "0.6.1" @@ -2264,9 +2150,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87dfd01fe195c66b572b37921ad8803d010623c0aca821bea2302239d155cdae" +checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" dependencies = [ "adler", ] @@ -2517,7 +2403,7 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ - "hermit-abi", + "hermit-abi 0.3.9", "libc", ] @@ -2793,13 +2679,13 @@ dependencies = [ [[package]] name = "polling" -version = "3.7.1" +version = "3.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6a007746f34ed64099e88783b0ae369eaa3da6392868ba262e2af9b8fbaea1" +checksum = "a3ed00ed3fbf728b5816498ecd316d1716eecaced9c0c8d2c5a6740ca214985b" dependencies = [ "cfg-if", "concurrent-queue", - "hermit-abi", + "hermit-abi 0.4.0", "pin-project-lite", "rustix 0.38.34", "tracing", @@ -3092,9 +2978,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.4" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "566cafdd92868e0939d3fb961bd0dc25fcfaaed179291093b3d43e6b3150ea10" +checksum = "c7d6d2a27d57148378eb5e111173f4276ad26340ecc5c49a4a2152167a2d6a37" dependencies = [ "base64 0.22.1", "bytes", @@ -3106,6 +2992,7 @@ dependencies = [ "http-body", "http-body-util", "hyper", + "hyper-rustls", "hyper-tls", "hyper-util", "ipnet", @@ -3120,7 +3007,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "sync_wrapper 0.1.2", + "sync_wrapper 1.0.1", "system-configuration", "tokio", "tokio-native-tls", @@ -3301,10 +3188,23 @@ checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" dependencies = [ "log", "ring", - "rustls-webpki", + "rustls-webpki 0.101.7", "sct", ] +[[package]] +name = "rustls" +version = "0.23.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05cff451f60db80f490f3c182b77c35260baace73209e9cdbbe526bfe3a4d402" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki 0.102.4", + "subtle", + "zeroize", +] + [[package]] name = "rustls-pemfile" version = "2.1.2" @@ -3331,6 +3231,17 @@ dependencies = [ "untrusted", ] +[[package]] +name = "rustls-webpki" +version = "0.102.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff448f7e92e913c4b7d4c6d8e4540a1724b319b4152b8aef6d4cf8339712b33e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.17" @@ -3662,12 +3573,6 @@ version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" -[[package]] -name = "stable_deref_trait" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" - [[package]] name = "static_assertions" version = "1.1.0" @@ -3690,6 +3595,12 @@ dependencies = [ "winapi", ] +[[package]] +name = "subtle" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" + [[package]] name = "syn" version = "1.0.109" @@ -3736,17 +3647,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" -[[package]] -name = "synstructure" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.66", -] - [[package]] name = "system-configuration" version = "0.5.1" @@ -3879,16 +3779,6 @@ dependencies = [ "time-core", ] -[[package]] -name = "tinystr" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" -dependencies = [ - "displaydoc", - "zerovec", -] - [[package]] name = "tinytemplate" version = "1.2.1" @@ -3959,7 +3849,18 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ - "rustls", + "rustls 0.21.12", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" +dependencies = [ + "rustls 0.23.10", + "rustls-pki-types", "tokio", ] @@ -4337,12 +4238,27 @@ dependencies = [ "version_check", ] +[[package]] +name = "unicode-bidi" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" + [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" +[[package]] +name = "unicode-normalization" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" +dependencies = [ + "tinyvec", +] + [[package]] name = "untrusted" version = "0.9.0" @@ -4351,27 +4267,15 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.1" +version = "2.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c25da092f0a868cdf09e8674cd3b7ef3a7d92a24253e663a2fb85e2496de56" +checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c" dependencies = [ "form_urlencoded", "idna", "percent-encoding", ] -[[package]] -name = "utf16_iter" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - [[package]] name = "utf8parse" version = "0.2.2" @@ -4726,18 +4630,6 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "write16" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" - -[[package]] -name = "writeable" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" - [[package]] name = "wyz" version = "0.5.1" @@ -4753,30 +4645,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" -[[package]] -name = "yoke" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" -dependencies = [ - "serde", - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.66", - "synstructure", -] - [[package]] name = "zerocopy" version = "0.7.34" @@ -4799,47 +4667,10 @@ dependencies = [ ] [[package]] -name = "zerofrom" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.66", - "synstructure", -] - -[[package]] -name = "zerovec" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb2cc8827d6c0994478a15c53f374f46fbd41bea663d809b14744bc42e6b109c" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.10.2" +name = "zeroize" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97cf56601ee5052b4417d90c8755c6683473c926039908196cf35d99f893ebe7" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.66", -] +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" [[package]] name = "zstd" @@ -4861,9 +4692,9 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.0.10+zstd.1.5.6" +version = "2.0.11+zstd.1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c253a4914af5bafc8fa8c86ee400827e83cf6ec01195ec1f1ed8441bf00d65aa" +checksum = "75652c55c0b6f3e6f12eb786fe1bc960396bf05a1eb3bf1f3691c3610ac2e6d4" dependencies = [ "cc", "pkg-config", From 84cc1a1d39432456b2b0c306d8289f6a618da7b1 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 19 Jun 2024 15:44:02 +0200 Subject: [PATCH 0388/1297] dev: use stream for udp requests --- .cargo/config.toml | 1 - cSpell.json | 2 + src/lib.rs | 2 +- src/servers/udp/handlers.rs | 8 +- src/servers/udp/server.rs | 476 +++++++++++++------ src/shared/bit_torrent/tracker/udp/client.rs | 57 ++- tests/servers/udp/contract.rs | 66 ++- tests/servers/udp/environment.rs | 11 +- 8 files changed, 425 insertions(+), 198 deletions(-) diff --git a/.cargo/config.toml b/.cargo/config.toml index 34d6230b9..a88db5f38 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -23,4 +23,3 @@ rustflags = [ "-D", "unused", ] - diff --git a/cSpell.json b/cSpell.json index ef807f035..6a9da0324 100644 --- a/cSpell.json +++ b/cSpell.json @@ -34,10 +34,12 @@ "codecov", "codegen", "completei", + "Condvar", "connectionless", "Containerfile", "conv", "curr", + "cvar", "Cyberneering", "dashmap", "datagram", diff --git a/src/lib.rs b/src/lib.rs index cf2834418..bb6826dd1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -494,7 +494,7 @@ pub mod bootstrap; pub mod console; pub mod core; pub mod servers; -pub mod shared; +pub mod shared; #[macro_use] extern crate lazy_static; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 36825f084..f7e3aac64 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -10,7 +10,6 @@ use aquatic_udp_protocol::{ ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfDownloads, NumberOfPeers, Port, Request, Response, ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; -use tokio::net::UdpSocket; use torrust_tracker_located_error::DynError; use torrust_tracker_primitives::info_hash::InfoHash; use tracing::debug; @@ -34,13 +33,12 @@ use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; /// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. -pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc, socket: Arc) -> Response { +pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc, addr: SocketAddr) -> Response { debug!("Handling Packets: {udp_request:?}"); let start_time = Instant::now(); let request_id = RequestId::make(&udp_request); - let server_socket_addr = socket.local_addr().expect("Could not get local_addr for socket."); match Request::parse_bytes(&udp_request.payload[..udp_request.payload.len()], MAX_SCRAPE_TORRENTS).map_err(|e| { Error::InternalServer { @@ -49,7 +47,7 @@ pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc { - log_request(&request, &request_id, &server_socket_addr); + log_request(&request, &request_id, &addr); let transaction_id = match &request { Request::Connect(connect_request) => connect_request.transaction_id, @@ -64,7 +62,7 @@ pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc { /// /// It panics if unable to receive the bound socket address from service. /// - pub async fn start(self, tracker: Arc, form: ServiceRegistrationForm) -> Result, Error> { + pub async fn start(self, tracker: Arc, form: ServiceRegistrationForm) -> Result, std::io::Error> { let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); @@ -129,6 +138,7 @@ impl UdpServer { let task = self.state.launcher.start(tracker, tx_start, rx_halt); let binding = rx_start.await.expect("it should be able to start the service").address; + let local_addr = format!("udp://{binding}"); form.send(ServiceRegistration::new(binding, Udp::check)) .expect("it should be able to send service registration"); @@ -141,7 +151,7 @@ impl UdpServer { }, }; - trace!("Running UDP Tracker on Socket: {}", running_udp_server.state.binding); + tracing::trace!(target: "UDP TRACKER: UdpServer::start", local_addr, "(running)"); Ok(running_udp_server) } @@ -159,13 +169,13 @@ impl UdpServer { /// # Panics /// /// It panics if unable to shutdown service. - pub async fn stop(self) -> Result, Error> { + pub async fn stop(self) -> Result, UdpError> { self.state .halt_task .send(Halted::Normal) - .map_err(|e| Error::Error(e.to_string()))?; + .map_err(|e| UdpError::Error(e.to_string()))?; - let launcher = self.state.task.await.expect("unable to shutdown service"); + let launcher = self.state.task.await.expect("it should shutdown service"); let stopped_api_server: UdpServer = UdpServer { state: Stopped { launcher }, @@ -200,23 +210,12 @@ impl Launcher { } } +/// Ring-Buffer of Active Requests +#[derive(Default)] struct ActiveRequests { rb: StaticRb, // the number of requests we handle at the same time. } -impl ActiveRequests { - /// Creates a new [`ActiveRequests`] filled with finished tasks. - async fn new() -> Self { - let mut rb = StaticRb::default(); - - let () = while rb.try_push(tokio::task::spawn_blocking(|| ()).abort_handle()).is_ok() {}; - - task::yield_now().await; - - Self { rb } - } -} - impl std::fmt::Debug for ActiveRequests { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let (left, right) = &self.rb.as_slices(); @@ -235,6 +234,84 @@ impl Drop for ActiveRequests { } } +/// Wrapper for Tokio [`UdpSocket`][`tokio::net::UdpSocket`] that is bound to a particular socket. +struct Socket { + socket: Arc, +} + +impl Socket { + async fn new(addr: SocketAddr) -> Result> { + let socket = tokio::net::UdpSocket::bind(addr).await; + + let socket = match socket { + Ok(socket) => socket, + Err(e) => Err(e)?, + }; + + let local_addr = format!("udp://{addr}"); + tracing::debug!(target: "UDP TRACKER: UdpSocket::new", local_addr, "(bound)"); + + Ok(Self { + socket: Arc::new(socket), + }) + } +} + +impl Deref for Socket { + type Target = tokio::net::UdpSocket; + + fn deref(&self) -> &Self::Target { + &self.socket + } +} + +impl Debug for Socket { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let local_addr = match self.socket.local_addr() { + Ok(socket) => format!("Receiving From: {socket}"), + Err(err) => format!("Socket Broken: {err}"), + }; + + f.debug_struct("UdpSocket").field("addr", &local_addr).finish_non_exhaustive() + } +} + +struct Receiver { + socket: Arc, + tracker: Arc, + data: RefCell<[u8; MAX_PACKET_SIZE]>, +} + +impl Stream for Receiver { + type Item = std::io::Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let mut buf = *self.data.borrow_mut(); + let mut buf = tokio::io::ReadBuf::new(&mut buf); + + let Poll::Ready(ready) = self.socket.poll_recv_from(cx, &mut buf) else { + return Poll::Pending; + }; + + let res = match ready { + Ok(from) => { + let payload = buf.filled().to_vec(); + let request = UdpRequest { payload, from }; + + Some(Ok(tokio::task::spawn(Udp::process_request( + request, + self.tracker.clone(), + self.socket.clone(), + )) + .abort_handle())) + } + Err(err) => Some(Err(err)), + }; + + Poll::Ready(res) + } +} + /// A UDP server instance launcher. #[derive(Constructor)] pub struct Udp; @@ -252,124 +329,178 @@ impl Udp { tx_start: oneshot::Sender, rx_halt: oneshot::Receiver, ) { - let socket = Arc::new( - UdpSocket::bind(bind_to) - .await - .unwrap_or_else(|_| panic!("Could not bind to {bind_to}.")), - ); - let address = socket - .local_addr() - .unwrap_or_else(|_| panic!("Could not get local_addr from {bind_to}.")); - let halt = shutdown_signal_with_message(rx_halt, format!("Halting Http Service Bound to Socket: {address}")); - - info!(target: "UDP TRACKER", "Starting on: udp://{}", address); - - let running = tokio::task::spawn(async move { - debug!(target: "UDP TRACKER", "Started: Waiting for packets on socket address: udp://{address} ..."); - Self::run_udp_server(tracker, socket).await; - }); + let halt_task = tokio::task::spawn(shutdown_signal_with_message( + rx_halt, + format!("Halting Http Service Bound to Socket: {bind_to}"), + )); + + let socket = tokio::time::timeout(Duration::from_millis(5000), Socket::new(bind_to)) + .await + .expect("it should bind to the socket within five seconds"); + + let socket = match socket { + Ok(socket) => socket, + Err(e) => { + tracing::error!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", addr = %bind_to, err = %e, "panic! (error when building socket)" ); + panic!("could not bind to socket!"); + } + }; + + let address = socket.local_addr().expect("it should get the locally bound address"); + let local_addr = format!("udp://{address}"); + + // note: this log message is parsed by our container. i.e: + // + // `[UDP TRACKER][INFO] Starting on: udp://` + // + tracing::info!(target: "UDP TRACKER", "Starting on: {local_addr}"); + + let socket = socket.socket; + + let direct = Receiver { + socket, + tracker, + data: RefCell::new([0; MAX_PACKET_SIZE]), + }; + + tracing::trace!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", local_addr, "(spawning main loop)"); + let running = { + let local_addr = local_addr.clone(); + tokio::task::spawn(async move { + tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown::task", local_addr, "(listening...)"); + let () = Self::run_udp_server_main(direct).await; + }) + }; tx_start .send(Started { address }) .expect("the UDP Tracker service should not be dropped"); - info!(target: "UDP TRACKER", "Started on: udp://{}", address); + tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", local_addr, "(started)"); let stop = running.abort_handle(); select! { - _ = running => { debug!(target: "UDP TRACKER", "Socket listener stopped on address: udp://{address}"); }, - () = halt => { debug!(target: "UDP TRACKER", "Halt signal spawned task stopped on address: udp://{address}"); } + _ = running => { tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", local_addr, "(stopped)"); }, + _ = halt_task => { tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown",local_addr, "(halting)"); } } stop.abort(); - task::yield_now().await; // lets allow the other threads to complete. + tokio::task::yield_now().await; // lets allow the other threads to complete. } - async fn run_udp_server(tracker: Arc, socket: Arc) { - let tracker = tracker.clone(); - let socket = socket.clone(); + async fn run_udp_server_main(mut direct: Receiver) { + let reqs = &mut ActiveRequests::default(); - let reqs = &mut ActiveRequests::new().await; + let addr = direct.socket.local_addr().expect("it should get local address"); + let local_addr = format!("udp://{addr}"); loop { - task::yield_now().await; - for h in reqs.rb.iter_mut() { - if h.is_finished() { - std::mem::swap( - h, - &mut Self::spawn_request_processor( - Self::receive_request(socket.clone()).await, - tracker.clone(), - socket.clone(), - ) - .abort_handle(), - ); - } else { - // the task is still running, lets yield and give it a chance to flush. + if let Some(req) = { + tracing::trace!(target: "UDP TRACKER: Udp::run_udp_server", local_addr, "(wait for request)"); + direct.next().await + } { + tracing::trace!(target: "UDP TRACKER: Udp::run_udp_server::loop", local_addr, "(in)"); + + let req = match req { + Ok(req) => req, + Err(e) => { + if e.kind() == std::io::ErrorKind::Interrupted { + tracing::warn!(target: "UDP TRACKER: Udp::run_udp_server::loop", local_addr, err = %e, "(interrupted)"); + return; + } + tracing::error!(target: "UDP TRACKER: Udp::run_udp_server::loop", local_addr, err = %e, "break: (got error)"); + break; + } + }; + + if req.is_finished() { + continue; + } + + // fill buffer with requests + let Err(req) = reqs.rb.try_push(req) else { + continue; + }; + + let mut finished: u64 = 0; + let mut unfinished_task = None; + // buffer is full.. lets make some space. + for h in reqs.rb.pop_iter() { + // remove some finished tasks + if h.is_finished() { + finished += 1; + continue; + } + + // task is unfinished.. give it another chance. tokio::task::yield_now().await; - h.abort(); + // if now finished, we continue. + if h.is_finished() { + finished += 1; + continue; + } - let server_socket_addr = socket.local_addr().expect("Could not get local_addr for socket."); + tracing::debug!(target: "UDP TRACKER: Udp::run_udp_server::loop", local_addr, removed_count = finished, "(got unfinished task)"); - tracing::span!( - target: "UDP TRACKER", - tracing::Level::WARN, "request-aborted", server_socket_addr = %server_socket_addr); + if finished == 0 { + // we have _no_ finished tasks.. will abort the unfinished task to make space... + h.abort(); - // force-break a single thread, then loop again. - break; - } - } - } - } + tracing::warn!(target: "UDP TRACKER: Udp::run_udp_server::loop", local_addr, "aborting request: (no finished tasks)"); + break; + } - async fn receive_request(socket: Arc) -> Result> { - // Wait for the socket to be readable - socket.readable().await?; + // we have space, return unfinished task for re-entry. + unfinished_task = Some(h); + } - let mut buf = Vec::with_capacity(MAX_PACKET_SIZE); + // re-insert the previous unfinished task. + if let Some(h) = unfinished_task { + reqs.rb.try_push(h).expect("it was previously inserted"); + } - match socket.recv_buf_from(&mut buf).await { - Ok((n, from)) => { - Vec::truncate(&mut buf, n); - trace!("GOT {buf:?}"); - Ok(UdpRequest { payload: buf, from }) + // insert the new task. + if !req.is_finished() { + reqs.rb.try_push(req).expect("it should remove at least one element."); + } + } else { + tokio::task::yield_now().await; + // the request iterator returned `None`. + tracing::error!(target: "UDP TRACKER: Udp::run_udp_server", local_addr, "breaking: (ran dry, should not happen in production!)"); + break; } - - Err(e) => Err(Box::new(e)), } } - fn spawn_request_processor( - result: Result>, - tracker: Arc, - socket: Arc, - ) -> JoinHandle<()> { - tokio::task::spawn(Self::process_request(result, tracker, socket)) - } - - async fn process_request(result: Result>, tracker: Arc, socket: Arc) { - match result { - Ok(udp_request) => { - trace!("Received Request from: {}", udp_request.from); - Self::process_valid_request(tracker.clone(), socket.clone(), udp_request).await; - } - Err(error) => { - debug!("error: {error}"); - } - } + async fn process_request(request: UdpRequest, tracker: Arc, socket: Arc) { + tracing::trace!(target: "UDP TRACKER: Udp::process_request", request = %request.from, "(receiving)"); + Self::process_valid_request(tracker, socket, request).await; } async fn process_valid_request(tracker: Arc, socket: Arc, udp_request: UdpRequest) { - trace!("Making Response to {udp_request:?}"); + tracing::trace!(target: "UDP TRACKER: Udp::process_valid_request", "Making Response to {udp_request:?}"); let from = udp_request.from; - let response = handlers::handle_packet(udp_request, &tracker.clone(), socket.clone()).await; + let response = handlers::handle_packet( + udp_request, + &tracker.clone(), + socket.local_addr().expect("it should get the local address"), + ) + .await; Self::send_response(&socket.clone(), from, response).await; } async fn send_response(socket: &Arc, to: SocketAddr, response: Response) { - trace!("Sending Response: {response:?} to: {to:?}"); + let response_type = match &response { + Response::Connect(_) => "Connect".to_string(), + Response::AnnounceIpv4(_) => "AnnounceIpv4".to_string(), + Response::AnnounceIpv6(_) => "AnnounceIpv6".to_string(), + Response::Scrape(_) => "Scrape".to_string(), + Response::Error(e) => format!("Error: {e:?}"), + }; + + tracing::debug!(target: "UDP TRACKER: Udp::send_response", target = ?to, response_type, "(sending)"); let buffer = vec![0u8; MAX_PACKET_SIZE]; let mut cursor = Cursor::new(buffer); @@ -380,22 +511,21 @@ impl Udp { let position = cursor.position() as usize; let inner = cursor.get_ref(); - debug!("Sending {} bytes ...", &inner[..position].len()); - debug!("To: {:?}", &to); - debug!("Payload: {:?}", &inner[..position]); + tracing::debug!(target: "UDP TRACKER: Udp::send_response", ?to, bytes_count = &inner[..position].len(), "(sending...)" ); + tracing::trace!(target: "UDP TRACKER: Udp::send_response", ?to, bytes_count = &inner[..position].len(), payload = ?&inner[..position], "(sending...)"); Self::send_packet(socket, &to, &inner[..position]).await; - debug!("{} bytes sent", &inner[..position].len()); + tracing::trace!(target: "UDP TRACKER: Udp::send_response", ?to, bytes_count = &inner[..position].len(), "(sent)"); } - Err(_) => { - error!("could not write response to bytes."); + Err(e) => { + tracing::error!(target: "UDP TRACKER: Udp::send_response", ?to, response_type, err = %e, "(error)"); } } } async fn send_packet(socket: &Arc, remote_addr: &SocketAddr, payload: &[u8]) { - trace!("Sending Packets: {payload:?} to: {remote_addr:?}"); + tracing::trace!(target: "UDP TRACKER: Udp::send_response", to = %remote_addr, ?payload, "(sending)"); // doesn't matter if it reaches or not drop(socket.send_to(payload, remote_addr).await); @@ -413,55 +543,46 @@ impl Udp { #[cfg(test)] mod tests { - use std::sync::Arc; - use std::time::Duration; + use std::{sync::Arc, time::Duration}; - use ringbuf::traits::{Consumer, Observer, RingBuffer}; use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; - use super::ActiveRequests; - use crate::bootstrap::app::initialize_with_configuration; - use crate::servers::registar::Registar; - use crate::servers::udp::server::{Launcher, UdpServer}; + use crate::{ + bootstrap::app::initialize_with_configuration, + servers::{ + registar::Registar, + udp::server::{Launcher, UdpServer}, + }, + }; #[tokio::test] - async fn it_should_return_to_the_start_of_the_ring_buffer() { - let mut a_req = ActiveRequests::new().await; - - tokio::time::sleep(Duration::from_millis(10)).await; + async fn it_should_be_able_to_start_and_stop() { + let cfg = Arc::new(ephemeral_mode_public()); + let tracker = initialize_with_configuration(&cfg); + let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); + let config = &udp_trackers[0]; + let bind_to = config.bind_address; + let register = &Registar::default(); - let mut count: usize = 0; - let cap: usize = a_req.rb.capacity().into(); + let stopped = UdpServer::new(Launcher::new(bind_to)); - // Add a single pending task to check that the ring-buffer is looping correctly. - a_req - .rb - .push_overwrite(tokio::task::spawn(std::future::pending::<()>()).abort_handle()); + let started = stopped + .start(tracker, register.give_form()) + .await + .expect("it should start the server"); - count += 1; + let stopped = started.stop().await.expect("it should stop the server"); - for _ in 0..2 { - for h in a_req.rb.iter() { - let first = count % cap; - println!("{count},{first},{}", h.is_finished()); - - if first == 0 { - assert!(!h.is_finished()); - } else { - assert!(h.is_finished()); - } + tokio::time::sleep(Duration::from_secs(1)).await; - count += 1; - } - } + assert_eq!(stopped.state.launcher.bind_to, bind_to); } #[tokio::test] - async fn it_should_be_able_to_start_and_stop() { + async fn it_should_be_able_to_start_and_stop_with_wait() { let cfg = Arc::new(ephemeral_mode_public()); let tracker = initialize_with_configuration(&cfg); - let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); - let config = &udp_trackers[0]; + let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; let register = &Registar::default(); @@ -472,6 +593,8 @@ mod tests { .await .expect("it should start the server"); + tokio::time::sleep(Duration::from_secs(1)).await; + let stopped = started.stop().await.expect("it should stop the server"); tokio::time::sleep(Duration::from_secs(1)).await; @@ -479,3 +602,68 @@ mod tests { assert_eq!(stopped.state.launcher.bind_to, bind_to); } } + +/// Todo: submit test to tokio documentation. +#[cfg(test)] +mod test_tokio { + use std::sync::Arc; + use std::time::Duration; + + use tokio::sync::Barrier; + use tokio::task::JoinSet; + + #[tokio::test] + async fn test_barrier_with_aborted_tasks() { + // Create a barrier that requires 10 tasks to proceed. + let barrier = Arc::new(Barrier::new(10)); + let mut tasks = JoinSet::default(); + let mut handles = Vec::default(); + + // Set Barrier to 9/10. + for _ in 0..9 { + let c = barrier.clone(); + handles.push(tasks.spawn(async move { + c.wait().await; + })); + } + + // Abort two tasks: Barrier: 7/10. + for _ in 0..2 { + if let Some(handle) = handles.pop() { + handle.abort(); + } + } + + // Spawn a single task: Barrier 8/10. + let c = barrier.clone(); + handles.push(tasks.spawn(async move { + c.wait().await; + })); + + // give a chance fro the barrier to release. + tokio::time::sleep(Duration::from_millis(50)).await; + + // assert that the barrier isn't removed, i.e. 8, not 10. + for h in &handles { + assert!(!h.is_finished()); + } + + // Spawn two more tasks to trigger the barrier release: Barrier 10/10. + for _ in 0..2 { + let c = barrier.clone(); + handles.push(tasks.spawn(async move { + c.wait().await; + })); + } + + // give a chance fro the barrier to release. + tokio::time::sleep(Duration::from_millis(50)).await; + + // assert that the barrier has been triggered + for h in &handles { + assert!(h.is_finished()); + } + + tasks.shutdown().await; + } +} diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs index 45b51ad35..900543462 100644 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -15,7 +15,7 @@ use crate::shared::bit_torrent::tracker::udp::{source_address, MAX_PACKET_SIZE}; /// Default timeout for sending and receiving packets. And waiting for sockets /// to be readable and writable. -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5); +pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5); #[allow(clippy::module_name_repetitions)] #[derive(Debug)] @@ -37,7 +37,16 @@ impl UdpClient { .parse::() .context(format!("{local_address} is not a valid socket address"))?; - let socket = UdpSocket::bind(socket_addr).await?; + let socket = match time::timeout(DEFAULT_TIMEOUT, UdpSocket::bind(socket_addr)).await { + Ok(bind_result) => match bind_result { + Ok(socket) => { + debug!("Bound to socket: {socket_addr}"); + Ok(socket) + } + Err(e) => Err(anyhow!("Failed to bind to socket: {socket_addr}, error: {e:?}")), + }, + Err(e) => Err(anyhow!("Timeout waiting to bind to socket: {socket_addr}, error: {e:?}")), + }?; let udp_client = Self { socket: Arc::new(socket), @@ -54,12 +63,15 @@ impl UdpClient { .parse::() .context(format!("{remote_address} is not a valid socket address"))?; - match self.socket.connect(socket_addr).await { - Ok(()) => { - debug!("Connected successfully"); - Ok(()) - } - Err(e) => Err(anyhow!("Failed to connect: {e:?}")), + match time::timeout(self.timeout, self.socket.connect(socket_addr)).await { + Ok(connect_result) => match connect_result { + Ok(()) => { + debug!("Connected to socket {socket_addr}"); + Ok(()) + } + Err(e) => Err(anyhow!("Failed to connect to socket {socket_addr}: {e:?}")), + }, + Err(e) => Err(anyhow!("Timeout waiting to connect to socket {socket_addr}, error: {e:?}")), } } @@ -100,7 +112,9 @@ impl UdpClient { /// /// # Panics /// - pub async fn receive(&self, bytes: &mut [u8]) -> Result { + pub async fn receive(&self) -> Result> { + let mut response_buffer = [0u8; MAX_PACKET_SIZE]; + debug!(target: "UDP client", "receiving ..."); match time::timeout(self.timeout, self.socket.readable()).await { @@ -113,21 +127,20 @@ impl UdpClient { Err(e) => return Err(anyhow!("Timeout waiting for the socket to become readable: {e:?}")), }; - let size_result = match time::timeout(self.timeout, self.socket.recv(bytes)).await { + let size = match time::timeout(self.timeout, self.socket.recv(&mut response_buffer)).await { Ok(recv_result) => match recv_result { Ok(size) => Ok(size), Err(e) => Err(anyhow!("IO error during send: {e:?}")), }, Err(e) => Err(anyhow!("Receive operation timed out: {e:?}")), - }; + }?; - if size_result.is_ok() { - let size = size_result.as_ref().unwrap(); - debug!(target: "UDP client", "{size} bytes received {bytes:?}"); - size_result - } else { - size_result - } + let mut res: Vec = response_buffer.to_vec(); + Vec::truncate(&mut res, size); + + debug!(target: "UDP client", "{size} bytes received {res:?}"); + + Ok(res) } } @@ -181,13 +194,11 @@ impl UdpTrackerClient { /// /// Will return error if can't create response from the received payload (bytes buffer). pub async fn receive(&self) -> Result { - let mut response_buffer = [0u8; MAX_PACKET_SIZE]; - - let payload_size = self.udp_client.receive(&mut response_buffer).await?; + let payload = self.udp_client.receive().await?; - debug!(target: "UDP tracker client", "received {payload_size} bytes. Response {response_buffer:?}"); + debug!(target: "UDP tracker client", "received {} bytes. Response {payload:?}", payload.len()); - let response = Response::parse_bytes(&response_buffer[..payload_size], true)?; + let response = Response::parse_bytes(&payload, true)?; Ok(response) } diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 7abd6092c..b23b20907 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -17,10 +17,6 @@ fn empty_udp_request() -> [u8; MAX_PACKET_SIZE] { [0; MAX_PACKET_SIZE] } -fn empty_buffer() -> [u8; MAX_PACKET_SIZE] { - [0; MAX_PACKET_SIZE] -} - async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrackerClient) -> ConnectionId { let connect_request = ConnectRequest { transaction_id }; @@ -54,13 +50,12 @@ async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_req Err(err) => panic!("{err}"), }; - let mut buffer = empty_buffer(); - match client.receive(&mut buffer).await { - Ok(_) => (), + let response = match client.receive().await { + Ok(response) => response, Err(err) => panic!("{err}"), }; - let response = Response::parse_bytes(&buffer, true).unwrap(); + let response = Response::parse_bytes(&response, true).unwrap(); assert!(is_error_response(&response, "bad request")); @@ -111,30 +106,20 @@ mod receiving_an_announce_request { AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectionId, InfoHash, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, TransactionId, }; - use torrust_tracker::shared::bit_torrent::tracker::udp::client::new_udp_tracker_client_connected; + use torrust_tracker::shared::bit_torrent::tracker::udp::client::{new_udp_tracker_client_connected, UdpTrackerClient}; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_ipv4_announce_response; use crate::servers::udp::contract::send_connection_request; use crate::servers::udp::Started; - #[tokio::test] - async fn should_return_an_announce_response() { - let env = Started::new(&configuration::ephemeral().into()).await; - - let client = match new_udp_tracker_client_connected(&env.bind_address().to_string()).await { - Ok(udp_tracker_client) => udp_tracker_client, - Err(err) => panic!("{err}"), - }; - - let connection_id = send_connection_request(TransactionId::new(123), &client).await; - + pub async fn send_and_get_announce(tx_id: TransactionId, c_id: ConnectionId, client: &UdpTrackerClient) { // Send announce request let announce_request = AnnounceRequest { - connection_id: ConnectionId(connection_id.0), + connection_id: ConnectionId(c_id.0), action_placeholder: AnnounceActionPlaceholder::default(), - transaction_id: TransactionId::new(123i32), + transaction_id: tx_id, info_hash: InfoHash([0u8; 20]), peer_id: PeerId([255u8; 20]), bytes_downloaded: NumberOfBytes(0i64.into()), @@ -160,6 +145,43 @@ mod receiving_an_announce_request { println!("test response {response:?}"); assert!(is_ipv4_announce_response(&response)); + } + + #[tokio::test] + async fn should_return_an_announce_response() { + let env = Started::new(&configuration::ephemeral().into()).await; + + let client = match new_udp_tracker_client_connected(&env.bind_address().to_string()).await { + Ok(udp_tracker_client) => udp_tracker_client, + Err(err) => panic!("{err}"), + }; + + let tx_id = TransactionId::new(123); + + let c_id = send_connection_request(tx_id, &client).await; + + send_and_get_announce(tx_id, c_id, &client).await; + + env.stop().await; + } + + #[tokio::test] + async fn should_return_many_announce_response() { + let env = Started::new(&configuration::ephemeral().into()).await; + + let client = match new_udp_tracker_client_connected(&env.bind_address().to_string()).await { + Ok(udp_tracker_client) => udp_tracker_client, + Err(err) => panic!("{err}"), + }; + + let tx_id = TransactionId::new(123); + + let c_id = send_connection_request(tx_id, &client).await; + + for x in 0..1000 { + tracing::info!("req no: {x}"); + send_and_get_announce(tx_id, c_id, &client).await; + } env.stop().await; } diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 1ba038c70..7b21defce 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -5,6 +5,7 @@ use torrust_tracker::bootstrap::app::initialize_with_configuration; use torrust_tracker::core::Tracker; use torrust_tracker::servers::registar::Registar; use torrust_tracker::servers::udp::server::{Launcher, Running, Stopped, UdpServer}; +use torrust_tracker::shared::bit_torrent::tracker::udp::client::DEFAULT_TIMEOUT; use torrust_tracker_configuration::{Configuration, UdpTracker}; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer; @@ -58,16 +59,22 @@ impl Environment { impl Environment { pub async fn new(configuration: &Arc) -> Self { - Environment::::new(configuration).start().await + tokio::time::timeout(DEFAULT_TIMEOUT, Environment::::new(configuration).start()) + .await + .expect("it should create an environment within the timeout") } #[allow(dead_code)] pub async fn stop(self) -> Environment { + let stopped = tokio::time::timeout(DEFAULT_TIMEOUT, self.server.stop()) + .await + .expect("it should stop the environment within the timeout"); + Environment { config: self.config, tracker: self.tracker, registar: Registar::default(), - server: self.server.stop().await.expect("it stop the udp tracker service"), + server: stopped.expect("it stop the udp tracker service"), } } From 9b3b75bd5fdf1dfc812d656294dbeac65b2643ca Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 07:59:21 +0100 Subject: [PATCH 0389/1297] fix: log message --- src/servers/udp/server.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 64f2fa2ab..af52e2de3 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -331,7 +331,7 @@ impl Udp { ) { let halt_task = tokio::task::spawn(shutdown_signal_with_message( rx_halt, - format!("Halting Http Service Bound to Socket: {bind_to}"), + format!("Halting UDP Service Bound to Socket: {bind_to}"), )); let socket = tokio::time::timeout(Duration::from_millis(5000), Socket::new(bind_to)) From 0e3678d2d6b4f4c0f0f6be7218b01e2b9e6e3fe3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 08:02:05 +0100 Subject: [PATCH 0390/1297] refactor: rename Socket to BoundSocket and fix format errors" --- src/lib.rs | 2 +- src/servers/udp/server.rs | 23 ++++++++++------------- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index bb6826dd1..cf2834418 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -494,7 +494,7 @@ pub mod bootstrap; pub mod console; pub mod core; pub mod servers; -pub mod shared; +pub mod shared; #[macro_use] extern crate lazy_static; diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index af52e2de3..3fb494238 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -235,11 +235,11 @@ impl Drop for ActiveRequests { } /// Wrapper for Tokio [`UdpSocket`][`tokio::net::UdpSocket`] that is bound to a particular socket. -struct Socket { +struct BoundSocket { socket: Arc, } -impl Socket { +impl BoundSocket { async fn new(addr: SocketAddr) -> Result> { let socket = tokio::net::UdpSocket::bind(addr).await; @@ -257,7 +257,7 @@ impl Socket { } } -impl Deref for Socket { +impl Deref for BoundSocket { type Target = tokio::net::UdpSocket; fn deref(&self) -> &Self::Target { @@ -265,7 +265,7 @@ impl Deref for Socket { } } -impl Debug for Socket { +impl Debug for BoundSocket { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let local_addr = match self.socket.local_addr() { Ok(socket) => format!("Receiving From: {socket}"), @@ -334,7 +334,7 @@ impl Udp { format!("Halting UDP Service Bound to Socket: {bind_to}"), )); - let socket = tokio::time::timeout(Duration::from_millis(5000), Socket::new(bind_to)) + let socket = tokio::time::timeout(Duration::from_millis(5000), BoundSocket::new(bind_to)) .await .expect("it should bind to the socket within five seconds"); @@ -543,17 +543,14 @@ impl Udp { #[cfg(test)] mod tests { - use std::{sync::Arc, time::Duration}; + use std::sync::Arc; + use std::time::Duration; use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; - use crate::{ - bootstrap::app::initialize_with_configuration, - servers::{ - registar::Registar, - udp::server::{Launcher, UdpServer}, - }, - }; + use crate::bootstrap::app::initialize_with_configuration; + use crate::servers::registar::Registar; + use crate::servers::udp::server::{Launcher, UdpServer}; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { From 7ff0cd249fe62adf4c8ba9b3c4815fb68d747b69 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 08:26:25 +0100 Subject: [PATCH 0391/1297] refactor: rename var --- src/servers/udp/server.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 3fb494238..c9f7e458f 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -357,7 +357,7 @@ impl Udp { let socket = socket.socket; - let direct = Receiver { + let receiver = Receiver { socket, tracker, data: RefCell::new([0; MAX_PACKET_SIZE]), @@ -368,7 +368,7 @@ impl Udp { let local_addr = local_addr.clone(); tokio::task::spawn(async move { tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown::task", local_addr, "(listening...)"); - let () = Self::run_udp_server_main(direct).await; + let () = Self::run_udp_server_main(receiver).await; }) }; From 16ae4fd14bdb03c8704c2af9ecb20873e6c396d3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 08:51:48 +0100 Subject: [PATCH 0392/1297] refactor: rename vars and extract constructor --- src/servers/udp/server.rs | 69 ++++++++++++++++++++------------------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index c9f7e458f..229729038 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -33,7 +33,6 @@ use derive_more::Constructor; use futures::{Stream, StreamExt}; use ringbuf::traits::{Consumer, Observer, Producer}; use ringbuf::StaticRb; -use tokio::net::UdpSocket; use tokio::select; use tokio::sync::oneshot; use tokio::task::{AbortHandle, JoinHandle}; @@ -255,6 +254,10 @@ impl BoundSocket { socket: Arc::new(socket), }) } + + fn local_addr(&self) -> SocketAddr { + self.socket.local_addr().expect("it should get local address") + } } impl Deref for BoundSocket { @@ -277,11 +280,21 @@ impl Debug for BoundSocket { } struct Receiver { - socket: Arc, + bound_socket: Arc, tracker: Arc, data: RefCell<[u8; MAX_PACKET_SIZE]>, } +impl Receiver { + pub fn new(bound_socket: Arc, tracker: Arc) -> Self { + Receiver { + bound_socket, + tracker, + data: RefCell::new([0; MAX_PACKET_SIZE]), + } + } +} + impl Stream for Receiver { type Item = std::io::Result; @@ -289,7 +302,7 @@ impl Stream for Receiver { let mut buf = *self.data.borrow_mut(); let mut buf = tokio::io::ReadBuf::new(&mut buf); - let Poll::Ready(ready) = self.socket.poll_recv_from(cx, &mut buf) else { + let Poll::Ready(ready) = self.bound_socket.poll_recv_from(cx, &mut buf) else { return Poll::Pending; }; @@ -301,7 +314,7 @@ impl Stream for Receiver { Some(Ok(tokio::task::spawn(Udp::process_request( request, self.tracker.clone(), - self.socket.clone(), + self.bound_socket.clone(), )) .abort_handle())) } @@ -338,7 +351,7 @@ impl Udp { .await .expect("it should bind to the socket within five seconds"); - let socket = match socket { + let bound_socket = match socket { Ok(socket) => socket, Err(e) => { tracing::error!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", addr = %bind_to, err = %e, "panic! (error when building socket)" ); @@ -346,26 +359,21 @@ impl Udp { } }; - let address = socket.local_addr().expect("it should get the locally bound address"); - let local_addr = format!("udp://{address}"); + let address = bound_socket.local_addr(); + let local_udp_url = format!("udp://{address}"); // note: this log message is parsed by our container. i.e: // // `[UDP TRACKER][INFO] Starting on: udp://` // - tracing::info!(target: "UDP TRACKER", "Starting on: {local_addr}"); + tracing::info!(target: "UDP TRACKER", "Starting on: {local_udp_url}"); - let socket = socket.socket; + let receiver = Receiver::new(bound_socket.into(), tracker); - let receiver = Receiver { - socket, - tracker, - data: RefCell::new([0; MAX_PACKET_SIZE]), - }; + tracing::trace!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", local_udp_url, "(spawning main loop)"); - tracing::trace!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", local_addr, "(spawning main loop)"); let running = { - let local_addr = local_addr.clone(); + let local_addr = local_udp_url.clone(); tokio::task::spawn(async move { tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown::task", local_addr, "(listening...)"); let () = Self::run_udp_server_main(receiver).await; @@ -376,29 +384,29 @@ impl Udp { .send(Started { address }) .expect("the UDP Tracker service should not be dropped"); - tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", local_addr, "(started)"); + tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", local_udp_url, "(started)"); let stop = running.abort_handle(); select! { - _ = running => { tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", local_addr, "(stopped)"); }, - _ = halt_task => { tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown",local_addr, "(halting)"); } + _ = running => { tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", local_udp_url, "(stopped)"); }, + _ = halt_task => { tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown",local_udp_url, "(halting)"); } } stop.abort(); tokio::task::yield_now().await; // lets allow the other threads to complete. } - async fn run_udp_server_main(mut direct: Receiver) { + async fn run_udp_server_main(mut receiver: Receiver) { let reqs = &mut ActiveRequests::default(); - let addr = direct.socket.local_addr().expect("it should get local address"); + let addr = receiver.bound_socket.local_addr(); let local_addr = format!("udp://{addr}"); loop { if let Some(req) = { tracing::trace!(target: "UDP TRACKER: Udp::run_udp_server", local_addr, "(wait for request)"); - direct.next().await + receiver.next().await } { tracing::trace!(target: "UDP TRACKER: Udp::run_udp_server::loop", local_addr, "(in)"); @@ -474,24 +482,19 @@ impl Udp { } } - async fn process_request(request: UdpRequest, tracker: Arc, socket: Arc) { + async fn process_request(request: UdpRequest, tracker: Arc, socket: Arc) { tracing::trace!(target: "UDP TRACKER: Udp::process_request", request = %request.from, "(receiving)"); Self::process_valid_request(tracker, socket, request).await; } - async fn process_valid_request(tracker: Arc, socket: Arc, udp_request: UdpRequest) { + async fn process_valid_request(tracker: Arc, socket: Arc, udp_request: UdpRequest) { tracing::trace!(target: "UDP TRACKER: Udp::process_valid_request", "Making Response to {udp_request:?}"); let from = udp_request.from; - let response = handlers::handle_packet( - udp_request, - &tracker.clone(), - socket.local_addr().expect("it should get the local address"), - ) - .await; + let response = handlers::handle_packet(udp_request, &tracker.clone(), socket.local_addr()).await; Self::send_response(&socket.clone(), from, response).await; } - async fn send_response(socket: &Arc, to: SocketAddr, response: Response) { + async fn send_response(bound_socket: &Arc, to: SocketAddr, response: Response) { let response_type = match &response { Response::Connect(_) => "Connect".to_string(), Response::AnnounceIpv4(_) => "AnnounceIpv4".to_string(), @@ -514,7 +517,7 @@ impl Udp { tracing::debug!(target: "UDP TRACKER: Udp::send_response", ?to, bytes_count = &inner[..position].len(), "(sending...)" ); tracing::trace!(target: "UDP TRACKER: Udp::send_response", ?to, bytes_count = &inner[..position].len(), payload = ?&inner[..position], "(sending...)"); - Self::send_packet(socket, &to, &inner[..position]).await; + Self::send_packet(bound_socket, &to, &inner[..position]).await; tracing::trace!(target: "UDP TRACKER: Udp::send_response", ?to, bytes_count = &inner[..position].len(), "(sent)"); } @@ -524,7 +527,7 @@ impl Udp { } } - async fn send_packet(socket: &Arc, remote_addr: &SocketAddr, payload: &[u8]) { + async fn send_packet(socket: &Arc, remote_addr: &SocketAddr, payload: &[u8]) { tracing::trace!(target: "UDP TRACKER: Udp::send_response", to = %remote_addr, ?payload, "(sending)"); // doesn't matter if it reaches or not From 0388e1d1439bbc1d2ef7b59bf225a2d152358a2b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 13:20:17 +0100 Subject: [PATCH 0393/1297] refactor: extract consts for logging targets --- src/bootstrap/jobs/health_check_api.rs | 8 +-- src/bootstrap/jobs/udp_tracker.rs | 7 +-- src/console/ci/e2e/logs_parser.rs | 7 +-- src/servers/apis/mod.rs | 6 ++- src/servers/apis/routes.rs | 5 +- src/servers/apis/server.rs | 9 ++-- src/servers/health_check_api/mod.rs | 2 + src/servers/health_check_api/server.rs | 7 +-- src/servers/http/mod.rs | 2 + src/servers/http/server.rs | 5 +- src/servers/http/v1/routes.rs | 5 +- src/servers/udp/logging.rs | 13 ++--- src/servers/udp/mod.rs | 2 + src/servers/udp/server.rs | 54 ++++++++++--------- src/shared/bit_torrent/tracker/udp/client.rs | 12 +++-- tests/servers/health_check_api/environment.rs | 10 ++-- 16 files changed, 87 insertions(+), 67 deletions(-) diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index c22a4cf95..e79a6da77 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -20,7 +20,7 @@ use torrust_tracker_configuration::HealthCheckApi; use tracing::info; use super::Started; -use crate::servers::health_check_api::server; +use crate::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; use crate::servers::registar::ServiceRegistry; use crate::servers::signals::Halted; @@ -44,18 +44,18 @@ pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> Jo // Run the API server let join_handle = tokio::spawn(async move { - info!(target: "HEALTH CHECK API", "Starting on: {protocol}://{}", bind_addr); + info!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting on: {protocol}://{}", bind_addr); let handle = server::start(bind_addr, tx_start, rx_halt, register); if let Ok(()) = handle.await { - info!(target: "HEALTH CHECK API", "Stopped server running on: {protocol}://{}", bind_addr); + info!(target: HEALTH_CHECK_API_LOG_TARGET, "Stopped server running on: {protocol}://{}", bind_addr); } }); // Wait until the server sends the started message match rx_start.await { - Ok(msg) => info!(target: "HEALTH CHECK API", "Started on: {protocol}://{}", msg.address), + Ok(msg) => info!(target: HEALTH_CHECK_API_LOG_TARGET, "Started on: {protocol}://{}", msg.address), Err(e) => panic!("the Health Check API server was dropped: {e}"), } diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 2c09e6de2..ba39df2fe 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -15,6 +15,7 @@ use tracing::debug; use crate::core; use crate::servers::registar::ServiceRegistrationForm; use crate::servers::udp::server::{Launcher, UdpServer}; +use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// It starts a new UDP server with the provided configuration. /// @@ -35,8 +36,8 @@ pub async fn start_job(config: &UdpTracker, tracker: Arc, form: S .expect("it should be able to start the udp tracker"); tokio::spawn(async move { - debug!(target: "UDP TRACKER", "Wait for launcher (UDP service) to finish ..."); - debug!(target: "UDP TRACKER", "Is halt channel closed before waiting?: {}", server.state.halt_task.is_closed()); + debug!(target: UDP_TRACKER_LOG_TARGET, "Wait for launcher (UDP service) to finish ..."); + debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed before waiting?: {}", server.state.halt_task.is_closed()); assert!( !server.state.halt_task.is_closed(), @@ -49,6 +50,6 @@ pub async fn start_job(config: &UdpTracker, tracker: Arc, form: S .await .expect("it should be able to join to the udp tracker task"); - debug!(target: "UDP TRACKER", "Is halt channel closed after finishing the server?: {}", server.state.halt_task.is_closed()); + debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed after finishing the server?: {}", server.state.halt_task.is_closed()); }) } diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index 4886786de..8bf7974c1 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -2,10 +2,11 @@ use regex::Regex; use serde::{Deserialize, Serialize}; +use crate::servers::health_check_api::HEALTH_CHECK_API_LOG_TARGET; +use crate::servers::http::HTTP_TRACKER_LOG_TARGET; +use crate::servers::udp::UDP_TRACKER_LOG_TARGET; + const INFO_LOG_LEVEL: &str = "INFO"; -const UDP_TRACKER_LOG_TARGET: &str = "UDP TRACKER"; -const HTTP_TRACKER_LOG_TARGET: &str = "HTTP TRACKER"; -const HEALTH_CHECK_API_LOG_TARGET: &str = "HEALTH CHECK API"; #[derive(Serialize, Deserialize, Debug, Default)] pub struct RunningServices { diff --git a/src/servers/apis/mod.rs b/src/servers/apis/mod.rs index 6dae66c2d..b44ccab9f 100644 --- a/src/servers/apis/mod.rs +++ b/src/servers/apis/mod.rs @@ -157,6 +157,10 @@ pub mod routes; pub mod server; pub mod v1; +use serde::{Deserialize, Serialize}; + +pub const API_LOG_TARGET: &str = "API"; + /// The info hash URL path parameter. /// /// Some API endpoints require an info hash as a path parameter. @@ -169,8 +173,6 @@ pub mod v1; #[derive(Deserialize)] pub struct InfoHashParam(pub String); -use serde::{Deserialize, Serialize}; - /// The version of the HTTP Api. #[derive(Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Debug)] pub enum Version { diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 087bcfa4a..2001afc2f 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -27,6 +27,7 @@ use super::v1; use super::v1::context::health_check::handlers::health_check_handler; use super::v1::middlewares::auth::State; use crate::core::Tracker; +use crate::servers::apis::API_LOG_TARGET; const TIMEOUT: Duration = Duration::from_secs(5); @@ -60,7 +61,7 @@ pub fn router(tracker: Arc, access_tokens: Arc) -> Router .unwrap_or_default(); tracing::span!( - target: "API", + target: API_LOG_TARGET, tracing::Level::INFO, "request", method = %method, uri = %uri, request_id = %request_id); }) .on_response(|response: &Response, latency: Duration, _span: &Span| { @@ -73,7 +74,7 @@ pub fn router(tracker: Arc, access_tokens: Arc) -> Router let latency_ms = latency.as_millis(); tracing::span!( - target: "API", + target: API_LOG_TARGET, tracing::Level::INFO, "response", latency = %latency_ms, status = %status_code, request_id = %request_id); }), ) diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 246660ab1..d47e5d542 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -37,6 +37,7 @@ use tracing::{debug, error, info}; use super::routes::router; use crate::bootstrap::jobs::Started; use crate::core::Tracker; +use crate::servers::apis::API_LOG_TARGET; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{graceful_shutdown, Halted}; @@ -121,11 +122,11 @@ impl ApiServer { let launcher = self.state.launcher; let task = tokio::spawn(async move { - debug!(target: "API", "Starting with launcher in spawned task ..."); + debug!(target: API_LOG_TARGET, "Starting with launcher in spawned task ..."); let _task = launcher.start(tracker, access_tokens, tx_start, rx_halt).await; - debug!(target: "API", "Started with launcher in spawned task"); + debug!(target: API_LOG_TARGET, "Started with launcher in spawned task"); launcher }); @@ -231,7 +232,7 @@ impl Launcher { let tls = self.tls.clone(); let protocol = if tls.is_some() { "https" } else { "http" }; - info!(target: "API", "Starting on {protocol}://{}", address); + info!(target: API_LOG_TARGET, "Starting on {protocol}://{}", address); let running = Box::pin(async { match tls { @@ -250,7 +251,7 @@ impl Launcher { } }); - info!(target: "API", "Started on {protocol}://{}", address); + info!(target: API_LOG_TARGET, "Started on {protocol}://{}", address); tx_start .send(Started { address }) diff --git a/src/servers/health_check_api/mod.rs b/src/servers/health_check_api/mod.rs index ec608387d..24c5232c8 100644 --- a/src/servers/health_check_api/mod.rs +++ b/src/servers/health_check_api/mod.rs @@ -2,3 +2,5 @@ pub mod handlers; pub mod resources; pub mod responses; pub mod server; + +pub const HEALTH_CHECK_API_LOG_TARGET: &str = "HEALTH CHECK API"; diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index f03753573..89fbafe45 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -22,6 +22,7 @@ use tracing::{debug, Level, Span}; use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; +use crate::servers::health_check_api::HEALTH_CHECK_API_LOG_TARGET; use crate::servers::registar::ServiceRegistry; use crate::servers::signals::{graceful_shutdown, Halted}; @@ -56,7 +57,7 @@ pub fn start( .unwrap_or_default(); tracing::span!( - target: "HEALTH CHECK API", + target: HEALTH_CHECK_API_LOG_TARGET, tracing::Level::INFO, "request", method = %method, uri = %uri, request_id = %request_id); }) .on_response(|response: &Response, latency: Duration, _span: &Span| { @@ -69,7 +70,7 @@ pub fn start( let latency_ms = latency.as_millis(); tracing::span!( - target: "HEALTH CHECK API", + target: HEALTH_CHECK_API_LOG_TARGET, tracing::Level::INFO, "response", latency = %latency_ms, status = %status_code, request_id = %request_id); }), ) @@ -80,7 +81,7 @@ pub fn start( let handle = Handle::new(); - debug!(target: "HEALTH CHECK API", "Starting service with graceful shutdown in a spawned task ..."); + debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting service with graceful shutdown in a spawned task ..."); tokio::task::spawn(graceful_shutdown( handle.clone(), diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index e50e3c351..4ef5ca7ea 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -309,6 +309,8 @@ pub mod percent_encoding; pub mod server; pub mod v1; +pub const HTTP_TRACKER_LOG_TARGET: &str = "HTTP TRACKER"; + /// The version of the HTTP tracker. #[derive(Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Debug)] pub enum Version { diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 5798f7c10..9199573b0 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -13,6 +13,7 @@ use super::v1::routes::router; use crate::bootstrap::jobs::Started; use crate::core::Tracker; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; +use crate::servers::http::HTTP_TRACKER_LOG_TARGET; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{graceful_shutdown, Halted}; @@ -55,7 +56,7 @@ impl Launcher { let tls = self.tls.clone(); let protocol = if tls.is_some() { "https" } else { "http" }; - info!(target: "HTTP TRACKER", "Starting on: {protocol}://{}", address); + info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{}", address); let app = router(tracker, address); @@ -76,7 +77,7 @@ impl Launcher { } }); - info!(target: "HTTP TRACKER", "Started on: {protocol}://{}", address); + info!(target: HTTP_TRACKER_LOG_TARGET, "Started on: {protocol}://{}", address); tx_start .send(Started { address }) diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 14641dc1d..b2f37880c 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -20,6 +20,7 @@ use tracing::{Level, Span}; use super::handlers::{announce, health_check, scrape}; use crate::core::Tracker; +use crate::servers::http::HTTP_TRACKER_LOG_TARGET; const TIMEOUT: Duration = Duration::from_secs(5); @@ -56,7 +57,7 @@ pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { .unwrap_or_default(); tracing::span!( - target:"HTTP TRACKER", + target: HTTP_TRACKER_LOG_TARGET, tracing::Level::INFO, "request", server_socket_addr= %server_socket_addr, method = %method, uri = %uri, request_id = %request_id); }) .on_response(move |response: &Response, latency: Duration, _span: &Span| { @@ -69,7 +70,7 @@ pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { let latency_ms = latency.as_millis(); tracing::span!( - target: "HTTP TRACKER", + target: HTTP_TRACKER_LOG_TARGET, tracing::Level::INFO, "response", server_socket_addr= %server_socket_addr, latency = %latency_ms, status = %status_code, request_id = %request_id); }), ) diff --git a/src/servers/udp/logging.rs b/src/servers/udp/logging.rs index 9bbb48f6a..3891278d7 100644 --- a/src/servers/udp/logging.rs +++ b/src/servers/udp/logging.rs @@ -7,6 +7,7 @@ use aquatic_udp_protocol::{Request, Response, TransactionId}; use torrust_tracker_primitives::info_hash::InfoHash; use super::handlers::RequestId; +use crate::servers::udp::UDP_TRACKER_LOG_TARGET; pub fn log_request(request: &Request, request_id: &RequestId, server_socket_addr: &SocketAddr) { let action = map_action_name(request); @@ -17,7 +18,7 @@ pub fn log_request(request: &Request, request_id: &RequestId, server_socket_addr let transaction_id_str = transaction_id.0.to_string(); tracing::span!( - target: "UDP TRACKER", + target: UDP_TRACKER_LOG_TARGET, tracing::Level::INFO, "request", server_socket_addr = %server_socket_addr, action = %action, transaction_id = %transaction_id_str, request_id = %request_id); } Request::Announce(announce_request) => { @@ -27,7 +28,7 @@ pub fn log_request(request: &Request, request_id: &RequestId, server_socket_addr let info_hash_str = InfoHash::from_bytes(&announce_request.info_hash.0).to_hex_string(); tracing::span!( - target: "UDP TRACKER", + target: UDP_TRACKER_LOG_TARGET, tracing::Level::INFO, "request", server_socket_addr = %server_socket_addr, action = %action, transaction_id = %transaction_id_str, request_id = %request_id, connection_id = %connection_id_str, info_hash = %info_hash_str); } Request::Scrape(scrape_request) => { @@ -36,7 +37,7 @@ pub fn log_request(request: &Request, request_id: &RequestId, server_socket_addr let connection_id_str = scrape_request.connection_id.0.to_string(); tracing::span!( - target: "UDP TRACKER", + target: UDP_TRACKER_LOG_TARGET, tracing::Level::INFO, "request", server_socket_addr = %server_socket_addr, @@ -64,7 +65,7 @@ pub fn log_response( latency: Duration, ) { tracing::span!( - target: "UDP TRACKER", + target: UDP_TRACKER_LOG_TARGET, tracing::Level::INFO, "response", server_socket_addr = %server_socket_addr, @@ -75,12 +76,12 @@ pub fn log_response( pub fn log_bad_request(request_id: &RequestId) { tracing::span!( - target: "UDP TRACKER", + target: UDP_TRACKER_LOG_TARGET, tracing::Level::INFO, "bad request", request_id = %request_id); } pub fn log_error_response(request_id: &RequestId) { tracing::span!( - target: "UDP TRACKER", + target: UDP_TRACKER_LOG_TARGET, tracing::Level::INFO, "response", request_id = %request_id); } diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index 3062a4393..5c5460397 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -649,6 +649,8 @@ pub mod peer_builder; pub mod request; pub mod server; +pub const UDP_TRACKER_LOG_TARGET: &str = "UDP TRACKER"; + /// Number of bytes. pub type Bytes = u64; /// The port the peer is listening on. diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 229729038..e60e49ace 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -42,7 +42,7 @@ use crate::bootstrap::jobs::Started; use crate::core::Tracker; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{shutdown_signal_with_message, Halted}; -use crate::servers::udp::handlers; +use crate::servers::udp::{handlers, UDP_TRACKER_LOG_TARGET}; use crate::shared::bit_torrent::tracker::udp::client::check; use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; @@ -150,7 +150,7 @@ impl UdpServer { }, }; - tracing::trace!(target: "UDP TRACKER: UdpServer::start", local_addr, "(running)"); + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpServer::start (running)"); Ok(running_udp_server) } @@ -248,7 +248,7 @@ impl BoundSocket { }; let local_addr = format!("udp://{addr}"); - tracing::debug!(target: "UDP TRACKER: UdpSocket::new", local_addr, "(bound)"); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpSocket::new (bound)"); Ok(Self { socket: Arc::new(socket), @@ -347,6 +347,8 @@ impl Udp { format!("Halting UDP Service Bound to Socket: {bind_to}"), )); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting on: {bind_to}"); + let socket = tokio::time::timeout(Duration::from_millis(5000), BoundSocket::new(bind_to)) .await .expect("it should bind to the socket within five seconds"); @@ -354,7 +356,7 @@ impl Udp { let bound_socket = match socket { Ok(socket) => socket, Err(e) => { - tracing::error!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", addr = %bind_to, err = %e, "panic! (error when building socket)" ); + tracing::error!(target: UDP_TRACKER_LOG_TARGET, addr = %bind_to, err = %e, "Udp::run_with_graceful_shutdown panic! (error when building socket)" ); panic!("could not bind to socket!"); } }; @@ -364,18 +366,18 @@ impl Udp { // note: this log message is parsed by our container. i.e: // - // `[UDP TRACKER][INFO] Starting on: udp://` + // `INFO UDP TRACKER: Started on: udp://0.0.0.0:6969` // - tracing::info!(target: "UDP TRACKER", "Starting on: {local_udp_url}"); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Started on: {local_udp_url}"); let receiver = Receiver::new(bound_socket.into(), tracker); - tracing::trace!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", local_udp_url, "(spawning main loop)"); + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (spawning main loop)"); let running = { let local_addr = local_udp_url.clone(); tokio::task::spawn(async move { - tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown::task", local_addr, "(listening...)"); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_with_graceful_shutdown::task (listening...)"); let () = Self::run_udp_server_main(receiver).await; }) }; @@ -384,13 +386,13 @@ impl Udp { .send(Started { address }) .expect("the UDP Tracker service should not be dropped"); - tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", local_udp_url, "(started)"); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (started)"); let stop = running.abort_handle(); select! { - _ = running => { tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown", local_udp_url, "(stopped)"); }, - _ = halt_task => { tracing::debug!(target: "UDP TRACKER: Udp::run_with_graceful_shutdown",local_udp_url, "(halting)"); } + _ = running => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (stopped)"); }, + _ = halt_task => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (halting)"); } } stop.abort(); @@ -405,19 +407,19 @@ impl Udp { loop { if let Some(req) = { - tracing::trace!(target: "UDP TRACKER: Udp::run_udp_server", local_addr, "(wait for request)"); + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server (wait for request)"); receiver.next().await } { - tracing::trace!(target: "UDP TRACKER: Udp::run_udp_server::loop", local_addr, "(in)"); + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop (in)"); let req = match req { Ok(req) => req, Err(e) => { if e.kind() == std::io::ErrorKind::Interrupted { - tracing::warn!(target: "UDP TRACKER: Udp::run_udp_server::loop", local_addr, err = %e, "(interrupted)"); + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, local_addr, err = %e, "Udp::run_udp_server::loop (interrupted)"); return; } - tracing::error!(target: "UDP TRACKER: Udp::run_udp_server::loop", local_addr, err = %e, "break: (got error)"); + tracing::error!(target: UDP_TRACKER_LOG_TARGET, local_addr, err = %e, "Udp::run_udp_server::loop break: (got error)"); break; } }; @@ -450,13 +452,13 @@ impl Udp { continue; } - tracing::debug!(target: "UDP TRACKER: Udp::run_udp_server::loop", local_addr, removed_count = finished, "(got unfinished task)"); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, removed_count = finished, "Udp::run_udp_server::loop (got unfinished task)"); if finished == 0 { // we have _no_ finished tasks.. will abort the unfinished task to make space... h.abort(); - tracing::warn!(target: "UDP TRACKER: Udp::run_udp_server::loop", local_addr, "aborting request: (no finished tasks)"); + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop aborting request: (no finished tasks)"); break; } @@ -476,19 +478,19 @@ impl Udp { } else { tokio::task::yield_now().await; // the request iterator returned `None`. - tracing::error!(target: "UDP TRACKER: Udp::run_udp_server", local_addr, "breaking: (ran dry, should not happen in production!)"); + tracing::error!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server breaking: (ran dry, should not happen in production!)"); break; } } } async fn process_request(request: UdpRequest, tracker: Arc, socket: Arc) { - tracing::trace!(target: "UDP TRACKER: Udp::process_request", request = %request.from, "(receiving)"); + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, request = %request.from, "Udp::process_request (receiving)"); Self::process_valid_request(tracker, socket, request).await; } async fn process_valid_request(tracker: Arc, socket: Arc, udp_request: UdpRequest) { - tracing::trace!(target: "UDP TRACKER: Udp::process_valid_request", "Making Response to {udp_request:?}"); + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, "Udp::process_valid_request. Making Response to {udp_request:?}"); let from = udp_request.from; let response = handlers::handle_packet(udp_request, &tracker.clone(), socket.local_addr()).await; Self::send_response(&socket.clone(), from, response).await; @@ -503,7 +505,7 @@ impl Udp { Response::Error(e) => format!("Error: {e:?}"), }; - tracing::debug!(target: "UDP TRACKER: Udp::send_response", target = ?to, response_type, "(sending)"); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, target = ?to, response_type, "Udp::send_response (sending)"); let buffer = vec![0u8; MAX_PACKET_SIZE]; let mut cursor = Cursor::new(buffer); @@ -514,21 +516,21 @@ impl Udp { let position = cursor.position() as usize; let inner = cursor.get_ref(); - tracing::debug!(target: "UDP TRACKER: Udp::send_response", ?to, bytes_count = &inner[..position].len(), "(sending...)" ); - tracing::trace!(target: "UDP TRACKER: Udp::send_response", ?to, bytes_count = &inner[..position].len(), payload = ?&inner[..position], "(sending...)"); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count = &inner[..position].len(), "Udp::send_response (sending...)" ); + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count = &inner[..position].len(), payload = ?&inner[..position], "Udp::send_response (sending...)"); Self::send_packet(bound_socket, &to, &inner[..position]).await; - tracing::trace!(target: "UDP TRACKER: Udp::send_response", ?to, bytes_count = &inner[..position].len(), "(sent)"); + tracing::trace!(target:UDP_TRACKER_LOG_TARGET, ?to, bytes_count = &inner[..position].len(), "Udp::send_response (sent)"); } Err(e) => { - tracing::error!(target: "UDP TRACKER: Udp::send_response", ?to, response_type, err = %e, "(error)"); + tracing::error!(target: UDP_TRACKER_LOG_TARGET, ?to, response_type, err = %e, "Udp::send_response (error)"); } } } async fn send_packet(socket: &Arc, remote_addr: &SocketAddr, payload: &[u8]) { - tracing::trace!(target: "UDP TRACKER: Udp::send_response", to = %remote_addr, ?payload, "(sending)"); + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, to = %remote_addr, ?payload, "Udp::send_response (sending)"); // doesn't matter if it reaches or not drop(socket.send_to(payload, remote_addr).await); diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs index 900543462..dce596e08 100644 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -13,6 +13,8 @@ use zerocopy::network_endian::I32; use crate::shared::bit_torrent::tracker::udp::{source_address, MAX_PACKET_SIZE}; +pub const UDP_CLIENT_LOG_TARGET: &str = "UDP CLIENT"; + /// Default timeout for sending and receiving packets. And waiting for sockets /// to be readable and writable. pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5); @@ -82,7 +84,7 @@ impl UdpClient { /// - Can't write to the socket. /// - Can't send data. pub async fn send(&self, bytes: &[u8]) -> Result { - debug!(target: "UDP client", "sending {bytes:?} ..."); + debug!(target: UDP_CLIENT_LOG_TARGET, "sending {bytes:?} ..."); match time::timeout(self.timeout, self.socket.writable()).await { Ok(writable_result) => { @@ -115,7 +117,7 @@ impl UdpClient { pub async fn receive(&self) -> Result> { let mut response_buffer = [0u8; MAX_PACKET_SIZE]; - debug!(target: "UDP client", "receiving ..."); + debug!(target: UDP_CLIENT_LOG_TARGET, "receiving ..."); match time::timeout(self.timeout, self.socket.readable()).await { Ok(readable_result) => { @@ -138,7 +140,7 @@ impl UdpClient { let mut res: Vec = response_buffer.to_vec(); Vec::truncate(&mut res, size); - debug!(target: "UDP client", "{size} bytes received {res:?}"); + debug!(target: UDP_CLIENT_LOG_TARGET, "{size} bytes received {res:?}"); Ok(res) } @@ -168,7 +170,7 @@ impl UdpTrackerClient { /// /// Will return error if can't write request to bytes. pub async fn send(&self, request: Request) -> Result { - debug!(target: "UDP tracker client", "send request {request:?}"); + debug!(target: UDP_CLIENT_LOG_TARGET, "send request {request:?}"); // Write request into a buffer let request_buffer = vec![0u8; MAX_PACKET_SIZE]; @@ -196,7 +198,7 @@ impl UdpTrackerClient { pub async fn receive(&self) -> Result { let payload = self.udp_client.receive().await?; - debug!(target: "UDP tracker client", "received {} bytes. Response {payload:?}", payload.len()); + debug!(target: UDP_CLIENT_LOG_TARGET, "received {} bytes. Response {payload:?}", payload.len()); let response = Response::parse_bytes(&payload, true)?; diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs index a50ad5156..cf0566d67 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/tests/servers/health_check_api/environment.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use tokio::sync::oneshot::{self, Sender}; use tokio::task::JoinHandle; use torrust_tracker::bootstrap::jobs::Started; -use torrust_tracker::servers::health_check_api::server; +use torrust_tracker::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; use torrust_tracker::servers::registar::Registar; use torrust_tracker::servers::signals::{self, Halted}; use torrust_tracker_configuration::HealthCheckApi; @@ -49,21 +49,21 @@ impl Environment { let register = self.registar.entries(); - debug!(target: "HEALTH CHECK API", "Spawning task to launch the service ..."); + debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Spawning task to launch the service ..."); let server = tokio::spawn(async move { - debug!(target: "HEALTH CHECK API", "Starting the server in a spawned task ..."); + debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting the server in a spawned task ..."); server::start(self.state.bind_to, tx_start, rx_halt, register) .await .expect("it should start the health check service"); - debug!(target: "HEALTH CHECK API", "Server started. Sending the binding {} ...", self.state.bind_to); + debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Server started. Sending the binding {} ...", self.state.bind_to); self.state.bind_to }); - debug!(target: "HEALTH CHECK API", "Waiting for spawning task to send the binding ..."); + debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Waiting for spawning task to send the binding ..."); let binding = rx_start.await.expect("it should send service binding").address; From b4b4515a9aa60ed5351c6f3f0c8b27ea01d9c0d6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 13:41:55 +0100 Subject: [PATCH 0394/1297] refactor: extract const for logging targets And make it explicit the coupling between logs and `RunningServices` type. --- src/bootstrap/jobs/health_check_api.rs | 3 ++- src/console/ci/e2e/logs_parser.rs | 7 ++++--- src/servers/apis/server.rs | 3 ++- src/servers/http/server.rs | 3 ++- src/servers/logging.rs | 29 ++++++++++++++++++++++++++ src/servers/mod.rs | 1 + src/servers/udp/server.rs | 7 ++----- 7 files changed, 42 insertions(+), 11 deletions(-) create mode 100644 src/servers/logging.rs diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index e79a6da77..b4d4862ee 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -21,6 +21,7 @@ use tracing::info; use super::Started; use crate::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; +use crate::servers::logging::STARTED_ON; use crate::servers::registar::ServiceRegistry; use crate::servers::signals::Halted; @@ -55,7 +56,7 @@ pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> Jo // Wait until the server sends the started message match rx_start.await { - Ok(msg) => info!(target: HEALTH_CHECK_API_LOG_TARGET, "Started on: {protocol}://{}", msg.address), + Ok(msg) => info!(target: HEALTH_CHECK_API_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", msg.address), Err(e) => panic!("the Health Check API server was dropped: {e}"), } diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index 8bf7974c1..37eb367b1 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize}; use crate::servers::health_check_api::HEALTH_CHECK_API_LOG_TARGET; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; +use crate::servers::logging::STARTED_ON; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; const INFO_LOG_LEVEL: &str = "INFO"; @@ -65,9 +66,9 @@ impl RunningServices { let mut http_trackers: Vec = Vec::new(); let mut health_checks: Vec = Vec::new(); - let udp_re = Regex::new(r"Started on: udp://([0-9.]+:[0-9]+)").unwrap(); - let http_re = Regex::new(r"Started on: (https?://[0-9.]+:[0-9]+)").unwrap(); // DevSkim: ignore DS137138 - let health_re = Regex::new(r"Started on: (https?://[0-9.]+:[0-9]+)").unwrap(); // DevSkim: ignore DS137138 + let udp_re = Regex::new(&format!("{STARTED_ON}: {}", r"udp://([0-9.]+:[0-9]+)")).unwrap(); + let http_re = Regex::new(&format!("{STARTED_ON}: {}", r"(https?://[0-9.]+:[0-9]+)")).unwrap(); // DevSkim: ignore DS137138 + let health_re = Regex::new(&format!("{STARTED_ON}: {}", r"(https?://[0-9.]+:[0-9]+)")).unwrap(); // DevSkim: ignore DS137138 let ansi_escape_re = Regex::new(r"\x1b\[[0-9;]*m").unwrap(); for line in logs.lines() { diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index d47e5d542..967080bd5 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -39,6 +39,7 @@ use crate::bootstrap::jobs::Started; use crate::core::Tracker; use crate::servers::apis::API_LOG_TARGET; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; +use crate::servers::logging::STARTED_ON; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{graceful_shutdown, Halted}; @@ -251,7 +252,7 @@ impl Launcher { } }); - info!(target: API_LOG_TARGET, "Started on {protocol}://{}", address); + info!(target: API_LOG_TARGET, "{STARTED_ON} {protocol}://{}", address); tx_start .send(Started { address }) diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 9199573b0..87f0e945b 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -14,6 +14,7 @@ use crate::bootstrap::jobs::Started; use crate::core::Tracker; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; +use crate::servers::logging::STARTED_ON; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{graceful_shutdown, Halted}; @@ -77,7 +78,7 @@ impl Launcher { } }); - info!(target: HTTP_TRACKER_LOG_TARGET, "Started on: {protocol}://{}", address); + info!(target: HTTP_TRACKER_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); tx_start .send(Started { address }) diff --git a/src/servers/logging.rs b/src/servers/logging.rs new file mode 100644 index 000000000..ad9ccbbcc --- /dev/null +++ b/src/servers/logging.rs @@ -0,0 +1,29 @@ +/// This is the prefix used in logs to identify a started service. +/// +/// For example: +/// +/// ```text +/// 2024-06-25T12:36:25.025312Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 +/// 2024-06-25T12:36:25.025445Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 +/// 2024-06-25T12:36:25.025527Z INFO API: Started on http://0.0.0.0:1212 +/// 2024-06-25T12:36:25.025580Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 +/// ``` +pub const STARTED_ON: &str = "Started on"; + +/* + +todo: we should use a field fot the URL. + +For example, instead of: + +``` +2024-06-25T12:36:25.025312Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 +``` + +We should use something like: + +``` +2024-06-25T12:36:25.025312Z INFO UDP TRACKER started_at_url=udp://0.0.0.0:6969 +``` + +*/ diff --git a/src/servers/mod.rs b/src/servers/mod.rs index 0c9cc5dd8..705a4728e 100644 --- a/src/servers/mod.rs +++ b/src/servers/mod.rs @@ -3,6 +3,7 @@ pub mod apis; pub mod custom_axum_server; pub mod health_check_api; pub mod http; +pub mod logging; pub mod registar; pub mod signals; pub mod udp; diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index e60e49ace..5e2a67c85 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -40,6 +40,7 @@ use tokio::task::{AbortHandle, JoinHandle}; use super::UdpRequest; use crate::bootstrap::jobs::Started; use crate::core::Tracker; +use crate::servers::logging::STARTED_ON; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{shutdown_signal_with_message, Halted}; use crate::servers::udp::{handlers, UDP_TRACKER_LOG_TARGET}; @@ -364,11 +365,7 @@ impl Udp { let address = bound_socket.local_addr(); let local_udp_url = format!("udp://{address}"); - // note: this log message is parsed by our container. i.e: - // - // `INFO UDP TRACKER: Started on: udp://0.0.0.0:6969` - // - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Started on: {local_udp_url}"); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "{STARTED_ON}: {local_udp_url}"); let receiver = Receiver::new(bound_socket.into(), tracker); From a5e2baf383edb593d6c8fe2e4477b8e6a61b466d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 13:52:26 +0100 Subject: [PATCH 0395/1297] refactor: extract method --- src/servers/udp/server.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 5e2a67c85..53fbaca34 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -36,6 +36,7 @@ use ringbuf::StaticRb; use tokio::select; use tokio::sync::oneshot; use tokio::task::{AbortHandle, JoinHandle}; +use url::Url; use super::UdpRequest; use crate::bootstrap::jobs::Started; @@ -241,6 +242,9 @@ struct BoundSocket { impl BoundSocket { async fn new(addr: SocketAddr) -> Result> { + let bind_addr = format!("udp://{addr}"); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, bind_addr, "UdpSocket::new (binding)"); + let socket = tokio::net::UdpSocket::bind(addr).await; let socket = match socket { @@ -259,6 +263,10 @@ impl BoundSocket { fn local_addr(&self) -> SocketAddr { self.socket.local_addr().expect("it should get local address") } + + fn url(&self) -> Url { + Url::parse(&format!("udp://{}", self.local_addr())).expect("UDP socket address should be valid") + } } impl Deref for BoundSocket { @@ -363,7 +371,7 @@ impl Udp { }; let address = bound_socket.local_addr(); - let local_udp_url = format!("udp://{address}"); + let local_udp_url = bound_socket.url().to_string(); tracing::info!(target: UDP_TRACKER_LOG_TARGET, "{STARTED_ON}: {local_udp_url}"); From 35b6c84fbb3d51365cd8e099225510d98494ac46 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 16:18:11 +0100 Subject: [PATCH 0396/1297] refactor: simplify UDP server receiver It only gets new UDP requests, whitout spwaning tasks to handle them. --- src/servers/udp/server.rs | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 53fbaca34..7557bff0b 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -290,22 +290,20 @@ impl Debug for BoundSocket { struct Receiver { bound_socket: Arc, - tracker: Arc, data: RefCell<[u8; MAX_PACKET_SIZE]>, } impl Receiver { - pub fn new(bound_socket: Arc, tracker: Arc) -> Self { + pub fn new(bound_socket: Arc) -> Self { Receiver { bound_socket, - tracker, data: RefCell::new([0; MAX_PACKET_SIZE]), } } } impl Stream for Receiver { - type Item = std::io::Result; + type Item = std::io::Result; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let mut buf = *self.data.borrow_mut(); @@ -319,13 +317,7 @@ impl Stream for Receiver { Ok(from) => { let payload = buf.filled().to_vec(); let request = UdpRequest { payload, from }; - - Some(Ok(tokio::task::spawn(Udp::process_request( - request, - self.tracker.clone(), - self.bound_socket.clone(), - )) - .abort_handle())) + Some(Ok(request)) } Err(err) => Some(Err(err)), }; @@ -375,7 +367,7 @@ impl Udp { tracing::info!(target: UDP_TRACKER_LOG_TARGET, "{STARTED_ON}: {local_udp_url}"); - let receiver = Receiver::new(bound_socket.into(), tracker); + let receiver = Receiver::new(bound_socket.into()); tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (spawning main loop)"); @@ -383,7 +375,7 @@ impl Udp { let local_addr = local_udp_url.clone(); tokio::task::spawn(async move { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_with_graceful_shutdown::task (listening...)"); - let () = Self::run_udp_server_main(receiver).await; + let () = Self::run_udp_server_main(receiver, tracker.clone()).await; }) }; @@ -404,7 +396,7 @@ impl Udp { tokio::task::yield_now().await; // lets allow the other threads to complete. } - async fn run_udp_server_main(mut receiver: Receiver) { + async fn run_udp_server_main(mut receiver: Receiver, tracker: Arc) { let reqs = &mut ActiveRequests::default(); let addr = receiver.bound_socket.local_addr(); @@ -429,12 +421,15 @@ impl Udp { } }; - if req.is_finished() { + let abort_handle = + tokio::task::spawn(Udp::process_request(req, tracker.clone(), receiver.bound_socket.clone())).abort_handle(); + + if abort_handle.is_finished() { continue; } // fill buffer with requests - let Err(req) = reqs.rb.try_push(req) else { + let Err(req) = reqs.rb.try_push(abort_handle) else { continue; }; From 61fb4b281d2d957be0292862d2517aebdc9dc1eb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 16:45:54 +0100 Subject: [PATCH 0397/1297] refactor: move active requests logic to ActiveRequest type --- src/servers/udp/server.rs | 125 ++++++++++++++++++++++++-------------- 1 file changed, 80 insertions(+), 45 deletions(-) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index 7557bff0b..14dd0a0f6 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -235,6 +235,67 @@ impl Drop for ActiveRequests { } } +impl ActiveRequests { + /// It inserts the abort handle for the UDP request processor tasks. + /// + /// If there is no room for the new task, it tries to make place: + /// + /// - Firstly, removing finished tasks. + /// - Secondly, removing the oldest unfinished tasks. + pub async fn force_push(&mut self, abort_handle: AbortHandle, local_addr: &str) { + // fill buffer with requests + let Err(abort_handle) = self.rb.try_push(abort_handle) else { + return; + }; + + let mut finished: u64 = 0; + let mut unfinished_task = None; + + // buffer is full.. lets make some space. + for h in self.rb.pop_iter() { + // remove some finished tasks + if h.is_finished() { + finished += 1; + continue; + } + + // task is unfinished.. give it another chance. + tokio::task::yield_now().await; + + // if now finished, we continue. + if h.is_finished() { + finished += 1; + continue; + } + + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, removed_count = finished, "Udp::run_udp_server::loop (got unfinished task)"); + + if finished == 0 { + // we have _no_ finished tasks.. will abort the unfinished task to make space... + h.abort(); + + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop aborting request: (no finished tasks)"); + break; + } + + // we have space, return unfinished task for re-entry. + unfinished_task = Some(h); + } + + // re-insert the previous unfinished task. + if let Some(h) = unfinished_task { + self.rb.try_push(h).expect("it was previously inserted"); + } + + // insert the new task. + if !abort_handle.is_finished() { + self.rb + .try_push(abort_handle) + .expect("it should remove at least one element."); + } + } +} + /// Wrapper for Tokio [`UdpSocket`][`tokio::net::UdpSocket`] that is bound to a particular socket. struct BoundSocket { socket: Arc, @@ -421,60 +482,34 @@ impl Udp { } }; - let abort_handle = - tokio::task::spawn(Udp::process_request(req, tracker.clone(), receiver.bound_socket.clone())).abort_handle(); - - if abort_handle.is_finished() { - continue; - } - - // fill buffer with requests - let Err(req) = reqs.rb.try_push(abort_handle) else { - continue; - }; - - let mut finished: u64 = 0; - let mut unfinished_task = None; - // buffer is full.. lets make some space. - for h in reqs.rb.pop_iter() { - // remove some finished tasks - if h.is_finished() { - finished += 1; - continue; - } + /* code-review: - // task is unfinished.. give it another chance. - tokio::task::yield_now().await; + Does it make sense to spawn a new request processor task when + the ActiveRequests buffer is full? - // if now finished, we continue. - if h.is_finished() { - finished += 1; - continue; - } + We could store the UDP request in a secondary buffer and wait + until active tasks are finished. When a active request is finished + we can move a new UDP request from the pending to process requests + buffer to the active requests buffer. - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, removed_count = finished, "Udp::run_udp_server::loop (got unfinished task)"); + This forces us to define an explicit timeout for active requests. - if finished == 0 { - // we have _no_ finished tasks.. will abort the unfinished task to make space... - h.abort(); + In the current solution the timeout is dynamic, it depends on + the system load. With high load we can remove tasks without + giving them enough time to be processed. With low load we could + keep processing running longer than a reasonable time for + the client to receive the response. - tracing::warn!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop aborting request: (no finished tasks)"); - break; - } + */ - // we have space, return unfinished task for re-entry. - unfinished_task = Some(h); - } + let abort_handle = + tokio::task::spawn(Udp::process_request(req, tracker.clone(), receiver.bound_socket.clone())).abort_handle(); - // re-insert the previous unfinished task. - if let Some(h) = unfinished_task { - reqs.rb.try_push(h).expect("it was previously inserted"); + if abort_handle.is_finished() { + continue; } - // insert the new task. - if !req.is_finished() { - reqs.rb.try_push(req).expect("it should remove at least one element."); - } + reqs.force_push(abort_handle, &local_addr).await; } else { tokio::task::yield_now().await; // the request iterator returned `None`. From 336e0e66f0c26c6393cc6701fa30ae0b83bf5aea Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 16:48:34 +0100 Subject: [PATCH 0398/1297] refactor: reorganize mod to extract new submods --- src/servers/udp/{server.rs => server/mod.rs} | 1 - 1 file changed, 1 deletion(-) rename src/servers/udp/{server.rs => server/mod.rs} (99%) diff --git a/src/servers/udp/server.rs b/src/servers/udp/server/mod.rs similarity index 99% rename from src/servers/udp/server.rs rename to src/servers/udp/server/mod.rs index 14dd0a0f6..36c377cc4 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server/mod.rs @@ -16,7 +16,6 @@ //! because we want to be able to start and stop the server multiple times, and //! we want to know the bound address and the current state of the server. //! In production, the `Udp` launcher is used directly. -//! use std::cell::RefCell; use std::fmt::Debug; From c121bf2575ecef77e2ecf14c15b30dbb90e33031 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 16:51:07 +0100 Subject: [PATCH 0399/1297] refactor: rename UDP server types --- src/bootstrap/jobs/udp_tracker.rs | 4 ++-- src/servers/udp/server/mod.rs | 33 ++++++++++++++++--------------- tests/servers/udp/environment.rs | 4 ++-- 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index ba39df2fe..e694163a9 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -14,7 +14,7 @@ use tracing::debug; use crate::core; use crate::servers::registar::ServiceRegistrationForm; -use crate::servers::udp::server::{Launcher, UdpServer}; +use crate::servers::udp::server::{Spawner, UdpServer}; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// It starts a new UDP server with the provided configuration. @@ -30,7 +30,7 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; pub async fn start_job(config: &UdpTracker, tracker: Arc, form: ServiceRegistrationForm) -> JoinHandle<()> { let bind_to = config.bind_address; - let server = UdpServer::new(Launcher::new(bind_to)) + let server = UdpServer::new(Spawner::new(bind_to)) .start(tracker, form) .await .expect("it should be able to start the udp tracker"); diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 36c377cc4..3b1792b3d 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -96,7 +96,7 @@ pub struct UdpServer { /// A stopped UDP server state. pub struct Stopped { - launcher: Launcher, + launcher: Spawner, } /// A running UDP server state. @@ -105,13 +105,13 @@ pub struct Running { /// The address where the server is bound. pub binding: SocketAddr, pub halt_task: tokio::sync::oneshot::Sender, - pub task: JoinHandle, + pub task: JoinHandle, } impl UdpServer { /// Creates a new `UdpServer` instance in `stopped`state. #[must_use] - pub fn new(launcher: Launcher) -> Self { + pub fn new(launcher: Spawner) -> Self { Self { state: Stopped { launcher }, } @@ -140,7 +140,7 @@ impl UdpServer { let binding = rx_start.await.expect("it should be able to start the service").address; let local_addr = format!("udp://{binding}"); - form.send(ServiceRegistration::new(binding, Udp::check)) + form.send(ServiceRegistration::new(binding, Launcher::check)) .expect("it should be able to send service registration"); let running_udp_server: UdpServer = UdpServer { @@ -186,12 +186,12 @@ impl UdpServer { } #[derive(Constructor, Copy, Clone, Debug)] -pub struct Launcher { +pub struct Spawner { bind_to: SocketAddr, } -impl Launcher { - /// It starts the UDP server instance. +impl Spawner { + /// It spawns a new tasks to run the UDP server instance. /// /// # Panics /// @@ -201,10 +201,10 @@ impl Launcher { tracker: Arc, tx_start: oneshot::Sender, rx_halt: oneshot::Receiver, - ) -> JoinHandle { - let launcher = Launcher::new(self.bind_to); + ) -> JoinHandle { + let launcher = Spawner::new(self.bind_to); tokio::spawn(async move { - Udp::run_with_graceful_shutdown(tracker, launcher.bind_to, tx_start, rx_halt).await; + Launcher::run_with_graceful_shutdown(tracker, launcher.bind_to, tx_start, rx_halt).await; launcher }) } @@ -388,9 +388,9 @@ impl Stream for Receiver { /// A UDP server instance launcher. #[derive(Constructor)] -pub struct Udp; +pub struct Launcher; -impl Udp { +impl Launcher { /// It starts the UDP server instance with graceful shutdown. /// /// # Panics @@ -502,7 +502,8 @@ impl Udp { */ let abort_handle = - tokio::task::spawn(Udp::process_request(req, tracker.clone(), receiver.bound_socket.clone())).abort_handle(); + tokio::task::spawn(Launcher::process_request(req, tracker.clone(), receiver.bound_socket.clone())) + .abort_handle(); if abort_handle.is_finished() { continue; @@ -589,7 +590,7 @@ mod tests { use crate::bootstrap::app::initialize_with_configuration; use crate::servers::registar::Registar; - use crate::servers::udp::server::{Launcher, UdpServer}; + use crate::servers::udp::server::{Spawner, UdpServer}; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { @@ -600,7 +601,7 @@ mod tests { let bind_to = config.bind_address; let register = &Registar::default(); - let stopped = UdpServer::new(Launcher::new(bind_to)); + let stopped = UdpServer::new(Spawner::new(bind_to)); let started = stopped .start(tracker, register.give_form()) @@ -622,7 +623,7 @@ mod tests { let bind_to = config.bind_address; let register = &Registar::default(); - let stopped = UdpServer::new(Launcher::new(bind_to)); + let stopped = UdpServer::new(Spawner::new(bind_to)); let started = stopped .start(tracker, register.give_form()) diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 7b21defce..e8fb048ca 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use torrust_tracker::bootstrap::app::initialize_with_configuration; use torrust_tracker::core::Tracker; use torrust_tracker::servers::registar::Registar; -use torrust_tracker::servers::udp::server::{Launcher, Running, Stopped, UdpServer}; +use torrust_tracker::servers::udp::server::{Running, Spawner, Stopped, UdpServer}; use torrust_tracker::shared::bit_torrent::tracker::udp::client::DEFAULT_TIMEOUT; use torrust_tracker_configuration::{Configuration, UdpTracker}; use torrust_tracker_primitives::info_hash::InfoHash; @@ -36,7 +36,7 @@ impl Environment { let bind_to = config.bind_address; - let server = UdpServer::new(Launcher::new(bind_to)); + let server = UdpServer::new(Spawner::new(bind_to)); Self { config, From 89bb73576af3b97f104943a6a01b7b0c37ae2489 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 17:53:14 +0100 Subject: [PATCH 0400/1297] refactor: reorganize UDP server mod --- src/bootstrap/jobs/udp_tracker.rs | 5 +- src/servers/udp/handlers.rs | 6 +- src/servers/udp/mod.rs | 2 +- src/servers/udp/server/bound_socket.rs | 73 +++ src/servers/udp/server/launcher.rs | 219 +++++++++ src/servers/udp/server/mod.rs | 550 +---------------------- src/servers/udp/server/receiver.rs | 54 +++ src/servers/udp/server/request_buffer.rs | 95 ++++ src/servers/udp/server/spawner.rs | 36 ++ src/servers/udp/server/states.rs | 115 +++++ tests/servers/udp/environment.rs | 8 +- tests/servers/udp/mod.rs | 4 +- 12 files changed, 621 insertions(+), 546 deletions(-) create mode 100644 src/servers/udp/server/bound_socket.rs create mode 100644 src/servers/udp/server/launcher.rs create mode 100644 src/servers/udp/server/receiver.rs create mode 100644 src/servers/udp/server/request_buffer.rs create mode 100644 src/servers/udp/server/spawner.rs create mode 100644 src/servers/udp/server/states.rs diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index e694163a9..647461bfc 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -14,7 +14,8 @@ use tracing::debug; use crate::core; use crate::servers::registar::ServiceRegistrationForm; -use crate::servers::udp::server::{Spawner, UdpServer}; +use crate::servers::udp::server::spawner::Spawner; +use crate::servers::udp::server::Server; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// It starts a new UDP server with the provided configuration. @@ -30,7 +31,7 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; pub async fn start_job(config: &UdpTracker, tracker: Arc, form: ServiceRegistrationForm) -> JoinHandle<()> { let bind_to = config.bind_address; - let server = UdpServer::new(Spawner::new(bind_to)) + let server = Server::new(Spawner::new(bind_to)) .start(tracker, form) .await .expect("it should be able to start the udp tracker"); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index f7e3aac64..12ae6a250 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -17,7 +17,7 @@ use uuid::Uuid; use zerocopy::network_endian::I32; use super::connection_cookie::{check, from_connection_id, into_connection_id, make}; -use super::UdpRequest; +use super::RawRequest; use crate::core::{statistics, ScrapeData, Tracker}; use crate::servers::udp::error::Error; use crate::servers::udp::logging::{log_bad_request, log_error_response, log_request, log_response}; @@ -33,7 +33,7 @@ use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; /// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. -pub(crate) async fn handle_packet(udp_request: UdpRequest, tracker: &Arc, addr: SocketAddr) -> Response { +pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Arc, addr: SocketAddr) -> Response { debug!("Handling Packets: {udp_request:?}"); let start_time = Instant::now(); @@ -304,7 +304,7 @@ fn handle_error(e: &Error, transaction_id: TransactionId) -> Response { pub struct RequestId(Uuid); impl RequestId { - fn make(_request: &UdpRequest) -> RequestId { + fn make(_request: &RawRequest) -> RequestId { RequestId(Uuid::new_v4()) } } diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index 5c5460397..8ea05d5b1 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -660,7 +660,7 @@ pub type Port = u16; pub type TransactionId = i64; #[derive(Clone, Debug)] -pub(crate) struct UdpRequest { +pub struct RawRequest { payload: Vec, from: SocketAddr, } diff --git a/src/servers/udp/server/bound_socket.rs b/src/servers/udp/server/bound_socket.rs new file mode 100644 index 000000000..cd416c7c5 --- /dev/null +++ b/src/servers/udp/server/bound_socket.rs @@ -0,0 +1,73 @@ +use std::fmt::Debug; +use std::net::SocketAddr; +use std::ops::Deref; +use std::sync::Arc; + +use url::Url; + +use crate::servers::udp::UDP_TRACKER_LOG_TARGET; + +/// Wrapper for Tokio [`UdpSocket`][`tokio::net::UdpSocket`] that is bound to a particular socket. +pub struct BoundSocket { + socket: Arc, +} + +impl BoundSocket { + /// # Errors + /// + /// Will return an error if the socket can't be bound the the provided address. + pub async fn new(addr: SocketAddr) -> Result> { + let bind_addr = format!("udp://{addr}"); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, bind_addr, "UdpSocket::new (binding)"); + + let socket = tokio::net::UdpSocket::bind(addr).await; + + let socket = match socket { + Ok(socket) => socket, + Err(e) => Err(e)?, + }; + + let local_addr = format!("udp://{addr}"); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpSocket::new (bound)"); + + Ok(Self { + socket: Arc::new(socket), + }) + } + + /// # Panics + /// + /// Will panic if the socket can't get the address it was bound to. + #[must_use] + pub fn address(&self) -> SocketAddr { + self.socket.local_addr().expect("it should get local address") + } + + /// # Panics + /// + /// Will panic if the address the socket was bound to is not a valid address + /// to be used in a URL. + #[must_use] + pub fn url(&self) -> Url { + Url::parse(&format!("udp://{}", self.address())).expect("UDP socket address should be valid") + } +} + +impl Deref for BoundSocket { + type Target = tokio::net::UdpSocket; + + fn deref(&self) -> &Self::Target { + &self.socket + } +} + +impl Debug for BoundSocket { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let local_addr = match self.socket.local_addr() { + Ok(socket) => format!("Receiving From: {socket}"), + Err(err) => format!("Socket Broken: {err}"), + }; + + f.debug_struct("UdpSocket").field("addr", &local_addr).finish_non_exhaustive() + } +} diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs new file mode 100644 index 000000000..db448c2ff --- /dev/null +++ b/src/servers/udp/server/launcher.rs @@ -0,0 +1,219 @@ +use std::io::Cursor; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::Duration; + +use aquatic_udp_protocol::Response; +use derive_more::Constructor; +use futures_util::StreamExt; +use tokio::select; +use tokio::sync::oneshot; + +use super::request_buffer::ActiveRequests; +use super::RawRequest; +use crate::bootstrap::jobs::Started; +use crate::core::Tracker; +use crate::servers::logging::STARTED_ON; +use crate::servers::registar::ServiceHealthCheckJob; +use crate::servers::signals::{shutdown_signal_with_message, Halted}; +use crate::servers::udp::server::bound_socket::BoundSocket; +use crate::servers::udp::server::receiver::Receiver; +use crate::servers::udp::{handlers, UDP_TRACKER_LOG_TARGET}; +use crate::shared::bit_torrent::tracker::udp::client::check; +use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; + +/// A UDP server instance launcher. +#[derive(Constructor)] +pub struct Launcher; + +impl Launcher { + /// It starts the UDP server instance with graceful shutdown. + /// + /// # Panics + /// + /// It panics if unable to bind to udp socket, and get the address from the udp socket. + /// It also panics if unable to send address of socket. + pub async fn run_with_graceful_shutdown( + tracker: Arc, + bind_to: SocketAddr, + tx_start: oneshot::Sender, + rx_halt: oneshot::Receiver, + ) { + let halt_task = tokio::task::spawn(shutdown_signal_with_message( + rx_halt, + format!("Halting UDP Service Bound to Socket: {bind_to}"), + )); + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting on: {bind_to}"); + + let socket = tokio::time::timeout(Duration::from_millis(5000), BoundSocket::new(bind_to)) + .await + .expect("it should bind to the socket within five seconds"); + + let bound_socket = match socket { + Ok(socket) => socket, + Err(e) => { + tracing::error!(target: UDP_TRACKER_LOG_TARGET, addr = %bind_to, err = %e, "Udp::run_with_graceful_shutdown panic! (error when building socket)" ); + panic!("could not bind to socket!"); + } + }; + + let address = bound_socket.address(); + let local_udp_url = bound_socket.url().to_string(); + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "{STARTED_ON}: {local_udp_url}"); + + let receiver = Receiver::new(bound_socket.into()); + + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (spawning main loop)"); + + let running = { + let local_addr = local_udp_url.clone(); + tokio::task::spawn(async move { + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_with_graceful_shutdown::task (listening...)"); + let () = Self::run_udp_server_main(receiver, tracker.clone()).await; + }) + }; + + tx_start + .send(Started { address }) + .expect("the UDP Tracker service should not be dropped"); + + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (started)"); + + let stop = running.abort_handle(); + + select! { + _ = running => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (stopped)"); }, + _ = halt_task => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (halting)"); } + } + stop.abort(); + + tokio::task::yield_now().await; // lets allow the other threads to complete. + } + + #[must_use] + pub fn check(binding: &SocketAddr) -> ServiceHealthCheckJob { + let binding = *binding; + let info = format!("checking the udp tracker health check at: {binding}"); + + let job = tokio::spawn(async move { check(&binding).await }); + + ServiceHealthCheckJob::new(binding, info, job) + } + + async fn run_udp_server_main(mut receiver: Receiver, tracker: Arc) { + let reqs = &mut ActiveRequests::default(); + + let addr = receiver.bound_socket_address(); + let local_addr = format!("udp://{addr}"); + + loop { + if let Some(req) = { + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server (wait for request)"); + receiver.next().await + } { + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop (in)"); + + let req = match req { + Ok(req) => req, + Err(e) => { + if e.kind() == std::io::ErrorKind::Interrupted { + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, local_addr, err = %e, "Udp::run_udp_server::loop (interrupted)"); + return; + } + tracing::error!(target: UDP_TRACKER_LOG_TARGET, local_addr, err = %e, "Udp::run_udp_server::loop break: (got error)"); + break; + } + }; + + /* code-review: + + Does it make sense to spawn a new request processor task when + the ActiveRequests buffer is full? + + We could store the UDP request in a secondary buffer and wait + until active tasks are finished. When a active request is finished + we can move a new UDP request from the pending to process requests + buffer to the active requests buffer. + + This forces us to define an explicit timeout for active requests. + + In the current solution the timeout is dynamic, it depends on + the system load. With high load we can remove tasks without + giving them enough time to be processed. With low load we could + keep processing running longer than a reasonable time for + the client to receive the response. + + */ + + let abort_handle = + tokio::task::spawn(Launcher::process_request(req, tracker.clone(), receiver.bound_socket.clone())) + .abort_handle(); + + if abort_handle.is_finished() { + continue; + } + + reqs.force_push(abort_handle, &local_addr).await; + } else { + tokio::task::yield_now().await; + // the request iterator returned `None`. + tracing::error!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server breaking: (ran dry, should not happen in production!)"); + break; + } + } + } + + async fn process_request(request: RawRequest, tracker: Arc, socket: Arc) { + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, request = %request.from, "Udp::process_request (receiving)"); + Self::process_valid_request(tracker, socket, request).await; + } + + async fn process_valid_request(tracker: Arc, socket: Arc, udp_request: RawRequest) { + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, "Udp::process_valid_request. Making Response to {udp_request:?}"); + let from = udp_request.from; + let response = handlers::handle_packet(udp_request, &tracker.clone(), socket.address()).await; + Self::send_response(&socket.clone(), from, response).await; + } + + async fn send_response(bound_socket: &Arc, to: SocketAddr, response: Response) { + let response_type = match &response { + Response::Connect(_) => "Connect".to_string(), + Response::AnnounceIpv4(_) => "AnnounceIpv4".to_string(), + Response::AnnounceIpv6(_) => "AnnounceIpv6".to_string(), + Response::Scrape(_) => "Scrape".to_string(), + Response::Error(e) => format!("Error: {e:?}"), + }; + + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, target = ?to, response_type, "Udp::send_response (sending)"); + + let buffer = vec![0u8; MAX_PACKET_SIZE]; + let mut cursor = Cursor::new(buffer); + + match response.write_bytes(&mut cursor) { + Ok(()) => { + #[allow(clippy::cast_possible_truncation)] + let position = cursor.position() as usize; + let inner = cursor.get_ref(); + + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count = &inner[..position].len(), "Udp::send_response (sending...)" ); + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count = &inner[..position].len(), payload = ?&inner[..position], "Udp::send_response (sending...)"); + + Self::send_packet(bound_socket, &to, &inner[..position]).await; + + tracing::trace!(target:UDP_TRACKER_LOG_TARGET, ?to, bytes_count = &inner[..position].len(), "Udp::send_response (sent)"); + } + Err(e) => { + tracing::error!(target: UDP_TRACKER_LOG_TARGET, ?to, response_type, err = %e, "Udp::send_response (error)"); + } + } + } + + async fn send_packet(bound_socket: &Arc, remote_addr: &SocketAddr, payload: &[u8]) { + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, to = %remote_addr, ?payload, "Udp::send_response (sending)"); + + // doesn't matter if it reaches or not + drop(bound_socket.send_to(payload, remote_addr).await); + } +} diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 3b1792b3d..1bb9831ee 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -17,35 +17,16 @@ //! we want to know the bound address and the current state of the server. //! In production, the `Udp` launcher is used directly. -use std::cell::RefCell; use std::fmt::Debug; -use std::io::Cursor; -use std::net::SocketAddr; -use std::ops::Deref; -use std::pin::Pin; -use std::sync::Arc; -use std::task::{Context, Poll}; -use std::time::Duration; - -use aquatic_udp_protocol::Response; -use derive_more::Constructor; -use futures::{Stream, StreamExt}; -use ringbuf::traits::{Consumer, Observer, Producer}; -use ringbuf::StaticRb; -use tokio::select; -use tokio::sync::oneshot; -use tokio::task::{AbortHandle, JoinHandle}; -use url::Url; - -use super::UdpRequest; -use crate::bootstrap::jobs::Started; -use crate::core::Tracker; -use crate::servers::logging::STARTED_ON; -use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; -use crate::servers::signals::{shutdown_signal_with_message, Halted}; -use crate::servers::udp::{handlers, UDP_TRACKER_LOG_TARGET}; -use crate::shared::bit_torrent::tracker::udp::client::check; -use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; + +use super::RawRequest; + +pub mod bound_socket; +pub mod launcher; +pub mod receiver; +pub mod request_buffer; +pub mod spawner; +pub mod states; /// Error that can occur when starting or stopping the UDP server. /// @@ -64,21 +45,7 @@ pub enum UdpError { Error(String), } -/// A UDP server instance controller with no UDP instance running. -#[allow(clippy::module_name_repetitions)] -pub type StoppedUdpServer = UdpServer; - -/// A UDP server instance controller with a running UDP instance. -#[allow(clippy::module_name_repetitions)] -pub type RunningUdpServer = UdpServer; - -/// A UDP server instance controller. -/// -/// It's responsible for: -/// -/// - Keeping the initial configuration of the server. -/// - Starting and stopping the server. -/// - Keeping the state of the server: `running` or `stopped`. +/// A UDP server. /// /// It's an state machine. Configurations cannot be changed. This struct /// represents concrete configuration and state. It allows to start and stop the @@ -88,499 +55,11 @@ pub type RunningUdpServer = UdpServer; /// > reset to the initial value after stopping the server. This struct is not /// > intended to persist configurations between runs. #[allow(clippy::module_name_repetitions)] -pub struct UdpServer { +pub struct Server { /// The state of the server: `running` or `stopped`. pub state: S, } -/// A stopped UDP server state. - -pub struct Stopped { - launcher: Spawner, -} - -/// A running UDP server state. -#[derive(Debug, Constructor)] -pub struct Running { - /// The address where the server is bound. - pub binding: SocketAddr, - pub halt_task: tokio::sync::oneshot::Sender, - pub task: JoinHandle, -} - -impl UdpServer { - /// Creates a new `UdpServer` instance in `stopped`state. - #[must_use] - pub fn new(launcher: Spawner) -> Self { - Self { - state: Stopped { launcher }, - } - } - - /// It starts the server and returns a `UdpServer` controller in `running` - /// state. - /// - /// # Errors - /// - /// Will return `Err` if UDP can't bind to given bind address. - /// - /// # Panics - /// - /// It panics if unable to receive the bound socket address from service. - /// - pub async fn start(self, tracker: Arc, form: ServiceRegistrationForm) -> Result, std::io::Error> { - let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); - let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); - - assert!(!tx_halt.is_closed(), "Halt channel for UDP tracker should be open"); - - // May need to wrap in a task to about a tokio bug. - let task = self.state.launcher.start(tracker, tx_start, rx_halt); - - let binding = rx_start.await.expect("it should be able to start the service").address; - let local_addr = format!("udp://{binding}"); - - form.send(ServiceRegistration::new(binding, Launcher::check)) - .expect("it should be able to send service registration"); - - let running_udp_server: UdpServer = UdpServer { - state: Running { - binding, - halt_task: tx_halt, - task, - }, - }; - - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpServer::start (running)"); - - Ok(running_udp_server) - } -} - -impl UdpServer { - /// It stops the server and returns a `UdpServer` controller in `stopped` - /// state. - /// - /// # Errors - /// - /// Will return `Err` if the oneshot channel to send the stop signal - /// has already been called once. - /// - /// # Panics - /// - /// It panics if unable to shutdown service. - pub async fn stop(self) -> Result, UdpError> { - self.state - .halt_task - .send(Halted::Normal) - .map_err(|e| UdpError::Error(e.to_string()))?; - - let launcher = self.state.task.await.expect("it should shutdown service"); - - let stopped_api_server: UdpServer = UdpServer { - state: Stopped { launcher }, - }; - - Ok(stopped_api_server) - } -} - -#[derive(Constructor, Copy, Clone, Debug)] -pub struct Spawner { - bind_to: SocketAddr, -} - -impl Spawner { - /// It spawns a new tasks to run the UDP server instance. - /// - /// # Panics - /// - /// It would panic if unable to resolve the `local_addr` from the supplied ´socket´. - pub fn start( - &self, - tracker: Arc, - tx_start: oneshot::Sender, - rx_halt: oneshot::Receiver, - ) -> JoinHandle { - let launcher = Spawner::new(self.bind_to); - tokio::spawn(async move { - Launcher::run_with_graceful_shutdown(tracker, launcher.bind_to, tx_start, rx_halt).await; - launcher - }) - } -} - -/// Ring-Buffer of Active Requests -#[derive(Default)] -struct ActiveRequests { - rb: StaticRb, // the number of requests we handle at the same time. -} - -impl std::fmt::Debug for ActiveRequests { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let (left, right) = &self.rb.as_slices(); - let dbg = format!("capacity: {}, left: {left:?}, right: {right:?}", &self.rb.capacity()); - f.debug_struct("ActiveRequests").field("rb", &dbg).finish() - } -} - -impl Drop for ActiveRequests { - fn drop(&mut self) { - for h in self.rb.pop_iter() { - if !h.is_finished() { - h.abort(); - } - } - } -} - -impl ActiveRequests { - /// It inserts the abort handle for the UDP request processor tasks. - /// - /// If there is no room for the new task, it tries to make place: - /// - /// - Firstly, removing finished tasks. - /// - Secondly, removing the oldest unfinished tasks. - pub async fn force_push(&mut self, abort_handle: AbortHandle, local_addr: &str) { - // fill buffer with requests - let Err(abort_handle) = self.rb.try_push(abort_handle) else { - return; - }; - - let mut finished: u64 = 0; - let mut unfinished_task = None; - - // buffer is full.. lets make some space. - for h in self.rb.pop_iter() { - // remove some finished tasks - if h.is_finished() { - finished += 1; - continue; - } - - // task is unfinished.. give it another chance. - tokio::task::yield_now().await; - - // if now finished, we continue. - if h.is_finished() { - finished += 1; - continue; - } - - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, removed_count = finished, "Udp::run_udp_server::loop (got unfinished task)"); - - if finished == 0 { - // we have _no_ finished tasks.. will abort the unfinished task to make space... - h.abort(); - - tracing::warn!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop aborting request: (no finished tasks)"); - break; - } - - // we have space, return unfinished task for re-entry. - unfinished_task = Some(h); - } - - // re-insert the previous unfinished task. - if let Some(h) = unfinished_task { - self.rb.try_push(h).expect("it was previously inserted"); - } - - // insert the new task. - if !abort_handle.is_finished() { - self.rb - .try_push(abort_handle) - .expect("it should remove at least one element."); - } - } -} - -/// Wrapper for Tokio [`UdpSocket`][`tokio::net::UdpSocket`] that is bound to a particular socket. -struct BoundSocket { - socket: Arc, -} - -impl BoundSocket { - async fn new(addr: SocketAddr) -> Result> { - let bind_addr = format!("udp://{addr}"); - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, bind_addr, "UdpSocket::new (binding)"); - - let socket = tokio::net::UdpSocket::bind(addr).await; - - let socket = match socket { - Ok(socket) => socket, - Err(e) => Err(e)?, - }; - - let local_addr = format!("udp://{addr}"); - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpSocket::new (bound)"); - - Ok(Self { - socket: Arc::new(socket), - }) - } - - fn local_addr(&self) -> SocketAddr { - self.socket.local_addr().expect("it should get local address") - } - - fn url(&self) -> Url { - Url::parse(&format!("udp://{}", self.local_addr())).expect("UDP socket address should be valid") - } -} - -impl Deref for BoundSocket { - type Target = tokio::net::UdpSocket; - - fn deref(&self) -> &Self::Target { - &self.socket - } -} - -impl Debug for BoundSocket { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let local_addr = match self.socket.local_addr() { - Ok(socket) => format!("Receiving From: {socket}"), - Err(err) => format!("Socket Broken: {err}"), - }; - - f.debug_struct("UdpSocket").field("addr", &local_addr).finish_non_exhaustive() - } -} - -struct Receiver { - bound_socket: Arc, - data: RefCell<[u8; MAX_PACKET_SIZE]>, -} - -impl Receiver { - pub fn new(bound_socket: Arc) -> Self { - Receiver { - bound_socket, - data: RefCell::new([0; MAX_PACKET_SIZE]), - } - } -} - -impl Stream for Receiver { - type Item = std::io::Result; - - fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - let mut buf = *self.data.borrow_mut(); - let mut buf = tokio::io::ReadBuf::new(&mut buf); - - let Poll::Ready(ready) = self.bound_socket.poll_recv_from(cx, &mut buf) else { - return Poll::Pending; - }; - - let res = match ready { - Ok(from) => { - let payload = buf.filled().to_vec(); - let request = UdpRequest { payload, from }; - Some(Ok(request)) - } - Err(err) => Some(Err(err)), - }; - - Poll::Ready(res) - } -} - -/// A UDP server instance launcher. -#[derive(Constructor)] -pub struct Launcher; - -impl Launcher { - /// It starts the UDP server instance with graceful shutdown. - /// - /// # Panics - /// - /// It panics if unable to bind to udp socket, and get the address from the udp socket. - /// It also panics if unable to send address of socket. - async fn run_with_graceful_shutdown( - tracker: Arc, - bind_to: SocketAddr, - tx_start: oneshot::Sender, - rx_halt: oneshot::Receiver, - ) { - let halt_task = tokio::task::spawn(shutdown_signal_with_message( - rx_halt, - format!("Halting UDP Service Bound to Socket: {bind_to}"), - )); - - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting on: {bind_to}"); - - let socket = tokio::time::timeout(Duration::from_millis(5000), BoundSocket::new(bind_to)) - .await - .expect("it should bind to the socket within five seconds"); - - let bound_socket = match socket { - Ok(socket) => socket, - Err(e) => { - tracing::error!(target: UDP_TRACKER_LOG_TARGET, addr = %bind_to, err = %e, "Udp::run_with_graceful_shutdown panic! (error when building socket)" ); - panic!("could not bind to socket!"); - } - }; - - let address = bound_socket.local_addr(); - let local_udp_url = bound_socket.url().to_string(); - - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "{STARTED_ON}: {local_udp_url}"); - - let receiver = Receiver::new(bound_socket.into()); - - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (spawning main loop)"); - - let running = { - let local_addr = local_udp_url.clone(); - tokio::task::spawn(async move { - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_with_graceful_shutdown::task (listening...)"); - let () = Self::run_udp_server_main(receiver, tracker.clone()).await; - }) - }; - - tx_start - .send(Started { address }) - .expect("the UDP Tracker service should not be dropped"); - - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (started)"); - - let stop = running.abort_handle(); - - select! { - _ = running => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (stopped)"); }, - _ = halt_task => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (halting)"); } - } - stop.abort(); - - tokio::task::yield_now().await; // lets allow the other threads to complete. - } - - async fn run_udp_server_main(mut receiver: Receiver, tracker: Arc) { - let reqs = &mut ActiveRequests::default(); - - let addr = receiver.bound_socket.local_addr(); - let local_addr = format!("udp://{addr}"); - - loop { - if let Some(req) = { - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server (wait for request)"); - receiver.next().await - } { - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop (in)"); - - let req = match req { - Ok(req) => req, - Err(e) => { - if e.kind() == std::io::ErrorKind::Interrupted { - tracing::warn!(target: UDP_TRACKER_LOG_TARGET, local_addr, err = %e, "Udp::run_udp_server::loop (interrupted)"); - return; - } - tracing::error!(target: UDP_TRACKER_LOG_TARGET, local_addr, err = %e, "Udp::run_udp_server::loop break: (got error)"); - break; - } - }; - - /* code-review: - - Does it make sense to spawn a new request processor task when - the ActiveRequests buffer is full? - - We could store the UDP request in a secondary buffer and wait - until active tasks are finished. When a active request is finished - we can move a new UDP request from the pending to process requests - buffer to the active requests buffer. - - This forces us to define an explicit timeout for active requests. - - In the current solution the timeout is dynamic, it depends on - the system load. With high load we can remove tasks without - giving them enough time to be processed. With low load we could - keep processing running longer than a reasonable time for - the client to receive the response. - - */ - - let abort_handle = - tokio::task::spawn(Launcher::process_request(req, tracker.clone(), receiver.bound_socket.clone())) - .abort_handle(); - - if abort_handle.is_finished() { - continue; - } - - reqs.force_push(abort_handle, &local_addr).await; - } else { - tokio::task::yield_now().await; - // the request iterator returned `None`. - tracing::error!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server breaking: (ran dry, should not happen in production!)"); - break; - } - } - } - - async fn process_request(request: UdpRequest, tracker: Arc, socket: Arc) { - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, request = %request.from, "Udp::process_request (receiving)"); - Self::process_valid_request(tracker, socket, request).await; - } - - async fn process_valid_request(tracker: Arc, socket: Arc, udp_request: UdpRequest) { - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, "Udp::process_valid_request. Making Response to {udp_request:?}"); - let from = udp_request.from; - let response = handlers::handle_packet(udp_request, &tracker.clone(), socket.local_addr()).await; - Self::send_response(&socket.clone(), from, response).await; - } - - async fn send_response(bound_socket: &Arc, to: SocketAddr, response: Response) { - let response_type = match &response { - Response::Connect(_) => "Connect".to_string(), - Response::AnnounceIpv4(_) => "AnnounceIpv4".to_string(), - Response::AnnounceIpv6(_) => "AnnounceIpv6".to_string(), - Response::Scrape(_) => "Scrape".to_string(), - Response::Error(e) => format!("Error: {e:?}"), - }; - - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, target = ?to, response_type, "Udp::send_response (sending)"); - - let buffer = vec![0u8; MAX_PACKET_SIZE]; - let mut cursor = Cursor::new(buffer); - - match response.write_bytes(&mut cursor) { - Ok(()) => { - #[allow(clippy::cast_possible_truncation)] - let position = cursor.position() as usize; - let inner = cursor.get_ref(); - - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count = &inner[..position].len(), "Udp::send_response (sending...)" ); - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count = &inner[..position].len(), payload = ?&inner[..position], "Udp::send_response (sending...)"); - - Self::send_packet(bound_socket, &to, &inner[..position]).await; - - tracing::trace!(target:UDP_TRACKER_LOG_TARGET, ?to, bytes_count = &inner[..position].len(), "Udp::send_response (sent)"); - } - Err(e) => { - tracing::error!(target: UDP_TRACKER_LOG_TARGET, ?to, response_type, err = %e, "Udp::send_response (error)"); - } - } - } - - async fn send_packet(socket: &Arc, remote_addr: &SocketAddr, payload: &[u8]) { - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, to = %remote_addr, ?payload, "Udp::send_response (sending)"); - - // doesn't matter if it reaches or not - drop(socket.send_to(payload, remote_addr).await); - } - - fn check(binding: &SocketAddr) -> ServiceHealthCheckJob { - let binding = *binding; - let info = format!("checking the udp tracker health check at: {binding}"); - - let job = tokio::spawn(async move { check(&binding).await }); - - ServiceHealthCheckJob::new(binding, info, job) - } -} - #[cfg(test)] mod tests { use std::sync::Arc; @@ -588,9 +67,10 @@ mod tests { use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; + use super::spawner::Spawner; + use super::Server; use crate::bootstrap::app::initialize_with_configuration; use crate::servers::registar::Registar; - use crate::servers::udp::server::{Spawner, UdpServer}; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { @@ -601,7 +81,7 @@ mod tests { let bind_to = config.bind_address; let register = &Registar::default(); - let stopped = UdpServer::new(Spawner::new(bind_to)); + let stopped = Server::new(Spawner::new(bind_to)); let started = stopped .start(tracker, register.give_form()) @@ -623,7 +103,7 @@ mod tests { let bind_to = config.bind_address; let register = &Registar::default(); - let stopped = UdpServer::new(Spawner::new(bind_to)); + let stopped = Server::new(Spawner::new(bind_to)); let started = stopped .start(tracker, register.give_form()) diff --git a/src/servers/udp/server/receiver.rs b/src/servers/udp/server/receiver.rs new file mode 100644 index 000000000..020ab7324 --- /dev/null +++ b/src/servers/udp/server/receiver.rs @@ -0,0 +1,54 @@ +use std::cell::RefCell; +use std::net::SocketAddr; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; + +use futures::Stream; + +use super::bound_socket::BoundSocket; +use super::RawRequest; +use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; + +pub struct Receiver { + pub bound_socket: Arc, + data: RefCell<[u8; MAX_PACKET_SIZE]>, +} + +impl Receiver { + #[must_use] + pub fn new(bound_socket: Arc) -> Self { + Receiver { + bound_socket, + data: RefCell::new([0; MAX_PACKET_SIZE]), + } + } + + pub fn bound_socket_address(&self) -> SocketAddr { + self.bound_socket.address() + } +} + +impl Stream for Receiver { + type Item = std::io::Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let mut buf = *self.data.borrow_mut(); + let mut buf = tokio::io::ReadBuf::new(&mut buf); + + let Poll::Ready(ready) = self.bound_socket.poll_recv_from(cx, &mut buf) else { + return Poll::Pending; + }; + + let res = match ready { + Ok(from) => { + let payload = buf.filled().to_vec(); + let request = RawRequest { payload, from }; + Some(Ok(request)) + } + Err(err) => Some(Err(err)), + }; + + Poll::Ready(res) + } +} diff --git a/src/servers/udp/server/request_buffer.rs b/src/servers/udp/server/request_buffer.rs new file mode 100644 index 000000000..c1d4f2696 --- /dev/null +++ b/src/servers/udp/server/request_buffer.rs @@ -0,0 +1,95 @@ +use ringbuf::traits::{Consumer, Observer, Producer}; +use ringbuf::StaticRb; +use tokio::task::AbortHandle; + +use crate::servers::udp::UDP_TRACKER_LOG_TARGET; + +/// Ring-Buffer of Active Requests +#[derive(Default)] +pub struct ActiveRequests { + rb: StaticRb, // the number of requests we handle at the same time. +} + +impl std::fmt::Debug for ActiveRequests { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let (left, right) = &self.rb.as_slices(); + let dbg = format!("capacity: {}, left: {left:?}, right: {right:?}", &self.rb.capacity()); + f.debug_struct("ActiveRequests").field("rb", &dbg).finish() + } +} + +impl Drop for ActiveRequests { + fn drop(&mut self) { + for h in self.rb.pop_iter() { + if !h.is_finished() { + h.abort(); + } + } + } +} + +impl ActiveRequests { + /// It inserts the abort handle for the UDP request processor tasks. + /// + /// If there is no room for the new task, it tries to make place: + /// + /// - Firstly, removing finished tasks. + /// - Secondly, removing the oldest unfinished tasks. + /// + /// # Panics + /// + /// Will panics if it can't make space for the new handle. + pub async fn force_push(&mut self, abort_handle: AbortHandle, local_addr: &str) { + // fill buffer with requests + let Err(abort_handle) = self.rb.try_push(abort_handle) else { + return; + }; + + let mut finished: u64 = 0; + let mut unfinished_task = None; + + // buffer is full.. lets make some space. + for h in self.rb.pop_iter() { + // remove some finished tasks + if h.is_finished() { + finished += 1; + continue; + } + + // task is unfinished.. give it another chance. + tokio::task::yield_now().await; + + // if now finished, we continue. + if h.is_finished() { + finished += 1; + continue; + } + + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, removed_count = finished, "Udp::run_udp_server::loop (got unfinished task)"); + + if finished == 0 { + // we have _no_ finished tasks.. will abort the unfinished task to make space... + h.abort(); + + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop aborting request: (no finished tasks)"); + + break; + } + + // we have space, return unfinished task for re-entry. + unfinished_task = Some(h); + } + + // re-insert the previous unfinished task. + if let Some(h) = unfinished_task { + self.rb.try_push(h).expect("it was previously inserted"); + } + + // insert the new task. + if !abort_handle.is_finished() { + self.rb + .try_push(abort_handle) + .expect("it should remove at least one element."); + } + } +} diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs new file mode 100644 index 000000000..a36404fce --- /dev/null +++ b/src/servers/udp/server/spawner.rs @@ -0,0 +1,36 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use derive_more::Constructor; +use tokio::sync::oneshot; +use tokio::task::JoinHandle; + +use super::launcher::Launcher; +use crate::bootstrap::jobs::Started; +use crate::core::Tracker; +use crate::servers::signals::Halted; + +#[derive(Constructor, Copy, Clone, Debug)] +pub struct Spawner { + pub bind_to: SocketAddr, +} + +impl Spawner { + /// It spawns a new tasks to run the UDP server instance. + /// + /// # Panics + /// + /// It would panic if unable to resolve the `local_addr` from the supplied ´socket´. + pub fn start( + &self, + tracker: Arc, + tx_start: oneshot::Sender, + rx_halt: oneshot::Receiver, + ) -> JoinHandle { + let launcher = Spawner::new(self.bind_to); + tokio::spawn(async move { + Launcher::run_with_graceful_shutdown(tracker, launcher.bind_to, tx_start, rx_halt).await; + launcher + }) + } +} diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs new file mode 100644 index 000000000..919646d7b --- /dev/null +++ b/src/servers/udp/server/states.rs @@ -0,0 +1,115 @@ +use std::fmt::Debug; +use std::net::SocketAddr; +use std::sync::Arc; + +use derive_more::Constructor; +use tokio::task::JoinHandle; + +use super::spawner::Spawner; +use super::{Server, UdpError}; +use crate::bootstrap::jobs::Started; +use crate::core::Tracker; +use crate::servers::registar::{ServiceRegistration, ServiceRegistrationForm}; +use crate::servers::signals::Halted; +use crate::servers::udp::server::launcher::Launcher; +use crate::servers::udp::UDP_TRACKER_LOG_TARGET; + +/// A UDP server instance controller with no UDP instance running. +#[allow(clippy::module_name_repetitions)] +pub type StoppedUdpServer = Server; + +/// A UDP server instance controller with a running UDP instance. +#[allow(clippy::module_name_repetitions)] +pub type RunningUdpServer = Server; + +/// A stopped UDP server state. + +pub struct Stopped { + pub launcher: Spawner, +} + +/// A running UDP server state. +#[derive(Debug, Constructor)] +pub struct Running { + /// The address where the server is bound. + pub binding: SocketAddr, + pub halt_task: tokio::sync::oneshot::Sender, + pub task: JoinHandle, +} + +impl Server { + /// Creates a new `UdpServer` instance in `stopped`state. + #[must_use] + pub fn new(launcher: Spawner) -> Self { + Self { + state: Stopped { launcher }, + } + } + + /// It starts the server and returns a `UdpServer` controller in `running` + /// state. + /// + /// # Errors + /// + /// Will return `Err` if UDP can't bind to given bind address. + /// + /// # Panics + /// + /// It panics if unable to receive the bound socket address from service. + /// + pub async fn start(self, tracker: Arc, form: ServiceRegistrationForm) -> Result, std::io::Error> { + let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); + let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); + + assert!(!tx_halt.is_closed(), "Halt channel for UDP tracker should be open"); + + // May need to wrap in a task to about a tokio bug. + let task = self.state.launcher.start(tracker, tx_start, rx_halt); + + let binding = rx_start.await.expect("it should be able to start the service").address; + let local_addr = format!("udp://{binding}"); + + form.send(ServiceRegistration::new(binding, Launcher::check)) + .expect("it should be able to send service registration"); + + let running_udp_server: Server = Server { + state: Running { + binding, + halt_task: tx_halt, + task, + }, + }; + + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpServer::start (running)"); + + Ok(running_udp_server) + } +} + +impl Server { + /// It stops the server and returns a `UdpServer` controller in `stopped` + /// state. + /// + /// # Errors + /// + /// Will return `Err` if the oneshot channel to send the stop signal + /// has already been called once. + /// + /// # Panics + /// + /// It panics if unable to shutdown service. + pub async fn stop(self) -> Result, UdpError> { + self.state + .halt_task + .send(Halted::Normal) + .map_err(|e| UdpError::Error(e.to_string()))?; + + let launcher = self.state.task.await.expect("it should shutdown service"); + + let stopped_api_server: Server = Server { + state: Stopped { launcher }, + }; + + Ok(stopped_api_server) + } +} diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index e8fb048ca..2232cb0e0 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -4,7 +4,9 @@ use std::sync::Arc; use torrust_tracker::bootstrap::app::initialize_with_configuration; use torrust_tracker::core::Tracker; use torrust_tracker::servers::registar::Registar; -use torrust_tracker::servers::udp::server::{Running, Spawner, Stopped, UdpServer}; +use torrust_tracker::servers::udp::server::spawner::Spawner; +use torrust_tracker::servers::udp::server::states::{Running, Stopped}; +use torrust_tracker::servers::udp::server::Server; use torrust_tracker::shared::bit_torrent::tracker::udp::client::DEFAULT_TIMEOUT; use torrust_tracker_configuration::{Configuration, UdpTracker}; use torrust_tracker_primitives::info_hash::InfoHash; @@ -14,7 +16,7 @@ pub struct Environment { pub config: Arc, pub tracker: Arc, pub registar: Registar, - pub server: UdpServer, + pub server: Server, } impl Environment { @@ -36,7 +38,7 @@ impl Environment { let bind_to = config.bind_address; - let server = UdpServer::new(Spawner::new(bind_to)); + let server = Server::new(Spawner::new(bind_to)); Self { config, diff --git a/tests/servers/udp/mod.rs b/tests/servers/udp/mod.rs index b13b82240..7eea8683f 100644 --- a/tests/servers/udp/mod.rs +++ b/tests/servers/udp/mod.rs @@ -1,7 +1,7 @@ -use torrust_tracker::servers::udp::server; +use torrust_tracker::servers::udp::server::states::Running; pub mod asserts; pub mod contract; pub mod environment; -pub type Started = environment::Environment; +pub type Started = environment::Environment; From f06976e33defa286e9856239f79f9a83f9d168c5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Jun 2024 18:02:01 +0100 Subject: [PATCH 0401/1297] docs: update some UDP server comments --- src/servers/udp/server/mod.rs | 24 +++--------------------- src/servers/udp/server/spawner.rs | 12 +++++++----- src/servers/udp/server/states.rs | 10 +++++----- 3 files changed, 15 insertions(+), 31 deletions(-) diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 1bb9831ee..034f71beb 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -1,22 +1,4 @@ //! Module to handle the UDP server instances. -//! -//! There are two main types in this module: -//! -//! - [`UdpServer`]: a controller to start and stop the server. -//! - [`Udp`]: the server launcher. -//! -//! The `UdpServer` is an state machine for a given configuration. This struct -//! represents concrete configuration and state. It allows to start and -//! stop the server but always keeping the same configuration. -//! -//! The `Udp` is the server launcher. It's responsible for launching the UDP -//! but without keeping any state. -//! -//! For the time being, the `UdpServer` is only used for testing purposes, -//! because we want to be able to start and stop the server multiple times, and -//! we want to know the bound address and the current state of the server. -//! In production, the `Udp` launcher is used directly. - use std::fmt::Debug; use super::RawRequest; @@ -37,7 +19,7 @@ pub mod states; /// /// Some errors triggered while stopping the server are: /// -/// - The [`UdpServer`] cannot send the shutdown signal to the spawned UDP service thread. +/// - The [`Server`] cannot send the shutdown signal to the spawned UDP service thread. #[derive(Debug)] pub enum UdpError { /// Any kind of error starting or stopping the server. @@ -92,7 +74,7 @@ mod tests { tokio::time::sleep(Duration::from_secs(1)).await; - assert_eq!(stopped.state.launcher.bind_to, bind_to); + assert_eq!(stopped.state.spawner.bind_to, bind_to); } #[tokio::test] @@ -116,7 +98,7 @@ mod tests { tokio::time::sleep(Duration::from_secs(1)).await; - assert_eq!(stopped.state.launcher.bind_to, bind_to); + assert_eq!(stopped.state.spawner.bind_to, bind_to); } } diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index a36404fce..e4612fbe0 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -1,3 +1,4 @@ +//! A thin wrapper for tokio spawn to launch the UDP server launcher as a new task. use std::net::SocketAddr; use std::sync::Arc; @@ -16,21 +17,22 @@ pub struct Spawner { } impl Spawner { - /// It spawns a new tasks to run the UDP server instance. + /// It spawns a new task to run the UDP server instance. /// /// # Panics /// /// It would panic if unable to resolve the `local_addr` from the supplied ´socket´. - pub fn start( + pub fn spawn_launcher( &self, tracker: Arc, tx_start: oneshot::Sender, rx_halt: oneshot::Receiver, ) -> JoinHandle { - let launcher = Spawner::new(self.bind_to); + let spawner = Self::new(self.bind_to); + tokio::spawn(async move { - Launcher::run_with_graceful_shutdown(tracker, launcher.bind_to, tx_start, rx_halt).await; - launcher + Launcher::run_with_graceful_shutdown(tracker, spawner.bind_to, tx_start, rx_halt).await; + spawner }) } } diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index 919646d7b..d0a2e4e8a 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -25,7 +25,7 @@ pub type RunningUdpServer = Server; /// A stopped UDP server state. pub struct Stopped { - pub launcher: Spawner, + pub spawner: Spawner, } /// A running UDP server state. @@ -40,9 +40,9 @@ pub struct Running { impl Server { /// Creates a new `UdpServer` instance in `stopped`state. #[must_use] - pub fn new(launcher: Spawner) -> Self { + pub fn new(spawner: Spawner) -> Self { Self { - state: Stopped { launcher }, + state: Stopped { spawner }, } } @@ -64,7 +64,7 @@ impl Server { assert!(!tx_halt.is_closed(), "Halt channel for UDP tracker should be open"); // May need to wrap in a task to about a tokio bug. - let task = self.state.launcher.start(tracker, tx_start, rx_halt); + let task = self.state.spawner.spawn_launcher(tracker, tx_start, rx_halt); let binding = rx_start.await.expect("it should be able to start the service").address; let local_addr = format!("udp://{binding}"); @@ -107,7 +107,7 @@ impl Server { let launcher = self.state.task.await.expect("it should shutdown service"); let stopped_api_server: Server = Server { - state: Stopped { launcher }, + state: Stopped { spawner: launcher }, }; Ok(stopped_api_server) From 2518c544f83ec0f7ff8d9f70f255d63ffe0460b1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 26 Jun 2024 17:02:27 +0100 Subject: [PATCH 0402/1297] fix: [#917] clients output in JSON should not include logging --- src/console/clients/checker/app.rs | 48 ++++++++++++++++++++++++++++-- src/console/clients/udp/app.rs | 4 +-- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/console/clients/checker/app.rs b/src/console/clients/checker/app.rs index 84802688d..e3bca2319 100644 --- a/src/console/clients/checker/app.rs +++ b/src/console/clients/checker/app.rs @@ -12,12 +12,56 @@ //! ```text //! TORRUST_CHECKER_CONFIG=$(cat "./share/default/config/tracker_checker.json") cargo run --bin tracker_checker //! ``` +//! +//! Another real example to test the Torrust demo tracker: +//! +//! ```text +//! TORRUST_CHECKER_CONFIG='{ +//! "udp_trackers": ["144.126.245.19:6969"], +//! "http_trackers": ["https://tracker.torrust-demo.com"], +//! "health_checks": ["https://tracker.torrust-demo.com/api/health_check"] +//! }' cargo run --bin tracker_checker +//! ``` +//! +//! The output should be something like the following: +//! +//! ```json +//! { +//! "udp_trackers": [ +//! { +//! "url": "144.126.245.19:6969", +//! "status": { +//! "code": "ok", +//! "message": "" +//! } +//! } +//! ], +//! "http_trackers": [ +//! { +//! "url": "https://tracker.torrust-demo.com/", +//! "status": { +//! "code": "ok", +//! "message": "" +//! } +//! } +//! ], +//! "health_checks": [ +//! { +//! "url": "https://tracker.torrust-demo.com/api/health_check", +//! "status": { +//! "code": "ok", +//! "message": "" +//! } +//! } +//! ] +//! } +//! ``` use std::path::PathBuf; use std::sync::Arc; use anyhow::{Context, Result}; use clap::Parser; -use tracing::info; +use tracing::debug; use tracing::level_filters::LevelFilter; use super::config::Configuration; @@ -59,7 +103,7 @@ pub async fn run() -> Result> { fn tracing_stdout_init(filter: LevelFilter) { tracing_subscriber::fmt().with_max_level(filter).init(); - info!("logging initialized."); + debug!("logging initialized."); } fn setup_config(args: Args) -> Result { diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index c780157f4..51d21b51e 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -63,8 +63,8 @@ use anyhow::Context; use aquatic_udp_protocol::{Port, Response, TransactionId}; use clap::{Parser, Subcommand}; use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; +use tracing::debug; use tracing::level_filters::LevelFilter; -use tracing::{debug, info}; use url::Url; use crate::console::clients::udp::checker; @@ -128,7 +128,7 @@ pub async fn run() -> anyhow::Result<()> { fn tracing_stdout_init(filter: LevelFilter) { tracing_subscriber::fmt().with_max_level(filter).init(); - info!("logging initialized."); + debug!("logging initialized."); } async fn handle_announce(tracker_socket_addr: &SocketAddr, info_hash: &TorrustInfoHash) -> anyhow::Result { From 3d567c8410b6b8ec83997ca94036ec571db43b5a Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 28 Jun 2024 20:17:28 +0200 Subject: [PATCH 0403/1297] ci: nightly build for coverage --- .github/workflows/coverage.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 66def04bf..125cd2487 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -36,7 +36,7 @@ jobs: - id: setup name: Setup Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@nightly with: toolchain: nightly components: llvm-tools-preview From f0de8dd327854cd270b40247bca10ac60213c404 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 29 Jun 2024 19:07:23 +0200 Subject: [PATCH 0404/1297] ci: pre-build coverage test --- .github/workflows/coverage.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 125cd2487..024935df4 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -59,6 +59,10 @@ jobs: name: Clean Build Directory run: cargo clean + - id: build + name: Pre-build Main Project + run: cargo build + - id: test name: Run Unit Tests run: cargo test --tests --workspace --all-targets --all-features From 5f3957a5642049c96574e81126df2e665978a518 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 30 Jun 2024 14:42:38 +0200 Subject: [PATCH 0405/1297] ci: coverage build with two jobs --- .github/workflows/coverage.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 024935df4..7e929030d 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -61,7 +61,7 @@ jobs: - id: build name: Pre-build Main Project - run: cargo build + run: cargo build --jobs 2 - id: test name: Run Unit Tests From 16d4cb66ab87d33c7ba8ee8fab59898558bd8a2c Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 30 Jun 2024 17:18:58 +0200 Subject: [PATCH 0406/1297] ci: coverage workflow add pre-build-test step --- .github/workflows/coverage.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 7e929030d..4dc104242 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -63,6 +63,10 @@ jobs: name: Pre-build Main Project run: cargo build --jobs 2 + - id: build_tests + name: Pre-build Tests + run: cargo build --tests --jobs 2 + - id: test name: Run Unit Tests run: cargo test --tests --workspace --all-targets --all-features From 988f1c7b8d196bf3703060cf5fc0bad3412a1c07 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 26 Jun 2024 16:20:26 +0200 Subject: [PATCH 0407/1297] dev: add vscode 'code-workspace' to git ignore file --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index c1abad7e0..b60b28991 100644 --- a/.gitignore +++ b/.gitignore @@ -12,4 +12,5 @@ /tracker.* /tracker.toml callgrind.out -perf.data* \ No newline at end of file +perf.data* +*.code-workspace \ No newline at end of file From c202db7186c2d2baf249f89f341c5317ddb09bb2 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 28 Jun 2024 18:36:44 +0200 Subject: [PATCH 0408/1297] dev: tracker client error enums --- Cargo.lock | 1 + Cargo.toml | 2 +- packages/configuration/src/lib.rs | 5 + src/console/clients/checker/app.rs | 2 +- src/console/clients/checker/checks/health.rs | 100 ++++--- src/console/clients/checker/checks/http.rs | 169 +++++------ src/console/clients/checker/checks/udp.rs | 142 ++++----- src/console/clients/checker/service.rs | 69 +++-- src/console/clients/http/app.rs | 14 +- src/console/clients/http/mod.rs | 35 +++ src/console/clients/udp/app.rs | 33 +-- src/console/clients/udp/checker.rs | 185 +++++------- src/console/clients/udp/mod.rs | 48 +++ src/servers/apis/routes.rs | 6 +- src/servers/http/v1/routes.rs | 5 +- .../bit_torrent/tracker/http/client/mod.rs | 139 ++++++--- src/shared/bit_torrent/tracker/udp/client.rs | 276 +++++++++--------- src/shared/bit_torrent/tracker/udp/mod.rs | 62 +++- tests/servers/udp/contract.rs | 33 ++- tests/servers/udp/environment.rs | 3 +- 20 files changed, 770 insertions(+), 559 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 94fbe7d87..4b833504e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4274,6 +4274,7 @@ dependencies = [ "form_urlencoded", "idna", "percent-encoding", + "serde", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index c22c3dd45..a65c2a74d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -80,7 +80,7 @@ tower-http = { version = "0", features = ["compression-full", "cors", "propagate trace = "0" tracing = "0" tracing-subscriber = { version = "0.3.18", features = ["json"] } -url = "2" +url = {version = "2", features = ["serde"] } uuid = { version = "1", features = ["v4"] } zerocopy = "0.7.33" diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index c8c91443a..ca008a49a 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -9,6 +9,7 @@ pub mod v1; use std::collections::HashMap; use std::env; use std::sync::Arc; +use std::time::Duration; use camino::Utf8PathBuf; use derive_more::Constructor; @@ -20,6 +21,10 @@ use torrust_tracker_located_error::{DynError, LocatedError}; /// The maximum number of returned peers for a torrent. pub const TORRENT_PEERS_LIMIT: usize = 74; +/// Default timeout for sending and receiving packets. And waiting for sockets +/// to be readable and writable. +pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5); + // Environment variables /// The whole `tracker.toml` file content. It has priority over the config file. diff --git a/src/console/clients/checker/app.rs b/src/console/clients/checker/app.rs index e3bca2319..9f9825d92 100644 --- a/src/console/clients/checker/app.rs +++ b/src/console/clients/checker/app.rs @@ -98,7 +98,7 @@ pub async fn run() -> Result> { console: console_printer, }; - Ok(service.run_checks().await) + service.run_checks().await.context("it should run the check tasks") } fn tracing_stdout_init(filter: LevelFilter) { diff --git a/src/console/clients/checker/checks/health.rs b/src/console/clients/checker/checks/health.rs index 47eec4cbd..b1fb79148 100644 --- a/src/console/clients/checker/checks/health.rs +++ b/src/console/clients/checker/checks/health.rs @@ -1,49 +1,77 @@ +use std::sync::Arc; use std::time::Duration; -use reqwest::{Client as HttpClient, Url, Url as ServiceUrl}; +use anyhow::Result; +use hyper::StatusCode; +use reqwest::{Client as HttpClient, Response}; +use serde::Serialize; +use thiserror::Error; +use url::Url; -use super::structs::{CheckerOutput, Status}; -use crate::console::clients::checker::service::{CheckError, CheckResult}; +#[derive(Debug, Clone, Error, Serialize)] +#[serde(into = "String")] +pub enum Error { + #[error("Failed to Build a Http Client: {err:?}")] + ClientBuildingError { err: Arc }, + #[error("Heath check failed to get a response: {err:?}")] + ResponseError { err: Arc }, + #[error("Http check returned a non-success code: \"{code}\" with the response: \"{response:?}\"")] + UnsuccessfulResponse { code: StatusCode, response: Arc }, +} + +impl From for String { + fn from(value: Error) -> Self { + value.to_string() + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct Checks { + url: Url, + result: Result, +} -#[allow(clippy::missing_panics_doc)] -pub async fn run(health_checks: &Vec, check_results: &mut Vec) -> Vec { - let mut health_checkers: Vec = Vec::new(); +pub async fn run(health_checks: Vec, timeout: Duration) -> Vec> { + let mut results = Vec::default(); - for health_check_url in health_checks { - let mut health_checker = CheckerOutput { - url: health_check_url.to_string(), - status: Status { - code: String::new(), - message: String::new(), - }, + tracing::debug!("Health checks ..."); + + for url in health_checks { + let result = match run_health_check(url.clone(), timeout).await { + Ok(response) => Ok(response.status().to_string()), + Err(err) => Err(err), }; - match run_health_check(health_check_url.clone()).await { - Ok(()) => { - check_results.push(Ok(())); - health_checker.status.code = "ok".to_string(); - } - Err(err) => { - check_results.push(Err(err)); - health_checker.status.code = "error".to_string(); - health_checker.status.message = "Health API is failing.".to_string(); - } + + let check = Checks { url, result }; + + if check.result.is_err() { + results.push(Err(check)); + } else { + results.push(Ok(check)); } - health_checkers.push(health_checker); } - health_checkers + + results } -async fn run_health_check(url: Url) -> Result<(), CheckError> { - let client = HttpClient::builder().timeout(Duration::from_secs(5)).build().unwrap(); +async fn run_health_check(url: Url, timeout: Duration) -> Result { + let client = HttpClient::builder() + .timeout(timeout) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; - match client.get(url.clone()).send().await { - Ok(response) => { - if response.status().is_success() { - Ok(()) - } else { - Err(CheckError::HealthCheckError { url }) - } - } - Err(_) => Err(CheckError::HealthCheckError { url }), + let response = client + .get(url.clone()) + .send() + .await + .map_err(|e| Error::ResponseError { err: e.into() })?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) } } diff --git a/src/console/clients/checker/checks/http.rs b/src/console/clients/checker/checks/http.rs index 57f8c3015..8abbeb669 100644 --- a/src/console/clients/checker/checks/http.rs +++ b/src/console/clients/checker/checks/http.rs @@ -1,120 +1,101 @@ -use std::str::FromStr; +use std::str::FromStr as _; +use std::time::Duration; -use reqwest::Url as ServiceUrl; +use serde::Serialize; use torrust_tracker_primitives::info_hash::InfoHash; -use tracing::debug; use url::Url; -use super::structs::{CheckerOutput, Status}; -use crate::console::clients::checker::service::{CheckError, CheckResult}; -use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; +use crate::console::clients::http::Error; use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; use crate::shared::bit_torrent::tracker::http::client::responses::scrape; use crate::shared::bit_torrent::tracker::http::client::{requests, Client}; -#[allow(clippy::missing_panics_doc)] -pub async fn run(http_trackers: &Vec, check_results: &mut Vec) -> Vec { - let mut http_checkers: Vec = Vec::new(); - - for http_tracker in http_trackers { - let mut http_checker = CheckerOutput { - url: http_tracker.to_string(), - status: Status { - code: String::new(), - message: String::new(), - }, +#[derive(Debug, Clone, Serialize)] +pub struct Checks { + url: Url, + results: Vec<(Check, Result<(), Error>)>, +} + +#[derive(Debug, Clone, Serialize)] +pub enum Check { + Announce, + Scrape, +} + +pub async fn run(http_trackers: Vec, timeout: Duration) -> Vec> { + let mut results = Vec::default(); + + tracing::debug!("HTTP trackers ..."); + + for ref url in http_trackers { + let mut checks = Checks { + url: url.clone(), + results: Vec::default(), }; - match check_http_announce(http_tracker).await { - Ok(()) => { - check_results.push(Ok(())); - http_checker.status.code = "ok".to_string(); - } - Err(err) => { - check_results.push(Err(err)); - http_checker.status.code = "error".to_string(); - http_checker.status.message = "Announce is failing.".to_string(); - } + // Announce + { + let check = check_http_announce(url, timeout).await.map(|_| ()); + + checks.results.push((Check::Announce, check)); } - match check_http_scrape(http_tracker).await { - Ok(()) => { - check_results.push(Ok(())); - http_checker.status.code = "ok".to_string(); - } - Err(err) => { - check_results.push(Err(err)); - http_checker.status.code = "error".to_string(); - http_checker.status.message = "Scrape is failing.".to_string(); - } + // Scrape + { + let check = check_http_scrape(url, timeout).await.map(|_| ()); + + checks.results.push((Check::Scrape, check)); + } + + if checks.results.iter().any(|f| f.1.is_err()) { + results.push(Err(checks)); + } else { + results.push(Ok(checks)); } - http_checkers.push(http_checker); } - http_checkers + + results } -async fn check_http_announce(tracker_url: &Url) -> Result<(), CheckError> { +async fn check_http_announce(url: &Url, timeout: Duration) -> Result { let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // # DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); - // todo: HTTP request could panic.For example, if the server is not accessible. - // We should change the client to catch that error and return a `CheckError`. - // Otherwise the checking process will stop. The idea is to process all checks - // and return a final report. - let Ok(client) = Client::new(tracker_url.clone()) else { - return Err(CheckError::HttpError { - url: (tracker_url.to_owned()), - }); - }; - let Ok(response) = client - .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) + let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; + + let response = client + .announce( + &requests::announce::QueryBuilder::with_default_values() + .with_info_hash(&info_hash) + .query(), + ) .await - else { - return Err(CheckError::HttpError { - url: (tracker_url.to_owned()), - }); - }; - - if let Ok(body) = response.bytes().await { - if let Ok(_announce_response) = serde_bencode::from_bytes::(&body) { - Ok(()) - } else { - debug!("announce body {:#?}", body); - Err(CheckError::HttpError { - url: tracker_url.clone(), - }) - } - } else { - Err(CheckError::HttpError { - url: tracker_url.clone(), - }) - } + .map_err(|err| Error::HttpClientError { err })?; + + let response = response.bytes().await.map_err(|e| Error::ResponseError { err: e.into() })?; + + let response = serde_bencode::from_bytes::(&response).map_err(|e| Error::ParseBencodeError { + data: response, + err: e.into(), + })?; + + Ok(response) } -async fn check_http_scrape(url: &Url) -> Result<(), CheckError> { +async fn check_http_scrape(url: &Url, timeout: Duration) -> Result { let info_hashes: Vec = vec!["9c38422213e30bff212b30c360d26f9a02136422".to_string()]; // # DevSkim: ignore DS173237 let query = requests::scrape::Query::try_from(info_hashes).expect("a valid array of info-hashes is required"); - // todo: HTTP request could panic.For example, if the server is not accessible. - // We should change the client to catch that error and return a `CheckError`. - // Otherwise the checking process will stop. The idea is to process all checks - // and return a final report. - - let Ok(client) = Client::new(url.clone()) else { - return Err(CheckError::HttpError { url: (url.to_owned()) }); - }; - let Ok(response) = client.scrape(&query).await else { - return Err(CheckError::HttpError { url: (url.to_owned()) }); - }; - - if let Ok(body) = response.bytes().await { - if let Ok(_scrape_response) = scrape::Response::try_from_bencoded(&body) { - Ok(()) - } else { - debug!("scrape body {:#?}", body); - Err(CheckError::HttpError { url: url.clone() }) - } - } else { - Err(CheckError::HttpError { url: url.clone() }) - } + let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; + + let response = client.scrape(&query).await.map_err(|err| Error::HttpClientError { err })?; + + let response = response.bytes().await.map_err(|e| Error::ResponseError { err: e.into() })?; + + let response = scrape::Response::try_from_bencoded(&response).map_err(|e| Error::BencodeParseError { + data: response, + err: e.into(), + })?; + + Ok(response) } diff --git a/src/console/clients/checker/checks/udp.rs b/src/console/clients/checker/checks/udp.rs index 072aa5ca7..dd4d5e639 100644 --- a/src/console/clients/checker/checks/udp.rs +++ b/src/console/clients/checker/checks/udp.rs @@ -1,94 +1,98 @@ use std::net::SocketAddr; +use std::time::Duration; -use aquatic_udp_protocol::{Port, TransactionId}; +use aquatic_udp_protocol::TransactionId; use hex_literal::hex; +use serde::Serialize; use torrust_tracker_primitives::info_hash::InfoHash; -use tracing::debug; -use crate::console::clients::checker::checks::structs::{CheckerOutput, Status}; -use crate::console::clients::checker::service::{CheckError, CheckResult}; -use crate::console::clients::udp::checker; +use crate::console::clients::udp::checker::Client; +use crate::console::clients::udp::Error; -const ASSIGNED_BY_OS: u16 = 0; -const RANDOM_TRANSACTION_ID: i32 = -888_840_697; - -#[allow(clippy::missing_panics_doc)] -pub async fn run(udp_trackers: &Vec, check_results: &mut Vec) -> Vec { - let mut udp_checkers: Vec = Vec::new(); - - for udp_tracker in udp_trackers { - let mut checker_output = CheckerOutput { - url: udp_tracker.to_string(), - status: Status { - code: String::new(), - message: String::new(), - }, - }; +#[derive(Debug, Clone, Serialize)] +pub struct Checks { + remote_addr: SocketAddr, + results: Vec<(Check, Result<(), Error>)>, +} - debug!("UDP tracker: {:?}", udp_tracker); +#[derive(Debug, Clone, Serialize)] +pub enum Check { + Setup, + Connect, + Announce, + Scrape, +} - let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); +#[allow(clippy::missing_panics_doc)] +pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec> { + let mut results = Vec::default(); - let mut client = checker::Client::default(); + tracing::debug!("UDP trackers ..."); - debug!("Bind and connect"); + let info_hash = InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237 - let Ok(bound_to) = client.bind_and_connect(ASSIGNED_BY_OS, udp_tracker).await else { - check_results.push(Err(CheckError::UdpError { - socket_addr: *udp_tracker, - })); - checker_output.status.code = "error".to_string(); - checker_output.status.message = "Can't connect to socket.".to_string(); - break; + for remote_addr in udp_trackers { + let mut checks = Checks { + remote_addr, + results: Vec::default(), }; - debug!("Send connection request"); - - let Ok(connection_id) = client.send_connection_request(transaction_id).await else { - check_results.push(Err(CheckError::UdpError { - socket_addr: *udp_tracker, - })); - checker_output.status.code = "error".to_string(); - checker_output.status.message = "Can't make tracker connection request.".to_string(); - break; + tracing::debug!("UDP tracker: {:?}", remote_addr); + + // Setup + let client = match Client::new(remote_addr, timeout).await { + Ok(client) => { + checks.results.push((Check::Setup, Ok(()))); + client + } + Err(err) => { + checks.results.push((Check::Setup, Err(err))); + results.push(Err(checks)); + break; + } }; - let info_hash = InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237 - - debug!("Send announce request"); + let transaction_id = TransactionId::new(1); + + // Connect Remote + let connection_id = match client.send_connection_request(transaction_id).await { + Ok(connection_id) => { + checks.results.push((Check::Connect, Ok(()))); + connection_id + } + Err(err) => { + checks.results.push((Check::Connect, Err(err))); + results.push(Err(checks)); + break; + } + }; - if (client - .send_announce_request(connection_id, transaction_id, info_hash, Port(bound_to.port().into())) - .await) - .is_ok() + // Announce { - check_results.push(Ok(())); - checker_output.status.code = "ok".to_string(); - } else { - let err = CheckError::UdpError { - socket_addr: *udp_tracker, - }; - check_results.push(Err(err)); - checker_output.status.code = "error".to_string(); - checker_output.status.message = "Announce is failing.".to_string(); + let check = client + .send_announce_request(transaction_id, connection_id, info_hash) + .await + .map(|_| ()); + + checks.results.push((Check::Announce, check)); } - debug!("Send scrape request"); + // Scrape + { + let check = client + .send_scrape_request(connection_id, transaction_id, &[info_hash]) + .await + .map(|_| ()); - let info_hashes = vec![InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422"))]; // # DevSkim: ignore DS173237 + checks.results.push((Check::Announce, check)); + } - if (client.send_scrape_request(connection_id, transaction_id, info_hashes).await).is_ok() { - check_results.push(Ok(())); - checker_output.status.code = "ok".to_string(); + if checks.results.iter().any(|f| f.1.is_err()) { + results.push(Err(checks)); } else { - let err = CheckError::UdpError { - socket_addr: *udp_tracker, - }; - check_results.push(Err(err)); - checker_output.status.code = "error".to_string(); - checker_output.status.message = "Scrape is failing.".to_string(); + results.push(Ok(checks)); } - udp_checkers.push(checker_output); } - udp_checkers + + results } diff --git a/src/console/clients/checker/service.rs b/src/console/clients/checker/service.rs index 16483e92e..acd312d8c 100644 --- a/src/console/clients/checker/service.rs +++ b/src/console/clients/checker/service.rs @@ -1,9 +1,11 @@ -use std::net::SocketAddr; use std::sync::Arc; -use reqwest::Url; +use futures::FutureExt as _; +use serde::Serialize; +use tokio::task::{JoinError, JoinSet}; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; -use super::checks::{self}; +use super::checks::{health, http, udp}; use super::config::Configuration; use super::console::Console; use crate::console::clients::checker::printer::Printer; @@ -13,33 +15,48 @@ pub struct Service { pub(crate) console: Console, } -pub type CheckResult = Result<(), CheckError>; - -#[derive(Debug)] -pub enum CheckError { - UdpError { socket_addr: SocketAddr }, - HttpError { url: Url }, - HealthCheckError { url: Url }, +#[derive(Debug, Clone, Serialize)] +pub enum CheckResult { + Udp(Result), + Http(Result), + Health(Result), } impl Service { /// # Errors /// - /// Will return OK is all checks pass or an array with the check errors. - #[allow(clippy::missing_panics_doc)] - pub async fn run_checks(&self) -> Vec { - let mut check_results = vec![]; - - let udp_checkers = checks::udp::run(&self.config.udp_trackers, &mut check_results).await; - - let http_checkers = checks::http::run(&self.config.http_trackers, &mut check_results).await; - - let health_checkers = checks::health::run(&self.config.health_checks, &mut check_results).await; - - let json_output = - serde_json::json!({ "udp_trackers": udp_checkers, "http_trackers": http_checkers, "health_checks": health_checkers }); - self.console.println(&serde_json::to_string_pretty(&json_output).unwrap()); - - check_results + /// It will return an error if some of the tests panic or otherwise fail to run. + /// On success it will return a vector of `Ok(())` of [`CheckResult`]. + /// + /// # Panics + /// + /// It would panic if `serde_json` produces invalid json for the `to_string_pretty` function. + pub async fn run_checks(self) -> Result, JoinError> { + tracing::info!("Running checks for trackers ..."); + + let mut check_results = Vec::default(); + + let mut checks = JoinSet::new(); + checks.spawn( + udp::run(self.config.udp_trackers.clone(), DEFAULT_TIMEOUT).map(|mut f| f.drain(..).map(CheckResult::Udp).collect()), + ); + checks.spawn( + http::run(self.config.http_trackers.clone(), DEFAULT_TIMEOUT) + .map(|mut f| f.drain(..).map(CheckResult::Http).collect()), + ); + checks.spawn( + health::run(self.config.health_checks.clone(), DEFAULT_TIMEOUT) + .map(|mut f| f.drain(..).map(CheckResult::Health).collect()), + ); + + while let Some(results) = checks.join_next().await { + check_results.append(&mut results?); + } + + let json_output = serde_json::json!(check_results); + self.console + .println(&serde_json::to_string_pretty(&json_output).expect("it should consume valid json")); + + Ok(check_results) } } diff --git a/src/console/clients/http/app.rs b/src/console/clients/http/app.rs index 8fc9db0c3..a54db5f8b 100644 --- a/src/console/clients/http/app.rs +++ b/src/console/clients/http/app.rs @@ -14,10 +14,12 @@ //! cargo run --bin http_tracker_client scrape http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq //! ``` use std::str::FromStr; +use std::time::Duration; use anyhow::Context; use clap::{Parser, Subcommand}; use reqwest::Url; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_primitives::info_hash::InfoHash; use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; @@ -46,25 +48,25 @@ pub async fn run() -> anyhow::Result<()> { match args.command { Command::Announce { tracker_url, info_hash } => { - announce_command(tracker_url, info_hash).await?; + announce_command(tracker_url, info_hash, DEFAULT_TIMEOUT).await?; } Command::Scrape { tracker_url, info_hashes, } => { - scrape_command(&tracker_url, &info_hashes).await?; + scrape_command(&tracker_url, &info_hashes, DEFAULT_TIMEOUT).await?; } } Ok(()) } -async fn announce_command(tracker_url: String, info_hash: String) -> anyhow::Result<()> { +async fn announce_command(tracker_url: String, info_hash: String, timeout: Duration) -> anyhow::Result<()> { let base_url = Url::parse(&tracker_url).context("failed to parse HTTP tracker base URL")?; let info_hash = InfoHash::from_str(&info_hash).expect("Invalid infohash. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); - let response = Client::new(base_url)? + let response = Client::new(base_url, timeout)? .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) .await?; @@ -80,12 +82,12 @@ async fn announce_command(tracker_url: String, info_hash: String) -> anyhow::Res Ok(()) } -async fn scrape_command(tracker_url: &str, info_hashes: &[String]) -> anyhow::Result<()> { +async fn scrape_command(tracker_url: &str, info_hashes: &[String], timeout: Duration) -> anyhow::Result<()> { let base_url = Url::parse(tracker_url).context("failed to parse HTTP tracker base URL")?; let query = requests::scrape::Query::try_from(info_hashes).context("failed to parse infohashes")?; - let response = Client::new(base_url)?.scrape(&query).await?; + let response = Client::new(base_url, timeout)?.scrape(&query).await?; let body = response.bytes().await?; diff --git a/src/console/clients/http/mod.rs b/src/console/clients/http/mod.rs index 309be6287..eaa71957f 100644 --- a/src/console/clients/http/mod.rs +++ b/src/console/clients/http/mod.rs @@ -1 +1,36 @@ +use std::sync::Arc; + +use serde::Serialize; +use thiserror::Error; + +use crate::shared::bit_torrent::tracker::http::client::responses::scrape::BencodeParseError; + pub mod app; + +#[derive(Debug, Clone, Error, Serialize)] +#[serde(into = "String")] +pub enum Error { + #[error("Http request did not receive a response within the timeout: {err:?}")] + HttpClientError { + err: crate::shared::bit_torrent::tracker::http::client::Error, + }, + #[error("Http failed to get a response at all: {err:?}")] + ResponseError { err: Arc }, + #[error("Failed to deserialize the bencoded response data with the error: \"{err:?}\"")] + ParseBencodeError { + data: hyper::body::Bytes, + err: Arc, + }, + + #[error("Failed to deserialize the bencoded response data with the error: \"{err:?}\"")] + BencodeParseError { + data: hyper::body::Bytes, + err: Arc, + }, +} + +impl From for String { + fn from(value: Error) -> Self { + value.to_string() + } +} diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index 51d21b51e..bcba39558 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -60,18 +60,19 @@ use std::net::{SocketAddr, ToSocketAddrs}; use std::str::FromStr; use anyhow::Context; -use aquatic_udp_protocol::{Port, Response, TransactionId}; +use aquatic_udp_protocol::{Response, TransactionId}; use clap::{Parser, Subcommand}; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; use tracing::debug; use tracing::level_filters::LevelFilter; use url::Url; +use super::Error; use crate::console::clients::udp::checker; use crate::console::clients::udp::responses::dto::SerializableResponse; use crate::console::clients::udp::responses::json::ToJson; -const ASSIGNED_BY_OS: u16 = 0; const RANDOM_TRANSACTION_ID: i32 = -888_840_697; #[derive(Parser, Debug)] @@ -109,13 +110,13 @@ pub async fn run() -> anyhow::Result<()> { let response = match args.command { Command::Announce { - tracker_socket_addr, + tracker_socket_addr: remote_addr, info_hash, - } => handle_announce(&tracker_socket_addr, &info_hash).await?, + } => handle_announce(remote_addr, &info_hash).await?, Command::Scrape { - tracker_socket_addr, + tracker_socket_addr: remote_addr, info_hashes, - } => handle_scrape(&tracker_socket_addr, &info_hashes).await?, + } => handle_scrape(remote_addr, &info_hashes).await?, }; let response: SerializableResponse = response.into(); @@ -131,32 +132,24 @@ fn tracing_stdout_init(filter: LevelFilter) { debug!("logging initialized."); } -async fn handle_announce(tracker_socket_addr: &SocketAddr, info_hash: &TorrustInfoHash) -> anyhow::Result { +async fn handle_announce(remote_addr: SocketAddr, info_hash: &TorrustInfoHash) -> Result { let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); - let mut client = checker::Client::default(); - - let bound_to = client.bind_and_connect(ASSIGNED_BY_OS, tracker_socket_addr).await?; + let client = checker::Client::new(remote_addr, DEFAULT_TIMEOUT).await?; let connection_id = client.send_connection_request(transaction_id).await?; - client - .send_announce_request(connection_id, transaction_id, *info_hash, Port(bound_to.port().into())) - .await + client.send_announce_request(transaction_id, connection_id, *info_hash).await } -async fn handle_scrape(tracker_socket_addr: &SocketAddr, info_hashes: &[TorrustInfoHash]) -> anyhow::Result { +async fn handle_scrape(remote_addr: SocketAddr, info_hashes: &[TorrustInfoHash]) -> Result { let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); - let mut client = checker::Client::default(); - - let _bound_to = client.bind_and_connect(ASSIGNED_BY_OS, tracker_socket_addr).await?; + let client = checker::Client::new(remote_addr, DEFAULT_TIMEOUT).await?; let connection_id = client.send_connection_request(transaction_id).await?; - client - .send_scrape_request(connection_id, transaction_id, info_hashes.to_vec()) - .await + client.send_scrape_request(connection_id, transaction_id, info_hashes).await } fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { diff --git a/src/console/clients/udp/checker.rs b/src/console/clients/udp/checker.rs index afde63d12..49f0ac41f 100644 --- a/src/console/clients/udp/checker.rs +++ b/src/console/clients/udp/checker.rs @@ -1,99 +1,46 @@ use std::net::{Ipv4Addr, SocketAddr}; +use std::num::NonZeroU16; +use std::time::Duration; -use anyhow::Context; use aquatic_udp_protocol::common::InfoHash; use aquatic_udp_protocol::{ AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, Response, ScrapeRequest, TransactionId, }; -use thiserror::Error; use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; use tracing::debug; -use crate::shared::bit_torrent::tracker::udp::client::{UdpClient, UdpTrackerClient}; - -#[derive(Error, Debug)] -pub enum ClientError { - #[error("Local socket address is not bound yet. Try binding before connecting.")] - NotBound, - #[error("Not connected to remote tracker UDP socket. Try connecting before making requests.")] - NotConnected, - #[error("Unexpected response while connecting the the remote server.")] - UnexpectedConnectionResponse, -} +use super::Error; +use crate::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; /// A UDP Tracker client to make test requests (checks). -#[derive(Debug, Default)] +#[derive(Debug)] pub struct Client { - /// Local UDP socket. It could be 0 to assign a free port. - local_binding_address: Option, - - /// Local UDP socket after binding. It's equals to binding address if a - /// non- zero port was used. - local_bound_address: Option, - - /// Remote UDP tracker socket - remote_socket: Option, - - /// The client used to make UDP requests to the tracker. - udp_tracker_client: Option, + client: UdpTrackerClient, } impl Client { - /// Binds to the local socket and connects to the remote one. + /// Creates a new `[Client]` for checking a UDP Tracker Service /// /// # Errors /// - /// Will return an error if - /// - /// - It can't bound to the local socket address. - /// - It can't make a connection request successfully to the remote UDP server. - pub async fn bind_and_connect(&mut self, local_port: u16, remote_socket_addr: &SocketAddr) -> anyhow::Result { - let bound_to = self.bind(local_port).await?; - self.connect(remote_socket_addr).await?; - Ok(bound_to) - } - - /// Binds local client socket. - /// - /// # Errors + /// It will error if unable to bind and connect to the udp remote address. /// - /// Will return an error if it can't bound to the local address. - async fn bind(&mut self, local_port: u16) -> anyhow::Result { - let local_bind_to = format!("0.0.0.0:{local_port}"); - let binding_address = local_bind_to.parse().context("binding local address")?; - - debug!("Binding to: {local_bind_to}"); - let udp_client = UdpClient::bind(&local_bind_to).await?; - - let bound_to = udp_client.socket.local_addr().context("bound local address")?; - debug!("Bound to: {bound_to}"); - - self.local_binding_address = Some(binding_address); - self.local_bound_address = Some(bound_to); - - self.udp_tracker_client = Some(UdpTrackerClient { udp_client }); + pub async fn new(remote_addr: SocketAddr, timeout: Duration) -> Result { + let client = UdpTrackerClient::new(remote_addr, timeout) + .await + .map_err(|err| Error::UnableToBindAndConnect { remote_addr, err })?; - Ok(bound_to) + Ok(Self { client }) } - /// Connects to the remote server socket. + /// Returns the local addr of this [`Client`]. /// /// # Errors /// - /// Will return and error if it can't make a connection request successfully - /// to the remote UDP server. - async fn connect(&mut self, tracker_socket_addr: &SocketAddr) -> anyhow::Result<()> { - debug!("Connecting to tracker: udp://{tracker_socket_addr}"); - - match &self.udp_tracker_client { - Some(client) => { - client.udp_client.connect(&tracker_socket_addr.to_string()).await?; - self.remote_socket = Some(*tracker_socket_addr); - Ok(()) - } - None => Err(ClientError::NotBound.into()), - } + /// This function will return an error if the socket is somehow not bound. + pub fn local_addr(&self) -> std::io::Result { + self.client.client.socket.local_addr() } /// Sends a connection request to the UDP Tracker server. @@ -109,25 +56,26 @@ impl Client { /// # Panics /// /// Will panic if it receives an unexpected response. - pub async fn send_connection_request(&self, transaction_id: TransactionId) -> anyhow::Result { + pub async fn send_connection_request(&self, transaction_id: TransactionId) -> Result { debug!("Sending connection request with transaction id: {transaction_id:#?}"); let connect_request = ConnectRequest { transaction_id }; - match &self.udp_tracker_client { - Some(client) => { - client.send(connect_request.into()).await?; - - let response = client.receive().await?; - - debug!("connection request response:\n{response:#?}"); - - match response { - Response::Connect(connect_response) => Ok(connect_response.connection_id), - _ => Err(ClientError::UnexpectedConnectionResponse.into()), - } - } - None => Err(ClientError::NotConnected.into()), + let _ = self + .client + .send(connect_request.into()) + .await + .map_err(|err| Error::UnableToSendConnectionRequest { err })?; + + let response = self + .client + .receive() + .await + .map_err(|err| Error::UnableToReceiveConnectResponse { err })?; + + match response { + Response::Connect(connect_response) => Ok(connect_response.connection_id), + _ => Err(Error::UnexpectedConnectionResponse { response }), } } @@ -137,15 +85,28 @@ impl Client { /// /// Will return and error if the client is not connected. You have to connect /// before calling this function. + /// + /// # Panics + /// + /// It will panic if the `local_address` has a zero port. pub async fn send_announce_request( &self, - connection_id: ConnectionId, transaction_id: TransactionId, + connection_id: ConnectionId, info_hash: TorrustInfoHash, - client_port: Port, - ) -> anyhow::Result { + ) -> Result { debug!("Sending announce request with transaction id: {transaction_id:#?}"); + let port = NonZeroU16::new( + self.client + .client + .socket + .local_addr() + .expect("it should get the local address") + .port(), + ) + .expect("it should no be zero"); + let announce_request = AnnounceRequest { connection_id, action_placeholder: AnnounceActionPlaceholder::default(), @@ -159,21 +120,22 @@ impl Client { ip_address: Ipv4Addr::new(0, 0, 0, 0).into(), key: PeerKey::new(0i32), peers_wanted: NumberOfPeers(1i32.into()), - port: client_port, + port: Port::new(port), }; - match &self.udp_tracker_client { - Some(client) => { - client.send(announce_request.into()).await?; - - let response = client.receive().await?; + let _ = self + .client + .send(announce_request.into()) + .await + .map_err(|err| Error::UnableToSendAnnounceRequest { err })?; - debug!("announce request response:\n{response:#?}"); + let response = self + .client + .receive() + .await + .map_err(|err| Error::UnableToReceiveAnnounceResponse { err })?; - Ok(response) - } - None => Err(ClientError::NotConnected.into()), - } + Ok(response) } /// Sends a scrape request to the UDP Tracker server. @@ -186,8 +148,8 @@ impl Client { &self, connection_id: ConnectionId, transaction_id: TransactionId, - info_hashes: Vec, - ) -> anyhow::Result { + info_hashes: &[TorrustInfoHash], + ) -> Result { debug!("Sending scrape request with transaction id: {transaction_id:#?}"); let scrape_request = ScrapeRequest { @@ -199,17 +161,18 @@ impl Client { .collect(), }; - match &self.udp_tracker_client { - Some(client) => { - client.send(scrape_request.into()).await?; - - let response = client.receive().await?; + let _ = self + .client + .send(scrape_request.into()) + .await + .map_err(|err| Error::UnableToSendScrapeRequest { err })?; - debug!("scrape request response:\n{response:#?}"); + let response = self + .client + .receive() + .await + .map_err(|err| Error::UnableToReceiveScrapeResponse { err })?; - Ok(response) - } - None => Err(ClientError::NotConnected.into()), - } + Ok(response) } } diff --git a/src/console/clients/udp/mod.rs b/src/console/clients/udp/mod.rs index 2fcb26ed0..b92bed096 100644 --- a/src/console/clients/udp/mod.rs +++ b/src/console/clients/udp/mod.rs @@ -1,3 +1,51 @@ +use std::net::SocketAddr; + +use aquatic_udp_protocol::Response; +use serde::Serialize; +use thiserror::Error; + +use crate::shared::bit_torrent::tracker::udp; + pub mod app; pub mod checker; pub mod responses; + +#[derive(Error, Debug, Clone, Serialize)] +#[serde(into = "String")] +pub enum Error { + #[error("Failed to Connect to: {remote_addr}, with error: {err}")] + UnableToBindAndConnect { remote_addr: SocketAddr, err: udp::Error }, + + #[error("Failed to send a connection request, with error: {err}")] + UnableToSendConnectionRequest { err: udp::Error }, + + #[error("Failed to receive a connect response, with error: {err}")] + UnableToReceiveConnectResponse { err: udp::Error }, + + #[error("Failed to send a announce request, with error: {err}")] + UnableToSendAnnounceRequest { err: udp::Error }, + + #[error("Failed to receive a announce response, with error: {err}")] + UnableToReceiveAnnounceResponse { err: udp::Error }, + + #[error("Failed to send a scrape request, with error: {err}")] + UnableToSendScrapeRequest { err: udp::Error }, + + #[error("Failed to receive a scrape response, with error: {err}")] + UnableToReceiveScrapeResponse { err: udp::Error }, + + #[error("Failed to receive a response, with error: {err}")] + UnableToReceiveResponse { err: udp::Error }, + + #[error("Failed to get local address for connection: {err}")] + UnableToGetLocalAddr { err: udp::Error }, + + #[error("Failed to get a connection response: {response:?}")] + UnexpectedConnectionResponse { response: Response }, +} + +impl From for String { + fn from(value: Error) -> Self { + value.to_string() + } +} diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 2001afc2f..4901d760d 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -14,7 +14,7 @@ use axum::response::Response; use axum::routing::get; use axum::{middleware, BoxError, Router}; use hyper::{Request, StatusCode}; -use torrust_tracker_configuration::AccessTokens; +use torrust_tracker_configuration::{AccessTokens, DEFAULT_TIMEOUT}; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; use tower_http::compression::CompressionLayer; @@ -29,8 +29,6 @@ use super::v1::middlewares::auth::State; use crate::core::Tracker; use crate::servers::apis::API_LOG_TARGET; -const TIMEOUT: Duration = Duration::from_secs(5); - /// Add all API routes to the router. #[allow(clippy::needless_pass_by_value)] pub fn router(tracker: Arc, access_tokens: Arc) -> Router { @@ -84,6 +82,6 @@ pub fn router(tracker: Arc, access_tokens: Arc) -> Router // this middleware goes above `TimeoutLayer` because it will receive // errors returned by `TimeoutLayer` .layer(HandleErrorLayer::new(|_: BoxError| async { StatusCode::REQUEST_TIMEOUT })) - .layer(TimeoutLayer::new(TIMEOUT)), + .layer(TimeoutLayer::new(DEFAULT_TIMEOUT)), ) } diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index b2f37880c..c24797c4a 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -10,6 +10,7 @@ use axum::routing::get; use axum::{BoxError, Router}; use axum_client_ip::SecureClientIpSource; use hyper::{Request, StatusCode}; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; use tower_http::compression::CompressionLayer; @@ -22,8 +23,6 @@ use super::handlers::{announce, health_check, scrape}; use crate::core::Tracker; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; -const TIMEOUT: Duration = Duration::from_secs(5); - /// It adds the routes to the router. /// /// > **NOTICE**: it's added a layer to get the client IP from the connection @@ -80,6 +79,6 @@ pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { // this middleware goes above `TimeoutLayer` because it will receive // errors returned by `TimeoutLayer` .layer(HandleErrorLayer::new(|_: BoxError| async { StatusCode::REQUEST_TIMEOUT })) - .layer(TimeoutLayer::new(TIMEOUT)), + .layer(TimeoutLayer::new(DEFAULT_TIMEOUT)), ) } diff --git a/src/shared/bit_torrent/tracker/http/client/mod.rs b/src/shared/bit_torrent/tracker/http/client/mod.rs index f5b1b3310..4c70cd68b 100644 --- a/src/shared/bit_torrent/tracker/http/client/mod.rs +++ b/src/shared/bit_torrent/tracker/http/client/mod.rs @@ -2,18 +2,30 @@ pub mod requests; pub mod responses; use std::net::IpAddr; +use std::sync::Arc; +use std::time::Duration; -use anyhow::{anyhow, Result}; -use requests::announce::{self, Query}; -use requests::scrape; -use reqwest::{Client as ReqwestClient, Response, Url}; +use hyper::StatusCode; +use requests::{announce, scrape}; +use reqwest::{Response, Url}; +use thiserror::Error; use crate::core::auth::Key; +#[derive(Debug, Clone, Error)] +pub enum Error { + #[error("Failed to Build a Http Client: {err:?}")] + ClientBuildingError { err: Arc }, + #[error("Failed to get a response: {err:?}")] + ResponseError { err: Arc }, + #[error("Returned a non-success code: \"{code}\" with the response: \"{response:?}\"")] + UnsuccessfulResponse { code: StatusCode, response: Arc }, +} + /// HTTP Tracker Client pub struct Client { + client: reqwest::Client, base_url: Url, - reqwest: ReqwestClient, key: Option, } @@ -29,11 +41,15 @@ impl Client { /// # Errors /// /// This method fails if the client builder fails. - pub fn new(base_url: Url) -> Result { - let reqwest = reqwest::Client::builder().build()?; + pub fn new(base_url: Url, timeout: Duration) -> Result { + let client = reqwest::Client::builder() + .timeout(timeout) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; + Ok(Self { base_url, - reqwest, + client, key: None, }) } @@ -43,11 +59,16 @@ impl Client { /// # Errors /// /// This method fails if the client builder fails. - pub fn bind(base_url: Url, local_address: IpAddr) -> Result { - let reqwest = reqwest::Client::builder().local_address(local_address).build()?; + pub fn bind(base_url: Url, timeout: Duration, local_address: IpAddr) -> Result { + let client = reqwest::Client::builder() + .timeout(timeout) + .local_address(local_address) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; + Ok(Self { base_url, - reqwest, + client, key: None, }) } @@ -55,54 +76,106 @@ impl Client { /// # Errors /// /// This method fails if the client builder fails. - pub fn authenticated(base_url: Url, key: Key) -> Result { - let reqwest = reqwest::Client::builder().build()?; + pub fn authenticated(base_url: Url, timeout: Duration, key: Key) -> Result { + let client = reqwest::Client::builder() + .timeout(timeout) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; + Ok(Self { base_url, - reqwest, + client, key: Some(key), }) } /// # Errors - pub async fn announce(&self, query: &announce::Query) -> Result { - self.get(&self.build_announce_path_and_query(query)).await + /// + /// This method fails if the returned response was not successful + pub async fn announce(&self, query: &announce::Query) -> Result { + let response = self.get(&self.build_announce_path_and_query(query)).await?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } } /// # Errors - pub async fn scrape(&self, query: &scrape::Query) -> Result { - self.get(&self.build_scrape_path_and_query(query)).await + /// + /// This method fails if the returned response was not successful + pub async fn scrape(&self, query: &scrape::Query) -> Result { + let response = self.get(&self.build_scrape_path_and_query(query)).await?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } } /// # Errors - pub async fn announce_with_header(&self, query: &Query, key: &str, value: &str) -> Result { - self.get_with_header(&self.build_announce_path_and_query(query), key, value) - .await + /// + /// This method fails if the returned response was not successful + pub async fn announce_with_header(&self, query: &announce::Query, key: &str, value: &str) -> Result { + let response = self + .get_with_header(&self.build_announce_path_and_query(query), key, value) + .await?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } } /// # Errors - pub async fn health_check(&self) -> Result { - self.get(&self.build_path("health_check")).await + /// + /// This method fails if the returned response was not successful + pub async fn health_check(&self) -> Result { + let response = self.get(&self.build_path("health_check")).await?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } } /// # Errors /// /// This method fails if there was an error while sending request. - pub async fn get(&self, path: &str) -> Result { - match self.reqwest.get(self.build_url(path)).send().await { - Ok(response) => Ok(response), - Err(err) => Err(anyhow!("{err}")), - } + pub async fn get(&self, path: &str) -> Result { + self.client + .get(self.build_url(path)) + .send() + .await + .map_err(|e| Error::ResponseError { err: e.into() }) } /// # Errors /// /// This method fails if there was an error while sending request. - pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Result { - match self.reqwest.get(self.build_url(path)).header(key, value).send().await { - Ok(response) => Ok(response), - Err(err) => Err(anyhow!("{err}")), - } + pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Result { + self.client + .get(self.build_url(path)) + .header(key, value) + .send() + .await + .map_err(|e| Error::ResponseError { err: e.into() }) } fn build_announce_path_and_query(&self, query: &announce::Query) -> String { diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs index dce596e08..edb8adc85 100644 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ b/src/shared/bit_torrent/tracker/udp/client.rs @@ -1,24 +1,20 @@ use core::result::Result::{Err, Ok}; use std::io::Cursor; -use std::net::SocketAddr; +use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; use std::time::Duration; -use anyhow::{anyhow, Context, Result}; use aquatic_udp_protocol::{ConnectRequest, Request, Response, TransactionId}; use tokio::net::UdpSocket; use tokio::time; -use tracing::debug; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; use zerocopy::network_endian::I32; -use crate::shared::bit_torrent::tracker::udp::{source_address, MAX_PACKET_SIZE}; +use super::Error; +use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; pub const UDP_CLIENT_LOG_TARGET: &str = "UDP CLIENT"; -/// Default timeout for sending and receiving packets. And waiting for sockets -/// to be readable and writable. -pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5); - #[allow(clippy::module_name_repetitions)] #[derive(Debug)] pub struct UdpClient { @@ -30,51 +26,94 @@ pub struct UdpClient { } impl UdpClient { + /// Creates a new `UdpClient` bound to the default port and ipv6 address + /// /// # Errors /// - /// Will return error if the local address can't be bound. + /// Will return error if unable to bind to any port or ip address. /// - pub async fn bind(local_address: &str) -> Result { - let socket_addr = local_address - .parse::() - .context(format!("{local_address} is not a valid socket address"))?; - - let socket = match time::timeout(DEFAULT_TIMEOUT, UdpSocket::bind(socket_addr)).await { - Ok(bind_result) => match bind_result { - Ok(socket) => { - debug!("Bound to socket: {socket_addr}"); - Ok(socket) - } - Err(e) => Err(anyhow!("Failed to bind to socket: {socket_addr}, error: {e:?}")), - }, - Err(e) => Err(anyhow!("Timeout waiting to bind to socket: {socket_addr}, error: {e:?}")), - }?; + async fn bound_to_default_ipv4(timeout: Duration) -> Result { + let addr = SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0); + + Self::bound(addr, timeout).await + } + + /// Creates a new `UdpClient` bound to the default port and ipv6 address + /// + /// # Errors + /// + /// Will return error if unable to bind to any port or ip address. + /// + async fn bound_to_default_ipv6(timeout: Duration) -> Result { + let addr = SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), 0); + + Self::bound(addr, timeout).await + } + + /// Creates a new `UdpClient` connected to a Udp server + /// + /// # Errors + /// + /// Will return any errors present in the call stack + /// + pub async fn connected(remote_addr: SocketAddr, timeout: Duration) -> Result { + let client = if remote_addr.is_ipv4() { + Self::bound_to_default_ipv4(timeout).await? + } else { + Self::bound_to_default_ipv6(timeout).await? + }; + + client.connect(remote_addr).await?; + Ok(client) + } + + /// Creates a `[UdpClient]` bound to a Socket. + /// + /// # Panics + /// + /// Panics if unable to get the `local_addr` of the bound socket. + /// + /// # Errors + /// + /// This function will return an error if the binding takes to long + /// or if there is an underlying OS error. + pub async fn bound(addr: SocketAddr, timeout: Duration) -> Result { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "binding to socket: {addr:?} ..."); + + let socket = time::timeout(timeout, UdpSocket::bind(addr)) + .await + .map_err(|_| Error::TimeoutWhileBindingToSocket { addr })? + .map_err(|e| Error::UnableToBindToSocket { err: e.into(), addr })?; + + let addr = socket.local_addr().expect("it should get the local address"); + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "bound to socket: {addr:?}."); let udp_client = Self { socket: Arc::new(socket), - timeout: DEFAULT_TIMEOUT, + timeout, }; + Ok(udp_client) } /// # Errors /// /// Will return error if can't connect to the socket. - pub async fn connect(&self, remote_address: &str) -> Result<()> { - let socket_addr = remote_address - .parse::() - .context(format!("{remote_address} is not a valid socket address"))?; - - match time::timeout(self.timeout, self.socket.connect(socket_addr)).await { - Ok(connect_result) => match connect_result { - Ok(()) => { - debug!("Connected to socket {socket_addr}"); - Ok(()) - } - Err(e) => Err(anyhow!("Failed to connect to socket {socket_addr}: {e:?}")), - }, - Err(e) => Err(anyhow!("Timeout waiting to connect to socket {socket_addr}, error: {e:?}")), - } + pub async fn connect(&self, remote_addr: SocketAddr) -> Result<(), Error> { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "connecting to remote: {remote_addr:?} ..."); + + let () = time::timeout(self.timeout, self.socket.connect(remote_addr)) + .await + .map_err(|_| Error::TimeoutWhileConnectingToRemote { remote_addr })? + .map_err(|e| Error::UnableToConnectToRemote { + err: e.into(), + remote_addr, + })?; + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "connected to remote: {remote_addr:?}."); + + Ok(()) } /// # Errors @@ -83,26 +122,25 @@ impl UdpClient { /// /// - Can't write to the socket. /// - Can't send data. - pub async fn send(&self, bytes: &[u8]) -> Result { - debug!(target: UDP_CLIENT_LOG_TARGET, "sending {bytes:?} ..."); - - match time::timeout(self.timeout, self.socket.writable()).await { - Ok(writable_result) => { - match writable_result { - Ok(()) => (), - Err(e) => return Err(anyhow!("IO error waiting for the socket to become readable: {e:?}")), - }; - } - Err(e) => return Err(anyhow!("Timeout waiting for the socket to become readable: {e:?}")), - }; + pub async fn send(&self, bytes: &[u8]) -> Result { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "sending {bytes:?} ..."); - match time::timeout(self.timeout, self.socket.send(bytes)).await { - Ok(send_result) => match send_result { - Ok(size) => Ok(size), - Err(e) => Err(anyhow!("IO error during send: {e:?}")), - }, - Err(e) => Err(anyhow!("Send operation timed out: {e:?}")), - } + let () = time::timeout(self.timeout, self.socket.writable()) + .await + .map_err(|_| Error::TimeoutWaitForWriteableSocket)? + .map_err(|e| Error::UnableToGetWritableSocket { err: e.into() })?; + + let sent_bytes = time::timeout(self.timeout, self.socket.send(bytes)) + .await + .map_err(|_| Error::TimeoutWhileSendingData { data: bytes.to_vec() })? + .map_err(|e| Error::UnableToSendData { + err: e.into(), + data: bytes.to_vec(), + })?; + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "sent {sent_bytes} bytes to remote."); + + Ok(sent_bytes) } /// # Errors @@ -114,110 +152,76 @@ impl UdpClient { /// /// # Panics /// - pub async fn receive(&self) -> Result> { - let mut response_buffer = [0u8; MAX_PACKET_SIZE]; + pub async fn receive(&self) -> Result, Error> { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "receiving ..."); - debug!(target: UDP_CLIENT_LOG_TARGET, "receiving ..."); + let mut buffer = [0u8; MAX_PACKET_SIZE]; - match time::timeout(self.timeout, self.socket.readable()).await { - Ok(readable_result) => { - match readable_result { - Ok(()) => (), - Err(e) => return Err(anyhow!("IO error waiting for the socket to become readable: {e:?}")), - }; - } - Err(e) => return Err(anyhow!("Timeout waiting for the socket to become readable: {e:?}")), - }; + let () = time::timeout(self.timeout, self.socket.readable()) + .await + .map_err(|_| Error::TimeoutWaitForReadableSocket)? + .map_err(|e| Error::UnableToGetReadableSocket { err: e.into() })?; - let size = match time::timeout(self.timeout, self.socket.recv(&mut response_buffer)).await { - Ok(recv_result) => match recv_result { - Ok(size) => Ok(size), - Err(e) => Err(anyhow!("IO error during send: {e:?}")), - }, - Err(e) => Err(anyhow!("Receive operation timed out: {e:?}")), - }?; + let received_bytes = time::timeout(self.timeout, self.socket.recv(&mut buffer)) + .await + .map_err(|_| Error::TimeoutWhileReceivingData)? + .map_err(|e| Error::UnableToReceivingData { err: e.into() })?; - let mut res: Vec = response_buffer.to_vec(); - Vec::truncate(&mut res, size); + let mut received: Vec = buffer.to_vec(); + Vec::truncate(&mut received, received_bytes); - debug!(target: UDP_CLIENT_LOG_TARGET, "{size} bytes received {res:?}"); + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "received {received_bytes} bytes: {received:?}"); - Ok(res) + Ok(received) } } -/// Creates a new `UdpClient` connected to a Udp server -/// -/// # Errors -/// -/// Will return any errors present in the call stack -/// -pub async fn new_udp_client_connected(remote_address: &str) -> Result { - let port = 0; // Let OS choose an unused port. - let client = UdpClient::bind(&source_address(port)).await?; - client.connect(remote_address).await?; - Ok(client) -} - #[allow(clippy::module_name_repetitions)] #[derive(Debug)] pub struct UdpTrackerClient { - pub udp_client: UdpClient, + pub client: UdpClient, } impl UdpTrackerClient { + /// Creates a new `UdpTrackerClient` connected to a Udp Tracker server + /// + /// # Errors + /// + /// If unable to connect to the remote address. + /// + pub async fn new(remote_addr: SocketAddr, timeout: Duration) -> Result { + let client = UdpClient::connected(remote_addr, timeout).await?; + Ok(UdpTrackerClient { client }) + } + /// # Errors /// /// Will return error if can't write request to bytes. - pub async fn send(&self, request: Request) -> Result { - debug!(target: UDP_CLIENT_LOG_TARGET, "send request {request:?}"); + pub async fn send(&self, request: Request) -> Result { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "sending request {request:?} ..."); // Write request into a buffer - let request_buffer = vec![0u8; MAX_PACKET_SIZE]; - let mut cursor = Cursor::new(request_buffer); - - let request_data_result = match request.write_bytes(&mut cursor) { - Ok(()) => { - #[allow(clippy::cast_possible_truncation)] - let position = cursor.position() as usize; - let inner_request_buffer = cursor.get_ref(); - // Return slice which contains written request data - Ok(&inner_request_buffer[..position]) - } - Err(e) => Err(anyhow!("could not write request to bytes: {e}.")), - }; + // todo: optimize the pre-allocated amount based upon request type. + let mut writer = Cursor::new(Vec::with_capacity(200)); + let () = request + .write_bytes(&mut writer) + .map_err(|e| Error::UnableToWriteDataFromRequest { err: e.into(), request })?; - let request_data = request_data_result?; - - self.udp_client.send(request_data).await + self.client.send(writer.get_ref()).await } /// # Errors /// /// Will return error if can't create response from the received payload (bytes buffer). - pub async fn receive(&self) -> Result { - let payload = self.udp_client.receive().await?; - - debug!(target: UDP_CLIENT_LOG_TARGET, "received {} bytes. Response {payload:?}", payload.len()); + pub async fn receive(&self) -> Result { + let response = self.client.receive().await?; - let response = Response::parse_bytes(&payload, true)?; + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "received {} bytes: {response:?}", response.len()); - Ok(response) + Response::parse_bytes(&response, true).map_err(|e| Error::UnableToParseResponse { err: e.into(), response }) } } -/// Creates a new `UdpTrackerClient` connected to a Udp Tracker server -/// -/// # Errors -/// -/// Will return any errors present in the call stack -/// -pub async fn new_udp_tracker_client_connected(remote_address: &str) -> Result { - let udp_client = new_udp_client_connected(remote_address).await?; - let udp_tracker_client = UdpTrackerClient { udp_client }; - Ok(udp_tracker_client) -} - /// Helper Function to Check if a UDP Service is Connectable /// /// # Panics @@ -226,10 +230,10 @@ pub async fn new_udp_tracker_client_connected(remote_address: &str) -> Result Result { - debug!("Checking Service (detail): {binding:?}."); +pub async fn check(remote_addr: &SocketAddr) -> Result { + tracing::debug!("Checking Service (detail): {remote_addr:?}."); - match new_udp_tracker_client_connected(binding.to_string().as_str()).await { + match UdpTrackerClient::new(*remote_addr, DEFAULT_TIMEOUT).await { Ok(client) => { let connect_request = ConnectRequest { transaction_id: TransactionId(I32::new(123)), @@ -238,7 +242,7 @@ pub async fn check(binding: &SocketAddr) -> Result { // client.send() return usize, but doesn't use here match client.send(connect_request.into()).await { Ok(_) => (), - Err(e) => debug!("Error: {e:?}."), + Err(e) => tracing::debug!("Error: {e:?}."), }; let process = move |response| { diff --git a/src/shared/bit_torrent/tracker/udp/mod.rs b/src/shared/bit_torrent/tracker/udp/mod.rs index 9322ef045..b9d5f34f6 100644 --- a/src/shared/bit_torrent/tracker/udp/mod.rs +++ b/src/shared/bit_torrent/tracker/udp/mod.rs @@ -1,3 +1,10 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::Request; +use thiserror::Error; +use torrust_tracker_located_error::DynError; + pub mod client; /// The maximum number of bytes in a UDP packet. @@ -6,7 +13,56 @@ pub const MAX_PACKET_SIZE: usize = 1496; /// identify the protocol. pub const PROTOCOL_ID: i64 = 0x0417_2710_1980; -/// Generates the source address for the UDP client -fn source_address(port: u16) -> String { - format!("127.0.0.1:{port}") +#[derive(Debug, Clone, Error)] +pub enum Error { + #[error("Timeout while waiting for socket to bind: {addr:?}")] + TimeoutWhileBindingToSocket { addr: SocketAddr }, + + #[error("Failed to bind to socket: {addr:?}, with error: {err:?}")] + UnableToBindToSocket { err: Arc, addr: SocketAddr }, + + #[error("Timeout while waiting for connection to remote: {remote_addr:?}")] + TimeoutWhileConnectingToRemote { remote_addr: SocketAddr }, + + #[error("Failed to connect to remote: {remote_addr:?}, with error: {err:?}")] + UnableToConnectToRemote { + err: Arc, + remote_addr: SocketAddr, + }, + + #[error("Timeout while waiting for the socket to become writable.")] + TimeoutWaitForWriteableSocket, + + #[error("Failed to get writable socket: {err:?}")] + UnableToGetWritableSocket { err: Arc }, + + #[error("Timeout while trying to send data: {data:?}")] + TimeoutWhileSendingData { data: Vec }, + + #[error("Failed to send data: {data:?}, with error: {err:?}")] + UnableToSendData { err: Arc, data: Vec }, + + #[error("Timeout while waiting for the socket to become readable.")] + TimeoutWaitForReadableSocket, + + #[error("Failed to get readable socket: {err:?}")] + UnableToGetReadableSocket { err: Arc }, + + #[error("Timeout while trying to receive data.")] + TimeoutWhileReceivingData, + + #[error("Failed to receive data: {err:?}")] + UnableToReceivingData { err: Arc }, + + #[error("Failed to get data from request: {request:?}, with error: {err:?}")] + UnableToWriteDataFromRequest { err: Arc, request: Request }, + + #[error("Failed to parse response: {response:?}, with error: {err:?}")] + UnableToParseResponse { err: Arc, response: Vec }, +} + +impl From for DynError { + fn from(e: Error) -> Self { + Arc::new(Box::new(e)) + } } diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index b23b20907..e37ef7bf0 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -6,8 +6,9 @@ use core::panic; use aquatic_udp_protocol::{ConnectRequest, ConnectionId, Response, TransactionId}; -use torrust_tracker::shared::bit_torrent::tracker::udp::client::{new_udp_client_connected, UdpTrackerClient}; +use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; use torrust_tracker::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_error_response; @@ -40,17 +41,17 @@ async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrac async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_request() { let env = Started::new(&configuration::ephemeral().into()).await; - let client = match new_udp_client_connected(&env.bind_address().to_string()).await { + let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_client) => udp_client, Err(err) => panic!("{err}"), }; - match client.send(&empty_udp_request()).await { + match client.client.send(&empty_udp_request()).await { Ok(_) => (), Err(err) => panic!("{err}"), }; - let response = match client.receive().await { + let response = match client.client.receive().await { Ok(response) => response, Err(err) => panic!("{err}"), }; @@ -64,7 +65,8 @@ async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_req mod receiving_a_connection_request { use aquatic_udp_protocol::{ConnectRequest, TransactionId}; - use torrust_tracker::shared::bit_torrent::tracker::udp::client::new_udp_tracker_client_connected; + use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; + use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_connect_response; @@ -74,7 +76,7 @@ mod receiving_a_connection_request { async fn should_return_a_connect_response() { let env = Started::new(&configuration::ephemeral().into()).await; - let client = match new_udp_tracker_client_connected(&env.bind_address().to_string()).await { + let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_tracker_client) => udp_tracker_client, Err(err) => panic!("{err}"), }; @@ -106,7 +108,8 @@ mod receiving_an_announce_request { AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectionId, InfoHash, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, TransactionId, }; - use torrust_tracker::shared::bit_torrent::tracker::udp::client::{new_udp_tracker_client_connected, UdpTrackerClient}; + use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; + use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_ipv4_announce_response; @@ -129,7 +132,7 @@ mod receiving_an_announce_request { ip_address: Ipv4Addr::new(0, 0, 0, 0).into(), key: PeerKey::new(0i32), peers_wanted: NumberOfPeers(1i32.into()), - port: Port(client.udp_client.socket.local_addr().unwrap().port().into()), + port: Port(client.client.socket.local_addr().unwrap().port().into()), }; match client.send(announce_request.into()).await { @@ -151,7 +154,7 @@ mod receiving_an_announce_request { async fn should_return_an_announce_response() { let env = Started::new(&configuration::ephemeral().into()).await; - let client = match new_udp_tracker_client_connected(&env.bind_address().to_string()).await { + let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_tracker_client) => udp_tracker_client, Err(err) => panic!("{err}"), }; @@ -169,7 +172,7 @@ mod receiving_an_announce_request { async fn should_return_many_announce_response() { let env = Started::new(&configuration::ephemeral().into()).await; - let client = match new_udp_tracker_client_connected(&env.bind_address().to_string()).await { + let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_tracker_client) => udp_tracker_client, Err(err) => panic!("{err}"), }; @@ -189,7 +192,8 @@ mod receiving_an_announce_request { mod receiving_an_scrape_request { use aquatic_udp_protocol::{ConnectionId, InfoHash, ScrapeRequest, TransactionId}; - use torrust_tracker::shared::bit_torrent::tracker::udp::client::new_udp_tracker_client_connected; + use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; + use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; use crate::servers::udp::asserts::is_scrape_response; @@ -200,7 +204,7 @@ mod receiving_an_scrape_request { async fn should_return_a_scrape_response() { let env = Started::new(&configuration::ephemeral().into()).await; - let client = match new_udp_tracker_client_connected(&env.bind_address().to_string()).await { + let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_tracker_client) => udp_tracker_client, Err(err) => panic!("{err}"), }; @@ -211,12 +215,13 @@ mod receiving_an_scrape_request { // Full scrapes are not allowed you need to pass an array of info hashes otherwise // it will return "bad request" error with empty vector - let info_hashes = vec![InfoHash([0u8; 20])]; + + let empty_info_hash = vec![InfoHash([0u8; 20])]; let scrape_request = ScrapeRequest { connection_id: ConnectionId(connection_id.0), transaction_id: TransactionId::new(123i32), - info_hashes, + info_hashes: empty_info_hash, }; match client.send(scrape_request.into()).await { diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 2232cb0e0..c580c3558 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -7,8 +7,7 @@ use torrust_tracker::servers::registar::Registar; use torrust_tracker::servers::udp::server::spawner::Spawner; use torrust_tracker::servers::udp::server::states::{Running, Stopped}; use torrust_tracker::servers::udp::server::Server; -use torrust_tracker::shared::bit_torrent::tracker::udp::client::DEFAULT_TIMEOUT; -use torrust_tracker_configuration::{Configuration, UdpTracker}; +use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer; From 77c6954f733763a898daf7fa655d2ea2f2d896bb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 07:23:51 +0100 Subject: [PATCH 0409/1297] chore(deps): update dependencies ```s cargo update Updating crates.io index Locking 20 packages to latest compatible versions Updating bitflags v2.5.0 -> v2.6.0 Updating cc v1.0.99 -> v1.0.103 Updating clap v4.5.7 -> v4.5.8 Updating clap_builder v4.5.7 -> v4.5.8 Updating clap_derive v4.5.5 -> v4.5.8 Updating either v1.12.0 -> v1.13.0 Updating lazy_static v1.4.0 -> v1.5.0 Updating libloading v0.8.3 -> v0.8.4 Updating log v0.4.21 -> v0.4.22 Updating num-bigint v0.4.5 -> v0.4.6 Updating object v0.36.0 -> v0.36.1 Updating proc-macro2 v1.0.85 -> v1.0.86 Updating serde_bytes v0.11.14 -> v0.11.15 Updating serde_json v1.0.117 -> v1.0.119 Updating serde_with v3.8.1 -> v3.8.2 Updating serde_with_macros v3.8.1 -> v3.8.2 Updating subtle v2.5.0 -> v2.6.1 Updating syn v2.0.66 -> v2.0.68 Updating tinyvec v1.6.0 -> v1.6.1 Updating uuid v1.8.0 -> v1.9.1 ``` --- Cargo.lock | 156 ++++++++++++++++++++++++++--------------------------- 1 file changed, 78 insertions(+), 78 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4b833504e..f977949ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -356,7 +356,7 @@ checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -479,7 +479,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -555,7 +555,7 @@ version = "0.69.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a00dc851838a2120612785d195287475a3ac45514741da670b735818822129a0" dependencies = [ - "bitflags 2.5.0", + "bitflags 2.6.0", "cexpr", "clang-sys", "itertools 0.12.1", @@ -566,7 +566,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -577,9 +577,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" +checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" [[package]] name = "bitvec" @@ -635,7 +635,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", "syn_derive", ] @@ -738,9 +738,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.99" +version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96c51067fd44124faa7f870b4b1c969379ad32b2ba805aa959430ceaa384f695" +checksum = "2755ff20a1d93490d26ba33a6f092a38a508398a5320df5d4b3014fcccce9410" dependencies = [ "jobserver", "libc", @@ -821,9 +821,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.7" +version = "4.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5db83dced34638ad474f39f250d7fea9598bdd239eaced1bdf45d597da0f433f" +checksum = "84b3edb18336f4df585bc9aa31dd99c036dfa5dc5e9a2939a722a188f3a8970d" dependencies = [ "clap_builder", "clap_derive", @@ -831,9 +831,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.7" +version = "4.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7e204572485eb3fbf28f871612191521df159bc3e15a9f5064c66dba3a8c05f" +checksum = "c1c09dd5ada6c6c78075d6fd0da3f90d8080651e2d6cc8eb2f1aaa4034ced708" dependencies = [ "anstream", "anstyle", @@ -843,14 +843,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.5" +version = "4.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c780290ccf4fb26629baa7a1081e68ced113f1d3ec302fa5948f1c381ebf06c6" +checksum = "2bac35c6dafb060fd4d275d9a4ffae97917c13a6327903a8be2153cd964f7085" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -1077,7 +1077,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -1088,7 +1088,7 @@ checksum = "733cabb43482b1a1b53eee8583c2b9e8684d592215ea83efd305dd31bc2f0178" dependencies = [ "darling_core", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -1124,7 +1124,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -1135,7 +1135,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -1156,9 +1156,9 @@ checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" [[package]] name = "either" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dca9240753cf90908d7e4aac30f630662b02aebaa1b58a3cadabdb23385b58b" +checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" [[package]] name = "encoding_rs" @@ -1357,7 +1357,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -1369,7 +1369,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -1381,7 +1381,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -1474,7 +1474,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -1951,9 +1951,9 @@ dependencies = [ [[package]] name = "lazy_static" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "lazycell" @@ -2042,9 +2042,9 @@ checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "libloading" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c2a198fb6b0eada2a8df47933734e6d35d350665a33a3593d7164fa52c75c19" +checksum = "e310b3a6b5907f99202fcdb4960ff45b93735d7c7d96b760fcff8db2dc0e103d" dependencies = [ "cfg-if", "windows-targets 0.52.5", @@ -2108,9 +2108,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.21" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" dependencies = [ "value-bag", ] @@ -2192,7 +2192,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -2243,7 +2243,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", "termcolor", "thiserror", ] @@ -2257,7 +2257,7 @@ dependencies = [ "base64 0.21.7", "bigdecimal", "bindgen", - "bitflags 2.5.0", + "bitflags 2.6.0", "bitvec", "byteorder", "bytes", @@ -2365,9 +2365,9 @@ dependencies = [ [[package]] name = "num-bigint" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c165a9ab64cf766f73521c0dd2cfdff64f488b8f0b3e621face3462d3db536d7" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" dependencies = [ "num-integer", "num-traits", @@ -2409,9 +2409,9 @@ dependencies = [ [[package]] name = "object" -version = "0.36.0" +version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "576dfe1fc8f9df304abb159d767a29d0476f7750fbf8aa7ad07816004a207434" +checksum = "081b846d1d56ddfc18fdf1a922e4f6e07a11768ea1b92dec44e42b72712ccfce" dependencies = [ "memchr", ] @@ -2434,7 +2434,7 @@ version = "0.10.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f" dependencies = [ - "bitflags 2.5.0", + "bitflags 2.6.0", "cfg-if", "foreign-types", "libc", @@ -2451,7 +2451,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -2527,7 +2527,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -2601,7 +2601,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -2775,9 +2775,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.85" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22244ce15aa966053a896d1accb3a6e68469b97c7f33f284b99f0d576879fc23" +checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" dependencies = [ "unicode-ident", ] @@ -2790,7 +2790,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", "version_check", "yansi", ] @@ -2929,7 +2929,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c82cf8cff14456045f55ec4241383baeff27af886adb72ffb2162f99911de0fd" dependencies = [ - "bitflags 2.5.0", + "bitflags 2.6.0", ] [[package]] @@ -3098,7 +3098,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.66", + "syn 2.0.68", "unicode-ident", ] @@ -3108,7 +3108,7 @@ version = "0.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b838eba278d213a8beaf485bd313fd580ca4505a00d5871caeb1457c55322cae" dependencies = [ - "bitflags 2.5.0", + "bitflags 2.6.0", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -3173,7 +3173,7 @@ version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ - "bitflags 2.5.0", + "bitflags 2.6.0", "errno", "libc", "linux-raw-sys 0.4.14", @@ -3315,7 +3315,7 @@ version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c627723fd09706bacdb5cf41499e95098555af3c3c29d014dc3c458ef6be11c0" dependencies = [ - "bitflags 2.5.0", + "bitflags 2.6.0", "core-foundation", "core-foundation-sys", "libc", @@ -3359,9 +3359,9 @@ dependencies = [ [[package]] name = "serde_bytes" -version = "0.11.14" +version = "0.11.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b8497c313fd43ab992087548117643f6fcd935cbf36f176ffda0aacf9591734" +checksum = "387cc504cb06bb40a96c8e04e951fe01854cf6bc921053c954e4a606d9675c6a" dependencies = [ "serde", ] @@ -3374,7 +3374,7 @@ checksum = "500cbc0ebeb6f46627f50f3f5811ccf6bf00643be300b4c3eabc0ef55dc5b5ba" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -3392,9 +3392,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.117" +version = "1.0.119" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "455182ea6142b14f93f4bc5320a2b31c1f266b66a4a5c858b013302a5d8cbfc3" +checksum = "e8eddb61f0697cc3989c5d64b452f5488e2b8a60fd7d5076a3045076ffef8cb0" dependencies = [ "indexmap 2.2.6", "itoa", @@ -3420,7 +3420,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -3446,9 +3446,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.8.1" +version = "3.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ad483d2ab0149d5a5ebcd9972a3852711e0153d863bf5a5d0391d28883c4a20" +checksum = "079f3a42cd87588d924ed95b533f8d30a483388c4e400ab736a7058e34f16169" dependencies = [ "base64 0.22.1", "chrono", @@ -3464,14 +3464,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.8.1" +version = "3.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65569b702f41443e8bc8bbb1c5779bd0450bbe723b56198980e80ec45780bce2" +checksum = "bc03aad67c1d26b7de277d51c86892e7d9a0110a2fe44bf6b26cc569fba302d6" dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -3597,9 +3597,9 @@ dependencies = [ [[package]] name = "subtle" -version = "2.5.0" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" @@ -3614,9 +3614,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.66" +version = "2.0.68" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c42f3f41a2de00b01c0aaad383c5a45241efc8b2d1eda5661812fda5f3cdcff5" +checksum = "901fa70d88b9d6c98022e23b4136f9f3e54e4662c3bc1bd1d84a42a9a0f0c1e9" dependencies = [ "proc-macro2", "quote", @@ -3632,7 +3632,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -3735,7 +3735,7 @@ checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -3791,9 +3791,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.6.0" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +checksum = "c55115c6fbe2d2bef26eb09ad74bde02d8255476fc0c7b515ef09fbb35742d82" dependencies = [ "tinyvec_macros", ] @@ -3830,7 +3830,7 @@ checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -4097,7 +4097,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ "async-compression", - "bitflags 2.5.0", + "bitflags 2.6.0", "bytes", "futures-core", "http", @@ -4155,7 +4155,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] @@ -4285,9 +4285,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.8.0" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a183cf7feeba97b4dd1c0d46788634f6221d87fa961b305bed08c851829efcc0" +checksum = "5de17fd2f7da591098415cff336e12965a28061ddace43b59cb3c430179c9439" dependencies = [ "getrandom", "rand", @@ -4369,7 +4369,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", "wasm-bindgen-shared", ] @@ -4403,7 +4403,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4664,7 +4664,7 @@ checksum = "15e934569e47891f7d9411f1a451d947a60e000ab3bd24fbb970f000387d1b3b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.66", + "syn 2.0.68", ] [[package]] From daeb7cc7756a83657e40121785f2525319be37e1 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 1 Jul 2024 09:09:37 +0200 Subject: [PATCH 0410/1297] ci: coverage workflow pre-build fix --- .github/workflows/coverage.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 4dc104242..28c1be6d0 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -61,11 +61,11 @@ jobs: - id: build name: Pre-build Main Project - run: cargo build --jobs 2 + run: cargo build --workspace --all-targets --all-features --jobs 2 - id: build_tests name: Pre-build Tests - run: cargo build --tests --jobs 2 + run: cargo build --workspace --all-targets --all-features --tests --jobs 2 - id: test name: Run Unit Tests From 6495a4c1458660d1709b9668ea7dac1ca4319abd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 28 Jun 2024 11:11:50 +0100 Subject: [PATCH 0411/1297] docs: [#918] add comments to the UDP server --- src/servers/udp/server/launcher.rs | 38 +++--- src/servers/udp/server/request_buffer.rs | 153 ++++++++++++++--------- 2 files changed, 112 insertions(+), 79 deletions(-) diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index db448c2ff..bb7c7d70f 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -103,7 +103,7 @@ impl Launcher { } async fn run_udp_server_main(mut receiver: Receiver, tracker: Arc) { - let reqs = &mut ActiveRequests::default(); + let active_requests = &mut ActiveRequests::default(); let addr = receiver.bound_socket_address(); let local_addr = format!("udp://{addr}"); @@ -127,27 +127,18 @@ impl Launcher { } }; - /* code-review: - - Does it make sense to spawn a new request processor task when - the ActiveRequests buffer is full? - - We could store the UDP request in a secondary buffer and wait - until active tasks are finished. When a active request is finished - we can move a new UDP request from the pending to process requests - buffer to the active requests buffer. - - This forces us to define an explicit timeout for active requests. - - In the current solution the timeout is dynamic, it depends on - the system load. With high load we can remove tasks without - giving them enough time to be processed. With low load we could - keep processing running longer than a reasonable time for - the client to receive the response. - - */ - - let abort_handle = + // We spawn the new task even if there active requests buffer is + // full. This could seem counterintuitive because we are accepting + // more request and consuming more memory even if the server is + // already busy. However, we "force_push" the new tasks in the + // buffer. That means, in the worst scenario we will abort a + // running task to make place for the new task. + // + // Once concern could be to reach an starvation point were we + // are only adding and removing tasks without given them the + // chance to finish. However, the buffer is yielding before + // aborting one tasks, giving it the chance to finish. + let abort_handle: tokio::task::AbortHandle = tokio::task::spawn(Launcher::process_request(req, tracker.clone(), receiver.bound_socket.clone())) .abort_handle(); @@ -155,9 +146,10 @@ impl Launcher { continue; } - reqs.force_push(abort_handle, &local_addr).await; + active_requests.force_push(abort_handle, &local_addr).await; } else { tokio::task::yield_now().await; + // the request iterator returned `None`. tracing::error!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server breaking: (ran dry, should not happen in production!)"); break; diff --git a/src/servers/udp/server/request_buffer.rs b/src/servers/udp/server/request_buffer.rs index c1d4f2696..b3a481b60 100644 --- a/src/servers/udp/server/request_buffer.rs +++ b/src/servers/udp/server/request_buffer.rs @@ -4,10 +4,15 @@ use tokio::task::AbortHandle; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; -/// Ring-Buffer of Active Requests +/// A ring buffer for managing active UDP request abort handles. +/// +/// The `ActiveRequests` struct maintains a fixed-size ring buffer of abort +/// handles for UDP request processor tasks. It ensures that at most 50 requests +/// are handled concurrently, and provides mechanisms to handle buffer overflow +/// by removing finished or oldest unfinished tasks. #[derive(Default)] pub struct ActiveRequests { - rb: StaticRb, // the number of requests we handle at the same time. + rb: StaticRb, // The number of requests handled simultaneously. } impl std::fmt::Debug for ActiveRequests { @@ -29,67 +34,103 @@ impl Drop for ActiveRequests { } impl ActiveRequests { - /// It inserts the abort handle for the UDP request processor tasks. + /// Inserts an abort handle for a UDP request processor task. /// - /// If there is no room for the new task, it tries to make place: + /// If the buffer is full, this method attempts to make space by: /// - /// - Firstly, removing finished tasks. - /// - Secondly, removing the oldest unfinished tasks. + /// 1. Removing finished tasks. + /// 2. Removing the oldest unfinished task if no finished tasks are found. /// /// # Panics /// - /// Will panics if it can't make space for the new handle. + /// This method will panic if it cannot make space for adding a new handle. + /// + /// # Arguments + /// + /// * `abort_handle` - The `AbortHandle` for the UDP request processor task. + /// * `local_addr` - A string slice representing the local address for logging. pub async fn force_push(&mut self, abort_handle: AbortHandle, local_addr: &str) { - // fill buffer with requests - let Err(abort_handle) = self.rb.try_push(abort_handle) else { - return; - }; - - let mut finished: u64 = 0; - let mut unfinished_task = None; - - // buffer is full.. lets make some space. - for h in self.rb.pop_iter() { - // remove some finished tasks - if h.is_finished() { - finished += 1; - continue; + // Attempt to add the new handle to the buffer. + match self.rb.try_push(abort_handle) { + Ok(()) => { + // Successfully added the task, no further action needed. } - - // task is unfinished.. give it another chance. - tokio::task::yield_now().await; - - // if now finished, we continue. - if h.is_finished() { - finished += 1; - continue; + Err(abort_handle) => { + // Buffer is full, attempt to make space. + + let mut finished: u64 = 0; + let mut unfinished_task = None; + + for removed_abort_handle in self.rb.pop_iter() { + // We found a finished tasks ... increase the counter and + // continue searching for more and ... + if removed_abort_handle.is_finished() { + finished += 1; + continue; + } + + // The current removed tasks is not finished. + + // Give it a second chance to finish. + tokio::task::yield_now().await; + + // Recheck if it finished ... increase the counter and + // continue searching for more and ... + if removed_abort_handle.is_finished() { + finished += 1; + continue; + } + + // At this point we found a "definitive" unfinished task. + + // Log unfinished task. + tracing::debug!( + target: UDP_TRACKER_LOG_TARGET, + local_addr, + removed_count = finished, + "Udp::run_udp_server::loop (got unfinished task)" + ); + + // If no finished tasks were found, abort the current + // unfinished task. + if finished == 0 { + // We make place aborting this task. + removed_abort_handle.abort(); + + tracing::warn!( + target: UDP_TRACKER_LOG_TARGET, + local_addr, + "Udp::run_udp_server::loop aborting request: (no finished tasks)" + ); + + break; + } + + // At this point we found at least one finished task, but the + // current one is not finished and it was removed from the + // buffer, so we need to re-insert in in the buffer. + + // Save the unfinished task for re-entry. + unfinished_task = Some(removed_abort_handle); + } + + // After this point there can't be a race condition because only + // one thread owns the active buffer. There is no way for the + // buffer to be full again. That means the "expects" should + // never happen. + + // Reinsert the unfinished task if any. + if let Some(h) = unfinished_task { + self.rb.try_push(h).expect("it was previously inserted"); + } + + // Insert the new task, ensuring there's space. + if !abort_handle.is_finished() { + self.rb + .try_push(abort_handle) + .expect("it should remove at least one element."); + } } - - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, removed_count = finished, "Udp::run_udp_server::loop (got unfinished task)"); - - if finished == 0 { - // we have _no_ finished tasks.. will abort the unfinished task to make space... - h.abort(); - - tracing::warn!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop aborting request: (no finished tasks)"); - - break; - } - - // we have space, return unfinished task for re-entry. - unfinished_task = Some(h); - } - - // re-insert the previous unfinished task. - if let Some(h) = unfinished_task { - self.rb.try_push(h).expect("it was previously inserted"); - } - - // insert the new task. - if !abort_handle.is_finished() { - self.rb - .try_push(abort_handle) - .expect("it should remove at least one element."); - } + }; } } From d1c2d15c7050ff75f04e026652b429077c8c2ace Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Fri, 28 Jun 2024 16:42:15 +0100 Subject: [PATCH 0412/1297] fix: [#918] revision for UDP active reqeust buffer comments --- src/servers/udp/server/request_buffer.rs | 30 ++++++++++++++---------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/servers/udp/server/request_buffer.rs b/src/servers/udp/server/request_buffer.rs index b3a481b60..ffbd9565d 100644 --- a/src/servers/udp/server/request_buffer.rs +++ b/src/servers/udp/server/request_buffer.rs @@ -49,22 +49,22 @@ impl ActiveRequests { /// /// * `abort_handle` - The `AbortHandle` for the UDP request processor task. /// * `local_addr` - A string slice representing the local address for logging. - pub async fn force_push(&mut self, abort_handle: AbortHandle, local_addr: &str) { + pub async fn force_push(&mut self, new_task: AbortHandle, local_addr: &str) { // Attempt to add the new handle to the buffer. - match self.rb.try_push(abort_handle) { + match self.rb.try_push(new_task) { Ok(()) => { // Successfully added the task, no further action needed. } - Err(abort_handle) => { + Err(new_task) => { // Buffer is full, attempt to make space. let mut finished: u64 = 0; let mut unfinished_task = None; - for removed_abort_handle in self.rb.pop_iter() { + for old_task in self.rb.pop_iter() { // We found a finished tasks ... increase the counter and // continue searching for more and ... - if removed_abort_handle.is_finished() { + if old_task.is_finished() { finished += 1; continue; } @@ -76,7 +76,7 @@ impl ActiveRequests { // Recheck if it finished ... increase the counter and // continue searching for more and ... - if removed_abort_handle.is_finished() { + if old_task.is_finished() { finished += 1; continue; } @@ -95,7 +95,7 @@ impl ActiveRequests { // unfinished task. if finished == 0 { // We make place aborting this task. - removed_abort_handle.abort(); + old_task.abort(); tracing::warn!( target: UDP_TRACKER_LOG_TARGET, @@ -111,7 +111,7 @@ impl ActiveRequests { // buffer, so we need to re-insert in in the buffer. // Save the unfinished task for re-entry. - unfinished_task = Some(removed_abort_handle); + unfinished_task = Some(old_task); } // After this point there can't be a race condition because only @@ -124,11 +124,15 @@ impl ActiveRequests { self.rb.try_push(h).expect("it was previously inserted"); } - // Insert the new task, ensuring there's space. - if !abort_handle.is_finished() { - self.rb - .try_push(abort_handle) - .expect("it should remove at least one element."); + // Insert the new task. + // + // Notice that space has already been made for this new task in + // the buffer. One or many old task have already been finished + // or yielded, freeing space in the buffer. Or a single + // unfinished task has been aborted to make space for this new + // task. + if !new_task.is_finished() { + self.rb.try_push(new_task).expect("it should have space for this new task."); } } }; From 2186809608de314d915aba8c5738a4ecb40fd10c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 10:26:02 +0100 Subject: [PATCH 0413/1297] refactor: [#932] sort config core section fields When you format a toml file with a linter it sorts the keys alphabetically. It's good to have the same order in the code. It's also a common practice for JSON. This helps to make serialization deterministic. --- packages/configuration/src/v1/core.rs | 75 +++++++++++++-------------- 1 file changed, 37 insertions(+), 38 deletions(-) diff --git a/packages/configuration/src/v1/core.rs b/packages/configuration/src/v1/core.rs index 49fdf2a80..31da85915 100644 --- a/packages/configuration/src/v1/core.rs +++ b/packages/configuration/src/v1/core.rs @@ -8,27 +8,6 @@ use crate::{AnnouncePolicy, TrackerPolicy}; #[allow(clippy::struct_excessive_bools)] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct Core { - /// Tracker mode. See [`TrackerMode`] for more information. - #[serde(default = "Core::default_mode")] - pub mode: TrackerMode, - - /// 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. - /// Refer to the [`Tracker`](https://docs.rs/torrust-tracker) for more - /// information about the collected metrics. - #[serde(default = "Core::default_tracker_usage_statistics")] - pub tracker_usage_statistics: bool, - - /// Interval in seconds that the cleanup job will run to remove inactive - /// peers from the torrent peer list. - #[serde(default = "Core::default_inactive_peer_cleanup_interval")] - pub inactive_peer_cleanup_interval: u64, - - // Tracker policy configuration. - #[serde(default = "Core::default_tracker_policy")] - pub tracker_policy: TrackerPolicy, - // Announce policy configuration. #[serde(default = "Core::default_announce_policy")] pub announce_policy: AnnouncePolicy, @@ -37,51 +16,71 @@ pub struct Core { #[serde(default = "Core::default_database")] pub database: Database, + /// Interval in seconds that the cleanup job will run to remove inactive + /// peers from the torrent peer list. + #[serde(default = "Core::default_inactive_peer_cleanup_interval")] + pub inactive_peer_cleanup_interval: u64, + + /// Tracker mode. See [`TrackerMode`] for more information. + #[serde(default = "Core::default_mode")] + pub mode: TrackerMode, + // Network configuration. #[serde(default = "Core::default_network")] pub net: Network, + + // Tracker policy configuration. + #[serde(default = "Core::default_tracker_policy")] + pub tracker_policy: TrackerPolicy, + + /// 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. + /// Refer to the [`Tracker`](https://docs.rs/torrust-tracker) for more + /// information about the collected metrics. + #[serde(default = "Core::default_tracker_usage_statistics")] + pub tracker_usage_statistics: bool, } impl Default for Core { fn default() -> Self { Self { - mode: Self::default_mode(), - tracker_usage_statistics: Self::default_tracker_usage_statistics(), - inactive_peer_cleanup_interval: Self::default_inactive_peer_cleanup_interval(), - tracker_policy: Self::default_tracker_policy(), announce_policy: Self::default_announce_policy(), database: Self::default_database(), + inactive_peer_cleanup_interval: Self::default_inactive_peer_cleanup_interval(), + mode: Self::default_mode(), net: Self::default_network(), + tracker_policy: Self::default_tracker_policy(), + tracker_usage_statistics: Self::default_tracker_usage_statistics(), } } } impl Core { - fn default_mode() -> TrackerMode { - TrackerMode::Public + fn default_announce_policy() -> AnnouncePolicy { + AnnouncePolicy::default() } - fn default_tracker_usage_statistics() -> bool { - true + fn default_database() -> Database { + Database::default() } fn default_inactive_peer_cleanup_interval() -> u64 { 600 } - fn default_tracker_policy() -> TrackerPolicy { - TrackerPolicy::default() + fn default_mode() -> TrackerMode { + TrackerMode::Public } - fn default_announce_policy() -> AnnouncePolicy { - AnnouncePolicy::default() + fn default_network() -> Network { + Network::default() } - fn default_database() -> Database { - Database::default() + fn default_tracker_policy() -> TrackerPolicy { + TrackerPolicy::default() } - - fn default_network() -> Network { - Network::default() + fn default_tracker_usage_statistics() -> bool { + true } } From f5d8dc6679e349578d69ed56251f30cc7f23f976 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 10:40:08 +0100 Subject: [PATCH 0414/1297] refactor: [#932] WIP. Add new core config options: private and listed --- packages/configuration/src/v1/core.rs | 18 ++++++++++++++++++ packages/configuration/src/v1/mod.rs | 4 +++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/packages/configuration/src/v1/core.rs b/packages/configuration/src/v1/core.rs index 31da85915..9f3af36b6 100644 --- a/packages/configuration/src/v1/core.rs +++ b/packages/configuration/src/v1/core.rs @@ -21,6 +21,10 @@ pub struct Core { #[serde(default = "Core::default_inactive_peer_cleanup_interval")] pub inactive_peer_cleanup_interval: u64, + // Whe `true` only approved torrents can be announced in the tracker. + #[serde(default = "Core::default_listed")] + pub listed: bool, + /// Tracker mode. See [`TrackerMode`] for more information. #[serde(default = "Core::default_mode")] pub mode: TrackerMode, @@ -29,6 +33,10 @@ pub struct Core { #[serde(default = "Core::default_network")] pub net: Network, + // Whe `true` clients require a key to connect and use the tracker. + #[serde(default = "Core::default_private")] + pub private: bool, + // Tracker policy configuration. #[serde(default = "Core::default_tracker_policy")] pub tracker_policy: TrackerPolicy, @@ -48,8 +56,10 @@ impl Default for Core { announce_policy: Self::default_announce_policy(), database: Self::default_database(), inactive_peer_cleanup_interval: Self::default_inactive_peer_cleanup_interval(), + listed: Self::default_listed(), mode: Self::default_mode(), net: Self::default_network(), + private: Self::default_private(), tracker_policy: Self::default_tracker_policy(), tracker_usage_statistics: Self::default_tracker_usage_statistics(), } @@ -69,6 +79,10 @@ impl Core { 600 } + fn default_listed() -> bool { + false + } + fn default_mode() -> TrackerMode { TrackerMode::Public } @@ -77,6 +91,10 @@ impl Core { Network::default() } + fn default_private() -> bool { + false + } + fn default_tracker_policy() -> TrackerPolicy { TrackerPolicy::default() } diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 546f55b6e..080edde70 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -366,8 +366,10 @@ mod tests { [core] mode = "public" - tracker_usage_statistics = true inactive_peer_cleanup_interval = 600 + listed = false + private = false + tracker_usage_statistics = true [core.tracker_policy] max_peer_timeout = 900 From ca31c835ed08503f89c8470eddcc84381847e959 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 11:22:06 +0100 Subject: [PATCH 0415/1297] feat: [#932] replace `mode` core config option with `private` and `listed` flags From: ```toml [core] mode = "public" tracker_usage_statistics = true inactive_peer_cleanup_interval = 600 ``` To: ```toml [core] inactive_peer_cleanup_interval = 600 listed = false private = false tracker_usage_statistics = true ``` --- Cargo.lock | 1 - Cargo.toml | 4 +- packages/configuration/src/v1/core.rs | 14 +---- packages/configuration/src/v1/mod.rs | 26 ++++---- packages/primitives/src/lib.rs | 69 ---------------------- packages/test-helpers/Cargo.toml | 1 - packages/test-helpers/src/configuration.rs | 18 +++--- src/app.rs | 6 +- src/bootstrap/jobs/http_tracker.rs | 4 +- src/bootstrap/jobs/tracker_apis.rs | 4 +- src/core/mod.rs | 41 ++++++------- src/lib.rs | 13 ++-- src/servers/apis/server.rs | 4 +- src/servers/http/server.rs | 4 +- src/servers/http/v1/handlers/announce.rs | 4 +- src/servers/http/v1/handlers/scrape.rs | 4 +- src/servers/http/v1/services/announce.rs | 2 +- src/servers/http/v1/services/scrape.rs | 2 +- src/servers/udp/handlers.rs | 6 +- src/servers/udp/server/mod.rs | 6 +- tests/servers/http/v1/contract.rs | 62 +++++++++---------- 21 files changed, 108 insertions(+), 187 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f977949ee..3a403332a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4054,7 +4054,6 @@ version = "3.0.0-alpha.12-develop" dependencies = [ "rand", "torrust-tracker-configuration", - "torrust-tracker-primitives", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index a65c2a74d..3eca9934d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -80,12 +80,12 @@ tower-http = { version = "0", features = ["compression-full", "cors", "propagate trace = "0" tracing = "0" tracing-subscriber = { version = "0.3.18", features = ["json"] } -url = {version = "2", features = ["serde"] } +url = { version = "2", features = ["serde"] } uuid = { version = "1", features = ["v4"] } zerocopy = "0.7.33" [package.metadata.cargo-machete] -ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_bytes"] +ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_bytes", "torrust-tracker-primitives"] [dev-dependencies] local-ip-address = "0" diff --git a/packages/configuration/src/v1/core.rs b/packages/configuration/src/v1/core.rs index 9f3af36b6..1f0a0f957 100644 --- a/packages/configuration/src/v1/core.rs +++ b/packages/configuration/src/v1/core.rs @@ -1,5 +1,4 @@ use serde::{Deserialize, Serialize}; -use torrust_tracker_primitives::TrackerMode; use super::network::Network; use crate::v1::database::Database; @@ -21,19 +20,15 @@ pub struct Core { #[serde(default = "Core::default_inactive_peer_cleanup_interval")] pub inactive_peer_cleanup_interval: u64, - // Whe `true` only approved torrents can be announced in the tracker. + // When `true` only approved torrents can be announced in the tracker. #[serde(default = "Core::default_listed")] pub listed: bool, - /// Tracker mode. See [`TrackerMode`] for more information. - #[serde(default = "Core::default_mode")] - pub mode: TrackerMode, - // Network configuration. #[serde(default = "Core::default_network")] pub net: Network, - // Whe `true` clients require a key to connect and use the tracker. + // When `true` clients require a key to connect and use the tracker. #[serde(default = "Core::default_private")] pub private: bool, @@ -57,7 +52,6 @@ impl Default for Core { database: Self::default_database(), inactive_peer_cleanup_interval: Self::default_inactive_peer_cleanup_interval(), listed: Self::default_listed(), - mode: Self::default_mode(), net: Self::default_network(), private: Self::default_private(), tracker_policy: Self::default_tracker_policy(), @@ -83,10 +77,6 @@ impl Core { false } - fn default_mode() -> TrackerMode { - TrackerMode::Public - } - fn default_network() -> Network { Network::default() } diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v1/mod.rs index 080edde70..c5e0f9f7a 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v1/mod.rs @@ -199,14 +199,10 @@ //! log_level = "info" //! //! [core] -//! mode = "public" -//! tracker_usage_statistics = true //! inactive_peer_cleanup_interval = 600 -//! -//! [core.tracker_policy] -//! max_peer_timeout = 900 -//! persistent_torrent_completed_stat = false -//! remove_peerless_torrents = true +//! listed = false +//! private = false +//! tracker_usage_statistics = true //! //! [core.announce_policy] //! interval = 120 @@ -220,6 +216,11 @@ //! external_ip = "0.0.0.0" //! on_reverse_proxy = false //! +//! [core.tracker_policy] +//! max_peer_timeout = 900 +//! persistent_torrent_completed_stat = false +//! remove_peerless_torrents = true +//! //! [http_api] //! bind_address = "127.0.0.1:1212" //! @@ -365,17 +366,11 @@ mod tests { log_level = "info" [core] - mode = "public" inactive_peer_cleanup_interval = 600 listed = false private = false tracker_usage_statistics = true - [core.tracker_policy] - max_peer_timeout = 900 - persistent_torrent_completed_stat = false - remove_peerless_torrents = true - [core.announce_policy] interval = 120 interval_min = 120 @@ -388,6 +383,11 @@ mod tests { external_ip = "0.0.0.0" on_reverse_proxy = false + [core.tracker_policy] + max_peer_timeout = 900 + persistent_torrent_completed_stat = false + remove_peerless_torrents = true + [health_check_api] bind_address = "127.0.0.1:1313" "# diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index 454635e8d..7ad1d35b4 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -5,8 +5,6 @@ //! by the tracker server crate, but also by other crates in the Torrust //! ecosystem. use std::collections::BTreeMap; -use std::fmt; -use std::str::FromStr; use std::time::Duration; use info_hash::InfoHash; @@ -64,70 +62,3 @@ pub enum DatabaseDriver { } pub type PersistentTorrents = BTreeMap; - -/// The mode the tracker will run in. -/// -/// Refer to [Torrust Tracker Configuration](https://docs.rs/torrust-tracker-configuration) -/// to know how to configure the tracker to run in each mode. -#[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 { - 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() - } -} diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 2f10c6a0f..4fed6bc42 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,4 +17,3 @@ version.workspace = true [dependencies] rand = "0" torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 646617b32..65d9d9144 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -3,7 +3,6 @@ use std::env; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, LogLevel, UdpTracker}; -use torrust_tracker_primitives::TrackerMode; use crate::random; @@ -86,40 +85,41 @@ pub fn ephemeral_without_reverse_proxy() -> Configuration { /// Ephemeral configuration with `public` mode. #[must_use] -pub fn ephemeral_mode_public() -> Configuration { +pub fn ephemeral_public() -> Configuration { let mut cfg = ephemeral(); - cfg.core.mode = TrackerMode::Public; + cfg.core.private = false; cfg } /// Ephemeral configuration with `private` mode. #[must_use] -pub fn ephemeral_mode_private() -> Configuration { +pub fn ephemeral_private() -> Configuration { let mut cfg = ephemeral(); - cfg.core.mode = TrackerMode::Private; + cfg.core.private = true; cfg } /// Ephemeral configuration with `listed` mode. #[must_use] -pub fn ephemeral_mode_whitelisted() -> Configuration { +pub fn ephemeral_listed() -> Configuration { let mut cfg = ephemeral(); - cfg.core.mode = TrackerMode::Listed; + cfg.core.listed = true; cfg } /// Ephemeral configuration with `private_listed` mode. #[must_use] -pub fn ephemeral_mode_private_whitelisted() -> Configuration { +pub fn ephemeral_private_and_listed() -> Configuration { let mut cfg = ephemeral(); - cfg.core.mode = TrackerMode::PrivateListed; + cfg.core.private = true; + cfg.core.listed = true; cfg } diff --git a/src/app.rs b/src/app.rs index f6a909002..2d70a6dde 100644 --- a/src/app.rs +++ b/src/app.rs @@ -51,7 +51,7 @@ pub async fn start(config: &Configuration, tracker: Arc) -> Vec) -> Vec>, - mode: TrackerMode, + private: bool, + listed: bool, policy: TrackerPolicy, keys: tokio::sync::RwLock>, whitelist: tokio::sync::RwLock>, @@ -558,12 +560,11 @@ impl Tracker { ) -> Result { let database = Arc::new(databases::driver::build(&config.database.driver, &config.database.path)?); - let mode = config.mode.clone(); - Ok(Tracker { //config, announce_policy: config.announce_policy, - mode, + private: config.private, + listed: config.listed, keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), torrents: Arc::default(), @@ -578,17 +579,17 @@ impl Tracker { /// Returns `true` is the tracker is in public mode. pub fn is_public(&self) -> bool { - self.mode == TrackerMode::Public + !self.private } /// Returns `true` is the tracker is in private mode. pub fn is_private(&self) -> bool { - self.mode == TrackerMode::Private || self.mode == TrackerMode::PrivateListed + self.private } /// Returns `true` is the tracker is in whitelisted mode. - pub fn is_whitelisted(&self) -> bool { - self.mode == TrackerMode::Listed || self.mode == TrackerMode::PrivateListed + pub fn is_listed(&self) -> bool { + self.listed } /// Returns `true` if the tracker requires authentication. @@ -869,7 +870,7 @@ impl Tracker { /// Will return an error if the tracker is running in `listed` mode /// and the infohash is not whitelisted. pub async fn authorize(&self, info_hash: &InfoHash) -> Result<(), Error> { - if !self.is_whitelisted() { + if !self.is_listed() { return Ok(()); } @@ -1028,15 +1029,15 @@ mod tests { use crate::shared::bit_torrent::info_hash::fixture::gen_seeded_infohash; fn public_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_mode_public()) + tracker_factory(&configuration::ephemeral_public()) } fn private_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_mode_private()) + tracker_factory(&configuration::ephemeral_private()) } fn whitelisted_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_mode_whitelisted()) + tracker_factory(&configuration::ephemeral_listed()) } pub fn tracker_persisting_torrents_in_database() -> Tracker { diff --git a/src/lib.rs b/src/lib.rs index cf2834418..e5362259f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -172,14 +172,10 @@ //! //! [core] //! inactive_peer_cleanup_interval = 600 -//! mode = "public" +//! listed = false +//! private = false //! tracker_usage_statistics = true //! -//! [core.tracker_policy] -//! max_peer_timeout = 900 -//! persistent_torrent_completed_stat = false -//! remove_peerless_torrents = true -//! //! [core.announce_policy] //! interval = 120 //! interval_min = 120 @@ -192,6 +188,11 @@ //! external_ip = "0.0.0.0" //! on_reverse_proxy = false //! +//! [core.tracker_policy] +//! max_peer_timeout = 900 +//! persistent_torrent_completed_stat = false +//! remove_peerless_torrents = true +//! //! [health_check_api] //! bind_address = "127.0.0.1:1313" //!``` diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 967080bd5..39a68a856 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -266,7 +266,7 @@ impl Launcher { mod tests { use std::sync::Arc; - use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; + use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::initialize_with_configuration; use crate::bootstrap::jobs::make_rust_tls; @@ -275,7 +275,7 @@ mod tests { #[tokio::test] async fn it_should_be_able_to_start_and_stop() { - let cfg = Arc::new(ephemeral_mode_public()); + let cfg = Arc::new(ephemeral_public()); let config = &cfg.http_api.clone().unwrap(); let tracker = initialize_with_configuration(&cfg); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 87f0e945b..faedaf921 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -226,7 +226,7 @@ pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { mod tests { use std::sync::Arc; - use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; + use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::initialize_with_configuration; use crate::bootstrap::jobs::make_rust_tls; @@ -235,7 +235,7 @@ mod tests { #[tokio::test] async fn it_should_be_able_to_start_and_stop() { - let cfg = Arc::new(ephemeral_mode_public()); + let cfg = Arc::new(ephemeral_public()); let tracker = initialize_with_configuration(&cfg); let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); let config = &http_trackers[0]; diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 0b009f700..0514a9f71 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -181,11 +181,11 @@ mod tests { use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; fn private_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_mode_private()) + tracker_factory(&configuration::ephemeral_private()) } fn whitelisted_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_mode_whitelisted()) + tracker_factory(&configuration::ephemeral_listed()) } fn tracker_on_reverse_proxy() -> Tracker { diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 172607637..eb8875a58 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -121,11 +121,11 @@ mod tests { use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; fn private_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_mode_private()) + tracker_factory(&configuration::ephemeral_private()) } fn whitelisted_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_mode_whitelisted()) + tracker_factory(&configuration::ephemeral_listed()) } fn tracker_on_reverse_proxy() -> Tracker { diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index eee5e4688..47175817d 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -57,7 +57,7 @@ mod tests { use crate::core::Tracker; fn public_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_mode_public()) + tracker_factory(&configuration::ephemeral_public()) } fn sample_info_hash() -> InfoHash { diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index bf9fbd933..ee7814194 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -70,7 +70,7 @@ mod tests { use crate::core::Tracker; fn public_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_mode_public()) + tracker_factory(&configuration::ephemeral_public()) } fn sample_info_hashes() -> Vec { diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 12ae6a250..f1f61ee6b 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -339,15 +339,15 @@ mod tests { } fn public_tracker() -> Arc { - initialized_tracker(&configuration::ephemeral_mode_public()) + initialized_tracker(&configuration::ephemeral_public()) } fn private_tracker() -> Arc { - initialized_tracker(&configuration::ephemeral_mode_private()) + initialized_tracker(&configuration::ephemeral_private()) } fn whitelisted_tracker() -> Arc { - initialized_tracker(&configuration::ephemeral_mode_whitelisted()) + initialized_tracker(&configuration::ephemeral_listed()) } fn initialized_tracker(configuration: &Configuration) -> Arc { diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 034f71beb..e3321f157 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -47,7 +47,7 @@ mod tests { use std::sync::Arc; use std::time::Duration; - use torrust_tracker_test_helpers::configuration::ephemeral_mode_public; + use torrust_tracker_test_helpers::configuration::ephemeral_public; use super::spawner::Spawner; use super::Server; @@ -56,7 +56,7 @@ mod tests { #[tokio::test] async fn it_should_be_able_to_start_and_stop() { - let cfg = Arc::new(ephemeral_mode_public()); + let cfg = Arc::new(ephemeral_public()); let tracker = initialize_with_configuration(&cfg); let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; @@ -79,7 +79,7 @@ mod tests { #[tokio::test] async fn it_should_be_able_to_start_and_stop_with_wait() { - let cfg = Arc::new(ephemeral_mode_public()); + let cfg = Arc::new(ephemeral_public()); let tracker = initialize_with_configuration(&cfg); let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index a7962db0f..cdffead99 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -107,7 +107,7 @@ mod for_all_config_modes { #[tokio::test] async fn it_should_start_and_stop() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; env.stop().await; } @@ -376,7 +376,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_no_peers_if_the_announced_peer_is_the_first_one() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let response = Client::new(*env.bind_address()) .announce( @@ -405,7 +405,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_list_of_previously_announced_peers() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -447,7 +447,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_list_of_previously_announced_peers_including_peers_using_ipv4_and_ipv6() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -499,7 +499,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_consider_two_peers_to_be_the_same_when_they_have_the_same_peer_id_even_if_the_ip_is_different() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); let peer = PeerBuilder::default().build(); @@ -526,7 +526,7 @@ mod for_all_config_modes { // Tracker Returns Compact Peer Lists // https://www.bittorrent.org/beps/bep_0023.html - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -567,7 +567,7 @@ mod for_all_config_modes { // code-review: the HTTP tracker does not return the compact response by default if the "compact" // param is not provided in the announce URL. The BEP 23 suggest to do so. - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -605,7 +605,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp4_connections_handled_in_statistics() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; Client::new(*env.bind_address()) .announce(&QueryBuilder::default().query()) @@ -648,7 +648,7 @@ mod for_all_config_modes { async fn should_not_increase_the_number_of_tcp6_connections_handled_if_the_client_is_not_using_an_ipv6_ip() { // The tracker ignores the peer address in the request param. It uses the client remote ip address. - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; Client::new(*env.bind_address()) .announce( @@ -669,7 +669,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp4_announce_requests_handled_in_statistics() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; Client::new(*env.bind_address()) .announce(&QueryBuilder::default().query()) @@ -712,7 +712,7 @@ mod for_all_config_modes { async fn should_not_increase_the_number_of_tcp6_announce_requests_handled_if_the_client_is_not_using_an_ipv6_ip() { // The tracker ignores the peer address in the request param. It uses the client remote ip address. - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; Client::new(*env.bind_address()) .announce( @@ -733,7 +733,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_assign_to_the_peer_ip_the_remote_client_ip_instead_of_the_peer_address_in_the_request_param() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); let client_ip = local_ip().unwrap(); @@ -905,7 +905,7 @@ mod for_all_config_modes { //#[tokio::test] #[allow(dead_code)] async fn should_fail_when_the_request_is_empty() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let response = Client::new(*env.bind_address()).get("scrape").await; assert_missing_query_params_for_scrape_request_error_response(response).await; @@ -915,7 +915,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -932,7 +932,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_file_with_the_incomplete_peer_when_there_is_one_peer_with_bytes_pending_to_download() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -971,7 +971,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_file_with_the_complete_peer_when_there_is_one_peer_with_no_bytes_pending_to_download() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1010,7 +1010,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_a_file_with_zeroed_values_when_there_are_no_peers() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1029,7 +1029,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_accept_multiple_infohashes() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash1 = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); let info_hash2 = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); @@ -1055,7 +1055,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_ot_tcp4_scrape_requests_handled_in_statistics() { - let env = Started::new(&configuration::ephemeral_mode_public().into()).await; + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1123,7 +1123,7 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_fail_if_the_torrent_is_not_in_the_whitelist() { - let env = Started::new(&configuration::ephemeral_mode_whitelisted().into()).await; + let env = Started::new(&configuration::ephemeral_listed().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1138,7 +1138,7 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_allow_announcing_a_whitelisted_torrent() { - let env = Started::new(&configuration::ephemeral_mode_whitelisted().into()).await; + let env = Started::new(&configuration::ephemeral_listed().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1172,7 +1172,7 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_return_the_zeroed_file_when_the_requested_file_is_not_whitelisted() { - let env = Started::new(&configuration::ephemeral_mode_whitelisted().into()).await; + let env = Started::new(&configuration::ephemeral_listed().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1202,7 +1202,7 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_return_the_file_stats_when_the_requested_file_is_whitelisted() { - let env = Started::new(&configuration::ephemeral_mode_whitelisted().into()).await; + let env = Started::new(&configuration::ephemeral_listed().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1263,7 +1263,7 @@ mod configured_as_private { #[tokio::test] async fn should_respond_to_authenticated_peers() { - let env = Started::new(&configuration::ephemeral_mode_private().into()).await; + let env = Started::new(&configuration::ephemeral_private().into()).await; let expiring_key = env.tracker.generate_auth_key(Duration::from_secs(60)).await.unwrap(); @@ -1278,7 +1278,7 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_peer_has_not_provided_the_authentication_key() { - let env = Started::new(&configuration::ephemeral_mode_private().into()).await; + let env = Started::new(&configuration::ephemeral_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1293,7 +1293,7 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { - let env = Started::new(&configuration::ephemeral_mode_private().into()).await; + let env = Started::new(&configuration::ephemeral_private().into()).await; let invalid_key = "INVALID_KEY"; @@ -1308,7 +1308,7 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_peer_cannot_be_authenticated_with_the_provided_key() { - let env = Started::new(&configuration::ephemeral_mode_private().into()).await; + let env = Started::new(&configuration::ephemeral_private().into()).await; // The tracker does not have this key let unregistered_key = Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); @@ -1341,7 +1341,7 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { - let env = Started::new(&configuration::ephemeral_mode_private().into()).await; + let env = Started::new(&configuration::ephemeral_private().into()).await; let invalid_key = "INVALID_KEY"; @@ -1356,7 +1356,7 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_zeroed_file_when_the_client_is_not_authenticated() { - let env = Started::new(&configuration::ephemeral_mode_private().into()).await; + let env = Started::new(&configuration::ephemeral_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1386,7 +1386,7 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_real_file_stats_when_the_client_is_authenticated() { - let env = Started::new(&configuration::ephemeral_mode_private().into()).await; + let env = Started::new(&configuration::ephemeral_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1430,7 +1430,7 @@ mod configured_as_private { // There is not authentication error // code-review: should this really be this way? - let env = Started::new(&configuration::ephemeral_mode_private().into()).await; + let env = Started::new(&configuration::ephemeral_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); From a5b9e14a47e1496ce8fddfec836f21651ad9ca5b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 12:40:39 +0100 Subject: [PATCH 0416/1297] refactor: inject the core config to the core tracker --- packages/configuration/src/lib.rs | 7 +++--- src/core/mod.rs | 41 +++++++++++-------------------- 2 files changed, 19 insertions(+), 29 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index ca008a49a..8a544b6e2 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -35,10 +35,11 @@ const ENV_VAR_CONFIG_TOML: &str = "TORRUST_TRACKER_CONFIG_TOML"; pub const ENV_VAR_CONFIG_TOML_PATH: &str = "TORRUST_TRACKER_CONFIG_TOML_PATH"; pub type Configuration = v1::Configuration; -pub type UdpTracker = v1::udp_tracker::UdpTracker; -pub type HttpTracker = v1::http_tracker::HttpTracker; -pub type HttpApi = v1::tracker_api::HttpApi; +pub type Core = v1::core::Core; pub type HealthCheckApi = v1::health_check_api::HealthCheckApi; +pub type HttpApi = v1::tracker_api::HttpApi; +pub type HttpTracker = v1::http_tracker::HttpTracker; +pub type UdpTracker = v1::udp_tracker::UdpTracker; pub type AccessTokens = HashMap; diff --git a/src/core/mod.rs b/src/core/mod.rs index 20b7c81f4..a9fe2a8a6 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -456,8 +456,7 @@ use std::time::Duration; use derive_more::Constructor; use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; -use torrust_tracker_configuration::v1::core::Core; -use torrust_tracker_configuration::{AnnouncePolicy, TrackerPolicy, TORRENT_PEERS_LIMIT}; +use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; @@ -482,20 +481,15 @@ use crate::CurrentClock; /// > Typically, the `Tracker` is used by a higher application service that handles /// > the network layer. pub struct Tracker { - announce_policy: AnnouncePolicy, + config: Core, /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) /// or [`MySQL`](crate::core::databases::mysql) pub database: Arc>, - private: bool, - listed: bool, - policy: TrackerPolicy, keys: tokio::sync::RwLock>, whitelist: tokio::sync::RwLock>, pub torrents: Arc, stats_event_sender: Option>, stats_repository: statistics::Repo, - external_ip: Option, - on_reverse_proxy: bool, } /// Structure that holds the data returned by the `announce` request. @@ -561,35 +555,29 @@ impl Tracker { let database = Arc::new(databases::driver::build(&config.database.driver, &config.database.path)?); Ok(Tracker { - //config, - announce_policy: config.announce_policy, - private: config.private, - listed: config.listed, + config: config.clone(), keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), torrents: Arc::default(), stats_event_sender, stats_repository, database, - external_ip: config.net.external_ip, - policy: config.tracker_policy.clone(), - on_reverse_proxy: config.net.on_reverse_proxy, }) } /// Returns `true` is the tracker is in public mode. pub fn is_public(&self) -> bool { - !self.private + !self.config.private } /// Returns `true` is the tracker is in private mode. pub fn is_private(&self) -> bool { - self.private + self.config.private } /// Returns `true` is the tracker is in whitelisted mode. pub fn is_listed(&self) -> bool { - self.listed + self.config.listed } /// Returns `true` if the tracker requires authentication. @@ -599,15 +587,15 @@ impl Tracker { /// Returns `true` is the tracker is in whitelisted mode. pub fn is_behind_reverse_proxy(&self) -> bool { - self.on_reverse_proxy + self.config.net.on_reverse_proxy } pub fn get_announce_policy(&self) -> AnnouncePolicy { - self.announce_policy + self.config.announce_policy } pub fn get_maybe_external_ip(&self) -> Option { - self.external_ip + self.config.net.external_ip } /// It handles an announce request. @@ -632,7 +620,7 @@ impl Tracker { // responsibility into another authentication service. debug!("Before: {peer:?}"); - peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.external_ip)); + peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); debug!("After: {peer:?}"); let stats = self.upsert_peer_and_get_stats(info_hash, peer).await; @@ -735,7 +723,7 @@ impl Tracker { /// /// # Context: Tracker async fn persist_stats(&self, info_hash: &InfoHash, swarm_metadata: &SwarmMetadata) { - if self.policy.persistent_torrent_completed_stat { + if self.config.tracker_policy.persistent_torrent_completed_stat { let completed = swarm_metadata.downloaded; let info_hash = *info_hash; @@ -759,11 +747,12 @@ impl Tracker { /// # Context: Tracker pub fn cleanup_torrents(&self) { // If we don't need to remove torrents we will use the faster iter - if self.policy.remove_peerless_torrents { - self.torrents.remove_peerless_torrents(&self.policy); + if self.config.tracker_policy.remove_peerless_torrents { + self.torrents.remove_peerless_torrents(&self.config.tracker_policy); } else { let current_cutoff = - CurrentClock::now_sub(&Duration::from_secs(u64::from(self.policy.max_peer_timeout))).unwrap_or_default(); + CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout))) + .unwrap_or_default(); self.torrents.remove_inactive_peers(current_cutoff); } } From 5a16ea10a8d474a444eadd27b17ebfb4e9a150f3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 12:53:22 +0100 Subject: [PATCH 0417/1297] refactor: [#932] make all Tracker fields private --- src/core/mod.rs | 16 ++++++++++++++-- tests/servers/api/mod.rs | 7 +++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index a9fe2a8a6..4136966d2 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -481,13 +481,14 @@ use crate::CurrentClock; /// > Typically, the `Tracker` is used by a higher application service that handles /// > the network layer. pub struct Tracker { + // The tracker configuration. config: Core, /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) /// or [`MySQL`](crate::core::databases::mysql) - pub database: Arc>, + database: Arc>, keys: tokio::sync::RwLock>, whitelist: tokio::sync::RwLock>, - pub torrents: Arc, + torrents: Arc, stats_event_sender: Option>, stats_repository: statistics::Repo, } @@ -987,6 +988,17 @@ impl Tracker { Some(stats_event_sender) => stats_event_sender.send_event(event).await, } } + + /// It drops the database tables. + /// + /// # Errors + /// + /// Will return `Err` if unable to drop tables. + pub fn drop_database_tables(&self) -> Result<(), databases::error::Error> { + // todo: this is only used for testing. WE have to pass the database + // reference directly to the tests instead of via the tracker. + self.database.drop_database_tables() + } } #[must_use] diff --git a/tests/servers/api/mod.rs b/tests/servers/api/mod.rs index 9c30e316a..38df46e9b 100644 --- a/tests/servers/api/mod.rs +++ b/tests/servers/api/mod.rs @@ -11,7 +11,10 @@ pub type Started = environment::Environment; /// It forces a database error by dropping all tables. /// That makes any query fail. -/// code-review: alternatively we could inject a database mock in the future. +/// code-review: +/// Alternatively we could: +/// - Inject a database mock in the future. +/// - Inject directly the database reference passed to the Tracker type. pub fn force_database_error(tracker: &Arc) { - tracker.database.drop_database_tables().unwrap(); + tracker.drop_database_tables().unwrap(); } From f61c7c36cb3592c1989aba71b0959f6477d6d8a9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 13:05:11 +0100 Subject: [PATCH 0418/1297] docs: add commments to core::Tracker struct fields --- src/core/mod.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 4136966d2..9a64826c9 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -481,15 +481,26 @@ use crate::CurrentClock; /// > Typically, the `Tracker` is used by a higher application service that handles /// > the network layer. pub struct Tracker { - // The tracker configuration. + /// The tracker configuration. config: Core, + /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) /// or [`MySQL`](crate::core::databases::mysql) database: Arc>, + + /// Tracker users' keys. Only for private trackers. keys: tokio::sync::RwLock>, + + /// The list of allowed torrents. Only for listed trackers. whitelist: tokio::sync::RwLock>, + + /// The in-memory torrents repository. torrents: Arc, + + /// Service to send stats events. stats_event_sender: Option>, + + /// The in-memory stats repo. stats_repository: statistics::Repo, } From b6b841d6fe244b8deaa62629791d100623a508ce Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 13:31:30 +0100 Subject: [PATCH 0419/1297] chore: remove crate from ignore list in cargo machete It was accidentaly added. --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 3eca9934d..41afb1538 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -85,7 +85,7 @@ uuid = { version = "1", features = ["v4"] } zerocopy = "0.7.33" [package.metadata.cargo-machete] -ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_bytes", "torrust-tracker-primitives"] +ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_bytes"] [dev-dependencies] local-ip-address = "0" From 2969df35a9a93ea824b1fa15f9f28b182dc8cece Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 15:50:57 +0100 Subject: [PATCH 0420/1297] refactor: [#939] change config version The current config version is 2 leaving the previous before the config averhaul as version 1. --- packages/configuration/src/lib.rs | 14 +++++++------- packages/configuration/src/{v1 => v2}/core.rs | 2 +- packages/configuration/src/{v1 => v2}/database.rs | 0 .../src/{v1 => v2}/health_check_api.rs | 0 .../configuration/src/{v1 => v2}/http_tracker.rs | 0 packages/configuration/src/{v1 => v2}/logging.rs | 0 packages/configuration/src/{v1 => v2}/mod.rs | 2 +- packages/configuration/src/{v1 => v2}/network.rs | 0 .../configuration/src/{v1 => v2}/tracker_api.rs | 2 +- .../configuration/src/{v1 => v2}/udp_tracker.rs | 0 src/bootstrap/jobs/torrent_cleanup.rs | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) rename packages/configuration/src/{v1 => v2}/core.rs (98%) rename packages/configuration/src/{v1 => v2}/database.rs (100%) rename packages/configuration/src/{v1 => v2}/health_check_api.rs (100%) rename packages/configuration/src/{v1 => v2}/http_tracker.rs (100%) rename packages/configuration/src/{v1 => v2}/logging.rs (100%) rename packages/configuration/src/{v1 => v2}/mod.rs (99%) rename packages/configuration/src/{v1 => v2}/network.rs (100%) rename packages/configuration/src/{v1 => v2}/tracker_api.rs (98%) rename packages/configuration/src/{v1 => v2}/udp_tracker.rs (100%) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 8a544b6e2..72b998a31 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -4,7 +4,7 @@ //! Torrust Tracker, which is a `BitTorrent` tracker server. //! //! The current version for configuration is [`v1`]. -pub mod v1; +pub mod v2; use std::collections::HashMap; use std::env; @@ -34,12 +34,12 @@ const ENV_VAR_CONFIG_TOML: &str = "TORRUST_TRACKER_CONFIG_TOML"; /// The `tracker.toml` file location. pub const ENV_VAR_CONFIG_TOML_PATH: &str = "TORRUST_TRACKER_CONFIG_TOML_PATH"; -pub type Configuration = v1::Configuration; -pub type Core = v1::core::Core; -pub type HealthCheckApi = v1::health_check_api::HealthCheckApi; -pub type HttpApi = v1::tracker_api::HttpApi; -pub type HttpTracker = v1::http_tracker::HttpTracker; -pub type UdpTracker = v1::udp_tracker::UdpTracker; +pub type Configuration = v2::Configuration; +pub type Core = v2::core::Core; +pub type HealthCheckApi = v2::health_check_api::HealthCheckApi; +pub type HttpApi = v2::tracker_api::HttpApi; +pub type HttpTracker = v2::http_tracker::HttpTracker; +pub type UdpTracker = v2::udp_tracker::UdpTracker; pub type AccessTokens = HashMap; diff --git a/packages/configuration/src/v1/core.rs b/packages/configuration/src/v2/core.rs similarity index 98% rename from packages/configuration/src/v1/core.rs rename to packages/configuration/src/v2/core.rs index 1f0a0f957..09280917c 100644 --- a/packages/configuration/src/v1/core.rs +++ b/packages/configuration/src/v2/core.rs @@ -1,7 +1,7 @@ use serde::{Deserialize, Serialize}; use super::network::Network; -use crate::v1::database::Database; +use crate::v2::database::Database; use crate::{AnnouncePolicy, TrackerPolicy}; #[allow(clippy::struct_excessive_bools)] diff --git a/packages/configuration/src/v1/database.rs b/packages/configuration/src/v2/database.rs similarity index 100% rename from packages/configuration/src/v1/database.rs rename to packages/configuration/src/v2/database.rs diff --git a/packages/configuration/src/v1/health_check_api.rs b/packages/configuration/src/v2/health_check_api.rs similarity index 100% rename from packages/configuration/src/v1/health_check_api.rs rename to packages/configuration/src/v2/health_check_api.rs diff --git a/packages/configuration/src/v1/http_tracker.rs b/packages/configuration/src/v2/http_tracker.rs similarity index 100% rename from packages/configuration/src/v1/http_tracker.rs rename to packages/configuration/src/v2/http_tracker.rs diff --git a/packages/configuration/src/v1/logging.rs b/packages/configuration/src/v2/logging.rs similarity index 100% rename from packages/configuration/src/v1/logging.rs rename to packages/configuration/src/v2/logging.rs diff --git a/packages/configuration/src/v1/mod.rs b/packages/configuration/src/v2/mod.rs similarity index 99% rename from packages/configuration/src/v1/mod.rs rename to packages/configuration/src/v2/mod.rs index c5e0f9f7a..80e6cc0e6 100644 --- a/packages/configuration/src/v1/mod.rs +++ b/packages/configuration/src/v2/mod.rs @@ -357,7 +357,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr}; - use crate::v1::Configuration; + use crate::v2::Configuration; use crate::Info; #[cfg(test)] diff --git a/packages/configuration/src/v1/network.rs b/packages/configuration/src/v2/network.rs similarity index 100% rename from packages/configuration/src/v1/network.rs rename to packages/configuration/src/v2/network.rs diff --git a/packages/configuration/src/v1/tracker_api.rs b/packages/configuration/src/v2/tracker_api.rs similarity index 98% rename from packages/configuration/src/v1/tracker_api.rs rename to packages/configuration/src/v2/tracker_api.rs index 302a4ee95..1a2e0cbf0 100644 --- a/packages/configuration/src/v1/tracker_api.rs +++ b/packages/configuration/src/v2/tracker_api.rs @@ -65,7 +65,7 @@ impl HttpApi { #[cfg(test)] mod tests { - use crate::v1::tracker_api::HttpApi; + use crate::v2::tracker_api::HttpApi; #[test] fn http_api_configuration_should_check_if_it_contains_a_token() { diff --git a/packages/configuration/src/v1/udp_tracker.rs b/packages/configuration/src/v2/udp_tracker.rs similarity index 100% rename from packages/configuration/src/v1/udp_tracker.rs rename to packages/configuration/src/v2/udp_tracker.rs diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index 992e7e644..c0890f6ac 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -14,7 +14,7 @@ use std::sync::Arc; use chrono::Utc; use tokio::task::JoinHandle; -use torrust_tracker_configuration::v1::core::Core; +use torrust_tracker_configuration::v2::core::Core; use tracing::info; use crate::core; From 632ad0d662f34070da38d9f82e1501a3b4f588bf Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 15:54:24 +0100 Subject: [PATCH 0421/1297] refactor: use only latest config version in prod code Concrete config versions should be use for testing or config migration tools. --- packages/configuration/src/lib.rs | 1 + src/bootstrap/jobs/torrent_cleanup.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 72b998a31..5b139f573 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -40,6 +40,7 @@ pub type HealthCheckApi = v2::health_check_api::HealthCheckApi; pub type HttpApi = v2::tracker_api::HttpApi; pub type HttpTracker = v2::http_tracker::HttpTracker; pub type UdpTracker = v2::udp_tracker::UdpTracker; +pub type Database = v2::database::Database; pub type AccessTokens = HashMap; diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index c0890f6ac..6f057fb53 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -14,7 +14,7 @@ use std::sync::Arc; use chrono::Utc; use tokio::task::JoinHandle; -use torrust_tracker_configuration::v2::core::Core; +use torrust_tracker_configuration::Core; use tracing::info; use crate::core; From e299792d94af7bc373e40a136d1d232e891a2f72 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 16:12:28 +0100 Subject: [PATCH 0422/1297] feat: warn adming when no service is enabled in the configration That migth be a config error. --- src/app.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/app.rs b/src/app.rs index 2d70a6dde..fd7d6a99d 100644 --- a/src/app.rs +++ b/src/app.rs @@ -38,6 +38,13 @@ use crate::{core, servers}; /// - Can't retrieve tracker keys from database. /// - Can't load whitelist from database. pub async fn start(config: &Configuration, tracker: Arc) -> Vec> { + if config.http_api.is_none() + && (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) + && (config.http_trackers.is_none() || config.http_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) + { + warn!("No services enabled in configuration"); + } + let mut jobs: Vec> = Vec::new(); let registar = Registar::default(); From 46c3263203778d8097cf32f3c4a868ad49f599c7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 16:13:25 +0100 Subject: [PATCH 0423/1297] feat: normalize log nessages - No '.' full stop at the end. - Start message wirh uppercase. --- src/bootstrap/logging.rs | 2 +- src/console/ci/e2e/logs_parser.rs | 4 ++-- src/console/ci/e2e/runner.rs | 2 +- src/console/clients/checker/app.rs | 2 +- src/console/clients/udp/app.rs | 2 +- src/console/profiling.rs | 2 +- src/main.rs | 2 +- src/servers/apis/mod.rs | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index 649495dc7..f17c1ef28 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -52,7 +52,7 @@ fn tracing_stdout_init(filter: LevelFilter, style: &TraceStyle) { TraceStyle::Json => builder.json().init(), }; - info!("logging initialized."); + info!("Logging initialized"); } #[derive(Debug)] diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index 37eb367b1..fd7295eab 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -23,7 +23,7 @@ impl RunningServices { /// /// ```text /// Loading configuration from default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... - /// 2024-06-10T16:07:39.989540Z INFO torrust_tracker::bootstrap::logging: logging initialized. + /// 2024-06-10T16:07:39.989540Z INFO torrust_tracker::bootstrap::logging: Logging initialized /// 2024-06-10T16:07:39.990205Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6868 /// 2024-06-10T16:07:39.990215Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6868 /// 2024-06-10T16:07:39.990244Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 @@ -116,7 +116,7 @@ mod tests { fn it_should_parse_from_logs_with_valid_logs() { let logs = r" Loading configuration from default configuration file: `./share/default/config/tracker.development.sqlite3.toml` ... - 2024-06-10T16:07:39.989540Z INFO torrust_tracker::bootstrap::logging: logging initialized. + 2024-06-10T16:07:39.989540Z INFO torrust_tracker::bootstrap::logging: Logging initialized 2024-06-10T16:07:39.990244Z INFO UDP TRACKER: Starting on: udp://0.0.0.0:6969 2024-06-10T16:07:39.990255Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 2024-06-10T16:07:39.990261Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled diff --git a/src/console/ci/e2e/runner.rs b/src/console/ci/e2e/runner.rs index a3d61894e..f2285938b 100644 --- a/src/console/ci/e2e/runner.rs +++ b/src/console/ci/e2e/runner.rs @@ -117,7 +117,7 @@ pub fn run() -> anyhow::Result<()> { fn tracing_stdout_init(filter: LevelFilter) { tracing_subscriber::fmt().with_max_level(filter).init(); - info!("Logging initialized."); + info!("Logging initialized"); } fn load_tracker_configuration(args: &Args) -> anyhow::Result { diff --git a/src/console/clients/checker/app.rs b/src/console/clients/checker/app.rs index 9f9825d92..3bafc2661 100644 --- a/src/console/clients/checker/app.rs +++ b/src/console/clients/checker/app.rs @@ -103,7 +103,7 @@ pub async fn run() -> Result> { fn tracing_stdout_init(filter: LevelFilter) { tracing_subscriber::fmt().with_max_level(filter).init(); - debug!("logging initialized."); + debug!("Logging initialized"); } fn setup_config(args: Args) -> Result { diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index bcba39558..af6f10611 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -129,7 +129,7 @@ pub async fn run() -> anyhow::Result<()> { fn tracing_stdout_init(filter: LevelFilter) { tracing_subscriber::fmt().with_max_level(filter).init(); - debug!("logging initialized."); + debug!("Logging initialized"); } async fn handle_announce(remote_addr: SocketAddr, info_hash: &TorrustInfoHash) -> Result { diff --git a/src/console/profiling.rs b/src/console/profiling.rs index c95354d6f..3e2925d9c 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -192,7 +192,7 @@ pub async fn run() { info!("Torrust timed shutdown.."); }, _ = tokio::signal::ctrl_c() => { - info!("Torrust shutting down via Ctrl+C.."); + info!("Torrust shutting down via Ctrl+C ..."); // Await for all jobs to shutdown futures::future::join_all(jobs).await; } diff --git a/src/main.rs b/src/main.rs index bad1fdb1e..ab2af65e2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,7 @@ async fn main() { // handle the signals tokio::select! { _ = tokio::signal::ctrl_c() => { - info!("Torrust shutting down.."); + info!("Torrust shutting down ..."); // Await for all jobs to shutdown futures::future::join_all(jobs).await; diff --git a/src/servers/apis/mod.rs b/src/servers/apis/mod.rs index b44ccab9f..0451b46c0 100644 --- a/src/servers/apis/mod.rs +++ b/src/servers/apis/mod.rs @@ -42,7 +42,7 @@ //! //! ```text //! Loading configuration from config file ./tracker.toml -//! 023-03-28T12:19:24.963054069+01:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized. +//! 023-03-28T12:19:24.963054069+01:00 [torrust_tracker::bootstrap::logging][INFO] Logging initialized //! ... //! 023-03-28T12:19:24.964138723+01:00 [torrust_tracker::bootstrap::jobs::tracker_apis][INFO] Starting Torrust APIs server on: http://0.0.0.0:1212 //! ``` From ddfbde3c05f89a02dc3dbb1d1fc45dc5aa836fcc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 16:30:49 +0100 Subject: [PATCH 0424/1297] feat: the configuration can be serialized as JSON We will print to logs the final configuration used to run the tracker (after Figment processes all sources): ```output Loading extra configuration from file: `storage/tracker/etc/tracker.toml` ... 2024-07-01T15:29:09.785334Z INFO torrust_tracker::bootstrap::logging: Logging initialized 2024-07-01T15:29:09.785862Z INFO torrust_tracker::bootstrap::app: Configuration: { "logging": { "log_level": "info" }, "core": { "announce_policy": { "interval": 120, "interval_min": 120 }, "database": { "driver": "Sqlite3", "path": "./storage/tracker/lib/database/sqlite3.db" }, "inactive_peer_cleanup_interval": 600, "listed": false, "net": { "external_ip": "0.0.0.0", "on_reverse_proxy": false }, "private": true, "tracker_policy": { "max_peer_timeout": 900, "persistent_torrent_completed_stat": false, "remove_peerless_torrents": true }, "tracker_usage_statistics": true }, "udp_trackers": null, "http_trackers": null, "http_api": null, "health_check_api": { "bind_address": "127.0.0.1:1313" } } 2024-07-01T15:29:09.785879Z WARN torrust_tracker::app: No services enabled in configuration 2024-07-01T15:29:09.785920Z INFO torrust_tracker::app: No UDP blocks in configuration 2024-07-01T15:29:09.785923Z INFO torrust_tracker::app: No HTTP blocks in configuration 2024-07-01T15:29:09.785924Z INFO torrust_tracker::app: No API block in configuration 2024-07-01T15:29:09.785941Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 2024-07-01T15:29:09.786035Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 ``` --- Cargo.lock | 1 + packages/configuration/Cargo.toml | 1 + 2 files changed, 2 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 3a403332a..96c78db81 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4012,6 +4012,7 @@ dependencies = [ "derive_more", "figment", "serde", + "serde_json", "serde_with", "thiserror", "toml", diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 53e4e4cfa..51260d082 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -19,6 +19,7 @@ camino = { version = "1.1.6", features = ["serde", "serde1"] } derive_more = "0" figment = { version = "0.10.18", features = ["env", "test", "toml"] } serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["preserve_order"] } serde_with = "3" thiserror = "1" toml = "0" From 397ef0f6d003d4887272b6e25a2c5bbad9cc96c8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 16:33:05 +0100 Subject: [PATCH 0425/1297] feat: log final config after processing all config sources We print to logs the final configuration used to run the tracker (after Figment processes all sources): ```output Loading extra configuration from file: `storage/tracker/etc/tracker.toml` ... 2024-07-01T15:29:09.785334Z INFO torrust_tracker::bootstrap::logging: Logging initialized 2024-07-01T15:29:09.785862Z INFO torrust_tracker::bootstrap::app: Configuration: { "logging": { "log_level": "info" }, "core": { "announce_policy": { "interval": 120, "interval_min": 120 }, "database": { "driver": "Sqlite3", "path": "./storage/tracker/lib/database/sqlite3.db" }, "inactive_peer_cleanup_interval": 600, "listed": false, "net": { "external_ip": "0.0.0.0", "on_reverse_proxy": false }, "private": true, "tracker_policy": { "max_peer_timeout": 900, "persistent_torrent_completed_stat": false, "remove_peerless_torrents": true }, "tracker_usage_statistics": true }, "udp_trackers": null, "http_trackers": null, "http_api": null, "health_check_api": { "bind_address": "127.0.0.1:1313" } } 2024-07-01T15:29:09.785879Z WARN torrust_tracker::app: No services enabled in configuration 2024-07-01T15:29:09.785920Z INFO torrust_tracker::app: No UDP blocks in configuration 2024-07-01T15:29:09.785923Z INFO torrust_tracker::app: No HTTP blocks in configuration 2024-07-01T15:29:09.785924Z INFO torrust_tracker::app: No API block in configuration 2024-07-01T15:29:09.785941Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 2024-07-01T15:29:09.786035Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 ``` --- packages/configuration/src/lib.rs | 6 +++--- packages/configuration/src/v2/mod.rs | 16 ++++++++++++++++ src/bootstrap/app.rs | 4 ++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 5b139f573..dd250d280 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -111,17 +111,17 @@ impl Info { let env_var_config_toml_path = ENV_VAR_CONFIG_TOML_PATH.to_string(); let config_toml = if let Ok(config_toml) = env::var(env_var_config_toml) { - println!("Loading configuration from environment variable:\n {config_toml}"); + println!("Loading extra configuration from environment variable:\n {config_toml}"); Some(config_toml) } else { None }; let config_toml_path = if let Ok(config_toml_path) = env::var(env_var_config_toml_path) { - println!("Loading configuration from file: `{config_toml_path}` ..."); + println!("Loading extra configuration from file: `{config_toml_path}` ..."); config_toml_path } else { - println!("Loading configuration from default configuration file: `{default_config_toml_path}` ..."); + println!("Loading extra configuration from default configuration file: `{default_config_toml_path}` ..."); default_config_toml_path }; diff --git a/packages/configuration/src/v2/mod.rs b/packages/configuration/src/v2/mod.rs index 80e6cc0e6..9b6e01cb4 100644 --- a/packages/configuration/src/v2/mod.rs +++ b/packages/configuration/src/v2/mod.rs @@ -346,10 +346,26 @@ impl Configuration { } /// Encodes the configuration to TOML. + /// + /// # Panics + /// + /// Will panic if it can't be converted to TOML. + #[must_use] fn to_toml(&self) -> String { // code-review: do we need to use Figment also to serialize into toml? toml::to_string(self).expect("Could not encode TOML value") } + + /// Encodes the configuration to JSON. + /// + /// # Panics + /// + /// Will panic if it can't be converted to JSON. + #[must_use] + pub fn to_json(&self) -> String { + // code-review: do we need to use Figment also to serialize into json? + serde_json::to_string_pretty(self).expect("Could not encode JSON value") + } } #[cfg(test)] diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 396e63682..285b72133 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -15,6 +15,7 @@ use std::sync::Arc; use torrust_tracker_clock::static_time; use torrust_tracker_configuration::Configuration; +use tracing::info; use super::config::initialize_configuration; use crate::bootstrap; @@ -26,8 +27,11 @@ use crate::shared::crypto::ephemeral_instance_keys; #[must_use] pub fn setup() -> (Configuration, Arc) { let configuration = initialize_configuration(); + let tracker = initialize_with_configuration(&configuration); + info!("Configuration:\n{}", configuration.to_json()); + (configuration, tracker) } From af61e20c43ced22dac50bcfae07891372c2a0dae Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 17:55:03 +0100 Subject: [PATCH 0426/1297] feat: [#936] rename config value log_level to threshold From: ```toml [logging] log_level = "info" ``` To: ```toml [logging] threshold = "info" ``` Threshold represetns better the concept since this value is the security level at which the app stops collecting logs, meaning it filters out logs with a lower security level. --- docs/benchmarking.md | 10 +++---- packages/configuration/src/lib.rs | 18 +----------- packages/configuration/src/v2/logging.rs | 29 ++++++++++++++----- packages/configuration/src/v2/mod.rs | 4 +-- packages/test-helpers/src/configuration.rs | 6 ++-- .../config/tracker.udp.benchmarking.toml | 2 +- src/bootstrap/app.rs | 2 +- src/bootstrap/logging.rs | 26 +++++++++-------- src/console/ci/e2e/logs_parser.rs | 4 +-- src/core/mod.rs | 2 +- src/lib.rs | 2 +- 11 files changed, 53 insertions(+), 52 deletions(-) diff --git a/docs/benchmarking.md b/docs/benchmarking.md index ce3b69057..7d0228737 100644 --- a/docs/benchmarking.md +++ b/docs/benchmarking.md @@ -26,11 +26,11 @@ cargo build --release -p aquatic_udp_load_test ### Run UDP load test -Run the tracker with UDP service enabled and other services disabled and set log level to `error`. +Run the tracker with UDP service enabled and other services disabled and set log threshold to `error`. ```toml [logging] -log_level = "error" +threshold = "error" [[udp_trackers]] bind_address = "0.0.0.0:6969" @@ -97,7 +97,7 @@ Announce responses per info hash: - p100: 361 ``` -> IMPORTANT: The performance of the Torrust UDP Tracker is drastically decreased with these log levels: `info`, `debug`, `trace`. +> IMPORTANT: The performance of the Torrust UDP Tracker is drastically decreased with these log threshold: `info`, `debug`, `trace`. ```output Requests out: 40719.21/second @@ -161,11 +161,11 @@ Announce responses per info hash: #### Torrust-Actix UDP Tracker -Run the tracker with UDP service enabled and other services disabled and set log level to `error`. +Run the tracker with UDP service enabled and other services disabled and set log threshold to `error`. ```toml [logging] -log_level = "error" +threshold = "error" [[udp_trackers]] bind_address = "0.0.0.0:6969" diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index dd250d280..841a5182e 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -41,6 +41,7 @@ pub type HttpApi = v2::tracker_api::HttpApi; pub type HttpTracker = v2::http_tracker::HttpTracker; pub type UdpTracker = v2::udp_tracker::UdpTracker; pub type Database = v2::database::Database; +pub type Threshold = v2::logging::Threshold; pub type AccessTokens = HashMap; @@ -241,20 +242,3 @@ impl TslConfig { Utf8PathBuf::new() } } - -#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Clone)] -#[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, -} diff --git a/packages/configuration/src/v2/logging.rs b/packages/configuration/src/v2/logging.rs index e33522db4..e7dbe146c 100644 --- a/packages/configuration/src/v2/logging.rs +++ b/packages/configuration/src/v2/logging.rs @@ -1,26 +1,41 @@ use serde::{Deserialize, Serialize}; -use crate::LogLevel; - #[allow(clippy::struct_excessive_bools)] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct Logging { /// Logging level. Possible values are: `Off`, `Error`, `Warn`, `Info`, /// `Debug` and `Trace`. Default is `Info`. - #[serde(default = "Logging::default_log_level")] - pub log_level: LogLevel, + #[serde(default = "Logging::default_threshold")] + pub threshold: Threshold, } impl Default for Logging { fn default() -> Self { Self { - log_level: Self::default_log_level(), + threshold: Self::default_threshold(), } } } impl Logging { - fn default_log_level() -> LogLevel { - LogLevel::Info + fn default_threshold() -> Threshold { + Threshold::Info } } + +#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Clone)] +#[serde(rename_all = "lowercase")] +pub enum Threshold { + /// A threshold lower than all security levels. + Off, + /// Corresponds to the `Error` security level. + Error, + /// Corresponds to the `Warn` security level. + Warn, + /// Corresponds to the `Info` security level. + Info, + /// Corresponds to the `Debug` security level. + Debug, + /// Corresponds to the `Trace` security level. + Trace, +} diff --git a/packages/configuration/src/v2/mod.rs b/packages/configuration/src/v2/mod.rs index 9b6e01cb4..92ac88506 100644 --- a/packages/configuration/src/v2/mod.rs +++ b/packages/configuration/src/v2/mod.rs @@ -196,7 +196,7 @@ //! //! ```toml //! [logging] -//! log_level = "info" +//! threshold = "info" //! //! [core] //! inactive_peer_cleanup_interval = 600 @@ -379,7 +379,7 @@ mod tests { #[cfg(test)] fn default_config_toml() -> String { let config = r#"[logging] - log_level = "info" + threshold = "info" [core] inactive_peer_cleanup_interval = 600 diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 65d9d9144..0a6c1c72b 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -2,7 +2,7 @@ use std::env; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; -use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, LogLevel, UdpTracker}; +use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, Threshold, UdpTracker}; use crate::random; @@ -14,7 +14,7 @@ use crate::random; /// > **NOTICE**: Port 0 is used for ephemeral ports, which means that the OS /// > will assign a random free port for the tracker to use. /// -/// > **NOTICE**: You can change the log level to `debug` to see the logs of the +/// > **NOTICE**: You can change the log threshold to `debug` to see the logs of the /// > tracker while running the tests. That can be particularly useful when /// > debugging tests. /// @@ -28,7 +28,7 @@ pub fn ephemeral() -> Configuration { let mut config = Configuration::default(); - config.logging.log_level = LogLevel::Off; // Change to `debug` for tests debugging + config.logging.threshold = Threshold::Off; // Change to `debug` for tests debugging // Ephemeral socket address for API let api_port = 0u16; diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml index d9361cf10..c01fcd25e 100644 --- a/share/default/config/tracker.udp.benchmarking.toml +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -1,5 +1,5 @@ [logging] -log_level = "error" +threshold = "error" [core] remove_peerless_torrents = false diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 285b72133..023520507 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -68,7 +68,7 @@ pub fn initialize_tracker(config: &Configuration) -> Tracker { tracker_factory(config) } -/// It initializes the log level, format and channel. +/// It initializes the log threshold, format and channel. /// /// See [the logging setup](crate::bootstrap::logging::setup) for more info about logging. pub fn initialize_logging(config: &Configuration) { diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index f17c1ef28..496b3ea45 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -1,6 +1,7 @@ //! Setup for the application logging. //! -//! It redirects the log info to the standard output with the log level defined in the configuration. +//! It redirects the log info to the standard output with the log threshold +//! defined in the configuration. //! //! - `Off` //! - `Error` @@ -12,15 +13,16 @@ //! Refer to the [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) to know how to change log settings. use std::sync::Once; -use torrust_tracker_configuration::{Configuration, LogLevel}; +use torrust_tracker_configuration::{Configuration, Threshold}; use tracing::info; use tracing::level_filters::LevelFilter; static INIT: Once = Once::new(); -/// It redirects the log info to the standard output with the log level defined in the configuration +/// It redirects the log info to the standard output with the log threshold +/// defined in the configuration. pub fn setup(cfg: &Configuration) { - let tracing_level = map_to_tracing_level_filter(&cfg.logging.log_level); + let tracing_level = map_to_tracing_level_filter(&cfg.logging.threshold); if tracing_level == LevelFilter::OFF { return; @@ -31,14 +33,14 @@ pub fn setup(cfg: &Configuration) { }); } -fn map_to_tracing_level_filter(log_level: &LogLevel) -> LevelFilter { - match log_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, +fn map_to_tracing_level_filter(threshold: &Threshold) -> LevelFilter { + match threshold { + Threshold::Off => LevelFilter::OFF, + Threshold::Error => LevelFilter::ERROR, + Threshold::Warn => LevelFilter::WARN, + Threshold::Info => LevelFilter::INFO, + Threshold::Debug => LevelFilter::DEBUG, + Threshold::Trace => LevelFilter::TRACE, } } diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index fd7295eab..95648a2b5 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -7,7 +7,7 @@ use crate::servers::http::HTTP_TRACKER_LOG_TARGET; use crate::servers::logging::STARTED_ON; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; -const INFO_LOG_LEVEL: &str = "INFO"; +const INFO_THRESHOLD: &str = "INFO"; #[derive(Serialize, Deserialize, Debug, Default)] pub struct RunningServices { @@ -74,7 +74,7 @@ impl RunningServices { for line in logs.lines() { let clean_line = ansi_escape_re.replace_all(line, ""); - if !line.contains(INFO_LOG_LEVEL) { + if !line.contains(INFO_THRESHOLD) { continue; }; diff --git a/src/core/mod.rs b/src/core/mod.rs index 9a64826c9..06b1aa0f9 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -313,7 +313,7 @@ //! //! ```toml //! [logging] -//! log_level = "debug" +//! threshold = "debug" //! //! [core] //! inactive_peer_cleanup_interval = 600 diff --git a/src/lib.rs b/src/lib.rs index e5362259f..9776345b0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -168,7 +168,7 @@ //! //! ```toml //! [logging] -//! log_level = "info" +//! threshold = "info" //! //! [core] //! inactive_peer_cleanup_interval = 600 From e2dbb0bbf70f599656d11ea145cae00bbf91e10c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 21:07:15 +0100 Subject: [PATCH 0427/1297] chore(deps): update dependencies ```output cargo update Updating crates.io index Locking 4 packages to latest compatible versions Updating cc v1.0.103 -> v1.0.104 Updating hyper v1.3.1 -> v1.4.0 Updating hyper-util v0.1.5 -> v0.1.6 Updating serde_json v1.0.119 -> v1.0.120 ``` --- Cargo.lock | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 96c78db81..2215edfeb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -738,9 +738,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.103" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2755ff20a1d93490d26ba33a6f092a38a508398a5320df5d4b3014fcccce9410" +checksum = "74b6a57f98764a267ff415d50a25e6e166f3831a5071af4995296ea97d210490" dependencies = [ "jobserver", "libc", @@ -1707,9 +1707,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.3.1" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe575dd17d0862a9a33781c8c4696a55c320909004a67a00fb286ba8b1bc496d" +checksum = "c4fe55fb7a772d59a5ff1dfbff4fe0258d19b89fec4b233e75d35d5d2316badc" dependencies = [ "bytes", "futures-channel", @@ -1761,9 +1761,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b875924a60b96e5d7b9ae7b066540b1dd1cbd90d1828f54c92e02a283351c56" +checksum = "3ab92f4f49ee4fb4f997c784b7a2e0fa70050211e0b6a287f898c3c9785ca956" dependencies = [ "bytes", "futures-channel", @@ -3392,9 +3392,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.119" +version = "1.0.120" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8eddb61f0697cc3989c5d64b452f5488e2b8a60fd7d5076a3045076ffef8cb0" +checksum = "4e0d21c9a8cae1235ad58a00c11cb40d4b1e5c784f1ef2c537876ed6ffd8b7c5" dependencies = [ "indexmap 2.2.6", "itoa", From 4846c9fe45285c650204e636331ff2eaa8ab3b57 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Jul 2024 21:08:15 +0100 Subject: [PATCH 0428/1297] chore: update workflow action build-push-action --- .github/workflows/container.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index 884a15843..9f51f3124 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -30,7 +30,7 @@ jobs: - id: build name: Build - uses: docker/build-push-action@v5 + uses: docker/build-push-action@v6 with: file: ./Containerfile push: false @@ -127,7 +127,7 @@ jobs: uses: docker/setup-buildx-action@v3 - name: Build and push - uses: docker/build-push-action@v5 + uses: docker/build-push-action@v6 with: file: ./Containerfile push: true @@ -168,7 +168,7 @@ jobs: uses: docker/setup-buildx-action@v3 - name: Build and push - uses: docker/build-push-action@v5 + uses: docker/build-push-action@v6 with: file: ./Containerfile push: true From 60c68762b64b7b909987fc6002447af7c823adbe Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 2 Jul 2024 08:23:23 +0100 Subject: [PATCH 0429/1297] feat: [#937] add version to configration file following semver. Add version and namespace to the configuration. It will fail if the provided version is not supported. ```toml version = "2" ``` It only supports the exact match '2'. --- packages/configuration/src/lib.rs | 62 ++++++++++++++++++- packages/configuration/src/v2/mod.rs | 20 +++++- .../config/tracker.container.mysql.toml | 2 + .../config/tracker.container.sqlite3.toml | 2 + .../config/tracker.development.sqlite3.toml | 2 + .../config/tracker.e2e.container.sqlite3.toml | 2 + .../config/tracker.udp.benchmarking.toml | 2 + 7 files changed, 89 insertions(+), 3 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 841a5182e..e5bfa6eb7 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use std::time::Duration; use camino::Utf8PathBuf; -use derive_more::Constructor; +use derive_more::{Constructor, Display}; use serde::{Deserialize, Serialize}; use serde_with::serde_as; use thiserror::Error; @@ -45,6 +45,63 @@ pub type Threshold = v2::logging::Threshold; pub type AccessTokens = HashMap; +pub const LATEST_VERSION: &str = "2"; + +/// Info about the configuration specification. +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display)] +pub struct Metadata { + #[serde(default = "Metadata::default_version")] + #[serde(flatten)] + version: Version, +} + +impl Default for Metadata { + fn default() -> Self { + Self { + version: Self::default_version(), + } + } +} + +impl Metadata { + fn default_version() -> Version { + Version::latest() + } +} + +/// The configuration version. +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display)] +pub struct Version { + #[serde(default = "Version::default_semver")] + version: String, +} + +impl Default for Version { + fn default() -> Self { + Self { + version: Self::default_semver(), + } + } +} + +impl Version { + fn new(semver: &str) -> Self { + Self { + version: semver.to_owned(), + } + } + + fn latest() -> Self { + Self { + version: LATEST_VERSION.to_string(), + } + } + + fn default_semver() -> String { + LATEST_VERSION.to_string() + } +} + #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Constructor)] pub struct TrackerPolicy { // Cleanup job configuration @@ -208,6 +265,9 @@ pub enum Error { #[error("The error for errors that can never happen.")] Infallible, + + #[error("Unsupported configuration version: {version}")] + UnsupportedVersion { version: Version }, } impl From for Error { diff --git a/packages/configuration/src/v2/mod.rs b/packages/configuration/src/v2/mod.rs index 92ac88506..3425dc0de 100644 --- a/packages/configuration/src/v2/mod.rs +++ b/packages/configuration/src/v2/mod.rs @@ -251,16 +251,24 @@ use self::health_check_api::HealthCheckApi; use self::http_tracker::HttpTracker; use self::tracker_api::HttpApi; use self::udp_tracker::UdpTracker; -use crate::{Error, Info}; +use crate::{Error, Info, Metadata, Version}; + +/// This configuration version +const VERSION_2: &str = "2"; /// Prefix for env vars that overwrite configuration options. const CONFIG_OVERRIDE_PREFIX: &str = "TORRUST_TRACKER_CONFIG_OVERRIDE_"; + /// Path separator in env var names for nested values in configuration. const CONFIG_OVERRIDE_SEPARATOR: &str = "__"; /// Core configuration for the tracker. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Default)] pub struct Configuration { + /// Configuration metadata. + #[serde(flatten)] + pub metadata: Metadata, + /// Logging configuration pub logging: Logging, @@ -326,6 +334,12 @@ impl Configuration { let config: Configuration = figment.extract()?; + if config.metadata.version != Version::new(VERSION_2) { + return Err(Error::UnsupportedVersion { + version: config.metadata.version, + }); + } + Ok(config) } @@ -378,7 +392,9 @@ mod tests { #[cfg(test)] fn default_config_toml() -> String { - let config = r#"[logging] + let config = r#"version = "2" + + [logging] threshold = "info" [core] diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml index 68cc8db8a..9465c0ef8 100644 --- a/share/default/config/tracker.container.mysql.toml +++ b/share/default/config/tracker.container.mysql.toml @@ -1,3 +1,5 @@ +version = "2" + [core.database] driver = "MySQL" path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml index 63e169a70..aa8aefa5e 100644 --- a/share/default/config/tracker.container.sqlite3.toml +++ b/share/default/config/tracker.container.sqlite3.toml @@ -1,3 +1,5 @@ +version = "2" + [core.database] path = "/var/lib/torrust/tracker/database/sqlite3.db" diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index 84754794e..554835922 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -1,3 +1,5 @@ +version = "2" + [[udp_trackers]] bind_address = "0.0.0.0:6969" diff --git a/share/default/config/tracker.e2e.container.sqlite3.toml b/share/default/config/tracker.e2e.container.sqlite3.toml index fb33a8e32..6b1383fb5 100644 --- a/share/default/config/tracker.e2e.container.sqlite3.toml +++ b/share/default/config/tracker.e2e.container.sqlite3.toml @@ -1,3 +1,5 @@ +version = "2" + [core.database] path = "/var/lib/torrust/tracker/database/sqlite3.db" diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml index c01fcd25e..907a05456 100644 --- a/share/default/config/tracker.udp.benchmarking.toml +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -1,3 +1,5 @@ +version = "2" + [logging] threshold = "error" From 16aa652821434a43e4efd7f8d85a63b9fae3ff3c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 4 Jul 2024 11:23:02 +0100 Subject: [PATCH 0430/1297] chore(deps): add url dependency It will be use to parse the MySQL path in the configuration. FOr example: ```toml [core.database] driver = "MySQL" path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" ``` --- Cargo.lock | 1 + packages/configuration/Cargo.toml | 1 + 2 files changed, 2 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 2215edfeb..4e25fc4c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4018,6 +4018,7 @@ dependencies = [ "toml", "torrust-tracker-located-error", "torrust-tracker-primitives", + "url", "uuid", ] diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 51260d082..90c816344 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -25,6 +25,7 @@ thiserror = "1" toml = "0" torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "../located-error" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } +url = "2.5.2" [dev-dependencies] uuid = { version = "1", features = ["v4"] } From 4673514bdd401c5546f0da7ec71eb7dd4c4f9c1a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 4 Jul 2024 11:28:44 +0100 Subject: [PATCH 0431/1297] fix: [#948] mask secrets in logs --- packages/configuration/src/lib.rs | 4 +- packages/configuration/src/v2/database.rs | 41 +++++++++++++++++++- packages/configuration/src/v2/mod.rs | 14 ++++++- packages/configuration/src/v2/tracker_api.rs | 6 +++ src/bootstrap/app.rs | 2 +- 5 files changed, 62 insertions(+), 5 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index e5bfa6eb7..32831409d 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -48,7 +48,7 @@ pub type AccessTokens = HashMap; pub const LATEST_VERSION: &str = "2"; /// Info about the configuration specification. -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display, Clone)] pub struct Metadata { #[serde(default = "Metadata::default_version")] #[serde(flatten)] @@ -70,7 +70,7 @@ impl Metadata { } /// The configuration version. -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display, Clone)] pub struct Version { #[serde(default = "Version::default_semver")] version: String, diff --git a/packages/configuration/src/v2/database.rs b/packages/configuration/src/v2/database.rs index b029175ce..932db552c 100644 --- a/packages/configuration/src/v2/database.rs +++ b/packages/configuration/src/v2/database.rs @@ -1,5 +1,6 @@ use serde::{Deserialize, Serialize}; use torrust_tracker_primitives::DatabaseDriver; +use url::Url; #[allow(clippy::struct_excessive_bools)] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] @@ -13,7 +14,7 @@ pub struct Database { /// For `Sqlite3`, the format is `path/to/database.db`, for example: /// `./storage/tracker/lib/database/sqlite3.db`. /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for - /// example: `root:password@localhost:3306/torrust`. + /// example: `mysql://root:password@localhost:3306/torrust`. #[serde(default = "Database::default_path")] pub path: String, } @@ -35,4 +36,42 @@ impl Database { fn default_path() -> String { String::from("./storage/tracker/lib/database/sqlite3.db") } + + /// Masks secrets in the configuration. + /// + /// # Panics + /// + /// Will panic if the database path for `MySQL` is not a valid URL. + pub fn mask_secrets(&mut self) { + match self.driver { + DatabaseDriver::Sqlite3 => { + // Nothing to mask + } + DatabaseDriver::MySQL => { + let mut url = Url::parse(&self.path).expect("path for MySQL driver should be a valid URL"); + url.set_password(Some("***")).expect("url password should be changed"); + self.path = url.to_string(); + } + } + } +} + +#[cfg(test)] +mod tests { + + use torrust_tracker_primitives::DatabaseDriver; + + use super::Database; + + #[test] + fn it_should_allow_masking_the_mysql_user_password() { + let mut database = Database { + driver: DatabaseDriver::MySQL, + path: "mysql://root:password@localhost:3306/torrust".to_string(), + }; + + database.mask_secrets(); + + assert_eq!(database.path, "mysql://root:***@localhost:3306/torrust".to_string()); + } } diff --git a/packages/configuration/src/v2/mod.rs b/packages/configuration/src/v2/mod.rs index 3425dc0de..141bab00f 100644 --- a/packages/configuration/src/v2/mod.rs +++ b/packages/configuration/src/v2/mod.rs @@ -263,7 +263,7 @@ const CONFIG_OVERRIDE_PREFIX: &str = "TORRUST_TRACKER_CONFIG_OVERRIDE_"; const CONFIG_OVERRIDE_SEPARATOR: &str = "__"; /// Core configuration for the tracker. -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Default)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Default, Clone)] pub struct Configuration { /// Configuration metadata. #[serde(flatten)] @@ -380,6 +380,18 @@ impl Configuration { // code-review: do we need to use Figment also to serialize into json? serde_json::to_string_pretty(self).expect("Could not encode JSON value") } + + /// Masks secrets in the configuration. + #[must_use] + pub fn mask_secrets(mut self) -> Self { + self.core.database.mask_secrets(); + + if let Some(ref mut api) = self.http_api { + api.mask_secrets(); + } + + self + } } #[cfg(test)] diff --git a/packages/configuration/src/v2/tracker_api.rs b/packages/configuration/src/v2/tracker_api.rs index 1a2e0cbf0..dbbff7995 100644 --- a/packages/configuration/src/v2/tracker_api.rs +++ b/packages/configuration/src/v2/tracker_api.rs @@ -61,6 +61,12 @@ impl HttpApi { pub fn override_admin_token(&mut self, api_admin_token: &str) { self.access_tokens.insert("admin".to_string(), api_admin_token.to_string()); } + + pub fn mask_secrets(&mut self) { + for token in self.access_tokens.values_mut() { + *token = "***".to_string(); + } + } } #[cfg(test)] diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 023520507..cfb84a2d1 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -30,7 +30,7 @@ pub fn setup() -> (Configuration, Arc) { let tracker = initialize_with_configuration(&configuration); - info!("Configuration:\n{}", configuration.to_json()); + info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); (configuration, tracker) } From 9be96380f92b56df40273bd33b69ede51e7fc963 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 5 Jul 2024 10:02:56 +0100 Subject: [PATCH 0432/1297] refactor: [#950] decouple database driver enum Use a different enum for configuration and domain. --- packages/configuration/src/lib.rs | 1 + packages/configuration/src/v2/database.rs | 29 +++++++++++++++-------- packages/primitives/src/lib.rs | 3 --- src/core/mod.rs | 10 ++++++-- 4 files changed, 28 insertions(+), 15 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 32831409d..5e839b7b1 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -41,6 +41,7 @@ pub type HttpApi = v2::tracker_api::HttpApi; pub type HttpTracker = v2::http_tracker::HttpTracker; pub type UdpTracker = v2::udp_tracker::UdpTracker; pub type Database = v2::database::Database; +pub type Driver = v2::database::Driver; pub type Threshold = v2::logging::Threshold; pub type AccessTokens = HashMap; diff --git a/packages/configuration/src/v2/database.rs b/packages/configuration/src/v2/database.rs index 932db552c..ef462556d 100644 --- a/packages/configuration/src/v2/database.rs +++ b/packages/configuration/src/v2/database.rs @@ -1,5 +1,4 @@ use serde::{Deserialize, Serialize}; -use torrust_tracker_primitives::DatabaseDriver; use url::Url; #[allow(clippy::struct_excessive_bools)] @@ -8,7 +7,7 @@ pub struct Database { // Database configuration /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. #[serde(default = "Database::default_driver")] - pub driver: DatabaseDriver, + pub driver: Driver, /// Database connection string. The format depends on the database driver. /// For `Sqlite3`, the format is `path/to/database.db`, for example: @@ -29,8 +28,8 @@ impl Default for Database { } impl Database { - fn default_driver() -> DatabaseDriver { - DatabaseDriver::Sqlite3 + fn default_driver() -> Driver { + Driver::Sqlite3 } fn default_path() -> String { @@ -44,10 +43,10 @@ impl Database { /// Will panic if the database path for `MySQL` is not a valid URL. pub fn mask_secrets(&mut self) { match self.driver { - DatabaseDriver::Sqlite3 => { + Driver::Sqlite3 => { // Nothing to mask } - DatabaseDriver::MySQL => { + Driver::MySQL => { let mut url = Url::parse(&self.path).expect("path for MySQL driver should be a valid URL"); url.set_password(Some("***")).expect("url password should be changed"); self.path = url.to_string(); @@ -56,17 +55,27 @@ impl Database { } } +/// The database management system used by the tracker. +#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Clone)] +pub enum Driver { + // todo: + // - Rename serialized values to lowercase: `sqlite3` and `mysql`. + // - Add serde default values. + /// The `Sqlite3` database driver. + Sqlite3, + /// The `MySQL` database driver. + MySQL, +} + #[cfg(test)] mod tests { - use torrust_tracker_primitives::DatabaseDriver; - - use super::Database; + use super::{Database, Driver}; #[test] fn it_should_allow_masking_the_mysql_user_password() { let mut database = Database { - driver: DatabaseDriver::MySQL, + driver: Driver::MySQL, path: "mysql://root:password@localhost:3306/torrust".to_string(), }; diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index 7ad1d35b4..9bd3bad55 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -52,9 +52,6 @@ pub struct NumberOfBytes(pub i64); /// For more information about persistence. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, derive_more::Display, Clone)] pub enum DatabaseDriver { - // TODO: - // - Move to the database crate once that gets its own crate. - // - Rename serialized values to lowercase: `sqlite3` and `mysql`. /// The Sqlite3 database driver. Sqlite3, /// The `MySQL` database driver. diff --git a/src/core/mod.rs b/src/core/mod.rs index 06b1aa0f9..57cf56bca 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -456,11 +456,12 @@ use std::time::Duration; use derive_more::Constructor; use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; +use torrust_tracker_configuration::v2::database; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DatabaseDriver}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; use tracing::debug; @@ -564,7 +565,12 @@ impl Tracker { stats_event_sender: Option>, stats_repository: statistics::Repo, ) -> Result { - let database = Arc::new(databases::driver::build(&config.database.driver, &config.database.path)?); + let driver = match config.database.driver { + database::Driver::Sqlite3 => DatabaseDriver::Sqlite3, + database::Driver::MySQL => DatabaseDriver::MySQL, + }; + + let database = Arc::new(databases::driver::build(&driver, &config.database.path)?); Ok(Tracker { config: config.clone(), From 954295aa09831c59b2dfe6206c20acdb0229543e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 5 Jul 2024 10:12:29 +0100 Subject: [PATCH 0433/1297] refactor: [#950] move DatabaseDriver to databases mod --- packages/primitives/src/lib.rs | 16 ---------------- src/core/databases/driver.rs | 23 ++++++++++++++++++++--- src/core/databases/error.rs | 3 ++- src/core/databases/mysql.rs | 3 ++- src/core/databases/sqlite.rs | 3 ++- src/core/mod.rs | 3 ++- 6 files changed, 28 insertions(+), 23 deletions(-) diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index 9bd3bad55..d6f29c2b5 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -42,20 +42,4 @@ pub enum IPVersion { #[derive(Hash, Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub struct NumberOfBytes(pub i64); -/// The database management system used by the tracker. -/// -/// Refer to: -/// -/// - [Torrust Tracker Configuration](https://docs.rs/torrust-tracker-configuration). -/// - [Torrust Tracker](https://docs.rs/torrust-tracker). -/// -/// For more information about persistence. -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, derive_more::Display, Clone)] -pub enum DatabaseDriver { - /// The Sqlite3 database driver. - Sqlite3, - /// The `MySQL` database driver. - MySQL, -} - pub type PersistentTorrents = BTreeMap; diff --git a/src/core/databases/driver.rs b/src/core/databases/driver.rs index 99d96c6b1..f6c7aeb08 100644 --- a/src/core/databases/driver.rs +++ b/src/core/databases/driver.rs @@ -2,20 +2,37 @@ //! //! See [`databases::driver::build`](crate::core::databases::driver::build) //! function for more information. -use torrust_tracker_primitives::DatabaseDriver; +use serde::{Deserialize, Serialize}; use super::error::Error; use super::mysql::Mysql; use super::sqlite::Sqlite; use super::{Builder, Database}; +/// The database management system used by the tracker. +/// +/// Refer to: +/// +/// - [Torrust Tracker Configuration](https://docs.rs/torrust-tracker-configuration). +/// - [Torrust Tracker](https://docs.rs/torrust-tracker). +/// +/// For more information about persistence. +#[allow(clippy::module_name_repetitions)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, derive_more::Display, Clone)] +pub enum DatabaseDriver { + /// The Sqlite3 database driver. + Sqlite3, + /// The `MySQL` database driver. + MySQL, +} + /// It builds a new database driver. /// /// Example for `SQLite3`: /// /// ```rust,no_run /// use torrust_tracker::core::databases; -/// use torrust_tracker_primitives::DatabaseDriver; +/// use torrust_tracker::core::databases::driver::DatabaseDriver; /// /// let db_driver = DatabaseDriver::Sqlite3; /// let db_path = "./storage/tracker/lib/database/sqlite3.db".to_string(); @@ -26,7 +43,7 @@ use super::{Builder, Database}; /// /// ```rust,no_run /// use torrust_tracker::core::databases; -/// use torrust_tracker_primitives::DatabaseDriver; +/// use torrust_tracker::core::databases::driver::DatabaseDriver; /// /// let db_driver = DatabaseDriver::MySQL; /// let db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker".to_string(); diff --git a/src/core/databases/error.rs b/src/core/databases/error.rs index a5179e3a4..315d1343a 100644 --- a/src/core/databases/error.rs +++ b/src/core/databases/error.rs @@ -6,7 +6,8 @@ use std::sync::Arc; use r2d2_mysql::mysql::UrlError; use torrust_tracker_located_error::{DynError, Located, LocatedError}; -use torrust_tracker_primitives::DatabaseDriver; + +use super::driver::DatabaseDriver; #[derive(thiserror::Error, Debug, Clone)] pub enum Error { diff --git a/src/core/databases/mysql.rs b/src/core/databases/mysql.rs index ebb002d31..e16929a04 100644 --- a/src/core/databases/mysql.rs +++ b/src/core/databases/mysql.rs @@ -8,9 +8,10 @@ use r2d2_mysql::mysql::prelude::Queryable; use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MySqlConnectionManager; use torrust_tracker_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::{DatabaseDriver, PersistentTorrents}; +use torrust_tracker_primitives::PersistentTorrents; use tracing::debug; +use super::driver::DatabaseDriver; use super::{Database, Error}; use crate::core::auth::{self, Key}; use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; diff --git a/src/core/databases/sqlite.rs b/src/core/databases/sqlite.rs index 53a01f80c..93bf1f9a1 100644 --- a/src/core/databases/sqlite.rs +++ b/src/core/databases/sqlite.rs @@ -6,8 +6,9 @@ use async_trait::async_trait; use r2d2::Pool; use r2d2_sqlite::SqliteConnectionManager; use torrust_tracker_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::{DatabaseDriver, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrents}; +use super::driver::DatabaseDriver; use super::{Database, Error}; use crate::core::auth::{self, Key}; diff --git a/src/core/mod.rs b/src/core/mod.rs index 57cf56bca..c70d81fed 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -453,15 +453,16 @@ use std::panic::Location; use std::sync::Arc; use std::time::Duration; +use databases::driver::DatabaseDriver; use derive_more::Constructor; use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::v2::database; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DatabaseDriver}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; use tracing::debug; From d970bb873d972903dbe06dbbeb9341e6dc78201f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 5 Jul 2024 10:15:00 +0100 Subject: [PATCH 0434/1297] refactor: [#950] rename DatabaseDriver to Driver --- src/core/databases/driver.rs | 17 ++++++++--------- src/core/databases/error.rs | 26 +++++++++++++------------- src/core/databases/mysql.rs | 4 ++-- src/core/databases/sqlite.rs | 6 +++--- src/core/mod.rs | 6 +++--- 5 files changed, 29 insertions(+), 30 deletions(-) diff --git a/src/core/databases/driver.rs b/src/core/databases/driver.rs index f6c7aeb08..a456a2650 100644 --- a/src/core/databases/driver.rs +++ b/src/core/databases/driver.rs @@ -17,9 +17,8 @@ use super::{Builder, Database}; /// - [Torrust Tracker](https://docs.rs/torrust-tracker). /// /// For more information about persistence. -#[allow(clippy::module_name_repetitions)] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, derive_more::Display, Clone)] -pub enum DatabaseDriver { +pub enum Driver { /// The Sqlite3 database driver. Sqlite3, /// The `MySQL` database driver. @@ -32,9 +31,9 @@ pub enum DatabaseDriver { /// /// ```rust,no_run /// use torrust_tracker::core::databases; -/// use torrust_tracker::core::databases::driver::DatabaseDriver; +/// use torrust_tracker::core::databases::driver::Driver; /// -/// let db_driver = DatabaseDriver::Sqlite3; +/// let db_driver = Driver::Sqlite3; /// let db_path = "./storage/tracker/lib/database/sqlite3.db".to_string(); /// let database = databases::driver::build(&db_driver, &db_path); /// ``` @@ -43,9 +42,9 @@ pub enum DatabaseDriver { /// /// ```rust,no_run /// use torrust_tracker::core::databases; -/// use torrust_tracker::core::databases::driver::DatabaseDriver; +/// use torrust_tracker::core::databases::driver::Driver; /// -/// let db_driver = DatabaseDriver::MySQL; +/// let db_driver = Driver::MySQL; /// let db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker".to_string(); /// let database = databases::driver::build(&db_driver, &db_path); /// ``` @@ -62,10 +61,10 @@ pub enum DatabaseDriver { /// # Panics /// /// This function will panic if unable to create database tables. -pub fn build(driver: &DatabaseDriver, db_path: &str) -> Result, Error> { +pub fn build(driver: &Driver, db_path: &str) -> Result, Error> { let database = match driver { - DatabaseDriver::Sqlite3 => Builder::::build(db_path), - DatabaseDriver::MySQL => Builder::::build(db_path), + Driver::Sqlite3 => Builder::::build(db_path), + Driver::MySQL => Builder::::build(db_path), }?; database.create_database_tables().expect("Could not create database tables."); diff --git a/src/core/databases/error.rs b/src/core/databases/error.rs index 315d1343a..4d64baf48 100644 --- a/src/core/databases/error.rs +++ b/src/core/databases/error.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use r2d2_mysql::mysql::UrlError; use torrust_tracker_located_error::{DynError, Located, LocatedError}; -use super::driver::DatabaseDriver; +use super::driver::Driver; #[derive(thiserror::Error, Debug, Clone)] pub enum Error { @@ -15,21 +15,21 @@ pub enum Error { #[error("The {driver} query unexpectedly returned nothing: {source}")] QueryReturnedNoRows { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - driver: DatabaseDriver, + driver: Driver, }, /// The query was malformed. #[error("The {driver} query was malformed: {source}")] InvalidQuery { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - driver: DatabaseDriver, + driver: Driver, }, /// Unable to insert a record into the database #[error("Unable to insert record into {driver} database, {location}")] InsertFailed { location: &'static Location<'static>, - driver: DatabaseDriver, + driver: Driver, }, /// Unable to delete a record into the database @@ -37,21 +37,21 @@ pub enum Error { DeleteFailed { location: &'static Location<'static>, error_code: usize, - driver: DatabaseDriver, + driver: Driver, }, /// Unable to connect to the database #[error("Failed to connect to {driver} database: {source}")] ConnectionError { source: LocatedError<'static, UrlError>, - driver: DatabaseDriver, + driver: Driver, }, /// Unable to create a connection pool #[error("Failed to create r2d2 {driver} connection pool: {source}")] ConnectionPool { source: LocatedError<'static, r2d2::Error>, - driver: DatabaseDriver, + driver: Driver, }, } @@ -61,11 +61,11 @@ impl From for Error { match err { r2d2_sqlite::rusqlite::Error::QueryReturnedNoRows => Error::QueryReturnedNoRows { source: (Arc::new(err) as DynError).into(), - driver: DatabaseDriver::Sqlite3, + driver: Driver::Sqlite3, }, _ => Error::InvalidQuery { source: (Arc::new(err) as DynError).into(), - driver: DatabaseDriver::Sqlite3, + driver: Driver::Sqlite3, }, } } @@ -77,7 +77,7 @@ impl From for Error { let e: DynError = Arc::new(err); Error::InvalidQuery { source: e.into(), - driver: DatabaseDriver::MySQL, + driver: Driver::MySQL, } } } @@ -87,14 +87,14 @@ impl From for Error { fn from(err: UrlError) -> Self { Self::ConnectionError { source: Located(err).into(), - driver: DatabaseDriver::MySQL, + driver: Driver::MySQL, } } } -impl From<(r2d2::Error, DatabaseDriver)> for Error { +impl From<(r2d2::Error, Driver)> for Error { #[track_caller] - fn from(e: (r2d2::Error, DatabaseDriver)) -> Self { + fn from(e: (r2d2::Error, Driver)) -> Self { let (err, driver) = e; Self::ConnectionPool { source: Located(err).into(), diff --git a/src/core/databases/mysql.rs b/src/core/databases/mysql.rs index e16929a04..c6094cd8f 100644 --- a/src/core/databases/mysql.rs +++ b/src/core/databases/mysql.rs @@ -11,12 +11,12 @@ use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::PersistentTorrents; use tracing::debug; -use super::driver::DatabaseDriver; +use super::driver::Driver; use super::{Database, Error}; use crate::core::auth::{self, Key}; use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; -const DRIVER: DatabaseDriver = DatabaseDriver::MySQL; +const DRIVER: Driver = Driver::MySQL; pub struct Mysql { pool: Pool, diff --git a/src/core/databases/sqlite.rs b/src/core/databases/sqlite.rs index 93bf1f9a1..071a824c5 100644 --- a/src/core/databases/sqlite.rs +++ b/src/core/databases/sqlite.rs @@ -8,11 +8,11 @@ use r2d2_sqlite::SqliteConnectionManager; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrents}; -use super::driver::DatabaseDriver; +use super::driver::Driver; use super::{Database, Error}; use crate::core::auth::{self, Key}; -const DRIVER: DatabaseDriver = DatabaseDriver::Sqlite3; +const DRIVER: Driver = Driver::Sqlite3; pub struct Sqlite { pool: Pool, @@ -29,7 +29,7 @@ impl Database for Sqlite { /// Will return `r2d2::Error` if `db_path` is not able to create `SqLite` database. fn new(db_path: &str) -> Result { let cm = SqliteConnectionManager::file(db_path); - Pool::new(cm).map_or_else(|err| Err((err, DatabaseDriver::Sqlite3).into()), |pool| Ok(Sqlite { pool })) + Pool::new(cm).map_or_else(|err| Err((err, Driver::Sqlite3).into()), |pool| Ok(Sqlite { pool })) } /// Refer to [`databases::Database::create_database_tables`](crate::core::databases::Database::create_database_tables). diff --git a/src/core/mod.rs b/src/core/mod.rs index c70d81fed..ce6189157 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -453,7 +453,7 @@ use std::panic::Location; use std::sync::Arc; use std::time::Duration; -use databases::driver::DatabaseDriver; +use databases::driver::Driver; use derive_more::Constructor; use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; @@ -567,8 +567,8 @@ impl Tracker { stats_repository: statistics::Repo, ) -> Result { let driver = match config.database.driver { - database::Driver::Sqlite3 => DatabaseDriver::Sqlite3, - database::Driver::MySQL => DatabaseDriver::MySQL, + database::Driver::Sqlite3 => Driver::Sqlite3, + database::Driver::MySQL => Driver::MySQL, }; let database = Arc::new(databases::driver::build(&driver, &config.database.path)?); From 9d72f5159887e21ff98b5fcb29ce87c5c1c86ca9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 5 Jul 2024 10:21:47 +0100 Subject: [PATCH 0435/1297] feat: [#950] use lowercase for database driver values in configuration ```toml [core.database] driver = "sqlite3" ``` We are normalizing all enum variants in configration to lowercase. --- Containerfile | 2 +- compose.yaml | 2 +- docs/containers.md | 4 ++-- packages/configuration/src/v2/database.rs | 8 +++----- packages/configuration/src/v2/mod.rs | 4 ++-- share/container/entry_script_sh | 6 +++--- share/default/config/tracker.container.mysql.toml | 2 +- src/core/mod.rs | 2 +- src/lib.rs | 2 +- 9 files changed, 15 insertions(+), 17 deletions(-) diff --git a/Containerfile b/Containerfile index d55d2f300..d302e5c66 100644 --- a/Containerfile +++ b/Containerfile @@ -96,7 +96,7 @@ RUN ["/busybox/cp", "-sp", "/busybox/sh","/busybox/cat","/busybox/ls","/busybox/ COPY --from=gcc --chmod=0555 /usr/local/bin/su-exec /bin/su-exec ARG TORRUST_TRACKER_CONFIG_TOML_PATH="/etc/torrust/tracker/tracker.toml" -ARG TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER="Sqlite3" +ARG TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER="sqlite3" ARG USER_ID=1000 ARG UDP_PORT=6969 ARG HTTP_PORT=7070 diff --git a/compose.yaml b/compose.yaml index cab5c6d5e..c2e7c63bd 100644 --- a/compose.yaml +++ b/compose.yaml @@ -4,7 +4,7 @@ services: image: torrust-tracker:release tty: true environment: - - TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER:-MySQL} + - TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER=${TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER:-mysql} - TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN=${TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN:-MyAccessToken} networks: - server_side diff --git a/docs/containers.md b/docs/containers.md index 82c67c26e..cddd2ba98 100644 --- a/docs/containers.md +++ b/docs/containers.md @@ -149,7 +149,7 @@ The following environmental variables can be set: - `TORRUST_TRACKER_CONFIG_TOML_PATH` - The in-container path to the tracker configuration file, (default: `"/etc/torrust/tracker/tracker.toml"`). - `TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN` - Override of the admin token. If set, this value overrides any value set in the config. -- `TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER` - The database type used for the container, (options: `Sqlite3`, `MySQL`, default `Sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. +- `TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER` - The database type used for the container, (options: `sqlite3`, `mysql`, default `sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. - `TORRUST_TRACKER_CONFIG_TOML` - Load config from this environmental variable instead from a file, (i.e: `TORRUST_TRACKER_CONFIG_TOML=$(cat tracker-tracker.toml)`). - `USER_ID` - The user id for the runtime crated `torrust` user. Please Note: This user id should match the ownership of the host-mapped volumes, (default `1000`). - `UDP_PORT` - The port for the UDP tracker. This should match the port used in the configuration, (default `6969`). @@ -244,7 +244,7 @@ The docker-compose configuration includes the MySQL service configuration. If yo ```toml [core.database] -driver = "MySQL" +driver = "mysql" path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" ``` diff --git a/packages/configuration/src/v2/database.rs b/packages/configuration/src/v2/database.rs index ef462556d..c2b24d809 100644 --- a/packages/configuration/src/v2/database.rs +++ b/packages/configuration/src/v2/database.rs @@ -5,12 +5,12 @@ use url::Url; #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct Database { // Database configuration - /// Database driver. Possible values are: `Sqlite3`, and `MySQL`. + /// Database driver. Possible values are: `sqlite3`, and `mysql`. #[serde(default = "Database::default_driver")] pub driver: Driver, /// Database connection string. The format depends on the database driver. - /// For `Sqlite3`, the format is `path/to/database.db`, for example: + /// For `sqlite3`, the format is `path/to/database.db`, for example: /// `./storage/tracker/lib/database/sqlite3.db`. /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for /// example: `mysql://root:password@localhost:3306/torrust`. @@ -57,10 +57,8 @@ impl Database { /// The database management system used by the tracker. #[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Clone)] +#[serde(rename_all = "lowercase")] pub enum Driver { - // todo: - // - Rename serialized values to lowercase: `sqlite3` and `mysql`. - // - Add serde default values. /// The `Sqlite3` database driver. Sqlite3, /// The `MySQL` database driver. diff --git a/packages/configuration/src/v2/mod.rs b/packages/configuration/src/v2/mod.rs index 141bab00f..35c8b1070 100644 --- a/packages/configuration/src/v2/mod.rs +++ b/packages/configuration/src/v2/mod.rs @@ -209,7 +209,7 @@ //! interval_min = 120 //! //! [core.database] -//! driver = "Sqlite3" +//! driver = "sqlite3" //! path = "./storage/tracker/lib/database/sqlite3.db" //! //! [core.net] @@ -420,7 +420,7 @@ mod tests { interval_min = 120 [core.database] - driver = "Sqlite3" + driver = "sqlite3" path = "./storage/tracker/lib/database/sqlite3.db" [core.net] diff --git a/share/container/entry_script_sh b/share/container/entry_script_sh index 0668114fd..32cdfe33d 100644 --- a/share/container/entry_script_sh +++ b/share/container/entry_script_sh @@ -27,7 +27,7 @@ chmod -R 2770 /var/lib/torrust /var/log/torrust /etc/torrust # Install the database and config: if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" ]; then - if cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" "Sqlite3"; then + if cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" "sqlite3"; then # Select Sqlite3 empty database default_database="/usr/share/torrust/default/database/tracker.sqlite3.db" @@ -35,7 +35,7 @@ if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" ]; then # Select Sqlite3 default configuration default_config="/usr/share/torrust/default/config/tracker.container.sqlite3.toml" - elif cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" "MySQL"; then + elif cmp_lc "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" "mysql"; then # (no database file needed for MySQL) @@ -44,7 +44,7 @@ if [ -n "$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER" ]; then else echo "Error: Unsupported Database Type: \"$TORRUST_TRACKER_CONFIG_OVERRIDE_CORE__DATABASE__DRIVER\"." - echo "Please Note: Supported Database Types: \"Sqlite3\", \"MySQL\"." + echo "Please Note: Supported Database Types: \"sqlite3\", \"mysql\"." exit 1 fi else diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml index 9465c0ef8..1c84fb2e2 100644 --- a/share/default/config/tracker.container.mysql.toml +++ b/share/default/config/tracker.container.mysql.toml @@ -1,7 +1,7 @@ version = "2" [core.database] -driver = "MySQL" +driver = "mysql" path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" # Uncomment to enable services diff --git a/src/core/mod.rs b/src/core/mod.rs index ce6189157..ee90cea39 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -326,7 +326,7 @@ //! interval_min = 120 //! //! [core.database] -//! driver = "Sqlite3" +//! driver = "sqlite3" //! path = "./storage/tracker/lib/database/sqlite3.db" //! //! [core.net] diff --git a/src/lib.rs b/src/lib.rs index 9776345b0..d242ac80e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -181,7 +181,7 @@ //! interval_min = 120 //! //! [core.database] -//! driver = "Sqlite3" +//! driver = "sqlite3" //! path = "./storage/tracker/lib/database/sqlite3.db" //! //! [core.net] From ca348a839867ec56a66b0ce8abfd714d7633ede8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 5 Jul 2024 10:31:11 +0100 Subject: [PATCH 0436/1297] chore: remove unused dependency --- Cargo.lock | 1 - packages/configuration/Cargo.toml | 1 - 2 files changed, 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4e25fc4c4..8ae3d20df 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4017,7 +4017,6 @@ dependencies = [ "thiserror", "toml", "torrust-tracker-located-error", - "torrust-tracker-primitives", "url", "uuid", ] diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 90c816344..ae9c64cfe 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -24,7 +24,6 @@ serde_with = "3" thiserror = "1" toml = "0" torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "../located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } url = "2.5.2" [dev-dependencies] From 019cf9ffdc327193f4c2e065e46a238ac76bdf1f Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 8 Jul 2024 16:21:37 +0200 Subject: [PATCH 0437/1297] udp: processor for requests --- src/servers/udp/handlers.rs | 6 +-- src/servers/udp/server/bound_socket.rs | 7 +-- src/servers/udp/server/launcher.rs | 65 ++----------------------- src/servers/udp/server/mod.rs | 1 + src/servers/udp/server/processor.rs | 66 ++++++++++++++++++++++++++ src/servers/udp/server/receiver.rs | 8 ++-- src/shared/bit_torrent/common.rs | 12 ----- 7 files changed, 81 insertions(+), 84 deletions(-) create mode 100644 src/servers/udp/server/processor.rs diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index f1f61ee6b..c6b2458e5 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -33,7 +33,7 @@ use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; /// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. -pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Arc, addr: SocketAddr) -> Response { +pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Tracker, local_addr: SocketAddr) -> Response { debug!("Handling Packets: {udp_request:?}"); let start_time = Instant::now(); @@ -47,7 +47,7 @@ pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Arc { - log_request(&request, &request_id, &addr); + log_request(&request, &request_id, &local_addr); let transaction_id = match &request { Request::Connect(connect_request) => connect_request.transaction_id, @@ -62,7 +62,7 @@ pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Arc, + socket: tokio::net::UdpSocket, } impl BoundSocket { @@ -30,9 +29,7 @@ impl BoundSocket { let local_addr = format!("udp://{addr}"); tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpSocket::new (bound)"); - Ok(Self { - socket: Arc::new(socket), - }) + Ok(Self { socket }) } /// # Panics diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index bb7c7d70f..7b40f6604 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -1,26 +1,23 @@ -use std::io::Cursor; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; -use aquatic_udp_protocol::Response; use derive_more::Constructor; use futures_util::StreamExt; use tokio::select; use tokio::sync::oneshot; use super::request_buffer::ActiveRequests; -use super::RawRequest; use crate::bootstrap::jobs::Started; use crate::core::Tracker; use crate::servers::logging::STARTED_ON; use crate::servers::registar::ServiceHealthCheckJob; use crate::servers::signals::{shutdown_signal_with_message, Halted}; use crate::servers::udp::server::bound_socket::BoundSocket; +use crate::servers::udp::server::processor::Processor; use crate::servers::udp::server::receiver::Receiver; -use crate::servers::udp::{handlers, UDP_TRACKER_LOG_TARGET}; +use crate::servers::udp::UDP_TRACKER_LOG_TARGET; use crate::shared::bit_torrent::tracker::udp::client::check; -use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; /// A UDP server instance launcher. #[derive(Constructor)] @@ -109,6 +106,8 @@ impl Launcher { let local_addr = format!("udp://{addr}"); loop { + let processor = Processor::new(receiver.socket.clone(), tracker.clone()); + if let Some(req) = { tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server (wait for request)"); receiver.next().await @@ -138,9 +137,7 @@ impl Launcher { // are only adding and removing tasks without given them the // chance to finish. However, the buffer is yielding before // aborting one tasks, giving it the chance to finish. - let abort_handle: tokio::task::AbortHandle = - tokio::task::spawn(Launcher::process_request(req, tracker.clone(), receiver.bound_socket.clone())) - .abort_handle(); + let abort_handle: tokio::task::AbortHandle = tokio::task::spawn(processor.process_request(req)).abort_handle(); if abort_handle.is_finished() { continue; @@ -156,56 +153,4 @@ impl Launcher { } } } - - async fn process_request(request: RawRequest, tracker: Arc, socket: Arc) { - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, request = %request.from, "Udp::process_request (receiving)"); - Self::process_valid_request(tracker, socket, request).await; - } - - async fn process_valid_request(tracker: Arc, socket: Arc, udp_request: RawRequest) { - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, "Udp::process_valid_request. Making Response to {udp_request:?}"); - let from = udp_request.from; - let response = handlers::handle_packet(udp_request, &tracker.clone(), socket.address()).await; - Self::send_response(&socket.clone(), from, response).await; - } - - async fn send_response(bound_socket: &Arc, to: SocketAddr, response: Response) { - let response_type = match &response { - Response::Connect(_) => "Connect".to_string(), - Response::AnnounceIpv4(_) => "AnnounceIpv4".to_string(), - Response::AnnounceIpv6(_) => "AnnounceIpv6".to_string(), - Response::Scrape(_) => "Scrape".to_string(), - Response::Error(e) => format!("Error: {e:?}"), - }; - - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, target = ?to, response_type, "Udp::send_response (sending)"); - - let buffer = vec![0u8; MAX_PACKET_SIZE]; - let mut cursor = Cursor::new(buffer); - - match response.write_bytes(&mut cursor) { - Ok(()) => { - #[allow(clippy::cast_possible_truncation)] - let position = cursor.position() as usize; - let inner = cursor.get_ref(); - - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count = &inner[..position].len(), "Udp::send_response (sending...)" ); - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count = &inner[..position].len(), payload = ?&inner[..position], "Udp::send_response (sending...)"); - - Self::send_packet(bound_socket, &to, &inner[..position]).await; - - tracing::trace!(target:UDP_TRACKER_LOG_TARGET, ?to, bytes_count = &inner[..position].len(), "Udp::send_response (sent)"); - } - Err(e) => { - tracing::error!(target: UDP_TRACKER_LOG_TARGET, ?to, response_type, err = %e, "Udp::send_response (error)"); - } - } - } - - async fn send_packet(bound_socket: &Arc, remote_addr: &SocketAddr, payload: &[u8]) { - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, to = %remote_addr, ?payload, "Udp::send_response (sending)"); - - // doesn't matter if it reaches or not - drop(bound_socket.send_to(payload, remote_addr).await); - } } diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index e3321f157..16133e21b 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -5,6 +5,7 @@ use super::RawRequest; pub mod bound_socket; pub mod launcher; +pub mod processor; pub mod receiver; pub mod request_buffer; pub mod spawner; diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs new file mode 100644 index 000000000..e633a2358 --- /dev/null +++ b/src/servers/udp/server/processor.rs @@ -0,0 +1,66 @@ +use std::io::Cursor; +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::Response; + +use super::bound_socket::BoundSocket; +use crate::core::Tracker; +use crate::servers::udp::{handlers, RawRequest, UDP_TRACKER_LOG_TARGET}; + +pub struct Processor { + socket: Arc, + tracker: Arc, +} + +impl Processor { + pub fn new(socket: Arc, tracker: Arc) -> Self { + Self { socket, tracker } + } + + pub async fn process_request(self, request: RawRequest) { + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, request = %request.from, "Udp::process_request (receiving)"); + + let from = request.from; + let response = handlers::handle_packet(request, &self.tracker, self.socket.address()).await; + self.send_response(from, response).await; + } + + async fn send_response(self, to: SocketAddr, response: Response) { + let response_type = match &response { + Response::Connect(_) => "Connect".to_string(), + Response::AnnounceIpv4(_) => "AnnounceIpv4".to_string(), + Response::AnnounceIpv6(_) => "AnnounceIpv6".to_string(), + Response::Scrape(_) => "Scrape".to_string(), + Response::Error(e) => format!("Error: {e:?}"), + }; + + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, target = ?to, response_type, "Udp::send_response (sending)"); + + let mut writer = Cursor::new(Vec::with_capacity(200)); + + match response.write_bytes(&mut writer) { + Ok(()) => { + let bytes_count = writer.get_ref().len(); + let payload = writer.get_ref(); + + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count, "Udp::send_response (sending...)" ); + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count, ?payload, "Udp::send_response (sending...)"); + + self.send_packet(&to, payload).await; + + tracing::trace!(target:UDP_TRACKER_LOG_TARGET, ?to, bytes_count, "Udp::send_response (sent)"); + } + Err(e) => { + tracing::error!(target: UDP_TRACKER_LOG_TARGET, ?to, response_type, err = %e, "Udp::send_response (error)"); + } + } + } + + async fn send_packet(&self, remote_addr: &SocketAddr, payload: &[u8]) { + tracing::trace!(target: UDP_TRACKER_LOG_TARGET, to = %remote_addr, ?payload, "Udp::send_response (sending)"); + + // doesn't matter if it reaches or not + drop(self.socket.send_to(payload, remote_addr).await); + } +} diff --git a/src/servers/udp/server/receiver.rs b/src/servers/udp/server/receiver.rs index 020ab7324..0176930a4 100644 --- a/src/servers/udp/server/receiver.rs +++ b/src/servers/udp/server/receiver.rs @@ -11,7 +11,7 @@ use super::RawRequest; use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; pub struct Receiver { - pub bound_socket: Arc, + pub socket: Arc, data: RefCell<[u8; MAX_PACKET_SIZE]>, } @@ -19,13 +19,13 @@ impl Receiver { #[must_use] pub fn new(bound_socket: Arc) -> Self { Receiver { - bound_socket, + socket: bound_socket, data: RefCell::new([0; MAX_PACKET_SIZE]), } } pub fn bound_socket_address(&self) -> SocketAddr { - self.bound_socket.address() + self.socket.address() } } @@ -36,7 +36,7 @@ impl Stream for Receiver { let mut buf = *self.data.borrow_mut(); let mut buf = tokio::io::ReadBuf::new(&mut buf); - let Poll::Ready(ready) = self.bound_socket.poll_recv_from(cx, &mut buf) else { + let Poll::Ready(ready) = self.socket.poll_recv_from(cx, &mut buf) else { return Poll::Pending; }; diff --git a/src/shared/bit_torrent/common.rs b/src/shared/bit_torrent/common.rs index 9625b88e7..3dd059a6a 100644 --- a/src/shared/bit_torrent/common.rs +++ b/src/shared/bit_torrent/common.rs @@ -1,7 +1,6 @@ //! `BitTorrent` protocol primitive types //! //! [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -use serde::{Deserialize, Serialize}; /// The maximum number of torrents that can be returned in an `scrape` response. /// @@ -21,14 +20,3 @@ pub const MAX_SCRAPE_TORRENTS: u8 = 74; /// See function to [`generate`](crate::core::auth::generate) the /// [`ExpiringKeys`](crate::core::auth::ExpiringKey) for more information. pub const AUTH_KEY_LENGTH: usize = 32; - -#[repr(u32)] -#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] -enum Actions { - // todo: it seems this enum is not used anywhere. Values match the ones in - // aquatic_udp_protocol::request::Request::from_bytes. - Connect = 0, - Announce = 1, - Scrape = 2, - Error = 3, -} From 64850aff2d29ce368f7c2be2edb7c4c7b789441d Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 13 Jul 2024 13:04:42 +0200 Subject: [PATCH 0438/1297] dev: remove async trait dep --- Cargo.lock | 1 - Cargo.toml | 1 - src/core/databases/mod.rs | 28 +++---- src/core/databases/mysql.rs | 22 +++-- src/core/databases/sqlite.rs | 22 +++-- src/core/mod.rs | 82 +++++++++---------- src/core/services/torrent.rs | 16 ++-- src/core/statistics.rs | 11 ++- .../http/v1/extractors/announce_request.rs | 24 ++++-- .../http/v1/extractors/authentication_key.rs | 30 +++++-- .../http/v1/extractors/client_ip_sources.rs | 42 ++++++---- .../http/v1/extractors/scrape_request.rs | 24 ++++-- src/servers/http/v1/services/announce.rs | 2 +- src/servers/http/v1/services/scrape.rs | 4 +- src/servers/udp/handlers.rs | 16 ++-- tests/servers/api/environment.rs | 4 +- .../servers/api/v1/contract/context/stats.rs | 3 +- .../api/v1/contract/context/torrent.rs | 18 ++-- tests/servers/http/environment.rs | 4 +- tests/servers/http/v1/contract.rs | 33 +++----- tests/servers/udp/environment.rs | 4 +- 21 files changed, 208 insertions(+), 183 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8ae3d20df..83b3781dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3939,7 +3939,6 @@ version = "3.0.0-alpha.12-develop" dependencies = [ "anyhow", "aquatic_udp_protocol", - "async-trait", "axum", "axum-client-ip", "axum-extra", diff --git a/Cargo.toml b/Cargo.toml index 41afb1538..ed2de33e8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,6 @@ version = "3.0.0-alpha.12-develop" [dependencies] anyhow = "1" aquatic_udp_protocol = "0" -async-trait = "0" axum = { version = "0", features = ["macros"] } axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } diff --git a/src/core/databases/mod.rs b/src/core/databases/mod.rs index e3fb9ad60..cdb4c7ce5 100644 --- a/src/core/databases/mod.rs +++ b/src/core/databases/mod.rs @@ -50,7 +50,6 @@ pub mod sqlite; use std::marker::PhantomData; -use async_trait::async_trait; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::PersistentTorrents; @@ -79,7 +78,6 @@ where } /// The persistence trait. It contains all the methods to interact with the database. -#[async_trait] pub trait Database: Sync + Send { /// It instantiates a new database driver. /// @@ -126,7 +124,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to load. - async fn load_persistent_torrents(&self) -> Result; + fn load_persistent_torrents(&self) -> Result; /// It saves the torrent metrics data into the database. /// @@ -135,7 +133,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to save. - async fn save_persistent_torrent(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error>; + fn save_persistent_torrent(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error>; // Whitelist @@ -146,7 +144,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to load. - async fn load_whitelist(&self) -> Result, Error>; + fn load_whitelist(&self) -> Result, Error>; /// It checks if the torrent is whitelisted. /// @@ -157,7 +155,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to load. - async fn get_info_hash_from_whitelist(&self, info_hash: &InfoHash) -> Result, Error>; + fn get_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result, Error>; /// It adds the torrent to the whitelist. /// @@ -166,7 +164,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to save. - async fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result; + fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result; /// It checks if the torrent is whitelisted. /// @@ -175,8 +173,8 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to load. - async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> Result { - Ok(self.get_info_hash_from_whitelist(info_hash).await?.is_some()) + fn is_info_hash_whitelisted(&self, info_hash: InfoHash) -> Result { + Ok(self.get_info_hash_from_whitelist(info_hash)?.is_some()) } /// It removes the torrent from the whitelist. @@ -186,7 +184,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to save. - async fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result; + fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result; // Authentication keys @@ -197,19 +195,19 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to load. - async fn load_keys(&self) -> Result, Error>; + fn load_keys(&self) -> Result, Error>; /// It gets an expiring authentication key from the database. /// /// It returns `Some(ExpiringKey)` if a [`ExpiringKey`](crate::core::auth::ExpiringKey) - /// with the input [`Key`](crate::core::auth::Key) exists, `None` otherwise. + /// with the input [`Key`] exists, `None` otherwise. /// /// # Context: Authentication Keys /// /// # Errors /// /// Will return `Err` if unable to load. - async fn get_key_from_keys(&self, key: &Key) -> Result, Error>; + fn get_key_from_keys(&self, key: &Key) -> Result, Error>; /// It adds an expiring authentication key to the database. /// @@ -218,7 +216,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to save. - async fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result; + fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result; /// It removes an expiring authentication key from the database. /// @@ -227,5 +225,5 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to load. - async fn remove_key_from_keys(&self, key: &Key) -> Result; + fn remove_key_from_keys(&self, key: &Key) -> Result; } diff --git a/src/core/databases/mysql.rs b/src/core/databases/mysql.rs index c6094cd8f..40eced900 100644 --- a/src/core/databases/mysql.rs +++ b/src/core/databases/mysql.rs @@ -2,7 +2,6 @@ use std::str::FromStr; use std::time::Duration; -use async_trait::async_trait; use r2d2::Pool; use r2d2_mysql::mysql::prelude::Queryable; use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; @@ -22,7 +21,6 @@ pub struct Mysql { pool: Pool, } -#[async_trait] impl Database for Mysql { /// It instantiates a new `MySQL` database driver. /// @@ -106,7 +104,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::load_persistent_torrents`](crate::core::databases::Database::load_persistent_torrents). - async fn load_persistent_torrents(&self) -> Result { + fn load_persistent_torrents(&self) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let torrents = conn.query_map( @@ -121,7 +119,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). - async fn load_keys(&self) -> Result, Error> { + fn load_keys(&self) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let keys = conn.query_map( @@ -136,7 +134,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::load_whitelist`](crate::core::databases::Database::load_whitelist). - async fn load_whitelist(&self) -> Result, Error> { + fn load_whitelist(&self) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let info_hashes = conn.query_map("SELECT info_hash FROM whitelist", |info_hash: String| { @@ -147,7 +145,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::save_persistent_torrent`](crate::core::databases::Database::save_persistent_torrent). - async fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { + fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { const COMMAND : &str = "INSERT INTO torrents (info_hash, completed) VALUES (:info_hash_str, :completed) ON DUPLICATE KEY UPDATE completed = VALUES(completed)"; let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -160,7 +158,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::get_info_hash_from_whitelist`](crate::core::databases::Database::get_info_hash_from_whitelist). - async fn get_info_hash_from_whitelist(&self, info_hash: &InfoHash) -> Result, Error> { + fn get_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let select = conn.exec_first::( @@ -174,7 +172,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::add_info_hash_to_whitelist`](crate::core::databases::Database::add_info_hash_to_whitelist). - async fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result { + fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let info_hash_str = info_hash.to_string(); @@ -188,7 +186,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::remove_info_hash_from_whitelist`](crate::core::databases::Database::remove_info_hash_from_whitelist). - async fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result { + fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let info_hash = info_hash.to_string(); @@ -199,7 +197,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::get_key_from_keys`](crate::core::databases::Database::get_key_from_keys). - async fn get_key_from_keys(&self, key: &Key) -> Result, Error> { + fn get_key_from_keys(&self, key: &Key) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let query = conn.exec_first::<(String, i64), _, _>( @@ -216,7 +214,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::add_key_to_keys`](crate::core::databases::Database::add_key_to_keys). - async fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result { + fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let key = auth_key.key.to_string(); @@ -231,7 +229,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::remove_key_from_keys`](crate::core::databases::Database::remove_key_from_keys). - async fn remove_key_from_keys(&self, key: &Key) -> Result { + fn remove_key_from_keys(&self, key: &Key) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; conn.exec_drop("DELETE FROM `keys` WHERE key = :key", params! { "key" => key.to_string() })?; diff --git a/src/core/databases/sqlite.rs b/src/core/databases/sqlite.rs index 071a824c5..3acbf9e77 100644 --- a/src/core/databases/sqlite.rs +++ b/src/core/databases/sqlite.rs @@ -2,7 +2,6 @@ use std::panic::Location; use std::str::FromStr; -use async_trait::async_trait; use r2d2::Pool; use r2d2_sqlite::SqliteConnectionManager; use torrust_tracker_primitives::info_hash::InfoHash; @@ -18,7 +17,6 @@ pub struct Sqlite { pool: Pool, } -#[async_trait] impl Database for Sqlite { /// It instantiates a new `SQLite3` database driver. /// @@ -90,7 +88,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::load_persistent_torrents`](crate::core::databases::Database::load_persistent_torrents). - async fn load_persistent_torrents(&self) -> Result { + fn load_persistent_torrents(&self) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT info_hash, completed FROM torrents")?; @@ -106,7 +104,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). - async fn load_keys(&self) -> Result, Error> { + fn load_keys(&self) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT key, valid_until FROM keys")?; @@ -127,7 +125,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::load_whitelist`](crate::core::databases::Database::load_whitelist). - async fn load_whitelist(&self) -> Result, Error> { + fn load_whitelist(&self) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT info_hash FROM whitelist")?; @@ -144,7 +142,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::save_persistent_torrent`](crate::core::databases::Database::save_persistent_torrent). - async fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { + fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let insert = conn.execute( @@ -163,7 +161,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::get_info_hash_from_whitelist`](crate::core::databases::Database::get_info_hash_from_whitelist). - async fn get_info_hash_from_whitelist(&self, info_hash: &InfoHash) -> Result, Error> { + fn get_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT info_hash FROM whitelist WHERE info_hash = ?")?; @@ -176,7 +174,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::add_info_hash_to_whitelist`](crate::core::databases::Database::add_info_hash_to_whitelist). - async fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result { + fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let insert = conn.execute("INSERT INTO whitelist (info_hash) VALUES (?)", [info_hash.to_string()])?; @@ -192,7 +190,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::remove_info_hash_from_whitelist`](crate::core::databases::Database::remove_info_hash_from_whitelist). - async fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result { + fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let deleted = conn.execute("DELETE FROM whitelist WHERE info_hash = ?", [info_hash.to_string()])?; @@ -210,7 +208,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::get_key_from_keys`](crate::core::databases::Database::get_key_from_keys). - async fn get_key_from_keys(&self, key: &Key) -> Result, Error> { + fn get_key_from_keys(&self, key: &Key) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT key, valid_until FROM keys WHERE key = ?")?; @@ -230,7 +228,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::add_key_to_keys`](crate::core::databases::Database::add_key_to_keys). - async fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result { + fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let insert = conn.execute( @@ -249,7 +247,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::remove_key_from_keys`](crate::core::databases::Database::remove_key_from_keys). - async fn remove_key_from_keys(&self, key: &Key) -> Result { + fn remove_key_from_keys(&self, key: &Key) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let deleted = conn.execute("DELETE FROM keys WHERE key = ?", [key.to_string()])?; diff --git a/src/core/mod.rs b/src/core/mod.rs index ee90cea39..64d5e2c9a 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -622,7 +622,7 @@ impl Tracker { /// # Context: Tracker /// /// BEP 03: [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html). - pub async fn announce(&self, info_hash: &InfoHash, peer: &mut peer::Peer, remote_client_ip: &IpAddr) -> AnnounceData { + pub fn announce(&self, info_hash: &InfoHash, peer: &mut peer::Peer, remote_client_ip: &IpAddr) -> AnnounceData { // code-review: maybe instead of mutating the peer we could just return // a tuple with the new peer and the announce data: (Peer, AnnounceData). // It could even be a different struct: `StoredPeer` or `PublicPeer`. @@ -642,7 +642,7 @@ impl Tracker { peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); debug!("After: {peer:?}"); - let stats = self.upsert_peer_and_get_stats(info_hash, peer).await; + let stats = self.upsert_peer_and_get_stats(info_hash, peer); let peers = self.get_peers_for(info_hash, peer); @@ -688,8 +688,8 @@ impl Tracker { /// # Errors /// /// Will return a `database::Error` if unable to load the list of `persistent_torrents` from the database. - pub async fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { - let persistent_torrents = self.database.load_persistent_torrents().await?; + pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { + let persistent_torrents = self.database.load_persistent_torrents()?; self.torrents.import_persistent(&persistent_torrents); @@ -718,7 +718,7 @@ impl Tracker { /// needed for a `announce` request response. /// /// # Context: Tracker - pub async fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { + pub fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { let swarm_metadata_before = match self.torrents.get_swarm_metadata(info_hash) { Some(swarm_metadata) => swarm_metadata, None => SwarmMetadata::zeroed(), @@ -732,7 +732,7 @@ impl Tracker { }; if swarm_metadata_before != swarm_metadata_after { - self.persist_stats(info_hash, &swarm_metadata_after).await; + self.persist_stats(info_hash, &swarm_metadata_after); } swarm_metadata_after @@ -741,12 +741,12 @@ impl Tracker { /// It stores the torrents stats into the database (if persistency is enabled). /// /// # Context: Tracker - async fn persist_stats(&self, info_hash: &InfoHash, swarm_metadata: &SwarmMetadata) { + fn persist_stats(&self, info_hash: &InfoHash, swarm_metadata: &SwarmMetadata) { if self.config.tracker_policy.persistent_torrent_completed_stat { let completed = swarm_metadata.downloaded; let info_hash = *info_hash; - drop(self.database.save_persistent_torrent(&info_hash, completed).await); + drop(self.database.save_persistent_torrent(&info_hash, completed)); } } @@ -804,7 +804,7 @@ impl Tracker { /// Will return a `database::Error` if unable to add the `auth_key` to the database. pub async fn generate_auth_key(&self, lifetime: Duration) -> Result { let auth_key = auth::generate(lifetime); - self.database.add_key_to_keys(&auth_key).await?; + self.database.add_key_to_keys(&auth_key)?; self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); Ok(auth_key) } @@ -821,7 +821,7 @@ impl Tracker { /// /// Will panic if key cannot be converted into a valid `Key`. pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> { - self.database.remove_key_from_keys(key).await?; + self.database.remove_key_from_keys(key)?; self.keys.write().await.remove(key); Ok(()) } @@ -856,7 +856,7 @@ impl Tracker { /// /// Will return a `database::Error` if unable to `load_keys` from the database. pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> { - let keys_from_database = self.database.load_keys().await?; + let keys_from_database = self.database.load_keys()?; let mut keys = self.keys.write().await; keys.clear(); @@ -901,20 +901,20 @@ impl Tracker { /// /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.add_torrent_to_database_whitelist(info_hash).await?; + self.add_torrent_to_database_whitelist(info_hash)?; self.add_torrent_to_memory_whitelist(info_hash).await; Ok(()) } /// It adds a torrent to the whitelist if it has not been whitelisted previously - async fn add_torrent_to_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - let is_whitelisted = self.database.is_info_hash_whitelisted(info_hash).await?; + fn add_torrent_to_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; if is_whitelisted { return Ok(()); } - self.database.add_info_hash_to_whitelist(*info_hash).await?; + self.database.add_info_hash_to_whitelist(*info_hash)?; Ok(()) } @@ -932,7 +932,7 @@ impl Tracker { /// /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.remove_torrent_from_database_whitelist(info_hash).await?; + self.remove_torrent_from_database_whitelist(info_hash)?; self.remove_torrent_from_memory_whitelist(info_hash).await; Ok(()) } @@ -944,14 +944,14 @@ impl Tracker { /// # Errors /// /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. - pub async fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - let is_whitelisted = self.database.is_info_hash_whitelisted(info_hash).await?; + pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; if !is_whitelisted { return Ok(()); } - self.database.remove_info_hash_from_whitelist(*info_hash).await?; + self.database.remove_info_hash_from_whitelist(*info_hash)?; Ok(()) } @@ -978,7 +978,7 @@ impl Tracker { /// /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { - let whitelisted_torrents_from_database = self.database.load_whitelist().await?; + let whitelisted_torrents_from_database = self.database.load_whitelist()?; let mut whitelist = self.whitelist.write().await; whitelist.clear(); @@ -1173,7 +1173,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - tracker.upsert_peer_and_get_stats(&info_hash, &peer).await; + tracker.upsert_peer_and_get_stats(&info_hash, &peer); let peers = tracker.get_torrent_peers(&info_hash); @@ -1187,7 +1187,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - tracker.upsert_peer_and_get_stats(&info_hash, &peer).await; + tracker.upsert_peer_and_get_stats(&info_hash, &peer); let peers = tracker.get_peers_for(&info_hash, &peer); @@ -1198,7 +1198,7 @@ mod tests { async fn it_should_return_the_torrent_metrics() { let tracker = public_tracker(); - tracker.upsert_peer_and_get_stats(&sample_info_hash(), &leecher()).await; + tracker.upsert_peer_and_get_stats(&sample_info_hash(), &leecher()); let torrent_metrics = tracker.get_torrents_metrics(); @@ -1219,7 +1219,7 @@ mod tests { let start_time = std::time::Instant::now(); for i in 0..1_000_000 { - tracker.upsert_peer_and_get_stats(&gen_seeded_infohash(&i), &leecher()).await; + tracker.upsert_peer_and_get_stats(&gen_seeded_infohash(&i), &leecher()); } let result_a = start_time.elapsed(); @@ -1353,7 +1353,7 @@ mod tests { let mut peer = sample_peer(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; + let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()); assert_eq!(announce_data.peers, vec![]); } @@ -1363,12 +1363,10 @@ mod tests { let tracker = public_tracker(); let mut previously_announced_peer = sample_peer_1(); - tracker - .announce(&sample_info_hash(), &mut previously_announced_peer, &peer_ip()) - .await; + tracker.announce(&sample_info_hash(), &mut previously_announced_peer, &peer_ip()); let mut peer = sample_peer_2(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; + let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()); assert_eq!(announce_data.peers, vec![Arc::new(previously_announced_peer)]); } @@ -1385,7 +1383,7 @@ mod tests { let mut peer = seeder(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; + let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()); assert_eq!(announce_data.stats.complete, 1); } @@ -1396,7 +1394,7 @@ mod tests { let mut peer = leecher(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await; + let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()); assert_eq!(announce_data.stats.incomplete, 1); } @@ -1407,10 +1405,10 @@ mod tests { // We have to announce with "started" event because peer does not count if peer was not previously known let mut started_peer = started_peer(); - tracker.announce(&sample_info_hash(), &mut started_peer, &peer_ip()).await; + tracker.announce(&sample_info_hash(), &mut started_peer, &peer_ip()); let mut completed_peer = completed_peer(); - let announce_data = tracker.announce(&sample_info_hash(), &mut completed_peer, &peer_ip()).await; + let announce_data = tracker.announce(&sample_info_hash(), &mut completed_peer, &peer_ip()); assert_eq!(announce_data.stats.downloaded, 1); } @@ -1450,15 +1448,11 @@ mod tests { // Announce a "complete" peer for the torrent let mut complete_peer = complete_peer(); - tracker - .announce(&info_hash, &mut complete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10))) - .await; + tracker.announce(&info_hash, &mut complete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10))); // Announce an "incomplete" peer for the torrent let mut incomplete_peer = incomplete_peer(); - tracker - .announce(&info_hash, &mut incomplete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11))) - .await; + tracker.announce(&info_hash, &mut incomplete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11))); // Scrape let scrape_data = tracker.scrape(&vec![info_hash]).await; @@ -1606,11 +1600,11 @@ mod tests { let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); let mut peer = incomplete_peer(); - tracker.announce(&info_hash, &mut peer, &peer_ip()).await; + tracker.announce(&info_hash, &mut peer, &peer_ip()); // Announce twice to force non zeroed swarm metadata let mut peer = complete_peer(); - tracker.announce(&info_hash, &mut peer, &peer_ip()).await; + tracker.announce(&info_hash, &mut peer, &peer_ip()); let scrape_data = tracker.scrape(&vec![info_hash]).await; @@ -1743,17 +1737,17 @@ mod tests { let mut peer = sample_peer(); peer.event = AnnounceEvent::Started; - let swarm_stats = tracker.upsert_peer_and_get_stats(&info_hash, &peer).await; + let swarm_stats = tracker.upsert_peer_and_get_stats(&info_hash, &peer); assert_eq!(swarm_stats.downloaded, 0); peer.event = AnnounceEvent::Completed; - let swarm_stats = tracker.upsert_peer_and_get_stats(&info_hash, &peer).await; + let swarm_stats = tracker.upsert_peer_and_get_stats(&info_hash, &peer); assert_eq!(swarm_stats.downloaded, 1); // Remove the newly updated torrent from memory tracker.torrents.remove(&info_hash); - tracker.load_torrents_from_database().await.unwrap(); + tracker.load_torrents_from_database().unwrap(); let torrent_entry = tracker.torrents.get(&info_hash).expect("it should be able to get entry"); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 9cba5de25..1c337a41d 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -156,7 +156,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()).await; + tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()); let torrent_info = get_torrent_info(tracker.clone(), &info_hash).await.unwrap(); @@ -206,7 +206,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()).await; + tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -230,8 +230,8 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()).await; - tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()).await; + tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()); + tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); let offset = 0; let limit = 1; @@ -250,8 +250,8 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()).await; - tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()).await; + tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()); + tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); let offset = 1; let limit = 4000; @@ -276,11 +276,11 @@ mod tests { let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()).await; + tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()); let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()).await; + tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; diff --git a/src/core/statistics.rs b/src/core/statistics.rs index d7192f5d1..bcafda17f 100644 --- a/src/core/statistics.rs +++ b/src/core/statistics.rs @@ -19,7 +19,8 @@ //! See the [`statistics::Event`](crate::core::statistics::Event) enum to check which events are available. use std::sync::Arc; -use async_trait::async_trait; +use futures::future::BoxFuture; +use futures::FutureExt; #[cfg(test)] use mockall::{automock, predicate::str}; use tokio::sync::mpsc::error::SendError; @@ -185,10 +186,9 @@ async fn event_handler(event: Event, stats_repository: &Repo) { } /// A trait to allow sending statistics events -#[async_trait] #[cfg_attr(test, automock)] pub trait EventSender: Sync + Send { - async fn send_event(&self, event: Event) -> Option>>; + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; } /// An [`statistics::EventSender`](crate::core::statistics::EventSender) implementation. @@ -199,10 +199,9 @@ pub struct Sender { sender: mpsc::Sender, } -#[async_trait] impl EventSender for Sender { - async fn send_event(&self, event: Event) -> Option>> { - Some(self.sender.send(event).await) + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { + async move { Some(self.sender.send(event).await) }.boxed() } } diff --git a/src/servers/http/v1/extractors/announce_request.rs b/src/servers/http/v1/extractors/announce_request.rs index bf77f0608..d2612f79b 100644 --- a/src/servers/http/v1/extractors/announce_request.rs +++ b/src/servers/http/v1/extractors/announce_request.rs @@ -29,10 +29,11 @@ //! ``` use std::panic::Location; -use axum::async_trait; use axum::extract::FromRequestParts; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; +use futures::future::BoxFuture; +use futures::FutureExt; use crate::servers::http::v1::query::Query; use crate::servers::http::v1::requests::announce::{Announce, ParseAnnounceQueryError}; @@ -42,18 +43,29 @@ use crate::servers::http::v1::responses; /// request. pub struct ExtractRequest(pub Announce); -#[async_trait] impl FromRequestParts for ExtractRequest where S: Send + Sync, { type Rejection = Response; - async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { - match extract_announce_from(parts.uri.query()) { - Ok(announce_request) => Ok(ExtractRequest(announce_request)), - Err(error) => Err(error.into_response()), + #[must_use] + fn from_request_parts<'life0, 'life1, 'async_trait>( + parts: &'life0 mut Parts, + _state: &'life1 S, + ) -> BoxFuture<'async_trait, Result> + where + 'life0: 'async_trait, + 'life1: 'async_trait, + Self: 'async_trait, + { + async { + match extract_announce_from(parts.uri.query()) { + Ok(announce_request) => Ok(ExtractRequest(announce_request)), + Err(error) => Err(error.into_response()), + } } + .boxed() } } diff --git a/src/servers/http/v1/extractors/authentication_key.rs b/src/servers/http/v1/extractors/authentication_key.rs index 985e32371..e86241edf 100644 --- a/src/servers/http/v1/extractors/authentication_key.rs +++ b/src/servers/http/v1/extractors/authentication_key.rs @@ -44,11 +44,12 @@ //! > specifications specify any HTTP status code for authentication errors. use std::panic::Location; -use axum::async_trait; use axum::extract::rejection::PathRejection; use axum::extract::{FromRequestParts, Path}; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; +use futures::future::BoxFuture; +use futures::FutureExt; use serde::Deserialize; use crate::core::auth::Key; @@ -68,21 +69,32 @@ impl KeyParam { } } -#[async_trait] impl FromRequestParts for Extract where S: Send + Sync, { type Rejection = Response; - async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { - // Extract `key` from URL path with Axum `Path` extractor - let maybe_path_with_key = Path::::from_request_parts(parts, state).await; - - match extract_key(maybe_path_with_key) { - Ok(key) => Ok(Extract(key)), - Err(error) => Err(error.into_response()), + #[must_use] + fn from_request_parts<'life0, 'life1, 'async_trait>( + parts: &'life0 mut Parts, + state: &'life1 S, + ) -> BoxFuture<'async_trait, Result> + where + 'life0: 'async_trait, + 'life1: 'async_trait, + Self: 'async_trait, + { + async { + // Extract `key` from URL path with Axum `Path` extractor + let maybe_path_with_key = Path::::from_request_parts(parts, state).await; + + match extract_key(maybe_path_with_key) { + Ok(key) => Ok(Extract(key)), + Err(error) => Err(error.into_response()), + } } + .boxed() } } diff --git a/src/servers/http/v1/extractors/client_ip_sources.rs b/src/servers/http/v1/extractors/client_ip_sources.rs index 1c6cdc636..5b235fbe0 100644 --- a/src/servers/http/v1/extractors/client_ip_sources.rs +++ b/src/servers/http/v1/extractors/client_ip_sources.rs @@ -37,11 +37,12 @@ //! ``` use std::net::SocketAddr; -use axum::async_trait; use axum::extract::{ConnectInfo, FromRequestParts}; use axum::http::request::Parts; use axum::response::Response; use axum_client_ip::RightmostXForwardedFor; +use futures::future::BoxFuture; +use futures::FutureExt; use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; @@ -49,27 +50,38 @@ use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; /// struct. pub struct Extract(pub ClientIpSources); -#[async_trait] impl FromRequestParts for Extract where S: Send + Sync, { type Rejection = Response; - async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { - let right_most_x_forwarded_for = match RightmostXForwardedFor::from_request_parts(parts, state).await { - Ok(right_most_x_forwarded_for) => Some(right_most_x_forwarded_for.0), - Err(_) => None, - }; + #[must_use] + fn from_request_parts<'life0, 'life1, 'async_trait>( + parts: &'life0 mut Parts, + state: &'life1 S, + ) -> BoxFuture<'async_trait, Result> + where + 'life0: 'async_trait, + 'life1: 'async_trait, + Self: 'async_trait, + { + async { + let right_most_x_forwarded_for = match RightmostXForwardedFor::from_request_parts(parts, state).await { + Ok(right_most_x_forwarded_for) => Some(right_most_x_forwarded_for.0), + Err(_) => None, + }; - let connection_info_ip = match ConnectInfo::::from_request_parts(parts, state).await { - Ok(connection_info_socket_addr) => Some(connection_info_socket_addr.0.ip()), - Err(_) => None, - }; + let connection_info_ip = match ConnectInfo::::from_request_parts(parts, state).await { + Ok(connection_info_socket_addr) => Some(connection_info_socket_addr.0.ip()), + Err(_) => None, + }; - Ok(Extract(ClientIpSources { - right_most_x_forwarded_for, - connection_info_ip, - })) + Ok(Extract(ClientIpSources { + right_most_x_forwarded_for, + connection_info_ip, + })) + } + .boxed() } } diff --git a/src/servers/http/v1/extractors/scrape_request.rs b/src/servers/http/v1/extractors/scrape_request.rs index 35a8da5f8..07fa4ccb9 100644 --- a/src/servers/http/v1/extractors/scrape_request.rs +++ b/src/servers/http/v1/extractors/scrape_request.rs @@ -29,10 +29,11 @@ //! ``` use std::panic::Location; -use axum::async_trait; use axum::extract::FromRequestParts; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; +use futures::future::BoxFuture; +use futures::FutureExt; use crate::servers::http::v1::query::Query; use crate::servers::http::v1::requests::scrape::{ParseScrapeQueryError, Scrape}; @@ -42,18 +43,29 @@ use crate::servers::http::v1::responses; /// request. pub struct ExtractRequest(pub Scrape); -#[async_trait] impl FromRequestParts for ExtractRequest where S: Send + Sync, { type Rejection = Response; - async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { - match extract_scrape_from(parts.uri.query()) { - Ok(scrape_request) => Ok(ExtractRequest(scrape_request)), - Err(error) => Err(error.into_response()), + #[must_use] + fn from_request_parts<'life0, 'life1, 'async_trait>( + parts: &'life0 mut Parts, + _state: &'life1 S, + ) -> BoxFuture<'async_trait, Result> + where + 'life0: 'async_trait, + 'life1: 'async_trait, + Self: 'async_trait, + { + async { + match extract_scrape_from(parts.uri.query()) { + Ok(scrape_request) => Ok(ExtractRequest(scrape_request)), + Err(error) => Err(error.into_response()), + } } + .boxed() } } diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 47175817d..f5f730ae2 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -30,7 +30,7 @@ pub async fn invoke(tracker: Arc, info_hash: InfoHash, peer: &mut peer: let original_peer_ip = peer.peer_addr.ip(); // The tracker could change the original peer ip - let announce_data = tracker.announce(&info_hash, peer, &original_peer_ip).await; + let announce_data = tracker.announce(&info_hash, peer, &original_peer_ip); match original_peer_ip { IpAddr::V4(_) => { diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index ee7814194..b83abb321 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -119,7 +119,7 @@ mod tests { // Announce a new peer to force scrape data to contain not zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); - tracker.announce(&info_hash, &mut peer, &original_peer_ip).await; + tracker.announce(&info_hash, &mut peer, &original_peer_ip); let scrape_data = invoke(&tracker, &info_hashes, &original_peer_ip).await; @@ -210,7 +210,7 @@ mod tests { // Announce a new peer to force scrape data to contain not zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); - tracker.announce(&info_hash, &mut peer, &original_peer_ip).await; + tracker.announce(&info_hash, &mut peer, &original_peer_ip); let scrape_data = fake(&tracker, &info_hashes, &original_peer_ip).await; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index c6b2458e5..53683fbb9 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -164,7 +164,7 @@ pub async fn handle_announce( let mut peer = peer_builder::from_request(&wrapped_announce_request, &remote_client_ip); - let response = tracker.announce(&info_hash, &mut peer, &remote_client_ip).await; + let response = tracker.announce(&info_hash, &mut peer, &remote_client_ip); match remote_client_ip { IpAddr::V4(_) => { @@ -722,7 +722,7 @@ mod tests { assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); } - async fn add_a_torrent_peer_using_ipv6(tracker: Arc) { + fn add_a_torrent_peer_using_ipv6(tracker: &Arc) { let info_hash = AquaticInfoHash([0u8; 20]); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); @@ -735,7 +735,7 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); - tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv6).await; + tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv6); } async fn announce_a_new_peer_using_ipv4(tracker: Arc) -> Response { @@ -751,7 +751,7 @@ mod tests { async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { let tracker = public_tracker(); - add_a_torrent_peer_using_ipv6(tracker.clone()).await; + add_a_torrent_peer_using_ipv6(&tracker); let response = announce_a_new_peer_using_ipv4(tracker.clone()).await; @@ -954,7 +954,7 @@ mod tests { assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); } - async fn add_a_torrent_peer_using_ipv4(tracker: Arc) { + fn add_a_torrent_peer_using_ipv4(tracker: &Arc) { let info_hash = AquaticInfoHash([0u8; 20]); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); @@ -966,7 +966,7 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) .into(); - tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv4).await; + tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv4); } async fn announce_a_new_peer_using_ipv6(tracker: Arc) -> Response { @@ -985,7 +985,7 @@ mod tests { async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { let tracker = public_tracker(); - add_a_torrent_peer_using_ipv4(tracker.clone()).await; + add_a_torrent_peer_using_ipv4(&tracker); let response = announce_a_new_peer_using_ipv6(tracker.clone()).await; @@ -1144,7 +1144,7 @@ mod tests { .with_number_of_bytes_left(0) .into(); - tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer).await; + tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer); } fn build_scrape_request(remote_addr: &SocketAddr, info_hash: &InfoHash) -> ScrapeRequest { diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index dc2f70a76..92ef7b70b 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -22,8 +22,8 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker - pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - self.tracker.upsert_peer_and_get_stats(info_hash, peer).await; + pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + self.tracker.upsert_peer_and_get_stats(info_hash, peer); } } diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index af6587673..c4c992484 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -17,8 +17,7 @@ async fn should_allow_getting_tracker_statistics() { env.add_torrent_peer( &InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), &PeerBuilder::default().into(), - ) - .await; + ); let response = Client::new(env.get_connection_info()).get_tracker_statistics().await; diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index d54935f80..7ef35e729 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -24,7 +24,7 @@ async fn should_allow_getting_all_torrents() { let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()); let response = Client::new(env.get_connection_info()).get_torrents(Query::empty()).await; @@ -50,8 +50,8 @@ async fn should_allow_limiting_the_torrents_in_the_result() { let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); - env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; - env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()); + env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()); let response = Client::new(env.get_connection_info()) .get_torrents(Query::params([QueryParam::new("limit", "1")].to_vec())) @@ -79,8 +79,8 @@ async fn should_allow_the_torrents_result_pagination() { let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); - env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; - env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()); + env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()); let response = Client::new(env.get_connection_info()) .get_torrents(Query::params([QueryParam::new("offset", "1")].to_vec())) @@ -107,8 +107,8 @@ async fn should_allow_getting_a_list_of_torrents_providing_infohashes() { let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); // DevSkim: ignore DS173237 - env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; - env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()); + env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()); let response = Client::new(env.get_connection_info()) .get_torrents(Query::params( @@ -224,7 +224,7 @@ async fn should_allow_getting_a_torrent_info() { let peer = PeerBuilder::default().into(); - env.add_torrent_peer(&info_hash, &peer).await; + env.add_torrent_peer(&info_hash, &peer); let response = Client::new(env.get_connection_info()) .get_torrent(&info_hash.to_string()) @@ -285,7 +285,7 @@ async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()); let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) .get_torrent(&info_hash.to_string()) diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 2133ed6d0..b6bb21c16 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -19,8 +19,8 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker - pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - self.tracker.upsert_peer_and_get_stats(info_hash, peer).await; + pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + self.tracker.upsert_peer_and_get_stats(info_hash, peer); } } diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index cdffead99..e4a35d0c5 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -415,7 +415,7 @@ mod for_all_config_modes { .build(); // Add the Peer 1 - env.add_torrent_peer(&info_hash, &previously_announced_peer).await; + env.add_torrent_peer(&info_hash, &previously_announced_peer); // Announce the new Peer 2. This new peer is non included on the response peer list let response = Client::new(*env.bind_address()) @@ -456,7 +456,7 @@ mod for_all_config_modes { .with_peer_id(&peer::Id(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), 8080)) .build(); - env.add_torrent_peer(&info_hash, &peer_using_ipv4).await; + env.add_torrent_peer(&info_hash, &peer_using_ipv4); // Announce a peer using IPV6 let peer_using_ipv6 = PeerBuilder::default() @@ -466,7 +466,7 @@ mod for_all_config_modes { 8080, )) .build(); - env.add_torrent_peer(&info_hash, &peer_using_ipv6).await; + env.add_torrent_peer(&info_hash, &peer_using_ipv6); // Announce the new Peer. let response = Client::new(*env.bind_address()) @@ -505,7 +505,7 @@ mod for_all_config_modes { let peer = PeerBuilder::default().build(); // Add a peer - env.add_torrent_peer(&info_hash, &peer).await; + env.add_torrent_peer(&info_hash, &peer); let announce_query = QueryBuilder::default() .with_info_hash(&info_hash) @@ -536,7 +536,7 @@ mod for_all_config_modes { .build(); // Add the Peer 1 - env.add_torrent_peer(&info_hash, &previously_announced_peer).await; + env.add_torrent_peer(&info_hash, &previously_announced_peer); // Announce the new Peer 2 accepting compact responses let response = Client::new(*env.bind_address()) @@ -577,7 +577,7 @@ mod for_all_config_modes { .build(); // Add the Peer 1 - env.add_torrent_peer(&info_hash, &previously_announced_peer).await; + env.add_torrent_peer(&info_hash, &previously_announced_peer); // Announce the new Peer 2 without passing the "compact" param // By default it should respond with the compact peer list @@ -942,8 +942,7 @@ mod for_all_config_modes { .with_peer_id(&peer::Id(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), - ) - .await; + ); let response = Client::new(*env.bind_address()) .scrape( @@ -981,8 +980,7 @@ mod for_all_config_modes { .with_peer_id(&peer::Id(*b"-qB00000000000000001")) .with_no_bytes_pending_to_download() .build(), - ) - .await; + ); let response = Client::new(*env.bind_address()) .scrape( @@ -1182,8 +1180,7 @@ mod configured_as_whitelisted { .with_peer_id(&peer::Id(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), - ) - .await; + ); let response = Client::new(*env.bind_address()) .scrape( @@ -1212,8 +1209,7 @@ mod configured_as_whitelisted { .with_peer_id(&peer::Id(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), - ) - .await; + ); env.tracker .add_torrent_to_whitelist(&info_hash) @@ -1366,8 +1362,7 @@ mod configured_as_private { .with_peer_id(&peer::Id(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), - ) - .await; + ); let response = Client::new(*env.bind_address()) .scrape( @@ -1396,8 +1391,7 @@ mod configured_as_private { .with_peer_id(&peer::Id(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), - ) - .await; + ); let expiring_key = env.tracker.generate_auth_key(Duration::from_secs(60)).await.unwrap(); @@ -1440,8 +1434,7 @@ mod configured_as_private { .with_peer_id(&peer::Id(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), - ) - .await; + ); let false_key: Key = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ".parse().unwrap(); diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index c580c3558..cfc4390c9 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -21,8 +21,8 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker #[allow(dead_code)] - pub async fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { - self.tracker.upsert_peer_and_get_stats(info_hash, peer).await; + pub fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { + self.tracker.upsert_peer_and_get_stats(info_hash, peer); } } From cafb9aaa46ccc408238835745363304113e483de Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 13 Jul 2024 13:57:18 +0200 Subject: [PATCH 0439/1297] chore: update deps Updating crates.io index Locking 38 packages to latest compatible versions Updating async-trait v0.1.80 -> v0.1.81 Updating bytes v1.6.0 -> v1.6.1 Updating castaway v0.2.2 -> v0.2.3 Updating cc v1.0.104 -> v1.1.2 Updating clap v4.5.8 -> v4.5.9 Updating clap_builder v4.5.8 -> v4.5.9 Updating darling v0.20.9 -> v0.20.10 Updating darling_core v0.20.9 -> v0.20.10 Updating darling_macro v0.20.9 -> v0.20.10 Updating http-body v1.0.0 -> v1.0.1 Updating hyper v1.4.0 -> v1.4.1 Updating oorandom v11.1.3 -> v11.1.4 Updating rustls v0.23.10 -> v0.23.11 Updating rustls-webpki v0.102.4 -> v0.102.5 Updating serde v1.0.203 -> v1.0.204 Updating serde_derive v1.0.203 -> v1.0.204 Updating serde_with v3.8.2 -> v3.8.3 Updating serde_with_macros v3.8.2 -> v3.8.3 Updating syn v2.0.68 -> v2.0.71 Updating thiserror v1.0.61 -> v1.0.62 Updating thiserror-impl v1.0.61 -> v1.0.62 Updating tinyvec v1.6.1 -> v1.8.0 Updating toml_edit v0.22.14 -> v0.22.15 Updating uuid v1.9.1 -> v1.10.0 Updating windows-targets v0.52.5 -> v0.52.6 Updating windows_aarch64_gnullvm v0.52.5 -> v0.52.6 Updating windows_aarch64_msvc v0.52.5 -> v0.52.6 Updating windows_i686_gnu v0.52.5 -> v0.52.6 Updating windows_i686_gnullvm v0.52.5 -> v0.52.6 Updating windows_i686_msvc v0.52.5 -> v0.52.6 Updating windows_x86_64_gnu v0.52.5 -> v0.52.6 Updating windows_x86_64_gnullvm v0.52.5 -> v0.52.6 Updating windows_x86_64_msvc v0.52.5 -> v0.52.6 Updating zerocopy v0.7.34 -> v0.7.35 Updating zerocopy-derive v0.7.34 -> v0.7.35 Updating zstd v0.13.1 -> v0.13.2 Updating zstd-safe v7.1.0 -> v7.2.0 Updating zstd-sys v2.0.11+zstd.1.5.6 -> v2.0.12+zstd.1.5.6 --- Cargo.lock | 244 ++++++++++++++++++++++++++--------------------------- 1 file changed, 122 insertions(+), 122 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 83b3781dc..e3c03fa69 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -350,13 +350,13 @@ checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" [[package]] name = "async-trait" -version = "0.1.80" +version = "0.1.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca" +checksum = "6e0c28dcc82d7c8ead5cb13beb15405b57b8546e93215673ff8ca0349a028107" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -479,7 +479,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -566,7 +566,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -635,7 +635,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", "syn_derive", ] @@ -708,9 +708,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.6.0" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" +checksum = "a12916984aab3fa6e39d655a33e09c0071eb36d6ab3aea5c2d78551f1df6d952" [[package]] name = "camino" @@ -729,18 +729,18 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "castaway" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a17ed5635fc8536268e5d4de1e22e81ac34419e5f052d4d51f4e01dcc263fcc" +checksum = "0abae9be0aaf9ea96a3b1b8b1b55c602ca751eba1b1500220cea4ecbafe7c0d5" dependencies = [ "rustversion", ] [[package]] name = "cc" -version = "1.0.104" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74b6a57f98764a267ff415d50a25e6e166f3831a5071af4995296ea97d210490" +checksum = "47de7e88bbbd467951ae7f5a6f34f70d1b4d9cfce53d5fd70f74ebe118b3db56" dependencies = [ "jobserver", "libc", @@ -778,7 +778,7 @@ dependencies = [ "iana-time-zone", "num-traits", "serde", - "windows-targets 0.52.5", + "windows-targets 0.52.6", ] [[package]] @@ -821,9 +821,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.8" +version = "4.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84b3edb18336f4df585bc9aa31dd99c036dfa5dc5e9a2939a722a188f3a8970d" +checksum = "64acc1846d54c1fe936a78dc189c34e28d3f5afc348403f28ecf53660b9b8462" dependencies = [ "clap_builder", "clap_derive", @@ -831,9 +831,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.8" +version = "4.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1c09dd5ada6c6c78075d6fd0da3f90d8080651e2d6cc8eb2f1aaa4034ced708" +checksum = "6fb8393d67ba2e7bfaf28a23458e4e2b543cc73a99595511eb207fdb8aede942" dependencies = [ "anstream", "anstyle", @@ -850,7 +850,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -1058,9 +1058,9 @@ dependencies = [ [[package]] name = "darling" -version = "0.20.9" +version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83b2eb4d90d12bdda5ed17de686c2acb4c57914f8f921b8da7e112b5a36f3fe1" +checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989" dependencies = [ "darling_core", "darling_macro", @@ -1068,27 +1068,27 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.20.9" +version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622687fe0bac72a04e5599029151f5796111b90f1baaa9b544d807a5e31cd120" +checksum = "95133861a8032aaea082871032f5815eb9e98cef03fa916ab4500513994df9e5" dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", "strsim", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] name = "darling_macro" -version = "0.20.9" +version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "733cabb43482b1a1b53eee8583c2b9e8684d592215ea83efd305dd31bc2f0178" +checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -1124,7 +1124,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -1135,7 +1135,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -1357,7 +1357,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -1369,7 +1369,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -1381,7 +1381,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -1474,7 +1474,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -1672,9 +1672,9 @@ dependencies = [ [[package]] name = "http-body" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" dependencies = [ "bytes", "http", @@ -1707,9 +1707,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.4.0" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4fe55fb7a772d59a5ff1dfbff4fe0258d19b89fec4b233e75d35d5d2316badc" +checksum = "50dfd22e0e76d0f662d429a5f80fcaf3855009297eab6a0a9f8543834744ba05" dependencies = [ "bytes", "futures-channel", @@ -1736,7 +1736,7 @@ dependencies = [ "http", "hyper", "hyper-util", - "rustls 0.23.10", + "rustls 0.23.11", "rustls-pki-types", "tokio", "tokio-rustls 0.26.0", @@ -2047,7 +2047,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e310b3a6b5907f99202fcdb4960ff45b93735d7c7d96b760fcff8db2dc0e103d" dependencies = [ "cfg-if", - "windows-targets 0.52.5", + "windows-targets 0.52.6", ] [[package]] @@ -2192,7 +2192,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -2243,7 +2243,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", "termcolor", "thiserror", ] @@ -2424,9 +2424,9 @@ checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "oorandom" -version = "11.1.3" +version = "11.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" +checksum = "b410bbe7e14ab526a0e86877eb47c6996a2bd7746f027ba551028c925390e4e9" [[package]] name = "openssl" @@ -2451,7 +2451,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -2504,7 +2504,7 @@ dependencies = [ "libc", "redox_syscall", "smallvec", - "windows-targets 0.52.5", + "windows-targets 0.52.6", ] [[package]] @@ -2527,7 +2527,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -2601,7 +2601,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -2790,7 +2790,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", "version_check", "yansi", ] @@ -3098,7 +3098,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.68", + "syn 2.0.71", "unicode-ident", ] @@ -3194,13 +3194,13 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.10" +version = "0.23.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05cff451f60db80f490f3c182b77c35260baace73209e9cdbbe526bfe3a4d402" +checksum = "4828ea528154ae444e5a642dbb7d5623354030dc9822b83fd9bb79683c7399d0" dependencies = [ "once_cell", "rustls-pki-types", - "rustls-webpki 0.102.4", + "rustls-webpki 0.102.5", "subtle", "zeroize", ] @@ -3233,9 +3233,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.102.4" +version = "0.102.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff448f7e92e913c4b7d4c6d8e4540a1724b319b4152b8aef6d4cf8339712b33e" +checksum = "f9a6fccd794a42c2c105b513a2f62bc3fd8f3ba57a4593677ceb0bd035164d78" dependencies = [ "ring", "rustls-pki-types", @@ -3340,9 +3340,9 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" -version = "1.0.203" +version = "1.0.204" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7253ab4de971e72fb7be983802300c30b5a7f0c2e56fab8abfc6a214307c0094" +checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12" dependencies = [ "serde_derive", ] @@ -3368,13 +3368,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.203" +version = "1.0.204" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "500cbc0ebeb6f46627f50f3f5811ccf6bf00643be300b4c3eabc0ef55dc5b5ba" +checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -3420,7 +3420,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -3446,9 +3446,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.8.2" +version = "3.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "079f3a42cd87588d924ed95b533f8d30a483388c4e400ab736a7058e34f16169" +checksum = "e73139bc5ec2d45e6c5fd85be5a46949c1c39a4c18e56915f5eb4c12f975e377" dependencies = [ "base64 0.22.1", "chrono", @@ -3464,14 +3464,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.8.2" +version = "3.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc03aad67c1d26b7de277d51c86892e7d9a0110a2fe44bf6b26cc569fba302d6" +checksum = "b80d3d6b56b64335c0180e5ffde23b3c5e08c14c585b51a15bd0e95393f46703" dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -3614,9 +3614,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.68" +version = "2.0.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "901fa70d88b9d6c98022e23b4136f9f3e54e4662c3bc1bd1d84a42a9a0f0c1e9" +checksum = "b146dcf730474b4bcd16c311627b31ede9ab149045db4d6088b3becaea046462" dependencies = [ "proc-macro2", "quote", @@ -3632,7 +3632,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -3720,22 +3720,22 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.61" +version = "1.0.62" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709" +checksum = "f2675633b1499176c2dff06b0856a27976a8f9d436737b4cf4f312d4d91d8bbb" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.61" +version = "1.0.62" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" +checksum = "d20468752b09f49e909e55a5d338caa8bedf615594e9d80bc4c565d30faf798c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -3791,9 +3791,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.6.1" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c55115c6fbe2d2bef26eb09ad74bde02d8255476fc0c7b515ef09fbb35742d82" +checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938" dependencies = [ "tinyvec_macros", ] @@ -3830,7 +3830,7 @@ checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -3859,7 +3859,7 @@ version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" dependencies = [ - "rustls 0.23.10", + "rustls 0.23.11", "rustls-pki-types", "tokio", ] @@ -3886,7 +3886,7 @@ dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.14", + "toml_edit 0.22.15", ] [[package]] @@ -3922,9 +3922,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.14" +version = "0.22.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f21c7aaf97f1bd9ca9d4f9e73b0a6c74bd5afef56f2bc931943a6e1c37e04e38" +checksum = "d59a3a72298453f564e2b111fa896f8d07fabb36f51f06d7e875fc5e0b5a3ef1" dependencies = [ "indexmap 2.2.6", "serde", @@ -4154,7 +4154,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -4284,9 +4284,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.9.1" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5de17fd2f7da591098415cff336e12965a28061ddace43b59cb3c430179c9439" +checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314" dependencies = [ "getrandom", "rand", @@ -4368,7 +4368,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", "wasm-bindgen-shared", ] @@ -4402,7 +4402,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4460,7 +4460,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ - "windows-targets 0.52.5", + "windows-targets 0.52.6", ] [[package]] @@ -4478,7 +4478,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.5", + "windows-targets 0.52.6", ] [[package]] @@ -4498,18 +4498,18 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.5" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.5", - "windows_aarch64_msvc 0.52.5", - "windows_i686_gnu 0.52.5", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", "windows_i686_gnullvm", - "windows_i686_msvc 0.52.5", - "windows_x86_64_gnu 0.52.5", - "windows_x86_64_gnullvm 0.52.5", - "windows_x86_64_msvc 0.52.5", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] [[package]] @@ -4520,9 +4520,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.5" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" @@ -4532,9 +4532,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.52.5" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" @@ -4544,15 +4544,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.52.5" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" -version = "0.52.5" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" @@ -4562,9 +4562,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.52.5" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" @@ -4574,9 +4574,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.52.5" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" @@ -4586,9 +4586,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.5" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" @@ -4598,9 +4598,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.52.5" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" @@ -4647,9 +4647,9 @@ checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" [[package]] name = "zerocopy" -version = "0.7.34" +version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae87e3fcd617500e5d106f0380cf7b77f3c6092aae37191433159dda23cfb087" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ "byteorder", "zerocopy-derive", @@ -4657,13 +4657,13 @@ dependencies = [ [[package]] name = "zerocopy-derive" -version = "0.7.34" +version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15e934569e47891f7d9411f1a451d947a60e000ab3bd24fbb970f000387d1b3b" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.68", + "syn 2.0.71", ] [[package]] @@ -4674,27 +4674,27 @@ checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" [[package]] name = "zstd" -version = "0.13.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d789b1514203a1120ad2429eae43a7bd32b90976a7bb8a05f7ec02fa88cc23a" +checksum = "fcf2b778a664581e31e389454a7072dab1647606d44f7feea22cd5abb9c9f3f9" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "7.1.0" +version = "7.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cd99b45c6bc03a018c8b8a86025678c87e55526064e38f9df301989dce7ec0a" +checksum = "fa556e971e7b568dc775c136fc9de8c779b1c2fc3a63defaafadffdbd3181afa" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.0.11+zstd.1.5.6" +version = "2.0.12+zstd.1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75652c55c0b6f3e6f12eb786fe1bc960396bf05a1eb3bf1f3691c3610ac2e6d4" +checksum = "0a4e40c320c3cb459d9a9ff6de98cff88f4751ee9275d140e2be94a2b74e4c13" dependencies = [ "cc", "pkg-config", From 7f867d6138f44962e280cb0ab3fed23a8f595deb Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 13 Jul 2024 15:10:29 +0200 Subject: [PATCH 0440/1297] toml: use major versions --- Cargo.toml | 26 +++++++++++++------------- packages/clock/Cargo.toml | 4 ++-- packages/configuration/Cargo.toml | 6 +++--- packages/located-error/Cargo.toml | 2 +- packages/primitives/Cargo.toml | 6 +++--- packages/torrent-repository/Cargo.toml | 8 ++++---- 6 files changed, 26 insertions(+), 26 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index ed2de33e8..e54946be1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,29 +36,29 @@ axum = { version = "0", features = ["macros"] } axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls"] } -camino = { version = "1.1.6", features = ["serde", "serde1"] } +camino = { version = "1", features = ["serde", "serde1"] } chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } -crossbeam-skiplist = "0.1" -dashmap = "5.5.3" +crossbeam-skiplist = "0" +dashmap = "5" derive_more = "0" -figment = "0.10.18" +figment = "0" futures = "0" -futures-util = "0.3.30" +futures-util = "0" hex-literal = "0" -http-body = "1.0.0" +http-body = "1" hyper = "1" -hyper-util = { version = "0.1.3", features = ["http1", "http2", "tokio"] } +hyper-util = { version = "0", features = ["http1", "http2", "tokio"] } lazy_static = "1" multimap = "0" -parking_lot = "0.12.1" +parking_lot = "0" percent-encoding = "2" -pin-project-lite = "0.2.14" +pin-project-lite = "0" r2d2 = "0" r2d2_mysql = "24" r2d2_sqlite = { version = "0", features = ["bundled"] } rand = "0" -regex = "1.10.5" +regex = "1" reqwest = { version = "0", features = ["json"] } ringbuf = "0" serde = { version = "1", features = ["derive"] } @@ -74,14 +74,14 @@ torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12-develop", path = " torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "packages/located-error" } torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } torrust-tracker-torrent-repository = { version = "3.0.0-alpha.12-develop", path = "packages/torrent-repository" } -tower = { version = "0.4.13", features = ["timeout"] } +tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } trace = "0" tracing = "0" -tracing-subscriber = { version = "0.3.18", features = ["json"] } +tracing-subscriber = { version = "0", features = ["json"] } url = { version = "2", features = ["serde"] } uuid = { version = "1", features = ["v4"] } -zerocopy = "0.7.33" +zerocopy = "0" [package.metadata.cargo-machete] ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_bytes"] diff --git a/packages/clock/Cargo.toml b/packages/clock/Cargo.toml index d7192b6e4..d71175fdc 100644 --- a/packages/clock/Cargo.toml +++ b/packages/clock/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library to a clock for the torrust tracker." -keywords = ["library", "clock", "torrents"] +keywords = ["clock", "library", "torrents"] name = "torrust-tracker-clock" readme = "README.md" @@ -16,8 +16,8 @@ rust-version.workspace = true version.workspace = true [dependencies] -lazy_static = "1" chrono = { version = "0", default-features = false, features = ["clock"] } +lazy_static = "1" torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index ae9c64cfe..5afa39b89 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -15,16 +15,16 @@ rust-version.workspace = true version.workspace = true [dependencies] -camino = { version = "1.1.6", features = ["serde", "serde1"] } +camino = { version = "1", features = ["serde", "serde1"] } derive_more = "0" -figment = { version = "0.10.18", features = ["env", "test", "toml"] } +figment = { version = "0", features = ["env", "test", "toml"] } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } serde_with = "3" thiserror = "1" toml = "0" torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "../located-error" } -url = "2.5.2" +url = "2" [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index 4b2c73178..637ea3055 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -15,7 +15,7 @@ rust-version.workspace = true version.workspace = true [dependencies] -tracing = "0.1.40" +tracing = "0" [dev-dependencies] thiserror = "1" diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index 3b2406a69..174750fbb 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -15,9 +15,9 @@ rust-version.workspace = true version.workspace = true [dependencies] -derive_more = "0" -thiserror = "1" binascii = "0" +derive_more = "0" serde = { version = "1", features = ["derive"] } tdyne-peer-id = "1" -tdyne-peer-id-registry = "0" \ No newline at end of file +tdyne-peer-id-registry = "0" +thiserror = "1" diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 937ec11e2..8b46a8abe 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -16,10 +16,10 @@ rust-version.workspace = true version.workspace = true [dependencies] -crossbeam-skiplist = "0.1" -dashmap = "5.5.3" -futures = "0.3.29" -parking_lot = "0.12.1" +crossbeam-skiplist = "0" +dashmap = "5" +futures = "0" +parking_lot = "0" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-alpha.12-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } From d2717ad1b9bb58a0b46f79620929becab64fa320 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 13 Jul 2024 23:43:24 +0200 Subject: [PATCH 0441/1297] fixup: doc fixups --- packages/configuration/src/lib.rs | 2 +- packages/configuration/src/v2/mod.rs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 5e839b7b1..7f63b7f18 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -3,7 +3,7 @@ //! This module contains the configuration data structures for the //! Torrust Tracker, which is a `BitTorrent` tracker server. //! -//! The current version for configuration is [`v1`]. +//! The current version for configuration is [`v2`]. pub mod v2; use std::collections::HashMap; diff --git a/packages/configuration/src/v2/mod.rs b/packages/configuration/src/v2/mod.rs index 35c8b1070..5fa142b0b 100644 --- a/packages/configuration/src/v2/mod.rs +++ b/packages/configuration/src/v2/mod.rs @@ -39,11 +39,11 @@ //! Please refer to the documentation of each structure for more information //! about each section. //! -//! - [`Core configuration`](crate::v1::Configuration) -//! - [`HTTP API configuration`](crate::v1::tracker_api::HttpApi) -//! - [`HTTP Tracker configuration`](crate::v1::http_tracker::HttpTracker) -//! - [`UDP Tracker configuration`](crate::v1::udp_tracker::UdpTracker) -//! - [`Health Check API configuration`](crate::v1::health_check_api::HealthCheckApi) +//! - [`Core configuration`](crate::v2::Configuration) +//! - [`HTTP API configuration`](crate::v2::tracker_api::HttpApi) +//! - [`HTTP Tracker configuration`](crate::v2::http_tracker::HttpTracker) +//! - [`UDP Tracker configuration`](crate::v2::udp_tracker::UdpTracker) +//! - [`Health Check API configuration`](crate::v2::health_check_api::HealthCheckApi) //! //! ## Port binding //! @@ -78,7 +78,7 @@ //! //! Alternatively, you could setup a reverse proxy like Nginx or Apache to //! handle the SSL/TLS part and forward the requests to the tracker. If you do -//! that, you should set [`on_reverse_proxy`](crate::v1::core::Core::on_reverse_proxy) +//! that, you should set [`on_reverse_proxy`](crate::v2::network::Network::on_reverse_proxy) //! to `true` in the configuration file. It's out of scope for this //! documentation to explain in detail how to setup a reverse proxy, but the //! configuration file should be something like this: From 9791427541ffba649b6803797df12117536585db Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 13 Jul 2024 15:21:39 +0200 Subject: [PATCH 0442/1297] chore: update deps --- Cargo.lock | 174 +++++++------------------ Cargo.toml | 4 +- packages/torrent-repository/Cargo.toml | 6 +- 3 files changed, 53 insertions(+), 131 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e3c03fa69..889a6a5d7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -64,6 +64,12 @@ dependencies = [ "alloc-no-stdlib", ] +[[package]] +name = "allocator-api2" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" + [[package]] name = "android-tzdata" version = "0.1.1" @@ -534,10 +540,12 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "bigdecimal" -version = "0.3.1" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6773ddc0eafc0e509fb60e48dff7f450f8e674a0686ae8605e8d9901bd5eefa" +checksum = "51d712318a27c7150326677b321a5fa91b55f6d9034ffd67f20319e147d40cee" dependencies = [ + "autocfg", + "libm", "num-bigint", "num-integer", "num-traits", @@ -632,7 +640,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3ef8005764f53cd4dca619f5bf64cafd4664dada50ece25e4d81de54c80cc0b" dependencies = [ "once_cell", - "proc-macro-crate 3.1.0", + "proc-macro-crate", "proc-macro2", "quote", "syn 2.0.71", @@ -660,6 +668,15 @@ dependencies = [ "alloc-stdlib", ] +[[package]] +name = "btoi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd6407f73a9b8b6162d8a2ef999fe6afd7cc15902ebf42c5cd296addf17e0ad" +dependencies = [ + "num-traits", +] + [[package]] name = "bufstream" version = "0.1.4" @@ -1093,11 +1110,12 @@ dependencies = [ [[package]] name = "dashmap" -version = "5.5.3" +version = "6.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" +checksum = "804c8821570c3f8b70230c2ba75ffa5c0f9a4189b9a432b6656c536712acae28" dependencies = [ "cfg-if", + "crossbeam-utils", "hashbrown 0.14.5", "lock_api", "once_cell", @@ -1596,15 +1614,6 @@ dependencies = [ "ahash 0.7.8", ] -[[package]] -name = "hashbrown" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" -dependencies = [ - "ahash 0.8.11", -] - [[package]] name = "hashbrown" version = "0.14.5" @@ -1612,6 +1621,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ "ahash 0.8.11", + "allocator-api2", ] [[package]] @@ -1961,79 +1971,6 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" -[[package]] -name = "lexical" -version = "6.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7aefb36fd43fef7003334742cbf77b243fcd36418a1d1bdd480d613a67968f6" -dependencies = [ - "lexical-core", -] - -[[package]] -name = "lexical-core" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cde5de06e8d4c2faabc400238f9ae1c74d5412d03a7bd067645ccbc47070e46" -dependencies = [ - "lexical-parse-float", - "lexical-parse-integer", - "lexical-util", - "lexical-write-float", - "lexical-write-integer", -] - -[[package]] -name = "lexical-parse-float" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683b3a5ebd0130b8fb52ba0bdc718cc56815b6a097e28ae5a6997d0ad17dc05f" -dependencies = [ - "lexical-parse-integer", - "lexical-util", - "static_assertions", -] - -[[package]] -name = "lexical-parse-integer" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d0994485ed0c312f6d965766754ea177d07f9c00c9b82a5ee62ed5b47945ee9" -dependencies = [ - "lexical-util", - "static_assertions", -] - -[[package]] -name = "lexical-util" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5255b9ff16ff898710eb9eb63cb39248ea8a5bb036bea8085b1a767ff6c4e3fc" -dependencies = [ - "static_assertions", -] - -[[package]] -name = "lexical-write-float" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accabaa1c4581f05a3923d1b4cfd124c329352288b7b9da09e766b0668116862" -dependencies = [ - "lexical-util", - "lexical-write-integer", - "static_assertions", -] - -[[package]] -name = "lexical-write-integer" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1b6f3d1f4422866b68192d62f77bc5c700bee84f3069f2469d7bc8c77852446" -dependencies = [ - "lexical-util", - "static_assertions", -] - [[package]] name = "libc" version = "0.2.155" @@ -2050,6 +1987,12 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "libm" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" + [[package]] name = "libsqlite3-sys" version = "0.28.0" @@ -2117,11 +2060,11 @@ dependencies = [ [[package]] name = "lru" -version = "0.10.1" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "718e8fae447df0c7e1ba7f5189829e63fd536945c8988d61444c19039f16b670" +checksum = "d3262e75e648fce39813cb56ac41f3c3e3f65217ebf3844d818d1f9398cfb0dc" dependencies = [ - "hashbrown 0.13.2", + "hashbrown 0.14.5", ] [[package]] @@ -2206,9 +2149,9 @@ dependencies = [ [[package]] name = "mysql" -version = "24.0.0" +version = "25.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfe2babc5f5b354eab9c0a0e40da3e69c4d77421c8b9b6ee03f97acc75bd7955" +checksum = "c6ad644efb545e459029b1ffa7c969d830975bd76906820913247620df10050b" dependencies = [ "bufstream", "bytes", @@ -2220,7 +2163,6 @@ dependencies = [ "mysql_common", "named_pipe", "native-tls", - "once_cell", "pem", "percent-encoding", "serde", @@ -2232,14 +2174,14 @@ dependencies = [ [[package]] name = "mysql-common-derive" -version = "0.30.2" +version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56b0d8a0db9bf6d2213e11f2c701cb91387b0614361625ab7b9743b41aa4938f" +checksum = "afe0450cc9344afff34915f8328600ab5ae19260802a334d0f72d2d5bdda3bfe" dependencies = [ "darling", "heck 0.4.1", "num-bigint", - "proc-macro-crate 1.3.1", + "proc-macro-crate", "proc-macro-error", "proc-macro2", "quote", @@ -2250,15 +2192,16 @@ dependencies = [ [[package]] name = "mysql_common" -version = "0.30.6" +version = "0.32.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57349d5a326b437989b6ee4dc8f2f34b0cc131202748414712a8e7d98952fc8c" +checksum = "478b0ff3f7d67b79da2b96f56f334431aef65e15ba4b29dd74a4236e29582bdc" dependencies = [ "base64 0.21.7", "bigdecimal", "bindgen", "bitflags 2.6.0", "bitvec", + "btoi", "byteorder", "bytes", "cc", @@ -2267,7 +2210,6 @@ dependencies = [ "flate2", "frunk", "lazy_static", - "lexical", "mysql-common-derive", "num-bigint", "num-traits", @@ -2284,6 +2226,7 @@ dependencies = [ "thiserror", "time", "uuid", + "zstd", ] [[package]] @@ -2532,11 +2475,11 @@ dependencies = [ [[package]] name = "pem" -version = "2.0.1" +version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b13fe415cdf3c8e44518e18a7c95a13431d9bdf6d15367d82b23c377fdd441a" +checksum = "8e459365e590736a54c3fa561947c84837534b8e9af6fc5bf781307e82658fae" dependencies = [ - "base64 0.21.7", + "base64 0.22.1", "serde", ] @@ -2730,16 +2673,6 @@ dependencies = [ "termtree", ] -[[package]] -name = "proc-macro-crate" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" -dependencies = [ - "once_cell", - "toml_edit 0.19.15", -] - [[package]] name = "proc-macro-crate" version = "3.1.0" @@ -2848,9 +2781,9 @@ dependencies = [ [[package]] name = "r2d2_mysql" -version = "24.0.0" +version = "25.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fe5127e6c21971cdb9580f2f54cbe6d9c2226eb861036c3ca6d390c25f52574" +checksum = "93963fe09ca35b0311d089439e944e42a6cb39bf8ea323782ddb31240ba2ae87" dependencies = [ "mysql", "r2d2", @@ -3092,7 +3025,7 @@ checksum = "4165dfae59a39dd41d8dec720d3cbfbc71f69744efb480a3920f5d4e0cc6798d" dependencies = [ "cfg-if", "glob", - "proc-macro-crate 3.1.0", + "proc-macro-crate", "proc-macro2", "quote", "regex", @@ -3898,17 +3831,6 @@ dependencies = [ "serde", ] -[[package]] -name = "toml_edit" -version = "0.19.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" -dependencies = [ - "indexmap 2.2.6", - "toml_datetime", - "winnow 0.5.40", -] - [[package]] name = "toml_edit" version = "0.21.1" diff --git a/Cargo.toml b/Cargo.toml index e54946be1..5e4401516 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,7 +40,7 @@ camino = { version = "1", features = ["serde", "serde1"] } chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } crossbeam-skiplist = "0" -dashmap = "5" +dashmap = "6" derive_more = "0" figment = "0" futures = "0" @@ -55,7 +55,7 @@ parking_lot = "0" percent-encoding = "2" pin-project-lite = "0" r2d2 = "0" -r2d2_mysql = "24" +r2d2_mysql = "25" r2d2_sqlite = { version = "0", features = ["bundled"] } rand = "0" regex = "1" diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 8b46a8abe..53bb41e52 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library that provides a repository of torrents files and their peers." -keywords = ["torrents", "repository", "library"] +keywords = ["library", "repository", "torrents"] name = "torrust-tracker-torrent-repository" readme = "README.md" @@ -17,7 +17,7 @@ version.workspace = true [dependencies] crossbeam-skiplist = "0" -dashmap = "5" +dashmap = "6" futures = "0" parking_lot = "0" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } @@ -26,9 +26,9 @@ torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = ".. torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } [dev-dependencies] +async-std = { version = "1", features = ["attributes", "tokio1"] } criterion = { version = "0", features = ["async_tokio"] } rstest = "0" -async-std = {version = "1", features = ["attributes", "tokio1"] } [[bench]] harness = false From 8cefad624d7550717a7f23858741aaa61f999436 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 15 Jul 2024 09:26:28 +0100 Subject: [PATCH 0443/1297] fix: [#933] uppercase for containerfile keywords --- Containerfile | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Containerfile b/Containerfile index d302e5c66..263053390 100644 --- a/Containerfile +++ b/Containerfile @@ -3,13 +3,13 @@ # Torrust Tracker ## Builder Image -FROM docker.io/library/rust:bookworm as chef +FROM docker.io/library/rust:bookworm AS chef WORKDIR /tmp RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash RUN cargo binstall --no-confirm cargo-chef cargo-nextest ## Tester Image -FROM docker.io/library/rust:slim-bookworm as tester +FROM docker.io/library/rust:slim-bookworm AS tester WORKDIR /tmp RUN apt-get update; apt-get install -y curl sqlite3; apt-get autoclean @@ -21,7 +21,7 @@ RUN mkdir -p /app/share/torrust/default/database/; \ sqlite3 /app/share/torrust/default/database/tracker.sqlite3.db "VACUUM;" ## Su Exe Compile -FROM docker.io/library/gcc:bookworm as gcc +FROM docker.io/library/gcc:bookworm AS gcc COPY ./contrib/dev-tools/su-exec/ /usr/local/src/su-exec/ RUN cc -Wall -Werror -g /usr/local/src/su-exec/su-exec.c -o /usr/local/bin/su-exec; chmod +x /usr/local/bin/su-exec @@ -62,7 +62,7 @@ RUN cargo nextest archive --tests --benches --examples --workspace --all-targets # Extract and Test (debug) -FROM tester as test_debug +FROM tester AS test_debug WORKDIR /test COPY . /test/src/ COPY --from=build_debug \ @@ -76,7 +76,7 @@ RUN mkdir /app/lib/; cp -l $(realpath $(ldd /app/bin/torrust-tracker | grep "lib RUN chown -R root:root /app; chmod -R u=rw,go=r,a+X /app; chmod -R a+x /app/bin # Extract and Test (release) -FROM tester as test +FROM tester AS test WORKDIR /test COPY . /test/src COPY --from=build \ @@ -91,7 +91,7 @@ RUN chown -R root:root /app; chmod -R u=rw,go=r,a+X /app; chmod -R a+x /app/bin ## Runtime -FROM gcr.io/distroless/cc-debian12:debug as runtime +FROM gcr.io/distroless/cc-debian12:debug AS runtime RUN ["/busybox/cp", "-sp", "/busybox/sh","/busybox/cat","/busybox/ls","/busybox/env", "/bin/"] COPY --from=gcc --chmod=0555 /usr/local/bin/su-exec /bin/su-exec @@ -129,14 +129,14 @@ ENTRYPOINT ["/usr/local/bin/entry.sh"] ## Torrust-Tracker (debug) -FROM runtime as debug +FROM runtime AS debug ENV RUNTIME="debug" COPY --from=test_debug /app/ /usr/ RUN env CMD ["sh"] ## Torrust-Tracker (release) (default) -FROM runtime as release +FROM runtime AS release ENV RUNTIME="release" COPY --from=test /app/ /usr/ HEALTHCHECK --interval=5s --timeout=5s --start-period=3s --retries=3 \ From 82a8b4355330db1f0f8b601b4da31b489b2cd5a6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 29 Jul 2024 10:00:27 +0100 Subject: [PATCH 0444/1297] chore(deps): update dependencies ```output cargo update Updating crates.io index Locking 47 packages to latest compatible versions Updating anstream v0.6.14 -> v0.6.15 Updating anstyle v1.0.7 -> v1.0.8 Updating anstyle-parse v0.2.4 -> v0.2.5 Updating anstyle-query v1.1.0 -> v1.1.1 Updating anstyle-wincon v3.0.3 -> v3.0.4 Updating async-compression v0.4.11 -> v0.4.12 Updating async-executor v1.12.0 -> v1.13.0 Updating cc v1.1.2 -> v1.1.6 Updating clap v4.5.9 -> v4.5.11 Updating clap_builder v4.5.9 -> v4.5.11 Updating clap_derive v4.5.8 -> v4.5.11 Updating clap_lex v0.7.1 -> v0.7.2 Updating colorchoice v1.0.1 -> v1.0.2 Updating is_terminal_polyfill v1.70.0 -> v1.70.1 Updating jobserver v0.1.31 -> v0.1.32 Updating libloading v0.8.4 -> v0.8.5 Updating libsqlite3-sys v0.28.0 -> v0.30.1 Updating mio v0.8.11 -> v1.0.1 Updating mockall v0.12.1 -> v0.13.0 Updating mockall_derive v0.12.1 -> v0.13.0 Removing num_cpus v1.16.0 Updating object v0.36.1 -> v0.36.2 Updating openssl v0.10.64 -> v0.10.66 Updating openssl-sys v0.9.102 -> v0.9.103 Updating predicates v3.1.0 -> v3.1.2 Updating predicates-core v1.0.6 -> v1.0.8 Updating predicates-tree v1.0.9 -> v1.0.11 Updating r2d2_sqlite v0.24.0 -> v0.25.0 Updating redox_syscall v0.5.2 -> v0.5.3 Updating rusqlite v0.31.0 -> v0.32.1 Updating rustls v0.23.11 -> v0.23.12 Updating rustls-webpki v0.102.5 -> v0.102.6 Updating security-framework v2.11.0 -> v2.11.1 Updating security-framework-sys v2.11.0 -> v2.11.1 Updating serde_json v1.0.120 -> v1.0.121 Updating serde_spanned v0.6.6 -> v0.6.7 Updating serde_with v3.8.3 -> v3.9.0 Updating serde_with_macros v3.8.3 -> v3.9.0 Updating syn v2.0.71 -> v2.0.72 Updating thiserror v1.0.62 -> v1.0.63 Updating thiserror-impl v1.0.62 -> v1.0.63 Updating tokio v1.38.0 -> v1.39.2 Updating tokio-macros v2.3.0 -> v2.4.0 Updating toml v0.8.14 -> v0.8.16 Updating toml_datetime v0.6.6 -> v0.6.7 Updating toml_edit v0.22.15 -> v0.22.17 Updating version_check v0.9.4 -> v0.9.5 Updating winnow v0.6.13 -> v0.6.16 ``` --- Cargo.lock | 277 +++++++++++++++++++++++++---------------------------- 1 file changed, 133 insertions(+), 144 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 889a6a5d7..e4f7a938e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -93,9 +93,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.14" +version = "0.6.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" +checksum = "64e15c1ab1f89faffbf04a634d5e1962e9074f2741eef6d97f3c4e322426d526" dependencies = [ "anstyle", "anstyle-parse", @@ -108,33 +108,33 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.7" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b" +checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1" [[package]] name = "anstyle-parse" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4" +checksum = "eb47de1e80c2b463c735db5b217a0ddc39d612e7ac9e2e96a5aed1f57616c1cb" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad186efb764318d35165f1758e7dcef3b10628e26d41a44bc5550652e6804391" +checksum = "6d36fc52c7f6c869915e99412912f22093507da8d9e942ceaf66fe4b7c14422a" dependencies = [ "windows-sys 0.52.0", ] [[package]] name = "anstyle-wincon" -version = "3.0.3" +version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19" +checksum = "5bf74e1b6e971609db8ca7a9ce79fd5768ab6ae46441c572e46cf596f59e57f8" dependencies = [ "anstyle", "windows-sys 0.52.0", @@ -219,9 +219,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.11" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd066d0b4ef8ecb03a55319dc13aa6910616d0f44008a045bb1835af830abff5" +checksum = "fec134f64e2bc57411226dfc4e52dec859ddfc7e711fc5e07b612584f000e4aa" dependencies = [ "brotli", "flate2", @@ -235,9 +235,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8828ec6e544c02b0d6691d21ed9f9218d0384a82542855073c2a3f58304aaf0" +checksum = "d7ebdfa2ebdab6b1760375fa7d6f382b9f486eac35fc994625a00e89280bdbb7" dependencies = [ "async-task", "concurrent-queue", @@ -362,7 +362,7 @@ checksum = "6e0c28dcc82d7c8ead5cb13beb15405b57b8546e93215673ff8ca0349a028107" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -485,7 +485,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -574,7 +574,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -643,7 +643,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", "syn_derive", ] @@ -755,13 +755,12 @@ dependencies = [ [[package]] name = "cc" -version = "1.1.2" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47de7e88bbbd467951ae7f5a6f34f70d1b4d9cfce53d5fd70f74ebe118b3db56" +checksum = "2aba8f4e9906c7ce3c73463f62a7f0c65183ada1a2d47e397cc8810827f9694f" dependencies = [ "jobserver", "libc", - "once_cell", ] [[package]] @@ -838,9 +837,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.9" +version = "4.5.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64acc1846d54c1fe936a78dc189c34e28d3f5afc348403f28ecf53660b9b8462" +checksum = "35723e6a11662c2afb578bcf0b88bf6ea8e21282a953428f240574fcc3a2b5b3" dependencies = [ "clap_builder", "clap_derive", @@ -848,9 +847,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.9" +version = "4.5.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fb8393d67ba2e7bfaf28a23458e4e2b543cc73a99595511eb207fdb8aede942" +checksum = "49eb96cbfa7cfa35017b7cd548c75b14c3118c98b423041d70562665e07fb0fa" dependencies = [ "anstream", "anstyle", @@ -860,21 +859,21 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.8" +version = "4.5.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bac35c6dafb060fd4d275d9a4ffae97917c13a6327903a8be2153cd964f7085" +checksum = "5d029b67f89d30bbb547c89fd5161293c0aec155fc691d7924b64550662db93e" dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] name = "clap_lex" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b82cf0babdbd58558212896d1a4272303a57bdb245c2bf1147185fb45640e70" +checksum = "1462739cb27611015575c0c11df5df7601141071f07518d56fcc1be504cbec97" [[package]] name = "cmake" @@ -887,9 +886,9 @@ dependencies = [ [[package]] name = "colorchoice" -version = "1.0.1" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" +checksum = "d3fd119d74b830634cea2a0f58bbd0d54540518a14397557951e79340abc28c0" [[package]] name = "compact_str" @@ -1094,7 +1093,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1105,7 +1104,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1142,7 +1141,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1153,7 +1152,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1375,7 +1374,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1387,7 +1386,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1399,7 +1398,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1492,7 +1491,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -1746,7 +1745,7 @@ dependencies = [ "http", "hyper", "hyper-util", - "rustls 0.23.11", + "rustls 0.23.12", "rustls-pki-types", "tokio", "tokio-rustls 0.26.0", @@ -1904,9 +1903,9 @@ dependencies = [ [[package]] name = "is_terminal_polyfill" -version = "1.70.0" +version = "1.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" +checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" [[package]] name = "itertools" @@ -1934,9 +1933,9 @@ checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "jobserver" -version = "0.1.31" +version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2b099aaa34a9751c5bf0878add70444e1ed2dd73f347be99003d4577277de6e" +checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0" dependencies = [ "libc", ] @@ -1979,9 +1978,9 @@ checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "libloading" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e310b3a6b5907f99202fcdb4960ff45b93735d7c7d96b760fcff8db2dc0e103d" +checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" dependencies = [ "cfg-if", "windows-targets 0.52.6", @@ -1995,9 +1994,9 @@ checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" [[package]] name = "libsqlite3-sys" -version = "0.28.0" +version = "0.30.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c10584274047cb335c23d3e61bcef8e323adae7c5c8c760540f73610177fc3f" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" dependencies = [ "cc", "pkg-config", @@ -2102,25 +2101,25 @@ dependencies = [ [[package]] name = "mio" -version = "0.8.11" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" +checksum = "4569e456d394deccd22ce1c1913e6ea0e54519f577285001215d33557431afe4" dependencies = [ + "hermit-abi 0.3.9", "libc", "wasi", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] name = "mockall" -version = "0.12.1" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43766c2b5203b10de348ffe19f7e54564b64f3d6018ff7648d1e2d6d3a0f0a48" +checksum = "d4c28b3fb6d753d28c20e826cd46ee611fda1cf3cde03a443a974043247c065a" dependencies = [ "cfg-if", "downcast", "fragile", - "lazy_static", "mockall_derive", "predicates", "predicates-tree", @@ -2128,14 +2127,14 @@ dependencies = [ [[package]] name = "mockall_derive" -version = "0.12.1" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af7cbce79ec385a1d4f54baa90a76401eb15d9cab93685f62e7e9f942aa00ae2" +checksum = "341014e7f530314e9a1fdbc7400b244efea7122662c96bfa248c31da5bfb2020" dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -2185,7 +2184,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", "termcolor", "thiserror", ] @@ -2340,21 +2339,11 @@ dependencies = [ "autocfg", ] -[[package]] -name = "num_cpus" -version = "1.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" -dependencies = [ - "hermit-abi 0.3.9", - "libc", -] - [[package]] name = "object" -version = "0.36.1" +version = "0.36.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "081b846d1d56ddfc18fdf1a922e4f6e07a11768ea1b92dec44e42b72712ccfce" +checksum = "3f203fa8daa7bb185f760ae12bd8e097f63d17041dcdcaf675ac54cdf863170e" dependencies = [ "memchr", ] @@ -2373,9 +2362,9 @@ checksum = "b410bbe7e14ab526a0e86877eb47c6996a2bd7746f027ba551028c925390e4e9" [[package]] name = "openssl" -version = "0.10.64" +version = "0.10.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f" +checksum = "9529f4786b70a3e8c61e11179af17ab6188ad8d0ded78c5529441ed39d4bd9c1" dependencies = [ "bitflags 2.6.0", "cfg-if", @@ -2394,7 +2383,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -2405,9 +2394,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-sys" -version = "0.9.102" +version = "0.9.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c597637d56fbc83893a35eb0dd04b2b8e7a50c91e64e9493e398b5df4fb45fa2" +checksum = "7f9e8deee91df40a943c71b917e5874b951d32a802526c85721ce3b776c929d6" dependencies = [ "cc", "libc", @@ -2470,7 +2459,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -2544,7 +2533,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -2649,9 +2638,9 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "predicates" -version = "3.1.0" +version = "3.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68b87bfd4605926cdfefc1c3b5f8fe560e3feca9d5552cf68c466d3d8236c7e8" +checksum = "7e9086cc7640c29a356d1a29fd134380bee9d8f79a17410aa76e7ad295f42c97" dependencies = [ "anstyle", "predicates-core", @@ -2659,15 +2648,15 @@ dependencies = [ [[package]] name = "predicates-core" -version = "1.0.6" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b794032607612e7abeb4db69adb4e33590fa6cf1149e95fd7cb00e634b92f174" +checksum = "ae8177bee8e75d6846599c6b9ff679ed51e882816914eec639944d7c9aa11931" [[package]] name = "predicates-tree" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368ba315fb8c5052ab692e68a0eefec6ec57b23a36959c14496f0b0df2c0cecf" +checksum = "41b740d195ed3166cd147c8047ec98db0e22ec019eb8eeb76d343b795304fb13" dependencies = [ "predicates-core", "termtree", @@ -2723,7 +2712,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", "version_check", "yansi", ] @@ -2791,9 +2780,9 @@ dependencies = [ [[package]] name = "r2d2_sqlite" -version = "0.24.0" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a982edf65c129796dba72f8775b292ef482b40d035e827a9825b3bc07ccc5f2" +checksum = "eb14dba8247a6a15b7fdbc7d389e2e6f03ee9f184f87117706d509c092dfe846" dependencies = [ "r2d2", "rusqlite", @@ -2858,9 +2847,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c82cf8cff14456045f55ec4241383baeff27af886adb72ffb2162f99911de0fd" +checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4" dependencies = [ "bitflags 2.6.0", ] @@ -3031,15 +3020,15 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.71", + "syn 2.0.72", "unicode-ident", ] [[package]] name = "rusqlite" -version = "0.31.0" +version = "0.32.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b838eba278d213a8beaf485bd313fd580ca4505a00d5871caeb1457c55322cae" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" dependencies = [ "bitflags 2.6.0", "fallible-iterator", @@ -3127,13 +3116,13 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.11" +version = "0.23.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4828ea528154ae444e5a642dbb7d5623354030dc9822b83fd9bb79683c7399d0" +checksum = "c58f8c84392efc0a126acce10fa59ff7b3d2ac06ab451a33f2741989b806b044" dependencies = [ "once_cell", "rustls-pki-types", - "rustls-webpki 0.102.5", + "rustls-webpki 0.102.6", "subtle", "zeroize", ] @@ -3166,9 +3155,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.102.5" +version = "0.102.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9a6fccd794a42c2c105b513a2f62bc3fd8f3ba57a4593677ceb0bd035164d78" +checksum = "8e6b52d4fda176fd835fdc55a835d4a89b8499cad995885a21149d5ad62f852e" dependencies = [ "ring", "rustls-pki-types", @@ -3244,9 +3233,9 @@ checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" [[package]] name = "security-framework" -version = "2.11.0" +version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c627723fd09706bacdb5cf41499e95098555af3c3c29d014dc3c458ef6be11c0" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" dependencies = [ "bitflags 2.6.0", "core-foundation", @@ -3257,9 +3246,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.11.0" +version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "317936bbbd05227752583946b9e66d7ce3b489f84e11a94a510b4437fef407d7" +checksum = "75da29fe9b9b08fe9d6b22b5b4bcbc75d8db3aa31e639aa56bb62e9d46bfceaf" dependencies = [ "core-foundation-sys", "libc", @@ -3307,7 +3296,7 @@ checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -3325,12 +3314,13 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.120" +version = "1.0.121" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e0d21c9a8cae1235ad58a00c11cb40d4b1e5c784f1ef2c537876ed6ffd8b7c5" +checksum = "4ab380d7d9f22ef3f21ad3e6c1ebe8e4fc7a2000ccba2e4d71fc96f15b2cb609" dependencies = [ "indexmap 2.2.6", "itoa", + "memchr", "ryu", "serde", ] @@ -3353,14 +3343,14 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] name = "serde_spanned" -version = "0.6.6" +version = "0.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79e674e01f999af37c49f70a6ede167a8a60b2503e56c5599532a65baa5969a0" +checksum = "eb5b1b31579f3811bf615c144393417496f152e12ac8b7663bf664f4a815306d" dependencies = [ "serde", ] @@ -3379,9 +3369,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.8.3" +version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e73139bc5ec2d45e6c5fd85be5a46949c1c39a4c18e56915f5eb4c12f975e377" +checksum = "69cecfa94848272156ea67b2b1a53f20fc7bc638c4a46d2f8abde08f05f4b857" dependencies = [ "base64 0.22.1", "chrono", @@ -3397,14 +3387,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.8.3" +version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b80d3d6b56b64335c0180e5ffde23b3c5e08c14c585b51a15bd0e95393f46703" +checksum = "a8fee4991ef4f274617a51ad4af30519438dacb2f56ac773b08a1922ff743350" dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -3547,9 +3537,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.71" +version = "2.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b146dcf730474b4bcd16c311627b31ede9ab149045db4d6088b3becaea046462" +checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" dependencies = [ "proc-macro2", "quote", @@ -3565,7 +3555,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -3653,22 +3643,22 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.62" +version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2675633b1499176c2dff06b0856a27976a8f9d436737b4cf4f312d4d91d8bbb" +checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.62" +version = "1.0.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d20468752b09f49e909e55a5d338caa8bedf615594e9d80bc4c565d30faf798c" +checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -3739,31 +3729,30 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.38.0" +version = "1.39.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba4f4a02a7a80d6f274636f0aa95c7e383b912d41fe721a31f29e29698585a4a" +checksum = "daa4fb1bc778bd6f04cbfc4bb2d06a7396a8f299dc33ea1900cedaa316f467b1" dependencies = [ "backtrace", "bytes", "libc", "mio", - "num_cpus", "pin-project-lite", "signal-hook-registry", "socket2 0.5.7", "tokio-macros", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] name = "tokio-macros" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" +checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -3792,7 +3781,7 @@ version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" dependencies = [ - "rustls 0.23.11", + "rustls 0.23.12", "rustls-pki-types", "tokio", ] @@ -3812,21 +3801,21 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.14" +version = "0.8.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f49eb2ab21d2f26bd6db7bf383edc527a7ebaee412d17af4d40fdccd442f335" +checksum = "81967dd0dd2c1ab0bc3468bd7caecc32b8a4aa47d0c8c695d8c2b2108168d62c" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.15", + "toml_edit 0.22.17", ] [[package]] name = "toml_datetime" -version = "0.6.6" +version = "0.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4badfd56924ae69bcc9039335b2e017639ce3f9b001c393c1b2d1ef846ce2cbf" +checksum = "f8fb9f64314842840f1d940ac544da178732128f1c78c21772e876579e0da1db" dependencies = [ "serde", ] @@ -3844,15 +3833,15 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.15" +version = "0.22.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d59a3a72298453f564e2b111fa896f8d07fabb36f51f06d7e875fc5e0b5a3ef1" +checksum = "8d9f8729f5aea9562aac1cc0441f5d6de3cff1ee0c5d67293eeca5eb36ee7c16" dependencies = [ "indexmap 2.2.6", "serde", "serde_spanned", "toml_datetime", - "winnow 0.6.13", + "winnow 0.6.16", ] [[package]] @@ -4076,7 +4065,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] @@ -4234,9 +4223,9 @@ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" [[package]] name = "version_check" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "waker-fn" @@ -4290,7 +4279,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", "wasm-bindgen-shared", ] @@ -4324,7 +4313,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4535,9 +4524,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.6.13" +version = "0.6.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59b5e5f6c299a3c7890b876a2a587f3115162487e704907d9b6cd29473052ba1" +checksum = "b480ae9340fc261e6be3e95a1ba86d54ae3f9171132a73ce8d4bbaf68339507c" dependencies = [ "memchr", ] @@ -4585,7 +4574,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.71", + "syn 2.0.72", ] [[package]] From 09beb52d8fe8d6833f881bc6d2365268564e84d8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 29 Jul 2024 16:56:48 +0100 Subject: [PATCH 0445/1297] feat: [#974] new API endpoint to upload pre-existing keys You can test it with: ```console curl -X POST http://localhost:1212/api/v1/keys?token=MyAccessToken \ -H "Content-Type: application/json" \ -d '{ "key": "Xc1L4PbQJSFGlrgSRZl8wxSFAuMa21z7", "seconds_valid": 7200 }' ``` The `key` field is optional. If it's not provided a random key will be generated. --- src/core/auth.rs | 2 +- src/core/mod.rs | 38 +++++++++++-- src/servers/apis/v1/context/auth_key/forms.rs | 8 +++ .../apis/v1/context/auth_key/handlers.rs | 53 ++++++++++++++++++- src/servers/apis/v1/context/auth_key/mod.rs | 1 + .../apis/v1/context/auth_key/responses.rs | 21 +++++++- .../apis/v1/context/auth_key/routes.rs | 8 ++- src/servers/apis/v1/responses.rs | 3 +- 8 files changed, 122 insertions(+), 12 deletions(-) create mode 100644 src/servers/apis/v1/context/auth_key/forms.rs diff --git a/src/core/auth.rs b/src/core/auth.rs index 94d455d7e..00ded71ef 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -152,7 +152,7 @@ pub struct Key(String); /// ``` /// /// If the string does not contains a valid key, the parser function will return this error. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Display)] pub struct ParseKeyError; impl FromStr for Key { diff --git a/src/core/mod.rs b/src/core/mod.rs index 64d5e2c9a..f0853ec27 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -453,6 +453,7 @@ use std::panic::Location; use std::sync::Arc; use std::time::Duration; +use auth::ExpiringKey; use databases::driver::Driver; use derive_more::Constructor; use tokio::sync::mpsc::error::SendError; @@ -460,9 +461,9 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::v2::database; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; use tracing::debug; @@ -804,6 +805,37 @@ impl Tracker { /// Will return a `database::Error` if unable to add the `auth_key` to the database. pub async fn generate_auth_key(&self, lifetime: Duration) -> Result { let auth_key = auth::generate(lifetime); + + self.database.add_key_to_keys(&auth_key)?; + self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); + Ok(auth_key) + } + + /// It adds a pre-generated authentication key. + /// + /// Authentication keys are used by HTTP trackers. + /// + /// # Context: Authentication + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `auth_key` to the + /// database. For example, if the key already exist. + /// + /// # Arguments + /// + /// * `lifetime` - The duration in seconds for the new key. The key will be + /// no longer valid after `lifetime` seconds. + pub async fn add_auth_key( + &self, + key: Key, + valid_until: DurationSinceUnixEpoch, + ) -> Result { + let auth_key = ExpiringKey { key, valid_until }; + + // code-review: should we return a friendly error instead of the DB + // constrain error when the key already exist? For now, it's returning + // the specif error for each DB driver when a UNIQUE constrain fails. self.database.add_key_to_keys(&auth_key)?; self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); Ok(auth_key) @@ -816,10 +848,6 @@ impl Tracker { /// # Errors /// /// Will return a `database::Error` if unable to remove the `key` to the database. - /// - /// # Panics - /// - /// Will panic if key cannot be converted into a valid `Key`. pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> { self.database.remove_key_from_keys(key)?; self.keys.write().await.remove(key); diff --git a/src/servers/apis/v1/context/auth_key/forms.rs b/src/servers/apis/v1/context/auth_key/forms.rs new file mode 100644 index 000000000..9c023ab72 --- /dev/null +++ b/src/servers/apis/v1/context/auth_key/forms.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug)] +pub struct AddKeyForm { + #[serde(rename = "key")] + pub opt_key: Option, + pub seconds_valid: u64, +} diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index 792d9507e..3f85089ec 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -3,17 +3,66 @@ use std::str::FromStr; use std::sync::Arc; use std::time::Duration; -use axum::extract::{Path, State}; +use axum::extract::{self, Path, State}; use axum::response::Response; use serde::Deserialize; +use torrust_tracker_clock::clock::Time; +use super::forms::AddKeyForm; use super::responses::{ - auth_key_response, failed_to_delete_key_response, failed_to_generate_key_response, failed_to_reload_keys_response, + auth_key_response, failed_to_add_key_response, failed_to_delete_key_response, failed_to_generate_key_response, + failed_to_reload_keys_response, invalid_auth_key_duration_response, invalid_auth_key_response, }; use crate::core::auth::Key; use crate::core::Tracker; use crate::servers::apis::v1::context::auth_key::resources::AuthKey; use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_response}; +use crate::CurrentClock; + +/// It handles the request to add a new authentication key. +/// +/// It returns these types of responses: +/// +/// - `200` with a json [`AuthKey`] +/// resource. If the key was generated successfully. +/// - `400` with an error if the key couldn't been added because of an invalid +/// request. +/// - `500` with serialized error in debug format. If the key couldn't be +/// generated. +/// +/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#generate-a-new-authentication-key) +/// for more information about this endpoint. +pub async fn add_auth_key_handler( + State(tracker): State>, + extract::Json(add_key_form): extract::Json, +) -> Response { + match add_key_form.opt_key { + Some(pre_existing_key) => { + let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(add_key_form.seconds_valid)) else { + return invalid_auth_key_duration_response(add_key_form.seconds_valid); + }; + + let key = pre_existing_key.parse::(); + + match key { + Ok(key) => match tracker.add_auth_key(key, valid_until).await { + Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), + Err(e) => failed_to_add_key_response(e), + }, + Err(e) => invalid_auth_key_response(&pre_existing_key, &e), + } + } + None => { + match tracker + .generate_auth_key(Duration::from_secs(add_key_form.seconds_valid)) + .await + { + Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), + Err(e) => failed_to_generate_key_response(e), + } + } + } +} /// It handles the request to generate a new authentication key. /// diff --git a/src/servers/apis/v1/context/auth_key/mod.rs b/src/servers/apis/v1/context/auth_key/mod.rs index 330249b58..b00d7a2cb 100644 --- a/src/servers/apis/v1/context/auth_key/mod.rs +++ b/src/servers/apis/v1/context/auth_key/mod.rs @@ -119,6 +119,7 @@ //! "status": "ok" //! } //! ``` +pub mod forms; pub mod handlers; pub mod resources; pub mod responses; diff --git a/src/servers/apis/v1/context/auth_key/responses.rs b/src/servers/apis/v1/context/auth_key/responses.rs index 51be162c5..dfe449b46 100644 --- a/src/servers/apis/v1/context/auth_key/responses.rs +++ b/src/servers/apis/v1/context/auth_key/responses.rs @@ -4,8 +4,9 @@ use std::error::Error; use axum::http::{header, StatusCode}; use axum::response::{IntoResponse, Response}; +use crate::core::auth::ParseKeyError; use crate::servers::apis::v1::context::auth_key::resources::AuthKey; -use crate::servers::apis::v1::responses::unhandled_rejection_response; +use crate::servers::apis::v1::responses::{bad_request_response, unhandled_rejection_response}; /// `200` response that contains the `AuthKey` resource as json. /// @@ -22,12 +23,20 @@ pub fn auth_key_response(auth_key: &AuthKey) -> Response { .into_response() } +// Error responses + /// `500` error response when a new authentication key cannot be generated. #[must_use] pub fn failed_to_generate_key_response(e: E) -> Response { unhandled_rejection_response(format!("failed to generate key: {e}")) } +/// `500` error response when the provide key cannot be added. +#[must_use] +pub fn failed_to_add_key_response(e: E) -> Response { + unhandled_rejection_response(format!("failed to add key: {e}")) +} + /// `500` error response when an authentication key cannot be deleted. #[must_use] pub fn failed_to_delete_key_response(e: E) -> Response { @@ -40,3 +49,13 @@ pub fn failed_to_delete_key_response(e: E) -> Response { pub fn failed_to_reload_keys_response(e: E) -> Response { unhandled_rejection_response(format!("failed to reload keys: {e}")) } + +#[must_use] +pub fn invalid_auth_key_response(auth_key: &str, error: &ParseKeyError) -> Response { + bad_request_response(&format!("Invalid URL: invalid auth key: string \"{auth_key}\", {error}")) +} + +#[must_use] +pub fn invalid_auth_key_duration_response(duration: u64) -> Response { + bad_request_response(&format!("Invalid URL: invalid auth key duration: \"{duration}\"")) +} diff --git a/src/servers/apis/v1/context/auth_key/routes.rs b/src/servers/apis/v1/context/auth_key/routes.rs index 003ee5af4..9452f2c0f 100644 --- a/src/servers/apis/v1/context/auth_key/routes.rs +++ b/src/servers/apis/v1/context/auth_key/routes.rs @@ -11,7 +11,7 @@ use std::sync::Arc; use axum::routing::{get, post}; use axum::Router; -use super::handlers::{delete_auth_key_handler, generate_auth_key_handler, reload_keys_handler}; +use super::handlers::{add_auth_key_handler, delete_auth_key_handler, generate_auth_key_handler, reload_keys_handler}; use crate::core::Tracker; /// It adds the routes to the router for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. @@ -30,5 +30,9 @@ pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { .with_state(tracker.clone()), ) // Keys command - .route(&format!("{prefix}/keys/reload"), get(reload_keys_handler).with_state(tracker)) + .route( + &format!("{prefix}/keys/reload"), + get(reload_keys_handler).with_state(tracker.clone()), + ) + .route(&format!("{prefix}/keys"), post(add_auth_key_handler).with_state(tracker)) } diff --git a/src/servers/apis/v1/responses.rs b/src/servers/apis/v1/responses.rs index ecaf90098..d2c52ac40 100644 --- a/src/servers/apis/v1/responses.rs +++ b/src/servers/apis/v1/responses.rs @@ -61,7 +61,8 @@ pub fn invalid_auth_key_param_response(invalid_key: &str) -> Response { bad_request_response(&format!("Invalid auth key id param \"{invalid_key}\"")) } -fn bad_request_response(body: &str) -> Response { +#[must_use] +pub fn bad_request_response(body: &str) -> Response { ( StatusCode::BAD_REQUEST, [(header::CONTENT_TYPE, "text/plain; charset=utf-8")], From 583b305ed32a310f5897be7de943df8e4975e751 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jul 2024 10:55:34 +0100 Subject: [PATCH 0446/1297] test: [#874] new key generation endpoint --- tests/servers/api/v1/asserts.rs | 35 ++- tests/servers/api/v1/client.rs | 28 +- .../api/v1/contract/context/auth_key.rs | 240 +++++++++++++++--- 3 files changed, 267 insertions(+), 36 deletions(-) diff --git a/tests/servers/api/v1/asserts.rs b/tests/servers/api/v1/asserts.rs index 955293db1..ba906f65f 100644 --- a/tests/servers/api/v1/asserts.rs +++ b/tests/servers/api/v1/asserts.rs @@ -61,6 +61,12 @@ pub async fn assert_bad_request(response: Response, body: &str) { assert_eq!(response.text().await.unwrap(), body); } +pub async fn assert_unprocessable_content(response: Response, text: &str) { + assert_eq!(response.status(), 422); + assert_eq!(response.headers().get("content-type").unwrap(), "text/plain; charset=utf-8"); + assert!(response.text().await.unwrap().contains(text)); +} + pub async fn assert_not_found(response: Response) { assert_eq!(response.status(), 404); // todo: missing header in the response @@ -82,10 +88,37 @@ pub async fn assert_invalid_infohash_param(response: Response, invalid_infohash: .await; } -pub async fn assert_invalid_auth_key_param(response: Response, invalid_auth_key: &str) { +pub async fn assert_invalid_auth_key_get_param(response: Response, invalid_auth_key: &str) { assert_bad_request(response, &format!("Invalid auth key id param \"{}\"", &invalid_auth_key)).await; } +pub async fn assert_invalid_auth_key_post_param(response: Response, invalid_auth_key: &str) { + assert_bad_request( + response, + &format!( + "Invalid URL: invalid auth key: string \"{}\", ParseKeyError", + &invalid_auth_key + ), + ) + .await; +} + +pub async fn _assert_unprocessable_auth_key_param(response: Response, _invalid_value: &str) { + assert_unprocessable_content( + response, + "Failed to deserialize the JSON body into the target type: seconds_valid: invalid type", + ) + .await; +} + +pub async fn assert_unprocessable_auth_key_duration_param(response: Response, _invalid_value: &str) { + assert_unprocessable_content( + response, + "Failed to deserialize the JSON body into the target type: seconds_valid: invalid type", + ) + .await; +} + pub async fn assert_invalid_key_duration_param(response: Response, invalid_key_duration: &str) { assert_bad_request( response, diff --git a/tests/servers/api/v1/client.rs b/tests/servers/api/v1/client.rs index 61e98e742..91f18acac 100644 --- a/tests/servers/api/v1/client.rs +++ b/tests/servers/api/v1/client.rs @@ -1,4 +1,5 @@ use reqwest::Response; +use serde::Serialize; use crate::common::http::{Query, QueryParam, ReqwestQuery}; use crate::servers::api::connection_info::ConnectionInfo; @@ -18,7 +19,11 @@ impl Client { } pub async fn generate_auth_key(&self, seconds_valid: i32) -> Response { - self.post(&format!("key/{}", &seconds_valid)).await + self.post_empty(&format!("key/{}", &seconds_valid)).await + } + + pub async fn add_auth_key(&self, add_key_form: AddKeyForm) -> Response { + self.post_form("keys", &add_key_form).await } pub async fn delete_auth_key(&self, key: &str) -> Response { @@ -30,7 +35,7 @@ impl Client { } pub async fn whitelist_a_torrent(&self, info_hash: &str) -> Response { - self.post(&format!("whitelist/{}", &info_hash)).await + self.post_empty(&format!("whitelist/{}", &info_hash)).await } pub async fn remove_torrent_from_whitelist(&self, info_hash: &str) -> Response { @@ -63,10 +68,20 @@ impl Client { self.get_request_with_query(path, query).await } - pub async fn post(&self, path: &str) -> Response { + pub async fn post_empty(&self, path: &str) -> Response { + reqwest::Client::new() + .post(self.base_url(path).clone()) + .query(&ReqwestQuery::from(self.query_with_token())) + .send() + .await + .unwrap() + } + + pub async fn post_form(&self, path: &str, form: &T) -> Response { reqwest::Client::new() .post(self.base_url(path).clone()) .query(&ReqwestQuery::from(self.query_with_token())) + .json(&form) .send() .await .unwrap() @@ -114,3 +129,10 @@ pub async fn get(path: &str, query: Option) -> Response { None => reqwest::Client::builder().build().unwrap().get(path).send().await.unwrap(), } } + +#[derive(Serialize, Debug)] +pub struct AddKeyForm { + #[serde(rename = "key")] + pub opt_key: Option, + pub seconds_valid: u64, +} diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index f9630bafe..f02267b8b 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -1,23 +1,28 @@ use std::time::Duration; +use serde::Serialize; use torrust_tracker::core::auth::Key; use torrust_tracker_test_helpers::configuration; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_auth_key_utf8, assert_failed_to_delete_key, assert_failed_to_generate_key, assert_failed_to_reload_keys, - assert_invalid_auth_key_param, assert_invalid_key_duration_param, assert_ok, assert_token_not_valid, assert_unauthorized, + assert_invalid_auth_key_get_param, assert_invalid_auth_key_post_param, assert_ok, assert_token_not_valid, + assert_unauthorized, assert_unprocessable_auth_key_duration_param, }; -use crate::servers::api::v1::client::Client; +use crate::servers::api::v1::client::{AddKeyForm, Client}; use crate::servers::api::{force_database_error, Started}; #[tokio::test] -async fn should_allow_generating_a_new_auth_key() { +async fn should_allow_generating_a_new_random_auth_key() { let env = Started::new(&configuration::ephemeral().into()).await; - let seconds_valid = 60; - - let response = Client::new(env.get_connection_info()).generate_auth_key(seconds_valid).await; + let response = Client::new(env.get_connection_info()) + .add_auth_key(AddKeyForm { + opt_key: None, + seconds_valid: 60, + }) + .await; let auth_key_resource = assert_auth_key_utf8(response).await; @@ -32,43 +37,49 @@ async fn should_allow_generating_a_new_auth_key() { } #[tokio::test] -async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { +async fn should_allow_uploading_a_preexisting_auth_key() { let env = Started::new(&configuration::ephemeral().into()).await; - let seconds_valid = 60; - - let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) - .generate_auth_key(seconds_valid) + let response = Client::new(env.get_connection_info()) + .add_auth_key(AddKeyForm { + opt_key: Some("Xc1L4PbQJSFGlrgSRZl8wxSFAuMa21z5".to_string()), + seconds_valid: 60, + }) .await; - assert_token_not_valid(response).await; - - let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) - .generate_auth_key(seconds_valid) - .await; + let auth_key_resource = assert_auth_key_utf8(response).await; - assert_unauthorized(response).await; + // Verify the key with the tracker + assert!(env + .tracker + .verify_auth_key(&auth_key_resource.key.parse::().unwrap()) + .await + .is_ok()); env.stop().await; } #[tokio::test] -async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid() { +async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { let env = Started::new(&configuration::ephemeral().into()).await; - let invalid_key_durations = [ - // "", it returns 404 - // " ", it returns 404 - "-1", "text", - ]; + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + .add_auth_key(AddKeyForm { + opt_key: None, + seconds_valid: 60, + }) + .await; - for invalid_key_duration in invalid_key_durations { - let response = Client::new(env.get_connection_info()) - .post(&format!("key/{invalid_key_duration}")) - .await; + assert_token_not_valid(response).await; - assert_invalid_key_duration_param(response, invalid_key_duration).await; - } + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) + .add_auth_key(AddKeyForm { + opt_key: None, + seconds_valid: 60, + }) + .await; + + assert_unauthorized(response).await; env.stop().await; } @@ -79,8 +90,12 @@ async fn should_fail_when_the_auth_key_cannot_be_generated() { force_database_error(&env.tracker); - let seconds_valid = 60; - let response = Client::new(env.get_connection_info()).generate_auth_key(seconds_valid).await; + let response = Client::new(env.get_connection_info()) + .add_auth_key(AddKeyForm { + opt_key: None, + seconds_valid: 60, + }) + .await; assert_failed_to_generate_key(response).await; @@ -107,6 +122,77 @@ async fn should_allow_deleting_an_auth_key() { env.stop().await; } +#[tokio::test] +async fn should_fail_generating_a_new_auth_key_when_the_provided_key_is_invalid() { + #[derive(Serialize, Debug)] + pub struct InvalidAddKeyForm { + #[serde(rename = "key")] + pub opt_key: Option, + pub seconds_valid: u64, + } + + let env = Started::new(&configuration::ephemeral().into()).await; + + let invalid_keys = [ + // "", it returns 404 + // " ", it returns 404 + "-1", // Not a string + "invalid", // Invalid string + "GQEs2ZNcCm9cwEV9dBpcPB5OwNFWFiR", // Not a 32-char string + // "%QEs2ZNcCm9cwEV9dBpcPB5OwNFWFiRd", // Invalid char. todo: this doesn't fail + ]; + + for invalid_key in invalid_keys { + let response = Client::new(env.get_connection_info()) + .post_form( + "keys", + &InvalidAddKeyForm { + opt_key: Some(invalid_key.to_string()), + seconds_valid: 60, + }, + ) + .await; + + assert_invalid_auth_key_post_param(response, invalid_key).await; + } + + env.stop().await; +} + +#[tokio::test] +async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid() { + #[derive(Serialize, Debug)] + pub struct InvalidAddKeyForm { + #[serde(rename = "key")] + pub opt_key: Option, + pub seconds_valid: String, + } + + let env = Started::new(&configuration::ephemeral().into()).await; + + let invalid_key_durations = [ + // "", it returns 404 + // " ", it returns 404 + "-1", "text", + ]; + + for invalid_key_duration in invalid_key_durations { + let response = Client::new(env.get_connection_info()) + .post_form( + "keys", + &InvalidAddKeyForm { + opt_key: None, + seconds_valid: invalid_key_duration.to_string(), + }, + ) + .await; + + assert_unprocessable_auth_key_duration_param(response, invalid_key_duration).await; + } + + env.stop().await; +} + #[tokio::test] async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { let env = Started::new(&configuration::ephemeral().into()).await; @@ -124,7 +210,7 @@ async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { for invalid_auth_key in &invalid_auth_keys { let response = Client::new(env.get_connection_info()).delete_auth_key(invalid_auth_key).await; - assert_invalid_auth_key_param(response, invalid_auth_key).await; + assert_invalid_auth_key_get_param(response, invalid_auth_key).await; } env.stop().await; @@ -247,3 +333,93 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { env.stop().await; } + +mod deprecated_generate_key_endpoint { + + use torrust_tracker::core::auth::Key; + use torrust_tracker_test_helpers::configuration; + + use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; + use crate::servers::api::v1::asserts::{ + assert_auth_key_utf8, assert_failed_to_generate_key, assert_invalid_key_duration_param, assert_token_not_valid, + assert_unauthorized, + }; + use crate::servers::api::v1::client::Client; + use crate::servers::api::{force_database_error, Started}; + + #[tokio::test] + async fn should_allow_generating_a_new_auth_key() { + let env = Started::new(&configuration::ephemeral().into()).await; + + let seconds_valid = 60; + + let response = Client::new(env.get_connection_info()).generate_auth_key(seconds_valid).await; + + let auth_key_resource = assert_auth_key_utf8(response).await; + + // Verify the key with the tracker + assert!(env + .tracker + .verify_auth_key(&auth_key_resource.key.parse::().unwrap()) + .await + .is_ok()); + + env.stop().await; + } + + #[tokio::test] + async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { + let env = Started::new(&configuration::ephemeral().into()).await; + + let seconds_valid = 60; + + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + .generate_auth_key(seconds_valid) + .await; + + assert_token_not_valid(response).await; + + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) + .generate_auth_key(seconds_valid) + .await; + + assert_unauthorized(response).await; + + env.stop().await; + } + + #[tokio::test] + async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid() { + let env = Started::new(&configuration::ephemeral().into()).await; + + let invalid_key_durations = [ + // "", it returns 404 + // " ", it returns 404 + "-1", "text", + ]; + + for invalid_key_duration in invalid_key_durations { + let response = Client::new(env.get_connection_info()) + .post_empty(&format!("key/{invalid_key_duration}")) + .await; + + assert_invalid_key_duration_param(response, invalid_key_duration).await; + } + + env.stop().await; + } + + #[tokio::test] + async fn should_fail_when_the_auth_key_cannot_be_generated() { + let env = Started::new(&configuration::ephemeral().into()).await; + + force_database_error(&env.tracker); + + let seconds_valid = 60; + let response = Client::new(env.get_connection_info()).generate_auth_key(seconds_valid).await; + + assert_failed_to_generate_key(response).await; + + env.stop().await; + } +} From 04f50e454e6e6c0c047a798af410ff3b19ad228d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jul 2024 11:22:30 +0100 Subject: [PATCH 0447/1297] docs: [#974] update add key endpoint doc --- .../apis/v1/context/auth_key/handlers.rs | 2 ++ src/servers/apis/v1/context/auth_key/mod.rs | 21 +++++++++++++------ .../apis/v1/context/auth_key/routes.rs | 8 +++++-- 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index 3f85089ec..6d2d99150 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -75,6 +75,8 @@ pub async fn add_auth_key_handler( /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#generate-a-new-authentication-key) /// for more information about this endpoint. +/// +/// This endpoint has been deprecated. Use [`add_auth_key_handler`]. pub async fn generate_auth_key_handler(State(tracker): State>, Path(seconds_valid_or_key): Path) -> Response { let seconds_valid = seconds_valid_or_key; match tracker.generate_auth_key(Duration::from_secs(seconds_valid)).await { diff --git a/src/servers/apis/v1/context/auth_key/mod.rs b/src/servers/apis/v1/context/auth_key/mod.rs index b00d7a2cb..f6762b26e 100644 --- a/src/servers/apis/v1/context/auth_key/mod.rs +++ b/src/servers/apis/v1/context/auth_key/mod.rs @@ -3,8 +3,8 @@ //! Authentication keys are used to authenticate HTTP tracker `announce` and //! `scrape` requests. //! -//! When the tracker is running in `private` or `private_listed` mode, the -//! authentication keys are required to announce and scrape torrents. +//! When the tracker is running in `private` mode, the authentication keys are +//! required to announce and scrape torrents. //! //! A sample `announce` request **without** authentication key: //! @@ -22,22 +22,31 @@ //! //! # Generate a new authentication key //! -//! `POST /key/:seconds_valid` +//! `POST /keys` //! -//! It generates a new authentication key. +//! It generates a new authentication key or upload a pre-generated key. //! //! > **NOTICE**: keys expire after a certain amount of time. //! -//! **Path parameters** +//! **POST parameters** //! //! Name | Type | Description | Required | Example //! ---|---|---|---|--- +//! `key` | 32-char string (0-9, a-z, A-Z) | The optional pre-generated key. | No | `Xc1L4PbQJSFGlrgSRZl8wxSFAuMa21z7` //! `seconds_valid` | positive integer | The number of seconds the key will be valid. | Yes | `3600` //! +//! > **NOTICE**: the `key` field is optional. If is not provided the tracker +//! > will generated a random one. +//! //! **Example request** //! //! ```bash -//! curl -X POST "http://127.0.0.1:1212/api/v1/key/120?token=MyAccessToken" +//! curl -X POST http://localhost:1212/api/v1/keys?token=MyAccessToken \ +//! -H "Content-Type: application/json" \ +//! -d '{ +//! "key": "xqD6NWH9TcKrOCwDmqcdH5hF5RrbL0A6", +//! "seconds_valid": 7200 +//! }' //! ``` //! //! **Example response** `200` diff --git a/src/servers/apis/v1/context/auth_key/routes.rs b/src/servers/apis/v1/context/auth_key/routes.rs index 9452f2c0f..60ccd77ab 100644 --- a/src/servers/apis/v1/context/auth_key/routes.rs +++ b/src/servers/apis/v1/context/auth_key/routes.rs @@ -21,8 +21,12 @@ pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { .route( // code-review: Axum does not allow two routes with the same path but different path variable name. // In the new major API version, `seconds_valid` should be a POST form field so that we will have two paths: - // POST /key - // DELETE /key/:key + // + // POST /keys + // DELETE /keys/:key + // + // The POST /key/:seconds_valid has been deprecated and it will removed in the future. + // Use POST /keys &format!("{prefix}/key/:seconds_valid_or_key"), post(generate_auth_key_handler) .with_state(tracker.clone()) From 8d41d1885d79580d598f4c88ad31379ffcea32a8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jul 2024 13:10:02 +0100 Subject: [PATCH 0448/1297] fix: [#976] do not allow invalid tracker keys --- src/core/auth.rs | 51 ++++++++++++++++--- .../api/v1/contract/context/auth_key.rs | 8 +-- 2 files changed, 48 insertions(+), 11 deletions(-) diff --git a/src/core/auth.rs b/src/core/auth.rs index 00ded71ef..f041c8f2b 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -131,13 +131,37 @@ impl ExpiringKey { } } -/// A randomly generated token used for authentication. +/// A token used for authentication. /// -/// It contains lower and uppercase letters and numbers. -/// It's a 32-char string. +/// - It contains only ascii alphanumeric chars: lower and uppercase letters and +/// numbers. +/// - It's a 32-char string. #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Display, Hash)] pub struct Key(String); +impl Key { + /// # Errors + /// + /// Will return an error is the string represents an invalid key. + /// Valid keys can only contain 32 chars including 0-9, a-z and A-Z. + pub fn new(value: &str) -> Result { + if value.len() != AUTH_KEY_LENGTH { + return Err(ParseKeyError); + } + + if !value.chars().all(|c| c.is_ascii_alphanumeric()) { + return Err(ParseKeyError); + } + + Ok(Self(value.to_owned())) + } + + #[must_use] + pub fn value(&self) -> &str { + &self.0 + } +} + /// Error returned when a key cannot be parsed from a string. /// /// ```rust,no_run @@ -159,10 +183,7 @@ impl FromStr for Key { type Err = ParseKeyError; fn from_str(s: &str) -> Result { - if s.len() != AUTH_KEY_LENGTH { - return Err(ParseKeyError); - } - + Key::new(s)?; Ok(Self(s.to_string())) } } @@ -209,6 +230,22 @@ mod tests { assert!(key.is_ok()); assert_eq!(key.unwrap().to_string(), key_string); } + + #[test] + fn length_should_be_32() { + let key = Key::new(""); + assert!(key.is_err()); + + let string_longer_than_32 = "012345678901234567890123456789012"; // DevSkim: ignore DS173237 + let key = Key::new(string_longer_than_32); + assert!(key.is_err()); + } + + #[test] + fn should_only_include_alphanumeric_chars() { + let key = Key::new("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); + assert!(key.is_err()); + } } mod expiring_auth_key { diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index f02267b8b..3130503d9 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -136,10 +136,10 @@ async fn should_fail_generating_a_new_auth_key_when_the_provided_key_is_invalid( let invalid_keys = [ // "", it returns 404 // " ", it returns 404 - "-1", // Not a string - "invalid", // Invalid string - "GQEs2ZNcCm9cwEV9dBpcPB5OwNFWFiR", // Not a 32-char string - // "%QEs2ZNcCm9cwEV9dBpcPB5OwNFWFiRd", // Invalid char. todo: this doesn't fail + "-1", // Not a string + "invalid", // Invalid string + "GQEs2ZNcCm9cwEV9dBpcPB5OwNFWFiR", // Not a 32-char string + "%QEs2ZNcCm9cwEV9dBpcPB5OwNFWFiRd", // Invalid char. ]; for invalid_key in invalid_keys { From e81914b9dd1da75196f0de0a529262c16e4d1b2b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 30 Jul 2024 17:07:20 +0100 Subject: [PATCH 0449/1297] refactor: [#976] concrete errors for parsing keys --- src/core/auth.rs | 20 +++++++++++++------- tests/servers/api/v1/asserts.rs | 21 ++++++++------------- 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/core/auth.rs b/src/core/auth.rs index f041c8f2b..783faa0da 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -146,11 +146,11 @@ impl Key { /// Valid keys can only contain 32 chars including 0-9, a-z and A-Z. pub fn new(value: &str) -> Result { if value.len() != AUTH_KEY_LENGTH { - return Err(ParseKeyError); + return Err(ParseKeyError::InvalidKeyLength); } if !value.chars().all(|c| c.is_ascii_alphanumeric()) { - return Err(ParseKeyError); + return Err(ParseKeyError::InvalidChars); } Ok(Self(value.to_owned())) @@ -175,9 +175,15 @@ impl Key { /// assert_eq!(key.unwrap().to_string(), key_string); /// ``` /// -/// If the string does not contains a valid key, the parser function will return this error. -#[derive(Debug, PartialEq, Eq, Display)] -pub struct ParseKeyError; +/// If the string does not contains a valid key, the parser function will return +/// this error. +#[derive(Debug, Error)] +pub enum ParseKeyError { + #[error("Invalid key length. Key must be have 32 chars")] + InvalidKeyLength, + #[error("Invalid chars for key. Key can only alphanumeric chars (0-9, a-z, A-Z)")] + InvalidChars, +} impl FromStr for Key { type Err = ParseKeyError; @@ -188,8 +194,8 @@ impl FromStr for Key { } } -/// Verification error. Error returned when an [`ExpiringKey`] cannot be verified with the [`verify(...)`](crate::core::auth::verify) function. -/// +/// Verification error. Error returned when an [`ExpiringKey`] cannot be +/// verified with the [`verify(...)`](crate::core::auth::verify) function. #[derive(Debug, Error)] #[allow(dead_code)] pub enum Error { diff --git a/tests/servers/api/v1/asserts.rs b/tests/servers/api/v1/asserts.rs index ba906f65f..aeecfa170 100644 --- a/tests/servers/api/v1/asserts.rs +++ b/tests/servers/api/v1/asserts.rs @@ -61,6 +61,12 @@ pub async fn assert_bad_request(response: Response, body: &str) { assert_eq!(response.text().await.unwrap(), body); } +pub async fn assert_bad_request_with_text(response: Response, text: &str) { + assert_eq!(response.status(), 400); + assert_eq!(response.headers().get("content-type").unwrap(), "text/plain; charset=utf-8"); + assert!(response.text().await.unwrap().contains(text)); +} + pub async fn assert_unprocessable_content(response: Response, text: &str) { assert_eq!(response.status(), 422); assert_eq!(response.headers().get("content-type").unwrap(), "text/plain; charset=utf-8"); @@ -93,20 +99,9 @@ pub async fn assert_invalid_auth_key_get_param(response: Response, invalid_auth_ } pub async fn assert_invalid_auth_key_post_param(response: Response, invalid_auth_key: &str) { - assert_bad_request( + assert_bad_request_with_text( response, - &format!( - "Invalid URL: invalid auth key: string \"{}\", ParseKeyError", - &invalid_auth_key - ), - ) - .await; -} - -pub async fn _assert_unprocessable_auth_key_param(response: Response, _invalid_value: &str) { - assert_unprocessable_content( - response, - "Failed to deserialize the JSON body into the target type: seconds_valid: invalid type", + &format!("Invalid URL: invalid auth key: string \"{}\"", &invalid_auth_key), ) .await; } From 8d3fe72e9ad0fb3c877ec6398d097666e19c9ad1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 31 Jul 2024 15:19:57 +0100 Subject: [PATCH 0450/1297] chore(deps): [#979] add new cargo dep: serde_with We will add a new enpoint to add tracker keys where some JSON values can be null: ```console curl -X POST http://localhost:1212/api/v1/keys?token=MyAccessToken \ -H "Content-Type: application/json" \ -d '{ "key": null, "seconds_valid": null }' ``` We need to set those values to `None` in the Rsut strucut. --- Cargo.lock | 1 + Cargo.toml | 1 + 2 files changed, 2 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index e4f7a938e..234f291c5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3886,6 +3886,7 @@ dependencies = [ "serde_bytes", "serde_json", "serde_repr", + "serde_with", "thiserror", "tokio", "torrust-tracker-clock", diff --git a/Cargo.toml b/Cargo.toml index 5e4401516..4184f2ae7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,6 +66,7 @@ serde_bencode = "0" serde_bytes = "0" serde_json = { version = "1", features = ["preserve_order"] } serde_repr = "0" +serde_with = { version = "3.9.0", features = ["json"] } thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-alpha.12-develop", path = "packages/clock" } From c5beff551e51f95e05e36a315350902d3b104153 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 31 Jul 2024 15:27:40 +0100 Subject: [PATCH 0451/1297] feat: [#979] permanent keys This commit adds a new feature. It allow creating permanent keys (keys that do not expire). THis is an example for making a request to the endpoint using curl: ```console curl -X POST http://localhost:1212/api/v1/keys?token=MyAccessToken \ -H "Content-Type: application/json" \ -d '{ "key": null, "seconds_valid": null }' ``` NOTICE: both the `key` and the `seconds_valid` fields can be null. - If `key` is `null` a new random key will be generated. You can use an string with a pre-generated key like `Xc1L4PbQJSFGlrgSRZl8wxSFAuMa2110`. That will allow users to migrate to the Torrust Tracker wihtout forcing the users to re-start downloading/seeding with new keys. - If `seconds_valid` is `null` the key will be permanent. Otherwise it will expire after the seconds specified in this value. --- migrations/README.md | 5 + ...3000_torrust_tracker_create_all_tables.sql | 21 +++ ...rust_tracker_keys_valid_until_nullable.sql | 1 + ...3000_torrust_tracker_create_all_tables.sql | 19 ++ ...rust_tracker_keys_valid_until_nullable.sql | 12 ++ src/core/auth.rs | 107 ++++++++---- src/core/databases/mod.rs | 8 +- src/core/databases/mysql.rs | 39 +++-- src/core/databases/sqlite.rs | 59 +++++-- src/core/error.rs | 23 +++ src/core/mod.rs | 162 ++++++++++++++++-- src/servers/apis/v1/context/auth_key/forms.rs | 16 +- .../apis/v1/context/auth_key/handlers.rs | 48 ++---- src/servers/apis/v1/context/auth_key/mod.rs | 10 +- .../apis/v1/context/auth_key/resources.rs | 53 +++--- .../apis/v1/context/auth_key/responses.rs | 5 +- src/shared/bit_torrent/common.rs | 4 +- tests/servers/api/v1/client.rs | 2 +- .../api/v1/contract/context/auth_key.rs | 24 +-- tests/servers/http/v1/contract.rs | 4 +- 20 files changed, 455 insertions(+), 167 deletions(-) create mode 100644 migrations/README.md create mode 100644 migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql create mode 100644 migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql create mode 100644 migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql create mode 100644 migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql diff --git a/migrations/README.md b/migrations/README.md new file mode 100644 index 000000000..090c46ccb --- /dev/null +++ b/migrations/README.md @@ -0,0 +1,5 @@ +# Database Migrations + +We don't support automatic migrations yet. The tracker creates all the needed tables when it starts. The SQL sentences are hardcoded in each database driver. + +The migrations in this folder were introduced to add some new changes (permanent keys) and to allow users to migrate to the new version. In the future, we will remove the hardcoded SQL and start using a Rust crate for database migrations. For the time being, if you are using the initial schema described in the migration `20240730183000_torrust_tracker_create_all_tables.sql` you will need to run all the subsequent migrations manually. diff --git a/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql b/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql new file mode 100644 index 000000000..407ae4dd1 --- /dev/null +++ b/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql @@ -0,0 +1,21 @@ +CREATE TABLE + IF NOT EXISTS whitelist ( + id integer PRIMARY KEY AUTO_INCREMENT, + info_hash VARCHAR(40) NOT NULL UNIQUE + ); + +CREATE TABLE + IF NOT EXISTS torrents ( + id integer PRIMARY KEY AUTO_INCREMENT, + info_hash VARCHAR(40) NOT NULL UNIQUE, + completed INTEGER DEFAULT 0 NOT NULL + ); + +CREATE TABLE + IF NOT EXISTS `keys` ( + `id` INT NOT NULL AUTO_INCREMENT, + `key` VARCHAR(32) NOT NULL, + `valid_until` INT (10) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE (`key`) + ); \ No newline at end of file diff --git a/migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql b/migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql new file mode 100644 index 000000000..2602797d6 --- /dev/null +++ b/migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql @@ -0,0 +1 @@ +ALTER TABLE `keys` CHANGE `valid_until` `valid_until` INT (10); \ No newline at end of file diff --git a/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql b/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql new file mode 100644 index 000000000..bd451bf8b --- /dev/null +++ b/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql @@ -0,0 +1,19 @@ +CREATE TABLE + IF NOT EXISTS whitelist ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + info_hash TEXT NOT NULL UNIQUE + ); + +CREATE TABLE + IF NOT EXISTS torrents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + info_hash TEXT NOT NULL UNIQUE, + completed INTEGER DEFAULT 0 NOT NULL + ); + +CREATE TABLE + IF NOT EXISTS keys ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + key TEXT NOT NULL UNIQUE, + valid_until INTEGER NOT NULL + ); \ No newline at end of file diff --git a/migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql b/migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql new file mode 100644 index 000000000..c6746e3ee --- /dev/null +++ b/migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql @@ -0,0 +1,12 @@ +CREATE TABLE + IF NOT EXISTS keys_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + key TEXT NOT NULL UNIQUE, + valid_until INTEGER + ); + +INSERT INTO keys_new SELECT * FROM `keys`; + +DROP TABLE `keys`; + +ALTER TABLE keys_new RENAME TO `keys`; \ No newline at end of file diff --git a/src/core/auth.rs b/src/core/auth.rs index 783faa0da..999b43615 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -4,7 +4,7 @@ //! Tracker keys are tokens used to authenticate the tracker clients when the tracker runs //! in `private` or `private_listed` modes. //! -//! There are services to [`generate`] and [`verify`] authentication keys. +//! There are services to [`generate_key`] and [`verify_key`] authentication keys. //! //! Authentication keys are used only by [`HTTP`](crate::servers::http) trackers. All keys have an expiration time, that means //! they are only valid during a period of time. After that time the expiring key will no longer be valid. @@ -19,7 +19,7 @@ //! /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` //! pub key: Key, //! /// Timestamp, the key will be no longer valid after this timestamp -//! pub valid_until: DurationSinceUnixEpoch, +//! pub valid_until: Option, //! } //! ``` //! @@ -29,11 +29,11 @@ //! use torrust_tracker::core::auth; //! use std::time::Duration; //! -//! let expiring_key = auth::generate(Duration::new(9999, 0)); +//! let expiring_key = auth::generate_key(Some(Duration::new(9999, 0))); //! //! // And you can later verify it with: //! -//! assert!(auth::verify(&expiring_key).is_ok()); +//! assert!(auth::verify_key(&expiring_key).is_ok()); //! ``` use std::panic::Location; @@ -55,63 +55,96 @@ use tracing::debug; use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; use crate::CurrentClock; +/// It generates a new permanent random key [`PeerKey`]. #[must_use] -/// It generates a new random 32-char authentication [`ExpiringKey`] +pub fn generate_permanent_key() -> PeerKey { + generate_key(None) +} + +/// It generates a new random 32-char authentication [`PeerKey`]. +/// +/// It can be an expiring or permanent key. /// /// # Panics /// /// It would panic if the `lifetime: Duration` + Duration is more than `Duration::MAX`. -pub fn generate(lifetime: Duration) -> ExpiringKey { +/// +/// # Arguments +/// +/// * `lifetime`: if `None` the key will be permanent. +#[must_use] +pub fn generate_key(lifetime: Option) -> PeerKey { let random_id: String = thread_rng() .sample_iter(&Alphanumeric) .take(AUTH_KEY_LENGTH) .map(char::from) .collect(); - debug!("Generated key: {}, valid for: {:?} seconds", random_id, lifetime); + if let Some(lifetime) = lifetime { + debug!("Generated key: {}, valid for: {:?} seconds", random_id, lifetime); + + PeerKey { + key: random_id.parse::().unwrap(), + valid_until: Some(CurrentClock::now_add(&lifetime).unwrap()), + } + } else { + debug!("Generated key: {}, permanent", random_id); - ExpiringKey { - key: random_id.parse::().unwrap(), - valid_until: CurrentClock::now_add(&lifetime).unwrap(), + PeerKey { + key: random_id.parse::().unwrap(), + valid_until: None, + } } } -/// It verifies an [`ExpiringKey`]. It checks if the expiration date has passed. +/// It verifies an [`PeerKey`]. It checks if the expiration date has passed. +/// Permanent keys without duration (`None`) do not expire. /// /// # Errors /// -/// Will return `Error::KeyExpired` if `auth_key.valid_until` is past the `current_time`. +/// Will return: /// -/// Will return `Error::KeyInvalid` if `auth_key.valid_until` is past the `None`. -pub fn verify(auth_key: &ExpiringKey) -> Result<(), Error> { +/// - `Error::KeyExpired` if `auth_key.valid_until` is past the `current_time`. +/// - `Error::KeyInvalid` if `auth_key.valid_until` is past the `None`. +pub fn verify_key(auth_key: &PeerKey) -> Result<(), Error> { let current_time: DurationSinceUnixEpoch = CurrentClock::now(); - if auth_key.valid_until < current_time { - Err(Error::KeyExpired { - location: Location::caller(), - }) - } else { - Ok(()) + match auth_key.valid_until { + Some(valid_until) => { + if valid_until < current_time { + Err(Error::KeyExpired { + location: Location::caller(), + }) + } else { + Ok(()) + } + } + None => Ok(()), // Permanent key } } -/// An authentication key which has an expiration time. +/// An authentication key which can potentially have an expiration time. /// After that time is will automatically become invalid. #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] -pub struct ExpiringKey { +pub struct PeerKey { /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` pub key: Key, - /// Timestamp, the key will be no longer valid after this timestamp - pub valid_until: DurationSinceUnixEpoch, + + /// Timestamp, the key will be no longer valid after this timestamp. + /// If `None` the keys will not expire (permanent key). + pub valid_until: Option, } -impl std::fmt::Display for ExpiringKey { +impl std::fmt::Display for PeerKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "key: `{}`, valid until `{}`", self.key, self.expiry_time()) + match self.expiry_time() { + Some(expire_time) => write!(f, "key: `{}`, valid until `{}`", self.key, expire_time), + None => write!(f, "key: `{}`, permanent", self.key), + } } } -impl ExpiringKey { +impl PeerKey { #[must_use] pub fn key(&self) -> Key { self.key.clone() @@ -126,8 +159,8 @@ impl ExpiringKey { /// Will panic when the key timestamp overflows the internal i64 type. /// (this will naturally happen in 292.5 billion years) #[must_use] - pub fn expiry_time(&self) -> chrono::DateTime { - convert_from_timestamp_to_datetime_utc(self.valid_until) + pub fn expiry_time(&self) -> Option> { + self.valid_until.map(convert_from_timestamp_to_datetime_utc) } } @@ -194,8 +227,8 @@ impl FromStr for Key { } } -/// Verification error. Error returned when an [`ExpiringKey`] cannot be -/// verified with the [`verify(...)`](crate::core::auth::verify) function. +/// Verification error. Error returned when an [`PeerKey`] cannot be +/// verified with the (`crate::core::auth::verify_key`) function. #[derive(Debug, Error)] #[allow(dead_code)] pub enum Error { @@ -277,7 +310,7 @@ mod tests { // Set the time to the current time. clock::Stopped::local_set_to_unix_epoch(); - let expiring_key = auth::generate(Duration::from_secs(0)); + let expiring_key = auth::generate_key(Some(Duration::from_secs(0))); assert_eq!( expiring_key.to_string(), @@ -287,9 +320,9 @@ mod tests { #[test] fn should_be_generated_with_a_expiration_time() { - let expiring_key = auth::generate(Duration::new(9999, 0)); + let expiring_key = auth::generate_key(Some(Duration::new(9999, 0))); - assert!(auth::verify(&expiring_key).is_ok()); + assert!(auth::verify_key(&expiring_key).is_ok()); } #[test] @@ -298,17 +331,17 @@ mod tests { clock::Stopped::local_set_to_system_time_now(); // Make key that is valid for 19 seconds. - let expiring_key = auth::generate(Duration::from_secs(19)); + let expiring_key = auth::generate_key(Some(Duration::from_secs(19))); // Mock the time has passed 10 sec. clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); - assert!(auth::verify(&expiring_key).is_ok()); + assert!(auth::verify_key(&expiring_key).is_ok()); // Mock the time has passed another 10 sec. clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); - assert!(auth::verify(&expiring_key).is_err()); + assert!(auth::verify_key(&expiring_key).is_err()); } } } diff --git a/src/core/databases/mod.rs b/src/core/databases/mod.rs index cdb4c7ce5..f559eb80e 100644 --- a/src/core/databases/mod.rs +++ b/src/core/databases/mod.rs @@ -195,11 +195,11 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to load. - fn load_keys(&self) -> Result, Error>; + fn load_keys(&self) -> Result, Error>; /// It gets an expiring authentication key from the database. /// - /// It returns `Some(ExpiringKey)` if a [`ExpiringKey`](crate::core::auth::ExpiringKey) + /// It returns `Some(PeerKey)` if a [`PeerKey`](crate::core::auth::PeerKey) /// with the input [`Key`] exists, `None` otherwise. /// /// # Context: Authentication Keys @@ -207,7 +207,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to load. - fn get_key_from_keys(&self, key: &Key) -> Result, Error>; + fn get_key_from_keys(&self, key: &Key) -> Result, Error>; /// It adds an expiring authentication key to the database. /// @@ -216,7 +216,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to save. - fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result; + fn add_key_to_keys(&self, auth_key: &auth::PeerKey) -> Result; /// It removes an expiring authentication key from the database. /// diff --git a/src/core/databases/mysql.rs b/src/core/databases/mysql.rs index 40eced900..3a06c4982 100644 --- a/src/core/databases/mysql.rs +++ b/src/core/databases/mysql.rs @@ -60,7 +60,7 @@ impl Database for Mysql { CREATE TABLE IF NOT EXISTS `keys` ( `id` INT NOT NULL AUTO_INCREMENT, `key` VARCHAR({}) NOT NULL, - `valid_until` INT(10) NOT NULL, + `valid_until` INT(10), PRIMARY KEY (`id`), UNIQUE (`key`) );", @@ -119,14 +119,20 @@ impl Database for Mysql { } /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). - fn load_keys(&self) -> Result, Error> { + fn load_keys(&self) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let keys = conn.query_map( "SELECT `key`, valid_until FROM `keys`", - |(key, valid_until): (String, i64)| auth::ExpiringKey { - key: key.parse::().unwrap(), - valid_until: Duration::from_secs(valid_until.unsigned_abs()), + |(key, valid_until): (String, Option)| match valid_until { + Some(valid_until) => auth::PeerKey { + key: key.parse::().unwrap(), + valid_until: Some(Duration::from_secs(valid_until.unsigned_abs())), + }, + None => auth::PeerKey { + key: key.parse::().unwrap(), + valid_until: None, + }, }, )?; @@ -197,28 +203,37 @@ impl Database for Mysql { } /// Refer to [`databases::Database::get_key_from_keys`](crate::core::databases::Database::get_key_from_keys). - fn get_key_from_keys(&self, key: &Key) -> Result, Error> { + fn get_key_from_keys(&self, key: &Key) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - let query = conn.exec_first::<(String, i64), _, _>( + let query = conn.exec_first::<(String, Option), _, _>( "SELECT `key`, valid_until FROM `keys` WHERE `key` = :key", params! { "key" => key.to_string() }, ); let key = query?; - Ok(key.map(|(key, expiry)| auth::ExpiringKey { - key: key.parse::().unwrap(), - valid_until: Duration::from_secs(expiry.unsigned_abs()), + Ok(key.map(|(key, opt_valid_until)| match opt_valid_until { + Some(valid_until) => auth::PeerKey { + key: key.parse::().unwrap(), + valid_until: Some(Duration::from_secs(valid_until.unsigned_abs())), + }, + None => auth::PeerKey { + key: key.parse::().unwrap(), + valid_until: None, + }, })) } /// Refer to [`databases::Database::add_key_to_keys`](crate::core::databases::Database::add_key_to_keys). - fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result { + fn add_key_to_keys(&self, auth_key: &auth::PeerKey) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let key = auth_key.key.to_string(); - let valid_until = auth_key.valid_until.as_secs().to_string(); + let valid_until = match auth_key.valid_until { + Some(valid_until) => valid_until.as_secs().to_string(), + None => todo!(), + }; conn.exec_drop( "INSERT INTO `keys` (`key`, valid_until) VALUES (:key, :valid_until)", diff --git a/src/core/databases/sqlite.rs b/src/core/databases/sqlite.rs index 3acbf9e77..69470ee04 100644 --- a/src/core/databases/sqlite.rs +++ b/src/core/databases/sqlite.rs @@ -3,6 +3,8 @@ use std::panic::Location; use std::str::FromStr; use r2d2::Pool; +use r2d2_sqlite::rusqlite::params; +use r2d2_sqlite::rusqlite::types::Null; use r2d2_sqlite::SqliteConnectionManager; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrents}; @@ -51,7 +53,7 @@ impl Database for Sqlite { CREATE TABLE IF NOT EXISTS keys ( id INTEGER PRIMARY KEY AUTOINCREMENT, key TEXT NOT NULL UNIQUE, - valid_until INTEGER NOT NULL + valid_until INTEGER );" .to_string(); @@ -104,22 +106,28 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). - fn load_keys(&self) -> Result, Error> { + fn load_keys(&self) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT key, valid_until FROM keys")?; let keys_iter = stmt.query_map([], |row| { let key: String = row.get(0)?; - let valid_until: i64 = row.get(1)?; - - Ok(auth::ExpiringKey { - key: key.parse::().unwrap(), - valid_until: DurationSinceUnixEpoch::from_secs(valid_until.unsigned_abs()), - }) + let opt_valid_until: Option = row.get(1)?; + + match opt_valid_until { + Some(valid_until) => Ok(auth::PeerKey { + key: key.parse::().unwrap(), + valid_until: Some(DurationSinceUnixEpoch::from_secs(valid_until.unsigned_abs())), + }), + None => Ok(auth::PeerKey { + key: key.parse::().unwrap(), + valid_until: None, + }), + } })?; - let keys: Vec = keys_iter.filter_map(std::result::Result::ok).collect(); + let keys: Vec = keys_iter.filter_map(std::result::Result::ok).collect(); Ok(keys) } @@ -208,7 +216,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::get_key_from_keys`](crate::core::databases::Database::get_key_from_keys). - fn get_key_from_keys(&self, key: &Key) -> Result, Error> { + fn get_key_from_keys(&self, key: &Key) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT key, valid_until FROM keys WHERE key = ?")?; @@ -218,23 +226,36 @@ impl Database for Sqlite { let key = rows.next()?; Ok(key.map(|f| { - let expiry: i64 = f.get(1).unwrap(); + let valid_until: Option = f.get(1).unwrap(); let key: String = f.get(0).unwrap(); - auth::ExpiringKey { - key: key.parse::().unwrap(), - valid_until: DurationSinceUnixEpoch::from_secs(expiry.unsigned_abs()), + + match valid_until { + Some(valid_until) => auth::PeerKey { + key: key.parse::().unwrap(), + valid_until: Some(DurationSinceUnixEpoch::from_secs(valid_until.unsigned_abs())), + }, + None => auth::PeerKey { + key: key.parse::().unwrap(), + valid_until: None, + }, } })) } /// Refer to [`databases::Database::add_key_to_keys`](crate::core::databases::Database::add_key_to_keys). - fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result { + fn add_key_to_keys(&self, auth_key: &auth::PeerKey) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - let insert = conn.execute( - "INSERT INTO keys (key, valid_until) VALUES (?1, ?2)", - [auth_key.key.to_string(), auth_key.valid_until.as_secs().to_string()], - )?; + let insert = match auth_key.valid_until { + Some(valid_until) => conn.execute( + "INSERT INTO keys (key, valid_until) VALUES (?1, ?2)", + [auth_key.key.to_string(), valid_until.as_secs().to_string()], + )?, + None => conn.execute( + "INSERT INTO keys (key, valid_until) VALUES (?1, ?2)", + params![auth_key.key.to_string(), Null], + )?, + }; if insert == 0 { Err(Error::InsertFailed { diff --git a/src/core/error.rs b/src/core/error.rs index a826de349..d89b030c4 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -11,6 +11,9 @@ use std::panic::Location; use torrust_tracker_located_error::LocatedError; use torrust_tracker_primitives::info_hash::InfoHash; +use super::auth::ParseKeyError; +use super::databases; + /// Authentication or authorization error returned by the core `Tracker` #[derive(thiserror::Error, Debug, Clone)] pub enum Error { @@ -20,6 +23,7 @@ pub enum Error { key: super::auth::Key, source: LocatedError<'static, dyn std::error::Error + Send + Sync>, }, + #[error("The peer is not authenticated, {location}")] PeerNotAuthenticated { location: &'static Location<'static> }, @@ -30,3 +34,22 @@ pub enum Error { location: &'static Location<'static>, }, } + +/// Errors related to peers keys. +#[allow(clippy::module_name_repetitions)] +#[derive(thiserror::Error, Debug, Clone)] +pub enum PeerKeyError { + #[error("Invalid peer key duration: {seconds_valid:?}, is not valid")] + DurationOverflow { seconds_valid: u64 }, + + #[error("Invalid key: {key}")] + InvalidKey { + key: String, + source: LocatedError<'static, ParseKeyError>, + }, + + #[error("Can't persist key: {source}")] + DatabaseError { + source: LocatedError<'static, databases::error::Error>, + }, +} diff --git a/src/core/mod.rs b/src/core/mod.rs index f0853ec27..f4cff8daf 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -453,13 +453,15 @@ use std::panic::Location; use std::sync::Arc; use std::time::Duration; -use auth::ExpiringKey; +use auth::PeerKey; use databases::driver::Driver; use derive_more::Constructor; +use error::PeerKeyError; use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::v2::database; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; +use torrust_tracker_located_error::Located; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; @@ -492,7 +494,7 @@ pub struct Tracker { database: Arc>, /// Tracker users' keys. Only for private trackers. - keys: tokio::sync::RwLock>, + keys: tokio::sync::RwLock>, /// The list of allowed torrents. Only for listed trackers. whitelist: tokio::sync::RwLock>, @@ -556,6 +558,20 @@ impl ScrapeData { } } +/// This type contains the info needed to add a new tracker key. +/// +/// You can upload a pre-generated key or let the app to generate a new one. +/// You can also set an expiration date or leave it empty (`None`) if you want +/// to create a permanent key that does not expire. +#[derive(Debug)] +pub struct AddKeyRequest { + /// The pre-generated key. Use `None` to generate a random key. + pub opt_key: Option, + + /// How long the key will be valid in seconds. Use `None` for permanent keys. + pub opt_seconds_valid: Option, +} + impl Tracker { /// `Tracker` constructor. /// @@ -793,9 +809,96 @@ impl Tracker { } } + /// Adds new peer keys to the tracker. + /// + /// Keys can be pre-generated or randomly created. They can also be permanent or expire. + /// + /// # Errors + /// + /// Will return an error if: + /// + /// - The key duration overflows the duration type maximum value. + /// - The provided pre-generated key is invalid. + /// - The key could not been persisted due to database issues. + pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { + // code-review: all methods related to keys should be moved to a new independent "keys" service. + + match add_key_req.opt_key { + // Upload pre-generated key + Some(pre_existing_key) => { + if let Some(seconds_valid) = add_key_req.opt_seconds_valid { + // Expiring key + let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(seconds_valid)) else { + return Err(PeerKeyError::DurationOverflow { seconds_valid }); + }; + + let key = pre_existing_key.parse::(); + + match key { + Ok(key) => match self.add_auth_key(key, Some(valid_until)).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + Err(err) => Err(PeerKeyError::InvalidKey { + key: pre_existing_key, + source: Located(err).into(), + }), + } + } else { + // Permanent key + let key = pre_existing_key.parse::(); + + match key { + Ok(key) => match self.add_permanent_auth_key(key).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + Err(err) => Err(PeerKeyError::InvalidKey { + key: pre_existing_key, + source: Located(err).into(), + }), + } + } + } + // Generate a new random key + None => match add_key_req.opt_seconds_valid { + // Expiring key + Some(seconds_valid) => match self.generate_auth_key(Some(Duration::from_secs(seconds_valid))).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + // Permanent key + None => match self.generate_permanent_auth_key().await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + }, + } + } + + /// It generates a new permanent authentication key. + /// + /// Authentication keys are used by HTTP trackers. + /// + /// # Context: Authentication + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `auth_key` to the database. + pub async fn generate_permanent_auth_key(&self) -> Result { + self.generate_auth_key(None).await + } + /// It generates a new expiring authentication key. - /// `lifetime` param is the duration in seconds for the new key. - /// The key will be no longer valid after `lifetime` seconds. + /// /// Authentication keys are used by HTTP trackers. /// /// # Context: Authentication @@ -803,14 +906,37 @@ impl Tracker { /// # Errors /// /// Will return a `database::Error` if unable to add the `auth_key` to the database. - pub async fn generate_auth_key(&self, lifetime: Duration) -> Result { - let auth_key = auth::generate(lifetime); + /// + /// # Arguments + /// + /// * `lifetime` - The duration in seconds for the new key. The key will be + /// no longer valid after `lifetime` seconds. + pub async fn generate_auth_key(&self, lifetime: Option) -> Result { + let auth_key = auth::generate_key(lifetime); self.database.add_key_to_keys(&auth_key)?; self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); Ok(auth_key) } + /// It adds a pre-generated permanent authentication key. + /// + /// Authentication keys are used by HTTP trackers. + /// + /// # Context: Authentication + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `auth_key` to the + /// database. For example, if the key already exist. + /// + /// # Arguments + /// + /// * `key` - The pre-generated key. + pub async fn add_permanent_auth_key(&self, key: Key) -> Result { + self.add_auth_key(key, None).await + } + /// It adds a pre-generated authentication key. /// /// Authentication keys are used by HTTP trackers. @@ -824,14 +950,15 @@ impl Tracker { /// /// # Arguments /// + /// * `key` - The pre-generated key. /// * `lifetime` - The duration in seconds for the new key. The key will be /// no longer valid after `lifetime` seconds. pub async fn add_auth_key( &self, key: Key, - valid_until: DurationSinceUnixEpoch, - ) -> Result { - let auth_key = ExpiringKey { key, valid_until }; + valid_until: Option, + ) -> Result { + let auth_key = PeerKey { key, valid_until }; // code-review: should we return a friendly error instead of the DB // constrain error when the key already exist? For now, it's returning @@ -869,7 +996,7 @@ impl Tracker { location: Location::caller(), key: Box::new(key.clone()), }), - Some(key) => auth::verify(key), + Some(key) => auth::verify_key(key), } } @@ -1661,16 +1788,19 @@ mod tests { async fn it_should_generate_the_expiring_authentication_keys() { let tracker = private_tracker(); - let key = tracker.generate_auth_key(Duration::from_secs(100)).await.unwrap(); + let key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); - assert_eq!(key.valid_until, CurrentClock::now_add(&Duration::from_secs(100)).unwrap()); + assert_eq!( + key.valid_until, + Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + ); } #[tokio::test] async fn it_should_authenticate_a_peer_by_using_a_key() { let tracker = private_tracker(); - let expiring_key = tracker.generate_auth_key(Duration::from_secs(100)).await.unwrap(); + let expiring_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); let result = tracker.authenticate(&expiring_key.key()).await; @@ -1694,7 +1824,7 @@ mod tests { // `verify_auth_key` should be a private method. let tracker = private_tracker(); - let expiring_key = tracker.generate_auth_key(Duration::from_secs(100)).await.unwrap(); + let expiring_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); assert!(tracker.verify_auth_key(&expiring_key.key()).await.is_ok()); } @@ -1712,7 +1842,7 @@ mod tests { async fn it_should_remove_an_authentication_key() { let tracker = private_tracker(); - let expiring_key = tracker.generate_auth_key(Duration::from_secs(100)).await.unwrap(); + let expiring_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); let result = tracker.remove_auth_key(&expiring_key.key()).await; @@ -1724,7 +1854,7 @@ mod tests { async fn it_should_load_authentication_keys_from_the_database() { let tracker = private_tracker(); - let expiring_key = tracker.generate_auth_key(Duration::from_secs(100)).await.unwrap(); + let expiring_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); // Remove the newly generated key in memory tracker.keys.write().await.remove(&expiring_key.key()); diff --git a/src/servers/apis/v1/context/auth_key/forms.rs b/src/servers/apis/v1/context/auth_key/forms.rs index 9c023ab72..5dfea6e80 100644 --- a/src/servers/apis/v1/context/auth_key/forms.rs +++ b/src/servers/apis/v1/context/auth_key/forms.rs @@ -1,8 +1,22 @@ use serde::{Deserialize, Serialize}; +use serde_with::{serde_as, DefaultOnNull}; +/// This type contains the info needed to add a new tracker key. +/// +/// You can upload a pre-generated key or let the app to generate a new one. +/// You can also set an expiration date or leave it empty (`None`) if you want +/// to create permanent key that does not expire. +#[serde_as] #[derive(Serialize, Deserialize, Debug)] pub struct AddKeyForm { + /// The pre-generated key. Use `None` (null in json) to generate a random key. + #[serde_as(deserialize_as = "DefaultOnNull")] #[serde(rename = "key")] pub opt_key: Option, - pub seconds_valid: u64, + + /// How long the key will be valid in seconds. Use `None` (null in json) for + /// permanent keys. + #[serde_as(deserialize_as = "DefaultOnNull")] + #[serde(rename = "seconds_valid")] + pub opt_seconds_valid: Option, } diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index 6d2d99150..fed3ad301 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -6,18 +6,16 @@ use std::time::Duration; use axum::extract::{self, Path, State}; use axum::response::Response; use serde::Deserialize; -use torrust_tracker_clock::clock::Time; use super::forms::AddKeyForm; use super::responses::{ - auth_key_response, failed_to_add_key_response, failed_to_delete_key_response, failed_to_generate_key_response, - failed_to_reload_keys_response, invalid_auth_key_duration_response, invalid_auth_key_response, + auth_key_response, failed_to_delete_key_response, failed_to_generate_key_response, failed_to_reload_keys_response, + invalid_auth_key_duration_response, invalid_auth_key_response, }; use crate::core::auth::Key; -use crate::core::Tracker; +use crate::core::{AddKeyRequest, Tracker}; use crate::servers::apis::v1::context::auth_key::resources::AuthKey; use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_response}; -use crate::CurrentClock; /// It handles the request to add a new authentication key. /// @@ -36,31 +34,21 @@ pub async fn add_auth_key_handler( State(tracker): State>, extract::Json(add_key_form): extract::Json, ) -> Response { - match add_key_form.opt_key { - Some(pre_existing_key) => { - let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(add_key_form.seconds_valid)) else { - return invalid_auth_key_duration_response(add_key_form.seconds_valid); - }; - - let key = pre_existing_key.parse::(); - - match key { - Ok(key) => match tracker.add_auth_key(key, valid_until).await { - Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), - Err(e) => failed_to_add_key_response(e), - }, - Err(e) => invalid_auth_key_response(&pre_existing_key, &e), - } - } - None => { - match tracker - .generate_auth_key(Duration::from_secs(add_key_form.seconds_valid)) - .await - { - Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), - Err(e) => failed_to_generate_key_response(e), + match tracker + .add_peer_key(AddKeyRequest { + opt_key: add_key_form.opt_key.clone(), + opt_seconds_valid: add_key_form.opt_seconds_valid, + }) + .await + { + Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), + Err(err) => match err { + crate::core::error::PeerKeyError::DurationOverflow { seconds_valid } => { + invalid_auth_key_duration_response(seconds_valid) } - } + crate::core::error::PeerKeyError::InvalidKey { key, source } => invalid_auth_key_response(&key, source), + crate::core::error::PeerKeyError::DatabaseError { source } => failed_to_generate_key_response(source), + }, } } @@ -79,7 +67,7 @@ pub async fn add_auth_key_handler( /// This endpoint has been deprecated. Use [`add_auth_key_handler`]. pub async fn generate_auth_key_handler(State(tracker): State>, Path(seconds_valid_or_key): Path) -> Response { let seconds_valid = seconds_valid_or_key; - match tracker.generate_auth_key(Duration::from_secs(seconds_valid)).await { + match tracker.generate_auth_key(Some(Duration::from_secs(seconds_valid))).await { Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), Err(e) => failed_to_generate_key_response(e), } diff --git a/src/servers/apis/v1/context/auth_key/mod.rs b/src/servers/apis/v1/context/auth_key/mod.rs index f6762b26e..b4112f21f 100644 --- a/src/servers/apis/v1/context/auth_key/mod.rs +++ b/src/servers/apis/v1/context/auth_key/mod.rs @@ -26,17 +26,15 @@ //! //! It generates a new authentication key or upload a pre-generated key. //! -//! > **NOTICE**: keys expire after a certain amount of time. -//! //! **POST parameters** //! //! Name | Type | Description | Required | Example //! ---|---|---|---|--- -//! `key` | 32-char string (0-9, a-z, A-Z) | The optional pre-generated key. | No | `Xc1L4PbQJSFGlrgSRZl8wxSFAuMa21z7` -//! `seconds_valid` | positive integer | The number of seconds the key will be valid. | Yes | `3600` +//! `key` | 32-char string (0-9, a-z, A-Z) or `null` | The optional pre-generated key. | Yes | `Xc1L4PbQJSFGlrgSRZl8wxSFAuMa21z7` or `null` +//! `seconds_valid` | positive integer or `null` | The number of seconds the key will be valid. | Yes | `3600` or `null` //! -//! > **NOTICE**: the `key` field is optional. If is not provided the tracker -//! > will generated a random one. +//! > **NOTICE**: the `key` and `seconds_valid` fields are optional. If `key` is not provided the tracker +//! > will generated a random one. If `seconds_valid` field is not provided the key will be permanent. You can use the `null` value. //! //! **Example request** //! diff --git a/src/servers/apis/v1/context/auth_key/resources.rs b/src/servers/apis/v1/context/auth_key/resources.rs index 3671438c2..c26b2c4d3 100644 --- a/src/servers/apis/v1/context/auth_key/resources.rs +++ b/src/servers/apis/v1/context/auth_key/resources.rs @@ -12,27 +12,36 @@ pub struct AuthKey { pub key: String, /// The timestamp when the key will expire. #[deprecated(since = "3.0.0", note = "please use `expiry_time` instead")] - pub valid_until: u64, // todo: remove when the torrust-index-backend starts using the `expiry_time` attribute. + pub valid_until: Option, // todo: remove when the torrust-index-backend starts using the `expiry_time` attribute. /// The ISO 8601 timestamp when the key will expire. - pub expiry_time: String, + pub expiry_time: Option, } -impl From for auth::ExpiringKey { +impl From for auth::PeerKey { fn from(auth_key_resource: AuthKey) -> Self { - auth::ExpiringKey { + auth::PeerKey { key: auth_key_resource.key.parse::().unwrap(), - valid_until: convert_from_iso_8601_to_timestamp(&auth_key_resource.expiry_time), + valid_until: auth_key_resource + .expiry_time + .map(|expiry_time| convert_from_iso_8601_to_timestamp(&expiry_time)), } } } #[allow(deprecated)] -impl From for AuthKey { - fn from(auth_key: auth::ExpiringKey) -> Self { - AuthKey { - key: auth_key.key.to_string(), - valid_until: auth_key.valid_until.as_secs(), - expiry_time: auth_key.expiry_time().to_string(), +impl From for AuthKey { + fn from(auth_key: auth::PeerKey) -> Self { + match (auth_key.valid_until, auth_key.expiry_time()) { + (Some(valid_until), Some(expiry_time)) => AuthKey { + key: auth_key.key.to_string(), + valid_until: Some(valid_until.as_secs()), + expiry_time: Some(expiry_time.to_string()), + }, + _ => AuthKey { + key: auth_key.key.to_string(), + valid_until: None, + expiry_time: None, + }, } } } @@ -72,15 +81,15 @@ mod tests { let auth_key_resource = AuthKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".to_string(), // cspell:disable-line - valid_until: one_hour_after_unix_epoch().timestamp, - expiry_time: one_hour_after_unix_epoch().iso_8601_v1, + valid_until: Some(one_hour_after_unix_epoch().timestamp), + expiry_time: Some(one_hour_after_unix_epoch().iso_8601_v1), }; assert_eq!( - auth::ExpiringKey::from(auth_key_resource), - auth::ExpiringKey { + auth::PeerKey::from(auth_key_resource), + auth::PeerKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".parse::().unwrap(), // cspell:disable-line - valid_until: CurrentClock::now_add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap() + valid_until: Some(CurrentClock::now_add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap()) } ); } @@ -90,17 +99,17 @@ mod tests { fn it_should_be_convertible_from_an_auth_key() { clock::Stopped::local_set_to_unix_epoch(); - let auth_key = auth::ExpiringKey { + let auth_key = auth::PeerKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".parse::().unwrap(), // cspell:disable-line - valid_until: CurrentClock::now_add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap(), + valid_until: Some(CurrentClock::now_add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap()), }; assert_eq!( AuthKey::from(auth_key), AuthKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".to_string(), // cspell:disable-line - valid_until: one_hour_after_unix_epoch().timestamp, - expiry_time: one_hour_after_unix_epoch().iso_8601_v2, + valid_until: Some(one_hour_after_unix_epoch().timestamp), + expiry_time: Some(one_hour_after_unix_epoch().iso_8601_v2), } ); } @@ -111,8 +120,8 @@ mod tests { assert_eq!( serde_json::to_string(&AuthKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".to_string(), // cspell:disable-line - valid_until: one_hour_after_unix_epoch().timestamp, - expiry_time: one_hour_after_unix_epoch().iso_8601_v1, + valid_until: Some(one_hour_after_unix_epoch().timestamp), + expiry_time: Some(one_hour_after_unix_epoch().iso_8601_v1), }) .unwrap(), "{\"key\":\"IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM\",\"valid_until\":60,\"expiry_time\":\"1970-01-01T00:01:00.000Z\"}" // cspell:disable-line diff --git a/src/servers/apis/v1/context/auth_key/responses.rs b/src/servers/apis/v1/context/auth_key/responses.rs index dfe449b46..4905d9adc 100644 --- a/src/servers/apis/v1/context/auth_key/responses.rs +++ b/src/servers/apis/v1/context/auth_key/responses.rs @@ -4,7 +4,6 @@ use std::error::Error; use axum::http::{header, StatusCode}; use axum::response::{IntoResponse, Response}; -use crate::core::auth::ParseKeyError; use crate::servers::apis::v1::context::auth_key::resources::AuthKey; use crate::servers::apis::v1::responses::{bad_request_response, unhandled_rejection_response}; @@ -51,8 +50,8 @@ pub fn failed_to_reload_keys_response(e: E) -> Response { } #[must_use] -pub fn invalid_auth_key_response(auth_key: &str, error: &ParseKeyError) -> Response { - bad_request_response(&format!("Invalid URL: invalid auth key: string \"{auth_key}\", {error}")) +pub fn invalid_auth_key_response(auth_key: &str, e: E) -> Response { + bad_request_response(&format!("Invalid URL: invalid auth key: string \"{auth_key}\", {e}")) } #[must_use] diff --git a/src/shared/bit_torrent/common.rs b/src/shared/bit_torrent/common.rs index 3dd059a6a..46026ac47 100644 --- a/src/shared/bit_torrent/common.rs +++ b/src/shared/bit_torrent/common.rs @@ -17,6 +17,6 @@ pub const MAX_SCRAPE_TORRENTS: u8 = 74; /// HTTP tracker authentication key length. /// -/// See function to [`generate`](crate::core::auth::generate) the -/// [`ExpiringKeys`](crate::core::auth::ExpiringKey) for more information. +/// For more information see function [`generate_key`](crate::core::auth::generate_key) to generate the +/// [`PeerKey`](crate::core::auth::PeerKey). pub const AUTH_KEY_LENGTH: usize = 32; diff --git a/tests/servers/api/v1/client.rs b/tests/servers/api/v1/client.rs index 91f18acac..3d95c10ca 100644 --- a/tests/servers/api/v1/client.rs +++ b/tests/servers/api/v1/client.rs @@ -134,5 +134,5 @@ pub async fn get(path: &str, query: Option) -> Response { pub struct AddKeyForm { #[serde(rename = "key")] pub opt_key: Option, - pub seconds_valid: u64, + pub seconds_valid: Option, } diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 3130503d9..cd6d2544f 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -20,7 +20,7 @@ async fn should_allow_generating_a_new_random_auth_key() { let response = Client::new(env.get_connection_info()) .add_auth_key(AddKeyForm { opt_key: None, - seconds_valid: 60, + seconds_valid: Some(60), }) .await; @@ -43,7 +43,7 @@ async fn should_allow_uploading_a_preexisting_auth_key() { let response = Client::new(env.get_connection_info()) .add_auth_key(AddKeyForm { opt_key: Some("Xc1L4PbQJSFGlrgSRZl8wxSFAuMa21z5".to_string()), - seconds_valid: 60, + seconds_valid: Some(60), }) .await; @@ -66,7 +66,7 @@ async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) .add_auth_key(AddKeyForm { opt_key: None, - seconds_valid: 60, + seconds_valid: Some(60), }) .await; @@ -75,7 +75,7 @@ async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) .add_auth_key(AddKeyForm { opt_key: None, - seconds_valid: 60, + seconds_valid: Some(60), }) .await; @@ -93,7 +93,7 @@ async fn should_fail_when_the_auth_key_cannot_be_generated() { let response = Client::new(env.get_connection_info()) .add_auth_key(AddKeyForm { opt_key: None, - seconds_valid: 60, + seconds_valid: Some(60), }) .await; @@ -109,7 +109,7 @@ async fn should_allow_deleting_an_auth_key() { let seconds_valid = 60; let auth_key = env .tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) + .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -223,7 +223,7 @@ async fn should_fail_when_the_auth_key_cannot_be_deleted() { let seconds_valid = 60; let auth_key = env .tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) + .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -247,7 +247,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { // Generate new auth key let auth_key = env .tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) + .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -260,7 +260,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { // Generate new auth key let auth_key = env .tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) + .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -279,7 +279,7 @@ async fn should_allow_reloading_keys() { let seconds_valid = 60; env.tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) + .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -296,7 +296,7 @@ async fn should_fail_when_keys_cannot_be_reloaded() { let seconds_valid = 60; env.tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) + .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -315,7 +315,7 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { let seconds_valid = 60; env.tracker - .generate_auth_key(Duration::from_secs(seconds_valid)) + .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index e4a35d0c5..14c237984 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -1261,7 +1261,7 @@ mod configured_as_private { async fn should_respond_to_authenticated_peers() { let env = Started::new(&configuration::ephemeral_private().into()).await; - let expiring_key = env.tracker.generate_auth_key(Duration::from_secs(60)).await.unwrap(); + let expiring_key = env.tracker.generate_auth_key(Some(Duration::from_secs(60))).await.unwrap(); let response = Client::authenticated(*env.bind_address(), expiring_key.key()) .announce(&QueryBuilder::default().query()) @@ -1393,7 +1393,7 @@ mod configured_as_private { .build(), ); - let expiring_key = env.tracker.generate_auth_key(Duration::from_secs(60)).await.unwrap(); + let expiring_key = env.tracker.generate_auth_key(Some(Duration::from_secs(60))).await.unwrap(); let response = Client::authenticated(*env.bind_address(), expiring_key.key()) .scrape( From e8e935caf0b8b474d07e30dacf4627200aa0150f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 Aug 2024 13:09:56 +0100 Subject: [PATCH 0452/1297] feat: [#978] add a config option to disable cheking keys' expiration When the tracker is running in private mode you can disable checking keys' expiration in the configuration with: ```toml [core] private = false [core.private_mode] check_keys_expiration = true ``` All keys will be valid as long as they exist in the database. --- packages/configuration/src/v2/core.rs | 39 +++++++++++++++++++++++++++ src/core/auth.rs | 10 +++---- src/core/mod.rs | 32 ++++++++++++++++++++-- 3 files changed, 74 insertions(+), 7 deletions(-) diff --git a/packages/configuration/src/v2/core.rs b/packages/configuration/src/v2/core.rs index 09280917c..5d6afdee2 100644 --- a/packages/configuration/src/v2/core.rs +++ b/packages/configuration/src/v2/core.rs @@ -1,3 +1,4 @@ +use derive_more::{Constructor, Display}; use serde::{Deserialize, Serialize}; use super::network::Network; @@ -32,6 +33,10 @@ pub struct Core { #[serde(default = "Core::default_private")] pub private: bool, + // Configuration specific when the tracker is running in private mode. + #[serde(default = "Core::default_private_mode")] + pub private_mode: Option, + // Tracker policy configuration. #[serde(default = "Core::default_tracker_policy")] pub tracker_policy: TrackerPolicy, @@ -54,6 +59,7 @@ impl Default for Core { listed: Self::default_listed(), net: Self::default_network(), private: Self::default_private(), + private_mode: Self::default_private_mode(), tracker_policy: Self::default_tracker_policy(), tracker_usage_statistics: Self::default_tracker_usage_statistics(), } @@ -85,6 +91,14 @@ impl Core { false } + fn default_private_mode() -> Option { + if Self::default_private() { + Some(PrivateMode::default()) + } else { + None + } + } + fn default_tracker_policy() -> TrackerPolicy { TrackerPolicy::default() } @@ -92,3 +106,28 @@ impl Core { true } } + +/// Configuration specific when the tracker is running in private mode. +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Copy, Constructor, Display)] +pub struct PrivateMode { + /// A flag to disable expiration date for peer keys. + /// + /// When true, if the keys is not permanent the expiration date will be + /// ignored. The key will be accepted even if it has expired. + #[serde(default = "PrivateMode::default_check_keys_expiration")] + pub check_keys_expiration: bool, +} + +impl Default for PrivateMode { + fn default() -> Self { + Self { + check_keys_expiration: Self::default_check_keys_expiration(), + } + } +} + +impl PrivateMode { + fn default_check_keys_expiration() -> bool { + true + } +} diff --git a/src/core/auth.rs b/src/core/auth.rs index 999b43615..fef5b3098 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -33,7 +33,7 @@ //! //! // And you can later verify it with: //! -//! assert!(auth::verify_key(&expiring_key).is_ok()); +//! assert!(auth::verify_key_expiration(&expiring_key).is_ok()); //! ``` use std::panic::Location; @@ -106,7 +106,7 @@ pub fn generate_key(lifetime: Option) -> PeerKey { /// /// - `Error::KeyExpired` if `auth_key.valid_until` is past the `current_time`. /// - `Error::KeyInvalid` if `auth_key.valid_until` is past the `None`. -pub fn verify_key(auth_key: &PeerKey) -> Result<(), Error> { +pub fn verify_key_expiration(auth_key: &PeerKey) -> Result<(), Error> { let current_time: DurationSinceUnixEpoch = CurrentClock::now(); match auth_key.valid_until { @@ -322,7 +322,7 @@ mod tests { fn should_be_generated_with_a_expiration_time() { let expiring_key = auth::generate_key(Some(Duration::new(9999, 0))); - assert!(auth::verify_key(&expiring_key).is_ok()); + assert!(auth::verify_key_expiration(&expiring_key).is_ok()); } #[test] @@ -336,12 +336,12 @@ mod tests { // Mock the time has passed 10 sec. clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); - assert!(auth::verify_key(&expiring_key).is_ok()); + assert!(auth::verify_key_expiration(&expiring_key).is_ok()); // Mock the time has passed another 10 sec. clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); - assert!(auth::verify_key(&expiring_key).is_err()); + assert!(auth::verify_key_expiration(&expiring_key).is_err()); } } } diff --git a/src/core/mod.rs b/src/core/mod.rs index f4cff8daf..a8c265408 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -996,7 +996,16 @@ impl Tracker { location: Location::caller(), key: Box::new(key.clone()), }), - Some(key) => auth::verify_key(key), + Some(key) => match self.config.private_mode { + Some(private_mode) => { + if private_mode.check_keys_expiration { + return auth::verify_key_expiration(key); + } + + Ok(()) + } + None => auth::verify_key_expiration(key), + }, } } @@ -1779,8 +1788,9 @@ mod tests { use std::time::Duration; use torrust_tracker_clock::clock::Time; + use torrust_tracker_configuration::v2::core::PrivateMode; - use crate::core::auth; + use crate::core::auth::{self, Key}; use crate::core::tests::the_tracker::private_tracker; use crate::CurrentClock; @@ -1829,6 +1839,24 @@ mod tests { assert!(tracker.verify_auth_key(&expiring_key.key()).await.is_ok()); } + #[tokio::test] + async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { + let mut tracker = private_tracker(); + + tracker.config.private_mode = Some(PrivateMode { + check_keys_expiration: false, + }); + + let past_time = Some(Duration::ZERO); + + let expiring_key = tracker + .add_auth_key(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), past_time) + .await + .unwrap(); + + assert!(tracker.authenticate(&expiring_key.key()).await.is_ok()); + } + #[tokio::test] async fn it_should_fail_verifying_an_unregistered_authentication_key() { let tracker = private_tracker(); From d7dfc3bea813cec6b45aa9c6d31bfa129766b2a0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 Aug 2024 13:46:08 +0100 Subject: [PATCH 0453/1297] feat: [#978] add semantic validation for configuration The section [core.provate_mode] can be inlcuded in the configration TOML file only if the tracker is running in private mode (`private = true`). This commits adds that validation and makes it possible to add more semantic validations in the future. Semantic validations are validations that depend on more than one value. Like the one added, it could be any other incompatible combination. --- packages/configuration/src/lib.rs | 1 + packages/configuration/src/v2/core.rs | 11 +++++++++++ packages/configuration/src/v2/mod.rs | 7 +++++++ packages/configuration/src/validator.rs | 19 +++++++++++++++++++ src/bootstrap/app.rs | 9 +++++++++ src/core/auth.rs | 2 +- 6 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 packages/configuration/src/validator.rs diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 7f63b7f18..7b59d3f95 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -5,6 +5,7 @@ //! //! The current version for configuration is [`v2`]. pub mod v2; +pub mod validator; use std::collections::HashMap; use std::env; diff --git a/packages/configuration/src/v2/core.rs b/packages/configuration/src/v2/core.rs index 5d6afdee2..3dfde122e 100644 --- a/packages/configuration/src/v2/core.rs +++ b/packages/configuration/src/v2/core.rs @@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize}; use super::network::Network; use crate::v2::database::Database; +use crate::validator::{SemanticValidationError, Validator}; use crate::{AnnouncePolicy, TrackerPolicy}; #[allow(clippy::struct_excessive_bools)] @@ -131,3 +132,13 @@ impl PrivateMode { true } } + +impl Validator for Core { + fn validate(&self) -> Result<(), SemanticValidationError> { + if self.private_mode.is_some() && !self.private { + return Err(SemanticValidationError::UselessPrivateModeSection); + } + + Ok(()) + } +} diff --git a/packages/configuration/src/v2/mod.rs b/packages/configuration/src/v2/mod.rs index 5fa142b0b..de8af0891 100644 --- a/packages/configuration/src/v2/mod.rs +++ b/packages/configuration/src/v2/mod.rs @@ -251,6 +251,7 @@ use self::health_check_api::HealthCheckApi; use self::http_tracker::HttpTracker; use self::tracker_api::HttpApi; use self::udp_tracker::UdpTracker; +use crate::validator::{SemanticValidationError, Validator}; use crate::{Error, Info, Metadata, Version}; /// This configuration version @@ -394,6 +395,12 @@ impl Configuration { } } +impl Validator for Configuration { + fn validate(&self) -> Result<(), SemanticValidationError> { + self.core.validate() + } +} + #[cfg(test)] mod tests { diff --git a/packages/configuration/src/validator.rs b/packages/configuration/src/validator.rs new file mode 100644 index 000000000..4555b88dd --- /dev/null +++ b/packages/configuration/src/validator.rs @@ -0,0 +1,19 @@ +//! Trait to validate semantic errors. +//! +//! Errors could involve more than one configuration option. Some configuration +//! combinations can be incompatible. +use thiserror::Error; + +/// Errors that can occur validating the configuration. +#[derive(Error, Debug)] +pub enum SemanticValidationError { + #[error("Private mode section in configuration can only be included when the tracker is running in private mode.")] + UselessPrivateModeSection, +} + +pub trait Validator { + /// # Errors + /// + /// Will return an error if the configuration is invalid. + fn validate(&self) -> Result<(), SemanticValidationError>; +} diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index cfb84a2d1..b79f4dc86 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -14,6 +14,7 @@ use std::sync::Arc; use torrust_tracker_clock::static_time; +use torrust_tracker_configuration::validator::Validator; use torrust_tracker_configuration::Configuration; use tracing::info; @@ -24,10 +25,18 @@ use crate::core::Tracker; use crate::shared::crypto::ephemeral_instance_keys; /// It loads the configuration from the environment and builds the main domain [`Tracker`] struct. +/// +/// # Panics +/// +/// Setup can file if the configuration is invalid. #[must_use] pub fn setup() -> (Configuration, Arc) { let configuration = initialize_configuration(); + if let Err(e) = configuration.validate() { + panic!("Configuration error: {e}"); + } + let tracker = initialize_with_configuration(&configuration); info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); diff --git a/src/core/auth.rs b/src/core/auth.rs index fef5b3098..61ccbdb52 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -4,7 +4,7 @@ //! Tracker keys are tokens used to authenticate the tracker clients when the tracker runs //! in `private` or `private_listed` modes. //! -//! There are services to [`generate_key`] and [`verify_key`] authentication keys. +//! There are services to [`generate_key`] and [`verify_key_expiration`] authentication keys. //! //! Authentication keys are used only by [`HTTP`](crate::servers::http) trackers. All keys have an expiration time, that means //! they are only valid during a period of time. After that time the expiring key will no longer be valid. From 8d58882a82014a4ac209c94ceae300fc9f07a6f1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 Aug 2024 16:04:22 +0100 Subject: [PATCH 0454/1297] refactor: make method private It was public becuase it was being used in a test but it can be used the `authenticate` method instead. --- src/core/mod.rs | 8 ++------ tests/servers/api/v1/contract/context/auth_key.rs | 9 +++------ 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index a8c265408..dd15d8705 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -988,9 +988,7 @@ impl Tracker { /// # Errors /// /// Will return a `key::Error` if unable to get any `auth_key`. - pub async fn verify_auth_key(&self, key: &Key) -> Result<(), auth::Error> { - // code-review: this function is public only because it's used in a test. - // We should change the test and make it private. + async fn verify_auth_key(&self, key: &Key) -> Result<(), auth::Error> { match self.keys.read().await.get(key) { None => Err(auth::Error::UnableToReadKey { location: Location::caller(), @@ -1830,13 +1828,11 @@ mod tests { #[tokio::test] async fn it_should_verify_a_valid_authentication_key() { - // todo: this should not be tested directly because - // `verify_auth_key` should be a private method. let tracker = private_tracker(); let expiring_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); - assert!(tracker.verify_auth_key(&expiring_key.key()).await.is_ok()); + assert!(tracker.authenticate(&expiring_key.key()).await.is_ok()); } #[tokio::test] diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index cd6d2544f..41f421ca6 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -26,10 +26,9 @@ async fn should_allow_generating_a_new_random_auth_key() { let auth_key_resource = assert_auth_key_utf8(response).await; - // Verify the key with the tracker assert!(env .tracker - .verify_auth_key(&auth_key_resource.key.parse::().unwrap()) + .authenticate(&auth_key_resource.key.parse::().unwrap()) .await .is_ok()); @@ -49,10 +48,9 @@ async fn should_allow_uploading_a_preexisting_auth_key() { let auth_key_resource = assert_auth_key_utf8(response).await; - // Verify the key with the tracker assert!(env .tracker - .verify_auth_key(&auth_key_resource.key.parse::().unwrap()) + .authenticate(&auth_key_resource.key.parse::().unwrap()) .await .is_ok()); @@ -357,10 +355,9 @@ mod deprecated_generate_key_endpoint { let auth_key_resource = assert_auth_key_utf8(response).await; - // Verify the key with the tracker assert!(env .tracker - .verify_auth_key(&auth_key_resource.key.parse::().unwrap()) + .authenticate(&auth_key_resource.key.parse::().unwrap()) .await .is_ok()); From 349692b928cf29108b9e9f7a176930d2c7ad478a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 Aug 2024 16:45:11 +0100 Subject: [PATCH 0455/1297] test: [#989] add more tests for keys There are four ways of adding keys to the tracker. One for each combination of: - Expiring or permanent key. - Pre-generated (uploaded) ot randomdly generated key. This commit adds new tests for each case. --- src/core/mod.rs | 242 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 187 insertions(+), 55 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index dd15d8705..ea1472b61 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -1785,35 +1785,8 @@ mod tests { use std::str::FromStr; use std::time::Duration; - use torrust_tracker_clock::clock::Time; - use torrust_tracker_configuration::v2::core::PrivateMode; - - use crate::core::auth::{self, Key}; + use crate::core::auth::{self}; use crate::core::tests::the_tracker::private_tracker; - use crate::CurrentClock; - - #[tokio::test] - async fn it_should_generate_the_expiring_authentication_keys() { - let tracker = private_tracker(); - - let key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); - - assert_eq!( - key.valid_until, - Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) - ); - } - - #[tokio::test] - async fn it_should_authenticate_a_peer_by_using_a_key() { - let tracker = private_tracker(); - - let expiring_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); - - let result = tracker.authenticate(&expiring_key.key()).await; - - assert!(result.is_ok()); - } #[tokio::test] async fn it_should_fail_authenticating_a_peer_when_it_uses_an_unregistered_key() { @@ -1826,33 +1799,6 @@ mod tests { assert!(result.is_err()); } - #[tokio::test] - async fn it_should_verify_a_valid_authentication_key() { - let tracker = private_tracker(); - - let expiring_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); - - assert!(tracker.authenticate(&expiring_key.key()).await.is_ok()); - } - - #[tokio::test] - async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { - let mut tracker = private_tracker(); - - tracker.config.private_mode = Some(PrivateMode { - check_keys_expiration: false, - }); - - let past_time = Some(Duration::ZERO); - - let expiring_key = tracker - .add_auth_key(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), past_time) - .await - .unwrap(); - - assert!(tracker.authenticate(&expiring_key.key()).await.is_ok()); - } - #[tokio::test] async fn it_should_fail_verifying_an_unregistered_authentication_key() { let tracker = private_tracker(); @@ -1888,6 +1834,192 @@ mod tests { assert!(result.is_ok()); assert!(tracker.verify_auth_key(&expiring_key.key()).await.is_ok()); } + + mod with_expiring_and { + + mod randomly_generated_keys { + use std::time::Duration; + + use torrust_tracker_clock::clock::Time; + use torrust_tracker_configuration::v2::core::PrivateMode; + + use crate::core::auth::Key; + use crate::core::tests::the_tracker::private_tracker; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_generate_the_key() { + let tracker = private_tracker(); + + let peer_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); + + assert_eq!( + peer_key.valid_until, + Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + ); + } + + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let tracker = private_tracker(); + + let peer_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); + + let result = tracker.authenticate(&peer_key.key()).await; + + assert!(result.is_ok()); + } + + #[tokio::test] + async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { + let mut tracker = private_tracker(); + + tracker.config.private_mode = Some(PrivateMode { + check_keys_expiration: false, + }); + + let past_timestamp = Duration::ZERO; + + let peer_key = tracker + .add_auth_key(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), Some(past_timestamp)) + .await + .unwrap(); + + assert!(tracker.authenticate(&peer_key.key()).await.is_ok()); + } + } + + mod pre_generated_keys { + use std::time::Duration; + + use torrust_tracker_clock::clock::Time; + use torrust_tracker_configuration::v2::core::PrivateMode; + + use crate::core::auth::Key; + use crate::core::tests::the_tracker::private_tracker; + use crate::core::AddKeyRequest; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_add_a_pre_generated_key() { + let tracker = private_tracker(); + + let peer_key = tracker + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(100), + }) + .await + .unwrap(); + + assert_eq!( + peer_key.valid_until, + Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + ); + } + + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let tracker = private_tracker(); + + let peer_key = tracker + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(100), + }) + .await + .unwrap(); + + let result = tracker.authenticate(&peer_key.key()).await; + + assert!(result.is_ok()); + } + + #[tokio::test] + async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { + let mut tracker = private_tracker(); + + tracker.config.private_mode = Some(PrivateMode { + check_keys_expiration: false, + }); + + let peer_key = tracker + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(0), + }) + .await + .unwrap(); + + assert!(tracker.authenticate(&peer_key.key()).await.is_ok()); + } + } + } + + mod with_permanent_and { + + mod randomly_generated_keys { + use crate::core::tests::the_tracker::private_tracker; + + #[tokio::test] + async fn it_should_generate_the_key() { + let tracker = private_tracker(); + + let peer_key = tracker.generate_permanent_auth_key().await.unwrap(); + + assert_eq!(peer_key.valid_until, None); + } + + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let tracker = private_tracker(); + + let peer_key = tracker.generate_permanent_auth_key().await.unwrap(); + + let result = tracker.authenticate(&peer_key.key()).await; + + assert!(result.is_ok()); + } + } + + mod pre_generated_keys { + use crate::core::auth::Key; + use crate::core::tests::the_tracker::private_tracker; + use crate::core::AddKeyRequest; + + #[tokio::test] + async fn it_should_add_a_pre_generated_key() { + let tracker = private_tracker(); + + let peer_key = tracker + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: None, + }) + .await + .unwrap(); + + assert_eq!(peer_key.valid_until, None); + } + + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let tracker = private_tracker(); + + let peer_key = tracker + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: None, + }) + .await + .unwrap(); + + let result = tracker.authenticate(&peer_key.key()).await; + + assert!(result.is_ok()); + } + } + } } mod handling_an_announce_request {} From 287e48422003e2e1b890dd2de9cb5ce102601d8c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 2 Aug 2024 10:21:00 +0100 Subject: [PATCH 0456/1297] feat!: [#958] improve metadata in config files The metadata section in the configuration file is changed: TOML: ```toml [metadata] app = "torrust-tracker" purpose = "configuration" schema_version = "2.0.0" ``` JSON: ```json { "metadata": { "app": "torrust-tracker", "purpose": "configuration", "version": "2.0.0" } } ``` - `app`: the applications this config file is used for. - `purpose`: the purpose of the file containing these metadata. - `schema_version`: the schema version for the file being parsed. --- packages/configuration/src/lib.rs | 71 ++++++++++++++----- .../configuration/src/{v2 => v2_0_0}/core.rs | 16 ++--- .../src/{v2 => v2_0_0}/database.rs | 0 .../src/{v2 => v2_0_0}/health_check_api.rs | 0 .../src/{v2 => v2_0_0}/http_tracker.rs | 0 .../src/{v2 => v2_0_0}/logging.rs | 0 .../configuration/src/{v2 => v2_0_0}/mod.rs | 14 ++-- .../src/{v2 => v2_0_0}/network.rs | 0 .../src/{v2 => v2_0_0}/tracker_api.rs | 2 +- .../src/{v2 => v2_0_0}/udp_tracker.rs | 0 .../config/tracker.container.mysql.toml | 5 +- .../config/tracker.container.sqlite3.toml | 5 +- .../config/tracker.development.sqlite3.toml | 5 +- .../config/tracker.e2e.container.sqlite3.toml | 5 +- .../config/tracker.udp.benchmarking.toml | 5 +- src/bootstrap/config.rs | 2 +- src/core/mod.rs | 6 +- 17 files changed, 93 insertions(+), 43 deletions(-) rename packages/configuration/src/{v2 => v2_0_0}/core.rs (90%) rename packages/configuration/src/{v2 => v2_0_0}/database.rs (100%) rename packages/configuration/src/{v2 => v2_0_0}/health_check_api.rs (100%) rename packages/configuration/src/{v2 => v2_0_0}/http_tracker.rs (100%) rename packages/configuration/src/{v2 => v2_0_0}/logging.rs (100%) rename packages/configuration/src/{v2 => v2_0_0}/mod.rs (97%) rename packages/configuration/src/{v2 => v2_0_0}/network.rs (100%) rename packages/configuration/src/{v2 => v2_0_0}/tracker_api.rs (98%) rename packages/configuration/src/{v2 => v2_0_0}/udp_tracker.rs (100%) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 7b59d3f95..aedf3a6f1 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -4,7 +4,7 @@ //! Torrust Tracker, which is a `BitTorrent` tracker server. //! //! The current version for configuration is [`v2`]. -pub mod v2; +pub mod v2_0_0; pub mod validator; use std::collections::HashMap; @@ -35,53 +35,86 @@ const ENV_VAR_CONFIG_TOML: &str = "TORRUST_TRACKER_CONFIG_TOML"; /// The `tracker.toml` file location. pub const ENV_VAR_CONFIG_TOML_PATH: &str = "TORRUST_TRACKER_CONFIG_TOML_PATH"; -pub type Configuration = v2::Configuration; -pub type Core = v2::core::Core; -pub type HealthCheckApi = v2::health_check_api::HealthCheckApi; -pub type HttpApi = v2::tracker_api::HttpApi; -pub type HttpTracker = v2::http_tracker::HttpTracker; -pub type UdpTracker = v2::udp_tracker::UdpTracker; -pub type Database = v2::database::Database; -pub type Driver = v2::database::Driver; -pub type Threshold = v2::logging::Threshold; +pub type Configuration = v2_0_0::Configuration; +pub type Core = v2_0_0::core::Core; +pub type HealthCheckApi = v2_0_0::health_check_api::HealthCheckApi; +pub type HttpApi = v2_0_0::tracker_api::HttpApi; +pub type HttpTracker = v2_0_0::http_tracker::HttpTracker; +pub type UdpTracker = v2_0_0::udp_tracker::UdpTracker; +pub type Database = v2_0_0::database::Database; +pub type Driver = v2_0_0::database::Driver; +pub type Threshold = v2_0_0::logging::Threshold; pub type AccessTokens = HashMap; -pub const LATEST_VERSION: &str = "2"; +pub const LATEST_VERSION: &str = "2.0.0"; /// Info about the configuration specification. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display, Clone)] +#[display(fmt = "Metadata(app: {app}, purpose: {purpose}, schema_version: {schema_version})")] pub struct Metadata { - #[serde(default = "Metadata::default_version")] + /// The application this configuration is valid for. + #[serde(default = "Metadata::default_app")] + app: App, + + /// The purpose of this parsed file. + #[serde(default = "Metadata::default_purpose")] + purpose: Purpose, + + /// The schema version for the configuration. + #[serde(default = "Metadata::default_schema_version")] #[serde(flatten)] - version: Version, + schema_version: Version, } impl Default for Metadata { fn default() -> Self { Self { - version: Self::default_version(), + app: Self::default_app(), + purpose: Self::default_purpose(), + schema_version: Self::default_schema_version(), } } } impl Metadata { - fn default_version() -> Version { + fn default_app() -> App { + App::TorrustTracker + } + + fn default_purpose() -> Purpose { + Purpose::Configuration + } + + fn default_schema_version() -> Version { Version::latest() } } +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display, Clone)] +#[serde(rename_all = "kebab-case")] +pub enum App { + TorrustTracker, +} + +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display, Clone)] +#[serde(rename_all = "lowercase")] +pub enum Purpose { + Configuration, +} + /// The configuration version. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display, Clone)] +#[serde(rename_all = "lowercase")] pub struct Version { #[serde(default = "Version::default_semver")] - version: String, + schema_version: String, } impl Default for Version { fn default() -> Self { Self { - version: Self::default_semver(), + schema_version: Self::default_semver(), } } } @@ -89,13 +122,13 @@ impl Default for Version { impl Version { fn new(semver: &str) -> Self { Self { - version: semver.to_owned(), + schema_version: semver.to_owned(), } } fn latest() -> Self { Self { - version: LATEST_VERSION.to_string(), + schema_version: LATEST_VERSION.to_string(), } } diff --git a/packages/configuration/src/v2/core.rs b/packages/configuration/src/v2_0_0/core.rs similarity index 90% rename from packages/configuration/src/v2/core.rs rename to packages/configuration/src/v2_0_0/core.rs index 3dfde122e..ed3e6aeb7 100644 --- a/packages/configuration/src/v2/core.rs +++ b/packages/configuration/src/v2_0_0/core.rs @@ -2,18 +2,18 @@ use derive_more::{Constructor, Display}; use serde::{Deserialize, Serialize}; use super::network::Network; -use crate::v2::database::Database; +use crate::v2_0_0::database::Database; use crate::validator::{SemanticValidationError, Validator}; use crate::{AnnouncePolicy, TrackerPolicy}; #[allow(clippy::struct_excessive_bools)] #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct Core { - // Announce policy configuration. + /// Announce policy configuration. #[serde(default = "Core::default_announce_policy")] pub announce_policy: AnnouncePolicy, - // Database configuration. + /// Database configuration. #[serde(default = "Core::default_database")] pub database: Database, @@ -22,23 +22,23 @@ pub struct Core { #[serde(default = "Core::default_inactive_peer_cleanup_interval")] pub inactive_peer_cleanup_interval: u64, - // When `true` only approved torrents can be announced in the tracker. + /// When `true` only approved torrents can be announced in the tracker. #[serde(default = "Core::default_listed")] pub listed: bool, - // Network configuration. + /// Network configuration. #[serde(default = "Core::default_network")] pub net: Network, - // When `true` clients require a key to connect and use the tracker. + /// When `true` clients require a key to connect and use the tracker. #[serde(default = "Core::default_private")] pub private: bool, - // Configuration specific when the tracker is running in private mode. + /// Configuration specific when the tracker is running in private mode. #[serde(default = "Core::default_private_mode")] pub private_mode: Option, - // Tracker policy configuration. + /// Tracker policy configuration. #[serde(default = "Core::default_tracker_policy")] pub tracker_policy: TrackerPolicy, diff --git a/packages/configuration/src/v2/database.rs b/packages/configuration/src/v2_0_0/database.rs similarity index 100% rename from packages/configuration/src/v2/database.rs rename to packages/configuration/src/v2_0_0/database.rs diff --git a/packages/configuration/src/v2/health_check_api.rs b/packages/configuration/src/v2_0_0/health_check_api.rs similarity index 100% rename from packages/configuration/src/v2/health_check_api.rs rename to packages/configuration/src/v2_0_0/health_check_api.rs diff --git a/packages/configuration/src/v2/http_tracker.rs b/packages/configuration/src/v2_0_0/http_tracker.rs similarity index 100% rename from packages/configuration/src/v2/http_tracker.rs rename to packages/configuration/src/v2_0_0/http_tracker.rs diff --git a/packages/configuration/src/v2/logging.rs b/packages/configuration/src/v2_0_0/logging.rs similarity index 100% rename from packages/configuration/src/v2/logging.rs rename to packages/configuration/src/v2_0_0/logging.rs diff --git a/packages/configuration/src/v2/mod.rs b/packages/configuration/src/v2_0_0/mod.rs similarity index 97% rename from packages/configuration/src/v2/mod.rs rename to packages/configuration/src/v2_0_0/mod.rs index de8af0891..b426b5c03 100644 --- a/packages/configuration/src/v2/mod.rs +++ b/packages/configuration/src/v2_0_0/mod.rs @@ -255,7 +255,7 @@ use crate::validator::{SemanticValidationError, Validator}; use crate::{Error, Info, Metadata, Version}; /// This configuration version -const VERSION_2: &str = "2"; +const VERSION_2_0_0: &str = "2.0.0"; /// Prefix for env vars that overwrite configuration options. const CONFIG_OVERRIDE_PREFIX: &str = "TORRUST_TRACKER_CONFIG_OVERRIDE_"; @@ -267,7 +267,6 @@ const CONFIG_OVERRIDE_SEPARATOR: &str = "__"; #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Default, Clone)] pub struct Configuration { /// Configuration metadata. - #[serde(flatten)] pub metadata: Metadata, /// Logging configuration @@ -335,9 +334,9 @@ impl Configuration { let config: Configuration = figment.extract()?; - if config.metadata.version != Version::new(VERSION_2) { + if config.metadata.schema_version != Version::new(VERSION_2_0_0) { return Err(Error::UnsupportedVersion { - version: config.metadata.version, + version: config.metadata.schema_version, }); } @@ -406,12 +405,15 @@ mod tests { use std::net::{IpAddr, Ipv4Addr}; - use crate::v2::Configuration; + use crate::v2_0_0::Configuration; use crate::Info; #[cfg(test)] fn default_config_toml() -> String { - let config = r#"version = "2" + let config = r#"[metadata] + app = "torrust-tracker" + purpose = "configuration" + schema_version = "2.0.0" [logging] threshold = "info" diff --git a/packages/configuration/src/v2/network.rs b/packages/configuration/src/v2_0_0/network.rs similarity index 100% rename from packages/configuration/src/v2/network.rs rename to packages/configuration/src/v2_0_0/network.rs diff --git a/packages/configuration/src/v2/tracker_api.rs b/packages/configuration/src/v2_0_0/tracker_api.rs similarity index 98% rename from packages/configuration/src/v2/tracker_api.rs rename to packages/configuration/src/v2_0_0/tracker_api.rs index dbbff7995..43b08a21e 100644 --- a/packages/configuration/src/v2/tracker_api.rs +++ b/packages/configuration/src/v2_0_0/tracker_api.rs @@ -71,7 +71,7 @@ impl HttpApi { #[cfg(test)] mod tests { - use crate::v2::tracker_api::HttpApi; + use crate::v2_0_0::tracker_api::HttpApi; #[test] fn http_api_configuration_should_check_if_it_contains_a_token() { diff --git a/packages/configuration/src/v2/udp_tracker.rs b/packages/configuration/src/v2_0_0/udp_tracker.rs similarity index 100% rename from packages/configuration/src/v2/udp_tracker.rs rename to packages/configuration/src/v2_0_0/udp_tracker.rs diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml index 1c84fb2e2..1fcad4df1 100644 --- a/share/default/config/tracker.container.mysql.toml +++ b/share/default/config/tracker.container.mysql.toml @@ -1,4 +1,7 @@ -version = "2" +[metadata] +app = "torrust-tracker" +purpose = "configuration" +schema_version = "2.0.0" [core.database] driver = "mysql" diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml index aa8aefa5e..017df5b48 100644 --- a/share/default/config/tracker.container.sqlite3.toml +++ b/share/default/config/tracker.container.sqlite3.toml @@ -1,4 +1,7 @@ -version = "2" +[metadata] +app = "torrust-tracker" +purpose = "configuration" +schema_version = "2.0.0" [core.database] path = "/var/lib/torrust/tracker/database/sqlite3.db" diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index 554835922..1ecc76532 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -1,4 +1,7 @@ -version = "2" +[metadata] +app = "torrust-tracker" +purpose = "configuration" +schema_version = "2.0.0" [[udp_trackers]] bind_address = "0.0.0.0:6969" diff --git a/share/default/config/tracker.e2e.container.sqlite3.toml b/share/default/config/tracker.e2e.container.sqlite3.toml index 6b1383fb5..7c6f4bb77 100644 --- a/share/default/config/tracker.e2e.container.sqlite3.toml +++ b/share/default/config/tracker.e2e.container.sqlite3.toml @@ -1,4 +1,7 @@ -version = "2" +[metadata] +app = "torrust-tracker" +purpose = "configuration" +schema_version = "2.0.0" [core.database] path = "/var/lib/torrust/tracker/database/sqlite3.db" diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml index 907a05456..afbef84b8 100644 --- a/share/default/config/tracker.udp.benchmarking.toml +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -1,4 +1,7 @@ -version = "2" +[metadata] +app = "torrust-tracker" +purpose = "configuration" +schema_version = "2.0.0" [logging] threshold = "error" diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 6b607bd6f..fb5afe403 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -24,7 +24,7 @@ pub const DEFAULT_PATH_CONFIG: &str = "./share/default/config/tracker.developmen #[must_use] pub fn initialize_configuration() -> Configuration { let info = Info::new(DEFAULT_PATH_CONFIG.to_string()).expect("info to load configuration is not valid"); - Configuration::load(&info).expect("configuration should be loaded from provided info") + Configuration::load(&info).expect("error loading configuration from sources") } #[cfg(test)] diff --git a/src/core/mod.rs b/src/core/mod.rs index ea1472b61..98de9e4fd 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -459,7 +459,7 @@ use derive_more::Constructor; use error::PeerKeyError; use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; -use torrust_tracker_configuration::v2::database; +use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_located_error::Located; use torrust_tracker_primitives::info_hash::InfoHash; @@ -1841,7 +1841,7 @@ mod tests { use std::time::Duration; use torrust_tracker_clock::clock::Time; - use torrust_tracker_configuration::v2::core::PrivateMode; + use torrust_tracker_configuration::v2_0_0::core::PrivateMode; use crate::core::auth::Key; use crate::core::tests::the_tracker::private_tracker; @@ -1893,7 +1893,7 @@ mod tests { use std::time::Duration; use torrust_tracker_clock::clock::Time; - use torrust_tracker_configuration::v2::core::PrivateMode; + use torrust_tracker_configuration::v2_0_0::core::PrivateMode; use crate::core::auth::Key; use crate::core::tests::the_tracker::private_tracker; From 90ef14d2d5450421fd2b59b78e09536ed30152e7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 2 Aug 2024 11:53:02 +0100 Subject: [PATCH 0457/1297] feat!: [#938] add mandatory config options Some configuration options are mandatory. The tracker will panic if the user doesn't provide an explicit value for them from one of the configuration sources: TOML or ENV VARS. The mandatory options are: ```toml [metadata] schema_version = "2.0.0" [logging] threshold = "info" [core] private = false listed = false ``` --- packages/configuration/src/lib.rs | 3 + packages/configuration/src/v2_0_0/mod.rs | 112 ++++++++++++++++-- .../config/tracker.container.mysql.toml | 7 ++ .../config/tracker.container.sqlite3.toml | 7 ++ .../config/tracker.development.sqlite3.toml | 7 ++ .../config/tracker.e2e.container.sqlite3.toml | 7 ++ .../config/tracker.udp.benchmarking.toml | 2 + 7 files changed, 133 insertions(+), 12 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index aedf3a6f1..bdbe419ca 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -303,6 +303,9 @@ pub enum Error { #[error("Unsupported configuration version: {version}")] UnsupportedVersion { version: Version }, + + #[error("Missing mandatory configuration option. Option path: {path}")] + MissingMandatoryOption { path: String }, } impl From for Error { diff --git a/packages/configuration/src/v2_0_0/mod.rs b/packages/configuration/src/v2_0_0/mod.rs index b426b5c03..5067210bb 100644 --- a/packages/configuration/src/v2_0_0/mod.rs +++ b/packages/configuration/src/v2_0_0/mod.rs @@ -313,27 +313,33 @@ impl Configuration { } /// Loads the configuration from the `Info` struct. The whole - /// configuration in toml format is included in the `info.tracker_toml` string. + /// configuration in toml format is included in the `info.tracker_toml` + /// string. /// - /// Optionally will override the admin api token. + /// Configuration provided via env var has priority over config file path. /// /// # Errors /// /// Will return `Err` if the environment variable does not exist or has a bad configuration. pub fn load(info: &Info) -> Result { + // Load configuration provided by the user, prioritizing env vars let figment = if let Some(config_toml) = &info.config_toml { - // Config in env var has priority over config file path - Figment::from(Serialized::defaults(Configuration::default())) - .merge(Toml::string(config_toml)) - .merge(Env::prefixed(CONFIG_OVERRIDE_PREFIX).split(CONFIG_OVERRIDE_SEPARATOR)) + Figment::from(Toml::string(config_toml)).merge(Env::prefixed(CONFIG_OVERRIDE_PREFIX).split(CONFIG_OVERRIDE_SEPARATOR)) } else { - Figment::from(Serialized::defaults(Configuration::default())) - .merge(Toml::file(&info.config_toml_path)) + Figment::from(Toml::file(&info.config_toml_path)) .merge(Env::prefixed(CONFIG_OVERRIDE_PREFIX).split(CONFIG_OVERRIDE_SEPARATOR)) }; + // Make sure user has provided the mandatory options. + Self::check_mandatory_options(&figment)?; + + // Fill missing options with default values. + let figment = figment.join(Serialized::defaults(Configuration::default())); + + // Build final configuration. let config: Configuration = figment.extract()?; + // Make sure the provided schema version matches this version. if config.metadata.schema_version != Version::new(VERSION_2_0_0) { return Err(Error::UnsupportedVersion { version: config.metadata.schema_version, @@ -343,6 +349,28 @@ impl Configuration { Ok(config) } + /// Some configuration options are mandatory. The tracker will panic if + /// the user doesn't provide an explicit value for them from one of the + /// configuration sources: TOML or ENV VARS. + /// + /// # Errors + /// + /// Will return an error if a mandatory configuration option is only + /// obtained by default value (code), meaning the user hasn't overridden it. + fn check_mandatory_options(figment: &Figment) -> Result<(), Error> { + let mandatory_options = ["metadata.schema_version", "logging.threshold", "core.private", "core.listed"]; + + for mandatory_option in mandatory_options { + figment + .find_value(mandatory_option) + .map_err(|_err| Error::MissingMandatoryOption { + path: mandatory_option.to_owned(), + })?; + } + + Ok(()) + } + /// Saves the configuration to the configuration file. /// /// # Errors @@ -496,14 +524,25 @@ mod tests { } #[test] - fn configuration_should_use_the_default_values_when_an_empty_configuration_is_provided_by_the_user() { + fn configuration_should_use_the_default_values_when_only_the_mandatory_options_are_provided_by_the_user_via_toml_file() { figment::Jail::expect_with(|jail| { - jail.create_file("tracker.toml", "")?; + jail.create_file( + "tracker.toml", + r#" + [metadata] + schema_version = "2.0.0" + + [logging] + threshold = "info" - let empty_configuration = String::new(); + [core] + listed = false + private = false + "#, + )?; let info = Info { - config_toml: Some(empty_configuration), + config_toml: None, config_toml_path: "tracker.toml".to_string(), }; @@ -515,10 +554,49 @@ mod tests { }); } + #[test] + fn configuration_should_use_the_default_values_when_only_the_mandatory_options_are_provided_by_the_user_via_toml_content() { + figment::Jail::expect_with(|_jail| { + let config_toml = r#" + [metadata] + schema_version = "2.0.0" + + [logging] + threshold = "info" + + [core] + listed = false + private = false + "# + .to_string(); + + let info = Info { + config_toml: Some(config_toml), + config_toml_path: String::new(), + }; + + let configuration = Configuration::load(&info).expect("Could not load configuration from file"); + + assert_eq!(configuration, Configuration::default()); + + Ok(()) + }); + } + #[test] fn default_configuration_could_be_overwritten_from_a_single_env_var_with_toml_contents() { figment::Jail::expect_with(|_jail| { let config_toml = r#" + [metadata] + schema_version = "2.0.0" + + [logging] + threshold = "info" + + [core] + listed = false + private = false + [core.database] path = "OVERWRITTEN DEFAULT DB PATH" "# @@ -543,6 +621,16 @@ mod tests { jail.create_file( "tracker.toml", r#" + [metadata] + schema_version = "2.0.0" + + [logging] + threshold = "info" + + [core] + listed = false + private = false + [core.database] path = "OVERWRITTEN DEFAULT DB PATH" "#, diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml index 1fcad4df1..865ea224e 100644 --- a/share/default/config/tracker.container.mysql.toml +++ b/share/default/config/tracker.container.mysql.toml @@ -3,6 +3,13 @@ app = "torrust-tracker" purpose = "configuration" schema_version = "2.0.0" +[logging] +threshold = "info" + +[core] +listed = false +private = false + [core.database] driver = "mysql" path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml index 017df5b48..6c73cf54a 100644 --- a/share/default/config/tracker.container.sqlite3.toml +++ b/share/default/config/tracker.container.sqlite3.toml @@ -3,6 +3,13 @@ app = "torrust-tracker" purpose = "configuration" schema_version = "2.0.0" +[logging] +threshold = "info" + +[core] +listed = false +private = false + [core.database] path = "/var/lib/torrust/tracker/database/sqlite3.db" diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index 1ecc76532..96addaf87 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -3,6 +3,13 @@ app = "torrust-tracker" purpose = "configuration" schema_version = "2.0.0" +[logging] +threshold = "info" + +[core] +listed = false +private = false + [[udp_trackers]] bind_address = "0.0.0.0:6969" diff --git a/share/default/config/tracker.e2e.container.sqlite3.toml b/share/default/config/tracker.e2e.container.sqlite3.toml index 7c6f4bb77..73c6df219 100644 --- a/share/default/config/tracker.e2e.container.sqlite3.toml +++ b/share/default/config/tracker.e2e.container.sqlite3.toml @@ -3,6 +3,13 @@ app = "torrust-tracker" purpose = "configuration" schema_version = "2.0.0" +[logging] +threshold = "info" + +[core] +listed = false +private = false + [core.database] path = "/var/lib/torrust/tracker/database/sqlite3.db" diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml index afbef84b8..a73760b95 100644 --- a/share/default/config/tracker.udp.benchmarking.toml +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -7,6 +7,8 @@ schema_version = "2.0.0" threshold = "error" [core] +listed = false +private = false remove_peerless_torrents = false tracker_usage_statistics = false From 7c626452c2183dd4578eb07ca19f3a58b153c39d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 5 Aug 2024 12:58:49 +0100 Subject: [PATCH 0458/1297] chore(deps): update dependencies ```output cargo update Updating crates.io index Locking 35 packages to latest compatible versions Adding aws-lc-rs v1.8.1 Adding aws-lc-sys v0.20.1 Updating axum-server v0.6.0 -> v0.7.1 Updating bytemuck v1.16.1 -> v1.16.3 Updating bytes v1.6.1 -> v1.7.1 Updating cc v1.1.6 -> v1.1.7 Updating clap v4.5.11 -> v4.5.13 Updating clap_builder v4.5.11 -> v4.5.13 Updating clap_derive v4.5.11 -> v4.5.13 Adding dunce v1.0.5 Updating flate2 v1.0.30 -> v1.0.31 Adding fs_extra v1.3.0 Adding home v0.5.9 Updating indexmap v2.2.6 -> v2.3.0 Updating lru v0.12.3 -> v0.12.4 Adding mirai-annotations v1.12.0 Adding paste v1.0.15 Updating ppv-lite86 v0.2.17 -> v0.2.20 Adding prettyplease v0.2.20 Updating regex v1.10.5 -> v1.10.6 Updating rstest v0.21.0 -> v0.22.0 Updating rstest_macros v0.21.0 -> v0.22.0 Removing rustls v0.21.12 Updating rustls-pemfile v2.1.2 -> v2.1.3 Removing rustls-webpki v0.101.7 Removing sct v0.7.1 Updating serde_json v1.0.121 -> v1.0.122 Updating tempfile v3.10.1 -> v3.11.0 Removing tokio-rustls v0.24.1 Updating toml v0.8.16 -> v0.8.19 Updating toml_datetime v0.6.7 -> v0.6.8 Updating toml_edit v0.22.17 -> v0.22.20 Adding which v4.4.2 (latest: v6.0.2) Updating winapi-util v0.1.8 -> v0.1.9 Adding windows-sys v0.59.0 Updating winnow v0.6.16 -> v0.6.18 Adding zeroize_derive v1.4.2 Updating zstd-safe v7.2.0 -> v7.2.1 Updating zstd-sys v2.0.12+zstd.1.5.6 -> v2.0.13+zstd.1.5.6 ``` --- Cargo.lock | 283 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 178 insertions(+), 105 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 234f291c5..e60aca814 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -386,6 +386,33 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" +[[package]] +name = "aws-lc-rs" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae74d9bd0a7530e8afd1770739ad34b36838829d6ad61818f9230f683f5ad77" +dependencies = [ + "aws-lc-sys", + "mirai-annotations", + "paste", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f0e249228c6ad2d240c2dc94b714d711629d52bad946075d8e9b2f5391f0703" +dependencies = [ + "bindgen", + "cc", + "cmake", + "dunce", + "fs_extra", + "libc", + "paste", +] + [[package]] name = "axum" version = "0.7.5" @@ -490,9 +517,9 @@ dependencies = [ [[package]] name = "axum-server" -version = "0.6.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1ad46c3ec4e12f4a4b6835e173ba21c25e484c9d02b49770bf006ce5367c036" +checksum = "56bac90848f6a9393ac03c63c640925c4b7c8ca21654de40d53f55964667c7d8" dependencies = [ "arc-swap", "bytes", @@ -503,10 +530,11 @@ dependencies = [ "hyper", "hyper-util", "pin-project-lite", - "rustls 0.21.12", + "rustls", "rustls-pemfile", + "rustls-pki-types", "tokio", - "tokio-rustls 0.24.1", + "tokio-rustls", "tower", "tower-service", ] @@ -569,12 +597,15 @@ dependencies = [ "itertools 0.12.1", "lazy_static", "lazycell", + "log", + "prettyplease", "proc-macro2", "quote", "regex", "rustc-hash", "shlex", "syn 2.0.72", + "which", ] [[package]] @@ -713,9 +744,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.16.1" +version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b236fc92302c97ed75b38da1f4917b5cdda4984745740f153a5d3059e48d725e" +checksum = "102087e286b4677862ea56cf8fc58bb2cdfa8725c40ffb80fe3a008eb7f2fc83" [[package]] name = "byteorder" @@ -725,9 +756,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.6.1" +version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a12916984aab3fa6e39d655a33e09c0071eb36d6ab3aea5c2d78551f1df6d952" +checksum = "8318a53db07bb3f8dca91a600466bdb3f2eaadeedfdbcf02e1accbad9271ba50" [[package]] name = "camino" @@ -755,9 +786,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.1.6" +version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aba8f4e9906c7ce3c73463f62a7f0c65183ada1a2d47e397cc8810827f9694f" +checksum = "26a5c3fd7bfa1ce3897a3a3501d362b2d87b7f2583ebcb4a949ec25911025cbc" dependencies = [ "jobserver", "libc", @@ -837,9 +868,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.11" +version = "4.5.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35723e6a11662c2afb578bcf0b88bf6ea8e21282a953428f240574fcc3a2b5b3" +checksum = "0fbb260a053428790f3de475e304ff84cdbc4face759ea7a3e64c1edd938a7fc" dependencies = [ "clap_builder", "clap_derive", @@ -847,9 +878,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.11" +version = "4.5.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49eb96cbfa7cfa35017b7cd548c75b14c3118c98b423041d70562665e07fb0fa" +checksum = "64b17d7ea74e9f833c7dbf2cbe4fb12ff26783eda4782a8975b72f895c9b4d99" dependencies = [ "anstream", "anstyle", @@ -859,9 +890,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.11" +version = "4.5.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d029b67f89d30bbb547c89fd5161293c0aec155fc691d7924b64550662db93e" +checksum = "501d359d5f3dcaf6ecdeee48833ae73ec6e42723a1e52419c79abf9507eec0a0" dependencies = [ "heck 0.5.0", "proc-macro2", @@ -1171,6 +1202,12 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "either" version = "1.13.0" @@ -1294,9 +1331,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.30" +version = "1.0.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f54427cfd1c7829e2a139fcefea601bf088ebca651d2bf53ebc600eac295dae" +checksum = "7f211bbe8e69bbd0cfdea405084f128ae8b4aaa6b0b522fc8f2b009084797920" dependencies = [ "crc32fast", "libz-sys", @@ -1401,6 +1438,12 @@ dependencies = [ "syn 2.0.72", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "funty" version = "2.0.0" @@ -1587,7 +1630,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.2.6", + "indexmap 2.3.0", "slab", "tokio", "tokio-util", @@ -1668,6 +1711,15 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" +[[package]] +name = "home" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" +dependencies = [ + "windows-sys 0.52.0", +] + [[package]] name = "http" version = "1.1.0" @@ -1745,10 +1797,10 @@ dependencies = [ "http", "hyper", "hyper-util", - "rustls 0.23.12", + "rustls", "rustls-pki-types", "tokio", - "tokio-rustls 0.26.0", + "tokio-rustls", "tower-service", ] @@ -1840,9 +1892,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.2.6" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" +checksum = "de3fc2e30ba82dd1b3911c8de1ffc143c74a914a14e99514d7637e3099df5ea0" dependencies = [ "equivalent", "hashbrown 0.14.5", @@ -2059,9 +2111,9 @@ dependencies = [ [[package]] name = "lru" -version = "0.12.3" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3262e75e648fce39813cb56ac41f3c3e3f65217ebf3844d818d1f9398cfb0dc" +checksum = "37ee39891760e7d94734f6f63fedc29a2e4a152f836120753a72503f09fcf904" dependencies = [ "hashbrown 0.14.5", ] @@ -2111,6 +2163,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "mirai-annotations" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9be0862c1b3f26a88803c4a49de6889c10e608b3ee9344e6ef5b45fb37ad3d1" + [[package]] name = "mockall" version = "0.13.0" @@ -2439,6 +2497,12 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + [[package]] name = "pear" version = "0.2.9" @@ -2632,9 +2696,12 @@ checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" [[package]] name = "ppv-lite86" -version = "0.2.17" +version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" +checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" +dependencies = [ + "zerocopy", +] [[package]] name = "predicates" @@ -2662,6 +2729,16 @@ dependencies = [ "termtree", ] +[[package]] +name = "prettyplease" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e" +dependencies = [ + "proc-macro2", + "syn 2.0.72", +] + [[package]] name = "proc-macro-crate" version = "3.1.0" @@ -2856,9 +2933,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.5" +version = "1.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f" +checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619" dependencies = [ "aho-corasick", "memchr", @@ -2996,9 +3073,9 @@ dependencies = [ [[package]] name = "rstest" -version = "0.21.0" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9afd55a67069d6e434a95161415f5beeada95a01c7b815508a82dcb0e1593682" +checksum = "7b423f0e62bdd61734b67cd21ff50871dfaeb9cc74f869dcd6af974fbcb19936" dependencies = [ "futures", "futures-timer", @@ -3008,9 +3085,9 @@ dependencies = [ [[package]] name = "rstest_macros" -version = "0.21.0" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4165dfae59a39dd41d8dec720d3cbfbc71f69744efb480a3920f5d4e0cc6798d" +checksum = "c5e1711e7d14f74b12a58411c542185ef7fb7f2e7f8ee6e2940a883628522b42" dependencies = [ "cfg-if", "glob", @@ -3102,36 +3179,25 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "rustls" -version = "0.21.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" -dependencies = [ - "log", - "ring", - "rustls-webpki 0.101.7", - "sct", -] - [[package]] name = "rustls" version = "0.23.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c58f8c84392efc0a126acce10fa59ff7b3d2ac06ab451a33f2741989b806b044" dependencies = [ + "aws-lc-rs", "once_cell", "rustls-pki-types", - "rustls-webpki 0.102.6", + "rustls-webpki", "subtle", "zeroize", ] [[package]] name = "rustls-pemfile" -version = "2.1.2" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d" +checksum = "196fe16b00e106300d3e45ecfcb764fa292a535d7326a29a5875c579c7417425" dependencies = [ "base64 0.22.1", "rustls-pki-types", @@ -3143,22 +3209,13 @@ version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d" -[[package]] -name = "rustls-webpki" -version = "0.101.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" -dependencies = [ - "ring", - "untrusted", -] - [[package]] name = "rustls-webpki" version = "0.102.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e6b52d4fda176fd835fdc55a835d4a89b8499cad995885a21149d5ad62f852e" dependencies = [ + "aws-lc-rs", "ring", "rustls-pki-types", "untrusted", @@ -3215,16 +3272,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" -[[package]] -name = "sct" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" -dependencies = [ - "ring", - "untrusted", -] - [[package]] name = "seahash" version = "4.1.0" @@ -3306,7 +3353,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8de514ef58196f1fc96dcaef80fe6170a1ce6215df9687a93fe8300e773fefc5" dependencies = [ "form_urlencoded", - "indexmap 2.2.6", + "indexmap 2.3.0", "itoa", "ryu", "serde", @@ -3314,11 +3361,11 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.121" +version = "1.0.122" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ab380d7d9f22ef3f21ad3e6c1ebe8e4fc7a2000ccba2e4d71fc96f15b2cb609" +checksum = "784b6203951c57ff748476b126ccb5e8e2959a5c19e5c617ab1956be3dbc68da" dependencies = [ - "indexmap 2.2.6", + "indexmap 2.3.0", "itoa", "memchr", "ryu", @@ -3377,7 +3424,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.2.6", + "indexmap 2.3.0", "serde", "serde_derive", "serde_json", @@ -3616,12 +3663,13 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.10.1" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" +checksum = "b8fcd239983515c23a32fb82099f97d0b11b8c72f654ed659363a95c3dad7a53" dependencies = [ "cfg-if", "fastrand 2.1.0", + "once_cell", "rustix 0.38.34", "windows-sys 0.52.0", ] @@ -3765,23 +3813,13 @@ dependencies = [ "tokio", ] -[[package]] -name = "tokio-rustls" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" -dependencies = [ - "rustls 0.21.12", - "tokio", -] - [[package]] name = "tokio-rustls" version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" dependencies = [ - "rustls 0.23.12", + "rustls", "rustls-pki-types", "tokio", ] @@ -3801,21 +3839,21 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.16" +version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81967dd0dd2c1ab0bc3468bd7caecc32b8a4aa47d0c8c695d8c2b2108168d62c" +checksum = "a1ed1f98e3fdc28d6d910e6737ae6ab1a93bf1985935a1193e68f93eeb68d24e" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.17", + "toml_edit 0.22.20", ] [[package]] name = "toml_datetime" -version = "0.6.7" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fb9f64314842840f1d940ac544da178732128f1c78c21772e876579e0da1db" +checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" dependencies = [ "serde", ] @@ -3826,22 +3864,22 @@ version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8534fd7f78b5405e860340ad6575217ce99f38d4d5c8f2442cb5ecb50090e1" dependencies = [ - "indexmap 2.2.6", + "indexmap 2.3.0", "toml_datetime", "winnow 0.5.40", ] [[package]] name = "toml_edit" -version = "0.22.17" +version = "0.22.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d9f8729f5aea9562aac1cc0441f5d6de3cff1ee0c5d67293eeca5eb36ee7c16" +checksum = "583c44c02ad26b0c3f3066fe629275e50627026c51ac2e595cca4c230ce1ce1d" dependencies = [ - "indexmap 2.2.6", + "indexmap 2.3.0", "serde", "serde_spanned", "toml_datetime", - "winnow 0.6.16", + "winnow 0.6.18", ] [[package]] @@ -4335,6 +4373,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix 0.38.34", +] + [[package]] name = "winapi" version = "0.3.9" @@ -4353,11 +4403,11 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b" +checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -4393,6 +4443,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-targets" version = "0.48.5" @@ -4525,9 +4584,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.6.16" +version = "0.6.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b480ae9340fc261e6be3e95a1ba86d54ae3f9171132a73ce8d4bbaf68339507c" +checksum = "68a9bda4691f099d435ad181000724da8e5899daa10713c2d432552b9ccd3a6f" dependencies = [ "memchr", ] @@ -4583,6 +4642,20 @@ name = "zeroize" version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.72", +] [[package]] name = "zstd" @@ -4595,18 +4668,18 @@ dependencies = [ [[package]] name = "zstd-safe" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa556e971e7b568dc775c136fc9de8c779b1c2fc3a63defaafadffdbd3181afa" +checksum = "54a3ab4db68cea366acc5c897c7b4d4d1b8994a9cd6e6f841f8964566a419059" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.0.12+zstd.1.5.6" +version = "2.0.13+zstd.1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a4e40c320c3cb459d9a9ff6de98cff88f4751ee9275d140e2be94a2b74e4c13" +checksum = "38ff0f21cfee8f97d94cef41359e0c89aa6113028ab0291aa8ca0038995a95aa" dependencies = [ "cc", "pkg-config", From 5939b9a69599fe4e578656d2a09cfafbdcc86a29 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 5 Aug 2024 16:09:50 +0100 Subject: [PATCH 0459/1297] docs: update roadmap in README Permanent keys have been already implemented. --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 306a8620c..6d611d9a5 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,6 @@ Core: - [ ] New option `want_ip_from_query_string`. See . -- [ ] Permanent keys. See . - [ ] Peer and torrents specific statistics. See . Persistence: From 222fa42ee0bf8674bb2b2ec639ed2fdcf8b02763 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 5 Jul 2024 11:33:24 +0100 Subject: [PATCH 0460/1297] feat: disable TimeoutAcceptor when TSL is enabled The TimeoutAcceptor es a custom acceptor for Axum that sets a timeput for making a request after openning a connection. It does not work when TSL is enabled. This commit disables it, therefore the app does not have any way to avoid a DDos attacks where clients just open connections without making any request. --- src/servers/apis/server.rs | 4 +++- src/servers/http/server.rs | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 39a68a856..40c4d0779 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -239,7 +239,9 @@ impl Launcher { match tls { Some(tls) => custom_axum_server::from_tcp_rustls_with_timeouts(socket, tls) .handle(handle) - .acceptor(TimeoutAcceptor) + // The TimeoutAcceptor is commented because TSL does not work with it. + // See: https://github.com/torrust/torrust-index/issues/204#issuecomment-2115529214 + //.acceptor(TimeoutAcceptor) .serve(router.into_make_service_with_connect_info::()) .await .expect("Axum server for tracker API crashed."), diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index faedaf921..4a6dccc6a 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -65,7 +65,9 @@ impl Launcher { match tls { Some(tls) => custom_axum_server::from_tcp_rustls_with_timeouts(socket, tls) .handle(handle) - .acceptor(TimeoutAcceptor) + // The TimeoutAcceptor is commented because TSL does not work with it. + // See: https://github.com/torrust/torrust-index/issues/204#issuecomment-2115529214 + //.acceptor(TimeoutAcceptor) .serve(app.into_make_service_with_connect_info::()) .await .expect("Axum server crashed."), From e563bfbcd0b25004ce13bfefd448656606380c00 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 8 Aug 2024 12:01:22 +0100 Subject: [PATCH 0461/1297] fix: benchmarking config template - Missing [core.tracker_policy] section. Configuration was changed. - Missing database config. Needed when the default DB folder does not exist. With this config storage folder is not needed. WE are not using DB which required DB for benchmarking. --- share/default/config/tracker.udp.benchmarking.toml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml index a73760b95..c6644d8dc 100644 --- a/share/default/config/tracker.udp.benchmarking.toml +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -1,6 +1,4 @@ [metadata] -app = "torrust-tracker" -purpose = "configuration" schema_version = "2.0.0" [logging] @@ -9,8 +7,15 @@ threshold = "error" [core] listed = false private = false -remove_peerless_torrents = false tracker_usage_statistics = false +[core.database] +driver = "sqlite3" +path = "./sqlite3.db" + +[core.tracker_policy] +persistent_torrent_completed_stat = false +remove_peerless_torrents = false + [[udp_trackers]] bind_address = "0.0.0.0:6969" From 176658762b9cd03d081b628a28aa1528ab19a137 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 8 Aug 2024 16:27:34 +0100 Subject: [PATCH 0462/1297] feat: [#1002] remove inactive peers always even when `remove_peerless_torrents` is disabled. We should remove peer that haven't announce otherwise we are returning inactive peers to the clients. That does not affect keeping the torrents even if they don't have any peer. --- src/core/mod.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 98de9e4fd..a6ee830db 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -778,18 +778,17 @@ impl Tracker { self.torrents.get_metrics() } - /// Remove inactive peers and (optionally) peerless torrents + /// Remove inactive peers and (optionally) peerless torrents. /// /// # Context: Tracker pub fn cleanup_torrents(&self) { - // If we don't need to remove torrents we will use the faster iter + let current_cutoff = CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout))) + .unwrap_or_default(); + + self.torrents.remove_inactive_peers(current_cutoff); + if self.config.tracker_policy.remove_peerless_torrents { self.torrents.remove_peerless_torrents(&self.config.tracker_policy); - } else { - let current_cutoff = - CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout))) - .unwrap_or_default(); - self.torrents.remove_inactive_peers(current_cutoff); } } From 3fbab31f741475596fcedd1527804efa72b02ead Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 8 Aug 2024 16:38:50 +0100 Subject: [PATCH 0463/1297] refactor: [#1002] rename is_good fn to meets_retaining_policy A "good" torrent means it should be retained in the repository according to the tracker policy. It should not be removed (even if it does not have any peers). --- packages/torrent-repository/src/entry/mod.rs | 6 +++--- .../src/entry/mutex_parking_lot.rs | 4 ++-- packages/torrent-repository/src/entry/mutex_std.rs | 4 ++-- packages/torrent-repository/src/entry/mutex_tokio.rs | 4 ++-- .../src/entry/rw_lock_parking_lot.rs | 4 ++-- packages/torrent-repository/src/entry/single.rs | 2 +- .../src/repository/dash_map_mutex_std.rs | 2 +- .../torrent-repository/src/repository/rw_lock_std.rs | 2 +- .../src/repository/rw_lock_std_mutex_std.rs | 2 +- .../src/repository/rw_lock_std_mutex_tokio.rs | 4 ++-- .../src/repository/rw_lock_tokio.rs | 2 +- .../src/repository/rw_lock_tokio_mutex_std.rs | 2 +- .../src/repository/rw_lock_tokio_mutex_tokio.rs | 2 +- .../src/repository/skip_map_mutex_std.rs | 6 +++--- packages/torrent-repository/tests/common/torrent.rs | 12 ++++++------ packages/torrent-repository/tests/entry/mod.rs | 12 ++++++------ packages/torrent-repository/tests/repository/mod.rs | 2 +- 17 files changed, 36 insertions(+), 36 deletions(-) diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index b811d3262..b920839d9 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -22,7 +22,7 @@ pub trait Entry { fn get_swarm_metadata(&self) -> SwarmMetadata; /// Returns True if Still a Valid Entry according to the Tracker Policy - fn is_good(&self, policy: &TrackerPolicy) -> bool; + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool; /// Returns True if the Peers is Empty fn peers_is_empty(&self) -> bool; @@ -53,7 +53,7 @@ pub trait Entry { #[allow(clippy::module_name_repetitions)] pub trait EntrySync { fn get_swarm_metadata(&self) -> SwarmMetadata; - fn is_good(&self, policy: &TrackerPolicy) -> bool; + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool; fn peers_is_empty(&self) -> bool; fn get_peers_len(&self) -> usize; fn get_peers(&self, limit: Option) -> Vec>; @@ -65,7 +65,7 @@ pub trait EntrySync { #[allow(clippy::module_name_repetitions)] pub trait EntryAsync { fn get_swarm_metadata(&self) -> impl std::future::Future + Send; - fn check_good(self, policy: &TrackerPolicy) -> impl std::future::Future + Send; + fn meets_retaining_policy(self, policy: &TrackerPolicy) -> impl std::future::Future + Send; fn peers_is_empty(&self) -> impl std::future::Future + Send; fn get_peers_len(&self) -> impl std::future::Future + Send; fn get_peers(&self, limit: Option) -> impl std::future::Future>> + Send; diff --git a/packages/torrent-repository/src/entry/mutex_parking_lot.rs b/packages/torrent-repository/src/entry/mutex_parking_lot.rs index 4f3921ea7..738c3ff9d 100644 --- a/packages/torrent-repository/src/entry/mutex_parking_lot.rs +++ b/packages/torrent-repository/src/entry/mutex_parking_lot.rs @@ -13,8 +13,8 @@ impl EntrySync for EntryMutexParkingLot { self.lock().get_swarm_metadata() } - fn is_good(&self, policy: &TrackerPolicy) -> bool { - self.lock().is_good(policy) + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + self.lock().meets_retaining_policy(policy) } fn peers_is_empty(&self) -> bool { diff --git a/packages/torrent-repository/src/entry/mutex_std.rs b/packages/torrent-repository/src/entry/mutex_std.rs index 990d8ab76..0ab70a96f 100644 --- a/packages/torrent-repository/src/entry/mutex_std.rs +++ b/packages/torrent-repository/src/entry/mutex_std.rs @@ -13,8 +13,8 @@ impl EntrySync for EntryMutexStd { self.lock().expect("it should get a lock").get_swarm_metadata() } - fn is_good(&self, policy: &TrackerPolicy) -> bool { - self.lock().expect("it should get a lock").is_good(policy) + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + self.lock().expect("it should get a lock").meets_retaining_policy(policy) } fn peers_is_empty(&self) -> bool { diff --git a/packages/torrent-repository/src/entry/mutex_tokio.rs b/packages/torrent-repository/src/entry/mutex_tokio.rs index c5363e51a..6db789a72 100644 --- a/packages/torrent-repository/src/entry/mutex_tokio.rs +++ b/packages/torrent-repository/src/entry/mutex_tokio.rs @@ -13,8 +13,8 @@ impl EntryAsync for EntryMutexTokio { self.lock().await.get_swarm_metadata() } - async fn check_good(self, policy: &TrackerPolicy) -> bool { - self.lock().await.is_good(policy) + async fn meets_retaining_policy(self, policy: &TrackerPolicy) -> bool { + self.lock().await.meets_retaining_policy(policy) } async fn peers_is_empty(&self) -> bool { diff --git a/packages/torrent-repository/src/entry/rw_lock_parking_lot.rs b/packages/torrent-repository/src/entry/rw_lock_parking_lot.rs index ef0e958d5..ac0dc0b30 100644 --- a/packages/torrent-repository/src/entry/rw_lock_parking_lot.rs +++ b/packages/torrent-repository/src/entry/rw_lock_parking_lot.rs @@ -13,8 +13,8 @@ impl EntrySync for EntryRwLockParkingLot { self.read().get_swarm_metadata() } - fn is_good(&self, policy: &TrackerPolicy) -> bool { - self.read().is_good(policy) + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + self.read().meets_retaining_policy(policy) } fn peers_is_empty(&self) -> bool { diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs index a01124454..6d7ed3155 100644 --- a/packages/torrent-repository/src/entry/single.rs +++ b/packages/torrent-repository/src/entry/single.rs @@ -22,7 +22,7 @@ impl Entry for EntrySingle { } } - fn is_good(&self, policy: &TrackerPolicy) -> bool { + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { if policy.persistent_torrent_completed_stat && self.downloaded > 0 { return true; } diff --git a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs index a38205205..4354c12ec 100644 --- a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs @@ -103,6 +103,6 @@ where } fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - self.torrents.retain(|_, entry| entry.is_good(policy)); + self.torrents.retain(|_, entry| entry.meets_retaining_policy(policy)); } } diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs index 0d96a2375..5439fdd79 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std.rs @@ -126,6 +126,6 @@ where fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { let mut db = self.get_torrents_mut(); - db.retain(|_, e| e.is_good(policy)); + db.retain(|_, e| e.meets_retaining_policy(policy)); } } diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs index 76d5e8f1e..7d58b0b10 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs @@ -124,6 +124,6 @@ where fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { let mut db = self.get_torrents_mut(); - db.retain(|_, e| e.lock().expect("it should lock entry").is_good(policy)); + db.retain(|_, e| e.lock().expect("it should lock entry").meets_retaining_policy(policy)); } } diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs index e527d6b59..90451ca9f 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs @@ -143,8 +143,8 @@ where handles = zip(db.keys().copied(), db.values().cloned()) .map(|(infohash, torrent)| { torrent - .check_good(policy) - .map(move |good| if good { None } else { Some(infohash) }) + .meets_retaining_policy(policy) + .map(move |should_be_retained| if should_be_retained { None } else { Some(infohash) }) .boxed() }) .collect::>(); diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs index c360106b8..baaa01232 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio.rs @@ -130,6 +130,6 @@ where async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { let mut db = self.get_torrents_mut().await; - db.retain(|_, e| e.is_good(policy)); + db.retain(|_, e| e.meets_retaining_policy(policy)); } } diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs index 9fce79b44..1887f70c7 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs @@ -124,6 +124,6 @@ where async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { let mut db = self.get_torrents_mut().await; - db.retain(|_, e| e.lock().expect("it should lock entry").is_good(policy)); + db.retain(|_, e| e.lock().expect("it should lock entry").meets_retaining_policy(policy)); } } diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs index c7e0d4054..6c9c08a73 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -130,7 +130,7 @@ where let mut not_good = Vec::::default(); for (&infohash, torrent) in db.iter() { - if !torrent.clone().check_good(policy).await { + if !torrent.clone().meets_retaining_policy(policy).await { not_good.push(infohash); } } diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index 9960b0c30..dd0d9c1b1 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -100,7 +100,7 @@ where fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { for entry in &self.torrents { - if entry.value().is_good(policy) { + if entry.value().meets_retaining_policy(policy) { continue; } @@ -191,7 +191,7 @@ where fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { for entry in &self.torrents { - if entry.value().is_good(policy) { + if entry.value().meets_retaining_policy(policy) { continue; } @@ -282,7 +282,7 @@ where fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { for entry in &self.torrents { - if entry.value().is_good(policy) { + if entry.value().meets_retaining_policy(policy) { continue; } diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index abcf5525e..927f13169 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -29,13 +29,13 @@ impl Torrent { } } - pub(crate) async fn is_good(&self, policy: &TrackerPolicy) -> bool { + pub(crate) async fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { match self { - Torrent::Single(entry) => entry.is_good(policy), - Torrent::MutexStd(entry) => entry.is_good(policy), - Torrent::MutexTokio(entry) => entry.clone().check_good(policy).await, - Torrent::MutexParkingLot(entry) => entry.is_good(policy), - Torrent::RwLockParkingLot(entry) => entry.is_good(policy), + Torrent::Single(entry) => entry.meets_retaining_policy(policy), + Torrent::MutexStd(entry) => entry.meets_retaining_policy(policy), + Torrent::MutexTokio(entry) => entry.clone().meets_retaining_policy(policy).await, + Torrent::MutexParkingLot(entry) => entry.meets_retaining_policy(policy), + Torrent::RwLockParkingLot(entry) => entry.meets_retaining_policy(policy), } } diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index fdbe211b3..2a7063a4f 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -126,7 +126,7 @@ async fn it_should_be_empty_by_default( #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_check_if_entry_is_good( +async fn it_should_check_if_entry_should_be_retained_based_on_the_tracker_policy( #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, #[case] makes: &Makes, #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, @@ -141,19 +141,19 @@ async fn it_should_check_if_entry_is_good( (true, true) => match (has_peers, has_downloads) { // no peers, but has downloads // peers, with or without downloads - (false, true) | (true, true | false) => assert!(torrent.is_good(&policy).await), + (false, true) | (true, true | false) => assert!(torrent.meets_retaining_policy(&policy).await), // no peers and no downloads - (false, false) => assert!(!torrent.is_good(&policy).await), + (false, false) => assert!(!torrent.meets_retaining_policy(&policy).await), }, // remove torrents without peers and drop completed download stats (true, false) => match (has_peers, has_downloads) { // peers, with or without downloads - (true, true | false) => assert!(torrent.is_good(&policy).await), + (true, true | false) => assert!(torrent.meets_retaining_policy(&policy).await), // no peers and with or without downloads - (false, true | false) => assert!(!torrent.is_good(&policy).await), + (false, true | false) => assert!(!torrent.meets_retaining_policy(&policy).await), }, // keep torrents without peers, but keep or drop completed download stats - (false, true | false) => assert!(torrent.is_good(&policy).await), + (false, true | false) => assert!(torrent.meets_retaining_policy(&policy).await), } } diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index b10f4a64a..b3b742607 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -634,6 +634,6 @@ async fn it_should_remove_peerless_torrents( let torrents = repo.get_paginated(None).await; for (_, entry) in torrents { - assert!(entry.is_good(&policy)); + assert!(entry.meets_retaining_policy(&policy)); } } From f5e38bb9f40675a9cca28d43ea92c2f3a5defdcc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 12 Aug 2024 10:17:12 +0100 Subject: [PATCH 0464/1297] feat!: [#1006] remove config deafults for secrets --- .../configuration/src/v2_0_0/tracker_api.rs | 21 ++++++++++++------- packages/test-helpers/src/configuration.rs | 6 ++++-- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/packages/configuration/src/v2_0_0/tracker_api.rs b/packages/configuration/src/v2_0_0/tracker_api.rs index 43b08a21e..2da21758b 100644 --- a/packages/configuration/src/v2_0_0/tracker_api.rs +++ b/packages/configuration/src/v2_0_0/tracker_api.rs @@ -52,14 +52,11 @@ impl HttpApi { } fn default_access_tokens() -> AccessTokens { - [(String::from("admin"), String::from("MyAccessToken"))] - .iter() - .cloned() - .collect() + [].iter().cloned().collect() } - pub fn override_admin_token(&mut self, api_admin_token: &str) { - self.access_tokens.insert("admin".to_string(), api_admin_token.to_string()); + pub fn add_token(&mut self, key: &str, token: &str) { + self.access_tokens.insert(key.to_string(), token.to_string()); } pub fn mask_secrets(&mut self) { @@ -74,10 +71,18 @@ mod tests { use crate::v2_0_0::tracker_api::HttpApi; #[test] - fn http_api_configuration_should_check_if_it_contains_a_token() { + fn default_http_api_configuration_should_not_contains_any_token() { let configuration = HttpApi::default(); + assert_eq!(configuration.access_tokens.values().len(), 0); + } + + #[test] + fn http_api_configuration_should_allow_adding_tokens() { + let mut configuration = HttpApi::default(); + + configuration.add_token("admin", "MyAccessToken"); + assert!(configuration.access_tokens.values().any(|t| t == "MyAccessToken")); - assert!(!configuration.access_tokens.values().any(|t| t == "NonExistingToken")); } } diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 0a6c1c72b..0c4029b69 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -32,10 +32,12 @@ pub fn ephemeral() -> Configuration { // Ephemeral socket address for API let api_port = 0u16; - config.http_api = Some(HttpApi { + let mut http_api = HttpApi { bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), api_port), ..Default::default() - }); + }; + http_api.add_token("admin", "MyAccessToken"); + config.http_api = Some(http_api); // Ephemeral socket address for Health Check API let health_check_api_port = 0u16; From 6a707b9d0975c7f0bef83c65e3771a8a77b79513 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 12 Aug 2024 10:30:06 +0100 Subject: [PATCH 0465/1297] fix: linter errors --- src/app.rs | 71 ++++++++++++------------- src/console/ci/e2e/tracker_container.rs | 13 ++--- 2 files changed, 39 insertions(+), 45 deletions(-) diff --git a/src/app.rs b/src/app.rs index fd7d6a99d..b2447a9ef 100644 --- a/src/app.rs +++ b/src/app.rs @@ -66,56 +66,53 @@ pub async fn start(config: &Configuration, tracker: Arc) -> Vec { - for udp_tracker_config in udp_trackers { - if tracker.is_private() { - warn!( - "Could not start UDP tracker on: {} while in private mode. UDP is not safe for private trackers!", - udp_tracker_config.bind_address - ); - } else { - jobs.push(udp_tracker::start_job(udp_tracker_config, tracker.clone(), registar.give_form()).await); - } + if let Some(udp_trackers) = &config.udp_trackers { + for udp_tracker_config in udp_trackers { + if tracker.is_private() { + warn!( + "Could not start UDP tracker on: {} while in private mode. UDP is not safe for private trackers!", + udp_tracker_config.bind_address + ); + } else { + jobs.push(udp_tracker::start_job(udp_tracker_config, tracker.clone(), registar.give_form()).await); } } - None => info!("No UDP blocks in configuration"), + } else { + info!("No UDP blocks in configuration"); } // Start the HTTP blocks - match &config.http_trackers { - Some(http_trackers) => { - for http_tracker_config in http_trackers { - if let Some(job) = http_tracker::start_job( - http_tracker_config, - tracker.clone(), - registar.give_form(), - servers::http::Version::V1, - ) - .await - { - jobs.push(job); - }; - } - } - None => info!("No HTTP blocks in configuration"), - } - - // Start HTTP API - match &config.http_api { - Some(http_api_config) => { - if let Some(job) = tracker_apis::start_job( - http_api_config, + if let Some(http_trackers) = &config.http_trackers { + for http_tracker_config in http_trackers { + if let Some(job) = http_tracker::start_job( + http_tracker_config, tracker.clone(), registar.give_form(), - servers::apis::Version::V1, + servers::http::Version::V1, ) .await { jobs.push(job); }; } - None => info!("No API block in configuration"), + } else { + info!("No HTTP blocks in configuration"); + } + + // Start HTTP API + if let Some(http_api_config) = &config.http_api { + if let Some(job) = tracker_apis::start_job( + http_api_config, + tracker.clone(), + registar.give_form(), + servers::apis::Version::V1, + ) + .await + { + jobs.push(job); + }; + } else { + info!("No API block in configuration"); } // Start runners to remove torrents without peers, every interval diff --git a/src/console/ci/e2e/tracker_container.rs b/src/console/ci/e2e/tracker_container.rs index dc7036faa..528fd3c62 100644 --- a/src/console/ci/e2e/tracker_container.rs +++ b/src/console/ci/e2e/tracker_container.rs @@ -105,14 +105,11 @@ impl TrackerContainer { /// /// Will panic if it can't remove the container. pub fn remove(&self) { - match &self.running { - Some(_running_container) => { - error!("Can't remove running container: {} ...", self.name); - } - None => { - info!("Removing docker tracker container: {} ...", self.name); - Docker::remove(&self.name).expect("Container should be removed"); - } + if let Some(_running_container) = &self.running { + error!("Can't remove running container: {} ...", self.name); + } else { + info!("Removing docker tracker container: {} ...", self.name); + Docker::remove(&self.name).expect("Container should be removed"); } } From 62ffffb124fad1bb78d932c38aca8b55a05278f6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 12 Aug 2024 11:04:07 +0100 Subject: [PATCH 0466/1297] chore(deps): update dependencies ```console cargo update Updating crates.io index Locking 16 packages to latest compatible versions Updating async-io v2.3.3 -> v2.3.4 Updating cc v1.1.7 -> v1.1.10 Updating clap v4.5.13 -> v4.5.15 Updating clap_builder v4.5.13 -> v4.5.15 Updating core-foundation-sys v0.8.6 -> v0.8.7 Updating hyper-util v0.1.6 -> v0.1.7 Updating mio v1.0.1 -> v1.0.2 Updating object v0.36.2 -> v0.36.3 Updating piper v0.2.3 -> v0.2.4 Updating polling v3.7.2 -> v3.7.3 Updating rustls-pki-types v1.7.0 -> v1.8.0 Updating serde v1.0.204 -> v1.0.206 Updating serde_derive v1.0.204 -> v1.0.206 Updating serde_json v1.0.122 -> v1.0.124 Updating syn v2.0.72 -> v2.0.74 Updating tempfile v3.11.0 -> v3.12.0 ``` --- Cargo.lock | 138 ++++++++++++++++++++++++++--------------------------- 1 file changed, 69 insertions(+), 69 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e60aca814..94bcd6419 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -254,7 +254,7 @@ checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" dependencies = [ "async-channel 2.3.1", "async-executor", - "async-io 2.3.3", + "async-io 2.3.4", "async-lock 3.4.0", "blocking", "futures-lite 2.3.0", @@ -284,9 +284,9 @@ dependencies = [ [[package]] name = "async-io" -version = "2.3.3" +version = "2.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d6baa8f0178795da0e71bc42c9e5d13261aac7ee549853162e66a241ba17964" +checksum = "444b0228950ee6501b3568d3c93bf1176a1fdbc3b758dcd9475046d30f4dc7e8" dependencies = [ "async-lock 3.4.0", "cfg-if", @@ -294,11 +294,11 @@ dependencies = [ "futures-io", "futures-lite 2.3.0", "parking", - "polling 3.7.2", + "polling 3.7.3", "rustix 0.38.34", "slab", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -362,7 +362,7 @@ checksum = "6e0c28dcc82d7c8ead5cb13beb15405b57b8546e93215673ff8ca0349a028107" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -512,7 +512,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -604,7 +604,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.72", + "syn 2.0.74", "which", ] @@ -674,7 +674,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", "syn_derive", ] @@ -786,9 +786,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.1.7" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26a5c3fd7bfa1ce3897a3a3501d362b2d87b7f2583ebcb4a949ec25911025cbc" +checksum = "e9e8aabfac534be767c909e0690571677d49f41bd8465ae876fe043d52ba5292" dependencies = [ "jobserver", "libc", @@ -868,9 +868,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.13" +version = "4.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fbb260a053428790f3de475e304ff84cdbc4face759ea7a3e64c1edd938a7fc" +checksum = "11d8838454fda655dafd3accb2b6e2bea645b9e4078abe84a22ceb947235c5cc" dependencies = [ "clap_builder", "clap_derive", @@ -878,9 +878,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.13" +version = "4.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64b17d7ea74e9f833c7dbf2cbe4fb12ff26783eda4782a8975b72f895c9b4d99" +checksum = "216aec2b177652e3846684cbfe25c9964d18ec45234f0f5da5157b207ed1aab6" dependencies = [ "anstream", "anstyle", @@ -897,7 +897,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -961,9 +961,9 @@ dependencies = [ [[package]] name = "core-foundation-sys" -version = "0.8.6" +version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpufeatures" @@ -1124,7 +1124,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -1135,7 +1135,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -1172,7 +1172,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -1183,7 +1183,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -1411,7 +1411,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -1423,7 +1423,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -1435,7 +1435,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -1534,7 +1534,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -1822,9 +1822,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ab92f4f49ee4fb4f997c784b7a2e0fa70050211e0b6a287f898c3c9785ca956" +checksum = "cde7055719c54e36e95e8719f95883f22072a48ede39db7fc17a4e1d5281e9b9" dependencies = [ "bytes", "futures-channel", @@ -2153,9 +2153,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.0.1" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4569e456d394deccd22ce1c1913e6ea0e54519f577285001215d33557431afe4" +checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" dependencies = [ "hermit-abi 0.3.9", "libc", @@ -2192,7 +2192,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -2242,7 +2242,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", "termcolor", "thiserror", ] @@ -2399,9 +2399,9 @@ dependencies = [ [[package]] name = "object" -version = "0.36.2" +version = "0.36.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f203fa8daa7bb185f760ae12bd8e097f63d17041dcdcaf675ac54cdf863170e" +checksum = "27b64972346851a39438c60b341ebc01bba47464ae329e55cf343eb93964efd9" dependencies = [ "memchr", ] @@ -2441,7 +2441,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -2523,7 +2523,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -2597,7 +2597,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -2614,9 +2614,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "piper" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae1d5c74c9876f070d3e8fd503d748c7d974c3e48da8f41350fa5222ef9b4391" +checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066" dependencies = [ "atomic-waker", "fastrand 2.1.0", @@ -2675,9 +2675,9 @@ dependencies = [ [[package]] name = "polling" -version = "3.7.2" +version = "3.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3ed00ed3fbf728b5816498ecd316d1716eecaced9c0c8d2c5a6740ca214985b" +checksum = "cc2790cd301dec6cd3b7a025e4815cf825724a51c98dccfe6a3e55f05ffb6511" dependencies = [ "cfg-if", "concurrent-queue", @@ -2685,7 +2685,7 @@ dependencies = [ "pin-project-lite", "rustix 0.38.34", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -2736,7 +2736,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e" dependencies = [ "proc-macro2", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -2789,7 +2789,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", "version_check", "yansi", ] @@ -3097,7 +3097,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.72", + "syn 2.0.74", "unicode-ident", ] @@ -3205,9 +3205,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.7.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d" +checksum = "fc0a2ce646f8655401bb81e7927b812614bd5d91dbc968696be50603510fcaf0" [[package]] name = "rustls-webpki" @@ -3309,9 +3309,9 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" -version = "1.0.204" +version = "1.0.206" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12" +checksum = "5b3e4cd94123dd520a128bcd11e34d9e9e423e7e3e50425cb1b4b1e3549d0284" dependencies = [ "serde_derive", ] @@ -3337,13 +3337,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.204" +version = "1.0.206" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" +checksum = "fabfb6138d2383ea8208cf98ccf69cdfb1aff4088460681d84189aa259762f97" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -3361,9 +3361,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.122" +version = "1.0.124" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "784b6203951c57ff748476b126ccb5e8e2959a5c19e5c617ab1956be3dbc68da" +checksum = "66ad62847a56b3dba58cc891acd13884b9c61138d330c0d7b6181713d4fce38d" dependencies = [ "indexmap 2.3.0", "itoa", @@ -3390,7 +3390,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -3441,7 +3441,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -3584,9 +3584,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.72" +version = "2.0.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" +checksum = "1fceb41e3d546d0bd83421d3409b1460cc7444cd389341a4c880fe7a042cb3d7" dependencies = [ "proc-macro2", "quote", @@ -3602,7 +3602,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -3663,15 +3663,15 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.11.0" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8fcd239983515c23a32fb82099f97d0b11b8c72f654ed659363a95c3dad7a53" +checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64" dependencies = [ "cfg-if", "fastrand 2.1.0", "once_cell", "rustix 0.38.34", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3706,7 +3706,7 @@ checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -3800,7 +3800,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -4104,7 +4104,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -4318,7 +4318,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", "wasm-bindgen-shared", ] @@ -4352,7 +4352,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4634,7 +4634,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] @@ -4654,7 +4654,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.72", + "syn 2.0.74", ] [[package]] From 1455295e39f955496b03dc9005afc9aa3214cbcd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 12 Aug 2024 17:24:58 +0100 Subject: [PATCH 0467/1297] ci: [#1010] fix missing publishing packages --- .github/workflows/deployment.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 2a0f174f7..6aa66e985 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -54,6 +54,8 @@ jobs: cargo publish -p torrust-tracker-contrib-bencode cargo publish -p torrust-tracker-located-error cargo publish -p torrust-tracker-primitives + cargo publish -p torrust-tracker-clock cargo publish -p torrust-tracker-configuration + cargo publish -p torrust-tracker-torrent-repository cargo publish -p torrust-tracker-test-helpers cargo publish -p torrust-tracker From 592c9cce0bf801735f39d9ab9b5764362de6b6a9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 13 Aug 2024 10:30:47 +0100 Subject: [PATCH 0468/1297] release: version 3.0.0-alpha.12 --- Cargo.lock | 16 ++++++++-------- Cargo.toml | 16 ++++++++-------- packages/clock/Cargo.toml | 2 +- packages/configuration/Cargo.toml | 2 +- packages/test-helpers/Cargo.toml | 2 +- packages/torrent-repository/Cargo.toml | 6 +++--- 6 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 94bcd6419..ddee311ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3884,7 +3884,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.12-develop" +version = "3.0.0-alpha.12" dependencies = [ "anyhow", "aquatic_udp_protocol", @@ -3946,7 +3946,7 @@ dependencies = [ [[package]] name = "torrust-tracker-clock" -version = "3.0.0-alpha.12-develop" +version = "3.0.0-alpha.12" dependencies = [ "chrono", "lazy_static", @@ -3955,7 +3955,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.12-develop" +version = "3.0.0-alpha.12" dependencies = [ "camino", "derive_more", @@ -3972,7 +3972,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.12-develop" +version = "3.0.0-alpha.12" dependencies = [ "criterion", "error-chain", @@ -3980,7 +3980,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.12-develop" +version = "3.0.0-alpha.12" dependencies = [ "thiserror", "tracing", @@ -3988,7 +3988,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.12-develop" +version = "3.0.0-alpha.12" dependencies = [ "binascii", "derive_more", @@ -4000,7 +4000,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.12-develop" +version = "3.0.0-alpha.12" dependencies = [ "rand", "torrust-tracker-configuration", @@ -4008,7 +4008,7 @@ dependencies = [ [[package]] name = "torrust-tracker-torrent-repository" -version = "3.0.0-alpha.12-develop" +version = "3.0.0-alpha.12" dependencies = [ "async-std", "criterion", diff --git a/Cargo.toml b/Cargo.toml index 4184f2ae7..7f9d211c3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ license = "AGPL-3.0-only" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.12-develop" +version = "3.0.0-alpha.12" [dependencies] anyhow = "1" @@ -69,12 +69,12 @@ serde_repr = "0" serde_with = { version = "3.9.0", features = ["json"] } thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-clock = { version = "3.0.0-alpha.12-develop", path = "packages/clock" } -torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12-develop", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "packages/primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-alpha.12-develop", path = "packages/torrent-repository" } +torrust-tracker-clock = { version = "3.0.0-alpha.12", path = "packages/clock" } +torrust-tracker-configuration = { version = "3.0.0-alpha.12", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.12", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.12", path = "packages/primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-alpha.12", path = "packages/torrent-repository" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } trace = "0" @@ -90,7 +90,7 @@ ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_byt [dev-dependencies] local-ip-address = "0" mockall = "0" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.12-develop", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-alpha.12", path = "packages/test-helpers" } [workspace] members = [ diff --git a/packages/clock/Cargo.toml b/packages/clock/Cargo.toml index d71175fdc..0177b2fb3 100644 --- a/packages/clock/Cargo.toml +++ b/packages/clock/Cargo.toml @@ -19,6 +19,6 @@ version.workspace = true chrono = { version = "0", default-features = false, features = ["clock"] } lazy_static = "1" -torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } +torrust-tracker-primitives = { version = "3.0.0-alpha.12", path = "../primitives" } [dev-dependencies] diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 5afa39b89..a4c3f2006 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -23,7 +23,7 @@ serde_json = { version = "1", features = ["preserve_order"] } serde_with = "3" thiserror = "1" toml = "0" -torrust-tracker-located-error = { version = "3.0.0-alpha.12-develop", path = "../located-error" } +torrust-tracker-located-error = { version = "3.0.0-alpha.12", path = "../located-error" } url = "2" [dev-dependencies] diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 4fed6bc42..5a4220b53 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -16,4 +16,4 @@ version.workspace = true [dependencies] rand = "0" -torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } +torrust-tracker-configuration = { version = "3.0.0-alpha.12", path = "../configuration" } diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 53bb41e52..f1f85a52d 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -21,9 +21,9 @@ dashmap = "6" futures = "0" parking_lot = "0" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-clock = { version = "3.0.0-alpha.12-develop", path = "../clock" } -torrust-tracker-configuration = { version = "3.0.0-alpha.12-develop", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.12-develop", path = "../primitives" } +torrust-tracker-clock = { version = "3.0.0-alpha.12", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-alpha.12", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.12", path = "../primitives" } [dev-dependencies] async-std = { version = "1", features = ["attributes", "tokio1"] } From 8fcc016fb62e363dde2214e0b73955987d9af2fa Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 13 Aug 2024 11:31:29 +0100 Subject: [PATCH 0469/1297] develop: bump to version 3.0.0-beta-develop --- Cargo.lock | 16 ++++++++-------- Cargo.toml | 16 ++++++++-------- packages/clock/Cargo.toml | 2 +- packages/configuration/Cargo.toml | 2 +- packages/test-helpers/Cargo.toml | 2 +- packages/torrent-repository/Cargo.toml | 6 +++--- 6 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ddee311ea..d51ecff56 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3884,7 +3884,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.12" +version = "3.0.0-beta-develop" dependencies = [ "anyhow", "aquatic_udp_protocol", @@ -3946,7 +3946,7 @@ dependencies = [ [[package]] name = "torrust-tracker-clock" -version = "3.0.0-alpha.12" +version = "3.0.0-beta-develop" dependencies = [ "chrono", "lazy_static", @@ -3955,7 +3955,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.12" +version = "3.0.0-beta-develop" dependencies = [ "camino", "derive_more", @@ -3972,7 +3972,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-alpha.12" +version = "3.0.0-beta-develop" dependencies = [ "criterion", "error-chain", @@ -3980,7 +3980,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.12" +version = "3.0.0-beta-develop" dependencies = [ "thiserror", "tracing", @@ -3988,7 +3988,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.12" +version = "3.0.0-beta-develop" dependencies = [ "binascii", "derive_more", @@ -4000,7 +4000,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.12" +version = "3.0.0-beta-develop" dependencies = [ "rand", "torrust-tracker-configuration", @@ -4008,7 +4008,7 @@ dependencies = [ [[package]] name = "torrust-tracker-torrent-repository" -version = "3.0.0-alpha.12" +version = "3.0.0-beta-develop" dependencies = [ "async-std", "criterion", diff --git a/Cargo.toml b/Cargo.toml index 7f9d211c3..43453cb5a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ license = "AGPL-3.0-only" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-alpha.12" +version = "3.0.0-beta-develop" [dependencies] anyhow = "1" @@ -69,12 +69,12 @@ serde_repr = "0" serde_with = { version = "3.9.0", features = ["json"] } thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-clock = { version = "3.0.0-alpha.12", path = "packages/clock" } -torrust-tracker-configuration = { version = "3.0.0-alpha.12", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.12", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-alpha.12", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-alpha.12", path = "packages/primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-alpha.12", path = "packages/torrent-repository" } +torrust-tracker-clock = { version = "3.0.0-beta-develop", path = "packages/clock" } +torrust-tracker-configuration = { version = "3.0.0-beta-develop", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-beta-develop", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-beta-develop", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-beta-develop", path = "packages/primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-beta-develop", path = "packages/torrent-repository" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } trace = "0" @@ -90,7 +90,7 @@ ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_byt [dev-dependencies] local-ip-address = "0" mockall = "0" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.12", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-beta-develop", path = "packages/test-helpers" } [workspace] members = [ diff --git a/packages/clock/Cargo.toml b/packages/clock/Cargo.toml index 0177b2fb3..e28a37466 100644 --- a/packages/clock/Cargo.toml +++ b/packages/clock/Cargo.toml @@ -19,6 +19,6 @@ version.workspace = true chrono = { version = "0", default-features = false, features = ["clock"] } lazy_static = "1" -torrust-tracker-primitives = { version = "3.0.0-alpha.12", path = "../primitives" } +torrust-tracker-primitives = { version = "3.0.0-beta-develop", path = "../primitives" } [dev-dependencies] diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index a4c3f2006..0a4cfea23 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -23,7 +23,7 @@ serde_json = { version = "1", features = ["preserve_order"] } serde_with = "3" thiserror = "1" toml = "0" -torrust-tracker-located-error = { version = "3.0.0-alpha.12", path = "../located-error" } +torrust-tracker-located-error = { version = "3.0.0-beta-develop", path = "../located-error" } url = "2" [dev-dependencies] diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 5a4220b53..0fd108ecf 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -16,4 +16,4 @@ version.workspace = true [dependencies] rand = "0" -torrust-tracker-configuration = { version = "3.0.0-alpha.12", path = "../configuration" } +torrust-tracker-configuration = { version = "3.0.0-beta-develop", path = "../configuration" } diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index f1f85a52d..1fd58ab02 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -21,9 +21,9 @@ dashmap = "6" futures = "0" parking_lot = "0" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-clock = { version = "3.0.0-alpha.12", path = "../clock" } -torrust-tracker-configuration = { version = "3.0.0-alpha.12", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-alpha.12", path = "../primitives" } +torrust-tracker-clock = { version = "3.0.0-beta-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-beta-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-beta-develop", path = "../primitives" } [dev-dependencies] async-std = { version = "1", features = ["attributes", "tokio1"] } From 33757e0858761fcc18dae6613e427d87e9555f4f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 20 Aug 2024 11:13:18 +0100 Subject: [PATCH 0470/1297] chore(deps): update dependencies ```output cargo update Updating crates.io index Locking 43 packages to latest compatible versions Adding adler2 v2.0.0 Updating arrayvec v0.7.4 -> v0.7.6 Adding bindgen v0.70.0 Updating bytemuck v1.16.3 -> v1.17.0 Updating camino v1.1.7 -> v1.1.9 Updating cc v1.1.10 -> v1.1.13 Updating clap v4.5.15 -> v4.5.16 Updating cmake v0.1.50 -> v0.1.51 Updating cpufeatures v0.2.12 -> v0.2.13 Updating flate2 v1.0.31 -> v1.0.32 Updating h2 v0.4.5 -> v0.4.6 Updating indexmap v2.3.0 -> v2.4.0 Updating is-terminal v0.4.12 -> v0.4.13 Adding itertools v0.13.0 Updating js-sys v0.3.69 -> v0.3.70 Updating libc v0.2.155 -> v0.2.158 Updating libz-sys v1.1.18 -> v1.1.19 Adding miniz_oxide v0.8.0 Updating reqwest v0.12.5 -> v0.12.7 Updating ringbuf v0.4.1 -> v0.4.4 Updating rkyv v0.7.44 -> v0.7.45 Updating rkyv_derive v0.7.44 -> v0.7.45 Updating rust_decimal v1.35.0 -> v1.36.0 Updating serde v1.0.206 -> v1.0.208 Updating serde_derive v1.0.206 -> v1.0.208 Updating serde_json v1.0.124 -> v1.0.125 Updating syn v2.0.74 -> v2.0.75 Updating system-configuration v0.5.1 -> v0.6.0 Updating system-configuration-sys v0.5.0 -> v0.6.0 Updating tokio v1.39.2 -> v1.39.3 Adding tower v0.5.0 Updating tower-layer v0.3.2 -> v0.3.3 Updating tower-service v0.3.2 -> v0.3.3 Updating wasm-bindgen v0.2.92 -> v0.2.93 Updating wasm-bindgen-backend v0.2.92 -> v0.2.93 Updating wasm-bindgen-futures v0.4.42 -> v0.4.43 Updating wasm-bindgen-macro v0.2.92 -> v0.2.93 Updating wasm-bindgen-macro-support v0.2.92 -> v0.2.93 Updating wasm-bindgen-shared v0.2.92 -> v0.2.93 Updating web-sys v0.3.69 -> v0.3.70 Adding windows-registry v0.2.0 Adding windows-result v0.2.0 Adding windows-strings v0.1.0 Removing winreg v0.52.0 ``` --- Cargo.lock | 339 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 209 insertions(+), 130 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d51ecff56..a7589c287 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,12 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +[[package]] +name = "adler2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" + [[package]] name = "ahash" version = "0.7.8" @@ -180,9 +186,9 @@ checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457" [[package]] name = "arrayvec" -version = "0.7.4" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" [[package]] name = "async-attributes" @@ -362,7 +368,7 @@ checksum = "6e0c28dcc82d7c8ead5cb13beb15405b57b8546e93215673ff8ca0349a028107" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -404,7 +410,7 @@ version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f0e249228c6ad2d240c2dc94b714d711629d52bad946075d8e9b2f5391f0703" dependencies = [ - "bindgen", + "bindgen 0.69.4", "cc", "cmake", "dunce", @@ -442,7 +448,7 @@ dependencies = [ "serde_urlencoded", "sync_wrapper 1.0.1", "tokio", - "tower", + "tower 0.4.13", "tower-layer", "tower-service", "tracing", @@ -497,7 +503,7 @@ dependencies = [ "pin-project-lite", "serde", "serde_html_form", - "tower", + "tower 0.4.13", "tower-layer", "tower-service", "tracing", @@ -512,7 +518,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -535,7 +541,7 @@ dependencies = [ "rustls-pki-types", "tokio", "tokio-rustls", - "tower", + "tower 0.4.13", "tower-service", ] @@ -549,7 +555,7 @@ dependencies = [ "cc", "cfg-if", "libc", - "miniz_oxide", + "miniz_oxide 0.7.4", "object", "rustc-demangle", ] @@ -604,10 +610,28 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.74", + "syn 2.0.75", "which", ] +[[package]] +name = "bindgen" +version = "0.70.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0127a1da21afb5adaae26910922c3f7afd3d329ba1a1b98a0884cab4907a251" +dependencies = [ + "bitflags 2.6.0", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn 2.0.75", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -674,7 +698,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", "syn_derive", ] @@ -744,9 +768,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.16.3" +version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "102087e286b4677862ea56cf8fc58bb2cdfa8725c40ffb80fe3a008eb7f2fc83" +checksum = "6fd4c6dcc3b0aea2f5c0b4b82c2b15fe39ddbc76041a310848f4706edf76bb31" [[package]] name = "byteorder" @@ -762,9 +786,9 @@ checksum = "8318a53db07bb3f8dca91a600466bdb3f2eaadeedfdbcf02e1accbad9271ba50" [[package]] name = "camino" -version = "1.1.7" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0ec6b951b160caa93cc0c7b209e5a3bff7aae9062213451ac99493cd844c239" +checksum = "8b96ec4966b5813e2c0507c1f86115c8c5abaadc3980879c3424042a02fd1ad3" dependencies = [ "serde", ] @@ -786,12 +810,13 @@ dependencies = [ [[package]] name = "cc" -version = "1.1.10" +version = "1.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9e8aabfac534be767c909e0690571677d49f41bd8465ae876fe043d52ba5292" +checksum = "72db2f7947ecee9b03b510377e8bb9077afa27176fdbff55c51027e976fdcc48" dependencies = [ "jobserver", "libc", + "shlex", ] [[package]] @@ -868,9 +893,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.15" +version = "4.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11d8838454fda655dafd3accb2b6e2bea645b9e4078abe84a22ceb947235c5cc" +checksum = "ed6719fffa43d0d87e5fd8caeab59be1554fb028cd30edc88fc4369b17971019" dependencies = [ "clap_builder", "clap_derive", @@ -897,7 +922,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -908,9 +933,9 @@ checksum = "1462739cb27611015575c0c11df5df7601141071f07518d56fcc1be504cbec97" [[package]] name = "cmake" -version = "0.1.50" +version = "0.1.51" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31c789563b815f77f4250caee12365734369f942439b7defd71e18a48197130" +checksum = "fb1e43aa7fd152b1f968787f7dbcdeb306d1867ff373c69955211876c053f91a" dependencies = [ "cc", ] @@ -967,9 +992,9 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpufeatures" -version = "0.2.12" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504" +checksum = "51e852e6dc9a5bed1fae92dd2375037bf2b768725bf3be87811edee3249d09ad" dependencies = [ "libc", ] @@ -1124,7 +1149,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -1135,7 +1160,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -1172,7 +1197,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -1183,7 +1208,7 @@ checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -1331,13 +1356,13 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.31" +version = "1.0.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f211bbe8e69bbd0cfdea405084f128ae8b4aaa6b0b522fc8f2b009084797920" +checksum = "9c0596c1eac1f9e04ed902702e9878208b336edc9d6fddc8a48387349bab3666" dependencies = [ "crc32fast", "libz-sys", - "miniz_oxide", + "miniz_oxide 0.8.0", ] [[package]] @@ -1411,7 +1436,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -1423,7 +1448,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -1435,7 +1460,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -1534,7 +1559,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -1620,9 +1645,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa82e28a107a8cc405f0839610bdc9b15f1e25ec7d696aa5cf173edbcb1486ab" +checksum = "524e8ac6999421f49a846c2d4411f337e53497d8ec55d67753beffa43c5d9205" dependencies = [ "atomic-waker", "bytes", @@ -1630,7 +1655,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.3.0", + "indexmap 2.4.0", "slab", "tokio", "tokio-util", @@ -1835,7 +1860,7 @@ dependencies = [ "pin-project-lite", "socket2 0.5.7", "tokio", - "tower", + "tower 0.4.13", "tower-service", "tracing", ] @@ -1892,9 +1917,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de3fc2e30ba82dd1b3911c8de1ffc143c74a914a14e99514d7637e3099df5ea0" +checksum = "93ead53efc7ea8ed3cfb0c79fc8023fbb782a5432b52830b6518941cebe6505c" dependencies = [ "equivalent", "hashbrown 0.14.5", @@ -1944,11 +1969,11 @@ checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" [[package]] name = "is-terminal" -version = "0.4.12" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f23ff5ef2b80d608d61efee834934d862cd92461afc0560dedf493e4c033738b" +checksum = "261f68e344040fbd0edea105bef17c66edf46f984ddb1115b775ce31be948f4b" dependencies = [ - "hermit-abi 0.3.9", + "hermit-abi 0.4.0", "libc", "windows-sys 0.52.0", ] @@ -1977,6 +2002,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.11" @@ -1994,9 +2028,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.69" +version = "0.3.70" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" +checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a" dependencies = [ "wasm-bindgen", ] @@ -2024,9 +2058,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.155" +version = "0.2.158" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" +checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439" [[package]] name = "libloading" @@ -2057,9 +2091,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.18" +version = "1.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c15da26e5af7e25c90b37a2d75cdbf940cf4a55316de9d84c679c9b8bfabf82e" +checksum = "fdc53a7799a7496ebc9fd29f31f7df80e83c9bda5299768af5f9e59eeea74647" dependencies = [ "cc", "pkg-config", @@ -2151,6 +2185,15 @@ dependencies = [ "adler", ] +[[package]] +name = "miniz_oxide" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" +dependencies = [ + "adler2", +] + [[package]] name = "mio" version = "1.0.2" @@ -2192,7 +2235,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -2242,7 +2285,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", "termcolor", "thiserror", ] @@ -2255,7 +2298,7 @@ checksum = "478b0ff3f7d67b79da2b96f56f334431aef65e15ba4b29dd74a4236e29582bdc" dependencies = [ "base64 0.21.7", "bigdecimal", - "bindgen", + "bindgen 0.70.0", "bitflags 2.6.0", "bitvec", "btoi", @@ -2441,7 +2484,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -2523,7 +2566,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -2597,7 +2640,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -2736,7 +2779,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e" dependencies = [ "proc-macro2", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -2789,7 +2832,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", "version_check", "yansi", ] @@ -2977,9 +3020,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.5" +version = "0.12.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7d6d2a27d57148378eb5e111173f4276ad26340ecc5c49a4a2152167a2d6a37" +checksum = "f8f4955649ef5c38cc7f9e8aa41761d48fb9677197daea9984dc54f56aad5e63" dependencies = [ "base64 0.22.1", "bytes", @@ -3015,7 +3058,7 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "winreg", + "windows-registry", ] [[package]] @@ -3035,18 +3078,18 @@ dependencies = [ [[package]] name = "ringbuf" -version = "0.4.1" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c65e4c865bc3d2e3294493dff0acf7e6c259d066e34e22059fa9c39645c3636" +checksum = "46f7f1b88601a8ee13cabf203611ccdf64345dc1c5d24de8b11e1a678ee619b6" dependencies = [ "crossbeam-utils", ] [[package]] name = "rkyv" -version = "0.7.44" +version = "0.7.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cba464629b3394fc4dbc6f940ff8f5b4ff5c7aef40f29166fd4ad12acbc99c0" +checksum = "9008cd6385b9e161d8229e1f6549dd23c3d022f132a2ea37ac3a10ac4935779b" dependencies = [ "bitvec", "bytecheck", @@ -3062,9 +3105,9 @@ dependencies = [ [[package]] name = "rkyv_derive" -version = "0.7.44" +version = "0.7.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7dddfff8de25e6f62b9d64e6e432bf1c6736c57d20323e15ee10435fbda7c65" +checksum = "503d1d27590a2b0a3a4ca4c94755aa2875657196ecbf401a42eff41d7de532c0" dependencies = [ "proc-macro2", "quote", @@ -3097,7 +3140,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.74", + "syn 2.0.75", "unicode-ident", ] @@ -3117,9 +3160,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.35.0" +version = "1.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1790d1c4c0ca81211399e0e0af16333276f375209e71a37b67698a373db5b47a" +checksum = "b082d80e3e3cc52b2ed634388d436fe1f4de6af5786cc2de9ba9737527bdf555" dependencies = [ "arrayvec", "borsh", @@ -3309,9 +3352,9 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" -version = "1.0.206" +version = "1.0.208" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3e4cd94123dd520a128bcd11e34d9e9e423e7e3e50425cb1b4b1e3549d0284" +checksum = "cff085d2cb684faa248efb494c39b68e522822ac0de72ccf08109abde717cfb2" dependencies = [ "serde_derive", ] @@ -3337,13 +3380,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.206" +version = "1.0.208" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabfb6138d2383ea8208cf98ccf69cdfb1aff4088460681d84189aa259762f97" +checksum = "24008e81ff7613ed8e5ba0cfaf24e2c2f1e5b8a0495711e44fcd4882fca62bcf" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -3353,7 +3396,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8de514ef58196f1fc96dcaef80fe6170a1ce6215df9687a93fe8300e773fefc5" dependencies = [ "form_urlencoded", - "indexmap 2.3.0", + "indexmap 2.4.0", "itoa", "ryu", "serde", @@ -3361,11 +3404,11 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.124" +version = "1.0.125" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66ad62847a56b3dba58cc891acd13884b9c61138d330c0d7b6181713d4fce38d" +checksum = "83c8e735a073ccf5be70aa8066aa984eaf2fa000db6c8d0100ae605b366d31ed" dependencies = [ - "indexmap 2.3.0", + "indexmap 2.4.0", "itoa", "memchr", "ryu", @@ -3390,7 +3433,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -3424,7 +3467,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.3.0", + "indexmap 2.4.0", "serde", "serde_derive", "serde_json", @@ -3441,7 +3484,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -3584,9 +3627,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.74" +version = "2.0.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fceb41e3d546d0bd83421d3409b1460cc7444cd389341a4c880fe7a042cb3d7" +checksum = "f6af063034fc1935ede7be0122941bafa9bacb949334d090b77ca98b5817c7d9" dependencies = [ "proc-macro2", "quote", @@ -3602,7 +3645,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -3616,23 +3659,26 @@ name = "sync_wrapper" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" +dependencies = [ + "futures-core", +] [[package]] name = "system-configuration" -version = "0.5.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" +checksum = "658bc6ee10a9b4fcf576e9b0819d95ec16f4d2c02d39fd83ac1c8789785c4a42" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.6.0", "core-foundation", "system-configuration-sys", ] [[package]] name = "system-configuration-sys" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" dependencies = [ "core-foundation-sys", "libc", @@ -3706,7 +3752,7 @@ checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -3777,9 +3823,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.39.2" +version = "1.39.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daa4fb1bc778bd6f04cbfc4bb2d06a7396a8f299dc33ea1900cedaa316f467b1" +checksum = "9babc99b9923bfa4804bd74722ff02c0381021eafa4db9949217e3be8e84fff5" dependencies = [ "backtrace", "bytes", @@ -3800,7 +3846,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -3864,7 +3910,7 @@ version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8534fd7f78b5405e860340ad6575217ce99f38d4d5c8f2442cb5ecb50090e1" dependencies = [ - "indexmap 2.3.0", + "indexmap 2.4.0", "toml_datetime", "winnow 0.5.40", ] @@ -3875,7 +3921,7 @@ version = "0.22.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "583c44c02ad26b0c3f3066fe629275e50627026c51ac2e595cca4c230ce1ce1d" dependencies = [ - "indexmap 2.3.0", + "indexmap 2.4.0", "serde", "serde_spanned", "toml_datetime", @@ -3934,7 +3980,7 @@ dependencies = [ "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-tracker-torrent-repository", - "tower", + "tower 0.5.0", "tower-http", "trace", "tracing", @@ -4039,6 +4085,18 @@ dependencies = [ "tracing", ] +[[package]] +name = "tower" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36b837f86b25d7c0d7988f00a54e74739be6477f2aac6201b8f429a7569991b7" +dependencies = [ + "pin-project-lite", + "tokio", + "tower-layer", + "tower-service", +] + [[package]] name = "tower-http" version = "0.5.2" @@ -4063,15 +4121,15 @@ dependencies = [ [[package]] name = "tower-layer" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" [[package]] name = "tower-service" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "trace" @@ -4104,7 +4162,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -4299,34 +4357,35 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.92" +version = "0.2.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" +checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5" dependencies = [ "cfg-if", + "once_cell", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" -version = "0.2.92" +version = "0.2.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" +checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.42" +version = "0.4.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0" +checksum = "61e9300f63a621e96ed275155c108eb6f843b6a26d053f122ab69724559dc8ed" dependencies = [ "cfg-if", "js-sys", @@ -4336,9 +4395,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.92" +version = "0.2.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" +checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -4346,28 +4405,28 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.92" +version = "0.2.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" +checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.92" +version = "0.2.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" +checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484" [[package]] name = "web-sys" -version = "0.3.69" +version = "0.3.70" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" +checksum = "26fdeaafd9bd129f65e7c031593c24d62186301e0c72c8978fa1678be7d532c0" dependencies = [ "js-sys", "wasm-bindgen", @@ -4425,6 +4484,36 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-registry" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e400001bb720a623c1c69032f8e3e4cf09984deec740f007dd2b03ec864804b0" +dependencies = [ + "windows-result", + "windows-strings", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-result" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-strings" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +dependencies = [ + "windows-result", + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.48.0" @@ -4591,16 +4680,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "winreg" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5" -dependencies = [ - "cfg-if", - "windows-sys 0.48.0", -] - [[package]] name = "wyz" version = "0.5.1" @@ -4634,7 +4713,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] @@ -4654,7 +4733,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.74", + "syn 2.0.75", ] [[package]] From 95333f0d21896477a09cd5a35a6e923b3f3eb450 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 20 Aug 2024 11:44:26 +0100 Subject: [PATCH 0471/1297] chore(deps): update udp cookie consts due the hasher fn udpate The hasher function produces new hashes and that changes the final cookie used in the UDP tracker tests. It adds a function to generate new values and fix the test with the new values. --- src/servers/udp/connection_cookie.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs index c15ad114c..36bf98304 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/servers/udp/connection_cookie.rs @@ -178,15 +178,16 @@ mod tests { #[test] fn it_should_make_a_connection_cookie() { - // Note: This constant may need to be updated in the future as the hash is not guaranteed to to be stable between versions. - const ID_COOKIE_OLD: Cookie = [23, 204, 198, 29, 48, 180, 62, 19]; - const ID_COOKIE_NEW: Cookie = [41, 166, 45, 246, 249, 24, 108, 203]; + // Note: This constant may need to be updated in the future as the hash + // is not guaranteed to to be stable between versions. + const ID_COOKIE_OLD_HASHER: Cookie = [41, 166, 45, 246, 249, 24, 108, 203]; + const ID_COOKIE_NEW_HASHER: Cookie = [185, 122, 191, 238, 6, 43, 2, 198]; clock::Stopped::local_set_to_unix_epoch(); let cookie = make(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)); - assert!(cookie == ID_COOKIE_OLD || cookie == ID_COOKIE_NEW); + assert!(cookie == ID_COOKIE_OLD_HASHER || cookie == ID_COOKIE_NEW_HASHER); } #[test] From 7779fa3db8728a9c04ca84e6bffaeb115dceb7ec Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 13 Jul 2024 14:10:21 +0200 Subject: [PATCH 0472/1297] dev: remove announce_request wrapper --- src/servers/udp/handlers.rs | 11 ++++------- src/servers/udp/mod.rs | 4 ---- src/servers/udp/peer_builder.rs | 15 +++++++-------- src/servers/udp/request.rs | 28 ---------------------------- 4 files changed, 11 insertions(+), 47 deletions(-) delete mode 100644 src/servers/udp/request.rs diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 53683fbb9..e37179b4b 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -22,7 +22,6 @@ use crate::core::{statistics, ScrapeData, Tracker}; use crate::servers::udp::error::Error; use crate::servers::udp::logging::{log_bad_request, log_error_response, log_request, log_response}; use crate::servers::udp::peer_builder; -use crate::servers::udp::request::AnnounceWrapper; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; /// It handles the incoming UDP packets. @@ -152,9 +151,7 @@ pub async fn handle_announce( check(&remote_addr, &from_connection_id(&announce_request.connection_id))?; - let wrapped_announce_request = AnnounceWrapper::new(announce_request); - - let info_hash = wrapped_announce_request.info_hash; + let info_hash = InfoHash(announce_request.info_hash.0); let remote_client_ip = remote_addr.ip(); // Authorization @@ -162,7 +159,7 @@ pub async fn handle_announce( source: (Arc::new(e) as Arc).into(), })?; - let mut peer = peer_builder::from_request(&wrapped_announce_request, &remote_client_ip); + let mut peer = peer_builder::from_request(announce_request, &remote_client_ip); let response = tracker.announce(&info_hash, &mut peer, &remote_client_ip); @@ -179,7 +176,7 @@ pub async fn handle_announce( if remote_addr.is_ipv4() { let announce_response = AnnounceResponse { fixed: AnnounceResponseFixedData { - transaction_id: wrapped_announce_request.announce_request.transaction_id, + transaction_id: announce_request.transaction_id, announce_interval: AnnounceInterval(I32::new(i64::from(tracker.get_announce_policy().interval) as i32)), leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), @@ -206,7 +203,7 @@ pub async fn handle_announce( } else { let announce_response = AnnounceResponse { fixed: AnnounceResponseFixedData { - transaction_id: wrapped_announce_request.announce_request.transaction_id, + transaction_id: announce_request.transaction_id, announce_interval: AnnounceInterval(I32::new(i64::from(tracker.get_announce_policy().interval) as i32)), leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index 8ea05d5b1..91b19a91d 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -61,9 +61,6 @@ //! UDP packet -> Aquatic Struct Request -> [Torrust Struct Request] -> Tracker -> Aquatic Struct Response -> UDP packet //! ``` //! -//! For the `Announce` request there is a wrapper struct [`AnnounceWrapper`](crate::servers::udp::request::AnnounceWrapper). -//! It was added to add an extra field with the internal [`InfoHash`](torrust_tracker_primitives::info_hash::InfoHash) struct. -//! //! ### Connect //! //! `Connect` requests are used to get a connection ID which must be provided on @@ -646,7 +643,6 @@ pub mod error; pub mod handlers; pub mod logging; pub mod peer_builder; -pub mod request; pub mod server; pub const UDP_TRACKER_LOG_TARGET: &str = "UDP TRACKER"; diff --git a/src/servers/udp/peer_builder.rs b/src/servers/udp/peer_builder.rs index e54a23443..39881ad5c 100644 --- a/src/servers/udp/peer_builder.rs +++ b/src/servers/udp/peer_builder.rs @@ -5,7 +5,6 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::{peer, NumberOfBytes}; -use super::request::AnnounceWrapper; use crate::CurrentClock; /// Extracts the [`peer::Peer`] info from the @@ -16,8 +15,8 @@ use crate::CurrentClock; /// * `announce_wrapper` - The announce request to extract the peer info from. /// * `peer_ip` - The real IP address of the peer, not the one in the announce request. #[must_use] -pub fn from_request(announce_wrapper: &AnnounceWrapper, peer_ip: &IpAddr) -> peer::Peer { - let announce_event = match aquatic_udp_protocol::AnnounceEvent::from(announce_wrapper.announce_request.event) { +pub fn from_request(announce_request: &aquatic_udp_protocol::AnnounceRequest, peer_ip: &IpAddr) -> peer::Peer { + let announce_event = match aquatic_udp_protocol::AnnounceEvent::from(announce_request.event) { aquatic_udp_protocol::AnnounceEvent::Started => AnnounceEvent::Started, aquatic_udp_protocol::AnnounceEvent::Stopped => AnnounceEvent::Stopped, aquatic_udp_protocol::AnnounceEvent::Completed => AnnounceEvent::Completed, @@ -25,12 +24,12 @@ pub fn from_request(announce_wrapper: &AnnounceWrapper, peer_ip: &IpAddr) -> pee }; peer::Peer { - peer_id: peer::Id(announce_wrapper.announce_request.peer_id.0), - peer_addr: SocketAddr::new(*peer_ip, announce_wrapper.announce_request.port.0.into()), + peer_id: peer::Id(announce_request.peer_id.0), + peer_addr: SocketAddr::new(*peer_ip, announce_request.port.0.into()), updated: CurrentClock::now(), - uploaded: NumberOfBytes(announce_wrapper.announce_request.bytes_uploaded.0.into()), - downloaded: NumberOfBytes(announce_wrapper.announce_request.bytes_downloaded.0.into()), - left: NumberOfBytes(announce_wrapper.announce_request.bytes_left.0.into()), + uploaded: NumberOfBytes(announce_request.bytes_uploaded.0.into()), + downloaded: NumberOfBytes(announce_request.bytes_downloaded.0.into()), + left: NumberOfBytes(announce_request.bytes_left.0.into()), event: announce_event, } } diff --git a/src/servers/udp/request.rs b/src/servers/udp/request.rs deleted file mode 100644 index f95fec07a..000000000 --- a/src/servers/udp/request.rs +++ /dev/null @@ -1,28 +0,0 @@ -//! UDP request types. -//! -//! Torrust Tracker uses the [`aquatic_udp_protocol`](https://crates.io/crates/aquatic_udp_protocol) -//! crate to parse and serialize UDP requests. -//! -//! Some of the type in this module are wrappers around the types in the -//! `aquatic_udp_protocol` crate. -use aquatic_udp_protocol::AnnounceRequest; -use torrust_tracker_primitives::info_hash::InfoHash; - -/// Wrapper around [`AnnounceRequest`]. -pub struct AnnounceWrapper { - /// [`AnnounceRequest`] to wrap. - pub announce_request: AnnounceRequest, - /// Info hash of the torrent. - pub info_hash: InfoHash, -} - -impl AnnounceWrapper { - /// Creates a new [`AnnounceWrapper`] from an [`AnnounceRequest`]. - #[must_use] - pub fn new(announce_request: &AnnounceRequest) -> Self { - AnnounceWrapper { - announce_request: *announce_request, - info_hash: InfoHash(announce_request.info_hash.0), - } - } -} From 325df70a5f6e3d9874364eb019b1a5d8e254c448 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 13 Jul 2024 14:59:46 +0200 Subject: [PATCH 0473/1297] dev: use aquatic_udp_protocol InfoHash inside our type --- Cargo.lock | 2 + packages/primitives/Cargo.toml | 2 + packages/primitives/src/info_hash.rs | 64 +++++++++++++++---- .../benches/helpers/asyn.rs | 12 ++-- .../benches/helpers/sync.rs | 12 ++-- .../benches/helpers/utils.rs | 2 +- src/console/clients/checker/checks/udp.rs | 7 +- src/servers/http/v1/responses/scrape.rs | 4 +- src/servers/udp/handlers.rs | 6 +- 9 files changed, 75 insertions(+), 36 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a7589c287..cfe940e43 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4036,12 +4036,14 @@ dependencies = [ name = "torrust-tracker-primitives" version = "3.0.0-beta-develop" dependencies = [ + "aquatic_udp_protocol", "binascii", "derive_more", "serde", "tdyne-peer-id", "tdyne-peer-id-registry", "thiserror", + "zerocopy", ] [[package]] diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index 174750fbb..05981b3a8 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -15,9 +15,11 @@ rust-version.workspace = true version.workspace = true [dependencies] +aquatic_udp_protocol = "0" binascii = "0" derive_more = "0" serde = { version = "1", features = ["derive"] } tdyne-peer-id = "1" tdyne-peer-id-registry = "0" thiserror = "1" +zerocopy = "0" diff --git a/packages/primitives/src/info_hash.rs b/packages/primitives/src/info_hash.rs index a07cc41a2..57dfd90e5 100644 --- a/packages/primitives/src/info_hash.rs +++ b/packages/primitives/src/info_hash.rs @@ -1,11 +1,15 @@ use std::hash::{DefaultHasher, Hash, Hasher}; +use std::ops::{Deref, DerefMut}; use std::panic::Location; use thiserror::Error; +use zerocopy::FromBytes; /// `BitTorrent` Info Hash v1 -#[derive(PartialEq, Eq, Hash, Clone, Copy, Default, Debug)] -pub struct InfoHash(pub [u8; 20]); +#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] +pub struct InfoHash { + data: aquatic_udp_protocol::InfoHash, +} pub const INFO_HASH_BYTES_LEN: usize = 20; @@ -17,10 +21,9 @@ impl InfoHash { /// Will panic if byte slice does not contains the exact amount of bytes need for the `InfoHash`. #[must_use] pub fn from_bytes(bytes: &[u8]) -> Self { - assert_eq!(bytes.len(), INFO_HASH_BYTES_LEN); - let mut ret = Self([0u8; INFO_HASH_BYTES_LEN]); - ret.0.clone_from_slice(bytes); - ret + let data = aquatic_udp_protocol::InfoHash::read_from(bytes).expect("it should have the exact amount of bytes"); + + Self { data } } /// Returns the `InfoHash` internal byte array. @@ -36,6 +39,34 @@ impl InfoHash { } } +impl Default for InfoHash { + fn default() -> Self { + Self { + data: aquatic_udp_protocol::InfoHash(Default::default()), + } + } +} + +impl From for InfoHash { + fn from(data: aquatic_udp_protocol::InfoHash) -> Self { + Self { data } + } +} + +impl Deref for InfoHash { + type Target = aquatic_udp_protocol::InfoHash; + + fn deref(&self) -> &Self::Target { + &self.data + } +} + +impl DerefMut for InfoHash { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.data + } +} + impl Ord for InfoHash { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.cmp(&other.0) @@ -60,7 +91,7 @@ impl std::str::FromStr for InfoHash { type Err = binascii::ConvertError; fn from_str(s: &str) -> Result { - let mut i = Self([0u8; 20]); + let mut i = Self::default(); if s.len() != 40 { return Err(binascii::ConvertError::InvalidInputLength); } @@ -72,7 +103,7 @@ impl std::str::FromStr for InfoHash { impl std::convert::From<&[u8]> for InfoHash { fn from(data: &[u8]) -> InfoHash { assert_eq!(data.len(), 20); - let mut ret = InfoHash([0u8; 20]); + let mut ret = Self::default(); ret.0.clone_from_slice(data); ret } @@ -82,23 +113,28 @@ impl std::convert::From<&[u8]> for InfoHash { impl std::convert::From<&DefaultHasher> for InfoHash { fn from(data: &DefaultHasher) -> InfoHash { let n = data.finish().to_le_bytes(); - InfoHash([ + let bytes = [ n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[0], n[1], n[2], n[3], - ]) + ]; + let data = aquatic_udp_protocol::InfoHash(bytes); + Self { data } } } impl std::convert::From<&i32> for InfoHash { fn from(n: &i32) -> InfoHash { let n = n.to_le_bytes(); - InfoHash([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, n[0], n[1], n[2], n[3]]) + let bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, n[0], n[1], n[2], n[3]]; + let data = aquatic_udp_protocol::InfoHash(bytes); + Self { data } } } impl std::convert::From<[u8; 20]> for InfoHash { - fn from(val: [u8; 20]) -> Self { - InfoHash(val) + fn from(bytes: [u8; 20]) -> Self { + let data = aquatic_udp_protocol::InfoHash(bytes); + Self { data } } } @@ -171,7 +207,7 @@ impl<'v> serde::de::Visitor<'v> for InfoHashVisitor { )); } - let mut res = InfoHash([0u8; 20]); + let mut res = InfoHash::default(); if binascii::hex2bin(v.as_bytes(), &mut res.0).is_err() { return Err(serde::de::Error::invalid_value( diff --git a/packages/torrent-repository/benches/helpers/asyn.rs b/packages/torrent-repository/benches/helpers/asyn.rs index 1c6d9d915..08862abc8 100644 --- a/packages/torrent-repository/benches/helpers/asyn.rs +++ b/packages/torrent-repository/benches/helpers/asyn.rs @@ -16,7 +16,7 @@ where for _ in 0..samples { let torrent_repository = V::default(); - let info_hash = InfoHash([0; 20]); + let info_hash = InfoHash::default(); torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER).await; @@ -33,13 +33,13 @@ where Arc: Clone + Send + Sync + 'static, { let torrent_repository = Arc::::default(); - let info_hash: &'static InfoHash = &InfoHash([0; 20]); + let info_hash = InfoHash::default(); let handles = FuturesUnordered::new(); // Add the torrent/peer to the torrent repository - torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER).await; + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER).await; - torrent_repository.get_swarm_metadata(info_hash).await; + torrent_repository.get_swarm_metadata(&info_hash).await; let start = Instant::now(); @@ -47,9 +47,9 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(info_hash, &DEFAULT_PEER).await; + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER).await; - torrent_repository_clone.get_swarm_metadata(info_hash).await; + torrent_repository_clone.get_swarm_metadata(&info_hash).await; if let Some(sleep_time) = sleep { let start_time = std::time::Instant::now(); diff --git a/packages/torrent-repository/benches/helpers/sync.rs b/packages/torrent-repository/benches/helpers/sync.rs index 63fccfc77..77055911d 100644 --- a/packages/torrent-repository/benches/helpers/sync.rs +++ b/packages/torrent-repository/benches/helpers/sync.rs @@ -18,7 +18,7 @@ where for _ in 0..samples { let torrent_repository = V::default(); - let info_hash = InfoHash([0; 20]); + let info_hash = InfoHash::default(); torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER); @@ -35,13 +35,13 @@ where Arc: Clone + Send + Sync + 'static, { let torrent_repository = Arc::::default(); - let info_hash: &'static InfoHash = &InfoHash([0; 20]); + let info_hash = InfoHash::default(); let handles = FuturesUnordered::new(); // Add the torrent/peer to the torrent repository - torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER); + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER); - torrent_repository.get_swarm_metadata(info_hash); + torrent_repository.get_swarm_metadata(&info_hash); let start = Instant::now(); @@ -49,9 +49,9 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(info_hash, &DEFAULT_PEER); + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER); - torrent_repository_clone.get_swarm_metadata(info_hash); + torrent_repository_clone.get_swarm_metadata(&info_hash); if let Some(sleep_time) = sleep { let start_time = std::time::Instant::now(); diff --git a/packages/torrent-repository/benches/helpers/utils.rs b/packages/torrent-repository/benches/helpers/utils.rs index 170194806..2f912a5c0 100644 --- a/packages/torrent-repository/benches/helpers/utils.rs +++ b/packages/torrent-repository/benches/helpers/utils.rs @@ -30,7 +30,7 @@ pub fn generate_unique_info_hashes(size: usize) -> Vec { bytes[2] = ((i >> 16) & 0xFF) as u8; bytes[3] = ((i >> 24) & 0xFF) as u8; - let info_hash = InfoHash(bytes); + let info_hash = InfoHash::from_bytes(&bytes); result.insert(info_hash); } diff --git a/src/console/clients/checker/checks/udp.rs b/src/console/clients/checker/checks/udp.rs index dd4d5e639..dd9afa47c 100644 --- a/src/console/clients/checker/checks/udp.rs +++ b/src/console/clients/checker/checks/udp.rs @@ -4,7 +4,6 @@ use std::time::Duration; use aquatic_udp_protocol::TransactionId; use hex_literal::hex; use serde::Serialize; -use torrust_tracker_primitives::info_hash::InfoHash; use crate::console::clients::udp::checker::Client; use crate::console::clients::udp::Error; @@ -29,7 +28,7 @@ pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec, timeout: Duration) -> Vec, timeout: Duration) -> Vec ScrapeData { - let info_hash = InfoHash([0x69; 20]); + let info_hash = InfoHash::from_bytes(&[0x69; 20]); let mut scrape_data = ScrapeData::empty(); scrape_data.add_file( &info_hash, diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index e37179b4b..7eb07bc8d 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -151,7 +151,7 @@ pub async fn handle_announce( check(&remote_addr, &from_connection_id(&announce_request.connection_id))?; - let info_hash = InfoHash(announce_request.info_hash.0); + let info_hash = announce_request.info_hash.into(); let remote_client_ip = remote_addr.ip(); // Authorization @@ -240,9 +240,9 @@ pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tra debug!("udp scrape request: {:#?}", request); // Convert from aquatic infohashes - let mut info_hashes = vec![]; + let mut info_hashes: Vec = vec![]; for info_hash in &request.info_hashes { - info_hashes.push(InfoHash(info_hash.0)); + info_hashes.push((*info_hash).into()); } let scrape_data = if tracker.requires_authentication() { From 00af70f2558b861ca0bf59796f0c3f4b683819cd Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 14 Jul 2024 16:42:25 +0200 Subject: [PATCH 0474/1297] dev: remove announce event wrapper --- packages/primitives/src/announce_event.rs | 43 ------------------- packages/primitives/src/lib.rs | 25 ++++++++++- packages/primitives/src/peer.rs | 22 ++++++++-- .../benches/helpers/utils.rs | 3 +- .../torrent-repository/src/entry/single.rs | 3 +- .../tests/common/torrent_peer_builder.rs | 3 +- .../torrent-repository/tests/entry/mod.rs | 3 +- .../tests/repository/mod.rs | 3 +- src/core/mod.rs | 12 +++--- src/core/peer_tests.rs | 2 +- src/core/services/torrent.rs | 2 +- .../apis/v1/context/torrent/resources/peer.rs | 2 +- .../v1/context/torrent/resources/torrent.rs | 2 +- src/servers/http/v1/handlers/announce.rs | 2 +- src/servers/http/v1/services/announce.rs | 2 +- src/servers/http/v1/services/scrape.rs | 2 +- src/servers/udp/peer_builder.rs | 10 +---- 17 files changed, 61 insertions(+), 80 deletions(-) delete mode 100644 packages/primitives/src/announce_event.rs diff --git a/packages/primitives/src/announce_event.rs b/packages/primitives/src/announce_event.rs deleted file mode 100644 index 3bd560084..000000000 --- a/packages/primitives/src/announce_event.rs +++ /dev/null @@ -1,43 +0,0 @@ -//! Copyright (c) 2020-2023 Joakim Frostegård and The Torrust Developers -//! -//! Distributed under Apache 2.0 license - -use serde::{Deserialize, Serialize}; - -/// Announce events. Described on the -/// [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -#[derive(Hash, Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -pub enum AnnounceEvent { - /// The peer has started downloading the torrent. - Started, - /// The peer has ceased downloading the torrent. - Stopped, - /// The peer has completed downloading the torrent. - Completed, - /// This is one of the announcements done at regular intervals. - None, -} - -impl AnnounceEvent { - #[inline] - #[must_use] - pub fn from_i32(i: i32) -> Self { - match i { - 1 => Self::Completed, - 2 => Self::Started, - 3 => Self::Stopped, - _ => Self::None, - } - } - - #[inline] - #[must_use] - pub fn to_i32(&self) -> i32 { - match self { - AnnounceEvent::None => 0, - AnnounceEvent::Completed => 1, - AnnounceEvent::Started => 2, - AnnounceEvent::Stopped => 3, - } - } -} diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index d6f29c2b5..44666c9c3 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -7,10 +7,10 @@ use std::collections::BTreeMap; use std::time::Duration; +pub use aquatic_udp_protocol::{AnnounceEvent, AnnounceEventBytes}; use info_hash::InfoHash; use serde::{Deserialize, Serialize}; -pub mod announce_event; pub mod info_hash; pub mod pagination; pub mod peer; @@ -29,6 +29,29 @@ pub fn ser_unix_time_value(unix_time_value: &DurationSince ser.serialize_u64(unix_time_value.as_millis() as u64) } +#[derive(Serialize)] +pub enum AnnounceEventSer { + Started, + Stopped, + Completed, + None, +} + +/// Serializes a `DurationSinceUnixEpoch` as a Unix timestamp in milliseconds. +/// # Errors +/// +/// Will return `serde::Serializer::Error` if unable to serialize the `unix_time_value`. +pub fn ser_announce_event(announce_event: &AnnounceEvent, ser: S) -> Result { + let event_ser = match announce_event { + AnnounceEvent::Started => AnnounceEventSer::Started, + AnnounceEvent::Stopped => AnnounceEventSer::Stopped, + AnnounceEvent::Completed => AnnounceEventSer::Completed, + AnnounceEvent::None => AnnounceEventSer::None, + }; + + ser.serialize_some(&event_ser) +} + /// IP version used by the peer to connect to the tracker: IPv4 or IPv6 #[derive(PartialEq, Eq, Debug)] pub enum IPVersion { diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index ab7559508..369aa443a 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -24,10 +24,10 @@ use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; +use aquatic_udp_protocol::AnnounceEvent; use serde::Serialize; -use crate::announce_event::AnnounceEvent; -use crate::{ser_unix_time_value, DurationSinceUnixEpoch, IPVersion, NumberOfBytes}; +use crate::{ser_announce_event, ser_unix_time_value, DurationSinceUnixEpoch, IPVersion, NumberOfBytes}; /// Peer struct used by the core `Tracker`. /// @@ -51,7 +51,7 @@ use crate::{ser_unix_time_value, DurationSinceUnixEpoch, IPVersion, NumberOfByte /// event: AnnounceEvent::Started, /// }; /// ``` -#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq, Hash)] pub struct Peer { /// ID used by the downloader peer pub peer_id: Id, @@ -67,9 +67,22 @@ pub struct Peer { /// The number of bytes this peer still has to download pub left: NumberOfBytes, /// This is an optional key which maps to started, completed, or stopped (or empty, which is the same as not being present). + #[serde(serialize_with = "ser_announce_event")] pub event: AnnounceEvent, } +impl Ord for Peer { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.peer_id.cmp(&other.peer_id) + } +} + +impl PartialOrd for Peer { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.peer_id.cmp(&other.peer_id)) + } +} + pub trait ReadInfo { fn is_seeder(&self) -> bool; fn get_event(&self) -> AnnounceEvent; @@ -344,8 +357,9 @@ impl FromIterator for Vec

{ pub mod fixture { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use aquatic_udp_protocol::AnnounceEvent; + use super::{Id, Peer}; - use crate::announce_event::AnnounceEvent; use crate::{DurationSinceUnixEpoch, NumberOfBytes}; #[derive(PartialEq, Debug)] diff --git a/packages/torrent-repository/benches/helpers/utils.rs b/packages/torrent-repository/benches/helpers/utils.rs index 2f912a5c0..b904ef0e8 100644 --- a/packages/torrent-repository/benches/helpers/utils.rs +++ b/packages/torrent-repository/benches/helpers/utils.rs @@ -1,10 +1,9 @@ use std::collections::HashSet; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::{Id, Peer}; -use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfBytes}; +use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes}; pub const DEFAULT_PEER: Peer = Peer { peer_id: Id([0; 20]), diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs index 6d7ed3155..2d99fa9c5 100644 --- a/packages/torrent-repository/src/entry/single.rs +++ b/packages/torrent-repository/src/entry/single.rs @@ -2,10 +2,9 @@ use std::net::SocketAddr; use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::peer::{self}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::DurationSinceUnixEpoch; +use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch}; use super::Entry; use crate::EntrySingle; diff --git a/packages/torrent-repository/tests/common/torrent_peer_builder.rs b/packages/torrent-repository/tests/common/torrent_peer_builder.rs index 3a4e61ed2..dbdec826d 100644 --- a/packages/torrent-repository/tests/common/torrent_peer_builder.rs +++ b/packages/torrent-repository/tests/common/torrent_peer_builder.rs @@ -1,8 +1,7 @@ use std::net::SocketAddr; use torrust_tracker_clock::clock::Time; -use torrust_tracker_primitives::announce_event::AnnounceEvent; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; +use torrust_tracker_primitives::{peer, AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes}; use crate::CurrentClock; diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index 2a7063a4f..be7d5d715 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -6,9 +6,8 @@ use rstest::{fixture, rstest}; use torrust_tracker_clock::clock::stopped::Stopped as _; use torrust_tracker_clock::clock::{self, Time as _}; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; -use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_primitives::{peer, NumberOfBytes}; +use torrust_tracker_primitives::{peer, AnnounceEvent, NumberOfBytes}; use torrust_tracker_torrent_repository::{ EntryMutexParkingLot, EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle, }; diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index b3b742607..132684c13 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -3,11 +3,10 @@ use std::hash::{DefaultHasher, Hash, Hasher}; use rstest::{fixture, rstest}; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::{NumberOfBytes, PersistentTorrents}; +use torrust_tracker_primitives::{AnnounceEvent, NumberOfBytes, PersistentTorrents}; use torrust_tracker_torrent_repository::entry::Entry as _; use torrust_tracker_torrent_repository::repository::dash_map_mutex_std::XacrimonDashMap; use torrust_tracker_torrent_repository::repository::rw_lock_std::RwLockStd; diff --git a/src/core/mod.rs b/src/core/mod.rs index a6ee830db..49c781959 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -55,15 +55,15 @@ //! Once you have instantiated the `Tracker` you can `announce` a new [`peer::Peer`] with: //! //! ```rust,no_run -//! use torrust_tracker_primitives::peer; -//! use torrust_tracker_primitives::info_hash::InfoHash; -//! use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfBytes}; -//! use torrust_tracker_primitives::announce_event::AnnounceEvent; //! use std::net::SocketAddr; //! use std::net::IpAddr; //! use std::net::Ipv4Addr; //! use std::str::FromStr; //! +//! use aquatic_udp_protocol::AnnounceEvent; +//! use torrust_tracker_primitives::peer; +//! use torrust_tracker_primitives::info_hash::InfoHash; +//! use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfBytes}; //! //! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); //! @@ -1198,7 +1198,7 @@ mod tests { use std::str::FromStr; use std::sync::Arc; - use torrust_tracker_primitives::announce_event::AnnounceEvent; + use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; @@ -2035,7 +2035,7 @@ mod tests { mod handling_torrent_persistence { - use torrust_tracker_primitives::announce_event::AnnounceEvent; + use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; diff --git a/src/core/peer_tests.rs b/src/core/peer_tests.rs index d30d73db3..fa1396887 100644 --- a/src/core/peer_tests.rs +++ b/src/core/peer_tests.rs @@ -2,9 +2,9 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_clock::clock::stopped::Stopped as _; use torrust_tracker_clock::clock::{self, Time}; -use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::{peer, NumberOfBytes}; use crate::CurrentClock; diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 1c337a41d..fce9a2602 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -105,7 +105,7 @@ pub async fn get_torrents(tracker: Arc, info_hashes: &[InfoHash]) -> Ve mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use torrust_tracker_primitives::announce_event::AnnounceEvent; + use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; fn sample_peer() -> peer::Peer { diff --git a/src/servers/apis/v1/context/torrent/resources/peer.rs b/src/servers/apis/v1/context/torrent/resources/peer.rs index e7a0802c1..59637f2ee 100644 --- a/src/servers/apis/v1/context/torrent/resources/peer.rs +++ b/src/servers/apis/v1/context/torrent/resources/peer.rs @@ -22,7 +22,7 @@ pub struct Peer { /// The peer's left bytes (pending to download). pub left: i64, /// The peer's event: `started`, `stopped`, `completed`. - /// See [`AnnounceEvent`](torrust_tracker_primitives::announce_event::AnnounceEvent). + /// See [`AnnounceEvent`](aquatic_udp_protocol::AnnounceEvent). pub event: String, } diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs index 0d65b3eb6..d5ff957de 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs @@ -97,7 +97,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; - use torrust_tracker_primitives::announce_event::AnnounceEvent; + use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 0514a9f71..32143ce8e 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -9,10 +9,10 @@ use std::net::{IpAddr, SocketAddr}; use std::panic::Location; use std::sync::Arc; +use aquatic_udp_protocol::AnnounceEvent; use axum::extract::State; use axum::response::{IntoResponse, Response}; use torrust_tracker_clock::clock::Time; -use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::{peer, NumberOfBytes}; use tracing::debug; diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index f5f730ae2..e8699a6eb 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -48,7 +48,7 @@ pub async fn invoke(tracker: Arc, info_hash: InfoHash, peer: &mut peer: mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use torrust_tracker_primitives::announce_event::AnnounceEvent; + use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index b83abb321..e49c37ba6 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -61,7 +61,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use torrust_tracker_primitives::announce_event::AnnounceEvent; + use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; use torrust_tracker_test_helpers::configuration; diff --git a/src/servers/udp/peer_builder.rs b/src/servers/udp/peer_builder.rs index 39881ad5c..a6bb3f7c3 100644 --- a/src/servers/udp/peer_builder.rs +++ b/src/servers/udp/peer_builder.rs @@ -2,7 +2,6 @@ use std::net::{IpAddr, SocketAddr}; use torrust_tracker_clock::clock::Time; -use torrust_tracker_primitives::announce_event::AnnounceEvent; use torrust_tracker_primitives::{peer, NumberOfBytes}; use crate::CurrentClock; @@ -16,13 +15,6 @@ use crate::CurrentClock; /// * `peer_ip` - The real IP address of the peer, not the one in the announce request. #[must_use] pub fn from_request(announce_request: &aquatic_udp_protocol::AnnounceRequest, peer_ip: &IpAddr) -> peer::Peer { - let announce_event = match aquatic_udp_protocol::AnnounceEvent::from(announce_request.event) { - aquatic_udp_protocol::AnnounceEvent::Started => AnnounceEvent::Started, - aquatic_udp_protocol::AnnounceEvent::Stopped => AnnounceEvent::Stopped, - aquatic_udp_protocol::AnnounceEvent::Completed => AnnounceEvent::Completed, - aquatic_udp_protocol::AnnounceEvent::None => AnnounceEvent::None, - }; - peer::Peer { peer_id: peer::Id(announce_request.peer_id.0), peer_addr: SocketAddr::new(*peer_ip, announce_request.port.0.into()), @@ -30,6 +22,6 @@ pub fn from_request(announce_request: &aquatic_udp_protocol::AnnounceRequest, pe uploaded: NumberOfBytes(announce_request.bytes_uploaded.0.into()), downloaded: NumberOfBytes(announce_request.bytes_downloaded.0.into()), left: NumberOfBytes(announce_request.bytes_left.0.into()), - event: announce_event, + event: announce_request.event.into(), } } From 03e88d0ffe9277f6328dcb5625a624940f1e91d0 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 14 Jul 2024 17:13:03 +0200 Subject: [PATCH 0475/1297] dev: use aquatic number_of_bytes --- Cargo.lock | 2 + packages/primitives/src/lib.rs | 22 +++++--- packages/primitives/src/peer.rs | 51 ++++++++++--------- packages/torrent-repository/Cargo.toml | 2 + .../benches/helpers/utils.rs | 10 ++-- .../torrent-repository/src/entry/single.rs | 3 +- .../tests/common/torrent_peer_builder.rs | 5 +- .../torrent-repository/tests/entry/mod.rs | 15 +++--- .../tests/repository/mod.rs | 7 +-- src/core/mod.rs | 38 +++++++------- src/core/peer_tests.rs | 10 ++-- src/core/services/torrent.rs | 10 ++-- .../apis/v1/context/torrent/resources/peer.rs | 6 +-- .../v1/context/torrent/resources/torrent.rs | 10 ++-- .../http/v1/extractors/announce_request.rs | 7 +-- src/servers/http/v1/handlers/announce.rs | 10 ++-- src/servers/http/v1/requests/announce.rs | 30 ++++++----- src/servers/http/v1/requests/scrape.rs | 2 - src/servers/http/v1/services/announce.rs | 10 ++-- src/servers/http/v1/services/scrape.rs | 10 ++-- src/servers/udp/handlers.rs | 5 +- src/servers/udp/peer_builder.rs | 9 ++-- 22 files changed, 147 insertions(+), 127 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cfe940e43..504a5bb17 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4058,6 +4058,7 @@ dependencies = [ name = "torrust-tracker-torrent-repository" version = "3.0.0-beta-develop" dependencies = [ + "aquatic_udp_protocol", "async-std", "criterion", "crossbeam-skiplist", @@ -4069,6 +4070,7 @@ dependencies = [ "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-primitives", + "zerocopy", ] [[package]] diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index 44666c9c3..b383e95ad 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -7,9 +7,9 @@ use std::collections::BTreeMap; use std::time::Duration; -pub use aquatic_udp_protocol::{AnnounceEvent, AnnounceEventBytes}; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use info_hash::InfoHash; -use serde::{Deserialize, Serialize}; +use serde::Serialize; pub mod info_hash; pub mod pagination; @@ -37,10 +37,11 @@ pub enum AnnounceEventSer { None, } -/// Serializes a `DurationSinceUnixEpoch` as a Unix timestamp in milliseconds. +/// Serializes a `Announce Event` as a enum. +/// /// # Errors /// -/// Will return `serde::Serializer::Error` if unable to serialize the `unix_time_value`. +/// If will return an error if the internal serializer was to fail. pub fn ser_announce_event(announce_event: &AnnounceEvent, ser: S) -> Result { let event_ser = match announce_event { AnnounceEvent::Started => AnnounceEventSer::Started, @@ -52,6 +53,15 @@ pub fn ser_announce_event(announce_event: &AnnounceEvent, ser.serialize_some(&event_ser) } +/// Serializes a `Announce Event` as a i64. +/// +/// # Errors +/// +/// If will return an error if the internal serializer was to fail. +pub fn ser_number_of_bytes(number_of_bytes: &NumberOfBytes, ser: S) -> Result { + ser.serialize_i64(number_of_bytes.0.get()) +} + /// IP version used by the peer to connect to the tracker: IPv4 or IPv6 #[derive(PartialEq, Eq, Debug)] pub enum IPVersion { @@ -61,8 +71,4 @@ pub enum IPVersion { IPv6, } -/// Number of bytes downloaded, uploaded or pending to download (left) by the peer. -#[derive(Hash, Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -pub struct NumberOfBytes(pub i64); - pub type PersistentTorrents = BTreeMap; diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index 369aa443a..987099b70 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -14,9 +14,9 @@ //! peer_id: peer::Id(*b"-qB00000000000000000"), //! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), //! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), -//! uploaded: NumberOfBytes(0), -//! downloaded: NumberOfBytes(0), -//! left: NumberOfBytes(0), +//! uploaded: NumberOfBytes::new(0), +//! downloaded: NumberOfBytes::new(0), +//! left: NumberOfBytes::new(0), //! event: AnnounceEvent::Started, //! }; //! ``` @@ -24,10 +24,10 @@ use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; -use aquatic_udp_protocol::AnnounceEvent; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use serde::Serialize; -use crate::{ser_announce_event, ser_unix_time_value, DurationSinceUnixEpoch, IPVersion, NumberOfBytes}; +use crate::{ser_announce_event, ser_number_of_bytes, ser_unix_time_value, DurationSinceUnixEpoch, IPVersion}; /// Peer struct used by the core `Tracker`. /// @@ -45,9 +45,9 @@ use crate::{ser_announce_event, ser_unix_time_value, DurationSinceUnixEpoch, IPV /// peer_id: peer::Id(*b"-qB00000000000000000"), /// peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), /// updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), -/// uploaded: NumberOfBytes(0), -/// downloaded: NumberOfBytes(0), -/// left: NumberOfBytes(0), +/// uploaded: NumberOfBytes::new(0), +/// downloaded: NumberOfBytes::new(0), +/// left: NumberOfBytes::new(0), /// event: AnnounceEvent::Started, /// }; /// ``` @@ -61,10 +61,13 @@ pub struct Peer { #[serde(serialize_with = "ser_unix_time_value")] pub updated: DurationSinceUnixEpoch, /// The total amount of bytes uploaded by this peer so far + #[serde(serialize_with = "ser_number_of_bytes")] pub uploaded: NumberOfBytes, /// The total amount of bytes downloaded by this peer so far + #[serde(serialize_with = "ser_number_of_bytes")] pub downloaded: NumberOfBytes, /// The number of bytes this peer still has to download + #[serde(serialize_with = "ser_number_of_bytes")] pub left: NumberOfBytes, /// This is an optional key which maps to started, completed, or stopped (or empty, which is the same as not being present). #[serde(serialize_with = "ser_announce_event")] @@ -93,7 +96,7 @@ pub trait ReadInfo { impl ReadInfo for Peer { fn is_seeder(&self) -> bool { - self.left.0 <= 0 && self.event != AnnounceEvent::Stopped + self.left.0.get() <= 0 && self.event != AnnounceEvent::Stopped } fn get_event(&self) -> AnnounceEvent { @@ -115,7 +118,7 @@ impl ReadInfo for Peer { impl ReadInfo for Arc { fn is_seeder(&self) -> bool { - self.left.0 <= 0 && self.event != AnnounceEvent::Stopped + self.left.0.get() <= 0 && self.event != AnnounceEvent::Stopped } fn get_event(&self) -> AnnounceEvent { @@ -138,7 +141,7 @@ impl ReadInfo for Arc { impl Peer { #[must_use] pub fn is_seeder(&self) -> bool { - self.left.0 <= 0 && self.event != AnnounceEvent::Stopped + self.left.0.get() <= 0 && self.event != AnnounceEvent::Stopped } pub fn ip(&mut self) -> IpAddr { @@ -357,10 +360,10 @@ impl FromIterator for Vec

{ pub mod fixture { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use aquatic_udp_protocol::AnnounceEvent; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use super::{Id, Peer}; - use crate::{DurationSinceUnixEpoch, NumberOfBytes}; + use crate::DurationSinceUnixEpoch; #[derive(PartialEq, Debug)] @@ -383,9 +386,9 @@ pub mod fixture { peer_id: Id(*b"-qB00000000000000001"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), event: AnnounceEvent::Completed, }; @@ -399,9 +402,9 @@ pub mod fixture { peer_id: Id(*b"-qB00000000000000002"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(10), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(10), event: AnnounceEvent::Started, }; @@ -425,14 +428,14 @@ pub mod fixture { #[allow(dead_code)] #[must_use] pub fn with_bytes_pending_to_download(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes(left); + self.peer.left = NumberOfBytes::new(left); self } #[allow(dead_code)] #[must_use] pub fn with_no_bytes_pending_to_download(mut self) -> Self { - self.peer.left = NumberOfBytes(0); + self.peer.left = NumberOfBytes::new(0); self } @@ -462,9 +465,9 @@ pub mod fixture { peer_id: Id::default(), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), event: AnnounceEvent::Started, } } diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 1fd58ab02..38405e4e0 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -16,6 +16,7 @@ rust-version.workspace = true version.workspace = true [dependencies] +aquatic_udp_protocol = "0" crossbeam-skiplist = "0" dashmap = "6" futures = "0" @@ -24,6 +25,7 @@ tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal torrust-tracker-clock = { version = "3.0.0-beta-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-beta-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-beta-develop", path = "../primitives" } +zerocopy = "0" [dev-dependencies] async-std = { version = "1", features = ["attributes", "tokio1"] } diff --git a/packages/torrent-repository/benches/helpers/utils.rs b/packages/torrent-repository/benches/helpers/utils.rs index b904ef0e8..f7a392bd8 100644 --- a/packages/torrent-repository/benches/helpers/utils.rs +++ b/packages/torrent-repository/benches/helpers/utils.rs @@ -1,17 +1,19 @@ use std::collections::HashSet; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::{Id, Peer}; -use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use zerocopy::I64; pub const DEFAULT_PEER: Peer = Peer { peer_id: Id([0; 20]), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::from_secs(0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), + uploaded: NumberOfBytes(I64::ZERO), + downloaded: NumberOfBytes(I64::ZERO), + left: NumberOfBytes(I64::ZERO), event: AnnounceEvent::Started, }; diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs index 2d99fa9c5..7f8cfc4e6 100644 --- a/packages/torrent-repository/src/entry/single.rs +++ b/packages/torrent-repository/src/entry/single.rs @@ -1,10 +1,11 @@ use std::net::SocketAddr; use std::sync::Arc; +use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::peer::{self}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::Entry; use crate::EntrySingle; diff --git a/packages/torrent-repository/tests/common/torrent_peer_builder.rs b/packages/torrent-repository/tests/common/torrent_peer_builder.rs index dbdec826d..a5d2814c1 100644 --- a/packages/torrent-repository/tests/common/torrent_peer_builder.rs +++ b/packages/torrent-repository/tests/common/torrent_peer_builder.rs @@ -1,7 +1,8 @@ use std::net::SocketAddr; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_clock::clock::Time; -use torrust_tracker_primitives::{peer, AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use crate::CurrentClock; @@ -48,7 +49,7 @@ impl TorrentPeerBuilder { #[must_use] fn with_number_of_bytes_left(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes(left); + self.peer.left = NumberOfBytes::new(left); self } diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index be7d5d715..223819a14 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -2,12 +2,13 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::ops::Sub; use std::time::Duration; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use rstest::{fixture, rstest}; use torrust_tracker_clock::clock::stopped::Stopped as _; use torrust_tracker_clock::clock::{self, Time as _}; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; +use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_primitives::{peer, AnnounceEvent, NumberOfBytes}; use torrust_tracker_torrent_repository::{ EntryMutexParkingLot, EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle, }; @@ -85,7 +86,7 @@ async fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { let mut peer = a_started_peer(3); torrent.upsert_peer(&peer).await; peer.event = AnnounceEvent::Completed; - peer.left = NumberOfBytes(0); + peer.left = NumberOfBytes::new(0); torrent.upsert_peer(&peer).await; vec![peer] } @@ -99,7 +100,7 @@ async fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { let mut peer_3 = a_started_peer(3); torrent.upsert_peer(&peer_3).await; peer_3.event = AnnounceEvent::Completed; - peer_3.left = NumberOfBytes(0); + peer_3.left = NumberOfBytes::new(0); torrent.upsert_peer(&peer_3).await; vec![peer_1, peer_2, peer_3] } @@ -304,10 +305,10 @@ async fn it_should_update_a_peer_as_a_seeder( let peers = torrent.get_peers(None).await; let mut peer = **peers.first().expect("there should be a peer"); - let is_already_non_left = peer.left == NumberOfBytes(0); + let is_already_non_left = peer.left == NumberOfBytes::new(0); // Set Bytes Left to Zero - peer.left = NumberOfBytes(0); + peer.left = NumberOfBytes::new(0); torrent.upsert_peer(&peer).await; let stats = torrent.get_stats().await; @@ -336,10 +337,10 @@ async fn it_should_update_a_peer_as_incomplete( let peers = torrent.get_peers(None).await; let mut peer = **peers.first().expect("there should be a peer"); - let completed_already = peer.left == NumberOfBytes(0); + let completed_already = peer.left == NumberOfBytes::new(0); // Set Bytes Left to no Zero - peer.left = NumberOfBytes(1); + peer.left = NumberOfBytes::new(1); torrent.upsert_peer(&peer).await; let stats = torrent.get_stats().await; diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 132684c13..05d538582 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -1,12 +1,13 @@ use std::collections::{BTreeMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use rstest::{fixture, rstest}; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::{AnnounceEvent, NumberOfBytes, PersistentTorrents}; +use torrust_tracker_primitives::PersistentTorrents; use torrust_tracker_torrent_repository::entry::Entry as _; use torrust_tracker_torrent_repository::repository::dash_map_mutex_std::XacrimonDashMap; use torrust_tracker_torrent_repository::repository::rw_lock_std::RwLockStd; @@ -99,7 +100,7 @@ fn downloaded() -> Entries { let mut peer = a_started_peer(3); torrent.upsert_peer(&peer); peer.event = AnnounceEvent::Completed; - peer.left = NumberOfBytes(0); + peer.left = NumberOfBytes::new(0); torrent.upsert_peer(&peer); vec![(InfoHash::default(), torrent)] } @@ -121,7 +122,7 @@ fn three() -> Entries { let mut downloaded_peer = a_started_peer(3); downloaded.upsert_peer(&downloaded_peer); downloaded_peer.event = AnnounceEvent::Completed; - downloaded_peer.left = NumberOfBytes(0); + downloaded_peer.left = NumberOfBytes::new(0); downloaded.upsert_peer(&downloaded_peer); downloaded.hash(downloaded_h); diff --git a/src/core/mod.rs b/src/core/mod.rs index 49c781959..7c10c0aae 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -60,10 +60,10 @@ //! use std::net::Ipv4Addr; //! use std::str::FromStr; //! -//! use aquatic_udp_protocol::AnnounceEvent; +//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; //! use torrust_tracker_primitives::peer; //! use torrust_tracker_primitives::info_hash::InfoHash; -//! use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfBytes}; +//! use torrust_tracker_primitives::{DurationSinceUnixEpoch}; //! //! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); //! @@ -71,9 +71,9 @@ //! peer_id: peer::Id(*b"-qB00000000000000001"), //! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), //! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), -//! uploaded: NumberOfBytes(0), -//! downloaded: NumberOfBytes(0), -//! left: NumberOfBytes(0), +//! uploaded: NumberOfBytes::new(0), +//! downloaded: NumberOfBytes::new(0), +//! left: NumberOfBytes::new(0), //! event: AnnounceEvent::Completed, //! }; //! @@ -1198,9 +1198,9 @@ mod tests { use std::str::FromStr; use std::sync::Arc; - use aquatic_udp_protocol::AnnounceEvent; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfBytes}; + use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; use crate::core::peer::{self, Peer}; @@ -1246,9 +1246,9 @@ mod tests { peer_id: peer::Id(*b"-qB00000000000000001"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), event: AnnounceEvent::Completed, } } @@ -1259,9 +1259,9 @@ mod tests { peer_id: peer::Id(*b"-qB00000000000000002"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8082), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), event: AnnounceEvent::Completed, } } @@ -1290,9 +1290,9 @@ mod tests { peer_id: peer::Id(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), // No bytes left to download + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download event: AnnounceEvent::Completed, } } @@ -1303,9 +1303,9 @@ mod tests { peer_id: peer::Id(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(1000), // Still bytes to download + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(1000), // Still bytes to download event: AnnounceEvent::Started, } } diff --git a/src/core/peer_tests.rs b/src/core/peer_tests.rs index fa1396887..f0773faf0 100644 --- a/src/core/peer_tests.rs +++ b/src/core/peer_tests.rs @@ -2,10 +2,10 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use aquatic_udp_protocol::AnnounceEvent; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_clock::clock::stopped::Stopped as _; use torrust_tracker_clock::clock::{self, Time}; -use torrust_tracker_primitives::{peer, NumberOfBytes}; +use torrust_tracker_primitives::peer; use crate::CurrentClock; @@ -17,9 +17,9 @@ fn it_should_be_serializable() { peer_id: peer::Id(*b"-qB0000-000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: CurrentClock::now(), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), event: AnnounceEvent::Started, }; diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index fce9a2602..9cb38e3f1 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -105,17 +105,17 @@ pub async fn get_torrents(tracker: Arc, info_hashes: &[InfoHash]) -> Ve mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use aquatic_udp_protocol::AnnounceEvent; - use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; fn sample_peer() -> peer::Peer { peer::Peer { peer_id: peer::Id(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), event: AnnounceEvent::Started, } } diff --git a/src/servers/apis/v1/context/torrent/resources/peer.rs b/src/servers/apis/v1/context/torrent/resources/peer.rs index 59637f2ee..129318ce1 100644 --- a/src/servers/apis/v1/context/torrent/resources/peer.rs +++ b/src/servers/apis/v1/context/torrent/resources/peer.rs @@ -52,9 +52,9 @@ impl From for Peer { peer_addr: value.peer_addr.to_string(), updated: value.updated.as_millis(), updated_milliseconds_ago: value.updated.as_millis(), - uploaded: value.uploaded.0, - downloaded: value.downloaded.0, - left: value.left.0, + uploaded: value.uploaded.0.get(), + downloaded: value.downloaded.0.get(), + left: value.left.0.get(), event: format!("{:?}", value.event), } } diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs index d5ff957de..772a37f98 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs @@ -97,9 +97,9 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; - use aquatic_udp_protocol::AnnounceEvent; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use super::Torrent; use crate::core::services::torrent::{BasicInfo, Info}; @@ -111,9 +111,9 @@ mod tests { peer_id: peer::Id(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), event: AnnounceEvent::Started, } } diff --git a/src/servers/http/v1/extractors/announce_request.rs b/src/servers/http/v1/extractors/announce_request.rs index d2612f79b..6867461e0 100644 --- a/src/servers/http/v1/extractors/announce_request.rs +++ b/src/servers/http/v1/extractors/announce_request.rs @@ -95,6 +95,7 @@ fn extract_announce_from(maybe_raw_query: Option<&str>) -> Result peer::Pee peer_id: announce_request.peer_id, peer_addr: SocketAddr::new(*peer_ip, announce_request.port), updated: CurrentClock::now(), - uploaded: NumberOfBytes(announce_request.uploaded.unwrap_or(0)), - downloaded: NumberOfBytes(announce_request.downloaded.unwrap_or(0)), - left: NumberOfBytes(announce_request.left.unwrap_or(0)), + uploaded: announce_request.uploaded.unwrap_or(NumberOfBytes::new(0)), + downloaded: announce_request.downloaded.unwrap_or(NumberOfBytes::new(0)), + left: announce_request.left.unwrap_or(NumberOfBytes::new(0)), event: map_to_torrust_event(&announce_request.event), } } diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index 83cc7ddf9..6efee18b3 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -5,6 +5,7 @@ use std::fmt; use std::panic::Location; use std::str::FromStr; +use aquatic_udp_protocol::NumberOfBytes; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; use torrust_tracker_primitives::info_hash::{self, InfoHash}; @@ -14,10 +15,6 @@ use crate::servers::http::percent_encoding::{percent_decode_info_hash, percent_d use crate::servers::http::v1::query::{ParseQueryError, Query}; use crate::servers::http::v1::responses; -/// The number of bytes `downloaded`, `uploaded` or `left`. It's used in the -/// `Announce` request for parameters that represent a number of bytes. -pub type NumberOfBytes = i64; - // Query param names const INFO_HASH: &str = "info_hash"; const PEER_ID: &str = "peer_id"; @@ -32,6 +29,7 @@ const COMPACT: &str = "compact"; /// query params of the request. /// /// ```rust +/// use aquatic_udp_protocol::NumberOfBytes; /// use torrust_tracker::servers::http::v1::requests::announce::{Announce, Compact, Event}; /// use torrust_tracker_primitives::info_hash::InfoHash; /// use torrust_tracker_primitives::peer; @@ -42,9 +40,9 @@ const COMPACT: &str = "compact"; /// peer_id: "-qB00000000000000001".parse::().unwrap(), /// port: 17548, /// // Optional params -/// downloaded: Some(1), -/// uploaded: Some(2), -/// left: Some(3), +/// downloaded: Some(NumberOfBytes::new(1)), +/// uploaded: Some(NumberOfBytes::new(2)), +/// left: Some(NumberOfBytes::new(3)), /// event: Some(Event::Started), /// compact: Some(Compact::NotAccepted) /// }; @@ -324,13 +322,16 @@ fn extract_number_of_bytes_from_param(param_name: &str, query: &Query) -> Result location: Location::caller(), })?; - Ok(Some(i64::try_from(number_of_bytes).map_err(|_e| { - ParseAnnounceQueryError::NumberOfBytesOverflow { + let number_of_bytes = + i64::try_from(number_of_bytes).map_err(|_e| ParseAnnounceQueryError::NumberOfBytesOverflow { param_name: param_name.to_owned(), param_value: raw_param.clone(), location: Location::caller(), - } - })?)) + })?; + + let number_of_bytes = NumberOfBytes::new(number_of_bytes); + + Ok(Some(number_of_bytes)) } None => Ok(None), } @@ -355,6 +356,7 @@ mod tests { mod announce_request { + use aquatic_udp_protocol::NumberOfBytes; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer; @@ -415,9 +417,9 @@ mod tests { info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), peer_id: "-qB00000000000000001".parse::().unwrap(), port: 17548, - downloaded: Some(1), - uploaded: Some(2), - left: Some(3), + downloaded: Some(NumberOfBytes::new(1)), + uploaded: Some(NumberOfBytes::new(2)), + left: Some(NumberOfBytes::new(3)), event: Some(Event::Started), compact: Some(Compact::NotAccepted), } diff --git a/src/servers/http/v1/requests/scrape.rs b/src/servers/http/v1/requests/scrape.rs index 19f6e35a6..c61d3be1f 100644 --- a/src/servers/http/v1/requests/scrape.rs +++ b/src/servers/http/v1/requests/scrape.rs @@ -11,8 +11,6 @@ use crate::servers::http::percent_encoding::percent_decode_info_hash; use crate::servers::http::v1::query::Query; use crate::servers::http::v1::responses; -pub type NumberOfBytes = i64; - // Query param names const INFO_HASH: &str = "info_hash"; diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index e8699a6eb..a85a4d4bf 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -48,9 +48,9 @@ pub async fn invoke(tracker: Arc, info_hash: InfoHash, peer: &mut peer: mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use aquatic_udp_protocol::AnnounceEvent; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; @@ -82,9 +82,9 @@ mod tests { peer_id: peer::Id(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), event: AnnounceEvent::Started, } } diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index e49c37ba6..bd3f323b4 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -61,9 +61,9 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use aquatic_udp_protocol::AnnounceEvent; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use torrust_tracker_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfBytes}; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; @@ -86,9 +86,9 @@ mod tests { peer_id: peer::Id(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes(0), - downloaded: NumberOfBytes(0), - left: NumberOfBytes(0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), event: AnnounceEvent::Started, } } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 7eb07bc8d..c7204b4b9 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -318,9 +318,10 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; + use aquatic_udp_protocol::NumberOfBytes; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Configuration; - use torrust_tracker_primitives::{peer, NumberOfBytes}; + use torrust_tracker_primitives::peer; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; @@ -397,7 +398,7 @@ mod tests { #[must_use] pub fn with_number_of_bytes_left(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes(left); + self.peer.left = NumberOfBytes::new(left); self } diff --git a/src/servers/udp/peer_builder.rs b/src/servers/udp/peer_builder.rs index a6bb3f7c3..1824b2826 100644 --- a/src/servers/udp/peer_builder.rs +++ b/src/servers/udp/peer_builder.rs @@ -2,7 +2,7 @@ use std::net::{IpAddr, SocketAddr}; use torrust_tracker_clock::clock::Time; -use torrust_tracker_primitives::{peer, NumberOfBytes}; +use torrust_tracker_primitives::peer; use crate::CurrentClock; @@ -11,7 +11,6 @@ use crate::CurrentClock; /// /// # Arguments /// -/// * `announce_wrapper` - The announce request to extract the peer info from. /// * `peer_ip` - The real IP address of the peer, not the one in the announce request. #[must_use] pub fn from_request(announce_request: &aquatic_udp_protocol::AnnounceRequest, peer_ip: &IpAddr) -> peer::Peer { @@ -19,9 +18,9 @@ pub fn from_request(announce_request: &aquatic_udp_protocol::AnnounceRequest, pe peer_id: peer::Id(announce_request.peer_id.0), peer_addr: SocketAddr::new(*peer_ip, announce_request.port.0.into()), updated: CurrentClock::now(), - uploaded: NumberOfBytes(announce_request.bytes_uploaded.0.into()), - downloaded: NumberOfBytes(announce_request.bytes_downloaded.0.into()), - left: NumberOfBytes(announce_request.bytes_left.0.into()), + uploaded: announce_request.bytes_uploaded, + downloaded: announce_request.bytes_downloaded, + left: announce_request.bytes_left, event: announce_request.event.into(), } } From 9362fa57817122292ba25202c85d6869329096df Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 15 Jul 2024 10:09:24 +0200 Subject: [PATCH 0476/1297] dev: use aquatic PeerId instead of local one --- .../flamegraph_generated_without_sudo.svg | 2 +- packages/primitives/src/lib.rs | 44 --- packages/primitives/src/peer.rs | 278 ++++++++---------- .../benches/helpers/utils.rs | 6 +- .../torrent-repository/src/entry/peer_list.rs | 21 +- .../tests/common/torrent_peer_builder.rs | 10 +- .../torrent-repository/tests/entry/mod.rs | 2 +- src/core/mod.rs | 23 +- src/core/peer_tests.rs | 4 +- src/core/services/torrent.rs | 4 +- .../apis/v1/context/torrent/resources/peer.rs | 6 +- .../v1/context/torrent/resources/torrent.rs | 4 +- src/servers/http/percent_encoding.rs | 18 +- .../http/v1/extractors/announce_request.rs | 5 +- src/servers/http/v1/handlers/announce.rs | 4 +- src/servers/http/v1/requests/announce.rs | 24 +- src/servers/http/v1/responses/announce.rs | 8 +- src/servers/http/v1/services/announce.rs | 4 +- src/servers/http/v1/services/scrape.rs | 4 +- src/servers/udp/handlers.rs | 24 +- src/servers/udp/peer_builder.rs | 2 +- .../tracker/http/client/requests/announce.rs | 6 +- .../tracker/http/client/responses/announce.rs | 3 +- tests/servers/http/requests/announce.rs | 6 +- tests/servers/http/responses/announce.rs | 3 +- tests/servers/http/v1/contract.rs | 46 ++- 26 files changed, 244 insertions(+), 317 deletions(-) diff --git a/docs/media/flamegraph_generated_without_sudo.svg b/docs/media/flamegraph_generated_without_sudo.svg index 84c00ffe3..e3df85866 100644 --- a/docs/media/flamegraph_generated_without_sudo.svg +++ b/docs/media/flamegraph_generated_without_sudo.svg @@ -488,4 +488,4 @@ function search(term) { function format_percent(n) { return n.toFixed(4) + "%"; } -]]>Flame Graph Reset ZoomSearch [unknown] (188 samples, 0.14%)[unknown] (187 samples, 0.14%)[unknown] (186 samples, 0.14%)[unknown] (178 samples, 0.14%)[unknown] (172 samples, 0.13%)[unknown] (158 samples, 0.12%)[unknown] (158 samples, 0.12%)[unknown] (125 samples, 0.10%)[unknown] (102 samples, 0.08%)[unknown] (93 samples, 0.07%)[unknown] (92 samples, 0.07%)[unknown] (41 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (29 samples, 0.02%)[unknown] (25 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (15 samples, 0.01%)__GI___mmap64 (18 samples, 0.01%)__GI___mmap64 (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (17 samples, 0.01%)profiling (214 samples, 0.16%)clone3 (22 samples, 0.02%)start_thread (22 samples, 0.02%)std::sys::pal::unix::thread::Thread::new::thread_start (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::Handler::new (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::imp::make_handler (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::imp::get_stack (19 samples, 0.01%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (30 samples, 0.02%)[[vdso]] (93 samples, 0.07%)<torrust_tracker::shared::crypto::ephemeral_instance_keys::RANDOM_SEED as core::ops::deref::Deref>::deref::__stability::LAZY (143 samples, 0.11%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (31 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<BorrowType,K,V>::init_front (21 samples, 0.02%)[[vdso]] (91 samples, 0.07%)__GI___clock_gettime (14 samples, 0.01%)_int_malloc (53 samples, 0.04%)epoll_wait (254 samples, 0.19%)tokio::runtime::context::with_scheduler (28 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.01%)tokio::runtime::context::with_scheduler::{{closure}} (14 samples, 0.01%)core::option::Option<T>::map (17 samples, 0.01%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (17 samples, 0.01%)mio::poll::Poll::poll (27 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select (27 samples, 0.02%)tokio::runtime::io::driver::Driver::turn (54 samples, 0.04%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (26 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (17 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (71 samples, 0.05%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (65 samples, 0.05%)core::sync::atomic::AtomicUsize::fetch_add (65 samples, 0.05%)core::sync::atomic::atomic_add (65 samples, 0.05%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (31 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark_condvar (18 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (49 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (33 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (93 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Parker::park (75 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Inner::park (75 samples, 0.06%)core::cell::RefCell<T>::borrow_mut (18 samples, 0.01%)core::cell::RefCell<T>::try_borrow_mut (18 samples, 0.01%)core::cell::BorrowRefMut::new (18 samples, 0.01%)tokio::runtime::coop::budget (26 samples, 0.02%)tokio::runtime::coop::with_budget (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (96 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (27 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (18 samples, 0.01%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (35 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (14 samples, 0.01%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (90 samples, 0.07%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (90 samples, 0.07%)core::slice::<impl [T]>::contains (220 samples, 0.17%)<T as core::slice::cmp::SliceContains>::slice_contains (220 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (220 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (54 samples, 0.04%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (54 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (240 samples, 0.18%)tokio::runtime::scheduler::multi_thread::idle::Idle::unpark_worker_by_id (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (265 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Context::park (284 samples, 0.22%)core::option::Option<T>::or_else (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (40 samples, 0.03%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (17 samples, 0.01%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (17 samples, 0.01%)core::num::<impl u32>::wrapping_add (17 samples, 0.01%)core::sync::atomic::AtomicU64::compare_exchange (26 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (129 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (128 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (119 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::pack (39 samples, 0.03%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run (613 samples, 0.47%)tokio::runtime::context::runtime::enter_runtime (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (613 samples, 0.47%)tokio::runtime::context::set_scheduler (613 samples, 0.47%)std::thread::local::LocalKey<T>::with (613 samples, 0.47%)std::thread::local::LocalKey<T>::try_with (613 samples, 0.47%)tokio::runtime::context::set_scheduler::{{closure}} (613 samples, 0.47%)tokio::runtime::context::scoped::Scoped<T>::set (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::Context::run (613 samples, 0.47%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (777 samples, 0.59%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (776 samples, 0.59%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (16 samples, 0.01%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (16 samples, 0.01%)tokio::runtime::context::set_current_task_id (16 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (16 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (20 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (20 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::poll (835 samples, 0.64%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (56 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage (46 samples, 0.04%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (897 samples, 0.68%)tokio::runtime::task::harness::poll_future::{{closure}} (897 samples, 0.68%)tokio::runtime::task::core::Core<T,S>::store_output (62 samples, 0.05%)tokio::runtime::task::harness::poll_future (930 samples, 0.71%)std::panic::catch_unwind (927 samples, 0.71%)std::panicking::try (927 samples, 0.71%)std::panicking::try::do_call (925 samples, 0.70%)core::mem::manually_drop::ManuallyDrop<T>::take (28 samples, 0.02%)core::ptr::read (28 samples, 0.02%)tokio::runtime::task::raw::poll (938 samples, 0.71%)tokio::runtime::task::harness::Harness<T,S>::poll (934 samples, 0.71%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (934 samples, 0.71%)core::array::<impl core::default::Default for [T: 32]>::default (26 samples, 0.02%)tokio::runtime::time::Inner::lock (16 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (15 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::time::wheel::Wheel::poll (25 samples, 0.02%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (98 samples, 0.07%)tokio::runtime::time::Driver::park_internal (51 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (15 samples, 0.01%)<F as core::future::into_future::IntoFuture>::into_future (16 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (24 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (46 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (131 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (24 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (14 samples, 0.01%)core::sync::atomic::AtomicU32::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (39 samples, 0.03%)std::sync::rwlock::RwLock<T>::read (34 samples, 0.03%)std::sys::sync::rwlock::futex::RwLock::read (32 samples, 0.02%)[[heap]] (2,361 samples, 1.80%)[..[[vdso]] (313 samples, 0.24%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (41 samples, 0.03%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (16 samples, 0.01%)<alloc::string::String as core::fmt::Write>::write_str (67 samples, 0.05%)alloc::string::String::push_str (18 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (18 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (18 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (18 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (36 samples, 0.03%)core::num::<impl u64>::rotate_left (28 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (60 samples, 0.05%)core::num::<impl u64>::wrapping_add (14 samples, 0.01%)core::hash::sip::u8to64_le (60 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (184 samples, 0.14%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (15 samples, 0.01%)tokio::runtime::context::CONTEXT::__getit (19 samples, 0.01%)core::cell::Cell<T>::get (17 samples, 0.01%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (26 samples, 0.02%)core::ops::function::FnMut::call_mut (21 samples, 0.02%)tokio::runtime::coop::poll_proceed (21 samples, 0.02%)tokio::runtime::context::budget (21 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (21 samples, 0.02%)[unknown] (18 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (195 samples, 0.15%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (14 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (14 samples, 0.01%)core::result::Result<T,E>::is_err (18 samples, 0.01%)core::result::Result<T,E>::is_ok (18 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (46 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (39 samples, 0.03%)core::sync::atomic::AtomicU32::compare_exchange (19 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (19 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (245 samples, 0.19%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (26 samples, 0.02%)[[vdso]] (748 samples, 0.57%)[profiling] (34 samples, 0.03%)core::fmt::write (31 samples, 0.02%)__GI___clock_gettime (29 samples, 0.02%)__GI___libc_free (131 samples, 0.10%)arena_for_chunk (20 samples, 0.02%)arena_for_chunk (19 samples, 0.01%)heap_for_ptr (19 samples, 0.01%)heap_max_size (14 samples, 0.01%)__GI___libc_malloc (114 samples, 0.09%)__GI___libc_realloc (15 samples, 0.01%)__GI___lll_lock_wake_private (22 samples, 0.02%)__GI___pthread_disable_asynccancel (66 samples, 0.05%)__GI_getsockname (249 samples, 0.19%)__libc_calloc (15 samples, 0.01%)__libc_recvfrom (23 samples, 0.02%)__libc_sendto (130 samples, 0.10%)__memcmp_evex_movbe (451 samples, 0.34%)__memcpy_avx512_unaligned_erms (426 samples, 0.32%)__memset_avx512_unaligned_erms (215 samples, 0.16%)__posix_memalign (17 samples, 0.01%)_int_free (418 samples, 0.32%)tcache_put (24 samples, 0.02%)_int_malloc (385 samples, 0.29%)_int_memalign (31 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (26 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (15 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (15 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (15 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (54 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::grow_one (15 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (96 samples, 0.07%)alloc::raw_vec::RawVec<T,A>::grow_amortized (66 samples, 0.05%)core::num::<impl usize>::checked_add (18 samples, 0.01%)core::num::<impl usize>::overflowing_add (18 samples, 0.01%)alloc::raw_vec::finish_grow (74 samples, 0.06%)alloc::sync::Arc<T,A>::drop_slow (16 samples, 0.01%)core::mem::drop (14 samples, 0.01%)core::fmt::Formatter::pad_integral (14 samples, 0.01%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (93 samples, 0.07%)core::ptr::drop_in_place<tokio::net::udp::UdpSocket::send_to<&core::net::socket_addr::SocketAddr>::{{closure}}> (23 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (188 samples, 0.14%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_announce::{{closure}}> (30 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_connect::{{closure}}> (22 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_packet::{{closure}}> (20 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}}> (19 samples, 0.01%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::send_response::{{closure}}> (22 samples, 0.02%)malloc_consolidate (24 samples, 0.02%)core::core_arch::x86::avx2::_mm256_or_si256 (15 samples, 0.01%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (17 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (17 samples, 0.01%)rand_chacha::guts::round (66 samples, 0.05%)rand_chacha::guts::refill_wide::impl_avx2 (99 samples, 0.08%)rand_chacha::guts::refill_wide::fn_impl (98 samples, 0.07%)rand_chacha::guts::refill_wide_impl (98 samples, 0.07%)std::io::error::Error::kind (14 samples, 0.01%)[unknown] (42 samples, 0.03%)[unknown] (14 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (490 samples, 0.37%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (211 samples, 0.16%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (84 samples, 0.06%)tokio::runtime::task::core::Header::get_owner_id (18 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (18 samples, 0.01%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (20 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::remove (19 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (31 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (29 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (108 samples, 0.08%)tokio::runtime::task::core::TaskIdGuard::enter (14 samples, 0.01%)tokio::runtime::context::set_current_task_id (14 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::complete (21 samples, 0.02%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (32 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (54 samples, 0.04%)tokio::runtime::task::raw::drop_abort_handle (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (17 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (22 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (22 samples, 0.02%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (79 samples, 0.06%)core::slice::<impl [T]>::contains (178 samples, 0.14%)<T as core::slice::cmp::SliceContains>::slice_contains (178 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (178 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (40 samples, 0.03%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (40 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (216 samples, 0.16%)tokio::loom::std::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (219 samples, 0.17%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (29 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (29 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (54 samples, 0.04%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (18 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (18 samples, 0.01%)core::sync::atomic::AtomicU32::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (113 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (51 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (31 samples, 0.02%)core::sync::atomic::AtomicU64::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (447 samples, 0.34%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (174 samples, 0.13%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (19 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (489 samples, 0.37%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (489 samples, 0.37%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run (484 samples, 0.37%)tokio::runtime::context::runtime::enter_runtime (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (484 samples, 0.37%)tokio::runtime::context::set_scheduler (484 samples, 0.37%)std::thread::local::LocalKey<T>::with (484 samples, 0.37%)std::thread::local::LocalKey<T>::try_with (484 samples, 0.37%)tokio::runtime::context::set_scheduler::{{closure}} (484 samples, 0.37%)tokio::runtime::context::scoped::Scoped<T>::set (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Context::run (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (24 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (20 samples, 0.02%)tokio::runtime::task::raw::poll (515 samples, 0.39%)tokio::runtime::task::harness::Harness<T,S>::poll (493 samples, 0.38%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (493 samples, 0.38%)tokio::runtime::task::harness::poll_future (493 samples, 0.38%)std::panic::catch_unwind (493 samples, 0.38%)std::panicking::try (493 samples, 0.38%)std::panicking::try::do_call (493 samples, 0.38%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (493 samples, 0.38%)tokio::runtime::task::harness::poll_future::{{closure}} (493 samples, 0.38%)tokio::runtime::task::core::Core<T,S>::poll (493 samples, 0.38%)tokio::runtime::time::wheel::Wheel::next_expiration (16 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (27 samples, 0.02%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (15 samples, 0.01%)torrust_tracker::core::Tracker::send_stats_event::{{closure}} (44 samples, 0.03%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (15 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::d_rounds (29 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (74 samples, 0.06%)torrust_tracker::servers::udp::peer_builder::from_request (17 samples, 0.01%)torrust_tracker::servers::udp::request::AnnounceWrapper::new (51 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (54 samples, 0.04%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (58 samples, 0.04%)torrust_tracker::core::Tracker::announce::{{closure}} (70 samples, 0.05%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (113 samples, 0.09%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (175 samples, 0.13%)<T as alloc::string::ToString>::to_string (38 samples, 0.03%)core::option::Option<T>::expect (56 samples, 0.04%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (18 samples, 0.01%)<T as alloc::string::ToString>::to_string (18 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (180 samples, 0.14%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (468 samples, 0.36%)torrust_tracker::servers::udp::logging::log_response (38 samples, 0.03%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (669 samples, 0.51%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (152 samples, 0.12%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (147 samples, 0.11%)tokio::net::udp::UdpSocket::send_to::{{closure}} (138 samples, 0.11%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (119 samples, 0.09%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (75 samples, 0.06%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (39 samples, 0.03%)mio::net::udp::UdpSocket::send_to (39 samples, 0.03%)mio::io_source::IoSource<T>::do_io (39 samples, 0.03%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (39 samples, 0.03%)mio::net::udp::UdpSocket::send_to::{{closure}} (39 samples, 0.03%)std::net::udp::UdpSocket::send_to (39 samples, 0.03%)std::sys_common::net::UdpSocket::send_to (39 samples, 0.03%)std::sys::pal::unix::cvt (39 samples, 0.03%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (39 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_stats (15 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (14 samples, 0.01%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count::to_usize::{{closure}} (33 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats::{{closure}} (33 samples, 0.03%)torrust_tracker_primitives::peer::Peer::is_seeder (33 samples, 0.03%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count (75 samples, 0.06%)core::iter::traits::iterator::Iterator::sum (75 samples, 0.06%)<usize as core::iter::traits::accum::Sum>::sum (75 samples, 0.06%)<core::iter::adapters::map::Map<I,F> as core::iter::traits::iterator::Iterator>::fold (75 samples, 0.06%)core::iter::traits::iterator::Iterator::fold (75 samples, 0.06%)core::iter::adapters::map::map_fold::{{closure}} (34 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (104 samples, 0.08%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (24 samples, 0.02%)core::mem::drop (15 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (15 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (15 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (15 samples, 0.01%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (215 samples, 0.16%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (198 samples, 0.15%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (89 samples, 0.07%)core::option::Option<T>::is_some_and (32 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (31 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (30 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (30 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (26 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.03%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (58 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (58 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (58 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (58 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (58 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (20 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (238 samples, 0.18%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (236 samples, 0.18%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (208 samples, 0.16%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (208 samples, 0.16%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (282 samples, 0.21%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (67 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (53 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (53 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (22 samples, 0.02%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (22 samples, 0.02%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (22 samples, 0.02%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (22 samples, 0.02%)<u8 as core::slice::cmp::SliceOrd>::compare (22 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (18 samples, 0.01%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (23 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (23 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (43 samples, 0.03%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (43 samples, 0.03%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (43 samples, 0.03%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (43 samples, 0.03%)<u8 as core::slice::cmp::SliceOrd>::compare (43 samples, 0.03%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (17 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (151 samples, 0.12%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (145 samples, 0.11%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (137 samples, 0.10%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (137 samples, 0.10%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (266 samples, 0.20%)core::sync::atomic::AtomicU32::load (27 samples, 0.02%)core::sync::atomic::atomic_load (27 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (38 samples, 0.03%)std::sync::rwlock::RwLock<T>::read (37 samples, 0.03%)std::sys::sync::rwlock::futex::RwLock::read (36 samples, 0.03%)tracing::span::Span::log (16 samples, 0.01%)tracing::span::Span::record_all (70 samples, 0.05%)unlink_chunk (139 samples, 0.11%)rand::rng::Rng::gen (30 samples, 0.02%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (30 samples, 0.02%)rand::rng::Rng::gen (30 samples, 0.02%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (30 samples, 0.02%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (30 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (30 samples, 0.02%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (30 samples, 0.02%)rand_core::block::BlockRng<R>::generate_and_set (28 samples, 0.02%)[anon] (8,759 samples, 6.67%)[anon]uuid::v4::<impl uuid::Uuid>::new_v4 (32 samples, 0.02%)uuid::rng::bytes (32 samples, 0.02%)rand::random (32 samples, 0.02%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (15 samples, 0.01%)_int_free (338 samples, 0.26%)tcache_put (18 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (22 samples, 0.02%)hashbrown::raw::h2 (14 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (23 samples, 0.02%)hashbrown::raw::RawTableInner::find_or_find_insert_slot_inner (17 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (25 samples, 0.02%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (15 samples, 0.01%)[profiling] (545 samples, 0.42%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (32 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (22 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (16 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (30 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (28 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (83 samples, 0.06%)alloc::string::String::push_str (57 samples, 0.04%)alloc::vec::Vec<T,A>::extend_from_slice (57 samples, 0.04%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (57 samples, 0.04%)alloc::vec::Vec<T,A>::append_elements (57 samples, 0.04%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (20 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (41 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (151 samples, 0.12%)core::hash::sip::u8to64_le (50 samples, 0.04%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (33 samples, 0.03%)tokio::runtime::context::CONTEXT::__getit (35 samples, 0.03%)core::cell::Cell<T>::get (33 samples, 0.03%)[unknown] (20 samples, 0.02%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (75 samples, 0.06%)core::ops::function::FnMut::call_mut (66 samples, 0.05%)tokio::runtime::coop::poll_proceed (66 samples, 0.05%)tokio::runtime::context::budget (66 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (66 samples, 0.05%)tokio::runtime::context::budget::{{closure}} (27 samples, 0.02%)tokio::runtime::coop::poll_proceed::{{closure}} (27 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (110 samples, 0.08%)[unknown] (15 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (27 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (27 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (14 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (84 samples, 0.06%)std::sync::mutex::Mutex<T>::lock (70 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock (59 samples, 0.04%)core::sync::atomic::AtomicU32::compare_exchange (55 samples, 0.04%)core::sync::atomic::atomic_compare_exchange (55 samples, 0.04%)[unknown] (33 samples, 0.03%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (214 samples, 0.16%)__memcpy_avx512_unaligned_erms (168 samples, 0.13%)[profiling] (171 samples, 0.13%)binascii::bin2hex (77 samples, 0.06%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (280 samples, 0.21%)[unknown] (317 samples, 0.24%)[[vdso]] (2,648 samples, 2.02%)[..[unknown] (669 samples, 0.51%)[unknown] (396 samples, 0.30%)[unknown] (251 samples, 0.19%)[unknown] (65 samples, 0.05%)[unknown] (30 samples, 0.02%)[unknown] (21 samples, 0.02%)__GI___clock_gettime (56 samples, 0.04%)arena_for_chunk (72 samples, 0.05%)arena_for_chunk (62 samples, 0.05%)heap_for_ptr (49 samples, 0.04%)heap_max_size (28 samples, 0.02%)__GI___libc_free (194 samples, 0.15%)arena_for_chunk (19 samples, 0.01%)checked_request2size (24 samples, 0.02%)__GI___libc_malloc (220 samples, 0.17%)tcache_get (44 samples, 0.03%)__GI___libc_write (25 samples, 0.02%)__GI___libc_write (14 samples, 0.01%)__GI___pthread_disable_asynccancel (97 samples, 0.07%)core::num::<impl u128>::leading_zeros (15 samples, 0.01%)compiler_builtins::float::conv::int_to_float::u128_to_f64_bits (72 samples, 0.05%)__floattidf (90 samples, 0.07%)compiler_builtins::float::conv::__floattidf (86 samples, 0.07%)exp_inline (40 samples, 0.03%)log_inline (64 samples, 0.05%)__ieee754_pow_fma (114 samples, 0.09%)__libc_calloc (106 samples, 0.08%)__libc_recvfrom (252 samples, 0.19%)__libc_sendto (133 samples, 0.10%)__memcmp_evex_movbe (137 samples, 0.10%)__memcpy_avx512_unaligned_erms (1,399 samples, 1.07%)__posix_memalign (172 samples, 0.13%)__posix_memalign (80 samples, 0.06%)_mid_memalign (71 samples, 0.05%)arena_for_chunk (14 samples, 0.01%)__pow (18 samples, 0.01%)__vdso_clock_gettime (40 samples, 0.03%)[unknown] (24 samples, 0.02%)_int_free (462 samples, 0.35%)tcache_put (54 samples, 0.04%)[unknown] (14 samples, 0.01%)_int_malloc (508 samples, 0.39%)_int_memalign (68 samples, 0.05%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (54 samples, 0.04%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (14 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (78 samples, 0.06%)alloc::raw_vec::RawVec<T,A>::grow_amortized (73 samples, 0.06%)alloc::raw_vec::finish_grow (91 samples, 0.07%)core::result::Result<T,E>::map_err (31 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Weak<ring::ec::curve25519::ed25519::signing::Ed25519KeyPair,&alloc::alloc::Global>> (16 samples, 0.01%)<alloc::sync::Weak<T,A> as core::ops::drop::Drop>::drop (16 samples, 0.01%)core::mem::drop (18 samples, 0.01%)alloc::sync::Arc<T,A>::drop_slow (21 samples, 0.02%)alloc_new_heap (49 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (49 samples, 0.04%)core::fmt::Formatter::pad_integral (40 samples, 0.03%)core::fmt::Formatter::pad_integral::write_prefix (19 samples, 0.01%)core::fmt::write (20 samples, 0.02%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (155 samples, 0.12%)core::ptr::drop_in_place<core::option::Option<core::task::wake::Waker>> (71 samples, 0.05%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (245 samples, 0.19%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_announce::{{closure}}> (33 samples, 0.03%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}}> (37 samples, 0.03%)core::str::converts::from_utf8 (33 samples, 0.03%)core::str::validations::run_utf8_validation (20 samples, 0.02%)epoll_wait (31 samples, 0.02%)hashbrown::map::HashMap<K,V,S,A>::insert (17 samples, 0.01%)rand_chacha::guts::refill_wide (19 samples, 0.01%)std_detect::detect::arch::x86::__is_feature_detected::avx2 (17 samples, 0.01%)std_detect::detect::check_for (17 samples, 0.01%)std_detect::detect::cache::test (17 samples, 0.01%)std_detect::detect::cache::Cache::test (17 samples, 0.01%)core::sync::atomic::AtomicUsize::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)std::sys::pal::unix::time::Timespec::new (29 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (132 samples, 0.10%)core::cmp::impls::<impl core::cmp::PartialOrd<&B> for &A>::ge (22 samples, 0.02%)core::cmp::PartialOrd::ge (22 samples, 0.02%)std::sys::pal::unix::time::Timespec::sub_timespec (67 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock_contended (18 samples, 0.01%)std::sys_common::net::TcpListener::socket_addr (29 samples, 0.02%)std::sys_common::net::sockname (28 samples, 0.02%)syscall (552 samples, 0.42%)core::ptr::drop_in_place<core::cell::RefMut<core::option::Option<alloc::boxed::Box<tokio::runtime::scheduler::multi_thread::worker::Core>>>> (74 samples, 0.06%)core::ptr::drop_in_place<core::cell::BorrowRefMut> (74 samples, 0.06%)<core::cell::BorrowRefMut as core::ops::drop::Drop>::drop (74 samples, 0.06%)core::cell::Cell<T>::set (74 samples, 0.06%)core::cell::Cell<T>::replace (74 samples, 0.06%)core::mem::replace (74 samples, 0.06%)core::ptr::write (74 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::push_back_or_overflow (14 samples, 0.01%)tokio::runtime::context::with_scheduler (176 samples, 0.13%)std::thread::local::LocalKey<T>::try_with (152 samples, 0.12%)tokio::runtime::context::with_scheduler::{{closure}} (151 samples, 0.12%)tokio::runtime::context::scoped::Scoped<T>::with (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (71 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (16 samples, 0.01%)core::option::Option<T>::map (19 samples, 0.01%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (24 samples, 0.02%)mio::poll::Poll::poll (53 samples, 0.04%)mio::sys::unix::selector::epoll::Selector::select (53 samples, 0.04%)core::result::Result<T,E>::map (28 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (28 samples, 0.02%)tokio::io::ready::Ready::from_mio (14 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (126 samples, 0.10%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (18 samples, 0.01%)[unknown] (51 samples, 0.04%)[unknown] (100 samples, 0.08%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (326 samples, 0.25%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (205 samples, 0.16%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (77 samples, 0.06%)[unknown] (26 samples, 0.02%)<tokio::util::linked_list::DrainFilter<T,F> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (396 samples, 0.30%)tokio::loom::std::mutex::Mutex<T>::lock (18 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (573 samples, 0.44%)core::sync::atomic::AtomicUsize::fetch_add (566 samples, 0.43%)core::sync::atomic::atomic_add (566 samples, 0.43%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (635 samples, 0.48%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (25 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::next_remote_task (44 samples, 0.03%)tokio::runtime::scheduler::inject::shared::Shared<T>::is_empty (21 samples, 0.02%)tokio::runtime::scheduler::inject::shared::Shared<T>::len (21 samples, 0.02%)core::sync::atomic::AtomicUsize::load (21 samples, 0.02%)core::sync::atomic::atomic_load (21 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id (32 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (32 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (32 samples, 0.02%)std::sync::poison::Flag::done (32 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>,tokio::runtime::task::core::Header>>> (43 samples, 0.03%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (43 samples, 0.03%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (123 samples, 0.09%)tokio::runtime::task::list::OwnedTasks<S>::remove (117 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (80 samples, 0.06%)tokio::runtime::scheduler::defer::Defer::wake (17 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (46 samples, 0.04%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (71 samples, 0.05%)std::sync::condvar::Condvar::wait (56 samples, 0.04%)std::sys::sync::condvar::futex::Condvar::wait (56 samples, 0.04%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (56 samples, 0.04%)core::sync::atomic::AtomicUsize::compare_exchange (37 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (37 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (138 samples, 0.11%)tokio::runtime::driver::Driver::park (77 samples, 0.06%)tokio::runtime::driver::TimeDriver::park (77 samples, 0.06%)tokio::runtime::time::Driver::park (75 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Parker::park (266 samples, 0.20%)tokio::runtime::scheduler::multi_thread::park::Inner::park (266 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (432 samples, 0.33%)tokio::runtime::scheduler::multi_thread::worker::Core::should_notify_others (26 samples, 0.02%)core::cell::RefCell<T>::borrow_mut (94 samples, 0.07%)core::cell::RefCell<T>::try_borrow_mut (94 samples, 0.07%)core::cell::BorrowRefMut::new (94 samples, 0.07%)tokio::runtime::coop::budget (142 samples, 0.11%)tokio::runtime::coop::with_budget (142 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (121 samples, 0.09%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (44 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (208 samples, 0.16%)tokio::runtime::signal::Driver::process (30 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (46 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (46 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (35 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::set_stage (75 samples, 0.06%)core::sync::atomic::AtomicUsize::fetch_xor (76 samples, 0.06%)core::sync::atomic::atomic_xor (76 samples, 0.06%)tokio::runtime::task::state::State::transition_to_complete (79 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::complete (113 samples, 0.09%)tokio::runtime::task::state::State::transition_to_terminal (18 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::dealloc (28 samples, 0.02%)core::mem::drop (18 samples, 0.01%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (18 samples, 0.01%)core::ptr::drop_in_place<tokio::util::sharded_list::ShardGuard<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>> (16 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>>> (16 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (16 samples, 0.01%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (53 samples, 0.04%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (21 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (113 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (15 samples, 0.01%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (15 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (15 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (15 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (14 samples, 0.01%)tokio::runtime::task::raw::drop_abort_handle (82 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (23 samples, 0.02%)tokio::runtime::task::state::State::ref_dec (23 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::task::raw::drop_join_handle_slow (34 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::drop_join_handle_slow (32 samples, 0.02%)tokio::runtime::task::state::State::unset_join_interested (23 samples, 0.02%)tokio::runtime::task::state::State::fetch_update (23 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (43 samples, 0.03%)core::num::<impl u32>::wrapping_add (23 samples, 0.02%)core::option::Option<T>::or_else (37 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (36 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (36 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (38 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (59 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (45 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (132 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (63 samples, 0.05%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run (290 samples, 0.22%)tokio::runtime::context::runtime::enter_runtime (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (290 samples, 0.22%)tokio::runtime::context::set_scheduler (290 samples, 0.22%)std::thread::local::LocalKey<T>::with (290 samples, 0.22%)std::thread::local::LocalKey<T>::try_with (290 samples, 0.22%)tokio::runtime::context::set_scheduler::{{closure}} (290 samples, 0.22%)tokio::runtime::context::scoped::Scoped<T>::set (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::Context::run (290 samples, 0.22%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (327 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (322 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::poll (333 samples, 0.25%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (342 samples, 0.26%)tokio::runtime::task::harness::poll_future::{{closure}} (342 samples, 0.26%)tokio::runtime::task::harness::poll_future (348 samples, 0.27%)std::panic::catch_unwind (347 samples, 0.26%)std::panicking::try (347 samples, 0.26%)std::panicking::try::do_call (347 samples, 0.26%)core::sync::atomic::AtomicUsize::compare_exchange (18 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (18 samples, 0.01%)tokio::runtime::task::state::State::transition_to_running (47 samples, 0.04%)tokio::runtime::task::state::State::fetch_update_action (47 samples, 0.04%)tokio::runtime::task::state::State::transition_to_running::{{closure}} (19 samples, 0.01%)tokio::runtime::task::raw::poll (427 samples, 0.33%)tokio::runtime::task::harness::Harness<T,S>::poll (408 samples, 0.31%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (407 samples, 0.31%)tokio::runtime::task::state::State::transition_to_idle (17 samples, 0.01%)core::array::<impl core::default::Default for [T: 32]>::default (21 samples, 0.02%)tokio::runtime::time::wheel::Wheel::poll (14 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (72 samples, 0.05%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (23 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (15 samples, 0.01%)tokio::runtime::time::source::TimeSource::now (14 samples, 0.01%)tokio::runtime::time::Driver::park_internal (155 samples, 0.12%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (96 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (35 samples, 0.03%)core::num::<impl usize>::pow (35 samples, 0.03%)tokio::runtime::time::wheel::level::level_range (39 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (33 samples, 0.03%)core::num::<impl usize>::pow (33 samples, 0.03%)tokio::runtime::time::wheel::level::Level::next_expiration (208 samples, 0.16%)tokio::runtime::time::wheel::level::slot_range (48 samples, 0.04%)core::num::<impl usize>::pow (48 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (277 samples, 0.21%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::is_empty (18 samples, 0.01%)core::option::Option<T>::is_some (18 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (50 samples, 0.04%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (37 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (27 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (19 samples, 0.01%)core::iter::traits::iterator::Iterator::collect (17 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (17 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (17 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (17 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (20 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (20 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (20 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (62 samples, 0.05%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (40 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (27 samples, 0.02%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (17 samples, 0.01%)torrust_tracker::servers::udp::peer_builder::from_request (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (19 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (355 samples, 0.27%)<F as core::future::into_future::IntoFuture>::into_future (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (37 samples, 0.03%)core::sync::atomic::AtomicUsize::fetch_add (25 samples, 0.02%)core::sync::atomic::atomic_add (25 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet (14 samples, 0.01%)core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (20 samples, 0.02%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)core::result::Result<T,E>::map_err (16 samples, 0.01%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (136 samples, 0.10%)torrust_tracker::core::Tracker::announce::{{closure}} (173 samples, 0.13%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (267 samples, 0.20%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (30 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (423 samples, 0.32%)core::fmt::Formatter::new (26 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (80 samples, 0.06%)core::fmt::num::imp::fmt_u64 (58 samples, 0.04%)core::intrinsics::copy_nonoverlapping (15 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (74 samples, 0.06%)core::fmt::num::imp::fmt_u64 (70 samples, 0.05%)<T as alloc::string::ToString>::to_string (207 samples, 0.16%)core::option::Option<T>::expect (19 samples, 0.01%)core::ptr::drop_in_place<alloc::string::String> (18 samples, 0.01%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (18 samples, 0.01%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (18 samples, 0.01%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (18 samples, 0.01%)torrust_tracker::servers::udp::logging::map_action_name (25 samples, 0.02%)alloc::str::<impl alloc::borrow::ToOwned for str>::to_owned (14 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (345 samples, 0.26%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (18 samples, 0.01%)core::fmt::num::imp::fmt_u64 (14 samples, 0.01%)<T as alloc::string::ToString>::to_string (35 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (1,067 samples, 0.81%)torrust_tracker::servers::udp::logging::log_response (72 samples, 0.05%)alloc::vec::from_elem (68 samples, 0.05%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (68 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (68 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (68 samples, 0.05%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (68 samples, 0.05%)alloc::alloc::Global::alloc_impl (68 samples, 0.05%)alloc::alloc::alloc_zeroed (68 samples, 0.05%)__rdl_alloc_zeroed (68 samples, 0.05%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (68 samples, 0.05%)[unknown] (48 samples, 0.04%)[unknown] (16 samples, 0.01%)[unknown] (28 samples, 0.02%)std::sys::pal::unix::cvt (134 samples, 0.10%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (134 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (1,908 samples, 1.45%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (504 samples, 0.38%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (382 samples, 0.29%)tokio::net::udp::UdpSocket::send_to::{{closure}} (344 samples, 0.26%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (332 samples, 0.25%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (304 samples, 0.23%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (215 samples, 0.16%)mio::net::udp::UdpSocket::send_to (185 samples, 0.14%)mio::io_source::IoSource<T>::do_io (185 samples, 0.14%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (185 samples, 0.14%)mio::net::udp::UdpSocket::send_to::{{closure}} (185 samples, 0.14%)std::net::udp::UdpSocket::send_to (185 samples, 0.14%)std::sys_common::net::UdpSocket::send_to (169 samples, 0.13%)alloc::vec::Vec<T>::with_capacity (17 samples, 0.01%)alloc::vec::Vec<T,A>::with_capacity_in (17 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (104 samples, 0.08%)tokio::net::udp::UdpSocket::ready::{{closure}} (85 samples, 0.06%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (190 samples, 0.14%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (49 samples, 0.04%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (28 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (330 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (327 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (92 samples, 0.07%)tokio::task::spawn::spawn (92 samples, 0.07%)tokio::task::spawn::spawn_inner (92 samples, 0.07%)tokio::runtime::context::current::with_current (92 samples, 0.07%)std::thread::local::LocalKey<T>::try_with (92 samples, 0.07%)tokio::runtime::context::current::with_current::{{closure}} (92 samples, 0.07%)core::option::Option<T>::map (92 samples, 0.07%)tokio::task::spawn::spawn_inner::{{closure}} (92 samples, 0.07%)tokio::runtime::scheduler::Handle::spawn (92 samples, 0.07%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (92 samples, 0.07%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (92 samples, 0.07%)tokio::runtime::task::list::OwnedTasks<S>::bind (90 samples, 0.07%)tokio::runtime::task::new_task (89 samples, 0.07%)tokio::runtime::task::raw::RawTask::new (89 samples, 0.07%)tokio::runtime::task::core::Cell<T,S>::new (89 samples, 0.07%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (34 samples, 0.03%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (27 samples, 0.02%)alloc::sync::Arc<T>::new (21 samples, 0.02%)alloc::boxed::Box<T>::new (21 samples, 0.02%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (152 samples, 0.12%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (125 samples, 0.10%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (88 samples, 0.07%)core::option::Option<T>::is_some_and (18 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (17 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (17 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (17 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (22 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (22 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (17 samples, 0.01%)std::sync::rwlock::RwLock<T>::read (16 samples, 0.01%)std::sys::sync::rwlock::futex::RwLock::read (16 samples, 0.01%)tracing::span::Span::log (26 samples, 0.02%)core::fmt::Arguments::new_v1 (15 samples, 0.01%)tracing_core::span::Record::is_empty (34 samples, 0.03%)tracing_core::field::ValueSet::is_empty (34 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::all (22 samples, 0.02%)tracing_core::field::ValueSet::is_empty::{{closure}} (18 samples, 0.01%)core::option::Option<T>::is_none (16 samples, 0.01%)core::option::Option<T>::is_some (16 samples, 0.01%)tracing::span::Span::record_all (143 samples, 0.11%)unlink_chunk (185 samples, 0.14%)uuid::builder::Builder::with_variant (48 samples, 0.04%)[unknown] (40 samples, 0.03%)uuid::builder::Builder::from_random_bytes (77 samples, 0.06%)uuid::builder::Builder::with_version (29 samples, 0.02%)[unknown] (24 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (161 samples, 0.12%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (161 samples, 0.12%)[unknown] (92 samples, 0.07%)rand::rng::Rng::gen (162 samples, 0.12%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (162 samples, 0.12%)rand::rng::Rng::gen (162 samples, 0.12%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (162 samples, 0.12%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (162 samples, 0.12%)[unknown] (18,233 samples, 13.89%)[unknown]uuid::v4::<impl uuid::Uuid>::new_v4 (270 samples, 0.21%)uuid::rng::bytes (190 samples, 0.14%)rand::random (190 samples, 0.14%)__memcpy_avx512_unaligned_erms (69 samples, 0.05%)_int_free (23 samples, 0.02%)_int_malloc (23 samples, 0.02%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)advise_stack_range (31 samples, 0.02%)__GI_madvise (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (29 samples, 0.02%)[unknown] (28 samples, 0.02%)[unknown] (28 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (17 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (31 samples, 0.02%)syscall (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (29 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (17 samples, 0.01%)std::sync::condvar::Condvar::wait_timeout (35 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_timeout (35 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (35 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (56 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (56 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (56 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (56 samples, 0.04%)std::sys::pal::unix::futex::futex_wait (56 samples, 0.04%)syscall (56 samples, 0.04%)[unknown] (56 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (53 samples, 0.04%)[unknown] (52 samples, 0.04%)[unknown] (46 samples, 0.04%)[unknown] (39 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (15 samples, 0.01%)[[vdso]] (26 samples, 0.02%)[[vdso]] (263 samples, 0.20%)__ieee754_pow_fma (26 samples, 0.02%)__pow (314 samples, 0.24%)std::f64::<impl f64>::powf (345 samples, 0.26%)__GI___clock_gettime (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (416 samples, 0.32%)std::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_processing_scheduled_tasks (24 samples, 0.02%)std::time::Instant::now (18 samples, 0.01%)std::sys::pal::unix::time::Instant::now (18 samples, 0.01%)mio::poll::Poll::poll (102 samples, 0.08%)mio::sys::unix::selector::epoll::Selector::select (102 samples, 0.08%)epoll_wait (99 samples, 0.08%)[unknown] (92 samples, 0.07%)[unknown] (91 samples, 0.07%)[unknown] (91 samples, 0.07%)[unknown] (88 samples, 0.07%)[unknown] (85 samples, 0.06%)[unknown] (84 samples, 0.06%)[unknown] (43 samples, 0.03%)[unknown] (29 samples, 0.02%)[unknown] (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (125 samples, 0.10%)tokio::runtime::scheduler::multi_thread::park::Parker::park_timeout (125 samples, 0.10%)tokio::runtime::driver::Driver::park_timeout (125 samples, 0.10%)tokio::runtime::driver::TimeDriver::park_timeout (125 samples, 0.10%)tokio::runtime::time::Driver::park_timeout (125 samples, 0.10%)tokio::runtime::time::Driver::park_internal (116 samples, 0.09%)tokio::runtime::io::driver::Driver::turn (116 samples, 0.09%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (148 samples, 0.11%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (111 samples, 0.08%)alloc::sync::Arc<T,A>::inner (111 samples, 0.08%)core::ptr::non_null::NonNull<T>::as_ref (111 samples, 0.08%)core::sync::atomic::AtomicUsize::compare_exchange (16 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (16 samples, 0.01%)core::bool::<impl bool>::then (88 samples, 0.07%)std::sys::pal::unix::futex::futex_wait (13,339 samples, 10.16%)std::sys::pal::..syscall (13,003 samples, 9.90%)syscall[unknown] (12,895 samples, 9.82%)[unknown][unknown] (12,759 samples, 9.72%)[unknown][unknown] (12,313 samples, 9.38%)[unknown][unknown] (12,032 samples, 9.16%)[unknown][unknown] (11,734 samples, 8.94%)[unknown][unknown] (11,209 samples, 8.54%)[unknown][unknown] (10,265 samples, 7.82%)[unknown][unknown] (9,345 samples, 7.12%)[unknown][unknown] (8,623 samples, 6.57%)[unknown][unknown] (7,744 samples, 5.90%)[unknow..[unknown] (5,922 samples, 4.51%)[unkn..[unknown] (4,459 samples, 3.40%)[un..[unknown] (2,808 samples, 2.14%)[..[unknown] (1,275 samples, 0.97%)[unknown] (1,022 samples, 0.78%)[unknown] (738 samples, 0.56%)[unknown] (607 samples, 0.46%)[unknown] (155 samples, 0.12%)core::result::Result<T,E>::is_err (77 samples, 0.06%)core::result::Result<T,E>::is_ok (77 samples, 0.06%)std::sync::condvar::Condvar::wait (13,429 samples, 10.23%)std::sync::cond..std::sys::sync::condvar::futex::Condvar::wait (13,428 samples, 10.23%)std::sys::sync:..std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (13,428 samples, 10.23%)std::sys::sync:..std::sys::sync::mutex::futex::Mutex::lock (89 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (13,508 samples, 10.29%)tokio::runtime:..tokio::loom::std::mutex::Mutex<T>::lock (64 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (31 samples, 0.02%)core::sync::atomic::AtomicU32::compare_exchange (30 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (30 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (38 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Parker::park (34 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park (34 samples, 0.03%)core::array::<impl core::default::Default for [T: 32]>::default (17 samples, 0.01%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (19 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (33 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (15 samples, 0.01%)core::num::<impl usize>::pow (15 samples, 0.01%)tokio::runtime::time::wheel::level::level_range (17 samples, 0.01%)tokio::runtime::time::wheel::level::slot_range (15 samples, 0.01%)core::num::<impl usize>::pow (15 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_expiration (95 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (41 samples, 0.03%)core::num::<impl usize>::pow (41 samples, 0.03%)tokio::runtime::time::wheel::Wheel::next_expiration (129 samples, 0.10%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (202 samples, 0.15%)tokio::runtime::time::wheel::Wheel::poll_at (17 samples, 0.01%)tokio::runtime::time::wheel::Wheel::next_expiration (15 samples, 0.01%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (38 samples, 0.03%)core::option::Option<T>::map (38 samples, 0.03%)core::result::Result<T,E>::map (31 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (31 samples, 0.02%)alloc::vec::Vec<T,A>::set_len (17 samples, 0.01%)[[vdso]] (28 samples, 0.02%)[unknown] (11,031 samples, 8.40%)[unknown][unknown] (10,941 samples, 8.33%)[unknown][unknown] (10,850 samples, 8.26%)[unknown][unknown] (10,691 samples, 8.14%)[unknown][unknown] (10,070 samples, 7.67%)[unknown][unknown] (9,737 samples, 7.42%)[unknown][unknown] (7,659 samples, 5.83%)[unknow..[unknown] (6,530 samples, 4.97%)[unkno..[unknown] (5,633 samples, 4.29%)[unkn..[unknown] (5,055 samples, 3.85%)[unk..[unknown] (4,046 samples, 3.08%)[un..[unknown] (2,911 samples, 2.22%)[..[unknown] (2,115 samples, 1.61%)[unknown] (1,226 samples, 0.93%)[unknown] (455 samples, 0.35%)[unknown] (408 samples, 0.31%)[unknown] (249 samples, 0.19%)[unknown] (202 samples, 0.15%)[unknown] (100 samples, 0.08%)mio::poll::Poll::poll (11,328 samples, 8.63%)mio::poll::P..mio::sys::unix::selector::epoll::Selector::select (11,328 samples, 8.63%)mio::sys::un..epoll_wait (11,229 samples, 8.55%)epoll_wait__GI___pthread_disable_asynccancel (50 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (47 samples, 0.04%)tokio::util::bit::Pack::pack (38 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (25 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (23 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (19 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (11,595 samples, 8.83%)tokio::runti..tokio::runtime::io::scheduled_io::ScheduledIo::wake (175 samples, 0.13%)__GI___clock_gettime (15 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (18 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (26 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (26 samples, 0.02%)tokio::time::clock::Clock::now (20 samples, 0.02%)tokio::time::clock::now (20 samples, 0.02%)std::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Instant::now (20 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (17 samples, 0.01%)tokio::runtime::time::Driver::park_internal (11,686 samples, 8.90%)tokio::runtim..tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (11,957 samples, 9.11%)tokio::runtim..tokio::runtime::driver::Driver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::driver::TimeDriver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::time::Driver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::scheduler::multi_thread::park::Parker::park (25,502 samples, 19.42%)tokio::runtime::scheduler::mul..tokio::runtime::scheduler::multi_thread::park::Inner::park (25,502 samples, 19.42%)tokio::runtime::scheduler::mul..tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (25,547 samples, 19.46%)tokio::runtime::scheduler::mul..core::result::Result<T,E>::is_err (14 samples, 0.01%)core::result::Result<T,E>::is_ok (14 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (45 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (45 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (84 samples, 0.06%)std::sync::mutex::Mutex<T>::lock (81 samples, 0.06%)std::sys::sync::mutex::futex::Mutex::lock (73 samples, 0.06%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (122 samples, 0.09%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (90 samples, 0.07%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (90 samples, 0.07%)core::slice::<impl [T]>::contains (241 samples, 0.18%)<T as core::slice::cmp::SliceContains>::slice_contains (241 samples, 0.18%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (241 samples, 0.18%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (75 samples, 0.06%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (75 samples, 0.06%)core::sync::atomic::AtomicU32::compare_exchange (20 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (283 samples, 0.22%)tokio::loom::std::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (24 samples, 0.02%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (33 samples, 0.03%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (33 samples, 0.03%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (33 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::unpark_worker_by_id (98 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (401 samples, 0.31%)alloc::vec::Vec<T,A>::push (14 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (15 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (15 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::unlock (14 samples, 0.01%)core::result::Result<T,E>::is_err (15 samples, 0.01%)core::result::Result<T,E>::is_ok (15 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (22 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (22 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (63 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (62 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock (59 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (106 samples, 0.08%)tokio::runtime::scheduler::multi_thread::idle::State::dec_num_unparked (14 samples, 0.01%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (21 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (17 samples, 0.01%)alloc::sync::Arc<T,A>::inner (17 samples, 0.01%)core::ptr::non_null::NonNull<T>::as_ref (17 samples, 0.01%)core::sync::atomic::AtomicU32::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (68 samples, 0.05%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (51 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (33 samples, 0.03%)core::sync::atomic::AtomicU64::load (16 samples, 0.01%)core::sync::atomic::atomic_load (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (106 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::park (26,672 samples, 20.31%)tokio::runtime::scheduler::multi..tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (272 samples, 0.21%)tokio::runtime::scheduler::multi_thread::worker::Core::has_tasks (33 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::has_tasks (24 samples, 0.02%)tokio::runtime::context::budget (18 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (18 samples, 0.01%)syscall (61 samples, 0.05%)__memcpy_avx512_unaligned_erms (172 samples, 0.13%)__memcpy_avx512_unaligned_erms (224 samples, 0.17%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (228 samples, 0.17%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (228 samples, 0.17%)std::panic::catch_unwind (415 samples, 0.32%)std::panicking::try (415 samples, 0.32%)std::panicking::try::do_call (415 samples, 0.32%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (415 samples, 0.32%)core::ops::function::FnOnce::call_once (415 samples, 0.32%)tokio::runtime::task::harness::Harness<T,S>::complete::{{closure}} (415 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (415 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::set_stage (410 samples, 0.31%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (27 samples, 0.02%)core::result::Result<T,E>::is_err (43 samples, 0.03%)core::result::Result<T,E>::is_ok (43 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::complete (570 samples, 0.43%)tokio::runtime::task::harness::Harness<T,S>::release (155 samples, 0.12%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (152 samples, 0.12%)tokio::runtime::task::list::OwnedTasks<S>::remove (152 samples, 0.12%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (103 samples, 0.08%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (65 samples, 0.05%)tokio::loom::std::mutex::Mutex<T>::lock (58 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (58 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (54 samples, 0.04%)std::io::stdio::stderr::INSTANCE (17 samples, 0.01%)tokio::runtime::coop::budget (26 samples, 0.02%)tokio::runtime::coop::with_budget (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (35 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (70 samples, 0.05%)__memcpy_avx512_unaligned_erms (42 samples, 0.03%)core::cmp::Ord::min (22 samples, 0.02%)core::cmp::min_by (22 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (27 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (30 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (24 samples, 0.02%)core::slice::index::<impl core::ops::index::Index<I> for [T]>::index (19 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::index (19 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (19 samples, 0.01%)<core::ops::range::Range<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (19 samples, 0.01%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (44 samples, 0.03%)std::io::impls::<impl std::io::Read for &[u8]>::read_exact (20 samples, 0.02%)byteorder::io::ReadBytesExt::read_i32 (46 samples, 0.04%)core::cmp::Ord::min (14 samples, 0.01%)core::cmp::min_by (14 samples, 0.01%)std::io::cursor::Cursor<T>::remaining_slice (19 samples, 0.01%)byteorder::io::ReadBytesExt::read_i64 (24 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (24 samples, 0.02%)aquatic_udp_protocol::request::Request::from_bytes (349 samples, 0.27%)__GI___lll_lock_wake_private (148 samples, 0.11%)[unknown] (139 samples, 0.11%)[unknown] (137 samples, 0.10%)[unknown] (123 samples, 0.09%)[unknown] (111 samples, 0.08%)[unknown] (98 samples, 0.07%)[unknown] (42 samples, 0.03%)[unknown] (30 samples, 0.02%)__GI___lll_lock_wait_private (553 samples, 0.42%)futex_wait (541 samples, 0.41%)[unknown] (536 samples, 0.41%)[unknown] (531 samples, 0.40%)[unknown] (524 samples, 0.40%)[unknown] (515 samples, 0.39%)[unknown] (498 samples, 0.38%)[unknown] (470 samples, 0.36%)[unknown] (435 samples, 0.33%)[unknown] (350 samples, 0.27%)[unknown] (327 samples, 0.25%)[unknown] (290 samples, 0.22%)[unknown] (222 samples, 0.17%)[unknown] (160 samples, 0.12%)[unknown] (104 samples, 0.08%)[unknown] (33 samples, 0.03%)[unknown] (25 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (703 samples, 0.54%)__GI___libc_free (866 samples, 0.66%)tracing::span::Span::record_all (30 samples, 0.02%)unlink_chunk (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (899 samples, 0.68%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (899 samples, 0.68%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (899 samples, 0.68%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (899 samples, 0.68%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (899 samples, 0.68%)alloc::alloc::dealloc (899 samples, 0.68%)__rdl_dealloc (899 samples, 0.68%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (899 samples, 0.68%)core::result::Result<T,E>::expect (91 samples, 0.07%)core::result::Result<T,E>::map_err (28 samples, 0.02%)[[vdso]] (28 samples, 0.02%)__GI___clock_gettime (47 samples, 0.04%)std::time::Instant::elapsed (67 samples, 0.05%)std::time::Instant::now (54 samples, 0.04%)std::sys::pal::unix::time::Instant::now (54 samples, 0.04%)std::sys::pal::unix::time::Timespec::now (53 samples, 0.04%)std::sys::pal::unix::cvt (23 samples, 0.02%)__GI_getsockname (3,792 samples, 2.89%)__..[unknown] (3,714 samples, 2.83%)[u..[unknown] (3,661 samples, 2.79%)[u..[unknown] (3,557 samples, 2.71%)[u..[unknown] (3,416 samples, 2.60%)[u..[unknown] (2,695 samples, 2.05%)[..[unknown] (2,063 samples, 1.57%)[unknown] (891 samples, 0.68%)[unknown] (270 samples, 0.21%)[unknown] (99 samples, 0.08%)[unknown] (94 samples, 0.07%)[unknown] (84 samples, 0.06%)[unknown] (77 samples, 0.06%)[unknown] (25 samples, 0.02%)[unknown] (16 samples, 0.01%)std::sys_common::net::TcpListener::socket_addr::{{closure}} (3,800 samples, 2.89%)st..tokio::net::udp::UdpSocket::local_addr (3,838 samples, 2.92%)to..mio::net::udp::UdpSocket::local_addr (3,838 samples, 2.92%)mi..std::net::tcp::TcpListener::local_addr (3,838 samples, 2.92%)st..std::sys_common::net::TcpListener::socket_addr (3,838 samples, 2.92%)st..std::sys_common::net::sockname (3,835 samples, 2.92%)st..[[vdso]] (60 samples, 0.05%)rand_chacha::guts::ChaCha::pos64 (168 samples, 0.13%)<ppv_lite86::soft::x2<W,G> as core::ops::arith::AddAssign>::add_assign (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::AddAssign>::add_assign (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::Add>::add (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_add_epi32 (26 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_or_si256 (29 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (31 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (31 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (18 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (18 samples, 0.01%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (18 samples, 0.01%)rand_chacha::guts::round (118 samples, 0.09%)rand_chacha::guts::refill_wide::impl_avx2 (312 samples, 0.24%)rand_chacha::guts::refill_wide::fn_impl (312 samples, 0.24%)rand_chacha::guts::refill_wide_impl (312 samples, 0.24%)<rand_chacha::chacha::ChaCha12Core as rand_core::block::BlockRngCore>::generate (384 samples, 0.29%)rand_chacha::guts::ChaCha::refill4 (384 samples, 0.29%)rand::rng::Rng::gen (432 samples, 0.33%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (432 samples, 0.33%)rand::rng::Rng::gen (432 samples, 0.33%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (432 samples, 0.33%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (432 samples, 0.33%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (432 samples, 0.33%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (432 samples, 0.33%)rand_core::block::BlockRng<R>::generate_and_set (392 samples, 0.30%)<rand::rngs::adapter::reseeding::ReseedingCore<R,Rsdr> as rand_core::block::BlockRngCore>::generate (392 samples, 0.30%)torrust_tracker::servers::udp::handlers::RequestId::make (440 samples, 0.34%)uuid::v4::<impl uuid::Uuid>::new_v4 (436 samples, 0.33%)uuid::rng::bytes (435 samples, 0.33%)rand::random (435 samples, 0.33%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (34 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (22 samples, 0.02%)core::iter::traits::iterator::Iterator::collect (16 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (16 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (16 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (16 samples, 0.01%)<core::iter::adapters::cloned::Cloned<I> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)<core::iter::adapters::take::Take<I> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::next (15 samples, 0.01%)core::iter::traits::iterator::Iterator::find (15 samples, 0.01%)core::iter::traits::iterator::Iterator::try_fold (15 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (31 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.03%)core::slice::iter::Iter<T>::post_inc_start (14 samples, 0.01%)core::ptr::non_null::NonNull<T>::add (14 samples, 0.01%)__memcmp_evex_movbe (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (26 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (165 samples, 0.13%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (165 samples, 0.13%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (165 samples, 0.13%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (165 samples, 0.13%)<u8 as core::slice::cmp::SliceOrd>::compare (165 samples, 0.13%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (339 samples, 0.26%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (308 samples, 0.23%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (308 samples, 0.23%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (342 samples, 0.26%)std::sys::sync::rwlock::futex::RwLock::spin_read (25 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_until (25 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read_contended (28 samples, 0.02%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (436 samples, 0.33%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (397 samples, 0.30%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (29 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (29 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (29 samples, 0.02%)__memcmp_evex_movbe (31 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (52 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (52 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (52 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (52 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (52 samples, 0.04%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (103 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (102 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (96 samples, 0.07%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (96 samples, 0.07%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (72 samples, 0.05%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.08%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.08%)core::slice::iter::Iter<T>::post_inc_start (32 samples, 0.02%)core::ptr::non_null::NonNull<T>::add (32 samples, 0.02%)__memcmp_evex_movbe (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (81 samples, 0.06%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (271 samples, 0.21%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (271 samples, 0.21%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (271 samples, 0.21%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (271 samples, 0.21%)<u8 as core::slice::cmp::SliceOrd>::compare (271 samples, 0.21%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (610 samples, 0.46%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (566 samples, 0.43%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (566 samples, 0.43%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut,K,V,Type>::keys (18 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (616 samples, 0.47%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::KV>::split (15 samples, 0.01%)alloc::collections::btree::map::entry::Entry<K,V,A>::or_insert (46 samples, 0.04%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (45 samples, 0.03%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert_recursing (40 samples, 0.03%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert (27 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (29 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (20 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (120 samples, 0.09%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (118 samples, 0.09%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Owned,K,V,alloc::collections::btree::node::marker::Leaf>::new_leaf (118 samples, 0.09%)alloc::collections::btree::node::LeafNode<K,V>::new (118 samples, 0.09%)alloc::boxed::Box<T,A>::new_uninit_in (118 samples, 0.09%)alloc::boxed::Box<T,A>::try_new_uninit_in (118 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (118 samples, 0.09%)alloc::alloc::Global::alloc_impl (118 samples, 0.09%)alloc::alloc::alloc (118 samples, 0.09%)__rdl_alloc (118 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (118 samples, 0.09%)__GI___libc_malloc (118 samples, 0.09%)_int_malloc (107 samples, 0.08%)_int_malloc (28 samples, 0.02%)__GI___libc_malloc (32 samples, 0.02%)__rdl_alloc (36 samples, 0.03%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (36 samples, 0.03%)alloc::sync::Arc<T>::new (42 samples, 0.03%)alloc::boxed::Box<T>::new (42 samples, 0.03%)alloc::alloc::exchange_malloc (39 samples, 0.03%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (39 samples, 0.03%)alloc::alloc::Global::alloc_impl (39 samples, 0.03%)alloc::alloc::alloc (39 samples, 0.03%)core::mem::drop (15 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (15 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (15 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (15 samples, 0.01%)__GI___libc_free (39 samples, 0.03%)_int_free (37 samples, 0.03%)get_max_fast (16 samples, 0.01%)core::option::Option<T>::is_some_and (50 samples, 0.04%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (50 samples, 0.04%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (50 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (50 samples, 0.04%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (290 samples, 0.22%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (284 samples, 0.22%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (255 samples, 0.19%)std::sys::sync::rwlock::futex::RwLock::spin_read (16 samples, 0.01%)std::sys::sync::rwlock::futex::RwLock::spin_until (16 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (21 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (21 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (21 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read_contended (21 samples, 0.02%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (1,147 samples, 0.87%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (1,144 samples, 0.87%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents_mut (32 samples, 0.02%)std::sync::rwlock::RwLock<T>::write (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::write (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::write_contended (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_write (28 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_until (28 samples, 0.02%)torrust_tracker::core::Tracker::announce::{{closure}} (1,597 samples, 1.22%)<core::net::socket_addr::SocketAddrV4 as core::hash::Hash>::hash (14 samples, 0.01%)<core::net::ip_addr::Ipv4Addr as core::hash::Hash>::hash (14 samples, 0.01%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (29 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (24 samples, 0.02%)<core::time::Nanoseconds as core::hash::Hash>::hash (25 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (25 samples, 0.02%)core::hash::Hasher::write_u32 (25 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (25 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (25 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (36 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (37 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (37 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (64 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (39 samples, 0.03%)core::hash::Hasher::write_u64 (39 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (122 samples, 0.09%)core::hash::impls::<impl core::hash::Hash for u64>::hash (58 samples, 0.04%)core::hash::Hasher::write_u64 (58 samples, 0.04%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (58 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (58 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (57 samples, 0.04%)core::hash::sip::u8to64_le (23 samples, 0.02%)core::hash::Hasher::write_length_prefix (27 samples, 0.02%)core::hash::Hasher::write_usize (27 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (16 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (246 samples, 0.19%)core::array::<impl core::hash::Hash for [T: N]>::hash (93 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (93 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (66 samples, 0.05%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (62 samples, 0.05%)core::hash::sip::u8to64_le (17 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::check (285 samples, 0.22%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (36 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (36 samples, 0.03%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (24 samples, 0.02%)std::time::SystemTime::now (19 samples, 0.01%)std::sys::pal::unix::time::SystemTime::now (19 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (1,954 samples, 1.49%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (24 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (18 samples, 0.01%)<core::time::Nanoseconds as core::hash::Hash>::hash (20 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (20 samples, 0.02%)core::hash::Hasher::write_u32 (20 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (20 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (20 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (44 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (65 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (45 samples, 0.03%)core::hash::Hasher::write_u64 (45 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (45 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (45 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (105 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u64>::hash (40 samples, 0.03%)core::hash::Hasher::write_u64 (40 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (40 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (40 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (39 samples, 0.03%)core::hash::Hasher::write_length_prefix (34 samples, 0.03%)core::hash::Hasher::write_usize (34 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (34 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (34 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (33 samples, 0.03%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (231 samples, 0.18%)core::array::<impl core::hash::Hash for [T: N]>::hash (100 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (100 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (66 samples, 0.05%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (61 samples, 0.05%)core::hash::sip::u8to64_le (16 samples, 0.01%)_int_free (16 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (270 samples, 0.21%)torrust_tracker::servers::udp::connection_cookie::make (268 samples, 0.20%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (36 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (35 samples, 0.03%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (31 samples, 0.02%)std::time::SystemTime::now (26 samples, 0.02%)std::sys::pal::unix::time::SystemTime::now (26 samples, 0.02%)torrust_tracker::core::ScrapeData::add_file (19 samples, 0.01%)std::collections::hash::map::HashMap<K,V,S>::insert (19 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (19 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (16 samples, 0.01%)hashbrown::raw::RawTable<T,A>::reserve (16 samples, 0.01%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (17 samples, 0.01%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (17 samples, 0.01%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (17 samples, 0.01%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (17 samples, 0.01%)<u8 as core::slice::cmp::SliceOrd>::compare (17 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (53 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (53 samples, 0.04%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (2,336 samples, 1.78%)t..torrust_tracker::servers::udp::handlers::handle_scrape::{{closure}} (101 samples, 0.08%)torrust_tracker::core::Tracker::scrape::{{closure}} (90 samples, 0.07%)torrust_tracker::core::Tracker::get_swarm_metadata (68 samples, 0.05%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (64 samples, 0.05%)alloc::raw_vec::finish_grow (19 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::grow_amortized (21 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (23 samples, 0.02%)alloc::string::String::push_str (23 samples, 0.02%)alloc::vec::Vec<T,A>::extend_from_slice (23 samples, 0.02%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (23 samples, 0.02%)alloc::vec::Vec<T,A>::append_elements (23 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (85 samples, 0.06%)core::fmt::num::imp::fmt_u64 (78 samples, 0.06%)<alloc::string::String as core::fmt::Write>::write_str (15 samples, 0.01%)alloc::string::String::push_str (15 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (15 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (15 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (15 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (37 samples, 0.03%)core::fmt::num::imp::fmt_u64 (36 samples, 0.03%)<T as alloc::string::ToString>::to_string (141 samples, 0.11%)core::option::Option<T>::expect (34 samples, 0.03%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (28 samples, 0.02%)alloc::alloc::dealloc (28 samples, 0.02%)__rdl_dealloc (28 samples, 0.02%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (28 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (55 samples, 0.04%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (55 samples, 0.04%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (55 samples, 0.04%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (55 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::current_memory (20 samples, 0.02%)torrust_tracker::servers::udp::logging::map_action_name (16 samples, 0.01%)binascii::bin2hex (51 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (16 samples, 0.01%)core::fmt::write (25 samples, 0.02%)core::fmt::rt::Argument::fmt (15 samples, 0.01%)core::fmt::Formatter::write_fmt (87 samples, 0.07%)core::str::converts::from_utf8 (43 samples, 0.03%)core::str::validations::run_utf8_validation (37 samples, 0.03%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (161 samples, 0.12%)<T as alloc::string::ToString>::to_string (161 samples, 0.12%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (156 samples, 0.12%)torrust_tracker::servers::udp::logging::log_request (479 samples, 0.36%)[[vdso]] (51 samples, 0.04%)alloc::raw_vec::finish_grow (56 samples, 0.04%)alloc::vec::Vec<T,A>::reserve (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::reserve (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::grow_amortized (64 samples, 0.05%)<alloc::string::String as core::fmt::Write>::write_str (65 samples, 0.05%)alloc::string::String::push_str (65 samples, 0.05%)alloc::vec::Vec<T,A>::extend_from_slice (65 samples, 0.05%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (65 samples, 0.05%)alloc::vec::Vec<T,A>::append_elements (65 samples, 0.05%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (114 samples, 0.09%)core::fmt::num::imp::fmt_u64 (110 samples, 0.08%)<T as alloc::string::ToString>::to_string (132 samples, 0.10%)core::option::Option<T>::expect (20 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (22 samples, 0.02%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (22 samples, 0.02%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (22 samples, 0.02%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (22 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (8,883 samples, 6.77%)torrust_t..torrust_tracker::servers::udp::logging::log_response (238 samples, 0.18%)__GI___lll_lock_wait_private (14 samples, 0.01%)futex_wait (14 samples, 0.01%)__GI___lll_lock_wake_private (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (17 samples, 0.01%)_int_malloc (191 samples, 0.15%)__libc_calloc (238 samples, 0.18%)__memcpy_avx512_unaligned_erms (34 samples, 0.03%)alloc::vec::from_elem (316 samples, 0.24%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (316 samples, 0.24%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (316 samples, 0.24%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (316 samples, 0.24%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (312 samples, 0.24%)alloc::alloc::Global::alloc_impl (312 samples, 0.24%)alloc::alloc::alloc_zeroed (312 samples, 0.24%)__rdl_alloc_zeroed (312 samples, 0.24%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (312 samples, 0.24%)byteorder::ByteOrder::write_i32 (18 samples, 0.01%)<byteorder::BigEndian as byteorder::ByteOrder>::write_u32 (18 samples, 0.01%)core::num::<impl u32>::to_be_bytes (18 samples, 0.01%)core::num::<impl u32>::to_be (18 samples, 0.01%)core::num::<impl u32>::swap_bytes (18 samples, 0.01%)byteorder::io::WriteBytesExt::write_i32 (89 samples, 0.07%)std::io::Write::write_all (71 samples, 0.05%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (71 samples, 0.05%)std::io::cursor::vec_write (71 samples, 0.05%)std::io::cursor::vec_write_unchecked (51 samples, 0.04%)core::ptr::mut_ptr::<impl *mut T>::copy_from (51 samples, 0.04%)core::intrinsics::copy (51 samples, 0.04%)aquatic_udp_protocol::response::Response::write (227 samples, 0.17%)byteorder::io::WriteBytesExt::write_i64 (28 samples, 0.02%)std::io::Write::write_all (21 samples, 0.02%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (21 samples, 0.02%)std::io::cursor::vec_write (21 samples, 0.02%)std::io::cursor::vec_write_unchecked (21 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::copy_from (21 samples, 0.02%)core::intrinsics::copy (21 samples, 0.02%)__GI___lll_lock_wake_private (17 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (14 samples, 0.01%)__GI___lll_lock_wait_private (16 samples, 0.01%)futex_wait (15 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (136 samples, 0.10%)__GI___libc_free (206 samples, 0.16%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (211 samples, 0.16%)alloc::alloc::dealloc (211 samples, 0.16%)__rdl_dealloc (211 samples, 0.16%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (211 samples, 0.16%)core::ptr::drop_in_place<std::io::cursor::Cursor<alloc::vec::Vec<u8>>> (224 samples, 0.17%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (224 samples, 0.17%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (224 samples, 0.17%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (224 samples, 0.17%)std::io::cursor::Cursor<T>::new (56 samples, 0.04%)tokio::io::ready::Ready::intersection (23 samples, 0.02%)tokio::io::ready::Ready::from_interest (23 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (83 samples, 0.06%)[unknown] (32,674 samples, 24.88%)[unknown][unknown] (32,402 samples, 24.68%)[unknown][unknown] (32,272 samples, 24.58%)[unknown][unknown] (32,215 samples, 24.54%)[unknown][unknown] (31,174 samples, 23.74%)[unknown][unknown] (30,794 samples, 23.45%)[unknown][unknown] (30,036 samples, 22.88%)[unknown][unknown] (28,639 samples, 21.81%)[unknown][unknown] (27,908 samples, 21.25%)[unknown][unknown] (26,013 samples, 19.81%)[unknown][unknown] (23,181 samples, 17.65%)[unknown][unknown] (19,559 samples, 14.90%)[unknown][unknown] (18,052 samples, 13.75%)[unknown][unknown] (15,794 samples, 12.03%)[unknown][unknown] (14,740 samples, 11.23%)[unknown][unknown] (12,486 samples, 9.51%)[unknown][unknown] (11,317 samples, 8.62%)[unknown][unknown] (10,725 samples, 8.17%)[unknown][unknown] (10,017 samples, 7.63%)[unknown][unknown] (9,713 samples, 7.40%)[unknown][unknown] (8,432 samples, 6.42%)[unknown][unknown] (8,062 samples, 6.14%)[unknown][unknown] (6,973 samples, 5.31%)[unknow..[unknown] (5,328 samples, 4.06%)[unk..[unknown] (4,352 samples, 3.31%)[un..[unknown] (3,786 samples, 2.88%)[u..[unknown] (3,659 samples, 2.79%)[u..[unknown] (3,276 samples, 2.50%)[u..[unknown] (2,417 samples, 1.84%)[..[unknown] (2,115 samples, 1.61%)[unknown] (1,610 samples, 1.23%)[unknown] (422 samples, 0.32%)[unknown] (84 samples, 0.06%)[unknown] (69 samples, 0.05%)__GI___pthread_disable_asynccancel (67 samples, 0.05%)__libc_sendto (32,896 samples, 25.05%)__libc_sendtotokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (32,981 samples, 25.12%)tokio::net::udp::UdpSocket::send_to_addr..mio::net::udp::UdpSocket::send_to (32,981 samples, 25.12%)mio::net::udp::UdpSocket::send_tomio::io_source::IoSource<T>::do_io (32,981 samples, 25.12%)mio::io_source::IoSource<T>::do_iomio::sys::unix::stateless_io_source::IoSourceState::do_io (32,981 samples, 25.12%)mio::sys::unix::stateless_io_source::IoS..mio::net::udp::UdpSocket::send_to::{{closure}} (32,981 samples, 25.12%)mio::net::udp::UdpSocket::send_to::{{clo..std::net::udp::UdpSocket::send_to (32,981 samples, 25.12%)std::net::udp::UdpSocket::send_tostd::sys_common::net::UdpSocket::send_to (32,981 samples, 25.12%)std::sys_common::net::UdpSocket::send_tostd::sys::pal::unix::cvt (85 samples, 0.06%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (44,349 samples, 33.78%)torrust_tracker::servers::udp::server::Udp::process_req..torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (43,412 samples, 33.06%)torrust_tracker::servers::udp::server::Udp::process_va..torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (34,320 samples, 26.14%)torrust_tracker::servers::udp::server::Udp..torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (33,360 samples, 25.41%)torrust_tracker::servers::udp::server::Ud..tokio::net::udp::UdpSocket::send_to::{{closure}} (33,227 samples, 25.31%)tokio::net::udp::UdpSocket::send_to::{{c..tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (33,142 samples, 25.24%)tokio::net::udp::UdpSocket::send_to_addr..tokio::runtime::io::registration::Registration::async_io::{{closure}} (33,115 samples, 25.22%)tokio::runtime::io::registration::Regist..tokio::runtime::io::registration::Registration::readiness::{{closure}} (28 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (18 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (15 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (14 samples, 0.01%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (15 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (15 samples, 0.01%)core::sync::atomic::atomic_add (15 samples, 0.01%)__GI___lll_lock_wait_private (16 samples, 0.01%)futex_wait (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (135 samples, 0.10%)__GI___libc_free (147 samples, 0.11%)syscall (22 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Core<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (15 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::dealloc (24 samples, 0.02%)core::mem::drop (24 samples, 0.02%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (24 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (24 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::abort::AbortHandle> (262 samples, 0.20%)<tokio::runtime::task::abort::AbortHandle as core::ops::drop::Drop>::drop (262 samples, 0.20%)tokio::runtime::task::raw::RawTask::drop_abort_handle (256 samples, 0.19%)tokio::runtime::task::raw::drop_abort_handle (59 samples, 0.04%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (50 samples, 0.04%)tokio::runtime::task::state::State::ref_dec (50 samples, 0.04%)tokio::runtime::task::raw::RawTask::drop_join_handle_slow (16 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::join::JoinHandle<()>> (47 samples, 0.04%)<tokio::runtime::task::join::JoinHandle<T> as core::ops::drop::Drop>::drop (47 samples, 0.04%)tokio::runtime::task::state::State::drop_join_handle_fast (19 samples, 0.01%)core::sync::atomic::AtomicUsize::compare_exchange_weak (19 samples, 0.01%)core::sync::atomic::atomic_compare_exchange_weak (19 samples, 0.01%)ringbuf::ring_buffer::base::RbBase::is_full (14 samples, 0.01%)<ringbuf::ring_buffer::shared::SharedRb<T,C> as ringbuf::ring_buffer::base::RbBase<T>>::head (14 samples, 0.01%)core::sync::atomic::AtomicUsize::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)ringbuf::consumer::Consumer<T,R>::advance (29 samples, 0.02%)ringbuf::ring_buffer::base::RbRead::advance_head (29 samples, 0.02%)ringbuf::ring_buffer::rb::Rb::pop (50 samples, 0.04%)ringbuf::consumer::Consumer<T,R>::pop (50 samples, 0.04%)ringbuf::producer::Producer<T,R>::advance (23 samples, 0.02%)ringbuf::ring_buffer::base::RbWrite::advance_tail (23 samples, 0.02%)core::num::nonzero::<impl core::ops::arith::Rem<core::num::nonzero::NonZero<usize>> for usize>::rem (19 samples, 0.01%)ringbuf::ring_buffer::rb::Rb::push_overwrite (107 samples, 0.08%)ringbuf::ring_buffer::rb::Rb::push (43 samples, 0.03%)ringbuf::producer::Producer<T,R>::push (43 samples, 0.03%)tokio::runtime::task::abort::AbortHandle::is_finished (84 samples, 0.06%)tokio::runtime::task::state::Snapshot::is_complete (84 samples, 0.06%)tokio::runtime::task::join::JoinHandle<T>::abort_handle (17 samples, 0.01%)tokio::runtime::task::raw::RawTask::ref_inc (17 samples, 0.01%)tokio::runtime::task::state::State::ref_inc (17 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (14 samples, 0.01%)core::sync::atomic::atomic_add (14 samples, 0.01%)__GI___lll_lock_wake_private (22 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)malloc_consolidate (95 samples, 0.07%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (76 samples, 0.06%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (31 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (26 samples, 0.02%)_int_malloc (282 samples, 0.21%)__GI___libc_malloc (323 samples, 0.25%)alloc::vec::Vec<T>::with_capacity (326 samples, 0.25%)alloc::vec::Vec<T,A>::with_capacity_in (326 samples, 0.25%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (324 samples, 0.25%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (324 samples, 0.25%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (324 samples, 0.25%)alloc::alloc::Global::alloc_impl (324 samples, 0.25%)alloc::alloc::alloc (324 samples, 0.25%)__rdl_alloc (324 samples, 0.25%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (324 samples, 0.25%)tokio::io::ready::Ready::intersection (24 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (199 samples, 0.15%)tokio::util::bit::Pack::unpack (16 samples, 0.01%)tokio::util::bit::unpack (16 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (19 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (17 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (16 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (222 samples, 0.17%)tokio::net::udp::UdpSocket::ready::{{closure}} (222 samples, 0.17%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (50 samples, 0.04%)std::io::error::repr_bitpacked::Repr::data (14 samples, 0.01%)std::io::error::repr_bitpacked::decode_repr (14 samples, 0.01%)std::io::error::Error::kind (16 samples, 0.01%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (14 samples, 0.01%)[unknown] (8,756 samples, 6.67%)[unknown][unknown] (8,685 samples, 6.61%)[unknown][unknown] (8,574 samples, 6.53%)[unknown][unknown] (8,415 samples, 6.41%)[unknown][unknown] (7,686 samples, 5.85%)[unknow..[unknown] (7,239 samples, 5.51%)[unknow..[unknown] (6,566 samples, 5.00%)[unkno..[unknown] (5,304 samples, 4.04%)[unk..[unknown] (4,008 samples, 3.05%)[un..[unknown] (3,571 samples, 2.72%)[u..[unknown] (2,375 samples, 1.81%)[..[unknown] (1,844 samples, 1.40%)[unknown] (1,030 samples, 0.78%)[unknown] (344 samples, 0.26%)[unknown] (113 samples, 0.09%)__libc_recvfrom (8,903 samples, 6.78%)__libc_re..__GI___pthread_disable_asynccancel (22 samples, 0.02%)std::sys::pal::unix::cvt (20 samples, 0.02%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (9,005 samples, 6.86%)tokio::ne..mio::net::udp::UdpSocket::recv_from (8,964 samples, 6.83%)mio::net:..mio::io_source::IoSource<T>::do_io (8,964 samples, 6.83%)mio::io_s..mio::sys::unix::stateless_io_source::IoSourceState::do_io (8,964 samples, 6.83%)mio::sys:..mio::net::udp::UdpSocket::recv_from::{{closure}} (8,964 samples, 6.83%)mio::net:..std::net::udp::UdpSocket::recv_from (8,964 samples, 6.83%)std::net:..std::sys_common::net::UdpSocket::recv_from (8,964 samples, 6.83%)std::sys_..std::sys::pal::unix::net::Socket::recv_from (8,964 samples, 6.83%)std::sys:..std::sys::pal::unix::net::Socket::recv_from_with_flags (8,964 samples, 6.83%)std::sys:..std::sys_common::net::sockaddr_to_addr (23 samples, 0.02%)tokio::runtime::io::registration::Registration::clear_readiness (18 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::clear_readiness (18 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (32 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (9,967 samples, 7.59%)torrust_tr..tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (9,291 samples, 7.08%)tokio::ne..tokio::runtime::io::registration::Registration::async_io::{{closure}} (9,287 samples, 7.07%)tokio::ru..tokio::runtime::io::registration::Registration::readiness::{{closure}} (45 samples, 0.03%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (41 samples, 0.03%)__memcpy_avx512_unaligned_erms (424 samples, 0.32%)__memcpy_avx512_unaligned_erms (493 samples, 0.38%)__memcpy_avx512_unaligned_erms (298 samples, 0.23%)syscall (1,105 samples, 0.84%)[unknown] (1,095 samples, 0.83%)[unknown] (1,091 samples, 0.83%)[unknown] (1,049 samples, 0.80%)[unknown] (998 samples, 0.76%)[unknown] (907 samples, 0.69%)[unknown] (710 samples, 0.54%)[unknown] (635 samples, 0.48%)[unknown] (538 samples, 0.41%)[unknown] (358 samples, 0.27%)[unknown] (256 samples, 0.19%)[unknown] (153 samples, 0.12%)[unknown] (96 samples, 0.07%)[unknown] (81 samples, 0.06%)tokio::runtime::context::with_scheduler (36 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (31 samples, 0.02%)tokio::runtime::context::with_scheduler::{{closure}} (27 samples, 0.02%)tokio::runtime::context::scoped::Scoped<T>::with (27 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (25 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (15 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (340 samples, 0.26%)core::sync::atomic::atomic_add (340 samples, 0.26%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (354 samples, 0.27%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (367 samples, 0.28%)[unknown] (95 samples, 0.07%)[unknown] (93 samples, 0.07%)[unknown] (92 samples, 0.07%)[unknown] (90 samples, 0.07%)[unknown] (82 samples, 0.06%)[unknown] (73 samples, 0.06%)[unknown] (63 samples, 0.05%)[unknown] (44 samples, 0.03%)[unknown] (40 samples, 0.03%)[unknown] (35 samples, 0.03%)[unknown] (30 samples, 0.02%)[unknown] (22 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (17 samples, 0.01%)tokio::runtime::driver::Handle::unpark (99 samples, 0.08%)tokio::runtime::driver::IoHandle::unpark (99 samples, 0.08%)tokio::runtime::io::driver::Handle::unpark (99 samples, 0.08%)mio::waker::Waker::wake (99 samples, 0.08%)mio::sys::unix::waker::fdbased::Waker::wake (99 samples, 0.08%)mio::sys::unix::waker::eventfd::WakerInternal::wake (99 samples, 0.08%)<&std::fs::File as std::io::Write>::write (99 samples, 0.08%)std::sys::pal::unix::fs::File::write (99 samples, 0.08%)std::sys::pal::unix::fd::FileDesc::write (99 samples, 0.08%)__GI___libc_write (99 samples, 0.08%)__GI___libc_write (99 samples, 0.08%)tokio::runtime::context::with_scheduler (1,615 samples, 1.23%)std::thread::local::LocalKey<T>::try_with (1,613 samples, 1.23%)tokio::runtime::context::with_scheduler::{{closure}} (1,612 samples, 1.23%)tokio::runtime::context::scoped::Scoped<T>::with (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (1,609 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (1,609 samples, 1.23%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (101 samples, 0.08%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (101 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_option_task_without_yield (1,647 samples, 1.25%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task (1,646 samples, 1.25%)tokio::runtime::scheduler::multi_thread::worker::with_current (1,646 samples, 1.25%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (23 samples, 0.02%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (18 samples, 0.01%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (104 samples, 0.08%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (60 samples, 0.05%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (57 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (49 samples, 0.04%)core::sync::atomic::AtomicU32::compare_exchange (38 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (38 samples, 0.03%)__memcpy_avx512_unaligned_erms (162 samples, 0.12%)__memcpy_avx512_unaligned_erms (34 samples, 0.03%)__GI___lll_lock_wake_private (127 samples, 0.10%)[unknown] (125 samples, 0.10%)[unknown] (124 samples, 0.09%)[unknown] (119 samples, 0.09%)[unknown] (110 samples, 0.08%)[unknown] (106 samples, 0.08%)[unknown] (87 samples, 0.07%)[unknown] (82 samples, 0.06%)[unknown] (51 samples, 0.04%)[unknown] (27 samples, 0.02%)[unknown] (19 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (77 samples, 0.06%)[unknown] (1,207 samples, 0.92%)[unknown] (1,146 samples, 0.87%)[unknown] (1,126 samples, 0.86%)[unknown] (1,091 samples, 0.83%)[unknown] (1,046 samples, 0.80%)[unknown] (962 samples, 0.73%)[unknown] (914 samples, 0.70%)[unknown] (848 samples, 0.65%)[unknown] (774 samples, 0.59%)[unknown] (580 samples, 0.44%)[unknown] (456 samples, 0.35%)[unknown] (305 samples, 0.23%)[unknown] (85 samples, 0.06%)__GI_mprotect (2,474 samples, 1.88%)_..[unknown] (2,457 samples, 1.87%)[..[unknown] (2,440 samples, 1.86%)[..[unknown] (2,436 samples, 1.86%)[..[unknown] (2,435 samples, 1.85%)[..[unknown] (2,360 samples, 1.80%)[..[unknown] (2,203 samples, 1.68%)[unknown] (1,995 samples, 1.52%)[unknown] (1,709 samples, 1.30%)[unknown] (1,524 samples, 1.16%)[unknown] (1,193 samples, 0.91%)[unknown] (865 samples, 0.66%)[unknown] (539 samples, 0.41%)[unknown] (259 samples, 0.20%)[unknown] (80 samples, 0.06%)[unknown] (29 samples, 0.02%)sysmalloc (3,786 samples, 2.88%)sy..grow_heap (2,509 samples, 1.91%)g.._int_malloc (4,038 samples, 3.08%)_in..unlink_chunk (31 samples, 0.02%)alloc::alloc::exchange_malloc (4,335 samples, 3.30%)all..<alloc::alloc::Global as core::alloc::Allocator>::allocate (4,329 samples, 3.30%)<al..alloc::alloc::Global::alloc_impl (4,329 samples, 3.30%)all..alloc::alloc::alloc (4,329 samples, 3.30%)all..__rdl_alloc (4,329 samples, 3.30%)__r..std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (4,329 samples, 3.30%)std..std::sys::pal::unix::alloc::aligned_malloc (4,329 samples, 3.30%)std..__posix_memalign (4,297 samples, 3.27%)__p..__posix_memalign (4,297 samples, 3.27%)__p.._mid_memalign (4,297 samples, 3.27%)_mi.._int_memalign (4,149 samples, 3.16%)_in..sysmalloc (18 samples, 0.01%)core::option::Option<T>::map (6,666 samples, 5.08%)core::..tokio::task::spawn::spawn_inner::{{closure}} (6,665 samples, 5.08%)tokio:..tokio::runtime::scheduler::Handle::spawn (6,665 samples, 5.08%)tokio:..tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (6,664 samples, 5.08%)tokio:..tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (6,661 samples, 5.07%)tokio:..tokio::runtime::task::list::OwnedTasks<S>::bind (4,692 samples, 3.57%)toki..tokio::runtime::task::new_task (4,579 samples, 3.49%)tok..tokio::runtime::task::raw::RawTask::new (4,579 samples, 3.49%)tok..tokio::runtime::task::core::Cell<T,S>::new (4,579 samples, 3.49%)tok..alloc::boxed::Box<T>::new (4,389 samples, 3.34%)all..tokio::runtime::context::current::with_current (7,636 samples, 5.82%)tokio::..std::thread::local::LocalKey<T>::try_with (7,635 samples, 5.81%)std::th..tokio::runtime::context::current::with_current::{{closure}} (7,188 samples, 5.47%)tokio::..tokio::task::spawn::spawn (7,670 samples, 5.84%)tokio::..tokio::task::spawn::spawn_inner (7,670 samples, 5.84%)tokio::..tokio::runtime::task::id::Id::next (24 samples, 0.02%)core::sync::atomic::AtomicU64::fetch_add (24 samples, 0.02%)core::sync::atomic::atomic_add (24 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (62,691 samples, 47.75%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (62,691 samples, 47.75%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (18,228 samples, 13.88%)torrust_tracker::serv..torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (18,226 samples, 13.88%)torrust_tracker::serv..torrust_tracker::servers::udp::server::Udp::spawn_request_processor (7,679 samples, 5.85%)torrust..__memcpy_avx512_unaligned_erms (38 samples, 0.03%)__memcpy_avx512_unaligned_erms (407 samples, 0.31%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (411 samples, 0.31%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (411 samples, 0.31%)tokio::runtime::task::core::Core<T,S>::poll (63,150 samples, 48.10%)tokio::runtime::task::core::Core<T,S>::polltokio::runtime::task::core::Core<T,S>::drop_future_or_output (459 samples, 0.35%)tokio::runtime::task::core::Core<T,S>::set_stage (459 samples, 0.35%)__memcpy_avx512_unaligned_erms (16 samples, 0.01%)__memcpy_avx512_unaligned_erms (398 samples, 0.30%)__memcpy_avx512_unaligned_erms (325 samples, 0.25%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (330 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (330 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::set_stage (731 samples, 0.56%)tokio::runtime::task::harness::poll_future (63,908 samples, 48.67%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (63,908 samples, 48.67%)std::panic::catch_unwindstd::panicking::try (63,908 samples, 48.67%)std::panicking::trystd::panicking::try::do_call (63,908 samples, 48.67%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (63,908 samples, 48.67%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()..tokio::runtime::task::harness::poll_future::{{closure}} (63,908 samples, 48.67%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::store_output (758 samples, 0.58%)tokio::runtime::coop::budget (65,027 samples, 49.53%)tokio::runtime::coop::budgettokio::runtime::coop::with_budget (65,027 samples, 49.53%)tokio::runtime::coop::with_budgettokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (65,009 samples, 49.51%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}}tokio::runtime::task::LocalNotified<S>::run (65,003 samples, 49.51%)tokio::runtime::task::LocalNotified<S>::runtokio::runtime::task::raw::RawTask::poll (65,003 samples, 49.51%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (64,538 samples, 49.15%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (64,493 samples, 49.12%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (63,919 samples, 48.68%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (93 samples, 0.07%)syscall (2,486 samples, 1.89%)s..[unknown] (2,424 samples, 1.85%)[..[unknown] (2,416 samples, 1.84%)[..[unknown] (2,130 samples, 1.62%)[unknown] (2,013 samples, 1.53%)[unknown] (1,951 samples, 1.49%)[unknown] (1,589 samples, 1.21%)[unknown] (1,415 samples, 1.08%)[unknown] (1,217 samples, 0.93%)[unknown] (820 samples, 0.62%)[unknown] (564 samples, 0.43%)[unknown] (360 samples, 0.27%)[unknown] (244 samples, 0.19%)[unknown] (194 samples, 0.15%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (339 samples, 0.26%)core::sync::atomic::AtomicUsize::fetch_add (337 samples, 0.26%)core::sync::atomic::atomic_add (337 samples, 0.26%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (364 samples, 0.28%)[unknown] (154 samples, 0.12%)[unknown] (152 samples, 0.12%)[unknown] (143 samples, 0.11%)[unknown] (139 samples, 0.11%)[unknown] (131 samples, 0.10%)[unknown] (123 samples, 0.09%)[unknown] (110 samples, 0.08%)[unknown] (80 samples, 0.06%)[unknown] (74 samples, 0.06%)[unknown] (65 samples, 0.05%)[unknown] (64 samples, 0.05%)[unknown] (47 samples, 0.04%)[unknown] (44 samples, 0.03%)[unknown] (43 samples, 0.03%)[unknown] (40 samples, 0.03%)[unknown] (26 samples, 0.02%)[unknown] (20 samples, 0.02%)__GI___libc_write (158 samples, 0.12%)__GI___libc_write (158 samples, 0.12%)mio::sys::unix::waker::eventfd::WakerInternal::wake (159 samples, 0.12%)<&std::fs::File as std::io::Write>::write (159 samples, 0.12%)std::sys::pal::unix::fs::File::write (159 samples, 0.12%)std::sys::pal::unix::fd::FileDesc::write (159 samples, 0.12%)tokio::runtime::driver::Handle::unpark (168 samples, 0.13%)tokio::runtime::driver::IoHandle::unpark (168 samples, 0.13%)tokio::runtime::io::driver::Handle::unpark (168 samples, 0.13%)mio::waker::Waker::wake (165 samples, 0.13%)mio::sys::unix::waker::fdbased::Waker::wake (165 samples, 0.13%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (68,159 samples, 51.91%)tokio::runtime::scheduler::multi_thread::worker::Context::run_tasktokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (3,024 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (3,023 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (3,022 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (171 samples, 0.13%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (171 samples, 0.13%)core::option::Option<T>::or_else (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::tune_global_queue_interval (53 samples, 0.04%)tokio::runtime::scheduler::multi_thread::stats::Stats::tuned_global_queue_interval (53 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (107 samples, 0.08%)__GI___libc_free (17 samples, 0.01%)_int_free (17 samples, 0.01%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Dying,K,V>::deallocating_end (18 samples, 0.01%)alloc::collections::btree::navigate::<impl alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>>::deallocating_end (18 samples, 0.01%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::LeafOrInternal>::deallocate_and_ascend (18 samples, 0.01%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (18 samples, 0.01%)alloc::alloc::dealloc (18 samples, 0.01%)__rdl_dealloc (18 samples, 0.01%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (18 samples, 0.01%)alloc::collections::btree::map::IntoIter<K,V,A>::dying_next (19 samples, 0.01%)tokio::runtime::task::Task<S>::shutdown (26 samples, 0.02%)tokio::runtime::task::raw::RawTask::shutdown (26 samples, 0.02%)tokio::runtime::task::raw::shutdown (26 samples, 0.02%)tokio::runtime::task::harness::Harness<T,S>::shutdown (26 samples, 0.02%)tokio::runtime::task::harness::cancel_task (26 samples, 0.02%)std::panic::catch_unwind (26 samples, 0.02%)std::panicking::try (26 samples, 0.02%)std::panicking::try::do_call (26 samples, 0.02%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (26 samples, 0.02%)core::ops::function::FnOnce::call_once (26 samples, 0.02%)tokio::runtime::task::harness::cancel_task::{{closure}} (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (26 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (26 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::core::Tracker> (26 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)core::ptr::drop_in_place<std::sync::rwlock::RwLock<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)core::mem::drop (26 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,NodeType>,alloc::collections::btree::node::marker::KV>::drop_key_val (24 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::assume_init_drop (24 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (24 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (21 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>> (20 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<torrust_tracker_torrent_repository::entry::Torrent>> (20 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker_torrent_repository::entry::Torrent> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::peer::Id,alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (20 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)core::mem::drop (20 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker_primitives::peer::Id,alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (20 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::pre_shutdown (33 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::close_and_shutdown_all (33 samples, 0.03%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (114 samples, 0.09%)alloc::sync::Arc<T,A>::inner (114 samples, 0.09%)core::ptr::non_null::NonNull<T>::as_ref (114 samples, 0.09%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (108 samples, 0.08%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (108 samples, 0.08%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (106 samples, 0.08%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (49 samples, 0.04%)alloc::sync::Arc<T,A>::inner (49 samples, 0.04%)core::ptr::non_null::NonNull<T>::as_ref (49 samples, 0.04%)core::num::<impl u32>::wrapping_sub (132 samples, 0.10%)core::sync::atomic::AtomicU64::load (40 samples, 0.03%)core::sync::atomic::atomic_load (40 samples, 0.03%)tokio::loom::std::atomic_u32::AtomicU32::unsync_load (48 samples, 0.04%)core::sync::atomic::AtomicU32::load (48 samples, 0.04%)core::sync::atomic::atomic_load (48 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (65 samples, 0.05%)alloc::sync::Arc<T,A>::inner (65 samples, 0.05%)core::ptr::non_null::NonNull<T>::as_ref (65 samples, 0.05%)core::num::<impl u32>::wrapping_sub (50 samples, 0.04%)core::sync::atomic::AtomicU32::load (55 samples, 0.04%)core::sync::atomic::atomic_load (55 samples, 0.04%)core::sync::atomic::AtomicU64::load (80 samples, 0.06%)core::sync::atomic::atomic_load (80 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::pack (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (666 samples, 0.51%)tokio::runtime::scheduler::multi_thread::queue::unpack (147 samples, 0.11%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (1,036 samples, 0.79%)tokio::runtime::scheduler::multi_thread::queue::unpack (46 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_searching (49 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_searching (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (2,414 samples, 1.84%)t..tokio::util::rand::FastRand::fastrand_n (24 samples, 0.02%)tokio::util::rand::FastRand::fastrand (24 samples, 0.02%)std::sys_common::backtrace::__rust_begin_short_backtrace (98,136 samples, 74.74%)std::sys_common::backtrace::__rust_begin_short_backtracetokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}} (98,136 samples, 74.74%)tokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}}tokio::runtime::blocking::pool::Inner::run (98,136 samples, 74.74%)tokio::runtime::blocking::pool::Inner::runtokio::runtime::blocking::pool::Task::run (98,042 samples, 74.67%)tokio::runtime::blocking::pool::Task::runtokio::runtime::task::UnownedTask<S>::run (98,042 samples, 74.67%)tokio::runtime::task::UnownedTask<S>::runtokio::runtime::task::raw::RawTask::poll (98,042 samples, 74.67%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (98,042 samples, 74.67%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (98,042 samples, 74.67%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (98,042 samples, 74.67%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::task::harness::poll_future (98,042 samples, 74.67%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (98,042 samples, 74.67%)std::panic::catch_unwindstd::panicking::try (98,042 samples, 74.67%)std::panicking::trystd::panicking::try::do_call (98,042 samples, 74.67%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (98,042 samples, 74.67%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncetokio::runtime::task::harness::poll_future::{{closure}} (98,042 samples, 74.67%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::poll (98,042 samples, 74.67%)tokio::runtime::task::core::Core<T,S>::polltokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (98,042 samples, 74.67%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (98,042 samples, 74.67%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (98,042 samples, 74.67%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::polltokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}}tokio::runtime::scheduler::multi_thread::worker::run (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::runtokio::runtime::context::runtime::enter_runtime (98,042 samples, 74.67%)tokio::runtime::context::runtime::enter_runtimetokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}tokio::runtime::context::set_scheduler (98,042 samples, 74.67%)tokio::runtime::context::set_schedulerstd::thread::local::LocalKey<T>::with (98,042 samples, 74.67%)std::thread::local::LocalKey<T>::withstd::thread::local::LocalKey<T>::try_with (98,042 samples, 74.67%)std::thread::local::LocalKey<T>::try_withtokio::runtime::context::set_scheduler::{{closure}} (98,042 samples, 74.67%)tokio::runtime::context::set_scheduler::{{closure}}tokio::runtime::context::scoped::Scoped<T>::set (98,042 samples, 74.67%)tokio::runtime::context::scoped::Scoped<T>::settokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}}tokio::runtime::scheduler::multi_thread::worker::Context::run (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::Context::runstd::panic::catch_unwind (98,137 samples, 74.74%)std::panic::catch_unwindstd::panicking::try (98,137 samples, 74.74%)std::panicking::trystd::panicking::try::do_call (98,137 samples, 74.74%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (98,137 samples, 74.74%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncestd::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}} (98,137 samples, 74.74%)std::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}}<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (98,139 samples, 74.74%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (98,139 samples, 74.74%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_oncecore::ops::function::FnOnce::call_once{{vtable.shim}} (98,139 samples, 74.74%)core::ops::function::FnOnce::call_once{{vtable.shim}}std::thread::Builder::spawn_unchecked_::{{closure}} (98,139 samples, 74.74%)std::thread::Builder::spawn_unchecked_::{{closure}}clone3 (98,205 samples, 74.79%)clone3start_thread (98,205 samples, 74.79%)start_threadstd::sys::pal::unix::thread::Thread::new::thread_start (98,158 samples, 74.76%)std::sys::pal::unix::thread::Thread::new::thread_startcore::ptr::drop_in_place<std::sys::pal::unix::stack_overflow::Handler> (19 samples, 0.01%)<std::sys::pal::unix::stack_overflow::Handler as core::ops::drop::Drop>::drop (19 samples, 0.01%)std::sys::pal::unix::stack_overflow::imp::drop_handler (19 samples, 0.01%)__GI_munmap (19 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (17 samples, 0.01%)[unknown] (16 samples, 0.01%)core::fmt::Formatter::pad_integral (112 samples, 0.09%)core::fmt::Formatter::pad_integral::write_prefix (59 samples, 0.04%)core::fmt::Formatter::pad_integral (16 samples, 0.01%)core::fmt::write (20 samples, 0.02%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (19 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (51 samples, 0.04%)rand_chacha::guts::round (18 samples, 0.01%)rand_chacha::guts::refill_wide::impl_avx2 (26 samples, 0.02%)rand_chacha::guts::refill_wide::fn_impl (26 samples, 0.02%)rand_chacha::guts::refill_wide_impl (26 samples, 0.02%)rand_chacha::guts::refill_wide (14 samples, 0.01%)std_detect::detect::arch::x86::__is_feature_detected::avx2 (14 samples, 0.01%)std_detect::detect::check_for (14 samples, 0.01%)std_detect::detect::cache::test (14 samples, 0.01%)std_detect::detect::cache::Cache::test (14 samples, 0.01%)core::sync::atomic::AtomicUsize::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)core::cell::RefCell<T>::borrow_mut (81 samples, 0.06%)core::cell::RefCell<T>::try_borrow_mut (81 samples, 0.06%)core::cell::BorrowRefMut::new (81 samples, 0.06%)std::sys::pal::unix::time::Timespec::now (164 samples, 0.12%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (106 samples, 0.08%)tokio::runtime::coop::budget (105 samples, 0.08%)tokio::runtime::coop::with_budget (105 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (96 samples, 0.07%)std::sys::pal::unix::time::Timespec::sub_timespec (35 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::lock_contended (15 samples, 0.01%)syscall (90 samples, 0.07%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (21 samples, 0.02%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run (61 samples, 0.05%)tokio::runtime::context::runtime::enter_runtime (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (61 samples, 0.05%)tokio::runtime::context::set_scheduler (61 samples, 0.05%)std::thread::local::LocalKey<T>::with (61 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (61 samples, 0.05%)tokio::runtime::context::set_scheduler::{{closure}} (61 samples, 0.05%)tokio::runtime::context::scoped::Scoped<T>::set (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Context::run (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (19 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (17 samples, 0.01%)tokio::runtime::context::CONTEXT::__getit (14 samples, 0.01%)core::cell::Cell<T>::get (14 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (22 samples, 0.02%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (22 samples, 0.02%)tokio::runtime::context::set_current_task_id (22 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (22 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (112 samples, 0.09%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (111 samples, 0.08%)tokio::runtime::task::harness::poll_future (125 samples, 0.10%)std::panic::catch_unwind (125 samples, 0.10%)std::panicking::try (125 samples, 0.10%)std::panicking::try::do_call (125 samples, 0.10%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (125 samples, 0.10%)tokio::runtime::task::harness::poll_future::{{closure}} (125 samples, 0.10%)tokio::runtime::task::core::Core<T,S>::poll (125 samples, 0.10%)tokio::runtime::task::raw::poll (157 samples, 0.12%)tokio::runtime::task::harness::Harness<T,S>::poll (135 samples, 0.10%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (135 samples, 0.10%)tokio::runtime::time::Driver::park_internal (15 samples, 0.01%)torrust_tracker::bootstrap::logging::INIT (17 samples, 0.01%)__memcpy_avx512_unaligned_erms (397 samples, 0.30%)_int_free (24 samples, 0.02%)_int_malloc (132 samples, 0.10%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE::META (570 samples, 0.43%)__GI___lll_lock_wait_private (22 samples, 0.02%)futex_wait (14 samples, 0.01%)__memcpy_avx512_unaligned_erms (299 samples, 0.23%)_int_free (16 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE (361 samples, 0.27%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (41 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (23 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (53 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (14 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (63 samples, 0.05%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (21 samples, 0.02%)__GI___libc_malloc (18 samples, 0.01%)alloc::vec::Vec<T>::with_capacity (116 samples, 0.09%)alloc::vec::Vec<T,A>::with_capacity_in (116 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (116 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (116 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (116 samples, 0.09%)alloc::alloc::Global::alloc_impl (116 samples, 0.09%)alloc::alloc::alloc (116 samples, 0.09%)__rdl_alloc (116 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (116 samples, 0.09%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (53 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (53 samples, 0.04%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (53 samples, 0.04%)_int_malloc (21 samples, 0.02%)[unknown] (36 samples, 0.03%)[unknown] (16 samples, 0.01%)core::mem::zeroed (27 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::zeroed (27 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::write_bytes (27 samples, 0.02%)core::intrinsics::write_bytes (27 samples, 0.02%)[unknown] (27 samples, 0.02%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (64 samples, 0.05%)mio::net::udp::UdpSocket::recv_from (49 samples, 0.04%)mio::io_source::IoSource<T>::do_io (49 samples, 0.04%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (49 samples, 0.04%)mio::net::udp::UdpSocket::recv_from::{{closure}} (49 samples, 0.04%)std::net::udp::UdpSocket::recv_from (49 samples, 0.04%)std::sys_common::net::UdpSocket::recv_from (49 samples, 0.04%)std::sys::pal::unix::net::Socket::recv_from (49 samples, 0.04%)std::sys::pal::unix::net::Socket::recv_from_with_flags (49 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (271 samples, 0.21%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (143 samples, 0.11%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (141 samples, 0.11%)tokio::runtime::io::registration::Registration::clear_readiness (15 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::clear_readiness (15 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (15 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (359 samples, 0.27%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (346 samples, 0.26%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (39 samples, 0.03%)tokio::task::spawn::spawn (39 samples, 0.03%)tokio::task::spawn::spawn_inner (39 samples, 0.03%)tokio::runtime::context::current::with_current (39 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (39 samples, 0.03%)tokio::runtime::context::current::with_current::{{closure}} (39 samples, 0.03%)core::option::Option<T>::map (39 samples, 0.03%)tokio::task::spawn::spawn_inner::{{closure}} (39 samples, 0.03%)tokio::runtime::scheduler::Handle::spawn (39 samples, 0.03%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (39 samples, 0.03%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (39 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::bind (34 samples, 0.03%)all (131,301 samples, 100%)tokio-runtime-w (131,061 samples, 99.82%)tokio-runtime-w \ No newline at end of file +]]>Flame Graph Reset ZoomSearch [unknown] (188 samples, 0.14%)[unknown] (187 samples, 0.14%)[unknown] (186 samples, 0.14%)[unknown] (178 samples, 0.14%)[unknown] (172 samples, 0.13%)[unknown] (158 samples, 0.12%)[unknown] (158 samples, 0.12%)[unknown] (125 samples, 0.10%)[unknown] (102 samples, 0.08%)[unknown] (93 samples, 0.07%)[unknown] (92 samples, 0.07%)[unknown] (41 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (29 samples, 0.02%)[unknown] (25 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (15 samples, 0.01%)__GI___mmap64 (18 samples, 0.01%)__GI___mmap64 (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (17 samples, 0.01%)profiling (214 samples, 0.16%)clone3 (22 samples, 0.02%)start_thread (22 samples, 0.02%)std::sys::pal::unix::thread::Thread::new::thread_start (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::Handler::new (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::imp::make_handler (20 samples, 0.02%)std::sys::pal::unix::stack_overflow::imp::get_stack (19 samples, 0.01%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (30 samples, 0.02%)[[vdso]] (93 samples, 0.07%)<torrust_tracker::shared::crypto::ephemeral_instance_keys::RANDOM_SEED as core::ops::deref::Deref>::deref::__stability::LAZY (143 samples, 0.11%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (31 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<BorrowType,K,V>::init_front (21 samples, 0.02%)[[vdso]] (91 samples, 0.07%)__GI___clock_gettime (14 samples, 0.01%)_int_malloc (53 samples, 0.04%)epoll_wait (254 samples, 0.19%)tokio::runtime::context::with_scheduler (28 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.01%)tokio::runtime::context::with_scheduler::{{closure}} (14 samples, 0.01%)core::option::Option<T>::map (17 samples, 0.01%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (17 samples, 0.01%)mio::poll::Poll::poll (27 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select (27 samples, 0.02%)tokio::runtime::io::driver::Driver::turn (54 samples, 0.04%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (26 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (17 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (71 samples, 0.05%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (65 samples, 0.05%)core::sync::atomic::AtomicUsize::fetch_add (65 samples, 0.05%)core::sync::atomic::atomic_add (65 samples, 0.05%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (31 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark_condvar (18 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (49 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (33 samples, 0.03%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (93 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Parker::park (75 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Inner::park (75 samples, 0.06%)core::cell::RefCell<T>::borrow_mut (18 samples, 0.01%)core::cell::RefCell<T>::try_borrow_mut (18 samples, 0.01%)core::cell::BorrowRefMut::new (18 samples, 0.01%)tokio::runtime::coop::budget (26 samples, 0.02%)tokio::runtime::coop::with_budget (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (96 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (27 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (18 samples, 0.01%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (35 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (14 samples, 0.01%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (90 samples, 0.07%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (90 samples, 0.07%)core::slice::<impl [T]>::contains (220 samples, 0.17%)<T as core::slice::cmp::SliceContains>::slice_contains (220 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (220 samples, 0.17%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (54 samples, 0.04%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (54 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (240 samples, 0.18%)tokio::runtime::scheduler::multi_thread::idle::Idle::unpark_worker_by_id (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (265 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Context::park (284 samples, 0.22%)core::option::Option<T>::or_else (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (40 samples, 0.03%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (17 samples, 0.01%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (17 samples, 0.01%)core::num::<impl u32>::wrapping_add (17 samples, 0.01%)core::sync::atomic::AtomicU64::compare_exchange (26 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (129 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (128 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (119 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::pack (39 samples, 0.03%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run (613 samples, 0.47%)tokio::runtime::context::runtime::enter_runtime (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (613 samples, 0.47%)tokio::runtime::context::set_scheduler (613 samples, 0.47%)std::thread::local::LocalKey<T>::with (613 samples, 0.47%)std::thread::local::LocalKey<T>::try_with (613 samples, 0.47%)tokio::runtime::context::set_scheduler::{{closure}} (613 samples, 0.47%)tokio::runtime::context::scoped::Scoped<T>::set (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (613 samples, 0.47%)tokio::runtime::scheduler::multi_thread::worker::Context::run (613 samples, 0.47%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (777 samples, 0.59%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (776 samples, 0.59%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (16 samples, 0.01%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (16 samples, 0.01%)tokio::runtime::context::set_current_task_id (16 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (16 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (20 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (20 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::poll (835 samples, 0.64%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (56 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage (46 samples, 0.04%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (897 samples, 0.68%)tokio::runtime::task::harness::poll_future::{{closure}} (897 samples, 0.68%)tokio::runtime::task::core::Core<T,S>::store_output (62 samples, 0.05%)tokio::runtime::task::harness::poll_future (930 samples, 0.71%)std::panic::catch_unwind (927 samples, 0.71%)std::panicking::try (927 samples, 0.71%)std::panicking::try::do_call (925 samples, 0.70%)core::mem::manually_drop::ManuallyDrop<T>::take (28 samples, 0.02%)core::ptr::read (28 samples, 0.02%)tokio::runtime::task::raw::poll (938 samples, 0.71%)tokio::runtime::task::harness::Harness<T,S>::poll (934 samples, 0.71%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (934 samples, 0.71%)core::array::<impl core::default::Default for [T: 32]>::default (26 samples, 0.02%)tokio::runtime::time::Inner::lock (16 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (15 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::time::wheel::Wheel::poll (25 samples, 0.02%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (98 samples, 0.07%)tokio::runtime::time::Driver::park_internal (51 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (15 samples, 0.01%)<F as core::future::into_future::IntoFuture>::into_future (16 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (24 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (46 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (131 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (24 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (14 samples, 0.01%)core::sync::atomic::AtomicU32::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (39 samples, 0.03%)std::sync::rwlock::RwLock<T>::read (34 samples, 0.03%)std::sys::sync::rwlock::futex::RwLock::read (32 samples, 0.02%)[[heap]] (2,361 samples, 1.80%)[..[[vdso]] (313 samples, 0.24%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (41 samples, 0.03%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (28 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (16 samples, 0.01%)<alloc::string::String as core::fmt::Write>::write_str (67 samples, 0.05%)alloc::string::String::push_str (18 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (18 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (18 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (18 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (36 samples, 0.03%)core::num::<impl u64>::rotate_left (28 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (60 samples, 0.05%)core::num::<impl u64>::wrapping_add (14 samples, 0.01%)core::hash::sip::u8to64_le (60 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (184 samples, 0.14%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (15 samples, 0.01%)tokio::runtime::context::CONTEXT::__getit (19 samples, 0.01%)core::cell::Cell<T>::get (17 samples, 0.01%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (26 samples, 0.02%)core::ops::function::FnMut::call_mut (21 samples, 0.02%)tokio::runtime::coop::poll_proceed (21 samples, 0.02%)tokio::runtime::context::budget (21 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (21 samples, 0.02%)[unknown] (18 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (195 samples, 0.15%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (14 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (14 samples, 0.01%)core::result::Result<T,E>::is_err (18 samples, 0.01%)core::result::Result<T,E>::is_ok (18 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (46 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (39 samples, 0.03%)core::sync::atomic::AtomicU32::compare_exchange (19 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (19 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (245 samples, 0.19%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (26 samples, 0.02%)[[vdso]] (748 samples, 0.57%)[profiling] (34 samples, 0.03%)core::fmt::write (31 samples, 0.02%)__GI___clock_gettime (29 samples, 0.02%)__GI___libc_free (131 samples, 0.10%)arena_for_chunk (20 samples, 0.02%)arena_for_chunk (19 samples, 0.01%)heap_for_ptr (19 samples, 0.01%)heap_max_size (14 samples, 0.01%)__GI___libc_malloc (114 samples, 0.09%)__GI___libc_realloc (15 samples, 0.01%)__GI___lll_lock_wake_private (22 samples, 0.02%)__GI___pthread_disable_asynccancel (66 samples, 0.05%)__GI_getsockname (249 samples, 0.19%)__libc_calloc (15 samples, 0.01%)__libc_recvfrom (23 samples, 0.02%)__libc_sendto (130 samples, 0.10%)__memcmp_evex_movbe (451 samples, 0.34%)__memcpy_avx512_unaligned_erms (426 samples, 0.32%)__memset_avx512_unaligned_erms (215 samples, 0.16%)__posix_memalign (17 samples, 0.01%)_int_free (418 samples, 0.32%)tcache_put (24 samples, 0.02%)_int_malloc (385 samples, 0.29%)_int_memalign (31 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (26 samples, 0.02%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (15 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (15 samples, 0.01%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (15 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (54 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::grow_one (15 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (96 samples, 0.07%)alloc::raw_vec::RawVec<T,A>::grow_amortized (66 samples, 0.05%)core::num::<impl usize>::checked_add (18 samples, 0.01%)core::num::<impl usize>::overflowing_add (18 samples, 0.01%)alloc::raw_vec::finish_grow (74 samples, 0.06%)alloc::sync::Arc<T,A>::drop_slow (16 samples, 0.01%)core::mem::drop (14 samples, 0.01%)core::fmt::Formatter::pad_integral (14 samples, 0.01%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (93 samples, 0.07%)core::ptr::drop_in_place<tokio::net::udp::UdpSocket::send_to<&core::net::socket_addr::SocketAddr>::{{closure}}> (23 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (188 samples, 0.14%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_announce::{{closure}}> (30 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_connect::{{closure}}> (22 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_packet::{{closure}}> (20 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}}> (19 samples, 0.01%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::send_response::{{closure}}> (22 samples, 0.02%)malloc_consolidate (24 samples, 0.02%)core::core_arch::x86::avx2::_mm256_or_si256 (15 samples, 0.01%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (17 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (17 samples, 0.01%)rand_chacha::guts::round (66 samples, 0.05%)rand_chacha::guts::refill_wide::impl_avx2 (99 samples, 0.08%)rand_chacha::guts::refill_wide::fn_impl (98 samples, 0.07%)rand_chacha::guts::refill_wide_impl (98 samples, 0.07%)std::io::error::Error::kind (14 samples, 0.01%)[unknown] (42 samples, 0.03%)[unknown] (14 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (490 samples, 0.37%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (211 samples, 0.16%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (84 samples, 0.06%)tokio::runtime::task::core::Header::get_owner_id (18 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (18 samples, 0.01%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (20 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::remove (19 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (31 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (29 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (108 samples, 0.08%)tokio::runtime::task::core::TaskIdGuard::enter (14 samples, 0.01%)tokio::runtime::context::set_current_task_id (14 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (14 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::complete (21 samples, 0.02%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (32 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (54 samples, 0.04%)tokio::runtime::task::raw::drop_abort_handle (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (17 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (22 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (22 samples, 0.02%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (79 samples, 0.06%)core::slice::<impl [T]>::contains (178 samples, 0.14%)<T as core::slice::cmp::SliceContains>::slice_contains (178 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (178 samples, 0.14%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (40 samples, 0.03%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (40 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (216 samples, 0.16%)tokio::loom::std::mutex::Mutex<T>::lock (16 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (219 samples, 0.17%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (29 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (29 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (54 samples, 0.04%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (18 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (18 samples, 0.01%)core::sync::atomic::AtomicU32::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (113 samples, 0.09%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (51 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (41 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (31 samples, 0.02%)core::sync::atomic::AtomicU64::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (447 samples, 0.34%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (174 samples, 0.13%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (19 samples, 0.01%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (489 samples, 0.37%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (489 samples, 0.37%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run (484 samples, 0.37%)tokio::runtime::context::runtime::enter_runtime (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (484 samples, 0.37%)tokio::runtime::context::set_scheduler (484 samples, 0.37%)std::thread::local::LocalKey<T>::with (484 samples, 0.37%)std::thread::local::LocalKey<T>::try_with (484 samples, 0.37%)tokio::runtime::context::set_scheduler::{{closure}} (484 samples, 0.37%)tokio::runtime::context::scoped::Scoped<T>::set (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Context::run (484 samples, 0.37%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (24 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (20 samples, 0.02%)tokio::runtime::task::raw::poll (515 samples, 0.39%)tokio::runtime::task::harness::Harness<T,S>::poll (493 samples, 0.38%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (493 samples, 0.38%)tokio::runtime::task::harness::poll_future (493 samples, 0.38%)std::panic::catch_unwind (493 samples, 0.38%)std::panicking::try (493 samples, 0.38%)std::panicking::try::do_call (493 samples, 0.38%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (493 samples, 0.38%)tokio::runtime::task::harness::poll_future::{{closure}} (493 samples, 0.38%)tokio::runtime::task::core::Core<T,S>::poll (493 samples, 0.38%)tokio::runtime::time::wheel::Wheel::next_expiration (16 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (27 samples, 0.02%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (15 samples, 0.01%)torrust_tracker::core::Tracker::send_stats_event::{{closure}} (44 samples, 0.03%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (15 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (47 samples, 0.04%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::d_rounds (29 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (74 samples, 0.06%)torrust_tracker::servers::udp::peer_builder::from_request (17 samples, 0.01%)torrust_tracker::servers::udp::request::AnnounceWrapper::new (51 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (54 samples, 0.04%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (58 samples, 0.04%)torrust_tracker::core::Tracker::announce::{{closure}} (70 samples, 0.05%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (113 samples, 0.09%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (175 samples, 0.13%)<T as alloc::string::ToString>::to_string (38 samples, 0.03%)core::option::Option<T>::expect (56 samples, 0.04%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (18 samples, 0.01%)<T as alloc::string::ToString>::to_string (18 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (180 samples, 0.14%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (468 samples, 0.36%)torrust_tracker::servers::udp::logging::log_response (38 samples, 0.03%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (669 samples, 0.51%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (152 samples, 0.12%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (147 samples, 0.11%)tokio::net::udp::UdpSocket::send_to::{{closure}} (138 samples, 0.11%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (119 samples, 0.09%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (75 samples, 0.06%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (39 samples, 0.03%)mio::net::udp::UdpSocket::send_to (39 samples, 0.03%)mio::io_source::IoSource<T>::do_io (39 samples, 0.03%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (39 samples, 0.03%)mio::net::udp::UdpSocket::send_to::{{closure}} (39 samples, 0.03%)std::net::udp::UdpSocket::send_to (39 samples, 0.03%)std::sys_common::net::UdpSocket::send_to (39 samples, 0.03%)std::sys::pal::unix::cvt (39 samples, 0.03%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (39 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_stats (15 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (14 samples, 0.01%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count::to_usize::{{closure}} (33 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats::{{closure}} (33 samples, 0.03%)torrust_tracker_primitives::peer::Peer::is_seeder (33 samples, 0.03%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::count (75 samples, 0.06%)core::iter::traits::iterator::Iterator::sum (75 samples, 0.06%)<usize as core::iter::traits::accum::Sum>::sum (75 samples, 0.06%)<core::iter::adapters::map::Map<I,F> as core::iter::traits::iterator::Iterator>::fold (75 samples, 0.06%)core::iter::traits::iterator::Iterator::fold (75 samples, 0.06%)core::iter::adapters::map::map_fold::{{closure}} (34 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (104 samples, 0.08%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (24 samples, 0.02%)core::mem::drop (15 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (15 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (15 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (15 samples, 0.01%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (215 samples, 0.16%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (198 samples, 0.15%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (89 samples, 0.07%)core::option::Option<T>::is_some_and (32 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (31 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (30 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (30 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (26 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (34 samples, 0.03%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (58 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (58 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (58 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (58 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (58 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (20 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (238 samples, 0.18%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (236 samples, 0.18%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (208 samples, 0.16%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (208 samples, 0.16%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (282 samples, 0.21%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (67 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (53 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (53 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (22 samples, 0.02%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (22 samples, 0.02%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (22 samples, 0.02%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (22 samples, 0.02%)<u8 as core::slice::cmp::SliceOrd>::compare (22 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (18 samples, 0.01%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (23 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (23 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (43 samples, 0.03%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (43 samples, 0.03%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (43 samples, 0.03%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (43 samples, 0.03%)<u8 as core::slice::cmp::SliceOrd>::compare (43 samples, 0.03%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (17 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (151 samples, 0.12%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (145 samples, 0.11%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (137 samples, 0.10%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (137 samples, 0.10%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (266 samples, 0.20%)core::sync::atomic::AtomicU32::load (27 samples, 0.02%)core::sync::atomic::atomic_load (27 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (38 samples, 0.03%)std::sync::rwlock::RwLock<T>::read (37 samples, 0.03%)std::sys::sync::rwlock::futex::RwLock::read (36 samples, 0.03%)tracing::span::Span::log (16 samples, 0.01%)tracing::span::Span::record_all (70 samples, 0.05%)unlink_chunk (139 samples, 0.11%)rand::rng::Rng::gen (30 samples, 0.02%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (30 samples, 0.02%)rand::rng::Rng::gen (30 samples, 0.02%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (30 samples, 0.02%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (30 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (30 samples, 0.02%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (30 samples, 0.02%)rand_core::block::BlockRng<R>::generate_and_set (28 samples, 0.02%)[anon] (8,759 samples, 6.67%)[anon]uuid::v4::<impl uuid::Uuid>::new_v4 (32 samples, 0.02%)uuid::rng::bytes (32 samples, 0.02%)rand::random (32 samples, 0.02%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (15 samples, 0.01%)_int_free (338 samples, 0.26%)tcache_put (18 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (22 samples, 0.02%)hashbrown::raw::h2 (14 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (23 samples, 0.02%)hashbrown::raw::RawTableInner::find_or_find_insert_slot_inner (17 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (25 samples, 0.02%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (15 samples, 0.01%)[profiling] (545 samples, 0.42%)<alloc::collections::btree::map::Values<K,V> as core::iter::traits::iterator::Iterator>::next (32 samples, 0.02%)<alloc::collections::btree::map::Iter<K,V> as core::iter::traits::iterator::Iterator>::next (22 samples, 0.02%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Immut,K,V>::next_unchecked (16 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (30 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (28 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (83 samples, 0.06%)alloc::string::String::push_str (57 samples, 0.04%)alloc::vec::Vec<T,A>::extend_from_slice (57 samples, 0.04%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (57 samples, 0.04%)alloc::vec::Vec<T,A>::append_elements (57 samples, 0.04%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (20 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (41 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (151 samples, 0.12%)core::hash::sip::u8to64_le (50 samples, 0.04%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (33 samples, 0.03%)tokio::runtime::context::CONTEXT::__getit (35 samples, 0.03%)core::cell::Cell<T>::get (33 samples, 0.03%)[unknown] (20 samples, 0.02%)<tokio::future::poll_fn::PollFn<F> as core::future::future::Future>::poll (75 samples, 0.06%)core::ops::function::FnMut::call_mut (66 samples, 0.05%)tokio::runtime::coop::poll_proceed (66 samples, 0.05%)tokio::runtime::context::budget (66 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (66 samples, 0.05%)tokio::runtime::context::budget::{{closure}} (27 samples, 0.02%)tokio::runtime::coop::poll_proceed::{{closure}} (27 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (110 samples, 0.08%)[unknown] (15 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::io::scheduled_io::Waiters>> (27 samples, 0.02%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (27 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::unlock (14 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (84 samples, 0.06%)std::sync::mutex::Mutex<T>::lock (70 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock (59 samples, 0.04%)core::sync::atomic::AtomicU32::compare_exchange (55 samples, 0.04%)core::sync::atomic::atomic_compare_exchange (55 samples, 0.04%)[unknown] (33 samples, 0.03%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (214 samples, 0.16%)__memcpy_avx512_unaligned_erms (168 samples, 0.13%)[profiling] (171 samples, 0.13%)binascii::bin2hex (77 samples, 0.06%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (280 samples, 0.21%)[unknown] (317 samples, 0.24%)[[vdso]] (2,648 samples, 2.02%)[..[unknown] (669 samples, 0.51%)[unknown] (396 samples, 0.30%)[unknown] (251 samples, 0.19%)[unknown] (65 samples, 0.05%)[unknown] (30 samples, 0.02%)[unknown] (21 samples, 0.02%)__GI___clock_gettime (56 samples, 0.04%)arena_for_chunk (72 samples, 0.05%)arena_for_chunk (62 samples, 0.05%)heap_for_ptr (49 samples, 0.04%)heap_max_size (28 samples, 0.02%)__GI___libc_free (194 samples, 0.15%)arena_for_chunk (19 samples, 0.01%)checked_request2size (24 samples, 0.02%)__GI___libc_malloc (220 samples, 0.17%)tcache_get (44 samples, 0.03%)__GI___libc_write (25 samples, 0.02%)__GI___libc_write (14 samples, 0.01%)__GI___pthread_disable_asynccancel (97 samples, 0.07%)core::num::<impl u128>::leading_zeros (15 samples, 0.01%)compiler_builtins::float::conv::int_to_float::u128_to_f64_bits (72 samples, 0.05%)__floattidf (90 samples, 0.07%)compiler_builtins::float::conv::__floattidf (86 samples, 0.07%)exp_inline (40 samples, 0.03%)log_inline (64 samples, 0.05%)__ieee754_pow_fma (114 samples, 0.09%)__libc_calloc (106 samples, 0.08%)__libc_recvfrom (252 samples, 0.19%)__libc_sendto (133 samples, 0.10%)__memcmp_evex_movbe (137 samples, 0.10%)__memcpy_avx512_unaligned_erms (1,399 samples, 1.07%)__posix_memalign (172 samples, 0.13%)__posix_memalign (80 samples, 0.06%)_mid_memalign (71 samples, 0.05%)arena_for_chunk (14 samples, 0.01%)__pow (18 samples, 0.01%)__vdso_clock_gettime (40 samples, 0.03%)[unknown] (24 samples, 0.02%)_int_free (462 samples, 0.35%)tcache_put (54 samples, 0.04%)[unknown] (14 samples, 0.01%)_int_malloc (508 samples, 0.39%)_int_memalign (68 samples, 0.05%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (54 samples, 0.04%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (14 samples, 0.01%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (78 samples, 0.06%)alloc::raw_vec::RawVec<T,A>::grow_amortized (73 samples, 0.06%)alloc::raw_vec::finish_grow (91 samples, 0.07%)core::result::Result<T,E>::map_err (31 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Weak<ring::ec::curve25519::ed25519::signing::Ed25519KeyPair,&alloc::alloc::Global>> (16 samples, 0.01%)<alloc::sync::Weak<T,A> as core::ops::drop::Drop>::drop (16 samples, 0.01%)core::mem::drop (18 samples, 0.01%)alloc::sync::Arc<T,A>::drop_slow (21 samples, 0.02%)alloc_new_heap (49 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (49 samples, 0.04%)core::fmt::Formatter::pad_integral (40 samples, 0.03%)core::fmt::Formatter::pad_integral::write_prefix (19 samples, 0.01%)core::fmt::write (20 samples, 0.02%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (155 samples, 0.12%)core::ptr::drop_in_place<core::option::Option<core::task::wake::Waker>> (71 samples, 0.05%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (245 samples, 0.19%)core::ptr::drop_in_place<torrust_tracker::servers::udp::handlers::handle_announce::{{closure}}> (33 samples, 0.03%)core::ptr::drop_in_place<torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}}> (37 samples, 0.03%)core::str::converts::from_utf8 (33 samples, 0.03%)core::str::validations::run_utf8_validation (20 samples, 0.02%)epoll_wait (31 samples, 0.02%)hashbrown::map::HashMap<K,V,S,A>::insert (17 samples, 0.01%)rand_chacha::guts::refill_wide (19 samples, 0.01%)std_detect::detect::arch::x86::__is_feature_detected::avx2 (17 samples, 0.01%)std_detect::detect::check_for (17 samples, 0.01%)std_detect::detect::cache::test (17 samples, 0.01%)std_detect::detect::cache::Cache::test (17 samples, 0.01%)core::sync::atomic::AtomicUsize::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)std::sys::pal::unix::time::Timespec::new (29 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (132 samples, 0.10%)core::cmp::impls::<impl core::cmp::PartialOrd<&B> for &A>::ge (22 samples, 0.02%)core::cmp::PartialOrd::ge (22 samples, 0.02%)std::sys::pal::unix::time::Timespec::sub_timespec (67 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock_contended (18 samples, 0.01%)std::sys_common::net::TcpListener::socket_addr (29 samples, 0.02%)std::sys_common::net::sockname (28 samples, 0.02%)syscall (552 samples, 0.42%)core::ptr::drop_in_place<core::cell::RefMut<core::option::Option<alloc::boxed::Box<tokio::runtime::scheduler::multi_thread::worker::Core>>>> (74 samples, 0.06%)core::ptr::drop_in_place<core::cell::BorrowRefMut> (74 samples, 0.06%)<core::cell::BorrowRefMut as core::ops::drop::Drop>::drop (74 samples, 0.06%)core::cell::Cell<T>::set (74 samples, 0.06%)core::cell::Cell<T>::replace (74 samples, 0.06%)core::mem::replace (74 samples, 0.06%)core::ptr::write (74 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::push_back_or_overflow (14 samples, 0.01%)tokio::runtime::context::with_scheduler (176 samples, 0.13%)std::thread::local::LocalKey<T>::try_with (152 samples, 0.12%)tokio::runtime::context::with_scheduler::{{closure}} (151 samples, 0.12%)tokio::runtime::context::scoped::Scoped<T>::with (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (150 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (71 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (16 samples, 0.01%)core::option::Option<T>::map (19 samples, 0.01%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (24 samples, 0.02%)mio::poll::Poll::poll (53 samples, 0.04%)mio::sys::unix::selector::epoll::Selector::select (53 samples, 0.04%)core::result::Result<T,E>::map (28 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (28 samples, 0.02%)tokio::io::ready::Ready::from_mio (14 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (126 samples, 0.10%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (18 samples, 0.01%)[unknown] (51 samples, 0.04%)[unknown] (100 samples, 0.08%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (326 samples, 0.25%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (205 samples, 0.16%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (77 samples, 0.06%)[unknown] (26 samples, 0.02%)<tokio::util::linked_list::DrainFilter<T,F> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (396 samples, 0.30%)tokio::loom::std::mutex::Mutex<T>::lock (18 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (573 samples, 0.44%)core::sync::atomic::AtomicUsize::fetch_add (566 samples, 0.43%)core::sync::atomic::atomic_add (566 samples, 0.43%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (635 samples, 0.48%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (25 samples, 0.02%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::next_remote_task (44 samples, 0.03%)tokio::runtime::scheduler::inject::shared::Shared<T>::is_empty (21 samples, 0.02%)tokio::runtime::scheduler::inject::shared::Shared<T>::len (21 samples, 0.02%)core::sync::atomic::AtomicUsize::load (21 samples, 0.02%)core::sync::atomic::atomic_load (21 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id (32 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with (32 samples, 0.02%)tokio::runtime::task::core::Header::get_owner_id::{{closure}} (32 samples, 0.02%)std::sync::poison::Flag::done (32 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>,tokio::runtime::task::core::Header>>> (43 samples, 0.03%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (43 samples, 0.03%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (123 samples, 0.09%)tokio::runtime::task::list::OwnedTasks<S>::remove (117 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (80 samples, 0.06%)tokio::runtime::scheduler::defer::Defer::wake (17 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (46 samples, 0.04%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (71 samples, 0.05%)std::sync::condvar::Condvar::wait (56 samples, 0.04%)std::sys::sync::condvar::futex::Condvar::wait (56 samples, 0.04%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (56 samples, 0.04%)core::sync::atomic::AtomicUsize::compare_exchange (37 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (37 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (138 samples, 0.11%)tokio::runtime::driver::Driver::park (77 samples, 0.06%)tokio::runtime::driver::TimeDriver::park (77 samples, 0.06%)tokio::runtime::time::Driver::park (75 samples, 0.06%)tokio::runtime::scheduler::multi_thread::park::Parker::park (266 samples, 0.20%)tokio::runtime::scheduler::multi_thread::park::Inner::park (266 samples, 0.20%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (432 samples, 0.33%)tokio::runtime::scheduler::multi_thread::worker::Core::should_notify_others (26 samples, 0.02%)core::cell::RefCell<T>::borrow_mut (94 samples, 0.07%)core::cell::RefCell<T>::try_borrow_mut (94 samples, 0.07%)core::cell::BorrowRefMut::new (94 samples, 0.07%)tokio::runtime::coop::budget (142 samples, 0.11%)tokio::runtime::coop::with_budget (142 samples, 0.11%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (121 samples, 0.09%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (44 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (208 samples, 0.16%)tokio::runtime::signal::Driver::process (30 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (46 samples, 0.04%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (46 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (35 samples, 0.03%)tokio::runtime::task::core::Core<T,S>::set_stage (75 samples, 0.06%)core::sync::atomic::AtomicUsize::fetch_xor (76 samples, 0.06%)core::sync::atomic::atomic_xor (76 samples, 0.06%)tokio::runtime::task::state::State::transition_to_complete (79 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::complete (113 samples, 0.09%)tokio::runtime::task::state::State::transition_to_terminal (18 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::dealloc (28 samples, 0.02%)core::mem::drop (18 samples, 0.01%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (18 samples, 0.01%)core::ptr::drop_in_place<tokio::util::sharded_list::ShardGuard<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>> (16 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::util::linked_list::LinkedList<tokio::runtime::task::Task<alloc::sync::Arc<tokio::runtime::scheduler::current_thread::Handle>>,tokio::runtime::task::core::Header>>> (16 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (16 samples, 0.01%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (53 samples, 0.04%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (21 samples, 0.02%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (113 samples, 0.09%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (15 samples, 0.01%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (15 samples, 0.01%)tokio::loom::std::mutex::Mutex<T>::lock (15 samples, 0.01%)std::sync::mutex::Mutex<T>::lock (15 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::lock (14 samples, 0.01%)tokio::runtime::task::raw::drop_abort_handle (82 samples, 0.06%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (23 samples, 0.02%)tokio::runtime::task::state::State::ref_dec (23 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::task::raw::drop_join_handle_slow (34 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::drop_join_handle_slow (32 samples, 0.02%)tokio::runtime::task::state::State::unset_join_interested (23 samples, 0.02%)tokio::runtime::task::state::State::fetch_update (23 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (43 samples, 0.03%)core::num::<impl u32>::wrapping_add (23 samples, 0.02%)core::option::Option<T>::or_else (37 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (36 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (36 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (38 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (59 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (45 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (132 samples, 0.10%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (63 samples, 0.05%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run (290 samples, 0.22%)tokio::runtime::context::runtime::enter_runtime (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (290 samples, 0.22%)tokio::runtime::context::set_scheduler (290 samples, 0.22%)std::thread::local::LocalKey<T>::with (290 samples, 0.22%)std::thread::local::LocalKey<T>::try_with (290 samples, 0.22%)tokio::runtime::context::set_scheduler::{{closure}} (290 samples, 0.22%)tokio::runtime::context::scoped::Scoped<T>::set (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (290 samples, 0.22%)tokio::runtime::scheduler::multi_thread::worker::Context::run (290 samples, 0.22%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (327 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (322 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::poll (333 samples, 0.25%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (342 samples, 0.26%)tokio::runtime::task::harness::poll_future::{{closure}} (342 samples, 0.26%)tokio::runtime::task::harness::poll_future (348 samples, 0.27%)std::panic::catch_unwind (347 samples, 0.26%)std::panicking::try (347 samples, 0.26%)std::panicking::try::do_call (347 samples, 0.26%)core::sync::atomic::AtomicUsize::compare_exchange (18 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (18 samples, 0.01%)tokio::runtime::task::state::State::transition_to_running (47 samples, 0.04%)tokio::runtime::task::state::State::fetch_update_action (47 samples, 0.04%)tokio::runtime::task::state::State::transition_to_running::{{closure}} (19 samples, 0.01%)tokio::runtime::task::raw::poll (427 samples, 0.33%)tokio::runtime::task::harness::Harness<T,S>::poll (408 samples, 0.31%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (407 samples, 0.31%)tokio::runtime::task::state::State::transition_to_idle (17 samples, 0.01%)core::array::<impl core::default::Default for [T: 32]>::default (21 samples, 0.02%)tokio::runtime::time::wheel::Wheel::poll (14 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (72 samples, 0.05%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (23 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (15 samples, 0.01%)tokio::runtime::time::source::TimeSource::now (14 samples, 0.01%)tokio::runtime::time::Driver::park_internal (155 samples, 0.12%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (96 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (35 samples, 0.03%)core::num::<impl usize>::pow (35 samples, 0.03%)tokio::runtime::time::wheel::level::level_range (39 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (33 samples, 0.03%)core::num::<impl usize>::pow (33 samples, 0.03%)tokio::runtime::time::wheel::level::Level::next_expiration (208 samples, 0.16%)tokio::runtime::time::wheel::level::slot_range (48 samples, 0.04%)core::num::<impl usize>::pow (48 samples, 0.04%)tokio::runtime::time::wheel::Wheel::next_expiration (277 samples, 0.21%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::is_empty (18 samples, 0.01%)core::option::Option<T>::is_some (18 samples, 0.01%)torrust_tracker::core::Tracker::authorize::{{closure}} (50 samples, 0.04%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (37 samples, 0.03%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (27 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (19 samples, 0.01%)core::iter::traits::iterator::Iterator::collect (17 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (17 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (17 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (17 samples, 0.01%)<std::hash::random::DefaultHasher as core::hash::Hasher>::finish (20 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::finish (20 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::finish (20 samples, 0.02%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (62 samples, 0.05%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (40 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (27 samples, 0.02%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (17 samples, 0.01%)torrust_tracker::servers::udp::peer_builder::from_request (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (19 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (355 samples, 0.27%)<F as core::future::into_future::IntoFuture>::into_future (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (37 samples, 0.03%)core::sync::atomic::AtomicUsize::fetch_add (25 samples, 0.02%)core::sync::atomic::atomic_add (25 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet (14 samples, 0.01%)core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (20 samples, 0.02%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)core::result::Result<T,E>::map_err (16 samples, 0.01%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (136 samples, 0.10%)torrust_tracker::core::Tracker::announce::{{closure}} (173 samples, 0.13%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (267 samples, 0.20%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (30 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (423 samples, 0.32%)core::fmt::Formatter::new (26 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (80 samples, 0.06%)core::fmt::num::imp::fmt_u64 (58 samples, 0.04%)core::intrinsics::copy_nonoverlapping (15 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (74 samples, 0.06%)core::fmt::num::imp::fmt_u64 (70 samples, 0.05%)<T as alloc::string::ToString>::to_string (207 samples, 0.16%)core::option::Option<T>::expect (19 samples, 0.01%)core::ptr::drop_in_place<alloc::string::String> (18 samples, 0.01%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (18 samples, 0.01%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (18 samples, 0.01%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (18 samples, 0.01%)torrust_tracker::servers::udp::logging::map_action_name (25 samples, 0.02%)alloc::str::<impl alloc::borrow::ToOwned for str>::to_owned (14 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request (345 samples, 0.26%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (18 samples, 0.01%)core::fmt::num::imp::fmt_u64 (14 samples, 0.01%)<T as alloc::string::ToString>::to_string (35 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (1,067 samples, 0.81%)torrust_tracker::servers::udp::logging::log_response (72 samples, 0.05%)alloc::vec::from_elem (68 samples, 0.05%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (68 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (68 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (68 samples, 0.05%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (68 samples, 0.05%)alloc::alloc::Global::alloc_impl (68 samples, 0.05%)alloc::alloc::alloc_zeroed (68 samples, 0.05%)__rdl_alloc_zeroed (68 samples, 0.05%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (68 samples, 0.05%)[unknown] (48 samples, 0.04%)[unknown] (16 samples, 0.01%)[unknown] (28 samples, 0.02%)std::sys::pal::unix::cvt (134 samples, 0.10%)<isize as std::sys::pal::unix::IsMinusOne>::is_minus_one (134 samples, 0.10%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (1,908 samples, 1.45%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (504 samples, 0.38%)torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (382 samples, 0.29%)tokio::net::udp::UdpSocket::send_to::{{closure}} (344 samples, 0.26%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (332 samples, 0.25%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (304 samples, 0.23%)tokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (215 samples, 0.16%)mio::net::udp::UdpSocket::send_to (185 samples, 0.14%)mio::io_source::IoSource<T>::do_io (185 samples, 0.14%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (185 samples, 0.14%)mio::net::udp::UdpSocket::send_to::{{closure}} (185 samples, 0.14%)std::net::udp::UdpSocket::send_to (185 samples, 0.14%)std::sys_common::net::UdpSocket::send_to (169 samples, 0.13%)alloc::vec::Vec<T>::with_capacity (17 samples, 0.01%)alloc::vec::Vec<T,A>::with_capacity_in (17 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (104 samples, 0.08%)tokio::net::udp::UdpSocket::ready::{{closure}} (85 samples, 0.06%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (190 samples, 0.14%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (49 samples, 0.04%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (28 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (330 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (327 samples, 0.25%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (92 samples, 0.07%)tokio::task::spawn::spawn (92 samples, 0.07%)tokio::task::spawn::spawn_inner (92 samples, 0.07%)tokio::runtime::context::current::with_current (92 samples, 0.07%)std::thread::local::LocalKey<T>::try_with (92 samples, 0.07%)tokio::runtime::context::current::with_current::{{closure}} (92 samples, 0.07%)core::option::Option<T>::map (92 samples, 0.07%)tokio::task::spawn::spawn_inner::{{closure}} (92 samples, 0.07%)tokio::runtime::scheduler::Handle::spawn (92 samples, 0.07%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (92 samples, 0.07%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (92 samples, 0.07%)tokio::runtime::task::list::OwnedTasks<S>::bind (90 samples, 0.07%)tokio::runtime::task::new_task (89 samples, 0.07%)tokio::runtime::task::raw::RawTask::new (89 samples, 0.07%)tokio::runtime::task::core::Cell<T,S>::new (89 samples, 0.07%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (34 samples, 0.03%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (27 samples, 0.02%)alloc::sync::Arc<T>::new (21 samples, 0.02%)alloc::boxed::Box<T>::new (21 samples, 0.02%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (152 samples, 0.12%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (125 samples, 0.10%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (88 samples, 0.07%)core::option::Option<T>::is_some_and (18 samples, 0.01%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (17 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (17 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (17 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (22 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (22 samples, 0.02%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (17 samples, 0.01%)std::sync::rwlock::RwLock<T>::read (16 samples, 0.01%)std::sys::sync::rwlock::futex::RwLock::read (16 samples, 0.01%)tracing::span::Span::log (26 samples, 0.02%)core::fmt::Arguments::new_v1 (15 samples, 0.01%)tracing_core::span::Record::is_empty (34 samples, 0.03%)tracing_core::field::ValueSet::is_empty (34 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::all (22 samples, 0.02%)tracing_core::field::ValueSet::is_empty::{{closure}} (18 samples, 0.01%)core::option::Option<T>::is_none (16 samples, 0.01%)core::option::Option<T>::is_some (16 samples, 0.01%)tracing::span::Span::record_all (143 samples, 0.11%)unlink_chunk (185 samples, 0.14%)uuid::builder::Builder::with_variant (48 samples, 0.04%)[unknown] (40 samples, 0.03%)uuid::builder::Builder::from_random_bytes (77 samples, 0.06%)uuid::builder::Builder::with_version (29 samples, 0.02%)[unknown] (24 samples, 0.02%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (161 samples, 0.12%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (161 samples, 0.12%)[unknown] (92 samples, 0.07%)rand::rng::Rng::gen (162 samples, 0.12%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (162 samples, 0.12%)rand::rng::Rng::gen (162 samples, 0.12%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (162 samples, 0.12%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (162 samples, 0.12%)[unknown] (18,233 samples, 13.89%)[unknown]uuid::v4::<impl uuid::Uuid>::new_v4 (270 samples, 0.21%)uuid::rng::bytes (190 samples, 0.14%)rand::random (190 samples, 0.14%)__memcpy_avx512_unaligned_erms (69 samples, 0.05%)_int_free (23 samples, 0.02%)_int_malloc (23 samples, 0.02%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)advise_stack_range (31 samples, 0.02%)__GI_madvise (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (29 samples, 0.02%)[unknown] (28 samples, 0.02%)[unknown] (28 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (17 samples, 0.01%)std::sys::pal::unix::futex::futex_wait (31 samples, 0.02%)syscall (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (31 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (30 samples, 0.02%)[unknown] (29 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (17 samples, 0.01%)std::sync::condvar::Condvar::wait_timeout (35 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_timeout (35 samples, 0.03%)std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (35 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (56 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (56 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (56 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (56 samples, 0.04%)std::sys::pal::unix::futex::futex_wait (56 samples, 0.04%)syscall (56 samples, 0.04%)[unknown] (56 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (55 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (54 samples, 0.04%)[unknown] (53 samples, 0.04%)[unknown] (52 samples, 0.04%)[unknown] (46 samples, 0.04%)[unknown] (39 samples, 0.03%)[unknown] (38 samples, 0.03%)[unknown] (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (15 samples, 0.01%)[[vdso]] (26 samples, 0.02%)[[vdso]] (263 samples, 0.20%)__ieee754_pow_fma (26 samples, 0.02%)__pow (314 samples, 0.24%)std::f64::<impl f64>::powf (345 samples, 0.26%)__GI___clock_gettime (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::end_processing_scheduled_tasks (416 samples, 0.32%)std::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Timespec::now (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_processing_scheduled_tasks (24 samples, 0.02%)std::time::Instant::now (18 samples, 0.01%)std::sys::pal::unix::time::Instant::now (18 samples, 0.01%)mio::poll::Poll::poll (102 samples, 0.08%)mio::sys::unix::selector::epoll::Selector::select (102 samples, 0.08%)epoll_wait (99 samples, 0.08%)[unknown] (92 samples, 0.07%)[unknown] (91 samples, 0.07%)[unknown] (91 samples, 0.07%)[unknown] (88 samples, 0.07%)[unknown] (85 samples, 0.06%)[unknown] (84 samples, 0.06%)[unknown] (43 samples, 0.03%)[unknown] (29 samples, 0.02%)[unknown] (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (125 samples, 0.10%)tokio::runtime::scheduler::multi_thread::park::Parker::park_timeout (125 samples, 0.10%)tokio::runtime::driver::Driver::park_timeout (125 samples, 0.10%)tokio::runtime::driver::TimeDriver::park_timeout (125 samples, 0.10%)tokio::runtime::time::Driver::park_timeout (125 samples, 0.10%)tokio::runtime::time::Driver::park_internal (116 samples, 0.09%)tokio::runtime::io::driver::Driver::turn (116 samples, 0.09%)tokio::runtime::scheduler::multi_thread::worker::Context::maintenance (148 samples, 0.11%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (111 samples, 0.08%)alloc::sync::Arc<T,A>::inner (111 samples, 0.08%)core::ptr::non_null::NonNull<T>::as_ref (111 samples, 0.08%)core::sync::atomic::AtomicUsize::compare_exchange (16 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (16 samples, 0.01%)core::bool::<impl bool>::then (88 samples, 0.07%)std::sys::pal::unix::futex::futex_wait (13,339 samples, 10.16%)std::sys::pal::..syscall (13,003 samples, 9.90%)syscall[unknown] (12,895 samples, 9.82%)[unknown][unknown] (12,759 samples, 9.72%)[unknown][unknown] (12,313 samples, 9.38%)[unknown][unknown] (12,032 samples, 9.16%)[unknown][unknown] (11,734 samples, 8.94%)[unknown][unknown] (11,209 samples, 8.54%)[unknown][unknown] (10,265 samples, 7.82%)[unknown][unknown] (9,345 samples, 7.12%)[unknown][unknown] (8,623 samples, 6.57%)[unknown][unknown] (7,744 samples, 5.90%)[unknow..[unknown] (5,922 samples, 4.51%)[unkn..[unknown] (4,459 samples, 3.40%)[un..[unknown] (2,808 samples, 2.14%)[..[unknown] (1,275 samples, 0.97%)[unknown] (1,022 samples, 0.78%)[unknown] (738 samples, 0.56%)[unknown] (607 samples, 0.46%)[unknown] (155 samples, 0.12%)core::result::Result<T,E>::is_err (77 samples, 0.06%)core::result::Result<T,E>::is_ok (77 samples, 0.06%)std::sync::condvar::Condvar::wait (13,429 samples, 10.23%)std::sync::cond..std::sys::sync::condvar::futex::Condvar::wait (13,428 samples, 10.23%)std::sys::sync:..std::sys::sync::condvar::futex::Condvar::wait_optional_timeout (13,428 samples, 10.23%)std::sys::sync:..std::sys::sync::mutex::futex::Mutex::lock (89 samples, 0.07%)tokio::runtime::scheduler::multi_thread::park::Inner::park_condvar (13,508 samples, 10.29%)tokio::runtime:..tokio::loom::std::mutex::Mutex<T>::lock (64 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (31 samples, 0.02%)core::sync::atomic::AtomicU32::compare_exchange (30 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (30 samples, 0.02%)core::sync::atomic::AtomicUsize::compare_exchange (15 samples, 0.01%)core::sync::atomic::atomic_compare_exchange (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (38 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Parker::park (34 samples, 0.03%)tokio::runtime::scheduler::multi_thread::park::Inner::park (34 samples, 0.03%)core::array::<impl core::default::Default for [T: 32]>::default (17 samples, 0.01%)core::ptr::drop_in_place<[core::option::Option<core::task::wake::Waker>: 32]> (19 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_occupied_slot (33 samples, 0.03%)tokio::runtime::time::wheel::level::slot_range (15 samples, 0.01%)core::num::<impl usize>::pow (15 samples, 0.01%)tokio::runtime::time::wheel::level::level_range (17 samples, 0.01%)tokio::runtime::time::wheel::level::slot_range (15 samples, 0.01%)core::num::<impl usize>::pow (15 samples, 0.01%)tokio::runtime::time::wheel::level::Level::next_expiration (95 samples, 0.07%)tokio::runtime::time::wheel::level::slot_range (41 samples, 0.03%)core::num::<impl usize>::pow (41 samples, 0.03%)tokio::runtime::time::wheel::Wheel::next_expiration (129 samples, 0.10%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process_at_time (202 samples, 0.15%)tokio::runtime::time::wheel::Wheel::poll_at (17 samples, 0.01%)tokio::runtime::time::wheel::Wheel::next_expiration (15 samples, 0.01%)<mio::event::events::Iter as core::iter::traits::iterator::Iterator>::next (38 samples, 0.03%)core::option::Option<T>::map (38 samples, 0.03%)core::result::Result<T,E>::map (31 samples, 0.02%)mio::sys::unix::selector::epoll::Selector::select::{{closure}} (31 samples, 0.02%)alloc::vec::Vec<T,A>::set_len (17 samples, 0.01%)[[vdso]] (28 samples, 0.02%)[unknown] (11,031 samples, 8.40%)[unknown][unknown] (10,941 samples, 8.33%)[unknown][unknown] (10,850 samples, 8.26%)[unknown][unknown] (10,691 samples, 8.14%)[unknown][unknown] (10,070 samples, 7.67%)[unknown][unknown] (9,737 samples, 7.42%)[unknown][unknown] (7,659 samples, 5.83%)[unknow..[unknown] (6,530 samples, 4.97%)[unkno..[unknown] (5,633 samples, 4.29%)[unkn..[unknown] (5,055 samples, 3.85%)[unk..[unknown] (4,046 samples, 3.08%)[un..[unknown] (2,911 samples, 2.22%)[..[unknown] (2,115 samples, 1.61%)[unknown] (1,226 samples, 0.93%)[unknown] (455 samples, 0.35%)[unknown] (408 samples, 0.31%)[unknown] (249 samples, 0.19%)[unknown] (202 samples, 0.15%)[unknown] (100 samples, 0.08%)mio::poll::Poll::poll (11,328 samples, 8.63%)mio::poll::P..mio::sys::unix::selector::epoll::Selector::select (11,328 samples, 8.63%)mio::sys::un..epoll_wait (11,229 samples, 8.55%)epoll_wait__GI___pthread_disable_asynccancel (50 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (47 samples, 0.04%)tokio::util::bit::Pack::pack (38 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (25 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (23 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (19 samples, 0.01%)tokio::runtime::io::driver::Driver::turn (11,595 samples, 8.83%)tokio::runti..tokio::runtime::io::scheduled_io::ScheduledIo::wake (175 samples, 0.13%)__GI___clock_gettime (15 samples, 0.01%)std::sys::pal::unix::time::Timespec::now (18 samples, 0.01%)tokio::runtime::time::<impl tokio::runtime::time::handle::Handle>::process (26 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (26 samples, 0.02%)tokio::time::clock::Clock::now (20 samples, 0.02%)tokio::time::clock::now (20 samples, 0.02%)std::time::Instant::now (20 samples, 0.02%)std::sys::pal::unix::time::Instant::now (20 samples, 0.02%)tokio::runtime::time::source::TimeSource::now (17 samples, 0.01%)tokio::runtime::time::Driver::park_internal (11,686 samples, 8.90%)tokio::runtim..tokio::runtime::scheduler::multi_thread::park::Inner::park_driver (11,957 samples, 9.11%)tokio::runtim..tokio::runtime::driver::Driver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::driver::TimeDriver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::time::Driver::park (11,950 samples, 9.10%)tokio::runtim..tokio::runtime::scheduler::multi_thread::park::Parker::park (25,502 samples, 19.42%)tokio::runtime::scheduler::mul..tokio::runtime::scheduler::multi_thread::park::Inner::park (25,502 samples, 19.42%)tokio::runtime::scheduler::mul..tokio::runtime::scheduler::multi_thread::worker::Context::park_timeout (25,547 samples, 19.46%)tokio::runtime::scheduler::mul..core::result::Result<T,E>::is_err (14 samples, 0.01%)core::result::Result<T,E>::is_ok (14 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (45 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (45 samples, 0.03%)tokio::loom::std::mutex::Mutex<T>::lock (84 samples, 0.06%)std::sync::mutex::Mutex<T>::lock (81 samples, 0.06%)std::sys::sync::mutex::futex::Mutex::lock (73 samples, 0.06%)tokio::runtime::scheduler::multi_thread::worker::Core::maintenance (122 samples, 0.09%)<T as core::slice::cmp::SliceContains>::slice_contains::{{closure}} (90 samples, 0.07%)core::cmp::impls::<impl core::cmp::PartialEq for usize>::eq (90 samples, 0.07%)core::slice::<impl [T]>::contains (241 samples, 0.18%)<T as core::slice::cmp::SliceContains>::slice_contains (241 samples, 0.18%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::any (241 samples, 0.18%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (75 samples, 0.06%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (75 samples, 0.06%)core::sync::atomic::AtomicU32::compare_exchange (20 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::is_parked (283 samples, 0.22%)tokio::loom::std::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sync::mutex::Mutex<T>::lock (32 samples, 0.02%)std::sys::sync::mutex::futex::Mutex::lock (24 samples, 0.02%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (33 samples, 0.03%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (33 samples, 0.03%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (33 samples, 0.03%)tokio::runtime::scheduler::multi_thread::idle::Idle::unpark_worker_by_id (98 samples, 0.07%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (401 samples, 0.31%)alloc::vec::Vec<T,A>::push (14 samples, 0.01%)core::ptr::drop_in_place<std::sync::mutex::MutexGuard<tokio::runtime::scheduler::multi_thread::worker::Synced>> (15 samples, 0.01%)<std::sync::mutex::MutexGuard<T> as core::ops::drop::Drop>::drop (15 samples, 0.01%)std::sys::sync::mutex::futex::Mutex::unlock (14 samples, 0.01%)core::result::Result<T,E>::is_err (15 samples, 0.01%)core::result::Result<T,E>::is_ok (15 samples, 0.01%)core::sync::atomic::AtomicU32::compare_exchange (22 samples, 0.02%)core::sync::atomic::atomic_compare_exchange (22 samples, 0.02%)tokio::loom::std::mutex::Mutex<T>::lock (63 samples, 0.05%)std::sync::mutex::Mutex<T>::lock (62 samples, 0.05%)std::sys::sync::mutex::futex::Mutex::lock (59 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock_contended (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_parked (106 samples, 0.08%)tokio::runtime::scheduler::multi_thread::idle::State::dec_num_unparked (14 samples, 0.01%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (21 samples, 0.02%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (21 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (17 samples, 0.01%)alloc::sync::Arc<T,A>::inner (17 samples, 0.01%)core::ptr::non_null::NonNull<T>::as_ref (17 samples, 0.01%)core::sync::atomic::AtomicU32::load (17 samples, 0.01%)core::sync::atomic::atomic_load (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::is_empty (68 samples, 0.05%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::is_empty (51 samples, 0.04%)tokio::runtime::scheduler::multi_thread::queue::Inner<T>::len (33 samples, 0.03%)core::sync::atomic::AtomicU64::load (16 samples, 0.01%)core::sync::atomic::atomic_load (16 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_if_work_pending (106 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::park (26,672 samples, 20.31%)tokio::runtime::scheduler::multi..tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_parked (272 samples, 0.21%)tokio::runtime::scheduler::multi_thread::worker::Core::has_tasks (33 samples, 0.03%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::has_tasks (24 samples, 0.02%)tokio::runtime::context::budget (18 samples, 0.01%)std::thread::local::LocalKey<T>::try_with (18 samples, 0.01%)syscall (61 samples, 0.05%)__memcpy_avx512_unaligned_erms (172 samples, 0.13%)__memcpy_avx512_unaligned_erms (224 samples, 0.17%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (228 samples, 0.17%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (228 samples, 0.17%)std::panic::catch_unwind (415 samples, 0.32%)std::panicking::try (415 samples, 0.32%)std::panicking::try::do_call (415 samples, 0.32%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (415 samples, 0.32%)core::ops::function::FnOnce::call_once (415 samples, 0.32%)tokio::runtime::task::harness::Harness<T,S>::complete::{{closure}} (415 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (415 samples, 0.32%)tokio::runtime::task::core::Core<T,S>::set_stage (410 samples, 0.31%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (27 samples, 0.02%)core::result::Result<T,E>::is_err (43 samples, 0.03%)core::result::Result<T,E>::is_ok (43 samples, 0.03%)tokio::runtime::task::harness::Harness<T,S>::complete (570 samples, 0.43%)tokio::runtime::task::harness::Harness<T,S>::release (155 samples, 0.12%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::task::Schedule for alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>::release (152 samples, 0.12%)tokio::runtime::task::list::OwnedTasks<S>::remove (152 samples, 0.12%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::remove (103 samples, 0.08%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (65 samples, 0.05%)tokio::loom::std::mutex::Mutex<T>::lock (58 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (58 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (54 samples, 0.04%)std::io::stdio::stderr::INSTANCE (17 samples, 0.01%)tokio::runtime::coop::budget (26 samples, 0.02%)tokio::runtime::coop::with_budget (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (35 samples, 0.03%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (70 samples, 0.05%)__memcpy_avx512_unaligned_erms (42 samples, 0.03%)core::cmp::Ord::min (22 samples, 0.02%)core::cmp::min_by (22 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (27 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (30 samples, 0.02%)std::io::cursor::Cursor<T>::remaining_slice (24 samples, 0.02%)core::slice::index::<impl core::ops::index::Index<I> for [T]>::index (19 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::index (19 samples, 0.01%)<core::ops::range::RangeFrom<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (19 samples, 0.01%)<core::ops::range::Range<usize> as core::slice::index::SliceIndex<[T]>>::get_unchecked (19 samples, 0.01%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (44 samples, 0.03%)std::io::impls::<impl std::io::Read for &[u8]>::read_exact (20 samples, 0.02%)byteorder::io::ReadBytesExt::read_i32 (46 samples, 0.04%)core::cmp::Ord::min (14 samples, 0.01%)core::cmp::min_by (14 samples, 0.01%)std::io::cursor::Cursor<T>::remaining_slice (19 samples, 0.01%)byteorder::io::ReadBytesExt::read_i64 (24 samples, 0.02%)<std::io::cursor::Cursor<T> as std::io::Read>::read_exact (24 samples, 0.02%)aquatic_udp_protocol::request::Request::from_bytes (349 samples, 0.27%)__GI___lll_lock_wake_private (148 samples, 0.11%)[unknown] (139 samples, 0.11%)[unknown] (137 samples, 0.10%)[unknown] (123 samples, 0.09%)[unknown] (111 samples, 0.08%)[unknown] (98 samples, 0.07%)[unknown] (42 samples, 0.03%)[unknown] (30 samples, 0.02%)__GI___lll_lock_wait_private (553 samples, 0.42%)futex_wait (541 samples, 0.41%)[unknown] (536 samples, 0.41%)[unknown] (531 samples, 0.40%)[unknown] (524 samples, 0.40%)[unknown] (515 samples, 0.39%)[unknown] (498 samples, 0.38%)[unknown] (470 samples, 0.36%)[unknown] (435 samples, 0.33%)[unknown] (350 samples, 0.27%)[unknown] (327 samples, 0.25%)[unknown] (290 samples, 0.22%)[unknown] (222 samples, 0.17%)[unknown] (160 samples, 0.12%)[unknown] (104 samples, 0.08%)[unknown] (33 samples, 0.03%)[unknown] (25 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (703 samples, 0.54%)__GI___libc_free (866 samples, 0.66%)tracing::span::Span::record_all (30 samples, 0.02%)unlink_chunk (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::servers::udp::UdpRequest> (899 samples, 0.68%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (899 samples, 0.68%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (899 samples, 0.68%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (899 samples, 0.68%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (899 samples, 0.68%)alloc::alloc::dealloc (899 samples, 0.68%)__rdl_dealloc (899 samples, 0.68%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (899 samples, 0.68%)core::result::Result<T,E>::expect (91 samples, 0.07%)core::result::Result<T,E>::map_err (28 samples, 0.02%)[[vdso]] (28 samples, 0.02%)__GI___clock_gettime (47 samples, 0.04%)std::time::Instant::elapsed (67 samples, 0.05%)std::time::Instant::now (54 samples, 0.04%)std::sys::pal::unix::time::Instant::now (54 samples, 0.04%)std::sys::pal::unix::time::Timespec::now (53 samples, 0.04%)std::sys::pal::unix::cvt (23 samples, 0.02%)__GI_getsockname (3,792 samples, 2.89%)__..[unknown] (3,714 samples, 2.83%)[u..[unknown] (3,661 samples, 2.79%)[u..[unknown] (3,557 samples, 2.71%)[u..[unknown] (3,416 samples, 2.60%)[u..[unknown] (2,695 samples, 2.05%)[..[unknown] (2,063 samples, 1.57%)[unknown] (891 samples, 0.68%)[unknown] (270 samples, 0.21%)[unknown] (99 samples, 0.08%)[unknown] (94 samples, 0.07%)[unknown] (84 samples, 0.06%)[unknown] (77 samples, 0.06%)[unknown] (25 samples, 0.02%)[unknown] (16 samples, 0.01%)std::sys_common::net::TcpListener::socket_addr::{{closure}} (3,800 samples, 2.89%)st..tokio::net::udp::UdpSocket::local_addr (3,838 samples, 2.92%)to..mio::net::udp::UdpSocket::local_addr (3,838 samples, 2.92%)mi..std::net::tcp::TcpListener::local_addr (3,838 samples, 2.92%)st..std::sys_common::net::TcpListener::socket_addr (3,838 samples, 2.92%)st..std::sys_common::net::sockname (3,835 samples, 2.92%)st..[[vdso]] (60 samples, 0.05%)rand_chacha::guts::ChaCha::pos64 (168 samples, 0.13%)<ppv_lite86::soft::x2<W,G> as core::ops::arith::AddAssign>::add_assign (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::AddAssign>::add_assign (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as core::ops::arith::Add>::add (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_add_epi32 (26 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (26 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right16 (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (26 samples, 0.02%)core::core_arch::x86::avx2::_mm256_or_si256 (29 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (31 samples, 0.02%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right20 (31 samples, 0.02%)<ppv_lite86::soft::x2<W,G> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (18 samples, 0.01%)<ppv_lite86::x86_64::sse2::avx2::u32x4x2_avx2<NI> as ppv_lite86::types::RotateEachWord32>::rotate_each_word_right24 (18 samples, 0.01%)core::core_arch::x86::avx2::_mm256_shuffle_epi8 (18 samples, 0.01%)rand_chacha::guts::round (118 samples, 0.09%)rand_chacha::guts::refill_wide::impl_avx2 (312 samples, 0.24%)rand_chacha::guts::refill_wide::fn_impl (312 samples, 0.24%)rand_chacha::guts::refill_wide_impl (312 samples, 0.24%)<rand_chacha::chacha::ChaCha12Core as rand_core::block::BlockRngCore>::generate (384 samples, 0.29%)rand_chacha::guts::ChaCha::refill4 (384 samples, 0.29%)rand::rng::Rng::gen (432 samples, 0.33%)rand::distributions::other::<impl rand::distributions::distribution::Distribution<[T: _]> for rand::distributions::Standard>::sample (432 samples, 0.33%)rand::rng::Rng::gen (432 samples, 0.33%)rand::distributions::integer::<impl rand::distributions::distribution::Distribution<u8> for rand::distributions::Standard>::sample (432 samples, 0.33%)<rand::rngs::thread::ThreadRng as rand_core::RngCore>::next_u32 (432 samples, 0.33%)<rand::rngs::adapter::reseeding::ReseedingRng<R,Rsdr> as rand_core::RngCore>::next_u32 (432 samples, 0.33%)<rand_core::block::BlockRng<R> as rand_core::RngCore>::next_u32 (432 samples, 0.33%)rand_core::block::BlockRng<R>::generate_and_set (392 samples, 0.30%)<rand::rngs::adapter::reseeding::ReseedingCore<R,Rsdr> as rand_core::block::BlockRngCore>::generate (392 samples, 0.30%)torrust_tracker::servers::udp::handlers::RequestId::make (440 samples, 0.34%)uuid::v4::<impl uuid::Uuid>::new_v4 (436 samples, 0.33%)uuid::rng::bytes (435 samples, 0.33%)rand::random (435 samples, 0.33%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::get_peers_for_client (34 samples, 0.03%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_peers_for_client (22 samples, 0.02%)core::iter::traits::iterator::Iterator::collect (16 samples, 0.01%)<alloc::vec::Vec<T> as core::iter::traits::collect::FromIterator<T>>::from_iter (16 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter::SpecFromIter<T,I>>::from_iter (16 samples, 0.01%)<alloc::vec::Vec<T> as alloc::vec::spec_from_iter_nested::SpecFromIterNested<T,I>>::from_iter (16 samples, 0.01%)<core::iter::adapters::cloned::Cloned<I> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)<core::iter::adapters::take::Take<I> as core::iter::traits::iterator::Iterator>::next (16 samples, 0.01%)<core::iter::adapters::filter::Filter<I,P> as core::iter::traits::iterator::Iterator>::next (15 samples, 0.01%)core::iter::traits::iterator::Iterator::find (15 samples, 0.01%)core::iter::traits::iterator::Iterator::try_fold (15 samples, 0.01%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (31 samples, 0.02%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.03%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (45 samples, 0.03%)core::slice::iter::Iter<T>::post_inc_start (14 samples, 0.01%)core::ptr::non_null::NonNull<T>::add (14 samples, 0.01%)__memcmp_evex_movbe (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (26 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (165 samples, 0.13%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (165 samples, 0.13%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (165 samples, 0.13%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (165 samples, 0.13%)<u8 as core::slice::cmp::SliceOrd>::compare (165 samples, 0.13%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (339 samples, 0.26%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (308 samples, 0.23%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (308 samples, 0.23%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (342 samples, 0.26%)std::sys::sync::rwlock::futex::RwLock::spin_read (25 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_until (25 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read_contended (28 samples, 0.02%)torrust_tracker::core::Tracker::get_torrent_peers_for_peer (436 samples, 0.33%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (397 samples, 0.30%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (29 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (29 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (29 samples, 0.02%)__memcmp_evex_movbe (31 samples, 0.02%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (52 samples, 0.04%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (52 samples, 0.04%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (52 samples, 0.04%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (52 samples, 0.04%)<u8 as core::slice::cmp::SliceOrd>::compare (52 samples, 0.04%)alloc::collections::btree::map::BTreeMap<K,V,A>::entry (103 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (102 samples, 0.08%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (96 samples, 0.07%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (96 samples, 0.07%)<core::ptr::non_null::NonNull<T> as core::cmp::PartialEq>::eq (72 samples, 0.05%)<core::iter::adapters::enumerate::Enumerate<I> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.08%)<core::slice::iter::Iter<T> as core::iter::traits::iterator::Iterator>::next (104 samples, 0.08%)core::slice::iter::Iter<T>::post_inc_start (32 samples, 0.02%)core::ptr::non_null::NonNull<T>::add (32 samples, 0.02%)__memcmp_evex_movbe (79 samples, 0.06%)core::cmp::impls::<impl core::cmp::Ord for isize>::cmp (81 samples, 0.06%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (271 samples, 0.21%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (271 samples, 0.21%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (271 samples, 0.21%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (271 samples, 0.21%)<u8 as core::slice::cmp::SliceOrd>::compare (271 samples, 0.21%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (610 samples, 0.46%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (566 samples, 0.43%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (566 samples, 0.43%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Immut,K,V,Type>::keys (18 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (616 samples, 0.47%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::KV>::split (15 samples, 0.01%)alloc::collections::btree::map::entry::Entry<K,V,A>::or_insert (46 samples, 0.04%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (45 samples, 0.03%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert_recursing (40 samples, 0.03%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>::insert (27 samples, 0.02%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::get_stats (29 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::values (20 samples, 0.02%)alloc::collections::btree::map::BTreeMap<K,V,A>::insert (120 samples, 0.09%)alloc::collections::btree::map::entry::VacantEntry<K,V,A>::insert (118 samples, 0.09%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Owned,K,V,alloc::collections::btree::node::marker::Leaf>::new_leaf (118 samples, 0.09%)alloc::collections::btree::node::LeafNode<K,V>::new (118 samples, 0.09%)alloc::boxed::Box<T,A>::new_uninit_in (118 samples, 0.09%)alloc::boxed::Box<T,A>::try_new_uninit_in (118 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (118 samples, 0.09%)alloc::alloc::Global::alloc_impl (118 samples, 0.09%)alloc::alloc::alloc (118 samples, 0.09%)__rdl_alloc (118 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (118 samples, 0.09%)__GI___libc_malloc (118 samples, 0.09%)_int_malloc (107 samples, 0.08%)_int_malloc (28 samples, 0.02%)__GI___libc_malloc (32 samples, 0.02%)__rdl_alloc (36 samples, 0.03%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (36 samples, 0.03%)alloc::sync::Arc<T>::new (42 samples, 0.03%)alloc::boxed::Box<T>::new (42 samples, 0.03%)alloc::alloc::exchange_malloc (39 samples, 0.03%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (39 samples, 0.03%)alloc::alloc::Global::alloc_impl (39 samples, 0.03%)alloc::alloc::alloc (39 samples, 0.03%)core::mem::drop (15 samples, 0.01%)core::ptr::drop_in_place<core::option::Option<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (15 samples, 0.01%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (15 samples, 0.01%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (15 samples, 0.01%)__GI___libc_free (39 samples, 0.03%)_int_free (37 samples, 0.03%)get_max_fast (16 samples, 0.01%)core::option::Option<T>::is_some_and (50 samples, 0.04%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer::{{closure}} (50 samples, 0.04%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>> (50 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (50 samples, 0.04%)torrust_tracker_torrent_repository::entry::mutex_std::<impl torrust_tracker_torrent_repository::entry::EntrySync for alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>::insert_or_update_peer_and_get_stats (290 samples, 0.22%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer_and_get_stats (284 samples, 0.22%)torrust_tracker_torrent_repository::entry::single::<impl torrust_tracker_torrent_repository::entry::Entry for torrust_tracker_torrent_repository::entry::Torrent>::insert_or_update_peer (255 samples, 0.19%)std::sys::sync::rwlock::futex::RwLock::spin_read (16 samples, 0.01%)std::sys::sync::rwlock::futex::RwLock::spin_until (16 samples, 0.01%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents (21 samples, 0.02%)std::sync::rwlock::RwLock<T>::read (21 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read (21 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::read_contended (21 samples, 0.02%)torrust_tracker::core::Tracker::update_torrent_with_peer_and_get_stats::{{closure}} (1,147 samples, 0.87%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::update_torrent_with_peer_and_get_stats (1,144 samples, 0.87%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get_torrents_mut (32 samples, 0.02%)std::sync::rwlock::RwLock<T>::write (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::write (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::write_contended (32 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_write (28 samples, 0.02%)std::sys::sync::rwlock::futex::RwLock::spin_until (28 samples, 0.02%)torrust_tracker::core::Tracker::announce::{{closure}} (1,597 samples, 1.22%)<core::net::socket_addr::SocketAddrV4 as core::hash::Hash>::hash (14 samples, 0.01%)<core::net::ip_addr::Ipv4Addr as core::hash::Hash>::hash (14 samples, 0.01%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (29 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (24 samples, 0.02%)<core::time::Nanoseconds as core::hash::Hash>::hash (25 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (25 samples, 0.02%)core::hash::Hasher::write_u32 (25 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (25 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (25 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (36 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (37 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (37 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (64 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (39 samples, 0.03%)core::hash::Hasher::write_u64 (39 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (122 samples, 0.09%)core::hash::impls::<impl core::hash::Hash for u64>::hash (58 samples, 0.04%)core::hash::Hasher::write_u64 (58 samples, 0.04%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (58 samples, 0.04%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (58 samples, 0.04%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (57 samples, 0.04%)core::hash::sip::u8to64_le (23 samples, 0.02%)core::hash::Hasher::write_length_prefix (27 samples, 0.02%)core::hash::Hasher::write_usize (27 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (27 samples, 0.02%)<core::hash::sip::Sip13Rounds as core::hash::sip::Sip>::c_rounds (16 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (246 samples, 0.19%)core::array::<impl core::hash::Hash for [T: N]>::hash (93 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (93 samples, 0.07%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (66 samples, 0.05%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (62 samples, 0.05%)core::hash::sip::u8to64_le (17 samples, 0.01%)torrust_tracker::servers::udp::connection_cookie::check (285 samples, 0.22%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (36 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (36 samples, 0.03%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (24 samples, 0.02%)std::time::SystemTime::now (19 samples, 0.01%)std::sys::pal::unix::time::SystemTime::now (19 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_announce::{{closure}} (1,954 samples, 1.49%)<core::net::socket_addr::SocketAddr as core::hash::Hash>::hash (24 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (18 samples, 0.01%)<core::time::Nanoseconds as core::hash::Hash>::hash (20 samples, 0.02%)core::hash::impls::<impl core::hash::Hash for u32>::hash (20 samples, 0.02%)core::hash::Hasher::write_u32 (20 samples, 0.02%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (20 samples, 0.02%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (20 samples, 0.02%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (44 samples, 0.03%)<core::time::Duration as core::hash::Hash>::hash (65 samples, 0.05%)core::hash::impls::<impl core::hash::Hash for u64>::hash (45 samples, 0.03%)core::hash::Hasher::write_u64 (45 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (45 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (45 samples, 0.03%)<torrust_tracker_clock::time_extent::TimeExtent as core::hash::Hash>::hash (105 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u64>::hash (40 samples, 0.03%)core::hash::Hasher::write_u64 (40 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (40 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (40 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (39 samples, 0.03%)core::hash::Hasher::write_length_prefix (34 samples, 0.03%)core::hash::Hasher::write_usize (34 samples, 0.03%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (34 samples, 0.03%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (34 samples, 0.03%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (33 samples, 0.03%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::build (231 samples, 0.18%)core::array::<impl core::hash::Hash for [T: N]>::hash (100 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for [T]>::hash (100 samples, 0.08%)core::hash::impls::<impl core::hash::Hash for u8>::hash_slice (66 samples, 0.05%)<std::hash::random::DefaultHasher as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::SipHasher13 as core::hash::Hasher>::write (66 samples, 0.05%)<core::hash::sip::Hasher<S> as core::hash::Hasher>::write (61 samples, 0.05%)core::hash::sip::u8to64_le (16 samples, 0.01%)_int_free (16 samples, 0.01%)torrust_tracker::servers::udp::handlers::handle_connect::{{closure}} (270 samples, 0.21%)torrust_tracker::servers::udp::connection_cookie::make (268 samples, 0.20%)torrust_tracker::servers::udp::connection_cookie::cookie_builder::get_last_time_extent (36 samples, 0.03%)torrust_tracker_clock::time_extent::Make::now (35 samples, 0.03%)torrust_tracker_clock::clock::working::<impl torrust_tracker_clock::clock::Time for torrust_tracker_clock::clock::Clock<torrust_tracker_clock::clock::working::WorkingClock>>::now (31 samples, 0.02%)std::time::SystemTime::now (26 samples, 0.02%)std::sys::pal::unix::time::SystemTime::now (26 samples, 0.02%)torrust_tracker::core::ScrapeData::add_file (19 samples, 0.01%)std::collections::hash::map::HashMap<K,V,S>::insert (19 samples, 0.01%)hashbrown::map::HashMap<K,V,S,A>::insert (19 samples, 0.01%)hashbrown::raw::RawTable<T,A>::find_or_find_insert_slot (16 samples, 0.01%)hashbrown::raw::RawTable<T,A>::reserve (16 samples, 0.01%)<torrust_tracker_primitives::info_hash::InfoHash as core::cmp::Ord>::cmp (17 samples, 0.01%)core::array::<impl core::cmp::Ord for [T: N]>::cmp (17 samples, 0.01%)core::cmp::impls::<impl core::cmp::Ord for &A>::cmp (17 samples, 0.01%)core::slice::cmp::<impl core::cmp::Ord for [T]>::cmp (17 samples, 0.01%)<u8 as core::slice::cmp::SliceOrd>::compare (17 samples, 0.01%)alloc::collections::btree::map::BTreeMap<K,V,A>::get (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree (61 samples, 0.05%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::search_node (53 samples, 0.04%)alloc::collections::btree::search::<impl alloc::collections::btree::node::NodeRef<BorrowType,K,V,Type>>::find_key_index (53 samples, 0.04%)torrust_tracker::servers::udp::handlers::handle_request::{{closure}} (2,336 samples, 1.78%)t..torrust_tracker::servers::udp::handlers::handle_scrape::{{closure}} (101 samples, 0.08%)torrust_tracker::core::Tracker::scrape::{{closure}} (90 samples, 0.07%)torrust_tracker::core::Tracker::get_swarm_metadata (68 samples, 0.05%)torrust_tracker_torrent_repository::repository::rw_lock_std_mutex_std::<impl torrust_tracker_torrent_repository::repository::Repository<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> for torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>::get (64 samples, 0.05%)alloc::raw_vec::finish_grow (19 samples, 0.01%)alloc::vec::Vec<T,A>::reserve (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (21 samples, 0.02%)alloc::raw_vec::RawVec<T,A>::grow_amortized (21 samples, 0.02%)<alloc::string::String as core::fmt::Write>::write_str (23 samples, 0.02%)alloc::string::String::push_str (23 samples, 0.02%)alloc::vec::Vec<T,A>::extend_from_slice (23 samples, 0.02%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (23 samples, 0.02%)alloc::vec::Vec<T,A>::append_elements (23 samples, 0.02%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (85 samples, 0.06%)core::fmt::num::imp::fmt_u64 (78 samples, 0.06%)<alloc::string::String as core::fmt::Write>::write_str (15 samples, 0.01%)alloc::string::String::push_str (15 samples, 0.01%)alloc::vec::Vec<T,A>::extend_from_slice (15 samples, 0.01%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (15 samples, 0.01%)alloc::vec::Vec<T,A>::append_elements (15 samples, 0.01%)core::fmt::num::imp::<impl core::fmt::Display for i64>::fmt (37 samples, 0.03%)core::fmt::num::imp::fmt_u64 (36 samples, 0.03%)<T as alloc::string::ToString>::to_string (141 samples, 0.11%)core::option::Option<T>::expect (34 samples, 0.03%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (28 samples, 0.02%)alloc::alloc::dealloc (28 samples, 0.02%)__rdl_dealloc (28 samples, 0.02%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (28 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (55 samples, 0.04%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (55 samples, 0.04%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (55 samples, 0.04%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (55 samples, 0.04%)alloc::raw_vec::RawVec<T,A>::current_memory (20 samples, 0.02%)torrust_tracker::servers::udp::logging::map_action_name (16 samples, 0.01%)binascii::bin2hex (51 samples, 0.04%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (16 samples, 0.01%)core::fmt::write (25 samples, 0.02%)core::fmt::rt::Argument::fmt (15 samples, 0.01%)core::fmt::Formatter::write_fmt (87 samples, 0.07%)core::str::converts::from_utf8 (43 samples, 0.03%)core::str::validations::run_utf8_validation (37 samples, 0.03%)torrust_tracker_primitives::info_hash::InfoHash::to_hex_string (161 samples, 0.12%)<T as alloc::string::ToString>::to_string (161 samples, 0.12%)<torrust_tracker_primitives::info_hash::InfoHash as core::fmt::Display>::fmt (156 samples, 0.12%)torrust_tracker::servers::udp::logging::log_request (479 samples, 0.36%)[[vdso]] (51 samples, 0.04%)alloc::raw_vec::finish_grow (56 samples, 0.04%)alloc::vec::Vec<T,A>::reserve (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::reserve (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle (64 samples, 0.05%)alloc::raw_vec::RawVec<T,A>::grow_amortized (64 samples, 0.05%)<alloc::string::String as core::fmt::Write>::write_str (65 samples, 0.05%)alloc::string::String::push_str (65 samples, 0.05%)alloc::vec::Vec<T,A>::extend_from_slice (65 samples, 0.05%)<alloc::vec::Vec<T,A> as alloc::vec::spec_extend::SpecExtend<&T,core::slice::iter::Iter<T>>>::spec_extend (65 samples, 0.05%)alloc::vec::Vec<T,A>::append_elements (65 samples, 0.05%)core::fmt::num::imp::<impl core::fmt::Display for i32>::fmt (114 samples, 0.09%)core::fmt::num::imp::fmt_u64 (110 samples, 0.08%)<T as alloc::string::ToString>::to_string (132 samples, 0.10%)core::option::Option<T>::expect (20 samples, 0.02%)core::ptr::drop_in_place<alloc::string::String> (22 samples, 0.02%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (22 samples, 0.02%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (22 samples, 0.02%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (22 samples, 0.02%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (8,883 samples, 6.77%)torrust_t..torrust_tracker::servers::udp::logging::log_response (238 samples, 0.18%)__GI___lll_lock_wait_private (14 samples, 0.01%)futex_wait (14 samples, 0.01%)__GI___lll_lock_wake_private (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (17 samples, 0.01%)_int_malloc (191 samples, 0.15%)__libc_calloc (238 samples, 0.18%)__memcpy_avx512_unaligned_erms (34 samples, 0.03%)alloc::vec::from_elem (316 samples, 0.24%)<u8 as alloc::vec::spec_from_elem::SpecFromElem>::from_elem (316 samples, 0.24%)alloc::raw_vec::RawVec<T,A>::with_capacity_zeroed_in (316 samples, 0.24%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (316 samples, 0.24%)<alloc::alloc::Global as core::alloc::Allocator>::allocate_zeroed (312 samples, 0.24%)alloc::alloc::Global::alloc_impl (312 samples, 0.24%)alloc::alloc::alloc_zeroed (312 samples, 0.24%)__rdl_alloc_zeroed (312 samples, 0.24%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc_zeroed (312 samples, 0.24%)byteorder::ByteOrder::write_i32 (18 samples, 0.01%)<byteorder::BigEndian as byteorder::ByteOrder>::write_u32 (18 samples, 0.01%)core::num::<impl u32>::to_be_bytes (18 samples, 0.01%)core::num::<impl u32>::to_be (18 samples, 0.01%)core::num::<impl u32>::swap_bytes (18 samples, 0.01%)byteorder::io::WriteBytesExt::write_i32 (89 samples, 0.07%)std::io::Write::write_all (71 samples, 0.05%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (71 samples, 0.05%)std::io::cursor::vec_write (71 samples, 0.05%)std::io::cursor::vec_write_unchecked (51 samples, 0.04%)core::ptr::mut_ptr::<impl *mut T>::copy_from (51 samples, 0.04%)core::intrinsics::copy (51 samples, 0.04%)aquatic_udp_protocol::response::Response::write (227 samples, 0.17%)byteorder::io::WriteBytesExt::write_i64 (28 samples, 0.02%)std::io::Write::write_all (21 samples, 0.02%)<std::io::cursor::Cursor<alloc::vec::Vec<u8,A>> as std::io::Write>::write (21 samples, 0.02%)std::io::cursor::vec_write (21 samples, 0.02%)std::io::cursor::vec_write_unchecked (21 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::copy_from (21 samples, 0.02%)core::intrinsics::copy (21 samples, 0.02%)__GI___lll_lock_wake_private (17 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (14 samples, 0.01%)__GI___lll_lock_wait_private (16 samples, 0.01%)futex_wait (15 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (136 samples, 0.10%)__GI___libc_free (206 samples, 0.16%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (211 samples, 0.16%)alloc::alloc::dealloc (211 samples, 0.16%)__rdl_dealloc (211 samples, 0.16%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (211 samples, 0.16%)core::ptr::drop_in_place<std::io::cursor::Cursor<alloc::vec::Vec<u8>>> (224 samples, 0.17%)core::ptr::drop_in_place<alloc::vec::Vec<u8>> (224 samples, 0.17%)core::ptr::drop_in_place<alloc::raw_vec::RawVec<u8>> (224 samples, 0.17%)<alloc::raw_vec::RawVec<T,A> as core::ops::drop::Drop>::drop (224 samples, 0.17%)std::io::cursor::Cursor<T>::new (56 samples, 0.04%)tokio::io::ready::Ready::intersection (23 samples, 0.02%)tokio::io::ready::Ready::from_interest (23 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (83 samples, 0.06%)[unknown] (32,674 samples, 24.88%)[unknown][unknown] (32,402 samples, 24.68%)[unknown][unknown] (32,272 samples, 24.58%)[unknown][unknown] (32,215 samples, 24.54%)[unknown][unknown] (31,174 samples, 23.74%)[unknown][unknown] (30,794 samples, 23.45%)[unknown][unknown] (30,036 samples, 22.88%)[unknown][unknown] (28,639 samples, 21.81%)[unknown][unknown] (27,908 samples, 21.25%)[unknown][unknown] (26,013 samples, 19.81%)[unknown][unknown] (23,181 samples, 17.65%)[unknown][unknown] (19,559 samples, 14.90%)[unknown][unknown] (18,052 samples, 13.75%)[unknown][unknown] (15,794 samples, 12.03%)[unknown][unknown] (14,740 samples, 11.23%)[unknown][unknown] (12,486 samples, 9.51%)[unknown][unknown] (11,317 samples, 8.62%)[unknown][unknown] (10,725 samples, 8.17%)[unknown][unknown] (10,017 samples, 7.63%)[unknown][unknown] (9,713 samples, 7.40%)[unknown][unknown] (8,432 samples, 6.42%)[unknown][unknown] (8,062 samples, 6.14%)[unknown][unknown] (6,973 samples, 5.31%)[unknow..[unknown] (5,328 samples, 4.06%)[unk..[unknown] (4,352 samples, 3.31%)[un..[unknown] (3,786 samples, 2.88%)[u..[unknown] (3,659 samples, 2.79%)[u..[unknown] (3,276 samples, 2.50%)[u..[unknown] (2,417 samples, 1.84%)[..[unknown] (2,115 samples, 1.61%)[unknown] (1,610 samples, 1.23%)[unknown] (422 samples, 0.32%)[unknown] (84 samples, 0.06%)[unknown] (69 samples, 0.05%)__GI___pthread_disable_asynccancel (67 samples, 0.05%)__libc_sendto (32,896 samples, 25.05%)__libc_sendtotokio::net::udp::UdpSocket::send_to_addr::{{closure}}::{{closure}} (32,981 samples, 25.12%)tokio::net::udp::UdpSocket::send_to_addr..mio::net::udp::UdpSocket::send_to (32,981 samples, 25.12%)mio::net::udp::UdpSocket::send_tomio::io_source::IoSource<T>::do_io (32,981 samples, 25.12%)mio::io_source::IoSource<T>::do_iomio::sys::unix::stateless_io_source::IoSourceState::do_io (32,981 samples, 25.12%)mio::sys::unix::stateless_io_source::IoS..mio::net::udp::UdpSocket::send_to::{{closure}} (32,981 samples, 25.12%)mio::net::udp::UdpSocket::send_to::{{clo..std::net::udp::UdpSocket::send_to (32,981 samples, 25.12%)std::net::udp::UdpSocket::send_tostd::sys_common::net::UdpSocket::send_to (32,981 samples, 25.12%)std::sys_common::net::UdpSocket::send_tostd::sys::pal::unix::cvt (85 samples, 0.06%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (44,349 samples, 33.78%)torrust_tracker::servers::udp::server::Udp::process_req..torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (43,412 samples, 33.06%)torrust_tracker::servers::udp::server::Udp::process_va..torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (34,320 samples, 26.14%)torrust_tracker::servers::udp::server::Udp..torrust_tracker::servers::udp::server::Udp::send_packet::{{closure}} (33,360 samples, 25.41%)torrust_tracker::servers::udp::server::Ud..tokio::net::udp::UdpSocket::send_to::{{closure}} (33,227 samples, 25.31%)tokio::net::udp::UdpSocket::send_to::{{c..tokio::net::udp::UdpSocket::send_to_addr::{{closure}} (33,142 samples, 25.24%)tokio::net::udp::UdpSocket::send_to_addr..tokio::runtime::io::registration::Registration::async_io::{{closure}} (33,115 samples, 25.22%)tokio::runtime::io::registration::Regist..tokio::runtime::io::registration::Registration::readiness::{{closure}} (28 samples, 0.02%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (18 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (15 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (14 samples, 0.01%)<alloc::sync::Arc<T,A> as core::clone::Clone>::clone (15 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (15 samples, 0.01%)core::sync::atomic::atomic_add (15 samples, 0.01%)__GI___lll_lock_wait_private (16 samples, 0.01%)futex_wait (16 samples, 0.01%)[unknown] (16 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (15 samples, 0.01%)[unknown] (14 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (135 samples, 0.10%)__GI___libc_free (147 samples, 0.11%)syscall (22 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Core<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (15 samples, 0.01%)tokio::runtime::task::harness::Harness<T,S>::dealloc (24 samples, 0.02%)core::mem::drop (24 samples, 0.02%)core::ptr::drop_in_place<alloc::boxed::Box<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>>> (24 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::core::Cell<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}},alloc::sync::Arc<tokio::runtime::scheduler::multi_thread::handle::Handle>>> (24 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::task::abort::AbortHandle> (262 samples, 0.20%)<tokio::runtime::task::abort::AbortHandle as core::ops::drop::Drop>::drop (262 samples, 0.20%)tokio::runtime::task::raw::RawTask::drop_abort_handle (256 samples, 0.19%)tokio::runtime::task::raw::drop_abort_handle (59 samples, 0.04%)tokio::runtime::task::harness::Harness<T,S>::drop_reference (50 samples, 0.04%)tokio::runtime::task::state::State::ref_dec (50 samples, 0.04%)tokio::runtime::task::raw::RawTask::drop_join_handle_slow (16 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::join::JoinHandle<()>> (47 samples, 0.04%)<tokio::runtime::task::join::JoinHandle<T> as core::ops::drop::Drop>::drop (47 samples, 0.04%)tokio::runtime::task::state::State::drop_join_handle_fast (19 samples, 0.01%)core::sync::atomic::AtomicUsize::compare_exchange_weak (19 samples, 0.01%)core::sync::atomic::atomic_compare_exchange_weak (19 samples, 0.01%)ringbuf::ring_buffer::base::RbBase::is_full (14 samples, 0.01%)<ringbuf::ring_buffer::shared::SharedRb<T,C> as ringbuf::ring_buffer::base::RbBase<T>>::head (14 samples, 0.01%)core::sync::atomic::AtomicUsize::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)ringbuf::consumer::Consumer<T,R>::advance (29 samples, 0.02%)ringbuf::ring_buffer::base::RbRead::advance_head (29 samples, 0.02%)ringbuf::ring_buffer::rb::Rb::pop (50 samples, 0.04%)ringbuf::consumer::Consumer<T,R>::pop (50 samples, 0.04%)ringbuf::producer::Producer<T,R>::advance (23 samples, 0.02%)ringbuf::ring_buffer::base::RbWrite::advance_tail (23 samples, 0.02%)core::num::nonzero::<impl core::ops::arith::Rem<core::num::nonzero::NonZero<usize>> for usize>::rem (19 samples, 0.01%)ringbuf::ring_buffer::rb::Rb::push_overwrite (107 samples, 0.08%)ringbuf::ring_buffer::rb::Rb::push (43 samples, 0.03%)ringbuf::producer::Producer<T,R>::push (43 samples, 0.03%)tokio::runtime::task::abort::AbortHandle::is_finished (84 samples, 0.06%)tokio::runtime::task::state::Snapshot::is_complete (84 samples, 0.06%)tokio::runtime::task::join::JoinHandle<T>::abort_handle (17 samples, 0.01%)tokio::runtime::task::raw::RawTask::ref_inc (17 samples, 0.01%)tokio::runtime::task::state::State::ref_inc (17 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (14 samples, 0.01%)core::sync::atomic::atomic_add (14 samples, 0.01%)__GI___lll_lock_wake_private (22 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)malloc_consolidate (95 samples, 0.07%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (76 samples, 0.06%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (31 samples, 0.02%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (26 samples, 0.02%)_int_malloc (282 samples, 0.21%)__GI___libc_malloc (323 samples, 0.25%)alloc::vec::Vec<T>::with_capacity (326 samples, 0.25%)alloc::vec::Vec<T,A>::with_capacity_in (326 samples, 0.25%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (324 samples, 0.25%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (324 samples, 0.25%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (324 samples, 0.25%)alloc::alloc::Global::alloc_impl (324 samples, 0.25%)alloc::alloc::alloc (324 samples, 0.25%)__rdl_alloc (324 samples, 0.25%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (324 samples, 0.25%)tokio::io::ready::Ready::intersection (24 samples, 0.02%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (199 samples, 0.15%)tokio::util::bit::Pack::unpack (16 samples, 0.01%)tokio::util::bit::unpack (16 samples, 0.01%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (19 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (17 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (16 samples, 0.01%)tokio::net::udp::UdpSocket::readable::{{closure}} (222 samples, 0.17%)tokio::net::udp::UdpSocket::ready::{{closure}} (222 samples, 0.17%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (50 samples, 0.04%)std::io::error::repr_bitpacked::Repr::data (14 samples, 0.01%)std::io::error::repr_bitpacked::decode_repr (14 samples, 0.01%)std::io::error::Error::kind (16 samples, 0.01%)<core::result::Result<T,E> as core::ops::try_trait::Try>::branch (14 samples, 0.01%)[unknown] (8,756 samples, 6.67%)[unknown][unknown] (8,685 samples, 6.61%)[unknown][unknown] (8,574 samples, 6.53%)[unknown][unknown] (8,415 samples, 6.41%)[unknown][unknown] (7,686 samples, 5.85%)[unknow..[unknown] (7,239 samples, 5.51%)[unknow..[unknown] (6,566 samples, 5.00%)[unkno..[unknown] (5,304 samples, 4.04%)[unk..[unknown] (4,008 samples, 3.05%)[un..[unknown] (3,571 samples, 2.72%)[u..[unknown] (2,375 samples, 1.81%)[..[unknown] (1,844 samples, 1.40%)[unknown] (1,030 samples, 0.78%)[unknown] (344 samples, 0.26%)[unknown] (113 samples, 0.09%)__libc_recvfrom (8,903 samples, 6.78%)__libc_re..__GI___pthread_disable_asynccancel (22 samples, 0.02%)std::sys::pal::unix::cvt (20 samples, 0.02%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (9,005 samples, 6.86%)tokio::ne..mio::net::udp::UdpSocket::recv_from (8,964 samples, 6.83%)mio::net:..mio::io_source::IoSource<T>::do_io (8,964 samples, 6.83%)mio::io_s..mio::sys::unix::stateless_io_source::IoSourceState::do_io (8,964 samples, 6.83%)mio::sys:..mio::net::udp::UdpSocket::recv_from::{{closure}} (8,964 samples, 6.83%)mio::net:..std::net::udp::UdpSocket::recv_from (8,964 samples, 6.83%)std::net:..std::sys_common::net::UdpSocket::recv_from (8,964 samples, 6.83%)std::sys_..std::sys::pal::unix::net::Socket::recv_from (8,964 samples, 6.83%)std::sys:..std::sys::pal::unix::net::Socket::recv_from_with_flags (8,964 samples, 6.83%)std::sys:..std::sys_common::net::sockaddr_to_addr (23 samples, 0.02%)tokio::runtime::io::registration::Registration::clear_readiness (18 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::clear_readiness (18 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (32 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (9,967 samples, 7.59%)torrust_tr..tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (9,291 samples, 7.08%)tokio::ne..tokio::runtime::io::registration::Registration::async_io::{{closure}} (9,287 samples, 7.07%)tokio::ru..tokio::runtime::io::registration::Registration::readiness::{{closure}} (45 samples, 0.03%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (41 samples, 0.03%)__memcpy_avx512_unaligned_erms (424 samples, 0.32%)__memcpy_avx512_unaligned_erms (493 samples, 0.38%)__memcpy_avx512_unaligned_erms (298 samples, 0.23%)syscall (1,105 samples, 0.84%)[unknown] (1,095 samples, 0.83%)[unknown] (1,091 samples, 0.83%)[unknown] (1,049 samples, 0.80%)[unknown] (998 samples, 0.76%)[unknown] (907 samples, 0.69%)[unknown] (710 samples, 0.54%)[unknown] (635 samples, 0.48%)[unknown] (538 samples, 0.41%)[unknown] (358 samples, 0.27%)[unknown] (256 samples, 0.19%)[unknown] (153 samples, 0.12%)[unknown] (96 samples, 0.07%)[unknown] (81 samples, 0.06%)tokio::runtime::context::with_scheduler (36 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (31 samples, 0.02%)tokio::runtime::context::with_scheduler::{{closure}} (27 samples, 0.02%)tokio::runtime::context::scoped::Scoped<T>::with (27 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (25 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (15 samples, 0.01%)core::sync::atomic::AtomicUsize::fetch_add (340 samples, 0.26%)core::sync::atomic::atomic_add (340 samples, 0.26%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (354 samples, 0.27%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (367 samples, 0.28%)[unknown] (95 samples, 0.07%)[unknown] (93 samples, 0.07%)[unknown] (92 samples, 0.07%)[unknown] (90 samples, 0.07%)[unknown] (82 samples, 0.06%)[unknown] (73 samples, 0.06%)[unknown] (63 samples, 0.05%)[unknown] (44 samples, 0.03%)[unknown] (40 samples, 0.03%)[unknown] (35 samples, 0.03%)[unknown] (30 samples, 0.02%)[unknown] (22 samples, 0.02%)[unknown] (21 samples, 0.02%)[unknown] (20 samples, 0.02%)[unknown] (17 samples, 0.01%)tokio::runtime::driver::Handle::unpark (99 samples, 0.08%)tokio::runtime::driver::IoHandle::unpark (99 samples, 0.08%)tokio::runtime::io::driver::Handle::unpark (99 samples, 0.08%)mio::waker::Waker::wake (99 samples, 0.08%)mio::sys::unix::waker::fdbased::Waker::wake (99 samples, 0.08%)mio::sys::unix::waker::eventfd::WakerInternal::wake (99 samples, 0.08%)<&std::fs::File as std::io::Write>::write (99 samples, 0.08%)std::sys::pal::unix::fs::File::write (99 samples, 0.08%)std::sys::pal::unix::fd::FileDesc::write (99 samples, 0.08%)__GI___libc_write (99 samples, 0.08%)__GI___libc_write (99 samples, 0.08%)tokio::runtime::context::with_scheduler (1,615 samples, 1.23%)std::thread::local::LocalKey<T>::try_with (1,613 samples, 1.23%)tokio::runtime::context::with_scheduler::{{closure}} (1,612 samples, 1.23%)tokio::runtime::context::scoped::Scoped<T>::with (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::with_current::{{closure}} (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task::{{closure}} (1,611 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_local (1,609 samples, 1.23%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (1,609 samples, 1.23%)tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (101 samples, 0.08%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (101 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_option_task_without_yield (1,647 samples, 1.25%)tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::schedule_task (1,646 samples, 1.25%)tokio::runtime::scheduler::multi_thread::worker::with_current (1,646 samples, 1.25%)tokio::util::sharded_list::ShardGuard<L,<L as tokio::util::linked_list::Link>::Target>::push (23 samples, 0.02%)tokio::util::linked_list::LinkedList<L,<L as tokio::util::linked_list::Link>::Target>::push_front (18 samples, 0.01%)tokio::runtime::task::list::OwnedTasks<S>::bind_inner (104 samples, 0.08%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::lock_shard (60 samples, 0.05%)tokio::util::sharded_list::ShardedList<L,<L as tokio::util::linked_list::Link>::Target>::shard_inner (57 samples, 0.04%)tokio::loom::std::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sync::mutex::Mutex<T>::lock (51 samples, 0.04%)std::sys::sync::mutex::futex::Mutex::lock (49 samples, 0.04%)core::sync::atomic::AtomicU32::compare_exchange (38 samples, 0.03%)core::sync::atomic::atomic_compare_exchange (38 samples, 0.03%)__memcpy_avx512_unaligned_erms (162 samples, 0.12%)__memcpy_avx512_unaligned_erms (34 samples, 0.03%)__GI___lll_lock_wake_private (127 samples, 0.10%)[unknown] (125 samples, 0.10%)[unknown] (124 samples, 0.09%)[unknown] (119 samples, 0.09%)[unknown] (110 samples, 0.08%)[unknown] (106 samples, 0.08%)[unknown] (87 samples, 0.07%)[unknown] (82 samples, 0.06%)[unknown] (51 samples, 0.04%)[unknown] (27 samples, 0.02%)[unknown] (19 samples, 0.01%)[unknown] (14 samples, 0.01%)_int_free (77 samples, 0.06%)[unknown] (1,207 samples, 0.92%)[unknown] (1,146 samples, 0.87%)[unknown] (1,126 samples, 0.86%)[unknown] (1,091 samples, 0.83%)[unknown] (1,046 samples, 0.80%)[unknown] (962 samples, 0.73%)[unknown] (914 samples, 0.70%)[unknown] (848 samples, 0.65%)[unknown] (774 samples, 0.59%)[unknown] (580 samples, 0.44%)[unknown] (456 samples, 0.35%)[unknown] (305 samples, 0.23%)[unknown] (85 samples, 0.06%)__GI_mprotect (2,474 samples, 1.88%)_..[unknown] (2,457 samples, 1.87%)[..[unknown] (2,440 samples, 1.86%)[..[unknown] (2,436 samples, 1.86%)[..[unknown] (2,435 samples, 1.85%)[..[unknown] (2,360 samples, 1.80%)[..[unknown] (2,203 samples, 1.68%)[unknown] (1,995 samples, 1.52%)[unknown] (1,709 samples, 1.30%)[unknown] (1,524 samples, 1.16%)[unknown] (1,193 samples, 0.91%)[unknown] (865 samples, 0.66%)[unknown] (539 samples, 0.41%)[unknown] (259 samples, 0.20%)[unknown] (80 samples, 0.06%)[unknown] (29 samples, 0.02%)sysmalloc (3,786 samples, 2.88%)sy..grow_heap (2,509 samples, 1.91%)g.._int_malloc (4,038 samples, 3.08%)_in..unlink_chunk (31 samples, 0.02%)alloc::alloc::exchange_malloc (4,335 samples, 3.30%)all..<alloc::alloc::Global as core::alloc::Allocator>::allocate (4,329 samples, 3.30%)<al..alloc::alloc::Global::alloc_impl (4,329 samples, 3.30%)all..alloc::alloc::alloc (4,329 samples, 3.30%)all..__rdl_alloc (4,329 samples, 3.30%)__r..std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (4,329 samples, 3.30%)std..std::sys::pal::unix::alloc::aligned_malloc (4,329 samples, 3.30%)std..__posix_memalign (4,297 samples, 3.27%)__p..__posix_memalign (4,297 samples, 3.27%)__p.._mid_memalign (4,297 samples, 3.27%)_mi.._int_memalign (4,149 samples, 3.16%)_in..sysmalloc (18 samples, 0.01%)core::option::Option<T>::map (6,666 samples, 5.08%)core::..tokio::task::spawn::spawn_inner::{{closure}} (6,665 samples, 5.08%)tokio:..tokio::runtime::scheduler::Handle::spawn (6,665 samples, 5.08%)tokio:..tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (6,664 samples, 5.08%)tokio:..tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (6,661 samples, 5.07%)tokio:..tokio::runtime::task::list::OwnedTasks<S>::bind (4,692 samples, 3.57%)toki..tokio::runtime::task::new_task (4,579 samples, 3.49%)tok..tokio::runtime::task::raw::RawTask::new (4,579 samples, 3.49%)tok..tokio::runtime::task::core::Cell<T,S>::new (4,579 samples, 3.49%)tok..alloc::boxed::Box<T>::new (4,389 samples, 3.34%)all..tokio::runtime::context::current::with_current (7,636 samples, 5.82%)tokio::..std::thread::local::LocalKey<T>::try_with (7,635 samples, 5.81%)std::th..tokio::runtime::context::current::with_current::{{closure}} (7,188 samples, 5.47%)tokio::..tokio::task::spawn::spawn (7,670 samples, 5.84%)tokio::..tokio::task::spawn::spawn_inner (7,670 samples, 5.84%)tokio::..tokio::runtime::task::id::Id::next (24 samples, 0.02%)core::sync::atomic::AtomicU64::fetch_add (24 samples, 0.02%)core::sync::atomic::atomic_add (24 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (62,691 samples, 47.75%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (62,691 samples, 47.75%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (18,228 samples, 13.88%)torrust_tracker::serv..torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (18,226 samples, 13.88%)torrust_tracker::serv..torrust_tracker::servers::udp::server::Udp::spawn_request_processor (7,679 samples, 5.85%)torrust..__memcpy_avx512_unaligned_erms (38 samples, 0.03%)__memcpy_avx512_unaligned_erms (407 samples, 0.31%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (411 samples, 0.31%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (411 samples, 0.31%)tokio::runtime::task::core::Core<T,S>::poll (63,150 samples, 48.10%)tokio::runtime::task::core::Core<T,S>::polltokio::runtime::task::core::Core<T,S>::drop_future_or_output (459 samples, 0.35%)tokio::runtime::task::core::Core<T,S>::set_stage (459 samples, 0.35%)__memcpy_avx512_unaligned_erms (16 samples, 0.01%)__memcpy_avx512_unaligned_erms (398 samples, 0.30%)__memcpy_avx512_unaligned_erms (325 samples, 0.25%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (330 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (330 samples, 0.25%)tokio::runtime::task::core::Core<T,S>::set_stage (731 samples, 0.56%)tokio::runtime::task::harness::poll_future (63,908 samples, 48.67%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (63,908 samples, 48.67%)std::panic::catch_unwindstd::panicking::try (63,908 samples, 48.67%)std::panicking::trystd::panicking::try::do_call (63,908 samples, 48.67%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (63,908 samples, 48.67%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()..tokio::runtime::task::harness::poll_future::{{closure}} (63,908 samples, 48.67%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::store_output (758 samples, 0.58%)tokio::runtime::coop::budget (65,027 samples, 49.53%)tokio::runtime::coop::budgettokio::runtime::coop::with_budget (65,027 samples, 49.53%)tokio::runtime::coop::with_budgettokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (65,009 samples, 49.51%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}}tokio::runtime::task::LocalNotified<S>::run (65,003 samples, 49.51%)tokio::runtime::task::LocalNotified<S>::runtokio::runtime::task::raw::RawTask::poll (65,003 samples, 49.51%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (64,538 samples, 49.15%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (64,493 samples, 49.12%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (63,919 samples, 48.68%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::scheduler::multi_thread::stats::Stats::start_poll (93 samples, 0.07%)syscall (2,486 samples, 1.89%)s..[unknown] (2,424 samples, 1.85%)[..[unknown] (2,416 samples, 1.84%)[..[unknown] (2,130 samples, 1.62%)[unknown] (2,013 samples, 1.53%)[unknown] (1,951 samples, 1.49%)[unknown] (1,589 samples, 1.21%)[unknown] (1,415 samples, 1.08%)[unknown] (1,217 samples, 0.93%)[unknown] (820 samples, 0.62%)[unknown] (564 samples, 0.43%)[unknown] (360 samples, 0.27%)[unknown] (244 samples, 0.19%)[unknown] (194 samples, 0.15%)tokio::runtime::scheduler::multi_thread::idle::Idle::notify_should_wakeup (339 samples, 0.26%)core::sync::atomic::AtomicUsize::fetch_add (337 samples, 0.26%)core::sync::atomic::atomic_add (337 samples, 0.26%)tokio::runtime::scheduler::multi_thread::idle::Idle::worker_to_notify (364 samples, 0.28%)[unknown] (154 samples, 0.12%)[unknown] (152 samples, 0.12%)[unknown] (143 samples, 0.11%)[unknown] (139 samples, 0.11%)[unknown] (131 samples, 0.10%)[unknown] (123 samples, 0.09%)[unknown] (110 samples, 0.08%)[unknown] (80 samples, 0.06%)[unknown] (74 samples, 0.06%)[unknown] (65 samples, 0.05%)[unknown] (64 samples, 0.05%)[unknown] (47 samples, 0.04%)[unknown] (44 samples, 0.03%)[unknown] (43 samples, 0.03%)[unknown] (40 samples, 0.03%)[unknown] (26 samples, 0.02%)[unknown] (20 samples, 0.02%)__GI___libc_write (158 samples, 0.12%)__GI___libc_write (158 samples, 0.12%)mio::sys::unix::waker::eventfd::WakerInternal::wake (159 samples, 0.12%)<&std::fs::File as std::io::Write>::write (159 samples, 0.12%)std::sys::pal::unix::fs::File::write (159 samples, 0.12%)std::sys::pal::unix::fd::FileDesc::write (159 samples, 0.12%)tokio::runtime::driver::Handle::unpark (168 samples, 0.13%)tokio::runtime::driver::IoHandle::unpark (168 samples, 0.13%)tokio::runtime::io::driver::Handle::unpark (168 samples, 0.13%)mio::waker::Waker::wake (165 samples, 0.13%)mio::sys::unix::waker::fdbased::Waker::wake (165 samples, 0.13%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (68,159 samples, 51.91%)tokio::runtime::scheduler::multi_thread::worker::Context::run_tasktokio::runtime::scheduler::multi_thread::worker::Core::transition_from_searching (3,024 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::transition_worker_from_searching (3,023 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::worker::<impl tokio::runtime::scheduler::multi_thread::handle::Handle>::notify_parked_local (3,022 samples, 2.30%)t..tokio::runtime::scheduler::multi_thread::park::Unparker::unpark (171 samples, 0.13%)tokio::runtime::scheduler::multi_thread::park::Inner::unpark (171 samples, 0.13%)core::option::Option<T>::or_else (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task::{{closure}} (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Local<T>::pop (14 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::next_local_task (18 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Core::tune_global_queue_interval (53 samples, 0.04%)tokio::runtime::scheduler::multi_thread::stats::Stats::tuned_global_queue_interval (53 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::next_task (107 samples, 0.08%)__GI___libc_free (17 samples, 0.01%)_int_free (17 samples, 0.01%)alloc::collections::btree::navigate::LazyLeafRange<alloc::collections::btree::node::marker::Dying,K,V>::deallocating_end (18 samples, 0.01%)alloc::collections::btree::navigate::<impl alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::Leaf>,alloc::collections::btree::node::marker::Edge>>::deallocating_end (18 samples, 0.01%)alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,alloc::collections::btree::node::marker::LeafOrInternal>::deallocate_and_ascend (18 samples, 0.01%)<alloc::alloc::Global as core::alloc::Allocator>::deallocate (18 samples, 0.01%)alloc::alloc::dealloc (18 samples, 0.01%)__rdl_dealloc (18 samples, 0.01%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::dealloc (18 samples, 0.01%)alloc::collections::btree::map::IntoIter<K,V,A>::dying_next (19 samples, 0.01%)tokio::runtime::task::Task<S>::shutdown (26 samples, 0.02%)tokio::runtime::task::raw::RawTask::shutdown (26 samples, 0.02%)tokio::runtime::task::raw::shutdown (26 samples, 0.02%)tokio::runtime::task::harness::Harness<T,S>::shutdown (26 samples, 0.02%)tokio::runtime::task::harness::cancel_task (26 samples, 0.02%)std::panic::catch_unwind (26 samples, 0.02%)std::panicking::try (26 samples, 0.02%)std::panicking::try::do_call (26 samples, 0.02%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (26 samples, 0.02%)core::ops::function::FnOnce::call_once (26 samples, 0.02%)tokio::runtime::task::harness::cancel_task::{{closure}} (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::drop_future_or_output (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage (26 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (26 samples, 0.02%)tokio::runtime::task::core::Core<T,S>::set_stage::{{closure}} (26 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker::core::Tracker> (26 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (26 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker_torrent_repository::repository::RwLockStd<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)core::ptr::drop_in_place<std::sync::rwlock::RwLock<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>>> (26 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)core::mem::drop (26 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker_primitives::info_hash::InfoHash,alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>>> (26 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (26 samples, 0.02%)alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Dying,K,V,NodeType>,alloc::collections::btree::node::marker::KV>::drop_key_val (24 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::assume_init_drop (24 samples, 0.02%)core::ptr::drop_in_place<alloc::sync::Arc<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>>> (24 samples, 0.02%)<alloc::sync::Arc<T,A> as core::ops::drop::Drop>::drop (24 samples, 0.02%)alloc::sync::Arc<T,A>::drop_slow (21 samples, 0.02%)core::ptr::drop_in_place<std::sync::mutex::Mutex<torrust_tracker_torrent_repository::entry::Torrent>> (20 samples, 0.02%)core::ptr::drop_in_place<core::cell::UnsafeCell<torrust_tracker_torrent_repository::entry::Torrent>> (20 samples, 0.02%)core::ptr::drop_in_place<torrust_tracker_torrent_repository::entry::Torrent> (20 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::BTreeMap<torrust_tracker_primitives::PeerId,alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (20 samples, 0.02%)<alloc::collections::btree::map::BTreeMap<K,V,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)core::mem::drop (20 samples, 0.02%)core::ptr::drop_in_place<alloc::collections::btree::map::IntoIter<torrust_tracker_primitives::PeerId,alloc::sync::Arc<torrust_tracker_primitives::peer::Peer>>> (20 samples, 0.02%)<alloc::collections::btree::map::IntoIter<K,V,A> as core::ops::drop::Drop>::drop (20 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::pre_shutdown (33 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::close_and_shutdown_all (33 samples, 0.03%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (114 samples, 0.09%)alloc::sync::Arc<T,A>::inner (114 samples, 0.09%)core::ptr::non_null::NonNull<T>::as_ref (114 samples, 0.09%)core::iter::range::<impl core::iter::traits::iterator::Iterator for core::ops::range::Range<A>>::next (108 samples, 0.08%)<core::ops::range::Range<T> as core::iter::range::RangeIteratorImpl>::spec_next (108 samples, 0.08%)core::cmp::impls::<impl core::cmp::PartialOrd for usize>::lt (106 samples, 0.08%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (49 samples, 0.04%)alloc::sync::Arc<T,A>::inner (49 samples, 0.04%)core::ptr::non_null::NonNull<T>::as_ref (49 samples, 0.04%)core::num::<impl u32>::wrapping_sub (132 samples, 0.10%)core::sync::atomic::AtomicU64::load (40 samples, 0.03%)core::sync::atomic::atomic_load (40 samples, 0.03%)tokio::loom::std::atomic_u32::AtomicU32::unsync_load (48 samples, 0.04%)core::sync::atomic::AtomicU32::load (48 samples, 0.04%)core::sync::atomic::atomic_load (48 samples, 0.04%)<alloc::sync::Arc<T,A> as core::ops::deref::Deref>::deref (65 samples, 0.05%)alloc::sync::Arc<T,A>::inner (65 samples, 0.05%)core::ptr::non_null::NonNull<T>::as_ref (65 samples, 0.05%)core::num::<impl u32>::wrapping_sub (50 samples, 0.04%)core::sync::atomic::AtomicU32::load (55 samples, 0.04%)core::sync::atomic::atomic_load (55 samples, 0.04%)core::sync::atomic::AtomicU64::load (80 samples, 0.06%)core::sync::atomic::atomic_load (80 samples, 0.06%)tokio::runtime::scheduler::multi_thread::queue::pack (26 samples, 0.02%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (666 samples, 0.51%)tokio::runtime::scheduler::multi_thread::queue::unpack (147 samples, 0.11%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (1,036 samples, 0.79%)tokio::runtime::scheduler::multi_thread::queue::unpack (46 samples, 0.04%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_to_searching (49 samples, 0.04%)tokio::runtime::scheduler::multi_thread::idle::Idle::transition_worker_to_searching (21 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (2,414 samples, 1.84%)t..tokio::util::rand::FastRand::fastrand_n (24 samples, 0.02%)tokio::util::rand::FastRand::fastrand (24 samples, 0.02%)std::sys_common::backtrace::__rust_begin_short_backtrace (98,136 samples, 74.74%)std::sys_common::backtrace::__rust_begin_short_backtracetokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}} (98,136 samples, 74.74%)tokio::runtime::blocking::pool::Spawner::spawn_thread::{{closure}}tokio::runtime::blocking::pool::Inner::run (98,136 samples, 74.74%)tokio::runtime::blocking::pool::Inner::runtokio::runtime::blocking::pool::Task::run (98,042 samples, 74.67%)tokio::runtime::blocking::pool::Task::runtokio::runtime::task::UnownedTask<S>::run (98,042 samples, 74.67%)tokio::runtime::task::UnownedTask<S>::runtokio::runtime::task::raw::RawTask::poll (98,042 samples, 74.67%)tokio::runtime::task::raw::RawTask::polltokio::runtime::task::raw::poll (98,042 samples, 74.67%)tokio::runtime::task::raw::polltokio::runtime::task::harness::Harness<T,S>::poll (98,042 samples, 74.67%)tokio::runtime::task::harness::Harness<T,S>::polltokio::runtime::task::harness::Harness<T,S>::poll_inner (98,042 samples, 74.67%)tokio::runtime::task::harness::Harness<T,S>::poll_innertokio::runtime::task::harness::poll_future (98,042 samples, 74.67%)tokio::runtime::task::harness::poll_futurestd::panic::catch_unwind (98,042 samples, 74.67%)std::panic::catch_unwindstd::panicking::try (98,042 samples, 74.67%)std::panicking::trystd::panicking::try::do_call (98,042 samples, 74.67%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (98,042 samples, 74.67%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncetokio::runtime::task::harness::poll_future::{{closure}} (98,042 samples, 74.67%)tokio::runtime::task::harness::poll_future::{{closure}}tokio::runtime::task::core::Core<T,S>::poll (98,042 samples, 74.67%)tokio::runtime::task::core::Core<T,S>::polltokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (98,042 samples, 74.67%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_muttokio::runtime::task::core::Core<T,S>::poll::{{closure}} (98,042 samples, 74.67%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}}<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (98,042 samples, 74.67%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::polltokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}}tokio::runtime::scheduler::multi_thread::worker::run (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::runtokio::runtime::context::runtime::enter_runtime (98,042 samples, 74.67%)tokio::runtime::context::runtime::enter_runtimetokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}tokio::runtime::context::set_scheduler (98,042 samples, 74.67%)tokio::runtime::context::set_schedulerstd::thread::local::LocalKey<T>::with (98,042 samples, 74.67%)std::thread::local::LocalKey<T>::withstd::thread::local::LocalKey<T>::try_with (98,042 samples, 74.67%)std::thread::local::LocalKey<T>::try_withtokio::runtime::context::set_scheduler::{{closure}} (98,042 samples, 74.67%)tokio::runtime::context::set_scheduler::{{closure}}tokio::runtime::context::scoped::Scoped<T>::set (98,042 samples, 74.67%)tokio::runtime::context::scoped::Scoped<T>::settokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}}tokio::runtime::scheduler::multi_thread::worker::Context::run (98,042 samples, 74.67%)tokio::runtime::scheduler::multi_thread::worker::Context::runstd::panic::catch_unwind (98,137 samples, 74.74%)std::panic::catch_unwindstd::panicking::try (98,137 samples, 74.74%)std::panicking::trystd::panicking::try::do_call (98,137 samples, 74.74%)std::panicking::try::do_call<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (98,137 samples, 74.74%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_oncestd::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}} (98,137 samples, 74.74%)std::thread::Builder::spawn_unchecked_::{{closure}}::{{closure}}<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (98,139 samples, 74.74%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_once (98,139 samples, 74.74%)<alloc::boxed::Box<F,A> as core::ops::function::FnOnce<Args>>::call_oncecore::ops::function::FnOnce::call_once{{vtable.shim}} (98,139 samples, 74.74%)core::ops::function::FnOnce::call_once{{vtable.shim}}std::thread::Builder::spawn_unchecked_::{{closure}} (98,139 samples, 74.74%)std::thread::Builder::spawn_unchecked_::{{closure}}clone3 (98,205 samples, 74.79%)clone3start_thread (98,205 samples, 74.79%)start_threadstd::sys::pal::unix::thread::Thread::new::thread_start (98,158 samples, 74.76%)std::sys::pal::unix::thread::Thread::new::thread_startcore::ptr::drop_in_place<std::sys::pal::unix::stack_overflow::Handler> (19 samples, 0.01%)<std::sys::pal::unix::stack_overflow::Handler as core::ops::drop::Drop>::drop (19 samples, 0.01%)std::sys::pal::unix::stack_overflow::imp::drop_handler (19 samples, 0.01%)__GI_munmap (19 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (18 samples, 0.01%)[unknown] (17 samples, 0.01%)[unknown] (16 samples, 0.01%)core::fmt::Formatter::pad_integral (112 samples, 0.09%)core::fmt::Formatter::pad_integral::write_prefix (59 samples, 0.04%)core::fmt::Formatter::pad_integral (16 samples, 0.01%)core::fmt::write (20 samples, 0.02%)core::ptr::drop_in_place<aquatic_udp_protocol::response::Response> (19 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::Stage<torrust_tracker::servers::udp::server::Udp::process_request::{{closure}}>> (51 samples, 0.04%)rand_chacha::guts::round (18 samples, 0.01%)rand_chacha::guts::refill_wide::impl_avx2 (26 samples, 0.02%)rand_chacha::guts::refill_wide::fn_impl (26 samples, 0.02%)rand_chacha::guts::refill_wide_impl (26 samples, 0.02%)rand_chacha::guts::refill_wide (14 samples, 0.01%)std_detect::detect::arch::x86::__is_feature_detected::avx2 (14 samples, 0.01%)std_detect::detect::check_for (14 samples, 0.01%)std_detect::detect::cache::test (14 samples, 0.01%)std_detect::detect::cache::Cache::test (14 samples, 0.01%)core::sync::atomic::AtomicUsize::load (14 samples, 0.01%)core::sync::atomic::atomic_load (14 samples, 0.01%)core::cell::RefCell<T>::borrow_mut (81 samples, 0.06%)core::cell::RefCell<T>::try_borrow_mut (81 samples, 0.06%)core::cell::BorrowRefMut::new (81 samples, 0.06%)std::sys::pal::unix::time::Timespec::now (164 samples, 0.12%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task (106 samples, 0.08%)tokio::runtime::coop::budget (105 samples, 0.08%)tokio::runtime::coop::with_budget (105 samples, 0.08%)tokio::runtime::scheduler::multi_thread::worker::Context::run_task::{{closure}} (96 samples, 0.07%)std::sys::pal::unix::time::Timespec::sub_timespec (35 samples, 0.03%)std::sys::sync::mutex::futex::Mutex::lock_contended (15 samples, 0.01%)syscall (90 samples, 0.07%)tokio::runtime::io::scheduled_io::ScheduledIo::wake (15 samples, 0.01%)tokio::runtime::scheduler::multi_thread::worker::Context::park (22 samples, 0.02%)tokio::runtime::scheduler::multi_thread::worker::Core::transition_from_parked (21 samples, 0.02%)<tokio::runtime::blocking::task::BlockingTask<T> as core::future::future::Future>::poll (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Launch::launch::{{closure}} (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run (61 samples, 0.05%)tokio::runtime::context::runtime::enter_runtime (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}} (61 samples, 0.05%)tokio::runtime::context::set_scheduler (61 samples, 0.05%)std::thread::local::LocalKey<T>::with (61 samples, 0.05%)std::thread::local::LocalKey<T>::try_with (61 samples, 0.05%)tokio::runtime::context::set_scheduler::{{closure}} (61 samples, 0.05%)tokio::runtime::context::scoped::Scoped<T>::set (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::run::{{closure}}::{{closure}} (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Context::run (61 samples, 0.05%)tokio::runtime::scheduler::multi_thread::worker::Core::steal_work (19 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into (17 samples, 0.01%)tokio::runtime::scheduler::multi_thread::queue::Steal<T>::steal_into2 (17 samples, 0.01%)tokio::runtime::context::CONTEXT::__getit (14 samples, 0.01%)core::cell::Cell<T>::get (14 samples, 0.01%)core::ptr::drop_in_place<tokio::runtime::task::core::TaskIdGuard> (22 samples, 0.02%)<tokio::runtime::task::core::TaskIdGuard as core::ops::drop::Drop>::drop (22 samples, 0.02%)tokio::runtime::context::set_current_task_id (22 samples, 0.02%)std::thread::local::LocalKey<T>::try_with (22 samples, 0.02%)tokio::loom::std::unsafe_cell::UnsafeCell<T>::with_mut (112 samples, 0.09%)tokio::runtime::task::core::Core<T,S>::poll::{{closure}} (111 samples, 0.08%)tokio::runtime::task::harness::poll_future (125 samples, 0.10%)std::panic::catch_unwind (125 samples, 0.10%)std::panicking::try (125 samples, 0.10%)std::panicking::try::do_call (125 samples, 0.10%)<core::panic::unwind_safe::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once (125 samples, 0.10%)tokio::runtime::task::harness::poll_future::{{closure}} (125 samples, 0.10%)tokio::runtime::task::core::Core<T,S>::poll (125 samples, 0.10%)tokio::runtime::task::raw::poll (157 samples, 0.12%)tokio::runtime::task::harness::Harness<T,S>::poll (135 samples, 0.10%)tokio::runtime::task::harness::Harness<T,S>::poll_inner (135 samples, 0.10%)tokio::runtime::time::Driver::park_internal (15 samples, 0.01%)torrust_tracker::bootstrap::logging::INIT (17 samples, 0.01%)__memcpy_avx512_unaligned_erms (397 samples, 0.30%)_int_free (24 samples, 0.02%)_int_malloc (132 samples, 0.10%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE::META (570 samples, 0.43%)__GI___lll_lock_wait_private (22 samples, 0.02%)futex_wait (14 samples, 0.01%)__memcpy_avx512_unaligned_erms (299 samples, 0.23%)_int_free (16 samples, 0.01%)torrust_tracker::servers::udp::logging::log_request::__CALLSITE (361 samples, 0.27%)torrust_tracker::servers::udp::server::Udp::process_request::{{closure}} (41 samples, 0.03%)torrust_tracker::servers::udp::handlers::handle_packet::{{closure}} (23 samples, 0.02%)torrust_tracker::servers::udp::server::Udp::process_valid_request::{{closure}} (53 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::send_response::{{closure}} (14 samples, 0.01%)<tokio::runtime::io::scheduled_io::Readiness as core::future::future::Future>::poll (63 samples, 0.05%)<tokio::runtime::io::scheduled_io::Readiness as core::ops::drop::Drop>::drop (21 samples, 0.02%)__GI___libc_malloc (18 samples, 0.01%)alloc::vec::Vec<T>::with_capacity (116 samples, 0.09%)alloc::vec::Vec<T,A>::with_capacity_in (116 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::with_capacity_in (116 samples, 0.09%)alloc::raw_vec::RawVec<T,A>::try_allocate_in (116 samples, 0.09%)<alloc::alloc::Global as core::alloc::Allocator>::allocate (116 samples, 0.09%)alloc::alloc::Global::alloc_impl (116 samples, 0.09%)alloc::alloc::alloc (116 samples, 0.09%)__rdl_alloc (116 samples, 0.09%)std::sys::pal::unix::alloc::<impl core::alloc::global::GlobalAlloc for std::alloc::System>::alloc (116 samples, 0.09%)tokio::runtime::io::registration::Registration::readiness::{{closure}} (53 samples, 0.04%)tokio::runtime::io::scheduled_io::ScheduledIo::readiness::{{closure}} (53 samples, 0.04%)core::ptr::drop_in_place<tokio::runtime::io::scheduled_io::Readiness> (53 samples, 0.04%)_int_malloc (21 samples, 0.02%)[unknown] (36 samples, 0.03%)[unknown] (16 samples, 0.01%)core::mem::zeroed (27 samples, 0.02%)core::mem::maybe_uninit::MaybeUninit<T>::zeroed (27 samples, 0.02%)core::ptr::mut_ptr::<impl *mut T>::write_bytes (27 samples, 0.02%)core::intrinsics::write_bytes (27 samples, 0.02%)[unknown] (27 samples, 0.02%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}}::{{closure}} (64 samples, 0.05%)mio::net::udp::UdpSocket::recv_from (49 samples, 0.04%)mio::io_source::IoSource<T>::do_io (49 samples, 0.04%)mio::sys::unix::stateless_io_source::IoSourceState::do_io (49 samples, 0.04%)mio::net::udp::UdpSocket::recv_from::{{closure}} (49 samples, 0.04%)std::net::udp::UdpSocket::recv_from (49 samples, 0.04%)std::sys_common::net::UdpSocket::recv_from (49 samples, 0.04%)std::sys::pal::unix::net::Socket::recv_from (49 samples, 0.04%)std::sys::pal::unix::net::Socket::recv_from_with_flags (49 samples, 0.04%)torrust_tracker::servers::udp::server::Udp::receive_request::{{closure}} (271 samples, 0.21%)tokio::net::udp::UdpSocket::recv_buf_from::{{closure}} (143 samples, 0.11%)tokio::runtime::io::registration::Registration::async_io::{{closure}} (141 samples, 0.11%)tokio::runtime::io::registration::Registration::clear_readiness (15 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::clear_readiness (15 samples, 0.01%)tokio::runtime::io::scheduled_io::ScheduledIo::set_readiness (15 samples, 0.01%)torrust_tracker::servers::udp::server::Udp::run_with_graceful_shutdown::{{closure}}::{{closure}} (359 samples, 0.27%)torrust_tracker::servers::udp::server::Udp::run_udp_server::{{closure}} (346 samples, 0.26%)torrust_tracker::servers::udp::server::Udp::spawn_request_processor (39 samples, 0.03%)tokio::task::spawn::spawn (39 samples, 0.03%)tokio::task::spawn::spawn_inner (39 samples, 0.03%)tokio::runtime::context::current::with_current (39 samples, 0.03%)std::thread::local::LocalKey<T>::try_with (39 samples, 0.03%)tokio::runtime::context::current::with_current::{{closure}} (39 samples, 0.03%)core::option::Option<T>::map (39 samples, 0.03%)tokio::task::spawn::spawn_inner::{{closure}} (39 samples, 0.03%)tokio::runtime::scheduler::Handle::spawn (39 samples, 0.03%)tokio::runtime::scheduler::multi_thread::handle::Handle::spawn (39 samples, 0.03%)tokio::runtime::scheduler::multi_thread::handle::Handle::bind_new_task (39 samples, 0.03%)tokio::runtime::task::list::OwnedTasks<S>::bind (34 samples, 0.03%)all (131,301 samples, 100%)tokio-runtime-w (131,061 samples, 99.82%)tokio-runtime-w \ No newline at end of file diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index b383e95ad..a9bf97009 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -7,9 +7,7 @@ use std::collections::BTreeMap; use std::time::Duration; -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use info_hash::InfoHash; -use serde::Serialize; pub mod info_hash; pub mod pagination; @@ -20,48 +18,6 @@ pub mod torrent_metrics; /// Duration since the Unix Epoch. pub type DurationSinceUnixEpoch = Duration; -/// Serializes a `DurationSinceUnixEpoch` as a Unix timestamp in milliseconds. -/// # Errors -/// -/// Will return `serde::Serializer::Error` if unable to serialize the `unix_time_value`. -pub fn ser_unix_time_value(unix_time_value: &DurationSinceUnixEpoch, ser: S) -> Result { - #[allow(clippy::cast_possible_truncation)] - ser.serialize_u64(unix_time_value.as_millis() as u64) -} - -#[derive(Serialize)] -pub enum AnnounceEventSer { - Started, - Stopped, - Completed, - None, -} - -/// Serializes a `Announce Event` as a enum. -/// -/// # Errors -/// -/// If will return an error if the internal serializer was to fail. -pub fn ser_announce_event(announce_event: &AnnounceEvent, ser: S) -> Result { - let event_ser = match announce_event { - AnnounceEvent::Started => AnnounceEventSer::Started, - AnnounceEvent::Stopped => AnnounceEventSer::Stopped, - AnnounceEvent::Completed => AnnounceEventSer::Completed, - AnnounceEvent::None => AnnounceEventSer::None, - }; - - ser.serialize_some(&event_ser) -} - -/// Serializes a `Announce Event` as a i64. -/// -/// # Errors -/// -/// If will return an error if the internal serializer was to fail. -pub fn ser_number_of_bytes(number_of_bytes: &NumberOfBytes, ser: S) -> Result { - ser.serialize_i64(number_of_bytes.0.get()) -} - /// IP version used by the peer to connect to the tracker: IPv4 or IPv6 #[derive(PartialEq, Eq, Debug)] pub enum IPVersion { diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index 987099b70..9a02ef39b 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -3,6 +3,7 @@ //! A sample peer: //! //! ```rust,no_run +//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; //! use torrust_tracker_primitives::peer; //! use std::net::SocketAddr; //! use std::net::IpAddr; @@ -11,7 +12,7 @@ //! //! //! peer::Peer { -//! peer_id: peer::Id(*b"-qB00000000000000000"), +//! peer_id: PeerId(*b"-qB00000000000000000"), //! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), //! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), //! uploaded: NumberOfBytes::new(0), @@ -22,18 +23,21 @@ //! ``` use std::net::{IpAddr, SocketAddr}; +use std::ops::{Deref, DerefMut}; use std::sync::Arc; -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use serde::Serialize; +use zerocopy::FromBytes as _; -use crate::{ser_announce_event, ser_number_of_bytes, ser_unix_time_value, DurationSinceUnixEpoch, IPVersion}; +use crate::{DurationSinceUnixEpoch, IPVersion}; /// Peer struct used by the core `Tracker`. /// /// A sample peer: /// /// ```rust,no_run +/// use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; /// use torrust_tracker_primitives::peer; /// use std::net::SocketAddr; /// use std::net::IpAddr; @@ -42,7 +46,7 @@ use crate::{ser_announce_event, ser_number_of_bytes, ser_unix_time_value, Durati /// /// /// peer::Peer { -/// peer_id: peer::Id(*b"-qB00000000000000000"), +/// peer_id: PeerId(*b"-qB00000000000000000"), /// peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), /// updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), /// uploaded: NumberOfBytes::new(0), @@ -54,7 +58,8 @@ use crate::{ser_announce_event, ser_number_of_bytes, ser_unix_time_value, Durati #[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq, Hash)] pub struct Peer { /// ID used by the downloader peer - pub peer_id: Id, + #[serde(serialize_with = "ser_peer_id")] + pub peer_id: PeerId, /// The IP and port this peer is listening on pub peer_addr: SocketAddr, /// The last time the the tracker receive an announce request from this peer (timestamp) @@ -74,6 +79,58 @@ pub struct Peer { pub event: AnnounceEvent, } +/// Serializes a `DurationSinceUnixEpoch` as a Unix timestamp in milliseconds. +/// # Errors +/// +/// Will return `serde::Serializer::Error` if unable to serialize the `unix_time_value`. +pub fn ser_unix_time_value(unix_time_value: &DurationSinceUnixEpoch, ser: S) -> Result { + #[allow(clippy::cast_possible_truncation)] + ser.serialize_u64(unix_time_value.as_millis() as u64) +} + +#[derive(Serialize)] +pub enum AnnounceEventSer { + Started, + Stopped, + Completed, + None, +} + +/// Serializes a `Announce Event` as a enum. +/// +/// # Errors +/// +/// If will return an error if the internal serializer was to fail. +pub fn ser_announce_event(announce_event: &AnnounceEvent, ser: S) -> Result { + let event_ser = match announce_event { + AnnounceEvent::Started => AnnounceEventSer::Started, + AnnounceEvent::Stopped => AnnounceEventSer::Stopped, + AnnounceEvent::Completed => AnnounceEventSer::Completed, + AnnounceEvent::None => AnnounceEventSer::None, + }; + + ser.serialize_some(&event_ser) +} + +/// Serializes a `Announce Event` as a i64. +/// +/// # Errors +/// +/// If will return an error if the internal serializer was to fail. +pub fn ser_number_of_bytes(number_of_bytes: &NumberOfBytes, ser: S) -> Result { + ser.serialize_i64(number_of_bytes.0.get()) +} + +/// Serializes a `PeerId` as a `peer::Id`. +/// +/// # Errors +/// +/// If will return an error if the internal serializer was to fail. +pub fn ser_peer_id(peer_id: &PeerId, ser: S) -> Result { + let id = Id { data: *peer_id }; + ser.serialize_some(&id) +} + impl Ord for Peer { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.peer_id.cmp(&other.peer_id) @@ -89,7 +146,7 @@ impl PartialOrd for Peer { pub trait ReadInfo { fn is_seeder(&self) -> bool; fn get_event(&self) -> AnnounceEvent; - fn get_id(&self) -> Id; + fn get_id(&self) -> PeerId; fn get_updated(&self) -> DurationSinceUnixEpoch; fn get_address(&self) -> SocketAddr; } @@ -103,7 +160,7 @@ impl ReadInfo for Peer { self.event } - fn get_id(&self) -> Id { + fn get_id(&self) -> PeerId { self.peer_id } @@ -125,7 +182,7 @@ impl ReadInfo for Arc { self.event } - fn get_id(&self) -> Id { + fn get_id(&self) -> PeerId { self.peer_id } @@ -183,19 +240,46 @@ pub enum IdConversionError { }, } +pub struct Id { + data: PeerId, +} + +impl From for Id { + fn from(id: PeerId) -> Self { + Self { data: id } + } +} + +impl Deref for Id { + type Target = PeerId; + + fn deref(&self) -> &Self::Target { + &self.data + } +} + +impl DerefMut for Id { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.data + } +} + impl From<[u8; 20]> for Id { fn from(bytes: [u8; 20]) -> Self { - Id(bytes) + let data = PeerId(bytes); + Self { data } } } impl From for Id { fn from(number: i32) -> Self { - let peer_id = number.to_le_bytes(); - Id::from([ - 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, peer_id[0], peer_id[1], peer_id[2], - peer_id[3], - ]) + let number = number.to_le_bytes(); + let bytes = [ + 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, number[0], number[1], number[2], + number[3], + ]; + + Id::from(bytes) } } @@ -215,15 +299,9 @@ impl TryFrom> for Id { message: format! {"got {} bytes, expected {}", bytes.len(), PEER_ID_BYTES_LEN}, }); } - Ok(Self::from_bytes(&bytes)) - } -} - -impl std::str::FromStr for Id { - type Err = IdConversionError; - fn from_str(s: &str) -> Result { - Self::try_from(s.as_bytes().to_vec()) + let data = PeerId::read_from(&bytes).expect("it should have the correct amount of bytes"); + Ok(Self { data }) } } @@ -236,51 +314,13 @@ impl std::fmt::Display for Id { } } -/// Peer ID. A 20-byte array. -/// -/// A string of length 20 which this downloader uses as its id. -/// Each downloader generates its own id at random at the start of a new download. -/// -/// A sample peer ID: -/// -/// ```rust,no_run -/// use torrust_tracker_primitives::peer; -/// -/// let peer_id = peer::Id(*b"-qB00000000000000000"); -/// ``` -/// -#[derive(PartialEq, Eq, Hash, Clone, Debug, PartialOrd, Ord, Copy)] -pub struct Id(pub [u8; 20]); - pub const PEER_ID_BYTES_LEN: usize = 20; impl Id { - /// # Panics - /// - /// Will panic if byte slice does not contains the exact amount of bytes need for the `Id`. - #[must_use] - pub fn from_bytes(bytes: &[u8]) -> Self { - assert_eq!( - PEER_ID_BYTES_LEN, - bytes.len(), - "we are testing the equality of the constant: `PEER_ID_BYTES_LEN` ({}) and the supplied `bytes` length: {}", - PEER_ID_BYTES_LEN, - bytes.len(), - ); - let mut ret = Self([0u8; PEER_ID_BYTES_LEN]); - ret.0.clone_from_slice(bytes); - ret - } - - #[must_use] - pub fn to_bytes(&self) -> [u8; 20] { - self.0 - } - #[must_use] /// Converts to hex string. /// - /// For the Id `-qB00000000000000000` it returns `2d71423030303030303030303030303030303030` + /// For the `PeerId` `-qB00000000000000000` it returns `2d71423030303030303030303030303030303030` /// /// For example: /// @@ -362,7 +402,7 @@ pub mod fixture { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - use super::{Id, Peer}; + use super::{Id, Peer, PeerId}; use crate::DurationSinceUnixEpoch; #[derive(PartialEq, Debug)] @@ -383,7 +423,7 @@ pub mod fixture { #[must_use] pub fn seeder() -> Self { let peer = Peer { - peer_id: Id(*b"-qB00000000000000001"), + peer_id: PeerId(*b"-qB00000000000000001"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), @@ -399,7 +439,7 @@ pub mod fixture { #[must_use] pub fn leecher() -> Self { let peer = Peer { - peer_id: Id(*b"-qB00000000000000002"), + peer_id: PeerId(*b"-qB00000000000000002"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), @@ -413,7 +453,7 @@ pub mod fixture { #[allow(dead_code)] #[must_use] - pub fn with_peer_id(mut self, peer_id: &Id) -> Self { + pub fn with_peer_id(mut self, peer_id: &PeerId) -> Self { self.peer.peer_id = *peer_id; self } @@ -462,7 +502,7 @@ pub mod fixture { impl Default for Peer { fn default() -> Self { Self { - peer_id: Id::default(), + peer_id: PeerId(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), @@ -475,7 +515,8 @@ pub mod fixture { impl Default for Id { fn default() -> Self { - Self(*b"-qB00000000000000000") + let data = PeerId(*b"-qB00000000000000000"); + Self { data } } } } @@ -483,113 +524,50 @@ pub mod fixture { #[cfg(test)] pub mod test { mod torrent_peer_id { - use crate::peer; - - #[test] - fn should_be_instantiated_from_a_byte_slice() { - let id = peer::Id::from_bytes(&[ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); - - let expected_id = peer::Id([ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); - - assert_eq!(id, expected_id); - } - - #[test] - #[should_panic = "we are testing the equality of the constant: `PEER_ID_BYTES_LEN` (20) and the supplied `bytes` length: 19"] - fn should_fail_trying_to_instantiate_from_a_byte_slice_with_less_than_20_bytes() { - let less_than_20_bytes = [0; 19]; - let _: peer::Id = peer::Id::from_bytes(&less_than_20_bytes); - } + use aquatic_udp_protocol::PeerId; - #[test] - #[should_panic = "we are testing the equality of the constant: `PEER_ID_BYTES_LEN` (20) and the supplied `bytes` length: 21"] - fn should_fail_trying_to_instantiate_from_a_byte_slice_with_more_than_20_bytes() { - let more_than_20_bytes = [0; 21]; - let _: peer::Id = peer::Id::from_bytes(&more_than_20_bytes); - } - - #[test] - fn should_be_instantiated_from_a_string() { - let id = "-qB00000000000000001".parse::().unwrap(); - - let expected_id = peer::Id([ - 45, 113, 66, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 49, - ]); - - assert_eq!(id, expected_id); - } - - #[test] - fn should_be_converted_from_a_20_byte_array() { - let id = peer::Id::from([ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); - - let expected_id = peer::Id([ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); - - assert_eq!(id, expected_id); - } - - #[test] - fn should_be_converted_from_a_byte_vector() { - let id = peer::Id::try_from( - [ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ] - .to_vec(), - ) - .unwrap(); - - let expected_id = peer::Id([ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); - - assert_eq!(id, expected_id); - } + use crate::peer; #[test] #[should_panic = "NotEnoughBytes"] fn should_fail_trying_to_convert_from_a_byte_vector_with_less_than_20_bytes() { - let _: peer::Id = peer::Id::try_from([0; 19].to_vec()).unwrap(); + let _ = peer::Id::try_from([0; 19].to_vec()).unwrap(); } #[test] #[should_panic = "TooManyBytes"] fn should_fail_trying_to_convert_from_a_byte_vector_with_more_than_20_bytes() { - let _: peer::Id = peer::Id::try_from([0; 21].to_vec()).unwrap(); + let _ = peer::Id::try_from([0; 21].to_vec()).unwrap(); } #[test] fn should_be_converted_to_hex_string() { - let id = peer::Id(*b"-qB00000000000000000"); + let id = peer::Id { + data: PeerId(*b"-qB00000000000000000"), + }; assert_eq!(id.to_hex_string().unwrap(), "0x2d71423030303030303030303030303030303030"); - let id = peer::Id([ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); + let id = peer::Id { + data: PeerId([ + 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, + ]), + }; assert_eq!(id.to_hex_string().unwrap(), "0x009f9296009f9296009f9296009f9296009f9296"); } #[test] fn should_be_converted_into_string_type_using_the_hex_string_format() { - let id = peer::Id(*b"-qB00000000000000000"); + let id = peer::Id { + data: PeerId(*b"-qB00000000000000000"), + }; assert_eq!(id.to_string(), "0x2d71423030303030303030303030303030303030"); - let id = peer::Id([ - 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, - ]); + let id = peer::Id { + data: PeerId([ + 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, 0, 159, 146, 150, + ]), + }; assert_eq!(id.to_string(), "0x009f9296009f9296009f9296009f9296009f9296"); } - - #[test] - fn should_return_the_inner_bytes() { - assert_eq!(peer::Id(*b"-qB00000000000000000").to_bytes(), *b"-qB00000000000000000"); - } } } diff --git a/packages/torrent-repository/benches/helpers/utils.rs b/packages/torrent-repository/benches/helpers/utils.rs index f7a392bd8..e21ac7332 100644 --- a/packages/torrent-repository/benches/helpers/utils.rs +++ b/packages/torrent-repository/benches/helpers/utils.rs @@ -1,14 +1,14 @@ use std::collections::HashSet; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use torrust_tracker_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::peer::{Id, Peer}; +use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; use zerocopy::I64; pub const DEFAULT_PEER: Peer = Peer { - peer_id: Id([0; 20]), + peer_id: PeerId([0; 20]), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::from_secs(0), uploaded: NumberOfBytes(I64::ZERO), diff --git a/packages/torrent-repository/src/entry/peer_list.rs b/packages/torrent-repository/src/entry/peer_list.rs index 3f69edbb5..33270cf27 100644 --- a/packages/torrent-repository/src/entry/peer_list.rs +++ b/packages/torrent-repository/src/entry/peer_list.rs @@ -2,6 +2,7 @@ use std::net::SocketAddr; use std::sync::Arc; +use aquatic_udp_protocol::PeerId; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; // code-review: the current implementation uses the peer Id as the ``BTreeMap`` @@ -11,7 +12,7 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct PeerList { - peers: std::collections::BTreeMap>, + peers: std::collections::BTreeMap>, } impl PeerList { @@ -29,7 +30,7 @@ impl PeerList { self.peers.insert(value.peer_id, value) } - pub fn remove(&mut self, key: &peer::Id) -> Option> { + pub fn remove(&mut self, key: &PeerId) -> Option> { self.peers.remove(key) } @@ -39,7 +40,7 @@ impl PeerList { } #[must_use] - pub fn get(&self, peer_id: &peer::Id) -> Option<&Arc> { + pub fn get(&self, peer_id: &PeerId) -> Option<&Arc> { self.peers.get(peer_id) } @@ -89,8 +90,8 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; + use aquatic_udp_protocol::PeerId; use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use torrust_tracker_primitives::peer::{self}; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::entry::peer_list::PeerList; @@ -193,13 +194,13 @@ mod tests { let mut peer_list = PeerList::default(); let peer1 = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); peer_list.upsert(peer1.into()); let peer2 = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000002")) + .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) .build(); peer_list.upsert(peer2.into()); @@ -273,14 +274,10 @@ mod tests { fn allow_inserting_two_identical_peers_except_for_the_id() { let mut peer_list = PeerList::default(); - let peer1 = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .build(); + let peer1 = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); peer_list.upsert(peer1.into()); - let peer2 = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000002")) - .build(); + let peer2 = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000002")).build(); peer_list.upsert(peer2.into()); assert_eq!(peer_list.len(), 2); diff --git a/packages/torrent-repository/tests/common/torrent_peer_builder.rs b/packages/torrent-repository/tests/common/torrent_peer_builder.rs index a5d2814c1..e9b869395 100644 --- a/packages/torrent-repository/tests/common/torrent_peer_builder.rs +++ b/packages/torrent-repository/tests/common/torrent_peer_builder.rs @@ -1,6 +1,6 @@ use std::net::SocketAddr; -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; @@ -42,7 +42,7 @@ impl TorrentPeerBuilder { } #[must_use] - fn with_peer_id(mut self, peer_id: peer::Id) -> Self { + fn with_peer_id(mut self, peer_id: PeerId) -> Self { self.peer.peer_id = peer_id; self } @@ -69,10 +69,11 @@ impl TorrentPeerBuilder { /// has not announced it has stopped #[must_use] pub fn a_completed_peer(id: i32) -> peer::Peer { + let peer_id = peer::Id::from(id); TorrentPeerBuilder::new() .with_number_of_bytes_left(0) .with_event_completed() - .with_peer_id(id.into()) + .with_peer_id(*peer_id) .into() } @@ -80,9 +81,10 @@ pub fn a_completed_peer(id: i32) -> peer::Peer { /// Leecher: left > 0 OR event = Stopped #[must_use] pub fn a_started_peer(id: i32) -> peer::Peer { + let peer_id = peer::Id::from(id); TorrentPeerBuilder::new() .with_number_of_bytes_left(1) .with_event_started() - .with_peer_id(id.into()) + .with_peer_id(*peer_id) .into() } diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index 223819a14..31bec313d 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -400,7 +400,7 @@ async fn it_should_limit_the_number_of_peers_returned( // We add one more peer than the scrape limit for peer_number in 1..=74 + 1 { let mut peer = a_started_peer(1); - peer.peer_id = peer::Id::from(peer_number); + peer.peer_id = *peer::Id::from(peer_number); torrent.upsert_peer(&peer).await; } diff --git a/src/core/mod.rs b/src/core/mod.rs index 7c10c0aae..a7ad66052 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -60,15 +60,15 @@ //! use std::net::Ipv4Addr; //! use std::str::FromStr; //! -//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; //! use torrust_tracker_primitives::peer; //! use torrust_tracker_primitives::info_hash::InfoHash; -//! use torrust_tracker_primitives::{DurationSinceUnixEpoch}; //! //! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); //! //! let peer = peer::Peer { -//! peer_id: peer::Id(*b"-qB00000000000000001"), +//! peer_id: PeerId(*b"-qB00000000000000001"), //! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), //! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), //! uploaded: NumberOfBytes::new(0), @@ -246,14 +246,15 @@ //! A `Peer` is the struct used by the `Tracker` to keep peers data: //! //! ```rust,no_run -//! use torrust_tracker_primitives::peer; //! use std::net::SocketAddr; + +//! use aquatic_udp_protocol::PeerId; //! use torrust_tracker_primitives::DurationSinceUnixEpoch; //! use aquatic_udp_protocol::NumberOfBytes; //! use aquatic_udp_protocol::AnnounceEvent; //! //! pub struct Peer { -//! pub peer_id: peer::Id, // The peer ID +//! pub peer_id: PeerId, // The peer ID //! pub peer_addr: SocketAddr, // Peer socket address //! pub updated: DurationSinceUnixEpoch, // Last time (timestamp) when the peer was updated //! pub uploaded: NumberOfBytes, // Number of bytes the peer has uploaded so far @@ -1198,12 +1199,12 @@ mod tests { use std::str::FromStr; use std::sync::Arc; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; - use crate::core::peer::{self, Peer}; + use crate::core::peer::Peer; use crate::core::services::tracker_factory; use crate::core::{TorrentsMetrics, Tracker}; use crate::shared::bit_torrent::info_hash::fixture::gen_seeded_infohash; @@ -1243,7 +1244,7 @@ mod tests { /// Sample peer when for tests that need more than one peer fn sample_peer_1() -> Peer { Peer { - peer_id: peer::Id(*b"-qB00000000000000001"), + peer_id: PeerId(*b"-qB00000000000000001"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), @@ -1256,7 +1257,7 @@ mod tests { /// Sample peer when for tests that need more than one peer fn sample_peer_2() -> Peer { Peer { - peer_id: peer::Id(*b"-qB00000000000000002"), + peer_id: PeerId(*b"-qB00000000000000002"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8082), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), @@ -1287,7 +1288,7 @@ mod tests { /// announcing the `AnnounceEvent::Completed` event. fn complete_peer() -> Peer { Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), + peer_id: PeerId(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), @@ -1300,7 +1301,7 @@ mod tests { /// A peer that counts as `incomplete` is swarm metadata fn incomplete_peer() -> Peer { Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), + peer_id: PeerId(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), diff --git a/src/core/peer_tests.rs b/src/core/peer_tests.rs index f0773faf0..b60ca3f6d 100644 --- a/src/core/peer_tests.rs +++ b/src/core/peer_tests.rs @@ -2,7 +2,7 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use torrust_tracker_clock::clock::stopped::Stopped as _; use torrust_tracker_clock::clock::{self, Time}; use torrust_tracker_primitives::peer; @@ -14,7 +14,7 @@ fn it_should_be_serializable() { clock::Stopped::local_set_to_unix_epoch(); let torrent_peer = peer::Peer { - peer_id: peer::Id(*b"-qB0000-000000000000"), + peer_id: PeerId(*b"-qB0000-000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: CurrentClock::now(), uploaded: NumberOfBytes::new(0), diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 9cb38e3f1..3b014982d 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -105,12 +105,12 @@ pub async fn get_torrents(tracker: Arc, info_hashes: &[InfoHash]) -> Ve mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; fn sample_peer() -> peer::Peer { peer::Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), + peer_id: PeerId(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), diff --git a/src/servers/apis/v1/context/torrent/resources/peer.rs b/src/servers/apis/v1/context/torrent/resources/peer.rs index 129318ce1..dd4a6cc26 100644 --- a/src/servers/apis/v1/context/torrent/resources/peer.rs +++ b/src/servers/apis/v1/context/torrent/resources/peer.rs @@ -1,4 +1,5 @@ //! `Peer` and Peer `Id` API resources. +use aquatic_udp_protocol::PeerId; use derive_more::From; use serde::{Deserialize, Serialize}; use torrust_tracker_primitives::peer; @@ -35,8 +36,9 @@ pub struct Id { pub client: Option, } -impl From for Id { - fn from(peer_id: peer::Id) -> Self { +impl From for Id { + fn from(peer_id: PeerId) -> Self { + let peer_id = peer::Id::from(peer_id); Id { id: peer_id.to_hex_string(), client: peer_id.get_client_name(), diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs index 772a37f98..657382c0c 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs @@ -97,7 +97,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; @@ -108,7 +108,7 @@ mod tests { fn sample_peer() -> peer::Peer { peer::Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), + peer_id: PeerId(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), diff --git a/src/servers/http/percent_encoding.rs b/src/servers/http/percent_encoding.rs index 90f4b9a43..c3243d597 100644 --- a/src/servers/http/percent_encoding.rs +++ b/src/servers/http/percent_encoding.rs @@ -15,6 +15,7 @@ //! - //! - //! - +use aquatic_udp_protocol::PeerId; use torrust_tracker_primitives::info_hash::{self, InfoHash}; use torrust_tracker_primitives::peer; @@ -49,7 +50,7 @@ pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result Result Result { +/// Will return `Err` if if the decoded bytes do not represent a valid [`PeerId`]. +pub fn percent_decode_peer_id(raw_peer_id: &str) -> Result { let bytes = percent_encoding::percent_decode_str(raw_peer_id).collect::>(); - peer::Id::try_from(bytes) + Ok(*peer::Id::try_from(bytes)?) } #[cfg(test)] mod tests { use std::str::FromStr; + use aquatic_udp_protocol::PeerId; use torrust_tracker_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::peer; use crate::servers::http::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; @@ -112,7 +114,7 @@ mod tests { let peer_id = percent_decode_peer_id(encoded_peer_id).unwrap(); - assert_eq!(peer_id, peer::Id(*b"-qB00000000000000000")); + assert_eq!(peer_id, PeerId(*b"-qB00000000000000000")); } #[test] diff --git a/src/servers/http/v1/extractors/announce_request.rs b/src/servers/http/v1/extractors/announce_request.rs index 6867461e0..b1d820598 100644 --- a/src/servers/http/v1/extractors/announce_request.rs +++ b/src/servers/http/v1/extractors/announce_request.rs @@ -95,9 +95,8 @@ fn extract_announce_from(maybe_raw_query: Option<&str>) -> Result) -> AnnounceEvent { #[cfg(test)] mod tests { + use aquatic_udp_protocol::PeerId; use torrust_tracker_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::peer; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; @@ -199,7 +199,7 @@ mod tests { fn sample_announce_request() -> Announce { Announce { info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), - peer_id: "-qB00000000000000001".parse::().unwrap(), + peer_id: PeerId(*b"-qB00000000000000001"), port: 17548, downloaded: None, uploaded: None, diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index 6efee18b3..3253a07c8 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -5,7 +5,7 @@ use std::fmt; use std::panic::Location; use std::str::FromStr; -use aquatic_udp_protocol::NumberOfBytes; +use aquatic_udp_protocol::{NumberOfBytes, PeerId}; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; use torrust_tracker_primitives::info_hash::{self, InfoHash}; @@ -29,20 +29,19 @@ const COMPACT: &str = "compact"; /// query params of the request. /// /// ```rust -/// use aquatic_udp_protocol::NumberOfBytes; +/// use aquatic_udp_protocol::{NumberOfBytes, PeerId}; /// use torrust_tracker::servers::http::v1::requests::announce::{Announce, Compact, Event}; /// use torrust_tracker_primitives::info_hash::InfoHash; -/// use torrust_tracker_primitives::peer; /// /// let request = Announce { /// // Mandatory params /// info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), -/// peer_id: "-qB00000000000000001".parse::().unwrap(), +/// peer_id: PeerId(*b"-qB00000000000000001"), /// port: 17548, /// // Optional params /// downloaded: Some(NumberOfBytes::new(1)), -/// uploaded: Some(NumberOfBytes::new(2)), -/// left: Some(NumberOfBytes::new(3)), +/// uploaded: Some(NumberOfBytes::new(1)), +/// left: Some(NumberOfBytes::new(1)), /// event: Some(Event::Started), /// compact: Some(Compact::NotAccepted) /// }; @@ -60,8 +59,8 @@ pub struct Announce { // Mandatory params /// The `InfoHash` of the torrent. pub info_hash: InfoHash, - /// The `peer::Id` of the peer. - pub peer_id: peer::Id, + /// The `PeerId` of the peer. + pub peer_id: PeerId, /// The port of the peer. pub port: u16, @@ -269,7 +268,7 @@ fn extract_info_hash(query: &Query) -> Result } } -fn extract_peer_id(query: &Query) -> Result { +fn extract_peer_id(query: &Query) -> Result { match query.get_param(PEER_ID) { Some(raw_param) => Ok( percent_decode_peer_id(&raw_param).map_err(|err| ParseAnnounceQueryError::InvalidPeerIdParam { @@ -356,9 +355,8 @@ mod tests { mod announce_request { - use aquatic_udp_protocol::NumberOfBytes; + use aquatic_udp_protocol::{NumberOfBytes, PeerId}; use torrust_tracker_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::peer; use crate::servers::http::v1::query::Query; use crate::servers::http::v1::requests::announce::{ @@ -382,7 +380,7 @@ mod tests { announce_request, Announce { info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), - peer_id: "-qB00000000000000001".parse::().unwrap(), + peer_id: PeerId(*b"-qB00000000000000001"), port: 17548, downloaded: None, uploaded: None, @@ -415,7 +413,7 @@ mod tests { announce_request, Announce { info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), - peer_id: "-qB00000000000000001".parse::().unwrap(), + peer_id: PeerId(*b"-qB00000000000000001"), port: 17548, downloaded: Some(NumberOfBytes::new(1)), uploaded: Some(NumberOfBytes::new(2)), diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index 134da919e..f223a4bb0 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -178,7 +178,7 @@ impl peer::Encoding for NormalPeer {} impl From for NormalPeer { fn from(peer: peer::Peer) -> Self { NormalPeer { - peer_id: peer.peer_id.to_bytes(), + peer_id: peer.peer_id.0, ip: peer.peer_addr.ip(), port: peer.peer_addr.port(), } @@ -300,8 +300,8 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; + use aquatic_udp_protocol::PeerId; use torrust_tracker_configuration::AnnouncePolicy; - use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; @@ -324,12 +324,12 @@ mod tests { let policy = AnnouncePolicy::new(111, 222); let peer_ipv4 = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), 0x7070)) .build(); let peer_ipv6 = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000002")) + .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), 0x7070, diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index a85a4d4bf..6b7f8af5a 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -48,7 +48,7 @@ pub async fn invoke(tracker: Arc, info_hash: InfoHash, peer: &mut peer: mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; @@ -79,7 +79,7 @@ mod tests { fn sample_peer() -> peer::Peer { peer::Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), + peer_id: PeerId(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index bd3f323b4..42fe4b518 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -61,7 +61,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; @@ -83,7 +83,7 @@ mod tests { fn sample_peer() -> peer::Peer { peer::Peer { - peer_id: peer::Id(*b"-qB00000000000000000"), + peer_id: PeerId(*b"-qB00000000000000000"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index c7204b4b9..1ef404ff0 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -318,7 +318,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; - use aquatic_udp_protocol::NumberOfBytes; + use aquatic_udp_protocol::{NumberOfBytes, PeerId}; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::peer; @@ -391,7 +391,7 @@ mod tests { } #[must_use] - pub fn with_peer_id(mut self, peer_id: peer::Id) -> Self { + pub fn with_peer_id(mut self, peer_id: PeerId) -> Self { self.peer.peer_id = peer_id; self } @@ -621,7 +621,6 @@ mod tests { PeerId as AquaticPeerId, Response, ResponsePeer, }; use mockall::predicate::eq; - use torrust_tracker_primitives::peer; use crate::core::{self, statistics}; use crate::servers::udp::connection_cookie::{into_connection_id, make}; @@ -655,7 +654,7 @@ mod tests { let peers = tracker.get_torrent_peers(&info_hash.0.into()); let expected_peer = TorrentPeerBuilder::new() - .with_peer_id(peer::Id(peer_id.0)) + .with_peer_id(peer_id) .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip), client_port)) .into(); @@ -729,7 +728,7 @@ mod tests { let peer_id = AquaticPeerId([255u8; 20]); let peer_using_ipv6 = TorrentPeerBuilder::new() - .with_peer_id(peer::Id(peer_id.0)) + .with_peer_id(peer_id) .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); @@ -795,7 +794,6 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; - use torrust_tracker_primitives::peer; use crate::servers::udp::connection_cookie::{into_connection_id, make}; use crate::servers::udp::handlers::handle_announce; @@ -828,7 +826,7 @@ mod tests { let external_ip_in_tracker_configuration = tracker.get_maybe_external_ip().unwrap(); let expected_peer = TorrentPeerBuilder::new() - .with_peer_id(peer::Id(peer_id.0)) + .with_peer_id(peer_id) .with_peer_address(SocketAddr::new(external_ip_in_tracker_configuration, client_port)) .into(); @@ -848,7 +846,6 @@ mod tests { PeerId as AquaticPeerId, Response, ResponsePeer, }; use mockall::predicate::eq; - use torrust_tracker_primitives::peer; use crate::core::{self, statistics}; use crate::servers::udp::connection_cookie::{into_connection_id, make}; @@ -883,7 +880,7 @@ mod tests { let peers = tracker.get_torrent_peers(&info_hash.0.into()); let expected_peer = TorrentPeerBuilder::new() - .with_peer_id(peer::Id(peer_id.0)) + .with_peer_id(peer_id) .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); @@ -960,7 +957,7 @@ mod tests { let peer_id = AquaticPeerId([255u8; 20]); let peer_using_ipv4 = TorrentPeerBuilder::new() - .with_peer_id(peer::Id(peer_id.0)) + .with_peer_id(peer_id) .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) .into(); @@ -1088,10 +1085,9 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{ - InfoHash, NumberOfDownloads, NumberOfPeers, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, + InfoHash, NumberOfDownloads, NumberOfPeers, PeerId, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; - use torrust_tracker_primitives::peer; use super::TorrentPeerBuilder; use crate::core::{self}; @@ -1134,10 +1130,10 @@ mod tests { } async fn add_a_seeder(tracker: Arc, remote_addr: &SocketAddr, info_hash: &InfoHash) { - let peer_id = peer::Id([255u8; 20]); + let peer_id = PeerId([255u8; 20]); let peer = TorrentPeerBuilder::new() - .with_peer_id(peer::Id(peer_id.0)) + .with_peer_id(peer_id) .with_peer_address(*remote_addr) .with_number_of_bytes_left(0) .into(); diff --git a/src/servers/udp/peer_builder.rs b/src/servers/udp/peer_builder.rs index 1824b2826..a42ddfaa5 100644 --- a/src/servers/udp/peer_builder.rs +++ b/src/servers/udp/peer_builder.rs @@ -15,7 +15,7 @@ use crate::CurrentClock; #[must_use] pub fn from_request(announce_request: &aquatic_udp_protocol::AnnounceRequest, peer_ip: &IpAddr) -> peer::Peer { peer::Peer { - peer_id: peer::Id(announce_request.peer_id.0), + peer_id: announce_request.peer_id, peer_addr: SocketAddr::new(*peer_ip, announce_request.port.0.into()), updated: CurrentClock::now(), uploaded: announce_request.bytes_uploaded, diff --git a/src/shared/bit_torrent/tracker/http/client/requests/announce.rs b/src/shared/bit_torrent/tracker/http/client/requests/announce.rs index b872e76e9..3c6b14222 100644 --- a/src/shared/bit_torrent/tracker/http/client/requests/announce.rs +++ b/src/shared/bit_torrent/tracker/http/client/requests/announce.rs @@ -2,9 +2,9 @@ use std::fmt; use std::net::{IpAddr, Ipv4Addr}; use std::str::FromStr; +use aquatic_udp_protocol::PeerId; use serde_repr::Serialize_repr; use torrust_tracker_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::peer; use crate::shared::bit_torrent::tracker::http::{percent_encode_byte_array, ByteArray20}; @@ -99,7 +99,7 @@ impl QueryBuilder { peer_addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 88)), downloaded: 0, uploaded: 0, - peer_id: peer::Id(*b"-qB00000000000000001").0, + peer_id: PeerId(*b"-qB00000000000000001").0, port: 17548, left: 0, event: Some(Event::Completed), @@ -117,7 +117,7 @@ impl QueryBuilder { } #[must_use] - pub fn with_peer_id(mut self, peer_id: &peer::Id) -> Self { + pub fn with_peer_id(mut self, peer_id: &PeerId) -> Self { self.announce_query.peer_id = peer_id.0; self } diff --git a/src/shared/bit_torrent/tracker/http/client/responses/announce.rs b/src/shared/bit_torrent/tracker/http/client/responses/announce.rs index 15ec446cb..7f2d3611c 100644 --- a/src/shared/bit_torrent/tracker/http/client/responses/announce.rs +++ b/src/shared/bit_torrent/tracker/http/client/responses/announce.rs @@ -2,6 +2,7 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use serde::{Deserialize, Serialize}; use torrust_tracker_primitives::peer; +use zerocopy::AsBytes as _; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Announce { @@ -25,7 +26,7 @@ pub struct DictionaryPeer { impl From for DictionaryPeer { fn from(peer: peer::Peer) -> Self { DictionaryPeer { - peer_id: peer.peer_id.to_bytes().to_vec(), + peer_id: peer.peer_id.as_bytes().to_vec(), ip: peer.peer_addr.ip().to_string(), port: peer.peer_addr.port(), } diff --git a/tests/servers/http/requests/announce.rs b/tests/servers/http/requests/announce.rs index 061990621..bcbb36852 100644 --- a/tests/servers/http/requests/announce.rs +++ b/tests/servers/http/requests/announce.rs @@ -2,9 +2,9 @@ use std::fmt; use std::net::{IpAddr, Ipv4Addr}; use std::str::FromStr; +use aquatic_udp_protocol::PeerId; use serde_repr::Serialize_repr; use torrust_tracker_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::peer; use crate::servers::http::{percent_encode_byte_array, ByteArray20}; @@ -93,7 +93,7 @@ impl QueryBuilder { peer_addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 88)), downloaded: 0, uploaded: 0, - peer_id: peer::Id(*b"-qB00000000000000001").0, + peer_id: PeerId(*b"-qB00000000000000001").0, port: 17548, left: 0, event: Some(Event::Completed), @@ -109,7 +109,7 @@ impl QueryBuilder { self } - pub fn with_peer_id(mut self, peer_id: &peer::Id) -> Self { + pub fn with_peer_id(mut self, peer_id: &PeerId) -> Self { self.announce_query.peer_id = peer_id.0; self } diff --git a/tests/servers/http/responses/announce.rs b/tests/servers/http/responses/announce.rs index 2b49b4405..554e5ab40 100644 --- a/tests/servers/http/responses/announce.rs +++ b/tests/servers/http/responses/announce.rs @@ -2,6 +2,7 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use serde::{Deserialize, Serialize}; use torrust_tracker_primitives::peer; +use zerocopy::AsBytes as _; #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Announce { @@ -25,7 +26,7 @@ pub struct DictionaryPeer { impl From for DictionaryPeer { fn from(peer: peer::Peer) -> Self { DictionaryPeer { - peer_id: peer.peer_id.to_bytes().to_vec(), + peer_id: peer.peer_id.as_bytes().to_vec(), ip: peer.peer_addr.ip().to_string(), port: peer.peer_addr.port(), } diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 14c237984..edc06fb07 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -86,11 +86,11 @@ mod for_all_config_modes { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV6}; use std::str::FromStr; + use aquatic_udp_protocol::PeerId; use local_ip_address::local_ip; use reqwest::{Response, StatusCode}; use tokio::net::TcpListener; use torrust_tracker_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; @@ -410,9 +410,7 @@ mod for_all_config_modes { let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // Peer 1 - let previously_announced_peer = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .build(); + let previously_announced_peer = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); // Add the Peer 1 env.add_torrent_peer(&info_hash, &previously_announced_peer); @@ -422,7 +420,7 @@ mod for_all_config_modes { .announce( &QueryBuilder::default() .with_info_hash(&info_hash) - .with_peer_id(&peer::Id(*b"-qB00000000000000002")) + .with_peer_id(&PeerId(*b"-qB00000000000000002")) .query(), ) .await; @@ -453,14 +451,14 @@ mod for_all_config_modes { // Announce a peer using IPV4 let peer_using_ipv4 = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), 8080)) .build(); env.add_torrent_peer(&info_hash, &peer_using_ipv4); // Announce a peer using IPV6 let peer_using_ipv6 = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000002")) + .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), 8080, @@ -473,7 +471,7 @@ mod for_all_config_modes { .announce( &QueryBuilder::default() .with_info_hash(&info_hash) - .with_peer_id(&peer::Id(*b"-qB00000000000000003")) + .with_peer_id(&PeerId(*b"-qB00000000000000003")) .query(), ) .await; @@ -531,9 +529,7 @@ mod for_all_config_modes { let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // Peer 1 - let previously_announced_peer = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .build(); + let previously_announced_peer = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); // Add the Peer 1 env.add_torrent_peer(&info_hash, &previously_announced_peer); @@ -543,7 +539,7 @@ mod for_all_config_modes { .announce( &QueryBuilder::default() .with_info_hash(&info_hash) - .with_peer_id(&peer::Id(*b"-qB00000000000000002")) + .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_compact(Compact::Accepted) .query(), ) @@ -572,9 +568,7 @@ mod for_all_config_modes { let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // Peer 1 - let previously_announced_peer = PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) - .build(); + let previously_announced_peer = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); // Add the Peer 1 env.add_torrent_peer(&info_hash, &previously_announced_peer); @@ -586,7 +580,7 @@ mod for_all_config_modes { .announce( &QueryBuilder::default() .with_info_hash(&info_hash) - .with_peer_id(&peer::Id(*b"-qB00000000000000002")) + .with_peer_id(&PeerId(*b"-qB00000000000000002")) .without_compact() .query(), ) @@ -886,9 +880,9 @@ mod for_all_config_modes { use std::net::{IpAddr, Ipv6Addr, SocketAddrV6}; use std::str::FromStr; + use aquatic_udp_protocol::PeerId; use tokio::net::TcpListener; use torrust_tracker_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; @@ -939,7 +933,7 @@ mod for_all_config_modes { env.add_torrent_peer( &info_hash, &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), ); @@ -977,7 +971,7 @@ mod for_all_config_modes { env.add_torrent_peer( &info_hash, &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_no_bytes_pending_to_download() .build(), ); @@ -1158,8 +1152,8 @@ mod configured_as_whitelisted { mod receiving_an_scrape_request { use std::str::FromStr; + use aquatic_udp_protocol::PeerId; use torrust_tracker_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; @@ -1177,7 +1171,7 @@ mod configured_as_whitelisted { env.add_torrent_peer( &info_hash, &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), ); @@ -1206,7 +1200,7 @@ mod configured_as_whitelisted { env.add_torrent_peer( &info_hash, &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), ); @@ -1324,9 +1318,9 @@ mod configured_as_private { use std::str::FromStr; use std::time::Duration; + use aquatic_udp_protocol::PeerId; use torrust_tracker::core::auth::Key; use torrust_tracker_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; @@ -1359,7 +1353,7 @@ mod configured_as_private { env.add_torrent_peer( &info_hash, &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), ); @@ -1388,7 +1382,7 @@ mod configured_as_private { env.add_torrent_peer( &info_hash, &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), ); @@ -1431,7 +1425,7 @@ mod configured_as_private { env.add_torrent_peer( &info_hash, &PeerBuilder::default() - .with_peer_id(&peer::Id(*b"-qB00000000000000001")) + .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), ); From bef5680a02d43aacf11684ab3b3245e6cace7fb6 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 15 Jul 2024 10:59:33 +0200 Subject: [PATCH 0477/1297] dev: vairous fixups --- packages/primitives/src/info_hash.rs | 2 +- packages/primitives/src/lib.rs | 9 ----- packages/primitives/src/peer.rs | 34 +++++++------------ .../tests/common/torrent_peer_builder.rs | 4 +-- .../torrent-repository/tests/entry/mod.rs | 2 +- 5 files changed, 16 insertions(+), 35 deletions(-) diff --git a/packages/primitives/src/info_hash.rs b/packages/primitives/src/info_hash.rs index 57dfd90e5..61b40a746 100644 --- a/packages/primitives/src/info_hash.rs +++ b/packages/primitives/src/info_hash.rs @@ -73,7 +73,7 @@ impl Ord for InfoHash { } } -impl std::cmp::PartialOrd for InfoHash { +impl PartialOrd for InfoHash { fn partial_cmp(&self, other: &InfoHash) -> Option { Some(self.cmp(other)) } diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index a9bf97009..08fc58976 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -18,13 +18,4 @@ pub mod torrent_metrics; /// Duration since the Unix Epoch. pub type DurationSinceUnixEpoch = Duration; -/// IP version used by the peer to connect to the tracker: IPv4 or IPv6 -#[derive(PartialEq, Eq, Debug)] -pub enum IPVersion { - /// - IPv4, - /// - IPv6, -} - pub type PersistentTorrents = BTreeMap; diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index 9a02ef39b..c8ff1791d 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -30,7 +30,7 @@ use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use serde::Serialize; use zerocopy::FromBytes as _; -use crate::{DurationSinceUnixEpoch, IPVersion}; +use crate::DurationSinceUnixEpoch; /// Peer struct used by the core `Tracker`. /// @@ -208,15 +208,6 @@ impl Peer { pub fn change_ip(&mut self, new_ip: &IpAddr) { self.peer_addr = SocketAddr::new(*new_ip, self.peer_addr.port()); } - - /// The IP version used by the peer: IPV4 or IPV6 - #[must_use] - pub fn ip_version(&self) -> IPVersion { - if self.peer_addr.is_ipv4() { - return IPVersion::IPv4; - } - IPVersion::IPv6 - } } use std::panic::Location; @@ -264,22 +255,21 @@ impl DerefMut for Id { } } -impl From<[u8; 20]> for Id { - fn from(bytes: [u8; 20]) -> Self { - let data = PeerId(bytes); - Self { data } - } -} - -impl From for Id { - fn from(number: i32) -> Self { +impl Id { + #[must_use] + pub fn new(number: T) -> Self + where + T: Into, + { + let number: i128 = number.into(); let number = number.to_le_bytes(); let bytes = [ - 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, number[0], number[1], number[2], - number[3], + 0u8, 0u8, 0u8, 0u8, number[0], number[1], number[2], number[3], number[4], number[5], number[6], number[7], + number[8], number[9], number[10], number[11], number[12], number[13], number[14], number[15], ]; - Id::from(bytes) + let data = PeerId(bytes); + Id { data } } } diff --git a/packages/torrent-repository/tests/common/torrent_peer_builder.rs b/packages/torrent-repository/tests/common/torrent_peer_builder.rs index e9b869395..33120180d 100644 --- a/packages/torrent-repository/tests/common/torrent_peer_builder.rs +++ b/packages/torrent-repository/tests/common/torrent_peer_builder.rs @@ -69,7 +69,7 @@ impl TorrentPeerBuilder { /// has not announced it has stopped #[must_use] pub fn a_completed_peer(id: i32) -> peer::Peer { - let peer_id = peer::Id::from(id); + let peer_id = peer::Id::new(id); TorrentPeerBuilder::new() .with_number_of_bytes_left(0) .with_event_completed() @@ -81,7 +81,7 @@ pub fn a_completed_peer(id: i32) -> peer::Peer { /// Leecher: left > 0 OR event = Stopped #[must_use] pub fn a_started_peer(id: i32) -> peer::Peer { - let peer_id = peer::Id::from(id); + let peer_id = peer::Id::new(id); TorrentPeerBuilder::new() .with_number_of_bytes_left(1) .with_event_started() diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index 31bec313d..43d7f94da 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -400,7 +400,7 @@ async fn it_should_limit_the_number_of_peers_returned( // We add one more peer than the scrape limit for peer_number in 1..=74 + 1 { let mut peer = a_started_peer(1); - peer.peer_id = *peer::Id::from(peer_number); + peer.peer_id = *peer::Id::new(peer_number); torrent.upsert_peer(&peer).await; } From dcb7770acb5867c704c66a38432507bf643b2541 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 24 Aug 2024 17:58:11 +0200 Subject: [PATCH 0478/1297] chore: update contrib bencode --- Cargo.lock | 12 +- contrib/bencode/Cargo.toml | 6 +- contrib/bencode/src/access/convert.rs | 78 ++++------ contrib/bencode/src/access/dict.rs | 6 +- contrib/bencode/src/access/list.rs | 8 -- contrib/bencode/src/error.rs | 143 ++++++------------- contrib/bencode/src/lib.rs | 6 +- contrib/bencode/src/mutable/encode.rs | 2 + contrib/bencode/src/reference/bencode_ref.rs | 7 +- contrib/bencode/src/reference/decode.rs | 81 ++++------- contrib/bencode/{test => tests}/mod.rs | 0 11 files changed, 117 insertions(+), 232 deletions(-) rename contrib/bencode/{test => tests}/mod.rs (100%) diff --git a/Cargo.lock b/Cargo.lock index 504a5bb17..057e1f5db 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1274,16 +1274,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "error-chain" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc" -dependencies = [ - "backtrace", - "version_check", -] - [[package]] name = "event-listener" version = "2.5.3" @@ -4021,7 +4011,7 @@ name = "torrust-tracker-contrib-bencode" version = "3.0.0-beta-develop" dependencies = [ "criterion", - "error-chain", + "thiserror", ] [[package]] diff --git a/contrib/bencode/Cargo.toml b/contrib/bencode/Cargo.toml index f7bab0585..e25a9b64f 100644 --- a/contrib/bencode/Cargo.toml +++ b/contrib/bencode/Cargo.toml @@ -16,15 +16,11 @@ rust-version.workspace = true version.workspace = true [dependencies] -error-chain = "0" +thiserror = "1" [dev-dependencies] criterion = "0" -[[test]] -name = "test" -path = "test/mod.rs" - [[bench]] harness = false name = "bencode_benchmark" diff --git a/contrib/bencode/src/access/convert.rs b/contrib/bencode/src/access/convert.rs index 42b04f267..b2eb41d15 100644 --- a/contrib/bencode/src/access/convert.rs +++ b/contrib/bencode/src/access/convert.rs @@ -2,7 +2,7 @@ use crate::access::bencode::{BRefAccess, BRefAccessExt}; use crate::access::dict::BDictAccess; use crate::access::list::BListAccess; -use crate::{BencodeConvertError, BencodeConvertErrorKind}; +use crate::BencodeConvertError; /// Trait for extended casting of bencode objects and converting conversion errors into application specific errors. pub trait BConvertExt: BConvert { @@ -12,12 +12,10 @@ pub trait BConvertExt: BConvert { B: BRefAccessExt<'a>, E: AsRef<[u8]>, { - bencode.bytes_ext().ok_or( - self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { - key: error_key.as_ref().to_owned(), - expected_type: "Bytes".to_owned(), - })), - ) + bencode.bytes_ext().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Bytes".to_owned(), + })) } /// See `BConvert::convert_str`. @@ -26,12 +24,10 @@ pub trait BConvertExt: BConvert { B: BRefAccessExt<'a>, E: AsRef<[u8]>, { - bencode.str_ext().ok_or( - self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { - key: error_key.as_ref().to_owned(), - expected_type: "UTF-8 Bytes".to_owned(), - })), - ) + bencode.str_ext().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "UTF-8 Bytes".to_owned(), + })) } /// See `BConvert::lookup_and_convert_bytes`. @@ -77,12 +73,10 @@ pub trait BConvert { B: BRefAccess, E: AsRef<[u8]>, { - bencode.int().ok_or( - self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { - key: error_key.as_ref().to_owned(), - expected_type: "Integer".to_owned(), - })), - ) + bencode.int().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Integer".to_owned(), + })) } /// Attempt to convert the given bencode value into bytes. @@ -93,12 +87,10 @@ pub trait BConvert { B: BRefAccess, E: AsRef<[u8]>, { - bencode.bytes().ok_or( - self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { - key: error_key.as_ref().to_owned(), - expected_type: "Bytes".to_owned(), - })), - ) + bencode.bytes().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Bytes".to_owned(), + })) } /// Attempt to convert the given bencode value into a UTF-8 string. @@ -109,12 +101,10 @@ pub trait BConvert { B: BRefAccess, E: AsRef<[u8]>, { - bencode.str().ok_or( - self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { - key: error_key.as_ref().to_owned(), - expected_type: "UTF-8 Bytes".to_owned(), - })), - ) + bencode.str().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "UTF-8 Bytes".to_owned(), + })) } /// Attempt to convert the given bencode value into a list. @@ -125,12 +115,10 @@ pub trait BConvert { B: BRefAccess, E: AsRef<[u8]>, { - bencode.list().ok_or( - self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { - key: error_key.as_ref().to_owned(), - expected_type: "List".to_owned(), - })), - ) + bencode.list().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "List".to_owned(), + })) } /// Attempt to convert the given bencode value into a dictionary. @@ -141,12 +129,10 @@ pub trait BConvert { B: BRefAccess, E: AsRef<[u8]>, { - bencode.dict().ok_or( - self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { - key: error_key.as_ref().to_owned(), - expected_type: "Dictionary".to_owned(), - })), - ) + bencode.dict().ok_or(self.handle_error(BencodeConvertError::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Dictionary".to_owned(), + })) } /// Look up a value in a dictionary of bencoded values using the given key. @@ -159,11 +145,7 @@ pub trait BConvert { match dictionary.lookup(key_ref) { Some(n) => Ok(n), - None => Err( - self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::MissingKey { - key: key_ref.to_owned(), - })), - ), + None => Err(self.handle_error(BencodeConvertError::MissingKey { key: key_ref.to_owned() })), } } diff --git a/contrib/bencode/src/access/dict.rs b/contrib/bencode/src/access/dict.rs index 7efe93fc3..a3e56d1bb 100644 --- a/contrib/bencode/src/access/dict.rs +++ b/contrib/bencode/src/access/dict.rs @@ -21,8 +21,7 @@ pub trait BDictAccess { impl<'a, V> BDictAccess<&'a [u8], V> for BTreeMap<&'a [u8], V> { fn to_list(&self) -> Vec<(&&'a [u8], &V)> { - #[allow(clippy::map_identity)] - self.iter().map(|(k, v)| (k, v)).collect() + self.iter().collect() } fn lookup(&self, key: &[u8]) -> Option<&V> { @@ -44,8 +43,7 @@ impl<'a, V> BDictAccess<&'a [u8], V> for BTreeMap<&'a [u8], V> { impl<'a, V> BDictAccess, V> for BTreeMap, V> { fn to_list(&self) -> Vec<(&Cow<'a, [u8]>, &V)> { - #[allow(clippy::map_identity)] - self.iter().map(|(k, v)| (k, v)).collect() + self.iter().collect() } fn lookup(&self, key: &[u8]) -> Option<&V> { diff --git a/contrib/bencode/src/access/list.rs b/contrib/bencode/src/access/list.rs index c6d1fc407..840bffa1e 100644 --- a/contrib/bencode/src/access/list.rs +++ b/contrib/bencode/src/access/list.rs @@ -45,14 +45,6 @@ impl<'a, V: 'a> IndexMut for &'a mut dyn BListAccess { } } -impl<'a, V: 'a> dyn BListAccess { - pub fn iter(&'a self) -> impl Iterator { - self.into_iter() - } -} - -#[allow(unknown_lints)] -#[allow(clippy::into_iter_without_iter)] impl<'a, V: 'a> IntoIterator for &'a dyn BListAccess { type Item = &'a V; type IntoIter = BListIter<'a, V>; diff --git a/contrib/bencode/src/error.rs b/contrib/bencode/src/error.rs index 54c589e3e..6e661a068 100644 --- a/contrib/bencode/src/error.rs +++ b/contrib/bencode/src/error.rs @@ -1,103 +1,52 @@ -#![allow(unknown_lints)] -#![allow(clippy::iter_without_into_iter)] -use error_chain::error_chain; +use thiserror::Error; -error_chain! { - types { - BencodeParseError, BencodeParseErrorKind, BencodeParseResultExt, BencodeParseResult; - } +#[allow(clippy::module_name_repetitions)] +#[derive(Error, Debug)] +pub enum BencodeParseError { + #[error("Incomplete Number Of Bytes At {pos}")] + BytesEmpty { pos: usize }, - errors { - BytesEmpty { - pos: usize - } { - description("Incomplete Number Of Bytes") - display("Incomplete Number Of Bytes At {:?}", pos) - } - InvalidByte { - pos: usize - } { - description("Invalid Byte Found") - display("Invalid Byte Found At {:?}", pos) - } - InvalidIntNoDelimiter { - pos: usize - } { - description("Invalid Integer Found With No Delimiter") - display("Invalid Integer Found With No Delimiter At {:?}", pos) - } - InvalidIntNegativeZero { - pos: usize - } { - description("Invalid Integer Found As Negative Zero") - display("Invalid Integer Found As Negative Zero At {:?}", pos) - } - InvalidIntZeroPadding { - pos: usize - } { - description("Invalid Integer Found With Zero Padding") - display("Invalid Integer Found With Zero Padding At {:?}", pos) - } - InvalidIntParseError { - pos: usize - } { - description("Invalid Integer Found To Fail Parsing") - display("Invalid Integer Found To Fail Parsing At {:?}", pos) - } - InvalidKeyOrdering { - pos: usize, - key: Vec - } { - description("Invalid Dictionary Key Ordering Found") - display("Invalid Dictionary Key Ordering Found At {:?} For Key {:?}", pos, key) - } - InvalidKeyDuplicates { - pos: usize, - key: Vec - } { - description("Invalid Dictionary Duplicate Keys Found") - display("Invalid Dictionary Key Found At {:?} For Key {:?}", pos, key) - } - InvalidLengthNegative { - pos: usize - } { - description("Invalid Byte Length Found As Negative") - display("Invalid Byte Length Found As Negative At {:?}", pos) - } - InvalidLengthOverflow { - pos: usize - } { - description("Invalid Byte Length Found To Overflow Buffer Length") - display("Invalid Byte Length Found To Overflow Buffer Length At {:?}", pos) - } - InvalidRecursionExceeded { - pos: usize, - max: usize - } { - description("Invalid Recursion Limit Exceeded") - display("Invalid Recursion Limit Exceeded At {:?} For Limit {:?}", pos, max) - } - } + #[error("Invalid Byte Found At {pos}")] + InvalidByte { pos: usize }, + + #[error("Invalid Integer Found With No Delimiter At {pos}")] + InvalidIntNoDelimiter { pos: usize }, + + #[error("Invalid Integer Found As Negative Zero At {pos}")] + InvalidIntNegativeZero { pos: usize }, + + #[error("Invalid Integer Found With Zero Padding At {pos}")] + InvalidIntZeroPadding { pos: usize }, + + #[error("Invalid Integer Found To Fail Parsing At {pos}")] + InvalidIntParseError { pos: usize }, + + #[error("Invalid Dictionary Key Ordering Found At {pos} For Key {key:?}")] + InvalidKeyOrdering { pos: usize, key: Vec }, + + #[error("Invalid Dictionary Key Found At {pos} For Key {key:?}")] + InvalidKeyDuplicates { pos: usize, key: Vec }, + + #[error("Invalid Byte Length Found As Negative At {pos}")] + InvalidLengthNegative { pos: usize }, + + #[error("Invalid Byte Length Found To Overflow Buffer Length At {pos}")] + InvalidLengthOverflow { pos: usize }, + + #[error("Invalid Recursion Limit Exceeded At {pos} For Limit {max}")] + InvalidRecursionExceeded { pos: usize, max: usize }, } -error_chain! { - types { - BencodeConvertError, BencodeConvertErrorKind, BencodeConvertResultExt, BencodeConvertResult; - } +pub type BencodeParseResult = Result; - errors { - MissingKey { - key: Vec - } { - description("Missing Key In Bencode") - display("Missing Key In Bencode For {:?}", key) - } - WrongType { - key: Vec, - expected_type: String - } { - description("Wrong Type In Bencode") - display("Wrong Type In Bencode For {:?} Expected Type {}", key, expected_type) - } - } +#[allow(clippy::module_name_repetitions)] +#[derive(Error, Debug)] +pub enum BencodeConvertError { + #[error("Missing Key In Bencode For {key:?}")] + MissingKey { key: Vec }, + + #[error("Wrong Type In Bencode For {key:?} Expected Type {expected_type}")] + WrongType { key: Vec, expected_type: String }, } + +pub type BencodeConvertResult = Result; diff --git a/contrib/bencode/src/lib.rs b/contrib/bencode/src/lib.rs index 78e113b66..09aaa6867 100644 --- a/contrib/bencode/src/lib.rs +++ b/contrib/bencode/src/lib.rs @@ -7,7 +7,6 @@ //! ```rust //! extern crate bencode; //! -//! use std::default::Default; //! use bencode::{BencodeRef, BRefAccess, BDecodeOpt}; //! //! fn main() { @@ -63,10 +62,7 @@ pub use crate::access::bencode::{BMutAccess, BRefAccess, MutKind, RefKind}; pub use crate::access::convert::BConvert; pub use crate::access::dict::BDictAccess; pub use crate::access::list::BListAccess; -pub use crate::error::{ - BencodeConvertError, BencodeConvertErrorKind, BencodeConvertResult, BencodeParseError, BencodeParseErrorKind, - BencodeParseResult, -}; +pub use crate::error::{BencodeConvertError, BencodeConvertResult, BencodeParseError, BencodeParseResult}; pub use crate::mutable::bencode_mut::BencodeMut; pub use crate::reference::bencode_ref::BencodeRef; pub use crate::reference::decode_opt::BDecodeOpt; diff --git a/contrib/bencode/src/mutable/encode.rs b/contrib/bencode/src/mutable/encode.rs index 25c91b41d..811c35816 100644 --- a/contrib/bencode/src/mutable/encode.rs +++ b/contrib/bencode/src/mutable/encode.rs @@ -1,3 +1,5 @@ +use std::iter::Extend; + use crate::access::bencode::{BRefAccess, RefKind}; use crate::access::dict::BDictAccess; use crate::access::list::BListAccess; diff --git a/contrib/bencode/src/reference/bencode_ref.rs b/contrib/bencode/src/reference/bencode_ref.rs index a6f2c15bc..73aaad039 100644 --- a/contrib/bencode/src/reference/bencode_ref.rs +++ b/contrib/bencode/src/reference/bencode_ref.rs @@ -4,7 +4,7 @@ use std::str; use crate::access::bencode::{BRefAccess, BRefAccessExt, RefKind}; use crate::access::dict::BDictAccess; use crate::access::list::BListAccess; -use crate::error::{BencodeParseError, BencodeParseErrorKind, BencodeParseResult}; +use crate::error::{BencodeParseError, BencodeParseResult}; use crate::reference::decode; use crate::reference::decode_opt::BDecodeOpt; @@ -41,9 +41,7 @@ impl<'a> BencodeRef<'a> { let (bencode, end_pos) = decode::decode(bytes, 0, opts, 0)?; if end_pos != bytes.len() && opts.enforce_full_decode() { - return Err(BencodeParseError::from_kind(BencodeParseErrorKind::BytesEmpty { - pos: end_pos, - })); + return Err(BencodeParseError::BytesEmpty { pos: end_pos }); } Ok(bencode) @@ -125,6 +123,7 @@ impl<'a> BRefAccessExt<'a> for BencodeRef<'a> { #[cfg(test)] mod tests { + use crate::access::bencode::BRefAccess; use crate::reference::bencode_ref::BencodeRef; use crate::reference::decode_opt::BDecodeOpt; diff --git a/contrib/bencode/src/reference/decode.rs b/contrib/bencode/src/reference/decode.rs index d35d1b597..97c5cf1ff 100644 --- a/contrib/bencode/src/reference/decode.rs +++ b/contrib/bencode/src/reference/decode.rs @@ -1,16 +1,14 @@ use std::collections::btree_map::Entry; use std::collections::BTreeMap; -use std::str::{self}; +use std::str; -use crate::error::{BencodeParseError, BencodeParseErrorKind, BencodeParseResult}; +use crate::error::{BencodeParseError, BencodeParseResult}; use crate::reference::bencode_ref::{BencodeRef, Inner}; use crate::reference::decode_opt::BDecodeOpt; pub fn decode(bytes: &[u8], pos: usize, opts: BDecodeOpt, depth: usize) -> BencodeParseResult<(BencodeRef<'_>, usize)> { if depth >= opts.max_recursion() { - return Err(BencodeParseError::from_kind( - BencodeParseErrorKind::InvalidRecursionExceeded { pos, max: depth }, - )); + return Err(BencodeParseError::InvalidRecursionExceeded { pos, max: depth }); } let curr_byte = peek_byte(bytes, pos)?; @@ -32,7 +30,7 @@ pub fn decode(bytes: &[u8], pos: usize, opts: BDecodeOpt, depth: usize) -> Benco // Include the length digit, don't increment position Ok((Inner::Bytes(bencode, &bytes[pos..next_pos]).into(), next_pos)) } - _ => Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidByte { pos })), + _ => Err(BencodeParseError::InvalidByte { pos }), } } @@ -40,32 +38,24 @@ fn decode_int(bytes: &[u8], pos: usize, delim: u8) -> BencodeParseResult<(i64, u let (_, begin_decode) = bytes.split_at(pos); let Some(relative_end_pos) = begin_decode.iter().position(|n| *n == delim) else { - return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntNoDelimiter { - pos, - })); + return Err(BencodeParseError::InvalidIntNoDelimiter { pos }); }; let int_byte_slice = &begin_decode[..relative_end_pos]; if int_byte_slice.len() > 1 { // Negative zero is not allowed (this would not be caught when converting) if int_byte_slice[0] == b'-' && int_byte_slice[1] == b'0' { - return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntNegativeZero { - pos, - })); + return Err(BencodeParseError::InvalidIntNegativeZero { pos }); } // Zero padding is illegal, and unspecified for key lengths (we disallow both) if int_byte_slice[0] == b'0' { - return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntZeroPadding { - pos, - })); + return Err(BencodeParseError::InvalidIntZeroPadding { pos }); } } let Ok(int_str) = str::from_utf8(int_byte_slice) else { - return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntParseError { - pos, - })); + return Err(BencodeParseError::InvalidIntParseError { pos }); }; // Position of end of integer type, next byte is the start of the next value @@ -73,31 +63,24 @@ fn decode_int(bytes: &[u8], pos: usize, delim: u8) -> BencodeParseResult<(i64, u let next_pos = absolute_end_pos + 1; match int_str.parse::() { Ok(n) => Ok((n, next_pos)), - Err(_) => Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntParseError { - pos, - })), + Err(_) => Err(BencodeParseError::InvalidIntParseError { pos }), } } +use std::convert::TryFrom; + fn decode_bytes(bytes: &[u8], pos: usize) -> BencodeParseResult<(&[u8], usize)> { let (num_bytes, start_pos) = decode_int(bytes, pos, crate::BYTE_LEN_END)?; if num_bytes < 0 { - return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidLengthNegative { - pos, - })); + return Err(BencodeParseError::InvalidLengthNegative { pos }); } - // Should be safe to cast to usize (TODO: Check if cast would overflow to provide - // a more helpful error message, otherwise, parsing will probably fail with an - // unrelated message). - let num_bytes = - usize::try_from(num_bytes).map_err(|_| BencodeParseErrorKind::Msg(format!("input length is too long: {num_bytes}")))?; + // Use usize::try_from to handle potential overflow + let num_bytes = usize::try_from(num_bytes).map_err(|_| BencodeParseError::InvalidLengthOverflow { pos })?; if num_bytes > bytes[start_pos..].len() { - return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidLengthOverflow { - pos, - })); + return Err(BencodeParseError::InvalidLengthOverflow { pos }); } let next_pos = start_pos + num_bytes; @@ -140,10 +123,10 @@ fn decode_dict( // Spec says that the keys must be in alphabetical order match (bencode_dict.keys().last(), opts.check_key_sort()) { (Some(last_key), true) if key_bytes < *last_key => { - return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidKeyOrdering { + return Err(BencodeParseError::InvalidKeyOrdering { pos: curr_pos, key: key_bytes.to_vec(), - })) + }) } _ => (), }; @@ -153,10 +136,10 @@ fn decode_dict( match bencode_dict.entry(key_bytes) { Entry::Vacant(n) => n.insert(value), Entry::Occupied(_) => { - return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidKeyDuplicates { + return Err(BencodeParseError::InvalidKeyDuplicates { pos: curr_pos, key: key_bytes.to_vec(), - })) + }) } }; @@ -169,14 +152,12 @@ fn decode_dict( } fn peek_byte(bytes: &[u8], pos: usize) -> BencodeParseResult { - bytes - .get(pos) - .copied() - .ok_or_else(|| BencodeParseError::from_kind(BencodeParseErrorKind::BytesEmpty { pos })) + bytes.get(pos).copied().ok_or(BencodeParseError::BytesEmpty { pos }) } #[cfg(test)] mod tests { + use crate::access::bencode::BRefAccess; use crate::reference::bencode_ref::BencodeRef; use crate::reference::decode_opt::BDecodeOpt; @@ -327,13 +308,13 @@ mod tests { } #[test] - #[should_panic = "BencodeParseError(InvalidByte { pos: 0 }"] + #[should_panic = "InvalidByte { pos: 0 }"] fn negative_decode_bytes_neg_len() { BencodeRef::decode(BYTES_NEG_LEN, BDecodeOpt::default()).unwrap(); } #[test] - #[should_panic = "BencodeParseError(BytesEmpty { pos: 20 }"] + #[should_panic = "BytesEmpty { pos: 20 }"] fn negative_decode_bytes_extra() { BencodeRef::decode(BYTES_EXTRA, BDecodeOpt::default()).unwrap(); } @@ -346,49 +327,49 @@ mod tests { } #[test] - #[should_panic = "BencodeParseError(InvalidIntParseError { pos: 1 }"] + #[should_panic = "InvalidIntParseError { pos: 1 }"] fn negative_decode_int_nan() { super::decode_int(INT_NAN, 1, crate::BEN_END).unwrap(); } #[test] - #[should_panic = "BencodeParseError(InvalidIntZeroPadding { pos: 1 }"] + #[should_panic = "InvalidIntZeroPadding { pos: 1 }"] fn negative_decode_int_leading_zero() { super::decode_int(INT_LEADING_ZERO, 1, crate::BEN_END).unwrap(); } #[test] - #[should_panic = "BencodeParseError(InvalidIntZeroPadding { pos: 1 }"] + #[should_panic = "InvalidIntZeroPadding { pos: 1 }"] fn negative_decode_int_double_zero() { super::decode_int(INT_DOUBLE_ZERO, 1, crate::BEN_END).unwrap(); } #[test] - #[should_panic = "BencodeParseError(InvalidIntNegativeZero { pos: 1 }"] + #[should_panic = "InvalidIntNegativeZero { pos: 1 }"] fn negative_decode_int_negative_zero() { super::decode_int(INT_NEGATIVE_ZERO, 1, crate::BEN_END).unwrap(); } #[test] - #[should_panic = " BencodeParseError(InvalidIntParseError { pos: 1 }"] + #[should_panic = " InvalidIntParseError { pos: 1 }"] fn negative_decode_int_double_negative() { super::decode_int(INT_DOUBLE_NEGATIVE, 1, crate::BEN_END).unwrap(); } #[test] - #[should_panic = "BencodeParseError(InvalidKeyOrdering { pos: 15, key: [97, 95, 107, 101, 121] }"] + #[should_panic = "InvalidKeyOrdering { pos: 15, key: [97, 95, 107, 101, 121] }"] fn negative_decode_dict_unordered_keys() { BencodeRef::decode(DICT_UNORDERED_KEYS, BDecodeOpt::new(5, true, true)).unwrap(); } #[test] - #[should_panic = "BencodeParseError(InvalidKeyDuplicates { pos: 18, key: [97, 95, 107, 101, 121] }"] + #[should_panic = "InvalidKeyDuplicates { pos: 18, key: [97, 95, 107, 101, 121] }"] fn negative_decode_dict_dup_keys_same_data() { BencodeRef::decode(DICT_DUP_KEYS_SAME_DATA, BDecodeOpt::default()).unwrap(); } #[test] - #[should_panic = "BencodeParseError(InvalidKeyDuplicates { pos: 18, key: [97, 95, 107, 101, 121] }"] + #[should_panic = "InvalidKeyDuplicates { pos: 18, key: [97, 95, 107, 101, 121] }"] fn negative_decode_dict_dup_keys_diff_data() { BencodeRef::decode(DICT_DUP_KEYS_DIFF_DATA, BDecodeOpt::default()).unwrap(); } diff --git a/contrib/bencode/test/mod.rs b/contrib/bencode/tests/mod.rs similarity index 100% rename from contrib/bencode/test/mod.rs rename to contrib/bencode/tests/mod.rs From c5a724e9da1e670edb775a4581ac3da92c8ebb44 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 24 Aug 2024 18:19:10 +0200 Subject: [PATCH 0479/1297] chore: update deps ``` sh cargo update Updating crates.io index Locking 12 packages to latest compatible versions Updating bindgen v0.70.0 -> v0.70.1 Updating cc v1.1.13 -> v1.1.14 Updating derive_utils v0.14.1 -> v0.14.2 Updating fastrand v2.1.0 -> v2.1.1 Updating flate2 v1.0.32 -> v1.0.33 Updating libz-sys v1.1.19 -> v1.1.20 Updating quote v1.0.36 -> v1.0.37 Updating serde v1.0.208 -> v1.0.209 Updating serde_derive v1.0.208 -> v1.0.209 Updating serde_json v1.0.125 -> v1.0.127 Updating syn v2.0.75 -> v2.0.76 Updating system-configuration v0.6.0 -> v0.6.1 ``` --- Cargo.lock | 128 ++++++++++++++++++++++++++--------------------------- Cargo.toml | 2 +- 2 files changed, 65 insertions(+), 65 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 057e1f5db..740f185bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -247,7 +247,7 @@ checksum = "d7ebdfa2ebdab6b1760375fa7d6f382b9f486eac35fc994625a00e89280bdbb7" dependencies = [ "async-task", "concurrent-queue", - "fastrand 2.1.0", + "fastrand 2.1.1", "futures-lite 2.3.0", "slab", ] @@ -368,7 +368,7 @@ checksum = "6e0c28dcc82d7c8ead5cb13beb15405b57b8546e93215673ff8ca0349a028107" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -518,7 +518,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -610,15 +610,15 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.75", + "syn 2.0.76", "which", ] [[package]] name = "bindgen" -version = "0.70.0" +version = "0.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0127a1da21afb5adaae26910922c3f7afd3d329ba1a1b98a0884cab4907a251" +checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" dependencies = [ "bitflags 2.6.0", "cexpr", @@ -629,7 +629,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -698,7 +698,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", "syn_derive", ] @@ -810,9 +810,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.1.13" +version = "1.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72db2f7947ecee9b03b510377e8bb9077afa27176fdbff55c51027e976fdcc48" +checksum = "50d2eb3cd3d1bf4529e31c215ee6f93ec5a3d536d9f578f93d9d33ee19562932" dependencies = [ "jobserver", "libc", @@ -922,7 +922,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -1149,7 +1149,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -1160,7 +1160,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -1197,18 +1197,18 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] name = "derive_utils" -version = "0.14.1" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61bb5a1014ce6dfc2a378578509abe775a5aa06bff584a547555d9efdb81b926" +checksum = "65f152f4b8559c4da5d574bafc7af85454d706b4c5fe8b530d508cacbb6807ea" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -1324,9 +1324,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.1.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" +checksum = "e8c02a5121d4ea3eb16a80748c74f5549a5665e4c21333c6098f283870fbdea6" [[package]] name = "figment" @@ -1346,9 +1346,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.32" +version = "1.0.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c0596c1eac1f9e04ed902702e9878208b336edc9d6fddc8a48387349bab3666" +checksum = "324a1be68054ef05ad64b861cc9eaf1d623d2d8cb25b4bf2cb9cdd902b4bf253" dependencies = [ "crc32fast", "libz-sys", @@ -1426,7 +1426,7 @@ checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -1438,7 +1438,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -1450,7 +1450,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -1534,7 +1534,7 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" dependencies = [ - "fastrand 2.1.0", + "fastrand 2.1.1", "futures-core", "futures-io", "parking", @@ -1549,7 +1549,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -2081,9 +2081,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.19" +version = "1.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdc53a7799a7496ebc9fd29f31f7df80e83c9bda5299768af5f9e59eeea74647" +checksum = "d2d16453e800a8cf6dd2fc3eb4bc99b786a9b90c663b8559a5b1a041bf89e472" dependencies = [ "cc", "pkg-config", @@ -2225,7 +2225,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -2275,7 +2275,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", "termcolor", "thiserror", ] @@ -2288,7 +2288,7 @@ checksum = "478b0ff3f7d67b79da2b96f56f334431aef65e15ba4b29dd74a4236e29582bdc" dependencies = [ "base64 0.21.7", "bigdecimal", - "bindgen 0.70.0", + "bindgen 0.70.1", "bitflags 2.6.0", "bitvec", "btoi", @@ -2474,7 +2474,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -2556,7 +2556,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -2630,7 +2630,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -2652,7 +2652,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066" dependencies = [ "atomic-waker", - "fastrand 2.1.0", + "fastrand 2.1.1", "futures-io", ] @@ -2764,12 +2764,12 @@ dependencies = [ [[package]] name = "prettyplease" -version = "0.2.20" +version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e" +checksum = "a909e6e8053fa1a5ad670f5816c7d93029ee1fa8898718490544a6b0d5d38b3e" dependencies = [ "proc-macro2", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -2822,7 +2822,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", "version_check", "yansi", ] @@ -2860,9 +2860,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.36" +version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" dependencies = [ "proc-macro2", ] @@ -3130,7 +3130,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.75", + "syn 2.0.76", "unicode-ident", ] @@ -3342,9 +3342,9 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" -version = "1.0.208" +version = "1.0.209" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cff085d2cb684faa248efb494c39b68e522822ac0de72ccf08109abde717cfb2" +checksum = "99fce0ffe7310761ca6bf9faf5115afbc19688edd00171d81b1bb1b116c63e09" dependencies = [ "serde_derive", ] @@ -3370,13 +3370,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.208" +version = "1.0.209" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24008e81ff7613ed8e5ba0cfaf24e2c2f1e5b8a0495711e44fcd4882fca62bcf" +checksum = "a5831b979fd7b5439637af1752d535ff49f4860c0f341d1baeb6faf0f4242170" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -3394,9 +3394,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.125" +version = "1.0.127" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83c8e735a073ccf5be70aa8066aa984eaf2fa000db6c8d0100ae605b366d31ed" +checksum = "8043c06d9f82bd7271361ed64f415fe5e12a77fdb52e573e7f06a516dea329ad" dependencies = [ "indexmap 2.4.0", "itoa", @@ -3423,7 +3423,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -3474,7 +3474,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -3617,9 +3617,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.75" +version = "2.0.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6af063034fc1935ede7be0122941bafa9bacb949334d090b77ca98b5817c7d9" +checksum = "578e081a14e0cefc3279b0472138c513f37b41a08d5a3cca9b6e4e8ceb6cd525" dependencies = [ "proc-macro2", "quote", @@ -3635,7 +3635,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -3655,9 +3655,9 @@ dependencies = [ [[package]] name = "system-configuration" -version = "0.6.0" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658bc6ee10a9b4fcf576e9b0819d95ec16f4d2c02d39fd83ac1c8789785c4a42" +checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" dependencies = [ "bitflags 2.6.0", "core-foundation", @@ -3704,7 +3704,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64" dependencies = [ "cfg-if", - "fastrand 2.1.0", + "fastrand 2.1.1", "once_cell", "rustix 0.38.34", "windows-sys 0.59.0", @@ -3742,7 +3742,7 @@ checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -3836,7 +3836,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -4156,7 +4156,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -4371,7 +4371,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", "wasm-bindgen-shared", ] @@ -4405,7 +4405,7 @@ checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4707,7 +4707,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] @@ -4727,7 +4727,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.75", + "syn 2.0.76", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 43453cb5a..e0774e237 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,7 +66,7 @@ serde_bencode = "0" serde_bytes = "0" serde_json = { version = "1", features = ["preserve_order"] } serde_repr = "0" -serde_with = { version = "3.9.0", features = ["json"] } +serde_with = { version = "3", features = ["json"] } thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-beta-develop", path = "packages/clock" } From 2c4bdab2c92ed30193024366b9915513213cf105 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 24 Aug 2024 18:31:25 +0200 Subject: [PATCH 0480/1297] chore: update to v1 of derive more --- Cargo.lock | 28 ++++++++++++++++++---------- Cargo.toml | 2 +- packages/configuration/Cargo.toml | 2 +- packages/configuration/src/lib.rs | 2 +- packages/primitives/Cargo.toml | 2 +- 5 files changed, 22 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 740f185bc..0e3401278 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -968,12 +968,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "convert_case" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" - [[package]] name = "core-foundation" version = "0.9.4" @@ -1189,15 +1183,23 @@ dependencies = [ [[package]] name = "derive_more" -version = "0.99.18" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a9b99b9cbbe49445b21764dc0625032a89b145a2642e67603e1c936f5458d05" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f33878137e4dafd7fa914ad4e259e18a4e8e532b9617a2d0150262bf53abfce" +checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ - "convert_case", "proc-macro2", "quote", - "rustc_version", "syn 2.0.76", + "unicode-xid", ] [[package]] @@ -4260,6 +4262,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-xid" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229730647fbc343e3a80e463c1db7f78f3855d3f3739bee0dda773c9a037c90a" + [[package]] name = "untrusted" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index e0774e237..1a875a192 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,7 +41,7 @@ chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } crossbeam-skiplist = "0" dashmap = "6" -derive_more = "0" +derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } figment = "0" futures = "0" futures-util = "0" diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 0a4cfea23..4f217e1b6 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -16,7 +16,7 @@ version.workspace = true [dependencies] camino = { version = "1", features = ["serde", "serde1"] } -derive_more = "0" +derive_more = { version = "1", features = ["constructor", "display"] } figment = { version = "0", features = ["env", "test", "toml"] } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index bdbe419ca..1ab3479fa 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -51,7 +51,7 @@ pub const LATEST_VERSION: &str = "2.0.0"; /// Info about the configuration specification. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Display, Clone)] -#[display(fmt = "Metadata(app: {app}, purpose: {purpose}, schema_version: {schema_version})")] +#[display("Metadata(app: {app}, purpose: {purpose}, schema_version: {schema_version})")] pub struct Metadata { /// The application this configuration is valid for. #[serde(default = "Metadata::default_app")] diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index 05981b3a8..02a53e3b7 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -17,7 +17,7 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" binascii = "0" -derive_more = "0" +derive_more = { version = "1", features = ["constructor"] } serde = { version = "1", features = ["derive"] } tdyne-peer-id = "1" tdyne-peer-id-registry = "0" From e4aa1db63b1006e5042f2dcb1d439173f444f395 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 24 Aug 2024 15:33:23 +0200 Subject: [PATCH 0481/1297] tracing: qualify use of tracing macros --- packages/located-error/src/lib.rs | 4 +--- src/app.rs | 11 ++++----- src/bootstrap/app.rs | 3 +-- src/bootstrap/jobs/health_check_api.rs | 7 +++--- src/bootstrap/jobs/mod.rs | 5 ++-- src/bootstrap/jobs/torrent_cleanup.rs | 7 +++--- src/bootstrap/jobs/udp_tracker.rs | 7 +++--- src/bootstrap/logging.rs | 3 +-- src/console/ci/e2e/docker.rs | 8 +++---- src/console/ci/e2e/runner.rs | 13 +++++------ src/console/ci/e2e/tracker_checker.rs | 6 ++--- src/console/ci/e2e/tracker_container.rs | 23 +++++++++---------- src/console/clients/checker/app.rs | 3 +-- src/console/clients/udp/app.rs | 9 ++++---- src/console/clients/udp/checker.rs | 7 +++--- src/console/profiling.rs | 5 ++-- src/core/auth.rs | 5 ++-- src/core/databases/mysql.rs | 3 +-- src/core/mod.rs | 5 ++-- src/core/statistics.rs | 3 +-- src/main.rs | 5 ++-- src/servers/apis/server.rs | 11 ++++----- .../apis/v1/context/torrent/handlers.rs | 3 +-- src/servers/health_check_api/server.rs | 4 ++-- src/servers/http/server.rs | 5 ++-- src/servers/http/v1/handlers/announce.rs | 5 ++-- src/servers/http/v1/handlers/scrape.rs | 5 ++-- src/servers/registar.rs | 3 +-- src/servers/signals.rs | 11 ++++----- src/servers/udp/handlers.rs | 19 ++++++++------- tests/servers/health_check_api/environment.rs | 9 ++++---- 31 files changed, 92 insertions(+), 125 deletions(-) diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs index bfd4d4a86..3cba6042d 100644 --- a/packages/located-error/src/lib.rs +++ b/packages/located-error/src/lib.rs @@ -33,8 +33,6 @@ use std::error::Error; use std::panic::Location; use std::sync::Arc; -use tracing::debug; - pub type DynError = Arc; /// A generic wrapper around an error. @@ -94,7 +92,7 @@ where source: Arc::new(self.0), location: Box::new(*std::panic::Location::caller()), }; - debug!("{e}"); + tracing::debug!("{e}"); e } } diff --git a/src/app.rs b/src/app.rs index b2447a9ef..f96ac399f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -25,7 +25,6 @@ use std::sync::Arc; use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; -use tracing::{info, warn}; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; use crate::servers::registar::Registar; @@ -42,7 +41,7 @@ pub async fn start(config: &Configuration, tracker: Arc) -> Vec> = Vec::new(); @@ -69,7 +68,7 @@ pub async fn start(config: &Configuration, tracker: Arc) -> Vec) -> Vec) -> Vec) -> Vec (Configuration, Arc) { let tracker = initialize_with_configuration(&configuration); - info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); + tracing::info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); (configuration, tracker) } diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index b4d4862ee..d306b2be9 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -17,7 +17,6 @@ use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_tracker_configuration::HealthCheckApi; -use tracing::info; use super::Started; use crate::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; @@ -45,18 +44,18 @@ pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> Jo // Run the API server let join_handle = tokio::spawn(async move { - info!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting on: {protocol}://{}", bind_addr); + tracing::info!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting on: {protocol}://{}", bind_addr); let handle = server::start(bind_addr, tx_start, rx_halt, register); if let Ok(()) = handle.await { - info!(target: HEALTH_CHECK_API_LOG_TARGET, "Stopped server running on: {protocol}://{}", bind_addr); + tracing::info!(target: HEALTH_CHECK_API_LOG_TARGET, "Stopped server running on: {protocol}://{}", bind_addr); } }); // Wait until the server sends the started message match rx_start.await { - Ok(msg) => info!(target: HEALTH_CHECK_API_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", msg.address), + Ok(msg) => tracing::info!(target: HEALTH_CHECK_API_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", msg.address), Err(e) => panic!("the Health Check API server was dropped: {e}"), } diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 79a4347ef..6534270fa 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -32,8 +32,8 @@ pub async fn make_rust_tls(opt_tsl_config: &Option) -> Option) -> JoinHandle<()> loop { tokio::select! { _ = tokio::signal::ctrl_c() => { - info!("Stopping torrent cleanup job.."); + tracing::info!("Stopping torrent cleanup job.."); break; } _ = interval.tick() => { if let Some(tracker) = weak_tracker.upgrade() { let start_time = Utc::now().time(); - info!("Cleaning up torrents.."); + tracing::info!("Cleaning up torrents.."); tracker.cleanup_torrents(); - info!("Cleaned up torrents in: {}ms", (Utc::now().time() - start_time).num_milliseconds()); + tracing::info!("Cleaned up torrents in: {}ms", (Utc::now().time() - start_time).num_milliseconds()); } else { break; } diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 647461bfc..407cfbbfa 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -10,7 +10,6 @@ use std::sync::Arc; use tokio::task::JoinHandle; use torrust_tracker_configuration::UdpTracker; -use tracing::debug; use crate::core; use crate::servers::registar::ServiceRegistrationForm; @@ -37,8 +36,8 @@ pub async fn start_job(config: &UdpTracker, tracker: Arc, form: S .expect("it should be able to start the udp tracker"); tokio::spawn(async move { - debug!(target: UDP_TRACKER_LOG_TARGET, "Wait for launcher (UDP service) to finish ..."); - debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed before waiting?: {}", server.state.halt_task.is_closed()); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Wait for launcher (UDP service) to finish ..."); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed before waiting?: {}", server.state.halt_task.is_closed()); assert!( !server.state.halt_task.is_closed(), @@ -51,6 +50,6 @@ pub async fn start_job(config: &UdpTracker, tracker: Arc, form: S .await .expect("it should be able to join to the udp tracker task"); - debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed after finishing the server?: {}", server.state.halt_task.is_closed()); + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, "Is halt channel closed after finishing the server?: {}", server.state.halt_task.is_closed()); }) } diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index 496b3ea45..34809c1ca 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -14,7 +14,6 @@ use std::sync::Once; use torrust_tracker_configuration::{Configuration, Threshold}; -use tracing::info; use tracing::level_filters::LevelFilter; static INIT: Once = Once::new(); @@ -54,7 +53,7 @@ fn tracing_stdout_init(filter: LevelFilter, style: &TraceStyle) { TraceStyle::Json => builder.json().init(), }; - info!("Logging initialized"); + tracing::info!("Logging initialized"); } #[derive(Debug)] diff --git a/src/console/ci/e2e/docker.rs b/src/console/ci/e2e/docker.rs index 32a0c3e56..ce2b1aa99 100644 --- a/src/console/ci/e2e/docker.rs +++ b/src/console/ci/e2e/docker.rs @@ -4,8 +4,6 @@ use std::process::{Command, Output}; use std::thread::sleep; use std::time::{Duration, Instant}; -use tracing::{debug, info}; - /// Docker command wrapper. pub struct Docker {} @@ -20,7 +18,7 @@ impl Drop for RunningContainer { /// Ensures that the temporary container is stopped when the struct goes out /// of scope. fn drop(&mut self) { - info!("Dropping running container: {}", self.name); + tracing::info!("Dropping running container: {}", self.name); if Docker::is_container_running(&self.name) { let _unused = Docker::stop(self); } @@ -89,7 +87,7 @@ impl Docker { let args = [initial_args, env_var_args, port_args, [image.to_string()].to_vec()].concat(); - debug!("Docker run args: {:?}", args); + tracing::debug!("Docker run args: {:?}", args); let output = Command::new("docker").args(args).output()?; @@ -176,7 +174,7 @@ impl Docker { let output_str = String::from_utf8_lossy(&output.stdout); - info!("Waiting until container is healthy: {:?}", output_str); + tracing::info!("Waiting until container is healthy: {:?}", output_str); if output_str.contains("(healthy)") { return true; diff --git a/src/console/ci/e2e/runner.rs b/src/console/ci/e2e/runner.rs index f2285938b..118ecda42 100644 --- a/src/console/ci/e2e/runner.rs +++ b/src/console/ci/e2e/runner.rs @@ -21,7 +21,6 @@ use std::path::PathBuf; use anyhow::Context; use clap::Parser; -use tracing::info; use tracing::level_filters::LevelFilter; use super::tracker_container::TrackerContainer; @@ -68,7 +67,7 @@ pub fn run() -> anyhow::Result<()> { let tracker_config = load_tracker_configuration(&args)?; - info!("tracker config:\n{tracker_config}"); + tracing::info!("tracker config:\n{tracker_config}"); let mut tracker_container = TrackerContainer::new(CONTAINER_IMAGE, CONTAINER_NAME_PREFIX); @@ -91,7 +90,7 @@ pub fn run() -> anyhow::Result<()> { let running_services = tracker_container.running_services(); - info!( + tracing::info!( "Running services:\n {}", serde_json::to_string_pretty(&running_services).expect("running services to be serializable to JSON") ); @@ -110,27 +109,27 @@ pub fn run() -> anyhow::Result<()> { tracker_container.remove(); - info!("Tracker container final state:\n{:#?}", tracker_container); + tracing::info!("Tracker container final state:\n{:#?}", tracker_container); Ok(()) } fn tracing_stdout_init(filter: LevelFilter) { tracing_subscriber::fmt().with_max_level(filter).init(); - info!("Logging initialized"); + tracing::info!("Logging initialized"); } fn load_tracker_configuration(args: &Args) -> anyhow::Result { match (args.config_toml_path.clone(), args.config_toml.clone()) { (Some(config_path), _) => { - info!( + tracing::info!( "Reading tracker configuration from file: {} ...", config_path.to_string_lossy() ); load_config_from_file(&config_path) } (_, Some(config_content)) => { - info!("Reading tracker configuration from env var ..."); + tracing::info!("Reading tracker configuration from env var ..."); Ok(config_content) } _ => Err(anyhow::anyhow!("No configuration provided")), diff --git a/src/console/ci/e2e/tracker_checker.rs b/src/console/ci/e2e/tracker_checker.rs index b2fd7df2e..192795e61 100644 --- a/src/console/ci/e2e/tracker_checker.rs +++ b/src/console/ci/e2e/tracker_checker.rs @@ -1,16 +1,14 @@ use std::io; use std::process::Command; -use tracing::info; - /// Runs the Tracker Checker. /// /// # Errors /// /// Will return an error if the Tracker Checker fails. pub fn run(config_content: &str) -> io::Result<()> { - info!("Running Tracker Checker: TORRUST_CHECKER_CONFIG=[config] cargo run --bin tracker_checker"); - info!("Tracker Checker config:\n{config_content}"); + tracing::info!("Running Tracker Checker: TORRUST_CHECKER_CONFIG=[config] cargo run --bin tracker_checker"); + tracing::info!("Tracker Checker config:\n{config_content}"); let status = Command::new("cargo") .env("TORRUST_CHECKER_CONFIG", config_content) diff --git a/src/console/ci/e2e/tracker_container.rs b/src/console/ci/e2e/tracker_container.rs index 528fd3c62..0d15035a8 100644 --- a/src/console/ci/e2e/tracker_container.rs +++ b/src/console/ci/e2e/tracker_container.rs @@ -2,7 +2,6 @@ use std::time::Duration; use rand::distributions::Alphanumeric; use rand::Rng; -use tracing::{error, info}; use super::docker::{RunOptions, RunningContainer}; use super::logs_parser::RunningServices; @@ -19,7 +18,7 @@ impl Drop for TrackerContainer { /// Ensures that the temporary container is removed when the /// struct goes out of scope. fn drop(&mut self) { - info!("Dropping tracker container: {}", self.name); + tracing::info!("Dropping tracker container: {}", self.name); if Docker::container_exist(&self.name) { let _unused = Docker::remove(&self.name); } @@ -40,7 +39,7 @@ impl TrackerContainer { /// /// Will panic if it can't build the docker image. pub fn build_image(&self) { - info!("Building tracker container image with tag: {} ...", self.image); + tracing::info!("Building tracker container image with tag: {} ...", self.image); Docker::build("./Containerfile", &self.image).expect("A tracker local docker image should be built"); } @@ -48,17 +47,17 @@ impl TrackerContainer { /// /// Will panic if it can't run the container. pub fn run(&mut self, options: &RunOptions) { - info!("Running docker tracker image: {} ...", self.name); + tracing::info!("Running docker tracker image: {} ...", self.name); let container = Docker::run(&self.image, &self.name, options).expect("A tracker local docker image should be running"); - info!("Waiting for the container {} to be healthy ...", self.name); + tracing::info!("Waiting for the container {} to be healthy ...", self.name); let is_healthy = Docker::wait_until_is_healthy(&self.name, Duration::from_secs(10)); assert!(is_healthy, "Unhealthy tracker container: {}", &self.name); - info!("Container {} is healthy ...", &self.name); + tracing::info!("Container {} is healthy ...", &self.name); self.running = Some(container); @@ -72,7 +71,7 @@ impl TrackerContainer { pub fn running_services(&self) -> RunningServices { let logs = Docker::logs(&self.name).expect("Logs should be captured from running container"); - info!("Parsing running services from logs. Logs :\n{logs}"); + tracing::info!("Parsing running services from logs. Logs :\n{logs}"); RunningServices::parse_from_logs(&logs) } @@ -83,7 +82,7 @@ impl TrackerContainer { pub fn stop(&mut self) { match &self.running { Some(container) => { - info!("Stopping docker tracker container: {} ...", self.name); + tracing::info!("Stopping docker tracker container: {} ...", self.name); Docker::stop(container).expect("Container should be stopped"); @@ -91,9 +90,9 @@ impl TrackerContainer { } None => { if Docker::is_container_running(&self.name) { - error!("Tracker container {} was started manually", self.name); + tracing::error!("Tracker container {} was started manually", self.name); } else { - info!("Docker tracker container is not running: {} ...", self.name); + tracing::info!("Docker tracker container is not running: {} ...", self.name); } } } @@ -106,9 +105,9 @@ impl TrackerContainer { /// Will panic if it can't remove the container. pub fn remove(&self) { if let Some(_running_container) = &self.running { - error!("Can't remove running container: {} ...", self.name); + tracing::error!("Can't remove running container: {} ...", self.name); } else { - info!("Removing docker tracker container: {} ...", self.name); + tracing::info!("Removing docker tracker container: {} ...", self.name); Docker::remove(&self.name).expect("Container should be removed"); } } diff --git a/src/console/clients/checker/app.rs b/src/console/clients/checker/app.rs index 3bafc2661..395f65df9 100644 --- a/src/console/clients/checker/app.rs +++ b/src/console/clients/checker/app.rs @@ -61,7 +61,6 @@ use std::sync::Arc; use anyhow::{Context, Result}; use clap::Parser; -use tracing::debug; use tracing::level_filters::LevelFilter; use super::config::Configuration; @@ -103,7 +102,7 @@ pub async fn run() -> Result> { fn tracing_stdout_init(filter: LevelFilter) { tracing_subscriber::fmt().with_max_level(filter).init(); - debug!("Logging initialized"); + tracing::debug!("Logging initialized"); } fn setup_config(args: Args) -> Result { diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index af6f10611..c2ba647b8 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -64,7 +64,6 @@ use aquatic_udp_protocol::{Response, TransactionId}; use clap::{Parser, Subcommand}; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; -use tracing::debug; use tracing::level_filters::LevelFilter; use url::Url; @@ -129,7 +128,7 @@ pub async fn run() -> anyhow::Result<()> { fn tracing_stdout_init(filter: LevelFilter) { tracing_subscriber::fmt().with_max_level(filter).init(); - debug!("Logging initialized"); + tracing::debug!("Logging initialized"); } async fn handle_announce(remote_addr: SocketAddr, info_hash: &TorrustInfoHash) -> Result { @@ -153,11 +152,11 @@ async fn handle_scrape(remote_addr: SocketAddr, info_hashes: &[TorrustInfoHash]) } fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { - debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); + tracing::debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); // Check if the address is a valid URL. If so, extract the host and port. let resolved_addr = if let Ok(url) = Url::parse(tracker_socket_addr_str) { - debug!("Tracker socket address URL: {url:?}"); + tracing::debug!("Tracker socket address URL: {url:?}"); let host = url .host_str() @@ -192,7 +191,7 @@ fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result = resolved_addr.to_socket_addrs()?.collect(); diff --git a/src/console/clients/udp/checker.rs b/src/console/clients/udp/checker.rs index 49f0ac41f..437af33e0 100644 --- a/src/console/clients/udp/checker.rs +++ b/src/console/clients/udp/checker.rs @@ -8,7 +8,6 @@ use aquatic_udp_protocol::{ PeerId, PeerKey, Port, Response, ScrapeRequest, TransactionId, }; use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; -use tracing::debug; use super::Error; use crate::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; @@ -57,7 +56,7 @@ impl Client { /// /// Will panic if it receives an unexpected response. pub async fn send_connection_request(&self, transaction_id: TransactionId) -> Result { - debug!("Sending connection request with transaction id: {transaction_id:#?}"); + tracing::debug!("Sending connection request with transaction id: {transaction_id:#?}"); let connect_request = ConnectRequest { transaction_id }; @@ -95,7 +94,7 @@ impl Client { connection_id: ConnectionId, info_hash: TorrustInfoHash, ) -> Result { - debug!("Sending announce request with transaction id: {transaction_id:#?}"); + tracing::debug!("Sending announce request with transaction id: {transaction_id:#?}"); let port = NonZeroU16::new( self.client @@ -150,7 +149,7 @@ impl Client { transaction_id: TransactionId, info_hashes: &[TorrustInfoHash], ) -> Result { - debug!("Sending scrape request with transaction id: {transaction_id:#?}"); + tracing::debug!("Sending scrape request with transaction id: {transaction_id:#?}"); let scrape_request = ScrapeRequest { connection_id, diff --git a/src/console/profiling.rs b/src/console/profiling.rs index 3e2925d9c..5fb507197 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -160,7 +160,6 @@ use std::env; use std::time::Duration; use tokio::time::sleep; -use tracing::info; use crate::{app, bootstrap}; @@ -189,10 +188,10 @@ pub async fn run() { tokio::select! { () = run_duration => { - info!("Torrust timed shutdown.."); + tracing::info!("Torrust timed shutdown.."); }, _ = tokio::signal::ctrl_c() => { - info!("Torrust shutting down via Ctrl+C ..."); + tracing::info!("Torrust shutting down via Ctrl+C ..."); // Await for all jobs to shutdown futures::future::join_all(jobs).await; } diff --git a/src/core/auth.rs b/src/core/auth.rs index 61ccbdb52..0243fceb4 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -50,7 +50,6 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; use torrust_tracker_located_error::{DynError, LocatedError}; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use tracing::debug; use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; use crate::CurrentClock; @@ -81,14 +80,14 @@ pub fn generate_key(lifetime: Option) -> PeerKey { .collect(); if let Some(lifetime) = lifetime { - debug!("Generated key: {}, valid for: {:?} seconds", random_id, lifetime); + tracing::debug!("Generated key: {}, valid for: {:?} seconds", random_id, lifetime); PeerKey { key: random_id.parse::().unwrap(), valid_until: Some(CurrentClock::now_add(&lifetime).unwrap()), } } else { - debug!("Generated key: {}, permanent", random_id); + tracing::debug!("Generated key: {}, permanent", random_id); PeerKey { key: random_id.parse::().unwrap(), diff --git a/src/core/databases/mysql.rs b/src/core/databases/mysql.rs index 3a06c4982..28a5f363b 100644 --- a/src/core/databases/mysql.rs +++ b/src/core/databases/mysql.rs @@ -8,7 +8,6 @@ use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MySqlConnectionManager; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::PersistentTorrents; -use tracing::debug; use super::driver::Driver; use super::{Database, Error}; @@ -158,7 +157,7 @@ impl Database for Mysql { let info_hash_str = info_hash.to_string(); - debug!("{}", info_hash_str); + tracing::debug!("{}", info_hash_str); Ok(conn.exec_drop(COMMAND, params! { info_hash_str, completed })?) } diff --git a/src/core/mod.rs b/src/core/mod.rs index a7ad66052..cbdd7bcbc 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -469,7 +469,6 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; -use tracing::debug; use self::auth::Key; use self::error::Error; @@ -656,9 +655,9 @@ impl Tracker { // we are actually handling authentication at the handlers level. So I would extract that // responsibility into another authentication service. - debug!("Before: {peer:?}"); + tracing::debug!("Before: {peer:?}"); peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); - debug!("After: {peer:?}"); + tracing::debug!("After: {peer:?}"); let stats = self.upsert_peer_and_get_stats(info_hash, peer); diff --git a/src/core/statistics.rs b/src/core/statistics.rs index bcafda17f..c9681d23c 100644 --- a/src/core/statistics.rs +++ b/src/core/statistics.rs @@ -25,7 +25,6 @@ use futures::FutureExt; use mockall::{automock, predicate::str}; use tokio::sync::mpsc::error::SendError; use tokio::sync::{mpsc, RwLock, RwLockReadGuard}; -use tracing::debug; const CHANNEL_BUFFER_SIZE: usize = 65_535; @@ -182,7 +181,7 @@ async fn event_handler(event: Event, stats_repository: &Repo) { } } - debug!("stats: {:?}", stats_repository.get_stats().await); + tracing::debug!("stats: {:?}", stats_repository.get_stats().await); } /// A trait to allow sending statistics events diff --git a/src/main.rs b/src/main.rs index ab2af65e2..e0b7bc4ab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,4 @@ use torrust_tracker::{app, bootstrap}; -use tracing::info; #[tokio::main] async fn main() { @@ -10,11 +9,11 @@ async fn main() { // handle the signals tokio::select! { _ = tokio::signal::ctrl_c() => { - info!("Torrust shutting down ..."); + tracing::info!("Torrust shutting down ..."); // Await for all jobs to shutdown futures::future::join_all(jobs).await; - info!("Torrust successfully shutdown."); + tracing::info!("Torrust successfully shutdown."); } } } diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 40c4d0779..9008d7ce6 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -32,7 +32,6 @@ use derive_more::Constructor; use futures::future::BoxFuture; use tokio::sync::oneshot::{Receiver, Sender}; use torrust_tracker_configuration::AccessTokens; -use tracing::{debug, error, info}; use super::routes::router; use crate::bootstrap::jobs::Started; @@ -123,11 +122,11 @@ impl ApiServer { let launcher = self.state.launcher; let task = tokio::spawn(async move { - debug!(target: API_LOG_TARGET, "Starting with launcher in spawned task ..."); + tracing::debug!(target: API_LOG_TARGET, "Starting with launcher in spawned task ..."); let _task = launcher.start(tracker, access_tokens, tx_start, rx_halt).await; - debug!(target: API_LOG_TARGET, "Started with launcher in spawned task"); + tracing::debug!(target: API_LOG_TARGET, "Started with launcher in spawned task"); launcher }); @@ -143,7 +142,7 @@ impl ApiServer { } Err(err) => { let msg = format!("Unable to start API server: {err}"); - error!("{}", msg); + tracing::error!("{}", msg); panic!("{}", msg); } }; @@ -233,7 +232,7 @@ impl Launcher { let tls = self.tls.clone(); let protocol = if tls.is_some() { "https" } else { "http" }; - info!(target: API_LOG_TARGET, "Starting on {protocol}://{}", address); + tracing::info!(target: API_LOG_TARGET, "Starting on {protocol}://{}", address); let running = Box::pin(async { match tls { @@ -254,7 +253,7 @@ impl Launcher { } }); - info!(target: API_LOG_TARGET, "{STARTED_ON} {protocol}://{}", address); + tracing::info!(target: API_LOG_TARGET, "{STARTED_ON} {protocol}://{}", address); tx_start .send(Started { address }) diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs index b2418c689..ebca504fd 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/src/servers/apis/v1/context/torrent/handlers.rs @@ -11,7 +11,6 @@ use serde::{de, Deserialize, Deserializer}; use thiserror::Error; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; -use tracing::debug; use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; use crate::core::services::torrent::{get_torrent_info, get_torrents, get_torrents_page}; @@ -77,7 +76,7 @@ pub struct QueryParams { /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent#list-torrents) /// for more information about this endpoint. pub async fn get_torrents_handler(State(tracker): State>, pagination: Query) -> Response { - debug!("pagination: {:?}", pagination); + tracing::debug!("pagination: {:?}", pagination); if pagination.0.info_hashes.is_empty() { torrent_list_response( diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index 89fbafe45..8a9b97306 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -18,7 +18,7 @@ use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; -use tracing::{debug, Level, Span}; +use tracing::{Level, Span}; use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; @@ -81,7 +81,7 @@ pub fn start( let handle = Handle::new(); - debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting service with graceful shutdown in a spawned task ..."); + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting service with graceful shutdown in a spawned task ..."); tokio::task::spawn(graceful_shutdown( handle.clone(), diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 4a6dccc6a..75888f6a4 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -7,7 +7,6 @@ use axum_server::Handle; use derive_more::Constructor; use futures::future::BoxFuture; use tokio::sync::oneshot::{Receiver, Sender}; -use tracing::info; use super::v1::routes::router; use crate::bootstrap::jobs::Started; @@ -57,7 +56,7 @@ impl Launcher { let tls = self.tls.clone(); let protocol = if tls.is_some() { "https" } else { "http" }; - info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{}", address); + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{}", address); let app = router(tracker, address); @@ -80,7 +79,7 @@ impl Launcher { } }); - info!(target: HTTP_TRACKER_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); tx_start .send(Started { address }) diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 0c1d2fdac..ee70b7841 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -14,7 +14,6 @@ use axum::extract::State; use axum::response::{IntoResponse, Response}; use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::peer; -use tracing::debug; use crate::core::auth::Key; use crate::core::{AnnounceData, Tracker}; @@ -36,7 +35,7 @@ pub async fn handle_without_key( ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { - debug!("http announce request: {:#?}", announce_request); + tracing::debug!("http announce request: {:#?}", announce_request); handle(&tracker, &announce_request, &client_ip_sources, None).await } @@ -50,7 +49,7 @@ pub async fn handle_with_key( ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { - debug!("http announce request: {:#?}", announce_request); + tracing::debug!("http announce request: {:#?}", announce_request); handle(&tracker, &announce_request, &client_ip_sources, Some(key)).await } diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index eb8875a58..ca4c85207 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -9,7 +9,6 @@ use std::sync::Arc; use axum::extract::State; use axum::response::{IntoResponse, Response}; -use tracing::debug; use crate::core::auth::Key; use crate::core::{ScrapeData, Tracker}; @@ -28,7 +27,7 @@ pub async fn handle_without_key( ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { - debug!("http scrape request: {:#?}", &scrape_request); + tracing::debug!("http scrape request: {:#?}", &scrape_request); handle(&tracker, &scrape_request, &client_ip_sources, None).await } @@ -44,7 +43,7 @@ pub async fn handle_with_key( ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { - debug!("http scrape request: {:#?}", &scrape_request); + tracing::debug!("http scrape request: {:#?}", &scrape_request); handle(&tracker, &scrape_request, &client_ip_sources, Some(key)).await } diff --git a/src/servers/registar.rs b/src/servers/registar.rs index 6058595ba..6b67188dc 100644 --- a/src/servers/registar.rs +++ b/src/servers/registar.rs @@ -7,7 +7,6 @@ use std::sync::Arc; use derive_more::Constructor; use tokio::sync::Mutex; use tokio::task::JoinHandle; -use tracing::debug; /// A [`ServiceHeathCheckResult`] is returned by a completed health check. pub type ServiceHeathCheckResult = Result; @@ -82,7 +81,7 @@ impl Registar { /// Inserts a listing into the registry. async fn insert(&self, rx: tokio::sync::oneshot::Receiver) { - debug!("Waiting for the started service to send registration data ..."); + tracing::debug!("Waiting for the started service to send registration data ..."); let service_registration = rx .await diff --git a/src/servers/signals.rs b/src/servers/signals.rs index 0a1a06312..367becff8 100644 --- a/src/servers/signals.rs +++ b/src/servers/signals.rs @@ -3,7 +3,6 @@ use std::time::Duration; use derive_more::Display; use tokio::time::sleep; -use tracing::info; /// This is the message that the "launcher" spawned task receives from the main /// application process to notify the service to shutdown. @@ -54,8 +53,8 @@ pub async fn shutdown_signal(rx_halt: tokio::sync::oneshot::Receiver) { }; tokio::select! { - signal = halt => { info!("Halt signal processed: {}", signal) }, - () = global_shutdown_signal() => { info!("Global shutdown signal processed") } + signal = halt => { tracing::info!("Halt signal processed: {}", signal) }, + () = global_shutdown_signal() => { tracing::info!("Global shutdown signal processed") } } } @@ -63,13 +62,13 @@ pub async fn shutdown_signal(rx_halt: tokio::sync::oneshot::Receiver) { pub async fn shutdown_signal_with_message(rx_halt: tokio::sync::oneshot::Receiver, message: String) { shutdown_signal(rx_halt).await; - info!("{message}"); + tracing::info!("{message}"); } pub async fn graceful_shutdown(handle: axum_server::Handle, rx_halt: tokio::sync::oneshot::Receiver, message: String) { shutdown_signal_with_message(rx_halt, message).await; - info!("Sending graceful shutdown signal"); + tracing::info!("Sending graceful shutdown signal"); handle.graceful_shutdown(Some(Duration::from_secs(90))); println!("!! shuting down in 90 seconds !!"); @@ -77,6 +76,6 @@ pub async fn graceful_shutdown(handle: axum_server::Handle, rx_halt: tokio::sync loop { sleep(Duration::from_secs(1)).await; - info!("remaining alive connections: {}", handle.connection_count()); + tracing::info!("remaining alive connections: {}", handle.connection_count()); } } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 1ef404ff0..34f786219 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -12,7 +12,6 @@ use aquatic_udp_protocol::{ }; use torrust_tracker_located_error::DynError; use torrust_tracker_primitives::info_hash::InfoHash; -use tracing::debug; use uuid::Uuid; use zerocopy::network_endian::I32; @@ -33,7 +32,7 @@ use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; /// /// It will return an `Error` response if the request is invalid. pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Tracker, local_addr: SocketAddr) -> Response { - debug!("Handling Packets: {udp_request:?}"); + tracing::debug!("Handling Packets: {udp_request:?}"); let start_time = Instant::now(); @@ -88,7 +87,7 @@ pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Tracker, lo /// /// If a error happens in the `handle_request` function, it will just return the `ServerError`. pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: &Tracker) -> Result { - debug!("Handling Request: {request:?} to: {remote_addr:?}"); + tracing::debug!("Handling Request: {request:?} to: {remote_addr:?}"); match request { Request::Connect(connect_request) => handle_connect(remote_addr, &connect_request, tracker).await, @@ -104,7 +103,7 @@ pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: /// /// This function does not ever return an error. pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, tracker: &Tracker) -> Result { - debug!("udp connect request: {:#?}", request); + tracing::debug!("udp connect request: {:#?}", request); let connection_cookie = make(&remote_addr); let connection_id = into_connection_id(&connection_cookie); @@ -114,7 +113,7 @@ pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, t connection_id, }; - debug!("udp connect response: {:#?}", response); + tracing::debug!("udp connect response: {:#?}", response); // send stats event match remote_addr { @@ -140,7 +139,7 @@ pub async fn handle_announce( announce_request: &AnnounceRequest, tracker: &Tracker, ) -> Result { - debug!("udp announce request: {:#?}", announce_request); + tracing::debug!("udp announce request: {:#?}", announce_request); // Authentication if tracker.requires_authentication() { @@ -197,7 +196,7 @@ pub async fn handle_announce( .collect(), }; - debug!("udp announce response: {:#?}", announce_response); + tracing::debug!("udp announce response: {:#?}", announce_response); Ok(Response::from(announce_response)) } else { @@ -224,7 +223,7 @@ pub async fn handle_announce( .collect(), }; - debug!("udp announce response: {:#?}", announce_response); + tracing::debug!("udp announce response: {:#?}", announce_response); Ok(Response::from(announce_response)) } @@ -237,7 +236,7 @@ pub async fn handle_announce( /// /// This function does not ever return an error. pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tracker: &Tracker) -> Result { - debug!("udp scrape request: {:#?}", request); + tracing::debug!("udp scrape request: {:#?}", request); // Convert from aquatic infohashes let mut info_hashes: Vec = vec![]; @@ -283,7 +282,7 @@ pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tra torrent_stats, }; - debug!("udp scrape response: {:#?}", response); + tracing::debug!("udp scrape response: {:#?}", response); Ok(Response::from(response)) } diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs index cf0566d67..b101a54e7 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/tests/servers/health_check_api/environment.rs @@ -8,7 +8,6 @@ use torrust_tracker::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TA use torrust_tracker::servers::registar::Registar; use torrust_tracker::servers::signals::{self, Halted}; use torrust_tracker_configuration::HealthCheckApi; -use tracing::debug; #[derive(Debug)] pub enum Error { @@ -49,21 +48,21 @@ impl Environment { let register = self.registar.entries(); - debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Spawning task to launch the service ..."); + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Spawning task to launch the service ..."); let server = tokio::spawn(async move { - debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting the server in a spawned task ..."); + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Starting the server in a spawned task ..."); server::start(self.state.bind_to, tx_start, rx_halt, register) .await .expect("it should start the health check service"); - debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Server started. Sending the binding {} ...", self.state.bind_to); + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Server started. Sending the binding {} ...", self.state.bind_to); self.state.bind_to }); - debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Waiting for spawning task to send the binding ..."); + tracing::debug!(target: HEALTH_CHECK_API_LOG_TARGET, "Waiting for spawning task to send the binding ..."); let binding = rx_start.await.expect("it should send service binding").address; From 3dc75d5873ee9ddd995a7aff7defab3a7e298fc6 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sat, 24 Aug 2024 17:41:34 +0200 Subject: [PATCH 0482/1297] tracing: init tracing-subscriber in intragration tests --- packages/test-helpers/src/configuration.rs | 2 +- tests/common/clock.rs | 6 + tests/common/logging.rs | 30 +++ tests/common/mod.rs | 1 + .../servers/api/v1/contract/authentication.rs | 22 ++ .../servers/api/v1/contract/configuration.rs | 8 + .../api/v1/contract/context/auth_key.rs | 72 ++++++ .../api/v1/contract/context/health_check.rs | 6 + .../servers/api/v1/contract/context/stats.rs | 10 + .../api/v1/contract/context/torrent.rs | 50 ++++ .../api/v1/contract/context/whitelist.rs | 50 ++++ tests/servers/health_check_api/contract.rs | 36 +++ tests/servers/http/v1/contract.rs | 226 +++++++++++++++++- tests/servers/udp/contract.rs | 28 +++ tests/servers/udp/environment.rs | 6 + 15 files changed, 551 insertions(+), 2 deletions(-) create mode 100644 tests/common/logging.rs diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 0c4029b69..dbd8eef9e 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -28,7 +28,7 @@ pub fn ephemeral() -> Configuration { let mut config = Configuration::default(); - config.logging.threshold = Threshold::Off; // Change to `debug` for tests debugging + config.logging.threshold = Threshold::Off; // It should always be off here, the tests manage their own logging. // Ephemeral socket address for API let api_port = 0u16; diff --git a/tests/common/clock.rs b/tests/common/clock.rs index 5d94bb83d..de3cc7c65 100644 --- a/tests/common/clock.rs +++ b/tests/common/clock.rs @@ -1,11 +1,17 @@ use std::time::Duration; use torrust_tracker_clock::clock::Time; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::CurrentClock; #[test] fn it_should_use_stopped_time_for_testing() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + assert_eq!(CurrentClock::dbg_clock_type(), "Stopped".to_owned()); let time = CurrentClock::now(); diff --git a/tests/common/logging.rs b/tests/common/logging.rs new file mode 100644 index 000000000..71be2ece7 --- /dev/null +++ b/tests/common/logging.rs @@ -0,0 +1,30 @@ +#![allow(clippy::doc_markdown)] +//! Logging for the Integration Tests +//! +//! Tests should start their own logging. +//! +//! To find tests that do not start their own logging: +//! +//! ´´´ sh +//! awk 'BEGIN{RS=""; FS="\n"} /#\[tokio::test\]\s*async\s+fn\s+\w+\s*\(\s*\)\s*\{[^}]*\}/ && !/#\[tokio::test\]\s*async\s+fn\s+\w+\s*\(\s*\)\s*\{[^}]*INIT\.call_once/' $(find . -name "*.rs") +//! ´´´ +//! + +use std::sync::Once; + +use tracing::level_filters::LevelFilter; + +#[allow(dead_code)] +pub static INIT: Once = Once::new(); + +#[allow(dead_code)] +pub fn tracing_stderr_init(filter: LevelFilter) { + let builder = tracing_subscriber::fmt() + .with_max_level(filter) + .with_ansi(true) + .with_writer(std::io::stderr); + + builder.pretty().with_file(true).init(); + + tracing::info!("Logging initialized"); +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 281c1fb9c..9589ccb1e 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,4 +1,5 @@ pub mod clock; pub mod fixtures; pub mod http; +pub mod logging; pub mod udp; diff --git a/tests/servers/api/v1/contract/authentication.rs b/tests/servers/api/v1/contract/authentication.rs index 49981dd02..5c5cd3ae0 100644 --- a/tests/servers/api/v1/contract/authentication.rs +++ b/tests/servers/api/v1/contract/authentication.rs @@ -1,12 +1,18 @@ use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; use crate::common::http::{Query, QueryParam}; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::v1::asserts::{assert_token_not_valid, assert_unauthorized}; use crate::servers::api::v1::client::Client; use crate::servers::api::Started; #[tokio::test] async fn should_authenticate_requests_by_using_a_token_query_param() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let token = env.get_connection_info().api_token.unwrap(); @@ -22,6 +28,10 @@ async fn should_authenticate_requests_by_using_a_token_query_param() { #[tokio::test] async fn should_not_authenticate_requests_when_the_token_is_missing() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(env.get_connection_info()) @@ -35,6 +45,10 @@ async fn should_not_authenticate_requests_when_the_token_is_missing() { #[tokio::test] async fn should_not_authenticate_requests_when_the_token_is_empty() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(env.get_connection_info()) @@ -48,6 +62,10 @@ async fn should_not_authenticate_requests_when_the_token_is_empty() { #[tokio::test] async fn should_not_authenticate_requests_when_the_token_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(env.get_connection_info()) @@ -61,6 +79,10 @@ async fn should_not_authenticate_requests_when_the_token_is_invalid() { #[tokio::test] async fn should_allow_the_token_query_param_to_be_at_any_position_in_the_url_query() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let token = env.get_connection_info().api_token.unwrap(); diff --git a/tests/servers/api/v1/contract/configuration.rs b/tests/servers/api/v1/contract/configuration.rs index 4220f62d2..be42f16ad 100644 --- a/tests/servers/api/v1/contract/configuration.rs +++ b/tests/servers/api/v1/contract/configuration.rs @@ -7,10 +7,18 @@ // use crate::common::app::setup_with_configuration; // use crate::servers::api::environment::stopped_environment; +use tracing::level_filters::LevelFilter; + +use crate::common::logging::{tracing_stderr_init, INIT}; + #[tokio::test] #[ignore] #[should_panic = "Could not receive bind_address."] async fn should_fail_with_ssl_enabled_and_bad_ssl_config() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // let tracker = setup_with_configuration(&Arc::new(configuration::ephemeral())); // let config = tracker.config.http_api.clone(); diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 41f421ca6..2792a513c 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -3,7 +3,9 @@ use std::time::Duration; use serde::Serialize; use torrust_tracker::core::auth::Key; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_auth_key_utf8, assert_failed_to_delete_key, assert_failed_to_generate_key, assert_failed_to_reload_keys, @@ -15,6 +17,10 @@ use crate::servers::api::{force_database_error, Started}; #[tokio::test] async fn should_allow_generating_a_new_random_auth_key() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(env.get_connection_info()) @@ -37,6 +43,10 @@ async fn should_allow_generating_a_new_random_auth_key() { #[tokio::test] async fn should_allow_uploading_a_preexisting_auth_key() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(env.get_connection_info()) @@ -59,6 +69,10 @@ async fn should_allow_uploading_a_preexisting_auth_key() { #[tokio::test] async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) @@ -84,6 +98,10 @@ async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() #[tokio::test] async fn should_fail_when_the_auth_key_cannot_be_generated() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; force_database_error(&env.tracker); @@ -102,6 +120,10 @@ async fn should_fail_when_the_auth_key_cannot_be_generated() { #[tokio::test] async fn should_allow_deleting_an_auth_key() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -129,6 +151,10 @@ async fn should_fail_generating_a_new_auth_key_when_the_provided_key_is_invalid( pub seconds_valid: u64, } + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_keys = [ @@ -166,6 +192,10 @@ async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid( pub seconds_valid: String, } + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_key_durations = [ @@ -193,6 +223,10 @@ async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid( #[tokio::test] async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_auth_keys = [ @@ -216,6 +250,10 @@ async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { #[tokio::test] async fn should_fail_when_the_auth_key_cannot_be_deleted() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -238,6 +276,10 @@ async fn should_fail_when_the_auth_key_cannot_be_deleted() { #[tokio::test] async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -273,6 +315,10 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { #[tokio::test] async fn should_allow_reloading_keys() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -290,6 +336,10 @@ async fn should_allow_reloading_keys() { #[tokio::test] async fn should_fail_when_keys_cannot_be_reloaded() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -309,6 +359,10 @@ async fn should_fail_when_keys_cannot_be_reloaded() { #[tokio::test] async fn should_not_allow_reloading_keys_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -336,7 +390,9 @@ mod deprecated_generate_key_endpoint { use torrust_tracker::core::auth::Key; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_auth_key_utf8, assert_failed_to_generate_key, assert_invalid_key_duration_param, assert_token_not_valid, @@ -347,6 +403,10 @@ mod deprecated_generate_key_endpoint { #[tokio::test] async fn should_allow_generating_a_new_auth_key() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -366,6 +426,10 @@ mod deprecated_generate_key_endpoint { #[tokio::test] async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; @@ -387,6 +451,10 @@ mod deprecated_generate_key_endpoint { #[tokio::test] async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_key_durations = [ @@ -408,6 +476,10 @@ mod deprecated_generate_key_endpoint { #[tokio::test] async fn should_fail_when_the_auth_key_cannot_be_generated() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; force_database_error(&env.tracker); diff --git a/tests/servers/api/v1/contract/context/health_check.rs b/tests/servers/api/v1/contract/context/health_check.rs index d8dc3c030..af46a5abe 100644 --- a/tests/servers/api/v1/contract/context/health_check.rs +++ b/tests/servers/api/v1/contract/context/health_check.rs @@ -1,11 +1,17 @@ use torrust_tracker::servers::apis::v1::context::health_check::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::v1::client::get; use crate::servers::api::Started; #[tokio::test] async fn health_check_endpoint_should_return_status_ok_if_api_is_running() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let url = format!("http://{}/api/health_check", env.get_connection_info().bind_address); diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index c4c992484..a034a7778 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -4,7 +4,9 @@ use torrust_tracker::servers::apis::v1::context::stats::resources::Stats; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{assert_stats, assert_token_not_valid, assert_unauthorized}; use crate::servers::api::v1::client::Client; @@ -12,6 +14,10 @@ use crate::servers::api::Started; #[tokio::test] async fn should_allow_getting_tracker_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; env.add_torrent_peer( @@ -49,6 +55,10 @@ async fn should_allow_getting_tracker_statistics() { #[tokio::test] async fn should_not_allow_getting_tracker_statistics_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index 7ef35e729..f5e930be3 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -5,8 +5,10 @@ use torrust_tracker::servers::apis::v1::context::torrent::resources::torrent::{s use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; use crate::common::http::{Query, QueryParam}; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_bad_request, assert_invalid_infohash_param, assert_not_found, assert_token_not_valid, assert_torrent_info, @@ -20,6 +22,10 @@ use crate::servers::api::Started; #[tokio::test] async fn should_allow_getting_all_torrents() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); @@ -44,6 +50,10 @@ async fn should_allow_getting_all_torrents() { #[tokio::test] async fn should_allow_limiting_the_torrents_in_the_result() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; // torrents are ordered alphabetically by infohashes @@ -73,6 +83,10 @@ async fn should_allow_limiting_the_torrents_in_the_result() { #[tokio::test] async fn should_allow_the_torrents_result_pagination() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; // torrents are ordered alphabetically by infohashes @@ -102,6 +116,10 @@ async fn should_allow_the_torrents_result_pagination() { #[tokio::test] async fn should_allow_getting_a_list_of_torrents_providing_infohashes() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 @@ -144,6 +162,10 @@ async fn should_allow_getting_a_list_of_torrents_providing_infohashes() { #[tokio::test] async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_parsed() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_offsets = [" ", "-1", "1.1", "INVALID OFFSET"]; @@ -161,6 +183,10 @@ async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_ #[tokio::test] async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_parsed() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_limits = [" ", "-1", "1.1", "INVALID LIMIT"]; @@ -178,6 +204,10 @@ async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_p #[tokio::test] async fn should_fail_getting_torrents_when_the_info_hash_parameter_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_info_hashes = [" ", "-1", "1.1", "INVALID INFO_HASH"]; @@ -199,6 +229,10 @@ async fn should_fail_getting_torrents_when_the_info_hash_parameter_is_invalid() #[tokio::test] async fn should_not_allow_getting_torrents_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) @@ -218,6 +252,10 @@ async fn should_not_allow_getting_torrents_for_unauthenticated_users() { #[tokio::test] async fn should_allow_getting_a_torrent_info() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); @@ -247,6 +285,10 @@ async fn should_allow_getting_a_torrent_info() { #[tokio::test] async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exist() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); @@ -262,6 +304,10 @@ async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exis #[tokio::test] async fn should_fail_getting_a_torrent_info_when_the_provided_infohash_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; for invalid_infohash in &invalid_infohashes_returning_bad_request() { @@ -281,6 +327,10 @@ async fn should_fail_getting_a_torrent_info_when_the_provided_infohash_is_invali #[tokio::test] async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index 29064ec9e..b30a7dbf8 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -2,7 +2,9 @@ use std::str::FromStr; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_failed_to_reload_whitelist, assert_failed_to_remove_torrent_from_whitelist, assert_failed_to_whitelist_torrent, @@ -16,6 +18,10 @@ use crate::servers::api::{force_database_error, Started}; #[tokio::test] async fn should_allow_whitelisting_a_torrent() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -34,6 +40,10 @@ async fn should_allow_whitelisting_a_torrent() { #[tokio::test] async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -51,6 +61,10 @@ async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() #[tokio::test] async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -72,6 +86,10 @@ async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { #[tokio::test] async fn should_fail_when_the_torrent_cannot_be_whitelisted() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -87,6 +105,10 @@ async fn should_fail_when_the_torrent_cannot_be_whitelisted() { #[tokio::test] async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; for invalid_infohash in &invalid_infohashes_returning_bad_request() { @@ -110,6 +132,10 @@ async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invali #[tokio::test] async fn should_allow_removing_a_torrent_from_the_whitelist() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -128,6 +154,10 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { #[tokio::test] async fn should_not_fail_trying_to_remove_a_non_whitelisted_torrent_from_the_whitelist() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let non_whitelisted_torrent_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -143,6 +173,10 @@ async fn should_not_fail_trying_to_remove_a_non_whitelisted_torrent_from_the_whi #[tokio::test] async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_infohash_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; for invalid_infohash in &invalid_infohashes_returning_bad_request() { @@ -166,6 +200,10 @@ async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_inf #[tokio::test] async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -185,6 +223,10 @@ async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { #[tokio::test] async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthenticated_users() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -209,6 +251,10 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica #[tokio::test] async fn should_allow_reload_the_whitelist_from_the_database() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -234,6 +280,10 @@ async fn should_allow_reload_the_whitelist_from_the_database() { #[tokio::test] async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index 3c3c13151..d40899f98 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -1,12 +1,18 @@ use torrust_tracker::servers::health_check_api::resources::{Report, Status}; use torrust_tracker::servers::registar::Registar; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::Started; #[tokio::test] async fn health_check_endpoint_should_return_status_ok_when_there_is_no_services_registered() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = configuration::ephemeral_with_no_services(); let env = Started::new(&configuration.health_check_api.into(), Registar::default()).await; @@ -31,13 +37,19 @@ mod api { use torrust_tracker::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::api; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::Started; #[tokio::test] pub(crate) async fn it_should_return_good_health_for_api_service() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = Arc::new(configuration::ephemeral()); let service = api::Started::new(&configuration).await; @@ -83,6 +95,10 @@ mod api { #[tokio::test] pub(crate) async fn it_should_return_error_when_api_service_was_stopped_after_registration() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = Arc::new(configuration::ephemeral()); let service = api::Started::new(&configuration).await; @@ -136,13 +152,19 @@ mod http { use torrust_tracker::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::Started; use crate::servers::http; #[tokio::test] pub(crate) async fn it_should_return_good_health_for_http_service() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = Arc::new(configuration::ephemeral()); let service = http::Started::new(&configuration).await; @@ -187,6 +209,10 @@ mod http { #[tokio::test] pub(crate) async fn it_should_return_error_when_http_service_was_stopped_after_registration() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = Arc::new(configuration::ephemeral()); let service = http::Started::new(&configuration).await; @@ -240,13 +266,19 @@ mod udp { use torrust_tracker::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::Started; use crate::servers::udp; #[tokio::test] pub(crate) async fn it_should_return_good_health_for_udp_service() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = Arc::new(configuration::ephemeral()); let service = udp::Started::new(&configuration).await; @@ -288,6 +320,10 @@ mod udp { #[tokio::test] pub(crate) async fn it_should_return_error_when_udp_service_was_stopped_after_registration() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let configuration = Arc::new(configuration::ephemeral()); let service = udp::Started::new(&configuration).await; diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index edc06fb07..f74b4717b 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -13,12 +13,18 @@ mod for_all_config_modes { use torrust_tracker::servers::http::v1::handlers::health_check::{Report, Status}; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::client::Client; use crate::servers::http::Started; #[tokio::test] async fn health_check_endpoint_should_return_ok_if_the_http_tracker_is_running() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; let response = Client::new(*env.bind_address()).health_check().await; @@ -32,7 +38,9 @@ mod for_all_config_modes { mod and_running_on_reverse_proxy { use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::assert_could_not_find_remote_address_on_x_forwarded_for_header_error_response; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; @@ -40,6 +48,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_http_request_does_not_include_the_xff_http_request_header() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // If the tracker is running behind a reverse proxy, the peer IP is the // right most IP in the `X-Forwarded-For` HTTP header, which is the IP of the proxy's client. @@ -56,6 +68,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_xff_http_request_header_contains_an_invalid_ip() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; let params = QueryBuilder::default().query().params(); @@ -93,8 +109,10 @@ mod for_all_config_modes { use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; use crate::common::fixtures::invalid_info_hashes; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::{ assert_announce_response, assert_bad_announce_request_error_response, assert_cannot_parse_query_param_error_response, assert_cannot_parse_query_params_error_response, assert_compact_announce_response, assert_empty_announce_response, @@ -107,12 +125,20 @@ mod for_all_config_modes { #[tokio::test] async fn it_should_start_and_stop() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; env.stop().await; } #[tokio::test] async fn should_respond_if_only_the_mandatory_fields_are_provided() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -128,6 +154,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_url_query_component_is_empty() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(*env.bind_address()).get("announce").await; @@ -139,6 +169,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_url_query_parameters_are_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let invalid_query_param = "a=b=c"; @@ -154,6 +188,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_a_mandatory_field_is_missing() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; // Without `info_hash` param @@ -191,6 +229,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -208,6 +250,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_not_fail_when_the_peer_address_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // AnnounceQuery does not even contain the `peer_addr` // The peer IP is obtained in two ways: // 1. If tracker is NOT running `on_reverse_proxy` from the remote client IP. @@ -228,6 +274,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_downloaded_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -247,6 +297,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_uploaded_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -266,6 +320,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_peer_id_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -292,6 +350,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_port_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -311,6 +373,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_left_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -330,6 +396,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_event_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -357,6 +427,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_compact_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -376,6 +450,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_no_peers_if_the_announced_peer_is_the_first_one() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let response = Client::new(*env.bind_address()) @@ -405,6 +483,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_list_of_previously_announced_peers() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -445,6 +527,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_list_of_previously_announced_peers_including_peers_using_ipv4_and_ipv6() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -497,6 +583,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_consider_two_peers_to_be_the_same_when_they_have_the_same_peer_id_even_if_the_ip_is_different() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -521,6 +611,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_compact_response() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // Tracker Returns Compact Peer Lists // https://www.bittorrent.org/beps/bep_0023.html @@ -560,6 +654,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_not_return_the_compact_response_by_default() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // code-review: the HTTP tracker does not return the compact response by default if the "compact" // param is not provided in the announce URL. The BEP 23 suggest to do so. @@ -599,6 +697,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp4_connections_handled_in_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; Client::new(*env.bind_address()) @@ -616,6 +718,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp6_connections_handled_in_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) .await .is_err() @@ -640,6 +746,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_not_increase_the_number_of_tcp6_connections_handled_if_the_client_is_not_using_an_ipv6_ip() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // The tracker ignores the peer address in the request param. It uses the client remote ip address. let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -663,6 +773,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp4_announce_requests_handled_in_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; Client::new(*env.bind_address()) @@ -680,6 +794,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp6_announce_requests_handled_in_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) .await .is_err() @@ -704,6 +822,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_not_increase_the_number_of_tcp6_announce_requests_handled_if_the_client_is_not_using_an_ipv6_ip() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // The tracker ignores the peer address in the request param. It uses the client remote ip address. let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -727,6 +849,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_assign_to_the_peer_ip_the_remote_client_ip_instead_of_the_peer_address_in_the_request_param() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -756,6 +882,10 @@ mod for_all_config_modes { #[tokio::test] async fn when_the_client_ip_is_a_loopback_ipv4_it_should_assign_to_the_peer_ip_the_external_ip_in_the_tracker_configuration( ) { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + /* We assume that both the client and tracker share the same public IP. client <-> tracker <-> Internet @@ -792,6 +922,10 @@ mod for_all_config_modes { #[tokio::test] async fn when_the_client_ip_is_a_loopback_ipv6_it_should_assign_to_the_peer_ip_the_external_ip_in_the_tracker_configuration( ) { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + /* We assume that both the client and tracker share the same public IP. client <-> tracker <-> Internet @@ -832,6 +966,10 @@ mod for_all_config_modes { #[tokio::test] async fn when_the_tracker_is_behind_a_reverse_proxy_it_should_assign_to_the_peer_ip_the_ip_in_the_x_forwarded_for_http_header( ) { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + /* client <-> http proxy <-> tracker <-> Internet ip: header: config: peer addr: @@ -885,8 +1023,10 @@ mod for_all_config_modes { use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; use crate::common::fixtures::invalid_info_hashes; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::{ assert_cannot_parse_query_params_error_response, assert_missing_query_params_for_scrape_request_error_response, assert_scrape_response, @@ -896,9 +1036,13 @@ mod for_all_config_modes { use crate::servers::http::responses::scrape::{self, File, ResponseBuilder}; use crate::servers::http::{requests, Started}; - //#[tokio::test] + #[tokio::test] #[allow(dead_code)] async fn should_fail_when_the_request_is_empty() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let response = Client::new(*env.bind_address()).get("scrape").await; @@ -909,6 +1053,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let mut params = QueryBuilder::default().query().params(); @@ -926,6 +1074,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_file_with_the_incomplete_peer_when_there_is_one_peer_with_bytes_pending_to_download() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -964,6 +1116,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_file_with_the_complete_peer_when_there_is_one_peer_with_no_bytes_pending_to_download() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1002,6 +1158,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_a_file_with_zeroed_values_when_there_are_no_peers() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1021,6 +1181,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_accept_multiple_infohashes() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash1 = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1047,6 +1211,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_ot_tcp4_scrape_requests_handled_in_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_public().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1070,6 +1238,10 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_ot_tcp6_scrape_requests_handled_in_statistics() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) .await .is_err() @@ -1107,7 +1279,9 @@ mod configured_as_whitelisted { use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::{assert_is_announce_response, assert_torrent_not_in_whitelist_error_response}; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; @@ -1115,6 +1289,10 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_fail_if_the_torrent_is_not_in_the_whitelist() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_listed().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1130,6 +1308,10 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_allow_announcing_a_whitelisted_torrent() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_listed().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1156,7 +1338,9 @@ mod configured_as_whitelisted { use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::assert_scrape_response; use crate::servers::http::client::Client; use crate::servers::http::responses::scrape::{File, ResponseBuilder}; @@ -1164,6 +1348,10 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_return_the_zeroed_file_when_the_requested_file_is_not_whitelisted() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_listed().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1193,6 +1381,10 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_return_the_file_stats_when_the_requested_file_is_whitelisted() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_listed().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1245,7 +1437,9 @@ mod configured_as_private { use torrust_tracker::core::auth::Key; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::{assert_authentication_error_response, assert_is_announce_response}; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; @@ -1253,6 +1447,10 @@ mod configured_as_private { #[tokio::test] async fn should_respond_to_authenticated_peers() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; let expiring_key = env.tracker.generate_auth_key(Some(Duration::from_secs(60))).await.unwrap(); @@ -1268,6 +1466,10 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_peer_has_not_provided_the_authentication_key() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1283,6 +1485,10 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; let invalid_key = "INVALID_KEY"; @@ -1298,6 +1504,10 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_peer_cannot_be_authenticated_with_the_provided_key() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; // The tracker does not have this key @@ -1323,7 +1533,9 @@ mod configured_as_private { use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::http::asserts::{assert_authentication_error_response, assert_scrape_response}; use crate::servers::http::client::Client; use crate::servers::http::responses::scrape::{File, ResponseBuilder}; @@ -1331,6 +1543,10 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; let invalid_key = "INVALID_KEY"; @@ -1346,6 +1562,10 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_zeroed_file_when_the_client_is_not_authenticated() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); @@ -1375,6 +1595,10 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_real_file_stats_when_the_client_is_authenticated() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral_private().into()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index e37ef7bf0..91f4c4e06 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -10,7 +10,9 @@ use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient use torrust_tracker::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; +use tracing::level_filters::LevelFilter; +use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::udp::asserts::is_error_response; use crate::servers::udp::Started; @@ -39,6 +41,10 @@ async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrac #[tokio::test] async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_request() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { @@ -68,12 +74,18 @@ mod receiving_a_connection_request { use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::udp::asserts::is_connect_response; use crate::servers::udp::Started; #[tokio::test] async fn should_return_a_connect_response() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { @@ -111,7 +123,9 @@ mod receiving_an_announce_request { use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::udp::asserts::is_ipv4_announce_response; use crate::servers::udp::contract::send_connection_request; use crate::servers::udp::Started; @@ -152,6 +166,10 @@ mod receiving_an_announce_request { #[tokio::test] async fn should_return_an_announce_response() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { @@ -170,6 +188,10 @@ mod receiving_an_announce_request { #[tokio::test] async fn should_return_many_announce_response() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { @@ -195,13 +217,19 @@ mod receiving_an_scrape_request { use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::udp::asserts::is_scrape_response; use crate::servers::udp::contract::send_connection_request; use crate::servers::udp::Started; #[tokio::test] async fn should_return_a_scrape_response() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index cfc4390c9..30f257d1c 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -90,11 +90,17 @@ mod tests { use tokio::time::sleep; use torrust_tracker_test_helpers::configuration; + use tracing::level_filters::LevelFilter; + use crate::common::logging::{tracing_stderr_init, INIT}; use crate::servers::udp::Started; #[tokio::test] async fn it_should_make_and_stop_udp_server() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + let env = Started::new(&configuration::ephemeral().into()).await; sleep(Duration::from_secs(1)).await; env.stop().await; From 14e672ec35bfd627d1829bec70a6643f417797e3 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Sun, 25 Aug 2024 10:08:51 +0200 Subject: [PATCH 0483/1297] tracing: add spans to many functions --- src/app.rs | 2 ++ src/bootstrap/app.rs | 6 ++++ src/bootstrap/jobs/health_check_api.rs | 3 ++ src/bootstrap/jobs/http_tracker.rs | 4 +++ src/bootstrap/jobs/mod.rs | 2 ++ src/bootstrap/jobs/torrent_cleanup.rs | 2 ++ src/bootstrap/jobs/tracker_apis.rs | 4 +++ src/bootstrap/jobs/udp_tracker.rs | 3 ++ src/servers/apis/routes.rs | 3 +- src/servers/apis/server.rs | 42 +++++++++++++++++++----- src/servers/health_check_api/handlers.rs | 2 ++ src/servers/health_check_api/server.rs | 3 +- src/servers/http/server.rs | 2 ++ src/servers/http/v1/routes.rs | 3 +- src/servers/signals.rs | 15 ++++++--- src/servers/udp/handlers.rs | 22 ++++++------- src/servers/udp/server/bound_socket.rs | 2 +- src/servers/udp/server/launcher.rs | 14 +++++--- src/servers/udp/server/mod.rs | 19 ++++++++--- src/servers/udp/server/processor.rs | 38 ++++++++++++--------- src/servers/udp/server/spawner.rs | 4 ++- src/servers/udp/server/states.rs | 22 ++++++++----- tests/servers/api/environment.rs | 14 +++++--- tests/servers/http/v1/contract.rs | 4 +++ tests/servers/udp/environment.rs | 12 +++++-- 25 files changed, 176 insertions(+), 71 deletions(-) diff --git a/src/app.rs b/src/app.rs index f96ac399f..06fea4d2e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -25,6 +25,7 @@ use std::sync::Arc; use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; +use tracing::instrument; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; use crate::servers::registar::Registar; @@ -36,6 +37,7 @@ use crate::{core, servers}; /// /// - Can't retrieve tracker keys from database. /// - Can't load whitelist from database. +#[instrument(skip(config, tracker))] pub async fn start(config: &Configuration, tracker: Arc) -> Vec> { if config.http_api.is_none() && (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 8b0acabc8..7c0cf45ac 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -16,6 +16,7 @@ use std::sync::Arc; use torrust_tracker_clock::static_time; use torrust_tracker_configuration::validator::Validator; use torrust_tracker_configuration::Configuration; +use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; @@ -29,6 +30,7 @@ use crate::shared::crypto::ephemeral_instance_keys; /// /// Setup can file if the configuration is invalid. #[must_use] +#[instrument(skip())] pub fn setup() -> (Configuration, Arc) { let configuration = initialize_configuration(); @@ -47,6 +49,7 @@ pub fn setup() -> (Configuration, Arc) { /// /// The configuration may be obtained from the environment (via config file or env vars). #[must_use] +#[instrument(skip())] pub fn initialize_with_configuration(configuration: &Configuration) -> Arc { initialize_static(); initialize_logging(configuration); @@ -59,6 +62,7 @@ pub fn initialize_with_configuration(configuration: &Configuration) -> Arc Tracker { tracker_factory(config) } @@ -79,6 +84,7 @@ pub fn initialize_tracker(config: &Configuration) -> Tracker { /// It initializes the log threshold, format and channel. /// /// See [the logging setup](crate::bootstrap::logging::setup) for more info about logging. +#[instrument(skip(config))] pub fn initialize_logging(config: &Configuration) { bootstrap::logging::setup(config); } diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index d306b2be9..b6250efcc 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -17,6 +17,7 @@ use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_tracker_configuration::HealthCheckApi; +use tracing::instrument; use super::Started; use crate::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; @@ -34,6 +35,8 @@ use crate::servers::signals::Halted; /// # Panics /// /// It would panic if unable to send the `ApiServerJobStarted` notice. +#[allow(clippy::async_yields_async)] +#[instrument(skip(config, register))] pub async fn start_job(config: &HealthCheckApi, register: ServiceRegistry) -> JoinHandle<()> { let bind_addr = config.bind_address; diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 745f564b1..c55723bc6 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -16,6 +16,7 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; use torrust_tracker_configuration::HttpTracker; +use tracing::instrument; use super::make_rust_tls; use crate::core; @@ -32,6 +33,7 @@ use crate::servers::registar::ServiceRegistrationForm; /// /// It would panic if the `config::HttpTracker` struct would contain inappropriate values. /// +#[instrument(skip(config, tracker, form))] pub async fn start_job( config: &HttpTracker, tracker: Arc, @@ -49,6 +51,8 @@ pub async fn start_job( } } +#[allow(clippy::async_yields_async)] +#[instrument(skip(socket, tls, tracker, form))] async fn start_v1( socket: SocketAddr, tls: Option, diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 6534270fa..6e18ec3ba 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -20,6 +20,7 @@ pub struct Started { pub address: std::net::SocketAddr, } +#[instrument(skip(opt_tsl_config))] pub async fn make_rust_tls(opt_tsl_config: &Option) -> Option> { match opt_tsl_config { Some(tsl_config) => { @@ -89,6 +90,7 @@ use axum_server::tls_rustls::RustlsConfig; use thiserror::Error; use torrust_tracker_configuration::TslConfig; use torrust_tracker_located_error::{DynError, LocatedError}; +use tracing::instrument; /// Error returned by the Bootstrap Process. #[derive(Error, Debug)] diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index ee02a4d6d..6abb4f26b 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -15,6 +15,7 @@ use std::sync::Arc; use chrono::Utc; use tokio::task::JoinHandle; use torrust_tracker_configuration::Core; +use tracing::instrument; use crate::core; @@ -24,6 +25,7 @@ use crate::core; /// /// Refer to [`torrust-tracker-configuration documentation`](https://docs.rs/torrust-tracker-configuration) for more info about that option. #[must_use] +#[instrument(skip(config, tracker))] pub fn start_job(config: &Core, tracker: &Arc) -> JoinHandle<()> { let weak_tracker = std::sync::Arc::downgrade(tracker); let interval = config.inactive_peer_cleanup_interval; diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index ca91fbc83..35b13b7ce 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -26,6 +26,7 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; use torrust_tracker_configuration::{AccessTokens, HttpApi}; +use tracing::instrument; use super::make_rust_tls; use crate::core; @@ -53,6 +54,7 @@ pub struct ApiServerJobStarted(); /// It would panic if unable to send the `ApiServerJobStarted` notice. /// /// +#[instrument(skip(config, tracker, form))] pub async fn start_job( config: &HttpApi, tracker: Arc, @@ -72,6 +74,8 @@ pub async fn start_job( } } +#[allow(clippy::async_yields_async)] +#[instrument(skip(socket, tls, tracker, form, access_tokens))] async fn start_v1( socket: SocketAddr, tls: Option, diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 407cfbbfa..ca503aa29 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -10,6 +10,7 @@ use std::sync::Arc; use tokio::task::JoinHandle; use torrust_tracker_configuration::UdpTracker; +use tracing::instrument; use crate::core; use crate::servers::registar::ServiceRegistrationForm; @@ -27,6 +28,8 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// It will panic if it is unable to start the UDP service. /// It will panic if the task did not finish successfully. #[must_use] +#[allow(clippy::async_yields_async)] +#[instrument(skip(config, tracker, form))] pub async fn start_job(config: &UdpTracker, tracker: Arc, form: ServiceRegistrationForm) -> JoinHandle<()> { let bind_to = config.bind_address; diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 4901d760d..327cab0c5 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -21,7 +21,7 @@ use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; -use tracing::{Level, Span}; +use tracing::{instrument, Level, Span}; use super::v1; use super::v1::context::health_check::handlers::health_check_handler; @@ -31,6 +31,7 @@ use crate::servers::apis::API_LOG_TARGET; /// Add all API routes to the router. #[allow(clippy::needless_pass_by_value)] +#[instrument(skip(tracker, access_tokens))] pub fn router(tracker: Arc, access_tokens: Arc) -> Router { let router = Router::new(); diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 9008d7ce6..31220f497 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -28,10 +28,13 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; +use derive_more::derive::Display; use derive_more::Constructor; use futures::future::BoxFuture; +use thiserror::Error; use tokio::sync::oneshot::{Receiver, Sender}; use torrust_tracker_configuration::AccessTokens; +use tracing::{instrument, Level}; use super::routes::router; use crate::bootstrap::jobs::Started; @@ -43,9 +46,10 @@ use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, Servi use crate::servers::signals::{graceful_shutdown, Halted}; /// Errors that can occur when starting or stopping the API server. -#[derive(Debug)] +#[derive(Debug, Error)] pub enum Error { - Error(String), + #[error("Error when starting or stopping the API server")] + FailedToStartOrStop(String), } /// An alias for the `ApiServer` struct with the `Stopped` state. @@ -62,18 +66,26 @@ pub type RunningApiServer = ApiServer; /// It's a state machine that can be in one of two /// states: `Stopped` or `Running`. #[allow(clippy::module_name_repetitions)] -pub struct ApiServer { +#[derive(Debug, Display)] +pub struct ApiServer +where + S: std::fmt::Debug + std::fmt::Display, +{ pub state: S, } /// The `Stopped` state of the `ApiServer` struct. +#[derive(Debug, Display)] +#[display("Stopped: {launcher}")] pub struct Stopped { launcher: Launcher, } /// The `Running` state of the `ApiServer` struct. +#[derive(Debug, Display)] +#[display("Running (with local address): {local_addr}")] pub struct Running { - pub binding: SocketAddr, + pub local_addr: SocketAddr, pub halt_task: tokio::sync::oneshot::Sender, pub task: tokio::task::JoinHandle, } @@ -81,12 +93,12 @@ pub struct Running { impl Running { #[must_use] pub fn new( - binding: SocketAddr, + local_addr: SocketAddr, halt_task: tokio::sync::oneshot::Sender, task: tokio::task::JoinHandle, ) -> Self { Self { - binding, + local_addr, halt_task, task, } @@ -110,6 +122,7 @@ impl ApiServer { /// # Panics /// /// It would panic if the bound socket address cannot be sent back to this starter. + #[instrument(skip(self, tracker, form, access_tokens), err, ret(Display, level = Level::INFO))] pub async fn start( self, tracker: Arc, @@ -157,13 +170,14 @@ impl ApiServer { /// # Errors /// /// It would return an error if the channel for the task killer signal was closed. + #[instrument(skip(self), err, ret(Display, level = Level::INFO))] pub async fn stop(self) -> Result, Error> { self.state .halt_task .send(Halted::Normal) - .map_err(|_| Error::Error("Task killer channel was closed.".to_string()))?; + .map_err(|_| Error::FailedToStartOrStop("Task killer channel was closed.".to_string()))?; - let launcher = self.state.task.await.map_err(|e| Error::Error(e.to_string()))?; + let launcher = self.state.task.await.map_err(|e| Error::FailedToStartOrStop(e.to_string()))?; Ok(ApiServer { state: Stopped { launcher }, @@ -178,6 +192,7 @@ impl ApiServer { /// This function will return an error if unable to connect. /// Or if there request returns an error code. #[must_use] +#[instrument(skip())] pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { let url = format!("http://{binding}/api/health_check"); // DevSkim: ignore DS137138 @@ -199,6 +214,16 @@ pub struct Launcher { tls: Option, } +impl std::fmt::Display for Launcher { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.tls.is_some() { + write!(f, "(with socket): {}, using TLS", self.bind_to,) + } else { + write!(f, "(with socket): {}, without TLS", self.bind_to,) + } + } +} + impl Launcher { /// Starts the API server with graceful shutdown. /// @@ -210,6 +235,7 @@ impl Launcher { /// /// Will panic if unable to bind to the socket, or unable to get the address of the bound socket. /// Will also panic if unable to send message regarding the bound socket address. + #[instrument(skip(self, tracker, access_tokens, tx_start, rx_halt))] pub fn start( &self, tracker: Arc, diff --git a/src/servers/health_check_api/handlers.rs b/src/servers/health_check_api/handlers.rs index 944e84a1d..fe65e996b 100644 --- a/src/servers/health_check_api/handlers.rs +++ b/src/servers/health_check_api/handlers.rs @@ -2,6 +2,7 @@ use std::collections::VecDeque; use axum::extract::State; use axum::Json; +use tracing::{instrument, Level}; use super::resources::{CheckReport, Report}; use super::responses; @@ -11,6 +12,7 @@ use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, Servi /// /// Creates a vector [`CheckReport`] from the input set of [`CheckJob`], and then builds a report from the results. /// +#[instrument(skip(register), ret(level = Level::DEBUG))] pub(crate) async fn health_check_handler(State(register): State) -> Json { #[allow(unused_assignments)] let mut checks: VecDeque = VecDeque::new(); diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index 8a9b97306..df4b1cf69 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -18,7 +18,7 @@ use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; -use tracing::{Level, Span}; +use tracing::{instrument, Level, Span}; use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; @@ -31,6 +31,7 @@ use crate::servers::signals::{graceful_shutdown, Halted}; /// # Panics /// /// Will panic if binding to the socket address fails. +#[instrument(skip(bind_to, tx, rx_halt, register))] pub fn start( bind_to: SocketAddr, tx: Sender, diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 75888f6a4..560d91681 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -7,6 +7,7 @@ use axum_server::Handle; use derive_more::Constructor; use futures::future::BoxFuture; use tokio::sync::oneshot::{Receiver, Sender}; +use tracing::instrument; use super::v1::routes::router; use crate::bootstrap::jobs::Started; @@ -41,6 +42,7 @@ pub struct Launcher { } impl Launcher { + #[instrument(skip(self, tracker, tx_start, rx_halt))] fn start(&self, tracker: Arc, tx_start: Sender, rx_halt: Receiver) -> BoxFuture<'static, ()> { let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index c24797c4a..16e39b61b 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -17,7 +17,7 @@ use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; -use tracing::{Level, Span}; +use tracing::{instrument, Level, Span}; use super::handlers::{announce, health_check, scrape}; use crate::core::Tracker; @@ -28,6 +28,7 @@ use crate::servers::http::HTTP_TRACKER_LOG_TARGET; /// > **NOTICE**: it's added a layer to get the client IP from the connection /// > info. The tracker could use the connection info to get the client IP. #[allow(clippy::needless_pass_by_value)] +#[instrument(skip(tracker, server_socket_addr))] pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { Router::new() // Health check diff --git a/src/servers/signals.rs b/src/servers/signals.rs index 367becff8..b83dd5213 100644 --- a/src/servers/signals.rs +++ b/src/servers/signals.rs @@ -3,6 +3,7 @@ use std::time::Duration; use derive_more::Display; use tokio::time::sleep; +use tracing::instrument; /// This is the message that the "launcher" spawned task receives from the main /// application process to notify the service to shutdown. @@ -17,6 +18,7 @@ pub enum Halted { /// # Panics /// /// Will panic if the `ctrl_c` or `terminate` signal resolves with an error. +#[instrument(skip())] pub async fn global_shutdown_signal() { let ctrl_c = async { tokio::signal::ctrl_c().await.expect("failed to install Ctrl+C handler"); @@ -34,8 +36,8 @@ pub async fn global_shutdown_signal() { let terminate = std::future::pending::<()>(); tokio::select! { - () = ctrl_c => {}, - () = terminate => {} + () = ctrl_c => {tracing::warn!("caught interrupt signal (ctrl-c), halting...");}, + () = terminate => {tracing::warn!("caught interrupt signal (terminate), halting...");} } } @@ -44,6 +46,7 @@ pub async fn global_shutdown_signal() { /// # Panics /// /// Will panic if the `stop_receiver` resolves with an error. +#[instrument(skip(rx_halt))] pub async fn shutdown_signal(rx_halt: tokio::sync::oneshot::Receiver) { let halt = async { match rx_halt.await { @@ -53,22 +56,24 @@ pub async fn shutdown_signal(rx_halt: tokio::sync::oneshot::Receiver) { }; tokio::select! { - signal = halt => { tracing::info!("Halt signal processed: {}", signal) }, - () = global_shutdown_signal() => { tracing::info!("Global shutdown signal processed") } + signal = halt => { tracing::debug!("Halt signal processed: {}", signal) }, + () = global_shutdown_signal() => { tracing::debug!("Global shutdown signal processed") } } } /// Same as `shutdown_signal()`, but shows a message when it resolves. +#[instrument(skip(rx_halt))] pub async fn shutdown_signal_with_message(rx_halt: tokio::sync::oneshot::Receiver, message: String) { shutdown_signal(rx_halt).await; tracing::info!("{message}"); } +#[instrument(skip(handle, rx_halt, message))] pub async fn graceful_shutdown(handle: axum_server::Handle, rx_halt: tokio::sync::oneshot::Receiver, message: String) { shutdown_signal_with_message(rx_halt, message).await; - tracing::info!("Sending graceful shutdown signal"); + tracing::debug!("Sending graceful shutdown signal"); handle.graceful_shutdown(Some(Duration::from_secs(90))); println!("!! shuting down in 90 seconds !!"); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 34f786219..373fb9c14 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -12,6 +12,7 @@ use aquatic_udp_protocol::{ }; use torrust_tracker_located_error::DynError; use torrust_tracker_primitives::info_hash::InfoHash; +use tracing::{instrument, Level}; use uuid::Uuid; use zerocopy::network_endian::I32; @@ -31,6 +32,7 @@ use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; /// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. +#[instrument(skip(udp_request, tracker, local_addr), ret(level = Level::TRACE))] pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Tracker, local_addr: SocketAddr) -> Response { tracing::debug!("Handling Packets: {udp_request:?}"); @@ -86,8 +88,9 @@ pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Tracker, lo /// # Errors /// /// If a error happens in the `handle_request` function, it will just return the `ServerError`. +#[instrument(skip(request, remote_addr, tracker))] pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: &Tracker) -> Result { - tracing::debug!("Handling Request: {request:?} to: {remote_addr:?}"); + tracing::trace!("handle request"); match request { Request::Connect(connect_request) => handle_connect(remote_addr, &connect_request, tracker).await, @@ -102,8 +105,9 @@ pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: /// # Errors /// /// This function does not ever return an error. +#[instrument(skip(tracker), err, ret(level = Level::TRACE))] pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, tracker: &Tracker) -> Result { - tracing::debug!("udp connect request: {:#?}", request); + tracing::trace!("handle connect"); let connection_cookie = make(&remote_addr); let connection_id = into_connection_id(&connection_cookie); @@ -113,8 +117,6 @@ pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, t connection_id, }; - tracing::debug!("udp connect response: {:#?}", response); - // send stats event match remote_addr { SocketAddr::V4(_) => { @@ -134,12 +136,13 @@ pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, t /// # Errors /// /// If a error happens in the `handle_announce` function, it will just return the `ServerError`. +#[instrument(skip(tracker), err, ret(level = Level::TRACE))] pub async fn handle_announce( remote_addr: SocketAddr, announce_request: &AnnounceRequest, tracker: &Tracker, ) -> Result { - tracing::debug!("udp announce request: {:#?}", announce_request); + tracing::trace!("handle announce"); // Authentication if tracker.requires_authentication() { @@ -196,8 +199,6 @@ pub async fn handle_announce( .collect(), }; - tracing::debug!("udp announce response: {:#?}", announce_response); - Ok(Response::from(announce_response)) } else { let announce_response = AnnounceResponse { @@ -223,8 +224,6 @@ pub async fn handle_announce( .collect(), }; - tracing::debug!("udp announce response: {:#?}", announce_response); - Ok(Response::from(announce_response)) } } @@ -235,8 +234,9 @@ pub async fn handle_announce( /// # Errors /// /// This function does not ever return an error. +#[instrument(skip(tracker), err, ret(level = Level::TRACE))] pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tracker: &Tracker) -> Result { - tracing::debug!("udp scrape request: {:#?}", request); + tracing::trace!("handle scrape"); // Convert from aquatic infohashes let mut info_hashes: Vec = vec![]; @@ -282,8 +282,6 @@ pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tra torrent_stats, }; - tracing::debug!("udp scrape response: {:#?}", response); - Ok(Response::from(response)) } diff --git a/src/servers/udp/server/bound_socket.rs b/src/servers/udp/server/bound_socket.rs index 42242e44a..658589aa6 100644 --- a/src/servers/udp/server/bound_socket.rs +++ b/src/servers/udp/server/bound_socket.rs @@ -26,7 +26,7 @@ impl BoundSocket { Err(e) => Err(e)?, }; - let local_addr = format!("udp://{addr}"); + let local_addr = format!("udp://{}", socket.local_addr()?); tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpSocket::new (bound)"); Ok(Self { socket }) diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 7b40f6604..c9ad213f6 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -6,6 +6,7 @@ use derive_more::Constructor; use futures_util::StreamExt; use tokio::select; use tokio::sync::oneshot; +use tracing::instrument; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; @@ -30,17 +31,13 @@ impl Launcher { /// /// It panics if unable to bind to udp socket, and get the address from the udp socket. /// It also panics if unable to send address of socket. + #[instrument(skip(tracker, bind_to, tx_start, rx_halt))] pub async fn run_with_graceful_shutdown( tracker: Arc, bind_to: SocketAddr, tx_start: oneshot::Sender, rx_halt: oneshot::Receiver, ) { - let halt_task = tokio::task::spawn(shutdown_signal_with_message( - rx_halt, - format!("Halting UDP Service Bound to Socket: {bind_to}"), - )); - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting on: {bind_to}"); let socket = tokio::time::timeout(Duration::from_millis(5000), BoundSocket::new(bind_to)) @@ -80,6 +77,11 @@ impl Launcher { let stop = running.abort_handle(); + let halt_task = tokio::task::spawn(shutdown_signal_with_message( + rx_halt, + format!("Halting UDP Service Bound to Socket: {address}"), + )); + select! { _ = running => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (stopped)"); }, _ = halt_task => { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (halting)"); } @@ -90,6 +92,7 @@ impl Launcher { } #[must_use] + #[instrument(skip(binding))] pub fn check(binding: &SocketAddr) -> ServiceHealthCheckJob { let binding = *binding; let info = format!("checking the udp tracker health check at: {binding}"); @@ -99,6 +102,7 @@ impl Launcher { ServiceHealthCheckJob::new(binding, info, job) } + #[instrument(skip(receiver, tracker))] async fn run_udp_server_main(mut receiver: Receiver, tracker: Arc) { let active_requests = &mut ActiveRequests::default(); diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 16133e21b..d81624cb2 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -1,6 +1,9 @@ //! Module to handle the UDP server instances. use std::fmt::Debug; +use derive_more::derive::Display; +use thiserror::Error; + use super::RawRequest; pub mod bound_socket; @@ -21,11 +24,13 @@ pub mod states; /// Some errors triggered while stopping the server are: /// /// - The [`Server`] cannot send the shutdown signal to the spawned UDP service thread. -#[derive(Debug)] +#[derive(Debug, Error)] pub enum UdpError { - /// Any kind of error starting or stopping the server. - Socket(std::io::Error), - Error(String), + #[error("Any error to do with the socket")] + FailedToBindSocket(std::io::Error), + + #[error("Any error to do with starting or stopping the sever")] + FailedToStartOrStopServer(String), } /// A UDP server. @@ -38,7 +43,11 @@ pub enum UdpError { /// > reset to the initial value after stopping the server. This struct is not /// > intended to persist configurations between runs. #[allow(clippy::module_name_repetitions)] -pub struct Server { +#[derive(Debug, Display)] +pub struct Server +where + S: std::fmt::Debug + std::fmt::Display, +{ /// The state of the server: `running` or `stopped`. pub state: S, } diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index e633a2358..9fa28a44d 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -3,10 +3,11 @@ use std::net::SocketAddr; use std::sync::Arc; use aquatic_udp_protocol::Response; +use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; use crate::core::Tracker; -use crate::servers::udp::{handlers, RawRequest, UDP_TRACKER_LOG_TARGET}; +use crate::servers::udp::{handlers, RawRequest}; pub struct Processor { socket: Arc, @@ -18,15 +19,17 @@ impl Processor { Self { socket, tracker } } + #[instrument(skip(self, request))] pub async fn process_request(self, request: RawRequest) { - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, request = %request.from, "Udp::process_request (receiving)"); - let from = request.from; let response = handlers::handle_packet(request, &self.tracker, self.socket.address()).await; self.send_response(from, response).await; } - async fn send_response(self, to: SocketAddr, response: Response) { + #[instrument(skip(self))] + async fn send_response(self, target: SocketAddr, response: Response) { + tracing::debug!("send response"); + let response_type = match &response { Response::Connect(_) => "Connect".to_string(), Response::AnnounceIpv4(_) => "AnnounceIpv4".to_string(), @@ -35,8 +38,6 @@ impl Processor { Response::Error(e) => format!("Error: {e:?}"), }; - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, target = ?to, response_type, "Udp::send_response (sending)"); - let mut writer = Cursor::new(Vec::with_capacity(200)); match response.write_bytes(&mut writer) { @@ -44,23 +45,28 @@ impl Processor { let bytes_count = writer.get_ref().len(); let payload = writer.get_ref(); - tracing::debug!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count, "Udp::send_response (sending...)" ); - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, ?to, bytes_count, ?payload, "Udp::send_response (sending...)"); - - self.send_packet(&to, payload).await; - - tracing::trace!(target:UDP_TRACKER_LOG_TARGET, ?to, bytes_count, "Udp::send_response (sent)"); + let () = match self.send_packet(&target, payload).await { + Ok(sent_bytes) => { + if tracing::event_enabled!(Level::TRACE) { + tracing::debug!(%bytes_count, %sent_bytes, ?payload, "sent {response_type}"); + } else { + tracing::debug!(%bytes_count, %sent_bytes, "sent {response_type}"); + } + } + Err(error) => tracing::warn!(%bytes_count, %error, ?payload, "failed to send"), + }; } Err(e) => { - tracing::error!(target: UDP_TRACKER_LOG_TARGET, ?to, response_type, err = %e, "Udp::send_response (error)"); + tracing::error!(%e, "error"); } } } - async fn send_packet(&self, remote_addr: &SocketAddr, payload: &[u8]) { - tracing::trace!(target: UDP_TRACKER_LOG_TARGET, to = %remote_addr, ?payload, "Udp::send_response (sending)"); + #[instrument(skip(self))] + async fn send_packet(&self, target: &SocketAddr, payload: &[u8]) -> std::io::Result { + tracing::trace!("send packet"); // doesn't matter if it reaches or not - drop(self.socket.send_to(payload, remote_addr).await); + self.socket.send_to(payload, target).await } } diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index e4612fbe0..dea293ad7 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -2,6 +2,7 @@ use std::net::SocketAddr; use std::sync::Arc; +use derive_more::derive::Display; use derive_more::Constructor; use tokio::sync::oneshot; use tokio::task::JoinHandle; @@ -11,7 +12,8 @@ use crate::bootstrap::jobs::Started; use crate::core::Tracker; use crate::servers::signals::Halted; -#[derive(Constructor, Copy, Clone, Debug)] +#[derive(Constructor, Copy, Clone, Debug, Display)] +#[display("(with socket): {bind_to}")] pub struct Spawner { pub bind_to: SocketAddr, } diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index d0a2e4e8a..e90c4da54 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -2,8 +2,10 @@ use std::fmt::Debug; use std::net::SocketAddr; use std::sync::Arc; +use derive_more::derive::Display; use derive_more::Constructor; use tokio::task::JoinHandle; +use tracing::{instrument, Level}; use super::spawner::Spawner; use super::{Server, UdpError}; @@ -23,16 +25,18 @@ pub type StoppedUdpServer = Server; pub type RunningUdpServer = Server; /// A stopped UDP server state. - +#[derive(Debug, Display)] +#[display("Stopped: {spawner}")] pub struct Stopped { pub spawner: Spawner, } /// A running UDP server state. -#[derive(Debug, Constructor)] +#[derive(Debug, Display, Constructor)] +#[display("Running (with local address): {local_addr}")] pub struct Running { /// The address where the server is bound. - pub binding: SocketAddr, + pub local_addr: SocketAddr, pub halt_task: tokio::sync::oneshot::Sender, pub task: JoinHandle, } @@ -57,6 +61,7 @@ impl Server { /// /// It panics if unable to receive the bound socket address from service. /// + #[instrument(skip(self, tracker, form), err, ret(Display, level = Level::INFO))] pub async fn start(self, tracker: Arc, form: ServiceRegistrationForm) -> Result, std::io::Error> { let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); @@ -66,20 +71,20 @@ impl Server { // May need to wrap in a task to about a tokio bug. let task = self.state.spawner.spawn_launcher(tracker, tx_start, rx_halt); - let binding = rx_start.await.expect("it should be able to start the service").address; - let local_addr = format!("udp://{binding}"); + let local_addr = rx_start.await.expect("it should be able to start the service").address; - form.send(ServiceRegistration::new(binding, Launcher::check)) + form.send(ServiceRegistration::new(local_addr, Launcher::check)) .expect("it should be able to send service registration"); let running_udp_server: Server = Server { state: Running { - binding, + local_addr, halt_task: tx_halt, task, }, }; + let local_addr = format!("udp://{local_addr}"); tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "UdpServer::start (running)"); Ok(running_udp_server) @@ -98,11 +103,12 @@ impl Server { /// # Panics /// /// It panics if unable to shutdown service. + #[instrument(skip(self), err, ret(Display, level = Level::INFO))] pub async fn stop(self) -> Result, UdpError> { self.state .halt_task .send(Halted::Normal) - .map_err(|e| UdpError::Error(e.to_string()))?; + .map_err(|e| UdpError::FailedToStartOrStopServer(e.to_string()))?; let launcher = self.state.task.await.expect("it should shutdown service"); diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 92ef7b70b..2f4606be7 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -13,14 +13,20 @@ use torrust_tracker_primitives::peer; use super::connection_info::ConnectionInfo; -pub struct Environment { +pub struct Environment +where + S: std::fmt::Debug + std::fmt::Display, +{ pub config: Arc, pub tracker: Arc, pub registar: Registar, pub server: ApiServer, } -impl Environment { +impl Environment +where + S: std::fmt::Debug + std::fmt::Display, +{ /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { self.tracker.upsert_peer_and_get_stats(info_hash, peer); @@ -79,12 +85,12 @@ impl Environment { pub fn get_connection_info(&self) -> ConnectionInfo { ConnectionInfo { - bind_address: self.server.state.binding.to_string(), + bind_address: self.server.state.local_addr.to_string(), api_token: self.config.access_tokens.get("admin").cloned(), } } pub fn bind_address(&self) -> SocketAddr { - self.server.state.binding + self.server.state.local_addr } } diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index f74b4717b..41e92c9d6 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -1639,6 +1639,10 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_zeroed_file_when_the_authentication_key_provided_by_the_client_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + // There is not authentication error // code-review: should this really be this way? diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 30f257d1c..b7ac2336c 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -11,14 +11,20 @@ use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer; -pub struct Environment { +pub struct Environment +where + S: std::fmt::Debug + std::fmt::Display, +{ pub config: Arc, pub tracker: Arc, pub registar: Registar, pub server: Server, } -impl Environment { +impl Environment +where + S: std::fmt::Debug + std::fmt::Display, +{ /// Add a torrent to the tracker #[allow(dead_code)] pub fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { @@ -80,7 +86,7 @@ impl Environment { } pub fn bind_address(&self) -> SocketAddr { - self.server.state.binding + self.server.state.local_addr } } From 39ab661d0785b299aecfe0ac13db44f528851d90 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 3 Sep 2024 12:01:03 +0100 Subject: [PATCH 0484/1297] release: version 3.0.0-beta --- Cargo.lock | 38 +++++++++----------------- Cargo.toml | 16 +++++------ packages/clock/Cargo.toml | 2 +- packages/configuration/Cargo.toml | 2 +- packages/test-helpers/Cargo.toml | 2 +- packages/torrent-repository/Cargo.toml | 6 ++-- 6 files changed, 27 insertions(+), 39 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0e3401278..44dc6812c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -448,7 +448,7 @@ dependencies = [ "serde_urlencoded", "sync_wrapper 1.0.1", "tokio", - "tower 0.4.13", + "tower", "tower-layer", "tower-service", "tracing", @@ -503,7 +503,7 @@ dependencies = [ "pin-project-lite", "serde", "serde_html_form", - "tower 0.4.13", + "tower", "tower-layer", "tower-service", "tracing", @@ -541,7 +541,7 @@ dependencies = [ "rustls-pki-types", "tokio", "tokio-rustls", - "tower 0.4.13", + "tower", "tower-service", ] @@ -1852,7 +1852,7 @@ dependencies = [ "pin-project-lite", "socket2 0.5.7", "tokio", - "tower 0.4.13", + "tower", "tower-service", "tracing", ] @@ -3922,7 +3922,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-beta-develop" +version = "3.0.0-beta" dependencies = [ "anyhow", "aquatic_udp_protocol", @@ -3972,7 +3972,7 @@ dependencies = [ "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-tracker-torrent-repository", - "tower 0.5.0", + "tower", "tower-http", "trace", "tracing", @@ -3984,7 +3984,7 @@ dependencies = [ [[package]] name = "torrust-tracker-clock" -version = "3.0.0-beta-develop" +version = "3.0.0-beta" dependencies = [ "chrono", "lazy_static", @@ -3993,7 +3993,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-beta-develop" +version = "3.0.0-beta" dependencies = [ "camino", "derive_more", @@ -4010,7 +4010,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-beta-develop" +version = "3.0.0-beta" dependencies = [ "criterion", "thiserror", @@ -4018,7 +4018,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-beta-develop" +version = "3.0.0-beta" dependencies = [ "thiserror", "tracing", @@ -4026,7 +4026,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-beta-develop" +version = "3.0.0-beta" dependencies = [ "aquatic_udp_protocol", "binascii", @@ -4040,7 +4040,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-beta-develop" +version = "3.0.0-beta" dependencies = [ "rand", "torrust-tracker-configuration", @@ -4048,7 +4048,7 @@ dependencies = [ [[package]] name = "torrust-tracker-torrent-repository" -version = "3.0.0-beta-develop" +version = "3.0.0-beta" dependencies = [ "aquatic_udp_protocol", "async-std", @@ -4081,18 +4081,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "tower" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36b837f86b25d7c0d7988f00a54e74739be6477f2aac6201b8f429a7569991b7" -dependencies = [ - "pin-project-lite", - "tokio", - "tower-layer", - "tower-service", -] - [[package]] name = "tower-http" version = "0.5.2" diff --git a/Cargo.toml b/Cargo.toml index 1a875a192..1cce015e0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ license = "AGPL-3.0-only" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-beta-develop" +version = "3.0.0-beta" [dependencies] anyhow = "1" @@ -69,12 +69,12 @@ serde_repr = "0" serde_with = { version = "3", features = ["json"] } thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-clock = { version = "3.0.0-beta-develop", path = "packages/clock" } -torrust-tracker-configuration = { version = "3.0.0-beta-develop", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-beta-develop", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-beta-develop", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-beta-develop", path = "packages/primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-beta-develop", path = "packages/torrent-repository" } +torrust-tracker-clock = { version = "3.0.0-beta", path = "packages/clock" } +torrust-tracker-configuration = { version = "3.0.0-beta", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-beta", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-beta", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-beta", path = "packages/primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-beta", path = "packages/torrent-repository" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } trace = "0" @@ -90,7 +90,7 @@ ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_byt [dev-dependencies] local-ip-address = "0" mockall = "0" -torrust-tracker-test-helpers = { version = "3.0.0-beta-develop", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-beta", path = "packages/test-helpers" } [workspace] members = [ diff --git a/packages/clock/Cargo.toml b/packages/clock/Cargo.toml index e28a37466..d7893ada7 100644 --- a/packages/clock/Cargo.toml +++ b/packages/clock/Cargo.toml @@ -19,6 +19,6 @@ version.workspace = true chrono = { version = "0", default-features = false, features = ["clock"] } lazy_static = "1" -torrust-tracker-primitives = { version = "3.0.0-beta-develop", path = "../primitives" } +torrust-tracker-primitives = { version = "3.0.0-beta", path = "../primitives" } [dev-dependencies] diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 4f217e1b6..65b4ffa3a 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -23,7 +23,7 @@ serde_json = { version = "1", features = ["preserve_order"] } serde_with = "3" thiserror = "1" toml = "0" -torrust-tracker-located-error = { version = "3.0.0-beta-develop", path = "../located-error" } +torrust-tracker-located-error = { version = "3.0.0-beta", path = "../located-error" } url = "2" [dev-dependencies] diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 0fd108ecf..56d5580ea 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -16,4 +16,4 @@ version.workspace = true [dependencies] rand = "0" -torrust-tracker-configuration = { version = "3.0.0-beta-develop", path = "../configuration" } +torrust-tracker-configuration = { version = "3.0.0-beta", path = "../configuration" } diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 38405e4e0..e30a2d80a 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -22,9 +22,9 @@ dashmap = "6" futures = "0" parking_lot = "0" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-clock = { version = "3.0.0-beta-develop", path = "../clock" } -torrust-tracker-configuration = { version = "3.0.0-beta-develop", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-beta-develop", path = "../primitives" } +torrust-tracker-clock = { version = "3.0.0-beta", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-beta", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-beta", path = "../primitives" } zerocopy = "0" [dev-dependencies] From b88cc6151f421506f502a7dd2b8a79a262fb2517 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 3 Sep 2024 12:07:26 +0100 Subject: [PATCH 0485/1297] develop: bump to version 3.0.0-rc.1-develop --- Cargo.lock | 16 ++++++++-------- Cargo.toml | 16 ++++++++-------- packages/clock/Cargo.toml | 2 +- packages/configuration/Cargo.toml | 2 +- packages/test-helpers/Cargo.toml | 2 +- packages/torrent-repository/Cargo.toml | 6 +++--- 6 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 44dc6812c..ae780dd5c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3922,7 +3922,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-beta" +version = "3.0.0-rc.1-develop" dependencies = [ "anyhow", "aquatic_udp_protocol", @@ -3984,7 +3984,7 @@ dependencies = [ [[package]] name = "torrust-tracker-clock" -version = "3.0.0-beta" +version = "3.0.0-rc.1-develop" dependencies = [ "chrono", "lazy_static", @@ -3993,7 +3993,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-beta" +version = "3.0.0-rc.1-develop" dependencies = [ "camino", "derive_more", @@ -4010,7 +4010,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-beta" +version = "3.0.0-rc.1-develop" dependencies = [ "criterion", "thiserror", @@ -4018,7 +4018,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-beta" +version = "3.0.0-rc.1-develop" dependencies = [ "thiserror", "tracing", @@ -4026,7 +4026,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-beta" +version = "3.0.0-rc.1-develop" dependencies = [ "aquatic_udp_protocol", "binascii", @@ -4040,7 +4040,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-beta" +version = "3.0.0-rc.1-develop" dependencies = [ "rand", "torrust-tracker-configuration", @@ -4048,7 +4048,7 @@ dependencies = [ [[package]] name = "torrust-tracker-torrent-repository" -version = "3.0.0-beta" +version = "3.0.0-rc.1-develop" dependencies = [ "aquatic_udp_protocol", "async-std", diff --git a/Cargo.toml b/Cargo.toml index 1cce015e0..5a2b382cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ license = "AGPL-3.0-only" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-beta" +version = "3.0.0-rc.1-develop" [dependencies] anyhow = "1" @@ -69,12 +69,12 @@ serde_repr = "0" serde_with = { version = "3", features = ["json"] } thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-clock = { version = "3.0.0-beta", path = "packages/clock" } -torrust-tracker-configuration = { version = "3.0.0-beta", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-beta", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-beta", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-beta", path = "packages/primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-beta", path = "packages/torrent-repository" } +torrust-tracker-clock = { version = "3.0.0-rc.1-develop", path = "packages/clock" } +torrust-tracker-configuration = { version = "3.0.0-rc.1-develop", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-rc.1-develop", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-rc.1-develop", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-rc.1-develop", path = "packages/primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-rc.1-develop", path = "packages/torrent-repository" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } trace = "0" @@ -90,7 +90,7 @@ ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_byt [dev-dependencies] local-ip-address = "0" mockall = "0" -torrust-tracker-test-helpers = { version = "3.0.0-beta", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-rc.1-develop", path = "packages/test-helpers" } [workspace] members = [ diff --git a/packages/clock/Cargo.toml b/packages/clock/Cargo.toml index d7893ada7..908816742 100644 --- a/packages/clock/Cargo.toml +++ b/packages/clock/Cargo.toml @@ -19,6 +19,6 @@ version.workspace = true chrono = { version = "0", default-features = false, features = ["clock"] } lazy_static = "1" -torrust-tracker-primitives = { version = "3.0.0-beta", path = "../primitives" } +torrust-tracker-primitives = { version = "3.0.0-rc.1-develop", path = "../primitives" } [dev-dependencies] diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 65b4ffa3a..8eafcc06a 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -23,7 +23,7 @@ serde_json = { version = "1", features = ["preserve_order"] } serde_with = "3" thiserror = "1" toml = "0" -torrust-tracker-located-error = { version = "3.0.0-beta", path = "../located-error" } +torrust-tracker-located-error = { version = "3.0.0-rc.1-develop", path = "../located-error" } url = "2" [dev-dependencies] diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 56d5580ea..b8762824d 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -16,4 +16,4 @@ version.workspace = true [dependencies] rand = "0" -torrust-tracker-configuration = { version = "3.0.0-beta", path = "../configuration" } +torrust-tracker-configuration = { version = "3.0.0-rc.1-develop", path = "../configuration" } diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index e30a2d80a..5268b223f 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -22,9 +22,9 @@ dashmap = "6" futures = "0" parking_lot = "0" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-clock = { version = "3.0.0-beta", path = "../clock" } -torrust-tracker-configuration = { version = "3.0.0-beta", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-beta", path = "../primitives" } +torrust-tracker-clock = { version = "3.0.0-rc.1-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-rc.1-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-rc.1-develop", path = "../primitives" } zerocopy = "0" [dev-dependencies] From 1f64cc9a1d851d90e29806fc87088b585ec5b6ac Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 10 Sep 2024 09:23:51 +0100 Subject: [PATCH 0486/1297] chore(deps): udpate dependencies ``` cargo update Updating crates.io index Locking 44 packages to latest compatible versions Updating addr2line v0.22.0 -> v0.24.1 Removing adler v1.0.2 Updating anyhow v1.0.86 -> v1.0.87 Updating async-executor v1.13.0 -> v1.13.1 Removing async-io v1.13.0 Removing async-lock v2.8.0 Updating async-std v1.12.0 -> v1.13.0 Updating async-trait v0.1.81 -> v0.1.82 Updating aws-lc-rs v1.8.1 -> v1.9.0 Updating aws-lc-sys v0.20.1 -> v0.21.1 Updating backtrace v0.3.73 -> v0.3.74 Removing bitflags v1.3.2 Updating bytemuck v1.17.0 -> v1.18.0 Updating cc v1.1.14 -> v1.1.18 Updating clap v4.5.16 -> v4.5.17 Updating clap_builder v4.5.15 -> v4.5.17 Updating cpufeatures v0.2.13 -> v0.2.14 Updating dashmap v6.0.1 -> v6.1.0 Removing fastrand v1.9.0 Updating frunk v0.4.2 -> v0.4.3 Updating frunk_core v0.4.2 -> v0.4.3 Updating frunk_derives v0.4.2 -> v0.4.3 Updating frunk_proc_macro_helpers v0.1.2 -> v0.1.3 Updating frunk_proc_macros v0.1.2 -> v0.1.3 Removing futures-lite v1.13.0 Updating gimli v0.29.0 -> v0.31.0 Updating gloo-timers v0.2.6 -> v0.3.0 Updating hyper-rustls v0.27.2 -> v0.27.3 Updating hyper-util v0.1.7 -> v0.1.8 Updating indexmap v2.4.0 -> v2.5.0 Removing instant v0.1.13 Removing io-lifetimes v1.0.11 Updating ipnet v2.9.0 -> v2.10.0 Removing linux-raw-sys v0.3.8 Updating local-ip-address v0.6.1 -> v0.6.2 Removing miniz_oxide v0.7.4 Updating object v0.36.3 -> v0.36.4 Updating parking v2.2.0 -> v2.2.1 Updating plotters v0.3.6 -> v0.3.7 Updating plotters-backend v0.3.6 -> v0.3.7 Updating plotters-svg v0.3.6 -> v0.3.7 Removing polling v2.8.0 Updating prettyplease v0.2.21 -> v0.2.22 Updating proc-macro-crate v3.1.0 -> v3.2.0 Updating rustc_version v0.4.0 -> v0.4.1 Removing rustix v0.37.27 Removing rustix v0.38.34 Adding rustix v0.38.36 Updating rustls-webpki v0.102.6 -> v0.102.8 Updating schannel v0.1.23 -> v0.1.24 Updating serde v1.0.209 -> v1.0.210 Updating serde_derive v1.0.209 -> v1.0.210 Updating serde_json v1.0.127 -> v1.0.128 Removing socket2 v0.4.10 Updating syn v2.0.76 -> v2.0.77 Updating tokio v1.39.3 -> v1.40.0 Updating tokio-util v0.7.11 -> v0.7.12 Removing toml_edit v0.21.1 Adding tower v0.5.1 Removing waker-fn v1.2.0 Removing winnow v0.5.40 Removing zeroize_derive v1.4.2 ``` --- Cargo.lock | 532 ++++++++++++++++++----------------------------------- 1 file changed, 184 insertions(+), 348 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ae780dd5c..7204fd612 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,19 +4,13 @@ version = 3 [[package]] name = "addr2line" -version = "0.22.0" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" +checksum = "f5fb1d8e4442bd405fdfd1dacb42792696b0cf9cb15882e5d097b742a676d375" dependencies = [ "gimli", ] -[[package]] -name = "adler" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" - [[package]] name = "adler2" version = "2.0.0" @@ -148,9 +142,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.86" +version = "1.0.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" +checksum = "10f00e1f6e58a40e807377c75c6a7f97bf9044fab57816f2414e6f5f4499d7b8" [[package]] name = "aquatic_peer_id" @@ -241,14 +235,14 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.13.0" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7ebdfa2ebdab6b1760375fa7d6f382b9f486eac35fc994625a00e89280bdbb7" +checksum = "30ca9a001c1e8ba5149f91a74362376cc6bc5b919d92d988668657bd570bdcec" dependencies = [ "async-task", "concurrent-queue", - "fastrand 2.1.1", - "futures-lite 2.3.0", + "fastrand", + "futures-lite", "slab", ] @@ -260,62 +254,33 @@ checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" dependencies = [ "async-channel 2.3.1", "async-executor", - "async-io 2.3.4", - "async-lock 3.4.0", + "async-io", + "async-lock", "blocking", - "futures-lite 2.3.0", + "futures-lite", "once_cell", "tokio", ] -[[package]] -name = "async-io" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af" -dependencies = [ - "async-lock 2.8.0", - "autocfg", - "cfg-if", - "concurrent-queue", - "futures-lite 1.13.0", - "log", - "parking", - "polling 2.8.0", - "rustix 0.37.27", - "slab", - "socket2 0.4.10", - "waker-fn", -] - [[package]] name = "async-io" version = "2.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "444b0228950ee6501b3568d3c93bf1176a1fdbc3b758dcd9475046d30f4dc7e8" dependencies = [ - "async-lock 3.4.0", + "async-lock", "cfg-if", "concurrent-queue", "futures-io", - "futures-lite 2.3.0", + "futures-lite", "parking", - "polling 3.7.3", - "rustix 0.38.34", + "polling", + "rustix", "slab", "tracing", "windows-sys 0.59.0", ] -[[package]] -name = "async-lock" -version = "2.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b" -dependencies = [ - "event-listener 2.5.3", -] - [[package]] name = "async-lock" version = "3.4.0" @@ -329,20 +294,20 @@ dependencies = [ [[package]] name = "async-std" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62565bb4402e926b29953c785397c6dc0391b7b446e45008b0049eb43cec6f5d" +checksum = "c634475f29802fde2b8f0b505b1bd00dfe4df7d4a000f0b36f7671197d5c3615" dependencies = [ "async-attributes", "async-channel 1.9.0", "async-global-executor", - "async-io 1.13.0", - "async-lock 2.8.0", + "async-io", + "async-lock", "crossbeam-utils", "futures-channel", "futures-core", "futures-io", - "futures-lite 1.13.0", + "futures-lite", "gloo-timers", "kv-log-macro", "log", @@ -362,13 +327,13 @@ checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" [[package]] name = "async-trait" -version = "0.1.81" +version = "0.1.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e0c28dcc82d7c8ead5cb13beb15405b57b8546e93215673ff8ca0349a028107" +checksum = "a27b8a3a6e1a44fa4c8baf1f653e4172e81486d4941f2237e20dc2d0cf4ddff1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -394,9 +359,9 @@ checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" [[package]] name = "aws-lc-rs" -version = "1.8.1" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae74d9bd0a7530e8afd1770739ad34b36838829d6ad61818f9230f683f5ad77" +checksum = "2f95446d919226d587817a7d21379e6eb099b97b45110a7f272a444ca5c54070" dependencies = [ "aws-lc-sys", "mirai-annotations", @@ -406,9 +371,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.20.1" +version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f0e249228c6ad2d240c2dc94b714d711629d52bad946075d8e9b2f5391f0703" +checksum = "234314bd569802ec87011d653d6815c6d7b9ffb969e9fee5b8b20ef860e8dce9" dependencies = [ "bindgen 0.69.4", "cc", @@ -448,7 +413,7 @@ dependencies = [ "serde_urlencoded", "sync_wrapper 1.0.1", "tokio", - "tower", + "tower 0.4.13", "tower-layer", "tower-service", "tracing", @@ -503,7 +468,7 @@ dependencies = [ "pin-project-lite", "serde", "serde_html_form", - "tower", + "tower 0.4.13", "tower-layer", "tower-service", "tracing", @@ -518,7 +483,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -541,23 +506,23 @@ dependencies = [ "rustls-pki-types", "tokio", "tokio-rustls", - "tower", + "tower 0.4.13", "tower-service", ] [[package]] name = "backtrace" -version = "0.3.73" +version = "0.3.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" +checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" dependencies = [ "addr2line", - "cc", "cfg-if", "libc", - "miniz_oxide 0.7.4", + "miniz_oxide", "object", "rustc-demangle", + "windows-targets 0.52.6", ] [[package]] @@ -597,7 +562,7 @@ version = "0.69.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a00dc851838a2120612785d195287475a3ac45514741da670b735818822129a0" dependencies = [ - "bitflags 2.6.0", + "bitflags", "cexpr", "clang-sys", "itertools 0.12.1", @@ -610,7 +575,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.76", + "syn 2.0.77", "which", ] @@ -620,7 +585,7 @@ version = "0.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" dependencies = [ - "bitflags 2.6.0", + "bitflags", "cexpr", "clang-sys", "itertools 0.13.0", @@ -629,15 +594,9 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.76", + "syn 2.0.77", ] -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - [[package]] name = "bitflags" version = "2.6.0" @@ -674,7 +633,7 @@ dependencies = [ "async-channel 2.3.1", "async-task", "futures-io", - "futures-lite 2.3.0", + "futures-lite", "piper", ] @@ -698,7 +657,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", "syn_derive", ] @@ -768,9 +727,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.17.0" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fd4c6dcc3b0aea2f5c0b4b82c2b15fe39ddbc76041a310848f4706edf76bb31" +checksum = "94bbb0ad554ad961ddc5da507a12a29b14e4ae5bda06b19f575a3e6079d2e2ae" [[package]] name = "byteorder" @@ -810,9 +769,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.1.14" +version = "1.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50d2eb3cd3d1bf4529e31c215ee6f93ec5a3d536d9f578f93d9d33ee19562932" +checksum = "b62ac837cdb5cb22e10a256099b4fc502b1dfe560cb282963a974d7abd80e476" dependencies = [ "jobserver", "libc", @@ -893,9 +852,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.16" +version = "4.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed6719fffa43d0d87e5fd8caeab59be1554fb028cd30edc88fc4369b17971019" +checksum = "3e5a21b8495e732f1b3c364c9949b201ca7bae518c502c80256c96ad79eaf6ac" dependencies = [ "clap_builder", "clap_derive", @@ -903,9 +862,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.15" +version = "4.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "216aec2b177652e3846684cbfe25c9964d18ec45234f0f5da5157b207ed1aab6" +checksum = "8cf2dd12af7a047ad9d6da2b6b249759a22a7abc0f474c1dae1777afa4b21a73" dependencies = [ "anstream", "anstyle", @@ -922,7 +881,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -986,9 +945,9 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpufeatures" -version = "0.2.13" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51e852e6dc9a5bed1fae92dd2375037bf2b768725bf3be87811edee3249d09ad" +checksum = "608697df725056feaccfa42cffdaeeec3fccc4ffc38358ecd19b243e716a78e0" dependencies = [ "libc", ] @@ -1143,7 +1102,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -1154,14 +1113,14 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] name = "dashmap" -version = "6.0.1" +version = "6.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "804c8821570c3f8b70230c2ba75ffa5c0f9a4189b9a432b6656c536712acae28" +checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" dependencies = [ "cfg-if", "crossbeam-utils", @@ -1198,7 +1157,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", "unicode-xid", ] @@ -1210,7 +1169,7 @@ checksum = "65f152f4b8559c4da5d574bafc7af85454d706b4c5fe8b530d508cacbb6807ea" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -1315,15 +1274,6 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" -[[package]] -name = "fastrand" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" -dependencies = [ - "instant", -] - [[package]] name = "fastrand" version = "2.1.1" @@ -1354,7 +1304,7 @@ checksum = "324a1be68054ef05ad64b861cc9eaf1d623d2d8cb25b4bf2cb9cdd902b4bf253" dependencies = [ "crc32fast", "libz-sys", - "miniz_oxide 0.8.0", + "miniz_oxide", ] [[package]] @@ -1405,54 +1355,58 @@ checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" [[package]] name = "frunk" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11a351b59e12f97b4176ee78497dff72e4276fb1ceb13e19056aca7fa0206287" +checksum = "874b6a17738fc273ec753618bac60ddaeac48cb1d7684c3e7bd472e57a28b817" dependencies = [ "frunk_core", "frunk_derives", "frunk_proc_macros", + "serde", ] [[package]] name = "frunk_core" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af2469fab0bd07e64ccf0ad57a1438f63160c69b2e57f04a439653d68eb558d6" +checksum = "3529a07095650187788833d585c219761114005d5976185760cf794d265b6a5c" +dependencies = [ + "serde", +] [[package]] name = "frunk_derives" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" +checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] name = "frunk_proc_macro_helpers" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35b54add839292b743aeda6ebedbd8b11e93404f902c56223e51b9ec18a13d2c" +checksum = "05a956ef36c377977e512e227dcad20f68c2786ac7a54dacece3746046fea5ce" dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] name = "frunk_proc_macros" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71b85a1d4a9a6b300b41c05e8e13ef2feca03e0334127f29eca9506a7fe13a93" +checksum = "67e86c2c9183662713fea27ea527aad20fb15fee635a71081ff91bf93df4dc51" dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -1515,28 +1469,13 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" -[[package]] -name = "futures-lite" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce" -dependencies = [ - "fastrand 1.9.0", - "futures-core", - "futures-io", - "memchr", - "parking", - "pin-project-lite", - "waker-fn", -] - [[package]] name = "futures-lite" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" dependencies = [ - "fastrand 2.1.1", + "fastrand", "futures-core", "futures-io", "parking", @@ -1551,7 +1490,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -1613,9 +1552,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.29.0" +version = "0.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" +checksum = "32085ea23f3234fc7846555e85283ba4de91e21016dc0455a16286d87a292d64" [[package]] name = "glob" @@ -1625,9 +1564,9 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "gloo-timers" -version = "0.2.6" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b995a66bb87bebce9a0f4a95aed01daca4872c050bfcb21653361c03bc35e5c" +checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" dependencies = [ "futures-channel", "futures-core", @@ -1647,7 +1586,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.4.0", + "indexmap 2.5.0", "slab", "tokio", "tokio-util", @@ -1806,9 +1745,9 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.2" +version = "0.27.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ee4be2c948921a1a5320b629c4193916ed787a7f7f293fd3f7f5a6c9de74155" +checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333" dependencies = [ "futures-util", "http", @@ -1839,9 +1778,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cde7055719c54e36e95e8719f95883f22072a48ede39db7fc17a4e1d5281e9b9" +checksum = "da62f120a8a37763efb0cf8fdf264b884c7b8b9ac8660b900c8661030c00e6ba" dependencies = [ "bytes", "futures-channel", @@ -1850,9 +1789,9 @@ dependencies = [ "http-body", "hyper", "pin-project-lite", - "socket2 0.5.7", + "socket2", "tokio", - "tower", + "tower 0.4.13", "tower-service", "tracing", ] @@ -1909,9 +1848,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93ead53efc7ea8ed3cfb0c79fc8023fbb782a5432b52830b6518941cebe6505c" +checksum = "68b900aa2f7301e21c36462b170ee99994de34dff39a4a6a528e80e7376d07e5" dependencies = [ "equivalent", "hashbrown 0.14.5", @@ -1924,15 +1863,6 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" -[[package]] -name = "instant" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" -dependencies = [ - "cfg-if", -] - [[package]] name = "io-enum" version = "1.1.3" @@ -1942,22 +1872,11 @@ dependencies = [ "derive_utils", ] -[[package]] -name = "io-lifetimes" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" -dependencies = [ - "hermit-abi 0.3.9", - "libc", - "windows-sys 0.48.0", -] - [[package]] name = "ipnet" -version = "2.9.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" +checksum = "187674a687eed5fe42285b40c6291f9a01517d415fad1c3cbc6a9f778af7fcd4" [[package]] name = "is-terminal" @@ -2092,12 +2011,6 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "linux-raw-sys" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" - [[package]] name = "linux-raw-sys" version = "0.4.14" @@ -2106,9 +2019,9 @@ checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "local-ip-address" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "136ef34e18462b17bf39a7826f8f3bbc223341f8e83822beb8b77db9a3d49696" +checksum = "b435d7dd476416a905f9634dff8c330cee8d3168fdd1fbd472a17d1a75c00c3e" dependencies = [ "libc", "neli", @@ -2168,15 +2081,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" -[[package]] -name = "miniz_oxide" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" -dependencies = [ - "adler", -] - [[package]] name = "miniz_oxide" version = "0.8.0" @@ -2227,7 +2131,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -2259,7 +2163,7 @@ dependencies = [ "percent-encoding", "serde", "serde_json", - "socket2 0.5.7", + "socket2", "twox-hash", "url", ] @@ -2277,7 +2181,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", "termcolor", "thiserror", ] @@ -2291,7 +2195,7 @@ dependencies = [ "base64 0.21.7", "bigdecimal", "bindgen 0.70.1", - "bitflags 2.6.0", + "bitflags", "bitvec", "btoi", "byteorder", @@ -2434,9 +2338,9 @@ dependencies = [ [[package]] name = "object" -version = "0.36.3" +version = "0.36.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b64972346851a39438c60b341ebc01bba47464ae329e55cf343eb93964efd9" +checksum = "084f1a5821ac4c651660a94a7153d27ac9d8a53736203f58b31945ded098070a" dependencies = [ "memchr", ] @@ -2459,7 +2363,7 @@ version = "0.10.66" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9529f4786b70a3e8c61e11179af17ab6188ad8d0ded78c5529441ed39d4bd9c1" dependencies = [ - "bitflags 2.6.0", + "bitflags", "cfg-if", "foreign-types", "libc", @@ -2476,7 +2380,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -2505,9 +2409,9 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" [[package]] name = "parking" -version = "2.2.0" +version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb813b8af86854136c6922af0598d719255ecb2179515e6e7730d468f05c9cae" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" [[package]] name = "parking_lot" @@ -2558,7 +2462,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -2632,7 +2536,7 @@ checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -2654,7 +2558,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066" dependencies = [ "atomic-waker", - "fastrand 2.1.1", + "fastrand", "futures-io", ] @@ -2666,9 +2570,9 @@ checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" [[package]] name = "plotters" -version = "0.3.6" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a15b6eccb8484002195a3e44fe65a4ce8e93a625797a063735536fd59cb01cf3" +checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" dependencies = [ "num-traits", "plotters-backend", @@ -2679,35 +2583,19 @@ dependencies = [ [[package]] name = "plotters-backend" -version = "0.3.6" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "414cec62c6634ae900ea1c56128dfe87cf63e7caece0852ec76aba307cebadb7" +checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" [[package]] name = "plotters-svg" -version = "0.3.6" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81b30686a7d9c3e010b84284bdd26a29f2138574f52f5eb6f794fc0ad924e705" +checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" dependencies = [ "plotters-backend", ] -[[package]] -name = "polling" -version = "2.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b2d323e8ca7996b3e23126511a523f7e62924d93ecd5ae73b333815b0eb3dce" -dependencies = [ - "autocfg", - "bitflags 1.3.2", - "cfg-if", - "concurrent-queue", - "libc", - "log", - "pin-project-lite", - "windows-sys 0.48.0", -] - [[package]] name = "polling" version = "3.7.3" @@ -2718,7 +2606,7 @@ dependencies = [ "concurrent-queue", "hermit-abi 0.4.0", "pin-project-lite", - "rustix 0.38.34", + "rustix", "tracing", "windows-sys 0.59.0", ] @@ -2766,21 +2654,21 @@ dependencies = [ [[package]] name = "prettyplease" -version = "0.2.21" +version = "0.2.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a909e6e8053fa1a5ad670f5816c7d93029ee1fa8898718490544a6b0d5d38b3e" +checksum = "479cf940fbbb3426c32c5d5176f62ad57549a0bb84773423ba8be9d089f5faba" dependencies = [ "proc-macro2", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] name = "proc-macro-crate" -version = "3.1.0" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d37c51ca738a55da99dc0c4a34860fd675453b8b36209178c2249bb13651284" +checksum = "8ecf48c7ca261d60b74ab1a7b20da18bede46776b2e55535cb958eb595c5fa7b" dependencies = [ - "toml_edit 0.21.1", + "toml_edit", ] [[package]] @@ -2824,7 +2712,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", "version_check", "yansi", ] @@ -2963,7 +2851,7 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4" dependencies = [ - "bitflags 2.6.0", + "bitflags", ] [[package]] @@ -3132,7 +3020,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.76", + "syn 2.0.77", "unicode-ident", ] @@ -3142,7 +3030,7 @@ version = "0.32.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" dependencies = [ - "bitflags 2.6.0", + "bitflags", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -3180,37 +3068,23 @@ checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" [[package]] name = "rustc_version" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" dependencies = [ "semver", ] [[package]] name = "rustix" -version = "0.37.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fea8ca367a3a01fe35e6943c400addf443c0f57670e6ec51196f71a4b8762dd2" -dependencies = [ - "bitflags 1.3.2", - "errno", - "io-lifetimes", - "libc", - "linux-raw-sys 0.3.8", - "windows-sys 0.48.0", -] - -[[package]] -name = "rustix" -version = "0.38.34" +version = "0.38.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" +checksum = "3f55e80d50763938498dd5ebb18647174e0c76dc38c5505294bb224624f30f36" dependencies = [ - "bitflags 2.6.0", + "bitflags", "errno", "libc", - "linux-raw-sys 0.4.14", + "linux-raw-sys", "windows-sys 0.52.0", ] @@ -3246,9 +3120,9 @@ checksum = "fc0a2ce646f8655401bb81e7927b812614bd5d91dbc968696be50603510fcaf0" [[package]] name = "rustls-webpki" -version = "0.102.6" +version = "0.102.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e6b52d4fda176fd835fdc55a835d4a89b8499cad995885a21149d5ad62f852e" +checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" dependencies = [ "aws-lc-rs", "ring", @@ -3285,11 +3159,11 @@ checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" [[package]] name = "schannel" -version = "0.1.23" +version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbc91545643bcf3a0bbb6569265615222618bdf33ce4ffbbd13c4bbd4c093534" +checksum = "e9aaafd5a2b6e3d657ff009d82fbd630b6bd54dd4eb06f21693925cdf80f9b8b" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3319,7 +3193,7 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" dependencies = [ - "bitflags 2.6.0", + "bitflags", "core-foundation", "core-foundation-sys", "libc", @@ -3344,9 +3218,9 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" -version = "1.0.209" +version = "1.0.210" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99fce0ffe7310761ca6bf9faf5115afbc19688edd00171d81b1bb1b116c63e09" +checksum = "c8e3592472072e6e22e0a54d5904d9febf8508f65fb8552499a1abc7d1078c3a" dependencies = [ "serde_derive", ] @@ -3372,13 +3246,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.209" +version = "1.0.210" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5831b979fd7b5439637af1752d535ff49f4860c0f341d1baeb6faf0f4242170" +checksum = "243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -3388,7 +3262,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8de514ef58196f1fc96dcaef80fe6170a1ce6215df9687a93fe8300e773fefc5" dependencies = [ "form_urlencoded", - "indexmap 2.4.0", + "indexmap 2.5.0", "itoa", "ryu", "serde", @@ -3396,11 +3270,11 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.127" +version = "1.0.128" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8043c06d9f82bd7271361ed64f415fe5e12a77fdb52e573e7f06a516dea329ad" +checksum = "6ff5456707a1de34e7e37f2a6fd3d3f808c318259cbd01ab6377795054b483d8" dependencies = [ - "indexmap 2.4.0", + "indexmap 2.5.0", "itoa", "memchr", "ryu", @@ -3425,7 +3299,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -3459,7 +3333,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.4.0", + "indexmap 2.5.0", "serde", "serde_derive", "serde_json", @@ -3476,7 +3350,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -3552,16 +3426,6 @@ version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" -[[package]] -name = "socket2" -version = "0.4.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d" -dependencies = [ - "libc", - "winapi", -] - [[package]] name = "socket2" version = "0.5.7" @@ -3619,9 +3483,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.76" +version = "2.0.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578e081a14e0cefc3279b0472138c513f37b41a08d5a3cca9b6e4e8ceb6cd525" +checksum = "9f35bcdf61fd8e7be6caf75f429fdca8beb3ed76584befb503b1569faee373ed" dependencies = [ "proc-macro2", "quote", @@ -3637,7 +3501,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -3661,7 +3525,7 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" dependencies = [ - "bitflags 2.6.0", + "bitflags", "core-foundation", "system-configuration-sys", ] @@ -3706,9 +3570,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64" dependencies = [ "cfg-if", - "fastrand 2.1.1", + "fastrand", "once_cell", - "rustix 0.38.34", + "rustix", "windows-sys 0.59.0", ] @@ -3744,7 +3608,7 @@ checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -3815,9 +3679,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.39.3" +version = "1.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9babc99b9923bfa4804bd74722ff02c0381021eafa4db9949217e3be8e84fff5" +checksum = "e2b070231665d27ad9ec9b8df639893f46727666c6767db40317fbe920a5d998" dependencies = [ "backtrace", "bytes", @@ -3825,7 +3689,7 @@ dependencies = [ "mio", "pin-project-lite", "signal-hook-registry", - "socket2 0.5.7", + "socket2", "tokio-macros", "windows-sys 0.52.0", ] @@ -3838,7 +3702,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -3864,9 +3728,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.11" +version = "0.7.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf6b47b3771c49ac75ad09a6162f53ad4b8088b76ac60e8ec1455b31a189fe1" +checksum = "61e7c3654c13bcd040d4a03abee2c75b1d14a37b423cf5a813ceae1cc903ec6a" dependencies = [ "bytes", "futures-core", @@ -3884,7 +3748,7 @@ dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.22.20", + "toml_edit", ] [[package]] @@ -3896,28 +3760,17 @@ dependencies = [ "serde", ] -[[package]] -name = "toml_edit" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a8534fd7f78b5405e860340ad6575217ce99f38d4d5c8f2442cb5ecb50090e1" -dependencies = [ - "indexmap 2.4.0", - "toml_datetime", - "winnow 0.5.40", -] - [[package]] name = "toml_edit" version = "0.22.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "583c44c02ad26b0c3f3066fe629275e50627026c51ac2e595cca4c230ce1ce1d" dependencies = [ - "indexmap 2.4.0", + "indexmap 2.5.0", "serde", "serde_spanned", "toml_datetime", - "winnow 0.6.18", + "winnow", ] [[package]] @@ -3972,7 +3825,7 @@ dependencies = [ "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-tracker-torrent-repository", - "tower", + "tower 0.5.1", "tower-http", "trace", "tracing", @@ -4081,6 +3934,18 @@ dependencies = [ "tracing", ] +[[package]] +name = "tower" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2873938d487c3cfb9aed7546dc9f2711d867c9f90c46b889989a2cb84eba6b4f" +dependencies = [ + "pin-project-lite", + "tokio", + "tower-layer", + "tower-service", +] + [[package]] name = "tower-http" version = "0.5.2" @@ -4088,7 +3953,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ "async-compression", - "bitflags 2.6.0", + "bitflags", "bytes", "futures-core", "http", @@ -4146,7 +4011,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -4314,12 +4179,6 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "waker-fn" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" - [[package]] name = "walkdir" version = "2.5.0" @@ -4367,7 +4226,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", "wasm-bindgen-shared", ] @@ -4401,7 +4260,7 @@ checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4431,7 +4290,7 @@ dependencies = [ "either", "home", "once_cell", - "rustix 0.38.34", + "rustix", ] [[package]] @@ -4652,15 +4511,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "winnow" -version = "0.5.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" -dependencies = [ - "memchr", -] - [[package]] name = "winnow" version = "0.6.18" @@ -4703,7 +4553,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.76", + "syn 2.0.77", ] [[package]] @@ -4711,20 +4561,6 @@ name = "zeroize" version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.76", -] [[package]] name = "zstd" From ff836ed3885bfa0d12fde7c3832ace856f933a95 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 10 Sep 2024 09:30:41 +0100 Subject: [PATCH 0487/1297] fix: clippy error --- packages/clock/src/conv/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/clock/src/conv/mod.rs b/packages/clock/src/conv/mod.rs index f70950c38..894083061 100644 --- a/packages/clock/src/conv/mod.rs +++ b/packages/clock/src/conv/mod.rs @@ -4,6 +4,7 @@ use chrono::{DateTime, Utc}; use torrust_tracker_primitives::DurationSinceUnixEpoch; /// It converts a string in ISO 8601 format to a timestamp. +/// /// For example, the string `1970-01-01T00:00:00.000Z` which is the Unix Epoch /// will be converted to a timestamp of 0: `DurationSinceUnixEpoch::ZERO`. /// From 481d41333c5c3a4a6a0cc0b968d1b904bc9284ee Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 10 Sep 2024 13:29:50 +0100 Subject: [PATCH 0488/1297] feat: [#569] allow UDP clients to limit peers in response The UDP tracker announce response always include all peers available up to a maxium of 74 peers, ignoring the `num_want` param in the request described in: https://www.bittorrent.org/beps/bep_0015.html This change applies that limit only when is lower than then TORRENT_PEERS_LIMIT (74). --- src/core/mod.rs | 178 ++++++++++++++++++++--- src/servers/http/v1/services/announce.rs | 4 +- src/servers/http/v1/services/scrape.rs | 8 +- src/servers/udp/handlers.rs | 5 +- tests/servers/udp/contract.rs | 2 +- 5 files changed, 167 insertions(+), 30 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index cbdd7bcbc..1d2d856ba 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -448,6 +448,7 @@ pub mod torrent; pub mod peer_tests; +use std::cmp::max; use std::collections::HashMap; use std::net::IpAddr; use std::panic::Location; @@ -520,6 +521,38 @@ pub struct AnnounceData { pub policy: AnnouncePolicy, } +/// How many peers the peer announcing wants in the announce response. +#[derive(Clone, Debug, PartialEq, Default)] +pub enum PeersWanted { + /// The peer wants as many peers as possible in the announce response. + #[default] + All, + /// The peer only wants a certain amount of peers in the announce response. + Only { amount: usize }, +} + +impl PeersWanted { + fn limit(&self) -> usize { + match self { + PeersWanted::All => TORRENT_PEERS_LIMIT, + PeersWanted::Only { amount } => *amount, + } + } +} + +impl From for PeersWanted { + fn from(value: i32) -> Self { + if value > 0 { + match value.try_into() { + Ok(peers_wanted) => Self::Only { amount: peers_wanted }, + Err(_) => Self::All, + } + } else { + Self::All + } + } +} + /// Structure that holds the data returned by the `scrape` request. #[derive(Debug, PartialEq, Default)] pub struct ScrapeData { @@ -639,7 +672,13 @@ impl Tracker { /// # Context: Tracker /// /// BEP 03: [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html). - pub fn announce(&self, info_hash: &InfoHash, peer: &mut peer::Peer, remote_client_ip: &IpAddr) -> AnnounceData { + pub fn announce( + &self, + info_hash: &InfoHash, + peer: &mut peer::Peer, + remote_client_ip: &IpAddr, + peers_wanted: &PeersWanted, + ) -> AnnounceData { // code-review: maybe instead of mutating the peer we could just return // a tuple with the new peer and the announce data: (Peer, AnnounceData). // It could even be a different struct: `StoredPeer` or `PublicPeer`. @@ -661,7 +700,7 @@ impl Tracker { let stats = self.upsert_peer_and_get_stats(info_hash, peer); - let peers = self.get_peers_for(info_hash, peer); + let peers = self.get_peers_for(info_hash, peer, peers_wanted.limit()); AnnounceData { peers, @@ -713,16 +752,21 @@ impl Tracker { Ok(()) } - fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer) -> Vec> { + /// # Context: Tracker + /// + /// Get torrent peers for a given torrent and client. + /// + /// It filters out the client making the request. + fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { match self.torrents.get(info_hash) { None => vec![], - Some(entry) => entry.get_peers_for_client(&peer.peer_addr, Some(TORRENT_PEERS_LIMIT)), + Some(entry) => entry.get_peers_for_client(&peer.peer_addr, Some(max(limit, TORRENT_PEERS_LIMIT))), } } /// # Context: Tracker /// - /// Get all torrent peers for a given torrent + /// Get torrent peers for a given torrent. pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { match self.torrents.get(info_hash) { None => vec![], @@ -1199,6 +1243,7 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; @@ -1328,7 +1373,7 @@ mod tests { } #[tokio::test] - async fn it_should_return_all_the_peers_for_a_given_torrent() { + async fn it_should_return_the_peers_for_a_given_torrent() { let tracker = public_tracker(); let info_hash = sample_info_hash(); @@ -1341,8 +1386,51 @@ mod tests { assert_eq!(peers, vec![Arc::new(peer)]); } + /// It generates a peer id from a number where the number is the last + /// part of the peer ID. For example, for `12` it returns + /// `-qB00000000000000012`. + fn numeric_peer_id(two_digits_value: i32) -> PeerId { + // Format idx as a string with leading zeros, ensuring it has exactly 2 digits + let idx_str = format!("{two_digits_value:02}"); + + // Create the base part of the peer ID. + let base = b"-qB00000000000000000"; + + // Concatenate the base with idx bytes, ensuring the total length is 20 bytes. + let mut peer_id_bytes = [0u8; 20]; + peer_id_bytes[..base.len()].copy_from_slice(base); + peer_id_bytes[base.len() - idx_str.len()..].copy_from_slice(idx_str.as_bytes()); + + PeerId(peer_id_bytes) + } + #[tokio::test] - async fn it_should_return_all_the_peers_for_a_given_torrent_excluding_a_given_peer() { + async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { + let tracker = public_tracker(); + + let info_hash = sample_info_hash(); + + for idx in 1..=75 { + let peer = Peer { + peer_id: numeric_peer_id(idx), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + }; + + tracker.upsert_peer_and_get_stats(&info_hash, &peer); + } + + let peers = tracker.get_torrent_peers(&info_hash); + + assert_eq!(peers.len(), 74); + } + + #[tokio::test] + async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { let tracker = public_tracker(); let info_hash = sample_info_hash(); @@ -1350,11 +1438,41 @@ mod tests { tracker.upsert_peer_and_get_stats(&info_hash, &peer); - let peers = tracker.get_peers_for(&info_hash, &peer); + let peers = tracker.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); assert_eq!(peers, vec![]); } + #[tokio::test] + async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { + let tracker = public_tracker(); + + let info_hash = sample_info_hash(); + + let excluded_peer = sample_peer(); + + tracker.upsert_peer_and_get_stats(&info_hash, &excluded_peer); + + // Add 74 peers + for idx in 2..=75 { + let peer = Peer { + peer_id: numeric_peer_id(idx), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + }; + + tracker.upsert_peer_and_get_stats(&info_hash, &peer); + } + + let peers = tracker.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); + + assert_eq!(peers.len(), 74); + } + #[tokio::test] async fn it_should_return_the_torrent_metrics() { let tracker = public_tracker(); @@ -1409,6 +1527,7 @@ mod tests { use crate::core::tests::the_tracker::{ peer_ip, public_tracker, sample_info_hash, sample_peer, sample_peer_1, sample_peer_2, }; + use crate::core::PeersWanted; mod should_assign_the_ip_to_the_peer { @@ -1514,7 +1633,7 @@ mod tests { let mut peer = sample_peer(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()); + let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); assert_eq!(announce_data.peers, vec![]); } @@ -1524,10 +1643,15 @@ mod tests { let tracker = public_tracker(); let mut previously_announced_peer = sample_peer_1(); - tracker.announce(&sample_info_hash(), &mut previously_announced_peer, &peer_ip()); + tracker.announce( + &sample_info_hash(), + &mut previously_announced_peer, + &peer_ip(), + &PeersWanted::All, + ); let mut peer = sample_peer_2(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()); + let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); assert_eq!(announce_data.peers, vec![Arc::new(previously_announced_peer)]); } @@ -1537,6 +1661,7 @@ mod tests { use crate::core::tests::the_tracker::{ completed_peer, leecher, peer_ip, public_tracker, sample_info_hash, seeder, started_peer, }; + use crate::core::PeersWanted; #[tokio::test] async fn when_the_peer_is_a_seeder() { @@ -1544,7 +1669,7 @@ mod tests { let mut peer = seeder(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()); + let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); assert_eq!(announce_data.stats.complete, 1); } @@ -1555,7 +1680,7 @@ mod tests { let mut peer = leecher(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()); + let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); assert_eq!(announce_data.stats.incomplete, 1); } @@ -1566,10 +1691,11 @@ mod tests { // We have to announce with "started" event because peer does not count if peer was not previously known let mut started_peer = started_peer(); - tracker.announce(&sample_info_hash(), &mut started_peer, &peer_ip()); + tracker.announce(&sample_info_hash(), &mut started_peer, &peer_ip(), &PeersWanted::All); let mut completed_peer = completed_peer(); - let announce_data = tracker.announce(&sample_info_hash(), &mut completed_peer, &peer_ip()); + let announce_data = + tracker.announce(&sample_info_hash(), &mut completed_peer, &peer_ip(), &PeersWanted::All); assert_eq!(announce_data.stats.downloaded, 1); } @@ -1583,7 +1709,7 @@ mod tests { use torrust_tracker_primitives::info_hash::InfoHash; use crate::core::tests::the_tracker::{complete_peer, incomplete_peer, public_tracker}; - use crate::core::{ScrapeData, SwarmMetadata}; + use crate::core::{PeersWanted, ScrapeData, SwarmMetadata}; #[tokio::test] async fn it_should_return_a_zeroed_swarm_metadata_for_the_requested_file_if_the_tracker_does_not_have_that_torrent( @@ -1609,11 +1735,21 @@ mod tests { // Announce a "complete" peer for the torrent let mut complete_peer = complete_peer(); - tracker.announce(&info_hash, &mut complete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10))); + tracker.announce( + &info_hash, + &mut complete_peer, + &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10)), + &PeersWanted::All, + ); // Announce an "incomplete" peer for the torrent let mut incomplete_peer = incomplete_peer(); - tracker.announce(&info_hash, &mut incomplete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11))); + tracker.announce( + &info_hash, + &mut incomplete_peer, + &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11)), + &PeersWanted::All, + ); // Scrape let scrape_data = tracker.scrape(&vec![info_hash]).await; @@ -1740,7 +1876,7 @@ mod tests { use crate::core::tests::the_tracker::{ complete_peer, incomplete_peer, peer_ip, sample_info_hash, whitelisted_tracker, }; - use crate::core::ScrapeData; + use crate::core::{PeersWanted, ScrapeData}; #[test] fn it_should_be_able_to_build_a_zeroed_scrape_data_for_a_list_of_info_hashes() { @@ -1761,11 +1897,11 @@ mod tests { let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); let mut peer = incomplete_peer(); - tracker.announce(&info_hash, &mut peer, &peer_ip()); + tracker.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); // Announce twice to force non zeroed swarm metadata let mut peer = complete_peer(); - tracker.announce(&info_hash, &mut peer, &peer_ip()); + tracker.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); let scrape_data = tracker.scrape(&vec![info_hash]).await; diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 6b7f8af5a..a58df4e18 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -14,7 +14,7 @@ use std::sync::Arc; use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer; -use crate::core::{statistics, AnnounceData, Tracker}; +use crate::core::{statistics, AnnounceData, PeersWanted, Tracker}; /// The HTTP tracker `announce` service. /// @@ -30,7 +30,7 @@ pub async fn invoke(tracker: Arc, info_hash: InfoHash, peer: &mut peer: let original_peer_ip = peer.peer_addr.ip(); // The tracker could change the original peer ip - let announce_data = tracker.announce(&info_hash, peer, &original_peer_ip); + let announce_data = tracker.announce(&info_hash, peer, &original_peer_ip, &PeersWanted::All); match original_peer_ip { IpAddr::V4(_) => { diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 42fe4b518..0d561c7bc 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -103,7 +103,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; - use crate::core::{statistics, ScrapeData, Tracker}; + use crate::core::{statistics, PeersWanted, ScrapeData, Tracker}; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ public_tracker, sample_info_hash, sample_info_hashes, sample_peer, @@ -119,7 +119,7 @@ mod tests { // Announce a new peer to force scrape data to contain not zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); - tracker.announce(&info_hash, &mut peer, &original_peer_ip); + tracker.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); let scrape_data = invoke(&tracker, &info_hashes, &original_peer_ip).await; @@ -194,7 +194,7 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_test_helpers::configuration; - use crate::core::{statistics, ScrapeData, Tracker}; + use crate::core::{statistics, PeersWanted, ScrapeData, Tracker}; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ public_tracker, sample_info_hash, sample_info_hashes, sample_peer, @@ -210,7 +210,7 @@ mod tests { // Announce a new peer to force scrape data to contain not zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); - tracker.announce(&info_hash, &mut peer, &original_peer_ip); + tracker.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); let scrape_data = fake(&tracker, &info_hashes, &original_peer_ip).await; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 373fb9c14..69a427e0e 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -18,7 +18,7 @@ use zerocopy::network_endian::I32; use super::connection_cookie::{check, from_connection_id, into_connection_id, make}; use super::RawRequest; -use crate::core::{statistics, ScrapeData, Tracker}; +use crate::core::{statistics, PeersWanted, ScrapeData, Tracker}; use crate::servers::udp::error::Error; use crate::servers::udp::logging::{log_bad_request, log_error_response, log_request, log_response}; use crate::servers::udp::peer_builder; @@ -162,8 +162,9 @@ pub async fn handle_announce( })?; let mut peer = peer_builder::from_request(announce_request, &remote_client_ip); + let peers_wanted: PeersWanted = i32::from(announce_request.peers_wanted.0).into(); - let response = tracker.announce(&info_hash, &mut peer, &remote_client_ip); + let response = tracker.announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted); match remote_client_ip { IpAddr::V4(_) => { diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 91f4c4e06..1f9b71b62 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -159,7 +159,7 @@ mod receiving_an_announce_request { Err(err) => panic!("{err}"), }; - println!("test response {response:?}"); + // println!("test response {response:?}"); assert!(is_ipv4_announce_response(&response)); } From 084879e89f4632bd395dbca35460c08c03abdae9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 10 Sep 2024 18:49:25 +0100 Subject: [PATCH 0489/1297] feat: [#569] numwant HTTP tracker announce param It allows HTTP clients to limit peers in the announce response with the `numwant` GET param. --- src/core/mod.rs | 10 ++++ .../http/v1/extractors/announce_request.rs | 3 +- src/servers/http/v1/handlers/announce.rs | 9 +++- src/servers/http/v1/requests/announce.rs | 47 +++++++++++++++++-- src/servers/http/v1/services/announce.rs | 18 ++++--- tests/servers/http/requests/announce.rs | 12 +++++ tests/servers/http/v1/contract.rs | 23 +++++++++ 7 files changed, 110 insertions(+), 12 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 1d2d856ba..f12eb9a3d 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -532,6 +532,16 @@ pub enum PeersWanted { } impl PeersWanted { + #[must_use] + pub fn only(limit: u32) -> Self { + let amount: usize = match limit.try_into() { + Ok(amount) => amount, + Err(_) => TORRENT_PEERS_LIMIT, + }; + + Self::Only { amount } + } + fn limit(&self) -> usize { match self { PeersWanted::All => TORRENT_PEERS_LIMIT, diff --git a/src/servers/http/v1/extractors/announce_request.rs b/src/servers/http/v1/extractors/announce_request.rs index b1d820598..324e91bf2 100644 --- a/src/servers/http/v1/extractors/announce_request.rs +++ b/src/servers/http/v1/extractors/announce_request.rs @@ -111,7 +111,7 @@ mod tests { #[test] fn it_should_extract_the_announce_request_from_the_url_query_params() { - let raw_query = "info_hash=%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0&peer_addr=2.137.87.41&downloaded=0&uploaded=0&peer_id=-qB00000000000000001&port=17548&left=0&event=completed&compact=0"; + let raw_query = "info_hash=%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0&peer_addr=2.137.87.41&downloaded=0&uploaded=0&peer_id=-qB00000000000000001&port=17548&left=0&event=completed&compact=0&numwant=50"; let announce = extract_announce_from(Some(raw_query)).unwrap(); @@ -126,6 +126,7 @@ mod tests { left: Some(NumberOfBytes::new(0)), event: Some(Event::Completed), compact: Some(Compact::NotAccepted), + numwant: Some(50), } ); } diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index ee70b7841..1c7796fca 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -16,7 +16,7 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::peer; use crate::core::auth::Key; -use crate::core::{AnnounceData, Tracker}; +use crate::core::{AnnounceData, PeersWanted, Tracker}; use crate::servers::http::v1::extractors::announce_request::ExtractRequest; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; @@ -110,8 +110,12 @@ async fn handle_announce( }; let mut peer = peer_from_request(announce_request, &peer_ip); + let peers_wanted = match announce_request.numwant { + Some(numwant) => PeersWanted::only(numwant), + None => PeersWanted::All, + }; - let announce_data = services::announce::invoke(tracker.clone(), announce_request.info_hash, &mut peer).await; + let announce_data = services::announce::invoke(tracker.clone(), announce_request.info_hash, &mut peer, &peers_wanted).await; Ok(announce_data) } @@ -205,6 +209,7 @@ mod tests { left: None, event: None, compact: None, + numwant: None, } } diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index 3253a07c8..b432d3478 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -24,6 +24,7 @@ const UPLOADED: &str = "uploaded"; const LEFT: &str = "left"; const EVENT: &str = "event"; const COMPACT: &str = "compact"; +const NUMWANT: &str = "numwant"; /// The `Announce` request. Fields use the domain types after parsing the /// query params of the request. @@ -43,7 +44,8 @@ const COMPACT: &str = "compact"; /// uploaded: Some(NumberOfBytes::new(1)), /// left: Some(NumberOfBytes::new(1)), /// event: Some(Event::Started), -/// compact: Some(Compact::NotAccepted) +/// compact: Some(Compact::NotAccepted), +/// numwant: Some(50) /// }; /// ``` /// @@ -59,8 +61,10 @@ pub struct Announce { // Mandatory params /// The `InfoHash` of the torrent. pub info_hash: InfoHash, + /// The `PeerId` of the peer. pub peer_id: PeerId, + /// The port of the peer. pub port: u16, @@ -80,6 +84,10 @@ pub struct Announce { /// Whether the response should be in compact mode or not. pub compact: Option, + + /// Number of peers that the client would receive from the tracker. The + /// value is permitted to be zero. + pub numwant: Option, } /// Errors that can occur when parsing the `Announce` request. @@ -244,6 +252,7 @@ impl TryFrom for Announce { left: extract_left(&query)?, event: extract_event(&query)?, compact: extract_compact(&query)?, + numwant: extract_numwant(&query)?, }) } } @@ -350,6 +359,22 @@ fn extract_compact(query: &Query) -> Result, ParseAnnounceQueryE } } +fn extract_numwant(query: &Query) -> Result, ParseAnnounceQueryError> { + print!("numwant {query:#?}"); + + match query.get_param(NUMWANT) { + Some(raw_param) => match u32::from_str(&raw_param) { + Ok(numwant) => Ok(Some(numwant)), + Err(_) => Err(ParseAnnounceQueryError::InvalidParam { + param_name: NUMWANT.to_owned(), + param_value: raw_param.clone(), + location: Location::caller(), + }), + }, + None => Ok(None), + } +} + #[cfg(test)] mod tests { @@ -360,7 +385,7 @@ mod tests { use crate::servers::http::v1::query::Query; use crate::servers::http::v1::requests::announce::{ - Announce, Compact, Event, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, PEER_ID, PORT, UPLOADED, + Announce, Compact, Event, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, NUMWANT, PEER_ID, PORT, UPLOADED, }; #[test] @@ -387,6 +412,7 @@ mod tests { left: None, event: None, compact: None, + numwant: None, } ); } @@ -402,6 +428,7 @@ mod tests { (LEFT, "3"), (EVENT, "started"), (COMPACT, "0"), + (NUMWANT, "50"), ]) .to_string(); @@ -420,6 +447,7 @@ mod tests { left: Some(NumberOfBytes::new(3)), event: Some(Event::Started), compact: Some(Compact::NotAccepted), + numwant: Some(50), } ); } @@ -428,7 +456,7 @@ mod tests { use crate::servers::http::v1::query::Query; use crate::servers::http::v1::requests::announce::{ - Announce, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, PEER_ID, PORT, UPLOADED, + Announce, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, NUMWANT, PEER_ID, PORT, UPLOADED, }; #[test] @@ -547,6 +575,19 @@ mod tests { assert!(Announce::try_from(raw_query.parse::().unwrap()).is_err()); } + + #[test] + fn it_should_fail_if_the_numwant_param_is_invalid() { + let raw_query = Query::from(vec![ + (INFO_HASH, "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0"), + (PEER_ID, "-qB00000000000000001"), + (PORT, "17548"), + (NUMWANT, "-1"), + ]) + .to_string(); + + assert!(Announce::try_from(raw_query.parse::().unwrap()).is_err()); + } } } } diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index a58df4e18..9c5dfdad2 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -26,11 +26,16 @@ use crate::core::{statistics, AnnounceData, PeersWanted, Tracker}; /// > **NOTICE**: as the HTTP tracker does not requires a connection request /// > like the UDP tracker, the number of TCP connections is incremented for /// > each `announce` request. -pub async fn invoke(tracker: Arc, info_hash: InfoHash, peer: &mut peer::Peer) -> AnnounceData { +pub async fn invoke( + tracker: Arc, + info_hash: InfoHash, + peer: &mut peer::Peer, + peers_wanted: &PeersWanted, +) -> AnnounceData { let original_peer_ip = peer.peer_addr.ip(); // The tracker could change the original peer ip - let announce_data = tracker.announce(&info_hash, peer, &original_peer_ip, &PeersWanted::All); + let announce_data = tracker.announce(&info_hash, peer, &original_peer_ip, peers_wanted); match original_peer_ip { IpAddr::V4(_) => { @@ -100,7 +105,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; - use crate::core::{statistics, AnnounceData, Tracker}; + use crate::core::{statistics, AnnounceData, PeersWanted, Tracker}; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; @@ -110,7 +115,7 @@ mod tests { let mut peer = sample_peer(); - let announce_data = invoke(tracker.clone(), sample_info_hash(), &mut peer).await; + let announce_data = invoke(tracker.clone(), sample_info_hash(), &mut peer, &PeersWanted::All).await; let expected_announce_data = AnnounceData { peers: vec![], @@ -146,7 +151,7 @@ mod tests { let mut peer = sample_peer_using_ipv4(); - let _announce_data = invoke(tracker, sample_info_hash(), &mut peer).await; + let _announce_data = invoke(tracker, sample_info_hash(), &mut peer, &PeersWanted::All).await; } fn tracker_with_an_ipv6_external_ip(stats_event_sender: Box) -> Tracker { @@ -185,6 +190,7 @@ mod tests { tracker_with_an_ipv6_external_ip(stats_event_sender).into(), sample_info_hash(), &mut peer, + &PeersWanted::All, ) .await; } @@ -211,7 +217,7 @@ mod tests { let mut peer = sample_peer_using_ipv6(); - let _announce_data = invoke(tracker, sample_info_hash(), &mut peer).await; + let _announce_data = invoke(tracker, sample_info_hash(), &mut peer, &PeersWanted::All).await; } } } diff --git a/tests/servers/http/requests/announce.rs b/tests/servers/http/requests/announce.rs index bcbb36852..fa20553d0 100644 --- a/tests/servers/http/requests/announce.rs +++ b/tests/servers/http/requests/announce.rs @@ -18,6 +18,7 @@ pub struct Query { pub left: BaseTenASCII, pub event: Option, pub compact: Option, + pub numwant: Option, } impl fmt::Display for Query { @@ -98,6 +99,7 @@ impl QueryBuilder { left: 0, event: Some(Event::Completed), compact: Some(Compact::NotAccepted), + numwant: None, }; Self { announce_query: default_announce_query, @@ -149,7 +151,9 @@ impl QueryBuilder { /// left=0 /// event=completed /// compact=0 +/// numwant=50 /// ``` +#[derive(Debug)] pub struct QueryParams { pub info_hash: Option, pub peer_addr: Option, @@ -160,6 +164,7 @@ pub struct QueryParams { pub left: Option, pub event: Option, pub compact: Option, + pub numwant: Option, } impl std::fmt::Display for QueryParams { @@ -193,6 +198,9 @@ impl std::fmt::Display for QueryParams { if let Some(compact) = &self.compact { params.push(("compact", compact)); } + if let Some(numwant) = &self.numwant { + params.push(("numwant", numwant)); + } let query = params .iter() @@ -208,6 +216,7 @@ impl QueryParams { pub fn from(announce_query: &Query) -> Self { let event = announce_query.event.as_ref().map(std::string::ToString::to_string); let compact = announce_query.compact.as_ref().map(std::string::ToString::to_string); + let numwant = announce_query.numwant.map(|numwant| numwant.to_string()); Self { info_hash: Some(percent_encode_byte_array(&announce_query.info_hash)), @@ -219,6 +228,7 @@ impl QueryParams { left: Some(announce_query.left.to_string()), event, compact, + numwant, } } @@ -241,6 +251,7 @@ impl QueryParams { self.left = None; self.event = None; self.compact = None; + self.numwant = None; } pub fn set(&mut self, param_name: &str, param_value: &str) { @@ -254,6 +265,7 @@ impl QueryParams { "left" => self.left = Some(param_value.to_string()), "event" => self.event = Some(param_value.to_string()), "compact" => self.compact = Some(param_value.to_string()), + "numwant" => self.numwant = Some(param_value.to_string()), &_ => panic!("Invalid param name for announce query"), } } diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 41e92c9d6..405a35dc5 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -448,6 +448,29 @@ mod for_all_config_modes { env.stop().await; } + #[tokio::test] + async fn should_fail_when_the_numwant_param_is_invalid() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let mut params = QueryBuilder::default().query().params(); + + let invalid_values = ["-1", "1.1", "a"]; + + for invalid_value in invalid_values { + params.set("numwant", invalid_value); + + let response = Client::new(*env.bind_address()).get(&format!("announce?{params}")).await; + + assert_bad_announce_request_error_response(response, "invalid param value").await; + } + + env.stop().await; + } + #[tokio::test] async fn should_return_no_peers_if_the_announced_peer_is_the_first_one() { INIT.call_once(|| { From c49438fc72711c2e82a1bbe76ecf02b45a870597 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 11 Sep 2024 09:17:11 +0100 Subject: [PATCH 0490/1297] fix: remove debugging print --- src/servers/http/v1/requests/announce.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index b432d3478..029bdbc01 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -360,8 +360,6 @@ fn extract_compact(query: &Query) -> Result, ParseAnnounceQueryE } fn extract_numwant(query: &Query) -> Result, ParseAnnounceQueryError> { - print!("numwant {query:#?}"); - match query.get_param(NUMWANT) { Some(raw_param) => match u32::from_str(&raw_param) { Ok(numwant) => Ok(Some(numwant)), From dbee825a47e7059af79b874f5fa83108b74bd647 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 11 Sep 2024 10:45:50 +0100 Subject: [PATCH 0491/1297] fix: [#1037] wrong req type name in tracker checker outout Fixed ouoput: ```output $ TORRUST_CHECKER_CONFIG='{ "udp_trackers": ["127.0.0.1:6969"], "http_trackers": [], "health_checks": [] }' cargo run --bin tracker_checker Compiling torrust-tracker v3.0.0-rc.1-develop (/home/josecelano/Documents/git/committer/me/github/torrust/torrust-tracker) Finished `dev` profile [optimized + debuginfo] target(s) in 15.42s Running `target/debug/tracker_checker` 2024-09-11T09:44:57.432395Z INFO torrust_tracker::console::clients::checker::service: Running checks for trackers ... [ { "Udp": { "Ok": { "remote_addr": "127.0.0.1:6969", "results": [ [ "Setup", { "Ok": null } ], [ "Connect", { "Ok": null } ], [ "Announce", { "Ok": null } ], [ "Scrape", { "Ok": null } ] ] } } } ] ``` --- src/console/clients/checker/checks/udp.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/console/clients/checker/checks/udp.rs b/src/console/clients/checker/checks/udp.rs index dd9afa47c..3ba26ceda 100644 --- a/src/console/clients/checker/checks/udp.rs +++ b/src/console/clients/checker/checks/udp.rs @@ -83,7 +83,7 @@ pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec Date: Thu, 12 Sep 2024 16:25:42 +0100 Subject: [PATCH 0492/1297] feat: [#675] tracker checker supports more service address formats All the following URL for UDP trackers are allow now: ```console TORRUST_CHECKER_CONFIG='{ "udp_trackers": [ "127.0.0.1:6969", "127.0.0.1:6969/", "127.0.0.1:6969/announce", "localhost:6969", "localhost:6969/", "localhost:6969/announce", "udp://127.0.0.1:6969", "udp://127.0.0.1:6969/", "udp://127.0.0.1:6969/announce", "udp://localhost:6969", "udp://localhost:6969/", "udp://localhost:6969/announce" ], "http_trackers": [], "health_checks": [] }' cargo run --bin tracker_checker ``` NOTICE: the client will resolve the domain to a socket address if needed. --- src/console/clients/checker/checks/udp.rs | 43 +++++- src/console/clients/checker/config.rs | 165 +++++++++++++++++----- 2 files changed, 169 insertions(+), 39 deletions(-) diff --git a/src/console/clients/checker/checks/udp.rs b/src/console/clients/checker/checks/udp.rs index 3ba26ceda..4044b4c52 100644 --- a/src/console/clients/checker/checks/udp.rs +++ b/src/console/clients/checker/checks/udp.rs @@ -4,6 +4,7 @@ use std::time::Duration; use aquatic_udp_protocol::TransactionId; use hex_literal::hex; use serde::Serialize; +use url::Url; use crate::console::clients::udp::checker::Client; use crate::console::clients::udp::Error; @@ -23,20 +24,22 @@ pub enum Check { } #[allow(clippy::missing_panics_doc)] -pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec> { +pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec> { let mut results = Vec::default(); tracing::debug!("UDP trackers ..."); let info_hash = aquatic_udp_protocol::InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237 - for remote_addr in udp_trackers { + for remote_url in udp_trackers { + let remote_addr = resolve_socket_addr(&remote_url); + let mut checks = Checks { remote_addr, results: Vec::default(), }; - tracing::debug!("UDP tracker: {:?}", remote_addr); + tracing::debug!("UDP tracker: {:?}", remote_url); // Setup let client = match Client::new(remote_addr, timeout).await { @@ -95,3 +98,37 @@ pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec SocketAddr { + let socket_addr = url.socket_addrs(|| None).unwrap(); + *socket_addr.first().unwrap() +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + + use url::Url; + + use crate::console::clients::checker::checks::udp::resolve_socket_addr; + + #[test] + fn it_should_resolve_the_socket_address_for_udp_scheme_urls_containing_a_domain() { + let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); + + assert!( + socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) + || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) + ); + } + + #[test] + fn it_should_resolve_the_socket_address_for_udp_scheme_urls_containing_an_ip() { + let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); + + assert!( + socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) + || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) + ); + } +} diff --git a/src/console/clients/checker/config.rs b/src/console/clients/checker/config.rs index 6e44d889b..78c5926b8 100644 --- a/src/console/clients/checker/config.rs +++ b/src/console/clients/checker/config.rs @@ -1,6 +1,5 @@ use std::error::Error; use std::fmt; -use std::net::SocketAddr; use reqwest::Url as ServiceUrl; use serde::Deserialize; @@ -31,7 +30,7 @@ struct PlainConfiguration { /// Validated configuration pub struct Configuration { - pub udp_trackers: Vec, + pub udp_trackers: Vec, pub http_trackers: Vec, pub health_checks: Vec, } @@ -62,7 +61,8 @@ impl TryFrom for Configuration { let udp_trackers = plain_config .udp_trackers .into_iter() - .map(|s| s.parse::().map_err(ConfigurationError::InvalidUdpAddress)) + .map(|s| if s.starts_with("udp://") { s } else { format!("udp://{s}") }) + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) .collect::, _>>()?; let http_trackers = plain_config @@ -87,68 +87,161 @@ impl TryFrom for Configuration { #[cfg(test)] mod tests { - use std::net::{IpAddr, Ipv4Addr}; - use super::*; #[test] fn configuration_should_be_build_from_plain_serializable_configuration() { let dto = PlainConfiguration { - udp_trackers: vec!["127.0.0.1:8080".to_string()], + udp_trackers: vec!["udp://127.0.0.1:8080".to_string()], http_trackers: vec!["http://127.0.0.1:8080".to_string()], health_checks: vec!["http://127.0.0.1:8080/health".to_string()], }; let config = Configuration::try_from(dto).expect("A valid configuration"); - assert_eq!( - config.udp_trackers, - vec![SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080)] - ); + assert_eq!(config.udp_trackers, vec![ServiceUrl::parse("udp://127.0.0.1:8080").unwrap()]); + assert_eq!( config.http_trackers, vec![ServiceUrl::parse("http://127.0.0.1:8080").unwrap()] ); + assert_eq!( config.health_checks, vec![ServiceUrl::parse("http://127.0.0.1:8080/health").unwrap()] ); } - mod building_configuration_from_plan_configuration { - use crate::console::clients::checker::config::{Configuration, PlainConfiguration}; + mod building_configuration_from_plain_configuration_for { + + mod udp_trackers { + use crate::console::clients::checker::config::{Configuration, PlainConfiguration, ServiceUrl}; + + /* The plain configuration should allow UDP URLs with: + + - IP or domain. + - With or without scheme. + - With or without `announce` suffix. + - With or without `/` at the end of the authority section (with empty path). + + For example: + + 127.0.0.1:6969 + 127.0.0.1:6969/ + 127.0.0.1:6969/announce + + localhost:6969 + localhost:6969/ + localhost:6969/announce + + udp://127.0.0.1:6969 + udp://127.0.0.1:6969/ + udp://127.0.0.1:6969/announce + + udp://localhost:6969 + udp://localhost:6969/ + udp://localhost:6969/announce + + */ - #[test] - fn it_should_fail_when_a_tracker_udp_address_is_invalid() { - let plain_config = PlainConfiguration { - udp_trackers: vec!["invalid_address".to_string()], - http_trackers: vec![], - health_checks: vec![], - }; + #[test] + fn it_should_fail_when_a_tracker_udp_url_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["invalid URL".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; - assert!(Configuration::try_from(plain_config).is_err()); + assert!(Configuration::try_from(plain_config).is_err()); + } + + #[test] + fn it_should_add_the_udp_scheme_to_the_udp_url_when_it_is_missing() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:6969".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!(config.udp_trackers[0], "udp://127.0.0.1:6969".parse::().unwrap()); + } + + #[test] + fn it_should_allow_using_domains() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["udp://localhost:6969".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!(config.udp_trackers[0], "udp://localhost:6969".parse::().unwrap()); + } + + #[test] + fn it_should_allow_the_url_to_have_an_empty_path() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:6969/".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!(config.udp_trackers[0], "udp://127.0.0.1:6969/".parse::().unwrap()); + } + + #[test] + fn it_should_allow_the_url_to_contain_a_path() { + // This is the common format for UDP tracker URLs: + // udp://domain.com:6969/announce + + let plain_config = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:6969/announce".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!( + config.udp_trackers[0], + "udp://127.0.0.1:6969/announce".parse::().unwrap() + ); + } } - #[test] - fn it_should_fail_when_a_tracker_http_address_is_invalid() { - let plain_config = PlainConfiguration { - udp_trackers: vec![], - http_trackers: vec!["not_a_url".to_string()], - health_checks: vec![], - }; + mod http_trackers { + use crate::console::clients::checker::config::{Configuration, PlainConfiguration}; + + #[test] + fn it_should_fail_when_a_tracker_http_url_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec!["invalid URL".to_string()], + health_checks: vec![], + }; - assert!(Configuration::try_from(plain_config).is_err()); + assert!(Configuration::try_from(plain_config).is_err()); + } } - #[test] - fn it_should_fail_when_a_health_check_http_address_is_invalid() { - let plain_config = PlainConfiguration { - udp_trackers: vec![], - http_trackers: vec![], - health_checks: vec!["not_a_url".to_string()], - }; + mod health_checks { + use crate::console::clients::checker::config::{Configuration, PlainConfiguration}; + + #[test] + fn it_should_fail_when_a_health_check_http_url_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec![], + health_checks: vec!["invalid URL".to_string()], + }; - assert!(Configuration::try_from(plain_config).is_err()); + assert!(Configuration::try_from(plain_config).is_err()); + } } } } From faee02f257812571f7635b2432e4d7a297958c96 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 12 Sep 2024 17:25:53 +0100 Subject: [PATCH 0493/1297] feat: [#675] tracker checker (HTTP tracker) supports more service address formats Now it supports a path prefix. It will be remove by the client to build the "scrape" URLs. This type of URL is very common in tracker lists like in https://newtrackon.com/. ```console TORRUST_CHECKER_CONFIG='{ "udp_trackers": [], "http_trackers": [ "http://127.0.0.1:7070", "http://127.0.0.1:7070/", "http://127.0.0.1:7070/announce" ], "health_checks": [] }' cargo run --bin tracker_checker ``` --- src/console/clients/checker/checks/http.rs | 7 ++-- src/console/clients/checker/config.rs | 37 +++++++++++++++++++++- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/src/console/clients/checker/checks/http.rs b/src/console/clients/checker/checks/http.rs index 8abbeb669..0904f4e6e 100644 --- a/src/console/clients/checker/checks/http.rs +++ b/src/console/clients/checker/checks/http.rs @@ -28,6 +28,9 @@ pub async fn run(http_trackers: Vec, timeout: Duration) -> Vec, timeout: Duration) -> Vec().unwrap() + ); + } + + #[test] + fn it_should_allow_the_url_to_contain_an_empty_path() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec!["http://127.0.0.1:7070/".to_string()], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!( + config.http_trackers[0], + "http://127.0.0.1:7070/".parse::().unwrap() + ); + } } mod health_checks { From bdb04198d57a9d415e9da7f1dc8551266d2a2864 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 23 Sep 2024 15:38:18 +0100 Subject: [PATCH 0494/1297] chore(deps): update dependencies ```output cargo update Updating crates.io index Locking 26 packages to latest compatible versions Updating anyhow v1.0.87 -> v1.0.89 Updating aws-lc-sys v0.21.1 -> v0.21.2 Updating axum v0.7.5 -> v0.7.6 Updating axum-core v0.4.3 -> v0.4.4 Updating axum-extra v0.9.3 -> v0.9.4 Updating axum-macros v0.4.1 -> v0.4.2 Updating bytes v1.7.1 -> v1.7.2 Updating cc v1.1.18 -> v1.1.21 Updating clap v4.5.17 -> v4.5.18 Updating clap_builder v4.5.17 -> v4.5.18 Updating clap_derive v4.5.13 -> v4.5.18 Updating iana-time-zone v0.1.60 -> v0.1.61 Updating local-ip-address v0.6.2 -> v0.6.3 Updating pkg-config v0.3.30 -> v0.3.31 Updating redox_syscall v0.5.3 -> v0.5.4 Updating rustix v0.38.36 -> v0.38.37 Updating rustls v0.23.12 -> v0.23.13 Updating security-framework-sys v2.11.1 -> v2.12.0 Updating simdutf8 v0.1.4 -> v0.1.5 Updating thiserror v1.0.63 -> v1.0.64 Updating thiserror-impl v1.0.63 -> v1.0.64 Updating toml_edit v0.22.20 -> v0.22.21 Updating tower-http v0.5.2 -> v0.6.1 Updating unicode-ident v1.0.12 -> v1.0.13 Updating unicode-normalization v0.1.23 -> v0.1.24 Updating unicode-xid v0.2.5 -> v0.2.6 Removing windows-sys v0.48.0 Removing windows-targets v0.48.5 Removing windows_aarch64_gnullvm v0.48.5 Removing windows_aarch64_msvc v0.48.5 Removing windows_i686_gnu v0.48.5 Removing windows_i686_msvc v0.48.5 Removing windows_x86_64_gnu v0.48.5 Removing windows_x86_64_gnullvm v0.48.5 Removing windows_x86_64_msvc v0.48.5 ``` --- Cargo.lock | 218 +++++++++++++++++++---------------------------------- 1 file changed, 77 insertions(+), 141 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7204fd612..97cdbb551 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -142,9 +142,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.87" +version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10f00e1f6e58a40e807377c75c6a7f97bf9044fab57816f2414e6f5f4499d7b8" +checksum = "86fdf8605db99b54d3cd748a44c6d04df638eb5dafb219b135d0149bd0db01f6" [[package]] name = "aquatic_peer_id" @@ -371,9 +371,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.21.1" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "234314bd569802ec87011d653d6815c6d7b9ffb969e9fee5b8b20ef860e8dce9" +checksum = "b3ddc4a5b231dd6958b140ff3151b6412b3f4321fab354f399eec8f14b06df62" dependencies = [ "bindgen 0.69.4", "cc", @@ -386,9 +386,9 @@ dependencies = [ [[package]] name = "axum" -version = "0.7.5" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a6c9af12842a67734c9a2e355436e5d03b22383ed60cf13cd0c18fbfe3dcbcf" +checksum = "8f43644eed690f5374f1af436ecd6aea01cd201f6fbdf0178adaf6907afb2cec" dependencies = [ "async-trait", "axum-core", @@ -413,7 +413,7 @@ dependencies = [ "serde_urlencoded", "sync_wrapper 1.0.1", "tokio", - "tower 0.4.13", + "tower 0.5.1", "tower-layer", "tower-service", "tracing", @@ -432,9 +432,9 @@ dependencies = [ [[package]] name = "axum-core" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a15c63fd72d41492dc4f497196f5da1fb04fb7529e631d73630d1b491e47a2e3" +checksum = "5e6b8ba012a258d63c9adfa28b9ddcf66149da6f986c5b5452e629d5ee64bf00" dependencies = [ "async-trait", "bytes", @@ -445,7 +445,7 @@ dependencies = [ "mime", "pin-project-lite", "rustversion", - "sync_wrapper 0.1.2", + "sync_wrapper 1.0.1", "tower-layer", "tower-service", "tracing", @@ -453,9 +453,9 @@ dependencies = [ [[package]] name = "axum-extra" -version = "0.9.3" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0be6ea09c9b96cb5076af0de2e383bd2bc0c18f827cf1967bdd353e0b910d733" +checksum = "73c3220b188aea709cf1b6c5f9b01c3bd936bb08bd2b5184a12b35ac8131b1f9" dependencies = [ "axum", "axum-core", @@ -468,7 +468,7 @@ dependencies = [ "pin-project-lite", "serde", "serde_html_form", - "tower 0.4.13", + "tower 0.5.1", "tower-layer", "tower-service", "tracing", @@ -476,11 +476,10 @@ dependencies = [ [[package]] name = "axum-macros" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00c055ee2d014ae5981ce1016374e8213682aa14d9bf40e48ab48b5f3ef20eaa" +checksum = "57d123550fa8d071b7255cb0cc04dc302baa6c8c4a79f55701552684d8399bce" dependencies = [ - "heck 0.4.1", "proc-macro2", "quote", "syn 2.0.77", @@ -522,7 +521,7 @@ dependencies = [ "miniz_oxide", "object", "rustc-demangle", - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -739,9 +738,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.7.1" +version = "1.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8318a53db07bb3f8dca91a600466bdb3f2eaadeedfdbcf02e1accbad9271ba50" +checksum = "428d9aa8fbc0670b7b8d6030a7fadd0f86151cae55e4dbbece15f3780a3dfaf3" [[package]] name = "camino" @@ -769,9 +768,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.1.18" +version = "1.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b62ac837cdb5cb22e10a256099b4fc502b1dfe560cb282963a974d7abd80e476" +checksum = "07b1695e2c7e8fc85310cde85aeaab7e3097f593c91d209d3f9df76c928100f0" dependencies = [ "jobserver", "libc", @@ -809,7 +808,7 @@ dependencies = [ "iana-time-zone", "num-traits", "serde", - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -852,9 +851,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.17" +version = "4.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e5a21b8495e732f1b3c364c9949b201ca7bae518c502c80256c96ad79eaf6ac" +checksum = "b0956a43b323ac1afaffc053ed5c4b7c1f1800bacd1683c353aabbb752515dd3" dependencies = [ "clap_builder", "clap_derive", @@ -862,9 +861,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.17" +version = "4.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cf2dd12af7a047ad9d6da2b6b249759a22a7abc0f474c1dae1777afa4b21a73" +checksum = "4d72166dd41634086d5803a47eb71ae740e61d84709c36f3c34110173db3961b" dependencies = [ "anstream", "anstyle", @@ -874,9 +873,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.13" +version = "4.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "501d359d5f3dcaf6ecdeee48833ae73ec6e42723a1e52419c79abf9507eec0a0" +checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" dependencies = [ "heck 0.5.0", "proc-macro2", @@ -1798,9 +1797,9 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.60" +version = "0.1.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" +checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -1980,7 +1979,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" dependencies = [ "cfg-if", - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -2019,14 +2018,14 @@ checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "local-ip-address" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b435d7dd476416a905f9634dff8c330cee8d3168fdd1fbd472a17d1a75c00c3e" +checksum = "3669cf5561f8d27e8fc84cc15e58350e70f557d4d65f70e3154e54cd2f8e1782" dependencies = [ "libc", "neli", "thiserror", - "windows-sys 0.48.0", + "windows-sys 0.59.0", ] [[package]] @@ -2433,7 +2432,7 @@ dependencies = [ "libc", "redox_syscall", "smallvec", - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -2564,9 +2563,9 @@ dependencies = [ [[package]] name = "pkg-config" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" +checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" [[package]] name = "plotters" @@ -2847,9 +2846,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4" +checksum = "0884ad60e090bf1345b93da0a5de8923c93884cd03f40dfcfddd3b4bee661853" dependencies = [ "bitflags", ] @@ -3077,9 +3076,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.36" +version = "0.38.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f55e80d50763938498dd5ebb18647174e0c76dc38c5505294bb224624f30f36" +checksum = "8acb788b847c24f28525660c4d7758620a7210875711f79e7f663cc152726811" dependencies = [ "bitflags", "errno", @@ -3090,9 +3089,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.12" +version = "0.23.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c58f8c84392efc0a126acce10fa59ff7b3d2ac06ab451a33f2741989b806b044" +checksum = "f2dabaac7466917e566adb06783a81ca48944c6898a1b08b9374106dd671f4c8" dependencies = [ "aws-lc-rs", "once_cell", @@ -3202,9 +3201,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.11.1" +version = "2.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75da29fe9b9b08fe9d6b22b5b4bcbc75d8db3aa31e639aa56bb62e9d46bfceaf" +checksum = "ea4a292869320c0272d7bc55a5a6aafaff59b4f63404a003887b679a2e05b4b6" dependencies = [ "core-foundation-sys", "libc", @@ -3401,9 +3400,9 @@ dependencies = [ [[package]] name = "simdutf8" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f27f6278552951f1f2b8cf9da965d10969b2efdea95a6ec47987ab46edfe263a" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] name = "siphasher" @@ -3593,18 +3592,18 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.63" +version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724" +checksum = "d50af8abc119fb8bb6dbabcfa89656f46f84aa0ac7688088608076ad2b459a84" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.63" +version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" +checksum = "08904e7672f5eb876eaaf87e0ce17857500934f4981c4a0ab2b4aa98baac7fc3" dependencies = [ "proc-macro2", "quote", @@ -3762,9 +3761,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.20" +version = "0.22.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "583c44c02ad26b0c3f3066fe629275e50627026c51ac2e595cca4c230ce1ce1d" +checksum = "3b072cee73c449a636ffd6f32bd8de3a9f7119139aff882f44943ce2986dc5cf" dependencies = [ "indexmap 2.5.0", "serde", @@ -3940,17 +3939,21 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2873938d487c3cfb9aed7546dc9f2711d867c9f90c46b889989a2cb84eba6b4f" dependencies = [ + "futures-core", + "futures-util", "pin-project-lite", + "sync_wrapper 0.1.2", "tokio", "tower-layer", "tower-service", + "tracing", ] [[package]] name = "tower-http" -version = "0.5.2" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" +checksum = "8437150ab6bbc8c5f0f519e3d5ed4aa883a83dd4cdd3d1b21f9482936046cb97" dependencies = [ "async-compression", "bitflags", @@ -3958,7 +3961,6 @@ dependencies = [ "futures-core", "http", "http-body", - "http-body-util", "pin-project-lite", "tokio", "tokio-util", @@ -4102,24 +4104,24 @@ checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" [[package]] name = "unicode-ident" -version = "1.0.12" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" +checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" [[package]] name = "unicode-normalization" -version = "0.1.23" +version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" +checksum = "5033c97c4262335cded6d6fc3e5c18ab755e1a3dc96376350f3d8e9f009ad956" dependencies = [ "tinyvec", ] [[package]] name = "unicode-xid" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "229730647fbc343e3a80e463c1db7f78f3855d3f3739bee0dda773c9a037c90a" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" [[package]] name = "untrusted" @@ -4330,7 +4332,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -4341,7 +4343,7 @@ checksum = "e400001bb720a623c1c69032f8e3e4cf09984deec740f007dd2b03ec864804b0" dependencies = [ "windows-result", "windows-strings", - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -4350,7 +4352,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -4360,16 +4362,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" dependencies = [ "windows-result", - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", + "windows-targets", ] [[package]] @@ -4378,7 +4371,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -4387,22 +4380,7 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", + "windows-targets", ] [[package]] @@ -4411,46 +4389,28 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", "windows_i686_gnullvm", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -4463,48 +4423,24 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" From beb56d31857c863bb78582efc847aca1a431fecd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 23 Sep 2024 16:15:53 +0100 Subject: [PATCH 0495/1297] release: version 3.0.0-rc.1 --- Cargo.lock | 18 +++++++++--------- Cargo.toml | 16 ++++++++-------- packages/clock/Cargo.toml | 2 +- packages/configuration/Cargo.toml | 2 +- packages/test-helpers/Cargo.toml | 2 +- packages/torrent-repository/Cargo.toml | 6 +++--- 6 files changed, 23 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 97cdbb551..56978738f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3774,7 +3774,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-rc.1-develop" +version = "3.0.0-rc.1" dependencies = [ "anyhow", "aquatic_udp_protocol", @@ -3824,7 +3824,7 @@ dependencies = [ "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-tracker-torrent-repository", - "tower 0.5.1", + "tower 0.4.13", "tower-http", "trace", "tracing", @@ -3836,7 +3836,7 @@ dependencies = [ [[package]] name = "torrust-tracker-clock" -version = "3.0.0-rc.1-develop" +version = "3.0.0-rc.1" dependencies = [ "chrono", "lazy_static", @@ -3845,7 +3845,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-rc.1-develop" +version = "3.0.0-rc.1" dependencies = [ "camino", "derive_more", @@ -3862,7 +3862,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-rc.1-develop" +version = "3.0.0-rc.1" dependencies = [ "criterion", "thiserror", @@ -3870,7 +3870,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-rc.1-develop" +version = "3.0.0-rc.1" dependencies = [ "thiserror", "tracing", @@ -3878,7 +3878,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-rc.1-develop" +version = "3.0.0-rc.1" dependencies = [ "aquatic_udp_protocol", "binascii", @@ -3892,7 +3892,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-rc.1-develop" +version = "3.0.0-rc.1" dependencies = [ "rand", "torrust-tracker-configuration", @@ -3900,7 +3900,7 @@ dependencies = [ [[package]] name = "torrust-tracker-torrent-repository" -version = "3.0.0-rc.1-develop" +version = "3.0.0-rc.1" dependencies = [ "aquatic_udp_protocol", "async-std", diff --git a/Cargo.toml b/Cargo.toml index 5a2b382cb..4aa87e6e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ license = "AGPL-3.0-only" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-rc.1-develop" +version = "3.0.0-rc.1" [dependencies] anyhow = "1" @@ -69,12 +69,12 @@ serde_repr = "0" serde_with = { version = "3", features = ["json"] } thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-clock = { version = "3.0.0-rc.1-develop", path = "packages/clock" } -torrust-tracker-configuration = { version = "3.0.0-rc.1-develop", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-rc.1-develop", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-rc.1-develop", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-rc.1-develop", path = "packages/primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-rc.1-develop", path = "packages/torrent-repository" } +torrust-tracker-clock = { version = "3.0.0-rc.1", path = "packages/clock" } +torrust-tracker-configuration = { version = "3.0.0-rc.1", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-rc.1", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-rc.1", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-rc.1", path = "packages/primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-rc.1", path = "packages/torrent-repository" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } trace = "0" @@ -90,7 +90,7 @@ ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_byt [dev-dependencies] local-ip-address = "0" mockall = "0" -torrust-tracker-test-helpers = { version = "3.0.0-rc.1-develop", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-rc.1", path = "packages/test-helpers" } [workspace] members = [ diff --git a/packages/clock/Cargo.toml b/packages/clock/Cargo.toml index 908816742..f95c12a0c 100644 --- a/packages/clock/Cargo.toml +++ b/packages/clock/Cargo.toml @@ -19,6 +19,6 @@ version.workspace = true chrono = { version = "0", default-features = false, features = ["clock"] } lazy_static = "1" -torrust-tracker-primitives = { version = "3.0.0-rc.1-develop", path = "../primitives" } +torrust-tracker-primitives = { version = "3.0.0-rc.1", path = "../primitives" } [dev-dependencies] diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 8eafcc06a..7b8b3c3bf 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -23,7 +23,7 @@ serde_json = { version = "1", features = ["preserve_order"] } serde_with = "3" thiserror = "1" toml = "0" -torrust-tracker-located-error = { version = "3.0.0-rc.1-develop", path = "../located-error" } +torrust-tracker-located-error = { version = "3.0.0-rc.1", path = "../located-error" } url = "2" [dev-dependencies] diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index b8762824d..ccf08b570 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -16,4 +16,4 @@ version.workspace = true [dependencies] rand = "0" -torrust-tracker-configuration = { version = "3.0.0-rc.1-develop", path = "../configuration" } +torrust-tracker-configuration = { version = "3.0.0-rc.1", path = "../configuration" } diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 5268b223f..0650d608f 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -22,9 +22,9 @@ dashmap = "6" futures = "0" parking_lot = "0" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-clock = { version = "3.0.0-rc.1-develop", path = "../clock" } -torrust-tracker-configuration = { version = "3.0.0-rc.1-develop", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-rc.1-develop", path = "../primitives" } +torrust-tracker-clock = { version = "3.0.0-rc.1", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-rc.1", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-rc.1", path = "../primitives" } zerocopy = "0" [dev-dependencies] From cb809d3984d86a5ef4adb0f6f452d7a4442bf10b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 23 Sep 2024 17:48:40 +0100 Subject: [PATCH 0496/1297] develop: bump to version 3.0.0-develop --- Cargo.lock | 16 ++++++++-------- Cargo.toml | 16 ++++++++-------- packages/clock/Cargo.toml | 2 +- packages/configuration/Cargo.toml | 2 +- packages/test-helpers/Cargo.toml | 2 +- packages/torrent-repository/Cargo.toml | 6 +++--- 6 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 56978738f..d43356ca4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3774,7 +3774,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-rc.1" +version = "3.0.0-develop" dependencies = [ "anyhow", "aquatic_udp_protocol", @@ -3836,7 +3836,7 @@ dependencies = [ [[package]] name = "torrust-tracker-clock" -version = "3.0.0-rc.1" +version = "3.0.0-develop" dependencies = [ "chrono", "lazy_static", @@ -3845,7 +3845,7 @@ dependencies = [ [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-rc.1" +version = "3.0.0-develop" dependencies = [ "camino", "derive_more", @@ -3862,7 +3862,7 @@ dependencies = [ [[package]] name = "torrust-tracker-contrib-bencode" -version = "3.0.0-rc.1" +version = "3.0.0-develop" dependencies = [ "criterion", "thiserror", @@ -3870,7 +3870,7 @@ dependencies = [ [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-rc.1" +version = "3.0.0-develop" dependencies = [ "thiserror", "tracing", @@ -3878,7 +3878,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-rc.1" +version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", "binascii", @@ -3892,7 +3892,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-rc.1" +version = "3.0.0-develop" dependencies = [ "rand", "torrust-tracker-configuration", @@ -3900,7 +3900,7 @@ dependencies = [ [[package]] name = "torrust-tracker-torrent-repository" -version = "3.0.0-rc.1" +version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", "async-std", diff --git a/Cargo.toml b/Cargo.toml index 4aa87e6e3..47102a349 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,7 @@ license = "AGPL-3.0-only" publish = true repository = "https://github.com/torrust/torrust-tracker" rust-version = "1.72" -version = "3.0.0-rc.1" +version = "3.0.0-develop" [dependencies] anyhow = "1" @@ -69,12 +69,12 @@ serde_repr = "0" serde_with = { version = "3", features = ["json"] } thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-clock = { version = "3.0.0-rc.1", path = "packages/clock" } -torrust-tracker-configuration = { version = "3.0.0-rc.1", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-rc.1", path = "contrib/bencode" } -torrust-tracker-located-error = { version = "3.0.0-rc.1", path = "packages/located-error" } -torrust-tracker-primitives = { version = "3.0.0-rc.1", path = "packages/primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-rc.1", path = "packages/torrent-repository" } +torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-develop", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-develop", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "packages/primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "packages/torrent-repository" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } trace = "0" @@ -90,7 +90,7 @@ ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_byt [dev-dependencies] local-ip-address = "0" mockall = "0" -torrust-tracker-test-helpers = { version = "3.0.0-rc.1", path = "packages/test-helpers" } +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "packages/test-helpers" } [workspace] members = [ diff --git a/packages/clock/Cargo.toml b/packages/clock/Cargo.toml index f95c12a0c..2ede678d9 100644 --- a/packages/clock/Cargo.toml +++ b/packages/clock/Cargo.toml @@ -19,6 +19,6 @@ version.workspace = true chrono = { version = "0", default-features = false, features = ["clock"] } lazy_static = "1" -torrust-tracker-primitives = { version = "3.0.0-rc.1", path = "../primitives" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } [dev-dependencies] diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 7b8b3c3bf..8706679f6 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -23,7 +23,7 @@ serde_json = { version = "1", features = ["preserve_order"] } serde_with = "3" thiserror = "1" toml = "0" -torrust-tracker-located-error = { version = "3.0.0-rc.1", path = "../located-error" } +torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } url = "2" [dev-dependencies] diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index ccf08b570..ad291d209 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -16,4 +16,4 @@ version.workspace = true [dependencies] rand = "0" -torrust-tracker-configuration = { version = "3.0.0-rc.1", path = "../configuration" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 0650d608f..32c324538 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -22,9 +22,9 @@ dashmap = "6" futures = "0" parking_lot = "0" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } -torrust-tracker-clock = { version = "3.0.0-rc.1", path = "../clock" } -torrust-tracker-configuration = { version = "3.0.0-rc.1", path = "../configuration" } -torrust-tracker-primitives = { version = "3.0.0-rc.1", path = "../primitives" } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } zerocopy = "0" [dev-dependencies] From ae5ea1ea0dfe2c1a9a9d2277affee78912a8c815 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 2 Oct 2024 08:28:07 +0100 Subject: [PATCH 0497/1297] docs: fix link to containers docs --- src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index d242ac80e..5d7c92ae2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -155,7 +155,7 @@ //! ## Run with docker //! //! You can run the tracker with a pre-built docker image. Please refer to the -//! [tracker docker documentation](https://github.com/torrust/torrust-tracker/tree/develop/docker). +//! [tracker docker documentation](https://github.com/torrust/torrust-tracker/blob/develop/docs/containers.md). //! //! # Configuration //! @@ -214,7 +214,7 @@ //! of the `tracker.toml` file. //! //! The env var contains the same data as the `tracker.toml`. It's particularly -//! useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/tree/develop/docker). +//! useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/blob/develop/docs/containers.md). //! //! > NOTICE: The `TORRUST_TRACKER_CONFIG_TOML` env var has priority over the `tracker.toml` file. //! From 6b2d8e8372b002cf501f244f4d1b8ffeda8983d9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 2 Oct 2024 09:00:27 +0100 Subject: [PATCH 0498/1297] fix: clippy errors --- packages/clock/src/clock/stopped/mod.rs | 1 - packages/clock/src/conv/mod.rs | 1 - 2 files changed, 2 deletions(-) diff --git a/packages/clock/src/clock/stopped/mod.rs b/packages/clock/src/clock/stopped/mod.rs index 57655ab75..5d0b2ec4e 100644 --- a/packages/clock/src/clock/stopped/mod.rs +++ b/packages/clock/src/clock/stopped/mod.rs @@ -1,6 +1,5 @@ /// Trait for types that can be used as a timestamp clock stopped /// at a given time. - #[allow(clippy::module_name_repetitions)] pub struct StoppedClock {} diff --git a/packages/clock/src/conv/mod.rs b/packages/clock/src/conv/mod.rs index 894083061..0ac278171 100644 --- a/packages/clock/src/conv/mod.rs +++ b/packages/clock/src/conv/mod.rs @@ -48,7 +48,6 @@ pub fn convert_from_timestamp_to_datetime_utc(duration: DurationSinceUnixEpoch) } #[cfg(test)] - mod tests { use chrono::DateTime; use torrust_tracker_primitives::DurationSinceUnixEpoch; From 9341f2cd5db3fe555b79bddcf586066d0980cc74 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 3 Oct 2024 11:40:38 +0200 Subject: [PATCH 0499/1297] ci: temp allow clipply lint: needless_return --- .github/workflows/testing.yaml | 2 +- Cargo.toml | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index abe6f0a60..124b13b5a 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -69,7 +69,7 @@ jobs: - id: lint name: Run Lint Checks - run: cargo clippy --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic + run: cargo clippy --tests --benches --examples --workspace --all-targets --all-features - id: docs name: Lint Documentation diff --git a/Cargo.toml b/Cargo.toml index 47102a349..f6ac9aafd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -115,3 +115,14 @@ opt-level = 3 [profile.release-debug] debug = true inherits = "release" + +[lints.clippy] +complexity = { level = "deny", priority = -1 } +correctness = { level = "deny", priority = -1 } +pedantic = { level = "deny", priority = -1 } +perf = { level = "deny", priority = -1 } +style = { level = "deny", priority = -1 } +suspicious = { level = "deny", priority = -1 } + +# temp allow this lint +needless_return = "allow" From 8eacbe3481c6a5613874f383076d82e7d2fe1867 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 3 Oct 2024 11:42:21 +0200 Subject: [PATCH 0500/1297] ci: fix toolchain bug with release --- .github/workflows/deployment.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 6aa66e985..e30eccc71 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -35,6 +35,10 @@ jobs: needs: test runs-on: ubuntu-latest + strategy: + matrix: + toolchain: [stable] + steps: - id: checkout name: Checkout Repository From 7dda918c245700691d93613e874f0f20f48ac915 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 3 Oct 2024 11:59:54 +0200 Subject: [PATCH 0501/1297] vscode: update clippy to include lints from cargo manifest --- .vscode/settings.json | 30 ++++++++---------------------- 1 file changed, 8 insertions(+), 22 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index caa48dd01..d27d562e8 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,34 +2,20 @@ "[rust]": { "editor.formatOnSave": true }, - "[ignore]": { "rust-analyzer.cargo.extraEnv" : { - "RUSTFLAGS": "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests", - "RUSTDOCFLAGS": "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests", - "CARGO_INCREMENTAL": "0", - "RUST_BACKTRACE": "1" - }}, + "[ignore]": { + "rust-analyzer.cargo.extraEnv": { + "RUSTFLAGS": "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests", + "RUSTDOCFLAGS": "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests", + "CARGO_INCREMENTAL": "0", + "RUST_BACKTRACE": "1" + } + }, "rust-analyzer.checkOnSave": true, "rust-analyzer.check.command": "clippy", "rust-analyzer.check.allTargets": true, - "rust-analyzer.check.extraArgs": [ - "--", - "-D", - "clippy::correctness", - "-D", - "clippy::suspicious", - "-W", - "clippy::complexity", - "-W", - "clippy::perf", - "-W", - "clippy::style", - "-W", - "clippy::pedantic" - ], "evenBetterToml.formatter.allowedBlankLines": 1, "evenBetterToml.formatter.columnWidth": 130, "evenBetterToml.formatter.trailingNewline": true, "evenBetterToml.formatter.reorderKeys": true, "evenBetterToml.formatter.reorderArrays": true, - } \ No newline at end of file From f95aac2338a6d96ed319d474923682b8ce14d00b Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Thu, 3 Oct 2024 12:04:57 +0200 Subject: [PATCH 0502/1297] cargo: remove unused trace dependancy --- Cargo.lock | 12 ------------ Cargo.toml | 1 - 2 files changed, 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d43356ca4..3d0645ebf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3826,7 +3826,6 @@ dependencies = [ "torrust-tracker-torrent-repository", "tower 0.4.13", "tower-http", - "trace", "tracing", "tracing-subscriber", "url", @@ -3982,17 +3981,6 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" -[[package]] -name = "trace" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ad0c048e114d19d1140662762bfdb10682f3bc806d8be18af846600214dd9af" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "tracing" version = "0.1.40" diff --git a/Cargo.toml b/Cargo.toml index f6ac9aafd..6fd61b6e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -77,7 +77,6 @@ torrust-tracker-primitives = { version = "3.0.0-develop", path = "packages/primi torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "packages/torrent-repository" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } -trace = "0" tracing = "0" tracing-subscriber = { version = "0", features = ["json"] } url = { version = "2", features = ["serde"] } From c9f4dfdc3b0cba23ed508a2273beaf057d2433a5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 4 Oct 2024 17:41:57 +0100 Subject: [PATCH 0503/1297] docs: update release process --- docs/release_process.md | 41 ++++++++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/docs/release_process.md b/docs/release_process.md index 73b0a8827..f9d1cce71 100644 --- a/docs/release_process.md +++ b/docs/release_process.md @@ -1,11 +1,12 @@ -# Torrust Tracker Release Process (v2.2.2) +# Torrust Tracker Release Process (v2.2.2) + +## Version -## Version: > **The `[semantic version]` is bumped according to releases, new features, and breaking changes.** > > *The `develop` branch uses the (semantic version) suffix `-develop`.* -## Process: +## Process **Note**: this guide assumes that the your git `torrust` remote is like this: @@ -20,18 +21,18 @@ git remote show torrust ... ``` +### 1. The `develop` branch is ready for a release -### 1. The `develop` branch is ready for a release. The `develop` branch should have the version `[semantic version]-develop` that is ready to be released. -### 2. Stage `develop` HEAD for merging into the `main` branch: +### 2. Stage `develop` HEAD for merging into the `main` branch ```sh git fetch --all git push --force torrust develop:staging/main ``` -### 3. Create Release Commit: +### 3. Create Release Commit ```sh git stash @@ -43,13 +44,13 @@ git commit -m "release: version [semantic version]" git push torrust ``` -### 4. Create and Merge Pull Request from `staging/main` into `main` branch. +### 4. Create and Merge Pull Request from `staging/main` into `main` branch Pull request title format: "Release Version `[semantic version]`". This pull request merges the new version into the `main` branch. -### 5. Push new version from `main` HEAD to `releases/v[semantic version]` branch: +### 5. Push new version from `main` HEAD to `releases/v[semantic version]` branch ```sh git fetch --all @@ -58,7 +59,7 @@ git push torrust main:releases/v[semantic version] > **Check that the deployment is successful!** -### 6. Create Release Tag: +### 6. Create Release Tag ```sh git switch releases/v[semantic version] @@ -66,17 +67,31 @@ git tag --sign v[semantic version] git push --tags torrust ``` -### 7. Create Release on Github from Tag. +Make sure the [deployment](https://github.com/torrust/torrust-tracker/actions/workflows/deployment.yaml) workflow was successfully executed and the new version for the following crates were published: + +- [torrust-tracker-contrib-bencode](https://crates.io/crates/torrust-tracker-contrib-bencode) +- [torrust-tracker-located-error](https://crates.io/crates/torrust-tracker-located-error) +- [torrust-tracker-primitives](https://crates.io/crates/torrust-tracker-primitives) +- [torrust-tracker-clock](https://crates.io/crates/torrust-tracker-clock) +- [torrust-tracker-configuration](https://crates.io/crates/torrust-tracker-configuration) +- [torrust-tracker-torrent-repository](https://crates.io/crates/torrust-tracker-torrent-repository) +- [torrust-tracker-test-helpers](https://crates.io/crates/torrust-tracker-test-helpers) +- [torrust-tracker](https://crates.io/crates/torrust-tracker) + +### 7. Create Release on Github from Tag + This is for those who wish to download the source code. -### 8. Stage `main` HEAD for merging into the `develop` branch: +### 8. Stage `main` HEAD for merging into the `develop` branch + Merge release back into the develop branch. ```sh git fetch --all git push --force torrust main:staging/develop ``` -### 9. Create Comment that bumps next development version: + +### 9. Create Comment that bumps next development version ```sh git stash @@ -88,7 +103,7 @@ git commit -m "develop: bump to version (next)[semantic version]-develop" git push torrust ``` -### 10. Create and Merge Pull Request from `staging/develop` into `develop` branch. +### 10. Create and Merge Pull Request from `staging/develop` into `develop` branch Pull request title format: "Version `[semantic version]` was Released". From a34f66e1cd422c0fdbcb01da7c6b14bee7b27055 Mon Sep 17 00:00:00 2001 From: abstralexis Date: Thu, 17 Oct 2024 16:48:57 +0100 Subject: [PATCH 0504/1297] Fix #1040: `continue` when finding errors --- src/console/clients/checker/checks/udp.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/console/clients/checker/checks/udp.rs b/src/console/clients/checker/checks/udp.rs index 4044b4c52..21bdcd1b7 100644 --- a/src/console/clients/checker/checks/udp.rs +++ b/src/console/clients/checker/checks/udp.rs @@ -50,7 +50,7 @@ pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec { checks.results.push((Check::Setup, Err(err))); results.push(Err(checks)); - break; + continue; } }; @@ -65,7 +65,7 @@ pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec { checks.results.push((Check::Connect, Err(err))); results.push(Err(checks)); - break; + continue; } }; From 7d7dba500c15ddf971aa1c564259068f7967c708 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 30 Oct 2024 16:27:30 +0000 Subject: [PATCH 0505/1297] feat: add dep bittorrent-primitives --- Cargo.lock | 31 ++++++++++++++++++++------ Cargo.toml | 1 + packages/primitives/Cargo.toml | 1 + packages/torrent-repository/Cargo.toml | 1 + 4 files changed, 27 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3d0645ebf..9dade94be 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -602,6 +602,20 @@ version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" +[[package]] +name = "bittorrent-primitives" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdc1bd0462f0af0b57abd5f5f8f32b904ba0a17cc8be1714db160a054552f242" +dependencies = [ + "aquatic_udp_protocol", + "binascii", + "serde", + "serde_json", + "thiserror", + "zerocopy", +] + [[package]] name = "bitvec" version = "1.0.1" @@ -3269,9 +3283,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.128" +version = "1.0.132" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ff5456707a1de34e7e37f2a6fd3d3f808c318259cbd01ab6377795054b483d8" +checksum = "d726bfaff4b320266d395898905d0eba0345aae23b54aee3a737e260fd46db03" dependencies = [ "indexmap 2.5.0", "itoa", @@ -3592,18 +3606,18 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.64" +version = "1.0.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d50af8abc119fb8bb6dbabcfa89656f46f84aa0ac7688088608076ad2b459a84" +checksum = "5d11abd9594d9b38965ef50805c5e469ca9cc6f197f883f717e0269a3057b3d5" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.64" +version = "1.0.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08904e7672f5eb876eaaf87e0ce17857500934f4981c4a0ab2b4aa98baac7fc3" +checksum = "ae71770322cbd277e69d762a16c444af02aa0575ac0d174f0b9562d3b37f8602" dependencies = [ "proc-macro2", "quote", @@ -3782,6 +3796,7 @@ dependencies = [ "axum-client-ip", "axum-extra", "axum-server", + "bittorrent-primitives", "camino", "chrono", "clap", @@ -3824,7 +3839,7 @@ dependencies = [ "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-tracker-torrent-repository", - "tower 0.4.13", + "tower 0.5.1", "tower-http", "tracing", "tracing-subscriber", @@ -3881,6 +3896,7 @@ version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", "binascii", + "bittorrent-primitives", "derive_more", "serde", "tdyne-peer-id", @@ -3903,6 +3919,7 @@ version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", "async-std", + "bittorrent-primitives", "criterion", "crossbeam-skiplist", "dashmap", diff --git a/Cargo.toml b/Cargo.toml index 6fd61b6e6..d69fa3e5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ axum = { version = "0", features = ["macros"] } axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls"] } +bittorrent-primitives = "0.1.0" camino = { version = "1", features = ["serde", "serde1"] } chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index 02a53e3b7..4b5abc8f3 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -17,6 +17,7 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" binascii = "0" +bittorrent-primitives = "0.1.0" derive_more = { version = "1", features = ["constructor"] } serde = { version = "1", features = ["derive"] } tdyne-peer-id = "1" diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 32c324538..0933457d3 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -17,6 +17,7 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" crossbeam-skiplist = "0" dashmap = "6" futures = "0" From 7fe648c0dd7a3ae63be061ce998b7f22e7bd00b1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 30 Oct 2024 16:42:37 +0000 Subject: [PATCH 0506/1297] refactor: replace InfoHash with external extracted crate The `InfoHash` struct has been extracted into a new crate to be reused in other projects like the Torrust Index: https://github.com/torrust/bittorrent-primitives --- contrib/bencode/src/access/bencode.rs | 2 +- packages/located-error/src/lib.rs | 6 +- packages/primitives/src/info_hash.rs | 220 ------------- packages/primitives/src/lib.rs | 11 +- .../benches/helpers/asyn.rs | 2 +- .../benches/helpers/sync.rs | 2 +- .../benches/helpers/utils.rs | 2 +- .../src/repository/dash_map_mutex_std.rs | 2 +- .../torrent-repository/src/repository/mod.rs | 2 +- .../src/repository/rw_lock_std.rs | 4 +- .../src/repository/rw_lock_std_mutex_std.rs | 2 +- .../src/repository/rw_lock_std_mutex_tokio.rs | 2 +- .../src/repository/rw_lock_tokio.rs | 7 +- .../src/repository/rw_lock_tokio_mutex_std.rs | 2 +- .../repository/rw_lock_tokio_mutex_tokio.rs | 2 +- .../src/repository/skip_map_mutex_std.rs | 2 +- .../torrent-repository/tests/common/repo.rs | 2 +- .../tests/repository/mod.rs | 2 +- src/console/clients/checker/checks/http.rs | 2 +- src/console/clients/http/app.rs | 2 +- src/console/clients/udp/app.rs | 2 +- src/console/clients/udp/checker.rs | 2 +- src/core/databases/mod.rs | 2 +- src/core/databases/mysql.rs | 2 +- src/core/databases/sqlite.rs | 2 +- src/core/error.rs | 2 +- src/core/mod.rs | 16 +- src/core/services/torrent.rs | 6 +- .../apis/v1/context/torrent/handlers.rs | 2 +- .../v1/context/torrent/resources/torrent.rs | 2 +- .../apis/v1/context/whitelist/handlers.rs | 2 +- src/servers/http/percent_encoding.rs | 8 +- .../http/v1/extractors/announce_request.rs | 2 +- .../http/v1/extractors/scrape_request.rs | 2 +- src/servers/http/v1/handlers/announce.rs | 2 +- src/servers/http/v1/handlers/scrape.rs | 2 +- src/servers/http/v1/requests/announce.rs | 6 +- src/servers/http/v1/requests/scrape.rs | 4 +- src/servers/http/v1/responses/scrape.rs | 4 +- src/servers/http/v1/services/announce.rs | 4 +- src/servers/http/v1/services/scrape.rs | 4 +- src/servers/udp/handlers.rs | 2 +- src/servers/udp/logging.rs | 2 +- src/servers/udp/mod.rs | 2 +- src/shared/bit_torrent/info_hash.rs | 288 ------------------ src/shared/bit_torrent/mod.rs | 1 - .../tracker/http/client/requests/announce.rs | 2 +- .../tracker/http/client/requests/scrape.rs | 2 +- tests/servers/api/environment.rs | 2 +- .../servers/api/v1/contract/context/stats.rs | 2 +- .../api/v1/contract/context/torrent.rs | 2 +- .../api/v1/contract/context/whitelist.rs | 2 +- tests/servers/http/environment.rs | 2 +- tests/servers/http/requests/announce.rs | 2 +- tests/servers/http/requests/scrape.rs | 2 +- tests/servers/http/v1/contract.rs | 12 +- tests/servers/udp/environment.rs | 2 +- 57 files changed, 85 insertions(+), 598 deletions(-) delete mode 100644 packages/primitives/src/info_hash.rs delete mode 100644 src/shared/bit_torrent/info_hash.rs diff --git a/contrib/bencode/src/access/bencode.rs b/contrib/bencode/src/access/bencode.rs index ee90296e2..728535a98 100644 --- a/contrib/bencode/src/access/bencode.rs +++ b/contrib/bencode/src/access/bencode.rs @@ -50,7 +50,7 @@ pub trait BRefAccessExt<'a>: BRefAccess { fn bytes_ext(&self) -> Option<&'a [u8]>; } -impl<'a, T> BRefAccess for &'a T +impl BRefAccess for &T where T: BRefAccess, { diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs index 3cba6042d..c30043cd3 100644 --- a/packages/located-error/src/lib.rs +++ b/packages/located-error/src/lib.rs @@ -50,7 +50,7 @@ where location: Box>, } -impl<'a, E> std::fmt::Display for LocatedError<'a, E> +impl std::fmt::Display for LocatedError<'_, E> where E: Error + ?Sized + Send + Sync, { @@ -59,7 +59,7 @@ where } } -impl<'a, E> Error for LocatedError<'a, E> +impl Error for LocatedError<'_, E> where E: Error + ?Sized + Send + Sync + 'static, { @@ -68,7 +68,7 @@ where } } -impl<'a, E> Clone for LocatedError<'a, E> +impl Clone for LocatedError<'_, E> where E: Error + ?Sized + Send + Sync, { diff --git a/packages/primitives/src/info_hash.rs b/packages/primitives/src/info_hash.rs deleted file mode 100644 index 61b40a746..000000000 --- a/packages/primitives/src/info_hash.rs +++ /dev/null @@ -1,220 +0,0 @@ -use std::hash::{DefaultHasher, Hash, Hasher}; -use std::ops::{Deref, DerefMut}; -use std::panic::Location; - -use thiserror::Error; -use zerocopy::FromBytes; - -/// `BitTorrent` Info Hash v1 -#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] -pub struct InfoHash { - data: aquatic_udp_protocol::InfoHash, -} - -pub const INFO_HASH_BYTES_LEN: usize = 20; - -impl InfoHash { - /// Create a new `InfoHash` from a byte slice. - /// - /// # Panics - /// - /// Will panic if byte slice does not contains the exact amount of bytes need for the `InfoHash`. - #[must_use] - pub fn from_bytes(bytes: &[u8]) -> Self { - let data = aquatic_udp_protocol::InfoHash::read_from(bytes).expect("it should have the exact amount of bytes"); - - Self { data } - } - - /// Returns the `InfoHash` internal byte array. - #[must_use] - pub fn bytes(&self) -> [u8; 20] { - self.0 - } - - /// Returns the `InfoHash` as a hex string. - #[must_use] - pub fn to_hex_string(&self) -> String { - self.to_string() - } -} - -impl Default for InfoHash { - fn default() -> Self { - Self { - data: aquatic_udp_protocol::InfoHash(Default::default()), - } - } -} - -impl From for InfoHash { - fn from(data: aquatic_udp_protocol::InfoHash) -> Self { - Self { data } - } -} - -impl Deref for InfoHash { - type Target = aquatic_udp_protocol::InfoHash; - - fn deref(&self) -> &Self::Target { - &self.data - } -} - -impl DerefMut for InfoHash { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.data - } -} - -impl Ord for InfoHash { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.0.cmp(&other.0) - } -} - -impl PartialOrd for InfoHash { - fn partial_cmp(&self, other: &InfoHash) -> Option { - Some(self.cmp(other)) - } -} - -impl std::fmt::Display for InfoHash { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let mut chars = [0u8; 40]; - binascii::bin2hex(&self.0, &mut chars).expect("failed to hexlify"); - write!(f, "{}", std::str::from_utf8(&chars).unwrap()) - } -} - -impl std::str::FromStr for InfoHash { - type Err = binascii::ConvertError; - - fn from_str(s: &str) -> Result { - let mut i = Self::default(); - if s.len() != 40 { - return Err(binascii::ConvertError::InvalidInputLength); - } - binascii::hex2bin(s.as_bytes(), &mut i.0)?; - Ok(i) - } -} - -impl std::convert::From<&[u8]> for InfoHash { - fn from(data: &[u8]) -> InfoHash { - assert_eq!(data.len(), 20); - let mut ret = Self::default(); - ret.0.clone_from_slice(data); - ret - } -} - -/// for testing -impl std::convert::From<&DefaultHasher> for InfoHash { - fn from(data: &DefaultHasher) -> InfoHash { - let n = data.finish().to_le_bytes(); - let bytes = [ - n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[0], n[1], n[2], - n[3], - ]; - let data = aquatic_udp_protocol::InfoHash(bytes); - Self { data } - } -} - -impl std::convert::From<&i32> for InfoHash { - fn from(n: &i32) -> InfoHash { - let n = n.to_le_bytes(); - let bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, n[0], n[1], n[2], n[3]]; - let data = aquatic_udp_protocol::InfoHash(bytes); - Self { data } - } -} - -impl std::convert::From<[u8; 20]> for InfoHash { - fn from(bytes: [u8; 20]) -> Self { - let data = aquatic_udp_protocol::InfoHash(bytes); - Self { data } - } -} - -/// Errors that can occur when converting from a `Vec` to an `InfoHash`. -#[derive(Error, Debug)] -pub enum ConversionError { - /// Not enough bytes for infohash. An infohash is 20 bytes. - #[error("not enough bytes for infohash: {message} {location}")] - NotEnoughBytes { - location: &'static Location<'static>, - message: String, - }, - /// Too many bytes for infohash. An infohash is 20 bytes. - #[error("too many bytes for infohash: {message} {location}")] - TooManyBytes { - location: &'static Location<'static>, - message: String, - }, -} - -impl TryFrom> for InfoHash { - type Error = ConversionError; - - fn try_from(bytes: Vec) -> Result { - if bytes.len() < INFO_HASH_BYTES_LEN { - return Err(ConversionError::NotEnoughBytes { - location: Location::caller(), - message: format! {"got {} bytes, expected {}", bytes.len(), INFO_HASH_BYTES_LEN}, - }); - } - if bytes.len() > INFO_HASH_BYTES_LEN { - return Err(ConversionError::TooManyBytes { - location: Location::caller(), - message: format! {"got {} bytes, expected {}", bytes.len(), INFO_HASH_BYTES_LEN}, - }); - } - Ok(Self::from_bytes(&bytes)) - } -} - -impl serde::ser::Serialize for InfoHash { - fn serialize(&self, serializer: S) -> Result { - let mut buffer = [0u8; 40]; - let bytes_out = binascii::bin2hex(&self.0, &mut buffer).ok().unwrap(); - let str_out = std::str::from_utf8(bytes_out).unwrap(); - serializer.serialize_str(str_out) - } -} - -impl<'de> serde::de::Deserialize<'de> for InfoHash { - fn deserialize>(des: D) -> Result { - des.deserialize_str(InfoHashVisitor) - } -} - -struct InfoHashVisitor; - -impl<'v> serde::de::Visitor<'v> for InfoHashVisitor { - type Value = InfoHash; - - fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(formatter, "a 40 character long hash") - } - - fn visit_str(self, v: &str) -> Result { - if v.len() != 40 { - return Err(serde::de::Error::invalid_value( - serde::de::Unexpected::Str(v), - &"a 40 character long string", - )); - } - - let mut res = InfoHash::default(); - - if binascii::hex2bin(v.as_bytes(), &mut res.0).is_err() { - return Err(serde::de::Error::invalid_value( - serde::de::Unexpected::Str(v), - &"a hexadecimal string", - )); - }; - Ok(res) - } -} diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index 08fc58976..d5c6fc525 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -4,17 +4,16 @@ //! which is a `BitTorrent` tracker server. These structures are used not only //! by the tracker server crate, but also by other crates in the Torrust //! ecosystem. -use std::collections::BTreeMap; -use std::time::Duration; - -use info_hash::InfoHash; - -pub mod info_hash; pub mod pagination; pub mod peer; pub mod swarm_metadata; pub mod torrent_metrics; +use std::collections::BTreeMap; +use std::time::Duration; + +use bittorrent_primitives::info_hash::InfoHash; + /// Duration since the Unix Epoch. pub type DurationSinceUnixEpoch = Duration; diff --git a/packages/torrent-repository/benches/helpers/asyn.rs b/packages/torrent-repository/benches/helpers/asyn.rs index 08862abc8..dec3984c6 100644 --- a/packages/torrent-repository/benches/helpers/asyn.rs +++ b/packages/torrent-repository/benches/helpers/asyn.rs @@ -1,8 +1,8 @@ use std::sync::Arc; use std::time::{Duration, Instant}; +use bittorrent_primitives::info_hash::InfoHash; use futures::stream::FuturesUnordered; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_torrent_repository::repository::RepositoryAsync; use super::utils::{generate_unique_info_hashes, DEFAULT_PEER}; diff --git a/packages/torrent-repository/benches/helpers/sync.rs b/packages/torrent-repository/benches/helpers/sync.rs index 77055911d..048e709bc 100644 --- a/packages/torrent-repository/benches/helpers/sync.rs +++ b/packages/torrent-repository/benches/helpers/sync.rs @@ -1,8 +1,8 @@ use std::sync::Arc; use std::time::{Duration, Instant}; +use bittorrent_primitives::info_hash::InfoHash; use futures::stream::FuturesUnordered; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_torrent_repository::repository::Repository; use super::utils::{generate_unique_info_hashes, DEFAULT_PEER}; diff --git a/packages/torrent-repository/benches/helpers/utils.rs b/packages/torrent-repository/benches/helpers/utils.rs index e21ac7332..51b09ec0f 100644 --- a/packages/torrent-repository/benches/helpers/utils.rs +++ b/packages/torrent-repository/benches/helpers/utils.rs @@ -2,7 +2,7 @@ use std::collections::HashSet; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; -use torrust_tracker_primitives::info_hash::InfoHash; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; use zerocopy::I64; diff --git a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs index 4354c12ec..54a83aeb4 100644 --- a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs @@ -1,8 +1,8 @@ use std::sync::Arc; +use bittorrent_primitives::info_hash::InfoHash; use dashmap::DashMap; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs index f198288f8..14f03ed9d 100644 --- a/packages/torrent-repository/src/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -1,5 +1,5 @@ +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs index 5439fdd79..409a16498 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std.rs @@ -1,5 +1,5 @@ +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; @@ -21,7 +21,7 @@ impl RwLockStd { /// Panics if unable to get a lock. pub fn write( &self, - ) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { + ) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { self.torrents.write().expect("it should get lock") } } diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs index 7d58b0b10..8814f09ed 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs @@ -1,7 +1,7 @@ use std::sync::Arc; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs index 90451ca9f..46f4a9567 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs @@ -2,10 +2,10 @@ use std::iter::zip; use std::pin::Pin; use std::sync::Arc; +use bittorrent_primitives::info_hash::InfoHash; use futures::future::join_all; use futures::{Future, FutureExt}; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs index baaa01232..ce6646e92 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio.rs @@ -1,5 +1,5 @@ +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; @@ -19,10 +19,7 @@ impl RwLockTokio { pub fn write( &self, ) -> impl std::future::Future< - Output = tokio::sync::RwLockWriteGuard< - '_, - std::collections::BTreeMap, - >, + Output = tokio::sync::RwLockWriteGuard<'_, std::collections::BTreeMap>, > { self.torrents.write() } diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs index 1887f70c7..7efb093e9 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs @@ -1,7 +1,7 @@ use std::sync::Arc; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs index 6c9c08a73..e08a6af59 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -1,7 +1,7 @@ use std::sync::Arc; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index dd0d9c1b1..47fe9620a 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -1,8 +1,8 @@ use std::sync::Arc; +use bittorrent_primitives::info_hash::InfoHash; use crossbeam_skiplist::SkipMap; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index f317d0d17..ebd829f3c 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -1,5 +1,5 @@ +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 05d538582..c5cf2059c 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -2,9 +2,9 @@ use std::collections::{BTreeMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use bittorrent_primitives::info_hash::InfoHash; use rstest::{fixture, rstest}; use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::PersistentTorrents; diff --git a/src/console/clients/checker/checks/http.rs b/src/console/clients/checker/checks/http.rs index 0904f4e6e..b64297bed 100644 --- a/src/console/clients/checker/checks/http.rs +++ b/src/console/clients/checker/checks/http.rs @@ -1,8 +1,8 @@ use std::str::FromStr as _; use std::time::Duration; +use bittorrent_primitives::info_hash::InfoHash; use serde::Serialize; -use torrust_tracker_primitives::info_hash::InfoHash; use url::Url; use crate::console::clients::http::Error; diff --git a/src/console/clients/http/app.rs b/src/console/clients/http/app.rs index a54db5f8b..6730c027d 100644 --- a/src/console/clients/http/app.rs +++ b/src/console/clients/http/app.rs @@ -17,10 +17,10 @@ use std::str::FromStr; use std::time::Duration; use anyhow::Context; +use bittorrent_primitives::info_hash::InfoHash; use clap::{Parser, Subcommand}; use reqwest::Url; use torrust_tracker_configuration::DEFAULT_TIMEOUT; -use torrust_tracker_primitives::info_hash::InfoHash; use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs index c2ba647b8..a2736c365 100644 --- a/src/console/clients/udp/app.rs +++ b/src/console/clients/udp/app.rs @@ -61,9 +61,9 @@ use std::str::FromStr; use anyhow::Context; use aquatic_udp_protocol::{Response, TransactionId}; +use bittorrent_primitives::info_hash::InfoHash as TorrustInfoHash; use clap::{Parser, Subcommand}; use torrust_tracker_configuration::DEFAULT_TIMEOUT; -use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; use tracing::level_filters::LevelFilter; use url::Url; diff --git a/src/console/clients/udp/checker.rs b/src/console/clients/udp/checker.rs index 437af33e0..14e94c132 100644 --- a/src/console/clients/udp/checker.rs +++ b/src/console/clients/udp/checker.rs @@ -7,7 +7,7 @@ use aquatic_udp_protocol::{ AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, Response, ScrapeRequest, TransactionId, }; -use torrust_tracker_primitives::info_hash::InfoHash as TorrustInfoHash; +use bittorrent_primitives::info_hash::InfoHash as TorrustInfoHash; use super::Error; use crate::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; diff --git a/src/core/databases/mod.rs b/src/core/databases/mod.rs index f559eb80e..e29ce22e8 100644 --- a/src/core/databases/mod.rs +++ b/src/core/databases/mod.rs @@ -50,7 +50,7 @@ pub mod sqlite; use std::marker::PhantomData; -use torrust_tracker_primitives::info_hash::InfoHash; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::PersistentTorrents; use self::error::Error; diff --git a/src/core/databases/mysql.rs b/src/core/databases/mysql.rs index 28a5f363b..1b849421b 100644 --- a/src/core/databases/mysql.rs +++ b/src/core/databases/mysql.rs @@ -2,11 +2,11 @@ use std::str::FromStr; use std::time::Duration; +use bittorrent_primitives::info_hash::InfoHash; use r2d2::Pool; use r2d2_mysql::mysql::prelude::Queryable; use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MySqlConnectionManager; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::PersistentTorrents; use super::driver::Driver; diff --git a/src/core/databases/sqlite.rs b/src/core/databases/sqlite.rs index 69470ee04..5bb23bb3e 100644 --- a/src/core/databases/sqlite.rs +++ b/src/core/databases/sqlite.rs @@ -2,11 +2,11 @@ use std::panic::Location; use std::str::FromStr; +use bittorrent_primitives::info_hash::InfoHash; use r2d2::Pool; use r2d2_sqlite::rusqlite::params; use r2d2_sqlite::rusqlite::types::Null; use r2d2_sqlite::SqliteConnectionManager; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrents}; use super::driver::Driver; diff --git a/src/core/error.rs b/src/core/error.rs index d89b030c4..ba87c84c8 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -8,8 +8,8 @@ //! use std::panic::Location; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_located_error::LocatedError; -use torrust_tracker_primitives::info_hash::InfoHash; use super::auth::ParseKeyError; use super::databases; diff --git a/src/core/mod.rs b/src/core/mod.rs index f12eb9a3d..a41ef2eba 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -63,7 +63,7 @@ //! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; //! use torrust_tracker_primitives::DurationSinceUnixEpoch; //! use torrust_tracker_primitives::peer; -//! use torrust_tracker_primitives::info_hash::InfoHash; +//! use bittorrent_primitives::info_hash::InfoHash; //! //! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); //! @@ -136,7 +136,7 @@ //! The returned struct is: //! //! ```rust,no_run -//! use torrust_tracker_primitives::info_hash::InfoHash; +//! use bittorrent_primitives::info_hash::InfoHash; //! use std::collections::HashMap; //! //! pub struct ScrapeData { @@ -165,7 +165,7 @@ //! There are two data structures for infohashes: byte arrays and hex strings: //! //! ```rust,no_run -//! use torrust_tracker_primitives::info_hash::InfoHash; +//! use bittorrent_primitives::info_hash::InfoHash; //! use std::str::FromStr; //! //! let info_hash: InfoHash = [255u8; 20].into(); @@ -456,6 +456,7 @@ use std::sync::Arc; use std::time::Duration; use auth::PeerKey; +use bittorrent_primitives::info_hash::InfoHash; use databases::driver::Driver; use derive_more::Constructor; use error::PeerKeyError; @@ -464,7 +465,6 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_located_error::Located; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; @@ -1253,15 +1253,15 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; - use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; use crate::core::peer::Peer; use crate::core::services::tracker_factory; use crate::core::{TorrentsMetrics, Tracker}; - use crate::shared::bit_torrent::info_hash::fixture::gen_seeded_infohash; fn public_tracker() -> Tracker { tracker_factory(&configuration::ephemeral_public()) @@ -1716,7 +1716,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr}; - use torrust_tracker_primitives::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; use crate::core::tests::the_tracker::{complete_peer, incomplete_peer, public_tracker}; use crate::core::{PeersWanted, ScrapeData, SwarmMetadata}; @@ -1880,7 +1880,7 @@ mod tests { mod handling_an_scrape_request { - use torrust_tracker_primitives::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::core::tests::the_tracker::{ diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 3b014982d..e63d2efa2 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -6,7 +6,7 @@ //! - [`get_torrents`]: it returns data about some torrent in bulk excluding the peer list. use std::sync::Arc; -use torrust_tracker_primitives::info_hash::InfoHash; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::peer; use torrust_tracker_torrent_repository::entry::EntrySync; @@ -125,8 +125,8 @@ mod tests { use std::str::FromStr; use std::sync::Arc; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::Configuration; - use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::core::services::torrent::tests::sample_peer; @@ -178,8 +178,8 @@ mod tests { use std::str::FromStr; use std::sync::Arc; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::Configuration; - use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::core::services::torrent::tests::sample_peer; diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs index ebca504fd..0ba713f62 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/src/servers/apis/v1/context/torrent/handlers.rs @@ -7,9 +7,9 @@ use std::sync::Arc; use axum::extract::{Path, State}; use axum::response::{IntoResponse, Response}; use axum_extra::extract::Query; +use bittorrent_primitives::info_hash::InfoHash; use serde::{de, Deserialize, Deserializer}; use thiserror::Error; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs index 657382c0c..8fbb89418 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs @@ -98,7 +98,7 @@ mod tests { use std::str::FromStr; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; - use torrust_tracker_primitives::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use super::Torrent; diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/src/servers/apis/v1/context/whitelist/handlers.rs index 32e434918..04085f8ab 100644 --- a/src/servers/apis/v1/context/whitelist/handlers.rs +++ b/src/servers/apis/v1/context/whitelist/handlers.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use axum::extract::{Path, State}; use axum::response::Response; -use torrust_tracker_primitives::info_hash::InfoHash; +use bittorrent_primitives::info_hash::InfoHash; use super::responses::{ failed_to_reload_whitelist_response, failed_to_remove_torrent_from_whitelist_response, failed_to_whitelist_torrent_response, diff --git a/src/servers/http/percent_encoding.rs b/src/servers/http/percent_encoding.rs index c3243d597..323444cc7 100644 --- a/src/servers/http/percent_encoding.rs +++ b/src/servers/http/percent_encoding.rs @@ -16,7 +16,7 @@ //! - //! - use aquatic_udp_protocol::PeerId; -use torrust_tracker_primitives::info_hash::{self, InfoHash}; +use bittorrent_primitives::info_hash::{self, InfoHash}; use torrust_tracker_primitives::peer; /// Percent decodes a percent encoded infohash. Internally an @@ -28,7 +28,7 @@ use torrust_tracker_primitives::peer; /// ```rust /// use std::str::FromStr; /// use torrust_tracker::servers::http::percent_encoding::percent_decode_info_hash; -/// use torrust_tracker_primitives::info_hash::InfoHash; +/// use bittorrent_primitives::info_hash::InfoHash; /// use torrust_tracker_primitives::peer; /// /// let encoded_infohash = "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0"; @@ -61,7 +61,7 @@ pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result) -> Result) -> AnnounceEvent { mod tests { use aquatic_udp_protocol::PeerId; - use torrust_tracker_primitives::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index ca4c85207..10f945d70 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -110,7 +110,7 @@ mod tests { use std::net::IpAddr; use std::str::FromStr; - use torrust_tracker_primitives::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index 029bdbc01..a9a9f8a76 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -6,9 +6,9 @@ use std::panic::Location; use std::str::FromStr; use aquatic_udp_protocol::{NumberOfBytes, PeerId}; +use bittorrent_primitives::info_hash::{self, InfoHash}; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; -use torrust_tracker_primitives::info_hash::{self, InfoHash}; use torrust_tracker_primitives::peer; use crate::servers::http::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; @@ -32,7 +32,7 @@ const NUMWANT: &str = "numwant"; /// ```rust /// use aquatic_udp_protocol::{NumberOfBytes, PeerId}; /// use torrust_tracker::servers::http::v1::requests::announce::{Announce, Compact, Event}; -/// use torrust_tracker_primitives::info_hash::InfoHash; +/// use bittorrent_primitives::info_hash::InfoHash; /// /// let request = Announce { /// // Mandatory params @@ -379,7 +379,7 @@ mod tests { mod announce_request { use aquatic_udp_protocol::{NumberOfBytes, PeerId}; - use torrust_tracker_primitives::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; use crate::servers::http::v1::query::Query; use crate::servers::http::v1::requests::announce::{ diff --git a/src/servers/http/v1/requests/scrape.rs b/src/servers/http/v1/requests/scrape.rs index c61d3be1f..0a47a4fb4 100644 --- a/src/servers/http/v1/requests/scrape.rs +++ b/src/servers/http/v1/requests/scrape.rs @@ -3,9 +3,9 @@ //! Data structures and logic for parsing the `scrape` request. use std::panic::Location; +use bittorrent_primitives::info_hash::{self, InfoHash}; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; -use torrust_tracker_primitives::info_hash::{self, InfoHash}; use crate::servers::http::percent_encoding::percent_decode_info_hash; use crate::servers::http::v1::query::Query; @@ -84,7 +84,7 @@ mod tests { mod scrape_request { - use torrust_tracker_primitives::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; use crate::servers::http::v1::query::Query; use crate::servers::http::v1::requests::scrape::{Scrape, INFO_HASH}; diff --git a/src/servers/http/v1/responses/scrape.rs b/src/servers/http/v1/responses/scrape.rs index 9690d4392..0aef70cb1 100644 --- a/src/servers/http/v1/responses/scrape.rs +++ b/src/servers/http/v1/responses/scrape.rs @@ -13,7 +13,7 @@ use crate::core::ScrapeData; /// /// ```rust /// use torrust_tracker::servers::http::v1::responses::scrape::Bencoded; -/// use torrust_tracker_primitives::info_hash::InfoHash; +/// use bittorrent_primitives::info_hash::InfoHash; /// use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; /// use torrust_tracker::core::ScrapeData; /// @@ -92,7 +92,7 @@ impl IntoResponse for Bencoded { mod tests { mod scrape_response { - use torrust_tracker_primitives::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::core::ScrapeData; diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 9c5dfdad2..51ec43d56 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -11,7 +11,7 @@ use std::net::IpAddr; use std::sync::Arc; -use torrust_tracker_primitives::info_hash::InfoHash; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer; use crate::core::{statistics, AnnounceData, PeersWanted, Tracker}; @@ -54,7 +54,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; - use torrust_tracker_primitives::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 0d561c7bc..f040e0430 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -11,7 +11,7 @@ use std::net::IpAddr; use std::sync::Arc; -use torrust_tracker_primitives::info_hash::InfoHash; +use bittorrent_primitives::info_hash::InfoHash; use crate::core::{statistics, ScrapeData, Tracker}; @@ -62,7 +62,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; - use torrust_tracker_primitives::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 69a427e0e..6af634c32 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -10,8 +10,8 @@ use aquatic_udp_protocol::{ ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfDownloads, NumberOfPeers, Port, Request, Response, ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_located_error::DynError; -use torrust_tracker_primitives::info_hash::InfoHash; use tracing::{instrument, Level}; use uuid::Uuid; use zerocopy::network_endian::I32; diff --git a/src/servers/udp/logging.rs b/src/servers/udp/logging.rs index 3891278d7..a61668e83 100644 --- a/src/servers/udp/logging.rs +++ b/src/servers/udp/logging.rs @@ -4,7 +4,7 @@ use std::net::SocketAddr; use std::time::Duration; use aquatic_udp_protocol::{Request, Response, TransactionId}; -use torrust_tracker_primitives::info_hash::InfoHash; +use bittorrent_primitives::info_hash::InfoHash; use super::handlers::RequestId; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index 91b19a91d..d41bc8b3f 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -342,7 +342,7 @@ //! > packet. //! //! We are using a wrapper struct for the aquatic [`AnnounceRequest`](aquatic_udp_protocol::request::AnnounceRequest) -//! struct, because we have our internal [`InfoHash`](torrust_tracker_primitives::info_hash::InfoHash) +//! struct, because we have our internal [`InfoHash`](bittorrent_primitives::info_hash::InfoHash) //! struct. //! //! ```text diff --git a/src/shared/bit_torrent/info_hash.rs b/src/shared/bit_torrent/info_hash.rs deleted file mode 100644 index 506c37758..000000000 --- a/src/shared/bit_torrent/info_hash.rs +++ /dev/null @@ -1,288 +0,0 @@ -//! A `BitTorrent` `InfoHash`. It's a unique identifier for a `BitTorrent` torrent. -//! -//! "The 20-byte sha1 hash of the bencoded form of the info value -//! from the metainfo file." -//! -//! See [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -//! for the official specification. -//! -//! This modules provides a type that can be used to represent infohashes. -//! -//! > **NOTICE**: It only supports Info Hash v1. -//! -//! Typically infohashes are represented as hex strings, but internally they are -//! a 20-byte array. -//! -//! # Calculating the info-hash of a torrent file -//! -//! A sample torrent: -//! -//! - Torrent file: `mandelbrot_2048x2048_infohash_v1.png.torrent` -//! - File: `mandelbrot_2048x2048.png` -//! - Info Hash v1: `5452869be36f9f3350ccee6b4544e7e76caaadab` -//! - Sha1 hash of the info dictionary: `5452869BE36F9F3350CCEE6B4544E7E76CAAADAB` -//! -//! A torrent file is a binary file encoded with [Bencode encoding](https://en.wikipedia.org/wiki/Bencode): -//! -//! ```text -//! 0000000: 6431 303a 6372 6561 7465 6420 6279 3138 d10:created by18 -//! 0000010: 3a71 4269 7474 6f72 7265 6e74 2076 342e :qBittorrent v4. -//! 0000020: 342e 3131 333a 6372 6561 7469 6f6e 2064 4.113:creation d -//! 0000030: 6174 6569 3136 3739 3637 3436 3238 6534 atei1679674628e4 -//! 0000040: 3a69 6e66 6f64 363a 6c65 6e67 7468 6931 :infod6:lengthi1 -//! 0000050: 3732 3230 3465 343a 6e61 6d65 3234 3a6d 72204e4:name24:m -//! 0000060: 616e 6465 6c62 726f 745f 3230 3438 7832 andelbrot_2048x2 -//! 0000070: 3034 382e 706e 6731 323a 7069 6563 6520 048.png12:piece -//! 0000080: 6c65 6e67 7468 6931 3633 3834 6536 3a70 lengthi16384e6:p -//! 0000090: 6965 6365 7332 3230 3a7d 9171 0d9d 4dba ieces220:}.q..M. -//! 00000a0: 889b 5420 54d5 2672 8d5a 863f e121 df77 ..T T.&r.Z.?.!.w -//! 00000b0: c7f7 bb6c 7796 2166 2538 c5d9 cdab 8b08 ...lw.!f%8...... -//! 00000c0: ef8c 249b b2f5 c4cd 2adf 0bc0 0cf0 addf ..$.....*....... -//! 00000d0: 7290 e5b6 414c 236c 479b 8e9f 46aa 0c0d r...AL#lG...F... -//! 00000e0: 8ed1 97ff ee68 8b5f 34a3 87d7 71c5 a6f9 .....h._4...q... -//! 00000f0: 8e2e a631 7cbd f0f9 e223 f9cc 80af 5400 ...1|....#....T. -//! 0000100: 04f9 8569 1c77 89c1 764e d6aa bf61 a6c2 ...i.w..vN...a.. -//! 0000110: 8099 abb6 5f60 2f40 a825 be32 a33d 9d07 ...._`/@.%.2.=.. -//! 0000120: 0c79 6898 d49d 6349 af20 5866 266f 986b .yh...cI. Xf&o.k -//! 0000130: 6d32 34cd 7d08 155e 1ad0 0009 57ab 303b m24.}..^....W.0; -//! 0000140: 2060 c1dc 1287 d6f3 e745 4f70 6709 3631 `.......EOpg.61 -//! 0000150: 55f2 20f6 6ca5 156f 2c89 9569 1653 817d U. .l..o,..i.S.} -//! 0000160: 31f1 b6bd 3742 cc11 0bb2 fc2b 49a5 85b6 1...7B.....+I... -//! 0000170: fc76 7444 9365 65 .vtD.ee -//! ``` -//! -//! You can generate that output with the command: -//! -//! ```text -//! xxd mandelbrot_2048x2048_infohash_v1.png.torrent -//! ``` -//! -//! And you can show only the bytes (hexadecimal): -//! -//! ```text -//! 6431303a6372656174656420627931383a71426974746f7272656e742076 -//! 342e342e3131333a6372656174696f6e2064617465693136373936373436 -//! 323865343a696e666f64363a6c656e6774686931373232303465343a6e61 -//! 6d6532343a6d616e64656c62726f745f3230343878323034382e706e6731 -//! 323a7069656365206c656e67746869313633383465363a70696563657332 -//! 32303a7d91710d9d4dba889b542054d526728d5a863fe121df77c7f7bb6c -//! 779621662538c5d9cdab8b08ef8c249bb2f5c4cd2adf0bc00cf0addf7290 -//! e5b6414c236c479b8e9f46aa0c0d8ed197ffee688b5f34a387d771c5a6f9 -//! 8e2ea6317cbdf0f9e223f9cc80af540004f985691c7789c1764ed6aabf61 -//! a6c28099abb65f602f40a825be32a33d9d070c796898d49d6349af205866 -//! 266f986b6d3234cd7d08155e1ad0000957ab303b2060c1dc1287d6f3e745 -//! 4f706709363155f220f66ca5156f2c8995691653817d31f1b6bd3742cc11 -//! 0bb2fc2b49a585b6fc767444936565 -//! ``` -//! -//! You can generate that output with the command: -//! -//! ```text -//! `xxd -ps mandelbrot_2048x2048_infohash_v1.png.torrent`. -//! ``` -//! -//! The same data can be represented in a JSON format: -//! -//! ```json -//! { -//! "created by": "qBittorrent v4.4.1", -//! "creation date": 1679674628, -//! "info": { -//! "length": 172204, -//! "name": "mandelbrot_2048x2048.png", -//! "piece length": 16384, -//! "pieces": "7D 91 71 0D 9D 4D BA 88 9B 54 20 54 D5 26 72 8D 5A 86 3F E1 21 DF 77 C7 F7 BB 6C 77 96 21 66 25 38 C5 D9 CD AB 8B 08 EF 8C 24 9B B2 F5 C4 CD 2A DF 0B C0 0C F0 AD DF 72 90 E5 B6 41 4C 23 6C 47 9B 8E 9F 46 AA 0C 0D 8E D1 97 FF EE 68 8B 5F 34 A3 87 D7 71 C5 A6 F9 8E 2E A6 31 7C BD F0 F9 E2 23 F9 CC 80 AF 54 00 04 F9 85 69 1C 77 89 C1 76 4E D6 AA BF 61 A6 C2 80 99 AB B6 5F 60 2F 40 A8 25 BE 32 A3 3D 9D 07 0C 79 68 98 D4 9D 63 49 AF 20 58 66 26 6F 98 6B 6D 32 34 CD 7D 08 15 5E 1A D0 00 09 57 AB 30 3B 20 60 C1 DC 12 87 D6 F3 E7 45 4F 70 67 09 36 31 55 F2 20 F6 6C A5 15 6F 2C 89 95 69 16 53 81 7D 31 F1 B6 BD 37 42 CC 11 0B B2 FC 2B 49 A5 85 B6 FC 76 74 44 93" -//! } -//! } -//! ``` -//! -//! The JSON object was generated with: -//! -//! As you can see, there is a `info` attribute: -//! -//! ```json -//! { -//! "length": 172204, -//! "name": "mandelbrot_2048x2048.png", -//! "piece length": 16384, -//! "pieces": "7D 91 71 0D 9D 4D BA 88 9B 54 20 54 D5 26 72 8D 5A 86 3F E1 21 DF 77 C7 F7 BB 6C 77 96 21 66 25 38 C5 D9 CD AB 8B 08 EF 8C 24 9B B2 F5 C4 CD 2A DF 0B C0 0C F0 AD DF 72 90 E5 B6 41 4C 23 6C 47 9B 8E 9F 46 AA 0C 0D 8E D1 97 FF EE 68 8B 5F 34 A3 87 D7 71 C5 A6 F9 8E 2E A6 31 7C BD F0 F9 E2 23 F9 CC 80 AF 54 00 04 F9 85 69 1C 77 89 C1 76 4E D6 AA BF 61 A6 C2 80 99 AB B6 5F 60 2F 40 A8 25 BE 32 A3 3D 9D 07 0C 79 68 98 D4 9D 63 49 AF 20 58 66 26 6F 98 6B 6D 32 34 CD 7D 08 15 5E 1A D0 00 09 57 AB 30 3B 20 60 C1 DC 12 87 D6 F3 E7 45 4F 70 67 09 36 31 55 F2 20 F6 6C A5 15 6F 2C 89 95 69 16 53 81 7D 31 F1 B6 BD 37 42 CC 11 0B B2 FC 2B 49 A5 85 B6 FC 76 74 44 93" -//! } -//! ``` -//! -//! The infohash is the [SHA1](https://en.wikipedia.org/wiki/SHA-1) hash -//! of the `info` attribute. That is, the SHA1 hash of: -//! -//! ```text -//! 64363a6c656e6774686931373232303465343a6e61 -//! d6532343a6d616e64656c62726f745f3230343878323034382e706e6731 -//! 23a7069656365206c656e67746869313633383465363a70696563657332 -//! 2303a7d91710d9d4dba889b542054d526728d5a863fe121df77c7f7bb6c -//! 79621662538c5d9cdab8b08ef8c249bb2f5c4cd2adf0bc00cf0addf7290 -//! 5b6414c236c479b8e9f46aa0c0d8ed197ffee688b5f34a387d771c5a6f9 -//! e2ea6317cbdf0f9e223f9cc80af540004f985691c7789c1764ed6aabf61 -//! 6c28099abb65f602f40a825be32a33d9d070c796898d49d6349af205866 -//! 66f986b6d3234cd7d08155e1ad0000957ab303b2060c1dc1287d6f3e745 -//! f706709363155f220f66ca5156f2c8995691653817d31f1b6bd3742cc11 -//! bb2fc2b49a585b6fc7674449365 -//! ``` -//! -//! You can hash that byte string with -//! -//! The result is a 20-char string: `5452869BE36F9F3350CCEE6B4544E7E76CAAADAB` - -use torrust_tracker_primitives::info_hash::InfoHash; - -pub mod fixture { - use std::hash::{DefaultHasher, Hash, Hasher}; - - use super::InfoHash; - - /// Generate as semi-stable pseudo-random infohash - /// - /// Note: If the [`DefaultHasher`] implementation changes - /// so will the resulting info-hashes. - /// - /// The results should not be relied upon between versions. - #[must_use] - pub fn gen_seeded_infohash(seed: &u64) -> InfoHash { - let mut buf_a: [[u8; 8]; 4] = Default::default(); - let mut buf_b = InfoHash::default(); - - let mut hasher = DefaultHasher::new(); - seed.hash(&mut hasher); - - for u in &mut buf_a { - seed.hash(&mut hasher); - *u = hasher.finish().to_le_bytes(); - } - - for (a, b) in buf_a.iter().flat_map(|a| a.iter()).zip(buf_b.0.iter_mut()) { - *b = *a; - } - - buf_b - } -} - -#[cfg(test)] -mod tests { - - use std::str::FromStr; - - use serde::{Deserialize, Serialize}; - use serde_json::json; - - use super::InfoHash; - - #[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)] - struct ContainingInfoHash { - pub info_hash: InfoHash, - } - - #[test] - fn an_info_hash_can_be_created_from_a_valid_40_utf8_char_string_representing_an_hexadecimal_value() { - let info_hash = InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); - assert!(info_hash.is_ok()); - } - - #[test] - fn an_info_hash_can_not_be_created_from_a_utf8_string_representing_a_not_valid_hexadecimal_value() { - let info_hash = InfoHash::from_str("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG"); - assert!(info_hash.is_err()); - } - - #[test] - fn an_info_hash_can_only_be_created_from_a_40_utf8_char_string() { - let info_hash = InfoHash::from_str(&"F".repeat(39)); - assert!(info_hash.is_err()); - - let info_hash = InfoHash::from_str(&"F".repeat(41)); - assert!(info_hash.is_err()); - } - - #[test] - fn an_info_hash_should_by_displayed_like_a_40_utf8_lowercased_char_hex_string() { - let info_hash = InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(); - - let output = format!("{info_hash}"); - - assert_eq!(output, "ffffffffffffffffffffffffffffffffffffffff"); - } - - #[test] - fn an_info_hash_should_return_its_a_40_utf8_lowercased_char_hex_representations_as_string() { - let info_hash = InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(); - - assert_eq!(info_hash.to_hex_string(), "ffffffffffffffffffffffffffffffffffffffff"); - } - - #[test] - fn an_info_hash_can_be_created_from_a_valid_20_byte_array_slice() { - let info_hash: InfoHash = [255u8; 20].as_slice().into(); - - assert_eq!( - info_hash, - InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() - ); - } - - #[test] - fn an_info_hash_can_be_created_from_a_valid_20_byte_array() { - let info_hash: InfoHash = [255u8; 20].into(); - - assert_eq!( - info_hash, - InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() - ); - } - - #[test] - fn an_info_hash_can_be_created_from_a_byte_vector() { - let info_hash: InfoHash = [255u8; 20].to_vec().try_into().unwrap(); - - assert_eq!( - info_hash, - InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() - ); - } - - #[test] - fn it_should_fail_trying_to_create_an_info_hash_from_a_byte_vector_with_less_than_20_bytes() { - assert!(InfoHash::try_from([255u8; 19].to_vec()).is_err()); - } - - #[test] - fn it_should_fail_trying_to_create_an_info_hash_from_a_byte_vector_with_more_than_20_bytes() { - assert!(InfoHash::try_from([255u8; 21].to_vec()).is_err()); - } - - #[test] - fn an_info_hash_can_be_serialized() { - let s = ContainingInfoHash { - info_hash: InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap(), - }; - - let json_serialized_value = serde_json::to_string(&s).unwrap(); - - assert_eq!( - json_serialized_value, - r#"{"info_hash":"ffffffffffffffffffffffffffffffffffffffff"}"# - ); - } - - #[test] - fn an_info_hash_can_be_deserialized() { - let json = json!({ - "info_hash": "ffffffffffffffffffffffffffffffffffffffff", - }); - - let s: ContainingInfoHash = serde_json::from_value(json).unwrap(); - - assert_eq!( - s, - ContainingInfoHash { - info_hash: InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() - } - ); - } -} diff --git a/src/shared/bit_torrent/mod.rs b/src/shared/bit_torrent/mod.rs index 8074661be..7d6b12f09 100644 --- a/src/shared/bit_torrent/mod.rs +++ b/src/shared/bit_torrent/mod.rs @@ -68,5 +68,4 @@ //! Percent Encoding spec | //!Bencode & bdecode in your browser | pub mod common; -pub mod info_hash; pub mod tracker; diff --git a/src/shared/bit_torrent/tracker/http/client/requests/announce.rs b/src/shared/bit_torrent/tracker/http/client/requests/announce.rs index 3c6b14222..f3ce327ea 100644 --- a/src/shared/bit_torrent/tracker/http/client/requests/announce.rs +++ b/src/shared/bit_torrent/tracker/http/client/requests/announce.rs @@ -3,8 +3,8 @@ use std::net::{IpAddr, Ipv4Addr}; use std::str::FromStr; use aquatic_udp_protocol::PeerId; +use bittorrent_primitives::info_hash::InfoHash; use serde_repr::Serialize_repr; -use torrust_tracker_primitives::info_hash::InfoHash; use crate::shared::bit_torrent::tracker::http::{percent_encode_byte_array, ByteArray20}; diff --git a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs index 4d12fc2d2..58b9e0dc7 100644 --- a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs +++ b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs @@ -2,7 +2,7 @@ use std::error::Error; use std::fmt::{self}; use std::str::FromStr; -use torrust_tracker_primitives::info_hash::InfoHash; +use bittorrent_primitives::info_hash::InfoHash; use crate::shared::bit_torrent::tracker::http::{percent_encode_byte_array, ByteArray20}; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 2f4606be7..bffe42603 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -1,6 +1,7 @@ use std::net::SocketAddr; use std::sync::Arc; +use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; use torrust_tracker::bootstrap::app::initialize_with_configuration; use torrust_tracker::bootstrap::jobs::make_rust_tls; @@ -8,7 +9,6 @@ use torrust_tracker::core::Tracker; use torrust_tracker::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker::servers::registar::Registar; use torrust_tracker_configuration::{Configuration, HttpApi}; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer; use super::connection_info::ConnectionInfo; diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index a034a7778..2c8e8d6a5 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -1,7 +1,7 @@ use std::str::FromStr; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker::servers::apis::v1::context::stats::resources::Stats; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index f5e930be3..e500ac63c 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -1,8 +1,8 @@ use std::str::FromStr; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker::servers::apis::v1::context::torrent::resources::peer::Peer; use torrust_tracker::servers::apis::v1::context::torrent::resources::torrent::{self, Torrent}; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index b30a7dbf8..49ce3e865 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -1,6 +1,6 @@ use std::str::FromStr; -use torrust_tracker_primitives::info_hash::InfoHash; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index b6bb21c16..20b126c18 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; use torrust_tracker::bootstrap::app::initialize_with_configuration; use torrust_tracker::bootstrap::jobs::make_rust_tls; @@ -7,7 +8,6 @@ use torrust_tracker::core::Tracker; use torrust_tracker::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker::servers::registar::Registar; use torrust_tracker_configuration::{Configuration, HttpTracker}; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer; pub struct Environment { diff --git a/tests/servers/http/requests/announce.rs b/tests/servers/http/requests/announce.rs index fa20553d0..740c86d38 100644 --- a/tests/servers/http/requests/announce.rs +++ b/tests/servers/http/requests/announce.rs @@ -3,8 +3,8 @@ use std::net::{IpAddr, Ipv4Addr}; use std::str::FromStr; use aquatic_udp_protocol::PeerId; +use bittorrent_primitives::info_hash::InfoHash; use serde_repr::Serialize_repr; -use torrust_tracker_primitives::info_hash::InfoHash; use crate::servers::http::{percent_encode_byte_array, ByteArray20}; diff --git a/tests/servers/http/requests/scrape.rs b/tests/servers/http/requests/scrape.rs index f66605855..ecef541f1 100644 --- a/tests/servers/http/requests/scrape.rs +++ b/tests/servers/http/requests/scrape.rs @@ -1,7 +1,7 @@ use std::fmt; use std::str::FromStr; -use torrust_tracker_primitives::info_hash::InfoHash; +use bittorrent_primitives::info_hash::InfoHash; use crate::servers::http::{percent_encode_byte_array, ByteArray20}; diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 405a35dc5..554849aee 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -103,10 +103,10 @@ mod for_all_config_modes { use std::str::FromStr; use aquatic_udp_protocol::PeerId; + use bittorrent_primitives::info_hash::InfoHash; use local_ip_address::local_ip; use reqwest::{Response, StatusCode}; use tokio::net::TcpListener; - use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; @@ -1042,8 +1042,8 @@ mod for_all_config_modes { use std::str::FromStr; use aquatic_udp_protocol::PeerId; + use bittorrent_primitives::info_hash::InfoHash; use tokio::net::TcpListener; - use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; @@ -1300,7 +1300,7 @@ mod configured_as_whitelisted { mod and_receiving_an_announce_request { use std::str::FromStr; - use torrust_tracker_primitives::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; @@ -1358,7 +1358,7 @@ mod configured_as_whitelisted { use std::str::FromStr; use aquatic_udp_protocol::PeerId; - use torrust_tracker_primitives::info_hash::InfoHash; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; @@ -1457,8 +1457,8 @@ mod configured_as_private { use std::str::FromStr; use std::time::Duration; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker::core::auth::Key; - use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; @@ -1552,8 +1552,8 @@ mod configured_as_private { use std::time::Duration; use aquatic_udp_protocol::PeerId; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker::core::auth::Key; - use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index b7ac2336c..83dc076ce 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -1,6 +1,7 @@ use std::net::SocketAddr; use std::sync::Arc; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker::bootstrap::app::initialize_with_configuration; use torrust_tracker::core::Tracker; use torrust_tracker::servers::registar::Registar; @@ -8,7 +9,6 @@ use torrust_tracker::servers::udp::server::spawner::Spawner; use torrust_tracker::servers::udp::server::states::{Running, Stopped}; use torrust_tracker::servers::udp::server::Server; use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; -use torrust_tracker_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer; pub struct Environment From d5af5d3081f61b40edae0a3102f9ce1c97ea47eb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 1 Nov 2024 08:53:55 +0000 Subject: [PATCH 0507/1297] chore(deps): uddate deps ``` cargo update Updating crates.io index Locking 96 packages to latest compatible versions Updating addr2line v0.24.1 -> v0.24.2 Updating anstream v0.6.15 -> v0.6.17 Updating anstyle v1.0.8 -> v1.0.9 Updating anstyle-parse v0.2.5 -> v0.2.6 Updating anstyle-query v1.1.1 -> v1.1.2 Updating anstyle-wincon v3.0.4 -> v3.0.6 Updating anyhow v1.0.89 -> v1.0.92 Updating async-compression v0.4.12 -> v0.4.17 Updating async-trait v0.1.82 -> v0.1.83 Updating autocfg v1.3.0 -> v1.4.0 Updating aws-lc-rs v1.9.0 -> v1.10.0 Updating aws-lc-sys v0.21.2 -> v0.22.0 Updating axum v0.7.6 -> v0.7.7 Updating axum-client-ip v0.6.0 -> v0.6.1 Updating axum-core v0.4.4 -> v0.4.5 Updating bigdecimal v0.4.5 -> v0.4.6 Updating bindgen v0.69.4 -> v0.69.5 Updating brotli v6.0.0 -> v7.0.0 Updating bytemuck v1.18.0 -> v1.19.0 Updating bytes v1.7.2 -> v1.8.0 Updating cc v1.1.21 -> v1.1.31 Updating clap v4.5.18 -> v4.5.20 Updating clap_builder v4.5.18 -> v4.5.20 Updating colorchoice v1.0.2 -> v1.0.3 Updating encoding_rs v0.8.34 -> v0.8.35 Updating flate2 v1.0.33 -> v1.0.34 Adding foldhash v0.1.3 Updating futures v0.3.30 -> v0.3.31 Updating futures-channel v0.3.30 -> v0.3.31 Updating futures-core v0.3.30 -> v0.3.31 Updating futures-executor v0.3.30 -> v0.3.31 Updating futures-io v0.3.30 -> v0.3.31 Updating futures-lite v2.3.0 -> v2.4.0 Updating futures-macro v0.3.30 -> v0.3.31 Updating futures-sink v0.3.30 -> v0.3.31 Updating futures-task v0.3.30 -> v0.3.31 Updating futures-util v0.3.30 -> v0.3.31 Updating gimli v0.31.0 -> v0.31.1 Adding hashbrown v0.15.0 Updating httparse v1.9.4 -> v1.9.5 Updating hyper v1.4.1 -> v1.5.0 Updating hyper-util v0.1.8 -> v0.1.10 Updating indexmap v2.5.0 -> v2.6.0 Updating ipnet v2.10.0 -> v2.10.1 Updating js-sys v0.3.70 -> v0.3.72 Updating libc v0.2.158 -> v0.2.161 Updating libm v0.2.8 -> v0.2.11 Updating lru v0.12.4 -> v0.12.5 Updating object v0.36.4 -> v0.36.5 Updating once_cell v1.19.0 -> v1.20.2 Updating openssl v0.10.66 -> v0.10.68 Updating openssl-sys v0.9.103 -> v0.9.104 Updating pin-project v1.1.5 -> v1.1.7 Updating pin-project-internal v1.1.5 -> v1.1.7 Updating pin-project-lite v0.2.14 -> v0.2.15 Adding portable-atomic v1.9.0 Updating prettyplease v0.2.22 -> v0.2.25 Updating proc-macro2 v1.0.86 -> v1.0.89 Updating redox_syscall v0.5.4 -> v0.5.7 Updating regex v1.10.6 -> v1.11.1 Updating regex-automata v0.4.7 -> v0.4.8 Updating regex-syntax v0.8.4 -> v0.8.5 Updating reqwest v0.12.7 -> v0.12.9 Updating ringbuf v0.4.4 -> v0.4.7 Updating rstest v0.22.0 -> v0.23.0 Updating rstest_macros v0.22.0 -> v0.23.0 Updating rustix v0.38.37 -> v0.38.38 Updating rustls v0.23.13 -> v0.23.16 Updating rustls-pemfile v2.1.3 -> v2.2.0 Updating rustls-pki-types v1.8.0 -> v1.10.0 Updating rustversion v1.0.17 -> v1.0.18 Updating schannel v0.1.24 -> v0.1.26 Updating serde v1.0.210 -> v1.0.214 Updating serde_derive v1.0.210 -> v1.0.214 Updating serde_spanned v0.6.7 -> v0.6.8 Updating serde_with v3.9.0 -> v3.11.0 Updating serde_with_macros v3.9.0 -> v3.11.0 Updating syn v2.0.77 -> v2.0.86 Updating tempfile v3.12.0 -> v3.13.0 Updating thiserror v1.0.65 -> v1.0.66 Updating thiserror-impl v1.0.65 -> v1.0.66 Updating tokio v1.40.0 -> v1.41.0 Updating toml_edit v0.22.21 -> v0.22.22 Updating unicode-bidi v0.3.15 -> v0.3.17 Updating uuid v1.10.0 -> v1.11.0 Updating value-bag v1.9.0 -> v1.10.0 Updating wasm-bindgen v0.2.93 -> v0.2.95 Updating wasm-bindgen-backend v0.2.93 -> v0.2.95 Updating wasm-bindgen-futures v0.4.43 -> v0.4.45 Updating wasm-bindgen-macro v0.2.93 -> v0.2.95 Updating wasm-bindgen-macro-support v0.2.93 -> v0.2.95 Updating wasm-bindgen-shared v0.2.93 -> v0.2.95 Updating web-sys v0.3.70 -> v0.3.72 Updating winnow v0.6.18 -> v0.6.20 Adding zerocopy v0.8.8 Adding zerocopy-derive v0.8.8 ``` --- Cargo.lock | 512 +++++++++++++++++++++++++++++------------------------ 1 file changed, 276 insertions(+), 236 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9dade94be..9788725db 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "addr2line" -version = "0.24.1" +version = "0.24.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5fb1d8e4442bd405fdfd1dacb42792696b0cf9cb15882e5d097b742a676d375" +checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" dependencies = [ "gimli", ] @@ -37,7 +37,7 @@ dependencies = [ "cfg-if", "once_cell", "version_check", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -93,9 +93,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.15" +version = "0.6.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64e15c1ab1f89faffbf04a634d5e1962e9074f2741eef6d97f3c4e322426d526" +checksum = "23a1e53f0f5d86382dafe1cf314783b2044280f406e7e1506368220ad11b1338" dependencies = [ "anstyle", "anstyle-parse", @@ -108,43 +108,43 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.8" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1" +checksum = "8365de52b16c035ff4fcafe0092ba9390540e3e352870ac09933bebcaa2c8c56" [[package]] name = "anstyle-parse" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb47de1e80c2b463c735db5b217a0ddc39d612e7ac9e2e96a5aed1f57616c1cb" +checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.1.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d36fc52c7f6c869915e99412912f22093507da8d9e942ceaf66fe4b7c14422a" +checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] name = "anstyle-wincon" -version = "3.0.4" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bf74e1b6e971609db8ca7a9ce79fd5768ab6ae46441c572e46cf596f59e57f8" +checksum = "2109dbce0e72be3ec00bed26e6a7479ca384ad226efdd66db8fa2e3a38c83125" dependencies = [ "anstyle", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] name = "anyhow" -version = "1.0.89" +version = "1.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86fdf8605db99b54d3cd748a44c6d04df638eb5dafb219b135d0149bd0db01f6" +checksum = "74f37166d7d48a0284b99dd824694c26119c700b53bf0d1540cdb147dbdaaf13" [[package]] name = "aquatic_peer_id" @@ -157,7 +157,7 @@ dependencies = [ "quickcheck", "regex", "serde", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -169,7 +169,7 @@ dependencies = [ "aquatic_peer_id", "byteorder", "either", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -219,9 +219,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.12" +version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fec134f64e2bc57411226dfc4e52dec859ddfc7e711fc5e07b612584f000e4aa" +checksum = "0cb8f1d480b0ea3783ab015936d2a55c87e219676f0c0b7dec61494043f21857" dependencies = [ "brotli", "flate2", @@ -327,13 +327,13 @@ checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" [[package]] name = "async-trait" -version = "0.1.82" +version = "0.1.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a27b8a3a6e1a44fa4c8baf1f653e4172e81486d4941f2237e20dc2d0cf4ddff1" +checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -353,15 +353,15 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.3.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "aws-lc-rs" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f95446d919226d587817a7d21379e6eb099b97b45110a7f272a444ca5c54070" +checksum = "cdd82dba44d209fddb11c190e0a94b78651f95299598e472215667417a03ff1d" dependencies = [ "aws-lc-sys", "mirai-annotations", @@ -371,11 +371,11 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.21.2" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3ddc4a5b231dd6958b140ff3151b6412b3f4321fab354f399eec8f14b06df62" +checksum = "df7a4168111d7eb622a31b214057b8509c0a7e1794f44c546d742330dc793972" dependencies = [ - "bindgen 0.69.4", + "bindgen 0.69.5", "cc", "cmake", "dunce", @@ -386,9 +386,9 @@ dependencies = [ [[package]] name = "axum" -version = "0.7.6" +version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f43644eed690f5374f1af436ecd6aea01cd201f6fbdf0178adaf6907afb2cec" +checksum = "504e3947307ac8326a5437504c517c4b56716c9d98fac0028c2acc7ca47d70ae" dependencies = [ "async-trait", "axum-core", @@ -421,9 +421,9 @@ dependencies = [ [[package]] name = "axum-client-ip" -version = "0.6.0" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72188bed20deb981f3a4a9fe674e5980fd9e9c2bd880baa94715ad5d60d64c67" +checksum = "9eefda7e2b27e1bda4d6fa8a06b50803b8793769045918bc37ad062d48a6efac" dependencies = [ "axum", "forwarded-header-value", @@ -432,9 +432,9 @@ dependencies = [ [[package]] name = "axum-core" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6b8ba012a258d63c9adfa28b9ddcf66149da6f986c5b5452e629d5ee64bf00" +checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" dependencies = [ "async-trait", "bytes", @@ -482,7 +482,7 @@ checksum = "57d123550fa8d071b7255cb0cc04dc302baa6c8c4a79f55701552684d8399bce" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -538,9 +538,9 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "bigdecimal" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d712318a27c7150326677b321a5fa91b55f6d9034ffd67f20319e147d40cee" +checksum = "8f850665a0385e070b64c38d2354e6c104c8479c59868d1e48a0c13ee2c7a1c1" dependencies = [ "autocfg", "libm", @@ -557,9 +557,9 @@ checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" [[package]] name = "bindgen" -version = "0.69.4" +version = "0.69.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a00dc851838a2120612785d195287475a3ac45514741da670b735818822129a0" +checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088" dependencies = [ "bitflags", "cexpr", @@ -574,7 +574,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.77", + "syn 2.0.86", "which", ] @@ -593,7 +593,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -613,7 +613,7 @@ dependencies = [ "serde", "serde_json", "thiserror", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -670,15 +670,15 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", "syn_derive", ] [[package]] name = "brotli" -version = "6.0.0" +version = "7.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74f7971dbd9326d58187408ab83117d8ac1bb9c17b085fdacd1cf2f598719b6b" +checksum = "cc97b8f16f944bba54f0433f07e30be199b6dc2bd25937444bbad560bcea29bd" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -740,9 +740,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94bbb0ad554ad961ddc5da507a12a29b14e4ae5bda06b19f575a3e6079d2e2ae" +checksum = "8334215b81e418a0a7bdb8ef0849474f40bb10c8b71f1c4ed315cff49f32494d" [[package]] name = "byteorder" @@ -752,9 +752,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.7.2" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "428d9aa8fbc0670b7b8d6030a7fadd0f86151cae55e4dbbece15f3780a3dfaf3" +checksum = "9ac0150caa2ae65ca5bd83f25c7de183dea78d4d366469f148435e2acfbad0da" [[package]] name = "camino" @@ -782,9 +782,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.1.21" +version = "1.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07b1695e2c7e8fc85310cde85aeaab7e3097f593c91d209d3f9df76c928100f0" +checksum = "c2e7962b54006dcfcc61cb72735f4d89bb97061dd6a7ed882ec6b8ee53714c6f" dependencies = [ "jobserver", "libc", @@ -865,9 +865,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.18" +version = "4.5.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0956a43b323ac1afaffc053ed5c4b7c1f1800bacd1683c353aabbb752515dd3" +checksum = "b97f376d85a664d5837dbae44bf546e6477a679ff6610010f17276f686d867e8" dependencies = [ "clap_builder", "clap_derive", @@ -875,9 +875,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.18" +version = "4.5.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d72166dd41634086d5803a47eb71ae740e61d84709c36f3c34110173db3961b" +checksum = "19bc80abd44e4bed93ca373a0704ccbd1b710dc5749406201bb018272808dc54" dependencies = [ "anstream", "anstyle", @@ -894,7 +894,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -914,9 +914,9 @@ dependencies = [ [[package]] name = "colorchoice" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fd119d74b830634cea2a0f58bbd0d54540518a14397557951e79340abc28c0" +checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" [[package]] name = "compact_str" @@ -1115,7 +1115,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -1126,7 +1126,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -1170,7 +1170,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", "unicode-xid", ] @@ -1182,7 +1182,7 @@ checksum = "65f152f4b8559c4da5d574bafc7af85454d706b4c5fe8b530d508cacbb6807ea" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -1215,9 +1215,9 @@ checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" [[package]] name = "encoding_rs" -version = "0.8.34" +version = "0.8.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" dependencies = [ "cfg-if", ] @@ -1311,9 +1311,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.33" +version = "1.0.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "324a1be68054ef05ad64b861cc9eaf1d623d2d8cb25b4bf2cb9cdd902b4bf253" +checksum = "a1b589b4dc103969ad3cf85c950899926ec64300a1a46d76c03a6072957036f0" dependencies = [ "crc32fast", "libz-sys", @@ -1326,6 +1326,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f81ec6369c545a7d40e4589b5597581fa1c441fe1cce96dd1de43159910a36a2" + [[package]] name = "foreign-types" version = "0.3.2" @@ -1395,7 +1401,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -1407,7 +1413,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -1419,7 +1425,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -1436,9 +1442,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" [[package]] name = "futures" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" +checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" dependencies = [ "futures-channel", "futures-core", @@ -1451,9 +1457,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" dependencies = [ "futures-core", "futures-sink", @@ -1461,15 +1467,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" [[package]] name = "futures-executor" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" dependencies = [ "futures-core", "futures-task", @@ -1478,15 +1484,15 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" [[package]] name = "futures-lite" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" +checksum = "3f1fa2f9765705486b33fd2acf1577f8ec449c2ba1f318ae5447697b7c08d210" dependencies = [ "fastrand", "futures-core", @@ -1497,26 +1503,26 @@ dependencies = [ [[package]] name = "futures-macro" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] name = "futures-sink" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" +checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" [[package]] name = "futures-task" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" [[package]] name = "futures-timer" @@ -1526,9 +1532,9 @@ checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" [[package]] name = "futures-util" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" dependencies = [ "futures-channel", "futures-core", @@ -1565,9 +1571,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.31.0" +version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32085ea23f3234fc7846555e85283ba4de91e21016dc0455a16286d87a292d64" +checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" [[package]] name = "glob" @@ -1599,7 +1605,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.5.0", + "indexmap 2.6.0", "slab", "tokio", "tokio-util", @@ -1632,7 +1638,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ "ahash 0.8.11", +] + +[[package]] +name = "hashbrown" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e087f84d4f86bf4b218b927129862374b72199ae7d8657835f1e89000eea4fb" +dependencies = [ "allocator-api2", + "equivalent", + "foldhash", ] [[package]] @@ -1725,9 +1741,9 @@ dependencies = [ [[package]] name = "httparse" -version = "1.9.4" +version = "1.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fcc0b4a115bf80b728eb8ea024ad5bd707b615bfed49e0665b6e0f86fd082d9" +checksum = "7d71d3574edd2771538b901e6549113b4006ece66150fb69c0fb6d9a2adae946" [[package]] name = "httpdate" @@ -1737,9 +1753,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.4.1" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50dfd22e0e76d0f662d429a5f80fcaf3855009297eab6a0a9f8543834744ba05" +checksum = "bbbff0a806a4728c99295b254c8838933b5b082d75e3cb70c8dab21fdfbcfa9a" dependencies = [ "bytes", "futures-channel", @@ -1791,9 +1807,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.8" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da62f120a8a37763efb0cf8fdf264b884c7b8b9ac8660b900c8661030c00e6ba" +checksum = "df2dcfbe0677734ab2f3ffa7fa7bfd4706bfdc1ef393f2ee30184aed67e631b4" dependencies = [ "bytes", "futures-channel", @@ -1804,7 +1820,6 @@ dependencies = [ "pin-project-lite", "socket2", "tokio", - "tower 0.4.13", "tower-service", "tracing", ] @@ -1861,12 +1876,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68b900aa2f7301e21c36462b170ee99994de34dff39a4a6a528e80e7376d07e5" +checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" dependencies = [ "equivalent", - "hashbrown 0.14.5", + "hashbrown 0.15.0", "serde", ] @@ -1887,9 +1902,9 @@ dependencies = [ [[package]] name = "ipnet" -version = "2.10.0" +version = "2.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "187674a687eed5fe42285b40c6291f9a01517d415fad1c3cbc6a9f778af7fcd4" +checksum = "ddc24109865250148c2e0f3d25d4f0f479571723792d3802153c60922a4fb708" [[package]] name = "is-terminal" @@ -1952,9 +1967,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.70" +version = "0.3.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a" +checksum = "6a88f1bda2bd75b0452a14784937d796722fdebfe50df998aeb3f0b7603019a9" dependencies = [ "wasm-bindgen", ] @@ -1982,9 +1997,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.158" +version = "0.2.161" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439" +checksum = "8e9489c2807c139ffd9c1794f4af0ebe86a828db53ecdc7fea2111d0fed085d1" [[package]] name = "libloading" @@ -1998,9 +2013,9 @@ dependencies = [ [[package]] name = "libm" -version = "0.2.8" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" +checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa" [[package]] name = "libsqlite3-sys" @@ -2063,11 +2078,11 @@ dependencies = [ [[package]] name = "lru" -version = "0.12.4" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37ee39891760e7d94734f6f63fedc29a2e4a152f836120753a72503f09fcf904" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" dependencies = [ - "hashbrown 0.14.5", + "hashbrown 0.15.0", ] [[package]] @@ -2144,7 +2159,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -2194,7 +2209,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", "termcolor", "thiserror", ] @@ -2351,18 +2366,18 @@ dependencies = [ [[package]] name = "object" -version = "0.36.4" +version = "0.36.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "084f1a5821ac4c651660a94a7153d27ac9d8a53736203f58b31945ded098070a" +checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" dependencies = [ "memchr", ] [[package]] name = "once_cell" -version = "1.19.0" +version = "1.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" +checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" [[package]] name = "oorandom" @@ -2372,9 +2387,9 @@ checksum = "b410bbe7e14ab526a0e86877eb47c6996a2bd7746f027ba551028c925390e4e9" [[package]] name = "openssl" -version = "0.10.66" +version = "0.10.68" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9529f4786b70a3e8c61e11179af17ab6188ad8d0ded78c5529441ed39d4bd9c1" +checksum = "6174bc48f102d208783c2c84bf931bb75927a617866870de8a4ea85597f871f5" dependencies = [ "bitflags", "cfg-if", @@ -2393,7 +2408,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -2404,9 +2419,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-sys" -version = "0.9.103" +version = "0.9.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f9e8deee91df40a943c71b917e5874b951d32a802526c85721ce3b776c929d6" +checksum = "45abf306cbf99debc8195b66b7346498d7b10c210de50418b5ccd7ceba08c741" dependencies = [ "cc", "libc", @@ -2475,7 +2490,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -2534,29 +2549,29 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.5" +version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6bf43b791c5b9e34c3d182969b4abb522f9343702850a2e57f460d00d09b4b3" +checksum = "be57f64e946e500c8ee36ef6331845d40a93055567ec57e8fae13efd33759b95" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.5" +version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" +checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] name = "pin-project-lite" -version = "0.2.14" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" +checksum = "915a1e146535de9163f3987b8944ed8cf49a18bb0056bcebcdcece385cece4ff" [[package]] name = "pin-utils" @@ -2624,6 +2639,12 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "portable-atomic" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc9c68a3f6da06753e9335d63e27f6b9754dd1920d941135b7ea8224f141adb2" + [[package]] name = "powerfmt" version = "0.2.0" @@ -2636,7 +2657,7 @@ version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" dependencies = [ - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -2667,12 +2688,12 @@ dependencies = [ [[package]] name = "prettyplease" -version = "0.2.22" +version = "0.2.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479cf940fbbb3426c32c5d5176f62ad57549a0bb84773423ba8be9d089f5faba" +checksum = "64d1ec885c64d0457d564db4ec299b2dae3f9c02808b8ad9c3a089c591b18033" dependencies = [ "proc-macro2", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -2710,9 +2731,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.86" +version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" +checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" dependencies = [ "unicode-ident", ] @@ -2725,7 +2746,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", "version_check", "yansi", ] @@ -2860,18 +2881,18 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.4" +version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0884ad60e090bf1345b93da0a5de8923c93884cd03f40dfcfddd3b4bee661853" +checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" dependencies = [ "bitflags", ] [[package]] name = "regex" -version = "1.10.6" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619" +checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" dependencies = [ "aho-corasick", "memchr", @@ -2881,9 +2902,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.7" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" +checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3" dependencies = [ "aho-corasick", "memchr", @@ -2892,9 +2913,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "relative-path" @@ -2913,9 +2934,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.7" +version = "0.12.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8f4955649ef5c38cc7f9e8aa41761d48fb9677197daea9984dc54f56aad5e63" +checksum = "a77c62af46e79de0a562e1a9849205ffcb7fc1238876e9bd743357570e04046f" dependencies = [ "base64 0.22.1", "bytes", @@ -2971,11 +2992,12 @@ dependencies = [ [[package]] name = "ringbuf" -version = "0.4.4" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46f7f1b88601a8ee13cabf203611ccdf64345dc1c5d24de8b11e1a678ee619b6" +checksum = "726bb493fe9cac765e8f96a144c3a8396bdf766dedad22e504b70b908dcbceb4" dependencies = [ "crossbeam-utils", + "portable-atomic", ] [[package]] @@ -3009,9 +3031,9 @@ dependencies = [ [[package]] name = "rstest" -version = "0.22.0" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b423f0e62bdd61734b67cd21ff50871dfaeb9cc74f869dcd6af974fbcb19936" +checksum = "0a2c585be59b6b5dd66a9d2084aa1d8bd52fbdb806eafdeffb52791147862035" dependencies = [ "futures", "futures-timer", @@ -3021,9 +3043,9 @@ dependencies = [ [[package]] name = "rstest_macros" -version = "0.22.0" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e1711e7d14f74b12a58411c542185ef7fb7f2e7f8ee6e2940a883628522b42" +checksum = "825ea780781b15345a146be27eaefb05085e337e869bff01b4306a4fd4a9ad5a" dependencies = [ "cfg-if", "glob", @@ -3033,7 +3055,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.77", + "syn 2.0.86", "unicode-ident", ] @@ -3090,9 +3112,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.37" +version = "0.38.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8acb788b847c24f28525660c4d7758620a7210875711f79e7f663cc152726811" +checksum = "aa260229e6538e52293eeb577aabd09945a09d6d9cc0fc550ed7529056c2e32a" dependencies = [ "bitflags", "errno", @@ -3103,9 +3125,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.13" +version = "0.23.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2dabaac7466917e566adb06783a81ca48944c6898a1b08b9374106dd671f4c8" +checksum = "eee87ff5d9b36712a58574e12e9f0ea80f915a5b0ac518d322b24a465617925e" dependencies = [ "aws-lc-rs", "once_cell", @@ -3117,19 +3139,18 @@ dependencies = [ [[package]] name = "rustls-pemfile" -version = "2.1.3" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "196fe16b00e106300d3e45ecfcb764fa292a535d7326a29a5875c579c7417425" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" dependencies = [ - "base64 0.22.1", "rustls-pki-types", ] [[package]] name = "rustls-pki-types" -version = "1.8.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0a2ce646f8655401bb81e7927b812614bd5d91dbc968696be50603510fcaf0" +checksum = "16f1201b3c9a7ee8039bcadc17b7e605e2945b27eee7631788c1bd2b0643674b" [[package]] name = "rustls-webpki" @@ -3145,9 +3166,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6" +checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248" [[package]] name = "ryu" @@ -3172,9 +3193,9 @@ checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" [[package]] name = "schannel" -version = "0.1.24" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9aaafd5a2b6e3d657ff009d82fbd630b6bd54dd4eb06f21693925cdf80f9b8b" +checksum = "01227be5826fa0690321a2ba6c5cd57a19cf3f6a09e76973b58e61de6ab9d1c1" dependencies = [ "windows-sys 0.59.0", ] @@ -3231,9 +3252,9 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" -version = "1.0.210" +version = "1.0.214" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8e3592472072e6e22e0a54d5904d9febf8508f65fb8552499a1abc7d1078c3a" +checksum = "f55c3193aca71c12ad7890f1785d2b73e1b9f63a0bbc353c08ef26fe03fc56b5" dependencies = [ "serde_derive", ] @@ -3259,13 +3280,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.210" +version = "1.0.214" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f" +checksum = "de523f781f095e28fa605cdce0f8307e451cc0fd14e2eb4cd2e98a355b147766" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -3275,7 +3296,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8de514ef58196f1fc96dcaef80fe6170a1ce6215df9687a93fe8300e773fefc5" dependencies = [ "form_urlencoded", - "indexmap 2.5.0", + "indexmap 2.6.0", "itoa", "ryu", "serde", @@ -3287,7 +3308,7 @@ version = "1.0.132" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d726bfaff4b320266d395898905d0eba0345aae23b54aee3a737e260fd46db03" dependencies = [ - "indexmap 2.5.0", + "indexmap 2.6.0", "itoa", "memchr", "ryu", @@ -3312,14 +3333,14 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] name = "serde_spanned" -version = "0.6.7" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb5b1b31579f3811bf615c144393417496f152e12ac8b7663bf664f4a815306d" +checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1" dependencies = [ "serde", ] @@ -3338,15 +3359,15 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.9.0" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cecfa94848272156ea67b2b1a53f20fc7bc638c4a46d2f8abde08f05f4b857" +checksum = "8e28bdad6db2b8340e449f7108f020b3b092e8583a9e3fb82713e1d4e71fe817" dependencies = [ "base64 0.22.1", "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.5.0", + "indexmap 2.6.0", "serde", "serde_derive", "serde_json", @@ -3356,14 +3377,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.9.0" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8fee4991ef4f274617a51ad4af30519438dacb2f56ac773b08a1922ff743350" +checksum = "9d846214a9854ef724f3da161b426242d8de7c1fc7de2f89bb1efcb154dca79d" dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -3496,9 +3517,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.77" +version = "2.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f35bcdf61fd8e7be6caf75f429fdca8beb3ed76584befb503b1569faee373ed" +checksum = "e89275301d38033efb81a6e60e3497e734dfcc62571f2854bf4b16690398824c" dependencies = [ "proc-macro2", "quote", @@ -3514,7 +3535,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -3578,9 +3599,9 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.12.0" +version = "3.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64" +checksum = "f0f2c9fc62d0beef6951ccffd757e241266a2c833136efbe35af6cd2567dca5b" dependencies = [ "cfg-if", "fastrand", @@ -3606,22 +3627,22 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.65" +version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d11abd9594d9b38965ef50805c5e469ca9cc6f197f883f717e0269a3057b3d5" +checksum = "5d171f59dbaa811dbbb1aee1e73db92ec2b122911a48e1390dfe327a821ddede" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.65" +version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae71770322cbd277e69d762a16c444af02aa0575ac0d174f0b9562d3b37f8602" +checksum = "b08be0f17bd307950653ce45db00cd31200d82b624b36e181337d9c7d92765b5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -3692,9 +3713,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.40.0" +version = "1.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2b070231665d27ad9ec9b8df639893f46727666c6767db40317fbe920a5d998" +checksum = "145f3413504347a2be84393cc8a7d2fb4d863b375909ea59f2158261aa258bbb" dependencies = [ "backtrace", "bytes", @@ -3715,7 +3736,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -3775,11 +3796,11 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.21" +version = "0.22.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b072cee73c449a636ffd6f32bd8de3a9f7119139aff882f44943ce2986dc5cf" +checksum = "4ae48d6208a266e853d946088ed816055e556cc6028c5e8e2b84d9fa5dd7c7f5" dependencies = [ - "indexmap 2.5.0", + "indexmap 2.6.0", "serde", "serde_spanned", "toml_datetime", @@ -3845,7 +3866,7 @@ dependencies = [ "tracing-subscriber", "url", "uuid", - "zerocopy", + "zerocopy 0.8.8", ] [[package]] @@ -3902,7 +3923,7 @@ dependencies = [ "tdyne-peer-id", "tdyne-peer-id-registry", "thiserror", - "zerocopy", + "zerocopy 0.8.8", ] [[package]] @@ -3930,7 +3951,7 @@ dependencies = [ "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-primitives", - "zerocopy", + "zerocopy 0.8.8", ] [[package]] @@ -3943,7 +3964,6 @@ dependencies = [ "futures-util", "pin-project", "pin-project-lite", - "tokio", "tower-layer", "tower-service", "tracing", @@ -4018,7 +4038,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", ] [[package]] @@ -4103,9 +4123,9 @@ dependencies = [ [[package]] name = "unicode-bidi" -version = "0.3.15" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" +checksum = "5ab17db44d7388991a428b2ee655ce0c212e862eff1768a455c58f9aad6e7893" [[package]] name = "unicode-ident" @@ -4154,9 +4174,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314" +checksum = "f8c5f0a0af699448548ad1a2fbf920fb4bee257eae39953ba95cb84891a0446a" dependencies = [ "getrandom", "rand", @@ -4170,9 +4190,9 @@ checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" [[package]] name = "value-bag" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a84c137d37ab0142f0f2ddfe332651fdbf252e7b7dbb4e67b6c1f1b2e925101" +checksum = "3ef4c4aa54d5d05a279399bfa921ec387b7aba77caf7a682ae8d86785b8fdad2" [[package]] name = "vcpkg" @@ -4213,9 +4233,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5" +checksum = "128d1e363af62632b8eb57219c8fd7877144af57558fb2ef0368d0087bddeb2e" dependencies = [ "cfg-if", "once_cell", @@ -4224,24 +4244,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b" +checksum = "cb6dd4d3ca0ddffd1dd1c9c04f94b868c37ff5fac97c30b97cff2d74fce3a358" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.43" +version = "0.4.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61e9300f63a621e96ed275155c108eb6f843b6a26d053f122ab69724559dc8ed" +checksum = "cc7ec4f8827a71586374db3e87abdb5a2bb3a15afed140221307c3ec06b1f63b" dependencies = [ "cfg-if", "js-sys", @@ -4251,9 +4271,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf" +checksum = "e79384be7f8f5a9dd5d7167216f022090cf1f9ec128e6e6a482a2cb5c5422c56" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -4261,28 +4281,28 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" +checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484" +checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" [[package]] name = "web-sys" -version = "0.3.70" +version = "0.3.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26fdeaafd9bd129f65e7c031593c24d62186301e0c72c8978fa1678be7d532c0" +checksum = "f6488b90108c040df0fe62fa815cbdee25124641df01814dd7282749234c6112" dependencies = [ "js-sys", "wasm-bindgen", @@ -4454,9 +4474,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "0.6.18" +version = "0.6.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68a9bda4691f099d435ad181000724da8e5899daa10713c2d432552b9ccd3a6f" +checksum = "36c1fec1a2bb5866f07c25f68c26e565c4c200aebb96d7e55710c19d3e8ac49b" dependencies = [ "memchr", ] @@ -4483,7 +4503,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ "byteorder", - "zerocopy-derive", + "zerocopy-derive 0.7.35", +] + +[[package]] +name = "zerocopy" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a4e33e6dce36f2adba29746927f8e848ba70989fdb61c772773bbdda8b5d6a7" +dependencies = [ + "zerocopy-derive 0.8.8", ] [[package]] @@ -4494,7 +4523,18 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.77", + "syn 2.0.86", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cd137b4cc21bde6ecce3bbbb3350130872cda0be2c6888874279ea76e17d4c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.86", ] [[package]] From e58bdeb571878b3e1b68f1f5faacacca644d56ca Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 1 Nov 2024 09:07:34 +0000 Subject: [PATCH 0508/1297] chore(deps): force 0.7 version for zerocopy The aquatic_udp_protocol crate uses version 0.7: https://github.com/greatest-ape/aquatic/blob/master/crates/udp_protocol/Cargo.toml#L19 We were having problems with trait `read_from`. Example: ```rust let data = PeerId::read_from(&bytes).expect("it should have the correct amount of bytes"); ``` There have been changes in version 0.8: https://github.com/google/zerocopy/discussions/1680 --- Cargo.lock | 38 ++++++-------------------- Cargo.toml | 2 +- packages/primitives/Cargo.toml | 2 +- packages/torrent-repository/Cargo.toml | 2 +- 4 files changed, 12 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9788725db..bcb27fb43 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -37,7 +37,7 @@ dependencies = [ "cfg-if", "once_cell", "version_check", - "zerocopy 0.7.35", + "zerocopy", ] [[package]] @@ -157,7 +157,7 @@ dependencies = [ "quickcheck", "regex", "serde", - "zerocopy 0.7.35", + "zerocopy", ] [[package]] @@ -169,7 +169,7 @@ dependencies = [ "aquatic_peer_id", "byteorder", "either", - "zerocopy 0.7.35", + "zerocopy", ] [[package]] @@ -613,7 +613,7 @@ dependencies = [ "serde", "serde_json", "thiserror", - "zerocopy 0.7.35", + "zerocopy", ] [[package]] @@ -2657,7 +2657,7 @@ version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" dependencies = [ - "zerocopy 0.7.35", + "zerocopy", ] [[package]] @@ -3866,7 +3866,7 @@ dependencies = [ "tracing-subscriber", "url", "uuid", - "zerocopy 0.8.8", + "zerocopy", ] [[package]] @@ -3923,7 +3923,7 @@ dependencies = [ "tdyne-peer-id", "tdyne-peer-id-registry", "thiserror", - "zerocopy 0.8.8", + "zerocopy", ] [[package]] @@ -3951,7 +3951,7 @@ dependencies = [ "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-primitives", - "zerocopy 0.8.8", + "zerocopy", ] [[package]] @@ -4503,16 +4503,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ "byteorder", - "zerocopy-derive 0.7.35", -] - -[[package]] -name = "zerocopy" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a4e33e6dce36f2adba29746927f8e848ba70989fdb61c772773bbdda8b5d6a7" -dependencies = [ - "zerocopy-derive 0.8.8", + "zerocopy-derive", ] [[package]] @@ -4526,17 +4517,6 @@ dependencies = [ "syn 2.0.86", ] -[[package]] -name = "zerocopy-derive" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cd137b4cc21bde6ecce3bbbb3350130872cda0be2c6888874279ea76e17d4c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.86", -] - [[package]] name = "zeroize" version = "1.8.1" diff --git a/Cargo.toml b/Cargo.toml index d69fa3e5e..e42702d06 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -82,7 +82,7 @@ tracing = "0" tracing-subscriber = { version = "0", features = ["json"] } url = { version = "2", features = ["serde"] } uuid = { version = "1", features = ["v4"] } -zerocopy = "0" +zerocopy = "0.7" [package.metadata.cargo-machete] ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_bytes"] diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index 4b5abc8f3..4d18bdca6 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -23,4 +23,4 @@ serde = { version = "1", features = ["derive"] } tdyne-peer-id = "1" tdyne-peer-id-registry = "0" thiserror = "1" -zerocopy = "0" +zerocopy = "0.7" diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 0933457d3..2097d57d2 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -26,7 +26,7 @@ tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -zerocopy = "0" +zerocopy = "0.7" [dev-dependencies] async-std = { version = "1", features = ["attributes", "tokio1"] } From 093e8c9bbb86bde793c8f8903f25b52aa2d7c80d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 1 Nov 2024 16:31:08 +0000 Subject: [PATCH 0509/1297] feat: extract new package bittorrent-tracker-client This will allow other projects to reuse the tracker lib clients and console clients. --- Cargo.lock | 32 ++ Cargo.toml | 2 + packages/tracker-client/Cargo.toml | 42 +++ packages/tracker-client/README.md | 25 ++ .../docs/licenses/LICENSE-MIT_0 | 14 + .../src/bin/http_tracker_client.rs | 7 + .../tracker-client/src/bin/tracker_checker.rs | 7 + .../src/bin/udp_tracker_client.rs | 7 + .../src/console/clients/checker/app.rs | 120 ++++++++ .../console/clients/checker/checks/health.rs | 77 +++++ .../console/clients/checker/checks/http.rs | 104 +++++++ .../src/console/clients/checker/checks/mod.rs | 4 + .../console/clients/checker/checks/structs.rs | 12 + .../src/console/clients/checker/checks/udp.rs | 134 +++++++++ .../src/console/clients/checker/config.rs | 282 ++++++++++++++++++ .../src/console/clients/checker/console.rs | 38 +++ .../src/console/clients/checker/logger.rs | 72 +++++ .../src/console/clients/checker/mod.rs | 7 + .../src/console/clients/checker/printer.rs | 9 + .../src/console/clients/checker/service.rs | 62 ++++ .../src/console/clients/http/app.rs | 102 +++++++ .../src/console/clients/http/mod.rs | 34 +++ .../tracker-client/src/console/clients/mod.rs | 4 + .../src/console/clients/udp/app.rs | 208 +++++++++++++ .../src/console/clients/udp/checker.rs | 177 +++++++++++ .../src/console/clients/udp/mod.rs | 51 ++++ .../src/console/clients/udp/responses/dto.rs | 128 ++++++++ .../src/console/clients/udp/responses/json.rs | 25 ++ .../src/console/clients/udp/responses/mod.rs | 2 + packages/tracker-client/src/console/mod.rs | 2 + .../tracker-client/src/http/client/mod.rs | 220 ++++++++++++++ .../src/http/client/requests/announce.rs | 275 +++++++++++++++++ .../src/http/client/requests/mod.rs | 2 + .../src/http/client/requests/scrape.rs | 172 +++++++++++ .../src/http/client/responses/announce.rs | 126 ++++++++ .../src/http/client/responses/error.rs | 7 + .../src/http/client/responses/mod.rs | 3 + .../src/http/client/responses/scrape.rs | 230 ++++++++++++++ packages/tracker-client/src/http/mod.rs | 27 ++ .../tracker-client/src/http/url_encoding.rs | 132 ++++++++ packages/tracker-client/src/lib.rs | 3 + packages/tracker-client/src/udp/client.rs | 270 +++++++++++++++++ packages/tracker-client/src/udp/mod.rs | 68 +++++ 43 files changed, 3325 insertions(+) create mode 100644 packages/tracker-client/Cargo.toml create mode 100644 packages/tracker-client/README.md create mode 100644 packages/tracker-client/docs/licenses/LICENSE-MIT_0 create mode 100644 packages/tracker-client/src/bin/http_tracker_client.rs create mode 100644 packages/tracker-client/src/bin/tracker_checker.rs create mode 100644 packages/tracker-client/src/bin/udp_tracker_client.rs create mode 100644 packages/tracker-client/src/console/clients/checker/app.rs create mode 100644 packages/tracker-client/src/console/clients/checker/checks/health.rs create mode 100644 packages/tracker-client/src/console/clients/checker/checks/http.rs create mode 100644 packages/tracker-client/src/console/clients/checker/checks/mod.rs create mode 100644 packages/tracker-client/src/console/clients/checker/checks/structs.rs create mode 100644 packages/tracker-client/src/console/clients/checker/checks/udp.rs create mode 100644 packages/tracker-client/src/console/clients/checker/config.rs create mode 100644 packages/tracker-client/src/console/clients/checker/console.rs create mode 100644 packages/tracker-client/src/console/clients/checker/logger.rs create mode 100644 packages/tracker-client/src/console/clients/checker/mod.rs create mode 100644 packages/tracker-client/src/console/clients/checker/printer.rs create mode 100644 packages/tracker-client/src/console/clients/checker/service.rs create mode 100644 packages/tracker-client/src/console/clients/http/app.rs create mode 100644 packages/tracker-client/src/console/clients/http/mod.rs create mode 100644 packages/tracker-client/src/console/clients/mod.rs create mode 100644 packages/tracker-client/src/console/clients/udp/app.rs create mode 100644 packages/tracker-client/src/console/clients/udp/checker.rs create mode 100644 packages/tracker-client/src/console/clients/udp/mod.rs create mode 100644 packages/tracker-client/src/console/clients/udp/responses/dto.rs create mode 100644 packages/tracker-client/src/console/clients/udp/responses/json.rs create mode 100644 packages/tracker-client/src/console/clients/udp/responses/mod.rs create mode 100644 packages/tracker-client/src/console/mod.rs create mode 100644 packages/tracker-client/src/http/client/mod.rs create mode 100644 packages/tracker-client/src/http/client/requests/announce.rs create mode 100644 packages/tracker-client/src/http/client/requests/mod.rs create mode 100644 packages/tracker-client/src/http/client/requests/scrape.rs create mode 100644 packages/tracker-client/src/http/client/responses/announce.rs create mode 100644 packages/tracker-client/src/http/client/responses/error.rs create mode 100644 packages/tracker-client/src/http/client/responses/mod.rs create mode 100644 packages/tracker-client/src/http/client/responses/scrape.rs create mode 100644 packages/tracker-client/src/http/mod.rs create mode 100644 packages/tracker-client/src/http/url_encoding.rs create mode 100644 packages/tracker-client/src/lib.rs create mode 100644 packages/tracker-client/src/udp/client.rs create mode 100644 packages/tracker-client/src/udp/mod.rs diff --git a/Cargo.lock b/Cargo.lock index bcb27fb43..00d83fddb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -616,6 +616,37 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "bittorrent-tracker-client" +version = "3.0.0-develop" +dependencies = [ + "anyhow", + "aquatic_udp_protocol", + "bittorrent-primitives", + "clap", + "derive_more", + "futures", + "futures-util", + "hex-literal", + "hyper", + "percent-encoding", + "reqwest", + "serde", + "serde_bencode", + "serde_bytes", + "serde_json", + "serde_repr", + "thiserror", + "tokio", + "torrust-tracker-configuration", + "torrust-tracker-located-error", + "torrust-tracker-primitives", + "tracing", + "tracing-subscriber", + "url", + "zerocopy", +] + [[package]] name = "bitvec" version = "1.0.1" @@ -3818,6 +3849,7 @@ dependencies = [ "axum-extra", "axum-server", "bittorrent-primitives", + "bittorrent-tracker-client", "camino", "chrono", "clap", diff --git a/Cargo.toml b/Cargo.toml index e42702d06..574881a94 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,7 @@ axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls"] } bittorrent-primitives = "0.1.0" +bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } camino = { version = "1", features = ["serde", "serde1"] } chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } @@ -100,6 +101,7 @@ members = [ "packages/primitives", "packages/test-helpers", "packages/torrent-repository", + "packages/tracker-client", ] [profile.dev] diff --git a/packages/tracker-client/Cargo.toml b/packages/tracker-client/Cargo.toml new file mode 100644 index 000000000..85e10c03e --- /dev/null +++ b/packages/tracker-client/Cargo.toml @@ -0,0 +1,42 @@ +[package] +description = "A library with the primitive types shared by the Torrust tracker packages." +keywords = ["bittorrent", "client", "tracker"] +license = "LGPL-3.0" +name = "bittorrent-tracker-client" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +anyhow = "1" +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +clap = { version = "4", features = ["derive", "env"] } +derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } +futures = "0" +futures-util = "0" +hex-literal = "0" +hyper = "1" +percent-encoding = "2" +reqwest = { version = "0", features = ["json"] } +serde = { version = "1", features = ["derive"] } +serde_bencode = "0" +serde_bytes = "0" +serde_json = { version = "1", features = ["preserve_order"] } +serde_repr = "0" +thiserror = "1" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tracing = "0" +tracing-subscriber = { version = "0", features = ["json"] } +url = { version = "2", features = ["serde"] } +zerocopy = "0.7" diff --git a/packages/tracker-client/README.md b/packages/tracker-client/README.md new file mode 100644 index 000000000..1d12f9c86 --- /dev/null +++ b/packages/tracker-client/README.md @@ -0,0 +1,25 @@ +# BitTorrent Tracker Client + +A library an console applications to interact with a BitTorrent tracker. + +> **Disclaimer**: This project is actively under development. We’re currently extracting and refining common types from the ][Torrust Tracker](https://github.com/torrust/torrust-tracker) to make them available to the BitTorrent community in Rust. While these types are functional, they are not yet ready for use in production or third-party projects. + +## License + +**Copyright (c) 2024 The Torrust Developers.** + +This program is free software: you can redistribute it and/or modify it under the terms of the [GNU Lesser General Public License][LGPL_3_0] as published by the [Free Software Foundation][FSF], version 3. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the [GNU Lesser General Public License][LGPL_3_0] for more details. + +You should have received a copy of the *GNU Lesser General Public License* along with this program. If not, see . + +Some files include explicit copyright notices and/or license notices. + +### Legacy Exception + +For prosperity, versions of Torrust BitTorrent Tracker Client that are older than five years are automatically granted the [MIT-0][MIT_0] license in addition to the existing [LGPL-3.0-only][LGPL_3_0] license. + +[LGPL_3_0]: ./LICENSE +[MIT_0]: ./docs/licenses/LICENSE-MIT_0 +[FSF]: https://www.fsf.org/ diff --git a/packages/tracker-client/docs/licenses/LICENSE-MIT_0 b/packages/tracker-client/docs/licenses/LICENSE-MIT_0 new file mode 100644 index 000000000..fc06cc4fe --- /dev/null +++ b/packages/tracker-client/docs/licenses/LICENSE-MIT_0 @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/tracker-client/src/bin/http_tracker_client.rs b/packages/tracker-client/src/bin/http_tracker_client.rs new file mode 100644 index 000000000..8c2c0356d --- /dev/null +++ b/packages/tracker-client/src/bin/http_tracker_client.rs @@ -0,0 +1,7 @@ +//! Program to make request to HTTP trackers. +use bittorrent_tracker_client::console::clients::http::app; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + app::run().await +} diff --git a/packages/tracker-client/src/bin/tracker_checker.rs b/packages/tracker-client/src/bin/tracker_checker.rs new file mode 100644 index 000000000..eb2a7d82c --- /dev/null +++ b/packages/tracker-client/src/bin/tracker_checker.rs @@ -0,0 +1,7 @@ +//! Program to check running trackers. +use bittorrent_tracker_client::console::clients::checker::app; + +#[tokio::main] +async fn main() { + app::run().await.expect("Some checks fail"); +} diff --git a/packages/tracker-client/src/bin/udp_tracker_client.rs b/packages/tracker-client/src/bin/udp_tracker_client.rs new file mode 100644 index 000000000..5f6b4f50d --- /dev/null +++ b/packages/tracker-client/src/bin/udp_tracker_client.rs @@ -0,0 +1,7 @@ +//! Program to make request to UDP trackers. +use bittorrent_tracker_client::console::clients::udp::app; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + app::run().await +} diff --git a/packages/tracker-client/src/console/clients/checker/app.rs b/packages/tracker-client/src/console/clients/checker/app.rs new file mode 100644 index 000000000..395f65df9 --- /dev/null +++ b/packages/tracker-client/src/console/clients/checker/app.rs @@ -0,0 +1,120 @@ +//! Program to run checks against running trackers. +//! +//! Run providing a config file path: +//! +//! ```text +//! cargo run --bin tracker_checker -- --config-path "./share/default/config/tracker_checker.json" +//! TORRUST_CHECKER_CONFIG_PATH="./share/default/config/tracker_checker.json" cargo run --bin tracker_checker +//! ``` +//! +//! Run providing the configuration: +//! +//! ```text +//! TORRUST_CHECKER_CONFIG=$(cat "./share/default/config/tracker_checker.json") cargo run --bin tracker_checker +//! ``` +//! +//! Another real example to test the Torrust demo tracker: +//! +//! ```text +//! TORRUST_CHECKER_CONFIG='{ +//! "udp_trackers": ["144.126.245.19:6969"], +//! "http_trackers": ["https://tracker.torrust-demo.com"], +//! "health_checks": ["https://tracker.torrust-demo.com/api/health_check"] +//! }' cargo run --bin tracker_checker +//! ``` +//! +//! The output should be something like the following: +//! +//! ```json +//! { +//! "udp_trackers": [ +//! { +//! "url": "144.126.245.19:6969", +//! "status": { +//! "code": "ok", +//! "message": "" +//! } +//! } +//! ], +//! "http_trackers": [ +//! { +//! "url": "https://tracker.torrust-demo.com/", +//! "status": { +//! "code": "ok", +//! "message": "" +//! } +//! } +//! ], +//! "health_checks": [ +//! { +//! "url": "https://tracker.torrust-demo.com/api/health_check", +//! "status": { +//! "code": "ok", +//! "message": "" +//! } +//! } +//! ] +//! } +//! ``` +use std::path::PathBuf; +use std::sync::Arc; + +use anyhow::{Context, Result}; +use clap::Parser; +use tracing::level_filters::LevelFilter; + +use super::config::Configuration; +use super::console::Console; +use super::service::{CheckResult, Service}; +use crate::console::clients::checker::config::parse_from_json; + +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + /// Path to the JSON configuration file. + #[clap(short, long, env = "TORRUST_CHECKER_CONFIG_PATH")] + config_path: Option, + + /// Direct configuration content in JSON. + #[clap(env = "TORRUST_CHECKER_CONFIG", hide_env_values = true)] + config_content: Option, +} + +/// # Errors +/// +/// Will return an error if the configuration was not provided. +pub async fn run() -> Result> { + tracing_stdout_init(LevelFilter::INFO); + + 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.context("it should run the check tasks") +} + +fn tracing_stdout_init(filter: LevelFilter) { + tracing_subscriber::fmt().with_max_level(filter).init(); + tracing::debug!("Logging initialized"); +} + +fn setup_config(args: Args) -> Result { + match (args.config_path, args.config_content) { + (Some(config_path), _) => load_config_from_file(&config_path), + (_, Some(config_content)) => parse_from_json(&config_content).context("invalid config format"), + _ => Err(anyhow::anyhow!("no configuration provided")), + } +} + +fn load_config_from_file(path: &PathBuf) -> Result { + let file_content = std::fs::read_to_string(path).with_context(|| format!("can't read config file {path:?}"))?; + + parse_from_json(&file_content).context("invalid config format") +} diff --git a/packages/tracker-client/src/console/clients/checker/checks/health.rs b/packages/tracker-client/src/console/clients/checker/checks/health.rs new file mode 100644 index 000000000..b1fb79148 --- /dev/null +++ b/packages/tracker-client/src/console/clients/checker/checks/health.rs @@ -0,0 +1,77 @@ +use std::sync::Arc; +use std::time::Duration; + +use anyhow::Result; +use hyper::StatusCode; +use reqwest::{Client as HttpClient, Response}; +use serde::Serialize; +use thiserror::Error; +use url::Url; + +#[derive(Debug, Clone, Error, Serialize)] +#[serde(into = "String")] +pub enum Error { + #[error("Failed to Build a Http Client: {err:?}")] + ClientBuildingError { err: Arc }, + #[error("Heath check failed to get a response: {err:?}")] + ResponseError { err: Arc }, + #[error("Http check returned a non-success code: \"{code}\" with the response: \"{response:?}\"")] + UnsuccessfulResponse { code: StatusCode, response: Arc }, +} + +impl From for String { + fn from(value: Error) -> Self { + value.to_string() + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct Checks { + url: Url, + result: Result, +} + +pub async fn run(health_checks: Vec, timeout: Duration) -> Vec> { + let mut results = Vec::default(); + + tracing::debug!("Health checks ..."); + + for url in health_checks { + let result = match run_health_check(url.clone(), timeout).await { + Ok(response) => Ok(response.status().to_string()), + Err(err) => Err(err), + }; + + let check = Checks { url, result }; + + if check.result.is_err() { + results.push(Err(check)); + } else { + results.push(Ok(check)); + } + } + + results +} + +async fn run_health_check(url: Url, timeout: Duration) -> Result { + let client = HttpClient::builder() + .timeout(timeout) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; + + let response = client + .get(url.clone()) + .send() + .await + .map_err(|e| Error::ResponseError { err: e.into() })?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } +} diff --git a/packages/tracker-client/src/console/clients/checker/checks/http.rs b/packages/tracker-client/src/console/clients/checker/checks/http.rs new file mode 100644 index 000000000..48ce9678d --- /dev/null +++ b/packages/tracker-client/src/console/clients/checker/checks/http.rs @@ -0,0 +1,104 @@ +use std::str::FromStr as _; +use std::time::Duration; + +use bittorrent_primitives::info_hash::InfoHash; +use serde::Serialize; +use url::Url; + +use crate::console::clients::http::Error; +use crate::http::client::responses::announce::Announce; +use crate::http::client::responses::scrape; +use crate::http::client::{requests, Client}; + +#[derive(Debug, Clone, Serialize)] +pub struct Checks { + url: Url, + results: Vec<(Check, Result<(), Error>)>, +} + +#[derive(Debug, Clone, Serialize)] +pub enum Check { + Announce, + Scrape, +} + +pub async fn run(http_trackers: Vec, timeout: Duration) -> Vec> { + let mut results = Vec::default(); + + tracing::debug!("HTTP trackers ..."); + + for ref url in http_trackers { + let mut base_url = url.clone(); + base_url.set_path(""); + + let mut checks = Checks { + url: url.clone(), + results: Vec::default(), + }; + + // Announce + { + let check = check_http_announce(&base_url, timeout).await.map(|_| ()); + + checks.results.push((Check::Announce, check)); + } + + // Scrape + { + let check = check_http_scrape(&base_url, timeout).await.map(|_| ()); + + checks.results.push((Check::Scrape, check)); + } + + if checks.results.iter().any(|f| f.1.is_err()) { + results.push(Err(checks)); + } else { + results.push(Ok(checks)); + } + } + + results +} + +async fn check_http_announce(url: &Url, timeout: Duration) -> Result { + let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // # DevSkim: ignore DS173237 + let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); + + let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; + + let response = client + .announce( + &requests::announce::QueryBuilder::with_default_values() + .with_info_hash(&info_hash) + .query(), + ) + .await + .map_err(|err| Error::HttpClientError { err })?; + + let response = response.bytes().await.map_err(|e| Error::ResponseError { err: e.into() })?; + + let response = serde_bencode::from_bytes::(&response).map_err(|e| Error::ParseBencodeError { + data: response, + err: e.into(), + })?; + + Ok(response) +} + +async fn check_http_scrape(url: &Url, timeout: Duration) -> Result { + let info_hashes: Vec = vec!["9c38422213e30bff212b30c360d26f9a02136422".to_string()]; // # DevSkim: ignore DS173237 + let query = requests::scrape::Query::try_from(info_hashes).expect("a valid array of info-hashes is required"); + + let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; + + let response = client.scrape(&query).await.map_err(|err| Error::HttpClientError { err })?; + + let response = response.bytes().await.map_err(|e| Error::ResponseError { err: e.into() })?; + + let response = scrape::Response::try_from_bencoded(&response).map_err(|e| Error::BencodeParseError { + data: response, + err: e.into(), + })?; + + Ok(response) +} diff --git a/packages/tracker-client/src/console/clients/checker/checks/mod.rs b/packages/tracker-client/src/console/clients/checker/checks/mod.rs new file mode 100644 index 000000000..f8b03f749 --- /dev/null +++ b/packages/tracker-client/src/console/clients/checker/checks/mod.rs @@ -0,0 +1,4 @@ +pub mod health; +pub mod http; +pub mod structs; +pub mod udp; diff --git a/packages/tracker-client/src/console/clients/checker/checks/structs.rs b/packages/tracker-client/src/console/clients/checker/checks/structs.rs new file mode 100644 index 000000000..d28e20c04 --- /dev/null +++ b/packages/tracker-client/src/console/clients/checker/checks/structs.rs @@ -0,0 +1,12 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub struct Status { + pub code: String, + pub message: String, +} +#[derive(Serialize, Deserialize)] +pub struct CheckerOutput { + pub url: String, + pub status: Status, +} diff --git a/packages/tracker-client/src/console/clients/checker/checks/udp.rs b/packages/tracker-client/src/console/clients/checker/checks/udp.rs new file mode 100644 index 000000000..21bdcd1b7 --- /dev/null +++ b/packages/tracker-client/src/console/clients/checker/checks/udp.rs @@ -0,0 +1,134 @@ +use std::net::SocketAddr; +use std::time::Duration; + +use aquatic_udp_protocol::TransactionId; +use hex_literal::hex; +use serde::Serialize; +use url::Url; + +use crate::console::clients::udp::checker::Client; +use crate::console::clients::udp::Error; + +#[derive(Debug, Clone, Serialize)] +pub struct Checks { + remote_addr: SocketAddr, + results: Vec<(Check, Result<(), Error>)>, +} + +#[derive(Debug, Clone, Serialize)] +pub enum Check { + Setup, + Connect, + Announce, + Scrape, +} + +#[allow(clippy::missing_panics_doc)] +pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec> { + let mut results = Vec::default(); + + tracing::debug!("UDP trackers ..."); + + let info_hash = aquatic_udp_protocol::InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237 + + for remote_url in udp_trackers { + let remote_addr = resolve_socket_addr(&remote_url); + + let mut checks = Checks { + remote_addr, + results: Vec::default(), + }; + + tracing::debug!("UDP tracker: {:?}", remote_url); + + // Setup + let client = match Client::new(remote_addr, timeout).await { + Ok(client) => { + checks.results.push((Check::Setup, Ok(()))); + client + } + Err(err) => { + checks.results.push((Check::Setup, Err(err))); + results.push(Err(checks)); + continue; + } + }; + + let transaction_id = TransactionId::new(1); + + // Connect Remote + let connection_id = match client.send_connection_request(transaction_id).await { + Ok(connection_id) => { + checks.results.push((Check::Connect, Ok(()))); + connection_id + } + Err(err) => { + checks.results.push((Check::Connect, Err(err))); + results.push(Err(checks)); + continue; + } + }; + + // Announce + { + let check = client + .send_announce_request(transaction_id, connection_id, info_hash.into()) + .await + .map(|_| ()); + + checks.results.push((Check::Announce, check)); + } + + // Scrape + { + let check = client + .send_scrape_request(connection_id, transaction_id, &[info_hash.into()]) + .await + .map(|_| ()); + + checks.results.push((Check::Scrape, check)); + } + + if checks.results.iter().any(|f| f.1.is_err()) { + results.push(Err(checks)); + } else { + results.push(Ok(checks)); + } + } + + results +} + +fn resolve_socket_addr(url: &Url) -> SocketAddr { + let socket_addr = url.socket_addrs(|| None).unwrap(); + *socket_addr.first().unwrap() +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + + use url::Url; + + use crate::console::clients::checker::checks::udp::resolve_socket_addr; + + #[test] + fn it_should_resolve_the_socket_address_for_udp_scheme_urls_containing_a_domain() { + let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); + + assert!( + socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) + || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) + ); + } + + #[test] + fn it_should_resolve_the_socket_address_for_udp_scheme_urls_containing_an_ip() { + let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); + + assert!( + socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) + || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) + ); + } +} diff --git a/packages/tracker-client/src/console/clients/checker/config.rs b/packages/tracker-client/src/console/clients/checker/config.rs new file mode 100644 index 000000000..154dcae85 --- /dev/null +++ b/packages/tracker-client/src/console/clients/checker/config.rs @@ -0,0 +1,282 @@ +use std::error::Error; +use std::fmt; + +use reqwest::Url as ServiceUrl; +use serde::Deserialize; + +/// It parses the configuration from a JSON format. +/// +/// # Errors +/// +/// Will return an error if the configuration is not valid. +/// +/// # Panics +/// +/// Will panic if unable to read the configuration file. +pub fn parse_from_json(json: &str) -> Result { + let plain_config: PlainConfiguration = serde_json::from_str(json).map_err(ConfigurationError::JsonParseError)?; + Configuration::try_from(plain_config) +} + +/// DTO for the configuration to serialize/deserialize configuration. +/// +/// Configuration does not need to be valid. +#[derive(Deserialize)] +struct PlainConfiguration { + pub udp_trackers: Vec, + pub http_trackers: Vec, + pub health_checks: Vec, +} + +/// Validated configuration +pub struct Configuration { + pub udp_trackers: Vec, + pub http_trackers: Vec, + pub health_checks: Vec, +} + +#[derive(Debug)] +pub enum ConfigurationError { + JsonParseError(serde_json::Error), + InvalidUdpAddress(std::net::AddrParseError), + InvalidUrl(url::ParseError), +} + +impl Error for ConfigurationError {} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ConfigurationError::JsonParseError(e) => write!(f, "JSON parse error: {e}"), + ConfigurationError::InvalidUdpAddress(e) => write!(f, "Invalid UDP address: {e}"), + ConfigurationError::InvalidUrl(e) => write!(f, "Invalid URL: {e}"), + } + } +} + +impl TryFrom for Configuration { + type Error = ConfigurationError; + + fn try_from(plain_config: PlainConfiguration) -> Result { + let udp_trackers = plain_config + .udp_trackers + .into_iter() + .map(|s| if s.starts_with("udp://") { s } else { format!("udp://{s}") }) + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) + .collect::, _>>()?; + + let http_trackers = plain_config + .http_trackers + .into_iter() + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) + .collect::, _>>()?; + + let health_checks = plain_config + .health_checks + .into_iter() + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) + .collect::, _>>()?; + + Ok(Configuration { + udp_trackers, + http_trackers, + health_checks, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn configuration_should_be_build_from_plain_serializable_configuration() { + let dto = PlainConfiguration { + udp_trackers: vec!["udp://127.0.0.1:8080".to_string()], + http_trackers: vec!["http://127.0.0.1:8080".to_string()], + health_checks: vec!["http://127.0.0.1:8080/health".to_string()], + }; + + let config = Configuration::try_from(dto).expect("A valid configuration"); + + assert_eq!(config.udp_trackers, vec![ServiceUrl::parse("udp://127.0.0.1:8080").unwrap()]); + + assert_eq!( + config.http_trackers, + vec![ServiceUrl::parse("http://127.0.0.1:8080").unwrap()] + ); + + assert_eq!( + config.health_checks, + vec![ServiceUrl::parse("http://127.0.0.1:8080/health").unwrap()] + ); + } + + mod building_configuration_from_plain_configuration_for { + + mod udp_trackers { + use crate::console::clients::checker::config::{Configuration, PlainConfiguration, ServiceUrl}; + + /* The plain configuration should allow UDP URLs with: + + - IP or domain. + - With or without scheme. + - With or without `announce` suffix. + - With or without `/` at the end of the authority section (with empty path). + + For example: + + 127.0.0.1:6969 + 127.0.0.1:6969/ + 127.0.0.1:6969/announce + + localhost:6969 + localhost:6969/ + localhost:6969/announce + + udp://127.0.0.1:6969 + udp://127.0.0.1:6969/ + udp://127.0.0.1:6969/announce + + udp://localhost:6969 + udp://localhost:6969/ + udp://localhost:6969/announce + + */ + + #[test] + fn it_should_fail_when_a_tracker_udp_url_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["invalid URL".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + assert!(Configuration::try_from(plain_config).is_err()); + } + + #[test] + fn it_should_add_the_udp_scheme_to_the_udp_url_when_it_is_missing() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:6969".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!(config.udp_trackers[0], "udp://127.0.0.1:6969".parse::().unwrap()); + } + + #[test] + fn it_should_allow_using_domains() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["udp://localhost:6969".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!(config.udp_trackers[0], "udp://localhost:6969".parse::().unwrap()); + } + + #[test] + fn it_should_allow_the_url_to_have_an_empty_path() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:6969/".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!(config.udp_trackers[0], "udp://127.0.0.1:6969/".parse::().unwrap()); + } + + #[test] + fn it_should_allow_the_url_to_contain_a_path() { + // This is the common format for UDP tracker URLs: + // udp://domain.com:6969/announce + + let plain_config = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:6969/announce".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!( + config.udp_trackers[0], + "udp://127.0.0.1:6969/announce".parse::().unwrap() + ); + } + } + + mod http_trackers { + use crate::console::clients::checker::config::{Configuration, PlainConfiguration, ServiceUrl}; + + #[test] + fn it_should_fail_when_a_tracker_http_url_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec!["invalid URL".to_string()], + health_checks: vec![], + }; + + assert!(Configuration::try_from(plain_config).is_err()); + } + + #[test] + fn it_should_allow_the_url_to_contain_a_path() { + // This is the common format for HTTP tracker URLs: + // http://domain.com:7070/announce + + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec!["http://127.0.0.1:7070/announce".to_string()], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!( + config.http_trackers[0], + "http://127.0.0.1:7070/announce".parse::().unwrap() + ); + } + + #[test] + fn it_should_allow_the_url_to_contain_an_empty_path() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec!["http://127.0.0.1:7070/".to_string()], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!( + config.http_trackers[0], + "http://127.0.0.1:7070/".parse::().unwrap() + ); + } + } + + mod health_checks { + use crate::console::clients::checker::config::{Configuration, PlainConfiguration}; + + #[test] + fn it_should_fail_when_a_health_check_http_url_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec![], + health_checks: vec!["invalid URL".to_string()], + }; + + assert!(Configuration::try_from(plain_config).is_err()); + } + } + } +} diff --git a/packages/tracker-client/src/console/clients/checker/console.rs b/packages/tracker-client/src/console/clients/checker/console.rs new file mode 100644 index 000000000..b55c559fc --- /dev/null +++ b/packages/tracker-client/src/console/clients/checker/console.rs @@ -0,0 +1,38 @@ +use super::printer::{Printer, CLEAR_SCREEN}; + +pub struct Console {} + +impl Default for Console { + fn default() -> Self { + Self::new() + } +} + +impl Console { + #[must_use] + pub fn new() -> Self { + Self {} + } +} + +impl Printer for Console { + fn clear(&self) { + self.print(CLEAR_SCREEN); + } + + fn print(&self, output: &str) { + print!("{}", &output); + } + + fn eprint(&self, output: &str) { + eprint!("{}", &output); + } + + fn println(&self, output: &str) { + println!("{}", &output); + } + + fn eprintln(&self, output: &str) { + eprintln!("{}", &output); + } +} diff --git a/packages/tracker-client/src/console/clients/checker/logger.rs b/packages/tracker-client/src/console/clients/checker/logger.rs new file mode 100644 index 000000000..50e97189f --- /dev/null +++ b/packages/tracker-client/src/console/clients/checker/logger.rs @@ -0,0 +1,72 @@ +use std::cell::RefCell; + +use super::printer::{Printer, CLEAR_SCREEN}; + +pub struct Logger { + output: RefCell, +} + +impl Default for Logger { + fn default() -> Self { + Self::new() + } +} + +impl Logger { + #[must_use] + pub fn new() -> Self { + Self { + output: RefCell::new(String::new()), + } + } + + pub fn log(&self) -> String { + self.output.borrow().clone() + } +} + +impl Printer for Logger { + fn clear(&self) { + self.print(CLEAR_SCREEN); + } + + fn print(&self, output: &str) { + *self.output.borrow_mut() = format!("{}{}", self.output.borrow(), &output); + } + + fn eprint(&self, output: &str) { + *self.output.borrow_mut() = format!("{}{}", self.output.borrow(), &output); + } + + fn println(&self, output: &str) { + self.print(&format!("{}/n", &output)); + } + + fn eprintln(&self, output: &str) { + self.eprint(&format!("{}/n", &output)); + } +} + +#[cfg(test)] +mod tests { + use crate::console::clients::checker::logger::Logger; + use crate::console::clients::checker::printer::{Printer, CLEAR_SCREEN}; + + #[test] + fn should_capture_the_clear_screen_command() { + let console_logger = Logger::new(); + + console_logger.clear(); + + assert_eq!(CLEAR_SCREEN, console_logger.log()); + } + + #[test] + fn should_capture_the_print_command_output() { + let console_logger = Logger::new(); + + console_logger.print("OUTPUT"); + + assert_eq!("OUTPUT", console_logger.log()); + } +} diff --git a/packages/tracker-client/src/console/clients/checker/mod.rs b/packages/tracker-client/src/console/clients/checker/mod.rs new file mode 100644 index 000000000..d26a4a686 --- /dev/null +++ b/packages/tracker-client/src/console/clients/checker/mod.rs @@ -0,0 +1,7 @@ +pub mod app; +pub mod checks; +pub mod config; +pub mod console; +pub mod logger; +pub mod printer; +pub mod service; diff --git a/packages/tracker-client/src/console/clients/checker/printer.rs b/packages/tracker-client/src/console/clients/checker/printer.rs new file mode 100644 index 000000000..d590dfedb --- /dev/null +++ b/packages/tracker-client/src/console/clients/checker/printer.rs @@ -0,0 +1,9 @@ +pub const CLEAR_SCREEN: &str = "\x1B[2J\x1B[1;1H"; + +pub trait Printer { + fn clear(&self); + fn print(&self, output: &str); + fn eprint(&self, output: &str); + fn println(&self, output: &str); + fn eprintln(&self, output: &str); +} diff --git a/packages/tracker-client/src/console/clients/checker/service.rs b/packages/tracker-client/src/console/clients/checker/service.rs new file mode 100644 index 000000000..acd312d8c --- /dev/null +++ b/packages/tracker-client/src/console/clients/checker/service.rs @@ -0,0 +1,62 @@ +use std::sync::Arc; + +use futures::FutureExt as _; +use serde::Serialize; +use tokio::task::{JoinError, JoinSet}; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; + +use super::checks::{health, http, udp}; +use super::config::Configuration; +use super::console::Console; +use crate::console::clients::checker::printer::Printer; + +pub struct Service { + pub(crate) config: Arc, + pub(crate) console: Console, +} + +#[derive(Debug, Clone, Serialize)] +pub enum CheckResult { + Udp(Result), + Http(Result), + Health(Result), +} + +impl Service { + /// # Errors + /// + /// It will return an error if some of the tests panic or otherwise fail to run. + /// On success it will return a vector of `Ok(())` of [`CheckResult`]. + /// + /// # Panics + /// + /// It would panic if `serde_json` produces invalid json for the `to_string_pretty` function. + pub async fn run_checks(self) -> Result, JoinError> { + tracing::info!("Running checks for trackers ..."); + + let mut check_results = Vec::default(); + + let mut checks = JoinSet::new(); + checks.spawn( + udp::run(self.config.udp_trackers.clone(), DEFAULT_TIMEOUT).map(|mut f| f.drain(..).map(CheckResult::Udp).collect()), + ); + checks.spawn( + http::run(self.config.http_trackers.clone(), DEFAULT_TIMEOUT) + .map(|mut f| f.drain(..).map(CheckResult::Http).collect()), + ); + checks.spawn( + health::run(self.config.health_checks.clone(), DEFAULT_TIMEOUT) + .map(|mut f| f.drain(..).map(CheckResult::Health).collect()), + ); + + while let Some(results) = checks.join_next().await { + check_results.append(&mut results?); + } + + let json_output = serde_json::json!(check_results); + self.console + .println(&serde_json::to_string_pretty(&json_output).expect("it should consume valid json")); + + Ok(check_results) + } +} diff --git a/packages/tracker-client/src/console/clients/http/app.rs b/packages/tracker-client/src/console/clients/http/app.rs new file mode 100644 index 000000000..8db6fe46d --- /dev/null +++ b/packages/tracker-client/src/console/clients/http/app.rs @@ -0,0 +1,102 @@ +//! HTTP Tracker client: +//! +//! Examples: +//! +//! `Announce` request: +//! +//! ```text +//! cargo run --bin http_tracker_client announce http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! `Scrape` request: +//! +//! ```text +//! cargo run --bin http_tracker_client scrape http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +use std::str::FromStr; +use std::time::Duration; + +use anyhow::Context; +use bittorrent_primitives::info_hash::InfoHash; +use clap::{Parser, Subcommand}; +use reqwest::Url; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; + +use crate::http::client::requests::announce::QueryBuilder; +use crate::http::client::responses::announce::Announce; +use crate::http::client::responses::scrape; +use crate::http::client::{requests, Client}; + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand, Debug)] +enum Command { + Announce { tracker_url: String, info_hash: String }, + Scrape { tracker_url: String, info_hashes: Vec }, +} + +/// # Errors +/// +/// Will return an error if the command fails. +pub async fn run() -> anyhow::Result<()> { + let args = Args::parse(); + + match args.command { + Command::Announce { tracker_url, info_hash } => { + announce_command(tracker_url, info_hash, DEFAULT_TIMEOUT).await?; + } + Command::Scrape { + tracker_url, + info_hashes, + } => { + scrape_command(&tracker_url, &info_hashes, DEFAULT_TIMEOUT).await?; + } + } + + Ok(()) +} + +async fn announce_command(tracker_url: String, info_hash: String, timeout: Duration) -> anyhow::Result<()> { + let base_url = Url::parse(&tracker_url).context("failed to parse HTTP tracker base URL")?; + let info_hash = + InfoHash::from_str(&info_hash).expect("Invalid infohash. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); + + let response = Client::new(base_url, timeout)? + .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) + .await?; + + let body = response.bytes().await?; + + let announce_response: Announce = serde_bencode::from_bytes(&body) + .unwrap_or_else(|_| panic!("response body should be a valid announce response, got: \"{:#?}\"", &body)); + + let json = serde_json::to_string(&announce_response).context("failed to serialize scrape response into JSON")?; + + println!("{json}"); + + Ok(()) +} + +async fn scrape_command(tracker_url: &str, info_hashes: &[String], timeout: Duration) -> anyhow::Result<()> { + let base_url = Url::parse(tracker_url).context("failed to parse HTTP tracker base URL")?; + + let query = requests::scrape::Query::try_from(info_hashes).context("failed to parse infohashes")?; + + let response = Client::new(base_url, timeout)?.scrape(&query).await?; + + let body = response.bytes().await?; + + let scrape_response = scrape::Response::try_from_bencoded(&body) + .unwrap_or_else(|_| panic!("response body should be a valid scrape response, got: \"{:#?}\"", &body)); + + let json = serde_json::to_string(&scrape_response).context("failed to serialize scrape response into JSON")?; + + println!("{json}"); + + Ok(()) +} diff --git a/packages/tracker-client/src/console/clients/http/mod.rs b/packages/tracker-client/src/console/clients/http/mod.rs new file mode 100644 index 000000000..e4b6fbe57 --- /dev/null +++ b/packages/tracker-client/src/console/clients/http/mod.rs @@ -0,0 +1,34 @@ +use std::sync::Arc; + +use serde::Serialize; +use thiserror::Error; + +use crate::http::client::responses::scrape::BencodeParseError; + +pub mod app; + +#[derive(Debug, Clone, Error, Serialize)] +#[serde(into = "String")] +pub enum Error { + #[error("Http request did not receive a response within the timeout: {err:?}")] + HttpClientError { err: crate::http::client::Error }, + #[error("Http failed to get a response at all: {err:?}")] + ResponseError { err: Arc }, + #[error("Failed to deserialize the bencoded response data with the error: \"{err:?}\"")] + ParseBencodeError { + data: hyper::body::Bytes, + err: Arc, + }, + + #[error("Failed to deserialize the bencoded response data with the error: \"{err:?}\"")] + BencodeParseError { + data: hyper::body::Bytes, + err: Arc, + }, +} + +impl From for String { + fn from(value: Error) -> Self { + value.to_string() + } +} diff --git a/packages/tracker-client/src/console/clients/mod.rs b/packages/tracker-client/src/console/clients/mod.rs new file mode 100644 index 000000000..8492f8ba5 --- /dev/null +++ b/packages/tracker-client/src/console/clients/mod.rs @@ -0,0 +1,4 @@ +//! Console clients. +pub mod checker; +pub mod http; +pub mod udp; diff --git a/packages/tracker-client/src/console/clients/udp/app.rs b/packages/tracker-client/src/console/clients/udp/app.rs new file mode 100644 index 000000000..a2736c365 --- /dev/null +++ b/packages/tracker-client/src/console/clients/udp/app.rs @@ -0,0 +1,208 @@ +//! UDP Tracker client: +//! +//! Examples: +//! +//! Announce request: +//! +//! ```text +//! cargo run --bin udp_tracker_client announce 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! Announce response: +//! +//! ```json +//! { +//! "transaction_id": -888840697 +//! "announce_interval": 120, +//! "leechers": 0, +//! "seeders": 1, +//! "peers": [ +//! "123.123.123.123:51289" +//! ], +//! } +//! ``` +//! +//! Scrape request: +//! +//! ```text +//! cargo run --bin udp_tracker_client scrape 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! Scrape response: +//! +//! ```json +//! { +//! "transaction_id": -888840697, +//! "torrent_stats": [ +//! { +//! "completed": 0, +//! "leechers": 0, +//! "seeders": 0 +//! }, +//! { +//! "completed": 0, +//! "leechers": 0, +//! "seeders": 0 +//! } +//! ] +//! } +//! ``` +//! +//! You can use an URL with instead of the socket address. For example: +//! +//! ```text +//! cargo run --bin udp_tracker_client scrape udp://localhost:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! cargo run --bin udp_tracker_client scrape udp://localhost:6969/scrape 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! The protocol (`udp://`) in the URL is mandatory. The path (`\scrape`) is optional. It always uses `\scrape`. +use std::net::{SocketAddr, ToSocketAddrs}; +use std::str::FromStr; + +use anyhow::Context; +use aquatic_udp_protocol::{Response, TransactionId}; +use bittorrent_primitives::info_hash::InfoHash as TorrustInfoHash; +use clap::{Parser, Subcommand}; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; +use tracing::level_filters::LevelFilter; +use url::Url; + +use super::Error; +use crate::console::clients::udp::checker; +use crate::console::clients::udp::responses::dto::SerializableResponse; +use crate::console::clients::udp::responses::json::ToJson; + +const RANDOM_TRANSACTION_ID: i32 = -888_840_697; + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand, Debug)] +enum Command { + Announce { + #[arg(value_parser = parse_socket_addr)] + tracker_socket_addr: SocketAddr, + #[arg(value_parser = parse_info_hash)] + info_hash: TorrustInfoHash, + }, + Scrape { + #[arg(value_parser = parse_socket_addr)] + tracker_socket_addr: SocketAddr, + #[arg(value_parser = parse_info_hash, num_args = 1..=74, value_delimiter = ' ')] + info_hashes: Vec, + }, +} + +/// # Errors +/// +/// Will return an error if the command fails. +/// +/// +pub async fn run() -> anyhow::Result<()> { + tracing_stdout_init(LevelFilter::INFO); + + let args = Args::parse(); + + let response = match args.command { + Command::Announce { + tracker_socket_addr: remote_addr, + info_hash, + } => handle_announce(remote_addr, &info_hash).await?, + Command::Scrape { + tracker_socket_addr: remote_addr, + info_hashes, + } => handle_scrape(remote_addr, &info_hashes).await?, + }; + + let response: SerializableResponse = response.into(); + let response_json = response.to_json_string()?; + + print!("{response_json}"); + + Ok(()) +} + +fn tracing_stdout_init(filter: LevelFilter) { + tracing_subscriber::fmt().with_max_level(filter).init(); + tracing::debug!("Logging initialized"); +} + +async fn handle_announce(remote_addr: SocketAddr, info_hash: &TorrustInfoHash) -> Result { + let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); + + let client = checker::Client::new(remote_addr, DEFAULT_TIMEOUT).await?; + + let connection_id = client.send_connection_request(transaction_id).await?; + + client.send_announce_request(transaction_id, connection_id, *info_hash).await +} + +async fn handle_scrape(remote_addr: SocketAddr, info_hashes: &[TorrustInfoHash]) -> Result { + let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); + + let client = checker::Client::new(remote_addr, DEFAULT_TIMEOUT).await?; + + let connection_id = client.send_connection_request(transaction_id).await?; + + client.send_scrape_request(connection_id, transaction_id, info_hashes).await +} + +fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { + tracing::debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); + + // Check if the address is a valid URL. If so, extract the host and port. + let resolved_addr = if let Ok(url) = Url::parse(tracker_socket_addr_str) { + tracing::debug!("Tracker socket address URL: {url:?}"); + + let host = url + .host_str() + .with_context(|| format!("invalid host in URL: `{tracker_socket_addr_str}`"))? + .to_owned(); + + let port = url + .port() + .with_context(|| format!("port not found in URL: `{tracker_socket_addr_str}`"))? + .to_owned(); + + (host, port) + } else { + // If not a URL, assume it's a host:port pair. + + let parts: Vec<&str> = tracker_socket_addr_str.split(':').collect(); + + if parts.len() != 2 { + return Err(anyhow::anyhow!( + "invalid address format: `{}`. Expected format is host:port", + tracker_socket_addr_str + )); + } + + let host = parts[0].to_owned(); + + let port = parts[1] + .parse::() + .with_context(|| format!("invalid port: `{}`", parts[1]))? + .to_owned(); + + (host, port) + }; + + tracing::debug!("Resolved address: {resolved_addr:#?}"); + + // Perform DNS resolution. + let socket_addrs: Vec<_> = resolved_addr.to_socket_addrs()?.collect(); + if socket_addrs.is_empty() { + Err(anyhow::anyhow!("DNS resolution failed for `{}`", tracker_socket_addr_str)) + } else { + Ok(socket_addrs[0]) + } +} + +fn parse_info_hash(info_hash_str: &str) -> anyhow::Result { + TorrustInfoHash::from_str(info_hash_str) + .map_err(|e| anyhow::Error::msg(format!("failed to parse info-hash `{info_hash_str}`: {e:?}"))) +} diff --git a/packages/tracker-client/src/console/clients/udp/checker.rs b/packages/tracker-client/src/console/clients/udp/checker.rs new file mode 100644 index 000000000..b9fd3a729 --- /dev/null +++ b/packages/tracker-client/src/console/clients/udp/checker.rs @@ -0,0 +1,177 @@ +use std::net::{Ipv4Addr, SocketAddr}; +use std::num::NonZeroU16; +use std::time::Duration; + +use aquatic_udp_protocol::common::InfoHash; +use aquatic_udp_protocol::{ + AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, + PeerId, PeerKey, Port, Response, ScrapeRequest, TransactionId, +}; +use bittorrent_primitives::info_hash::InfoHash as TorrustInfoHash; + +use super::Error; +use crate::udp::client::UdpTrackerClient; + +/// A UDP Tracker client to make test requests (checks). +#[derive(Debug)] +pub struct Client { + client: UdpTrackerClient, +} + +impl Client { + /// Creates a new `[Client]` for checking a UDP Tracker Service + /// + /// # Errors + /// + /// It will error if unable to bind and connect to the udp remote address. + /// + pub async fn new(remote_addr: SocketAddr, timeout: Duration) -> Result { + let client = UdpTrackerClient::new(remote_addr, timeout) + .await + .map_err(|err| Error::UnableToBindAndConnect { remote_addr, err })?; + + Ok(Self { client }) + } + + /// Returns the local addr of this [`Client`]. + /// + /// # Errors + /// + /// This function will return an error if the socket is somehow not bound. + pub fn local_addr(&self) -> std::io::Result { + self.client.client.socket.local_addr() + } + + /// Sends a connection request to the UDP Tracker server. + /// + /// # Errors + /// + /// Will return and error if + /// + /// - It can't connect to the remote UDP socket. + /// - It can't make a connection request successfully to the remote UDP + /// server (after successfully connecting to the remote UDP socket). + /// + /// # Panics + /// + /// Will panic if it receives an unexpected response. + pub async fn send_connection_request(&self, transaction_id: TransactionId) -> Result { + tracing::debug!("Sending connection request with transaction id: {transaction_id:#?}"); + + let connect_request = ConnectRequest { transaction_id }; + + let _ = self + .client + .send(connect_request.into()) + .await + .map_err(|err| Error::UnableToSendConnectionRequest { err })?; + + let response = self + .client + .receive() + .await + .map_err(|err| Error::UnableToReceiveConnectResponse { err })?; + + match response { + Response::Connect(connect_response) => Ok(connect_response.connection_id), + _ => Err(Error::UnexpectedConnectionResponse { response }), + } + } + + /// Sends an announce request to the UDP Tracker server. + /// + /// # Errors + /// + /// Will return and error if the client is not connected. You have to connect + /// before calling this function. + /// + /// # Panics + /// + /// It will panic if the `local_address` has a zero port. + pub async fn send_announce_request( + &self, + transaction_id: TransactionId, + connection_id: ConnectionId, + info_hash: TorrustInfoHash, + ) -> Result { + tracing::debug!("Sending announce request with transaction id: {transaction_id:#?}"); + + let port = NonZeroU16::new( + self.client + .client + .socket + .local_addr() + .expect("it should get the local address") + .port(), + ) + .expect("it should no be zero"); + + let announce_request = AnnounceRequest { + connection_id, + action_placeholder: AnnounceActionPlaceholder::default(), + transaction_id, + info_hash: InfoHash(info_hash.bytes()), + peer_id: PeerId(*b"-qB00000000000000001"), + bytes_downloaded: NumberOfBytes(0i64.into()), + bytes_uploaded: NumberOfBytes(0i64.into()), + bytes_left: NumberOfBytes(0i64.into()), + event: AnnounceEvent::Started.into(), + ip_address: Ipv4Addr::new(0, 0, 0, 0).into(), + key: PeerKey::new(0i32), + peers_wanted: NumberOfPeers(1i32.into()), + port: Port::new(port), + }; + + let _ = self + .client + .send(announce_request.into()) + .await + .map_err(|err| Error::UnableToSendAnnounceRequest { err })?; + + let response = self + .client + .receive() + .await + .map_err(|err| Error::UnableToReceiveAnnounceResponse { err })?; + + Ok(response) + } + + /// Sends a scrape request to the UDP Tracker server. + /// + /// # Errors + /// + /// Will return and error if the client is not connected. You have to connect + /// before calling this function. + pub async fn send_scrape_request( + &self, + connection_id: ConnectionId, + transaction_id: TransactionId, + info_hashes: &[TorrustInfoHash], + ) -> Result { + tracing::debug!("Sending scrape request with transaction id: {transaction_id:#?}"); + + let scrape_request = ScrapeRequest { + connection_id, + transaction_id, + info_hashes: info_hashes + .iter() + .map(|torrust_info_hash| InfoHash(torrust_info_hash.bytes())) + .collect(), + }; + + let _ = self + .client + .send(scrape_request.into()) + .await + .map_err(|err| Error::UnableToSendScrapeRequest { err })?; + + let response = self + .client + .receive() + .await + .map_err(|err| Error::UnableToReceiveScrapeResponse { err })?; + + Ok(response) + } +} diff --git a/packages/tracker-client/src/console/clients/udp/mod.rs b/packages/tracker-client/src/console/clients/udp/mod.rs new file mode 100644 index 000000000..ae6271a78 --- /dev/null +++ b/packages/tracker-client/src/console/clients/udp/mod.rs @@ -0,0 +1,51 @@ +use std::net::SocketAddr; + +use aquatic_udp_protocol::Response; +use serde::Serialize; +use thiserror::Error; + +use crate::udp; + +pub mod app; +pub mod checker; +pub mod responses; + +#[derive(Error, Debug, Clone, Serialize)] +#[serde(into = "String")] +pub enum Error { + #[error("Failed to Connect to: {remote_addr}, with error: {err}")] + UnableToBindAndConnect { remote_addr: SocketAddr, err: udp::Error }, + + #[error("Failed to send a connection request, with error: {err}")] + UnableToSendConnectionRequest { err: udp::Error }, + + #[error("Failed to receive a connect response, with error: {err}")] + UnableToReceiveConnectResponse { err: udp::Error }, + + #[error("Failed to send a announce request, with error: {err}")] + UnableToSendAnnounceRequest { err: udp::Error }, + + #[error("Failed to receive a announce response, with error: {err}")] + UnableToReceiveAnnounceResponse { err: udp::Error }, + + #[error("Failed to send a scrape request, with error: {err}")] + UnableToSendScrapeRequest { err: udp::Error }, + + #[error("Failed to receive a scrape response, with error: {err}")] + UnableToReceiveScrapeResponse { err: udp::Error }, + + #[error("Failed to receive a response, with error: {err}")] + UnableToReceiveResponse { err: udp::Error }, + + #[error("Failed to get local address for connection: {err}")] + UnableToGetLocalAddr { err: udp::Error }, + + #[error("Failed to get a connection response: {response:?}")] + UnexpectedConnectionResponse { response: Response }, +} + +impl From for String { + fn from(value: Error) -> Self { + value.to_string() + } +} diff --git a/packages/tracker-client/src/console/clients/udp/responses/dto.rs b/packages/tracker-client/src/console/clients/udp/responses/dto.rs new file mode 100644 index 000000000..93320b0f7 --- /dev/null +++ b/packages/tracker-client/src/console/clients/udp/responses/dto.rs @@ -0,0 +1,128 @@ +//! Aquatic responses are not serializable. These are the serializable wrappers. +use std::net::{Ipv4Addr, Ipv6Addr}; + +use aquatic_udp_protocol::Response::{self}; +use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse}; +use serde::Serialize; + +#[derive(Serialize)] +pub enum SerializableResponse { + Connect(ConnectSerializableResponse), + AnnounceIpv4(AnnounceSerializableResponse), + AnnounceIpv6(AnnounceSerializableResponse), + Scrape(ScrapeSerializableResponse), + Error(ErrorSerializableResponse), +} + +impl From for SerializableResponse { + fn from(response: Response) -> Self { + match response { + Response::Connect(response) => SerializableResponse::Connect(ConnectSerializableResponse::from(response)), + Response::AnnounceIpv4(response) => SerializableResponse::AnnounceIpv4(AnnounceSerializableResponse::from(response)), + Response::AnnounceIpv6(response) => SerializableResponse::AnnounceIpv6(AnnounceSerializableResponse::from(response)), + Response::Scrape(response) => SerializableResponse::Scrape(ScrapeSerializableResponse::from(response)), + Response::Error(response) => SerializableResponse::Error(ErrorSerializableResponse::from(response)), + } + } +} + +#[derive(Serialize)] +pub struct ConnectSerializableResponse { + transaction_id: i32, + connection_id: i64, +} + +impl From for ConnectSerializableResponse { + fn from(connect: ConnectResponse) -> Self { + Self { + transaction_id: connect.transaction_id.0.into(), + connection_id: connect.connection_id.0.into(), + } + } +} + +#[derive(Serialize)] +pub struct AnnounceSerializableResponse { + transaction_id: i32, + announce_interval: i32, + leechers: i32, + seeders: i32, + peers: Vec, +} + +impl From> for AnnounceSerializableResponse { + fn from(announce: AnnounceResponse) -> Self { + Self { + transaction_id: announce.fixed.transaction_id.0.into(), + announce_interval: announce.fixed.announce_interval.0.into(), + leechers: announce.fixed.leechers.0.into(), + seeders: announce.fixed.seeders.0.into(), + peers: announce + .peers + .iter() + .map(|peer| format!("{}:{}", Ipv4Addr::from(peer.ip_address), peer.port.0)) + .collect::>(), + } + } +} + +impl From> for AnnounceSerializableResponse { + fn from(announce: AnnounceResponse) -> Self { + Self { + transaction_id: announce.fixed.transaction_id.0.into(), + announce_interval: announce.fixed.announce_interval.0.into(), + leechers: announce.fixed.leechers.0.into(), + seeders: announce.fixed.seeders.0.into(), + peers: announce + .peers + .iter() + .map(|peer| format!("{}:{}", Ipv6Addr::from(peer.ip_address), peer.port.0)) + .collect::>(), + } + } +} + +#[derive(Serialize)] +pub struct ScrapeSerializableResponse { + transaction_id: i32, + torrent_stats: Vec, +} + +impl From for ScrapeSerializableResponse { + fn from(scrape: ScrapeResponse) -> Self { + Self { + transaction_id: scrape.transaction_id.0.into(), + torrent_stats: scrape + .torrent_stats + .iter() + .map(|torrent_scrape_statistics| TorrentStats { + seeders: torrent_scrape_statistics.seeders.0.into(), + completed: torrent_scrape_statistics.completed.0.into(), + leechers: torrent_scrape_statistics.leechers.0.into(), + }) + .collect::>(), + } + } +} + +#[derive(Serialize)] +pub struct ErrorSerializableResponse { + transaction_id: i32, + message: String, +} + +impl From for ErrorSerializableResponse { + fn from(error: ErrorResponse) -> Self { + Self { + transaction_id: error.transaction_id.0.into(), + message: error.message.to_string(), + } + } +} + +#[derive(Serialize)] +struct TorrentStats { + seeders: i32, + completed: i32, + leechers: i32, +} diff --git a/packages/tracker-client/src/console/clients/udp/responses/json.rs b/packages/tracker-client/src/console/clients/udp/responses/json.rs new file mode 100644 index 000000000..5d2bd6b89 --- /dev/null +++ b/packages/tracker-client/src/console/clients/udp/responses/json.rs @@ -0,0 +1,25 @@ +use anyhow::Context; +use serde::Serialize; + +use super::dto::SerializableResponse; + +#[allow(clippy::module_name_repetitions)] +pub trait ToJson { + /// + /// Returns a string with the JSON serialized version of the response + /// + /// # Errors + /// + /// Will return an error if serialization fails. + /// + fn to_json_string(&self) -> anyhow::Result + where + Self: Serialize, + { + let pretty_json = serde_json::to_string_pretty(self).context("response JSON serialization")?; + + Ok(pretty_json) + } +} + +impl ToJson for SerializableResponse {} diff --git a/packages/tracker-client/src/console/clients/udp/responses/mod.rs b/packages/tracker-client/src/console/clients/udp/responses/mod.rs new file mode 100644 index 000000000..e6d2e5e51 --- /dev/null +++ b/packages/tracker-client/src/console/clients/udp/responses/mod.rs @@ -0,0 +1,2 @@ +pub mod dto; +pub mod json; diff --git a/packages/tracker-client/src/console/mod.rs b/packages/tracker-client/src/console/mod.rs new file mode 100644 index 000000000..4b4cb9de4 --- /dev/null +++ b/packages/tracker-client/src/console/mod.rs @@ -0,0 +1,2 @@ +//! Console apps. +pub mod clients; diff --git a/packages/tracker-client/src/http/client/mod.rs b/packages/tracker-client/src/http/client/mod.rs new file mode 100644 index 000000000..3c904a7c9 --- /dev/null +++ b/packages/tracker-client/src/http/client/mod.rs @@ -0,0 +1,220 @@ +pub mod requests; +pub mod responses; + +use std::net::IpAddr; +use std::sync::Arc; +use std::time::Duration; + +use derive_more::Display; +use hyper::StatusCode; +use requests::{announce, scrape}; +use reqwest::{Response, Url}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +#[derive(Debug, Clone, Error)] +pub enum Error { + #[error("Failed to Build a Http Client: {err:?}")] + ClientBuildingError { err: Arc }, + #[error("Failed to get a response: {err:?}")] + ResponseError { err: Arc }, + #[error("Returned a non-success code: \"{code}\" with the response: \"{response:?}\"")] + UnsuccessfulResponse { code: StatusCode, response: Arc }, +} + +/// HTTP Tracker Client +pub struct Client { + client: reqwest::Client, + base_url: Url, + key: Option, +} + +/// URL components in this context: +/// +/// ```text +/// http://127.0.0.1:62304/announce/YZ....rJ?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 +/// \_____________________/\_______________/ \__________________________________________________________/ +/// | | | +/// base url path query +/// ``` +impl Client { + /// # Errors + /// + /// This method fails if the client builder fails. + pub fn new(base_url: Url, timeout: Duration) -> Result { + let client = reqwest::Client::builder() + .timeout(timeout) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; + + Ok(Self { + base_url, + client, + key: None, + }) + } + + /// Creates the new client binding it to an specific local address. + /// + /// # Errors + /// + /// This method fails if the client builder fails. + pub fn bind(base_url: Url, timeout: Duration, local_address: IpAddr) -> Result { + let client = reqwest::Client::builder() + .timeout(timeout) + .local_address(local_address) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; + + Ok(Self { + base_url, + client, + key: None, + }) + } + + /// # Errors + /// + /// This method fails if the client builder fails. + pub fn authenticated(base_url: Url, timeout: Duration, key: Key) -> Result { + let client = reqwest::Client::builder() + .timeout(timeout) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; + + Ok(Self { + base_url, + client, + key: Some(key), + }) + } + + /// # Errors + /// + /// This method fails if the returned response was not successful + pub async fn announce(&self, query: &announce::Query) -> Result { + let response = self.get(&self.build_announce_path_and_query(query)).await?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } + } + + /// # Errors + /// + /// This method fails if the returned response was not successful + pub async fn scrape(&self, query: &scrape::Query) -> Result { + let response = self.get(&self.build_scrape_path_and_query(query)).await?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } + } + + /// # Errors + /// + /// This method fails if the returned response was not successful + pub async fn announce_with_header(&self, query: &announce::Query, key: &str, value: &str) -> Result { + let response = self + .get_with_header(&self.build_announce_path_and_query(query), key, value) + .await?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } + } + + /// # Errors + /// + /// This method fails if the returned response was not successful + pub async fn health_check(&self) -> Result { + let response = self.get(&self.build_path("health_check")).await?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } + } + + /// # Errors + /// + /// This method fails if there was an error while sending request. + pub async fn get(&self, path: &str) -> Result { + self.client + .get(self.build_url(path)) + .send() + .await + .map_err(|e| Error::ResponseError { err: e.into() }) + } + + /// # Errors + /// + /// This method fails if there was an error while sending request. + pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Result { + self.client + .get(self.build_url(path)) + .header(key, value) + .send() + .await + .map_err(|e| Error::ResponseError { err: e.into() }) + } + + fn build_announce_path_and_query(&self, query: &announce::Query) -> String { + format!("{}?{query}", self.build_path("announce")) + } + + fn build_scrape_path_and_query(&self, query: &scrape::Query) -> String { + format!("{}?{query}", self.build_path("scrape")) + } + + fn build_path(&self, path: &str) -> String { + match &self.key { + Some(key) => format!("{path}/{key}"), + None => path.to_string(), + } + } + + fn build_url(&self, path: &str) -> String { + let base_url = self.base_url(); + format!("{base_url}{path}") + } + + fn base_url(&self) -> String { + self.base_url.to_string() + } +} + +/// A token used for authentication. +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Display, Hash)] +pub struct Key(String); + +impl Key { + #[must_use] + pub fn new(value: &str) -> Self { + Self(value.to_owned()) + } + + #[must_use] + pub fn value(&self) -> &str { + &self.0 + } +} diff --git a/packages/tracker-client/src/http/client/requests/announce.rs b/packages/tracker-client/src/http/client/requests/announce.rs new file mode 100644 index 000000000..8f81cc80e --- /dev/null +++ b/packages/tracker-client/src/http/client/requests/announce.rs @@ -0,0 +1,275 @@ +use std::fmt; +use std::net::{IpAddr, Ipv4Addr}; +use std::str::FromStr; + +use aquatic_udp_protocol::PeerId; +use bittorrent_primitives::info_hash::InfoHash; +use serde_repr::Serialize_repr; + +use crate::http::{percent_encode_byte_array, ByteArray20}; + +pub struct Query { + pub info_hash: ByteArray20, + pub peer_addr: IpAddr, + pub downloaded: BaseTenASCII, + pub uploaded: BaseTenASCII, + pub peer_id: ByteArray20, + pub port: PortNumber, + pub left: BaseTenASCII, + pub event: Option, + pub compact: Option, +} + +impl fmt::Display for Query { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.build()) + } +} + +/// HTTP Tracker Announce Request: +/// +/// +/// +/// Some parameters in the specification are not implemented in this tracker yet. +impl Query { + /// It builds the URL query component for the announce request. + /// + /// This custom URL query params encoding is needed because `reqwest` does not allow + /// bytes arrays in query parameters. More info on this issue: + /// + /// + #[must_use] + pub fn build(&self) -> String { + self.params().to_string() + } + + #[must_use] + pub fn params(&self) -> QueryParams { + QueryParams::from(self) + } +} + +pub type BaseTenASCII = u64; +pub type PortNumber = u16; + +pub enum Event { + //Started, + //Stopped, + Completed, +} + +impl fmt::Display for Event { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + //Event::Started => write!(f, "started"), + //Event::Stopped => write!(f, "stopped"), + Event::Completed => write!(f, "completed"), + } + } +} + +#[derive(Serialize_repr, PartialEq, Debug)] +#[repr(u8)] +pub enum Compact { + Accepted = 1, + NotAccepted = 0, +} + +impl fmt::Display for Compact { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Compact::Accepted => write!(f, "1"), + Compact::NotAccepted => write!(f, "0"), + } + } +} + +pub struct QueryBuilder { + announce_query: Query, +} + +impl QueryBuilder { + /// # Panics + /// + /// Will panic if the default info-hash value is not a valid info-hash. + #[must_use] + pub fn with_default_values() -> QueryBuilder { + let default_announce_query = Query { + info_hash: InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0, // # DevSkim: ignore DS173237 + peer_addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 88)), + downloaded: 0, + uploaded: 0, + peer_id: PeerId(*b"-qB00000000000000001").0, + port: 17548, + left: 0, + event: Some(Event::Completed), + compact: Some(Compact::NotAccepted), + }; + Self { + announce_query: default_announce_query, + } + } + + #[must_use] + pub fn with_info_hash(mut self, info_hash: &InfoHash) -> Self { + self.announce_query.info_hash = info_hash.0; + self + } + + #[must_use] + pub fn with_peer_id(mut self, peer_id: &PeerId) -> Self { + self.announce_query.peer_id = peer_id.0; + self + } + + #[must_use] + pub fn with_compact(mut self, compact: Compact) -> Self { + self.announce_query.compact = Some(compact); + self + } + + #[must_use] + pub fn with_peer_addr(mut self, peer_addr: &IpAddr) -> Self { + self.announce_query.peer_addr = *peer_addr; + self + } + + #[must_use] + pub fn without_compact(mut self) -> Self { + self.announce_query.compact = None; + self + } + + #[must_use] + pub fn query(self) -> Query { + self.announce_query + } +} + +/// It contains all the GET parameters that can be used in a HTTP Announce request. +/// +/// Sample Announce URL with all the GET parameters (mandatory and optional): +/// +/// ```text +/// http://127.0.0.1:7070/announce? +/// info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 (mandatory) +/// peer_addr=192.168.1.88 +/// downloaded=0 +/// uploaded=0 +/// peer_id=%2DqB00000000000000000 (mandatory) +/// port=17548 (mandatory) +/// left=0 +/// event=completed +/// compact=0 +/// ``` +pub struct QueryParams { + pub info_hash: Option, + pub peer_addr: Option, + pub downloaded: Option, + pub uploaded: Option, + pub peer_id: Option, + pub port: Option, + pub left: Option, + pub event: Option, + pub compact: Option, +} + +impl std::fmt::Display for QueryParams { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut params = vec![]; + + if let Some(info_hash) = &self.info_hash { + params.push(("info_hash", info_hash)); + } + if let Some(peer_addr) = &self.peer_addr { + params.push(("peer_addr", peer_addr)); + } + if let Some(downloaded) = &self.downloaded { + params.push(("downloaded", downloaded)); + } + if let Some(uploaded) = &self.uploaded { + params.push(("uploaded", uploaded)); + } + if let Some(peer_id) = &self.peer_id { + params.push(("peer_id", peer_id)); + } + if let Some(port) = &self.port { + params.push(("port", port)); + } + if let Some(left) = &self.left { + params.push(("left", left)); + } + if let Some(event) = &self.event { + params.push(("event", event)); + } + if let Some(compact) = &self.compact { + params.push(("compact", compact)); + } + + let query = params + .iter() + .map(|param| format!("{}={}", param.0, param.1)) + .collect::>() + .join("&"); + + write!(f, "{query}") + } +} + +impl QueryParams { + pub fn from(announce_query: &Query) -> Self { + let event = announce_query.event.as_ref().map(std::string::ToString::to_string); + let compact = announce_query.compact.as_ref().map(std::string::ToString::to_string); + + Self { + info_hash: Some(percent_encode_byte_array(&announce_query.info_hash)), + peer_addr: Some(announce_query.peer_addr.to_string()), + downloaded: Some(announce_query.downloaded.to_string()), + uploaded: Some(announce_query.uploaded.to_string()), + peer_id: Some(percent_encode_byte_array(&announce_query.peer_id)), + port: Some(announce_query.port.to_string()), + left: Some(announce_query.left.to_string()), + event, + compact, + } + } + + pub fn remove_optional_params(&mut self) { + // todo: make them optional with the Option<...> in the AnnounceQuery struct + // if they are really optional. So that we can crete a minimal AnnounceQuery + // instead of removing the optional params afterwards. + // + // The original specification on: + // + // says only `ip` and `event` are optional. + // + // On + // says only `ip`, `numwant`, `key` and `trackerid` are optional. + // + // but the server is responding if all these params are not included. + self.peer_addr = None; + self.downloaded = None; + self.uploaded = None; + self.left = None; + self.event = None; + self.compact = None; + } + + /// # Panics + /// + /// Will panic if invalid param name is provided. + pub fn set(&mut self, param_name: &str, param_value: &str) { + match param_name { + "info_hash" => self.info_hash = Some(param_value.to_string()), + "peer_addr" => self.peer_addr = Some(param_value.to_string()), + "downloaded" => self.downloaded = Some(param_value.to_string()), + "uploaded" => self.uploaded = Some(param_value.to_string()), + "peer_id" => self.peer_id = Some(param_value.to_string()), + "port" => self.port = Some(param_value.to_string()), + "left" => self.left = Some(param_value.to_string()), + "event" => self.event = Some(param_value.to_string()), + "compact" => self.compact = Some(param_value.to_string()), + &_ => panic!("Invalid param name for announce query"), + } + } +} diff --git a/packages/tracker-client/src/http/client/requests/mod.rs b/packages/tracker-client/src/http/client/requests/mod.rs new file mode 100644 index 000000000..776d2dfbf --- /dev/null +++ b/packages/tracker-client/src/http/client/requests/mod.rs @@ -0,0 +1,2 @@ +pub mod announce; +pub mod scrape; diff --git a/packages/tracker-client/src/http/client/requests/scrape.rs b/packages/tracker-client/src/http/client/requests/scrape.rs new file mode 100644 index 000000000..1b423390b --- /dev/null +++ b/packages/tracker-client/src/http/client/requests/scrape.rs @@ -0,0 +1,172 @@ +use std::error::Error; +use std::fmt::{self}; +use std::str::FromStr; + +use bittorrent_primitives::info_hash::InfoHash; + +use crate::http::{percent_encode_byte_array, ByteArray20}; + +pub struct Query { + pub info_hash: Vec, +} + +impl fmt::Display for Query { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.build()) + } +} + +#[derive(Debug)] +#[allow(dead_code)] +pub struct ConversionError(String); + +impl fmt::Display for ConversionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Invalid infohash: {}", self.0) + } +} + +impl Error for ConversionError {} + +impl TryFrom<&[String]> for Query { + type Error = ConversionError; + + fn try_from(info_hashes: &[String]) -> Result { + let mut validated_info_hashes: Vec = Vec::new(); + + for info_hash in info_hashes { + let validated_info_hash = InfoHash::from_str(info_hash).map_err(|_| ConversionError(info_hash.clone()))?; + validated_info_hashes.push(validated_info_hash.0); + } + + Ok(Self { + info_hash: validated_info_hashes, + }) + } +} + +impl TryFrom> for Query { + type Error = ConversionError; + + fn try_from(info_hashes: Vec) -> Result { + let mut validated_info_hashes: Vec = Vec::new(); + + for info_hash in info_hashes { + let validated_info_hash = InfoHash::from_str(&info_hash).map_err(|_| ConversionError(info_hash.clone()))?; + validated_info_hashes.push(validated_info_hash.0); + } + + Ok(Self { + info_hash: validated_info_hashes, + }) + } +} + +/// HTTP Tracker Scrape Request: +/// +/// +impl Query { + /// It builds the URL query component for the scrape request. + /// + /// This custom URL query params encoding is needed because `reqwest` does not allow + /// bytes arrays in query parameters. More info on this issue: + /// + /// + #[must_use] + pub fn build(&self) -> String { + self.params().to_string() + } + + #[must_use] + pub fn params(&self) -> QueryParams { + QueryParams::from(self) + } +} + +pub struct QueryBuilder { + scrape_query: Query, +} + +impl Default for QueryBuilder { + fn default() -> Self { + let default_scrape_query = Query { + info_hash: [InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0].to_vec(), // # DevSkim: ignore DS173237 + }; + Self { + scrape_query: default_scrape_query, + } + } +} + +impl QueryBuilder { + #[must_use] + pub fn with_one_info_hash(mut self, info_hash: &InfoHash) -> Self { + self.scrape_query.info_hash = [info_hash.0].to_vec(); + self + } + + #[must_use] + pub fn add_info_hash(mut self, info_hash: &InfoHash) -> Self { + self.scrape_query.info_hash.push(info_hash.0); + self + } + + #[must_use] + pub fn query(self) -> Query { + self.scrape_query + } +} + +/// It contains all the GET parameters that can be used in a HTTP Scrape request. +/// +/// The `info_hash` param is the percent encoded of the the 20-byte array info hash. +/// +/// Sample Scrape URL with all the GET parameters: +/// +/// For `IpV4`: +/// +/// ```text +/// http://127.0.0.1:7070/scrape?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 +/// ``` +/// +/// For `IpV6`: +/// +/// ```text +/// http://[::1]:7070/scrape?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 +/// ``` +/// +/// You can add as many info hashes as you want, just adding the same param again. +pub struct QueryParams { + pub info_hash: Vec, +} + +impl QueryParams { + pub fn set_one_info_hash_param(&mut self, info_hash: &str) { + self.info_hash = vec![info_hash.to_string()]; + } +} + +impl std::fmt::Display for QueryParams { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let query = self + .info_hash + .iter() + .map(|info_hash| format!("info_hash={}", &info_hash)) + .collect::>() + .join("&"); + + write!(f, "{query}") + } +} + +impl QueryParams { + pub fn from(scrape_query: &Query) -> Self { + let info_hashes = scrape_query + .info_hash + .iter() + .map(percent_encode_byte_array) + .collect::>(); + + Self { info_hash: info_hashes } + } +} diff --git a/packages/tracker-client/src/http/client/responses/announce.rs b/packages/tracker-client/src/http/client/responses/announce.rs new file mode 100644 index 000000000..7f2d3611c --- /dev/null +++ b/packages/tracker-client/src/http/client/responses/announce.rs @@ -0,0 +1,126 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use serde::{Deserialize, Serialize}; +use torrust_tracker_primitives::peer; +use zerocopy::AsBytes as _; + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct Announce { + pub complete: u32, + pub incomplete: u32, + pub interval: u32, + #[serde(rename = "min interval")] + pub min_interval: u32, + pub peers: Vec, // Peers using IPV4 and IPV6 +} + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct DictionaryPeer { + pub ip: String, + #[serde(rename = "peer id")] + #[serde(with = "serde_bytes")] + pub peer_id: Vec, + pub port: u16, +} + +impl From for DictionaryPeer { + fn from(peer: peer::Peer) -> Self { + DictionaryPeer { + peer_id: peer.peer_id.as_bytes().to_vec(), + ip: peer.peer_addr.ip().to_string(), + port: peer.peer_addr.port(), + } + } +} + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct DeserializedCompact { + pub complete: u32, + pub incomplete: u32, + pub interval: u32, + #[serde(rename = "min interval")] + pub min_interval: u32, + #[serde(with = "serde_bytes")] + pub peers: Vec, +} + +impl DeserializedCompact { + /// # Errors + /// + /// Will return an error if bytes can't be deserialized. + pub fn from_bytes(bytes: &[u8]) -> Result { + serde_bencode::from_bytes::(bytes) + } +} + +#[derive(Debug, PartialEq)] +pub struct Compact { + // code-review: there could be a way to deserialize this struct directly + // by using serde instead of doing it manually. Or at least using a custom deserializer. + pub complete: u32, + pub incomplete: u32, + pub interval: u32, + pub min_interval: u32, + pub peers: CompactPeerList, +} + +#[derive(Debug, PartialEq)] +pub struct CompactPeerList { + peers: Vec, +} + +impl CompactPeerList { + #[must_use] + pub fn new(peers: Vec) -> Self { + Self { peers } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct CompactPeer { + ip: Ipv4Addr, + port: u16, +} + +impl CompactPeer { + /// # Panics + /// + /// Will panic if the provided socket address is a IPv6 IP address. + /// It's not supported for compact peers. + #[must_use] + pub fn new(socket_addr: &SocketAddr) -> Self { + match socket_addr.ip() { + IpAddr::V4(ip) => Self { + ip, + port: socket_addr.port(), + }, + IpAddr::V6(_ip) => panic!("IPV6 is not supported for compact peer"), + } + } + + #[must_use] + pub fn new_from_bytes(bytes: &[u8]) -> Self { + Self { + ip: Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]), + port: u16::from_be_bytes([bytes[4], bytes[5]]), + } + } +} + +impl From for Compact { + fn from(compact_announce: DeserializedCompact) -> Self { + let mut peers = vec![]; + + for peer_bytes in compact_announce.peers.chunks_exact(6) { + peers.push(CompactPeer::new_from_bytes(peer_bytes)); + } + + Self { + complete: compact_announce.complete, + incomplete: compact_announce.incomplete, + interval: compact_announce.interval, + min_interval: compact_announce.min_interval, + peers: CompactPeerList::new(peers), + } + } +} diff --git a/packages/tracker-client/src/http/client/responses/error.rs b/packages/tracker-client/src/http/client/responses/error.rs new file mode 100644 index 000000000..00befdb54 --- /dev/null +++ b/packages/tracker-client/src/http/client/responses/error.rs @@ -0,0 +1,7 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +pub struct Error { + #[serde(rename = "failure reason")] + pub failure_reason: String, +} diff --git a/packages/tracker-client/src/http/client/responses/mod.rs b/packages/tracker-client/src/http/client/responses/mod.rs new file mode 100644 index 000000000..bdc689056 --- /dev/null +++ b/packages/tracker-client/src/http/client/responses/mod.rs @@ -0,0 +1,3 @@ +pub mod announce; +pub mod error; +pub mod scrape; diff --git a/packages/tracker-client/src/http/client/responses/scrape.rs b/packages/tracker-client/src/http/client/responses/scrape.rs new file mode 100644 index 000000000..6c0e8800a --- /dev/null +++ b/packages/tracker-client/src/http/client/responses/scrape.rs @@ -0,0 +1,230 @@ +use std::collections::HashMap; +use std::fmt::Write; +use std::str; + +use serde::ser::SerializeMap; +use serde::{Deserialize, Serialize, Serializer}; +use serde_bencode::value::Value; + +use crate::http::{ByteArray20, InfoHash}; + +#[derive(Debug, PartialEq, Default, Deserialize)] +pub struct Response { + pub files: HashMap, +} + +impl Response { + #[must_use] + pub fn with_one_file(info_hash_bytes: ByteArray20, file: File) -> Self { + let mut files: HashMap = HashMap::new(); + files.insert(info_hash_bytes, file); + Self { files } + } + + /// # Errors + /// + /// Will return an error if the deserialized bencoded response can't not be converted into a valid response. + /// + /// # Panics + /// + /// Will panic if it can't deserialize the bencoded response. + pub fn try_from_bencoded(bytes: &[u8]) -> Result { + let scrape_response: DeserializedResponse = + serde_bencode::from_bytes(bytes).expect("provided bytes should be a valid bencoded response"); + Self::try_from(scrape_response) + } +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Default)] +pub struct File { + pub complete: i64, // The number of active peers that have completed downloading + pub downloaded: i64, // The number of peers that have ever completed downloading + pub incomplete: i64, // The number of active peers that have not completed downloading +} + +impl File { + #[must_use] + pub fn zeroed() -> Self { + Self::default() + } +} + +impl TryFrom for Response { + type Error = BencodeParseError; + + fn try_from(scrape_response: DeserializedResponse) -> Result { + parse_bencoded_response(&scrape_response.files) + } +} + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +struct DeserializedResponse { + pub files: Value, +} + +// Custom serialization for Response +impl Serialize for Response { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut map = serializer.serialize_map(Some(self.files.len()))?; + for (key, value) in &self.files { + // Convert ByteArray20 key to hex string + let hex_key = byte_array_to_hex_string(key); + map.serialize_entry(&hex_key, value)?; + } + map.end() + } +} + +// Helper function to convert ByteArray20 to hex string +fn byte_array_to_hex_string(byte_array: &ByteArray20) -> String { + let mut hex_string = String::with_capacity(byte_array.len() * 2); + for byte in byte_array { + write!(hex_string, "{byte:02x}").expect("Writing to string should never fail"); + } + hex_string +} + +#[derive(Default)] +pub struct ResponseBuilder { + response: Response, +} + +impl ResponseBuilder { + #[must_use] + pub fn add_file(mut self, info_hash_bytes: ByteArray20, file: File) -> Self { + self.response.files.insert(info_hash_bytes, file); + self + } + + #[must_use] + pub fn build(self) -> Response { + self.response + } +} + +#[derive(Debug)] +pub enum BencodeParseError { + InvalidValueExpectedDict { value: Value }, + InvalidValueExpectedInt { value: Value }, + InvalidFileField { value: Value }, + MissingFileField { field_name: String }, +} + +/// It parses a bencoded scrape response into a `Response` struct. +/// +/// For example: +/// +/// ```text +/// d5:filesd20:xxxxxxxxxxxxxxxxxxxxd8:completei11e10:downloadedi13772e10:incompletei19e +/// 20:yyyyyyyyyyyyyyyyyyyyd8:completei21e10:downloadedi206e10:incompletei20eee +/// ``` +/// +/// Response (JSON encoded for readability): +/// +/// ```text +/// { +/// 'files': { +/// 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19}, +/// 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20} +/// } +/// } +fn parse_bencoded_response(value: &Value) -> Result { + let mut files: HashMap = HashMap::new(); + + match value { + Value::Dict(dict) => { + for file_element in dict { + let info_hash_byte_vec = file_element.0; + let file_value = file_element.1; + + let file = parse_bencoded_file(file_value).unwrap(); + + files.insert(InfoHash::new(info_hash_byte_vec).bytes(), file); + } + } + _ => return Err(BencodeParseError::InvalidValueExpectedDict { value: value.clone() }), + } + + Ok(Response { files }) +} + +/// It parses a bencoded dictionary into a `File` struct. +/// +/// For example: +/// +/// +/// ```text +/// d8:completei11e10:downloadedi13772e10:incompletei19ee +/// ``` +/// +/// into: +/// +/// ```text +/// File { +/// complete: 11, +/// downloaded: 13772, +/// incomplete: 19, +/// } +/// ``` +fn parse_bencoded_file(value: &Value) -> Result { + let file = match &value { + Value::Dict(dict) => { + let mut complete = None; + let mut downloaded = None; + let mut incomplete = None; + + for file_field in dict { + let field_name = file_field.0; + + let field_value = match file_field.1 { + Value::Int(number) => Ok(*number), + _ => Err(BencodeParseError::InvalidValueExpectedInt { + value: file_field.1.clone(), + }), + }?; + + if field_name == b"complete" { + complete = Some(field_value); + } else if field_name == b"downloaded" { + downloaded = Some(field_value); + } else if field_name == b"incomplete" { + incomplete = Some(field_value); + } else { + return Err(BencodeParseError::InvalidFileField { + value: file_field.1.clone(), + }); + } + } + + if complete.is_none() { + return Err(BencodeParseError::MissingFileField { + field_name: "complete".to_string(), + }); + } + + if downloaded.is_none() { + return Err(BencodeParseError::MissingFileField { + field_name: "downloaded".to_string(), + }); + } + + if incomplete.is_none() { + return Err(BencodeParseError::MissingFileField { + field_name: "incomplete".to_string(), + }); + } + + File { + complete: complete.unwrap(), + downloaded: downloaded.unwrap(), + incomplete: incomplete.unwrap(), + } + } + _ => return Err(BencodeParseError::InvalidValueExpectedDict { value: value.clone() }), + }; + + Ok(file) +} diff --git a/packages/tracker-client/src/http/mod.rs b/packages/tracker-client/src/http/mod.rs new file mode 100644 index 000000000..dc144814d --- /dev/null +++ b/packages/tracker-client/src/http/mod.rs @@ -0,0 +1,27 @@ +pub mod client; +pub mod url_encoding; + +use percent_encoding::NON_ALPHANUMERIC; + +pub type ByteArray20 = [u8; 20]; + +#[must_use] +pub fn percent_encode_byte_array(bytes: &ByteArray20) -> String { + percent_encoding::percent_encode(bytes, NON_ALPHANUMERIC).to_string() +} + +pub struct InfoHash(ByteArray20); + +impl InfoHash { + #[must_use] + pub fn new(vec: &[u8]) -> Self { + let mut byte_array_20: ByteArray20 = Default::default(); + byte_array_20.clone_from_slice(vec); + Self(byte_array_20) + } + + #[must_use] + pub fn bytes(&self) -> ByteArray20 { + self.0 + } +} diff --git a/packages/tracker-client/src/http/url_encoding.rs b/packages/tracker-client/src/http/url_encoding.rs new file mode 100644 index 000000000..ee7ab166e --- /dev/null +++ b/packages/tracker-client/src/http/url_encoding.rs @@ -0,0 +1,132 @@ +//! This module contains functions for percent decoding infohashes and peer IDs. +//! +//! Percent encoding is an encoding format used to encode arbitrary data in a +//! format that is safe to use in URLs. It is used by the HTTP tracker protocol +//! to encode infohashes and peer ids in the URLs of requests. +//! +//! `BitTorrent` infohashes and peer ids are percent encoded like any other +//! arbitrary URL parameter. But they are encoded from binary data (byte arrays) +//! which may not be valid UTF-8. That makes hard to use the `percent_encoding` +//! crate to decode them because all of them expect a well-formed UTF-8 string. +//! However, percent encoding is not limited to UTF-8 strings. +//! +//! More information about "Percent Encoding" can be found here: +//! +//! - +//! - +//! - +use aquatic_udp_protocol::PeerId; +use bittorrent_primitives::info_hash::{self, InfoHash}; +use torrust_tracker_primitives::peer; + +/* code-review: this module is duplicated in torrust_tracker::servers::http::percent_encoding. + Should we move it to torrust_tracker_primitives? +*/ + +/// Percent decodes a percent encoded infohash. Internally an +/// [`InfoHash`] is a 20-byte array. +/// +/// For example, given the infohash `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`, +/// it's percent encoded representation is `%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0`. +/// +/// ```rust +/// use std::str::FromStr; +/// use torrust_tracker::servers::http::percent_encoding::percent_decode_info_hash; +/// use bittorrent_primitives::info_hash::InfoHash; +/// use torrust_tracker_primitives::peer; +/// +/// let encoded_infohash = "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0"; +/// +/// let info_hash = percent_decode_info_hash(encoded_infohash).unwrap(); +/// +/// assert_eq!( +/// info_hash, +/// InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap() +/// ); +/// ``` +/// +/// # Errors +/// +/// Will return `Err` if the decoded bytes do not represent a valid +/// [`InfoHash`]. +pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result { + let bytes = percent_encoding::percent_decode_str(raw_info_hash).collect::>(); + InfoHash::try_from(bytes) +} + +/// Percent decodes a percent encoded peer id. Internally a peer [`Id`](PeerId) +/// is a 20-byte array. +/// +/// For example, given the peer id `*b"-qB00000000000000000"`, +/// it's percent encoded representation is `%2DqB00000000000000000`. +/// +/// ```rust +/// use std::str::FromStr; +/// +/// use aquatic_udp_protocol::PeerId; +/// use torrust_tracker::servers::http::percent_encoding::percent_decode_peer_id; +/// use bittorrent_primitives::info_hash::InfoHash; +/// +/// let encoded_peer_id = "%2DqB00000000000000000"; +/// +/// let peer_id = percent_decode_peer_id(encoded_peer_id).unwrap(); +/// +/// assert_eq!(peer_id, PeerId(*b"-qB00000000000000000")); +/// ``` +/// +/// # Errors +/// +/// Will return `Err` if if the decoded bytes do not represent a valid [`PeerId`]. +pub fn percent_decode_peer_id(raw_peer_id: &str) -> Result { + let bytes = percent_encoding::percent_decode_str(raw_peer_id).collect::>(); + Ok(*peer::Id::try_from(bytes)?) +} + +#[cfg(test)] +mod tests { + use std::str::FromStr; + + use aquatic_udp_protocol::PeerId; + use bittorrent_primitives::info_hash::InfoHash; + + use crate::http::url_encoding::{percent_decode_info_hash, percent_decode_peer_id}; + + #[test] + fn it_should_decode_a_percent_encoded_info_hash() { + let encoded_infohash = "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0"; + + let info_hash = percent_decode_info_hash(encoded_infohash).unwrap(); + + assert_eq!( + info_hash, + InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap() + ); + } + + #[test] + fn it_should_fail_decoding_an_invalid_percent_encoded_info_hash() { + let invalid_encoded_infohash = "invalid percent-encoded infohash"; + + let info_hash = percent_decode_info_hash(invalid_encoded_infohash); + + assert!(info_hash.is_err()); + } + + #[test] + fn it_should_decode_a_percent_encoded_peer_id() { + let encoded_peer_id = "%2DqB00000000000000000"; + + let peer_id = percent_decode_peer_id(encoded_peer_id).unwrap(); + + assert_eq!(peer_id, PeerId(*b"-qB00000000000000000")); + } + + #[test] + fn it_should_fail_decoding_an_invalid_percent_encoded_peer_id() { + let invalid_encoded_peer_id = "invalid percent-encoded peer id"; + + let peer_id = percent_decode_peer_id(invalid_encoded_peer_id); + + assert!(peer_id.is_err()); + } +} diff --git a/packages/tracker-client/src/lib.rs b/packages/tracker-client/src/lib.rs new file mode 100644 index 000000000..344e1b577 --- /dev/null +++ b/packages/tracker-client/src/lib.rs @@ -0,0 +1,3 @@ +pub mod console; +pub mod http; +pub mod udp; diff --git a/packages/tracker-client/src/udp/client.rs b/packages/tracker-client/src/udp/client.rs new file mode 100644 index 000000000..facdfac38 --- /dev/null +++ b/packages/tracker-client/src/udp/client.rs @@ -0,0 +1,270 @@ +use core::result::Result::{Err, Ok}; +use std::io::Cursor; +use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::sync::Arc; +use std::time::Duration; + +use aquatic_udp_protocol::{ConnectRequest, Request, Response, TransactionId}; +use tokio::net::UdpSocket; +use tokio::time; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; +use zerocopy::network_endian::I32; + +use super::Error; +use crate::udp::MAX_PACKET_SIZE; + +pub const UDP_CLIENT_LOG_TARGET: &str = "UDP CLIENT"; + +#[allow(clippy::module_name_repetitions)] +#[derive(Debug)] +pub struct UdpClient { + /// The socket to connect to + pub socket: Arc, + + /// Timeout for sending and receiving packets + pub timeout: Duration, +} + +impl UdpClient { + /// Creates a new `UdpClient` bound to the default port and ipv6 address + /// + /// # Errors + /// + /// Will return error if unable to bind to any port or ip address. + /// + async fn bound_to_default_ipv4(timeout: Duration) -> Result { + let addr = SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0); + + Self::bound(addr, timeout).await + } + + /// Creates a new `UdpClient` bound to the default port and ipv6 address + /// + /// # Errors + /// + /// Will return error if unable to bind to any port or ip address. + /// + async fn bound_to_default_ipv6(timeout: Duration) -> Result { + let addr = SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), 0); + + Self::bound(addr, timeout).await + } + + /// Creates a new `UdpClient` connected to a Udp server + /// + /// # Errors + /// + /// Will return any errors present in the call stack + /// + pub async fn connected(remote_addr: SocketAddr, timeout: Duration) -> Result { + let client = if remote_addr.is_ipv4() { + Self::bound_to_default_ipv4(timeout).await? + } else { + Self::bound_to_default_ipv6(timeout).await? + }; + + client.connect(remote_addr).await?; + Ok(client) + } + + /// Creates a `[UdpClient]` bound to a Socket. + /// + /// # Panics + /// + /// Panics if unable to get the `local_addr` of the bound socket. + /// + /// # Errors + /// + /// This function will return an error if the binding takes to long + /// or if there is an underlying OS error. + pub async fn bound(addr: SocketAddr, timeout: Duration) -> Result { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "binding to socket: {addr:?} ..."); + + let socket = time::timeout(timeout, UdpSocket::bind(addr)) + .await + .map_err(|_| Error::TimeoutWhileBindingToSocket { addr })? + .map_err(|e| Error::UnableToBindToSocket { err: e.into(), addr })?; + + let addr = socket.local_addr().expect("it should get the local address"); + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "bound to socket: {addr:?}."); + + let udp_client = Self { + socket: Arc::new(socket), + timeout, + }; + + Ok(udp_client) + } + + /// # Errors + /// + /// Will return error if can't connect to the socket. + pub async fn connect(&self, remote_addr: SocketAddr) -> Result<(), Error> { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "connecting to remote: {remote_addr:?} ..."); + + let () = time::timeout(self.timeout, self.socket.connect(remote_addr)) + .await + .map_err(|_| Error::TimeoutWhileConnectingToRemote { remote_addr })? + .map_err(|e| Error::UnableToConnectToRemote { + err: e.into(), + remote_addr, + })?; + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "connected to remote: {remote_addr:?}."); + + Ok(()) + } + + /// # Errors + /// + /// Will return error if: + /// + /// - Can't write to the socket. + /// - Can't send data. + pub async fn send(&self, bytes: &[u8]) -> Result { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "sending {bytes:?} ..."); + + let () = time::timeout(self.timeout, self.socket.writable()) + .await + .map_err(|_| Error::TimeoutWaitForWriteableSocket)? + .map_err(|e| Error::UnableToGetWritableSocket { err: e.into() })?; + + let sent_bytes = time::timeout(self.timeout, self.socket.send(bytes)) + .await + .map_err(|_| Error::TimeoutWhileSendingData { data: bytes.to_vec() })? + .map_err(|e| Error::UnableToSendData { + err: e.into(), + data: bytes.to_vec(), + })?; + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "sent {sent_bytes} bytes to remote."); + + Ok(sent_bytes) + } + + /// # Errors + /// + /// Will return error if: + /// + /// - Can't read from the socket. + /// - Can't receive data. + /// + /// # Panics + /// + pub async fn receive(&self) -> Result, Error> { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "receiving ..."); + + let mut buffer = [0u8; MAX_PACKET_SIZE]; + + let () = time::timeout(self.timeout, self.socket.readable()) + .await + .map_err(|_| Error::TimeoutWaitForReadableSocket)? + .map_err(|e| Error::UnableToGetReadableSocket { err: e.into() })?; + + let received_bytes = time::timeout(self.timeout, self.socket.recv(&mut buffer)) + .await + .map_err(|_| Error::TimeoutWhileReceivingData)? + .map_err(|e| Error::UnableToReceivingData { err: e.into() })?; + + let mut received: Vec = buffer.to_vec(); + Vec::truncate(&mut received, received_bytes); + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "received {received_bytes} bytes: {received:?}"); + + Ok(received) + } +} + +#[allow(clippy::module_name_repetitions)] +#[derive(Debug)] +pub struct UdpTrackerClient { + pub client: UdpClient, +} + +impl UdpTrackerClient { + /// Creates a new `UdpTrackerClient` connected to a Udp Tracker server + /// + /// # Errors + /// + /// If unable to connect to the remote address. + /// + pub async fn new(remote_addr: SocketAddr, timeout: Duration) -> Result { + let client = UdpClient::connected(remote_addr, timeout).await?; + Ok(UdpTrackerClient { client }) + } + + /// # Errors + /// + /// Will return error if can't write request to bytes. + pub async fn send(&self, request: Request) -> Result { + tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "sending request {request:?} ..."); + + // Write request into a buffer + // todo: optimize the pre-allocated amount based upon request type. + let mut writer = Cursor::new(Vec::with_capacity(200)); + let () = request + .write_bytes(&mut writer) + .map_err(|e| Error::UnableToWriteDataFromRequest { err: e.into(), request })?; + + self.client.send(writer.get_ref()).await + } + + /// # Errors + /// + /// Will return error if can't create response from the received payload (bytes buffer). + pub async fn receive(&self) -> Result { + let response = self.client.receive().await?; + + tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "received {} bytes: {response:?}", response.len()); + + Response::parse_bytes(&response, true).map_err(|e| Error::UnableToParseResponse { err: e.into(), response }) + } +} + +/// Helper Function to Check if a UDP Service is Connectable +/// +/// # Panics +/// +/// It will return an error if unable to connect to the UDP service. +/// +/// # Errors +/// +pub async fn check(remote_addr: &SocketAddr) -> Result { + tracing::debug!("Checking Service (detail): {remote_addr:?}."); + + match UdpTrackerClient::new(*remote_addr, DEFAULT_TIMEOUT).await { + Ok(client) => { + let connect_request = ConnectRequest { + transaction_id: TransactionId(I32::new(123)), + }; + + // client.send() return usize, but doesn't use here + match client.send(connect_request.into()).await { + Ok(_) => (), + Err(e) => tracing::debug!("Error: {e:?}."), + }; + + let process = move |response| { + if matches!(response, Response::Connect(_connect_response)) { + Ok("Connected".to_string()) + } else { + Err("Did not Connect".to_string()) + } + }; + + let sleep = time::sleep(Duration::from_millis(2000)); + tokio::pin!(sleep); + + tokio::select! { + () = &mut sleep => { + Err("Timed Out".to_string()) + } + response = client.receive() => { + process(response.unwrap()) + } + } + } + Err(e) => Err(format!("{e:?}")), + } +} diff --git a/packages/tracker-client/src/udp/mod.rs b/packages/tracker-client/src/udp/mod.rs new file mode 100644 index 000000000..b9d5f34f6 --- /dev/null +++ b/packages/tracker-client/src/udp/mod.rs @@ -0,0 +1,68 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::Request; +use thiserror::Error; +use torrust_tracker_located_error::DynError; + +pub mod client; + +/// The maximum number of bytes in a UDP packet. +pub const MAX_PACKET_SIZE: usize = 1496; +/// A magic 64-bit integer constant defined in the protocol that is used to +/// identify the protocol. +pub const PROTOCOL_ID: i64 = 0x0417_2710_1980; + +#[derive(Debug, Clone, Error)] +pub enum Error { + #[error("Timeout while waiting for socket to bind: {addr:?}")] + TimeoutWhileBindingToSocket { addr: SocketAddr }, + + #[error("Failed to bind to socket: {addr:?}, with error: {err:?}")] + UnableToBindToSocket { err: Arc, addr: SocketAddr }, + + #[error("Timeout while waiting for connection to remote: {remote_addr:?}")] + TimeoutWhileConnectingToRemote { remote_addr: SocketAddr }, + + #[error("Failed to connect to remote: {remote_addr:?}, with error: {err:?}")] + UnableToConnectToRemote { + err: Arc, + remote_addr: SocketAddr, + }, + + #[error("Timeout while waiting for the socket to become writable.")] + TimeoutWaitForWriteableSocket, + + #[error("Failed to get writable socket: {err:?}")] + UnableToGetWritableSocket { err: Arc }, + + #[error("Timeout while trying to send data: {data:?}")] + TimeoutWhileSendingData { data: Vec }, + + #[error("Failed to send data: {data:?}, with error: {err:?}")] + UnableToSendData { err: Arc, data: Vec }, + + #[error("Timeout while waiting for the socket to become readable.")] + TimeoutWaitForReadableSocket, + + #[error("Failed to get readable socket: {err:?}")] + UnableToGetReadableSocket { err: Arc }, + + #[error("Timeout while trying to receive data.")] + TimeoutWhileReceivingData, + + #[error("Failed to receive data: {err:?}")] + UnableToReceivingData { err: Arc }, + + #[error("Failed to get data from request: {request:?}, with error: {err:?}")] + UnableToWriteDataFromRequest { err: Arc, request: Request }, + + #[error("Failed to parse response: {response:?}, with error: {err:?}")] + UnableToParseResponse { err: Arc, response: Vec }, +} + +impl From for DynError { + fn from(e: Error) -> Self { + Arc::new(Box::new(e)) + } +} From 31ac6cf215f61b17d3593a0f6d97713aa287f8d6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 1 Nov 2024 16:43:41 +0000 Subject: [PATCH 0510/1297] refactor: use extracted bittorrent-tracker-client --- src/bin/http_tracker_client.rs | 7 - src/bin/tracker_checker.rs | 7 - src/bin/udp_tracker_client.rs | 7 - src/console/clients/checker/app.rs | 120 -------- src/console/clients/checker/checks/health.rs | 77 ----- src/console/clients/checker/checks/http.rs | 104 ------- src/console/clients/checker/checks/mod.rs | 4 - src/console/clients/checker/checks/structs.rs | 12 - src/console/clients/checker/checks/udp.rs | 134 --------- src/console/clients/checker/config.rs | 282 ------------------ src/console/clients/checker/console.rs | 38 --- src/console/clients/checker/logger.rs | 72 ----- src/console/clients/checker/mod.rs | 7 - src/console/clients/checker/printer.rs | 9 - src/console/clients/checker/service.rs | 62 ---- src/console/clients/http/app.rs | 102 ------- src/console/clients/http/mod.rs | 36 --- src/console/clients/mod.rs | 4 - src/console/clients/udp/app.rs | 208 ------------- src/console/clients/udp/checker.rs | 177 ----------- src/console/clients/udp/mod.rs | 51 ---- src/console/clients/udp/responses/dto.rs | 128 -------- src/console/clients/udp/responses/json.rs | 25 -- src/console/clients/udp/responses/mod.rs | 2 - src/console/mod.rs | 1 - src/servers/udp/server/launcher.rs | 2 +- .../bit_torrent/tracker/http/client/mod.rs | 204 ------------- .../tracker/http/client/requests/announce.rs | 275 ----------------- .../tracker/http/client/requests/mod.rs | 2 - .../tracker/http/client/requests/scrape.rs | 172 ----------- .../tracker/http/client/responses/announce.rs | 126 -------- .../tracker/http/client/responses/error.rs | 7 - .../tracker/http/client/responses/mod.rs | 3 - .../tracker/http/client/responses/scrape.rs | 230 -------------- src/shared/bit_torrent/tracker/http/mod.rs | 26 -- src/shared/bit_torrent/tracker/mod.rs | 1 - src/shared/bit_torrent/tracker/udp/client.rs | 270 ----------------- src/shared/bit_torrent/tracker/udp/mod.rs | 64 +--- tests/servers/udp/contract.rs | 8 +- 39 files changed, 6 insertions(+), 3060 deletions(-) delete mode 100644 src/bin/http_tracker_client.rs delete mode 100644 src/bin/tracker_checker.rs delete mode 100644 src/bin/udp_tracker_client.rs delete mode 100644 src/console/clients/checker/app.rs delete mode 100644 src/console/clients/checker/checks/health.rs delete mode 100644 src/console/clients/checker/checks/http.rs delete mode 100644 src/console/clients/checker/checks/mod.rs delete mode 100644 src/console/clients/checker/checks/structs.rs delete mode 100644 src/console/clients/checker/checks/udp.rs delete mode 100644 src/console/clients/checker/config.rs delete mode 100644 src/console/clients/checker/console.rs delete mode 100644 src/console/clients/checker/logger.rs delete mode 100644 src/console/clients/checker/mod.rs delete mode 100644 src/console/clients/checker/printer.rs delete mode 100644 src/console/clients/checker/service.rs delete mode 100644 src/console/clients/http/app.rs delete mode 100644 src/console/clients/http/mod.rs delete mode 100644 src/console/clients/mod.rs delete mode 100644 src/console/clients/udp/app.rs delete mode 100644 src/console/clients/udp/checker.rs delete mode 100644 src/console/clients/udp/mod.rs delete mode 100644 src/console/clients/udp/responses/dto.rs delete mode 100644 src/console/clients/udp/responses/json.rs delete mode 100644 src/console/clients/udp/responses/mod.rs delete mode 100644 src/shared/bit_torrent/tracker/http/client/mod.rs delete mode 100644 src/shared/bit_torrent/tracker/http/client/requests/announce.rs delete mode 100644 src/shared/bit_torrent/tracker/http/client/requests/mod.rs delete mode 100644 src/shared/bit_torrent/tracker/http/client/requests/scrape.rs delete mode 100644 src/shared/bit_torrent/tracker/http/client/responses/announce.rs delete mode 100644 src/shared/bit_torrent/tracker/http/client/responses/error.rs delete mode 100644 src/shared/bit_torrent/tracker/http/client/responses/mod.rs delete mode 100644 src/shared/bit_torrent/tracker/http/client/responses/scrape.rs delete mode 100644 src/shared/bit_torrent/tracker/http/mod.rs delete mode 100644 src/shared/bit_torrent/tracker/udp/client.rs diff --git a/src/bin/http_tracker_client.rs b/src/bin/http_tracker_client.rs deleted file mode 100644 index 0de040549..000000000 --- a/src/bin/http_tracker_client.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Program to make request to HTTP trackers. -use torrust_tracker::console::clients::http::app; - -#[tokio::main] -async fn main() -> anyhow::Result<()> { - app::run().await -} diff --git a/src/bin/tracker_checker.rs b/src/bin/tracker_checker.rs deleted file mode 100644 index 87aeedeac..000000000 --- a/src/bin/tracker_checker.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Program to check running trackers. -use torrust_tracker::console::clients::checker::app; - -#[tokio::main] -async fn main() { - app::run().await.expect("Some checks fail"); -} diff --git a/src/bin/udp_tracker_client.rs b/src/bin/udp_tracker_client.rs deleted file mode 100644 index 909b296ca..000000000 --- a/src/bin/udp_tracker_client.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Program to make request to UDP trackers. -use torrust_tracker::console::clients::udp::app; - -#[tokio::main] -async fn main() -> anyhow::Result<()> { - app::run().await -} diff --git a/src/console/clients/checker/app.rs b/src/console/clients/checker/app.rs deleted file mode 100644 index 395f65df9..000000000 --- a/src/console/clients/checker/app.rs +++ /dev/null @@ -1,120 +0,0 @@ -//! Program to run checks against running trackers. -//! -//! Run providing a config file path: -//! -//! ```text -//! cargo run --bin tracker_checker -- --config-path "./share/default/config/tracker_checker.json" -//! TORRUST_CHECKER_CONFIG_PATH="./share/default/config/tracker_checker.json" cargo run --bin tracker_checker -//! ``` -//! -//! Run providing the configuration: -//! -//! ```text -//! TORRUST_CHECKER_CONFIG=$(cat "./share/default/config/tracker_checker.json") cargo run --bin tracker_checker -//! ``` -//! -//! Another real example to test the Torrust demo tracker: -//! -//! ```text -//! TORRUST_CHECKER_CONFIG='{ -//! "udp_trackers": ["144.126.245.19:6969"], -//! "http_trackers": ["https://tracker.torrust-demo.com"], -//! "health_checks": ["https://tracker.torrust-demo.com/api/health_check"] -//! }' cargo run --bin tracker_checker -//! ``` -//! -//! The output should be something like the following: -//! -//! ```json -//! { -//! "udp_trackers": [ -//! { -//! "url": "144.126.245.19:6969", -//! "status": { -//! "code": "ok", -//! "message": "" -//! } -//! } -//! ], -//! "http_trackers": [ -//! { -//! "url": "https://tracker.torrust-demo.com/", -//! "status": { -//! "code": "ok", -//! "message": "" -//! } -//! } -//! ], -//! "health_checks": [ -//! { -//! "url": "https://tracker.torrust-demo.com/api/health_check", -//! "status": { -//! "code": "ok", -//! "message": "" -//! } -//! } -//! ] -//! } -//! ``` -use std::path::PathBuf; -use std::sync::Arc; - -use anyhow::{Context, Result}; -use clap::Parser; -use tracing::level_filters::LevelFilter; - -use super::config::Configuration; -use super::console::Console; -use super::service::{CheckResult, Service}; -use crate::console::clients::checker::config::parse_from_json; - -#[derive(Parser, Debug)] -#[clap(author, version, about, long_about = None)] -struct Args { - /// Path to the JSON configuration file. - #[clap(short, long, env = "TORRUST_CHECKER_CONFIG_PATH")] - config_path: Option, - - /// Direct configuration content in JSON. - #[clap(env = "TORRUST_CHECKER_CONFIG", hide_env_values = true)] - config_content: Option, -} - -/// # Errors -/// -/// Will return an error if the configuration was not provided. -pub async fn run() -> Result> { - tracing_stdout_init(LevelFilter::INFO); - - 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.context("it should run the check tasks") -} - -fn tracing_stdout_init(filter: LevelFilter) { - tracing_subscriber::fmt().with_max_level(filter).init(); - tracing::debug!("Logging initialized"); -} - -fn setup_config(args: Args) -> Result { - match (args.config_path, args.config_content) { - (Some(config_path), _) => load_config_from_file(&config_path), - (_, Some(config_content)) => parse_from_json(&config_content).context("invalid config format"), - _ => Err(anyhow::anyhow!("no configuration provided")), - } -} - -fn load_config_from_file(path: &PathBuf) -> Result { - let file_content = std::fs::read_to_string(path).with_context(|| format!("can't read config file {path:?}"))?; - - parse_from_json(&file_content).context("invalid config format") -} diff --git a/src/console/clients/checker/checks/health.rs b/src/console/clients/checker/checks/health.rs deleted file mode 100644 index b1fb79148..000000000 --- a/src/console/clients/checker/checks/health.rs +++ /dev/null @@ -1,77 +0,0 @@ -use std::sync::Arc; -use std::time::Duration; - -use anyhow::Result; -use hyper::StatusCode; -use reqwest::{Client as HttpClient, Response}; -use serde::Serialize; -use thiserror::Error; -use url::Url; - -#[derive(Debug, Clone, Error, Serialize)] -#[serde(into = "String")] -pub enum Error { - #[error("Failed to Build a Http Client: {err:?}")] - ClientBuildingError { err: Arc }, - #[error("Heath check failed to get a response: {err:?}")] - ResponseError { err: Arc }, - #[error("Http check returned a non-success code: \"{code}\" with the response: \"{response:?}\"")] - UnsuccessfulResponse { code: StatusCode, response: Arc }, -} - -impl From for String { - fn from(value: Error) -> Self { - value.to_string() - } -} - -#[derive(Debug, Clone, Serialize)] -pub struct Checks { - url: Url, - result: Result, -} - -pub async fn run(health_checks: Vec, timeout: Duration) -> Vec> { - let mut results = Vec::default(); - - tracing::debug!("Health checks ..."); - - for url in health_checks { - let result = match run_health_check(url.clone(), timeout).await { - Ok(response) => Ok(response.status().to_string()), - Err(err) => Err(err), - }; - - let check = Checks { url, result }; - - if check.result.is_err() { - results.push(Err(check)); - } else { - results.push(Ok(check)); - } - } - - results -} - -async fn run_health_check(url: Url, timeout: Duration) -> Result { - let client = HttpClient::builder() - .timeout(timeout) - .build() - .map_err(|e| Error::ClientBuildingError { err: e.into() })?; - - let response = client - .get(url.clone()) - .send() - .await - .map_err(|e| Error::ResponseError { err: e.into() })?; - - if response.status().is_success() { - Ok(response) - } else { - Err(Error::UnsuccessfulResponse { - code: response.status(), - response: response.into(), - }) - } -} diff --git a/src/console/clients/checker/checks/http.rs b/src/console/clients/checker/checks/http.rs deleted file mode 100644 index b64297bed..000000000 --- a/src/console/clients/checker/checks/http.rs +++ /dev/null @@ -1,104 +0,0 @@ -use std::str::FromStr as _; -use std::time::Duration; - -use bittorrent_primitives::info_hash::InfoHash; -use serde::Serialize; -use url::Url; - -use crate::console::clients::http::Error; -use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; -use crate::shared::bit_torrent::tracker::http::client::responses::scrape; -use crate::shared::bit_torrent::tracker::http::client::{requests, Client}; - -#[derive(Debug, Clone, Serialize)] -pub struct Checks { - url: Url, - results: Vec<(Check, Result<(), Error>)>, -} - -#[derive(Debug, Clone, Serialize)] -pub enum Check { - Announce, - Scrape, -} - -pub async fn run(http_trackers: Vec, timeout: Duration) -> Vec> { - let mut results = Vec::default(); - - tracing::debug!("HTTP trackers ..."); - - for ref url in http_trackers { - let mut base_url = url.clone(); - base_url.set_path(""); - - let mut checks = Checks { - url: url.clone(), - results: Vec::default(), - }; - - // Announce - { - let check = check_http_announce(&base_url, timeout).await.map(|_| ()); - - checks.results.push((Check::Announce, check)); - } - - // Scrape - { - let check = check_http_scrape(&base_url, timeout).await.map(|_| ()); - - checks.results.push((Check::Scrape, check)); - } - - if checks.results.iter().any(|f| f.1.is_err()) { - results.push(Err(checks)); - } else { - results.push(Ok(checks)); - } - } - - results -} - -async fn check_http_announce(url: &Url, timeout: Duration) -> Result { - let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // # DevSkim: ignore DS173237 - let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); - - let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; - - let response = client - .announce( - &requests::announce::QueryBuilder::with_default_values() - .with_info_hash(&info_hash) - .query(), - ) - .await - .map_err(|err| Error::HttpClientError { err })?; - - let response = response.bytes().await.map_err(|e| Error::ResponseError { err: e.into() })?; - - let response = serde_bencode::from_bytes::(&response).map_err(|e| Error::ParseBencodeError { - data: response, - err: e.into(), - })?; - - Ok(response) -} - -async fn check_http_scrape(url: &Url, timeout: Duration) -> Result { - let info_hashes: Vec = vec!["9c38422213e30bff212b30c360d26f9a02136422".to_string()]; // # DevSkim: ignore DS173237 - let query = requests::scrape::Query::try_from(info_hashes).expect("a valid array of info-hashes is required"); - - let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; - - let response = client.scrape(&query).await.map_err(|err| Error::HttpClientError { err })?; - - let response = response.bytes().await.map_err(|e| Error::ResponseError { err: e.into() })?; - - let response = scrape::Response::try_from_bencoded(&response).map_err(|e| Error::BencodeParseError { - data: response, - err: e.into(), - })?; - - Ok(response) -} diff --git a/src/console/clients/checker/checks/mod.rs b/src/console/clients/checker/checks/mod.rs deleted file mode 100644 index f8b03f749..000000000 --- a/src/console/clients/checker/checks/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -pub mod health; -pub mod http; -pub mod structs; -pub mod udp; diff --git a/src/console/clients/checker/checks/structs.rs b/src/console/clients/checker/checks/structs.rs deleted file mode 100644 index d28e20c04..000000000 --- a/src/console/clients/checker/checks/structs.rs +++ /dev/null @@ -1,12 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize)] -pub struct Status { - pub code: String, - pub message: String, -} -#[derive(Serialize, Deserialize)] -pub struct CheckerOutput { - pub url: String, - pub status: Status, -} diff --git a/src/console/clients/checker/checks/udp.rs b/src/console/clients/checker/checks/udp.rs deleted file mode 100644 index 21bdcd1b7..000000000 --- a/src/console/clients/checker/checks/udp.rs +++ /dev/null @@ -1,134 +0,0 @@ -use std::net::SocketAddr; -use std::time::Duration; - -use aquatic_udp_protocol::TransactionId; -use hex_literal::hex; -use serde::Serialize; -use url::Url; - -use crate::console::clients::udp::checker::Client; -use crate::console::clients::udp::Error; - -#[derive(Debug, Clone, Serialize)] -pub struct Checks { - remote_addr: SocketAddr, - results: Vec<(Check, Result<(), Error>)>, -} - -#[derive(Debug, Clone, Serialize)] -pub enum Check { - Setup, - Connect, - Announce, - Scrape, -} - -#[allow(clippy::missing_panics_doc)] -pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec> { - let mut results = Vec::default(); - - tracing::debug!("UDP trackers ..."); - - let info_hash = aquatic_udp_protocol::InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237 - - for remote_url in udp_trackers { - let remote_addr = resolve_socket_addr(&remote_url); - - let mut checks = Checks { - remote_addr, - results: Vec::default(), - }; - - tracing::debug!("UDP tracker: {:?}", remote_url); - - // Setup - let client = match Client::new(remote_addr, timeout).await { - Ok(client) => { - checks.results.push((Check::Setup, Ok(()))); - client - } - Err(err) => { - checks.results.push((Check::Setup, Err(err))); - results.push(Err(checks)); - continue; - } - }; - - let transaction_id = TransactionId::new(1); - - // Connect Remote - let connection_id = match client.send_connection_request(transaction_id).await { - Ok(connection_id) => { - checks.results.push((Check::Connect, Ok(()))); - connection_id - } - Err(err) => { - checks.results.push((Check::Connect, Err(err))); - results.push(Err(checks)); - continue; - } - }; - - // Announce - { - let check = client - .send_announce_request(transaction_id, connection_id, info_hash.into()) - .await - .map(|_| ()); - - checks.results.push((Check::Announce, check)); - } - - // Scrape - { - let check = client - .send_scrape_request(connection_id, transaction_id, &[info_hash.into()]) - .await - .map(|_| ()); - - checks.results.push((Check::Scrape, check)); - } - - if checks.results.iter().any(|f| f.1.is_err()) { - results.push(Err(checks)); - } else { - results.push(Ok(checks)); - } - } - - results -} - -fn resolve_socket_addr(url: &Url) -> SocketAddr { - let socket_addr = url.socket_addrs(|| None).unwrap(); - *socket_addr.first().unwrap() -} - -#[cfg(test)] -mod tests { - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - - use url::Url; - - use crate::console::clients::checker::checks::udp::resolve_socket_addr; - - #[test] - fn it_should_resolve_the_socket_address_for_udp_scheme_urls_containing_a_domain() { - let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); - - assert!( - socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) - || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) - ); - } - - #[test] - fn it_should_resolve_the_socket_address_for_udp_scheme_urls_containing_an_ip() { - let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); - - assert!( - socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) - || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) - ); - } -} diff --git a/src/console/clients/checker/config.rs b/src/console/clients/checker/config.rs deleted file mode 100644 index 154dcae85..000000000 --- a/src/console/clients/checker/config.rs +++ /dev/null @@ -1,282 +0,0 @@ -use std::error::Error; -use std::fmt; - -use reqwest::Url as ServiceUrl; -use serde::Deserialize; - -/// It parses the configuration from a JSON format. -/// -/// # Errors -/// -/// Will return an error if the configuration is not valid. -/// -/// # Panics -/// -/// Will panic if unable to read the configuration file. -pub fn parse_from_json(json: &str) -> Result { - let plain_config: PlainConfiguration = serde_json::from_str(json).map_err(ConfigurationError::JsonParseError)?; - Configuration::try_from(plain_config) -} - -/// DTO for the configuration to serialize/deserialize configuration. -/// -/// Configuration does not need to be valid. -#[derive(Deserialize)] -struct PlainConfiguration { - pub udp_trackers: Vec, - pub http_trackers: Vec, - pub health_checks: Vec, -} - -/// Validated configuration -pub struct Configuration { - pub udp_trackers: Vec, - pub http_trackers: Vec, - pub health_checks: Vec, -} - -#[derive(Debug)] -pub enum ConfigurationError { - JsonParseError(serde_json::Error), - InvalidUdpAddress(std::net::AddrParseError), - InvalidUrl(url::ParseError), -} - -impl Error for ConfigurationError {} - -impl fmt::Display for ConfigurationError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ConfigurationError::JsonParseError(e) => write!(f, "JSON parse error: {e}"), - ConfigurationError::InvalidUdpAddress(e) => write!(f, "Invalid UDP address: {e}"), - ConfigurationError::InvalidUrl(e) => write!(f, "Invalid URL: {e}"), - } - } -} - -impl TryFrom for Configuration { - type Error = ConfigurationError; - - fn try_from(plain_config: PlainConfiguration) -> Result { - let udp_trackers = plain_config - .udp_trackers - .into_iter() - .map(|s| if s.starts_with("udp://") { s } else { format!("udp://{s}") }) - .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) - .collect::, _>>()?; - - let http_trackers = plain_config - .http_trackers - .into_iter() - .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) - .collect::, _>>()?; - - let health_checks = plain_config - .health_checks - .into_iter() - .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) - .collect::, _>>()?; - - Ok(Configuration { - udp_trackers, - http_trackers, - health_checks, - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn configuration_should_be_build_from_plain_serializable_configuration() { - let dto = PlainConfiguration { - udp_trackers: vec!["udp://127.0.0.1:8080".to_string()], - http_trackers: vec!["http://127.0.0.1:8080".to_string()], - health_checks: vec!["http://127.0.0.1:8080/health".to_string()], - }; - - let config = Configuration::try_from(dto).expect("A valid configuration"); - - assert_eq!(config.udp_trackers, vec![ServiceUrl::parse("udp://127.0.0.1:8080").unwrap()]); - - assert_eq!( - config.http_trackers, - vec![ServiceUrl::parse("http://127.0.0.1:8080").unwrap()] - ); - - assert_eq!( - config.health_checks, - vec![ServiceUrl::parse("http://127.0.0.1:8080/health").unwrap()] - ); - } - - mod building_configuration_from_plain_configuration_for { - - mod udp_trackers { - use crate::console::clients::checker::config::{Configuration, PlainConfiguration, ServiceUrl}; - - /* The plain configuration should allow UDP URLs with: - - - IP or domain. - - With or without scheme. - - With or without `announce` suffix. - - With or without `/` at the end of the authority section (with empty path). - - For example: - - 127.0.0.1:6969 - 127.0.0.1:6969/ - 127.0.0.1:6969/announce - - localhost:6969 - localhost:6969/ - localhost:6969/announce - - udp://127.0.0.1:6969 - udp://127.0.0.1:6969/ - udp://127.0.0.1:6969/announce - - udp://localhost:6969 - udp://localhost:6969/ - udp://localhost:6969/announce - - */ - - #[test] - fn it_should_fail_when_a_tracker_udp_url_is_invalid() { - let plain_config = PlainConfiguration { - udp_trackers: vec!["invalid URL".to_string()], - http_trackers: vec![], - health_checks: vec![], - }; - - assert!(Configuration::try_from(plain_config).is_err()); - } - - #[test] - fn it_should_add_the_udp_scheme_to_the_udp_url_when_it_is_missing() { - let plain_config = PlainConfiguration { - udp_trackers: vec!["127.0.0.1:6969".to_string()], - http_trackers: vec![], - health_checks: vec![], - }; - - let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); - - assert_eq!(config.udp_trackers[0], "udp://127.0.0.1:6969".parse::().unwrap()); - } - - #[test] - fn it_should_allow_using_domains() { - let plain_config = PlainConfiguration { - udp_trackers: vec!["udp://localhost:6969".to_string()], - http_trackers: vec![], - health_checks: vec![], - }; - - let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); - - assert_eq!(config.udp_trackers[0], "udp://localhost:6969".parse::().unwrap()); - } - - #[test] - fn it_should_allow_the_url_to_have_an_empty_path() { - let plain_config = PlainConfiguration { - udp_trackers: vec!["127.0.0.1:6969/".to_string()], - http_trackers: vec![], - health_checks: vec![], - }; - - let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); - - assert_eq!(config.udp_trackers[0], "udp://127.0.0.1:6969/".parse::().unwrap()); - } - - #[test] - fn it_should_allow_the_url_to_contain_a_path() { - // This is the common format for UDP tracker URLs: - // udp://domain.com:6969/announce - - let plain_config = PlainConfiguration { - udp_trackers: vec!["127.0.0.1:6969/announce".to_string()], - http_trackers: vec![], - health_checks: vec![], - }; - - let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); - - assert_eq!( - config.udp_trackers[0], - "udp://127.0.0.1:6969/announce".parse::().unwrap() - ); - } - } - - mod http_trackers { - use crate::console::clients::checker::config::{Configuration, PlainConfiguration, ServiceUrl}; - - #[test] - fn it_should_fail_when_a_tracker_http_url_is_invalid() { - let plain_config = PlainConfiguration { - udp_trackers: vec![], - http_trackers: vec!["invalid URL".to_string()], - health_checks: vec![], - }; - - assert!(Configuration::try_from(plain_config).is_err()); - } - - #[test] - fn it_should_allow_the_url_to_contain_a_path() { - // This is the common format for HTTP tracker URLs: - // http://domain.com:7070/announce - - let plain_config = PlainConfiguration { - udp_trackers: vec![], - http_trackers: vec!["http://127.0.0.1:7070/announce".to_string()], - health_checks: vec![], - }; - - let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); - - assert_eq!( - config.http_trackers[0], - "http://127.0.0.1:7070/announce".parse::().unwrap() - ); - } - - #[test] - fn it_should_allow_the_url_to_contain_an_empty_path() { - let plain_config = PlainConfiguration { - udp_trackers: vec![], - http_trackers: vec!["http://127.0.0.1:7070/".to_string()], - health_checks: vec![], - }; - - let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); - - assert_eq!( - config.http_trackers[0], - "http://127.0.0.1:7070/".parse::().unwrap() - ); - } - } - - mod health_checks { - use crate::console::clients::checker::config::{Configuration, PlainConfiguration}; - - #[test] - fn it_should_fail_when_a_health_check_http_url_is_invalid() { - let plain_config = PlainConfiguration { - udp_trackers: vec![], - http_trackers: vec![], - health_checks: vec!["invalid URL".to_string()], - }; - - assert!(Configuration::try_from(plain_config).is_err()); - } - } - } -} diff --git a/src/console/clients/checker/console.rs b/src/console/clients/checker/console.rs deleted file mode 100644 index b55c559fc..000000000 --- a/src/console/clients/checker/console.rs +++ /dev/null @@ -1,38 +0,0 @@ -use super::printer::{Printer, CLEAR_SCREEN}; - -pub struct Console {} - -impl Default for Console { - fn default() -> Self { - Self::new() - } -} - -impl Console { - #[must_use] - pub fn new() -> Self { - Self {} - } -} - -impl Printer for Console { - fn clear(&self) { - self.print(CLEAR_SCREEN); - } - - fn print(&self, output: &str) { - print!("{}", &output); - } - - fn eprint(&self, output: &str) { - eprint!("{}", &output); - } - - fn println(&self, output: &str) { - println!("{}", &output); - } - - fn eprintln(&self, output: &str) { - eprintln!("{}", &output); - } -} diff --git a/src/console/clients/checker/logger.rs b/src/console/clients/checker/logger.rs deleted file mode 100644 index 50e97189f..000000000 --- a/src/console/clients/checker/logger.rs +++ /dev/null @@ -1,72 +0,0 @@ -use std::cell::RefCell; - -use super::printer::{Printer, CLEAR_SCREEN}; - -pub struct Logger { - output: RefCell, -} - -impl Default for Logger { - fn default() -> Self { - Self::new() - } -} - -impl Logger { - #[must_use] - pub fn new() -> Self { - Self { - output: RefCell::new(String::new()), - } - } - - pub fn log(&self) -> String { - self.output.borrow().clone() - } -} - -impl Printer for Logger { - fn clear(&self) { - self.print(CLEAR_SCREEN); - } - - fn print(&self, output: &str) { - *self.output.borrow_mut() = format!("{}{}", self.output.borrow(), &output); - } - - fn eprint(&self, output: &str) { - *self.output.borrow_mut() = format!("{}{}", self.output.borrow(), &output); - } - - fn println(&self, output: &str) { - self.print(&format!("{}/n", &output)); - } - - fn eprintln(&self, output: &str) { - self.eprint(&format!("{}/n", &output)); - } -} - -#[cfg(test)] -mod tests { - use crate::console::clients::checker::logger::Logger; - use crate::console::clients::checker::printer::{Printer, CLEAR_SCREEN}; - - #[test] - fn should_capture_the_clear_screen_command() { - let console_logger = Logger::new(); - - console_logger.clear(); - - assert_eq!(CLEAR_SCREEN, console_logger.log()); - } - - #[test] - fn should_capture_the_print_command_output() { - let console_logger = Logger::new(); - - console_logger.print("OUTPUT"); - - assert_eq!("OUTPUT", console_logger.log()); - } -} diff --git a/src/console/clients/checker/mod.rs b/src/console/clients/checker/mod.rs deleted file mode 100644 index d26a4a686..000000000 --- a/src/console/clients/checker/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub mod app; -pub mod checks; -pub mod config; -pub mod console; -pub mod logger; -pub mod printer; -pub mod service; diff --git a/src/console/clients/checker/printer.rs b/src/console/clients/checker/printer.rs deleted file mode 100644 index d590dfedb..000000000 --- a/src/console/clients/checker/printer.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub const CLEAR_SCREEN: &str = "\x1B[2J\x1B[1;1H"; - -pub trait Printer { - fn clear(&self); - fn print(&self, output: &str); - fn eprint(&self, output: &str); - fn println(&self, output: &str); - fn eprintln(&self, output: &str); -} diff --git a/src/console/clients/checker/service.rs b/src/console/clients/checker/service.rs deleted file mode 100644 index acd312d8c..000000000 --- a/src/console/clients/checker/service.rs +++ /dev/null @@ -1,62 +0,0 @@ -use std::sync::Arc; - -use futures::FutureExt as _; -use serde::Serialize; -use tokio::task::{JoinError, JoinSet}; -use torrust_tracker_configuration::DEFAULT_TIMEOUT; - -use super::checks::{health, http, udp}; -use super::config::Configuration; -use super::console::Console; -use crate::console::clients::checker::printer::Printer; - -pub struct Service { - pub(crate) config: Arc, - pub(crate) console: Console, -} - -#[derive(Debug, Clone, Serialize)] -pub enum CheckResult { - Udp(Result), - Http(Result), - Health(Result), -} - -impl Service { - /// # Errors - /// - /// It will return an error if some of the tests panic or otherwise fail to run. - /// On success it will return a vector of `Ok(())` of [`CheckResult`]. - /// - /// # Panics - /// - /// It would panic if `serde_json` produces invalid json for the `to_string_pretty` function. - pub async fn run_checks(self) -> Result, JoinError> { - tracing::info!("Running checks for trackers ..."); - - let mut check_results = Vec::default(); - - let mut checks = JoinSet::new(); - checks.spawn( - udp::run(self.config.udp_trackers.clone(), DEFAULT_TIMEOUT).map(|mut f| f.drain(..).map(CheckResult::Udp).collect()), - ); - checks.spawn( - http::run(self.config.http_trackers.clone(), DEFAULT_TIMEOUT) - .map(|mut f| f.drain(..).map(CheckResult::Http).collect()), - ); - checks.spawn( - health::run(self.config.health_checks.clone(), DEFAULT_TIMEOUT) - .map(|mut f| f.drain(..).map(CheckResult::Health).collect()), - ); - - while let Some(results) = checks.join_next().await { - check_results.append(&mut results?); - } - - let json_output = serde_json::json!(check_results); - self.console - .println(&serde_json::to_string_pretty(&json_output).expect("it should consume valid json")); - - Ok(check_results) - } -} diff --git a/src/console/clients/http/app.rs b/src/console/clients/http/app.rs deleted file mode 100644 index 6730c027d..000000000 --- a/src/console/clients/http/app.rs +++ /dev/null @@ -1,102 +0,0 @@ -//! HTTP Tracker client: -//! -//! Examples: -//! -//! `Announce` request: -//! -//! ```text -//! cargo run --bin http_tracker_client announce http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -//! -//! `Scrape` request: -//! -//! ```text -//! cargo run --bin http_tracker_client scrape http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -use std::str::FromStr; -use std::time::Duration; - -use anyhow::Context; -use bittorrent_primitives::info_hash::InfoHash; -use clap::{Parser, Subcommand}; -use reqwest::Url; -use torrust_tracker_configuration::DEFAULT_TIMEOUT; - -use crate::shared::bit_torrent::tracker::http::client::requests::announce::QueryBuilder; -use crate::shared::bit_torrent::tracker::http::client::responses::announce::Announce; -use crate::shared::bit_torrent::tracker::http::client::responses::scrape; -use crate::shared::bit_torrent::tracker::http::client::{requests, Client}; - -#[derive(Parser, Debug)] -#[command(author, version, about, long_about = None)] -struct Args { - #[command(subcommand)] - command: Command, -} - -#[derive(Subcommand, Debug)] -enum Command { - Announce { tracker_url: String, info_hash: String }, - Scrape { tracker_url: String, info_hashes: Vec }, -} - -/// # Errors -/// -/// Will return an error if the command fails. -pub async fn run() -> anyhow::Result<()> { - let args = Args::parse(); - - match args.command { - Command::Announce { tracker_url, info_hash } => { - announce_command(tracker_url, info_hash, DEFAULT_TIMEOUT).await?; - } - Command::Scrape { - tracker_url, - info_hashes, - } => { - scrape_command(&tracker_url, &info_hashes, DEFAULT_TIMEOUT).await?; - } - } - - Ok(()) -} - -async fn announce_command(tracker_url: String, info_hash: String, timeout: Duration) -> anyhow::Result<()> { - let base_url = Url::parse(&tracker_url).context("failed to parse HTTP tracker base URL")?; - let info_hash = - InfoHash::from_str(&info_hash).expect("Invalid infohash. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); - - let response = Client::new(base_url, timeout)? - .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) - .await?; - - let body = response.bytes().await?; - - let announce_response: Announce = serde_bencode::from_bytes(&body) - .unwrap_or_else(|_| panic!("response body should be a valid announce response, got: \"{:#?}\"", &body)); - - let json = serde_json::to_string(&announce_response).context("failed to serialize scrape response into JSON")?; - - println!("{json}"); - - Ok(()) -} - -async fn scrape_command(tracker_url: &str, info_hashes: &[String], timeout: Duration) -> anyhow::Result<()> { - let base_url = Url::parse(tracker_url).context("failed to parse HTTP tracker base URL")?; - - let query = requests::scrape::Query::try_from(info_hashes).context("failed to parse infohashes")?; - - let response = Client::new(base_url, timeout)?.scrape(&query).await?; - - let body = response.bytes().await?; - - let scrape_response = scrape::Response::try_from_bencoded(&body) - .unwrap_or_else(|_| panic!("response body should be a valid scrape response, got: \"{:#?}\"", &body)); - - let json = serde_json::to_string(&scrape_response).context("failed to serialize scrape response into JSON")?; - - println!("{json}"); - - Ok(()) -} diff --git a/src/console/clients/http/mod.rs b/src/console/clients/http/mod.rs deleted file mode 100644 index eaa71957f..000000000 --- a/src/console/clients/http/mod.rs +++ /dev/null @@ -1,36 +0,0 @@ -use std::sync::Arc; - -use serde::Serialize; -use thiserror::Error; - -use crate::shared::bit_torrent::tracker::http::client::responses::scrape::BencodeParseError; - -pub mod app; - -#[derive(Debug, Clone, Error, Serialize)] -#[serde(into = "String")] -pub enum Error { - #[error("Http request did not receive a response within the timeout: {err:?}")] - HttpClientError { - err: crate::shared::bit_torrent::tracker::http::client::Error, - }, - #[error("Http failed to get a response at all: {err:?}")] - ResponseError { err: Arc }, - #[error("Failed to deserialize the bencoded response data with the error: \"{err:?}\"")] - ParseBencodeError { - data: hyper::body::Bytes, - err: Arc, - }, - - #[error("Failed to deserialize the bencoded response data with the error: \"{err:?}\"")] - BencodeParseError { - data: hyper::body::Bytes, - err: Arc, - }, -} - -impl From for String { - fn from(value: Error) -> Self { - value.to_string() - } -} diff --git a/src/console/clients/mod.rs b/src/console/clients/mod.rs deleted file mode 100644 index 8492f8ba5..000000000 --- a/src/console/clients/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! Console clients. -pub mod checker; -pub mod http; -pub mod udp; diff --git a/src/console/clients/udp/app.rs b/src/console/clients/udp/app.rs deleted file mode 100644 index a2736c365..000000000 --- a/src/console/clients/udp/app.rs +++ /dev/null @@ -1,208 +0,0 @@ -//! UDP Tracker client: -//! -//! Examples: -//! -//! Announce request: -//! -//! ```text -//! cargo run --bin udp_tracker_client announce 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -//! -//! Announce response: -//! -//! ```json -//! { -//! "transaction_id": -888840697 -//! "announce_interval": 120, -//! "leechers": 0, -//! "seeders": 1, -//! "peers": [ -//! "123.123.123.123:51289" -//! ], -//! } -//! ``` -//! -//! Scrape request: -//! -//! ```text -//! cargo run --bin udp_tracker_client scrape 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -//! -//! Scrape response: -//! -//! ```json -//! { -//! "transaction_id": -888840697, -//! "torrent_stats": [ -//! { -//! "completed": 0, -//! "leechers": 0, -//! "seeders": 0 -//! }, -//! { -//! "completed": 0, -//! "leechers": 0, -//! "seeders": 0 -//! } -//! ] -//! } -//! ``` -//! -//! You can use an URL with instead of the socket address. For example: -//! -//! ```text -//! cargo run --bin udp_tracker_client scrape udp://localhost:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! cargo run --bin udp_tracker_client scrape udp://localhost:6969/scrape 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -//! -//! The protocol (`udp://`) in the URL is mandatory. The path (`\scrape`) is optional. It always uses `\scrape`. -use std::net::{SocketAddr, ToSocketAddrs}; -use std::str::FromStr; - -use anyhow::Context; -use aquatic_udp_protocol::{Response, TransactionId}; -use bittorrent_primitives::info_hash::InfoHash as TorrustInfoHash; -use clap::{Parser, Subcommand}; -use torrust_tracker_configuration::DEFAULT_TIMEOUT; -use tracing::level_filters::LevelFilter; -use url::Url; - -use super::Error; -use crate::console::clients::udp::checker; -use crate::console::clients::udp::responses::dto::SerializableResponse; -use crate::console::clients::udp::responses::json::ToJson; - -const RANDOM_TRANSACTION_ID: i32 = -888_840_697; - -#[derive(Parser, Debug)] -#[command(author, version, about, long_about = None)] -struct Args { - #[command(subcommand)] - command: Command, -} - -#[derive(Subcommand, Debug)] -enum Command { - Announce { - #[arg(value_parser = parse_socket_addr)] - tracker_socket_addr: SocketAddr, - #[arg(value_parser = parse_info_hash)] - info_hash: TorrustInfoHash, - }, - Scrape { - #[arg(value_parser = parse_socket_addr)] - tracker_socket_addr: SocketAddr, - #[arg(value_parser = parse_info_hash, num_args = 1..=74, value_delimiter = ' ')] - info_hashes: Vec, - }, -} - -/// # Errors -/// -/// Will return an error if the command fails. -/// -/// -pub async fn run() -> anyhow::Result<()> { - tracing_stdout_init(LevelFilter::INFO); - - let args = Args::parse(); - - let response = match args.command { - Command::Announce { - tracker_socket_addr: remote_addr, - info_hash, - } => handle_announce(remote_addr, &info_hash).await?, - Command::Scrape { - tracker_socket_addr: remote_addr, - info_hashes, - } => handle_scrape(remote_addr, &info_hashes).await?, - }; - - let response: SerializableResponse = response.into(); - let response_json = response.to_json_string()?; - - print!("{response_json}"); - - Ok(()) -} - -fn tracing_stdout_init(filter: LevelFilter) { - tracing_subscriber::fmt().with_max_level(filter).init(); - tracing::debug!("Logging initialized"); -} - -async fn handle_announce(remote_addr: SocketAddr, info_hash: &TorrustInfoHash) -> Result { - let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); - - let client = checker::Client::new(remote_addr, DEFAULT_TIMEOUT).await?; - - let connection_id = client.send_connection_request(transaction_id).await?; - - client.send_announce_request(transaction_id, connection_id, *info_hash).await -} - -async fn handle_scrape(remote_addr: SocketAddr, info_hashes: &[TorrustInfoHash]) -> Result { - let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); - - let client = checker::Client::new(remote_addr, DEFAULT_TIMEOUT).await?; - - let connection_id = client.send_connection_request(transaction_id).await?; - - client.send_scrape_request(connection_id, transaction_id, info_hashes).await -} - -fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { - tracing::debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); - - // Check if the address is a valid URL. If so, extract the host and port. - let resolved_addr = if let Ok(url) = Url::parse(tracker_socket_addr_str) { - tracing::debug!("Tracker socket address URL: {url:?}"); - - let host = url - .host_str() - .with_context(|| format!("invalid host in URL: `{tracker_socket_addr_str}`"))? - .to_owned(); - - let port = url - .port() - .with_context(|| format!("port not found in URL: `{tracker_socket_addr_str}`"))? - .to_owned(); - - (host, port) - } else { - // If not a URL, assume it's a host:port pair. - - let parts: Vec<&str> = tracker_socket_addr_str.split(':').collect(); - - if parts.len() != 2 { - return Err(anyhow::anyhow!( - "invalid address format: `{}`. Expected format is host:port", - tracker_socket_addr_str - )); - } - - let host = parts[0].to_owned(); - - let port = parts[1] - .parse::() - .with_context(|| format!("invalid port: `{}`", parts[1]))? - .to_owned(); - - (host, port) - }; - - tracing::debug!("Resolved address: {resolved_addr:#?}"); - - // Perform DNS resolution. - let socket_addrs: Vec<_> = resolved_addr.to_socket_addrs()?.collect(); - if socket_addrs.is_empty() { - Err(anyhow::anyhow!("DNS resolution failed for `{}`", tracker_socket_addr_str)) - } else { - Ok(socket_addrs[0]) - } -} - -fn parse_info_hash(info_hash_str: &str) -> anyhow::Result { - TorrustInfoHash::from_str(info_hash_str) - .map_err(|e| anyhow::Error::msg(format!("failed to parse info-hash `{info_hash_str}`: {e:?}"))) -} diff --git a/src/console/clients/udp/checker.rs b/src/console/clients/udp/checker.rs deleted file mode 100644 index 14e94c132..000000000 --- a/src/console/clients/udp/checker.rs +++ /dev/null @@ -1,177 +0,0 @@ -use std::net::{Ipv4Addr, SocketAddr}; -use std::num::NonZeroU16; -use std::time::Duration; - -use aquatic_udp_protocol::common::InfoHash; -use aquatic_udp_protocol::{ - AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, - PeerId, PeerKey, Port, Response, ScrapeRequest, TransactionId, -}; -use bittorrent_primitives::info_hash::InfoHash as TorrustInfoHash; - -use super::Error; -use crate::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; - -/// A UDP Tracker client to make test requests (checks). -#[derive(Debug)] -pub struct Client { - client: UdpTrackerClient, -} - -impl Client { - /// Creates a new `[Client]` for checking a UDP Tracker Service - /// - /// # Errors - /// - /// It will error if unable to bind and connect to the udp remote address. - /// - pub async fn new(remote_addr: SocketAddr, timeout: Duration) -> Result { - let client = UdpTrackerClient::new(remote_addr, timeout) - .await - .map_err(|err| Error::UnableToBindAndConnect { remote_addr, err })?; - - Ok(Self { client }) - } - - /// Returns the local addr of this [`Client`]. - /// - /// # Errors - /// - /// This function will return an error if the socket is somehow not bound. - pub fn local_addr(&self) -> std::io::Result { - self.client.client.socket.local_addr() - } - - /// Sends a connection request to the UDP Tracker server. - /// - /// # Errors - /// - /// Will return and error if - /// - /// - It can't connect to the remote UDP socket. - /// - It can't make a connection request successfully to the remote UDP - /// server (after successfully connecting to the remote UDP socket). - /// - /// # Panics - /// - /// Will panic if it receives an unexpected response. - pub async fn send_connection_request(&self, transaction_id: TransactionId) -> Result { - tracing::debug!("Sending connection request with transaction id: {transaction_id:#?}"); - - let connect_request = ConnectRequest { transaction_id }; - - let _ = self - .client - .send(connect_request.into()) - .await - .map_err(|err| Error::UnableToSendConnectionRequest { err })?; - - let response = self - .client - .receive() - .await - .map_err(|err| Error::UnableToReceiveConnectResponse { err })?; - - match response { - Response::Connect(connect_response) => Ok(connect_response.connection_id), - _ => Err(Error::UnexpectedConnectionResponse { response }), - } - } - - /// Sends an announce request to the UDP Tracker server. - /// - /// # Errors - /// - /// Will return and error if the client is not connected. You have to connect - /// before calling this function. - /// - /// # Panics - /// - /// It will panic if the `local_address` has a zero port. - pub async fn send_announce_request( - &self, - transaction_id: TransactionId, - connection_id: ConnectionId, - info_hash: TorrustInfoHash, - ) -> Result { - tracing::debug!("Sending announce request with transaction id: {transaction_id:#?}"); - - let port = NonZeroU16::new( - self.client - .client - .socket - .local_addr() - .expect("it should get the local address") - .port(), - ) - .expect("it should no be zero"); - - let announce_request = AnnounceRequest { - connection_id, - action_placeholder: AnnounceActionPlaceholder::default(), - transaction_id, - info_hash: InfoHash(info_hash.bytes()), - peer_id: PeerId(*b"-qB00000000000000001"), - bytes_downloaded: NumberOfBytes(0i64.into()), - bytes_uploaded: NumberOfBytes(0i64.into()), - bytes_left: NumberOfBytes(0i64.into()), - event: AnnounceEvent::Started.into(), - ip_address: Ipv4Addr::new(0, 0, 0, 0).into(), - key: PeerKey::new(0i32), - peers_wanted: NumberOfPeers(1i32.into()), - port: Port::new(port), - }; - - let _ = self - .client - .send(announce_request.into()) - .await - .map_err(|err| Error::UnableToSendAnnounceRequest { err })?; - - let response = self - .client - .receive() - .await - .map_err(|err| Error::UnableToReceiveAnnounceResponse { err })?; - - Ok(response) - } - - /// Sends a scrape request to the UDP Tracker server. - /// - /// # Errors - /// - /// Will return and error if the client is not connected. You have to connect - /// before calling this function. - pub async fn send_scrape_request( - &self, - connection_id: ConnectionId, - transaction_id: TransactionId, - info_hashes: &[TorrustInfoHash], - ) -> Result { - tracing::debug!("Sending scrape request with transaction id: {transaction_id:#?}"); - - let scrape_request = ScrapeRequest { - connection_id, - transaction_id, - info_hashes: info_hashes - .iter() - .map(|torrust_info_hash| InfoHash(torrust_info_hash.bytes())) - .collect(), - }; - - let _ = self - .client - .send(scrape_request.into()) - .await - .map_err(|err| Error::UnableToSendScrapeRequest { err })?; - - let response = self - .client - .receive() - .await - .map_err(|err| Error::UnableToReceiveScrapeResponse { err })?; - - Ok(response) - } -} diff --git a/src/console/clients/udp/mod.rs b/src/console/clients/udp/mod.rs deleted file mode 100644 index b92bed096..000000000 --- a/src/console/clients/udp/mod.rs +++ /dev/null @@ -1,51 +0,0 @@ -use std::net::SocketAddr; - -use aquatic_udp_protocol::Response; -use serde::Serialize; -use thiserror::Error; - -use crate::shared::bit_torrent::tracker::udp; - -pub mod app; -pub mod checker; -pub mod responses; - -#[derive(Error, Debug, Clone, Serialize)] -#[serde(into = "String")] -pub enum Error { - #[error("Failed to Connect to: {remote_addr}, with error: {err}")] - UnableToBindAndConnect { remote_addr: SocketAddr, err: udp::Error }, - - #[error("Failed to send a connection request, with error: {err}")] - UnableToSendConnectionRequest { err: udp::Error }, - - #[error("Failed to receive a connect response, with error: {err}")] - UnableToReceiveConnectResponse { err: udp::Error }, - - #[error("Failed to send a announce request, with error: {err}")] - UnableToSendAnnounceRequest { err: udp::Error }, - - #[error("Failed to receive a announce response, with error: {err}")] - UnableToReceiveAnnounceResponse { err: udp::Error }, - - #[error("Failed to send a scrape request, with error: {err}")] - UnableToSendScrapeRequest { err: udp::Error }, - - #[error("Failed to receive a scrape response, with error: {err}")] - UnableToReceiveScrapeResponse { err: udp::Error }, - - #[error("Failed to receive a response, with error: {err}")] - UnableToReceiveResponse { err: udp::Error }, - - #[error("Failed to get local address for connection: {err}")] - UnableToGetLocalAddr { err: udp::Error }, - - #[error("Failed to get a connection response: {response:?}")] - UnexpectedConnectionResponse { response: Response }, -} - -impl From for String { - fn from(value: Error) -> Self { - value.to_string() - } -} diff --git a/src/console/clients/udp/responses/dto.rs b/src/console/clients/udp/responses/dto.rs deleted file mode 100644 index 93320b0f7..000000000 --- a/src/console/clients/udp/responses/dto.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! Aquatic responses are not serializable. These are the serializable wrappers. -use std::net::{Ipv4Addr, Ipv6Addr}; - -use aquatic_udp_protocol::Response::{self}; -use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse}; -use serde::Serialize; - -#[derive(Serialize)] -pub enum SerializableResponse { - Connect(ConnectSerializableResponse), - AnnounceIpv4(AnnounceSerializableResponse), - AnnounceIpv6(AnnounceSerializableResponse), - Scrape(ScrapeSerializableResponse), - Error(ErrorSerializableResponse), -} - -impl From for SerializableResponse { - fn from(response: Response) -> Self { - match response { - Response::Connect(response) => SerializableResponse::Connect(ConnectSerializableResponse::from(response)), - Response::AnnounceIpv4(response) => SerializableResponse::AnnounceIpv4(AnnounceSerializableResponse::from(response)), - Response::AnnounceIpv6(response) => SerializableResponse::AnnounceIpv6(AnnounceSerializableResponse::from(response)), - Response::Scrape(response) => SerializableResponse::Scrape(ScrapeSerializableResponse::from(response)), - Response::Error(response) => SerializableResponse::Error(ErrorSerializableResponse::from(response)), - } - } -} - -#[derive(Serialize)] -pub struct ConnectSerializableResponse { - transaction_id: i32, - connection_id: i64, -} - -impl From for ConnectSerializableResponse { - fn from(connect: ConnectResponse) -> Self { - Self { - transaction_id: connect.transaction_id.0.into(), - connection_id: connect.connection_id.0.into(), - } - } -} - -#[derive(Serialize)] -pub struct AnnounceSerializableResponse { - transaction_id: i32, - announce_interval: i32, - leechers: i32, - seeders: i32, - peers: Vec, -} - -impl From> for AnnounceSerializableResponse { - fn from(announce: AnnounceResponse) -> Self { - Self { - transaction_id: announce.fixed.transaction_id.0.into(), - announce_interval: announce.fixed.announce_interval.0.into(), - leechers: announce.fixed.leechers.0.into(), - seeders: announce.fixed.seeders.0.into(), - peers: announce - .peers - .iter() - .map(|peer| format!("{}:{}", Ipv4Addr::from(peer.ip_address), peer.port.0)) - .collect::>(), - } - } -} - -impl From> for AnnounceSerializableResponse { - fn from(announce: AnnounceResponse) -> Self { - Self { - transaction_id: announce.fixed.transaction_id.0.into(), - announce_interval: announce.fixed.announce_interval.0.into(), - leechers: announce.fixed.leechers.0.into(), - seeders: announce.fixed.seeders.0.into(), - peers: announce - .peers - .iter() - .map(|peer| format!("{}:{}", Ipv6Addr::from(peer.ip_address), peer.port.0)) - .collect::>(), - } - } -} - -#[derive(Serialize)] -pub struct ScrapeSerializableResponse { - transaction_id: i32, - torrent_stats: Vec, -} - -impl From for ScrapeSerializableResponse { - fn from(scrape: ScrapeResponse) -> Self { - Self { - transaction_id: scrape.transaction_id.0.into(), - torrent_stats: scrape - .torrent_stats - .iter() - .map(|torrent_scrape_statistics| TorrentStats { - seeders: torrent_scrape_statistics.seeders.0.into(), - completed: torrent_scrape_statistics.completed.0.into(), - leechers: torrent_scrape_statistics.leechers.0.into(), - }) - .collect::>(), - } - } -} - -#[derive(Serialize)] -pub struct ErrorSerializableResponse { - transaction_id: i32, - message: String, -} - -impl From for ErrorSerializableResponse { - fn from(error: ErrorResponse) -> Self { - Self { - transaction_id: error.transaction_id.0.into(), - message: error.message.to_string(), - } - } -} - -#[derive(Serialize)] -struct TorrentStats { - seeders: i32, - completed: i32, - leechers: i32, -} diff --git a/src/console/clients/udp/responses/json.rs b/src/console/clients/udp/responses/json.rs deleted file mode 100644 index 5d2bd6b89..000000000 --- a/src/console/clients/udp/responses/json.rs +++ /dev/null @@ -1,25 +0,0 @@ -use anyhow::Context; -use serde::Serialize; - -use super::dto::SerializableResponse; - -#[allow(clippy::module_name_repetitions)] -pub trait ToJson { - /// - /// Returns a string with the JSON serialized version of the response - /// - /// # Errors - /// - /// Will return an error if serialization fails. - /// - fn to_json_string(&self) -> anyhow::Result - where - Self: Serialize, - { - let pretty_json = serde_json::to_string_pretty(self).context("response JSON serialization")?; - - Ok(pretty_json) - } -} - -impl ToJson for SerializableResponse {} diff --git a/src/console/clients/udp/responses/mod.rs b/src/console/clients/udp/responses/mod.rs deleted file mode 100644 index e6d2e5e51..000000000 --- a/src/console/clients/udp/responses/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod dto; -pub mod json; diff --git a/src/console/mod.rs b/src/console/mod.rs index dab338e4b..0e0da3fa2 100644 --- a/src/console/mod.rs +++ b/src/console/mod.rs @@ -1,4 +1,3 @@ //! Console apps. pub mod ci; -pub mod clients; pub mod profiling; diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index c9ad213f6..7f31d7739 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -2,6 +2,7 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; +use bittorrent_tracker_client::udp::client::check; use derive_more::Constructor; use futures_util::StreamExt; use tokio::select; @@ -18,7 +19,6 @@ use crate::servers::udp::server::bound_socket::BoundSocket; use crate::servers::udp::server::processor::Processor; use crate::servers::udp::server::receiver::Receiver; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; -use crate::shared::bit_torrent::tracker::udp::client::check; /// A UDP server instance launcher. #[derive(Constructor)] diff --git a/src/shared/bit_torrent/tracker/http/client/mod.rs b/src/shared/bit_torrent/tracker/http/client/mod.rs deleted file mode 100644 index 4c70cd68b..000000000 --- a/src/shared/bit_torrent/tracker/http/client/mod.rs +++ /dev/null @@ -1,204 +0,0 @@ -pub mod requests; -pub mod responses; - -use std::net::IpAddr; -use std::sync::Arc; -use std::time::Duration; - -use hyper::StatusCode; -use requests::{announce, scrape}; -use reqwest::{Response, Url}; -use thiserror::Error; - -use crate::core::auth::Key; - -#[derive(Debug, Clone, Error)] -pub enum Error { - #[error("Failed to Build a Http Client: {err:?}")] - ClientBuildingError { err: Arc }, - #[error("Failed to get a response: {err:?}")] - ResponseError { err: Arc }, - #[error("Returned a non-success code: \"{code}\" with the response: \"{response:?}\"")] - UnsuccessfulResponse { code: StatusCode, response: Arc }, -} - -/// HTTP Tracker Client -pub struct Client { - client: reqwest::Client, - base_url: Url, - key: Option, -} - -/// URL components in this context: -/// -/// ```text -/// http://127.0.0.1:62304/announce/YZ....rJ?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 -/// \_____________________/\_______________/ \__________________________________________________________/ -/// | | | -/// base url path query -/// ``` -impl Client { - /// # Errors - /// - /// This method fails if the client builder fails. - pub fn new(base_url: Url, timeout: Duration) -> Result { - let client = reqwest::Client::builder() - .timeout(timeout) - .build() - .map_err(|e| Error::ClientBuildingError { err: e.into() })?; - - Ok(Self { - base_url, - client, - key: None, - }) - } - - /// Creates the new client binding it to an specific local address. - /// - /// # Errors - /// - /// This method fails if the client builder fails. - pub fn bind(base_url: Url, timeout: Duration, local_address: IpAddr) -> Result { - let client = reqwest::Client::builder() - .timeout(timeout) - .local_address(local_address) - .build() - .map_err(|e| Error::ClientBuildingError { err: e.into() })?; - - Ok(Self { - base_url, - client, - key: None, - }) - } - - /// # Errors - /// - /// This method fails if the client builder fails. - pub fn authenticated(base_url: Url, timeout: Duration, key: Key) -> Result { - let client = reqwest::Client::builder() - .timeout(timeout) - .build() - .map_err(|e| Error::ClientBuildingError { err: e.into() })?; - - Ok(Self { - base_url, - client, - key: Some(key), - }) - } - - /// # Errors - /// - /// This method fails if the returned response was not successful - pub async fn announce(&self, query: &announce::Query) -> Result { - let response = self.get(&self.build_announce_path_and_query(query)).await?; - - if response.status().is_success() { - Ok(response) - } else { - Err(Error::UnsuccessfulResponse { - code: response.status(), - response: response.into(), - }) - } - } - - /// # Errors - /// - /// This method fails if the returned response was not successful - pub async fn scrape(&self, query: &scrape::Query) -> Result { - let response = self.get(&self.build_scrape_path_and_query(query)).await?; - - if response.status().is_success() { - Ok(response) - } else { - Err(Error::UnsuccessfulResponse { - code: response.status(), - response: response.into(), - }) - } - } - - /// # Errors - /// - /// This method fails if the returned response was not successful - pub async fn announce_with_header(&self, query: &announce::Query, key: &str, value: &str) -> Result { - let response = self - .get_with_header(&self.build_announce_path_and_query(query), key, value) - .await?; - - if response.status().is_success() { - Ok(response) - } else { - Err(Error::UnsuccessfulResponse { - code: response.status(), - response: response.into(), - }) - } - } - - /// # Errors - /// - /// This method fails if the returned response was not successful - pub async fn health_check(&self) -> Result { - let response = self.get(&self.build_path("health_check")).await?; - - if response.status().is_success() { - Ok(response) - } else { - Err(Error::UnsuccessfulResponse { - code: response.status(), - response: response.into(), - }) - } - } - - /// # Errors - /// - /// This method fails if there was an error while sending request. - pub async fn get(&self, path: &str) -> Result { - self.client - .get(self.build_url(path)) - .send() - .await - .map_err(|e| Error::ResponseError { err: e.into() }) - } - - /// # Errors - /// - /// This method fails if there was an error while sending request. - pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Result { - self.client - .get(self.build_url(path)) - .header(key, value) - .send() - .await - .map_err(|e| Error::ResponseError { err: e.into() }) - } - - fn build_announce_path_and_query(&self, query: &announce::Query) -> String { - format!("{}?{query}", self.build_path("announce")) - } - - fn build_scrape_path_and_query(&self, query: &scrape::Query) -> String { - format!("{}?{query}", self.build_path("scrape")) - } - - fn build_path(&self, path: &str) -> String { - match &self.key { - Some(key) => format!("{path}/{key}"), - None => path.to_string(), - } - } - - fn build_url(&self, path: &str) -> String { - let base_url = self.base_url(); - format!("{base_url}{path}") - } - - fn base_url(&self) -> String { - self.base_url.to_string() - } -} diff --git a/src/shared/bit_torrent/tracker/http/client/requests/announce.rs b/src/shared/bit_torrent/tracker/http/client/requests/announce.rs deleted file mode 100644 index f3ce327ea..000000000 --- a/src/shared/bit_torrent/tracker/http/client/requests/announce.rs +++ /dev/null @@ -1,275 +0,0 @@ -use std::fmt; -use std::net::{IpAddr, Ipv4Addr}; -use std::str::FromStr; - -use aquatic_udp_protocol::PeerId; -use bittorrent_primitives::info_hash::InfoHash; -use serde_repr::Serialize_repr; - -use crate::shared::bit_torrent::tracker::http::{percent_encode_byte_array, ByteArray20}; - -pub struct Query { - pub info_hash: ByteArray20, - pub peer_addr: IpAddr, - pub downloaded: BaseTenASCII, - pub uploaded: BaseTenASCII, - pub peer_id: ByteArray20, - pub port: PortNumber, - pub left: BaseTenASCII, - pub event: Option, - pub compact: Option, -} - -impl fmt::Display for Query { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.build()) - } -} - -/// HTTP Tracker Announce Request: -/// -/// -/// -/// Some parameters in the specification are not implemented in this tracker yet. -impl Query { - /// It builds the URL query component for the announce request. - /// - /// This custom URL query params encoding is needed because `reqwest` does not allow - /// bytes arrays in query parameters. More info on this issue: - /// - /// - #[must_use] - pub fn build(&self) -> String { - self.params().to_string() - } - - #[must_use] - pub fn params(&self) -> QueryParams { - QueryParams::from(self) - } -} - -pub type BaseTenASCII = u64; -pub type PortNumber = u16; - -pub enum Event { - //Started, - //Stopped, - Completed, -} - -impl fmt::Display for Event { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - //Event::Started => write!(f, "started"), - //Event::Stopped => write!(f, "stopped"), - Event::Completed => write!(f, "completed"), - } - } -} - -#[derive(Serialize_repr, PartialEq, Debug)] -#[repr(u8)] -pub enum Compact { - Accepted = 1, - NotAccepted = 0, -} - -impl fmt::Display for Compact { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Compact::Accepted => write!(f, "1"), - Compact::NotAccepted => write!(f, "0"), - } - } -} - -pub struct QueryBuilder { - announce_query: Query, -} - -impl QueryBuilder { - /// # Panics - /// - /// Will panic if the default info-hash value is not a valid info-hash. - #[must_use] - pub fn with_default_values() -> QueryBuilder { - let default_announce_query = Query { - info_hash: InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0, // # DevSkim: ignore DS173237 - peer_addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 88)), - downloaded: 0, - uploaded: 0, - peer_id: PeerId(*b"-qB00000000000000001").0, - port: 17548, - left: 0, - event: Some(Event::Completed), - compact: Some(Compact::NotAccepted), - }; - Self { - announce_query: default_announce_query, - } - } - - #[must_use] - pub fn with_info_hash(mut self, info_hash: &InfoHash) -> Self { - self.announce_query.info_hash = info_hash.0; - self - } - - #[must_use] - pub fn with_peer_id(mut self, peer_id: &PeerId) -> Self { - self.announce_query.peer_id = peer_id.0; - self - } - - #[must_use] - pub fn with_compact(mut self, compact: Compact) -> Self { - self.announce_query.compact = Some(compact); - self - } - - #[must_use] - pub fn with_peer_addr(mut self, peer_addr: &IpAddr) -> Self { - self.announce_query.peer_addr = *peer_addr; - self - } - - #[must_use] - pub fn without_compact(mut self) -> Self { - self.announce_query.compact = None; - self - } - - #[must_use] - pub fn query(self) -> Query { - self.announce_query - } -} - -/// It contains all the GET parameters that can be used in a HTTP Announce request. -/// -/// Sample Announce URL with all the GET parameters (mandatory and optional): -/// -/// ```text -/// http://127.0.0.1:7070/announce? -/// info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 (mandatory) -/// peer_addr=192.168.1.88 -/// downloaded=0 -/// uploaded=0 -/// peer_id=%2DqB00000000000000000 (mandatory) -/// port=17548 (mandatory) -/// left=0 -/// event=completed -/// compact=0 -/// ``` -pub struct QueryParams { - pub info_hash: Option, - pub peer_addr: Option, - pub downloaded: Option, - pub uploaded: Option, - pub peer_id: Option, - pub port: Option, - pub left: Option, - pub event: Option, - pub compact: Option, -} - -impl std::fmt::Display for QueryParams { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let mut params = vec![]; - - if let Some(info_hash) = &self.info_hash { - params.push(("info_hash", info_hash)); - } - if let Some(peer_addr) = &self.peer_addr { - params.push(("peer_addr", peer_addr)); - } - if let Some(downloaded) = &self.downloaded { - params.push(("downloaded", downloaded)); - } - if let Some(uploaded) = &self.uploaded { - params.push(("uploaded", uploaded)); - } - if let Some(peer_id) = &self.peer_id { - params.push(("peer_id", peer_id)); - } - if let Some(port) = &self.port { - params.push(("port", port)); - } - if let Some(left) = &self.left { - params.push(("left", left)); - } - if let Some(event) = &self.event { - params.push(("event", event)); - } - if let Some(compact) = &self.compact { - params.push(("compact", compact)); - } - - let query = params - .iter() - .map(|param| format!("{}={}", param.0, param.1)) - .collect::>() - .join("&"); - - write!(f, "{query}") - } -} - -impl QueryParams { - pub fn from(announce_query: &Query) -> Self { - let event = announce_query.event.as_ref().map(std::string::ToString::to_string); - let compact = announce_query.compact.as_ref().map(std::string::ToString::to_string); - - Self { - info_hash: Some(percent_encode_byte_array(&announce_query.info_hash)), - peer_addr: Some(announce_query.peer_addr.to_string()), - downloaded: Some(announce_query.downloaded.to_string()), - uploaded: Some(announce_query.uploaded.to_string()), - peer_id: Some(percent_encode_byte_array(&announce_query.peer_id)), - port: Some(announce_query.port.to_string()), - left: Some(announce_query.left.to_string()), - event, - compact, - } - } - - pub fn remove_optional_params(&mut self) { - // todo: make them optional with the Option<...> in the AnnounceQuery struct - // if they are really optional. So that we can crete a minimal AnnounceQuery - // instead of removing the optional params afterwards. - // - // The original specification on: - // - // says only `ip` and `event` are optional. - // - // On - // says only `ip`, `numwant`, `key` and `trackerid` are optional. - // - // but the server is responding if all these params are not included. - self.peer_addr = None; - self.downloaded = None; - self.uploaded = None; - self.left = None; - self.event = None; - self.compact = None; - } - - /// # Panics - /// - /// Will panic if invalid param name is provided. - pub fn set(&mut self, param_name: &str, param_value: &str) { - match param_name { - "info_hash" => self.info_hash = Some(param_value.to_string()), - "peer_addr" => self.peer_addr = Some(param_value.to_string()), - "downloaded" => self.downloaded = Some(param_value.to_string()), - "uploaded" => self.uploaded = Some(param_value.to_string()), - "peer_id" => self.peer_id = Some(param_value.to_string()), - "port" => self.port = Some(param_value.to_string()), - "left" => self.left = Some(param_value.to_string()), - "event" => self.event = Some(param_value.to_string()), - "compact" => self.compact = Some(param_value.to_string()), - &_ => panic!("Invalid param name for announce query"), - } - } -} diff --git a/src/shared/bit_torrent/tracker/http/client/requests/mod.rs b/src/shared/bit_torrent/tracker/http/client/requests/mod.rs deleted file mode 100644 index 776d2dfbf..000000000 --- a/src/shared/bit_torrent/tracker/http/client/requests/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod announce; -pub mod scrape; diff --git a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs b/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs deleted file mode 100644 index 58b9e0dc7..000000000 --- a/src/shared/bit_torrent/tracker/http/client/requests/scrape.rs +++ /dev/null @@ -1,172 +0,0 @@ -use std::error::Error; -use std::fmt::{self}; -use std::str::FromStr; - -use bittorrent_primitives::info_hash::InfoHash; - -use crate::shared::bit_torrent::tracker::http::{percent_encode_byte_array, ByteArray20}; - -pub struct Query { - pub info_hash: Vec, -} - -impl fmt::Display for Query { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.build()) - } -} - -#[derive(Debug)] -#[allow(dead_code)] -pub struct ConversionError(String); - -impl fmt::Display for ConversionError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Invalid infohash: {}", self.0) - } -} - -impl Error for ConversionError {} - -impl TryFrom<&[String]> for Query { - type Error = ConversionError; - - fn try_from(info_hashes: &[String]) -> Result { - let mut validated_info_hashes: Vec = Vec::new(); - - for info_hash in info_hashes { - let validated_info_hash = InfoHash::from_str(info_hash).map_err(|_| ConversionError(info_hash.clone()))?; - validated_info_hashes.push(validated_info_hash.0); - } - - Ok(Self { - info_hash: validated_info_hashes, - }) - } -} - -impl TryFrom> for Query { - type Error = ConversionError; - - fn try_from(info_hashes: Vec) -> Result { - let mut validated_info_hashes: Vec = Vec::new(); - - for info_hash in info_hashes { - let validated_info_hash = InfoHash::from_str(&info_hash).map_err(|_| ConversionError(info_hash.clone()))?; - validated_info_hashes.push(validated_info_hash.0); - } - - Ok(Self { - info_hash: validated_info_hashes, - }) - } -} - -/// HTTP Tracker Scrape Request: -/// -/// -impl Query { - /// It builds the URL query component for the scrape request. - /// - /// This custom URL query params encoding is needed because `reqwest` does not allow - /// bytes arrays in query parameters. More info on this issue: - /// - /// - #[must_use] - pub fn build(&self) -> String { - self.params().to_string() - } - - #[must_use] - pub fn params(&self) -> QueryParams { - QueryParams::from(self) - } -} - -pub struct QueryBuilder { - scrape_query: Query, -} - -impl Default for QueryBuilder { - fn default() -> Self { - let default_scrape_query = Query { - info_hash: [InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0].to_vec(), // # DevSkim: ignore DS173237 - }; - Self { - scrape_query: default_scrape_query, - } - } -} - -impl QueryBuilder { - #[must_use] - pub fn with_one_info_hash(mut self, info_hash: &InfoHash) -> Self { - self.scrape_query.info_hash = [info_hash.0].to_vec(); - self - } - - #[must_use] - pub fn add_info_hash(mut self, info_hash: &InfoHash) -> Self { - self.scrape_query.info_hash.push(info_hash.0); - self - } - - #[must_use] - pub fn query(self) -> Query { - self.scrape_query - } -} - -/// It contains all the GET parameters that can be used in a HTTP Scrape request. -/// -/// The `info_hash` param is the percent encoded of the the 20-byte array info hash. -/// -/// Sample Scrape URL with all the GET parameters: -/// -/// For `IpV4`: -/// -/// ```text -/// http://127.0.0.1:7070/scrape?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 -/// ``` -/// -/// For `IpV6`: -/// -/// ```text -/// http://[::1]:7070/scrape?info_hash=%9C8B%22%13%E3%0B%FF%21%2B0%C3%60%D2o%9A%02%13d%22 -/// ``` -/// -/// You can add as many info hashes as you want, just adding the same param again. -pub struct QueryParams { - pub info_hash: Vec, -} - -impl QueryParams { - pub fn set_one_info_hash_param(&mut self, info_hash: &str) { - self.info_hash = vec![info_hash.to_string()]; - } -} - -impl std::fmt::Display for QueryParams { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let query = self - .info_hash - .iter() - .map(|info_hash| format!("info_hash={}", &info_hash)) - .collect::>() - .join("&"); - - write!(f, "{query}") - } -} - -impl QueryParams { - pub fn from(scrape_query: &Query) -> Self { - let info_hashes = scrape_query - .info_hash - .iter() - .map(percent_encode_byte_array) - .collect::>(); - - Self { info_hash: info_hashes } - } -} diff --git a/src/shared/bit_torrent/tracker/http/client/responses/announce.rs b/src/shared/bit_torrent/tracker/http/client/responses/announce.rs deleted file mode 100644 index 7f2d3611c..000000000 --- a/src/shared/bit_torrent/tracker/http/client/responses/announce.rs +++ /dev/null @@ -1,126 +0,0 @@ -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - -use serde::{Deserialize, Serialize}; -use torrust_tracker_primitives::peer; -use zerocopy::AsBytes as _; - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct Announce { - pub complete: u32, - pub incomplete: u32, - pub interval: u32, - #[serde(rename = "min interval")] - pub min_interval: u32, - pub peers: Vec, // Peers using IPV4 and IPV6 -} - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct DictionaryPeer { - pub ip: String, - #[serde(rename = "peer id")] - #[serde(with = "serde_bytes")] - pub peer_id: Vec, - pub port: u16, -} - -impl From for DictionaryPeer { - fn from(peer: peer::Peer) -> Self { - DictionaryPeer { - peer_id: peer.peer_id.as_bytes().to_vec(), - ip: peer.peer_addr.ip().to_string(), - port: peer.peer_addr.port(), - } - } -} - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct DeserializedCompact { - pub complete: u32, - pub incomplete: u32, - pub interval: u32, - #[serde(rename = "min interval")] - pub min_interval: u32, - #[serde(with = "serde_bytes")] - pub peers: Vec, -} - -impl DeserializedCompact { - /// # Errors - /// - /// Will return an error if bytes can't be deserialized. - pub fn from_bytes(bytes: &[u8]) -> Result { - serde_bencode::from_bytes::(bytes) - } -} - -#[derive(Debug, PartialEq)] -pub struct Compact { - // code-review: there could be a way to deserialize this struct directly - // by using serde instead of doing it manually. Or at least using a custom deserializer. - pub complete: u32, - pub incomplete: u32, - pub interval: u32, - pub min_interval: u32, - pub peers: CompactPeerList, -} - -#[derive(Debug, PartialEq)] -pub struct CompactPeerList { - peers: Vec, -} - -impl CompactPeerList { - #[must_use] - pub fn new(peers: Vec) -> Self { - Self { peers } - } -} - -#[derive(Clone, Debug, PartialEq)] -pub struct CompactPeer { - ip: Ipv4Addr, - port: u16, -} - -impl CompactPeer { - /// # Panics - /// - /// Will panic if the provided socket address is a IPv6 IP address. - /// It's not supported for compact peers. - #[must_use] - pub fn new(socket_addr: &SocketAddr) -> Self { - match socket_addr.ip() { - IpAddr::V4(ip) => Self { - ip, - port: socket_addr.port(), - }, - IpAddr::V6(_ip) => panic!("IPV6 is not supported for compact peer"), - } - } - - #[must_use] - pub fn new_from_bytes(bytes: &[u8]) -> Self { - Self { - ip: Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]), - port: u16::from_be_bytes([bytes[4], bytes[5]]), - } - } -} - -impl From for Compact { - fn from(compact_announce: DeserializedCompact) -> Self { - let mut peers = vec![]; - - for peer_bytes in compact_announce.peers.chunks_exact(6) { - peers.push(CompactPeer::new_from_bytes(peer_bytes)); - } - - Self { - complete: compact_announce.complete, - incomplete: compact_announce.incomplete, - interval: compact_announce.interval, - min_interval: compact_announce.min_interval, - peers: CompactPeerList::new(peers), - } - } -} diff --git a/src/shared/bit_torrent/tracker/http/client/responses/error.rs b/src/shared/bit_torrent/tracker/http/client/responses/error.rs deleted file mode 100644 index 00befdb54..000000000 --- a/src/shared/bit_torrent/tracker/http/client/responses/error.rs +++ /dev/null @@ -1,7 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -pub struct Error { - #[serde(rename = "failure reason")] - pub failure_reason: String, -} diff --git a/src/shared/bit_torrent/tracker/http/client/responses/mod.rs b/src/shared/bit_torrent/tracker/http/client/responses/mod.rs deleted file mode 100644 index bdc689056..000000000 --- a/src/shared/bit_torrent/tracker/http/client/responses/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod announce; -pub mod error; -pub mod scrape; diff --git a/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs b/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs deleted file mode 100644 index 25a2f0a81..000000000 --- a/src/shared/bit_torrent/tracker/http/client/responses/scrape.rs +++ /dev/null @@ -1,230 +0,0 @@ -use std::collections::HashMap; -use std::fmt::Write; -use std::str; - -use serde::ser::SerializeMap; -use serde::{Deserialize, Serialize, Serializer}; -use serde_bencode::value::Value; - -use crate::shared::bit_torrent::tracker::http::{ByteArray20, InfoHash}; - -#[derive(Debug, PartialEq, Default, Deserialize)] -pub struct Response { - pub files: HashMap, -} - -impl Response { - #[must_use] - pub fn with_one_file(info_hash_bytes: ByteArray20, file: File) -> Self { - let mut files: HashMap = HashMap::new(); - files.insert(info_hash_bytes, file); - Self { files } - } - - /// # Errors - /// - /// Will return an error if the deserialized bencoded response can't not be converted into a valid response. - /// - /// # Panics - /// - /// Will panic if it can't deserialize the bencoded response. - pub fn try_from_bencoded(bytes: &[u8]) -> Result { - let scrape_response: DeserializedResponse = - serde_bencode::from_bytes(bytes).expect("provided bytes should be a valid bencoded response"); - Self::try_from(scrape_response) - } -} - -#[derive(Serialize, Deserialize, Debug, PartialEq, Default)] -pub struct File { - pub complete: i64, // The number of active peers that have completed downloading - pub downloaded: i64, // The number of peers that have ever completed downloading - pub incomplete: i64, // The number of active peers that have not completed downloading -} - -impl File { - #[must_use] - pub fn zeroed() -> Self { - Self::default() - } -} - -impl TryFrom for Response { - type Error = BencodeParseError; - - fn try_from(scrape_response: DeserializedResponse) -> Result { - parse_bencoded_response(&scrape_response.files) - } -} - -#[derive(Serialize, Deserialize, Debug, PartialEq)] -struct DeserializedResponse { - pub files: Value, -} - -// Custom serialization for Response -impl Serialize for Response { - fn serialize(&self, serializer: S) -> Result - where - S: Serializer, - { - let mut map = serializer.serialize_map(Some(self.files.len()))?; - for (key, value) in &self.files { - // Convert ByteArray20 key to hex string - let hex_key = byte_array_to_hex_string(key); - map.serialize_entry(&hex_key, value)?; - } - map.end() - } -} - -// Helper function to convert ByteArray20 to hex string -fn byte_array_to_hex_string(byte_array: &ByteArray20) -> String { - let mut hex_string = String::with_capacity(byte_array.len() * 2); - for byte in byte_array { - write!(hex_string, "{byte:02x}").expect("Writing to string should never fail"); - } - hex_string -} - -#[derive(Default)] -pub struct ResponseBuilder { - response: Response, -} - -impl ResponseBuilder { - #[must_use] - pub fn add_file(mut self, info_hash_bytes: ByteArray20, file: File) -> Self { - self.response.files.insert(info_hash_bytes, file); - self - } - - #[must_use] - pub fn build(self) -> Response { - self.response - } -} - -#[derive(Debug)] -pub enum BencodeParseError { - InvalidValueExpectedDict { value: Value }, - InvalidValueExpectedInt { value: Value }, - InvalidFileField { value: Value }, - MissingFileField { field_name: String }, -} - -/// It parses a bencoded scrape response into a `Response` struct. -/// -/// For example: -/// -/// ```text -/// d5:filesd20:xxxxxxxxxxxxxxxxxxxxd8:completei11e10:downloadedi13772e10:incompletei19e -/// 20:yyyyyyyyyyyyyyyyyyyyd8:completei21e10:downloadedi206e10:incompletei20eee -/// ``` -/// -/// Response (JSON encoded for readability): -/// -/// ```text -/// { -/// 'files': { -/// 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19}, -/// 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20} -/// } -/// } -fn parse_bencoded_response(value: &Value) -> Result { - let mut files: HashMap = HashMap::new(); - - match value { - Value::Dict(dict) => { - for file_element in dict { - let info_hash_byte_vec = file_element.0; - let file_value = file_element.1; - - let file = parse_bencoded_file(file_value).unwrap(); - - files.insert(InfoHash::new(info_hash_byte_vec).bytes(), file); - } - } - _ => return Err(BencodeParseError::InvalidValueExpectedDict { value: value.clone() }), - } - - Ok(Response { files }) -} - -/// It parses a bencoded dictionary into a `File` struct. -/// -/// For example: -/// -/// -/// ```text -/// d8:completei11e10:downloadedi13772e10:incompletei19ee -/// ``` -/// -/// into: -/// -/// ```text -/// File { -/// complete: 11, -/// downloaded: 13772, -/// incomplete: 19, -/// } -/// ``` -fn parse_bencoded_file(value: &Value) -> Result { - let file = match &value { - Value::Dict(dict) => { - let mut complete = None; - let mut downloaded = None; - let mut incomplete = None; - - for file_field in dict { - let field_name = file_field.0; - - let field_value = match file_field.1 { - Value::Int(number) => Ok(*number), - _ => Err(BencodeParseError::InvalidValueExpectedInt { - value: file_field.1.clone(), - }), - }?; - - if field_name == b"complete" { - complete = Some(field_value); - } else if field_name == b"downloaded" { - downloaded = Some(field_value); - } else if field_name == b"incomplete" { - incomplete = Some(field_value); - } else { - return Err(BencodeParseError::InvalidFileField { - value: file_field.1.clone(), - }); - } - } - - if complete.is_none() { - return Err(BencodeParseError::MissingFileField { - field_name: "complete".to_string(), - }); - } - - if downloaded.is_none() { - return Err(BencodeParseError::MissingFileField { - field_name: "downloaded".to_string(), - }); - } - - if incomplete.is_none() { - return Err(BencodeParseError::MissingFileField { - field_name: "incomplete".to_string(), - }); - } - - File { - complete: complete.unwrap(), - downloaded: downloaded.unwrap(), - incomplete: incomplete.unwrap(), - } - } - _ => return Err(BencodeParseError::InvalidValueExpectedDict { value: value.clone() }), - }; - - Ok(file) -} diff --git a/src/shared/bit_torrent/tracker/http/mod.rs b/src/shared/bit_torrent/tracker/http/mod.rs deleted file mode 100644 index 15723c1b7..000000000 --- a/src/shared/bit_torrent/tracker/http/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -pub mod client; - -use percent_encoding::NON_ALPHANUMERIC; - -pub type ByteArray20 = [u8; 20]; - -#[must_use] -pub fn percent_encode_byte_array(bytes: &ByteArray20) -> String { - percent_encoding::percent_encode(bytes, NON_ALPHANUMERIC).to_string() -} - -pub struct InfoHash(ByteArray20); - -impl InfoHash { - #[must_use] - pub fn new(vec: &[u8]) -> Self { - let mut byte_array_20: ByteArray20 = Default::default(); - byte_array_20.clone_from_slice(vec); - Self(byte_array_20) - } - - #[must_use] - pub fn bytes(&self) -> ByteArray20 { - self.0 - } -} diff --git a/src/shared/bit_torrent/tracker/mod.rs b/src/shared/bit_torrent/tracker/mod.rs index b08eaa622..7e5aaa137 100644 --- a/src/shared/bit_torrent/tracker/mod.rs +++ b/src/shared/bit_torrent/tracker/mod.rs @@ -1,2 +1 @@ -pub mod http; pub mod udp; diff --git a/src/shared/bit_torrent/tracker/udp/client.rs b/src/shared/bit_torrent/tracker/udp/client.rs deleted file mode 100644 index edb8adc85..000000000 --- a/src/shared/bit_torrent/tracker/udp/client.rs +++ /dev/null @@ -1,270 +0,0 @@ -use core::result::Result::{Err, Ok}; -use std::io::Cursor; -use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr}; -use std::sync::Arc; -use std::time::Duration; - -use aquatic_udp_protocol::{ConnectRequest, Request, Response, TransactionId}; -use tokio::net::UdpSocket; -use tokio::time; -use torrust_tracker_configuration::DEFAULT_TIMEOUT; -use zerocopy::network_endian::I32; - -use super::Error; -use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; - -pub const UDP_CLIENT_LOG_TARGET: &str = "UDP CLIENT"; - -#[allow(clippy::module_name_repetitions)] -#[derive(Debug)] -pub struct UdpClient { - /// The socket to connect to - pub socket: Arc, - - /// Timeout for sending and receiving packets - pub timeout: Duration, -} - -impl UdpClient { - /// Creates a new `UdpClient` bound to the default port and ipv6 address - /// - /// # Errors - /// - /// Will return error if unable to bind to any port or ip address. - /// - async fn bound_to_default_ipv4(timeout: Duration) -> Result { - let addr = SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0); - - Self::bound(addr, timeout).await - } - - /// Creates a new `UdpClient` bound to the default port and ipv6 address - /// - /// # Errors - /// - /// Will return error if unable to bind to any port or ip address. - /// - async fn bound_to_default_ipv6(timeout: Duration) -> Result { - let addr = SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), 0); - - Self::bound(addr, timeout).await - } - - /// Creates a new `UdpClient` connected to a Udp server - /// - /// # Errors - /// - /// Will return any errors present in the call stack - /// - pub async fn connected(remote_addr: SocketAddr, timeout: Duration) -> Result { - let client = if remote_addr.is_ipv4() { - Self::bound_to_default_ipv4(timeout).await? - } else { - Self::bound_to_default_ipv6(timeout).await? - }; - - client.connect(remote_addr).await?; - Ok(client) - } - - /// Creates a `[UdpClient]` bound to a Socket. - /// - /// # Panics - /// - /// Panics if unable to get the `local_addr` of the bound socket. - /// - /// # Errors - /// - /// This function will return an error if the binding takes to long - /// or if there is an underlying OS error. - pub async fn bound(addr: SocketAddr, timeout: Duration) -> Result { - tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "binding to socket: {addr:?} ..."); - - let socket = time::timeout(timeout, UdpSocket::bind(addr)) - .await - .map_err(|_| Error::TimeoutWhileBindingToSocket { addr })? - .map_err(|e| Error::UnableToBindToSocket { err: e.into(), addr })?; - - let addr = socket.local_addr().expect("it should get the local address"); - - tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "bound to socket: {addr:?}."); - - let udp_client = Self { - socket: Arc::new(socket), - timeout, - }; - - Ok(udp_client) - } - - /// # Errors - /// - /// Will return error if can't connect to the socket. - pub async fn connect(&self, remote_addr: SocketAddr) -> Result<(), Error> { - tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "connecting to remote: {remote_addr:?} ..."); - - let () = time::timeout(self.timeout, self.socket.connect(remote_addr)) - .await - .map_err(|_| Error::TimeoutWhileConnectingToRemote { remote_addr })? - .map_err(|e| Error::UnableToConnectToRemote { - err: e.into(), - remote_addr, - })?; - - tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "connected to remote: {remote_addr:?}."); - - Ok(()) - } - - /// # Errors - /// - /// Will return error if: - /// - /// - Can't write to the socket. - /// - Can't send data. - pub async fn send(&self, bytes: &[u8]) -> Result { - tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "sending {bytes:?} ..."); - - let () = time::timeout(self.timeout, self.socket.writable()) - .await - .map_err(|_| Error::TimeoutWaitForWriteableSocket)? - .map_err(|e| Error::UnableToGetWritableSocket { err: e.into() })?; - - let sent_bytes = time::timeout(self.timeout, self.socket.send(bytes)) - .await - .map_err(|_| Error::TimeoutWhileSendingData { data: bytes.to_vec() })? - .map_err(|e| Error::UnableToSendData { - err: e.into(), - data: bytes.to_vec(), - })?; - - tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "sent {sent_bytes} bytes to remote."); - - Ok(sent_bytes) - } - - /// # Errors - /// - /// Will return error if: - /// - /// - Can't read from the socket. - /// - Can't receive data. - /// - /// # Panics - /// - pub async fn receive(&self) -> Result, Error> { - tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "receiving ..."); - - let mut buffer = [0u8; MAX_PACKET_SIZE]; - - let () = time::timeout(self.timeout, self.socket.readable()) - .await - .map_err(|_| Error::TimeoutWaitForReadableSocket)? - .map_err(|e| Error::UnableToGetReadableSocket { err: e.into() })?; - - let received_bytes = time::timeout(self.timeout, self.socket.recv(&mut buffer)) - .await - .map_err(|_| Error::TimeoutWhileReceivingData)? - .map_err(|e| Error::UnableToReceivingData { err: e.into() })?; - - let mut received: Vec = buffer.to_vec(); - Vec::truncate(&mut received, received_bytes); - - tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "received {received_bytes} bytes: {received:?}"); - - Ok(received) - } -} - -#[allow(clippy::module_name_repetitions)] -#[derive(Debug)] -pub struct UdpTrackerClient { - pub client: UdpClient, -} - -impl UdpTrackerClient { - /// Creates a new `UdpTrackerClient` connected to a Udp Tracker server - /// - /// # Errors - /// - /// If unable to connect to the remote address. - /// - pub async fn new(remote_addr: SocketAddr, timeout: Duration) -> Result { - let client = UdpClient::connected(remote_addr, timeout).await?; - Ok(UdpTrackerClient { client }) - } - - /// # Errors - /// - /// Will return error if can't write request to bytes. - pub async fn send(&self, request: Request) -> Result { - tracing::trace!(target: UDP_CLIENT_LOG_TARGET, "sending request {request:?} ..."); - - // Write request into a buffer - // todo: optimize the pre-allocated amount based upon request type. - let mut writer = Cursor::new(Vec::with_capacity(200)); - let () = request - .write_bytes(&mut writer) - .map_err(|e| Error::UnableToWriteDataFromRequest { err: e.into(), request })?; - - self.client.send(writer.get_ref()).await - } - - /// # Errors - /// - /// Will return error if can't create response from the received payload (bytes buffer). - pub async fn receive(&self) -> Result { - let response = self.client.receive().await?; - - tracing::debug!(target: UDP_CLIENT_LOG_TARGET, "received {} bytes: {response:?}", response.len()); - - Response::parse_bytes(&response, true).map_err(|e| Error::UnableToParseResponse { err: e.into(), response }) - } -} - -/// Helper Function to Check if a UDP Service is Connectable -/// -/// # Panics -/// -/// It will return an error if unable to connect to the UDP service. -/// -/// # Errors -/// -pub async fn check(remote_addr: &SocketAddr) -> Result { - tracing::debug!("Checking Service (detail): {remote_addr:?}."); - - match UdpTrackerClient::new(*remote_addr, DEFAULT_TIMEOUT).await { - Ok(client) => { - let connect_request = ConnectRequest { - transaction_id: TransactionId(I32::new(123)), - }; - - // client.send() return usize, but doesn't use here - match client.send(connect_request.into()).await { - Ok(_) => (), - Err(e) => tracing::debug!("Error: {e:?}."), - }; - - let process = move |response| { - if matches!(response, Response::Connect(_connect_response)) { - Ok("Connected".to_string()) - } else { - Err("Did not Connect".to_string()) - } - }; - - let sleep = time::sleep(Duration::from_millis(2000)); - tokio::pin!(sleep); - - tokio::select! { - () = &mut sleep => { - Err("Timed Out".to_string()) - } - response = client.receive() => { - process(response.unwrap()) - } - } - } - Err(e) => Err(format!("{e:?}")), - } -} diff --git a/src/shared/bit_torrent/tracker/udp/mod.rs b/src/shared/bit_torrent/tracker/udp/mod.rs index b9d5f34f6..1ceb8a08b 100644 --- a/src/shared/bit_torrent/tracker/udp/mod.rs +++ b/src/shared/bit_torrent/tracker/udp/mod.rs @@ -1,68 +1,6 @@ -use std::net::SocketAddr; -use std::sync::Arc; - -use aquatic_udp_protocol::Request; -use thiserror::Error; -use torrust_tracker_located_error::DynError; - -pub mod client; - /// The maximum number of bytes in a UDP packet. pub const MAX_PACKET_SIZE: usize = 1496; + /// A magic 64-bit integer constant defined in the protocol that is used to /// identify the protocol. pub const PROTOCOL_ID: i64 = 0x0417_2710_1980; - -#[derive(Debug, Clone, Error)] -pub enum Error { - #[error("Timeout while waiting for socket to bind: {addr:?}")] - TimeoutWhileBindingToSocket { addr: SocketAddr }, - - #[error("Failed to bind to socket: {addr:?}, with error: {err:?}")] - UnableToBindToSocket { err: Arc, addr: SocketAddr }, - - #[error("Timeout while waiting for connection to remote: {remote_addr:?}")] - TimeoutWhileConnectingToRemote { remote_addr: SocketAddr }, - - #[error("Failed to connect to remote: {remote_addr:?}, with error: {err:?}")] - UnableToConnectToRemote { - err: Arc, - remote_addr: SocketAddr, - }, - - #[error("Timeout while waiting for the socket to become writable.")] - TimeoutWaitForWriteableSocket, - - #[error("Failed to get writable socket: {err:?}")] - UnableToGetWritableSocket { err: Arc }, - - #[error("Timeout while trying to send data: {data:?}")] - TimeoutWhileSendingData { data: Vec }, - - #[error("Failed to send data: {data:?}, with error: {err:?}")] - UnableToSendData { err: Arc, data: Vec }, - - #[error("Timeout while waiting for the socket to become readable.")] - TimeoutWaitForReadableSocket, - - #[error("Failed to get readable socket: {err:?}")] - UnableToGetReadableSocket { err: Arc }, - - #[error("Timeout while trying to receive data.")] - TimeoutWhileReceivingData, - - #[error("Failed to receive data: {err:?}")] - UnableToReceivingData { err: Arc }, - - #[error("Failed to get data from request: {request:?}, with error: {err:?}")] - UnableToWriteDataFromRequest { err: Arc, request: Request }, - - #[error("Failed to parse response: {response:?}, with error: {err:?}")] - UnableToParseResponse { err: Arc, response: Vec }, -} - -impl From for DynError { - fn from(e: Error) -> Self { - Arc::new(Box::new(e)) - } -} diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 1f9b71b62..73f7ce368 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -6,7 +6,7 @@ use core::panic; use aquatic_udp_protocol::{ConnectRequest, ConnectionId, Response, TransactionId}; -use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; +use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; @@ -71,7 +71,7 @@ async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_req mod receiving_a_connection_request { use aquatic_udp_protocol::{ConnectRequest, TransactionId}; - use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; + use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; @@ -120,7 +120,7 @@ mod receiving_an_announce_request { AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectionId, InfoHash, NumberOfBytes, NumberOfPeers, PeerId, PeerKey, Port, TransactionId, }; - use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; + use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; @@ -214,7 +214,7 @@ mod receiving_an_announce_request { mod receiving_an_scrape_request { use aquatic_udp_protocol::{ConnectionId, InfoHash, ScrapeRequest, TransactionId}; - use torrust_tracker::shared::bit_torrent::tracker::udp::client::UdpTrackerClient; + use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; From a5822cd63124a6617ee92676d176310918d822f4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 1 Nov 2024 16:58:56 +0000 Subject: [PATCH 0511/1297] fix: cargo machete errors --- Cargo.lock | 2 -- Cargo.toml | 1 - packages/tracker-client/Cargo.toml | 4 +++- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 00d83fddb..0bf1ad572 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -626,7 +626,6 @@ dependencies = [ "clap", "derive_more", "futures", - "futures-util", "hex-literal", "hyper", "percent-encoding", @@ -3859,7 +3858,6 @@ dependencies = [ "figment", "futures", "futures-util", - "hex-literal", "http-body", "hyper", "hyper-util", diff --git a/Cargo.toml b/Cargo.toml index 574881a94..a3d88be92 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,7 +47,6 @@ derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } figment = "0" futures = "0" futures-util = "0" -hex-literal = "0" http-body = "1" hyper = "1" hyper-util = { version = "0", features = ["http1", "http2", "tokio"] } diff --git a/packages/tracker-client/Cargo.toml b/packages/tracker-client/Cargo.toml index 85e10c03e..3334e7b47 100644 --- a/packages/tracker-client/Cargo.toml +++ b/packages/tracker-client/Cargo.toml @@ -21,7 +21,6 @@ bittorrent-primitives = "0.1.0" clap = { version = "4", features = ["derive", "env"] } derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } futures = "0" -futures-util = "0" hex-literal = "0" hyper = "1" percent-encoding = "2" @@ -40,3 +39,6 @@ tracing = "0" tracing-subscriber = { version = "0", features = ["json"] } url = { version = "2", features = ["serde"] } zerocopy = "0.7" + +[package.metadata.cargo-machete] +ignored = ["serde_bytes"] From e01995cf1bc9c08a99f9e3b59b6aa7d2a6620908 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 1 Nov 2024 17:34:50 +0000 Subject: [PATCH 0512/1297] fix: tracker checker execution in CI It was extractted in toa new package. --- src/console/ci/e2e/tracker_checker.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/console/ci/e2e/tracker_checker.rs b/src/console/ci/e2e/tracker_checker.rs index 192795e61..b4c2544ee 100644 --- a/src/console/ci/e2e/tracker_checker.rs +++ b/src/console/ci/e2e/tracker_checker.rs @@ -7,12 +7,14 @@ use std::process::Command; /// /// Will return an error if the Tracker Checker fails. pub fn run(config_content: &str) -> io::Result<()> { - tracing::info!("Running Tracker Checker: TORRUST_CHECKER_CONFIG=[config] cargo run --bin tracker_checker"); + tracing::info!( + "Running Tracker Checker: TORRUST_CHECKER_CONFIG=[config] cargo run -p bittorrent-tracker-client --bin tracker_checker" + ); tracing::info!("Tracker Checker config:\n{config_content}"); let status = Command::new("cargo") .env("TORRUST_CHECKER_CONFIG", config_content) - .args(["run", "--bin", "tracker_checker"]) + .args(["run", "-p", "bittorrent-tracker-client", "--bin", "tracker_checker"]) .status()?; if status.success() { From 9d8162488a6dade21e0a67cf8371a9745433f023 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 13 Nov 2024 10:23:45 +0000 Subject: [PATCH 0513/1297] feat: extract console clients into a new package --- .github/workflows/deployment.yaml | 9 +- Cargo.lock | 25 ++ Cargo.toml | 1 + console/tracker-client/Cargo.toml | 39 +++ console/tracker-client/README.md | 199 ++++++++++++ .../docs/licenses/LICENSE-MIT_0 | 14 + .../src/bin/http_tracker_client.rs | 7 + .../tracker-client/src/bin/tracker_checker.rs | 7 + .../src/bin/udp_tracker_client.rs | 7 + .../src/console/clients/checker/app.rs | 120 ++++++++ .../console/clients/checker/checks/health.rs | 77 +++++ .../console/clients/checker/checks/http.rs | 104 +++++++ .../src/console/clients/checker/checks/mod.rs | 4 + .../console/clients/checker/checks/structs.rs | 12 + .../src/console/clients/checker/checks/udp.rs | 134 +++++++++ .../src/console/clients/checker/config.rs | 282 ++++++++++++++++++ .../src/console/clients/checker/console.rs | 38 +++ .../src/console/clients/checker/logger.rs | 72 +++++ .../src/console/clients/checker/mod.rs | 7 + .../src/console/clients/checker/printer.rs | 9 + .../src/console/clients/checker/service.rs | 62 ++++ .../src/console/clients/http/app.rs | 101 +++++++ .../src/console/clients/http/mod.rs | 35 +++ .../tracker-client/src/console/clients/mod.rs | 4 + .../src/console/clients/udp/app.rs | 208 +++++++++++++ .../src/console/clients/udp/checker.rs | 177 +++++++++++ .../src/console/clients/udp/mod.rs | 50 ++++ .../src/console/clients/udp/responses/dto.rs | 128 ++++++++ .../src/console/clients/udp/responses/json.rs | 25 ++ .../src/console/clients/udp/responses/mod.rs | 2 + console/tracker-client/src/console/mod.rs | 2 + console/tracker-client/src/lib.rs | 1 + packages/tracker-client/README.md | 2 +- 33 files changed, 1959 insertions(+), 5 deletions(-) create mode 100644 console/tracker-client/Cargo.toml create mode 100644 console/tracker-client/README.md create mode 100644 console/tracker-client/docs/licenses/LICENSE-MIT_0 create mode 100644 console/tracker-client/src/bin/http_tracker_client.rs create mode 100644 console/tracker-client/src/bin/tracker_checker.rs create mode 100644 console/tracker-client/src/bin/udp_tracker_client.rs create mode 100644 console/tracker-client/src/console/clients/checker/app.rs create mode 100644 console/tracker-client/src/console/clients/checker/checks/health.rs create mode 100644 console/tracker-client/src/console/clients/checker/checks/http.rs create mode 100644 console/tracker-client/src/console/clients/checker/checks/mod.rs create mode 100644 console/tracker-client/src/console/clients/checker/checks/structs.rs create mode 100644 console/tracker-client/src/console/clients/checker/checks/udp.rs create mode 100644 console/tracker-client/src/console/clients/checker/config.rs create mode 100644 console/tracker-client/src/console/clients/checker/console.rs create mode 100644 console/tracker-client/src/console/clients/checker/logger.rs create mode 100644 console/tracker-client/src/console/clients/checker/mod.rs create mode 100644 console/tracker-client/src/console/clients/checker/printer.rs create mode 100644 console/tracker-client/src/console/clients/checker/service.rs create mode 100644 console/tracker-client/src/console/clients/http/app.rs create mode 100644 console/tracker-client/src/console/clients/http/mod.rs create mode 100644 console/tracker-client/src/console/clients/mod.rs create mode 100644 console/tracker-client/src/console/clients/udp/app.rs create mode 100644 console/tracker-client/src/console/clients/udp/checker.rs create mode 100644 console/tracker-client/src/console/clients/udp/mod.rs create mode 100644 console/tracker-client/src/console/clients/udp/responses/dto.rs create mode 100644 console/tracker-client/src/console/clients/udp/responses/json.rs create mode 100644 console/tracker-client/src/console/clients/udp/responses/mod.rs create mode 100644 console/tracker-client/src/console/mod.rs create mode 100644 console/tracker-client/src/lib.rs diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index e30eccc71..7f458cda2 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -55,11 +55,12 @@ jobs: env: CARGO_REGISTRY_TOKEN: "${{ secrets.TORRUST_UPDATE_CARGO_REGISTRY_TOKEN }}" run: | + cargo publish -p torrust-tracker + cargo publish -p torrust-tracker-client + cargo publish -p torrust-tracker-clock + cargo publish -p torrust-tracker-configuration cargo publish -p torrust-tracker-contrib-bencode cargo publish -p torrust-tracker-located-error cargo publish -p torrust-tracker-primitives - cargo publish -p torrust-tracker-clock - cargo publish -p torrust-tracker-configuration - cargo publish -p torrust-tracker-torrent-repository cargo publish -p torrust-tracker-test-helpers - cargo publish -p torrust-tracker + cargo publish -p torrust-tracker-torrent-repository diff --git a/Cargo.lock b/Cargo.lock index 0bf1ad572..ec723efff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3899,6 +3899,31 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "torrust-tracker-client" +version = "3.0.0-develop" +dependencies = [ + "anyhow", + "aquatic_udp_protocol", + "bittorrent-primitives", + "bittorrent-tracker-client", + "clap", + "futures", + "hex-literal", + "hyper", + "reqwest", + "serde", + "serde_bencode", + "serde_bytes", + "serde_json", + "thiserror", + "tokio", + "torrust-tracker-configuration", + "tracing", + "tracing-subscriber", + "url", +] + [[package]] name = "torrust-tracker-clock" version = "3.0.0-develop" diff --git a/Cargo.toml b/Cargo.toml index a3d88be92..bc772d08a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -94,6 +94,7 @@ torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "packages/tes [workspace] members = [ + "console/tracker-client", "contrib/bencode", "packages/configuration", "packages/located-error", diff --git a/console/tracker-client/Cargo.toml b/console/tracker-client/Cargo.toml new file mode 100644 index 000000000..c9e951003 --- /dev/null +++ b/console/tracker-client/Cargo.toml @@ -0,0 +1,39 @@ +[package] +description = "A collection of console clients to make requests to BitTorrent trackers." +keywords = ["bittorrent", "client", "tracker"] +license = "LGPL-3.0" +name = "torrust-tracker-client" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +anyhow = "1" +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +bittorrent-tracker-client = { version = "3.0.0-develop", path = "../../packages/tracker-client" } +clap = { version = "4", features = ["derive", "env"] } +futures = "0" +hex-literal = "0" +hyper = "1" +reqwest = { version = "0", features = ["json"] } +serde = { version = "1", features = ["derive"] } +serde_bencode = "0" +serde_bytes = "0" +serde_json = { version = "1", features = ["preserve_order"] } +thiserror = "1" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../../packages/configuration" } +tracing = "0" +tracing-subscriber = { version = "0", features = ["json"] } +url = { version = "2", features = ["serde"] } + +[package.metadata.cargo-machete] +ignored = ["serde_bytes"] diff --git a/console/tracker-client/README.md b/console/tracker-client/README.md new file mode 100644 index 000000000..87722657f --- /dev/null +++ b/console/tracker-client/README.md @@ -0,0 +1,199 @@ +# Torrust Tracker Client + +A collection of console clients to make requests to BitTorrent trackers. + +> **Disclaimer**: This project is actively under development. We’re currently extracting and refining common functionality from the[Torrust Tracker](https://github.com/torrust/torrust-tracker) to make it available to the BitTorrent community in Rust. While these tools are functional, they are not yet ready for use in production or third-party projects. + +There are currently three console clients available: + +- UDP Client +- HTTP Client +- Tracker Checker + +> **Notice**: [Console apps are planned to be merge into a single tracker client in the short-term](https://github.com/torrust/torrust-tracker/discussions/660). + +## UDP Client + +`Announce` request: + +```text +cargo run --bin udp_tracker_client announce udp://127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +``` + +`Announce` response: + +```json +{ + "AnnounceIpv4": { + "transaction_id": -888840697, + "announce_interval": 120, + "leechers": 0, + "seeders": 1, + "peers": [] + } +} +``` + +`Scrape` request: + +```text +cargo run --bin udp_tracker_client scrape udp://127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +``` + +`Scrape` response: + +```json +{ + "Scrape": { + "transaction_id": -888840697, + "torrent_stats": [ + { + "seeders": 1, + "completed": 0, + "leechers": 0 + } + ] + } +} +``` + +## HTTP Client + +`Announce` request: + +```text +cargo run --bin http_tracker_client announce http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +``` + +`Announce` response: + +```json +{ + "complete": 1, + "incomplete": 0, + "interval": 120, + "min interval": 120, + "peers": [] +} +``` + +`Scrape` request: + +```text + cargo run --bin http_tracker_client scrape http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +``` + +`Scrape` response: + +```json +{ + "9c38422213e30bff212b30c360d26f9a02136422": { + "complete": 1, + "downloaded": 1, + "incomplete": 0 + } +} +``` + +## Tracker Checker + +The Tracker Checker is a tool to check the health of a list of trackers. + +```console +TORRUST_CHECKER_CONFIG='{ + "udp_trackers": ["127.0.0.1:6969"], + "http_trackers": ["http://127.0.0.1:7070"], + "health_checks": ["http://127.0.0.1:1212/api/health_check"] + }' cargo run --bin tracker_checker +``` + +Output: + +```json +[ + { + "Udp": { + "Ok": { + "remote_addr": "127.0.0.1:6969", + "results": [ + [ + "Setup", + { + "Ok": null + } + ], + [ + "Connect", + { + "Ok": null + } + ], + [ + "Announce", + { + "Ok": null + } + ], + [ + "Scrape", + { + "Ok": null + } + ] + ] + } + } + }, + { + "Health": { + "Ok": { + "url": "http://127.0.0.1:1212/api/health_check", + "result": { + "Ok": "200 OK" + } + } + } + }, + { + "Http": { + "Ok": { + "url": "http://127.0.0.1:7070/", + "results": [ + [ + "Announce", + { + "Ok": null + } + ], + [ + "Scrape", + { + "Ok": null + } + ] + ] + } + } + } +] +``` + +## License + +**Copyright (c) 2024 The Torrust Developers.** + +This program is free software: you can redistribute it and/or modify it under the terms of the [GNU Lesser General Public License][LGPL_3_0] as published by the [Free Software Foundation][FSF], version 3. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the [GNU Lesser General Public License][LGPL_3_0] for more details. + +You should have received a copy of the *GNU Lesser General Public License* along with this program. If not, see . + +Some files include explicit copyright notices and/or license notices. + +### Legacy Exception + +For prosperity, versions of Torrust BitTorrent Tracker Client that are older than five years are automatically granted the [MIT-0][MIT_0] license in addition to the existing [LGPL-3.0-only][LGPL_3_0] license. + +[LGPL_3_0]: ./LICENSE +[MIT_0]: ./docs/licenses/LICENSE-MIT_0 +[FSF]: https://www.fsf.org/ diff --git a/console/tracker-client/docs/licenses/LICENSE-MIT_0 b/console/tracker-client/docs/licenses/LICENSE-MIT_0 new file mode 100644 index 000000000..fc06cc4fe --- /dev/null +++ b/console/tracker-client/docs/licenses/LICENSE-MIT_0 @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/console/tracker-client/src/bin/http_tracker_client.rs b/console/tracker-client/src/bin/http_tracker_client.rs new file mode 100644 index 000000000..be1b4821d --- /dev/null +++ b/console/tracker-client/src/bin/http_tracker_client.rs @@ -0,0 +1,7 @@ +//! Program to make request to HTTP trackers. +use torrust_tracker_client::console::clients::http::app; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + app::run().await +} diff --git a/console/tracker-client/src/bin/tracker_checker.rs b/console/tracker-client/src/bin/tracker_checker.rs new file mode 100644 index 000000000..3ff78eec1 --- /dev/null +++ b/console/tracker-client/src/bin/tracker_checker.rs @@ -0,0 +1,7 @@ +//! Program to check running trackers. +use torrust_tracker_client::console::clients::checker::app; + +#[tokio::main] +async fn main() { + app::run().await.expect("Some checks fail"); +} diff --git a/console/tracker-client/src/bin/udp_tracker_client.rs b/console/tracker-client/src/bin/udp_tracker_client.rs new file mode 100644 index 000000000..caf5ab0dc --- /dev/null +++ b/console/tracker-client/src/bin/udp_tracker_client.rs @@ -0,0 +1,7 @@ +//! Program to make request to UDP trackers. +use torrust_tracker_client::console::clients::udp::app; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + app::run().await +} diff --git a/console/tracker-client/src/console/clients/checker/app.rs b/console/tracker-client/src/console/clients/checker/app.rs new file mode 100644 index 000000000..395f65df9 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/app.rs @@ -0,0 +1,120 @@ +//! Program to run checks against running trackers. +//! +//! Run providing a config file path: +//! +//! ```text +//! cargo run --bin tracker_checker -- --config-path "./share/default/config/tracker_checker.json" +//! TORRUST_CHECKER_CONFIG_PATH="./share/default/config/tracker_checker.json" cargo run --bin tracker_checker +//! ``` +//! +//! Run providing the configuration: +//! +//! ```text +//! TORRUST_CHECKER_CONFIG=$(cat "./share/default/config/tracker_checker.json") cargo run --bin tracker_checker +//! ``` +//! +//! Another real example to test the Torrust demo tracker: +//! +//! ```text +//! TORRUST_CHECKER_CONFIG='{ +//! "udp_trackers": ["144.126.245.19:6969"], +//! "http_trackers": ["https://tracker.torrust-demo.com"], +//! "health_checks": ["https://tracker.torrust-demo.com/api/health_check"] +//! }' cargo run --bin tracker_checker +//! ``` +//! +//! The output should be something like the following: +//! +//! ```json +//! { +//! "udp_trackers": [ +//! { +//! "url": "144.126.245.19:6969", +//! "status": { +//! "code": "ok", +//! "message": "" +//! } +//! } +//! ], +//! "http_trackers": [ +//! { +//! "url": "https://tracker.torrust-demo.com/", +//! "status": { +//! "code": "ok", +//! "message": "" +//! } +//! } +//! ], +//! "health_checks": [ +//! { +//! "url": "https://tracker.torrust-demo.com/api/health_check", +//! "status": { +//! "code": "ok", +//! "message": "" +//! } +//! } +//! ] +//! } +//! ``` +use std::path::PathBuf; +use std::sync::Arc; + +use anyhow::{Context, Result}; +use clap::Parser; +use tracing::level_filters::LevelFilter; + +use super::config::Configuration; +use super::console::Console; +use super::service::{CheckResult, Service}; +use crate::console::clients::checker::config::parse_from_json; + +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + /// Path to the JSON configuration file. + #[clap(short, long, env = "TORRUST_CHECKER_CONFIG_PATH")] + config_path: Option, + + /// Direct configuration content in JSON. + #[clap(env = "TORRUST_CHECKER_CONFIG", hide_env_values = true)] + config_content: Option, +} + +/// # Errors +/// +/// Will return an error if the configuration was not provided. +pub async fn run() -> Result> { + tracing_stdout_init(LevelFilter::INFO); + + 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.context("it should run the check tasks") +} + +fn tracing_stdout_init(filter: LevelFilter) { + tracing_subscriber::fmt().with_max_level(filter).init(); + tracing::debug!("Logging initialized"); +} + +fn setup_config(args: Args) -> Result { + match (args.config_path, args.config_content) { + (Some(config_path), _) => load_config_from_file(&config_path), + (_, Some(config_content)) => parse_from_json(&config_content).context("invalid config format"), + _ => Err(anyhow::anyhow!("no configuration provided")), + } +} + +fn load_config_from_file(path: &PathBuf) -> Result { + let file_content = std::fs::read_to_string(path).with_context(|| format!("can't read config file {path:?}"))?; + + parse_from_json(&file_content).context("invalid config format") +} diff --git a/console/tracker-client/src/console/clients/checker/checks/health.rs b/console/tracker-client/src/console/clients/checker/checks/health.rs new file mode 100644 index 000000000..b1fb79148 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/checks/health.rs @@ -0,0 +1,77 @@ +use std::sync::Arc; +use std::time::Duration; + +use anyhow::Result; +use hyper::StatusCode; +use reqwest::{Client as HttpClient, Response}; +use serde::Serialize; +use thiserror::Error; +use url::Url; + +#[derive(Debug, Clone, Error, Serialize)] +#[serde(into = "String")] +pub enum Error { + #[error("Failed to Build a Http Client: {err:?}")] + ClientBuildingError { err: Arc }, + #[error("Heath check failed to get a response: {err:?}")] + ResponseError { err: Arc }, + #[error("Http check returned a non-success code: \"{code}\" with the response: \"{response:?}\"")] + UnsuccessfulResponse { code: StatusCode, response: Arc }, +} + +impl From for String { + fn from(value: Error) -> Self { + value.to_string() + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct Checks { + url: Url, + result: Result, +} + +pub async fn run(health_checks: Vec, timeout: Duration) -> Vec> { + let mut results = Vec::default(); + + tracing::debug!("Health checks ..."); + + for url in health_checks { + let result = match run_health_check(url.clone(), timeout).await { + Ok(response) => Ok(response.status().to_string()), + Err(err) => Err(err), + }; + + let check = Checks { url, result }; + + if check.result.is_err() { + results.push(Err(check)); + } else { + results.push(Ok(check)); + } + } + + results +} + +async fn run_health_check(url: Url, timeout: Duration) -> Result { + let client = HttpClient::builder() + .timeout(timeout) + .build() + .map_err(|e| Error::ClientBuildingError { err: e.into() })?; + + let response = client + .get(url.clone()) + .send() + .await + .map_err(|e| Error::ResponseError { err: e.into() })?; + + if response.status().is_success() { + Ok(response) + } else { + Err(Error::UnsuccessfulResponse { + code: response.status(), + response: response.into(), + }) + } +} diff --git a/console/tracker-client/src/console/clients/checker/checks/http.rs b/console/tracker-client/src/console/clients/checker/checks/http.rs new file mode 100644 index 000000000..0fd37ca48 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/checks/http.rs @@ -0,0 +1,104 @@ +use std::str::FromStr as _; +use std::time::Duration; + +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_client::http::client::responses::announce::Announce; +use bittorrent_tracker_client::http::client::responses::scrape; +use bittorrent_tracker_client::http::client::{requests, Client}; +use serde::Serialize; +use url::Url; + +use crate::console::clients::http::Error; + +#[derive(Debug, Clone, Serialize)] +pub struct Checks { + url: Url, + results: Vec<(Check, Result<(), Error>)>, +} + +#[derive(Debug, Clone, Serialize)] +pub enum Check { + Announce, + Scrape, +} + +pub async fn run(http_trackers: Vec, timeout: Duration) -> Vec> { + let mut results = Vec::default(); + + tracing::debug!("HTTP trackers ..."); + + for ref url in http_trackers { + let mut base_url = url.clone(); + base_url.set_path(""); + + let mut checks = Checks { + url: url.clone(), + results: Vec::default(), + }; + + // Announce + { + let check = check_http_announce(&base_url, timeout).await.map(|_| ()); + + checks.results.push((Check::Announce, check)); + } + + // Scrape + { + let check = check_http_scrape(&base_url, timeout).await.map(|_| ()); + + checks.results.push((Check::Scrape, check)); + } + + if checks.results.iter().any(|f| f.1.is_err()) { + results.push(Err(checks)); + } else { + results.push(Ok(checks)); + } + } + + results +} + +async fn check_http_announce(url: &Url, timeout: Duration) -> Result { + let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // # DevSkim: ignore DS173237 + let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); + + let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; + + let response = client + .announce( + &requests::announce::QueryBuilder::with_default_values() + .with_info_hash(&info_hash) + .query(), + ) + .await + .map_err(|err| Error::HttpClientError { err })?; + + let response = response.bytes().await.map_err(|e| Error::ResponseError { err: e.into() })?; + + let response = serde_bencode::from_bytes::(&response).map_err(|e| Error::ParseBencodeError { + data: response, + err: e.into(), + })?; + + Ok(response) +} + +async fn check_http_scrape(url: &Url, timeout: Duration) -> Result { + let info_hashes: Vec = vec!["9c38422213e30bff212b30c360d26f9a02136422".to_string()]; // # DevSkim: ignore DS173237 + let query = requests::scrape::Query::try_from(info_hashes).expect("a valid array of info-hashes is required"); + + let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; + + let response = client.scrape(&query).await.map_err(|err| Error::HttpClientError { err })?; + + let response = response.bytes().await.map_err(|e| Error::ResponseError { err: e.into() })?; + + let response = scrape::Response::try_from_bencoded(&response).map_err(|e| Error::BencodeParseError { + data: response, + err: e.into(), + })?; + + Ok(response) +} diff --git a/console/tracker-client/src/console/clients/checker/checks/mod.rs b/console/tracker-client/src/console/clients/checker/checks/mod.rs new file mode 100644 index 000000000..f8b03f749 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/checks/mod.rs @@ -0,0 +1,4 @@ +pub mod health; +pub mod http; +pub mod structs; +pub mod udp; diff --git a/console/tracker-client/src/console/clients/checker/checks/structs.rs b/console/tracker-client/src/console/clients/checker/checks/structs.rs new file mode 100644 index 000000000..d28e20c04 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/checks/structs.rs @@ -0,0 +1,12 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub struct Status { + pub code: String, + pub message: String, +} +#[derive(Serialize, Deserialize)] +pub struct CheckerOutput { + pub url: String, + pub status: Status, +} diff --git a/console/tracker-client/src/console/clients/checker/checks/udp.rs b/console/tracker-client/src/console/clients/checker/checks/udp.rs new file mode 100644 index 000000000..21bdcd1b7 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/checks/udp.rs @@ -0,0 +1,134 @@ +use std::net::SocketAddr; +use std::time::Duration; + +use aquatic_udp_protocol::TransactionId; +use hex_literal::hex; +use serde::Serialize; +use url::Url; + +use crate::console::clients::udp::checker::Client; +use crate::console::clients::udp::Error; + +#[derive(Debug, Clone, Serialize)] +pub struct Checks { + remote_addr: SocketAddr, + results: Vec<(Check, Result<(), Error>)>, +} + +#[derive(Debug, Clone, Serialize)] +pub enum Check { + Setup, + Connect, + Announce, + Scrape, +} + +#[allow(clippy::missing_panics_doc)] +pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec> { + let mut results = Vec::default(); + + tracing::debug!("UDP trackers ..."); + + let info_hash = aquatic_udp_protocol::InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237 + + for remote_url in udp_trackers { + let remote_addr = resolve_socket_addr(&remote_url); + + let mut checks = Checks { + remote_addr, + results: Vec::default(), + }; + + tracing::debug!("UDP tracker: {:?}", remote_url); + + // Setup + let client = match Client::new(remote_addr, timeout).await { + Ok(client) => { + checks.results.push((Check::Setup, Ok(()))); + client + } + Err(err) => { + checks.results.push((Check::Setup, Err(err))); + results.push(Err(checks)); + continue; + } + }; + + let transaction_id = TransactionId::new(1); + + // Connect Remote + let connection_id = match client.send_connection_request(transaction_id).await { + Ok(connection_id) => { + checks.results.push((Check::Connect, Ok(()))); + connection_id + } + Err(err) => { + checks.results.push((Check::Connect, Err(err))); + results.push(Err(checks)); + continue; + } + }; + + // Announce + { + let check = client + .send_announce_request(transaction_id, connection_id, info_hash.into()) + .await + .map(|_| ()); + + checks.results.push((Check::Announce, check)); + } + + // Scrape + { + let check = client + .send_scrape_request(connection_id, transaction_id, &[info_hash.into()]) + .await + .map(|_| ()); + + checks.results.push((Check::Scrape, check)); + } + + if checks.results.iter().any(|f| f.1.is_err()) { + results.push(Err(checks)); + } else { + results.push(Ok(checks)); + } + } + + results +} + +fn resolve_socket_addr(url: &Url) -> SocketAddr { + let socket_addr = url.socket_addrs(|| None).unwrap(); + *socket_addr.first().unwrap() +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + + use url::Url; + + use crate::console::clients::checker::checks::udp::resolve_socket_addr; + + #[test] + fn it_should_resolve_the_socket_address_for_udp_scheme_urls_containing_a_domain() { + let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); + + assert!( + socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) + || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) + ); + } + + #[test] + fn it_should_resolve_the_socket_address_for_udp_scheme_urls_containing_an_ip() { + let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); + + assert!( + socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) + || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) + ); + } +} diff --git a/console/tracker-client/src/console/clients/checker/config.rs b/console/tracker-client/src/console/clients/checker/config.rs new file mode 100644 index 000000000..154dcae85 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/config.rs @@ -0,0 +1,282 @@ +use std::error::Error; +use std::fmt; + +use reqwest::Url as ServiceUrl; +use serde::Deserialize; + +/// It parses the configuration from a JSON format. +/// +/// # Errors +/// +/// Will return an error if the configuration is not valid. +/// +/// # Panics +/// +/// Will panic if unable to read the configuration file. +pub fn parse_from_json(json: &str) -> Result { + let plain_config: PlainConfiguration = serde_json::from_str(json).map_err(ConfigurationError::JsonParseError)?; + Configuration::try_from(plain_config) +} + +/// DTO for the configuration to serialize/deserialize configuration. +/// +/// Configuration does not need to be valid. +#[derive(Deserialize)] +struct PlainConfiguration { + pub udp_trackers: Vec, + pub http_trackers: Vec, + pub health_checks: Vec, +} + +/// Validated configuration +pub struct Configuration { + pub udp_trackers: Vec, + pub http_trackers: Vec, + pub health_checks: Vec, +} + +#[derive(Debug)] +pub enum ConfigurationError { + JsonParseError(serde_json::Error), + InvalidUdpAddress(std::net::AddrParseError), + InvalidUrl(url::ParseError), +} + +impl Error for ConfigurationError {} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ConfigurationError::JsonParseError(e) => write!(f, "JSON parse error: {e}"), + ConfigurationError::InvalidUdpAddress(e) => write!(f, "Invalid UDP address: {e}"), + ConfigurationError::InvalidUrl(e) => write!(f, "Invalid URL: {e}"), + } + } +} + +impl TryFrom for Configuration { + type Error = ConfigurationError; + + fn try_from(plain_config: PlainConfiguration) -> Result { + let udp_trackers = plain_config + .udp_trackers + .into_iter() + .map(|s| if s.starts_with("udp://") { s } else { format!("udp://{s}") }) + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) + .collect::, _>>()?; + + let http_trackers = plain_config + .http_trackers + .into_iter() + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) + .collect::, _>>()?; + + let health_checks = plain_config + .health_checks + .into_iter() + .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) + .collect::, _>>()?; + + Ok(Configuration { + udp_trackers, + http_trackers, + health_checks, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn configuration_should_be_build_from_plain_serializable_configuration() { + let dto = PlainConfiguration { + udp_trackers: vec!["udp://127.0.0.1:8080".to_string()], + http_trackers: vec!["http://127.0.0.1:8080".to_string()], + health_checks: vec!["http://127.0.0.1:8080/health".to_string()], + }; + + let config = Configuration::try_from(dto).expect("A valid configuration"); + + assert_eq!(config.udp_trackers, vec![ServiceUrl::parse("udp://127.0.0.1:8080").unwrap()]); + + assert_eq!( + config.http_trackers, + vec![ServiceUrl::parse("http://127.0.0.1:8080").unwrap()] + ); + + assert_eq!( + config.health_checks, + vec![ServiceUrl::parse("http://127.0.0.1:8080/health").unwrap()] + ); + } + + mod building_configuration_from_plain_configuration_for { + + mod udp_trackers { + use crate::console::clients::checker::config::{Configuration, PlainConfiguration, ServiceUrl}; + + /* The plain configuration should allow UDP URLs with: + + - IP or domain. + - With or without scheme. + - With or without `announce` suffix. + - With or without `/` at the end of the authority section (with empty path). + + For example: + + 127.0.0.1:6969 + 127.0.0.1:6969/ + 127.0.0.1:6969/announce + + localhost:6969 + localhost:6969/ + localhost:6969/announce + + udp://127.0.0.1:6969 + udp://127.0.0.1:6969/ + udp://127.0.0.1:6969/announce + + udp://localhost:6969 + udp://localhost:6969/ + udp://localhost:6969/announce + + */ + + #[test] + fn it_should_fail_when_a_tracker_udp_url_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["invalid URL".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + assert!(Configuration::try_from(plain_config).is_err()); + } + + #[test] + fn it_should_add_the_udp_scheme_to_the_udp_url_when_it_is_missing() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:6969".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!(config.udp_trackers[0], "udp://127.0.0.1:6969".parse::().unwrap()); + } + + #[test] + fn it_should_allow_using_domains() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["udp://localhost:6969".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!(config.udp_trackers[0], "udp://localhost:6969".parse::().unwrap()); + } + + #[test] + fn it_should_allow_the_url_to_have_an_empty_path() { + let plain_config = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:6969/".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!(config.udp_trackers[0], "udp://127.0.0.1:6969/".parse::().unwrap()); + } + + #[test] + fn it_should_allow_the_url_to_contain_a_path() { + // This is the common format for UDP tracker URLs: + // udp://domain.com:6969/announce + + let plain_config = PlainConfiguration { + udp_trackers: vec!["127.0.0.1:6969/announce".to_string()], + http_trackers: vec![], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!( + config.udp_trackers[0], + "udp://127.0.0.1:6969/announce".parse::().unwrap() + ); + } + } + + mod http_trackers { + use crate::console::clients::checker::config::{Configuration, PlainConfiguration, ServiceUrl}; + + #[test] + fn it_should_fail_when_a_tracker_http_url_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec!["invalid URL".to_string()], + health_checks: vec![], + }; + + assert!(Configuration::try_from(plain_config).is_err()); + } + + #[test] + fn it_should_allow_the_url_to_contain_a_path() { + // This is the common format for HTTP tracker URLs: + // http://domain.com:7070/announce + + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec!["http://127.0.0.1:7070/announce".to_string()], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!( + config.http_trackers[0], + "http://127.0.0.1:7070/announce".parse::().unwrap() + ); + } + + #[test] + fn it_should_allow_the_url_to_contain_an_empty_path() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec!["http://127.0.0.1:7070/".to_string()], + health_checks: vec![], + }; + + let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); + + assert_eq!( + config.http_trackers[0], + "http://127.0.0.1:7070/".parse::().unwrap() + ); + } + } + + mod health_checks { + use crate::console::clients::checker::config::{Configuration, PlainConfiguration}; + + #[test] + fn it_should_fail_when_a_health_check_http_url_is_invalid() { + let plain_config = PlainConfiguration { + udp_trackers: vec![], + http_trackers: vec![], + health_checks: vec!["invalid URL".to_string()], + }; + + assert!(Configuration::try_from(plain_config).is_err()); + } + } + } +} diff --git a/console/tracker-client/src/console/clients/checker/console.rs b/console/tracker-client/src/console/clients/checker/console.rs new file mode 100644 index 000000000..b55c559fc --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/console.rs @@ -0,0 +1,38 @@ +use super::printer::{Printer, CLEAR_SCREEN}; + +pub struct Console {} + +impl Default for Console { + fn default() -> Self { + Self::new() + } +} + +impl Console { + #[must_use] + pub fn new() -> Self { + Self {} + } +} + +impl Printer for Console { + fn clear(&self) { + self.print(CLEAR_SCREEN); + } + + fn print(&self, output: &str) { + print!("{}", &output); + } + + fn eprint(&self, output: &str) { + eprint!("{}", &output); + } + + fn println(&self, output: &str) { + println!("{}", &output); + } + + fn eprintln(&self, output: &str) { + eprintln!("{}", &output); + } +} diff --git a/console/tracker-client/src/console/clients/checker/logger.rs b/console/tracker-client/src/console/clients/checker/logger.rs new file mode 100644 index 000000000..50e97189f --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/logger.rs @@ -0,0 +1,72 @@ +use std::cell::RefCell; + +use super::printer::{Printer, CLEAR_SCREEN}; + +pub struct Logger { + output: RefCell, +} + +impl Default for Logger { + fn default() -> Self { + Self::new() + } +} + +impl Logger { + #[must_use] + pub fn new() -> Self { + Self { + output: RefCell::new(String::new()), + } + } + + pub fn log(&self) -> String { + self.output.borrow().clone() + } +} + +impl Printer for Logger { + fn clear(&self) { + self.print(CLEAR_SCREEN); + } + + fn print(&self, output: &str) { + *self.output.borrow_mut() = format!("{}{}", self.output.borrow(), &output); + } + + fn eprint(&self, output: &str) { + *self.output.borrow_mut() = format!("{}{}", self.output.borrow(), &output); + } + + fn println(&self, output: &str) { + self.print(&format!("{}/n", &output)); + } + + fn eprintln(&self, output: &str) { + self.eprint(&format!("{}/n", &output)); + } +} + +#[cfg(test)] +mod tests { + use crate::console::clients::checker::logger::Logger; + use crate::console::clients::checker::printer::{Printer, CLEAR_SCREEN}; + + #[test] + fn should_capture_the_clear_screen_command() { + let console_logger = Logger::new(); + + console_logger.clear(); + + assert_eq!(CLEAR_SCREEN, console_logger.log()); + } + + #[test] + fn should_capture_the_print_command_output() { + let console_logger = Logger::new(); + + console_logger.print("OUTPUT"); + + assert_eq!("OUTPUT", console_logger.log()); + } +} diff --git a/console/tracker-client/src/console/clients/checker/mod.rs b/console/tracker-client/src/console/clients/checker/mod.rs new file mode 100644 index 000000000..d26a4a686 --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/mod.rs @@ -0,0 +1,7 @@ +pub mod app; +pub mod checks; +pub mod config; +pub mod console; +pub mod logger; +pub mod printer; +pub mod service; diff --git a/console/tracker-client/src/console/clients/checker/printer.rs b/console/tracker-client/src/console/clients/checker/printer.rs new file mode 100644 index 000000000..d590dfedb --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/printer.rs @@ -0,0 +1,9 @@ +pub const CLEAR_SCREEN: &str = "\x1B[2J\x1B[1;1H"; + +pub trait Printer { + fn clear(&self); + fn print(&self, output: &str); + fn eprint(&self, output: &str); + fn println(&self, output: &str); + fn eprintln(&self, output: &str); +} diff --git a/console/tracker-client/src/console/clients/checker/service.rs b/console/tracker-client/src/console/clients/checker/service.rs new file mode 100644 index 000000000..acd312d8c --- /dev/null +++ b/console/tracker-client/src/console/clients/checker/service.rs @@ -0,0 +1,62 @@ +use std::sync::Arc; + +use futures::FutureExt as _; +use serde::Serialize; +use tokio::task::{JoinError, JoinSet}; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; + +use super::checks::{health, http, udp}; +use super::config::Configuration; +use super::console::Console; +use crate::console::clients::checker::printer::Printer; + +pub struct Service { + pub(crate) config: Arc, + pub(crate) console: Console, +} + +#[derive(Debug, Clone, Serialize)] +pub enum CheckResult { + Udp(Result), + Http(Result), + Health(Result), +} + +impl Service { + /// # Errors + /// + /// It will return an error if some of the tests panic or otherwise fail to run. + /// On success it will return a vector of `Ok(())` of [`CheckResult`]. + /// + /// # Panics + /// + /// It would panic if `serde_json` produces invalid json for the `to_string_pretty` function. + pub async fn run_checks(self) -> Result, JoinError> { + tracing::info!("Running checks for trackers ..."); + + let mut check_results = Vec::default(); + + let mut checks = JoinSet::new(); + checks.spawn( + udp::run(self.config.udp_trackers.clone(), DEFAULT_TIMEOUT).map(|mut f| f.drain(..).map(CheckResult::Udp).collect()), + ); + checks.spawn( + http::run(self.config.http_trackers.clone(), DEFAULT_TIMEOUT) + .map(|mut f| f.drain(..).map(CheckResult::Http).collect()), + ); + checks.spawn( + health::run(self.config.health_checks.clone(), DEFAULT_TIMEOUT) + .map(|mut f| f.drain(..).map(CheckResult::Health).collect()), + ); + + while let Some(results) = checks.join_next().await { + check_results.append(&mut results?); + } + + let json_output = serde_json::json!(check_results); + self.console + .println(&serde_json::to_string_pretty(&json_output).expect("it should consume valid json")); + + Ok(check_results) + } +} diff --git a/console/tracker-client/src/console/clients/http/app.rs b/console/tracker-client/src/console/clients/http/app.rs new file mode 100644 index 000000000..105b18bff --- /dev/null +++ b/console/tracker-client/src/console/clients/http/app.rs @@ -0,0 +1,101 @@ +//! HTTP Tracker client: +//! +//! Examples: +//! +//! `Announce` request: +//! +//! ```text +//! cargo run --bin http_tracker_client announce http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! `Scrape` request: +//! +//! ```text +//! cargo run --bin http_tracker_client scrape http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +use std::str::FromStr; +use std::time::Duration; + +use anyhow::Context; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_client::http::client::requests::announce::QueryBuilder; +use bittorrent_tracker_client::http::client::responses::announce::Announce; +use bittorrent_tracker_client::http::client::responses::scrape; +use bittorrent_tracker_client::http::client::{requests, Client}; +use clap::{Parser, Subcommand}; +use reqwest::Url; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand, Debug)] +enum Command { + Announce { tracker_url: String, info_hash: String }, + Scrape { tracker_url: String, info_hashes: Vec }, +} + +/// # Errors +/// +/// Will return an error if the command fails. +pub async fn run() -> anyhow::Result<()> { + let args = Args::parse(); + + match args.command { + Command::Announce { tracker_url, info_hash } => { + announce_command(tracker_url, info_hash, DEFAULT_TIMEOUT).await?; + } + Command::Scrape { + tracker_url, + info_hashes, + } => { + scrape_command(&tracker_url, &info_hashes, DEFAULT_TIMEOUT).await?; + } + } + + Ok(()) +} + +async fn announce_command(tracker_url: String, info_hash: String, timeout: Duration) -> anyhow::Result<()> { + let base_url = Url::parse(&tracker_url).context("failed to parse HTTP tracker base URL")?; + let info_hash = + InfoHash::from_str(&info_hash).expect("Invalid infohash. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); + + let response = Client::new(base_url, timeout)? + .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) + .await?; + + let body = response.bytes().await?; + + let announce_response: Announce = serde_bencode::from_bytes(&body) + .unwrap_or_else(|_| panic!("response body should be a valid announce response, got: \"{:#?}\"", &body)); + + let json = serde_json::to_string(&announce_response).context("failed to serialize scrape response into JSON")?; + + println!("{json}"); + + Ok(()) +} + +async fn scrape_command(tracker_url: &str, info_hashes: &[String], timeout: Duration) -> anyhow::Result<()> { + let base_url = Url::parse(tracker_url).context("failed to parse HTTP tracker base URL")?; + + let query = requests::scrape::Query::try_from(info_hashes).context("failed to parse infohashes")?; + + let response = Client::new(base_url, timeout)?.scrape(&query).await?; + + let body = response.bytes().await?; + + let scrape_response = scrape::Response::try_from_bencoded(&body) + .unwrap_or_else(|_| panic!("response body should be a valid scrape response, got: \"{:#?}\"", &body)); + + let json = serde_json::to_string(&scrape_response).context("failed to serialize scrape response into JSON")?; + + println!("{json}"); + + Ok(()) +} diff --git a/console/tracker-client/src/console/clients/http/mod.rs b/console/tracker-client/src/console/clients/http/mod.rs new file mode 100644 index 000000000..917c94fa8 --- /dev/null +++ b/console/tracker-client/src/console/clients/http/mod.rs @@ -0,0 +1,35 @@ +use std::sync::Arc; + +use bittorrent_tracker_client::http::client::responses::scrape::BencodeParseError; +use serde::Serialize; +use thiserror::Error; + +pub mod app; + +#[derive(Debug, Clone, Error, Serialize)] +#[serde(into = "String")] +pub enum Error { + #[error("Http request did not receive a response within the timeout: {err:?}")] + HttpClientError { + err: bittorrent_tracker_client::http::client::Error, + }, + #[error("Http failed to get a response at all: {err:?}")] + ResponseError { err: Arc }, + #[error("Failed to deserialize the bencoded response data with the error: \"{err:?}\"")] + ParseBencodeError { + data: hyper::body::Bytes, + err: Arc, + }, + + #[error("Failed to deserialize the bencoded response data with the error: \"{err:?}\"")] + BencodeParseError { + data: hyper::body::Bytes, + err: Arc, + }, +} + +impl From for String { + fn from(value: Error) -> Self { + value.to_string() + } +} diff --git a/console/tracker-client/src/console/clients/mod.rs b/console/tracker-client/src/console/clients/mod.rs new file mode 100644 index 000000000..8492f8ba5 --- /dev/null +++ b/console/tracker-client/src/console/clients/mod.rs @@ -0,0 +1,4 @@ +//! Console clients. +pub mod checker; +pub mod http; +pub mod udp; diff --git a/console/tracker-client/src/console/clients/udp/app.rs b/console/tracker-client/src/console/clients/udp/app.rs new file mode 100644 index 000000000..a2736c365 --- /dev/null +++ b/console/tracker-client/src/console/clients/udp/app.rs @@ -0,0 +1,208 @@ +//! UDP Tracker client: +//! +//! Examples: +//! +//! Announce request: +//! +//! ```text +//! cargo run --bin udp_tracker_client announce 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! Announce response: +//! +//! ```json +//! { +//! "transaction_id": -888840697 +//! "announce_interval": 120, +//! "leechers": 0, +//! "seeders": 1, +//! "peers": [ +//! "123.123.123.123:51289" +//! ], +//! } +//! ``` +//! +//! Scrape request: +//! +//! ```text +//! cargo run --bin udp_tracker_client scrape 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! Scrape response: +//! +//! ```json +//! { +//! "transaction_id": -888840697, +//! "torrent_stats": [ +//! { +//! "completed": 0, +//! "leechers": 0, +//! "seeders": 0 +//! }, +//! { +//! "completed": 0, +//! "leechers": 0, +//! "seeders": 0 +//! } +//! ] +//! } +//! ``` +//! +//! You can use an URL with instead of the socket address. For example: +//! +//! ```text +//! cargo run --bin udp_tracker_client scrape udp://localhost:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! cargo run --bin udp_tracker_client scrape udp://localhost:6969/scrape 9c38422213e30bff212b30c360d26f9a02136422 | jq +//! ``` +//! +//! The protocol (`udp://`) in the URL is mandatory. The path (`\scrape`) is optional. It always uses `\scrape`. +use std::net::{SocketAddr, ToSocketAddrs}; +use std::str::FromStr; + +use anyhow::Context; +use aquatic_udp_protocol::{Response, TransactionId}; +use bittorrent_primitives::info_hash::InfoHash as TorrustInfoHash; +use clap::{Parser, Subcommand}; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; +use tracing::level_filters::LevelFilter; +use url::Url; + +use super::Error; +use crate::console::clients::udp::checker; +use crate::console::clients::udp::responses::dto::SerializableResponse; +use crate::console::clients::udp::responses::json::ToJson; + +const RANDOM_TRANSACTION_ID: i32 = -888_840_697; + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand, Debug)] +enum Command { + Announce { + #[arg(value_parser = parse_socket_addr)] + tracker_socket_addr: SocketAddr, + #[arg(value_parser = parse_info_hash)] + info_hash: TorrustInfoHash, + }, + Scrape { + #[arg(value_parser = parse_socket_addr)] + tracker_socket_addr: SocketAddr, + #[arg(value_parser = parse_info_hash, num_args = 1..=74, value_delimiter = ' ')] + info_hashes: Vec, + }, +} + +/// # Errors +/// +/// Will return an error if the command fails. +/// +/// +pub async fn run() -> anyhow::Result<()> { + tracing_stdout_init(LevelFilter::INFO); + + let args = Args::parse(); + + let response = match args.command { + Command::Announce { + tracker_socket_addr: remote_addr, + info_hash, + } => handle_announce(remote_addr, &info_hash).await?, + Command::Scrape { + tracker_socket_addr: remote_addr, + info_hashes, + } => handle_scrape(remote_addr, &info_hashes).await?, + }; + + let response: SerializableResponse = response.into(); + let response_json = response.to_json_string()?; + + print!("{response_json}"); + + Ok(()) +} + +fn tracing_stdout_init(filter: LevelFilter) { + tracing_subscriber::fmt().with_max_level(filter).init(); + tracing::debug!("Logging initialized"); +} + +async fn handle_announce(remote_addr: SocketAddr, info_hash: &TorrustInfoHash) -> Result { + let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); + + let client = checker::Client::new(remote_addr, DEFAULT_TIMEOUT).await?; + + let connection_id = client.send_connection_request(transaction_id).await?; + + client.send_announce_request(transaction_id, connection_id, *info_hash).await +} + +async fn handle_scrape(remote_addr: SocketAddr, info_hashes: &[TorrustInfoHash]) -> Result { + let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); + + let client = checker::Client::new(remote_addr, DEFAULT_TIMEOUT).await?; + + let connection_id = client.send_connection_request(transaction_id).await?; + + client.send_scrape_request(connection_id, transaction_id, info_hashes).await +} + +fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { + tracing::debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); + + // Check if the address is a valid URL. If so, extract the host and port. + let resolved_addr = if let Ok(url) = Url::parse(tracker_socket_addr_str) { + tracing::debug!("Tracker socket address URL: {url:?}"); + + let host = url + .host_str() + .with_context(|| format!("invalid host in URL: `{tracker_socket_addr_str}`"))? + .to_owned(); + + let port = url + .port() + .with_context(|| format!("port not found in URL: `{tracker_socket_addr_str}`"))? + .to_owned(); + + (host, port) + } else { + // If not a URL, assume it's a host:port pair. + + let parts: Vec<&str> = tracker_socket_addr_str.split(':').collect(); + + if parts.len() != 2 { + return Err(anyhow::anyhow!( + "invalid address format: `{}`. Expected format is host:port", + tracker_socket_addr_str + )); + } + + let host = parts[0].to_owned(); + + let port = parts[1] + .parse::() + .with_context(|| format!("invalid port: `{}`", parts[1]))? + .to_owned(); + + (host, port) + }; + + tracing::debug!("Resolved address: {resolved_addr:#?}"); + + // Perform DNS resolution. + let socket_addrs: Vec<_> = resolved_addr.to_socket_addrs()?.collect(); + if socket_addrs.is_empty() { + Err(anyhow::anyhow!("DNS resolution failed for `{}`", tracker_socket_addr_str)) + } else { + Ok(socket_addrs[0]) + } +} + +fn parse_info_hash(info_hash_str: &str) -> anyhow::Result { + TorrustInfoHash::from_str(info_hash_str) + .map_err(|e| anyhow::Error::msg(format!("failed to parse info-hash `{info_hash_str}`: {e:?}"))) +} diff --git a/console/tracker-client/src/console/clients/udp/checker.rs b/console/tracker-client/src/console/clients/udp/checker.rs new file mode 100644 index 000000000..bf6b49782 --- /dev/null +++ b/console/tracker-client/src/console/clients/udp/checker.rs @@ -0,0 +1,177 @@ +use std::net::{Ipv4Addr, SocketAddr}; +use std::num::NonZeroU16; +use std::time::Duration; + +use aquatic_udp_protocol::common::InfoHash; +use aquatic_udp_protocol::{ + AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, + PeerId, PeerKey, Port, Response, ScrapeRequest, TransactionId, +}; +use bittorrent_primitives::info_hash::InfoHash as TorrustInfoHash; +use bittorrent_tracker_client::udp::client::UdpTrackerClient; + +use super::Error; + +/// A UDP Tracker client to make test requests (checks). +#[derive(Debug)] +pub struct Client { + client: UdpTrackerClient, +} + +impl Client { + /// Creates a new `[Client]` for checking a UDP Tracker Service + /// + /// # Errors + /// + /// It will error if unable to bind and connect to the udp remote address. + /// + pub async fn new(remote_addr: SocketAddr, timeout: Duration) -> Result { + let client = UdpTrackerClient::new(remote_addr, timeout) + .await + .map_err(|err| Error::UnableToBindAndConnect { remote_addr, err })?; + + Ok(Self { client }) + } + + /// Returns the local addr of this [`Client`]. + /// + /// # Errors + /// + /// This function will return an error if the socket is somehow not bound. + pub fn local_addr(&self) -> std::io::Result { + self.client.client.socket.local_addr() + } + + /// Sends a connection request to the UDP Tracker server. + /// + /// # Errors + /// + /// Will return and error if + /// + /// - It can't connect to the remote UDP socket. + /// - It can't make a connection request successfully to the remote UDP + /// server (after successfully connecting to the remote UDP socket). + /// + /// # Panics + /// + /// Will panic if it receives an unexpected response. + pub async fn send_connection_request(&self, transaction_id: TransactionId) -> Result { + tracing::debug!("Sending connection request with transaction id: {transaction_id:#?}"); + + let connect_request = ConnectRequest { transaction_id }; + + let _ = self + .client + .send(connect_request.into()) + .await + .map_err(|err| Error::UnableToSendConnectionRequest { err })?; + + let response = self + .client + .receive() + .await + .map_err(|err| Error::UnableToReceiveConnectResponse { err })?; + + match response { + Response::Connect(connect_response) => Ok(connect_response.connection_id), + _ => Err(Error::UnexpectedConnectionResponse { response }), + } + } + + /// Sends an announce request to the UDP Tracker server. + /// + /// # Errors + /// + /// Will return and error if the client is not connected. You have to connect + /// before calling this function. + /// + /// # Panics + /// + /// It will panic if the `local_address` has a zero port. + pub async fn send_announce_request( + &self, + transaction_id: TransactionId, + connection_id: ConnectionId, + info_hash: TorrustInfoHash, + ) -> Result { + tracing::debug!("Sending announce request with transaction id: {transaction_id:#?}"); + + let port = NonZeroU16::new( + self.client + .client + .socket + .local_addr() + .expect("it should get the local address") + .port(), + ) + .expect("it should no be zero"); + + let announce_request = AnnounceRequest { + connection_id, + action_placeholder: AnnounceActionPlaceholder::default(), + transaction_id, + info_hash: InfoHash(info_hash.bytes()), + peer_id: PeerId(*b"-qB00000000000000001"), + bytes_downloaded: NumberOfBytes(0i64.into()), + bytes_uploaded: NumberOfBytes(0i64.into()), + bytes_left: NumberOfBytes(0i64.into()), + event: AnnounceEvent::Started.into(), + ip_address: Ipv4Addr::new(0, 0, 0, 0).into(), + key: PeerKey::new(0i32), + peers_wanted: NumberOfPeers(1i32.into()), + port: Port::new(port), + }; + + let _ = self + .client + .send(announce_request.into()) + .await + .map_err(|err| Error::UnableToSendAnnounceRequest { err })?; + + let response = self + .client + .receive() + .await + .map_err(|err| Error::UnableToReceiveAnnounceResponse { err })?; + + Ok(response) + } + + /// Sends a scrape request to the UDP Tracker server. + /// + /// # Errors + /// + /// Will return and error if the client is not connected. You have to connect + /// before calling this function. + pub async fn send_scrape_request( + &self, + connection_id: ConnectionId, + transaction_id: TransactionId, + info_hashes: &[TorrustInfoHash], + ) -> Result { + tracing::debug!("Sending scrape request with transaction id: {transaction_id:#?}"); + + let scrape_request = ScrapeRequest { + connection_id, + transaction_id, + info_hashes: info_hashes + .iter() + .map(|torrust_info_hash| InfoHash(torrust_info_hash.bytes())) + .collect(), + }; + + let _ = self + .client + .send(scrape_request.into()) + .await + .map_err(|err| Error::UnableToSendScrapeRequest { err })?; + + let response = self + .client + .receive() + .await + .map_err(|err| Error::UnableToReceiveScrapeResponse { err })?; + + Ok(response) + } +} diff --git a/console/tracker-client/src/console/clients/udp/mod.rs b/console/tracker-client/src/console/clients/udp/mod.rs new file mode 100644 index 000000000..fbfd53770 --- /dev/null +++ b/console/tracker-client/src/console/clients/udp/mod.rs @@ -0,0 +1,50 @@ +use std::net::SocketAddr; + +use aquatic_udp_protocol::Response; +use bittorrent_tracker_client::udp; +use serde::Serialize; +use thiserror::Error; + +pub mod app; +pub mod checker; +pub mod responses; + +#[derive(Error, Debug, Clone, Serialize)] +#[serde(into = "String")] +pub enum Error { + #[error("Failed to Connect to: {remote_addr}, with error: {err}")] + UnableToBindAndConnect { remote_addr: SocketAddr, err: udp::Error }, + + #[error("Failed to send a connection request, with error: {err}")] + UnableToSendConnectionRequest { err: udp::Error }, + + #[error("Failed to receive a connect response, with error: {err}")] + UnableToReceiveConnectResponse { err: udp::Error }, + + #[error("Failed to send a announce request, with error: {err}")] + UnableToSendAnnounceRequest { err: udp::Error }, + + #[error("Failed to receive a announce response, with error: {err}")] + UnableToReceiveAnnounceResponse { err: udp::Error }, + + #[error("Failed to send a scrape request, with error: {err}")] + UnableToSendScrapeRequest { err: udp::Error }, + + #[error("Failed to receive a scrape response, with error: {err}")] + UnableToReceiveScrapeResponse { err: udp::Error }, + + #[error("Failed to receive a response, with error: {err}")] + UnableToReceiveResponse { err: udp::Error }, + + #[error("Failed to get local address for connection: {err}")] + UnableToGetLocalAddr { err: udp::Error }, + + #[error("Failed to get a connection response: {response:?}")] + UnexpectedConnectionResponse { response: Response }, +} + +impl From for String { + fn from(value: Error) -> Self { + value.to_string() + } +} diff --git a/console/tracker-client/src/console/clients/udp/responses/dto.rs b/console/tracker-client/src/console/clients/udp/responses/dto.rs new file mode 100644 index 000000000..93320b0f7 --- /dev/null +++ b/console/tracker-client/src/console/clients/udp/responses/dto.rs @@ -0,0 +1,128 @@ +//! Aquatic responses are not serializable. These are the serializable wrappers. +use std::net::{Ipv4Addr, Ipv6Addr}; + +use aquatic_udp_protocol::Response::{self}; +use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse}; +use serde::Serialize; + +#[derive(Serialize)] +pub enum SerializableResponse { + Connect(ConnectSerializableResponse), + AnnounceIpv4(AnnounceSerializableResponse), + AnnounceIpv6(AnnounceSerializableResponse), + Scrape(ScrapeSerializableResponse), + Error(ErrorSerializableResponse), +} + +impl From for SerializableResponse { + fn from(response: Response) -> Self { + match response { + Response::Connect(response) => SerializableResponse::Connect(ConnectSerializableResponse::from(response)), + Response::AnnounceIpv4(response) => SerializableResponse::AnnounceIpv4(AnnounceSerializableResponse::from(response)), + Response::AnnounceIpv6(response) => SerializableResponse::AnnounceIpv6(AnnounceSerializableResponse::from(response)), + Response::Scrape(response) => SerializableResponse::Scrape(ScrapeSerializableResponse::from(response)), + Response::Error(response) => SerializableResponse::Error(ErrorSerializableResponse::from(response)), + } + } +} + +#[derive(Serialize)] +pub struct ConnectSerializableResponse { + transaction_id: i32, + connection_id: i64, +} + +impl From for ConnectSerializableResponse { + fn from(connect: ConnectResponse) -> Self { + Self { + transaction_id: connect.transaction_id.0.into(), + connection_id: connect.connection_id.0.into(), + } + } +} + +#[derive(Serialize)] +pub struct AnnounceSerializableResponse { + transaction_id: i32, + announce_interval: i32, + leechers: i32, + seeders: i32, + peers: Vec, +} + +impl From> for AnnounceSerializableResponse { + fn from(announce: AnnounceResponse) -> Self { + Self { + transaction_id: announce.fixed.transaction_id.0.into(), + announce_interval: announce.fixed.announce_interval.0.into(), + leechers: announce.fixed.leechers.0.into(), + seeders: announce.fixed.seeders.0.into(), + peers: announce + .peers + .iter() + .map(|peer| format!("{}:{}", Ipv4Addr::from(peer.ip_address), peer.port.0)) + .collect::>(), + } + } +} + +impl From> for AnnounceSerializableResponse { + fn from(announce: AnnounceResponse) -> Self { + Self { + transaction_id: announce.fixed.transaction_id.0.into(), + announce_interval: announce.fixed.announce_interval.0.into(), + leechers: announce.fixed.leechers.0.into(), + seeders: announce.fixed.seeders.0.into(), + peers: announce + .peers + .iter() + .map(|peer| format!("{}:{}", Ipv6Addr::from(peer.ip_address), peer.port.0)) + .collect::>(), + } + } +} + +#[derive(Serialize)] +pub struct ScrapeSerializableResponse { + transaction_id: i32, + torrent_stats: Vec, +} + +impl From for ScrapeSerializableResponse { + fn from(scrape: ScrapeResponse) -> Self { + Self { + transaction_id: scrape.transaction_id.0.into(), + torrent_stats: scrape + .torrent_stats + .iter() + .map(|torrent_scrape_statistics| TorrentStats { + seeders: torrent_scrape_statistics.seeders.0.into(), + completed: torrent_scrape_statistics.completed.0.into(), + leechers: torrent_scrape_statistics.leechers.0.into(), + }) + .collect::>(), + } + } +} + +#[derive(Serialize)] +pub struct ErrorSerializableResponse { + transaction_id: i32, + message: String, +} + +impl From for ErrorSerializableResponse { + fn from(error: ErrorResponse) -> Self { + Self { + transaction_id: error.transaction_id.0.into(), + message: error.message.to_string(), + } + } +} + +#[derive(Serialize)] +struct TorrentStats { + seeders: i32, + completed: i32, + leechers: i32, +} diff --git a/console/tracker-client/src/console/clients/udp/responses/json.rs b/console/tracker-client/src/console/clients/udp/responses/json.rs new file mode 100644 index 000000000..5d2bd6b89 --- /dev/null +++ b/console/tracker-client/src/console/clients/udp/responses/json.rs @@ -0,0 +1,25 @@ +use anyhow::Context; +use serde::Serialize; + +use super::dto::SerializableResponse; + +#[allow(clippy::module_name_repetitions)] +pub trait ToJson { + /// + /// Returns a string with the JSON serialized version of the response + /// + /// # Errors + /// + /// Will return an error if serialization fails. + /// + fn to_json_string(&self) -> anyhow::Result + where + Self: Serialize, + { + let pretty_json = serde_json::to_string_pretty(self).context("response JSON serialization")?; + + Ok(pretty_json) + } +} + +impl ToJson for SerializableResponse {} diff --git a/console/tracker-client/src/console/clients/udp/responses/mod.rs b/console/tracker-client/src/console/clients/udp/responses/mod.rs new file mode 100644 index 000000000..e6d2e5e51 --- /dev/null +++ b/console/tracker-client/src/console/clients/udp/responses/mod.rs @@ -0,0 +1,2 @@ +pub mod dto; +pub mod json; diff --git a/console/tracker-client/src/console/mod.rs b/console/tracker-client/src/console/mod.rs new file mode 100644 index 000000000..4b4cb9de4 --- /dev/null +++ b/console/tracker-client/src/console/mod.rs @@ -0,0 +1,2 @@ +//! Console apps. +pub mod clients; diff --git a/console/tracker-client/src/lib.rs b/console/tracker-client/src/lib.rs new file mode 100644 index 000000000..5b9849fdc --- /dev/null +++ b/console/tracker-client/src/lib.rs @@ -0,0 +1 @@ +pub mod console; diff --git a/packages/tracker-client/README.md b/packages/tracker-client/README.md index 1d12f9c86..56a61e154 100644 --- a/packages/tracker-client/README.md +++ b/packages/tracker-client/README.md @@ -2,7 +2,7 @@ A library an console applications to interact with a BitTorrent tracker. -> **Disclaimer**: This project is actively under development. We’re currently extracting and refining common types from the ][Torrust Tracker](https://github.com/torrust/torrust-tracker) to make them available to the BitTorrent community in Rust. While these types are functional, they are not yet ready for use in production or third-party projects. +> **Disclaimer**: This project is actively under development. We’re currently extracting and refining common types from the[Torrust Tracker](https://github.com/torrust/torrust-tracker) to make them available to the BitTorrent community in Rust. While these types are functional, they are not yet ready for use in production or third-party projects. ## License From e966ae47e342683d3c51fd29b4db646317827ad0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 13 Nov 2024 10:46:16 +0000 Subject: [PATCH 0514/1297] refactor!: remove tracker console client from tracker lib client --- Cargo.lock | 7 - packages/tracker-client/Cargo.toml | 9 +- packages/tracker-client/README.md | 2 +- .../src/bin/http_tracker_client.rs | 7 - .../tracker-client/src/bin/tracker_checker.rs | 7 - .../src/bin/udp_tracker_client.rs | 7 - .../src/console/clients/checker/app.rs | 120 -------- .../console/clients/checker/checks/health.rs | 77 ----- .../console/clients/checker/checks/http.rs | 104 ------- .../src/console/clients/checker/checks/mod.rs | 4 - .../console/clients/checker/checks/structs.rs | 12 - .../src/console/clients/checker/checks/udp.rs | 134 --------- .../src/console/clients/checker/config.rs | 282 ------------------ .../src/console/clients/checker/console.rs | 38 --- .../src/console/clients/checker/logger.rs | 72 ----- .../src/console/clients/checker/mod.rs | 7 - .../src/console/clients/checker/printer.rs | 9 - .../src/console/clients/checker/service.rs | 62 ---- .../src/console/clients/http/app.rs | 102 ------- .../src/console/clients/http/mod.rs | 34 --- .../tracker-client/src/console/clients/mod.rs | 4 - .../src/console/clients/udp/app.rs | 208 ------------- .../src/console/clients/udp/checker.rs | 177 ----------- .../src/console/clients/udp/mod.rs | 51 ---- .../src/console/clients/udp/responses/dto.rs | 128 -------- .../src/console/clients/udp/responses/json.rs | 25 -- .../src/console/clients/udp/responses/mod.rs | 2 - packages/tracker-client/src/console/mod.rs | 2 - .../tracker-client/src/http/url_encoding.rs | 4 +- packages/tracker-client/src/lib.rs | 1 - 30 files changed, 4 insertions(+), 1694 deletions(-) delete mode 100644 packages/tracker-client/src/bin/http_tracker_client.rs delete mode 100644 packages/tracker-client/src/bin/tracker_checker.rs delete mode 100644 packages/tracker-client/src/bin/udp_tracker_client.rs delete mode 100644 packages/tracker-client/src/console/clients/checker/app.rs delete mode 100644 packages/tracker-client/src/console/clients/checker/checks/health.rs delete mode 100644 packages/tracker-client/src/console/clients/checker/checks/http.rs delete mode 100644 packages/tracker-client/src/console/clients/checker/checks/mod.rs delete mode 100644 packages/tracker-client/src/console/clients/checker/checks/structs.rs delete mode 100644 packages/tracker-client/src/console/clients/checker/checks/udp.rs delete mode 100644 packages/tracker-client/src/console/clients/checker/config.rs delete mode 100644 packages/tracker-client/src/console/clients/checker/console.rs delete mode 100644 packages/tracker-client/src/console/clients/checker/logger.rs delete mode 100644 packages/tracker-client/src/console/clients/checker/mod.rs delete mode 100644 packages/tracker-client/src/console/clients/checker/printer.rs delete mode 100644 packages/tracker-client/src/console/clients/checker/service.rs delete mode 100644 packages/tracker-client/src/console/clients/http/app.rs delete mode 100644 packages/tracker-client/src/console/clients/http/mod.rs delete mode 100644 packages/tracker-client/src/console/clients/mod.rs delete mode 100644 packages/tracker-client/src/console/clients/udp/app.rs delete mode 100644 packages/tracker-client/src/console/clients/udp/checker.rs delete mode 100644 packages/tracker-client/src/console/clients/udp/mod.rs delete mode 100644 packages/tracker-client/src/console/clients/udp/responses/dto.rs delete mode 100644 packages/tracker-client/src/console/clients/udp/responses/json.rs delete mode 100644 packages/tracker-client/src/console/clients/udp/responses/mod.rs delete mode 100644 packages/tracker-client/src/console/mod.rs diff --git a/Cargo.lock b/Cargo.lock index ec723efff..bbb012cea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -620,20 +620,15 @@ dependencies = [ name = "bittorrent-tracker-client" version = "3.0.0-develop" dependencies = [ - "anyhow", "aquatic_udp_protocol", "bittorrent-primitives", - "clap", "derive_more", - "futures", - "hex-literal", "hyper", "percent-encoding", "reqwest", "serde", "serde_bencode", "serde_bytes", - "serde_json", "serde_repr", "thiserror", "tokio", @@ -641,8 +636,6 @@ dependencies = [ "torrust-tracker-located-error", "torrust-tracker-primitives", "tracing", - "tracing-subscriber", - "url", "zerocopy", ] diff --git a/packages/tracker-client/Cargo.toml b/packages/tracker-client/Cargo.toml index 3334e7b47..52b0be639 100644 --- a/packages/tracker-client/Cargo.toml +++ b/packages/tracker-client/Cargo.toml @@ -1,5 +1,5 @@ [package] -description = "A library with the primitive types shared by the Torrust tracker packages." +description = "A library with the generic tracker clients." keywords = ["bittorrent", "client", "tracker"] license = "LGPL-3.0" name = "bittorrent-tracker-client" @@ -15,20 +15,15 @@ rust-version.workspace = true version.workspace = true [dependencies] -anyhow = "1" aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" -clap = { version = "4", features = ["derive", "env"] } derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } -futures = "0" -hex-literal = "0" hyper = "1" percent-encoding = "2" reqwest = { version = "0", features = ["json"] } serde = { version = "1", features = ["derive"] } serde_bencode = "0" serde_bytes = "0" -serde_json = { version = "1", features = ["preserve_order"] } serde_repr = "0" thiserror = "1" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } @@ -36,8 +31,6 @@ torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configur torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } tracing = "0" -tracing-subscriber = { version = "0", features = ["json"] } -url = { version = "2", features = ["serde"] } zerocopy = "0.7" [package.metadata.cargo-machete] diff --git a/packages/tracker-client/README.md b/packages/tracker-client/README.md index 56a61e154..ebd0c4bda 100644 --- a/packages/tracker-client/README.md +++ b/packages/tracker-client/README.md @@ -1,6 +1,6 @@ # BitTorrent Tracker Client -A library an console applications to interact with a BitTorrent tracker. +A library to interact with BitTorrent trackers. > **Disclaimer**: This project is actively under development. We’re currently extracting and refining common types from the[Torrust Tracker](https://github.com/torrust/torrust-tracker) to make them available to the BitTorrent community in Rust. While these types are functional, they are not yet ready for use in production or third-party projects. diff --git a/packages/tracker-client/src/bin/http_tracker_client.rs b/packages/tracker-client/src/bin/http_tracker_client.rs deleted file mode 100644 index 8c2c0356d..000000000 --- a/packages/tracker-client/src/bin/http_tracker_client.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Program to make request to HTTP trackers. -use bittorrent_tracker_client::console::clients::http::app; - -#[tokio::main] -async fn main() -> anyhow::Result<()> { - app::run().await -} diff --git a/packages/tracker-client/src/bin/tracker_checker.rs b/packages/tracker-client/src/bin/tracker_checker.rs deleted file mode 100644 index eb2a7d82c..000000000 --- a/packages/tracker-client/src/bin/tracker_checker.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Program to check running trackers. -use bittorrent_tracker_client::console::clients::checker::app; - -#[tokio::main] -async fn main() { - app::run().await.expect("Some checks fail"); -} diff --git a/packages/tracker-client/src/bin/udp_tracker_client.rs b/packages/tracker-client/src/bin/udp_tracker_client.rs deleted file mode 100644 index 5f6b4f50d..000000000 --- a/packages/tracker-client/src/bin/udp_tracker_client.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Program to make request to UDP trackers. -use bittorrent_tracker_client::console::clients::udp::app; - -#[tokio::main] -async fn main() -> anyhow::Result<()> { - app::run().await -} diff --git a/packages/tracker-client/src/console/clients/checker/app.rs b/packages/tracker-client/src/console/clients/checker/app.rs deleted file mode 100644 index 395f65df9..000000000 --- a/packages/tracker-client/src/console/clients/checker/app.rs +++ /dev/null @@ -1,120 +0,0 @@ -//! Program to run checks against running trackers. -//! -//! Run providing a config file path: -//! -//! ```text -//! cargo run --bin tracker_checker -- --config-path "./share/default/config/tracker_checker.json" -//! TORRUST_CHECKER_CONFIG_PATH="./share/default/config/tracker_checker.json" cargo run --bin tracker_checker -//! ``` -//! -//! Run providing the configuration: -//! -//! ```text -//! TORRUST_CHECKER_CONFIG=$(cat "./share/default/config/tracker_checker.json") cargo run --bin tracker_checker -//! ``` -//! -//! Another real example to test the Torrust demo tracker: -//! -//! ```text -//! TORRUST_CHECKER_CONFIG='{ -//! "udp_trackers": ["144.126.245.19:6969"], -//! "http_trackers": ["https://tracker.torrust-demo.com"], -//! "health_checks": ["https://tracker.torrust-demo.com/api/health_check"] -//! }' cargo run --bin tracker_checker -//! ``` -//! -//! The output should be something like the following: -//! -//! ```json -//! { -//! "udp_trackers": [ -//! { -//! "url": "144.126.245.19:6969", -//! "status": { -//! "code": "ok", -//! "message": "" -//! } -//! } -//! ], -//! "http_trackers": [ -//! { -//! "url": "https://tracker.torrust-demo.com/", -//! "status": { -//! "code": "ok", -//! "message": "" -//! } -//! } -//! ], -//! "health_checks": [ -//! { -//! "url": "https://tracker.torrust-demo.com/api/health_check", -//! "status": { -//! "code": "ok", -//! "message": "" -//! } -//! } -//! ] -//! } -//! ``` -use std::path::PathBuf; -use std::sync::Arc; - -use anyhow::{Context, Result}; -use clap::Parser; -use tracing::level_filters::LevelFilter; - -use super::config::Configuration; -use super::console::Console; -use super::service::{CheckResult, Service}; -use crate::console::clients::checker::config::parse_from_json; - -#[derive(Parser, Debug)] -#[clap(author, version, about, long_about = None)] -struct Args { - /// Path to the JSON configuration file. - #[clap(short, long, env = "TORRUST_CHECKER_CONFIG_PATH")] - config_path: Option, - - /// Direct configuration content in JSON. - #[clap(env = "TORRUST_CHECKER_CONFIG", hide_env_values = true)] - config_content: Option, -} - -/// # Errors -/// -/// Will return an error if the configuration was not provided. -pub async fn run() -> Result> { - tracing_stdout_init(LevelFilter::INFO); - - 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.context("it should run the check tasks") -} - -fn tracing_stdout_init(filter: LevelFilter) { - tracing_subscriber::fmt().with_max_level(filter).init(); - tracing::debug!("Logging initialized"); -} - -fn setup_config(args: Args) -> Result { - match (args.config_path, args.config_content) { - (Some(config_path), _) => load_config_from_file(&config_path), - (_, Some(config_content)) => parse_from_json(&config_content).context("invalid config format"), - _ => Err(anyhow::anyhow!("no configuration provided")), - } -} - -fn load_config_from_file(path: &PathBuf) -> Result { - let file_content = std::fs::read_to_string(path).with_context(|| format!("can't read config file {path:?}"))?; - - parse_from_json(&file_content).context("invalid config format") -} diff --git a/packages/tracker-client/src/console/clients/checker/checks/health.rs b/packages/tracker-client/src/console/clients/checker/checks/health.rs deleted file mode 100644 index b1fb79148..000000000 --- a/packages/tracker-client/src/console/clients/checker/checks/health.rs +++ /dev/null @@ -1,77 +0,0 @@ -use std::sync::Arc; -use std::time::Duration; - -use anyhow::Result; -use hyper::StatusCode; -use reqwest::{Client as HttpClient, Response}; -use serde::Serialize; -use thiserror::Error; -use url::Url; - -#[derive(Debug, Clone, Error, Serialize)] -#[serde(into = "String")] -pub enum Error { - #[error("Failed to Build a Http Client: {err:?}")] - ClientBuildingError { err: Arc }, - #[error("Heath check failed to get a response: {err:?}")] - ResponseError { err: Arc }, - #[error("Http check returned a non-success code: \"{code}\" with the response: \"{response:?}\"")] - UnsuccessfulResponse { code: StatusCode, response: Arc }, -} - -impl From for String { - fn from(value: Error) -> Self { - value.to_string() - } -} - -#[derive(Debug, Clone, Serialize)] -pub struct Checks { - url: Url, - result: Result, -} - -pub async fn run(health_checks: Vec, timeout: Duration) -> Vec> { - let mut results = Vec::default(); - - tracing::debug!("Health checks ..."); - - for url in health_checks { - let result = match run_health_check(url.clone(), timeout).await { - Ok(response) => Ok(response.status().to_string()), - Err(err) => Err(err), - }; - - let check = Checks { url, result }; - - if check.result.is_err() { - results.push(Err(check)); - } else { - results.push(Ok(check)); - } - } - - results -} - -async fn run_health_check(url: Url, timeout: Duration) -> Result { - let client = HttpClient::builder() - .timeout(timeout) - .build() - .map_err(|e| Error::ClientBuildingError { err: e.into() })?; - - let response = client - .get(url.clone()) - .send() - .await - .map_err(|e| Error::ResponseError { err: e.into() })?; - - if response.status().is_success() { - Ok(response) - } else { - Err(Error::UnsuccessfulResponse { - code: response.status(), - response: response.into(), - }) - } -} diff --git a/packages/tracker-client/src/console/clients/checker/checks/http.rs b/packages/tracker-client/src/console/clients/checker/checks/http.rs deleted file mode 100644 index 48ce9678d..000000000 --- a/packages/tracker-client/src/console/clients/checker/checks/http.rs +++ /dev/null @@ -1,104 +0,0 @@ -use std::str::FromStr as _; -use std::time::Duration; - -use bittorrent_primitives::info_hash::InfoHash; -use serde::Serialize; -use url::Url; - -use crate::console::clients::http::Error; -use crate::http::client::responses::announce::Announce; -use crate::http::client::responses::scrape; -use crate::http::client::{requests, Client}; - -#[derive(Debug, Clone, Serialize)] -pub struct Checks { - url: Url, - results: Vec<(Check, Result<(), Error>)>, -} - -#[derive(Debug, Clone, Serialize)] -pub enum Check { - Announce, - Scrape, -} - -pub async fn run(http_trackers: Vec, timeout: Duration) -> Vec> { - let mut results = Vec::default(); - - tracing::debug!("HTTP trackers ..."); - - for ref url in http_trackers { - let mut base_url = url.clone(); - base_url.set_path(""); - - let mut checks = Checks { - url: url.clone(), - results: Vec::default(), - }; - - // Announce - { - let check = check_http_announce(&base_url, timeout).await.map(|_| ()); - - checks.results.push((Check::Announce, check)); - } - - // Scrape - { - let check = check_http_scrape(&base_url, timeout).await.map(|_| ()); - - checks.results.push((Check::Scrape, check)); - } - - if checks.results.iter().any(|f| f.1.is_err()) { - results.push(Err(checks)); - } else { - results.push(Ok(checks)); - } - } - - results -} - -async fn check_http_announce(url: &Url, timeout: Duration) -> Result { - let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // # DevSkim: ignore DS173237 - let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); - - let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; - - let response = client - .announce( - &requests::announce::QueryBuilder::with_default_values() - .with_info_hash(&info_hash) - .query(), - ) - .await - .map_err(|err| Error::HttpClientError { err })?; - - let response = response.bytes().await.map_err(|e| Error::ResponseError { err: e.into() })?; - - let response = serde_bencode::from_bytes::(&response).map_err(|e| Error::ParseBencodeError { - data: response, - err: e.into(), - })?; - - Ok(response) -} - -async fn check_http_scrape(url: &Url, timeout: Duration) -> Result { - let info_hashes: Vec = vec!["9c38422213e30bff212b30c360d26f9a02136422".to_string()]; // # DevSkim: ignore DS173237 - let query = requests::scrape::Query::try_from(info_hashes).expect("a valid array of info-hashes is required"); - - let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; - - let response = client.scrape(&query).await.map_err(|err| Error::HttpClientError { err })?; - - let response = response.bytes().await.map_err(|e| Error::ResponseError { err: e.into() })?; - - let response = scrape::Response::try_from_bencoded(&response).map_err(|e| Error::BencodeParseError { - data: response, - err: e.into(), - })?; - - Ok(response) -} diff --git a/packages/tracker-client/src/console/clients/checker/checks/mod.rs b/packages/tracker-client/src/console/clients/checker/checks/mod.rs deleted file mode 100644 index f8b03f749..000000000 --- a/packages/tracker-client/src/console/clients/checker/checks/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -pub mod health; -pub mod http; -pub mod structs; -pub mod udp; diff --git a/packages/tracker-client/src/console/clients/checker/checks/structs.rs b/packages/tracker-client/src/console/clients/checker/checks/structs.rs deleted file mode 100644 index d28e20c04..000000000 --- a/packages/tracker-client/src/console/clients/checker/checks/structs.rs +++ /dev/null @@ -1,12 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Serialize, Deserialize)] -pub struct Status { - pub code: String, - pub message: String, -} -#[derive(Serialize, Deserialize)] -pub struct CheckerOutput { - pub url: String, - pub status: Status, -} diff --git a/packages/tracker-client/src/console/clients/checker/checks/udp.rs b/packages/tracker-client/src/console/clients/checker/checks/udp.rs deleted file mode 100644 index 21bdcd1b7..000000000 --- a/packages/tracker-client/src/console/clients/checker/checks/udp.rs +++ /dev/null @@ -1,134 +0,0 @@ -use std::net::SocketAddr; -use std::time::Duration; - -use aquatic_udp_protocol::TransactionId; -use hex_literal::hex; -use serde::Serialize; -use url::Url; - -use crate::console::clients::udp::checker::Client; -use crate::console::clients::udp::Error; - -#[derive(Debug, Clone, Serialize)] -pub struct Checks { - remote_addr: SocketAddr, - results: Vec<(Check, Result<(), Error>)>, -} - -#[derive(Debug, Clone, Serialize)] -pub enum Check { - Setup, - Connect, - Announce, - Scrape, -} - -#[allow(clippy::missing_panics_doc)] -pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec> { - let mut results = Vec::default(); - - tracing::debug!("UDP trackers ..."); - - let info_hash = aquatic_udp_protocol::InfoHash(hex!("9c38422213e30bff212b30c360d26f9a02136422")); // # DevSkim: ignore DS173237 - - for remote_url in udp_trackers { - let remote_addr = resolve_socket_addr(&remote_url); - - let mut checks = Checks { - remote_addr, - results: Vec::default(), - }; - - tracing::debug!("UDP tracker: {:?}", remote_url); - - // Setup - let client = match Client::new(remote_addr, timeout).await { - Ok(client) => { - checks.results.push((Check::Setup, Ok(()))); - client - } - Err(err) => { - checks.results.push((Check::Setup, Err(err))); - results.push(Err(checks)); - continue; - } - }; - - let transaction_id = TransactionId::new(1); - - // Connect Remote - let connection_id = match client.send_connection_request(transaction_id).await { - Ok(connection_id) => { - checks.results.push((Check::Connect, Ok(()))); - connection_id - } - Err(err) => { - checks.results.push((Check::Connect, Err(err))); - results.push(Err(checks)); - continue; - } - }; - - // Announce - { - let check = client - .send_announce_request(transaction_id, connection_id, info_hash.into()) - .await - .map(|_| ()); - - checks.results.push((Check::Announce, check)); - } - - // Scrape - { - let check = client - .send_scrape_request(connection_id, transaction_id, &[info_hash.into()]) - .await - .map(|_| ()); - - checks.results.push((Check::Scrape, check)); - } - - if checks.results.iter().any(|f| f.1.is_err()) { - results.push(Err(checks)); - } else { - results.push(Ok(checks)); - } - } - - results -} - -fn resolve_socket_addr(url: &Url) -> SocketAddr { - let socket_addr = url.socket_addrs(|| None).unwrap(); - *socket_addr.first().unwrap() -} - -#[cfg(test)] -mod tests { - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - - use url::Url; - - use crate::console::clients::checker::checks::udp::resolve_socket_addr; - - #[test] - fn it_should_resolve_the_socket_address_for_udp_scheme_urls_containing_a_domain() { - let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); - - assert!( - socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) - || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) - ); - } - - #[test] - fn it_should_resolve_the_socket_address_for_udp_scheme_urls_containing_an_ip() { - let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); - - assert!( - socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) - || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) - ); - } -} diff --git a/packages/tracker-client/src/console/clients/checker/config.rs b/packages/tracker-client/src/console/clients/checker/config.rs deleted file mode 100644 index 154dcae85..000000000 --- a/packages/tracker-client/src/console/clients/checker/config.rs +++ /dev/null @@ -1,282 +0,0 @@ -use std::error::Error; -use std::fmt; - -use reqwest::Url as ServiceUrl; -use serde::Deserialize; - -/// It parses the configuration from a JSON format. -/// -/// # Errors -/// -/// Will return an error if the configuration is not valid. -/// -/// # Panics -/// -/// Will panic if unable to read the configuration file. -pub fn parse_from_json(json: &str) -> Result { - let plain_config: PlainConfiguration = serde_json::from_str(json).map_err(ConfigurationError::JsonParseError)?; - Configuration::try_from(plain_config) -} - -/// DTO for the configuration to serialize/deserialize configuration. -/// -/// Configuration does not need to be valid. -#[derive(Deserialize)] -struct PlainConfiguration { - pub udp_trackers: Vec, - pub http_trackers: Vec, - pub health_checks: Vec, -} - -/// Validated configuration -pub struct Configuration { - pub udp_trackers: Vec, - pub http_trackers: Vec, - pub health_checks: Vec, -} - -#[derive(Debug)] -pub enum ConfigurationError { - JsonParseError(serde_json::Error), - InvalidUdpAddress(std::net::AddrParseError), - InvalidUrl(url::ParseError), -} - -impl Error for ConfigurationError {} - -impl fmt::Display for ConfigurationError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ConfigurationError::JsonParseError(e) => write!(f, "JSON parse error: {e}"), - ConfigurationError::InvalidUdpAddress(e) => write!(f, "Invalid UDP address: {e}"), - ConfigurationError::InvalidUrl(e) => write!(f, "Invalid URL: {e}"), - } - } -} - -impl TryFrom for Configuration { - type Error = ConfigurationError; - - fn try_from(plain_config: PlainConfiguration) -> Result { - let udp_trackers = plain_config - .udp_trackers - .into_iter() - .map(|s| if s.starts_with("udp://") { s } else { format!("udp://{s}") }) - .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) - .collect::, _>>()?; - - let http_trackers = plain_config - .http_trackers - .into_iter() - .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) - .collect::, _>>()?; - - let health_checks = plain_config - .health_checks - .into_iter() - .map(|s| s.parse::().map_err(ConfigurationError::InvalidUrl)) - .collect::, _>>()?; - - Ok(Configuration { - udp_trackers, - http_trackers, - health_checks, - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn configuration_should_be_build_from_plain_serializable_configuration() { - let dto = PlainConfiguration { - udp_trackers: vec!["udp://127.0.0.1:8080".to_string()], - http_trackers: vec!["http://127.0.0.1:8080".to_string()], - health_checks: vec!["http://127.0.0.1:8080/health".to_string()], - }; - - let config = Configuration::try_from(dto).expect("A valid configuration"); - - assert_eq!(config.udp_trackers, vec![ServiceUrl::parse("udp://127.0.0.1:8080").unwrap()]); - - assert_eq!( - config.http_trackers, - vec![ServiceUrl::parse("http://127.0.0.1:8080").unwrap()] - ); - - assert_eq!( - config.health_checks, - vec![ServiceUrl::parse("http://127.0.0.1:8080/health").unwrap()] - ); - } - - mod building_configuration_from_plain_configuration_for { - - mod udp_trackers { - use crate::console::clients::checker::config::{Configuration, PlainConfiguration, ServiceUrl}; - - /* The plain configuration should allow UDP URLs with: - - - IP or domain. - - With or without scheme. - - With or without `announce` suffix. - - With or without `/` at the end of the authority section (with empty path). - - For example: - - 127.0.0.1:6969 - 127.0.0.1:6969/ - 127.0.0.1:6969/announce - - localhost:6969 - localhost:6969/ - localhost:6969/announce - - udp://127.0.0.1:6969 - udp://127.0.0.1:6969/ - udp://127.0.0.1:6969/announce - - udp://localhost:6969 - udp://localhost:6969/ - udp://localhost:6969/announce - - */ - - #[test] - fn it_should_fail_when_a_tracker_udp_url_is_invalid() { - let plain_config = PlainConfiguration { - udp_trackers: vec!["invalid URL".to_string()], - http_trackers: vec![], - health_checks: vec![], - }; - - assert!(Configuration::try_from(plain_config).is_err()); - } - - #[test] - fn it_should_add_the_udp_scheme_to_the_udp_url_when_it_is_missing() { - let plain_config = PlainConfiguration { - udp_trackers: vec!["127.0.0.1:6969".to_string()], - http_trackers: vec![], - health_checks: vec![], - }; - - let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); - - assert_eq!(config.udp_trackers[0], "udp://127.0.0.1:6969".parse::().unwrap()); - } - - #[test] - fn it_should_allow_using_domains() { - let plain_config = PlainConfiguration { - udp_trackers: vec!["udp://localhost:6969".to_string()], - http_trackers: vec![], - health_checks: vec![], - }; - - let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); - - assert_eq!(config.udp_trackers[0], "udp://localhost:6969".parse::().unwrap()); - } - - #[test] - fn it_should_allow_the_url_to_have_an_empty_path() { - let plain_config = PlainConfiguration { - udp_trackers: vec!["127.0.0.1:6969/".to_string()], - http_trackers: vec![], - health_checks: vec![], - }; - - let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); - - assert_eq!(config.udp_trackers[0], "udp://127.0.0.1:6969/".parse::().unwrap()); - } - - #[test] - fn it_should_allow_the_url_to_contain_a_path() { - // This is the common format for UDP tracker URLs: - // udp://domain.com:6969/announce - - let plain_config = PlainConfiguration { - udp_trackers: vec!["127.0.0.1:6969/announce".to_string()], - http_trackers: vec![], - health_checks: vec![], - }; - - let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); - - assert_eq!( - config.udp_trackers[0], - "udp://127.0.0.1:6969/announce".parse::().unwrap() - ); - } - } - - mod http_trackers { - use crate::console::clients::checker::config::{Configuration, PlainConfiguration, ServiceUrl}; - - #[test] - fn it_should_fail_when_a_tracker_http_url_is_invalid() { - let plain_config = PlainConfiguration { - udp_trackers: vec![], - http_trackers: vec!["invalid URL".to_string()], - health_checks: vec![], - }; - - assert!(Configuration::try_from(plain_config).is_err()); - } - - #[test] - fn it_should_allow_the_url_to_contain_a_path() { - // This is the common format for HTTP tracker URLs: - // http://domain.com:7070/announce - - let plain_config = PlainConfiguration { - udp_trackers: vec![], - http_trackers: vec!["http://127.0.0.1:7070/announce".to_string()], - health_checks: vec![], - }; - - let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); - - assert_eq!( - config.http_trackers[0], - "http://127.0.0.1:7070/announce".parse::().unwrap() - ); - } - - #[test] - fn it_should_allow_the_url_to_contain_an_empty_path() { - let plain_config = PlainConfiguration { - udp_trackers: vec![], - http_trackers: vec!["http://127.0.0.1:7070/".to_string()], - health_checks: vec![], - }; - - let config = Configuration::try_from(plain_config).expect("Invalid plain configuration"); - - assert_eq!( - config.http_trackers[0], - "http://127.0.0.1:7070/".parse::().unwrap() - ); - } - } - - mod health_checks { - use crate::console::clients::checker::config::{Configuration, PlainConfiguration}; - - #[test] - fn it_should_fail_when_a_health_check_http_url_is_invalid() { - let plain_config = PlainConfiguration { - udp_trackers: vec![], - http_trackers: vec![], - health_checks: vec!["invalid URL".to_string()], - }; - - assert!(Configuration::try_from(plain_config).is_err()); - } - } - } -} diff --git a/packages/tracker-client/src/console/clients/checker/console.rs b/packages/tracker-client/src/console/clients/checker/console.rs deleted file mode 100644 index b55c559fc..000000000 --- a/packages/tracker-client/src/console/clients/checker/console.rs +++ /dev/null @@ -1,38 +0,0 @@ -use super::printer::{Printer, CLEAR_SCREEN}; - -pub struct Console {} - -impl Default for Console { - fn default() -> Self { - Self::new() - } -} - -impl Console { - #[must_use] - pub fn new() -> Self { - Self {} - } -} - -impl Printer for Console { - fn clear(&self) { - self.print(CLEAR_SCREEN); - } - - fn print(&self, output: &str) { - print!("{}", &output); - } - - fn eprint(&self, output: &str) { - eprint!("{}", &output); - } - - fn println(&self, output: &str) { - println!("{}", &output); - } - - fn eprintln(&self, output: &str) { - eprintln!("{}", &output); - } -} diff --git a/packages/tracker-client/src/console/clients/checker/logger.rs b/packages/tracker-client/src/console/clients/checker/logger.rs deleted file mode 100644 index 50e97189f..000000000 --- a/packages/tracker-client/src/console/clients/checker/logger.rs +++ /dev/null @@ -1,72 +0,0 @@ -use std::cell::RefCell; - -use super::printer::{Printer, CLEAR_SCREEN}; - -pub struct Logger { - output: RefCell, -} - -impl Default for Logger { - fn default() -> Self { - Self::new() - } -} - -impl Logger { - #[must_use] - pub fn new() -> Self { - Self { - output: RefCell::new(String::new()), - } - } - - pub fn log(&self) -> String { - self.output.borrow().clone() - } -} - -impl Printer for Logger { - fn clear(&self) { - self.print(CLEAR_SCREEN); - } - - fn print(&self, output: &str) { - *self.output.borrow_mut() = format!("{}{}", self.output.borrow(), &output); - } - - fn eprint(&self, output: &str) { - *self.output.borrow_mut() = format!("{}{}", self.output.borrow(), &output); - } - - fn println(&self, output: &str) { - self.print(&format!("{}/n", &output)); - } - - fn eprintln(&self, output: &str) { - self.eprint(&format!("{}/n", &output)); - } -} - -#[cfg(test)] -mod tests { - use crate::console::clients::checker::logger::Logger; - use crate::console::clients::checker::printer::{Printer, CLEAR_SCREEN}; - - #[test] - fn should_capture_the_clear_screen_command() { - let console_logger = Logger::new(); - - console_logger.clear(); - - assert_eq!(CLEAR_SCREEN, console_logger.log()); - } - - #[test] - fn should_capture_the_print_command_output() { - let console_logger = Logger::new(); - - console_logger.print("OUTPUT"); - - assert_eq!("OUTPUT", console_logger.log()); - } -} diff --git a/packages/tracker-client/src/console/clients/checker/mod.rs b/packages/tracker-client/src/console/clients/checker/mod.rs deleted file mode 100644 index d26a4a686..000000000 --- a/packages/tracker-client/src/console/clients/checker/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub mod app; -pub mod checks; -pub mod config; -pub mod console; -pub mod logger; -pub mod printer; -pub mod service; diff --git a/packages/tracker-client/src/console/clients/checker/printer.rs b/packages/tracker-client/src/console/clients/checker/printer.rs deleted file mode 100644 index d590dfedb..000000000 --- a/packages/tracker-client/src/console/clients/checker/printer.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub const CLEAR_SCREEN: &str = "\x1B[2J\x1B[1;1H"; - -pub trait Printer { - fn clear(&self); - fn print(&self, output: &str); - fn eprint(&self, output: &str); - fn println(&self, output: &str); - fn eprintln(&self, output: &str); -} diff --git a/packages/tracker-client/src/console/clients/checker/service.rs b/packages/tracker-client/src/console/clients/checker/service.rs deleted file mode 100644 index acd312d8c..000000000 --- a/packages/tracker-client/src/console/clients/checker/service.rs +++ /dev/null @@ -1,62 +0,0 @@ -use std::sync::Arc; - -use futures::FutureExt as _; -use serde::Serialize; -use tokio::task::{JoinError, JoinSet}; -use torrust_tracker_configuration::DEFAULT_TIMEOUT; - -use super::checks::{health, http, udp}; -use super::config::Configuration; -use super::console::Console; -use crate::console::clients::checker::printer::Printer; - -pub struct Service { - pub(crate) config: Arc, - pub(crate) console: Console, -} - -#[derive(Debug, Clone, Serialize)] -pub enum CheckResult { - Udp(Result), - Http(Result), - Health(Result), -} - -impl Service { - /// # Errors - /// - /// It will return an error if some of the tests panic or otherwise fail to run. - /// On success it will return a vector of `Ok(())` of [`CheckResult`]. - /// - /// # Panics - /// - /// It would panic if `serde_json` produces invalid json for the `to_string_pretty` function. - pub async fn run_checks(self) -> Result, JoinError> { - tracing::info!("Running checks for trackers ..."); - - let mut check_results = Vec::default(); - - let mut checks = JoinSet::new(); - checks.spawn( - udp::run(self.config.udp_trackers.clone(), DEFAULT_TIMEOUT).map(|mut f| f.drain(..).map(CheckResult::Udp).collect()), - ); - checks.spawn( - http::run(self.config.http_trackers.clone(), DEFAULT_TIMEOUT) - .map(|mut f| f.drain(..).map(CheckResult::Http).collect()), - ); - checks.spawn( - health::run(self.config.health_checks.clone(), DEFAULT_TIMEOUT) - .map(|mut f| f.drain(..).map(CheckResult::Health).collect()), - ); - - while let Some(results) = checks.join_next().await { - check_results.append(&mut results?); - } - - let json_output = serde_json::json!(check_results); - self.console - .println(&serde_json::to_string_pretty(&json_output).expect("it should consume valid json")); - - Ok(check_results) - } -} diff --git a/packages/tracker-client/src/console/clients/http/app.rs b/packages/tracker-client/src/console/clients/http/app.rs deleted file mode 100644 index 8db6fe46d..000000000 --- a/packages/tracker-client/src/console/clients/http/app.rs +++ /dev/null @@ -1,102 +0,0 @@ -//! HTTP Tracker client: -//! -//! Examples: -//! -//! `Announce` request: -//! -//! ```text -//! cargo run --bin http_tracker_client announce http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -//! -//! `Scrape` request: -//! -//! ```text -//! cargo run --bin http_tracker_client scrape http://127.0.0.1:7070 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -use std::str::FromStr; -use std::time::Duration; - -use anyhow::Context; -use bittorrent_primitives::info_hash::InfoHash; -use clap::{Parser, Subcommand}; -use reqwest::Url; -use torrust_tracker_configuration::DEFAULT_TIMEOUT; - -use crate::http::client::requests::announce::QueryBuilder; -use crate::http::client::responses::announce::Announce; -use crate::http::client::responses::scrape; -use crate::http::client::{requests, Client}; - -#[derive(Parser, Debug)] -#[command(author, version, about, long_about = None)] -struct Args { - #[command(subcommand)] - command: Command, -} - -#[derive(Subcommand, Debug)] -enum Command { - Announce { tracker_url: String, info_hash: String }, - Scrape { tracker_url: String, info_hashes: Vec }, -} - -/// # Errors -/// -/// Will return an error if the command fails. -pub async fn run() -> anyhow::Result<()> { - let args = Args::parse(); - - match args.command { - Command::Announce { tracker_url, info_hash } => { - announce_command(tracker_url, info_hash, DEFAULT_TIMEOUT).await?; - } - Command::Scrape { - tracker_url, - info_hashes, - } => { - scrape_command(&tracker_url, &info_hashes, DEFAULT_TIMEOUT).await?; - } - } - - Ok(()) -} - -async fn announce_command(tracker_url: String, info_hash: String, timeout: Duration) -> anyhow::Result<()> { - let base_url = Url::parse(&tracker_url).context("failed to parse HTTP tracker base URL")?; - let info_hash = - InfoHash::from_str(&info_hash).expect("Invalid infohash. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`"); - - let response = Client::new(base_url, timeout)? - .announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query()) - .await?; - - let body = response.bytes().await?; - - let announce_response: Announce = serde_bencode::from_bytes(&body) - .unwrap_or_else(|_| panic!("response body should be a valid announce response, got: \"{:#?}\"", &body)); - - let json = serde_json::to_string(&announce_response).context("failed to serialize scrape response into JSON")?; - - println!("{json}"); - - Ok(()) -} - -async fn scrape_command(tracker_url: &str, info_hashes: &[String], timeout: Duration) -> anyhow::Result<()> { - let base_url = Url::parse(tracker_url).context("failed to parse HTTP tracker base URL")?; - - let query = requests::scrape::Query::try_from(info_hashes).context("failed to parse infohashes")?; - - let response = Client::new(base_url, timeout)?.scrape(&query).await?; - - let body = response.bytes().await?; - - let scrape_response = scrape::Response::try_from_bencoded(&body) - .unwrap_or_else(|_| panic!("response body should be a valid scrape response, got: \"{:#?}\"", &body)); - - let json = serde_json::to_string(&scrape_response).context("failed to serialize scrape response into JSON")?; - - println!("{json}"); - - Ok(()) -} diff --git a/packages/tracker-client/src/console/clients/http/mod.rs b/packages/tracker-client/src/console/clients/http/mod.rs deleted file mode 100644 index e4b6fbe57..000000000 --- a/packages/tracker-client/src/console/clients/http/mod.rs +++ /dev/null @@ -1,34 +0,0 @@ -use std::sync::Arc; - -use serde::Serialize; -use thiserror::Error; - -use crate::http::client::responses::scrape::BencodeParseError; - -pub mod app; - -#[derive(Debug, Clone, Error, Serialize)] -#[serde(into = "String")] -pub enum Error { - #[error("Http request did not receive a response within the timeout: {err:?}")] - HttpClientError { err: crate::http::client::Error }, - #[error("Http failed to get a response at all: {err:?}")] - ResponseError { err: Arc }, - #[error("Failed to deserialize the bencoded response data with the error: \"{err:?}\"")] - ParseBencodeError { - data: hyper::body::Bytes, - err: Arc, - }, - - #[error("Failed to deserialize the bencoded response data with the error: \"{err:?}\"")] - BencodeParseError { - data: hyper::body::Bytes, - err: Arc, - }, -} - -impl From for String { - fn from(value: Error) -> Self { - value.to_string() - } -} diff --git a/packages/tracker-client/src/console/clients/mod.rs b/packages/tracker-client/src/console/clients/mod.rs deleted file mode 100644 index 8492f8ba5..000000000 --- a/packages/tracker-client/src/console/clients/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! Console clients. -pub mod checker; -pub mod http; -pub mod udp; diff --git a/packages/tracker-client/src/console/clients/udp/app.rs b/packages/tracker-client/src/console/clients/udp/app.rs deleted file mode 100644 index a2736c365..000000000 --- a/packages/tracker-client/src/console/clients/udp/app.rs +++ /dev/null @@ -1,208 +0,0 @@ -//! UDP Tracker client: -//! -//! Examples: -//! -//! Announce request: -//! -//! ```text -//! cargo run --bin udp_tracker_client announce 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -//! -//! Announce response: -//! -//! ```json -//! { -//! "transaction_id": -888840697 -//! "announce_interval": 120, -//! "leechers": 0, -//! "seeders": 1, -//! "peers": [ -//! "123.123.123.123:51289" -//! ], -//! } -//! ``` -//! -//! Scrape request: -//! -//! ```text -//! cargo run --bin udp_tracker_client scrape 127.0.0.1:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -//! -//! Scrape response: -//! -//! ```json -//! { -//! "transaction_id": -888840697, -//! "torrent_stats": [ -//! { -//! "completed": 0, -//! "leechers": 0, -//! "seeders": 0 -//! }, -//! { -//! "completed": 0, -//! "leechers": 0, -//! "seeders": 0 -//! } -//! ] -//! } -//! ``` -//! -//! You can use an URL with instead of the socket address. For example: -//! -//! ```text -//! cargo run --bin udp_tracker_client scrape udp://localhost:6969 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! cargo run --bin udp_tracker_client scrape udp://localhost:6969/scrape 9c38422213e30bff212b30c360d26f9a02136422 | jq -//! ``` -//! -//! The protocol (`udp://`) in the URL is mandatory. The path (`\scrape`) is optional. It always uses `\scrape`. -use std::net::{SocketAddr, ToSocketAddrs}; -use std::str::FromStr; - -use anyhow::Context; -use aquatic_udp_protocol::{Response, TransactionId}; -use bittorrent_primitives::info_hash::InfoHash as TorrustInfoHash; -use clap::{Parser, Subcommand}; -use torrust_tracker_configuration::DEFAULT_TIMEOUT; -use tracing::level_filters::LevelFilter; -use url::Url; - -use super::Error; -use crate::console::clients::udp::checker; -use crate::console::clients::udp::responses::dto::SerializableResponse; -use crate::console::clients::udp::responses::json::ToJson; - -const RANDOM_TRANSACTION_ID: i32 = -888_840_697; - -#[derive(Parser, Debug)] -#[command(author, version, about, long_about = None)] -struct Args { - #[command(subcommand)] - command: Command, -} - -#[derive(Subcommand, Debug)] -enum Command { - Announce { - #[arg(value_parser = parse_socket_addr)] - tracker_socket_addr: SocketAddr, - #[arg(value_parser = parse_info_hash)] - info_hash: TorrustInfoHash, - }, - Scrape { - #[arg(value_parser = parse_socket_addr)] - tracker_socket_addr: SocketAddr, - #[arg(value_parser = parse_info_hash, num_args = 1..=74, value_delimiter = ' ')] - info_hashes: Vec, - }, -} - -/// # Errors -/// -/// Will return an error if the command fails. -/// -/// -pub async fn run() -> anyhow::Result<()> { - tracing_stdout_init(LevelFilter::INFO); - - let args = Args::parse(); - - let response = match args.command { - Command::Announce { - tracker_socket_addr: remote_addr, - info_hash, - } => handle_announce(remote_addr, &info_hash).await?, - Command::Scrape { - tracker_socket_addr: remote_addr, - info_hashes, - } => handle_scrape(remote_addr, &info_hashes).await?, - }; - - let response: SerializableResponse = response.into(); - let response_json = response.to_json_string()?; - - print!("{response_json}"); - - Ok(()) -} - -fn tracing_stdout_init(filter: LevelFilter) { - tracing_subscriber::fmt().with_max_level(filter).init(); - tracing::debug!("Logging initialized"); -} - -async fn handle_announce(remote_addr: SocketAddr, info_hash: &TorrustInfoHash) -> Result { - let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); - - let client = checker::Client::new(remote_addr, DEFAULT_TIMEOUT).await?; - - let connection_id = client.send_connection_request(transaction_id).await?; - - client.send_announce_request(transaction_id, connection_id, *info_hash).await -} - -async fn handle_scrape(remote_addr: SocketAddr, info_hashes: &[TorrustInfoHash]) -> Result { - let transaction_id = TransactionId::new(RANDOM_TRANSACTION_ID); - - let client = checker::Client::new(remote_addr, DEFAULT_TIMEOUT).await?; - - let connection_id = client.send_connection_request(transaction_id).await?; - - client.send_scrape_request(connection_id, transaction_id, info_hashes).await -} - -fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result { - tracing::debug!("Tracker socket address: {tracker_socket_addr_str:#?}"); - - // Check if the address is a valid URL. If so, extract the host and port. - let resolved_addr = if let Ok(url) = Url::parse(tracker_socket_addr_str) { - tracing::debug!("Tracker socket address URL: {url:?}"); - - let host = url - .host_str() - .with_context(|| format!("invalid host in URL: `{tracker_socket_addr_str}`"))? - .to_owned(); - - let port = url - .port() - .with_context(|| format!("port not found in URL: `{tracker_socket_addr_str}`"))? - .to_owned(); - - (host, port) - } else { - // If not a URL, assume it's a host:port pair. - - let parts: Vec<&str> = tracker_socket_addr_str.split(':').collect(); - - if parts.len() != 2 { - return Err(anyhow::anyhow!( - "invalid address format: `{}`. Expected format is host:port", - tracker_socket_addr_str - )); - } - - let host = parts[0].to_owned(); - - let port = parts[1] - .parse::() - .with_context(|| format!("invalid port: `{}`", parts[1]))? - .to_owned(); - - (host, port) - }; - - tracing::debug!("Resolved address: {resolved_addr:#?}"); - - // Perform DNS resolution. - let socket_addrs: Vec<_> = resolved_addr.to_socket_addrs()?.collect(); - if socket_addrs.is_empty() { - Err(anyhow::anyhow!("DNS resolution failed for `{}`", tracker_socket_addr_str)) - } else { - Ok(socket_addrs[0]) - } -} - -fn parse_info_hash(info_hash_str: &str) -> anyhow::Result { - TorrustInfoHash::from_str(info_hash_str) - .map_err(|e| anyhow::Error::msg(format!("failed to parse info-hash `{info_hash_str}`: {e:?}"))) -} diff --git a/packages/tracker-client/src/console/clients/udp/checker.rs b/packages/tracker-client/src/console/clients/udp/checker.rs deleted file mode 100644 index b9fd3a729..000000000 --- a/packages/tracker-client/src/console/clients/udp/checker.rs +++ /dev/null @@ -1,177 +0,0 @@ -use std::net::{Ipv4Addr, SocketAddr}; -use std::num::NonZeroU16; -use std::time::Duration; - -use aquatic_udp_protocol::common::InfoHash; -use aquatic_udp_protocol::{ - AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, NumberOfBytes, NumberOfPeers, - PeerId, PeerKey, Port, Response, ScrapeRequest, TransactionId, -}; -use bittorrent_primitives::info_hash::InfoHash as TorrustInfoHash; - -use super::Error; -use crate::udp::client::UdpTrackerClient; - -/// A UDP Tracker client to make test requests (checks). -#[derive(Debug)] -pub struct Client { - client: UdpTrackerClient, -} - -impl Client { - /// Creates a new `[Client]` for checking a UDP Tracker Service - /// - /// # Errors - /// - /// It will error if unable to bind and connect to the udp remote address. - /// - pub async fn new(remote_addr: SocketAddr, timeout: Duration) -> Result { - let client = UdpTrackerClient::new(remote_addr, timeout) - .await - .map_err(|err| Error::UnableToBindAndConnect { remote_addr, err })?; - - Ok(Self { client }) - } - - /// Returns the local addr of this [`Client`]. - /// - /// # Errors - /// - /// This function will return an error if the socket is somehow not bound. - pub fn local_addr(&self) -> std::io::Result { - self.client.client.socket.local_addr() - } - - /// Sends a connection request to the UDP Tracker server. - /// - /// # Errors - /// - /// Will return and error if - /// - /// - It can't connect to the remote UDP socket. - /// - It can't make a connection request successfully to the remote UDP - /// server (after successfully connecting to the remote UDP socket). - /// - /// # Panics - /// - /// Will panic if it receives an unexpected response. - pub async fn send_connection_request(&self, transaction_id: TransactionId) -> Result { - tracing::debug!("Sending connection request with transaction id: {transaction_id:#?}"); - - let connect_request = ConnectRequest { transaction_id }; - - let _ = self - .client - .send(connect_request.into()) - .await - .map_err(|err| Error::UnableToSendConnectionRequest { err })?; - - let response = self - .client - .receive() - .await - .map_err(|err| Error::UnableToReceiveConnectResponse { err })?; - - match response { - Response::Connect(connect_response) => Ok(connect_response.connection_id), - _ => Err(Error::UnexpectedConnectionResponse { response }), - } - } - - /// Sends an announce request to the UDP Tracker server. - /// - /// # Errors - /// - /// Will return and error if the client is not connected. You have to connect - /// before calling this function. - /// - /// # Panics - /// - /// It will panic if the `local_address` has a zero port. - pub async fn send_announce_request( - &self, - transaction_id: TransactionId, - connection_id: ConnectionId, - info_hash: TorrustInfoHash, - ) -> Result { - tracing::debug!("Sending announce request with transaction id: {transaction_id:#?}"); - - let port = NonZeroU16::new( - self.client - .client - .socket - .local_addr() - .expect("it should get the local address") - .port(), - ) - .expect("it should no be zero"); - - let announce_request = AnnounceRequest { - connection_id, - action_placeholder: AnnounceActionPlaceholder::default(), - transaction_id, - info_hash: InfoHash(info_hash.bytes()), - peer_id: PeerId(*b"-qB00000000000000001"), - bytes_downloaded: NumberOfBytes(0i64.into()), - bytes_uploaded: NumberOfBytes(0i64.into()), - bytes_left: NumberOfBytes(0i64.into()), - event: AnnounceEvent::Started.into(), - ip_address: Ipv4Addr::new(0, 0, 0, 0).into(), - key: PeerKey::new(0i32), - peers_wanted: NumberOfPeers(1i32.into()), - port: Port::new(port), - }; - - let _ = self - .client - .send(announce_request.into()) - .await - .map_err(|err| Error::UnableToSendAnnounceRequest { err })?; - - let response = self - .client - .receive() - .await - .map_err(|err| Error::UnableToReceiveAnnounceResponse { err })?; - - Ok(response) - } - - /// Sends a scrape request to the UDP Tracker server. - /// - /// # Errors - /// - /// Will return and error if the client is not connected. You have to connect - /// before calling this function. - pub async fn send_scrape_request( - &self, - connection_id: ConnectionId, - transaction_id: TransactionId, - info_hashes: &[TorrustInfoHash], - ) -> Result { - tracing::debug!("Sending scrape request with transaction id: {transaction_id:#?}"); - - let scrape_request = ScrapeRequest { - connection_id, - transaction_id, - info_hashes: info_hashes - .iter() - .map(|torrust_info_hash| InfoHash(torrust_info_hash.bytes())) - .collect(), - }; - - let _ = self - .client - .send(scrape_request.into()) - .await - .map_err(|err| Error::UnableToSendScrapeRequest { err })?; - - let response = self - .client - .receive() - .await - .map_err(|err| Error::UnableToReceiveScrapeResponse { err })?; - - Ok(response) - } -} diff --git a/packages/tracker-client/src/console/clients/udp/mod.rs b/packages/tracker-client/src/console/clients/udp/mod.rs deleted file mode 100644 index ae6271a78..000000000 --- a/packages/tracker-client/src/console/clients/udp/mod.rs +++ /dev/null @@ -1,51 +0,0 @@ -use std::net::SocketAddr; - -use aquatic_udp_protocol::Response; -use serde::Serialize; -use thiserror::Error; - -use crate::udp; - -pub mod app; -pub mod checker; -pub mod responses; - -#[derive(Error, Debug, Clone, Serialize)] -#[serde(into = "String")] -pub enum Error { - #[error("Failed to Connect to: {remote_addr}, with error: {err}")] - UnableToBindAndConnect { remote_addr: SocketAddr, err: udp::Error }, - - #[error("Failed to send a connection request, with error: {err}")] - UnableToSendConnectionRequest { err: udp::Error }, - - #[error("Failed to receive a connect response, with error: {err}")] - UnableToReceiveConnectResponse { err: udp::Error }, - - #[error("Failed to send a announce request, with error: {err}")] - UnableToSendAnnounceRequest { err: udp::Error }, - - #[error("Failed to receive a announce response, with error: {err}")] - UnableToReceiveAnnounceResponse { err: udp::Error }, - - #[error("Failed to send a scrape request, with error: {err}")] - UnableToSendScrapeRequest { err: udp::Error }, - - #[error("Failed to receive a scrape response, with error: {err}")] - UnableToReceiveScrapeResponse { err: udp::Error }, - - #[error("Failed to receive a response, with error: {err}")] - UnableToReceiveResponse { err: udp::Error }, - - #[error("Failed to get local address for connection: {err}")] - UnableToGetLocalAddr { err: udp::Error }, - - #[error("Failed to get a connection response: {response:?}")] - UnexpectedConnectionResponse { response: Response }, -} - -impl From for String { - fn from(value: Error) -> Self { - value.to_string() - } -} diff --git a/packages/tracker-client/src/console/clients/udp/responses/dto.rs b/packages/tracker-client/src/console/clients/udp/responses/dto.rs deleted file mode 100644 index 93320b0f7..000000000 --- a/packages/tracker-client/src/console/clients/udp/responses/dto.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! Aquatic responses are not serializable. These are the serializable wrappers. -use std::net::{Ipv4Addr, Ipv6Addr}; - -use aquatic_udp_protocol::Response::{self}; -use aquatic_udp_protocol::{AnnounceResponse, ConnectResponse, ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, ScrapeResponse}; -use serde::Serialize; - -#[derive(Serialize)] -pub enum SerializableResponse { - Connect(ConnectSerializableResponse), - AnnounceIpv4(AnnounceSerializableResponse), - AnnounceIpv6(AnnounceSerializableResponse), - Scrape(ScrapeSerializableResponse), - Error(ErrorSerializableResponse), -} - -impl From for SerializableResponse { - fn from(response: Response) -> Self { - match response { - Response::Connect(response) => SerializableResponse::Connect(ConnectSerializableResponse::from(response)), - Response::AnnounceIpv4(response) => SerializableResponse::AnnounceIpv4(AnnounceSerializableResponse::from(response)), - Response::AnnounceIpv6(response) => SerializableResponse::AnnounceIpv6(AnnounceSerializableResponse::from(response)), - Response::Scrape(response) => SerializableResponse::Scrape(ScrapeSerializableResponse::from(response)), - Response::Error(response) => SerializableResponse::Error(ErrorSerializableResponse::from(response)), - } - } -} - -#[derive(Serialize)] -pub struct ConnectSerializableResponse { - transaction_id: i32, - connection_id: i64, -} - -impl From for ConnectSerializableResponse { - fn from(connect: ConnectResponse) -> Self { - Self { - transaction_id: connect.transaction_id.0.into(), - connection_id: connect.connection_id.0.into(), - } - } -} - -#[derive(Serialize)] -pub struct AnnounceSerializableResponse { - transaction_id: i32, - announce_interval: i32, - leechers: i32, - seeders: i32, - peers: Vec, -} - -impl From> for AnnounceSerializableResponse { - fn from(announce: AnnounceResponse) -> Self { - Self { - transaction_id: announce.fixed.transaction_id.0.into(), - announce_interval: announce.fixed.announce_interval.0.into(), - leechers: announce.fixed.leechers.0.into(), - seeders: announce.fixed.seeders.0.into(), - peers: announce - .peers - .iter() - .map(|peer| format!("{}:{}", Ipv4Addr::from(peer.ip_address), peer.port.0)) - .collect::>(), - } - } -} - -impl From> for AnnounceSerializableResponse { - fn from(announce: AnnounceResponse) -> Self { - Self { - transaction_id: announce.fixed.transaction_id.0.into(), - announce_interval: announce.fixed.announce_interval.0.into(), - leechers: announce.fixed.leechers.0.into(), - seeders: announce.fixed.seeders.0.into(), - peers: announce - .peers - .iter() - .map(|peer| format!("{}:{}", Ipv6Addr::from(peer.ip_address), peer.port.0)) - .collect::>(), - } - } -} - -#[derive(Serialize)] -pub struct ScrapeSerializableResponse { - transaction_id: i32, - torrent_stats: Vec, -} - -impl From for ScrapeSerializableResponse { - fn from(scrape: ScrapeResponse) -> Self { - Self { - transaction_id: scrape.transaction_id.0.into(), - torrent_stats: scrape - .torrent_stats - .iter() - .map(|torrent_scrape_statistics| TorrentStats { - seeders: torrent_scrape_statistics.seeders.0.into(), - completed: torrent_scrape_statistics.completed.0.into(), - leechers: torrent_scrape_statistics.leechers.0.into(), - }) - .collect::>(), - } - } -} - -#[derive(Serialize)] -pub struct ErrorSerializableResponse { - transaction_id: i32, - message: String, -} - -impl From for ErrorSerializableResponse { - fn from(error: ErrorResponse) -> Self { - Self { - transaction_id: error.transaction_id.0.into(), - message: error.message.to_string(), - } - } -} - -#[derive(Serialize)] -struct TorrentStats { - seeders: i32, - completed: i32, - leechers: i32, -} diff --git a/packages/tracker-client/src/console/clients/udp/responses/json.rs b/packages/tracker-client/src/console/clients/udp/responses/json.rs deleted file mode 100644 index 5d2bd6b89..000000000 --- a/packages/tracker-client/src/console/clients/udp/responses/json.rs +++ /dev/null @@ -1,25 +0,0 @@ -use anyhow::Context; -use serde::Serialize; - -use super::dto::SerializableResponse; - -#[allow(clippy::module_name_repetitions)] -pub trait ToJson { - /// - /// Returns a string with the JSON serialized version of the response - /// - /// # Errors - /// - /// Will return an error if serialization fails. - /// - fn to_json_string(&self) -> anyhow::Result - where - Self: Serialize, - { - let pretty_json = serde_json::to_string_pretty(self).context("response JSON serialization")?; - - Ok(pretty_json) - } -} - -impl ToJson for SerializableResponse {} diff --git a/packages/tracker-client/src/console/clients/udp/responses/mod.rs b/packages/tracker-client/src/console/clients/udp/responses/mod.rs deleted file mode 100644 index e6d2e5e51..000000000 --- a/packages/tracker-client/src/console/clients/udp/responses/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod dto; -pub mod json; diff --git a/packages/tracker-client/src/console/mod.rs b/packages/tracker-client/src/console/mod.rs deleted file mode 100644 index 4b4cb9de4..000000000 --- a/packages/tracker-client/src/console/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -//! Console apps. -pub mod clients; diff --git a/packages/tracker-client/src/http/url_encoding.rs b/packages/tracker-client/src/http/url_encoding.rs index ee7ab166e..6adb2e903 100644 --- a/packages/tracker-client/src/http/url_encoding.rs +++ b/packages/tracker-client/src/http/url_encoding.rs @@ -31,7 +31,7 @@ use torrust_tracker_primitives::peer; /// /// ```rust /// use std::str::FromStr; -/// use torrust_tracker::servers::http::percent_encoding::percent_decode_info_hash; +/// use bittorrent_tracker_client::http::url_encoding::percent_decode_info_hash; /// use bittorrent_primitives::info_hash::InfoHash; /// use torrust_tracker_primitives::peer; /// @@ -64,7 +64,7 @@ pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result Date: Wed, 13 Nov 2024 10:52:25 +0000 Subject: [PATCH 0515/1297] fix: add missing package in deployment workflow --- .github/workflows/deployment.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 7f458cda2..59913d476 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -55,6 +55,7 @@ jobs: env: CARGO_REGISTRY_TOKEN: "${{ secrets.TORRUST_UPDATE_CARGO_REGISTRY_TOKEN }}" run: | + cargo publish -p bittorrent-tracker-client cargo publish -p torrust-tracker cargo publish -p torrust-tracker-client cargo publish -p torrust-tracker-clock From 33980246bdb74a625139fe9fe356cb4c3a914699 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 13 Nov 2024 11:22:02 +0000 Subject: [PATCH 0516/1297] fix: tracker checker execution in CI --- src/console/ci/e2e/tracker_checker.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/console/ci/e2e/tracker_checker.rs b/src/console/ci/e2e/tracker_checker.rs index b4c2544ee..a39e68c93 100644 --- a/src/console/ci/e2e/tracker_checker.rs +++ b/src/console/ci/e2e/tracker_checker.rs @@ -8,13 +8,13 @@ use std::process::Command; /// Will return an error if the Tracker Checker fails. pub fn run(config_content: &str) -> io::Result<()> { tracing::info!( - "Running Tracker Checker: TORRUST_CHECKER_CONFIG=[config] cargo run -p bittorrent-tracker-client --bin tracker_checker" + "Running Tracker Checker: TORRUST_CHECKER_CONFIG=[config] cargo run -p torrust-tracker-client --bin tracker_checker" ); tracing::info!("Tracker Checker config:\n{config_content}"); let status = Command::new("cargo") .env("TORRUST_CHECKER_CONFIG", config_content) - .args(["run", "-p", "bittorrent-tracker-client", "--bin", "tracker_checker"]) + .args(["run", "-p", "torrust-tracker-client", "--bin", "tracker_checker"]) .status()?; if status.success() { From 4007530a4c773c48c9b5cfa38fb29d53503ff388 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 15 Nov 2024 07:03:30 +0000 Subject: [PATCH 0517/1297] chore(deps): update depencencies ```console cargo update Updating crates.io index Locking 59 packages to latest compatible versions Updating allocator-api2 v0.2.18 -> v0.2.20 Updating anstream v0.6.17 -> v0.6.18 Updating anstyle v1.0.9 -> v1.0.10 Updating anyhow v1.0.92 -> v1.0.93 Updating async-io v2.3.4 -> v2.4.0 Updating borsh v1.5.1 -> v1.5.3 Updating borsh-derive v1.5.1 -> v1.5.3 Updating cc v1.1.31 -> v1.2.1 Updating clap v4.5.20 -> v4.5.21 Updating clap_builder v4.5.20 -> v4.5.21 Updating clap_lex v0.7.2 -> v0.7.3 Updating cpufeatures v0.2.14 -> v0.2.15 Adding displaydoc v0.2.5 Updating fastrand v2.1.1 -> v2.2.0 Updating flate2 v1.0.34 -> v1.0.35 Updating futures-lite v2.4.0 -> v2.5.0 Updating hashbrown v0.15.0 -> v0.15.1 Removing heck v0.4.1 Adding icu_collections v1.5.0 Adding icu_locid v1.5.0 Adding icu_locid_transform v1.5.0 Adding icu_locid_transform_data v1.5.0 Adding icu_normalizer v1.5.0 Adding icu_normalizer_data v1.5.0 Adding icu_properties v1.5.1 Adding icu_properties_data v1.5.0 Adding icu_provider v1.5.0 Adding icu_provider_macros v1.5.0 Updating idna v0.5.0 -> v1.0.3 Adding idna_adapter v1.2.0 Updating libc v0.2.161 -> v0.2.162 Adding litemap v0.7.3 Updating mysql-common-derive v0.31.1 -> v0.31.2 Updating polling v3.7.3 -> v3.7.4 Removing proc-macro-error v1.0.4 Removing proc-macro-error-attr v1.0.4 Adding proc-macro-error-attr2 v2.0.0 Adding proc-macro-error2 v2.0.1 Updating regex-automata v0.4.8 -> v0.4.9 Updating rustix v0.38.38 -> v0.38.40 Updating security-framework-sys v2.12.0 -> v2.12.1 Updating serde v1.0.214 -> v1.0.215 Updating serde_derive v1.0.214 -> v1.0.215 Adding stable_deref_trait v1.2.0 Updating syn v2.0.86 -> v2.0.87 Removing syn_derive v0.1.8 Adding synstructure v0.13.1 Updating tempfile v3.13.0 -> v3.14.0 Updating thiserror v1.0.66 -> v1.0.69 (available: v2.0.3) Updating thiserror-impl v1.0.66 -> v1.0.69 Adding tinystr v0.7.6 Updating tokio v1.41.0 -> v1.41.1 Removing unicode-bidi v0.3.17 Removing unicode-normalization v0.1.24 Updating url v2.5.2 -> v2.5.3 Adding utf16_iter v1.0.5 Adding utf8_iter v1.0.4 Adding write16 v1.0.0 Adding writeable v0.5.5 Adding yoke v0.7.4 Adding yoke-derive v0.7.4 Adding zerofrom v0.1.4 Adding zerofrom-derive v0.1.4 Adding zerovec v0.10.4 Adding zerovec-derive v0.10.3 ``` --- Cargo.lock | 516 ++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 372 insertions(+), 144 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bbb012cea..20de3d0dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -66,9 +66,9 @@ dependencies = [ [[package]] name = "allocator-api2" -version = "0.2.18" +version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" +checksum = "45862d1c77f2228b9e10bc609d5bc203d86ebc9b87ad8d5d5167a6c9abf739d9" [[package]] name = "android-tzdata" @@ -93,9 +93,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.17" +version = "0.6.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23a1e53f0f5d86382dafe1cf314783b2044280f406e7e1506368220ad11b1338" +checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" dependencies = [ "anstyle", "anstyle-parse", @@ -108,9 +108,9 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8365de52b16c035ff4fcafe0092ba9390540e3e352870ac09933bebcaa2c8c56" +checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" [[package]] name = "anstyle-parse" @@ -142,9 +142,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.92" +version = "1.0.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74f37166d7d48a0284b99dd824694c26119c700b53bf0d1540cdb147dbdaaf13" +checksum = "4c95c10ba0b00a02636238b814946408b1322d5ac4760326e6fb8ec956d85775" [[package]] name = "aquatic_peer_id" @@ -264,9 +264,9 @@ dependencies = [ [[package]] name = "async-io" -version = "2.3.4" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "444b0228950ee6501b3568d3c93bf1176a1fdbc3b758dcd9475046d30f4dc7e8" +checksum = "43a2b323ccce0a1d90b449fd71f2a06ca7faa7c54c2751f06c9bd851fc061059" dependencies = [ "async-lock", "cfg-if", @@ -333,7 +333,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -482,7 +482,7 @@ checksum = "57d123550fa8d071b7255cb0cc04dc302baa6c8c4a79f55701552684d8399bce" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -574,7 +574,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.86", + "syn 2.0.87", "which", ] @@ -593,7 +593,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -675,9 +675,9 @@ dependencies = [ [[package]] name = "borsh" -version = "1.5.1" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6362ed55def622cddc70a4746a68554d7b687713770de539e59a739b249f8ed" +checksum = "2506947f73ad44e344215ccd6403ac2ae18cd8e046e581a441bf8d199f257f03" dependencies = [ "borsh-derive", "cfg_aliases", @@ -685,16 +685,15 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.5.1" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3ef8005764f53cd4dca619f5bf64cafd4664dada50ece25e4d81de54c80cc0b" +checksum = "c2593a3b8b938bd68373196c9832f516be11fa487ef4ae745eb282e6a56a7244" dependencies = [ "once_cell", "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.86", - "syn_derive", + "syn 2.0.87", ] [[package]] @@ -805,9 +804,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.1.31" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2e7962b54006dcfcc61cb72735f4d89bb97061dd6a7ed882ec6b8ee53714c6f" +checksum = "fd9de9f2205d5ef3fd67e685b0df337994ddd4495e2a28d185500d0e1edfea47" dependencies = [ "jobserver", "libc", @@ -888,9 +887,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.20" +version = "4.5.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97f376d85a664d5837dbae44bf546e6477a679ff6610010f17276f686d867e8" +checksum = "fb3b4b9e5a7c7514dfa52869339ee98b3156b0bfb4e8a77c4ff4babb64b1604f" dependencies = [ "clap_builder", "clap_derive", @@ -898,9 +897,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.20" +version = "4.5.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19bc80abd44e4bed93ca373a0704ccbd1b710dc5749406201bb018272808dc54" +checksum = "b17a95aa67cc7b5ebd32aa5370189aa0d79069ef1c64ce893bd30fb24bff20ec" dependencies = [ "anstream", "anstyle", @@ -914,17 +913,17 @@ version = "4.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" dependencies = [ - "heck 0.5.0", + "heck", "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] name = "clap_lex" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1462739cb27611015575c0c11df5df7601141071f07518d56fcc1be504cbec97" +checksum = "afb84c814227b90d6895e01398aee0d8033c00e7466aca416fb6a8e0eb19d8a7" [[package]] name = "cmake" @@ -981,9 +980,9 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpufeatures" -version = "0.2.14" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "608697df725056feaccfa42cffdaeeec3fccc4ffc38358ecd19b243e716a78e0" +checksum = "0ca741a962e1b0bff6d724a1a0958b686406e853bb14061f218562e1896f95e6" dependencies = [ "libc", ] @@ -1138,7 +1137,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -1149,7 +1148,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -1193,7 +1192,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", "unicode-xid", ] @@ -1205,7 +1204,7 @@ checksum = "65f152f4b8559c4da5d574bafc7af85454d706b4c5fe8b530d508cacbb6807ea" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -1218,6 +1217,17 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + [[package]] name = "downcast" version = "0.11.0" @@ -1312,9 +1322,9 @@ checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" [[package]] name = "fastrand" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8c02a5121d4ea3eb16a80748c74f5549a5665e4c21333c6098f283870fbdea6" +checksum = "486f806e73c5707928240ddc295403b1b93c96a02038563881c4a2fd84b81ac4" [[package]] name = "figment" @@ -1334,9 +1344,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.34" +version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1b589b4dc103969ad3cf85c950899926ec64300a1a46d76c03a6072957036f0" +checksum = "c936bfdafb507ebbf50b8074c54fa31c5be9a1e7e5f467dd659697041407d07c" dependencies = [ "crc32fast", "libz-sys", @@ -1424,7 +1434,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -1436,7 +1446,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -1448,7 +1458,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -1513,9 +1523,9 @@ checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" [[package]] name = "futures-lite" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f1fa2f9765705486b33fd2acf1577f8ec449c2ba1f318ae5447697b7c08d210" +checksum = "cef40d21ae2c515b51041df9ed313ed21e572df340ea58a922a0aefe7e8891a1" dependencies = [ "fastrand", "futures-core", @@ -1532,7 +1542,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -1665,9 +1675,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.15.0" +version = "0.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e087f84d4f86bf4b218b927129862374b72199ae7d8657835f1e89000eea4fb" +checksum = "3a9bfc1af68b1726ea47d3d5109de126281def866b33970e10fbab11b5dafab3" dependencies = [ "allocator-api2", "equivalent", @@ -1683,12 +1693,6 @@ dependencies = [ "hashbrown 0.14.5", ] -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - [[package]] name = "heck" version = "0.5.0" @@ -1870,6 +1874,124 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_collections" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locid" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locid_transform" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_locid_transform_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locid_transform_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" + +[[package]] +name = "icu_normalizer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" + +[[package]] +name = "icu_properties" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93d6020766cfc6302c15dbbc9c8778c37e62c14427cb7f6e601d849e092aeef5" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locid_transform", + "icu_properties_data", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" + +[[package]] +name = "icu_provider" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" +dependencies = [ + "displaydoc", + "icu_locid", + "icu_provider_macros", + "stable_deref_trait", + "tinystr", + "writeable", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_provider_macros" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + [[package]] name = "ident_case" version = "1.0.1" @@ -1878,12 +2000,23 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "idna" -version = "0.5.0" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" +checksum = "daca1df1c957320b2cf139ac61e7bd64fed304c5040df000a745aa1de3b4ef71" dependencies = [ - "unicode-bidi", - "unicode-normalization", + "icu_normalizer", + "icu_properties", ] [[package]] @@ -1904,7 +2037,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" dependencies = [ "equivalent", - "hashbrown 0.15.0", + "hashbrown 0.15.1", "serde", ] @@ -2020,9 +2153,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.161" +version = "0.2.162" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9489c2807c139ffd9c1794f4af0ebe86a828db53ecdc7fea2111d0fed085d1" +checksum = "18d287de67fe55fd7e1581fe933d965a5a9477b38e949cfa9f8574ef01506398" [[package]] name = "libloading" @@ -2068,6 +2201,12 @@ version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" +[[package]] +name = "litemap" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" + [[package]] name = "local-ip-address" version = "0.6.3" @@ -2105,7 +2244,7 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" dependencies = [ - "hashbrown 0.15.0", + "hashbrown 0.15.1", ] [[package]] @@ -2182,7 +2321,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -2221,18 +2360,18 @@ dependencies = [ [[package]] name = "mysql-common-derive" -version = "0.31.1" +version = "0.31.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afe0450cc9344afff34915f8328600ab5ae19260802a334d0f72d2d5bdda3bfe" +checksum = "63c3512cf11487168e0e9db7157801bf5273be13055a9cc95356dc9e0035e49c" dependencies = [ "darling", - "heck 0.4.1", + "heck", "num-bigint", "proc-macro-crate", - "proc-macro-error", + "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", "termcolor", "thiserror", ] @@ -2431,7 +2570,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -2513,7 +2652,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -2587,7 +2726,7 @@ checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -2649,9 +2788,9 @@ dependencies = [ [[package]] name = "polling" -version = "3.7.3" +version = "3.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc2790cd301dec6cd3b7a025e4815cf825724a51c98dccfe6a3e55f05ffb6511" +checksum = "a604568c3202727d1507653cb121dbd627a58684eb09a820fd746bee38b4442f" dependencies = [ "cfg-if", "concurrent-queue", @@ -2716,7 +2855,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64d1ec885c64d0457d564db4ec299b2dae3f9c02808b8ad9c3a089c591b18033" dependencies = [ "proc-macro2", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -2729,27 +2868,25 @@ dependencies = [ ] [[package]] -name = "proc-macro-error" -version = "1.0.4" +name = "proc-macro-error-attr2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" dependencies = [ - "proc-macro-error-attr", "proc-macro2", "quote", - "syn 1.0.109", - "version_check", ] [[package]] -name = "proc-macro-error-attr" -version = "1.0.4" +name = "proc-macro-error2" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" dependencies = [ + "proc-macro-error-attr2", "proc-macro2", "quote", - "version_check", + "syn 2.0.87", ] [[package]] @@ -2769,7 +2906,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", "version_check", "yansi", ] @@ -2925,9 +3062,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.8" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3" +checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" dependencies = [ "aho-corasick", "memchr", @@ -3078,7 +3215,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.86", + "syn 2.0.87", "unicode-ident", ] @@ -3135,9 +3272,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.38" +version = "0.38.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa260229e6538e52293eeb577aabd09945a09d6d9cc0fc550ed7529056c2e32a" +checksum = "99e4ea3e1cdc4b559b8e5650f9c8e5998e3e5c1343b4eaf034565f32318d63c0" dependencies = [ "bitflags", "errno", @@ -3259,9 +3396,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.12.0" +version = "2.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea4a292869320c0272d7bc55a5a6aafaff59b4f63404a003887b679a2e05b4b6" +checksum = "fa39c7303dc58b5543c94d22c1766b0d31f2ee58306363ea622b10bbc075eaa2" dependencies = [ "core-foundation-sys", "libc", @@ -3275,9 +3412,9 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" -version = "1.0.214" +version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f55c3193aca71c12ad7890f1785d2b73e1b9f63a0bbc353c08ef26fe03fc56b5" +checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" dependencies = [ "serde_derive", ] @@ -3303,13 +3440,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.214" +version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de523f781f095e28fa605cdce0f8307e451cc0fd14e2eb4cd2e98a355b147766" +checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -3356,7 +3493,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -3407,7 +3544,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -3499,6 +3636,12 @@ version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + [[package]] name = "static_assertions" version = "1.1.0" @@ -3540,27 +3683,15 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.86" +version = "2.0.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e89275301d38033efb81a6e60e3497e734dfcc62571f2854bf4b16690398824c" +checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] -[[package]] -name = "syn_derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1329189c02ff984e9736652b1631330da25eaa6bc639089ed4915d25446cbe7b" -dependencies = [ - "proc-macro-error", - "proc-macro2", - "quote", - "syn 2.0.86", -] - [[package]] name = "sync_wrapper" version = "0.1.2" @@ -3576,6 +3707,17 @@ dependencies = [ "futures-core", ] +[[package]] +name = "synstructure" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + [[package]] name = "system-configuration" version = "0.6.1" @@ -3622,9 +3764,9 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.13.0" +version = "3.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0f2c9fc62d0beef6951ccffd757e241266a2c833136efbe35af6cd2567dca5b" +checksum = "28cce251fcbc87fac86a866eeb0d6c2d536fc16d06f184bb61aeae11aa4cee0c" dependencies = [ "cfg-if", "fastrand", @@ -3650,22 +3792,22 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.66" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d171f59dbaa811dbbb1aee1e73db92ec2b122911a48e1390dfe327a821ddede" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.66" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b08be0f17bd307950653ce45db00cd31200d82b624b36e181337d9c7d92765b5" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -3709,6 +3851,16 @@ dependencies = [ "time-core", ] +[[package]] +name = "tinystr" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "tinytemplate" version = "1.2.1" @@ -3736,9 +3888,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.41.0" +version = "1.41.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "145f3413504347a2be84393cc8a7d2fb4d863b375909ea59f2158261aa258bbb" +checksum = "22cfb5bee7a6a52939ca9224d6ac897bb669134078daa8735560897f69de4d33" dependencies = [ "backtrace", "bytes", @@ -3759,7 +3911,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -4086,7 +4238,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", ] [[package]] @@ -4169,27 +4321,12 @@ dependencies = [ "version_check", ] -[[package]] -name = "unicode-bidi" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ab17db44d7388991a428b2ee655ce0c212e862eff1768a455c58f9aad6e7893" - [[package]] name = "unicode-ident" version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" -[[package]] -name = "unicode-normalization" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5033c97c4262335cded6d6fc3e5c18ab755e1a3dc96376350f3d8e9f009ad956" -dependencies = [ - "tinyvec", -] - [[package]] name = "unicode-xid" version = "0.2.6" @@ -4204,9 +4341,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.2" +version = "2.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c" +checksum = "8d157f1b96d14500ffdc1f10ba712e780825526c03d9a49b4d0324b0d9113ada" dependencies = [ "form_urlencoded", "idna", @@ -4214,6 +4351,18 @@ dependencies = [ "serde", ] +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "utf8parse" version = "0.2.2" @@ -4301,7 +4450,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", "wasm-bindgen-shared", ] @@ -4335,7 +4484,7 @@ checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4529,6 +4678,18 @@ dependencies = [ "memchr", ] +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" + [[package]] name = "wyz" version = "0.5.1" @@ -4544,6 +4705,30 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" +[[package]] +name = "yoke" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" +dependencies = [ + "serde", + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.7.35" @@ -4562,7 +4747,28 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.86", + "syn 2.0.87", +] + +[[package]] +name = "zerofrom" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", + "synstructure", ] [[package]] @@ -4571,6 +4777,28 @@ version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" +[[package]] +name = "zerovec" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa2b893d79df23bfb12d5461018d408ea19dfafe76c2c7ef6d4eba614f8ff079" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + [[package]] name = "zstd" version = "0.13.2" From fcef4aadb5ee7300acfaddc1ed25f398dda27de2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 15 Nov 2024 07:42:09 +0000 Subject: [PATCH 0518/1297] chore(deps): bump thiserror from 1.0.66 to 2.0.3 --- Cargo.lock | 46 +++++++++++++++++++++++++++++++++------------- Cargo.toml | 2 +- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 20de3d0dc..be96e6580 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -612,7 +612,7 @@ dependencies = [ "binascii", "serde", "serde_json", - "thiserror", + "thiserror 1.0.69", "zerocopy", ] @@ -630,7 +630,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_repr", - "thiserror", + "thiserror 1.0.69", "tokio", "torrust-tracker-configuration", "torrust-tracker-located-error", @@ -1396,7 +1396,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8835f84f38484cc86f110a805655697908257fb9a7af005234060891557198e9" dependencies = [ "nonempty", - "thiserror", + "thiserror 1.0.69", ] [[package]] @@ -2215,7 +2215,7 @@ checksum = "3669cf5561f8d27e8fc84cc15e58350e70f557d4d65f70e3154e54cd2f8e1782" dependencies = [ "libc", "neli", - "thiserror", + "thiserror 1.0.69", "windows-sys 0.59.0", ] @@ -2373,7 +2373,7 @@ dependencies = [ "quote", "syn 2.0.87", "termcolor", - "thiserror", + "thiserror 1.0.69", ] [[package]] @@ -2409,7 +2409,7 @@ dependencies = [ "sha2", "smallvec", "subprocess", - "thiserror", + "thiserror 1.0.69", "time", "uuid", "zstd", @@ -3796,7 +3796,16 @@ version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c006c85c7651b3cf2ada4584faa36773bd07bac24acfb39f3c431b36d7e667aa" +dependencies = [ + "thiserror-impl 2.0.3", ] [[package]] @@ -3810,6 +3819,17 @@ dependencies = [ "syn 2.0.87", ] +[[package]] +name = "thiserror-impl" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + [[package]] name = "thread_local" version = "1.1.8" @@ -4026,7 +4046,7 @@ dependencies = [ "serde_json", "serde_repr", "serde_with", - "thiserror", + "thiserror 2.0.3", "tokio", "torrust-tracker-clock", "torrust-tracker-configuration", @@ -4061,7 +4081,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_json", - "thiserror", + "thiserror 1.0.69", "tokio", "torrust-tracker-configuration", "tracing", @@ -4088,7 +4108,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror", + "thiserror 1.0.69", "toml", "torrust-tracker-located-error", "url", @@ -4100,14 +4120,14 @@ name = "torrust-tracker-contrib-bencode" version = "3.0.0-develop" dependencies = [ "criterion", - "thiserror", + "thiserror 1.0.69", ] [[package]] name = "torrust-tracker-located-error" version = "3.0.0-develop" dependencies = [ - "thiserror", + "thiserror 1.0.69", "tracing", ] @@ -4122,7 +4142,7 @@ dependencies = [ "serde", "tdyne-peer-id", "tdyne-peer-id-registry", - "thiserror", + "thiserror 1.0.69", "zerocopy", ] diff --git a/Cargo.toml b/Cargo.toml index bc772d08a..f9e7eff3b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,7 +68,7 @@ serde_bytes = "0" serde_json = { version = "1", features = ["preserve_order"] } serde_repr = "0" serde_with = { version = "3", features = ["json"] } -thiserror = "1" +thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } From 4dd6659abc264f752997bff3bf8bd528bc517a6a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 15 Nov 2024 08:21:05 +0000 Subject: [PATCH 0519/1297] ci: [#1075] remove current coverage workflow --- .github/workflows/coverage.yaml | 85 --------------------------------- 1 file changed, 85 deletions(-) delete mode 100644 .github/workflows/coverage.yaml diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml deleted file mode 100644 index 28c1be6d0..000000000 --- a/.github/workflows/coverage.yaml +++ /dev/null @@ -1,85 +0,0 @@ -name: Coverage - -on: - push: - branches: - - develop - pull_request_target: - branches: - - develop - -env: - CARGO_TERM_COLOR: always - -jobs: - report: - name: Report - environment: coverage - runs-on: ubuntu-latest - env: - CARGO_INCREMENTAL: "0" - RUSTFLAGS: "-Z profile -C codegen-units=1 -C opt-level=0 -C link-dead-code -C overflow-checks=off -Z panic_abort_tests -C panic=abort" - RUSTDOCFLAGS: "-Z profile -C codegen-units=1 -C opt-level=0 -C link-dead-code -C overflow-checks=off -Z panic_abort_tests -C panic=abort" - - steps: - - id: checkout_push - if: github.event_name == 'push' - name: Checkout Repository (Push) - uses: actions/checkout@v4 - - - id: checkout_pull_request_target - if: github.event_name == 'pull_request_target' - name: Checkout Repository (Pull Request Target) - uses: actions/checkout@v4 - with: - ref: "refs/pull/${{ github.event.pull_request.number }}/head" - - - id: setup - name: Setup Toolchain - uses: dtolnay/rust-toolchain@nightly - with: - toolchain: nightly - components: llvm-tools-preview - - - id: cache - name: Enable Workflow Cache - uses: Swatinem/rust-cache@v2 - - - id: tools - name: Install Tools - uses: taiki-e/install-action@v2 - with: - tool: grcov - - - id: check - name: Run Build Checks - run: cargo check --tests --benches --examples --workspace --all-targets --all-features - - - id: clean - name: Clean Build Directory - run: cargo clean - - - id: build - name: Pre-build Main Project - run: cargo build --workspace --all-targets --all-features --jobs 2 - - - id: build_tests - name: Pre-build Tests - run: cargo build --workspace --all-targets --all-features --tests --jobs 2 - - - id: test - name: Run Unit Tests - run: cargo test --tests --workspace --all-targets --all-features - - - id: coverage - name: Generate Coverage Report - uses: alekitto/grcov@v0.2 - - - id: upload - name: Upload Coverage Report - uses: codecov/codecov-action@v3 - with: - token: ${{ secrets.CODECOV_TOKEN }} - files: ${{ steps.coverage.outputs.report }} - verbose: true - fail_ci_if_error: true From 9d8174df6f0913abd65a90538619f9036cb38a13 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 15 Nov 2024 08:22:22 +0000 Subject: [PATCH 0520/1297] ci: [#1075] fix coverage report --- .cargo/config.toml | 1 + .github/workflows/generate_coverage.yaml | 87 +++++++++++++++++ .github/workflows/upload_coverage.yaml | 119 +++++++++++++++++++++++ .gitignore | 6 +- 4 files changed, 211 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/generate_coverage.yaml create mode 100644 .github/workflows/upload_coverage.yaml diff --git a/.cargo/config.toml b/.cargo/config.toml index a88db5f38..28cde74ec 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,6 +1,7 @@ [alias] cov = "llvm-cov" cov-lcov = "llvm-cov --lcov --output-path=./.coverage/lcov.info" +cov-codecov = "llvm-cov --codecov --output-path=./.coverage/codecov.json" cov-html = "llvm-cov --html" time = "build --timings --all-targets" diff --git a/.github/workflows/generate_coverage.yaml b/.github/workflows/generate_coverage.yaml new file mode 100644 index 000000000..8de299c74 --- /dev/null +++ b/.github/workflows/generate_coverage.yaml @@ -0,0 +1,87 @@ +name: Generate Coverage Report + +on: + push: + branches: + - develop + pull_request: + branches: + - develop + +env: + CARGO_TERM_COLOR: always + +jobs: + coverage: + name: Generate Coverage Report + environment: coverage + runs-on: ubuntu-latest + env: + CARGO_INCREMENTAL: "0" + RUSTFLAGS: "-Cinstrument-coverage" + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install LLVM tools + run: sudo apt-get update && sudo apt-get install -y llvm + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@nightly + with: + toolchain: nightly + components: llvm-tools-preview + + - id: cache + name: Enable Workflow Cache + uses: Swatinem/rust-cache@v2 + + - id: tools + name: Install Tools + uses: taiki-e/install-action@v2 + with: + tool: grcov,cargo-llvm-cov + + - id: coverage + name: Generate Coverage Report + run: | + cargo clean + cargo llvm-cov --all-features --workspace --codecov --output-path ./codecov.json + + - name: Store PR number and commit SHA + run: | + echo "Storing PR number ${{ github.event.number }}" + echo "${{ github.event.number }}" > pr_number.txt + + echo "Storing commit SHA ${{ github.event.pull_request.head.sha }}" + echo "${{ github.event.pull_request.head.sha }}" > commit_sha.txt + + # Workaround for https://github.com/orgs/community/discussions/25220 + # Triggered sub-workflow is not able to detect the original commit/PR which is available + # in this workflow. + - name: Store PR number + uses: actions/upload-artifact@v4 + with: + name: pr_number + path: pr_number.txt + + - name: Store commit SHA + uses: actions/upload-artifact@v4 + with: + name: commit_sha + path: commit_sha.txt + + # This stores the coverage report in artifacts. The actual upload to Codecov + # is executed by a different workflow `upload_coverage.yml`. The reason for this + # split is because `on.pull_request` workflows don't have access to secrets. + - name: Store coverage report in artifacts + uses: actions/upload-artifact@v4 + with: + name: codecov_report + path: ./codecov.json + + - run: | + echo "The coverage report was stored in Github artifacts." + echo "It will be uploaded to Codecov using [upload_coverage.yml] workflow shortly." diff --git a/.github/workflows/upload_coverage.yaml b/.github/workflows/upload_coverage.yaml new file mode 100644 index 000000000..b9a65ae7c --- /dev/null +++ b/.github/workflows/upload_coverage.yaml @@ -0,0 +1,119 @@ +name: Upload Coverage Report + +on: + # This workflow is triggered after every successfull execution + # of `Generate Coverage Report` workflow. + workflow_run: + workflows: ["Generate Coverage Report"] + types: + - completed + +permissions: + actions: write + contents: write + issues: write + pull-requests: write + +jobs: + coverage: + name: Upload Coverage Report + environment: coverage + runs-on: ubuntu-latest + steps: + - name: "Download existing coverage report" + id: prepare_report + uses: actions/github-script@v7 + with: + script: | + var fs = require('fs'); + + // List artifacts of the workflow run that triggered this workflow + var artifacts = await github.rest.actions.listWorkflowRunArtifacts({ + owner: context.repo.owner, + repo: context.repo.repo, + run_id: context.payload.workflow_run.id, + }); + + let codecovReport = artifacts.data.artifacts.filter((artifact) => { + return artifact.name == "codecov_report"; + }); + + if (codecovReport.length != 1) { + throw new Error("Unexpected number of {codecov_report} artifacts: " + codecovReport.length); + } + + var download = await github.rest.actions.downloadArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: codecovReport[0].id, + archive_format: 'zip', + }); + fs.writeFileSync('codecov_report.zip', Buffer.from(download.data)); + + let prNumber = artifacts.data.artifacts.filter((artifact) => { + return artifact.name == "pr_number"; + }); + + if (prNumber.length != 1) { + throw new Error("Unexpected number of {pr_number} artifacts: " + prNumber.length); + } + + var download = await github.rest.actions.downloadArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: prNumber[0].id, + archive_format: 'zip', + }); + fs.writeFileSync('pr_number.zip', Buffer.from(download.data)); + + let commitSha = artifacts.data.artifacts.filter((artifact) => { + return artifact.name == "commit_sha"; + }); + + if (commitSha.length != 1) { + throw new Error("Unexpected number of {commit_sha} artifacts: " + commitSha.length); + } + + var download = await github.rest.actions.downloadArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: commitSha[0].id, + archive_format: 'zip', + }); + fs.writeFileSync('commit_sha.zip', Buffer.from(download.data)); + + - id: parse_previous_artifacts + run: | + unzip codecov_report.zip + unzip pr_number.zip + unzip commit_sha.zip + + echo "Detected PR is: $(> "$GITHUB_OUTPUT" + echo "override_commit=$(> "$GITHUB_OUTPUT" + + - name: Checkout repository + uses: actions/checkout@v4 + with: + ref: ${{ steps.parse_previous_artifacts.outputs.override_commit || '' }} + path: repo_root + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v5 + with: + verbose: true + token: ${{ secrets.CODECOV_TOKEN }} + files: ${{ github.workspace }}/codecov.json + fail_ci_if_error: true + # Manual overrides for these parameters are needed because automatic detection + # in codecov-action does not work for non-`pull_request` workflows. + # In `main` branch push, these default to empty strings since we want to run + # the analysis on HEAD. + override_commit: ${{ steps.parse_previous_artifacts.outputs.override_commit || '' }} + override_pr: ${{ steps.parse_previous_artifacts.outputs.override_pr || '' }} + working-directory: ${{ github.workspace }}/repo_root + # Location where coverage report files are searched for + directory: ${{ github.workspace }} diff --git a/.gitignore b/.gitignore index b60b28991..d9087bcff 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .env +*.code-workspace **/*.rs.bk /.coverage/ /.idea/ @@ -12,5 +13,6 @@ /tracker.* /tracker.toml callgrind.out -perf.data* -*.code-workspace \ No newline at end of file +codecov.json +lcov.info +perf.data* \ No newline at end of file From 0950eb12b042f2e86a19b75e2a3fec1484a3e991 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 15 Nov 2024 11:06:12 +0000 Subject: [PATCH 0521/1297] ci: [1075] coverage report for push event The new coverage workflows (generate and upload) only work for PRs. We have to keep the old one for push events. --- .github/workflows/coverage.yaml | 57 +++++++++++++++++++ ...overage.yaml => generate_coverage_pr.yaml} | 5 +- ..._coverage.yaml => upload_coverage_pr.yaml} | 4 +- 3 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/coverage.yaml rename .github/workflows/{generate_coverage.yaml => generate_coverage_pr.yaml} (97%) rename .github/workflows/{upload_coverage.yaml => upload_coverage_pr.yaml} (98%) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml new file mode 100644 index 000000000..e10c5ac66 --- /dev/null +++ b/.github/workflows/coverage.yaml @@ -0,0 +1,57 @@ +name: Coverage + +on: + push: + branches: + - develop + +env: + CARGO_TERM_COLOR: always + +jobs: + report: + name: Generate Coverage Report + environment: coverage + runs-on: ubuntu-latest + env: + CARGO_INCREMENTAL: "0" + RUSTFLAGS: "-Cinstrument-coverage" + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install LLVM tools + run: sudo apt-get update && sudo apt-get install -y llvm + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@nightly + with: + toolchain: nightly + components: llvm-tools-preview + + - id: cache + name: Enable Workflow Cache + uses: Swatinem/rust-cache@v2 + + - id: tools + name: Install Tools + uses: taiki-e/install-action@v2 + with: + tool: grcov,cargo-llvm-cov + + - id: coverage + name: Generate Coverage Report + run: | + cargo clean + cargo llvm-cov --all-features --workspace --codecov --output-path ./codecov.json + + - id: upload + name: Upload Coverage Report + uses: codecov/codecov-action@v5 + with: + verbose: true + token: ${{ secrets.CODECOV_TOKEN }} + files: ${{ github.workspace }}/codecov.json + fail_ci_if_error: true \ No newline at end of file diff --git a/.github/workflows/generate_coverage.yaml b/.github/workflows/generate_coverage_pr.yaml similarity index 97% rename from .github/workflows/generate_coverage.yaml rename to .github/workflows/generate_coverage_pr.yaml index 8de299c74..d1b241b9d 100644 --- a/.github/workflows/generate_coverage.yaml +++ b/.github/workflows/generate_coverage_pr.yaml @@ -1,9 +1,6 @@ -name: Generate Coverage Report +name: Generate Coverage Report (PR) on: - push: - branches: - - develop pull_request: branches: - develop diff --git a/.github/workflows/upload_coverage.yaml b/.github/workflows/upload_coverage_pr.yaml similarity index 98% rename from .github/workflows/upload_coverage.yaml rename to .github/workflows/upload_coverage_pr.yaml index b9a65ae7c..1ed2f7bcc 100644 --- a/.github/workflows/upload_coverage.yaml +++ b/.github/workflows/upload_coverage_pr.yaml @@ -1,10 +1,10 @@ -name: Upload Coverage Report +name: Upload Coverage Report (PR) on: # This workflow is triggered after every successfull execution # of `Generate Coverage Report` workflow. workflow_run: - workflows: ["Generate Coverage Report"] + workflows: ["Generate Coverage Report (PR)"] types: - completed From e3562f0694b78eb3fe4941fea1ad4f85f359e854 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Mon, 18 Nov 2024 11:32:05 +0800 Subject: [PATCH 0522/1297] udp: symmetric encrypted cookie --- Cargo.lock | 31 + Cargo.toml | 2 + cSpell.json | 3 + packages/clock/src/lib.rs | 11 - packages/clock/src/time_extent/mod.rs | 665 ------------------ .../configuration/src/v2_0_0/udp_tracker.rs | 11 + packages/test-helpers/src/configuration.rs | 2 + src/bootstrap/app.rs | 22 + src/bootstrap/jobs/udp_tracker.rs | 3 +- src/lib.rs | 12 +- src/servers/udp/connection_cookie.rs | 468 ++++++------ src/servers/udp/error.rs | 22 +- src/servers/udp/handlers.rs | 286 ++++++-- src/servers/udp/server/launcher.rs | 9 +- src/servers/udp/server/mod.rs | 4 +- src/servers/udp/server/processor.rs | 25 +- src/servers/udp/server/spawner.rs | 4 +- src/servers/udp/server/states.rs | 10 +- src/shared/crypto/ephemeral_instance_keys.rs | 12 + src/shared/crypto/keys.rs | 192 +++-- tests/servers/udp/environment.rs | 7 +- 21 files changed, 711 insertions(+), 1090 deletions(-) delete mode 100644 packages/clock/src/time_extent/mod.rs diff --git a/Cargo.lock b/Cargo.lock index be96e6580..5d07ba62f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -673,6 +673,16 @@ dependencies = [ "piper", ] +[[package]] +name = "blowfish" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7" +dependencies = [ + "byteorder", + "cipher", +] + [[package]] name = "borsh" version = "1.5.3" @@ -874,6 +884,16 @@ dependencies = [ "half", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + [[package]] name = "clang-sys" version = "1.8.1" @@ -2047,6 +2067,15 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" +[[package]] +name = "inout" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" +dependencies = [ + "generic-array", +] + [[package]] name = "io-enum" version = "1.1.3" @@ -4014,8 +4043,10 @@ dependencies = [ "axum-server", "bittorrent-primitives", "bittorrent-tracker-client", + "blowfish", "camino", "chrono", + "cipher", "clap", "crossbeam-skiplist", "dashmap", diff --git a/Cargo.toml b/Cargo.toml index f9e7eff3b..35b1ac9a7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,8 +38,10 @@ axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls"] } bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } +blowfish = "0" camino = { version = "1", features = ["serde", "serde1"] } chrono = { version = "0", default-features = false, features = ["clock"] } +cipher = "0" clap = { version = "4", features = ["derive", "env"] } crossbeam-skiplist = "0" dashmap = "6" diff --git a/cSpell.json b/cSpell.json index 6a9da0324..e2ecd1bc3 100644 --- a/cSpell.json +++ b/cSpell.json @@ -30,6 +30,7 @@ "canonicalized", "certbot", "chrono", + "ciphertext", "clippy", "codecov", "codegen", @@ -52,6 +53,7 @@ "downloadedi", "dtolnay", "elif", + "endianness", "Eray", "filesd", "flamegraph", @@ -161,6 +163,7 @@ "Trackon", "typenum", "Unamed", + "underflows", "untuple", "uroot", "Vagaa", diff --git a/packages/clock/src/lib.rs b/packages/clock/src/lib.rs index 295d22c16..b7d20620c 100644 --- a/packages/clock/src/lib.rs +++ b/packages/clock/src/lib.rs @@ -26,7 +26,6 @@ pub mod clock; pub mod conv; pub mod static_time; -pub mod time_extent; #[macro_use] extern crate lazy_static; @@ -41,13 +40,3 @@ pub(crate) type CurrentClock = clock::Working; #[cfg(test)] #[allow(dead_code)] pub(crate) type CurrentClock = clock::Stopped; - -/// Working version, for production. -#[cfg(not(test))] -#[allow(dead_code)] -pub(crate) type DefaultTimeExtentMaker = time_extent::WorkingTimeExtentMaker; - -/// Stopped version, for testing. -#[cfg(test)] -#[allow(dead_code)] -pub(crate) type DefaultTimeExtentMaker = time_extent::StoppedTimeExtentMaker; diff --git a/packages/clock/src/time_extent/mod.rs b/packages/clock/src/time_extent/mod.rs deleted file mode 100644 index c51849f21..000000000 --- a/packages/clock/src/time_extent/mod.rs +++ /dev/null @@ -1,665 +0,0 @@ -//! It includes functionality to handle time extents. -//! -//! Time extents are used to represent a duration of time which contains -//! N times intervals of the same duration. -//! -//! Given a duration of: 60 seconds. -//! -//! ```text -//! |------------------------------------------------------------| -//! ``` -//! -//! If we define a **base** duration of `10` seconds, we would have `6` intervals. -//! -//! ```text -//! |----------|----------|----------|----------|----------|----------| -//! ^--- 10 seconds -//! ``` -//! -//! Then, You can represent half of the duration (`30` seconds) as: -//! -//! ```text -//! |----------|----------|----------|----------|----------|----------| -//! ^--- 30 seconds -//! ``` -//! -//! `3` times (**multiplier**) the **base** interval (3*10 = 30 seconds): -//! -//! ```text -//! |----------|----------|----------|----------|----------|----------| -//! ^--- 30 seconds (3 units of 10 seconds) -//! ``` -//! -//! Time extents are a way to measure time duration using only one unit of time -//! (**base** duration) repeated `N` times (**multiplier**). -//! -//! Time extents are not clocks in a sense that they do not have a start time. -//! They are not synchronized with the real time. In order to measure time, -//! you need to define a start time for the intervals. -//! -//! For example, we could measure time is "lustrums" (5 years) since the start -//! of the 21st century. The time extent would contains a base 5-year duration -//! and the multiplier. The current "lustrum" (2023) would be 5th one if we -//! start counting "lustrums" at 1. -//! -//! ```text -//! Lustrum 1: 2000-2004 -//! Lustrum 2: 2005-2009 -//! Lustrum 3: 2010-2014 -//! Lustrum 4: 2015-2019 -//! Lustrum 5: 2020-2024 -//! ``` -//! -//! More practically time extents are used to represent number of time intervals -//! since the Unix Epoch. Each interval is typically an amount of seconds. -//! It's specially useful to check expiring dates. For example, you can have an -//! authentication token that expires after 120 seconds. If you divide the -//! current timestamp by 120 you get the number of 2-minute intervals since the -//! Unix Epoch, you can hash that value with a secret key and send it to a -//! client. The client can authenticate by sending the hashed value back to the -//! server. The server can build the same hash and compare it with the one sent -//! by the client. The hash would be the same during the 2-minute interval, but -//! it would change after that. This method is one of the methods used by UDP -//! trackers to generate and verify a connection ID, which a a token sent to -//! the client to identify the connection. -use std::num::{IntErrorKind, TryFromIntError}; -use std::time::Duration; - -use crate::clock::{self, Stopped, Working}; - -/// This trait defines the operations that can be performed on a `TimeExtent`. -pub trait Extent: Sized + Default { - type Base; - type Multiplier; - type Product; - - /// It creates a new `TimeExtent`. - fn new(unit: &Self::Base, count: &Self::Multiplier) -> Self; - - /// It increases the `TimeExtent` by a multiplier. - /// - /// # Errors - /// - /// Will return `IntErrorKind` if `add` would overflow the internal `Duration`. - fn increase(&self, add: Self::Multiplier) -> Result; - - /// It decreases the `TimeExtent` by a multiplier. - /// - /// # Errors - /// - /// Will return `IntErrorKind` if `sub` would underflow the internal `Duration`. - fn decrease(&self, sub: Self::Multiplier) -> Result; - - /// It returns the total `Duration` of the `TimeExtent`. - fn total(&self) -> Option>; - - /// It returns the total `Duration` of the `TimeExtent` plus one increment. - fn total_next(&self) -> Option>; -} - -/// The `TimeExtent` base `Duration`, which is the duration of a single interval. -pub type Base = Duration; -/// The `TimeExtent` `Multiplier`, which is the number of `Base` duration intervals. -pub type Multiplier = u64; -/// The `TimeExtent` product, which is the total duration of the `TimeExtent`. -pub type Product = Base; - -/// A `TimeExtent` is a duration of time which contains N times intervals -/// of the same duration. -#[derive(Debug, Default, Hash, PartialEq, Eq)] -pub struct TimeExtent { - pub increment: Base, - pub amount: Multiplier, -} - -/// A zero time extent. It's the additive identity for a `TimeExtent`. -pub const ZERO: TimeExtent = TimeExtent { - increment: Base::ZERO, - amount: Multiplier::MIN, -}; - -/// The maximum value for a `TimeExtent`. -pub const MAX: TimeExtent = TimeExtent { - increment: Base::MAX, - amount: Multiplier::MAX, -}; - -impl TimeExtent { - #[must_use] - pub const fn from_sec(seconds: u64, amount: &Multiplier) -> Self { - Self { - increment: Base::from_secs(seconds), - amount: *amount, - } - } -} - -fn checked_duration_from_nanos(time: u128) -> Result { - const NANOS_PER_SEC: u32 = 1_000_000_000; - - let secs = time.div_euclid(u128::from(NANOS_PER_SEC)); - let nanos = time.rem_euclid(u128::from(NANOS_PER_SEC)); - - assert!(nanos < u128::from(NANOS_PER_SEC)); - - match u64::try_from(secs) { - Err(error) => Err(error), - Ok(secs) => Ok(Duration::new(secs, nanos.try_into().unwrap())), - } -} - -impl Extent for TimeExtent { - type Base = Base; - type Multiplier = Multiplier; - type Product = Product; - - fn new(increment: &Self::Base, amount: &Self::Multiplier) -> Self { - Self { - increment: *increment, - amount: *amount, - } - } - - fn increase(&self, add: Self::Multiplier) -> Result { - match self.amount.checked_add(add) { - None => Err(IntErrorKind::PosOverflow), - Some(amount) => Ok(Self { - increment: self.increment, - amount, - }), - } - } - - fn decrease(&self, sub: Self::Multiplier) -> Result { - match self.amount.checked_sub(sub) { - None => Err(IntErrorKind::NegOverflow), - Some(amount) => Ok(Self { - increment: self.increment, - amount, - }), - } - } - - fn total(&self) -> Option> { - self.increment - .as_nanos() - .checked_mul(u128::from(self.amount)) - .map(checked_duration_from_nanos) - } - - fn total_next(&self) -> Option> { - self.increment - .as_nanos() - .checked_mul(u128::from(self.amount) + 1) - .map(checked_duration_from_nanos) - } -} - -/// A `TimeExtent` maker. It's a clock base on time extents. -/// It gives you the time in time extents. -pub trait Make: Sized -where - Clock: clock::Time, -{ - /// It gives you the current time extent (with a certain increment) for - /// the current time. It gets the current timestamp front the `Clock`. - /// - /// For example: - /// - /// - If the base increment is `1` second, it will return a time extent - /// whose duration is `1 second` and whose multiplier is the the number - /// of seconds since the Unix Epoch (time extent). - /// - If the base increment is `1` minute, it will return a time extent - /// whose duration is `60 seconds` and whose multiplier is the number of - /// minutes since the Unix Epoch (time extent). - #[must_use] - fn now(increment: &Base) -> Option> { - Clock::now() - .as_nanos() - .checked_div((*increment).as_nanos()) - .map(|amount| match Multiplier::try_from(amount) { - Err(error) => Err(error), - Ok(amount) => Ok(TimeExtent::new(increment, &amount)), - }) - } - - /// Same as [`now`](crate::time_extent::Make::now), but it - /// will add an extra duration to the current time before calculating the - /// time extent. It gives you a time extent for a time in the future. - #[must_use] - fn now_after(increment: &Base, add_time: &Duration) -> Option> { - match Clock::now_add(add_time) { - None => None, - Some(time) => time - .as_nanos() - .checked_div(increment.as_nanos()) - .map(|amount| match Multiplier::try_from(amount) { - Err(error) => Err(error), - Ok(amount) => Ok(TimeExtent::new(increment, &amount)), - }), - } - } - - /// Same as [`now`](crate::time_extent::Make::now), but it - /// will subtract a duration to the current time before calculating the - /// time extent. It gives you a time extent for a time in the past. - #[must_use] - fn now_before(increment: &Base, sub_time: &Duration) -> Option> { - match Clock::now_sub(sub_time) { - None => None, - Some(time) => time - .as_nanos() - .checked_div(increment.as_nanos()) - .map(|amount| match Multiplier::try_from(amount) { - Err(error) => Err(error), - Ok(amount) => Ok(TimeExtent::new(increment, &amount)), - }), - } - } -} - -/// A `TimeExtent` maker which makes `TimeExtents`. -/// -/// It's a clock which measures time in `TimeExtents`. -#[derive(Debug)] -pub struct Maker { - clock: std::marker::PhantomData, -} - -/// A `TimeExtent` maker which makes `TimeExtents` from the `Working` clock. -pub type WorkingTimeExtentMaker = Maker; - -/// A `TimeExtent` maker which makes `TimeExtents` from the `Stopped` clock. -pub type StoppedTimeExtentMaker = Maker; - -impl Make for WorkingTimeExtentMaker {} -impl Make for StoppedTimeExtentMaker {} - -#[cfg(test)] -mod test { - use crate::time_extent::TimeExtent; - - const TIME_EXTENT_VAL: TimeExtent = TimeExtent::from_sec(2, &239_812_388_723); - - mod fn_checked_duration_from_nanos { - use std::time::Duration; - - use crate::time_extent::checked_duration_from_nanos; - use crate::time_extent::test::TIME_EXTENT_VAL; - - const NANOS_PER_SEC: u32 = 1_000_000_000; - - #[test] - fn it_should_give_zero_for_zero_input() { - assert_eq!(checked_duration_from_nanos(0).unwrap(), Duration::ZERO); - } - - #[test] - fn it_should_be_the_same_as_duration_implementation_for_u64_numbers() { - assert_eq!( - checked_duration_from_nanos(1_232_143_214_343_432).unwrap(), - Duration::from_nanos(1_232_143_214_343_432) - ); - assert_eq!( - checked_duration_from_nanos(u128::from(u64::MAX)).unwrap(), - Duration::from_nanos(u64::MAX) - ); - } - - #[test] - fn it_should_work_for_some_numbers_larger_than_u64() { - assert_eq!( - checked_duration_from_nanos(u128::from(TIME_EXTENT_VAL.amount) * u128::from(NANOS_PER_SEC)).unwrap(), - Duration::from_secs(TIME_EXTENT_VAL.amount) - ); - } - - #[test] - fn it_should_fail_for_numbers_that_are_too_large() { - assert_eq!( - checked_duration_from_nanos(u128::MAX).unwrap_err(), - u64::try_from(u128::MAX).unwrap_err() - ); - } - } - - mod time_extent { - - mod fn_default { - use crate::time_extent::{TimeExtent, ZERO}; - - #[test] - fn it_should_default_initialize_to_zero() { - assert_eq!(TimeExtent::default(), ZERO); - } - } - - mod fn_from_sec { - use crate::time_extent::test::TIME_EXTENT_VAL; - use crate::time_extent::{Multiplier, TimeExtent, ZERO}; - - #[test] - fn it_should_make_empty_for_zero() { - assert_eq!(TimeExtent::from_sec(u64::MIN, &Multiplier::MIN), ZERO); - } - #[test] - fn it_should_make_from_seconds() { - assert_eq!( - TimeExtent::from_sec(TIME_EXTENT_VAL.increment.as_secs(), &TIME_EXTENT_VAL.amount), - TIME_EXTENT_VAL - ); - } - } - - mod fn_new { - use crate::time_extent::test::TIME_EXTENT_VAL; - use crate::time_extent::{Base, Extent, Multiplier, TimeExtent, ZERO}; - - #[test] - fn it_should_make_empty_for_zero() { - assert_eq!(TimeExtent::new(&Base::ZERO, &Multiplier::MIN), ZERO); - } - - #[test] - fn it_should_make_new() { - assert_eq!( - TimeExtent::new(&Base::from_millis(2), &TIME_EXTENT_VAL.amount), - TimeExtent { - increment: Base::from_millis(2), - amount: TIME_EXTENT_VAL.amount - } - ); - } - } - - mod fn_increase { - use std::num::IntErrorKind; - - use crate::time_extent::test::TIME_EXTENT_VAL; - use crate::time_extent::{Extent, TimeExtent, ZERO}; - - #[test] - fn it_should_not_increase_for_zero() { - assert_eq!(ZERO.increase(0).unwrap(), ZERO); - } - - #[test] - fn it_should_increase() { - assert_eq!( - TIME_EXTENT_VAL.increase(50).unwrap(), - TimeExtent { - increment: TIME_EXTENT_VAL.increment, - amount: TIME_EXTENT_VAL.amount + 50, - } - ); - } - - #[test] - fn it_should_fail_when_attempting_to_increase_beyond_bounds() { - assert_eq!(TIME_EXTENT_VAL.increase(u64::MAX), Err(IntErrorKind::PosOverflow)); - } - } - - mod fn_decrease { - use std::num::IntErrorKind; - - use crate::time_extent::test::TIME_EXTENT_VAL; - use crate::time_extent::{Extent, TimeExtent, ZERO}; - - #[test] - fn it_should_not_decrease_for_zero() { - assert_eq!(ZERO.decrease(0).unwrap(), ZERO); - } - - #[test] - fn it_should_decrease() { - assert_eq!( - TIME_EXTENT_VAL.decrease(50).unwrap(), - TimeExtent { - increment: TIME_EXTENT_VAL.increment, - amount: TIME_EXTENT_VAL.amount - 50, - } - ); - } - - #[test] - fn it_should_fail_when_attempting_to_decrease_beyond_bounds() { - assert_eq!(TIME_EXTENT_VAL.decrease(u64::MAX), Err(IntErrorKind::NegOverflow)); - } - } - - mod fn_total { - use crate::time_extent::test::TIME_EXTENT_VAL; - use crate::time_extent::{Base, Extent, Product, TimeExtent, MAX, ZERO}; - - #[test] - fn it_should_be_zero_for_zero() { - assert_eq!(ZERO.total().unwrap().unwrap(), Product::ZERO); - } - - #[test] - fn it_should_give_a_total() { - assert_eq!( - TIME_EXTENT_VAL.total().unwrap().unwrap(), - Product::from_secs(TIME_EXTENT_VAL.increment.as_secs() * TIME_EXTENT_VAL.amount) - ); - - assert_eq!( - TimeExtent::new(&Base::from_millis(2), &(TIME_EXTENT_VAL.amount * 1000)) - .total() - .unwrap() - .unwrap(), - Product::from_secs(TIME_EXTENT_VAL.increment.as_secs() * TIME_EXTENT_VAL.amount) - ); - - assert_eq!( - TimeExtent::new(&Base::from_secs(1), &(u64::MAX)).total().unwrap().unwrap(), - Product::from_secs(u64::MAX) - ); - } - - #[test] - fn it_should_fail_when_too_large() { - assert_eq!(MAX.total(), None); - } - - #[test] - fn it_should_fail_when_product_is_too_large() { - let time_extent = TimeExtent { - increment: MAX.increment, - amount: 2, - }; - assert_eq!( - time_extent.total().unwrap().unwrap_err(), - u64::try_from(u128::MAX).unwrap_err() - ); - } - } - - mod fn_total_next { - use crate::time_extent::test::TIME_EXTENT_VAL; - use crate::time_extent::{Base, Extent, Product, TimeExtent, MAX, ZERO}; - - #[test] - fn it_should_be_zero_for_zero() { - assert_eq!(ZERO.total_next().unwrap().unwrap(), Product::ZERO); - } - - #[test] - fn it_should_give_a_total() { - assert_eq!( - TIME_EXTENT_VAL.total_next().unwrap().unwrap(), - Product::from_secs(TIME_EXTENT_VAL.increment.as_secs() * (TIME_EXTENT_VAL.amount + 1)) - ); - - assert_eq!( - TimeExtent::new(&Base::from_millis(2), &(TIME_EXTENT_VAL.amount * 1000)) - .total_next() - .unwrap() - .unwrap(), - Product::new( - TIME_EXTENT_VAL.increment.as_secs() * (TIME_EXTENT_VAL.amount), - Base::from_millis(2).as_nanos().try_into().unwrap() - ) - ); - - assert_eq!( - TimeExtent::new(&Base::from_secs(1), &(u64::MAX - 1)) - .total_next() - .unwrap() - .unwrap(), - Product::from_secs(u64::MAX) - ); - } - - #[test] - fn it_should_fail_when_too_large() { - assert_eq!(MAX.total_next(), None); - } - - #[test] - fn it_should_fail_when_product_is_too_large() { - let time_extent = TimeExtent { - increment: MAX.increment, - amount: 2, - }; - assert_eq!( - time_extent.total_next().unwrap().unwrap_err(), - u64::try_from(u128::MAX).unwrap_err() - ); - } - } - } - - mod make_time_extent { - - mod fn_now { - use torrust_tracker_primitives::DurationSinceUnixEpoch; - - use crate::clock::stopped::Stopped as _; - use crate::time_extent::test::TIME_EXTENT_VAL; - use crate::time_extent::{Base, Make, TimeExtent}; - use crate::{CurrentClock, DefaultTimeExtentMaker}; - - #[test] - fn it_should_give_a_time_extent() { - assert_eq!( - DefaultTimeExtentMaker::now(&TIME_EXTENT_VAL.increment).unwrap().unwrap(), - TimeExtent { - increment: TIME_EXTENT_VAL.increment, - amount: 0 - } - ); - - CurrentClock::local_set(&DurationSinceUnixEpoch::from_secs(TIME_EXTENT_VAL.amount * 2)); - - assert_eq!( - DefaultTimeExtentMaker::now(&TIME_EXTENT_VAL.increment).unwrap().unwrap(), - TIME_EXTENT_VAL - ); - } - - #[test] - fn it_should_fail_for_zero() { - assert_eq!(DefaultTimeExtentMaker::now(&Base::ZERO), None); - } - - #[test] - fn it_should_fail_if_amount_exceeds_bounds() { - CurrentClock::local_set(&DurationSinceUnixEpoch::MAX); - assert_eq!( - DefaultTimeExtentMaker::now(&Base::from_millis(1)).unwrap().unwrap_err(), - u64::try_from(u128::MAX).unwrap_err() - ); - } - } - - mod fn_now_after { - use std::time::Duration; - - use torrust_tracker_primitives::DurationSinceUnixEpoch; - - use crate::clock::stopped::Stopped as _; - use crate::time_extent::test::TIME_EXTENT_VAL; - use crate::time_extent::{Base, Make}; - use crate::{CurrentClock, DefaultTimeExtentMaker}; - - #[test] - fn it_should_give_a_time_extent() { - assert_eq!( - DefaultTimeExtentMaker::now_after( - &TIME_EXTENT_VAL.increment, - &Duration::from_secs(TIME_EXTENT_VAL.amount * 2) - ) - .unwrap() - .unwrap(), - TIME_EXTENT_VAL - ); - } - - #[test] - fn it_should_fail_for_zero() { - assert_eq!(DefaultTimeExtentMaker::now_after(&Base::ZERO, &Duration::ZERO), None); - - CurrentClock::local_set(&DurationSinceUnixEpoch::MAX); - assert_eq!(DefaultTimeExtentMaker::now_after(&Base::ZERO, &Duration::MAX), None); - } - - #[test] - fn it_should_fail_if_amount_exceeds_bounds() { - CurrentClock::local_set(&DurationSinceUnixEpoch::MAX); - assert_eq!( - DefaultTimeExtentMaker::now_after(&Base::from_millis(1), &Duration::ZERO) - .unwrap() - .unwrap_err(), - u64::try_from(u128::MAX).unwrap_err() - ); - } - } - mod fn_now_before { - use std::time::Duration; - - use torrust_tracker_primitives::DurationSinceUnixEpoch; - - use crate::clock::stopped::Stopped as _; - use crate::time_extent::{Base, Make, TimeExtent}; - use crate::{CurrentClock, DefaultTimeExtentMaker}; - - #[test] - fn it_should_give_a_time_extent() { - CurrentClock::local_set(&DurationSinceUnixEpoch::MAX); - - assert_eq!( - DefaultTimeExtentMaker::now_before( - &Base::from_secs(u64::from(u32::MAX)), - &Duration::from_secs(u64::from(u32::MAX)) - ) - .unwrap() - .unwrap(), - TimeExtent { - increment: Base::from_secs(u64::from(u32::MAX)), - amount: 4_294_967_296 - } - ); - } - - #[test] - fn it_should_fail_for_zero() { - assert_eq!(DefaultTimeExtentMaker::now_before(&Base::ZERO, &Duration::ZERO), None); - - assert_eq!(DefaultTimeExtentMaker::now_before(&Base::ZERO, &Duration::MAX), None); - } - - #[test] - fn it_should_fail_if_amount_exceeds_bounds() { - CurrentClock::local_set(&DurationSinceUnixEpoch::MAX); - assert_eq!( - DefaultTimeExtentMaker::now_before(&Base::from_millis(1), &Duration::ZERO) - .unwrap() - .unwrap_err(), - u64::try_from(u128::MAX).unwrap_err() - ); - } - } - } -} diff --git a/packages/configuration/src/v2_0_0/udp_tracker.rs b/packages/configuration/src/v2_0_0/udp_tracker.rs index b3d420d72..0eee87700 100644 --- a/packages/configuration/src/v2_0_0/udp_tracker.rs +++ b/packages/configuration/src/v2_0_0/udp_tracker.rs @@ -1,4 +1,5 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::time::Duration; use serde::{Deserialize, Serialize}; @@ -10,11 +11,17 @@ pub struct UdpTracker { /// system to choose a random port, use port `0`. #[serde(default = "UdpTracker::default_bind_address")] pub bind_address: SocketAddr, + + /// The lifetime of the server-generated connection cookie, that is passed + /// the client as the `ConnectionId`. + #[serde(default = "UdpTracker::default_cookie_lifetime")] + pub cookie_lifetime: Duration, } impl Default for UdpTracker { fn default() -> Self { Self { bind_address: Self::default_bind_address(), + cookie_lifetime: Self::default_cookie_lifetime(), } } } @@ -23,4 +30,8 @@ impl UdpTracker { fn default_bind_address() -> SocketAddr { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 6969) } + + fn default_cookie_lifetime() -> Duration { + Duration::from_secs(120) + } } diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index dbd8eef9e..acedbc672 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -1,6 +1,7 @@ //! Tracker configuration factories for testing. use std::env; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::time::Duration; use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, Threshold, UdpTracker}; @@ -47,6 +48,7 @@ pub fn ephemeral() -> Configuration { let udp_port = 0u16; config.udp_trackers = Some(vec![UdpTracker { bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), udp_port), + cookie_lifetime: Duration::from_secs(120), }]); // Ephemeral socket address for HTTP tracker diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 7c0cf45ac..e106f73cc 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -23,6 +23,7 @@ use crate::bootstrap; use crate::core::services::tracker_factory; use crate::core::Tracker; use crate::shared::crypto::ephemeral_instance_keys; +use crate::shared::crypto::keys::{self, Keeper as _}; /// It loads the configuration from the environment and builds the main domain [`Tracker`] struct. /// @@ -32,6 +33,9 @@ use crate::shared::crypto::ephemeral_instance_keys; #[must_use] #[instrument(skip())] pub fn setup() -> (Configuration, Arc) { + #[cfg(not(test))] + check_seed(); + let configuration = initialize_configuration(); if let Err(e) = configuration.validate() { @@ -45,6 +49,18 @@ pub fn setup() -> (Configuration, Arc) { (configuration, tracker) } +/// checks if the seed is the instance seed in production. +/// +/// # Panics +/// +/// It would panic if the seed is not the instance seed. +pub fn check_seed() { + let seed = keys::Current::get_seed(); + let instance = keys::Instance::get_seed(); + + assert_eq!(seed, instance, "maybe using zeroed see in production!?"); +} + /// It initializes the application with the given configuration. /// /// The configuration may be obtained from the environment (via config file or env vars). @@ -69,6 +85,12 @@ pub fn initialize_static() { // Initialize the Ephemeral Instance Random Seed lazy_static::initialize(&ephemeral_instance_keys::RANDOM_SEED); + + // Initialize the Ephemeral Instance Random Cipher + lazy_static::initialize(&ephemeral_instance_keys::RANDOM_CIPHER_BLOWFISH); + + // Initialize the Zeroed Cipher + lazy_static::initialize(&ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH); } /// It builds the domain tracker diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index ca503aa29..6aab06d4f 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -32,9 +32,10 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; #[instrument(skip(config, tracker, form))] pub async fn start_job(config: &UdpTracker, tracker: Arc, form: ServiceRegistrationForm) -> JoinHandle<()> { let bind_to = config.bind_address; + let cookie_lifetime = config.cookie_lifetime; let server = Server::new(Spawner::new(bind_to)) - .start(tracker, form) + .start(tracker, form, cookie_lifetime) .await .expect("it should be able to start the udp tracker"); diff --git a/src/lib.rs b/src/lib.rs index 5d7c92ae2..d7e4bc5b2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -488,7 +488,7 @@ //! In addition to the production code documentation you can find a lot of //! examples on the integration and unit tests. -use torrust_tracker_clock::{clock, time_extent}; +use torrust_tracker_clock::clock; pub mod app; pub mod bootstrap; @@ -510,13 +510,3 @@ pub(crate) type CurrentClock = clock::Working; #[cfg(test)] #[allow(dead_code)] pub(crate) type CurrentClock = clock::Stopped; - -/// Working version, for production. -#[cfg(not(test))] -#[allow(dead_code)] -pub(crate) type DefaultTimeExtentMaker = time_extent::WorkingTimeExtentMaker; - -/// Stopped version, for testing. -#[cfg(test)] -#[allow(dead_code)] -pub(crate) type DefaultTimeExtentMaker = time_extent::StoppedTimeExtentMaker; diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs index 36bf98304..31c6396e8 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/servers/udp/connection_cookie.rs @@ -1,339 +1,305 @@ -//! Logic for generating and verifying connection IDs. +//! Module for Generating and Verifying Connection IDs (Cookies) in the UDP Tracker Protocol //! -//! The UDP tracker requires the client to connect to the server before it can -//! send any data. The server responds with a random 64-bit integer that the -//! client must use to identify itself. +//! **Overview:** //! -//! This connection ID is used to avoid spoofing attacks. The client must send -//! the connection ID in all requests to the server. The server will ignore any -//! requests that do not contain the correct connection ID. +//! In the `BitTorrent` UDP tracker protocol, clients initiate communication by obtaining a connection ID from the server. This connection ID serves as a safeguard against IP spoofing and replay attacks, ensuring that only legitimate clients can interact with the tracker. //! -//! The simplest way to implement this would be to generate a random number when -//! the client connects and store it in a hash table. However, this would -//! require the server to store a large number of connection IDs, which would be -//! a waste of memory. Instead, the server generates a connection ID based on -//! the client's IP address and the current time. This allows the server to -//! verify the connection ID without storing it. +//! To maintain a stateless server architecture, this module implements a method for generating and verifying connection IDs based on the client's fingerprint (typically derived from the client's IP address) and the time of issuance, without storing state on the server. //! -//! This module implements this method of generating connection IDs. It's the -//! most common way to generate connection IDs. The connection ID is generated -//! using a time based algorithm and it is valid for a certain amount of time -//! (usually two minutes). The connection ID is generated using the following: +//! The connection ID is an encrypted, opaque cookie held by the client. Since the same server that generates the cookie also validates it, endianness is not a concern. //! -//! ```text -//! connection ID = hash(client IP + current time slot + secret seed) -//! ``` +//! **Connection ID Generation Algorithm:** //! -//! Time slots are two minute intervals since the Unix epoch. The secret seed is -//! a random number that is generated when the server starts. And the client IP -//! is used in order generate a unique connection ID for each client. +//! 1. **Issue Time (`issue_at`):** +//! - Obtain a 64-bit floating-point number (`f64`), this number should be a normal number. //! -//! The BEP-15 recommends a two-minute time slot. +//! 2. **Fingerprint:** +//! - Use an 8-byte fingerprint unique to the client (e.g., derived from the client's IP address). //! -//! ```text -//! Timestamp (seconds from Unix epoch): -//! |------------|------------|------------|------------| -//! 0 120 240 360 480 -//! Time slots (two-minutes time extents from Unix epoch): -//! |------------|------------|------------|------------| -//! 0 1 2 3 4 -//! Peer connections: -//! Peer A |-------------------------| -//! Peer B |-------------------------| -//! Peer C |------------------| -//! Peer A connects at timestamp 120 slot 1 -> connection ID will be valid from timestamp 120 to 360 -//! Peer B connects at timestamp 240 slot 2 -> connection ID will be valid from timestamp 240 to 480 -//! Peer C connects at timestamp 180 slot 1 -> connection ID will be valid from timestamp 180 to 360 -//! ``` -//! > **NOTICE**: connection ID is always the same for a given peer -//! > (socket address) and time slot. +//! 3. **Assemble Cookie Value:** +//! - Interpret the bytes of `issue_at` as a 64-bit integer (`i64`) without altering the bit pattern. +//! - Similarly, interpret the fingerprint bytes as an `i64`. +//! - Compute the cookie value: +//! ```rust,ignore +//! let cookie_value = issue_at_i64.wrapping_add(fingerprint_i64); +//! ``` +//! - *Note:* Wrapping addition handles potential integer overflows gracefully. //! -//! > **NOTICE**: connection ID will be valid for two time extents, **not two -//! > minutes**. It'll be valid for the the current time extent and the next one. +//! 4. **Encrypt Cookie Value:** +//! - Encrypt `cookie_value` using a symmetric block cipher obtained from `Current::get_cipher()`. +//! - The encrypted `cookie_value` becomes the connection ID sent to the client. //! -//! Refer to [`Connect`](crate::servers::udp#connect) for more information about -//! the connection process. +//! **Connection ID Verification Algorithm:** //! -//! ## Advantages +//! When a client sends a request with a connection ID, the server verifies it using the following steps: //! -//! - It consumes less memory than storing a hash table of connection IDs. -//! - It's easy to implement. -//! - It's fast. +//! 1. **Decrypt Connection ID:** +//! - Decrypt the received connection ID using the same cipher to retrieve `cookie_value`. +//! - *Important:* The decryption is non-authenticated, meaning it does not verify the integrity or authenticity of the ciphertext. The decrypted `cookie_value` can be any byte sequence, including manipulated data. //! -//! ## Disadvantages +//! 2. **Recover Issue Time:** +//! - Interpret the fingerprint bytes as `i64`. +//! - Compute the issue time: +//! ```rust,ignore +//! let issue_at_i64 = cookie_value.wrapping_sub(fingerprint_i64); +//! ``` +//! - *Note:* Wrapping subtraction handles potential integer underflows gracefully. +//! - Reinterpret `issue_at_i64` bytes as an `f64` to get `issue_time`. +//! +//! 3. **Validate Issue Time:** +//! - **Handling Arbitrary `issue_time` Values:** +//! - Since the decrypted `cookie_value` may be arbitrary, `issue_time` can be any `f64` value, including special values like `NaN`, positive or negative infinity, and subnormal numbers. +//! - **Validation Steps:** +//! - **Step 1:** Check if `issue_time` is finite using `issue_time.is_finite()`. +//! - If `issue_time` is `NaN` or infinite, it is considered invalid. +//! - **Step 2:** If `issue_time` is finite, perform range checks: +//! - Verify that `min <= issue_time <= max`. +//! - If `issue_time` passes these checks, accept the connection ID; otherwise, reject it with an appropriate error. +//! +//! **Security Considerations:** +//! +//! - **Non-Authenticated Encryption:** +//! - Due to protocol constraints (an 8-byte connection ID), using an authenticated encryption algorithm is not feasible. +//! - As a result, attackers might attempt to forge or manipulate connection IDs. +//! - However, the probability of an arbitrary 64-bit value decrypting to a valid `issue_time` within the acceptable range is extremely low, effectively serving as a form of authentication. +//! +//! - **Handling Special `f64` Values:** +//! - By checking `issue_time.is_finite()`, the implementation excludes `NaN` and infinite values, ensuring that only valid, finite timestamps are considered. +//! +//! - **Probability of Successful Attack:** +//! - Given the narrow valid time window (usually around 2 minutes) compared to the vast range of `f64` values, the chance of successfully guessing a valid `issue_time` is negligible. +//! +//! **Key Points:** +//! +//! - The server maintains a stateless design, reducing resource consumption and complexity. +//! - Wrapping arithmetic ensures that the addition and subtraction of `i64` values are safe from overflow or underflow issues. +//! - The validation process is robust against malformed or malicious connection IDs due to stringent checks on the deserialized `issue_time`. +//! - The module leverages existing cryptographic primitives while acknowledging and addressing the limitations imposed by the protocol's specifications. //! -//! - It's not very flexible. The connection ID is only valid for a certain amount of time. -//! - It's not very accurate. The connection ID is valid for more than two minutes. -use std::net::SocketAddr; -use std::panic::Location; - -use aquatic_udp_protocol::ConnectionId; -use torrust_tracker_clock::time_extent::{Extent, TimeExtent}; -use zerocopy::network_endian::I64; -use zerocopy::AsBytes; - -use super::error::Error; - -pub type Cookie = [u8; 8]; - -pub type SinceUnixEpochTimeExtent = TimeExtent; - -pub const COOKIE_LIFETIME: TimeExtent = TimeExtent::from_sec(2, &60); -/// Converts a connection ID into a connection cookie. -#[must_use] -pub fn from_connection_id(connection_id: &ConnectionId) -> Cookie { - let mut cookie = [0u8; 8]; - connection_id.write_to(&mut cookie); - cookie -} +use aquatic_udp_protocol::ConnectionId as Cookie; +use cookie_builder::{assemble, decode, disassemble, encode}; +use zerocopy::AsBytes; -/// Converts a connection cookie into a connection ID. -#[must_use] -pub fn into_connection_id(connection_cookie: &Cookie) -> ConnectionId { - ConnectionId(I64::new(i64::from_be_bytes(*connection_cookie))) -} +use super::error::{self, Error}; +use crate::shared::crypto::keys::CipherArrayBlowfish; /// Generates a new connection cookie. -#[must_use] -pub fn make(remote_address: &SocketAddr) -> Cookie { - let time_extent = cookie_builder::get_last_time_extent(); +/// +/// # Errors +/// +/// It would error if the supplied `issue_at` value is a zero, infinite, subnormal, or NaN. +/// +/// # Panics +/// +/// It would panic if the cookie is not exactly 8 bytes is size. +/// +pub fn make(fingerprint: u64, issue_at: f64) -> Result { + if !issue_at.is_normal() { + return Err(Error::InvalidCookieIssueTime { invalid_value: issue_at }); + } - //println!("remote_address: {remote_address:?}, time_extent: {time_extent:?}, cookie: {cookie:?}"); - cookie_builder::build(remote_address, &time_extent) + let cookie = assemble(fingerprint, issue_at); + let cookie = encode(cookie); + + // using `read_from` as the array may be not correctly aligned + Ok(zerocopy::FromBytes::read_from(cookie.as_slice()).expect("it should be the same size")) } /// Checks if the supplied `connection_cookie` is valid. /// -/// # Panics +/// # Errors /// -/// It would panic if the `COOKIE_LIFETIME` constant would be an unreasonably large number. +/// It would error if the connection cookie is somehow invalid or expired. /// -/// # Errors +/// # Panics /// -/// Will return a `ServerError::InvalidConnectionId` if the supplied `connection_cookie` fails to verify. -pub fn check(remote_address: &SocketAddr, connection_cookie: &Cookie) -> Result { - // we loop backwards testing each time_extent until we find one that matches. - // (or the lifetime of time_extents is exhausted) - for offset in 0..=COOKIE_LIFETIME.amount { - let checking_time_extent = cookie_builder::get_last_time_extent().decrease(offset).unwrap(); - - let checking_cookie = cookie_builder::build(remote_address, &checking_time_extent); - //println!("remote_address: {remote_address:?}, time_extent: {checking_time_extent:?}, cookie: {checking_cookie:?}"); - - if *connection_cookie == checking_cookie { - return Ok(checking_time_extent); - } - } - Err(Error::InvalidConnectionId { - location: Location::caller(), - }) -} +/// It would panic if cookie min value is larger than the max value. +pub fn check(cookie: &Cookie, fingerprint: u64, min: f64, max: f64) -> Result { + assert!(min < max, "min is larger than max"); -mod cookie_builder { - use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; - use std::net::SocketAddr; - - use torrust_tracker_clock::time_extent::{Extent, Make, TimeExtent}; - - use super::{Cookie, SinceUnixEpochTimeExtent, COOKIE_LIFETIME}; - use crate::shared::crypto::keys::seeds::{Current, Keeper}; - use crate::DefaultTimeExtentMaker; - - pub(super) fn get_last_time_extent() -> SinceUnixEpochTimeExtent { - DefaultTimeExtentMaker::now(&COOKIE_LIFETIME.increment) - .unwrap() - .unwrap() - .increase(COOKIE_LIFETIME.amount) - .unwrap() - } + let cookie_bytes = CipherArrayBlowfish::from_slice(cookie.0.as_bytes()); + let cookie_bytes = decode(*cookie_bytes); - pub(super) fn build(remote_address: &SocketAddr, time_extent: &TimeExtent) -> Cookie { - let seed = Current::get_seed(); + let issue_time = disassemble(fingerprint, cookie_bytes); - let mut hasher = DefaultHasher::new(); - - remote_address.hash(&mut hasher); - time_extent.hash(&mut hasher); - seed.hash(&mut hasher); + if !issue_time.is_normal() { + return Err(Error::InvalidConnectionId { + bad_id: error::ConnectionCookie(*cookie), + }); + } - hasher.finish().to_le_bytes() + if issue_time < min { + return Err(Error::ConnectionIdExpired { + bad_age: issue_time, + min_age: min, + }); } -} -#[cfg(test)] -mod tests { - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + if issue_time > max { + return Err(Error::ConnectionIdFromFuture { + future_age: issue_time, + max_age: max, + }); + } - use torrust_tracker_clock::clock::stopped::Stopped as _; - use torrust_tracker_clock::clock::{self}; - use torrust_tracker_clock::time_extent::{self, Extent}; + Ok(issue_time) +} - use super::cookie_builder::{self}; - use crate::servers::udp::connection_cookie::{check, make, Cookie, COOKIE_LIFETIME}; +mod cookie_builder { + use cipher::{BlockDecrypt, BlockEncrypt}; + use tracing::{instrument, Level}; + use zerocopy::{byteorder, AsBytes as _, NativeEndian}; - // #![feature(const_socketaddr)] - // const REMOTE_ADDRESS_IPV4_ZERO: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); + pub type CookiePlainText = CipherArrayBlowfish; + pub type CookieCipherText = CipherArrayBlowfish; - #[test] - fn it_should_make_a_connection_cookie() { - // Note: This constant may need to be updated in the future as the hash - // is not guaranteed to to be stable between versions. - const ID_COOKIE_OLD_HASHER: Cookie = [41, 166, 45, 246, 249, 24, 108, 203]; - const ID_COOKIE_NEW_HASHER: Cookie = [185, 122, 191, 238, 6, 43, 2, 198]; + use crate::shared::crypto::keys::{CipherArrayBlowfish, Current, Keeper}; - clock::Stopped::local_set_to_unix_epoch(); + #[instrument(ret(level = Level::TRACE))] + pub(super) fn assemble(fingerprint: u64, issue_at: f64) -> CookiePlainText { + let issue_at: byteorder::I64 = + *zerocopy::FromBytes::ref_from(&issue_at.to_ne_bytes()).expect("it should be aligned"); + let fingerprint: byteorder::I64 = + *zerocopy::FromBytes::ref_from(&fingerprint.to_ne_bytes()).expect("it should be aligned"); - let cookie = make(&SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0)); + let cookie = issue_at.get().wrapping_add(fingerprint.get()); + let cookie: byteorder::I64 = + *zerocopy::FromBytes::ref_from(&cookie.to_ne_bytes()).expect("it should be aligned"); - assert!(cookie == ID_COOKIE_OLD_HASHER || cookie == ID_COOKIE_NEW_HASHER); + *CipherArrayBlowfish::from_slice(cookie.as_bytes()) } - #[test] - fn it_should_make_the_same_connection_cookie_for_the_same_input_data() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - let time_extent_zero = time_extent::ZERO; + #[instrument(ret(level = Level::TRACE))] + pub(super) fn disassemble(fingerprint: u64, cookie: CookiePlainText) -> f64 { + let fingerprint: byteorder::I64 = + *zerocopy::FromBytes::ref_from(&fingerprint.to_ne_bytes()).expect("it should be aligned"); - let cookie = cookie_builder::build(&remote_address, &time_extent_zero); - let cookie_2 = cookie_builder::build(&remote_address, &time_extent_zero); + // the array may be not aligned, so we read instead of reference. + let cookie: byteorder::I64 = + zerocopy::FromBytes::read_from(cookie.as_bytes()).expect("it should be the same size"); - println!("remote_address: {remote_address:?}, time_extent: {time_extent_zero:?}, cookie: {cookie:?}"); - println!("remote_address: {remote_address:?}, time_extent: {time_extent_zero:?}, cookie: {cookie_2:?}"); + let issue_time_bytes = cookie.get().wrapping_sub(fingerprint.get()).to_ne_bytes(); - //remote_address: 127.0.0.1:8080, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [212, 9, 204, 223, 176, 190, 150, 153] - //remote_address: 127.0.0.1:8080, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [212, 9, 204, 223, 176, 190, 150, 153] + let issue_time: byteorder::F64 = + *zerocopy::FromBytes::ref_from(&issue_time_bytes).expect("it should be aligned"); - assert_eq!(cookie, cookie_2); + issue_time.get() } - #[test] - fn it_should_make_the_different_connection_cookie_for_different_ip() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - let remote_address_2 = SocketAddr::new(IpAddr::V4(Ipv4Addr::BROADCAST), 0); - let time_extent_zero = time_extent::ZERO; - - let cookie = cookie_builder::build(&remote_address, &time_extent_zero); - let cookie_2 = cookie_builder::build(&remote_address_2, &time_extent_zero); - - println!("remote_address: {remote_address:?}, time_extent: {time_extent_zero:?}, cookie: {cookie:?}"); - println!("remote_address: {remote_address_2:?}, time_extent: {time_extent_zero:?}, cookie: {cookie_2:?}"); + #[instrument(ret(level = Level::TRACE))] + pub(super) fn encode(mut cookie: CookiePlainText) -> CookieCipherText { + let cipher = Current::get_cipher_blowfish(); - //remote_address: 0.0.0.0:0, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [151, 130, 30, 157, 190, 41, 179, 135] - //remote_address: 255.255.255.255:0, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [217, 87, 239, 178, 182, 126, 66, 166] + cipher.encrypt_block(&mut cookie); - assert_ne!(cookie, cookie_2); + cookie } - #[test] - fn it_should_make_the_different_connection_cookie_for_different_ip_version() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - let remote_address_2 = SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0); - let time_extent_zero = time_extent::ZERO; - - let cookie = cookie_builder::build(&remote_address, &time_extent_zero); - let cookie_2 = cookie_builder::build(&remote_address_2, &time_extent_zero); + #[instrument(ret(level = Level::TRACE))] + pub(super) fn decode(mut cookie: CookieCipherText) -> CookiePlainText { + let cipher = Current::get_cipher_blowfish(); - println!("remote_address: {remote_address:?}, time_extent: {time_extent_zero:?}, cookie: {cookie:?}"); - println!("remote_address: {remote_address_2:?}, time_extent: {time_extent_zero:?}, cookie: {cookie_2:?}"); + cipher.decrypt_block(&mut cookie); - //remote_address: 0.0.0.0:0, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [151, 130, 30, 157, 190, 41, 179, 135] - //remote_address: [::]:0, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [99, 119, 230, 177, 20, 220, 163, 187] - - assert_ne!(cookie, cookie_2); + cookie } +} - #[test] - fn it_should_make_the_different_connection_cookie_for_different_socket() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - let remote_address_2 = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 1); - let time_extent_zero = time_extent::ZERO; - - let cookie = cookie_builder::build(&remote_address, &time_extent_zero); - let cookie_2 = cookie_builder::build(&remote_address_2, &time_extent_zero); +#[cfg(test)] +mod tests { - println!("remote_address: {remote_address:?}, time_extent: {time_extent_zero:?}, cookie: {cookie:?}"); - println!("remote_address: {remote_address_2:?}, time_extent: {time_extent_zero:?}, cookie: {cookie_2:?}"); + use super::*; - //remote_address: 0.0.0.0:0, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [151, 130, 30, 157, 190, 41, 179, 135] - //remote_address: 0.0.0.0:1, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [38, 8, 0, 102, 92, 170, 220, 11] + #[test] + fn it_should_make_a_connection_cookie() { + let fingerprint = 1_000_000; + let issue_at = 1000.0; + let cookie = make(fingerprint, issue_at).unwrap().0.get(); - assert_ne!(cookie, cookie_2); + // Expected connection ID derived through experimentation + assert_eq!(cookie.to_le_bytes(), [10, 130, 175, 211, 244, 253, 230, 210]); } #[test] - fn it_should_make_the_different_connection_cookie_for_different_time_extents() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - let time_extent_zero = time_extent::ZERO; - let time_extent_max = time_extent::MAX; - - let cookie = cookie_builder::build(&remote_address, &time_extent_zero); - let cookie_2 = cookie_builder::build(&remote_address, &time_extent_max); + fn it_should_create_same_cookie_for_same_input() { + let fingerprint = 1_000_000; + let issue_at = 1000.0; + let cookie1 = make(fingerprint, issue_at).unwrap(); + let cookie2 = make(fingerprint, issue_at).unwrap(); - println!("remote_address: {remote_address:?}, time_extent: {time_extent_zero:?}, cookie: {cookie:?}"); - println!("remote_address: {remote_address:?}, time_extent: {time_extent_max:?}, cookie: {cookie_2:?}"); - - //remote_address: 0.0.0.0:0, time_extent: TimeExtent { increment: 0ns, amount: 0 }, cookie: [151, 130, 30, 157, 190, 41, 179, 135] - //remote_address: 0.0.0.0:0, time_extent: TimeExtent { increment: 18446744073709551615.999999999s, amount: 18446744073709551615 }, cookie: [87, 111, 109, 125, 182, 206, 3, 201] - - assert_ne!(cookie, cookie_2); + assert_eq!(cookie1, cookie2); } #[test] - fn it_should_make_different_cookies_for_the_next_time_extent() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - - let cookie = make(&remote_address); - - clock::Stopped::local_add(&COOKIE_LIFETIME.increment).unwrap(); - - let cookie_next = make(&remote_address); - - assert_ne!(cookie, cookie_next); + fn it_should_create_different_cookies_for_different_fingerprints() { + let fingerprint1 = 1_000_000; + let fingerprint2 = 2_000_000; + let issue_at = 1000.0; + let cookie1 = make(fingerprint1, issue_at).unwrap(); + let cookie2 = make(fingerprint2, issue_at).unwrap(); + + assert_ne!(cookie1, cookie2); } #[test] - fn it_should_be_valid_for_this_time_extent() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); - - let cookie = make(&remote_address); - - check(&remote_address, &cookie).unwrap(); + fn it_should_create_different_cookies_for_different_issue_times() { + let fingerprint = 1_000_000; + let issue_at1 = 1000.0; + let issue_at2 = 2000.0; + let cookie1 = make(fingerprint, issue_at1).unwrap(); + let cookie2 = make(fingerprint, issue_at2).unwrap(); + + assert_ne!(cookie1, cookie2); } #[test] - fn it_should_be_valid_for_the_next_time_extent() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); + fn it_should_validate_a_valid_cookie() { + let fingerprint = 1_000_000; + let issue_at = 1_000_000_000_f64; + let cookie = make(fingerprint, issue_at).unwrap(); - let cookie = make(&remote_address); + let min = issue_at - 10.0; + let max = issue_at + 10.0; - clock::Stopped::local_add(&COOKIE_LIFETIME.increment).unwrap(); + let result = check(&cookie, fingerprint, min, max).unwrap(); - check(&remote_address, &cookie).unwrap(); + // we should have exactly the same bytes returned + assert_eq!(result.to_ne_bytes(), issue_at.to_ne_bytes()); } #[test] - fn it_should_be_valid_for_the_last_time_extent() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); + fn it_should_reject_an_expired_cookie() { + let fingerprint = 1_000_000; + let issue_at = 1_000_000_000_f64; + let cookie = make(fingerprint, issue_at).unwrap(); - clock::Stopped::local_set_to_unix_epoch(); + let min = issue_at + 10.0; + let max = issue_at + 20.0; - let cookie = make(&remote_address); + let result = check(&cookie, fingerprint, min, max).unwrap_err(); - clock::Stopped::local_set(&COOKIE_LIFETIME.total().unwrap().unwrap()); - - check(&remote_address, &cookie).unwrap(); + match result { + Error::ConnectionIdExpired { .. } => {} // Expected error + _ => panic!("Expected ConnectionIdExpired error"), + } } #[test] - #[should_panic = "InvalidConnectionId"] - fn it_should_be_not_valid_after_their_last_time_extent() { - let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); + fn it_should_reject_a_cookie_from_the_future() { + let fingerprint = 1_000_000; + let issue_at = 1_000_000_000_f64; - let cookie = make(&remote_address); + let cookie = make(fingerprint, issue_at).unwrap(); - clock::Stopped::local_set(&COOKIE_LIFETIME.total_next().unwrap().unwrap()); + let min = issue_at - 20.0; + let max = issue_at - 10.0; - check(&remote_address, &cookie).unwrap(); + let result = check(&cookie, fingerprint, min, max).unwrap_err(); + + match result { + Error::ConnectionIdFromFuture { .. } => {} // Expected error + _ => panic!("Expected ConnectionIdFromFuture error"), + } } } diff --git a/src/servers/udp/error.rs b/src/servers/udp/error.rs index 315c9d1cf..8f30b0138 100644 --- a/src/servers/udp/error.rs +++ b/src/servers/udp/error.rs @@ -1,12 +1,30 @@ //! Error types for the UDP server. use std::panic::Location; +use aquatic_udp_protocol::ConnectionId; +use derive_more::derive::Display; use thiserror::Error; use torrust_tracker_located_error::LocatedError; +#[derive(Display, Debug)] +#[display(":?")] +pub struct ConnectionCookie(pub ConnectionId); + /// Error returned by the UDP server. #[derive(Error, Debug)] pub enum Error { + #[error("the issue time should be a normal floating point number")] + InvalidCookieIssueTime { invalid_value: f64 }, + + #[error("connection id was decoded, but could not be understood")] + InvalidConnectionId { bad_id: ConnectionCookie }, + + #[error("connection id was decoded, but was expired (too old)")] + ConnectionIdExpired { bad_age: f64, min_age: f64 }, + + #[error("connection id was decoded, but was invalid (from future)")] + ConnectionIdFromFuture { future_age: f64, max_age: f64 }, + /// Error returned when the domain tracker returns an error. #[error("tracker server error: {source}")] TrackerError { @@ -20,10 +38,6 @@ pub enum Error { message: String, }, - /// Error returned when the connection id could not be verified. - #[error("connection id could not be verified")] - InvalidConnectionId { location: &'static Location<'static> }, - /// Error returned when the request is invalid. #[error("bad request: {source}")] BadRequest { diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 6af634c32..ba75ac3c6 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -1,5 +1,6 @@ //! Handlers for the UDP server. use std::fmt; +use std::hash::{DefaultHasher, Hash, Hasher as _}; use std::net::{IpAddr, SocketAddr}; use std::panic::Location; use std::sync::Arc; @@ -16,7 +17,7 @@ use tracing::{instrument, Level}; use uuid::Uuid; use zerocopy::network_endian::I32; -use super::connection_cookie::{check, from_connection_id, into_connection_id, make}; +use super::connection_cookie::{check, make}; use super::RawRequest; use crate::core::{statistics, PeersWanted, ScrapeData, Tracker}; use crate::servers::udp::error::Error; @@ -33,7 +34,14 @@ use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; /// /// It will return an `Error` response if the request is invalid. #[instrument(skip(udp_request, tracker, local_addr), ret(level = Level::TRACE))] -pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Tracker, local_addr: SocketAddr) -> Response { +pub(crate) async fn handle_packet( + udp_request: RawRequest, + tracker: &Tracker, + local_addr: SocketAddr, + cookie_issue_time: f64, + cookie_expiry_time: f64, + cookie_tolerance_max_time: f64, +) -> Response { tracing::debug!("Handling Packets: {udp_request:?}"); let start_time = Instant::now(); @@ -55,7 +63,16 @@ pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Tracker, lo Request::Scrape(scrape_request) => scrape_request.transaction_id, }; - let response = match handle_request(request, udp_request.from, tracker).await { + let response = match handle_request( + request, + udp_request.from, + tracker, + cookie_issue_time, + cookie_expiry_time, + cookie_tolerance_max_time, + ) + .await + { Ok(response) => response, Err(e) => handle_error(&e, transaction_id), }; @@ -89,12 +106,28 @@ pub(crate) async fn handle_packet(udp_request: RawRequest, tracker: &Tracker, lo /// /// If a error happens in the `handle_request` function, it will just return the `ServerError`. #[instrument(skip(request, remote_addr, tracker))] -pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: &Tracker) -> Result { +pub async fn handle_request( + request: Request, + remote_addr: SocketAddr, + tracker: &Tracker, + cookie_issue_time: f64, + cookie_expiry_time: f64, + cookie_tolerance_max_time: f64, +) -> Result { tracing::trace!("handle request"); match request { - Request::Connect(connect_request) => handle_connect(remote_addr, &connect_request, tracker).await, - Request::Announce(announce_request) => handle_announce(remote_addr, &announce_request, tracker).await, + Request::Connect(connect_request) => handle_connect(remote_addr, &connect_request, tracker, cookie_issue_time).await, + Request::Announce(announce_request) => { + handle_announce( + remote_addr, + &announce_request, + tracker, + cookie_expiry_time, + cookie_tolerance_max_time, + ) + .await + } Request::Scrape(scrape_request) => handle_scrape(remote_addr, &scrape_request, tracker).await, } } @@ -106,11 +139,22 @@ pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: /// /// This function does not ever return an error. #[instrument(skip(tracker), err, ret(level = Level::TRACE))] -pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, tracker: &Tracker) -> Result { +pub async fn handle_connect( + remote_addr: SocketAddr, + request: &ConnectRequest, + tracker: &Tracker, + cookie_issue_time: f64, +) -> Result { tracing::trace!("handle connect"); - let connection_cookie = make(&remote_addr); - let connection_id = into_connection_id(&connection_cookie); + let connection_id = make( + { + let mut state = DefaultHasher::new(); + remote_addr.hash(&mut state); + state.finish() + }, + cookie_issue_time, + )?; let response = ConnectResponse { transaction_id: request.transaction_id, @@ -141,6 +185,8 @@ pub async fn handle_announce( remote_addr: SocketAddr, announce_request: &AnnounceRequest, tracker: &Tracker, + cookie_expiry_time: f64, + cookie_tolerance_max_time: f64, ) -> Result { tracing::trace!("handle announce"); @@ -151,7 +197,16 @@ pub async fn handle_announce( }); } - check(&remote_addr, &from_connection_id(&announce_request.connection_id))?; + check( + &announce_request.connection_id, + { + let mut state = DefaultHasher::new(); + remote_addr.hash(&mut state); + state.finish() + }, + cookie_expiry_time, + cookie_tolerance_max_time, + )?; let info_hash = announce_request.info_hash.into(); let remote_client_ip = remote_addr.ip(); @@ -313,6 +368,7 @@ impl fmt::Display for RequestId { #[cfg(test)] mod tests { + use std::hash::{DefaultHasher, Hash as _, Hasher as _}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; @@ -350,14 +406,28 @@ mod tests { tracker_factory(configuration).into() } + fn make_remote_addr_fingerprint(remote_addr: &SocketAddr) -> u64 { + let mut state = DefaultHasher::new(); + remote_addr.hash(&mut state); + state.finish() + } + fn sample_ipv4_remote_addr() -> SocketAddr { sample_ipv4_socket_address() } + fn sample_ipv4_remote_addr_fingerprint() -> u64 { + make_remote_addr_fingerprint(&sample_ipv4_socket_address()) + } + fn sample_ipv6_remote_addr() -> SocketAddr { sample_ipv6_socket_address() } + fn sample_ipv6_remote_addr_fingerprint() -> u64 { + make_remote_addr_fingerprint(&sample_ipv6_socket_address()) + } + fn sample_ipv4_socket_address() -> SocketAddr { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) } @@ -366,6 +436,18 @@ mod tests { SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) } + fn sample_issue_time() -> f64 { + 1_000_000_000_f64 + } + + fn sample_expiry_time() -> f64 { + sample_issue_time() - 10.0 + } + + fn tolerance_max_time() -> f64 { + sample_issue_time() + 10.0 + } + #[derive(Debug, Default)] pub struct TorrentPeerBuilder { peer: peer::Peer, @@ -438,9 +520,12 @@ mod tests { use super::{sample_ipv4_socket_address, sample_ipv6_remote_addr, tracker_configuration}; use crate::core::{self, statistics}; - use crate::servers::udp::connection_cookie::{into_connection_id, make}; + use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_connect; - use crate::servers::udp::handlers::tests::{public_tracker, sample_ipv4_remote_addr}; + use crate::servers::udp::handlers::tests::{ + public_tracker, sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv6_remote_addr_fingerprint, + sample_issue_time, + }; fn sample_connect_request() -> ConnectRequest { ConnectRequest { @@ -454,14 +539,14 @@ mod tests { transaction_id: TransactionId(0i32.into()), }; - let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker()) + let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker(), sample_issue_time()) .await .unwrap(); assert_eq!( response, Response::Connect(ConnectResponse { - connection_id: into_connection_id(&make(&sample_ipv4_remote_addr())), + connection_id: make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), transaction_id: request.transaction_id }) ); @@ -473,14 +558,33 @@ mod tests { transaction_id: TransactionId(0i32.into()), }; - let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker()) + let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker(), sample_issue_time()) + .await + .unwrap(); + + assert_eq!( + response, + Response::Connect(ConnectResponse { + connection_id: make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + transaction_id: request.transaction_id + }) + ); + } + + #[tokio::test] + async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { + let request = ConnectRequest { + transaction_id: TransactionId(0i32.into()), + }; + + let response = handle_connect(sample_ipv6_remote_addr(), &request, &public_tracker(), sample_issue_time()) .await .unwrap(); assert_eq!( response, Response::Connect(ConnectResponse { - connection_id: into_connection_id(&make(&sample_ipv4_remote_addr())), + connection_id: make(sample_ipv6_remote_addr_fingerprint(), sample_issue_time()).unwrap(), transaction_id: request.transaction_id }) ); @@ -506,9 +610,14 @@ mod tests { ) .unwrap(), ); - handle_connect(client_socket_address, &sample_connect_request(), &torrent_tracker) - .await - .unwrap(); + handle_connect( + client_socket_address, + &sample_connect_request(), + &torrent_tracker, + sample_issue_time(), + ) + .await + .unwrap(); } #[tokio::test] @@ -529,9 +638,14 @@ mod tests { ) .unwrap(), ); - handle_connect(sample_ipv6_remote_addr(), &sample_connect_request(), &torrent_tracker) - .await - .unwrap(); + handle_connect( + sample_ipv6_remote_addr(), + &sample_connect_request(), + &torrent_tracker, + sample_issue_time(), + ) + .await + .unwrap(); } } @@ -545,8 +659,8 @@ mod tests { PeerId as AquaticPeerId, PeerKey, Port, TransactionId, }; - use crate::servers::udp::connection_cookie::{into_connection_id, make}; - use crate::servers::udp::handlers::tests::sample_ipv4_remote_addr; + use super::{sample_ipv4_remote_addr_fingerprint, sample_issue_time}; + use crate::servers::udp::connection_cookie::make; struct AnnounceRequestBuilder { request: AnnounceRequest, @@ -559,7 +673,7 @@ mod tests { let info_hash_aquatic = aquatic_udp_protocol::InfoHash([0u8; 20]); let default_request = AnnounceRequest { - connection_id: into_connection_id(&make(&sample_ipv4_remote_addr())), + connection_id: make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), action_placeholder: AnnounceActionPlaceholder::default(), transaction_id: TransactionId(0i32.into()), info_hash: info_hash_aquatic, @@ -621,10 +735,11 @@ mod tests { use mockall::predicate::eq; use crate::core::{self, statistics}; - use crate::servers::udp::connection_cookie::{into_connection_id, make}; + use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - public_tracker, sample_ipv4_socket_address, tracker_configuration, TorrentPeerBuilder, + make_remote_addr_fingerprint, public_tracker, sample_expiry_time, sample_ipv4_socket_address, sample_issue_time, + tolerance_max_time, tracker_configuration, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; @@ -640,14 +755,16 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) + .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip) .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker).await.unwrap(); + handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + .await + .unwrap(); let peers = tracker.get_torrent_peers(&info_hash.0.into()); @@ -664,10 +781,18 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) + .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - let response = handle_announce(remote_addr, &request, &public_tracker()).await.unwrap(); + let response = handle_announce( + remote_addr, + &request, + &public_tracker(), + sample_expiry_time(), + tolerance_max_time(), + ) + .await + .unwrap(); let empty_peer_vector: Vec> = vec![]; assert_eq!( @@ -703,14 +828,16 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V4(remote_client_ip), remote_client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) + .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(peer_address) .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker).await.unwrap(); + handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + .await + .unwrap(); let peers = tracker.get_torrent_peers(&info_hash.0.into()); @@ -736,10 +863,12 @@ mod tests { async fn announce_a_new_peer_using_ipv4(tracker: Arc) -> Response { let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) + .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - handle_announce(remote_addr, &request, &tracker).await.unwrap() + handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + .await + .unwrap() } #[tokio::test] @@ -782,6 +911,8 @@ mod tests { sample_ipv4_socket_address(), &AnnounceRequestBuilder::default().into(), &tracker, + sample_expiry_time(), + tolerance_max_time(), ) .await .unwrap(); @@ -793,10 +924,13 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; - use crate::servers::udp::connection_cookie::{into_connection_id, make}; + use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::tests::{public_tracker, TorrentPeerBuilder}; + use crate::servers::udp::handlers::tests::{ + make_remote_addr_fingerprint, public_tracker, sample_expiry_time, sample_issue_time, tolerance_max_time, + TorrentPeerBuilder, + }; #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { @@ -810,14 +944,16 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) + .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip) .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker).await.unwrap(); + handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + .await + .unwrap(); let peers = tracker.get_torrent_peers(&info_hash.0.into()); @@ -846,10 +982,11 @@ mod tests { use mockall::predicate::eq; use crate::core::{self, statistics}; - use crate::servers::udp::connection_cookie::{into_connection_id, make}; + use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - public_tracker, sample_ipv6_remote_addr, tracker_configuration, TorrentPeerBuilder, + make_remote_addr_fingerprint, public_tracker, sample_expiry_time, sample_ipv6_remote_addr, sample_issue_time, + tolerance_max_time, tracker_configuration, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; @@ -866,14 +1003,16 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) + .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip_v4) .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker).await.unwrap(); + handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + .await + .unwrap(); let peers = tracker.get_torrent_peers(&info_hash.0.into()); @@ -893,10 +1032,18 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), 8080); let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) + .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - let response = handle_announce(remote_addr, &request, &public_tracker()).await.unwrap(); + let response = handle_announce( + remote_addr, + &request, + &public_tracker(), + sample_expiry_time(), + tolerance_max_time(), + ) + .await + .unwrap(); let empty_peer_vector: Vec> = vec![]; assert_eq!( @@ -932,14 +1079,16 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V6(remote_client_ip), remote_client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) + .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(peer_address) .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker).await.unwrap(); + handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + .await + .unwrap(); let peers = tracker.get_torrent_peers(&info_hash.0.into()); @@ -968,10 +1117,12 @@ mod tests { let client_port = 8080; let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) + .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - handle_announce(remote_addr, &request, &tracker).await.unwrap() + handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + .await + .unwrap() } #[tokio::test] @@ -1013,10 +1164,18 @@ mod tests { let remote_addr = sample_ipv6_remote_addr(); let announce_request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) + .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - handle_announce(remote_addr, &announce_request, &tracker).await.unwrap(); + handle_announce( + remote_addr, + &announce_request, + &tracker, + sample_expiry_time(), + tolerance_max_time(), + ) + .await + .unwrap(); } mod from_a_loopback_ip { @@ -1027,10 +1186,13 @@ mod tests { use crate::core; use crate::core::statistics::Keeper; - use crate::servers::udp::connection_cookie::{into_connection_id, make}; + use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::tests::TrackerConfigurationBuilder; + use crate::servers::udp::handlers::tests::{ + make_remote_addr_fingerprint, sample_expiry_time, sample_issue_time, tolerance_max_time, + TrackerConfigurationBuilder, + }; #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { @@ -1052,14 +1214,16 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(into_connection_id(&make(&remote_addr))) + .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip_v4) .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker).await.unwrap(); + handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + .await + .unwrap(); let peers = tracker.get_torrent_peers(&info_hash.0.into()); @@ -1087,11 +1251,11 @@ mod tests { TransactionId, }; - use super::TorrentPeerBuilder; + use super::{make_remote_addr_fingerprint, TorrentPeerBuilder}; use crate::core::{self}; - use crate::servers::udp::connection_cookie::{into_connection_id, make}; + use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{public_tracker, sample_ipv4_remote_addr}; + use crate::servers::udp::handlers::tests::{public_tracker, sample_ipv4_remote_addr, sample_issue_time}; fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { TorrentScrapeStatistics { @@ -1109,7 +1273,7 @@ mod tests { let info_hashes = vec![info_hash]; let request = ScrapeRequest { - connection_id: into_connection_id(&make(&remote_addr)), + connection_id: make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap(), transaction_id: TransactionId(0i32.into()), info_hashes, }; @@ -1143,7 +1307,7 @@ mod tests { let info_hashes = vec![*info_hash]; ScrapeRequest { - connection_id: into_connection_id(&make(remote_addr)), + connection_id: make(make_remote_addr_fingerprint(remote_addr), sample_issue_time()).unwrap(), transaction_id: TransactionId::new(0i32), info_hashes, } @@ -1285,7 +1449,7 @@ mod tests { let info_hashes = vec![info_hash]; ScrapeRequest { - connection_id: into_connection_id(&make(remote_addr)), + connection_id: make(make_remote_addr_fingerprint(remote_addr), sample_issue_time()).unwrap(), transaction_id: TransactionId(0i32.into()), info_hashes, } diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 7f31d7739..348446876 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -35,6 +35,7 @@ impl Launcher { pub async fn run_with_graceful_shutdown( tracker: Arc, bind_to: SocketAddr, + cookie_lifetime: Duration, tx_start: oneshot::Sender, rx_halt: oneshot::Receiver, ) { @@ -65,7 +66,7 @@ impl Launcher { let local_addr = local_udp_url.clone(); tokio::task::spawn(async move { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_with_graceful_shutdown::task (listening...)"); - let () = Self::run_udp_server_main(receiver, tracker.clone()).await; + let () = Self::run_udp_server_main(receiver, tracker.clone(), cookie_lifetime).await; }) }; @@ -103,14 +104,16 @@ impl Launcher { } #[instrument(skip(receiver, tracker))] - async fn run_udp_server_main(mut receiver: Receiver, tracker: Arc) { + async fn run_udp_server_main(mut receiver: Receiver, tracker: Arc, cookie_lifetime: Duration) { let active_requests = &mut ActiveRequests::default(); let addr = receiver.bound_socket_address(); let local_addr = format!("udp://{addr}"); + let cookie_lifetime = cookie_lifetime.as_secs_f64(); + loop { - let processor = Processor::new(receiver.socket.clone(), tracker.clone()); + let processor = Processor::new(receiver.socket.clone(), tracker.clone(), cookie_lifetime); if let Some(req) = { tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server (wait for request)"); diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index d81624cb2..7067512b6 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -76,7 +76,7 @@ mod tests { let stopped = Server::new(Spawner::new(bind_to)); let started = stopped - .start(tracker, register.give_form()) + .start(tracker, register.give_form(), config.cookie_lifetime) .await .expect("it should start the server"); @@ -98,7 +98,7 @@ mod tests { let stopped = Server::new(Spawner::new(bind_to)); let started = stopped - .start(tracker, register.give_form()) + .start(tracker, register.give_form(), config.cookie_lifetime) .await .expect("it should start the server"); diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 9fa28a44d..2ac7f27cd 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -3,26 +3,45 @@ use std::net::SocketAddr; use std::sync::Arc; use aquatic_udp_protocol::Response; +use torrust_tracker_clock::clock::Time as _; use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; use crate::core::Tracker; use crate::servers::udp::{handlers, RawRequest}; +use crate::CurrentClock; pub struct Processor { socket: Arc, tracker: Arc, + cookie_lifetime: f64, } impl Processor { - pub fn new(socket: Arc, tracker: Arc) -> Self { - Self { socket, tracker } + pub fn new(socket: Arc, tracker: Arc, cookie_lifetime: f64) -> Self { + Self { + socket, + tracker, + cookie_lifetime, + } } #[instrument(skip(self, request))] pub async fn process_request(self, request: RawRequest) { + let cookie_issue_time = CurrentClock::now().as_secs_f64(); + let cookie_expiry_time = cookie_issue_time - self.cookie_lifetime - 1.0; + let cookie_tolerance_max_time = cookie_issue_time + 1.0; + let from = request.from; - let response = handlers::handle_packet(request, &self.tracker, self.socket.address()).await; + let response = handlers::handle_packet( + request, + &self.tracker, + self.socket.address(), + cookie_issue_time, + cookie_expiry_time, + cookie_tolerance_max_time, + ) + .await; self.send_response(from, response).await; } diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index dea293ad7..acebdcf75 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -1,6 +1,7 @@ //! A thin wrapper for tokio spawn to launch the UDP server launcher as a new task. use std::net::SocketAddr; use std::sync::Arc; +use std::time::Duration; use derive_more::derive::Display; use derive_more::Constructor; @@ -27,13 +28,14 @@ impl Spawner { pub fn spawn_launcher( &self, tracker: Arc, + cookie_lifetime: Duration, tx_start: oneshot::Sender, rx_halt: oneshot::Receiver, ) -> JoinHandle { let spawner = Self::new(self.bind_to); tokio::spawn(async move { - Launcher::run_with_graceful_shutdown(tracker, spawner.bind_to, tx_start, rx_halt).await; + Launcher::run_with_graceful_shutdown(tracker, spawner.bind_to, cookie_lifetime, tx_start, rx_halt).await; spawner }) } diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index e90c4da54..8b87c6efb 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -1,6 +1,7 @@ use std::fmt::Debug; use std::net::SocketAddr; use std::sync::Arc; +use std::time::Duration; use derive_more::derive::Display; use derive_more::Constructor; @@ -62,14 +63,19 @@ impl Server { /// It panics if unable to receive the bound socket address from service. /// #[instrument(skip(self, tracker, form), err, ret(Display, level = Level::INFO))] - pub async fn start(self, tracker: Arc, form: ServiceRegistrationForm) -> Result, std::io::Error> { + pub async fn start( + self, + tracker: Arc, + form: ServiceRegistrationForm, + cookie_lifetime: Duration, + ) -> Result, std::io::Error> { let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); assert!(!tx_halt.is_closed(), "Halt channel for UDP tracker should be open"); // May need to wrap in a task to about a tokio bug. - let task = self.state.spawner.spawn_launcher(tracker, tx_start, rx_halt); + let task = self.state.spawner.spawn_launcher(tracker, cookie_lifetime, tx_start, rx_halt); let local_addr = rx_start.await.expect("it should be able to start the service").address; diff --git a/src/shared/crypto/ephemeral_instance_keys.rs b/src/shared/crypto/ephemeral_instance_keys.rs index 44283365a..d214b6e6a 100644 --- a/src/shared/crypto/ephemeral_instance_keys.rs +++ b/src/shared/crypto/ephemeral_instance_keys.rs @@ -2,12 +2,24 @@ //! //! They are ephemeral because they are generated at runtime when the //! application starts and are not persisted anywhere. + +use blowfish::BlowfishLE; +use cipher::generic_array::GenericArray; +use cipher::{BlockSizeUser, KeyInit}; use rand::rngs::ThreadRng; use rand::Rng; pub type Seed = [u8; 32]; +pub type CipherBlowfish = BlowfishLE; +pub type CipherArrayBlowfish = GenericArray::BlockSize>; lazy_static! { /// The random static seed. pub static ref RANDOM_SEED: Seed = Rng::gen(&mut ThreadRng::default()); + + /// The random cipher from the seed. + pub static ref RANDOM_CIPHER_BLOWFISH: CipherBlowfish = CipherBlowfish::new_from_slice(&Rng::gen::(&mut ThreadRng::default())).expect("it could not generate key"); + + /// The constant cipher for testing. + pub static ref ZEROED_TEST_CIPHER_BLOWFISH: CipherBlowfish = CipherBlowfish::new_from_slice(&[0u8; 32]).expect("it could not generate key"); } diff --git a/src/shared/crypto/keys.rs b/src/shared/crypto/keys.rs index deb70574f..60dc16660 100644 --- a/src/shared/crypto/keys.rs +++ b/src/shared/crypto/keys.rs @@ -1,110 +1,154 @@ //! This module contains logic related to cryptographic keys. -pub mod seeds { - //! This module contains logic related to cryptographic seeds. - //! - //! Specifically, it contains the logic for storing the seed and providing - //! it to other modules. - //! - //! A **seed** is a pseudo-random number that is used as a secret key for - //! cryptographic operations. - use self::detail::CURRENT_SEED; - use crate::shared::crypto::ephemeral_instance_keys::{Seed, RANDOM_SEED}; - - /// This trait is for structures that can keep and provide a seed. - pub trait Keeper { - type Seed: Sized + Default + AsMut<[u8]>; - - /// It returns a reference to the seed that is keeping. - fn get_seed() -> &'static Self::Seed; +//! +//! Specifically, it contains the logic for storing the seed and providing +//! it to other modules. +//! +//! It also provides the logic for the cipher for encryption and decryption. + +use self::detail_cipher::CURRENT_CIPHER; +use self::detail_seed::CURRENT_SEED; +pub use crate::shared::crypto::ephemeral_instance_keys::CipherArrayBlowfish; +use crate::shared::crypto::ephemeral_instance_keys::{CipherBlowfish, Seed, RANDOM_CIPHER_BLOWFISH, RANDOM_SEED}; + +/// This trait is for structures that can keep and provide a seed. +pub trait Keeper { + type Seed: Sized + Default + AsMut<[u8]>; + type Cipher: cipher::BlockCipher; + + /// It returns a reference to the seed that is keeping. + fn get_seed() -> &'static Self::Seed; + fn get_cipher_blowfish() -> &'static Self::Cipher; +} + +/// The keeper for the instance. When the application is running +/// in production, this will be the seed keeper that is used. +pub struct Instance; + +/// The keeper for the current execution. It's a facade at compilation +/// time that will either be the instance seed keeper (with a randomly +/// generated key for production) or the zeroed seed keeper. +pub struct Current; + +impl Keeper for Instance { + type Seed = Seed; + type Cipher = CipherBlowfish; + + fn get_seed() -> &'static Self::Seed { + &RANDOM_SEED } - /// The seed keeper for the instance. When the application is running - /// in production, this will be the seed keeper that is used. - pub struct Instance; + fn get_cipher_blowfish() -> &'static Self::Cipher { + &RANDOM_CIPHER_BLOWFISH + } +} - /// The seed keeper for the current execution. It's a facade at compilation - /// time that will either be the instance seed keeper (with a randomly - /// generated key for production) or the zeroed seed keeper. - pub struct Current; +impl Keeper for Current { + type Seed = Seed; + type Cipher = CipherBlowfish; - impl Keeper for Instance { - type Seed = Seed; + #[allow(clippy::needless_borrow)] + fn get_seed() -> &'static Self::Seed { + &CURRENT_SEED + } - fn get_seed() -> &'static Self::Seed { - &RANDOM_SEED - } + fn get_cipher_blowfish() -> &'static Self::Cipher { + &CURRENT_CIPHER } +} + +#[cfg(test)] +mod tests { + + use super::detail_seed::ZEROED_TEST_SEED; + use super::{Current, Instance, Keeper}; + use crate::shared::crypto::ephemeral_instance_keys::{CipherBlowfish, Seed, ZEROED_TEST_CIPHER_BLOWFISH}; - impl Keeper for Current { + pub struct ZeroedTest; + + impl Keeper for ZeroedTest { type Seed = Seed; + type Cipher = CipherBlowfish; #[allow(clippy::needless_borrow)] fn get_seed() -> &'static Self::Seed { - &CURRENT_SEED + &ZEROED_TEST_SEED + } + + fn get_cipher_blowfish() -> &'static Self::Cipher { + &ZEROED_TEST_CIPHER_BLOWFISH } } + #[test] + fn the_default_seed_and_the_zeroed_seed_should_be_the_same_when_testing() { + assert_eq!(Current::get_seed(), ZeroedTest::get_seed()); + } + + #[test] + fn the_default_seed_and_the_instance_seed_should_be_different_when_testing() { + assert_ne!(Current::get_seed(), Instance::get_seed()); + } +} + +mod detail_seed { + use crate::shared::crypto::ephemeral_instance_keys::Seed; + + #[allow(dead_code)] + pub const ZEROED_TEST_SEED: Seed = [0u8; 32]; + #[cfg(test)] - mod tests { - use super::detail::ZEROED_TEST_SEED; - use super::{Current, Instance, Keeper}; - use crate::shared::crypto::ephemeral_instance_keys::Seed; + pub use ZEROED_TEST_SEED as CURRENT_SEED; - pub struct ZeroedTestSeed; + #[cfg(not(test))] + pub use crate::shared::crypto::ephemeral_instance_keys::RANDOM_SEED as CURRENT_SEED; - impl Keeper for ZeroedTestSeed { - type Seed = Seed; + #[cfg(test)] + mod tests { + use crate::shared::crypto::ephemeral_instance_keys::RANDOM_SEED; + use crate::shared::crypto::keys::detail_seed::ZEROED_TEST_SEED; + use crate::shared::crypto::keys::CURRENT_SEED; - #[allow(clippy::needless_borrow)] - fn get_seed() -> &'static Self::Seed { - &ZEROED_TEST_SEED - } + #[test] + fn it_should_have_a_zero_test_seed() { + assert_eq!(ZEROED_TEST_SEED, [0u8; 32]); } #[test] - fn the_default_seed_and_the_zeroed_seed_should_be_the_same_when_testing() { - assert_eq!(Current::get_seed(), ZeroedTestSeed::get_seed()); + fn it_should_default_to_zeroed_seed_when_testing() { + assert_eq!(CURRENT_SEED, ZEROED_TEST_SEED); } #[test] - fn the_default_seed_and_the_instance_seed_should_be_different_when_testing() { - assert_ne!(Current::get_seed(), Instance::get_seed()); + fn it_should_have_a_large_random_seed() { + assert!(u128::from_ne_bytes((*RANDOM_SEED)[..16].try_into().unwrap()) > u128::from(u64::MAX)); + assert!(u128::from_ne_bytes((*RANDOM_SEED)[16..].try_into().unwrap()) > u128::from(u64::MAX)); } } +} - mod detail { - use crate::shared::crypto::ephemeral_instance_keys::Seed; - - #[allow(dead_code)] - pub const ZEROED_TEST_SEED: &Seed = &[0u8; 32]; - - #[cfg(test)] - pub use ZEROED_TEST_SEED as CURRENT_SEED; +mod detail_cipher { + #[allow(unused_imports)] + #[cfg(not(test))] + pub use crate::shared::crypto::ephemeral_instance_keys::RANDOM_CIPHER_BLOWFISH as CURRENT_CIPHER; + #[cfg(test)] + pub use crate::shared::crypto::ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH as CURRENT_CIPHER; - #[cfg(not(test))] - pub use crate::shared::crypto::ephemeral_instance_keys::RANDOM_SEED as CURRENT_SEED; + #[cfg(test)] + mod tests { + use cipher::BlockEncrypt; - #[cfg(test)] - mod tests { - use crate::shared::crypto::ephemeral_instance_keys::RANDOM_SEED; - use crate::shared::crypto::keys::seeds::detail::ZEROED_TEST_SEED; - use crate::shared::crypto::keys::seeds::CURRENT_SEED; + use crate::shared::crypto::ephemeral_instance_keys::{CipherArrayBlowfish, ZEROED_TEST_CIPHER_BLOWFISH}; + use crate::shared::crypto::keys::detail_cipher::CURRENT_CIPHER; - #[test] - fn it_should_have_a_zero_test_seed() { - assert_eq!(*ZEROED_TEST_SEED, [0u8; 32]); - } + #[test] + fn it_should_default_to_zeroed_seed_when_testing() { + let mut data: cipher::generic_array::GenericArray = CipherArrayBlowfish::from([0u8; 8]); + let mut data_2 = CipherArrayBlowfish::from([0u8; 8]); - #[test] - fn it_should_default_to_zeroed_seed_when_testing() { - assert_eq!(*CURRENT_SEED, *ZEROED_TEST_SEED); - } + CURRENT_CIPHER.encrypt_block(&mut data); + ZEROED_TEST_CIPHER_BLOWFISH.encrypt_block(&mut data_2); - #[test] - fn it_should_have_a_large_random_seed() { - assert!(u128::from_ne_bytes((*RANDOM_SEED)[..16].try_into().unwrap()) > u128::from(u64::MAX)); - assert!(u128::from_ne_bytes((*RANDOM_SEED)[16..].try_into().unwrap()) > u128::from(u64::MAX)); - } + assert_eq!(data, data_2); } } } diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 83dc076ce..f96ba2bea 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -55,11 +55,16 @@ impl Environment { #[allow(dead_code)] pub async fn start(self) -> Environment { + let cookie_lifetime = self.config.cookie_lifetime; Environment { config: self.config, tracker: self.tracker.clone(), registar: self.registar.clone(), - server: self.server.start(self.tracker, self.registar.give_form()).await.unwrap(), + server: self + .server + .start(self.tracker, self.registar.give_form(), cookie_lifetime) + .await + .unwrap(), } } } From c53e2895d96b2c6c30a7d454d23f793b53fee4f1 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Tue, 19 Nov 2024 16:15:23 +0800 Subject: [PATCH 0523/1297] udp: cookie fixups as suggested by Jose --- src/bootstrap/app.rs | 2 +- src/servers/udp/connection_cookie.rs | 32 +++-- src/servers/udp/error.rs | 12 +- src/servers/udp/handlers.rs | 201 +++++++++++---------------- src/servers/udp/server/processor.rs | 11 +- 5 files changed, 110 insertions(+), 148 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index e106f73cc..4f3425469 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -58,7 +58,7 @@ pub fn check_seed() { let seed = keys::Current::get_seed(); let instance = keys::Instance::get_seed(); - assert_eq!(seed, instance, "maybe using zeroed see in production!?"); + assert_eq!(seed, instance, "maybe using zeroed seed in production!?"); } /// It initializes the application with the given configuration. diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs index 31c6396e8..9ed1bcdc8 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/servers/udp/connection_cookie.rs @@ -81,7 +81,7 @@ use aquatic_udp_protocol::ConnectionId as Cookie; use cookie_builder::{assemble, decode, disassemble, encode}; use zerocopy::AsBytes; -use super::error::{self, Error}; +use super::error::Error; use crate::shared::crypto::keys::CipherArrayBlowfish; /// Generates a new connection cookie. @@ -106,6 +106,8 @@ pub fn make(fingerprint: u64, issue_at: f64) -> Result { Ok(zerocopy::FromBytes::read_from(cookie.as_slice()).expect("it should be the same size")) } +use std::ops::Range; + /// Checks if the supplied `connection_cookie` is valid. /// /// # Errors @@ -114,9 +116,9 @@ pub fn make(fingerprint: u64, issue_at: f64) -> Result { /// /// # Panics /// -/// It would panic if cookie min value is larger than the max value. -pub fn check(cookie: &Cookie, fingerprint: u64, min: f64, max: f64) -> Result { - assert!(min < max, "min is larger than max"); +/// It would panic if the range start is not smaller than it's end. +pub fn check(cookie: &Cookie, fingerprint: u64, valid_range: Range) -> Result { + assert!(valid_range.start <= valid_range.end, "range start is larger than range end"); let cookie_bytes = CipherArrayBlowfish::from_slice(cookie.0.as_bytes()); let cookie_bytes = decode(*cookie_bytes); @@ -124,22 +126,22 @@ pub fn check(cookie: &Cookie, fingerprint: u64, min: f64, max: f64) -> Result max { + if issue_time > valid_range.end { return Err(Error::ConnectionIdFromFuture { - future_age: issue_time, - max_age: max, + future_value: issue_time, + max_value: valid_range.end, }); } @@ -262,7 +264,7 @@ mod tests { let min = issue_at - 10.0; let max = issue_at + 10.0; - let result = check(&cookie, fingerprint, min, max).unwrap(); + let result = check(&cookie, fingerprint, min..max).unwrap(); // we should have exactly the same bytes returned assert_eq!(result.to_ne_bytes(), issue_at.to_ne_bytes()); @@ -277,7 +279,7 @@ mod tests { let min = issue_at + 10.0; let max = issue_at + 20.0; - let result = check(&cookie, fingerprint, min, max).unwrap_err(); + let result = check(&cookie, fingerprint, min..max).unwrap_err(); match result { Error::ConnectionIdExpired { .. } => {} // Expected error @@ -295,7 +297,7 @@ mod tests { let min = issue_at - 20.0; let max = issue_at - 10.0; - let result = check(&cookie, fingerprint, min, max).unwrap_err(); + let result = check(&cookie, fingerprint, min..max).unwrap_err(); match result { Error::ConnectionIdFromFuture { .. } => {} // Expected error diff --git a/src/servers/udp/error.rs b/src/servers/udp/error.rs index 8f30b0138..5996cae73 100644 --- a/src/servers/udp/error.rs +++ b/src/servers/udp/error.rs @@ -16,14 +16,14 @@ pub enum Error { #[error("the issue time should be a normal floating point number")] InvalidCookieIssueTime { invalid_value: f64 }, - #[error("connection id was decoded, but could not be understood")] - InvalidConnectionId { bad_id: ConnectionCookie }, + #[error("connection id did not produce a normal value")] + ConnectionIdNotNormal { not_normal_value: f64 }, - #[error("connection id was decoded, but was expired (too old)")] - ConnectionIdExpired { bad_age: f64, min_age: f64 }, + #[error("connection id produced an expired value")] + ConnectionIdExpired { expired_value: f64, min_value: f64 }, - #[error("connection id was decoded, but was invalid (from future)")] - ConnectionIdFromFuture { future_age: f64, max_age: f64 }, + #[error("connection id produces a future value")] + ConnectionIdFromFuture { future_value: f64, max_value: f64 }, /// Error returned when the domain tracker returns an error. #[error("tracker server error: {source}")] diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index ba75ac3c6..814ee5e9e 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -2,6 +2,7 @@ use std::fmt; use std::hash::{DefaultHasher, Hash, Hasher as _}; use std::net::{IpAddr, SocketAddr}; +use std::ops::Range; use std::panic::Location; use std::sync::Arc; use std::time::Instant; @@ -12,6 +13,7 @@ use aquatic_udp_protocol::{ ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_clock::clock::Time as _; use torrust_tracker_located_error::DynError; use tracing::{instrument, Level}; use uuid::Uuid; @@ -24,6 +26,26 @@ use crate::servers::udp::error::Error; use crate::servers::udp::logging::{log_bad_request, log_error_response, log_request, log_response}; use crate::servers::udp::peer_builder; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; +use crate::CurrentClock; + +#[derive(Debug)] +pub(super) struct CookieTimeValues { + pub(super) issue_time: f64, + pub(super) valid_range: Range, +} + +impl CookieTimeValues { + pub(super) fn new(cookie_lifetime: f64) -> Self { + let issue_time = CurrentClock::now().as_secs_f64(); + let expiry_time = issue_time - cookie_lifetime - 1.0; + let tolerance_max_time = issue_time + 1.0; + + Self { + issue_time, + valid_range: expiry_time..tolerance_max_time, + } + } +} /// It handles the incoming UDP packets. /// @@ -38,9 +60,7 @@ pub(crate) async fn handle_packet( udp_request: RawRequest, tracker: &Tracker, local_addr: SocketAddr, - cookie_issue_time: f64, - cookie_expiry_time: f64, - cookie_tolerance_max_time: f64, + cookie_time_values: CookieTimeValues, ) -> Response { tracing::debug!("Handling Packets: {udp_request:?}"); @@ -63,16 +83,7 @@ pub(crate) async fn handle_packet( Request::Scrape(scrape_request) => scrape_request.transaction_id, }; - let response = match handle_request( - request, - udp_request.from, - tracker, - cookie_issue_time, - cookie_expiry_time, - cookie_tolerance_max_time, - ) - .await - { + let response = match handle_request(request, udp_request.from, tracker, cookie_time_values).await { Ok(response) => response, Err(e) => handle_error(&e, transaction_id), }; @@ -110,23 +121,16 @@ pub async fn handle_request( request: Request, remote_addr: SocketAddr, tracker: &Tracker, - cookie_issue_time: f64, - cookie_expiry_time: f64, - cookie_tolerance_max_time: f64, + cookie_time_values: CookieTimeValues, ) -> Result { tracing::trace!("handle request"); match request { - Request::Connect(connect_request) => handle_connect(remote_addr, &connect_request, tracker, cookie_issue_time).await, + Request::Connect(connect_request) => { + handle_connect(remote_addr, &connect_request, tracker, cookie_time_values.issue_time).await + } Request::Announce(announce_request) => { - handle_announce( - remote_addr, - &announce_request, - tracker, - cookie_expiry_time, - cookie_tolerance_max_time, - ) - .await + handle_announce(remote_addr, &announce_request, tracker, cookie_time_values.valid_range).await } Request::Scrape(scrape_request) => handle_scrape(remote_addr, &scrape_request, tracker).await, } @@ -147,14 +151,7 @@ pub async fn handle_connect( ) -> Result { tracing::trace!("handle connect"); - let connection_id = make( - { - let mut state = DefaultHasher::new(); - remote_addr.hash(&mut state); - state.finish() - }, - cookie_issue_time, - )?; + let connection_id = make(make_remote_fingerprint(&remote_addr), cookie_issue_time)?; let response = ConnectResponse { transaction_id: request.transaction_id, @@ -185,8 +182,7 @@ pub async fn handle_announce( remote_addr: SocketAddr, announce_request: &AnnounceRequest, tracker: &Tracker, - cookie_expiry_time: f64, - cookie_tolerance_max_time: f64, + cookie_valid_range: Range, ) -> Result { tracing::trace!("handle announce"); @@ -199,13 +195,8 @@ pub async fn handle_announce( check( &announce_request.connection_id, - { - let mut state = DefaultHasher::new(); - remote_addr.hash(&mut state); - state.finish() - }, - cookie_expiry_time, - cookie_tolerance_max_time, + make_remote_fingerprint(&remote_addr), + cookie_valid_range, )?; let info_hash = announce_request.info_hash.into(); @@ -349,6 +340,12 @@ fn handle_error(e: &Error, transaction_id: TransactionId) -> Response { }) } +fn make_remote_fingerprint(remote_addr: &SocketAddr) -> u64 { + let mut state = DefaultHasher::new(); + remote_addr.hash(&mut state); + state.finish() +} + /// An identifier for a request. #[derive(Debug, Clone)] pub struct RequestId(Uuid); @@ -368,8 +365,8 @@ impl fmt::Display for RequestId { #[cfg(test)] mod tests { - use std::hash::{DefaultHasher, Hash as _, Hasher as _}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::ops::Range; use std::sync::Arc; use aquatic_udp_protocol::{NumberOfBytes, PeerId}; @@ -378,6 +375,7 @@ mod tests { use torrust_tracker_primitives::peer; use torrust_tracker_test_helpers::configuration; + use super::make_remote_fingerprint; use crate::core::services::tracker_factory; use crate::core::Tracker; use crate::CurrentClock; @@ -406,18 +404,12 @@ mod tests { tracker_factory(configuration).into() } - fn make_remote_addr_fingerprint(remote_addr: &SocketAddr) -> u64 { - let mut state = DefaultHasher::new(); - remote_addr.hash(&mut state); - state.finish() - } - fn sample_ipv4_remote_addr() -> SocketAddr { sample_ipv4_socket_address() } fn sample_ipv4_remote_addr_fingerprint() -> u64 { - make_remote_addr_fingerprint(&sample_ipv4_socket_address()) + make_remote_fingerprint(&sample_ipv4_socket_address()) } fn sample_ipv6_remote_addr() -> SocketAddr { @@ -425,7 +417,7 @@ mod tests { } fn sample_ipv6_remote_addr_fingerprint() -> u64 { - make_remote_addr_fingerprint(&sample_ipv6_socket_address()) + make_remote_fingerprint(&sample_ipv6_socket_address()) } fn sample_ipv4_socket_address() -> SocketAddr { @@ -440,12 +432,8 @@ mod tests { 1_000_000_000_f64 } - fn sample_expiry_time() -> f64 { - sample_issue_time() - 10.0 - } - - fn tolerance_max_time() -> f64 { - sample_issue_time() + 10.0 + fn sample_cookie_valid_range() -> Range { + sample_issue_time() - 10.0..sample_issue_time() + 10.0 } #[derive(Debug, Default)] @@ -738,8 +726,8 @@ mod tests { use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - make_remote_addr_fingerprint, public_tracker, sample_expiry_time, sample_ipv4_socket_address, sample_issue_time, - tolerance_max_time, tracker_configuration, TorrentPeerBuilder, + make_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, + sample_issue_time, tracker_configuration, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; @@ -755,14 +743,14 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip) .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) .await .unwrap(); @@ -781,18 +769,12 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - let response = handle_announce( - remote_addr, - &request, - &public_tracker(), - sample_expiry_time(), - tolerance_max_time(), - ) - .await - .unwrap(); + let response = handle_announce(remote_addr, &request, &public_tracker(), sample_cookie_valid_range()) + .await + .unwrap(); let empty_peer_vector: Vec> = vec![]; assert_eq!( @@ -828,14 +810,14 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V4(remote_client_ip), remote_client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(peer_address) .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) .await .unwrap(); @@ -863,10 +845,10 @@ mod tests { async fn announce_a_new_peer_using_ipv4(tracker: Arc) -> Response { let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) .await .unwrap() } @@ -911,8 +893,7 @@ mod tests { sample_ipv4_socket_address(), &AnnounceRequestBuilder::default().into(), &tracker, - sample_expiry_time(), - tolerance_max_time(), + sample_cookie_valid_range(), ) .await .unwrap(); @@ -928,8 +909,7 @@ mod tests { use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - make_remote_addr_fingerprint, public_tracker, sample_expiry_time, sample_issue_time, tolerance_max_time, - TorrentPeerBuilder, + make_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_issue_time, TorrentPeerBuilder, }; #[tokio::test] @@ -944,14 +924,14 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip) .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) .await .unwrap(); @@ -985,8 +965,8 @@ mod tests { use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - make_remote_addr_fingerprint, public_tracker, sample_expiry_time, sample_ipv6_remote_addr, sample_issue_time, - tolerance_max_time, tracker_configuration, TorrentPeerBuilder, + make_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, sample_issue_time, + tracker_configuration, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; @@ -1003,14 +983,14 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip_v4) .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) .await .unwrap(); @@ -1032,18 +1012,12 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), 8080); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - let response = handle_announce( - remote_addr, - &request, - &public_tracker(), - sample_expiry_time(), - tolerance_max_time(), - ) - .await - .unwrap(); + let response = handle_announce(remote_addr, &request, &public_tracker(), sample_cookie_valid_range()) + .await + .unwrap(); let empty_peer_vector: Vec> = vec![]; assert_eq!( @@ -1079,14 +1053,14 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V6(remote_client_ip), remote_client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(peer_address) .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) .await .unwrap(); @@ -1117,10 +1091,10 @@ mod tests { let client_port = 8080; let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) .await .unwrap() } @@ -1164,18 +1138,12 @@ mod tests { let remote_addr = sample_ipv6_remote_addr(); let announce_request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - handle_announce( - remote_addr, - &announce_request, - &tracker, - sample_expiry_time(), - tolerance_max_time(), - ) - .await - .unwrap(); + handle_announce(remote_addr, &announce_request, &tracker, sample_cookie_valid_range()) + .await + .unwrap(); } mod from_a_loopback_ip { @@ -1190,8 +1158,7 @@ mod tests { use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - make_remote_addr_fingerprint, sample_expiry_time, sample_issue_time, tolerance_max_time, - TrackerConfigurationBuilder, + make_remote_fingerprint, sample_cookie_valid_range, sample_issue_time, TrackerConfigurationBuilder, }; #[tokio::test] @@ -1214,14 +1181,14 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip_v4) .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker, sample_expiry_time(), tolerance_max_time()) + handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) .await .unwrap(); @@ -1251,7 +1218,7 @@ mod tests { TransactionId, }; - use super::{make_remote_addr_fingerprint, TorrentPeerBuilder}; + use super::{make_remote_fingerprint, TorrentPeerBuilder}; use crate::core::{self}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_scrape; @@ -1273,7 +1240,7 @@ mod tests { let info_hashes = vec![info_hash]; let request = ScrapeRequest { - connection_id: make(make_remote_addr_fingerprint(&remote_addr), sample_issue_time()).unwrap(), + connection_id: make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap(), transaction_id: TransactionId(0i32.into()), info_hashes, }; @@ -1307,7 +1274,7 @@ mod tests { let info_hashes = vec![*info_hash]; ScrapeRequest { - connection_id: make(make_remote_addr_fingerprint(remote_addr), sample_issue_time()).unwrap(), + connection_id: make(make_remote_fingerprint(remote_addr), sample_issue_time()).unwrap(), transaction_id: TransactionId::new(0i32), info_hashes, } @@ -1449,7 +1416,7 @@ mod tests { let info_hashes = vec![info_hash]; ScrapeRequest { - connection_id: make(make_remote_addr_fingerprint(remote_addr), sample_issue_time()).unwrap(), + connection_id: make(make_remote_fingerprint(remote_addr), sample_issue_time()).unwrap(), transaction_id: TransactionId(0i32.into()), info_hashes, } diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 2ac7f27cd..703367f35 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -3,13 +3,12 @@ use std::net::SocketAddr; use std::sync::Arc; use aquatic_udp_protocol::Response; -use torrust_tracker_clock::clock::Time as _; use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; use crate::core::Tracker; +use crate::servers::udp::handlers::CookieTimeValues; use crate::servers::udp::{handlers, RawRequest}; -use crate::CurrentClock; pub struct Processor { socket: Arc, @@ -28,18 +27,12 @@ impl Processor { #[instrument(skip(self, request))] pub async fn process_request(self, request: RawRequest) { - let cookie_issue_time = CurrentClock::now().as_secs_f64(); - let cookie_expiry_time = cookie_issue_time - self.cookie_lifetime - 1.0; - let cookie_tolerance_max_time = cookie_issue_time + 1.0; - let from = request.from; let response = handlers::handle_packet( request, &self.tracker, self.socket.address(), - cookie_issue_time, - cookie_expiry_time, - cookie_tolerance_max_time, + CookieTimeValues::new(self.cookie_lifetime), ) .await; self.send_response(from, response).await; From 8c703955f010948199be75c2dcd3481d519d6bc4 Mon Sep 17 00:00:00 2001 From: Cameron Garnham Date: Wed, 20 Nov 2024 05:13:14 +0800 Subject: [PATCH 0524/1297] udp: various changes - remove old logging module - remove udp test for private mode - check `ConnectionID` for scrape - check `ConnectionID` when included in badly formatted responses - pass-through any errors when parsing a response --- cSpell.json | 1 + src/core/mod.rs | 2 + src/core/services/statistics/mod.rs | 2 + src/core/statistics.rs | 24 ++ .../apis/v1/context/stats/resources.rs | 22 +- src/servers/udp/connection_cookie.rs | 27 +- src/servers/udp/error.rs | 24 +- src/servers/udp/handlers.rs | 397 +++++++++--------- src/servers/udp/logging.rs | 87 ---- src/servers/udp/mod.rs | 1 - src/servers/udp/server/launcher.rs | 9 +- .../servers/api/v1/contract/context/stats.rs | 2 + tests/servers/udp/asserts.rs | 6 +- tests/servers/udp/contract.rs | 4 +- 14 files changed, 288 insertions(+), 320 deletions(-) delete mode 100644 src/servers/udp/logging.rs diff --git a/cSpell.json b/cSpell.json index e2ecd1bc3..090a2b0e3 100644 --- a/cSpell.json +++ b/cSpell.json @@ -164,6 +164,7 @@ "typenum", "Unamed", "underflows", + "Unsendable", "untuple", "uroot", "Vagaa", diff --git a/src/core/mod.rs b/src/core/mod.rs index a41ef2eba..835776e30 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -470,6 +470,7 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; +use tracing::instrument; use self::auth::Key; use self::error::Error; @@ -1092,6 +1093,7 @@ impl Tracker { /// /// Will return an error if the tracker is running in `listed` mode /// and the infohash is not whitelisted. + #[instrument(skip(self, info_hash), err)] pub async fn authorize(&self, info_hash: &InfoHash) -> Result<(), Error> { if !self.is_listed() { return Ok(()); diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index ee1c0c4fa..0e7735be2 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -76,9 +76,11 @@ pub async fn get_metrics(tracker: Arc) -> TrackerMetrics { udp4_connections_handled: stats.udp4_connections_handled, udp4_announces_handled: stats.udp4_announces_handled, udp4_scrapes_handled: stats.udp4_scrapes_handled, + udp4_errors_handled: stats.udp4_errors_handled, udp6_connections_handled: stats.udp6_connections_handled, udp6_announces_handled: stats.udp6_announces_handled, udp6_scrapes_handled: stats.udp6_scrapes_handled, + udp6_errors_handled: stats.udp6_errors_handled, }, } } diff --git a/src/core/statistics.rs b/src/core/statistics.rs index c9681d23c..b106b2691 100644 --- a/src/core/statistics.rs +++ b/src/core/statistics.rs @@ -47,9 +47,11 @@ pub enum Event { Udp4Connect, Udp4Announce, Udp4Scrape, + Udp4Error, Udp6Connect, Udp6Announce, Udp6Scrape, + Udp6Error, } /// Metrics collected by the tracker. @@ -82,12 +84,16 @@ pub struct Metrics { pub udp4_announces_handled: u64, /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. pub udp4_scrapes_handled: u64, + /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. + pub udp4_errors_handled: u64, /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. pub udp6_connections_handled: u64, /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. pub udp6_announces_handled: u64, /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. pub udp6_scrapes_handled: u64, + /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. + pub udp6_errors_handled: u64, } /// The service responsible for keeping tracker metrics (listening to statistics events and handle them). @@ -168,6 +174,9 @@ async fn event_handler(event: Event, stats_repository: &Repo) { Event::Udp4Scrape => { stats_repository.increase_udp4_scrapes().await; } + Event::Udp4Error => { + stats_repository.increase_udp4_errors().await; + } // UDP6 Event::Udp6Connect => { @@ -179,6 +188,9 @@ async fn event_handler(event: Event, stats_repository: &Repo) { Event::Udp6Scrape => { stats_repository.increase_udp6_scrapes().await; } + Event::Udp6Error => { + stats_repository.increase_udp6_errors().await; + } } tracing::debug!("stats: {:?}", stats_repository.get_stats().await); @@ -282,6 +294,12 @@ impl Repo { drop(stats_lock); } + pub async fn increase_udp4_errors(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_errors_handled += 1; + drop(stats_lock); + } + pub async fn increase_udp6_connections(&self) { let mut stats_lock = self.stats.write().await; stats_lock.udp6_connections_handled += 1; @@ -299,6 +317,12 @@ impl Repo { stats_lock.udp6_scrapes_handled += 1; drop(stats_lock); } + + pub async fn increase_udp6_errors(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_errors_handled += 1; + drop(stats_lock); + } } #[cfg(test)] diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index 9e8ab6bab..de6f6ca89 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -38,12 +38,16 @@ pub struct Stats { pub udp4_announces_handled: u64, /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. pub udp4_scrapes_handled: u64, + /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. + pub udp4_errors_handled: u64, /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. pub udp6_connections_handled: u64, /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. pub udp6_announces_handled: u64, /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. pub udp6_scrapes_handled: u64, + /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. + pub udp6_errors_handled: u64, } impl From for Stats { @@ -62,9 +66,11 @@ impl From for Stats { udp4_connections_handled: metrics.protocol_metrics.udp4_connections_handled, udp4_announces_handled: metrics.protocol_metrics.udp4_announces_handled, udp4_scrapes_handled: metrics.protocol_metrics.udp4_scrapes_handled, + udp4_errors_handled: metrics.protocol_metrics.udp4_errors_handled, udp6_connections_handled: metrics.protocol_metrics.udp6_connections_handled, udp6_announces_handled: metrics.protocol_metrics.udp6_announces_handled, udp6_scrapes_handled: metrics.protocol_metrics.udp6_scrapes_handled, + udp6_errors_handled: metrics.protocol_metrics.udp6_errors_handled, } } } @@ -97,9 +103,11 @@ mod tests { udp4_connections_handled: 11, udp4_announces_handled: 12, udp4_scrapes_handled: 13, - udp6_connections_handled: 14, - udp6_announces_handled: 15, - udp6_scrapes_handled: 16 + udp4_errors_handled: 14, + udp6_connections_handled: 15, + udp6_announces_handled: 16, + udp6_scrapes_handled: 17, + udp6_errors_handled: 18 } }), Stats { @@ -116,9 +124,11 @@ mod tests { udp4_connections_handled: 11, udp4_announces_handled: 12, udp4_scrapes_handled: 13, - udp6_connections_handled: 14, - udp6_announces_handled: 15, - udp6_scrapes_handled: 16 + udp4_errors_handled: 14, + udp6_connections_handled: 15, + udp6_announces_handled: 16, + udp6_scrapes_handled: 17, + udp6_errors_handled: 18 } ); } diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs index 9ed1bcdc8..50359033c 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/servers/udp/connection_cookie.rs @@ -79,6 +79,7 @@ use aquatic_udp_protocol::ConnectionId as Cookie; use cookie_builder::{assemble, decode, disassemble, encode}; +use tracing::instrument; use zerocopy::AsBytes; use super::error::Error; @@ -94,9 +95,12 @@ use crate::shared::crypto::keys::CipherArrayBlowfish; /// /// It would panic if the cookie is not exactly 8 bytes is size. /// +#[instrument(err)] pub fn make(fingerprint: u64, issue_at: f64) -> Result { if !issue_at.is_normal() { - return Err(Error::InvalidCookieIssueTime { invalid_value: issue_at }); + return Err(Error::CookieValueNotNormal { + not_normal_value: issue_at, + }); } let cookie = assemble(fingerprint, issue_at); @@ -117,6 +121,7 @@ use std::ops::Range; /// # Panics /// /// It would panic if the range start is not smaller than it's end. +#[instrument(err)] pub fn check(cookie: &Cookie, fingerprint: u64, valid_range: Range) -> Result { assert!(valid_range.start <= valid_range.end, "range start is larger than range end"); @@ -126,20 +131,20 @@ pub fn check(cookie: &Cookie, fingerprint: u64, valid_range: Range) -> Resu let issue_time = disassemble(fingerprint, cookie_bytes); if !issue_time.is_normal() { - return Err(Error::ConnectionIdNotNormal { + return Err(Error::CookieValueNotNormal { not_normal_value: issue_time, }); } if issue_time < valid_range.start { - return Err(Error::ConnectionIdExpired { + return Err(Error::CookieValueExpired { expired_value: issue_time, min_value: valid_range.start, }); } if issue_time > valid_range.end { - return Err(Error::ConnectionIdFromFuture { + return Err(Error::CookieValueFromFuture { future_value: issue_time, max_value: valid_range.end, }); @@ -150,7 +155,7 @@ pub fn check(cookie: &Cookie, fingerprint: u64, valid_range: Range) -> Resu mod cookie_builder { use cipher::{BlockDecrypt, BlockEncrypt}; - use tracing::{instrument, Level}; + use tracing::instrument; use zerocopy::{byteorder, AsBytes as _, NativeEndian}; pub type CookiePlainText = CipherArrayBlowfish; @@ -158,7 +163,7 @@ mod cookie_builder { use crate::shared::crypto::keys::{CipherArrayBlowfish, Current, Keeper}; - #[instrument(ret(level = Level::TRACE))] + #[instrument()] pub(super) fn assemble(fingerprint: u64, issue_at: f64) -> CookiePlainText { let issue_at: byteorder::I64 = *zerocopy::FromBytes::ref_from(&issue_at.to_ne_bytes()).expect("it should be aligned"); @@ -172,7 +177,7 @@ mod cookie_builder { *CipherArrayBlowfish::from_slice(cookie.as_bytes()) } - #[instrument(ret(level = Level::TRACE))] + #[instrument()] pub(super) fn disassemble(fingerprint: u64, cookie: CookiePlainText) -> f64 { let fingerprint: byteorder::I64 = *zerocopy::FromBytes::ref_from(&fingerprint.to_ne_bytes()).expect("it should be aligned"); @@ -189,7 +194,7 @@ mod cookie_builder { issue_time.get() } - #[instrument(ret(level = Level::TRACE))] + #[instrument()] pub(super) fn encode(mut cookie: CookiePlainText) -> CookieCipherText { let cipher = Current::get_cipher_blowfish(); @@ -198,7 +203,7 @@ mod cookie_builder { cookie } - #[instrument(ret(level = Level::TRACE))] + #[instrument()] pub(super) fn decode(mut cookie: CookieCipherText) -> CookiePlainText { let cipher = Current::get_cipher_blowfish(); @@ -282,7 +287,7 @@ mod tests { let result = check(&cookie, fingerprint, min..max).unwrap_err(); match result { - Error::ConnectionIdExpired { .. } => {} // Expected error + Error::CookieValueExpired { .. } => {} // Expected error _ => panic!("Expected ConnectionIdExpired error"), } } @@ -300,7 +305,7 @@ mod tests { let result = check(&cookie, fingerprint, min..max).unwrap_err(); match result { - Error::ConnectionIdFromFuture { .. } => {} // Expected error + Error::CookieValueFromFuture { .. } => {} // Expected error _ => panic!("Expected ConnectionIdFromFuture error"), } } diff --git a/src/servers/udp/error.rs b/src/servers/udp/error.rs index 5996cae73..cda562aed 100644 --- a/src/servers/udp/error.rs +++ b/src/servers/udp/error.rs @@ -1,7 +1,7 @@ //! Error types for the UDP server. use std::panic::Location; -use aquatic_udp_protocol::ConnectionId; +use aquatic_udp_protocol::{ConnectionId, RequestParseError}; use derive_more::derive::Display; use thiserror::Error; use torrust_tracker_located_error::LocatedError; @@ -13,17 +13,17 @@ pub struct ConnectionCookie(pub ConnectionId); /// Error returned by the UDP server. #[derive(Error, Debug)] pub enum Error { - #[error("the issue time should be a normal floating point number")] - InvalidCookieIssueTime { invalid_value: f64 }, + #[error("cookie value is not normal: {not_normal_value}")] + CookieValueNotNormal { not_normal_value: f64 }, - #[error("connection id did not produce a normal value")] - ConnectionIdNotNormal { not_normal_value: f64 }, + #[error("cookie value is expired: {expired_value}, expected > {min_value}")] + CookieValueExpired { expired_value: f64, min_value: f64 }, - #[error("connection id produced an expired value")] - ConnectionIdExpired { expired_value: f64, min_value: f64 }, + #[error("cookie value is from future: {future_value}, expected < {max_value}")] + CookieValueFromFuture { future_value: f64, max_value: f64 }, - #[error("connection id produces a future value")] - ConnectionIdFromFuture { future_value: f64, max_value: f64 }, + #[error("error when phrasing request: {request_parse_error:?}")] + RequestParseError { request_parse_error: RequestParseError }, /// Error returned when the domain tracker returns an error. #[error("tracker server error: {source}")] @@ -48,3 +48,9 @@ pub enum Error { #[error("domain tracker requires authentication but is not supported in current UDP implementation. Location: {location}")] TrackerAuthenticationRequired { location: &'static Location<'static> }, } + +impl From for Error { + fn from(request_parse_error: RequestParseError) -> Self { + Self::RequestParseError { request_parse_error } + } +} diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 814ee5e9e..af22b263d 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -1,34 +1,30 @@ //! Handlers for the UDP server. -use std::fmt; use std::hash::{DefaultHasher, Hash, Hasher as _}; use std::net::{IpAddr, SocketAddr}; use std::ops::Range; -use std::panic::Location; use std::sync::Arc; use std::time::Instant; use aquatic_udp_protocol::{ AnnounceInterval, AnnounceRequest, AnnounceResponse, AnnounceResponseFixedData, ConnectRequest, ConnectResponse, - ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfDownloads, NumberOfPeers, Port, Request, Response, ResponsePeer, - ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, + ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfDownloads, NumberOfPeers, Port, Request, RequestParseError, Response, + ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_clock::clock::Time as _; -use torrust_tracker_located_error::DynError; use tracing::{instrument, Level}; use uuid::Uuid; use zerocopy::network_endian::I32; use super::connection_cookie::{check, make}; use super::RawRequest; -use crate::core::{statistics, PeersWanted, ScrapeData, Tracker}; +use crate::core::{statistics, PeersWanted, Tracker}; use crate::servers::udp::error::Error; -use crate::servers::udp::logging::{log_bad_request, log_error_response, log_request, log_response}; use crate::servers::udp::peer_builder; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; use crate::CurrentClock; -#[derive(Debug)] +#[derive(Debug, Clone, PartialEq)] pub(super) struct CookieTimeValues { pub(super) issue_time: f64, pub(super) valid_range: Range, @@ -55,60 +51,40 @@ impl CookieTimeValues { /// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. -#[instrument(skip(udp_request, tracker, local_addr), ret(level = Level::TRACE))] +#[instrument(fields(request_id), skip(udp_request, tracker, cookie_time_values), ret(level = Level::TRACE))] pub(crate) async fn handle_packet( udp_request: RawRequest, tracker: &Tracker, local_addr: SocketAddr, cookie_time_values: CookieTimeValues, ) -> Response { + tracing::Span::current().record("request_id", Uuid::new_v4().to_string()); tracing::debug!("Handling Packets: {udp_request:?}"); let start_time = Instant::now(); - let request_id = RequestId::make(&udp_request); - - match Request::parse_bytes(&udp_request.payload[..udp_request.payload.len()], MAX_SCRAPE_TORRENTS).map_err(|e| { - Error::InternalServer { - message: format!("{e:?}"), - location: Location::caller(), - } - }) { - Ok(request) => { - log_request(&request, &request_id, &local_addr); - - let transaction_id = match &request { - Request::Connect(connect_request) => connect_request.transaction_id, - Request::Announce(announce_request) => announce_request.transaction_id, - Request::Scrape(scrape_request) => scrape_request.transaction_id, - }; - - let response = match handle_request(request, udp_request.from, tracker, cookie_time_values).await { - Ok(response) => response, - Err(e) => handle_error(&e, transaction_id), - }; - - let latency = start_time.elapsed(); - - log_response(&response, &transaction_id, &request_id, &local_addr, latency); - - response - } - Err(e) => { - log_bad_request(&request_id); - - let response = handle_error( - &Error::BadRequest { - source: (Arc::new(e) as DynError).into(), - }, - TransactionId(I32::new(0)), - ); + let response = + match Request::parse_bytes(&udp_request.payload[..udp_request.payload.len()], MAX_SCRAPE_TORRENTS).map_err(Error::from) { + Ok(request) => match handle_request(request, udp_request.from, tracker, cookie_time_values.clone()).await { + Ok(response) => return response, + Err((e, transaction_id)) => { + handle_error( + udp_request.from, + tracker, + cookie_time_values.valid_range.clone(), + &e, + Some(transaction_id), + ) + .await + } + }, + Err(e) => handle_error(udp_request.from, tracker, cookie_time_values.valid_range.clone(), &e, None).await, + }; - log_error_response(&request_id); + let latency = start_time.elapsed(); + tracing::trace!(?latency, "responded"); - response - } - } + response } /// It dispatches the request to the correct handler. @@ -116,23 +92,25 @@ pub(crate) async fn handle_packet( /// # Errors /// /// If a error happens in the `handle_request` function, it will just return the `ServerError`. -#[instrument(skip(request, remote_addr, tracker))] +#[instrument(skip(request, remote_addr, tracker, cookie_time_values))] pub async fn handle_request( request: Request, remote_addr: SocketAddr, tracker: &Tracker, cookie_time_values: CookieTimeValues, -) -> Result { +) -> Result { tracing::trace!("handle request"); match request { Request::Connect(connect_request) => { - handle_connect(remote_addr, &connect_request, tracker, cookie_time_values.issue_time).await + Ok(handle_connect(remote_addr, &connect_request, tracker, cookie_time_values.issue_time).await) } Request::Announce(announce_request) => { handle_announce(remote_addr, &announce_request, tracker, cookie_time_values.valid_range).await } - Request::Scrape(scrape_request) => handle_scrape(remote_addr, &scrape_request, tracker).await, + Request::Scrape(scrape_request) => { + handle_scrape(remote_addr, &scrape_request, tracker, cookie_time_values.valid_range).await + } } } @@ -142,16 +120,18 @@ pub async fn handle_request( /// # Errors /// /// This function does not ever return an error. -#[instrument(skip(tracker), err, ret(level = Level::TRACE))] +#[instrument(fields(transaction_id), skip(tracker), ret(level = Level::TRACE))] pub async fn handle_connect( remote_addr: SocketAddr, request: &ConnectRequest, tracker: &Tracker, cookie_issue_time: f64, -) -> Result { +) -> Response { + tracing::Span::current().record("transaction_id", request.transaction_id.0.to_string()); + tracing::trace!("handle connect"); - let connection_id = make(make_remote_fingerprint(&remote_addr), cookie_issue_time)?; + let connection_id = make(gen_remote_fingerprint(&remote_addr), cookie_issue_time).expect("it should be a normal value"); let response = ConnectResponse { transaction_id: request.transaction_id, @@ -168,7 +148,7 @@ pub async fn handle_connect( } } - Ok(Response::from(response)) + Response::from(response) } /// It handles the `Announce` request. Refer to [`Announce`](crate::servers::udp#announce) @@ -177,38 +157,41 @@ pub async fn handle_connect( /// # Errors /// /// If a error happens in the `handle_announce` function, it will just return the `ServerError`. -#[instrument(skip(tracker), err, ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id, info_hash), skip(tracker), ret(level = Level::TRACE))] pub async fn handle_announce( remote_addr: SocketAddr, - announce_request: &AnnounceRequest, + request: &AnnounceRequest, tracker: &Tracker, cookie_valid_range: Range, -) -> Result { - tracing::trace!("handle announce"); +) -> Result { + tracing::Span::current() + .record("transaction_id", request.transaction_id.0.to_string()) + .record("connection_id", request.connection_id.0.to_string()) + .record("info_hash", InfoHash::from_bytes(&request.info_hash.0).to_hex_string()); - // Authentication - if tracker.requires_authentication() { - return Err(Error::TrackerAuthenticationRequired { - location: Location::caller(), - }); - } + tracing::trace!("handle announce"); check( - &announce_request.connection_id, - make_remote_fingerprint(&remote_addr), + &request.connection_id, + gen_remote_fingerprint(&remote_addr), cookie_valid_range, - )?; + ) + .map_err(|e| (e, request.transaction_id))?; - let info_hash = announce_request.info_hash.into(); + let info_hash = request.info_hash.into(); let remote_client_ip = remote_addr.ip(); // Authorization - tracker.authorize(&info_hash).await.map_err(|e| Error::TrackerError { - source: (Arc::new(e) as Arc).into(), - })?; + tracker + .authorize(&info_hash) + .await + .map_err(|e| Error::TrackerError { + source: (Arc::new(e) as Arc).into(), + }) + .map_err(|e| (e, request.transaction_id))?; - let mut peer = peer_builder::from_request(announce_request, &remote_client_ip); - let peers_wanted: PeersWanted = i32::from(announce_request.peers_wanted.0).into(); + let mut peer = peer_builder::from_request(request, &remote_client_ip); + let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); let response = tracker.announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted); @@ -225,7 +208,7 @@ pub async fn handle_announce( if remote_addr.is_ipv4() { let announce_response = AnnounceResponse { fixed: AnnounceResponseFixedData { - transaction_id: announce_request.transaction_id, + transaction_id: request.transaction_id, announce_interval: AnnounceInterval(I32::new(i64::from(tracker.get_announce_policy().interval) as i32)), leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), @@ -250,7 +233,7 @@ pub async fn handle_announce( } else { let announce_response = AnnounceResponse { fixed: AnnounceResponseFixedData { - transaction_id: announce_request.transaction_id, + transaction_id: request.transaction_id, announce_interval: AnnounceInterval(I32::new(i64::from(tracker.get_announce_policy().interval) as i32)), leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), @@ -281,21 +264,33 @@ pub async fn handle_announce( /// # Errors /// /// This function does not ever return an error. -#[instrument(skip(tracker), err, ret(level = Level::TRACE))] -pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tracker: &Tracker) -> Result { +#[instrument(fields(transaction_id, connection_id), skip(tracker), ret(level = Level::TRACE))] +pub async fn handle_scrape( + remote_addr: SocketAddr, + request: &ScrapeRequest, + tracker: &Tracker, + cookie_valid_range: Range, +) -> Result { + tracing::Span::current() + .record("transaction_id", request.transaction_id.0.to_string()) + .record("connection_id", request.connection_id.0.to_string()); + tracing::trace!("handle scrape"); + check( + &request.connection_id, + gen_remote_fingerprint(&remote_addr), + cookie_valid_range, + ) + .map_err(|e| (e, request.transaction_id))?; + // Convert from aquatic infohashes let mut info_hashes: Vec = vec![]; for info_hash in &request.info_hashes { info_hashes.push((*info_hash).into()); } - let scrape_data = if tracker.requires_authentication() { - ScrapeData::zeroed(&info_hashes) - } else { - tracker.scrape(&info_hashes).await - }; + let scrape_data = tracker.scrape(&info_hashes).await; let mut torrent_stats: Vec = Vec::new(); @@ -332,36 +327,59 @@ pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tra Ok(Response::from(response)) } -fn handle_error(e: &Error, transaction_id: TransactionId) -> Response { - let message = e.to_string(); +#[instrument(fields(transaction_id), skip(tracker), ret(level = Level::TRACE))] +async fn handle_error( + remote_addr: SocketAddr, + tracker: &Tracker, + cookie_valid_range: Range, + e: &Error, + transaction_id: Option, +) -> Response { + tracing::trace!("handle error"); + + let e = if let Error::RequestParseError { request_parse_error } = e { + match request_parse_error { + RequestParseError::Sendable { + connection_id, + transaction_id, + err, + } => { + if let Err(e) = check(connection_id, gen_remote_fingerprint(&remote_addr), cookie_valid_range) { + (e.to_string(), Some(*transaction_id)) + } else { + ((*err).to_string(), Some(*transaction_id)) + } + } + RequestParseError::Unsendable { err } => (err.to_string(), transaction_id), + } + } else { + (e.to_string(), transaction_id) + }; + + if e.1.is_some() { + // send stats event + match remote_addr { + SocketAddr::V4(_) => { + tracker.send_stats_event(statistics::Event::Udp4Error).await; + } + SocketAddr::V6(_) => { + tracker.send_stats_event(statistics::Event::Udp6Error).await; + } + } + } + Response::from(ErrorResponse { - transaction_id, - message: message.into(), + transaction_id: e.1.unwrap_or(TransactionId(I32::new(0))), + message: e.0.into(), }) } -fn make_remote_fingerprint(remote_addr: &SocketAddr) -> u64 { +fn gen_remote_fingerprint(remote_addr: &SocketAddr) -> u64 { let mut state = DefaultHasher::new(); remote_addr.hash(&mut state); state.finish() } -/// An identifier for a request. -#[derive(Debug, Clone)] -pub struct RequestId(Uuid); - -impl RequestId { - fn make(_request: &RawRequest) -> RequestId { - RequestId(Uuid::new_v4()) - } -} - -impl fmt::Display for RequestId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.0) - } -} - #[cfg(test)] mod tests { @@ -375,7 +393,7 @@ mod tests { use torrust_tracker_primitives::peer; use torrust_tracker_test_helpers::configuration; - use super::make_remote_fingerprint; + use super::gen_remote_fingerprint; use crate::core::services::tracker_factory; use crate::core::Tracker; use crate::CurrentClock; @@ -392,10 +410,6 @@ mod tests { initialized_tracker(&configuration::ephemeral_public()) } - fn private_tracker() -> Arc { - initialized_tracker(&configuration::ephemeral_private()) - } - fn whitelisted_tracker() -> Arc { initialized_tracker(&configuration::ephemeral_listed()) } @@ -409,7 +423,7 @@ mod tests { } fn sample_ipv4_remote_addr_fingerprint() -> u64 { - make_remote_fingerprint(&sample_ipv4_socket_address()) + gen_remote_fingerprint(&sample_ipv4_socket_address()) } fn sample_ipv6_remote_addr() -> SocketAddr { @@ -417,7 +431,7 @@ mod tests { } fn sample_ipv6_remote_addr_fingerprint() -> u64 { - make_remote_fingerprint(&sample_ipv6_socket_address()) + gen_remote_fingerprint(&sample_ipv6_socket_address()) } fn sample_ipv4_socket_address() -> SocketAddr { @@ -527,9 +541,7 @@ mod tests { transaction_id: TransactionId(0i32.into()), }; - let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker(), sample_issue_time()) - .await - .unwrap(); + let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker(), sample_issue_time()).await; assert_eq!( response, @@ -546,9 +558,7 @@ mod tests { transaction_id: TransactionId(0i32.into()), }; - let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker(), sample_issue_time()) - .await - .unwrap(); + let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker(), sample_issue_time()).await; assert_eq!( response, @@ -565,9 +575,7 @@ mod tests { transaction_id: TransactionId(0i32.into()), }; - let response = handle_connect(sample_ipv6_remote_addr(), &request, &public_tracker(), sample_issue_time()) - .await - .unwrap(); + let response = handle_connect(sample_ipv6_remote_addr(), &request, &public_tracker(), sample_issue_time()).await; assert_eq!( response, @@ -604,8 +612,7 @@ mod tests { &torrent_tracker, sample_issue_time(), ) - .await - .unwrap(); + .await; } #[tokio::test] @@ -632,8 +639,7 @@ mod tests { &torrent_tracker, sample_issue_time(), ) - .await - .unwrap(); + .await; } } @@ -726,8 +732,8 @@ mod tests { use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - make_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, - sample_issue_time, tracker_configuration, TorrentPeerBuilder, + gen_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, sample_issue_time, + tracker_configuration, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; @@ -743,7 +749,7 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip) @@ -769,7 +775,7 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); let response = handle_announce(remote_addr, &request, &public_tracker(), sample_cookie_valid_range()) @@ -810,7 +816,7 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V4(remote_client_ip), remote_client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(peer_address) @@ -845,7 +851,7 @@ mod tests { async fn announce_a_new_peer_using_ipv4(tracker: Arc) -> Response { let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) @@ -909,7 +915,7 @@ mod tests { use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - make_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_issue_time, TorrentPeerBuilder, + gen_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_issue_time, TorrentPeerBuilder, }; #[tokio::test] @@ -924,7 +930,7 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip) @@ -965,7 +971,7 @@ mod tests { use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - make_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, sample_issue_time, + gen_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, sample_issue_time, tracker_configuration, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; @@ -983,7 +989,7 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip_v4) @@ -1012,7 +1018,7 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), 8080); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); let response = handle_announce(remote_addr, &request, &public_tracker(), sample_cookie_valid_range()) @@ -1053,7 +1059,7 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V6(remote_client_ip), remote_client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(peer_address) @@ -1091,7 +1097,7 @@ mod tests { let client_port = 8080; let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) @@ -1138,7 +1144,7 @@ mod tests { let remote_addr = sample_ipv6_remote_addr(); let announce_request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); handle_announce(remote_addr, &announce_request, &tracker, sample_cookie_valid_range()) @@ -1158,7 +1164,7 @@ mod tests { use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - make_remote_fingerprint, sample_cookie_valid_range, sample_issue_time, TrackerConfigurationBuilder, + gen_remote_fingerprint, sample_cookie_valid_range, sample_issue_time, TrackerConfigurationBuilder, }; #[tokio::test] @@ -1181,7 +1187,7 @@ mod tests { let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip_v4) @@ -1218,11 +1224,13 @@ mod tests { TransactionId, }; - use super::{make_remote_fingerprint, TorrentPeerBuilder}; + use super::{gen_remote_fingerprint, TorrentPeerBuilder}; use crate::core::{self}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{public_tracker, sample_ipv4_remote_addr, sample_issue_time}; + use crate::servers::udp::handlers::tests::{ + public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, sample_issue_time, + }; fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { TorrentScrapeStatistics { @@ -1240,12 +1248,14 @@ mod tests { let info_hashes = vec![info_hash]; let request = ScrapeRequest { - connection_id: make(make_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap(), + connection_id: make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap(), transaction_id: TransactionId(0i32.into()), info_hashes, }; - let response = handle_scrape(remote_addr, &request, &public_tracker()).await.unwrap(); + let response = handle_scrape(remote_addr, &request, &public_tracker(), sample_cookie_valid_range()) + .await + .unwrap(); let expected_torrent_stats = vec![zeroed_torrent_statistics()]; @@ -1274,7 +1284,7 @@ mod tests { let info_hashes = vec![*info_hash]; ScrapeRequest { - connection_id: make(make_remote_fingerprint(remote_addr), sample_issue_time()).unwrap(), + connection_id: make(gen_remote_fingerprint(remote_addr), sample_issue_time()).unwrap(), transaction_id: TransactionId::new(0i32), info_hashes, } @@ -1288,7 +1298,9 @@ mod tests { let request = build_scrape_request(&remote_addr, &info_hash); - handle_scrape(remote_addr, &request, &tracker).await.unwrap() + handle_scrape(remote_addr, &request, &tracker, sample_cookie_valid_range()) + .await + .unwrap() } fn match_scrape_response(response: Response) -> Option { @@ -1320,45 +1332,6 @@ mod tests { } } - mod with_a_private_tracker { - - use aquatic_udp_protocol::InfoHash; - - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::scrape_request::{ - add_a_sample_seeder_and_scrape, build_scrape_request, match_scrape_response, zeroed_torrent_statistics, - }; - use crate::servers::udp::handlers::tests::{private_tracker, sample_ipv4_remote_addr}; - - #[tokio::test] - async fn should_return_zeroed_statistics_when_the_tracker_does_not_have_the_requested_torrent() { - let tracker = private_tracker(); - - let remote_addr = sample_ipv4_remote_addr(); - let non_existing_info_hash = InfoHash([0u8; 20]); - - let request = build_scrape_request(&remote_addr, &non_existing_info_hash); - - let torrent_stats = match_scrape_response(handle_scrape(remote_addr, &request, &tracker).await.unwrap()).unwrap(); - - let expected_torrent_stats = vec![zeroed_torrent_statistics()]; - - assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); - } - - #[tokio::test] - async fn should_return_zeroed_statistics_when_the_tracker_has_the_requested_torrent_because_authenticated_requests_are_not_supported_in_udp_tracker( - ) { - let tracker = private_tracker(); - - let torrent_stats = match_scrape_response(add_a_sample_seeder_and_scrape(tracker.clone()).await).unwrap(); - - let expected_torrent_stats = vec![zeroed_torrent_statistics()]; - - assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); - } - } - mod with_a_whitelisted_tracker { use aquatic_udp_protocol::{InfoHash, NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; @@ -1366,7 +1339,7 @@ mod tests { use crate::servers::udp::handlers::tests::scrape_request::{ add_a_seeder, build_scrape_request, match_scrape_response, zeroed_torrent_statistics, }; - use crate::servers::udp::handlers::tests::{sample_ipv4_remote_addr, whitelisted_tracker}; + use crate::servers::udp::handlers::tests::{sample_cookie_valid_range, sample_ipv4_remote_addr, whitelisted_tracker}; #[tokio::test] async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { @@ -1381,7 +1354,12 @@ mod tests { let request = build_scrape_request(&remote_addr, &info_hash); - let torrent_stats = match_scrape_response(handle_scrape(remote_addr, &request, &tracker).await.unwrap()).unwrap(); + let torrent_stats = match_scrape_response( + handle_scrape(remote_addr, &request, &tracker, sample_cookie_valid_range()) + .await + .unwrap(), + ) + .unwrap(); let expected_torrent_stats = vec![TorrentScrapeStatistics { seeders: NumberOfPeers(1.into()), @@ -1403,7 +1381,12 @@ mod tests { let request = build_scrape_request(&remote_addr, &info_hash); - let torrent_stats = match_scrape_response(handle_scrape(remote_addr, &request, &tracker).await.unwrap()).unwrap(); + let torrent_stats = match_scrape_response( + handle_scrape(remote_addr, &request, &tracker, sample_cookie_valid_range()) + .await + .unwrap(), + ) + .unwrap(); let expected_torrent_stats = vec![zeroed_torrent_statistics()]; @@ -1416,7 +1399,7 @@ mod tests { let info_hashes = vec![info_hash]; ScrapeRequest { - connection_id: make(make_remote_fingerprint(remote_addr), sample_issue_time()).unwrap(), + connection_id: make(gen_remote_fingerprint(remote_addr), sample_issue_time()).unwrap(), transaction_id: TransactionId(0i32.into()), info_hashes, } @@ -1431,7 +1414,9 @@ mod tests { use super::sample_scrape_request; use crate::core::{self, statistics}; use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{sample_ipv4_remote_addr, tracker_configuration}; + use crate::servers::udp::handlers::tests::{ + sample_cookie_valid_range, sample_ipv4_remote_addr, tracker_configuration, + }; #[tokio::test] async fn should_send_the_upd4_scrape_event() { @@ -1453,9 +1438,14 @@ mod tests { .unwrap(), ); - handle_scrape(remote_addr, &sample_scrape_request(&remote_addr), &tracker) - .await - .unwrap(); + handle_scrape( + remote_addr, + &sample_scrape_request(&remote_addr), + &tracker, + sample_cookie_valid_range(), + ) + .await + .unwrap(); } } @@ -1468,7 +1458,9 @@ mod tests { use super::sample_scrape_request; use crate::core::{self, statistics}; use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{sample_ipv6_remote_addr, tracker_configuration}; + use crate::servers::udp::handlers::tests::{ + sample_cookie_valid_range, sample_ipv6_remote_addr, tracker_configuration, + }; #[tokio::test] async fn should_send_the_upd6_scrape_event() { @@ -1490,9 +1482,14 @@ mod tests { .unwrap(), ); - handle_scrape(remote_addr, &sample_scrape_request(&remote_addr), &tracker) - .await - .unwrap(); + handle_scrape( + remote_addr, + &sample_scrape_request(&remote_addr), + &tracker, + sample_cookie_valid_range(), + ) + .await + .unwrap(); } } } diff --git a/src/servers/udp/logging.rs b/src/servers/udp/logging.rs deleted file mode 100644 index a61668e83..000000000 --- a/src/servers/udp/logging.rs +++ /dev/null @@ -1,87 +0,0 @@ -//! Logging for UDP Tracker requests and responses. - -use std::net::SocketAddr; -use std::time::Duration; - -use aquatic_udp_protocol::{Request, Response, TransactionId}; -use bittorrent_primitives::info_hash::InfoHash; - -use super::handlers::RequestId; -use crate::servers::udp::UDP_TRACKER_LOG_TARGET; - -pub fn log_request(request: &Request, request_id: &RequestId, server_socket_addr: &SocketAddr) { - let action = map_action_name(request); - - match &request { - Request::Connect(connect_request) => { - let transaction_id = connect_request.transaction_id; - let transaction_id_str = transaction_id.0.to_string(); - - tracing::span!( - target: UDP_TRACKER_LOG_TARGET, - tracing::Level::INFO, "request", server_socket_addr = %server_socket_addr, action = %action, transaction_id = %transaction_id_str, request_id = %request_id); - } - Request::Announce(announce_request) => { - let transaction_id = announce_request.transaction_id; - let transaction_id_str = transaction_id.0.to_string(); - let connection_id_str = announce_request.connection_id.0.to_string(); - let info_hash_str = InfoHash::from_bytes(&announce_request.info_hash.0).to_hex_string(); - - tracing::span!( - target: UDP_TRACKER_LOG_TARGET, - tracing::Level::INFO, "request", server_socket_addr = %server_socket_addr, action = %action, transaction_id = %transaction_id_str, request_id = %request_id, connection_id = %connection_id_str, info_hash = %info_hash_str); - } - Request::Scrape(scrape_request) => { - let transaction_id = scrape_request.transaction_id; - let transaction_id_str = transaction_id.0.to_string(); - let connection_id_str = scrape_request.connection_id.0.to_string(); - - tracing::span!( - target: UDP_TRACKER_LOG_TARGET, - tracing::Level::INFO, - "request", - server_socket_addr = %server_socket_addr, - action = %action, - transaction_id = %transaction_id_str, - request_id = %request_id, - connection_id = %connection_id_str); - } - }; -} - -fn map_action_name(udp_request: &Request) -> String { - match udp_request { - Request::Connect(_connect_request) => "CONNECT".to_owned(), - Request::Announce(_announce_request) => "ANNOUNCE".to_owned(), - Request::Scrape(_scrape_request) => "SCRAPE".to_owned(), - } -} - -pub fn log_response( - _response: &Response, - transaction_id: &TransactionId, - request_id: &RequestId, - server_socket_addr: &SocketAddr, - latency: Duration, -) { - tracing::span!( - target: UDP_TRACKER_LOG_TARGET, - tracing::Level::INFO, - "response", - server_socket_addr = %server_socket_addr, - transaction_id = %transaction_id.0.to_string(), - request_id = %request_id, - latency_ms = %latency.as_millis()); -} - -pub fn log_bad_request(request_id: &RequestId) { - tracing::span!( - target: UDP_TRACKER_LOG_TARGET, - tracing::Level::INFO, "bad request", request_id = %request_id); -} - -pub fn log_error_response(request_id: &RequestId) { - tracing::span!( - target: UDP_TRACKER_LOG_TARGET, - tracing::Level::INFO, "response", request_id = %request_id); -} diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index d41bc8b3f..9b4d90c89 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -641,7 +641,6 @@ use std::net::SocketAddr; pub mod connection_cookie; pub mod error; pub mod handlers; -pub mod logging; pub mod peer_builder; pub mod server; diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 348446876..c8bac8098 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -30,7 +30,9 @@ impl Launcher { /// # Panics /// /// It panics if unable to bind to udp socket, and get the address from the udp socket. - /// It also panics if unable to send address of socket. + /// It panics if unable to send address of socket. + /// It panics if the udp server is loaded when the tracker is private. + /// #[instrument(skip(tracker, bind_to, tx_start, rx_halt))] pub async fn run_with_graceful_shutdown( tracker: Arc, @@ -41,6 +43,11 @@ impl Launcher { ) { tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting on: {bind_to}"); + if tracker.requires_authentication() { + tracing::error!("udp services cannot be used for private trackers"); + panic!("it should not use udp if using authentication"); + } + let socket = tokio::time::timeout(Duration::from_millis(5000), BoundSocket::new(bind_to)) .await .expect("it should bind to the socket within five seconds"); diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index 2c8e8d6a5..463dc563e 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -43,9 +43,11 @@ async fn should_allow_getting_tracker_statistics() { udp4_connections_handled: 0, udp4_announces_handled: 0, udp4_scrapes_handled: 0, + udp4_errors_handled: 0, udp6_connections_handled: 0, udp6_announces_handled: 0, udp6_scrapes_handled: 0, + udp6_errors_handled: 0, }, ) .await; diff --git a/tests/servers/udp/asserts.rs b/tests/servers/udp/asserts.rs index bf8fb6728..37c848e06 100644 --- a/tests/servers/udp/asserts.rs +++ b/tests/servers/udp/asserts.rs @@ -1,9 +1,9 @@ use aquatic_udp_protocol::{Response, TransactionId}; -pub fn is_error_response(response: &Response, error_message: &str) -> bool { +pub fn get_error_response_message(response: &Response) -> Option { match response { - Response::Error(error_response) => error_response.message.starts_with(error_message), - _ => false, + Response::Error(error_response) => Some(error_response.message.to_string()), + _ => None, } } diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 73f7ce368..b12a8a900 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -13,7 +13,7 @@ use torrust_tracker_test_helpers::configuration; use tracing::level_filters::LevelFilter; use crate::common::logging::{tracing_stderr_init, INIT}; -use crate::servers::udp::asserts::is_error_response; +use crate::servers::udp::asserts::get_error_response_message; use crate::servers::udp::Started; fn empty_udp_request() -> [u8; MAX_PACKET_SIZE] { @@ -64,7 +64,7 @@ async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_req let response = Response::parse_bytes(&response, true).unwrap(); - assert!(is_error_response(&response, "bad request")); + assert_eq!(get_error_response_message(&response).unwrap(), "Protocol identifier missing"); env.stop().await; } From 66a8648416d2e84d57d848939420c6cab69ee080 Mon Sep 17 00:00:00 2001 From: Power2All Date: Wed, 27 Nov 2024 15:07:58 +0000 Subject: [PATCH 0525/1297] fix: [#325] windows compiling --- Cargo.lock | 124 +---------------------------------------------------- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 124 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d07ba62f..6ece5ab7d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -357,33 +357,6 @@ version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" -[[package]] -name = "aws-lc-rs" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdd82dba44d209fddb11c190e0a94b78651f95299598e472215667417a03ff1d" -dependencies = [ - "aws-lc-sys", - "mirai-annotations", - "paste", - "zeroize", -] - -[[package]] -name = "aws-lc-sys" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df7a4168111d7eb622a31b214057b8509c0a7e1794f44c546d742330dc793972" -dependencies = [ - "bindgen 0.69.5", - "cc", - "cmake", - "dunce", - "fs_extra", - "libc", - "paste", -] - [[package]] name = "axum" version = "0.7.7" @@ -555,29 +528,6 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" -[[package]] -name = "bindgen" -version = "0.69.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088" -dependencies = [ - "bitflags", - "cexpr", - "clang-sys", - "itertools 0.12.1", - "lazy_static", - "lazycell", - "log", - "prettyplease", - "proc-macro2", - "quote", - "regex", - "rustc-hash", - "shlex", - "syn 2.0.87", - "which", -] - [[package]] name = "bindgen" version = "0.70.1" @@ -1254,12 +1204,6 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" -[[package]] -name = "dunce" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" - [[package]] name = "either" version = "1.13.0" @@ -1481,12 +1425,6 @@ dependencies = [ "syn 2.0.87", ] -[[package]] -name = "fs_extra" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" - [[package]] name = "funty" version = "2.0.0" @@ -1743,15 +1681,6 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" -[[package]] -name = "home" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" -dependencies = [ - "windows-sys 0.52.0", -] - [[package]] name = "http" version = "1.1.0" @@ -2117,15 +2046,6 @@ dependencies = [ "either", ] -[[package]] -name = "itertools" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.13.0" @@ -2174,12 +2094,6 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" -[[package]] -name = "lazycell" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" - [[package]] name = "libc" version = "0.2.162" @@ -2321,12 +2235,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "mirai-annotations" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9be0862c1b3f26a88803c4a49de6889c10e608b3ee9344e6ef5b45fb37ad3d1" - [[package]] name = "mockall" version = "0.13.0" @@ -2413,7 +2321,7 @@ checksum = "478b0ff3f7d67b79da2b96f56f334431aef65e15ba4b29dd74a4236e29582bdc" dependencies = [ "base64 0.21.7", "bigdecimal", - "bindgen 0.70.1", + "bindgen", "bitflags", "bitvec", "btoi", @@ -2655,12 +2563,6 @@ dependencies = [ "windows-targets", ] -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - [[package]] name = "pear" version = "0.2.9" @@ -2877,16 +2779,6 @@ dependencies = [ "termtree", ] -[[package]] -name = "prettyplease" -version = "0.2.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64d1ec885c64d0457d564db4ec299b2dae3f9c02808b8ad9c3a089c591b18033" -dependencies = [ - "proc-macro2", - "syn 2.0.87", -] - [[package]] name = "proc-macro-crate" version = "3.2.0" @@ -3318,7 +3210,6 @@ version = "0.23.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eee87ff5d9b36712a58574e12e9f0ea80f915a5b0ac518d322b24a465617925e" dependencies = [ - "aws-lc-rs", "once_cell", "rustls-pki-types", "rustls-webpki", @@ -3347,7 +3238,6 @@ version = "0.102.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" dependencies = [ - "aws-lc-rs", "ring", "rustls-pki-types", "untrusted", @@ -4556,18 +4446,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "which" -version = "4.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" -dependencies = [ - "either", - "home", - "once_cell", - "rustix", -] - [[package]] name = "winapi" version = "0.3.9" diff --git a/Cargo.toml b/Cargo.toml index 35b1ac9a7..0a40f4917 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,7 +35,7 @@ aquatic_udp_protocol = "0" axum = { version = "0", features = ["macros"] } axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } -axum-server = { version = "0", features = ["tls-rustls"] } +axum-server = { version = "0", features = ["tls-rustls-no-provider"] } bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } blowfish = "0" From 38baaea557fc4e045ab9eac7af70fa07543e6ba9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 27 Nov 2024 15:59:35 +0000 Subject: [PATCH 0526/1297] ci: [#1099] Add a new job to the testing workflow to test compilation in different OSs --- .github/workflows/testing.yaml | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 124b13b5a..74dc254ef 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -85,6 +85,27 @@ jobs: name: Check Unused Dependencies run: cargo machete + build: + name: Build on ${{ matrix.os }} (${{ matrix.toolchain }}) + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + toolchain: [nightly, stable] + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + + - name: Build project + run: cargo build --verbose unit: name: Units From c3ded10ec1d2716b78ac619ee36798f54e15c03c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 29 Nov 2024 15:49:09 +0000 Subject: [PATCH 0527/1297] chore(deps): udpate dependencies --- Cargo.lock | 250 ++++++++++++++++++++++++++++------------------------- 1 file changed, 134 insertions(+), 116 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6ece5ab7d..fe8d93ff8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -219,9 +219,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.17" +version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cb8f1d480b0ea3783ab015936d2a55c87e219676f0c0b7dec61494043f21857" +checksum = "df895a515f70646414f4b45c0b79082783b80552b373a68283012928df56f522" dependencies = [ "brotli", "flate2", @@ -333,7 +333,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -359,9 +359,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "axum" -version = "0.7.7" +version = "0.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "504e3947307ac8326a5437504c517c4b56716c9d98fac0028c2acc7ca47d70ae" +checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" dependencies = [ "async-trait", "axum-core", @@ -384,7 +384,7 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", - "sync_wrapper 1.0.1", + "sync_wrapper 1.0.2", "tokio", "tower 0.5.1", "tower-layer", @@ -418,7 +418,7 @@ dependencies = [ "mime", "pin-project-lite", "rustversion", - "sync_wrapper 1.0.1", + "sync_wrapper 1.0.2", "tower-layer", "tower-service", "tracing", @@ -426,25 +426,26 @@ dependencies = [ [[package]] name = "axum-extra" -version = "0.9.4" +version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73c3220b188aea709cf1b6c5f9b01c3bd936bb08bd2b5184a12b35ac8131b1f9" +checksum = "c794b30c904f0a1c2fb7740f7df7f7972dfaa14ef6f57cb6178dc63e5dca2f04" dependencies = [ "axum", "axum-core", "bytes", + "fastrand", "futures-util", "http", "http-body", "http-body-util", "mime", + "multer", "pin-project-lite", "serde", "serde_html_form", "tower 0.5.1", "tower-layer", "tower-service", - "tracing", ] [[package]] @@ -455,7 +456,7 @@ checksum = "57d123550fa8d071b7255cb0cc04dc302baa6c8c4a79f55701552684d8399bce" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -543,7 +544,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -653,7 +654,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -722,9 +723,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.19.0" +version = "1.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8334215b81e418a0a7bdb8ef0849474f40bb10c8b71f1c4ed315cff49f32494d" +checksum = "8b37c88a63ffd85d15b406896cc343916d7cf57838a847b3a6f2ca5d39a5695a" [[package]] name = "byteorder" @@ -734,9 +735,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.8.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ac0150caa2ae65ca5bd83f25c7de183dea78d4d366469f148435e2acfbad0da" +checksum = "325918d6fe32f23b19878fe4b34794ae41fc19ddbe53b10571a4874d44ffd39b" [[package]] name = "camino" @@ -764,9 +765,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd9de9f2205d5ef3fd67e685b0df337994ddd4495e2a28d185500d0e1edfea47" +checksum = "f34d93e62b03caf570cccc334cbc6c2fceca82f39211051345108adcba3eebdc" dependencies = [ "jobserver", "libc", @@ -886,7 +887,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -897,9 +898,9 @@ checksum = "afb84c814227b90d6895e01398aee0d8033c00e7466aca416fb6a8e0eb19d8a7" [[package]] name = "cmake" -version = "0.1.51" +version = "0.1.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb1e43aa7fd152b1f968787f7dbcdeb306d1867ff373c69955211876c053f91a" +checksum = "c682c223677e0e5b6b7f63a64b9351844c3f1b1678a68b7ee617e30fb082620e" dependencies = [ "cc", ] @@ -950,9 +951,9 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpufeatures" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ca741a962e1b0bff6d724a1a0958b686406e853bb14061f218562e1896f95e6" +checksum = "16b80225097f2e5ae4e7179dd2266824648f3e2f49d9134d584b76389d31c4c3" dependencies = [ "libc", ] @@ -1107,7 +1108,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -1118,7 +1119,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -1162,7 +1163,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", "unicode-xid", ] @@ -1174,7 +1175,7 @@ checksum = "65f152f4b8559c4da5d574bafc7af85454d706b4c5fe8b530d508cacbb6807ea" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -1195,7 +1196,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -1237,12 +1238,12 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.9" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" +checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -1398,7 +1399,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -1410,7 +1411,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -1422,7 +1423,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -1500,7 +1501,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -1586,9 +1587,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524e8ac6999421f49a846c2d4411f337e53497d8ec55d67753beffa43c5d9205" +checksum = "ccae279728d634d083c00f6099cb58f01cc99c145b84b8be2f6c74618d79922e" dependencies = [ "atomic-waker", "bytes", @@ -1633,9 +1634,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.15.1" +version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a9bfc1af68b1726ea47d3d5109de126281def866b33970e10fbab11b5dafab3" +checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289" dependencies = [ "allocator-api2", "equivalent", @@ -1729,9 +1730,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbbff0a806a4728c99295b254c8838933b5b082d75e3cb70c8dab21fdfbcfa9a" +checksum = "97818827ef4f364230e16705d4706e2897df2bb60617d6ca15d598025a3c481f" dependencies = [ "bytes", "futures-channel", @@ -1938,7 +1939,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -1986,7 +1987,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" dependencies = [ "equivalent", - "hashbrown 0.15.1", + "hashbrown 0.15.2", "serde", ] @@ -2057,9 +2058,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.11" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" +checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" [[package]] name = "jobserver" @@ -2096,9 +2097,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.162" +version = "0.2.167" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18d287de67fe55fd7e1581fe933d965a5a9477b38e949cfa9f8574ef01506398" +checksum = "09d6582e104315a817dff97f75133544b2e094ee22447d2acf4a74e189ba06fc" [[package]] name = "libloading" @@ -2146,9 +2147,9 @@ checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "litemap" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704" +checksum = "4ee93343901ab17bd981295f2cf0026d4ad018c7c31ba84549a4ddbb47a45104" [[package]] name = "local-ip-address" @@ -2187,7 +2188,7 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" dependencies = [ - "hashbrown 0.15.1", + "hashbrown 0.15.2", ] [[package]] @@ -2237,9 +2238,9 @@ dependencies = [ [[package]] name = "mockall" -version = "0.13.0" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4c28b3fb6d753d28c20e826cd46ee611fda1cf3cde03a443a974043247c065a" +checksum = "39a6bfcc6c8c7eed5ee98b9c3e33adc726054389233e201c95dab2d41a3839d2" dependencies = [ "cfg-if", "downcast", @@ -2251,14 +2252,31 @@ dependencies = [ [[package]] name = "mockall_derive" -version = "0.13.0" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "341014e7f530314e9a1fdbc7400b244efea7122662c96bfa248c31da5bfb2020" +checksum = "25ca3004c2efe9011bd4e461bd8256445052b9615405b4f7ea43fc8ca5c20898" dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", +] + +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", ] [[package]] @@ -2308,7 +2326,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", "termcolor", "thiserror 1.0.69", ] @@ -2507,7 +2525,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -2583,7 +2601,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -2657,7 +2675,7 @@ checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -2734,9 +2752,9 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc9c68a3f6da06753e9335d63e27f6b9754dd1920d941135b7ea8224f141adb2" +checksum = "280dc24453071f1b63954171985a0b0d30058d287960968b9b2aca264c8d4ee6" [[package]] name = "powerfmt" @@ -2807,14 +2825,14 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] name = "proc-macro2" -version = "1.0.89" +version = "1.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" +checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" dependencies = [ "unicode-ident", ] @@ -2827,7 +2845,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", "version_check", "yansi", ] @@ -3044,7 +3062,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "sync_wrapper 1.0.1", + "sync_wrapper 1.0.2", "system-configuration", "tokio", "tokio-native-tls", @@ -3136,7 +3154,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.87", + "syn 2.0.89", "unicode-ident", ] @@ -3193,9 +3211,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.40" +version = "0.38.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99e4ea3e1cdc4b559b8e5650f9c8e5998e3e5c1343b4eaf034565f32318d63c0" +checksum = "d7f649912bc1495e167a6edee79151c84b1bad49748cb4f1f1167f459f6224f6" dependencies = [ "bitflags", "errno", @@ -3206,9 +3224,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.16" +version = "0.23.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eee87ff5d9b36712a58574e12e9f0ea80f915a5b0ac518d322b24a465617925e" +checksum = "934b404430bb06b3fae2cba809eb45a1ab1aecd64491213d7c3301b88393f8d1" dependencies = [ "once_cell", "rustls-pki-types", @@ -3272,9 +3290,9 @@ checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" [[package]] name = "schannel" -version = "0.1.26" +version = "0.1.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01227be5826fa0690321a2ba6c5cd57a19cf3f6a09e76973b58e61de6ab9d1c1" +checksum = "1f29ebaa345f945cec9fbbc532eb307f0fdad8161f281b6369539c8d84876b3d" dependencies = [ "windows-sys 0.59.0", ] @@ -3365,7 +3383,7 @@ checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -3383,9 +3401,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.132" +version = "1.0.133" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d726bfaff4b320266d395898905d0eba0345aae23b54aee3a737e260fd46db03" +checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" dependencies = [ "indexmap 2.6.0", "itoa", @@ -3412,7 +3430,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -3463,7 +3481,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -3541,9 +3559,9 @@ checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "socket2" -version = "0.5.7" +version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" +checksum = "c970269d99b64e60ec3bd6ad27270092a5394c4e309314b18ae3fe575695fbe8" dependencies = [ "libc", "windows-sys 0.52.0", @@ -3602,9 +3620,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.87" +version = "2.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" +checksum = "44d46482f1c1c87acd84dea20c1bf5ebff4c757009ed6bf19cfd36fb10e92c4e" dependencies = [ "proc-macro2", "quote", @@ -3619,9 +3637,9 @@ checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" [[package]] name = "sync_wrapper" -version = "1.0.1" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" dependencies = [ "futures-core", ] @@ -3634,7 +3652,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -3735,7 +3753,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -3746,7 +3764,7 @@ checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -3850,7 +3868,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] @@ -4128,9 +4146,9 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8437150ab6bbc8c5f0f519e3d5ed4aa883a83dd4cdd3d1b21f9482936046cb97" +checksum = "403fa3b783d4b626a8ad51d766ab03cb6d2dbfc46b1c5d4448395e6628dc9697" dependencies = [ "async-compression", "bitflags", @@ -4161,9 +4179,9 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tracing" -version = "0.1.40" +version = "0.1.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" +checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" dependencies = [ "log", "pin-project-lite", @@ -4173,20 +4191,20 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.27" +version = "0.1.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" +checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] name = "tracing-core" -version = "0.1.32" +version = "0.1.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" +checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" dependencies = [ "once_cell", "valuable", @@ -4264,9 +4282,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.13" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" +checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" [[package]] name = "unicode-xid" @@ -4282,9 +4300,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.3" +version = "2.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d157f1b96d14500ffdc1f10ba712e780825526c03d9a49b4d0324b0d9113ada" +checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60" dependencies = [ "form_urlencoded", "idna", @@ -4391,7 +4409,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", "wasm-bindgen-shared", ] @@ -4425,7 +4443,7 @@ checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4636,9 +4654,9 @@ checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" [[package]] name = "yoke" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5" +checksum = "120e6aef9aa629e3d4f52dc8cc43a015c7724194c97dfaf45180d2daf2b77f40" dependencies = [ "serde", "stable_deref_trait", @@ -4648,13 +4666,13 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95" +checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", "synstructure", ] @@ -4676,27 +4694,27 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] name = "zerofrom" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" +checksum = "cff3ee08c995dee1859d998dea82f7374f2826091dd9cd47def953cae446cd2e" dependencies = [ "zerofrom-derive", ] [[package]] name = "zerofrom-derive" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5" +checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", "synstructure", ] @@ -4725,7 +4743,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.87", + "syn 2.0.89", ] [[package]] From 555d5b8522eca6e2b097cc4c88436598b39d1646 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 29 Nov 2024 16:17:42 +0000 Subject: [PATCH 0528/1297] fix: [#1097] by extracting duplicate module --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 12 + Cargo.toml | 1 + packages/http-protocol/Cargo.toml | 21 + packages/http-protocol/LICENSE | 661 ++++++++++++++++++ packages/http-protocol/README.md | 11 + packages/http-protocol/src/lib.rs | 2 + .../http-protocol/src}/percent_encoding.rs | 6 +- packages/tracker-client/Cargo.toml | 1 + packages/tracker-client/src/http/mod.rs | 1 - .../tracker-client/src/http/url_encoding.rs | 132 ---- src/servers/http/mod.rs | 1 - src/servers/http/v1/requests/announce.rs | 2 +- src/servers/http/v1/requests/scrape.rs | 2 +- 14 files changed, 715 insertions(+), 139 deletions(-) create mode 100644 packages/http-protocol/Cargo.toml create mode 100644 packages/http-protocol/LICENSE create mode 100644 packages/http-protocol/README.md create mode 100644 packages/http-protocol/src/lib.rs rename {src/servers/http => packages/http-protocol/src}/percent_encoding.rs (94%) delete mode 100644 packages/tracker-client/src/http/url_encoding.rs diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 59913d476..1e0f59b43 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -55,6 +55,7 @@ jobs: env: CARGO_REGISTRY_TOKEN: "${{ secrets.TORRUST_UPDATE_CARGO_REGISTRY_TOKEN }}" run: | + cargo publish -p bittorrent-http-protocol cargo publish -p bittorrent-tracker-client cargo publish -p torrust-tracker cargo publish -p torrust-tracker-client diff --git a/Cargo.lock b/Cargo.lock index fe8d93ff8..2931b0f8f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -553,6 +553,16 @@ version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" +[[package]] +name = "bittorrent-http-protocol" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "bittorrent-primitives", + "percent-encoding", + "torrust-tracker-primitives", +] + [[package]] name = "bittorrent-primitives" version = "0.1.0" @@ -572,6 +582,7 @@ name = "bittorrent-tracker-client" version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", + "bittorrent-http-protocol", "bittorrent-primitives", "derive_more", "hyper", @@ -3949,6 +3960,7 @@ dependencies = [ "axum-client-ip", "axum-extra", "axum-server", + "bittorrent-http-protocol", "bittorrent-primitives", "bittorrent-tracker-client", "blowfish", diff --git a/Cargo.toml b/Cargo.toml index 0a40f4917..f512dca92 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ axum = { version = "0", features = ["macros"] } axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls-no-provider"] } +bittorrent-http-protocol = { version = "3.0.0-develop", path = "packages/http-protocol" } bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } blowfish = "0" diff --git a/packages/http-protocol/Cargo.toml b/packages/http-protocol/Cargo.toml new file mode 100644 index 000000000..4f20407b6 --- /dev/null +++ b/packages/http-protocol/Cargo.toml @@ -0,0 +1,21 @@ +[package] +description = "A library with the primitive types and functions for the BitTorrent HTTP tracker protocol." +keywords = ["api", "library", "primitives"] +name = "bittorrent-http-protocol" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +percent-encoding = "2" +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } diff --git a/packages/http-protocol/LICENSE b/packages/http-protocol/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/http-protocol/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/http-protocol/README.md b/packages/http-protocol/README.md new file mode 100644 index 000000000..62de968d9 --- /dev/null +++ b/packages/http-protocol/README.md @@ -0,0 +1,11 @@ +# BitTorrent HTTP Tracker Protocol + +A library with the primitive types and functions used by BitTorrent HTTP trackers. + +## Documentation + +[Crate documentation](https://docs.rs/bittorrent-http-protocol). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/http-protocol/src/lib.rs b/packages/http-protocol/src/lib.rs new file mode 100644 index 000000000..44237d6fd --- /dev/null +++ b/packages/http-protocol/src/lib.rs @@ -0,0 +1,2 @@ +//! Primitive types and function for `BitTorrent` HTTP trackers. +pub mod percent_encoding; diff --git a/src/servers/http/percent_encoding.rs b/packages/http-protocol/src/percent_encoding.rs similarity index 94% rename from src/servers/http/percent_encoding.rs rename to packages/http-protocol/src/percent_encoding.rs index 323444cc7..b54c89a04 100644 --- a/src/servers/http/percent_encoding.rs +++ b/packages/http-protocol/src/percent_encoding.rs @@ -27,7 +27,7 @@ use torrust_tracker_primitives::peer; /// /// ```rust /// use std::str::FromStr; -/// use torrust_tracker::servers::http::percent_encoding::percent_decode_info_hash; +/// use bittorrent_http_protocol::percent_encoding::percent_decode_info_hash; /// use bittorrent_primitives::info_hash::InfoHash; /// use torrust_tracker_primitives::peer; /// @@ -60,7 +60,7 @@ pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result -//! - -//! - -use aquatic_udp_protocol::PeerId; -use bittorrent_primitives::info_hash::{self, InfoHash}; -use torrust_tracker_primitives::peer; - -/* code-review: this module is duplicated in torrust_tracker::servers::http::percent_encoding. - Should we move it to torrust_tracker_primitives? -*/ - -/// Percent decodes a percent encoded infohash. Internally an -/// [`InfoHash`] is a 20-byte array. -/// -/// For example, given the infohash `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`, -/// it's percent encoded representation is `%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0`. -/// -/// ```rust -/// use std::str::FromStr; -/// use bittorrent_tracker_client::http::url_encoding::percent_decode_info_hash; -/// use bittorrent_primitives::info_hash::InfoHash; -/// use torrust_tracker_primitives::peer; -/// -/// let encoded_infohash = "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0"; -/// -/// let info_hash = percent_decode_info_hash(encoded_infohash).unwrap(); -/// -/// assert_eq!( -/// info_hash, -/// InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap() -/// ); -/// ``` -/// -/// # Errors -/// -/// Will return `Err` if the decoded bytes do not represent a valid -/// [`InfoHash`]. -pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result { - let bytes = percent_encoding::percent_decode_str(raw_info_hash).collect::>(); - InfoHash::try_from(bytes) -} - -/// Percent decodes a percent encoded peer id. Internally a peer [`Id`](PeerId) -/// is a 20-byte array. -/// -/// For example, given the peer id `*b"-qB00000000000000000"`, -/// it's percent encoded representation is `%2DqB00000000000000000`. -/// -/// ```rust -/// use std::str::FromStr; -/// -/// use aquatic_udp_protocol::PeerId; -/// use bittorrent_tracker_client::http::url_encoding::percent_decode_peer_id; -/// use bittorrent_primitives::info_hash::InfoHash; -/// -/// let encoded_peer_id = "%2DqB00000000000000000"; -/// -/// let peer_id = percent_decode_peer_id(encoded_peer_id).unwrap(); -/// -/// assert_eq!(peer_id, PeerId(*b"-qB00000000000000000")); -/// ``` -/// -/// # Errors -/// -/// Will return `Err` if if the decoded bytes do not represent a valid [`PeerId`]. -pub fn percent_decode_peer_id(raw_peer_id: &str) -> Result { - let bytes = percent_encoding::percent_decode_str(raw_peer_id).collect::>(); - Ok(*peer::Id::try_from(bytes)?) -} - -#[cfg(test)] -mod tests { - use std::str::FromStr; - - use aquatic_udp_protocol::PeerId; - use bittorrent_primitives::info_hash::InfoHash; - - use crate::http::url_encoding::{percent_decode_info_hash, percent_decode_peer_id}; - - #[test] - fn it_should_decode_a_percent_encoded_info_hash() { - let encoded_infohash = "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0"; - - let info_hash = percent_decode_info_hash(encoded_infohash).unwrap(); - - assert_eq!( - info_hash, - InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap() - ); - } - - #[test] - fn it_should_fail_decoding_an_invalid_percent_encoded_info_hash() { - let invalid_encoded_infohash = "invalid percent-encoded infohash"; - - let info_hash = percent_decode_info_hash(invalid_encoded_infohash); - - assert!(info_hash.is_err()); - } - - #[test] - fn it_should_decode_a_percent_encoded_peer_id() { - let encoded_peer_id = "%2DqB00000000000000000"; - - let peer_id = percent_decode_peer_id(encoded_peer_id).unwrap(); - - assert_eq!(peer_id, PeerId(*b"-qB00000000000000000")); - } - - #[test] - fn it_should_fail_decoding_an_invalid_percent_encoded_peer_id() { - let invalid_encoded_peer_id = "invalid percent-encoded peer id"; - - let peer_id = percent_decode_peer_id(invalid_encoded_peer_id); - - assert!(peer_id.is_err()); - } -} diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index 4ef5ca7ea..6dfb6ce7c 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -305,7 +305,6 @@ //! - [Bencode to Json Online converter](https://chocobo1.github.io/bencode_online). use serde::{Deserialize, Serialize}; -pub mod percent_encoding; pub mod server; pub mod v1; diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index a9a9f8a76..b84f07995 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -6,12 +6,12 @@ use std::panic::Location; use std::str::FromStr; use aquatic_udp_protocol::{NumberOfBytes, PeerId}; +use bittorrent_http_protocol::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; use bittorrent_primitives::info_hash::{self, InfoHash}; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; use torrust_tracker_primitives::peer; -use crate::servers::http::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; use crate::servers::http::v1::query::{ParseQueryError, Query}; use crate::servers::http::v1::responses; diff --git a/src/servers/http/v1/requests/scrape.rs b/src/servers/http/v1/requests/scrape.rs index 0a47a4fb4..30052c8b4 100644 --- a/src/servers/http/v1/requests/scrape.rs +++ b/src/servers/http/v1/requests/scrape.rs @@ -3,11 +3,11 @@ //! Data structures and logic for parsing the `scrape` request. use std::panic::Location; +use bittorrent_http_protocol::percent_encoding::percent_decode_info_hash; use bittorrent_primitives::info_hash::{self, InfoHash}; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; -use crate::servers::http::percent_encoding::percent_decode_info_hash; use crate::servers::http::v1::query::Query; use crate::servers::http::v1::responses; From c61cc9a5242909246c6db9ccf3806c68bc423a96 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 29 Nov 2024 16:31:55 +0000 Subject: [PATCH 0529/1297] fix: doc tests --- contrib/bencode/src/lib.rs | 6 +++--- packages/located-error/src/lib.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/contrib/bencode/src/lib.rs b/contrib/bencode/src/lib.rs index 09aaa6867..c44ec07b2 100644 --- a/contrib/bencode/src/lib.rs +++ b/contrib/bencode/src/lib.rs @@ -5,9 +5,9 @@ //! Decoding bencoded data: //! //! ```rust -//! extern crate bencode; +//! extern crate torrust_tracker_contrib_bencode; //! -//! use bencode::{BencodeRef, BRefAccess, BDecodeOpt}; +//! use torrust_tracker_contrib_bencode::{BencodeRef, BRefAccess, BDecodeOpt}; //! //! fn main() { //! let data = b"d12:lucky_numberi7ee"; // cspell:disable-line @@ -22,7 +22,7 @@ //! //! ```rust //! #[macro_use] -//! extern crate bencode; +//! extern crate torrust_tracker_contrib_bencode; //! //! fn main() { //! let message = (ben_map!{ diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs index c30043cd3..09bfbd185 100644 --- a/packages/located-error/src/lib.rs +++ b/packages/located-error/src/lib.rs @@ -23,7 +23,7 @@ //! let b: LocatedError = Located(e).into(); //! let l = get_caller_location(); //! -//! assert!(b.to_string().contains("Test, src/lib.rs")); +//! assert!(b.to_string().contains("src/lib.rs")); //! ``` //! //! # Credits From 39716a8e4765e4898f4530b9a137da5980ebcfe2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 29 Nov 2024 16:32:48 +0000 Subject: [PATCH 0530/1297] ci: fix testing workflow. Run doc tests for all packages in the workspace. --- .github/workflows/testing.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 74dc254ef..28600dee9 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -140,7 +140,7 @@ jobs: - id: test-docs name: Run Documentation Tests - run: cargo test --doc + run: cargo test --doc --workspace - id: test name: Run Unit Tests From a62ae8215c556e9979042a5c6011249f72215945 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 29 Nov 2024 17:12:32 +0000 Subject: [PATCH 0531/1297] fix: cargo machete warning --- Cargo.lock | 1 - packages/tracker-client/Cargo.toml | 1 - 2 files changed, 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2931b0f8f..71edc530c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -582,7 +582,6 @@ name = "bittorrent-tracker-client" version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", - "bittorrent-http-protocol", "bittorrent-primitives", "derive_more", "hyper", diff --git a/packages/tracker-client/Cargo.toml b/packages/tracker-client/Cargo.toml index 2c536677b..52b0be639 100644 --- a/packages/tracker-client/Cargo.toml +++ b/packages/tracker-client/Cargo.toml @@ -16,7 +16,6 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" -bittorrent-http-protocol = { version = "3.0.0-develop", path = "../http-protocol" } bittorrent-primitives = "0.1.0" derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } hyper = "1" From 2bc44af7e332aadaa2ef9d4fcef549827cb32874 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 29 Nov 2024 17:12:53 +0000 Subject: [PATCH 0532/1297] test: add test for percent_encode_byte_array --- packages/tracker-client/src/http/mod.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/tracker-client/src/http/mod.rs b/packages/tracker-client/src/http/mod.rs index 15723c1b7..d8f8242e8 100644 --- a/packages/tracker-client/src/http/mod.rs +++ b/packages/tracker-client/src/http/mod.rs @@ -24,3 +24,19 @@ impl InfoHash { self.0 } } + +#[cfg(test)] +mod tests { + use crate::http::percent_encode_byte_array; + + #[test] + fn it_should_encode_a_20_byte_array() { + assert_eq!( + percent_encode_byte_array(&[ + 0x3b, 0x24, 0x55, 0x04, 0xcf, 0x5f, 0x11, 0xbb, 0xdb, 0xe1, 0x20, 0x1c, 0xea, 0x6a, 0x6b, 0xf4, 0x5a, 0xee, 0x1b, + 0xc0, + ]), + "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0" + ); + } +} From 3af1928fe218b8f14de6549b3e4620903e49bef0 Mon Sep 17 00:00:00 2001 From: Binlogo Date: Mon, 2 Dec 2024 10:26:09 +0000 Subject: [PATCH 0533/1297] fix: [#1104] improve HTTP announce error message --- src/servers/http/v1/extractors/announce_request.rs | 10 +++++----- src/servers/http/v1/extractors/scrape_request.rs | 10 +++++----- src/servers/http/v1/requests/announce.rs | 4 ++-- src/servers/http/v1/requests/scrape.rs | 2 +- tests/servers/http/asserts.rs | 2 +- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/servers/http/v1/extractors/announce_request.rs b/src/servers/http/v1/extractors/announce_request.rs index 5a642e3fc..ea9a22c7a 100644 --- a/src/servers/http/v1/extractors/announce_request.rs +++ b/src/servers/http/v1/extractors/announce_request.rs @@ -19,13 +19,13 @@ //! Missing query params for `announce` request: //! //! ```text -//! d14:failure reason149:Cannot parse query params for announce request: missing query params for announce request in src/servers/http/v1/extractors/announce_request.rs:54:23e +//! d14:failure reason149:Bad request. Cannot parse query params for announce request: missing query params for announce request in src/servers/http/v1/extractors/announce_request.rs:54:23e //! ``` //! //! Invalid query param (`info_hash`): //! //! ```text -//! d14:failure reason240:Cannot parse query params for announce request: invalid param value invalid for info_hash in not enough bytes for infohash: got 7 bytes, expected 20 src/shared/bit_torrent/info_hash.rs:240:27, src/servers/http/v1/requests/announce.rs:182:42e +//! d14:failure reason240:Bad request. Cannot parse query params for announce request: invalid param value invalid for info_hash in not enough bytes for infohash: got 7 bytes, expected 20 src/shared/bit_torrent/info_hash.rs:240:27, src/servers/http/v1/requests/announce.rs:182:42e //! ``` use std::panic::Location; @@ -137,7 +137,7 @@ mod tests { assert_error_response( &response, - "Cannot parse query params for announce request: missing query params for announce request", + "Bad request. Cannot parse query params for announce request: missing query params for announce request", ); } @@ -146,13 +146,13 @@ mod tests { let invalid_query = "param1=value1=value2"; let response = extract_announce_from(Some(invalid_query)).unwrap_err(); - assert_error_response(&response, "Cannot parse query params"); + assert_error_response(&response, "Bad request. Cannot parse query params"); } #[test] fn it_should_reject_a_request_with_a_query_that_cannot_be_parsed_into_an_announce_request() { let response = extract_announce_from(Some("param1=value1")).unwrap_err(); - assert_error_response(&response, "Cannot parse query params for announce request"); + assert_error_response(&response, "Bad request. Cannot parse query params for announce request"); } } diff --git a/src/servers/http/v1/extractors/scrape_request.rs b/src/servers/http/v1/extractors/scrape_request.rs index 80173a33c..35c0bb1b5 100644 --- a/src/servers/http/v1/extractors/scrape_request.rs +++ b/src/servers/http/v1/extractors/scrape_request.rs @@ -19,13 +19,13 @@ //! Missing query params for scrape request: //! //! ```text -//! d14:failure reason143:Cannot parse query params for scrape request: missing query params for scrape request in src/servers/http/v1/extractors/scrape_request.rs:52:23e +//! d14:failure reason143:Bad request. Cannot parse query params for scrape request: missing query params for scrape request in src/servers/http/v1/extractors/scrape_request.rs:52:23e //! ``` //! //! Invalid query params for scrape request: //! //! ```text -//! d14:failure reason235:Cannot parse query params for scrape request: invalid param value invalid for info_hash in not enough bytes for infohash: got 7 bytes, expected 20 src/shared/bit_torrent/info_hash.rs:240:27, src/servers/http/v1/requests/scrape.rs:66:46e +//! d14:failure reason235:Bad request. Cannot parse query params for scrape request: invalid param value invalid for info_hash in not enough bytes for infohash: got 7 bytes, expected 20 src/shared/bit_torrent/info_hash.rs:240:27, src/servers/http/v1/requests/scrape.rs:66:46e //! ``` use std::panic::Location; @@ -158,7 +158,7 @@ mod tests { assert_error_response( &response, - "Cannot parse query params for scrape request: missing query params for scrape request", + "Bad request. Cannot parse query params for scrape request: missing query params for scrape request", ); } @@ -167,13 +167,13 @@ mod tests { let invalid_query = "param1=value1=value2"; let response = extract_scrape_from(Some(invalid_query)).unwrap_err(); - assert_error_response(&response, "Cannot parse query params"); + assert_error_response(&response, "Bad request. Cannot parse query params"); } #[test] fn it_should_reject_a_request_with_a_query_that_cannot_be_parsed_into_a_scrape_request() { let response = extract_scrape_from(Some("param1=value1")).unwrap_err(); - assert_error_response(&response, "Cannot parse query params for scrape request"); + assert_error_response(&response, "Bad request. Cannot parse query params for scrape request"); } } diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index b84f07995..00bf53c6f 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -226,7 +226,7 @@ impl FromStr for Compact { impl From for responses::error::Error { fn from(err: ParseQueryError) -> Self { responses::error::Error { - failure_reason: format!("Cannot parse query params: {err}"), + failure_reason: format!("Bad request. Cannot parse query params: {err}"), } } } @@ -234,7 +234,7 @@ impl From for responses::error::Error { impl From for responses::error::Error { fn from(err: ParseAnnounceQueryError) -> Self { responses::error::Error { - failure_reason: format!("Cannot parse query params for announce request: {err}"), + failure_reason: format!("Bad request. Cannot parse query params for announce request: {err}"), } } } diff --git a/src/servers/http/v1/requests/scrape.rs b/src/servers/http/v1/requests/scrape.rs index 30052c8b4..a8e76282e 100644 --- a/src/servers/http/v1/requests/scrape.rs +++ b/src/servers/http/v1/requests/scrape.rs @@ -39,7 +39,7 @@ pub enum ParseScrapeQueryError { impl From for responses::error::Error { fn from(err: ParseScrapeQueryError) -> Self { responses::error::Error { - failure_reason: format!("Cannot parse query params for scrape request: {err}"), + failure_reason: format!("Bad request. Cannot parse query params for scrape request: {err}"), } } } diff --git a/tests/servers/http/asserts.rs b/tests/servers/http/asserts.rs index 3a2e67bf0..8d40d7e74 100644 --- a/tests/servers/http/asserts.rs +++ b/tests/servers/http/asserts.rs @@ -133,7 +133,7 @@ pub async fn assert_cannot_parse_query_params_error_response(response: Response, assert_bencoded_error( &response.text().await.unwrap(), - &format!("Cannot parse query params{failure}"), + &format!("Bad request. Cannot parse query params{failure}"), Location::caller(), ); } From 6862301855d8b2ad399d7f8ea6b5374b6eaa140e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 3 Dec 2024 11:08:53 +0000 Subject: [PATCH 0534/1297] chore(deps): update depencencies ``` cargo update Updating crates.io index Locking 18 packages to latest compatible versions Updating allocator-api2 v0.2.20 -> v0.2.21 Updating event-listener-strategy v0.5.2 -> v0.5.3 Removing hermit-abi v0.3.9 Updating indexmap v2.6.0 -> v2.7.0 Updating js-sys v0.3.72 -> v0.3.74 Updating libloading v0.8.5 -> v0.8.6 Updating mio v1.0.2 -> v1.0.3 Updating syn v2.0.89 -> v2.0.90 Updating time v0.3.36 -> v0.3.37 Updating time-macros v0.2.18 -> v0.2.19 Updating tracing-serde v0.1.3 -> v0.2.0 Updating tracing-subscriber v0.3.18 -> v0.3.19 Updating wasm-bindgen v0.2.95 -> v0.2.97 Updating wasm-bindgen-backend v0.2.95 -> v0.2.97 Updating wasm-bindgen-futures v0.4.45 -> v0.4.47 Updating wasm-bindgen-macro v0.2.95 -> v0.2.97 Updating wasm-bindgen-macro-support v0.2.95 -> v0.2.97 Updating wasm-bindgen-shared v0.2.95 -> v0.2.97 Updating web-sys v0.3.72 -> v0.3.74 ``` --- Cargo.lock | 169 ++++++++++++++++++++++++++--------------------------- 1 file changed, 82 insertions(+), 87 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 71edc530c..479c1dbc8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -66,9 +66,9 @@ dependencies = [ [[package]] name = "allocator-api2" -version = "0.2.20" +version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45862d1c77f2228b9e10bc609d5bc203d86ebc9b87ad8d5d5167a6c9abf739d9" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "android-tzdata" @@ -333,7 +333,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -456,7 +456,7 @@ checksum = "57d123550fa8d071b7255cb0cc04dc302baa6c8c4a79f55701552684d8399bce" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -544,7 +544,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -664,7 +664,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -897,7 +897,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1118,7 +1118,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1129,7 +1129,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1173,7 +1173,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "unicode-xid", ] @@ -1185,7 +1185,7 @@ checksum = "65f152f4b8559c4da5d574bafc7af85454d706b4c5fe8b530d508cacbb6807ea" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1206,7 +1206,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1275,9 +1275,9 @@ dependencies = [ [[package]] name = "event-listener-strategy" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" +checksum = "3c3e4e0dd3673c1139bf041f3008816d9cf2946bbfac2945c09e523b8d7b05b2" dependencies = [ "event-listener 5.3.1", "pin-project-lite", @@ -1409,7 +1409,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1421,7 +1421,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1433,7 +1433,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1511,7 +1511,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1607,7 +1607,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.6.0", + "indexmap 2.7.0", "slab", "tokio", "tokio-util", @@ -1668,12 +1668,6 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" -[[package]] -name = "hermit-abi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" - [[package]] name = "hermit-abi" version = "0.4.0" @@ -1949,7 +1943,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1992,9 +1986,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.6.0" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" +checksum = "62f822373a4fe84d4bb149bf54e584a7f4abec90e072ed49cda0edea5b95471f" dependencies = [ "equivalent", "hashbrown 0.15.2", @@ -2037,7 +2031,7 @@ version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "261f68e344040fbd0edea105bef17c66edf46f984ddb1115b775ce31be948f4b" dependencies = [ - "hermit-abi 0.4.0", + "hermit-abi", "libc", "windows-sys 0.52.0", ] @@ -2083,10 +2077,11 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.72" +version = "0.3.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a88f1bda2bd75b0452a14784937d796722fdebfe50df998aeb3f0b7603019a9" +checksum = "a865e038f7f6ed956f788f0d7d60c541fff74c7bd74272c5d4cf15c63743e705" dependencies = [ + "once_cell", "wasm-bindgen", ] @@ -2113,9 +2108,9 @@ checksum = "09d6582e104315a817dff97f75133544b2e094ee22447d2acf4a74e189ba06fc" [[package]] name = "libloading" -version = "0.8.5" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" +checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" dependencies = [ "cfg-if", "windows-targets", @@ -2236,11 +2231,10 @@ dependencies = [ [[package]] name = "mio" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" +checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" dependencies = [ - "hermit-abi 0.3.9", "libc", "wasi", "windows-sys 0.52.0", @@ -2269,7 +2263,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -2336,7 +2330,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "termcolor", "thiserror 1.0.69", ] @@ -2535,7 +2529,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -2611,7 +2605,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -2685,7 +2679,7 @@ checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -2753,7 +2747,7 @@ checksum = "a604568c3202727d1507653cb121dbd627a58684eb09a820fd746bee38b4442f" dependencies = [ "cfg-if", "concurrent-queue", - "hermit-abi 0.4.0", + "hermit-abi", "pin-project-lite", "rustix", "tracing", @@ -2835,7 +2829,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -2855,7 +2849,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "version_check", "yansi", ] @@ -3164,7 +3158,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.89", + "syn 2.0.90", "unicode-ident", ] @@ -3393,7 +3387,7 @@ checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -3403,7 +3397,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8de514ef58196f1fc96dcaef80fe6170a1ce6215df9687a93fe8300e773fefc5" dependencies = [ "form_urlencoded", - "indexmap 2.6.0", + "indexmap 2.7.0", "itoa", "ryu", "serde", @@ -3415,7 +3409,7 @@ version = "1.0.133" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" dependencies = [ - "indexmap 2.6.0", + "indexmap 2.7.0", "itoa", "memchr", "ryu", @@ -3440,7 +3434,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -3474,7 +3468,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.6.0", + "indexmap 2.7.0", "serde", "serde_derive", "serde_json", @@ -3491,7 +3485,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -3630,9 +3624,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.89" +version = "2.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d46482f1c1c87acd84dea20c1bf5ebff4c757009ed6bf19cfd36fb10e92c4e" +checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31" dependencies = [ "proc-macro2", "quote", @@ -3662,7 +3656,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -3763,7 +3757,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -3774,7 +3768,7 @@ checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -3789,9 +3783,9 @@ dependencies = [ [[package]] name = "time" -version = "0.3.36" +version = "0.3.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" +checksum = "35e7868883861bd0e56d9ac6efcaaca0d6d5d82a2a7ec8209ff492c07cf37b21" dependencies = [ "deranged", "itoa", @@ -3810,9 +3804,9 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.18" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" +checksum = "2834e6017e3e5e4b9834939793b282bc03b37a3336245fa820e35e233e2a85de" dependencies = [ "num-conv", "time-core", @@ -3878,7 +3872,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -3942,7 +3936,7 @@ version = "0.22.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ae48d6208a266e853d946088ed816055e556cc6028c5e8e2b84d9fa5dd7c7f5" dependencies = [ - "indexmap 2.6.0", + "indexmap 2.7.0", "serde", "serde_spanned", "toml_datetime", @@ -4208,7 +4202,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -4234,9 +4228,9 @@ dependencies = [ [[package]] name = "tracing-serde" -version = "0.1.3" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc6b213177105856957181934e4920de57730fc69bf42c37ee5bb664d406d9e1" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" dependencies = [ "serde", "tracing-core", @@ -4244,9 +4238,9 @@ dependencies = [ [[package]] name = "tracing-subscriber" -version = "0.3.18" +version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b" +checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008" dependencies = [ "nu-ansi-term", "serde", @@ -4400,9 +4394,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.95" +version = "0.2.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "128d1e363af62632b8eb57219c8fd7877144af57558fb2ef0368d0087bddeb2e" +checksum = "d15e63b4482863c109d70a7b8706c1e364eb6ea449b201a76c5b89cedcec2d5c" dependencies = [ "cfg-if", "once_cell", @@ -4411,36 +4405,37 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.95" +version = "0.2.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb6dd4d3ca0ddffd1dd1c9c04f94b868c37ff5fac97c30b97cff2d74fce3a358" +checksum = "8d36ef12e3aaca16ddd3f67922bc63e48e953f126de60bd33ccc0101ef9998cd" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.45" +version = "0.4.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7ec4f8827a71586374db3e87abdb5a2bb3a15afed140221307c3ec06b1f63b" +checksum = "9dfaf8f50e5f293737ee323940c7d8b08a66a95a419223d9f41610ca08b0833d" dependencies = [ "cfg-if", "js-sys", + "once_cell", "wasm-bindgen", "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.95" +version = "0.2.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e79384be7f8f5a9dd5d7167216f022090cf1f9ec128e6e6a482a2cb5c5422c56" +checksum = "705440e08b42d3e4b36de7d66c944be628d579796b8090bfa3471478a2260051" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -4448,28 +4443,28 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.95" +version = "0.2.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" +checksum = "98c9ae5a76e46f4deecd0f0255cc223cfa18dc9b261213b8aa0c7b36f61b3f1d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.95" +version = "0.2.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" +checksum = "6ee99da9c5ba11bd675621338ef6fa52296b76b83305e9b6e5c77d4c286d6d49" [[package]] name = "web-sys" -version = "0.3.72" +version = "0.3.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6488b90108c040df0fe62fa815cbdee25124641df01814dd7282749234c6112" +checksum = "a98bc3c33f0fe7e59ad7cd041b89034fa82a7c2d4365ca538dda6cdaf513863c" dependencies = [ "js-sys", "wasm-bindgen", @@ -4683,7 +4678,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "synstructure", ] @@ -4705,7 +4700,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -4725,7 +4720,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "synstructure", ] @@ -4754,7 +4749,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] From 0d36fb2bf5ecc03110ebca2045fc5769284d2b93 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 4 Dec 2024 17:29:38 +0000 Subject: [PATCH 0535/1297] chore(deps): update depencencies ```ouput cargo update Updating crates.io index Locking 8 packages to latest compatible versions Updating anyhow v1.0.93 -> v1.0.94 Updating clap v4.5.21 -> v4.5.22 Updating clap_builder v4.5.21 -> v4.5.22 Updating http v1.1.0 -> v1.2.0 Updating thiserror v2.0.3 -> v2.0.4 Updating thiserror-impl v2.0.3 -> v2.0.4 Updating tokio v1.41.1 -> v1.42.0 Updating tokio-util v0.7.12 -> v0.7.13 ``` --- Cargo.lock | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 479c1dbc8..7134365df 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -142,9 +142,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.93" +version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c95c10ba0b00a02636238b814946408b1322d5ac4760326e6fb8ec956d85775" +checksum = "c1fd03a028ef38ba2276dce7e33fcd6369c158a1bca17946c4b1b701891c1ff7" [[package]] name = "aquatic_peer_id" @@ -868,9 +868,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.21" +version = "4.5.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb3b4b9e5a7c7514dfa52869339ee98b3156b0bfb4e8a77c4ff4babb64b1604f" +checksum = "69371e34337c4c984bbe322360c2547210bf632eb2814bbe78a6e87a2935bd2b" dependencies = [ "clap_builder", "clap_derive", @@ -878,9 +878,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.21" +version = "4.5.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b17a95aa67cc7b5ebd32aa5370189aa0d79069ef1c64ce893bd30fb24bff20ec" +checksum = "6e24c1b4099818523236a8ca881d2b45db98dadfb4625cf6608c12069fcbbde1" dependencies = [ "anstream", "anstyle", @@ -1688,9 +1688,9 @@ checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" [[package]] name = "http" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" +checksum = "f16ca2af56261c99fba8bac40a10251ce8188205a4c448fbb745a2e4daa76fea" dependencies = [ "bytes", "fnv", @@ -3742,11 +3742,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.3" +version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c006c85c7651b3cf2ada4584faa36773bd07bac24acfb39f3c431b36d7e667aa" +checksum = "2f49a1853cf82743e3b7950f77e0f4d622ca36cf4317cba00c767838bac8d490" dependencies = [ - "thiserror-impl 2.0.3", + "thiserror-impl 2.0.4", ] [[package]] @@ -3762,9 +3762,9 @@ dependencies = [ [[package]] name = "thiserror-impl" -version = "2.0.3" +version = "2.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568" +checksum = "8381894bb3efe0c4acac3ded651301ceee58a15d47c2e34885ed1908ad667061" dependencies = [ "proc-macro2", "quote", @@ -3849,9 +3849,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.41.1" +version = "1.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cfb5bee7a6a52939ca9224d6ac897bb669134078daa8735560897f69de4d33" +checksum = "5cec9b21b0450273377fc97bd4c33a8acffc8c996c987a7c5b319a0083707551" dependencies = [ "backtrace", "bytes", @@ -3898,9 +3898,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.12" +version = "0.7.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61e7c3654c13bcd040d4a03abee2c75b1d14a37b423cf5a813ceae1cc903ec6a" +checksum = "d7fcaa8d55a2bdd6b83ace262b016eca0d79ee02818c5c1bcdf0305114081078" dependencies = [ "bytes", "futures-core", @@ -3990,7 +3990,7 @@ dependencies = [ "serde_json", "serde_repr", "serde_with", - "thiserror 2.0.3", + "thiserror 2.0.4", "tokio", "torrust-tracker-clock", "torrust-tracker-configuration", From 52d3505bb4a54435c05775a25875993bff465a47 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 10 Dec 2024 18:24:43 +0000 Subject: [PATCH 0536/1297] feat: [#1126] add support for prometheus text format on stats API endpoint http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken&format=prometheus ```text torrents 0 seeders 0 completed 0 leechers 0 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 udp4_errors_handled 0 udp6_connections_handled 0 udp6_announces_handled 0 udp6_scrapes_handled 0 udp6_errors_handled 0 ``` --- src/servers/apis/v1/context/stats/handlers.rs | 39 +++++++-- .../apis/v1/context/stats/responses.rs | 81 ++++++++++++++++++- 2 files changed, 111 insertions(+), 9 deletions(-) diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index c3be5dc7a..8b11b1ff1 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -3,19 +3,46 @@ use std::sync::Arc; use axum::extract::State; -use axum::response::Json; +use axum::response::Response; +use axum_extra::extract::Query; +use serde::Deserialize; -use super::resources::Stats; -use super::responses::stats_response; +use super::responses::{metrics_response, stats_response}; use crate::core::services::statistics::get_metrics; use crate::core::Tracker; +#[derive(Deserialize, Debug, Default)] +#[serde(rename_all = "lowercase")] +pub enum Format { + #[default] + Json, + Prometheus, +} + +#[derive(Deserialize, Debug)] +pub struct QueryParams { + /// The [`Format`] of the stats. + #[serde(default)] + pub format: Option, +} + /// It handles the request to get the tracker statistics. /// -/// It returns a `200` response with a json [`Stats`] +/// By default it returns a `200` response with the stats in JSON format. +/// +/// You can add the GET parameter `format=prometheus` to get the stats in +/// Prometheus Text Exposition Format. /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::stats#get-tracker-statistics) /// for more information about this endpoint. -pub async fn get_stats_handler(State(tracker): State>) -> Json { - stats_response(get_metrics(tracker.clone()).await) +pub async fn get_stats_handler(State(tracker): State>, params: Query) -> Response { + let metrics = get_metrics(tracker.clone()).await; + + match params.0.format { + Some(format) => match format { + Format::Json => stats_response(metrics), + Format::Prometheus => metrics_response(&metrics), + }, + None => stats_response(metrics), + } } diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index 9d03ccedf..4fd8be94f 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -1,11 +1,86 @@ //! API responses for the [`stats`](crate::servers::apis::v1::context::stats) //! API context. -use axum::response::Json; +use axum::response::{IntoResponse, Json, Response}; use super::resources::Stats; use crate::core::services::statistics::TrackerMetrics; /// `200` response that contains the [`Stats`] resource as json. -pub fn stats_response(tracker_metrics: TrackerMetrics) -> Json { - Json(Stats::from(tracker_metrics)) +#[must_use] +pub fn stats_response(tracker_metrics: TrackerMetrics) -> Response { + Json(Stats::from(tracker_metrics)).into_response() +} + +/// `200` response that contains the [`Stats`] resource in Prometheus Text Exposition Format . +#[must_use] +pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { + let mut lines = vec![]; + + lines.push(format!("torrents {}", tracker_metrics.torrents_metrics.torrents)); + lines.push(format!("seeders {}", tracker_metrics.torrents_metrics.complete)); + lines.push(format!("completed {}", tracker_metrics.torrents_metrics.downloaded)); + lines.push(format!("leechers {}", tracker_metrics.torrents_metrics.incomplete)); + + lines.push(format!( + "tcp4_connections_handled {}", + tracker_metrics.protocol_metrics.tcp4_connections_handled + )); + lines.push(format!( + "tcp4_announces_handled {}", + tracker_metrics.protocol_metrics.tcp4_announces_handled + )); + lines.push(format!( + "tcp4_scrapes_handled {}", + tracker_metrics.protocol_metrics.tcp4_scrapes_handled + )); + + lines.push(format!( + "tcp6_connections_handled {}", + tracker_metrics.protocol_metrics.tcp6_connections_handled + )); + lines.push(format!( + "tcp6_announces_handled {}", + tracker_metrics.protocol_metrics.tcp6_announces_handled + )); + lines.push(format!( + "tcp6_scrapes_handled {}", + tracker_metrics.protocol_metrics.tcp6_scrapes_handled + )); + + lines.push(format!( + "udp4_connections_handled {}", + tracker_metrics.protocol_metrics.udp4_connections_handled + )); + lines.push(format!( + "udp4_announces_handled {}", + tracker_metrics.protocol_metrics.udp4_announces_handled + )); + lines.push(format!( + "udp4_scrapes_handled {}", + tracker_metrics.protocol_metrics.udp4_scrapes_handled + )); + lines.push(format!( + "udp4_errors_handled {}", + tracker_metrics.protocol_metrics.udp4_errors_handled + )); + + lines.push(format!( + "udp6_connections_handled {}", + tracker_metrics.protocol_metrics.udp6_connections_handled + )); + lines.push(format!( + "udp6_announces_handled {}", + tracker_metrics.protocol_metrics.udp6_announces_handled + )); + lines.push(format!( + "udp6_scrapes_handled {}", + tracker_metrics.protocol_metrics.udp6_scrapes_handled + )); + lines.push(format!( + "udp6_errors_handled {}", + tracker_metrics.protocol_metrics.udp6_errors_handled + )); + + // Return the plain text response + lines.join("\n").into_response() } From 7993f13995f686db7ab8df9970a331e1bf65e9d6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 13 Dec 2024 17:01:44 +0000 Subject: [PATCH 0537/1297] chore(deps): update depencencies ```output cargo update Updating crates.io index Locking 29 packages to latest compatible versions Updating bigdecimal v0.4.6 -> v0.4.7 Updating bindgen v0.70.1 -> v0.71.1 Updating cc v1.2.2 -> v1.2.4 Updating chrono v0.4.38 -> v0.4.39 Updating clap v4.5.22 -> v4.5.23 Updating clap_builder v4.5.22 -> v4.5.23 Updating clap_lex v0.7.3 -> v0.7.4 Updating fastrand v2.2.0 -> v2.3.0 Updating js-sys v0.3.74 -> v0.3.76 Updating libc v0.2.167 -> v0.2.168 Updating redox_syscall v0.5.7 -> v0.5.8 Updating rustc-hash v1.1.0 -> v2.1.0 Updating rustix v0.38.41 -> v0.38.42 Updating rustls v0.23.19 -> v0.23.20 Updating rustls-pki-types v1.10.0 -> v1.10.1 Updating semver v1.0.23 -> v1.0.24 Updating serde v1.0.215 -> v1.0.216 Updating serde_derive v1.0.215 -> v1.0.216 Removing sync_wrapper v0.1.2 Updating thiserror v2.0.4 -> v2.0.6 Updating thiserror-impl v2.0.4 -> v2.0.6 Updating tokio-rustls v0.26.0 -> v0.26.1 Updating tower v0.5.1 -> v0.5.2 Updating wasm-bindgen v0.2.97 -> v0.2.99 Updating wasm-bindgen-backend v0.2.97 -> v0.2.99 Updating wasm-bindgen-futures v0.4.47 -> v0.4.49 Updating wasm-bindgen-macro v0.2.97 -> v0.2.99 Updating wasm-bindgen-macro-support v0.2.97 -> v0.2.99 Updating wasm-bindgen-shared v0.2.97 -> v0.2.99 Updating web-sys v0.3.74 -> v0.3.76 ``` --- Cargo.lock | 144 +++++++++++++++++++++++++---------------------------- 1 file changed, 68 insertions(+), 76 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7134365df..6573dcd0f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -384,9 +384,9 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", - "sync_wrapper 1.0.2", + "sync_wrapper", "tokio", - "tower 0.5.1", + "tower 0.5.2", "tower-layer", "tower-service", "tracing", @@ -418,7 +418,7 @@ dependencies = [ "mime", "pin-project-lite", "rustversion", - "sync_wrapper 1.0.2", + "sync_wrapper", "tower-layer", "tower-service", "tracing", @@ -443,7 +443,7 @@ dependencies = [ "pin-project-lite", "serde", "serde_html_form", - "tower 0.5.1", + "tower 0.5.2", "tower-layer", "tower-service", ] @@ -512,9 +512,9 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "bigdecimal" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f850665a0385e070b64c38d2354e6c104c8479c59868d1e48a0c13ee2c7a1c1" +checksum = "7f31f3af01c5c65a07985c804d3366560e6fa7883d640a122819b14ec327482c" dependencies = [ "autocfg", "libm", @@ -531,9 +531,9 @@ checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" [[package]] name = "bindgen" -version = "0.70.1" +version = "0.71.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" +checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3" dependencies = [ "bitflags", "cexpr", @@ -775,9 +775,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.2" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f34d93e62b03caf570cccc334cbc6c2fceca82f39211051345108adcba3eebdc" +checksum = "9157bbaa6b165880c27a4293a474c91cdcf265cc68cc829bf10be0964a391caf" dependencies = [ "jobserver", "libc", @@ -807,9 +807,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "chrono" -version = "0.4.38" +version = "0.4.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +checksum = "7e36cc9d416881d2e24f9a963be5fb1cd90966419ac844274161d10488b3e825" dependencies = [ "android-tzdata", "iana-time-zone", @@ -868,9 +868,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.22" +version = "4.5.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69371e34337c4c984bbe322360c2547210bf632eb2814bbe78a6e87a2935bd2b" +checksum = "3135e7ec2ef7b10c6ed8950f0f792ed96ee093fa088608f1c76e569722700c84" dependencies = [ "clap_builder", "clap_derive", @@ -878,9 +878,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.22" +version = "4.5.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e24c1b4099818523236a8ca881d2b45db98dadfb4625cf6608c12069fcbbde1" +checksum = "30582fc632330df2bd26877bde0c1f4470d57c582bbc070376afcd04d8cb4838" dependencies = [ "anstream", "anstyle", @@ -902,9 +902,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afb84c814227b90d6895e01398aee0d8033c00e7466aca416fb6a8e0eb19d8a7" +checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" [[package]] name = "cmake" @@ -1297,9 +1297,9 @@ checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" [[package]] name = "fastrand" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "486f806e73c5707928240ddc295403b1b93c96a02038563881c4a2fd84b81ac4" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "figment" @@ -2077,9 +2077,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.74" +version = "0.3.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a865e038f7f6ed956f788f0d7d60c541fff74c7bd74272c5d4cf15c63743e705" +checksum = "6717b6b5b077764fb5966237269cb3c64edddde4b14ce42647430a78ced9e7b7" dependencies = [ "once_cell", "wasm-bindgen", @@ -2102,9 +2102,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.167" +version = "0.2.168" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09d6582e104315a817dff97f75133544b2e094ee22447d2acf4a74e189ba06fc" +checksum = "5aaeb2981e0606ca11d79718f8bb01164f1d6ed75080182d3abf017e6d244b6d" [[package]] name = "libloading" @@ -2984,9 +2984,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.7" +version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" +checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" dependencies = [ "bitflags", ] @@ -3066,7 +3066,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "sync_wrapper 1.0.2", + "sync_wrapper", "system-configuration", "tokio", "tokio-native-tls", @@ -3200,9 +3200,9 @@ checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" [[package]] name = "rustc-hash" -version = "1.1.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" +checksum = "c7fb8039b3032c191086b10f11f319a6e99e1e82889c5cc6046f515c9db1d497" [[package]] name = "rustc_version" @@ -3215,22 +3215,22 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.41" +version = "0.38.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7f649912bc1495e167a6edee79151c84b1bad49748cb4f1f1167f459f6224f6" +checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] name = "rustls" -version = "0.23.19" +version = "0.23.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "934b404430bb06b3fae2cba809eb45a1ab1aecd64491213d7c3301b88393f8d1" +checksum = "5065c3f250cbd332cd894be57c40fa52387247659b14a2d6041d121547903b1b" dependencies = [ "once_cell", "rustls-pki-types", @@ -3250,9 +3250,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.10.0" +version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16f1201b3c9a7ee8039bcadc17b7e605e2945b27eee7631788c1bd2b0643674b" +checksum = "d2bf47e6ff922db3825eb750c4e2ff784c6ff8fb9e13046ef6a1d1c5401b0b37" [[package]] name = "rustls-webpki" @@ -3347,15 +3347,15 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.23" +version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" +checksum = "3cb6eb87a131f756572d7fb904f6e7b68633f09cca868c5df1c4b8d1a694bbba" [[package]] name = "serde" -version = "1.0.215" +version = "1.0.216" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" +checksum = "0b9781016e935a97e8beecf0c933758c97a5520d32930e460142b4cd80c6338e" dependencies = [ "serde_derive", ] @@ -3381,9 +3381,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.215" +version = "1.0.216" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" +checksum = "46f859dbbf73865c6627ed570e78961cd3ac92407a2d117204c49232485da55e" dependencies = [ "proc-macro2", "quote", @@ -3633,12 +3633,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "sync_wrapper" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" - [[package]] name = "sync_wrapper" version = "1.0.2" @@ -3742,11 +3736,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.4" +version = "2.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f49a1853cf82743e3b7950f77e0f4d622ca36cf4317cba00c767838bac8d490" +checksum = "8fec2a1820ebd077e2b90c4df007bebf344cd394098a13c563957d0afc83ea47" dependencies = [ - "thiserror-impl 2.0.4", + "thiserror-impl 2.0.6", ] [[package]] @@ -3762,9 +3756,9 @@ dependencies = [ [[package]] name = "thiserror-impl" -version = "2.0.4" +version = "2.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8381894bb3efe0c4acac3ded651301ceee58a15d47c2e34885ed1908ad667061" +checksum = "d65750cab40f4ff1929fb1ba509e9914eb756131cef4210da8d5d700d26f6312" dependencies = [ "proc-macro2", "quote", @@ -3887,12 +3881,11 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.26.0" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" +checksum = "5f6d0975eaace0cf0fcadee4e4aaa5da15b5c079146f2cffb67c113be122bf37" dependencies = [ "rustls", - "rustls-pki-types", "tokio", ] @@ -3990,7 +3983,7 @@ dependencies = [ "serde_json", "serde_repr", "serde_with", - "thiserror 2.0.4", + "thiserror 2.0.6", "tokio", "torrust-tracker-clock", "torrust-tracker-configuration", @@ -3999,7 +3992,7 @@ dependencies = [ "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-tracker-torrent-repository", - "tower 0.5.1", + "tower 0.5.2", "tower-http", "tracing", "tracing-subscriber", @@ -4135,14 +4128,14 @@ dependencies = [ [[package]] name = "tower" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2873938d487c3cfb9aed7546dc9f2711d867c9f90c46b889989a2cb84eba6b4f" +checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" dependencies = [ "futures-core", "futures-util", "pin-project-lite", - "sync_wrapper 0.1.2", + "sync_wrapper", "tokio", "tower-layer", "tower-service", @@ -4394,9 +4387,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.97" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d15e63b4482863c109d70a7b8706c1e364eb6ea449b201a76c5b89cedcec2d5c" +checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396" dependencies = [ "cfg-if", "once_cell", @@ -4405,13 +4398,12 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.97" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d36ef12e3aaca16ddd3f67922bc63e48e953f126de60bd33ccc0101ef9998cd" +checksum = "5f89bb38646b4f81674e8f5c3fb81b562be1fd936d84320f3264486418519c79" dependencies = [ "bumpalo", "log", - "once_cell", "proc-macro2", "quote", "syn 2.0.90", @@ -4420,9 +4412,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.47" +version = "0.4.49" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dfaf8f50e5f293737ee323940c7d8b08a66a95a419223d9f41610ca08b0833d" +checksum = "38176d9b44ea84e9184eff0bc34cc167ed044f816accfe5922e54d84cf48eca2" dependencies = [ "cfg-if", "js-sys", @@ -4433,9 +4425,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.97" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "705440e08b42d3e4b36de7d66c944be628d579796b8090bfa3471478a2260051" +checksum = "2cc6181fd9a7492eef6fef1f33961e3695e4579b9872a6f7c83aee556666d4fe" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -4443,9 +4435,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.97" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98c9ae5a76e46f4deecd0f0255cc223cfa18dc9b261213b8aa0c7b36f61b3f1d" +checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" dependencies = [ "proc-macro2", "quote", @@ -4456,15 +4448,15 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.97" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ee99da9c5ba11bd675621338ef6fa52296b76b83305e9b6e5c77d4c286d6d49" +checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6" [[package]] name = "web-sys" -version = "0.3.74" +version = "0.3.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a98bc3c33f0fe7e59ad7cd041b89034fa82a7c2d4365ca538dda6cdaf513863c" +checksum = "04dd7223427d52553d3702c004d3b2fe07c148165faa56313cb00211e31c12bc" dependencies = [ "js-sys", "wasm-bindgen", From abb242368b8fd4f8ade6eab265cebafea4ba8592 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 13 Dec 2024 17:07:33 +0000 Subject: [PATCH 0538/1297] chore(deps): update thiserror in workspace packages --- Cargo.lock | 12 ++++++------ console/tracker-client/Cargo.toml | 2 +- contrib/bencode/Cargo.toml | 2 +- packages/configuration/Cargo.toml | 2 +- packages/located-error/Cargo.toml | 2 +- packages/primitives/Cargo.toml | 2 +- packages/tracker-client/Cargo.toml | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6573dcd0f..7bd2d7037 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -591,7 +591,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_repr", - "thiserror 1.0.69", + "thiserror 2.0.6", "tokio", "torrust-tracker-configuration", "torrust-tracker-located-error", @@ -4018,7 +4018,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_json", - "thiserror 1.0.69", + "thiserror 2.0.6", "tokio", "torrust-tracker-configuration", "tracing", @@ -4045,7 +4045,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 1.0.69", + "thiserror 2.0.6", "toml", "torrust-tracker-located-error", "url", @@ -4057,14 +4057,14 @@ name = "torrust-tracker-contrib-bencode" version = "3.0.0-develop" dependencies = [ "criterion", - "thiserror 1.0.69", + "thiserror 2.0.6", ] [[package]] name = "torrust-tracker-located-error" version = "3.0.0-develop" dependencies = [ - "thiserror 1.0.69", + "thiserror 2.0.6", "tracing", ] @@ -4079,7 +4079,7 @@ dependencies = [ "serde", "tdyne-peer-id", "tdyne-peer-id-registry", - "thiserror 1.0.69", + "thiserror 2.0.6", "zerocopy", ] diff --git a/console/tracker-client/Cargo.toml b/console/tracker-client/Cargo.toml index c9e951003..4db6702cb 100644 --- a/console/tracker-client/Cargo.toml +++ b/console/tracker-client/Cargo.toml @@ -28,7 +28,7 @@ serde = { version = "1", features = ["derive"] } serde_bencode = "0" serde_bytes = "0" serde_json = { version = "1", features = ["preserve_order"] } -thiserror = "1" +thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../../packages/configuration" } tracing = "0" diff --git a/contrib/bencode/Cargo.toml b/contrib/bencode/Cargo.toml index e25a9b64f..f6355b6fc 100644 --- a/contrib/bencode/Cargo.toml +++ b/contrib/bencode/Cargo.toml @@ -16,7 +16,7 @@ rust-version.workspace = true version.workspace = true [dependencies] -thiserror = "1" +thiserror = "2" [dev-dependencies] criterion = "0" diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 8706679f6..05789b882 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -21,7 +21,7 @@ figment = { version = "0", features = ["env", "test", "toml"] } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } serde_with = "3" -thiserror = "1" +thiserror = "2" toml = "0" torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } url = "2" diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index 637ea3055..29b0dfb2c 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -18,4 +18,4 @@ version.workspace = true tracing = "0" [dev-dependencies] -thiserror = "1" +thiserror = "2" diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index 4d18bdca6..66b81d65d 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -22,5 +22,5 @@ derive_more = { version = "1", features = ["constructor"] } serde = { version = "1", features = ["derive"] } tdyne-peer-id = "1" tdyne-peer-id-registry = "0" -thiserror = "1" +thiserror = "2" zerocopy = "0.7" diff --git a/packages/tracker-client/Cargo.toml b/packages/tracker-client/Cargo.toml index 52b0be639..67a4c767a 100644 --- a/packages/tracker-client/Cargo.toml +++ b/packages/tracker-client/Cargo.toml @@ -25,7 +25,7 @@ serde = { version = "1", features = ["derive"] } serde_bencode = "0" serde_bytes = "0" serde_repr = "0" -thiserror = "1" +thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } From 286fe022f7186ed9376878774e42fe167cffb7b8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 13 Dec 2024 17:48:05 +0000 Subject: [PATCH 0539/1297] feat: [#1128] add new metric UDP total requests In the stats enpoint the new values are: - udp4_requests - udp6_requests --- src/core/services/statistics/mod.rs | 2 + src/core/statistics.rs | 27 +++++++++++ .../apis/v1/context/stats/resources.rs | 45 ++++++++++++------- .../apis/v1/context/stats/responses.rs | 2 + src/servers/udp/server/launcher.rs | 13 +++++- .../servers/api/v1/contract/context/stats.rs | 2 + 6 files changed, 73 insertions(+), 18 deletions(-) diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 0e7735be2..4d9035481 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -73,10 +73,12 @@ pub async fn get_metrics(tracker: Arc) -> TrackerMetrics { tcp6_connections_handled: stats.tcp6_connections_handled, tcp6_announces_handled: stats.tcp6_announces_handled, tcp6_scrapes_handled: stats.tcp6_scrapes_handled, + udp4_requests: stats.udp4_requests, udp4_connections_handled: stats.udp4_connections_handled, udp4_announces_handled: stats.udp4_announces_handled, udp4_scrapes_handled: stats.udp4_scrapes_handled, udp4_errors_handled: stats.udp4_errors_handled, + udp6_requests: stats.udp6_requests, udp6_connections_handled: stats.udp6_connections_handled, udp6_announces_handled: stats.udp6_announces_handled, udp6_scrapes_handled: stats.udp6_scrapes_handled, diff --git a/src/core/statistics.rs b/src/core/statistics.rs index b106b2691..37d3c8822 100644 --- a/src/core/statistics.rs +++ b/src/core/statistics.rs @@ -44,10 +44,12 @@ pub enum Event { Tcp4Scrape, Tcp6Announce, Tcp6Scrape, + Udp4Request, Udp4Connect, Udp4Announce, Udp4Scrape, Udp4Error, + Udp6Request, Udp6Connect, Udp6Announce, Udp6Scrape, @@ -72,12 +74,16 @@ pub struct Metrics { pub tcp4_announces_handled: u64, /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. pub tcp4_scrapes_handled: u64, + /// Total number of TCP (HTTP tracker) connections from IPv6 peers. pub tcp6_connections_handled: u64, /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. pub tcp6_announces_handled: u64, /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. pub tcp6_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) requests from IPv4 peers. + pub udp4_requests: u64, /// Total number of UDP (UDP tracker) connections from IPv4 peers. pub udp4_connections_handled: u64, /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. @@ -86,6 +92,9 @@ pub struct Metrics { pub udp4_scrapes_handled: u64, /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. pub udp4_errors_handled: u64, + + /// Total number of UDP (UDP tracker) requests from IPv4 peers. + pub udp6_requests: u64, /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. pub udp6_connections_handled: u64, /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. @@ -165,6 +174,9 @@ async fn event_handler(event: Event, stats_repository: &Repo) { } // UDP4 + Event::Udp4Request => { + stats_repository.increase_udp4_requests().await; + } Event::Udp4Connect => { stats_repository.increase_udp4_connections().await; } @@ -179,6 +191,9 @@ async fn event_handler(event: Event, stats_repository: &Repo) { } // UDP6 + Event::Udp6Request => { + stats_repository.increase_udp6_requests().await; + } Event::Udp6Connect => { stats_repository.increase_udp6_connections().await; } @@ -276,6 +291,12 @@ impl Repo { drop(stats_lock); } + pub async fn increase_udp4_requests(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_requests += 1; + drop(stats_lock); + } + pub async fn increase_udp4_connections(&self) { let mut stats_lock = self.stats.write().await; stats_lock.udp4_connections_handled += 1; @@ -300,6 +321,12 @@ impl Repo { drop(stats_lock); } + pub async fn increase_udp6_requests(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_requests += 1; + drop(stats_lock); + } + pub async fn increase_udp6_connections(&self) { let mut stats_lock = self.stats.write().await; stats_lock.udp6_connections_handled += 1; diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index de6f6ca89..5a70e4aed 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -26,12 +26,16 @@ pub struct Stats { pub tcp4_announces_handled: u64, /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. pub tcp4_scrapes_handled: u64, + /// Total number of TCP (HTTP tracker) connections from IPv6 peers. pub tcp6_connections_handled: u64, /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. pub tcp6_announces_handled: u64, /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. pub tcp6_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) requests from IPv4 peers. + pub udp4_requests: u64, /// Total number of UDP (UDP tracker) connections from IPv4 peers. pub udp4_connections_handled: u64, /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. @@ -40,6 +44,9 @@ pub struct Stats { pub udp4_scrapes_handled: u64, /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. pub udp4_errors_handled: u64, + + /// Total number of UDP (UDP tracker) requests from IPv6 peers. + pub udp6_requests: u64, /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. pub udp6_connections_handled: u64, /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. @@ -63,10 +70,12 @@ impl From for Stats { tcp6_connections_handled: metrics.protocol_metrics.tcp6_connections_handled, tcp6_announces_handled: metrics.protocol_metrics.tcp6_announces_handled, tcp6_scrapes_handled: metrics.protocol_metrics.tcp6_scrapes_handled, + udp4_requests: metrics.protocol_metrics.udp4_requests, udp4_connections_handled: metrics.protocol_metrics.udp4_connections_handled, udp4_announces_handled: metrics.protocol_metrics.udp4_announces_handled, udp4_scrapes_handled: metrics.protocol_metrics.udp4_scrapes_handled, udp4_errors_handled: metrics.protocol_metrics.udp4_errors_handled, + udp6_requests: metrics.protocol_metrics.udp6_requests, udp6_connections_handled: metrics.protocol_metrics.udp6_connections_handled, udp6_announces_handled: metrics.protocol_metrics.udp6_announces_handled, udp6_scrapes_handled: metrics.protocol_metrics.udp6_scrapes_handled, @@ -100,14 +109,16 @@ mod tests { tcp6_connections_handled: 8, tcp6_announces_handled: 9, tcp6_scrapes_handled: 10, - udp4_connections_handled: 11, - udp4_announces_handled: 12, - udp4_scrapes_handled: 13, - udp4_errors_handled: 14, - udp6_connections_handled: 15, - udp6_announces_handled: 16, - udp6_scrapes_handled: 17, - udp6_errors_handled: 18 + udp4_requests: 11, + udp4_connections_handled: 12, + udp4_announces_handled: 13, + udp4_scrapes_handled: 14, + udp4_errors_handled: 15, + udp6_requests: 16, + udp6_connections_handled: 17, + udp6_announces_handled: 18, + udp6_scrapes_handled: 19, + udp6_errors_handled: 20 } }), Stats { @@ -121,14 +132,16 @@ mod tests { tcp6_connections_handled: 8, tcp6_announces_handled: 9, tcp6_scrapes_handled: 10, - udp4_connections_handled: 11, - udp4_announces_handled: 12, - udp4_scrapes_handled: 13, - udp4_errors_handled: 14, - udp6_connections_handled: 15, - udp6_announces_handled: 16, - udp6_scrapes_handled: 17, - udp6_errors_handled: 18 + udp4_requests: 11, + udp4_connections_handled: 12, + udp4_announces_handled: 13, + udp4_scrapes_handled: 14, + udp4_errors_handled: 15, + udp6_requests: 16, + udp6_connections_handled: 17, + udp6_announces_handled: 18, + udp6_scrapes_handled: 19, + udp6_errors_handled: 20 } ); } diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index 4fd8be94f..3358a70cf 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -47,6 +47,7 @@ pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { tracker_metrics.protocol_metrics.tcp6_scrapes_handled )); + lines.push(format!("udp4_requests {}", tracker_metrics.protocol_metrics.udp4_requests)); lines.push(format!( "udp4_connections_handled {}", tracker_metrics.protocol_metrics.udp4_connections_handled @@ -64,6 +65,7 @@ pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { tracker_metrics.protocol_metrics.udp4_errors_handled )); + lines.push(format!("udp6_requests {}", tracker_metrics.protocol_metrics.udp6_requests)); lines.push(format!( "udp6_connections_handled {}", tracker_metrics.protocol_metrics.udp6_connections_handled diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index c8bac8098..6bd503e61 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -1,4 +1,4 @@ -use std::net::SocketAddr; +use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use std::time::Duration; @@ -11,7 +11,7 @@ use tracing::instrument; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; -use crate::core::Tracker; +use crate::core::{statistics, Tracker}; use crate::servers::logging::STARTED_ON; use crate::servers::registar::ServiceHealthCheckJob; use crate::servers::signals::{shutdown_signal_with_message, Halted}; @@ -140,6 +140,15 @@ impl Launcher { } }; + match req.from.ip() { + IpAddr::V4(_) => { + tracker.send_stats_event(statistics::Event::Udp4Request).await; + } + IpAddr::V6(_) => { + tracker.send_stats_event(statistics::Event::Udp6Request).await; + } + } + // We spawn the new task even if there active requests buffer is // full. This could seem counterintuitive because we are accepting // more request and consuming more memory even if the server is diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index 463dc563e..465b7b73a 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -40,10 +40,12 @@ async fn should_allow_getting_tracker_statistics() { tcp6_connections_handled: 0, tcp6_announces_handled: 0, tcp6_scrapes_handled: 0, + udp4_requests: 0, udp4_connections_handled: 0, udp4_announces_handled: 0, udp4_scrapes_handled: 0, udp4_errors_handled: 0, + udp6_requests: 0, udp6_connections_handled: 0, udp6_announces_handled: 0, udp6_scrapes_handled: 0, From 9499fd8924a926eece3a2774907ee8840fe96170 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 13 Dec 2024 18:21:49 +0000 Subject: [PATCH 0540/1297] feat: [#1128] add new metric UDP total responses In the stats enpoint the new values are: - udp4_responses - udp6_responses --- src/core/services/statistics/mod.rs | 2 ++ src/core/statistics.rs | 26 +++++++++++++- .../apis/v1/context/stats/resources.rs | 34 ++++++++++++------- .../apis/v1/context/stats/responses.rs | 2 ++ src/servers/udp/server/processor.rs | 13 +++++-- .../servers/api/v1/contract/context/stats.rs | 2 ++ 6 files changed, 64 insertions(+), 15 deletions(-) diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 4d9035481..a037e53b9 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -77,11 +77,13 @@ pub async fn get_metrics(tracker: Arc) -> TrackerMetrics { udp4_connections_handled: stats.udp4_connections_handled, udp4_announces_handled: stats.udp4_announces_handled, udp4_scrapes_handled: stats.udp4_scrapes_handled, + udp4_responses: stats.udp4_responses, udp4_errors_handled: stats.udp4_errors_handled, udp6_requests: stats.udp6_requests, udp6_connections_handled: stats.udp6_connections_handled, udp6_announces_handled: stats.udp6_announces_handled, udp6_scrapes_handled: stats.udp6_scrapes_handled, + udp6_responses: stats.udp6_responses, udp6_errors_handled: stats.udp6_errors_handled, }, } diff --git a/src/core/statistics.rs b/src/core/statistics.rs index 37d3c8822..2df88ae97 100644 --- a/src/core/statistics.rs +++ b/src/core/statistics.rs @@ -48,11 +48,13 @@ pub enum Event { Udp4Connect, Udp4Announce, Udp4Scrape, + Udp4Response, Udp4Error, Udp6Request, Udp6Connect, Udp6Announce, Udp6Scrape, + Udp6Response, Udp6Error, } @@ -90,10 +92,12 @@ pub struct Metrics { pub udp4_announces_handled: u64, /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. pub udp4_scrapes_handled: u64, + /// Total number of UDP (UDP tracker) responses from IPv4 peers. + pub udp4_responses: u64, /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. pub udp4_errors_handled: u64, - /// Total number of UDP (UDP tracker) requests from IPv4 peers. + /// Total number of UDP (UDP tracker) requests from IPv6 peers. pub udp6_requests: u64, /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. pub udp6_connections_handled: u64, @@ -101,6 +105,8 @@ pub struct Metrics { pub udp6_announces_handled: u64, /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. pub udp6_scrapes_handled: u64, + /// Total number of UDP (UDP tracker) responses from IPv6 peers. + pub udp6_responses: u64, /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. pub udp6_errors_handled: u64, } @@ -186,6 +192,9 @@ async fn event_handler(event: Event, stats_repository: &Repo) { Event::Udp4Scrape => { stats_repository.increase_udp4_scrapes().await; } + Event::Udp4Response => { + stats_repository.increase_udp4_responses().await; + } Event::Udp4Error => { stats_repository.increase_udp4_errors().await; } @@ -203,6 +212,9 @@ async fn event_handler(event: Event, stats_repository: &Repo) { Event::Udp6Scrape => { stats_repository.increase_udp6_scrapes().await; } + Event::Udp6Response => { + stats_repository.increase_udp6_responses().await; + } Event::Udp6Error => { stats_repository.increase_udp6_errors().await; } @@ -315,6 +327,12 @@ impl Repo { drop(stats_lock); } + pub async fn increase_udp4_responses(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_responses += 1; + drop(stats_lock); + } + pub async fn increase_udp4_errors(&self) { let mut stats_lock = self.stats.write().await; stats_lock.udp4_errors_handled += 1; @@ -345,6 +363,12 @@ impl Repo { drop(stats_lock); } + pub async fn increase_udp6_responses(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_responses += 1; + drop(stats_lock); + } + pub async fn increase_udp6_errors(&self) { let mut stats_lock = self.stats.write().await; stats_lock.udp6_errors_handled += 1; diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index 5a70e4aed..21a0dc04a 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -42,6 +42,8 @@ pub struct Stats { pub udp4_announces_handled: u64, /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. pub udp4_scrapes_handled: u64, + /// Total number of UDP (UDP tracker) responses from IPv4 peers. + pub udp4_responses: u64, /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. pub udp4_errors_handled: u64, @@ -53,6 +55,8 @@ pub struct Stats { pub udp6_announces_handled: u64, /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. pub udp6_scrapes_handled: u64, + /// Total number of UDP (UDP tracker) responses from IPv6 peers. + pub udp6_responses: u64, /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. pub udp6_errors_handled: u64, } @@ -74,11 +78,13 @@ impl From for Stats { udp4_connections_handled: metrics.protocol_metrics.udp4_connections_handled, udp4_announces_handled: metrics.protocol_metrics.udp4_announces_handled, udp4_scrapes_handled: metrics.protocol_metrics.udp4_scrapes_handled, + udp4_responses: metrics.protocol_metrics.udp4_responses, udp4_errors_handled: metrics.protocol_metrics.udp4_errors_handled, udp6_requests: metrics.protocol_metrics.udp6_requests, udp6_connections_handled: metrics.protocol_metrics.udp6_connections_handled, udp6_announces_handled: metrics.protocol_metrics.udp6_announces_handled, udp6_scrapes_handled: metrics.protocol_metrics.udp6_scrapes_handled, + udp6_responses: metrics.protocol_metrics.udp6_responses, udp6_errors_handled: metrics.protocol_metrics.udp6_errors_handled, } } @@ -113,12 +119,14 @@ mod tests { udp4_connections_handled: 12, udp4_announces_handled: 13, udp4_scrapes_handled: 14, - udp4_errors_handled: 15, - udp6_requests: 16, - udp6_connections_handled: 17, - udp6_announces_handled: 18, - udp6_scrapes_handled: 19, - udp6_errors_handled: 20 + udp4_responses: 15, + udp4_errors_handled: 16, + udp6_requests: 17, + udp6_connections_handled: 18, + udp6_announces_handled: 19, + udp6_scrapes_handled: 20, + udp6_responses: 21, + udp6_errors_handled: 22 } }), Stats { @@ -136,12 +144,14 @@ mod tests { udp4_connections_handled: 12, udp4_announces_handled: 13, udp4_scrapes_handled: 14, - udp4_errors_handled: 15, - udp6_requests: 16, - udp6_connections_handled: 17, - udp6_announces_handled: 18, - udp6_scrapes_handled: 19, - udp6_errors_handled: 20 + udp4_responses: 15, + udp4_errors_handled: 16, + udp6_requests: 17, + udp6_connections_handled: 18, + udp6_announces_handled: 19, + udp6_scrapes_handled: 20, + udp6_responses: 21, + udp6_errors_handled: 22 } ); } diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index 3358a70cf..e4d5b577d 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -60,6 +60,7 @@ pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { "udp4_scrapes_handled {}", tracker_metrics.protocol_metrics.udp4_scrapes_handled )); + lines.push(format!("udp4_responses {}", tracker_metrics.protocol_metrics.udp4_responses)); lines.push(format!( "udp4_errors_handled {}", tracker_metrics.protocol_metrics.udp4_errors_handled @@ -78,6 +79,7 @@ pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { "udp6_scrapes_handled {}", tracker_metrics.protocol_metrics.udp6_scrapes_handled )); + lines.push(format!("udp6_responses {}", tracker_metrics.protocol_metrics.udp6_responses)); lines.push(format!( "udp6_errors_handled {}", tracker_metrics.protocol_metrics.udp6_errors_handled diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 703367f35..fc39f28b9 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -1,12 +1,12 @@ use std::io::Cursor; -use std::net::SocketAddr; +use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::Response; use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; -use crate::core::Tracker; +use crate::core::{statistics, Tracker}; use crate::servers::udp::handlers::CookieTimeValues; use crate::servers::udp::{handlers, RawRequest}; @@ -64,6 +64,15 @@ impl Processor { } else { tracing::debug!(%bytes_count, %sent_bytes, "sent {response_type}"); } + + match target.ip() { + IpAddr::V4(_) => { + self.tracker.send_stats_event(statistics::Event::Udp4Response).await; + } + IpAddr::V6(_) => { + self.tracker.send_stats_event(statistics::Event::Udp6Response).await; + } + } } Err(error) => tracing::warn!(%bytes_count, %error, ?payload, "failed to send"), }; diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index 465b7b73a..f2dbd2118 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -44,11 +44,13 @@ async fn should_allow_getting_tracker_statistics() { udp4_connections_handled: 0, udp4_announces_handled: 0, udp4_scrapes_handled: 0, + udp4_responses: 0, udp4_errors_handled: 0, udp6_requests: 0, udp6_connections_handled: 0, udp6_announces_handled: 0, udp6_scrapes_handled: 0, + udp6_responses: 0, udp6_errors_handled: 0, }, ) From 6ca82e9d0661a829cebd90243ba932e1affeeb85 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 13 Dec 2024 18:39:34 +0000 Subject: [PATCH 0541/1297] feat: [#1128] add new metric UDP total requests aborted --- src/core/services/statistics/mod.rs | 3 + src/core/statistics.rs | 15 +++++ .../apis/v1/context/stats/resources.rs | 60 +++++++++++-------- .../apis/v1/context/stats/responses.rs | 5 ++ src/servers/udp/server/launcher.rs | 7 ++- src/servers/udp/server/request_buffer.rs | 11 +++- .../servers/api/v1/contract/context/stats.rs | 3 + 7 files changed, 77 insertions(+), 27 deletions(-) diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index a037e53b9..82ff359ab 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -67,12 +67,15 @@ pub async fn get_metrics(tracker: Arc) -> TrackerMetrics { TrackerMetrics { torrents_metrics, protocol_metrics: Metrics { + // TCP tcp4_connections_handled: stats.tcp4_connections_handled, tcp4_announces_handled: stats.tcp4_announces_handled, tcp4_scrapes_handled: stats.tcp4_scrapes_handled, tcp6_connections_handled: stats.tcp6_connections_handled, tcp6_announces_handled: stats.tcp6_announces_handled, tcp6_scrapes_handled: stats.tcp6_scrapes_handled, + // UDP + udp_requests_aborted: stats.udp_requests_aborted, udp4_requests: stats.udp4_requests, udp4_connections_handled: stats.udp4_connections_handled, udp4_announces_handled: stats.udp4_announces_handled, diff --git a/src/core/statistics.rs b/src/core/statistics.rs index 2df88ae97..6df7c4961 100644 --- a/src/core/statistics.rs +++ b/src/core/statistics.rs @@ -44,6 +44,7 @@ pub enum Event { Tcp4Scrape, Tcp6Announce, Tcp6Scrape, + Udp4RequestAborted, Udp4Request, Udp4Connect, Udp4Announce, @@ -84,6 +85,9 @@ pub struct Metrics { /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. pub tcp6_scrapes_handled: u64, + /// Total number of UDP (UDP tracker) requests aborted. + pub udp_requests_aborted: u64, + /// Total number of UDP (UDP tracker) requests from IPv4 peers. pub udp4_requests: u64, /// Total number of UDP (UDP tracker) connections from IPv4 peers. @@ -179,6 +183,11 @@ async fn event_handler(event: Event, stats_repository: &Repo) { stats_repository.increase_tcp6_connections().await; } + // UDP + Event::Udp4RequestAborted => { + stats_repository.increase_udp_requests_aborted().await; + } + // UDP4 Event::Udp4Request => { stats_repository.increase_udp4_requests().await; @@ -303,6 +312,12 @@ impl Repo { drop(stats_lock); } + pub async fn increase_udp_requests_aborted(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp_requests_aborted += 1; + drop(stats_lock); + } + pub async fn increase_udp4_requests(&self) { let mut stats_lock = self.stats.write().await; stats_lock.udp4_requests += 1; diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index 21a0dc04a..e7057f30a 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -34,6 +34,9 @@ pub struct Stats { /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. pub tcp6_scrapes_handled: u64, + /// Total number of UDP (UDP tracker) requests aborted. + pub udp_requests_aborted: u64, + /// Total number of UDP (UDP tracker) requests from IPv4 peers. pub udp4_requests: u64, /// Total number of UDP (UDP tracker) connections from IPv4 peers. @@ -68,12 +71,15 @@ impl From for Stats { seeders: metrics.torrents_metrics.complete, completed: metrics.torrents_metrics.downloaded, leechers: metrics.torrents_metrics.incomplete, + // TCP tcp4_connections_handled: metrics.protocol_metrics.tcp4_connections_handled, tcp4_announces_handled: metrics.protocol_metrics.tcp4_announces_handled, tcp4_scrapes_handled: metrics.protocol_metrics.tcp4_scrapes_handled, tcp6_connections_handled: metrics.protocol_metrics.tcp6_connections_handled, tcp6_announces_handled: metrics.protocol_metrics.tcp6_announces_handled, tcp6_scrapes_handled: metrics.protocol_metrics.tcp6_scrapes_handled, + // UDP + udp_requests_aborted: metrics.protocol_metrics.udp_requests_aborted, udp4_requests: metrics.protocol_metrics.udp4_requests, udp4_connections_handled: metrics.protocol_metrics.udp4_connections_handled, udp4_announces_handled: metrics.protocol_metrics.udp4_announces_handled, @@ -109,24 +115,27 @@ mod tests { torrents: 4 }, protocol_metrics: Metrics { + // TCP tcp4_connections_handled: 5, tcp4_announces_handled: 6, tcp4_scrapes_handled: 7, tcp6_connections_handled: 8, tcp6_announces_handled: 9, tcp6_scrapes_handled: 10, - udp4_requests: 11, - udp4_connections_handled: 12, - udp4_announces_handled: 13, - udp4_scrapes_handled: 14, - udp4_responses: 15, - udp4_errors_handled: 16, - udp6_requests: 17, - udp6_connections_handled: 18, - udp6_announces_handled: 19, - udp6_scrapes_handled: 20, - udp6_responses: 21, - udp6_errors_handled: 22 + // UDP + udp_requests_aborted: 11, + udp4_requests: 12, + udp4_connections_handled: 13, + udp4_announces_handled: 14, + udp4_scrapes_handled: 15, + udp4_responses: 16, + udp4_errors_handled: 17, + udp6_requests: 18, + udp6_connections_handled: 19, + udp6_announces_handled: 20, + udp6_scrapes_handled: 21, + udp6_responses: 22, + udp6_errors_handled: 23 } }), Stats { @@ -134,24 +143,27 @@ mod tests { seeders: 1, completed: 2, leechers: 3, + // TCP tcp4_connections_handled: 5, tcp4_announces_handled: 6, tcp4_scrapes_handled: 7, tcp6_connections_handled: 8, tcp6_announces_handled: 9, tcp6_scrapes_handled: 10, - udp4_requests: 11, - udp4_connections_handled: 12, - udp4_announces_handled: 13, - udp4_scrapes_handled: 14, - udp4_responses: 15, - udp4_errors_handled: 16, - udp6_requests: 17, - udp6_connections_handled: 18, - udp6_announces_handled: 19, - udp6_scrapes_handled: 20, - udp6_responses: 21, - udp6_errors_handled: 22 + // UDP + udp_requests_aborted: 11, + udp4_requests: 12, + udp4_connections_handled: 13, + udp4_announces_handled: 14, + udp4_scrapes_handled: 15, + udp4_responses: 16, + udp4_errors_handled: 17, + udp6_requests: 18, + udp6_connections_handled: 19, + udp6_announces_handled: 20, + udp6_scrapes_handled: 21, + udp6_responses: 22, + udp6_errors_handled: 23 } ); } diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index e4d5b577d..6b214d0c9 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -47,6 +47,11 @@ pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { tracker_metrics.protocol_metrics.tcp6_scrapes_handled )); + lines.push(format!( + "udp_requests_aborted {}", + tracker_metrics.protocol_metrics.udp_requests_aborted + )); + lines.push(format!("udp4_requests {}", tracker_metrics.protocol_metrics.udp4_requests)); lines.push(format!( "udp4_connections_handled {}", diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 6bd503e61..d6827346d 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -166,7 +166,12 @@ impl Launcher { continue; } - active_requests.force_push(abort_handle, &local_addr).await; + let old_request_aborted = active_requests.force_push(abort_handle, &local_addr).await; + + if old_request_aborted { + // Evicted task from active requests buffer was aborted. + tracker.send_stats_event(statistics::Event::Udp4RequestAborted).await; + } } else { tokio::task::yield_now().await; diff --git a/src/servers/udp/server/request_buffer.rs b/src/servers/udp/server/request_buffer.rs index ffbd9565d..03cb6040f 100644 --- a/src/servers/udp/server/request_buffer.rs +++ b/src/servers/udp/server/request_buffer.rs @@ -41,6 +41,8 @@ impl ActiveRequests { /// 1. Removing finished tasks. /// 2. Removing the oldest unfinished task if no finished tasks are found. /// + /// Returns `true` if a task was removed, `false` otherwise. + /// /// # Panics /// /// This method will panic if it cannot make space for adding a new handle. @@ -49,17 +51,19 @@ impl ActiveRequests { /// /// * `abort_handle` - The `AbortHandle` for the UDP request processor task. /// * `local_addr` - A string slice representing the local address for logging. - pub async fn force_push(&mut self, new_task: AbortHandle, local_addr: &str) { + pub async fn force_push(&mut self, new_task: AbortHandle, local_addr: &str) -> bool { // Attempt to add the new handle to the buffer. match self.rb.try_push(new_task) { Ok(()) => { // Successfully added the task, no further action needed. + false } Err(new_task) => { // Buffer is full, attempt to make space. let mut finished: u64 = 0; let mut unfinished_task = None; + let mut old_task_aborted = false; for old_task in self.rb.pop_iter() { // We found a finished tasks ... increase the counter and @@ -96,6 +100,7 @@ impl ActiveRequests { if finished == 0 { // We make place aborting this task. old_task.abort(); + old_task_aborted = true; tracing::warn!( target: UDP_TRACKER_LOG_TARGET, @@ -134,7 +139,9 @@ impl ActiveRequests { if !new_task.is_finished() { self.rb.try_push(new_task).expect("it should have space for this new task."); } + + old_task_aborted } - }; + } } } diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index f2dbd2118..7853450e2 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -34,12 +34,15 @@ async fn should_allow_getting_tracker_statistics() { seeders: 1, completed: 0, leechers: 0, + // TCP tcp4_connections_handled: 0, tcp4_announces_handled: 0, tcp4_scrapes_handled: 0, tcp6_connections_handled: 0, tcp6_announces_handled: 0, tcp6_scrapes_handled: 0, + // UDP + udp_requests_aborted: 0, udp4_requests: 0, udp4_connections_handled: 0, udp4_announces_handled: 0, From 87401e894d8720b5e25a735cb822f58b2c92be94 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 9 Dec 2024 09:57:19 +0000 Subject: [PATCH 0542/1297] chore(deps): add dependency bloom --- Cargo.lock | 16 ++++++++++++++++ Cargo.toml | 1 + 2 files changed, 17 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 7bd2d7037..c9f388f48 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -547,6 +547,12 @@ dependencies = [ "syn 2.0.90", ] +[[package]] +name = "bit-vec" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b4ff8b16e6076c3e14220b39fbc1fabb6737522281a388998046859400895f" + [[package]] name = "bitflags" version = "2.6.0" @@ -634,6 +640,15 @@ dependencies = [ "piper", ] +[[package]] +name = "bloom" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d00ac8e5056d6d65376a3c1aa5c7c34850d6949ace17f0266953a254eb3d6fe8" +dependencies = [ + "bit-vec", +] + [[package]] name = "blowfish" version = "0.9.1" @@ -3949,6 +3964,7 @@ dependencies = [ "bittorrent-http-protocol", "bittorrent-primitives", "bittorrent-tracker-client", + "bloom", "blowfish", "camino", "chrono", diff --git a/Cargo.toml b/Cargo.toml index f512dca92..6832f17f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ axum-server = { version = "0", features = ["tls-rustls-no-provider"] } bittorrent-http-protocol = { version = "3.0.0-develop", path = "packages/http-protocol" } bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } +bloom = "0.3.2" blowfish = "0" camino = { version = "1", features = ["serde", "serde1"] } chrono = { version = "0", default-features = false, features = ["clock"] } From 10f9bdaacf6b156da075224737f6f1ab83c84f53 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 9 Dec 2024 12:09:03 +0000 Subject: [PATCH 0543/1297] feat: [#1096] ban client IP when exceeds connection ID errors limit The life demo tracker is receiving many UDP requests with a wrong conenctions IDs. Errors are logged (write disk) and that decreases the tracker performance. This counts errors and bans Ips after 10 errors for 2 minutes. We use two levels of counters. 1. First level: A Counting Bloom Filter: fast and low memory consumption but innacurate (False Positives). 2. HashMap: Exact Counter for Ips. CBFs are fast and use litle memory but they are also innaccurate. They have False Positives meaning some IPs would be banned only becuase there are bucket colissions (IPs sharing the same counter). To avoid banning IPs incorrectly we decided to introduce a second counter, which is a HashMap that counts error precisely. IPs are only banned when this counter reaches the limit (over 10 errors). We keep the CBF as a first level filter. It's a fast-check IP filter without affecting tracker's performance. When the IP is banned according to the first filter we double-check in the HashMap. CBF is faster than checking always for banned IPs against the HashMap. This solution should be good if the number of IPs is low. We have to find another solution anyway for IPv6 where is cheaper to own a range of IPs. --- cSpell.json | 1 + src/servers/udp/handlers.rs | 16 ++- src/servers/udp/server/banning.rs | 150 ++++++++++++++++++++++++++++ src/servers/udp/server/launcher.rs | 62 +++++++++--- src/servers/udp/server/mod.rs | 1 + src/servers/udp/server/processor.rs | 8 +- tests/servers/udp/contract.rs | 87 ++++++++++++---- 7 files changed, 288 insertions(+), 37 deletions(-) create mode 100644 src/servers/udp/server/banning.rs diff --git a/cSpell.json b/cSpell.json index 090a2b0e3..a21e69b9f 100644 --- a/cSpell.json +++ b/cSpell.json @@ -5,6 +5,7 @@ "alekitto", "appuser", "Arvid", + "ASMS", "asyn", "autoclean", "AUTOINCREMENT", diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index af22b263d..1fb450e1a 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -11,12 +11,14 @@ use aquatic_udp_protocol::{ ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; use bittorrent_primitives::info_hash::InfoHash; +use tokio::sync::RwLock; use torrust_tracker_clock::clock::Time as _; use tracing::{instrument, Level}; use uuid::Uuid; use zerocopy::network_endian::I32; use super::connection_cookie::{check, make}; +use super::server::banning::BanService; use super::RawRequest; use crate::core::{statistics, PeersWanted, Tracker}; use crate::servers::udp::error::Error; @@ -51,12 +53,13 @@ impl CookieTimeValues { /// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. -#[instrument(fields(request_id), skip(udp_request, tracker, cookie_time_values), ret(level = Level::TRACE))] +#[instrument(fields(request_id), skip(udp_request, tracker, cookie_time_values, ban_service), ret(level = Level::TRACE))] pub(crate) async fn handle_packet( udp_request: RawRequest, tracker: &Tracker, local_addr: SocketAddr, cookie_time_values: CookieTimeValues, + ban_service: Arc>, ) -> Response { tracing::Span::current().record("request_id", Uuid::new_v4().to_string()); tracing::debug!("Handling Packets: {udp_request:?}"); @@ -68,6 +71,17 @@ pub(crate) async fn handle_packet( Ok(request) => match handle_request(request, udp_request.from, tracker, cookie_time_values.clone()).await { Ok(response) => return response, Err((e, transaction_id)) => { + match &e { + Error::CookieValueNotNormal { .. } + | Error::CookieValueExpired { .. } + | Error::CookieValueFromFuture { .. } => { + // code-review: should we include `RequestParseError` and `BadRequest`? + let mut ban_service = ban_service.write().await; + ban_service.increase_counter(&udp_request.from.ip()); + } + _ => {} + } + handle_error( udp_request.from, tracker, diff --git a/src/servers/udp/server/banning.rs b/src/servers/udp/server/banning.rs new file mode 100644 index 000000000..df236820c --- /dev/null +++ b/src/servers/udp/server/banning.rs @@ -0,0 +1,150 @@ +//! Banning service for UDP tracker. +//! +//! It bans clients that send invalid connection id's. +//! +//! It uses two levels of filtering: +//! +//! 1. First, tt uses a Counting Bloom Filter to keep track of the number of +//! connection ID errors per ip. That means there can be false positives, but +//! not false negatives. 1 out of 100000 requests will be a false positive +//! and the client will be banned and not receive a response. +//! 2. Since we want to avoid false positives (banning a client that is not +//! sending invalid connection id's), we use a `HashMap` to keep track of the +//! exact number of connection ID errors per ip. +//! +//! This two level filtering is to avoid false positives. It has the advantage +//! of being fast by using a Counting Bloom Filter and not having false +//! negatives at the cost of increasing the memory usage. +use std::collections::HashMap; +use std::net::IpAddr; + +use bloom::{CountingBloomFilter, ASMS}; +use tokio::time::Instant; +use url::Url; + +use crate::servers::udp::UDP_TRACKER_LOG_TARGET; + +pub struct BanService { + max_connection_id_errors_per_ip: u32, + fuzzy_error_counter: CountingBloomFilter, + accurate_error_counter: HashMap, + local_addr: Url, + last_connection_id_errors_reset: Instant, +} + +impl BanService { + #[must_use] + pub fn new(max_connection_id_errors_per_ip: u32, local_addr: Url) -> Self { + Self { + max_connection_id_errors_per_ip, + local_addr, + fuzzy_error_counter: CountingBloomFilter::with_rate(4, 0.01, 100), + accurate_error_counter: HashMap::new(), + last_connection_id_errors_reset: tokio::time::Instant::now(), + } + } + + pub fn increase_counter(&mut self, ip: &IpAddr) { + self.fuzzy_error_counter.insert(&ip.to_string()); + *self.accurate_error_counter.entry(*ip).or_insert(0) += 1; + } + + #[must_use] + pub fn get_count(&self, ip: &IpAddr) -> Option { + self.accurate_error_counter.get(ip).copied() + } + + #[must_use] + pub fn get_estimate_count(&self, ip: &IpAddr) -> u32 { + self.fuzzy_error_counter.estimate_count(&ip.to_string()) + } + + /// Returns true if the given ip address is banned. + #[must_use] + pub fn is_banned(&self, ip: &IpAddr) -> bool { + // First check if the ip is in the bloom filter (fast check) + if self.fuzzy_error_counter.estimate_count(&ip.to_string()) <= self.max_connection_id_errors_per_ip { + return false; + } + + // Check with the exact counter (to avoid false positives) + match self.get_count(ip) { + Some(count) => count > self.max_connection_id_errors_per_ip, + None => false, + } + } + + /// Resets the filters and updates the reset timestamp. + pub fn reset_bans(&mut self) { + self.fuzzy_error_counter.clear(); + + self.accurate_error_counter.clear(); + + self.last_connection_id_errors_reset = Instant::now(); + + let local_addr = self.local_addr.to_string(); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop (connection id errors filter cleared)"); + } +} + +#[cfg(test)] +mod tests { + use std::net::IpAddr; + + use super::BanService; + + /// Sample service with one day ban duration. + fn ban_service(counter_limit: u32) -> BanService { + let udp_tracker_url = "udp://127.0.0.1".parse().unwrap(); + BanService::new(counter_limit, udp_tracker_url) + } + + #[test] + fn it_should_increase_the_errors_counter_for_a_given_ip() { + let mut ban_service = ban_service(1); + + let ip: IpAddr = "127.0.0.2".parse().unwrap(); + + ban_service.increase_counter(&ip); + + assert_eq!(ban_service.get_count(&ip), Some(1)); + } + + #[test] + fn it_should_ban_ips_with_counters_exceeding_a_predefined_limit() { + let mut ban_service = ban_service(1); + + let ip: IpAddr = "127.0.0.2".parse().unwrap(); + + ban_service.increase_counter(&ip); // Counter = 1 + ban_service.increase_counter(&ip); // Counter = 2 + + println!("Counter: {}", ban_service.get_count(&ip).unwrap()); + + assert!(ban_service.is_banned(&ip)); + } + + #[test] + fn it_should_not_ban_ips_whose_counters_do_not_exceed_the_predefined_limit() { + let mut ban_service = ban_service(1); + + let ip: IpAddr = "127.0.0.2".parse().unwrap(); + + ban_service.increase_counter(&ip); + + assert!(!ban_service.is_banned(&ip)); + } + + #[test] + fn it_should_allow_resetting_all_the_counters() { + let mut ban_service = ban_service(1); + + let ip: IpAddr = "127.0.0.2".parse().unwrap(); + + ban_service.increase_counter(&ip); // Counter = 1 + + ban_service.reset_bans(); + + assert_eq!(ban_service.get_estimate_count(&ip), 0); + } +} diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index d6827346d..f314e3721 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -6,9 +6,11 @@ use bittorrent_tracker_client::udp::client::check; use derive_more::Constructor; use futures_util::StreamExt; use tokio::select; -use tokio::sync::oneshot; +use tokio::sync::{oneshot, RwLock}; +use tokio::time::interval; use tracing::instrument; +use super::banning::BanService; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; use crate::core::{statistics, Tracker}; @@ -20,6 +22,11 @@ use crate::servers::udp::server::processor::Processor; use crate::servers::udp::server::receiver::Receiver; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; +/// The maximum number of connection id errors per ip. Clients will be banned if +/// they exceed this limit. +const MAX_CONNECTION_ID_ERRORS_PER_IP: u32 = 10; +const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 120; + /// A UDP server instance launcher. #[derive(Constructor)] pub struct Launcher; @@ -115,13 +122,30 @@ impl Launcher { let active_requests = &mut ActiveRequests::default(); let addr = receiver.bound_socket_address(); + let local_addr = format!("udp://{addr}"); let cookie_lifetime = cookie_lifetime.as_secs_f64(); - loop { - let processor = Processor::new(receiver.socket.clone(), tracker.clone(), cookie_lifetime); + let ban_service = Arc::new(RwLock::new(BanService::new( + MAX_CONNECTION_ID_ERRORS_PER_IP, + local_addr.parse().unwrap(), + ))); + + let ban_cleaner = ban_service.clone(); + + tokio::spawn(async move { + let mut cleaner_interval = interval(Duration::from_secs(IP_BANS_RESET_INTERVAL_IN_SECS)); + + cleaner_interval.tick().await; + loop { + cleaner_interval.tick().await; + ban_cleaner.write().await.reset_bans(); + } + }); + + loop { if let Some(req) = { tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server (wait for request)"); receiver.next().await @@ -149,18 +173,26 @@ impl Launcher { } } - // We spawn the new task even if there active requests buffer is - // full. This could seem counterintuitive because we are accepting - // more request and consuming more memory even if the server is - // already busy. However, we "force_push" the new tasks in the - // buffer. That means, in the worst scenario we will abort a - // running task to make place for the new task. - // - // Once concern could be to reach an starvation point were we - // are only adding and removing tasks without given them the - // chance to finish. However, the buffer is yielding before - // aborting one tasks, giving it the chance to finish. - let abort_handle: tokio::task::AbortHandle = tokio::task::spawn(processor.process_request(req)).abort_handle(); + if ban_service.read().await.is_banned(&req.from.ip()) { + tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop continue: (banned ip)"); + continue; + } + + let processor = Processor::new(receiver.socket.clone(), tracker.clone(), cookie_lifetime); + + /* We spawn the new task even if the active requests buffer is + full. This could seem counterintuitive because we are accepting + more request and consuming more memory even if the server is + already busy. However, we "force_push" the new tasks in the + buffer. That means, in the worst scenario we will abort a + running task to make place for the new task. + + Once concern could be to reach an starvation point were we are + only adding and removing tasks without given them the chance to + finish. However, the buffer is yielding before aborting one + tasks, giving it the chance to finish. */ + let abort_handle: tokio::task::AbortHandle = + tokio::task::spawn(processor.process_request(req, ban_service.clone())).abort_handle(); if abort_handle.is_finished() { continue; diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 7067512b6..9f974ca8c 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -6,6 +6,7 @@ use thiserror::Error; use super::RawRequest; +pub mod banning; pub mod bound_socket; pub mod launcher; pub mod processor; diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index fc39f28b9..120196431 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -3,8 +3,10 @@ use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::Response; +use tokio::sync::RwLock; use tracing::{instrument, Level}; +use super::banning::BanService; use super::bound_socket::BoundSocket; use crate::core::{statistics, Tracker}; use crate::servers::udp::handlers::CookieTimeValues; @@ -25,16 +27,18 @@ impl Processor { } } - #[instrument(skip(self, request))] - pub async fn process_request(self, request: RawRequest) { + #[instrument(skip(self, request, ban_service))] + pub async fn process_request(self, request: RawRequest, ban_service: Arc>) { let from = request.from; let response = handlers::handle_packet( request, &self.tracker, self.socket.address(), CookieTimeValues::new(self.cookie_lifetime), + ban_service, ) .await; + self.send_response(from, response).await; } diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index b12a8a900..9e9085e62 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -130,10 +130,31 @@ mod receiving_an_announce_request { use crate::servers::udp::contract::send_connection_request; use crate::servers::udp::Started; - pub async fn send_and_get_announce(tx_id: TransactionId, c_id: ConnectionId, client: &UdpTrackerClient) { - // Send announce request + pub async fn assert_send_and_get_announce(tx_id: TransactionId, c_id: ConnectionId, client: &UdpTrackerClient) { + let response = send_and_get_announce(tx_id, c_id, client).await; + assert!(is_ipv4_announce_response(&response)); + } + + pub async fn send_and_get_announce( + tx_id: TransactionId, + c_id: ConnectionId, + client: &UdpTrackerClient, + ) -> aquatic_udp_protocol::Response { + let announce_request = build_sample_announce_request(tx_id, c_id, client.client.socket.local_addr().unwrap().port()); + + match client.send(announce_request.into()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + }; - let announce_request = AnnounceRequest { + match client.receive().await { + Ok(response) => response, + Err(err) => panic!("{err}"), + } + } + + fn build_sample_announce_request(tx_id: TransactionId, c_id: ConnectionId, port: u16) -> AnnounceRequest { + AnnounceRequest { connection_id: ConnectionId(c_id.0), action_placeholder: AnnounceActionPlaceholder::default(), transaction_id: tx_id, @@ -146,26 +167,34 @@ mod receiving_an_announce_request { ip_address: Ipv4Addr::new(0, 0, 0, 0).into(), key: PeerKey::new(0i32), peers_wanted: NumberOfPeers(1i32.into()), - port: Port(client.client.socket.local_addr().unwrap().port().into()), - }; + port: Port(port.into()), + } + } - match client.send(announce_request.into()).await { - Ok(_) => (), - Err(err) => panic!("{err}"), - }; + #[tokio::test] + async fn should_return_an_announce_response() { + INIT.call_once(|| { + tracing_stderr_init(LevelFilter::ERROR); + }); - let response = match client.receive().await { - Ok(response) => response, + let env = Started::new(&configuration::ephemeral().into()).await; + + let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { + Ok(udp_tracker_client) => udp_tracker_client, Err(err) => panic!("{err}"), }; - // println!("test response {response:?}"); + let tx_id = TransactionId::new(123); - assert!(is_ipv4_announce_response(&response)); + let c_id = send_connection_request(tx_id, &client).await; + + assert_send_and_get_announce(tx_id, c_id, &client).await; + + env.stop().await; } #[tokio::test] - async fn should_return_an_announce_response() { + async fn should_return_many_announce_response() { INIT.call_once(|| { tracing_stderr_init(LevelFilter::ERROR); }); @@ -181,13 +210,16 @@ mod receiving_an_announce_request { let c_id = send_connection_request(tx_id, &client).await; - send_and_get_announce(tx_id, c_id, &client).await; + for x in 0..1000 { + tracing::info!("req no: {x}"); + assert_send_and_get_announce(tx_id, c_id, &client).await; + } env.stop().await; } #[tokio::test] - async fn should_return_many_announce_response() { + async fn should_ban_the_client_ip_if_it_sends_more_than_10_requests_with_a_cookie_value_not_normal() { INIT.call_once(|| { tracing_stderr_init(LevelFilter::ERROR); }); @@ -201,13 +233,30 @@ mod receiving_an_announce_request { let tx_id = TransactionId::new(123); - let c_id = send_connection_request(tx_id, &client).await; + // The eleven first requests should be fine - for x in 0..1000 { + let invalid_connection_id = ConnectionId::new(0); // Zero is one of the not normal values. + + for x in 0..=10 { tracing::info!("req no: {x}"); - send_and_get_announce(tx_id, c_id, &client).await; + send_and_get_announce(tx_id, invalid_connection_id, &client).await; } + // The twelfth request should be banned (timeout error) + + let announce_request = build_sample_announce_request( + tx_id, + invalid_connection_id, + client.client.socket.local_addr().unwrap().port(), + ); + + match client.send(announce_request.into()).await { + Ok(_) => (), + Err(err) => panic!("{err}"), + }; + + assert!(client.receive().await.is_err()); + env.stop().await; } } From 29e506d2aa7946e201902e7b0bce06a1ba5a778b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 10 Dec 2024 10:10:01 +0000 Subject: [PATCH 0544/1297] feat: use default aquatic udp port for benchmarking Becuase we are using aquatic_udp_load_test with this ocndifugration ``` Starting client with config: Config { server_address: 127.0.0.1:3000, log_level: Error, workers: 1, duration: 0, summarize_last: 0, extra_statistics: true, network: NetworkConfig { multiple_client_ipv4s: true, sockets_per_worker: 4, recv_buffer: 8000000, }, requests: RequestConfig { number_of_torrents: 1000000, number_of_peers: 2000000, scrape_max_torrents: 10, announce_peers_wanted: 30, weight_connect: 50, weight_announce: 50, weight_scrape: 1, peer_seeder_probability: 0.75, }, } ``` --- share/default/config/tracker.udp.benchmarking.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/share/default/config/tracker.udp.benchmarking.toml b/share/default/config/tracker.udp.benchmarking.toml index c6644d8dc..8a898153a 100644 --- a/share/default/config/tracker.udp.benchmarking.toml +++ b/share/default/config/tracker.udp.benchmarking.toml @@ -18,4 +18,4 @@ persistent_torrent_completed_stat = false remove_peerless_torrents = false [[udp_trackers]] -bind_address = "0.0.0.0:6969" +bind_address = "0.0.0.0:3000" From fe4103d297dda35382e4177ce1422ad50d1c34f2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 17 Dec 2024 08:02:05 +0000 Subject: [PATCH 0545/1297] chore(deps): update depencencies ```output cargo update Updating crates.io index Locking 7 packages to latest compatible versions Updating crossbeam-channel v0.5.13 -> v0.5.14 Updating crossbeam-deque v0.8.5 -> v0.8.6 Updating crossbeam-queue v0.3.11 -> v0.3.12 Updating crossbeam-utils v0.8.20 -> v0.8.21 Updating hyper v1.5.1 -> v1.5.2 Updating thiserror v2.0.6 -> v2.0.7 Updating thiserror-impl v2.0.6 -> v2.0.7 ``` --- Cargo.lock | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c9f388f48..dacd04454 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -597,7 +597,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_repr", - "thiserror 2.0.6", + "thiserror 2.0.7", "tokio", "torrust-tracker-configuration", "torrust-tracker-located-error", @@ -1045,18 +1045,18 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.13" +version = "0.5.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33480d6946193aa8033910124896ca395333cae7e2d1113d1fef6c3272217df2" +checksum = "06ba6d68e24814cb8de6bb986db8222d3a027d15872cabc0d18817bc3c0e4471" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-deque" -version = "0.8.5" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" +checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -1073,9 +1073,9 @@ dependencies = [ [[package]] name = "crossbeam-queue" -version = "0.3.11" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df0346b5d5e76ac2fe4e327c5fd1118d6be7c51dfb18f9b7922923f287471e35" +checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" dependencies = [ "crossbeam-utils", ] @@ -1092,9 +1092,9 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.20" +version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "crunchy" @@ -1749,9 +1749,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.5.1" +version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97818827ef4f364230e16705d4706e2897df2bb60617d6ca15d598025a3c481f" +checksum = "256fb8d4bd6413123cc9d91832d78325c48ff41677595be797d90f42969beae0" dependencies = [ "bytes", "futures-channel", @@ -3751,11 +3751,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.6" +version = "2.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fec2a1820ebd077e2b90c4df007bebf344cd394098a13c563957d0afc83ea47" +checksum = "93605438cbd668185516ab499d589afb7ee1859ea3d5fc8f6b0755e1c7443767" dependencies = [ - "thiserror-impl 2.0.6", + "thiserror-impl 2.0.7", ] [[package]] @@ -3771,9 +3771,9 @@ dependencies = [ [[package]] name = "thiserror-impl" -version = "2.0.6" +version = "2.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d65750cab40f4ff1929fb1ba509e9914eb756131cef4210da8d5d700d26f6312" +checksum = "e1d8749b4531af2117677a5fcd12b1348a3fe2b81e36e61ffeac5c4aa3273e36" dependencies = [ "proc-macro2", "quote", @@ -3999,7 +3999,7 @@ dependencies = [ "serde_json", "serde_repr", "serde_with", - "thiserror 2.0.6", + "thiserror 2.0.7", "tokio", "torrust-tracker-clock", "torrust-tracker-configuration", @@ -4034,7 +4034,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_json", - "thiserror 2.0.6", + "thiserror 2.0.7", "tokio", "torrust-tracker-configuration", "tracing", @@ -4061,7 +4061,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.6", + "thiserror 2.0.7", "toml", "torrust-tracker-located-error", "url", @@ -4073,14 +4073,14 @@ name = "torrust-tracker-contrib-bencode" version = "3.0.0-develop" dependencies = [ "criterion", - "thiserror 2.0.6", + "thiserror 2.0.7", ] [[package]] name = "torrust-tracker-located-error" version = "3.0.0-develop" dependencies = [ - "thiserror 2.0.6", + "thiserror 2.0.7", "tracing", ] @@ -4095,7 +4095,7 @@ dependencies = [ "serde", "tdyne-peer-id", "tdyne-peer-id-registry", - "thiserror 2.0.6", + "thiserror 2.0.7", "zerocopy", ] From 7cf08a608bcc1172deff5274a939026b294ec27e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 17 Dec 2024 12:18:53 +0000 Subject: [PATCH 0546/1297] refactor: reorganize statistics mod Preaparing to introduce new changes in the repository. --- src/core/mod.rs | 21 +- src/core/services/statistics/mod.rs | 12 +- src/core/services/statistics/setup.rs | 13 +- src/core/statistics.rs | 578 ------------------ src/core/statistics/event/handler.rs | 234 +++++++ src/core/statistics/event/listener.rs | 11 + src/core/statistics/event/mod.rs | 34 ++ src/core/statistics/event/sender.rs | 29 + src/core/statistics/keeper.rs | 77 +++ src/core/statistics/metrics.rs | 69 +++ src/core/statistics/mod.rs | 30 + src/core/statistics/repository.rs | 144 +++++ .../apis/v1/context/stats/resources.rs | 2 +- src/servers/http/v1/services/announce.rs | 31 +- src/servers/http/v1/services/scrape.rs | 30 +- src/servers/udp/handlers.rs | 54 +- src/servers/udp/server/launcher.rs | 6 +- src/servers/udp/server/processor.rs | 4 +- 18 files changed, 721 insertions(+), 658 deletions(-) delete mode 100644 src/core/statistics.rs create mode 100644 src/core/statistics/event/handler.rs create mode 100644 src/core/statistics/event/listener.rs create mode 100644 src/core/statistics/event/mod.rs create mode 100644 src/core/statistics/event/sender.rs create mode 100644 src/core/statistics/keeper.rs create mode 100644 src/core/statistics/metrics.rs create mode 100644 src/core/statistics/mod.rs create mode 100644 src/core/statistics/repository.rs diff --git a/src/core/mod.rs b/src/core/mod.rs index 835776e30..b5759709b 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -422,7 +422,7 @@ //! For example, the HTTP tracker would send an event like the following when it handles an `announce` request received from a peer using IP version 4. //! //! ```text -//! tracker.send_stats_event(statistics::Event::Tcp4Announce).await +//! tracker.send_stats_event(statistics::event::Event::Tcp4Announce).await //! ``` //! //! Refer to [`statistics`] module for more information about statistics. @@ -505,10 +505,10 @@ pub struct Tracker { torrents: Arc, /// Service to send stats events. - stats_event_sender: Option>, + stats_event_sender: Option>, /// The in-memory stats repo. - stats_repository: statistics::Repo, + stats_repository: statistics::repository::Repository, } /// Structure that holds the data returned by the `announce` request. @@ -624,8 +624,8 @@ impl Tracker { /// Will return a `databases::error::Error` if unable to connect to database. The `Tracker` is responsible for the persistence. pub fn new( config: &Core, - stats_event_sender: Option>, - stats_repository: statistics::Repo, + stats_event_sender: Option>, + stats_repository: statistics::repository::Repository, ) -> Result { let driver = match config.database.driver { database::Driver::Sqlite3 => Driver::Sqlite3, @@ -1207,17 +1207,20 @@ impl Tracker { Ok(()) } - /// It return the `Tracker` [`statistics::Metrics`]. + /// It return the `Tracker` [`statistics::metrics::Metrics`]. /// /// # Context: Statistics - pub async fn get_stats(&self) -> tokio::sync::RwLockReadGuard<'_, statistics::Metrics> { + pub async fn get_stats(&self) -> tokio::sync::RwLockReadGuard<'_, statistics::metrics::Metrics> { self.stats_repository.get_stats().await } - /// It allows to send a statistic events which eventually will be used to update [`statistics::Metrics`]. + /// It allows to send a statistic events which eventually will be used to update [`statistics::metrics::Metrics`]. /// /// # Context: Statistics - pub async fn send_stats_event(&self, event: statistics::Event) -> Option>> { + pub async fn send_stats_event( + &self, + event: statistics::event::Event, + ) -> Option>> { match &self.stats_event_sender { None => None, Some(stats_event_sender) => stats_event_sender.send_event(event).await, diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 82ff359ab..10e1c60fa 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -3,14 +3,14 @@ //! It includes: //! //! - A [`factory`](crate::core::services::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. -//! - A [`get_metrics`] service to get the [`tracker metrics`](crate::core::statistics::Metrics). +//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::core::statistics::metrics::Metrics). //! //! Tracker metrics are collected using a Publisher-Subscribe pattern. //! //! The factory function builds two structs: //! -//! - An statistics [`EventSender`](crate::core::statistics::EventSender) -//! - An statistics [`Repo`](crate::core::statistics::Repo) +//! - An statistics event [`Sender`](crate::core::statistics::event::sender::Sender) +//! - An statistics [`Repository`](crate::core::statistics::repository::Repository) //! //! ```text //! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); @@ -21,7 +21,7 @@ //! There is an event listener that is receiving all the events and processing them with an event handler. //! Then, the event handler updates the metrics depending on the received event. //! -//! For example, if you send the event [`Event::Udp4Connect`](crate::core::statistics::Event::Udp4Connect): +//! For example, if you send the event [`Event::Udp4Connect`](crate::core::statistics::event::Event::Udp4Connect): //! //! ```text //! let result = event_sender.send_event(Event::Udp4Connect).await; @@ -42,7 +42,7 @@ use std::sync::Arc; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use crate::core::statistics::Metrics; +use crate::core::statistics::metrics::Metrics; use crate::core::Tracker; /// All the metrics collected by the tracker. @@ -118,7 +118,7 @@ mod tests { tracker_metrics, TrackerMetrics { torrents_metrics: TorrentsMetrics::default(), - protocol_metrics: core::statistics::Metrics::default(), + protocol_metrics: core::statistics::metrics::Metrics::default(), } ); } diff --git a/src/core/services/statistics/setup.rs b/src/core/services/statistics/setup.rs index 37603852b..e440a709c 100644 --- a/src/core/services/statistics/setup.rs +++ b/src/core/services/statistics/setup.rs @@ -7,16 +7,21 @@ use crate::core::statistics; /// /// It returns: /// -/// - An statistics [`EventSender`](crate::core::statistics::EventSender) that allows you to send events related to statistics. -/// - An statistics [`Repo`](crate::core::statistics::Repo) which is an in-memory repository for the tracker metrics. +/// - An statistics event [`Sender`](crate::core::statistics::event::sender::Sender) that allows you to send events related to statistics. +/// - An statistics [`Repository`](crate::core::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. /// /// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics /// events are sent are received but not dispatched to the handler. #[must_use] -pub fn factory(tracker_usage_statistics: bool) -> (Option>, statistics::Repo) { +pub fn factory( + tracker_usage_statistics: bool, +) -> ( + Option>, + statistics::repository::Repository, +) { let mut stats_event_sender = None; - let mut stats_tracker = statistics::Keeper::new(); + let mut stats_tracker = statistics::keeper::Keeper::new(); if tracker_usage_statistics { stats_event_sender = Some(stats_tracker.run_event_listener()); diff --git a/src/core/statistics.rs b/src/core/statistics.rs deleted file mode 100644 index 6df7c4961..000000000 --- a/src/core/statistics.rs +++ /dev/null @@ -1,578 +0,0 @@ -//! Structs to collect and keep tracker metrics. -//! -//! The tracker collects metrics such as: -//! -//! - Number of connections handled -//! - Number of `announce` requests handled -//! - Number of `scrape` request handled -//! -//! These metrics are collected for each connection type: UDP and HTTP and -//! also for each IP version used by the peers: IPv4 and IPv6. -//! -//! > Notice: that UDP tracker have an specific `connection` request. For the HTTP metrics the counter counts one connection for each `announce` or `scrape` request. -//! -//! The data is collected by using an `event-sender -> event listener` model. -//! -//! The tracker uses an [`statistics::EventSender`](crate::core::statistics::EventSender) instance to send an event. -//! The [`statistics::Keeper`](crate::core::statistics::Keeper) listens to new events and uses the [`statistics::Repo`](crate::core::statistics::Repo) to upgrade and store metrics. -//! -//! See the [`statistics::Event`](crate::core::statistics::Event) enum to check which events are available. -use std::sync::Arc; - -use futures::future::BoxFuture; -use futures::FutureExt; -#[cfg(test)] -use mockall::{automock, predicate::str}; -use tokio::sync::mpsc::error::SendError; -use tokio::sync::{mpsc, RwLock, RwLockReadGuard}; - -const CHANNEL_BUFFER_SIZE: usize = 65_535; - -/// An statistics event. It is used to collect tracker metrics. -/// -/// - `Tcp` prefix means the event was triggered by the HTTP tracker -/// - `Udp` prefix means the event was triggered by the UDP tracker -/// - `4` or `6` prefixes means the IP version used by the peer -/// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection` -/// -/// > NOTE: HTTP trackers do not use `connection` requests. -#[derive(Debug, PartialEq, Eq)] -pub enum Event { - // code-review: consider one single event for request type with data: Event::Announce { scheme: HTTPorUDP, ip_version: V4orV6 } - // Attributes are enums too. - Tcp4Announce, - Tcp4Scrape, - Tcp6Announce, - Tcp6Scrape, - Udp4RequestAborted, - Udp4Request, - Udp4Connect, - Udp4Announce, - Udp4Scrape, - Udp4Response, - Udp4Error, - Udp6Request, - Udp6Connect, - Udp6Announce, - Udp6Scrape, - Udp6Response, - Udp6Error, -} - -/// Metrics collected by the tracker. -/// -/// - Number of connections handled -/// - Number of `announce` requests handled -/// - Number of `scrape` request handled -/// -/// These metrics are collected for each connection type: UDP and HTTP -/// and also for each IP version used by the peers: IPv4 and IPv6. -#[derive(Debug, PartialEq, Default)] -pub struct Metrics { - /// Total number of TCP (HTTP tracker) connections from IPv4 peers. - /// Since the HTTP tracker spec does not require a handshake, this metric - /// increases for every HTTP request. - pub tcp4_connections_handled: u64, - /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. - pub tcp4_announces_handled: u64, - /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. - pub tcp4_scrapes_handled: u64, - - /// Total number of TCP (HTTP tracker) connections from IPv6 peers. - pub tcp6_connections_handled: u64, - /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. - pub tcp6_announces_handled: u64, - /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. - pub tcp6_scrapes_handled: u64, - - /// Total number of UDP (UDP tracker) requests aborted. - pub udp_requests_aborted: u64, - - /// Total number of UDP (UDP tracker) requests from IPv4 peers. - pub udp4_requests: u64, - /// Total number of UDP (UDP tracker) connections from IPv4 peers. - pub udp4_connections_handled: u64, - /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. - pub udp4_announces_handled: u64, - /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. - pub udp4_scrapes_handled: u64, - /// Total number of UDP (UDP tracker) responses from IPv4 peers. - pub udp4_responses: u64, - /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. - pub udp4_errors_handled: u64, - - /// Total number of UDP (UDP tracker) requests from IPv6 peers. - pub udp6_requests: u64, - /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. - pub udp6_connections_handled: u64, - /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. - pub udp6_announces_handled: u64, - /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. - pub udp6_scrapes_handled: u64, - /// Total number of UDP (UDP tracker) responses from IPv6 peers. - pub udp6_responses: u64, - /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. - pub udp6_errors_handled: u64, -} - -/// The service responsible for keeping tracker metrics (listening to statistics events and handle them). -/// -/// It actively listen to new statistics events. When it receives a new event -/// it accordingly increases the counters. -pub struct Keeper { - pub repository: Repo, -} - -impl Default for Keeper { - fn default() -> Self { - Self::new() - } -} - -impl Keeper { - #[must_use] - pub fn new() -> Self { - Self { repository: Repo::new() } - } - - #[must_use] - pub fn new_active_instance() -> (Box, Repo) { - let mut stats_tracker = Self::new(); - - let stats_event_sender = stats_tracker.run_event_listener(); - - (stats_event_sender, stats_tracker.repository) - } - - pub fn run_event_listener(&mut self) -> Box { - let (sender, receiver) = mpsc::channel::(CHANNEL_BUFFER_SIZE); - - let stats_repository = self.repository.clone(); - - tokio::spawn(async move { event_listener(receiver, stats_repository).await }); - - Box::new(Sender { sender }) - } -} - -async fn event_listener(mut receiver: mpsc::Receiver, stats_repository: Repo) { - while let Some(event) = receiver.recv().await { - event_handler(event, &stats_repository).await; - } -} - -async fn event_handler(event: Event, stats_repository: &Repo) { - match event { - // TCP4 - Event::Tcp4Announce => { - stats_repository.increase_tcp4_announces().await; - stats_repository.increase_tcp4_connections().await; - } - Event::Tcp4Scrape => { - stats_repository.increase_tcp4_scrapes().await; - stats_repository.increase_tcp4_connections().await; - } - - // TCP6 - Event::Tcp6Announce => { - stats_repository.increase_tcp6_announces().await; - stats_repository.increase_tcp6_connections().await; - } - Event::Tcp6Scrape => { - stats_repository.increase_tcp6_scrapes().await; - stats_repository.increase_tcp6_connections().await; - } - - // UDP - Event::Udp4RequestAborted => { - stats_repository.increase_udp_requests_aborted().await; - } - - // UDP4 - Event::Udp4Request => { - stats_repository.increase_udp4_requests().await; - } - Event::Udp4Connect => { - stats_repository.increase_udp4_connections().await; - } - Event::Udp4Announce => { - stats_repository.increase_udp4_announces().await; - } - Event::Udp4Scrape => { - stats_repository.increase_udp4_scrapes().await; - } - Event::Udp4Response => { - stats_repository.increase_udp4_responses().await; - } - Event::Udp4Error => { - stats_repository.increase_udp4_errors().await; - } - - // UDP6 - Event::Udp6Request => { - stats_repository.increase_udp6_requests().await; - } - Event::Udp6Connect => { - stats_repository.increase_udp6_connections().await; - } - Event::Udp6Announce => { - stats_repository.increase_udp6_announces().await; - } - Event::Udp6Scrape => { - stats_repository.increase_udp6_scrapes().await; - } - Event::Udp6Response => { - stats_repository.increase_udp6_responses().await; - } - Event::Udp6Error => { - stats_repository.increase_udp6_errors().await; - } - } - - tracing::debug!("stats: {:?}", stats_repository.get_stats().await); -} - -/// A trait to allow sending statistics events -#[cfg_attr(test, automock)] -pub trait EventSender: Sync + Send { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; -} - -/// An [`statistics::EventSender`](crate::core::statistics::EventSender) implementation. -/// -/// It uses a channel sender to send the statistic events. The channel is created by a -/// [`statistics::Keeper`](crate::core::statistics::Keeper) -pub struct Sender { - sender: mpsc::Sender, -} - -impl EventSender for Sender { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { - async move { Some(self.sender.send(event).await) }.boxed() - } -} - -/// A repository for the tracker metrics. -#[derive(Clone)] -pub struct Repo { - pub stats: Arc>, -} - -impl Default for Repo { - fn default() -> Self { - Self::new() - } -} - -impl Repo { - #[must_use] - pub fn new() -> Self { - Self { - stats: Arc::new(RwLock::new(Metrics::default())), - } - } - - pub async fn get_stats(&self) -> RwLockReadGuard<'_, Metrics> { - self.stats.read().await - } - - pub async fn increase_tcp4_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp4_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp4_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp4_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp4_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp4_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp6_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp6_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp6_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp6_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp6_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp6_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp_requests_aborted(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp_requests_aborted += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_requests(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_requests += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_responses(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_responses += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_errors(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_errors_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_requests(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_requests += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_responses(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_responses += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_errors(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_errors_handled += 1; - drop(stats_lock); - } -} - -#[cfg(test)] -mod tests { - - mod stats_tracker { - use crate::core::statistics::{Event, Keeper, Metrics}; - - #[tokio::test] - async fn should_contain_the_tracker_statistics() { - let stats_tracker = Keeper::new(); - - let stats = stats_tracker.repository.get_stats().await; - - assert_eq!(stats.tcp4_announces_handled, Metrics::default().tcp4_announces_handled); - } - - #[tokio::test] - async fn should_create_an_event_sender_to_send_statistical_events() { - let mut stats_tracker = Keeper::new(); - - let event_sender = stats_tracker.run_event_listener(); - - let result = event_sender.send_event(Event::Udp4Connect).await; - - assert!(result.is_some()); - } - } - - mod event_handler { - use crate::core::statistics::{event_handler, Event, Repo}; - - #[tokio::test] - async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp4Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_announce_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp4Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp4_scrapes_counter_when_it_receives_a_tcp4_scrape_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp4Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_scrapes_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_scrape_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp4Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp6_announces_counter_when_it_receives_a_tcp6_announce_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp6Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_announce_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp6Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp6_scrapes_counter_when_it_receives_a_tcp6_scrape_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp6Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_scrapes_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_scrape_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Tcp6Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_connections_counter_when_it_receives_a_udp4_connect_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Udp4Connect, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_announces_counter_when_it_receives_a_udp4_announce_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Udp4Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_scrapes_counter_when_it_receives_a_udp4_scrape_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Udp4Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_scrapes_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_connections_counter_when_it_receives_a_udp6_connect_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Udp6Connect, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_announces_counter_when_it_receives_a_udp6_announce_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Udp6Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_scrapes_counter_when_it_receives_a_udp6_scrape_event() { - let stats_repository = Repo::new(); - - event_handler(Event::Udp6Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_scrapes_handled, 1); - } - } -} diff --git a/src/core/statistics/event/handler.rs b/src/core/statistics/event/handler.rs new file mode 100644 index 000000000..5acc5e12c --- /dev/null +++ b/src/core/statistics/event/handler.rs @@ -0,0 +1,234 @@ +use crate::core::statistics::event::Event; +use crate::core::statistics::repository::Repository; + +pub async fn handle_event(event: Event, stats_repository: &Repository) { + match event { + // TCP4 + Event::Tcp4Announce => { + stats_repository.increase_tcp4_announces().await; + stats_repository.increase_tcp4_connections().await; + } + Event::Tcp4Scrape => { + stats_repository.increase_tcp4_scrapes().await; + stats_repository.increase_tcp4_connections().await; + } + + // TCP6 + Event::Tcp6Announce => { + stats_repository.increase_tcp6_announces().await; + stats_repository.increase_tcp6_connections().await; + } + Event::Tcp6Scrape => { + stats_repository.increase_tcp6_scrapes().await; + stats_repository.increase_tcp6_connections().await; + } + + // UDP + Event::Udp4RequestAborted => { + stats_repository.increase_udp_requests_aborted().await; + } + + // UDP4 + Event::Udp4Request => { + stats_repository.increase_udp4_requests().await; + } + Event::Udp4Connect => { + stats_repository.increase_udp4_connections().await; + } + Event::Udp4Announce => { + stats_repository.increase_udp4_announces().await; + } + Event::Udp4Scrape => { + stats_repository.increase_udp4_scrapes().await; + } + Event::Udp4Response => { + stats_repository.increase_udp4_responses().await; + } + Event::Udp4Error => { + stats_repository.increase_udp4_errors().await; + } + + // UDP6 + Event::Udp6Request => { + stats_repository.increase_udp6_requests().await; + } + Event::Udp6Connect => { + stats_repository.increase_udp6_connections().await; + } + Event::Udp6Announce => { + stats_repository.increase_udp6_announces().await; + } + Event::Udp6Scrape => { + stats_repository.increase_udp6_scrapes().await; + } + Event::Udp6Response => { + stats_repository.increase_udp6_responses().await; + } + Event::Udp6Error => { + stats_repository.increase_udp6_errors().await; + } + } + + tracing::debug!("stats: {:?}", stats_repository.get_stats().await); +} + +#[cfg(test)] +mod tests { + use crate::core::statistics::event::handler::handle_event; + use crate::core::statistics::event::Event; + use crate::core::statistics::repository::Repository; + + #[tokio::test] + async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp4Announce, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp4_announces_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_announce_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp4Announce, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp4_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp4_scrapes_counter_when_it_receives_a_tcp4_scrape_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp4Scrape, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp4_scrapes_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_scrape_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp4Scrape, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp4_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp6_announces_counter_when_it_receives_a_tcp6_announce_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp6Announce, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp6_announces_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_announce_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp6Announce, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp6_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp6_scrapes_counter_when_it_receives_a_tcp6_scrape_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp6Scrape, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp6_scrapes_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_scrape_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp6Scrape, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp6_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_connections_counter_when_it_receives_a_udp4_connect_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp4Connect, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_announces_counter_when_it_receives_a_udp4_announce_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp4Announce, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_announces_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_scrapes_counter_when_it_receives_a_udp4_scrape_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp4Scrape, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_scrapes_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_connections_counter_when_it_receives_a_udp6_connect_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp6Connect, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_announces_counter_when_it_receives_a_udp6_announce_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp6Announce, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_announces_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_scrapes_counter_when_it_receives_a_udp6_scrape_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp6Scrape, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_scrapes_handled, 1); + } +} diff --git a/src/core/statistics/event/listener.rs b/src/core/statistics/event/listener.rs new file mode 100644 index 000000000..89ed7b41a --- /dev/null +++ b/src/core/statistics/event/listener.rs @@ -0,0 +1,11 @@ +use tokio::sync::mpsc; + +use super::handler::handle_event; +use super::Event; +use crate::core::statistics::repository::Repository; + +pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) { + while let Some(event) = receiver.recv().await { + handle_event(event, &stats_repository).await; + } +} diff --git a/src/core/statistics/event/mod.rs b/src/core/statistics/event/mod.rs new file mode 100644 index 000000000..b14995cc1 --- /dev/null +++ b/src/core/statistics/event/mod.rs @@ -0,0 +1,34 @@ +pub mod handler; +pub mod listener; +pub mod sender; + +/// An statistics event. It is used to collect tracker metrics. +/// +/// - `Tcp` prefix means the event was triggered by the HTTP tracker +/// - `Udp` prefix means the event was triggered by the UDP tracker +/// - `4` or `6` prefixes means the IP version used by the peer +/// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection` +/// +/// > NOTE: HTTP trackers do not use `connection` requests. +#[derive(Debug, PartialEq, Eq)] +pub enum Event { + // code-review: consider one single event for request type with data: Event::Announce { scheme: HTTPorUDP, ip_version: V4orV6 } + // Attributes are enums too. + Tcp4Announce, + Tcp4Scrape, + Tcp6Announce, + Tcp6Scrape, + Udp4RequestAborted, + Udp4Request, + Udp4Connect, + Udp4Announce, + Udp4Scrape, + Udp4Response, + Udp4Error, + Udp6Request, + Udp6Connect, + Udp6Announce, + Udp6Scrape, + Udp6Response, + Udp6Error, +} diff --git a/src/core/statistics/event/sender.rs b/src/core/statistics/event/sender.rs new file mode 100644 index 000000000..1b663b5d1 --- /dev/null +++ b/src/core/statistics/event/sender.rs @@ -0,0 +1,29 @@ +use futures::future::BoxFuture; +use futures::FutureExt; +#[cfg(test)] +use mockall::{automock, predicate::str}; +use tokio::sync::mpsc; +use tokio::sync::mpsc::error::SendError; + +use super::Event; + +/// A trait to allow sending statistics events +#[cfg_attr(test, automock)] +pub trait Sender: Sync + Send { + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; +} + +/// An [`statistics::EventSender`](crate::core::statistics::event::sender::Sender) implementation. +/// +/// It uses a channel sender to send the statistic events. The channel is created by a +/// [`statistics::Keeper`](crate::core::statistics::keeper::Keeper) +#[allow(clippy::module_name_repetitions)] +pub struct ChannelSender { + pub(crate) sender: mpsc::Sender, +} + +impl Sender for ChannelSender { + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { + async move { Some(self.sender.send(event).await) }.boxed() + } +} diff --git a/src/core/statistics/keeper.rs b/src/core/statistics/keeper.rs new file mode 100644 index 000000000..5427734e1 --- /dev/null +++ b/src/core/statistics/keeper.rs @@ -0,0 +1,77 @@ +use tokio::sync::mpsc; + +use super::event::listener::dispatch_events; +use super::event::sender::{ChannelSender, Sender}; +use super::event::Event; +use super::repository::Repository; + +const CHANNEL_BUFFER_SIZE: usize = 65_535; + +/// The service responsible for keeping tracker metrics (listening to statistics events and handle them). +/// +/// It actively listen to new statistics events. When it receives a new event +/// it accordingly increases the counters. +pub struct Keeper { + pub repository: Repository, +} + +impl Default for Keeper { + fn default() -> Self { + Self::new() + } +} + +impl Keeper { + #[must_use] + pub fn new() -> Self { + Self { + repository: Repository::new(), + } + } + + #[must_use] + pub fn new_active_instance() -> (Box, Repository) { + let mut stats_tracker = Self::new(); + + let stats_event_sender = stats_tracker.run_event_listener(); + + (stats_event_sender, stats_tracker.repository) + } + + pub fn run_event_listener(&mut self) -> Box { + let (sender, receiver) = mpsc::channel::(CHANNEL_BUFFER_SIZE); + + let stats_repository = self.repository.clone(); + + tokio::spawn(async move { dispatch_events(receiver, stats_repository).await }); + + Box::new(ChannelSender { sender }) + } +} + +#[cfg(test)] +mod tests { + use crate::core::statistics::event::Event; + use crate::core::statistics::keeper::Keeper; + use crate::core::statistics::metrics::Metrics; + + #[tokio::test] + async fn should_contain_the_tracker_statistics() { + let stats_tracker = Keeper::new(); + + let stats = stats_tracker.repository.get_stats().await; + + assert_eq!(stats.tcp4_announces_handled, Metrics::default().tcp4_announces_handled); + } + + #[tokio::test] + async fn should_create_an_event_sender_to_send_statistical_events() { + let mut stats_tracker = Keeper::new(); + + let event_sender = stats_tracker.run_event_listener(); + + let result = event_sender.send_event(Event::Udp4Connect).await; + + assert!(result.is_some()); + } +} diff --git a/src/core/statistics/metrics.rs b/src/core/statistics/metrics.rs new file mode 100644 index 000000000..970302816 --- /dev/null +++ b/src/core/statistics/metrics.rs @@ -0,0 +1,69 @@ +/// Metrics collected by the tracker. +/// +/// - Number of connections handled +/// - Number of `announce` requests handled +/// - Number of `scrape` request handled +/// +/// These metrics are collected for each connection type: UDP and HTTP +/// and also for each IP version used by the peers: IPv4 and IPv6. +#[derive(Debug, PartialEq, Default)] +pub struct Metrics { + /// Total number of TCP (HTTP tracker) connections from IPv4 peers. + /// Since the HTTP tracker spec does not require a handshake, this metric + /// increases for every HTTP request. + pub tcp4_connections_handled: u64, + + /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. + pub tcp4_announces_handled: u64, + + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. + pub tcp4_scrapes_handled: u64, + + /// Total number of TCP (HTTP tracker) connections from IPv6 peers. + pub tcp6_connections_handled: u64, + + /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. + pub tcp6_announces_handled: u64, + + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. + pub tcp6_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) requests aborted. + pub udp_requests_aborted: u64, + + /// Total number of UDP (UDP tracker) requests from IPv4 peers. + pub udp4_requests: u64, + + /// Total number of UDP (UDP tracker) connections from IPv4 peers. + pub udp4_connections_handled: u64, + + /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. + pub udp4_announces_handled: u64, + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. + pub udp4_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) responses from IPv4 peers. + pub udp4_responses: u64, + + /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. + pub udp4_errors_handled: u64, + + /// Total number of UDP (UDP tracker) requests from IPv6 peers. + pub udp6_requests: u64, + + /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. + pub udp6_connections_handled: u64, + + /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. + pub udp6_announces_handled: u64, + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. + pub udp6_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) responses from IPv6 peers. + pub udp6_responses: u64, + + /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. + pub udp6_errors_handled: u64, +} diff --git a/src/core/statistics/mod.rs b/src/core/statistics/mod.rs new file mode 100644 index 000000000..49a82bea9 --- /dev/null +++ b/src/core/statistics/mod.rs @@ -0,0 +1,30 @@ +//! Structs to collect and keep tracker metrics. +//! +//! The tracker collects metrics such as: +//! +//! - Number of connections handled +//! - Number of `announce` requests handled +//! - Number of `scrape` request handled +//! +//! These metrics are collected for each connection type: UDP and HTTP and +//! also for each IP version used by the peers: IPv4 and IPv6. +//! +//! > Notice: that UDP tracker have an specific `connection` request. For the +//! > `HTTP` metrics the counter counts one connection for each `announce` or +//! > `scrape` request. +//! +//! The data is collected by using an `event-sender -> event listener` model. +//! +//! The tracker uses a [`Sender`](crate::core::statistics::event::sender::Sender) +//! instance to send an event. +//! +//! The [`statistics::keeper::Keeper`](crate::core::statistics::keeper::Keeper) listens to new +//! events and uses the [`statistics::repository::Repository`](crate::core::statistics::repository::Repository) to +//! upgrade and store metrics. +//! +//! See the [`statistics::event::Event`](crate::core::statistics::event::Event) enum to check +//! which events are available. +pub mod event; +pub mod keeper; +pub mod metrics; +pub mod repository; diff --git a/src/core/statistics/repository.rs b/src/core/statistics/repository.rs new file mode 100644 index 000000000..bdbc046de --- /dev/null +++ b/src/core/statistics/repository.rs @@ -0,0 +1,144 @@ +use std::sync::Arc; + +use tokio::sync::{RwLock, RwLockReadGuard}; + +use super::metrics::Metrics; + +/// A repository for the tracker metrics. +#[derive(Clone)] +pub struct Repository { + pub stats: Arc>, +} + +impl Default for Repository { + fn default() -> Self { + Self::new() + } +} + +impl Repository { + #[must_use] + pub fn new() -> Self { + Self { + stats: Arc::new(RwLock::new(Metrics::default())), + } + } + + pub async fn get_stats(&self) -> RwLockReadGuard<'_, Metrics> { + self.stats.read().await + } + + pub async fn increase_tcp4_announces(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.tcp4_announces_handled += 1; + drop(stats_lock); + } + + pub async fn increase_tcp4_connections(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.tcp4_connections_handled += 1; + drop(stats_lock); + } + + pub async fn increase_tcp4_scrapes(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.tcp4_scrapes_handled += 1; + drop(stats_lock); + } + + pub async fn increase_tcp6_announces(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.tcp6_announces_handled += 1; + drop(stats_lock); + } + + pub async fn increase_tcp6_connections(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.tcp6_connections_handled += 1; + drop(stats_lock); + } + + pub async fn increase_tcp6_scrapes(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.tcp6_scrapes_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp_requests_aborted(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp_requests_aborted += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_requests(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_requests += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_connections(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_connections_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_announces(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_announces_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_scrapes(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_scrapes_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_responses(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_responses += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_errors(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_errors_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_requests(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_requests += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_connections(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_connections_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_announces(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_announces_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_scrapes(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_scrapes_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_responses(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_responses += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_errors(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_errors_handled += 1; + drop(stats_lock); + } +} diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index e7057f30a..55cb3a581 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -102,7 +102,7 @@ mod tests { use super::Stats; use crate::core::services::statistics::TrackerMetrics; - use crate::core::statistics::Metrics; + use crate::core::statistics::metrics::Metrics; #[test] fn stats_resource_should_be_converted_from_tracker_metrics() { diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 51ec43d56..73d480c79 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -6,7 +6,7 @@ //! and it returns the [`AnnounceData`] returned //! by the [`Tracker`]. //! -//! It also sends an [`statistics::Event`] +//! It also sends an [`statistics::event::Event`] //! because events are specific for the HTTP tracker. use std::net::IpAddr; use std::sync::Arc; @@ -39,10 +39,10 @@ pub async fn invoke( match original_peer_ip { IpAddr::V4(_) => { - tracker.send_stats_event(statistics::Event::Tcp4Announce).await; + tracker.send_stats_event(statistics::event::Event::Tcp4Announce).await; } IpAddr::V6(_) => { - tracker.send_stats_event(statistics::Event::Tcp6Announce).await; + tracker.send_stats_event(statistics::event::Event::Tcp6Announce).await; } } @@ -132,10 +132,10 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_announce_event_when_the_peer_uses_ipv4() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Tcp4Announce)) + .with(eq(statistics::event::Event::Tcp4Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -144,7 +144,7 @@ mod tests { Tracker::new( &configuration::ephemeral().core, Some(stats_event_sender), - statistics::Repo::new(), + statistics::repository::Repository::new(), ) .unwrap(), ); @@ -154,13 +154,18 @@ mod tests { let _announce_data = invoke(tracker, sample_info_hash(), &mut peer, &PeersWanted::All).await; } - fn tracker_with_an_ipv6_external_ip(stats_event_sender: Box) -> Tracker { + fn tracker_with_an_ipv6_external_ip(stats_event_sender: Box) -> Tracker { let mut configuration = configuration::ephemeral(); configuration.core.net.external_ip = Some(IpAddr::V6(Ipv6Addr::new( 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, ))); - Tracker::new(&configuration.core, Some(stats_event_sender), statistics::Repo::new()).unwrap() + Tracker::new( + &configuration.core, + Some(stats_event_sender), + statistics::repository::Repository::new(), + ) + .unwrap() } fn peer_with_the_ipv4_loopback_ip() -> peer::Peer { @@ -176,10 +181,10 @@ mod tests { // Tracker changes the peer IP to the tracker external IP when the peer is using the loopback IP. // Assert that the event sent is a TCP4 event - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Tcp4Announce)) + .with(eq(statistics::event::Event::Tcp4Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -198,10 +203,10 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_announce_event_when_the_peer_uses_ipv6_even_if_the_tracker_changes_the_peer_ip_to_ipv4() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Tcp6Announce)) + .with(eq(statistics::event::Event::Tcp6Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -210,7 +215,7 @@ mod tests { Tracker::new( &configuration::ephemeral().core, Some(stats_event_sender), - statistics::Repo::new(), + statistics::repository::Repository::new(), ) .unwrap(), ); diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index f040e0430..9eef263cb 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -6,7 +6,7 @@ //! and it returns the [`ScrapeData`] returned //! by the [`Tracker`]. //! -//! It also sends an [`statistics::Event`] +//! It also sends an [`statistics::event::Event`] //! because events are specific for the HTTP tracker. use std::net::IpAddr; use std::sync::Arc; @@ -48,10 +48,10 @@ pub async fn fake(tracker: &Arc, info_hashes: &Vec, original_ async fn send_scrape_event(original_peer_ip: &IpAddr, tracker: &Arc) { match original_peer_ip { IpAddr::V4(_) => { - tracker.send_stats_event(statistics::Event::Tcp4Scrape).await; + tracker.send_stats_event(statistics::event::Event::Tcp4Scrape).await; } IpAddr::V6(_) => { - tracker.send_stats_event(statistics::Event::Tcp6Scrape).await; + tracker.send_stats_event(statistics::event::Event::Tcp6Scrape).await; } } } @@ -138,10 +138,10 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_scrape_event_when_the_peer_uses_ipv4() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Tcp4Scrape)) + .with(eq(statistics::event::Event::Tcp4Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -150,7 +150,7 @@ mod tests { Tracker::new( &configuration::ephemeral().core, Some(stats_event_sender), - statistics::Repo::new(), + statistics::repository::Repository::new(), ) .unwrap(), ); @@ -162,10 +162,10 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Tcp6Scrape)) + .with(eq(statistics::event::Event::Tcp6Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -174,7 +174,7 @@ mod tests { Tracker::new( &configuration::ephemeral().core, Some(stats_event_sender), - statistics::Repo::new(), + statistics::repository::Repository::new(), ) .unwrap(), ); @@ -221,10 +221,10 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_scrape_event_when_the_peer_uses_ipv4() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Tcp4Scrape)) + .with(eq(statistics::event::Event::Tcp4Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -233,7 +233,7 @@ mod tests { Tracker::new( &configuration::ephemeral().core, Some(stats_event_sender), - statistics::Repo::new(), + statistics::repository::Repository::new(), ) .unwrap(), ); @@ -245,10 +245,10 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Tcp6Scrape)) + .with(eq(statistics::event::Event::Tcp6Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -257,7 +257,7 @@ mod tests { Tracker::new( &configuration::ephemeral().core, Some(stats_event_sender), - statistics::Repo::new(), + statistics::repository::Repository::new(), ) .unwrap(), ); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 1fb450e1a..1f838cd68 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -155,10 +155,10 @@ pub async fn handle_connect( // send stats event match remote_addr { SocketAddr::V4(_) => { - tracker.send_stats_event(statistics::Event::Udp4Connect).await; + tracker.send_stats_event(statistics::event::Event::Udp4Connect).await; } SocketAddr::V6(_) => { - tracker.send_stats_event(statistics::Event::Udp6Connect).await; + tracker.send_stats_event(statistics::event::Event::Udp6Connect).await; } } @@ -211,10 +211,10 @@ pub async fn handle_announce( match remote_client_ip { IpAddr::V4(_) => { - tracker.send_stats_event(statistics::Event::Udp4Announce).await; + tracker.send_stats_event(statistics::event::Event::Udp4Announce).await; } IpAddr::V6(_) => { - tracker.send_stats_event(statistics::Event::Udp6Announce).await; + tracker.send_stats_event(statistics::event::Event::Udp6Announce).await; } } @@ -326,10 +326,10 @@ pub async fn handle_scrape( // send stats event match remote_addr { SocketAddr::V4(_) => { - tracker.send_stats_event(statistics::Event::Udp4Scrape).await; + tracker.send_stats_event(statistics::event::Event::Udp4Scrape).await; } SocketAddr::V6(_) => { - tracker.send_stats_event(statistics::Event::Udp6Scrape).await; + tracker.send_stats_event(statistics::event::Event::Udp6Scrape).await; } } @@ -374,10 +374,10 @@ async fn handle_error( // send stats event match remote_addr { SocketAddr::V4(_) => { - tracker.send_stats_event(statistics::Event::Udp4Error).await; + tracker.send_stats_event(statistics::event::Event::Udp4Error).await; } SocketAddr::V6(_) => { - tracker.send_stats_event(statistics::Event::Udp6Error).await; + tracker.send_stats_event(statistics::event::Event::Udp6Error).await; } } } @@ -602,10 +602,10 @@ mod tests { #[tokio::test] async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Udp4Connect)) + .with(eq(statistics::event::Event::Udp4Connect)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -616,7 +616,7 @@ mod tests { core::Tracker::new( &tracker_configuration().core, Some(stats_event_sender), - statistics::Repo::new(), + statistics::repository::Repository::new(), ) .unwrap(), ); @@ -631,10 +631,10 @@ mod tests { #[tokio::test] async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Udp6Connect)) + .with(eq(statistics::event::Event::Udp6Connect)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -643,7 +643,7 @@ mod tests { core::Tracker::new( &tracker_configuration().core, Some(stats_event_sender), - statistics::Repo::new(), + statistics::repository::Repository::new(), ) .unwrap(), ); @@ -892,10 +892,10 @@ mod tests { #[tokio::test] async fn should_send_the_upd4_announce_event() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Udp4Announce)) + .with(eq(statistics::event::Event::Udp4Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -904,7 +904,7 @@ mod tests { core::Tracker::new( &tracker_configuration().core, Some(stats_event_sender), - statistics::Repo::new(), + statistics::repository::Repository::new(), ) .unwrap(), ); @@ -1138,10 +1138,10 @@ mod tests { #[tokio::test] async fn should_send_the_upd6_announce_event() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Udp6Announce)) + .with(eq(statistics::event::Event::Udp6Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -1150,7 +1150,7 @@ mod tests { core::Tracker::new( &tracker_configuration().core, Some(stats_event_sender), - statistics::Repo::new(), + statistics::repository::Repository::new(), ) .unwrap(), ); @@ -1173,7 +1173,7 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; use crate::core; - use crate::core::statistics::Keeper; + use crate::core::statistics::keeper::Keeper; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; @@ -1434,10 +1434,10 @@ mod tests { #[tokio::test] async fn should_send_the_upd4_scrape_event() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Udp4Scrape)) + .with(eq(statistics::event::Event::Udp4Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -1447,7 +1447,7 @@ mod tests { core::Tracker::new( &tracker_configuration().core, Some(stats_event_sender), - statistics::Repo::new(), + statistics::repository::Repository::new(), ) .unwrap(), ); @@ -1478,10 +1478,10 @@ mod tests { #[tokio::test] async fn should_send_the_upd6_scrape_event() { - let mut stats_event_sender_mock = statistics::MockEventSender::new(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock .expect_send_event() - .with(eq(statistics::Event::Udp6Scrape)) + .with(eq(statistics::event::Event::Udp6Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); @@ -1491,7 +1491,7 @@ mod tests { core::Tracker::new( &tracker_configuration().core, Some(stats_event_sender), - statistics::Repo::new(), + statistics::repository::Repository::new(), ) .unwrap(), ); diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index f314e3721..1d1ba4de4 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -166,10 +166,10 @@ impl Launcher { match req.from.ip() { IpAddr::V4(_) => { - tracker.send_stats_event(statistics::Event::Udp4Request).await; + tracker.send_stats_event(statistics::event::Event::Udp4Request).await; } IpAddr::V6(_) => { - tracker.send_stats_event(statistics::Event::Udp6Request).await; + tracker.send_stats_event(statistics::event::Event::Udp6Request).await; } } @@ -202,7 +202,7 @@ impl Launcher { if old_request_aborted { // Evicted task from active requests buffer was aborted. - tracker.send_stats_event(statistics::Event::Udp4RequestAborted).await; + tracker.send_stats_event(statistics::event::Event::Udp4RequestAborted).await; } } else { tokio::task::yield_now().await; diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 120196431..9a9798698 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -71,10 +71,10 @@ impl Processor { match target.ip() { IpAddr::V4(_) => { - self.tracker.send_stats_event(statistics::Event::Udp4Response).await; + self.tracker.send_stats_event(statistics::event::Event::Udp4Response).await; } IpAddr::V6(_) => { - self.tracker.send_stats_event(statistics::Event::Udp6Response).await; + self.tracker.send_stats_event(statistics::event::Event::Udp6Response).await; } } } From 0e13ff72554507218d2a548b54c4478c1410f48e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 18 Dec 2024 10:53:36 +0000 Subject: [PATCH 0547/1297] fix: [1097] do not compile slow doc tests It takes 32 seconds to compile and run all doc tests inckuding the ones that use the main tracker lib (each test compiles the main lib). This change disabled the compilation and execution of those tests. In terms of code coverage is not a problem becuase we have units test for that functionality. It only affects to the documentation. However there are too slow and they are even making crah some developers' computers. The good solution would be to extract those parts into new workspace packages to avoid compiling the main library. A new issue has been opened for it: https://github.com/torrust/torrust-tracker/issues/1140 --- src/core/auth.rs | 2 +- src/core/databases/driver.rs | 4 ++-- src/servers/http/v1/query.rs | 8 ++++---- src/servers/http/v1/requests/announce.rs | 2 +- src/servers/http/v1/responses/announce.rs | 4 ++-- src/servers/http/v1/responses/error.rs | 2 +- src/servers/http/v1/responses/scrape.rs | 2 +- src/servers/http/v1/services/peer_ip_resolver.rs | 4 ++-- 8 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/core/auth.rs b/src/core/auth.rs index 0243fceb4..7bbb25eca 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -196,7 +196,7 @@ impl Key { /// Error returned when a key cannot be parsed from a string. /// -/// ```rust,no_run +/// ```text /// use torrust_tracker::core::auth::Key; /// use std::str::FromStr; /// diff --git a/src/core/databases/driver.rs b/src/core/databases/driver.rs index a456a2650..3cbab9473 100644 --- a/src/core/databases/driver.rs +++ b/src/core/databases/driver.rs @@ -29,7 +29,7 @@ pub enum Driver { /// /// Example for `SQLite3`: /// -/// ```rust,no_run +/// ```text /// use torrust_tracker::core::databases; /// use torrust_tracker::core::databases::driver::Driver; /// @@ -40,7 +40,7 @@ pub enum Driver { /// /// Example for `MySQL`: /// -/// ```rust,no_run +/// ```text /// use torrust_tracker::core::databases; /// use torrust_tracker::core::databases::driver::Driver; /// diff --git a/src/servers/http/v1/query.rs b/src/servers/http/v1/query.rs index 3a078daae..abaf89845 100644 --- a/src/servers/http/v1/query.rs +++ b/src/servers/http/v1/query.rs @@ -30,7 +30,7 @@ impl Query { /// It return `Some(value)` for a URL query param if the param with the /// input `name` exists. For example: /// - /// ```rust + /// ```text /// use torrust_tracker::servers::http::v1::query::Query; /// /// let raw_query = "param1=value1¶m2=value2"; @@ -43,7 +43,7 @@ impl Query { /// /// It returns only the first param value even if it has multiple values: /// - /// ```rust + /// ```text /// use torrust_tracker::servers::http::v1::query::Query; /// /// let raw_query = "param1=value1¶m1=value2"; @@ -59,7 +59,7 @@ impl Query { /// Returns all the param values as a vector. /// - /// ```rust + /// ```text /// use torrust_tracker::servers::http::v1::query::Query; /// /// let query = "param1=value1¶m1=value2".parse::().unwrap(); @@ -72,7 +72,7 @@ impl Query { /// /// Returns all the param values as a vector even if it has only one value. /// - /// ```rust + /// ```text /// use torrust_tracker::servers::http::v1::query::Query; /// /// let query = "param1=value1".parse::().unwrap(); diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index 00bf53c6f..954d62c82 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -29,7 +29,7 @@ const NUMWANT: &str = "numwant"; /// The `Announce` request. Fields use the domain types after parsing the /// query params of the request. /// -/// ```rust +/// ```text /// use aquatic_udp_protocol::{NumberOfBytes, PeerId}; /// use torrust_tracker::servers::http::v1::requests::announce::{Announce, Compact, Event}; /// use bittorrent_primitives::info_hash::InfoHash; diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index f223a4bb0..bc63aa7fd 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -152,7 +152,7 @@ impl Into> for Compact { /// A [`NormalPeer`], for the [`Normal`] form. /// -/// ```rust +/// ```text /// use std::net::{IpAddr, Ipv4Addr}; /// use torrust_tracker::servers::http::v1::responses::announce::{Normal, NormalPeer}; /// @@ -204,7 +204,7 @@ impl From<&NormalPeer> for BencodeMut<'_> { /// A part from reducing the size of the response, this format does not contain /// the peer's ID. /// -/// ```rust +/// ```text /// use std::net::{IpAddr, Ipv4Addr}; /// use torrust_tracker::servers::http::v1::responses::announce::{Compact, CompactPeer, CompactPeerData}; /// diff --git a/src/servers/http/v1/responses/error.rs b/src/servers/http/v1/responses/error.rs index c406c797a..8572d861d 100644 --- a/src/servers/http/v1/responses/error.rs +++ b/src/servers/http/v1/responses/error.rs @@ -26,7 +26,7 @@ pub struct Error { impl Error { /// Returns the bencoded representation of the `Error` struct. /// - /// ```rust + /// ```text /// use torrust_tracker::servers::http::v1::responses::error::Error; /// /// let err = Error { diff --git a/src/servers/http/v1/responses/scrape.rs b/src/servers/http/v1/responses/scrape.rs index 0aef70cb1..878311ce7 100644 --- a/src/servers/http/v1/responses/scrape.rs +++ b/src/servers/http/v1/responses/scrape.rs @@ -11,7 +11,7 @@ use crate::core::ScrapeData; /// The `Scrape` response for the HTTP tracker. /// -/// ```rust +/// ```text /// use torrust_tracker::servers::http::v1::responses::scrape::Bencoded; /// use bittorrent_primitives::info_hash::InfoHash; /// use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; diff --git a/src/servers/http/v1/services/peer_ip_resolver.rs b/src/servers/http/v1/services/peer_ip_resolver.rs index b8987bb4d..548a99756 100644 --- a/src/servers/http/v1/services/peer_ip_resolver.rs +++ b/src/servers/http/v1/services/peer_ip_resolver.rs @@ -59,7 +59,7 @@ pub enum PeerIpResolutionError { /// /// With the tracker running on reverse proxy mode: /// -/// ```rust +/// ```text /// use std::net::IpAddr; /// use std::str::FromStr; /// @@ -81,7 +81,7 @@ pub enum PeerIpResolutionError { /// /// With the tracker non running on reverse proxy mode: /// -/// ```rust +/// ```text /// use std::net::IpAddr; /// use std::str::FromStr; /// From fb77972fc5660e8ddc57e8b754e62b2d4a0b73f2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 19 Dec 2024 11:31:33 +0000 Subject: [PATCH 0548/1297] feat: [#1139] increas ip ban duration to 1 hour --- src/servers/udp/server/launcher.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 1d1ba4de4..ada50eb31 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -25,7 +25,7 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// The maximum number of connection id errors per ip. Clients will be banned if /// they exceed this limit. const MAX_CONNECTION_ID_ERRORS_PER_IP: u32 = 10; -const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 120; +const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 3600; /// A UDP server instance launcher. #[derive(Constructor)] From d11ab3260c45d264fe068d41a6b13ba79f72f0d6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 23 Dec 2024 12:09:29 +0000 Subject: [PATCH 0549/1297] test: capture logs in tests This feature will be used in the future to write assertions about logs. It also changes when we show logs running tests. If you run tests with: ```console cargo test ``` logs win't be showed. If you want to see logs you have to execute tests with: ```console cargo test -- --nocapture ``` --- packages/test-helpers/src/configuration.rs | 7 +- src/bootstrap/logging.rs | 9 +- tests/common/clock.rs | 6 - tests/common/logging.rs | 166 ++++++++++-- .../servers/api/v1/contract/authentication.rs | 23 +- .../servers/api/v1/contract/configuration.rs | 9 - .../api/v1/contract/context/auth_key.rs | 74 ++---- .../api/v1/contract/context/health_check.rs | 7 +- .../servers/api/v1/contract/context/stats.rs | 11 +- .../api/v1/contract/context/torrent.rs | 51 +--- .../api/v1/contract/context/whitelist.rs | 51 +--- tests/servers/health_check_api/contract.rs | 40 +-- tests/servers/http/v1/contract.rs | 243 +++++------------- tests/servers/udp/contract.rs | 36 +-- tests/servers/udp/environment.rs | 7 +- 15 files changed, 302 insertions(+), 438 deletions(-) diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index acedbc672..e5de53fc2 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -29,7 +29,12 @@ pub fn ephemeral() -> Configuration { let mut config = Configuration::default(); - config.logging.threshold = Threshold::Off; // It should always be off here, the tests manage their own logging. + // This have to be Off otherwise the tracing global subscriber + // initialization will panic because you can't set a global subscriber more + // than once. You can use enable logging in tests with: + // `crate::common::logging::setup(LevelFilter::ERROR);` + // That will also allow you to capture logs and write assertions on them. + config.logging.threshold = Threshold::Off; // Ephemeral socket address for API let api_port = 0u16; diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index 34809c1ca..d7a100aed 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -28,7 +28,7 @@ pub fn setup(cfg: &Configuration) { } INIT.call_once(|| { - tracing_stdout_init(tracing_level, &TraceStyle::Default); + tracing_init(tracing_level, &TraceStyle::Default); }); } @@ -43,8 +43,11 @@ fn map_to_tracing_level_filter(threshold: &Threshold) -> LevelFilter { } } -fn tracing_stdout_init(filter: LevelFilter, style: &TraceStyle) { - let builder = tracing_subscriber::fmt().with_max_level(filter).with_ansi(true); +fn tracing_init(filter: LevelFilter, style: &TraceStyle) { + let builder = tracing_subscriber::fmt() + .with_max_level(filter) + .with_ansi(true) + .with_test_writer(); let () = match style { TraceStyle::Default => builder.init(), diff --git a/tests/common/clock.rs b/tests/common/clock.rs index de3cc7c65..5d94bb83d 100644 --- a/tests/common/clock.rs +++ b/tests/common/clock.rs @@ -1,17 +1,11 @@ use std::time::Duration; use torrust_tracker_clock::clock::Time; -use tracing::level_filters::LevelFilter; -use crate::common::logging::{tracing_stderr_init, INIT}; use crate::CurrentClock; #[test] fn it_should_use_stopped_time_for_testing() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); - assert_eq!(CurrentClock::dbg_clock_type(), "Stopped".to_owned()); let time = CurrentClock::now(); diff --git a/tests/common/logging.rs b/tests/common/logging.rs index 71be2ece7..d2abc37b4 100644 --- a/tests/common/logging.rs +++ b/tests/common/logging.rs @@ -1,30 +1,156 @@ -#![allow(clippy::doc_markdown)] -//! Logging for the Integration Tests -//! -//! Tests should start their own logging. -//! -//! To find tests that do not start their own logging: -//! -//! ´´´ sh -//! awk 'BEGIN{RS=""; FS="\n"} /#\[tokio::test\]\s*async\s+fn\s+\w+\s*\(\s*\)\s*\{[^}]*\}/ && !/#\[tokio::test\]\s*async\s+fn\s+\w+\s*\(\s*\)\s*\{[^}]*INIT\.call_once/' $(find . -name "*.rs") -//! ´´´ -//! - -use std::sync::Once; +//! Setup for logging in tests. +use std::collections::VecDeque; +use std::io; +use std::sync::{Mutex, MutexGuard, Once, OnceLock}; +use torrust_tracker::bootstrap::logging::TraceStyle; use tracing::level_filters::LevelFilter; +use tracing_subscriber::fmt::MakeWriter; -#[allow(dead_code)] -pub static INIT: Once = Once::new(); +static INIT: Once = Once::new(); + +/// A global buffer containing the latest lines captured from logs. +#[doc(hidden)] +pub fn captured_logs_buffer() -> &'static Mutex { + static CAPTURED_LOGS_GLOBAL_BUFFER: OnceLock> = OnceLock::new(); + CAPTURED_LOGS_GLOBAL_BUFFER.get_or_init(|| Mutex::new(CircularBuffer::new(10000, 200))) +} + +pub fn setup() { + INIT.call_once(|| { + tracing_init(LevelFilter::ERROR, &TraceStyle::Default); + }); +} + +fn tracing_init(level_filter: LevelFilter, style: &TraceStyle) { + let mock_writer = LogCapturer::new(captured_logs_buffer()); -#[allow(dead_code)] -pub fn tracing_stderr_init(filter: LevelFilter) { let builder = tracing_subscriber::fmt() - .with_max_level(filter) + .with_max_level(level_filter) .with_ansi(true) - .with_writer(std::io::stderr); + .with_test_writer() + .with_writer(mock_writer); - builder.pretty().with_file(true).init(); + let () = match style { + TraceStyle::Default => builder.init(), + TraceStyle::Pretty(display_filename) => builder.pretty().with_file(*display_filename).init(), + TraceStyle::Compact => builder.compact().init(), + TraceStyle::Json => builder.json().init(), + }; tracing::info!("Logging initialized"); } + +/// It returns true is there is a log line containing all the texts passed. +/// +/// # Panics +/// +/// Will panic if it can't get the lock for the global buffer or convert it into +/// a vec. +#[must_use] +#[allow(dead_code)] +pub fn logs_contains_a_line_with(texts: &[&str]) -> bool { + // code-review: we can search directly in the buffer instead of converting + // the buffer into a string but that would slow down the tests because + // cloning should be faster that locking the buffer for searching. + // Because the buffer is not big. + let logs = String::from_utf8(captured_logs_buffer().lock().unwrap().as_vec()).unwrap(); + + for line in logs.split('\n') { + if contains(line, texts) { + return true; + } + } + + false +} + +#[allow(dead_code)] +fn contains(text: &str, texts: &[&str]) -> bool { + texts.iter().all(|&word| text.contains(word)) +} + +/// A tracing writer which captures the latests logs lines into a buffer. +/// It's used to capture the logs in the tests. +#[derive(Debug)] +pub struct LogCapturer<'a> { + logs: &'a Mutex, +} + +impl<'a> LogCapturer<'a> { + pub fn new(buf: &'a Mutex) -> Self { + Self { logs: buf } + } + + fn buf(&self) -> io::Result> { + self.logs.lock().map_err(|_| io::Error::from(io::ErrorKind::Other)) + } +} + +impl io::Write for LogCapturer<'_> { + fn write(&mut self, buf: &[u8]) -> io::Result { + print!("{}", String::from_utf8(buf.to_vec()).unwrap()); + + let mut target = self.buf()?; + + target.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.buf()?.flush() + } +} + +impl MakeWriter<'_> for LogCapturer<'_> { + type Writer = Self; + + fn make_writer(&self) -> Self::Writer { + LogCapturer::new(self.logs) + } +} + +#[derive(Debug)] +pub struct CircularBuffer { + max_size: usize, + buffer: VecDeque, +} + +impl CircularBuffer { + #[must_use] + pub fn new(max_lines: usize, average_line_size: usize) -> Self { + Self { + max_size: max_lines * average_line_size, + buffer: VecDeque::with_capacity(max_lines * average_line_size), + } + } + + /// # Errors + /// + /// Won't return any error. + #[allow(clippy::unnecessary_wraps)] + pub fn write(&mut self, buf: &[u8]) -> io::Result { + for &byte in buf { + if self.buffer.len() == self.max_size { + // Remove oldest byte to make space + self.buffer.pop_front(); + } + self.buffer.push_back(byte); + } + + Ok(buf.len()) + } + + /// # Errors + /// + /// Won't return any error. + #[allow(clippy::unnecessary_wraps)] + #[allow(clippy::unused_self)] + pub fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + + #[must_use] + pub fn as_vec(&self) -> Vec { + self.buffer.iter().copied().collect() + } +} diff --git a/tests/servers/api/v1/contract/authentication.rs b/tests/servers/api/v1/contract/authentication.rs index 5c5cd3ae0..8f5ce8f53 100644 --- a/tests/servers/api/v1/contract/authentication.rs +++ b/tests/servers/api/v1/contract/authentication.rs @@ -1,17 +1,14 @@ use torrust_tracker_test_helpers::configuration; -use tracing::level_filters::LevelFilter; use crate::common::http::{Query, QueryParam}; -use crate::common::logging::{tracing_stderr_init, INIT}; +use crate::common::logging::{self}; use crate::servers::api::v1::asserts::{assert_token_not_valid, assert_unauthorized}; use crate::servers::api::v1::client::Client; use crate::servers::api::Started; #[tokio::test] async fn should_authenticate_requests_by_using_a_token_query_param() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -28,9 +25,7 @@ async fn should_authenticate_requests_by_using_a_token_query_param() { #[tokio::test] async fn should_not_authenticate_requests_when_the_token_is_missing() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -45,9 +40,7 @@ async fn should_not_authenticate_requests_when_the_token_is_missing() { #[tokio::test] async fn should_not_authenticate_requests_when_the_token_is_empty() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -62,9 +55,7 @@ async fn should_not_authenticate_requests_when_the_token_is_empty() { #[tokio::test] async fn should_not_authenticate_requests_when_the_token_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -79,9 +70,7 @@ async fn should_not_authenticate_requests_when_the_token_is_invalid() { #[tokio::test] async fn should_allow_the_token_query_param_to_be_at_any_position_in_the_url_query() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; diff --git a/tests/servers/api/v1/contract/configuration.rs b/tests/servers/api/v1/contract/configuration.rs index be42f16ad..91aa138a8 100644 --- a/tests/servers/api/v1/contract/configuration.rs +++ b/tests/servers/api/v1/contract/configuration.rs @@ -7,18 +7,10 @@ // use crate::common::app::setup_with_configuration; // use crate::servers::api::environment::stopped_environment; -use tracing::level_filters::LevelFilter; - -use crate::common::logging::{tracing_stderr_init, INIT}; - #[tokio::test] #[ignore] #[should_panic = "Could not receive bind_address."] async fn should_fail_with_ssl_enabled_and_bad_ssl_config() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); - // let tracker = setup_with_configuration(&Arc::new(configuration::ephemeral())); // let config = tracker.config.http_api.clone(); @@ -36,6 +28,5 @@ async fn should_fail_with_ssl_enabled_and_bad_ssl_config() { // }; // let env = new_stopped(tracker, bind_to, tls); - // env.start().await; } diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 2792a513c..9560a2f49 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -3,9 +3,8 @@ use std::time::Duration; use serde::Serialize; use torrust_tracker::core::auth::Key; use torrust_tracker_test_helpers::configuration; -use tracing::level_filters::LevelFilter; -use crate::common::logging::{tracing_stderr_init, INIT}; +use crate::common::logging::{self}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_auth_key_utf8, assert_failed_to_delete_key, assert_failed_to_generate_key, assert_failed_to_reload_keys, @@ -17,9 +16,7 @@ use crate::servers::api::{force_database_error, Started}; #[tokio::test] async fn should_allow_generating_a_new_random_auth_key() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -43,9 +40,7 @@ async fn should_allow_generating_a_new_random_auth_key() { #[tokio::test] async fn should_allow_uploading_a_preexisting_auth_key() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -69,9 +64,7 @@ async fn should_allow_uploading_a_preexisting_auth_key() { #[tokio::test] async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -98,9 +91,7 @@ async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() #[tokio::test] async fn should_fail_when_the_auth_key_cannot_be_generated() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -120,9 +111,7 @@ async fn should_fail_when_the_auth_key_cannot_be_generated() { #[tokio::test] async fn should_allow_deleting_an_auth_key() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -151,9 +140,7 @@ async fn should_fail_generating_a_new_auth_key_when_the_provided_key_is_invalid( pub seconds_valid: u64, } - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -192,9 +179,7 @@ async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid( pub seconds_valid: String, } - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -223,9 +208,7 @@ async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid( #[tokio::test] async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -250,9 +233,7 @@ async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { #[tokio::test] async fn should_fail_when_the_auth_key_cannot_be_deleted() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -276,9 +257,7 @@ async fn should_fail_when_the_auth_key_cannot_be_deleted() { #[tokio::test] async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -315,9 +294,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { #[tokio::test] async fn should_allow_reloading_keys() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -336,9 +313,7 @@ async fn should_allow_reloading_keys() { #[tokio::test] async fn should_fail_when_keys_cannot_be_reloaded() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -359,9 +334,7 @@ async fn should_fail_when_keys_cannot_be_reloaded() { #[tokio::test] async fn should_not_allow_reloading_keys_for_unauthenticated_users() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -390,9 +363,8 @@ mod deprecated_generate_key_endpoint { use torrust_tracker::core::auth::Key; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging::{self}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_auth_key_utf8, assert_failed_to_generate_key, assert_invalid_key_duration_param, assert_token_not_valid, @@ -403,9 +375,7 @@ mod deprecated_generate_key_endpoint { #[tokio::test] async fn should_allow_generating_a_new_auth_key() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -426,9 +396,7 @@ mod deprecated_generate_key_endpoint { #[tokio::test] async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -451,9 +419,7 @@ mod deprecated_generate_key_endpoint { #[tokio::test] async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -476,9 +442,7 @@ mod deprecated_generate_key_endpoint { #[tokio::test] async fn should_fail_when_the_auth_key_cannot_be_generated() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; diff --git a/tests/servers/api/v1/contract/context/health_check.rs b/tests/servers/api/v1/contract/context/health_check.rs index af46a5abe..0fd3f6ea6 100644 --- a/tests/servers/api/v1/contract/context/health_check.rs +++ b/tests/servers/api/v1/contract/context/health_check.rs @@ -1,16 +1,13 @@ use torrust_tracker::servers::apis::v1::context::health_check::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; -use tracing::level_filters::LevelFilter; -use crate::common::logging::{tracing_stderr_init, INIT}; +use crate::common::logging; use crate::servers::api::v1::client::get; use crate::servers::api::Started; #[tokio::test] async fn health_check_endpoint_should_return_status_ok_if_api_is_running() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index 7853450e2..e05107d25 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -4,9 +4,8 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker::servers::apis::v1::context::stats::resources::Stats; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; -use tracing::level_filters::LevelFilter; -use crate::common::logging::{tracing_stderr_init, INIT}; +use crate::common::logging::{self}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{assert_stats, assert_token_not_valid, assert_unauthorized}; use crate::servers::api::v1::client::Client; @@ -14,9 +13,7 @@ use crate::servers::api::Started; #[tokio::test] async fn should_allow_getting_tracker_statistics() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -64,9 +61,7 @@ async fn should_allow_getting_tracker_statistics() { #[tokio::test] async fn should_not_allow_getting_tracker_statistics_for_unauthenticated_users() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index e500ac63c..55c25d228 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -5,10 +5,9 @@ use torrust_tracker::servers::apis::v1::context::torrent::resources::peer::Peer; use torrust_tracker::servers::apis::v1::context::torrent::resources::torrent::{self, Torrent}; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; -use tracing::level_filters::LevelFilter; use crate::common::http::{Query, QueryParam}; -use crate::common::logging::{tracing_stderr_init, INIT}; +use crate::common::logging::{self}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_bad_request, assert_invalid_infohash_param, assert_not_found, assert_token_not_valid, assert_torrent_info, @@ -22,9 +21,7 @@ use crate::servers::api::Started; #[tokio::test] async fn should_allow_getting_all_torrents() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -50,9 +47,7 @@ async fn should_allow_getting_all_torrents() { #[tokio::test] async fn should_allow_limiting_the_torrents_in_the_result() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -83,9 +78,7 @@ async fn should_allow_limiting_the_torrents_in_the_result() { #[tokio::test] async fn should_allow_the_torrents_result_pagination() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -116,9 +109,7 @@ async fn should_allow_the_torrents_result_pagination() { #[tokio::test] async fn should_allow_getting_a_list_of_torrents_providing_infohashes() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -162,9 +153,7 @@ async fn should_allow_getting_a_list_of_torrents_providing_infohashes() { #[tokio::test] async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_parsed() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -183,9 +172,7 @@ async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_ #[tokio::test] async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_parsed() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -204,9 +191,7 @@ async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_p #[tokio::test] async fn should_fail_getting_torrents_when_the_info_hash_parameter_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -229,9 +214,7 @@ async fn should_fail_getting_torrents_when_the_info_hash_parameter_is_invalid() #[tokio::test] async fn should_not_allow_getting_torrents_for_unauthenticated_users() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -252,9 +235,7 @@ async fn should_not_allow_getting_torrents_for_unauthenticated_users() { #[tokio::test] async fn should_allow_getting_a_torrent_info() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -285,9 +266,7 @@ async fn should_allow_getting_a_torrent_info() { #[tokio::test] async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exist() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -304,9 +283,7 @@ async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exis #[tokio::test] async fn should_fail_getting_a_torrent_info_when_the_provided_infohash_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -327,9 +304,7 @@ async fn should_fail_getting_a_torrent_info_when_the_provided_infohash_is_invali #[tokio::test] async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index 49ce3e865..2be1706fc 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -2,9 +2,8 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; -use tracing::level_filters::LevelFilter; -use crate::common::logging::{tracing_stderr_init, INIT}; +use crate::common::logging::{self}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_failed_to_reload_whitelist, assert_failed_to_remove_torrent_from_whitelist, assert_failed_to_whitelist_torrent, @@ -18,9 +17,7 @@ use crate::servers::api::{force_database_error, Started}; #[tokio::test] async fn should_allow_whitelisting_a_torrent() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -40,9 +37,7 @@ async fn should_allow_whitelisting_a_torrent() { #[tokio::test] async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -61,9 +56,7 @@ async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() #[tokio::test] async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -86,9 +79,7 @@ async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { #[tokio::test] async fn should_fail_when_the_torrent_cannot_be_whitelisted() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -105,9 +96,7 @@ async fn should_fail_when_the_torrent_cannot_be_whitelisted() { #[tokio::test] async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -132,9 +121,7 @@ async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invali #[tokio::test] async fn should_allow_removing_a_torrent_from_the_whitelist() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -154,9 +141,7 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { #[tokio::test] async fn should_not_fail_trying_to_remove_a_non_whitelisted_torrent_from_the_whitelist() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -173,9 +158,7 @@ async fn should_not_fail_trying_to_remove_a_non_whitelisted_torrent_from_the_whi #[tokio::test] async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_infohash_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -200,9 +183,7 @@ async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_inf #[tokio::test] async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -223,9 +204,7 @@ async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { #[tokio::test] async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthenticated_users() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -251,9 +230,7 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica #[tokio::test] async fn should_allow_reload_the_whitelist_from_the_database() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -280,9 +257,7 @@ async fn should_allow_reload_the_whitelist_from_the_database() { #[tokio::test] async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index d40899f98..9c79c4a37 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -1,17 +1,14 @@ use torrust_tracker::servers::health_check_api::resources::{Report, Status}; use torrust_tracker::servers::registar::Registar; use torrust_tracker_test_helpers::configuration; -use tracing::level_filters::LevelFilter; -use crate::common::logging::{tracing_stderr_init, INIT}; +use crate::common::logging; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::Started; #[tokio::test] async fn health_check_endpoint_should_return_status_ok_when_there_is_no_services_registered() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let configuration = configuration::ephemeral_with_no_services(); @@ -37,18 +34,15 @@ mod api { use torrust_tracker::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::api; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::Started; #[tokio::test] pub(crate) async fn it_should_return_good_health_for_api_service() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let configuration = Arc::new(configuration::ephemeral()); @@ -95,9 +89,7 @@ mod api { #[tokio::test] pub(crate) async fn it_should_return_error_when_api_service_was_stopped_after_registration() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let configuration = Arc::new(configuration::ephemeral()); @@ -152,18 +144,15 @@ mod http { use torrust_tracker::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::Started; use crate::servers::http; #[tokio::test] pub(crate) async fn it_should_return_good_health_for_http_service() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let configuration = Arc::new(configuration::ephemeral()); @@ -209,9 +198,7 @@ mod http { #[tokio::test] pub(crate) async fn it_should_return_error_when_http_service_was_stopped_after_registration() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let configuration = Arc::new(configuration::ephemeral()); @@ -266,18 +253,15 @@ mod udp { use torrust_tracker::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::health_check_api::client::get; use crate::servers::health_check_api::Started; use crate::servers::udp; #[tokio::test] pub(crate) async fn it_should_return_good_health_for_udp_service() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let configuration = Arc::new(configuration::ephemeral()); @@ -320,9 +304,7 @@ mod udp { #[tokio::test] pub(crate) async fn it_should_return_error_when_udp_service_was_stopped_after_registration() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let configuration = Arc::new(configuration::ephemeral()); diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 554849aee..632f38bf4 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -1,9 +1,12 @@ use torrust_tracker_test_helpers::configuration; +use crate::common::logging; use crate::servers::http::Started; #[tokio::test] async fn environment_should_be_started_and_stopped() { + logging::setup(); + let env = Started::new(&configuration::ephemeral().into()).await; env.stop().await; @@ -13,17 +16,14 @@ mod for_all_config_modes { use torrust_tracker::servers::http::v1::handlers::health_check::{Report, Status}; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::http::client::Client; use crate::servers::http::Started; #[tokio::test] async fn health_check_endpoint_should_return_ok_if_the_http_tracker_is_running() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; @@ -38,9 +38,8 @@ mod for_all_config_modes { mod and_running_on_reverse_proxy { use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::http::asserts::assert_could_not_find_remote_address_on_x_forwarded_for_header_error_response; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; @@ -48,9 +47,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_http_request_does_not_include_the_xff_http_request_header() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); // If the tracker is running behind a reverse proxy, the peer IP is the // right most IP in the `X-Forwarded-For` HTTP header, which is the IP of the proxy's client. @@ -68,9 +65,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_xff_http_request_header_contains_an_invalid_ip() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; @@ -109,10 +104,9 @@ mod for_all_config_modes { use tokio::net::TcpListener; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; use crate::common::fixtures::invalid_info_hashes; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::http::asserts::{ assert_announce_response, assert_bad_announce_request_error_response, assert_cannot_parse_query_param_error_response, assert_cannot_parse_query_params_error_response, assert_compact_announce_response, assert_empty_announce_response, @@ -125,9 +119,7 @@ mod for_all_config_modes { #[tokio::test] async fn it_should_start_and_stop() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; env.stop().await; @@ -135,9 +127,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_respond_if_only_the_mandatory_fields_are_provided() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -154,9 +144,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_url_query_component_is_empty() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -169,9 +157,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_url_query_parameters_are_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -188,9 +174,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_a_mandatory_field_is_missing() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -229,9 +213,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -250,9 +232,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_not_fail_when_the_peer_address_param_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); // AnnounceQuery does not even contain the `peer_addr` // The peer IP is obtained in two ways: @@ -274,9 +254,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_downloaded_param_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -297,9 +275,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_uploaded_param_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -320,9 +296,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_peer_id_param_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -350,9 +324,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_port_param_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -373,9 +345,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_left_param_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -396,9 +366,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_event_param_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -427,9 +395,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_compact_param_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -450,9 +416,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_numwant_param_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -473,9 +437,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_no_peers_if_the_announced_peer_is_the_first_one() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -506,9 +468,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_list_of_previously_announced_peers() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -550,9 +510,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_list_of_previously_announced_peers_including_peers_using_ipv4_and_ipv6() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -606,9 +564,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_consider_two_peers_to_be_the_same_when_they_have_the_same_peer_id_even_if_the_ip_is_different() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -634,9 +590,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_compact_response() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); // Tracker Returns Compact Peer Lists // https://www.bittorrent.org/beps/bep_0023.html @@ -677,9 +631,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_not_return_the_compact_response_by_default() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); // code-review: the HTTP tracker does not return the compact response by default if the "compact" // param is not provided in the announce URL. The BEP 23 suggest to do so. @@ -720,9 +672,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp4_connections_handled_in_statistics() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -741,9 +691,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp6_connections_handled_in_statistics() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) .await @@ -769,9 +717,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_not_increase_the_number_of_tcp6_connections_handled_if_the_client_is_not_using_an_ipv6_ip() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); // The tracker ignores the peer address in the request param. It uses the client remote ip address. @@ -796,9 +742,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp4_announce_requests_handled_in_statistics() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -817,9 +761,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp6_announce_requests_handled_in_statistics() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) .await @@ -845,9 +787,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_not_increase_the_number_of_tcp6_announce_requests_handled_if_the_client_is_not_using_an_ipv6_ip() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); // The tracker ignores the peer address in the request param. It uses the client remote ip address. @@ -872,9 +812,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_assign_to_the_peer_ip_the_remote_client_ip_instead_of_the_peer_address_in_the_request_param() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -905,9 +843,7 @@ mod for_all_config_modes { #[tokio::test] async fn when_the_client_ip_is_a_loopback_ipv4_it_should_assign_to_the_peer_ip_the_external_ip_in_the_tracker_configuration( ) { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); /* We assume that both the client and tracker share the same public IP. @@ -945,9 +881,7 @@ mod for_all_config_modes { #[tokio::test] async fn when_the_client_ip_is_a_loopback_ipv6_it_should_assign_to_the_peer_ip_the_external_ip_in_the_tracker_configuration( ) { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); /* We assume that both the client and tracker share the same public IP. @@ -989,9 +923,7 @@ mod for_all_config_modes { #[tokio::test] async fn when_the_tracker_is_behind_a_reverse_proxy_it_should_assign_to_the_peer_ip_the_ip_in_the_x_forwarded_for_http_header( ) { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); /* client <-> http proxy <-> tracker <-> Internet @@ -1046,10 +978,9 @@ mod for_all_config_modes { use tokio::net::TcpListener; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; use crate::common::fixtures::invalid_info_hashes; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::http::asserts::{ assert_cannot_parse_query_params_error_response, assert_missing_query_params_for_scrape_request_error_response, assert_scrape_response, @@ -1062,9 +993,7 @@ mod for_all_config_modes { #[tokio::test] #[allow(dead_code)] async fn should_fail_when_the_request_is_empty() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; let response = Client::new(*env.bind_address()).get("scrape").await; @@ -1076,9 +1005,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_fail_when_the_info_hash_param_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -1097,9 +1024,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_file_with_the_incomplete_peer_when_there_is_one_peer_with_bytes_pending_to_download() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -1139,9 +1064,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_the_file_with_the_complete_peer_when_there_is_one_peer_with_no_bytes_pending_to_download() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -1181,9 +1104,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_return_a_file_with_zeroed_values_when_there_are_no_peers() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -1204,9 +1125,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_accept_multiple_infohashes() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -1234,9 +1153,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_ot_tcp4_scrape_requests_handled_in_statistics() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -1261,9 +1178,7 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_ot_tcp6_scrape_requests_handled_in_statistics() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) .await @@ -1302,9 +1217,8 @@ mod configured_as_whitelisted { use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging::{self}; use crate::servers::http::asserts::{assert_is_announce_response, assert_torrent_not_in_whitelist_error_response}; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; @@ -1312,9 +1226,7 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_fail_if_the_torrent_is_not_in_the_whitelist() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_listed().into()).await; @@ -1331,9 +1243,7 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_allow_announcing_a_whitelisted_torrent() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_listed().into()).await; @@ -1361,9 +1271,8 @@ mod configured_as_whitelisted { use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging::{self}; use crate::servers::http::asserts::assert_scrape_response; use crate::servers::http::client::Client; use crate::servers::http::responses::scrape::{File, ResponseBuilder}; @@ -1371,9 +1280,7 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_return_the_zeroed_file_when_the_requested_file_is_not_whitelisted() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_listed().into()).await; @@ -1404,9 +1311,7 @@ mod configured_as_whitelisted { #[tokio::test] async fn should_return_the_file_stats_when_the_requested_file_is_whitelisted() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_listed().into()).await; @@ -1460,9 +1365,8 @@ mod configured_as_private { use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker::core::auth::Key; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::http::asserts::{assert_authentication_error_response, assert_is_announce_response}; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; @@ -1470,9 +1374,7 @@ mod configured_as_private { #[tokio::test] async fn should_respond_to_authenticated_peers() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_private().into()).await; @@ -1489,9 +1391,7 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_peer_has_not_provided_the_authentication_key() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_private().into()).await; @@ -1508,9 +1408,7 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_private().into()).await; @@ -1527,9 +1425,7 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_peer_cannot_be_authenticated_with_the_provided_key() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_private().into()).await; @@ -1556,9 +1452,8 @@ mod configured_as_private { use torrust_tracker::core::auth::Key; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::http::asserts::{assert_authentication_error_response, assert_scrape_response}; use crate::servers::http::client::Client; use crate::servers::http::responses::scrape::{File, ResponseBuilder}; @@ -1566,9 +1461,7 @@ mod configured_as_private { #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_private().into()).await; @@ -1585,9 +1478,7 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_zeroed_file_when_the_client_is_not_authenticated() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_private().into()).await; @@ -1618,9 +1509,7 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_real_file_stats_when_the_client_is_authenticated() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral_private().into()).await; @@ -1662,9 +1551,7 @@ mod configured_as_private { #[tokio::test] async fn should_return_the_zeroed_file_when_the_authentication_key_provided_by_the_client_is_invalid() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); // There is not authentication error // code-review: should this really be this way? diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 9e9085e62..86bb1d18c 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -10,9 +10,8 @@ use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; -use tracing::level_filters::LevelFilter; -use crate::common::logging::{tracing_stderr_init, INIT}; +use crate::common::logging; use crate::servers::udp::asserts::get_error_response_message; use crate::servers::udp::Started; @@ -41,9 +40,7 @@ async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrac #[tokio::test] async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_request() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -74,17 +71,14 @@ mod receiving_a_connection_request { use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::udp::asserts::is_connect_response; use crate::servers::udp::Started; #[tokio::test] async fn should_return_a_connect_response() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -123,9 +117,8 @@ mod receiving_an_announce_request { use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::udp::asserts::is_ipv4_announce_response; use crate::servers::udp::contract::send_connection_request; use crate::servers::udp::Started; @@ -173,9 +166,7 @@ mod receiving_an_announce_request { #[tokio::test] async fn should_return_an_announce_response() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -195,9 +186,7 @@ mod receiving_an_announce_request { #[tokio::test] async fn should_return_many_announce_response() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -220,9 +209,7 @@ mod receiving_an_announce_request { #[tokio::test] async fn should_ban_the_client_ip_if_it_sends_more_than_10_requests_with_a_cookie_value_not_normal() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; @@ -266,18 +253,15 @@ mod receiving_an_scrape_request { use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::udp::asserts::is_scrape_response; use crate::servers::udp::contract::send_connection_request; use crate::servers::udp::Started; #[tokio::test] async fn should_return_a_scrape_response() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index f96ba2bea..acfb199f2 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -101,16 +101,13 @@ mod tests { use tokio::time::sleep; use torrust_tracker_test_helpers::configuration; - use tracing::level_filters::LevelFilter; - use crate::common::logging::{tracing_stderr_init, INIT}; + use crate::common::logging; use crate::servers::udp::Started; #[tokio::test] async fn it_should_make_and_stop_udp_server() { - INIT.call_once(|| { - tracing_stderr_init(LevelFilter::ERROR); - }); + logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; sleep(Duration::from_secs(1)).await; From 9ac676c714ccf94feb6ece5a8e7cfc23d0650104 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 23 Dec 2024 16:08:12 +0000 Subject: [PATCH 0550/1297] feat: [#1146] override tower-http tracing error From: ``` 2024-12-23T15:54:25.842837Z ERROR tower_http::trace::on_failure: response failed classification=Status code: 500 Internal Server Error latency=0 ms ``` To: ``` 2024-12-23T16:06:53.553023Z ERROR API: response failed classification=Status code: 500 Internal Server Error latency=0 ms ``` The target has been changed: ``` 2024-12-23T15:54:25.842837Z ERROR tower_http::trace::on_failure: response failed classification=Status code: 500 Internal Server Error latency=0 ms 2024-12-23T16:06:53.553023Z ERROR API: response failed classification=Status code: 500 Internal Server Error latency=0 ms ``` It was changed to: - Easily identify the origin of the error in our code. - Allow to insert more fields in the future, for example, to write assertions about logs. --- src/servers/apis/routes.rs | 12 ++++++++++- src/servers/health_check_api/server.rs | 12 ++++++++++- src/servers/http/v1/routes.rs | 12 ++++++++++- src/servers/logging.rs | 29 ++++++++++++++++++++++++++ 4 files changed, 62 insertions(+), 3 deletions(-) diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 327cab0c5..2ae422607 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -17,10 +17,12 @@ use hyper::{Request, StatusCode}; use torrust_tracker_configuration::{AccessTokens, DEFAULT_TIMEOUT}; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; +use tower_http::classify::ServerErrorsFailureClass; use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; +use tower_http::LatencyUnit; use tracing::{instrument, Level, Span}; use super::v1; @@ -28,6 +30,7 @@ use super::v1::context::health_check::handlers::health_check_handler; use super::v1::middlewares::auth::State; use crate::core::Tracker; use crate::servers::apis::API_LOG_TARGET; +use crate::servers::logging::Latency; /// Add all API routes to the router. #[allow(clippy::needless_pass_by_value)] @@ -75,7 +78,14 @@ pub fn router(tracker: Arc, access_tokens: Arc) -> Router tracing::span!( target: API_LOG_TARGET, tracing::Level::INFO, "response", latency = %latency_ms, status = %status_code, request_id = %request_id); - }), + }) + .on_failure(|failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { + let latency = Latency::new( + LatencyUnit::Millis, + latency, + ); + tracing::error!(target: API_LOG_TARGET, "response failed classification={failure_classification} latency={latency}"); + }) ) .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) .layer( diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index df4b1cf69..f8ca65b82 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -14,15 +14,18 @@ use futures::Future; use hyper::Request; use serde_json::json; use tokio::sync::oneshot::{Receiver, Sender}; +use tower_http::classify::ServerErrorsFailureClass; use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; +use tower_http::LatencyUnit; use tracing::{instrument, Level, Span}; use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; use crate::servers::health_check_api::HEALTH_CHECK_API_LOG_TARGET; +use crate::servers::logging::Latency; use crate::servers::registar::ServiceRegistry; use crate::servers::signals::{graceful_shutdown, Halted}; @@ -73,7 +76,14 @@ pub fn start( tracing::span!( target: HEALTH_CHECK_API_LOG_TARGET, tracing::Level::INFO, "response", latency = %latency_ms, status = %status_code, request_id = %request_id); - }), + }) + .on_failure(|failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { + let latency = Latency::new( + LatencyUnit::Millis, + latency, + ); + tracing::error!(target: HEALTH_CHECK_API_LOG_TARGET, "response failed classification={failure_classification} latency={latency}"); + }) ) .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)); diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 16e39b61b..6eacb1e5c 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -13,15 +13,18 @@ use hyper::{Request, StatusCode}; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; +use tower_http::classify::ServerErrorsFailureClass; use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; +use tower_http::LatencyUnit; use tracing::{instrument, Level, Span}; use super::handlers::{announce, health_check, scrape}; use crate::core::Tracker; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; +use crate::servers::logging::Latency; /// It adds the routes to the router. /// @@ -72,7 +75,14 @@ pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { tracing::span!( target: HTTP_TRACKER_LOG_TARGET, tracing::Level::INFO, "response", server_socket_addr= %server_socket_addr, latency = %latency_ms, status = %status_code, request_id = %request_id); - }), + }) + .on_failure(|failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { + let latency = Latency::new( + LatencyUnit::Millis, + latency, + ); + tracing::error!(target: HTTP_TRACKER_LOG_TARGET, "response failed classification={failure_classification} latency={latency}"); + }) ) .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) .layer( diff --git a/src/servers/logging.rs b/src/servers/logging.rs index ad9ccbbcc..c503cfd35 100644 --- a/src/servers/logging.rs +++ b/src/servers/logging.rs @@ -1,3 +1,8 @@ +use std::fmt; +use std::time::Duration; + +use tower_http::LatencyUnit; + /// This is the prefix used in logs to identify a started service. /// /// For example: @@ -27,3 +32,27 @@ We should use something like: ``` */ + +pub struct Latency { + unit: LatencyUnit, + duration: Duration, +} + +impl Latency { + #[must_use] + pub fn new(unit: LatencyUnit, duration: Duration) -> Self { + Self { unit, duration } + } +} + +impl fmt::Display for Latency { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.unit { + LatencyUnit::Seconds => write!(f, "{} s", self.duration.as_secs_f64()), + LatencyUnit::Millis => write!(f, "{} ms", self.duration.as_millis()), + LatencyUnit::Micros => write!(f, "{} μs", self.duration.as_micros()), + LatencyUnit::Nanos => write!(f, "{} ns", self.duration.as_nanos()), + _ => panic!("Invalid latency unit"), + } + } +} From 97233f57aa9595e05bc6d44ad2dd41ae1087e3de Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 23 Dec 2024 17:55:04 +0000 Subject: [PATCH 0551/1297] fix: missing logs for HTTP requests Some tracing log spans were missing. In adition to that we were using new spans to log requests and responses instead of using the span provided by the TraceLayer. That enables to join all the log events related tho the same requests. This fix is needed to contunie with this issue: https://github.com/torrust/torrust-tracker/issues/1150 Becuase it allos to use a "request-id" header to identify logs. We can write log assertions by mathich lines with the request-id used in the request. For example, it yo make this request: ```console curl -H "x-request-id: YOUR_REQUEST_ID" http://0.0.0.0:1212/api/v1/stats?token=InvalidToken ``` This is the new output (which was missing before this change): ```output 2024-12-23T17:53:06.530704Z INFO request{method=GET uri=/api/v1/stats?token=InvalidToken version=HTTP/1.1}: API: request method=GET uri=/api/v1/stats?token=InvalidToken request_id=YOUR_REQUEST_ID 2024-12-23T17:53:06.530777Z ERROR request{method=GET uri=/api/v1/stats?token=InvalidToken version=HTTP/1.1}: API: response latency_ms=0 status_code=500 Internal Server Error request_id=YOUR_REQUEST_ID 2024-12-23T17:53:06.530785Z ERROR request{method=GET uri=/api/v1/stats?token=InvalidToken version=HTTP/1.1}: API: response failed failure_classification=Status code: 500 Internal Server Error latency=0 ms ``` As you can see. now we have the "request_id=YOUR_REQUEST_ID" field which can be used to identify the test that made the request. --- src/servers/apis/routes.rs | 42 +++++++++++++++--------- src/servers/health_check_api/server.rs | 42 +++++++++++++++--------- src/servers/http/v1/routes.rs | 44 ++++++++++++++++---------- 3 files changed, 82 insertions(+), 46 deletions(-) diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 2ae422607..c021cb215 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -53,7 +53,7 @@ pub fn router(tracker: Arc, access_tokens: Arc) -> Router .layer( TraceLayer::new_for_http() .make_span_with(DefaultMakeSpan::new().level(Level::INFO)) - .on_request(|request: &Request, _span: &Span| { + .on_request(|request: &Request, span: &Span| { let method = request.method().to_string(); let uri = request.uri().to_string(); let request_id = request @@ -62,30 +62,42 @@ pub fn router(tracker: Arc, access_tokens: Arc) -> Router .map(|v| v.to_str().unwrap_or_default()) .unwrap_or_default(); - tracing::span!( + span.record("request_id", request_id); + + tracing::event!( target: API_LOG_TARGET, - tracing::Level::INFO, "request", method = %method, uri = %uri, request_id = %request_id); + tracing::Level::INFO, %method, %uri, %request_id, "request"); }) - .on_response(|response: &Response, latency: Duration, _span: &Span| { + .on_response(|response: &Response, latency: Duration, span: &Span| { + let latency_ms = latency.as_millis(); let status_code = response.status(); let request_id = response .headers() .get("x-request-id") .map(|v| v.to_str().unwrap_or_default()) .unwrap_or_default(); - let latency_ms = latency.as_millis(); - tracing::span!( - target: API_LOG_TARGET, - tracing::Level::INFO, "response", latency = %latency_ms, status = %status_code, request_id = %request_id); - }) - .on_failure(|failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { - let latency = Latency::new( - LatencyUnit::Millis, - latency, - ); - tracing::error!(target: API_LOG_TARGET, "response failed classification={failure_classification} latency={latency}"); + span.record("request_id", request_id); + + if status_code.is_server_error() { + tracing::event!( + target: API_LOG_TARGET, + tracing::Level::ERROR, %latency_ms, %status_code, %request_id, "response"); + } else { + tracing::event!( + target: API_LOG_TARGET, + tracing::Level::INFO, %latency_ms, %status_code, %request_id, "response"); + } }) + .on_failure( + |failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { + let latency = Latency::new(LatencyUnit::Millis, latency); + + tracing::event!( + target: API_LOG_TARGET, + tracing::Level::ERROR, %failure_classification, %latency, "response failed"); + }, + ), ) .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) .layer( diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index f8ca65b82..42111f507 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -51,7 +51,7 @@ pub fn start( .layer( TraceLayer::new_for_http() .make_span_with(DefaultMakeSpan::new().level(Level::INFO)) - .on_request(|request: &Request, _span: &Span| { + .on_request(|request: &Request, span: &Span| { let method = request.method().to_string(); let uri = request.uri().to_string(); let request_id = request @@ -60,30 +60,42 @@ pub fn start( .map(|v| v.to_str().unwrap_or_default()) .unwrap_or_default(); - tracing::span!( + span.record("request_id", request_id); + + tracing::event!( target: HEALTH_CHECK_API_LOG_TARGET, - tracing::Level::INFO, "request", method = %method, uri = %uri, request_id = %request_id); + tracing::Level::INFO, %method, %uri, %request_id, "request"); }) - .on_response(|response: &Response, latency: Duration, _span: &Span| { + .on_response(|response: &Response, latency: Duration, span: &Span| { + let latency_ms = latency.as_millis(); let status_code = response.status(); let request_id = response .headers() .get("x-request-id") .map(|v| v.to_str().unwrap_or_default()) .unwrap_or_default(); - let latency_ms = latency.as_millis(); - tracing::span!( - target: HEALTH_CHECK_API_LOG_TARGET, - tracing::Level::INFO, "response", latency = %latency_ms, status = %status_code, request_id = %request_id); - }) - .on_failure(|failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { - let latency = Latency::new( - LatencyUnit::Millis, - latency, - ); - tracing::error!(target: HEALTH_CHECK_API_LOG_TARGET, "response failed classification={failure_classification} latency={latency}"); + span.record("request_id", request_id); + + if status_code.is_server_error() { + tracing::event!( + target: HEALTH_CHECK_API_LOG_TARGET, + tracing::Level::ERROR, %latency_ms, %status_code, %request_id, "response"); + } else { + tracing::event!( + target: HEALTH_CHECK_API_LOG_TARGET, + tracing::Level::INFO, %latency_ms, %status_code, %request_id, "response"); + } }) + .on_failure( + |failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { + let latency = Latency::new(LatencyUnit::Millis, latency); + + tracing::event!( + target: HEALTH_CHECK_API_LOG_TARGET, + tracing::Level::ERROR, %failure_classification, %latency, "response failed"); + }, + ), ) .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)); diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 6eacb1e5c..a5d402693 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -50,7 +50,7 @@ pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { .layer( TraceLayer::new_for_http() .make_span_with(DefaultMakeSpan::new().level(Level::INFO)) - .on_request(move |request: &Request, _span: &Span| { + .on_request(move |request: &Request, span: &Span| { let method = request.method().to_string(); let uri = request.uri().to_string(); let request_id = request @@ -59,33 +59,45 @@ pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { .map(|v| v.to_str().unwrap_or_default()) .unwrap_or_default(); - tracing::span!( + span.record("request_id", request_id); + + tracing::event!( target: HTTP_TRACKER_LOG_TARGET, - tracing::Level::INFO, "request", server_socket_addr= %server_socket_addr, method = %method, uri = %uri, request_id = %request_id); + tracing::Level::INFO, %server_socket_addr, %method, %uri, %request_id, "request"); }) - .on_response(move |response: &Response, latency: Duration, _span: &Span| { + .on_response(move |response: &Response, latency: Duration, span: &Span| { + let latency_ms = latency.as_millis(); let status_code = response.status(); let request_id = response .headers() .get("x-request-id") .map(|v| v.to_str().unwrap_or_default()) .unwrap_or_default(); - let latency_ms = latency.as_millis(); - tracing::span!( - target: HTTP_TRACKER_LOG_TARGET, - tracing::Level::INFO, "response", server_socket_addr= %server_socket_addr, latency = %latency_ms, status = %status_code, request_id = %request_id); - }) - .on_failure(|failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { - let latency = Latency::new( - LatencyUnit::Millis, - latency, - ); - tracing::error!(target: HTTP_TRACKER_LOG_TARGET, "response failed classification={failure_classification} latency={latency}"); + span.record("request_id", request_id); + + if status_code.is_server_error() { + tracing::event!( + target: HTTP_TRACKER_LOG_TARGET, + tracing::Level::ERROR, %server_socket_addr, %latency_ms, %status_code, %request_id, "response"); + } else { + tracing::event!( + target: HTTP_TRACKER_LOG_TARGET, + tracing::Level::INFO, %server_socket_addr, %latency_ms, %status_code, %request_id, "response"); + } }) + .on_failure( + |failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { + let latency = Latency::new(LatencyUnit::Millis, latency); + + tracing::event!( + target: HTTP_TRACKER_LOG_TARGET, + tracing::Level::ERROR, %failure_classification, %latency, "response failed"); + }, + ), ) .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)) - .layer( + .layer( ServiceBuilder::new() // this middleware goes above `TimeoutLayer` because it will receive // errors returned by `TimeoutLayer` From 86b046068389d37ab5e53ea4b37c9b0c2fe1329d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 23 Dec 2024 19:37:48 +0000 Subject: [PATCH 0552/1297] chore(deps): update depencencies ```output cargo update Updating crates.io index Locking 19 packages to latest compatible versions Updating anyhow v1.0.94 -> v1.0.95 Updating bytemuck v1.20.0 -> v1.21.0 Updating cc v1.2.4 -> v1.2.5 Updating foldhash v0.1.3 -> v0.1.4 Updating hyper-rustls v0.27.3 -> v0.27.5 Updating libc v0.2.168 -> v0.2.169 Updating miniz_oxide v0.8.0 -> v0.8.2 Updating object v0.36.5 -> v0.36.7 Updating predicates v3.1.2 -> v3.1.3 Updating predicates-core v1.0.8 -> v1.0.9 Updating predicates-tree v1.0.11 -> v1.0.12 Updating security-framework-sys v2.12.1 -> v2.13.0 Updating serde_html_form v0.2.6 -> v0.2.7 Updating serde_json v1.0.133 -> v1.0.134 Updating syn v2.0.90 -> v2.0.91 Updating termtree v0.4.1 -> v0.5.1 Updating thiserror v2.0.7 -> v2.0.9 Updating thiserror-impl v2.0.7 -> v2.0.9 Updating tinyvec v1.8.0 -> v1.8.1 ``` --- Cargo.lock | 166 ++++++++++++++++++++++++++--------------------------- 1 file changed, 83 insertions(+), 83 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index dacd04454..98875f48d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -142,9 +142,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.94" +version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1fd03a028ef38ba2276dce7e33fcd6369c158a1bca17946c4b1b701891c1ff7" +checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04" [[package]] name = "aquatic_peer_id" @@ -333,7 +333,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -456,7 +456,7 @@ checksum = "57d123550fa8d071b7255cb0cc04dc302baa6c8c4a79f55701552684d8399bce" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -544,7 +544,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -597,7 +597,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_repr", - "thiserror 2.0.7", + "thiserror 2.0.9", "tokio", "torrust-tracker-configuration", "torrust-tracker-located-error", @@ -679,7 +679,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -748,9 +748,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.20.0" +version = "1.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b37c88a63ffd85d15b406896cc343916d7cf57838a847b3a6f2ca5d39a5695a" +checksum = "ef657dfab802224e671f5818e9a4935f9b1957ed18e58292690cc39e7a4092a3" [[package]] name = "byteorder" @@ -790,9 +790,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.4" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9157bbaa6b165880c27a4293a474c91cdcf265cc68cc829bf10be0964a391caf" +checksum = "c31a0499c1dc64f458ad13872de75c0eb7e3fdb0e67964610c914b034fc5956e" dependencies = [ "jobserver", "libc", @@ -912,7 +912,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1133,7 +1133,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1144,7 +1144,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1188,7 +1188,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "unicode-xid", ] @@ -1200,7 +1200,7 @@ checksum = "65f152f4b8559c4da5d574bafc7af85454d706b4c5fe8b530d508cacbb6807ea" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1221,7 +1221,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1351,9 +1351,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "foldhash" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f81ec6369c545a7d40e4589b5597581fa1c441fe1cce96dd1de43159910a36a2" +checksum = "a0d2fde1f7b3d48b8395d5f2de76c18a528bd6a9cdde438df747bfcba3e05d6f" [[package]] name = "foreign-types" @@ -1424,7 +1424,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1436,7 +1436,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1448,7 +1448,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1526,7 +1526,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1770,9 +1770,9 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.3" +version = "0.27.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333" +checksum = "2d191583f3da1305256f22463b9bb0471acad48a4e534a5218b9963e9c1f59b2" dependencies = [ "futures-util", "http", @@ -1958,7 +1958,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -2117,9 +2117,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.168" +version = "0.2.169" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aaeb2981e0606ca11d79718f8bb01164f1d6ed75080182d3abf017e6d244b6d" +checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" [[package]] name = "libloading" @@ -2237,9 +2237,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.8.0" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" +checksum = "4ffbe83022cedc1d264172192511ae958937694cd57ce297164951b8b3568394" dependencies = [ "adler2", ] @@ -2278,7 +2278,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -2345,7 +2345,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "termcolor", "thiserror 1.0.69", ] @@ -2502,9 +2502,9 @@ dependencies = [ [[package]] name = "object" -version = "0.36.5" +version = "0.36.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" +checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" dependencies = [ "memchr", ] @@ -2544,7 +2544,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -2620,7 +2620,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -2694,7 +2694,7 @@ checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -2792,9 +2792,9 @@ dependencies = [ [[package]] name = "predicates" -version = "3.1.2" +version = "3.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e9086cc7640c29a356d1a29fd134380bee9d8f79a17410aa76e7ad295f42c97" +checksum = "a5d19ee57562043d37e82899fade9a22ebab7be9cef5026b07fda9cdd4293573" dependencies = [ "anstyle", "predicates-core", @@ -2802,15 +2802,15 @@ dependencies = [ [[package]] name = "predicates-core" -version = "1.0.8" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae8177bee8e75d6846599c6b9ff679ed51e882816914eec639944d7c9aa11931" +checksum = "727e462b119fe9c93fd0eb1429a5f7647394014cf3c04ab2c0350eeb09095ffa" [[package]] name = "predicates-tree" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41b740d195ed3166cd147c8047ec98db0e22ec019eb8eeb76d343b795304fb13" +checksum = "72dd2d6d381dfb73a193c7fca536518d7caee39fc8503f74e7dc0be0531b425c" dependencies = [ "predicates-core", "termtree", @@ -2844,7 +2844,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -2864,7 +2864,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "version_check", "yansi", ] @@ -3173,7 +3173,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.90", + "syn 2.0.91", "unicode-ident", ] @@ -3352,9 +3352,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.12.1" +version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa39c7303dc58b5543c94d22c1766b0d31f2ee58306363ea622b10bbc075eaa2" +checksum = "1863fd3768cd83c56a7f60faa4dc0d403f1b6df0a38c3c25f44b7894e45370d5" dependencies = [ "core-foundation-sys", "libc", @@ -3402,14 +3402,14 @@ checksum = "46f859dbbf73865c6627ed570e78961cd3ac92407a2d117204c49232485da55e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] name = "serde_html_form" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de514ef58196f1fc96dcaef80fe6170a1ce6215df9687a93fe8300e773fefc5" +checksum = "9d2de91cf02bbc07cde38891769ccd5d4f073d22a40683aa4bc7a95781aaa2c4" dependencies = [ "form_urlencoded", "indexmap 2.7.0", @@ -3420,9 +3420,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.133" +version = "1.0.134" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" +checksum = "d00f4175c42ee48b15416f6193a959ba3a0d67fc699a0db9ad12df9f83991c7d" dependencies = [ "indexmap 2.7.0", "itoa", @@ -3449,7 +3449,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -3500,7 +3500,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -3639,9 +3639,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.90" +version = "2.0.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31" +checksum = "d53cbcb5a243bd33b7858b1d7f4aca2153490815872d86d955d6ea29f743c035" dependencies = [ "proc-macro2", "quote", @@ -3665,7 +3665,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -3736,9 +3736,9 @@ dependencies = [ [[package]] name = "termtree" -version = "0.4.1" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "thiserror" @@ -3751,11 +3751,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.7" +version = "2.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93605438cbd668185516ab499d589afb7ee1859ea3d5fc8f6b0755e1c7443767" +checksum = "f072643fd0190df67a8bab670c20ef5d8737177d6ac6b2e9a236cb096206b2cc" dependencies = [ - "thiserror-impl 2.0.7", + "thiserror-impl 2.0.9", ] [[package]] @@ -3766,18 +3766,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] name = "thiserror-impl" -version = "2.0.7" +version = "2.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1d8749b4531af2117677a5fcd12b1348a3fe2b81e36e61ffeac5c4aa3273e36" +checksum = "7b50fa271071aae2e6ee85f842e2e28ba8cd2c5fb67f11fcb1fd70b276f9e7d4" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -3843,9 +3843,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.8.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938" +checksum = "022db8904dfa342efe721985167e9fcd16c29b226db4397ed752a761cfce81e8" dependencies = [ "tinyvec_macros", ] @@ -3881,7 +3881,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -3999,7 +3999,7 @@ dependencies = [ "serde_json", "serde_repr", "serde_with", - "thiserror 2.0.7", + "thiserror 2.0.9", "tokio", "torrust-tracker-clock", "torrust-tracker-configuration", @@ -4034,7 +4034,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_json", - "thiserror 2.0.7", + "thiserror 2.0.9", "tokio", "torrust-tracker-configuration", "tracing", @@ -4061,7 +4061,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.7", + "thiserror 2.0.9", "toml", "torrust-tracker-located-error", "url", @@ -4073,14 +4073,14 @@ name = "torrust-tracker-contrib-bencode" version = "3.0.0-develop" dependencies = [ "criterion", - "thiserror 2.0.7", + "thiserror 2.0.9", ] [[package]] name = "torrust-tracker-located-error" version = "3.0.0-develop" dependencies = [ - "thiserror 2.0.7", + "thiserror 2.0.9", "tracing", ] @@ -4095,7 +4095,7 @@ dependencies = [ "serde", "tdyne-peer-id", "tdyne-peer-id-registry", - "thiserror 2.0.7", + "thiserror 2.0.9", "zerocopy", ] @@ -4211,7 +4211,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -4422,7 +4422,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "wasm-bindgen-shared", ] @@ -4457,7 +4457,7 @@ checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4686,7 +4686,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "synstructure", ] @@ -4708,7 +4708,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -4728,7 +4728,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "synstructure", ] @@ -4757,7 +4757,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] From 88d3d497de51436d230d2c2dfd6ebcb82b55a049 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 26 Dec 2024 09:36:06 +0000 Subject: [PATCH 0553/1297] feat: add server socket address to logs in API ``` 2024-12-26T09:07:18.149759Z ERROR API: response latency_ms=0 status_code=500 Internal Server Error server_socket_addr=127.0.0.1:41579 request_id=44d8c2f6-630d-4eab-a399-65aed1dbc8ab ``` --- src/servers/apis/routes.rs | 13 +++++++------ src/servers/apis/server.rs | 3 ++- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index c021cb215..0b0862fb9 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -5,6 +5,7 @@ //! //! All the API routes have the `/api` prefix and the version number as the //! first path segment. For example: `/api/v1/torrents`. +use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; @@ -35,7 +36,7 @@ use crate::servers::logging::Latency; /// Add all API routes to the router. #[allow(clippy::needless_pass_by_value)] #[instrument(skip(tracker, access_tokens))] -pub fn router(tracker: Arc, access_tokens: Arc) -> Router { +pub fn router(tracker: Arc, access_tokens: Arc, server_socket_addr: SocketAddr) -> Router { let router = Router::new(); let api_url_prefix = "/api"; @@ -68,7 +69,7 @@ pub fn router(tracker: Arc, access_tokens: Arc) -> Router target: API_LOG_TARGET, tracing::Level::INFO, %method, %uri, %request_id, "request"); }) - .on_response(|response: &Response, latency: Duration, span: &Span| { + .on_response(move |response: &Response, latency: Duration, span: &Span| { let latency_ms = latency.as_millis(); let status_code = response.status(); let request_id = response @@ -82,20 +83,20 @@ pub fn router(tracker: Arc, access_tokens: Arc) -> Router if status_code.is_server_error() { tracing::event!( target: API_LOG_TARGET, - tracing::Level::ERROR, %latency_ms, %status_code, %request_id, "response"); + tracing::Level::ERROR, %latency_ms, %status_code, %server_socket_addr, %request_id, "response"); } else { tracing::event!( target: API_LOG_TARGET, - tracing::Level::INFO, %latency_ms, %status_code, %request_id, "response"); + tracing::Level::INFO, %latency_ms, %status_code, %server_socket_addr, %request_id, "response"); } }) .on_failure( - |failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { + move |failure_classification: ServerErrorsFailureClass, latency: Duration, _span: &Span| { let latency = Latency::new(LatencyUnit::Millis, latency); tracing::event!( target: API_LOG_TARGET, - tracing::Level::ERROR, %failure_classification, %latency, "response failed"); + tracing::Level::ERROR, %failure_classification, %latency, %server_socket_addr, "response failed"); }, ), ) diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 31220f497..eadadecf2 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -243,10 +243,11 @@ impl Launcher { tx_start: Sender, rx_halt: Receiver, ) -> BoxFuture<'static, ()> { - let router = router(tracker, access_tokens); let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); + let router = router(tracker, access_tokens, address); + let handle = Handle::new(); tokio::task::spawn(graceful_shutdown( From cc2840f25e69e4fd7bf801c6afe5048c8afc2164 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 26 Dec 2024 10:24:35 +0000 Subject: [PATCH 0554/1297] feat: add an option to pass the request id in the API client Now you can send a header `x-request-id` to the API. ```rust let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) .get_request_with_query( "stats", Query::params([QueryParam::new("token", "")].to_vec()), Some(headers_with_request_id(request_id)), ) .await; ``` That ID is recorded in logs. So you can use it to track the request. --- tests/servers/api/v1/client.rs | 43 ++++++++++++------- .../servers/api/v1/contract/authentication.rs | 28 +++++++++--- .../api/v1/contract/context/health_check.rs | 2 +- 3 files changed, 50 insertions(+), 23 deletions(-) diff --git a/tests/servers/api/v1/client.rs b/tests/servers/api/v1/client.rs index 3d95c10ca..a447805d0 100644 --- a/tests/servers/api/v1/client.rs +++ b/tests/servers/api/v1/client.rs @@ -1,5 +1,7 @@ +use hyper::HeaderMap; use reqwest::Response; use serde::Serialize; +use uuid::Uuid; use crate::common::http::{Query, QueryParam, ReqwestQuery}; use crate::servers::api::connection_info::ConnectionInfo; @@ -65,7 +67,7 @@ impl Client { query.add_param(QueryParam::new("token", token)); }; - self.get_request_with_query(path, query).await + self.get_request_with_query(path, query, None).await } pub async fn post_empty(&self, path: &str) -> Response { @@ -96,12 +98,12 @@ impl Client { .unwrap() } - pub async fn get_request_with_query(&self, path: &str, params: Query) -> Response { - get(&self.base_url(path), Some(params)).await + pub async fn get_request_with_query(&self, path: &str, params: Query, headers: Option) -> Response { + get(&self.base_url(path), Some(params), headers).await } pub async fn get_request(&self, path: &str) -> Response { - get(&self.base_url(path), None).await + get(&self.base_url(path), None, None).await } fn query_with_token(&self) -> Query { @@ -116,18 +118,27 @@ impl Client { } } -pub async fn get(path: &str, query: Option) -> Response { - match query { - Some(params) => reqwest::Client::builder() - .build() - .unwrap() - .get(path) - .query(&ReqwestQuery::from(params)) - .send() - .await - .unwrap(), - None => reqwest::Client::builder().build().unwrap().get(path).send().await.unwrap(), - } +pub async fn get(path: &str, query: Option, headers: Option) -> Response { + let builder = reqwest::Client::builder().build().unwrap(); + + let builder = match query { + Some(params) => builder.get(path).query(&ReqwestQuery::from(params)), + None => builder.get(path), + }; + + let builder = match headers { + Some(headers) => builder.headers(headers), + None => builder, + }; + + builder.send().await.unwrap() +} + +/// Returns a `HeaderMap` with a request id header +pub fn headers_with_request_id(request_id: Uuid) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert("x-request-id", request_id.to_string().parse().unwrap()); + headers } #[derive(Serialize, Debug)] diff --git a/tests/servers/api/v1/contract/authentication.rs b/tests/servers/api/v1/contract/authentication.rs index 8f5ce8f53..dc50048fb 100644 --- a/tests/servers/api/v1/contract/authentication.rs +++ b/tests/servers/api/v1/contract/authentication.rs @@ -1,9 +1,10 @@ use torrust_tracker_test_helpers::configuration; +use uuid::Uuid; use crate::common::http::{Query, QueryParam}; -use crate::common::logging::{self}; +use crate::common::logging::{self, logs_contains_a_line_with}; use crate::servers::api::v1::asserts::{assert_token_not_valid, assert_unauthorized}; -use crate::servers::api::v1::client::Client; +use crate::servers::api::v1::client::{headers_with_request_id, Client}; use crate::servers::api::Started; #[tokio::test] @@ -15,7 +16,7 @@ async fn should_authenticate_requests_by_using_a_token_query_param() { let token = env.get_connection_info().api_token.unwrap(); let response = Client::new(env.get_connection_info()) - .get_request_with_query("stats", Query::params([QueryParam::new("token", &token)].to_vec())) + .get_request_with_query("stats", Query::params([QueryParam::new("token", &token)].to_vec()), None) .await; assert_eq!(response.status(), 200); @@ -30,7 +31,7 @@ async fn should_not_authenticate_requests_when_the_token_is_missing() { let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(env.get_connection_info()) - .get_request_with_query("stats", Query::default()) + .get_request_with_query("stats", Query::default(), None) .await; assert_unauthorized(response).await; @@ -44,13 +45,24 @@ async fn should_not_authenticate_requests_when_the_token_is_empty() { let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .get_request_with_query("stats", Query::params([QueryParam::new("token", "")].to_vec())) + .get_request_with_query( + "stats", + Query::params([QueryParam::new("token", "")].to_vec()), + Some(headers_with_request_id(request_id)), + ) .await; assert_token_not_valid(response).await; env.stop().await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); } #[tokio::test] @@ -60,7 +72,11 @@ async fn should_not_authenticate_requests_when_the_token_is_invalid() { let env = Started::new(&configuration::ephemeral().into()).await; let response = Client::new(env.get_connection_info()) - .get_request_with_query("stats", Query::params([QueryParam::new("token", "INVALID TOKEN")].to_vec())) + .get_request_with_query( + "stats", + Query::params([QueryParam::new("token", "INVALID TOKEN")].to_vec()), + None, + ) .await; assert_token_not_valid(response).await; diff --git a/tests/servers/api/v1/contract/context/health_check.rs b/tests/servers/api/v1/contract/context/health_check.rs index 0fd3f6ea6..fa6cfa094 100644 --- a/tests/servers/api/v1/contract/context/health_check.rs +++ b/tests/servers/api/v1/contract/context/health_check.rs @@ -13,7 +13,7 @@ async fn health_check_endpoint_should_return_status_ok_if_api_is_running() { let url = format!("http://{}/api/health_check", env.get_connection_info().bind_address); - let response = get(&url, None).await; + let response = get(&url, None, None).await; assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); From 5d49d48a74114f1eb80e60776433a71ec6ddb4a3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 26 Dec 2024 11:07:03 +0000 Subject: [PATCH 0555/1297] test: [#1152] write assertions when API writes errors into logs --- tests/servers/api/v1/client.rs | 92 +++++---- .../servers/api/v1/contract/authentication.rs | 22 +- .../api/v1/contract/context/auth_key.rs | 194 ++++++++++++++---- .../servers/api/v1/contract/context/stats.rs | 29 ++- .../api/v1/contract/context/torrent.rs | 120 ++++++++--- .../api/v1/contract/context/whitelist.rs | 122 +++++++++-- 6 files changed, 450 insertions(+), 129 deletions(-) diff --git a/tests/servers/api/v1/client.rs b/tests/servers/api/v1/client.rs index a447805d0..635331078 100644 --- a/tests/servers/api/v1/client.rs +++ b/tests/servers/api/v1/client.rs @@ -20,82 +20,94 @@ impl Client { } } - pub async fn generate_auth_key(&self, seconds_valid: i32) -> Response { - self.post_empty(&format!("key/{}", &seconds_valid)).await + pub async fn generate_auth_key(&self, seconds_valid: i32, headers: Option) -> Response { + self.post_empty(&format!("key/{}", &seconds_valid), headers).await } - pub async fn add_auth_key(&self, add_key_form: AddKeyForm) -> Response { - self.post_form("keys", &add_key_form).await + pub async fn add_auth_key(&self, add_key_form: AddKeyForm, headers: Option) -> Response { + self.post_form("keys", &add_key_form, headers).await } - pub async fn delete_auth_key(&self, key: &str) -> Response { - self.delete(&format!("key/{}", &key)).await + pub async fn delete_auth_key(&self, key: &str, headers: Option) -> Response { + self.delete(&format!("key/{}", &key), headers).await } - pub async fn reload_keys(&self) -> Response { - self.get("keys/reload", Query::default()).await + pub async fn reload_keys(&self, headers: Option) -> Response { + self.get("keys/reload", Query::default(), headers).await } - pub async fn whitelist_a_torrent(&self, info_hash: &str) -> Response { - self.post_empty(&format!("whitelist/{}", &info_hash)).await + pub async fn whitelist_a_torrent(&self, info_hash: &str, headers: Option) -> Response { + self.post_empty(&format!("whitelist/{}", &info_hash), headers).await } - pub async fn remove_torrent_from_whitelist(&self, info_hash: &str) -> Response { - self.delete(&format!("whitelist/{}", &info_hash)).await + pub async fn remove_torrent_from_whitelist(&self, info_hash: &str, headers: Option) -> Response { + self.delete(&format!("whitelist/{}", &info_hash), headers).await } - pub async fn reload_whitelist(&self) -> Response { - self.get("whitelist/reload", Query::default()).await + pub async fn reload_whitelist(&self, headers: Option) -> Response { + self.get("whitelist/reload", Query::default(), headers).await } - pub async fn get_torrent(&self, info_hash: &str) -> Response { - self.get(&format!("torrent/{}", &info_hash), Query::default()).await + pub async fn get_torrent(&self, info_hash: &str, headers: Option) -> Response { + self.get(&format!("torrent/{}", &info_hash), Query::default(), headers).await } - pub async fn get_torrents(&self, params: Query) -> Response { - self.get("torrents", params).await + pub async fn get_torrents(&self, params: Query, headers: Option) -> Response { + self.get("torrents", params, headers).await } - pub async fn get_tracker_statistics(&self) -> Response { - self.get("stats", Query::default()).await + pub async fn get_tracker_statistics(&self, headers: Option) -> Response { + self.get("stats", Query::default(), headers).await } - pub async fn get(&self, path: &str, params: Query) -> Response { + pub async fn get(&self, path: &str, params: Query, headers: Option) -> Response { let mut query: Query = params; if let Some(token) = &self.connection_info.api_token { query.add_param(QueryParam::new("token", token)); }; - self.get_request_with_query(path, query, None).await + self.get_request_with_query(path, query, headers).await } - pub async fn post_empty(&self, path: &str) -> Response { - reqwest::Client::new() + pub async fn post_empty(&self, path: &str, headers: Option) -> Response { + let builder = reqwest::Client::new() .post(self.base_url(path).clone()) - .query(&ReqwestQuery::from(self.query_with_token())) - .send() - .await - .unwrap() + .query(&ReqwestQuery::from(self.query_with_token())); + + let builder = match headers { + Some(headers) => builder.headers(headers), + None => builder, + }; + + builder.send().await.unwrap() } - pub async fn post_form(&self, path: &str, form: &T) -> Response { - reqwest::Client::new() + pub async fn post_form(&self, path: &str, form: &T, headers: Option) -> Response { + let builder = reqwest::Client::new() .post(self.base_url(path).clone()) .query(&ReqwestQuery::from(self.query_with_token())) - .json(&form) - .send() - .await - .unwrap() + .json(&form); + + let builder = match headers { + Some(headers) => builder.headers(headers), + None => builder, + }; + + builder.send().await.unwrap() } - async fn delete(&self, path: &str) -> Response { - reqwest::Client::new() + async fn delete(&self, path: &str, headers: Option) -> Response { + let builder = reqwest::Client::new() .delete(self.base_url(path).clone()) - .query(&ReqwestQuery::from(self.query_with_token())) - .send() - .await - .unwrap() + .query(&ReqwestQuery::from(self.query_with_token())); + + let builder = match headers { + Some(headers) => builder.headers(headers), + None => builder, + }; + + builder.send().await.unwrap() } pub async fn get_request_with_query(&self, path: &str, params: Query, headers: Option) -> Response { diff --git a/tests/servers/api/v1/contract/authentication.rs b/tests/servers/api/v1/contract/authentication.rs index dc50048fb..4e0cf49da 100644 --- a/tests/servers/api/v1/contract/authentication.rs +++ b/tests/servers/api/v1/contract/authentication.rs @@ -30,12 +30,19 @@ async fn should_not_authenticate_requests_when_the_token_is_missing() { let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .get_request_with_query("stats", Query::default(), None) + .get_request_with_query("stats", Query::default(), Some(headers_with_request_id(request_id))) .await; assert_unauthorized(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } @@ -57,12 +64,12 @@ async fn should_not_authenticate_requests_when_the_token_is_empty() { assert_token_not_valid(response).await; - env.stop().await; - assert!( logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), "Expected logs to contain: ERROR ... API ... request_id={request_id}" ); + + env.stop().await; } #[tokio::test] @@ -71,16 +78,23 @@ async fn should_not_authenticate_requests_when_the_token_is_invalid() { let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) .get_request_with_query( "stats", Query::params([QueryParam::new("token", "INVALID TOKEN")].to_vec()), - None, + Some(headers_with_request_id(request_id)), ) .await; assert_token_not_valid(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 9560a2f49..8ef72230e 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -3,15 +3,16 @@ use std::time::Duration; use serde::Serialize; use torrust_tracker::core::auth::Key; use torrust_tracker_test_helpers::configuration; +use uuid::Uuid; -use crate::common::logging::{self}; +use crate::common::logging::{self, logs_contains_a_line_with}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_auth_key_utf8, assert_failed_to_delete_key, assert_failed_to_generate_key, assert_failed_to_reload_keys, assert_invalid_auth_key_get_param, assert_invalid_auth_key_post_param, assert_ok, assert_token_not_valid, assert_unauthorized, assert_unprocessable_auth_key_duration_param, }; -use crate::servers::api::v1::client::{AddKeyForm, Client}; +use crate::servers::api::v1::client::{headers_with_request_id, AddKeyForm, Client}; use crate::servers::api::{force_database_error, Started}; #[tokio::test] @@ -20,11 +21,16 @@ async fn should_allow_generating_a_new_random_auth_key() { let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .add_auth_key(AddKeyForm { - opt_key: None, - seconds_valid: Some(60), - }) + .add_auth_key( + AddKeyForm { + opt_key: None, + seconds_valid: Some(60), + }, + Some(headers_with_request_id(request_id)), + ) .await; let auth_key_resource = assert_auth_key_utf8(response).await; @@ -44,11 +50,16 @@ async fn should_allow_uploading_a_preexisting_auth_key() { let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .add_auth_key(AddKeyForm { - opt_key: Some("Xc1L4PbQJSFGlrgSRZl8wxSFAuMa21z5".to_string()), - seconds_valid: Some(60), - }) + .add_auth_key( + AddKeyForm { + opt_key: Some("Xc1L4PbQJSFGlrgSRZl8wxSFAuMa21z5".to_string()), + seconds_valid: Some(60), + }, + Some(headers_with_request_id(request_id)), + ) .await; let auth_key_resource = assert_auth_key_utf8(response).await; @@ -68,24 +79,44 @@ async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) - .add_auth_key(AddKeyForm { - opt_key: None, - seconds_valid: Some(60), - }) + .add_auth_key( + AddKeyForm { + opt_key: None, + seconds_valid: Some(60), + }, + Some(headers_with_request_id(request_id)), + ) .await; assert_token_not_valid(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) - .add_auth_key(AddKeyForm { - opt_key: None, - seconds_valid: Some(60), - }) + .add_auth_key( + AddKeyForm { + opt_key: None, + seconds_valid: Some(60), + }, + Some(headers_with_request_id(request_id)), + ) .await; assert_unauthorized(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } @@ -97,15 +128,25 @@ async fn should_fail_when_the_auth_key_cannot_be_generated() { force_database_error(&env.tracker); + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .add_auth_key(AddKeyForm { - opt_key: None, - seconds_valid: Some(60), - }) + .add_auth_key( + AddKeyForm { + opt_key: None, + seconds_valid: Some(60), + }, + Some(headers_with_request_id(request_id)), + ) .await; assert_failed_to_generate_key(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } @@ -122,8 +163,10 @@ async fn should_allow_deleting_an_auth_key() { .await .unwrap(); + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .delete_auth_key(&auth_key.key.to_string()) + .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) .await; assert_ok(response).await; @@ -154,6 +197,8 @@ async fn should_fail_generating_a_new_auth_key_when_the_provided_key_is_invalid( ]; for invalid_key in invalid_keys { + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) .post_form( "keys", @@ -161,6 +206,7 @@ async fn should_fail_generating_a_new_auth_key_when_the_provided_key_is_invalid( opt_key: Some(invalid_key.to_string()), seconds_valid: 60, }, + Some(headers_with_request_id(request_id)), ) .await; @@ -190,6 +236,8 @@ async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid( ]; for invalid_key_duration in invalid_key_durations { + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) .post_form( "keys", @@ -197,6 +245,7 @@ async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid( opt_key: None, seconds_valid: invalid_key_duration.to_string(), }, + Some(headers_with_request_id(request_id)), ) .await; @@ -223,7 +272,11 @@ async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { ]; for invalid_auth_key in &invalid_auth_keys { - let response = Client::new(env.get_connection_info()).delete_auth_key(invalid_auth_key).await; + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .delete_auth_key(invalid_auth_key, Some(headers_with_request_id(request_id))) + .await; assert_invalid_auth_key_get_param(response, invalid_auth_key).await; } @@ -246,12 +299,19 @@ async fn should_fail_when_the_auth_key_cannot_be_deleted() { force_database_error(&env.tracker); + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .delete_auth_key(&auth_key.key.to_string()) + .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) .await; assert_failed_to_delete_key(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } @@ -270,12 +330,19 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { .await .unwrap(); + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) - .delete_auth_key(&auth_key.key.to_string()) + .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) .await; assert_token_not_valid(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + // Generate new auth key let auth_key = env .tracker @@ -283,12 +350,19 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { .await .unwrap(); + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) - .delete_auth_key(&auth_key.key.to_string()) + .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) .await; assert_unauthorized(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } @@ -304,7 +378,11 @@ async fn should_allow_reloading_keys() { .await .unwrap(); - let response = Client::new(env.get_connection_info()).reload_keys().await; + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .reload_keys(Some(headers_with_request_id(request_id))) + .await; assert_ok(response).await; @@ -317,7 +395,9 @@ async fn should_fail_when_keys_cannot_be_reloaded() { let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); let seconds_valid = 60; + env.tracker .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await @@ -325,10 +405,17 @@ async fn should_fail_when_keys_cannot_be_reloaded() { force_database_error(&env.tracker); - let response = Client::new(env.get_connection_info()).reload_keys().await; + let response = Client::new(env.get_connection_info()) + .reload_keys(Some(headers_with_request_id(request_id))) + .await; assert_failed_to_reload_keys(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } @@ -344,18 +431,32 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { .await .unwrap(); + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) - .reload_keys() + .reload_keys(Some(headers_with_request_id(request_id))) .await; assert_token_not_valid(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) - .reload_keys() + .reload_keys(Some(headers_with_request_id(request_id))) .await; assert_unauthorized(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } @@ -363,14 +464,15 @@ mod deprecated_generate_key_endpoint { use torrust_tracker::core::auth::Key; use torrust_tracker_test_helpers::configuration; + use uuid::Uuid; - use crate::common::logging::{self}; + use crate::common::logging::{self, logs_contains_a_line_with}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_auth_key_utf8, assert_failed_to_generate_key, assert_invalid_key_duration_param, assert_token_not_valid, assert_unauthorized, }; - use crate::servers::api::v1::client::Client; + use crate::servers::api::v1::client::{headers_with_request_id, Client}; use crate::servers::api::{force_database_error, Started}; #[tokio::test] @@ -381,7 +483,9 @@ mod deprecated_generate_key_endpoint { let seconds_valid = 60; - let response = Client::new(env.get_connection_info()).generate_auth_key(seconds_valid).await; + let response = Client::new(env.get_connection_info()) + .generate_auth_key(seconds_valid, None) + .await; let auth_key_resource = assert_auth_key_utf8(response).await; @@ -400,21 +504,27 @@ mod deprecated_generate_key_endpoint { let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); let seconds_valid = 60; let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) - .generate_auth_key(seconds_valid) + .generate_auth_key(seconds_valid, Some(headers_with_request_id(request_id))) .await; assert_token_not_valid(response).await; let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) - .generate_auth_key(seconds_valid) + .generate_auth_key(seconds_valid, None) .await; assert_unauthorized(response).await; env.stop().await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); } #[tokio::test] @@ -431,7 +541,7 @@ mod deprecated_generate_key_endpoint { for invalid_key_duration in invalid_key_durations { let response = Client::new(env.get_connection_info()) - .post_empty(&format!("key/{invalid_key_duration}")) + .post_empty(&format!("key/{invalid_key_duration}"), None) .await; assert_invalid_key_duration_param(response, invalid_key_duration).await; @@ -448,11 +558,19 @@ mod deprecated_generate_key_endpoint { force_database_error(&env.tracker); + let request_id = Uuid::new_v4(); let seconds_valid = 60; - let response = Client::new(env.get_connection_info()).generate_auth_key(seconds_valid).await; + let response = Client::new(env.get_connection_info()) + .generate_auth_key(seconds_valid, Some(headers_with_request_id(request_id))) + .await; assert_failed_to_generate_key(response).await; env.stop().await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); } } diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index e05107d25..d49d03535 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -4,11 +4,12 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker::servers::apis::v1::context::stats::resources::Stats; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; +use uuid::Uuid; -use crate::common::logging::{self}; +use crate::common::logging::{self, logs_contains_a_line_with}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{assert_stats, assert_token_not_valid, assert_unauthorized}; -use crate::servers::api::v1::client::Client; +use crate::servers::api::v1::client::{headers_with_request_id, Client}; use crate::servers::api::Started; #[tokio::test] @@ -22,7 +23,11 @@ async fn should_allow_getting_tracker_statistics() { &PeerBuilder::default().into(), ); - let response = Client::new(env.get_connection_info()).get_tracker_statistics().await; + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .get_tracker_statistics(Some(headers_with_request_id(request_id))) + .await; assert_stats( response, @@ -65,17 +70,31 @@ async fn should_not_allow_getting_tracker_statistics_for_unauthenticated_users() let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) - .get_tracker_statistics() + .get_tracker_statistics(Some(headers_with_request_id(request_id))) .await; assert_token_not_valid(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) - .get_tracker_statistics() + .get_tracker_statistics(Some(headers_with_request_id(request_id))) .await; assert_unauthorized(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index 55c25d228..b741a1a65 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -5,15 +5,16 @@ use torrust_tracker::servers::apis::v1::context::torrent::resources::peer::Peer; use torrust_tracker::servers::apis::v1::context::torrent::resources::torrent::{self, Torrent}; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; +use uuid::Uuid; use crate::common::http::{Query, QueryParam}; -use crate::common::logging::{self}; +use crate::common::logging::{self, logs_contains_a_line_with}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_bad_request, assert_invalid_infohash_param, assert_not_found, assert_token_not_valid, assert_torrent_info, assert_torrent_list, assert_torrent_not_known, assert_unauthorized, }; -use crate::servers::api::v1::client::Client; +use crate::servers::api::v1::client::{headers_with_request_id, Client}; use crate::servers::api::v1::contract::fixtures::{ invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found, }; @@ -29,7 +30,11 @@ async fn should_allow_getting_all_torrents() { env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()); - let response = Client::new(env.get_connection_info()).get_torrents(Query::empty()).await; + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .get_torrents(Query::empty(), Some(headers_with_request_id(request_id))) + .await; assert_torrent_list( response, @@ -58,8 +63,13 @@ async fn should_allow_limiting_the_torrents_in_the_result() { env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()); env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()); + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .get_torrents(Query::params([QueryParam::new("limit", "1")].to_vec())) + .get_torrents( + Query::params([QueryParam::new("limit", "1")].to_vec()), + Some(headers_with_request_id(request_id)), + ) .await; assert_torrent_list( @@ -89,8 +99,13 @@ async fn should_allow_the_torrents_result_pagination() { env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()); env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()); + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .get_torrents(Query::params([QueryParam::new("offset", "1")].to_vec())) + .get_torrents( + Query::params([QueryParam::new("offset", "1")].to_vec()), + Some(headers_with_request_id(request_id)), + ) .await; assert_torrent_list( @@ -119,14 +134,19 @@ async fn should_allow_getting_a_list_of_torrents_providing_infohashes() { env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()); env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()); + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .get_torrents(Query::params( - [ - QueryParam::new("info_hash", "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d"), // DevSkim: ignore DS173237 - QueryParam::new("info_hash", "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d"), // DevSkim: ignore DS173237 - ] - .to_vec(), - )) + .get_torrents( + Query::params( + [ + QueryParam::new("info_hash", "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d"), // DevSkim: ignore DS173237 + QueryParam::new("info_hash", "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d"), // DevSkim: ignore DS173237 + ] + .to_vec(), + ), + Some(headers_with_request_id(request_id)), + ) .await; assert_torrent_list( @@ -160,8 +180,13 @@ async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_ let invalid_offsets = [" ", "-1", "1.1", "INVALID OFFSET"]; for invalid_offset in &invalid_offsets { + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .get_torrents(Query::params([QueryParam::new("offset", invalid_offset)].to_vec())) + .get_torrents( + Query::params([QueryParam::new("offset", invalid_offset)].to_vec()), + Some(headers_with_request_id(request_id)), + ) .await; assert_bad_request(response, "Failed to deserialize query string: invalid digit found in string").await; @@ -179,8 +204,13 @@ async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_p let invalid_limits = [" ", "-1", "1.1", "INVALID LIMIT"]; for invalid_limit in &invalid_limits { + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .get_torrents(Query::params([QueryParam::new("limit", invalid_limit)].to_vec())) + .get_torrents( + Query::params([QueryParam::new("limit", invalid_limit)].to_vec()), + Some(headers_with_request_id(request_id)), + ) .await; assert_bad_request(response, "Failed to deserialize query string: invalid digit found in string").await; @@ -198,8 +228,13 @@ async fn should_fail_getting_torrents_when_the_info_hash_parameter_is_invalid() let invalid_info_hashes = [" ", "-1", "1.1", "INVALID INFO_HASH"]; for invalid_info_hash in &invalid_info_hashes { + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .get_torrents(Query::params([QueryParam::new("info_hash", invalid_info_hash)].to_vec())) + .get_torrents( + Query::params([QueryParam::new("info_hash", invalid_info_hash)].to_vec()), + Some(headers_with_request_id(request_id)), + ) .await; assert_bad_request( @@ -218,18 +253,32 @@ async fn should_not_allow_getting_torrents_for_unauthenticated_users() { let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) - .get_torrents(Query::empty()) + .get_torrents(Query::empty(), Some(headers_with_request_id(request_id))) .await; assert_token_not_valid(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) - .get_torrents(Query::default()) + .get_torrents(Query::default(), Some(headers_with_request_id(request_id))) .await; assert_unauthorized(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } @@ -245,8 +294,10 @@ async fn should_allow_getting_a_torrent_info() { env.add_torrent_peer(&info_hash, &peer); + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .get_torrent(&info_hash.to_string()) + .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) .await; assert_torrent_info( @@ -270,10 +321,11 @@ async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exis let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); let response = Client::new(env.get_connection_info()) - .get_torrent(&info_hash.to_string()) + .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) .await; assert_torrent_not_known(response).await; @@ -288,13 +340,21 @@ async fn should_fail_getting_a_torrent_info_when_the_provided_infohash_is_invali let env = Started::new(&configuration::ephemeral().into()).await; for invalid_infohash in &invalid_infohashes_returning_bad_request() { - let response = Client::new(env.get_connection_info()).get_torrent(invalid_infohash).await; + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .get_torrent(invalid_infohash, Some(headers_with_request_id(request_id))) + .await; assert_invalid_infohash_param(response, invalid_infohash).await; } for invalid_infohash in &invalid_infohashes_returning_not_found() { - let response = Client::new(env.get_connection_info()).get_torrent(invalid_infohash).await; + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .get_torrent(invalid_infohash, Some(headers_with_request_id(request_id))) + .await; assert_not_found(response).await; } @@ -312,17 +372,31 @@ async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()); + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) - .get_torrent(&info_hash.to_string()) + .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) .await; assert_token_not_valid(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) - .get_torrent(&info_hash.to_string()) + .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) .await; assert_unauthorized(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index 2be1706fc..d0a80e968 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -2,14 +2,15 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; +use uuid::Uuid; -use crate::common::logging::{self}; +use crate::common::logging::{self, logs_contains_a_line_with}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_failed_to_reload_whitelist, assert_failed_to_remove_torrent_from_whitelist, assert_failed_to_whitelist_torrent, assert_invalid_infohash_param, assert_not_found, assert_ok, assert_token_not_valid, assert_unauthorized, }; -use crate::servers::api::v1::client::Client; +use crate::servers::api::v1::client::{headers_with_request_id, Client}; use crate::servers::api::v1::contract::fixtures::{ invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found, }; @@ -21,9 +22,12 @@ async fn should_allow_whitelisting_a_torrent() { let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - let response = Client::new(env.get_connection_info()).whitelist_a_torrent(&info_hash).await; + let response = Client::new(env.get_connection_info()) + .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) + .await; assert_ok(response).await; assert!( @@ -45,10 +49,18 @@ async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() let api_client = Client::new(env.get_connection_info()); - let response = api_client.whitelist_a_torrent(&info_hash).await; + let request_id = Uuid::new_v4(); + + let response = api_client + .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) + .await; assert_ok(response).await; - let response = api_client.whitelist_a_torrent(&info_hash).await; + let request_id = Uuid::new_v4(); + + let response = api_client + .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) + .await; assert_ok(response).await; env.stop().await; @@ -62,18 +74,32 @@ async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) - .whitelist_a_torrent(&info_hash) + .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) .await; assert_token_not_valid(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) - .whitelist_a_torrent(&info_hash) + .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) .await; assert_unauthorized(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } @@ -87,10 +113,19 @@ async fn should_fail_when_the_torrent_cannot_be_whitelisted() { force_database_error(&env.tracker); - let response = Client::new(env.get_connection_info()).whitelist_a_torrent(&info_hash).await; + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) + .await; assert_failed_to_whitelist_torrent(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } @@ -100,17 +135,21 @@ async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invali let env = Started::new(&configuration::ephemeral().into()).await; + let request_id = Uuid::new_v4(); + for invalid_infohash in &invalid_infohashes_returning_bad_request() { let response = Client::new(env.get_connection_info()) - .whitelist_a_torrent(invalid_infohash) + .whitelist_a_torrent(invalid_infohash, Some(headers_with_request_id(request_id))) .await; assert_invalid_infohash_param(response, invalid_infohash).await; } + let request_id = Uuid::new_v4(); + for invalid_infohash in &invalid_infohashes_returning_not_found() { let response = Client::new(env.get_connection_info()) - .whitelist_a_torrent(invalid_infohash) + .whitelist_a_torrent(invalid_infohash, Some(headers_with_request_id(request_id))) .await; assert_not_found(response).await; @@ -127,10 +166,13 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); + env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .remove_torrent_from_whitelist(&hash) + .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) .await; assert_ok(response).await; @@ -147,8 +189,10 @@ async fn should_not_fail_trying_to_remove_a_non_whitelisted_torrent_from_the_whi let non_whitelisted_torrent_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .remove_torrent_from_whitelist(&non_whitelisted_torrent_hash) + .remove_torrent_from_whitelist(&non_whitelisted_torrent_hash, Some(headers_with_request_id(request_id))) .await; assert_ok(response).await; @@ -163,16 +207,20 @@ async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_inf let env = Started::new(&configuration::ephemeral().into()).await; for invalid_infohash in &invalid_infohashes_returning_bad_request() { + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .remove_torrent_from_whitelist(invalid_infohash) + .remove_torrent_from_whitelist(invalid_infohash, Some(headers_with_request_id(request_id))) .await; assert_invalid_infohash_param(response, invalid_infohash).await; } for invalid_infohash in &invalid_infohashes_returning_not_found() { + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .remove_torrent_from_whitelist(invalid_infohash) + .remove_torrent_from_whitelist(invalid_infohash, Some(headers_with_request_id(request_id))) .await; assert_not_found(response).await; @@ -193,12 +241,19 @@ async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { force_database_error(&env.tracker); + let request_id = Uuid::new_v4(); + let response = Client::new(env.get_connection_info()) - .remove_torrent_from_whitelist(&hash) + .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) .await; assert_failed_to_remove_torrent_from_whitelist(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } @@ -212,19 +267,35 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica let info_hash = InfoHash::from_str(&hash).unwrap(); env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) - .remove_torrent_from_whitelist(&hash) + .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) .await; assert_token_not_valid(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + + let request_id = Uuid::new_v4(); + let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) - .remove_torrent_from_whitelist(&hash) + .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) .await; assert_unauthorized(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } @@ -238,7 +309,11 @@ async fn should_allow_reload_the_whitelist_from_the_database() { let info_hash = InfoHash::from_str(&hash).unwrap(); env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); - let response = Client::new(env.get_connection_info()).reload_whitelist().await; + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .reload_whitelist(Some(headers_with_request_id(request_id))) + .await; assert_ok(response).await; /* todo: this assert fails because the whitelist has not been reloaded yet. @@ -267,9 +342,18 @@ async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { force_database_error(&env.tracker); - let response = Client::new(env.get_connection_info()).reload_whitelist().await; + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .reload_whitelist(Some(headers_with_request_id(request_id))) + .await; assert_failed_to_reload_whitelist(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + env.stop().await; } From 03243cbd132ebe3d1d195b14ad528e7f48fff7d3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 26 Dec 2024 12:12:22 +0000 Subject: [PATCH 0556/1297] tests: add assertions for HTTP tracker error logs It's using the info-hash to find the ERROR in logs. IT's generated a newly random info-hash for each tests. It could have been also used a `x-request-id` header in the HTTP request but this solution is simpler and the chances to have an info-hash collision is very low. --- tests/common/fixtures.rs | 10 ++++++++++ tests/servers/http/v1/contract.rs | 28 +++++++++++++++++++++++----- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/tests/common/fixtures.rs b/tests/common/fixtures.rs index bbdebff76..562ed1544 100644 --- a/tests/common/fixtures.rs +++ b/tests/common/fixtures.rs @@ -1,3 +1,5 @@ +use bittorrent_primitives::info_hash::InfoHash; + #[allow(dead_code)] pub fn invalid_info_hashes() -> Vec { [ @@ -10,3 +12,11 @@ pub fn invalid_info_hashes() -> Vec { ] .to_vec() } + +/// Returns a random info hash. +pub fn random_info_hash() -> InfoHash { + let mut rng = rand::thread_rng(); + let random_bytes: [u8; 20] = rand::Rng::gen(&mut rng); + + InfoHash::from_bytes(&random_bytes) +} diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 632f38bf4..83ebb9ae3 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -1217,8 +1217,10 @@ mod configured_as_whitelisted { use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; + use uuid::Uuid; - use crate::common::logging::{self}; + use crate::common::fixtures::random_info_hash; + use crate::common::logging::{self, logs_contains_a_line_with}; use crate::servers::http::asserts::{assert_is_announce_response, assert_torrent_not_in_whitelist_error_response}; use crate::servers::http::client::Client; use crate::servers::http::requests::announce::QueryBuilder; @@ -1230,14 +1232,24 @@ mod configured_as_whitelisted { let env = Started::new(&configuration::ephemeral_listed().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let request_id = Uuid::new_v4(); + let info_hash = random_info_hash(); let response = Client::new(*env.bind_address()) - .announce(&QueryBuilder::default().with_info_hash(&info_hash).query()) + .announce_with_header( + &QueryBuilder::default().with_info_hash(&info_hash).query(), + "x-request-id", + &request_id.to_string(), + ) .await; assert_torrent_not_in_whitelist_error_response(response).await; + assert!( + logs_contains_a_line_with(&["ERROR", &format!("{info_hash}"), "is not whitelisted"]), + "Expected logs to contain: ERROR ... {info_hash} is not whitelisted" + ); + env.stop().await; } @@ -1272,7 +1284,8 @@ mod configured_as_whitelisted { use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; - use crate::common::logging::{self}; + use crate::common::fixtures::random_info_hash; + use crate::common::logging::{self, logs_contains_a_line_with}; use crate::servers::http::asserts::assert_scrape_response; use crate::servers::http::client::Client; use crate::servers::http::responses::scrape::{File, ResponseBuilder}; @@ -1284,7 +1297,7 @@ mod configured_as_whitelisted { let env = Started::new(&configuration::ephemeral_listed().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = random_info_hash(); env.add_torrent_peer( &info_hash, @@ -1306,6 +1319,11 @@ mod configured_as_whitelisted { assert_scrape_response(response, &expected_scrape_response).await; + assert!( + logs_contains_a_line_with(&["ERROR", &format!("{info_hash}"), "is not whitelisted"]), + "Expected logs to contain: ERROR ... {info_hash} is not whitelisted" + ); + env.stop().await; } From 33e72bb04e14370e90ec1c421b3666488e72e19a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 26 Dec 2024 15:46:43 +0000 Subject: [PATCH 0557/1297] tests: add info-hash to announce req fixture --- tests/servers/udp/contract.rs | 36 +++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 86bb1d18c..ddccf4f9a 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -118,22 +118,30 @@ mod receiving_an_announce_request { use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; + use crate::common::fixtures::random_info_hash; use crate::common::logging; use crate::servers::udp::asserts::is_ipv4_announce_response; use crate::servers::udp::contract::send_connection_request; use crate::servers::udp::Started; - pub async fn assert_send_and_get_announce(tx_id: TransactionId, c_id: ConnectionId, client: &UdpTrackerClient) { - let response = send_and_get_announce(tx_id, c_id, client).await; + pub async fn assert_send_and_get_announce( + tx_id: TransactionId, + c_id: ConnectionId, + info_hash: bittorrent_primitives::info_hash::InfoHash, + client: &UdpTrackerClient, + ) { + let response = send_and_get_announce(tx_id, c_id, info_hash, client).await; assert!(is_ipv4_announce_response(&response)); } pub async fn send_and_get_announce( tx_id: TransactionId, c_id: ConnectionId, + info_hash: bittorrent_primitives::info_hash::InfoHash, client: &UdpTrackerClient, ) -> aquatic_udp_protocol::Response { - let announce_request = build_sample_announce_request(tx_id, c_id, client.client.socket.local_addr().unwrap().port()); + let announce_request = + build_sample_announce_request(tx_id, c_id, client.client.socket.local_addr().unwrap().port(), info_hash); match client.send(announce_request.into()).await { Ok(_) => (), @@ -146,12 +154,17 @@ mod receiving_an_announce_request { } } - fn build_sample_announce_request(tx_id: TransactionId, c_id: ConnectionId, port: u16) -> AnnounceRequest { + fn build_sample_announce_request( + tx_id: TransactionId, + c_id: ConnectionId, + port: u16, + info_hash: bittorrent_primitives::info_hash::InfoHash, + ) -> AnnounceRequest { AnnounceRequest { connection_id: ConnectionId(c_id.0), action_placeholder: AnnounceActionPlaceholder::default(), transaction_id: tx_id, - info_hash: InfoHash([0u8; 20]), + info_hash: InfoHash(info_hash.0), peer_id: PeerId([255u8; 20]), bytes_downloaded: NumberOfBytes(0i64.into()), bytes_uploaded: NumberOfBytes(0i64.into()), @@ -179,7 +192,9 @@ mod receiving_an_announce_request { let c_id = send_connection_request(tx_id, &client).await; - assert_send_and_get_announce(tx_id, c_id, &client).await; + let info_hash = random_info_hash(); + + assert_send_and_get_announce(tx_id, c_id, info_hash, &client).await; env.stop().await; } @@ -199,9 +214,11 @@ mod receiving_an_announce_request { let c_id = send_connection_request(tx_id, &client).await; + let info_hash = random_info_hash(); + for x in 0..1000 { tracing::info!("req no: {x}"); - assert_send_and_get_announce(tx_id, c_id, &client).await; + assert_send_and_get_announce(tx_id, c_id, info_hash, &client).await; } env.stop().await; @@ -224,9 +241,11 @@ mod receiving_an_announce_request { let invalid_connection_id = ConnectionId::new(0); // Zero is one of the not normal values. + let info_hash = random_info_hash(); + for x in 0..=10 { tracing::info!("req no: {x}"); - send_and_get_announce(tx_id, invalid_connection_id, &client).await; + send_and_get_announce(tx_id, invalid_connection_id, info_hash, &client).await; } // The twelfth request should be banned (timeout error) @@ -235,6 +254,7 @@ mod receiving_an_announce_request { tx_id, invalid_connection_id, client.client.socket.local_addr().unwrap().port(), + info_hash, ); match client.send(announce_request.into()).await { From 5f206f0ad806a93c0878b3a3218a4ef8bc80434a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 26 Dec 2024 16:14:02 +0000 Subject: [PATCH 0558/1297] feat: add more fields to UDP error response log ``` 2024-12-26T16:12:06.336340Z ERROR UDP TRACKER: response error error=cookie value is from future: 6831818432388564000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, expected < 1735229527.33634 remote_addr=127.0.0.1:35550 local_addr=127.0.0.1:36599 request_id=ce34c229-82c6-4a18-a60c-5eea1cf55919 transaction_id=123 ``` Added custom log with fields: - remote_addr - request_id - transaction_id --- src/servers/udp/connection_cookie.rs | 2 +- src/servers/udp/handlers.rs | 33 +++++++++++++++++++++++++--- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs index 50359033c..439be9da7 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/servers/udp/connection_cookie.rs @@ -121,7 +121,7 @@ use std::ops::Range; /// # Panics /// /// It would panic if the range start is not smaller than it's end. -#[instrument(err)] +#[instrument] pub fn check(cookie: &Cookie, fingerprint: u64, valid_range: Range) -> Result { assert!(valid_range.start <= valid_range.end, "range start is larger than range end"); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 1f838cd68..1a9c164e2 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -22,7 +22,7 @@ use super::server::banning::BanService; use super::RawRequest; use crate::core::{statistics, PeersWanted, Tracker}; use crate::servers::udp::error::Error; -use crate::servers::udp::peer_builder; +use crate::servers::udp::{peer_builder, UDP_TRACKER_LOG_TARGET}; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; use crate::CurrentClock; @@ -61,7 +61,9 @@ pub(crate) async fn handle_packet( cookie_time_values: CookieTimeValues, ban_service: Arc>, ) -> Response { - tracing::Span::current().record("request_id", Uuid::new_v4().to_string()); + let request_id = Uuid::new_v4(); + + tracing::Span::current().record("request_id", request_id.to_string()); tracing::debug!("Handling Packets: {udp_request:?}"); let start_time = Instant::now(); @@ -84,6 +86,8 @@ pub(crate) async fn handle_packet( handle_error( udp_request.from, + local_addr, + request_id, tracker, cookie_time_values.valid_range.clone(), &e, @@ -92,7 +96,18 @@ pub(crate) async fn handle_packet( .await } }, - Err(e) => handle_error(udp_request.from, tracker, cookie_time_values.valid_range.clone(), &e, None).await, + Err(e) => { + handle_error( + udp_request.from, + local_addr, + request_id, + tracker, + cookie_time_values.valid_range.clone(), + &e, + None, + ) + .await + } }; let latency = start_time.elapsed(); @@ -344,6 +359,8 @@ pub async fn handle_scrape( #[instrument(fields(transaction_id), skip(tracker), ret(level = Level::TRACE))] async fn handle_error( remote_addr: SocketAddr, + local_addr: SocketAddr, + request_id: Uuid, tracker: &Tracker, cookie_valid_range: Range, e: &Error, @@ -351,6 +368,16 @@ async fn handle_error( ) -> Response { tracing::trace!("handle error"); + match transaction_id { + Some(transaction_id) => { + let transaction_id = transaction_id.0.to_string(); + tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %e, %remote_addr, %local_addr, %request_id, %transaction_id, "response error"); + } + None => { + tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %e, %remote_addr, %local_addr, %request_id, "response error"); + } + } + let e = if let Error::RequestParseError { request_parse_error } = e { match request_parse_error { RequestParseError::Sendable { From 71e7ef7888768f2a47493b1b7be13a6f989d1f8a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 26 Dec 2024 16:34:53 +0000 Subject: [PATCH 0559/1297] test: [#1164] assert logged error when connection ID is wrong in UDP tracker. Only for the tests that is currently showing logging errors. --- tests/common/fixtures.rs | 7 +++++++ tests/servers/udp/contract.rs | 19 +++++++++++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/tests/common/fixtures.rs b/tests/common/fixtures.rs index 562ed1544..f96b03dd1 100644 --- a/tests/common/fixtures.rs +++ b/tests/common/fixtures.rs @@ -1,3 +1,4 @@ +use aquatic_udp_protocol::TransactionId; use bittorrent_primitives::info_hash::InfoHash; #[allow(dead_code)] @@ -20,3 +21,9 @@ pub fn random_info_hash() -> InfoHash { InfoHash::from_bytes(&random_bytes) } + +/// Returns a random transaction id. +pub fn random_transaction_id() -> TransactionId { + let random_value = rand::Rng::gen::(&mut rand::thread_rng()); + TransactionId::new(random_value) +} diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index ddccf4f9a..9618bef65 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -118,8 +118,8 @@ mod receiving_an_announce_request { use torrust_tracker_configuration::DEFAULT_TIMEOUT; use torrust_tracker_test_helpers::configuration; - use crate::common::fixtures::random_info_hash; - use crate::common::logging; + use crate::common::fixtures::{random_info_hash, random_transaction_id}; + use crate::common::logging::{self, logs_contains_a_line_with}; use crate::servers::udp::asserts::is_ipv4_announce_response; use crate::servers::udp::contract::send_connection_request; use crate::servers::udp::Started; @@ -235,8 +235,6 @@ mod receiving_an_announce_request { Err(err) => panic!("{err}"), }; - let tx_id = TransactionId::new(123); - // The eleven first requests should be fine let invalid_connection_id = ConnectionId::new(0); // Zero is one of the not normal values. @@ -245,11 +243,23 @@ mod receiving_an_announce_request { for x in 0..=10 { tracing::info!("req no: {x}"); + + let tx_id = random_transaction_id(); + send_and_get_announce(tx_id, invalid_connection_id, info_hash, &client).await; + + let transaction_id = tx_id.0.to_string(); + + assert!( + logs_contains_a_line_with(&["ERROR", "UDP TRACKER", &transaction_id.to_string()]), + "Expected logs to contain: ERROR ... UDP TRACKER ... transaction_id={transaction_id}" + ); } // The twelfth request should be banned (timeout error) + let tx_id = random_transaction_id(); + let announce_request = build_sample_announce_request( tx_id, invalid_connection_id, @@ -257,6 +267,7 @@ mod receiving_an_announce_request { info_hash, ); + // This should return a timeout error match client.send(announce_request.into()).await { Ok(_) => (), Err(err) => panic!("{err}"), From bfaf08b394e16fee64ad5165eb0f1e376b1c189e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 27 Dec 2024 09:07:04 +0000 Subject: [PATCH 0560/1297] refactor: [#1137] rename lib to torrust_tracker_lib to avoid collisions in docs: ``` cargo doc --no-deps --bins --examples --workspace --all-features ``` becuase the main binary and lib have the same name. --- Cargo.toml | 3 +++ src/bin/e2e_tests_runner.rs | 2 +- src/bin/profiling.rs | 2 +- src/core/auth.rs | 6 +++--- src/core/databases/driver.rs | 8 ++++---- src/main.rs | 2 +- src/servers/http/v1/query.rs | 8 ++++---- src/servers/http/v1/requests/announce.rs | 2 +- src/servers/http/v1/responses/announce.rs | 4 ++-- src/servers/http/v1/responses/error.rs | 2 +- src/servers/http/v1/responses/scrape.rs | 4 ++-- src/servers/http/v1/services/peer_ip_resolver.rs | 4 ++-- tests/common/logging.rs | 2 +- tests/servers/api/environment.rs | 10 +++++----- tests/servers/api/mod.rs | 4 ++-- tests/servers/api/v1/asserts.rs | 6 +++--- tests/servers/api/v1/contract/context/auth_key.rs | 4 ++-- .../servers/api/v1/contract/context/health_check.rs | 2 +- tests/servers/api/v1/contract/context/stats.rs | 2 +- tests/servers/api/v1/contract/context/torrent.rs | 4 ++-- tests/servers/health_check_api/contract.rs | 10 +++++----- tests/servers/health_check_api/environment.rs | 8 ++++---- tests/servers/http/client.rs | 2 +- tests/servers/http/connection_info.rs | 2 +- tests/servers/http/environment.rs | 10 +++++----- tests/servers/http/mod.rs | 2 +- tests/servers/http/v1/contract.rs | 6 +++--- tests/servers/udp/contract.rs | 2 +- tests/servers/udp/environment.rs | 12 ++++++------ tests/servers/udp/mod.rs | 2 +- 30 files changed, 70 insertions(+), 67 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6832f17f2..f1ae96dad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,9 @@ repository.workspace = true rust-version.workspace = true version.workspace = true +[lib] +name = "torrust_tracker_lib" + [workspace.package] authors = ["Nautilus Cyberneering , Mick van Dijke "] categories = ["network-programming", "web-programming"] diff --git a/src/bin/e2e_tests_runner.rs b/src/bin/e2e_tests_runner.rs index eb91c0d86..5787799dc 100644 --- a/src/bin/e2e_tests_runner.rs +++ b/src/bin/e2e_tests_runner.rs @@ -1,5 +1,5 @@ //! Program to run E2E tests. -use torrust_tracker::console::ci::e2e; +use torrust_tracker_lib::console::ci::e2e; fn main() -> anyhow::Result<()> { e2e::runner::run() diff --git a/src/bin/profiling.rs b/src/bin/profiling.rs index bc1ac6526..aca6ab98d 100644 --- a/src/bin/profiling.rs +++ b/src/bin/profiling.rs @@ -1,6 +1,6 @@ //! This binary is used for profiling with [valgrind](https://valgrind.org/) //! and [kcachegrind](https://kcachegrind.github.io/). -use torrust_tracker::console::profiling::run; +use torrust_tracker_lib::console::profiling::run; #[tokio::main] async fn main() { diff --git a/src/core/auth.rs b/src/core/auth.rs index 7bbb25eca..c92a4723d 100644 --- a/src/core/auth.rs +++ b/src/core/auth.rs @@ -12,7 +12,7 @@ //! Keys are stored in this struct: //! //! ```rust,no_run -//! use torrust_tracker::core::auth::Key; +//! use torrust_tracker_lib::core::auth::Key; //! use torrust_tracker_primitives::DurationSinceUnixEpoch; //! //! pub struct ExpiringKey { @@ -26,7 +26,7 @@ //! You can generate a new key valid for `9999` seconds and `0` nanoseconds from the current time with the following: //! //! ```rust,no_run -//! use torrust_tracker::core::auth; +//! use torrust_tracker_lib::core::auth; //! use std::time::Duration; //! //! let expiring_key = auth::generate_key(Some(Duration::new(9999, 0))); @@ -197,7 +197,7 @@ impl Key { /// Error returned when a key cannot be parsed from a string. /// /// ```text -/// use torrust_tracker::core::auth::Key; +/// use torrust_tracker_lib::core::auth::Key; /// use std::str::FromStr; /// /// let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; diff --git a/src/core/databases/driver.rs b/src/core/databases/driver.rs index 3cbab9473..b5cb797aa 100644 --- a/src/core/databases/driver.rs +++ b/src/core/databases/driver.rs @@ -30,8 +30,8 @@ pub enum Driver { /// Example for `SQLite3`: /// /// ```text -/// use torrust_tracker::core::databases; -/// use torrust_tracker::core::databases::driver::Driver; +/// use torrust_tracker_lib::core::databases; +/// use torrust_tracker_lib::core::databases::driver::Driver; /// /// let db_driver = Driver::Sqlite3; /// let db_path = "./storage/tracker/lib/database/sqlite3.db".to_string(); @@ -41,8 +41,8 @@ pub enum Driver { /// Example for `MySQL`: /// /// ```text -/// use torrust_tracker::core::databases; -/// use torrust_tracker::core::databases::driver::Driver; +/// use torrust_tracker_lib::core::databases; +/// use torrust_tracker_lib::core::databases::driver::Driver; /// /// let db_driver = Driver::MySQL; /// let db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker".to_string(); diff --git a/src/main.rs b/src/main.rs index e0b7bc4ab..0e2bcfbc9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,4 @@ -use torrust_tracker::{app, bootstrap}; +use torrust_tracker_lib::{app, bootstrap}; #[tokio::main] async fn main() { diff --git a/src/servers/http/v1/query.rs b/src/servers/http/v1/query.rs index abaf89845..e65f62ada 100644 --- a/src/servers/http/v1/query.rs +++ b/src/servers/http/v1/query.rs @@ -31,7 +31,7 @@ impl Query { /// input `name` exists. For example: /// /// ```text - /// use torrust_tracker::servers::http::v1::query::Query; + /// use torrust_tracker_lib::servers::http::v1::query::Query; /// /// let raw_query = "param1=value1¶m2=value2"; /// @@ -44,7 +44,7 @@ impl Query { /// It returns only the first param value even if it has multiple values: /// /// ```text - /// use torrust_tracker::servers::http::v1::query::Query; + /// use torrust_tracker_lib::servers::http::v1::query::Query; /// /// let raw_query = "param1=value1¶m1=value2"; /// @@ -60,7 +60,7 @@ impl Query { /// Returns all the param values as a vector. /// /// ```text - /// use torrust_tracker::servers::http::v1::query::Query; + /// use torrust_tracker_lib::servers::http::v1::query::Query; /// /// let query = "param1=value1¶m1=value2".parse::().unwrap(); /// @@ -73,7 +73,7 @@ impl Query { /// Returns all the param values as a vector even if it has only one value. /// /// ```text - /// use torrust_tracker::servers::http::v1::query::Query; + /// use torrust_tracker_lib::servers::http::v1::query::Query; /// /// let query = "param1=value1".parse::().unwrap(); /// diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index 954d62c82..e8a730e9c 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -31,7 +31,7 @@ const NUMWANT: &str = "numwant"; /// /// ```text /// use aquatic_udp_protocol::{NumberOfBytes, PeerId}; -/// use torrust_tracker::servers::http::v1::requests::announce::{Announce, Compact, Event}; +/// use torrust_tracker_lib::servers::http::v1::requests::announce::{Announce, Compact, Event}; /// use bittorrent_primitives::info_hash::InfoHash; /// /// let request = Announce { diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index bc63aa7fd..925c0893e 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -154,7 +154,7 @@ impl Into> for Compact { /// /// ```text /// use std::net::{IpAddr, Ipv4Addr}; -/// use torrust_tracker::servers::http::v1::responses::announce::{Normal, NormalPeer}; +/// use torrust_tracker_lib::servers::http::v1::responses::announce::{Normal, NormalPeer}; /// /// let peer = NormalPeer { /// peer_id: *b"-qB00000000000000001", @@ -206,7 +206,7 @@ impl From<&NormalPeer> for BencodeMut<'_> { /// /// ```text /// use std::net::{IpAddr, Ipv4Addr}; -/// use torrust_tracker::servers::http::v1::responses::announce::{Compact, CompactPeer, CompactPeerData}; +/// use torrust_tracker_lib::servers::http::v1::responses::announce::{Compact, CompactPeer, CompactPeerData}; /// /// let peer = CompactPeer::V4(CompactPeerData { /// ip: Ipv4Addr::new(0x69, 0x69, 0x69, 0x69), // 105.105.105.105 diff --git a/src/servers/http/v1/responses/error.rs b/src/servers/http/v1/responses/error.rs index 8572d861d..7223063fd 100644 --- a/src/servers/http/v1/responses/error.rs +++ b/src/servers/http/v1/responses/error.rs @@ -27,7 +27,7 @@ impl Error { /// Returns the bencoded representation of the `Error` struct. /// /// ```text - /// use torrust_tracker::servers::http::v1::responses::error::Error; + /// use torrust_tracker_lib::servers::http::v1::responses::error::Error; /// /// let err = Error { /// failure_reason: "error message".to_owned(), diff --git a/src/servers/http/v1/responses/scrape.rs b/src/servers/http/v1/responses/scrape.rs index 878311ce7..1f367a9c9 100644 --- a/src/servers/http/v1/responses/scrape.rs +++ b/src/servers/http/v1/responses/scrape.rs @@ -12,10 +12,10 @@ use crate::core::ScrapeData; /// The `Scrape` response for the HTTP tracker. /// /// ```text -/// use torrust_tracker::servers::http::v1::responses::scrape::Bencoded; +/// use torrust_tracker_lib::servers::http::v1::responses::scrape::Bencoded; /// use bittorrent_primitives::info_hash::InfoHash; /// use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -/// use torrust_tracker::core::ScrapeData; +/// use torrust_tracker_lib::core::ScrapeData; /// /// let info_hash = InfoHash::from_bytes(&[0x69; 20]); /// let mut scrape_data = ScrapeData::empty(); diff --git a/src/servers/http/v1/services/peer_ip_resolver.rs b/src/servers/http/v1/services/peer_ip_resolver.rs index 548a99756..56bd3d86f 100644 --- a/src/servers/http/v1/services/peer_ip_resolver.rs +++ b/src/servers/http/v1/services/peer_ip_resolver.rs @@ -63,7 +63,7 @@ pub enum PeerIpResolutionError { /// use std::net::IpAddr; /// use std::str::FromStr; /// -/// use torrust_tracker::servers::http::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; +/// use torrust_tracker_lib::servers::http::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; /// /// let on_reverse_proxy = true; /// @@ -85,7 +85,7 @@ pub enum PeerIpResolutionError { /// use std::net::IpAddr; /// use std::str::FromStr; /// -/// use torrust_tracker::servers::http::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; +/// use torrust_tracker_lib::servers::http::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; /// /// let on_reverse_proxy = false; /// diff --git a/tests/common/logging.rs b/tests/common/logging.rs index d2abc37b4..f04dcdc7d 100644 --- a/tests/common/logging.rs +++ b/tests/common/logging.rs @@ -3,7 +3,7 @@ use std::collections::VecDeque; use std::io; use std::sync::{Mutex, MutexGuard, Once, OnceLock}; -use torrust_tracker::bootstrap::logging::TraceStyle; +use torrust_tracker_lib::bootstrap::logging::TraceStyle; use tracing::level_filters::LevelFilter; use tracing_subscriber::fmt::MakeWriter; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index bffe42603..f754e329f 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -3,12 +3,12 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; -use torrust_tracker::bootstrap::app::initialize_with_configuration; -use torrust_tracker::bootstrap::jobs::make_rust_tls; -use torrust_tracker::core::Tracker; -use torrust_tracker::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; -use torrust_tracker::servers::registar::Registar; use torrust_tracker_configuration::{Configuration, HttpApi}; +use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; +use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; +use torrust_tracker_lib::core::Tracker; +use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; +use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; use super::connection_info::ConnectionInfo; diff --git a/tests/servers/api/mod.rs b/tests/servers/api/mod.rs index 38df46e9b..278fd869d 100644 --- a/tests/servers/api/mod.rs +++ b/tests/servers/api/mod.rs @@ -1,7 +1,7 @@ use std::sync::Arc; -use torrust_tracker::core::Tracker; -use torrust_tracker::servers::apis::server; +use torrust_tracker_lib::core::Tracker; +use torrust_tracker_lib::servers::apis::server; pub mod connection_info; pub mod environment; diff --git a/tests/servers/api/v1/asserts.rs b/tests/servers/api/v1/asserts.rs index aeecfa170..f3d04d524 100644 --- a/tests/servers/api/v1/asserts.rs +++ b/tests/servers/api/v1/asserts.rs @@ -1,9 +1,9 @@ // code-review: should we use macros to return the exact line where the assert fails? use reqwest::Response; -use torrust_tracker::servers::apis::v1::context::auth_key::resources::AuthKey; -use torrust_tracker::servers::apis::v1::context::stats::resources::Stats; -use torrust_tracker::servers::apis::v1::context::torrent::resources::torrent::{ListItem, Torrent}; +use torrust_tracker_lib::servers::apis::v1::context::auth_key::resources::AuthKey; +use torrust_tracker_lib::servers::apis::v1::context::stats::resources::Stats; +use torrust_tracker_lib::servers::apis::v1::context::torrent::resources::torrent::{ListItem, Torrent}; // Resource responses diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 8ef72230e..4dc039a9b 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -1,7 +1,7 @@ use std::time::Duration; use serde::Serialize; -use torrust_tracker::core::auth::Key; +use torrust_tracker_lib::core::auth::Key; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; @@ -462,7 +462,7 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { mod deprecated_generate_key_endpoint { - use torrust_tracker::core::auth::Key; + use torrust_tracker_lib::core::auth::Key; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; diff --git a/tests/servers/api/v1/contract/context/health_check.rs b/tests/servers/api/v1/contract/context/health_check.rs index fa6cfa094..32228575d 100644 --- a/tests/servers/api/v1/contract/context/health_check.rs +++ b/tests/servers/api/v1/contract/context/health_check.rs @@ -1,4 +1,4 @@ -use torrust_tracker::servers::apis::v1::context::health_check::resources::{Report, Status}; +use torrust_tracker_lib::servers::apis::v1::context::health_check::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index d49d03535..a81ad6f8c 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -1,7 +1,7 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker::servers::apis::v1::context::stats::resources::Stats; +use torrust_tracker_lib::servers::apis::v1::context::stats::resources::Stats; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index b741a1a65..6070eb4f4 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -1,8 +1,8 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker::servers::apis::v1::context::torrent::resources::peer::Peer; -use torrust_tracker::servers::apis::v1::context::torrent::resources::torrent::{self, Torrent}; +use torrust_tracker_lib::servers::apis::v1::context::torrent::resources::peer::Peer; +use torrust_tracker_lib::servers::apis::v1::context::torrent::resources::torrent::{self, Torrent}; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index 9c79c4a37..2c7efd547 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -1,5 +1,5 @@ -use torrust_tracker::servers::health_check_api::resources::{Report, Status}; -use torrust_tracker::servers::registar::Registar; +use torrust_tracker_lib::servers::health_check_api::resources::{Report, Status}; +use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_test_helpers::configuration; use crate::common::logging; @@ -32,7 +32,7 @@ async fn health_check_endpoint_should_return_status_ok_when_there_is_no_services mod api { use std::sync::Arc; - use torrust_tracker::servers::health_check_api::resources::{Report, Status}; + use torrust_tracker_lib::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; @@ -142,7 +142,7 @@ mod api { mod http { use std::sync::Arc; - use torrust_tracker::servers::health_check_api::resources::{Report, Status}; + use torrust_tracker_lib::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; @@ -251,7 +251,7 @@ mod http { mod udp { use std::sync::Arc; - use torrust_tracker::servers::health_check_api::resources::{Report, Status}; + use torrust_tracker_lib::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs index b101a54e7..17d87d666 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/tests/servers/health_check_api/environment.rs @@ -3,11 +3,11 @@ use std::sync::Arc; use tokio::sync::oneshot::{self, Sender}; use tokio::task::JoinHandle; -use torrust_tracker::bootstrap::jobs::Started; -use torrust_tracker::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; -use torrust_tracker::servers::registar::Registar; -use torrust_tracker::servers::signals::{self, Halted}; use torrust_tracker_configuration::HealthCheckApi; +use torrust_tracker_lib::bootstrap::jobs::Started; +use torrust_tracker_lib::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; +use torrust_tracker_lib::servers::registar::Registar; +use torrust_tracker_lib::servers::signals::{self, Halted}; #[derive(Debug)] pub enum Error { diff --git a/tests/servers/http/client.rs b/tests/servers/http/client.rs index 288987c55..b64a616cd 100644 --- a/tests/servers/http/client.rs +++ b/tests/servers/http/client.rs @@ -1,7 +1,7 @@ use std::net::IpAddr; use reqwest::{Client as ReqwestClient, Response}; -use torrust_tracker::core::auth::Key; +use torrust_tracker_lib::core::auth::Key; use super::requests::announce::{self, Query}; use super::requests::scrape; diff --git a/tests/servers/http/connection_info.rs b/tests/servers/http/connection_info.rs index f4081d60e..123ac05f0 100644 --- a/tests/servers/http/connection_info.rs +++ b/tests/servers/http/connection_info.rs @@ -1,4 +1,4 @@ -use torrust_tracker::core::auth::Key; +use torrust_tracker_lib::core::auth::Key; #[derive(Clone, Debug)] pub struct ConnectionInfo { diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 20b126c18..d615d7eaf 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -2,12 +2,12 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; -use torrust_tracker::bootstrap::app::initialize_with_configuration; -use torrust_tracker::bootstrap::jobs::make_rust_tls; -use torrust_tracker::core::Tracker; -use torrust_tracker::servers::http::server::{HttpServer, Launcher, Running, Stopped}; -use torrust_tracker::servers::registar::Registar; use torrust_tracker_configuration::{Configuration, HttpTracker}; +use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; +use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; +use torrust_tracker_lib::core::Tracker; +use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; +use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; pub struct Environment { diff --git a/tests/servers/http/mod.rs b/tests/servers/http/mod.rs index 65affc433..adcdcbf5e 100644 --- a/tests/servers/http/mod.rs +++ b/tests/servers/http/mod.rs @@ -8,7 +8,7 @@ pub mod v1; pub type Started = environment::Environment; use percent_encoding::NON_ALPHANUMERIC; -use torrust_tracker::servers::http::server; +use torrust_tracker_lib::servers::http::server; pub type ByteArray20 = [u8; 20]; diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 83ebb9ae3..db03f526e 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -14,7 +14,7 @@ async fn environment_should_be_started_and_stopped() { mod for_all_config_modes { - use torrust_tracker::servers::http::v1::handlers::health_check::{Report, Status}; + use torrust_tracker_lib::servers::http::v1::handlers::health_check::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; @@ -1381,7 +1381,7 @@ mod configured_as_private { use std::time::Duration; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker::core::auth::Key; + use torrust_tracker_lib::core::auth::Key; use torrust_tracker_test_helpers::configuration; use crate::common::logging; @@ -1467,7 +1467,7 @@ mod configured_as_private { use aquatic_udp_protocol::PeerId; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker::core::auth::Key; + use torrust_tracker_lib::core::auth::Key; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 9618bef65..de46b7c10 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -7,8 +7,8 @@ use core::panic; use aquatic_udp_protocol::{ConnectRequest, ConnectionId, Response, TransactionId}; use bittorrent_tracker_client::udp::client::UdpTrackerClient; -use torrust_tracker::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; use torrust_tracker_configuration::DEFAULT_TIMEOUT; +use torrust_tracker_lib::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; use torrust_tracker_test_helpers::configuration; use crate::common::logging; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index acfb199f2..01639accc 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -2,13 +2,13 @@ use std::net::SocketAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker::bootstrap::app::initialize_with_configuration; -use torrust_tracker::core::Tracker; -use torrust_tracker::servers::registar::Registar; -use torrust_tracker::servers::udp::server::spawner::Spawner; -use torrust_tracker::servers::udp::server::states::{Running, Stopped}; -use torrust_tracker::servers::udp::server::Server; use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; +use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; +use torrust_tracker_lib::core::Tracker; +use torrust_tracker_lib::servers::registar::Registar; +use torrust_tracker_lib::servers::udp::server::spawner::Spawner; +use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; +use torrust_tracker_lib::servers::udp::server::Server; use torrust_tracker_primitives::peer; pub struct Environment diff --git a/tests/servers/udp/mod.rs b/tests/servers/udp/mod.rs index 7eea8683f..4a89b667a 100644 --- a/tests/servers/udp/mod.rs +++ b/tests/servers/udp/mod.rs @@ -1,4 +1,4 @@ -use torrust_tracker::servers::udp::server::states::Running; +use torrust_tracker_lib::servers::udp::server::states::Running; pub mod asserts; pub mod contract; From 0100bfe1a2b3ff070e1da23fe94105e8102bce30 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 27 Dec 2024 09:50:39 +0000 Subject: [PATCH 0561/1297] chore(deps): update depencencies ``` cargo update Updating crates.io index Locking 7 packages to latest compatible versions Updating cc v1.2.5 -> v1.2.6 Updating quote v1.0.37 -> v1.0.38 Updating reqwest v0.12.9 -> v0.12.10 Updating rustversion v1.0.18 -> v1.0.19 Updating serde_with v3.11.0 -> v3.12.0 Updating serde_with_macros v3.11.0 -> v3.12.0 Updating syn v2.0.91 -> v2.0.92 ``` --- Cargo.lock | 103 +++++++++++++++++++++++++++-------------------------- 1 file changed, 52 insertions(+), 51 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 98875f48d..bf806101e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -333,7 +333,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -456,7 +456,7 @@ checksum = "57d123550fa8d071b7255cb0cc04dc302baa6c8c4a79f55701552684d8399bce" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -544,7 +544,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -679,7 +679,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -790,9 +790,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.5" +version = "1.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c31a0499c1dc64f458ad13872de75c0eb7e3fdb0e67964610c914b034fc5956e" +checksum = "8d6dbb628b8f8555f86d0323c2eb39e3ec81901f4b83e091db8a6a76d316a333" dependencies = [ "jobserver", "libc", @@ -912,7 +912,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -1133,7 +1133,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -1144,7 +1144,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -1188,7 +1188,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", "unicode-xid", ] @@ -1200,7 +1200,7 @@ checksum = "65f152f4b8559c4da5d574bafc7af85454d706b4c5fe8b530d508cacbb6807ea" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -1221,7 +1221,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -1424,7 +1424,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -1436,7 +1436,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -1448,7 +1448,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -1526,7 +1526,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -1958,7 +1958,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -2278,7 +2278,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -2345,7 +2345,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", "termcolor", "thiserror 1.0.69", ] @@ -2544,7 +2544,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -2620,7 +2620,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -2694,7 +2694,7 @@ checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -2844,7 +2844,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -2864,7 +2864,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", "version_check", "yansi", ] @@ -2902,9 +2902,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.37" +version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" dependencies = [ "proc-macro2", ] @@ -3052,9 +3052,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.9" +version = "0.12.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a77c62af46e79de0a562e1a9849205ffcb7fc1238876e9bd743357570e04046f" +checksum = "3d3536321cfc54baa8cf3e273d5e1f63f889067829c4b410fcdbac8ca7b80994" dependencies = [ "base64 0.22.1", "bytes", @@ -3085,6 +3085,7 @@ dependencies = [ "system-configuration", "tokio", "tokio-native-tls", + "tower 0.5.2", "tower-service", "url", "wasm-bindgen", @@ -3173,7 +3174,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.91", + "syn 2.0.92", "unicode-ident", ] @@ -3282,9 +3283,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248" +checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4" [[package]] name = "ryu" @@ -3402,7 +3403,7 @@ checksum = "46f859dbbf73865c6627ed570e78961cd3ac92407a2d117204c49232485da55e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -3449,7 +3450,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -3475,9 +3476,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.11.0" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28bdad6db2b8340e449f7108f020b3b092e8583a9e3fb82713e1d4e71fe817" +checksum = "d6b6f7f2fcb69f747921f79f3926bd1e203fce4fef62c268dd3abfb6d86029aa" dependencies = [ "base64 0.22.1", "chrono", @@ -3493,14 +3494,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.11.0" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d846214a9854ef724f3da161b426242d8de7c1fc7de2f89bb1efcb154dca79d" +checksum = "8d00caa5193a3c8362ac2b73be6b9e768aa5a4b2f721d8f4b339600c3cb51f8e" dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -3639,9 +3640,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.91" +version = "2.0.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d53cbcb5a243bd33b7858b1d7f4aca2153490815872d86d955d6ea29f743c035" +checksum = "70ae51629bf965c5c098cc9e87908a3df5301051a9e087d6f9bef5c9771ed126" dependencies = [ "proc-macro2", "quote", @@ -3665,7 +3666,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -3766,7 +3767,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -3777,7 +3778,7 @@ checksum = "7b50fa271071aae2e6ee85f842e2e28ba8cd2c5fb67f11fcb1fd70b276f9e7d4" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -3881,7 +3882,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -4211,7 +4212,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -4422,7 +4423,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", "wasm-bindgen-shared", ] @@ -4457,7 +4458,7 @@ checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4686,7 +4687,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", "synstructure", ] @@ -4708,7 +4709,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] @@ -4728,7 +4729,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", "synstructure", ] @@ -4757,7 +4758,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.91", + "syn 2.0.92", ] [[package]] From 333794877233d3c409d49ef11a21716325fa64b8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Jan 2025 10:42:15 +0000 Subject: [PATCH 0562/1297] chore(deps): udpate dependencies ```output cargo update Updating crates.io index Locking 26 packages to latest compatible versions Removing async-trait v0.1.83 Updating axum v0.7.9 -> v0.8.1 Updating axum-client-ip v0.6.1 -> v0.7.0 Updating axum-core v0.4.5 -> v0.5.0 Updating axum-extra v0.9.6 -> v0.10.0 Updating axum-macros v0.4.2 -> v0.5.0 Updating btoi v0.4.3 -> v0.4.4 Updating cc v1.2.6 -> v1.2.7 Updating glob v0.3.1 -> v0.3.2 Updating matchit v0.7.3 -> v0.8.4 (available: v0.8.6) Removing multer v3.1.0 Updating phf v0.11.2 -> v0.11.3 Updating phf_codegen v0.11.2 -> v0.11.3 Updating phf_generator v0.11.2 -> v0.11.3 Updating phf_shared v0.11.2 -> v0.11.3 Updating pin-project v1.1.7 -> v1.1.8 Updating pin-project-internal v1.1.7 -> v1.1.8 Updating pin-project-lite v0.2.15 -> v0.2.16 Updating reqwest v0.12.10 -> v0.12.12 Updating rstest v0.23.0 -> v0.24.0 Updating rstest_macros v0.23.0 -> v0.24.0 Updating serde v1.0.216 -> v1.0.217 Updating serde_derive v1.0.216 -> v1.0.217 Updating serde_json v1.0.134 -> v1.0.135 Updating siphasher v0.3.11 -> v1.0.1 Updating syn v2.0.92 -> v2.0.95 Updating tempfile v3.14.0 -> v3.15.0 Updating winnow v0.6.20 -> v0.6.22 ``` --- Cargo.lock | 214 +++++++++++++++++++++++------------------------------ 1 file changed, 93 insertions(+), 121 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bf806101e..68e32ddbd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -325,17 +325,6 @@ version = "4.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" -[[package]] -name = "async-trait" -version = "0.1.83" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.92", -] - [[package]] name = "atomic" version = "0.6.0" @@ -359,14 +348,14 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "axum" -version = "0.7.9" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" +checksum = "6d6fd624c75e18b3b4c6b9caf42b1afe24437daaee904069137d8bab077be8b8" dependencies = [ - "async-trait", "axum-core", "axum-macros", "bytes", + "form_urlencoded", "futures-util", "http", "http-body", @@ -394,9 +383,9 @@ dependencies = [ [[package]] name = "axum-client-ip" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9eefda7e2b27e1bda4d6fa8a06b50803b8793769045918bc37ad062d48a6efac" +checksum = "dff8ee1869817523c8f91c20bf17fd932707f66c2e7e0b0f811b29a227289562" dependencies = [ "axum", "forwarded-header-value", @@ -405,11 +394,10 @@ dependencies = [ [[package]] name = "axum-core" -version = "0.4.5" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" +checksum = "df1362f362fd16024ae199c1970ce98f9661bf5ef94b9808fee734bc3698b733" dependencies = [ - "async-trait", "bytes", "futures-util", "http", @@ -426,23 +414,23 @@ dependencies = [ [[package]] name = "axum-extra" -version = "0.9.6" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c794b30c904f0a1c2fb7740f7df7f7972dfaa14ef6f57cb6178dc63e5dca2f04" +checksum = "460fc6f625a1f7705c6cf62d0d070794e94668988b1c38111baeec177c715f7b" dependencies = [ "axum", "axum-core", "bytes", - "fastrand", + "form_urlencoded", "futures-util", "http", "http-body", "http-body-util", "mime", - "multer", "pin-project-lite", "serde", "serde_html_form", + "serde_path_to_error", "tower 0.5.2", "tower-layer", "tower-service", @@ -450,13 +438,13 @@ dependencies = [ [[package]] name = "axum-macros" -version = "0.4.2" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57d123550fa8d071b7255cb0cc04dc302baa6c8c4a79f55701552684d8399bce" +checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -544,7 +532,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -679,7 +667,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -705,9 +693,9 @@ dependencies = [ [[package]] name = "btoi" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd6407f73a9b8b6162d8a2ef999fe6afd7cc15902ebf42c5cd296addf17e0ad" +checksum = "9586aa4bb508d369941af10c87af0ce6f4ea051bb4f21047791b921c45822137" dependencies = [ "num-traits", ] @@ -790,9 +778,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.6" +version = "1.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d6dbb628b8f8555f86d0323c2eb39e3ec81901f4b83e091db8a6a76d316a333" +checksum = "a012a0df96dd6d06ba9a1b29d6402d1a5d77c6befd2566afdc26e10603dc93d7" dependencies = [ "jobserver", "libc", @@ -912,7 +900,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -1133,7 +1121,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -1144,7 +1132,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -1188,7 +1176,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", "unicode-xid", ] @@ -1200,7 +1188,7 @@ checksum = "65f152f4b8559c4da5d574bafc7af85454d706b4c5fe8b530d508cacbb6807ea" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -1221,7 +1209,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -1424,7 +1412,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -1436,7 +1424,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -1448,7 +1436,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -1526,7 +1514,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -1594,9 +1582,9 @@ checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" [[package]] name = "glob" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" +checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" [[package]] name = "gloo-timers" @@ -1958,7 +1946,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -2213,9 +2201,9 @@ dependencies = [ [[package]] name = "matchit" -version = "0.7.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" [[package]] name = "memchr" @@ -2278,24 +2266,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.92", -] - -[[package]] -name = "multer" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" -dependencies = [ - "bytes", - "encoding_rs", - "futures-util", - "http", - "httparse", - "memchr", - "mime", - "spin", - "version_check", + "syn 2.0.95", ] [[package]] @@ -2345,7 +2316,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", "termcolor", "thiserror 1.0.69", ] @@ -2544,7 +2515,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -2620,7 +2591,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -2641,18 +2612,18 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "phf" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" dependencies = [ "phf_shared", ] [[package]] name = "phf_codegen" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" dependencies = [ "phf_generator", "phf_shared", @@ -2660,9 +2631,9 @@ dependencies = [ [[package]] name = "phf_generator" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ "phf_shared", "rand", @@ -2670,38 +2641,38 @@ dependencies = [ [[package]] name = "phf_shared" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" dependencies = [ "siphasher", ] [[package]] name = "pin-project" -version = "1.1.7" +version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be57f64e946e500c8ee36ef6331845d40a93055567ec57e8fae13efd33759b95" +checksum = "1e2ec53ad785f4d35dac0adea7f7dc6f1bb277ad84a680c7afefeae05d1f5916" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.7" +version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" +checksum = "d56a66c0c55993aa927429d0f8a0abfd74f084e4d9c192cffed01e418d83eefb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] name = "pin-project-lite" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "915a1e146535de9163f3987b8944ed8cf49a18bb0056bcebcdcece385cece4ff" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" [[package]] name = "pin-utils" @@ -2844,7 +2815,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -2864,7 +2835,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", "version_check", "yansi", ] @@ -3052,9 +3023,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.10" +version = "0.12.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3536321cfc54baa8cf3e273d5e1f63f889067829c4b410fcdbac8ca7b80994" +checksum = "43e734407157c3c2034e0258f5e4473ddb361b1e85f95a66690d67264d7cd1da" dependencies = [ "base64 0.22.1", "bytes", @@ -3150,21 +3121,21 @@ dependencies = [ [[package]] name = "rstest" -version = "0.23.0" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a2c585be59b6b5dd66a9d2084aa1d8bd52fbdb806eafdeffb52791147862035" +checksum = "03e905296805ab93e13c1ec3a03f4b6c4f35e9498a3d5fa96dc626d22c03cd89" dependencies = [ - "futures", "futures-timer", + "futures-util", "rstest_macros", "rustc_version", ] [[package]] name = "rstest_macros" -version = "0.23.0" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "825ea780781b15345a146be27eaefb05085e337e869bff01b4306a4fd4a9ad5a" +checksum = "ef0053bbffce09062bee4bcc499b0fbe7a57b879f1efe088d6d8d4c7adcdef9b" dependencies = [ "cfg-if", "glob", @@ -3174,7 +3145,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.92", + "syn 2.0.95", "unicode-ident", ] @@ -3369,9 +3340,9 @@ checksum = "3cb6eb87a131f756572d7fb904f6e7b68633f09cca868c5df1c4b8d1a694bbba" [[package]] name = "serde" -version = "1.0.216" +version = "1.0.217" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b9781016e935a97e8beecf0c933758c97a5520d32930e460142b4cd80c6338e" +checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70" dependencies = [ "serde_derive", ] @@ -3397,13 +3368,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.216" +version = "1.0.217" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46f859dbbf73865c6627ed570e78961cd3ac92407a2d117204c49232485da55e" +checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -3421,9 +3392,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.134" +version = "1.0.135" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d00f4175c42ee48b15416f6193a959ba3a0d67fc699a0db9ad12df9f83991c7d" +checksum = "2b0d7ba2887406110130a978386c4e1befb98c674b4fba677954e4db976630d9" dependencies = [ "indexmap 2.7.0", "itoa", @@ -3450,7 +3421,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -3501,7 +3472,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -3558,9 +3529,9 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] name = "siphasher" -version = "0.3.11" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" +checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" [[package]] name = "slab" @@ -3640,9 +3611,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.92" +version = "2.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ae51629bf965c5c098cc9e87908a3df5301051a9e087d6f9bef5c9771ed126" +checksum = "46f71c0377baf4ef1cc3e3402ded576dccc315800fbc62dfc7fe04b009773b4a" dependencies = [ "proc-macro2", "quote", @@ -3666,7 +3637,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -3715,12 +3686,13 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.14.0" +version = "3.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cce251fcbc87fac86a866eeb0d6c2d536fc16d06f184bb61aeae11aa4cee0c" +checksum = "9a8a559c81686f576e8cd0290cd2a24a2a9ad80c98b3478856500fcbd7acd704" dependencies = [ "cfg-if", "fastrand", + "getrandom", "once_cell", "rustix", "windows-sys 0.59.0", @@ -3767,7 +3739,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -3778,7 +3750,7 @@ checksum = "7b50fa271071aae2e6ee85f842e2e28ba8cd2c5fb67f11fcb1fd70b276f9e7d4" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -3882,7 +3854,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -4212,7 +4184,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -4423,7 +4395,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", "wasm-bindgen-shared", ] @@ -4458,7 +4430,7 @@ checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4633,9 +4605,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "0.6.20" +version = "0.6.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36c1fec1a2bb5866f07c25f68c26e565c4c200aebb96d7e55710c19d3e8ac49b" +checksum = "39281189af81c07ec09db316b302a3e67bf9bd7cbf6c820b50e35fee9c2fa980" dependencies = [ "memchr", ] @@ -4687,7 +4659,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", "synstructure", ] @@ -4709,7 +4681,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] @@ -4729,7 +4701,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", "synstructure", ] @@ -4758,7 +4730,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.92", + "syn 2.0.95", ] [[package]] From 366ef1c9df44ff7f66f03d025adf3f370d8f9624 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Jan 2025 12:37:28 +0000 Subject: [PATCH 0563/1297] fix: lifetime parameters on function `from_request_parts` do not match the trait ``` error[E0195]: lifetime parameters or bounds on associated function `from_request_parts` do not match the trait declaration --> src/servers/http/v1/extractors/announce_request.rs:53:26 | 53 | fn from_request_parts<'life0, 'life1, 'async_trait>( | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetimes do not match associated function in trait error[E0195]: lifetime parameters or bounds on associated function `from_request_parts` do not match the trait declaration --> src/servers/http/v1/extractors/authentication_key.rs:79:26 | 79 | fn from_request_parts<'life0, 'life1, 'async_trait>( | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetimes do not match associated function in trait error[E0195]: lifetime parameters or bounds on associated function `from_request_parts` do not match the trait declaration --> src/servers/http/v1/extractors/client_ip_sources.rs:60:26 | 60 | fn from_request_parts<'life0, 'life1, 'async_trait>( | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetimes do not match associated function in trait error[E0195]: lifetime parameters or bounds on associated function `from_request_parts` do not match the trait declaration --> src/servers/http/v1/extractors/scrape_request.rs:53:26 | 53 | fn from_request_parts<'life0, 'life1, 'async_trait>( | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetimes do not match associated function in trait For more information about this error, try `rustc --explain E0195`. ``` --- .../http/v1/extractors/announce_request.rs | 13 ++---------- .../http/v1/extractors/authentication_key.rs | 20 +++++-------------- .../http/v1/extractors/client_ip_sources.rs | 18 ++++------------- .../http/v1/extractors/scrape_request.rs | 13 ++---------- 4 files changed, 13 insertions(+), 51 deletions(-) diff --git a/src/servers/http/v1/extractors/announce_request.rs b/src/servers/http/v1/extractors/announce_request.rs index ea9a22c7a..32b69ae0b 100644 --- a/src/servers/http/v1/extractors/announce_request.rs +++ b/src/servers/http/v1/extractors/announce_request.rs @@ -27,12 +27,12 @@ //! ```text //! d14:failure reason240:Bad request. Cannot parse query params for announce request: invalid param value invalid for info_hash in not enough bytes for infohash: got 7 bytes, expected 20 src/shared/bit_torrent/info_hash.rs:240:27, src/servers/http/v1/requests/announce.rs:182:42e //! ``` +use std::future::Future; use std::panic::Location; use axum::extract::FromRequestParts; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; -use futures::future::BoxFuture; use futures::FutureExt; use crate::servers::http::v1::query::Query; @@ -49,16 +49,7 @@ where { type Rejection = Response; - #[must_use] - fn from_request_parts<'life0, 'life1, 'async_trait>( - parts: &'life0 mut Parts, - _state: &'life1 S, - ) -> BoxFuture<'async_trait, Result> - where - 'life0: 'async_trait, - 'life1: 'async_trait, - Self: 'async_trait, - { + fn from_request_parts(parts: &mut Parts, _state: &S) -> impl Future> + Send { async { match extract_announce_from(parts.uri.query()) { Ok(announce_request) => Ok(ExtractRequest(announce_request)), diff --git a/src/servers/http/v1/extractors/authentication_key.rs b/src/servers/http/v1/extractors/authentication_key.rs index e86241edf..35efdf93d 100644 --- a/src/servers/http/v1/extractors/authentication_key.rs +++ b/src/servers/http/v1/extractors/authentication_key.rs @@ -42,14 +42,13 @@ //! > Neither [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) //! > nor [The Private Torrents](https://www.bittorrent.org/beps/bep_0027.html) //! > specifications specify any HTTP status code for authentication errors. +use std::future::Future; use std::panic::Location; use axum::extract::rejection::PathRejection; use axum::extract::{FromRequestParts, Path}; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; -use futures::future::BoxFuture; -use futures::FutureExt; use serde::Deserialize; use crate::core::auth::Key; @@ -71,21 +70,13 @@ impl KeyParam { impl FromRequestParts for Extract where - S: Send + Sync, + S: Send + Sync + 'static, { type Rejection = Response; - #[must_use] - fn from_request_parts<'life0, 'life1, 'async_trait>( - parts: &'life0 mut Parts, - state: &'life1 S, - ) -> BoxFuture<'async_trait, Result> - where - 'life0: 'async_trait, - 'life1: 'async_trait, - Self: 'async_trait, - { - async { + #[allow(clippy::manual_async_fn)] + fn from_request_parts(parts: &mut Parts, state: &S) -> impl Future> + Send { + async move { // Extract `key` from URL path with Axum `Path` extractor let maybe_path_with_key = Path::::from_request_parts(parts, state).await; @@ -94,7 +85,6 @@ where Err(error) => Err(error.into_response()), } } - .boxed() } } diff --git a/src/servers/http/v1/extractors/client_ip_sources.rs b/src/servers/http/v1/extractors/client_ip_sources.rs index 5b235fbe0..1ca5a22d0 100644 --- a/src/servers/http/v1/extractors/client_ip_sources.rs +++ b/src/servers/http/v1/extractors/client_ip_sources.rs @@ -35,14 +35,13 @@ //! `right_most_x_forwarded_for` = 126.0.0.2 //! `connection_info_ip` = 126.0.0.3 //! ``` +use std::future::Future; use std::net::SocketAddr; use axum::extract::{ConnectInfo, FromRequestParts}; use axum::http::request::Parts; use axum::response::Response; use axum_client_ip::RightmostXForwardedFor; -use futures::future::BoxFuture; -use futures::FutureExt; use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; @@ -56,17 +55,9 @@ where { type Rejection = Response; - #[must_use] - fn from_request_parts<'life0, 'life1, 'async_trait>( - parts: &'life0 mut Parts, - state: &'life1 S, - ) -> BoxFuture<'async_trait, Result> - where - 'life0: 'async_trait, - 'life1: 'async_trait, - Self: 'async_trait, - { - async { + #[allow(clippy::manual_async_fn)] + fn from_request_parts(parts: &mut Parts, state: &S) -> impl Future> + Send { + async move { let right_most_x_forwarded_for = match RightmostXForwardedFor::from_request_parts(parts, state).await { Ok(right_most_x_forwarded_for) => Some(right_most_x_forwarded_for.0), Err(_) => None, @@ -82,6 +73,5 @@ where connection_info_ip, })) } - .boxed() } } diff --git a/src/servers/http/v1/extractors/scrape_request.rs b/src/servers/http/v1/extractors/scrape_request.rs index 35c0bb1b5..890c4033c 100644 --- a/src/servers/http/v1/extractors/scrape_request.rs +++ b/src/servers/http/v1/extractors/scrape_request.rs @@ -27,12 +27,12 @@ //! ```text //! d14:failure reason235:Bad request. Cannot parse query params for scrape request: invalid param value invalid for info_hash in not enough bytes for infohash: got 7 bytes, expected 20 src/shared/bit_torrent/info_hash.rs:240:27, src/servers/http/v1/requests/scrape.rs:66:46e //! ``` +use std::future::Future; use std::panic::Location; use axum::extract::FromRequestParts; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; -use futures::future::BoxFuture; use futures::FutureExt; use crate::servers::http::v1::query::Query; @@ -49,16 +49,7 @@ where { type Rejection = Response; - #[must_use] - fn from_request_parts<'life0, 'life1, 'async_trait>( - parts: &'life0 mut Parts, - _state: &'life1 S, - ) -> BoxFuture<'async_trait, Result> - where - 'life0: 'async_trait, - 'life1: 'async_trait, - Self: 'async_trait, - { + fn from_request_parts(parts: &mut Parts, _state: &S) -> impl Future> + Send { async { match extract_scrape_from(parts.uri.query()) { Ok(scrape_request) => Ok(ExtractRequest(scrape_request)), From bfab30f40c62ff113274a2fb55469ea3bde580f5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Jan 2025 12:51:09 +0000 Subject: [PATCH 0564/1297] fix: update axum routes captures You have to use `{capture}` instead of semicolon `:` to insert segment variables in the URL. It fixes these tests: ``` failures: ---- bootstrap::jobs::tracker_apis::tests::it_should_start_http_tracker stdout ---- thread 'bootstrap::jobs::tracker_apis::tests::it_should_start_http_tracker' panicked at src/servers/apis/v1/context/auth_key/routes.rs:21:10: Path segments must not start with `:`. For capture groups, use `{capture}`. If you meant to literally match a segment starting with a colon, call `without_v07_checks` on the router. note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace thread 'bootstrap::jobs::tracker_apis::tests::it_should_start_http_tracker' panicked at src/servers/apis/server.rs:159:17: Unable to start API server: channel closed ---- bootstrap::jobs::http_tracker::tests::it_should_start_http_tracker stdout ---- thread 'bootstrap::jobs::http_tracker::tests::it_should_start_http_tracker' panicked at src/servers/http/v1/routes.rs:41:10: Path segments must not start with `:`. For capture groups, use `{capture}`. If you meant to literally match a segment starting with a colon, call `without_v07_checks` on the router. thread 'bootstrap::jobs::http_tracker::tests::it_should_start_http_tracker' panicked at src/servers/http/server.rs:170:38: it should be able to start the service: RecvError(()) ---- servers::http::server::tests::it_should_be_able_to_start_and_stop stdout ---- thread 'servers::http::server::tests::it_should_be_able_to_start_and_stop' panicked at src/servers/http/v1/routes.rs:41:10: Path segments must not start with `:`. For capture groups, use `{capture}`. If you meant to literally match a segment starting with a colon, call `without_v07_checks` on the router. thread 'servers::http::server::tests::it_should_be_able_to_start_and_stop' panicked at src/servers/http/server.rs:170:38: it should be able to start the service: RecvError(()) ---- servers::apis::server::tests::it_should_be_able_to_start_and_stop stdout ---- thread 'servers::apis::server::tests::it_should_be_able_to_start_and_stop' panicked at src/servers/apis/v1/context/auth_key/routes.rs:21:10: Path segments must not start with `:`. For capture groups, use `{capture}`. If you meant to literally match a segment starting with a colon, call `without_v07_checks` on the router. thread 'servers::apis::server::tests::it_should_be_able_to_start_and_stop' panicked at src/servers/apis/server.rs:159:17: Unable to start API server: channel closed failures: bootstrap::jobs::http_tracker::tests::it_should_start_http_tracker bootstrap::jobs::tracker_apis::tests::it_should_start_http_tracker servers::apis::server::tests::it_should_be_able_to_start_and_stop servers::http::server::tests::it_should_be_able_to_start_and_stop test result: FAILED. 203 passed; 4 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.05s ``` --- src/servers/apis/v1/context/auth_key/routes.rs | 2 +- src/servers/apis/v1/context/torrent/routes.rs | 2 +- src/servers/apis/v1/context/whitelist/routes.rs | 4 ++-- src/servers/http/v1/routes.rs | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/servers/apis/v1/context/auth_key/routes.rs b/src/servers/apis/v1/context/auth_key/routes.rs index 60ccd77ab..ac11281ee 100644 --- a/src/servers/apis/v1/context/auth_key/routes.rs +++ b/src/servers/apis/v1/context/auth_key/routes.rs @@ -27,7 +27,7 @@ pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { // // The POST /key/:seconds_valid has been deprecated and it will removed in the future. // Use POST /keys - &format!("{prefix}/key/:seconds_valid_or_key"), + &format!("{prefix}/key/{{seconds_valid_or_key}}"), post(generate_auth_key_handler) .with_state(tracker.clone()) .delete(delete_auth_key_handler) diff --git a/src/servers/apis/v1/context/torrent/routes.rs b/src/servers/apis/v1/context/torrent/routes.rs index 6f8c28df5..bca594e3d 100644 --- a/src/servers/apis/v1/context/torrent/routes.rs +++ b/src/servers/apis/v1/context/torrent/routes.rs @@ -17,7 +17,7 @@ pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { // Torrents router .route( - &format!("{prefix}/torrent/:info_hash"), + &format!("{prefix}/torrent/{{info_hash}}"), get(get_torrent_handler).with_state(tracker.clone()), ) .route(&format!("{prefix}/torrents"), get(get_torrents_handler).with_state(tracker)) diff --git a/src/servers/apis/v1/context/whitelist/routes.rs b/src/servers/apis/v1/context/whitelist/routes.rs index e4e85181f..35312ea97 100644 --- a/src/servers/apis/v1/context/whitelist/routes.rs +++ b/src/servers/apis/v1/context/whitelist/routes.rs @@ -20,11 +20,11 @@ pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { router // Whitelisted torrents .route( - &format!("{prefix}/:info_hash"), + &format!("{prefix}/{{info_hash}}"), post(add_torrent_to_whitelist_handler).with_state(tracker.clone()), ) .route( - &format!("{prefix}/:info_hash"), + &format!("{prefix}/{{info_hash}}"), delete(remove_torrent_from_whitelist_handler).with_state(tracker.clone()), ) // Whitelist commands diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index a5d402693..3c6926c37 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -38,10 +38,10 @@ pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { .route("/health_check", get(health_check::handler)) // Announce request .route("/announce", get(announce::handle_without_key).with_state(tracker.clone())) - .route("/announce/:key", get(announce::handle_with_key).with_state(tracker.clone())) + .route("/announce/{key}", get(announce::handle_with_key).with_state(tracker.clone())) // Scrape request .route("/scrape", get(scrape::handle_without_key).with_state(tracker.clone())) - .route("/scrape/:key", get(scrape::handle_with_key).with_state(tracker)) + .route("/scrape/{key}", get(scrape::handle_with_key).with_state(tracker)) // Add extension to get the client IP from the connection info .layer(SecureClientIpSource::ConnectInfo.into_extension()) .layer(CompressionLayer::new()) From f4a73997969e58457f836f72cbbef93026bb21a8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Jan 2025 12:58:35 +0000 Subject: [PATCH 0565/1297] test: fix should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid --- tests/servers/api/v1/asserts.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/servers/api/v1/asserts.rs b/tests/servers/api/v1/asserts.rs index f3d04d524..b56144d3f 100644 --- a/tests/servers/api/v1/asserts.rs +++ b/tests/servers/api/v1/asserts.rs @@ -117,7 +117,7 @@ pub async fn assert_unprocessable_auth_key_duration_param(response: Response, _i pub async fn assert_invalid_key_duration_param(response: Response, invalid_key_duration: &str) { assert_bad_request( response, - &format!("Invalid URL: Cannot parse `\"{invalid_key_duration}\"` to a `u64`"), + &format!("Invalid URL: Cannot parse `{invalid_key_duration}` to a `u64`"), ) .await; } From cb406871472c8270b4eee3e53a3151db3fe4e8f0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Jan 2025 13:00:57 +0000 Subject: [PATCH 0566/1297] test: should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_parsed --- tests/servers/api/v1/contract/context/torrent.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index 6070eb4f4..602545273 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -213,7 +213,7 @@ async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_p ) .await; - assert_bad_request(response, "Failed to deserialize query string: invalid digit found in string").await; + assert_bad_request(response, "Failed to deserialize query string: limit: invalid digit found in string").await; } env.stop().await; From ce12fe72f8dac7522a6bd1a7ae321404c3d21aa1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Jan 2025 13:03:08 +0000 Subject: [PATCH 0567/1297] test: fix test should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_parsed ``` servers::api::v1::contract::context::torrent::should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_parsed ``` --- tests/servers/api/v1/contract/context/torrent.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index 602545273..fff8129a5 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -189,7 +189,7 @@ async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_ ) .await; - assert_bad_request(response, "Failed to deserialize query string: invalid digit found in string").await; + assert_bad_request(response, "Failed to deserialize query string: offset: invalid digit found in string").await; } env.stop().await; From 76329d742ff79aebddb33be39e0782309fbed300 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Jan 2025 13:05:39 +0000 Subject: [PATCH 0568/1297] chore: fix format --- tests/servers/api/v1/contract/context/torrent.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index fff8129a5..260fe4a3a 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -189,7 +189,11 @@ async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_ ) .await; - assert_bad_request(response, "Failed to deserialize query string: offset: invalid digit found in string").await; + assert_bad_request( + response, + "Failed to deserialize query string: offset: invalid digit found in string", + ) + .await; } env.stop().await; @@ -213,7 +217,11 @@ async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_p ) .await; - assert_bad_request(response, "Failed to deserialize query string: limit: invalid digit found in string").await; + assert_bad_request( + response, + "Failed to deserialize query string: limit: invalid digit found in string", + ) + .await; } env.stop().await; From 2ff476b541794a56188f866927e5660e20ba268f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Jan 2025 15:40:40 +0000 Subject: [PATCH 0569/1297] refactor: rename enum variand Udp4RequestAborted The event is used for both UDP 4 and UDP 6 requests aborted. --- src/core/statistics/event/handler.rs | 2 +- src/core/statistics/event/mod.rs | 2 +- src/servers/udp/server/launcher.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/statistics/event/handler.rs b/src/core/statistics/event/handler.rs index 5acc5e12c..3e2e64866 100644 --- a/src/core/statistics/event/handler.rs +++ b/src/core/statistics/event/handler.rs @@ -24,7 +24,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { } // UDP - Event::Udp4RequestAborted => { + Event::UdpRequestAborted => { stats_repository.increase_udp_requests_aborted().await; } diff --git a/src/core/statistics/event/mod.rs b/src/core/statistics/event/mod.rs index b14995cc1..70c543c70 100644 --- a/src/core/statistics/event/mod.rs +++ b/src/core/statistics/event/mod.rs @@ -18,7 +18,7 @@ pub enum Event { Tcp4Scrape, Tcp6Announce, Tcp6Scrape, - Udp4RequestAborted, + UdpRequestAborted, Udp4Request, Udp4Connect, Udp4Announce, diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index ada50eb31..4fe0b1cba 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -202,7 +202,7 @@ impl Launcher { if old_request_aborted { // Evicted task from active requests buffer was aborted. - tracker.send_stats_event(statistics::event::Event::Udp4RequestAborted).await; + tracker.send_stats_event(statistics::event::Event::UdpRequestAborted).await; } } else { tokio::task::yield_now().await; From 6f9b44c4fa5d93d49fbcb0b51c39fff4ebf25d61 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Jan 2025 16:01:47 +0000 Subject: [PATCH 0570/1297] feat: [#1145] add banned reqs counter to stats --- src/core/services/statistics/mod.rs | 1 + src/core/statistics/event/handler.rs | 3 ++ src/core/statistics/event/mod.rs | 1 + src/core/statistics/metrics.rs | 3 ++ src/core/statistics/repository.rs | 6 +++ .../apis/v1/context/stats/resources.rs | 53 ++++++++++--------- src/servers/udp/server/launcher.rs | 3 ++ .../servers/api/v1/contract/context/stats.rs | 1 + tests/servers/udp/contract.rs | 8 +++ 9 files changed, 55 insertions(+), 24 deletions(-) diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 10e1c60fa..b4cc32198 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -76,6 +76,7 @@ pub async fn get_metrics(tracker: Arc) -> TrackerMetrics { tcp6_scrapes_handled: stats.tcp6_scrapes_handled, // UDP udp_requests_aborted: stats.udp_requests_aborted, + udp_requests_banned: stats.udp_requests_banned, udp4_requests: stats.udp4_requests, udp4_connections_handled: stats.udp4_connections_handled, udp4_announces_handled: stats.udp4_announces_handled, diff --git a/src/core/statistics/event/handler.rs b/src/core/statistics/event/handler.rs index 3e2e64866..06ff6abe2 100644 --- a/src/core/statistics/event/handler.rs +++ b/src/core/statistics/event/handler.rs @@ -27,6 +27,9 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { Event::UdpRequestAborted => { stats_repository.increase_udp_requests_aborted().await; } + Event::UdpRequestBanned => { + stats_repository.increase_udp_requests_banned().await; + } // UDP4 Event::Udp4Request => { diff --git a/src/core/statistics/event/mod.rs b/src/core/statistics/event/mod.rs index 70c543c70..b2344fb78 100644 --- a/src/core/statistics/event/mod.rs +++ b/src/core/statistics/event/mod.rs @@ -19,6 +19,7 @@ pub enum Event { Tcp6Announce, Tcp6Scrape, UdpRequestAborted, + UdpRequestBanned, Udp4Request, Udp4Connect, Udp4Announce, diff --git a/src/core/statistics/metrics.rs b/src/core/statistics/metrics.rs index 970302816..47bc5af6e 100644 --- a/src/core/statistics/metrics.rs +++ b/src/core/statistics/metrics.rs @@ -31,6 +31,9 @@ pub struct Metrics { /// Total number of UDP (UDP tracker) requests aborted. pub udp_requests_aborted: u64, + /// Total number of UDP (UDP tracker) requests banned. + pub udp_requests_banned: u64, + /// Total number of UDP (UDP tracker) requests from IPv4 peers. pub udp4_requests: u64, diff --git a/src/core/statistics/repository.rs b/src/core/statistics/repository.rs index bdbc046de..563e87534 100644 --- a/src/core/statistics/repository.rs +++ b/src/core/statistics/repository.rs @@ -70,6 +70,12 @@ impl Repository { drop(stats_lock); } + pub async fn increase_udp_requests_banned(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp_requests_banned += 1; + drop(stats_lock); + } + pub async fn increase_udp4_requests(&self) { let mut stats_lock = self.stats.write().await; stats_lock.udp4_requests += 1; diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index 55cb3a581..fd73499ef 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -36,6 +36,8 @@ pub struct Stats { /// Total number of UDP (UDP tracker) requests aborted. pub udp_requests_aborted: u64, + /// Total number of UDP (UDP tracker) requests banned. + pub udp_requests_banned: u64, /// Total number of UDP (UDP tracker) requests from IPv4 peers. pub udp4_requests: u64, @@ -80,6 +82,7 @@ impl From for Stats { tcp6_scrapes_handled: metrics.protocol_metrics.tcp6_scrapes_handled, // UDP udp_requests_aborted: metrics.protocol_metrics.udp_requests_aborted, + udp_requests_banned: metrics.protocol_metrics.udp_requests_banned, udp4_requests: metrics.protocol_metrics.udp4_requests, udp4_connections_handled: metrics.protocol_metrics.udp4_connections_handled, udp4_announces_handled: metrics.protocol_metrics.udp4_announces_handled, @@ -124,18 +127,19 @@ mod tests { tcp6_scrapes_handled: 10, // UDP udp_requests_aborted: 11, - udp4_requests: 12, - udp4_connections_handled: 13, - udp4_announces_handled: 14, - udp4_scrapes_handled: 15, - udp4_responses: 16, - udp4_errors_handled: 17, - udp6_requests: 18, - udp6_connections_handled: 19, - udp6_announces_handled: 20, - udp6_scrapes_handled: 21, - udp6_responses: 22, - udp6_errors_handled: 23 + udp_requests_banned: 12, + udp4_requests: 13, + udp4_connections_handled: 14, + udp4_announces_handled: 15, + udp4_scrapes_handled: 16, + udp4_responses: 17, + udp4_errors_handled: 18, + udp6_requests: 19, + udp6_connections_handled: 20, + udp6_announces_handled: 21, + udp6_scrapes_handled: 22, + udp6_responses: 23, + udp6_errors_handled: 24 } }), Stats { @@ -152,18 +156,19 @@ mod tests { tcp6_scrapes_handled: 10, // UDP udp_requests_aborted: 11, - udp4_requests: 12, - udp4_connections_handled: 13, - udp4_announces_handled: 14, - udp4_scrapes_handled: 15, - udp4_responses: 16, - udp4_errors_handled: 17, - udp6_requests: 18, - udp6_connections_handled: 19, - udp6_announces_handled: 20, - udp6_scrapes_handled: 21, - udp6_responses: 22, - udp6_errors_handled: 23 + udp_requests_banned: 12, + udp4_requests: 13, + udp4_connections_handled: 14, + udp4_announces_handled: 15, + udp4_scrapes_handled: 16, + udp4_responses: 17, + udp4_errors_handled: 18, + udp6_requests: 19, + udp6_connections_handled: 20, + udp6_announces_handled: 21, + udp6_scrapes_handled: 22, + udp6_responses: 23, + udp6_errors_handled: 24 } ); } diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 4fe0b1cba..15c7ca017 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -175,6 +175,9 @@ impl Launcher { if ban_service.read().await.is_banned(&req.from.ip()) { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop continue: (banned ip)"); + + tracker.send_stats_event(statistics::event::Event::UdpRequestBanned).await; + continue; } diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index a81ad6f8c..087c36cc6 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -45,6 +45,7 @@ async fn should_allow_getting_tracker_statistics() { tcp6_scrapes_handled: 0, // UDP udp_requests_aborted: 0, + udp_requests_banned: 0, udp4_requests: 0, udp4_connections_handled: 0, udp4_announces_handled: 0, diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index de46b7c10..b77343785 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -229,6 +229,7 @@ mod receiving_an_announce_request { logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; + let tracker = env.tracker.clone(); let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_tracker_client) => udp_tracker_client, @@ -267,6 +268,8 @@ mod receiving_an_announce_request { info_hash, ); + let udp_requests_banned_before = tracker.get_stats().await.udp_requests_banned; + // This should return a timeout error match client.send(announce_request.into()).await { Ok(_) => (), @@ -275,6 +278,11 @@ mod receiving_an_announce_request { assert!(client.receive().await.is_err()); + let udp_requests_banned_after = tracker.get_stats().await.udp_requests_banned; + + // UDP counter for banned requests should be increased by 1 + assert_eq!(udp_requests_banned_after, udp_requests_banned_before + 1); + env.stop().await; } } From 1299f17237923c36a5efa0ceb2d9e407437702b4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Jan 2025 16:35:30 +0000 Subject: [PATCH 0571/1297] feat: make ban service generic for all trackers All UDP tracker will share the same service. In the future, the HTTP trackers can also use it. The service was not include inside the tracker (easy solution) becuase the Tracker type is too big. It has became the app container. In fact, we want to reduce it in the future by extracting the services outside of the tracker: stats, whitelist, etc. Those services will be instantiate independently in the future in the app bootstrap. --- src/app.rs | 14 +++++++++++--- src/bootstrap/app.rs | 9 +++++++-- src/bootstrap/jobs/udp_tracker.rs | 13 ++++++++++--- src/console/profiling.rs | 4 ++-- src/main.rs | 4 ++-- src/servers/udp/server/banning.rs | 11 +++-------- src/servers/udp/server/launcher.rs | 21 +++++++++++---------- src/servers/udp/server/mod.rs | 13 +++++++++++-- src/servers/udp/server/spawner.rs | 6 ++++-- src/servers/udp/server/states.rs | 10 ++++++++-- tests/servers/udp/environment.rs | 10 +++++++++- 11 files changed, 78 insertions(+), 37 deletions(-) diff --git a/src/app.rs b/src/app.rs index 06fea4d2e..f40072132 100644 --- a/src/app.rs +++ b/src/app.rs @@ -23,12 +23,14 @@ //! - Tracker REST API: the tracker API can be enabled/disabled. use std::sync::Arc; +use tokio::sync::RwLock; use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; use tracing::instrument; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; use crate::servers::registar::Registar; +use crate::servers::udp::server::banning::BanService; use crate::{core, servers}; /// # Panics @@ -37,8 +39,12 @@ use crate::{core, servers}; /// /// - Can't retrieve tracker keys from database. /// - Can't load whitelist from database. -#[instrument(skip(config, tracker))] -pub async fn start(config: &Configuration, tracker: Arc) -> Vec> { +#[instrument(skip(config, tracker, ban_service))] +pub async fn start( + config: &Configuration, + tracker: Arc, + ban_service: Arc>, +) -> Vec> { if config.http_api.is_none() && (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) && (config.http_trackers.is_none() || config.http_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) @@ -75,7 +81,9 @@ pub async fn start(config: &Configuration, tracker: Arc) -> Vec (Configuration, Arc) { +pub fn setup() -> (Configuration, Arc, Arc>) { #[cfg(not(test))] check_seed(); @@ -44,9 +47,11 @@ pub fn setup() -> (Configuration, Arc) { let tracker = initialize_with_configuration(&configuration); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + tracing::info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); - (configuration, tracker) + (configuration, tracker, ban_service) } /// checks if the seed is the instance seed in production. diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 6aab06d4f..8948811af 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -8,12 +8,14 @@ //! > for the configuration options. use std::sync::Arc; +use tokio::sync::RwLock; use tokio::task::JoinHandle; use torrust_tracker_configuration::UdpTracker; use tracing::instrument; use crate::core; use crate::servers::registar::ServiceRegistrationForm; +use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::spawner::Spawner; use crate::servers::udp::server::Server; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; @@ -29,13 +31,18 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// It will panic if the task did not finish successfully. #[must_use] #[allow(clippy::async_yields_async)] -#[instrument(skip(config, tracker, form))] -pub async fn start_job(config: &UdpTracker, tracker: Arc, form: ServiceRegistrationForm) -> JoinHandle<()> { +#[instrument(skip(config, tracker, ban_service, form))] +pub async fn start_job( + config: &UdpTracker, + tracker: Arc, + ban_service: Arc>, + form: ServiceRegistrationForm, +) -> JoinHandle<()> { let bind_to = config.bind_address; let cookie_lifetime = config.cookie_lifetime; let server = Server::new(Spawner::new(bind_to)) - .start(tracker, form, cookie_lifetime) + .start(tracker, ban_service, form, cookie_lifetime) .await .expect("it should be able to start the udp tracker"); diff --git a/src/console/profiling.rs b/src/console/profiling.rs index 5fb507197..1d31af3ce 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -179,9 +179,9 @@ pub async fn run() { return; }; - let (config, tracker) = bootstrap::app::setup(); + let (config, tracker, ban_service) = bootstrap::app::setup(); - let jobs = app::start(&config, tracker).await; + let jobs = app::start(&config, tracker, ban_service).await; // Run the tracker for a fixed duration let run_duration = sleep(Duration::from_secs(duration_secs)); diff --git a/src/main.rs b/src/main.rs index 0e2bcfbc9..206633f8c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,9 +2,9 @@ use torrust_tracker_lib::{app, bootstrap}; #[tokio::main] async fn main() { - let (config, tracker) = bootstrap::app::setup(); + let (config, tracker, ban_service) = bootstrap::app::setup(); - let jobs = app::start(&config, tracker).await; + let jobs = app::start(&config, tracker, ban_service).await; // handle the signals tokio::select! { diff --git a/src/servers/udp/server/banning.rs b/src/servers/udp/server/banning.rs index df236820c..dada592be 100644 --- a/src/servers/udp/server/banning.rs +++ b/src/servers/udp/server/banning.rs @@ -20,7 +20,6 @@ use std::net::IpAddr; use bloom::{CountingBloomFilter, ASMS}; use tokio::time::Instant; -use url::Url; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; @@ -28,16 +27,14 @@ pub struct BanService { max_connection_id_errors_per_ip: u32, fuzzy_error_counter: CountingBloomFilter, accurate_error_counter: HashMap, - local_addr: Url, last_connection_id_errors_reset: Instant, } impl BanService { #[must_use] - pub fn new(max_connection_id_errors_per_ip: u32, local_addr: Url) -> Self { + pub fn new(max_connection_id_errors_per_ip: u32) -> Self { Self { max_connection_id_errors_per_ip, - local_addr, fuzzy_error_counter: CountingBloomFilter::with_rate(4, 0.01, 100), accurate_error_counter: HashMap::new(), last_connection_id_errors_reset: tokio::time::Instant::now(), @@ -82,8 +79,7 @@ impl BanService { self.last_connection_id_errors_reset = Instant::now(); - let local_addr = self.local_addr.to_string(); - tracing::info!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop (connection id errors filter cleared)"); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp::run_udp_server::loop (connection id errors filter cleared)"); } } @@ -95,8 +91,7 @@ mod tests { /// Sample service with one day ban duration. fn ban_service(counter_limit: u32) -> BanService { - let udp_tracker_url = "udp://127.0.0.1".parse().unwrap(); - BanService::new(counter_limit, udp_tracker_url) + BanService::new(counter_limit) } #[test] diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 15c7ca017..753dc9915 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -24,7 +24,7 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// The maximum number of connection id errors per ip. Clients will be banned if /// they exceed this limit. -const MAX_CONNECTION_ID_ERRORS_PER_IP: u32 = 10; +pub const MAX_CONNECTION_ID_ERRORS_PER_IP: u32 = 10; const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 3600; /// A UDP server instance launcher. @@ -40,9 +40,10 @@ impl Launcher { /// It panics if unable to send address of socket. /// It panics if the udp server is loaded when the tracker is private. /// - #[instrument(skip(tracker, bind_to, tx_start, rx_halt))] + #[instrument(skip(tracker, ban_service, bind_to, tx_start, rx_halt))] pub async fn run_with_graceful_shutdown( tracker: Arc, + ban_service: Arc>, bind_to: SocketAddr, cookie_lifetime: Duration, tx_start: oneshot::Sender, @@ -80,7 +81,7 @@ impl Launcher { let local_addr = local_udp_url.clone(); tokio::task::spawn(async move { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_with_graceful_shutdown::task (listening...)"); - let () = Self::run_udp_server_main(receiver, tracker.clone(), cookie_lifetime).await; + let () = Self::run_udp_server_main(receiver, tracker.clone(), ban_service.clone(), cookie_lifetime).await; }) }; @@ -117,8 +118,13 @@ impl Launcher { ServiceHealthCheckJob::new(binding, info, job) } - #[instrument(skip(receiver, tracker))] - async fn run_udp_server_main(mut receiver: Receiver, tracker: Arc, cookie_lifetime: Duration) { + #[instrument(skip(receiver, tracker, ban_service))] + async fn run_udp_server_main( + mut receiver: Receiver, + tracker: Arc, + ban_service: Arc>, + cookie_lifetime: Duration, + ) { let active_requests = &mut ActiveRequests::default(); let addr = receiver.bound_socket_address(); @@ -127,11 +133,6 @@ impl Launcher { let cookie_lifetime = cookie_lifetime.as_secs_f64(); - let ban_service = Arc::new(RwLock::new(BanService::new( - MAX_CONNECTION_ID_ERRORS_PER_IP, - local_addr.parse().unwrap(), - ))); - let ban_cleaner = ban_service.clone(); tokio::spawn(async move { diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 9f974ca8c..6eb98a7b1 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -58,17 +58,23 @@ mod tests { use std::sync::Arc; use std::time::Duration; + use tokio::sync::RwLock; use torrust_tracker_test_helpers::configuration::ephemeral_public; use super::spawner::Spawner; use super::Server; use crate::bootstrap::app::initialize_with_configuration; use crate::servers::registar::Registar; + use crate::servers::udp::server::banning::BanService; + use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_public()); + let tracker = initialize_with_configuration(&cfg); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; let bind_to = config.bind_address; @@ -77,7 +83,7 @@ mod tests { let stopped = Server::new(Spawner::new(bind_to)); let started = stopped - .start(tracker, register.give_form(), config.cookie_lifetime) + .start(tracker, ban_service, register.give_form(), config.cookie_lifetime) .await .expect("it should start the server"); @@ -91,7 +97,10 @@ mod tests { #[tokio::test] async fn it_should_be_able_to_start_and_stop_with_wait() { let cfg = Arc::new(ephemeral_public()); + let tracker = initialize_with_configuration(&cfg); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; let register = &Registar::default(); @@ -99,7 +108,7 @@ mod tests { let stopped = Server::new(Spawner::new(bind_to)); let started = stopped - .start(tracker, register.give_form(), config.cookie_lifetime) + .start(tracker, ban_service, register.give_form(), config.cookie_lifetime) .await .expect("it should start the server"); diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index acebdcf75..ce2fe8eae 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -5,9 +5,10 @@ use std::time::Duration; use derive_more::derive::Display; use derive_more::Constructor; -use tokio::sync::oneshot; +use tokio::sync::{oneshot, RwLock}; use tokio::task::JoinHandle; +use super::banning::BanService; use super::launcher::Launcher; use crate::bootstrap::jobs::Started; use crate::core::Tracker; @@ -28,6 +29,7 @@ impl Spawner { pub fn spawn_launcher( &self, tracker: Arc, + ban_service: Arc>, cookie_lifetime: Duration, tx_start: oneshot::Sender, rx_halt: oneshot::Receiver, @@ -35,7 +37,7 @@ impl Spawner { let spawner = Self::new(self.bind_to); tokio::spawn(async move { - Launcher::run_with_graceful_shutdown(tracker, spawner.bind_to, cookie_lifetime, tx_start, rx_halt).await; + Launcher::run_with_graceful_shutdown(tracker, ban_service, spawner.bind_to, cookie_lifetime, tx_start, rx_halt).await; spawner }) } diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index 8b87c6efb..02742049d 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -5,9 +5,11 @@ use std::time::Duration; use derive_more::derive::Display; use derive_more::Constructor; +use tokio::sync::RwLock; use tokio::task::JoinHandle; use tracing::{instrument, Level}; +use super::banning::BanService; use super::spawner::Spawner; use super::{Server, UdpError}; use crate::bootstrap::jobs::Started; @@ -62,10 +64,11 @@ impl Server { /// /// It panics if unable to receive the bound socket address from service. /// - #[instrument(skip(self, tracker, form), err, ret(Display, level = Level::INFO))] + #[instrument(skip(self, tracker, ban_service, form), err, ret(Display, level = Level::INFO))] pub async fn start( self, tracker: Arc, + ban_service: Arc>, form: ServiceRegistrationForm, cookie_lifetime: Duration, ) -> Result, std::io::Error> { @@ -75,7 +78,10 @@ impl Server { assert!(!tx_halt.is_closed(), "Halt channel for UDP tracker should be open"); // May need to wrap in a task to about a tokio bug. - let task = self.state.spawner.spawn_launcher(tracker, cookie_lifetime, tx_start, rx_halt); + let task = self + .state + .spawner + .spawn_launcher(tracker, ban_service, cookie_lifetime, tx_start, rx_halt); let local_addr = rx_start.await.expect("it should be able to start the service").address; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 01639accc..f744809c5 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -2,10 +2,13 @@ use std::net::SocketAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; +use tokio::sync::RwLock; use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::registar::Registar; +use torrust_tracker_lib::servers::udp::server::banning::BanService; +use torrust_tracker_lib::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; use torrust_tracker_lib::servers::udp::server::Server; @@ -17,6 +20,7 @@ where { pub config: Arc, pub tracker: Arc, + pub ban_service: Arc>, pub registar: Registar, pub server: Server, } @@ -36,6 +40,7 @@ impl Environment { #[allow(dead_code)] pub fn new(configuration: &Arc) -> Self { let tracker = initialize_with_configuration(configuration); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let udp_tracker = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); @@ -48,6 +53,7 @@ impl Environment { Self { config, tracker, + ban_service, registar: Registar::default(), server, } @@ -59,10 +65,11 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + ban_service: self.ban_service.clone(), registar: self.registar.clone(), server: self .server - .start(self.tracker, self.registar.give_form(), cookie_lifetime) + .start(self.tracker, self.ban_service, self.registar.give_form(), cookie_lifetime) .await .unwrap(), } @@ -85,6 +92,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + ban_service: self.ban_service, registar: Registar::default(), server: stopped.expect("it stop the udp tracker service"), } From 1ce2e33271272c598050ab712110f2ab5048bf57 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Jan 2025 17:35:35 +0000 Subject: [PATCH 0572/1297] feat: [#1145] add banned ips total for UDP to stats ```json { "torrents": 0, "seeders": 0, "completed": 0, "leechers": 0, "tcp4_connections_handled": 0, "tcp4_announces_handled": 0, "tcp4_scrapes_handled": 0, "tcp6_connections_handled": 0, "tcp6_announces_handled": 0, "tcp6_scrapes_handled": 0, "udp_requests_aborted": 0, "udp_requests_banned": 0, "udp_banned_ips_total": 0, "udp4_requests": 0, "udp4_connections_handled": 0, "udp4_announces_handled": 0, "udp4_scrapes_handled": 0, "udp4_responses": 0, "udp4_errors_handled": 0, "udp6_requests": 0, "udp6_connections_handled": 0, "udp6_announces_handled": 0, "udp6_scrapes_handled": 0, "udp6_responses": 0, "udp6_errors_handled": 0 } ``` The new metric: `udp_banned_ips_total`. It's the total number of IPs that have been banned for sending wrong connection IDs. --- src/app.rs | 1 + src/bootstrap/app.rs | 4 +- src/bootstrap/jobs/tracker_apis.rs | 18 +++++-- src/core/services/statistics/mod.rs | 12 ++++- src/core/statistics/metrics.rs | 3 ++ src/main.rs | 4 +- src/servers/apis/routes.rs | 13 +++-- src/servers/apis/server.rs | 18 +++++-- src/servers/apis/v1/context/stats/handlers.rs | 9 +++- .../apis/v1/context/stats/resources.rs | 53 ++++++++++--------- src/servers/apis/v1/context/stats/routes.rs | 9 +++- src/servers/apis/v1/routes.rs | 6 ++- src/servers/udp/server/banning.rs | 5 ++ tests/servers/api/environment.rs | 11 +++- .../servers/api/v1/contract/context/stats.rs | 1 + tests/servers/udp/contract.rs | 7 +++ 16 files changed, 124 insertions(+), 50 deletions(-) diff --git a/src/app.rs b/src/app.rs index f40072132..abfe75256 100644 --- a/src/app.rs +++ b/src/app.rs @@ -113,6 +113,7 @@ pub async fn start( if let Some(job) = tracker_apis::start_job( http_api_config, tracker.clone(), + ban_service.clone(), registar.give_form(), servers::apis::Version::V1, ) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index a4bdd14ea..38b7d40c5 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -47,11 +47,11 @@ pub fn setup() -> (Configuration, Arc, Arc>) { let tracker = initialize_with_configuration(&configuration); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let udp_ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); tracing::info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); - (configuration, tracker, ban_service) + (configuration, tracker, udp_ban_service) } /// checks if the seed is the instance seed in production. diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 35b13b7ce..858888540 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -24,6 +24,7 @@ use std::net::SocketAddr; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; +use tokio::sync::RwLock; use tokio::task::JoinHandle; use torrust_tracker_configuration::{AccessTokens, HttpApi}; use tracing::instrument; @@ -33,6 +34,7 @@ use crate::core; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::apis::Version; use crate::servers::registar::ServiceRegistrationForm; +use crate::servers::udp::server::banning::BanService; /// This is the message that the "launcher" spawned task sends to the main /// application process to notify the API server was successfully started. @@ -54,10 +56,11 @@ pub struct ApiServerJobStarted(); /// It would panic if unable to send the `ApiServerJobStarted` notice. /// /// -#[instrument(skip(config, tracker, form))] +#[instrument(skip(config, tracker, ban_service, form))] pub async fn start_job( config: &HttpApi, tracker: Arc, + ban_service: Arc>, form: ServiceRegistrationForm, version: Version, ) -> Option> { @@ -70,21 +73,22 @@ pub async fn start_job( let access_tokens = Arc::new(config.access_tokens.clone()); match version { - Version::V1 => Some(start_v1(bind_to, tls, tracker.clone(), form, access_tokens).await), + Version::V1 => Some(start_v1(bind_to, tls, tracker.clone(), ban_service.clone(), form, access_tokens).await), } } #[allow(clippy::async_yields_async)] -#[instrument(skip(socket, tls, tracker, form, access_tokens))] +#[instrument(skip(socket, tls, tracker, ban_service, form, access_tokens))] async fn start_v1( socket: SocketAddr, tls: Option, tracker: Arc, + ban_service: Arc>, form: ServiceRegistrationForm, access_tokens: Arc, ) -> JoinHandle<()> { let server = ApiServer::new(Launcher::new(socket, tls)) - .start(tracker, form, access_tokens) + .start(tracker, ban_service, form, access_tokens) .await .expect("it should be able to start to the tracker api"); @@ -98,21 +102,25 @@ async fn start_v1( mod tests { use std::sync::Arc; + use tokio::sync::RwLock; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::initialize_with_configuration; use crate::bootstrap::jobs::tracker_apis::start_job; use crate::servers::apis::Version; use crate::servers::registar::Registar; + use crate::servers::udp::server::banning::BanService; + use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; #[tokio::test] async fn it_should_start_http_tracker() { let cfg = Arc::new(ephemeral_public()); let config = &cfg.http_api.clone().unwrap(); let tracker = initialize_with_configuration(&cfg); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let version = Version::V1; - start_job(config, tracker, Registar::default().give_form(), version) + start_job(config, tracker, ban_service, Registar::default().give_form(), version) .await .expect("it should be able to join to the tracker api start-job"); } diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index b4cc32198..41d2f2e10 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -40,10 +40,12 @@ pub mod setup; use std::sync::Arc; +use tokio::sync::RwLock; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use crate::core::statistics::metrics::Metrics; use crate::core::Tracker; +use crate::servers::udp::server::banning::BanService; /// All the metrics collected by the tracker. #[derive(Debug, PartialEq)] @@ -60,9 +62,10 @@ pub struct TrackerMetrics { } /// It returns all the [`TrackerMetrics`] -pub async fn get_metrics(tracker: Arc) -> TrackerMetrics { +pub async fn get_metrics(tracker: Arc, ban_service: Arc>) -> TrackerMetrics { let torrents_metrics = tracker.get_torrents_metrics(); let stats = tracker.get_stats().await; + let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); TrackerMetrics { torrents_metrics, @@ -77,6 +80,7 @@ pub async fn get_metrics(tracker: Arc) -> TrackerMetrics { // UDP udp_requests_aborted: stats.udp_requests_aborted, udp_requests_banned: stats.udp_requests_banned, + udp_banned_ips_total: udp_banned_ips_total as u64, udp4_requests: stats.udp4_requests, udp4_connections_handled: stats.udp4_connections_handled, udp4_announces_handled: stats.udp4_announces_handled, @@ -97,6 +101,7 @@ pub async fn get_metrics(tracker: Arc) -> TrackerMetrics { mod tests { use std::sync::Arc; + use tokio::sync::RwLock; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; @@ -104,6 +109,8 @@ mod tests { use crate::core; use crate::core::services::statistics::{get_metrics, TrackerMetrics}; use crate::core::services::tracker_factory; + use crate::servers::udp::server::banning::BanService; + use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -112,8 +119,9 @@ mod tests { #[tokio::test] async fn the_statistics_service_should_return_the_tracker_metrics() { let tracker = Arc::new(tracker_factory(&tracker_configuration())); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let tracker_metrics = get_metrics(tracker.clone()).await; + let tracker_metrics = get_metrics(tracker.clone(), ban_service.clone()).await; assert_eq!( tracker_metrics, diff --git a/src/core/statistics/metrics.rs b/src/core/statistics/metrics.rs index 47bc5af6e..2cbbf4b05 100644 --- a/src/core/statistics/metrics.rs +++ b/src/core/statistics/metrics.rs @@ -34,6 +34,9 @@ pub struct Metrics { /// Total number of UDP (UDP tracker) requests banned. pub udp_requests_banned: u64, + /// Total number of banned IPs. + pub udp_banned_ips_total: u64, + /// Total number of UDP (UDP tracker) requests from IPv4 peers. pub udp4_requests: u64, diff --git a/src/main.rs b/src/main.rs index 206633f8c..c93982191 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,9 +2,9 @@ use torrust_tracker_lib::{app, bootstrap}; #[tokio::main] async fn main() { - let (config, tracker, ban_service) = bootstrap::app::setup(); + let (config, tracker, udp_ban_service) = bootstrap::app::setup(); - let jobs = app::start(&config, tracker, ban_service).await; + let jobs = app::start(&config, tracker, udp_ban_service).await; // handle the signals tokio::select! { diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 0b0862fb9..98442ea97 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -15,6 +15,7 @@ use axum::response::Response; use axum::routing::get; use axum::{middleware, BoxError, Router}; use hyper::{Request, StatusCode}; +use tokio::sync::RwLock; use torrust_tracker_configuration::{AccessTokens, DEFAULT_TIMEOUT}; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; @@ -32,16 +33,22 @@ use super::v1::middlewares::auth::State; use crate::core::Tracker; use crate::servers::apis::API_LOG_TARGET; use crate::servers::logging::Latency; +use crate::servers::udp::server::banning::BanService; /// Add all API routes to the router. #[allow(clippy::needless_pass_by_value)] -#[instrument(skip(tracker, access_tokens))] -pub fn router(tracker: Arc, access_tokens: Arc, server_socket_addr: SocketAddr) -> Router { +#[instrument(skip(tracker, ban_service, access_tokens))] +pub fn router( + tracker: Arc, + ban_service: Arc>, + access_tokens: Arc, + server_socket_addr: SocketAddr, +) -> Router { let router = Router::new(); let api_url_prefix = "/api"; - let router = v1::routes::add(api_url_prefix, router, tracker.clone()); + let router = v1::routes::add(api_url_prefix, router, tracker.clone(), ban_service.clone()); let state = State { access_tokens }; diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index eadadecf2..9d1c77c03 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -33,6 +33,7 @@ use derive_more::Constructor; use futures::future::BoxFuture; use thiserror::Error; use tokio::sync::oneshot::{Receiver, Sender}; +use tokio::sync::RwLock; use torrust_tracker_configuration::AccessTokens; use tracing::{instrument, Level}; @@ -44,6 +45,7 @@ use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::logging::STARTED_ON; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{graceful_shutdown, Halted}; +use crate::servers::udp::server::banning::BanService; /// Errors that can occur when starting or stopping the API server. #[derive(Debug, Error)] @@ -122,10 +124,11 @@ impl ApiServer { /// # Panics /// /// It would panic if the bound socket address cannot be sent back to this starter. - #[instrument(skip(self, tracker, form, access_tokens), err, ret(Display, level = Level::INFO))] + #[instrument(skip(self, tracker, ban_service, form, access_tokens), err, ret(Display, level = Level::INFO))] pub async fn start( self, tracker: Arc, + ban_service: Arc>, form: ServiceRegistrationForm, access_tokens: Arc, ) -> Result, Error> { @@ -137,7 +140,7 @@ impl ApiServer { let task = tokio::spawn(async move { tracing::debug!(target: API_LOG_TARGET, "Starting with launcher in spawned task ..."); - let _task = launcher.start(tracker, access_tokens, tx_start, rx_halt).await; + let _task = launcher.start(tracker, ban_service, access_tokens, tx_start, rx_halt).await; tracing::debug!(target: API_LOG_TARGET, "Started with launcher in spawned task"); @@ -235,10 +238,11 @@ impl Launcher { /// /// Will panic if unable to bind to the socket, or unable to get the address of the bound socket. /// Will also panic if unable to send message regarding the bound socket address. - #[instrument(skip(self, tracker, access_tokens, tx_start, rx_halt))] + #[instrument(skip(self, tracker, ban_service, access_tokens, tx_start, rx_halt))] pub fn start( &self, tracker: Arc, + ban_service: Arc>, access_tokens: Arc, tx_start: Sender, rx_halt: Receiver, @@ -246,7 +250,7 @@ impl Launcher { let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); - let router = router(tracker, access_tokens, address); + let router = router(tracker, ban_service, access_tokens, address); let handle = Handle::new(); @@ -294,12 +298,15 @@ impl Launcher { mod tests { use std::sync::Arc; + use tokio::sync::RwLock; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::initialize_with_configuration; use crate::bootstrap::jobs::make_rust_tls; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::registar::Registar; + use crate::servers::udp::server::banning::BanService; + use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { @@ -307,6 +314,7 @@ mod tests { let config = &cfg.http_api.clone().unwrap(); let tracker = initialize_with_configuration(&cfg); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let bind_to = config.bind_address; @@ -321,7 +329,7 @@ mod tests { let register = &Registar::default(); let started = stopped - .start(tracker, register.give_form(), access_tokens) + .start(tracker, ban_service, register.give_form(), access_tokens) .await .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index 8b11b1ff1..b630c763d 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -6,10 +6,12 @@ use axum::extract::State; use axum::response::Response; use axum_extra::extract::Query; use serde::Deserialize; +use tokio::sync::RwLock; use super::responses::{metrics_response, stats_response}; use crate::core::services::statistics::get_metrics; use crate::core::Tracker; +use crate::servers::udp::server::banning::BanService; #[derive(Deserialize, Debug, Default)] #[serde(rename_all = "lowercase")] @@ -35,8 +37,11 @@ pub struct QueryParams { /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::stats#get-tracker-statistics) /// for more information about this endpoint. -pub async fn get_stats_handler(State(tracker): State>, params: Query) -> Response { - let metrics = get_metrics(tracker.clone()).await; +pub async fn get_stats_handler( + State(state): State<(Arc, Arc>)>, + params: Query, +) -> Response { + let metrics = get_metrics(state.0.clone(), state.1.clone()).await; match params.0.format { Some(format) => match format { diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index fd73499ef..814f94b21 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -38,6 +38,8 @@ pub struct Stats { pub udp_requests_aborted: u64, /// Total number of UDP (UDP tracker) requests banned. pub udp_requests_banned: u64, + /// Total number of IPs banned for UDP (UDP tracker) requests. + pub udp_banned_ips_total: u64, /// Total number of UDP (UDP tracker) requests from IPv4 peers. pub udp4_requests: u64, @@ -83,6 +85,7 @@ impl From for Stats { // UDP udp_requests_aborted: metrics.protocol_metrics.udp_requests_aborted, udp_requests_banned: metrics.protocol_metrics.udp_requests_banned, + udp_banned_ips_total: metrics.protocol_metrics.udp_banned_ips_total, udp4_requests: metrics.protocol_metrics.udp4_requests, udp4_connections_handled: metrics.protocol_metrics.udp4_connections_handled, udp4_announces_handled: metrics.protocol_metrics.udp4_announces_handled, @@ -128,18 +131,19 @@ mod tests { // UDP udp_requests_aborted: 11, udp_requests_banned: 12, - udp4_requests: 13, - udp4_connections_handled: 14, - udp4_announces_handled: 15, - udp4_scrapes_handled: 16, - udp4_responses: 17, - udp4_errors_handled: 18, - udp6_requests: 19, - udp6_connections_handled: 20, - udp6_announces_handled: 21, - udp6_scrapes_handled: 22, - udp6_responses: 23, - udp6_errors_handled: 24 + udp_banned_ips_total: 13, + udp4_requests: 14, + udp4_connections_handled: 15, + udp4_announces_handled: 16, + udp4_scrapes_handled: 17, + udp4_responses: 18, + udp4_errors_handled: 19, + udp6_requests: 20, + udp6_connections_handled: 21, + udp6_announces_handled: 22, + udp6_scrapes_handled: 23, + udp6_responses: 24, + udp6_errors_handled: 25 } }), Stats { @@ -157,18 +161,19 @@ mod tests { // UDP udp_requests_aborted: 11, udp_requests_banned: 12, - udp4_requests: 13, - udp4_connections_handled: 14, - udp4_announces_handled: 15, - udp4_scrapes_handled: 16, - udp4_responses: 17, - udp4_errors_handled: 18, - udp6_requests: 19, - udp6_connections_handled: 20, - udp6_announces_handled: 21, - udp6_scrapes_handled: 22, - udp6_responses: 23, - udp6_errors_handled: 24 + udp_banned_ips_total: 13, + udp4_requests: 14, + udp4_connections_handled: 15, + udp4_announces_handled: 16, + udp4_scrapes_handled: 17, + udp4_responses: 18, + udp4_errors_handled: 19, + udp6_requests: 20, + udp6_connections_handled: 21, + udp6_announces_handled: 22, + udp6_scrapes_handled: 23, + udp6_responses: 24, + udp6_errors_handled: 25 } ); } diff --git a/src/servers/apis/v1/context/stats/routes.rs b/src/servers/apis/v1/context/stats/routes.rs index d8d552697..fde1056c3 100644 --- a/src/servers/apis/v1/context/stats/routes.rs +++ b/src/servers/apis/v1/context/stats/routes.rs @@ -7,11 +7,16 @@ use std::sync::Arc; use axum::routing::get; use axum::Router; +use tokio::sync::RwLock; use super::handlers::get_stats_handler; use crate::core::Tracker; +use crate::servers::udp::server::banning::BanService; /// It adds the routes to the router for the [`stats`](crate::servers::apis::v1::context::stats) API context. -pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { - router.route(&format!("{prefix}/stats"), get(get_stats_handler).with_state(tracker)) +pub fn add(prefix: &str, router: Router, tracker: Arc, ban_service: Arc>) -> Router { + router.route( + &format!("{prefix}/stats"), + get(get_stats_handler).with_state((tracker, ban_service)), + ) } diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs index 3786b3532..23ef6c47e 100644 --- a/src/servers/apis/v1/routes.rs +++ b/src/servers/apis/v1/routes.rs @@ -2,16 +2,18 @@ use std::sync::Arc; use axum::Router; +use tokio::sync::RwLock; use super::context::{auth_key, stats, torrent, whitelist}; use crate::core::Tracker; +use crate::servers::udp::server::banning::BanService; /// Add the routes for the v1 API. -pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { +pub fn add(prefix: &str, router: Router, tracker: Arc, ban_service: Arc>) -> Router { let v1_prefix = format!("{prefix}/v1"); let router = auth_key::routes::add(&v1_prefix, router, tracker.clone()); - let router = stats::routes::add(&v1_prefix, router, tracker.clone()); + let router = stats::routes::add(&v1_prefix, router, tracker.clone(), ban_service); let router = whitelist::routes::add(&v1_prefix, router, tracker.clone()); torrent::routes::add(&v1_prefix, router, tracker) diff --git a/src/servers/udp/server/banning.rs b/src/servers/udp/server/banning.rs index dada592be..d32dfa541 100644 --- a/src/servers/udp/server/banning.rs +++ b/src/servers/udp/server/banning.rs @@ -51,6 +51,11 @@ impl BanService { self.accurate_error_counter.get(ip).copied() } + #[must_use] + pub fn get_banned_ips_total(&self) -> usize { + self.accurate_error_counter.len() + } + #[must_use] pub fn get_estimate_count(&self, ip: &IpAddr) -> u32 { self.fuzzy_error_counter.estimate_count(&ip.to_string()) diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index f754e329f..00fb9d05b 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -3,12 +3,15 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; +use tokio::sync::RwLock; use torrust_tracker_configuration::{Configuration, HttpApi}; use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; +use torrust_tracker_lib::servers::udp::server::banning::BanService; +use torrust_tracker_lib::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use torrust_tracker_primitives::peer; use super::connection_info::ConnectionInfo; @@ -19,6 +22,7 @@ where { pub config: Arc, pub tracker: Arc, + pub ban_service: Arc>, pub registar: Registar, pub server: ApiServer, } @@ -37,6 +41,8 @@ impl Environment { pub fn new(configuration: &Arc) -> Self { let tracker = initialize_with_configuration(configuration); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let config = Arc::new(configuration.http_api.clone().expect("missing API configuration")); let bind_to = config.bind_address; @@ -48,6 +54,7 @@ impl Environment { Self { config, tracker, + ban_service, registar: Registar::default(), server, } @@ -59,10 +66,11 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + ban_service: self.ban_service.clone(), registar: self.registar.clone(), server: self .server - .start(self.tracker, self.registar.give_form(), access_tokens) + .start(self.tracker, self.ban_service, self.registar.give_form(), access_tokens) .await .unwrap(), } @@ -78,6 +86,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + ban_service: self.ban_service, registar: Registar::default(), server: self.server.stop().await.unwrap(), } diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index 087c36cc6..e99333d7a 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -46,6 +46,7 @@ async fn should_allow_getting_tracker_statistics() { // UDP udp_requests_aborted: 0, udp_requests_banned: 0, + udp_banned_ips_total: 0, udp4_requests: 0, udp4_connections_handled: 0, udp4_announces_handled: 0, diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index b77343785..f0ed98b21 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -230,12 +230,15 @@ mod receiving_an_announce_request { let env = Started::new(&configuration::ephemeral().into()).await; let tracker = env.tracker.clone(); + let ban_service = env.ban_service.clone(); let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_tracker_client) => udp_tracker_client, Err(err) => panic!("{err}"), }; + let udp_banned_ips_total_before = ban_service.read().await.get_banned_ips_total(); + // The eleven first requests should be fine let invalid_connection_id = ConnectionId::new(0); // Zero is one of the not normal values. @@ -279,10 +282,14 @@ mod receiving_an_announce_request { assert!(client.receive().await.is_err()); let udp_requests_banned_after = tracker.get_stats().await.udp_requests_banned; + let udp_banned_ips_total_after = ban_service.read().await.get_banned_ips_total(); // UDP counter for banned requests should be increased by 1 assert_eq!(udp_requests_banned_after, udp_requests_banned_before + 1); + // UDP counter for banned IPs should be increased by 1 + assert_eq!(udp_banned_ips_total_after, udp_banned_ips_total_before + 1); + env.stop().await; } } From 08a862a5adbc95e0bd998c0b5dd6103d3e0a5f57 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Jan 2025 18:15:13 +0000 Subject: [PATCH 0573/1297] refactor: [#1145] add type and processing time to UDP response events - The `kind`is the type of response: connect, annouince, etc - The req_processing_time is the time it took to process the requests on the backend, without including sending the response back to the client (network latency). --- src/core/statistics/event/handler.rs | 10 +++++++-- src/core/statistics/event/mod.rs | 20 +++++++++++++++-- src/servers/udp/server/processor.rs | 33 ++++++++++++++++++++++++---- 3 files changed, 55 insertions(+), 8 deletions(-) diff --git a/src/core/statistics/event/handler.rs b/src/core/statistics/event/handler.rs index 06ff6abe2..32b666d68 100644 --- a/src/core/statistics/event/handler.rs +++ b/src/core/statistics/event/handler.rs @@ -44,7 +44,10 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { Event::Udp4Scrape => { stats_repository.increase_udp4_scrapes().await; } - Event::Udp4Response => { + Event::Udp4Response { + kind: _, + req_processing_time: _, + } => { stats_repository.increase_udp4_responses().await; } Event::Udp4Error => { @@ -64,7 +67,10 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { Event::Udp6Scrape => { stats_repository.increase_udp6_scrapes().await; } - Event::Udp6Response => { + Event::Udp6Response { + kind: _, + req_processing_time: _, + } => { stats_repository.increase_udp6_responses().await; } Event::Udp6Error => { diff --git a/src/core/statistics/event/mod.rs b/src/core/statistics/event/mod.rs index b2344fb78..905aa0372 100644 --- a/src/core/statistics/event/mod.rs +++ b/src/core/statistics/event/mod.rs @@ -1,3 +1,5 @@ +use std::time::Duration; + pub mod handler; pub mod listener; pub mod sender; @@ -24,12 +26,26 @@ pub enum Event { Udp4Connect, Udp4Announce, Udp4Scrape, - Udp4Response, + Udp4Response { + kind: UdpResponseKind, + req_processing_time: Duration, + }, Udp4Error, Udp6Request, Udp6Connect, Udp6Announce, Udp6Scrape, - Udp6Response, + Udp6Response { + kind: UdpResponseKind, + req_processing_time: Duration, + }, Udp6Error, } + +#[derive(Debug, PartialEq, Eq)] +pub enum UdpResponseKind { + Connect, + Announce, + Scrape, + Error, +} diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 9a9798698..e0f7c4624 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -1,13 +1,16 @@ use std::io::Cursor; use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; +use std::time::Duration; use aquatic_udp_protocol::Response; use tokio::sync::RwLock; +use tokio::time::Instant; use tracing::{instrument, Level}; use super::banning::BanService; use super::bound_socket::BoundSocket; +use crate::core::statistics::event::UdpResponseKind; use crate::core::{statistics, Tracker}; use crate::servers::udp::handlers::CookieTimeValues; use crate::servers::udp::{handlers, RawRequest}; @@ -30,6 +33,9 @@ impl Processor { #[instrument(skip(self, request, ban_service))] pub async fn process_request(self, request: RawRequest, ban_service: Arc>) { let from = request.from; + + let start_time = Instant::now(); + let response = handlers::handle_packet( request, &self.tracker, @@ -39,11 +45,13 @@ impl Processor { ) .await; - self.send_response(from, response).await; + let elapsed_time = start_time.elapsed(); + + self.send_response(from, response, elapsed_time).await; } #[instrument(skip(self))] - async fn send_response(self, target: SocketAddr, response: Response) { + async fn send_response(self, target: SocketAddr, response: Response, req_processing_time: Duration) { tracing::debug!("send response"); let response_type = match &response { @@ -54,6 +62,13 @@ impl Processor { Response::Error(e) => format!("Error: {e:?}"), }; + let response_kind = match &response { + Response::Connect(_) => UdpResponseKind::Connect, + Response::AnnounceIpv4(_) | Response::AnnounceIpv6(_) => UdpResponseKind::Announce, + Response::Scrape(_) => UdpResponseKind::Scrape, + Response::Error(_e) => UdpResponseKind::Error, + }; + let mut writer = Cursor::new(Vec::with_capacity(200)); match response.write_bytes(&mut writer) { @@ -71,10 +86,20 @@ impl Processor { match target.ip() { IpAddr::V4(_) => { - self.tracker.send_stats_event(statistics::event::Event::Udp4Response).await; + self.tracker + .send_stats_event(statistics::event::Event::Udp4Response { + kind: response_kind, + req_processing_time, + }) + .await; } IpAddr::V6(_) => { - self.tracker.send_stats_event(statistics::event::Event::Udp6Response).await; + self.tracker + .send_stats_event(statistics::event::Event::Udp6Response { + kind: response_kind, + req_processing_time, + }) + .await; } } } From 903d47f7258a56d141228e95ba0d34552fe038f1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 9 Jan 2025 16:54:04 +0000 Subject: [PATCH 0574/1297] feat: [#1145] add UDP avg processing time to stats ```json { "torrents": 1, "seeders": 1, "completed": 0, "leechers": 0, "tcp4_connections_handled": 0, "tcp4_announces_handled": 0, "tcp4_scrapes_handled": 0, "tcp6_connections_handled": 0, "tcp6_announces_handled": 0, "tcp6_scrapes_handled": 0, "udp_requests_aborted": 0, "udp_requests_banned": 0, "udp_banned_ips_total": 0, "udp_avg_connect_processing_time_ns": 37000, "udp_avg_announce_processing_time_ns": 42067, "udp_avg_scrape_processing_time_ns": 0, "udp4_requests": 60, "udp4_connections_handled": 30, "udp4_announces_handled": 30, "udp4_scrapes_handled": 0, "udp4_responses": 60, "udp4_errors_handled": 0, "udp6_requests": 0, "udp6_connections_handled": 0, "udp6_announces_handled": 0, "udp6_scrapes_handled": 0, "udp6_responses": 0, "udp6_errors_handled": 0 } ``` New metrcis are: - udp_avg_connect_processing_time_ns - udp_avg_announce_processing_time_ns - udp_avg_scrape_processing_time_ns --- src/core/services/statistics/mod.rs | 8 +- src/core/statistics/event/handler.rs | 25 ++++++- src/core/statistics/metrics.rs | 12 +++ src/core/statistics/repository.rs | 59 +++++++++++++++ .../apis/v1/context/stats/resources.rs | 75 ++++++++++++------- .../apis/v1/context/stats/responses.rs | 32 ++++++++ .../servers/api/v1/contract/context/stats.rs | 5 ++ 7 files changed, 187 insertions(+), 29 deletions(-) diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 41d2f2e10..4143aaf1f 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -70,10 +70,11 @@ pub async fn get_metrics(tracker: Arc, ban_service: Arc, ban_service: Arc { stats_repository.increase_udp4_responses().await; + + match kind { + UdpResponseKind::Connect => { + stats_repository + .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) + .await; + } + UdpResponseKind::Announce => { + stats_repository + .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) + .await; + } + UdpResponseKind::Scrape => { + stats_repository + .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) + .await; + } + UdpResponseKind::Error => {} + } } Event::Udp4Error => { stats_repository.increase_udp4_errors().await; diff --git a/src/core/statistics/metrics.rs b/src/core/statistics/metrics.rs index 2cbbf4b05..40262efd6 100644 --- a/src/core/statistics/metrics.rs +++ b/src/core/statistics/metrics.rs @@ -28,6 +28,7 @@ pub struct Metrics { /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. pub tcp6_scrapes_handled: u64, + // UDP /// Total number of UDP (UDP tracker) requests aborted. pub udp_requests_aborted: u64, @@ -37,6 +38,16 @@ pub struct Metrics { /// Total number of banned IPs. pub udp_banned_ips_total: u64, + /// Average rounded time spent processing UDP connect requests. + pub udp_avg_connect_processing_time_ns: u64, + + /// Average rounded time spent processing UDP announce requests. + pub udp_avg_announce_processing_time_ns: u64, + + /// Average rounded time spent processing UDP scrape requests. + pub udp_avg_scrape_processing_time_ns: u64, + + // UDPv4 /// Total number of UDP (UDP tracker) requests from IPv4 peers. pub udp4_requests: u64, @@ -55,6 +66,7 @@ pub struct Metrics { /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. pub udp4_errors_handled: u64, + // UDPv6 /// Total number of UDP (UDP tracker) requests from IPv6 peers. pub udp6_requests: u64, diff --git a/src/core/statistics/repository.rs b/src/core/statistics/repository.rs index 563e87534..ec5100073 100644 --- a/src/core/statistics/repository.rs +++ b/src/core/statistics/repository.rs @@ -1,4 +1,5 @@ use std::sync::Arc; +use std::time::Duration; use tokio::sync::{RwLock, RwLockReadGuard}; @@ -112,6 +113,64 @@ impl Repository { drop(stats_lock); } + #[allow(clippy::cast_precision_loss)] + #[allow(clippy::cast_possible_truncation)] + #[allow(clippy::cast_sign_loss)] + pub async fn recalculate_udp_avg_connect_processing_time_ns(&self, req_processing_time: Duration) { + let mut stats_lock = self.stats.write().await; + + let req_processing_time = req_processing_time.as_nanos() as f64; + let udp_connections_handled = (stats_lock.udp4_connections_handled + stats_lock.udp6_connections_handled) as f64; + + let previous_avg = stats_lock.udp_avg_connect_processing_time_ns; + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_connections_handled; + + stats_lock.udp_avg_connect_processing_time_ns = new_avg.ceil() as u64; + + drop(stats_lock); + } + + #[allow(clippy::cast_precision_loss)] + #[allow(clippy::cast_possible_truncation)] + #[allow(clippy::cast_sign_loss)] + pub async fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) { + let mut stats_lock = self.stats.write().await; + + let req_processing_time = req_processing_time.as_nanos() as f64; + + let udp_announces_handled = (stats_lock.udp4_announces_handled + stats_lock.udp6_announces_handled) as f64; + + let previous_avg = stats_lock.udp_avg_announce_processing_time_ns; + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_announces_handled; + + stats_lock.udp_avg_announce_processing_time_ns = new_avg.ceil() as u64; + + drop(stats_lock); + } + + #[allow(clippy::cast_precision_loss)] + #[allow(clippy::cast_possible_truncation)] + #[allow(clippy::cast_sign_loss)] + pub async fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) { + let mut stats_lock = self.stats.write().await; + + let req_processing_time = req_processing_time.as_nanos() as f64; + let udp_scrapes_handled = (stats_lock.udp4_scrapes_handled + stats_lock.udp6_scrapes_handled) as f64; + + let previous_avg = stats_lock.udp_avg_scrape_processing_time_ns; + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_scrapes_handled; + + stats_lock.udp_avg_scrape_processing_time_ns = new_avg.ceil() as u64; + + drop(stats_lock); + } + pub async fn increase_udp6_requests(&self) { let mut stats_lock = self.stats.write().await; stats_lock.udp6_requests += 1; diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index 814f94b21..c6a526a7d 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -34,13 +34,21 @@ pub struct Stats { /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. pub tcp6_scrapes_handled: u64, + // UDP /// Total number of UDP (UDP tracker) requests aborted. pub udp_requests_aborted: u64, /// Total number of UDP (UDP tracker) requests banned. pub udp_requests_banned: u64, /// Total number of IPs banned for UDP (UDP tracker) requests. pub udp_banned_ips_total: u64, + /// Average rounded time spent processing UDP connect requests. + pub udp_avg_connect_processing_time_ns: u64, + /// Average rounded time spent processing UDP announce requests. + pub udp_avg_announce_processing_time_ns: u64, + /// Average rounded time spent processing UDP scrape requests. + pub udp_avg_scrape_processing_time_ns: u64, + // UDPv4 /// Total number of UDP (UDP tracker) requests from IPv4 peers. pub udp4_requests: u64, /// Total number of UDP (UDP tracker) connections from IPv4 peers. @@ -54,6 +62,7 @@ pub struct Stats { /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. pub udp4_errors_handled: u64, + // UDPv6 /// Total number of UDP (UDP tracker) requests from IPv6 peers. pub udp6_requests: u64, /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. @@ -86,12 +95,17 @@ impl From for Stats { udp_requests_aborted: metrics.protocol_metrics.udp_requests_aborted, udp_requests_banned: metrics.protocol_metrics.udp_requests_banned, udp_banned_ips_total: metrics.protocol_metrics.udp_banned_ips_total, + udp_avg_connect_processing_time_ns: metrics.protocol_metrics.udp_avg_connect_processing_time_ns, + udp_avg_announce_processing_time_ns: metrics.protocol_metrics.udp_avg_announce_processing_time_ns, + udp_avg_scrape_processing_time_ns: metrics.protocol_metrics.udp_avg_scrape_processing_time_ns, + // UDPv4 udp4_requests: metrics.protocol_metrics.udp4_requests, udp4_connections_handled: metrics.protocol_metrics.udp4_connections_handled, udp4_announces_handled: metrics.protocol_metrics.udp4_announces_handled, udp4_scrapes_handled: metrics.protocol_metrics.udp4_scrapes_handled, udp4_responses: metrics.protocol_metrics.udp4_responses, udp4_errors_handled: metrics.protocol_metrics.udp4_errors_handled, + // UDPv6 udp6_requests: metrics.protocol_metrics.udp6_requests, udp6_connections_handled: metrics.protocol_metrics.udp6_connections_handled, udp6_announces_handled: metrics.protocol_metrics.udp6_announces_handled, @@ -132,18 +146,23 @@ mod tests { udp_requests_aborted: 11, udp_requests_banned: 12, udp_banned_ips_total: 13, - udp4_requests: 14, - udp4_connections_handled: 15, - udp4_announces_handled: 16, - udp4_scrapes_handled: 17, - udp4_responses: 18, - udp4_errors_handled: 19, - udp6_requests: 20, - udp6_connections_handled: 21, - udp6_announces_handled: 22, - udp6_scrapes_handled: 23, - udp6_responses: 24, - udp6_errors_handled: 25 + udp_avg_connect_processing_time_ns: 14, + udp_avg_announce_processing_time_ns: 15, + udp_avg_scrape_processing_time_ns: 16, + // UDPv4 + udp4_requests: 17, + udp4_connections_handled: 18, + udp4_announces_handled: 19, + udp4_scrapes_handled: 20, + udp4_responses: 21, + udp4_errors_handled: 22, + // UDPv6 + udp6_requests: 23, + udp6_connections_handled: 24, + udp6_announces_handled: 25, + udp6_scrapes_handled: 26, + udp6_responses: 27, + udp6_errors_handled: 28 } }), Stats { @@ -151,10 +170,11 @@ mod tests { seeders: 1, completed: 2, leechers: 3, - // TCP + // TCPv4 tcp4_connections_handled: 5, tcp4_announces_handled: 6, tcp4_scrapes_handled: 7, + // TCPv6 tcp6_connections_handled: 8, tcp6_announces_handled: 9, tcp6_scrapes_handled: 10, @@ -162,18 +182,23 @@ mod tests { udp_requests_aborted: 11, udp_requests_banned: 12, udp_banned_ips_total: 13, - udp4_requests: 14, - udp4_connections_handled: 15, - udp4_announces_handled: 16, - udp4_scrapes_handled: 17, - udp4_responses: 18, - udp4_errors_handled: 19, - udp6_requests: 20, - udp6_connections_handled: 21, - udp6_announces_handled: 22, - udp6_scrapes_handled: 23, - udp6_responses: 24, - udp6_errors_handled: 25 + udp_avg_connect_processing_time_ns: 14, + udp_avg_announce_processing_time_ns: 15, + udp_avg_scrape_processing_time_ns: 16, + // UDPv4 + udp4_requests: 17, + udp4_connections_handled: 18, + udp4_announces_handled: 19, + udp4_scrapes_handled: 20, + udp4_responses: 21, + udp4_errors_handled: 22, + // UDPv6 + udp6_requests: 23, + udp6_connections_handled: 24, + udp6_announces_handled: 25, + udp6_scrapes_handled: 26, + udp6_responses: 27, + udp6_errors_handled: 28 } ); } diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index 6b214d0c9..a67b5328a 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -21,6 +21,10 @@ pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { lines.push(format!("completed {}", tracker_metrics.torrents_metrics.downloaded)); lines.push(format!("leechers {}", tracker_metrics.torrents_metrics.incomplete)); + // TCP + + // TCPv4 + lines.push(format!( "tcp4_connections_handled {}", tracker_metrics.protocol_metrics.tcp4_connections_handled @@ -34,6 +38,8 @@ pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { tracker_metrics.protocol_metrics.tcp4_scrapes_handled )); + // TCPv6 + lines.push(format!( "tcp6_connections_handled {}", tracker_metrics.protocol_metrics.tcp6_connections_handled @@ -47,10 +53,34 @@ pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { tracker_metrics.protocol_metrics.tcp6_scrapes_handled )); + // UDP + lines.push(format!( "udp_requests_aborted {}", tracker_metrics.protocol_metrics.udp_requests_aborted )); + lines.push(format!( + "udp_requests_banned {}", + tracker_metrics.protocol_metrics.udp_requests_banned + )); + lines.push(format!( + "udp_banned_ips_total {}", + tracker_metrics.protocol_metrics.udp_banned_ips_total + )); + lines.push(format!( + "udp_avg_connect_processing_time_ns {}", + tracker_metrics.protocol_metrics.udp_avg_connect_processing_time_ns + )); + lines.push(format!( + "udp_avg_announce_processing_time_ns {}", + tracker_metrics.protocol_metrics.udp_avg_announce_processing_time_ns + )); + lines.push(format!( + "udp_avg_scrape_processing_time_ns {}", + tracker_metrics.protocol_metrics.udp_avg_scrape_processing_time_ns + )); + + // UDPv4 lines.push(format!("udp4_requests {}", tracker_metrics.protocol_metrics.udp4_requests)); lines.push(format!( @@ -71,6 +101,8 @@ pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { tracker_metrics.protocol_metrics.udp4_errors_handled )); + // UDPv6 + lines.push(format!("udp6_requests {}", tracker_metrics.protocol_metrics.udp6_requests)); lines.push(format!( "udp6_connections_handled {}", diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index e99333d7a..bc6e495a3 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -47,12 +47,17 @@ async fn should_allow_getting_tracker_statistics() { udp_requests_aborted: 0, udp_requests_banned: 0, udp_banned_ips_total: 0, + udp_avg_connect_processing_time_ns: 0, + udp_avg_announce_processing_time_ns: 0, + udp_avg_scrape_processing_time_ns: 0, + // UDPv4 udp4_requests: 0, udp4_connections_handled: 0, udp4_announces_handled: 0, udp4_scrapes_handled: 0, udp4_responses: 0, udp4_errors_handled: 0, + // UDPv6 udp6_requests: 0, udp6_connections_handled: 0, udp6_announces_handled: 0, From a1ded65db45548ccdc9249debd2593fd542b9725 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 10 Jan 2025 12:43:34 +0000 Subject: [PATCH 0575/1297] feat: [#1159] extract new package tracker api client --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 10 + Cargo.toml | 3 +- packages/tracker-api-client/Cargo.toml | 21 ++ packages/tracker-api-client/README.md | 23 +++ .../docs/licenses/LICENSE-MIT_0 | 14 ++ .../tracker-api-client/src/common/http.rs | 57 ++++++ packages/tracker-api-client/src/common/mod.rs | 1 + .../tracker-api-client/src/connection_info.rs | 33 ++++ packages/tracker-api-client/src/lib.rs | 3 + packages/tracker-api-client/src/v1/client.rs | 179 ++++++++++++++++++ packages/tracker-api-client/src/v1/mod.rs | 1 + 12 files changed, 345 insertions(+), 1 deletion(-) create mode 100644 packages/tracker-api-client/Cargo.toml create mode 100644 packages/tracker-api-client/README.md create mode 100644 packages/tracker-api-client/docs/licenses/LICENSE-MIT_0 create mode 100644 packages/tracker-api-client/src/common/http.rs create mode 100644 packages/tracker-api-client/src/common/mod.rs create mode 100644 packages/tracker-api-client/src/connection_info.rs create mode 100644 packages/tracker-api-client/src/lib.rs create mode 100644 packages/tracker-api-client/src/v1/client.rs create mode 100644 packages/tracker-api-client/src/v1/mod.rs diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 1e0f59b43..fd4e0fd5c 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -58,6 +58,7 @@ jobs: cargo publish -p bittorrent-http-protocol cargo publish -p bittorrent-tracker-client cargo publish -p torrust-tracker + cargo publish -p torrust-tracker-api-client cargo publish -p torrust-tracker-client cargo publish -p torrust-tracker-clock cargo publish -p torrust-tracker-configuration diff --git a/Cargo.lock b/Cargo.lock index 68e32ddbd..3b0cc9093 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3990,6 +3990,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "torrust-tracker-api-client" +version = "3.0.0-develop" +dependencies = [ + "hyper", + "reqwest", + "serde", + "uuid", +] + [[package]] name = "torrust-tracker-client" version = "3.0.0-develop" diff --git a/Cargo.toml b/Cargo.toml index f1ae96dad..e57016596 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ rust-version.workspace = true version.workspace = true [lib] -name = "torrust_tracker_lib" +name = "torrust_tracker_lib" [workspace.package] authors = ["Nautilus Cyberneering , Mick van Dijke "] @@ -108,6 +108,7 @@ members = [ "packages/primitives", "packages/test-helpers", "packages/torrent-repository", + "packages/tracker-api-client", "packages/tracker-client", ] diff --git a/packages/tracker-api-client/Cargo.toml b/packages/tracker-api-client/Cargo.toml new file mode 100644 index 000000000..388ad4bd2 --- /dev/null +++ b/packages/tracker-api-client/Cargo.toml @@ -0,0 +1,21 @@ +[package] +description = "A library to interact with the Torrust Tracker REST API." +keywords = ["bittorrent", "client", "tracker"] +license = "LGPL-3.0" +name = "torrust-tracker-api-client" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +hyper = "1" +reqwest = { version = "0", features = ["json"] } +serde = { version = "1", features = ["derive"] } +uuid = { version = "1", features = ["v4"] } diff --git a/packages/tracker-api-client/README.md b/packages/tracker-api-client/README.md new file mode 100644 index 000000000..3c10cdb5c --- /dev/null +++ b/packages/tracker-api-client/README.md @@ -0,0 +1,23 @@ +# Torrust Tracker API Client + +A library to interact with the Torrust Tracker REST API. + +## License + +**Copyright (c) 2024 The Torrust Developers.** + +This program is free software: you can redistribute it and/or modify it under the terms of the [GNU Lesser General Public License][LGPL_3_0] as published by the [Free Software Foundation][FSF], version 3. + +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the [GNU Lesser General Public License][LGPL_3_0] for more details. + +You should have received a copy of the *GNU Lesser General Public License* along with this program. If not, see . + +Some files include explicit copyright notices and/or license notices. + +### Legacy Exception + +For prosperity, versions of Torrust BitTorrent Tracker Client that are older than five years are automatically granted the [MIT-0][MIT_0] license in addition to the existing [LGPL-3.0-only][LGPL_3_0] license. + +[LGPL_3_0]: ./LICENSE +[MIT_0]: ./docs/licenses/LICENSE-MIT_0 +[FSF]: https://www.fsf.org/ diff --git a/packages/tracker-api-client/docs/licenses/LICENSE-MIT_0 b/packages/tracker-api-client/docs/licenses/LICENSE-MIT_0 new file mode 100644 index 000000000..fc06cc4fe --- /dev/null +++ b/packages/tracker-api-client/docs/licenses/LICENSE-MIT_0 @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/tracker-api-client/src/common/http.rs b/packages/tracker-api-client/src/common/http.rs new file mode 100644 index 000000000..adbc7dc15 --- /dev/null +++ b/packages/tracker-api-client/src/common/http.rs @@ -0,0 +1,57 @@ +pub type ReqwestQuery = Vec; +pub type ReqwestQueryParam = (String, String); + +/// URL Query component +#[derive(Default, Debug)] +pub struct Query { + params: Vec, +} + +impl Query { + #[must_use] + pub fn empty() -> Self { + Self { params: vec![] } + } + + #[must_use] + pub fn params(params: Vec) -> Self { + Self { params } + } + + pub fn add_param(&mut self, param: QueryParam) { + self.params.push(param); + } +} + +impl From for ReqwestQuery { + fn from(url_search_params: Query) -> Self { + url_search_params + .params + .iter() + .map(|param| ReqwestQueryParam::from((*param).clone())) + .collect() + } +} + +/// URL query param +#[derive(Clone, Debug)] +pub struct QueryParam { + name: String, + value: String, +} + +impl QueryParam { + #[must_use] + pub fn new(name: &str, value: &str) -> Self { + Self { + name: name.to_string(), + value: value.to_string(), + } + } +} + +impl From for ReqwestQueryParam { + fn from(param: QueryParam) -> Self { + (param.name, param.value) + } +} diff --git a/packages/tracker-api-client/src/common/mod.rs b/packages/tracker-api-client/src/common/mod.rs new file mode 100644 index 000000000..3883215fc --- /dev/null +++ b/packages/tracker-api-client/src/common/mod.rs @@ -0,0 +1 @@ +pub mod http; diff --git a/packages/tracker-api-client/src/connection_info.rs b/packages/tracker-api-client/src/connection_info.rs new file mode 100644 index 000000000..32eeda686 --- /dev/null +++ b/packages/tracker-api-client/src/connection_info.rs @@ -0,0 +1,33 @@ +#[must_use] +pub fn connection_with_invalid_token(bind_address: &str) -> ConnectionInfo { + ConnectionInfo::authenticated(bind_address, "invalid token") +} + +#[must_use] +pub fn connection_with_no_token(bind_address: &str) -> ConnectionInfo { + ConnectionInfo::anonymous(bind_address) +} + +#[derive(Clone)] +pub struct ConnectionInfo { + pub bind_address: String, + pub api_token: Option, +} + +impl ConnectionInfo { + #[must_use] + pub fn authenticated(bind_address: &str, api_token: &str) -> Self { + Self { + bind_address: bind_address.to_string(), + api_token: Some(api_token.to_string()), + } + } + + #[must_use] + pub fn anonymous(bind_address: &str) -> Self { + Self { + bind_address: bind_address.to_string(), + api_token: None, + } + } +} diff --git a/packages/tracker-api-client/src/lib.rs b/packages/tracker-api-client/src/lib.rs new file mode 100644 index 000000000..baf80e3cd --- /dev/null +++ b/packages/tracker-api-client/src/lib.rs @@ -0,0 +1,3 @@ +pub mod common; +pub mod connection_info; +pub mod v1; diff --git a/packages/tracker-api-client/src/v1/client.rs b/packages/tracker-api-client/src/v1/client.rs new file mode 100644 index 000000000..b5c0dc60b --- /dev/null +++ b/packages/tracker-api-client/src/v1/client.rs @@ -0,0 +1,179 @@ +use hyper::HeaderMap; +use reqwest::Response; +use serde::Serialize; +use uuid::Uuid; + +use crate::common::http::{Query, QueryParam, ReqwestQuery}; +use crate::connection_info::ConnectionInfo; + +/// API Client +pub struct Client { + connection_info: ConnectionInfo, + base_path: String, +} + +impl Client { + #[must_use] + pub fn new(connection_info: ConnectionInfo) -> Self { + Self { + connection_info, + base_path: "/api/v1/".to_string(), + } + } + + pub async fn generate_auth_key(&self, seconds_valid: i32, headers: Option) -> Response { + self.post_empty(&format!("key/{}", &seconds_valid), headers).await + } + + pub async fn add_auth_key(&self, add_key_form: AddKeyForm, headers: Option) -> Response { + self.post_form("keys", &add_key_form, headers).await + } + + pub async fn delete_auth_key(&self, key: &str, headers: Option) -> Response { + self.delete(&format!("key/{}", &key), headers).await + } + + pub async fn reload_keys(&self, headers: Option) -> Response { + self.get("keys/reload", Query::default(), headers).await + } + + pub async fn whitelist_a_torrent(&self, info_hash: &str, headers: Option) -> Response { + self.post_empty(&format!("whitelist/{}", &info_hash), headers).await + } + + pub async fn remove_torrent_from_whitelist(&self, info_hash: &str, headers: Option) -> Response { + self.delete(&format!("whitelist/{}", &info_hash), headers).await + } + + pub async fn reload_whitelist(&self, headers: Option) -> Response { + self.get("whitelist/reload", Query::default(), headers).await + } + + pub async fn get_torrent(&self, info_hash: &str, headers: Option) -> Response { + self.get(&format!("torrent/{}", &info_hash), Query::default(), headers).await + } + + pub async fn get_torrents(&self, params: Query, headers: Option) -> Response { + self.get("torrents", params, headers).await + } + + pub async fn get_tracker_statistics(&self, headers: Option) -> Response { + self.get("stats", Query::default(), headers).await + } + + pub async fn get(&self, path: &str, params: Query, headers: Option) -> Response { + let mut query: Query = params; + + if let Some(token) = &self.connection_info.api_token { + query.add_param(QueryParam::new("token", token)); + }; + + self.get_request_with_query(path, query, headers).await + } + + /// # Panics + /// + /// Will panic if the request can't be sent + pub async fn post_empty(&self, path: &str, headers: Option) -> Response { + let builder = reqwest::Client::new() + .post(self.base_url(path).clone()) + .query(&ReqwestQuery::from(self.query_with_token())); + + let builder = match headers { + Some(headers) => builder.headers(headers), + None => builder, + }; + + builder.send().await.unwrap() + } + + /// # Panics + /// + /// Will panic if the request can't be sent + pub async fn post_form(&self, path: &str, form: &T, headers: Option) -> Response { + let builder = reqwest::Client::new() + .post(self.base_url(path).clone()) + .query(&ReqwestQuery::from(self.query_with_token())) + .json(&form); + + let builder = match headers { + Some(headers) => builder.headers(headers), + None => builder, + }; + + builder.send().await.unwrap() + } + + /// # Panics + /// + /// Will panic if the request can't be sent + async fn delete(&self, path: &str, headers: Option) -> Response { + let builder = reqwest::Client::new() + .delete(self.base_url(path).clone()) + .query(&ReqwestQuery::from(self.query_with_token())); + + let builder = match headers { + Some(headers) => builder.headers(headers), + None => builder, + }; + + builder.send().await.unwrap() + } + + pub async fn get_request_with_query(&self, path: &str, params: Query, headers: Option) -> Response { + get(&self.base_url(path), Some(params), headers).await + } + + pub async fn get_request(&self, path: &str) -> Response { + get(&self.base_url(path), None, None).await + } + + fn query_with_token(&self) -> Query { + match &self.connection_info.api_token { + Some(token) => Query::params([QueryParam::new("token", token)].to_vec()), + None => Query::default(), + } + } + + fn base_url(&self, path: &str) -> String { + format!("http://{}{}{path}", &self.connection_info.bind_address, &self.base_path) + } +} + +/// # Panics +/// +/// Will panic if the request can't be sent +pub async fn get(path: &str, query: Option, headers: Option) -> Response { + let builder = reqwest::Client::builder().build().unwrap(); + + let builder = match query { + Some(params) => builder.get(path).query(&ReqwestQuery::from(params)), + None => builder.get(path), + }; + + let builder = match headers { + Some(headers) => builder.headers(headers), + None => builder, + }; + + builder.send().await.unwrap() +} + +/// Returns a `HeaderMap` with a request id header +/// +/// # Panics +/// +/// Will panic if the request ID can't be parsed into a string. +#[must_use] +pub fn headers_with_request_id(request_id: Uuid) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert("x-request-id", request_id.to_string().parse().unwrap()); + headers +} + +#[derive(Serialize, Debug)] +pub struct AddKeyForm { + #[serde(rename = "key")] + pub opt_key: Option, + pub seconds_valid: Option, +} diff --git a/packages/tracker-api-client/src/v1/mod.rs b/packages/tracker-api-client/src/v1/mod.rs new file mode 100644 index 000000000..b9babe5bc --- /dev/null +++ b/packages/tracker-api-client/src/v1/mod.rs @@ -0,0 +1 @@ +pub mod client; From e4b9875e18ebeb6d12d33b19b6a478c262e563e4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 10 Jan 2025 16:03:29 +0000 Subject: [PATCH 0576/1297] refactor: [#1159] use new tracker api client package in tests The Tracker API client was extracted into a new package. This removes the duplicate client in tests and starts using the new package. --- Cargo.lock | 1 + Cargo.toml | 1 + .../tracker-api-client/src/connection_info.rs | 10 -- tests/servers/api/connection_info.rs | 24 +-- tests/servers/api/environment.rs | 3 +- tests/servers/api/v1/client.rs | 161 ------------------ .../servers/api/v1/contract/authentication.rs | 4 +- .../api/v1/contract/context/auth_key.rs | 4 +- .../api/v1/contract/context/health_check.rs | 2 +- .../servers/api/v1/contract/context/stats.rs | 2 +- .../api/v1/contract/context/torrent.rs | 4 +- .../api/v1/contract/context/whitelist.rs | 2 +- tests/servers/api/v1/mod.rs | 1 - 13 files changed, 14 insertions(+), 205 deletions(-) delete mode 100644 tests/servers/api/v1/client.rs diff --git a/Cargo.lock b/Cargo.lock index 3b0cc9093..a8b23465a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3974,6 +3974,7 @@ dependencies = [ "serde_with", "thiserror 2.0.9", "tokio", + "torrust-tracker-api-client", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-contrib-bencode", diff --git a/Cargo.toml b/Cargo.toml index e57016596..0bf3e39e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -97,6 +97,7 @@ ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_byt [dev-dependencies] local-ip-address = "0" mockall = "0" +torrust-tracker-api-client = { version = "3.0.0-develop", path = "packages/tracker-api-client" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "packages/test-helpers" } [workspace] diff --git a/packages/tracker-api-client/src/connection_info.rs b/packages/tracker-api-client/src/connection_info.rs index 32eeda686..5785f98e6 100644 --- a/packages/tracker-api-client/src/connection_info.rs +++ b/packages/tracker-api-client/src/connection_info.rs @@ -1,13 +1,3 @@ -#[must_use] -pub fn connection_with_invalid_token(bind_address: &str) -> ConnectionInfo { - ConnectionInfo::authenticated(bind_address, "invalid token") -} - -#[must_use] -pub fn connection_with_no_token(bind_address: &str) -> ConnectionInfo { - ConnectionInfo::anonymous(bind_address) -} - #[derive(Clone)] pub struct ConnectionInfo { pub bind_address: String, diff --git a/tests/servers/api/connection_info.rs b/tests/servers/api/connection_info.rs index 35314a2fd..1ae08921a 100644 --- a/tests/servers/api/connection_info.rs +++ b/tests/servers/api/connection_info.rs @@ -1,3 +1,5 @@ +use torrust_tracker_api_client::connection_info::ConnectionInfo; + pub fn connection_with_invalid_token(bind_address: &str) -> ConnectionInfo { ConnectionInfo::authenticated(bind_address, "invalid token") } @@ -5,25 +7,3 @@ pub fn connection_with_invalid_token(bind_address: &str) -> ConnectionInfo { pub fn connection_with_no_token(bind_address: &str) -> ConnectionInfo { ConnectionInfo::anonymous(bind_address) } - -#[derive(Clone)] -pub struct ConnectionInfo { - pub bind_address: String, - pub api_token: Option, -} - -impl ConnectionInfo { - pub fn authenticated(bind_address: &str, api_token: &str) -> Self { - Self { - bind_address: bind_address.to_string(), - api_token: Some(api_token.to_string()), - } - } - - pub fn anonymous(bind_address: &str) -> Self { - Self { - bind_address: bind_address.to_string(), - api_token: None, - } - } -} diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 00fb9d05b..c4f503f9c 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; use tokio::sync::RwLock; +use torrust_tracker_api_client::connection_info::ConnectionInfo; use torrust_tracker_configuration::{Configuration, HttpApi}; use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; @@ -14,8 +15,6 @@ use torrust_tracker_lib::servers::udp::server::banning::BanService; use torrust_tracker_lib::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use torrust_tracker_primitives::peer; -use super::connection_info::ConnectionInfo; - pub struct Environment where S: std::fmt::Debug + std::fmt::Display, diff --git a/tests/servers/api/v1/client.rs b/tests/servers/api/v1/client.rs deleted file mode 100644 index 635331078..000000000 --- a/tests/servers/api/v1/client.rs +++ /dev/null @@ -1,161 +0,0 @@ -use hyper::HeaderMap; -use reqwest::Response; -use serde::Serialize; -use uuid::Uuid; - -use crate::common::http::{Query, QueryParam, ReqwestQuery}; -use crate::servers::api::connection_info::ConnectionInfo; - -/// API Client -pub struct Client { - connection_info: ConnectionInfo, - base_path: String, -} - -impl Client { - pub fn new(connection_info: ConnectionInfo) -> Self { - Self { - connection_info, - base_path: "/api/v1/".to_string(), - } - } - - pub async fn generate_auth_key(&self, seconds_valid: i32, headers: Option) -> Response { - self.post_empty(&format!("key/{}", &seconds_valid), headers).await - } - - pub async fn add_auth_key(&self, add_key_form: AddKeyForm, headers: Option) -> Response { - self.post_form("keys", &add_key_form, headers).await - } - - pub async fn delete_auth_key(&self, key: &str, headers: Option) -> Response { - self.delete(&format!("key/{}", &key), headers).await - } - - pub async fn reload_keys(&self, headers: Option) -> Response { - self.get("keys/reload", Query::default(), headers).await - } - - pub async fn whitelist_a_torrent(&self, info_hash: &str, headers: Option) -> Response { - self.post_empty(&format!("whitelist/{}", &info_hash), headers).await - } - - pub async fn remove_torrent_from_whitelist(&self, info_hash: &str, headers: Option) -> Response { - self.delete(&format!("whitelist/{}", &info_hash), headers).await - } - - pub async fn reload_whitelist(&self, headers: Option) -> Response { - self.get("whitelist/reload", Query::default(), headers).await - } - - pub async fn get_torrent(&self, info_hash: &str, headers: Option) -> Response { - self.get(&format!("torrent/{}", &info_hash), Query::default(), headers).await - } - - pub async fn get_torrents(&self, params: Query, headers: Option) -> Response { - self.get("torrents", params, headers).await - } - - pub async fn get_tracker_statistics(&self, headers: Option) -> Response { - self.get("stats", Query::default(), headers).await - } - - pub async fn get(&self, path: &str, params: Query, headers: Option) -> Response { - let mut query: Query = params; - - if let Some(token) = &self.connection_info.api_token { - query.add_param(QueryParam::new("token", token)); - }; - - self.get_request_with_query(path, query, headers).await - } - - pub async fn post_empty(&self, path: &str, headers: Option) -> Response { - let builder = reqwest::Client::new() - .post(self.base_url(path).clone()) - .query(&ReqwestQuery::from(self.query_with_token())); - - let builder = match headers { - Some(headers) => builder.headers(headers), - None => builder, - }; - - builder.send().await.unwrap() - } - - pub async fn post_form(&self, path: &str, form: &T, headers: Option) -> Response { - let builder = reqwest::Client::new() - .post(self.base_url(path).clone()) - .query(&ReqwestQuery::from(self.query_with_token())) - .json(&form); - - let builder = match headers { - Some(headers) => builder.headers(headers), - None => builder, - }; - - builder.send().await.unwrap() - } - - async fn delete(&self, path: &str, headers: Option) -> Response { - let builder = reqwest::Client::new() - .delete(self.base_url(path).clone()) - .query(&ReqwestQuery::from(self.query_with_token())); - - let builder = match headers { - Some(headers) => builder.headers(headers), - None => builder, - }; - - builder.send().await.unwrap() - } - - pub async fn get_request_with_query(&self, path: &str, params: Query, headers: Option) -> Response { - get(&self.base_url(path), Some(params), headers).await - } - - pub async fn get_request(&self, path: &str) -> Response { - get(&self.base_url(path), None, None).await - } - - fn query_with_token(&self) -> Query { - match &self.connection_info.api_token { - Some(token) => Query::params([QueryParam::new("token", token)].to_vec()), - None => Query::default(), - } - } - - fn base_url(&self, path: &str) -> String { - format!("http://{}{}{path}", &self.connection_info.bind_address, &self.base_path) - } -} - -pub async fn get(path: &str, query: Option, headers: Option) -> Response { - let builder = reqwest::Client::builder().build().unwrap(); - - let builder = match query { - Some(params) => builder.get(path).query(&ReqwestQuery::from(params)), - None => builder.get(path), - }; - - let builder = match headers { - Some(headers) => builder.headers(headers), - None => builder, - }; - - builder.send().await.unwrap() -} - -/// Returns a `HeaderMap` with a request id header -pub fn headers_with_request_id(request_id: Uuid) -> HeaderMap { - let mut headers = HeaderMap::new(); - headers.insert("x-request-id", request_id.to_string().parse().unwrap()); - headers -} - -#[derive(Serialize, Debug)] -pub struct AddKeyForm { - #[serde(rename = "key")] - pub opt_key: Option, - pub seconds_valid: Option, -} diff --git a/tests/servers/api/v1/contract/authentication.rs b/tests/servers/api/v1/contract/authentication.rs index 4e0cf49da..6cb1e52b9 100644 --- a/tests/servers/api/v1/contract/authentication.rs +++ b/tests/servers/api/v1/contract/authentication.rs @@ -1,10 +1,10 @@ +use torrust_tracker_api_client::common::http::{Query, QueryParam}; +use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; -use crate::common::http::{Query, QueryParam}; use crate::common::logging::{self, logs_contains_a_line_with}; use crate::servers::api::v1::asserts::{assert_token_not_valid, assert_unauthorized}; -use crate::servers::api::v1::client::{headers_with_request_id, Client}; use crate::servers::api::Started; #[tokio::test] diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 4dc039a9b..b143f6659 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -1,6 +1,7 @@ use std::time::Duration; use serde::Serialize; +use torrust_tracker_api_client::v1::client::{headers_with_request_id, AddKeyForm, Client}; use torrust_tracker_lib::core::auth::Key; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; @@ -12,7 +13,6 @@ use crate::servers::api::v1::asserts::{ assert_invalid_auth_key_get_param, assert_invalid_auth_key_post_param, assert_ok, assert_token_not_valid, assert_unauthorized, assert_unprocessable_auth_key_duration_param, }; -use crate::servers::api::v1::client::{headers_with_request_id, AddKeyForm, Client}; use crate::servers::api::{force_database_error, Started}; #[tokio::test] @@ -462,6 +462,7 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { mod deprecated_generate_key_endpoint { + use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_lib::core::auth::Key; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; @@ -472,7 +473,6 @@ mod deprecated_generate_key_endpoint { assert_auth_key_utf8, assert_failed_to_generate_key, assert_invalid_key_duration_param, assert_token_not_valid, assert_unauthorized, }; - use crate::servers::api::v1::client::{headers_with_request_id, Client}; use crate::servers::api::{force_database_error, Started}; #[tokio::test] diff --git a/tests/servers/api/v1/contract/context/health_check.rs b/tests/servers/api/v1/contract/context/health_check.rs index 32228575d..4c3509c66 100644 --- a/tests/servers/api/v1/contract/context/health_check.rs +++ b/tests/servers/api/v1/contract/context/health_check.rs @@ -1,8 +1,8 @@ +use torrust_tracker_api_client::v1::client::get; use torrust_tracker_lib::servers::apis::v1::context::health_check::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; -use crate::servers::api::v1::client::get; use crate::servers::api::Started; #[tokio::test] diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index bc6e495a3..4a36e2561 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -1,6 +1,7 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_lib::servers::apis::v1::context::stats::resources::Stats; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; @@ -9,7 +10,6 @@ use uuid::Uuid; use crate::common::logging::{self, logs_contains_a_line_with}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{assert_stats, assert_token_not_valid, assert_unauthorized}; -use crate::servers::api::v1::client::{headers_with_request_id, Client}; use crate::servers::api::Started; #[tokio::test] diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index 260fe4a3a..c5d8e2547 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -1,20 +1,20 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_api_client::common::http::{Query, QueryParam}; +use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_lib::servers::apis::v1::context::torrent::resources::peer::Peer; use torrust_tracker_lib::servers::apis::v1::context::torrent::resources::torrent::{self, Torrent}; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; -use crate::common::http::{Query, QueryParam}; use crate::common::logging::{self, logs_contains_a_line_with}; use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; use crate::servers::api::v1::asserts::{ assert_bad_request, assert_invalid_infohash_param, assert_not_found, assert_token_not_valid, assert_torrent_info, assert_torrent_list, assert_torrent_not_known, assert_unauthorized, }; -use crate::servers::api::v1::client::{headers_with_request_id, Client}; use crate::servers::api::v1::contract::fixtures::{ invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found, }; diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index d0a80e968..360e057ec 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -1,6 +1,7 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; @@ -10,7 +11,6 @@ use crate::servers::api::v1::asserts::{ assert_failed_to_reload_whitelist, assert_failed_to_remove_torrent_from_whitelist, assert_failed_to_whitelist_torrent, assert_invalid_infohash_param, assert_not_found, assert_ok, assert_token_not_valid, assert_unauthorized, }; -use crate::servers::api::v1::client::{headers_with_request_id, Client}; use crate::servers::api::v1::contract::fixtures::{ invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found, }; diff --git a/tests/servers/api/v1/mod.rs b/tests/servers/api/v1/mod.rs index 37298b377..e2db6b4ce 100644 --- a/tests/servers/api/v1/mod.rs +++ b/tests/servers/api/v1/mod.rs @@ -1,3 +1,2 @@ pub mod asserts; -pub mod client; pub mod contract; From aa7ffdf20c8f89a563cca2db19be516a7f103d85 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 10 Jan 2025 17:11:09 +0000 Subject: [PATCH 0577/1297] refactor: [#1159] API client. Extract Origin type Instead of using a plain string we now use a Origin type containing hte base URL for the API without path or fragments. ``` scheme://host:port/ ``` --- Cargo.lock | 2 + packages/tracker-api-client/Cargo.toml | 2 + .../tracker-api-client/src/connection_info.rs | 145 +++++++++++++++++- packages/tracker-api-client/src/v1/client.rs | 13 +- tests/servers/api/connection_info.rs | 10 +- tests/servers/api/environment.rs | 6 +- .../api/v1/contract/context/auth_key.rs | 16 +- .../api/v1/contract/context/health_check.rs | 5 +- .../servers/api/v1/contract/context/stats.rs | 4 +- .../api/v1/contract/context/torrent.rs | 8 +- .../api/v1/contract/context/whitelist.rs | 8 +- 11 files changed, 179 insertions(+), 40 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a8b23465a..6e7a10116 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3998,6 +3998,8 @@ dependencies = [ "hyper", "reqwest", "serde", + "thiserror 2.0.9", + "url", "uuid", ] diff --git a/packages/tracker-api-client/Cargo.toml b/packages/tracker-api-client/Cargo.toml index 388ad4bd2..ee45e12f7 100644 --- a/packages/tracker-api-client/Cargo.toml +++ b/packages/tracker-api-client/Cargo.toml @@ -18,4 +18,6 @@ version.workspace = true hyper = "1" reqwest = { version = "0", features = ["json"] } serde = { version = "1", features = ["derive"] } +thiserror = "2" +url = { version = "2", features = ["serde"] } uuid = { version = "1", features = ["v4"] } diff --git a/packages/tracker-api-client/src/connection_info.rs b/packages/tracker-api-client/src/connection_info.rs index 5785f98e6..1224527ae 100644 --- a/packages/tracker-api-client/src/connection_info.rs +++ b/packages/tracker-api-client/src/connection_info.rs @@ -1,23 +1,154 @@ +use std::str::FromStr; + +use thiserror::Error; +use url::Url; + #[derive(Clone)] pub struct ConnectionInfo { - pub bind_address: String, + pub origin: Origin, pub api_token: Option, } impl ConnectionInfo { #[must_use] - pub fn authenticated(bind_address: &str, api_token: &str) -> Self { + pub fn authenticated(origin: Origin, api_token: &str) -> Self { Self { - bind_address: bind_address.to_string(), + origin, api_token: Some(api_token.to_string()), } } #[must_use] - pub fn anonymous(bind_address: &str) -> Self { - Self { - bind_address: bind_address.to_string(), - api_token: None, + pub fn anonymous(origin: Origin) -> Self { + Self { origin, api_token: None } + } +} + +/// Represents the origin of a HTTP request. +/// +/// The format of the origin is a URL, but only the scheme, host, and port are used. +/// +/// Pattern: `scheme://host:port/` +#[derive(Debug, Clone)] +pub struct Origin { + url: Url, +} + +#[derive(Debug, Error)] +pub enum OriginError { + #[error("Invalid URL: {0}")] + InvalidUrl(#[from] url::ParseError), + + #[error("URL is missing scheme or host")] + InvalidOrigin, + + #[error("Invalid URL scheme, only http and https are supported")] + InvalidScheme, +} + +impl FromStr for Origin { + type Err = OriginError; + + fn from_str(s: &str) -> Result { + let mut url = Url::parse(s).map_err(OriginError::InvalidUrl)?; + + // Ensure the URL has a scheme and host + if url.scheme().is_empty() || url.host().is_none() { + return Err(OriginError::InvalidOrigin); + } + + if url.scheme() != "http" && url.scheme() != "https" { + return Err(OriginError::InvalidScheme); + } + + // Retain only the origin components + url.set_path("/"); + url.set_query(None); + url.set_fragment(None); + + Ok(Origin { url }) + } +} + +impl std::fmt::Display for Origin { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.url) + } +} + +impl Origin { + /// # Errors + /// + /// Will return an error if the string is not a valid URL containing a + /// scheme and host. + pub fn new(s: &str) -> Result { + s.parse() + } + + #[must_use] + pub fn url(&self) -> &Url { + &self.url + } +} + +#[cfg(test)] +mod tests { + mod origin { + use crate::connection_info::Origin; + + #[test] + fn should_be_parsed_from_a_string_representing_a_url() { + let origin = Origin::new("https://example.com:8080/path?query#fragment").unwrap(); + + assert_eq!(origin.to_string(), "https://example.com:8080/"); + } + + mod when_parsing_from_url_string { + use crate::connection_info::Origin; + + #[test] + fn should_ignore_default_ports() { + let origin = Origin::new("http://example.com:80").unwrap(); // DevSkim: ignore DS137138 + assert_eq!(origin.to_string(), "http://example.com/"); // DevSkim: ignore DS137138 + + let origin = Origin::new("https://example.com:443").unwrap(); + assert_eq!(origin.to_string(), "https://example.com/"); + } + + #[test] + fn should_add_the_slash_after_the_host() { + let origin = Origin::new("https://example.com:1212").unwrap(); + + assert_eq!(origin.to_string(), "https://example.com:1212/"); + } + + #[test] + fn should_remove_extra_path_and_query_parameters() { + let origin = Origin::new("https://example.com:1212/path/to/resource?query=1#fragment").unwrap(); + + assert_eq!(origin.to_string(), "https://example.com:1212/"); + } + + #[test] + fn should_fail_when_the_scheme_is_missing() { + let result = Origin::new("example.com"); + + assert!(result.is_err()); + } + + #[test] + fn should_fail_when_the_scheme_is_not_supported() { + let result = Origin::new("udp://example.com"); + + assert!(result.is_err()); + } + + #[test] + fn should_fail_when_the_host_is_missing() { + let result = Origin::new("http://"); + + assert!(result.is_err()); + } } } } diff --git a/packages/tracker-api-client/src/v1/client.rs b/packages/tracker-api-client/src/v1/client.rs index b5c0dc60b..d48d4c008 100644 --- a/packages/tracker-api-client/src/v1/client.rs +++ b/packages/tracker-api-client/src/v1/client.rs @@ -1,6 +1,7 @@ use hyper::HeaderMap; use reqwest::Response; use serde::Serialize; +use url::Url; use uuid::Uuid; use crate::common::http::{Query, QueryParam, ReqwestQuery}; @@ -17,7 +18,7 @@ impl Client { pub fn new(connection_info: ConnectionInfo) -> Self { Self { connection_info, - base_path: "/api/v1/".to_string(), + base_path: "api/v1/".to_string(), } } @@ -121,11 +122,11 @@ impl Client { } pub async fn get_request_with_query(&self, path: &str, params: Query, headers: Option) -> Response { - get(&self.base_url(path), Some(params), headers).await + get(self.base_url(path), Some(params), headers).await } pub async fn get_request(&self, path: &str) -> Response { - get(&self.base_url(path), None, None).await + get(self.base_url(path), None, None).await } fn query_with_token(&self) -> Query { @@ -135,15 +136,15 @@ impl Client { } } - fn base_url(&self, path: &str) -> String { - format!("http://{}{}{path}", &self.connection_info.bind_address, &self.base_path) + fn base_url(&self, path: &str) -> Url { + Url::parse(&format!("{}{}{path}", &self.connection_info.origin, &self.base_path)).unwrap() } } /// # Panics /// /// Will panic if the request can't be sent -pub async fn get(path: &str, query: Option, headers: Option) -> Response { +pub async fn get(path: Url, query: Option, headers: Option) -> Response { let builder = reqwest::Client::builder().build().unwrap(); let builder = match query { diff --git a/tests/servers/api/connection_info.rs b/tests/servers/api/connection_info.rs index 1ae08921a..e78f4cbb7 100644 --- a/tests/servers/api/connection_info.rs +++ b/tests/servers/api/connection_info.rs @@ -1,9 +1,9 @@ -use torrust_tracker_api_client::connection_info::ConnectionInfo; +use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; -pub fn connection_with_invalid_token(bind_address: &str) -> ConnectionInfo { - ConnectionInfo::authenticated(bind_address, "invalid token") +pub fn connection_with_invalid_token(origin: Origin) -> ConnectionInfo { + ConnectionInfo::authenticated(origin, "invalid token") } -pub fn connection_with_no_token(bind_address: &str) -> ConnectionInfo { - ConnectionInfo::anonymous(bind_address) +pub fn connection_with_no_token(origin: Origin) -> ConnectionInfo { + ConnectionInfo::anonymous(origin) } diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index c4f503f9c..70f2d4c65 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; use tokio::sync::RwLock; -use torrust_tracker_api_client::connection_info::ConnectionInfo; +use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::{Configuration, HttpApi}; use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; @@ -92,8 +92,10 @@ impl Environment { } pub fn get_connection_info(&self) -> ConnectionInfo { + let origin = Origin::new(&format!("http://{}/", self.server.state.local_addr)).unwrap(); // DevSkim: ignore DS137138 + ConnectionInfo { - bind_address: self.server.state.local_addr.to_string(), + origin, api_token: self.config.access_tokens.get("admin").cloned(), } } diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index b143f6659..9b2e740c0 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -81,7 +81,7 @@ async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) .add_auth_key( AddKeyForm { opt_key: None, @@ -100,7 +100,7 @@ async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) .add_auth_key( AddKeyForm { opt_key: None, @@ -332,7 +332,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) .await; @@ -352,7 +352,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) .await; @@ -433,7 +433,7 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) .reload_keys(Some(headers_with_request_id(request_id))) .await; @@ -446,7 +446,7 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) .reload_keys(Some(headers_with_request_id(request_id))) .await; @@ -507,13 +507,13 @@ mod deprecated_generate_key_endpoint { let request_id = Uuid::new_v4(); let seconds_valid = 60; - let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) .generate_auth_key(seconds_valid, Some(headers_with_request_id(request_id))) .await; assert_token_not_valid(response).await; - let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) .generate_auth_key(seconds_valid, None) .await; diff --git a/tests/servers/api/v1/contract/context/health_check.rs b/tests/servers/api/v1/contract/context/health_check.rs index 4c3509c66..4d37917fc 100644 --- a/tests/servers/api/v1/contract/context/health_check.rs +++ b/tests/servers/api/v1/contract/context/health_check.rs @@ -1,6 +1,7 @@ use torrust_tracker_api_client::v1::client::get; use torrust_tracker_lib::servers::apis::v1::context::health_check::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; +use url::Url; use crate::common::logging; use crate::servers::api::Started; @@ -11,9 +12,9 @@ async fn health_check_endpoint_should_return_status_ok_if_api_is_running() { let env = Started::new(&configuration::ephemeral().into()).await; - let url = format!("http://{}/api/health_check", env.get_connection_info().bind_address); + let url = Url::parse(&format!("{}api/health_check", env.get_connection_info().origin)).unwrap(); - let response = get(&url, None, None).await; + let response = get(url, None, None).await; assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index 4a36e2561..2eda0ed4a 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -79,7 +79,7 @@ async fn should_not_allow_getting_tracker_statistics_for_unauthenticated_users() let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) .get_tracker_statistics(Some(headers_with_request_id(request_id))) .await; @@ -92,7 +92,7 @@ async fn should_not_allow_getting_tracker_statistics_for_unauthenticated_users() let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) .get_tracker_statistics(Some(headers_with_request_id(request_id))) .await; diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index c5d8e2547..76646db14 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -263,7 +263,7 @@ async fn should_not_allow_getting_torrents_for_unauthenticated_users() { let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) .get_torrents(Query::empty(), Some(headers_with_request_id(request_id))) .await; @@ -276,7 +276,7 @@ async fn should_not_allow_getting_torrents_for_unauthenticated_users() { let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) .get_torrents(Query::default(), Some(headers_with_request_id(request_id))) .await; @@ -382,7 +382,7 @@ async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) .await; @@ -395,7 +395,7 @@ async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) .await; diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index 360e057ec..6dde663a5 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -76,7 +76,7 @@ async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) .await; @@ -89,7 +89,7 @@ async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) .await; @@ -270,7 +270,7 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_invalid_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) .await; @@ -285,7 +285,7 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica let request_id = Uuid::new_v4(); - let response = Client::new(connection_with_no_token(env.get_connection_info().bind_address.as_str())) + let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) .await; From a7ceb0f135c6673ba8e7a8845f43facd626708a9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Sat, 11 Jan 2025 18:47:05 +0000 Subject: [PATCH 0578/1297] refactor: [#1140] move http tracker logic to http-protocol and primitives packages - Generic logic for http tracker has bben moved to http-protocol package (bittorrent-http-protocol crate). - Generic tracker types like AnnounceData and ScrapeData have been moved to the primitives package (torrust-tracker-primitives crate). This has also a desiderable side effect: generic re-usable domain logic has been decoupled from Axum framework. --- Cargo.lock | 11 +++- Cargo.toml | 2 - packages/http-protocol/Cargo.toml | 8 +++ packages/http-protocol/src/lib.rs | 1 + packages/http-protocol/src/v1/mod.rs | 4 ++ .../http-protocol/src}/v1/query.rs | 8 +-- .../src}/v1/requests/announce.rs | 14 ++--- .../http-protocol/src}/v1/requests/mod.rs | 0 .../http-protocol/src}/v1/requests/scrape.rs | 14 ++--- .../src}/v1/responses/announce.rs | 36 +++--------- .../http-protocol/src}/v1/responses/error.rs | 12 ++-- .../http-protocol/src/v1/responses/mod.rs | 9 +++ .../http-protocol/src}/v1/responses/scrape.rs | 17 ++---- packages/http-protocol/src/v1/services/mod.rs | 1 + .../src}/v1/services/peer_ip_resolver.rs | 4 +- packages/primitives/Cargo.toml | 1 + packages/primitives/src/core.rs | 58 +++++++++++++++++++ packages/primitives/src/lib.rs | 1 + src/core/error.rs | 9 +++ src/core/mod.rs | 52 +---------------- src/servers/http/mod.rs | 26 ++++----- .../http/v1/extractors/announce_request.rs | 18 +++--- .../http/v1/extractors/authentication_key.rs | 10 ++-- .../http/v1/extractors/client_ip_sources.rs | 3 +- .../http/v1/extractors/scrape_request.rs | 18 +++--- src/servers/http/v1/handlers/announce.rs | 33 ++++++----- src/servers/http/v1/handlers/common/auth.rs | 2 +- .../http/v1/handlers/common/peer_ip.rs | 16 +---- src/servers/http/v1/handlers/mod.rs | 11 ---- src/servers/http/v1/handlers/scrape.rs | 36 +++++++----- src/servers/http/v1/mod.rs | 3 - src/servers/http/v1/responses/mod.rs | 19 ------ src/servers/http/v1/services/announce.rs | 6 +- src/servers/http/v1/services/mod.rs | 1 - src/servers/http/v1/services/scrape.rs | 9 ++- 35 files changed, 235 insertions(+), 238 deletions(-) create mode 100644 packages/http-protocol/src/v1/mod.rs rename {src/servers/http => packages/http-protocol/src}/v1/query.rs (97%) rename {src/servers/http => packages/http-protocol/src}/v1/requests/announce.rs (97%) rename {src/servers/http => packages/http-protocol/src}/v1/requests/mod.rs (100%) rename {src/servers/http => packages/http-protocol/src}/v1/requests/scrape.rs (89%) rename {src/servers/http => packages/http-protocol/src}/v1/responses/announce.rs (90%) rename {src/servers/http => packages/http-protocol/src}/v1/responses/error.rs (88%) create mode 100644 packages/http-protocol/src/v1/responses/mod.rs rename {src/servers/http => packages/http-protocol/src}/v1/responses/scrape.rs (89%) create mode 100644 packages/http-protocol/src/v1/services/mod.rs rename {src/servers/http => packages/http-protocol/src}/v1/services/peer_ip_resolver.rs (96%) create mode 100644 packages/primitives/src/core.rs delete mode 100644 src/servers/http/v1/responses/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 6e7a10116..c097ed80e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -553,7 +553,15 @@ version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", "bittorrent-primitives", + "derive_more", + "multimap", "percent-encoding", + "serde", + "serde_bencode", + "thiserror 2.0.9", + "torrust-tracker-configuration", + "torrust-tracker-contrib-bencode", + "torrust-tracker-located-error", "torrust-tracker-primitives", ] @@ -3955,7 +3963,6 @@ dependencies = [ "lazy_static", "local-ip-address", "mockall", - "multimap", "parking_lot", "percent-encoding", "pin-project-lite", @@ -3977,7 +3984,6 @@ dependencies = [ "torrust-tracker-api-client", "torrust-tracker-clock", "torrust-tracker-configuration", - "torrust-tracker-contrib-bencode", "torrust-tracker-located-error", "torrust-tracker-primitives", "torrust-tracker-test-helpers", @@ -4082,6 +4088,7 @@ dependencies = [ "tdyne-peer-id", "tdyne-peer-id-registry", "thiserror 2.0.9", + "torrust-tracker-configuration", "zerocopy", ] diff --git a/Cargo.toml b/Cargo.toml index 0bf3e39e3..4b4862cca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,7 +58,6 @@ http-body = "1" hyper = "1" hyper-util = { version = "0", features = ["http1", "http2", "tokio"] } lazy_static = "1" -multimap = "0" parking_lot = "0" percent-encoding = "2" pin-project-lite = "0" @@ -79,7 +78,6 @@ thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } -torrust-tracker-contrib-bencode = { version = "3.0.0-develop", path = "contrib/bencode" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "packages/located-error" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "packages/primitives" } torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "packages/torrent-repository" } diff --git a/packages/http-protocol/Cargo.toml b/packages/http-protocol/Cargo.toml index 4f20407b6..05b69d201 100644 --- a/packages/http-protocol/Cargo.toml +++ b/packages/http-protocol/Cargo.toml @@ -17,5 +17,13 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" +derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } +multimap = "0" percent-encoding = "2" +serde = { version = "1", features = ["derive"] } +serde_bencode = "0" +thiserror = "2" +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-develop", path = "../../contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } diff --git a/packages/http-protocol/src/lib.rs b/packages/http-protocol/src/lib.rs index 44237d6fd..6525a6dca 100644 --- a/packages/http-protocol/src/lib.rs +++ b/packages/http-protocol/src/lib.rs @@ -1,2 +1,3 @@ //! Primitive types and function for `BitTorrent` HTTP trackers. pub mod percent_encoding; +pub mod v1; diff --git a/packages/http-protocol/src/v1/mod.rs b/packages/http-protocol/src/v1/mod.rs new file mode 100644 index 000000000..d52ba7609 --- /dev/null +++ b/packages/http-protocol/src/v1/mod.rs @@ -0,0 +1,4 @@ +pub mod query; +pub mod requests; +pub mod responses; +pub mod services; diff --git a/src/servers/http/v1/query.rs b/packages/http-protocol/src/v1/query.rs similarity index 97% rename from src/servers/http/v1/query.rs rename to packages/http-protocol/src/v1/query.rs index e65f62ada..8f9170aad 100644 --- a/src/servers/http/v1/query.rs +++ b/packages/http-protocol/src/v1/query.rs @@ -224,7 +224,7 @@ impl std::fmt::Display for FieldValuePairSet { mod tests { mod url_query { - use crate::servers::http::v1::query::Query; + use crate::v1::query::Query; #[test] fn should_parse_the_query_params_from_an_url_query_string() { @@ -277,7 +277,7 @@ mod tests { } mod should_allow_more_than_one_value_for_the_same_param { - use crate::servers::http::v1::query::Query; + use crate::v1::query::Query; #[test] fn instantiated_from_a_vector() { @@ -299,7 +299,7 @@ mod tests { } mod should_be_displayed { - use crate::servers::http::v1::query::Query; + use crate::v1::query::Query; #[test] fn with_one_param() { @@ -320,7 +320,7 @@ mod tests { } mod param_name_value_pair { - use crate::servers::http::v1::query::NameValuePair; + use crate::v1::query::NameValuePair; #[test] fn should_parse_a_single_query_param() { diff --git a/src/servers/http/v1/requests/announce.rs b/packages/http-protocol/src/v1/requests/announce.rs similarity index 97% rename from src/servers/http/v1/requests/announce.rs rename to packages/http-protocol/src/v1/requests/announce.rs index e8a730e9c..28cecd386 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/packages/http-protocol/src/v1/requests/announce.rs @@ -6,14 +6,14 @@ use std::panic::Location; use std::str::FromStr; use aquatic_udp_protocol::{NumberOfBytes, PeerId}; -use bittorrent_http_protocol::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; use bittorrent_primitives::info_hash::{self, InfoHash}; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; use torrust_tracker_primitives::peer; -use crate::servers::http::v1::query::{ParseQueryError, Query}; -use crate::servers::http::v1::responses; +use crate::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; +use crate::v1::query::{ParseQueryError, Query}; +use crate::v1::responses; // Query param names const INFO_HASH: &str = "info_hash"; @@ -381,8 +381,8 @@ mod tests { use aquatic_udp_protocol::{NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; - use crate::servers::http::v1::query::Query; - use crate::servers::http::v1::requests::announce::{ + use crate::v1::query::Query; + use crate::v1::requests::announce::{ Announce, Compact, Event, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, NUMWANT, PEER_ID, PORT, UPLOADED, }; @@ -452,8 +452,8 @@ mod tests { mod when_it_is_instantiated_from_the_url_query_params { - use crate::servers::http::v1::query::Query; - use crate::servers::http::v1::requests::announce::{ + use crate::v1::query::Query; + use crate::v1::requests::announce::{ Announce, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, NUMWANT, PEER_ID, PORT, UPLOADED, }; diff --git a/src/servers/http/v1/requests/mod.rs b/packages/http-protocol/src/v1/requests/mod.rs similarity index 100% rename from src/servers/http/v1/requests/mod.rs rename to packages/http-protocol/src/v1/requests/mod.rs diff --git a/src/servers/http/v1/requests/scrape.rs b/packages/http-protocol/src/v1/requests/scrape.rs similarity index 89% rename from src/servers/http/v1/requests/scrape.rs rename to packages/http-protocol/src/v1/requests/scrape.rs index a8e76282e..ae8e41cc2 100644 --- a/src/servers/http/v1/requests/scrape.rs +++ b/packages/http-protocol/src/v1/requests/scrape.rs @@ -3,13 +3,13 @@ //! Data structures and logic for parsing the `scrape` request. use std::panic::Location; -use bittorrent_http_protocol::percent_encoding::percent_decode_info_hash; use bittorrent_primitives::info_hash::{self, InfoHash}; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; -use crate::servers::http::v1::query::Query; -use crate::servers::http::v1::responses; +use crate::percent_encoding::percent_decode_info_hash; +use crate::v1::query::Query; +use crate::v1::responses; // Query param names const INFO_HASH: &str = "info_hash"; @@ -86,8 +86,8 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; - use crate::servers::http::v1::query::Query; - use crate::servers::http::v1::requests::scrape::{Scrape, INFO_HASH}; + use crate::v1::query::Query; + use crate::v1::requests::scrape::{Scrape, INFO_HASH}; #[test] fn should_be_instantiated_from_the_url_query_with_only_one_infohash() { @@ -107,8 +107,8 @@ mod tests { mod when_it_is_instantiated_from_the_url_query_params { - use crate::servers::http::v1::query::Query; - use crate::servers::http::v1::requests::scrape::{Scrape, INFO_HASH}; + use crate::v1::query::Query; + use crate::v1::requests::scrape::{Scrape, INFO_HASH}; #[test] fn it_should_fail_if_the_query_does_not_include_the_info_hash_param() { diff --git a/src/servers/http/v1/responses/announce.rs b/packages/http-protocol/src/v1/responses/announce.rs similarity index 90% rename from src/servers/http/v1/responses/announce.rs rename to packages/http-protocol/src/v1/responses/announce.rs index 925c0893e..986a881a5 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/packages/http-protocol/src/v1/responses/announce.rs @@ -1,18 +1,14 @@ -//! `Announce` response for the HTTP tracker [`announce`](crate::servers::http::v1::requests::announce::Announce) request. +//! `Announce` response for the HTTP tracker [`announce`](bittorrent_http_protocol::v1::requests::announce::Announce) request. //! //! Data structures and logic to build the `announce` response. use std::io::Write; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -use axum::http::StatusCode; use derive_more::{AsRef, Constructor, From}; use torrust_tracker_contrib_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; +use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; -use super::Response; -use crate::core::AnnounceData; -use crate::servers::http::v1::responses; - /// An [`Announce`] response, that can be anything that is convertible from [`AnnounceData`]. /// /// The [`Announce`] can built from any data that implements: [`From`] and [`Into>`]. @@ -35,7 +31,7 @@ pub struct Announce where E: From + Into>, { - data: E, + pub data: E, } /// Build any [`Announce`] from an [`AnnounceData`]. @@ -45,24 +41,6 @@ impl + Into>> From for Announce { } } -/// Convert any Announce [`Announce`] into a [`axum::response::Response`] -impl + Into>> axum::response::IntoResponse for Announce -where - Announce: Response, -{ - fn into_response(self) -> axum::response::Response { - axum::response::IntoResponse::into_response(self.body().map(|bytes| (StatusCode::OK, bytes))) - } -} - -/// Implement the [`Response`] for the [`Announce`]. -/// -impl + Into>> Response for Announce { - fn body(self) -> Result, responses::error::Error> { - Ok(self.data.into()) - } -} - /// Format of the [`Normal`] (Non-Compact) Encoding pub struct Normal { complete: i64, @@ -302,11 +280,11 @@ mod tests { use aquatic_udp_protocol::PeerId; use torrust_tracker_configuration::AnnouncePolicy; + use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::core::AnnounceData; - use crate::servers::http::v1::responses::announce::{Announce, Compact, Normal, Response}; + use crate::v1::responses::announce::{Announce, Compact, Normal}; // Some ascii values used in tests: // @@ -345,7 +323,7 @@ mod tests { #[test] fn non_compact_announce_response_can_be_bencoded() { let response: Announce = setup_announce_data().into(); - let bytes = response.body().expect("it should encode the response"); + let bytes = response.data.into(); // cspell:disable-next-line let expected_bytes = b"d8:completei333e10:incompletei444e8:intervali111e12:min intervali222e5:peersld2:ip15:105.105.105.1057:peer id20:-qB000000000000000014:porti28784eed2:ip39:6969:6969:6969:6969:6969:6969:6969:69697:peer id20:-qB000000000000000024:porti28784eeee"; @@ -359,7 +337,7 @@ mod tests { #[test] fn compact_announce_response_can_be_bencoded() { let response: Announce = setup_announce_data().into(); - let bytes = response.body().expect("it should encode the response"); + let bytes = response.data.into(); let expected_bytes = // cspell:disable-next-line diff --git a/src/servers/http/v1/responses/error.rs b/packages/http-protocol/src/v1/responses/error.rs similarity index 88% rename from src/servers/http/v1/responses/error.rs rename to packages/http-protocol/src/v1/responses/error.rs index 7223063fd..9aca9c71c 100644 --- a/src/servers/http/v1/responses/error.rs +++ b/packages/http-protocol/src/v1/responses/error.rs @@ -11,10 +11,10 @@ //! > **NOTICE**: error responses are bencoded and always have a `200 OK` status //! > code. The official `BitTorrent` specification does not specify the status //! > code. -use axum::http::StatusCode; -use axum::response::{IntoResponse, Response}; use serde::Serialize; +use crate::v1::services::peer_ip_resolver::PeerIpResolutionError; + /// `Error` response for the [`HTTP tracker`](crate::servers::http). #[derive(Serialize, Debug, PartialEq)] pub struct Error { @@ -47,9 +47,11 @@ impl Error { } } -impl IntoResponse for Error { - fn into_response(self) -> Response { - (StatusCode::OK, self.write()).into_response() +impl From for Error { + fn from(err: PeerIpResolutionError) -> Self { + Self { + failure_reason: format!("Error resolving peer IP: {err}"), + } } } diff --git a/packages/http-protocol/src/v1/responses/mod.rs b/packages/http-protocol/src/v1/responses/mod.rs new file mode 100644 index 000000000..495b1eb84 --- /dev/null +++ b/packages/http-protocol/src/v1/responses/mod.rs @@ -0,0 +1,9 @@ +//! HTTP responses for the HTTP tracker. +//! +//! Refer to the generic [HTTP server documentation](crate::servers::http) for +//! more information about the HTTP tracker. +pub mod announce; +pub mod error; +pub mod scrape; + +pub use announce::{Announce, Compact, Normal}; diff --git a/src/servers/http/v1/responses/scrape.rs b/packages/http-protocol/src/v1/responses/scrape.rs similarity index 89% rename from src/servers/http/v1/responses/scrape.rs rename to packages/http-protocol/src/v1/responses/scrape.rs index 1f367a9c9..a52fa263c 100644 --- a/src/servers/http/v1/responses/scrape.rs +++ b/packages/http-protocol/src/v1/responses/scrape.rs @@ -1,13 +1,10 @@ -//! `Scrape` response for the HTTP tracker [`scrape`](crate::servers::http::v1::requests::scrape::Scrape) request. +//! `Scrape` response for the HTTP tracker [`scrape`](bittorrent_http_protocol::v1::requests::scrape::Scrape) request. //! //! Data structures and logic to build the `scrape` response. use std::borrow::Cow; -use axum::http::StatusCode; -use axum::response::{IntoResponse, Response}; use torrust_tracker_contrib_bencode::{ben_int, ben_map, BMutAccess}; - -use crate::core::ScrapeData; +use torrust_tracker_primitives::core::ScrapeData; /// The `Scrape` response for the HTTP tracker. /// @@ -82,21 +79,15 @@ impl From for Bencoded { } } -impl IntoResponse for Bencoded { - fn into_response(self) -> Response { - (StatusCode::OK, self.body()).into_response() - } -} - #[cfg(test)] mod tests { mod scrape_response { use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::core::ScrapeData; - use crate::servers::http::v1::responses::scrape::Bencoded; + use crate::v1::responses::scrape::Bencoded; fn sample_scrape_data() -> ScrapeData { let info_hash = InfoHash::from_bytes(&[0x69; 20]); diff --git a/packages/http-protocol/src/v1/services/mod.rs b/packages/http-protocol/src/v1/services/mod.rs new file mode 100644 index 000000000..de800f630 --- /dev/null +++ b/packages/http-protocol/src/v1/services/mod.rs @@ -0,0 +1 @@ +pub mod peer_ip_resolver; diff --git a/src/servers/http/v1/services/peer_ip_resolver.rs b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs similarity index 96% rename from src/servers/http/v1/services/peer_ip_resolver.rs rename to packages/http-protocol/src/v1/services/peer_ip_resolver.rs index 56bd3d86f..366f8820c 100644 --- a/src/servers/http/v1/services/peer_ip_resolver.rs +++ b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs @@ -142,7 +142,7 @@ mod tests { use std::str::FromStr; use super::invoke; - use crate::servers::http::v1::services::peer_ip_resolver::{ClientIpSources, PeerIpResolutionError}; + use crate::v1::services::peer_ip_resolver::{ClientIpSources, PeerIpResolutionError}; #[test] fn it_should_get_the_peer_ip_from_the_connection_info() { @@ -181,7 +181,7 @@ mod tests { use std::net::IpAddr; use std::str::FromStr; - use crate::servers::http::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; + use crate::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; #[test] fn it_should_get_the_peer_ip_from_the_right_most_ip_in_the_x_forwarded_for_header() { diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index 66b81d65d..b83886385 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -23,4 +23,5 @@ serde = { version = "1", features = ["derive"] } tdyne-peer-id = "1" tdyne-peer-id-registry = "0" thiserror = "2" +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } zerocopy = "0.7" diff --git a/packages/primitives/src/core.rs b/packages/primitives/src/core.rs new file mode 100644 index 000000000..0c0f68b8b --- /dev/null +++ b/packages/primitives/src/core.rs @@ -0,0 +1,58 @@ +use std::collections::HashMap; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use derive_more::derive::Constructor; +use torrust_tracker_configuration::AnnouncePolicy; + +use crate::peer; +use crate::swarm_metadata::SwarmMetadata; + +/// Structure that holds the data returned by the `announce` request. +#[derive(Clone, Debug, PartialEq, Constructor, Default)] +pub struct AnnounceData { + /// The list of peers that are downloading the same torrent. + /// It excludes the peer that made the request. + pub peers: Vec>, + /// Swarm statistics + pub stats: SwarmMetadata, + pub policy: AnnouncePolicy, +} + +/// Structure that holds the data returned by the `scrape` request. +#[derive(Debug, PartialEq, Default)] +pub struct ScrapeData { + /// A map of infohashes and swarm metadata for each torrent. + pub files: HashMap, +} + +impl ScrapeData { + /// Creates a new empty `ScrapeData` with no files (torrents). + #[must_use] + pub fn empty() -> Self { + let files: HashMap = HashMap::new(); + Self { files } + } + + /// Creates a new `ScrapeData` with zeroed metadata for each torrent. + #[must_use] + pub fn zeroed(info_hashes: &Vec) -> Self { + let mut scrape_data = Self::empty(); + + for info_hash in info_hashes { + scrape_data.add_file(info_hash, SwarmMetadata::zeroed()); + } + + scrape_data + } + + /// Adds a torrent to the `ScrapeData`. + pub fn add_file(&mut self, info_hash: &InfoHash, swarm_metadata: SwarmMetadata) { + self.files.insert(*info_hash, swarm_metadata); + } + + /// Adds a torrent to the `ScrapeData` with zeroed metadata. + pub fn add_file_with_zeroed_metadata(&mut self, info_hash: &InfoHash) { + self.files.insert(*info_hash, SwarmMetadata::zeroed()); + } +} diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index d5c6fc525..55f90ef20 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -4,6 +4,7 @@ //! which is a `BitTorrent` tracker server. These structures are used not only //! by the tracker server crate, but also by other crates in the Torrust //! ecosystem. +pub mod core; pub mod pagination; pub mod peer; pub mod swarm_metadata; diff --git a/src/core/error.rs b/src/core/error.rs index ba87c84c8..f0de7df40 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -8,6 +8,7 @@ //! use std::panic::Location; +use bittorrent_http_protocol::v1::responses; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_located_error::LocatedError; @@ -53,3 +54,11 @@ pub enum PeerKeyError { source: LocatedError<'static, databases::error::Error>, }, } + +impl From for responses::error::Error { + fn from(err: Error) -> Self { + responses::error::Error { + failure_reason: format!("Tracker error: {err}"), + } + } +} diff --git a/src/core/mod.rs b/src/core/mod.rs index b5759709b..6ba8e94ad 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -449,7 +449,6 @@ pub mod torrent; pub mod peer_tests; use std::cmp::max; -use std::collections::HashMap; use std::net::IpAddr; use std::panic::Location; use std::sync::Arc; @@ -458,13 +457,13 @@ use std::time::Duration; use auth::PeerKey; use bittorrent_primitives::info_hash::InfoHash; use databases::driver::Driver; -use derive_more::Constructor; use error::PeerKeyError; use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_located_error::Located; +use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; @@ -511,17 +510,6 @@ pub struct Tracker { stats_repository: statistics::repository::Repository, } -/// Structure that holds the data returned by the `announce` request. -#[derive(Clone, Debug, PartialEq, Constructor, Default)] -pub struct AnnounceData { - /// The list of peers that are downloading the same torrent. - /// It excludes the peer that made the request. - pub peers: Vec>, - /// Swarm statistics - pub stats: SwarmMetadata, - pub policy: AnnouncePolicy, -} - /// How many peers the peer announcing wants in the announce response. #[derive(Clone, Debug, PartialEq, Default)] pub enum PeersWanted { @@ -564,44 +552,6 @@ impl From for PeersWanted { } } -/// Structure that holds the data returned by the `scrape` request. -#[derive(Debug, PartialEq, Default)] -pub struct ScrapeData { - /// A map of infohashes and swarm metadata for each torrent. - pub files: HashMap, -} - -impl ScrapeData { - /// Creates a new empty `ScrapeData` with no files (torrents). - #[must_use] - pub fn empty() -> Self { - let files: HashMap = HashMap::new(); - Self { files } - } - - /// Creates a new `ScrapeData` with zeroed metadata for each torrent. - #[must_use] - pub fn zeroed(info_hashes: &Vec) -> Self { - let mut scrape_data = Self::empty(); - - for info_hash in info_hashes { - scrape_data.add_file(info_hash, SwarmMetadata::zeroed()); - } - - scrape_data - } - - /// Adds a torrent to the `ScrapeData`. - pub fn add_file(&mut self, info_hash: &InfoHash, swarm_metadata: SwarmMetadata) { - self.files.insert(*info_hash, swarm_metadata); - } - - /// Adds a torrent to the `ScrapeData` with zeroed metadata. - pub fn add_file_with_zeroed_metadata(&mut self, info_hash: &InfoHash) { - self.files.insert(*info_hash, SwarmMetadata::zeroed()); - } -} - /// This type contains the info needed to add a new tracker key. /// /// You can upload a pre-generated key or let the app to generate a new one. diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index 6dfb6ce7c..fa0ccc776 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -43,18 +43,18 @@ //! //! Parameter | Type | Description | Required | Default | Example //! ---|---|---|---|---|--- -//! [`info_hash`](crate::servers::http::v1::requests::announce::Announce::info_hash) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` +//! [`info_hash`](bittorrent_http_protocol::v1::requests::announce::Announce::info_hash) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` //! `peer_addr` | string |The IP address of the peer. | No | No | `2.137.87.41` -//! [`downloaded`](crate::servers::http::v1::requests::announce::Announce::downloaded) | positive integer |The number of bytes downloaded by the peer. | No | `0` | `0` -//! [`uploaded`](crate::servers::http::v1::requests::announce::Announce::uploaded) | positive integer | The number of bytes uploaded by the peer. | No | `0` | `0` -//! [`peer_id`](crate::servers::http::v1::requests::announce::Announce::peer_id) | percent encoded of 20-byte array | The ID of the peer. | Yes | No | `-qB00000000000000001` -//! [`port`](crate::servers::http::v1::requests::announce::Announce::port) | positive integer | The port used by the peer. | Yes | No | `17548` -//! [`left`](crate::servers::http::v1::requests::announce::Announce::left) | positive integer | The number of bytes pending to download. | No | `0` | `0` -//! [`event`](crate::servers::http::v1::requests::announce::Announce::event) | positive integer | The event that triggered the `Announce` request: `started`, `completed`, `stopped` | No | `None` | `completed` -//! [`compact`](crate::servers::http::v1::requests::announce::Announce::compact) | `0` or `1` | Whether the tracker should return a compact peer list. | No | `None` | `0` +//! [`downloaded`](bittorrent_http_protocol::v1::requests::announce::Announce::downloaded) | positive integer |The number of bytes downloaded by the peer. | No | `0` | `0` +//! [`uploaded`](bittorrent_http_protocol::v1::requests::announce::Announce::uploaded) | positive integer | The number of bytes uploaded by the peer. | No | `0` | `0` +//! [`peer_id`](bittorrent_http_protocol::v1::requests::announce::Announce::peer_id) | percent encoded of 20-byte array | The ID of the peer. | Yes | No | `-qB00000000000000001` +//! [`port`](bittorrent_http_protocol::v1::requests::announce::Announce::port) | positive integer | The port used by the peer. | Yes | No | `17548` +//! [`left`](bittorrent_http_protocol::v1::requests::announce::Announce::left) | positive integer | The number of bytes pending to download. | No | `0` | `0` +//! [`event`](bittorrent_http_protocol::v1::requests::announce::Announce::event) | positive integer | The event that triggered the `Announce` request: `started`, `completed`, `stopped` | No | `None` | `completed` +//! [`compact`](bittorrent_http_protocol::v1::requests::announce::Announce::compact) | `0` or `1` | Whether the tracker should return a compact peer list. | No | `None` | `0` //! `numwant` | positive integer | **Not implemented**. The maximum number of peers you want in the reply. | No | `50` | `50` //! -//! Refer to the [`Announce`](crate::servers::http::v1::requests::announce::Announce) +//! Refer to the [`Announce`](bittorrent_http_protocol::v1::requests::announce::Announce) //! request for more information about the parameters. //! //! > **NOTICE**: the [BEP 03](https://www.bittorrent.org/beps/bep_0003.html) @@ -152,7 +152,7 @@ //! 000000f0: 65 e //! ``` //! -//! Refer to the [`Normal`](crate::servers::http::v1::responses::announce::Normal), i.e. `Non-Compact` +//! Refer to the [`Normal`](bittorrent_http_protocol::v1::responses::announce::Normal), i.e. `Non-Compact` //! response for more information about the response. //! //! **Sample compact response** @@ -190,7 +190,7 @@ //! 0000070: 7065 pe //! ``` //! -//! Refer to the [`Compact`](crate::servers::http::v1::responses::announce::Compact) +//! Refer to the [`Compact`](bittorrent_http_protocol::v1::responses::announce::Compact) //! response for more information about the response. //! //! **Protocol** @@ -220,12 +220,12 @@ //! //! Parameter | Type | Description | Required | Default | Example //! ---|---|---|---|---|--- -//! [`info_hash`](crate::servers::http::v1::requests::scrape::Scrape::info_hashes) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` +//! [`info_hash`](bittorrent_http_protocol::v1::requests::scrape::Scrape::info_hashes) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` //! //! > **NOTICE**: you can scrape multiple torrents at the same time by passing //! > multiple `info_hash` parameters. //! -//! Refer to the [`Scrape`](crate::servers::http::v1::requests::scrape::Scrape) +//! Refer to the [`Scrape`](bittorrent_http_protocol::v1::requests::scrape::Scrape) //! request for more information about the parameters. //! //! **Sample scrape URL** diff --git a/src/servers/http/v1/extractors/announce_request.rs b/src/servers/http/v1/extractors/announce_request.rs index 32b69ae0b..74c9ab8c1 100644 --- a/src/servers/http/v1/extractors/announce_request.rs +++ b/src/servers/http/v1/extractors/announce_request.rs @@ -4,10 +4,10 @@ //! It parses the query parameters returning an [`Announce`] //! request. //! -//! Refer to [`Announce`](crate::servers::http::v1::requests::announce) for more +//! Refer to [`Announce`](bittorrent_http_protocol::v1::requests::announce) for more //! information about the returned structure. //! -//! It returns a bencoded [`Error`](crate::servers::http::v1::responses::error) +//! It returns a bencoded [`Error`](bittorrent_http_protocol::v1::responses::error) //! response (`500`) if the query parameters are missing or invalid. //! //! **Sample announce request** @@ -33,11 +33,11 @@ use std::panic::Location; use axum::extract::FromRequestParts; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; +use bittorrent_http_protocol::v1::query::Query; +use bittorrent_http_protocol::v1::requests::announce::{Announce, ParseAnnounceQueryError}; +use bittorrent_http_protocol::v1::responses; use futures::FutureExt; - -use crate::servers::http::v1::query::Query; -use crate::servers::http::v1::requests::announce::{Announce, ParseAnnounceQueryError}; -use crate::servers::http::v1::responses; +use hyper::StatusCode; /// Extractor for the [`Announce`] /// request. @@ -53,7 +53,7 @@ where async { match extract_announce_from(parts.uri.query()) { Ok(announce_request) => Ok(ExtractRequest(announce_request)), - Err(error) => Err(error.into_response()), + Err(error) => Err((StatusCode::OK, error.write()).into_response()), } } .boxed() @@ -87,11 +87,11 @@ mod tests { use std::str::FromStr; use aquatic_udp_protocol::{NumberOfBytes, PeerId}; + use bittorrent_http_protocol::v1::requests::announce::{Announce, Compact, Event}; + use bittorrent_http_protocol::v1::responses::error::Error; use bittorrent_primitives::info_hash::InfoHash; use super::extract_announce_from; - use crate::servers::http::v1::requests::announce::{Announce, Compact, Event}; - use crate::servers::http::v1::responses::error::Error; fn assert_error_response(error: &Error, error_message: &str) { assert!( diff --git a/src/servers/http/v1/extractors/authentication_key.rs b/src/servers/http/v1/extractors/authentication_key.rs index 35efdf93d..6610b197a 100644 --- a/src/servers/http/v1/extractors/authentication_key.rs +++ b/src/servers/http/v1/extractors/authentication_key.rs @@ -9,7 +9,7 @@ //! It's a wrapper for Axum `Path` extractor in order to return custom //! authentication errors. //! -//! It returns a bencoded [`Error`](crate::servers::http::v1::responses::error) +//! It returns a bencoded [`Error`](bittorrent_http_protocol::v1::responses::error) //! response (`500`) if the `key` parameter are missing or invalid. //! //! **Sample authentication error responses** @@ -49,11 +49,12 @@ use axum::extract::rejection::PathRejection; use axum::extract::{FromRequestParts, Path}; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; +use bittorrent_http_protocol::v1::responses; +use hyper::StatusCode; use serde::Deserialize; use crate::core::auth::Key; use crate::servers::http::v1::handlers::common::auth; -use crate::servers::http::v1::responses; /// Extractor for the [`Key`] struct. pub struct Extract(pub Key); @@ -82,7 +83,7 @@ where match extract_key(maybe_path_with_key) { Ok(key) => Ok(Extract(key)), - Err(error) => Err(error.into_response()), + Err(error) => Err((StatusCode::OK, error.write()).into_response()), } } } @@ -130,8 +131,9 @@ fn custom_error(rejection: &PathRejection) -> responses::error::Error { #[cfg(test)] mod tests { + use bittorrent_http_protocol::v1::responses::error::Error; + use super::parse_key; - use crate::servers::http::v1::responses::error::Error; fn assert_error_response(error: &Error, error_message: &str) { assert!( diff --git a/src/servers/http/v1/extractors/client_ip_sources.rs b/src/servers/http/v1/extractors/client_ip_sources.rs index 1ca5a22d0..02265554e 100644 --- a/src/servers/http/v1/extractors/client_ip_sources.rs +++ b/src/servers/http/v1/extractors/client_ip_sources.rs @@ -42,8 +42,7 @@ use axum::extract::{ConnectInfo, FromRequestParts}; use axum::http::request::Parts; use axum::response::Response; use axum_client_ip::RightmostXForwardedFor; - -use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; +use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; /// Extractor for the [`ClientIpSources`] /// struct. diff --git a/src/servers/http/v1/extractors/scrape_request.rs b/src/servers/http/v1/extractors/scrape_request.rs index 890c4033c..bacd36169 100644 --- a/src/servers/http/v1/extractors/scrape_request.rs +++ b/src/servers/http/v1/extractors/scrape_request.rs @@ -4,10 +4,10 @@ //! It parses the query parameters returning an [`Scrape`] //! request. //! -//! Refer to [`Scrape`](crate::servers::http::v1::requests::scrape) for more +//! Refer to [`Scrape`](bittorrent_http_protocol::v1::requests::scrape) for more //! information about the returned structure. //! -//! It returns a bencoded [`Error`](crate::servers::http::v1::responses::error) +//! It returns a bencoded [`Error`](bittorrent_http_protocol::v1::responses::error) //! response (`500`) if the query parameters are missing or invalid. //! //! **Sample scrape request** @@ -33,11 +33,11 @@ use std::panic::Location; use axum::extract::FromRequestParts; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; +use bittorrent_http_protocol::v1::query::Query; +use bittorrent_http_protocol::v1::requests::scrape::{ParseScrapeQueryError, Scrape}; +use bittorrent_http_protocol::v1::responses; use futures::FutureExt; - -use crate::servers::http::v1::query::Query; -use crate::servers::http::v1::requests::scrape::{ParseScrapeQueryError, Scrape}; -use crate::servers::http::v1::responses; +use hyper::StatusCode; /// Extractor for the [`Scrape`] /// request. @@ -53,7 +53,7 @@ where async { match extract_scrape_from(parts.uri.query()) { Ok(scrape_request) => Ok(ExtractRequest(scrape_request)), - Err(error) => Err(error.into_response()), + Err(error) => Err((StatusCode::OK, error.write()).into_response()), } } .boxed() @@ -86,11 +86,11 @@ fn extract_scrape_from(maybe_raw_query: Option<&str>) -> Result Response { let announce_data = match handle_announce(tracker, announce_request, client_ip_sources, maybe_key).await { Ok(announce_data) => announce_data, - Err(error) => return error.into_response(), + Err(error) => return (StatusCode::OK, error.write()).into_response(), }; build_response(announce_request, announce_data) } @@ -123,10 +126,12 @@ async fn handle_announce( fn build_response(announce_request: &Announce, announce_data: AnnounceData) -> Response { if announce_request.compact.as_ref().is_some_and(|f| *f == Compact::Accepted) { let response: responses::Announce = announce_data.into(); - response.into_response() + let bytes: Vec = response.data.into(); + (StatusCode::OK, bytes).into_response() } else { let response: responses::Announce = announce_data.into(); - response.into_response() + let bytes: Vec = response.data.into(); + (StatusCode::OK, bytes).into_response() } } @@ -174,14 +179,14 @@ pub fn map_to_torrust_event(event: &Option) -> AnnounceEvent { mod tests { use aquatic_udp_protocol::PeerId; + use bittorrent_http_protocol::v1::requests::announce::Announce; + use bittorrent_http_protocol::v1::responses; + use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; use crate::core::Tracker; - use crate::servers::http::v1::requests::announce::Announce; - use crate::servers::http::v1::responses; - use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; fn private_tracker() -> Tracker { tracker_factory(&configuration::ephemeral_private()) @@ -301,10 +306,11 @@ mod tests { use std::sync::Arc; + use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use super::{sample_announce_request, tracker_on_reverse_proxy}; use crate::servers::http::v1::handlers::announce::handle_announce; use crate::servers::http::v1::handlers::announce::tests::assert_error_response; - use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { @@ -330,10 +336,11 @@ mod tests { use std::sync::Arc; + use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use super::{sample_announce_request, tracker_not_on_reverse_proxy}; use crate::servers::http::v1::handlers::announce::handle_announce; use crate::servers::http::v1::handlers::announce::tests::assert_error_response; - use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { diff --git a/src/servers/http/v1/handlers/common/auth.rs b/src/servers/http/v1/handlers/common/auth.rs index f9a7796a4..ff1d47e91 100644 --- a/src/servers/http/v1/handlers/common/auth.rs +++ b/src/servers/http/v1/handlers/common/auth.rs @@ -3,10 +3,10 @@ //! response. use std::panic::Location; +use bittorrent_http_protocol::v1::responses; use thiserror::Error; use crate::core::auth; -use crate::servers::http::v1::responses; /// Authentication error. /// diff --git a/src/servers/http/v1/handlers/common/peer_ip.rs b/src/servers/http/v1/handlers/common/peer_ip.rs index 5602bd26c..0fe7c14f1 100644 --- a/src/servers/http/v1/handlers/common/peer_ip.rs +++ b/src/servers/http/v1/handlers/common/peer_ip.rs @@ -2,25 +2,15 @@ //! //! The HTTP tracker may fail to resolve the peer IP address. This module //! contains the logic to convert those -//! [`PeerIpResolutionError`] +//! [`PeerIpResolutionError`](bittorrent_http_protocol::v1::services::peer_ip_resolver::PeerIpResolutionError) //! errors into responses. -use crate::servers::http::v1::responses; -use crate::servers::http::v1::services::peer_ip_resolver::PeerIpResolutionError; - -impl From for responses::error::Error { - fn from(err: PeerIpResolutionError) -> Self { - responses::error::Error { - failure_reason: format!("Error resolving peer IP: {err}"), - } - } -} #[cfg(test)] mod tests { use std::panic::Location; - use crate::servers::http::v1::responses; - use crate::servers::http::v1::services::peer_ip_resolver::PeerIpResolutionError; + use bittorrent_http_protocol::v1::responses; + use bittorrent_http_protocol::v1::services::peer_ip_resolver::PeerIpResolutionError; fn assert_error_response(error: &responses::error::Error, error_message: &str) { assert!( diff --git a/src/servers/http/v1/handlers/mod.rs b/src/servers/http/v1/handlers/mod.rs index 7b3a1e7c3..f9305cf20 100644 --- a/src/servers/http/v1/handlers/mod.rs +++ b/src/servers/http/v1/handlers/mod.rs @@ -2,18 +2,7 @@ //! //! Refer to the generic [HTTP server documentation](crate::servers::http) for //! more information about the HTTP tracker. -use super::responses; -use crate::core::error::Error; - pub mod announce; pub mod common; pub mod health_check; pub mod scrape; - -impl From for responses::error::Error { - fn from(err: Error) -> Self { - responses::error::Error { - failure_reason: format!("Tracker error: {err}"), - } - } -} diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 10f945d70..2aa1bd9f8 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -9,15 +9,18 @@ use std::sync::Arc; use axum::extract::State; use axum::response::{IntoResponse, Response}; +use bittorrent_http_protocol::v1::requests::scrape::Scrape; +use bittorrent_http_protocol::v1::responses; +use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; +use hyper::StatusCode; +use torrust_tracker_primitives::core::ScrapeData; use crate::core::auth::Key; -use crate::core::{ScrapeData, Tracker}; +use crate::core::Tracker; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::extractors::scrape_request::ExtractRequest; -use crate::servers::http::v1::requests::scrape::Scrape; -use crate::servers::http::v1::services::peer_ip_resolver::{self, ClientIpSources}; -use crate::servers::http::v1::{responses, services}; +use crate::servers::http::v1::services; /// It handles the `scrape` request when the HTTP tracker is configured /// to run in `public` mode. @@ -56,7 +59,7 @@ async fn handle( ) -> Response { let scrape_data = match handle_scrape(tracker, scrape_request, client_ip_sources, maybe_key).await { Ok(scrape_data) => scrape_data, - Err(error) => return error.into_response(), + Err(error) => return (StatusCode::OK, error.write()).into_response(), }; build_response(scrape_data) } @@ -102,7 +105,9 @@ async fn handle_scrape( } fn build_response(scrape_data: ScrapeData) -> Response { - responses::scrape::Bencoded::from(scrape_data).into_response() + let response = responses::scrape::Bencoded::from(scrape_data); + + (StatusCode::OK, response.body()).into_response() } #[cfg(test)] @@ -110,14 +115,14 @@ mod tests { use std::net::IpAddr; use std::str::FromStr; + use bittorrent_http_protocol::v1::requests::scrape::Scrape; + use bittorrent_http_protocol::v1::responses; + use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::core::services::tracker_factory; use crate::core::Tracker; - use crate::servers::http::v1::requests::scrape::Scrape; - use crate::servers::http::v1::responses; - use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; fn private_tracker() -> Tracker { tracker_factory(&configuration::ephemeral_private()) @@ -159,8 +164,10 @@ mod tests { use std::str::FromStr; use std::sync::Arc; + use torrust_tracker_primitives::core::ScrapeData; + use super::{private_tracker, sample_client_ip_sources, sample_scrape_request}; - use crate::core::{auth, ScrapeData}; + use crate::core::auth; use crate::servers::http::v1::handlers::scrape::handle_scrape; #[tokio::test] @@ -201,8 +208,9 @@ mod tests { use std::sync::Arc; + use torrust_tracker_primitives::core::ScrapeData; + use super::{sample_client_ip_sources, sample_scrape_request, whitelisted_tracker}; - use crate::core::ScrapeData; use crate::servers::http::v1::handlers::scrape::handle_scrape; #[tokio::test] @@ -224,10 +232,11 @@ mod tests { mod with_tracker_on_reverse_proxy { use std::sync::Arc; + use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use super::{sample_scrape_request, tracker_on_reverse_proxy}; use crate::servers::http::v1::handlers::scrape::handle_scrape; use crate::servers::http::v1::handlers::scrape::tests::assert_error_response; - use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { @@ -252,10 +261,11 @@ mod tests { mod with_tracker_not_on_reverse_proxy { use std::sync::Arc; + use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use super::{sample_scrape_request, tracker_not_on_reverse_proxy}; use crate::servers::http::v1::handlers::scrape::handle_scrape; use crate::servers::http::v1::handlers::scrape::tests::assert_error_response; - use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources; #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { diff --git a/src/servers/http/v1/mod.rs b/src/servers/http/v1/mod.rs index 9d2745692..48dac5663 100644 --- a/src/servers/http/v1/mod.rs +++ b/src/servers/http/v1/mod.rs @@ -4,8 +4,5 @@ //! more information about the endpoints and their usage. pub mod extractors; pub mod handlers; -pub mod query; -pub mod requests; -pub mod responses; pub mod routes; pub mod services; diff --git a/src/servers/http/v1/responses/mod.rs b/src/servers/http/v1/responses/mod.rs deleted file mode 100644 index e22879c6d..000000000 --- a/src/servers/http/v1/responses/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -//! HTTP responses for the HTTP tracker. -//! -//! Refer to the generic [HTTP server documentation](crate::servers::http) for -//! more information about the HTTP tracker. -pub mod announce; -pub mod error; -pub mod scrape; - -pub use announce::{Announce, Compact, Normal}; - -/// Trait that defines the Announce Response Format -pub trait Response: axum::response::IntoResponse { - /// Returns the Body of the Announce Response - /// - /// # Errors - /// - /// If unable to generate the response, it will return an error. - fn body(self) -> Result, error::Error>; -} diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 73d480c79..df827aee2 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -12,9 +12,10 @@ use std::net::IpAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; -use crate::core::{statistics, AnnounceData, PeersWanted, Tracker}; +use crate::core::{statistics, PeersWanted, Tracker}; /// The HTTP tracker `announce` service. /// @@ -100,12 +101,13 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; + use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; - use crate::core::{statistics, AnnounceData, PeersWanted, Tracker}; + use crate::core::{statistics, PeersWanted, Tracker}; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; diff --git a/src/servers/http/v1/services/mod.rs b/src/servers/http/v1/services/mod.rs index 2e6285d1a..ce99c6856 100644 --- a/src/servers/http/v1/services/mod.rs +++ b/src/servers/http/v1/services/mod.rs @@ -6,5 +6,4 @@ //! //! Refer to [`torrust_tracker`](crate) documentation. pub mod announce; -pub mod peer_ip_resolver; pub mod scrape; diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 9eef263cb..80d81d78a 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -12,8 +12,9 @@ use std::net::IpAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::core::ScrapeData; -use crate::core::{statistics, ScrapeData, Tracker}; +use crate::core::{statistics, Tracker}; /// The HTTP tracker `scrape` service. /// @@ -100,10 +101,11 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; + use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; - use crate::core::{statistics, PeersWanted, ScrapeData, Tracker}; + use crate::core::{statistics, PeersWanted, Tracker}; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ public_tracker, sample_info_hash, sample_info_hashes, sample_peer, @@ -192,9 +194,10 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; + use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_test_helpers::configuration; - use crate::core::{statistics, PeersWanted, ScrapeData, Tracker}; + use crate::core::{statistics, PeersWanted, Tracker}; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ public_tracker, sample_info_hash, sample_info_hashes, sample_peer, From c2d134e792216fbc58f9df67d89762434cf7bae2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Sat, 11 Jan 2025 21:09:40 +0000 Subject: [PATCH 0579/1297] test: re-enable slow tests Some doc tests were slow becuase they required to compile the main library. The code used from the main library was moved to workspace pacakages and there is no dependency with the main tracker lib. See https://github.com/torrust/torrust-tracker/issues/1097 --- packages/http-protocol/src/v1/query.rs | 16 ++++++++-------- .../http-protocol/src/v1/requests/announce.rs | 4 ++-- .../http-protocol/src/v1/responses/announce.rs | 8 ++++---- packages/http-protocol/src/v1/responses/error.rs | 4 ++-- .../http-protocol/src/v1/responses/scrape.rs | 6 +++--- .../src/v1/services/peer_ip_resolver.rs | 8 ++++---- 6 files changed, 23 insertions(+), 23 deletions(-) diff --git a/packages/http-protocol/src/v1/query.rs b/packages/http-protocol/src/v1/query.rs index 8f9170aad..f77145cb6 100644 --- a/packages/http-protocol/src/v1/query.rs +++ b/packages/http-protocol/src/v1/query.rs @@ -30,8 +30,8 @@ impl Query { /// It return `Some(value)` for a URL query param if the param with the /// input `name` exists. For example: /// - /// ```text - /// use torrust_tracker_lib::servers::http::v1::query::Query; + /// ```rust + /// use bittorrent_http_protocol::v1::query::Query; /// /// let raw_query = "param1=value1¶m2=value2"; /// @@ -43,8 +43,8 @@ impl Query { /// /// It returns only the first param value even if it has multiple values: /// - /// ```text - /// use torrust_tracker_lib::servers::http::v1::query::Query; + /// ```rust + /// use bittorrent_http_protocol::v1::query::Query; /// /// let raw_query = "param1=value1¶m1=value2"; /// @@ -59,8 +59,8 @@ impl Query { /// Returns all the param values as a vector. /// - /// ```text - /// use torrust_tracker_lib::servers::http::v1::query::Query; + /// ```rust + /// use bittorrent_http_protocol::v1::query::Query; /// /// let query = "param1=value1¶m1=value2".parse::().unwrap(); /// @@ -72,8 +72,8 @@ impl Query { /// /// Returns all the param values as a vector even if it has only one value. /// - /// ```text - /// use torrust_tracker_lib::servers::http::v1::query::Query; + /// ```rust + /// use bittorrent_http_protocol::v1::query::Query; /// /// let query = "param1=value1".parse::().unwrap(); /// diff --git a/packages/http-protocol/src/v1/requests/announce.rs b/packages/http-protocol/src/v1/requests/announce.rs index 28cecd386..ea76771dd 100644 --- a/packages/http-protocol/src/v1/requests/announce.rs +++ b/packages/http-protocol/src/v1/requests/announce.rs @@ -29,9 +29,9 @@ const NUMWANT: &str = "numwant"; /// The `Announce` request. Fields use the domain types after parsing the /// query params of the request. /// -/// ```text +/// ```rust /// use aquatic_udp_protocol::{NumberOfBytes, PeerId}; -/// use torrust_tracker_lib::servers::http::v1::requests::announce::{Announce, Compact, Event}; +/// use bittorrent_http_protocol::v1::requests::announce::{Announce, Compact, Event}; /// use bittorrent_primitives::info_hash::InfoHash; /// /// let request = Announce { diff --git a/packages/http-protocol/src/v1/responses/announce.rs b/packages/http-protocol/src/v1/responses/announce.rs index 986a881a5..3854c9f34 100644 --- a/packages/http-protocol/src/v1/responses/announce.rs +++ b/packages/http-protocol/src/v1/responses/announce.rs @@ -130,9 +130,9 @@ impl Into> for Compact { /// A [`NormalPeer`], for the [`Normal`] form. /// -/// ```text +/// ```rust /// use std::net::{IpAddr, Ipv4Addr}; -/// use torrust_tracker_lib::servers::http::v1::responses::announce::{Normal, NormalPeer}; +/// use bittorrent_http_protocol::v1::responses::announce::{Normal, NormalPeer}; /// /// let peer = NormalPeer { /// peer_id: *b"-qB00000000000000001", @@ -182,9 +182,9 @@ impl From<&NormalPeer> for BencodeMut<'_> { /// A part from reducing the size of the response, this format does not contain /// the peer's ID. /// -/// ```text +/// ```rust /// use std::net::{IpAddr, Ipv4Addr}; -/// use torrust_tracker_lib::servers::http::v1::responses::announce::{Compact, CompactPeer, CompactPeerData}; +/// use bittorrent_http_protocol::v1::responses::announce::{Compact, CompactPeer, CompactPeerData}; /// /// let peer = CompactPeer::V4(CompactPeerData { /// ip: Ipv4Addr::new(0x69, 0x69, 0x69, 0x69), // 105.105.105.105 diff --git a/packages/http-protocol/src/v1/responses/error.rs b/packages/http-protocol/src/v1/responses/error.rs index 9aca9c71c..7516cd39e 100644 --- a/packages/http-protocol/src/v1/responses/error.rs +++ b/packages/http-protocol/src/v1/responses/error.rs @@ -26,8 +26,8 @@ pub struct Error { impl Error { /// Returns the bencoded representation of the `Error` struct. /// - /// ```text - /// use torrust_tracker_lib::servers::http::v1::responses::error::Error; + /// ```rust + /// use bittorrent_http_protocol::v1::responses::error::Error; /// /// let err = Error { /// failure_reason: "error message".to_owned(), diff --git a/packages/http-protocol/src/v1/responses/scrape.rs b/packages/http-protocol/src/v1/responses/scrape.rs index a52fa263c..ee4c4155b 100644 --- a/packages/http-protocol/src/v1/responses/scrape.rs +++ b/packages/http-protocol/src/v1/responses/scrape.rs @@ -8,11 +8,11 @@ use torrust_tracker_primitives::core::ScrapeData; /// The `Scrape` response for the HTTP tracker. /// -/// ```text -/// use torrust_tracker_lib::servers::http::v1::responses::scrape::Bencoded; +/// ```rust +/// use bittorrent_http_protocol::v1::responses::scrape::Bencoded; /// use bittorrent_primitives::info_hash::InfoHash; /// use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -/// use torrust_tracker_lib::core::ScrapeData; +/// use torrust_tracker_primitives::core::ScrapeData; /// /// let info_hash = InfoHash::from_bytes(&[0x69; 20]); /// let mut scrape_data = ScrapeData::empty(); diff --git a/packages/http-protocol/src/v1/services/peer_ip_resolver.rs b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs index 366f8820c..f0ad6a83e 100644 --- a/packages/http-protocol/src/v1/services/peer_ip_resolver.rs +++ b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs @@ -59,11 +59,11 @@ pub enum PeerIpResolutionError { /// /// With the tracker running on reverse proxy mode: /// -/// ```text +/// ```rust /// use std::net::IpAddr; /// use std::str::FromStr; /// -/// use torrust_tracker_lib::servers::http::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; +/// use bittorrent_http_protocol::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; /// /// let on_reverse_proxy = true; /// @@ -81,11 +81,11 @@ pub enum PeerIpResolutionError { /// /// With the tracker non running on reverse proxy mode: /// -/// ```text +/// ```rust /// use std::net::IpAddr; /// use std::str::FromStr; /// -/// use torrust_tracker_lib::servers::http::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; +/// use bittorrent_http_protocol::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; /// /// let on_reverse_proxy = false; /// From 40eb805934567fd54619581567786e5ad05003ad Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 Jan 2025 10:01:41 +0000 Subject: [PATCH 0580/1297] refactor: [1182] extract WhitelistManager --- src/core/mod.rs | 174 ++++++++++++++++++++++++++++++++++++------------ 1 file changed, 130 insertions(+), 44 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 6ba8e94ad..066792eb3 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -498,7 +498,7 @@ pub struct Tracker { keys: tokio::sync::RwLock>, /// The list of allowed torrents. Only for listed trackers. - whitelist: tokio::sync::RwLock>, + whitelist_manager: WhiteListManager, /// The in-memory torrents repository. torrents: Arc, @@ -510,6 +510,123 @@ pub struct Tracker { stats_repository: statistics::repository::Repository, } +pub struct WhiteListManager { + /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) + /// or [`MySQL`](crate::core::databases::mysql) + database: Arc>, + + /// The list of allowed torrents. Only for listed trackers. + whitelist: tokio::sync::RwLock>, +} + +impl WhiteListManager { + #[must_use] + pub fn new(database: Arc>) -> Self { + Self { + database, + whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), + } + } + + /// It adds a torrent to the whitelist. + /// Adding torrents is not relevant to public trackers. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. + pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + self.add_torrent_to_database_whitelist(info_hash)?; + self.add_torrent_to_memory_whitelist(info_hash).await; + Ok(()) + } + + /// It adds a torrent to the whitelist if it has not been whitelisted previously + fn add_torrent_to_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; + + if is_whitelisted { + return Ok(()); + } + + self.database.add_info_hash_to_whitelist(*info_hash)?; + + Ok(()) + } + + pub async fn add_torrent_to_memory_whitelist(&self, info_hash: &InfoHash) -> bool { + self.whitelist.write().await.insert(*info_hash) + } + + /// It removes a torrent from the whitelist. + /// Removing torrents is not relevant to public trackers. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. + pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + self.remove_torrent_from_database_whitelist(info_hash)?; + self.remove_torrent_from_memory_whitelist(info_hash).await; + Ok(()) + } + + /// It removes a torrent from the whitelist in the database. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. + pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; + + if !is_whitelisted { + return Ok(()); + } + + self.database.remove_info_hash_from_whitelist(*info_hash)?; + + Ok(()) + } + + /// It removes a torrent from the whitelist in memory. + /// + /// # Context: Whitelist + pub async fn remove_torrent_from_memory_whitelist(&self, info_hash: &InfoHash) -> bool { + self.whitelist.write().await.remove(info_hash) + } + + /// It checks if a torrent is whitelisted. + /// + /// # Context: Whitelist + pub async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { + self.whitelist.read().await.contains(info_hash) + } + + /// It loads the whitelist from the database. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. + pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { + let whitelisted_torrents_from_database = self.database.load_whitelist()?; + let mut whitelist = self.whitelist.write().await; + + whitelist.clear(); + + for info_hash in whitelisted_torrents_from_database { + let _: bool = whitelist.insert(info_hash); + } + + Ok(()) + } +} + /// How many peers the peer announcing wants in the announce response. #[derive(Clone, Debug, PartialEq, Default)] pub enum PeersWanted { @@ -587,7 +704,7 @@ impl Tracker { Ok(Tracker { config: config.clone(), keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), - whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), + whitelist_manager: WhiteListManager::new(database.clone()), torrents: Arc::default(), stats_event_sender, stats_repository, @@ -1068,26 +1185,11 @@ impl Tracker { /// /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.add_torrent_to_database_whitelist(info_hash)?; - self.add_torrent_to_memory_whitelist(info_hash).await; - Ok(()) - } - - /// It adds a torrent to the whitelist if it has not been whitelisted previously - fn add_torrent_to_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; - - if is_whitelisted { - return Ok(()); - } - - self.database.add_info_hash_to_whitelist(*info_hash)?; - - Ok(()) + self.whitelist_manager.add_torrent_to_whitelist(info_hash).await } pub async fn add_torrent_to_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.whitelist.write().await.insert(*info_hash) + self.whitelist_manager.add_torrent_to_memory_whitelist(info_hash).await } /// It removes a torrent from the whitelist. @@ -1099,9 +1201,7 @@ impl Tracker { /// /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.remove_torrent_from_database_whitelist(info_hash)?; - self.remove_torrent_from_memory_whitelist(info_hash).await; - Ok(()) + self.whitelist_manager.remove_torrent_from_whitelist(info_hash).await } /// It removes a torrent from the whitelist in the database. @@ -1112,29 +1212,21 @@ impl Tracker { /// /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; - - if !is_whitelisted { - return Ok(()); - } - - self.database.remove_info_hash_from_whitelist(*info_hash)?; - - Ok(()) + self.whitelist_manager.remove_torrent_from_database_whitelist(info_hash) } /// It removes a torrent from the whitelist in memory. /// /// # Context: Whitelist pub async fn remove_torrent_from_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.whitelist.write().await.remove(info_hash) + self.whitelist_manager.remove_torrent_from_memory_whitelist(info_hash).await } /// It checks if a torrent is whitelisted. /// /// # Context: Whitelist pub async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { - self.whitelist.read().await.contains(info_hash) + self.whitelist_manager.is_info_hash_whitelisted(info_hash).await } /// It loads the whitelist from the database. @@ -1145,16 +1237,7 @@ impl Tracker { /// /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { - let whitelisted_torrents_from_database = self.database.load_whitelist()?; - let mut whitelist = self.whitelist.write().await; - - whitelist.clear(); - - for info_hash in whitelisted_torrents_from_database { - let _: bool = whitelist.insert(info_hash); - } - - Ok(()) + self.whitelist_manager.load_whitelist_from_database().await } /// It return the `Tracker` [`statistics::metrics::Metrics`]. @@ -1821,7 +1904,10 @@ mod tests { tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); // Remove torrent from the in-memory whitelist - tracker.whitelist.write().await.remove(&info_hash); + tracker + .whitelist_manager + .remove_torrent_from_memory_whitelist(&info_hash) + .await; assert!(!tracker.is_info_hash_whitelisted(&info_hash).await); tracker.load_whitelist_from_database().await.unwrap(); From 439493d7ecf7b051f0fc3b1041b346e0a7d69be7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 Jan 2025 10:09:23 +0000 Subject: [PATCH 0581/1297] refactor: [#1182] move extracted service to new mod --- src/core/mod.rs | 119 +------------------------------------ src/core/whitelist/mod.rs | 122 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+), 117 deletions(-) create mode 100644 src/core/whitelist/mod.rs diff --git a/src/core/mod.rs b/src/core/mod.rs index 066792eb3..4b5f97a92 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -445,6 +445,7 @@ pub mod error; pub mod services; pub mod statistics; pub mod torrent; +pub mod whitelist; pub mod peer_tests; @@ -470,6 +471,7 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; use tracing::instrument; +use whitelist::WhiteListManager; use self::auth::Key; use self::error::Error; @@ -510,123 +512,6 @@ pub struct Tracker { stats_repository: statistics::repository::Repository, } -pub struct WhiteListManager { - /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) - /// or [`MySQL`](crate::core::databases::mysql) - database: Arc>, - - /// The list of allowed torrents. Only for listed trackers. - whitelist: tokio::sync::RwLock>, -} - -impl WhiteListManager { - #[must_use] - pub fn new(database: Arc>) -> Self { - Self { - database, - whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), - } - } - - /// It adds a torrent to the whitelist. - /// Adding torrents is not relevant to public trackers. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. - pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.add_torrent_to_database_whitelist(info_hash)?; - self.add_torrent_to_memory_whitelist(info_hash).await; - Ok(()) - } - - /// It adds a torrent to the whitelist if it has not been whitelisted previously - fn add_torrent_to_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; - - if is_whitelisted { - return Ok(()); - } - - self.database.add_info_hash_to_whitelist(*info_hash)?; - - Ok(()) - } - - pub async fn add_torrent_to_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.whitelist.write().await.insert(*info_hash) - } - - /// It removes a torrent from the whitelist. - /// Removing torrents is not relevant to public trackers. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. - pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.remove_torrent_from_database_whitelist(info_hash)?; - self.remove_torrent_from_memory_whitelist(info_hash).await; - Ok(()) - } - - /// It removes a torrent from the whitelist in the database. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. - pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; - - if !is_whitelisted { - return Ok(()); - } - - self.database.remove_info_hash_from_whitelist(*info_hash)?; - - Ok(()) - } - - /// It removes a torrent from the whitelist in memory. - /// - /// # Context: Whitelist - pub async fn remove_torrent_from_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.whitelist.write().await.remove(info_hash) - } - - /// It checks if a torrent is whitelisted. - /// - /// # Context: Whitelist - pub async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { - self.whitelist.read().await.contains(info_hash) - } - - /// It loads the whitelist from the database. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. - pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { - let whitelisted_torrents_from_database = self.database.load_whitelist()?; - let mut whitelist = self.whitelist.write().await; - - whitelist.clear(); - - for info_hash in whitelisted_torrents_from_database { - let _: bool = whitelist.insert(info_hash); - } - - Ok(()) - } -} - /// How many peers the peer announcing wants in the announce response. #[derive(Clone, Debug, PartialEq, Default)] pub enum PeersWanted { diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs new file mode 100644 index 000000000..266bcec23 --- /dev/null +++ b/src/core/whitelist/mod.rs @@ -0,0 +1,122 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; + +use super::databases::{self, Database}; + +pub struct WhiteListManager { + /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) + /// or [`MySQL`](crate::core::databases::mysql) + database: Arc>, + + /// The list of allowed torrents. Only for listed trackers. + whitelist: tokio::sync::RwLock>, +} + +impl WhiteListManager { + #[must_use] + pub fn new(database: Arc>) -> Self { + Self { + database, + whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), + } + } + + /// It adds a torrent to the whitelist. + /// Adding torrents is not relevant to public trackers. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. + pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + self.add_torrent_to_database_whitelist(info_hash)?; + self.add_torrent_to_memory_whitelist(info_hash).await; + Ok(()) + } + + /// It adds a torrent to the whitelist if it has not been whitelisted previously + fn add_torrent_to_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; + + if is_whitelisted { + return Ok(()); + } + + self.database.add_info_hash_to_whitelist(*info_hash)?; + + Ok(()) + } + + pub async fn add_torrent_to_memory_whitelist(&self, info_hash: &InfoHash) -> bool { + self.whitelist.write().await.insert(*info_hash) + } + + /// It removes a torrent from the whitelist. + /// Removing torrents is not relevant to public trackers. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. + pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + self.remove_torrent_from_database_whitelist(info_hash)?; + self.remove_torrent_from_memory_whitelist(info_hash).await; + Ok(()) + } + + /// It removes a torrent from the whitelist in the database. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. + pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; + + if !is_whitelisted { + return Ok(()); + } + + self.database.remove_info_hash_from_whitelist(*info_hash)?; + + Ok(()) + } + + /// It removes a torrent from the whitelist in memory. + /// + /// # Context: Whitelist + pub async fn remove_torrent_from_memory_whitelist(&self, info_hash: &InfoHash) -> bool { + self.whitelist.write().await.remove(info_hash) + } + + /// It checks if a torrent is whitelisted. + /// + /// # Context: Whitelist + pub async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { + self.whitelist.read().await.contains(info_hash) + } + + /// It loads the whitelist from the database. + /// + /// # Context: Whitelist + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. + pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { + let whitelisted_torrents_from_database = self.database.load_whitelist()?; + let mut whitelist = self.whitelist.write().await; + + whitelist.clear(); + + for info_hash in whitelisted_torrents_from_database { + let _: bool = whitelist.insert(info_hash); + } + + Ok(()) + } +} From 39d1620b338a31328ac96aaaa49e327443183c23 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 Jan 2025 10:13:15 +0000 Subject: [PATCH 0582/1297] refactor: [#1182] remove unused methods --- src/core/mod.rs | 24 +----------------------- src/servers/udp/handlers.rs | 2 +- 2 files changed, 2 insertions(+), 24 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 4b5f97a92..875992da5 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -500,7 +500,7 @@ pub struct Tracker { keys: tokio::sync::RwLock>, /// The list of allowed torrents. Only for listed trackers. - whitelist_manager: WhiteListManager, + pub whitelist_manager: WhiteListManager, /// The in-memory torrents repository. torrents: Arc, @@ -1073,10 +1073,6 @@ impl Tracker { self.whitelist_manager.add_torrent_to_whitelist(info_hash).await } - pub async fn add_torrent_to_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.whitelist_manager.add_torrent_to_memory_whitelist(info_hash).await - } - /// It removes a torrent from the whitelist. /// Removing torrents is not relevant to public trackers. /// @@ -1089,24 +1085,6 @@ impl Tracker { self.whitelist_manager.remove_torrent_from_whitelist(info_hash).await } - /// It removes a torrent from the whitelist in the database. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. - pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.whitelist_manager.remove_torrent_from_database_whitelist(info_hash) - } - - /// It removes a torrent from the whitelist in memory. - /// - /// # Context: Whitelist - pub async fn remove_torrent_from_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.whitelist_manager.remove_torrent_from_memory_whitelist(info_hash).await - } - /// It checks if a torrent is whitelisted. /// /// # Context: Whitelist diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 1a9c164e2..3d7d411ce 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -1391,7 +1391,7 @@ mod tests { add_a_seeder(tracker.clone(), &remote_addr, &info_hash).await; - tracker.add_torrent_to_memory_whitelist(&info_hash.0.into()).await; + tracker.whitelist_manager.add_torrent_to_memory_whitelist(&info_hash.0.into()).await; let request = build_scrape_request(&remote_addr, &info_hash); From ea35ba5fa7caae38ace7af089e87c63e19391f54 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 Jan 2025 10:55:37 +0000 Subject: [PATCH 0583/1297] refactor: [#1182] extract struct InMemoryWhitelist --- src/core/whitelist/mod.rs | 134 +++++++++++++++++++++++++++++++------- 1 file changed, 109 insertions(+), 25 deletions(-) diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs index 266bcec23..84469ca37 100644 --- a/src/core/whitelist/mod.rs +++ b/src/core/whitelist/mod.rs @@ -4,13 +4,14 @@ use bittorrent_primitives::info_hash::InfoHash; use super::databases::{self, Database}; +/// It handles the list of allowed torrents. Only for listed trackers. pub struct WhiteListManager { /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) /// or [`MySQL`](crate::core::databases::mysql) database: Arc>, - /// The list of allowed torrents. Only for listed trackers. - whitelist: tokio::sync::RwLock>, + /// The in-memory list of allowed torrents. + in_memory_whitelist: InMemoryWhitelist, } impl WhiteListManager { @@ -18,21 +19,19 @@ impl WhiteListManager { pub fn new(database: Arc>) -> Self { Self { database, - whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), + in_memory_whitelist: InMemoryWhitelist::new(), } } /// It adds a torrent to the whitelist. /// Adding torrents is not relevant to public trackers. /// - /// # Context: Whitelist - /// /// # Errors /// /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { self.add_torrent_to_database_whitelist(info_hash)?; - self.add_torrent_to_memory_whitelist(info_hash).await; + self.in_memory_whitelist.add(info_hash).await; Ok(()) } @@ -49,15 +48,9 @@ impl WhiteListManager { Ok(()) } - pub async fn add_torrent_to_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.whitelist.write().await.insert(*info_hash) - } - /// It removes a torrent from the whitelist. /// Removing torrents is not relevant to public trackers. /// - /// # Context: Whitelist - /// /// # Errors /// /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. @@ -69,8 +62,6 @@ impl WhiteListManager { /// It removes a torrent from the whitelist in the database. /// - /// # Context: Whitelist - /// /// # Errors /// /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. @@ -86,37 +77,130 @@ impl WhiteListManager { Ok(()) } + /// It adds a torrent from the whitelist in memory. + pub async fn add_torrent_to_memory_whitelist(&self, info_hash: &InfoHash) -> bool { + self.in_memory_whitelist.add(info_hash).await + } + /// It removes a torrent from the whitelist in memory. - /// - /// # Context: Whitelist pub async fn remove_torrent_from_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.whitelist.write().await.remove(info_hash) + self.in_memory_whitelist.remove(info_hash).await } /// It checks if a torrent is whitelisted. - /// - /// # Context: Whitelist pub async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { - self.whitelist.read().await.contains(info_hash) + self.in_memory_whitelist.contains(info_hash).await } /// It loads the whitelist from the database. /// - /// # Context: Whitelist - /// /// # Errors /// /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { let whitelisted_torrents_from_database = self.database.load_whitelist()?; - let mut whitelist = self.whitelist.write().await; - whitelist.clear(); + self.in_memory_whitelist.clear().await; for info_hash in whitelisted_torrents_from_database { - let _: bool = whitelist.insert(info_hash); + let _: bool = self.in_memory_whitelist.add(&info_hash).await; } Ok(()) } } + +struct InMemoryWhitelist { + /// The list of allowed torrents. Only for listed trackers. + whitelist: tokio::sync::RwLock>, +} + +impl InMemoryWhitelist { + pub fn new() -> Self { + Self { + whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), + } + } + + /// It adds a torrent from the whitelist in memory. + pub async fn add(&self, info_hash: &InfoHash) -> bool { + self.whitelist.write().await.insert(*info_hash) + } + + /// It removes a torrent from the whitelist in memory. + pub async fn remove(&self, info_hash: &InfoHash) -> bool { + self.whitelist.write().await.remove(info_hash) + } + + /// It checks if it contains an info-hash. + pub async fn contains(&self, info_hash: &InfoHash) -> bool { + self.whitelist.read().await.contains(info_hash) + } + + /// It clears the whitelist. + pub async fn clear(&self) { + let mut whitelist = self.whitelist.write().await; + whitelist.clear(); + } +} + +#[cfg(test)] +mod tests { + use bittorrent_primitives::info_hash::InfoHash; + + fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() // # DevSkim: ignore DS173237 + } + + mod in_memory_whitelist { + + use crate::core::whitelist::tests::sample_info_hash; + use crate::core::whitelist::InMemoryWhitelist; + + #[tokio::test] + async fn should_allow_adding_a_new_torrent_to_the_whitelist() { + let info_hash = sample_info_hash(); + + let whitelist = InMemoryWhitelist::new(); + + whitelist.add(&info_hash).await; + + assert!(whitelist.contains(&info_hash).await); + } + + #[tokio::test] + async fn should_allow_removing_a_new_torrent_to_the_whitelist() { + let info_hash = sample_info_hash(); + + let whitelist = InMemoryWhitelist::new(); + + whitelist.add(&info_hash).await; + whitelist.remove(&sample_info_hash()).await; + + assert!(!whitelist.contains(&info_hash).await); + } + + #[tokio::test] + async fn should_allow_clearing_the_whitelist() { + let info_hash = sample_info_hash(); + + let whitelist = InMemoryWhitelist::new(); + + whitelist.add(&info_hash).await; + whitelist.clear().await; + + assert!(!whitelist.contains(&info_hash).await); + } + + #[tokio::test] + async fn should_allow_checking_if_an_infohash_is_whitelisted() { + let info_hash = sample_info_hash(); + + let whitelist = InMemoryWhitelist::new(); + + whitelist.add(&info_hash).await; + + assert!(whitelist.contains(&info_hash).await); + } + } +} From 07f53a4ad665c33a2047867075c0657700cb7260 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 Jan 2025 11:09:42 +0000 Subject: [PATCH 0584/1297] refactor: [#1182] extract strcut DatabaseWhitelist --- src/core/whitelist/mod.rs | 98 ++++++++++++++++++++++++++------------- 1 file changed, 66 insertions(+), 32 deletions(-) diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs index 84469ca37..97affa1ea 100644 --- a/src/core/whitelist/mod.rs +++ b/src/core/whitelist/mod.rs @@ -6,20 +6,19 @@ use super::databases::{self, Database}; /// It handles the list of allowed torrents. Only for listed trackers. pub struct WhiteListManager { - /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) - /// or [`MySQL`](crate::core::databases::mysql) - database: Arc>, - /// The in-memory list of allowed torrents. in_memory_whitelist: InMemoryWhitelist, + + /// The persisted list of allowed torrents. + database_whitelist: DatabaseWhitelist, } impl WhiteListManager { #[must_use] pub fn new(database: Arc>) -> Self { Self { - database, in_memory_whitelist: InMemoryWhitelist::new(), + database_whitelist: DatabaseWhitelist::new(database), } } @@ -30,24 +29,11 @@ impl WhiteListManager { /// /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.add_torrent_to_database_whitelist(info_hash)?; + self.database_whitelist.add_torrent_to_database_whitelist(info_hash)?; self.in_memory_whitelist.add(info_hash).await; Ok(()) } - /// It adds a torrent to the whitelist if it has not been whitelisted previously - fn add_torrent_to_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; - - if is_whitelisted { - return Ok(()); - } - - self.database.add_info_hash_to_whitelist(*info_hash)?; - - Ok(()) - } - /// It removes a torrent from the whitelist. /// Removing torrents is not relevant to public trackers. /// @@ -55,8 +41,8 @@ impl WhiteListManager { /// /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.remove_torrent_from_database_whitelist(info_hash)?; - self.remove_torrent_from_memory_whitelist(info_hash).await; + self.database_whitelist.remove_torrent_from_database_whitelist(info_hash)?; + self.in_memory_whitelist.remove(info_hash).await; Ok(()) } @@ -66,15 +52,7 @@ impl WhiteListManager { /// /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; - - if !is_whitelisted { - return Ok(()); - } - - self.database.remove_info_hash_from_whitelist(*info_hash)?; - - Ok(()) + self.database_whitelist.remove_torrent_from_database_whitelist(info_hash) } /// It adds a torrent from the whitelist in memory. @@ -98,7 +76,7 @@ impl WhiteListManager { /// /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { - let whitelisted_torrents_from_database = self.database.load_whitelist()?; + let whitelisted_torrents_from_database = self.database_whitelist.load_whitelist_from_database()?; self.in_memory_whitelist.clear().await; @@ -110,8 +88,9 @@ impl WhiteListManager { } } +/// The in-memory list of allowed torrents. struct InMemoryWhitelist { - /// The list of allowed torrents. Only for listed trackers. + /// The list of allowed torrents. whitelist: tokio::sync::RwLock>, } @@ -144,6 +123,59 @@ impl InMemoryWhitelist { } } +/// The persisted list of allowed torrents. +struct DatabaseWhitelist { + /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) + /// or [`MySQL`](crate::core::databases::mysql) + database: Arc>, +} + +impl DatabaseWhitelist { + #[must_use] + pub fn new(database: Arc>) -> Self { + Self { database } + } + + /// It adds a torrent to the whitelist if it has not been whitelisted previously + fn add_torrent_to_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; + + if is_whitelisted { + return Ok(()); + } + + self.database.add_info_hash_to_whitelist(*info_hash)?; + + Ok(()) + } + + /// It removes a torrent from the whitelist in the database. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. + pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; + + if !is_whitelisted { + return Ok(()); + } + + self.database.remove_info_hash_from_whitelist(*info_hash)?; + + Ok(()) + } + + /// It loads the whitelist from the database. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. + pub fn load_whitelist_from_database(&self) -> Result, databases::error::Error> { + self.database.load_whitelist() + } +} + #[cfg(test)] mod tests { use bittorrent_primitives::info_hash::InfoHash; @@ -203,4 +235,6 @@ mod tests { assert!(whitelist.contains(&info_hash).await); } } + + mod database_whitelist {} } From cc2bc7bb8e54772fac42523dc8b412429df5a0b7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 Jan 2025 11:17:48 +0000 Subject: [PATCH 0585/1297] refactor: [#1182] move structs to new mods in whitelist --- src/core/whitelist/in_memory.rs | 88 +++++++++++++++++ src/core/whitelist/mod.rs | 166 ++------------------------------ src/core/whitelist/persisted.rs | 62 ++++++++++++ src/servers/udp/handlers.rs | 5 +- 4 files changed, 164 insertions(+), 157 deletions(-) create mode 100644 src/core/whitelist/in_memory.rs create mode 100644 src/core/whitelist/persisted.rs diff --git a/src/core/whitelist/in_memory.rs b/src/core/whitelist/in_memory.rs new file mode 100644 index 000000000..78e0eb11f --- /dev/null +++ b/src/core/whitelist/in_memory.rs @@ -0,0 +1,88 @@ +use bittorrent_primitives::info_hash::InfoHash; + +/// The in-memory list of allowed torrents. +#[derive(Debug, Default)] +pub struct InMemoryWhitelist { + /// The list of allowed torrents. + whitelist: tokio::sync::RwLock>, +} + +impl InMemoryWhitelist { + /// It adds a torrent from the whitelist in memory. + pub async fn add(&self, info_hash: &InfoHash) -> bool { + self.whitelist.write().await.insert(*info_hash) + } + + /// It removes a torrent from the whitelist in memory. + pub async fn remove(&self, info_hash: &InfoHash) -> bool { + self.whitelist.write().await.remove(info_hash) + } + + /// It checks if it contains an info-hash. + pub async fn contains(&self, info_hash: &InfoHash) -> bool { + self.whitelist.read().await.contains(info_hash) + } + + /// It clears the whitelist. + pub async fn clear(&self) { + let mut whitelist = self.whitelist.write().await; + whitelist.clear(); + } +} + +#[cfg(test)] +mod tests { + use bittorrent_primitives::info_hash::InfoHash; + + use crate::core::whitelist::in_memory::InMemoryWhitelist; + + fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() // # DevSkim: ignore DS173237 + } + + #[tokio::test] + async fn should_allow_adding_a_new_torrent_to_the_whitelist() { + let info_hash = sample_info_hash(); + + let whitelist = InMemoryWhitelist::default(); + + whitelist.add(&info_hash).await; + + assert!(whitelist.contains(&info_hash).await); + } + + #[tokio::test] + async fn should_allow_removing_a_new_torrent_to_the_whitelist() { + let info_hash = sample_info_hash(); + + let whitelist = InMemoryWhitelist::default(); + + whitelist.add(&info_hash).await; + whitelist.remove(&sample_info_hash()).await; + + assert!(!whitelist.contains(&info_hash).await); + } + + #[tokio::test] + async fn should_allow_clearing_the_whitelist() { + let info_hash = sample_info_hash(); + + let whitelist = InMemoryWhitelist::default(); + + whitelist.add(&info_hash).await; + whitelist.clear().await; + + assert!(!whitelist.contains(&info_hash).await); + } + + #[tokio::test] + async fn should_allow_checking_if_an_infohash_is_whitelisted() { + let info_hash = sample_info_hash(); + + let whitelist = InMemoryWhitelist::default(); + + whitelist.add(&info_hash).await; + + assert!(whitelist.contains(&info_hash).await); + } +} diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs index 97affa1ea..5096bacc9 100644 --- a/src/core/whitelist/mod.rs +++ b/src/core/whitelist/mod.rs @@ -1,6 +1,11 @@ +pub mod in_memory; +pub mod persisted; + use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; +use in_memory::InMemoryWhitelist; +use persisted::DatabaseWhitelist; use super::databases::{self, Database}; @@ -17,7 +22,7 @@ impl WhiteListManager { #[must_use] pub fn new(database: Arc>) -> Self { Self { - in_memory_whitelist: InMemoryWhitelist::new(), + in_memory_whitelist: InMemoryWhitelist::default(), database_whitelist: DatabaseWhitelist::new(database), } } @@ -29,7 +34,7 @@ impl WhiteListManager { /// /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.database_whitelist.add_torrent_to_database_whitelist(info_hash)?; + self.database_whitelist.add(info_hash)?; self.in_memory_whitelist.add(info_hash).await; Ok(()) } @@ -41,7 +46,7 @@ impl WhiteListManager { /// /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.database_whitelist.remove_torrent_from_database_whitelist(info_hash)?; + self.database_whitelist.remove(info_hash)?; self.in_memory_whitelist.remove(info_hash).await; Ok(()) } @@ -52,7 +57,7 @@ impl WhiteListManager { /// /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.database_whitelist.remove_torrent_from_database_whitelist(info_hash) + self.database_whitelist.remove(info_hash) } /// It adds a torrent from the whitelist in memory. @@ -76,7 +81,7 @@ impl WhiteListManager { /// /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { - let whitelisted_torrents_from_database = self.database_whitelist.load_whitelist_from_database()?; + let whitelisted_torrents_from_database = self.database_whitelist.load_from_database()?; self.in_memory_whitelist.clear().await; @@ -87,154 +92,3 @@ impl WhiteListManager { Ok(()) } } - -/// The in-memory list of allowed torrents. -struct InMemoryWhitelist { - /// The list of allowed torrents. - whitelist: tokio::sync::RwLock>, -} - -impl InMemoryWhitelist { - pub fn new() -> Self { - Self { - whitelist: tokio::sync::RwLock::new(std::collections::HashSet::new()), - } - } - - /// It adds a torrent from the whitelist in memory. - pub async fn add(&self, info_hash: &InfoHash) -> bool { - self.whitelist.write().await.insert(*info_hash) - } - - /// It removes a torrent from the whitelist in memory. - pub async fn remove(&self, info_hash: &InfoHash) -> bool { - self.whitelist.write().await.remove(info_hash) - } - - /// It checks if it contains an info-hash. - pub async fn contains(&self, info_hash: &InfoHash) -> bool { - self.whitelist.read().await.contains(info_hash) - } - - /// It clears the whitelist. - pub async fn clear(&self) { - let mut whitelist = self.whitelist.write().await; - whitelist.clear(); - } -} - -/// The persisted list of allowed torrents. -struct DatabaseWhitelist { - /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) - /// or [`MySQL`](crate::core::databases::mysql) - database: Arc>, -} - -impl DatabaseWhitelist { - #[must_use] - pub fn new(database: Arc>) -> Self { - Self { database } - } - - /// It adds a torrent to the whitelist if it has not been whitelisted previously - fn add_torrent_to_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; - - if is_whitelisted { - return Ok(()); - } - - self.database.add_info_hash_to_whitelist(*info_hash)?; - - Ok(()) - } - - /// It removes a torrent from the whitelist in the database. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. - pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; - - if !is_whitelisted { - return Ok(()); - } - - self.database.remove_info_hash_from_whitelist(*info_hash)?; - - Ok(()) - } - - /// It loads the whitelist from the database. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. - pub fn load_whitelist_from_database(&self) -> Result, databases::error::Error> { - self.database.load_whitelist() - } -} - -#[cfg(test)] -mod tests { - use bittorrent_primitives::info_hash::InfoHash; - - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() // # DevSkim: ignore DS173237 - } - - mod in_memory_whitelist { - - use crate::core::whitelist::tests::sample_info_hash; - use crate::core::whitelist::InMemoryWhitelist; - - #[tokio::test] - async fn should_allow_adding_a_new_torrent_to_the_whitelist() { - let info_hash = sample_info_hash(); - - let whitelist = InMemoryWhitelist::new(); - - whitelist.add(&info_hash).await; - - assert!(whitelist.contains(&info_hash).await); - } - - #[tokio::test] - async fn should_allow_removing_a_new_torrent_to_the_whitelist() { - let info_hash = sample_info_hash(); - - let whitelist = InMemoryWhitelist::new(); - - whitelist.add(&info_hash).await; - whitelist.remove(&sample_info_hash()).await; - - assert!(!whitelist.contains(&info_hash).await); - } - - #[tokio::test] - async fn should_allow_clearing_the_whitelist() { - let info_hash = sample_info_hash(); - - let whitelist = InMemoryWhitelist::new(); - - whitelist.add(&info_hash).await; - whitelist.clear().await; - - assert!(!whitelist.contains(&info_hash).await); - } - - #[tokio::test] - async fn should_allow_checking_if_an_infohash_is_whitelisted() { - let info_hash = sample_info_hash(); - - let whitelist = InMemoryWhitelist::new(); - - whitelist.add(&info_hash).await; - - assert!(whitelist.contains(&info_hash).await); - } - } - - mod database_whitelist {} -} diff --git a/src/core/whitelist/persisted.rs b/src/core/whitelist/persisted.rs new file mode 100644 index 000000000..993060139 --- /dev/null +++ b/src/core/whitelist/persisted.rs @@ -0,0 +1,62 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; + +use super::databases::{self, Database}; + +/// The persisted list of allowed torrents. +pub struct DatabaseWhitelist { + /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) + /// or [`MySQL`](crate::core::databases::mysql) + database: Arc>, +} + +impl DatabaseWhitelist { + #[must_use] + pub fn new(database: Arc>) -> Self { + Self { database } + } + + /// It adds a torrent to the whitelist if it has not been whitelisted previously + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `info_hash` to the whitelist database. + pub fn add(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; + + if is_whitelisted { + return Ok(()); + } + + self.database.add_info_hash_to_whitelist(*info_hash)?; + + Ok(()) + } + + /// It removes a torrent from the whitelist in the database. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. + pub fn remove(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; + + if !is_whitelisted { + return Ok(()); + } + + self.database.remove_info_hash_from_whitelist(*info_hash)?; + + Ok(()) + } + + /// It loads the whitelist from the database. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. + pub fn load_from_database(&self) -> Result, databases::error::Error> { + self.database.load_whitelist() + } +} diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 3d7d411ce..62f7d0a02 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -1391,7 +1391,10 @@ mod tests { add_a_seeder(tracker.clone(), &remote_addr, &info_hash).await; - tracker.whitelist_manager.add_torrent_to_memory_whitelist(&info_hash.0.into()).await; + tracker + .whitelist_manager + .add_torrent_to_memory_whitelist(&info_hash.0.into()) + .await; let request = build_scrape_request(&remote_addr, &info_hash); From 2f1abeb873a7c9d273247d064f61163ef3bf0168 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 Jan 2025 16:14:51 +0000 Subject: [PATCH 0586/1297] refactor: [#1182] inject database and whitelist in tracker as dep Inject the database (persistence) and whitelist manager into the Tracker via the contructor to be able to use the whitelist manager directly in Axum handlers. --- src/core/mod.rs | 17 ++-- src/core/services/mod.rs | 38 +++++++- src/core/whitelist/mod.rs | 8 +- src/servers/http/v1/services/announce.rs | 43 +++++---- src/servers/http/v1/services/scrape.rs | 67 ++++++-------- src/servers/udp/handlers.rs | 109 ++++++++++------------- 6 files changed, 140 insertions(+), 142 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 875992da5..5f9d44fdb 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -457,11 +457,9 @@ use std::time::Duration; use auth::PeerKey; use bittorrent_primitives::info_hash::InfoHash; -use databases::driver::Driver; use error::PeerKeyError; use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; -use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_located_error::Located; use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; @@ -500,7 +498,7 @@ pub struct Tracker { keys: tokio::sync::RwLock>, /// The list of allowed torrents. Only for listed trackers. - pub whitelist_manager: WhiteListManager, + pub whitelist_manager: Arc, /// The in-memory torrents repository. torrents: Arc, @@ -576,24 +574,19 @@ impl Tracker { /// Will return a `databases::error::Error` if unable to connect to database. The `Tracker` is responsible for the persistence. pub fn new( config: &Core, + database: &Arc>, + whitelist_manager: &Arc, stats_event_sender: Option>, stats_repository: statistics::repository::Repository, ) -> Result { - let driver = match config.database.driver { - database::Driver::Sqlite3 => Driver::Sqlite3, - database::Driver::MySQL => Driver::MySQL, - }; - - let database = Arc::new(databases::driver::build(&driver, &config.database.path)?); - Ok(Tracker { config: config.clone(), + database: database.clone(), keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), - whitelist_manager: WhiteListManager::new(database.clone()), + whitelist_manager: whitelist_manager.clone(), torrents: Arc::default(), stats_event_sender, stats_repository, - database, }) } diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index 166f40df4..67d5113bc 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -9,8 +9,13 @@ pub mod torrent; use std::sync::Arc; +use databases::driver::Driver; +use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::Configuration; +use super::databases::{self, Database}; +use super::whitelist::persisted::DatabaseWhitelist; +use super::whitelist::WhiteListManager; use crate::core::Tracker; /// It returns a new tracker building its dependencies. @@ -20,14 +25,41 @@ use crate::core::Tracker; /// Will panic if tracker cannot be instantiated. #[must_use] pub fn tracker_factory(config: &Configuration) -> Tracker { - // Initialize statistics + let database = initialize_database(config); + + let whitelist_manager = initialize_whitelist(database.clone()); + let (stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - // Initialize Torrust tracker - match Tracker::new(&Arc::new(config).core, stats_event_sender, stats_repository) { + match Tracker::new( + &Arc::new(config).core, + &database, + &whitelist_manager, + stats_event_sender, + stats_repository, + ) { Ok(tracker) => tracker, Err(error) => { panic!("{}", error) } } } + +/// # Panics +/// +/// Will panic if database cannot be initialized. +#[must_use] +pub fn initialize_database(config: &Configuration) -> Arc> { + let driver = match config.core.database.driver { + database::Driver::Sqlite3 => Driver::Sqlite3, + database::Driver::MySQL => Driver::MySQL, + }; + + Arc::new(databases::driver::build(&driver, &config.core.database.path).expect("Database driver build failed.")) +} + +#[must_use] +pub fn initialize_whitelist(database: Arc>) -> Arc { + let database_whitelist = Arc::new(DatabaseWhitelist::new(database)); + Arc::new(WhiteListManager::new(database_whitelist)) +} diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs index 5096bacc9..3a88b404c 100644 --- a/src/core/whitelist/mod.rs +++ b/src/core/whitelist/mod.rs @@ -7,7 +7,7 @@ use bittorrent_primitives::info_hash::InfoHash; use in_memory::InMemoryWhitelist; use persisted::DatabaseWhitelist; -use super::databases::{self, Database}; +use super::databases::{self}; /// It handles the list of allowed torrents. Only for listed trackers. pub struct WhiteListManager { @@ -15,15 +15,15 @@ pub struct WhiteListManager { in_memory_whitelist: InMemoryWhitelist, /// The persisted list of allowed torrents. - database_whitelist: DatabaseWhitelist, + database_whitelist: Arc, } impl WhiteListManager { #[must_use] - pub fn new(database: Arc>) -> Self { + pub fn new(database_whitelist: Arc) -> Self { Self { in_memory_whitelist: InMemoryWhitelist::default(), - database_whitelist: DatabaseWhitelist::new(database), + database_whitelist, } } diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index df827aee2..06aad669f 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -107,10 +107,28 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; + use crate::core::services::{initialize_database, initialize_whitelist}; use crate::core::{statistics, PeersWanted, Tracker}; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; + fn test_tracker_factory(stats_event_sender: Option>) -> Tracker { + let config = configuration::ephemeral(); + + let database = initialize_database(&config); + + let whitelist_manager = initialize_whitelist(database.clone()); + + Tracker::new( + &config.core, + &database, + &whitelist_manager, + stats_event_sender, + statistics::repository::Repository::new(), + ) + .unwrap() + } + #[tokio::test] async fn it_should_return_the_announce_data() { let tracker = Arc::new(public_tracker()); @@ -142,14 +160,7 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - Tracker::new( - &configuration::ephemeral().core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap(), - ); + let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); let mut peer = sample_peer_using_ipv4(); @@ -162,12 +173,7 @@ mod tests { 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, ))); - Tracker::new( - &configuration.core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap() + test_tracker_factory(Some(stats_event_sender)) } fn peer_with_the_ipv4_loopback_ip() -> peer::Peer { @@ -213,14 +219,7 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - Tracker::new( - &configuration::ephemeral().core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap(), - ); + let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); let mut peer = sample_peer_using_ipv6(); diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 80d81d78a..6ab11bb4a 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -67,8 +67,8 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::core::services::tracker_factory; - use crate::core::Tracker; + use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; + use crate::core::{statistics, Tracker}; fn public_tracker() -> Tracker { tracker_factory(&configuration::ephemeral_public()) @@ -94,6 +94,23 @@ mod tests { } } + fn test_tracker_factory(stats_event_sender: Option>) -> Tracker { + let config = configuration::ephemeral(); + + let database = initialize_database(&config); + + let whitelist_manager = initialize_whitelist(database.clone()); + + Tracker::new( + &config.core, + &database, + &whitelist_manager, + stats_event_sender, + statistics::repository::Repository::new(), + ) + .unwrap() + } + mod with_real_data { use std::future; @@ -103,12 +120,11 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use torrust_tracker_test_helpers::configuration; - use crate::core::{statistics, PeersWanted, Tracker}; + use crate::core::{statistics, PeersWanted}; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ - public_tracker, sample_info_hash, sample_info_hashes, sample_peer, + public_tracker, sample_info_hash, sample_info_hashes, sample_peer, test_tracker_factory, }; #[tokio::test] @@ -148,14 +164,7 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - Tracker::new( - &configuration::ephemeral().core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap(), - ); + let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); @@ -172,14 +181,7 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - Tracker::new( - &configuration::ephemeral().core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap(), - ); + let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); @@ -195,12 +197,11 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; - use torrust_tracker_test_helpers::configuration; - use crate::core::{statistics, PeersWanted, Tracker}; + use crate::core::{statistics, PeersWanted}; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ - public_tracker, sample_info_hash, sample_info_hashes, sample_peer, + public_tracker, sample_info_hash, sample_info_hashes, sample_peer, test_tracker_factory, }; #[tokio::test] @@ -232,14 +233,7 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - Tracker::new( - &configuration::ephemeral().core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap(), - ); + let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); @@ -256,14 +250,7 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - Tracker::new( - &configuration::ephemeral().core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap(), - ); + let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 62f7d0a02..5fc695f88 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -435,8 +435,8 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::gen_remote_fingerprint; - use crate::core::services::tracker_factory; - use crate::core::Tracker; + use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; + use crate::core::{statistics, Tracker}; use crate::CurrentClock; fn tracker_configuration() -> Configuration { @@ -553,6 +553,23 @@ mod tests { } } + fn test_tracker_factory(stats_event_sender: Option>) -> Tracker { + let config = tracker_configuration(); + + let database = initialize_database(&config); + + let whitelist_manager = initialize_whitelist(database.clone()); + + Tracker::new( + &config.core, + &database, + &whitelist_manager, + stats_event_sender, + statistics::repository::Repository::new(), + ) + .unwrap() + } + mod connect_request { use std::future; @@ -561,13 +578,13 @@ mod tests { use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; use mockall::predicate::eq; - use super::{sample_ipv4_socket_address, sample_ipv6_remote_addr, tracker_configuration}; - use crate::core::{self, statistics}; + use super::{sample_ipv4_socket_address, sample_ipv6_remote_addr}; + use crate::core::statistics; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_connect; use crate::servers::udp::handlers::tests::{ public_tracker, sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv6_remote_addr_fingerprint, - sample_issue_time, + sample_issue_time, test_tracker_factory, }; fn sample_connect_request() -> ConnectRequest { @@ -639,14 +656,7 @@ mod tests { let client_socket_address = sample_ipv4_socket_address(); - let torrent_tracker = Arc::new( - core::Tracker::new( - &tracker_configuration().core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap(), - ); + let torrent_tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); handle_connect( client_socket_address, &sample_connect_request(), @@ -666,14 +676,7 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let torrent_tracker = Arc::new( - core::Tracker::new( - &tracker_configuration().core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap(), - ); + let torrent_tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); handle_connect( sample_ipv6_remote_addr(), &sample_connect_request(), @@ -774,7 +777,7 @@ mod tests { use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ gen_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, sample_issue_time, - tracker_configuration, TorrentPeerBuilder, + test_tracker_factory, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; @@ -927,14 +930,7 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - core::Tracker::new( - &tracker_configuration().core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap(), - ); + let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); handle_announce( sample_ipv4_socket_address(), @@ -1013,7 +1009,7 @@ mod tests { use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ gen_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, sample_issue_time, - tracker_configuration, TorrentPeerBuilder, + test_tracker_factory, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; @@ -1173,14 +1169,7 @@ mod tests { .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let stats_event_sender = Box::new(stats_event_sender_mock); - let tracker = Arc::new( - core::Tracker::new( - &tracker_configuration().core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap(), - ); + let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); let remote_addr = sample_ipv6_remote_addr(); @@ -1200,6 +1189,7 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; use crate::core; + use crate::core::services::{initialize_database, initialize_whitelist}; use crate::core::statistics::keeper::Keeper; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; @@ -1211,9 +1201,20 @@ mod tests { #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let configuration = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); + let database = initialize_database(&configuration); + let whitelist_manager = initialize_whitelist(database.clone()); let (stats_event_sender, stats_repository) = Keeper::new_active_instance(); - let tracker = - Arc::new(core::Tracker::new(&configuration.core, Some(stats_event_sender), stats_repository).unwrap()); + + let tracker = Arc::new( + core::Tracker::new( + &configuration.core, + &database, + &whitelist_manager, + Some(stats_event_sender), + stats_repository, + ) + .unwrap(), + ); let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); @@ -1456,10 +1457,10 @@ mod tests { use mockall::predicate::eq; use super::sample_scrape_request; - use crate::core::{self, statistics}; + use crate::core::statistics; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ - sample_cookie_valid_range, sample_ipv4_remote_addr, tracker_configuration, + sample_cookie_valid_range, sample_ipv4_remote_addr, test_tracker_factory, }; #[tokio::test] @@ -1473,14 +1474,7 @@ mod tests { let stats_event_sender = Box::new(stats_event_sender_mock); let remote_addr = sample_ipv4_remote_addr(); - let tracker = Arc::new( - core::Tracker::new( - &tracker_configuration().core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap(), - ); + let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); handle_scrape( remote_addr, @@ -1500,10 +1494,10 @@ mod tests { use mockall::predicate::eq; use super::sample_scrape_request; - use crate::core::{self, statistics}; + use crate::core::statistics; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ - sample_cookie_valid_range, sample_ipv6_remote_addr, tracker_configuration, + sample_cookie_valid_range, sample_ipv6_remote_addr, test_tracker_factory, }; #[tokio::test] @@ -1517,14 +1511,7 @@ mod tests { let stats_event_sender = Box::new(stats_event_sender_mock); let remote_addr = sample_ipv6_remote_addr(); - let tracker = Arc::new( - core::Tracker::new( - &tracker_configuration().core, - Some(stats_event_sender), - statistics::repository::Repository::new(), - ) - .unwrap(), - ); + let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); handle_scrape( remote_addr, From 4253d0f7b62d5e8bf9bb1e757ef3b20347992491 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 Jan 2025 16:30:18 +0000 Subject: [PATCH 0587/1297] refactor: [#1182] use WhitelistManager in API handlers directly, instead of using it via the Tracker. --- src/servers/apis/v1/context/whitelist/handlers.rs | 14 +++++++------- src/servers/apis/v1/context/whitelist/routes.rs | 11 +++++++---- src/servers/apis/v1/routes.rs | 2 +- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/src/servers/apis/v1/context/whitelist/handlers.rs index 04085f8ab..f548f5dc4 100644 --- a/src/servers/apis/v1/context/whitelist/handlers.rs +++ b/src/servers/apis/v1/context/whitelist/handlers.rs @@ -10,7 +10,7 @@ use bittorrent_primitives::info_hash::InfoHash; use super::responses::{ failed_to_reload_whitelist_response, failed_to_remove_torrent_from_whitelist_response, failed_to_whitelist_torrent_response, }; -use crate::core::Tracker; +use crate::core::whitelist::WhiteListManager; use crate::servers::apis::v1::responses::{invalid_info_hash_param_response, ok_response}; use crate::servers::apis::InfoHashParam; @@ -24,12 +24,12 @@ use crate::servers::apis::InfoHashParam; /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#add-a-torrent-to-the-whitelist) /// for more information about this endpoint. pub async fn add_torrent_to_whitelist_handler( - State(tracker): State>, + State(whitelist_manager): State>, Path(info_hash): Path, ) -> Response { match InfoHash::from_str(&info_hash.0) { Err(_) => invalid_info_hash_param_response(&info_hash.0), - Ok(info_hash) => match tracker.add_torrent_to_whitelist(&info_hash).await { + Ok(info_hash) => match whitelist_manager.add_torrent_to_whitelist(&info_hash).await { Ok(()) => ok_response(), Err(e) => failed_to_whitelist_torrent_response(e), }, @@ -47,12 +47,12 @@ pub async fn add_torrent_to_whitelist_handler( /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#remove-a-torrent-from-the-whitelist) /// for more information about this endpoint. pub async fn remove_torrent_from_whitelist_handler( - State(tracker): State>, + State(whitelist_manager): State>, Path(info_hash): Path, ) -> Response { match InfoHash::from_str(&info_hash.0) { Err(_) => invalid_info_hash_param_response(&info_hash.0), - Ok(info_hash) => match tracker.remove_torrent_from_whitelist(&info_hash).await { + Ok(info_hash) => match whitelist_manager.remove_torrent_from_whitelist(&info_hash).await { Ok(()) => ok_response(), Err(e) => failed_to_remove_torrent_from_whitelist_response(e), }, @@ -69,8 +69,8 @@ pub async fn remove_torrent_from_whitelist_handler( /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#reload-the-whitelist) /// for more information about this endpoint. -pub async fn reload_whitelist_handler(State(tracker): State>) -> Response { - match tracker.load_whitelist_from_database().await { +pub async fn reload_whitelist_handler(State(whitelist_manager): State>) -> Response { + match whitelist_manager.load_whitelist_from_database().await { Ok(()) => ok_response(), Err(e) => failed_to_reload_whitelist_response(e), } diff --git a/src/servers/apis/v1/context/whitelist/routes.rs b/src/servers/apis/v1/context/whitelist/routes.rs index 35312ea97..c58aa7177 100644 --- a/src/servers/apis/v1/context/whitelist/routes.rs +++ b/src/servers/apis/v1/context/whitelist/routes.rs @@ -14,19 +14,22 @@ use super::handlers::{add_torrent_to_whitelist_handler, reload_whitelist_handler use crate::core::Tracker; /// It adds the routes to the router for the [`whitelist`](crate::servers::apis::v1::context::whitelist) API context. -pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { +pub fn add(prefix: &str, router: Router, tracker: &Arc) -> Router { let prefix = format!("{prefix}/whitelist"); router // Whitelisted torrents .route( &format!("{prefix}/{{info_hash}}"), - post(add_torrent_to_whitelist_handler).with_state(tracker.clone()), + post(add_torrent_to_whitelist_handler).with_state(tracker.whitelist_manager.clone()), ) .route( &format!("{prefix}/{{info_hash}}"), - delete(remove_torrent_from_whitelist_handler).with_state(tracker.clone()), + delete(remove_torrent_from_whitelist_handler).with_state(tracker.whitelist_manager.clone()), ) // Whitelist commands - .route(&format!("{prefix}/reload"), get(reload_whitelist_handler).with_state(tracker)) + .route( + &format!("{prefix}/reload"), + get(reload_whitelist_handler).with_state(tracker.whitelist_manager.clone()), + ) } diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs index 23ef6c47e..4c97c7578 100644 --- a/src/servers/apis/v1/routes.rs +++ b/src/servers/apis/v1/routes.rs @@ -14,7 +14,7 @@ pub fn add(prefix: &str, router: Router, tracker: Arc, ban_service: Arc let router = auth_key::routes::add(&v1_prefix, router, tracker.clone()); let router = stats::routes::add(&v1_prefix, router, tracker.clone(), ban_service); - let router = whitelist::routes::add(&v1_prefix, router, tracker.clone()); + let router = whitelist::routes::add(&v1_prefix, router, &tracker); torrent::routes::add(&v1_prefix, router, tracker) } From 658d2be631be303eaaaf4e35260d3bfe0f89769a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 Jan 2025 17:09:56 +0000 Subject: [PATCH 0588/1297] refactor: [#1182] inject database and whitelist manager in tracker factory Refactor in progress. The final goal is to inject the whitelist manager directly wherever is needed (for example, test evns) to avoid injecting the whole tracker. Adn to finally remove the whitelist manager from the Tracker (A higer level refator in progress: remove responsabilities fromcore Tracker). --- src/bootstrap/app.rs | 8 +++-- src/core/mod.rs | 25 ++++++++++----- src/core/services/mod.rs | 14 ++++----- src/core/services/statistics/mod.rs | 7 +++-- src/core/services/torrent.rs | 39 ++++++++++++++++++------ src/servers/http/v1/handlers/announce.rs | 22 ++++++++++--- src/servers/http/v1/handlers/scrape.rs | 22 ++++++++++--- src/servers/http/v1/services/announce.rs | 7 +++-- src/servers/http/v1/services/scrape.rs | 5 ++- src/servers/udp/handlers.rs | 4 ++- 10 files changed, 112 insertions(+), 41 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 38b7d40c5..9be52359b 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -21,7 +21,7 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; -use crate::core::services::tracker_factory; +use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -105,7 +105,11 @@ pub fn initialize_static() { #[must_use] #[instrument(skip(config))] pub fn initialize_tracker(config: &Configuration) -> Tracker { - tracker_factory(config) + let database = initialize_database(config); + + let whitelist_manager = initialize_whitelist(database.clone()); + + tracker_factory(config, &database, &whitelist_manager) } /// It initializes the log threshold, format and channel. diff --git a/src/core/mod.rs b/src/core/mod.rs index 5f9d44fdb..51d330880 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -1154,25 +1154,36 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::core::peer::Peer; - use crate::core::services::tracker_factory; + use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; use crate::core::{TorrentsMetrics, Tracker}; fn public_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_public()) + let config = configuration::ephemeral_public(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn private_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_private()) + let config = configuration::ephemeral_private(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn whitelisted_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_listed()) + let config = configuration::ephemeral_listed(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } pub fn tracker_persisting_torrents_in_database() -> Tracker { - let mut configuration = configuration::ephemeral(); - configuration.core.tracker_policy.persistent_torrent_completed_stat = true; - tracker_factory(&configuration) + let mut config = configuration::ephemeral_listed(); + config.core.tracker_policy.persistent_torrent_completed_stat = true; + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn sample_info_hash() -> InfoHash { diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index 67d5113bc..a6b5e3371 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -24,17 +24,17 @@ use crate::core::Tracker; /// /// Will panic if tracker cannot be instantiated. #[must_use] -pub fn tracker_factory(config: &Configuration) -> Tracker { - let database = initialize_database(config); - - let whitelist_manager = initialize_whitelist(database.clone()); - +pub fn tracker_factory( + config: &Configuration, + database: &Arc>, + whitelist_manager: &Arc, +) -> Tracker { let (stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); match Tracker::new( &Arc::new(config).core, - &database, - &whitelist_manager, + database, + whitelist_manager, stats_event_sender, stats_repository, ) { diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 4143aaf1f..2352953eb 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -114,7 +114,7 @@ mod tests { use crate::core; use crate::core::services::statistics::{get_metrics, TrackerMetrics}; - use crate::core::services::tracker_factory; + use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -124,7 +124,10 @@ mod tests { #[tokio::test] async fn the_statistics_service_should_return_the_tracker_metrics() { - let tracker = Arc::new(tracker_factory(&tracker_configuration())); + let config = tracker_configuration(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&tracker_configuration(), &database, &whitelist_manager)); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let tracker_metrics = get_metrics(tracker.clone(), ban_service.clone()).await; diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index e63d2efa2..0b89de7ef 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -131,7 +131,7 @@ mod tests { use crate::core::services::torrent::tests::sample_peer; use crate::core::services::torrent::{get_torrent_info, Info}; - use crate::core::services::tracker_factory; + use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -139,7 +139,10 @@ mod tests { #[tokio::test] async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { - let tracker = Arc::new(tracker_factory(&tracker_configuration())); + let config = tracker_configuration(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let torrent_info = get_torrent_info( tracker.clone(), @@ -152,7 +155,10 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { - let tracker = Arc::new(tracker_factory(&tracker_configuration())); + let config = tracker_configuration(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -184,7 +190,7 @@ mod tests { use crate::core::services::torrent::tests::sample_peer; use crate::core::services::torrent::{get_torrents_page, BasicInfo, Pagination}; - use crate::core::services::tracker_factory; + use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -192,7 +198,10 @@ mod tests { #[tokio::test] async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { - let tracker = Arc::new(tracker_factory(&tracker_configuration())); + let config = tracker_configuration(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -201,7 +210,10 @@ mod tests { #[tokio::test] async fn should_return_a_summarized_info_for_all_torrents() { - let tracker = Arc::new(tracker_factory(&tracker_configuration())); + let config = tracker_configuration(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -223,7 +235,10 @@ mod tests { #[tokio::test] async fn should_allow_limiting_the_number_of_torrents_in_the_result() { - let tracker = Arc::new(tracker_factory(&tracker_configuration())); + let config = tracker_configuration(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -243,7 +258,10 @@ mod tests { #[tokio::test] async fn should_allow_using_pagination_in_the_result() { - let tracker = Arc::new(tracker_factory(&tracker_configuration())); + let config = tracker_configuration(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -272,7 +290,10 @@ mod tests { #[tokio::test] async fn should_return_torrents_ordered_by_info_hash() { - let tracker = Arc::new(tracker_factory(&tracker_configuration())); + let config = tracker_configuration(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index a17e877fa..fc2739db4 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -185,23 +185,35 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; - use crate::core::services::tracker_factory; + use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; use crate::core::Tracker; fn private_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_private()) + let config = configuration::ephemeral_private(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn whitelisted_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_listed()) + let config = configuration::ephemeral_listed(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn tracker_on_reverse_proxy() -> Tracker { - tracker_factory(&configuration::ephemeral_with_reverse_proxy()) + let config = configuration::ephemeral_with_reverse_proxy(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn tracker_not_on_reverse_proxy() -> Tracker { - tracker_factory(&configuration::ephemeral_without_reverse_proxy()) + let config = configuration::ephemeral_without_reverse_proxy(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn sample_announce_request() -> Announce { diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 2aa1bd9f8..88d4c92de 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -121,23 +121,35 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; - use crate::core::services::tracker_factory; + use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; use crate::core::Tracker; fn private_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_private()) + let config = configuration::ephemeral_private(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn whitelisted_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_listed()) + let config = configuration::ephemeral_listed(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn tracker_on_reverse_proxy() -> Tracker { - tracker_factory(&configuration::ephemeral_with_reverse_proxy()) + let config = configuration::ephemeral_with_reverse_proxy(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn tracker_not_on_reverse_proxy() -> Tracker { - tracker_factory(&configuration::ephemeral_without_reverse_proxy()) + let config = configuration::ephemeral_without_reverse_proxy(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn sample_scrape_request() -> Scrape { diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 06aad669f..937560692 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -59,11 +59,14 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::core::services::tracker_factory; + use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; use crate::core::Tracker; fn public_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_public()) + let config = configuration::ephemeral_public(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn sample_info_hash() -> InfoHash { diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 6ab11bb4a..ea2712b6e 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -71,7 +71,10 @@ mod tests { use crate::core::{statistics, Tracker}; fn public_tracker() -> Tracker { - tracker_factory(&configuration::ephemeral_public()) + let config = configuration::ephemeral_public(); + let database = initialize_database(&config); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(&config, &database, &whitelist_manager) } fn sample_info_hashes() -> Vec { diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 5fc695f88..6110af530 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -456,7 +456,9 @@ mod tests { } fn initialized_tracker(configuration: &Configuration) -> Arc { - tracker_factory(configuration).into() + let database = initialize_database(configuration); + let whitelist_manager = initialize_whitelist(database.clone()); + tracker_factory(configuration, &database, &whitelist_manager).into() } fn sample_ipv4_remote_addr() -> SocketAddr { From 882af33a179290a817a532a8eeaf7d3d4b9979c6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 Jan 2025 17:25:21 +0000 Subject: [PATCH 0589/1297] refactor: [#1182] remove duplicate code --- src/bootstrap/app.rs | 12 +++++++++-- src/core/mod.rs | 15 ++++++------- src/core/services/statistics/mod.rs | 6 +++--- src/core/services/torrent.rs | 27 ++++++++++-------------- src/servers/http/v1/handlers/announce.rs | 15 ++++++------- src/servers/http/v1/handlers/scrape.rs | 15 ++++++------- src/servers/http/v1/services/announce.rs | 12 +++++------ src/servers/http/v1/services/scrape.rs | 10 ++++----- src/servers/udp/handlers.rs | 23 +++++++++----------- 9 files changed, 61 insertions(+), 74 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 9be52359b..788037b0b 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -21,7 +21,9 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; +use crate::core::databases::Database; use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; +use crate::core::whitelist::WhiteListManager; use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -105,11 +107,17 @@ pub fn initialize_static() { #[must_use] #[instrument(skip(config))] pub fn initialize_tracker(config: &Configuration) -> Tracker { - let database = initialize_database(config); + let (database, whitelist_manager) = initialize_tracker_dependencies(config); + + tracker_factory(config, &database, &whitelist_manager) +} +#[must_use] +pub fn initialize_tracker_dependencies(config: &Configuration) -> (Arc>, Arc) { + let database = initialize_database(config); let whitelist_manager = initialize_whitelist(database.clone()); - tracker_factory(config, &database, &whitelist_manager) + (database, whitelist_manager) } /// It initializes the log threshold, format and channel. diff --git a/src/core/mod.rs b/src/core/mod.rs index 51d330880..c8bb7f6a9 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -1153,36 +1153,33 @@ mod tests { use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; + use crate::bootstrap::app::initialize_tracker_dependencies; use crate::core::peer::Peer; - use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; + use crate::core::services::tracker_factory; use crate::core::{TorrentsMetrics, Tracker}; fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } fn private_tracker() -> Tracker { let config = configuration::ephemeral_private(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } fn whitelisted_tracker() -> Tracker { let config = configuration::ephemeral_listed(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } pub fn tracker_persisting_torrents_in_database() -> Tracker { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 2352953eb..d4e77ce4c 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -112,9 +112,10 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; + use crate::bootstrap::app::initialize_tracker_dependencies; use crate::core; use crate::core::services::statistics::{get_metrics, TrackerMetrics}; - use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; + use crate::core::services::tracker_factory; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -125,8 +126,7 @@ mod tests { #[tokio::test] async fn the_statistics_service_should_return_the_tracker_metrics() { let config = tracker_configuration(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let tracker = Arc::new(tracker_factory(&tracker_configuration(), &database, &whitelist_manager)); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 0b89de7ef..1be2acc93 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -129,9 +129,10 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; + use crate::bootstrap::app::initialize_tracker_dependencies; use crate::core::services::torrent::tests::sample_peer; use crate::core::services::torrent::{get_torrent_info, Info}; - use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; + use crate::core::services::tracker_factory; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -140,8 +141,7 @@ mod tests { #[tokio::test] async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { let config = tracker_configuration(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let torrent_info = get_torrent_info( @@ -156,8 +156,7 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let config = tracker_configuration(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -188,9 +187,10 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; + use crate::bootstrap::app::initialize_tracker_dependencies; use crate::core::services::torrent::tests::sample_peer; use crate::core::services::torrent::{get_torrents_page, BasicInfo, Pagination}; - use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; + use crate::core::services::tracker_factory; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -199,8 +199,7 @@ mod tests { #[tokio::test] async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let config = tracker_configuration(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -211,8 +210,7 @@ mod tests { #[tokio::test] async fn should_return_a_summarized_info_for_all_torrents() { let config = tracker_configuration(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -236,8 +234,7 @@ mod tests { #[tokio::test] async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let config = tracker_configuration(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -259,8 +256,7 @@ mod tests { #[tokio::test] async fn should_allow_using_pagination_in_the_result() { let config = tracker_configuration(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); @@ -291,8 +287,7 @@ mod tests { #[tokio::test] async fn should_return_torrents_ordered_by_info_hash() { let config = tracker_configuration(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index fc2739db4..df4658420 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -185,34 +185,31 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; - use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; + use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::core::services::tracker_factory; use crate::core::Tracker; fn private_tracker() -> Tracker { let config = configuration::ephemeral_private(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } fn whitelisted_tracker() -> Tracker { let config = configuration::ephemeral_listed(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } fn tracker_on_reverse_proxy() -> Tracker { let config = configuration::ephemeral_with_reverse_proxy(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } fn tracker_not_on_reverse_proxy() -> Tracker { let config = configuration::ephemeral_without_reverse_proxy(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 88d4c92de..dd144d898 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -121,34 +121,31 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; - use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; + use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::core::services::tracker_factory; use crate::core::Tracker; fn private_tracker() -> Tracker { let config = configuration::ephemeral_private(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } fn whitelisted_tracker() -> Tracker { let config = configuration::ephemeral_listed(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } fn tracker_on_reverse_proxy() -> Tracker { let config = configuration::ephemeral_with_reverse_proxy(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } fn tracker_not_on_reverse_proxy() -> Tracker { let config = configuration::ephemeral_without_reverse_proxy(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 937560692..f19c69c2f 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -59,13 +59,13 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; + use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::core::services::tracker_factory; use crate::core::Tracker; fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } @@ -110,7 +110,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; - use crate::core::services::{initialize_database, initialize_whitelist}; + use crate::bootstrap::app::initialize_tracker_dependencies; use crate::core::{statistics, PeersWanted, Tracker}; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; @@ -118,9 +118,7 @@ mod tests { fn test_tracker_factory(stats_event_sender: Option>) -> Tracker { let config = configuration::ephemeral(); - let database = initialize_database(&config); - - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); Tracker::new( &config.core, diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index ea2712b6e..0a96031a0 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -67,13 +67,13 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; + use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::core::services::tracker_factory; use crate::core::{statistics, Tracker}; fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let database = initialize_database(&config); - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); tracker_factory(&config, &database, &whitelist_manager) } @@ -100,9 +100,7 @@ mod tests { fn test_tracker_factory(stats_event_sender: Option>) -> Tracker { let config = configuration::ephemeral(); - let database = initialize_database(&config); - - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); Tracker::new( &config.core, diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 6110af530..292ccfd3a 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -435,7 +435,8 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::gen_remote_fingerprint; - use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; + use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::core::services::tracker_factory; use crate::core::{statistics, Tracker}; use crate::CurrentClock; @@ -455,10 +456,9 @@ mod tests { initialized_tracker(&configuration::ephemeral_listed()) } - fn initialized_tracker(configuration: &Configuration) -> Arc { - let database = initialize_database(configuration); - let whitelist_manager = initialize_whitelist(database.clone()); - tracker_factory(configuration, &database, &whitelist_manager).into() + fn initialized_tracker(config: &Configuration) -> Arc { + let (database, whitelist_manager) = initialize_tracker_dependencies(config); + tracker_factory(config, &database, &whitelist_manager).into() } fn sample_ipv4_remote_addr() -> SocketAddr { @@ -558,9 +558,7 @@ mod tests { fn test_tracker_factory(stats_event_sender: Option>) -> Tracker { let config = tracker_configuration(); - let database = initialize_database(&config); - - let whitelist_manager = initialize_whitelist(database.clone()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); Tracker::new( &config.core, @@ -1190,8 +1188,8 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; + use crate::bootstrap::app::initialize_tracker_dependencies; use crate::core; - use crate::core::services::{initialize_database, initialize_whitelist}; use crate::core::statistics::keeper::Keeper; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; @@ -1202,14 +1200,13 @@ mod tests { #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { - let configuration = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - let database = initialize_database(&configuration); - let whitelist_manager = initialize_whitelist(database.clone()); + let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let (stats_event_sender, stats_repository) = Keeper::new_active_instance(); let tracker = Arc::new( core::Tracker::new( - &configuration.core, + &config.core, &database, &whitelist_manager, Some(stats_event_sender), From 57455cabc88556b432a9eaf15f360ca8f428d0f2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 15 Jan 2025 17:51:12 +0000 Subject: [PATCH 0590/1297] refactor: [#1182] remove whitelist context methods from core tracker --- src/app.rs | 1 + src/core/mod.rs | 95 ++++++------------- tests/servers/api/environment.rs | 8 ++ .../api/v1/contract/context/whitelist.rs | 16 ++-- tests/servers/http/environment.rs | 7 ++ tests/servers/http/v1/contract.rs | 4 +- 6 files changed, 55 insertions(+), 76 deletions(-) diff --git a/src/app.rs b/src/app.rs index abfe75256..1cfc57c2e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -67,6 +67,7 @@ pub async fn start( // Load whitelisted torrents if tracker.is_listed() { tracker + .whitelist_manager .load_whitelist_from_database() .await .expect("Could not load whitelist from database."); diff --git a/src/core/mod.rs b/src/core/mod.rs index c8bb7f6a9..f142fa26e 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -1044,7 +1044,7 @@ impl Tracker { return Ok(()); } - if self.is_info_hash_whitelisted(info_hash).await { + if self.whitelist_manager.is_info_hash_whitelisted(info_hash).await { return Ok(()); } @@ -1054,48 +1054,6 @@ impl Tracker { }) } - /// It adds a torrent to the whitelist. - /// Adding torrents is not relevant to public trackers. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. - pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.whitelist_manager.add_torrent_to_whitelist(info_hash).await - } - - /// It removes a torrent from the whitelist. - /// Removing torrents is not relevant to public trackers. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. - pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.whitelist_manager.remove_torrent_from_whitelist(info_hash).await - } - - /// It checks if a torrent is whitelisted. - /// - /// # Context: Whitelist - pub async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { - self.whitelist_manager.is_info_hash_whitelisted(info_hash).await - } - - /// It loads the whitelist from the database. - /// - /// # Context: Whitelist - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. - pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { - self.whitelist_manager.load_whitelist_from_database().await - } - /// It return the `Tracker` [`statistics::metrics::Metrics`]. /// /// # Context: Statistics @@ -1156,6 +1114,7 @@ mod tests { use crate::bootstrap::app::initialize_tracker_dependencies; use crate::core::peer::Peer; use crate::core::services::tracker_factory; + use crate::core::whitelist::WhiteListManager; use crate::core::{TorrentsMetrics, Tracker}; fn public_tracker() -> Tracker { @@ -1170,10 +1129,12 @@ mod tests { tracker_factory(&config, &database, &whitelist_manager) } - fn whitelisted_tracker() -> Tracker { + fn whitelisted_tracker() -> (Tracker, Arc) { let config = configuration::ephemeral_listed(); let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let tracker = tracker_factory(&config, &database, &whitelist_manager); + + (tracker, whitelist_manager) } pub fn tracker_persisting_torrents_in_database() -> Tracker { @@ -1707,11 +1668,11 @@ mod tests { #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { - let tracker = whitelisted_tracker(); + let (tracker, whitelist_manager) = whitelisted_tracker(); let info_hash = sample_info_hash(); - let result = tracker.add_torrent_to_whitelist(&info_hash).await; + let result = whitelist_manager.add_torrent_to_whitelist(&info_hash).await; assert!(result.is_ok()); let result = tracker.authorize(&info_hash).await; @@ -1720,7 +1681,7 @@ mod tests { #[tokio::test] async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { - let tracker = whitelisted_tracker(); + let (tracker, _whitelist_manager) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1732,28 +1693,33 @@ mod tests { mod handling_the_torrent_whitelist { use crate::core::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; + // todo: after extracting the WhitelistManager from the Tracker, + // there is no need to use the tracker to test the whitelist. + // Test not using the `tracker` (`_tracker` variable) should be + // moved to the whitelist module. + #[tokio::test] async fn it_should_add_a_torrent_to_the_whitelist() { - let tracker = whitelisted_tracker(); + let (_tracker, whitelist_manager) = whitelisted_tracker(); let info_hash = sample_info_hash(); - tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); - assert!(tracker.is_info_hash_whitelisted(&info_hash).await); + assert!(whitelist_manager.is_info_hash_whitelisted(&info_hash).await); } #[tokio::test] async fn it_should_remove_a_torrent_from_the_whitelist() { - let tracker = whitelisted_tracker(); + let (_tracker, whitelist_manager) = whitelisted_tracker(); let info_hash = sample_info_hash(); - tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); - tracker.remove_torrent_from_whitelist(&info_hash).await.unwrap(); + whitelist_manager.remove_torrent_from_whitelist(&info_hash).await.unwrap(); - assert!(!tracker.is_info_hash_whitelisted(&info_hash).await); + assert!(!whitelist_manager.is_info_hash_whitelisted(&info_hash).await); } mod persistence { @@ -1761,22 +1727,19 @@ mod tests { #[tokio::test] async fn it_should_load_the_whitelist_from_the_database() { - let tracker = whitelisted_tracker(); + let (_tracker, whitelist_manager) = whitelisted_tracker(); let info_hash = sample_info_hash(); - tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); + + whitelist_manager.remove_torrent_from_memory_whitelist(&info_hash).await; - // Remove torrent from the in-memory whitelist - tracker - .whitelist_manager - .remove_torrent_from_memory_whitelist(&info_hash) - .await; - assert!(!tracker.is_info_hash_whitelisted(&info_hash).await); + assert!(!whitelist_manager.is_info_hash_whitelisted(&info_hash).await); - tracker.load_whitelist_from_database().await.unwrap(); + whitelist_manager.load_whitelist_from_database().await.unwrap(); - assert!(tracker.is_info_hash_whitelisted(&info_hash).await); + assert!(whitelist_manager.is_info_hash_whitelisted(&info_hash).await); } } } @@ -1807,7 +1770,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { - let tracker = whitelisted_tracker(); + let (tracker, _whitelist_manager) = whitelisted_tracker(); let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 70f2d4c65..37d031e1c 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -8,6 +8,7 @@ use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::{Configuration, HttpApi}; use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; +use torrust_tracker_lib::core::whitelist::WhiteListManager; use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; @@ -21,6 +22,7 @@ where { pub config: Arc, pub tracker: Arc, + pub whitelist_manager: Arc, pub ban_service: Arc>, pub registar: Registar, pub server: ApiServer, @@ -40,6 +42,9 @@ impl Environment { pub fn new(configuration: &Arc) -> Self { let tracker = initialize_with_configuration(configuration); + // todo: get from `initialize_with_configuration` + let whitelist_manager = tracker.whitelist_manager.clone(); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let config = Arc::new(configuration.http_api.clone().expect("missing API configuration")); @@ -53,6 +58,7 @@ impl Environment { Self { config, tracker, + whitelist_manager, ban_service, registar: Registar::default(), server, @@ -65,6 +71,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + whitelist_manager: self.whitelist_manager.clone(), ban_service: self.ban_service.clone(), registar: self.registar.clone(), server: self @@ -85,6 +92,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + whitelist_manager: self.whitelist_manager, ban_service: self.ban_service, registar: Registar::default(), server: self.server.stop().await.unwrap(), diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index 6dde663a5..aef1db4f1 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -31,7 +31,7 @@ async fn should_allow_whitelisting_a_torrent() { assert_ok(response).await; assert!( - env.tracker + env.whitelist_manager .is_info_hash_whitelisted(&InfoHash::from_str(&info_hash).unwrap()) .await ); @@ -167,7 +167,7 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); let request_id = Uuid::new_v4(); @@ -176,7 +176,7 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { .await; assert_ok(response).await; - assert!(!env.tracker.is_info_hash_whitelisted(&info_hash).await); + assert!(!env.whitelist_manager.is_info_hash_whitelisted(&info_hash).await); env.stop().await; } @@ -237,7 +237,7 @@ async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); force_database_error(&env.tracker); @@ -266,7 +266,7 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); let request_id = Uuid::new_v4(); @@ -281,7 +281,7 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica "Expected logs to contain: ERROR ... API ... request_id={request_id}" ); - env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); let request_id = Uuid::new_v4(); @@ -307,7 +307,7 @@ async fn should_allow_reload_the_whitelist_from_the_database() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); let request_id = Uuid::new_v4(); @@ -338,7 +338,7 @@ async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - env.tracker.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); force_database_error(&env.tracker); diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index d615d7eaf..6d4001e6c 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -5,6 +5,7 @@ use futures::executor::block_on; use torrust_tracker_configuration::{Configuration, HttpTracker}; use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; +use torrust_tracker_lib::core::whitelist::WhiteListManager; use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; @@ -13,6 +14,7 @@ use torrust_tracker_primitives::peer; pub struct Environment { pub config: Arc, pub tracker: Arc, + pub whitelist_manager: Arc, pub registar: Registar, pub server: HttpServer, } @@ -29,6 +31,8 @@ impl Environment { pub fn new(configuration: &Arc) -> Self { let tracker = initialize_with_configuration(configuration); + let whitelist_manager = tracker.whitelist_manager.clone(); + let http_tracker = configuration .http_trackers .clone() @@ -45,6 +49,7 @@ impl Environment { Self { config, tracker, + whitelist_manager, registar: Registar::default(), server, } @@ -55,6 +60,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + whitelist_manager: self.whitelist_manager.clone(), registar: self.registar.clone(), server: self.server.start(self.tracker, self.registar.give_form()).await.unwrap(), } @@ -70,6 +76,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + whitelist_manager: self.whitelist_manager, registar: Registar::default(), server: self.server.stop().await.unwrap(), diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index db03f526e..37d0288f4 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -1261,7 +1261,7 @@ mod configured_as_whitelisted { let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - env.tracker + env.whitelist_manager .add_torrent_to_whitelist(&info_hash) .await .expect("should add the torrent to the whitelist"); @@ -1343,7 +1343,7 @@ mod configured_as_whitelisted { .build(), ); - env.tracker + env.whitelist_manager .add_torrent_to_whitelist(&info_hash) .await .expect("should add the torrent to the whitelist"); From 4c2d61e6d4160a1b4309af3ee05de774e2308751 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 16 Jan 2025 09:36:48 +0000 Subject: [PATCH 0591/1297] chore(deps): udpate dependencies ```output cargo update Updating crates.io index Locking 36 packages to latest compatible versions Updating anstyle-wincon v3.0.6 -> v3.0.7 Updating bitflags v2.6.0 -> v2.8.0 Updating borsh v1.5.3 -> v1.5.4 Updating borsh-derive v1.5.3 -> v1.5.4 Downgrading btoi v0.4.4 -> v0.4.3 Updating cc v1.2.7 -> v1.2.9 Updating clap v4.5.23 -> v4.5.26 Updating clap_builder v4.5.23 -> v4.5.26 Updating clap_derive v4.5.18 -> v4.5.24 Updating event-listener v5.3.1 -> v5.4.0 Updating futures-lite v2.5.0 -> v2.6.0 Updating js-sys v0.3.76 -> v0.3.77 Updating libz-sys v1.1.20 -> v1.1.21 Updating linux-raw-sys v0.4.14 -> v0.4.15 Updating log v0.4.22 -> v0.4.25 Updating miniz_oxide v0.8.2 -> v0.8.3 Updating neli v0.6.4 -> v0.6.5 Updating neli-proc-macros v0.1.3 -> v0.1.4 Updating proc-macro2 v1.0.92 -> v1.0.93 Updating rustix v0.38.42 -> v0.38.43 Updating rustls v0.23.20 -> v0.23.21 Updating security-framework-sys v2.13.0 -> v2.14.0 Updating syn v2.0.95 -> v2.0.96 Updating thiserror v2.0.9 -> v2.0.11 Updating thiserror-impl v2.0.9 -> v2.0.11 Updating tokio v1.42.0 -> v1.43.0 Updating tokio-macros v2.4.0 -> v2.5.0 Updating uuid v1.11.0 -> v1.12.0 Updating wasm-bindgen v0.2.99 -> v0.2.100 Updating wasm-bindgen-backend v0.2.99 -> v0.2.100 Updating wasm-bindgen-futures v0.4.49 -> v0.4.50 Updating wasm-bindgen-macro v0.2.99 -> v0.2.100 Updating wasm-bindgen-macro-support v0.2.99 -> v0.2.100 Updating wasm-bindgen-shared v0.2.99 -> v0.2.100 Updating web-sys v0.3.76 -> v0.3.77 Updating winnow v0.6.22 -> v0.6.24 ``` --- Cargo.lock | 245 +++++++++++++++++++++++++++-------------------------- 1 file changed, 125 insertions(+), 120 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c097ed80e..7ab861d2b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -132,11 +132,12 @@ dependencies = [ [[package]] name = "anstyle-wincon" -version = "3.0.6" +version = "3.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2109dbce0e72be3ec00bed26e6a7479ca384ad226efdd66db8fa2e3a38c83125" +checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e" dependencies = [ "anstyle", + "once_cell", "windows-sys 0.59.0", ] @@ -287,7 +288,7 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" dependencies = [ - "event-listener 5.3.1", + "event-listener 5.4.0", "event-listener-strategy", "pin-project-lite", ] @@ -444,7 +445,7 @@ checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -532,7 +533,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -543,9 +544,9 @@ checksum = "02b4ff8b16e6076c3e14220b39fbc1fabb6737522281a388998046859400895f" [[package]] name = "bitflags" -version = "2.6.0" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" +checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" [[package]] name = "bittorrent-http-protocol" @@ -558,7 +559,7 @@ dependencies = [ "percent-encoding", "serde", "serde_bencode", - "thiserror 2.0.9", + "thiserror 2.0.11", "torrust-tracker-configuration", "torrust-tracker-contrib-bencode", "torrust-tracker-located-error", @@ -593,7 +594,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_repr", - "thiserror 2.0.9", + "thiserror 2.0.11", "tokio", "torrust-tracker-configuration", "torrust-tracker-located-error", @@ -657,9 +658,9 @@ dependencies = [ [[package]] name = "borsh" -version = "1.5.3" +version = "1.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2506947f73ad44e344215ccd6403ac2ae18cd8e046e581a441bf8d199f257f03" +checksum = "9fb65153674e51d3a42c8f27b05b9508cea85edfaade8aa46bc8fc18cecdfef3" dependencies = [ "borsh-derive", "cfg_aliases", @@ -667,15 +668,15 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.5.3" +version = "1.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2593a3b8b938bd68373196c9832f516be11fa487ef4ae745eb282e6a56a7244" +checksum = "a396e17ad94059c650db3d253bb6e25927f1eb462eede7e7a153bb6e75dce0a7" dependencies = [ "once_cell", "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -701,9 +702,9 @@ dependencies = [ [[package]] name = "btoi" -version = "0.4.4" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9586aa4bb508d369941af10c87af0ce6f4ea051bb4f21047791b921c45822137" +checksum = "9dd6407f73a9b8b6162d8a2ef999fe6afd7cc15902ebf42c5cd296addf17e0ad" dependencies = [ "num-traits", ] @@ -786,9 +787,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.7" +version = "1.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a012a0df96dd6d06ba9a1b29d6402d1a5d77c6befd2566afdc26e10603dc93d7" +checksum = "c8293772165d9345bdaaa39b45b2109591e63fe5e6fbc23c6ff930a048aa310b" dependencies = [ "jobserver", "libc", @@ -879,9 +880,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.23" +version = "4.5.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3135e7ec2ef7b10c6ed8950f0f792ed96ee093fa088608f1c76e569722700c84" +checksum = "a8eb5e908ef3a6efbe1ed62520fb7287959888c88485abe072543190ecc66783" dependencies = [ "clap_builder", "clap_derive", @@ -889,9 +890,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.23" +version = "4.5.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30582fc632330df2bd26877bde0c1f4470d57c582bbc070376afcd04d8cb4838" +checksum = "96b01801b5fc6a0a232407abc821660c9c6d25a1cafc0d4f85f29fb8d9afc121" dependencies = [ "anstream", "anstyle", @@ -901,14 +902,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.18" +version = "4.5.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" +checksum = "54b755194d6389280185988721fffba69495eed5ee9feeee9a599b53db80318c" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -1129,7 +1130,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -1140,7 +1141,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -1184,7 +1185,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", "unicode-xid", ] @@ -1196,7 +1197,7 @@ checksum = "65f152f4b8559c4da5d574bafc7af85454d706b4c5fe8b530d508cacbb6807ea" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -1217,7 +1218,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -1275,9 +1276,9 @@ checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" [[package]] name = "event-listener" -version = "5.3.1" +version = "5.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6032be9bd27023a771701cc49f9f053c751055f71efb2e0ae5c15809093675ba" +checksum = "3492acde4c3fc54c845eaab3eed8bd00c7a7d881f78bfc801e43a93dec1331ae" dependencies = [ "concurrent-queue", "parking", @@ -1290,7 +1291,7 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c3e4e0dd3673c1139bf041f3008816d9cf2946bbfac2945c09e523b8d7b05b2" dependencies = [ - "event-listener 5.3.1", + "event-listener 5.4.0", "pin-project-lite", ] @@ -1420,7 +1421,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -1432,7 +1433,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -1444,7 +1445,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -1503,9 +1504,9 @@ checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" [[package]] name = "futures-lite" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cef40d21ae2c515b51041df9ed313ed21e572df340ea58a922a0aefe7e8891a1" +checksum = "f5edaec856126859abb19ed65f39e90fea3a9574b9707f13539acf4abf7eb532" dependencies = [ "fastrand", "futures-core", @@ -1522,7 +1523,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -1954,7 +1955,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -2088,9 +2089,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.76" +version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6717b6b5b077764fb5966237269cb3c64edddde4b14ce42647430a78ced9e7b7" +checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" dependencies = [ "once_cell", "wasm-bindgen", @@ -2146,9 +2147,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.20" +version = "1.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2d16453e800a8cf6dd2fc3eb4bc99b786a9b90c663b8559a5b1a041bf89e472" +checksum = "df9b68e50e6e0b26f672573834882eb57759f6db9b3be2ea3c35c91188bb4eaa" dependencies = [ "cc", "pkg-config", @@ -2157,9 +2158,9 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.4.14" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] name = "litemap" @@ -2191,9 +2192,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.22" +version = "0.4.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" +checksum = "04cbf5b083de1c7e0222a7a51dbfdba1cbe1c6ab0b15e29fff3f6c077fd9cd9f" dependencies = [ "value-bag", ] @@ -2233,9 +2234,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ffbe83022cedc1d264172192511ae958937694cd57ce297164951b8b3568394" +checksum = "b8402cab7aefae129c6977bb0ff1b8fd9a04eb5b51efc50a70bea51cda0c7924" dependencies = [ "adler2", ] @@ -2274,7 +2275,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -2324,7 +2325,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", "termcolor", "thiserror 1.0.69", ] @@ -2396,9 +2397,9 @@ dependencies = [ [[package]] name = "neli" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1100229e06604150b3becd61a4965d5c70f3be1759544ea7274166f4be41ef43" +checksum = "93062a0dce6da2517ea35f301dfc88184ce18d3601ec786a727a87bf535deca9" dependencies = [ "byteorder", "libc", @@ -2408,9 +2409,9 @@ dependencies = [ [[package]] name = "neli-proc-macros" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c168194d373b1e134786274020dae7fc5513d565ea2ebb9bc9ff17ffb69106d4" +checksum = "0c8034b7fbb6f9455b2a96c19e6edf8dc9fc34c70449938d8ee3b4df363f61fe" dependencies = [ "either", "proc-macro2", @@ -2523,7 +2524,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -2599,7 +2600,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -2673,7 +2674,7 @@ checksum = "d56a66c0c55993aa927429d0f8a0abfd74f084e4d9c192cffed01e418d83eefb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -2823,14 +2824,14 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] name = "proc-macro2" -version = "1.0.92" +version = "1.0.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" +checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" dependencies = [ "unicode-ident", ] @@ -2843,7 +2844,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", "version_check", "yansi", ] @@ -3153,7 +3154,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.95", + "syn 2.0.96", "unicode-ident", ] @@ -3210,9 +3211,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.42" +version = "0.38.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85" +checksum = "a78891ee6bf2340288408954ac787aa063d8e8817e9f53abb37c695c6d834ef6" dependencies = [ "bitflags", "errno", @@ -3223,9 +3224,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.20" +version = "0.23.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5065c3f250cbd332cd894be57c40fa52387247659b14a2d6041d121547903b1b" +checksum = "8f287924602bf649d949c63dc8ac8b235fa5387d394020705b80c4eb597ce5b8" dependencies = [ "once_cell", "rustls-pki-types", @@ -3332,9 +3333,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.13.0" +version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1863fd3768cd83c56a7f60faa4dc0d403f1b6df0a38c3c25f44b7894e45370d5" +checksum = "49db231d56a190491cb4aeda9527f1ad45345af50b0851622a7adb8c03b01c32" dependencies = [ "core-foundation-sys", "libc", @@ -3382,7 +3383,7 @@ checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -3429,7 +3430,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -3480,7 +3481,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -3619,9 +3620,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.95" +version = "2.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46f71c0377baf4ef1cc3e3402ded576dccc315800fbc62dfc7fe04b009773b4a" +checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80" dependencies = [ "proc-macro2", "quote", @@ -3645,7 +3646,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -3732,11 +3733,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.9" +version = "2.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f072643fd0190df67a8bab670c20ef5d8737177d6ac6b2e9a236cb096206b2cc" +checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc" dependencies = [ - "thiserror-impl 2.0.9", + "thiserror-impl 2.0.11", ] [[package]] @@ -3747,18 +3748,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] name = "thiserror-impl" -version = "2.0.9" +version = "2.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b50fa271071aae2e6ee85f842e2e28ba8cd2c5fb67f11fcb1fd70b276f9e7d4" +checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -3839,9 +3840,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.42.0" +version = "1.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cec9b21b0450273377fc97bd4c33a8acffc8c996c987a7c5b319a0083707551" +checksum = "3d61fa4ffa3de412bfea335c6ecff681de2b609ba3c77ef3e00e521813a9ed9e" dependencies = [ "backtrace", "bytes", @@ -3856,13 +3857,13 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" +checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -3979,7 +3980,7 @@ dependencies = [ "serde_json", "serde_repr", "serde_with", - "thiserror 2.0.9", + "thiserror 2.0.11", "tokio", "torrust-tracker-api-client", "torrust-tracker-clock", @@ -4004,7 +4005,7 @@ dependencies = [ "hyper", "reqwest", "serde", - "thiserror 2.0.9", + "thiserror 2.0.11", "url", "uuid", ] @@ -4026,7 +4027,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_json", - "thiserror 2.0.9", + "thiserror 2.0.11", "tokio", "torrust-tracker-configuration", "tracing", @@ -4053,7 +4054,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.9", + "thiserror 2.0.11", "toml", "torrust-tracker-located-error", "url", @@ -4065,14 +4066,14 @@ name = "torrust-tracker-contrib-bencode" version = "3.0.0-develop" dependencies = [ "criterion", - "thiserror 2.0.9", + "thiserror 2.0.11", ] [[package]] name = "torrust-tracker-located-error" version = "3.0.0-develop" dependencies = [ - "thiserror 2.0.9", + "thiserror 2.0.11", "tracing", ] @@ -4087,7 +4088,7 @@ dependencies = [ "serde", "tdyne-peer-id", "tdyne-peer-id-registry", - "thiserror 2.0.9", + "thiserror 2.0.11", "torrust-tracker-configuration", "zerocopy", ] @@ -4204,7 +4205,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -4337,9 +4338,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8c5f0a0af699448548ad1a2fbf920fb4bee257eae39953ba95cb84891a0446a" +checksum = "744018581f9a3454a9e15beb8a33b017183f1e7c0cd170232a2d1453b23a51c4" dependencies = [ "getrandom", "rand", @@ -4396,34 +4397,35 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.99" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396" +checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" dependencies = [ "cfg-if", "once_cell", + "rustversion", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" -version = "0.2.99" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f89bb38646b4f81674e8f5c3fb81b562be1fd936d84320f3264486418519c79" +checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" dependencies = [ "bumpalo", "log", "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.49" +version = "0.4.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38176d9b44ea84e9184eff0bc34cc167ed044f816accfe5922e54d84cf48eca2" +checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61" dependencies = [ "cfg-if", "js-sys", @@ -4434,9 +4436,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.99" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cc6181fd9a7492eef6fef1f33961e3695e4579b9872a6f7c83aee556666d4fe" +checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -4444,28 +4446,31 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.99" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" +checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.99" +version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6" +checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" +dependencies = [ + "unicode-ident", +] [[package]] name = "web-sys" -version = "0.3.76" +version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04dd7223427d52553d3702c004d3b2fe07c148165faa56313cb00211e31c12bc" +checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2" dependencies = [ "js-sys", "wasm-bindgen", @@ -4625,9 +4630,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "0.6.22" +version = "0.6.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39281189af81c07ec09db316b302a3e67bf9bd7cbf6c820b50e35fee9c2fa980" +checksum = "c8d71a593cc5c42ad7876e2c1fda56f314f3754c084128833e64f1345ff8a03a" dependencies = [ "memchr", ] @@ -4679,7 +4684,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", "synstructure", ] @@ -4701,7 +4706,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] @@ -4721,7 +4726,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", "synstructure", ] @@ -4750,7 +4755,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.95", + "syn 2.0.96", ] [[package]] From c415430fca76341d9571dc61673831274c5f6a8a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 16 Jan 2025 17:54:22 +0000 Subject: [PATCH 0592/1297] refactor: [#1184] inject stats event sender and repository into the core tracker This is part of a big refactor. We are extracting responsabilities from the tracker. The first step is to inject the service into the tracker and later we will use the extracted services directly. Finally we will removed the injected service from the tracker when it's not used anymore via the tracker. --- src/bootstrap/app.rs | 23 ++++++-- src/core/mod.rs | 30 +++++------ src/core/services/mod.rs | 6 ++- src/core/services/statistics/mod.rs | 12 ++++- src/core/services/torrent.rs | 67 +++++++++++++++++++----- src/servers/http/v1/handlers/announce.rs | 16 +++--- src/servers/http/v1/handlers/scrape.rs | 16 +++--- src/servers/http/v1/services/announce.rs | 14 +++-- src/servers/http/v1/services/scrape.rs | 15 ++++-- src/servers/udp/handlers.rs | 23 +++++--- 10 files changed, 151 insertions(+), 71 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 788037b0b..2c6c23ab9 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -22,7 +22,9 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; use crate::core::databases::Database; -use crate::core::services::{initialize_database, initialize_whitelist, tracker_factory}; +use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; +use crate::core::statistics::event::sender::Sender; +use crate::core::statistics::repository::Repository; use crate::core::whitelist::WhiteListManager; use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; @@ -107,17 +109,28 @@ pub fn initialize_static() { #[must_use] #[instrument(skip(config))] pub fn initialize_tracker(config: &Configuration) -> Tracker { - let (database, whitelist_manager) = initialize_tracker_dependencies(config); + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(config); - tracker_factory(config, &database, &whitelist_manager) + tracker_factory(config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } +#[allow(clippy::type_complexity)] #[must_use] -pub fn initialize_tracker_dependencies(config: &Configuration) -> (Arc>, Arc) { +pub fn initialize_tracker_dependencies( + config: &Configuration, +) -> ( + Arc>, + Arc, + Arc>>, + Arc, +) { let database = initialize_database(config); let whitelist_manager = initialize_whitelist(database.clone()); + let (stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + let stats_repository = Arc::new(stats_repository); - (database, whitelist_manager) + (database, whitelist_manager, stats_event_sender, stats_repository) } /// It initializes the log threshold, format and channel. diff --git a/src/core/mod.rs b/src/core/mod.rs index f142fa26e..d61474c2c 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -504,10 +504,10 @@ pub struct Tracker { torrents: Arc, /// Service to send stats events. - stats_event_sender: Option>, + stats_event_sender: Arc>>, /// The in-memory stats repo. - stats_repository: statistics::repository::Repository, + stats_repository: Arc, } /// How many peers the peer announcing wants in the announce response. @@ -576,8 +576,8 @@ impl Tracker { config: &Core, database: &Arc>, whitelist_manager: &Arc, - stats_event_sender: Option>, - stats_repository: statistics::repository::Repository, + stats_event_sender: &Arc>>, + stats_repository: &Arc, ) -> Result { Ok(Tracker { config: config.clone(), @@ -585,8 +585,8 @@ impl Tracker { keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), whitelist_manager: whitelist_manager.clone(), torrents: Arc::default(), - stats_event_sender, - stats_repository, + stats_event_sender: stats_event_sender.clone(), + stats_repository: stats_repository.clone(), }) } @@ -1068,7 +1068,7 @@ impl Tracker { &self, event: statistics::event::Event, ) -> Option>> { - match &self.stats_event_sender { + match &*self.stats_event_sender { None => None, Some(stats_event_sender) => stats_event_sender.send_event(event).await, } @@ -1119,20 +1119,20 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn private_tracker() -> Tracker { let config = configuration::ephemeral_private(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn whitelisted_tracker() -> (Tracker, Arc) { let config = configuration::ephemeral_listed(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = tracker_factory(&config, &database, &whitelist_manager); + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + let tracker = tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository); (tracker, whitelist_manager) } @@ -1140,8 +1140,8 @@ mod tests { pub fn tracker_persisting_torrents_in_database() -> Tracker { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn sample_info_hash() -> InfoHash { diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index a6b5e3371..4034925cd 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -14,6 +14,8 @@ use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::Configuration; use super::databases::{self, Database}; +use super::statistics::event::sender::Sender; +use super::statistics::repository::Repository; use super::whitelist::persisted::DatabaseWhitelist; use super::whitelist::WhiteListManager; use crate::core::Tracker; @@ -28,8 +30,10 @@ pub fn tracker_factory( config: &Configuration, database: &Arc>, whitelist_manager: &Arc, + stats_event_sender: &Arc>>, + stats_repository: &Arc, ) -> Tracker { - let (stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + //let (stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); match Tracker::new( &Arc::new(config).core, diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index d4e77ce4c..3c44bc310 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -126,8 +126,16 @@ mod tests { #[tokio::test] async fn the_statistics_service_should_return_the_tracker_metrics() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&tracker_configuration(), &database, &whitelist_manager)); + + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory( + &config, + &database, + &whitelist_manager, + &stats_event_sender, + &stats_repository, + )); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let tracker_metrics = get_metrics(tracker.clone(), ban_service.clone()).await; diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 1be2acc93..a4db67979 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -141,8 +141,11 @@ mod tests { #[tokio::test] async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + let tracker = tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository); + + let tracker = Arc::new(tracker); let torrent_info = get_torrent_info( tracker.clone(), @@ -156,8 +159,14 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory( + &config, + &database, + &whitelist_manager, + &stats_event_sender, + &stats_repository, + )); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -199,8 +208,14 @@ mod tests { #[tokio::test] async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory( + &config, + &database, + &whitelist_manager, + &stats_event_sender, + &stats_repository, + )); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -210,8 +225,14 @@ mod tests { #[tokio::test] async fn should_return_a_summarized_info_for_all_torrents() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory( + &config, + &database, + &whitelist_manager, + &stats_event_sender, + &stats_repository, + )); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -234,8 +255,14 @@ mod tests { #[tokio::test] async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory( + &config, + &database, + &whitelist_manager, + &stats_event_sender, + &stats_repository, + )); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -256,8 +283,14 @@ mod tests { #[tokio::test] async fn should_allow_using_pagination_in_the_result() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory( + &config, + &database, + &whitelist_manager, + &stats_event_sender, + &stats_repository, + )); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -287,8 +320,14 @@ mod tests { #[tokio::test] async fn should_return_torrents_ordered_by_info_hash() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory( + &config, + &database, + &whitelist_manager, + &stats_event_sender, + &stats_repository, + )); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index df4658420..b21f035da 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -191,26 +191,26 @@ mod tests { fn private_tracker() -> Tracker { let config = configuration::ephemeral_private(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn whitelisted_tracker() -> Tracker { let config = configuration::ephemeral_listed(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn tracker_on_reverse_proxy() -> Tracker { let config = configuration::ephemeral_with_reverse_proxy(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn tracker_not_on_reverse_proxy() -> Tracker { let config = configuration::ephemeral_without_reverse_proxy(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn sample_announce_request() -> Announce { diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index dd144d898..41afb6bbb 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -127,26 +127,26 @@ mod tests { fn private_tracker() -> Tracker { let config = configuration::ephemeral_private(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn whitelisted_tracker() -> Tracker { let config = configuration::ephemeral_listed(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn tracker_on_reverse_proxy() -> Tracker { let config = configuration::ephemeral_with_reverse_proxy(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn tracker_not_on_reverse_proxy() -> Tracker { let config = configuration::ephemeral_without_reverse_proxy(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn sample_scrape_request() -> Scrape { diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index f19c69c2f..3a4d4820a 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -65,8 +65,8 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn sample_info_hash() -> InfoHash { @@ -118,14 +118,18 @@ mod tests { fn test_tracker_factory(stats_event_sender: Option>) -> Tracker { let config = configuration::ephemeral(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, whitelist_manager, _stats_event_sender, _stats_repository) = initialize_tracker_dependencies(&config); + + let stats_event_sender = Arc::new(stats_event_sender); + + let stats_repository = Arc::new(statistics::repository::Repository::new()); Tracker::new( &config.core, &database, &whitelist_manager, - stats_event_sender, - statistics::repository::Repository::new(), + &stats_event_sender, + &stats_repository, ) .unwrap() } diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 0a96031a0..01be81db6 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -61,6 +61,7 @@ async fn send_scrape_event(original_peer_ip: &IpAddr, tracker: &Arc) { mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; @@ -73,8 +74,8 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) } fn sample_info_hashes() -> Vec { @@ -100,14 +101,18 @@ mod tests { fn test_tracker_factory(stats_event_sender: Option>) -> Tracker { let config = configuration::ephemeral(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, whitelist_manager, _stats_event_sender, _stats_repository) = initialize_tracker_dependencies(&config); + + let stats_event_sender = Arc::new(stats_event_sender); + + let stats_repository = Arc::new(statistics::repository::Repository::new()); Tracker::new( &config.core, &database, &whitelist_manager, - stats_event_sender, - statistics::repository::Repository::new(), + &stats_event_sender, + &stats_repository, ) .unwrap() } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 292ccfd3a..4b20c2ac5 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -457,8 +457,8 @@ mod tests { } fn initialized_tracker(config: &Configuration) -> Arc { - let (database, whitelist_manager) = initialize_tracker_dependencies(config); - tracker_factory(config, &database, &whitelist_manager).into() + let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(config); + tracker_factory(config, &database, &whitelist_manager, &stats_event_sender, &stats_repository).into() } fn sample_ipv4_remote_addr() -> SocketAddr { @@ -558,14 +558,18 @@ mod tests { fn test_tracker_factory(stats_event_sender: Option>) -> Tracker { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, whitelist_manager, _stats_event_sender, _stats_repository) = initialize_tracker_dependencies(&config); + + let stats_event_sender = Arc::new(stats_event_sender); + + let stats_repository = Arc::new(statistics::repository::Repository::new()); Tracker::new( &config.core, &database, &whitelist_manager, - stats_event_sender, - statistics::repository::Repository::new(), + &stats_event_sender, + &stats_repository, ) .unwrap() } @@ -1201,7 +1205,10 @@ mod tests { #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + + let (database, whitelist_manager, _stats_event_sender, _stats_repository) = + initialize_tracker_dependencies(&config); + let (stats_event_sender, stats_repository) = Keeper::new_active_instance(); let tracker = Arc::new( @@ -1209,8 +1216,8 @@ mod tests { &config.core, &database, &whitelist_manager, - Some(stats_event_sender), - stats_repository, + &Arc::new(Some(stats_event_sender)), + &Arc::new(stats_repository), ) .unwrap(), ); From 2a0bc4789fb13cd3e69c88d3cabf30642f6fb2d6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 Jan 2025 09:43:58 +0000 Subject: [PATCH 0593/1297] refactor: [#1184] remove stats functionality from core tracker --- src/app.rs | 18 +- src/bootstrap/app.rs | 37 +- src/bootstrap/jobs/http_tracker.rs | 18 +- src/bootstrap/jobs/tracker_apis.rs | 66 ++- src/bootstrap/jobs/udp_tracker.rs | 6 +- src/console/profiling.rs | 4 +- src/core/mod.rs | 49 +- src/core/services/mod.rs | 14 +- src/core/services/statistics/mod.rs | 28 +- src/core/services/torrent.rs | 70 +-- src/main.rs | 4 +- src/servers/apis/routes.rs | 15 +- src/servers/apis/server.rs | 57 ++- src/servers/apis/v1/context/stats/handlers.rs | 6 +- src/servers/apis/v1/context/stats/routes.rs | 13 +- src/servers/apis/v1/routes.rs | 20 +- src/servers/http/server.rs | 30 +- src/servers/http/v1/handlers/announce.rs | 156 ++++-- src/servers/http/v1/handlers/scrape.rs | 137 +++-- src/servers/http/v1/routes.rs | 25 +- src/servers/http/v1/services/announce.rs | 89 ++-- src/servers/http/v1/services/scrape.rs | 102 ++-- src/servers/udp/handlers.rs | 481 ++++++++++++------ src/servers/udp/server/launcher.rs | 50 +- src/servers/udp/server/mod.rs | 25 +- src/servers/udp/server/processor.rs | 45 +- src/servers/udp/server/spawner.rs | 13 +- src/servers/udp/server/states.rs | 16 +- tests/servers/api/environment.rs | 29 +- tests/servers/http/environment.rs | 22 +- tests/servers/http/v1/contract.rs | 16 +- tests/servers/udp/contract.rs | 5 +- tests/servers/udp/environment.rs | 25 +- 33 files changed, 1134 insertions(+), 557 deletions(-) diff --git a/src/app.rs b/src/app.rs index 1cfc57c2e..14dc0b07f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -29,6 +29,8 @@ use torrust_tracker_configuration::Configuration; use tracing::instrument; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; +use crate::core::statistics::event::sender::Sender; +use crate::core::statistics::repository::Repository; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; use crate::{core, servers}; @@ -39,11 +41,13 @@ use crate::{core, servers}; /// /// - Can't retrieve tracker keys from database. /// - Can't load whitelist from database. -#[instrument(skip(config, tracker, ban_service))] +#[instrument(skip(config, tracker, ban_service, stats_event_sender, stats_repository))] pub async fn start( config: &Configuration, tracker: Arc, ban_service: Arc>, + stats_event_sender: Arc>>, + stats_repository: Arc, ) -> Vec> { if config.http_api.is_none() && (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) @@ -83,7 +87,14 @@ pub async fn start( ); } else { jobs.push( - udp_tracker::start_job(udp_tracker_config, tracker.clone(), ban_service.clone(), registar.give_form()).await, + udp_tracker::start_job( + udp_tracker_config, + tracker.clone(), + stats_event_sender.clone(), + ban_service.clone(), + registar.give_form(), + ) + .await, ); } } @@ -97,6 +108,7 @@ pub async fn start( if let Some(job) = http_tracker::start_job( http_tracker_config, tracker.clone(), + stats_event_sender.clone(), registar.give_form(), servers::http::Version::V1, ) @@ -115,6 +127,8 @@ pub async fn start( http_api_config, tracker.clone(), ban_service.clone(), + stats_event_sender.clone(), + stats_repository.clone(), registar.give_form(), servers::apis::Version::V1, ) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 2c6c23ab9..d63b414e1 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -38,8 +38,15 @@ use crate::shared::crypto::keys::{self, Keeper as _}; /// /// Setup can file if the configuration is invalid. #[must_use] +#[allow(clippy::type_complexity)] #[instrument(skip())] -pub fn setup() -> (Configuration, Arc, Arc>) { +pub fn setup() -> ( + Configuration, + Arc, + Arc>, + Arc>>, + Arc, +) { #[cfg(not(test))] check_seed(); @@ -49,13 +56,19 @@ pub fn setup() -> (Configuration, Arc, Arc>) { panic!("Configuration error: {e}"); } - let tracker = initialize_with_configuration(&configuration); + // Initialize services + + let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + let stats_repository = Arc::new(stats_repository); let udp_ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let tracker = initialize_with_configuration(&configuration); + tracing::info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); - (configuration, tracker, udp_ban_service) + (configuration, tracker, udp_ban_service, stats_event_sender, stats_repository) } /// checks if the seed is the instance seed in production. @@ -109,28 +122,18 @@ pub fn initialize_static() { #[must_use] #[instrument(skip(config))] pub fn initialize_tracker(config: &Configuration) -> Tracker { - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(config); + let (database, whitelist_manager) = initialize_tracker_dependencies(config); - tracker_factory(config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + tracker_factory(config, &database, &whitelist_manager) } #[allow(clippy::type_complexity)] #[must_use] -pub fn initialize_tracker_dependencies( - config: &Configuration, -) -> ( - Arc>, - Arc, - Arc>>, - Arc, -) { +pub fn initialize_tracker_dependencies(config: &Configuration) -> (Arc>, Arc) { let database = initialize_database(config); let whitelist_manager = initialize_whitelist(database.clone()); - let (stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - let stats_repository = Arc::new(stats_repository); - (database, whitelist_manager, stats_event_sender, stats_repository) + (database, whitelist_manager) } /// It initializes the log threshold, format and channel. diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index c55723bc6..9135a8828 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -19,7 +19,8 @@ use torrust_tracker_configuration::HttpTracker; use tracing::instrument; use super::make_rust_tls; -use crate::core; +use crate::core::statistics::event::sender::Sender; +use crate::core::{self, statistics}; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::http::Version; use crate::servers::registar::ServiceRegistrationForm; @@ -33,10 +34,11 @@ use crate::servers::registar::ServiceRegistrationForm; /// /// It would panic if the `config::HttpTracker` struct would contain inappropriate values. /// -#[instrument(skip(config, tracker, form))] +#[instrument(skip(config, tracker, stats_event_sender, form))] pub async fn start_job( config: &HttpTracker, tracker: Arc, + stats_event_sender: Arc>>, form: ServiceRegistrationForm, version: Version, ) -> Option> { @@ -47,20 +49,21 @@ pub async fn start_job( .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); match version { - Version::V1 => Some(start_v1(socket, tls, tracker.clone(), form).await), + Version::V1 => Some(start_v1(socket, tls, tracker.clone(), stats_event_sender.clone(), form).await), } } #[allow(clippy::async_yields_async)] -#[instrument(skip(socket, tls, tracker, form))] +#[instrument(skip(socket, tls, tracker, stats_event_sender, form))] async fn start_v1( socket: SocketAddr, tls: Option, tracker: Arc, + stats_event_sender: Arc>>, form: ServiceRegistrationForm, ) -> JoinHandle<()> { let server = HttpServer::new(Launcher::new(socket, tls)) - .start(tracker, form) + .start(tracker, stats_event_sender, form) .await .expect("it should be able to start to the http tracker"); @@ -85,6 +88,7 @@ mod tests { use crate::bootstrap::app::initialize_with_configuration; use crate::bootstrap::jobs::http_tracker::start_job; + use crate::core::services::statistics; use crate::servers::http::Version; use crate::servers::registar::Registar; @@ -93,10 +97,12 @@ mod tests { let cfg = Arc::new(ephemeral_public()); let http_tracker = cfg.http_trackers.clone().expect("missing HTTP tracker configuration"); let config = &http_tracker[0]; + let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); let tracker = initialize_with_configuration(&cfg); let version = Version::V1; - start_job(config, tracker, Registar::default().give_form(), version) + start_job(config, tracker, stats_event_sender, Registar::default().give_form(), version) .await .expect("it should be able to join to the http tracker start-job"); } diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 858888540..d84bb08a9 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -31,6 +31,8 @@ use tracing::instrument; use super::make_rust_tls; use crate::core; +use crate::core::statistics::event::sender::Sender; +use crate::core::statistics::repository::Repository; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::apis::Version; use crate::servers::registar::ServiceRegistrationForm; @@ -56,11 +58,13 @@ pub struct ApiServerJobStarted(); /// It would panic if unable to send the `ApiServerJobStarted` notice. /// /// -#[instrument(skip(config, tracker, ban_service, form))] +#[instrument(skip(config, tracker, ban_service, stats_event_sender, stats_repository, form))] pub async fn start_job( config: &HttpApi, tracker: Arc, ban_service: Arc>, + stats_event_sender: Arc>>, + stats_repository: Arc, form: ServiceRegistrationForm, version: Version, ) -> Option> { @@ -73,22 +77,53 @@ pub async fn start_job( let access_tokens = Arc::new(config.access_tokens.clone()); match version { - Version::V1 => Some(start_v1(bind_to, tls, tracker.clone(), ban_service.clone(), form, access_tokens).await), + Version::V1 => Some( + start_v1( + bind_to, + tls, + tracker.clone(), + ban_service.clone(), + stats_event_sender.clone(), + stats_repository.clone(), + form, + access_tokens, + ) + .await, + ), } } #[allow(clippy::async_yields_async)] -#[instrument(skip(socket, tls, tracker, ban_service, form, access_tokens))] +#[allow(clippy::too_many_arguments)] +#[instrument(skip( + socket, + tls, + tracker, + ban_service, + stats_event_sender, + stats_repository, + form, + access_tokens +))] async fn start_v1( socket: SocketAddr, tls: Option, tracker: Arc, ban_service: Arc>, + stats_event_sender: Arc>>, + stats_repository: Arc, form: ServiceRegistrationForm, access_tokens: Arc, ) -> JoinHandle<()> { let server = ApiServer::new(Launcher::new(socket, tls)) - .start(tracker, ban_service, form, access_tokens) + .start( + tracker, + stats_event_sender, + stats_repository, + ban_service, + form, + access_tokens, + ) .await .expect("it should be able to start to the tracker api"); @@ -107,6 +142,7 @@ mod tests { use crate::bootstrap::app::initialize_with_configuration; use crate::bootstrap::jobs::tracker_apis::start_job; + use crate::core::services::statistics; use crate::servers::apis::Version; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -116,12 +152,26 @@ mod tests { async fn it_should_start_http_tracker() { let cfg = Arc::new(ephemeral_public()); let config = &cfg.http_api.clone().unwrap(); - let tracker = initialize_with_configuration(&cfg); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let (stats_event_sender, stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + let stats_repository = Arc::new(stats_repository); + + let tracker = initialize_with_configuration(&cfg); + let version = Version::V1; - start_job(config, tracker, ban_service, Registar::default().give_form(), version) - .await - .expect("it should be able to join to the tracker api start-job"); + start_job( + config, + tracker, + ban_service, + stats_event_sender, + stats_repository, + Registar::default().give_form(), + version, + ) + .await + .expect("it should be able to join to the tracker api start-job"); } } diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 8948811af..105c7f723 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -14,6 +14,7 @@ use torrust_tracker_configuration::UdpTracker; use tracing::instrument; use crate::core; +use crate::core::statistics::event::sender::Sender; use crate::servers::registar::ServiceRegistrationForm; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::spawner::Spawner; @@ -31,10 +32,11 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// It will panic if the task did not finish successfully. #[must_use] #[allow(clippy::async_yields_async)] -#[instrument(skip(config, tracker, ban_service, form))] +#[instrument(skip(config, tracker, stats_event_sender, ban_service, form))] pub async fn start_job( config: &UdpTracker, tracker: Arc, + stats_event_sender: Arc>>, ban_service: Arc>, form: ServiceRegistrationForm, ) -> JoinHandle<()> { @@ -42,7 +44,7 @@ pub async fn start_job( let cookie_lifetime = config.cookie_lifetime; let server = Server::new(Spawner::new(bind_to)) - .start(tracker, ban_service, form, cookie_lifetime) + .start(tracker, stats_event_sender, ban_service, form, cookie_lifetime) .await .expect("it should be able to start the udp tracker"); diff --git a/src/console/profiling.rs b/src/console/profiling.rs index 1d31af3ce..2f6471906 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -179,9 +179,9 @@ pub async fn run() { return; }; - let (config, tracker, ban_service) = bootstrap::app::setup(); + let (config, tracker, ban_service, stats_event_sender, stats_repository) = bootstrap::app::setup(); - let jobs = app::start(&config, tracker, ban_service).await; + let jobs = app::start(&config, tracker, ban_service, stats_event_sender, stats_repository).await; // Run the tracker for a fixed duration let run_duration = sleep(Duration::from_secs(duration_secs)); diff --git a/src/core/mod.rs b/src/core/mod.rs index d61474c2c..9aef1b2f2 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -422,7 +422,7 @@ //! For example, the HTTP tracker would send an event like the following when it handles an `announce` request received from a peer using IP version 4. //! //! ```text -//! tracker.send_stats_event(statistics::event::Event::Tcp4Announce).await +//! stats_event_sender.send_stats_event(statistics::event::Event::Tcp4Announce).await //! ``` //! //! Refer to [`statistics`] module for more information about statistics. @@ -458,7 +458,6 @@ use std::time::Duration; use auth::PeerKey; use bittorrent_primitives::info_hash::InfoHash; use error::PeerKeyError; -use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_located_error::Located; @@ -502,12 +501,6 @@ pub struct Tracker { /// The in-memory torrents repository. torrents: Arc, - - /// Service to send stats events. - stats_event_sender: Arc>>, - - /// The in-memory stats repo. - stats_repository: Arc, } /// How many peers the peer announcing wants in the announce response. @@ -576,8 +569,6 @@ impl Tracker { config: &Core, database: &Arc>, whitelist_manager: &Arc, - stats_event_sender: &Arc>>, - stats_repository: &Arc, ) -> Result { Ok(Tracker { config: config.clone(), @@ -585,8 +576,6 @@ impl Tracker { keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), whitelist_manager: whitelist_manager.clone(), torrents: Arc::default(), - stats_event_sender: stats_event_sender.clone(), - stats_repository: stats_repository.clone(), }) } @@ -1054,26 +1043,6 @@ impl Tracker { }) } - /// It return the `Tracker` [`statistics::metrics::Metrics`]. - /// - /// # Context: Statistics - pub async fn get_stats(&self) -> tokio::sync::RwLockReadGuard<'_, statistics::metrics::Metrics> { - self.stats_repository.get_stats().await - } - - /// It allows to send a statistic events which eventually will be used to update [`statistics::metrics::Metrics`]. - /// - /// # Context: Statistics - pub async fn send_stats_event( - &self, - event: statistics::event::Event, - ) -> Option>> { - match &*self.stats_event_sender { - None => None, - Some(stats_event_sender) => stats_event_sender.send_event(event).await, - } - } - /// It drops the database tables. /// /// # Errors @@ -1119,20 +1088,20 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager) } fn private_tracker() -> Tracker { let config = configuration::ephemeral_private(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager) } fn whitelisted_tracker() -> (Tracker, Arc) { let config = configuration::ephemeral_listed(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - let tracker = tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let tracker = tracker_factory(&config, &database, &whitelist_manager); (tracker, whitelist_manager) } @@ -1140,8 +1109,8 @@ mod tests { pub fn tracker_persisting_torrents_in_database() -> Tracker { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + tracker_factory(&config, &database, &whitelist_manager) } fn sample_info_hash() -> InfoHash { diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index 4034925cd..d3336068c 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -14,8 +14,6 @@ use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::Configuration; use super::databases::{self, Database}; -use super::statistics::event::sender::Sender; -use super::statistics::repository::Repository; use super::whitelist::persisted::DatabaseWhitelist; use super::whitelist::WhiteListManager; use crate::core::Tracker; @@ -30,18 +28,8 @@ pub fn tracker_factory( config: &Configuration, database: &Arc>, whitelist_manager: &Arc, - stats_event_sender: &Arc>>, - stats_repository: &Arc, ) -> Tracker { - //let (stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - - match Tracker::new( - &Arc::new(config).core, - database, - whitelist_manager, - stats_event_sender, - stats_repository, - ) { + match Tracker::new(&Arc::new(config).core, database, whitelist_manager) { Ok(tracker) => tracker, Err(error) => { panic!("{}", error) diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 3c44bc310..657f3eb06 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -10,7 +10,7 @@ //! The factory function builds two structs: //! //! - An statistics event [`Sender`](crate::core::statistics::event::sender::Sender) -//! - An statistics [`Repository`](crate::core::statistics::repository::Repository) +//! - An statistics [`Repository`] //! //! ```text //! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); @@ -44,6 +44,7 @@ use tokio::sync::RwLock; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use crate::core::statistics::metrics::Metrics; +use crate::core::statistics::repository::Repository; use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; @@ -62,9 +63,13 @@ pub struct TrackerMetrics { } /// It returns all the [`TrackerMetrics`] -pub async fn get_metrics(tracker: Arc, ban_service: Arc>) -> TrackerMetrics { +pub async fn get_metrics( + tracker: Arc, + ban_service: Arc>, + stats_repository: Arc, +) -> TrackerMetrics { let torrents_metrics = tracker.get_torrents_metrics(); - let stats = tracker.get_stats().await; + let stats = stats_repository.get_stats().await; let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); TrackerMetrics { @@ -114,7 +119,7 @@ mod tests { use crate::bootstrap::app::initialize_tracker_dependencies; use crate::core; - use crate::core::services::statistics::{get_metrics, TrackerMetrics}; + use crate::core::services::statistics::{self, get_metrics, TrackerMetrics}; use crate::core::services::tracker_factory; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -127,18 +132,15 @@ mod tests { async fn the_statistics_service_should_return_the_tracker_metrics() { let config = tracker_configuration(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory( - &config, - &database, - &whitelist_manager, - &stats_event_sender, - &stats_repository, - )); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let stats_repository = Arc::new(stats_repository); + + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let tracker_metrics = get_metrics(tracker.clone(), ban_service.clone()).await; + let tracker_metrics = get_metrics(tracker.clone(), ban_service.clone(), stats_repository.clone()).await; assert_eq!( tracker_metrics, diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index a4db67979..9a1a2a725 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -142,8 +142,8 @@ mod tests { async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { let config = tracker_configuration(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - let tracker = tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let tracker = tracker_factory(&config, &database, &whitelist_manager); let tracker = Arc::new(tracker); @@ -159,14 +159,9 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let config = tracker_configuration(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory( - &config, - &database, - &whitelist_manager, - &stats_event_sender, - &stats_repository, - )); + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -208,14 +203,9 @@ mod tests { #[tokio::test] async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let config = tracker_configuration(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory( - &config, - &database, - &whitelist_manager, - &stats_event_sender, - &stats_repository, - )); + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -225,14 +215,9 @@ mod tests { #[tokio::test] async fn should_return_a_summarized_info_for_all_torrents() { let config = tracker_configuration(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory( - &config, - &database, - &whitelist_manager, - &stats_event_sender, - &stats_repository, - )); + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -255,14 +240,9 @@ mod tests { #[tokio::test] async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let config = tracker_configuration(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory( - &config, - &database, - &whitelist_manager, - &stats_event_sender, - &stats_repository, - )); + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -283,14 +263,9 @@ mod tests { #[tokio::test] async fn should_allow_using_pagination_in_the_result() { let config = tracker_configuration(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory( - &config, - &database, - &whitelist_manager, - &stats_event_sender, - &stats_repository, - )); + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -320,14 +295,9 @@ mod tests { #[tokio::test] async fn should_return_torrents_ordered_by_info_hash() { let config = tracker_configuration(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory( - &config, - &database, - &whitelist_manager, - &stats_event_sender, - &stats_repository, - )); + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); diff --git a/src/main.rs b/src/main.rs index c93982191..e536124a2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,9 +2,9 @@ use torrust_tracker_lib::{app, bootstrap}; #[tokio::main] async fn main() { - let (config, tracker, udp_ban_service) = bootstrap::app::setup(); + let (config, tracker, udp_ban_service, stats_event_sender, stats_repository) = bootstrap::app::setup(); - let jobs = app::start(&config, tracker, udp_ban_service).await; + let jobs = app::start(&config, tracker, udp_ban_service, stats_event_sender, stats_repository).await; // handle the signals tokio::select! { diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 98442ea97..cb3789a06 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -30,6 +30,8 @@ use tracing::{instrument, Level, Span}; use super::v1; use super::v1::context::health_check::handlers::health_check_handler; use super::v1::middlewares::auth::State; +use crate::core::statistics::event::sender::Sender; +use crate::core::statistics::repository::Repository; use crate::core::Tracker; use crate::servers::apis::API_LOG_TARGET; use crate::servers::logging::Latency; @@ -37,10 +39,12 @@ use crate::servers::udp::server::banning::BanService; /// Add all API routes to the router. #[allow(clippy::needless_pass_by_value)] -#[instrument(skip(tracker, ban_service, access_tokens))] +#[instrument(skip(tracker, ban_service, stats_event_sender, stats_repository, access_tokens))] pub fn router( tracker: Arc, ban_service: Arc>, + stats_event_sender: Arc>>, + stats_repository: Arc, access_tokens: Arc, server_socket_addr: SocketAddr, ) -> Router { @@ -48,7 +52,14 @@ pub fn router( let api_url_prefix = "/api"; - let router = v1::routes::add(api_url_prefix, router, tracker.clone(), ban_service.clone()); + let router = v1::routes::add( + api_url_prefix, + router, + tracker.clone(), + ban_service.clone(), + stats_event_sender.clone(), + stats_repository.clone(), + ); let state = State { access_tokens }; diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 9d1c77c03..bf1511edb 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -39,7 +39,8 @@ use tracing::{instrument, Level}; use super::routes::router; use crate::bootstrap::jobs::Started; -use crate::core::Tracker; +use crate::core::statistics::repository::Repository; +use crate::core::{statistics, Tracker}; use crate::servers::apis::API_LOG_TARGET; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::logging::STARTED_ON; @@ -124,10 +125,12 @@ impl ApiServer { /// # Panics /// /// It would panic if the bound socket address cannot be sent back to this starter. - #[instrument(skip(self, tracker, ban_service, form, access_tokens), err, ret(Display, level = Level::INFO))] + #[instrument(skip(self, tracker, stats_event_sender, ban_service, stats_repository, form, access_tokens), err, ret(Display, level = Level::INFO))] pub async fn start( self, tracker: Arc, + stats_event_sender: Arc>>, + stats_repository: Arc, ban_service: Arc>, form: ServiceRegistrationForm, access_tokens: Arc, @@ -140,7 +143,17 @@ impl ApiServer { let task = tokio::spawn(async move { tracing::debug!(target: API_LOG_TARGET, "Starting with launcher in spawned task ..."); - let _task = launcher.start(tracker, ban_service, access_tokens, tx_start, rx_halt).await; + let _task = launcher + .start( + tracker, + ban_service, + stats_event_sender, + stats_repository, + access_tokens, + tx_start, + rx_halt, + ) + .await; tracing::debug!(target: API_LOG_TARGET, "Started with launcher in spawned task"); @@ -238,11 +251,23 @@ impl Launcher { /// /// Will panic if unable to bind to the socket, or unable to get the address of the bound socket. /// Will also panic if unable to send message regarding the bound socket address. - #[instrument(skip(self, tracker, ban_service, access_tokens, tx_start, rx_halt))] + #[allow(clippy::too_many_arguments)] + #[instrument(skip( + self, + tracker, + ban_service, + stats_event_sender, + stats_repository, + access_tokens, + tx_start, + rx_halt + ))] pub fn start( &self, tracker: Arc, ban_service: Arc>, + stats_event_sender: Arc>>, + stats_repository: Arc, access_tokens: Arc, tx_start: Sender, rx_halt: Receiver, @@ -250,7 +275,14 @@ impl Launcher { let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); - let router = router(tracker, ban_service, access_tokens, address); + let router = router( + tracker, + ban_service, + stats_event_sender, + stats_repository, + access_tokens, + address, + ); let handle = Handle::new(); @@ -303,6 +335,7 @@ mod tests { use crate::bootstrap::app::initialize_with_configuration; use crate::bootstrap::jobs::make_rust_tls; + use crate::core::services::statistics; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -313,8 +346,11 @@ mod tests { let cfg = Arc::new(ephemeral_public()); let config = &cfg.http_api.clone().unwrap(); - let tracker = initialize_with_configuration(&cfg); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let (stats_event_sender, stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + let stats_repository = Arc::new(stats_repository); + let tracker = initialize_with_configuration(&cfg); let bind_to = config.bind_address; @@ -329,7 +365,14 @@ mod tests { let register = &Registar::default(); let started = stopped - .start(tracker, ban_service, register.give_form(), access_tokens) + .start( + tracker, + stats_event_sender, + stats_repository, + ban_service, + register.give_form(), + access_tokens, + ) .await .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index b630c763d..af7e1c239 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -10,6 +10,7 @@ use tokio::sync::RwLock; use super::responses::{metrics_response, stats_response}; use crate::core::services::statistics::get_metrics; +use crate::core::statistics::repository::Repository; use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; @@ -37,11 +38,12 @@ pub struct QueryParams { /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::stats#get-tracker-statistics) /// for more information about this endpoint. +#[allow(clippy::type_complexity)] pub async fn get_stats_handler( - State(state): State<(Arc, Arc>)>, + State(state): State<(Arc, Arc>, Arc)>, params: Query, ) -> Response { - let metrics = get_metrics(state.0.clone(), state.1.clone()).await; + let metrics = get_metrics(state.0.clone(), state.1.clone(), state.2.clone()).await; match params.0.format { Some(format) => match format { diff --git a/src/servers/apis/v1/context/stats/routes.rs b/src/servers/apis/v1/context/stats/routes.rs index fde1056c3..b5df32963 100644 --- a/src/servers/apis/v1/context/stats/routes.rs +++ b/src/servers/apis/v1/context/stats/routes.rs @@ -10,13 +10,22 @@ use axum::Router; use tokio::sync::RwLock; use super::handlers::get_stats_handler; +use crate::core::statistics::event::sender::Sender; +use crate::core::statistics::repository::Repository; use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; /// It adds the routes to the router for the [`stats`](crate::servers::apis::v1::context::stats) API context. -pub fn add(prefix: &str, router: Router, tracker: Arc, ban_service: Arc>) -> Router { +pub fn add( + prefix: &str, + router: Router, + tracker: Arc, + ban_service: Arc>, + _stats_event_sender: Arc>>, + stats_repository: Arc, +) -> Router { router.route( &format!("{prefix}/stats"), - get(get_stats_handler).with_state((tracker, ban_service)), + get(get_stats_handler).with_state((tracker, ban_service, stats_repository)), ) } diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs index 4c97c7578..9fbd5da0e 100644 --- a/src/servers/apis/v1/routes.rs +++ b/src/servers/apis/v1/routes.rs @@ -5,15 +5,31 @@ use axum::Router; use tokio::sync::RwLock; use super::context::{auth_key, stats, torrent, whitelist}; +use crate::core::statistics::event::sender::Sender; +use crate::core::statistics::repository::Repository; use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; /// Add the routes for the v1 API. -pub fn add(prefix: &str, router: Router, tracker: Arc, ban_service: Arc>) -> Router { +pub fn add( + prefix: &str, + router: Router, + tracker: Arc, + ban_service: Arc>, + stats_event_sender: Arc>>, + stats_repository: Arc, +) -> Router { let v1_prefix = format!("{prefix}/v1"); let router = auth_key::routes::add(&v1_prefix, router, tracker.clone()); - let router = stats::routes::add(&v1_prefix, router, tracker.clone(), ban_service); + let router = stats::routes::add( + &v1_prefix, + router, + tracker.clone(), + ban_service, + stats_event_sender, + stats_repository, + ); let router = whitelist::routes::add(&v1_prefix, router, &tracker); torrent::routes::add(&v1_prefix, router, tracker) diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 560d91681..537fc37fb 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -11,7 +11,7 @@ use tracing::instrument; use super::v1::routes::router; use crate::bootstrap::jobs::Started; -use crate::core::Tracker; +use crate::core::{statistics, Tracker}; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; use crate::servers::logging::STARTED_ON; @@ -42,8 +42,14 @@ pub struct Launcher { } impl Launcher { - #[instrument(skip(self, tracker, tx_start, rx_halt))] - fn start(&self, tracker: Arc, tx_start: Sender, rx_halt: Receiver) -> BoxFuture<'static, ()> { + #[instrument(skip(self, tracker, stats_event_sender, tx_start, rx_halt))] + fn start( + &self, + tracker: Arc, + stats_event_sender: Arc>>, + tx_start: Sender, + rx_halt: Receiver, + ) -> BoxFuture<'static, ()> { let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); @@ -60,7 +66,7 @@ impl Launcher { tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{}", address); - let app = router(tracker, address); + let app = router(tracker, stats_event_sender, address); let running = Box::pin(async { match tls { @@ -153,14 +159,19 @@ impl HttpServer { /// /// It would panic spawned HTTP server launcher cannot send the bound `SocketAddr` /// back to the main thread. - pub async fn start(self, tracker: Arc, form: ServiceRegistrationForm) -> Result, Error> { + pub async fn start( + self, + tracker: Arc, + stats_event_sender: Arc>>, + form: ServiceRegistrationForm, + ) -> Result, Error> { let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); let launcher = self.state.launcher; let task = tokio::spawn(async move { - let server = launcher.start(tracker, tx_start, rx_halt); + let server = launcher.start(tracker, stats_event_sender, tx_start, rx_halt); server.await; @@ -233,13 +244,18 @@ mod tests { use crate::bootstrap::app::initialize_with_configuration; use crate::bootstrap::jobs::make_rust_tls; + use crate::core::services::statistics; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::registar::Registar; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_public()); + + let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); let tracker = initialize_with_configuration(&cfg); + let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); let config = &http_trackers[0]; @@ -253,7 +269,7 @@ mod tests { let stopped = HttpServer::new(Launcher::new(bind_to, tls)); let started = stopped - .start(tracker, register.give_form()) + .start(tracker, stats_event_sender, register.give_form()) .await .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index b21f035da..1c8779625 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -22,6 +22,7 @@ use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; use crate::core::auth::Key; +use crate::core::statistics::event::sender::Sender; use crate::core::{PeersWanted, Tracker}; use crate::servers::http::v1::extractors::announce_request::ExtractRequest; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; @@ -33,28 +34,30 @@ use crate::CurrentClock; /// It handles the `announce` request when the HTTP tracker does not require /// authentication (no PATH `key` parameter required). #[allow(clippy::unused_async)] +#[allow(clippy::type_complexity)] pub async fn handle_without_key( - State(tracker): State>, + State(state): State<(Arc, Arc>>)>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { tracing::debug!("http announce request: {:#?}", announce_request); - handle(&tracker, &announce_request, &client_ip_sources, None).await + handle(&state.0, &state.1, &announce_request, &client_ip_sources, None).await } /// It handles the `announce` request when the HTTP tracker requires /// authentication (PATH `key` parameter required). #[allow(clippy::unused_async)] +#[allow(clippy::type_complexity)] pub async fn handle_with_key( - State(tracker): State>, + State(state): State<(Arc, Arc>>)>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { tracing::debug!("http announce request: {:#?}", announce_request); - handle(&tracker, &announce_request, &client_ip_sources, Some(key)).await + handle(&state.0, &state.1, &announce_request, &client_ip_sources, Some(key)).await } /// It handles the `announce` request. @@ -63,11 +66,20 @@ pub async fn handle_with_key( /// `unauthenticated` modes. async fn handle( tracker: &Arc, + opt_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Response { - let announce_data = match handle_announce(tracker, announce_request, client_ip_sources, maybe_key).await { + let announce_data = match handle_announce( + tracker, + opt_stats_event_sender, + announce_request, + client_ip_sources, + maybe_key, + ) + .await + { Ok(announce_data) => announce_data, Err(error) => return (StatusCode::OK, error.write()).into_response(), }; @@ -82,6 +94,7 @@ async fn handle( async fn handle_announce( tracker: &Arc, + opt_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, maybe_key: Option, @@ -118,7 +131,14 @@ async fn handle_announce( None => PeersWanted::All, }; - let announce_data = services::announce::invoke(tracker.clone(), announce_request.info_hash, &mut peer, &peers_wanted).await; + let announce_data = services::announce::invoke( + tracker.clone(), + opt_stats_event_sender.clone(), + announce_request.info_hash, + &mut peer, + &peers_wanted, + ) + .await; Ok(announce_data) } @@ -186,31 +206,44 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::bootstrap::app::initialize_tracker_dependencies; - use crate::core::services::tracker_factory; + use crate::core::services::{statistics, tracker_factory}; + use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; - fn private_tracker() -> Tracker { + fn private_tracker() -> (Tracker, Option>) { let config = configuration::ephemeral_private(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + + (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) } - fn whitelisted_tracker() -> Tracker { + fn whitelisted_tracker() -> (Tracker, Option>) { let config = configuration::ephemeral_listed(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + + (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) } - fn tracker_on_reverse_proxy() -> Tracker { + fn tracker_on_reverse_proxy() -> (Tracker, Option>) { let config = configuration::ephemeral_with_reverse_proxy(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + + (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) } - fn tracker_not_on_reverse_proxy() -> Tracker { + fn tracker_not_on_reverse_proxy() -> (Tracker, Option>) { let config = configuration::ephemeral_without_reverse_proxy(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + + (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) } fn sample_announce_request() -> Announce { @@ -253,13 +286,22 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_missing() { - let tracker = Arc::new(private_tracker()); + let (tracker, stats_event_sender) = private_tracker(); + + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let maybe_key = None; - let response = handle_announce(&tracker, &sample_announce_request(), &sample_client_ip_sources(), maybe_key) - .await - .unwrap_err(); + let response = handle_announce( + &tracker, + &stats_event_sender, + &sample_announce_request(), + &sample_client_ip_sources(), + maybe_key, + ) + .await + .unwrap_err(); assert_error_response( &response, @@ -269,15 +311,24 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_invalid() { - let tracker = Arc::new(private_tracker()); + let (tracker, stats_event_sender) = private_tracker(); + + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let unregistered_key = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); let maybe_key = Some(unregistered_key); - let response = handle_announce(&tracker, &sample_announce_request(), &sample_client_ip_sources(), maybe_key) - .await - .unwrap_err(); + let response = handle_announce( + &tracker, + &stats_event_sender, + &sample_announce_request(), + &sample_client_ip_sources(), + maybe_key, + ) + .await + .unwrap_err(); assert_error_response(&response, "Authentication error: Failed to read key"); } @@ -293,13 +344,22 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_announced_torrent_is_not_whitelisted() { - let tracker = Arc::new(whitelisted_tracker()); + let (tracker, stats_event_sender) = whitelisted_tracker(); + + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let announce_request = sample_announce_request(); - let response = handle_announce(&tracker, &announce_request, &sample_client_ip_sources(), None) - .await - .unwrap_err(); + let response = handle_announce( + &tracker, + &stats_event_sender, + &announce_request, + &sample_client_ip_sources(), + None, + ) + .await + .unwrap_err(); assert_error_response( &response, @@ -323,16 +383,25 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let tracker = Arc::new(tracker_on_reverse_proxy()); + let (tracker, stats_event_sender) = tracker_on_reverse_proxy(); + + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, connection_info_ip: None, }; - let response = handle_announce(&tracker, &sample_announce_request(), &client_ip_sources, None) - .await - .unwrap_err(); + let response = handle_announce( + &tracker, + &stats_event_sender, + &sample_announce_request(), + &client_ip_sources, + None, + ) + .await + .unwrap_err(); assert_error_response( &response, @@ -353,16 +422,25 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let tracker = Arc::new(tracker_not_on_reverse_proxy()); + let (tracker, stats_event_sender) = tracker_not_on_reverse_proxy(); + + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, connection_info_ip: None, }; - let response = handle_announce(&tracker, &sample_announce_request(), &client_ip_sources, None) - .await - .unwrap_err(); + let response = handle_announce( + &tracker, + &stats_event_sender, + &sample_announce_request(), + &client_ip_sources, + None, + ) + .await + .unwrap_err(); assert_error_response( &response, diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 41afb6bbb..6ff8a61cf 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -16,6 +16,7 @@ use hyper::StatusCode; use torrust_tracker_primitives::core::ScrapeData; use crate::core::auth::Key; +use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; @@ -25,14 +26,15 @@ use crate::servers::http::v1::services; /// It handles the `scrape` request when the HTTP tracker is configured /// to run in `public` mode. #[allow(clippy::unused_async)] +#[allow(clippy::type_complexity)] pub async fn handle_without_key( - State(tracker): State>, + State(state): State<(Arc, Arc>>)>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { tracing::debug!("http scrape request: {:#?}", &scrape_request); - handle(&tracker, &scrape_request, &client_ip_sources, None).await + handle(&state.0, &state.1, &scrape_request, &client_ip_sources, None).await } /// It handles the `scrape` request when the HTTP tracker is configured @@ -40,24 +42,26 @@ pub async fn handle_without_key( /// /// In this case, the authentication `key` parameter is required. #[allow(clippy::unused_async)] +#[allow(clippy::type_complexity)] pub async fn handle_with_key( - State(tracker): State>, + State(state): State<(Arc, Arc>>)>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { tracing::debug!("http scrape request: {:#?}", &scrape_request); - handle(&tracker, &scrape_request, &client_ip_sources, Some(key)).await + handle(&state.0, &state.1, &scrape_request, &client_ip_sources, Some(key)).await } async fn handle( tracker: &Arc, + stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Response { - let scrape_data = match handle_scrape(tracker, scrape_request, client_ip_sources, maybe_key).await { + let scrape_data = match handle_scrape(tracker, stats_event_sender, scrape_request, client_ip_sources, maybe_key).await { Ok(scrape_data) => scrape_data, Err(error) => return (StatusCode::OK, error.write()).into_response(), }; @@ -72,6 +76,7 @@ async fn handle( async fn handle_scrape( tracker: &Arc, + opt_stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, maybe_key: Option, @@ -98,9 +103,9 @@ async fn handle_scrape( }; if return_real_scrape_data { - Ok(services::scrape::invoke(tracker, &scrape_request.info_hashes, &peer_ip).await) + Ok(services::scrape::invoke(tracker, opt_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await) } else { - Ok(services::scrape::fake(tracker, &scrape_request.info_hashes, &peer_ip).await) + Ok(services::scrape::fake(opt_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await) } } @@ -122,31 +127,43 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::bootstrap::app::initialize_tracker_dependencies; - use crate::core::services::tracker_factory; + use crate::core::services::{statistics, tracker_factory}; use crate::core::Tracker; - fn private_tracker() -> Tracker { + fn private_tracker() -> (Tracker, Option>) { let config = configuration::ephemeral_private(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + + (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) } - fn whitelisted_tracker() -> Tracker { + fn whitelisted_tracker() -> (Tracker, Option>) { let config = configuration::ephemeral_listed(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + + (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) } - fn tracker_on_reverse_proxy() -> Tracker { + fn tracker_on_reverse_proxy() -> (Tracker, Option>) { let config = configuration::ephemeral_with_reverse_proxy(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + + (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) } - fn tracker_not_on_reverse_proxy() -> Tracker { + fn tracker_not_on_reverse_proxy() -> (Tracker, Option>) { let config = configuration::ephemeral_without_reverse_proxy(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + + (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) } fn sample_scrape_request() -> Scrape { @@ -181,14 +198,22 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { - let tracker = Arc::new(private_tracker()); + let (tracker, stats_event_sender) = private_tracker(); + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let scrape_request = sample_scrape_request(); let maybe_key = None; - let scrape_data = handle_scrape(&tracker, &scrape_request, &sample_client_ip_sources(), maybe_key) - .await - .unwrap(); + let scrape_data = handle_scrape( + &tracker, + &stats_event_sender, + &scrape_request, + &sample_client_ip_sources(), + maybe_key, + ) + .await + .unwrap(); let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes); @@ -197,15 +222,23 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() { - let tracker = Arc::new(private_tracker()); + let (tracker, stats_event_sender) = private_tracker(); + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let scrape_request = sample_scrape_request(); let unregistered_key = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); let maybe_key = Some(unregistered_key); - let scrape_data = handle_scrape(&tracker, &scrape_request, &sample_client_ip_sources(), maybe_key) - .await - .unwrap(); + let scrape_data = handle_scrape( + &tracker, + &stats_event_sender, + &scrape_request, + &sample_client_ip_sources(), + maybe_key, + ) + .await + .unwrap(); let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes); @@ -224,13 +257,21 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() { - let tracker = Arc::new(whitelisted_tracker()); + let (tracker, stats_event_sender) = whitelisted_tracker(); + let tracker: Arc = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let scrape_request = sample_scrape_request(); - let scrape_data = handle_scrape(&tracker, &scrape_request, &sample_client_ip_sources(), None) - .await - .unwrap(); + let scrape_data = handle_scrape( + &tracker, + &stats_event_sender, + &scrape_request, + &sample_client_ip_sources(), + None, + ) + .await + .unwrap(); let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes); @@ -249,16 +290,24 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let tracker = Arc::new(tracker_on_reverse_proxy()); + let (tracker, stats_event_sender) = tracker_on_reverse_proxy(); + let tracker: Arc = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, connection_info_ip: None, }; - let response = handle_scrape(&tracker, &sample_scrape_request(), &client_ip_sources, None) - .await - .unwrap_err(); + let response = handle_scrape( + &tracker, + &stats_event_sender, + &sample_scrape_request(), + &client_ip_sources, + None, + ) + .await + .unwrap_err(); assert_error_response( &response, @@ -278,16 +327,24 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let tracker = Arc::new(tracker_not_on_reverse_proxy()); + let (tracker, stats_event_sender) = tracker_not_on_reverse_proxy(); + let tracker: Arc = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, connection_info_ip: None, }; - let response = handle_scrape(&tracker, &sample_scrape_request(), &client_ip_sources, None) - .await - .unwrap_err(); + let response = handle_scrape( + &tracker, + &stats_event_sender, + &sample_scrape_request(), + &client_ip_sources, + None, + ) + .await + .unwrap_err(); assert_error_response( &response, diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 3c6926c37..97eb5b95d 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -22,6 +22,7 @@ use tower_http::LatencyUnit; use tracing::{instrument, Level, Span}; use super::handlers::{announce, health_check, scrape}; +use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; use crate::servers::logging::Latency; @@ -31,17 +32,29 @@ use crate::servers::logging::Latency; /// > **NOTICE**: it's added a layer to get the client IP from the connection /// > info. The tracker could use the connection info to get the client IP. #[allow(clippy::needless_pass_by_value)] -#[instrument(skip(tracker, server_socket_addr))] -pub fn router(tracker: Arc, server_socket_addr: SocketAddr) -> Router { +#[instrument(skip(tracker, stats_event_sender, server_socket_addr))] +pub fn router(tracker: Arc, stats_event_sender: Arc>>, server_socket_addr: SocketAddr) -> Router { Router::new() // Health check .route("/health_check", get(health_check::handler)) // Announce request - .route("/announce", get(announce::handle_without_key).with_state(tracker.clone())) - .route("/announce/{key}", get(announce::handle_with_key).with_state(tracker.clone())) + .route( + "/announce", + get(announce::handle_without_key).with_state((tracker.clone(), stats_event_sender.clone())), + ) + .route( + "/announce/{key}", + get(announce::handle_with_key).with_state((tracker.clone(), stats_event_sender.clone())), + ) // Scrape request - .route("/scrape", get(scrape::handle_without_key).with_state(tracker.clone())) - .route("/scrape/{key}", get(scrape::handle_with_key).with_state(tracker)) + .route( + "/scrape", + get(scrape::handle_without_key).with_state((tracker.clone(), stats_event_sender.clone())), + ) + .route( + "/scrape/{key}", + get(scrape::handle_with_key).with_state((tracker.clone(), stats_event_sender.clone())), + ) // Add extension to get the client IP from the connection info .layer(SecureClientIpSource::ConnectInfo.into_extension()) .layer(CompressionLayer::new()) diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 3a4d4820a..45bcb5843 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -15,7 +15,9 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; -use crate::core::{statistics, PeersWanted, Tracker}; +use crate::core::statistics::event::sender::Sender; +use crate::core::statistics::{self}; +use crate::core::{PeersWanted, Tracker}; /// The HTTP tracker `announce` service. /// @@ -29,6 +31,7 @@ use crate::core::{statistics, PeersWanted, Tracker}; /// > each `announce` request. pub async fn invoke( tracker: Arc, + opt_stats_event_sender: Arc>>, info_hash: InfoHash, peer: &mut peer::Peer, peers_wanted: &PeersWanted, @@ -38,12 +41,14 @@ pub async fn invoke( // The tracker could change the original peer ip let announce_data = tracker.announce(&info_hash, peer, &original_peer_ip, peers_wanted); - match original_peer_ip { - IpAddr::V4(_) => { - tracker.send_stats_event(statistics::event::Event::Tcp4Announce).await; - } - IpAddr::V6(_) => { - tracker.send_stats_event(statistics::event::Event::Tcp6Announce).await; + if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { + match original_peer_ip { + IpAddr::V4(_) => { + stats_event_sender.send_event(statistics::event::Event::Tcp4Announce).await; + } + IpAddr::V6(_) => { + stats_event_sender.send_event(statistics::event::Event::Tcp6Announce).await; + } } } @@ -53,6 +58,7 @@ pub async fn invoke( #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; @@ -60,13 +66,20 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::bootstrap::app::initialize_tracker_dependencies; - use crate::core::services::tracker_factory; + use crate::core::services::{statistics, tracker_factory}; + use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; - fn public_tracker() -> Tracker { + fn public_tracker() -> (Tracker, Arc>>) { let config = configuration::ephemeral_public(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + + let tracker = tracker_factory(&config, &database, &whitelist_manager); + + (tracker, stats_event_sender) } fn sample_info_hash() -> InfoHash { @@ -115,32 +128,30 @@ mod tests { use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; - fn test_tracker_factory(stats_event_sender: Option>) -> Tracker { + fn test_tracker_factory() -> Tracker { let config = configuration::ephemeral(); - let (database, whitelist_manager, _stats_event_sender, _stats_repository) = initialize_tracker_dependencies(&config); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let stats_event_sender = Arc::new(stats_event_sender); - - let stats_repository = Arc::new(statistics::repository::Repository::new()); - - Tracker::new( - &config.core, - &database, - &whitelist_manager, - &stats_event_sender, - &stats_repository, - ) - .unwrap() + Tracker::new(&config.core, &database, &whitelist_manager).unwrap() } #[tokio::test] async fn it_should_return_the_announce_data() { - let tracker = Arc::new(public_tracker()); + let (tracker, stats_event_sender) = public_tracker(); + + let tracker = Arc::new(tracker); let mut peer = sample_peer(); - let announce_data = invoke(tracker.clone(), sample_info_hash(), &mut peer, &PeersWanted::All).await; + let announce_data = invoke( + tracker.clone(), + stats_event_sender.clone(), + sample_info_hash(), + &mut peer, + &PeersWanted::All, + ) + .await; let expected_announce_data = AnnounceData { peers: vec![], @@ -163,22 +174,23 @@ mod tests { .with(eq(statistics::event::Event::Tcp4Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); + let tracker = Arc::new(test_tracker_factory()); let mut peer = sample_peer_using_ipv4(); - let _announce_data = invoke(tracker, sample_info_hash(), &mut peer, &PeersWanted::All).await; + let _announce_data = invoke(tracker, stats_event_sender, sample_info_hash(), &mut peer, &PeersWanted::All).await; } - fn tracker_with_an_ipv6_external_ip(stats_event_sender: Box) -> Tracker { + fn tracker_with_an_ipv6_external_ip() -> Tracker { let mut configuration = configuration::ephemeral(); configuration.core.net.external_ip = Some(IpAddr::V6(Ipv6Addr::new( 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, ))); - test_tracker_factory(Some(stats_event_sender)) + test_tracker_factory() } fn peer_with_the_ipv4_loopback_ip() -> peer::Peer { @@ -200,12 +212,14 @@ mod tests { .with(eq(statistics::event::Event::Tcp4Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); let mut peer = peer_with_the_ipv4_loopback_ip(); let _announce_data = invoke( - tracker_with_an_ipv6_external_ip(stats_event_sender).into(), + tracker_with_an_ipv6_external_ip().into(), + stats_event_sender, sample_info_hash(), &mut peer, &PeersWanted::All, @@ -222,13 +236,14 @@ mod tests { .with(eq(statistics::event::Event::Tcp6Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); + let tracker = Arc::new(test_tracker_factory()); let mut peer = sample_peer_using_ipv6(); - let _announce_data = invoke(tracker, sample_info_hash(), &mut peer, &PeersWanted::All).await; + let _announce_data = invoke(tracker, stats_event_sender, sample_info_hash(), &mut peer, &PeersWanted::All).await; } } } diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 01be81db6..9805dd8a4 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -14,7 +14,9 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::core::ScrapeData; -use crate::core::{statistics, Tracker}; +use crate::core::statistics::event::sender::Sender; +use crate::core::statistics::{self}; +use crate::core::Tracker; /// The HTTP tracker `scrape` service. /// @@ -26,10 +28,15 @@ use crate::core::{statistics, Tracker}; /// > **NOTICE**: as the HTTP tracker does not requires a connection request /// > like the UDP tracker, the number of TCP connections is incremented for /// > each `scrape` request. -pub async fn invoke(tracker: &Arc, info_hashes: &Vec, original_peer_ip: &IpAddr) -> ScrapeData { +pub async fn invoke( + tracker: &Arc, + opt_stats_event_sender: &Arc>>, + info_hashes: &Vec, + original_peer_ip: &IpAddr, +) -> ScrapeData { let scrape_data = tracker.scrape(info_hashes).await; - send_scrape_event(original_peer_ip, tracker).await; + send_scrape_event(original_peer_ip, opt_stats_event_sender).await; scrape_data } @@ -40,19 +47,25 @@ pub async fn invoke(tracker: &Arc, info_hashes: &Vec, origina /// the tracker returns empty stats for all the torrents. /// /// > **NOTICE**: tracker statistics are not updated in this case. -pub async fn fake(tracker: &Arc, info_hashes: &Vec, original_peer_ip: &IpAddr) -> ScrapeData { - send_scrape_event(original_peer_ip, tracker).await; +pub async fn fake( + opt_stats_event_sender: &Arc>>, + info_hashes: &Vec, + original_peer_ip: &IpAddr, +) -> ScrapeData { + send_scrape_event(original_peer_ip, opt_stats_event_sender).await; ScrapeData::zeroed(info_hashes) } -async fn send_scrape_event(original_peer_ip: &IpAddr, tracker: &Arc) { - match original_peer_ip { - IpAddr::V4(_) => { - tracker.send_stats_event(statistics::event::Event::Tcp4Scrape).await; - } - IpAddr::V6(_) => { - tracker.send_stats_event(statistics::event::Event::Tcp6Scrape).await; +async fn send_scrape_event(original_peer_ip: &IpAddr, opt_stats_event_sender: &Arc>>) { + if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { + match original_peer_ip { + IpAddr::V4(_) => { + stats_event_sender.send_event(statistics::event::Event::Tcp4Scrape).await; + } + IpAddr::V6(_) => { + stats_event_sender.send_event(statistics::event::Event::Tcp6Scrape).await; + } } } } @@ -61,7 +74,6 @@ async fn send_scrape_event(original_peer_ip: &IpAddr, tracker: &Arc) { mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; @@ -70,12 +82,14 @@ mod tests { use crate::bootstrap::app::initialize_tracker_dependencies; use crate::core::services::tracker_factory; - use crate::core::{statistics, Tracker}; + use crate::core::Tracker; fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager, &stats_event_sender, &stats_repository) + + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + + tracker_factory(&config, &database, &whitelist_manager) } fn sample_info_hashes() -> Vec { @@ -98,23 +112,12 @@ mod tests { } } - fn test_tracker_factory(stats_event_sender: Option>) -> Tracker { + fn test_tracker_factory() -> Tracker { let config = configuration::ephemeral(); - let (database, whitelist_manager, _stats_event_sender, _stats_repository) = initialize_tracker_dependencies(&config); - - let stats_event_sender = Arc::new(stats_event_sender); - - let stats_repository = Arc::new(statistics::repository::Repository::new()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - Tracker::new( - &config.core, - &database, - &whitelist_manager, - &stats_event_sender, - &stats_repository, - ) - .unwrap() + Tracker::new(&config.core, &database, &whitelist_manager).unwrap() } mod with_real_data { @@ -135,6 +138,9 @@ mod tests { #[tokio::test] async fn it_should_return_the_scrape_data_for_a_torrent() { + let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let stats_event_sender = Arc::new(stats_event_sender); + let tracker = Arc::new(public_tracker()); let info_hash = sample_info_hash(); @@ -145,7 +151,7 @@ mod tests { let original_peer_ip = peer.ip(); tracker.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); - let scrape_data = invoke(&tracker, &info_hashes, &original_peer_ip).await; + let scrape_data = invoke(&tracker, &stats_event_sender, &info_hashes, &original_peer_ip).await; let mut expected_scrape_data = ScrapeData::empty(); expected_scrape_data.add_file( @@ -168,13 +174,14 @@ mod tests { .with(eq(statistics::event::Event::Tcp4Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); + let tracker = Arc::new(test_tracker_factory()); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); - invoke(&tracker, &sample_info_hashes(), &peer_ip).await; + invoke(&tracker, &stats_event_sender, &sample_info_hashes(), &peer_ip).await; } #[tokio::test] @@ -185,13 +192,14 @@ mod tests { .with(eq(statistics::event::Event::Tcp6Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); + let tracker = Arc::new(test_tracker_factory()); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); - invoke(&tracker, &sample_info_hashes(), &peer_ip).await; + invoke(&tracker, &stats_event_sender, &sample_info_hashes(), &peer_ip).await; } } @@ -207,11 +215,13 @@ mod tests { use crate::core::{statistics, PeersWanted}; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ - public_tracker, sample_info_hash, sample_info_hashes, sample_peer, test_tracker_factory, + public_tracker, sample_info_hash, sample_info_hashes, sample_peer, }; #[tokio::test] async fn it_should_always_return_the_zeroed_scrape_data_for_a_torrent() { + let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let stats_event_sender = Arc::new(stats_event_sender); let tracker = Arc::new(public_tracker()); let info_hash = sample_info_hash(); @@ -222,7 +232,7 @@ mod tests { let original_peer_ip = peer.ip(); tracker.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); - let scrape_data = fake(&tracker, &info_hashes, &original_peer_ip).await; + let scrape_data = fake(&stats_event_sender, &info_hashes, &original_peer_ip).await; let expected_scrape_data = ScrapeData::zeroed(&info_hashes); @@ -237,13 +247,12 @@ mod tests { .with(eq(statistics::event::Event::Tcp4Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); - fake(&tracker, &sample_info_hashes(), &peer_ip).await; + fake(&stats_event_sender, &sample_info_hashes(), &peer_ip).await; } #[tokio::test] @@ -254,13 +263,12 @@ mod tests { .with(eq(statistics::event::Event::Tcp6Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); - - let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); - fake(&tracker, &sample_info_hashes(), &peer_ip).await; + fake(&stats_event_sender, &sample_info_hashes(), &peer_ip).await; } } } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 4b20c2ac5..9883de54b 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -20,6 +20,7 @@ use zerocopy::network_endian::I32; use super::connection_cookie::{check, make}; use super::server::banning::BanService; use super::RawRequest; +use crate::core::statistics::event::sender::Sender; use crate::core::{statistics, PeersWanted, Tracker}; use crate::servers::udp::error::Error; use crate::servers::udp::{peer_builder, UDP_TRACKER_LOG_TARGET}; @@ -53,10 +54,11 @@ impl CookieTimeValues { /// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. -#[instrument(fields(request_id), skip(udp_request, tracker, cookie_time_values, ban_service), ret(level = Level::TRACE))] +#[instrument(fields(request_id), skip(udp_request, tracker, opt_stats_event_sender, cookie_time_values, ban_service), ret(level = Level::TRACE))] pub(crate) async fn handle_packet( udp_request: RawRequest, tracker: &Tracker, + opt_stats_event_sender: &Arc>>, local_addr: SocketAddr, cookie_time_values: CookieTimeValues, ban_service: Arc>, @@ -70,7 +72,15 @@ pub(crate) async fn handle_packet( let response = match Request::parse_bytes(&udp_request.payload[..udp_request.payload.len()], MAX_SCRAPE_TORRENTS).map_err(Error::from) { - Ok(request) => match handle_request(request, udp_request.from, tracker, cookie_time_values.clone()).await { + Ok(request) => match handle_request( + request, + udp_request.from, + tracker, + opt_stats_event_sender, + cookie_time_values.clone(), + ) + .await + { Ok(response) => return response, Err((e, transaction_id)) => { match &e { @@ -88,7 +98,7 @@ pub(crate) async fn handle_packet( udp_request.from, local_addr, request_id, - tracker, + opt_stats_event_sender, cookie_time_values.valid_range.clone(), &e, Some(transaction_id), @@ -101,7 +111,7 @@ pub(crate) async fn handle_packet( udp_request.from, local_addr, request_id, - tracker, + opt_stats_event_sender, cookie_time_values.valid_range.clone(), &e, None, @@ -121,24 +131,43 @@ pub(crate) async fn handle_packet( /// # Errors /// /// If a error happens in the `handle_request` function, it will just return the `ServerError`. -#[instrument(skip(request, remote_addr, tracker, cookie_time_values))] +#[instrument(skip(request, remote_addr, tracker, opt_stats_event_sender, cookie_time_values))] pub async fn handle_request( request: Request, remote_addr: SocketAddr, tracker: &Tracker, + opt_stats_event_sender: &Arc>>, cookie_time_values: CookieTimeValues, ) -> Result { tracing::trace!("handle request"); match request { - Request::Connect(connect_request) => { - Ok(handle_connect(remote_addr, &connect_request, tracker, cookie_time_values.issue_time).await) - } + Request::Connect(connect_request) => Ok(handle_connect( + remote_addr, + &connect_request, + opt_stats_event_sender, + cookie_time_values.issue_time, + ) + .await), Request::Announce(announce_request) => { - handle_announce(remote_addr, &announce_request, tracker, cookie_time_values.valid_range).await + handle_announce( + remote_addr, + &announce_request, + tracker, + opt_stats_event_sender, + cookie_time_values.valid_range, + ) + .await } Request::Scrape(scrape_request) => { - handle_scrape(remote_addr, &scrape_request, tracker, cookie_time_values.valid_range).await + handle_scrape( + remote_addr, + &scrape_request, + tracker, + opt_stats_event_sender, + cookie_time_values.valid_range, + ) + .await } } } @@ -149,11 +178,11 @@ pub async fn handle_request( /// # Errors /// /// This function does not ever return an error. -#[instrument(fields(transaction_id), skip(tracker), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id), skip(opt_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_connect( remote_addr: SocketAddr, request: &ConnectRequest, - tracker: &Tracker, + opt_stats_event_sender: &Arc>>, cookie_issue_time: f64, ) -> Response { tracing::Span::current().record("transaction_id", request.transaction_id.0.to_string()); @@ -167,13 +196,14 @@ pub async fn handle_connect( connection_id, }; - // send stats event - match remote_addr { - SocketAddr::V4(_) => { - tracker.send_stats_event(statistics::event::Event::Udp4Connect).await; - } - SocketAddr::V6(_) => { - tracker.send_stats_event(statistics::event::Event::Udp6Connect).await; + if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + stats_event_sender.send_event(statistics::event::Event::Udp4Connect).await; + } + SocketAddr::V6(_) => { + stats_event_sender.send_event(statistics::event::Event::Udp6Connect).await; + } } } @@ -186,11 +216,12 @@ pub async fn handle_connect( /// # Errors /// /// If a error happens in the `handle_announce` function, it will just return the `ServerError`. -#[instrument(fields(transaction_id, connection_id, info_hash), skip(tracker), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id, info_hash), skip(tracker, opt_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_announce( remote_addr: SocketAddr, request: &AnnounceRequest, tracker: &Tracker, + opt_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { tracing::Span::current() @@ -224,12 +255,14 @@ pub async fn handle_announce( let response = tracker.announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted); - match remote_client_ip { - IpAddr::V4(_) => { - tracker.send_stats_event(statistics::event::Event::Udp4Announce).await; - } - IpAddr::V6(_) => { - tracker.send_stats_event(statistics::event::Event::Udp6Announce).await; + if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { + match remote_client_ip { + IpAddr::V4(_) => { + stats_event_sender.send_event(statistics::event::Event::Udp4Announce).await; + } + IpAddr::V6(_) => { + stats_event_sender.send_event(statistics::event::Event::Udp6Announce).await; + } } } @@ -293,11 +326,12 @@ pub async fn handle_announce( /// # Errors /// /// This function does not ever return an error. -#[instrument(fields(transaction_id, connection_id), skip(tracker), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id), skip(tracker, opt_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_scrape( remote_addr: SocketAddr, request: &ScrapeRequest, tracker: &Tracker, + opt_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { tracing::Span::current() @@ -338,13 +372,14 @@ pub async fn handle_scrape( torrent_stats.push(scrape_entry); } - // send stats event - match remote_addr { - SocketAddr::V4(_) => { - tracker.send_stats_event(statistics::event::Event::Udp4Scrape).await; - } - SocketAddr::V6(_) => { - tracker.send_stats_event(statistics::event::Event::Udp6Scrape).await; + if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + stats_event_sender.send_event(statistics::event::Event::Udp4Scrape).await; + } + SocketAddr::V6(_) => { + stats_event_sender.send_event(statistics::event::Event::Udp6Scrape).await; + } } } @@ -356,12 +391,12 @@ pub async fn handle_scrape( Ok(Response::from(response)) } -#[instrument(fields(transaction_id), skip(tracker), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id), skip(opt_stats_event_sender), ret(level = Level::TRACE))] async fn handle_error( remote_addr: SocketAddr, local_addr: SocketAddr, request_id: Uuid, - tracker: &Tracker, + opt_stats_event_sender: &Arc>>, cookie_valid_range: Range, e: &Error, transaction_id: Option, @@ -398,13 +433,14 @@ async fn handle_error( }; if e.1.is_some() { - // send stats event - match remote_addr { - SocketAddr::V4(_) => { - tracker.send_stats_event(statistics::event::Event::Udp4Error).await; - } - SocketAddr::V6(_) => { - tracker.send_stats_event(statistics::event::Event::Udp6Error).await; + if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + stats_event_sender.send_event(statistics::event::Event::Udp4Error).await; + } + SocketAddr::V6(_) => { + stats_event_sender.send_event(statistics::event::Event::Udp6Error).await; + } } } } @@ -426,7 +462,6 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::ops::Range; - use std::sync::Arc; use aquatic_udp_protocol::{NumberOfBytes, PeerId}; use torrust_tracker_clock::clock::Time; @@ -436,8 +471,9 @@ mod tests { use super::gen_remote_fingerprint; use crate::bootstrap::app::initialize_tracker_dependencies; - use crate::core::services::tracker_factory; - use crate::core::{statistics, Tracker}; + use crate::core::services::{statistics, tracker_factory}; + use crate::core::statistics::event::sender::Sender; + use crate::core::Tracker; use crate::CurrentClock; fn tracker_configuration() -> Configuration { @@ -448,17 +484,19 @@ mod tests { configuration::ephemeral() } - fn public_tracker() -> Arc { + fn public_tracker() -> (Tracker, Option>) { initialized_tracker(&configuration::ephemeral_public()) } - fn whitelisted_tracker() -> Arc { + fn whitelisted_tracker() -> (Tracker, Option>) { initialized_tracker(&configuration::ephemeral_listed()) } - fn initialized_tracker(config: &Configuration) -> Arc { - let (database, whitelist_manager, stats_event_sender, stats_repository) = initialize_tracker_dependencies(config); - tracker_factory(config, &database, &whitelist_manager, &stats_event_sender, &stats_repository).into() + fn initialized_tracker(config: &Configuration) -> (Tracker, Option>) { + let (database, whitelist_manager) = initialize_tracker_dependencies(config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + + (tracker_factory(config, &database, &whitelist_manager), stats_event_sender) } fn sample_ipv4_remote_addr() -> SocketAddr { @@ -555,23 +593,12 @@ mod tests { } } - fn test_tracker_factory(stats_event_sender: Option>) -> Tracker { + fn test_tracker_factory() -> Tracker { let config = tracker_configuration(); - let (database, whitelist_manager, _stats_event_sender, _stats_repository) = initialize_tracker_dependencies(&config); - - let stats_event_sender = Arc::new(stats_event_sender); - - let stats_repository = Arc::new(statistics::repository::Repository::new()); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - Tracker::new( - &config.core, - &database, - &whitelist_manager, - &stats_event_sender, - &stats_repository, - ) - .unwrap() + Tracker::new(&config.core, &database, &whitelist_manager).unwrap() } mod connect_request { @@ -587,8 +614,7 @@ mod tests { use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_connect; use crate::servers::udp::handlers::tests::{ - public_tracker, sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv6_remote_addr_fingerprint, - sample_issue_time, test_tracker_factory, + sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv6_remote_addr_fingerprint, sample_issue_time, }; fn sample_connect_request() -> ConnectRequest { @@ -599,11 +625,14 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { + let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let stats_event_sender = Arc::new(stats_event_sender); + let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), }; - let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker(), sample_issue_time()).await; + let response = handle_connect(sample_ipv4_remote_addr(), &request, &stats_event_sender, sample_issue_time()).await; assert_eq!( response, @@ -616,11 +645,14 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { + let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let stats_event_sender = Arc::new(stats_event_sender); + let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), }; - let response = handle_connect(sample_ipv4_remote_addr(), &request, &public_tracker(), sample_issue_time()).await; + let response = handle_connect(sample_ipv4_remote_addr(), &request, &stats_event_sender, sample_issue_time()).await; assert_eq!( response, @@ -633,11 +665,14 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { + let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let stats_event_sender = Arc::new(stats_event_sender); + let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), }; - let response = handle_connect(sample_ipv6_remote_addr(), &request, &public_tracker(), sample_issue_time()).await; + let response = handle_connect(sample_ipv6_remote_addr(), &request, &stats_event_sender, sample_issue_time()).await; assert_eq!( response, @@ -656,15 +691,15 @@ mod tests { .with(eq(statistics::event::Event::Udp4Connect)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); let client_socket_address = sample_ipv4_socket_address(); - let torrent_tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); handle_connect( client_socket_address, &sample_connect_request(), - &torrent_tracker, + &stats_event_sender, sample_issue_time(), ) .await; @@ -678,13 +713,13 @@ mod tests { .with(eq(statistics::event::Event::Udp6Connect)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); - let torrent_tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); handle_connect( sample_ipv6_remote_addr(), &sample_connect_request(), - &torrent_tracker, + &stats_event_sender, sample_issue_time(), ) .await; @@ -787,7 +822,9 @@ mod tests { #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { - let tracker = public_tracker(); + let (tracker, stats_event_sender) = public_tracker(); + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let client_ip = Ipv4Addr::new(126, 0, 0, 1); let client_port = 8080; @@ -804,9 +841,15 @@ mod tests { .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) - .await - .unwrap(); + handle_announce( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); let peers = tracker.get_torrent_peers(&info_hash.0.into()); @@ -820,15 +863,25 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { + let (tracker, stats_event_sender) = public_tracker(); + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); + let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - let response = handle_announce(remote_addr, &request, &public_tracker(), sample_cookie_valid_range()) - .await - .unwrap(); + let response = handle_announce( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); let empty_peer_vector: Vec> = vec![]; assert_eq!( @@ -851,7 +904,9 @@ mod tests { // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): // "Do note that most trackers will only honor the IP address field under limited circumstances." - let tracker = public_tracker(); + let (tracker, stats_event_sender) = public_tracker(); + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -871,9 +926,15 @@ mod tests { .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) - .await - .unwrap(); + handle_announce( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); let peers = tracker.get_torrent_peers(&info_hash.0.into()); @@ -897,19 +958,29 @@ mod tests { } async fn announce_a_new_peer_using_ipv4(tracker: Arc) -> Response { + let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let stats_event_sender = Arc::new(stats_event_sender); + let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) - .await - .unwrap() + handle_announce( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap() } #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { - let tracker = public_tracker(); + let (tracker, _stats_event_sender) = public_tracker(); + let tracker = Arc::new(tracker); add_a_torrent_peer_using_ipv6(&tracker); @@ -932,14 +1003,16 @@ mod tests { .with(eq(statistics::event::Event::Udp4Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); + let tracker = Arc::new(test_tracker_factory()); handle_announce( sample_ipv4_socket_address(), &AnnounceRequestBuilder::default().into(), &tracker, + &stats_event_sender, sample_cookie_valid_range(), ) .await @@ -961,7 +1034,9 @@ mod tests { #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { - let tracker = public_tracker(); + let (tracker, stats_event_sender) = public_tracker(); + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let client_ip = Ipv4Addr::new(127, 0, 0, 1); let client_port = 8080; @@ -978,9 +1053,15 @@ mod tests { .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) - .await - .unwrap(); + handle_announce( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); let peers = tracker.get_torrent_peers(&info_hash.0.into()); @@ -1019,7 +1100,9 @@ mod tests { #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { - let tracker = public_tracker(); + let (tracker, stats_event_sender) = public_tracker(); + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -1037,9 +1120,15 @@ mod tests { .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) - .await - .unwrap(); + handle_announce( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); let peers = tracker.get_torrent_peers(&info_hash.0.into()); @@ -1053,6 +1142,10 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { + let (tracker, stats_event_sender) = public_tracker(); + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -1062,9 +1155,15 @@ mod tests { .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - let response = handle_announce(remote_addr, &request, &public_tracker(), sample_cookie_valid_range()) - .await - .unwrap(); + let response = handle_announce( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); let empty_peer_vector: Vec> = vec![]; assert_eq!( @@ -1087,7 +1186,9 @@ mod tests { // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): // "Do note that most trackers will only honor the IP address field under limited circumstances." - let tracker = public_tracker(); + let (tracker, stats_event_sender) = public_tracker(); + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -1107,9 +1208,15 @@ mod tests { .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) - .await - .unwrap(); + handle_announce( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); let peers = tracker.get_torrent_peers(&info_hash.0.into()); @@ -1133,6 +1240,9 @@ mod tests { } async fn announce_a_new_peer_using_ipv6(tracker: Arc) -> Response { + let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let stats_event_sender = Arc::new(stats_event_sender); + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); let client_port = 8080; @@ -1141,14 +1251,21 @@ mod tests { .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) - .await - .unwrap() + handle_announce( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap() } #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { - let tracker = public_tracker(); + let (tracker, _stats_event_sender) = public_tracker(); + let tracker = Arc::new(tracker); add_a_torrent_peer_using_ipv4(&tracker); @@ -1171,9 +1288,10 @@ mod tests { .with(eq(statistics::event::Event::Udp6Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); + let tracker = Arc::new(test_tracker_factory()); let remote_addr = sample_ipv6_remote_addr(); @@ -1181,20 +1299,27 @@ mod tests { .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); - handle_announce(remote_addr, &announce_request, &tracker, sample_cookie_valid_range()) - .await - .unwrap(); + handle_announce( + remote_addr, + &announce_request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); } mod from_a_loopback_ip { + use std::future; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; + use mockall::predicate::eq; use crate::bootstrap::app::initialize_tracker_dependencies; - use crate::core; - use crate::core::statistics::keeper::Keeper; + use crate::core::{self, statistics}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; @@ -1206,21 +1331,18 @@ mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - let (database, whitelist_manager, _stats_event_sender, _stats_repository) = - initialize_tracker_dependencies(&config); + let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let (stats_event_sender, stats_repository) = Keeper::new_active_instance(); + let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + stats_event_sender_mock + .expect_send_event() + .with(eq(statistics::event::Event::Udp6Announce)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new( - core::Tracker::new( - &config.core, - &database, - &whitelist_manager, - &Arc::new(Some(stats_event_sender)), - &Arc::new(stats_repository), - ) - .unwrap(), - ); + let tracker = Arc::new(core::Tracker::new(&config.core, &database, &whitelist_manager).unwrap()); let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); @@ -1242,9 +1364,15 @@ mod tests { .with_port(client_port) .into(); - handle_announce(remote_addr, &request, &tracker, sample_cookie_valid_range()) - .await - .unwrap(); + handle_announce( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); let peers = tracker.get_torrent_peers(&info_hash.0.into()); @@ -1273,6 +1401,7 @@ mod tests { }; use super::{gen_remote_fingerprint, TorrentPeerBuilder}; + use crate::core::services::statistics; use crate::core::{self}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_scrape; @@ -1290,6 +1419,10 @@ mod tests { #[tokio::test] async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { + let (tracker, stats_event_sender) = public_tracker(); + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); + let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -1301,9 +1434,15 @@ mod tests { info_hashes, }; - let response = handle_scrape(remote_addr, &request, &public_tracker(), sample_cookie_valid_range()) - .await - .unwrap(); + let response = handle_scrape( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); let expected_torrent_stats = vec![zeroed_torrent_statistics()]; @@ -1339,6 +1478,9 @@ mod tests { } async fn add_a_sample_seeder_and_scrape(tracker: Arc) -> Response { + let (stats_event_sender, _stats_repository) = statistics::setup::factory(false); + let stats_event_sender = Arc::new(stats_event_sender); + let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -1346,9 +1488,15 @@ mod tests { let request = build_scrape_request(&remote_addr, &info_hash); - handle_scrape(remote_addr, &request, &tracker, sample_cookie_valid_range()) - .await - .unwrap() + handle_scrape( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap() } fn match_scrape_response(response: Response) -> Option { @@ -1359,6 +1507,8 @@ mod tests { } mod with_a_public_tracker { + use std::sync::Arc; + use aquatic_udp_protocol::{NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; use crate::servers::udp::handlers::tests::public_tracker; @@ -1366,7 +1516,8 @@ mod tests { #[tokio::test] async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { - let tracker = public_tracker(); + let (tracker, _stats_event_sender) = public_tracker(); + let tracker = Arc::new(tracker); let torrent_stats = match_scrape_response(add_a_sample_seeder_and_scrape(tracker.clone()).await); @@ -1381,6 +1532,8 @@ mod tests { } mod with_a_whitelisted_tracker { + use std::sync::Arc; + use aquatic_udp_protocol::{InfoHash, NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; use crate::servers::udp::handlers::handle_scrape; @@ -1391,7 +1544,9 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { - let tracker = whitelisted_tracker(); + let (tracker, stats_event_sender) = whitelisted_tracker(); + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -1406,9 +1561,15 @@ mod tests { let request = build_scrape_request(&remote_addr, &info_hash); let torrent_stats = match_scrape_response( - handle_scrape(remote_addr, &request, &tracker, sample_cookie_valid_range()) - .await - .unwrap(), + handle_scrape( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(), ) .unwrap(); @@ -1423,7 +1584,9 @@ mod tests { #[tokio::test] async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { - let tracker = whitelisted_tracker(); + let (tracker, stats_event_sender) = whitelisted_tracker(); + let tracker = Arc::new(tracker); + let stats_event_sender = Arc::new(stats_event_sender); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -1433,9 +1596,15 @@ mod tests { let request = build_scrape_request(&remote_addr, &info_hash); let torrent_stats = match_scrape_response( - handle_scrape(remote_addr, &request, &tracker, sample_cookie_valid_range()) - .await - .unwrap(), + handle_scrape( + remote_addr, + &request, + &tracker, + &stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(), ) .unwrap(); @@ -1477,15 +1646,17 @@ mod tests { .with(eq(statistics::event::Event::Udp4Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); let remote_addr = sample_ipv4_remote_addr(); - let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); + let tracker = Arc::new(test_tracker_factory()); handle_scrape( remote_addr, &sample_scrape_request(&remote_addr), &tracker, + &stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1514,15 +1685,17 @@ mod tests { .with(eq(statistics::event::Event::Udp6Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender = Box::new(stats_event_sender_mock); + let stats_event_sender: Arc>> = + Arc::new(Some(Box::new(stats_event_sender_mock))); let remote_addr = sample_ipv6_remote_addr(); - let tracker = Arc::new(test_tracker_factory(Some(stats_event_sender))); + let tracker = Arc::new(test_tracker_factory()); handle_scrape( remote_addr, &sample_scrape_request(&remote_addr), &tracker, + &stats_event_sender, sample_cookie_valid_range(), ) .await diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 753dc9915..d71ffcfd1 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -13,6 +13,7 @@ use tracing::instrument; use super::banning::BanService; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; +use crate::core::statistics::event::sender::Sender; use crate::core::{statistics, Tracker}; use crate::servers::logging::STARTED_ON; use crate::servers::registar::ServiceHealthCheckJob; @@ -40,9 +41,10 @@ impl Launcher { /// It panics if unable to send address of socket. /// It panics if the udp server is loaded when the tracker is private. /// - #[instrument(skip(tracker, ban_service, bind_to, tx_start, rx_halt))] + #[instrument(skip(tracker, opt_stats_event_sender, ban_service, bind_to, tx_start, rx_halt))] pub async fn run_with_graceful_shutdown( tracker: Arc, + opt_stats_event_sender: Arc>>, ban_service: Arc>, bind_to: SocketAddr, cookie_lifetime: Duration, @@ -81,7 +83,14 @@ impl Launcher { let local_addr = local_udp_url.clone(); tokio::task::spawn(async move { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_with_graceful_shutdown::task (listening...)"); - let () = Self::run_udp_server_main(receiver, tracker.clone(), ban_service.clone(), cookie_lifetime).await; + let () = Self::run_udp_server_main( + receiver, + tracker.clone(), + opt_stats_event_sender.clone(), + ban_service.clone(), + cookie_lifetime, + ) + .await; }) }; @@ -118,10 +127,11 @@ impl Launcher { ServiceHealthCheckJob::new(binding, info, job) } - #[instrument(skip(receiver, tracker, ban_service))] + #[instrument(skip(receiver, tracker, opt_stats_event_sender, ban_service))] async fn run_udp_server_main( mut receiver: Receiver, tracker: Arc, + opt_stats_event_sender: Arc>>, ban_service: Arc>, cookie_lifetime: Duration, ) { @@ -165,24 +175,35 @@ impl Launcher { } }; - match req.from.ip() { - IpAddr::V4(_) => { - tracker.send_stats_event(statistics::event::Event::Udp4Request).await; - } - IpAddr::V6(_) => { - tracker.send_stats_event(statistics::event::Event::Udp6Request).await; + if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { + match req.from.ip() { + IpAddr::V4(_) => { + stats_event_sender.send_event(statistics::event::Event::Udp4Request).await; + } + IpAddr::V6(_) => { + stats_event_sender.send_event(statistics::event::Event::Udp6Request).await; + } } } if ban_service.read().await.is_banned(&req.from.ip()) { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop continue: (banned ip)"); - tracker.send_stats_event(statistics::event::Event::UdpRequestBanned).await; + if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { + stats_event_sender + .send_event(statistics::event::Event::UdpRequestBanned) + .await; + } continue; } - let processor = Processor::new(receiver.socket.clone(), tracker.clone(), cookie_lifetime); + let processor = Processor::new( + receiver.socket.clone(), + tracker.clone(), + opt_stats_event_sender.clone(), + cookie_lifetime, + ); /* We spawn the new task even if the active requests buffer is full. This could seem counterintuitive because we are accepting @@ -206,7 +227,12 @@ impl Launcher { if old_request_aborted { // Evicted task from active requests buffer was aborted. - tracker.send_stats_event(statistics::event::Event::UdpRequestAborted).await; + + if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { + stats_event_sender + .send_event(statistics::event::Event::UdpRequestAborted) + .await; + }; } } else { tokio::task::yield_now().await; diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 6eb98a7b1..1b0a1da9a 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -64,6 +64,7 @@ mod tests { use super::spawner::Spawner; use super::Server; use crate::bootstrap::app::initialize_with_configuration; + use crate::core::services::statistics; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -72,8 +73,10 @@ mod tests { async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_public()); - let tracker = initialize_with_configuration(&cfg); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let tracker = initialize_with_configuration(&cfg); let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; @@ -83,7 +86,13 @@ mod tests { let stopped = Server::new(Spawner::new(bind_to)); let started = stopped - .start(tracker, ban_service, register.give_form(), config.cookie_lifetime) + .start( + tracker, + stats_event_sender, + ban_service, + register.give_form(), + config.cookie_lifetime, + ) .await .expect("it should start the server"); @@ -98,8 +107,10 @@ mod tests { async fn it_should_be_able_to_start_and_stop_with_wait() { let cfg = Arc::new(ephemeral_public()); - let tracker = initialize_with_configuration(&cfg); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let tracker = initialize_with_configuration(&cfg); let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; @@ -108,7 +119,13 @@ mod tests { let stopped = Server::new(Spawner::new(bind_to)); let started = stopped - .start(tracker, ban_service, register.give_form(), config.cookie_lifetime) + .start( + tracker, + stats_event_sender, + ban_service, + register.give_form(), + config.cookie_lifetime, + ) .await .expect("it should start the server"); diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index e0f7c4624..2ef7cc482 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -10,6 +10,7 @@ use tracing::{instrument, Level}; use super::banning::BanService; use super::bound_socket::BoundSocket; +use crate::core::statistics::event::sender::Sender; use crate::core::statistics::event::UdpResponseKind; use crate::core::{statistics, Tracker}; use crate::servers::udp::handlers::CookieTimeValues; @@ -18,14 +19,21 @@ use crate::servers::udp::{handlers, RawRequest}; pub struct Processor { socket: Arc, tracker: Arc, + opt_stats_event_sender: Arc>>, cookie_lifetime: f64, } impl Processor { - pub fn new(socket: Arc, tracker: Arc, cookie_lifetime: f64) -> Self { + pub fn new( + socket: Arc, + tracker: Arc, + opt_stats_event_sender: Arc>>, + cookie_lifetime: f64, + ) -> Self { Self { socket, tracker, + opt_stats_event_sender, cookie_lifetime, } } @@ -39,6 +47,7 @@ impl Processor { let response = handlers::handle_packet( request, &self.tracker, + &self.opt_stats_event_sender, self.socket.address(), CookieTimeValues::new(self.cookie_lifetime), ban_service, @@ -84,22 +93,24 @@ impl Processor { tracing::debug!(%bytes_count, %sent_bytes, "sent {response_type}"); } - match target.ip() { - IpAddr::V4(_) => { - self.tracker - .send_stats_event(statistics::event::Event::Udp4Response { - kind: response_kind, - req_processing_time, - }) - .await; - } - IpAddr::V6(_) => { - self.tracker - .send_stats_event(statistics::event::Event::Udp6Response { - kind: response_kind, - req_processing_time, - }) - .await; + if let Some(stats_event_sender) = self.opt_stats_event_sender.as_deref() { + match target.ip() { + IpAddr::V4(_) => { + stats_event_sender + .send_event(statistics::event::Event::Udp4Response { + kind: response_kind, + req_processing_time, + }) + .await; + } + IpAddr::V6(_) => { + stats_event_sender + .send_event(statistics::event::Event::Udp6Response { + kind: response_kind, + req_processing_time, + }) + .await; + } } } } diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index ce2fe8eae..5d7a97877 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -11,6 +11,7 @@ use tokio::task::JoinHandle; use super::banning::BanService; use super::launcher::Launcher; use crate::bootstrap::jobs::Started; +use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; use crate::servers::signals::Halted; @@ -29,6 +30,7 @@ impl Spawner { pub fn spawn_launcher( &self, tracker: Arc, + opt_stats_event_sender: Arc>>, ban_service: Arc>, cookie_lifetime: Duration, tx_start: oneshot::Sender, @@ -37,7 +39,16 @@ impl Spawner { let spawner = Self::new(self.bind_to); tokio::spawn(async move { - Launcher::run_with_graceful_shutdown(tracker, ban_service, spawner.bind_to, cookie_lifetime, tx_start, rx_halt).await; + Launcher::run_with_graceful_shutdown( + tracker, + opt_stats_event_sender, + ban_service, + spawner.bind_to, + cookie_lifetime, + tx_start, + rx_halt, + ) + .await; spawner }) } diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index 02742049d..5cdca5a7d 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -13,6 +13,7 @@ use super::banning::BanService; use super::spawner::Spawner; use super::{Server, UdpError}; use crate::bootstrap::jobs::Started; +use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; use crate::servers::registar::{ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::Halted; @@ -64,10 +65,11 @@ impl Server { /// /// It panics if unable to receive the bound socket address from service. /// - #[instrument(skip(self, tracker, ban_service, form), err, ret(Display, level = Level::INFO))] + #[instrument(skip(self, tracker, opt_stats_event_sender, ban_service, form), err, ret(Display, level = Level::INFO))] pub async fn start( self, tracker: Arc, + opt_stats_event_sender: Arc>>, ban_service: Arc>, form: ServiceRegistrationForm, cookie_lifetime: Duration, @@ -78,10 +80,14 @@ impl Server { assert!(!tx_halt.is_closed(), "Halt channel for UDP tracker should be open"); // May need to wrap in a task to about a tokio bug. - let task = self - .state - .spawner - .spawn_launcher(tracker, ban_service, cookie_lifetime, tx_start, rx_halt); + let task = self.state.spawner.spawn_launcher( + tracker, + opt_stats_event_sender, + ban_service, + cookie_lifetime, + tx_start, + rx_halt, + ); let local_addr = rx_start.await.expect("it should be able to start the service").address; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 37d031e1c..6658c27da 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -8,6 +8,9 @@ use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::{Configuration, HttpApi}; use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; +use torrust_tracker_lib::core::services::statistics; +use torrust_tracker_lib::core::statistics::event::sender::Sender; +use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::whitelist::WhiteListManager; use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; @@ -22,6 +25,8 @@ where { pub config: Arc, pub tracker: Arc, + pub stats_event_sender: Arc>>, + pub stats_repository: Arc, pub whitelist_manager: Arc, pub ban_service: Arc>, pub registar: Registar, @@ -40,13 +45,16 @@ where impl Environment { pub fn new(configuration: &Arc) -> Self { + let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + let stats_repository = Arc::new(stats_repository); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let tracker = initialize_with_configuration(configuration); - // todo: get from `initialize_with_configuration` + // todo: instantiate outside of `initialize_with_configuration` let whitelist_manager = tracker.whitelist_manager.clone(); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let config = Arc::new(configuration.http_api.clone().expect("missing API configuration")); let bind_to = config.bind_address; @@ -58,6 +66,8 @@ impl Environment { Self { config, tracker, + stats_event_sender, + stats_repository, whitelist_manager, ban_service, registar: Registar::default(), @@ -71,12 +81,21 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + stats_event_sender: self.stats_event_sender.clone(), + stats_repository: self.stats_repository.clone(), whitelist_manager: self.whitelist_manager.clone(), ban_service: self.ban_service.clone(), registar: self.registar.clone(), server: self .server - .start(self.tracker, self.ban_service, self.registar.give_form(), access_tokens) + .start( + self.tracker, + self.stats_event_sender, + self.stats_repository, + self.ban_service, + self.registar.give_form(), + access_tokens, + ) .await .unwrap(), } @@ -92,6 +111,8 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + stats_event_sender: self.stats_event_sender, + stats_repository: self.stats_repository, whitelist_manager: self.whitelist_manager, ban_service: self.ban_service, registar: Registar::default(), diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 6d4001e6c..845d9d440 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -5,6 +5,9 @@ use futures::executor::block_on; use torrust_tracker_configuration::{Configuration, HttpTracker}; use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; +use torrust_tracker_lib::core::services::statistics; +use torrust_tracker_lib::core::statistics::event::sender::Sender; +use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::whitelist::WhiteListManager; use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; @@ -14,6 +17,8 @@ use torrust_tracker_primitives::peer; pub struct Environment { pub config: Arc, pub tracker: Arc, + pub stats_event_sender: Arc>>, + pub stats_repository: Arc, pub whitelist_manager: Arc, pub registar: Registar, pub server: HttpServer, @@ -29,8 +34,13 @@ impl Environment { impl Environment { #[allow(dead_code)] pub fn new(configuration: &Arc) -> Self { + let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + let stats_repository = Arc::new(stats_repository); + let tracker = initialize_with_configuration(configuration); + // todo: instantiate outside of `initialize_with_configuration` let whitelist_manager = tracker.whitelist_manager.clone(); let http_tracker = configuration @@ -49,6 +59,8 @@ impl Environment { Self { config, tracker, + stats_event_sender, + stats_repository, whitelist_manager, registar: Registar::default(), server, @@ -60,9 +72,15 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + stats_event_sender: self.stats_event_sender.clone(), + stats_repository: self.stats_repository.clone(), whitelist_manager: self.whitelist_manager.clone(), registar: self.registar.clone(), - server: self.server.start(self.tracker, self.registar.give_form()).await.unwrap(), + server: self + .server + .start(self.tracker, self.stats_event_sender, self.registar.give_form()) + .await + .unwrap(), } } } @@ -76,6 +94,8 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + stats_event_sender: self.stats_event_sender, + stats_repository: self.stats_repository, whitelist_manager: self.whitelist_manager, registar: Registar::default(), diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 37d0288f4..2cec1790f 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -680,7 +680,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.tracker.get_stats().await; + let stats = env.stats_repository.get_stats().await; assert_eq!(stats.tcp4_connections_handled, 1); @@ -706,7 +706,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.tracker.get_stats().await; + let stats = env.stats_repository.get_stats().await; assert_eq!(stats.tcp6_connections_handled, 1); @@ -731,7 +731,7 @@ mod for_all_config_modes { ) .await; - let stats = env.tracker.get_stats().await; + let stats = env.stats_repository.get_stats().await; assert_eq!(stats.tcp6_connections_handled, 0); @@ -750,7 +750,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.tracker.get_stats().await; + let stats = env.stats_repository.get_stats().await; assert_eq!(stats.tcp4_announces_handled, 1); @@ -776,7 +776,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.tracker.get_stats().await; + let stats = env.stats_repository.get_stats().await; assert_eq!(stats.tcp6_announces_handled, 1); @@ -801,7 +801,7 @@ mod for_all_config_modes { ) .await; - let stats = env.tracker.get_stats().await; + let stats = env.stats_repository.get_stats().await; assert_eq!(stats.tcp6_announces_handled, 0); @@ -1167,7 +1167,7 @@ mod for_all_config_modes { ) .await; - let stats = env.tracker.get_stats().await; + let stats = env.stats_repository.get_stats().await; assert_eq!(stats.tcp4_scrapes_handled, 1); @@ -1199,7 +1199,7 @@ mod for_all_config_modes { ) .await; - let stats = env.tracker.get_stats().await; + let stats = env.stats_repository.get_stats().await; assert_eq!(stats.tcp6_scrapes_handled, 1); diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index f0ed98b21..0767d5f07 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -229,7 +229,6 @@ mod receiving_an_announce_request { logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; - let tracker = env.tracker.clone(); let ban_service = env.ban_service.clone(); let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { @@ -271,7 +270,7 @@ mod receiving_an_announce_request { info_hash, ); - let udp_requests_banned_before = tracker.get_stats().await.udp_requests_banned; + let udp_requests_banned_before = env.stats_repository.get_stats().await.udp_requests_banned; // This should return a timeout error match client.send(announce_request.into()).await { @@ -281,7 +280,7 @@ mod receiving_an_announce_request { assert!(client.receive().await.is_err()); - let udp_requests_banned_after = tracker.get_stats().await.udp_requests_banned; + let udp_requests_banned_after = env.stats_repository.get_stats().await.udp_requests_banned; let udp_banned_ips_total_after = ban_service.read().await.get_banned_ips_total(); // UDP counter for banned requests should be increased by 1 diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index f744809c5..06a22229e 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -5,6 +5,9 @@ use bittorrent_primitives::info_hash::InfoHash; use tokio::sync::RwLock; use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; +use torrust_tracker_lib::core::services::statistics; +use torrust_tracker_lib::core::statistics::event::sender::Sender; +use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::banning::BanService; @@ -20,6 +23,8 @@ where { pub config: Arc, pub tracker: Arc, + pub stats_event_sender: Arc>>, + pub stats_repository: Arc, pub ban_service: Arc>, pub registar: Registar, pub server: Server, @@ -39,9 +44,13 @@ where impl Environment { #[allow(dead_code)] pub fn new(configuration: &Arc) -> Self { - let tracker = initialize_with_configuration(configuration); + let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + let stats_repository = Arc::new(stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let tracker = initialize_with_configuration(configuration); + let udp_tracker = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); let config = Arc::new(udp_tracker[0].clone()); @@ -53,6 +62,8 @@ impl Environment { Self { config, tracker, + stats_event_sender, + stats_repository, ban_service, registar: Registar::default(), server, @@ -65,11 +76,19 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + stats_event_sender: self.stats_event_sender.clone(), + stats_repository: self.stats_repository.clone(), ban_service: self.ban_service.clone(), registar: self.registar.clone(), server: self .server - .start(self.tracker, self.ban_service, self.registar.give_form(), cookie_lifetime) + .start( + self.tracker, + self.stats_event_sender, + self.ban_service, + self.registar.give_form(), + cookie_lifetime, + ) .await .unwrap(), } @@ -92,6 +111,8 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + stats_event_sender: self.stats_event_sender, + stats_repository: self.stats_repository, ban_service: self.ban_service, registar: Registar::default(), server: stopped.expect("it stop the udp tracker service"), From 8bea5213c3a55bfd26101073c52c86124440b958 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 Jan 2025 16:19:05 +0000 Subject: [PATCH 0594/1297] refactor: [#1187] extract IoC Container --- src/app.rs | 51 +++++++++++++++++----------------------- src/bootstrap/app.rs | 24 +++++++++---------- src/console/profiling.rs | 4 ++-- src/container.rs | 15 ++++++++++++ src/lib.rs | 1 + src/main.rs | 4 ++-- 6 files changed, 53 insertions(+), 46 deletions(-) create mode 100644 src/container.rs diff --git a/src/app.rs b/src/app.rs index 14dc0b07f..64119aa34 100644 --- a/src/app.rs +++ b/src/app.rs @@ -21,19 +21,14 @@ //! - UDP trackers: the user can enable multiple UDP tracker on several ports. //! - HTTP trackers: the user can enable multiple HTTP tracker on several ports. //! - Tracker REST API: the tracker API can be enabled/disabled. -use std::sync::Arc; - -use tokio::sync::RwLock; use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; use tracing::instrument; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; -use crate::core::statistics::event::sender::Sender; -use crate::core::statistics::repository::Repository; +use crate::container::AppContainer; +use crate::servers; use crate::servers::registar::Registar; -use crate::servers::udp::server::banning::BanService; -use crate::{core, servers}; /// # Panics /// @@ -41,14 +36,8 @@ use crate::{core, servers}; /// /// - Can't retrieve tracker keys from database. /// - Can't load whitelist from database. -#[instrument(skip(config, tracker, ban_service, stats_event_sender, stats_repository))] -pub async fn start( - config: &Configuration, - tracker: Arc, - ban_service: Arc>, - stats_event_sender: Arc>>, - stats_repository: Arc, -) -> Vec> { +#[instrument(skip(config, app_container))] +pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec> { if config.http_api.is_none() && (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) && (config.http_trackers.is_none() || config.http_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) @@ -61,16 +50,18 @@ pub async fn start( let registar = Registar::default(); // Load peer keys - if tracker.is_private() { - tracker + if app_container.tracker.is_private() { + app_container + .tracker .load_keys_from_database() .await .expect("Could not retrieve keys from database."); } // Load whitelisted torrents - if tracker.is_listed() { - tracker + if app_container.tracker.is_listed() { + app_container + .tracker .whitelist_manager .load_whitelist_from_database() .await @@ -80,7 +71,7 @@ pub async fn start( // Start the UDP blocks if let Some(udp_trackers) = &config.udp_trackers { for udp_tracker_config in udp_trackers { - if tracker.is_private() { + if app_container.tracker.is_private() { tracing::warn!( "Could not start UDP tracker on: {} while in private mode. UDP is not safe for private trackers!", udp_tracker_config.bind_address @@ -89,9 +80,9 @@ pub async fn start( jobs.push( udp_tracker::start_job( udp_tracker_config, - tracker.clone(), - stats_event_sender.clone(), - ban_service.clone(), + app_container.tracker.clone(), + app_container.stats_event_sender.clone(), + app_container.ban_service.clone(), registar.give_form(), ) .await, @@ -107,8 +98,8 @@ pub async fn start( for http_tracker_config in http_trackers { if let Some(job) = http_tracker::start_job( http_tracker_config, - tracker.clone(), - stats_event_sender.clone(), + app_container.tracker.clone(), + app_container.stats_event_sender.clone(), registar.give_form(), servers::http::Version::V1, ) @@ -125,10 +116,10 @@ pub async fn start( if let Some(http_api_config) = &config.http_api { if let Some(job) = tracker_apis::start_job( http_api_config, - tracker.clone(), - ban_service.clone(), - stats_event_sender.clone(), - stats_repository.clone(), + app_container.tracker.clone(), + app_container.ban_service.clone(), + app_container.stats_event_sender.clone(), + app_container.stats_repository.clone(), registar.give_form(), servers::apis::Version::V1, ) @@ -142,7 +133,7 @@ pub async fn start( // Start runners to remove torrents without peers, every interval if config.core.inactive_peer_cleanup_interval > 0 { - jobs.push(torrent_cleanup::start_job(&config.core, &tracker)); + jobs.push(torrent_cleanup::start_job(&config.core, &app_container.tracker)); } // Start Health Check API diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index d63b414e1..68ec93e38 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -21,10 +21,9 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; +use crate::container::AppContainer; use crate::core::databases::Database; use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; -use crate::core::statistics::event::sender::Sender; -use crate::core::statistics::repository::Repository; use crate::core::whitelist::WhiteListManager; use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; @@ -38,15 +37,8 @@ use crate::shared::crypto::keys::{self, Keeper as _}; /// /// Setup can file if the configuration is invalid. #[must_use] -#[allow(clippy::type_complexity)] #[instrument(skip())] -pub fn setup() -> ( - Configuration, - Arc, - Arc>, - Arc>>, - Arc, -) { +pub fn setup() -> (Configuration, AppContainer) { #[cfg(not(test))] check_seed(); @@ -62,13 +54,21 @@ pub fn setup() -> ( let stats_event_sender = Arc::new(stats_event_sender); let stats_repository = Arc::new(stats_repository); - let udp_ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let tracker = initialize_with_configuration(&configuration); tracing::info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); - (configuration, tracker, udp_ban_service, stats_event_sender, stats_repository) + ( + configuration, + AppContainer { + tracker, + ban_service, + stats_event_sender, + stats_repository, + }, + ) } /// checks if the seed is the instance seed in production. diff --git a/src/console/profiling.rs b/src/console/profiling.rs index 2f6471906..318fce1e8 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -179,9 +179,9 @@ pub async fn run() { return; }; - let (config, tracker, ban_service, stats_event_sender, stats_repository) = bootstrap::app::setup(); + let (config, app_container) = bootstrap::app::setup(); - let jobs = app::start(&config, tracker, ban_service, stats_event_sender, stats_repository).await; + let jobs = app::start(&config, &app_container).await; // Run the tracker for a fixed duration let run_duration = sleep(Duration::from_secs(duration_secs)); diff --git a/src/container.rs b/src/container.rs new file mode 100644 index 000000000..961b32a12 --- /dev/null +++ b/src/container.rs @@ -0,0 +1,15 @@ +use std::sync::Arc; + +use tokio::sync::RwLock; + +use crate::core::statistics::event::sender::Sender; +use crate::core::statistics::repository::Repository; +use crate::core::Tracker; +use crate::servers::udp::server::banning::BanService; + +pub struct AppContainer { + pub tracker: Arc, + pub ban_service: Arc>, + pub stats_event_sender: Arc>>, + pub stats_repository: Arc, +} diff --git a/src/lib.rs b/src/lib.rs index d7e4bc5b2..212430605 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -493,6 +493,7 @@ use torrust_tracker_clock::clock; pub mod app; pub mod bootstrap; pub mod console; +pub mod container; pub mod core; pub mod servers; pub mod shared; diff --git a/src/main.rs b/src/main.rs index e536124a2..f05de0327 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,9 +2,9 @@ use torrust_tracker_lib::{app, bootstrap}; #[tokio::main] async fn main() { - let (config, tracker, udp_ban_service, stats_event_sender, stats_repository) = bootstrap::app::setup(); + let (config, app_container) = bootstrap::app::setup(); - let jobs = app::start(&config, tracker, udp_ban_service, stats_event_sender, stats_repository).await; + let jobs = app::start(&config, &app_container).await; // handle the signals tokio::select! { From 747b58d88c7496c7eafbd135d07b524079aa65ec Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 Jan 2025 16:32:06 +0000 Subject: [PATCH 0595/1297] refactor: [#1187] extract one function and rename another one --- src/bootstrap/app.rs | 12 +++++++++--- src/bootstrap/jobs/http_tracker.rs | 4 ++-- src/bootstrap/jobs/tracker_apis.rs | 4 ++-- src/servers/apis/server.rs | 4 ++-- src/servers/http/server.rs | 4 ++-- src/servers/udp/server/mod.rs | 6 +++--- tests/servers/api/environment.rs | 6 +++--- tests/servers/http/environment.rs | 6 +++--- tests/servers/udp/environment.rs | 4 ++-- 9 files changed, 28 insertions(+), 22 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 68ec93e38..294de64e3 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -56,7 +56,7 @@ pub fn setup() -> (Configuration, AppContainer) { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let tracker = initialize_with_configuration(&configuration); + let tracker = initialize_globals_and_tracker(&configuration); tracing::info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); @@ -88,10 +88,16 @@ pub fn check_seed() { /// The configuration may be obtained from the environment (via config file or env vars). #[must_use] #[instrument(skip())] -pub fn initialize_with_configuration(configuration: &Configuration) -> Arc { +pub fn initialize_globals_and_tracker(configuration: &Configuration) -> Arc { + initialize_global_services(configuration); + Arc::new(initialize_tracker(configuration)) +} + +/// It initializes the global services. +#[instrument(skip())] +pub fn initialize_global_services(configuration: &Configuration) { initialize_static(); initialize_logging(configuration); - Arc::new(initialize_tracker(configuration)) } /// It initializes the application static values. diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 9135a8828..abb531049 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -86,7 +86,7 @@ mod tests { use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_with_configuration; + use crate::bootstrap::app::initialize_globals_and_tracker; use crate::bootstrap::jobs::http_tracker::start_job; use crate::core::services::statistics; use crate::servers::http::Version; @@ -99,7 +99,7 @@ mod tests { let config = &http_tracker[0]; let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = initialize_with_configuration(&cfg); + let tracker = initialize_globals_and_tracker(&cfg); let version = Version::V1; start_job(config, tracker, stats_event_sender, Registar::default().give_form(), version) diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index d84bb08a9..1932888de 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -140,7 +140,7 @@ mod tests { use tokio::sync::RwLock; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_with_configuration; + use crate::bootstrap::app::initialize_globals_and_tracker; use crate::bootstrap::jobs::tracker_apis::start_job; use crate::core::services::statistics; use crate::servers::apis::Version; @@ -158,7 +158,7 @@ mod tests { let stats_event_sender = Arc::new(stats_event_sender); let stats_repository = Arc::new(stats_repository); - let tracker = initialize_with_configuration(&cfg); + let tracker = initialize_globals_and_tracker(&cfg); let version = Version::V1; diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index bf1511edb..e0123a173 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -333,7 +333,7 @@ mod tests { use tokio::sync::RwLock; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_with_configuration; + use crate::bootstrap::app::initialize_globals_and_tracker; use crate::bootstrap::jobs::make_rust_tls; use crate::core::services::statistics; use crate::servers::apis::server::{ApiServer, Launcher}; @@ -350,7 +350,7 @@ mod tests { let (stats_event_sender, stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let stats_repository = Arc::new(stats_repository); - let tracker = initialize_with_configuration(&cfg); + let tracker = initialize_globals_and_tracker(&cfg); let bind_to = config.bind_address; diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 537fc37fb..40035bc52 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -242,7 +242,7 @@ mod tests { use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_with_configuration; + use crate::bootstrap::app::initialize_globals_and_tracker; use crate::bootstrap::jobs::make_rust_tls; use crate::core::services::statistics; use crate::servers::http::server::{HttpServer, Launcher}; @@ -254,7 +254,7 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = initialize_with_configuration(&cfg); + let tracker = initialize_globals_and_tracker(&cfg); let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); let config = &http_trackers[0]; diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 1b0a1da9a..373541f75 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -63,7 +63,7 @@ mod tests { use super::spawner::Spawner; use super::Server; - use crate::bootstrap::app::initialize_with_configuration; + use crate::bootstrap::app::initialize_globals_and_tracker; use crate::core::services::statistics; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -76,7 +76,7 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let tracker = initialize_with_configuration(&cfg); + let tracker = initialize_globals_and_tracker(&cfg); let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; @@ -110,7 +110,7 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let tracker = initialize_with_configuration(&cfg); + let tracker = initialize_globals_and_tracker(&cfg); let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 6658c27da..32db0ab5d 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -6,7 +6,7 @@ use futures::executor::block_on; use tokio::sync::RwLock; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::{Configuration, HttpApi}; -use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; +use torrust_tracker_lib::bootstrap::app::initialize_globals_and_tracker; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::core::services::statistics; use torrust_tracker_lib::core::statistics::event::sender::Sender; @@ -50,9 +50,9 @@ impl Environment { let stats_repository = Arc::new(stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let tracker = initialize_with_configuration(configuration); + let tracker = initialize_globals_and_tracker(configuration); - // todo: instantiate outside of `initialize_with_configuration` + // todo: instantiate outside of `initialize_globals_and_tracker` let whitelist_manager = tracker.whitelist_manager.clone(); let config = Arc::new(configuration.http_api.clone().expect("missing API configuration")); diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 845d9d440..b6f98f32c 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; use torrust_tracker_configuration::{Configuration, HttpTracker}; -use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; +use torrust_tracker_lib::bootstrap::app::initialize_globals_and_tracker; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::core::services::statistics; use torrust_tracker_lib::core::statistics::event::sender::Sender; @@ -38,9 +38,9 @@ impl Environment { let stats_event_sender = Arc::new(stats_event_sender); let stats_repository = Arc::new(stats_repository); - let tracker = initialize_with_configuration(configuration); + let tracker = initialize_globals_and_tracker(configuration); - // todo: instantiate outside of `initialize_with_configuration` + // todo: instantiate outside of `initialize_globals_and_tracker` let whitelist_manager = tracker.whitelist_manager.clone(); let http_tracker = configuration diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 06a22229e..69952ecda 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use tokio::sync::RwLock; use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; -use torrust_tracker_lib::bootstrap::app::initialize_with_configuration; +use torrust_tracker_lib::bootstrap::app::initialize_globals_and_tracker; use torrust_tracker_lib::core::services::statistics; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; @@ -49,7 +49,7 @@ impl Environment { let stats_repository = Arc::new(stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let tracker = initialize_with_configuration(configuration); + let tracker = initialize_globals_and_tracker(configuration); let udp_tracker = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); From 4aea9db2215b64eedf44a1264d56f53ecaa63812 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 Jan 2025 16:42:53 +0000 Subject: [PATCH 0596/1297] refactor: [#1187] extract fn initialize_app_container --- src/bootstrap/app.rs | 41 +++++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 294de64e3..65b0549ec 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -48,27 +48,13 @@ pub fn setup() -> (Configuration, AppContainer) { panic!("Configuration error: {e}"); } - // Initialize services - - let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - let stats_repository = Arc::new(stats_repository); - - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - - let tracker = initialize_globals_and_tracker(&configuration); + initialize_global_services(&configuration); tracing::info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); - ( - configuration, - AppContainer { - tracker, - ban_service, - stats_event_sender, - stats_repository, - }, - ) + let app_container = initialize_app_container(&configuration); + + (configuration, app_container) } /// checks if the seed is the instance seed in production. @@ -100,6 +86,25 @@ pub fn initialize_global_services(configuration: &Configuration) { initialize_logging(configuration); } +/// It initializes the stIoC Container. +#[instrument(skip())] +pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { + let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + let stats_repository = Arc::new(stats_repository); + + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + + let tracker = Arc::new(initialize_tracker(configuration)); + + AppContainer { + tracker, + ban_service, + stats_event_sender, + stats_repository, + } +} + /// It initializes the application static values. /// /// These values are accessible throughout the entire application: From 36db088fb6d79301984fb59a81698237f354a062 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 Jan 2025 17:00:30 +0000 Subject: [PATCH 0597/1297] refactor: [#1187] inline fn initialize_globals_and_tracker --- src/bootstrap/app.rs | 12 +----------- src/bootstrap/jobs/http_tracker.rs | 8 ++++++-- src/bootstrap/jobs/tracker_apis.rs | 5 +++-- src/servers/apis/server.rs | 6 ++++-- src/servers/http/server.rs | 6 ++++-- src/servers/udp/server/mod.rs | 10 +++++++--- tests/servers/api/environment.rs | 7 ++++--- tests/servers/http/environment.rs | 7 ++++--- tests/servers/udp/environment.rs | 5 +++-- 9 files changed, 36 insertions(+), 30 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 65b0549ec..b44cf745a 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -69,16 +69,6 @@ pub fn check_seed() { assert_eq!(seed, instance, "maybe using zeroed seed in production!?"); } -/// It initializes the application with the given configuration. -/// -/// The configuration may be obtained from the environment (via config file or env vars). -#[must_use] -#[instrument(skip())] -pub fn initialize_globals_and_tracker(configuration: &Configuration) -> Arc { - initialize_global_services(configuration); - Arc::new(initialize_tracker(configuration)) -} - /// It initializes the global services. #[instrument(skip())] pub fn initialize_global_services(configuration: &Configuration) { @@ -86,7 +76,7 @@ pub fn initialize_global_services(configuration: &Configuration) { initialize_logging(configuration); } -/// It initializes the stIoC Container. +/// It initializes the IoC Container. #[instrument(skip())] pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index abb531049..aff9a2e11 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -86,7 +86,7 @@ mod tests { use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_globals_and_tracker; + use crate::bootstrap::app::{initialize_global_services, initialize_tracker}; use crate::bootstrap::jobs::http_tracker::start_job; use crate::core::services::statistics; use crate::servers::http::Version; @@ -97,9 +97,13 @@ mod tests { let cfg = Arc::new(ephemeral_public()); let http_tracker = cfg.http_trackers.clone().expect("missing HTTP tracker configuration"); let config = &http_tracker[0]; + let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = initialize_globals_and_tracker(&cfg); + + initialize_global_services(&cfg); + let tracker = Arc::new(initialize_tracker(&cfg)); + let version = Version::V1; start_job(config, tracker, stats_event_sender, Registar::default().give_form(), version) diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 1932888de..e4d73849a 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -140,7 +140,7 @@ mod tests { use tokio::sync::RwLock; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_globals_and_tracker; + use crate::bootstrap::app::{initialize_global_services, initialize_tracker}; use crate::bootstrap::jobs::tracker_apis::start_job; use crate::core::services::statistics; use crate::servers::apis::Version; @@ -158,7 +158,8 @@ mod tests { let stats_event_sender = Arc::new(stats_event_sender); let stats_repository = Arc::new(stats_repository); - let tracker = initialize_globals_and_tracker(&cfg); + initialize_global_services(&cfg); + let tracker = Arc::new(initialize_tracker(&cfg)); let version = Version::V1; diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index e0123a173..edec7fc1a 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -333,7 +333,7 @@ mod tests { use tokio::sync::RwLock; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_globals_and_tracker; + use crate::bootstrap::app::{initialize_global_services, initialize_tracker}; use crate::bootstrap::jobs::make_rust_tls; use crate::core::services::statistics; use crate::servers::apis::server::{ApiServer, Launcher}; @@ -350,7 +350,9 @@ mod tests { let (stats_event_sender, stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let stats_repository = Arc::new(stats_repository); - let tracker = initialize_globals_and_tracker(&cfg); + + initialize_global_services(&cfg); + let tracker = Arc::new(initialize_tracker(&cfg)); let bind_to = config.bind_address; diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 40035bc52..ec466ae4a 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -242,7 +242,7 @@ mod tests { use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_globals_and_tracker; + use crate::bootstrap::app::{initialize_global_services, initialize_tracker}; use crate::bootstrap::jobs::make_rust_tls; use crate::core::services::statistics; use crate::servers::http::server::{HttpServer, Launcher}; @@ -254,7 +254,9 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = initialize_globals_and_tracker(&cfg); + + initialize_global_services(&cfg); + let tracker = Arc::new(initialize_tracker(&cfg)); let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); let config = &http_trackers[0]; diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 373541f75..950c0fa74 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -63,7 +63,7 @@ mod tests { use super::spawner::Spawner; use super::Server; - use crate::bootstrap::app::initialize_globals_and_tracker; + use crate::bootstrap::app::{initialize_global_services, initialize_tracker}; use crate::core::services::statistics; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -76,7 +76,9 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let tracker = initialize_globals_and_tracker(&cfg); + + initialize_global_services(&cfg); + let tracker = Arc::new(initialize_tracker(&cfg)); let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; @@ -110,7 +112,9 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let tracker = initialize_globals_and_tracker(&cfg); + + initialize_global_services(&cfg); + let tracker = Arc::new(initialize_tracker(&cfg)); let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 32db0ab5d..e7fc319d8 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -6,7 +6,7 @@ use futures::executor::block_on; use tokio::sync::RwLock; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::{Configuration, HttpApi}; -use torrust_tracker_lib::bootstrap::app::initialize_globals_and_tracker; +use torrust_tracker_lib::bootstrap::app::{initialize_global_services, initialize_tracker}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::core::services::statistics; use torrust_tracker_lib::core::statistics::event::sender::Sender; @@ -50,9 +50,10 @@ impl Environment { let stats_repository = Arc::new(stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let tracker = initialize_globals_and_tracker(configuration); + initialize_global_services(configuration); + let tracker = Arc::new(initialize_tracker(configuration)); - // todo: instantiate outside of `initialize_globals_and_tracker` + // todo: instantiate outside of `initialize_tracker_dependencies` let whitelist_manager = tracker.whitelist_manager.clone(); let config = Arc::new(configuration.http_api.clone().expect("missing API configuration")); diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index b6f98f32c..2137ca0d4 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; use torrust_tracker_configuration::{Configuration, HttpTracker}; -use torrust_tracker_lib::bootstrap::app::initialize_globals_and_tracker; +use torrust_tracker_lib::bootstrap::app::{initialize_global_services, initialize_tracker}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::core::services::statistics; use torrust_tracker_lib::core::statistics::event::sender::Sender; @@ -38,9 +38,10 @@ impl Environment { let stats_event_sender = Arc::new(stats_event_sender); let stats_repository = Arc::new(stats_repository); - let tracker = initialize_globals_and_tracker(configuration); + initialize_global_services(configuration); + let tracker = Arc::new(initialize_tracker(configuration)); - // todo: instantiate outside of `initialize_globals_and_tracker` + // todo: instantiate outside of `initialize_tracker_dependencies` let whitelist_manager = tracker.whitelist_manager.clone(); let http_tracker = configuration diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 69952ecda..0a0125714 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use tokio::sync::RwLock; use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; -use torrust_tracker_lib::bootstrap::app::initialize_globals_and_tracker; +use torrust_tracker_lib::bootstrap::app::{initialize_global_services, initialize_tracker}; use torrust_tracker_lib::core::services::statistics; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; @@ -49,7 +49,8 @@ impl Environment { let stats_repository = Arc::new(stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let tracker = initialize_globals_and_tracker(configuration); + initialize_global_services(configuration); + let tracker = Arc::new(initialize_tracker(configuration)); let udp_tracker = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); From a4d8da0eff07f1ccd471b31b21193682de35b955 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 Jan 2025 17:23:04 +0000 Subject: [PATCH 0598/1297] refactor: [#1187] inline fn initialize_tracker --- src/bootstrap/app.rs | 19 +++---------------- src/bootstrap/jobs/http_tracker.rs | 9 ++++++--- src/bootstrap/jobs/tracker_apis.rs | 9 ++++++--- src/servers/apis/server.rs | 9 ++++++--- src/servers/http/server.rs | 9 ++++++--- src/servers/udp/server/mod.rs | 14 ++++++++++---- tests/servers/api/environment.rs | 10 +++++----- tests/servers/http/environment.rs | 10 +++++----- tests/servers/udp/environment.rs | 9 ++++++--- 9 files changed, 53 insertions(+), 45 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index b44cf745a..b0df03404 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -25,7 +25,6 @@ use crate::container::AppContainer; use crate::core::databases::Database; use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; use crate::core::whitelist::WhiteListManager; -use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; @@ -82,10 +81,10 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let stats_repository = Arc::new(stats_repository); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - - let tracker = Arc::new(initialize_tracker(configuration)); + let database = initialize_database(configuration); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(configuration, &database, &whitelist_manager)); AppContainer { tracker, @@ -116,18 +115,6 @@ pub fn initialize_static() { lazy_static::initialize(&ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH); } -/// It builds the domain tracker -/// -/// The tracker is the domain layer service. It's the entrypoint to make requests to the domain layer. -/// It's used by other higher-level components like the UDP and HTTP trackers or the tracker API. -#[must_use] -#[instrument(skip(config))] -pub fn initialize_tracker(config: &Configuration) -> Tracker { - let (database, whitelist_manager) = initialize_tracker_dependencies(config); - - tracker_factory(config, &database, &whitelist_manager) -} - #[allow(clippy::type_complexity)] #[must_use] pub fn initialize_tracker_dependencies(config: &Configuration) -> (Arc>, Arc) { diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index aff9a2e11..0714cbd72 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -86,9 +86,9 @@ mod tests { use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::{initialize_global_services, initialize_tracker}; + use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::http_tracker::start_job; - use crate::core::services::statistics; + use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; use crate::servers::http::Version; use crate::servers::registar::Registar; @@ -102,7 +102,10 @@ mod tests { let stats_event_sender = Arc::new(stats_event_sender); initialize_global_services(&cfg); - let tracker = Arc::new(initialize_tracker(&cfg)); + + let database = initialize_database(&cfg); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&cfg, &database, &whitelist_manager)); let version = Version::V1; diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index e4d73849a..dabed1509 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -140,9 +140,9 @@ mod tests { use tokio::sync::RwLock; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::{initialize_global_services, initialize_tracker}; + use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::tracker_apis::start_job; - use crate::core::services::statistics; + use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; use crate::servers::apis::Version; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -159,7 +159,10 @@ mod tests { let stats_repository = Arc::new(stats_repository); initialize_global_services(&cfg); - let tracker = Arc::new(initialize_tracker(&cfg)); + + let database = initialize_database(&cfg); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&cfg, &database, &whitelist_manager)); let version = Version::V1; diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index edec7fc1a..e74b2265e 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -333,9 +333,9 @@ mod tests { use tokio::sync::RwLock; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::{initialize_global_services, initialize_tracker}; + use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::make_rust_tls; - use crate::core::services::statistics; + use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -352,7 +352,10 @@ mod tests { let stats_repository = Arc::new(stats_repository); initialize_global_services(&cfg); - let tracker = Arc::new(initialize_tracker(&cfg)); + + let database = initialize_database(&cfg); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&cfg, &database, &whitelist_manager)); let bind_to = config.bind_address; diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index ec466ae4a..1cb8d7adb 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -242,9 +242,9 @@ mod tests { use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::{initialize_global_services, initialize_tracker}; + use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::make_rust_tls; - use crate::core::services::statistics; + use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::registar::Registar; @@ -256,7 +256,10 @@ mod tests { let stats_event_sender = Arc::new(stats_event_sender); initialize_global_services(&cfg); - let tracker = Arc::new(initialize_tracker(&cfg)); + + let database = initialize_database(&cfg); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&cfg, &database, &whitelist_manager)); let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); let config = &http_trackers[0]; diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 950c0fa74..d5fe554ea 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -63,8 +63,8 @@ mod tests { use super::spawner::Spawner; use super::Server; - use crate::bootstrap::app::{initialize_global_services, initialize_tracker}; - use crate::core::services::statistics; + use crate::bootstrap::app::initialize_global_services; + use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -78,7 +78,10 @@ mod tests { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); initialize_global_services(&cfg); - let tracker = Arc::new(initialize_tracker(&cfg)); + + let database = initialize_database(&cfg); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&cfg, &database, &whitelist_manager)); let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; @@ -114,7 +117,10 @@ mod tests { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); initialize_global_services(&cfg); - let tracker = Arc::new(initialize_tracker(&cfg)); + + let database = initialize_database(&cfg); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(&cfg, &database, &whitelist_manager)); let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index e7fc319d8..b230562f3 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -6,9 +6,9 @@ use futures::executor::block_on; use tokio::sync::RwLock; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::{Configuration, HttpApi}; -use torrust_tracker_lib::bootstrap::app::{initialize_global_services, initialize_tracker}; +use torrust_tracker_lib::bootstrap::app::initialize_global_services; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; -use torrust_tracker_lib::core::services::statistics; +use torrust_tracker_lib::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::whitelist::WhiteListManager; @@ -51,10 +51,10 @@ impl Environment { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); initialize_global_services(configuration); - let tracker = Arc::new(initialize_tracker(configuration)); - // todo: instantiate outside of `initialize_tracker_dependencies` - let whitelist_manager = tracker.whitelist_manager.clone(); + let database = initialize_database(configuration); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(configuration, &database, &whitelist_manager)); let config = Arc::new(configuration.http_api.clone().expect("missing API configuration")); diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 2137ca0d4..3732e9341 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -3,9 +3,9 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; use torrust_tracker_configuration::{Configuration, HttpTracker}; -use torrust_tracker_lib::bootstrap::app::{initialize_global_services, initialize_tracker}; +use torrust_tracker_lib::bootstrap::app::initialize_global_services; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; -use torrust_tracker_lib::core::services::statistics; +use torrust_tracker_lib::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::whitelist::WhiteListManager; @@ -39,10 +39,10 @@ impl Environment { let stats_repository = Arc::new(stats_repository); initialize_global_services(configuration); - let tracker = Arc::new(initialize_tracker(configuration)); - // todo: instantiate outside of `initialize_tracker_dependencies` - let whitelist_manager = tracker.whitelist_manager.clone(); + let database = initialize_database(configuration); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(configuration, &database, &whitelist_manager)); let http_tracker = configuration .http_trackers diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 0a0125714..34841df16 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -4,8 +4,8 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use tokio::sync::RwLock; use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; -use torrust_tracker_lib::bootstrap::app::{initialize_global_services, initialize_tracker}; -use torrust_tracker_lib::core::services::statistics; +use torrust_tracker_lib::bootstrap::app::initialize_global_services; +use torrust_tracker_lib::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::Tracker; @@ -50,7 +50,10 @@ impl Environment { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); initialize_global_services(configuration); - let tracker = Arc::new(initialize_tracker(configuration)); + + let database = initialize_database(configuration); + let whitelist_manager = initialize_whitelist(database.clone()); + let tracker = Arc::new(tracker_factory(configuration, &database, &whitelist_manager)); let udp_tracker = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); From aa9f1c314e4b020a32d591f3e32338d18de4d609 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 Jan 2025 17:31:19 +0000 Subject: [PATCH 0599/1297] refactor: [#1187] move fn initialize_tracker_dependencies --- src/app_test.rs | 18 ++++++++++++++++++ src/bootstrap/app.rs | 11 ----------- src/core/mod.rs | 2 +- src/core/services/statistics/mod.rs | 2 +- src/core/services/torrent.rs | 4 ++-- src/lib.rs | 1 + src/servers/http/v1/handlers/announce.rs | 2 +- src/servers/http/v1/handlers/scrape.rs | 2 +- src/servers/http/v1/services/announce.rs | 4 ++-- src/servers/http/v1/services/scrape.rs | 2 +- src/servers/udp/handlers.rs | 4 ++-- 11 files changed, 30 insertions(+), 22 deletions(-) create mode 100644 src/app_test.rs diff --git a/src/app_test.rs b/src/app_test.rs new file mode 100644 index 000000000..c50f87965 --- /dev/null +++ b/src/app_test.rs @@ -0,0 +1,18 @@ +//! This file contains only functions used for testing. +use std::sync::Arc; + +use torrust_tracker_configuration::Configuration; + +use crate::core::databases::Database; +use crate::core::services::{initialize_database, initialize_whitelist}; +use crate::core::whitelist::WhiteListManager; + +/// Initialize the tracker dependencies. +#[allow(clippy::type_complexity)] +#[must_use] +pub fn initialize_tracker_dependencies(config: &Configuration) -> (Arc>, Arc) { + let database = initialize_database(config); + let whitelist_manager = initialize_whitelist(database.clone()); + + (database, whitelist_manager) +} diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index b0df03404..fb3f50b65 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -22,9 +22,7 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; use crate::container::AppContainer; -use crate::core::databases::Database; use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; -use crate::core::whitelist::WhiteListManager; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; @@ -115,15 +113,6 @@ pub fn initialize_static() { lazy_static::initialize(&ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH); } -#[allow(clippy::type_complexity)] -#[must_use] -pub fn initialize_tracker_dependencies(config: &Configuration) -> (Arc>, Arc) { - let database = initialize_database(config); - let whitelist_manager = initialize_whitelist(database.clone()); - - (database, whitelist_manager) -} - /// It initializes the log threshold, format and channel. /// /// See [the logging setup](crate::bootstrap::logging::setup) for more info about logging. diff --git a/src/core/mod.rs b/src/core/mod.rs index 9aef1b2f2..a5f9988b9 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -1080,7 +1080,7 @@ mod tests { use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; - use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::app_test::initialize_tracker_dependencies; use crate::core::peer::Peer; use crate::core::services::tracker_factory; use crate::core::whitelist::WhiteListManager; diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 657f3eb06..fd185a727 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -117,7 +117,7 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; - use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::app_test::initialize_tracker_dependencies; use crate::core; use crate::core::services::statistics::{self, get_metrics, TrackerMetrics}; use crate::core::services::tracker_factory; diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 9a1a2a725..445b8fb8f 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -129,7 +129,7 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; - use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::app_test::initialize_tracker_dependencies; use crate::core::services::torrent::tests::sample_peer; use crate::core::services::torrent::{get_torrent_info, Info}; use crate::core::services::tracker_factory; @@ -191,7 +191,7 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; - use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::app_test::initialize_tracker_dependencies; use crate::core::services::torrent::tests::sample_peer; use crate::core::services::torrent::{get_torrents_page, BasicInfo, Pagination}; use crate::core::services::tracker_factory; diff --git a/src/lib.rs b/src/lib.rs index 212430605..8e0e64db0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -491,6 +491,7 @@ use torrust_tracker_clock::clock; pub mod app; +pub mod app_test; pub mod bootstrap; pub mod console; pub mod container; diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 1c8779625..6cfe0871f 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -205,7 +205,7 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; - use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::app_test::initialize_tracker_dependencies; use crate::core::services::{statistics, tracker_factory}; use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 6ff8a61cf..553b50882 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -126,7 +126,7 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; - use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::app_test::initialize_tracker_dependencies; use crate::core::services::{statistics, tracker_factory}; use crate::core::Tracker; diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 45bcb5843..263f5dbc7 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -65,7 +65,7 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::app_test::initialize_tracker_dependencies; use crate::core::services::{statistics, tracker_factory}; use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; @@ -123,7 +123,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; - use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::app_test::initialize_tracker_dependencies; use crate::core::{statistics, PeersWanted, Tracker}; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 9805dd8a4..61542478d 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -80,7 +80,7 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::app_test::initialize_tracker_dependencies; use crate::core::services::tracker_factory; use crate::core::Tracker; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 9883de54b..cad246b6f 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -470,7 +470,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::gen_remote_fingerprint; - use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::app_test::initialize_tracker_dependencies; use crate::core::services::{statistics, tracker_factory}; use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; @@ -1318,7 +1318,7 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; use mockall::predicate::eq; - use crate::bootstrap::app::initialize_tracker_dependencies; + use crate::app_test::initialize_tracker_dependencies; use crate::core::{self, statistics}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; From c45a12b9f595e9ac091701e11d6ea416b18e1aeb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 Jan 2025 17:38:16 +0000 Subject: [PATCH 0600/1297] refactor: [#1187] rename fn tracker_factory to initialize_tracker --- src/bootstrap/app.rs | 5 +++-- src/bootstrap/jobs/http_tracker.rs | 4 ++-- src/bootstrap/jobs/tracker_apis.rs | 4 ++-- src/container.rs | 2 ++ src/core/mod.rs | 10 +++++----- src/core/services/mod.rs | 2 +- src/core/services/statistics/mod.rs | 4 ++-- src/core/services/torrent.rs | 18 +++++++++--------- src/servers/apis/server.rs | 4 ++-- src/servers/http/server.rs | 4 ++-- src/servers/http/v1/handlers/announce.rs | 10 +++++----- src/servers/http/v1/handlers/scrape.rs | 10 +++++----- src/servers/http/v1/services/announce.rs | 4 ++-- src/servers/http/v1/services/scrape.rs | 4 ++-- src/servers/udp/handlers.rs | 4 ++-- src/servers/udp/server/mod.rs | 6 +++--- tests/servers/api/environment.rs | 23 +++++++---------------- tests/servers/http/environment.rs | 4 ++-- tests/servers/udp/environment.rs | 4 ++-- 19 files changed, 60 insertions(+), 66 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index fb3f50b65..d17aec3a7 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -22,7 +22,7 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; use crate::container::AppContainer; -use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; +use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; @@ -82,13 +82,14 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let database = initialize_database(configuration); let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(tracker_factory(configuration, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(configuration, &database, &whitelist_manager)); AppContainer { tracker, ban_service, stats_event_sender, stats_repository, + whitelist_manager, } } diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 0714cbd72..d32e8d4aa 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -88,7 +88,7 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::http_tracker::start_job; - use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; + use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; use crate::servers::http::Version; use crate::servers::registar::Registar; @@ -105,7 +105,7 @@ mod tests { let database = initialize_database(&cfg); let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(tracker_factory(&cfg, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_manager)); let version = Version::V1; diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index dabed1509..9c284fbfc 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -142,7 +142,7 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::tracker_apis::start_job; - use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; + use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; use crate::servers::apis::Version; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -162,7 +162,7 @@ mod tests { let database = initialize_database(&cfg); let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(tracker_factory(&cfg, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_manager)); let version = Version::V1; diff --git a/src/container.rs b/src/container.rs index 961b32a12..7a2b86d18 100644 --- a/src/container.rs +++ b/src/container.rs @@ -4,6 +4,7 @@ use tokio::sync::RwLock; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; +use crate::core::whitelist::WhiteListManager; use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; @@ -12,4 +13,5 @@ pub struct AppContainer { pub ban_service: Arc>, pub stats_event_sender: Arc>>, pub stats_repository: Arc, + pub whitelist_manager: Arc, } diff --git a/src/core/mod.rs b/src/core/mod.rs index a5f9988b9..e802b2c43 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -1082,26 +1082,26 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::peer::Peer; - use crate::core::services::tracker_factory; + use crate::core::services::initialize_tracker; use crate::core::whitelist::WhiteListManager; use crate::core::{TorrentsMetrics, Tracker}; fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + initialize_tracker(&config, &database, &whitelist_manager) } fn private_tracker() -> Tracker { let config = configuration::ephemeral_private(); let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + initialize_tracker(&config, &database, &whitelist_manager) } fn whitelisted_tracker() -> (Tracker, Arc) { let config = configuration::ephemeral_listed(); let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = tracker_factory(&config, &database, &whitelist_manager); + let tracker = initialize_tracker(&config, &database, &whitelist_manager); (tracker, whitelist_manager) } @@ -1110,7 +1110,7 @@ mod tests { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + initialize_tracker(&config, &database, &whitelist_manager) } fn sample_info_hash() -> InfoHash { diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index d3336068c..fd301b62d 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -24,7 +24,7 @@ use crate::core::Tracker; /// /// Will panic if tracker cannot be instantiated. #[must_use] -pub fn tracker_factory( +pub fn initialize_tracker( config: &Configuration, database: &Arc>, whitelist_manager: &Arc, diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index fd185a727..1e0403c2a 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -119,8 +119,8 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core; + use crate::core::services::initialize_tracker; use crate::core::services::statistics::{self, get_metrics, TrackerMetrics}; - use crate::core::services::tracker_factory; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -136,7 +136,7 @@ mod tests { let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_repository = Arc::new(stats_repository); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 445b8fb8f..593d8be8c 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -130,9 +130,9 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; + use crate::core::services::initialize_tracker; use crate::core::services::torrent::tests::sample_peer; use crate::core::services::torrent::{get_torrent_info, Info}; - use crate::core::services::tracker_factory; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -143,7 +143,7 @@ mod tests { let config = tracker_configuration(); let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = tracker_factory(&config, &database, &whitelist_manager); + let tracker = initialize_tracker(&config, &database, &whitelist_manager); let tracker = Arc::new(tracker); @@ -161,7 +161,7 @@ mod tests { let config = tracker_configuration(); let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -192,9 +192,9 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; + use crate::core::services::initialize_tracker; use crate::core::services::torrent::tests::sample_peer; use crate::core::services::torrent::{get_torrents_page, BasicInfo, Pagination}; - use crate::core::services::tracker_factory; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -205,7 +205,7 @@ mod tests { let config = tracker_configuration(); let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -217,7 +217,7 @@ mod tests { let config = tracker_configuration(); let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -242,7 +242,7 @@ mod tests { let config = tracker_configuration(); let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -265,7 +265,7 @@ mod tests { let config = tracker_configuration(); let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -297,7 +297,7 @@ mod tests { let config = tracker_configuration(); let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(tracker_factory(&config, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index e74b2265e..c4fae6ebf 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -335,7 +335,7 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::make_rust_tls; - use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; + use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -355,7 +355,7 @@ mod tests { let database = initialize_database(&cfg); let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(tracker_factory(&cfg, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_manager)); let bind_to = config.bind_address; diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 1cb8d7adb..82b65c2ff 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -244,7 +244,7 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::make_rust_tls; - use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; + use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::registar::Registar; @@ -259,7 +259,7 @@ mod tests { let database = initialize_database(&cfg); let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(tracker_factory(&cfg, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_manager)); let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); let config = &http_trackers[0]; diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 6cfe0871f..24beadbc2 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -206,7 +206,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; - use crate::core::services::{statistics, tracker_factory}; + use crate::core::services::{initialize_tracker, statistics}; use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; @@ -216,7 +216,7 @@ mod tests { let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) + (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) } fn whitelisted_tracker() -> (Tracker, Option>) { @@ -225,7 +225,7 @@ mod tests { let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) + (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) } fn tracker_on_reverse_proxy() -> (Tracker, Option>) { @@ -234,7 +234,7 @@ mod tests { let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) + (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) } fn tracker_not_on_reverse_proxy() -> (Tracker, Option>) { @@ -243,7 +243,7 @@ mod tests { let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) + (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) } fn sample_announce_request() -> Announce { diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 553b50882..a5cf58129 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -127,7 +127,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; - use crate::core::services::{statistics, tracker_factory}; + use crate::core::services::{initialize_tracker, statistics}; use crate::core::Tracker; fn private_tracker() -> (Tracker, Option>) { @@ -136,7 +136,7 @@ mod tests { let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) + (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) } fn whitelisted_tracker() -> (Tracker, Option>) { @@ -145,7 +145,7 @@ mod tests { let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) + (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) } fn tracker_on_reverse_proxy() -> (Tracker, Option>) { @@ -154,7 +154,7 @@ mod tests { let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) + (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) } fn tracker_not_on_reverse_proxy() -> (Tracker, Option>) { @@ -163,7 +163,7 @@ mod tests { let (database, whitelist_manager) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (tracker_factory(&config, &database, &whitelist_manager), stats_event_sender) + (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) } fn sample_scrape_request() -> Scrape { diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 263f5dbc7..63a904182 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -66,7 +66,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; - use crate::core::services::{statistics, tracker_factory}; + use crate::core::services::{initialize_tracker, statistics}; use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; @@ -77,7 +77,7 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = tracker_factory(&config, &database, &whitelist_manager); + let tracker = initialize_tracker(&config, &database, &whitelist_manager); (tracker, stats_event_sender) } diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 61542478d..56c18cbb3 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -81,7 +81,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; - use crate::core::services::tracker_factory; + use crate::core::services::initialize_tracker; use crate::core::Tracker; fn public_tracker() -> Tracker { @@ -89,7 +89,7 @@ mod tests { let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - tracker_factory(&config, &database, &whitelist_manager) + initialize_tracker(&config, &database, &whitelist_manager) } fn sample_info_hashes() -> Vec { diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index cad246b6f..a7d964391 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -471,7 +471,7 @@ mod tests { use super::gen_remote_fingerprint; use crate::app_test::initialize_tracker_dependencies; - use crate::core::services::{statistics, tracker_factory}; + use crate::core::services::{initialize_tracker, statistics}; use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; use crate::CurrentClock; @@ -496,7 +496,7 @@ mod tests { let (database, whitelist_manager) = initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (tracker_factory(config, &database, &whitelist_manager), stats_event_sender) + (initialize_tracker(config, &database, &whitelist_manager), stats_event_sender) } fn sample_ipv4_remote_addr() -> SocketAddr { diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index d5fe554ea..b5da9d326 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -64,7 +64,7 @@ mod tests { use super::spawner::Spawner; use super::Server; use crate::bootstrap::app::initialize_global_services; - use crate::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; + use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -81,7 +81,7 @@ mod tests { let database = initialize_database(&cfg); let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(tracker_factory(&cfg, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_manager)); let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; @@ -120,7 +120,7 @@ mod tests { let database = initialize_database(&cfg); let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(tracker_factory(&cfg, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_manager)); let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index b230562f3..dcfe526f1 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -6,9 +6,8 @@ use futures::executor::block_on; use tokio::sync::RwLock; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::{Configuration, HttpApi}; -use torrust_tracker_lib::bootstrap::app::initialize_global_services; +use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; -use torrust_tracker_lib::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::whitelist::WhiteListManager; @@ -16,7 +15,6 @@ use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::banning::BanService; -use torrust_tracker_lib::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use torrust_tracker_primitives::peer; pub struct Environment @@ -45,16 +43,9 @@ where impl Environment { pub fn new(configuration: &Arc) -> Self { - let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - let stats_repository = Arc::new(stats_repository); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - initialize_global_services(configuration); - let database = initialize_database(configuration); - let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(tracker_factory(configuration, &database, &whitelist_manager)); + let app_container = initialize_app_container(configuration); let config = Arc::new(configuration.http_api.clone().expect("missing API configuration")); @@ -66,11 +57,11 @@ impl Environment { Self { config, - tracker, - stats_event_sender, - stats_repository, - whitelist_manager, - ban_service, + tracker: app_container.tracker.clone(), + stats_event_sender: app_container.stats_event_sender.clone(), + stats_repository: app_container.stats_repository.clone(), + whitelist_manager: app_container.whitelist_manager.clone(), + ban_service: app_container.ban_service.clone(), registar: Registar::default(), server, } diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 3732e9341..f1f0e8247 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -5,7 +5,7 @@ use futures::executor::block_on; use torrust_tracker_configuration::{Configuration, HttpTracker}; use torrust_tracker_lib::bootstrap::app::initialize_global_services; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; -use torrust_tracker_lib::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; +use torrust_tracker_lib::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::whitelist::WhiteListManager; @@ -42,7 +42,7 @@ impl Environment { let database = initialize_database(configuration); let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(tracker_factory(configuration, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(configuration, &database, &whitelist_manager)); let http_tracker = configuration .http_trackers diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 34841df16..10ef97f47 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -5,7 +5,7 @@ use bittorrent_primitives::info_hash::InfoHash; use tokio::sync::RwLock; use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::initialize_global_services; -use torrust_tracker_lib::core::services::{initialize_database, initialize_whitelist, statistics, tracker_factory}; +use torrust_tracker_lib::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::Tracker; @@ -53,7 +53,7 @@ impl Environment { let database = initialize_database(configuration); let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(tracker_factory(configuration, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(configuration, &database, &whitelist_manager)); let udp_tracker = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); From 3d0f4f820bcb7ff1348f59ad647e2efe5179de49 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 Jan 2025 17:54:56 +0000 Subject: [PATCH 0601/1297] refactor: [#1187] use AppContainer in test environments --- tests/servers/http/environment.rs | 19 ++++++------------- tests/servers/udp/environment.rs | 21 ++++++--------------- 2 files changed, 12 insertions(+), 28 deletions(-) diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index f1f0e8247..131fe4ac1 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -3,9 +3,8 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; use torrust_tracker_configuration::{Configuration, HttpTracker}; -use torrust_tracker_lib::bootstrap::app::initialize_global_services; +use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; -use torrust_tracker_lib::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::whitelist::WhiteListManager; @@ -34,15 +33,9 @@ impl Environment { impl Environment { #[allow(dead_code)] pub fn new(configuration: &Arc) -> Self { - let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - let stats_repository = Arc::new(stats_repository); - initialize_global_services(configuration); - let database = initialize_database(configuration); - let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(initialize_tracker(configuration, &database, &whitelist_manager)); + let app_container = initialize_app_container(configuration); let http_tracker = configuration .http_trackers @@ -59,10 +52,10 @@ impl Environment { Self { config, - tracker, - stats_event_sender, - stats_repository, - whitelist_manager, + tracker: app_container.tracker.clone(), + stats_event_sender: app_container.stats_event_sender.clone(), + stats_repository: app_container.stats_repository.clone(), + whitelist_manager: app_container.whitelist_manager.clone(), registar: Registar::default(), server, } diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 10ef97f47..81e626e1c 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -4,14 +4,12 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use tokio::sync::RwLock; use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; -use torrust_tracker_lib::bootstrap::app::initialize_global_services; -use torrust_tracker_lib::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; +use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::banning::BanService; -use torrust_tracker_lib::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; use torrust_tracker_lib::servers::udp::server::Server; @@ -44,16 +42,9 @@ where impl Environment { #[allow(dead_code)] pub fn new(configuration: &Arc) -> Self { - let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - let stats_repository = Arc::new(stats_repository); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - initialize_global_services(configuration); - let database = initialize_database(configuration); - let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(initialize_tracker(configuration, &database, &whitelist_manager)); + let app_container = initialize_app_container(configuration); let udp_tracker = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); @@ -65,10 +56,10 @@ impl Environment { Self { config, - tracker, - stats_event_sender, - stats_repository, - ban_service, + tracker: app_container.tracker.clone(), + stats_event_sender: app_container.stats_event_sender.clone(), + stats_repository: app_container.stats_repository.clone(), + ban_service: app_container.ban_service.clone(), registar: Registar::default(), server, } From 20018abe446af1503463a9ac99631c616a0618dd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 17 Jan 2025 18:14:57 +0000 Subject: [PATCH 0602/1297] fix: [#1187] doc link error --- src/bootstrap/app.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index d17aec3a7..53bf44f79 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -28,7 +28,7 @@ use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; use crate::shared::crypto::keys::{self, Keeper as _}; -/// It loads the configuration from the environment and builds the main domain [`Tracker`] struct. +/// It loads the configuration from the environment and builds app container. /// /// # Panics /// From c35c1243f9cdfee45b98ee253749e352e2819eec Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 20 Jan 2025 08:48:30 +0000 Subject: [PATCH 0603/1297] refactor: [#1189] new whitelist::repository module --- src/core/services/mod.rs | 2 +- src/core/whitelist/mod.rs | 7 +++---- src/core/whitelist/{ => repository}/in_memory.rs | 2 +- src/core/whitelist/repository/mod.rs | 2 ++ src/core/whitelist/{ => repository}/persisted.rs | 2 +- 5 files changed, 8 insertions(+), 7 deletions(-) rename src/core/whitelist/{ => repository}/in_memory.rs (97%) create mode 100644 src/core/whitelist/repository/mod.rs rename src/core/whitelist/{ => repository}/persisted.rs (97%) diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index fd301b62d..cfb62d625 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -14,7 +14,7 @@ use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::Configuration; use super::databases::{self, Database}; -use super::whitelist::persisted::DatabaseWhitelist; +use super::whitelist::repository::persisted::DatabaseWhitelist; use super::whitelist::WhiteListManager; use crate::core::Tracker; diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs index 3a88b404c..1504838dc 100644 --- a/src/core/whitelist/mod.rs +++ b/src/core/whitelist/mod.rs @@ -1,11 +1,10 @@ -pub mod in_memory; -pub mod persisted; +pub mod repository; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; -use in_memory::InMemoryWhitelist; -use persisted::DatabaseWhitelist; +use repository::in_memory::InMemoryWhitelist; +use repository::persisted::DatabaseWhitelist; use super::databases::{self}; diff --git a/src/core/whitelist/in_memory.rs b/src/core/whitelist/repository/in_memory.rs similarity index 97% rename from src/core/whitelist/in_memory.rs rename to src/core/whitelist/repository/in_memory.rs index 78e0eb11f..8d919f1e4 100644 --- a/src/core/whitelist/in_memory.rs +++ b/src/core/whitelist/repository/in_memory.rs @@ -34,7 +34,7 @@ impl InMemoryWhitelist { mod tests { use bittorrent_primitives::info_hash::InfoHash; - use crate::core::whitelist::in_memory::InMemoryWhitelist; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; fn sample_info_hash() -> InfoHash { "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() // # DevSkim: ignore DS173237 diff --git a/src/core/whitelist/repository/mod.rs b/src/core/whitelist/repository/mod.rs new file mode 100644 index 000000000..51723b68d --- /dev/null +++ b/src/core/whitelist/repository/mod.rs @@ -0,0 +1,2 @@ +pub mod in_memory; +pub mod persisted; diff --git a/src/core/whitelist/persisted.rs b/src/core/whitelist/repository/persisted.rs similarity index 97% rename from src/core/whitelist/persisted.rs rename to src/core/whitelist/repository/persisted.rs index 993060139..fd56d56b5 100644 --- a/src/core/whitelist/persisted.rs +++ b/src/core/whitelist/repository/persisted.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; -use super::databases::{self, Database}; +use crate::core::databases::{self, Database}; /// The persisted list of allowed torrents. pub struct DatabaseWhitelist { From 597c9862cf4b3d07a470d12898aa43020f31991a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 20 Jan 2025 08:53:52 +0000 Subject: [PATCH 0604/1297] refactor: [#1189] extract mod whitelist::manager --- src/app_test.rs | 2 +- src/container.rs | 2 +- src/core/mod.rs | 4 +- src/core/services/mod.rs | 2 +- src/core/whitelist/manager.rs | 91 ++++++++++++++++++ src/core/whitelist/mod.rs | 93 +------------------ .../apis/v1/context/whitelist/handlers.rs | 2 +- tests/servers/api/environment.rs | 2 +- tests/servers/http/environment.rs | 2 +- 9 files changed, 100 insertions(+), 100 deletions(-) create mode 100644 src/core/whitelist/manager.rs diff --git a/src/app_test.rs b/src/app_test.rs index c50f87965..92f64cc7b 100644 --- a/src/app_test.rs +++ b/src/app_test.rs @@ -5,7 +5,7 @@ use torrust_tracker_configuration::Configuration; use crate::core::databases::Database; use crate::core::services::{initialize_database, initialize_whitelist}; -use crate::core::whitelist::WhiteListManager; +use crate::core::whitelist::manager::WhiteListManager; /// Initialize the tracker dependencies. #[allow(clippy::type_complexity)] diff --git a/src/container.rs b/src/container.rs index 7a2b86d18..3f7028d4b 100644 --- a/src/container.rs +++ b/src/container.rs @@ -4,7 +4,7 @@ use tokio::sync::RwLock; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; -use crate::core::whitelist::WhiteListManager; +use crate::core::whitelist::manager::WhiteListManager; use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; diff --git a/src/core/mod.rs b/src/core/mod.rs index e802b2c43..0349fd935 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -468,7 +468,7 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; use tracing::instrument; -use whitelist::WhiteListManager; +use whitelist::manager::WhiteListManager; use self::auth::Key; use self::error::Error; @@ -1083,7 +1083,7 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::peer::Peer; use crate::core::services::initialize_tracker; - use crate::core::whitelist::WhiteListManager; + use crate::core::whitelist::manager::WhiteListManager; use crate::core::{TorrentsMetrics, Tracker}; fn public_tracker() -> Tracker { diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index cfb62d625..e0f67305a 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -14,8 +14,8 @@ use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::Configuration; use super::databases::{self, Database}; +use super::whitelist::manager::WhiteListManager; use super::whitelist::repository::persisted::DatabaseWhitelist; -use super::whitelist::WhiteListManager; use crate::core::Tracker; /// It returns a new tracker building its dependencies. diff --git a/src/core/whitelist/manager.rs b/src/core/whitelist/manager.rs new file mode 100644 index 000000000..832af6892 --- /dev/null +++ b/src/core/whitelist/manager.rs @@ -0,0 +1,91 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; + +use super::repository::in_memory::InMemoryWhitelist; +use super::repository::persisted::DatabaseWhitelist; +use crate::core::databases; + +/// It handles the list of allowed torrents. Only for listed trackers. +pub struct WhiteListManager { + /// The in-memory list of allowed torrents. + in_memory_whitelist: InMemoryWhitelist, + + /// The persisted list of allowed torrents. + database_whitelist: Arc, +} + +impl WhiteListManager { + #[must_use] + pub fn new(database_whitelist: Arc) -> Self { + Self { + in_memory_whitelist: InMemoryWhitelist::default(), + database_whitelist, + } + } + + /// It adds a torrent to the whitelist. + /// Adding torrents is not relevant to public trackers. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. + pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + self.database_whitelist.add(info_hash)?; + self.in_memory_whitelist.add(info_hash).await; + Ok(()) + } + + /// It removes a torrent from the whitelist. + /// Removing torrents is not relevant to public trackers. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. + pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + self.database_whitelist.remove(info_hash)?; + self.in_memory_whitelist.remove(info_hash).await; + Ok(()) + } + + /// It removes a torrent from the whitelist in the database. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. + pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + self.database_whitelist.remove(info_hash) + } + + /// It adds a torrent from the whitelist in memory. + pub async fn add_torrent_to_memory_whitelist(&self, info_hash: &InfoHash) -> bool { + self.in_memory_whitelist.add(info_hash).await + } + + /// It removes a torrent from the whitelist in memory. + pub async fn remove_torrent_from_memory_whitelist(&self, info_hash: &InfoHash) -> bool { + self.in_memory_whitelist.remove(info_hash).await + } + + /// It checks if a torrent is whitelisted. + pub async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { + self.in_memory_whitelist.contains(info_hash).await + } + + /// It loads the whitelist from the database. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. + pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { + let whitelisted_torrents_from_database = self.database_whitelist.load_from_database()?; + + self.in_memory_whitelist.clear().await; + + for info_hash in whitelisted_torrents_from_database { + let _: bool = self.in_memory_whitelist.add(&info_hash).await; + } + + Ok(()) + } +} diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs index 1504838dc..faf83c87b 100644 --- a/src/core/whitelist/mod.rs +++ b/src/core/whitelist/mod.rs @@ -1,93 +1,2 @@ +pub mod manager; pub mod repository; - -use std::sync::Arc; - -use bittorrent_primitives::info_hash::InfoHash; -use repository::in_memory::InMemoryWhitelist; -use repository::persisted::DatabaseWhitelist; - -use super::databases::{self}; - -/// It handles the list of allowed torrents. Only for listed trackers. -pub struct WhiteListManager { - /// The in-memory list of allowed torrents. - in_memory_whitelist: InMemoryWhitelist, - - /// The persisted list of allowed torrents. - database_whitelist: Arc, -} - -impl WhiteListManager { - #[must_use] - pub fn new(database_whitelist: Arc) -> Self { - Self { - in_memory_whitelist: InMemoryWhitelist::default(), - database_whitelist, - } - } - - /// It adds a torrent to the whitelist. - /// Adding torrents is not relevant to public trackers. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. - pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.database_whitelist.add(info_hash)?; - self.in_memory_whitelist.add(info_hash).await; - Ok(()) - } - - /// It removes a torrent from the whitelist. - /// Removing torrents is not relevant to public trackers. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. - pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.database_whitelist.remove(info_hash)?; - self.in_memory_whitelist.remove(info_hash).await; - Ok(()) - } - - /// It removes a torrent from the whitelist in the database. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. - pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.database_whitelist.remove(info_hash) - } - - /// It adds a torrent from the whitelist in memory. - pub async fn add_torrent_to_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.in_memory_whitelist.add(info_hash).await - } - - /// It removes a torrent from the whitelist in memory. - pub async fn remove_torrent_from_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.in_memory_whitelist.remove(info_hash).await - } - - /// It checks if a torrent is whitelisted. - pub async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { - self.in_memory_whitelist.contains(info_hash).await - } - - /// It loads the whitelist from the database. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. - pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { - let whitelisted_torrents_from_database = self.database_whitelist.load_from_database()?; - - self.in_memory_whitelist.clear().await; - - for info_hash in whitelisted_torrents_from_database { - let _: bool = self.in_memory_whitelist.add(&info_hash).await; - } - - Ok(()) - } -} diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/src/servers/apis/v1/context/whitelist/handlers.rs index f548f5dc4..473ed56c5 100644 --- a/src/servers/apis/v1/context/whitelist/handlers.rs +++ b/src/servers/apis/v1/context/whitelist/handlers.rs @@ -10,7 +10,7 @@ use bittorrent_primitives::info_hash::InfoHash; use super::responses::{ failed_to_reload_whitelist_response, failed_to_remove_torrent_from_whitelist_response, failed_to_whitelist_torrent_response, }; -use crate::core::whitelist::WhiteListManager; +use crate::core::whitelist::manager::WhiteListManager; use crate::servers::apis::v1::responses::{invalid_info_hash_param_response, ok_response}; use crate::servers::apis::InfoHashParam; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index dcfe526f1..cf997eb7c 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -10,7 +10,7 @@ use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_g use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; -use torrust_tracker_lib::core::whitelist::WhiteListManager; +use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 131fe4ac1..d68924e07 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -7,7 +7,7 @@ use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_g use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; -use torrust_tracker_lib::core::whitelist::WhiteListManager; +use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; From a5f41fc1c18c998f88b266daeb247a555f817a00 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 20 Jan 2025 13:36:47 +0000 Subject: [PATCH 0605/1297] refactor: [#1189] extract whitelist::authorization::Authorization --- src/app.rs | 4 +- src/app_test.rs | 21 +- src/bootstrap/app.rs | 15 +- src/bootstrap/jobs/http_tracker.rs | 47 +++-- src/bootstrap/jobs/tracker_apis.rs | 26 ++- src/bootstrap/jobs/udp_tracker.rs | 14 +- src/container.rs | 3 +- src/core/mod.rs | 85 +++----- src/core/services/mod.rs | 13 +- src/core/services/statistics/mod.rs | 7 +- src/core/services/torrent.rs | 28 +-- src/core/whitelist/authorization.rs | 59 ++++++ src/core/whitelist/manager.rs | 6 +- src/core/whitelist/mod.rs | 1 + src/servers/apis/routes.rs | 12 +- src/servers/apis/server.rs | 23 ++- .../apis/v1/context/whitelist/routes.rs | 10 +- src/servers/apis/v1/routes.rs | 4 +- src/servers/http/server.rs | 25 ++- src/servers/http/v1/handlers/announce.rs | 87 +++++---- src/servers/http/v1/handlers/scrape.rs | 28 ++- src/servers/http/v1/routes.rs | 23 ++- src/servers/http/v1/services/announce.rs | 8 +- src/servers/http/v1/services/scrape.rs | 8 +- src/servers/udp/handlers.rs | 184 +++++++++++------- src/servers/udp/server/launcher.rs | 20 +- src/servers/udp/server/mod.rs | 24 ++- src/servers/udp/server/processor.rs | 6 +- src/servers/udp/server/spawner.rs | 5 +- src/servers/udp/server/states.rs | 6 +- tests/servers/api/environment.rs | 1 + tests/servers/http/environment.rs | 13 +- tests/servers/udp/environment.rs | 7 +- 33 files changed, 551 insertions(+), 272 deletions(-) create mode 100644 src/core/whitelist/authorization.rs diff --git a/src/app.rs b/src/app.rs index 64119aa34..289db1fdc 100644 --- a/src/app.rs +++ b/src/app.rs @@ -61,7 +61,6 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< // Load whitelisted torrents if app_container.tracker.is_listed() { app_container - .tracker .whitelist_manager .load_whitelist_from_database() .await @@ -81,6 +80,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< udp_tracker::start_job( udp_tracker_config, app_container.tracker.clone(), + app_container.whitelist_authorization.clone(), app_container.stats_event_sender.clone(), app_container.ban_service.clone(), registar.give_form(), @@ -99,6 +99,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< if let Some(job) = http_tracker::start_job( http_tracker_config, app_container.tracker.clone(), + app_container.whitelist_authorization.clone(), app_container.stats_event_sender.clone(), registar.give_form(), servers::http::Version::V1, @@ -117,6 +118,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< if let Some(job) = tracker_apis::start_job( http_api_config, app_container.tracker.clone(), + app_container.whitelist_manager.clone(), app_container.ban_service.clone(), app_container.stats_event_sender.clone(), app_container.stats_repository.clone(), diff --git a/src/app_test.rs b/src/app_test.rs index 92f64cc7b..ffd55581e 100644 --- a/src/app_test.rs +++ b/src/app_test.rs @@ -4,15 +4,26 @@ use std::sync::Arc; use torrust_tracker_configuration::Configuration; use crate::core::databases::Database; -use crate::core::services::{initialize_database, initialize_whitelist}; -use crate::core::whitelist::manager::WhiteListManager; +use crate::core::services::initialize_database; +use crate::core::whitelist; +use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; /// Initialize the tracker dependencies. #[allow(clippy::type_complexity)] #[must_use] -pub fn initialize_tracker_dependencies(config: &Configuration) -> (Arc>, Arc) { +pub fn initialize_tracker_dependencies( + config: &Configuration, +) -> ( + Arc>, + Arc, + Arc, +) { let database = initialize_database(config); - let whitelist_manager = initialize_whitelist(database.clone()); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + &config.core, + &in_memory_whitelist.clone(), + )); - (database, whitelist_manager) + (database, in_memory_whitelist, whitelist_authorization) } diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 53bf44f79..5dbdd15cb 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -22,7 +22,9 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; use crate::container::AppContainer; -use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; +use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; +use crate::core::whitelist; +use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; @@ -81,11 +83,18 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let stats_repository = Arc::new(stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let database = initialize_database(configuration); - let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(initialize_tracker(configuration, &database, &whitelist_manager)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + &configuration.core, + &in_memory_whitelist.clone(), + )); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + + let tracker = Arc::new(initialize_tracker(configuration, &database, &whitelist_authorization)); AppContainer { tracker, + whitelist_authorization, ban_service, stats_event_sender, stats_repository, diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index d32e8d4aa..dea866648 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -20,7 +20,7 @@ use tracing::instrument; use super::make_rust_tls; use crate::core::statistics::event::sender::Sender; -use crate::core::{self, statistics}; +use crate::core::{self, statistics, whitelist}; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::http::Version; use crate::servers::registar::ServiceRegistrationForm; @@ -34,10 +34,11 @@ use crate::servers::registar::ServiceRegistrationForm; /// /// It would panic if the `config::HttpTracker` struct would contain inappropriate values. /// -#[instrument(skip(config, tracker, stats_event_sender, form))] +#[instrument(skip(config, tracker, whitelist_authorization, stats_event_sender, form))] pub async fn start_job( config: &HttpTracker, tracker: Arc, + whitelist_authorization: Arc, stats_event_sender: Arc>>, form: ServiceRegistrationForm, version: Version, @@ -49,21 +50,32 @@ pub async fn start_job( .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); match version { - Version::V1 => Some(start_v1(socket, tls, tracker.clone(), stats_event_sender.clone(), form).await), + Version::V1 => Some( + start_v1( + socket, + tls, + tracker.clone(), + whitelist_authorization.clone(), + stats_event_sender.clone(), + form, + ) + .await, + ), } } #[allow(clippy::async_yields_async)] -#[instrument(skip(socket, tls, tracker, stats_event_sender, form))] +#[instrument(skip(socket, tls, tracker, whitelist_authorization, stats_event_sender, form))] async fn start_v1( socket: SocketAddr, tls: Option, tracker: Arc, + whitelist_authorization: Arc, stats_event_sender: Arc>>, form: ServiceRegistrationForm, ) -> JoinHandle<()> { let server = HttpServer::new(Launcher::new(socket, tls)) - .start(tracker, stats_event_sender, form) + .start(tracker, whitelist_authorization, stats_event_sender, form) .await .expect("it should be able to start to the http tracker"); @@ -88,7 +100,9 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::http_tracker::start_job; - use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; + use crate::core::services::{initialize_database, initialize_tracker, statistics}; + use crate::core::whitelist; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::http::Version; use crate::servers::registar::Registar; @@ -104,13 +118,24 @@ mod tests { initialize_global_services(&cfg); let database = initialize_database(&cfg); - let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_manager)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + &cfg.core, + &in_memory_whitelist.clone(), + )); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); let version = Version::V1; - start_job(config, tracker, stats_event_sender, Registar::default().give_form(), version) - .await - .expect("it should be able to join to the http tracker start-job"); + start_job( + config, + tracker, + whitelist_authorization, + stats_event_sender, + Registar::default().give_form(), + version, + ) + .await + .expect("it should be able to join to the http tracker start-job"); } } diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 9c284fbfc..7e06829c4 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -30,9 +30,10 @@ use torrust_tracker_configuration::{AccessTokens, HttpApi}; use tracing::instrument; use super::make_rust_tls; -use crate::core; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; +use crate::core::whitelist::manager::WhiteListManager; +use crate::core::{self}; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::apis::Version; use crate::servers::registar::ServiceRegistrationForm; @@ -58,10 +59,12 @@ pub struct ApiServerJobStarted(); /// It would panic if unable to send the `ApiServerJobStarted` notice. /// /// -#[instrument(skip(config, tracker, ban_service, stats_event_sender, stats_repository, form))] +#[allow(clippy::too_many_arguments)] +#[instrument(skip(config, tracker, whitelist_manager, ban_service, stats_event_sender, stats_repository, form))] pub async fn start_job( config: &HttpApi, tracker: Arc, + whitelist_manager: Arc, ban_service: Arc>, stats_event_sender: Arc>>, stats_repository: Arc, @@ -82,6 +85,7 @@ pub async fn start_job( bind_to, tls, tracker.clone(), + whitelist_manager.clone(), ban_service.clone(), stats_event_sender.clone(), stats_repository.clone(), @@ -99,6 +103,7 @@ pub async fn start_job( socket, tls, tracker, + whitelist_manager, ban_service, stats_event_sender, stats_repository, @@ -109,6 +114,7 @@ async fn start_v1( socket: SocketAddr, tls: Option, tracker: Arc, + whitelist_manager: Arc, ban_service: Arc>, stats_event_sender: Arc>>, stats_repository: Arc, @@ -118,6 +124,7 @@ async fn start_v1( let server = ApiServer::new(Launcher::new(socket, tls)) .start( tracker, + whitelist_manager, stats_event_sender, stats_repository, ban_service, @@ -142,7 +149,9 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::tracker_apis::start_job; - use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; + use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; + use crate::core::whitelist; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::apis::Version; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -161,14 +170,21 @@ mod tests { initialize_global_services(&cfg); let database = initialize_database(&cfg); - let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_manager)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + &cfg.core, + &in_memory_whitelist.clone(), + )); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); let version = Version::V1; start_job( config, tracker, + whitelist_manager, ban_service, stats_event_sender, stats_repository, diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 105c7f723..724e2043e 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -13,8 +13,8 @@ use tokio::task::JoinHandle; use torrust_tracker_configuration::UdpTracker; use tracing::instrument; -use crate::core; use crate::core::statistics::event::sender::Sender; +use crate::core::{self, whitelist}; use crate::servers::registar::ServiceRegistrationForm; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::spawner::Spawner; @@ -32,10 +32,11 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// It will panic if the task did not finish successfully. #[must_use] #[allow(clippy::async_yields_async)] -#[instrument(skip(config, tracker, stats_event_sender, ban_service, form))] +#[instrument(skip(config, tracker, whitelist_authorization, stats_event_sender, ban_service, form))] pub async fn start_job( config: &UdpTracker, tracker: Arc, + whitelist_authorization: Arc, stats_event_sender: Arc>>, ban_service: Arc>, form: ServiceRegistrationForm, @@ -44,7 +45,14 @@ pub async fn start_job( let cookie_lifetime = config.cookie_lifetime; let server = Server::new(Spawner::new(bind_to)) - .start(tracker, stats_event_sender, ban_service, form, cookie_lifetime) + .start( + tracker, + whitelist_authorization, + stats_event_sender, + ban_service, + form, + cookie_lifetime, + ) .await .expect("it should be able to start the udp tracker"); diff --git a/src/container.rs b/src/container.rs index 3f7028d4b..fd75601ae 100644 --- a/src/container.rs +++ b/src/container.rs @@ -5,11 +5,12 @@ use tokio::sync::RwLock; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; use crate::core::whitelist::manager::WhiteListManager; -use crate::core::Tracker; +use crate::core::{whitelist, Tracker}; use crate::servers::udp::server::banning::BanService; pub struct AppContainer { pub tracker: Arc, + pub whitelist_authorization: Arc, pub ban_service: Arc>, pub stats_event_sender: Arc>>, pub stats_repository: Arc, diff --git a/src/core/mod.rs b/src/core/mod.rs index 0349fd935..480d0e971 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -467,11 +467,8 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; -use tracing::instrument; -use whitelist::manager::WhiteListManager; use self::auth::Key; -use self::error::Error; use self::torrent::Torrents; use crate::core::databases::Database; use crate::CurrentClock; @@ -496,8 +493,8 @@ pub struct Tracker { /// Tracker users' keys. Only for private trackers. keys: tokio::sync::RwLock>, - /// The list of allowed torrents. Only for listed trackers. - pub whitelist_manager: Arc, + /// The service to check is a torrent is whitelisted. + pub whitelist_authorization: Arc, /// The in-memory torrents repository. torrents: Arc, @@ -568,13 +565,13 @@ impl Tracker { pub fn new( config: &Core, database: &Arc>, - whitelist_manager: &Arc, + whitelist_authorization: &Arc, ) -> Result { Ok(Tracker { config: config.clone(), database: database.clone(), keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), - whitelist_manager: whitelist_manager.clone(), + whitelist_authorization: whitelist_authorization.clone(), torrents: Arc::default(), }) } @@ -663,7 +660,7 @@ impl Tracker { let mut scrape_data = ScrapeData::empty(); for info_hash in info_hashes { - let swarm_metadata = match self.authorize(info_hash).await { + let swarm_metadata = match self.whitelist_authorization.authorize(info_hash).await { Ok(()) => self.get_swarm_metadata(info_hash), Err(_) => SwarmMetadata::zeroed(), }; @@ -1018,31 +1015,6 @@ impl Tracker { Ok(()) } - /// Right now, there is only authorization when the `Tracker` runs in - /// `listed` or `private_listed` modes. - /// - /// # Context: Authorization - /// - /// # Errors - /// - /// Will return an error if the tracker is running in `listed` mode - /// and the infohash is not whitelisted. - #[instrument(skip(self, info_hash), err)] - pub async fn authorize(&self, info_hash: &InfoHash) -> Result<(), Error> { - if !self.is_listed() { - return Ok(()); - } - - if self.whitelist_manager.is_info_hash_whitelisted(info_hash).await { - return Ok(()); - } - - Err(Error::TorrentNotWhitelisted { - info_hash: *info_hash, - location: Location::caller(), - }) - } - /// It drops the database tables. /// /// # Errors @@ -1082,35 +1054,42 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::peer::Peer; - use crate::core::services::initialize_tracker; + use crate::core::services::{initialize_tracker, initialize_whitelist_manager}; use crate::core::whitelist::manager::WhiteListManager; - use crate::core::{TorrentsMetrics, Tracker}; + use crate::core::{whitelist, TorrentsMetrics, Tracker}; fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - initialize_tracker(&config, &database, &whitelist_manager) + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + + initialize_tracker(&config, &database, &whitelist_authorization) } fn private_tracker() -> Tracker { let config = configuration::ephemeral_private(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - initialize_tracker(&config, &database, &whitelist_manager) + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + + initialize_tracker(&config, &database, &whitelist_authorization) } - fn whitelisted_tracker() -> (Tracker, Arc) { + fn whitelisted_tracker() -> (Tracker, Arc, Arc) { let config = configuration::ephemeral_listed(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = initialize_tracker(&config, &database, &whitelist_manager); - (tracker, whitelist_manager) + let (database, in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + + let tracker = initialize_tracker(&config, &database, &whitelist_authorization); + + (tracker, whitelist_authorization, whitelist_manager) } pub fn tracker_persisting_torrents_in_database() -> Tracker { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - initialize_tracker(&config, &database, &whitelist_manager) + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + + initialize_tracker(&config, &database, &whitelist_authorization) } fn sample_info_hash() -> InfoHash { @@ -1637,24 +1616,24 @@ mod tests { #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { - let (tracker, whitelist_manager) = whitelisted_tracker(); + let (tracker, _whitelist_authorization, whitelist_manager) = whitelisted_tracker(); let info_hash = sample_info_hash(); let result = whitelist_manager.add_torrent_to_whitelist(&info_hash).await; assert!(result.is_ok()); - let result = tracker.authorize(&info_hash).await; + let result = tracker.whitelist_authorization.authorize(&info_hash).await; assert!(result.is_ok()); } #[tokio::test] async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { - let (tracker, _whitelist_manager) = whitelisted_tracker(); + let (tracker, _whitelist_authorization, _whitelist_manager) = whitelisted_tracker(); let info_hash = sample_info_hash(); - let result = tracker.authorize(&info_hash).await; + let result = tracker.whitelist_authorization.authorize(&info_hash).await; assert!(result.is_err()); } } @@ -1669,7 +1648,7 @@ mod tests { #[tokio::test] async fn it_should_add_a_torrent_to_the_whitelist() { - let (_tracker, whitelist_manager) = whitelisted_tracker(); + let (_tracker, _whitelist_authorization, whitelist_manager) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1680,7 +1659,7 @@ mod tests { #[tokio::test] async fn it_should_remove_a_torrent_from_the_whitelist() { - let (_tracker, whitelist_manager) = whitelisted_tracker(); + let (_tracker, _whitelist_authorization, whitelist_manager) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1696,7 +1675,7 @@ mod tests { #[tokio::test] async fn it_should_load_the_whitelist_from_the_database() { - let (_tracker, whitelist_manager) = whitelisted_tracker(); + let (_tracker, _whitelist_authorization, whitelist_manager) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1739,7 +1718,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { - let (tracker, _whitelist_manager) = whitelisted_tracker(); + let (tracker, _whitelist_authorization, _whitelist_manager) = whitelisted_tracker(); let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index e0f67305a..611ea24d2 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -14,7 +14,9 @@ use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::Configuration; use super::databases::{self, Database}; +use super::whitelist; use super::whitelist::manager::WhiteListManager; +use super::whitelist::repository::in_memory::InMemoryWhitelist; use super::whitelist::repository::persisted::DatabaseWhitelist; use crate::core::Tracker; @@ -27,9 +29,9 @@ use crate::core::Tracker; pub fn initialize_tracker( config: &Configuration, database: &Arc>, - whitelist_manager: &Arc, + whitelist_authorization: &Arc, ) -> Tracker { - match Tracker::new(&Arc::new(config).core, database, whitelist_manager) { + match Tracker::new(&Arc::new(config).core, database, whitelist_authorization) { Ok(tracker) => tracker, Err(error) => { panic!("{}", error) @@ -51,7 +53,10 @@ pub fn initialize_database(config: &Configuration) -> Arc> { } #[must_use] -pub fn initialize_whitelist(database: Arc>) -> Arc { +pub fn initialize_whitelist_manager( + database: Arc>, + in_memory_whitelist: Arc, +) -> Arc { let database_whitelist = Arc::new(DatabaseWhitelist::new(database)); - Arc::new(WhiteListManager::new(database_whitelist)) + Arc::new(WhiteListManager::new(database_whitelist, in_memory_whitelist)) } diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 1e0403c2a..3567de2a9 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -118,9 +118,9 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; - use crate::core; use crate::core::services::initialize_tracker; use crate::core::services::statistics::{self, get_metrics, TrackerMetrics}; + use crate::core::{self}; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -132,11 +132,10 @@ mod tests { async fn the_statistics_service_should_return_the_tracker_metrics() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_repository = Arc::new(stats_repository); - - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 593d8be8c..457aa54d8 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -142,8 +142,8 @@ mod tests { async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = initialize_tracker(&config, &database, &whitelist_manager); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let tracker = initialize_tracker(&config, &database, &whitelist_authorization); let tracker = Arc::new(tracker); @@ -160,8 +160,8 @@ mod tests { async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -204,8 +204,8 @@ mod tests { async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -216,8 +216,8 @@ mod tests { async fn should_return_a_summarized_info_for_all_torrents() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -241,8 +241,8 @@ mod tests { async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -264,8 +264,8 @@ mod tests { async fn should_allow_using_pagination_in_the_result() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -296,8 +296,8 @@ mod tests { async fn should_return_torrents_ordered_by_info_hash() { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_manager)); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); diff --git a/src/core/whitelist/authorization.rs b/src/core/whitelist/authorization.rs new file mode 100644 index 000000000..74029495f --- /dev/null +++ b/src/core/whitelist/authorization.rs @@ -0,0 +1,59 @@ +use std::panic::Location; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::Core; +use tracing::instrument; + +use super::repository::in_memory::InMemoryWhitelist; +use crate::core::error::Error; + +pub struct Authorization { + /// Core tracker configuration. + config: Core, + + /// The in-memory list of allowed torrents. + in_memory_whitelist: Arc, +} + +impl Authorization { + /// Creates a new authorization instance. + pub fn new(config: &Core, in_memory_whitelist: &Arc) -> Self { + Self { + config: config.clone(), + in_memory_whitelist: in_memory_whitelist.clone(), + } + } + + /// It returns true if the torrent is authorized. + /// + /// # Errors + /// + /// Will return an error if the tracker is running in `listed` mode + /// and the infohash is not whitelisted. + #[instrument(skip(self, info_hash), err)] + pub async fn authorize(&self, info_hash: &InfoHash) -> Result<(), Error> { + if !self.is_listed() { + return Ok(()); + } + + if self.is_info_hash_whitelisted(info_hash).await { + return Ok(()); + } + + Err(Error::TorrentNotWhitelisted { + info_hash: *info_hash, + location: Location::caller(), + }) + } + + /// Returns `true` is the tracker is in listed mode. + fn is_listed(&self) -> bool { + self.config.listed + } + + /// It checks if a torrent is whitelisted. + async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { + self.in_memory_whitelist.contains(info_hash).await + } +} diff --git a/src/core/whitelist/manager.rs b/src/core/whitelist/manager.rs index 832af6892..757053f71 100644 --- a/src/core/whitelist/manager.rs +++ b/src/core/whitelist/manager.rs @@ -9,7 +9,7 @@ use crate::core::databases; /// It handles the list of allowed torrents. Only for listed trackers. pub struct WhiteListManager { /// The in-memory list of allowed torrents. - in_memory_whitelist: InMemoryWhitelist, + in_memory_whitelist: Arc, /// The persisted list of allowed torrents. database_whitelist: Arc, @@ -17,9 +17,9 @@ pub struct WhiteListManager { impl WhiteListManager { #[must_use] - pub fn new(database_whitelist: Arc) -> Self { + pub fn new(database_whitelist: Arc, in_memory_whitelist: Arc) -> Self { Self { - in_memory_whitelist: InMemoryWhitelist::default(), + in_memory_whitelist, database_whitelist, } } diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs index faf83c87b..89c69b761 100644 --- a/src/core/whitelist/mod.rs +++ b/src/core/whitelist/mod.rs @@ -1,2 +1,3 @@ +pub mod authorization; pub mod manager; pub mod repository; diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index cb3789a06..a5c33d5ee 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -32,6 +32,7 @@ use super::v1::context::health_check::handlers::health_check_handler; use super::v1::middlewares::auth::State; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; +use crate::core::whitelist::manager::WhiteListManager; use crate::core::Tracker; use crate::servers::apis::API_LOG_TARGET; use crate::servers::logging::Latency; @@ -39,9 +40,17 @@ use crate::servers::udp::server::banning::BanService; /// Add all API routes to the router. #[allow(clippy::needless_pass_by_value)] -#[instrument(skip(tracker, ban_service, stats_event_sender, stats_repository, access_tokens))] +#[instrument(skip( + tracker, + whitelist_manager, + ban_service, + stats_event_sender, + stats_repository, + access_tokens +))] pub fn router( tracker: Arc, + whitelist_manager: Arc, ban_service: Arc>, stats_event_sender: Arc>>, stats_repository: Arc, @@ -56,6 +65,7 @@ pub fn router( api_url_prefix, router, tracker.clone(), + &whitelist_manager.clone(), ban_service.clone(), stats_event_sender.clone(), stats_repository.clone(), diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index c4fae6ebf..f98770359 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -40,6 +40,7 @@ use tracing::{instrument, Level}; use super::routes::router; use crate::bootstrap::jobs::Started; use crate::core::statistics::repository::Repository; +use crate::core::whitelist::manager::WhiteListManager; use crate::core::{statistics, Tracker}; use crate::servers::apis::API_LOG_TARGET; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; @@ -125,10 +126,12 @@ impl ApiServer { /// # Panics /// /// It would panic if the bound socket address cannot be sent back to this starter. - #[instrument(skip(self, tracker, stats_event_sender, ban_service, stats_repository, form, access_tokens), err, ret(Display, level = Level::INFO))] + #[allow(clippy::too_many_arguments)] + #[instrument(skip(self, tracker, whitelist_manager, stats_event_sender, ban_service, stats_repository, form, access_tokens), err, ret(Display, level = Level::INFO))] pub async fn start( self, tracker: Arc, + whitelist_manager: Arc, stats_event_sender: Arc>>, stats_repository: Arc, ban_service: Arc>, @@ -146,6 +149,7 @@ impl ApiServer { let _task = launcher .start( tracker, + whitelist_manager, ban_service, stats_event_sender, stats_repository, @@ -255,6 +259,7 @@ impl Launcher { #[instrument(skip( self, tracker, + whitelist_manager, ban_service, stats_event_sender, stats_repository, @@ -265,6 +270,7 @@ impl Launcher { pub fn start( &self, tracker: Arc, + whitelist_manager: Arc, ban_service: Arc>, stats_event_sender: Arc>>, stats_repository: Arc, @@ -277,6 +283,7 @@ impl Launcher { let router = router( tracker, + whitelist_manager, ban_service, stats_event_sender, stats_repository, @@ -335,7 +342,9 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::make_rust_tls; - use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; + use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; + use crate::core::whitelist; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -354,8 +363,13 @@ mod tests { initialize_global_services(&cfg); let database = initialize_database(&cfg); - let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_manager)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + &cfg.core, + &in_memory_whitelist.clone(), + )); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); let bind_to = config.bind_address; @@ -372,6 +386,7 @@ mod tests { let started = stopped .start( tracker, + whitelist_manager, stats_event_sender, stats_repository, ban_service, diff --git a/src/servers/apis/v1/context/whitelist/routes.rs b/src/servers/apis/v1/context/whitelist/routes.rs index c58aa7177..34f1393b8 100644 --- a/src/servers/apis/v1/context/whitelist/routes.rs +++ b/src/servers/apis/v1/context/whitelist/routes.rs @@ -11,25 +11,25 @@ use axum::routing::{delete, get, post}; use axum::Router; use super::handlers::{add_torrent_to_whitelist_handler, reload_whitelist_handler, remove_torrent_from_whitelist_handler}; -use crate::core::Tracker; +use crate::core::whitelist::manager::WhiteListManager; /// It adds the routes to the router for the [`whitelist`](crate::servers::apis::v1::context::whitelist) API context. -pub fn add(prefix: &str, router: Router, tracker: &Arc) -> Router { +pub fn add(prefix: &str, router: Router, whitelist_manager: &Arc) -> Router { let prefix = format!("{prefix}/whitelist"); router // Whitelisted torrents .route( &format!("{prefix}/{{info_hash}}"), - post(add_torrent_to_whitelist_handler).with_state(tracker.whitelist_manager.clone()), + post(add_torrent_to_whitelist_handler).with_state(whitelist_manager.clone()), ) .route( &format!("{prefix}/{{info_hash}}"), - delete(remove_torrent_from_whitelist_handler).with_state(tracker.whitelist_manager.clone()), + delete(remove_torrent_from_whitelist_handler).with_state(whitelist_manager.clone()), ) // Whitelist commands .route( &format!("{prefix}/reload"), - get(reload_whitelist_handler).with_state(tracker.whitelist_manager.clone()), + get(reload_whitelist_handler).with_state(whitelist_manager.clone()), ) } diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs index 9fbd5da0e..1954af2e4 100644 --- a/src/servers/apis/v1/routes.rs +++ b/src/servers/apis/v1/routes.rs @@ -7,6 +7,7 @@ use tokio::sync::RwLock; use super::context::{auth_key, stats, torrent, whitelist}; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; +use crate::core::whitelist::manager::WhiteListManager; use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; @@ -15,6 +16,7 @@ pub fn add( prefix: &str, router: Router, tracker: Arc, + whitelist_manager: &Arc, ban_service: Arc>, stats_event_sender: Arc>>, stats_repository: Arc, @@ -30,7 +32,7 @@ pub fn add( stats_event_sender, stats_repository, ); - let router = whitelist::routes::add(&v1_prefix, router, &tracker); + let router = whitelist::routes::add(&v1_prefix, router, whitelist_manager); torrent::routes::add(&v1_prefix, router, tracker) } diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 82b65c2ff..b053628ce 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -11,7 +11,7 @@ use tracing::instrument; use super::v1::routes::router; use crate::bootstrap::jobs::Started; -use crate::core::{statistics, Tracker}; +use crate::core::{statistics, whitelist, Tracker}; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; use crate::servers::logging::STARTED_ON; @@ -42,10 +42,11 @@ pub struct Launcher { } impl Launcher { - #[instrument(skip(self, tracker, stats_event_sender, tx_start, rx_halt))] + #[instrument(skip(self, tracker, whitelist_authorization, stats_event_sender, tx_start, rx_halt))] fn start( &self, tracker: Arc, + whitelist_authorization: Arc, stats_event_sender: Arc>>, tx_start: Sender, rx_halt: Receiver, @@ -66,7 +67,7 @@ impl Launcher { tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{}", address); - let app = router(tracker, stats_event_sender, address); + let app = router(tracker, whitelist_authorization, stats_event_sender, address); let running = Box::pin(async { match tls { @@ -162,6 +163,7 @@ impl HttpServer { pub async fn start( self, tracker: Arc, + whitelist_authorization: Arc, stats_event_sender: Arc>>, form: ServiceRegistrationForm, ) -> Result, Error> { @@ -171,7 +173,7 @@ impl HttpServer { let launcher = self.state.launcher; let task = tokio::spawn(async move { - let server = launcher.start(tracker, stats_event_sender, tx_start, rx_halt); + let server = launcher.start(tracker, whitelist_authorization, stats_event_sender, tx_start, rx_halt); server.await; @@ -244,7 +246,9 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::make_rust_tls; - use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; + use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; + use crate::core::whitelist; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::registar::Registar; @@ -258,8 +262,13 @@ mod tests { initialize_global_services(&cfg); let database = initialize_database(&cfg); - let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_manager)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + &cfg.core, + &in_memory_whitelist.clone(), + )); + let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); let config = &http_trackers[0]; @@ -274,7 +283,7 @@ mod tests { let stopped = HttpServer::new(Launcher::new(bind_to, tls)); let started = stopped - .start(tracker, stats_event_sender, register.give_form()) + .start(tracker, whitelist_authorization, stats_event_sender, register.give_form()) .await .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 24beadbc2..61464f1d5 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -23,7 +23,7 @@ use torrust_tracker_primitives::peer; use crate::core::auth::Key; use crate::core::statistics::event::sender::Sender; -use crate::core::{PeersWanted, Tracker}; +use crate::core::{whitelist, PeersWanted, Tracker}; use crate::servers::http::v1::extractors::announce_request::ExtractRequest; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; @@ -36,13 +36,17 @@ use crate::CurrentClock; #[allow(clippy::unused_async)] #[allow(clippy::type_complexity)] pub async fn handle_without_key( - State(state): State<(Arc, Arc>>)>, + State(state): State<( + Arc, + Arc, + Arc>>, + )>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { tracing::debug!("http announce request: {:#?}", announce_request); - handle(&state.0, &state.1, &announce_request, &client_ip_sources, None).await + handle(&state.0, &state.1, &state.2, &announce_request, &client_ip_sources, None).await } /// It handles the `announce` request when the HTTP tracker requires @@ -50,14 +54,18 @@ pub async fn handle_without_key( #[allow(clippy::unused_async)] #[allow(clippy::type_complexity)] pub async fn handle_with_key( - State(state): State<(Arc, Arc>>)>, + State(state): State<( + Arc, + Arc, + Arc>>, + )>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { tracing::debug!("http announce request: {:#?}", announce_request); - handle(&state.0, &state.1, &announce_request, &client_ip_sources, Some(key)).await + handle(&state.0, &state.1, &state.2, &announce_request, &client_ip_sources, Some(key)).await } /// It handles the `announce` request. @@ -66,6 +74,7 @@ pub async fn handle_with_key( /// `unauthenticated` modes. async fn handle( tracker: &Arc, + whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, @@ -73,6 +82,7 @@ async fn handle( ) -> Response { let announce_data = match handle_announce( tracker, + whitelist_authorization, opt_stats_event_sender, announce_request, client_ip_sources, @@ -94,6 +104,7 @@ async fn handle( async fn handle_announce( tracker: &Arc, + whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, @@ -115,7 +126,7 @@ async fn handle_announce( } // Authorization - match tracker.authorize(&announce_request.info_hash).await { + match whitelist_authorization.authorize(&announce_request.info_hash).await { Ok(()) => (), Err(error) => return Err(responses::error::Error::from(error)), } @@ -198,52 +209,51 @@ pub fn map_to_torrust_event(event: &Option) -> AnnounceEvent { #[cfg(test)] mod tests { + use std::sync::Arc; + use aquatic_udp_protocol::PeerId; use bittorrent_http_protocol::v1::requests::announce::Announce; use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; use crate::core::services::{initialize_tracker, statistics}; use crate::core::statistics::event::sender::Sender; - use crate::core::Tracker; - - fn private_tracker() -> (Tracker, Option>) { - let config = configuration::ephemeral_private(); + use crate::core::{whitelist, Tracker}; - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + type TrackerAndDeps = ( + Arc, + Arc>>, + Arc, + ); - (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) + fn private_tracker() -> TrackerAndDeps { + initialize_tracker_and_deps(&configuration::ephemeral_private()) } - fn whitelisted_tracker() -> (Tracker, Option>) { - let config = configuration::ephemeral_listed(); - - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - - (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) + fn whitelisted_tracker() -> TrackerAndDeps { + initialize_tracker_and_deps(&configuration::ephemeral_listed()) } - fn tracker_on_reverse_proxy() -> (Tracker, Option>) { - let config = configuration::ephemeral_with_reverse_proxy(); - - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - - (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) + fn tracker_on_reverse_proxy() -> TrackerAndDeps { + initialize_tracker_and_deps(&configuration::ephemeral_with_reverse_proxy()) } - fn tracker_not_on_reverse_proxy() -> (Tracker, Option>) { - let config = configuration::ephemeral_without_reverse_proxy(); + fn tracker_not_on_reverse_proxy() -> TrackerAndDeps { + initialize_tracker_and_deps(&configuration::ephemeral_without_reverse_proxy()) + } - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + /// Initialize tracker's dependencies and tracker. + fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + let tracker = Arc::new(initialize_tracker(config, &database, &whitelist_authorization)); - (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) + (tracker, stats_event_sender, whitelist_authorization) } fn sample_announce_request() -> Announce { @@ -286,7 +296,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_missing() { - let (tracker, stats_event_sender) = private_tracker(); + let (tracker, stats_event_sender, whitelist_authorization) = private_tracker(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -295,6 +305,7 @@ mod tests { let response = handle_announce( &tracker, + &whitelist_authorization, &stats_event_sender, &sample_announce_request(), &sample_client_ip_sources(), @@ -311,7 +322,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_invalid() { - let (tracker, stats_event_sender) = private_tracker(); + let (tracker, stats_event_sender, whitelist_authorization) = private_tracker(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -322,6 +333,7 @@ mod tests { let response = handle_announce( &tracker, + &whitelist_authorization, &stats_event_sender, &sample_announce_request(), &sample_client_ip_sources(), @@ -344,7 +356,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_announced_torrent_is_not_whitelisted() { - let (tracker, stats_event_sender) = whitelisted_tracker(); + let (tracker, stats_event_sender, whitelist_authorization) = whitelisted_tracker(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -353,6 +365,7 @@ mod tests { let response = handle_announce( &tracker, + &whitelist_authorization, &stats_event_sender, &announce_request, &sample_client_ip_sources(), @@ -383,7 +396,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let (tracker, stats_event_sender) = tracker_on_reverse_proxy(); + let (tracker, stats_event_sender, whitelist_authorization) = tracker_on_reverse_proxy(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -395,6 +408,7 @@ mod tests { let response = handle_announce( &tracker, + &whitelist_authorization, &stats_event_sender, &sample_announce_request(), &client_ip_sources, @@ -422,7 +436,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let (tracker, stats_event_sender) = tracker_not_on_reverse_proxy(); + let (tracker, stats_event_sender, whitelist_authorization) = tracker_not_on_reverse_proxy(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -434,6 +448,7 @@ mod tests { let response = handle_announce( &tracker, + &whitelist_authorization, &stats_event_sender, &sample_announce_request(), &client_ip_sources, diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index a5cf58129..9c57eda58 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -133,37 +133,49 @@ mod tests { fn private_tracker() -> (Tracker, Option>) { let config = configuration::ephemeral_private(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) + ( + initialize_tracker(&config, &database, &whitelist_authorization), + stats_event_sender, + ) } fn whitelisted_tracker() -> (Tracker, Option>) { let config = configuration::ephemeral_listed(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) + ( + initialize_tracker(&config, &database, &whitelist_authorization), + stats_event_sender, + ) } fn tracker_on_reverse_proxy() -> (Tracker, Option>) { let config = configuration::ephemeral_with_reverse_proxy(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) + ( + initialize_tracker(&config, &database, &whitelist_authorization), + stats_event_sender, + ) } fn tracker_not_on_reverse_proxy() -> (Tracker, Option>) { let config = configuration::ephemeral_without_reverse_proxy(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - (initialize_tracker(&config, &database, &whitelist_manager), stats_event_sender) + ( + initialize_tracker(&config, &database, &whitelist_authorization), + stats_event_sender, + ) } fn sample_scrape_request() -> Scrape { diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 97eb5b95d..d37c55c7a 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -23,7 +23,7 @@ use tracing::{instrument, Level, Span}; use super::handlers::{announce, health_check, scrape}; use crate::core::statistics::event::sender::Sender; -use crate::core::Tracker; +use crate::core::{whitelist, Tracker}; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; use crate::servers::logging::Latency; @@ -32,19 +32,32 @@ use crate::servers::logging::Latency; /// > **NOTICE**: it's added a layer to get the client IP from the connection /// > info. The tracker could use the connection info to get the client IP. #[allow(clippy::needless_pass_by_value)] -#[instrument(skip(tracker, stats_event_sender, server_socket_addr))] -pub fn router(tracker: Arc, stats_event_sender: Arc>>, server_socket_addr: SocketAddr) -> Router { +#[instrument(skip(tracker, whitelist_authorization, stats_event_sender, server_socket_addr))] +pub fn router( + tracker: Arc, + whitelist_authorization: Arc, + stats_event_sender: Arc>>, + server_socket_addr: SocketAddr, +) -> Router { Router::new() // Health check .route("/health_check", get(health_check::handler)) // Announce request .route( "/announce", - get(announce::handle_without_key).with_state((tracker.clone(), stats_event_sender.clone())), + get(announce::handle_without_key).with_state(( + tracker.clone(), + whitelist_authorization.clone(), + stats_event_sender.clone(), + )), ) .route( "/announce/{key}", - get(announce::handle_with_key).with_state((tracker.clone(), stats_event_sender.clone())), + get(announce::handle_with_key).with_state(( + tracker.clone(), + whitelist_authorization.clone(), + stats_event_sender.clone(), + )), ) // Scrape request .route( diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 63a904182..17598904c 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -73,11 +73,11 @@ mod tests { fn public_tracker() -> (Tracker, Arc>>) { let config = configuration::ephemeral_public(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = initialize_tracker(&config, &database, &whitelist_manager); + let tracker = initialize_tracker(&config, &database, &whitelist_authorization); (tracker, stats_event_sender) } @@ -131,9 +131,9 @@ mod tests { fn test_tracker_factory() -> Tracker { let config = configuration::ephemeral(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - Tracker::new(&config.core, &database, &whitelist_manager).unwrap() + Tracker::new(&config.core, &database, &whitelist_authorization).unwrap() } #[tokio::test] diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 56c18cbb3..0a25bccaf 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -87,9 +87,9 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - initialize_tracker(&config, &database, &whitelist_manager) + initialize_tracker(&config, &database, &whitelist_authorization) } fn sample_info_hashes() -> Vec { @@ -115,9 +115,9 @@ mod tests { fn test_tracker_factory() -> Tracker { let config = configuration::ephemeral(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - Tracker::new(&config.core, &database, &whitelist_manager).unwrap() + Tracker::new(&config.core, &database, &whitelist_authorization).unwrap() } mod with_real_data { diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index a7d964391..c01dc2548 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -21,7 +21,7 @@ use super::connection_cookie::{check, make}; use super::server::banning::BanService; use super::RawRequest; use crate::core::statistics::event::sender::Sender; -use crate::core::{statistics, PeersWanted, Tracker}; +use crate::core::{statistics, whitelist, PeersWanted, Tracker}; use crate::servers::udp::error::Error; use crate::servers::udp::{peer_builder, UDP_TRACKER_LOG_TARGET}; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; @@ -54,10 +54,11 @@ impl CookieTimeValues { /// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. -#[instrument(fields(request_id), skip(udp_request, tracker, opt_stats_event_sender, cookie_time_values, ban_service), ret(level = Level::TRACE))] +#[instrument(fields(request_id), skip(udp_request, tracker, whitelist_authorization, opt_stats_event_sender, cookie_time_values, ban_service), ret(level = Level::TRACE))] pub(crate) async fn handle_packet( udp_request: RawRequest, tracker: &Tracker, + whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, local_addr: SocketAddr, cookie_time_values: CookieTimeValues, @@ -76,6 +77,7 @@ pub(crate) async fn handle_packet( request, udp_request.from, tracker, + whitelist_authorization, opt_stats_event_sender, cookie_time_values.clone(), ) @@ -131,11 +133,19 @@ pub(crate) async fn handle_packet( /// # Errors /// /// If a error happens in the `handle_request` function, it will just return the `ServerError`. -#[instrument(skip(request, remote_addr, tracker, opt_stats_event_sender, cookie_time_values))] +#[instrument(skip( + request, + remote_addr, + tracker, + whitelist_authorization, + opt_stats_event_sender, + cookie_time_values +))] pub async fn handle_request( request: Request, remote_addr: SocketAddr, tracker: &Tracker, + whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, cookie_time_values: CookieTimeValues, ) -> Result { @@ -154,6 +164,7 @@ pub async fn handle_request( remote_addr, &announce_request, tracker, + whitelist_authorization, opt_stats_event_sender, cookie_time_values.valid_range, ) @@ -216,11 +227,12 @@ pub async fn handle_connect( /// # Errors /// /// If a error happens in the `handle_announce` function, it will just return the `ServerError`. -#[instrument(fields(transaction_id, connection_id, info_hash), skip(tracker, opt_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id, info_hash), skip(tracker, whitelist_authorization, opt_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_announce( remote_addr: SocketAddr, request: &AnnounceRequest, tracker: &Tracker, + whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { @@ -242,7 +254,7 @@ pub async fn handle_announce( let remote_client_ip = remote_addr.ip(); // Authorization - tracker + whitelist_authorization .authorize(&info_hash) .await .map_err(|e| Error::TrackerError { @@ -462,6 +474,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::ops::Range; + use std::sync::Arc; use aquatic_udp_protocol::{NumberOfBytes, PeerId}; use torrust_tracker_clock::clock::Time; @@ -471,11 +484,21 @@ mod tests { use super::gen_remote_fingerprint; use crate::app_test::initialize_tracker_dependencies; - use crate::core::services::{initialize_tracker, statistics}; + use crate::core::services::{initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::statistics::event::sender::Sender; - use crate::core::Tracker; + use crate::core::whitelist::manager::WhiteListManager; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::core::{whitelist, Tracker}; use crate::CurrentClock; + type TrackerAndDeps = ( + Arc, + Arc>>, + Arc, + Arc, + Arc, + ); + fn tracker_configuration() -> Configuration { default_testing_tracker_configuration() } @@ -484,19 +507,29 @@ mod tests { configuration::ephemeral() } - fn public_tracker() -> (Tracker, Option>) { - initialized_tracker(&configuration::ephemeral_public()) + fn public_tracker() -> TrackerAndDeps { + initialize_tracker_and_deps(&configuration::ephemeral_public()) } - fn whitelisted_tracker() -> (Tracker, Option>) { - initialized_tracker(&configuration::ephemeral_listed()) + fn whitelisted_tracker() -> TrackerAndDeps { + initialize_tracker_and_deps(&configuration::ephemeral_listed()) } - fn initialized_tracker(config: &Configuration) -> (Tracker, Option>) { - let (database, whitelist_manager) = initialize_tracker_dependencies(config); + fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { + let (database, in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + + let tracker = Arc::new(initialize_tracker(config, &database, &whitelist_authorization)); - (initialize_tracker(config, &database, &whitelist_manager), stats_event_sender) + ( + tracker, + stats_event_sender, + in_memory_whitelist, + whitelist_manager, + whitelist_authorization, + ) } fn sample_ipv4_remote_addr() -> SocketAddr { @@ -593,12 +626,14 @@ mod tests { } } - fn test_tracker_factory() -> Tracker { + fn test_tracker_factory() -> (Arc, Arc) { let config = tracker_configuration(); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - Tracker::new(&config.core, &database, &whitelist_manager).unwrap() + let tracker = Arc::new(Tracker::new(&config.core, &database, &whitelist_authorization).unwrap()); + + (tracker, whitelist_authorization) } mod connect_request { @@ -811,7 +846,7 @@ mod tests { }; use mockall::predicate::eq; - use crate::core::{self, statistics}; + use crate::core::{self, statistics, whitelist}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ @@ -822,9 +857,8 @@ mod tests { #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { - let (tracker, stats_event_sender) = public_tracker(); - let tracker = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = + public_tracker(); let client_ip = Ipv4Addr::new(126, 0, 0, 1); let client_port = 8080; @@ -845,6 +879,7 @@ mod tests { remote_addr, &request, &tracker, + &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -863,9 +898,8 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { - let (tracker, stats_event_sender) = public_tracker(); - let tracker = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = + public_tracker(); let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); @@ -877,6 +911,7 @@ mod tests { remote_addr, &request, &tracker, + &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -904,9 +939,8 @@ mod tests { // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): // "Do note that most trackers will only honor the IP address field under limited circumstances." - let (tracker, stats_event_sender) = public_tracker(); - let tracker = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = + public_tracker(); let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -930,6 +964,7 @@ mod tests { remote_addr, &request, &tracker, + &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -957,7 +992,10 @@ mod tests { tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv6); } - async fn announce_a_new_peer_using_ipv4(tracker: Arc) -> Response { + async fn announce_a_new_peer_using_ipv4( + tracker: Arc, + whitelist_authorization: Arc, + ) -> Response { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); @@ -970,6 +1008,7 @@ mod tests { remote_addr, &request, &tracker, + &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -979,12 +1018,12 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { - let (tracker, _stats_event_sender) = public_tracker(); - let tracker = Arc::new(tracker); + let (tracker, _stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = + public_tracker(); add_a_torrent_peer_using_ipv6(&tracker); - let response = announce_a_new_peer_using_ipv4(tracker.clone()).await; + let response = announce_a_new_peer_using_ipv4(tracker.clone(), whitelist_authorization).await; // The response should not contain the peer using IPV6 let peers: Option>> = match response { @@ -1006,12 +1045,13 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(test_tracker_factory()); + let (tracker, whitelist_authorization) = test_tracker_factory(); handle_announce( sample_ipv4_socket_address(), &AnnounceRequestBuilder::default().into(), &tracker, + &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1034,9 +1074,8 @@ mod tests { #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { - let (tracker, stats_event_sender) = public_tracker(); - let tracker = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = + public_tracker(); let client_ip = Ipv4Addr::new(127, 0, 0, 1); let client_port = 8080; @@ -1057,6 +1096,7 @@ mod tests { remote_addr, &request, &tracker, + &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1089,7 +1129,7 @@ mod tests { }; use mockall::predicate::eq; - use crate::core::{self, statistics}; + use crate::core::{self, statistics, whitelist}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ @@ -1100,9 +1140,8 @@ mod tests { #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { - let (tracker, stats_event_sender) = public_tracker(); - let tracker = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = + public_tracker(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -1124,6 +1163,7 @@ mod tests { remote_addr, &request, &tracker, + &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1142,9 +1182,8 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { - let (tracker, stats_event_sender) = public_tracker(); - let tracker = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = + public_tracker(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -1159,6 +1198,7 @@ mod tests { remote_addr, &request, &tracker, + &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1186,9 +1226,8 @@ mod tests { // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): // "Do note that most trackers will only honor the IP address field under limited circumstances." - let (tracker, stats_event_sender) = public_tracker(); - let tracker = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = + public_tracker(); let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -1212,6 +1251,7 @@ mod tests { remote_addr, &request, &tracker, + &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1239,7 +1279,10 @@ mod tests { tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv4); } - async fn announce_a_new_peer_using_ipv6(tracker: Arc) -> Response { + async fn announce_a_new_peer_using_ipv6( + tracker: Arc, + whitelist_authorization: Arc, + ) -> Response { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); @@ -1255,6 +1298,7 @@ mod tests { remote_addr, &request, &tracker, + &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1264,12 +1308,12 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { - let (tracker, _stats_event_sender) = public_tracker(); - let tracker = Arc::new(tracker); + let (tracker, _stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = + public_tracker(); add_a_torrent_peer_using_ipv4(&tracker); - let response = announce_a_new_peer_using_ipv6(tracker.clone()).await; + let response = announce_a_new_peer_using_ipv6(tracker.clone(), whitelist_authorization).await; // The response should not contain the peer using IPV4 let peers: Option>> = match response { @@ -1291,7 +1335,7 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(test_tracker_factory()); + let (tracker, whitelist_authorization) = test_tracker_factory(); let remote_addr = sample_ipv6_remote_addr(); @@ -1303,6 +1347,7 @@ mod tests { remote_addr, &announce_request, &tracker, + &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1331,7 +1376,7 @@ mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - let (database, whitelist_manager) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock @@ -1342,7 +1387,7 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(core::Tracker::new(&config.core, &database, &whitelist_manager).unwrap()); + let tracker = Arc::new(core::Tracker::new(&config.core, &database, &whitelist_authorization).unwrap()); let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); @@ -1368,6 +1413,7 @@ mod tests { remote_addr, &request, &tracker, + &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1419,9 +1465,8 @@ mod tests { #[tokio::test] async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { - let (tracker, stats_event_sender) = public_tracker(); - let tracker = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, _whitelist_authorization) = + public_tracker(); let remote_addr = sample_ipv4_remote_addr(); @@ -1507,8 +1552,6 @@ mod tests { } mod with_a_public_tracker { - use std::sync::Arc; - use aquatic_udp_protocol::{NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; use crate::servers::udp::handlers::tests::public_tracker; @@ -1516,8 +1559,8 @@ mod tests { #[tokio::test] async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { - let (tracker, _stats_event_sender) = public_tracker(); - let tracker = Arc::new(tracker); + let (tracker, _stats_event_sender, _in_memory_whitelist, _whitelist_manager, _whitelist_authorization) = + public_tracker(); let torrent_stats = match_scrape_response(add_a_sample_seeder_and_scrape(tracker.clone()).await); @@ -1532,8 +1575,6 @@ mod tests { } mod with_a_whitelisted_tracker { - use std::sync::Arc; - use aquatic_udp_protocol::{InfoHash, NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; use crate::servers::udp::handlers::handle_scrape; @@ -1544,19 +1585,15 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { - let (tracker, stats_event_sender) = whitelisted_tracker(); - let tracker = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, stats_event_sender, in_memory_whitelist, _whitelist_manager, _whitelist_authorization) = + whitelisted_tracker(); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); add_a_seeder(tracker.clone(), &remote_addr, &info_hash).await; - tracker - .whitelist_manager - .add_torrent_to_memory_whitelist(&info_hash.0.into()) - .await; + in_memory_whitelist.add(&info_hash.0.into()).await; let request = build_scrape_request(&remote_addr, &info_hash); @@ -1584,9 +1621,8 @@ mod tests { #[tokio::test] async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { - let (tracker, stats_event_sender) = whitelisted_tracker(); - let tracker = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, _whitelist_authorization) = + whitelisted_tracker(); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -1650,7 +1686,8 @@ mod tests { Arc::new(Some(Box::new(stats_event_sender_mock))); let remote_addr = sample_ipv4_remote_addr(); - let tracker = Arc::new(test_tracker_factory()); + + let (tracker, _whitelist_authorization) = test_tracker_factory(); handle_scrape( remote_addr, @@ -1689,7 +1726,8 @@ mod tests { Arc::new(Some(Box::new(stats_event_sender_mock))); let remote_addr = sample_ipv6_remote_addr(); - let tracker = Arc::new(test_tracker_factory()); + + let (tracker, _whitelist_authorization) = test_tracker_factory(); handle_scrape( remote_addr, diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index d71ffcfd1..bb5c30d44 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -14,7 +14,7 @@ use super::banning::BanService; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; use crate::core::statistics::event::sender::Sender; -use crate::core::{statistics, Tracker}; +use crate::core::{statistics, whitelist, Tracker}; use crate::servers::logging::STARTED_ON; use crate::servers::registar::ServiceHealthCheckJob; use crate::servers::signals::{shutdown_signal_with_message, Halted}; @@ -40,10 +40,19 @@ impl Launcher { /// It panics if unable to bind to udp socket, and get the address from the udp socket. /// It panics if unable to send address of socket. /// It panics if the udp server is loaded when the tracker is private. - /// - #[instrument(skip(tracker, opt_stats_event_sender, ban_service, bind_to, tx_start, rx_halt))] + #[allow(clippy::too_many_arguments)] + #[instrument(skip( + tracker, + whitelist_authorization, + opt_stats_event_sender, + ban_service, + bind_to, + tx_start, + rx_halt + ))] pub async fn run_with_graceful_shutdown( tracker: Arc, + whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, ban_service: Arc>, bind_to: SocketAddr, @@ -86,6 +95,7 @@ impl Launcher { let () = Self::run_udp_server_main( receiver, tracker.clone(), + whitelist_authorization.clone(), opt_stats_event_sender.clone(), ban_service.clone(), cookie_lifetime, @@ -127,10 +137,11 @@ impl Launcher { ServiceHealthCheckJob::new(binding, info, job) } - #[instrument(skip(receiver, tracker, opt_stats_event_sender, ban_service))] + #[instrument(skip(receiver, tracker, whitelist_authorization, opt_stats_event_sender, ban_service))] async fn run_udp_server_main( mut receiver: Receiver, tracker: Arc, + whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, ban_service: Arc>, cookie_lifetime: Duration, @@ -201,6 +212,7 @@ impl Launcher { let processor = Processor::new( receiver.socket.clone(), tracker.clone(), + whitelist_authorization.clone(), opt_stats_event_sender.clone(), cookie_lifetime, ); diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index b5da9d326..f47e0b1db 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -64,7 +64,9 @@ mod tests { use super::spawner::Spawner; use super::Server; use crate::bootstrap::app::initialize_global_services; - use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist, statistics}; + use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; + use crate::core::whitelist; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -80,8 +82,13 @@ mod tests { initialize_global_services(&cfg); let database = initialize_database(&cfg); - let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_manager)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + &cfg.core, + &in_memory_whitelist.clone(), + )); + let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; @@ -93,6 +100,7 @@ mod tests { let started = stopped .start( tracker, + whitelist_authorization, stats_event_sender, ban_service, register.give_form(), @@ -119,8 +127,13 @@ mod tests { initialize_global_services(&cfg); let database = initialize_database(&cfg); - let whitelist_manager = initialize_whitelist(database.clone()); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_manager)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + &cfg.core, + &in_memory_whitelist.clone(), + )); + + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; @@ -131,6 +144,7 @@ mod tests { let started = stopped .start( tracker, + whitelist_authorization, stats_event_sender, ban_service, register.give_form(), diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 2ef7cc482..fe3666c1d 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -12,13 +12,14 @@ use super::banning::BanService; use super::bound_socket::BoundSocket; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::event::UdpResponseKind; -use crate::core::{statistics, Tracker}; +use crate::core::{statistics, whitelist, Tracker}; use crate::servers::udp::handlers::CookieTimeValues; use crate::servers::udp::{handlers, RawRequest}; pub struct Processor { socket: Arc, tracker: Arc, + whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, cookie_lifetime: f64, } @@ -27,12 +28,14 @@ impl Processor { pub fn new( socket: Arc, tracker: Arc, + whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, cookie_lifetime: f64, ) -> Self { Self { socket, tracker, + whitelist_authorization, opt_stats_event_sender, cookie_lifetime, } @@ -47,6 +50,7 @@ impl Processor { let response = handlers::handle_packet( request, &self.tracker, + &self.whitelist_authorization, &self.opt_stats_event_sender, self.socket.address(), CookieTimeValues::new(self.cookie_lifetime), diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index 5d7a97877..aecba39ec 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -12,7 +12,7 @@ use super::banning::BanService; use super::launcher::Launcher; use crate::bootstrap::jobs::Started; use crate::core::statistics::event::sender::Sender; -use crate::core::Tracker; +use crate::core::{whitelist, Tracker}; use crate::servers::signals::Halted; #[derive(Constructor, Copy, Clone, Debug, Display)] @@ -27,9 +27,11 @@ impl Spawner { /// # Panics /// /// It would panic if unable to resolve the `local_addr` from the supplied ´socket´. + #[allow(clippy::too_many_arguments)] pub fn spawn_launcher( &self, tracker: Arc, + whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, ban_service: Arc>, cookie_lifetime: Duration, @@ -41,6 +43,7 @@ impl Spawner { tokio::spawn(async move { Launcher::run_with_graceful_shutdown( tracker, + whitelist_authorization, opt_stats_event_sender, ban_service, spawner.bind_to, diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index 5cdca5a7d..9a01b5c6d 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -14,7 +14,7 @@ use super::spawner::Spawner; use super::{Server, UdpError}; use crate::bootstrap::jobs::Started; use crate::core::statistics::event::sender::Sender; -use crate::core::Tracker; +use crate::core::{whitelist, Tracker}; use crate::servers::registar::{ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::Halted; use crate::servers::udp::server::launcher::Launcher; @@ -65,10 +65,11 @@ impl Server { /// /// It panics if unable to receive the bound socket address from service. /// - #[instrument(skip(self, tracker, opt_stats_event_sender, ban_service, form), err, ret(Display, level = Level::INFO))] + #[instrument(skip(self, tracker, whitelist_authorization, opt_stats_event_sender, ban_service, form), err, ret(Display, level = Level::INFO))] pub async fn start( self, tracker: Arc, + whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, ban_service: Arc>, form: ServiceRegistrationForm, @@ -82,6 +83,7 @@ impl Server { // May need to wrap in a task to about a tokio bug. let task = self.state.spawner.spawn_launcher( tracker, + whitelist_authorization, opt_stats_event_sender, ban_service, cookie_lifetime, diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index cf997eb7c..a9628f053 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -82,6 +82,7 @@ impl Environment { .server .start( self.tracker, + self.whitelist_manager, self.stats_event_sender, self.stats_repository, self.ban_service, diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index d68924e07..160cb49f8 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -8,7 +8,7 @@ use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; -use torrust_tracker_lib::core::Tracker; +use torrust_tracker_lib::core::{whitelist, Tracker}; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; @@ -18,6 +18,7 @@ pub struct Environment { pub tracker: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, + pub whitelist_authorization: Arc, pub whitelist_manager: Arc, pub registar: Registar, pub server: HttpServer, @@ -55,6 +56,7 @@ impl Environment { tracker: app_container.tracker.clone(), stats_event_sender: app_container.stats_event_sender.clone(), stats_repository: app_container.stats_repository.clone(), + whitelist_authorization: app_container.whitelist_authorization.clone(), whitelist_manager: app_container.whitelist_manager.clone(), registar: Registar::default(), server, @@ -66,13 +68,19 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + whitelist_authorization: self.whitelist_authorization.clone(), stats_event_sender: self.stats_event_sender.clone(), stats_repository: self.stats_repository.clone(), whitelist_manager: self.whitelist_manager.clone(), registar: self.registar.clone(), server: self .server - .start(self.tracker, self.stats_event_sender, self.registar.give_form()) + .start( + self.tracker, + self.whitelist_authorization, + self.stats_event_sender, + self.registar.give_form(), + ) .await .unwrap(), } @@ -88,6 +96,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + whitelist_authorization: self.whitelist_authorization, stats_event_sender: self.stats_event_sender, stats_repository: self.stats_repository, whitelist_manager: self.whitelist_manager, diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 81e626e1c..43778ef6e 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -7,7 +7,7 @@ use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; -use torrust_tracker_lib::core::Tracker; +use torrust_tracker_lib::core::{whitelist, Tracker}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::banning::BanService; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; @@ -21,6 +21,7 @@ where { pub config: Arc, pub tracker: Arc, + pub whitelist_authorization: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub ban_service: Arc>, @@ -57,6 +58,7 @@ impl Environment { Self { config, tracker: app_container.tracker.clone(), + whitelist_authorization: app_container.whitelist_authorization.clone(), stats_event_sender: app_container.stats_event_sender.clone(), stats_repository: app_container.stats_repository.clone(), ban_service: app_container.ban_service.clone(), @@ -71,6 +73,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + whitelist_authorization: self.whitelist_authorization.clone(), stats_event_sender: self.stats_event_sender.clone(), stats_repository: self.stats_repository.clone(), ban_service: self.ban_service.clone(), @@ -79,6 +82,7 @@ impl Environment { .server .start( self.tracker, + self.whitelist_authorization, self.stats_event_sender, self.ban_service, self.registar.give_form(), @@ -106,6 +110,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + whitelist_authorization: self.whitelist_authorization, stats_event_sender: self.stats_event_sender, stats_repository: self.stats_repository, ban_service: self.ban_service, From 88560ce4748c6af347f7380ab452e2953196b3c8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 20 Jan 2025 15:29:42 +0000 Subject: [PATCH 0606/1297] refactor: [#1191] create dir for mod We will add more mods inside. This is part of a bigger refactor. --- src/core/{auth.rs => auth/mod.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/core/{auth.rs => auth/mod.rs} (100%) diff --git a/src/core/auth.rs b/src/core/auth/mod.rs similarity index 100% rename from src/core/auth.rs rename to src/core/auth/mod.rs From f216b052f967c9b365603c951237c0182a6e81db Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 20 Jan 2025 16:17:10 +0000 Subject: [PATCH 0607/1297] refactor: [#1191] extract mod auth::key --- src/core/auth/key.rs | 348 ++++++++++++++++++++++++++++++++++++++++++ src/core/auth/mod.rs | 349 +------------------------------------------ src/core/error.rs | 3 +- src/core/mod.rs | 6 +- 4 files changed, 356 insertions(+), 350 deletions(-) create mode 100644 src/core/auth/key.rs diff --git a/src/core/auth/key.rs b/src/core/auth/key.rs new file mode 100644 index 000000000..f0adf5946 --- /dev/null +++ b/src/core/auth/key.rs @@ -0,0 +1,348 @@ +//! Tracker authentication services and structs. +//! +//! This module contains functions to handle tracker keys. +//! Tracker keys are tokens used to authenticate the tracker clients when the tracker runs +//! in `private` or `private_listed` modes. +//! +//! There are services to [`generate_key`] and [`verify_key_expiration`] authentication keys. +//! +//! Authentication keys are used only by [`HTTP`](crate::servers::http) trackers. All keys have an expiration time, that means +//! they are only valid during a period of time. After that time the expiring key will no longer be valid. +//! +//! Keys are stored in this struct: +//! +//! ```rust,no_run +//! use torrust_tracker_lib::core::auth::Key; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; +//! +//! pub struct PeerKey { +//! /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` +//! pub key: Key, +//! +//! /// Timestamp, the key will be no longer valid after this timestamp. +//! /// If `None` the keys will not expire (permanent key). +//! pub valid_until: Option, +//! } +//! ``` +//! +//! You can generate a new key valid for `9999` seconds and `0` nanoseconds from the current time with the following: +//! +//! ```rust,no_run +//! use torrust_tracker_lib::core::auth; +//! use std::time::Duration; +//! +//! let expiring_key = auth::key::generate_key(Some(Duration::new(9999, 0))); +//! +//! // And you can later verify it with: +//! +//! assert!(auth::key::verify_key_expiration(&expiring_key).is_ok()); +//! ``` + +use std::panic::Location; +use std::str::FromStr; +use std::sync::Arc; +use std::time::Duration; + +use derive_more::Display; +use rand::distributions::Alphanumeric; +use rand::{thread_rng, Rng}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; +use torrust_tracker_located_error::{DynError, LocatedError}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; +use crate::CurrentClock; + +/// It generates a new permanent random key [`PeerKey`]. +#[must_use] +pub fn generate_permanent_key() -> PeerKey { + generate_key(None) +} + +/// It generates a new random 32-char authentication [`PeerKey`]. +/// +/// It can be an expiring or permanent key. +/// +/// # Panics +/// +/// It would panic if the `lifetime: Duration` + Duration is more than `Duration::MAX`. +/// +/// # Arguments +/// +/// * `lifetime`: if `None` the key will be permanent. +#[must_use] +pub fn generate_key(lifetime: Option) -> PeerKey { + let random_id: String = thread_rng() + .sample_iter(&Alphanumeric) + .take(AUTH_KEY_LENGTH) + .map(char::from) + .collect(); + + if let Some(lifetime) = lifetime { + tracing::debug!("Generated key: {}, valid for: {:?} seconds", random_id, lifetime); + + PeerKey { + key: random_id.parse::().unwrap(), + valid_until: Some(CurrentClock::now_add(&lifetime).unwrap()), + } + } else { + tracing::debug!("Generated key: {}, permanent", random_id); + + PeerKey { + key: random_id.parse::().unwrap(), + valid_until: None, + } + } +} + +/// It verifies an [`PeerKey`]. It checks if the expiration date has passed. +/// Permanent keys without duration (`None`) do not expire. +/// +/// # Errors +/// +/// Will return: +/// +/// - `Error::KeyExpired` if `auth_key.valid_until` is past the `current_time`. +/// - `Error::KeyInvalid` if `auth_key.valid_until` is past the `None`. +pub fn verify_key_expiration(auth_key: &PeerKey) -> Result<(), Error> { + let current_time: DurationSinceUnixEpoch = CurrentClock::now(); + + match auth_key.valid_until { + Some(valid_until) => { + if valid_until < current_time { + Err(Error::KeyExpired { + location: Location::caller(), + }) + } else { + Ok(()) + } + } + None => Ok(()), // Permanent key + } +} + +/// An authentication key which can potentially have an expiration time. +/// After that time is will automatically become invalid. +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] +pub struct PeerKey { + /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` + pub key: Key, + + /// Timestamp, the key will be no longer valid after this timestamp. + /// If `None` the keys will not expire (permanent key). + pub valid_until: Option, +} + +impl std::fmt::Display for PeerKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.expiry_time() { + Some(expire_time) => write!(f, "key: `{}`, valid until `{}`", self.key, expire_time), + None => write!(f, "key: `{}`, permanent", self.key), + } + } +} + +impl PeerKey { + #[must_use] + pub fn key(&self) -> Key { + self.key.clone() + } + + /// It returns the expiry time. For example, for the starting time for Unix Epoch + /// (timestamp 0) it will return a `DateTime` whose string representation is + /// `1970-01-01 00:00:00 UTC`. + /// + /// # Panics + /// + /// Will panic when the key timestamp overflows the internal i64 type. + /// (this will naturally happen in 292.5 billion years) + #[must_use] + pub fn expiry_time(&self) -> Option> { + self.valid_until.map(convert_from_timestamp_to_datetime_utc) + } +} + +/// A token used for authentication. +/// +/// - It contains only ascii alphanumeric chars: lower and uppercase letters and +/// numbers. +/// - It's a 32-char string. +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Display, Hash)] +pub struct Key(String); + +impl Key { + /// # Errors + /// + /// Will return an error is the string represents an invalid key. + /// Valid keys can only contain 32 chars including 0-9, a-z and A-Z. + pub fn new(value: &str) -> Result { + if value.len() != AUTH_KEY_LENGTH { + return Err(ParseKeyError::InvalidKeyLength); + } + + if !value.chars().all(|c| c.is_ascii_alphanumeric()) { + return Err(ParseKeyError::InvalidChars); + } + + Ok(Self(value.to_owned())) + } + + #[must_use] + pub fn value(&self) -> &str { + &self.0 + } +} + +/// Error returned when a key cannot be parsed from a string. +/// +/// ```text +/// use torrust_tracker_lib::core::auth::Key; +/// use std::str::FromStr; +/// +/// let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; +/// let key = Key::from_str(key_string); +/// +/// assert!(key.is_ok()); +/// assert_eq!(key.unwrap().to_string(), key_string); +/// ``` +/// +/// If the string does not contains a valid key, the parser function will return +/// this error. +#[derive(Debug, Error)] +pub enum ParseKeyError { + #[error("Invalid key length. Key must be have 32 chars")] + InvalidKeyLength, + #[error("Invalid chars for key. Key can only alphanumeric chars (0-9, a-z, A-Z)")] + InvalidChars, +} + +impl FromStr for Key { + type Err = ParseKeyError; + + fn from_str(s: &str) -> Result { + Key::new(s)?; + Ok(Self(s.to_string())) + } +} + +/// Verification error. Error returned when an [`PeerKey`] cannot be +/// verified with the (`crate::core::auth::verify_key`) function. +#[derive(Debug, Error)] +#[allow(dead_code)] +pub enum Error { + #[error("Key could not be verified: {source}")] + KeyVerificationError { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + }, + #[error("Failed to read key: {key}, {location}")] + UnableToReadKey { + location: &'static Location<'static>, + key: Box, + }, + #[error("Key has expired, {location}")] + KeyExpired { location: &'static Location<'static> }, +} + +impl From for Error { + fn from(e: r2d2_sqlite::rusqlite::Error) -> Self { + Error::KeyVerificationError { + source: (Arc::new(e) as DynError).into(), + } + } +} + +#[cfg(test)] +mod tests { + + mod key { + use std::str::FromStr; + + use crate::core::auth::Key; + + #[test] + fn should_be_parsed_from_an_string() { + let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; + let key = Key::from_str(key_string); + + assert!(key.is_ok()); + assert_eq!(key.unwrap().to_string(), key_string); + } + + #[test] + fn length_should_be_32() { + let key = Key::new(""); + assert!(key.is_err()); + + let string_longer_than_32 = "012345678901234567890123456789012"; // DevSkim: ignore DS173237 + let key = Key::new(string_longer_than_32); + assert!(key.is_err()); + } + + #[test] + fn should_only_include_alphanumeric_chars() { + let key = Key::new("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); + assert!(key.is_err()); + } + } + + mod expiring_auth_key { + use std::str::FromStr; + use std::time::Duration; + + use torrust_tracker_clock::clock; + use torrust_tracker_clock::clock::stopped::Stopped as _; + + use crate::core::auth; + + #[test] + fn should_be_parsed_from_an_string() { + let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; + let auth_key = auth::Key::from_str(key_string); + + assert!(auth_key.is_ok()); + assert_eq!(auth_key.unwrap().to_string(), key_string); + } + + #[test] + fn should_be_displayed() { + // Set the time to the current time. + clock::Stopped::local_set_to_unix_epoch(); + + let expiring_key = auth::key::generate_key(Some(Duration::from_secs(0))); + + assert_eq!( + expiring_key.to_string(), + format!("key: `{}`, valid until `1970-01-01 00:00:00 UTC`", expiring_key.key) // cspell:disable-line + ); + } + + #[test] + fn should_be_generated_with_a_expiration_time() { + let expiring_key = auth::key::generate_key(Some(Duration::new(9999, 0))); + + assert!(auth::key::verify_key_expiration(&expiring_key).is_ok()); + } + + #[test] + fn should_be_generate_and_verified() { + // Set the time to the current time. + clock::Stopped::local_set_to_system_time_now(); + + // Make key that is valid for 19 seconds. + let expiring_key = auth::key::generate_key(Some(Duration::from_secs(19))); + + // Mock the time has passed 10 sec. + clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); + + assert!(auth::key::verify_key_expiration(&expiring_key).is_ok()); + + // Mock the time has passed another 10 sec. + clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); + + assert!(auth::key::verify_key_expiration(&expiring_key).is_err()); + } + } +} diff --git a/src/core/auth/mod.rs b/src/core/auth/mod.rs index c92a4723d..d0f72340d 100644 --- a/src/core/auth/mod.rs +++ b/src/core/auth/mod.rs @@ -1,346 +1,5 @@ -//! Tracker authentication services and structs. -//! -//! This module contains functions to handle tracker keys. -//! Tracker keys are tokens used to authenticate the tracker clients when the tracker runs -//! in `private` or `private_listed` modes. -//! -//! There are services to [`generate_key`] and [`verify_key_expiration`] authentication keys. -//! -//! Authentication keys are used only by [`HTTP`](crate::servers::http) trackers. All keys have an expiration time, that means -//! they are only valid during a period of time. After that time the expiring key will no longer be valid. -//! -//! Keys are stored in this struct: -//! -//! ```rust,no_run -//! use torrust_tracker_lib::core::auth::Key; -//! use torrust_tracker_primitives::DurationSinceUnixEpoch; -//! -//! pub struct ExpiringKey { -//! /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` -//! pub key: Key, -//! /// Timestamp, the key will be no longer valid after this timestamp -//! pub valid_until: Option, -//! } -//! ``` -//! -//! You can generate a new key valid for `9999` seconds and `0` nanoseconds from the current time with the following: -//! -//! ```rust,no_run -//! use torrust_tracker_lib::core::auth; -//! use std::time::Duration; -//! -//! let expiring_key = auth::generate_key(Some(Duration::new(9999, 0))); -//! -//! // And you can later verify it with: -//! -//! assert!(auth::verify_key_expiration(&expiring_key).is_ok()); -//! ``` +pub mod key; -use std::panic::Location; -use std::str::FromStr; -use std::sync::Arc; -use std::time::Duration; - -use derive_more::Display; -use rand::distributions::Alphanumeric; -use rand::{thread_rng, Rng}; -use serde::{Deserialize, Serialize}; -use thiserror::Error; -use torrust_tracker_clock::clock::Time; -use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; -use torrust_tracker_located_error::{DynError, LocatedError}; -use torrust_tracker_primitives::DurationSinceUnixEpoch; - -use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; -use crate::CurrentClock; - -/// It generates a new permanent random key [`PeerKey`]. -#[must_use] -pub fn generate_permanent_key() -> PeerKey { - generate_key(None) -} - -/// It generates a new random 32-char authentication [`PeerKey`]. -/// -/// It can be an expiring or permanent key. -/// -/// # Panics -/// -/// It would panic if the `lifetime: Duration` + Duration is more than `Duration::MAX`. -/// -/// # Arguments -/// -/// * `lifetime`: if `None` the key will be permanent. -#[must_use] -pub fn generate_key(lifetime: Option) -> PeerKey { - let random_id: String = thread_rng() - .sample_iter(&Alphanumeric) - .take(AUTH_KEY_LENGTH) - .map(char::from) - .collect(); - - if let Some(lifetime) = lifetime { - tracing::debug!("Generated key: {}, valid for: {:?} seconds", random_id, lifetime); - - PeerKey { - key: random_id.parse::().unwrap(), - valid_until: Some(CurrentClock::now_add(&lifetime).unwrap()), - } - } else { - tracing::debug!("Generated key: {}, permanent", random_id); - - PeerKey { - key: random_id.parse::().unwrap(), - valid_until: None, - } - } -} - -/// It verifies an [`PeerKey`]. It checks if the expiration date has passed. -/// Permanent keys without duration (`None`) do not expire. -/// -/// # Errors -/// -/// Will return: -/// -/// - `Error::KeyExpired` if `auth_key.valid_until` is past the `current_time`. -/// - `Error::KeyInvalid` if `auth_key.valid_until` is past the `None`. -pub fn verify_key_expiration(auth_key: &PeerKey) -> Result<(), Error> { - let current_time: DurationSinceUnixEpoch = CurrentClock::now(); - - match auth_key.valid_until { - Some(valid_until) => { - if valid_until < current_time { - Err(Error::KeyExpired { - location: Location::caller(), - }) - } else { - Ok(()) - } - } - None => Ok(()), // Permanent key - } -} - -/// An authentication key which can potentially have an expiration time. -/// After that time is will automatically become invalid. -#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] -pub struct PeerKey { - /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` - pub key: Key, - - /// Timestamp, the key will be no longer valid after this timestamp. - /// If `None` the keys will not expire (permanent key). - pub valid_until: Option, -} - -impl std::fmt::Display for PeerKey { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self.expiry_time() { - Some(expire_time) => write!(f, "key: `{}`, valid until `{}`", self.key, expire_time), - None => write!(f, "key: `{}`, permanent", self.key), - } - } -} - -impl PeerKey { - #[must_use] - pub fn key(&self) -> Key { - self.key.clone() - } - - /// It returns the expiry time. For example, for the starting time for Unix Epoch - /// (timestamp 0) it will return a `DateTime` whose string representation is - /// `1970-01-01 00:00:00 UTC`. - /// - /// # Panics - /// - /// Will panic when the key timestamp overflows the internal i64 type. - /// (this will naturally happen in 292.5 billion years) - #[must_use] - pub fn expiry_time(&self) -> Option> { - self.valid_until.map(convert_from_timestamp_to_datetime_utc) - } -} - -/// A token used for authentication. -/// -/// - It contains only ascii alphanumeric chars: lower and uppercase letters and -/// numbers. -/// - It's a 32-char string. -#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Display, Hash)] -pub struct Key(String); - -impl Key { - /// # Errors - /// - /// Will return an error is the string represents an invalid key. - /// Valid keys can only contain 32 chars including 0-9, a-z and A-Z. - pub fn new(value: &str) -> Result { - if value.len() != AUTH_KEY_LENGTH { - return Err(ParseKeyError::InvalidKeyLength); - } - - if !value.chars().all(|c| c.is_ascii_alphanumeric()) { - return Err(ParseKeyError::InvalidChars); - } - - Ok(Self(value.to_owned())) - } - - #[must_use] - pub fn value(&self) -> &str { - &self.0 - } -} - -/// Error returned when a key cannot be parsed from a string. -/// -/// ```text -/// use torrust_tracker_lib::core::auth::Key; -/// use std::str::FromStr; -/// -/// let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; -/// let key = Key::from_str(key_string); -/// -/// assert!(key.is_ok()); -/// assert_eq!(key.unwrap().to_string(), key_string); -/// ``` -/// -/// If the string does not contains a valid key, the parser function will return -/// this error. -#[derive(Debug, Error)] -pub enum ParseKeyError { - #[error("Invalid key length. Key must be have 32 chars")] - InvalidKeyLength, - #[error("Invalid chars for key. Key can only alphanumeric chars (0-9, a-z, A-Z)")] - InvalidChars, -} - -impl FromStr for Key { - type Err = ParseKeyError; - - fn from_str(s: &str) -> Result { - Key::new(s)?; - Ok(Self(s.to_string())) - } -} - -/// Verification error. Error returned when an [`PeerKey`] cannot be -/// verified with the (`crate::core::auth::verify_key`) function. -#[derive(Debug, Error)] -#[allow(dead_code)] -pub enum Error { - #[error("Key could not be verified: {source}")] - KeyVerificationError { - source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - }, - #[error("Failed to read key: {key}, {location}")] - UnableToReadKey { - location: &'static Location<'static>, - key: Box, - }, - #[error("Key has expired, {location}")] - KeyExpired { location: &'static Location<'static> }, -} - -impl From for Error { - fn from(e: r2d2_sqlite::rusqlite::Error) -> Self { - Error::KeyVerificationError { - source: (Arc::new(e) as DynError).into(), - } - } -} - -#[cfg(test)] -mod tests { - - mod key { - use std::str::FromStr; - - use crate::core::auth::Key; - - #[test] - fn should_be_parsed_from_an_string() { - let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; - let key = Key::from_str(key_string); - - assert!(key.is_ok()); - assert_eq!(key.unwrap().to_string(), key_string); - } - - #[test] - fn length_should_be_32() { - let key = Key::new(""); - assert!(key.is_err()); - - let string_longer_than_32 = "012345678901234567890123456789012"; // DevSkim: ignore DS173237 - let key = Key::new(string_longer_than_32); - assert!(key.is_err()); - } - - #[test] - fn should_only_include_alphanumeric_chars() { - let key = Key::new("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); - assert!(key.is_err()); - } - } - - mod expiring_auth_key { - use std::str::FromStr; - use std::time::Duration; - - use torrust_tracker_clock::clock; - use torrust_tracker_clock::clock::stopped::Stopped as _; - - use crate::core::auth; - - #[test] - fn should_be_parsed_from_an_string() { - let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; - let auth_key = auth::Key::from_str(key_string); - - assert!(auth_key.is_ok()); - assert_eq!(auth_key.unwrap().to_string(), key_string); - } - - #[test] - fn should_be_displayed() { - // Set the time to the current time. - clock::Stopped::local_set_to_unix_epoch(); - - let expiring_key = auth::generate_key(Some(Duration::from_secs(0))); - - assert_eq!( - expiring_key.to_string(), - format!("key: `{}`, valid until `1970-01-01 00:00:00 UTC`", expiring_key.key) // cspell:disable-line - ); - } - - #[test] - fn should_be_generated_with_a_expiration_time() { - let expiring_key = auth::generate_key(Some(Duration::new(9999, 0))); - - assert!(auth::verify_key_expiration(&expiring_key).is_ok()); - } - - #[test] - fn should_be_generate_and_verified() { - // Set the time to the current time. - clock::Stopped::local_set_to_system_time_now(); - - // Make key that is valid for 19 seconds. - let expiring_key = auth::generate_key(Some(Duration::from_secs(19))); - - // Mock the time has passed 10 sec. - clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); - - assert!(auth::verify_key_expiration(&expiring_key).is_ok()); - - // Mock the time has passed another 10 sec. - clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); - - assert!(auth::verify_key_expiration(&expiring_key).is_err()); - } - } -} +pub type PeerKey = key::PeerKey; +pub type Key = key::Key; +pub type Error = key::Error; diff --git a/src/core/error.rs b/src/core/error.rs index f0de7df40..f0e4b849e 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -12,8 +12,7 @@ use bittorrent_http_protocol::v1::responses; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_located_error::LocatedError; -use super::auth::ParseKeyError; -use super::databases; +use super::{auth::key::ParseKeyError, databases}; /// Authentication or authorization error returned by the core `Tracker` #[derive(thiserror::Error, Debug, Clone)] diff --git a/src/core/mod.rs b/src/core/mod.rs index 480d0e971..e0e53128d 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -897,7 +897,7 @@ impl Tracker { /// * `lifetime` - The duration in seconds for the new key. The key will be /// no longer valid after `lifetime` seconds. pub async fn generate_auth_key(&self, lifetime: Option) -> Result { - let auth_key = auth::generate_key(lifetime); + let auth_key = auth::key::generate_key(lifetime); self.database.add_key_to_keys(&auth_key)?; self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); @@ -982,12 +982,12 @@ impl Tracker { Some(key) => match self.config.private_mode { Some(private_mode) => { if private_mode.check_keys_expiration { - return auth::verify_key_expiration(key); + return auth::key::verify_key_expiration(key); } Ok(()) } - None => auth::verify_key_expiration(key), + None => auth::key::verify_key_expiration(key), }, } } From 2b7373a260d7bb532744a271192e9f1d85dfed5b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 20 Jan 2025 16:28:14 +0000 Subject: [PATCH 0608/1297] refactor: [#1191] rename mod core::auth to core::authentication The `auth` name is ambiguous, it could mean authorization. --- src/core/{auth => authentication}/key.rs | 30 ++++++------- src/core/{auth => authentication}/mod.rs | 0 src/core/databases/mod.rs | 10 ++--- src/core/databases/mysql.rs | 18 ++++---- src/core/databases/sqlite.rs | 18 ++++---- src/core/error.rs | 4 +- src/core/mod.rs | 45 ++++++++++--------- .../apis/v1/context/auth_key/handlers.rs | 2 +- .../apis/v1/context/auth_key/resources.rs | 18 ++++---- .../http/v1/extractors/authentication_key.rs | 2 +- src/servers/http/v1/handlers/announce.rs | 6 +-- src/servers/http/v1/handlers/common/auth.rs | 6 +-- src/servers/http/v1/handlers/scrape.rs | 6 +-- src/shared/bit_torrent/common.rs | 4 +- .../api/v1/contract/context/auth_key.rs | 4 +- tests/servers/http/client.rs | 2 +- tests/servers/http/connection_info.rs | 2 +- tests/servers/http/v1/contract.rs | 4 +- 18 files changed, 92 insertions(+), 89 deletions(-) rename src/core/{auth => authentication}/key.rs (89%) rename src/core/{auth => authentication}/mod.rs (100%) diff --git a/src/core/auth/key.rs b/src/core/authentication/key.rs similarity index 89% rename from src/core/auth/key.rs rename to src/core/authentication/key.rs index f0adf5946..8858361ec 100644 --- a/src/core/auth/key.rs +++ b/src/core/authentication/key.rs @@ -12,7 +12,7 @@ //! Keys are stored in this struct: //! //! ```rust,no_run -//! use torrust_tracker_lib::core::auth::Key; +//! use torrust_tracker_lib::core::authentication::Key; //! use torrust_tracker_primitives::DurationSinceUnixEpoch; //! //! pub struct PeerKey { @@ -28,14 +28,14 @@ //! You can generate a new key valid for `9999` seconds and `0` nanoseconds from the current time with the following: //! //! ```rust,no_run -//! use torrust_tracker_lib::core::auth; +//! use torrust_tracker_lib::core::authentication; //! use std::time::Duration; //! -//! let expiring_key = auth::key::generate_key(Some(Duration::new(9999, 0))); +//! let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0))); //! //! // And you can later verify it with: //! -//! assert!(auth::key::verify_key_expiration(&expiring_key).is_ok()); +//! assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); //! ``` use std::panic::Location; @@ -199,7 +199,7 @@ impl Key { /// Error returned when a key cannot be parsed from a string. /// /// ```text -/// use torrust_tracker_lib::core::auth::Key; +/// use torrust_tracker_lib::core::authentication::Key; /// use std::str::FromStr; /// /// let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; @@ -229,7 +229,7 @@ impl FromStr for Key { } /// Verification error. Error returned when an [`PeerKey`] cannot be -/// verified with the (`crate::core::auth::verify_key`) function. +/// verified with the (`crate::core::authentication::verify_key`) function. #[derive(Debug, Error)] #[allow(dead_code)] pub enum Error { @@ -260,7 +260,7 @@ mod tests { mod key { use std::str::FromStr; - use crate::core::auth::Key; + use crate::core::authentication::Key; #[test] fn should_be_parsed_from_an_string() { @@ -295,12 +295,12 @@ mod tests { use torrust_tracker_clock::clock; use torrust_tracker_clock::clock::stopped::Stopped as _; - use crate::core::auth; + use crate::core::authentication; #[test] fn should_be_parsed_from_an_string() { let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; - let auth_key = auth::Key::from_str(key_string); + let auth_key = authentication::Key::from_str(key_string); assert!(auth_key.is_ok()); assert_eq!(auth_key.unwrap().to_string(), key_string); @@ -311,7 +311,7 @@ mod tests { // Set the time to the current time. clock::Stopped::local_set_to_unix_epoch(); - let expiring_key = auth::key::generate_key(Some(Duration::from_secs(0))); + let expiring_key = authentication::key::generate_key(Some(Duration::from_secs(0))); assert_eq!( expiring_key.to_string(), @@ -321,9 +321,9 @@ mod tests { #[test] fn should_be_generated_with_a_expiration_time() { - let expiring_key = auth::key::generate_key(Some(Duration::new(9999, 0))); + let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0))); - assert!(auth::key::verify_key_expiration(&expiring_key).is_ok()); + assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); } #[test] @@ -332,17 +332,17 @@ mod tests { clock::Stopped::local_set_to_system_time_now(); // Make key that is valid for 19 seconds. - let expiring_key = auth::key::generate_key(Some(Duration::from_secs(19))); + let expiring_key = authentication::key::generate_key(Some(Duration::from_secs(19))); // Mock the time has passed 10 sec. clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); - assert!(auth::key::verify_key_expiration(&expiring_key).is_ok()); + assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); // Mock the time has passed another 10 sec. clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); - assert!(auth::key::verify_key_expiration(&expiring_key).is_err()); + assert!(authentication::key::verify_key_expiration(&expiring_key).is_err()); } } } diff --git a/src/core/auth/mod.rs b/src/core/authentication/mod.rs similarity index 100% rename from src/core/auth/mod.rs rename to src/core/authentication/mod.rs diff --git a/src/core/databases/mod.rs b/src/core/databases/mod.rs index e29ce22e8..e0b1b4f1b 100644 --- a/src/core/databases/mod.rs +++ b/src/core/databases/mod.rs @@ -54,7 +54,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::PersistentTorrents; use self::error::Error; -use crate::core::auth::{self, Key}; +use crate::core::authentication::{self, Key}; struct Builder where @@ -195,11 +195,11 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to load. - fn load_keys(&self) -> Result, Error>; + fn load_keys(&self) -> Result, Error>; /// It gets an expiring authentication key from the database. /// - /// It returns `Some(PeerKey)` if a [`PeerKey`](crate::core::auth::PeerKey) + /// It returns `Some(PeerKey)` if a [`PeerKey`](crate::core::authentication::PeerKey) /// with the input [`Key`] exists, `None` otherwise. /// /// # Context: Authentication Keys @@ -207,7 +207,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to load. - fn get_key_from_keys(&self, key: &Key) -> Result, Error>; + fn get_key_from_keys(&self, key: &Key) -> Result, Error>; /// It adds an expiring authentication key to the database. /// @@ -216,7 +216,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Will return `Err` if unable to save. - fn add_key_to_keys(&self, auth_key: &auth::PeerKey) -> Result; + fn add_key_to_keys(&self, auth_key: &authentication::PeerKey) -> Result; /// It removes an expiring authentication key from the database. /// diff --git a/src/core/databases/mysql.rs b/src/core/databases/mysql.rs index 1b849421b..213f6300a 100644 --- a/src/core/databases/mysql.rs +++ b/src/core/databases/mysql.rs @@ -11,7 +11,7 @@ use torrust_tracker_primitives::PersistentTorrents; use super::driver::Driver; use super::{Database, Error}; -use crate::core::auth::{self, Key}; +use crate::core::authentication::{self, Key}; use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; const DRIVER: Driver = Driver::MySQL; @@ -63,7 +63,7 @@ impl Database for Mysql { PRIMARY KEY (`id`), UNIQUE (`key`) );", - i8::try_from(AUTH_KEY_LENGTH).expect("auth::Auth Key Length Should fit within a i8!") + i8::try_from(AUTH_KEY_LENGTH).expect("authentication key length should fit within a i8!") ); let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -118,17 +118,17 @@ impl Database for Mysql { } /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). - fn load_keys(&self) -> Result, Error> { + fn load_keys(&self) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let keys = conn.query_map( "SELECT `key`, valid_until FROM `keys`", |(key, valid_until): (String, Option)| match valid_until { - Some(valid_until) => auth::PeerKey { + Some(valid_until) => authentication::PeerKey { key: key.parse::().unwrap(), valid_until: Some(Duration::from_secs(valid_until.unsigned_abs())), }, - None => auth::PeerKey { + None => authentication::PeerKey { key: key.parse::().unwrap(), valid_until: None, }, @@ -202,7 +202,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::get_key_from_keys`](crate::core::databases::Database::get_key_from_keys). - fn get_key_from_keys(&self, key: &Key) -> Result, Error> { + fn get_key_from_keys(&self, key: &Key) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let query = conn.exec_first::<(String, Option), _, _>( @@ -213,11 +213,11 @@ impl Database for Mysql { let key = query?; Ok(key.map(|(key, opt_valid_until)| match opt_valid_until { - Some(valid_until) => auth::PeerKey { + Some(valid_until) => authentication::PeerKey { key: key.parse::().unwrap(), valid_until: Some(Duration::from_secs(valid_until.unsigned_abs())), }, - None => auth::PeerKey { + None => authentication::PeerKey { key: key.parse::().unwrap(), valid_until: None, }, @@ -225,7 +225,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::add_key_to_keys`](crate::core::databases::Database::add_key_to_keys). - fn add_key_to_keys(&self, auth_key: &auth::PeerKey) -> Result { + fn add_key_to_keys(&self, auth_key: &authentication::PeerKey) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let key = auth_key.key.to_string(); diff --git a/src/core/databases/sqlite.rs b/src/core/databases/sqlite.rs index 5bb23bb3e..6fe9ac599 100644 --- a/src/core/databases/sqlite.rs +++ b/src/core/databases/sqlite.rs @@ -11,7 +11,7 @@ use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrents}; use super::driver::Driver; use super::{Database, Error}; -use crate::core::auth::{self, Key}; +use crate::core::authentication::{self, Key}; const DRIVER: Driver = Driver::Sqlite3; @@ -106,7 +106,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). - fn load_keys(&self) -> Result, Error> { + fn load_keys(&self) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT key, valid_until FROM keys")?; @@ -116,18 +116,18 @@ impl Database for Sqlite { let opt_valid_until: Option = row.get(1)?; match opt_valid_until { - Some(valid_until) => Ok(auth::PeerKey { + Some(valid_until) => Ok(authentication::PeerKey { key: key.parse::().unwrap(), valid_until: Some(DurationSinceUnixEpoch::from_secs(valid_until.unsigned_abs())), }), - None => Ok(auth::PeerKey { + None => Ok(authentication::PeerKey { key: key.parse::().unwrap(), valid_until: None, }), } })?; - let keys: Vec = keys_iter.filter_map(std::result::Result::ok).collect(); + let keys: Vec = keys_iter.filter_map(std::result::Result::ok).collect(); Ok(keys) } @@ -216,7 +216,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::get_key_from_keys`](crate::core::databases::Database::get_key_from_keys). - fn get_key_from_keys(&self, key: &Key) -> Result, Error> { + fn get_key_from_keys(&self, key: &Key) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT key, valid_until FROM keys WHERE key = ?")?; @@ -230,11 +230,11 @@ impl Database for Sqlite { let key: String = f.get(0).unwrap(); match valid_until { - Some(valid_until) => auth::PeerKey { + Some(valid_until) => authentication::PeerKey { key: key.parse::().unwrap(), valid_until: Some(DurationSinceUnixEpoch::from_secs(valid_until.unsigned_abs())), }, - None => auth::PeerKey { + None => authentication::PeerKey { key: key.parse::().unwrap(), valid_until: None, }, @@ -243,7 +243,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::add_key_to_keys`](crate::core::databases::Database::add_key_to_keys). - fn add_key_to_keys(&self, auth_key: &auth::PeerKey) -> Result { + fn add_key_to_keys(&self, auth_key: &authentication::PeerKey) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let insert = match auth_key.valid_until { diff --git a/src/core/error.rs b/src/core/error.rs index f0e4b849e..434e3c825 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -12,7 +12,7 @@ use bittorrent_http_protocol::v1::responses; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_located_error::LocatedError; -use super::{auth::key::ParseKeyError, databases}; +use super::{authentication::key::ParseKeyError, databases}; /// Authentication or authorization error returned by the core `Tracker` #[derive(thiserror::Error, Debug, Clone)] @@ -20,7 +20,7 @@ pub enum Error { // Authentication errors #[error("The supplied key: {key:?}, is not valid: {source}")] PeerKeyNotValid { - key: super::auth::Key, + key: super::authentication::Key, source: LocatedError<'static, dyn std::error::Error + Send + Sync>, }, diff --git a/src/core/mod.rs b/src/core/mod.rs index e0e53128d..11945a79a 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -439,7 +439,7 @@ //! - Torrent metrics //! //! Refer to [`databases`] module for more information about persistence. -pub mod auth; +pub mod authentication; pub mod databases; pub mod error; pub mod services; @@ -455,7 +455,7 @@ use std::panic::Location; use std::sync::Arc; use std::time::Duration; -use auth::PeerKey; +use authentication::PeerKey; use bittorrent_primitives::info_hash::InfoHash; use error::PeerKeyError; use torrust_tracker_clock::clock::Time; @@ -468,7 +468,7 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; -use self::auth::Key; +use self::authentication::Key; use self::torrent::Torrents; use crate::core::databases::Database; use crate::CurrentClock; @@ -491,7 +491,7 @@ pub struct Tracker { database: Arc>, /// Tracker users' keys. Only for private trackers. - keys: tokio::sync::RwLock>, + keys: tokio::sync::RwLock>, /// The service to check is a torrent is whitelisted. pub whitelist_authorization: Arc, @@ -786,7 +786,7 @@ impl Tracker { /// Will return an error if the the authentication key cannot be verified. /// /// # Context: Authentication - pub async fn authenticate(&self, key: &Key) -> Result<(), auth::Error> { + pub async fn authenticate(&self, key: &Key) -> Result<(), authentication::Error> { if self.is_private() { self.verify_auth_key(key).await } else { @@ -805,7 +805,7 @@ impl Tracker { /// - The key duration overflows the duration type maximum value. /// - The provided pre-generated key is invalid. /// - The key could not been persisted due to database issues. - pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { + pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { // code-review: all methods related to keys should be moved to a new independent "keys" service. match add_key_req.opt_key { @@ -878,7 +878,7 @@ impl Tracker { /// # Errors /// /// Will return a `database::Error` if unable to add the `auth_key` to the database. - pub async fn generate_permanent_auth_key(&self) -> Result { + pub async fn generate_permanent_auth_key(&self) -> Result { self.generate_auth_key(None).await } @@ -896,8 +896,11 @@ impl Tracker { /// /// * `lifetime` - The duration in seconds for the new key. The key will be /// no longer valid after `lifetime` seconds. - pub async fn generate_auth_key(&self, lifetime: Option) -> Result { - let auth_key = auth::key::generate_key(lifetime); + pub async fn generate_auth_key( + &self, + lifetime: Option, + ) -> Result { + let auth_key = authentication::key::generate_key(lifetime); self.database.add_key_to_keys(&auth_key)?; self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); @@ -918,7 +921,7 @@ impl Tracker { /// # Arguments /// /// * `key` - The pre-generated key. - pub async fn add_permanent_auth_key(&self, key: Key) -> Result { + pub async fn add_permanent_auth_key(&self, key: Key) -> Result { self.add_auth_key(key, None).await } @@ -942,7 +945,7 @@ impl Tracker { &self, key: Key, valid_until: Option, - ) -> Result { + ) -> Result { let auth_key = PeerKey { key, valid_until }; // code-review: should we return a friendly error instead of the DB @@ -973,21 +976,21 @@ impl Tracker { /// # Errors /// /// Will return a `key::Error` if unable to get any `auth_key`. - async fn verify_auth_key(&self, key: &Key) -> Result<(), auth::Error> { + async fn verify_auth_key(&self, key: &Key) -> Result<(), authentication::Error> { match self.keys.read().await.get(key) { - None => Err(auth::Error::UnableToReadKey { + None => Err(authentication::Error::UnableToReadKey { location: Location::caller(), key: Box::new(key.clone()), }), Some(key) => match self.config.private_mode { Some(private_mode) => { if private_mode.check_keys_expiration { - return auth::key::verify_key_expiration(key); + return authentication::key::verify_key_expiration(key); } Ok(()) } - None => auth::key::verify_key_expiration(key), + None => authentication::key::verify_key_expiration(key), }, } } @@ -1746,14 +1749,14 @@ mod tests { use std::str::FromStr; use std::time::Duration; - use crate::core::auth::{self}; + use crate::core::authentication::{self}; use crate::core::tests::the_tracker::private_tracker; #[tokio::test] async fn it_should_fail_authenticating_a_peer_when_it_uses_an_unregistered_key() { let tracker = private_tracker(); - let unregistered_key = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); let result = tracker.authenticate(&unregistered_key).await; @@ -1764,7 +1767,7 @@ mod tests { async fn it_should_fail_verifying_an_unregistered_authentication_key() { let tracker = private_tracker(); - let unregistered_key = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); assert!(tracker.verify_auth_key(&unregistered_key).await.is_err()); } @@ -1804,7 +1807,7 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::v2_0_0::core::PrivateMode; - use crate::core::auth::Key; + use crate::core::authentication::Key; use crate::core::tests::the_tracker::private_tracker; use crate::CurrentClock; @@ -1856,7 +1859,7 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::v2_0_0::core::PrivateMode; - use crate::core::auth::Key; + use crate::core::authentication::Key; use crate::core::tests::the_tracker::private_tracker; use crate::core::AddKeyRequest; use crate::CurrentClock; @@ -1944,7 +1947,7 @@ mod tests { } mod pre_generated_keys { - use crate::core::auth::Key; + use crate::core::authentication::Key; use crate::core::tests::the_tracker::private_tracker; use crate::core::AddKeyRequest; diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index fed3ad301..bb8a98744 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -12,7 +12,7 @@ use super::responses::{ auth_key_response, failed_to_delete_key_response, failed_to_generate_key_response, failed_to_reload_keys_response, invalid_auth_key_duration_response, invalid_auth_key_response, }; -use crate::core::auth::Key; +use crate::core::authentication::Key; use crate::core::{AddKeyRequest, Tracker}; use crate::servers::apis::v1::context::auth_key::resources::AuthKey; use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_response}; diff --git a/src/servers/apis/v1/context/auth_key/resources.rs b/src/servers/apis/v1/context/auth_key/resources.rs index c26b2c4d3..a65eb2ab2 100644 --- a/src/servers/apis/v1/context/auth_key/resources.rs +++ b/src/servers/apis/v1/context/auth_key/resources.rs @@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize}; use torrust_tracker_clock::conv::convert_from_iso_8601_to_timestamp; -use crate::core::auth::{self, Key}; +use crate::core::authentication::{self, Key}; /// A resource that represents an authentication key. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -17,9 +17,9 @@ pub struct AuthKey { pub expiry_time: Option, } -impl From for auth::PeerKey { +impl From for authentication::PeerKey { fn from(auth_key_resource: AuthKey) -> Self { - auth::PeerKey { + authentication::PeerKey { key: auth_key_resource.key.parse::().unwrap(), valid_until: auth_key_resource .expiry_time @@ -29,8 +29,8 @@ impl From for auth::PeerKey { } #[allow(deprecated)] -impl From for AuthKey { - fn from(auth_key: auth::PeerKey) -> Self { +impl From for AuthKey { + fn from(auth_key: authentication::PeerKey) -> Self { match (auth_key.valid_until, auth_key.expiry_time()) { (Some(valid_until), Some(expiry_time)) => AuthKey { key: auth_key.key.to_string(), @@ -54,7 +54,7 @@ mod tests { use torrust_tracker_clock::clock::{self, Time}; use super::AuthKey; - use crate::core::auth::{self, Key}; + use crate::core::authentication::{self, Key}; use crate::CurrentClock; struct TestTime { @@ -86,8 +86,8 @@ mod tests { }; assert_eq!( - auth::PeerKey::from(auth_key_resource), - auth::PeerKey { + authentication::PeerKey::from(auth_key_resource), + authentication::PeerKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".parse::().unwrap(), // cspell:disable-line valid_until: Some(CurrentClock::now_add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap()) } @@ -99,7 +99,7 @@ mod tests { fn it_should_be_convertible_from_an_auth_key() { clock::Stopped::local_set_to_unix_epoch(); - let auth_key = auth::PeerKey { + let auth_key = authentication::PeerKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".parse::().unwrap(), // cspell:disable-line valid_until: Some(CurrentClock::now_add(&Duration::new(one_hour_after_unix_epoch().timestamp, 0)).unwrap()), }; diff --git a/src/servers/http/v1/extractors/authentication_key.rs b/src/servers/http/v1/extractors/authentication_key.rs index 6610b197a..d3b77c31a 100644 --- a/src/servers/http/v1/extractors/authentication_key.rs +++ b/src/servers/http/v1/extractors/authentication_key.rs @@ -53,7 +53,7 @@ use bittorrent_http_protocol::v1::responses; use hyper::StatusCode; use serde::Deserialize; -use crate::core::auth::Key; +use crate::core::authentication::Key; use crate::servers::http::v1::handlers::common::auth; /// Extractor for the [`Key`] struct. diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 61464f1d5..fe3825a41 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -21,7 +21,7 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; -use crate::core::auth::Key; +use crate::core::authentication::Key; use crate::core::statistics::event::sender::Sender; use crate::core::{whitelist, PeersWanted, Tracker}; use crate::servers::http::v1::extractors::announce_request::ExtractRequest; @@ -290,7 +290,7 @@ mod tests { use std::sync::Arc; use super::{private_tracker, sample_announce_request, sample_client_ip_sources}; - use crate::core::auth; + use crate::core::authentication; use crate::servers::http::v1::handlers::announce::handle_announce; use crate::servers::http::v1::handlers::announce::tests::assert_error_response; @@ -327,7 +327,7 @@ mod tests { let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); - let unregistered_key = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); let maybe_key = Some(unregistered_key); diff --git a/src/servers/http/v1/handlers/common/auth.rs b/src/servers/http/v1/handlers/common/auth.rs index ff1d47e91..5497427d8 100644 --- a/src/servers/http/v1/handlers/common/auth.rs +++ b/src/servers/http/v1/handlers/common/auth.rs @@ -6,7 +6,7 @@ use std::panic::Location; use bittorrent_http_protocol::v1::responses; use thiserror::Error; -use crate::core::auth; +use crate::core::authentication; /// Authentication error. /// @@ -31,8 +31,8 @@ impl From for responses::error::Error { } } -impl From for responses::error::Error { - fn from(err: auth::Error) -> Self { +impl From for responses::error::Error { + fn from(err: authentication::Error) -> Self { responses::error::Error { failure_reason: format!("Authentication error: {err}"), } diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 9c57eda58..58c2d012b 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -15,7 +15,7 @@ use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSou use hyper::StatusCode; use torrust_tracker_primitives::core::ScrapeData; -use crate::core::auth::Key; +use crate::core::authentication::Key; use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; @@ -205,7 +205,7 @@ mod tests { use torrust_tracker_primitives::core::ScrapeData; use super::{private_tracker, sample_client_ip_sources, sample_scrape_request}; - use crate::core::auth; + use crate::core::authentication; use crate::servers::http::v1::handlers::scrape::handle_scrape; #[tokio::test] @@ -239,7 +239,7 @@ mod tests { let stats_event_sender = Arc::new(stats_event_sender); let scrape_request = sample_scrape_request(); - let unregistered_key = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); let maybe_key = Some(unregistered_key); let scrape_data = handle_scrape( diff --git a/src/shared/bit_torrent/common.rs b/src/shared/bit_torrent/common.rs index 46026ac47..5ba2e0492 100644 --- a/src/shared/bit_torrent/common.rs +++ b/src/shared/bit_torrent/common.rs @@ -17,6 +17,6 @@ pub const MAX_SCRAPE_TORRENTS: u8 = 74; /// HTTP tracker authentication key length. /// -/// For more information see function [`generate_key`](crate::core::auth::generate_key) to generate the -/// [`PeerKey`](crate::core::auth::PeerKey). +/// For more information see function [`generate_key`](crate::core::authentication::generate_key) to generate the +/// [`PeerKey`](crate::core::authentication::PeerKey). pub const AUTH_KEY_LENGTH: usize = 32; diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 9b2e740c0..40c10be5f 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -2,7 +2,7 @@ use std::time::Duration; use serde::Serialize; use torrust_tracker_api_client::v1::client::{headers_with_request_id, AddKeyForm, Client}; -use torrust_tracker_lib::core::auth::Key; +use torrust_tracker_lib::core::authentication::Key; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; @@ -463,7 +463,7 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { mod deprecated_generate_key_endpoint { use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; - use torrust_tracker_lib::core::auth::Key; + use torrust_tracker_lib::core::authentication::Key; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; diff --git a/tests/servers/http/client.rs b/tests/servers/http/client.rs index b64a616cd..9fc278536 100644 --- a/tests/servers/http/client.rs +++ b/tests/servers/http/client.rs @@ -1,7 +1,7 @@ use std::net::IpAddr; use reqwest::{Client as ReqwestClient, Response}; -use torrust_tracker_lib::core::auth::Key; +use torrust_tracker_lib::core::authentication::Key; use super::requests::announce::{self, Query}; use super::requests::scrape; diff --git a/tests/servers/http/connection_info.rs b/tests/servers/http/connection_info.rs index 123ac05f0..327bc0073 100644 --- a/tests/servers/http/connection_info.rs +++ b/tests/servers/http/connection_info.rs @@ -1,4 +1,4 @@ -use torrust_tracker_lib::core::auth::Key; +use torrust_tracker_lib::core::authentication::Key; #[derive(Clone, Debug)] pub struct ConnectionInfo { diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 2cec1790f..961caf017 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -1381,7 +1381,7 @@ mod configured_as_private { use std::time::Duration; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_lib::core::auth::Key; + use torrust_tracker_lib::core::authentication::Key; use torrust_tracker_test_helpers::configuration; use crate::common::logging; @@ -1467,7 +1467,7 @@ mod configured_as_private { use aquatic_udp_protocol::PeerId; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_lib::core::auth::Key; + use torrust_tracker_lib::core::authentication::Key; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; From e75728a807303bd525faacdb6436930a993a45ba Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 20 Jan 2025 16:48:29 +0000 Subject: [PATCH 0609/1297] refactor: [#1191] extract core::authentication::Facade type It's a temporary type to extract responsability from the tracker. --- src/core/authentication/mod.rs | 292 +++++++++++++++++++++++++++++++++ 1 file changed, 292 insertions(+) diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index d0f72340d..358678def 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -1,5 +1,297 @@ +use std::panic::Location; +use std::sync::Arc; +use std::time::Duration; + +use torrust_tracker_clock::clock::Time; +use torrust_tracker_configuration::Core; +use torrust_tracker_located_error::Located; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::databases::{self, Database}; +use super::error::PeerKeyError; +use crate::CurrentClock; + pub mod key; pub type PeerKey = key::PeerKey; pub type Key = key::Key; pub type Error = key::Error; + +/// This type contains the info needed to add a new tracker key. +/// +/// You can upload a pre-generated key or let the app to generate a new one. +/// You can also set an expiration date or leave it empty (`None`) if you want +/// to create a permanent key that does not expire. +#[derive(Debug)] +pub struct AddKeyRequest { + /// The pre-generated key. Use `None` to generate a random key. + pub opt_key: Option, + + /// How long the key will be valid in seconds. Use `None` for permanent keys. + pub opt_seconds_valid: Option, +} + +pub struct Facade { + /// The tracker configuration. + config: Core, + + /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) + /// or [`MySQL`](crate::core::databases::mysql) + database: Arc>, + + /// Tracker users' keys. Only for private trackers. + keys: tokio::sync::RwLock>, +} + +impl Facade { + #[must_use] + pub fn new(config: &Core, database: &Arc>) -> Self { + Self { + config: config.clone(), + database: database.clone(), + keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), + } + } + + /// It authenticates the peer `key` against the `Tracker` authentication + /// key list. + /// + /// # Errors + /// + /// Will return an error if the the authentication key cannot be verified. + /// + /// # Context: Authentication + pub async fn authenticate(&self, key: &Key) -> Result<(), Error> { + if self.is_private() { + self.verify_auth_key(key).await + } else { + Ok(()) + } + } + + /// Returns `true` is the tracker is in private mode. + pub fn is_private(&self) -> bool { + self.config.private + } + + /// It verifies an authentication key. + /// + /// # Context: Authentication + /// + /// # Errors + /// + /// Will return a `key::Error` if unable to get any `auth_key`. + async fn verify_auth_key(&self, key: &Key) -> Result<(), Error> { + match self.keys.read().await.get(key) { + None => Err(Error::UnableToReadKey { + location: Location::caller(), + key: Box::new(key.clone()), + }), + Some(key) => match self.config.private_mode { + Some(private_mode) => { + if private_mode.check_keys_expiration { + return key::verify_key_expiration(key); + } + + Ok(()) + } + None => key::verify_key_expiration(key), + }, + } + } + + /// Adds new peer keys to the tracker. + /// + /// Keys can be pre-generated or randomly created. They can also be permanent or expire. + /// + /// # Errors + /// + /// Will return an error if: + /// + /// - The key duration overflows the duration type maximum value. + /// - The provided pre-generated key is invalid. + /// - The key could not been persisted due to database issues. + pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { + // code-review: all methods related to keys should be moved to a new independent "keys" service. + + match add_key_req.opt_key { + // Upload pre-generated key + Some(pre_existing_key) => { + if let Some(seconds_valid) = add_key_req.opt_seconds_valid { + // Expiring key + let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(seconds_valid)) else { + return Err(PeerKeyError::DurationOverflow { seconds_valid }); + }; + + let key = pre_existing_key.parse::(); + + match key { + Ok(key) => match self.add_auth_key(key, Some(valid_until)).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + Err(err) => Err(PeerKeyError::InvalidKey { + key: pre_existing_key, + source: Located(err).into(), + }), + } + } else { + // Permanent key + let key = pre_existing_key.parse::(); + + match key { + Ok(key) => match self.add_permanent_auth_key(key).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + Err(err) => Err(PeerKeyError::InvalidKey { + key: pre_existing_key, + source: Located(err).into(), + }), + } + } + } + // Generate a new random key + None => match add_key_req.opt_seconds_valid { + // Expiring key + Some(seconds_valid) => match self.generate_auth_key(Some(Duration::from_secs(seconds_valid))).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + // Permanent key + None => match self.generate_permanent_auth_key().await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + }, + } + } + + /// It generates a new permanent authentication key. + /// + /// Authentication keys are used by HTTP trackers. + /// + /// # Context: Authentication + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `auth_key` to the database. + pub async fn generate_permanent_auth_key(&self) -> Result { + self.generate_auth_key(None).await + } + + /// It generates a new expiring authentication key. + /// + /// Authentication keys are used by HTTP trackers. + /// + /// # Context: Authentication + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `auth_key` to the database. + /// + /// # Arguments + /// + /// * `lifetime` - The duration in seconds for the new key. The key will be + /// no longer valid after `lifetime` seconds. + pub async fn generate_auth_key(&self, lifetime: Option) -> Result { + let auth_key = key::generate_key(lifetime); + + self.database.add_key_to_keys(&auth_key)?; + self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); + Ok(auth_key) + } + + /// It adds a pre-generated permanent authentication key. + /// + /// Authentication keys are used by HTTP trackers. + /// + /// # Context: Authentication + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `auth_key` to the + /// database. For example, if the key already exist. + /// + /// # Arguments + /// + /// * `key` - The pre-generated key. + pub async fn add_permanent_auth_key(&self, key: Key) -> Result { + self.add_auth_key(key, None).await + } + + /// It adds a pre-generated authentication key. + /// + /// Authentication keys are used by HTTP trackers. + /// + /// # Context: Authentication + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `auth_key` to the + /// database. For example, if the key already exist. + /// + /// # Arguments + /// + /// * `key` - The pre-generated key. + /// * `lifetime` - The duration in seconds for the new key. The key will be + /// no longer valid after `lifetime` seconds. + pub async fn add_auth_key( + &self, + key: Key, + valid_until: Option, + ) -> Result { + let auth_key = PeerKey { key, valid_until }; + + // code-review: should we return a friendly error instead of the DB + // constrain error when the key already exist? For now, it's returning + // the specif error for each DB driver when a UNIQUE constrain fails. + self.database.add_key_to_keys(&auth_key)?; + self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); + Ok(auth_key) + } + + /// It removes an authentication key. + /// + /// # Context: Authentication + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to remove the `key` to the database. + pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> { + self.database.remove_key_from_keys(key)?; + self.keys.write().await.remove(key); + Ok(()) + } + + /// The `Tracker` stores the authentication keys in memory and in the database. + /// In case you need to restart the `Tracker` you can load the keys from the database + /// into memory with this function. Keys are automatically stored in the database when they + /// are generated. + /// + /// # Context: Authentication + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to `load_keys` from the database. + pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> { + let keys_from_database = self.database.load_keys()?; + let mut keys = self.keys.write().await; + + keys.clear(); + + for key in keys_from_database { + keys.insert(key.key.clone(), key); + } + + Ok(()) + } +} From 986a2f661a0012a8f1038910f19f271da31abda8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 20 Jan 2025 17:01:56 +0000 Subject: [PATCH 0610/1297] fix: [#1191] format --- src/core/error.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/error.rs b/src/core/error.rs index 434e3c825..1d0e974e5 100644 --- a/src/core/error.rs +++ b/src/core/error.rs @@ -12,7 +12,8 @@ use bittorrent_http_protocol::v1::responses; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_located_error::LocatedError; -use super::{authentication::key::ParseKeyError, databases}; +use super::authentication::key::ParseKeyError; +use super::databases; /// Authentication or authorization error returned by the core `Tracker` #[derive(thiserror::Error, Debug, Clone)] From 39c2a8fb80902bd4a013c79f400fa5f75c790c79 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 20 Jan 2025 17:41:36 +0000 Subject: [PATCH 0611/1297] refactor: [#1191] replace authentication methods with extracted service in the core tracker --- src/app_test.rs | 6 +- src/bootstrap/app.rs | 11 +- src/bootstrap/jobs/http_tracker.rs | 6 +- src/bootstrap/jobs/tracker_apis.rs | 5 +- src/container.rs | 3 +- src/core/authentication/mod.rs | 11 +- src/core/mod.rs | 249 ++++++------------ src/core/services/mod.rs | 5 +- src/core/services/statistics/mod.rs | 10 +- src/core/services/torrent.rs | 88 +++++-- src/servers/apis/server.rs | 6 +- .../apis/v1/context/auth_key/handlers.rs | 4 +- src/servers/http/server.rs | 6 +- src/servers/http/v1/handlers/announce.rs | 10 +- src/servers/http/v1/handlers/scrape.rs | 16 +- src/servers/http/v1/services/announce.rs | 9 +- src/servers/http/v1/services/scrape.rs | 8 +- src/servers/udp/handlers.rs | 25 +- src/servers/udp/server/mod.rs | 9 +- src/shared/bit_torrent/common.rs | 2 +- tests/servers/api/environment.rs | 2 +- tests/servers/http/environment.rs | 2 +- tests/servers/udp/environment.rs | 2 +- 23 files changed, 243 insertions(+), 252 deletions(-) diff --git a/src/app_test.rs b/src/app_test.rs index ffd55581e..884aed6ef 100644 --- a/src/app_test.rs +++ b/src/app_test.rs @@ -5,8 +5,8 @@ use torrust_tracker_configuration::Configuration; use crate::core::databases::Database; use crate::core::services::initialize_database; -use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; +use crate::core::{authentication, whitelist}; /// Initialize the tracker dependencies. #[allow(clippy::type_complexity)] @@ -17,6 +17,7 @@ pub fn initialize_tracker_dependencies( Arc>, Arc, Arc, + Arc, ) { let database = initialize_database(config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -24,6 +25,7 @@ pub fn initialize_tracker_dependencies( &config.core, &in_memory_whitelist.clone(), )); + let authentication = Arc::new(authentication::Facade::new(&config.core, &database.clone())); - (database, in_memory_whitelist, whitelist_authorization) + (database, in_memory_whitelist, whitelist_authorization, authentication) } diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 5dbdd15cb..bc6b7a6bd 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -23,8 +23,8 @@ use super::config::initialize_configuration; use crate::bootstrap; use crate::container::AppContainer; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; -use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; +use crate::core::{authentication, whitelist}; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; @@ -89,8 +89,14 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { &in_memory_whitelist.clone(), )); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + let authentication = Arc::new(authentication::Facade::new(&configuration.core, &database.clone())); - let tracker = Arc::new(initialize_tracker(configuration, &database, &whitelist_authorization)); + let tracker = Arc::new(initialize_tracker( + configuration, + &database, + &whitelist_authorization, + &authentication, + )); AppContainer { tracker, @@ -99,6 +105,7 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { stats_event_sender, stats_repository, whitelist_manager, + authentication, } } diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index dea866648..b07ff935c 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -101,8 +101,8 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::http_tracker::start_job; use crate::core::services::{initialize_database, initialize_tracker, statistics}; - use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::core::{authentication, whitelist}; use crate::servers::http::Version; use crate::servers::registar::Registar; @@ -123,7 +123,9 @@ mod tests { &cfg.core, &in_memory_whitelist.clone(), )); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); + let authentication = Arc::new(authentication::Facade::new(&cfg.core, &database.clone())); + + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); let version = Version::V1; diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 7e06829c4..70e2e6737 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -150,8 +150,8 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::tracker_apis::start_job; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; - use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::core::{authentication, whitelist}; use crate::servers::apis::Version; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -176,8 +176,9 @@ mod tests { &in_memory_whitelist.clone(), )); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + let authentication = Arc::new(authentication::Facade::new(&cfg.core, &database.clone())); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); let version = Version::V1; diff --git a/src/container.rs b/src/container.rs index fd75601ae..3c9229b89 100644 --- a/src/container.rs +++ b/src/container.rs @@ -5,7 +5,7 @@ use tokio::sync::RwLock; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; use crate::core::whitelist::manager::WhiteListManager; -use crate::core::{whitelist, Tracker}; +use crate::core::{authentication, whitelist, Tracker}; use crate::servers::udp::server::banning::BanService; pub struct AppContainer { @@ -15,4 +15,5 @@ pub struct AppContainer { pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub whitelist_manager: Arc, + pub authentication: Arc, } diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 358678def..d03502988 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -81,7 +81,7 @@ impl Facade { /// # Errors /// /// Will return a `key::Error` if unable to get any `auth_key`. - async fn verify_auth_key(&self, key: &Key) -> Result<(), Error> { + pub async fn verify_auth_key(&self, key: &Key) -> Result<(), Error> { match self.keys.read().await.get(key) { None => Err(Error::UnableToReadKey { location: Location::caller(), @@ -268,10 +268,17 @@ impl Facade { /// Will return a `database::Error` if unable to remove the `key` to the database. pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> { self.database.remove_key_from_keys(key)?; - self.keys.write().await.remove(key); + self.remove_in_memory_auth_key(key).await; Ok(()) } + /// It removes an authentication key from memory. + /// + /// # Context: Authentication + pub async fn remove_in_memory_auth_key(&self, key: &Key) { + self.keys.write().await.remove(key); + } + /// The `Tracker` stores the authentication keys in memory and in the database. /// In case you need to restart the `Tracker` you can load the keys from the database /// into memory with this function. Keys are automatically stored in the database when they diff --git a/src/core/mod.rs b/src/core/mod.rs index 11945a79a..4b8d4c7f2 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -371,7 +371,7 @@ //! //! To learn more about tracker authentication, refer to the following modules : //! -//! - [`auth`] module. +//! - [`authentication`] module. //! - [`core`](crate::core) module. //! - [`http`](crate::servers::http) module. //! @@ -451,16 +451,14 @@ pub mod peer_tests; use std::cmp::max; use std::net::IpAddr; -use std::panic::Location; use std::sync::Arc; use std::time::Duration; -use authentication::PeerKey; +use authentication::AddKeyRequest; use bittorrent_primitives::info_hash::InfoHash; use error::PeerKeyError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; -use torrust_tracker_located_error::Located; use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; @@ -490,14 +488,14 @@ pub struct Tracker { /// or [`MySQL`](crate::core::databases::mysql) database: Arc>, - /// Tracker users' keys. Only for private trackers. - keys: tokio::sync::RwLock>, - /// The service to check is a torrent is whitelisted. pub whitelist_authorization: Arc, /// The in-memory torrents repository. torrents: Arc, + + /// The service to authenticate peers. + authentication: Arc, } /// How many peers the peer announcing wants in the announce response. @@ -542,20 +540,6 @@ impl From for PeersWanted { } } -/// This type contains the info needed to add a new tracker key. -/// -/// You can upload a pre-generated key or let the app to generate a new one. -/// You can also set an expiration date or leave it empty (`None`) if you want -/// to create a permanent key that does not expire. -#[derive(Debug)] -pub struct AddKeyRequest { - /// The pre-generated key. Use `None` to generate a random key. - pub opt_key: Option, - - /// How long the key will be valid in seconds. Use `None` for permanent keys. - pub opt_seconds_valid: Option, -} - impl Tracker { /// `Tracker` constructor. /// @@ -566,45 +550,53 @@ impl Tracker { config: &Core, database: &Arc>, whitelist_authorization: &Arc, + authentication: &Arc, ) -> Result { Ok(Tracker { config: config.clone(), database: database.clone(), - keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), whitelist_authorization: whitelist_authorization.clone(), torrents: Arc::default(), + authentication: authentication.clone(), }) } /// Returns `true` is the tracker is in public mode. + #[must_use] pub fn is_public(&self) -> bool { !self.config.private } /// Returns `true` is the tracker is in private mode. + #[must_use] pub fn is_private(&self) -> bool { self.config.private } /// Returns `true` is the tracker is in whitelisted mode. + #[must_use] pub fn is_listed(&self) -> bool { self.config.listed } /// Returns `true` if the tracker requires authentication. + #[must_use] pub fn requires_authentication(&self) -> bool { self.is_private() } /// Returns `true` is the tracker is in whitelisted mode. + #[must_use] pub fn is_behind_reverse_proxy(&self) -> bool { self.config.net.on_reverse_proxy } + #[must_use] pub fn get_announce_policy(&self) -> AnnouncePolicy { self.config.announce_policy } + #[must_use] pub fn get_maybe_external_ip(&self) -> Option { self.config.net.external_ip } @@ -709,6 +701,7 @@ impl Tracker { /// # Context: Tracker /// /// Get torrent peers for a given torrent. + #[must_use] pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { match self.torrents.get(info_hash) { None => vec![], @@ -721,6 +714,7 @@ impl Tracker { /// needed for a `announce` request response. /// /// # Context: Tracker + #[must_use] pub fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { let swarm_metadata_before = match self.torrents.get_swarm_metadata(info_hash) { Some(swarm_metadata) => swarm_metadata, @@ -760,6 +754,7 @@ impl Tracker { /// /// # Panics /// Panics if unable to get the torrent metrics. + #[must_use] pub fn get_torrents_metrics(&self) -> TorrentsMetrics { self.torrents.get_metrics() } @@ -781,23 +776,21 @@ impl Tracker { /// It authenticates the peer `key` against the `Tracker` authentication /// key list. /// + /// # Context: Authentication + /// /// # Errors /// /// Will return an error if the the authentication key cannot be verified. - /// - /// # Context: Authentication pub async fn authenticate(&self, key: &Key) -> Result<(), authentication::Error> { - if self.is_private() { - self.verify_auth_key(key).await - } else { - Ok(()) - } + self.authentication.authenticate(key).await } /// Adds new peer keys to the tracker. /// /// Keys can be pre-generated or randomly created. They can also be permanent or expire. /// + /// # Context: Authentication + /// /// # Errors /// /// Will return an error if: @@ -806,67 +799,7 @@ impl Tracker { /// - The provided pre-generated key is invalid. /// - The key could not been persisted due to database issues. pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { - // code-review: all methods related to keys should be moved to a new independent "keys" service. - - match add_key_req.opt_key { - // Upload pre-generated key - Some(pre_existing_key) => { - if let Some(seconds_valid) = add_key_req.opt_seconds_valid { - // Expiring key - let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(seconds_valid)) else { - return Err(PeerKeyError::DurationOverflow { seconds_valid }); - }; - - let key = pre_existing_key.parse::(); - - match key { - Ok(key) => match self.add_auth_key(key, Some(valid_until)).await { - Ok(auth_key) => Ok(auth_key), - Err(err) => Err(PeerKeyError::DatabaseError { - source: Located(err).into(), - }), - }, - Err(err) => Err(PeerKeyError::InvalidKey { - key: pre_existing_key, - source: Located(err).into(), - }), - } - } else { - // Permanent key - let key = pre_existing_key.parse::(); - - match key { - Ok(key) => match self.add_permanent_auth_key(key).await { - Ok(auth_key) => Ok(auth_key), - Err(err) => Err(PeerKeyError::DatabaseError { - source: Located(err).into(), - }), - }, - Err(err) => Err(PeerKeyError::InvalidKey { - key: pre_existing_key, - source: Located(err).into(), - }), - } - } - } - // Generate a new random key - None => match add_key_req.opt_seconds_valid { - // Expiring key - Some(seconds_valid) => match self.generate_auth_key(Some(Duration::from_secs(seconds_valid))).await { - Ok(auth_key) => Ok(auth_key), - Err(err) => Err(PeerKeyError::DatabaseError { - source: Located(err).into(), - }), - }, - // Permanent key - None => match self.generate_permanent_auth_key().await { - Ok(auth_key) => Ok(auth_key), - Err(err) => Err(PeerKeyError::DatabaseError { - source: Located(err).into(), - }), - }, - }, - } + self.authentication.add_peer_key(add_key_req).await } /// It generates a new permanent authentication key. @@ -879,7 +812,7 @@ impl Tracker { /// /// Will return a `database::Error` if unable to add the `auth_key` to the database. pub async fn generate_permanent_auth_key(&self) -> Result { - self.generate_auth_key(None).await + self.authentication.generate_auth_key(None).await } /// It generates a new expiring authentication key. @@ -900,11 +833,7 @@ impl Tracker { &self, lifetime: Option, ) -> Result { - let auth_key = authentication::key::generate_key(lifetime); - - self.database.add_key_to_keys(&auth_key)?; - self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); - Ok(auth_key) + self.authentication.generate_auth_key(lifetime).await } /// It adds a pre-generated permanent authentication key. @@ -922,7 +851,7 @@ impl Tracker { /// /// * `key` - The pre-generated key. pub async fn add_permanent_auth_key(&self, key: Key) -> Result { - self.add_auth_key(key, None).await + self.authentication.add_auth_key(key, None).await } /// It adds a pre-generated authentication key. @@ -946,14 +875,7 @@ impl Tracker { key: Key, valid_until: Option, ) -> Result { - let auth_key = PeerKey { key, valid_until }; - - // code-review: should we return a friendly error instead of the DB - // constrain error when the key already exist? For now, it's returning - // the specif error for each DB driver when a UNIQUE constrain fails. - self.database.add_key_to_keys(&auth_key)?; - self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); - Ok(auth_key) + self.authentication.add_auth_key(key, valid_until).await } /// It removes an authentication key. @@ -964,35 +886,7 @@ impl Tracker { /// /// Will return a `database::Error` if unable to remove the `key` to the database. pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> { - self.database.remove_key_from_keys(key)?; - self.keys.write().await.remove(key); - Ok(()) - } - - /// It verifies an authentication key. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return a `key::Error` if unable to get any `auth_key`. - async fn verify_auth_key(&self, key: &Key) -> Result<(), authentication::Error> { - match self.keys.read().await.get(key) { - None => Err(authentication::Error::UnableToReadKey { - location: Location::caller(), - key: Box::new(key.clone()), - }), - Some(key) => match self.config.private_mode { - Some(private_mode) => { - if private_mode.check_keys_expiration { - return authentication::key::verify_key_expiration(key); - } - - Ok(()) - } - None => authentication::key::verify_key_expiration(key), - }, - } + self.authentication.remove_auth_key(key).await } /// The `Tracker` stores the authentication keys in memory and in the database. @@ -1006,16 +900,7 @@ impl Tracker { /// /// Will return a `database::Error` if unable to `load_keys` from the database. pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> { - let keys_from_database = self.database.load_keys()?; - let mut keys = self.keys.write().await; - - keys.clear(); - - for key in keys_from_database { - keys.insert(key.key.clone(), key); - } - - Ok(()) + self.authentication.load_keys_from_database().await } /// It drops the database tables. @@ -1051,6 +936,7 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_configuration::v2_0_0::core::PrivateMode; use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; @@ -1063,36 +949,56 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - initialize_tracker(&config, &database, &whitelist_authorization) + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + initialize_tracker(&config, &database, &whitelist_authorization, &authentication) } fn private_tracker() -> Tracker { let config = configuration::ephemeral_private(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - initialize_tracker(&config, &database, &whitelist_authorization) + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + initialize_tracker(&config, &database, &whitelist_authorization, &authentication) } fn whitelisted_tracker() -> (Tracker, Arc, Arc) { let config = configuration::ephemeral_listed(); - let (database, in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let (database, in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = initialize_tracker(&config, &database, &whitelist_authorization); + let tracker = initialize_tracker(&config, &database, &whitelist_authorization, &authentication); (tracker, whitelist_authorization, whitelist_manager) } + fn private_tracker_without_checking_keys_expiration() -> Tracker { + let mut config = configuration::ephemeral_private(); + + config.core.private_mode = Some(PrivateMode { + check_keys_expiration: false, + }); + + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + initialize_tracker(&config, &database, &whitelist_authorization, &authentication) + } + pub fn tracker_persisting_torrents_in_database() -> Tracker { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - initialize_tracker(&config, &database, &whitelist_authorization) + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + initialize_tracker(&config, &database, &whitelist_authorization, &authentication) } fn sample_info_hash() -> InfoHash { @@ -1203,7 +1109,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - tracker.upsert_peer_and_get_stats(&info_hash, &peer); + let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); let peers = tracker.get_torrent_peers(&info_hash); @@ -1245,7 +1151,7 @@ mod tests { event: AnnounceEvent::Completed, }; - tracker.upsert_peer_and_get_stats(&info_hash, &peer); + let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); } let peers = tracker.get_torrent_peers(&info_hash); @@ -1260,7 +1166,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - tracker.upsert_peer_and_get_stats(&info_hash, &peer); + let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); let peers = tracker.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); @@ -1275,7 +1181,7 @@ mod tests { let excluded_peer = sample_peer(); - tracker.upsert_peer_and_get_stats(&info_hash, &excluded_peer); + let _ = tracker.upsert_peer_and_get_stats(&info_hash, &excluded_peer); // Add 74 peers for idx in 2..=75 { @@ -1289,7 +1195,7 @@ mod tests { event: AnnounceEvent::Completed, }; - tracker.upsert_peer_and_get_stats(&info_hash, &peer); + let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); } let peers = tracker.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); @@ -1301,7 +1207,7 @@ mod tests { async fn it_should_return_the_torrent_metrics() { let tracker = public_tracker(); - tracker.upsert_peer_and_get_stats(&sample_info_hash(), &leecher()); + let _ = tracker.upsert_peer_and_get_stats(&sample_info_hash(), &leecher()); let torrent_metrics = tracker.get_torrents_metrics(); @@ -1322,7 +1228,7 @@ mod tests { let start_time = std::time::Instant::now(); for i in 0..1_000_000 { - tracker.upsert_peer_and_get_stats(&gen_seeded_infohash(&i), &leecher()); + let _ = tracker.upsert_peer_and_get_stats(&gen_seeded_infohash(&i), &leecher()); } let result_a = start_time.elapsed(); @@ -1769,7 +1675,7 @@ mod tests { let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - assert!(tracker.verify_auth_key(&unregistered_key).await.is_err()); + assert!(tracker.authentication.verify_auth_key(&unregistered_key).await.is_err()); } #[tokio::test] @@ -1781,7 +1687,7 @@ mod tests { let result = tracker.remove_auth_key(&expiring_key.key()).await; assert!(result.is_ok()); - assert!(tracker.verify_auth_key(&expiring_key.key()).await.is_err()); + assert!(tracker.authentication.verify_auth_key(&expiring_key.key()).await.is_err()); } #[tokio::test] @@ -1791,12 +1697,12 @@ mod tests { let expiring_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); // Remove the newly generated key in memory - tracker.keys.write().await.remove(&expiring_key.key()); + tracker.authentication.remove_in_memory_auth_key(&expiring_key.key()).await; let result = tracker.load_keys_from_database().await; assert!(result.is_ok()); - assert!(tracker.verify_auth_key(&expiring_key.key()).await.is_ok()); + assert!(tracker.authentication.verify_auth_key(&expiring_key.key()).await.is_ok()); } mod with_expiring_and { @@ -1805,10 +1711,11 @@ mod tests { use std::time::Duration; use torrust_tracker_clock::clock::Time; - use torrust_tracker_configuration::v2_0_0::core::PrivateMode; use crate::core::authentication::Key; - use crate::core::tests::the_tracker::private_tracker; + use crate::core::tests::the_tracker::{ + private_tracker, private_tracker_without_checking_keys_expiration, + }; use crate::CurrentClock; #[tokio::test] @@ -1836,11 +1743,7 @@ mod tests { #[tokio::test] async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { - let mut tracker = private_tracker(); - - tracker.config.private_mode = Some(PrivateMode { - check_keys_expiration: false, - }); + let tracker = private_tracker_without_checking_keys_expiration(); let past_timestamp = Duration::ZERO; @@ -1859,9 +1762,8 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::v2_0_0::core::PrivateMode; - use crate::core::authentication::Key; + use crate::core::authentication::{AddKeyRequest, Key}; use crate::core::tests::the_tracker::private_tracker; - use crate::core::AddKeyRequest; use crate::CurrentClock; #[tokio::test] @@ -1947,9 +1849,8 @@ mod tests { } mod pre_generated_keys { - use crate::core::authentication::Key; + use crate::core::authentication::{AddKeyRequest, Key}; use crate::core::tests::the_tracker::private_tracker; - use crate::core::AddKeyRequest; #[tokio::test] async fn it_should_add_a_pre_generated_key() { diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index 611ea24d2..b1d0d441d 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -14,10 +14,10 @@ use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::Configuration; use super::databases::{self, Database}; -use super::whitelist; use super::whitelist::manager::WhiteListManager; use super::whitelist::repository::in_memory::InMemoryWhitelist; use super::whitelist::repository::persisted::DatabaseWhitelist; +use super::{authentication, whitelist}; use crate::core::Tracker; /// It returns a new tracker building its dependencies. @@ -30,8 +30,9 @@ pub fn initialize_tracker( config: &Configuration, database: &Arc>, whitelist_authorization: &Arc, + authentication: &Arc, ) -> Tracker { - match Tracker::new(&Arc::new(config).core, database, whitelist_authorization) { + match Tracker::new(&Arc::new(config).core, database, whitelist_authorization, authentication) { Ok(tracker) => tracker, Err(error) => { panic!("{}", error) diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 3567de2a9..4081fd6bb 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -132,10 +132,16 @@ mod tests { async fn the_statistics_service_should_return_the_tracker_metrics() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_repository = Arc::new(stats_repository); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &authentication, + )); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 457aa54d8..c23c7e04b 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -142,8 +142,10 @@ mod tests { async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - let tracker = initialize_tracker(&config, &database, &whitelist_authorization); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + let tracker = initialize_tracker(&config, &database, &whitelist_authorization, &authentication); let tracker = Arc::new(tracker); @@ -160,12 +162,19 @@ mod tests { async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &authentication, + )); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()); + let _ = tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()); let torrent_info = get_torrent_info(tracker.clone(), &info_hash).await.unwrap(); @@ -204,8 +213,15 @@ mod tests { async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &authentication, + )); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -216,13 +232,20 @@ mod tests { async fn should_return_a_summarized_info_for_all_torrents() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &authentication, + )); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()); + let _ = tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -241,16 +264,23 @@ mod tests { async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &authentication, + )); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()); - tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); + let _ = tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()); + let _ = tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); let offset = 0; let limit = 1; @@ -264,16 +294,23 @@ mod tests { async fn should_allow_using_pagination_in_the_result() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &authentication, + )); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()); - tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); + let _ = tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()); + let _ = tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); let offset = 1; let limit = 4000; @@ -296,16 +333,23 @@ mod tests { async fn should_return_torrents_ordered_by_info_hash() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &authentication, + )); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()); + let _ = tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()); let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); + let _ = tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index f98770359..a11442a53 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -343,8 +343,8 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::make_rust_tls; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; - use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::core::{authentication, whitelist}; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -369,7 +369,9 @@ mod tests { &in_memory_whitelist.clone(), )); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); + let authentication = Arc::new(authentication::Facade::new(&cfg.core, &database.clone())); + + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); let bind_to = config.bind_address; diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index bb8a98744..bccc7d9eb 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -12,8 +12,8 @@ use super::responses::{ auth_key_response, failed_to_delete_key_response, failed_to_generate_key_response, failed_to_reload_keys_response, invalid_auth_key_duration_response, invalid_auth_key_response, }; -use crate::core::authentication::Key; -use crate::core::{AddKeyRequest, Tracker}; +use crate::core::authentication::{AddKeyRequest, Key}; +use crate::core::Tracker; use crate::servers::apis::v1::context::auth_key::resources::AuthKey; use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_response}; diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index b053628ce..e6370c775 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -247,8 +247,8 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::make_rust_tls; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; - use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::core::{authentication, whitelist}; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::registar::Registar; @@ -268,7 +268,9 @@ mod tests { &in_memory_whitelist.clone(), )); let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); + let authentication = Arc::new(authentication::Facade::new(&cfg.core, &database.clone())); + + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); let config = &http_trackers[0]; diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index fe3825a41..ac39b0422 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -248,10 +248,16 @@ mod tests { /// Initialize tracker's dependencies and tracker. fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = Arc::new(initialize_tracker(config, &database, &whitelist_authorization)); + + let tracker = Arc::new(initialize_tracker( + config, + &database, + &whitelist_authorization, + &authentication, + )); (tracker, stats_event_sender, whitelist_authorization) } diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 58c2d012b..d973735ff 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -133,11 +133,11 @@ mod tests { fn private_tracker() -> (Tracker, Option>) { let config = configuration::ephemeral_private(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( - initialize_tracker(&config, &database, &whitelist_authorization), + initialize_tracker(&config, &database, &whitelist_authorization, &authentication), stats_event_sender, ) } @@ -145,11 +145,11 @@ mod tests { fn whitelisted_tracker() -> (Tracker, Option>) { let config = configuration::ephemeral_listed(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( - initialize_tracker(&config, &database, &whitelist_authorization), + initialize_tracker(&config, &database, &whitelist_authorization, &authentication), stats_event_sender, ) } @@ -157,11 +157,11 @@ mod tests { fn tracker_on_reverse_proxy() -> (Tracker, Option>) { let config = configuration::ephemeral_with_reverse_proxy(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( - initialize_tracker(&config, &database, &whitelist_authorization), + initialize_tracker(&config, &database, &whitelist_authorization, &authentication), stats_event_sender, ) } @@ -169,11 +169,11 @@ mod tests { fn tracker_not_on_reverse_proxy() -> (Tracker, Option>) { let config = configuration::ephemeral_without_reverse_proxy(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( - initialize_tracker(&config, &database, &whitelist_authorization), + initialize_tracker(&config, &database, &whitelist_authorization, &authentication), stats_event_sender, ) } diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 17598904c..929b00ff4 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -73,11 +73,11 @@ mod tests { fn public_tracker() -> (Tracker, Arc>>) { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = initialize_tracker(&config, &database, &whitelist_authorization); + let tracker = initialize_tracker(&config, &database, &whitelist_authorization, &authentication); (tracker, stats_event_sender) } @@ -131,9 +131,10 @@ mod tests { fn test_tracker_factory() -> Tracker { let config = configuration::ephemeral(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); - Tracker::new(&config.core, &database, &whitelist_authorization).unwrap() + Tracker::new(&config.core, &database, &whitelist_authorization, &authentication).unwrap() } #[tokio::test] diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 0a25bccaf..856b2ae72 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -87,9 +87,9 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); - initialize_tracker(&config, &database, &whitelist_authorization) + initialize_tracker(&config, &database, &whitelist_authorization, &authentication) } fn sample_info_hashes() -> Vec { @@ -115,9 +115,9 @@ mod tests { fn test_tracker_factory() -> Tracker { let config = configuration::ephemeral(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); - Tracker::new(&config.core, &database, &whitelist_authorization).unwrap() + Tracker::new(&config.core, &database, &whitelist_authorization, &authentication).unwrap() } mod with_real_data { diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index c01dc2548..67bb35c5a 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -516,12 +516,17 @@ mod tests { } fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { - let (database, in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(config); + let (database, in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = Arc::new(initialize_tracker(config, &database, &whitelist_authorization)); + let tracker = Arc::new(initialize_tracker( + config, + &database, + &whitelist_authorization, + &authentication, + )); ( tracker, @@ -629,9 +634,9 @@ mod tests { fn test_tracker_factory() -> (Arc, Arc) { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(Tracker::new(&config.core, &database, &whitelist_authorization).unwrap()); + let tracker = Arc::new(Tracker::new(&config.core, &database, &whitelist_authorization, &authentication).unwrap()); (tracker, whitelist_authorization) } @@ -989,7 +994,7 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); - tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv6); + let _ = tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv6); } async fn announce_a_new_peer_using_ipv4( @@ -1276,7 +1281,7 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) .into(); - tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv4); + let _ = tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv4); } async fn announce_a_new_peer_using_ipv6( @@ -1376,7 +1381,8 @@ mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - let (database, _in_memory_whitelist, whitelist_authorization) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock @@ -1387,7 +1393,8 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(core::Tracker::new(&config.core, &database, &whitelist_authorization).unwrap()); + let tracker = + Arc::new(core::Tracker::new(&config.core, &database, &whitelist_authorization, &authentication).unwrap()); let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); @@ -1509,7 +1516,7 @@ mod tests { .with_number_of_bytes_left(0) .into(); - tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer); + let _ = tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer); } fn build_scrape_request(remote_addr: &SocketAddr, info_hash: &InfoHash) -> ScrapeRequest { diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index f47e0b1db..078510bcd 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -65,8 +65,8 @@ mod tests { use super::Server; use crate::bootstrap::app::initialize_global_services; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; - use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::core::{authentication, whitelist}; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -88,7 +88,8 @@ mod tests { &in_memory_whitelist.clone(), )); let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); + let authentication = Arc::new(authentication::Facade::new(&cfg.core, &database.clone())); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; @@ -132,8 +133,8 @@ mod tests { &cfg.core, &in_memory_whitelist.clone(), )); - - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); + let authentication = Arc::new(authentication::Facade::new(&cfg.core, &database.clone())); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; diff --git a/src/shared/bit_torrent/common.rs b/src/shared/bit_torrent/common.rs index 5ba2e0492..2f93b5a08 100644 --- a/src/shared/bit_torrent/common.rs +++ b/src/shared/bit_torrent/common.rs @@ -17,6 +17,6 @@ pub const MAX_SCRAPE_TORRENTS: u8 = 74; /// HTTP tracker authentication key length. /// -/// For more information see function [`generate_key`](crate::core::authentication::generate_key) to generate the +/// For more information see function [`generate_key`](crate::core::authentication::key::generate_key) to generate the /// [`PeerKey`](crate::core::authentication::PeerKey). pub const AUTH_KEY_LENGTH: usize = 32; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index a9628f053..3bac7e570 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -37,7 +37,7 @@ where { /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - self.tracker.upsert_peer_and_get_stats(info_hash, peer); + let _ = self.tracker.upsert_peer_and_get_stats(info_hash, peer); } } diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 160cb49f8..a8e5fc572 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -27,7 +27,7 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - self.tracker.upsert_peer_and_get_stats(info_hash, peer); + let _ = self.tracker.upsert_peer_and_get_stats(info_hash, peer); } } diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 43778ef6e..b728509c0 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -36,7 +36,7 @@ where /// Add a torrent to the tracker #[allow(dead_code)] pub fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { - self.tracker.upsert_peer_and_get_stats(info_hash, peer); + let _ = self.tracker.upsert_peer_and_get_stats(info_hash, peer); } } From a0936805c0a6b282a651ace3ec89a43206cca176 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Jan 2025 08:16:18 +0000 Subject: [PATCH 0612/1297] refactor: [#1191] remove authentication wrapper methods from core tracker --- src/app.rs | 1 + src/core/mod.rs | 189 ++++-------------- .../apis/v1/context/auth_key/handlers.rs | 11 +- src/servers/http/v1/handlers/announce.rs | 2 +- src/servers/http/v1/handlers/scrape.rs | 2 +- .../api/v1/contract/context/auth_key.rs | 10 + tests/servers/http/v1/contract.rs | 14 +- 7 files changed, 72 insertions(+), 157 deletions(-) diff --git a/src/app.rs b/src/app.rs index 289db1fdc..da8795ffe 100644 --- a/src/app.rs +++ b/src/app.rs @@ -53,6 +53,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< if app_container.tracker.is_private() { app_container .tracker + .authentication .load_keys_from_database() .await .expect("Could not retrieve keys from database."); diff --git a/src/core/mod.rs b/src/core/mod.rs index 4b8d4c7f2..bd585893d 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -454,19 +454,16 @@ use std::net::IpAddr; use std::sync::Arc; use std::time::Duration; -use authentication::AddKeyRequest; use bittorrent_primitives::info_hash::InfoHash; -use error::PeerKeyError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; +use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; -use self::authentication::Key; use self::torrent::Torrents; use crate::core::databases::Database; use crate::CurrentClock; @@ -495,7 +492,7 @@ pub struct Tracker { torrents: Arc, /// The service to authenticate peers. - authentication: Arc, + pub authentication: Arc, } /// How many peers the peer announcing wants in the announce response. @@ -773,136 +770,6 @@ impl Tracker { } } - /// It authenticates the peer `key` against the `Tracker` authentication - /// key list. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return an error if the the authentication key cannot be verified. - pub async fn authenticate(&self, key: &Key) -> Result<(), authentication::Error> { - self.authentication.authenticate(key).await - } - - /// Adds new peer keys to the tracker. - /// - /// Keys can be pre-generated or randomly created. They can also be permanent or expire. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return an error if: - /// - /// - The key duration overflows the duration type maximum value. - /// - The provided pre-generated key is invalid. - /// - The key could not been persisted due to database issues. - pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { - self.authentication.add_peer_key(add_key_req).await - } - - /// It generates a new permanent authentication key. - /// - /// Authentication keys are used by HTTP trackers. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `auth_key` to the database. - pub async fn generate_permanent_auth_key(&self) -> Result { - self.authentication.generate_auth_key(None).await - } - - /// It generates a new expiring authentication key. - /// - /// Authentication keys are used by HTTP trackers. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `auth_key` to the database. - /// - /// # Arguments - /// - /// * `lifetime` - The duration in seconds for the new key. The key will be - /// no longer valid after `lifetime` seconds. - pub async fn generate_auth_key( - &self, - lifetime: Option, - ) -> Result { - self.authentication.generate_auth_key(lifetime).await - } - - /// It adds a pre-generated permanent authentication key. - /// - /// Authentication keys are used by HTTP trackers. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `auth_key` to the - /// database. For example, if the key already exist. - /// - /// # Arguments - /// - /// * `key` - The pre-generated key. - pub async fn add_permanent_auth_key(&self, key: Key) -> Result { - self.authentication.add_auth_key(key, None).await - } - - /// It adds a pre-generated authentication key. - /// - /// Authentication keys are used by HTTP trackers. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `auth_key` to the - /// database. For example, if the key already exist. - /// - /// # Arguments - /// - /// * `key` - The pre-generated key. - /// * `lifetime` - The duration in seconds for the new key. The key will be - /// no longer valid after `lifetime` seconds. - pub async fn add_auth_key( - &self, - key: Key, - valid_until: Option, - ) -> Result { - self.authentication.add_auth_key(key, valid_until).await - } - - /// It removes an authentication key. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `key` to the database. - pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> { - self.authentication.remove_auth_key(key).await - } - - /// The `Tracker` stores the authentication keys in memory and in the database. - /// In case you need to restart the `Tracker` you can load the keys from the database - /// into memory with this function. Keys are automatically stored in the database when they - /// are generated. - /// - /// # Context: Authentication - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to `load_keys` from the database. - pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> { - self.authentication.load_keys_from_database().await - } - /// It drops the database tables. /// /// # Errors @@ -1664,7 +1531,7 @@ mod tests { let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - let result = tracker.authenticate(&unregistered_key).await; + let result = tracker.authentication.authenticate(&unregistered_key).await; assert!(result.is_err()); } @@ -1682,9 +1549,13 @@ mod tests { async fn it_should_remove_an_authentication_key() { let tracker = private_tracker(); - let expiring_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); + let expiring_key = tracker + .authentication + .generate_auth_key(Some(Duration::from_secs(100))) + .await + .unwrap(); - let result = tracker.remove_auth_key(&expiring_key.key()).await; + let result = tracker.authentication.remove_auth_key(&expiring_key.key()).await; assert!(result.is_ok()); assert!(tracker.authentication.verify_auth_key(&expiring_key.key()).await.is_err()); @@ -1694,12 +1565,16 @@ mod tests { async fn it_should_load_authentication_keys_from_the_database() { let tracker = private_tracker(); - let expiring_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); + let expiring_key = tracker + .authentication + .generate_auth_key(Some(Duration::from_secs(100))) + .await + .unwrap(); // Remove the newly generated key in memory tracker.authentication.remove_in_memory_auth_key(&expiring_key.key()).await; - let result = tracker.load_keys_from_database().await; + let result = tracker.authentication.load_keys_from_database().await; assert!(result.is_ok()); assert!(tracker.authentication.verify_auth_key(&expiring_key.key()).await.is_ok()); @@ -1722,7 +1597,11 @@ mod tests { async fn it_should_generate_the_key() { let tracker = private_tracker(); - let peer_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); + let peer_key = tracker + .authentication + .generate_auth_key(Some(Duration::from_secs(100))) + .await + .unwrap(); assert_eq!( peer_key.valid_until, @@ -1734,9 +1613,13 @@ mod tests { async fn it_should_authenticate_a_peer_with_the_key() { let tracker = private_tracker(); - let peer_key = tracker.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); + let peer_key = tracker + .authentication + .generate_auth_key(Some(Duration::from_secs(100))) + .await + .unwrap(); - let result = tracker.authenticate(&peer_key.key()).await; + let result = tracker.authentication.authenticate(&peer_key.key()).await; assert!(result.is_ok()); } @@ -1748,11 +1631,12 @@ mod tests { let past_timestamp = Duration::ZERO; let peer_key = tracker + .authentication .add_auth_key(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), Some(past_timestamp)) .await .unwrap(); - assert!(tracker.authenticate(&peer_key.key()).await.is_ok()); + assert!(tracker.authentication.authenticate(&peer_key.key()).await.is_ok()); } } @@ -1771,6 +1655,7 @@ mod tests { let tracker = private_tracker(); let peer_key = tracker + .authentication .add_peer_key(AddKeyRequest { opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), opt_seconds_valid: Some(100), @@ -1789,6 +1674,7 @@ mod tests { let tracker = private_tracker(); let peer_key = tracker + .authentication .add_peer_key(AddKeyRequest { opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), opt_seconds_valid: Some(100), @@ -1796,7 +1682,7 @@ mod tests { .await .unwrap(); - let result = tracker.authenticate(&peer_key.key()).await; + let result = tracker.authentication.authenticate(&peer_key.key()).await; assert!(result.is_ok()); } @@ -1810,6 +1696,7 @@ mod tests { }); let peer_key = tracker + .authentication .add_peer_key(AddKeyRequest { opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), opt_seconds_valid: Some(0), @@ -1817,7 +1704,7 @@ mod tests { .await .unwrap(); - assert!(tracker.authenticate(&peer_key.key()).await.is_ok()); + assert!(tracker.authentication.authenticate(&peer_key.key()).await.is_ok()); } } } @@ -1831,7 +1718,7 @@ mod tests { async fn it_should_generate_the_key() { let tracker = private_tracker(); - let peer_key = tracker.generate_permanent_auth_key().await.unwrap(); + let peer_key = tracker.authentication.generate_permanent_auth_key().await.unwrap(); assert_eq!(peer_key.valid_until, None); } @@ -1840,9 +1727,9 @@ mod tests { async fn it_should_authenticate_a_peer_with_the_key() { let tracker = private_tracker(); - let peer_key = tracker.generate_permanent_auth_key().await.unwrap(); + let peer_key = tracker.authentication.generate_permanent_auth_key().await.unwrap(); - let result = tracker.authenticate(&peer_key.key()).await; + let result = tracker.authentication.authenticate(&peer_key.key()).await; assert!(result.is_ok()); } @@ -1857,6 +1744,7 @@ mod tests { let tracker = private_tracker(); let peer_key = tracker + .authentication .add_peer_key(AddKeyRequest { opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), opt_seconds_valid: None, @@ -1872,6 +1760,7 @@ mod tests { let tracker = private_tracker(); let peer_key = tracker + .authentication .add_peer_key(AddKeyRequest { opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), opt_seconds_valid: None, @@ -1879,7 +1768,7 @@ mod tests { .await .unwrap(); - let result = tracker.authenticate(&peer_key.key()).await; + let result = tracker.authentication.authenticate(&peer_key.key()).await; assert!(result.is_ok()); } diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index bccc7d9eb..ba345d8a5 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -35,6 +35,7 @@ pub async fn add_auth_key_handler( extract::Json(add_key_form): extract::Json, ) -> Response { match tracker + .authentication .add_peer_key(AddKeyRequest { opt_key: add_key_form.opt_key.clone(), opt_seconds_valid: add_key_form.opt_seconds_valid, @@ -67,7 +68,11 @@ pub async fn add_auth_key_handler( /// This endpoint has been deprecated. Use [`add_auth_key_handler`]. pub async fn generate_auth_key_handler(State(tracker): State>, Path(seconds_valid_or_key): Path) -> Response { let seconds_valid = seconds_valid_or_key; - match tracker.generate_auth_key(Some(Duration::from_secs(seconds_valid))).await { + match tracker + .authentication + .generate_auth_key(Some(Duration::from_secs(seconds_valid))) + .await + { Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), Err(e) => failed_to_generate_key_response(e), } @@ -108,7 +113,7 @@ pub async fn delete_auth_key_handler( ) -> Response { match Key::from_str(&seconds_valid_or_key.0) { Err(_) => invalid_auth_key_param_response(&seconds_valid_or_key.0), - Ok(key) => match tracker.remove_auth_key(&key).await { + Ok(key) => match tracker.authentication.remove_auth_key(&key).await { Ok(()) => ok_response(), Err(e) => failed_to_delete_key_response(e), }, @@ -128,7 +133,7 @@ pub async fn delete_auth_key_handler( /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#reload-authentication-keys) /// for more information about this endpoint. pub async fn reload_keys_handler(State(tracker): State>) -> Response { - match tracker.load_keys_from_database().await { + match tracker.authentication.load_keys_from_database().await { Ok(()) => ok_response(), Err(e) => failed_to_reload_keys_response(e), } diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index ac39b0422..7af2b9261 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -113,7 +113,7 @@ async fn handle_announce( // Authentication if tracker.requires_authentication() { match maybe_key { - Some(key) => match tracker.authenticate(&key).await { + Some(key) => match tracker.authentication.authenticate(&key).await { Ok(()) => (), Err(error) => return Err(responses::error::Error::from(error)), }, diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index d973735ff..062a017f8 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -84,7 +84,7 @@ async fn handle_scrape( // Authentication let return_real_scrape_data = if tracker.requires_authentication() { match maybe_key { - Some(key) => match tracker.authenticate(&key).await { + Some(key) => match tracker.authentication.authenticate(&key).await { Ok(()) => true, Err(_error) => false, }, diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 40c10be5f..cee6b4034 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -37,6 +37,7 @@ async fn should_allow_generating_a_new_random_auth_key() { assert!(env .tracker + .authentication .authenticate(&auth_key_resource.key.parse::().unwrap()) .await .is_ok()); @@ -66,6 +67,7 @@ async fn should_allow_uploading_a_preexisting_auth_key() { assert!(env .tracker + .authentication .authenticate(&auth_key_resource.key.parse::().unwrap()) .await .is_ok()); @@ -159,6 +161,7 @@ async fn should_allow_deleting_an_auth_key() { let seconds_valid = 60; let auth_key = env .tracker + .authentication .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -293,6 +296,7 @@ async fn should_fail_when_the_auth_key_cannot_be_deleted() { let seconds_valid = 60; let auth_key = env .tracker + .authentication .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -326,6 +330,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { // Generate new auth key let auth_key = env .tracker + .authentication .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -346,6 +351,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { // Generate new auth key let auth_key = env .tracker + .authentication .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -374,6 +380,7 @@ async fn should_allow_reloading_keys() { let seconds_valid = 60; env.tracker + .authentication .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -399,6 +406,7 @@ async fn should_fail_when_keys_cannot_be_reloaded() { let seconds_valid = 60; env.tracker + .authentication .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -427,6 +435,7 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { let seconds_valid = 60; env.tracker + .authentication .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -491,6 +500,7 @@ mod deprecated_generate_key_endpoint { assert!(env .tracker + .authentication .authenticate(&auth_key_resource.key.parse::().unwrap()) .await .is_ok()); diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 961caf017..d8b1c92c2 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -1396,7 +1396,12 @@ mod configured_as_private { let env = Started::new(&configuration::ephemeral_private().into()).await; - let expiring_key = env.tracker.generate_auth_key(Some(Duration::from_secs(60))).await.unwrap(); + let expiring_key = env + .tracker + .authentication + .generate_auth_key(Some(Duration::from_secs(60))) + .await + .unwrap(); let response = Client::authenticated(*env.bind_address(), expiring_key.key()) .announce(&QueryBuilder::default().query()) @@ -1541,7 +1546,12 @@ mod configured_as_private { .build(), ); - let expiring_key = env.tracker.generate_auth_key(Some(Duration::from_secs(60))).await.unwrap(); + let expiring_key = env + .tracker + .authentication + .generate_auth_key(Some(Duration::from_secs(60))) + .await + .unwrap(); let response = Client::authenticated(*env.bind_address(), expiring_key.key()) .scrape( From 9a60c0c7e084cd6a1256e5b4edcec4d5297f965a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Jan 2025 11:31:38 +0000 Subject: [PATCH 0613/1297] refactor: [#11191] copy private tracker tests to authentication module --- src/core/authentication/mod.rs | 298 +++++++++++++++++++++++++++++++++ 1 file changed, 298 insertions(+) diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index d03502988..70101dbf6 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -302,3 +302,301 @@ impl Facade { Ok(()) } } + +#[cfg(test)] +mod tests { + + mod the_tracker { + + use torrust_tracker_configuration::v2_0_0::core::PrivateMode; + use torrust_tracker_test_helpers::configuration; + + use crate::app_test::initialize_tracker_dependencies; + use crate::core::services::initialize_tracker; + use crate::core::Tracker; + + fn private_tracker() -> Tracker { + let config = configuration::ephemeral_private(); + + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + initialize_tracker(&config, &database, &whitelist_authorization, &authentication) + } + + fn private_tracker_without_checking_keys_expiration() -> Tracker { + let mut config = configuration::ephemeral_private(); + + config.core.private_mode = Some(PrivateMode { + check_keys_expiration: false, + }); + + let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + initialize_tracker_dependencies(&config); + + initialize_tracker(&config, &database, &whitelist_authorization, &authentication) + } + + mod configured_as_private { + + mod handling_authentication { + use std::str::FromStr; + use std::time::Duration; + + use crate::core::authentication::tests::the_tracker::private_tracker; + use crate::core::authentication::{self}; + + #[tokio::test] + async fn it_should_fail_authenticating_a_peer_when_it_uses_an_unregistered_key() { + let tracker = private_tracker(); + + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + let result = tracker.authentication.authenticate(&unregistered_key).await; + + assert!(result.is_err()); + } + + #[tokio::test] + async fn it_should_fail_verifying_an_unregistered_authentication_key() { + let tracker = private_tracker(); + + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + assert!(tracker.authentication.verify_auth_key(&unregistered_key).await.is_err()); + } + + #[tokio::test] + async fn it_should_remove_an_authentication_key() { + let tracker = private_tracker(); + + let expiring_key = tracker + .authentication + .generate_auth_key(Some(Duration::from_secs(100))) + .await + .unwrap(); + + let result = tracker.authentication.remove_auth_key(&expiring_key.key()).await; + + assert!(result.is_ok()); + assert!(tracker.authentication.verify_auth_key(&expiring_key.key()).await.is_err()); + } + + #[tokio::test] + async fn it_should_load_authentication_keys_from_the_database() { + let tracker = private_tracker(); + + let expiring_key = tracker + .authentication + .generate_auth_key(Some(Duration::from_secs(100))) + .await + .unwrap(); + + // Remove the newly generated key in memory + tracker.authentication.remove_in_memory_auth_key(&expiring_key.key()).await; + + let result = tracker.authentication.load_keys_from_database().await; + + assert!(result.is_ok()); + assert!(tracker.authentication.verify_auth_key(&expiring_key.key()).await.is_ok()); + } + + mod with_expiring_and { + + mod randomly_generated_keys { + use std::time::Duration; + + use torrust_tracker_clock::clock::Time; + + use crate::core::authentication::tests::the_tracker::{ + private_tracker, private_tracker_without_checking_keys_expiration, + }; + use crate::core::authentication::Key; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_generate_the_key() { + let tracker = private_tracker(); + + let peer_key = tracker + .authentication + .generate_auth_key(Some(Duration::from_secs(100))) + .await + .unwrap(); + + assert_eq!( + peer_key.valid_until, + Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + ); + } + + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let tracker = private_tracker(); + + let peer_key = tracker + .authentication + .generate_auth_key(Some(Duration::from_secs(100))) + .await + .unwrap(); + + let result = tracker.authentication.authenticate(&peer_key.key()).await; + + assert!(result.is_ok()); + } + + #[tokio::test] + async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { + let tracker = private_tracker_without_checking_keys_expiration(); + + let past_timestamp = Duration::ZERO; + + let peer_key = tracker + .authentication + .add_auth_key(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), Some(past_timestamp)) + .await + .unwrap(); + + assert!(tracker.authentication.authenticate(&peer_key.key()).await.is_ok()); + } + } + + mod pre_generated_keys { + use std::time::Duration; + + use torrust_tracker_clock::clock::Time; + + use crate::core::authentication::tests::the_tracker::{ + private_tracker, private_tracker_without_checking_keys_expiration, + }; + use crate::core::authentication::{AddKeyRequest, Key}; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_add_a_pre_generated_key() { + let tracker = private_tracker(); + + let peer_key = tracker + .authentication + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(100), + }) + .await + .unwrap(); + + assert_eq!( + peer_key.valid_until, + Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + ); + } + + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let tracker = private_tracker(); + + let peer_key = tracker + .authentication + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(100), + }) + .await + .unwrap(); + + let result = tracker.authentication.authenticate(&peer_key.key()).await; + + assert!(result.is_ok()); + } + + #[tokio::test] + async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { + let tracker = private_tracker_without_checking_keys_expiration(); + + let peer_key = tracker + .authentication + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(0), + }) + .await + .unwrap(); + + assert!(tracker.authentication.authenticate(&peer_key.key()).await.is_ok()); + } + } + } + + mod with_permanent_and { + + mod randomly_generated_keys { + use crate::core::authentication::tests::the_tracker::private_tracker; + + #[tokio::test] + async fn it_should_generate_the_key() { + let tracker = private_tracker(); + + let peer_key = tracker.authentication.generate_permanent_auth_key().await.unwrap(); + + assert_eq!(peer_key.valid_until, None); + } + + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let tracker = private_tracker(); + + let peer_key = tracker.authentication.generate_permanent_auth_key().await.unwrap(); + + let result = tracker.authentication.authenticate(&peer_key.key()).await; + + assert!(result.is_ok()); + } + } + + mod pre_generated_keys { + use crate::core::authentication::tests::the_tracker::private_tracker; + use crate::core::authentication::{AddKeyRequest, Key}; + + #[tokio::test] + async fn it_should_add_a_pre_generated_key() { + let tracker = private_tracker(); + + let peer_key = tracker + .authentication + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: None, + }) + .await + .unwrap(); + + assert_eq!(peer_key.valid_until, None); + } + + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let tracker = private_tracker(); + + let peer_key = tracker + .authentication + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: None, + }) + .await + .unwrap(); + + let result = tracker.authentication.authenticate(&peer_key.key()).await; + + assert!(result.is_ok()); + } + } + } + } + + mod handling_an_announce_request {} + + mod handling_an_scrape_request {} + } + } +} From f41a524e46788a3ba819442c4aec2359adba4c89 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Jan 2025 11:37:04 +0000 Subject: [PATCH 0614/1297] refactor: [#1191] remove duplicate tests for private tracker There were copied to the authentication module. --- src/core/mod.rs | 295 ------------------------------------------------ 1 file changed, 295 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index bd585893d..9a5692690 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -803,7 +803,6 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_configuration::v2_0_0::core::PrivateMode; use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; @@ -823,15 +822,6 @@ mod tests { initialize_tracker(&config, &database, &whitelist_authorization, &authentication) } - fn private_tracker() -> Tracker { - let config = configuration::ephemeral_private(); - - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = - initialize_tracker_dependencies(&config); - - initialize_tracker(&config, &database, &whitelist_authorization, &authentication) - } - fn whitelisted_tracker() -> (Tracker, Arc, Arc) { let config = configuration::ephemeral_listed(); @@ -845,19 +835,6 @@ mod tests { (tracker, whitelist_authorization, whitelist_manager) } - fn private_tracker_without_checking_keys_expiration() -> Tracker { - let mut config = configuration::ephemeral_private(); - - config.core.private_mode = Some(PrivateMode { - check_keys_expiration: false, - }); - - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = - initialize_tracker_dependencies(&config); - - initialize_tracker(&config, &database, &whitelist_authorization, &authentication) - } - pub fn tracker_persisting_torrents_in_database() -> Tracker { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; @@ -1516,278 +1493,6 @@ mod tests { } } - mod configured_as_private { - - mod handling_authentication { - use std::str::FromStr; - use std::time::Duration; - - use crate::core::authentication::{self}; - use crate::core::tests::the_tracker::private_tracker; - - #[tokio::test] - async fn it_should_fail_authenticating_a_peer_when_it_uses_an_unregistered_key() { - let tracker = private_tracker(); - - let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - - let result = tracker.authentication.authenticate(&unregistered_key).await; - - assert!(result.is_err()); - } - - #[tokio::test] - async fn it_should_fail_verifying_an_unregistered_authentication_key() { - let tracker = private_tracker(); - - let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - - assert!(tracker.authentication.verify_auth_key(&unregistered_key).await.is_err()); - } - - #[tokio::test] - async fn it_should_remove_an_authentication_key() { - let tracker = private_tracker(); - - let expiring_key = tracker - .authentication - .generate_auth_key(Some(Duration::from_secs(100))) - .await - .unwrap(); - - let result = tracker.authentication.remove_auth_key(&expiring_key.key()).await; - - assert!(result.is_ok()); - assert!(tracker.authentication.verify_auth_key(&expiring_key.key()).await.is_err()); - } - - #[tokio::test] - async fn it_should_load_authentication_keys_from_the_database() { - let tracker = private_tracker(); - - let expiring_key = tracker - .authentication - .generate_auth_key(Some(Duration::from_secs(100))) - .await - .unwrap(); - - // Remove the newly generated key in memory - tracker.authentication.remove_in_memory_auth_key(&expiring_key.key()).await; - - let result = tracker.authentication.load_keys_from_database().await; - - assert!(result.is_ok()); - assert!(tracker.authentication.verify_auth_key(&expiring_key.key()).await.is_ok()); - } - - mod with_expiring_and { - - mod randomly_generated_keys { - use std::time::Duration; - - use torrust_tracker_clock::clock::Time; - - use crate::core::authentication::Key; - use crate::core::tests::the_tracker::{ - private_tracker, private_tracker_without_checking_keys_expiration, - }; - use crate::CurrentClock; - - #[tokio::test] - async fn it_should_generate_the_key() { - let tracker = private_tracker(); - - let peer_key = tracker - .authentication - .generate_auth_key(Some(Duration::from_secs(100))) - .await - .unwrap(); - - assert_eq!( - peer_key.valid_until, - Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) - ); - } - - #[tokio::test] - async fn it_should_authenticate_a_peer_with_the_key() { - let tracker = private_tracker(); - - let peer_key = tracker - .authentication - .generate_auth_key(Some(Duration::from_secs(100))) - .await - .unwrap(); - - let result = tracker.authentication.authenticate(&peer_key.key()).await; - - assert!(result.is_ok()); - } - - #[tokio::test] - async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { - let tracker = private_tracker_without_checking_keys_expiration(); - - let past_timestamp = Duration::ZERO; - - let peer_key = tracker - .authentication - .add_auth_key(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), Some(past_timestamp)) - .await - .unwrap(); - - assert!(tracker.authentication.authenticate(&peer_key.key()).await.is_ok()); - } - } - - mod pre_generated_keys { - use std::time::Duration; - - use torrust_tracker_clock::clock::Time; - use torrust_tracker_configuration::v2_0_0::core::PrivateMode; - - use crate::core::authentication::{AddKeyRequest, Key}; - use crate::core::tests::the_tracker::private_tracker; - use crate::CurrentClock; - - #[tokio::test] - async fn it_should_add_a_pre_generated_key() { - let tracker = private_tracker(); - - let peer_key = tracker - .authentication - .add_peer_key(AddKeyRequest { - opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: Some(100), - }) - .await - .unwrap(); - - assert_eq!( - peer_key.valid_until, - Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) - ); - } - - #[tokio::test] - async fn it_should_authenticate_a_peer_with_the_key() { - let tracker = private_tracker(); - - let peer_key = tracker - .authentication - .add_peer_key(AddKeyRequest { - opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: Some(100), - }) - .await - .unwrap(); - - let result = tracker.authentication.authenticate(&peer_key.key()).await; - - assert!(result.is_ok()); - } - - #[tokio::test] - async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { - let mut tracker = private_tracker(); - - tracker.config.private_mode = Some(PrivateMode { - check_keys_expiration: false, - }); - - let peer_key = tracker - .authentication - .add_peer_key(AddKeyRequest { - opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: Some(0), - }) - .await - .unwrap(); - - assert!(tracker.authentication.authenticate(&peer_key.key()).await.is_ok()); - } - } - } - - mod with_permanent_and { - - mod randomly_generated_keys { - use crate::core::tests::the_tracker::private_tracker; - - #[tokio::test] - async fn it_should_generate_the_key() { - let tracker = private_tracker(); - - let peer_key = tracker.authentication.generate_permanent_auth_key().await.unwrap(); - - assert_eq!(peer_key.valid_until, None); - } - - #[tokio::test] - async fn it_should_authenticate_a_peer_with_the_key() { - let tracker = private_tracker(); - - let peer_key = tracker.authentication.generate_permanent_auth_key().await.unwrap(); - - let result = tracker.authentication.authenticate(&peer_key.key()).await; - - assert!(result.is_ok()); - } - } - - mod pre_generated_keys { - use crate::core::authentication::{AddKeyRequest, Key}; - use crate::core::tests::the_tracker::private_tracker; - - #[tokio::test] - async fn it_should_add_a_pre_generated_key() { - let tracker = private_tracker(); - - let peer_key = tracker - .authentication - .add_peer_key(AddKeyRequest { - opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: None, - }) - .await - .unwrap(); - - assert_eq!(peer_key.valid_until, None); - } - - #[tokio::test] - async fn it_should_authenticate_a_peer_with_the_key() { - let tracker = private_tracker(); - - let peer_key = tracker - .authentication - .add_peer_key(AddKeyRequest { - opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: None, - }) - .await - .unwrap(); - - let result = tracker.authentication.authenticate(&peer_key.key()).await; - - assert!(result.is_ok()); - } - } - } - } - - mod handling_an_announce_request {} - - mod handling_an_scrape_request {} - } - - mod configured_as_private_and_whitelisted { - - mod handling_an_announce_request {} - - mod handling_an_scrape_request {} - } - mod handling_torrent_persistence { use aquatic_udp_protocol::AnnounceEvent; From 6584fe434067c3a8c5eb12d5aa108df817291ccb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Jan 2025 11:54:13 +0000 Subject: [PATCH 0615/1297] refactor: [#1191] remove tracker dependency for authentication tests --- src/core/authentication/mod.rs | 407 +++++++++++++++------------------ 1 file changed, 190 insertions(+), 217 deletions(-) diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 70101dbf6..d611ae57e 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -306,297 +306,270 @@ impl Facade { #[cfg(test)] mod tests { - mod the_tracker { + mod the_tracker_configured_as_private { + + use std::str::FromStr; + use std::time::Duration; use torrust_tracker_configuration::v2_0_0::core::PrivateMode; use torrust_tracker_test_helpers::configuration; - use crate::app_test::initialize_tracker_dependencies; - use crate::core::services::initialize_tracker; - use crate::core::Tracker; + use crate::core::authentication; + use crate::core::services::initialize_database; - fn private_tracker() -> Tracker { + fn instantiate_authentication() -> authentication::Facade { let config = configuration::ephemeral_private(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = - initialize_tracker_dependencies(&config); - - initialize_tracker(&config, &database, &whitelist_authorization, &authentication) + let database = initialize_database(&config); + authentication::Facade::new(&config.core, &database.clone()) } - fn private_tracker_without_checking_keys_expiration() -> Tracker { + fn instantiate_authentication_with_checking_keys_expiration_disabled() -> authentication::Facade { let mut config = configuration::ephemeral_private(); config.core.private_mode = Some(PrivateMode { check_keys_expiration: false, }); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = - initialize_tracker_dependencies(&config); + let database = initialize_database(&config); + authentication::Facade::new(&config.core, &database.clone()) + } + + #[tokio::test] + async fn it_should_fail_authenticating_a_peer_when_it_uses_an_unregistered_key() { + let authentication = instantiate_authentication(); + + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - initialize_tracker(&config, &database, &whitelist_authorization, &authentication) + let result = authentication.authenticate(&unregistered_key).await; + + assert!(result.is_err()); } - mod configured_as_private { + #[tokio::test] + async fn it_should_fail_verifying_an_unregistered_authentication_key() { + let authentication = instantiate_authentication(); - mod handling_authentication { - use std::str::FromStr; - use std::time::Duration; + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - use crate::core::authentication::tests::the_tracker::private_tracker; - use crate::core::authentication::{self}; + assert!(authentication.verify_auth_key(&unregistered_key).await.is_err()); + } - #[tokio::test] - async fn it_should_fail_authenticating_a_peer_when_it_uses_an_unregistered_key() { - let tracker = private_tracker(); + #[tokio::test] + async fn it_should_remove_an_authentication_key() { + let authentication = instantiate_authentication(); - let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + let expiring_key = authentication + .generate_auth_key(Some(Duration::from_secs(100))) + .await + .unwrap(); - let result = tracker.authentication.authenticate(&unregistered_key).await; + let result = authentication.remove_auth_key(&expiring_key.key()).await; - assert!(result.is_err()); - } + assert!(result.is_ok()); + assert!(authentication.verify_auth_key(&expiring_key.key()).await.is_err()); + } - #[tokio::test] - async fn it_should_fail_verifying_an_unregistered_authentication_key() { - let tracker = private_tracker(); + #[tokio::test] + async fn it_should_load_authentication_keys_from_the_database() { + let authentication = instantiate_authentication(); - let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + let expiring_key = authentication + .generate_auth_key(Some(Duration::from_secs(100))) + .await + .unwrap(); - assert!(tracker.authentication.verify_auth_key(&unregistered_key).await.is_err()); - } + // Remove the newly generated key in memory + authentication.remove_in_memory_auth_key(&expiring_key.key()).await; + + let result = authentication.load_keys_from_database().await; + + assert!(result.is_ok()); + assert!(authentication.verify_auth_key(&expiring_key.key()).await.is_ok()); + } + + mod with_expiring_and { + + mod randomly_generated_keys { + use std::time::Duration; + + use torrust_tracker_clock::clock::Time; + + use crate::core::authentication::tests::the_tracker_configured_as_private::{ + instantiate_authentication, instantiate_authentication_with_checking_keys_expiration_disabled, + }; + use crate::core::authentication::Key; + use crate::CurrentClock; #[tokio::test] - async fn it_should_remove_an_authentication_key() { - let tracker = private_tracker(); + async fn it_should_generate_the_key() { + let authentication = instantiate_authentication(); - let expiring_key = tracker - .authentication + let peer_key = authentication .generate_auth_key(Some(Duration::from_secs(100))) .await .unwrap(); - let result = tracker.authentication.remove_auth_key(&expiring_key.key()).await; - - assert!(result.is_ok()); - assert!(tracker.authentication.verify_auth_key(&expiring_key.key()).await.is_err()); + assert_eq!( + peer_key.valid_until, + Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + ); } #[tokio::test] - async fn it_should_load_authentication_keys_from_the_database() { - let tracker = private_tracker(); + async fn it_should_authenticate_a_peer_with_the_key() { + let authentication = instantiate_authentication(); - let expiring_key = tracker - .authentication + let peer_key = authentication .generate_auth_key(Some(Duration::from_secs(100))) .await .unwrap(); - // Remove the newly generated key in memory - tracker.authentication.remove_in_memory_auth_key(&expiring_key.key()).await; - - let result = tracker.authentication.load_keys_from_database().await; + let result = authentication.authenticate(&peer_key.key()).await; assert!(result.is_ok()); - assert!(tracker.authentication.verify_auth_key(&expiring_key.key()).await.is_ok()); } - mod with_expiring_and { + #[tokio::test] + async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { + let authentication = instantiate_authentication_with_checking_keys_expiration_disabled(); - mod randomly_generated_keys { - use std::time::Duration; + let past_timestamp = Duration::ZERO; - use torrust_tracker_clock::clock::Time; + let peer_key = authentication + .add_auth_key(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), Some(past_timestamp)) + .await + .unwrap(); - use crate::core::authentication::tests::the_tracker::{ - private_tracker, private_tracker_without_checking_keys_expiration, - }; - use crate::core::authentication::Key; - use crate::CurrentClock; + assert!(authentication.authenticate(&peer_key.key()).await.is_ok()); + } + } - #[tokio::test] - async fn it_should_generate_the_key() { - let tracker = private_tracker(); + mod pre_generated_keys { + use std::time::Duration; - let peer_key = tracker - .authentication - .generate_auth_key(Some(Duration::from_secs(100))) - .await - .unwrap(); + use torrust_tracker_clock::clock::Time; - assert_eq!( - peer_key.valid_until, - Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) - ); - } + use crate::core::authentication::tests::the_tracker_configured_as_private::{ + instantiate_authentication, instantiate_authentication_with_checking_keys_expiration_disabled, + }; + use crate::core::authentication::{AddKeyRequest, Key}; + use crate::CurrentClock; - #[tokio::test] - async fn it_should_authenticate_a_peer_with_the_key() { - let tracker = private_tracker(); + #[tokio::test] + async fn it_should_add_a_pre_generated_key() { + let authentication = instantiate_authentication(); + + let peer_key = authentication + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(100), + }) + .await + .unwrap(); - let peer_key = tracker - .authentication - .generate_auth_key(Some(Duration::from_secs(100))) - .await - .unwrap(); + assert_eq!( + peer_key.valid_until, + Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + ); + } - let result = tracker.authentication.authenticate(&peer_key.key()).await; + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let authentication = instantiate_authentication(); + + let peer_key = authentication + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(100), + }) + .await + .unwrap(); - assert!(result.is_ok()); - } + let result = authentication.authenticate(&peer_key.key()).await; - #[tokio::test] - async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { - let tracker = private_tracker_without_checking_keys_expiration(); + assert!(result.is_ok()); + } - let past_timestamp = Duration::ZERO; + #[tokio::test] + async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { + let authentication = instantiate_authentication_with_checking_keys_expiration_disabled(); + + let peer_key = authentication + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(0), + }) + .await + .unwrap(); - let peer_key = tracker - .authentication - .add_auth_key(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), Some(past_timestamp)) - .await - .unwrap(); + assert!(authentication.authenticate(&peer_key.key()).await.is_ok()); + } + } + } - assert!(tracker.authentication.authenticate(&peer_key.key()).await.is_ok()); - } - } + mod with_permanent_and { - mod pre_generated_keys { - use std::time::Duration; - - use torrust_tracker_clock::clock::Time; - - use crate::core::authentication::tests::the_tracker::{ - private_tracker, private_tracker_without_checking_keys_expiration, - }; - use crate::core::authentication::{AddKeyRequest, Key}; - use crate::CurrentClock; - - #[tokio::test] - async fn it_should_add_a_pre_generated_key() { - let tracker = private_tracker(); - - let peer_key = tracker - .authentication - .add_peer_key(AddKeyRequest { - opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: Some(100), - }) - .await - .unwrap(); - - assert_eq!( - peer_key.valid_until, - Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) - ); - } - - #[tokio::test] - async fn it_should_authenticate_a_peer_with_the_key() { - let tracker = private_tracker(); - - let peer_key = tracker - .authentication - .add_peer_key(AddKeyRequest { - opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: Some(100), - }) - .await - .unwrap(); - - let result = tracker.authentication.authenticate(&peer_key.key()).await; - - assert!(result.is_ok()); - } - - #[tokio::test] - async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { - let tracker = private_tracker_without_checking_keys_expiration(); - - let peer_key = tracker - .authentication - .add_peer_key(AddKeyRequest { - opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: Some(0), - }) - .await - .unwrap(); - - assert!(tracker.authentication.authenticate(&peer_key.key()).await.is_ok()); - } - } - } + mod randomly_generated_keys { + use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_authentication; - mod with_permanent_and { + #[tokio::test] + async fn it_should_generate_the_key() { + let authentication = instantiate_authentication(); - mod randomly_generated_keys { - use crate::core::authentication::tests::the_tracker::private_tracker; + let peer_key = authentication.generate_permanent_auth_key().await.unwrap(); - #[tokio::test] - async fn it_should_generate_the_key() { - let tracker = private_tracker(); + assert_eq!(peer_key.valid_until, None); + } - let peer_key = tracker.authentication.generate_permanent_auth_key().await.unwrap(); + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let authentication = instantiate_authentication(); - assert_eq!(peer_key.valid_until, None); - } + let peer_key = authentication.generate_permanent_auth_key().await.unwrap(); - #[tokio::test] - async fn it_should_authenticate_a_peer_with_the_key() { - let tracker = private_tracker(); + let result = authentication.authenticate(&peer_key.key()).await; - let peer_key = tracker.authentication.generate_permanent_auth_key().await.unwrap(); + assert!(result.is_ok()); + } + } - let result = tracker.authentication.authenticate(&peer_key.key()).await; + mod pre_generated_keys { + use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_authentication; + use crate::core::authentication::{AddKeyRequest, Key}; - assert!(result.is_ok()); - } - } + #[tokio::test] + async fn it_should_add_a_pre_generated_key() { + let authentication = instantiate_authentication(); + + let peer_key = authentication + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: None, + }) + .await + .unwrap(); - mod pre_generated_keys { - use crate::core::authentication::tests::the_tracker::private_tracker; - use crate::core::authentication::{AddKeyRequest, Key}; - - #[tokio::test] - async fn it_should_add_a_pre_generated_key() { - let tracker = private_tracker(); - - let peer_key = tracker - .authentication - .add_peer_key(AddKeyRequest { - opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: None, - }) - .await - .unwrap(); - - assert_eq!(peer_key.valid_until, None); - } - - #[tokio::test] - async fn it_should_authenticate_a_peer_with_the_key() { - let tracker = private_tracker(); - - let peer_key = tracker - .authentication - .add_peer_key(AddKeyRequest { - opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: None, - }) - .await - .unwrap(); - - let result = tracker.authentication.authenticate(&peer_key.key()).await; - - assert!(result.is_ok()); - } - } + assert_eq!(peer_key.valid_until, None); } - } - mod handling_an_announce_request {} + #[tokio::test] + async fn it_should_authenticate_a_peer_with_the_key() { + let authentication = instantiate_authentication(); + + let peer_key = authentication + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: None, + }) + .await + .unwrap(); + + let result = authentication.authenticate(&peer_key.key()).await; - mod handling_an_scrape_request {} + assert!(result.is_ok()); + } + } } } } From 44255e243c062ad2a101a426c9c02f03b1cfb5d2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Jan 2025 16:45:36 +0000 Subject: [PATCH 0616/1297] refactor: [#1195] create dir for mod We will add more submodules. --- src/core/authentication/{key.rs => key/mod.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/core/authentication/{key.rs => key/mod.rs} (100%) diff --git a/src/core/authentication/key.rs b/src/core/authentication/key/mod.rs similarity index 100% rename from src/core/authentication/key.rs rename to src/core/authentication/key/mod.rs From f4c7b9746562a45331d108b11ebe7dc794253a2a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Jan 2025 17:08:47 +0000 Subject: [PATCH 0617/1297] refactor: [#1195] extract DatabaseKeyRepository --- src/core/authentication/key/mod.rs | 1 + src/core/authentication/key/repository/mod.rs | 1 + .../key/repository/persisted.rs | 48 +++++++++++++++++++ src/core/authentication/mod.rs | 23 +++++---- 4 files changed, 64 insertions(+), 9 deletions(-) create mode 100644 src/core/authentication/key/repository/mod.rs create mode 100644 src/core/authentication/key/repository/persisted.rs diff --git a/src/core/authentication/key/mod.rs b/src/core/authentication/key/mod.rs index 8858361ec..49d559e42 100644 --- a/src/core/authentication/key/mod.rs +++ b/src/core/authentication/key/mod.rs @@ -37,6 +37,7 @@ //! //! assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); //! ``` +pub mod repository; use std::panic::Location; use std::str::FromStr; diff --git a/src/core/authentication/key/repository/mod.rs b/src/core/authentication/key/repository/mod.rs new file mode 100644 index 000000000..fe3bdd68c --- /dev/null +++ b/src/core/authentication/key/repository/mod.rs @@ -0,0 +1 @@ +pub mod persisted; diff --git a/src/core/authentication/key/repository/persisted.rs b/src/core/authentication/key/repository/persisted.rs new file mode 100644 index 000000000..736a409eb --- /dev/null +++ b/src/core/authentication/key/repository/persisted.rs @@ -0,0 +1,48 @@ +use std::sync::Arc; + +use crate::core::authentication::key::{Key, PeerKey}; +use crate::core::databases::{self, Database}; + +/// The database repository for the authentication keys. +pub struct DatabaseKeyRepository { + database: Arc>, +} + +impl DatabaseKeyRepository { + #[must_use] + pub fn new(database: &Arc>) -> Self { + Self { + database: database.clone(), + } + } + + /// It adds a new key to the database. + /// + /// # Errors + /// + /// Will return a `databases::error::Error` if unable to add the `auth_key` to the database. + pub fn add(&self, peer_key: &PeerKey) -> Result<(), databases::error::Error> { + self.database.add_key_to_keys(peer_key)?; + Ok(()) + } + + /// It removes an key from the database. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to remove the `key` from the database. + pub fn remove(&self, key: &Key) -> Result<(), databases::error::Error> { + self.database.remove_key_from_keys(key)?; + Ok(()) + } + + /// It loads all keys from the database. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to load the keys from the database. + pub fn load_keys(&self) -> Result, databases::error::Error> { + let keys = self.database.load_keys()?; + Ok(keys) + } +} diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index d611ae57e..618f57f91 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -2,6 +2,7 @@ use std::panic::Location; use std::sync::Arc; use std::time::Duration; +use key::repository::persisted::DatabaseKeyRepository; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Core; use torrust_tracker_located_error::Located; @@ -35,12 +36,11 @@ pub struct Facade { /// The tracker configuration. config: Core, - /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) - /// or [`MySQL`](crate::core::databases::mysql) - database: Arc>, - /// Tracker users' keys. Only for private trackers. keys: tokio::sync::RwLock>, + + /// The database repository for the authentication keys. + db_key_repository: DatabaseKeyRepository, } impl Facade { @@ -48,8 +48,8 @@ impl Facade { pub fn new(config: &Core, database: &Arc>) -> Self { Self { config: config.clone(), - database: database.clone(), keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), + db_key_repository: DatabaseKeyRepository::new(database), } } @@ -205,7 +205,8 @@ impl Facade { pub async fn generate_auth_key(&self, lifetime: Option) -> Result { let auth_key = key::generate_key(lifetime); - self.database.add_key_to_keys(&auth_key)?; + self.db_key_repository.add(&auth_key)?; + self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); Ok(auth_key) } @@ -254,7 +255,8 @@ impl Facade { // code-review: should we return a friendly error instead of the DB // constrain error when the key already exist? For now, it's returning // the specif error for each DB driver when a UNIQUE constrain fails. - self.database.add_key_to_keys(&auth_key)?; + self.db_key_repository.add(&auth_key)?; + self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); Ok(auth_key) } @@ -267,8 +269,10 @@ impl Facade { /// /// Will return a `database::Error` if unable to remove the `key` to the database. pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> { - self.database.remove_key_from_keys(key)?; + self.db_key_repository.remove(key)?; + self.remove_in_memory_auth_key(key).await; + Ok(()) } @@ -290,7 +294,8 @@ impl Facade { /// /// Will return a `database::Error` if unable to `load_keys` from the database. pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> { - let keys_from_database = self.database.load_keys()?; + let keys_from_database = self.db_key_repository.load_keys()?; + let mut keys = self.keys.write().await; keys.clear(); From 12a62ceaef3bdec903f575be00c81c781549f323 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Jan 2025 17:28:12 +0000 Subject: [PATCH 0618/1297] refactor: [#1195] extract InMemoryKeyRepository --- .../key/repository/in_memory.rs | 30 ++++++++++++++ src/core/authentication/key/repository/mod.rs | 1 + src/core/authentication/mod.rs | 41 ++++++++++--------- 3 files changed, 52 insertions(+), 20 deletions(-) create mode 100644 src/core/authentication/key/repository/in_memory.rs diff --git a/src/core/authentication/key/repository/in_memory.rs b/src/core/authentication/key/repository/in_memory.rs new file mode 100644 index 000000000..266d5a5fb --- /dev/null +++ b/src/core/authentication/key/repository/in_memory.rs @@ -0,0 +1,30 @@ +use crate::core::authentication::key::{Key, PeerKey}; + +/// In-memory implementation of the authentication key repository. +#[derive(Debug, Default)] +pub struct InMemoryKeyRepository { + /// Tracker users' keys. Only for private trackers. + keys: tokio::sync::RwLock>, +} + +impl InMemoryKeyRepository { + /// It adds a new authentication key. + pub async fn insert(&self, auth_key: &PeerKey) { + self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); + } + + /// It removes an authentication key. + pub async fn remove(&self, key: &Key) { + self.keys.write().await.remove(key); + } + + pub async fn get(&self, key: &Key) -> Option { + self.keys.read().await.get(key).cloned() + } + + /// It clears all the authentication keys. + pub async fn clear(&self) { + let mut keys = self.keys.write().await; + keys.clear(); + } +} diff --git a/src/core/authentication/key/repository/mod.rs b/src/core/authentication/key/repository/mod.rs index fe3bdd68c..51723b68d 100644 --- a/src/core/authentication/key/repository/mod.rs +++ b/src/core/authentication/key/repository/mod.rs @@ -1 +1,2 @@ +pub mod in_memory; pub mod persisted; diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 618f57f91..4a65a26a7 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -2,6 +2,7 @@ use std::panic::Location; use std::sync::Arc; use std::time::Duration; +use key::repository::in_memory::InMemoryKeyRepository; use key::repository::persisted::DatabaseKeyRepository; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Core; @@ -36,11 +37,11 @@ pub struct Facade { /// The tracker configuration. config: Core, - /// Tracker users' keys. Only for private trackers. - keys: tokio::sync::RwLock>, - /// The database repository for the authentication keys. db_key_repository: DatabaseKeyRepository, + + /// In-memory implementation of the authentication key repository. + in_memory_key_repository: InMemoryKeyRepository, } impl Facade { @@ -48,8 +49,8 @@ impl Facade { pub fn new(config: &Core, database: &Arc>) -> Self { Self { config: config.clone(), - keys: tokio::sync::RwLock::new(std::collections::HashMap::new()), db_key_repository: DatabaseKeyRepository::new(database), + in_memory_key_repository: InMemoryKeyRepository::default(), } } @@ -82,7 +83,7 @@ impl Facade { /// /// Will return a `key::Error` if unable to get any `auth_key`. pub async fn verify_auth_key(&self, key: &Key) -> Result<(), Error> { - match self.keys.read().await.get(key) { + match self.in_memory_key_repository.get(key).await { None => Err(Error::UnableToReadKey { location: Location::caller(), key: Box::new(key.clone()), @@ -90,12 +91,12 @@ impl Facade { Some(key) => match self.config.private_mode { Some(private_mode) => { if private_mode.check_keys_expiration { - return key::verify_key_expiration(key); + return key::verify_key_expiration(&key); } Ok(()) } - None => key::verify_key_expiration(key), + None => key::verify_key_expiration(&key), }, } } @@ -203,12 +204,13 @@ impl Facade { /// * `lifetime` - The duration in seconds for the new key. The key will be /// no longer valid after `lifetime` seconds. pub async fn generate_auth_key(&self, lifetime: Option) -> Result { - let auth_key = key::generate_key(lifetime); + let peer_key = key::generate_key(lifetime); + + self.db_key_repository.add(&peer_key)?; - self.db_key_repository.add(&auth_key)?; + self.in_memory_key_repository.insert(&peer_key).await; - self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); - Ok(auth_key) + Ok(peer_key) } /// It adds a pre-generated permanent authentication key. @@ -250,15 +252,16 @@ impl Facade { key: Key, valid_until: Option, ) -> Result { - let auth_key = PeerKey { key, valid_until }; + let peer_key = PeerKey { key, valid_until }; // code-review: should we return a friendly error instead of the DB // constrain error when the key already exist? For now, it's returning // the specif error for each DB driver when a UNIQUE constrain fails. - self.db_key_repository.add(&auth_key)?; + self.db_key_repository.add(&peer_key)?; - self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); - Ok(auth_key) + self.in_memory_key_repository.insert(&peer_key).await; + + Ok(peer_key) } /// It removes an authentication key. @@ -280,7 +283,7 @@ impl Facade { /// /// # Context: Authentication pub async fn remove_in_memory_auth_key(&self, key: &Key) { - self.keys.write().await.remove(key); + self.in_memory_key_repository.remove(key).await; } /// The `Tracker` stores the authentication keys in memory and in the database. @@ -296,12 +299,10 @@ impl Facade { pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> { let keys_from_database = self.db_key_repository.load_keys()?; - let mut keys = self.keys.write().await; - - keys.clear(); + self.in_memory_key_repository.clear().await; for key in keys_from_database { - keys.insert(key.key.clone(), key); + self.in_memory_key_repository.insert(&key).await; } Ok(()) From a93a79c5a6bdf63d37ac273a3f23c98b3f4e0801 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Jan 2025 17:34:51 +0000 Subject: [PATCH 0619/1297] refactor: [#1195] remove deprecated context section in docs It was used to group methods by services in the old core tracker. --- src/core/authentication/mod.rs | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 4a65a26a7..1b841767e 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -60,8 +60,6 @@ impl Facade { /// # Errors /// /// Will return an error if the the authentication key cannot be verified. - /// - /// # Context: Authentication pub async fn authenticate(&self, key: &Key) -> Result<(), Error> { if self.is_private() { self.verify_auth_key(key).await @@ -77,8 +75,6 @@ impl Facade { /// It verifies an authentication key. /// - /// # Context: Authentication - /// /// # Errors /// /// Will return a `key::Error` if unable to get any `auth_key`. @@ -180,8 +176,6 @@ impl Facade { /// /// Authentication keys are used by HTTP trackers. /// - /// # Context: Authentication - /// /// # Errors /// /// Will return a `database::Error` if unable to add the `auth_key` to the database. @@ -193,8 +187,6 @@ impl Facade { /// /// Authentication keys are used by HTTP trackers. /// - /// # Context: Authentication - /// /// # Errors /// /// Will return a `database::Error` if unable to add the `auth_key` to the database. @@ -217,8 +209,6 @@ impl Facade { /// /// Authentication keys are used by HTTP trackers. /// - /// # Context: Authentication - /// /// # Errors /// /// Will return a `database::Error` if unable to add the `auth_key` to the @@ -235,8 +225,6 @@ impl Facade { /// /// Authentication keys are used by HTTP trackers. /// - /// # Context: Authentication - /// /// # Errors /// /// Will return a `database::Error` if unable to add the `auth_key` to the @@ -266,8 +254,6 @@ impl Facade { /// It removes an authentication key. /// - /// # Context: Authentication - /// /// # Errors /// /// Will return a `database::Error` if unable to remove the `key` to the database. @@ -280,8 +266,6 @@ impl Facade { } /// It removes an authentication key from memory. - /// - /// # Context: Authentication pub async fn remove_in_memory_auth_key(&self, key: &Key) { self.in_memory_key_repository.remove(key).await; } @@ -291,8 +275,6 @@ impl Facade { /// into memory with this function. Keys are automatically stored in the database when they /// are generated. /// - /// # Context: Authentication - /// /// # Errors /// /// Will return a `database::Error` if unable to `load_keys` from the database. From cd542dc3523ce52a26e32961f222f5f4167dd63f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Jan 2025 17:53:55 +0000 Subject: [PATCH 0620/1297] refactor: [#1195] extract authentication::Service --- src/core/authentication/mod.rs | 69 +++++++++++------------------ src/core/authentication/service.rs | 70 ++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 44 deletions(-) create mode 100644 src/core/authentication/service.rs diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 1b841767e..7e60648f5 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -1,4 +1,3 @@ -use std::panic::Location; use std::sync::Arc; use std::time::Duration; @@ -14,6 +13,7 @@ use super::error::PeerKeyError; use crate::CurrentClock; pub mod key; +pub mod service; pub type PeerKey = key::PeerKey; pub type Key = key::Key; @@ -34,23 +34,25 @@ pub struct AddKeyRequest { } pub struct Facade { - /// The tracker configuration. - config: Core, - /// The database repository for the authentication keys. db_key_repository: DatabaseKeyRepository, /// In-memory implementation of the authentication key repository. - in_memory_key_repository: InMemoryKeyRepository, + in_memory_key_repository: Arc, + + /// The authentication service. + authentication_service: service::Service, } impl Facade { #[must_use] pub fn new(config: &Core, database: &Arc>) -> Self { + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + Self { - config: config.clone(), db_key_repository: DatabaseKeyRepository::new(database), - in_memory_key_repository: InMemoryKeyRepository::default(), + in_memory_key_repository: in_memory_key_repository.clone(), + authentication_service: service::Service::new(config, &in_memory_key_repository), } } @@ -61,40 +63,7 @@ impl Facade { /// /// Will return an error if the the authentication key cannot be verified. pub async fn authenticate(&self, key: &Key) -> Result<(), Error> { - if self.is_private() { - self.verify_auth_key(key).await - } else { - Ok(()) - } - } - - /// Returns `true` is the tracker is in private mode. - pub fn is_private(&self) -> bool { - self.config.private - } - - /// It verifies an authentication key. - /// - /// # Errors - /// - /// Will return a `key::Error` if unable to get any `auth_key`. - pub async fn verify_auth_key(&self, key: &Key) -> Result<(), Error> { - match self.in_memory_key_repository.get(key).await { - None => Err(Error::UnableToReadKey { - location: Location::caller(), - key: Box::new(key.clone()), - }), - Some(key) => match self.config.private_mode { - Some(private_mode) => { - if private_mode.check_keys_expiration { - return key::verify_key_expiration(&key); - } - - Ok(()) - } - None => key::verify_key_expiration(&key), - }, - } + self.authentication_service.authenticate(key).await } /// Adds new peer keys to the tracker. @@ -340,7 +309,11 @@ mod tests { let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - assert!(authentication.verify_auth_key(&unregistered_key).await.is_err()); + assert!(authentication + .authentication_service + .verify_auth_key(&unregistered_key) + .await + .is_err()); } #[tokio::test] @@ -355,7 +328,11 @@ mod tests { let result = authentication.remove_auth_key(&expiring_key.key()).await; assert!(result.is_ok()); - assert!(authentication.verify_auth_key(&expiring_key.key()).await.is_err()); + assert!(authentication + .authentication_service + .verify_auth_key(&expiring_key.key()) + .await + .is_err()); } #[tokio::test] @@ -373,7 +350,11 @@ mod tests { let result = authentication.load_keys_from_database().await; assert!(result.is_ok()); - assert!(authentication.verify_auth_key(&expiring_key.key()).await.is_ok()); + assert!(authentication + .authentication_service + .verify_auth_key(&expiring_key.key()) + .await + .is_ok()); } mod with_expiring_and { diff --git a/src/core/authentication/service.rs b/src/core/authentication/service.rs new file mode 100644 index 000000000..d33ed673b --- /dev/null +++ b/src/core/authentication/service.rs @@ -0,0 +1,70 @@ +use std::panic::Location; +use std::sync::Arc; + +use torrust_tracker_configuration::Core; + +use super::key::repository::in_memory::InMemoryKeyRepository; +use super::{key, Error, Key}; + +#[derive(Debug)] +pub struct Service { + /// The tracker configuration. + config: Core, + + /// In-memory implementation of the authentication key repository. + in_memory_key_repository: Arc, +} + +impl Service { + #[must_use] + pub fn new(config: &Core, in_memory_key_repository: &Arc) -> Self { + Self { + config: config.clone(), + in_memory_key_repository: in_memory_key_repository.clone(), + } + } + + /// It authenticates the peer `key` against the `Tracker` authentication + /// key list. + /// + /// # Errors + /// + /// Will return an error if the the authentication key cannot be verified. + pub async fn authenticate(&self, key: &Key) -> Result<(), Error> { + if self.is_private() { + self.verify_auth_key(key).await + } else { + Ok(()) + } + } + + /// Returns `true` is the tracker is in private mode. + #[must_use] + pub fn is_private(&self) -> bool { + self.config.private + } + + /// It verifies an authentication key. + /// + /// # Errors + /// + /// Will return a `key::Error` if unable to get any `auth_key`. + pub async fn verify_auth_key(&self, key: &Key) -> Result<(), Error> { + match self.in_memory_key_repository.get(key).await { + None => Err(Error::UnableToReadKey { + location: Location::caller(), + key: Box::new(key.clone()), + }), + Some(key) => match self.config.private_mode { + Some(private_mode) => { + if private_mode.check_keys_expiration { + return key::verify_key_expiration(&key); + } + + Ok(()) + } + None => key::verify_key_expiration(&key), + }, + } + } +} From 81b4b3c0a006378264c2248a9b188d45e0783246 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Jan 2025 18:00:35 +0000 Subject: [PATCH 0621/1297] refactor: [#1195] extract and move method --- .../authentication/key/repository/in_memory.rs | 11 +++++++++++ src/core/authentication/mod.rs | 14 +++++--------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/core/authentication/key/repository/in_memory.rs b/src/core/authentication/key/repository/in_memory.rs index 266d5a5fb..a15f9ecfa 100644 --- a/src/core/authentication/key/repository/in_memory.rs +++ b/src/core/authentication/key/repository/in_memory.rs @@ -27,4 +27,15 @@ impl InMemoryKeyRepository { let mut keys = self.keys.write().await; keys.clear(); } + + /// It resets the authentication keys with a new list of keys. + pub async fn reset_with(&self, peer_keys: Vec) { + let mut keys_lock = self.keys.write().await; + + keys_lock.clear(); + + for key in peer_keys { + keys_lock.insert(key.key.clone(), key.clone()); + } + } } diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 7e60648f5..9d47409e3 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -239,10 +239,10 @@ impl Facade { self.in_memory_key_repository.remove(key).await; } - /// The `Tracker` stores the authentication keys in memory and in the database. - /// In case you need to restart the `Tracker` you can load the keys from the database - /// into memory with this function. Keys are automatically stored in the database when they - /// are generated. + /// The `Tracker` stores the authentication keys in memory and in the + /// database. In case you need to restart the `Tracker` you can load the + /// keys from the database into memory with this function. Keys are + /// automatically stored in the database when they are generated. /// /// # Errors /// @@ -250,11 +250,7 @@ impl Facade { pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> { let keys_from_database = self.db_key_repository.load_keys()?; - self.in_memory_key_repository.clear().await; - - for key in keys_from_database { - self.in_memory_key_repository.insert(&key).await; - } + self.in_memory_key_repository.reset_with(keys_from_database).await; Ok(()) } From 23590e7bff89f842682209f0801b20ff37ebd98f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Jan 2025 18:08:06 +0000 Subject: [PATCH 0622/1297] refactor: [#1195] make method private --- src/core/authentication/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 9d47409e3..098524ed9 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -186,7 +186,7 @@ impl Facade { /// # Arguments /// /// * `key` - The pre-generated key. - pub async fn add_permanent_auth_key(&self, key: Key) -> Result { + async fn add_permanent_auth_key(&self, key: Key) -> Result { self.add_auth_key(key, None).await } @@ -239,9 +239,9 @@ impl Facade { self.in_memory_key_repository.remove(key).await; } - /// The `Tracker` stores the authentication keys in memory and in the - /// database. In case you need to restart the `Tracker` you can load the - /// keys from the database into memory with this function. Keys are + /// The `Tracker` stores the authentication keys in memory and in the + /// database. In case you need to restart the `Tracker` you can load the + /// keys from the database into memory with this function. Keys are /// automatically stored in the database when they are generated. /// /// # Errors From bb2f9e07072af8b58330ef9842d1b99434437ae9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 21 Jan 2025 18:28:31 +0000 Subject: [PATCH 0623/1297] refactor: [#1195] extract core::authentication::handler::KeysHandler --- src/core/authentication/handler.rs | 233 ++++++++++++++++++ src/core/authentication/mod.rs | 144 ++--------- .../apis/v1/context/auth_key/handlers.rs | 3 +- 3 files changed, 249 insertions(+), 131 deletions(-) create mode 100644 src/core/authentication/handler.rs diff --git a/src/core/authentication/handler.rs b/src/core/authentication/handler.rs new file mode 100644 index 000000000..f327c4fdd --- /dev/null +++ b/src/core/authentication/handler.rs @@ -0,0 +1,233 @@ +use std::sync::Arc; +use std::time::Duration; + +use torrust_tracker_clock::clock::Time; +use torrust_tracker_located_error::Located; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::key::repository::in_memory::InMemoryKeyRepository; +use super::key::repository::persisted::DatabaseKeyRepository; +use super::{key, CurrentClock, Key, PeerKey}; +use crate::core::databases; +use crate::core::error::PeerKeyError; + +/// This type contains the info needed to add a new tracker key. +/// +/// You can upload a pre-generated key or let the app to generate a new one. +/// You can also set an expiration date or leave it empty (`None`) if you want +/// to create a permanent key that does not expire. +#[derive(Debug)] +pub struct AddKeyRequest { + /// The pre-generated key. Use `None` to generate a random key. + pub opt_key: Option, + + /// How long the key will be valid in seconds. Use `None` for permanent keys. + pub opt_seconds_valid: Option, +} + +pub struct KeysHandler { + /// The database repository for the authentication keys. + db_key_repository: Arc, + + /// In-memory implementation of the authentication key repository. + in_memory_key_repository: Arc, +} + +impl KeysHandler { + #[must_use] + pub fn new(db_key_repository: &Arc, in_memory_key_repository: &Arc) -> Self { + Self { + db_key_repository: db_key_repository.clone(), + in_memory_key_repository: in_memory_key_repository.clone(), + } + } + + /// Adds new peer keys to the tracker. + /// + /// Keys can be pre-generated or randomly created. They can also be permanent or expire. + /// + /// # Errors + /// + /// Will return an error if: + /// + /// - The key duration overflows the duration type maximum value. + /// - The provided pre-generated key is invalid. + /// - The key could not been persisted due to database issues. + pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { + // code-review: all methods related to keys should be moved to a new independent "keys" service. + + match add_key_req.opt_key { + // Upload pre-generated key + Some(pre_existing_key) => { + if let Some(seconds_valid) = add_key_req.opt_seconds_valid { + // Expiring key + let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(seconds_valid)) else { + return Err(PeerKeyError::DurationOverflow { seconds_valid }); + }; + + let key = pre_existing_key.parse::(); + + match key { + Ok(key) => match self.add_auth_key(key, Some(valid_until)).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + Err(err) => Err(PeerKeyError::InvalidKey { + key: pre_existing_key, + source: Located(err).into(), + }), + } + } else { + // Permanent key + let key = pre_existing_key.parse::(); + + match key { + Ok(key) => match self.add_permanent_auth_key(key).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + Err(err) => Err(PeerKeyError::InvalidKey { + key: pre_existing_key, + source: Located(err).into(), + }), + } + } + } + // Generate a new random key + None => match add_key_req.opt_seconds_valid { + // Expiring key + Some(seconds_valid) => match self.generate_auth_key(Some(Duration::from_secs(seconds_valid))).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + // Permanent key + None => match self.generate_permanent_auth_key().await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { + source: Located(err).into(), + }), + }, + }, + } + } + + /// It generates a new permanent authentication key. + /// + /// Authentication keys are used by HTTP trackers. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `auth_key` to the database. + pub async fn generate_permanent_auth_key(&self) -> Result { + self.generate_auth_key(None).await + } + + /// It generates a new expiring authentication key. + /// + /// Authentication keys are used by HTTP trackers. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `auth_key` to the database. + /// + /// # Arguments + /// + /// * `lifetime` - The duration in seconds for the new key. The key will be + /// no longer valid after `lifetime` seconds. + pub async fn generate_auth_key(&self, lifetime: Option) -> Result { + let peer_key = key::generate_key(lifetime); + + self.db_key_repository.add(&peer_key)?; + + self.in_memory_key_repository.insert(&peer_key).await; + + Ok(peer_key) + } + + /// It adds a pre-generated permanent authentication key. + /// + /// Authentication keys are used by HTTP trackers. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `auth_key` to the + /// database. For example, if the key already exist. + /// + /// # Arguments + /// + /// * `key` - The pre-generated key. + pub async fn add_permanent_auth_key(&self, key: Key) -> Result { + self.add_auth_key(key, None).await + } + + /// It adds a pre-generated authentication key. + /// + /// Authentication keys are used by HTTP trackers. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to add the `auth_key` to the + /// database. For example, if the key already exist. + /// + /// # Arguments + /// + /// * `key` - The pre-generated key. + /// * `lifetime` - The duration in seconds for the new key. The key will be + /// no longer valid after `lifetime` seconds. + pub async fn add_auth_key( + &self, + key: Key, + valid_until: Option, + ) -> Result { + let peer_key = PeerKey { key, valid_until }; + + // code-review: should we return a friendly error instead of the DB + // constrain error when the key already exist? For now, it's returning + // the specif error for each DB driver when a UNIQUE constrain fails. + self.db_key_repository.add(&peer_key)?; + + self.in_memory_key_repository.insert(&peer_key).await; + + Ok(peer_key) + } + + /// It removes an authentication key. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to remove the `key` to the database. + pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> { + self.db_key_repository.remove(key)?; + + self.remove_in_memory_auth_key(key).await; + + Ok(()) + } + + /// It removes an authentication key from memory. + pub async fn remove_in_memory_auth_key(&self, key: &Key) { + self.in_memory_key_repository.remove(key).await; + } + + /// The `Tracker` stores the authentication keys in memory and in the + /// database. In case you need to restart the `Tracker` you can load the + /// keys from the database into memory with this function. Keys are + /// automatically stored in the database when they are generated. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to `load_keys` from the database. + pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> { + let keys_from_database = self.db_key_repository.load_keys()?; + + self.in_memory_key_repository.reset_with(keys_from_database).await; + + Ok(()) + } +} diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 098524ed9..5c9356c10 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -1,17 +1,17 @@ use std::sync::Arc; use std::time::Duration; +use handler::{AddKeyRequest, KeysHandler}; use key::repository::in_memory::InMemoryKeyRepository; use key::repository::persisted::DatabaseKeyRepository; -use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Core; -use torrust_tracker_located_error::Located; use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::databases::{self, Database}; use super::error::PeerKeyError; use crate::CurrentClock; +pub mod handler; pub mod key; pub mod service; @@ -19,40 +19,23 @@ pub type PeerKey = key::PeerKey; pub type Key = key::Key; pub type Error = key::Error; -/// This type contains the info needed to add a new tracker key. -/// -/// You can upload a pre-generated key or let the app to generate a new one. -/// You can also set an expiration date or leave it empty (`None`) if you want -/// to create a permanent key that does not expire. -#[derive(Debug)] -pub struct AddKeyRequest { - /// The pre-generated key. Use `None` to generate a random key. - pub opt_key: Option, - - /// How long the key will be valid in seconds. Use `None` for permanent keys. - pub opt_seconds_valid: Option, -} - pub struct Facade { - /// The database repository for the authentication keys. - db_key_repository: DatabaseKeyRepository, - - /// In-memory implementation of the authentication key repository. - in_memory_key_repository: Arc, - /// The authentication service. authentication_service: service::Service, + + /// The keys handler. + keys_handler: handler::KeysHandler, } impl Facade { #[must_use] pub fn new(config: &Core, database: &Arc>) -> Self { + let db_key_repository = Arc::new(DatabaseKeyRepository::new(database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); Self { - db_key_repository: DatabaseKeyRepository::new(database), - in_memory_key_repository: in_memory_key_repository.clone(), authentication_service: service::Service::new(config, &in_memory_key_repository), + keys_handler: KeysHandler::new(&db_key_repository.clone(), &in_memory_key_repository.clone()), } } @@ -78,67 +61,7 @@ impl Facade { /// - The provided pre-generated key is invalid. /// - The key could not been persisted due to database issues. pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { - // code-review: all methods related to keys should be moved to a new independent "keys" service. - - match add_key_req.opt_key { - // Upload pre-generated key - Some(pre_existing_key) => { - if let Some(seconds_valid) = add_key_req.opt_seconds_valid { - // Expiring key - let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(seconds_valid)) else { - return Err(PeerKeyError::DurationOverflow { seconds_valid }); - }; - - let key = pre_existing_key.parse::(); - - match key { - Ok(key) => match self.add_auth_key(key, Some(valid_until)).await { - Ok(auth_key) => Ok(auth_key), - Err(err) => Err(PeerKeyError::DatabaseError { - source: Located(err).into(), - }), - }, - Err(err) => Err(PeerKeyError::InvalidKey { - key: pre_existing_key, - source: Located(err).into(), - }), - } - } else { - // Permanent key - let key = pre_existing_key.parse::(); - - match key { - Ok(key) => match self.add_permanent_auth_key(key).await { - Ok(auth_key) => Ok(auth_key), - Err(err) => Err(PeerKeyError::DatabaseError { - source: Located(err).into(), - }), - }, - Err(err) => Err(PeerKeyError::InvalidKey { - key: pre_existing_key, - source: Located(err).into(), - }), - } - } - } - // Generate a new random key - None => match add_key_req.opt_seconds_valid { - // Expiring key - Some(seconds_valid) => match self.generate_auth_key(Some(Duration::from_secs(seconds_valid))).await { - Ok(auth_key) => Ok(auth_key), - Err(err) => Err(PeerKeyError::DatabaseError { - source: Located(err).into(), - }), - }, - // Permanent key - None => match self.generate_permanent_auth_key().await { - Ok(auth_key) => Ok(auth_key), - Err(err) => Err(PeerKeyError::DatabaseError { - source: Located(err).into(), - }), - }, - }, - } + self.keys_handler.add_peer_key(add_key_req).await } /// It generates a new permanent authentication key. @@ -149,7 +72,7 @@ impl Facade { /// /// Will return a `database::Error` if unable to add the `auth_key` to the database. pub async fn generate_permanent_auth_key(&self) -> Result { - self.generate_auth_key(None).await + self.keys_handler.generate_permanent_auth_key().await } /// It generates a new expiring authentication key. @@ -165,29 +88,7 @@ impl Facade { /// * `lifetime` - The duration in seconds for the new key. The key will be /// no longer valid after `lifetime` seconds. pub async fn generate_auth_key(&self, lifetime: Option) -> Result { - let peer_key = key::generate_key(lifetime); - - self.db_key_repository.add(&peer_key)?; - - self.in_memory_key_repository.insert(&peer_key).await; - - Ok(peer_key) - } - - /// It adds a pre-generated permanent authentication key. - /// - /// Authentication keys are used by HTTP trackers. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `auth_key` to the - /// database. For example, if the key already exist. - /// - /// # Arguments - /// - /// * `key` - The pre-generated key. - async fn add_permanent_auth_key(&self, key: Key) -> Result { - self.add_auth_key(key, None).await + self.keys_handler.generate_auth_key(lifetime).await } /// It adds a pre-generated authentication key. @@ -209,16 +110,7 @@ impl Facade { key: Key, valid_until: Option, ) -> Result { - let peer_key = PeerKey { key, valid_until }; - - // code-review: should we return a friendly error instead of the DB - // constrain error when the key already exist? For now, it's returning - // the specif error for each DB driver when a UNIQUE constrain fails. - self.db_key_repository.add(&peer_key)?; - - self.in_memory_key_repository.insert(&peer_key).await; - - Ok(peer_key) + self.keys_handler.add_auth_key(key, valid_until).await } /// It removes an authentication key. @@ -227,16 +119,12 @@ impl Facade { /// /// Will return a `database::Error` if unable to remove the `key` to the database. pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> { - self.db_key_repository.remove(key)?; - - self.remove_in_memory_auth_key(key).await; - - Ok(()) + self.keys_handler.remove_auth_key(key).await } /// It removes an authentication key from memory. pub async fn remove_in_memory_auth_key(&self, key: &Key) { - self.in_memory_key_repository.remove(key).await; + self.keys_handler.remove_in_memory_auth_key(key).await; } /// The `Tracker` stores the authentication keys in memory and in the @@ -248,11 +136,7 @@ impl Facade { /// /// Will return a `database::Error` if unable to `load_keys` from the database. pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> { - let keys_from_database = self.db_key_repository.load_keys()?; - - self.in_memory_key_repository.reset_with(keys_from_database).await; - - Ok(()) + self.keys_handler.load_keys_from_database().await } } diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index ba345d8a5..f0c131bbf 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -12,7 +12,8 @@ use super::responses::{ auth_key_response, failed_to_delete_key_response, failed_to_generate_key_response, failed_to_reload_keys_response, invalid_auth_key_duration_response, invalid_auth_key_response, }; -use crate::core::authentication::{AddKeyRequest, Key}; +use crate::core::authentication::handler::AddKeyRequest; +use crate::core::authentication::Key; use crate::core::Tracker; use crate::servers::apis::v1::context::auth_key::resources::AuthKey; use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_response}; From c06da07c44300ced5fe28976119b4386a68d369b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 22 Jan 2025 08:09:42 +0000 Subject: [PATCH 0624/1297] refactor: [#1195] more authentication tests to authentication service --- src/core/authentication/mod.rs | 33 +++++--------------------- src/core/authentication/service.rs | 37 +++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 28 deletions(-) diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 5c9356c10..86337b714 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -145,7 +145,6 @@ mod tests { mod the_tracker_configured_as_private { - use std::str::FromStr; use std::time::Duration; use torrust_tracker_configuration::v2_0_0::core::PrivateMode; @@ -172,30 +171,6 @@ mod tests { authentication::Facade::new(&config.core, &database.clone()) } - #[tokio::test] - async fn it_should_fail_authenticating_a_peer_when_it_uses_an_unregistered_key() { - let authentication = instantiate_authentication(); - - let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - - let result = authentication.authenticate(&unregistered_key).await; - - assert!(result.is_err()); - } - - #[tokio::test] - async fn it_should_fail_verifying_an_unregistered_authentication_key() { - let authentication = instantiate_authentication(); - - let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - - assert!(authentication - .authentication_service - .verify_auth_key(&unregistered_key) - .await - .is_err()); - } - #[tokio::test] async fn it_should_remove_an_authentication_key() { let authentication = instantiate_authentication(); @@ -208,9 +183,11 @@ mod tests { let result = authentication.remove_auth_key(&expiring_key.key()).await; assert!(result.is_ok()); + + // The key should no longer be valid assert!(authentication .authentication_service - .verify_auth_key(&expiring_key.key()) + .authenticate(&expiring_key.key()) .await .is_err()); } @@ -230,9 +207,11 @@ mod tests { let result = authentication.load_keys_from_database().await; assert!(result.is_ok()); + + // The key should no longer be valid assert!(authentication .authentication_service - .verify_auth_key(&expiring_key.key()) + .authenticate(&expiring_key.key()) .await .is_ok()); } diff --git a/src/core/authentication/service.rs b/src/core/authentication/service.rs index d33ed673b..d7572136f 100644 --- a/src/core/authentication/service.rs +++ b/src/core/authentication/service.rs @@ -49,7 +49,7 @@ impl Service { /// # Errors /// /// Will return a `key::Error` if unable to get any `auth_key`. - pub async fn verify_auth_key(&self, key: &Key) -> Result<(), Error> { + async fn verify_auth_key(&self, key: &Key) -> Result<(), Error> { match self.in_memory_key_repository.get(key).await { None => Err(Error::UnableToReadKey { location: Location::caller(), @@ -68,3 +68,38 @@ impl Service { } } } + +#[cfg(test)] +mod tests { + + mod the_tracker_configured_as_private { + + use std::str::FromStr; + use std::sync::Arc; + + use torrust_tracker_test_helpers::configuration; + + use crate::core::authentication; + use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::core::authentication::service::Service; + + fn instantiate_authentication() -> Service { + let config = configuration::ephemeral_private(); + + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + Service::new(&config.core, &in_memory_key_repository.clone()) + } + + #[tokio::test] + async fn it_should_not_authenticate_an_unregistered_key() { + let authentication = instantiate_authentication(); + + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + let result = authentication.authenticate(&unregistered_key).await; + + assert!(result.is_err()); + } + } +} From 9c61b2685d0d0ffbba7be78ba032232f4e654931 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 22 Jan 2025 08:26:06 +0000 Subject: [PATCH 0625/1297] refactor: [#1195] move tests to KeysHandler These tests do not require the authentication service. --- src/core/authentication/handler.rs | 133 +++++++++++++++++++++++++++++ src/core/authentication/mod.rs | 64 -------------- 2 files changed, 133 insertions(+), 64 deletions(-) diff --git a/src/core/authentication/handler.rs b/src/core/authentication/handler.rs index f327c4fdd..3ada2b110 100644 --- a/src/core/authentication/handler.rs +++ b/src/core/authentication/handler.rs @@ -231,3 +231,136 @@ impl KeysHandler { Ok(()) } } + +#[cfg(test)] +mod tests { + + mod the_keys_handler_when_tracker_is_configured_as_private { + + use std::sync::Arc; + + use torrust_tracker_configuration::v2_0_0::core::PrivateMode; + use torrust_tracker_configuration::Configuration; + use torrust_tracker_test_helpers::configuration; + + use crate::core::authentication::handler::KeysHandler; + use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::core::services::initialize_database; + + fn instantiate_keys_handler() -> KeysHandler { + let config = configuration::ephemeral_private(); + + instantiate_keys_handler_with_configuration(&config) + } + + #[allow(dead_code)] + fn instantiate_keys_handler_with_checking_keys_expiration_disabled() -> KeysHandler { + let mut config = configuration::ephemeral_private(); + + config.core.private_mode = Some(PrivateMode { + check_keys_expiration: false, + }); + + instantiate_keys_handler_with_configuration(&config) + } + + fn instantiate_keys_handler_with_configuration(config: &Configuration) -> KeysHandler { + let database = initialize_database(config); + + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + KeysHandler::new(&db_key_repository, &in_memory_key_repository) + } + + mod with_expiring_and { + + mod randomly_generated_keys { + use std::time::Duration; + + use torrust_tracker_clock::clock::Time; + + use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_generate_the_key() { + let keys_handler = instantiate_keys_handler(); + + let peer_key = keys_handler.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); + + assert_eq!( + peer_key.valid_until, + Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + ); + } + } + + mod pre_generated_keys { + use std::time::Duration; + + use torrust_tracker_clock::clock::Time; + + use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::core::authentication::{AddKeyRequest, Key}; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_add_a_pre_generated_key() { + let keys_handler = instantiate_keys_handler(); + + let peer_key = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(100), + }) + .await + .unwrap(); + + assert_eq!( + peer_key.valid_until, + Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + ); + } + } + } + + mod with_permanent_and { + + mod randomly_generated_keys { + use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; + + #[tokio::test] + async fn it_should_generate_the_key() { + let keys_handler = instantiate_keys_handler(); + + let peer_key = keys_handler.generate_permanent_auth_key().await.unwrap(); + + assert_eq!(peer_key.valid_until, None); + } + } + + mod pre_generated_keys { + + use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::core::authentication::{AddKeyRequest, Key}; + + #[tokio::test] + async fn it_should_add_a_pre_generated_key() { + let keys_handler = instantiate_keys_handler(); + + let peer_key = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: None, + }) + .await + .unwrap(); + + assert_eq!(peer_key.valid_until, None); + } + } + } + } +} diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 86337b714..4d0001fd2 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -221,28 +221,10 @@ mod tests { mod randomly_generated_keys { use std::time::Duration; - use torrust_tracker_clock::clock::Time; - use crate::core::authentication::tests::the_tracker_configured_as_private::{ instantiate_authentication, instantiate_authentication_with_checking_keys_expiration_disabled, }; use crate::core::authentication::Key; - use crate::CurrentClock; - - #[tokio::test] - async fn it_should_generate_the_key() { - let authentication = instantiate_authentication(); - - let peer_key = authentication - .generate_auth_key(Some(Duration::from_secs(100))) - .await - .unwrap(); - - assert_eq!( - peer_key.valid_until, - Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) - ); - } #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { @@ -274,33 +256,11 @@ mod tests { } mod pre_generated_keys { - use std::time::Duration; - - use torrust_tracker_clock::clock::Time; use crate::core::authentication::tests::the_tracker_configured_as_private::{ instantiate_authentication, instantiate_authentication_with_checking_keys_expiration_disabled, }; use crate::core::authentication::{AddKeyRequest, Key}; - use crate::CurrentClock; - - #[tokio::test] - async fn it_should_add_a_pre_generated_key() { - let authentication = instantiate_authentication(); - - let peer_key = authentication - .add_peer_key(AddKeyRequest { - opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: Some(100), - }) - .await - .unwrap(); - - assert_eq!( - peer_key.valid_until, - Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) - ); - } #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { @@ -341,15 +301,6 @@ mod tests { mod randomly_generated_keys { use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_authentication; - #[tokio::test] - async fn it_should_generate_the_key() { - let authentication = instantiate_authentication(); - - let peer_key = authentication.generate_permanent_auth_key().await.unwrap(); - - assert_eq!(peer_key.valid_until, None); - } - #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { let authentication = instantiate_authentication(); @@ -366,21 +317,6 @@ mod tests { use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_authentication; use crate::core::authentication::{AddKeyRequest, Key}; - #[tokio::test] - async fn it_should_add_a_pre_generated_key() { - let authentication = instantiate_authentication(); - - let peer_key = authentication - .add_peer_key(AddKeyRequest { - opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: None, - }) - .await - .unwrap(); - - assert_eq!(peer_key.valid_until, None); - } - #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { let authentication = instantiate_authentication(); From 663250bfa5921fd9e4ab949bd4af582fc1dfa771 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 22 Jan 2025 08:29:39 +0000 Subject: [PATCH 0626/1297] refactor: [#1195] rename methods --- src/core/authentication/mod.rs | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 4d0001fd2..bab0de8a3 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -153,14 +153,15 @@ mod tests { use crate::core::authentication; use crate::core::services::initialize_database; - fn instantiate_authentication() -> authentication::Facade { + fn instantiate_authentication_facade() -> authentication::Facade { let config = configuration::ephemeral_private(); let database = initialize_database(&config); + authentication::Facade::new(&config.core, &database.clone()) } - fn instantiate_authentication_with_checking_keys_expiration_disabled() -> authentication::Facade { + fn instantiate_authentication_facade_with_checking_keys_expiration_disabled() -> authentication::Facade { let mut config = configuration::ephemeral_private(); config.core.private_mode = Some(PrivateMode { @@ -168,12 +169,13 @@ mod tests { }); let database = initialize_database(&config); + authentication::Facade::new(&config.core, &database.clone()) } #[tokio::test] async fn it_should_remove_an_authentication_key() { - let authentication = instantiate_authentication(); + let authentication = instantiate_authentication_facade(); let expiring_key = authentication .generate_auth_key(Some(Duration::from_secs(100))) @@ -194,7 +196,7 @@ mod tests { #[tokio::test] async fn it_should_load_authentication_keys_from_the_database() { - let authentication = instantiate_authentication(); + let authentication = instantiate_authentication_facade(); let expiring_key = authentication .generate_auth_key(Some(Duration::from_secs(100))) @@ -222,13 +224,13 @@ mod tests { use std::time::Duration; use crate::core::authentication::tests::the_tracker_configured_as_private::{ - instantiate_authentication, instantiate_authentication_with_checking_keys_expiration_disabled, + instantiate_authentication_facade, instantiate_authentication_facade_with_checking_keys_expiration_disabled, }; use crate::core::authentication::Key; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { - let authentication = instantiate_authentication(); + let authentication = instantiate_authentication_facade(); let peer_key = authentication .generate_auth_key(Some(Duration::from_secs(100))) @@ -242,7 +244,7 @@ mod tests { #[tokio::test] async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { - let authentication = instantiate_authentication_with_checking_keys_expiration_disabled(); + let authentication = instantiate_authentication_facade_with_checking_keys_expiration_disabled(); let past_timestamp = Duration::ZERO; @@ -258,13 +260,13 @@ mod tests { mod pre_generated_keys { use crate::core::authentication::tests::the_tracker_configured_as_private::{ - instantiate_authentication, instantiate_authentication_with_checking_keys_expiration_disabled, + instantiate_authentication_facade, instantiate_authentication_facade_with_checking_keys_expiration_disabled, }; use crate::core::authentication::{AddKeyRequest, Key}; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { - let authentication = instantiate_authentication(); + let authentication = instantiate_authentication_facade(); let peer_key = authentication .add_peer_key(AddKeyRequest { @@ -281,7 +283,7 @@ mod tests { #[tokio::test] async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { - let authentication = instantiate_authentication_with_checking_keys_expiration_disabled(); + let authentication = instantiate_authentication_facade_with_checking_keys_expiration_disabled(); let peer_key = authentication .add_peer_key(AddKeyRequest { @@ -299,11 +301,11 @@ mod tests { mod with_permanent_and { mod randomly_generated_keys { - use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_authentication; + use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_authentication_facade; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { - let authentication = instantiate_authentication(); + let authentication = instantiate_authentication_facade(); let peer_key = authentication.generate_permanent_auth_key().await.unwrap(); @@ -314,12 +316,12 @@ mod tests { } mod pre_generated_keys { - use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_authentication; + use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_authentication_facade; use crate::core::authentication::{AddKeyRequest, Key}; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { - let authentication = instantiate_authentication(); + let authentication = instantiate_authentication_facade(); let peer_key = authentication .add_peer_key(AddKeyRequest { From 504357c2d2e1c2db0dcf0f4e2b3673907a87122a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 22 Jan 2025 08:44:17 +0000 Subject: [PATCH 0627/1297] refactor: [#1195] inject dependencies in authenticatio::Facade Facade service will be removed. --- src/app_test.rs | 10 ++++++++- src/bootstrap/app.rs | 10 ++++++++- src/bootstrap/jobs/http_tracker.rs | 10 ++++++++- src/bootstrap/jobs/tracker_apis.rs | 10 ++++++++- src/core/authentication/mod.rs | 34 +++++++++++++++++++----------- src/servers/apis/server.rs | 10 ++++++++- src/servers/http/server.rs | 10 ++++++++- src/servers/udp/server/mod.rs | 20 ++++++++++++++++-- 8 files changed, 94 insertions(+), 20 deletions(-) diff --git a/src/app_test.rs b/src/app_test.rs index 884aed6ef..13b10fefa 100644 --- a/src/app_test.rs +++ b/src/app_test.rs @@ -3,6 +3,8 @@ use std::sync::Arc; use torrust_tracker_configuration::Configuration; +use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; +use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::databases::Database; use crate::core::services::initialize_database; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; @@ -25,7 +27,13 @@ pub fn initialize_tracker_dependencies( &config.core, &in_memory_whitelist.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&config.core, &database.clone())); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication = Arc::new(authentication::Facade::new( + &config.core, + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); (database, in_memory_whitelist, whitelist_authorization, authentication) } diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index bc6b7a6bd..a87e4ca8e 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -22,6 +22,8 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; use crate::container::AppContainer; +use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; +use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{authentication, whitelist}; @@ -89,7 +91,13 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { &in_memory_whitelist.clone(), )); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let authentication = Arc::new(authentication::Facade::new(&configuration.core, &database.clone())); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication = Arc::new(authentication::Facade::new( + &configuration.core, + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); let tracker = Arc::new(initialize_tracker( configuration, diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index b07ff935c..abcc2a08c 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -100,6 +100,8 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::http_tracker::start_job; + use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::services::{initialize_database, initialize_tracker, statistics}; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{authentication, whitelist}; @@ -123,7 +125,13 @@ mod tests { &cfg.core, &in_memory_whitelist.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&cfg.core, &database.clone())); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication = Arc::new(authentication::Facade::new( + &cfg.core, + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 70e2e6737..56e4a2e44 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -149,6 +149,8 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::tracker_apis::start_job; + use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{authentication, whitelist}; @@ -176,7 +178,13 @@ mod tests { &in_memory_whitelist.clone(), )); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let authentication = Arc::new(authentication::Facade::new(&cfg.core, &database.clone())); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication = Arc::new(authentication::Facade::new( + &cfg.core, + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index bab0de8a3..d26379b09 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -7,7 +7,7 @@ use key::repository::persisted::DatabaseKeyRepository; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use super::databases::{self, Database}; +use super::databases::{self}; use super::error::PeerKeyError; use crate::CurrentClock; @@ -29,12 +29,13 @@ pub struct Facade { impl Facade { #[must_use] - pub fn new(config: &Core, database: &Arc>) -> Self { - let db_key_repository = Arc::new(DatabaseKeyRepository::new(database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - + pub fn new( + config: &Core, + db_key_repository: &Arc, + in_memory_key_repository: &Arc, + ) -> Self { Self { - authentication_service: service::Service::new(config, &in_memory_key_repository), + authentication_service: service::Service::new(config, in_memory_key_repository), keys_handler: KeysHandler::new(&db_key_repository.clone(), &in_memory_key_repository.clone()), } } @@ -145,20 +146,22 @@ mod tests { mod the_tracker_configured_as_private { + use std::sync::Arc; use std::time::Duration; use torrust_tracker_configuration::v2_0_0::core::PrivateMode; + use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; use crate::core::authentication; + use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::services::initialize_database; fn instantiate_authentication_facade() -> authentication::Facade { let config = configuration::ephemeral_private(); - let database = initialize_database(&config); - - authentication::Facade::new(&config.core, &database.clone()) + instantiate_authentication_facade_with_configuration(&config) } fn instantiate_authentication_facade_with_checking_keys_expiration_disabled() -> authentication::Facade { @@ -168,9 +171,16 @@ mod tests { check_keys_expiration: false, }); - let database = initialize_database(&config); - - authentication::Facade::new(&config.core, &database.clone()) + instantiate_authentication_facade_with_configuration(&config) + } + + fn instantiate_authentication_facade_with_configuration(config: &Configuration) -> authentication::Facade { + let database = initialize_database(config); + + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + authentication::Facade::new(&config.core, &db_key_repository.clone(), &in_memory_key_repository.clone()) } #[tokio::test] diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index a11442a53..b6ff50995 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -342,6 +342,8 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::make_rust_tls; + use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{authentication, whitelist}; @@ -369,7 +371,13 @@ mod tests { &in_memory_whitelist.clone(), )); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let authentication = Arc::new(authentication::Facade::new(&cfg.core, &database.clone())); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication = Arc::new(authentication::Facade::new( + &cfg.core, + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index e6370c775..140ef4e07 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -246,6 +246,8 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::make_rust_tls; + use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{authentication, whitelist}; @@ -268,7 +270,13 @@ mod tests { &in_memory_whitelist.clone(), )); let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let authentication = Arc::new(authentication::Facade::new(&cfg.core, &database.clone())); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication = Arc::new(authentication::Facade::new( + &cfg.core, + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 078510bcd..fafb82997 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -64,6 +64,8 @@ mod tests { use super::spawner::Spawner; use super::Server; use crate::bootstrap::app::initialize_global_services; + use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{authentication, whitelist}; @@ -88,7 +90,14 @@ mod tests { &in_memory_whitelist.clone(), )); let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let authentication = Arc::new(authentication::Facade::new(&cfg.core, &database.clone())); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication = Arc::new(authentication::Facade::new( + &cfg.core, + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); @@ -133,7 +142,14 @@ mod tests { &cfg.core, &in_memory_whitelist.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&cfg.core, &database.clone())); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication = Arc::new(authentication::Facade::new( + &cfg.core, + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); From 965e911cdf9a16b57ba0370b358398e2d6a6cc4d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 22 Jan 2025 09:56:40 +0000 Subject: [PATCH 0628/1297] refactor: [#1195] inject dependencies into authenticattion::Facade The Facade will be replaced by its dependencies. --- src/app_test.rs | 7 +++++-- src/bootstrap/app.rs | 7 +++++-- src/bootstrap/jobs/http_tracker.rs | 7 +++++-- src/bootstrap/jobs/tracker_apis.rs | 7 +++++-- src/core/authentication/mod.rs | 30 +++++++++++++++--------------- src/servers/apis/server.rs | 7 +++++-- src/servers/http/server.rs | 7 +++++-- src/servers/udp/server/mod.rs | 12 ++++++++---- 8 files changed, 53 insertions(+), 31 deletions(-) diff --git a/src/app_test.rs b/src/app_test.rs index 13b10fefa..6aa318e97 100644 --- a/src/app_test.rs +++ b/src/app_test.rs @@ -3,8 +3,10 @@ use std::sync::Arc; use torrust_tracker_configuration::Configuration; +use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; +use crate::core::authentication::service; use crate::core::databases::Database; use crate::core::services::initialize_database; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; @@ -29,11 +31,12 @@ pub fn initialize_tracker_dependencies( )); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication = Arc::new(authentication::Facade::new( - &config.core, + let authentication_service = Arc::new(service::Service::new(&config.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); + let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); (database, in_memory_whitelist, whitelist_authorization, authentication) } diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index a87e4ca8e..59b484cce 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -22,8 +22,10 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; use crate::container::AppContainer; +use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; +use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{authentication, whitelist}; @@ -93,11 +95,12 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication = Arc::new(authentication::Facade::new( - &configuration.core, + let authentication_service = Arc::new(service::Service::new(&configuration.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); + let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); let tracker = Arc::new(initialize_tracker( configuration, diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index abcc2a08c..a68686224 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -100,8 +100,10 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::http_tracker::start_job; + use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, statistics}; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{authentication, whitelist}; @@ -127,11 +129,12 @@ mod tests { )); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication = Arc::new(authentication::Facade::new( - &cfg.core, + let authentication_service = Arc::new(service::Service::new(&cfg.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); + let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 56e4a2e44..9ddd095c8 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -149,8 +149,10 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::tracker_apis::start_job; + use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{authentication, whitelist}; @@ -180,11 +182,12 @@ mod tests { let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication = Arc::new(authentication::Facade::new( - &cfg.core, + let authentication_service = Arc::new(service::Service::new(&cfg.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); + let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index d26379b09..9ac3638fc 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -1,10 +1,7 @@ use std::sync::Arc; use std::time::Duration; -use handler::{AddKeyRequest, KeysHandler}; -use key::repository::in_memory::InMemoryKeyRepository; -use key::repository::persisted::DatabaseKeyRepository; -use torrust_tracker_configuration::Core; +use handler::AddKeyRequest; use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::databases::{self}; @@ -21,22 +18,18 @@ pub type Error = key::Error; pub struct Facade { /// The authentication service. - authentication_service: service::Service, + authentication_service: Arc, /// The keys handler. - keys_handler: handler::KeysHandler, + keys_handler: Arc, } impl Facade { #[must_use] - pub fn new( - config: &Core, - db_key_repository: &Arc, - in_memory_key_repository: &Arc, - ) -> Self { + pub fn new(authentication_service: &Arc, keys_handler: &Arc) -> Self { Self { - authentication_service: service::Service::new(config, in_memory_key_repository), - keys_handler: KeysHandler::new(&db_key_repository.clone(), &in_memory_key_repository.clone()), + authentication_service: authentication_service.clone(), + keys_handler: keys_handler.clone(), } } @@ -153,9 +146,10 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; - use crate::core::authentication; + use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::core::authentication::{self, service}; use crate::core::services::initialize_database; fn instantiate_authentication_facade() -> authentication::Facade { @@ -180,7 +174,13 @@ mod tests { let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - authentication::Facade::new(&config.core, &db_key_repository.clone(), &in_memory_key_repository.clone()) + let authentication_service = Arc::new(service::Service::new(&config.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); + + authentication::Facade::new(&authentication_service, &keys_handler) } #[tokio::test] diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index b6ff50995..956d54799 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -342,8 +342,10 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::make_rust_tls; + use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{authentication, whitelist}; @@ -373,11 +375,12 @@ mod tests { let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication = Arc::new(authentication::Facade::new( - &cfg.core, + let authentication_service = Arc::new(service::Service::new(&cfg.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); + let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 140ef4e07..751ac5d5c 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -246,8 +246,10 @@ mod tests { use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::make_rust_tls; + use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{authentication, whitelist}; @@ -272,11 +274,12 @@ mod tests { let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication = Arc::new(authentication::Facade::new( - &cfg.core, + let authentication_service = Arc::new(service::Service::new(&cfg.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); + let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index fafb82997..cebeb9b0a 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -64,8 +64,10 @@ mod tests { use super::spawner::Spawner; use super::Server; use crate::bootstrap::app::initialize_global_services; + use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{authentication, whitelist}; @@ -92,11 +94,12 @@ mod tests { let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication = Arc::new(authentication::Facade::new( - &cfg.core, + let authentication_service = Arc::new(service::Service::new(&cfg.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); + let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); @@ -144,11 +147,12 @@ mod tests { )); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication = Arc::new(authentication::Facade::new( - &cfg.core, + let authentication_service = Arc::new(service::Service::new(&cfg.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); + let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); From 457d01b36b6bda0e8e8099a861a79bfaa883a2c1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 22 Jan 2025 09:59:57 +0000 Subject: [PATCH 0629/1297] refactor: [#1195] rename service to AuthenticationService --- src/app_test.rs | 2 +- src/bootstrap/app.rs | 5 ++++- src/bootstrap/jobs/http_tracker.rs | 2 +- src/bootstrap/jobs/tracker_apis.rs | 2 +- src/core/authentication/mod.rs | 6 +++--- src/core/authentication/service.rs | 10 +++++----- src/servers/apis/server.rs | 2 +- src/servers/http/server.rs | 2 +- src/servers/udp/server/mod.rs | 4 ++-- 9 files changed, 19 insertions(+), 16 deletions(-) diff --git a/src/app_test.rs b/src/app_test.rs index 6aa318e97..461a18758 100644 --- a/src/app_test.rs +++ b/src/app_test.rs @@ -31,7 +31,7 @@ pub fn initialize_tracker_dependencies( )); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::Service::new(&config.core, &in_memory_key_repository)); + let authentication_service = Arc::new(service::AuthenticationService::new(&config.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 59b484cce..5c2d47c40 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -95,7 +95,10 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::Service::new(&configuration.core, &in_memory_key_repository)); + let authentication_service = Arc::new(service::AuthenticationService::new( + &configuration.core, + &in_memory_key_repository, + )); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index a68686224..a26906fa5 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -129,7 +129,7 @@ mod tests { )); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::Service::new(&cfg.core, &in_memory_key_repository)); + let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 9ddd095c8..dfc5b108a 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -182,7 +182,7 @@ mod tests { let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::Service::new(&cfg.core, &in_memory_key_repository)); + let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 9ac3638fc..ebc7b1fe1 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -18,7 +18,7 @@ pub type Error = key::Error; pub struct Facade { /// The authentication service. - authentication_service: Arc, + authentication_service: Arc, /// The keys handler. keys_handler: Arc, @@ -26,7 +26,7 @@ pub struct Facade { impl Facade { #[must_use] - pub fn new(authentication_service: &Arc, keys_handler: &Arc) -> Self { + pub fn new(authentication_service: &Arc, keys_handler: &Arc) -> Self { Self { authentication_service: authentication_service.clone(), keys_handler: keys_handler.clone(), @@ -174,7 +174,7 @@ mod tests { let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::Service::new(&config.core, &in_memory_key_repository)); + let authentication_service = Arc::new(service::AuthenticationService::new(&config.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), diff --git a/src/core/authentication/service.rs b/src/core/authentication/service.rs index d7572136f..d100e3a70 100644 --- a/src/core/authentication/service.rs +++ b/src/core/authentication/service.rs @@ -7,7 +7,7 @@ use super::key::repository::in_memory::InMemoryKeyRepository; use super::{key, Error, Key}; #[derive(Debug)] -pub struct Service { +pub struct AuthenticationService { /// The tracker configuration. config: Core, @@ -15,7 +15,7 @@ pub struct Service { in_memory_key_repository: Arc, } -impl Service { +impl AuthenticationService { #[must_use] pub fn new(config: &Core, in_memory_key_repository: &Arc) -> Self { Self { @@ -81,14 +81,14 @@ mod tests { use crate::core::authentication; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::core::authentication::service::Service; + use crate::core::authentication::service::AuthenticationService; - fn instantiate_authentication() -> Service { + fn instantiate_authentication() -> AuthenticationService { let config = configuration::ephemeral_private(); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - Service::new(&config.core, &in_memory_key_repository.clone()) + AuthenticationService::new(&config.core, &in_memory_key_repository.clone()) } #[tokio::test] diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 956d54799..de7845eba 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -375,7 +375,7 @@ mod tests { let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::Service::new(&cfg.core, &in_memory_key_repository)); + let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 751ac5d5c..ef13a3535 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -274,7 +274,7 @@ mod tests { let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::Service::new(&cfg.core, &in_memory_key_repository)); + let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index cebeb9b0a..9658b1bca 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -94,7 +94,7 @@ mod tests { let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::Service::new(&cfg.core, &in_memory_key_repository)); + let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), @@ -147,7 +147,7 @@ mod tests { )); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::Service::new(&cfg.core, &in_memory_key_repository)); + let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), From 747b6089b92aad1c08804d64eec5f35a7ac8e376 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 22 Jan 2025 10:37:57 +0000 Subject: [PATCH 0630/1297] refactor: [#1195] use AuthenticationService directy Instead of via the authentication::Facade. The Facade will be removed. --- src/app.rs | 1 + src/app_test.rs | 13 ++- src/bootstrap/app.rs | 1 + src/bootstrap/jobs/http_tracker.rs | 15 +++- src/container.rs | 2 + src/core/mod.rs | 6 +- src/core/services/statistics/mod.rs | 3 +- src/core/services/torrent.rs | 14 +-- src/servers/http/server.rs | 38 ++++++++- src/servers/http/v1/handlers/announce.rs | 52 +++++++++--- src/servers/http/v1/handlers/scrape.rs | 85 ++++++++++++++----- src/servers/http/v1/routes.rs | 24 +++++- src/servers/http/v1/services/announce.rs | 4 +- src/servers/http/v1/services/scrape.rs | 6 +- src/servers/udp/handlers.rs | 8 +- tests/servers/api/environment.rs | 5 ++ .../api/v1/contract/context/auth_key.rs | 9 +- tests/servers/http/environment.rs | 6 ++ 18 files changed, 227 insertions(+), 65 deletions(-) diff --git a/src/app.rs b/src/app.rs index da8795ffe..8fa14da54 100644 --- a/src/app.rs +++ b/src/app.rs @@ -100,6 +100,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< if let Some(job) = http_tracker::start_job( http_tracker_config, app_container.tracker.clone(), + app_container.authentication_service.clone(), app_container.whitelist_authorization.clone(), app_container.stats_event_sender.clone(), registar.give_form(), diff --git a/src/app_test.rs b/src/app_test.rs index 461a18758..d4e8df961 100644 --- a/src/app_test.rs +++ b/src/app_test.rs @@ -6,7 +6,7 @@ use torrust_tracker_configuration::Configuration; use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; -use crate::core::authentication::service; +use crate::core::authentication::service::{self, AuthenticationService}; use crate::core::databases::Database; use crate::core::services::initialize_database; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; @@ -22,6 +22,7 @@ pub fn initialize_tracker_dependencies( Arc, Arc, Arc, + Arc, ) { let database = initialize_database(config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -36,7 +37,13 @@ pub fn initialize_tracker_dependencies( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); + let authentication_facade = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); - (database, in_memory_whitelist, whitelist_authorization, authentication) + ( + database, + in_memory_whitelist, + whitelist_authorization, + authentication_facade, + authentication_service, + ) } diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 5c2d47c40..31689005d 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -114,6 +114,7 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { AppContainer { tracker, + authentication_service, whitelist_authorization, ban_service, stats_event_sender, diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index a26906fa5..46e627b6b 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -19,6 +19,7 @@ use torrust_tracker_configuration::HttpTracker; use tracing::instrument; use super::make_rust_tls; +use crate::core::authentication::service::AuthenticationService; use crate::core::statistics::event::sender::Sender; use crate::core::{self, statistics, whitelist}; use crate::servers::http::server::{HttpServer, Launcher}; @@ -34,10 +35,11 @@ use crate::servers::registar::ServiceRegistrationForm; /// /// It would panic if the `config::HttpTracker` struct would contain inappropriate values. /// -#[instrument(skip(config, tracker, whitelist_authorization, stats_event_sender, form))] +#[instrument(skip(config, tracker, authentication_service, whitelist_authorization, stats_event_sender, form))] pub async fn start_job( config: &HttpTracker, tracker: Arc, + authentication_service: Arc, whitelist_authorization: Arc, stats_event_sender: Arc>>, form: ServiceRegistrationForm, @@ -55,6 +57,7 @@ pub async fn start_job( socket, tls, tracker.clone(), + authentication_service.clone(), whitelist_authorization.clone(), stats_event_sender.clone(), form, @@ -70,12 +73,19 @@ async fn start_v1( socket: SocketAddr, tls: Option, tracker: Arc, + authentication_service: Arc, whitelist_authorization: Arc, stats_event_sender: Arc>>, form: ServiceRegistrationForm, ) -> JoinHandle<()> { let server = HttpServer::new(Launcher::new(socket, tls)) - .start(tracker, whitelist_authorization, stats_event_sender, form) + .start( + tracker, + authentication_service, + whitelist_authorization, + stats_event_sender, + form, + ) .await .expect("it should be able to start to the http tracker"); @@ -143,6 +153,7 @@ mod tests { start_job( config, tracker, + authentication_service, whitelist_authorization, stats_event_sender, Registar::default().give_form(), diff --git a/src/container.rs b/src/container.rs index 3c9229b89..0ea8e3c03 100644 --- a/src/container.rs +++ b/src/container.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use tokio::sync::RwLock; +use crate::core::authentication::service::AuthenticationService; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; use crate::core::whitelist::manager::WhiteListManager; @@ -10,6 +11,7 @@ use crate::servers::udp::server::banning::BanService; pub struct AppContainer { pub tracker: Arc, + pub authentication_service: Arc, pub whitelist_authorization: Arc, pub ban_service: Arc>, pub stats_event_sender: Arc>>, diff --git a/src/core/mod.rs b/src/core/mod.rs index 9a5692690..2b13bc0c0 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -816,7 +816,7 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); initialize_tracker(&config, &database, &whitelist_authorization, &authentication) @@ -825,7 +825,7 @@ mod tests { fn whitelisted_tracker() -> (Tracker, Arc, Arc) { let config = configuration::ephemeral_listed(); - let (database, in_memory_whitelist, whitelist_authorization, authentication) = + let (database, in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); @@ -839,7 +839,7 @@ mod tests { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); initialize_tracker(&config, &database, &whitelist_authorization, &authentication) diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 4081fd6bb..a30588472 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -132,7 +132,8 @@ mod tests { async fn the_statistics_service_should_return_the_tracker_metrics() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + initialize_tracker_dependencies(&config); let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_repository = Arc::new(stats_repository); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index c23c7e04b..462f10101 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -142,7 +142,7 @@ mod tests { async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); let tracker = initialize_tracker(&config, &database, &whitelist_authorization, &authentication); @@ -162,7 +162,7 @@ mod tests { async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); let tracker = Arc::new(initialize_tracker( @@ -213,7 +213,7 @@ mod tests { async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); let tracker = Arc::new(initialize_tracker( @@ -232,7 +232,7 @@ mod tests { async fn should_return_a_summarized_info_for_all_torrents() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); let tracker = Arc::new(initialize_tracker( @@ -264,7 +264,7 @@ mod tests { async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); let tracker = Arc::new(initialize_tracker( @@ -294,7 +294,7 @@ mod tests { async fn should_allow_using_pagination_in_the_result() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); let tracker = Arc::new(initialize_tracker( @@ -333,7 +333,7 @@ mod tests { async fn should_return_torrents_ordered_by_info_hash() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); let tracker = Arc::new(initialize_tracker( diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index ef13a3535..3bc6773dd 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -11,6 +11,7 @@ use tracing::instrument; use super::v1::routes::router; use crate::bootstrap::jobs::Started; +use crate::core::authentication::service::AuthenticationService; use crate::core::{statistics, whitelist, Tracker}; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; @@ -42,10 +43,19 @@ pub struct Launcher { } impl Launcher { - #[instrument(skip(self, tracker, whitelist_authorization, stats_event_sender, tx_start, rx_halt))] + #[instrument(skip( + self, + tracker, + authentication_service, + whitelist_authorization, + stats_event_sender, + tx_start, + rx_halt + ))] fn start( &self, tracker: Arc, + authentication_service: Arc, whitelist_authorization: Arc, stats_event_sender: Arc>>, tx_start: Sender, @@ -67,7 +77,13 @@ impl Launcher { tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{}", address); - let app = router(tracker, whitelist_authorization, stats_event_sender, address); + let app = router( + tracker, + authentication_service, + whitelist_authorization, + stats_event_sender, + address, + ); let running = Box::pin(async { match tls { @@ -163,6 +179,7 @@ impl HttpServer { pub async fn start( self, tracker: Arc, + authentication_service: Arc, whitelist_authorization: Arc, stats_event_sender: Arc>>, form: ServiceRegistrationForm, @@ -173,7 +190,14 @@ impl HttpServer { let launcher = self.state.launcher; let task = tokio::spawn(async move { - let server = launcher.start(tracker, whitelist_authorization, stats_event_sender, tx_start, rx_halt); + let server = launcher.start( + tracker, + authentication_service, + whitelist_authorization, + stats_event_sender, + tx_start, + rx_halt, + ); server.await; @@ -296,7 +320,13 @@ mod tests { let stopped = HttpServer::new(Launcher::new(bind_to, tls)); let started = stopped - .start(tracker, whitelist_authorization, stats_event_sender, register.give_form()) + .start( + tracker, + authentication_service, + whitelist_authorization, + stats_event_sender, + register.give_form(), + ) .await .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 7af2b9261..fbadde967 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -21,6 +21,7 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; +use crate::core::authentication::service::AuthenticationService; use crate::core::authentication::Key; use crate::core::statistics::event::sender::Sender; use crate::core::{whitelist, PeersWanted, Tracker}; @@ -38,6 +39,7 @@ use crate::CurrentClock; pub async fn handle_without_key( State(state): State<( Arc, + Arc, Arc, Arc>>, )>, @@ -46,7 +48,16 @@ pub async fn handle_without_key( ) -> Response { tracing::debug!("http announce request: {:#?}", announce_request); - handle(&state.0, &state.1, &state.2, &announce_request, &client_ip_sources, None).await + handle( + &state.0, + &state.1, + &state.2, + &state.3, + &announce_request, + &client_ip_sources, + None, + ) + .await } /// It handles the `announce` request when the HTTP tracker requires @@ -56,6 +67,7 @@ pub async fn handle_without_key( pub async fn handle_with_key( State(state): State<( Arc, + Arc, Arc, Arc>>, )>, @@ -65,7 +77,16 @@ pub async fn handle_with_key( ) -> Response { tracing::debug!("http announce request: {:#?}", announce_request); - handle(&state.0, &state.1, &state.2, &announce_request, &client_ip_sources, Some(key)).await + handle( + &state.0, + &state.1, + &state.2, + &state.3, + &announce_request, + &client_ip_sources, + Some(key), + ) + .await } /// It handles the `announce` request. @@ -74,6 +95,7 @@ pub async fn handle_with_key( /// `unauthenticated` modes. async fn handle( tracker: &Arc, + authentication_service: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, announce_request: &Announce, @@ -82,6 +104,7 @@ async fn handle( ) -> Response { let announce_data = match handle_announce( tracker, + authentication_service, whitelist_authorization, opt_stats_event_sender, announce_request, @@ -104,6 +127,7 @@ async fn handle( async fn handle_announce( tracker: &Arc, + authentication_service: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, announce_request: &Announce, @@ -113,7 +137,7 @@ async fn handle_announce( // Authentication if tracker.requires_authentication() { match maybe_key { - Some(key) => match tracker.authentication.authenticate(&key).await { + Some(key) => match authentication_service.authenticate(&key).await { Ok(()) => (), Err(error) => return Err(responses::error::Error::from(error)), }, @@ -220,6 +244,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; + use crate::core::authentication::service::AuthenticationService; use crate::core::services::{initialize_tracker, statistics}; use crate::core::statistics::event::sender::Sender; use crate::core::{whitelist, Tracker}; @@ -228,6 +253,7 @@ mod tests { Arc, Arc>>, Arc, + Arc, ); fn private_tracker() -> TrackerAndDeps { @@ -248,7 +274,8 @@ mod tests { /// Initialize tracker's dependencies and tracker. fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication, authentication_service) = + initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); @@ -259,7 +286,7 @@ mod tests { &authentication, )); - (tracker, stats_event_sender, whitelist_authorization) + (tracker, stats_event_sender, whitelist_authorization, authentication_service) } fn sample_announce_request() -> Announce { @@ -302,7 +329,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_missing() { - let (tracker, stats_event_sender, whitelist_authorization) = private_tracker(); + let (tracker, stats_event_sender, whitelist_authorization, authentication_service) = private_tracker(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -311,6 +338,7 @@ mod tests { let response = handle_announce( &tracker, + &authentication_service, &whitelist_authorization, &stats_event_sender, &sample_announce_request(), @@ -328,7 +356,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_invalid() { - let (tracker, stats_event_sender, whitelist_authorization) = private_tracker(); + let (tracker, stats_event_sender, whitelist_authorization, authentication_service) = private_tracker(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -339,6 +367,7 @@ mod tests { let response = handle_announce( &tracker, + &authentication_service, &whitelist_authorization, &stats_event_sender, &sample_announce_request(), @@ -362,7 +391,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_announced_torrent_is_not_whitelisted() { - let (tracker, stats_event_sender, whitelist_authorization) = whitelisted_tracker(); + let (tracker, stats_event_sender, whitelist_authorization, authentication_service) = whitelisted_tracker(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -371,6 +400,7 @@ mod tests { let response = handle_announce( &tracker, + &authentication_service, &whitelist_authorization, &stats_event_sender, &announce_request, @@ -402,7 +432,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let (tracker, stats_event_sender, whitelist_authorization) = tracker_on_reverse_proxy(); + let (tracker, stats_event_sender, whitelist_authorization, authentication_service) = tracker_on_reverse_proxy(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -414,6 +444,7 @@ mod tests { let response = handle_announce( &tracker, + &authentication_service, &whitelist_authorization, &stats_event_sender, &sample_announce_request(), @@ -442,7 +473,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let (tracker, stats_event_sender, whitelist_authorization) = tracker_not_on_reverse_proxy(); + let (tracker, stats_event_sender, whitelist_authorization, authentication_service) = tracker_not_on_reverse_proxy(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -454,6 +485,7 @@ mod tests { let response = handle_announce( &tracker, + &authentication_service, &whitelist_authorization, &stats_event_sender, &sample_announce_request(), diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 062a017f8..f7be42bff 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -15,6 +15,7 @@ use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSou use hyper::StatusCode; use torrust_tracker_primitives::core::ScrapeData; +use crate::core::authentication::service::AuthenticationService; use crate::core::authentication::Key; use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; @@ -28,13 +29,13 @@ use crate::servers::http::v1::services; #[allow(clippy::unused_async)] #[allow(clippy::type_complexity)] pub async fn handle_without_key( - State(state): State<(Arc, Arc>>)>, + State(state): State<(Arc, Arc, Arc>>)>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { tracing::debug!("http scrape request: {:#?}", &scrape_request); - handle(&state.0, &state.1, &scrape_request, &client_ip_sources, None).await + handle(&state.0, &state.1, &state.2, &scrape_request, &client_ip_sources, None).await } /// It handles the `scrape` request when the HTTP tracker is configured @@ -44,24 +45,34 @@ pub async fn handle_without_key( #[allow(clippy::unused_async)] #[allow(clippy::type_complexity)] pub async fn handle_with_key( - State(state): State<(Arc, Arc>>)>, + State(state): State<(Arc, Arc, Arc>>)>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { tracing::debug!("http scrape request: {:#?}", &scrape_request); - handle(&state.0, &state.1, &scrape_request, &client_ip_sources, Some(key)).await + handle(&state.0, &state.1, &state.2, &scrape_request, &client_ip_sources, Some(key)).await } async fn handle( tracker: &Arc, + authentication_service: &Arc, stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Response { - let scrape_data = match handle_scrape(tracker, stats_event_sender, scrape_request, client_ip_sources, maybe_key).await { + let scrape_data = match handle_scrape( + tracker, + authentication_service, + stats_event_sender, + scrape_request, + client_ip_sources, + maybe_key, + ) + .await + { Ok(scrape_data) => scrape_data, Err(error) => return (StatusCode::OK, error.write()).into_response(), }; @@ -76,6 +87,7 @@ async fn handle( async fn handle_scrape( tracker: &Arc, + authentication_service: &Arc, opt_stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, @@ -84,7 +96,7 @@ async fn handle_scrape( // Authentication let return_real_scrape_data = if tracker.requires_authentication() { match maybe_key { - Some(key) => match tracker.authentication.authenticate(&key).await { + Some(key) => match authentication_service.authenticate(&key).await { Ok(()) => true, Err(_error) => false, }, @@ -119,6 +131,7 @@ fn build_response(scrape_data: ScrapeData) -> Response { mod tests { use std::net::IpAddr; use std::str::FromStr; + use std::sync::Arc; use bittorrent_http_protocol::v1::requests::scrape::Scrape; use bittorrent_http_protocol::v1::responses; @@ -127,54 +140,83 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; + use crate::core::authentication::service::AuthenticationService; use crate::core::services::{initialize_tracker, statistics}; use crate::core::Tracker; - fn private_tracker() -> (Tracker, Option>) { + fn private_tracker() -> ( + Tracker, + Option>, + Arc, + ) { let config = configuration::ephemeral_private(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication, authentication_service) = + initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( initialize_tracker(&config, &database, &whitelist_authorization, &authentication), stats_event_sender, + authentication_service, ) } - fn whitelisted_tracker() -> (Tracker, Option>) { + fn whitelisted_tracker() -> ( + Tracker, + Option>, + Arc, + ) { let config = configuration::ephemeral_listed(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication, authentication_service) = + initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( initialize_tracker(&config, &database, &whitelist_authorization, &authentication), stats_event_sender, + authentication_service, ) } - fn tracker_on_reverse_proxy() -> (Tracker, Option>) { + fn tracker_on_reverse_proxy() -> ( + Tracker, + Option>, + Arc, + ) { let config = configuration::ephemeral_with_reverse_proxy(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication, authentication_service) = + initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( initialize_tracker(&config, &database, &whitelist_authorization, &authentication), stats_event_sender, + authentication_service, ) } - fn tracker_not_on_reverse_proxy() -> (Tracker, Option>) { + fn tracker_not_on_reverse_proxy() -> ( + Tracker, + Option>, + Arc, + ) { let config = configuration::ephemeral_without_reverse_proxy(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication, authentication_service) = + initialize_tracker_dependencies(&config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( initialize_tracker(&config, &database, &whitelist_authorization, &authentication), stats_event_sender, + authentication_service, ) } @@ -210,7 +252,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { - let (tracker, stats_event_sender) = private_tracker(); + let (tracker, stats_event_sender, authentication_service) = private_tracker(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -219,6 +261,7 @@ mod tests { let scrape_data = handle_scrape( &tracker, + &authentication_service, &stats_event_sender, &scrape_request, &sample_client_ip_sources(), @@ -234,7 +277,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() { - let (tracker, stats_event_sender) = private_tracker(); + let (tracker, stats_event_sender, authentication_service) = private_tracker(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -244,6 +287,7 @@ mod tests { let scrape_data = handle_scrape( &tracker, + &authentication_service, &stats_event_sender, &scrape_request, &sample_client_ip_sources(), @@ -269,7 +313,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() { - let (tracker, stats_event_sender) = whitelisted_tracker(); + let (tracker, stats_event_sender, authentication_service) = whitelisted_tracker(); let tracker: Arc = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -277,6 +321,7 @@ mod tests { let scrape_data = handle_scrape( &tracker, + &authentication_service, &stats_event_sender, &scrape_request, &sample_client_ip_sources(), @@ -302,7 +347,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let (tracker, stats_event_sender) = tracker_on_reverse_proxy(); + let (tracker, stats_event_sender, authentication_service) = tracker_on_reverse_proxy(); let tracker: Arc = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -313,6 +358,7 @@ mod tests { let response = handle_scrape( &tracker, + &authentication_service, &stats_event_sender, &sample_scrape_request(), &client_ip_sources, @@ -339,7 +385,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let (tracker, stats_event_sender) = tracker_not_on_reverse_proxy(); + let (tracker, stats_event_sender, authentication_service) = tracker_not_on_reverse_proxy(); let tracker: Arc = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -350,6 +396,7 @@ mod tests { let response = handle_scrape( &tracker, + &authentication_service, &stats_event_sender, &sample_scrape_request(), &client_ip_sources, diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index d37c55c7a..7a1465500 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -22,6 +22,7 @@ use tower_http::LatencyUnit; use tracing::{instrument, Level, Span}; use super::handlers::{announce, health_check, scrape}; +use crate::core::authentication::service::AuthenticationService; use crate::core::statistics::event::sender::Sender; use crate::core::{whitelist, Tracker}; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; @@ -32,9 +33,16 @@ use crate::servers::logging::Latency; /// > **NOTICE**: it's added a layer to get the client IP from the connection /// > info. The tracker could use the connection info to get the client IP. #[allow(clippy::needless_pass_by_value)] -#[instrument(skip(tracker, whitelist_authorization, stats_event_sender, server_socket_addr))] +#[instrument(skip( + tracker, + authentication_service, + whitelist_authorization, + stats_event_sender, + server_socket_addr +))] pub fn router( tracker: Arc, + authentication_service: Arc, whitelist_authorization: Arc, stats_event_sender: Arc>>, server_socket_addr: SocketAddr, @@ -47,6 +55,7 @@ pub fn router( "/announce", get(announce::handle_without_key).with_state(( tracker.clone(), + authentication_service.clone(), whitelist_authorization.clone(), stats_event_sender.clone(), )), @@ -55,6 +64,7 @@ pub fn router( "/announce/{key}", get(announce::handle_with_key).with_state(( tracker.clone(), + authentication_service.clone(), whitelist_authorization.clone(), stats_event_sender.clone(), )), @@ -62,11 +72,19 @@ pub fn router( // Scrape request .route( "/scrape", - get(scrape::handle_without_key).with_state((tracker.clone(), stats_event_sender.clone())), + get(scrape::handle_without_key).with_state(( + tracker.clone(), + authentication_service.clone(), + stats_event_sender.clone(), + )), ) .route( "/scrape/{key}", - get(scrape::handle_with_key).with_state((tracker.clone(), stats_event_sender.clone())), + get(scrape::handle_with_key).with_state(( + tracker.clone(), + authentication_service.clone(), + stats_event_sender.clone(), + )), ) // Add extension to get the client IP from the connection info .layer(SecureClientIpSource::ConnectInfo.into_extension()) diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 929b00ff4..446af1db3 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -73,7 +73,7 @@ mod tests { fn public_tracker() -> (Tracker, Arc>>) { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); @@ -131,7 +131,7 @@ mod tests { fn test_tracker_factory() -> Tracker { let config = configuration::ephemeral(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); Tracker::new(&config.core, &database, &whitelist_authorization, &authentication).unwrap() diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 856b2ae72..35b264363 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -87,7 +87,8 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + initialize_tracker_dependencies(&config); initialize_tracker(&config, &database, &whitelist_authorization, &authentication) } @@ -115,7 +116,8 @@ mod tests { fn test_tracker_factory() -> Tracker { let config = configuration::ephemeral(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + initialize_tracker_dependencies(&config); Tracker::new(&config.core, &database, &whitelist_authorization, &authentication).unwrap() } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 67bb35c5a..f0f7719e2 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -516,7 +516,8 @@ mod tests { } fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { - let (database, in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(config); + let (database, in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); @@ -634,7 +635,8 @@ mod tests { fn test_tracker_factory() -> (Arc, Arc) { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + initialize_tracker_dependencies(&config); let tracker = Arc::new(Tracker::new(&config.core, &database, &whitelist_authorization, &authentication).unwrap()); @@ -1381,7 +1383,7 @@ mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - let (database, _in_memory_whitelist, whitelist_authorization, authentication) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 3bac7e570..3e8fedd0e 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -8,6 +8,7 @@ use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::{Configuration, HttpApi}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; +use torrust_tracker_lib::core::authentication::service::AuthenticationService; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; @@ -23,6 +24,7 @@ where { pub config: Arc, pub tracker: Arc, + pub authentication_service: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub whitelist_manager: Arc, @@ -58,6 +60,7 @@ impl Environment { Self { config, tracker: app_container.tracker.clone(), + authentication_service: app_container.authentication_service.clone(), stats_event_sender: app_container.stats_event_sender.clone(), stats_repository: app_container.stats_repository.clone(), whitelist_manager: app_container.whitelist_manager.clone(), @@ -73,6 +76,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + authentication_service: self.authentication_service.clone(), stats_event_sender: self.stats_event_sender.clone(), stats_repository: self.stats_repository.clone(), whitelist_manager: self.whitelist_manager.clone(), @@ -104,6 +108,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + authentication_service: self.authentication_service, stats_event_sender: self.stats_event_sender, stats_repository: self.stats_repository, whitelist_manager: self.whitelist_manager, diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index cee6b4034..6a270f894 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -36,8 +36,7 @@ async fn should_allow_generating_a_new_random_auth_key() { let auth_key_resource = assert_auth_key_utf8(response).await; assert!(env - .tracker - .authentication + .authentication_service .authenticate(&auth_key_resource.key.parse::().unwrap()) .await .is_ok()); @@ -66,8 +65,7 @@ async fn should_allow_uploading_a_preexisting_auth_key() { let auth_key_resource = assert_auth_key_utf8(response).await; assert!(env - .tracker - .authentication + .authentication_service .authenticate(&auth_key_resource.key.parse::().unwrap()) .await .is_ok()); @@ -499,8 +497,7 @@ mod deprecated_generate_key_endpoint { let auth_key_resource = assert_auth_key_utf8(response).await; assert!(env - .tracker - .authentication + .authentication_service .authenticate(&auth_key_resource.key.parse::().unwrap()) .await .is_ok()); diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index a8e5fc572..85921cd37 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -5,6 +5,7 @@ use futures::executor::block_on; use torrust_tracker_configuration::{Configuration, HttpTracker}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; +use torrust_tracker_lib::core::authentication::service::AuthenticationService; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; @@ -16,6 +17,7 @@ use torrust_tracker_primitives::peer; pub struct Environment { pub config: Arc, pub tracker: Arc, + pub authentication_service: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub whitelist_authorization: Arc, @@ -54,6 +56,7 @@ impl Environment { Self { config, tracker: app_container.tracker.clone(), + authentication_service: app_container.authentication_service.clone(), stats_event_sender: app_container.stats_event_sender.clone(), stats_repository: app_container.stats_repository.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), @@ -68,6 +71,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + authentication_service: self.authentication_service.clone(), whitelist_authorization: self.whitelist_authorization.clone(), stats_event_sender: self.stats_event_sender.clone(), stats_repository: self.stats_repository.clone(), @@ -77,6 +81,7 @@ impl Environment { .server .start( self.tracker, + self.authentication_service, self.whitelist_authorization, self.stats_event_sender, self.registar.give_form(), @@ -96,6 +101,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + authentication_service: self.authentication_service, whitelist_authorization: self.whitelist_authorization, stats_event_sender: self.stats_event_sender, stats_repository: self.stats_repository, From 661fe6abe741321ecdc3cb8e3519bd5bb5a2b714 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 22 Jan 2025 10:49:59 +0000 Subject: [PATCH 0631/1297] refactor: [#1195] remove AuthenticationService from authentication Facade It's now used directly. --- src/app_test.rs | 2 +- src/bootstrap/app.rs | 2 +- src/bootstrap/jobs/http_tracker.rs | 2 +- src/bootstrap/jobs/tracker_apis.rs | 4 +- src/core/authentication/mod.rs | 117 ++++++++++++----------------- src/servers/apis/server.rs | 4 +- src/servers/http/server.rs | 2 +- src/servers/udp/server/mod.rs | 8 +- 8 files changed, 60 insertions(+), 81 deletions(-) diff --git a/src/app_test.rs b/src/app_test.rs index d4e8df961..a8ad9f967 100644 --- a/src/app_test.rs +++ b/src/app_test.rs @@ -37,7 +37,7 @@ pub fn initialize_tracker_dependencies( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication_facade = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); + let authentication_facade = Arc::new(authentication::Facade::new(&keys_handler)); ( database, diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 31689005d..b5067f5f6 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -103,7 +103,7 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); + let authentication = Arc::new(authentication::Facade::new(&keys_handler)); let tracker = Arc::new(initialize_tracker( configuration, diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 46e627b6b..a0e11a688 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -144,7 +144,7 @@ mod tests { &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); + let authentication = Arc::new(authentication::Facade::new(&keys_handler)); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index dfc5b108a..39bfc112d 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -182,12 +182,12 @@ mod tests { let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); + let _authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); + let authentication = Arc::new(authentication::Facade::new(&keys_handler)); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index ebc7b1fe1..ac5db55d1 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -17,32 +17,18 @@ pub type Key = key::Key; pub type Error = key::Error; pub struct Facade { - /// The authentication service. - authentication_service: Arc, - /// The keys handler. keys_handler: Arc, } impl Facade { #[must_use] - pub fn new(authentication_service: &Arc, keys_handler: &Arc) -> Self { + pub fn new(keys_handler: &Arc) -> Self { Self { - authentication_service: authentication_service.clone(), keys_handler: keys_handler.clone(), } } - /// It authenticates the peer `key` against the `Tracker` authentication - /// key list. - /// - /// # Errors - /// - /// Will return an error if the the authentication key cannot be verified. - pub async fn authenticate(&self, key: &Key) -> Result<(), Error> { - self.authentication_service.authenticate(key).await - } - /// Adds new peer keys to the tracker. /// /// Keys can be pre-generated or randomly created. They can also be permanent or expire. @@ -149,26 +135,30 @@ mod tests { use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::core::authentication::service::AuthenticationService; use crate::core::authentication::{self, service}; use crate::core::services::initialize_database; - fn instantiate_authentication_facade() -> authentication::Facade { + fn instantiate_keys_manager_and_authentication() -> (authentication::Facade, Arc) { let config = configuration::ephemeral_private(); - instantiate_authentication_facade_with_configuration(&config) + instantiate_keys_manager_and_authentication_with_configuration(&config) } - fn instantiate_authentication_facade_with_checking_keys_expiration_disabled() -> authentication::Facade { + fn instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled( + ) -> (authentication::Facade, Arc) { let mut config = configuration::ephemeral_private(); config.core.private_mode = Some(PrivateMode { check_keys_expiration: false, }); - instantiate_authentication_facade_with_configuration(&config) + instantiate_keys_manager_and_authentication_with_configuration(&config) } - fn instantiate_authentication_facade_with_configuration(config: &Configuration) -> authentication::Facade { + fn instantiate_keys_manager_and_authentication_with_configuration( + config: &Configuration, + ) -> (authentication::Facade, Arc) { let database = initialize_database(config); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); @@ -180,52 +170,40 @@ mod tests { &in_memory_key_repository.clone(), )); - authentication::Facade::new(&authentication_service, &keys_handler) + let facade = authentication::Facade::new(&keys_handler); + + (facade, authentication_service) } #[tokio::test] async fn it_should_remove_an_authentication_key() { - let authentication = instantiate_authentication_facade(); + let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); - let expiring_key = authentication - .generate_auth_key(Some(Duration::from_secs(100))) - .await - .unwrap(); + let expiring_key = keys_manager.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); - let result = authentication.remove_auth_key(&expiring_key.key()).await; + let result = keys_manager.remove_auth_key(&expiring_key.key()).await; assert!(result.is_ok()); // The key should no longer be valid - assert!(authentication - .authentication_service - .authenticate(&expiring_key.key()) - .await - .is_err()); + assert!(authentication_service.authenticate(&expiring_key.key()).await.is_err()); } #[tokio::test] async fn it_should_load_authentication_keys_from_the_database() { - let authentication = instantiate_authentication_facade(); + let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); - let expiring_key = authentication - .generate_auth_key(Some(Duration::from_secs(100))) - .await - .unwrap(); + let expiring_key = keys_manager.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); // Remove the newly generated key in memory - authentication.remove_in_memory_auth_key(&expiring_key.key()).await; + keys_manager.remove_in_memory_auth_key(&expiring_key.key()).await; - let result = authentication.load_keys_from_database().await; + let result = keys_manager.load_keys_from_database().await; assert!(result.is_ok()); // The key should no longer be valid - assert!(authentication - .authentication_service - .authenticate(&expiring_key.key()) - .await - .is_ok()); + assert!(authentication_service.authenticate(&expiring_key.key()).await.is_ok()); } mod with_expiring_and { @@ -234,51 +212,51 @@ mod tests { use std::time::Duration; use crate::core::authentication::tests::the_tracker_configured_as_private::{ - instantiate_authentication_facade, instantiate_authentication_facade_with_checking_keys_expiration_disabled, + instantiate_keys_manager_and_authentication, + instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled, }; use crate::core::authentication::Key; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { - let authentication = instantiate_authentication_facade(); + let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); - let peer_key = authentication - .generate_auth_key(Some(Duration::from_secs(100))) - .await - .unwrap(); + let peer_key = keys_manager.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); - let result = authentication.authenticate(&peer_key.key()).await; + let result = authentication_service.authenticate(&peer_key.key()).await; assert!(result.is_ok()); } #[tokio::test] async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { - let authentication = instantiate_authentication_facade_with_checking_keys_expiration_disabled(); + let (keys_manager, authentication_service) = + instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled(); let past_timestamp = Duration::ZERO; - let peer_key = authentication + let peer_key = keys_manager .add_auth_key(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), Some(past_timestamp)) .await .unwrap(); - assert!(authentication.authenticate(&peer_key.key()).await.is_ok()); + assert!(authentication_service.authenticate(&peer_key.key()).await.is_ok()); } } mod pre_generated_keys { use crate::core::authentication::tests::the_tracker_configured_as_private::{ - instantiate_authentication_facade, instantiate_authentication_facade_with_checking_keys_expiration_disabled, + instantiate_keys_manager_and_authentication, + instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled, }; use crate::core::authentication::{AddKeyRequest, Key}; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { - let authentication = instantiate_authentication_facade(); + let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); - let peer_key = authentication + let peer_key = keys_manager .add_peer_key(AddKeyRequest { opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), opt_seconds_valid: Some(100), @@ -286,16 +264,17 @@ mod tests { .await .unwrap(); - let result = authentication.authenticate(&peer_key.key()).await; + let result = authentication_service.authenticate(&peer_key.key()).await; assert!(result.is_ok()); } #[tokio::test] async fn it_should_accept_an_expired_key_when_checking_expiration_is_disabled_in_configuration() { - let authentication = instantiate_authentication_facade_with_checking_keys_expiration_disabled(); + let (keys_manager, authentication_service) = + instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled(); - let peer_key = authentication + let peer_key = keys_manager .add_peer_key(AddKeyRequest { opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), opt_seconds_valid: Some(0), @@ -303,7 +282,7 @@ mod tests { .await .unwrap(); - assert!(authentication.authenticate(&peer_key.key()).await.is_ok()); + assert!(authentication_service.authenticate(&peer_key.key()).await.is_ok()); } } } @@ -311,29 +290,29 @@ mod tests { mod with_permanent_and { mod randomly_generated_keys { - use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_authentication_facade; + use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { - let authentication = instantiate_authentication_facade(); + let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); - let peer_key = authentication.generate_permanent_auth_key().await.unwrap(); + let peer_key = keys_manager.generate_permanent_auth_key().await.unwrap(); - let result = authentication.authenticate(&peer_key.key()).await; + let result = authentication_service.authenticate(&peer_key.key()).await; assert!(result.is_ok()); } } mod pre_generated_keys { - use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_authentication_facade; + use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication; use crate::core::authentication::{AddKeyRequest, Key}; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { - let authentication = instantiate_authentication_facade(); + let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); - let peer_key = authentication + let peer_key = keys_manager .add_peer_key(AddKeyRequest { opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), opt_seconds_valid: None, @@ -341,7 +320,7 @@ mod tests { .await .unwrap(); - let result = authentication.authenticate(&peer_key.key()).await; + let result = authentication_service.authenticate(&peer_key.key()).await; assert!(result.is_ok()); } diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index de7845eba..c9fc2f185 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -375,12 +375,12 @@ mod tests { let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); + let _authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); + let authentication = Arc::new(authentication::Facade::new(&keys_handler)); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 3bc6773dd..a9b618c84 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -303,7 +303,7 @@ mod tests { &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); + let authentication = Arc::new(authentication::Facade::new(&keys_handler)); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 9658b1bca..c507b3cb6 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -94,12 +94,12 @@ mod tests { let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); + let _authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); + let authentication = Arc::new(authentication::Facade::new(&keys_handler)); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); @@ -147,12 +147,12 @@ mod tests { )); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); + let _authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&authentication_service, &keys_handler)); + let authentication = Arc::new(authentication::Facade::new(&keys_handler)); let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); From 77eccdc33da86f8029b6fee7e467697650fd4fa6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 22 Jan 2025 10:50:49 +0000 Subject: [PATCH 0632/1297] fix: [#1195] format --- src/servers/http/v1/services/announce.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 446af1db3..2f2876f5b 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -73,7 +73,8 @@ mod tests { fn public_tracker() -> (Tracker, Arc>>) { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = initialize_tracker_dependencies(&config); + let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); From dff6bca1bbf587074ad31ddd8a73f3c4c15ba058 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 22 Jan 2025 11:27:57 +0000 Subject: [PATCH 0633/1297] refactor: [#1195] remove authentication::Facade service --- src/app.rs | 4 +- src/app_test.rs | 14 +- src/bootstrap/app.rs | 12 +- src/bootstrap/jobs/http_tracker.rs | 7 +- src/bootstrap/jobs/tracker_apis.rs | 23 ++- src/container.rs | 5 +- src/core/authentication/handler.rs | 6 +- src/core/authentication/mod.rs | 132 ++---------------- src/core/mod.rs | 17 +-- src/core/services/mod.rs | 5 +- src/core/services/statistics/mod.rs | 9 +- src/core/services/torrent.rs | 58 ++------ src/servers/apis/routes.rs | 5 + src/servers/apis/server.rs | 14 +- .../apis/v1/context/auth_key/handlers.rs | 27 ++-- .../apis/v1/context/auth_key/routes.rs | 12 +- src/servers/apis/v1/routes.rs | 5 +- src/servers/http/server.rs | 7 +- src/servers/http/v1/handlers/announce.rs | 9 +- src/servers/http/v1/handlers/scrape.rs | 16 +-- src/servers/http/v1/services/announce.rs | 8 +- src/servers/http/v1/services/scrape.rs | 8 +- src/servers/udp/handlers.rs | 18 +-- src/servers/udp/server/mod.rs | 12 +- tests/servers/api/environment.rs | 6 + .../api/v1/contract/context/auth_key.rs | 21 +-- tests/servers/http/environment.rs | 5 + tests/servers/http/v1/contract.rs | 6 +- 28 files changed, 161 insertions(+), 310 deletions(-) diff --git a/src/app.rs b/src/app.rs index 8fa14da54..e41f227e7 100644 --- a/src/app.rs +++ b/src/app.rs @@ -52,8 +52,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< // Load peer keys if app_container.tracker.is_private() { app_container - .tracker - .authentication + .keys_handler .load_keys_from_database() .await .expect("Could not retrieve keys from database."); @@ -120,6 +119,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< if let Some(job) = tracker_apis::start_job( http_api_config, app_container.tracker.clone(), + app_container.keys_handler.clone(), app_container.whitelist_manager.clone(), app_container.ban_service.clone(), app_container.stats_event_sender.clone(), diff --git a/src/app_test.rs b/src/app_test.rs index a8ad9f967..929a23418 100644 --- a/src/app_test.rs +++ b/src/app_test.rs @@ -9,8 +9,8 @@ use crate::core::authentication::key::repository::persisted::DatabaseKeyReposito use crate::core::authentication::service::{self, AuthenticationService}; use crate::core::databases::Database; use crate::core::services::initialize_database; +use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; -use crate::core::{authentication, whitelist}; /// Initialize the tracker dependencies. #[allow(clippy::type_complexity)] @@ -21,7 +21,6 @@ pub fn initialize_tracker_dependencies( Arc>, Arc, Arc, - Arc, Arc, ) { let database = initialize_database(config); @@ -33,17 +32,10 @@ pub fn initialize_tracker_dependencies( let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); let authentication_service = Arc::new(service::AuthenticationService::new(&config.core, &in_memory_key_repository)); - let keys_handler = Arc::new(KeysHandler::new( + let _keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication_facade = Arc::new(authentication::Facade::new(&keys_handler)); - ( - database, - in_memory_whitelist, - whitelist_authorization, - authentication_facade, - authentication_service, - ) + (database, in_memory_whitelist, whitelist_authorization, authentication_service) } diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index b5067f5f6..a0c7887cf 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -27,8 +27,8 @@ use crate::core::authentication::key::repository::in_memory::InMemoryKeyReposito use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; +use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; -use crate::core::{authentication, whitelist}; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; @@ -103,24 +103,18 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&keys_handler)); - let tracker = Arc::new(initialize_tracker( - configuration, - &database, - &whitelist_authorization, - &authentication, - )); + let tracker = Arc::new(initialize_tracker(configuration, &database, &whitelist_authorization)); AppContainer { tracker, + keys_handler, authentication_service, whitelist_authorization, ban_service, stats_event_sender, stats_repository, whitelist_manager, - authentication, } } diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index a0e11a688..4df669675 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -115,8 +115,8 @@ mod tests { use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, statistics}; + use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - use crate::core::{authentication, whitelist}; use crate::servers::http::Version; use crate::servers::registar::Registar; @@ -140,13 +140,12 @@ mod tests { let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); - let keys_handler = Arc::new(KeysHandler::new( + let _keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&keys_handler)); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); let version = Version::V1; diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 39bfc112d..9bb7e6d45 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -30,6 +30,7 @@ use torrust_tracker_configuration::{AccessTokens, HttpApi}; use tracing::instrument; use super::make_rust_tls; +use crate::core::authentication::handler::KeysHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; use crate::core::whitelist::manager::WhiteListManager; @@ -60,10 +61,20 @@ pub struct ApiServerJobStarted(); /// /// #[allow(clippy::too_many_arguments)] -#[instrument(skip(config, tracker, whitelist_manager, ban_service, stats_event_sender, stats_repository, form))] +#[instrument(skip( + config, + tracker, + keys_handler, + whitelist_manager, + ban_service, + stats_event_sender, + stats_repository, + form +))] pub async fn start_job( config: &HttpApi, tracker: Arc, + keys_handler: Arc, whitelist_manager: Arc, ban_service: Arc>, stats_event_sender: Arc>>, @@ -85,6 +96,7 @@ pub async fn start_job( bind_to, tls, tracker.clone(), + keys_handler.clone(), whitelist_manager.clone(), ban_service.clone(), stats_event_sender.clone(), @@ -103,6 +115,7 @@ pub async fn start_job( socket, tls, tracker, + keys_handler, whitelist_manager, ban_service, stats_event_sender, @@ -114,6 +127,7 @@ async fn start_v1( socket: SocketAddr, tls: Option, tracker: Arc, + keys_handler: Arc, whitelist_manager: Arc, ban_service: Arc>, stats_event_sender: Arc>>, @@ -124,6 +138,7 @@ async fn start_v1( let server = ApiServer::new(Launcher::new(socket, tls)) .start( tracker, + keys_handler, whitelist_manager, stats_event_sender, stats_repository, @@ -154,8 +169,8 @@ mod tests { use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; + use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - use crate::core::{authentication, whitelist}; use crate::servers::apis::Version; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -187,15 +202,15 @@ mod tests { &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&keys_handler)); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); let version = Version::V1; start_job( config, tracker, + keys_handler, whitelist_manager, ban_service, stats_event_sender, diff --git a/src/container.rs b/src/container.rs index 0ea8e3c03..14c4b5d7b 100644 --- a/src/container.rs +++ b/src/container.rs @@ -2,20 +2,21 @@ use std::sync::Arc; use tokio::sync::RwLock; +use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::service::AuthenticationService; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; use crate::core::whitelist::manager::WhiteListManager; -use crate::core::{authentication, whitelist, Tracker}; +use crate::core::{whitelist, Tracker}; use crate::servers::udp::server::banning::BanService; pub struct AppContainer { pub tracker: Arc, + pub keys_handler: Arc, pub authentication_service: Arc, pub whitelist_authorization: Arc, pub ban_service: Arc>, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub whitelist_manager: Arc, - pub authentication: Arc, } diff --git a/src/core/authentication/handler.rs b/src/core/authentication/handler.rs index 3ada2b110..17033aefc 100644 --- a/src/core/authentication/handler.rs +++ b/src/core/authentication/handler.rs @@ -303,7 +303,8 @@ mod tests { use torrust_tracker_clock::clock::Time; use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; - use crate::core::authentication::{AddKeyRequest, Key}; + use crate::core::authentication::handler::AddKeyRequest; + use crate::core::authentication::Key; use crate::CurrentClock; #[tokio::test] @@ -344,7 +345,8 @@ mod tests { mod pre_generated_keys { use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; - use crate::core::authentication::{AddKeyRequest, Key}; + use crate::core::authentication::handler::AddKeyRequest; + use crate::core::authentication::Key; #[tokio::test] async fn it_should_add_a_pre_generated_key() { diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index ac5db55d1..799263752 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -1,11 +1,3 @@ -use std::sync::Arc; -use std::time::Duration; - -use handler::AddKeyRequest; -use torrust_tracker_primitives::DurationSinceUnixEpoch; - -use super::databases::{self}; -use super::error::PeerKeyError; use crate::CurrentClock; pub mod handler; @@ -16,113 +8,11 @@ pub type PeerKey = key::PeerKey; pub type Key = key::Key; pub type Error = key::Error; -pub struct Facade { - /// The keys handler. - keys_handler: Arc, -} - -impl Facade { - #[must_use] - pub fn new(keys_handler: &Arc) -> Self { - Self { - keys_handler: keys_handler.clone(), - } - } - - /// Adds new peer keys to the tracker. - /// - /// Keys can be pre-generated or randomly created. They can also be permanent or expire. - /// - /// # Errors - /// - /// Will return an error if: - /// - /// - The key duration overflows the duration type maximum value. - /// - The provided pre-generated key is invalid. - /// - The key could not been persisted due to database issues. - pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { - self.keys_handler.add_peer_key(add_key_req).await - } - - /// It generates a new permanent authentication key. - /// - /// Authentication keys are used by HTTP trackers. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `auth_key` to the database. - pub async fn generate_permanent_auth_key(&self) -> Result { - self.keys_handler.generate_permanent_auth_key().await - } - - /// It generates a new expiring authentication key. - /// - /// Authentication keys are used by HTTP trackers. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `auth_key` to the database. - /// - /// # Arguments - /// - /// * `lifetime` - The duration in seconds for the new key. The key will be - /// no longer valid after `lifetime` seconds. - pub async fn generate_auth_key(&self, lifetime: Option) -> Result { - self.keys_handler.generate_auth_key(lifetime).await - } - - /// It adds a pre-generated authentication key. - /// - /// Authentication keys are used by HTTP trackers. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to add the `auth_key` to the - /// database. For example, if the key already exist. - /// - /// # Arguments - /// - /// * `key` - The pre-generated key. - /// * `lifetime` - The duration in seconds for the new key. The key will be - /// no longer valid after `lifetime` seconds. - pub async fn add_auth_key( - &self, - key: Key, - valid_until: Option, - ) -> Result { - self.keys_handler.add_auth_key(key, valid_until).await - } - - /// It removes an authentication key. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `key` to the database. - pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> { - self.keys_handler.remove_auth_key(key).await - } - - /// It removes an authentication key from memory. - pub async fn remove_in_memory_auth_key(&self, key: &Key) { - self.keys_handler.remove_in_memory_auth_key(key).await; - } - - /// The `Tracker` stores the authentication keys in memory and in the - /// database. In case you need to restart the `Tracker` you can load the - /// keys from the database into memory with this function. Keys are - /// automatically stored in the database when they are generated. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to `load_keys` from the database. - pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> { - self.keys_handler.load_keys_from_database().await - } -} - #[cfg(test)] mod tests { + // Integration tests for authentication. + mod the_tracker_configured_as_private { use std::sync::Arc; @@ -135,18 +25,18 @@ mod tests { use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::core::authentication::service; use crate::core::authentication::service::AuthenticationService; - use crate::core::authentication::{self, service}; use crate::core::services::initialize_database; - fn instantiate_keys_manager_and_authentication() -> (authentication::Facade, Arc) { + fn instantiate_keys_manager_and_authentication() -> (Arc, Arc) { let config = configuration::ephemeral_private(); instantiate_keys_manager_and_authentication_with_configuration(&config) } fn instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled( - ) -> (authentication::Facade, Arc) { + ) -> (Arc, Arc) { let mut config = configuration::ephemeral_private(); config.core.private_mode = Some(PrivateMode { @@ -158,7 +48,7 @@ mod tests { fn instantiate_keys_manager_and_authentication_with_configuration( config: &Configuration, - ) -> (authentication::Facade, Arc) { + ) -> (Arc, Arc) { let database = initialize_database(config); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); @@ -170,9 +60,7 @@ mod tests { &in_memory_key_repository.clone(), )); - let facade = authentication::Facade::new(&keys_handler); - - (facade, authentication_service) + (keys_handler, authentication_service) } #[tokio::test] @@ -246,11 +134,12 @@ mod tests { mod pre_generated_keys { + use crate::core::authentication::handler::AddKeyRequest; use crate::core::authentication::tests::the_tracker_configured_as_private::{ instantiate_keys_manager_and_authentication, instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled, }; - use crate::core::authentication::{AddKeyRequest, Key}; + use crate::core::authentication::Key; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { @@ -305,8 +194,9 @@ mod tests { } mod pre_generated_keys { + use crate::core::authentication::handler::AddKeyRequest; use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication; - use crate::core::authentication::{AddKeyRequest, Key}; + use crate::core::authentication::Key; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { diff --git a/src/core/mod.rs b/src/core/mod.rs index 2b13bc0c0..26ef69bfa 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -490,9 +490,6 @@ pub struct Tracker { /// The in-memory torrents repository. torrents: Arc, - - /// The service to authenticate peers. - pub authentication: Arc, } /// How many peers the peer announcing wants in the announce response. @@ -547,14 +544,12 @@ impl Tracker { config: &Core, database: &Arc>, whitelist_authorization: &Arc, - authentication: &Arc, ) -> Result { Ok(Tracker { config: config.clone(), database: database.clone(), whitelist_authorization: whitelist_authorization.clone(), torrents: Arc::default(), - authentication: authentication.clone(), }) } @@ -816,21 +811,21 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - initialize_tracker(&config, &database, &whitelist_authorization, &authentication) + initialize_tracker(&config, &database, &whitelist_authorization) } fn whitelisted_tracker() -> (Tracker, Arc, Arc) { let config = configuration::ephemeral_listed(); - let (database, in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = initialize_tracker(&config, &database, &whitelist_authorization, &authentication); + let tracker = initialize_tracker(&config, &database, &whitelist_authorization); (tracker, whitelist_authorization, whitelist_manager) } @@ -839,10 +834,10 @@ mod tests { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - initialize_tracker(&config, &database, &whitelist_authorization, &authentication) + initialize_tracker(&config, &database, &whitelist_authorization) } fn sample_info_hash() -> InfoHash { diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index b1d0d441d..611ea24d2 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -14,10 +14,10 @@ use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::Configuration; use super::databases::{self, Database}; +use super::whitelist; use super::whitelist::manager::WhiteListManager; use super::whitelist::repository::in_memory::InMemoryWhitelist; use super::whitelist::repository::persisted::DatabaseWhitelist; -use super::{authentication, whitelist}; use crate::core::Tracker; /// It returns a new tracker building its dependencies. @@ -30,9 +30,8 @@ pub fn initialize_tracker( config: &Configuration, database: &Arc>, whitelist_authorization: &Arc, - authentication: &Arc, ) -> Tracker { - match Tracker::new(&Arc::new(config).core, database, whitelist_authorization, authentication) { + match Tracker::new(&Arc::new(config).core, database, whitelist_authorization) { Ok(tracker) => tracker, Err(error) => { panic!("{}", error) diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index a30588472..cc59bcf12 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -132,17 +132,12 @@ mod tests { async fn the_statistics_service_should_return_the_tracker_metrics() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_repository = Arc::new(stats_repository); - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &authentication, - )); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 462f10101..9b7254098 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -142,10 +142,10 @@ mod tests { async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - let tracker = initialize_tracker(&config, &database, &whitelist_authorization, &authentication); + let tracker = initialize_tracker(&config, &database, &whitelist_authorization); let tracker = Arc::new(tracker); @@ -162,15 +162,10 @@ mod tests { async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &authentication, - )); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -213,15 +208,10 @@ mod tests { async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &authentication, - )); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -232,15 +222,10 @@ mod tests { async fn should_return_a_summarized_info_for_all_torrents() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &authentication, - )); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -264,15 +249,10 @@ mod tests { async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &authentication, - )); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -294,15 +274,10 @@ mod tests { async fn should_allow_using_pagination_in_the_result() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &authentication, - )); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -333,15 +308,10 @@ mod tests { async fn should_return_torrents_ordered_by_info_hash() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &authentication, - )); + let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index a5c33d5ee..4a005393d 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -30,6 +30,7 @@ use tracing::{instrument, Level, Span}; use super::v1; use super::v1::context::health_check::handlers::health_check_handler; use super::v1::middlewares::auth::State; +use crate::core::authentication::handler::KeysHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; use crate::core::whitelist::manager::WhiteListManager; @@ -39,9 +40,11 @@ use crate::servers::logging::Latency; use crate::servers::udp::server::banning::BanService; /// Add all API routes to the router. +#[allow(clippy::too_many_arguments)] #[allow(clippy::needless_pass_by_value)] #[instrument(skip( tracker, + keys_handler, whitelist_manager, ban_service, stats_event_sender, @@ -50,6 +53,7 @@ use crate::servers::udp::server::banning::BanService; ))] pub fn router( tracker: Arc, + keys_handler: Arc, whitelist_manager: Arc, ban_service: Arc>, stats_event_sender: Arc>>, @@ -65,6 +69,7 @@ pub fn router( api_url_prefix, router, tracker.clone(), + &keys_handler.clone(), &whitelist_manager.clone(), ban_service.clone(), stats_event_sender.clone(), diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index c9fc2f185..f219ca023 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -39,6 +39,7 @@ use tracing::{instrument, Level}; use super::routes::router; use crate::bootstrap::jobs::Started; +use crate::core::authentication::handler::KeysHandler; use crate::core::statistics::repository::Repository; use crate::core::whitelist::manager::WhiteListManager; use crate::core::{statistics, Tracker}; @@ -127,10 +128,11 @@ impl ApiServer { /// /// It would panic if the bound socket address cannot be sent back to this starter. #[allow(clippy::too_many_arguments)] - #[instrument(skip(self, tracker, whitelist_manager, stats_event_sender, ban_service, stats_repository, form, access_tokens), err, ret(Display, level = Level::INFO))] + #[instrument(skip(self, tracker, keys_handler, whitelist_manager, stats_event_sender, ban_service, stats_repository, form, access_tokens), err, ret(Display, level = Level::INFO))] pub async fn start( self, tracker: Arc, + keys_handler: Arc, whitelist_manager: Arc, stats_event_sender: Arc>>, stats_repository: Arc, @@ -149,6 +151,7 @@ impl ApiServer { let _task = launcher .start( tracker, + keys_handler, whitelist_manager, ban_service, stats_event_sender, @@ -259,6 +262,7 @@ impl Launcher { #[instrument(skip( self, tracker, + keys_handler, whitelist_manager, ban_service, stats_event_sender, @@ -270,6 +274,7 @@ impl Launcher { pub fn start( &self, tracker: Arc, + keys_handler: Arc, whitelist_manager: Arc, ban_service: Arc>, stats_event_sender: Arc>>, @@ -283,6 +288,7 @@ impl Launcher { let router = router( tracker, + keys_handler, whitelist_manager, ban_service, stats_event_sender, @@ -347,8 +353,8 @@ mod tests { use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; + use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - use crate::core::{authentication, whitelist}; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; @@ -380,9 +386,8 @@ mod tests { &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&keys_handler)); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); let bind_to = config.bind_address; @@ -399,6 +404,7 @@ mod tests { let started = stopped .start( tracker, + keys_handler, whitelist_manager, stats_event_sender, stats_repository, diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index f0c131bbf..045a9d211 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -12,9 +12,8 @@ use super::responses::{ auth_key_response, failed_to_delete_key_response, failed_to_generate_key_response, failed_to_reload_keys_response, invalid_auth_key_duration_response, invalid_auth_key_response, }; -use crate::core::authentication::handler::AddKeyRequest; +use crate::core::authentication::handler::{AddKeyRequest, KeysHandler}; use crate::core::authentication::Key; -use crate::core::Tracker; use crate::servers::apis::v1::context::auth_key::resources::AuthKey; use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_response}; @@ -32,11 +31,10 @@ use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_re /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#generate-a-new-authentication-key) /// for more information about this endpoint. pub async fn add_auth_key_handler( - State(tracker): State>, + State(keys_handler): State>, extract::Json(add_key_form): extract::Json, ) -> Response { - match tracker - .authentication + match keys_handler .add_peer_key(AddKeyRequest { opt_key: add_key_form.opt_key.clone(), opt_seconds_valid: add_key_form.opt_seconds_valid, @@ -67,13 +65,12 @@ pub async fn add_auth_key_handler( /// for more information about this endpoint. /// /// This endpoint has been deprecated. Use [`add_auth_key_handler`]. -pub async fn generate_auth_key_handler(State(tracker): State>, Path(seconds_valid_or_key): Path) -> Response { +pub async fn generate_auth_key_handler( + State(keys_handler): State>, + Path(seconds_valid_or_key): Path, +) -> Response { let seconds_valid = seconds_valid_or_key; - match tracker - .authentication - .generate_auth_key(Some(Duration::from_secs(seconds_valid))) - .await - { + match keys_handler.generate_auth_key(Some(Duration::from_secs(seconds_valid))).await { Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), Err(e) => failed_to_generate_key_response(e), } @@ -109,12 +106,12 @@ pub struct KeyParam(String); /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#delete-an-authentication-key) /// for more information about this endpoint. pub async fn delete_auth_key_handler( - State(tracker): State>, + State(keys_handler): State>, Path(seconds_valid_or_key): Path, ) -> Response { match Key::from_str(&seconds_valid_or_key.0) { Err(_) => invalid_auth_key_param_response(&seconds_valid_or_key.0), - Ok(key) => match tracker.authentication.remove_auth_key(&key).await { + Ok(key) => match keys_handler.remove_auth_key(&key).await { Ok(()) => ok_response(), Err(e) => failed_to_delete_key_response(e), }, @@ -133,8 +130,8 @@ pub async fn delete_auth_key_handler( /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#reload-authentication-keys) /// for more information about this endpoint. -pub async fn reload_keys_handler(State(tracker): State>) -> Response { - match tracker.authentication.load_keys_from_database().await { +pub async fn reload_keys_handler(State(keys_handler): State>) -> Response { + match keys_handler.load_keys_from_database().await { Ok(()) => ok_response(), Err(e) => failed_to_reload_keys_response(e), } diff --git a/src/servers/apis/v1/context/auth_key/routes.rs b/src/servers/apis/v1/context/auth_key/routes.rs index ac11281ee..45aeb02ec 100644 --- a/src/servers/apis/v1/context/auth_key/routes.rs +++ b/src/servers/apis/v1/context/auth_key/routes.rs @@ -12,10 +12,10 @@ use axum::routing::{get, post}; use axum::Router; use super::handlers::{add_auth_key_handler, delete_auth_key_handler, generate_auth_key_handler, reload_keys_handler}; -use crate::core::Tracker; +use crate::core::authentication::handler::KeysHandler; /// It adds the routes to the router for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. -pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { +pub fn add(prefix: &str, router: Router, keys_handler: Arc) -> Router { // Keys router .route( @@ -29,14 +29,14 @@ pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { // Use POST /keys &format!("{prefix}/key/{{seconds_valid_or_key}}"), post(generate_auth_key_handler) - .with_state(tracker.clone()) + .with_state(keys_handler.clone()) .delete(delete_auth_key_handler) - .with_state(tracker.clone()), + .with_state(keys_handler.clone()), ) // Keys command .route( &format!("{prefix}/keys/reload"), - get(reload_keys_handler).with_state(tracker.clone()), + get(reload_keys_handler).with_state(keys_handler.clone()), ) - .route(&format!("{prefix}/keys"), post(add_auth_key_handler).with_state(tracker)) + .route(&format!("{prefix}/keys"), post(add_auth_key_handler).with_state(keys_handler)) } diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs index 1954af2e4..c26ce4f3d 100644 --- a/src/servers/apis/v1/routes.rs +++ b/src/servers/apis/v1/routes.rs @@ -5,6 +5,7 @@ use axum::Router; use tokio::sync::RwLock; use super::context::{auth_key, stats, torrent, whitelist}; +use crate::core::authentication::handler::KeysHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; use crate::core::whitelist::manager::WhiteListManager; @@ -12,10 +13,12 @@ use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; /// Add the routes for the v1 API. +#[allow(clippy::too_many_arguments)] pub fn add( prefix: &str, router: Router, tracker: Arc, + keys_handler: &Arc, whitelist_manager: &Arc, ban_service: Arc>, stats_event_sender: Arc>>, @@ -23,7 +26,7 @@ pub fn add( ) -> Router { let v1_prefix = format!("{prefix}/v1"); - let router = auth_key::routes::add(&v1_prefix, router, tracker.clone()); + let router = auth_key::routes::add(&v1_prefix, router, keys_handler.clone()); let router = stats::routes::add( &v1_prefix, router, diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index a9b618c84..5f62a2013 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -275,8 +275,8 @@ mod tests { use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; + use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - use crate::core::{authentication, whitelist}; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::registar::Registar; @@ -299,13 +299,12 @@ mod tests { let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); - let keys_handler = Arc::new(KeysHandler::new( + let _keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&keys_handler)); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); let config = &http_trackers[0]; diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index fbadde967..c42981d4c 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -274,17 +274,12 @@ mod tests { /// Initialize tracker's dependencies and tracker. fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { - let (database, _in_memory_whitelist, whitelist_authorization, authentication, authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication_service) = initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = Arc::new(initialize_tracker( - config, - &database, - &whitelist_authorization, - &authentication, - )); + let tracker = Arc::new(initialize_tracker(config, &database, &whitelist_authorization)); (tracker, stats_event_sender, whitelist_authorization, authentication_service) } diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index f7be42bff..de4610a61 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -151,13 +151,13 @@ mod tests { ) { let config = configuration::ephemeral_private(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication_service) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( - initialize_tracker(&config, &database, &whitelist_authorization, &authentication), + initialize_tracker(&config, &database, &whitelist_authorization), stats_event_sender, authentication_service, ) @@ -170,13 +170,13 @@ mod tests { ) { let config = configuration::ephemeral_listed(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication_service) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( - initialize_tracker(&config, &database, &whitelist_authorization, &authentication), + initialize_tracker(&config, &database, &whitelist_authorization), stats_event_sender, authentication_service, ) @@ -189,13 +189,13 @@ mod tests { ) { let config = configuration::ephemeral_with_reverse_proxy(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication_service) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( - initialize_tracker(&config, &database, &whitelist_authorization, &authentication), + initialize_tracker(&config, &database, &whitelist_authorization), stats_event_sender, authentication_service, ) @@ -208,13 +208,13 @@ mod tests { ) { let config = configuration::ephemeral_without_reverse_proxy(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, authentication_service) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( - initialize_tracker(&config, &database, &whitelist_authorization, &authentication), + initialize_tracker(&config, &database, &whitelist_authorization), stats_event_sender, authentication_service, ) diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 2f2876f5b..018348d7e 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -73,12 +73,12 @@ mod tests { fn public_tracker() -> (Tracker, Arc>>) { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = initialize_tracker(&config, &database, &whitelist_authorization, &authentication); + let tracker = initialize_tracker(&config, &database, &whitelist_authorization); (tracker, stats_event_sender) } @@ -132,10 +132,10 @@ mod tests { fn test_tracker_factory() -> Tracker { let config = configuration::ephemeral(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - Tracker::new(&config.core, &database, &whitelist_authorization, &authentication).unwrap() + Tracker::new(&config.core, &database, &whitelist_authorization).unwrap() } #[tokio::test] diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 35b264363..9ad741234 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -87,10 +87,10 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - initialize_tracker(&config, &database, &whitelist_authorization, &authentication) + initialize_tracker(&config, &database, &whitelist_authorization) } fn sample_info_hashes() -> Vec { @@ -116,10 +116,10 @@ mod tests { fn test_tracker_factory() -> Tracker { let config = configuration::ephemeral(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - Tracker::new(&config.core, &database, &whitelist_authorization, &authentication).unwrap() + Tracker::new(&config.core, &database, &whitelist_authorization).unwrap() } mod with_real_data { diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index f0f7719e2..feeca4e40 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -516,18 +516,13 @@ mod tests { } fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { - let (database, in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = Arc::new(initialize_tracker( - config, - &database, - &whitelist_authorization, - &authentication, - )); + let tracker = Arc::new(initialize_tracker(config, &database, &whitelist_authorization)); ( tracker, @@ -635,10 +630,10 @@ mod tests { fn test_tracker_factory() -> (Arc, Arc) { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(Tracker::new(&config.core, &database, &whitelist_authorization, &authentication).unwrap()); + let tracker = Arc::new(Tracker::new(&config.core, &database, &whitelist_authorization).unwrap()); (tracker, whitelist_authorization) } @@ -1383,7 +1378,7 @@ mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - let (database, _in_memory_whitelist, whitelist_authorization, authentication, _authentication_service) = + let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = initialize_tracker_dependencies(&config); let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); @@ -1395,8 +1390,7 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = - Arc::new(core::Tracker::new(&config.core, &database, &whitelist_authorization, &authentication).unwrap()); + let tracker = Arc::new(core::Tracker::new(&config.core, &database, &whitelist_authorization).unwrap()); let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index c507b3cb6..844c18678 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -69,8 +69,8 @@ mod tests { use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; + use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - use crate::core::{authentication, whitelist}; use crate::servers::registar::Registar; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -95,13 +95,12 @@ mod tests { let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); let _authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); - let keys_handler = Arc::new(KeysHandler::new( + let _keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&keys_handler)); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; @@ -148,13 +147,12 @@ mod tests { let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); let _authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); - let keys_handler = Arc::new(KeysHandler::new( + let _keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let authentication = Arc::new(authentication::Facade::new(&keys_handler)); - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization, &authentication)); + let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 3e8fedd0e..f014df36f 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -8,6 +8,7 @@ use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::{Configuration, HttpApi}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; +use torrust_tracker_lib::core::authentication::handler::KeysHandler; use torrust_tracker_lib::core::authentication::service::AuthenticationService; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; @@ -24,6 +25,7 @@ where { pub config: Arc, pub tracker: Arc, + pub keys_handler: Arc, pub authentication_service: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, @@ -60,6 +62,7 @@ impl Environment { Self { config, tracker: app_container.tracker.clone(), + keys_handler: app_container.keys_handler.clone(), authentication_service: app_container.authentication_service.clone(), stats_event_sender: app_container.stats_event_sender.clone(), stats_repository: app_container.stats_repository.clone(), @@ -76,6 +79,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + keys_handler: self.keys_handler.clone(), authentication_service: self.authentication_service.clone(), stats_event_sender: self.stats_event_sender.clone(), stats_repository: self.stats_repository.clone(), @@ -86,6 +90,7 @@ impl Environment { .server .start( self.tracker, + self.keys_handler, self.whitelist_manager, self.stats_event_sender, self.stats_repository, @@ -108,6 +113,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + keys_handler: self.keys_handler, authentication_service: self.authentication_service, stats_event_sender: self.stats_event_sender, stats_repository: self.stats_repository, diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 6a270f894..73860c9c2 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -158,8 +158,7 @@ async fn should_allow_deleting_an_auth_key() { let seconds_valid = 60; let auth_key = env - .tracker - .authentication + .keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -293,8 +292,7 @@ async fn should_fail_when_the_auth_key_cannot_be_deleted() { let seconds_valid = 60; let auth_key = env - .tracker - .authentication + .keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -327,8 +325,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { // Generate new auth key let auth_key = env - .tracker - .authentication + .keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -348,8 +345,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { // Generate new auth key let auth_key = env - .tracker - .authentication + .keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -377,8 +373,7 @@ async fn should_allow_reloading_keys() { let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - env.tracker - .authentication + env.keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -403,8 +398,7 @@ async fn should_fail_when_keys_cannot_be_reloaded() { let request_id = Uuid::new_v4(); let seconds_valid = 60; - env.tracker - .authentication + env.keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -432,8 +426,7 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - env.tracker - .authentication + env.keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 85921cd37..81b6a12e2 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -5,6 +5,7 @@ use futures::executor::block_on; use torrust_tracker_configuration::{Configuration, HttpTracker}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; +use torrust_tracker_lib::core::authentication::handler::KeysHandler; use torrust_tracker_lib::core::authentication::service::AuthenticationService; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; @@ -17,6 +18,7 @@ use torrust_tracker_primitives::peer; pub struct Environment { pub config: Arc, pub tracker: Arc, + pub keys_handler: Arc, pub authentication_service: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, @@ -56,6 +58,7 @@ impl Environment { Self { config, tracker: app_container.tracker.clone(), + keys_handler: app_container.keys_handler.clone(), authentication_service: app_container.authentication_service.clone(), stats_event_sender: app_container.stats_event_sender.clone(), stats_repository: app_container.stats_repository.clone(), @@ -71,6 +74,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker.clone(), + keys_handler: self.keys_handler.clone(), authentication_service: self.authentication_service.clone(), whitelist_authorization: self.whitelist_authorization.clone(), stats_event_sender: self.stats_event_sender.clone(), @@ -101,6 +105,7 @@ impl Environment { Environment { config: self.config, tracker: self.tracker, + keys_handler: self.keys_handler, authentication_service: self.authentication_service, whitelist_authorization: self.whitelist_authorization, stats_event_sender: self.stats_event_sender, diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index d8b1c92c2..0aafbd213 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -1397,8 +1397,7 @@ mod configured_as_private { let env = Started::new(&configuration::ephemeral_private().into()).await; let expiring_key = env - .tracker - .authentication + .keys_handler .generate_auth_key(Some(Duration::from_secs(60))) .await .unwrap(); @@ -1547,8 +1546,7 @@ mod configured_as_private { ); let expiring_key = env - .tracker - .authentication + .keys_handler .generate_auth_key(Some(Duration::from_secs(60))) .await .unwrap(); From 718e960f50ee4a332513e80d968eaee532e16cb0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 22 Jan 2025 15:54:49 +0000 Subject: [PATCH 0634/1297] chore(deps): udpate dependencies ```output cargo update Updating crates.io index Locking 21 packages to latest compatible versions Removing ahash v0.8.11 Updating borsh v1.5.4 -> v1.5.5 Updating borsh-derive v1.5.4 -> v1.5.5 Updating brotli-decompressor v4.0.1 -> v4.0.2 Updating cc v1.2.9 -> v1.2.10 Updating clap v4.5.26 -> v4.5.27 Updating clap_builder v4.5.26 -> v4.5.27 Updating crunchy v0.2.2 -> v0.2.3 Updating derive_utils v0.14.2 -> v0.15.0 Updating hashlink v0.9.1 -> v0.10.0 Updating indexmap v2.7.0 -> v2.7.1 Updating io-enum v1.1.3 -> v1.2.0 Updating ipnet v2.10.1 -> v2.11.0 Updating is-terminal v0.4.13 -> v0.4.15 Updating libsqlite3-sys v0.30.1 -> v0.31.0 Updating r2d2_sqlite v0.25.0 -> v0.26.0 Updating rusqlite v0.32.1 -> v0.33.0 Updating rustix v0.38.43 -> v0.38.44 Updating semver v1.0.24 -> v1.0.25 Updating serde_json v1.0.135 -> v1.0.137 Updating uuid v1.12.0 -> v1.12.1 Updating valuable v0.1.0 -> v0.1.1 ``` --- Cargo.lock | 115 +++++++++++++++++++++++------------------------------ 1 file changed, 50 insertions(+), 65 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7ab861d2b..355457721 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -28,18 +28,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "ahash" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" -dependencies = [ - "cfg-if", - "once_cell", - "version_check", - "zerocopy", -] - [[package]] name = "aho-corasick" version = "1.1.3" @@ -658,9 +646,9 @@ dependencies = [ [[package]] name = "borsh" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb65153674e51d3a42c8f27b05b9508cea85edfaade8aa46bc8fc18cecdfef3" +checksum = "5430e3be710b68d984d1391c854eb431a9d548640711faa54eecb1df93db91cc" dependencies = [ "borsh-derive", "cfg_aliases", @@ -668,9 +656,9 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a396e17ad94059c650db3d253bb6e25927f1eb462eede7e7a153bb6e75dce0a7" +checksum = "f8b668d39970baad5356d7c83a86fee3a539e6f93bf6764c97368243e17a0487" dependencies = [ "once_cell", "proc-macro-crate", @@ -692,9 +680,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "4.0.1" +version = "4.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a45bd2e4095a8b518033b128020dd4a55aab1c0a381ba4404a472630f4bc362" +checksum = "74fa05ad7d803d413eb8380983b092cbbaf9a85f151b871360e7b00cd7060b37" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -787,9 +775,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.9" +version = "1.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8293772165d9345bdaaa39b45b2109591e63fe5e6fbc23c6ff930a048aa310b" +checksum = "13208fcbb66eaeffe09b99fffbe1af420f00a7b35aa99ad683dfc1aa76145229" dependencies = [ "jobserver", "libc", @@ -880,9 +868,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.26" +version = "4.5.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8eb5e908ef3a6efbe1ed62520fb7287959888c88485abe072543190ecc66783" +checksum = "769b0145982b4b48713e01ec42d61614425f27b7058bda7180a3a41f30104796" dependencies = [ "clap_builder", "clap_derive", @@ -890,9 +878,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.26" +version = "4.5.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96b01801b5fc6a0a232407abc821660c9c6d25a1cafc0d4f85f29fb8d9afc121" +checksum = "1b26884eb4b57140e4d2d93652abfa49498b938b3c9179f9fc487b0acc3edad7" dependencies = [ "anstream", "anstyle", @@ -1095,9 +1083,9 @@ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "crunchy" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" +checksum = "43da5946c66ffcc7745f48db692ffbb10a83bfe0afd96235c5c2a4fb23994929" [[package]] name = "crypto-common" @@ -1191,9 +1179,9 @@ dependencies = [ [[package]] name = "derive_utils" -version = "0.14.2" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65f152f4b8559c4da5d574bafc7af85454d706b4c5fe8b530d508cacbb6807ea" +checksum = "ccfae181bab5ab6c5478b2ccb69e4c68a02f8c3ec72f6616bfec9dbc599d2ee0" dependencies = [ "proc-macro2", "quote", @@ -1619,7 +1607,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.7.0", + "indexmap 2.7.1", "slab", "tokio", "tokio-util", @@ -1642,7 +1630,7 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" dependencies = [ - "ahash 0.7.8", + "ahash", ] [[package]] @@ -1650,9 +1638,6 @@ name = "hashbrown" version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" -dependencies = [ - "ahash 0.8.11", -] [[package]] name = "hashbrown" @@ -1667,11 +1652,11 @@ dependencies = [ [[package]] name = "hashlink" -version = "0.9.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" dependencies = [ - "hashbrown 0.14.5", + "hashbrown 0.15.2", ] [[package]] @@ -1998,9 +1983,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.7.0" +version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f822373a4fe84d4bb149bf54e584a7f4abec90e072ed49cda0edea5b95471f" +checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652" dependencies = [ "equivalent", "hashbrown 0.15.2", @@ -2024,28 +2009,28 @@ dependencies = [ [[package]] name = "io-enum" -version = "1.1.3" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53b53d712d99a73eec59ee5e4fe6057f8052142d38eeafbbffcb06b36d738a6e" +checksum = "d197db2f7ebf90507296df3aebaf65d69f5dce8559d8dbd82776a6cadab61bbf" dependencies = [ "derive_utils", ] [[package]] name = "ipnet" -version = "2.10.1" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddc24109865250148c2e0f3d25d4f0f479571723792d3802153c60922a4fb708" +checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" [[package]] name = "is-terminal" -version = "0.4.13" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "261f68e344040fbd0edea105bef17c66edf46f984ddb1115b775ce31be948f4b" +checksum = "e19b23d53f35ce9f56aebc7d1bb4e6ac1e9c0db7ac85c8d1760c04379edced37" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -2136,9 +2121,9 @@ checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa" [[package]] name = "libsqlite3-sys" -version = "0.30.1" +version = "0.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +checksum = "ad8935b44e7c13394a179a438e0cebba0fe08fe01b54f152e29a93b5cf993fd4" dependencies = [ "cc", "pkg-config", @@ -2912,9 +2897,9 @@ dependencies = [ [[package]] name = "r2d2_sqlite" -version = "0.25.0" +version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb14dba8247a6a15b7fdbc7d389e2e6f03ee9f184f87117706d509c092dfe846" +checksum = "ee025287c0188d75ae2563bcb91c9b0d1843cfc56e4bd3ab867597971b5cc256" dependencies = [ "r2d2", "rusqlite", @@ -3160,9 +3145,9 @@ dependencies = [ [[package]] name = "rusqlite" -version = "0.32.1" +version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +checksum = "1c6d5e5acb6f6129fe3f7ba0a7fc77bca1942cb568535e18e7bc40262baf3110" dependencies = [ "bitflags", "fallible-iterator", @@ -3211,9 +3196,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.43" +version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a78891ee6bf2340288408954ac787aa063d8e8817e9f53abb37c695c6d834ef6" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ "bitflags", "errno", @@ -3343,9 +3328,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.24" +version = "1.0.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cb6eb87a131f756572d7fb904f6e7b68633f09cca868c5df1c4b8d1a694bbba" +checksum = "f79dfe2d285b0488816f30e700a7438c5a73d816b5b7d3ac72fbc48b0d185e03" [[package]] name = "serde" @@ -3393,7 +3378,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d2de91cf02bbc07cde38891769ccd5d4f073d22a40683aa4bc7a95781aaa2c4" dependencies = [ "form_urlencoded", - "indexmap 2.7.0", + "indexmap 2.7.1", "itoa", "ryu", "serde", @@ -3401,11 +3386,11 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.135" +version = "1.0.137" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b0d7ba2887406110130a978386c4e1befb98c674b4fba677954e4db976630d9" +checksum = "930cfb6e6abf99298aaad7d29abbef7a9999a9a8806a40088f55f0dcec03146b" dependencies = [ - "indexmap 2.7.0", + "indexmap 2.7.1", "itoa", "memchr", "ryu", @@ -3464,7 +3449,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.7.0", + "indexmap 2.7.1", "serde", "serde_derive", "serde_json", @@ -3926,7 +3911,7 @@ version = "0.22.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ae48d6208a266e853d946088ed816055e556cc6028c5e8e2b84d9fa5dd7c7f5" dependencies = [ - "indexmap 2.7.0", + "indexmap 2.7.1", "serde", "serde_spanned", "toml_datetime", @@ -4338,9 +4323,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.12.0" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "744018581f9a3454a9e15beb8a33b017183f1e7c0cd170232a2d1453b23a51c4" +checksum = "b3758f5e68192bb96cc8f9b7e2c2cfdabb435499a28499a42f8f984092adad4b" dependencies = [ "getrandom", "rand", @@ -4348,9 +4333,9 @@ dependencies = [ [[package]] name = "valuable" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" [[package]] name = "value-bag" From df6ed93e4eb1589dee88bd5248d2644382ec5696 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 22 Jan 2025 17:10:43 +0000 Subject: [PATCH 0635/1297] refactor: [#1198] remove duplicate code in app init in tests --- src/bootstrap/jobs/http_tracker.rs | 36 +++------------- src/bootstrap/jobs/tracker_apis.rs | 46 ++++---------------- src/core/authentication/handler.rs | 1 - src/core/authentication/mod.rs | 2 - src/servers/apis/server.rs | 46 ++++---------------- src/servers/http/server.rs | 37 +++------------- src/servers/udp/server/mod.rs | 69 +++++------------------------- 7 files changed, 39 insertions(+), 198 deletions(-) diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 4df669675..92a255c9e 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -108,15 +108,8 @@ mod tests { use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_global_services; + use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::http_tracker::start_job; - use crate::core::authentication::handler::KeysHandler; - use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; - use crate::core::authentication::service; - use crate::core::services::{initialize_database, initialize_tracker, statistics}; - use crate::core::whitelist; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::http::Version; use crate::servers::registar::Registar; @@ -126,35 +119,18 @@ mod tests { let http_tracker = cfg.http_trackers.clone().expect("missing HTTP tracker configuration"); let config = &http_tracker[0]; - let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - initialize_global_services(&cfg); - let database = initialize_database(&cfg); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( - &cfg.core, - &in_memory_whitelist.clone(), - )); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); - let _keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); + let app_container = initialize_app_container(&cfg); let version = Version::V1; start_job( config, - tracker, - authentication_service, - whitelist_authorization, - stats_event_sender, + app_container.tracker, + app_container.authentication_service, + app_container.whitelist_authorization, + app_container.stats_event_sender, Registar::default().give_form(), version, ) diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 9bb7e6d45..1047fa418 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -159,62 +159,32 @@ async fn start_v1( mod tests { use std::sync::Arc; - use tokio::sync::RwLock; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_global_services; + use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::tracker_apis::start_job; - use crate::core::authentication::handler::KeysHandler; - use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; - use crate::core::authentication::service; - use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; - use crate::core::whitelist; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::apis::Version; use crate::servers::registar::Registar; - use crate::servers::udp::server::banning::BanService; - use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; #[tokio::test] async fn it_should_start_http_tracker() { let cfg = Arc::new(ephemeral_public()); let config = &cfg.http_api.clone().unwrap(); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let (stats_event_sender, stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - let stats_repository = Arc::new(stats_repository); - initialize_global_services(&cfg); - let database = initialize_database(&cfg); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( - &cfg.core, - &in_memory_whitelist.clone(), - )); - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let _authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); - let keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); + let app_container = initialize_app_container(&cfg); let version = Version::V1; start_job( config, - tracker, - keys_handler, - whitelist_manager, - ban_service, - stats_event_sender, - stats_repository, + app_container.tracker, + app_container.keys_handler, + app_container.whitelist_manager, + app_container.ban_service, + app_container.stats_event_sender, + app_container.stats_repository, Registar::default().give_form(), version, ) diff --git a/src/core/authentication/handler.rs b/src/core/authentication/handler.rs index 17033aefc..5ec9a11b4 100644 --- a/src/core/authentication/handler.rs +++ b/src/core/authentication/handler.rs @@ -267,7 +267,6 @@ mod tests { fn instantiate_keys_handler_with_configuration(config: &Configuration) -> KeysHandler { let database = initialize_database(config); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 799263752..0180b3a1e 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -50,10 +50,8 @@ mod tests { config: &Configuration, ) -> (Arc, Arc) { let database = initialize_database(config); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::AuthenticationService::new(&config.core, &in_memory_key_repository)); let keys_handler = Arc::new(KeysHandler::new( &db_key_repository.clone(), diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index f219ca023..e65d6643d 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -343,51 +343,21 @@ impl Launcher { mod tests { use std::sync::Arc; - use tokio::sync::RwLock; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_global_services; + use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::make_rust_tls; - use crate::core::authentication::handler::KeysHandler; - use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; - use crate::core::authentication::service; - use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; - use crate::core::whitelist; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::registar::Registar; - use crate::servers::udp::server::banning::BanService; - use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_public()); let config = &cfg.http_api.clone().unwrap(); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let (stats_event_sender, stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - let stats_repository = Arc::new(stats_repository); - initialize_global_services(&cfg); - let database = initialize_database(&cfg); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( - &cfg.core, - &in_memory_whitelist.clone(), - )); - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let _authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); - let keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); + let app_container = initialize_app_container(&cfg); let bind_to = config.bind_address; @@ -403,12 +373,12 @@ mod tests { let started = stopped .start( - tracker, - keys_handler, - whitelist_manager, - stats_event_sender, - stats_repository, - ban_service, + app_container.tracker, + app_container.keys_handler, + app_container.whitelist_manager, + app_container.stats_event_sender, + app_container.stats_repository, + app_container.ban_service, register.give_form(), access_tokens, ) diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 5f62a2013..e7a3a92ec 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -268,15 +268,8 @@ mod tests { use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_global_services; + use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::make_rust_tls; - use crate::core::authentication::handler::KeysHandler; - use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; - use crate::core::authentication::service; - use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; - use crate::core::whitelist; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::registar::Registar; @@ -284,27 +277,9 @@ mod tests { async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_public()); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - initialize_global_services(&cfg); - let database = initialize_database(&cfg); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( - &cfg.core, - &in_memory_whitelist.clone(), - )); - let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); - let _keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); + let app_container = initialize_app_container(&cfg); let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); let config = &http_trackers[0]; @@ -320,10 +295,10 @@ mod tests { let stopped = HttpServer::new(Launcher::new(bind_to, tls)); let started = stopped .start( - tracker, - authentication_service, - whitelist_authorization, - stats_event_sender, + app_container.tracker, + app_container.authentication_service, + app_container.whitelist_authorization, + app_container.stats_event_sender, register.give_form(), ) .await diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 844c18678..af51b7fb7 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -58,49 +58,20 @@ mod tests { use std::sync::Arc; use std::time::Duration; - use tokio::sync::RwLock; use torrust_tracker_test_helpers::configuration::ephemeral_public; use super::spawner::Spawner; use super::Server; - use crate::bootstrap::app::initialize_global_services; - use crate::core::authentication::handler::KeysHandler; - use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; - use crate::core::authentication::service; - use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; - use crate::core::whitelist; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::servers::registar::Registar; - use crate::servers::udp::server::banning::BanService; - use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_public()); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - initialize_global_services(&cfg); - let database = initialize_database(&cfg); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( - &cfg.core, - &in_memory_whitelist.clone(), - )); - let _whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let _authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); - let _keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); + let app_container = initialize_app_container(&cfg); let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; @@ -111,10 +82,10 @@ mod tests { let started = stopped .start( - tracker, - whitelist_authorization, - stats_event_sender, - ban_service, + app_container.tracker, + app_container.whitelist_authorization, + app_container.stats_event_sender, + app_container.ban_service, register.give_form(), config.cookie_lifetime, ) @@ -132,27 +103,9 @@ mod tests { async fn it_should_be_able_to_start_and_stop_with_wait() { let cfg = Arc::new(ephemeral_public()); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(cfg.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - initialize_global_services(&cfg); - let database = initialize_database(&cfg); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( - &cfg.core, - &in_memory_whitelist.clone(), - )); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let _authentication_service = Arc::new(service::AuthenticationService::new(&cfg.core, &in_memory_key_repository)); - let _keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - - let tracker = Arc::new(initialize_tracker(&cfg, &database, &whitelist_authorization)); + let app_container = initialize_app_container(&cfg); let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; @@ -162,10 +115,10 @@ mod tests { let started = stopped .start( - tracker, - whitelist_authorization, - stats_event_sender, - ban_service, + app_container.tracker, + app_container.whitelist_authorization, + app_container.stats_event_sender, + app_container.ban_service, register.give_form(), config.cookie_lifetime, ) From 03ef7f6178ae9c25f4fca925741c9d48bf809886 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 23 Jan 2025 16:23:28 +0000 Subject: [PATCH 0636/1297] refactor: [1201] extract InMemoryTorrentRepository --- src/core/mod.rs | 33 +++----- src/core/services/torrent.rs | 1 - src/core/torrent/mod.rs | 2 + src/core/torrent/repository/in_memory.rs | 103 +++++++++++++++++++++++ src/core/torrent/repository/mod.rs | 1 + 5 files changed, 116 insertions(+), 24 deletions(-) create mode 100644 src/core/torrent/repository/in_memory.rs create mode 100644 src/core/torrent/repository/mod.rs diff --git a/src/core/mod.rs b/src/core/mod.rs index 26ef69bfa..fd25a0506 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -449,22 +449,19 @@ pub mod whitelist; pub mod peer_tests; -use std::cmp::max; use std::net::IpAddr; use std::sync::Arc; use std::time::Duration; use bittorrent_primitives::info_hash::InfoHash; +use torrent::repository::in_memory::InMemoryTorrentRepository; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_torrent_repository::entry::EntrySync; -use torrust_tracker_torrent_repository::repository::Repository; -use self::torrent::Torrents; use crate::core::databases::Database; use crate::CurrentClock; @@ -489,7 +486,7 @@ pub struct Tracker { pub whitelist_authorization: Arc, /// The in-memory torrents repository. - torrents: Arc, + torrents: Arc, } /// How many peers the peer announcing wants in the announce response. @@ -549,7 +546,7 @@ impl Tracker { config: config.clone(), database: database.clone(), whitelist_authorization: whitelist_authorization.clone(), - torrents: Arc::default(), + torrents: Arc::new(InMemoryTorrentRepository::default()), }) } @@ -656,10 +653,7 @@ impl Tracker { /// It returns the data for a `scrape` response. fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { - match self.torrents.get(info_hash) { - Some(torrent_entry) => torrent_entry.get_swarm_metadata(), - None => SwarmMetadata::default(), - } + self.torrents.get_swarm_metadata(info_hash) } /// It loads the torrents from database into memory. It only loads the torrent entry list with the number of seeders for each torrent. @@ -684,10 +678,7 @@ impl Tracker { /// /// It filters out the client making the request. fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { - match self.torrents.get(info_hash) { - None => vec![], - Some(entry) => entry.get_peers_for_client(&peer.peer_addr, Some(max(limit, TORRENT_PEERS_LIMIT))), - } + self.torrents.get_peers_for(info_hash, peer, limit) } /// # Context: Tracker @@ -695,10 +686,7 @@ impl Tracker { /// Get torrent peers for a given torrent. #[must_use] pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { - match self.torrents.get(info_hash) { - None => vec![], - Some(entry) => entry.get_peers(Some(TORRENT_PEERS_LIMIT)), - } + self.torrents.get_torrent_peers(info_hash) } /// It updates the torrent entry in memory, it also stores in the database @@ -708,14 +696,14 @@ impl Tracker { /// # Context: Tracker #[must_use] pub fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { - let swarm_metadata_before = match self.torrents.get_swarm_metadata(info_hash) { + let swarm_metadata_before = match self.torrents.get_opt_swarm_metadata(info_hash) { Some(swarm_metadata) => swarm_metadata, None => SwarmMetadata::zeroed(), }; self.torrents.upsert_peer(info_hash, peer); - let swarm_metadata_after = match self.torrents.get_swarm_metadata(info_hash) { + let swarm_metadata_after = match self.torrents.get_opt_swarm_metadata(info_hash) { Some(swarm_metadata) => swarm_metadata, None => SwarmMetadata::zeroed(), }; @@ -748,7 +736,7 @@ impl Tracker { /// Panics if unable to get the torrent metrics. #[must_use] pub fn get_torrents_metrics(&self) -> TorrentsMetrics { - self.torrents.get_metrics() + self.torrents.get_torrents_metrics() } /// Remove inactive peers and (optionally) peerless torrents. @@ -1492,7 +1480,6 @@ mod tests { use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_torrent_repository::entry::EntrySync; - use torrust_tracker_torrent_repository::repository::Repository; use crate::core::tests::the_tracker::{sample_info_hash, sample_peer, tracker_persisting_torrents_in_database}; @@ -1513,7 +1500,7 @@ mod tests { assert_eq!(swarm_stats.downloaded, 1); // Remove the newly updated torrent from memory - tracker.torrents.remove(&info_hash); + let _unused = tracker.torrents.remove(&info_hash); tracker.load_torrents_from_database().unwrap(); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 9b7254098..7f99451eb 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -10,7 +10,6 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::peer; use torrust_tracker_torrent_repository::entry::EntrySync; -use torrust_tracker_torrent_repository::repository::Repository; use crate::core::Tracker; diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index 38311864b..3e3e065f2 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -25,6 +25,8 @@ //! - The number of peers that have NOT completed downloading the torrent and are still active, that means they are actively participating in the network. //! Peer that don not have a full copy of the torrent data are called "leechers". //! +pub mod repository; + use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; pub type Torrents = TorrentsSkipMapMutexStd; // Currently Used diff --git a/src/core/torrent/repository/in_memory.rs b/src/core/torrent/repository/in_memory.rs new file mode 100644 index 000000000..6b1902d95 --- /dev/null +++ b/src/core/torrent/repository/in_memory.rs @@ -0,0 +1,103 @@ +use std::cmp::max; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_torrent_repository::entry::EntrySync; +use torrust_tracker_torrent_repository::repository::Repository; +use torrust_tracker_torrent_repository::EntryMutexStd; + +use crate::core::torrent::Torrents; + +/// The in-memory torrents repository. +/// +/// There are many implementations of the repository trait. We tried with +/// different types of data structures, but the best performance was with +/// the one we use for production. We kept the other implementations for +/// reference. +#[derive(Debug, Default)] +pub struct InMemoryTorrentRepository { + /// The in-memory torrents repository implementation. + torrents: Arc, +} + +impl InMemoryTorrentRepository { + /// It inserts (or updates if it's already in the list) the peer in the + /// torrent entry. + pub fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + self.torrents.upsert_peer(info_hash, peer); + } + + #[must_use] + pub fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key) + } + + pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + self.torrents.remove_inactive_peers(current_cutoff); + } + + pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + self.torrents.remove_peerless_torrents(policy); + } + + #[must_use] + pub fn get(&self, key: &InfoHash) -> Option { + self.torrents.get(key) + } + + #[must_use] + pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + self.torrents.get_paginated(pagination) + } + + /// It returns the data for a `scrape` response or empty if the torrent is + /// not found. + #[must_use] + pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { + match self.torrents.get(info_hash) { + Some(torrent_entry) => torrent_entry.get_swarm_metadata(), + None => SwarmMetadata::default(), + } + } + + /// It returns the data for a `scrape` response if the torrent is found. + #[must_use] + pub fn get_opt_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get_swarm_metadata(info_hash) + } + + /// Get torrent peers for a given torrent and client. + /// + /// It filters out the client making the request. + #[must_use] + pub fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { + match self.torrents.get(info_hash) { + None => vec![], + Some(entry) => entry.get_peers_for_client(&peer.peer_addr, Some(max(limit, TORRENT_PEERS_LIMIT))), + } + } + + /// Get torrent peers for a given torrent. + #[must_use] + pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { + match self.torrents.get(info_hash) { + None => vec![], + Some(entry) => entry.get_peers(Some(TORRENT_PEERS_LIMIT)), + } + } + + /// It calculates and returns the general [`TorrentsMetrics`]. + #[must_use] + pub fn get_torrents_metrics(&self) -> TorrentsMetrics { + self.torrents.get_metrics() + } + + pub fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + self.torrents.import_persistent(persistent_torrents); + } +} diff --git a/src/core/torrent/repository/mod.rs b/src/core/torrent/repository/mod.rs new file mode 100644 index 000000000..fa2e12699 --- /dev/null +++ b/src/core/torrent/repository/mod.rs @@ -0,0 +1 @@ +pub mod in_memory; From 9b5f776c28483e17d5dfa39f4026faacf7aa6546 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 23 Jan 2025 16:50:56 +0000 Subject: [PATCH 0637/1297] refactor: [#1201] exatrct DatabasePersistentTorrentRepository --- src/core/mod.rs | 11 ++++-- src/core/torrent/repository/mod.rs | 1 + src/core/torrent/repository/persisted.rs | 44 ++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 src/core/torrent/repository/persisted.rs diff --git a/src/core/mod.rs b/src/core/mod.rs index fd25a0506..4cb4a04ef 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -455,6 +455,7 @@ use std::time::Duration; use bittorrent_primitives::info_hash::InfoHash; use torrent::repository::in_memory::InMemoryTorrentRepository; +use torrent::repository::persisted::DatabasePersistentTorrentRepository; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; @@ -487,6 +488,9 @@ pub struct Tracker { /// The in-memory torrents repository. torrents: Arc, + + /// The persistent torrents repository. + db_torrent_repository: Arc, } /// How many peers the peer announcing wants in the announce response. @@ -547,6 +551,7 @@ impl Tracker { database: database.clone(), whitelist_authorization: whitelist_authorization.clone(), torrents: Arc::new(InMemoryTorrentRepository::default()), + db_torrent_repository: Arc::new(DatabasePersistentTorrentRepository::new(database)), }) } @@ -665,7 +670,7 @@ impl Tracker { /// /// Will return a `database::Error` if unable to load the list of `persistent_torrents` from the database. pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { - let persistent_torrents = self.database.load_persistent_torrents()?; + let persistent_torrents = self.db_torrent_repository.load_all()?; self.torrents.import_persistent(&persistent_torrents); @@ -723,7 +728,7 @@ impl Tracker { let completed = swarm_metadata.downloaded; let info_hash = *info_hash; - drop(self.database.save_persistent_torrent(&info_hash, completed)); + drop(self.db_torrent_repository.save(&info_hash, completed)); } } @@ -759,7 +764,7 @@ impl Tracker { /// /// Will return `Err` if unable to drop tables. pub fn drop_database_tables(&self) -> Result<(), databases::error::Error> { - // todo: this is only used for testing. WE have to pass the database + // todo: this is only used for testing. We have to pass the database // reference directly to the tests instead of via the tracker. self.database.drop_database_tables() } diff --git a/src/core/torrent/repository/mod.rs b/src/core/torrent/repository/mod.rs index fa2e12699..51723b68d 100644 --- a/src/core/torrent/repository/mod.rs +++ b/src/core/torrent/repository/mod.rs @@ -1 +1,2 @@ pub mod in_memory; +pub mod persisted; diff --git a/src/core/torrent/repository/persisted.rs b/src/core/torrent/repository/persisted.rs new file mode 100644 index 000000000..86a3db0e3 --- /dev/null +++ b/src/core/torrent/repository/persisted.rs @@ -0,0 +1,44 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::PersistentTorrents; + +use crate::core::databases::error::Error; +use crate::core::databases::Database; + +/// Torrent repository implementation that persists the torrents in a database. +/// +/// Not all the torrent in-memory data is persisted. For now only some of the +/// torrent metrics are persisted. +pub struct DatabasePersistentTorrentRepository { + /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) + /// or [`MySQL`](crate::core::databases::mysql) + database: Arc>, +} + +impl DatabasePersistentTorrentRepository { + #[must_use] + pub fn new(database: &Arc>) -> DatabasePersistentTorrentRepository { + Self { + database: database.clone(), + } + } + + /// It loads the persistent torrents from the database. + /// + /// # Errors + /// + /// Will return a database `Err` if unable to load. + pub fn load_all(&self) -> Result { + self.database.load_persistent_torrents() + } + + /// It saves the persistent torrent into the database. + /// + /// # Errors + /// + /// Will return a database `Err` if unable to save. + pub fn save(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error> { + self.database.save_persistent_torrent(info_hash, downloaded) + } +} From f4dcb51f1f5eaa6e2a34c441d2b4d816807f56bd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 23 Jan 2025 16:52:55 +0000 Subject: [PATCH 0638/1297] refactor: [#1201] rename tracker field --- src/core/mod.rs | 32 ++++++++++++++++++-------------- src/core/services/torrent.rs | 10 +++++++--- 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 4cb4a04ef..c9a7e9dc3 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -487,7 +487,7 @@ pub struct Tracker { pub whitelist_authorization: Arc, /// The in-memory torrents repository. - torrents: Arc, + in_memory_torrent_repository: Arc, /// The persistent torrents repository. db_torrent_repository: Arc, @@ -550,7 +550,7 @@ impl Tracker { config: config.clone(), database: database.clone(), whitelist_authorization: whitelist_authorization.clone(), - torrents: Arc::new(InMemoryTorrentRepository::default()), + in_memory_torrent_repository: Arc::new(InMemoryTorrentRepository::default()), db_torrent_repository: Arc::new(DatabasePersistentTorrentRepository::new(database)), }) } @@ -658,7 +658,7 @@ impl Tracker { /// It returns the data for a `scrape` response. fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { - self.torrents.get_swarm_metadata(info_hash) + self.in_memory_torrent_repository.get_swarm_metadata(info_hash) } /// It loads the torrents from database into memory. It only loads the torrent entry list with the number of seeders for each torrent. @@ -672,7 +672,7 @@ impl Tracker { pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { let persistent_torrents = self.db_torrent_repository.load_all()?; - self.torrents.import_persistent(&persistent_torrents); + self.in_memory_torrent_repository.import_persistent(&persistent_torrents); Ok(()) } @@ -683,7 +683,7 @@ impl Tracker { /// /// It filters out the client making the request. fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { - self.torrents.get_peers_for(info_hash, peer, limit) + self.in_memory_torrent_repository.get_peers_for(info_hash, peer, limit) } /// # Context: Tracker @@ -691,7 +691,7 @@ impl Tracker { /// Get torrent peers for a given torrent. #[must_use] pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { - self.torrents.get_torrent_peers(info_hash) + self.in_memory_torrent_repository.get_torrent_peers(info_hash) } /// It updates the torrent entry in memory, it also stores in the database @@ -701,14 +701,14 @@ impl Tracker { /// # Context: Tracker #[must_use] pub fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { - let swarm_metadata_before = match self.torrents.get_opt_swarm_metadata(info_hash) { + let swarm_metadata_before = match self.in_memory_torrent_repository.get_opt_swarm_metadata(info_hash) { Some(swarm_metadata) => swarm_metadata, None => SwarmMetadata::zeroed(), }; - self.torrents.upsert_peer(info_hash, peer); + self.in_memory_torrent_repository.upsert_peer(info_hash, peer); - let swarm_metadata_after = match self.torrents.get_opt_swarm_metadata(info_hash) { + let swarm_metadata_after = match self.in_memory_torrent_repository.get_opt_swarm_metadata(info_hash) { Some(swarm_metadata) => swarm_metadata, None => SwarmMetadata::zeroed(), }; @@ -741,7 +741,7 @@ impl Tracker { /// Panics if unable to get the torrent metrics. #[must_use] pub fn get_torrents_metrics(&self) -> TorrentsMetrics { - self.torrents.get_torrents_metrics() + self.in_memory_torrent_repository.get_torrents_metrics() } /// Remove inactive peers and (optionally) peerless torrents. @@ -751,10 +751,11 @@ impl Tracker { let current_cutoff = CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout))) .unwrap_or_default(); - self.torrents.remove_inactive_peers(current_cutoff); + self.in_memory_torrent_repository.remove_inactive_peers(current_cutoff); if self.config.tracker_policy.remove_peerless_torrents { - self.torrents.remove_peerless_torrents(&self.config.tracker_policy); + self.in_memory_torrent_repository + .remove_peerless_torrents(&self.config.tracker_policy); } } @@ -1505,11 +1506,14 @@ mod tests { assert_eq!(swarm_stats.downloaded, 1); // Remove the newly updated torrent from memory - let _unused = tracker.torrents.remove(&info_hash); + let _unused = tracker.in_memory_torrent_repository.remove(&info_hash); tracker.load_torrents_from_database().unwrap(); - let torrent_entry = tracker.torrents.get(&info_hash).expect("it should be able to get entry"); + let torrent_entry = tracker + .in_memory_torrent_repository + .get(&info_hash) + .expect("it should be able to get entry"); // It persists the number of completed peers. assert_eq!(torrent_entry.get_swarm_metadata().downloaded, 1); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 7f99451eb..032b526dd 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -45,7 +45,7 @@ pub struct BasicInfo { /// It returns all the information the tracker has about one torrent in a [Info] struct. pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Option { - let torrent_entry_option = tracker.torrents.get(info_hash); + let torrent_entry_option = tracker.in_memory_torrent_repository.get(info_hash); let torrent_entry = torrent_entry_option?; @@ -68,7 +68,7 @@ pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Op pub async fn get_torrents_page(tracker: Arc, pagination: Option<&Pagination>) -> Vec { let mut basic_infos: Vec = vec![]; - for (info_hash, torrent_entry) in tracker.torrents.get_paginated(pagination) { + for (info_hash, torrent_entry) in tracker.in_memory_torrent_repository.get_paginated(pagination) { let stats = torrent_entry.get_swarm_metadata(); basic_infos.push(BasicInfo { @@ -87,7 +87,11 @@ pub async fn get_torrents(tracker: Arc, info_hashes: &[InfoHash]) -> Ve let mut basic_infos: Vec = vec![]; for info_hash in info_hashes { - if let Some(stats) = tracker.torrents.get(info_hash).map(|t| t.get_swarm_metadata()) { + if let Some(stats) = tracker + .in_memory_torrent_repository + .get(info_hash) + .map(|t| t.get_swarm_metadata()) + { basic_infos.push(BasicInfo { info_hash: *info_hash, seeders: u64::from(stats.complete), From 6332261af8a6a5e5d6de235283187d3440325133 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 23 Jan 2025 17:12:26 +0000 Subject: [PATCH 0639/1297] refactor: [#1201] extract TorrentsManager --- src/core/mod.rs | 35 ++++++++++---------- src/core/torrent/manager.rs | 64 +++++++++++++++++++++++++++++++++++++ src/core/torrent/mod.rs | 1 + 3 files changed, 81 insertions(+), 19 deletions(-) create mode 100644 src/core/torrent/manager.rs diff --git a/src/core/mod.rs b/src/core/mod.rs index c9a7e9dc3..61f194f3d 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -451,12 +451,11 @@ pub mod peer_tests; use std::net::IpAddr; use std::sync::Arc; -use std::time::Duration; use bittorrent_primitives::info_hash::InfoHash; +use torrent::manager::TorrentsManager; use torrent::repository::in_memory::InMemoryTorrentRepository; use torrent::repository::persisted::DatabasePersistentTorrentRepository; -use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; use torrust_tracker_primitives::peer; @@ -464,7 +463,6 @@ use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use crate::core::databases::Database; -use crate::CurrentClock; /// The domain layer tracker service. /// @@ -491,6 +489,9 @@ pub struct Tracker { /// The persistent torrents repository. db_torrent_repository: Arc, + + /// The service to run torrents tasks. + torrents_manager: Arc, } /// How many peers the peer announcing wants in the announce response. @@ -546,12 +547,20 @@ impl Tracker { database: &Arc>, whitelist_authorization: &Arc, ) -> Result { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(database)); + Ok(Tracker { config: config.clone(), database: database.clone(), whitelist_authorization: whitelist_authorization.clone(), - in_memory_torrent_repository: Arc::new(InMemoryTorrentRepository::default()), - db_torrent_repository: Arc::new(DatabasePersistentTorrentRepository::new(database)), + in_memory_torrent_repository: in_memory_torrent_repository.clone(), + db_torrent_repository: db_torrent_repository.clone(), + torrents_manager: Arc::new(TorrentsManager::new( + config, + &in_memory_torrent_repository, + &db_torrent_repository, + )), }) } @@ -670,11 +679,7 @@ impl Tracker { /// /// Will return a `database::Error` if unable to load the list of `persistent_torrents` from the database. pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { - let persistent_torrents = self.db_torrent_repository.load_all()?; - - self.in_memory_torrent_repository.import_persistent(&persistent_torrents); - - Ok(()) + self.torrents_manager.load_torrents_from_database() } /// # Context: Tracker @@ -748,15 +753,7 @@ impl Tracker { /// /// # Context: Tracker pub fn cleanup_torrents(&self) { - let current_cutoff = CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout))) - .unwrap_or_default(); - - self.in_memory_torrent_repository.remove_inactive_peers(current_cutoff); - - if self.config.tracker_policy.remove_peerless_torrents { - self.in_memory_torrent_repository - .remove_peerless_torrents(&self.config.tracker_policy); - } + self.torrents_manager.cleanup_torrents(); } /// It drops the database tables. diff --git a/src/core/torrent/manager.rs b/src/core/torrent/manager.rs new file mode 100644 index 000000000..261376755 --- /dev/null +++ b/src/core/torrent/manager.rs @@ -0,0 +1,64 @@ +use std::sync::Arc; +use std::time::Duration; + +use torrust_tracker_clock::clock::Time; +use torrust_tracker_configuration::Core; + +use super::repository::in_memory::InMemoryTorrentRepository; +use super::repository::persisted::DatabasePersistentTorrentRepository; +use crate::core::databases; +use crate::CurrentClock; + +pub struct TorrentsManager { + /// The tracker configuration. + config: Core, + + /// The in-memory torrents repository. + in_memory_torrent_repository: Arc, + + /// The persistent torrents repository. + db_torrent_repository: Arc, +} + +impl TorrentsManager { + #[must_use] + pub fn new( + config: &Core, + in_memory_torrent_repository: &Arc, + db_torrent_repository: &Arc, + ) -> Self { + Self { + config: config.clone(), + in_memory_torrent_repository: in_memory_torrent_repository.clone(), + db_torrent_repository: db_torrent_repository.clone(), + } + } + + /// It loads the torrents from database into memory. It only loads the + /// torrent entry list with the number of seeders for each torrent. Peers + /// data is not persisted. + /// + /// # Errors + /// + /// Will return a `database::Error` if unable to load the list of `persistent_torrents` from the database. + pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { + let persistent_torrents = self.db_torrent_repository.load_all()?; + + self.in_memory_torrent_repository.import_persistent(&persistent_torrents); + + Ok(()) + } + + /// Remove inactive peers and (optionally) peerless torrents. + pub fn cleanup_torrents(&self) { + let current_cutoff = CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout))) + .unwrap_or_default(); + + self.in_memory_torrent_repository.remove_inactive_peers(current_cutoff); + + if self.config.tracker_policy.remove_peerless_torrents { + self.in_memory_torrent_repository + .remove_peerless_torrents(&self.config.tracker_policy); + } + } +} diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index 3e3e065f2..95a5ff1eb 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -25,6 +25,7 @@ //! - The number of peers that have NOT completed downloading the torrent and are still active, that means they are actively participating in the network. //! Peer that don not have a full copy of the torrent data are called "leechers". //! +pub mod manager; pub mod repository; use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; From 4e3dbae05b8e7999f08bf8035575499c300bd496 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 23 Jan 2025 17:34:13 +0000 Subject: [PATCH 0640/1297] refactor: [#1201] inject new extracted sercvies in core tracker --- src/app_test.rs | 23 +++- src/bootstrap/app.rs | 19 ++- src/core/mod.rs | 76 ++++++++--- src/core/services/mod.rs | 15 ++- src/core/services/statistics/mod.rs | 21 +++- src/core/services/torrent.rs | 154 ++++++++++++++++++----- src/servers/http/v1/handlers/announce.rs | 20 ++- src/servers/http/v1/handlers/scrape.rs | 80 ++++++++++-- src/servers/http/v1/services/announce.rs | 43 +++++-- src/servers/http/v1/services/scrape.rs | 45 +++++-- src/servers/udp/handlers.rs | 68 ++++++++-- 11 files changed, 471 insertions(+), 93 deletions(-) diff --git a/src/app_test.rs b/src/app_test.rs index 929a23418..5f189f391 100644 --- a/src/app_test.rs +++ b/src/app_test.rs @@ -9,6 +9,9 @@ use crate::core::authentication::key::repository::persisted::DatabaseKeyReposito use crate::core::authentication::service::{self, AuthenticationService}; use crate::core::databases::Database; use crate::core::services::initialize_database; +use crate::core::torrent::manager::TorrentsManager; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; +use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; @@ -22,6 +25,9 @@ pub fn initialize_tracker_dependencies( Arc, Arc, Arc, + Arc, + Arc, + Arc, ) { let database = initialize_database(config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -36,6 +42,21 @@ pub fn initialize_tracker_dependencies( &db_key_repository.clone(), &in_memory_key_repository.clone(), )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let torrents_manager = Arc::new(TorrentsManager::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); - (database, in_memory_whitelist, whitelist_authorization, authentication_service) + ( + database, + in_memory_whitelist, + whitelist_authorization, + authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) } diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index a0c7887cf..ea7d7f030 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -27,6 +27,9 @@ use crate::core::authentication::key::repository::in_memory::InMemoryKeyReposito use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::authentication::service; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; +use crate::core::torrent::manager::TorrentsManager; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; +use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use crate::core::whitelist; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::udp::server::banning::BanService; @@ -103,8 +106,22 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { &db_key_repository.clone(), &in_memory_key_repository.clone(), )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let torrents_manager = Arc::new(TorrentsManager::new( + &configuration.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); - let tracker = Arc::new(initialize_tracker(configuration, &database, &whitelist_authorization)); + let tracker = Arc::new(initialize_tracker( + configuration, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + )); AppContainer { tracker, diff --git a/src/core/mod.rs b/src/core/mod.rs index 61f194f3d..161607857 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -546,21 +546,17 @@ impl Tracker { config: &Core, database: &Arc>, whitelist_authorization: &Arc, + in_memory_torrent_repository: &Arc, + db_torrent_repository: &Arc, + torrents_manager: &Arc, ) -> Result { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(database)); - Ok(Tracker { config: config.clone(), database: database.clone(), whitelist_authorization: whitelist_authorization.clone(), in_memory_torrent_repository: in_memory_torrent_repository.clone(), db_torrent_repository: db_torrent_repository.clone(), - torrents_manager: Arc::new(TorrentsManager::new( - config, - &in_memory_torrent_repository, - &db_torrent_repository, - )), + torrents_manager: torrents_manager.clone(), }) } @@ -802,21 +798,49 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - initialize_tracker(&config, &database, &whitelist_authorization) + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ) } fn whitelisted_tracker() -> (Tracker, Arc, Arc) { let config = configuration::ephemeral_listed(); - let (database, in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); + let ( + database, + in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = initialize_tracker(&config, &database, &whitelist_authorization); + let tracker = initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ); (tracker, whitelist_authorization, whitelist_manager) } @@ -825,10 +849,24 @@ mod tests { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - initialize_tracker(&config, &database, &whitelist_authorization) + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ) } fn sample_info_hash() -> InfoHash { diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index 611ea24d2..f5d9bd375 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -14,6 +14,9 @@ use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::Configuration; use super::databases::{self, Database}; +use super::torrent::manager::TorrentsManager; +use super::torrent::repository::in_memory::InMemoryTorrentRepository; +use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; use super::whitelist; use super::whitelist::manager::WhiteListManager; use super::whitelist::repository::in_memory::InMemoryWhitelist; @@ -30,8 +33,18 @@ pub fn initialize_tracker( config: &Configuration, database: &Arc>, whitelist_authorization: &Arc, + in_memory_torrent_repository: &Arc, + db_torrent_repository: &Arc, + torrents_manager: &Arc, ) -> Tracker { - match Tracker::new(&Arc::new(config).core, database, whitelist_authorization) { + match Tracker::new( + &Arc::new(config).core, + database, + whitelist_authorization, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) { Ok(tracker) => tracker, Err(error) => { panic!("{}", error) diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index cc59bcf12..9e4696f48 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -132,12 +132,27 @@ mod tests { async fn the_statistics_service_should_return_the_tracker_metrics() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_repository = Arc::new(stats_repository); - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + )); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 032b526dd..1e3f67eba 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -145,10 +145,24 @@ mod tests { async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - let tracker = initialize_tracker(&config, &database, &whitelist_authorization); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let tracker = initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ); let tracker = Arc::new(tracker); @@ -165,10 +179,24 @@ mod tests { async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + )); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -211,10 +239,24 @@ mod tests { async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + )); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -225,10 +267,24 @@ mod tests { async fn should_return_a_summarized_info_for_all_torrents() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + )); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -252,10 +308,24 @@ mod tests { async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + )); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -277,10 +347,24 @@ mod tests { async fn should_allow_using_pagination_in_the_result() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + )); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -311,10 +395,24 @@ mod tests { async fn should_return_torrents_ordered_by_info_hash() { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - let tracker = Arc::new(initialize_tracker(&config, &database, &whitelist_authorization)); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + )); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index c42981d4c..b18671422 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -274,12 +274,26 @@ mod tests { /// Initialize tracker's dependencies and tracker. fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { - let (database, _in_memory_whitelist, whitelist_authorization, authentication_service) = - initialize_tracker_dependencies(config); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = Arc::new(initialize_tracker(config, &database, &whitelist_authorization)); + let tracker = Arc::new(initialize_tracker( + config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + )); (tracker, stats_event_sender, whitelist_authorization, authentication_service) } diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index de4610a61..e619ba120 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -151,13 +151,27 @@ mod tests { ) { let config = configuration::ephemeral_private(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication_service) = - initialize_tracker_dependencies(&config); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( - initialize_tracker(&config, &database, &whitelist_authorization), + initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ), stats_event_sender, authentication_service, ) @@ -170,13 +184,27 @@ mod tests { ) { let config = configuration::ephemeral_listed(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication_service) = - initialize_tracker_dependencies(&config); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( - initialize_tracker(&config, &database, &whitelist_authorization), + initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ), stats_event_sender, authentication_service, ) @@ -189,13 +217,27 @@ mod tests { ) { let config = configuration::ephemeral_with_reverse_proxy(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication_service) = - initialize_tracker_dependencies(&config); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( - initialize_tracker(&config, &database, &whitelist_authorization), + initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ), stats_event_sender, authentication_service, ) @@ -208,13 +250,27 @@ mod tests { ) { let config = configuration::ephemeral_without_reverse_proxy(); - let (database, _in_memory_whitelist, whitelist_authorization, authentication_service) = - initialize_tracker_dependencies(&config); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); ( - initialize_tracker(&config, &database, &whitelist_authorization), + initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ), stats_event_sender, authentication_service, ) diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 018348d7e..99724f728 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -73,12 +73,26 @@ mod tests { fn public_tracker() -> (Tracker, Arc>>) { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = initialize_tracker(&config, &database, &whitelist_authorization); + let tracker = initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ); (tracker, stats_event_sender) } @@ -132,10 +146,25 @@ mod tests { fn test_tracker_factory() -> Tracker { let config = configuration::ephemeral(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - Tracker::new(&config.core, &database, &whitelist_authorization).unwrap() + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + Tracker::new( + &config.core, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ) + .unwrap() } #[tokio::test] diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 9ad741234..c9e657d11 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -87,10 +87,24 @@ mod tests { fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - initialize_tracker(&config, &database, &whitelist_authorization) + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + initialize_tracker( + &config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ) } fn sample_info_hashes() -> Vec { @@ -116,10 +130,25 @@ mod tests { fn test_tracker_factory() -> Tracker { let config = configuration::ephemeral(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - Tracker::new(&config.core, &database, &whitelist_authorization).unwrap() + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + Tracker::new( + &config.core, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ) + .unwrap() } mod with_real_data { diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index feeca4e40..840b789a1 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -516,13 +516,27 @@ mod tests { } fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { - let (database, in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(config); + let ( + database, + in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = Arc::new(initialize_tracker(config, &database, &whitelist_authorization)); + let tracker = Arc::new(initialize_tracker( + config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + )); ( tracker, @@ -630,10 +644,27 @@ mod tests { fn test_tracker_factory() -> (Arc, Arc) { let config = tracker_configuration(); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); - - let tracker = Arc::new(Tracker::new(&config.core, &database, &whitelist_authorization).unwrap()); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let tracker = Arc::new( + Tracker::new( + &config.core, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ) + .unwrap(), + ); (tracker, whitelist_authorization) } @@ -1378,8 +1409,15 @@ mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - let (database, _in_memory_whitelist, whitelist_authorization, _authentication_service) = - initialize_tracker_dependencies(&config); + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock @@ -1390,7 +1428,17 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(core::Tracker::new(&config.core, &database, &whitelist_authorization).unwrap()); + let tracker = Arc::new( + core::Tracker::new( + &config.core, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + ) + .unwrap(), + ); let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); From 6fb632ee841dc2a10421a20ba935585c17099d85 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 23 Jan 2025 17:48:17 +0000 Subject: [PATCH 0641/1297] refactor: [#1201] remove duplicate code --- src/core/services/torrent.rs | 148 ++++++----------------- src/servers/http/v1/handlers/announce.rs | 1 + src/servers/udp/handlers.rs | 1 + 3 files changed, 37 insertions(+), 113 deletions(-) diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 1e3f67eba..f8da88d6f 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -107,10 +107,37 @@ pub async fn get_torrents(tracker: Arc, info_hashes: &[InfoHash]) -> Ve #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + use crate::app_test::initialize_tracker_dependencies; + use crate::core::services::initialize_tracker; + use crate::core::Tracker; + + fn initialize_tracker_and_deps(config: &Configuration) -> Arc { + let ( + database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(config); + + Arc::new(initialize_tracker( + config, + &database, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + &torrents_manager, + )) + } + fn sample_peer() -> peer::Peer { peer::Peer { peer_id: PeerId(*b"-qB00000000000000000"), @@ -134,7 +161,7 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::services::initialize_tracker; - use crate::core::services::torrent::tests::sample_peer; + use crate::core::services::torrent::tests::{initialize_tracker_and_deps, sample_peer}; use crate::core::services::torrent::{get_torrent_info, Info}; pub fn tracker_configuration() -> Configuration { @@ -179,24 +206,7 @@ mod tests { async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let config = tracker_configuration(); - let ( - database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - &torrents_manager, - )); + let tracker = initialize_tracker_and_deps(&config); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -220,15 +230,12 @@ mod tests { mod searching_for_torrents { use std::str::FromStr; - use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; - use crate::app_test::initialize_tracker_dependencies; - use crate::core::services::initialize_tracker; - use crate::core::services::torrent::tests::sample_peer; + use crate::core::services::torrent::tests::{initialize_tracker_and_deps, sample_peer}; use crate::core::services::torrent::{get_torrents_page, BasicInfo, Pagination}; pub fn tracker_configuration() -> Configuration { @@ -239,24 +246,7 @@ mod tests { async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let config = tracker_configuration(); - let ( - database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - &torrents_manager, - )); + let tracker = initialize_tracker_and_deps(&config); let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; @@ -267,24 +257,7 @@ mod tests { async fn should_return_a_summarized_info_for_all_torrents() { let config = tracker_configuration(); - let ( - database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - &torrents_manager, - )); + let tracker = initialize_tracker_and_deps(&config); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -308,24 +281,7 @@ mod tests { async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let config = tracker_configuration(); - let ( - database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - &torrents_manager, - )); + let tracker = initialize_tracker_and_deps(&config); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -347,24 +303,7 @@ mod tests { async fn should_allow_using_pagination_in_the_result() { let config = tracker_configuration(); - let ( - database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - &torrents_manager, - )); + let tracker = initialize_tracker_and_deps(&config); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -395,24 +334,7 @@ mod tests { async fn should_return_torrents_ordered_by_info_hash() { let config = tracker_configuration(); - let ( - database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let tracker = Arc::new(initialize_tracker( - &config, - &database, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - &torrents_manager, - )); + let tracker = initialize_tracker_and_deps(&config); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index b18671422..b0b54fa0d 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -283,6 +283,7 @@ mod tests { db_torrent_repository, torrents_manager, ) = initialize_tracker_dependencies(config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 840b789a1..6abbd95c6 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -525,6 +525,7 @@ mod tests { db_torrent_repository, torrents_manager, ) = initialize_tracker_dependencies(config); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); From a4a2d678bb5a2cd3dfa87f05cf9f748e9efbc1bc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 23 Jan 2025 17:54:18 +0000 Subject: [PATCH 0642/1297] refactor: [#1201] remove pub fn from tracker --- src/core/mod.rs | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 161607857..a1b496c56 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -666,18 +666,6 @@ impl Tracker { self.in_memory_torrent_repository.get_swarm_metadata(info_hash) } - /// It loads the torrents from database into memory. It only loads the torrent entry list with the number of seeders for each torrent. - /// Peers data is not persisted. - /// - /// # Context: Tracker - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to load the list of `persistent_torrents` from the database. - pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { - self.torrents_manager.load_torrents_from_database() - } - /// # Context: Tracker /// /// Get torrent peers for a given torrent and client. @@ -1543,7 +1531,7 @@ mod tests { // Remove the newly updated torrent from memory let _unused = tracker.in_memory_torrent_repository.remove(&info_hash); - tracker.load_torrents_from_database().unwrap(); + tracker.torrents_manager.load_torrents_from_database().unwrap(); let torrent_entry = tracker .in_memory_torrent_repository From bdc3f22a8c5e67a7a67a2589ced713373d227697 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 23 Jan 2025 18:01:09 +0000 Subject: [PATCH 0643/1297] refactor: [#1201] add database to app container y environments --- src/bootstrap/app.rs | 1 + src/container.rs | 2 ++ tests/servers/api/environment.rs | 5 +++++ tests/servers/http/environment.rs | 5 +++++ tests/servers/udp/environment.rs | 5 +++++ 5 files changed, 18 insertions(+) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index ea7d7f030..ea5dc41b6 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -124,6 +124,7 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { )); AppContainer { + database, tracker, keys_handler, authentication_service, diff --git a/src/container.rs b/src/container.rs index 14c4b5d7b..d8c95c42b 100644 --- a/src/container.rs +++ b/src/container.rs @@ -4,6 +4,7 @@ use tokio::sync::RwLock; use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::service::AuthenticationService; +use crate::core::databases::Database; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; use crate::core::whitelist::manager::WhiteListManager; @@ -11,6 +12,7 @@ use crate::core::{whitelist, Tracker}; use crate::servers::udp::server::banning::BanService; pub struct AppContainer { + pub database: Arc>, pub tracker: Arc, pub keys_handler: Arc, pub authentication_service: Arc, diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index f014df36f..8967ff830 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -10,6 +10,7 @@ use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_g use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::core::authentication::handler::KeysHandler; use torrust_tracker_lib::core::authentication::service::AuthenticationService; +use torrust_tracker_lib::core::databases::Database; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; @@ -24,6 +25,7 @@ where S: std::fmt::Debug + std::fmt::Display, { pub config: Arc, + pub database: Arc>, pub tracker: Arc, pub keys_handler: Arc, pub authentication_service: Arc, @@ -61,6 +63,7 @@ impl Environment { Self { config, + database: app_container.database.clone(), tracker: app_container.tracker.clone(), keys_handler: app_container.keys_handler.clone(), authentication_service: app_container.authentication_service.clone(), @@ -78,6 +81,7 @@ impl Environment { Environment { config: self.config, + database: self.database.clone(), tracker: self.tracker.clone(), keys_handler: self.keys_handler.clone(), authentication_service: self.authentication_service.clone(), @@ -112,6 +116,7 @@ impl Environment { pub async fn stop(self) -> Environment { Environment { config: self.config, + database: self.database, tracker: self.tracker, keys_handler: self.keys_handler, authentication_service: self.authentication_service, diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 81b6a12e2..80c042a21 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -7,6 +7,7 @@ use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_g use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::core::authentication::handler::KeysHandler; use torrust_tracker_lib::core::authentication::service::AuthenticationService; +use torrust_tracker_lib::core::databases::Database; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; @@ -17,6 +18,7 @@ use torrust_tracker_primitives::peer; pub struct Environment { pub config: Arc, + pub database: Arc>, pub tracker: Arc, pub keys_handler: Arc, pub authentication_service: Arc, @@ -57,6 +59,7 @@ impl Environment { Self { config, + database: app_container.database.clone(), tracker: app_container.tracker.clone(), keys_handler: app_container.keys_handler.clone(), authentication_service: app_container.authentication_service.clone(), @@ -73,6 +76,7 @@ impl Environment { pub async fn start(self) -> Environment { Environment { config: self.config, + database: self.database.clone(), tracker: self.tracker.clone(), keys_handler: self.keys_handler.clone(), authentication_service: self.authentication_service.clone(), @@ -104,6 +108,7 @@ impl Environment { pub async fn stop(self) -> Environment { Environment { config: self.config, + database: self.database, tracker: self.tracker, keys_handler: self.keys_handler, authentication_service: self.authentication_service, diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index b728509c0..c02e35e6e 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -5,6 +5,7 @@ use bittorrent_primitives::info_hash::InfoHash; use tokio::sync::RwLock; use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; +use torrust_tracker_lib::core::databases::Database; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::{whitelist, Tracker}; @@ -20,6 +21,7 @@ where S: std::fmt::Debug + std::fmt::Display, { pub config: Arc, + pub database: Arc>, pub tracker: Arc, pub whitelist_authorization: Arc, pub stats_event_sender: Arc>>, @@ -57,6 +59,7 @@ impl Environment { Self { config, + database: app_container.database.clone(), tracker: app_container.tracker.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), stats_event_sender: app_container.stats_event_sender.clone(), @@ -72,6 +75,7 @@ impl Environment { let cookie_lifetime = self.config.cookie_lifetime; Environment { config: self.config, + database: self.database.clone(), tracker: self.tracker.clone(), whitelist_authorization: self.whitelist_authorization.clone(), stats_event_sender: self.stats_event_sender.clone(), @@ -109,6 +113,7 @@ impl Environment { Environment { config: self.config, + database: self.database, tracker: self.tracker, whitelist_authorization: self.whitelist_authorization, stats_event_sender: self.stats_event_sender, From b3fcdb4c156feb610ad719afca90ead8912f29db Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 23 Jan 2025 18:11:47 +0000 Subject: [PATCH 0644/1297] refactor: [#1201] remove direct dependency on database from tracker --- src/bootstrap/app.rs | 1 - src/core/mod.rs | 26 ++----------------- src/core/services/mod.rs | 2 -- src/core/services/statistics/mod.rs | 3 +-- src/core/services/torrent.rs | 6 ++--- src/servers/http/v1/handlers/announce.rs | 5 ++-- src/servers/http/v1/handlers/scrape.rs | 12 +++------ src/servers/http/v1/services/announce.rs | 6 ++--- src/servers/http/v1/services/scrape.rs | 6 ++--- src/servers/udp/handlers.rs | 9 +++---- tests/servers/api/mod.rs | 11 +++++--- .../api/v1/contract/context/auth_key.rs | 8 +++--- .../api/v1/contract/context/whitelist.rs | 6 ++--- 13 files changed, 32 insertions(+), 69 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index ea5dc41b6..2340eb0ac 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -116,7 +116,6 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let tracker = Arc::new(initialize_tracker( configuration, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, diff --git a/src/core/mod.rs b/src/core/mod.rs index a1b496c56..18c99d3b9 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -462,8 +462,6 @@ use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use crate::core::databases::Database; - /// The domain layer tracker service. /// /// Its main responsibility is to handle the `announce` and `scrape` requests. @@ -477,10 +475,6 @@ pub struct Tracker { /// The tracker configuration. config: Core, - /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) - /// or [`MySQL`](crate::core::databases::mysql) - database: Arc>, - /// The service to check is a torrent is whitelisted. pub whitelist_authorization: Arc, @@ -544,7 +538,6 @@ impl Tracker { /// Will return a `databases::error::Error` if unable to connect to database. The `Tracker` is responsible for the persistence. pub fn new( config: &Core, - database: &Arc>, whitelist_authorization: &Arc, in_memory_torrent_repository: &Arc, db_torrent_repository: &Arc, @@ -552,7 +545,6 @@ impl Tracker { ) -> Result { Ok(Tracker { config: config.clone(), - database: database.clone(), whitelist_authorization: whitelist_authorization.clone(), in_memory_torrent_repository: in_memory_torrent_repository.clone(), db_torrent_repository: db_torrent_repository.clone(), @@ -739,17 +731,6 @@ impl Tracker { pub fn cleanup_torrents(&self) { self.torrents_manager.cleanup_torrents(); } - - /// It drops the database tables. - /// - /// # Errors - /// - /// Will return `Err` if unable to drop tables. - pub fn drop_database_tables(&self) -> Result<(), databases::error::Error> { - // todo: this is only used for testing. We have to pass the database - // reference directly to the tests instead of via the tracker. - self.database.drop_database_tables() - } } #[must_use] @@ -787,7 +768,7 @@ mod tests { let config = configuration::ephemeral_public(); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, _authentication_service, @@ -798,7 +779,6 @@ mod tests { initialize_tracker( &config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, @@ -823,7 +803,6 @@ mod tests { let tracker = initialize_tracker( &config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, @@ -838,7 +817,7 @@ mod tests { config.core.tracker_policy.persistent_torrent_completed_stat = true; let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, _authentication_service, @@ -849,7 +828,6 @@ mod tests { initialize_tracker( &config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index f5d9bd375..3a684ac8f 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -31,7 +31,6 @@ use crate::core::Tracker; #[must_use] pub fn initialize_tracker( config: &Configuration, - database: &Arc>, whitelist_authorization: &Arc, in_memory_torrent_repository: &Arc, db_torrent_repository: &Arc, @@ -39,7 +38,6 @@ pub fn initialize_tracker( ) -> Tracker { match Tracker::new( &Arc::new(config).core, - database, whitelist_authorization, in_memory_torrent_repository, db_torrent_repository, diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 9e4696f48..01e49df71 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -133,7 +133,7 @@ mod tests { let config = tracker_configuration(); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, _authentication_service, @@ -147,7 +147,6 @@ mod tests { let tracker = Arc::new(initialize_tracker( &config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index f8da88d6f..dc07405ee 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -119,7 +119,7 @@ mod tests { fn initialize_tracker_and_deps(config: &Configuration) -> Arc { let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, _authentication_service, @@ -130,7 +130,6 @@ mod tests { Arc::new(initialize_tracker( config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, @@ -173,7 +172,7 @@ mod tests { let config = tracker_configuration(); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, _authentication_service, @@ -184,7 +183,6 @@ mod tests { let tracker = initialize_tracker( &config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index b0b54fa0d..4088ab73c 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -275,7 +275,7 @@ mod tests { /// Initialize tracker's dependencies and tracker. fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, authentication_service, @@ -283,13 +283,12 @@ mod tests { db_torrent_repository, torrents_manager, ) = initialize_tracker_dependencies(config); - + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let tracker = Arc::new(initialize_tracker( config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index e619ba120..24b1c783d 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -152,7 +152,7 @@ mod tests { let config = configuration::ephemeral_private(); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, authentication_service, @@ -166,7 +166,6 @@ mod tests { ( initialize_tracker( &config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, @@ -185,7 +184,7 @@ mod tests { let config = configuration::ephemeral_listed(); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, authentication_service, @@ -199,7 +198,6 @@ mod tests { ( initialize_tracker( &config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, @@ -218,7 +216,7 @@ mod tests { let config = configuration::ephemeral_with_reverse_proxy(); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, authentication_service, @@ -232,7 +230,6 @@ mod tests { ( initialize_tracker( &config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, @@ -251,7 +248,7 @@ mod tests { let config = configuration::ephemeral_without_reverse_proxy(); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, authentication_service, @@ -265,7 +262,6 @@ mod tests { ( initialize_tracker( &config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 99724f728..56b2dd1e3 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -74,7 +74,7 @@ mod tests { let config = configuration::ephemeral_public(); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, _authentication_service, @@ -87,7 +87,6 @@ mod tests { let tracker = initialize_tracker( &config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, @@ -147,7 +146,7 @@ mod tests { let config = configuration::ephemeral(); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, _authentication_service, @@ -158,7 +157,6 @@ mod tests { Tracker::new( &config.core, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index c9e657d11..ea4cb2702 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -88,7 +88,7 @@ mod tests { let config = configuration::ephemeral_public(); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, _authentication_service, @@ -99,7 +99,6 @@ mod tests { initialize_tracker( &config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, @@ -131,7 +130,7 @@ mod tests { let config = configuration::ephemeral(); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, _authentication_service, @@ -142,7 +141,6 @@ mod tests { Tracker::new( &config.core, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 6abbd95c6..c85efc1fa 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -525,14 +525,13 @@ mod tests { db_torrent_repository, torrents_manager, ) = initialize_tracker_dependencies(config); - + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let tracker = Arc::new(initialize_tracker( config, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, @@ -646,7 +645,7 @@ mod tests { let config = tracker_configuration(); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, _authentication_service, @@ -658,7 +657,6 @@ mod tests { let tracker = Arc::new( Tracker::new( &config.core, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, @@ -1411,7 +1409,7 @@ mod tests { let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); let ( - database, + _database, _in_memory_whitelist, whitelist_authorization, _authentication_service, @@ -1432,7 +1430,6 @@ mod tests { let tracker = Arc::new( core::Tracker::new( &config.core, - &database, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, diff --git a/tests/servers/api/mod.rs b/tests/servers/api/mod.rs index 278fd869d..92bc19a5f 100644 --- a/tests/servers/api/mod.rs +++ b/tests/servers/api/mod.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use torrust_tracker_lib::core::Tracker; +use torrust_tracker_lib::core::databases::Database; use torrust_tracker_lib::servers::apis::server; pub mod connection_info; @@ -9,12 +9,15 @@ pub mod v1; pub type Started = environment::Environment; -/// It forces a database error by dropping all tables. -/// That makes any query fail. +/// It forces a database error by dropping all tables. That makes all queries +/// fail. +/// /// code-review: +/// /// Alternatively we could: +/// /// - Inject a database mock in the future. /// - Inject directly the database reference passed to the Tracker type. -pub fn force_database_error(tracker: &Arc) { +pub fn force_database_error(tracker: &Arc>) { tracker.drop_database_tables().unwrap(); } diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 73860c9c2..3b7d2d6ba 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -126,7 +126,7 @@ async fn should_fail_when_the_auth_key_cannot_be_generated() { let env = Started::new(&configuration::ephemeral().into()).await; - force_database_error(&env.tracker); + force_database_error(&env.database); let request_id = Uuid::new_v4(); @@ -297,7 +297,7 @@ async fn should_fail_when_the_auth_key_cannot_be_deleted() { .await .unwrap(); - force_database_error(&env.tracker); + force_database_error(&env.database); let request_id = Uuid::new_v4(); @@ -403,7 +403,7 @@ async fn should_fail_when_keys_cannot_be_reloaded() { .await .unwrap(); - force_database_error(&env.tracker); + force_database_error(&env.database); let response = Client::new(env.get_connection_info()) .reload_keys(Some(headers_with_request_id(request_id))) @@ -556,7 +556,7 @@ mod deprecated_generate_key_endpoint { let env = Started::new(&configuration::ephemeral().into()).await; - force_database_error(&env.tracker); + force_database_error(&env.database); let request_id = Uuid::new_v4(); let seconds_valid = 60; diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index aef1db4f1..78850d3bf 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -111,7 +111,7 @@ async fn should_fail_when_the_torrent_cannot_be_whitelisted() { let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); - force_database_error(&env.tracker); + force_database_error(&env.database); let request_id = Uuid::new_v4(); @@ -239,7 +239,7 @@ async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { let info_hash = InfoHash::from_str(&hash).unwrap(); env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); - force_database_error(&env.tracker); + force_database_error(&env.database); let request_id = Uuid::new_v4(); @@ -340,7 +340,7 @@ async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { let info_hash = InfoHash::from_str(&hash).unwrap(); env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); - force_database_error(&env.tracker); + force_database_error(&env.database); let request_id = Uuid::new_v4(); From 3a2e8f0d4c3a1d06d77fd83b7f2d065f250e8390 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 23 Jan 2025 18:17:37 +0000 Subject: [PATCH 0645/1297] refactor: [#1201] reorganize methods in tracker Grouping similar methods. --- src/core/mod.rs | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 18c99d3b9..d50d2b545 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -653,28 +653,6 @@ impl Tracker { scrape_data } - /// It returns the data for a `scrape` response. - fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { - self.in_memory_torrent_repository.get_swarm_metadata(info_hash) - } - - /// # Context: Tracker - /// - /// Get torrent peers for a given torrent and client. - /// - /// It filters out the client making the request. - fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { - self.in_memory_torrent_repository.get_peers_for(info_hash, peer, limit) - } - - /// # Context: Tracker - /// - /// Get torrent peers for a given torrent. - #[must_use] - pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { - self.in_memory_torrent_repository.get_torrent_peers(info_hash) - } - /// It updates the torrent entry in memory, it also stores in the database /// the torrent info data which is persistent, and finally return the data /// needed for a `announce` request response. @@ -713,6 +691,28 @@ impl Tracker { } } + /// It returns the data for a `scrape` response. + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { + self.in_memory_torrent_repository.get_swarm_metadata(info_hash) + } + + /// # Context: Tracker + /// + /// Get torrent peers for a given torrent and client. + /// + /// It filters out the client making the request. + fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { + self.in_memory_torrent_repository.get_peers_for(info_hash, peer, limit) + } + + /// # Context: Tracker + /// + /// Get torrent peers for a given torrent. + #[must_use] + pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { + self.in_memory_torrent_repository.get_torrent_peers(info_hash) + } + /// It calculates and returns the general `Tracker` /// [`TorrentsMetrics`] /// From 612f7293d5a2190e710852dfd51330248e50c61a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 23 Jan 2025 18:28:16 +0000 Subject: [PATCH 0646/1297] refactor: [#1201] remove tracker dependency on TorrentsManager --- src/app.rs | 2 +- src/bootstrap/app.rs | 4 ++- src/bootstrap/jobs/torrent_cleanup.rs | 12 ++++----- src/container.rs | 6 +++++ src/core/mod.rs | 33 +++++++----------------- src/core/services/mod.rs | 3 --- src/core/services/statistics/mod.rs | 3 +-- src/core/services/torrent.rs | 6 ++--- src/servers/http/v1/handlers/announce.rs | 3 +-- src/servers/http/v1/handlers/scrape.rs | 12 +++------ src/servers/http/v1/services/announce.rs | 6 ++--- src/servers/http/v1/services/scrape.rs | 6 ++--- src/servers/udp/handlers.rs | 9 +++---- 13 files changed, 41 insertions(+), 64 deletions(-) diff --git a/src/app.rs b/src/app.rs index e41f227e7..c71237443 100644 --- a/src/app.rs +++ b/src/app.rs @@ -137,7 +137,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< // Start runners to remove torrents without peers, every interval if config.core.inactive_peer_cleanup_interval > 0 { - jobs.push(torrent_cleanup::start_job(&config.core, &app_container.tracker)); + jobs.push(torrent_cleanup::start_job(&config.core, &app_container.torrents_manager)); } // Start Health Check API diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 2340eb0ac..294b2ca73 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -119,7 +119,6 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, )); AppContainer { @@ -132,6 +131,9 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { stats_event_sender, stats_repository, whitelist_manager, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, } } diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index 6abb4f26b..45e6e9e68 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -17,7 +17,7 @@ use tokio::task::JoinHandle; use torrust_tracker_configuration::Core; use tracing::instrument; -use crate::core; +use crate::core::torrent::manager::TorrentsManager; /// It starts a jobs for cleaning up the torrent data in the tracker. /// @@ -25,9 +25,9 @@ use crate::core; /// /// Refer to [`torrust-tracker-configuration documentation`](https://docs.rs/torrust-tracker-configuration) for more info about that option. #[must_use] -#[instrument(skip(config, tracker))] -pub fn start_job(config: &Core, tracker: &Arc) -> JoinHandle<()> { - let weak_tracker = std::sync::Arc::downgrade(tracker); +#[instrument(skip(config, torrents_manager))] +pub fn start_job(config: &Core, torrents_manager: &Arc) -> JoinHandle<()> { + let weak_torrents_manager = std::sync::Arc::downgrade(torrents_manager); let interval = config.inactive_peer_cleanup_interval; tokio::spawn(async move { @@ -42,10 +42,10 @@ pub fn start_job(config: &Core, tracker: &Arc) -> JoinHandle<()> break; } _ = interval.tick() => { - if let Some(tracker) = weak_tracker.upgrade() { + if let Some(torrents_manager) = weak_torrents_manager.upgrade() { let start_time = Utc::now().time(); tracing::info!("Cleaning up torrents.."); - tracker.cleanup_torrents(); + torrents_manager.cleanup_torrents(); tracing::info!("Cleaned up torrents in: {}ms", (Utc::now().time() - start_time).num_milliseconds()); } else { break; diff --git a/src/container.rs b/src/container.rs index d8c95c42b..8407d0b69 100644 --- a/src/container.rs +++ b/src/container.rs @@ -7,6 +7,9 @@ use crate::core::authentication::service::AuthenticationService; use crate::core::databases::Database; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; +use crate::core::torrent::manager::TorrentsManager; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; +use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use crate::core::whitelist::manager::WhiteListManager; use crate::core::{whitelist, Tracker}; use crate::servers::udp::server::banning::BanService; @@ -21,4 +24,7 @@ pub struct AppContainer { pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub whitelist_manager: Arc, + pub in_memory_torrent_repository: Arc, + pub db_torrent_repository: Arc, + pub torrents_manager: Arc, } diff --git a/src/core/mod.rs b/src/core/mod.rs index d50d2b545..f2483b21e 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -453,7 +453,6 @@ use std::net::IpAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; -use torrent::manager::TorrentsManager; use torrent::repository::in_memory::InMemoryTorrentRepository; use torrent::repository::persisted::DatabasePersistentTorrentRepository; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; @@ -483,9 +482,6 @@ pub struct Tracker { /// The persistent torrents repository. db_torrent_repository: Arc, - - /// The service to run torrents tasks. - torrents_manager: Arc, } /// How many peers the peer announcing wants in the announce response. @@ -541,14 +537,12 @@ impl Tracker { whitelist_authorization: &Arc, in_memory_torrent_repository: &Arc, db_torrent_repository: &Arc, - torrents_manager: &Arc, ) -> Result { Ok(Tracker { config: config.clone(), whitelist_authorization: whitelist_authorization.clone(), in_memory_torrent_repository: in_memory_torrent_repository.clone(), db_torrent_repository: db_torrent_repository.clone(), - torrents_manager: torrents_manager.clone(), }) } @@ -724,13 +718,6 @@ impl Tracker { pub fn get_torrents_metrics(&self) -> TorrentsMetrics { self.in_memory_torrent_repository.get_torrents_metrics() } - - /// Remove inactive peers and (optionally) peerless torrents. - /// - /// # Context: Tracker - pub fn cleanup_torrents(&self) { - self.torrents_manager.cleanup_torrents(); - } } #[must_use] @@ -761,6 +748,7 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::peer::Peer; use crate::core::services::{initialize_tracker, initialize_whitelist_manager}; + use crate::core::torrent::manager::TorrentsManager; use crate::core::whitelist::manager::WhiteListManager; use crate::core::{whitelist, TorrentsMetrics, Tracker}; @@ -774,7 +762,7 @@ mod tests { _authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); initialize_tracker( @@ -782,7 +770,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ) } @@ -796,7 +783,7 @@ mod tests { _authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); @@ -806,13 +793,12 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ); (tracker, whitelist_authorization, whitelist_manager) } - pub fn tracker_persisting_torrents_in_database() -> Tracker { + pub fn tracker_persisting_torrents_in_database() -> (Tracker, Arc) { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; @@ -826,13 +812,14 @@ mod tests { torrents_manager, ) = initialize_tracker_dependencies(&config); - initialize_tracker( + let tracker = initialize_tracker( &config, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, - ) + ); + + (tracker, torrents_manager) } fn sample_info_hash() -> InfoHash { @@ -1492,7 +1479,7 @@ mod tests { #[tokio::test] async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { - let tracker = tracker_persisting_torrents_in_database(); + let (tracker, torrents_manager) = tracker_persisting_torrents_in_database(); let info_hash = sample_info_hash(); @@ -1509,7 +1496,7 @@ mod tests { // Remove the newly updated torrent from memory let _unused = tracker.in_memory_torrent_repository.remove(&info_hash); - tracker.torrents_manager.load_torrents_from_database().unwrap(); + torrents_manager.load_torrents_from_database().unwrap(); let torrent_entry = tracker .in_memory_torrent_repository diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index 3a684ac8f..a9bca2df7 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -14,7 +14,6 @@ use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::Configuration; use super::databases::{self, Database}; -use super::torrent::manager::TorrentsManager; use super::torrent::repository::in_memory::InMemoryTorrentRepository; use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; use super::whitelist; @@ -34,14 +33,12 @@ pub fn initialize_tracker( whitelist_authorization: &Arc, in_memory_torrent_repository: &Arc, db_torrent_repository: &Arc, - torrents_manager: &Arc, ) -> Tracker { match Tracker::new( &Arc::new(config).core, whitelist_authorization, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, ) { Ok(tracker) => tracker, Err(error) => { diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 01e49df71..7c2233efd 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -139,7 +139,7 @@ mod tests { _authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); @@ -150,7 +150,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, )); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index dc07405ee..c2ffa05aa 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -125,7 +125,7 @@ mod tests { _authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(config); Arc::new(initialize_tracker( @@ -133,7 +133,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, )) } @@ -178,7 +177,7 @@ mod tests { _authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); let tracker = initialize_tracker( @@ -186,7 +185,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ); let tracker = Arc::new(tracker); diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 4088ab73c..a9567fb81 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -281,7 +281,7 @@ mod tests { authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); @@ -292,7 +292,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, )); (tracker, stats_event_sender, whitelist_authorization, authentication_service) diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 24b1c783d..116d717a1 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -158,7 +158,7 @@ mod tests { authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); @@ -169,7 +169,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ), stats_event_sender, authentication_service, @@ -190,7 +189,7 @@ mod tests { authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); @@ -201,7 +200,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ), stats_event_sender, authentication_service, @@ -222,7 +220,7 @@ mod tests { authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); @@ -233,7 +231,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ), stats_event_sender, authentication_service, @@ -254,7 +251,7 @@ mod tests { authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); @@ -265,7 +262,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ), stats_event_sender, authentication_service, diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 56b2dd1e3..322bc80eb 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -80,7 +80,7 @@ mod tests { _authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); @@ -90,7 +90,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ); (tracker, stats_event_sender) @@ -152,7 +151,7 @@ mod tests { _authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); Tracker::new( @@ -160,7 +159,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ) .unwrap() } diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index ea4cb2702..299938f84 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -94,7 +94,7 @@ mod tests { _authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); initialize_tracker( @@ -102,7 +102,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ) } @@ -136,7 +135,7 @@ mod tests { _authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); Tracker::new( @@ -144,7 +143,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ) .unwrap() } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index c85efc1fa..5584c167b 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -523,7 +523,7 @@ mod tests { _authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); @@ -535,7 +535,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, )); ( @@ -651,7 +650,7 @@ mod tests { _authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); let tracker = Arc::new( @@ -660,7 +659,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ) .unwrap(), ); @@ -1415,7 +1413,7 @@ mod tests { _authentication_service, in_memory_torrent_repository, db_torrent_repository, - torrents_manager, + _torrents_manager, ) = initialize_tracker_dependencies(&config); let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); @@ -1433,7 +1431,6 @@ mod tests { &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - &torrents_manager, ) .unwrap(), ); From 94673d677c59d75b41c4846b5014f98f073e8bbd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 24 Jan 2025 08:34:07 +0000 Subject: [PATCH 0647/1297] refactor: [#1203] inline methods in core tracker For the InMemoryTorrentRepository. --- src/core/mod.rs | 64 ++++++++--------------------- src/core/services/statistics/mod.rs | 2 +- src/servers/udp/handlers.rs | 12 +++--- tests/servers/http/v1/contract.rs | 8 ++-- 4 files changed, 29 insertions(+), 57 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index f2483b21e..d00db88a8 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -459,7 +459,6 @@ use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; /// The domain layer tracker service. /// @@ -478,7 +477,7 @@ pub struct Tracker { pub whitelist_authorization: Arc, /// The in-memory torrents repository. - in_memory_torrent_repository: Arc, + pub in_memory_torrent_repository: Arc, /// The persistent torrents repository. db_torrent_repository: Arc, @@ -619,7 +618,9 @@ impl Tracker { let stats = self.upsert_peer_and_get_stats(info_hash, peer); - let peers = self.get_peers_for(info_hash, peer, peers_wanted.limit()); + let peers = self + .in_memory_torrent_repository + .get_peers_for(info_hash, peer, peers_wanted.limit()); AnnounceData { peers, @@ -638,7 +639,7 @@ impl Tracker { for info_hash in info_hashes { let swarm_metadata = match self.whitelist_authorization.authorize(info_hash).await { - Ok(()) => self.get_swarm_metadata(info_hash), + Ok(()) => self.in_memory_torrent_repository.get_swarm_metadata(info_hash), Err(_) => SwarmMetadata::zeroed(), }; scrape_data.add_file(info_hash, swarm_metadata); @@ -684,40 +685,6 @@ impl Tracker { drop(self.db_torrent_repository.save(&info_hash, completed)); } } - - /// It returns the data for a `scrape` response. - fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { - self.in_memory_torrent_repository.get_swarm_metadata(info_hash) - } - - /// # Context: Tracker - /// - /// Get torrent peers for a given torrent and client. - /// - /// It filters out the client making the request. - fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { - self.in_memory_torrent_repository.get_peers_for(info_hash, peer, limit) - } - - /// # Context: Tracker - /// - /// Get torrent peers for a given torrent. - #[must_use] - pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { - self.in_memory_torrent_repository.get_torrent_peers(info_hash) - } - - /// It calculates and returns the general `Tracker` - /// [`TorrentsMetrics`] - /// - /// # Context: Tracker - /// - /// # Panics - /// Panics if unable to get the torrent metrics. - #[must_use] - pub fn get_torrents_metrics(&self) -> TorrentsMetrics { - self.in_memory_torrent_repository.get_torrents_metrics() - } } #[must_use] @@ -742,6 +709,7 @@ mod tests { use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; + use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; @@ -750,7 +718,7 @@ mod tests { use crate::core::services::{initialize_tracker, initialize_whitelist_manager}; use crate::core::torrent::manager::TorrentsManager; use crate::core::whitelist::manager::WhiteListManager; - use crate::core::{whitelist, TorrentsMetrics, Tracker}; + use crate::core::{whitelist, Tracker}; fn public_tracker() -> Tracker { let config = configuration::ephemeral_public(); @@ -910,7 +878,7 @@ mod tests { async fn should_collect_torrent_metrics() { let tracker = public_tracker(); - let torrents_metrics = tracker.get_torrents_metrics(); + let torrents_metrics = tracker.in_memory_torrent_repository.get_torrents_metrics(); assert_eq!( torrents_metrics, @@ -932,7 +900,7 @@ mod tests { let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); - let peers = tracker.get_torrent_peers(&info_hash); + let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash); assert_eq!(peers, vec![Arc::new(peer)]); } @@ -975,7 +943,7 @@ mod tests { let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); } - let peers = tracker.get_torrent_peers(&info_hash); + let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash); assert_eq!(peers.len(), 74); } @@ -989,7 +957,9 @@ mod tests { let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); - let peers = tracker.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); + let peers = tracker + .in_memory_torrent_repository + .get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); assert_eq!(peers, vec![]); } @@ -1019,7 +989,9 @@ mod tests { let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); } - let peers = tracker.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); + let peers = tracker + .in_memory_torrent_repository + .get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); assert_eq!(peers.len(), 74); } @@ -1030,7 +1002,7 @@ mod tests { let _ = tracker.upsert_peer_and_get_stats(&sample_info_hash(), &leecher()); - let torrent_metrics = tracker.get_torrents_metrics(); + let torrent_metrics = tracker.in_memory_torrent_repository.get_torrents_metrics(); assert_eq!( torrent_metrics, @@ -1054,7 +1026,7 @@ mod tests { let result_a = start_time.elapsed(); let start_time = std::time::Instant::now(); - let torrent_metrics = tracker.get_torrents_metrics(); + let torrent_metrics = tracker.in_memory_torrent_repository.get_torrents_metrics(); let result_b = start_time.elapsed(); assert_eq!( diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 7c2233efd..fefe17933 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -68,7 +68,7 @@ pub async fn get_metrics( ban_service: Arc>, stats_repository: Arc, ) -> TrackerMetrics { - let torrents_metrics = tracker.get_torrents_metrics(); + let torrents_metrics = tracker.in_memory_torrent_repository.get_torrents_metrics(); let stats = stats_repository.get_stats().await; let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 5584c167b..fd2a37683 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -916,7 +916,7 @@ mod tests { .await .unwrap(); - let peers = tracker.get_torrent_peers(&info_hash.0.into()); + let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) @@ -1001,7 +1001,7 @@ mod tests { .await .unwrap(); - let peers = tracker.get_torrent_peers(&info_hash.0.into()); + let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); } @@ -1133,7 +1133,7 @@ mod tests { .await .unwrap(); - let peers = tracker.get_torrent_peers(&info_hash.0.into()); + let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); let external_ip_in_tracker_configuration = tracker.get_maybe_external_ip().unwrap(); @@ -1200,7 +1200,7 @@ mod tests { .await .unwrap(); - let peers = tracker.get_torrent_peers(&info_hash.0.into()); + let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) @@ -1288,7 +1288,7 @@ mod tests { .await .unwrap(); - let peers = tracker.get_torrent_peers(&info_hash.0.into()); + let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); // When using IPv6 the tracker converts the remote client ip into a IPv4 address assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); @@ -1466,7 +1466,7 @@ mod tests { .await .unwrap(); - let peers = tracker.get_torrent_peers(&info_hash.0.into()); + let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); let external_ip_in_tracker_configuration = tracker.get_maybe_external_ip().unwrap(); diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 0aafbd213..31aae9b50 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -831,7 +831,7 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.tracker.get_torrent_peers(&info_hash); + let peers = env.tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), client_ip); @@ -869,7 +869,7 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.tracker.get_torrent_peers(&info_hash); + let peers = env.tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), env.tracker.get_maybe_external_ip().unwrap()); @@ -911,7 +911,7 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.tracker.get_torrent_peers(&info_hash); + let peers = env.tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), env.tracker.get_maybe_external_ip().unwrap()); @@ -951,7 +951,7 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.tracker.get_torrent_peers(&info_hash); + let peers = env.tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), IpAddr::from_str("150.172.238.178").unwrap()); From 2ac68f6935966ff8ecfed6b75a2a2f0d7a2cf197 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 24 Jan 2025 09:28:35 +0000 Subject: [PATCH 0648/1297] refactor: [#1203] move test --- src/core/mod.rs | 17 ---------------- src/core/torrent/repository/in_memory.rs | 26 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index d00db88a8..ff5b03e09 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -874,23 +874,6 @@ mod tests { } } - #[tokio::test] - async fn should_collect_torrent_metrics() { - let tracker = public_tracker(); - - let torrents_metrics = tracker.in_memory_torrent_repository.get_torrents_metrics(); - - assert_eq!( - torrents_metrics, - TorrentsMetrics { - complete: 0, - downloaded: 0, - incomplete: 0, - torrents: 0 - } - ); - } - #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent() { let tracker = public_tracker(); diff --git a/src/core/torrent/repository/in_memory.rs b/src/core/torrent/repository/in_memory.rs index 6b1902d95..7d469a0f5 100644 --- a/src/core/torrent/repository/in_memory.rs +++ b/src/core/torrent/repository/in_memory.rs @@ -101,3 +101,29 @@ impl InMemoryTorrentRepository { self.torrents.import_persistent(persistent_torrents); } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + + #[tokio::test] + async fn should_collect_torrent_metrics() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + + assert_eq!( + torrents_metrics, + TorrentsMetrics { + complete: 0, + downloaded: 0, + incomplete: 0, + torrents: 0 + } + ); + } +} From 0f1b2fb9ce551088daca799fc007733889fe2424 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 24 Jan 2025 09:53:40 +0000 Subject: [PATCH 0649/1297] refactor: [#1203] use InMemoryTorrentRepository directly in core tracker tests --- src/core/mod.rs | 48 ++++++++++++++++++++++++++++++++++++------------ 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index ff5b03e09..d6d079cf6 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -717,6 +717,7 @@ mod tests { use crate::core::peer::Peer; use crate::core::services::{initialize_tracker, initialize_whitelist_manager}; use crate::core::torrent::manager::TorrentsManager; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::whitelist::manager::WhiteListManager; use crate::core::{whitelist, Tracker}; @@ -741,6 +742,29 @@ mod tests { ) } + fn public_tracker_and_in_memory_torrents_repository() -> (Arc, Arc) { + let config = configuration::ephemeral_public(); + + let ( + _database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + _torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let tracker = Arc::new(initialize_tracker( + &config, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + (tracker, in_memory_torrent_repository) + } + fn whitelisted_tracker() -> (Tracker, Arc, Arc) { let config = configuration::ephemeral_listed(); @@ -766,7 +790,7 @@ mod tests { (tracker, whitelist_authorization, whitelist_manager) } - pub fn tracker_persisting_torrents_in_database() -> (Tracker, Arc) { + pub fn tracker_persisting_torrents_in_database() -> (Tracker, Arc, Arc) { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; @@ -787,7 +811,7 @@ mod tests { &db_torrent_repository, ); - (tracker, torrents_manager) + (tracker, torrents_manager, in_memory_torrent_repository) } fn sample_info_hash() -> InfoHash { @@ -876,14 +900,14 @@ mod tests { #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent() { - let tracker = public_tracker(); + let (tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); let info_hash = sample_info_hash(); let peer = sample_peer(); let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); - let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash); + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); assert_eq!(peers, vec![Arc::new(peer)]); } @@ -908,7 +932,7 @@ mod tests { #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { - let tracker = public_tracker(); + let (tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); let info_hash = sample_info_hash(); @@ -926,7 +950,7 @@ mod tests { let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); } - let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash); + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); assert_eq!(peers.len(), 74); } @@ -981,11 +1005,11 @@ mod tests { #[tokio::test] async fn it_should_return_the_torrent_metrics() { - let tracker = public_tracker(); + let (tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); let _ = tracker.upsert_peer_and_get_stats(&sample_info_hash(), &leecher()); - let torrent_metrics = tracker.in_memory_torrent_repository.get_torrents_metrics(); + let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); assert_eq!( torrent_metrics, @@ -1000,7 +1024,7 @@ mod tests { #[tokio::test] async fn it_should_get_many_the_torrent_metrics() { - let tracker = public_tracker(); + let (tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); let start_time = std::time::Instant::now(); for i in 0..1_000_000 { @@ -1009,7 +1033,7 @@ mod tests { let result_a = start_time.elapsed(); let start_time = std::time::Instant::now(); - let torrent_metrics = tracker.in_memory_torrent_repository.get_torrents_metrics(); + let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); let result_b = start_time.elapsed(); assert_eq!( @@ -1434,7 +1458,7 @@ mod tests { #[tokio::test] async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { - let (tracker, torrents_manager) = tracker_persisting_torrents_in_database(); + let (tracker, torrents_manager, in_memory_torrent_repository) = tracker_persisting_torrents_in_database(); let info_hash = sample_info_hash(); @@ -1449,7 +1473,7 @@ mod tests { assert_eq!(swarm_stats.downloaded, 1); // Remove the newly updated torrent from memory - let _unused = tracker.in_memory_torrent_repository.remove(&info_hash); + let _unused = in_memory_torrent_repository.remove(&info_hash); torrents_manager.load_torrents_from_database().unwrap(); From 046578d87706137bb9e9fbc3d07c734b89c4ba80 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 24 Jan 2025 10:34:41 +0000 Subject: [PATCH 0650/1297] refactor: [#1203] use directly the InMemoryTorrentRepository --- src/app.rs | 2 +- src/bootstrap/jobs/tracker_apis.rs | 14 +- src/core/mod.rs | 12 +- src/core/services/statistics/mod.rs | 15 +- src/core/services/torrent.rs | 92 +++++------ src/servers/apis/routes.rs | 7 +- src/servers/apis/server.rs | 16 +- src/servers/apis/v1/context/stats/handlers.rs | 4 +- src/servers/apis/v1/context/stats/routes.rs | 6 +- .../apis/v1/context/torrent/handlers.rs | 20 ++- src/servers/apis/v1/context/torrent/routes.rs | 11 +- src/servers/apis/v1/routes.rs | 8 +- src/servers/udp/handlers.rs | 145 ++++++++++++++---- tests/servers/api/environment.rs | 7 +- tests/servers/http/environment.rs | 5 + tests/servers/http/v1/contract.rs | 8 +- 16 files changed, 233 insertions(+), 139 deletions(-) diff --git a/src/app.rs b/src/app.rs index c71237443..67a319549 100644 --- a/src/app.rs +++ b/src/app.rs @@ -118,7 +118,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< if let Some(http_api_config) = &config.http_api { if let Some(job) = tracker_apis::start_job( http_api_config, - app_container.tracker.clone(), + app_container.in_memory_torrent_repository.clone(), app_container.keys_handler.clone(), app_container.whitelist_manager.clone(), app_container.ban_service.clone(), diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 1047fa418..f735bc4d7 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -33,8 +33,8 @@ use super::make_rust_tls; use crate::core::authentication::handler::KeysHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::whitelist::manager::WhiteListManager; -use crate::core::{self}; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::apis::Version; use crate::servers::registar::ServiceRegistrationForm; @@ -63,7 +63,6 @@ pub struct ApiServerJobStarted(); #[allow(clippy::too_many_arguments)] #[instrument(skip( config, - tracker, keys_handler, whitelist_manager, ban_service, @@ -73,7 +72,7 @@ pub struct ApiServerJobStarted(); ))] pub async fn start_job( config: &HttpApi, - tracker: Arc, + in_memory_torrent_repository: Arc, keys_handler: Arc, whitelist_manager: Arc, ban_service: Arc>, @@ -95,7 +94,7 @@ pub async fn start_job( start_v1( bind_to, tls, - tracker.clone(), + in_memory_torrent_repository.clone(), keys_handler.clone(), whitelist_manager.clone(), ban_service.clone(), @@ -114,7 +113,6 @@ pub async fn start_job( #[instrument(skip( socket, tls, - tracker, keys_handler, whitelist_manager, ban_service, @@ -126,7 +124,7 @@ pub async fn start_job( async fn start_v1( socket: SocketAddr, tls: Option, - tracker: Arc, + in_memory_torrent_repository: Arc, keys_handler: Arc, whitelist_manager: Arc, ban_service: Arc>, @@ -137,7 +135,7 @@ async fn start_v1( ) -> JoinHandle<()> { let server = ApiServer::new(Launcher::new(socket, tls)) .start( - tracker, + in_memory_torrent_repository, keys_handler, whitelist_manager, stats_event_sender, @@ -179,7 +177,7 @@ mod tests { start_job( config, - app_container.tracker, + app_container.in_memory_torrent_repository, app_container.keys_handler, app_container.whitelist_manager, app_container.ban_service, diff --git a/src/core/mod.rs b/src/core/mod.rs index d6d079cf6..6ad48289f 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -474,10 +474,10 @@ pub struct Tracker { config: Core, /// The service to check is a torrent is whitelisted. - pub whitelist_authorization: Arc, + whitelist_authorization: Arc, /// The in-memory torrents repository. - pub in_memory_torrent_repository: Arc, + in_memory_torrent_repository: Arc, /// The persistent torrents repository. db_torrent_repository: Arc, @@ -1325,24 +1325,24 @@ mod tests { #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { - let (tracker, _whitelist_authorization, whitelist_manager) = whitelisted_tracker(); + let (_tracker, whitelist_authorization, whitelist_manager) = whitelisted_tracker(); let info_hash = sample_info_hash(); let result = whitelist_manager.add_torrent_to_whitelist(&info_hash).await; assert!(result.is_ok()); - let result = tracker.whitelist_authorization.authorize(&info_hash).await; + let result = whitelist_authorization.authorize(&info_hash).await; assert!(result.is_ok()); } #[tokio::test] async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { - let (tracker, _whitelist_authorization, _whitelist_manager) = whitelisted_tracker(); + let (_tracker, whitelist_authorization, _whitelist_manager) = whitelisted_tracker(); let info_hash = sample_info_hash(); - let result = tracker.whitelist_authorization.authorize(&info_hash).await; + let result = whitelist_authorization.authorize(&info_hash).await; assert!(result.is_err()); } } diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index fefe17933..ea7ebe994 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -45,7 +45,7 @@ use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use crate::core::statistics::metrics::Metrics; use crate::core::statistics::repository::Repository; -use crate::core::Tracker; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::servers::udp::server::banning::BanService; /// All the metrics collected by the tracker. @@ -64,11 +64,11 @@ pub struct TrackerMetrics { /// It returns all the [`TrackerMetrics`] pub async fn get_metrics( - tracker: Arc, + in_memory_torrent_repository: Arc, ban_service: Arc>, stats_repository: Arc, ) -> TrackerMetrics { - let torrents_metrics = tracker.in_memory_torrent_repository.get_torrents_metrics(); + let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); let stats = stats_repository.get_stats().await; let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); @@ -145,7 +145,7 @@ mod tests { let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_repository = Arc::new(stats_repository); - let tracker = Arc::new(initialize_tracker( + let _tracker = Arc::new(initialize_tracker( &config, &whitelist_authorization, &in_memory_torrent_repository, @@ -154,7 +154,12 @@ mod tests { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let tracker_metrics = get_metrics(tracker.clone(), ban_service.clone(), stats_repository.clone()).await; + let tracker_metrics = get_metrics( + in_memory_torrent_repository.clone(), + ban_service.clone(), + stats_repository.clone(), + ) + .await; assert_eq!( tracker_metrics, diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index c2ffa05aa..dae619d62 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -11,7 +11,7 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::peer; use torrust_tracker_torrent_repository::entry::EntrySync; -use crate::core::Tracker; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; /// It contains all the information the tracker has about a torrent #[derive(Debug, PartialEq)] @@ -44,8 +44,11 @@ pub struct BasicInfo { } /// It returns all the information the tracker has about one torrent in a [Info] struct. -pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Option { - let torrent_entry_option = tracker.in_memory_torrent_repository.get(info_hash); +pub async fn get_torrent_info( + in_memory_torrent_repository: Arc, + info_hash: &InfoHash, +) -> Option { + let torrent_entry_option = in_memory_torrent_repository.get(info_hash); let torrent_entry = torrent_entry_option?; @@ -65,10 +68,13 @@ pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Op } /// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list. -pub async fn get_torrents_page(tracker: Arc, pagination: Option<&Pagination>) -> Vec { +pub async fn get_torrents_page( + in_memory_torrent_repository: Arc, + pagination: Option<&Pagination>, +) -> Vec { let mut basic_infos: Vec = vec![]; - for (info_hash, torrent_entry) in tracker.in_memory_torrent_repository.get_paginated(pagination) { + for (info_hash, torrent_entry) in in_memory_torrent_repository.get_paginated(pagination) { let stats = torrent_entry.get_swarm_metadata(); basic_infos.push(BasicInfo { @@ -83,15 +89,14 @@ pub async fn get_torrents_page(tracker: Arc, pagination: Option<&Pagina } /// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list. -pub async fn get_torrents(tracker: Arc, info_hashes: &[InfoHash]) -> Vec { +pub async fn get_torrents( + in_memory_torrent_repository: Arc, + info_hashes: &[InfoHash], +) -> Vec { let mut basic_infos: Vec = vec![]; for info_hash in info_hashes { - if let Some(stats) = tracker - .in_memory_torrent_repository - .get(info_hash) - .map(|t| t.get_swarm_metadata()) - { + if let Some(stats) = in_memory_torrent_repository.get(info_hash).map(|t| t.get_swarm_metadata()) { basic_infos.push(BasicInfo { info_hash: *info_hash, seeders: u64::from(stats.complete), @@ -115,9 +120,10 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::services::initialize_tracker; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::Tracker; - fn initialize_tracker_and_deps(config: &Configuration) -> Arc { + fn initialize_tracker_and_deps(config: &Configuration) -> (Arc, Arc) { let ( _database, _in_memory_whitelist, @@ -128,12 +134,14 @@ mod tests { _torrents_manager, ) = initialize_tracker_dependencies(config); - Arc::new(initialize_tracker( + let tracker = Arc::new(initialize_tracker( config, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - )) + )); + + (tracker, in_memory_torrent_repository) } fn sample_peer() -> peer::Peer { @@ -157,10 +165,9 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; - use crate::app_test::initialize_tracker_dependencies; - use crate::core::services::initialize_tracker; use crate::core::services::torrent::tests::{initialize_tracker_and_deps, sample_peer}; use crate::core::services::torrent::{get_torrent_info, Info}; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -168,29 +175,10 @@ mod tests { #[tokio::test] async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { - let config = tracker_configuration(); - - let ( - _database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let tracker = initialize_tracker( - &config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - ); - - let tracker = Arc::new(tracker); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let torrent_info = get_torrent_info( - tracker.clone(), + in_memory_torrent_repository.clone(), &InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(), ) .await; @@ -202,13 +190,15 @@ mod tests { async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let config = tracker_configuration(); - let tracker = initialize_tracker_and_deps(&config); + let (tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); let _ = tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()); - let torrent_info = get_torrent_info(tracker.clone(), &info_hash).await.unwrap(); + let torrent_info = get_torrent_info(in_memory_torrent_repository.clone(), &info_hash) + .await + .unwrap(); assert_eq!( torrent_info, @@ -226,6 +216,7 @@ mod tests { mod searching_for_torrents { use std::str::FromStr; + use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::Configuration; @@ -233,6 +224,7 @@ mod tests { use crate::core::services::torrent::tests::{initialize_tracker_and_deps, sample_peer}; use crate::core::services::torrent::{get_torrents_page, BasicInfo, Pagination}; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -240,11 +232,9 @@ mod tests { #[tokio::test] async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { - let config = tracker_configuration(); - - let tracker = initialize_tracker_and_deps(&config); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; + let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::default())).await; assert_eq!(torrents, vec![]); } @@ -253,14 +243,14 @@ mod tests { async fn should_return_a_summarized_info_for_all_torrents() { let config = tracker_configuration(); - let tracker = initialize_tracker_and_deps(&config); + let (tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); let _ = tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()); - let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; + let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::default())).await; assert_eq!( torrents, @@ -277,7 +267,7 @@ mod tests { async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let config = tracker_configuration(); - let tracker = initialize_tracker_and_deps(&config); + let (tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -290,7 +280,7 @@ mod tests { let offset = 0; let limit = 1; - let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::new(offset, limit))).await; + let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::new(offset, limit))).await; assert_eq!(torrents.len(), 1); } @@ -299,7 +289,7 @@ mod tests { async fn should_allow_using_pagination_in_the_result() { let config = tracker_configuration(); - let tracker = initialize_tracker_and_deps(&config); + let (tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -312,7 +302,7 @@ mod tests { let offset = 1; let limit = 4000; - let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::new(offset, limit))).await; + let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::new(offset, limit))).await; assert_eq!(torrents.len(), 1); assert_eq!( @@ -330,7 +320,7 @@ mod tests { async fn should_return_torrents_ordered_by_info_hash() { let config = tracker_configuration(); - let tracker = initialize_tracker_and_deps(&config); + let (tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -340,7 +330,7 @@ mod tests { let info_hash2 = InfoHash::from_str(&hash2).unwrap(); let _ = tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); - let torrents = get_torrents_page(tracker.clone(), Some(&Pagination::default())).await; + let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::default())).await; assert_eq!( torrents, diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 4a005393d..c27b5f906 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -33,8 +33,8 @@ use super::v1::middlewares::auth::State; use crate::core::authentication::handler::KeysHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::whitelist::manager::WhiteListManager; -use crate::core::Tracker; use crate::servers::apis::API_LOG_TARGET; use crate::servers::logging::Latency; use crate::servers::udp::server::banning::BanService; @@ -43,7 +43,6 @@ use crate::servers::udp::server::banning::BanService; #[allow(clippy::too_many_arguments)] #[allow(clippy::needless_pass_by_value)] #[instrument(skip( - tracker, keys_handler, whitelist_manager, ban_service, @@ -52,7 +51,7 @@ use crate::servers::udp::server::banning::BanService; access_tokens ))] pub fn router( - tracker: Arc, + in_memory_torrent_repository: Arc, keys_handler: Arc, whitelist_manager: Arc, ban_service: Arc>, @@ -68,7 +67,7 @@ pub fn router( let router = v1::routes::add( api_url_prefix, router, - tracker.clone(), + &in_memory_torrent_repository.clone(), &keys_handler.clone(), &whitelist_manager.clone(), ban_service.clone(), diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index e65d6643d..b37f71d5b 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -40,9 +40,10 @@ use tracing::{instrument, Level}; use super::routes::router; use crate::bootstrap::jobs::Started; use crate::core::authentication::handler::KeysHandler; +use crate::core::statistics; use crate::core::statistics::repository::Repository; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::whitelist::manager::WhiteListManager; -use crate::core::{statistics, Tracker}; use crate::servers::apis::API_LOG_TARGET; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::logging::STARTED_ON; @@ -128,10 +129,10 @@ impl ApiServer { /// /// It would panic if the bound socket address cannot be sent back to this starter. #[allow(clippy::too_many_arguments)] - #[instrument(skip(self, tracker, keys_handler, whitelist_manager, stats_event_sender, ban_service, stats_repository, form, access_tokens), err, ret(Display, level = Level::INFO))] + #[instrument(skip(self, in_memory_torrent_repository, keys_handler, whitelist_manager, stats_event_sender, ban_service, stats_repository, form, access_tokens), err, ret(Display, level = Level::INFO))] pub async fn start( self, - tracker: Arc, + in_memory_torrent_repository: Arc, keys_handler: Arc, whitelist_manager: Arc, stats_event_sender: Arc>>, @@ -150,7 +151,7 @@ impl ApiServer { let _task = launcher .start( - tracker, + in_memory_torrent_repository, keys_handler, whitelist_manager, ban_service, @@ -261,7 +262,6 @@ impl Launcher { #[allow(clippy::too_many_arguments)] #[instrument(skip( self, - tracker, keys_handler, whitelist_manager, ban_service, @@ -273,7 +273,7 @@ impl Launcher { ))] pub fn start( &self, - tracker: Arc, + in_memory_torrent_repository: Arc, keys_handler: Arc, whitelist_manager: Arc, ban_service: Arc>, @@ -287,7 +287,7 @@ impl Launcher { let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); let router = router( - tracker, + in_memory_torrent_repository, keys_handler, whitelist_manager, ban_service, @@ -373,7 +373,7 @@ mod tests { let started = stopped .start( - app_container.tracker, + app_container.in_memory_torrent_repository, app_container.keys_handler, app_container.whitelist_manager, app_container.stats_event_sender, diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index af7e1c239..da87696fc 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -11,7 +11,7 @@ use tokio::sync::RwLock; use super::responses::{metrics_response, stats_response}; use crate::core::services::statistics::get_metrics; use crate::core::statistics::repository::Repository; -use crate::core::Tracker; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::servers::udp::server::banning::BanService; #[derive(Deserialize, Debug, Default)] @@ -40,7 +40,7 @@ pub struct QueryParams { /// for more information about this endpoint. #[allow(clippy::type_complexity)] pub async fn get_stats_handler( - State(state): State<(Arc, Arc>, Arc)>, + State(state): State<(Arc, Arc>, Arc)>, params: Query, ) -> Response { let metrics = get_metrics(state.0.clone(), state.1.clone(), state.2.clone()).await; diff --git a/src/servers/apis/v1/context/stats/routes.rs b/src/servers/apis/v1/context/stats/routes.rs index b5df32963..083c72b10 100644 --- a/src/servers/apis/v1/context/stats/routes.rs +++ b/src/servers/apis/v1/context/stats/routes.rs @@ -12,20 +12,20 @@ use tokio::sync::RwLock; use super::handlers::get_stats_handler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; -use crate::core::Tracker; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::servers::udp::server::banning::BanService; /// It adds the routes to the router for the [`stats`](crate::servers::apis::v1::context::stats) API context. pub fn add( prefix: &str, router: Router, - tracker: Arc, + in_memory_torrent_repository: Arc, ban_service: Arc>, _stats_event_sender: Arc>>, stats_repository: Arc, ) -> Router { router.route( &format!("{prefix}/stats"), - get(get_stats_handler).with_state((tracker, ban_service, stats_repository)), + get(get_stats_handler).with_state((in_memory_torrent_repository, ban_service, stats_repository)), ) } diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs index 0ba713f62..8fe20ab80 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/src/servers/apis/v1/context/torrent/handlers.rs @@ -14,7 +14,7 @@ use torrust_tracker_primitives::pagination::Pagination; use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; use crate::core::services::torrent::{get_torrent_info, get_torrents, get_torrents_page}; -use crate::core::Tracker; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::servers::apis::v1::responses::invalid_info_hash_param_response; use crate::servers::apis::InfoHashParam; @@ -27,10 +27,13 @@ use crate::servers::apis::InfoHashParam; /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent#get-a-torrent) /// for more information about this endpoint. -pub async fn get_torrent_handler(State(tracker): State>, Path(info_hash): Path) -> Response { +pub async fn get_torrent_handler( + State(in_memory_torrent_repository): State>, + Path(info_hash): Path, +) -> Response { match InfoHash::from_str(&info_hash.0) { Err(_) => invalid_info_hash_param_response(&info_hash.0), - Ok(info_hash) => match get_torrent_info(tracker.clone(), &info_hash).await { + Ok(info_hash) => match get_torrent_info(in_memory_torrent_repository.clone(), &info_hash).await { Some(info) => torrent_info_response(info).into_response(), None => torrent_not_known_response(), }, @@ -75,13 +78,16 @@ pub struct QueryParams { /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent#list-torrents) /// for more information about this endpoint. -pub async fn get_torrents_handler(State(tracker): State>, pagination: Query) -> Response { +pub async fn get_torrents_handler( + State(in_memory_torrent_repository): State>, + pagination: Query, +) -> Response { tracing::debug!("pagination: {:?}", pagination); if pagination.0.info_hashes.is_empty() { torrent_list_response( &get_torrents_page( - tracker.clone(), + in_memory_torrent_repository.clone(), Some(&Pagination::new_with_options(pagination.0.offset, pagination.0.limit)), ) .await, @@ -89,7 +95,9 @@ pub async fn get_torrents_handler(State(tracker): State>, paginatio .into_response() } else { match parse_info_hashes(pagination.0.info_hashes) { - Ok(info_hashes) => torrent_list_response(&get_torrents(tracker.clone(), &info_hashes).await).into_response(), + Ok(info_hashes) => { + torrent_list_response(&get_torrents(in_memory_torrent_repository.clone(), &info_hashes).await).into_response() + } Err(err) => match err { QueryParamError::InvalidInfoHash { info_hash } => invalid_info_hash_param_response(&info_hash), }, diff --git a/src/servers/apis/v1/context/torrent/routes.rs b/src/servers/apis/v1/context/torrent/routes.rs index bca594e3d..dc66a1753 100644 --- a/src/servers/apis/v1/context/torrent/routes.rs +++ b/src/servers/apis/v1/context/torrent/routes.rs @@ -10,15 +10,18 @@ use axum::routing::get; use axum::Router; use super::handlers::{get_torrent_handler, get_torrents_handler}; -use crate::core::Tracker; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; /// It adds the routes to the router for the [`torrent`](crate::servers::apis::v1::context::torrent) API context. -pub fn add(prefix: &str, router: Router, tracker: Arc) -> Router { +pub fn add(prefix: &str, router: Router, in_memory_torrent_repository: Arc) -> Router { // Torrents router .route( &format!("{prefix}/torrent/{{info_hash}}"), - get(get_torrent_handler).with_state(tracker.clone()), + get(get_torrent_handler).with_state(in_memory_torrent_repository.clone()), + ) + .route( + &format!("{prefix}/torrents"), + get(get_torrents_handler).with_state(in_memory_torrent_repository), ) - .route(&format!("{prefix}/torrents"), get(get_torrents_handler).with_state(tracker)) } diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs index c26ce4f3d..8fac453b8 100644 --- a/src/servers/apis/v1/routes.rs +++ b/src/servers/apis/v1/routes.rs @@ -8,8 +8,8 @@ use super::context::{auth_key, stats, torrent, whitelist}; use crate::core::authentication::handler::KeysHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; +use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::whitelist::manager::WhiteListManager; -use crate::core::Tracker; use crate::servers::udp::server::banning::BanService; /// Add the routes for the v1 API. @@ -17,7 +17,7 @@ use crate::servers::udp::server::banning::BanService; pub fn add( prefix: &str, router: Router, - tracker: Arc, + in_memory_torrent_repository: &Arc, keys_handler: &Arc, whitelist_manager: &Arc, ban_service: Arc>, @@ -30,12 +30,12 @@ pub fn add( let router = stats::routes::add( &v1_prefix, router, - tracker.clone(), + in_memory_torrent_repository.clone(), ban_service, stats_event_sender, stats_repository, ); let router = whitelist::routes::add(&v1_prefix, router, whitelist_manager); - torrent::routes::add(&v1_prefix, router, tracker) + torrent::routes::add(&v1_prefix, router, in_memory_torrent_repository.clone()) } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index fd2a37683..c88f6fdc9 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -486,6 +486,7 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::services::{initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::statistics::event::sender::Sender; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::whitelist::manager::WhiteListManager; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::core::{whitelist, Tracker}; @@ -493,6 +494,7 @@ mod tests { type TrackerAndDeps = ( Arc, + Arc, Arc>>, Arc, Arc, @@ -539,6 +541,7 @@ mod tests { ( tracker, + in_memory_torrent_repository, stats_event_sender, in_memory_whitelist, whitelist_manager, @@ -887,8 +890,14 @@ mod tests { #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { - let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = - public_tracker(); + let ( + tracker, + in_memory_torrent_repository, + stats_event_sender, + _in_memory_whitelist, + _whitelist_manager, + whitelist_authorization, + ) = public_tracker(); let client_ip = Ipv4Addr::new(126, 0, 0, 1); let client_port = 8080; @@ -916,7 +925,7 @@ mod tests { .await .unwrap(); - let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) @@ -928,8 +937,14 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { - let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = - public_tracker(); + let ( + tracker, + _in_memory_torrent_repository, + stats_event_sender, + _in_memory_whitelist, + _whitelist_manager, + whitelist_authorization, + ) = public_tracker(); let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); @@ -969,8 +984,14 @@ mod tests { // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): // "Do note that most trackers will only honor the IP address field under limited circumstances." - let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = - public_tracker(); + let ( + tracker, + in_memory_torrent_repository, + stats_event_sender, + _in_memory_whitelist, + _whitelist_manager, + whitelist_authorization, + ) = public_tracker(); let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -1001,7 +1022,7 @@ mod tests { .await .unwrap(); - let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); } @@ -1048,8 +1069,14 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { - let (tracker, _stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = - public_tracker(); + let ( + tracker, + _in_memory_torrent_repository, + _stats_event_sender, + _in_memory_whitelist, + _whitelist_manager, + whitelist_authorization, + ) = public_tracker(); add_a_torrent_peer_using_ipv6(&tracker); @@ -1104,8 +1131,14 @@ mod tests { #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { - let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = - public_tracker(); + let ( + tracker, + in_memory_torrent_repository, + stats_event_sender, + _in_memory_whitelist, + _whitelist_manager, + whitelist_authorization, + ) = public_tracker(); let client_ip = Ipv4Addr::new(127, 0, 0, 1); let client_port = 8080; @@ -1133,7 +1166,7 @@ mod tests { .await .unwrap(); - let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); let external_ip_in_tracker_configuration = tracker.get_maybe_external_ip().unwrap(); @@ -1170,8 +1203,14 @@ mod tests { #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { - let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = - public_tracker(); + let ( + tracker, + in_memory_torrent_repository, + stats_event_sender, + _in_memory_whitelist, + _whitelist_manager, + whitelist_authorization, + ) = public_tracker(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -1200,7 +1239,7 @@ mod tests { .await .unwrap(); - let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) @@ -1212,8 +1251,14 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { - let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = - public_tracker(); + let ( + tracker, + _in_memory_torrent_repository, + stats_event_sender, + _in_memory_whitelist, + _whitelist_manager, + whitelist_authorization, + ) = public_tracker(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -1256,8 +1301,14 @@ mod tests { // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): // "Do note that most trackers will only honor the IP address field under limited circumstances." - let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = - public_tracker(); + let ( + tracker, + in_memory_torrent_repository, + stats_event_sender, + _in_memory_whitelist, + _whitelist_manager, + whitelist_authorization, + ) = public_tracker(); let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -1288,7 +1339,7 @@ mod tests { .await .unwrap(); - let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); // When using IPv6 the tracker converts the remote client ip into a IPv4 address assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); @@ -1338,8 +1389,14 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { - let (tracker, _stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization) = - public_tracker(); + let ( + tracker, + _in_memory_torrent_repository, + _stats_event_sender, + _in_memory_whitelist, + _whitelist_manager, + whitelist_authorization, + ) = public_tracker(); add_a_torrent_peer_using_ipv4(&tracker); @@ -1466,7 +1523,7 @@ mod tests { .await .unwrap(); - let peers = tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); let external_ip_in_tracker_configuration = tracker.get_maybe_external_ip().unwrap(); @@ -1511,8 +1568,14 @@ mod tests { #[tokio::test] async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { - let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, _whitelist_authorization) = - public_tracker(); + let ( + tracker, + _in_memory_torrent_repository, + stats_event_sender, + _in_memory_whitelist, + _whitelist_manager, + _whitelist_authorization, + ) = public_tracker(); let remote_addr = sample_ipv4_remote_addr(); @@ -1605,8 +1668,14 @@ mod tests { #[tokio::test] async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { - let (tracker, _stats_event_sender, _in_memory_whitelist, _whitelist_manager, _whitelist_authorization) = - public_tracker(); + let ( + tracker, + _in_memory_torrent_repository, + _stats_event_sender, + _in_memory_whitelist, + _whitelist_manager, + _whitelist_authorization, + ) = public_tracker(); let torrent_stats = match_scrape_response(add_a_sample_seeder_and_scrape(tracker.clone()).await); @@ -1631,8 +1700,14 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { - let (tracker, stats_event_sender, in_memory_whitelist, _whitelist_manager, _whitelist_authorization) = - whitelisted_tracker(); + let ( + tracker, + _in_memory_torrent_repository, + stats_event_sender, + in_memory_whitelist, + _whitelist_manager, + _whitelist_authorization, + ) = whitelisted_tracker(); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -1667,8 +1742,14 @@ mod tests { #[tokio::test] async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { - let (tracker, stats_event_sender, _in_memory_whitelist, _whitelist_manager, _whitelist_authorization) = - whitelisted_tracker(); + let ( + tracker, + _in_memory_torrent_repository, + stats_event_sender, + _in_memory_whitelist, + _whitelist_manager, + _whitelist_authorization, + ) = whitelisted_tracker(); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 8967ff830..70f071bf4 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -13,6 +13,7 @@ use torrust_tracker_lib::core::authentication::service::AuthenticationService; use torrust_tracker_lib::core::databases::Database; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; +use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; @@ -27,6 +28,7 @@ where pub config: Arc, pub database: Arc>, pub tracker: Arc, + pub in_memory_torrent_repository: Arc, pub keys_handler: Arc, pub authentication_service: Arc, pub stats_event_sender: Arc>>, @@ -65,6 +67,7 @@ impl Environment { config, database: app_container.database.clone(), tracker: app_container.tracker.clone(), + in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), keys_handler: app_container.keys_handler.clone(), authentication_service: app_container.authentication_service.clone(), stats_event_sender: app_container.stats_event_sender.clone(), @@ -83,6 +86,7 @@ impl Environment { config: self.config, database: self.database.clone(), tracker: self.tracker.clone(), + in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), keys_handler: self.keys_handler.clone(), authentication_service: self.authentication_service.clone(), stats_event_sender: self.stats_event_sender.clone(), @@ -93,7 +97,7 @@ impl Environment { server: self .server .start( - self.tracker, + self.in_memory_torrent_repository, self.keys_handler, self.whitelist_manager, self.stats_event_sender, @@ -118,6 +122,7 @@ impl Environment { config: self.config, database: self.database, tracker: self.tracker, + in_memory_torrent_repository: self.in_memory_torrent_repository, keys_handler: self.keys_handler, authentication_service: self.authentication_service, stats_event_sender: self.stats_event_sender, diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 80c042a21..c0de4efbe 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -10,6 +10,7 @@ use torrust_tracker_lib::core::authentication::service::AuthenticationService; use torrust_tracker_lib::core::databases::Database; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; +use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; use torrust_tracker_lib::core::{whitelist, Tracker}; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; @@ -20,6 +21,7 @@ pub struct Environment { pub config: Arc, pub database: Arc>, pub tracker: Arc, + pub in_memory_torrent_repository: Arc, pub keys_handler: Arc, pub authentication_service: Arc, pub stats_event_sender: Arc>>, @@ -61,6 +63,7 @@ impl Environment { config, database: app_container.database.clone(), tracker: app_container.tracker.clone(), + in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), keys_handler: app_container.keys_handler.clone(), authentication_service: app_container.authentication_service.clone(), stats_event_sender: app_container.stats_event_sender.clone(), @@ -78,6 +81,7 @@ impl Environment { config: self.config, database: self.database.clone(), tracker: self.tracker.clone(), + in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), keys_handler: self.keys_handler.clone(), authentication_service: self.authentication_service.clone(), whitelist_authorization: self.whitelist_authorization.clone(), @@ -110,6 +114,7 @@ impl Environment { config: self.config, database: self.database, tracker: self.tracker, + in_memory_torrent_repository: self.in_memory_torrent_repository, keys_handler: self.keys_handler, authentication_service: self.authentication_service, whitelist_authorization: self.whitelist_authorization, diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 31aae9b50..8a65d941a 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -831,7 +831,7 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash); + let peers = env.in_memory_torrent_repository.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), client_ip); @@ -869,7 +869,7 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash); + let peers = env.in_memory_torrent_repository.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), env.tracker.get_maybe_external_ip().unwrap()); @@ -911,7 +911,7 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash); + let peers = env.in_memory_torrent_repository.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), env.tracker.get_maybe_external_ip().unwrap()); @@ -951,7 +951,7 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.tracker.in_memory_torrent_repository.get_torrent_peers(&info_hash); + let peers = env.in_memory_torrent_repository.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), IpAddr::from_str("150.172.238.178").unwrap()); From 3867bbbca3917a8e8d28a1f8e10681e0ba4a7497 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 27 Jan 2025 10:58:15 +0000 Subject: [PATCH 0651/1297] refactor: [#1205] extract ScrapeHandler --- src/app.rs | 2 + src/bootstrap/app.rs | 5 +- src/bootstrap/jobs/http_tracker.rs | 21 ++- src/bootstrap/jobs/udp_tracker.rs | 13 +- src/container.rs | 2 + src/core/mod.rs | 145 ++++++------------ src/core/scrape_handler.rs | 108 +++++++++++++ src/core/services/mod.rs | 9 +- src/core/services/statistics/mod.rs | 3 +- src/core/services/torrent.rs | 3 +- src/servers/http/server.rs | 8 + src/servers/http/v1/handlers/announce.rs | 1 - src/servers/http/v1/handlers/scrape.rs | 183 ++++++++++++++--------- src/servers/http/v1/routes.rs | 5 + src/servers/http/v1/services/announce.rs | 19 +-- src/servers/http/v1/services/scrape.rs | 59 ++++---- src/servers/udp/handlers.rs | 87 ++++++----- src/servers/udp/server/launcher.rs | 15 +- src/servers/udp/server/mod.rs | 2 + src/servers/udp/server/processor.rs | 5 + src/servers/udp/server/spawner.rs | 3 + src/servers/udp/server/states.rs | 7 +- tests/servers/http/environment.rs | 6 + tests/servers/udp/environment.rs | 6 + 24 files changed, 442 insertions(+), 275 deletions(-) create mode 100644 src/core/scrape_handler.rs diff --git a/src/app.rs b/src/app.rs index 67a319549..3f0e8d399 100644 --- a/src/app.rs +++ b/src/app.rs @@ -80,6 +80,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< udp_tracker::start_job( udp_tracker_config, app_container.tracker.clone(), + app_container.scrape_handler.clone(), app_container.whitelist_authorization.clone(), app_container.stats_event_sender.clone(), app_container.ban_service.clone(), @@ -99,6 +100,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< if let Some(job) = http_tracker::start_job( http_tracker_config, app_container.tracker.clone(), + app_container.scrape_handler.clone(), app_container.authentication_service.clone(), app_container.whitelist_authorization.clone(), app_container.stats_event_sender.clone(), diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 294b2ca73..a0b6df3ca 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -26,6 +26,7 @@ use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::authentication::service; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -116,14 +117,16 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let tracker = Arc::new(initialize_tracker( configuration, - &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + AppContainer { database, tracker, + scrape_handler, keys_handler, authentication_service, whitelist_authorization, diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 92a255c9e..2e76e2f31 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -20,6 +20,7 @@ use tracing::instrument; use super::make_rust_tls; use crate::core::authentication::service::AuthenticationService; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::{self, statistics, whitelist}; use crate::servers::http::server::{HttpServer, Launcher}; @@ -34,11 +35,20 @@ use crate::servers::registar::ServiceRegistrationForm; /// # Panics /// /// It would panic if the `config::HttpTracker` struct would contain inappropriate values. -/// -#[instrument(skip(config, tracker, authentication_service, whitelist_authorization, stats_event_sender, form))] +#[allow(clippy::too_many_arguments)] +#[instrument(skip( + config, + tracker, + scrape_handler, + authentication_service, + whitelist_authorization, + stats_event_sender, + form +))] pub async fn start_job( config: &HttpTracker, tracker: Arc, + scrape_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, stats_event_sender: Arc>>, @@ -57,6 +67,7 @@ pub async fn start_job( socket, tls, tracker.clone(), + scrape_handler.clone(), authentication_service.clone(), whitelist_authorization.clone(), stats_event_sender.clone(), @@ -67,12 +78,14 @@ pub async fn start_job( } } +#[allow(clippy::too_many_arguments)] #[allow(clippy::async_yields_async)] -#[instrument(skip(socket, tls, tracker, whitelist_authorization, stats_event_sender, form))] +#[instrument(skip(socket, tls, tracker, scrape_handler, whitelist_authorization, stats_event_sender, form))] async fn start_v1( socket: SocketAddr, tls: Option, tracker: Arc, + scrape_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, stats_event_sender: Arc>>, @@ -81,6 +94,7 @@ async fn start_v1( let server = HttpServer::new(Launcher::new(socket, tls)) .start( tracker, + scrape_handler, authentication_service, whitelist_authorization, stats_event_sender, @@ -128,6 +142,7 @@ mod tests { start_job( config, app_container.tracker, + app_container.scrape_handler, app_container.authentication_service, app_container.whitelist_authorization, app_container.stats_event_sender, diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 724e2043e..dd55e4b8b 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -13,6 +13,7 @@ use tokio::task::JoinHandle; use torrust_tracker_configuration::UdpTracker; use tracing::instrument; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::{self, whitelist}; use crate::servers::registar::ServiceRegistrationForm; @@ -32,10 +33,19 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// It will panic if the task did not finish successfully. #[must_use] #[allow(clippy::async_yields_async)] -#[instrument(skip(config, tracker, whitelist_authorization, stats_event_sender, ban_service, form))] +#[instrument(skip( + config, + tracker, + scrape_handler, + whitelist_authorization, + stats_event_sender, + ban_service, + form +))] pub async fn start_job( config: &UdpTracker, tracker: Arc, + scrape_handler: Arc, whitelist_authorization: Arc, stats_event_sender: Arc>>, ban_service: Arc>, @@ -47,6 +57,7 @@ pub async fn start_job( let server = Server::new(Spawner::new(bind_to)) .start( tracker, + scrape_handler, whitelist_authorization, stats_event_sender, ban_service, diff --git a/src/container.rs b/src/container.rs index 8407d0b69..a73862006 100644 --- a/src/container.rs +++ b/src/container.rs @@ -5,6 +5,7 @@ use tokio::sync::RwLock; use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::service::AuthenticationService; use crate::core::databases::Database; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; use crate::core::torrent::manager::TorrentsManager; @@ -17,6 +18,7 @@ use crate::servers::udp::server::banning::BanService; pub struct AppContainer { pub database: Arc>, pub tracker: Arc, + pub scrape_handler: Arc, pub keys_handler: Arc, pub authentication_service: Arc, pub whitelist_authorization: Arc, diff --git a/src/core/mod.rs b/src/core/mod.rs index 6ad48289f..064e8eb3e 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -442,6 +442,7 @@ pub mod authentication; pub mod databases; pub mod error; +pub mod scrape_handler; pub mod services; pub mod statistics; pub mod torrent; @@ -456,7 +457,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrent::repository::in_memory::InMemoryTorrentRepository; use torrent::repository::persisted::DatabasePersistentTorrentRepository; use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; -use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; +use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; @@ -473,9 +474,6 @@ pub struct Tracker { /// The tracker configuration. config: Core, - /// The service to check is a torrent is whitelisted. - whitelist_authorization: Arc, - /// The in-memory torrents repository. in_memory_torrent_repository: Arc, @@ -533,13 +531,11 @@ impl Tracker { /// Will return a `databases::error::Error` if unable to connect to database. The `Tracker` is responsible for the persistence. pub fn new( config: &Core, - whitelist_authorization: &Arc, in_memory_torrent_repository: &Arc, db_torrent_repository: &Arc, ) -> Result { Ok(Tracker { config: config.clone(), - whitelist_authorization: whitelist_authorization.clone(), in_memory_torrent_repository: in_memory_torrent_repository.clone(), db_torrent_repository: db_torrent_repository.clone(), }) @@ -629,25 +625,6 @@ impl Tracker { } } - /// It handles a scrape request. - /// - /// # Context: Tracker - /// - /// BEP 48: [Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). - pub async fn scrape(&self, info_hashes: &Vec) -> ScrapeData { - let mut scrape_data = ScrapeData::empty(); - - for info_hash in info_hashes { - let swarm_metadata = match self.whitelist_authorization.authorize(info_hash).await { - Ok(()) => self.in_memory_torrent_repository.get_swarm_metadata(info_hash), - Err(_) => SwarmMetadata::zeroed(), - }; - scrape_data.add_file(info_hash, swarm_metadata); - } - - scrape_data - } - /// It updates the torrent entry in memory, it also stores in the database /// the torrent info data which is persistent, and finally return the data /// needed for a `announce` request response. @@ -715,13 +692,14 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::peer::Peer; + use crate::core::scrape_handler::ScrapeHandler; use crate::core::services::{initialize_tracker, initialize_whitelist_manager}; use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::whitelist::manager::WhiteListManager; use crate::core::{whitelist, Tracker}; - fn public_tracker() -> Tracker { + fn public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); let ( @@ -734,12 +712,15 @@ mod tests { _torrents_manager, ) = initialize_tracker_dependencies(&config); - initialize_tracker( + let tracker = Arc::new(initialize_tracker( &config, - &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - ) + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (tracker, scrape_handler) } fn public_tracker_and_in_memory_torrents_repository() -> (Arc, Arc) { @@ -748,7 +729,7 @@ mod tests { let ( _database, _in_memory_whitelist, - whitelist_authorization, + _whitelist_authorization, _authentication_service, in_memory_torrent_repository, db_torrent_repository, @@ -757,7 +738,6 @@ mod tests { let tracker = Arc::new(initialize_tracker( &config, - &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); @@ -765,7 +745,12 @@ mod tests { (tracker, in_memory_torrent_repository) } - fn whitelisted_tracker() -> (Tracker, Arc, Arc) { + fn whitelisted_tracker() -> ( + Tracker, + Arc, + Arc, + Arc, + ) { let config = configuration::ephemeral_listed(); let ( @@ -780,14 +765,11 @@ mod tests { let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = initialize_tracker( - &config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - ); + let tracker = initialize_tracker(&config, &in_memory_torrent_repository, &db_torrent_repository); - (tracker, whitelist_authorization, whitelist_manager) + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (tracker, whitelist_authorization, whitelist_manager, scrape_handler) } pub fn tracker_persisting_torrents_in_database() -> (Tracker, Arc, Arc) { @@ -797,19 +779,14 @@ mod tests { let ( _database, _in_memory_whitelist, - whitelist_authorization, + _whitelist_authorization, _authentication_service, in_memory_torrent_repository, db_torrent_repository, torrents_manager, ) = initialize_tracker_dependencies(&config); - let tracker = initialize_tracker( - &config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - ); + let tracker = initialize_tracker(&config, &in_memory_torrent_repository, &db_torrent_repository); (tracker, torrents_manager, in_memory_torrent_repository) } @@ -957,7 +934,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let tracker = public_tracker(); + let (tracker, _scrape_handler) = public_tracker(); let info_hash = sample_info_hash(); let peer = sample_peer(); @@ -973,7 +950,7 @@ mod tests { #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { - let tracker = public_tracker(); + let (tracker, _scrape_handler) = public_tracker(); let info_hash = sample_info_hash(); @@ -1159,7 +1136,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_announce_data_with_an_empty_peer_list_when_it_is_the_first_announced_peer() { - let tracker = public_tracker(); + let (tracker, _scrape_handler) = public_tracker(); let mut peer = sample_peer(); @@ -1170,7 +1147,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_announce_data_with_the_previously_announced_peers() { - let tracker = public_tracker(); + let (tracker, _scrape_handler) = public_tracker(); let mut previously_announced_peer = sample_peer_1(); tracker.announce( @@ -1195,7 +1172,7 @@ mod tests { #[tokio::test] async fn when_the_peer_is_a_seeder() { - let tracker = public_tracker(); + let (tracker, _scrape_handler) = public_tracker(); let mut peer = seeder(); @@ -1206,7 +1183,7 @@ mod tests { #[tokio::test] async fn when_the_peer_is_a_leecher() { - let tracker = public_tracker(); + let (tracker, _scrape_handler) = public_tracker(); let mut peer = leecher(); @@ -1217,7 +1194,7 @@ mod tests { #[tokio::test] async fn when_a_previously_announced_started_peer_has_completed_downloading() { - let tracker = public_tracker(); + let (tracker, _scrape_handler) = public_tracker(); // We have to announce with "started" event because peer does not count if peer was not previously known let mut started_peer = started_peer(); @@ -1237,31 +1214,16 @@ mod tests { use std::net::{IpAddr, Ipv4Addr}; use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::core::ScrapeData; use crate::core::tests::the_tracker::{complete_peer, incomplete_peer, public_tracker}; - use crate::core::{PeersWanted, ScrapeData, SwarmMetadata}; - - #[tokio::test] - async fn it_should_return_a_zeroed_swarm_metadata_for_the_requested_file_if_the_tracker_does_not_have_that_torrent( - ) { - let tracker = public_tracker(); - - let info_hashes = vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()]; - - let scrape_data = tracker.scrape(&info_hashes).await; - - let mut expected_scrape_data = ScrapeData::empty(); - - expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[0]); - - assert_eq!(scrape_data, expected_scrape_data); - } + use crate::core::{PeersWanted, SwarmMetadata}; #[tokio::test] async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() { - let tracker = public_tracker(); + let (tracker, scrape_handler) = public_tracker(); - let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); + let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // # DevSkim: ignore DS173237 // Announce a "complete" peer for the torrent let mut complete_peer = complete_peer(); @@ -1282,7 +1244,7 @@ mod tests { ); // Scrape - let scrape_data = tracker.scrape(&vec![info_hash]).await; + let scrape_data = scrape_handler.scrape(&vec![info_hash]).await; // The expected swarm metadata for the file let mut expected_scrape_data = ScrapeData::empty(); @@ -1297,24 +1259,6 @@ mod tests { assert_eq!(scrape_data, expected_scrape_data); } - - #[tokio::test] - async fn it_should_allow_scraping_for_multiple_torrents() { - let tracker = public_tracker(); - - let info_hashes = vec![ - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), - "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1".parse::().unwrap(), - ]; - - let scrape_data = tracker.scrape(&info_hashes).await; - - let mut expected_scrape_data = ScrapeData::empty(); - expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[0]); - expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[1]); - - assert_eq!(scrape_data, expected_scrape_data); - } } } @@ -1325,7 +1269,7 @@ mod tests { #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { - let (_tracker, whitelist_authorization, whitelist_manager) = whitelisted_tracker(); + let (_tracker, whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1338,7 +1282,7 @@ mod tests { #[tokio::test] async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { - let (_tracker, whitelist_authorization, _whitelist_manager) = whitelisted_tracker(); + let (_tracker, whitelist_authorization, _whitelist_manager, _scrape_handler) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1357,7 +1301,7 @@ mod tests { #[tokio::test] async fn it_should_add_a_torrent_to_the_whitelist() { - let (_tracker, _whitelist_authorization, whitelist_manager) = whitelisted_tracker(); + let (_tracker, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1368,7 +1312,7 @@ mod tests { #[tokio::test] async fn it_should_remove_a_torrent_from_the_whitelist() { - let (_tracker, _whitelist_authorization, whitelist_manager) = whitelisted_tracker(); + let (_tracker, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1384,7 +1328,7 @@ mod tests { #[tokio::test] async fn it_should_load_the_whitelist_from_the_database() { - let (_tracker, _whitelist_authorization, whitelist_manager) = whitelisted_tracker(); + let (_tracker, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1406,12 +1350,13 @@ mod tests { mod handling_an_scrape_request { use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::core::tests::the_tracker::{ complete_peer, incomplete_peer, peer_ip, sample_info_hash, whitelisted_tracker, }; - use crate::core::{PeersWanted, ScrapeData}; + use crate::core::PeersWanted; #[test] fn it_should_be_able_to_build_a_zeroed_scrape_data_for_a_list_of_info_hashes() { @@ -1427,9 +1372,9 @@ mod tests { #[tokio::test] async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { - let (tracker, _whitelist_authorization, _whitelist_manager) = whitelisted_tracker(); + let (tracker, _whitelist_authorization, _whitelist_manager, scrape_handler) = whitelisted_tracker(); - let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); + let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // # DevSkim: ignore DS173237 let mut peer = incomplete_peer(); tracker.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); @@ -1438,7 +1383,7 @@ mod tests { let mut peer = complete_peer(); tracker.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); - let scrape_data = tracker.scrape(&vec![info_hash]).await; + let scrape_data = scrape_handler.scrape(&vec![info_hash]).await; // The expected zeroed swarm metadata for the file let mut expected_scrape_data = ScrapeData::empty(); diff --git a/src/core/scrape_handler.rs b/src/core/scrape_handler.rs new file mode 100644 index 000000000..47049ed71 --- /dev/null +++ b/src/core/scrape_handler.rs @@ -0,0 +1,108 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::core::ScrapeData; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + +use super::torrent::repository::in_memory::InMemoryTorrentRepository; +use super::whitelist; + +pub struct ScrapeHandler { + /// The service to check is a torrent is whitelisted. + whitelist_authorization: Arc, + + /// The in-memory torrents repository. + in_memory_torrent_repository: Arc, +} + +impl ScrapeHandler { + #[must_use] + pub fn new( + whitelist_authorization: &Arc, + in_memory_torrent_repository: &Arc, + ) -> Self { + Self { + whitelist_authorization: whitelist_authorization.clone(), + in_memory_torrent_repository: in_memory_torrent_repository.clone(), + } + } + + /// It handles a scrape request. + /// + /// # Context: Tracker + /// + /// BEP 48: [Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). + pub async fn scrape(&self, info_hashes: &Vec) -> ScrapeData { + let mut scrape_data = ScrapeData::empty(); + + for info_hash in info_hashes { + let swarm_metadata = match self.whitelist_authorization.authorize(info_hash).await { + Ok(()) => self.in_memory_torrent_repository.get_swarm_metadata(info_hash), + Err(_) => SwarmMetadata::zeroed(), + }; + scrape_data.add_file(info_hash, swarm_metadata); + } + + scrape_data + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_test_helpers::configuration; + + use super::ScrapeHandler; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::core::whitelist::{self}; + + fn scrape_handler() -> ScrapeHandler { + let config = configuration::ephemeral_public(); + + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + &config.core, + &in_memory_whitelist.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository) + } + + #[tokio::test] + async fn it_should_return_a_zeroed_swarm_metadata_for_the_requested_file_if_the_tracker_does_not_have_that_torrent() { + let scrape_handler = scrape_handler(); + + let info_hashes = vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()]; // # DevSkim: ignore DS173237 + + let scrape_data = scrape_handler.scrape(&info_hashes).await; + + let mut expected_scrape_data = ScrapeData::empty(); + + expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[0]); + + assert_eq!(scrape_data, expected_scrape_data); + } + + #[tokio::test] + async fn it_should_allow_scraping_for_multiple_torrents() { + let scrape_handler = scrape_handler(); + + let info_hashes = vec![ + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), // # DevSkim: ignore DS173237 + "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1".parse::().unwrap(), // # DevSkim: ignore DS173237 + ]; + + let scrape_data = scrape_handler.scrape(&info_hashes).await; + + let mut expected_scrape_data = ScrapeData::empty(); + expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[0]); + expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[1]); + + assert_eq!(scrape_data, expected_scrape_data); + } +} diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index a9bca2df7..a6cf54d60 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -16,7 +16,6 @@ use torrust_tracker_configuration::Configuration; use super::databases::{self, Database}; use super::torrent::repository::in_memory::InMemoryTorrentRepository; use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; -use super::whitelist; use super::whitelist::manager::WhiteListManager; use super::whitelist::repository::in_memory::InMemoryWhitelist; use super::whitelist::repository::persisted::DatabaseWhitelist; @@ -30,16 +29,10 @@ use crate::core::Tracker; #[must_use] pub fn initialize_tracker( config: &Configuration, - whitelist_authorization: &Arc, in_memory_torrent_repository: &Arc, db_torrent_repository: &Arc, ) -> Tracker { - match Tracker::new( - &Arc::new(config).core, - whitelist_authorization, - in_memory_torrent_repository, - db_torrent_repository, - ) { + match Tracker::new(&Arc::new(config).core, in_memory_torrent_repository, db_torrent_repository) { Ok(tracker) => tracker, Err(error) => { panic!("{}", error) diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index ea7ebe994..680504607 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -135,7 +135,7 @@ mod tests { let ( _database, _in_memory_whitelist, - whitelist_authorization, + _whitelist_authorization, _authentication_service, in_memory_torrent_repository, db_torrent_repository, @@ -147,7 +147,6 @@ mod tests { let _tracker = Arc::new(initialize_tracker( &config, - &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index dae619d62..8677096cc 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -127,7 +127,7 @@ mod tests { let ( _database, _in_memory_whitelist, - whitelist_authorization, + _whitelist_authorization, _authentication_service, in_memory_torrent_repository, db_torrent_repository, @@ -136,7 +136,6 @@ mod tests { let tracker = Arc::new(initialize_tracker( config, - &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index e7a3a92ec..573337ba9 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -12,6 +12,7 @@ use tracing::instrument; use super::v1::routes::router; use crate::bootstrap::jobs::Started; use crate::core::authentication::service::AuthenticationService; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::{statistics, whitelist, Tracker}; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; @@ -43,9 +44,11 @@ pub struct Launcher { } impl Launcher { + #[allow(clippy::too_many_arguments)] #[instrument(skip( self, tracker, + scrape_handler, authentication_service, whitelist_authorization, stats_event_sender, @@ -55,6 +58,7 @@ impl Launcher { fn start( &self, tracker: Arc, + scrape_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, stats_event_sender: Arc>>, @@ -79,6 +83,7 @@ impl Launcher { let app = router( tracker, + scrape_handler, authentication_service, whitelist_authorization, stats_event_sender, @@ -179,6 +184,7 @@ impl HttpServer { pub async fn start( self, tracker: Arc, + scrape_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, stats_event_sender: Arc>>, @@ -192,6 +198,7 @@ impl HttpServer { let task = tokio::spawn(async move { let server = launcher.start( tracker, + scrape_handler, authentication_service, whitelist_authorization, stats_event_sender, @@ -296,6 +303,7 @@ mod tests { let started = stopped .start( app_container.tracker, + app_container.scrape_handler, app_container.authentication_service, app_container.whitelist_authorization, app_container.stats_event_sender, diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index a9567fb81..8b57ce543 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -289,7 +289,6 @@ mod tests { let tracker = Arc::new(initialize_tracker( config, - &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 116d717a1..3c19fe324 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -17,6 +17,7 @@ use torrust_tracker_primitives::core::ScrapeData; use crate::core::authentication::service::AuthenticationService; use crate::core::authentication::Key; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; @@ -29,13 +30,27 @@ use crate::servers::http::v1::services; #[allow(clippy::unused_async)] #[allow(clippy::type_complexity)] pub async fn handle_without_key( - State(state): State<(Arc, Arc, Arc>>)>, + State(state): State<( + Arc, + Arc, + Arc, + Arc>>, + )>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { tracing::debug!("http scrape request: {:#?}", &scrape_request); - handle(&state.0, &state.1, &state.2, &scrape_request, &client_ip_sources, None).await + handle( + &state.0, + &state.1, + &state.2, + &state.3, + &scrape_request, + &client_ip_sources, + None, + ) + .await } /// It handles the `scrape` request when the HTTP tracker is configured @@ -45,18 +60,33 @@ pub async fn handle_without_key( #[allow(clippy::unused_async)] #[allow(clippy::type_complexity)] pub async fn handle_with_key( - State(state): State<(Arc, Arc, Arc>>)>, + State(state): State<( + Arc, + Arc, + Arc, + Arc>>, + )>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { tracing::debug!("http scrape request: {:#?}", &scrape_request); - handle(&state.0, &state.1, &state.2, &scrape_request, &client_ip_sources, Some(key)).await + handle( + &state.0, + &state.1, + &state.2, + &state.3, + &scrape_request, + &client_ip_sources, + Some(key), + ) + .await } async fn handle( tracker: &Arc, + scrape_handler: &Arc, authentication_service: &Arc, stats_event_sender: &Arc>>, scrape_request: &Scrape, @@ -65,6 +95,7 @@ async fn handle( ) -> Response { let scrape_data = match handle_scrape( tracker, + scrape_handler, authentication_service, stats_event_sender, scrape_request, @@ -87,6 +118,7 @@ async fn handle( async fn handle_scrape( tracker: &Arc, + scrape_handler: &Arc, authentication_service: &Arc, opt_stats_event_sender: &Arc>>, scrape_request: &Scrape, @@ -115,7 +147,7 @@ async fn handle_scrape( }; if return_real_scrape_data { - Ok(services::scrape::invoke(tracker, opt_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await) + Ok(services::scrape::invoke(scrape_handler, opt_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await) } else { Ok(services::scrape::fake(opt_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await) } @@ -141,12 +173,15 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::authentication::service::AuthenticationService; + use crate::core::scrape_handler::ScrapeHandler; use crate::core::services::{initialize_tracker, statistics}; use crate::core::Tracker; + #[allow(clippy::type_complexity)] fn private_tracker() -> ( - Tracker, - Option>, + Arc, + Arc, + Arc>>, Arc, ) { let config = configuration::ephemeral_private(); @@ -163,21 +198,24 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - ( - initialize_tracker( - &config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - ), - stats_event_sender, - authentication_service, - ) + let stats_event_sender = Arc::new(stats_event_sender); + + let tracker = Arc::new(initialize_tracker( + &config, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (tracker, scrape_handler, stats_event_sender, authentication_service) } + #[allow(clippy::type_complexity)] fn whitelisted_tracker() -> ( - Tracker, - Option>, + Arc, + Arc, + Arc>>, Arc, ) { let config = configuration::ephemeral_listed(); @@ -194,21 +232,24 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - ( - initialize_tracker( - &config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - ), - stats_event_sender, - authentication_service, - ) + let stats_event_sender = Arc::new(stats_event_sender); + + let tracker = Arc::new(initialize_tracker( + &config, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (tracker, scrape_handler, stats_event_sender, authentication_service) } + #[allow(clippy::type_complexity)] fn tracker_on_reverse_proxy() -> ( - Tracker, - Option>, + Arc, + Arc, + Arc>>, Arc, ) { let config = configuration::ephemeral_with_reverse_proxy(); @@ -225,21 +266,24 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - ( - initialize_tracker( - &config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - ), - stats_event_sender, - authentication_service, - ) + let stats_event_sender = Arc::new(stats_event_sender); + + let tracker = Arc::new(initialize_tracker( + &config, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (tracker, scrape_handler, stats_event_sender, authentication_service) } + #[allow(clippy::type_complexity)] fn tracker_not_on_reverse_proxy() -> ( - Tracker, - Option>, + Arc, + Arc, + Arc>>, Arc, ) { let config = configuration::ephemeral_without_reverse_proxy(); @@ -256,21 +300,22 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - ( - initialize_tracker( - &config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - ), - stats_event_sender, - authentication_service, - ) + let stats_event_sender = Arc::new(stats_event_sender); + + let tracker = Arc::new(initialize_tracker( + &config, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (tracker, scrape_handler, stats_event_sender, authentication_service) } fn sample_scrape_request() -> Scrape { Scrape { - info_hashes: vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()], + info_hashes: vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()], // # DevSkim: ignore DS173237 } } @@ -290,7 +335,6 @@ mod tests { mod with_tracker_in_private_mode { use std::str::FromStr; - use std::sync::Arc; use torrust_tracker_primitives::core::ScrapeData; @@ -300,15 +344,14 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { - let (tracker, stats_event_sender, authentication_service) = private_tracker(); - let tracker = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, scrape_handler, stats_event_sender, authentication_service) = private_tracker(); let scrape_request = sample_scrape_request(); let maybe_key = None; let scrape_data = handle_scrape( &tracker, + &scrape_handler, &authentication_service, &stats_event_sender, &scrape_request, @@ -325,9 +368,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() { - let (tracker, stats_event_sender, authentication_service) = private_tracker(); - let tracker = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, scrape_handler, stats_event_sender, authentication_service) = private_tracker(); let scrape_request = sample_scrape_request(); let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); @@ -335,6 +376,7 @@ mod tests { let scrape_data = handle_scrape( &tracker, + &scrape_handler, &authentication_service, &stats_event_sender, &scrape_request, @@ -352,8 +394,6 @@ mod tests { mod with_tracker_in_listed_mode { - use std::sync::Arc; - use torrust_tracker_primitives::core::ScrapeData; use super::{sample_client_ip_sources, sample_scrape_request, whitelisted_tracker}; @@ -361,14 +401,13 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() { - let (tracker, stats_event_sender, authentication_service) = whitelisted_tracker(); - let tracker: Arc = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, scrape_handler, stats_event_sender, authentication_service) = whitelisted_tracker(); let scrape_request = sample_scrape_request(); let scrape_data = handle_scrape( &tracker, + &scrape_handler, &authentication_service, &stats_event_sender, &scrape_request, @@ -385,7 +424,6 @@ mod tests { } mod with_tracker_on_reverse_proxy { - use std::sync::Arc; use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -395,9 +433,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let (tracker, stats_event_sender, authentication_service) = tracker_on_reverse_proxy(); - let tracker: Arc = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, scrape_handler, stats_event_sender, authentication_service) = tracker_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -406,6 +442,7 @@ mod tests { let response = handle_scrape( &tracker, + &scrape_handler, &authentication_service, &stats_event_sender, &sample_scrape_request(), @@ -423,7 +460,6 @@ mod tests { } mod with_tracker_not_on_reverse_proxy { - use std::sync::Arc; use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -433,9 +469,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let (tracker, stats_event_sender, authentication_service) = tracker_not_on_reverse_proxy(); - let tracker: Arc = Arc::new(tracker); - let stats_event_sender = Arc::new(stats_event_sender); + let (tracker, scrape_handler, stats_event_sender, authentication_service) = tracker_not_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -444,6 +478,7 @@ mod tests { let response = handle_scrape( &tracker, + &scrape_handler, &authentication_service, &stats_event_sender, &sample_scrape_request(), diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 7a1465500..0c0be5bd5 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -23,6 +23,7 @@ use tracing::{instrument, Level, Span}; use super::handlers::{announce, health_check, scrape}; use crate::core::authentication::service::AuthenticationService; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::{whitelist, Tracker}; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; @@ -35,6 +36,7 @@ use crate::servers::logging::Latency; #[allow(clippy::needless_pass_by_value)] #[instrument(skip( tracker, + scrape_handler, authentication_service, whitelist_authorization, stats_event_sender, @@ -42,6 +44,7 @@ use crate::servers::logging::Latency; ))] pub fn router( tracker: Arc, + scrape_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, stats_event_sender: Arc>>, @@ -74,6 +77,7 @@ pub fn router( "/scrape", get(scrape::handle_without_key).with_state(( tracker.clone(), + scrape_handler.clone(), authentication_service.clone(), stats_event_sender.clone(), )), @@ -82,6 +86,7 @@ pub fn router( "/scrape/{key}", get(scrape::handle_with_key).with_state(( tracker.clone(), + scrape_handler.clone(), authentication_service.clone(), stats_event_sender.clone(), )), diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 322bc80eb..9e381d8b2 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -76,7 +76,7 @@ mod tests { let ( _database, _in_memory_whitelist, - whitelist_authorization, + _whitelist_authorization, _authentication_service, in_memory_torrent_repository, db_torrent_repository, @@ -85,12 +85,7 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = initialize_tracker( - &config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - ); + let tracker = initialize_tracker(&config, &in_memory_torrent_repository, &db_torrent_repository); (tracker, stats_event_sender) } @@ -147,20 +142,14 @@ mod tests { let ( _database, _in_memory_whitelist, - whitelist_authorization, + _whitelist_authorization, _authentication_service, in_memory_torrent_repository, db_torrent_repository, _torrents_manager, ) = initialize_tracker_dependencies(&config); - Tracker::new( - &config.core, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - ) - .unwrap() + Tracker::new(&config.core, &in_memory_torrent_repository, &db_torrent_repository).unwrap() } #[tokio::test] diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 299938f84..e3ee6560f 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -2,9 +2,8 @@ //! //! The service is responsible for handling the `scrape` requests. //! -//! It delegates the `scrape` logic to the [`Tracker`](crate::core::Tracker::scrape) -//! and it returns the [`ScrapeData`] returned -//! by the [`Tracker`]. +//! It delegates the `scrape` logic to the [`ScrapeHandler`] and it returns the +//! [`ScrapeData`]. //! //! It also sends an [`statistics::event::Event`] //! because events are specific for the HTTP tracker. @@ -14,9 +13,9 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::core::ScrapeData; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::{self}; -use crate::core::Tracker; /// The HTTP tracker `scrape` service. /// @@ -29,12 +28,12 @@ use crate::core::Tracker; /// > like the UDP tracker, the number of TCP connections is incremented for /// > each `scrape` request. pub async fn invoke( - tracker: &Arc, + scrape_handler: &Arc, opt_stats_event_sender: &Arc>>, info_hashes: &Vec, original_peer_ip: &IpAddr, ) -> ScrapeData { - let scrape_data = tracker.scrape(info_hashes).await; + let scrape_data = scrape_handler.scrape(info_hashes).await; send_scrape_event(original_peer_ip, opt_stats_event_sender).await; @@ -74,6 +73,7 @@ async fn send_scrape_event(original_peer_ip: &IpAddr, opt_stats_event_sender: &A mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; @@ -81,10 +81,11 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; + use crate::core::scrape_handler::ScrapeHandler; use crate::core::services::initialize_tracker; use crate::core::Tracker; - fn public_tracker() -> Tracker { + fn public_tracker_and_scrape_handler() -> (Arc, Arc) { let config = configuration::ephemeral_public(); let ( @@ -97,12 +98,15 @@ mod tests { _torrents_manager, ) = initialize_tracker_dependencies(&config); - initialize_tracker( + let tracker = Arc::new(initialize_tracker( &config, - &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, - ) + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (tracker, scrape_handler) } fn sample_info_hashes() -> Vec { @@ -110,7 +114,7 @@ mod tests { } fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() // # DevSkim: ignore DS173237 } fn sample_peer() -> peer::Peer { @@ -125,7 +129,7 @@ mod tests { } } - fn test_tracker_factory() -> Tracker { + fn test_tracker_factory() -> (Arc, Arc) { let config = configuration::ephemeral(); let ( @@ -138,13 +142,11 @@ mod tests { _torrents_manager, ) = initialize_tracker_dependencies(&config); - Tracker::new( - &config.core, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - ) - .unwrap() + let tracker = Arc::new(Tracker::new(&config.core, &in_memory_torrent_repository, &db_torrent_repository).unwrap()); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (tracker, scrape_handler) } mod with_real_data { @@ -160,7 +162,7 @@ mod tests { use crate::core::{statistics, PeersWanted}; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ - public_tracker, sample_info_hash, sample_info_hashes, sample_peer, test_tracker_factory, + public_tracker_and_scrape_handler, sample_info_hash, sample_info_hashes, sample_peer, test_tracker_factory, }; #[tokio::test] @@ -168,7 +170,7 @@ mod tests { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = Arc::new(public_tracker()); + let (tracker, scrape_handler) = public_tracker_and_scrape_handler(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; @@ -178,7 +180,7 @@ mod tests { let original_peer_ip = peer.ip(); tracker.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); - let scrape_data = invoke(&tracker, &stats_event_sender, &info_hashes, &original_peer_ip).await; + let scrape_data = invoke(&scrape_handler, &stats_event_sender, &info_hashes, &original_peer_ip).await; let mut expected_scrape_data = ScrapeData::empty(); expected_scrape_data.add_file( @@ -204,11 +206,11 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(test_tracker_factory()); + let (_tracker, scrape_handler) = test_tracker_factory(); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); - invoke(&tracker, &stats_event_sender, &sample_info_hashes(), &peer_ip).await; + invoke(&scrape_handler, &stats_event_sender, &sample_info_hashes(), &peer_ip).await; } #[tokio::test] @@ -222,11 +224,11 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(test_tracker_factory()); + let (_tracker, scrape_handler) = test_tracker_factory(); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); - invoke(&tracker, &stats_event_sender, &sample_info_hashes(), &peer_ip).await; + invoke(&scrape_handler, &stats_event_sender, &sample_info_hashes(), &peer_ip).await; } } @@ -242,14 +244,15 @@ mod tests { use crate::core::{statistics, PeersWanted}; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ - public_tracker, sample_info_hash, sample_info_hashes, sample_peer, + public_tracker_and_scrape_handler, sample_info_hash, sample_info_hashes, sample_peer, }; #[tokio::test] async fn it_should_always_return_the_zeroed_scrape_data_for_a_torrent() { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = Arc::new(public_tracker()); + + let (tracker, _scrape_handler) = public_tracker_and_scrape_handler(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index c88f6fdc9..f8f57aea9 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -20,6 +20,7 @@ use zerocopy::network_endian::I32; use super::connection_cookie::{check, make}; use super::server::banning::BanService; use super::RawRequest; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::{statistics, whitelist, PeersWanted, Tracker}; use crate::servers::udp::error::Error; @@ -54,10 +55,12 @@ impl CookieTimeValues { /// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. -#[instrument(fields(request_id), skip(udp_request, tracker, whitelist_authorization, opt_stats_event_sender, cookie_time_values, ban_service), ret(level = Level::TRACE))] +#[allow(clippy::too_many_arguments)] +#[instrument(fields(request_id), skip(udp_request, tracker, scrape_handler, whitelist_authorization, opt_stats_event_sender, cookie_time_values, ban_service), ret(level = Level::TRACE))] pub(crate) async fn handle_packet( udp_request: RawRequest, tracker: &Tracker, + scrape_handler: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, local_addr: SocketAddr, @@ -77,6 +80,7 @@ pub(crate) async fn handle_packet( request, udp_request.from, tracker, + scrape_handler, whitelist_authorization, opt_stats_event_sender, cookie_time_values.clone(), @@ -137,6 +141,7 @@ pub(crate) async fn handle_packet( request, remote_addr, tracker, + scrape_handler, whitelist_authorization, opt_stats_event_sender, cookie_time_values @@ -145,6 +150,7 @@ pub async fn handle_request( request: Request, remote_addr: SocketAddr, tracker: &Tracker, + scrape_handler: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, cookie_time_values: CookieTimeValues, @@ -174,7 +180,7 @@ pub async fn handle_request( handle_scrape( remote_addr, &scrape_request, - tracker, + scrape_handler, opt_stats_event_sender, cookie_time_values.valid_range, ) @@ -338,11 +344,11 @@ pub async fn handle_announce( /// # Errors /// /// This function does not ever return an error. -#[instrument(fields(transaction_id, connection_id), skip(tracker, opt_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id), skip(scrape_handler, opt_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_scrape( remote_addr: SocketAddr, request: &ScrapeRequest, - tracker: &Tracker, + scrape_handler: &Arc, opt_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { @@ -365,7 +371,7 @@ pub async fn handle_scrape( info_hashes.push((*info_hash).into()); } - let scrape_data = tracker.scrape(&info_hashes).await; + let scrape_data = scrape_handler.scrape(&info_hashes).await; let mut torrent_stats: Vec = Vec::new(); @@ -484,6 +490,7 @@ mod tests { use super::gen_remote_fingerprint; use crate::app_test::initialize_tracker_dependencies; + use crate::core::scrape_handler::ScrapeHandler; use crate::core::services::{initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::statistics::event::sender::Sender; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -494,6 +501,7 @@ mod tests { type TrackerAndDeps = ( Arc, + Arc, Arc, Arc>>, Arc, @@ -534,13 +542,15 @@ mod tests { let tracker = Arc::new(initialize_tracker( config, - &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + ( tracker, + scrape_handler, in_memory_torrent_repository, stats_event_sender, in_memory_whitelist, @@ -643,7 +653,7 @@ mod tests { } } - fn test_tracker_factory() -> (Arc, Arc) { + fn test_tracker_factory() -> (Arc, Arc, Arc) { let config = tracker_configuration(); let ( @@ -656,17 +666,11 @@ mod tests { _torrents_manager, ) = initialize_tracker_dependencies(&config); - let tracker = Arc::new( - Tracker::new( - &config.core, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - ) - .unwrap(), - ); + let tracker = Arc::new(Tracker::new(&config.core, &in_memory_torrent_repository, &db_torrent_repository).unwrap()); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, whitelist_authorization) + (tracker, scrape_handler, whitelist_authorization) } mod connect_request { @@ -892,6 +896,7 @@ mod tests { async fn an_announced_peer_should_be_added_to_the_tracker() { let ( tracker, + _scrape_handler, in_memory_torrent_repository, stats_event_sender, _in_memory_whitelist, @@ -939,6 +944,7 @@ mod tests { async fn the_announced_peer_should_not_be_included_in_the_response() { let ( tracker, + _scrape_handler, _in_memory_torrent_repository, stats_event_sender, _in_memory_whitelist, @@ -986,6 +992,7 @@ mod tests { let ( tracker, + _scrape_handler, in_memory_torrent_repository, stats_event_sender, _in_memory_whitelist, @@ -1071,6 +1078,7 @@ mod tests { async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { let ( tracker, + _scrape_handler, _in_memory_torrent_repository, _stats_event_sender, _in_memory_whitelist, @@ -1102,7 +1110,7 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (tracker, whitelist_authorization) = test_tracker_factory(); + let (tracker, _scrape_handler, whitelist_authorization) = test_tracker_factory(); handle_announce( sample_ipv4_socket_address(), @@ -1133,6 +1141,7 @@ mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { let ( tracker, + _scrape_handler, in_memory_torrent_repository, stats_event_sender, _in_memory_whitelist, @@ -1205,6 +1214,7 @@ mod tests { async fn an_announced_peer_should_be_added_to_the_tracker() { let ( tracker, + _scrape_handler, in_memory_torrent_repository, stats_event_sender, _in_memory_whitelist, @@ -1253,6 +1263,7 @@ mod tests { async fn the_announced_peer_should_not_be_included_in_the_response() { let ( tracker, + _scrape_handler, _in_memory_torrent_repository, stats_event_sender, _in_memory_whitelist, @@ -1303,6 +1314,7 @@ mod tests { let ( tracker, + _scrape_handler, in_memory_torrent_repository, stats_event_sender, _in_memory_whitelist, @@ -1391,6 +1403,7 @@ mod tests { async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { let ( tracker, + _scrape_handler, _in_memory_torrent_repository, _stats_event_sender, _in_memory_whitelist, @@ -1422,7 +1435,7 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (tracker, whitelist_authorization) = test_tracker_factory(); + let (tracker, _scrape_handler, whitelist_authorization) = test_tracker_factory(); let remote_addr = sample_ipv6_remote_addr(); @@ -1483,13 +1496,7 @@ mod tests { Arc::new(Some(Box::new(stats_event_sender_mock))); let tracker = Arc::new( - core::Tracker::new( - &config.core, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - ) - .unwrap(), + core::Tracker::new(&config.core, &in_memory_torrent_repository, &db_torrent_repository).unwrap(), ); let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); @@ -1550,6 +1557,7 @@ mod tests { }; use super::{gen_remote_fingerprint, TorrentPeerBuilder}; + use crate::core::scrape_handler::ScrapeHandler; use crate::core::services::statistics; use crate::core::{self}; use crate::servers::udp::connection_cookie::make; @@ -1569,7 +1577,8 @@ mod tests { #[tokio::test] async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { let ( - tracker, + _tracker, + scrape_handler, _in_memory_torrent_repository, stats_event_sender, _in_memory_whitelist, @@ -1591,7 +1600,7 @@ mod tests { let response = handle_scrape( remote_addr, &request, - &tracker, + &scrape_handler, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1631,7 +1640,7 @@ mod tests { } } - async fn add_a_sample_seeder_and_scrape(tracker: Arc) -> Response { + async fn add_a_sample_seeder_and_scrape(tracker: Arc, scrape_handler: Arc) -> Response { let (stats_event_sender, _stats_repository) = statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); @@ -1645,7 +1654,7 @@ mod tests { handle_scrape( remote_addr, &request, - &tracker, + &scrape_handler, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1670,6 +1679,7 @@ mod tests { async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { let ( tracker, + scrape_handler, _in_memory_torrent_repository, _stats_event_sender, _in_memory_whitelist, @@ -1677,7 +1687,8 @@ mod tests { _whitelist_authorization, ) = public_tracker(); - let torrent_stats = match_scrape_response(add_a_sample_seeder_and_scrape(tracker.clone()).await); + let torrent_stats = + match_scrape_response(add_a_sample_seeder_and_scrape(tracker.clone(), scrape_handler.clone()).await); let expected_torrent_stats = vec![TorrentScrapeStatistics { seeders: NumberOfPeers(1.into()), @@ -1702,6 +1713,7 @@ mod tests { async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { let ( tracker, + scrape_handler, _in_memory_torrent_repository, stats_event_sender, in_memory_whitelist, @@ -1722,7 +1734,7 @@ mod tests { handle_scrape( remote_addr, &request, - &tracker, + &scrape_handler, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1744,6 +1756,7 @@ mod tests { async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { let ( tracker, + scrape_handler, _in_memory_torrent_repository, stats_event_sender, _in_memory_whitelist, @@ -1762,7 +1775,7 @@ mod tests { handle_scrape( remote_addr, &request, - &tracker, + &scrape_handler, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1814,12 +1827,12 @@ mod tests { let remote_addr = sample_ipv4_remote_addr(); - let (tracker, _whitelist_authorization) = test_tracker_factory(); + let (_tracker, scrape_handler, _whitelist_authorization) = test_tracker_factory(); handle_scrape( remote_addr, &sample_scrape_request(&remote_addr), - &tracker, + &scrape_handler, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1854,12 +1867,12 @@ mod tests { let remote_addr = sample_ipv6_remote_addr(); - let (tracker, _whitelist_authorization) = test_tracker_factory(); + let (_tracker, scrape_handler, _whitelist_authorization) = test_tracker_factory(); handle_scrape( remote_addr, &sample_scrape_request(&remote_addr), - &tracker, + &scrape_handler, &stats_event_sender, sample_cookie_valid_range(), ) diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index bb5c30d44..d6bc230e1 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -13,6 +13,7 @@ use tracing::instrument; use super::banning::BanService; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::{statistics, whitelist, Tracker}; use crate::servers::logging::STARTED_ON; @@ -43,6 +44,7 @@ impl Launcher { #[allow(clippy::too_many_arguments)] #[instrument(skip( tracker, + scrape_handler, whitelist_authorization, opt_stats_event_sender, ban_service, @@ -52,6 +54,7 @@ impl Launcher { ))] pub async fn run_with_graceful_shutdown( tracker: Arc, + scrape_handler: Arc, whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, ban_service: Arc>, @@ -95,6 +98,7 @@ impl Launcher { let () = Self::run_udp_server_main( receiver, tracker.clone(), + scrape_handler.clone(), whitelist_authorization.clone(), opt_stats_event_sender.clone(), ban_service.clone(), @@ -137,10 +141,18 @@ impl Launcher { ServiceHealthCheckJob::new(binding, info, job) } - #[instrument(skip(receiver, tracker, whitelist_authorization, opt_stats_event_sender, ban_service))] + #[instrument(skip( + receiver, + tracker, + scrape_handler, + whitelist_authorization, + opt_stats_event_sender, + ban_service + ))] async fn run_udp_server_main( mut receiver: Receiver, tracker: Arc, + scrape_handler: Arc, whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, ban_service: Arc>, @@ -212,6 +224,7 @@ impl Launcher { let processor = Processor::new( receiver.socket.clone(), tracker.clone(), + scrape_handler.clone(), whitelist_authorization.clone(), opt_stats_event_sender.clone(), cookie_lifetime, diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index af51b7fb7..668265752 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -83,6 +83,7 @@ mod tests { let started = stopped .start( app_container.tracker, + app_container.scrape_handler, app_container.whitelist_authorization, app_container.stats_event_sender, app_container.ban_service, @@ -116,6 +117,7 @@ mod tests { let started = stopped .start( app_container.tracker, + app_container.scrape_handler, app_container.whitelist_authorization, app_container.stats_event_sender, app_container.ban_service, diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index fe3666c1d..889a2a913 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -10,6 +10,7 @@ use tracing::{instrument, Level}; use super::banning::BanService; use super::bound_socket::BoundSocket; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::event::UdpResponseKind; use crate::core::{statistics, whitelist, Tracker}; @@ -19,6 +20,7 @@ use crate::servers::udp::{handlers, RawRequest}; pub struct Processor { socket: Arc, tracker: Arc, + scrape_handler: Arc, whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, cookie_lifetime: f64, @@ -28,6 +30,7 @@ impl Processor { pub fn new( socket: Arc, tracker: Arc, + scrape_handler: Arc, whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, cookie_lifetime: f64, @@ -35,6 +38,7 @@ impl Processor { Self { socket, tracker, + scrape_handler, whitelist_authorization, opt_stats_event_sender, cookie_lifetime, @@ -50,6 +54,7 @@ impl Processor { let response = handlers::handle_packet( request, &self.tracker, + &self.scrape_handler, &self.whitelist_authorization, &self.opt_stats_event_sender, self.socket.address(), diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index aecba39ec..82fd808c4 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -11,6 +11,7 @@ use tokio::task::JoinHandle; use super::banning::BanService; use super::launcher::Launcher; use crate::bootstrap::jobs::Started; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::{whitelist, Tracker}; use crate::servers::signals::Halted; @@ -31,6 +32,7 @@ impl Spawner { pub fn spawn_launcher( &self, tracker: Arc, + scrape_handler: Arc, whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, ban_service: Arc>, @@ -43,6 +45,7 @@ impl Spawner { tokio::spawn(async move { Launcher::run_with_graceful_shutdown( tracker, + scrape_handler, whitelist_authorization, opt_stats_event_sender, ban_service, diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index 9a01b5c6d..d2c91b03d 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -13,6 +13,7 @@ use super::banning::BanService; use super::spawner::Spawner; use super::{Server, UdpError}; use crate::bootstrap::jobs::Started; +use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::{whitelist, Tracker}; use crate::servers::registar::{ServiceRegistration, ServiceRegistrationForm}; @@ -64,11 +65,12 @@ impl Server { /// # Panics /// /// It panics if unable to receive the bound socket address from service. - /// - #[instrument(skip(self, tracker, whitelist_authorization, opt_stats_event_sender, ban_service, form), err, ret(Display, level = Level::INFO))] + #[allow(clippy::too_many_arguments)] + #[instrument(skip(self, tracker, scrape_handler, whitelist_authorization, opt_stats_event_sender, ban_service, form), err, ret(Display, level = Level::INFO))] pub async fn start( self, tracker: Arc, + scrape_handler: Arc, whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, ban_service: Arc>, @@ -83,6 +85,7 @@ impl Server { // May need to wrap in a task to about a tokio bug. let task = self.state.spawner.spawn_launcher( tracker, + scrape_handler, whitelist_authorization, opt_stats_event_sender, ban_service, diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index c0de4efbe..63d372880 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -8,6 +8,7 @@ use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::core::authentication::handler::KeysHandler; use torrust_tracker_lib::core::authentication::service::AuthenticationService; use torrust_tracker_lib::core::databases::Database; +use torrust_tracker_lib::core::scrape_handler::ScrapeHandler; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -21,6 +22,7 @@ pub struct Environment { pub config: Arc, pub database: Arc>, pub tracker: Arc, + pub scrape_handler: Arc, pub in_memory_torrent_repository: Arc, pub keys_handler: Arc, pub authentication_service: Arc, @@ -63,6 +65,7 @@ impl Environment { config, database: app_container.database.clone(), tracker: app_container.tracker.clone(), + scrape_handler: app_container.scrape_handler.clone(), in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), keys_handler: app_container.keys_handler.clone(), authentication_service: app_container.authentication_service.clone(), @@ -81,6 +84,7 @@ impl Environment { config: self.config, database: self.database.clone(), tracker: self.tracker.clone(), + scrape_handler: self.scrape_handler.clone(), in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), keys_handler: self.keys_handler.clone(), authentication_service: self.authentication_service.clone(), @@ -93,6 +97,7 @@ impl Environment { .server .start( self.tracker, + self.scrape_handler, self.authentication_service, self.whitelist_authorization, self.stats_event_sender, @@ -114,6 +119,7 @@ impl Environment { config: self.config, database: self.database, tracker: self.tracker, + scrape_handler: self.scrape_handler, in_memory_torrent_repository: self.in_memory_torrent_repository, keys_handler: self.keys_handler, authentication_service: self.authentication_service, diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index c02e35e6e..16719c317 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -6,6 +6,7 @@ use tokio::sync::RwLock; use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::core::databases::Database; +use torrust_tracker_lib::core::scrape_handler::ScrapeHandler; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::{whitelist, Tracker}; @@ -23,6 +24,7 @@ where pub config: Arc, pub database: Arc>, pub tracker: Arc, + pub scrape_handler: Arc, pub whitelist_authorization: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, @@ -61,6 +63,7 @@ impl Environment { config, database: app_container.database.clone(), tracker: app_container.tracker.clone(), + scrape_handler: app_container.scrape_handler.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), stats_event_sender: app_container.stats_event_sender.clone(), stats_repository: app_container.stats_repository.clone(), @@ -77,6 +80,7 @@ impl Environment { config: self.config, database: self.database.clone(), tracker: self.tracker.clone(), + scrape_handler: self.scrape_handler.clone(), whitelist_authorization: self.whitelist_authorization.clone(), stats_event_sender: self.stats_event_sender.clone(), stats_repository: self.stats_repository.clone(), @@ -86,6 +90,7 @@ impl Environment { .server .start( self.tracker, + self.scrape_handler, self.whitelist_authorization, self.stats_event_sender, self.ban_service, @@ -115,6 +120,7 @@ impl Environment { config: self.config, database: self.database, tracker: self.tracker, + scrape_handler: self.scrape_handler, whitelist_authorization: self.whitelist_authorization, stats_event_sender: self.stats_event_sender, stats_repository: self.stats_repository, From f23a3fc2a974f483a7a42f1d9270ea885f9a239f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 27 Jan 2025 12:04:23 +0000 Subject: [PATCH 0652/1297] chore: [#1207] remove deprecated comment --- src/core/mod.rs | 6 ------ src/core/scrape_handler.rs | 2 -- 2 files changed, 8 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 064e8eb3e..1d969068a 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -583,8 +583,6 @@ impl Tracker { /// It handles an announce request. /// - /// # Context: Tracker - /// /// BEP 03: [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html). pub fn announce( &self, @@ -628,8 +626,6 @@ impl Tracker { /// It updates the torrent entry in memory, it also stores in the database /// the torrent info data which is persistent, and finally return the data /// needed for a `announce` request response. - /// - /// # Context: Tracker #[must_use] pub fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { let swarm_metadata_before = match self.in_memory_torrent_repository.get_opt_swarm_metadata(info_hash) { @@ -652,8 +648,6 @@ impl Tracker { } /// It stores the torrents stats into the database (if persistency is enabled). - /// - /// # Context: Tracker fn persist_stats(&self, info_hash: &InfoHash, swarm_metadata: &SwarmMetadata) { if self.config.tracker_policy.persistent_torrent_completed_stat { let completed = swarm_metadata.downloaded; diff --git a/src/core/scrape_handler.rs b/src/core/scrape_handler.rs index 47049ed71..1d513a5a9 100644 --- a/src/core/scrape_handler.rs +++ b/src/core/scrape_handler.rs @@ -29,8 +29,6 @@ impl ScrapeHandler { /// It handles a scrape request. /// - /// # Context: Tracker - /// /// BEP 48: [Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). pub async fn scrape(&self, info_hashes: &Vec) -> ScrapeData { let mut scrape_data = ScrapeData::empty(); From f741d06db2281f44451e8097dcc0ce4e8b4972aa Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 27 Jan 2025 12:38:34 +0000 Subject: [PATCH 0653/1297] refactor: [#1207] use InMemoryTorrentRepository in tests to add torrents --- src/core/mod.rs | 42 +++++++++++------------ src/core/services/torrent.rs | 28 +++++++++------- src/servers/udp/handlers.rs | 56 ++++++++++++++++++------------- tests/servers/api/environment.rs | 2 +- tests/servers/http/environment.rs | 2 +- tests/servers/udp/environment.rs | 7 +++- 6 files changed, 77 insertions(+), 60 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 1d969068a..5d501b003 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -693,7 +693,7 @@ mod tests { use crate::core::whitelist::manager::WhiteListManager; use crate::core::{whitelist, Tracker}; - fn public_tracker() -> (Arc, Arc) { + fn public_tracker() -> (Arc, Arc, Arc) { let config = configuration::ephemeral_public(); let ( @@ -714,7 +714,7 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, scrape_handler) + (tracker, in_memory_torrent_repository, scrape_handler) } fn public_tracker_and_in_memory_torrents_repository() -> (Arc, Arc) { @@ -871,12 +871,12 @@ mod tests { #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent() { - let (tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); + let (_tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); let info_hash = sample_info_hash(); let peer = sample_peer(); - let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); @@ -903,7 +903,7 @@ mod tests { #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { - let (tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); + let (_tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); let info_hash = sample_info_hash(); @@ -918,7 +918,7 @@ mod tests { event: AnnounceEvent::Completed, }; - let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); } let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); @@ -928,12 +928,12 @@ mod tests { #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let (tracker, _scrape_handler) = public_tracker(); + let (tracker, in_memory_torrent_repository, _scrape_handler) = public_tracker(); let info_hash = sample_info_hash(); let peer = sample_peer(); - let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); let peers = tracker .in_memory_torrent_repository @@ -944,13 +944,13 @@ mod tests { #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { - let (tracker, _scrape_handler) = public_tracker(); + let (tracker, in_memory_torrent_repository, _scrape_handler) = public_tracker(); let info_hash = sample_info_hash(); let excluded_peer = sample_peer(); - let _ = tracker.upsert_peer_and_get_stats(&info_hash, &excluded_peer); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer); // Add 74 peers for idx in 2..=75 { @@ -964,7 +964,7 @@ mod tests { event: AnnounceEvent::Completed, }; - let _ = tracker.upsert_peer_and_get_stats(&info_hash, &peer); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); } let peers = tracker @@ -976,9 +976,9 @@ mod tests { #[tokio::test] async fn it_should_return_the_torrent_metrics() { - let (tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); + let (_tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); - let _ = tracker.upsert_peer_and_get_stats(&sample_info_hash(), &leecher()); + let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -995,11 +995,11 @@ mod tests { #[tokio::test] async fn it_should_get_many_the_torrent_metrics() { - let (tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); + let (_tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); let start_time = std::time::Instant::now(); for i in 0..1_000_000 { - let _ = tracker.upsert_peer_and_get_stats(&gen_seeded_infohash(&i), &leecher()); + let () = in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher()); } let result_a = start_time.elapsed(); @@ -1130,7 +1130,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_announce_data_with_an_empty_peer_list_when_it_is_the_first_announced_peer() { - let (tracker, _scrape_handler) = public_tracker(); + let (tracker, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); let mut peer = sample_peer(); @@ -1141,7 +1141,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_announce_data_with_the_previously_announced_peers() { - let (tracker, _scrape_handler) = public_tracker(); + let (tracker, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); let mut previously_announced_peer = sample_peer_1(); tracker.announce( @@ -1166,7 +1166,7 @@ mod tests { #[tokio::test] async fn when_the_peer_is_a_seeder() { - let (tracker, _scrape_handler) = public_tracker(); + let (tracker, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); let mut peer = seeder(); @@ -1177,7 +1177,7 @@ mod tests { #[tokio::test] async fn when_the_peer_is_a_leecher() { - let (tracker, _scrape_handler) = public_tracker(); + let (tracker, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); let mut peer = leecher(); @@ -1188,7 +1188,7 @@ mod tests { #[tokio::test] async fn when_a_previously_announced_started_peer_has_completed_downloading() { - let (tracker, _scrape_handler) = public_tracker(); + let (tracker, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); // We have to announce with "started" event because peer does not count if peer was not previously known let mut started_peer = started_peer(); @@ -1215,7 +1215,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() { - let (tracker, scrape_handler) = public_tracker(); + let (tracker, _in_memory_torrent_repository, scrape_handler) = public_tracker(); let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // # DevSkim: ignore DS173237 diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 8677096cc..5faaef1d1 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -189,11 +189,11 @@ mod tests { async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let config = tracker_configuration(); - let (tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); + let (_tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - let _ = tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); let torrent_info = get_torrent_info(in_memory_torrent_repository.clone(), &info_hash) .await @@ -242,12 +242,12 @@ mod tests { async fn should_return_a_summarized_info_for_all_torrents() { let config = tracker_configuration(); - let (tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); + let (_tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - let _ = tracker.upsert_peer_and_get_stats(&info_hash, &sample_peer()); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::default())).await; @@ -266,15 +266,16 @@ mod tests { async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let config = tracker_configuration(); - let (tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); + let (_tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); + let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _ = tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()); - let _ = tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); + let () = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); + let () = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); let offset = 0; let limit = 1; @@ -288,15 +289,16 @@ mod tests { async fn should_allow_using_pagination_in_the_result() { let config = tracker_configuration(); - let (tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); + let (_tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); + let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _ = tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()); - let _ = tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); + let () = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); + let () = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); let offset = 1; let limit = 4000; @@ -319,15 +321,15 @@ mod tests { async fn should_return_torrents_ordered_by_info_hash() { let config = tracker_configuration(); - let (tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); + let (_tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - let _ = tracker.upsert_peer_and_get_stats(&info_hash1, &sample_peer()); + let () = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _ = tracker.upsert_peer_and_get_stats(&info_hash2, &sample_peer()); + let () = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::default())).await; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index f8f57aea9..d6073d2e8 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -883,6 +883,7 @@ mod tests { }; use mockall::predicate::eq; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::{self, statistics, whitelist}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; @@ -1034,7 +1035,7 @@ mod tests { assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); } - fn add_a_torrent_peer_using_ipv6(tracker: &Arc) { + fn add_a_torrent_peer_using_ipv6(in_memory_torrent_repository: &Arc) { let info_hash = AquaticInfoHash([0u8; 20]); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); @@ -1047,7 +1048,7 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); - let _ = tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv6); + let () = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv6); } async fn announce_a_new_peer_using_ipv4( @@ -1079,14 +1080,14 @@ mod tests { let ( tracker, _scrape_handler, - _in_memory_torrent_repository, + in_memory_torrent_repository, _stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization, ) = public_tracker(); - add_a_torrent_peer_using_ipv6(&tracker); + add_a_torrent_peer_using_ipv6(&in_memory_torrent_repository); let response = announce_a_new_peer_using_ipv4(tracker.clone(), whitelist_authorization).await; @@ -1201,6 +1202,7 @@ mod tests { }; use mockall::predicate::eq; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::{self, statistics, whitelist}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; @@ -1357,7 +1359,7 @@ mod tests { assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); } - fn add_a_torrent_peer_using_ipv4(tracker: &Arc) { + fn add_a_torrent_peer_using_ipv4(in_memory_torrent_repository: &Arc) { let info_hash = AquaticInfoHash([0u8; 20]); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); @@ -1369,7 +1371,7 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) .into(); - let _ = tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer_using_ipv4); + let () = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv4); } async fn announce_a_new_peer_using_ipv6( @@ -1404,14 +1406,14 @@ mod tests { let ( tracker, _scrape_handler, - _in_memory_torrent_repository, + in_memory_torrent_repository, _stats_event_sender, _in_memory_whitelist, _whitelist_manager, whitelist_authorization, ) = public_tracker(); - add_a_torrent_peer_using_ipv4(&tracker); + add_a_torrent_peer_using_ipv4(&in_memory_torrent_repository); let response = announce_a_new_peer_using_ipv6(tracker.clone(), whitelist_authorization).await; @@ -1559,7 +1561,7 @@ mod tests { use super::{gen_remote_fingerprint, TorrentPeerBuilder}; use crate::core::scrape_handler::ScrapeHandler; use crate::core::services::statistics; - use crate::core::{self}; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ @@ -1618,7 +1620,11 @@ mod tests { ); } - async fn add_a_seeder(tracker: Arc, remote_addr: &SocketAddr, info_hash: &InfoHash) { + async fn add_a_seeder( + in_memory_torrent_repository: Arc, + remote_addr: &SocketAddr, + info_hash: &InfoHash, + ) { let peer_id = PeerId([255u8; 20]); let peer = TorrentPeerBuilder::new() @@ -1627,7 +1633,7 @@ mod tests { .with_number_of_bytes_left(0) .into(); - let _ = tracker.upsert_peer_and_get_stats(&info_hash.0.into(), &peer); + let () = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer); } fn build_scrape_request(remote_addr: &SocketAddr, info_hash: &InfoHash) -> ScrapeRequest { @@ -1640,14 +1646,17 @@ mod tests { } } - async fn add_a_sample_seeder_and_scrape(tracker: Arc, scrape_handler: Arc) -> Response { + async fn add_a_sample_seeder_and_scrape( + in_memory_torrent_repository: Arc, + scrape_handler: Arc, + ) -> Response { let (stats_event_sender, _stats_repository) = statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); - add_a_seeder(tracker.clone(), &remote_addr, &info_hash).await; + add_a_seeder(in_memory_torrent_repository.clone(), &remote_addr, &info_hash).await; let request = build_scrape_request(&remote_addr, &info_hash); @@ -1678,17 +1687,18 @@ mod tests { #[tokio::test] async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { let ( - tracker, + _tracker, scrape_handler, - _in_memory_torrent_repository, + in_memory_torrent_repository, _stats_event_sender, _in_memory_whitelist, _whitelist_manager, _whitelist_authorization, ) = public_tracker(); - let torrent_stats = - match_scrape_response(add_a_sample_seeder_and_scrape(tracker.clone(), scrape_handler.clone()).await); + let torrent_stats = match_scrape_response( + add_a_sample_seeder_and_scrape(in_memory_torrent_repository.clone(), scrape_handler.clone()).await, + ); let expected_torrent_stats = vec![TorrentScrapeStatistics { seeders: NumberOfPeers(1.into()), @@ -1712,9 +1722,9 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { let ( - tracker, + _tracker, scrape_handler, - _in_memory_torrent_repository, + in_memory_torrent_repository, stats_event_sender, in_memory_whitelist, _whitelist_manager, @@ -1724,7 +1734,7 @@ mod tests { let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); - add_a_seeder(tracker.clone(), &remote_addr, &info_hash).await; + add_a_seeder(in_memory_torrent_repository.clone(), &remote_addr, &info_hash).await; in_memory_whitelist.add(&info_hash.0.into()).await; @@ -1755,9 +1765,9 @@ mod tests { #[tokio::test] async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { let ( - tracker, + _tracker, scrape_handler, - _in_memory_torrent_repository, + in_memory_torrent_repository, stats_event_sender, _in_memory_whitelist, _whitelist_manager, @@ -1767,7 +1777,7 @@ mod tests { let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); - add_a_seeder(tracker.clone(), &remote_addr, &info_hash).await; + add_a_seeder(in_memory_torrent_repository.clone(), &remote_addr, &info_hash).await; let request = build_scrape_request(&remote_addr, &info_hash); diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 70f071bf4..927f76efe 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -45,7 +45,7 @@ where { /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let _ = self.tracker.upsert_peer_and_get_stats(info_hash, peer); + let () = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); } } diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 63d372880..beaf2d38c 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -37,7 +37,7 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let _ = self.tracker.upsert_peer_and_get_stats(info_hash, peer); + let () = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); } } diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 16719c317..09714146d 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -9,6 +9,7 @@ use torrust_tracker_lib::core::databases::Database; use torrust_tracker_lib::core::scrape_handler::ScrapeHandler; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; +use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; use torrust_tracker_lib::core::{whitelist, Tracker}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::banning::BanService; @@ -24,6 +25,7 @@ where pub config: Arc, pub database: Arc>, pub tracker: Arc, + pub in_memory_torrent_repository: Arc, pub scrape_handler: Arc, pub whitelist_authorization: Arc, pub stats_event_sender: Arc>>, @@ -40,7 +42,7 @@ where /// Add a torrent to the tracker #[allow(dead_code)] pub fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let _ = self.tracker.upsert_peer_and_get_stats(info_hash, peer); + let () = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); } } @@ -63,6 +65,7 @@ impl Environment { config, database: app_container.database.clone(), tracker: app_container.tracker.clone(), + in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), scrape_handler: app_container.scrape_handler.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), stats_event_sender: app_container.stats_event_sender.clone(), @@ -80,6 +83,7 @@ impl Environment { config: self.config, database: self.database.clone(), tracker: self.tracker.clone(), + in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), scrape_handler: self.scrape_handler.clone(), whitelist_authorization: self.whitelist_authorization.clone(), stats_event_sender: self.stats_event_sender.clone(), @@ -120,6 +124,7 @@ impl Environment { config: self.config, database: self.database, tracker: self.tracker, + in_memory_torrent_repository: self.in_memory_torrent_repository, scrape_handler: self.scrape_handler, whitelist_authorization: self.whitelist_authorization, stats_event_sender: self.stats_event_sender, From 401c228b4e066a85af98af8a301e63ccaa366b3b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 27 Jan 2025 12:45:53 +0000 Subject: [PATCH 0654/1297] refactor: [#1207] make method upsert_peer_and_get_stats private --- src/core/mod.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 5d501b003..5e5c20699 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -627,7 +627,7 @@ impl Tracker { /// the torrent info data which is persistent, and finally return the data /// needed for a `announce` request response. #[must_use] - pub fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { + fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { let swarm_metadata_before = match self.in_memory_torrent_repository.get_opt_swarm_metadata(info_hash) { Some(swarm_metadata) => swarm_metadata, None => SwarmMetadata::zeroed(), @@ -1393,7 +1393,10 @@ mod tests { use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_torrent_repository::entry::EntrySync; - use crate::core::tests::the_tracker::{sample_info_hash, sample_peer, tracker_persisting_torrents_in_database}; + use crate::core::tests::the_tracker::{ + peer_ip, sample_info_hash, sample_peer, tracker_persisting_torrents_in_database, + }; + use crate::core::PeersWanted; #[tokio::test] async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { @@ -1404,12 +1407,12 @@ mod tests { let mut peer = sample_peer(); peer.event = AnnounceEvent::Started; - let swarm_stats = tracker.upsert_peer_and_get_stats(&info_hash, &peer); - assert_eq!(swarm_stats.downloaded, 0); + let announce_data = tracker.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + assert_eq!(announce_data.stats.downloaded, 0); peer.event = AnnounceEvent::Completed; - let swarm_stats = tracker.upsert_peer_and_get_stats(&info_hash, &peer); - assert_eq!(swarm_stats.downloaded, 1); + let announce_data = tracker.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + assert_eq!(announce_data.stats.downloaded, 1); // Remove the newly updated torrent from memory let _unused = in_memory_torrent_repository.remove(&info_hash); From 026f957192072b4b62b53e4f291b3f38904390cd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 27 Jan 2025 13:47:11 +0000 Subject: [PATCH 0655/1297] refactor: [#1207] extract AnnounceHandler --- src/app.rs | 2 + src/bootstrap/app.rs | 8 + src/bootstrap/jobs/http_tracker.rs | 18 +- src/bootstrap/jobs/udp_tracker.rs | 5 + src/container.rs | 2 + src/core/announce_handler.rs | 164 +++++++++++++ src/core/mod.rs | 298 +++++++++-------------- src/servers/http/server.rs | 8 + src/servers/http/v1/handlers/announce.rs | 49 +++- src/servers/http/v1/routes.rs | 5 + src/servers/http/v1/services/announce.rs | 79 ++++-- src/servers/http/v1/services/scrape.rs | 30 ++- src/servers/udp/handlers.rs | 90 ++++++- src/servers/udp/server/launcher.rs | 8 + src/servers/udp/server/mod.rs | 2 + src/servers/udp/server/processor.rs | 5 + src/servers/udp/server/spawner.rs | 3 + src/servers/udp/server/states.rs | 5 +- tests/servers/http/environment.rs | 6 + tests/servers/udp/environment.rs | 6 + 20 files changed, 554 insertions(+), 239 deletions(-) create mode 100644 src/core/announce_handler.rs diff --git a/src/app.rs b/src/app.rs index 3f0e8d399..00414bc10 100644 --- a/src/app.rs +++ b/src/app.rs @@ -80,6 +80,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< udp_tracker::start_job( udp_tracker_config, app_container.tracker.clone(), + app_container.announce_handler.clone(), app_container.scrape_handler.clone(), app_container.whitelist_authorization.clone(), app_container.stats_event_sender.clone(), @@ -100,6 +101,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< if let Some(job) = http_tracker::start_job( http_tracker_config, app_container.tracker.clone(), + app_container.announce_handler.clone(), app_container.scrape_handler.clone(), app_container.authentication_service.clone(), app_container.whitelist_authorization.clone(), diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index a0b6df3ca..fa45998bb 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -22,6 +22,7 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; use crate::container::AppContainer; +use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; @@ -121,11 +122,18 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { &db_torrent_repository, )); + let announce_handler = Arc::new(AnnounceHandler::new( + &configuration.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); AppContainer { database, tracker, + announce_handler, scrape_handler, keys_handler, authentication_service, diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 2e76e2f31..5da7da739 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -19,6 +19,7 @@ use torrust_tracker_configuration::HttpTracker; use tracing::instrument; use super::make_rust_tls; +use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::service::AuthenticationService; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; @@ -39,6 +40,7 @@ use crate::servers::registar::ServiceRegistrationForm; #[instrument(skip( config, tracker, + announce_handler, scrape_handler, authentication_service, whitelist_authorization, @@ -48,6 +50,7 @@ use crate::servers::registar::ServiceRegistrationForm; pub async fn start_job( config: &HttpTracker, tracker: Arc, + announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, @@ -67,6 +70,7 @@ pub async fn start_job( socket, tls, tracker.clone(), + announce_handler.clone(), scrape_handler.clone(), authentication_service.clone(), whitelist_authorization.clone(), @@ -80,11 +84,21 @@ pub async fn start_job( #[allow(clippy::too_many_arguments)] #[allow(clippy::async_yields_async)] -#[instrument(skip(socket, tls, tracker, scrape_handler, whitelist_authorization, stats_event_sender, form))] +#[instrument(skip( + socket, + tls, + tracker, + announce_handler, + scrape_handler, + whitelist_authorization, + stats_event_sender, + form +))] async fn start_v1( socket: SocketAddr, tls: Option, tracker: Arc, + announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, @@ -94,6 +108,7 @@ async fn start_v1( let server = HttpServer::new(Launcher::new(socket, tls)) .start( tracker, + announce_handler, scrape_handler, authentication_service, whitelist_authorization, @@ -142,6 +157,7 @@ mod tests { start_job( config, app_container.tracker, + app_container.announce_handler, app_container.scrape_handler, app_container.authentication_service, app_container.whitelist_authorization, diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index dd55e4b8b..d43c1c930 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -13,6 +13,7 @@ use tokio::task::JoinHandle; use torrust_tracker_configuration::UdpTracker; use tracing::instrument; +use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::{self, whitelist}; @@ -32,10 +33,12 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// It will panic if it is unable to start the UDP service. /// It will panic if the task did not finish successfully. #[must_use] +#[allow(clippy::too_many_arguments)] #[allow(clippy::async_yields_async)] #[instrument(skip( config, tracker, + announce_handler, scrape_handler, whitelist_authorization, stats_event_sender, @@ -45,6 +48,7 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; pub async fn start_job( config: &UdpTracker, tracker: Arc, + announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, stats_event_sender: Arc>>, @@ -57,6 +61,7 @@ pub async fn start_job( let server = Server::new(Spawner::new(bind_to)) .start( tracker, + announce_handler, scrape_handler, whitelist_authorization, stats_event_sender, diff --git a/src/container.rs b/src/container.rs index a73862006..4e958b6ed 100644 --- a/src/container.rs +++ b/src/container.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use tokio::sync::RwLock; +use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::service::AuthenticationService; use crate::core::databases::Database; @@ -18,6 +19,7 @@ use crate::servers::udp::server::banning::BanService; pub struct AppContainer { pub database: Arc>, pub tracker: Arc, + pub announce_handler: Arc, pub scrape_handler: Arc, pub keys_handler: Arc, pub authentication_service: Arc, diff --git a/src/core/announce_handler.rs b/src/core/announce_handler.rs new file mode 100644 index 000000000..a037d33d4 --- /dev/null +++ b/src/core/announce_handler.rs @@ -0,0 +1,164 @@ +use std::net::IpAddr; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::{Core, TORRENT_PEERS_LIMIT}; +use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::peer; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + +use super::torrent::repository::in_memory::InMemoryTorrentRepository; +use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; + +pub struct AnnounceHandler { + /// The tracker configuration. + config: Core, + + /// The in-memory torrents repository. + in_memory_torrent_repository: Arc, + + /// The persistent torrents repository. + db_torrent_repository: Arc, +} + +impl AnnounceHandler { + #[must_use] + pub fn new( + config: &Core, + in_memory_torrent_repository: &Arc, + db_torrent_repository: &Arc, + ) -> Self { + Self { + config: config.clone(), + in_memory_torrent_repository: in_memory_torrent_repository.clone(), + db_torrent_repository: db_torrent_repository.clone(), + } + } + + /// It handles an announce request. + /// + /// BEP 03: [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html). + pub fn announce( + &self, + info_hash: &InfoHash, + peer: &mut peer::Peer, + remote_client_ip: &IpAddr, + peers_wanted: &PeersWanted, + ) -> AnnounceData { + // code-review: maybe instead of mutating the peer we could just return + // a tuple with the new peer and the announce data: (Peer, AnnounceData). + // It could even be a different struct: `StoredPeer` or `PublicPeer`. + + // code-review: in the `scrape` function we perform an authorization check. + // We check if the torrent is whitelisted. Should we also check authorization here? + // I think so because the `Tracker` has the responsibility for checking authentication and authorization. + // The `Tracker` has delegated that responsibility to the handlers + // (because we want to return a friendly error response) but that does not mean we should + // double-check authorization at this domain level too. + // I would propose to return a `Result` here. + // Besides, regarding authentication the `Tracker` is also responsible for authentication but + // we are actually handling authentication at the handlers level. So I would extract that + // responsibility into another authentication service. + + tracing::debug!("Before: {peer:?}"); + peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); + tracing::debug!("After: {peer:?}"); + + let stats = self.upsert_peer_and_get_stats(info_hash, peer); + + let peers = self + .in_memory_torrent_repository + .get_peers_for(info_hash, peer, peers_wanted.limit()); + + AnnounceData { + peers, + stats, + policy: self.config.announce_policy, + } + } + + /// It updates the torrent entry in memory, it also stores in the database + /// the torrent info data which is persistent, and finally return the data + /// needed for a `announce` request response. + #[must_use] + fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { + let swarm_metadata_before = match self.in_memory_torrent_repository.get_opt_swarm_metadata(info_hash) { + Some(swarm_metadata) => swarm_metadata, + None => SwarmMetadata::zeroed(), + }; + + self.in_memory_torrent_repository.upsert_peer(info_hash, peer); + + let swarm_metadata_after = match self.in_memory_torrent_repository.get_opt_swarm_metadata(info_hash) { + Some(swarm_metadata) => swarm_metadata, + None => SwarmMetadata::zeroed(), + }; + + if swarm_metadata_before != swarm_metadata_after { + self.persist_stats(info_hash, &swarm_metadata_after); + } + + swarm_metadata_after + } + + /// It stores the torrents stats into the database (if persistency is enabled). + fn persist_stats(&self, info_hash: &InfoHash, swarm_metadata: &SwarmMetadata) { + if self.config.tracker_policy.persistent_torrent_completed_stat { + let completed = swarm_metadata.downloaded; + let info_hash = *info_hash; + + drop(self.db_torrent_repository.save(&info_hash, completed)); + } + } +} + +/// How many peers the peer announcing wants in the announce response. +#[derive(Clone, Debug, PartialEq, Default)] +pub enum PeersWanted { + /// The peer wants as many peers as possible in the announce response. + #[default] + All, + /// The peer only wants a certain amount of peers in the announce response. + Only { amount: usize }, +} + +impl PeersWanted { + #[must_use] + pub fn only(limit: u32) -> Self { + let amount: usize = match limit.try_into() { + Ok(amount) => amount, + Err(_) => TORRENT_PEERS_LIMIT, + }; + + Self::Only { amount } + } + + fn limit(&self) -> usize { + match self { + PeersWanted::All => TORRENT_PEERS_LIMIT, + PeersWanted::Only { amount } => *amount, + } + } +} + +impl From for PeersWanted { + fn from(value: i32) -> Self { + if value > 0 { + match value.try_into() { + Ok(peers_wanted) => Self::Only { amount: peers_wanted }, + Err(_) => Self::All, + } + } else { + Self::All + } + } +} + +#[must_use] +pub fn assign_ip_address_to_peer(remote_client_ip: &IpAddr, tracker_external_ip: Option) -> IpAddr { + if let Some(host_ip) = tracker_external_ip.filter(|_| remote_client_ip.is_loopback()) { + host_ip + } else { + *remote_client_ip + } +} diff --git a/src/core/mod.rs b/src/core/mod.rs index 5e5c20699..2151ec1ef 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -439,6 +439,7 @@ //! - Torrent metrics //! //! Refer to [`databases`] module for more information about persistence. +pub mod announce_handler; pub mod authentication; pub mod databases; pub mod error; @@ -453,13 +454,9 @@ pub mod peer_tests; use std::net::IpAddr; use std::sync::Arc; -use bittorrent_primitives::info_hash::InfoHash; use torrent::repository::in_memory::InMemoryTorrentRepository; use torrent::repository::persisted::DatabasePersistentTorrentRepository; -use torrust_tracker_configuration::{AnnouncePolicy, Core, TORRENT_PEERS_LIMIT}; -use torrust_tracker_primitives::core::AnnounceData; -use torrust_tracker_primitives::peer; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_configuration::{AnnouncePolicy, Core}; /// The domain layer tracker service. /// @@ -475,52 +472,10 @@ pub struct Tracker { config: Core, /// The in-memory torrents repository. - in_memory_torrent_repository: Arc, + _in_memory_torrent_repository: Arc, /// The persistent torrents repository. - db_torrent_repository: Arc, -} - -/// How many peers the peer announcing wants in the announce response. -#[derive(Clone, Debug, PartialEq, Default)] -pub enum PeersWanted { - /// The peer wants as many peers as possible in the announce response. - #[default] - All, - /// The peer only wants a certain amount of peers in the announce response. - Only { amount: usize }, -} - -impl PeersWanted { - #[must_use] - pub fn only(limit: u32) -> Self { - let amount: usize = match limit.try_into() { - Ok(amount) => amount, - Err(_) => TORRENT_PEERS_LIMIT, - }; - - Self::Only { amount } - } - - fn limit(&self) -> usize { - match self { - PeersWanted::All => TORRENT_PEERS_LIMIT, - PeersWanted::Only { amount } => *amount, - } - } -} - -impl From for PeersWanted { - fn from(value: i32) -> Self { - if value > 0 { - match value.try_into() { - Ok(peers_wanted) => Self::Only { amount: peers_wanted }, - Err(_) => Self::All, - } - } else { - Self::All - } - } + _db_torrent_repository: Arc, } impl Tracker { @@ -536,8 +491,8 @@ impl Tracker { ) -> Result { Ok(Tracker { config: config.clone(), - in_memory_torrent_repository: in_memory_torrent_repository.clone(), - db_torrent_repository: db_torrent_repository.clone(), + _in_memory_torrent_repository: in_memory_torrent_repository.clone(), + _db_torrent_repository: db_torrent_repository.clone(), }) } @@ -580,91 +535,6 @@ impl Tracker { pub fn get_maybe_external_ip(&self) -> Option { self.config.net.external_ip } - - /// It handles an announce request. - /// - /// BEP 03: [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html). - pub fn announce( - &self, - info_hash: &InfoHash, - peer: &mut peer::Peer, - remote_client_ip: &IpAddr, - peers_wanted: &PeersWanted, - ) -> AnnounceData { - // code-review: maybe instead of mutating the peer we could just return - // a tuple with the new peer and the announce data: (Peer, AnnounceData). - // It could even be a different struct: `StoredPeer` or `PublicPeer`. - - // code-review: in the `scrape` function we perform an authorization check. - // We check if the torrent is whitelisted. Should we also check authorization here? - // I think so because the `Tracker` has the responsibility for checking authentication and authorization. - // The `Tracker` has delegated that responsibility to the handlers - // (because we want to return a friendly error response) but that does not mean we should - // double-check authorization at this domain level too. - // I would propose to return a `Result` here. - // Besides, regarding authentication the `Tracker` is also responsible for authentication but - // we are actually handling authentication at the handlers level. So I would extract that - // responsibility into another authentication service. - - tracing::debug!("Before: {peer:?}"); - peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); - tracing::debug!("After: {peer:?}"); - - let stats = self.upsert_peer_and_get_stats(info_hash, peer); - - let peers = self - .in_memory_torrent_repository - .get_peers_for(info_hash, peer, peers_wanted.limit()); - - AnnounceData { - peers, - stats, - policy: self.get_announce_policy(), - } - } - - /// It updates the torrent entry in memory, it also stores in the database - /// the torrent info data which is persistent, and finally return the data - /// needed for a `announce` request response. - #[must_use] - fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { - let swarm_metadata_before = match self.in_memory_torrent_repository.get_opt_swarm_metadata(info_hash) { - Some(swarm_metadata) => swarm_metadata, - None => SwarmMetadata::zeroed(), - }; - - self.in_memory_torrent_repository.upsert_peer(info_hash, peer); - - let swarm_metadata_after = match self.in_memory_torrent_repository.get_opt_swarm_metadata(info_hash) { - Some(swarm_metadata) => swarm_metadata, - None => SwarmMetadata::zeroed(), - }; - - if swarm_metadata_before != swarm_metadata_after { - self.persist_stats(info_hash, &swarm_metadata_after); - } - - swarm_metadata_after - } - - /// It stores the torrents stats into the database (if persistency is enabled). - fn persist_stats(&self, info_hash: &InfoHash, swarm_metadata: &SwarmMetadata) { - if self.config.tracker_policy.persistent_torrent_completed_stat { - let completed = swarm_metadata.downloaded; - let info_hash = *info_hash; - - drop(self.db_torrent_repository.save(&info_hash, completed)); - } - } -} - -#[must_use] -fn assign_ip_address_to_peer(remote_client_ip: &IpAddr, tracker_external_ip: Option) -> IpAddr { - if let Some(host_ip) = tracker_external_ip.filter(|_| remote_client_ip.is_loopback()) { - host_ip - } else { - *remote_client_ip - } } #[cfg(test)] @@ -680,12 +550,13 @@ mod tests { use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; + use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; - use crate::core::peer::Peer; + use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::services::{initialize_tracker, initialize_whitelist_manager}; use crate::core::torrent::manager::TorrentsManager; @@ -693,7 +564,12 @@ mod tests { use crate::core::whitelist::manager::WhiteListManager; use crate::core::{whitelist, Tracker}; - fn public_tracker() -> (Arc, Arc, Arc) { + fn public_tracker() -> ( + Arc, + Arc, + Arc, + Arc, + ) { let config = configuration::ephemeral_public(); let ( @@ -712,9 +588,15 @@ mod tests { &db_torrent_repository, )); + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, in_memory_torrent_repository, scrape_handler) + (tracker, announce_handler, in_memory_torrent_repository, scrape_handler) } fn public_tracker_and_in_memory_torrents_repository() -> (Arc, Arc) { @@ -739,8 +621,10 @@ mod tests { (tracker, in_memory_torrent_repository) } + #[allow(clippy::type_complexity)] fn whitelisted_tracker() -> ( - Tracker, + Arc, + Arc, Arc, Arc, Arc, @@ -759,14 +643,35 @@ mod tests { let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = initialize_tracker(&config, &in_memory_torrent_repository, &db_torrent_repository); + let tracker = Arc::new(initialize_tracker( + &config, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, whitelist_authorization, whitelist_manager, scrape_handler) + ( + tracker, + announce_handler, + whitelist_authorization, + whitelist_manager, + scrape_handler, + ) } - pub fn tracker_persisting_torrents_in_database() -> (Tracker, Arc, Arc) { + pub fn tracker_persisting_torrents_in_database() -> ( + Arc, + Arc, + Arc, + Arc, + ) { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; @@ -780,9 +685,19 @@ mod tests { torrents_manager, ) = initialize_tracker_dependencies(&config); - let tracker = initialize_tracker(&config, &in_memory_torrent_repository, &db_torrent_repository); + let tracker = Arc::new(initialize_tracker( + &config, + &in_memory_torrent_repository, + &db_torrent_repository, + )); - (tracker, torrents_manager, in_memory_torrent_repository) + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + (tracker, announce_handler, torrents_manager, in_memory_torrent_repository) } fn sample_info_hash() -> InfoHash { @@ -928,23 +843,21 @@ mod tests { #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let (tracker, in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (_tracker, _announce_handler, in_memory_torrent_repository, _scrape_handler) = public_tracker(); let info_hash = sample_info_hash(); let peer = sample_peer(); let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); - let peers = tracker - .in_memory_torrent_repository - .get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); + let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); assert_eq!(peers, vec![]); } #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { - let (tracker, in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (_tracker, _announce_handler, in_memory_torrent_repository, _scrape_handler) = public_tracker(); let info_hash = sample_info_hash(); @@ -967,9 +880,7 @@ mod tests { let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); } - let peers = tracker - .in_memory_torrent_repository - .get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); + let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); assert_eq!(peers.len(), 74); } @@ -1025,16 +936,16 @@ mod tests { use std::sync::Arc; + use crate::core::announce_handler::PeersWanted; use crate::core::tests::the_tracker::{ peer_ip, public_tracker, sample_info_hash, sample_peer, sample_peer_1, sample_peer_2, }; - use crate::core::PeersWanted; mod should_assign_the_ip_to_the_peer { use std::net::{IpAddr, Ipv4Addr}; - use crate::core::assign_ip_address_to_peer; + use crate::core::announce_handler::assign_ip_address_to_peer; #[test] fn using_the_source_ip_instead_of_the_ip_in_the_announce_request() { @@ -1050,7 +961,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::str::FromStr; - use crate::core::assign_ip_address_to_peer; + use crate::core::announce_handler::assign_ip_address_to_peer; #[test] fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { @@ -1091,7 +1002,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::str::FromStr; - use crate::core::assign_ip_address_to_peer; + use crate::core::announce_handler::assign_ip_address_to_peer; #[test] fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { @@ -1130,21 +1041,21 @@ mod tests { #[tokio::test] async fn it_should_return_the_announce_data_with_an_empty_peer_list_when_it_is_the_first_announced_peer() { - let (tracker, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (_tracker, announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); let mut peer = sample_peer(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); + let announce_data = announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); assert_eq!(announce_data.peers, vec![]); } #[tokio::test] async fn it_should_return_the_announce_data_with_the_previously_announced_peers() { - let (tracker, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (_tracker, announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); let mut previously_announced_peer = sample_peer_1(); - tracker.announce( + announce_handler.announce( &sample_info_hash(), &mut previously_announced_peer, &peer_ip(), @@ -1152,51 +1063,53 @@ mod tests { ); let mut peer = sample_peer_2(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); + let announce_data = announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); assert_eq!(announce_data.peers, vec![Arc::new(previously_announced_peer)]); } mod it_should_update_the_swarm_stats_for_the_torrent { + use crate::core::announce_handler::PeersWanted; use crate::core::tests::the_tracker::{ completed_peer, leecher, peer_ip, public_tracker, sample_info_hash, seeder, started_peer, }; - use crate::core::PeersWanted; #[tokio::test] async fn when_the_peer_is_a_seeder() { - let (tracker, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (_tracker, announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); let mut peer = seeder(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); + let announce_data = + announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); assert_eq!(announce_data.stats.complete, 1); } #[tokio::test] async fn when_the_peer_is_a_leecher() { - let (tracker, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (_tracker, announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); let mut peer = leecher(); - let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); + let announce_data = + announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); assert_eq!(announce_data.stats.incomplete, 1); } #[tokio::test] async fn when_a_previously_announced_started_peer_has_completed_downloading() { - let (tracker, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (_tracker, announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); // We have to announce with "started" event because peer does not count if peer was not previously known let mut started_peer = started_peer(); - tracker.announce(&sample_info_hash(), &mut started_peer, &peer_ip(), &PeersWanted::All); + announce_handler.announce(&sample_info_hash(), &mut started_peer, &peer_ip(), &PeersWanted::All); let mut completed_peer = completed_peer(); let announce_data = - tracker.announce(&sample_info_hash(), &mut completed_peer, &peer_ip(), &PeersWanted::All); + announce_handler.announce(&sample_info_hash(), &mut completed_peer, &peer_ip(), &PeersWanted::All); assert_eq!(announce_data.stats.downloaded, 1); } @@ -1209,19 +1122,20 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use crate::core::announce_handler::PeersWanted; use crate::core::tests::the_tracker::{complete_peer, incomplete_peer, public_tracker}; - use crate::core::{PeersWanted, SwarmMetadata}; #[tokio::test] async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() { - let (tracker, _in_memory_torrent_repository, scrape_handler) = public_tracker(); + let (_tracker, announce_handler, _in_memory_torrent_repository, scrape_handler) = public_tracker(); let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // # DevSkim: ignore DS173237 // Announce a "complete" peer for the torrent let mut complete_peer = complete_peer(); - tracker.announce( + announce_handler.announce( &info_hash, &mut complete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10)), @@ -1230,7 +1144,7 @@ mod tests { // Announce an "incomplete" peer for the torrent let mut incomplete_peer = incomplete_peer(); - tracker.announce( + announce_handler.announce( &info_hash, &mut incomplete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11)), @@ -1263,7 +1177,8 @@ mod tests { #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { - let (_tracker, whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + let (_tracker, _announce_handler, whitelist_authorization, whitelist_manager, _scrape_handler) = + whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1276,7 +1191,8 @@ mod tests { #[tokio::test] async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { - let (_tracker, whitelist_authorization, _whitelist_manager, _scrape_handler) = whitelisted_tracker(); + let (_tracker, _announce_handler, whitelist_authorization, _whitelist_manager, _scrape_handler) = + whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1295,7 +1211,8 @@ mod tests { #[tokio::test] async fn it_should_add_a_torrent_to_the_whitelist() { - let (_tracker, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + let (_tracker, _announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = + whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1306,7 +1223,8 @@ mod tests { #[tokio::test] async fn it_should_remove_a_torrent_from_the_whitelist() { - let (_tracker, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + let (_tracker, _announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = + whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1322,7 +1240,8 @@ mod tests { #[tokio::test] async fn it_should_load_the_whitelist_from_the_database() { - let (_tracker, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + let (_tracker, _announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = + whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1347,10 +1266,10 @@ mod tests { use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use crate::core::announce_handler::PeersWanted; use crate::core::tests::the_tracker::{ complete_peer, incomplete_peer, peer_ip, sample_info_hash, whitelisted_tracker, }; - use crate::core::PeersWanted; #[test] fn it_should_be_able_to_build_a_zeroed_scrape_data_for_a_list_of_info_hashes() { @@ -1366,16 +1285,17 @@ mod tests { #[tokio::test] async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { - let (tracker, _whitelist_authorization, _whitelist_manager, scrape_handler) = whitelisted_tracker(); + let (_tracker, announce_handler, _whitelist_authorization, _whitelist_manager, scrape_handler) = + whitelisted_tracker(); let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // # DevSkim: ignore DS173237 let mut peer = incomplete_peer(); - tracker.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); // Announce twice to force non zeroed swarm metadata let mut peer = complete_peer(); - tracker.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); let scrape_data = scrape_handler.scrape(&vec![info_hash]).await; @@ -1393,25 +1313,26 @@ mod tests { use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_torrent_repository::entry::EntrySync; + use crate::core::announce_handler::PeersWanted; use crate::core::tests::the_tracker::{ peer_ip, sample_info_hash, sample_peer, tracker_persisting_torrents_in_database, }; - use crate::core::PeersWanted; #[tokio::test] async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { - let (tracker, torrents_manager, in_memory_torrent_repository) = tracker_persisting_torrents_in_database(); + let (_tracker, announce_handler, torrents_manager, in_memory_torrent_repository) = + tracker_persisting_torrents_in_database(); let info_hash = sample_info_hash(); let mut peer = sample_peer(); peer.event = AnnounceEvent::Started; - let announce_data = tracker.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); assert_eq!(announce_data.stats.downloaded, 0); peer.event = AnnounceEvent::Completed; - let announce_data = tracker.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); assert_eq!(announce_data.stats.downloaded, 1); // Remove the newly updated torrent from memory @@ -1419,8 +1340,7 @@ mod tests { torrents_manager.load_torrents_from_database().unwrap(); - let torrent_entry = tracker - .in_memory_torrent_repository + let torrent_entry = in_memory_torrent_repository .get(&info_hash) .expect("it should be able to get entry"); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 573337ba9..3bb49c1ad 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -11,6 +11,7 @@ use tracing::instrument; use super::v1::routes::router; use crate::bootstrap::jobs::Started; +use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::service::AuthenticationService; use crate::core::scrape_handler::ScrapeHandler; use crate::core::{statistics, whitelist, Tracker}; @@ -48,6 +49,7 @@ impl Launcher { #[instrument(skip( self, tracker, + announce_handler, scrape_handler, authentication_service, whitelist_authorization, @@ -58,6 +60,7 @@ impl Launcher { fn start( &self, tracker: Arc, + announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, @@ -83,6 +86,7 @@ impl Launcher { let app = router( tracker, + announce_handler, scrape_handler, authentication_service, whitelist_authorization, @@ -181,9 +185,11 @@ impl HttpServer { /// /// It would panic spawned HTTP server launcher cannot send the bound `SocketAddr` /// back to the main thread. + #[allow(clippy::too_many_arguments)] pub async fn start( self, tracker: Arc, + announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, @@ -198,6 +204,7 @@ impl HttpServer { let task = tokio::spawn(async move { let server = launcher.start( tracker, + announce_handler, scrape_handler, authentication_service, whitelist_authorization, @@ -303,6 +310,7 @@ mod tests { let started = stopped .start( app_container.tracker, + app_container.announce_handler, app_container.scrape_handler, app_container.authentication_service, app_container.whitelist_authorization, diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 8b57ce543..39ddd1710 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -21,10 +21,11 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; +use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; use crate::core::authentication::service::AuthenticationService; use crate::core::authentication::Key; use crate::core::statistics::event::sender::Sender; -use crate::core::{whitelist, PeersWanted, Tracker}; +use crate::core::{whitelist, Tracker}; use crate::servers::http::v1::extractors::announce_request::ExtractRequest; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; @@ -39,6 +40,7 @@ use crate::CurrentClock; pub async fn handle_without_key( State(state): State<( Arc, + Arc, Arc, Arc, Arc>>, @@ -53,6 +55,7 @@ pub async fn handle_without_key( &state.1, &state.2, &state.3, + &state.4, &announce_request, &client_ip_sources, None, @@ -67,6 +70,7 @@ pub async fn handle_without_key( pub async fn handle_with_key( State(state): State<( Arc, + Arc, Arc, Arc, Arc>>, @@ -82,6 +86,7 @@ pub async fn handle_with_key( &state.1, &state.2, &state.3, + &state.4, &announce_request, &client_ip_sources, Some(key), @@ -93,8 +98,10 @@ pub async fn handle_with_key( /// /// Internal implementation that handles both the `authenticated` and /// `unauthenticated` modes. +#[allow(clippy::too_many_arguments)] async fn handle( tracker: &Arc, + announce_handler: &Arc, authentication_service: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, @@ -104,6 +111,7 @@ async fn handle( ) -> Response { let announce_data = match handle_announce( tracker, + announce_handler, authentication_service, whitelist_authorization, opt_stats_event_sender, @@ -125,8 +133,10 @@ async fn handle( See https://github.com/torrust/torrust-tracker/discussions/240. */ +#[allow(clippy::too_many_arguments)] async fn handle_announce( tracker: &Arc, + announce_handler: &Arc, authentication_service: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, @@ -168,6 +178,7 @@ async fn handle_announce( let announce_data = services::announce::invoke( tracker.clone(), + announce_handler.clone(), opt_stats_event_sender.clone(), announce_request.info_hash, &mut peer, @@ -244,6 +255,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; + use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::service::AuthenticationService; use crate::core::services::{initialize_tracker, statistics}; use crate::core::statistics::event::sender::Sender; @@ -251,6 +263,7 @@ mod tests { type TrackerAndDeps = ( Arc, + Arc, Arc>>, Arc, Arc, @@ -293,7 +306,19 @@ mod tests { &db_torrent_repository, )); - (tracker, stats_event_sender, whitelist_authorization, authentication_service) + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + ( + tracker, + announce_handler, + stats_event_sender, + whitelist_authorization, + authentication_service, + ) } fn sample_announce_request() -> Announce { @@ -336,7 +361,8 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_missing() { - let (tracker, stats_event_sender, whitelist_authorization, authentication_service) = private_tracker(); + let (tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + private_tracker(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -345,6 +371,7 @@ mod tests { let response = handle_announce( &tracker, + &announce_handler, &authentication_service, &whitelist_authorization, &stats_event_sender, @@ -363,7 +390,8 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_invalid() { - let (tracker, stats_event_sender, whitelist_authorization, authentication_service) = private_tracker(); + let (tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + private_tracker(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -374,6 +402,7 @@ mod tests { let response = handle_announce( &tracker, + &announce_handler, &authentication_service, &whitelist_authorization, &stats_event_sender, @@ -398,7 +427,8 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_announced_torrent_is_not_whitelisted() { - let (tracker, stats_event_sender, whitelist_authorization, authentication_service) = whitelisted_tracker(); + let (tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + whitelisted_tracker(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -407,6 +437,7 @@ mod tests { let response = handle_announce( &tracker, + &announce_handler, &authentication_service, &whitelist_authorization, &stats_event_sender, @@ -439,7 +470,8 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let (tracker, stats_event_sender, whitelist_authorization, authentication_service) = tracker_on_reverse_proxy(); + let (tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + tracker_on_reverse_proxy(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -451,6 +483,7 @@ mod tests { let response = handle_announce( &tracker, + &announce_handler, &authentication_service, &whitelist_authorization, &stats_event_sender, @@ -480,7 +513,8 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let (tracker, stats_event_sender, whitelist_authorization, authentication_service) = tracker_not_on_reverse_proxy(); + let (tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + tracker_not_on_reverse_proxy(); let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); @@ -492,6 +526,7 @@ mod tests { let response = handle_announce( &tracker, + &announce_handler, &authentication_service, &whitelist_authorization, &stats_event_sender, diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 0c0be5bd5..50e1494be 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -22,6 +22,7 @@ use tower_http::LatencyUnit; use tracing::{instrument, Level, Span}; use super::handlers::{announce, health_check, scrape}; +use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::service::AuthenticationService; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; @@ -36,6 +37,7 @@ use crate::servers::logging::Latency; #[allow(clippy::needless_pass_by_value)] #[instrument(skip( tracker, + announce_handler, scrape_handler, authentication_service, whitelist_authorization, @@ -44,6 +46,7 @@ use crate::servers::logging::Latency; ))] pub fn router( tracker: Arc, + announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, @@ -58,6 +61,7 @@ pub fn router( "/announce", get(announce::handle_without_key).with_state(( tracker.clone(), + announce_handler.clone(), authentication_service.clone(), whitelist_authorization.clone(), stats_event_sender.clone(), @@ -67,6 +71,7 @@ pub fn router( "/announce/{key}", get(announce::handle_with_key).with_state(( tracker.clone(), + announce_handler.clone(), authentication_service.clone(), whitelist_authorization.clone(), stats_event_sender.clone(), diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 9e381d8b2..2c88ebc60 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -15,9 +15,10 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; +use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::{self}; -use crate::core::{PeersWanted, Tracker}; +use crate::core::Tracker; /// The HTTP tracker `announce` service. /// @@ -30,7 +31,8 @@ use crate::core::{PeersWanted, Tracker}; /// > like the UDP tracker, the number of TCP connections is incremented for /// > each `announce` request. pub async fn invoke( - tracker: Arc, + _tracker: Arc, + announce_handler: Arc, opt_stats_event_sender: Arc>>, info_hash: InfoHash, peer: &mut peer::Peer, @@ -39,7 +41,7 @@ pub async fn invoke( let original_peer_ip = peer.peer_addr.ip(); // The tracker could change the original peer ip - let announce_data = tracker.announce(&info_hash, peer, &original_peer_ip, peers_wanted); + let announce_data = announce_handler.announce(&info_hash, peer, &original_peer_ip, peers_wanted); if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { match original_peer_ip { @@ -66,11 +68,13 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; + use crate::core::announce_handler::AnnounceHandler; use crate::core::services::{initialize_tracker, statistics}; use crate::core::statistics::event::sender::Sender; use crate::core::Tracker; - fn public_tracker() -> (Tracker, Arc>>) { + #[allow(clippy::type_complexity)] + fn public_tracker() -> (Arc, Arc, Arc>>) { let config = configuration::ephemeral_public(); let ( @@ -85,9 +89,19 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = initialize_tracker(&config, &in_memory_torrent_repository, &db_torrent_repository); + let tracker = Arc::new(initialize_tracker( + &config, + &in_memory_torrent_repository, + &db_torrent_repository, + )); - (tracker, stats_event_sender) + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + (tracker, announce_handler, stats_event_sender) } fn sample_info_hash() -> InfoHash { @@ -132,11 +146,12 @@ mod tests { use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; use crate::app_test::initialize_tracker_dependencies; - use crate::core::{statistics, PeersWanted, Tracker}; + use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; + use crate::core::{statistics, Tracker}; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; - fn test_tracker_factory() -> Tracker { + fn initialize_tracker_and_announce_handler() -> (Arc, Arc) { let config = configuration::ephemeral(); let ( @@ -149,19 +164,26 @@ mod tests { _torrents_manager, ) = initialize_tracker_dependencies(&config); - Tracker::new(&config.core, &in_memory_torrent_repository, &db_torrent_repository).unwrap() + let tracker = Arc::new(Tracker::new(&config.core, &in_memory_torrent_repository, &db_torrent_repository).unwrap()); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + (tracker, announce_handler) } #[tokio::test] async fn it_should_return_the_announce_data() { - let (tracker, stats_event_sender) = public_tracker(); - - let tracker = Arc::new(tracker); + let (tracker, announce_handler, stats_event_sender) = public_tracker(); let mut peer = sample_peer(); let announce_data = invoke( tracker.clone(), + announce_handler.clone(), stats_event_sender.clone(), sample_info_hash(), &mut peer, @@ -193,20 +215,28 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(test_tracker_factory()); + let (tracker, announce_handler) = initialize_tracker_and_announce_handler(); let mut peer = sample_peer_using_ipv4(); - let _announce_data = invoke(tracker, stats_event_sender, sample_info_hash(), &mut peer, &PeersWanted::All).await; + let _announce_data = invoke( + tracker, + announce_handler, + stats_event_sender, + sample_info_hash(), + &mut peer, + &PeersWanted::All, + ) + .await; } - fn tracker_with_an_ipv6_external_ip() -> Tracker { + fn tracker_with_an_ipv6_external_ip() -> (Arc, Arc) { let mut configuration = configuration::ephemeral(); configuration.core.net.external_ip = Some(IpAddr::V6(Ipv6Addr::new( 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, ))); - test_tracker_factory() + initialize_tracker_and_announce_handler() } fn peer_with_the_ipv4_loopback_ip() -> peer::Peer { @@ -233,8 +263,11 @@ mod tests { let mut peer = peer_with_the_ipv4_loopback_ip(); + let (tracker, announce_handler) = tracker_with_an_ipv6_external_ip(); + let _announce_data = invoke( - tracker_with_an_ipv6_external_ip().into(), + tracker, + announce_handler, stats_event_sender, sample_info_hash(), &mut peer, @@ -255,11 +288,19 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new(test_tracker_factory()); + let (tracker, announce_handler) = initialize_tracker_and_announce_handler(); let mut peer = sample_peer_using_ipv6(); - let _announce_data = invoke(tracker, stats_event_sender, sample_info_hash(), &mut peer, &PeersWanted::All).await; + let _announce_data = invoke( + tracker, + announce_handler, + stats_event_sender, + sample_info_hash(), + &mut peer, + &PeersWanted::All, + ) + .await; } } } diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index e3ee6560f..6df267d3a 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -81,11 +81,12 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; + use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::services::initialize_tracker; use crate::core::Tracker; - fn public_tracker_and_scrape_handler() -> (Arc, Arc) { + fn public_tracker_and_announce_and_scrape_handlers() -> (Arc, Arc, Arc) { let config = configuration::ephemeral_public(); let ( @@ -104,9 +105,15 @@ mod tests { &db_torrent_repository, )); + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, scrape_handler) + (tracker, announce_handler, scrape_handler) } fn sample_info_hashes() -> Vec { @@ -159,10 +166,12 @@ mod tests { use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::core::{statistics, PeersWanted}; + use crate::core::announce_handler::PeersWanted; + use crate::core::statistics; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ - public_tracker_and_scrape_handler, sample_info_hash, sample_info_hashes, sample_peer, test_tracker_factory, + public_tracker_and_announce_and_scrape_handlers, sample_info_hash, sample_info_hashes, sample_peer, + test_tracker_factory, }; #[tokio::test] @@ -170,7 +179,7 @@ mod tests { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); - let (tracker, scrape_handler) = public_tracker_and_scrape_handler(); + let (_tracker, announce_handler, scrape_handler) = public_tracker_and_announce_and_scrape_handlers(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; @@ -178,7 +187,7 @@ mod tests { // Announce a new peer to force scrape data to contain not zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); - tracker.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); + announce_handler.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); let scrape_data = invoke(&scrape_handler, &stats_event_sender, &info_hashes, &original_peer_ip).await; @@ -241,10 +250,11 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; - use crate::core::{statistics, PeersWanted}; + use crate::core::announce_handler::PeersWanted; + use crate::core::statistics; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ - public_tracker_and_scrape_handler, sample_info_hash, sample_info_hashes, sample_peer, + public_tracker_and_announce_and_scrape_handlers, sample_info_hash, sample_info_hashes, sample_peer, }; #[tokio::test] @@ -252,7 +262,7 @@ mod tests { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); - let (tracker, _scrape_handler) = public_tracker_and_scrape_handler(); + let (_tracker, announce_handler, _scrape_handler) = public_tracker_and_announce_and_scrape_handlers(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; @@ -260,7 +270,7 @@ mod tests { // Announce a new peer to force scrape data to contain not zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); - tracker.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); + announce_handler.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); let scrape_data = fake(&stats_event_sender, &info_hashes, &original_peer_ip).await; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index d6073d2e8..03a0248d4 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -20,9 +20,10 @@ use zerocopy::network_endian::I32; use super::connection_cookie::{check, make}; use super::server::banning::BanService; use super::RawRequest; +use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; -use crate::core::{statistics, whitelist, PeersWanted, Tracker}; +use crate::core::{statistics, whitelist, Tracker}; use crate::servers::udp::error::Error; use crate::servers::udp::{peer_builder, UDP_TRACKER_LOG_TARGET}; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; @@ -56,10 +57,11 @@ impl CookieTimeValues { /// /// It will return an `Error` response if the request is invalid. #[allow(clippy::too_many_arguments)] -#[instrument(fields(request_id), skip(udp_request, tracker, scrape_handler, whitelist_authorization, opt_stats_event_sender, cookie_time_values, ban_service), ret(level = Level::TRACE))] +#[instrument(fields(request_id), skip(udp_request, tracker, announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, cookie_time_values, ban_service), ret(level = Level::TRACE))] pub(crate) async fn handle_packet( udp_request: RawRequest, tracker: &Tracker, + announce_handler: &Arc, scrape_handler: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, @@ -80,6 +82,7 @@ pub(crate) async fn handle_packet( request, udp_request.from, tracker, + announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, @@ -137,10 +140,12 @@ pub(crate) async fn handle_packet( /// # Errors /// /// If a error happens in the `handle_request` function, it will just return the `ServerError`. +#[allow(clippy::too_many_arguments)] #[instrument(skip( request, remote_addr, tracker, + announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, @@ -150,6 +155,7 @@ pub async fn handle_request( request: Request, remote_addr: SocketAddr, tracker: &Tracker, + announce_handler: &Arc, scrape_handler: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, @@ -170,6 +176,7 @@ pub async fn handle_request( remote_addr, &announce_request, tracker, + announce_handler, whitelist_authorization, opt_stats_event_sender, cookie_time_values.valid_range, @@ -233,11 +240,12 @@ pub async fn handle_connect( /// # Errors /// /// If a error happens in the `handle_announce` function, it will just return the `ServerError`. -#[instrument(fields(transaction_id, connection_id, info_hash), skip(tracker, whitelist_authorization, opt_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id, info_hash), skip(tracker, announce_handler, whitelist_authorization, opt_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_announce( remote_addr: SocketAddr, request: &AnnounceRequest, tracker: &Tracker, + announce_handler: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, cookie_valid_range: Range, @@ -271,7 +279,7 @@ pub async fn handle_announce( let mut peer = peer_builder::from_request(request, &remote_client_ip); let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); - let response = tracker.announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted); + let response = announce_handler.announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted); if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { match remote_client_ip { @@ -490,6 +498,7 @@ mod tests { use super::gen_remote_fingerprint; use crate::app_test::initialize_tracker_dependencies; + use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::services::{initialize_tracker, initialize_whitelist_manager, statistics}; use crate::core::statistics::event::sender::Sender; @@ -501,6 +510,7 @@ mod tests { type TrackerAndDeps = ( Arc, + Arc, Arc, Arc, Arc>>, @@ -546,10 +556,17 @@ mod tests { &db_torrent_repository, )); + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); ( tracker, + announce_handler, scrape_handler, in_memory_torrent_repository, stats_event_sender, @@ -653,7 +670,12 @@ mod tests { } } - fn test_tracker_factory() -> (Arc, Arc, Arc) { + fn test_tracker_factory() -> ( + Arc, + Arc, + Arc, + Arc, + ) { let config = tracker_configuration(); let ( @@ -668,9 +690,15 @@ mod tests { let tracker = Arc::new(Tracker::new(&config.core, &in_memory_torrent_repository, &db_torrent_repository).unwrap()); + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, scrape_handler, whitelist_authorization) + (tracker, announce_handler, scrape_handler, whitelist_authorization) } mod connect_request { @@ -883,6 +911,7 @@ mod tests { }; use mockall::predicate::eq; + use crate::core::announce_handler::AnnounceHandler; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::{self, statistics, whitelist}; use crate::servers::udp::connection_cookie::make; @@ -897,6 +926,7 @@ mod tests { async fn an_announced_peer_should_be_added_to_the_tracker() { let ( tracker, + announce_handler, _scrape_handler, in_memory_torrent_repository, stats_event_sender, @@ -924,6 +954,7 @@ mod tests { remote_addr, &request, &tracker, + &announce_handler, &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), @@ -945,6 +976,7 @@ mod tests { async fn the_announced_peer_should_not_be_included_in_the_response() { let ( tracker, + announce_handler, _scrape_handler, _in_memory_torrent_repository, stats_event_sender, @@ -963,6 +995,7 @@ mod tests { remote_addr, &request, &tracker, + &announce_handler, &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), @@ -993,6 +1026,7 @@ mod tests { let ( tracker, + announce_handler, _scrape_handler, in_memory_torrent_repository, stats_event_sender, @@ -1023,6 +1057,7 @@ mod tests { remote_addr, &request, &tracker, + &announce_handler, &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), @@ -1053,6 +1088,7 @@ mod tests { async fn announce_a_new_peer_using_ipv4( tracker: Arc, + announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); @@ -1067,6 +1103,7 @@ mod tests { remote_addr, &request, &tracker, + &announce_handler, &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), @@ -1079,6 +1116,7 @@ mod tests { async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { let ( tracker, + announce_handler, _scrape_handler, in_memory_torrent_repository, _stats_event_sender, @@ -1089,7 +1127,8 @@ mod tests { add_a_torrent_peer_using_ipv6(&in_memory_torrent_repository); - let response = announce_a_new_peer_using_ipv4(tracker.clone(), whitelist_authorization).await; + let response = + announce_a_new_peer_using_ipv4(tracker.clone(), announce_handler.clone(), whitelist_authorization).await; // The response should not contain the peer using IPV6 let peers: Option>> = match response { @@ -1111,12 +1150,13 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (tracker, _scrape_handler, whitelist_authorization) = test_tracker_factory(); + let (tracker, announce_handler, _scrape_handler, whitelist_authorization) = test_tracker_factory(); handle_announce( sample_ipv4_socket_address(), &AnnounceRequestBuilder::default().into(), &tracker, + &announce_handler, &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), @@ -1142,6 +1182,7 @@ mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { let ( tracker, + announce_handler, _scrape_handler, in_memory_torrent_repository, stats_event_sender, @@ -1169,6 +1210,7 @@ mod tests { remote_addr, &request, &tracker, + &announce_handler, &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), @@ -1202,6 +1244,7 @@ mod tests { }; use mockall::predicate::eq; + use crate::core::announce_handler::AnnounceHandler; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::{self, statistics, whitelist}; use crate::servers::udp::connection_cookie::make; @@ -1216,6 +1259,7 @@ mod tests { async fn an_announced_peer_should_be_added_to_the_tracker() { let ( tracker, + announce_handler, _scrape_handler, in_memory_torrent_repository, stats_event_sender, @@ -1244,6 +1288,7 @@ mod tests { remote_addr, &request, &tracker, + &announce_handler, &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), @@ -1265,6 +1310,7 @@ mod tests { async fn the_announced_peer_should_not_be_included_in_the_response() { let ( tracker, + announce_handler, _scrape_handler, _in_memory_torrent_repository, stats_event_sender, @@ -1286,6 +1332,7 @@ mod tests { remote_addr, &request, &tracker, + &announce_handler, &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), @@ -1316,6 +1363,7 @@ mod tests { let ( tracker, + announce_handler, _scrape_handler, in_memory_torrent_repository, stats_event_sender, @@ -1346,6 +1394,7 @@ mod tests { remote_addr, &request, &tracker, + &announce_handler, &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), @@ -1376,6 +1425,7 @@ mod tests { async fn announce_a_new_peer_using_ipv6( tracker: Arc, + announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); @@ -1393,6 +1443,7 @@ mod tests { remote_addr, &request, &tracker, + &announce_handler, &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), @@ -1405,6 +1456,7 @@ mod tests { async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { let ( tracker, + announce_handler, _scrape_handler, in_memory_torrent_repository, _stats_event_sender, @@ -1415,7 +1467,8 @@ mod tests { add_a_torrent_peer_using_ipv4(&in_memory_torrent_repository); - let response = announce_a_new_peer_using_ipv6(tracker.clone(), whitelist_authorization).await; + let response = + announce_a_new_peer_using_ipv6(tracker.clone(), announce_handler.clone(), whitelist_authorization).await; // The response should not contain the peer using IPV4 let peers: Option>> = match response { @@ -1437,7 +1490,7 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (tracker, _scrape_handler, whitelist_authorization) = test_tracker_factory(); + let (tracker, announce_handler, _scrape_handler, whitelist_authorization) = test_tracker_factory(); let remote_addr = sample_ipv6_remote_addr(); @@ -1449,6 +1502,7 @@ mod tests { remote_addr, &announce_request, &tracker, + &announce_handler, &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), @@ -1466,6 +1520,7 @@ mod tests { use mockall::predicate::eq; use crate::app_test::initialize_tracker_dependencies; + use crate::core::announce_handler::AnnounceHandler; use crate::core::{self, statistics}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; @@ -1501,6 +1556,12 @@ mod tests { core::Tracker::new(&config.core, &in_memory_torrent_repository, &db_torrent_repository).unwrap(), ); + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); @@ -1525,6 +1586,7 @@ mod tests { remote_addr, &request, &tracker, + &announce_handler, &whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), @@ -1580,6 +1642,7 @@ mod tests { async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { let ( _tracker, + _announce_handler, scrape_handler, _in_memory_torrent_repository, stats_event_sender, @@ -1688,6 +1751,7 @@ mod tests { async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { let ( _tracker, + _announce_handler, scrape_handler, in_memory_torrent_repository, _stats_event_sender, @@ -1723,6 +1787,7 @@ mod tests { async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { let ( _tracker, + _announce_handler, scrape_handler, in_memory_torrent_repository, stats_event_sender, @@ -1766,6 +1831,7 @@ mod tests { async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { let ( _tracker, + _announce_handler, scrape_handler, in_memory_torrent_repository, stats_event_sender, @@ -1837,7 +1903,7 @@ mod tests { let remote_addr = sample_ipv4_remote_addr(); - let (_tracker, scrape_handler, _whitelist_authorization) = test_tracker_factory(); + let (_tracker, _announce_handler, scrape_handler, _whitelist_authorization) = test_tracker_factory(); handle_scrape( remote_addr, @@ -1877,7 +1943,7 @@ mod tests { let remote_addr = sample_ipv6_remote_addr(); - let (_tracker, scrape_handler, _whitelist_authorization) = test_tracker_factory(); + let (_tracker, _announce_handler, scrape_handler, _whitelist_authorization) = test_tracker_factory(); handle_scrape( remote_addr, diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index d6bc230e1..f1d0e4859 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -13,6 +13,7 @@ use tracing::instrument; use super::banning::BanService; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; +use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::{statistics, whitelist, Tracker}; @@ -44,6 +45,7 @@ impl Launcher { #[allow(clippy::too_many_arguments)] #[instrument(skip( tracker, + announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, @@ -54,6 +56,7 @@ impl Launcher { ))] pub async fn run_with_graceful_shutdown( tracker: Arc, + announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, @@ -98,6 +101,7 @@ impl Launcher { let () = Self::run_udp_server_main( receiver, tracker.clone(), + announce_handler.clone(), scrape_handler.clone(), whitelist_authorization.clone(), opt_stats_event_sender.clone(), @@ -141,9 +145,11 @@ impl Launcher { ServiceHealthCheckJob::new(binding, info, job) } + #[allow(clippy::too_many_arguments)] #[instrument(skip( receiver, tracker, + announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, @@ -152,6 +158,7 @@ impl Launcher { async fn run_udp_server_main( mut receiver: Receiver, tracker: Arc, + announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, @@ -224,6 +231,7 @@ impl Launcher { let processor = Processor::new( receiver.socket.clone(), tracker.clone(), + announce_handler.clone(), scrape_handler.clone(), whitelist_authorization.clone(), opt_stats_event_sender.clone(), diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 668265752..53ba588d4 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -83,6 +83,7 @@ mod tests { let started = stopped .start( app_container.tracker, + app_container.announce_handler, app_container.scrape_handler, app_container.whitelist_authorization, app_container.stats_event_sender, @@ -117,6 +118,7 @@ mod tests { let started = stopped .start( app_container.tracker, + app_container.announce_handler, app_container.scrape_handler, app_container.whitelist_authorization, app_container.stats_event_sender, diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 889a2a913..4cecbc36a 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -10,6 +10,7 @@ use tracing::{instrument, Level}; use super::banning::BanService; use super::bound_socket::BoundSocket; +use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::event::UdpResponseKind; @@ -20,6 +21,7 @@ use crate::servers::udp::{handlers, RawRequest}; pub struct Processor { socket: Arc, tracker: Arc, + announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, @@ -30,6 +32,7 @@ impl Processor { pub fn new( socket: Arc, tracker: Arc, + announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, @@ -38,6 +41,7 @@ impl Processor { Self { socket, tracker, + announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, @@ -54,6 +58,7 @@ impl Processor { let response = handlers::handle_packet( request, &self.tracker, + &self.announce_handler, &self.scrape_handler, &self.whitelist_authorization, &self.opt_stats_event_sender, diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index 82fd808c4..ea12b1c0b 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -11,6 +11,7 @@ use tokio::task::JoinHandle; use super::banning::BanService; use super::launcher::Launcher; use crate::bootstrap::jobs::Started; +use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::{whitelist, Tracker}; @@ -32,6 +33,7 @@ impl Spawner { pub fn spawn_launcher( &self, tracker: Arc, + announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, @@ -45,6 +47,7 @@ impl Spawner { tokio::spawn(async move { Launcher::run_with_graceful_shutdown( tracker, + announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index d2c91b03d..bab04fdcc 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -13,6 +13,7 @@ use super::banning::BanService; use super::spawner::Spawner; use super::{Server, UdpError}; use crate::bootstrap::jobs::Started; +use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::{whitelist, Tracker}; @@ -66,10 +67,11 @@ impl Server { /// /// It panics if unable to receive the bound socket address from service. #[allow(clippy::too_many_arguments)] - #[instrument(skip(self, tracker, scrape_handler, whitelist_authorization, opt_stats_event_sender, ban_service, form), err, ret(Display, level = Level::INFO))] + #[instrument(skip(self, tracker, announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, ban_service, form), err, ret(Display, level = Level::INFO))] pub async fn start( self, tracker: Arc, + announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, @@ -85,6 +87,7 @@ impl Server { // May need to wrap in a task to about a tokio bug. let task = self.state.spawner.spawn_launcher( tracker, + announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index beaf2d38c..78051cbbb 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -5,6 +5,7 @@ use futures::executor::block_on; use torrust_tracker_configuration::{Configuration, HttpTracker}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; +use torrust_tracker_lib::core::announce_handler::AnnounceHandler; use torrust_tracker_lib::core::authentication::handler::KeysHandler; use torrust_tracker_lib::core::authentication::service::AuthenticationService; use torrust_tracker_lib::core::databases::Database; @@ -22,6 +23,7 @@ pub struct Environment { pub config: Arc, pub database: Arc>, pub tracker: Arc, + pub announce_handler: Arc, pub scrape_handler: Arc, pub in_memory_torrent_repository: Arc, pub keys_handler: Arc, @@ -65,6 +67,7 @@ impl Environment { config, database: app_container.database.clone(), tracker: app_container.tracker.clone(), + announce_handler: app_container.announce_handler.clone(), scrape_handler: app_container.scrape_handler.clone(), in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), keys_handler: app_container.keys_handler.clone(), @@ -84,6 +87,7 @@ impl Environment { config: self.config, database: self.database.clone(), tracker: self.tracker.clone(), + announce_handler: self.announce_handler.clone(), scrape_handler: self.scrape_handler.clone(), in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), keys_handler: self.keys_handler.clone(), @@ -97,6 +101,7 @@ impl Environment { .server .start( self.tracker, + self.announce_handler, self.scrape_handler, self.authentication_service, self.whitelist_authorization, @@ -119,6 +124,7 @@ impl Environment { config: self.config, database: self.database, tracker: self.tracker, + announce_handler: self.announce_handler, scrape_handler: self.scrape_handler, in_memory_torrent_repository: self.in_memory_torrent_repository, keys_handler: self.keys_handler, diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 09714146d..fafb7ef7a 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -5,6 +5,7 @@ use bittorrent_primitives::info_hash::InfoHash; use tokio::sync::RwLock; use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; +use torrust_tracker_lib::core::announce_handler::AnnounceHandler; use torrust_tracker_lib::core::databases::Database; use torrust_tracker_lib::core::scrape_handler::ScrapeHandler; use torrust_tracker_lib::core::statistics::event::sender::Sender; @@ -26,6 +27,7 @@ where pub database: Arc>, pub tracker: Arc, pub in_memory_torrent_repository: Arc, + pub announce_handler: Arc, pub scrape_handler: Arc, pub whitelist_authorization: Arc, pub stats_event_sender: Arc>>, @@ -66,6 +68,7 @@ impl Environment { database: app_container.database.clone(), tracker: app_container.tracker.clone(), in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), + announce_handler: app_container.announce_handler.clone(), scrape_handler: app_container.scrape_handler.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), stats_event_sender: app_container.stats_event_sender.clone(), @@ -84,6 +87,7 @@ impl Environment { database: self.database.clone(), tracker: self.tracker.clone(), in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), + announce_handler: self.announce_handler.clone(), scrape_handler: self.scrape_handler.clone(), whitelist_authorization: self.whitelist_authorization.clone(), stats_event_sender: self.stats_event_sender.clone(), @@ -94,6 +98,7 @@ impl Environment { .server .start( self.tracker, + self.announce_handler, self.scrape_handler, self.whitelist_authorization, self.stats_event_sender, @@ -125,6 +130,7 @@ impl Environment { database: self.database, tracker: self.tracker, in_memory_torrent_repository: self.in_memory_torrent_repository, + announce_handler: self.announce_handler, scrape_handler: self.scrape_handler, whitelist_authorization: self.whitelist_authorization, stats_event_sender: self.stats_event_sender, From 209b52c0511a9b69e47a1a45f60310f5ae040723 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 27 Jan 2025 13:53:48 +0000 Subject: [PATCH 0656/1297] refactor: [#1207] inline methods --- src/app.rs | 6 +++--- src/core/mod.rs | 20 +------------------- 2 files changed, 4 insertions(+), 22 deletions(-) diff --git a/src/app.rs b/src/app.rs index 00414bc10..aafae5ebf 100644 --- a/src/app.rs +++ b/src/app.rs @@ -50,7 +50,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< let registar = Registar::default(); // Load peer keys - if app_container.tracker.is_private() { + if config.core.private { app_container .keys_handler .load_keys_from_database() @@ -59,7 +59,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< } // Load whitelisted torrents - if app_container.tracker.is_listed() { + if config.core.listed { app_container .whitelist_manager .load_whitelist_from_database() @@ -70,7 +70,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< // Start the UDP blocks if let Some(udp_trackers) = &config.udp_trackers { for udp_tracker_config in udp_trackers { - if app_container.tracker.is_private() { + if config.core.private { tracing::warn!( "Could not start UDP tracker on: {} while in private mode. UDP is not safe for private trackers!", udp_tracker_config.bind_address diff --git a/src/core/mod.rs b/src/core/mod.rs index 2151ec1ef..ae728dc12 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -496,28 +496,10 @@ impl Tracker { }) } - /// Returns `true` is the tracker is in public mode. - #[must_use] - pub fn is_public(&self) -> bool { - !self.config.private - } - - /// Returns `true` is the tracker is in private mode. - #[must_use] - pub fn is_private(&self) -> bool { - self.config.private - } - - /// Returns `true` is the tracker is in whitelisted mode. - #[must_use] - pub fn is_listed(&self) -> bool { - self.config.listed - } - /// Returns `true` if the tracker requires authentication. #[must_use] pub fn requires_authentication(&self) -> bool { - self.is_private() + self.config.private } /// Returns `true` is the tracker is in whitelisted mode. From 2f74cafda7ee3cbc5c1030da448aca7664e8972c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 27 Jan 2025 14:08:01 +0000 Subject: [PATCH 0657/1297] chore: fix linting errors --- packages/configuration/src/lib.rs | 2 +- packages/configuration/src/v2_0_0/mod.rs | 12 ++++++------ packages/http-protocol/src/v1/requests/announce.rs | 4 ++-- packages/http-protocol/src/v1/requests/mod.rs | 3 --- packages/http-protocol/src/v1/responses/announce.rs | 2 +- packages/http-protocol/src/v1/responses/error.rs | 4 ++-- packages/http-protocol/src/v1/responses/mod.rs | 3 --- packages/http-protocol/src/v1/responses/scrape.rs | 2 +- src/core/mod.rs | 6 +++--- src/servers/http/v1/services/announce.rs | 5 ++--- 10 files changed, 18 insertions(+), 25 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 1ab3479fa..7e384297d 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -3,7 +3,7 @@ //! This module contains the configuration data structures for the //! Torrust Tracker, which is a `BitTorrent` tracker server. //! -//! The current version for configuration is [`v2`]. +//! The current version for configuration is [`v2_0_0`]. pub mod v2_0_0; pub mod validator; diff --git a/packages/configuration/src/v2_0_0/mod.rs b/packages/configuration/src/v2_0_0/mod.rs index 5067210bb..fd742d8d2 100644 --- a/packages/configuration/src/v2_0_0/mod.rs +++ b/packages/configuration/src/v2_0_0/mod.rs @@ -39,11 +39,11 @@ //! Please refer to the documentation of each structure for more information //! about each section. //! -//! - [`Core configuration`](crate::v2::Configuration) -//! - [`HTTP API configuration`](crate::v2::tracker_api::HttpApi) -//! - [`HTTP Tracker configuration`](crate::v2::http_tracker::HttpTracker) -//! - [`UDP Tracker configuration`](crate::v2::udp_tracker::UdpTracker) -//! - [`Health Check API configuration`](crate::v2::health_check_api::HealthCheckApi) +//! - [`Core configuration`](crate::v2_0_0::Configuration) +//! - [`HTTP API configuration`](crate::v2_0_0::tracker_api::HttpApi) +//! - [`HTTP Tracker configuration`](crate::v2_0_0::http_tracker::HttpTracker) +//! - [`UDP Tracker configuration`](crate::v2_0_0::udp_tracker::UdpTracker) +//! - [`Health Check API configuration`](crate::v2_0_0::health_check_api::HealthCheckApi) //! //! ## Port binding //! @@ -78,7 +78,7 @@ //! //! Alternatively, you could setup a reverse proxy like Nginx or Apache to //! handle the SSL/TLS part and forward the requests to the tracker. If you do -//! that, you should set [`on_reverse_proxy`](crate::v2::network::Network::on_reverse_proxy) +//! that, you should set [`on_reverse_proxy`](crate::v2_0_0::network::Network::on_reverse_proxy) //! to `true` in the configuration file. It's out of scope for this //! documentation to explain in detail how to setup a reverse proxy, but the //! configuration file should be something like this: diff --git a/packages/http-protocol/src/v1/requests/announce.rs b/packages/http-protocol/src/v1/requests/announce.rs index ea76771dd..9bde7ec13 100644 --- a/packages/http-protocol/src/v1/requests/announce.rs +++ b/packages/http-protocol/src/v1/requests/announce.rs @@ -185,8 +185,8 @@ impl fmt::Display for Event { /// Depending on the value of this param, the tracker will return a different /// response: /// -/// - [`Normal`](crate::servers::http::v1::responses::announce::Normal), i.e. a `non-compact` response. -/// - [`Compact`](crate::servers::http::v1::responses::announce::Compact) response. +/// - [`Normal`](crate::v1::responses::announce::Normal), i.e. a `non-compact` response. +/// - [`Compact`](crate::v1::responses::announce::Compact) response. /// /// Refer to [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) #[derive(PartialEq, Debug)] diff --git a/packages/http-protocol/src/v1/requests/mod.rs b/packages/http-protocol/src/v1/requests/mod.rs index ee34ca72a..d19bd78d3 100644 --- a/packages/http-protocol/src/v1/requests/mod.rs +++ b/packages/http-protocol/src/v1/requests/mod.rs @@ -1,6 +1,3 @@ //! HTTP requests for the HTTP tracker. -//! -//! Refer to the generic [HTTP server documentation](crate::servers::http) for -//! more information about the HTTP tracker. pub mod announce; pub mod scrape; diff --git a/packages/http-protocol/src/v1/responses/announce.rs b/packages/http-protocol/src/v1/responses/announce.rs index 3854c9f34..df187fdd1 100644 --- a/packages/http-protocol/src/v1/responses/announce.rs +++ b/packages/http-protocol/src/v1/responses/announce.rs @@ -1,4 +1,4 @@ -//! `Announce` response for the HTTP tracker [`announce`](bittorrent_http_protocol::v1::requests::announce::Announce) request. +//! `Announce` response for the HTTP tracker [`announce`](crate::v1::requests::announce::Announce) request. //! //! Data structures and logic to build the `announce` response. use std::io::Write; diff --git a/packages/http-protocol/src/v1/responses/error.rs b/packages/http-protocol/src/v1/responses/error.rs index 7516cd39e..f939ce298 100644 --- a/packages/http-protocol/src/v1/responses/error.rs +++ b/packages/http-protocol/src/v1/responses/error.rs @@ -1,4 +1,4 @@ -//! `Error` response for the [`HTTP tracker`](crate::servers::http). +//! `Error` response for the HTTP tracker. //! //! Data structures and logic to build the error responses. //! @@ -15,7 +15,7 @@ use serde::Serialize; use crate::v1::services::peer_ip_resolver::PeerIpResolutionError; -/// `Error` response for the [`HTTP tracker`](crate::servers::http). +/// `Error` response for the HTTP tracker. #[derive(Serialize, Debug, PartialEq)] pub struct Error { /// Human readable string which explains why the request failed. diff --git a/packages/http-protocol/src/v1/responses/mod.rs b/packages/http-protocol/src/v1/responses/mod.rs index 495b1eb84..e704d8908 100644 --- a/packages/http-protocol/src/v1/responses/mod.rs +++ b/packages/http-protocol/src/v1/responses/mod.rs @@ -1,7 +1,4 @@ //! HTTP responses for the HTTP tracker. -//! -//! Refer to the generic [HTTP server documentation](crate::servers::http) for -//! more information about the HTTP tracker. pub mod announce; pub mod error; pub mod scrape; diff --git a/packages/http-protocol/src/v1/responses/scrape.rs b/packages/http-protocol/src/v1/responses/scrape.rs index ee4c4155b..6b4dcc793 100644 --- a/packages/http-protocol/src/v1/responses/scrape.rs +++ b/packages/http-protocol/src/v1/responses/scrape.rs @@ -1,4 +1,4 @@ -//! `Scrape` response for the HTTP tracker [`scrape`](bittorrent_http_protocol::v1::requests::scrape::Scrape) request. +//! `Scrape` response for the HTTP tracker [`scrape`](crate::v1::requests::scrape::Scrape) request. //! //! Data structures and logic to build the `scrape` response. use std::borrow::Cow; diff --git a/src/core/mod.rs b/src/core/mod.rs index ae728dc12..d30c47c6d 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -52,7 +52,7 @@ //! The tracker responds to the peer with the list of other peers in the swarm so that //! the peer can contact them to start downloading pieces of the file from them. //! -//! Once you have instantiated the `Tracker` you can `announce` a new [`peer::Peer`] with: +//! Once you have instantiated the `AnnounceHandler` you can `announce` a new [`peer::Peer`](torrust_tracker_primitives::peer::Peer) with: //! //! ```rust,no_run //! use std::net::SocketAddr; @@ -81,7 +81,7 @@ //! ``` //! //! ```text -//! let announce_data = tracker.announce(&info_hash, &mut peer, &peer_ip).await; +//! let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip).await; //! ``` //! //! The `Tracker` returns the list of peers for the torrent with the infohash `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`, @@ -306,7 +306,7 @@ //! `c1277613db1d28709b034a017ab2cae4be07ae10` is the torrent infohash and `completed` contains the number of peers //! that have a full version of the torrent data, also known as seeders. //! -//! Refer to [`peer`] module for more information about peers. +//! Refer to [`peer`](torrust_tracker_primitives::peer) for more information about peers. //! //! # Configuration //! diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 2c88ebc60..1923037b3 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -2,9 +2,8 @@ //! //! The service is responsible for handling the `announce` requests. //! -//! It delegates the `announce` logic to the [`Tracker`](crate::core::Tracker::announce) -//! and it returns the [`AnnounceData`] returned -//! by the [`Tracker`]. +//! It delegates the `announce` logic to the [`AnnounceHandler`] and it returns +//! the [`AnnounceData`]. //! //! It also sends an [`statistics::event::Event`] //! because events are specific for the HTTP tracker. From 85a2a2969f29d1287da280f99d6f62b90dcb490e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 27 Jan 2025 16:37:06 +0000 Subject: [PATCH 0658/1297] refactor: [#1209] inline core Tracker methods --- src/app.rs | 4 + src/bootstrap/jobs/http_tracker.rs | 7 +- src/bootstrap/jobs/udp_tracker.rs | 4 +- src/core/mod.rs | 31 +------- src/servers/http/server.rs | 6 ++ src/servers/http/v1/handlers/announce.rs | 47 ++++++++---- src/servers/http/v1/handlers/scrape.rs | 77 ++++++++++++++++--- src/servers/http/v1/routes.rs | 8 +- src/servers/http/v1/services/announce.rs | 11 ++- src/servers/udp/handlers.rs | 96 ++++++++++++++++++++---- src/servers/udp/server/launcher.rs | 7 +- src/servers/udp/server/mod.rs | 2 + src/servers/udp/server/processor.rs | 6 ++ src/servers/udp/server/spawner.rs | 3 + src/servers/udp/server/states.rs | 3 + tests/servers/http/environment.rs | 15 ++-- tests/servers/http/v1/contract.rs | 10 +-- tests/servers/udp/environment.rs | 7 +- 18 files changed, 255 insertions(+), 89 deletions(-) diff --git a/src/app.rs b/src/app.rs index aafae5ebf..54ccbc60c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -21,6 +21,8 @@ //! - UDP trackers: the user can enable multiple UDP tracker on several ports. //! - HTTP trackers: the user can enable multiple HTTP tracker on several ports. //! - Tracker REST API: the tracker API can be enabled/disabled. +use std::sync::Arc; + use tokio::task::JoinHandle; use torrust_tracker_configuration::Configuration; use tracing::instrument; @@ -78,6 +80,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< } else { jobs.push( udp_tracker::start_job( + Arc::new(config.core.clone()), udp_tracker_config, app_container.tracker.clone(), app_container.announce_handler.clone(), @@ -100,6 +103,7 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< for http_tracker_config in http_trackers { if let Some(job) = http_tracker::start_job( http_tracker_config, + Arc::new(config.core.clone()), app_container.tracker.clone(), app_container.announce_handler.clone(), app_container.scrape_handler.clone(), diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 5da7da739..5767f30ce 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -15,7 +15,7 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; -use torrust_tracker_configuration::HttpTracker; +use torrust_tracker_configuration::{Core, HttpTracker}; use tracing::instrument; use super::make_rust_tls; @@ -49,6 +49,7 @@ use crate::servers::registar::ServiceRegistrationForm; ))] pub async fn start_job( config: &HttpTracker, + core_config: Arc, tracker: Arc, announce_handler: Arc, scrape_handler: Arc, @@ -69,6 +70,7 @@ pub async fn start_job( start_v1( socket, tls, + core_config.clone(), tracker.clone(), announce_handler.clone(), scrape_handler.clone(), @@ -97,6 +99,7 @@ pub async fn start_job( async fn start_v1( socket: SocketAddr, tls: Option, + config: Arc, tracker: Arc, announce_handler: Arc, scrape_handler: Arc, @@ -107,6 +110,7 @@ async fn start_v1( ) -> JoinHandle<()> { let server = HttpServer::new(Launcher::new(socket, tls)) .start( + config, tracker, announce_handler, scrape_handler, @@ -156,6 +160,7 @@ mod tests { start_job( config, + Arc::new(cfg.core.clone()), app_container.tracker, app_container.announce_handler, app_container.scrape_handler, diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index d43c1c930..36f3cd7b0 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -10,7 +10,7 @@ use std::sync::Arc; use tokio::sync::RwLock; use tokio::task::JoinHandle; -use torrust_tracker_configuration::UdpTracker; +use torrust_tracker_configuration::{Core, UdpTracker}; use tracing::instrument; use crate::core::announce_handler::AnnounceHandler; @@ -46,6 +46,7 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; form ))] pub async fn start_job( + core_config: Arc, config: &UdpTracker, tracker: Arc, announce_handler: Arc, @@ -60,6 +61,7 @@ pub async fn start_job( let server = Server::new(Spawner::new(bind_to)) .start( + core_config, tracker, announce_handler, scrape_handler, diff --git a/src/core/mod.rs b/src/core/mod.rs index d30c47c6d..43a2aa11d 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -451,12 +451,11 @@ pub mod whitelist; pub mod peer_tests; -use std::net::IpAddr; use std::sync::Arc; use torrent::repository::in_memory::InMemoryTorrentRepository; use torrent::repository::persisted::DatabasePersistentTorrentRepository; -use torrust_tracker_configuration::{AnnouncePolicy, Core}; +use torrust_tracker_configuration::Core; /// The domain layer tracker service. /// @@ -469,7 +468,7 @@ use torrust_tracker_configuration::{AnnouncePolicy, Core}; /// > the network layer. pub struct Tracker { /// The tracker configuration. - config: Core, + _core_config: Core, /// The in-memory torrents repository. _in_memory_torrent_repository: Arc, @@ -485,38 +484,16 @@ impl Tracker { /// /// Will return a `databases::error::Error` if unable to connect to database. The `Tracker` is responsible for the persistence. pub fn new( - config: &Core, + core_config: &Core, in_memory_torrent_repository: &Arc, db_torrent_repository: &Arc, ) -> Result { Ok(Tracker { - config: config.clone(), + _core_config: core_config.clone(), _in_memory_torrent_repository: in_memory_torrent_repository.clone(), _db_torrent_repository: db_torrent_repository.clone(), }) } - - /// Returns `true` if the tracker requires authentication. - #[must_use] - pub fn requires_authentication(&self) -> bool { - self.config.private - } - - /// Returns `true` is the tracker is in whitelisted mode. - #[must_use] - pub fn is_behind_reverse_proxy(&self) -> bool { - self.config.net.on_reverse_proxy - } - - #[must_use] - pub fn get_announce_policy(&self) -> AnnouncePolicy { - self.config.announce_policy - } - - #[must_use] - pub fn get_maybe_external_ip(&self) -> Option { - self.config.net.external_ip - } } #[cfg(test)] diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 3bb49c1ad..3817882df 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -7,6 +7,7 @@ use axum_server::Handle; use derive_more::Constructor; use futures::future::BoxFuture; use tokio::sync::oneshot::{Receiver, Sender}; +use torrust_tracker_configuration::Core; use tracing::instrument; use super::v1::routes::router; @@ -59,6 +60,7 @@ impl Launcher { ))] fn start( &self, + config: Arc, tracker: Arc, announce_handler: Arc, scrape_handler: Arc, @@ -85,6 +87,7 @@ impl Launcher { tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{}", address); let app = router( + config, tracker, announce_handler, scrape_handler, @@ -188,6 +191,7 @@ impl HttpServer { #[allow(clippy::too_many_arguments)] pub async fn start( self, + core_config: Arc, tracker: Arc, announce_handler: Arc, scrape_handler: Arc, @@ -203,6 +207,7 @@ impl HttpServer { let task = tokio::spawn(async move { let server = launcher.start( + core_config, tracker, announce_handler, scrape_handler, @@ -309,6 +314,7 @@ mod tests { let stopped = HttpServer::new(Launcher::new(bind_to, tls)); let started = stopped .start( + Arc::new(cfg.core.clone()), app_container.tracker, app_container.announce_handler, app_container.scrape_handler, diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 39ddd1710..ebdb717c3 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -18,6 +18,7 @@ use bittorrent_http_protocol::v1::services::peer_ip_resolver; use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; use hyper::StatusCode; use torrust_tracker_clock::clock::Time; +use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; @@ -39,6 +40,7 @@ use crate::CurrentClock; #[allow(clippy::type_complexity)] pub async fn handle_without_key( State(state): State<( + Arc, Arc, Arc, Arc, @@ -56,6 +58,7 @@ pub async fn handle_without_key( &state.2, &state.3, &state.4, + &state.5, &announce_request, &client_ip_sources, None, @@ -69,6 +72,7 @@ pub async fn handle_without_key( #[allow(clippy::type_complexity)] pub async fn handle_with_key( State(state): State<( + Arc, Arc, Arc, Arc, @@ -87,6 +91,7 @@ pub async fn handle_with_key( &state.2, &state.3, &state.4, + &state.5, &announce_request, &client_ip_sources, Some(key), @@ -100,6 +105,7 @@ pub async fn handle_with_key( /// `unauthenticated` modes. #[allow(clippy::too_many_arguments)] async fn handle( + config: &Arc, tracker: &Arc, announce_handler: &Arc, authentication_service: &Arc, @@ -110,6 +116,7 @@ async fn handle( maybe_key: Option, ) -> Response { let announce_data = match handle_announce( + config, tracker, announce_handler, authentication_service, @@ -135,6 +142,7 @@ async fn handle( #[allow(clippy::too_many_arguments)] async fn handle_announce( + core_config: &Arc, tracker: &Arc, announce_handler: &Arc, authentication_service: &Arc, @@ -145,7 +153,7 @@ async fn handle_announce( maybe_key: Option, ) -> Result { // Authentication - if tracker.requires_authentication() { + if core_config.private { match maybe_key { Some(key) => match authentication_service.authenticate(&key).await { Ok(()) => (), @@ -165,7 +173,7 @@ async fn handle_announce( Err(error) => return Err(responses::error::Error::from(error)), } - let peer_ip = match peer_ip_resolver::invoke(tracker.is_behind_reverse_proxy(), client_ip_sources) { + let peer_ip = match peer_ip_resolver::invoke(core_config.net.on_reverse_proxy, client_ip_sources) { Ok(peer_ip) => peer_ip, Err(error) => return Err(responses::error::Error::from(error)), }; @@ -251,7 +259,7 @@ mod tests { use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_configuration::Configuration; + use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; @@ -262,6 +270,7 @@ mod tests { use crate::core::{whitelist, Tracker}; type TrackerAndDeps = ( + Arc, Arc, Arc, Arc>>, @@ -270,23 +279,23 @@ mod tests { ); fn private_tracker() -> TrackerAndDeps { - initialize_tracker_and_deps(&configuration::ephemeral_private()) + initialize_tracker_and_deps(configuration::ephemeral_private()) } fn whitelisted_tracker() -> TrackerAndDeps { - initialize_tracker_and_deps(&configuration::ephemeral_listed()) + initialize_tracker_and_deps(configuration::ephemeral_listed()) } fn tracker_on_reverse_proxy() -> TrackerAndDeps { - initialize_tracker_and_deps(&configuration::ephemeral_with_reverse_proxy()) + initialize_tracker_and_deps(configuration::ephemeral_with_reverse_proxy()) } fn tracker_not_on_reverse_proxy() -> TrackerAndDeps { - initialize_tracker_and_deps(&configuration::ephemeral_without_reverse_proxy()) + initialize_tracker_and_deps(configuration::ephemeral_without_reverse_proxy()) } /// Initialize tracker's dependencies and tracker. - fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { + fn initialize_tracker_and_deps(config: Configuration) -> TrackerAndDeps { let ( _database, _in_memory_whitelist, @@ -295,13 +304,13 @@ mod tests { in_memory_torrent_repository, db_torrent_repository, _torrents_manager, - ) = initialize_tracker_dependencies(config); + ) = initialize_tracker_dependencies(&config); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let tracker = Arc::new(initialize_tracker( - config, + &config, &in_memory_torrent_repository, &db_torrent_repository, )); @@ -312,7 +321,10 @@ mod tests { &db_torrent_repository, )); + let config = Arc::new(config.core); + ( + config, tracker, announce_handler, stats_event_sender, @@ -361,7 +373,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_missing() { - let (tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + let (config, tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = private_tracker(); let tracker = Arc::new(tracker); @@ -370,6 +382,7 @@ mod tests { let maybe_key = None; let response = handle_announce( + &config, &tracker, &announce_handler, &authentication_service, @@ -390,7 +403,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_invalid() { - let (tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + let (config, tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = private_tracker(); let tracker = Arc::new(tracker); @@ -401,6 +414,7 @@ mod tests { let maybe_key = Some(unregistered_key); let response = handle_announce( + &config, &tracker, &announce_handler, &authentication_service, @@ -427,7 +441,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_announced_torrent_is_not_whitelisted() { - let (tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + let (config, tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = whitelisted_tracker(); let tracker = Arc::new(tracker); @@ -436,6 +450,7 @@ mod tests { let announce_request = sample_announce_request(); let response = handle_announce( + &config, &tracker, &announce_handler, &authentication_service, @@ -470,7 +485,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let (tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + let (config, tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = tracker_on_reverse_proxy(); let tracker = Arc::new(tracker); @@ -482,6 +497,7 @@ mod tests { }; let response = handle_announce( + &config, &tracker, &announce_handler, &authentication_service, @@ -513,7 +529,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let (tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + let (config, tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = tracker_not_on_reverse_proxy(); let tracker = Arc::new(tracker); @@ -525,6 +541,7 @@ mod tests { }; let response = handle_announce( + &config, &tracker, &announce_handler, &authentication_service, diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 3c19fe324..4f47a066f 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -13,6 +13,7 @@ use bittorrent_http_protocol::v1::requests::scrape::Scrape; use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; use hyper::StatusCode; +use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; use crate::core::authentication::service::AuthenticationService; @@ -31,6 +32,7 @@ use crate::servers::http::v1::services; #[allow(clippy::type_complexity)] pub async fn handle_without_key( State(state): State<( + Arc, Arc, Arc, Arc, @@ -46,6 +48,7 @@ pub async fn handle_without_key( &state.1, &state.2, &state.3, + &state.4, &scrape_request, &client_ip_sources, None, @@ -61,6 +64,7 @@ pub async fn handle_without_key( #[allow(clippy::type_complexity)] pub async fn handle_with_key( State(state): State<( + Arc, Arc, Arc, Arc, @@ -77,6 +81,7 @@ pub async fn handle_with_key( &state.1, &state.2, &state.3, + &state.4, &scrape_request, &client_ip_sources, Some(key), @@ -84,7 +89,9 @@ pub async fn handle_with_key( .await } +#[allow(clippy::too_many_arguments)] async fn handle( + core_config: &Arc, tracker: &Arc, scrape_handler: &Arc, authentication_service: &Arc, @@ -94,6 +101,7 @@ async fn handle( maybe_key: Option, ) -> Response { let scrape_data = match handle_scrape( + core_config, tracker, scrape_handler, authentication_service, @@ -116,8 +124,10 @@ async fn handle( See https://github.com/torrust/torrust-tracker/discussions/240. */ +#[allow(clippy::too_many_arguments)] async fn handle_scrape( - tracker: &Arc, + core_config: &Arc, + _tracker: &Arc, scrape_handler: &Arc, authentication_service: &Arc, opt_stats_event_sender: &Arc>>, @@ -126,7 +136,7 @@ async fn handle_scrape( maybe_key: Option, ) -> Result { // Authentication - let return_real_scrape_data = if tracker.requires_authentication() { + let return_real_scrape_data = if core_config.private { match maybe_key { Some(key) => match authentication_service.authenticate(&key).await { Ok(()) => true, @@ -141,7 +151,7 @@ async fn handle_scrape( // Authorization for scrape requests is handled at the `Tracker` level // for each torrent. - let peer_ip = match peer_ip_resolver::invoke(tracker.is_behind_reverse_proxy(), client_ip_sources) { + let peer_ip = match peer_ip_resolver::invoke(core_config.net.on_reverse_proxy, client_ip_sources) { Ok(peer_ip) => peer_ip, Err(error) => return Err(responses::error::Error::from(error)), }; @@ -169,6 +179,7 @@ mod tests { use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_configuration::Core; use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; @@ -179,6 +190,7 @@ mod tests { #[allow(clippy::type_complexity)] fn private_tracker() -> ( + Arc, Arc, Arc, Arc>>, @@ -200,6 +212,8 @@ mod tests { let stats_event_sender = Arc::new(stats_event_sender); + let core_config = Arc::new(config.core.clone()); + let tracker = Arc::new(initialize_tracker( &config, &in_memory_torrent_repository, @@ -208,11 +222,18 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, scrape_handler, stats_event_sender, authentication_service) + ( + core_config, + tracker, + scrape_handler, + stats_event_sender, + authentication_service, + ) } #[allow(clippy::type_complexity)] fn whitelisted_tracker() -> ( + Arc, Arc, Arc, Arc>>, @@ -234,6 +255,8 @@ mod tests { let stats_event_sender = Arc::new(stats_event_sender); + let core_config = Arc::new(config.core.clone()); + let tracker = Arc::new(initialize_tracker( &config, &in_memory_torrent_repository, @@ -242,11 +265,18 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, scrape_handler, stats_event_sender, authentication_service) + ( + core_config, + tracker, + scrape_handler, + stats_event_sender, + authentication_service, + ) } #[allow(clippy::type_complexity)] fn tracker_on_reverse_proxy() -> ( + Arc, Arc, Arc, Arc>>, @@ -268,6 +298,8 @@ mod tests { let stats_event_sender = Arc::new(stats_event_sender); + let core_config = Arc::new(config.core.clone()); + let tracker = Arc::new(initialize_tracker( &config, &in_memory_torrent_repository, @@ -276,11 +308,18 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, scrape_handler, stats_event_sender, authentication_service) + ( + core_config, + tracker, + scrape_handler, + stats_event_sender, + authentication_service, + ) } #[allow(clippy::type_complexity)] fn tracker_not_on_reverse_proxy() -> ( + Arc, Arc, Arc, Arc>>, @@ -302,6 +341,8 @@ mod tests { let stats_event_sender = Arc::new(stats_event_sender); + let core_config = Arc::new(config.core.clone()); + let tracker = Arc::new(initialize_tracker( &config, &in_memory_torrent_repository, @@ -310,7 +351,13 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, scrape_handler, stats_event_sender, authentication_service) + ( + core_config, + tracker, + scrape_handler, + stats_event_sender, + authentication_service, + ) } fn sample_scrape_request() -> Scrape { @@ -344,12 +391,13 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { - let (tracker, scrape_handler, stats_event_sender, authentication_service) = private_tracker(); + let (core_config, tracker, scrape_handler, stats_event_sender, authentication_service) = private_tracker(); let scrape_request = sample_scrape_request(); let maybe_key = None; let scrape_data = handle_scrape( + &core_config, &tracker, &scrape_handler, &authentication_service, @@ -368,13 +416,14 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() { - let (tracker, scrape_handler, stats_event_sender, authentication_service) = private_tracker(); + let (core_config, tracker, scrape_handler, stats_event_sender, authentication_service) = private_tracker(); let scrape_request = sample_scrape_request(); let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); let maybe_key = Some(unregistered_key); let scrape_data = handle_scrape( + &core_config, &tracker, &scrape_handler, &authentication_service, @@ -401,11 +450,12 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() { - let (tracker, scrape_handler, stats_event_sender, authentication_service) = whitelisted_tracker(); + let (core_config, tracker, scrape_handler, stats_event_sender, authentication_service) = whitelisted_tracker(); let scrape_request = sample_scrape_request(); let scrape_data = handle_scrape( + &core_config, &tracker, &scrape_handler, &authentication_service, @@ -433,7 +483,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let (tracker, scrape_handler, stats_event_sender, authentication_service) = tracker_on_reverse_proxy(); + let (core_config, tracker, scrape_handler, stats_event_sender, authentication_service) = tracker_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -441,6 +491,7 @@ mod tests { }; let response = handle_scrape( + &core_config, &tracker, &scrape_handler, &authentication_service, @@ -469,7 +520,8 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let (tracker, scrape_handler, stats_event_sender, authentication_service) = tracker_not_on_reverse_proxy(); + let (core_config, tracker, scrape_handler, stats_event_sender, authentication_service) = + tracker_not_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -477,6 +529,7 @@ mod tests { }; let response = handle_scrape( + &core_config, &tracker, &scrape_handler, &authentication_service, diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 50e1494be..85564ca8c 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -10,7 +10,7 @@ use axum::routing::get; use axum::{BoxError, Router}; use axum_client_ip::SecureClientIpSource; use hyper::{Request, StatusCode}; -use torrust_tracker_configuration::DEFAULT_TIMEOUT; +use torrust_tracker_configuration::{Core, DEFAULT_TIMEOUT}; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; use tower_http::classify::ServerErrorsFailureClass; @@ -34,6 +34,7 @@ use crate::servers::logging::Latency; /// /// > **NOTICE**: it's added a layer to get the client IP from the connection /// > info. The tracker could use the connection info to get the client IP. +#[allow(clippy::too_many_arguments)] #[allow(clippy::needless_pass_by_value)] #[instrument(skip( tracker, @@ -45,6 +46,7 @@ use crate::servers::logging::Latency; server_socket_addr ))] pub fn router( + core_config: Arc, tracker: Arc, announce_handler: Arc, scrape_handler: Arc, @@ -60,6 +62,7 @@ pub fn router( .route( "/announce", get(announce::handle_without_key).with_state(( + core_config.clone(), tracker.clone(), announce_handler.clone(), authentication_service.clone(), @@ -70,6 +73,7 @@ pub fn router( .route( "/announce/{key}", get(announce::handle_with_key).with_state(( + core_config.clone(), tracker.clone(), announce_handler.clone(), authentication_service.clone(), @@ -81,6 +85,7 @@ pub fn router( .route( "/scrape", get(scrape::handle_without_key).with_state(( + core_config.clone(), tracker.clone(), scrape_handler.clone(), authentication_service.clone(), @@ -90,6 +95,7 @@ pub fn router( .route( "/scrape/{key}", get(scrape::handle_with_key).with_state(( + core_config.clone(), tracker.clone(), scrape_handler.clone(), authentication_service.clone(), diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 1923037b3..5e2e8f716 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -63,6 +63,7 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_configuration::Core; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; @@ -73,7 +74,7 @@ mod tests { use crate::core::Tracker; #[allow(clippy::type_complexity)] - fn public_tracker() -> (Arc, Arc, Arc>>) { + fn public_tracker() -> (Arc, Arc, Arc, Arc>>) { let config = configuration::ephemeral_public(); let ( @@ -100,7 +101,9 @@ mod tests { &db_torrent_repository, )); - (tracker, announce_handler, stats_event_sender) + let core_config = Arc::new(config.core.clone()); + + (core_config, tracker, announce_handler, stats_event_sender) } fn sample_info_hash() -> InfoHash { @@ -176,7 +179,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_announce_data() { - let (tracker, announce_handler, stats_event_sender) = public_tracker(); + let (core_config, tracker, announce_handler, stats_event_sender) = public_tracker(); let mut peer = sample_peer(); @@ -197,7 +200,7 @@ mod tests { complete: 1, incomplete: 0, }, - policy: tracker.get_announce_policy(), + policy: core_config.announce_policy, }; assert_eq!(announce_data, expected_announce_data); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 03a0248d4..b3ec1cb06 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -13,6 +13,7 @@ use aquatic_udp_protocol::{ use bittorrent_primitives::info_hash::InfoHash; use tokio::sync::RwLock; use torrust_tracker_clock::clock::Time as _; +use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; use uuid::Uuid; use zerocopy::network_endian::I32; @@ -60,6 +61,7 @@ impl CookieTimeValues { #[instrument(fields(request_id), skip(udp_request, tracker, announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, cookie_time_values, ban_service), ret(level = Level::TRACE))] pub(crate) async fn handle_packet( udp_request: RawRequest, + core_config: &Arc, tracker: &Tracker, announce_handler: &Arc, scrape_handler: &Arc, @@ -81,6 +83,7 @@ pub(crate) async fn handle_packet( Ok(request) => match handle_request( request, udp_request.from, + core_config, tracker, announce_handler, scrape_handler, @@ -154,6 +157,7 @@ pub(crate) async fn handle_packet( pub async fn handle_request( request: Request, remote_addr: SocketAddr, + core_config: &Arc, tracker: &Tracker, announce_handler: &Arc, scrape_handler: &Arc, @@ -175,6 +179,7 @@ pub async fn handle_request( handle_announce( remote_addr, &announce_request, + core_config, tracker, announce_handler, whitelist_authorization, @@ -240,11 +245,13 @@ pub async fn handle_connect( /// # Errors /// /// If a error happens in the `handle_announce` function, it will just return the `ServerError`. -#[instrument(fields(transaction_id, connection_id, info_hash), skip(tracker, announce_handler, whitelist_authorization, opt_stats_event_sender), ret(level = Level::TRACE))] +#[allow(clippy::too_many_arguments)] +#[instrument(fields(transaction_id, connection_id, info_hash), skip(_tracker, announce_handler, whitelist_authorization, opt_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_announce( remote_addr: SocketAddr, request: &AnnounceRequest, - tracker: &Tracker, + core_config: &Arc, + _tracker: &Tracker, announce_handler: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, @@ -297,7 +304,7 @@ pub async fn handle_announce( let announce_response = AnnounceResponse { fixed: AnnounceResponseFixedData { transaction_id: request.transaction_id, - announce_interval: AnnounceInterval(I32::new(i64::from(tracker.get_announce_policy().interval) as i32)), + announce_interval: AnnounceInterval(I32::new(i64::from(core_config.announce_policy.interval) as i32)), leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), }, @@ -322,7 +329,7 @@ pub async fn handle_announce( let announce_response = AnnounceResponse { fixed: AnnounceResponseFixedData { transaction_id: request.transaction_id, - announce_interval: AnnounceInterval(I32::new(i64::from(tracker.get_announce_policy().interval) as i32)), + announce_interval: AnnounceInterval(I32::new(i64::from(core_config.announce_policy.interval) as i32)), leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), }, @@ -492,7 +499,7 @@ mod tests { use aquatic_udp_protocol::{NumberOfBytes, PeerId}; use torrust_tracker_clock::clock::Time; - use torrust_tracker_configuration::Configuration; + use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_primitives::peer; use torrust_tracker_test_helpers::configuration; @@ -509,6 +516,7 @@ mod tests { use crate::CurrentClock; type TrackerAndDeps = ( + Arc, Arc, Arc, Arc, @@ -536,6 +544,8 @@ mod tests { } fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { + let core_config = Arc::new(config.core.clone()); + let ( database, in_memory_whitelist, @@ -565,6 +575,7 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); ( + core_config, tracker, announce_handler, scrape_handler, @@ -670,7 +681,9 @@ mod tests { } } + #[allow(clippy::type_complexity)] fn test_tracker_factory() -> ( + Arc, Arc, Arc, Arc, @@ -678,6 +691,8 @@ mod tests { ) { let config = tracker_configuration(); + let core_config = Arc::new(config.core.clone()); + let ( _database, _in_memory_whitelist, @@ -698,7 +713,13 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, announce_handler, scrape_handler, whitelist_authorization) + ( + core_config, + tracker, + announce_handler, + scrape_handler, + whitelist_authorization, + ) } mod connect_request { @@ -910,6 +931,7 @@ mod tests { PeerId as AquaticPeerId, Response, ResponsePeer, }; use mockall::predicate::eq; + use torrust_tracker_configuration::Core; use crate::core::announce_handler::AnnounceHandler; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -925,6 +947,7 @@ mod tests { #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { let ( + core_config, tracker, announce_handler, _scrape_handler, @@ -953,6 +976,7 @@ mod tests { handle_announce( remote_addr, &request, + &core_config, &tracker, &announce_handler, &whitelist_authorization, @@ -975,6 +999,7 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { let ( + core_config, tracker, announce_handler, _scrape_handler, @@ -994,6 +1019,7 @@ mod tests { let response = handle_announce( remote_addr, &request, + &core_config, &tracker, &announce_handler, &whitelist_authorization, @@ -1025,6 +1051,7 @@ mod tests { // "Do note that most trackers will only honor the IP address field under limited circumstances." let ( + core_config, tracker, announce_handler, _scrape_handler, @@ -1056,6 +1083,7 @@ mod tests { handle_announce( remote_addr, &request, + &core_config, &tracker, &announce_handler, &whitelist_authorization, @@ -1087,6 +1115,7 @@ mod tests { } async fn announce_a_new_peer_using_ipv4( + core_config: Arc, tracker: Arc, announce_handler: Arc, whitelist_authorization: Arc, @@ -1102,6 +1131,7 @@ mod tests { handle_announce( remote_addr, &request, + &core_config, &tracker, &announce_handler, &whitelist_authorization, @@ -1115,6 +1145,7 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { let ( + core_config, tracker, announce_handler, _scrape_handler, @@ -1127,8 +1158,13 @@ mod tests { add_a_torrent_peer_using_ipv6(&in_memory_torrent_repository); - let response = - announce_a_new_peer_using_ipv4(tracker.clone(), announce_handler.clone(), whitelist_authorization).await; + let response = announce_a_new_peer_using_ipv4( + core_config.clone(), + tracker.clone(), + announce_handler.clone(), + whitelist_authorization, + ) + .await; // The response should not contain the peer using IPV6 let peers: Option>> = match response { @@ -1150,11 +1186,12 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (tracker, announce_handler, _scrape_handler, whitelist_authorization) = test_tracker_factory(); + let (core_config, tracker, announce_handler, _scrape_handler, whitelist_authorization) = test_tracker_factory(); handle_announce( sample_ipv4_socket_address(), &AnnounceRequestBuilder::default().into(), + &core_config, &tracker, &announce_handler, &whitelist_authorization, @@ -1181,6 +1218,7 @@ mod tests { #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { let ( + core_config, tracker, announce_handler, _scrape_handler, @@ -1209,6 +1247,7 @@ mod tests { handle_announce( remote_addr, &request, + &core_config, &tracker, &announce_handler, &whitelist_authorization, @@ -1220,7 +1259,7 @@ mod tests { let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); - let external_ip_in_tracker_configuration = tracker.get_maybe_external_ip().unwrap(); + let external_ip_in_tracker_configuration = core_config.net.external_ip.unwrap(); let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) @@ -1243,6 +1282,7 @@ mod tests { PeerId as AquaticPeerId, Response, ResponsePeer, }; use mockall::predicate::eq; + use torrust_tracker_configuration::Core; use crate::core::announce_handler::AnnounceHandler; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -1258,6 +1298,7 @@ mod tests { #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { let ( + core_config, tracker, announce_handler, _scrape_handler, @@ -1287,6 +1328,7 @@ mod tests { handle_announce( remote_addr, &request, + &core_config, &tracker, &announce_handler, &whitelist_authorization, @@ -1309,6 +1351,7 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { let ( + core_config, tracker, announce_handler, _scrape_handler, @@ -1331,6 +1374,7 @@ mod tests { let response = handle_announce( remote_addr, &request, + &core_config, &tracker, &announce_handler, &whitelist_authorization, @@ -1362,6 +1406,7 @@ mod tests { // "Do note that most trackers will only honor the IP address field under limited circumstances." let ( + core_config, tracker, announce_handler, _scrape_handler, @@ -1393,6 +1438,7 @@ mod tests { handle_announce( remote_addr, &request, + &core_config, &tracker, &announce_handler, &whitelist_authorization, @@ -1424,6 +1470,7 @@ mod tests { } async fn announce_a_new_peer_using_ipv6( + core_config: Arc, tracker: Arc, announce_handler: Arc, whitelist_authorization: Arc, @@ -1442,6 +1489,7 @@ mod tests { handle_announce( remote_addr, &request, + &core_config, &tracker, &announce_handler, &whitelist_authorization, @@ -1455,6 +1503,7 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { let ( + core_config, tracker, announce_handler, _scrape_handler, @@ -1467,8 +1516,13 @@ mod tests { add_a_torrent_peer_using_ipv4(&in_memory_torrent_repository); - let response = - announce_a_new_peer_using_ipv6(tracker.clone(), announce_handler.clone(), whitelist_authorization).await; + let response = announce_a_new_peer_using_ipv6( + core_config.clone(), + tracker.clone(), + announce_handler.clone(), + whitelist_authorization, + ) + .await; // The response should not contain the peer using IPV4 let peers: Option>> = match response { @@ -1490,7 +1544,7 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (tracker, announce_handler, _scrape_handler, whitelist_authorization) = test_tracker_factory(); + let (core_config, tracker, announce_handler, _scrape_handler, whitelist_authorization) = test_tracker_factory(); let remote_addr = sample_ipv6_remote_addr(); @@ -1501,6 +1555,7 @@ mod tests { handle_announce( remote_addr, &announce_request, + &core_config, &tracker, &announce_handler, &whitelist_authorization, @@ -1582,9 +1637,12 @@ mod tests { .with_port(client_port) .into(); + let core_config = Arc::new(config.core.clone()); + handle_announce( remote_addr, &request, + &core_config, &tracker, &announce_handler, &whitelist_authorization, @@ -1596,7 +1654,7 @@ mod tests { let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); - let external_ip_in_tracker_configuration = tracker.get_maybe_external_ip().unwrap(); + let external_ip_in_tracker_configuration = core_config.net.external_ip.unwrap(); assert!(external_ip_in_tracker_configuration.is_ipv6()); @@ -1641,6 +1699,7 @@ mod tests { #[tokio::test] async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { let ( + _core_config, _tracker, _announce_handler, scrape_handler, @@ -1750,6 +1809,7 @@ mod tests { #[tokio::test] async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { let ( + _core_config, _tracker, _announce_handler, scrape_handler, @@ -1786,6 +1846,7 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { let ( + _core_config, _tracker, _announce_handler, scrape_handler, @@ -1830,6 +1891,7 @@ mod tests { #[tokio::test] async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { let ( + _core_config, _tracker, _announce_handler, scrape_handler, @@ -1903,7 +1965,8 @@ mod tests { let remote_addr = sample_ipv4_remote_addr(); - let (_tracker, _announce_handler, scrape_handler, _whitelist_authorization) = test_tracker_factory(); + let (_core_config, _tracker, _announce_handler, scrape_handler, _whitelist_authorization) = + test_tracker_factory(); handle_scrape( remote_addr, @@ -1943,7 +2006,8 @@ mod tests { let remote_addr = sample_ipv6_remote_addr(); - let (_tracker, _announce_handler, scrape_handler, _whitelist_authorization) = test_tracker_factory(); + let (_core_config, _tracker, _announce_handler, scrape_handler, _whitelist_authorization) = + test_tracker_factory(); handle_scrape( remote_addr, diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index f1d0e4859..d0ae14029 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -8,6 +8,7 @@ use futures_util::StreamExt; use tokio::select; use tokio::sync::{oneshot, RwLock}; use tokio::time::interval; +use torrust_tracker_configuration::Core; use tracing::instrument; use super::banning::BanService; @@ -55,6 +56,7 @@ impl Launcher { rx_halt ))] pub async fn run_with_graceful_shutdown( + core_config: Arc, tracker: Arc, announce_handler: Arc, scrape_handler: Arc, @@ -68,7 +70,7 @@ impl Launcher { ) { tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting on: {bind_to}"); - if tracker.requires_authentication() { + if core_config.private { tracing::error!("udp services cannot be used for private trackers"); panic!("it should not use udp if using authentication"); } @@ -100,6 +102,7 @@ impl Launcher { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_with_graceful_shutdown::task (listening...)"); let () = Self::run_udp_server_main( receiver, + core_config.clone(), tracker.clone(), announce_handler.clone(), scrape_handler.clone(), @@ -157,6 +160,7 @@ impl Launcher { ))] async fn run_udp_server_main( mut receiver: Receiver, + core_config: Arc, tracker: Arc, announce_handler: Arc, scrape_handler: Arc, @@ -230,6 +234,7 @@ impl Launcher { let processor = Processor::new( receiver.socket.clone(), + core_config.clone(), tracker.clone(), announce_handler.clone(), scrape_handler.clone(), diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 53ba588d4..f93d84a65 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -82,6 +82,7 @@ mod tests { let started = stopped .start( + Arc::new(cfg.core.clone()), app_container.tracker, app_container.announce_handler, app_container.scrape_handler, @@ -117,6 +118,7 @@ mod tests { let started = stopped .start( + Arc::new(cfg.core.clone()), app_container.tracker, app_container.announce_handler, app_container.scrape_handler, diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 4cecbc36a..0bb7c92c4 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -6,6 +6,7 @@ use std::time::Duration; use aquatic_udp_protocol::Response; use tokio::sync::RwLock; use tokio::time::Instant; +use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; use super::banning::BanService; @@ -20,6 +21,7 @@ use crate::servers::udp::{handlers, RawRequest}; pub struct Processor { socket: Arc, + core_config: Arc, tracker: Arc, announce_handler: Arc, scrape_handler: Arc, @@ -29,8 +31,10 @@ pub struct Processor { } impl Processor { + #[allow(clippy::too_many_arguments)] pub fn new( socket: Arc, + core_config: Arc, tracker: Arc, announce_handler: Arc, scrape_handler: Arc, @@ -40,6 +44,7 @@ impl Processor { ) -> Self { Self { socket, + core_config, tracker, announce_handler, scrape_handler, @@ -57,6 +62,7 @@ impl Processor { let response = handlers::handle_packet( request, + &self.core_config, &self.tracker, &self.announce_handler, &self.scrape_handler, diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index ea12b1c0b..ced5fbf4a 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -7,6 +7,7 @@ use derive_more::derive::Display; use derive_more::Constructor; use tokio::sync::{oneshot, RwLock}; use tokio::task::JoinHandle; +use torrust_tracker_configuration::Core; use super::banning::BanService; use super::launcher::Launcher; @@ -32,6 +33,7 @@ impl Spawner { #[allow(clippy::too_many_arguments)] pub fn spawn_launcher( &self, + core_config: Arc, tracker: Arc, announce_handler: Arc, scrape_handler: Arc, @@ -46,6 +48,7 @@ impl Spawner { tokio::spawn(async move { Launcher::run_with_graceful_shutdown( + core_config, tracker, announce_handler, scrape_handler, diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index bab04fdcc..4d63dc0a8 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -7,6 +7,7 @@ use derive_more::derive::Display; use derive_more::Constructor; use tokio::sync::RwLock; use tokio::task::JoinHandle; +use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; use super::banning::BanService; @@ -70,6 +71,7 @@ impl Server { #[instrument(skip(self, tracker, announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, ban_service, form), err, ret(Display, level = Level::INFO))] pub async fn start( self, + core_config: Arc, tracker: Arc, announce_handler: Arc, scrape_handler: Arc, @@ -86,6 +88,7 @@ impl Server { // May need to wrap in a task to about a tokio bug. let task = self.state.spawner.spawn_launcher( + core_config, tracker, announce_handler, scrape_handler, diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 78051cbbb..203dc880e 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; -use torrust_tracker_configuration::{Configuration, HttpTracker}; +use torrust_tracker_configuration::{Configuration, Core, HttpTracker}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::core::announce_handler::AnnounceHandler; @@ -20,7 +20,8 @@ use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; pub struct Environment { - pub config: Arc, + pub core_config: Arc, + pub http_tracker_config: Arc, pub database: Arc>, pub tracker: Arc, pub announce_handler: Arc, @@ -64,7 +65,8 @@ impl Environment { let server = HttpServer::new(Launcher::new(bind_to, tls)); Self { - config, + http_tracker_config: config, + core_config: Arc::new(configuration.core.clone()), database: app_container.database.clone(), tracker: app_container.tracker.clone(), announce_handler: app_container.announce_handler.clone(), @@ -84,7 +86,8 @@ impl Environment { #[allow(dead_code)] pub async fn start(self) -> Environment { Environment { - config: self.config, + http_tracker_config: self.http_tracker_config, + core_config: self.core_config.clone(), database: self.database.clone(), tracker: self.tracker.clone(), announce_handler: self.announce_handler.clone(), @@ -100,6 +103,7 @@ impl Environment { server: self .server .start( + self.core_config, self.tracker, self.announce_handler, self.scrape_handler, @@ -121,7 +125,8 @@ impl Environment { pub async fn stop(self) -> Environment { Environment { - config: self.config, + http_tracker_config: self.http_tracker_config, + core_config: self.core_config, database: self.database, tracker: self.tracker, announce_handler: self.announce_handler, diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 8a65d941a..33faf8578 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -449,7 +449,7 @@ mod for_all_config_modes { ) .await; - let announce_policy = env.tracker.get_announce_policy(); + let announce_policy = env.core_config.announce_policy; assert_announce_response( response, @@ -490,7 +490,7 @@ mod for_all_config_modes { ) .await; - let announce_policy = env.tracker.get_announce_policy(); + let announce_policy = env.core_config.announce_policy; // It should only contain the previously announced peer assert_announce_response( @@ -543,7 +543,7 @@ mod for_all_config_modes { ) .await; - let announce_policy = env.tracker.get_announce_policy(); + let announce_policy = env.core_config.announce_policy; // The newly announced peer is not included on the response peer list, // but all the previously announced peers should be included regardless the IP version they are using. @@ -872,7 +872,7 @@ mod for_all_config_modes { let peers = env.in_memory_torrent_repository.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; - assert_eq!(peer_addr.ip(), env.tracker.get_maybe_external_ip().unwrap()); + assert_eq!(peer_addr.ip(), env.core_config.net.external_ip.unwrap()); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); env.stop().await; @@ -914,7 +914,7 @@ mod for_all_config_modes { let peers = env.in_memory_torrent_repository.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; - assert_eq!(peer_addr.ip(), env.tracker.get_maybe_external_ip().unwrap()); + assert_eq!(peer_addr.ip(), env.core_config.net.external_ip.unwrap()); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); env.stop().await; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index fafb7ef7a..11967aeed 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use tokio::sync::RwLock; -use torrust_tracker_configuration::{Configuration, UdpTracker, DEFAULT_TIMEOUT}; +use torrust_tracker_configuration::{Configuration, Core, UdpTracker, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::core::announce_handler::AnnounceHandler; use torrust_tracker_lib::core::databases::Database; @@ -23,6 +23,7 @@ pub struct Environment where S: std::fmt::Debug + std::fmt::Display, { + pub core_config: Arc, pub config: Arc, pub database: Arc>, pub tracker: Arc, @@ -64,6 +65,7 @@ impl Environment { let server = Server::new(Spawner::new(bind_to)); Self { + core_config: Arc::new(configuration.core.clone()), config, database: app_container.database.clone(), tracker: app_container.tracker.clone(), @@ -83,6 +85,7 @@ impl Environment { pub async fn start(self) -> Environment { let cookie_lifetime = self.config.cookie_lifetime; Environment { + core_config: self.core_config.clone(), config: self.config, database: self.database.clone(), tracker: self.tracker.clone(), @@ -97,6 +100,7 @@ impl Environment { server: self .server .start( + self.core_config, self.tracker, self.announce_handler, self.scrape_handler, @@ -126,6 +130,7 @@ impl Environment { .expect("it should stop the environment within the timeout"); Environment { + core_config: self.core_config, config: self.config, database: self.database, tracker: self.tracker, From 73560a5612ed5a468c1d61bc910dd0eda166d022 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 27 Jan 2025 17:52:10 +0000 Subject: [PATCH 0659/1297] refactor: [#1209] remove core::Tracker --- src/app.rs | 2 - src/bootstrap/app.rs | 9 +- src/bootstrap/jobs/http_tracker.rs | 9 +- src/bootstrap/jobs/udp_tracker.rs | 5 +- src/container.rs | 3 +- src/core/mod.rs | 151 +++++------------------ src/core/services/mod.rs | 22 ---- src/core/services/statistics/mod.rs | 9 +- src/core/services/torrent.rs | 28 ++--- src/servers/http/server.rs | 8 +- src/servers/http/v1/handlers/announce.rs | 42 ++----- src/servers/http/v1/handlers/scrape.rs | 95 +++----------- src/servers/http/v1/routes.rs | 8 +- src/servers/http/v1/services/announce.rs | 43 ++----- src/servers/http/v1/services/scrape.rs | 34 ++--- src/servers/udp/handlers.rs | 100 +++------------ src/servers/udp/mod.rs | 3 +- src/servers/udp/server/launcher.rs | 8 +- src/servers/udp/server/mod.rs | 2 - src/servers/udp/server/processor.rs | 6 +- src/servers/udp/server/spawner.rs | 4 +- src/servers/udp/server/states.rs | 6 +- tests/servers/api/environment.rs | 5 - tests/servers/http/environment.rs | 7 +- tests/servers/udp/environment.rs | 7 +- 25 files changed, 119 insertions(+), 497 deletions(-) diff --git a/src/app.rs b/src/app.rs index 54ccbc60c..75c2e13bc 100644 --- a/src/app.rs +++ b/src/app.rs @@ -82,7 +82,6 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< udp_tracker::start_job( Arc::new(config.core.clone()), udp_tracker_config, - app_container.tracker.clone(), app_container.announce_handler.clone(), app_container.scrape_handler.clone(), app_container.whitelist_authorization.clone(), @@ -104,7 +103,6 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< if let Some(job) = http_tracker::start_job( http_tracker_config, Arc::new(config.core.clone()), - app_container.tracker.clone(), app_container.announce_handler.clone(), app_container.scrape_handler.clone(), app_container.authentication_service.clone(), diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index fa45998bb..da63048e0 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -28,7 +28,7 @@ use crate::core::authentication::key::repository::in_memory::InMemoryKeyReposito use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::authentication::service; use crate::core::scrape_handler::ScrapeHandler; -use crate::core::services::{initialize_database, initialize_tracker, initialize_whitelist_manager, statistics}; +use crate::core::services::{initialize_database, initialize_whitelist_manager, statistics}; use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; @@ -116,12 +116,6 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { &db_torrent_repository, )); - let tracker = Arc::new(initialize_tracker( - configuration, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let announce_handler = Arc::new(AnnounceHandler::new( &configuration.core, &in_memory_torrent_repository, @@ -132,7 +126,6 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { AppContainer { database, - tracker, announce_handler, scrape_handler, keys_handler, diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 5767f30ce..4a3aa7a9f 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -23,7 +23,7 @@ use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::service::AuthenticationService; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; -use crate::core::{self, statistics, whitelist}; +use crate::core::{statistics, whitelist}; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::http::Version; use crate::servers::registar::ServiceRegistrationForm; @@ -39,7 +39,6 @@ use crate::servers::registar::ServiceRegistrationForm; #[allow(clippy::too_many_arguments)] #[instrument(skip( config, - tracker, announce_handler, scrape_handler, authentication_service, @@ -50,7 +49,6 @@ use crate::servers::registar::ServiceRegistrationForm; pub async fn start_job( config: &HttpTracker, core_config: Arc, - tracker: Arc, announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, @@ -71,7 +69,6 @@ pub async fn start_job( socket, tls, core_config.clone(), - tracker.clone(), announce_handler.clone(), scrape_handler.clone(), authentication_service.clone(), @@ -89,7 +86,6 @@ pub async fn start_job( #[instrument(skip( socket, tls, - tracker, announce_handler, scrape_handler, whitelist_authorization, @@ -100,7 +96,6 @@ async fn start_v1( socket: SocketAddr, tls: Option, config: Arc, - tracker: Arc, announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, @@ -111,7 +106,6 @@ async fn start_v1( let server = HttpServer::new(Launcher::new(socket, tls)) .start( config, - tracker, announce_handler, scrape_handler, authentication_service, @@ -161,7 +155,6 @@ mod tests { start_job( config, Arc::new(cfg.core.clone()), - app_container.tracker, app_container.announce_handler, app_container.scrape_handler, app_container.authentication_service, diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 36f3cd7b0..3679c3195 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -16,7 +16,7 @@ use tracing::instrument; use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; -use crate::core::{self, whitelist}; +use crate::core::whitelist; use crate::servers::registar::ServiceRegistrationForm; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::spawner::Spawner; @@ -37,7 +37,6 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; #[allow(clippy::async_yields_async)] #[instrument(skip( config, - tracker, announce_handler, scrape_handler, whitelist_authorization, @@ -48,7 +47,6 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; pub async fn start_job( core_config: Arc, config: &UdpTracker, - tracker: Arc, announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, @@ -62,7 +60,6 @@ pub async fn start_job( let server = Server::new(Spawner::new(bind_to)) .start( core_config, - tracker, announce_handler, scrape_handler, whitelist_authorization, diff --git a/src/container.rs b/src/container.rs index 4e958b6ed..544abd02e 100644 --- a/src/container.rs +++ b/src/container.rs @@ -12,13 +12,12 @@ use crate::core::statistics::repository::Repository; use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use crate::core::whitelist; use crate::core::whitelist::manager::WhiteListManager; -use crate::core::{whitelist, Tracker}; use crate::servers::udp::server::banning::BanService; pub struct AppContainer { pub database: Arc>, - pub tracker: Arc, pub announce_handler: Arc, pub scrape_handler: Arc, pub keys_handler: Arc, diff --git a/src/core/mod.rs b/src/core/mod.rs index 43a2aa11d..f09e7d417 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -451,53 +451,9 @@ pub mod whitelist; pub mod peer_tests; -use std::sync::Arc; - -use torrent::repository::in_memory::InMemoryTorrentRepository; -use torrent::repository::persisted::DatabasePersistentTorrentRepository; -use torrust_tracker_configuration::Core; - -/// The domain layer tracker service. -/// -/// Its main responsibility is to handle the `announce` and `scrape` requests. -/// But it's also a container for the `Tracker` configuration, persistence, -/// authentication and other services. -/// -/// > **NOTICE**: the `Tracker` is not responsible for handling the network layer. -/// > Typically, the `Tracker` is used by a higher application service that handles -/// > the network layer. -pub struct Tracker { - /// The tracker configuration. - _core_config: Core, - - /// The in-memory torrents repository. - _in_memory_torrent_repository: Arc, - - /// The persistent torrents repository. - _db_torrent_repository: Arc, -} - -impl Tracker { - /// `Tracker` constructor. - /// - /// # Errors - /// - /// Will return a `databases::error::Error` if unable to connect to database. The `Tracker` is responsible for the persistence. - pub fn new( - core_config: &Core, - in_memory_torrent_repository: &Arc, - db_torrent_repository: &Arc, - ) -> Result { - Ok(Tracker { - _core_config: core_config.clone(), - _in_memory_torrent_repository: in_memory_torrent_repository.clone(), - _db_torrent_repository: db_torrent_repository.clone(), - }) - } -} - #[cfg(test)] mod tests { + // Integration tests for the core module. mod the_tracker { @@ -517,18 +473,13 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::{initialize_tracker, initialize_whitelist_manager}; + use crate::core::services::initialize_whitelist_manager; use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::whitelist; use crate::core::whitelist::manager::WhiteListManager; - use crate::core::{whitelist, Tracker}; - fn public_tracker() -> ( - Arc, - Arc, - Arc, - Arc, - ) { + fn public_tracker() -> (Arc, Arc, Arc) { let config = configuration::ephemeral_public(); let ( @@ -541,12 +492,6 @@ mod tests { _torrents_manager, ) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker( - &config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, @@ -555,10 +500,10 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, announce_handler, in_memory_torrent_repository, scrape_handler) + (announce_handler, in_memory_torrent_repository, scrape_handler) } - fn public_tracker_and_in_memory_torrents_repository() -> (Arc, Arc) { + fn initialize_in_memory_torrents_repository() -> Arc { let config = configuration::ephemeral_public(); let ( @@ -567,22 +512,15 @@ mod tests { _whitelist_authorization, _authentication_service, in_memory_torrent_repository, - db_torrent_repository, + _db_torrent_repository, _torrents_manager, ) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker( - &config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - (tracker, in_memory_torrent_repository) + in_memory_torrent_repository } #[allow(clippy::type_complexity)] fn whitelisted_tracker() -> ( - Arc, Arc, Arc, Arc, @@ -602,12 +540,6 @@ mod tests { let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = Arc::new(initialize_tracker( - &config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, @@ -616,21 +548,11 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - ( - tracker, - announce_handler, - whitelist_authorization, - whitelist_manager, - scrape_handler, - ) + (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) } - pub fn tracker_persisting_torrents_in_database() -> ( - Arc, - Arc, - Arc, - Arc, - ) { + pub fn tracker_persisting_torrents_in_database( + ) -> (Arc, Arc, Arc) { let mut config = configuration::ephemeral_listed(); config.core.tracker_policy.persistent_torrent_completed_stat = true; @@ -644,19 +566,13 @@ mod tests { torrents_manager, ) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker( - &config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, &db_torrent_repository, )); - (tracker, announce_handler, torrents_manager, in_memory_torrent_repository) + (announce_handler, torrents_manager, in_memory_torrent_repository) } fn sample_info_hash() -> InfoHash { @@ -745,7 +661,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent() { - let (_tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); + let in_memory_torrent_repository = initialize_in_memory_torrents_repository(); let info_hash = sample_info_hash(); let peer = sample_peer(); @@ -777,7 +693,7 @@ mod tests { #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { - let (_tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); + let in_memory_torrent_repository = initialize_in_memory_torrents_repository(); let info_hash = sample_info_hash(); @@ -802,7 +718,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let (_tracker, _announce_handler, in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (_announce_handler, in_memory_torrent_repository, _scrape_handler) = public_tracker(); let info_hash = sample_info_hash(); let peer = sample_peer(); @@ -816,7 +732,7 @@ mod tests { #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { - let (_tracker, _announce_handler, in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (_announce_handler, in_memory_torrent_repository, _scrape_handler) = public_tracker(); let info_hash = sample_info_hash(); @@ -846,7 +762,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_torrent_metrics() { - let (_tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); + let in_memory_torrent_repository = initialize_in_memory_torrents_repository(); let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); @@ -865,7 +781,7 @@ mod tests { #[tokio::test] async fn it_should_get_many_the_torrent_metrics() { - let (_tracker, in_memory_torrent_repository) = public_tracker_and_in_memory_torrents_repository(); + let in_memory_torrent_repository = initialize_in_memory_torrents_repository(); let start_time = std::time::Instant::now(); for i in 0..1_000_000 { @@ -1000,7 +916,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_announce_data_with_an_empty_peer_list_when_it_is_the_first_announced_peer() { - let (_tracker, announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); let mut peer = sample_peer(); @@ -1011,7 +927,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_announce_data_with_the_previously_announced_peers() { - let (_tracker, announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); let mut previously_announced_peer = sample_peer_1(); announce_handler.announce( @@ -1036,7 +952,7 @@ mod tests { #[tokio::test] async fn when_the_peer_is_a_seeder() { - let (_tracker, announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); let mut peer = seeder(); @@ -1048,7 +964,7 @@ mod tests { #[tokio::test] async fn when_the_peer_is_a_leecher() { - let (_tracker, announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); let mut peer = leecher(); @@ -1060,7 +976,7 @@ mod tests { #[tokio::test] async fn when_a_previously_announced_started_peer_has_completed_downloading() { - let (_tracker, announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); // We have to announce with "started" event because peer does not count if peer was not previously known let mut started_peer = started_peer(); @@ -1088,7 +1004,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() { - let (_tracker, announce_handler, _in_memory_torrent_repository, scrape_handler) = public_tracker(); + let (announce_handler, _in_memory_torrent_repository, scrape_handler) = public_tracker(); let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // # DevSkim: ignore DS173237 @@ -1136,8 +1052,7 @@ mod tests { #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { - let (_tracker, _announce_handler, whitelist_authorization, whitelist_manager, _scrape_handler) = - whitelisted_tracker(); + let (_announce_handler, whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1150,8 +1065,7 @@ mod tests { #[tokio::test] async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { - let (_tracker, _announce_handler, whitelist_authorization, _whitelist_manager, _scrape_handler) = - whitelisted_tracker(); + let (_announce_handler, whitelist_authorization, _whitelist_manager, _scrape_handler) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1170,8 +1084,7 @@ mod tests { #[tokio::test] async fn it_should_add_a_torrent_to_the_whitelist() { - let (_tracker, _announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = - whitelisted_tracker(); + let (_announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1182,8 +1095,7 @@ mod tests { #[tokio::test] async fn it_should_remove_a_torrent_from_the_whitelist() { - let (_tracker, _announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = - whitelisted_tracker(); + let (_announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1199,7 +1111,7 @@ mod tests { #[tokio::test] async fn it_should_load_the_whitelist_from_the_database() { - let (_tracker, _announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = + let (_announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -1244,8 +1156,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { - let (_tracker, announce_handler, _whitelist_authorization, _whitelist_manager, scrape_handler) = - whitelisted_tracker(); + let (announce_handler, _whitelist_authorization, _whitelist_manager, scrape_handler) = whitelisted_tracker(); let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // # DevSkim: ignore DS173237 @@ -1279,7 +1190,7 @@ mod tests { #[tokio::test] async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { - let (_tracker, announce_handler, torrents_manager, in_memory_torrent_repository) = + let (announce_handler, torrents_manager, in_memory_torrent_repository) = tracker_persisting_torrents_in_database(); let info_hash = sample_info_hash(); diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index a6cf54d60..73328aaeb 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -14,31 +14,9 @@ use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::Configuration; use super::databases::{self, Database}; -use super::torrent::repository::in_memory::InMemoryTorrentRepository; -use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; use super::whitelist::manager::WhiteListManager; use super::whitelist::repository::in_memory::InMemoryWhitelist; use super::whitelist::repository::persisted::DatabaseWhitelist; -use crate::core::Tracker; - -/// It returns a new tracker building its dependencies. -/// -/// # Panics -/// -/// Will panic if tracker cannot be instantiated. -#[must_use] -pub fn initialize_tracker( - config: &Configuration, - in_memory_torrent_repository: &Arc, - db_torrent_repository: &Arc, -) -> Tracker { - match Tracker::new(&Arc::new(config).core, in_memory_torrent_repository, db_torrent_repository) { - Ok(tracker) => tracker, - Err(error) => { - panic!("{}", error) - } - } -} /// # Panics /// diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 680504607..18d96605e 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -118,7 +118,6 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; - use crate::core::services::initialize_tracker; use crate::core::services::statistics::{self, get_metrics, TrackerMetrics}; use crate::core::{self}; use crate::servers::udp::server::banning::BanService; @@ -138,19 +137,13 @@ mod tests { _whitelist_authorization, _authentication_service, in_memory_torrent_repository, - db_torrent_repository, + _db_torrent_repository, _torrents_manager, ) = initialize_tracker_dependencies(&config); let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_repository = Arc::new(stats_repository); - let _tracker = Arc::new(initialize_tracker( - &config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let tracker_metrics = get_metrics( diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 5faaef1d1..6ae2c26a4 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -119,28 +119,20 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use crate::app_test::initialize_tracker_dependencies; - use crate::core::services::initialize_tracker; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::Tracker; - fn initialize_tracker_and_deps(config: &Configuration) -> (Arc, Arc) { + fn initialize_in_memory_torrent_repository(config: &Configuration) -> Arc { let ( _database, _in_memory_whitelist, _whitelist_authorization, _authentication_service, in_memory_torrent_repository, - db_torrent_repository, + _db_torrent_repository, _torrents_manager, ) = initialize_tracker_dependencies(config); - let tracker = Arc::new(initialize_tracker( - config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - (tracker, in_memory_torrent_repository) + in_memory_torrent_repository } fn sample_peer() -> peer::Peer { @@ -164,7 +156,7 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; - use crate::core::services::torrent::tests::{initialize_tracker_and_deps, sample_peer}; + use crate::core::services::torrent::tests::{initialize_in_memory_torrent_repository, sample_peer}; use crate::core::services::torrent::{get_torrent_info, Info}; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -189,7 +181,7 @@ mod tests { async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let config = tracker_configuration(); - let (_tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); + let in_memory_torrent_repository = initialize_in_memory_torrent_repository(&config); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -221,7 +213,7 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; - use crate::core::services::torrent::tests::{initialize_tracker_and_deps, sample_peer}; + use crate::core::services::torrent::tests::{initialize_in_memory_torrent_repository, sample_peer}; use crate::core::services::torrent::{get_torrents_page, BasicInfo, Pagination}; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -242,7 +234,7 @@ mod tests { async fn should_return_a_summarized_info_for_all_torrents() { let config = tracker_configuration(); - let (_tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); + let in_memory_torrent_repository = initialize_in_memory_torrent_repository(&config); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -266,7 +258,7 @@ mod tests { async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let config = tracker_configuration(); - let (_tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); + let in_memory_torrent_repository = initialize_in_memory_torrent_repository(&config); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -289,7 +281,7 @@ mod tests { async fn should_allow_using_pagination_in_the_result() { let config = tracker_configuration(); - let (_tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); + let in_memory_torrent_repository = initialize_in_memory_torrent_repository(&config); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -321,7 +313,7 @@ mod tests { async fn should_return_torrents_ordered_by_info_hash() { let config = tracker_configuration(); - let (_tracker, in_memory_torrent_repository) = initialize_tracker_and_deps(&config); + let in_memory_torrent_repository = initialize_in_memory_torrent_repository(&config); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 3817882df..28f407ad3 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -15,7 +15,7 @@ use crate::bootstrap::jobs::Started; use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::service::AuthenticationService; use crate::core::scrape_handler::ScrapeHandler; -use crate::core::{statistics, whitelist, Tracker}; +use crate::core::{statistics, whitelist}; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; use crate::servers::logging::STARTED_ON; @@ -49,7 +49,6 @@ impl Launcher { #[allow(clippy::too_many_arguments)] #[instrument(skip( self, - tracker, announce_handler, scrape_handler, authentication_service, @@ -61,7 +60,6 @@ impl Launcher { fn start( &self, config: Arc, - tracker: Arc, announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, @@ -88,7 +86,6 @@ impl Launcher { let app = router( config, - tracker, announce_handler, scrape_handler, authentication_service, @@ -192,7 +189,6 @@ impl HttpServer { pub async fn start( self, core_config: Arc, - tracker: Arc, announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, @@ -208,7 +204,6 @@ impl HttpServer { let task = tokio::spawn(async move { let server = launcher.start( core_config, - tracker, announce_handler, scrape_handler, authentication_service, @@ -315,7 +310,6 @@ mod tests { let started = stopped .start( Arc::new(cfg.core.clone()), - app_container.tracker, app_container.announce_handler, app_container.scrape_handler, app_container.authentication_service, diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index ebdb717c3..632688763 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -26,7 +26,7 @@ use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; use crate::core::authentication::service::AuthenticationService; use crate::core::authentication::Key; use crate::core::statistics::event::sender::Sender; -use crate::core::{whitelist, Tracker}; +use crate::core::whitelist; use crate::servers::http::v1::extractors::announce_request::ExtractRequest; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; @@ -41,7 +41,6 @@ use crate::CurrentClock; pub async fn handle_without_key( State(state): State<( Arc, - Arc, Arc, Arc, Arc, @@ -58,7 +57,6 @@ pub async fn handle_without_key( &state.2, &state.3, &state.4, - &state.5, &announce_request, &client_ip_sources, None, @@ -73,7 +71,6 @@ pub async fn handle_without_key( pub async fn handle_with_key( State(state): State<( Arc, - Arc, Arc, Arc, Arc, @@ -91,7 +88,6 @@ pub async fn handle_with_key( &state.2, &state.3, &state.4, - &state.5, &announce_request, &client_ip_sources, Some(key), @@ -106,7 +102,6 @@ pub async fn handle_with_key( #[allow(clippy::too_many_arguments)] async fn handle( config: &Arc, - tracker: &Arc, announce_handler: &Arc, authentication_service: &Arc, whitelist_authorization: &Arc, @@ -117,7 +112,6 @@ async fn handle( ) -> Response { let announce_data = match handle_announce( config, - tracker, announce_handler, authentication_service, whitelist_authorization, @@ -143,7 +137,6 @@ async fn handle( #[allow(clippy::too_many_arguments)] async fn handle_announce( core_config: &Arc, - tracker: &Arc, announce_handler: &Arc, authentication_service: &Arc, whitelist_authorization: &Arc, @@ -185,7 +178,6 @@ async fn handle_announce( }; let announce_data = services::announce::invoke( - tracker.clone(), announce_handler.clone(), opt_stats_event_sender.clone(), announce_request.info_hash, @@ -265,13 +257,12 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::service::AuthenticationService; - use crate::core::services::{initialize_tracker, statistics}; + use crate::core::services::statistics; use crate::core::statistics::event::sender::Sender; - use crate::core::{whitelist, Tracker}; + use crate::core::whitelist; type TrackerAndDeps = ( Arc, - Arc, Arc, Arc>>, Arc, @@ -309,12 +300,6 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = Arc::new(initialize_tracker( - &config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, @@ -325,7 +310,6 @@ mod tests { ( config, - tracker, announce_handler, stats_event_sender, whitelist_authorization, @@ -373,17 +357,15 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_missing() { - let (config, tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + let (config, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = private_tracker(); - let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); let maybe_key = None; let response = handle_announce( &config, - &tracker, &announce_handler, &authentication_service, &whitelist_authorization, @@ -403,10 +385,9 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_invalid() { - let (config, tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + let (config, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = private_tracker(); - let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); @@ -415,7 +396,6 @@ mod tests { let response = handle_announce( &config, - &tracker, &announce_handler, &authentication_service, &whitelist_authorization, @@ -441,17 +421,15 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_announced_torrent_is_not_whitelisted() { - let (config, tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + let (config, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = whitelisted_tracker(); - let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); let announce_request = sample_announce_request(); let response = handle_announce( &config, - &tracker, &announce_handler, &authentication_service, &whitelist_authorization, @@ -485,10 +463,9 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let (config, tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + let (config, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = tracker_on_reverse_proxy(); - let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); let client_ip_sources = ClientIpSources { @@ -498,7 +475,6 @@ mod tests { let response = handle_announce( &config, - &tracker, &announce_handler, &authentication_service, &whitelist_authorization, @@ -529,10 +505,9 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let (config, tracker, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = + let (config, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = tracker_not_on_reverse_proxy(); - let tracker = Arc::new(tracker); let stats_event_sender = Arc::new(stats_event_sender); let client_ip_sources = ClientIpSources { @@ -542,7 +517,6 @@ mod tests { let response = handle_announce( &config, - &tracker, &announce_handler, &authentication_service, &whitelist_authorization, diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 4f47a066f..c4013d8e9 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -20,7 +20,6 @@ use crate::core::authentication::service::AuthenticationService; use crate::core::authentication::Key; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; -use crate::core::Tracker; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::extractors::scrape_request::ExtractRequest; @@ -33,7 +32,6 @@ use crate::servers::http::v1::services; pub async fn handle_without_key( State(state): State<( Arc, - Arc, Arc, Arc, Arc>>, @@ -48,7 +46,6 @@ pub async fn handle_without_key( &state.1, &state.2, &state.3, - &state.4, &scrape_request, &client_ip_sources, None, @@ -65,7 +62,6 @@ pub async fn handle_without_key( pub async fn handle_with_key( State(state): State<( Arc, - Arc, Arc, Arc, Arc>>, @@ -81,7 +77,6 @@ pub async fn handle_with_key( &state.1, &state.2, &state.3, - &state.4, &scrape_request, &client_ip_sources, Some(key), @@ -92,7 +87,6 @@ pub async fn handle_with_key( #[allow(clippy::too_many_arguments)] async fn handle( core_config: &Arc, - tracker: &Arc, scrape_handler: &Arc, authentication_service: &Arc, stats_event_sender: &Arc>>, @@ -102,7 +96,6 @@ async fn handle( ) -> Response { let scrape_data = match handle_scrape( core_config, - tracker, scrape_handler, authentication_service, stats_event_sender, @@ -127,7 +120,6 @@ async fn handle( #[allow(clippy::too_many_arguments)] async fn handle_scrape( core_config: &Arc, - _tracker: &Arc, scrape_handler: &Arc, authentication_service: &Arc, opt_stats_event_sender: &Arc>>, @@ -185,13 +177,11 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::authentication::service::AuthenticationService; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::{initialize_tracker, statistics}; - use crate::core::Tracker; + use crate::core::services::statistics; #[allow(clippy::type_complexity)] fn private_tracker() -> ( Arc, - Arc, Arc, Arc>>, Arc, @@ -204,7 +194,7 @@ mod tests { whitelist_authorization, authentication_service, in_memory_torrent_repository, - db_torrent_repository, + _db_torrent_repository, _torrents_manager, ) = initialize_tracker_dependencies(&config); @@ -214,27 +204,14 @@ mod tests { let core_config = Arc::new(config.core.clone()); - let tracker = Arc::new(initialize_tracker( - &config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - ( - core_config, - tracker, - scrape_handler, - stats_event_sender, - authentication_service, - ) + (core_config, scrape_handler, stats_event_sender, authentication_service) } #[allow(clippy::type_complexity)] fn whitelisted_tracker() -> ( Arc, - Arc, Arc, Arc>>, Arc, @@ -247,7 +224,7 @@ mod tests { whitelist_authorization, authentication_service, in_memory_torrent_repository, - db_torrent_repository, + _db_torrent_repository, _torrents_manager, ) = initialize_tracker_dependencies(&config); @@ -257,27 +234,14 @@ mod tests { let core_config = Arc::new(config.core.clone()); - let tracker = Arc::new(initialize_tracker( - &config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - ( - core_config, - tracker, - scrape_handler, - stats_event_sender, - authentication_service, - ) + (core_config, scrape_handler, stats_event_sender, authentication_service) } #[allow(clippy::type_complexity)] fn tracker_on_reverse_proxy() -> ( Arc, - Arc, Arc, Arc>>, Arc, @@ -290,7 +254,7 @@ mod tests { whitelist_authorization, authentication_service, in_memory_torrent_repository, - db_torrent_repository, + _db_torrent_repository, _torrents_manager, ) = initialize_tracker_dependencies(&config); @@ -300,27 +264,14 @@ mod tests { let core_config = Arc::new(config.core.clone()); - let tracker = Arc::new(initialize_tracker( - &config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - ( - core_config, - tracker, - scrape_handler, - stats_event_sender, - authentication_service, - ) + (core_config, scrape_handler, stats_event_sender, authentication_service) } #[allow(clippy::type_complexity)] fn tracker_not_on_reverse_proxy() -> ( Arc, - Arc, Arc, Arc>>, Arc, @@ -333,7 +284,7 @@ mod tests { whitelist_authorization, authentication_service, in_memory_torrent_repository, - db_torrent_repository, + _db_torrent_repository, _torrents_manager, ) = initialize_tracker_dependencies(&config); @@ -343,21 +294,9 @@ mod tests { let core_config = Arc::new(config.core.clone()); - let tracker = Arc::new(initialize_tracker( - &config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - ( - core_config, - tracker, - scrape_handler, - stats_event_sender, - authentication_service, - ) + (core_config, scrape_handler, stats_event_sender, authentication_service) } fn sample_scrape_request() -> Scrape { @@ -391,14 +330,13 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { - let (core_config, tracker, scrape_handler, stats_event_sender, authentication_service) = private_tracker(); + let (core_config, scrape_handler, stats_event_sender, authentication_service) = private_tracker(); let scrape_request = sample_scrape_request(); let maybe_key = None; let scrape_data = handle_scrape( &core_config, - &tracker, &scrape_handler, &authentication_service, &stats_event_sender, @@ -416,7 +354,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() { - let (core_config, tracker, scrape_handler, stats_event_sender, authentication_service) = private_tracker(); + let (core_config, scrape_handler, stats_event_sender, authentication_service) = private_tracker(); let scrape_request = sample_scrape_request(); let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); @@ -424,7 +362,6 @@ mod tests { let scrape_data = handle_scrape( &core_config, - &tracker, &scrape_handler, &authentication_service, &stats_event_sender, @@ -450,13 +387,12 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() { - let (core_config, tracker, scrape_handler, stats_event_sender, authentication_service) = whitelisted_tracker(); + let (core_config, scrape_handler, stats_event_sender, authentication_service) = whitelisted_tracker(); let scrape_request = sample_scrape_request(); let scrape_data = handle_scrape( &core_config, - &tracker, &scrape_handler, &authentication_service, &stats_event_sender, @@ -483,7 +419,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let (core_config, tracker, scrape_handler, stats_event_sender, authentication_service) = tracker_on_reverse_proxy(); + let (core_config, scrape_handler, stats_event_sender, authentication_service) = tracker_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -492,7 +428,6 @@ mod tests { let response = handle_scrape( &core_config, - &tracker, &scrape_handler, &authentication_service, &stats_event_sender, @@ -520,8 +455,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let (core_config, tracker, scrape_handler, stats_event_sender, authentication_service) = - tracker_not_on_reverse_proxy(); + let (core_config, scrape_handler, stats_event_sender, authentication_service) = tracker_not_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -530,7 +464,6 @@ mod tests { let response = handle_scrape( &core_config, - &tracker, &scrape_handler, &authentication_service, &stats_event_sender, diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 85564ca8c..757a7d1bd 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -26,7 +26,7 @@ use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::service::AuthenticationService; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; -use crate::core::{whitelist, Tracker}; +use crate::core::whitelist; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; use crate::servers::logging::Latency; @@ -37,7 +37,6 @@ use crate::servers::logging::Latency; #[allow(clippy::too_many_arguments)] #[allow(clippy::needless_pass_by_value)] #[instrument(skip( - tracker, announce_handler, scrape_handler, authentication_service, @@ -47,7 +46,6 @@ use crate::servers::logging::Latency; ))] pub fn router( core_config: Arc, - tracker: Arc, announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, @@ -63,7 +61,6 @@ pub fn router( "/announce", get(announce::handle_without_key).with_state(( core_config.clone(), - tracker.clone(), announce_handler.clone(), authentication_service.clone(), whitelist_authorization.clone(), @@ -74,7 +71,6 @@ pub fn router( "/announce/{key}", get(announce::handle_with_key).with_state(( core_config.clone(), - tracker.clone(), announce_handler.clone(), authentication_service.clone(), whitelist_authorization.clone(), @@ -86,7 +82,6 @@ pub fn router( "/scrape", get(scrape::handle_without_key).with_state(( core_config.clone(), - tracker.clone(), scrape_handler.clone(), authentication_service.clone(), stats_event_sender.clone(), @@ -96,7 +91,6 @@ pub fn router( "/scrape/{key}", get(scrape::handle_with_key).with_state(( core_config.clone(), - tracker.clone(), scrape_handler.clone(), authentication_service.clone(), stats_event_sender.clone(), diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 5e2e8f716..e70377fd6 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -17,7 +17,6 @@ use torrust_tracker_primitives::peer; use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::{self}; -use crate::core::Tracker; /// The HTTP tracker `announce` service. /// @@ -30,7 +29,6 @@ use crate::core::Tracker; /// > like the UDP tracker, the number of TCP connections is incremented for /// > each `announce` request. pub async fn invoke( - _tracker: Arc, announce_handler: Arc, opt_stats_event_sender: Arc>>, info_hash: InfoHash, @@ -69,12 +67,11 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; - use crate::core::services::{initialize_tracker, statistics}; + use crate::core::services::statistics; use crate::core::statistics::event::sender::Sender; - use crate::core::Tracker; #[allow(clippy::type_complexity)] - fn public_tracker() -> (Arc, Arc, Arc, Arc>>) { + fn public_tracker() -> (Arc, Arc, Arc>>) { let config = configuration::ephemeral_public(); let ( @@ -89,12 +86,6 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let tracker = Arc::new(initialize_tracker( - &config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, @@ -103,7 +94,7 @@ mod tests { let core_config = Arc::new(config.core.clone()); - (core_config, tracker, announce_handler, stats_event_sender) + (core_config, announce_handler, stats_event_sender) } fn sample_info_hash() -> InfoHash { @@ -149,11 +140,11 @@ mod tests { use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; - use crate::core::{statistics, Tracker}; + use crate::core::statistics; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; - fn initialize_tracker_and_announce_handler() -> (Arc, Arc) { + fn initialize_announce_handler() -> Arc { let config = configuration::ephemeral(); let ( @@ -166,25 +157,20 @@ mod tests { _torrents_manager, ) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(Tracker::new(&config.core, &in_memory_torrent_repository, &db_torrent_repository).unwrap()); - - let announce_handler = Arc::new(AnnounceHandler::new( + Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, &db_torrent_repository, - )); - - (tracker, announce_handler) + )) } #[tokio::test] async fn it_should_return_the_announce_data() { - let (core_config, tracker, announce_handler, stats_event_sender) = public_tracker(); + let (core_config, announce_handler, stats_event_sender) = public_tracker(); let mut peer = sample_peer(); let announce_data = invoke( - tracker.clone(), announce_handler.clone(), stats_event_sender.clone(), sample_info_hash(), @@ -217,12 +203,11 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (tracker, announce_handler) = initialize_tracker_and_announce_handler(); + let announce_handler = initialize_announce_handler(); let mut peer = sample_peer_using_ipv4(); let _announce_data = invoke( - tracker, announce_handler, stats_event_sender, sample_info_hash(), @@ -232,13 +217,13 @@ mod tests { .await; } - fn tracker_with_an_ipv6_external_ip() -> (Arc, Arc) { + fn tracker_with_an_ipv6_external_ip() -> Arc { let mut configuration = configuration::ephemeral(); configuration.core.net.external_ip = Some(IpAddr::V6(Ipv6Addr::new( 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, ))); - initialize_tracker_and_announce_handler() + initialize_announce_handler() } fn peer_with_the_ipv4_loopback_ip() -> peer::Peer { @@ -265,10 +250,9 @@ mod tests { let mut peer = peer_with_the_ipv4_loopback_ip(); - let (tracker, announce_handler) = tracker_with_an_ipv6_external_ip(); + let announce_handler = tracker_with_an_ipv6_external_ip(); let _announce_data = invoke( - tracker, announce_handler, stats_event_sender, sample_info_hash(), @@ -290,12 +274,11 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (tracker, announce_handler) = initialize_tracker_and_announce_handler(); + let announce_handler = initialize_announce_handler(); let mut peer = sample_peer_using_ipv6(); let _announce_data = invoke( - tracker, announce_handler, stats_event_sender, sample_info_hash(), diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 6df267d3a..06c21d945 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -83,10 +83,8 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::initialize_tracker; - use crate::core::Tracker; - fn public_tracker_and_announce_and_scrape_handlers() -> (Arc, Arc, Arc) { + fn public_tracker_and_announce_and_scrape_handlers() -> (Arc, Arc) { let config = configuration::ephemeral_public(); let ( @@ -99,12 +97,6 @@ mod tests { _torrents_manager, ) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(initialize_tracker( - &config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, @@ -113,7 +105,7 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (tracker, announce_handler, scrape_handler) + (announce_handler, scrape_handler) } fn sample_info_hashes() -> Vec { @@ -136,7 +128,7 @@ mod tests { } } - fn test_tracker_factory() -> (Arc, Arc) { + fn initialize_scrape_handler() -> Arc { let config = configuration::ephemeral(); let ( @@ -145,15 +137,11 @@ mod tests { whitelist_authorization, _authentication_service, in_memory_torrent_repository, - db_torrent_repository, + _db_torrent_repository, _torrents_manager, ) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(Tracker::new(&config.core, &in_memory_torrent_repository, &db_torrent_repository).unwrap()); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - (tracker, scrape_handler) + Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)) } mod with_real_data { @@ -170,8 +158,8 @@ mod tests { use crate::core::statistics; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ - public_tracker_and_announce_and_scrape_handlers, sample_info_hash, sample_info_hashes, sample_peer, - test_tracker_factory, + initialize_scrape_handler, public_tracker_and_announce_and_scrape_handlers, sample_info_hash, sample_info_hashes, + sample_peer, }; #[tokio::test] @@ -179,7 +167,7 @@ mod tests { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); - let (_tracker, announce_handler, scrape_handler) = public_tracker_and_announce_and_scrape_handlers(); + let (announce_handler, scrape_handler) = public_tracker_and_announce_and_scrape_handlers(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; @@ -215,7 +203,7 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (_tracker, scrape_handler) = test_tracker_factory(); + let scrape_handler = initialize_scrape_handler(); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); @@ -233,7 +221,7 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (_tracker, scrape_handler) = test_tracker_factory(); + let scrape_handler = initialize_scrape_handler(); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); @@ -262,7 +250,7 @@ mod tests { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); - let (_tracker, announce_handler, _scrape_handler) = public_tracker_and_announce_and_scrape_handlers(); + let (announce_handler, _scrape_handler) = public_tracker_and_announce_and_scrape_handlers(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index b3ec1cb06..5589331a7 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -24,7 +24,7 @@ use super::RawRequest; use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; -use crate::core::{statistics, whitelist, Tracker}; +use crate::core::{statistics, whitelist}; use crate::servers::udp::error::Error; use crate::servers::udp::{peer_builder, UDP_TRACKER_LOG_TARGET}; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; @@ -58,11 +58,10 @@ impl CookieTimeValues { /// /// It will return an `Error` response if the request is invalid. #[allow(clippy::too_many_arguments)] -#[instrument(fields(request_id), skip(udp_request, tracker, announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, cookie_time_values, ban_service), ret(level = Level::TRACE))] +#[instrument(fields(request_id), skip(udp_request, announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, cookie_time_values, ban_service), ret(level = Level::TRACE))] pub(crate) async fn handle_packet( udp_request: RawRequest, core_config: &Arc, - tracker: &Tracker, announce_handler: &Arc, scrape_handler: &Arc, whitelist_authorization: &Arc, @@ -84,7 +83,6 @@ pub(crate) async fn handle_packet( request, udp_request.from, core_config, - tracker, announce_handler, scrape_handler, whitelist_authorization, @@ -147,7 +145,6 @@ pub(crate) async fn handle_packet( #[instrument(skip( request, remote_addr, - tracker, announce_handler, scrape_handler, whitelist_authorization, @@ -158,7 +155,6 @@ pub async fn handle_request( request: Request, remote_addr: SocketAddr, core_config: &Arc, - tracker: &Tracker, announce_handler: &Arc, scrape_handler: &Arc, whitelist_authorization: &Arc, @@ -180,7 +176,6 @@ pub async fn handle_request( remote_addr, &announce_request, core_config, - tracker, announce_handler, whitelist_authorization, opt_stats_event_sender, @@ -246,12 +241,11 @@ pub async fn handle_connect( /// /// If a error happens in the `handle_announce` function, it will just return the `ServerError`. #[allow(clippy::too_many_arguments)] -#[instrument(fields(transaction_id, connection_id, info_hash), skip(_tracker, announce_handler, whitelist_authorization, opt_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_handler, whitelist_authorization, opt_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_announce( remote_addr: SocketAddr, request: &AnnounceRequest, core_config: &Arc, - _tracker: &Tracker, announce_handler: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, @@ -507,17 +501,16 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::{initialize_tracker, initialize_whitelist_manager, statistics}; + use crate::core::services::{initialize_whitelist_manager, statistics}; use crate::core::statistics::event::sender::Sender; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::whitelist; use crate::core::whitelist::manager::WhiteListManager; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - use crate::core::{whitelist, Tracker}; use crate::CurrentClock; type TrackerAndDeps = ( Arc, - Arc, Arc, Arc, Arc, @@ -560,12 +553,6 @@ mod tests { let stats_event_sender = Arc::new(stats_event_sender); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let tracker = Arc::new(initialize_tracker( - config, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, @@ -576,7 +563,6 @@ mod tests { ( core_config, - tracker, announce_handler, scrape_handler, in_memory_torrent_repository, @@ -684,7 +670,6 @@ mod tests { #[allow(clippy::type_complexity)] fn test_tracker_factory() -> ( Arc, - Arc, Arc, Arc, Arc, @@ -703,8 +688,6 @@ mod tests { _torrents_manager, ) = initialize_tracker_dependencies(&config); - let tracker = Arc::new(Tracker::new(&config.core, &in_memory_torrent_repository, &db_torrent_repository).unwrap()); - let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, @@ -713,13 +696,7 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - ( - core_config, - tracker, - announce_handler, - scrape_handler, - whitelist_authorization, - ) + (core_config, announce_handler, scrape_handler, whitelist_authorization) } mod connect_request { @@ -935,7 +912,7 @@ mod tests { use crate::core::announce_handler::AnnounceHandler; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::{self, statistics, whitelist}; + use crate::core::{statistics, whitelist}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ @@ -948,7 +925,6 @@ mod tests { async fn an_announced_peer_should_be_added_to_the_tracker() { let ( core_config, - tracker, announce_handler, _scrape_handler, in_memory_torrent_repository, @@ -977,7 +953,6 @@ mod tests { remote_addr, &request, &core_config, - &tracker, &announce_handler, &whitelist_authorization, &stats_event_sender, @@ -1000,7 +975,6 @@ mod tests { async fn the_announced_peer_should_not_be_included_in_the_response() { let ( core_config, - tracker, announce_handler, _scrape_handler, _in_memory_torrent_repository, @@ -1020,7 +994,6 @@ mod tests { remote_addr, &request, &core_config, - &tracker, &announce_handler, &whitelist_authorization, &stats_event_sender, @@ -1052,7 +1025,6 @@ mod tests { let ( core_config, - tracker, announce_handler, _scrape_handler, in_memory_torrent_repository, @@ -1084,7 +1056,6 @@ mod tests { remote_addr, &request, &core_config, - &tracker, &announce_handler, &whitelist_authorization, &stats_event_sender, @@ -1116,7 +1087,6 @@ mod tests { async fn announce_a_new_peer_using_ipv4( core_config: Arc, - tracker: Arc, announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { @@ -1132,7 +1102,6 @@ mod tests { remote_addr, &request, &core_config, - &tracker, &announce_handler, &whitelist_authorization, &stats_event_sender, @@ -1146,7 +1115,6 @@ mod tests { async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { let ( core_config, - tracker, announce_handler, _scrape_handler, in_memory_torrent_repository, @@ -1158,13 +1126,8 @@ mod tests { add_a_torrent_peer_using_ipv6(&in_memory_torrent_repository); - let response = announce_a_new_peer_using_ipv4( - core_config.clone(), - tracker.clone(), - announce_handler.clone(), - whitelist_authorization, - ) - .await; + let response = + announce_a_new_peer_using_ipv4(core_config.clone(), announce_handler.clone(), whitelist_authorization).await; // The response should not contain the peer using IPV6 let peers: Option>> = match response { @@ -1186,13 +1149,12 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (core_config, tracker, announce_handler, _scrape_handler, whitelist_authorization) = test_tracker_factory(); + let (core_config, announce_handler, _scrape_handler, whitelist_authorization) = test_tracker_factory(); handle_announce( sample_ipv4_socket_address(), &AnnounceRequestBuilder::default().into(), &core_config, - &tracker, &announce_handler, &whitelist_authorization, &stats_event_sender, @@ -1219,7 +1181,6 @@ mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { let ( core_config, - tracker, announce_handler, _scrape_handler, in_memory_torrent_repository, @@ -1248,7 +1209,6 @@ mod tests { remote_addr, &request, &core_config, - &tracker, &announce_handler, &whitelist_authorization, &stats_event_sender, @@ -1286,7 +1246,7 @@ mod tests { use crate::core::announce_handler::AnnounceHandler; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::{self, statistics, whitelist}; + use crate::core::{statistics, whitelist}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ @@ -1299,7 +1259,6 @@ mod tests { async fn an_announced_peer_should_be_added_to_the_tracker() { let ( core_config, - tracker, announce_handler, _scrape_handler, in_memory_torrent_repository, @@ -1329,7 +1288,6 @@ mod tests { remote_addr, &request, &core_config, - &tracker, &announce_handler, &whitelist_authorization, &stats_event_sender, @@ -1352,7 +1310,6 @@ mod tests { async fn the_announced_peer_should_not_be_included_in_the_response() { let ( core_config, - tracker, announce_handler, _scrape_handler, _in_memory_torrent_repository, @@ -1375,7 +1332,6 @@ mod tests { remote_addr, &request, &core_config, - &tracker, &announce_handler, &whitelist_authorization, &stats_event_sender, @@ -1407,7 +1363,6 @@ mod tests { let ( core_config, - tracker, announce_handler, _scrape_handler, in_memory_torrent_repository, @@ -1439,7 +1394,6 @@ mod tests { remote_addr, &request, &core_config, - &tracker, &announce_handler, &whitelist_authorization, &stats_event_sender, @@ -1471,7 +1425,6 @@ mod tests { async fn announce_a_new_peer_using_ipv6( core_config: Arc, - tracker: Arc, announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { @@ -1490,7 +1443,6 @@ mod tests { remote_addr, &request, &core_config, - &tracker, &announce_handler, &whitelist_authorization, &stats_event_sender, @@ -1504,7 +1456,6 @@ mod tests { async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { let ( core_config, - tracker, announce_handler, _scrape_handler, in_memory_torrent_repository, @@ -1516,13 +1467,8 @@ mod tests { add_a_torrent_peer_using_ipv4(&in_memory_torrent_repository); - let response = announce_a_new_peer_using_ipv6( - core_config.clone(), - tracker.clone(), - announce_handler.clone(), - whitelist_authorization, - ) - .await; + let response = + announce_a_new_peer_using_ipv6(core_config.clone(), announce_handler.clone(), whitelist_authorization).await; // The response should not contain the peer using IPV4 let peers: Option>> = match response { @@ -1544,7 +1490,7 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (core_config, tracker, announce_handler, _scrape_handler, whitelist_authorization) = test_tracker_factory(); + let (core_config, announce_handler, _scrape_handler, whitelist_authorization) = test_tracker_factory(); let remote_addr = sample_ipv6_remote_addr(); @@ -1556,7 +1502,6 @@ mod tests { remote_addr, &announce_request, &core_config, - &tracker, &announce_handler, &whitelist_authorization, &stats_event_sender, @@ -1576,7 +1521,7 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; - use crate::core::{self, statistics}; + use crate::core::statistics; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; @@ -1607,10 +1552,6 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let tracker = Arc::new( - core::Tracker::new(&config.core, &in_memory_torrent_repository, &db_torrent_repository).unwrap(), - ); - let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, @@ -1643,7 +1584,6 @@ mod tests { remote_addr, &request, &core_config, - &tracker, &announce_handler, &whitelist_authorization, &stats_event_sender, @@ -1700,7 +1640,6 @@ mod tests { async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { let ( _core_config, - _tracker, _announce_handler, scrape_handler, _in_memory_torrent_repository, @@ -1810,7 +1749,6 @@ mod tests { async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { let ( _core_config, - _tracker, _announce_handler, scrape_handler, in_memory_torrent_repository, @@ -1847,7 +1785,6 @@ mod tests { async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { let ( _core_config, - _tracker, _announce_handler, scrape_handler, in_memory_torrent_repository, @@ -1892,7 +1829,6 @@ mod tests { async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { let ( _core_config, - _tracker, _announce_handler, scrape_handler, in_memory_torrent_repository, @@ -1965,8 +1901,7 @@ mod tests { let remote_addr = sample_ipv4_remote_addr(); - let (_core_config, _tracker, _announce_handler, scrape_handler, _whitelist_authorization) = - test_tracker_factory(); + let (_core_config, _announce_handler, scrape_handler, _whitelist_authorization) = test_tracker_factory(); handle_scrape( remote_addr, @@ -2006,8 +1941,7 @@ mod tests { let remote_addr = sample_ipv6_remote_addr(); - let (_core_config, _tracker, _announce_handler, scrape_handler, _whitelist_authorization) = - test_tracker_factory(); + let (_core_config, _announce_handler, scrape_handler, _whitelist_authorization) = test_tracker_factory(); handle_scrape( remote_addr, diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index 9b4d90c89..b141cc322 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -52,8 +52,7 @@ //! is designed to be as simple as possible. It uses a single UDP port and //! supports only three types of requests: `Connect`, `Announce` and `Scrape`. //! -//! Request are parsed from UDP packets using the [`aquatic_udp_protocol`](https://crates.io/crates/aquatic_udp_protocol) -//! crate and then handled by the [`Tracker`](crate::core::Tracker) struct. +//! Request are parsed from UDP packets using the [`aquatic_udp_protocol`](https://crates.io/crates/aquatic_udp_protocol). //! And then the response is also build using the [`aquatic_udp_protocol`](https://crates.io/crates/aquatic_udp_protocol) //! and converted to a UDP packet. //! diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index d0ae14029..f1b14860d 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -17,7 +17,7 @@ use crate::bootstrap::jobs::Started; use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; -use crate::core::{statistics, whitelist, Tracker}; +use crate::core::{statistics, whitelist}; use crate::servers::logging::STARTED_ON; use crate::servers::registar::ServiceHealthCheckJob; use crate::servers::signals::{shutdown_signal_with_message, Halted}; @@ -45,7 +45,6 @@ impl Launcher { /// It panics if the udp server is loaded when the tracker is private. #[allow(clippy::too_many_arguments)] #[instrument(skip( - tracker, announce_handler, scrape_handler, whitelist_authorization, @@ -57,7 +56,6 @@ impl Launcher { ))] pub async fn run_with_graceful_shutdown( core_config: Arc, - tracker: Arc, announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, @@ -103,7 +101,6 @@ impl Launcher { let () = Self::run_udp_server_main( receiver, core_config.clone(), - tracker.clone(), announce_handler.clone(), scrape_handler.clone(), whitelist_authorization.clone(), @@ -151,7 +148,6 @@ impl Launcher { #[allow(clippy::too_many_arguments)] #[instrument(skip( receiver, - tracker, announce_handler, scrape_handler, whitelist_authorization, @@ -161,7 +157,6 @@ impl Launcher { async fn run_udp_server_main( mut receiver: Receiver, core_config: Arc, - tracker: Arc, announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, @@ -235,7 +230,6 @@ impl Launcher { let processor = Processor::new( receiver.socket.clone(), core_config.clone(), - tracker.clone(), announce_handler.clone(), scrape_handler.clone(), whitelist_authorization.clone(), diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index f93d84a65..c87728361 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -83,7 +83,6 @@ mod tests { let started = stopped .start( Arc::new(cfg.core.clone()), - app_container.tracker, app_container.announce_handler, app_container.scrape_handler, app_container.whitelist_authorization, @@ -119,7 +118,6 @@ mod tests { let started = stopped .start( Arc::new(cfg.core.clone()), - app_container.tracker, app_container.announce_handler, app_container.scrape_handler, app_container.whitelist_authorization, diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 0bb7c92c4..475a36b74 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -15,14 +15,13 @@ use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::event::UdpResponseKind; -use crate::core::{statistics, whitelist, Tracker}; +use crate::core::{statistics, whitelist}; use crate::servers::udp::handlers::CookieTimeValues; use crate::servers::udp::{handlers, RawRequest}; pub struct Processor { socket: Arc, core_config: Arc, - tracker: Arc, announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, @@ -35,7 +34,6 @@ impl Processor { pub fn new( socket: Arc, core_config: Arc, - tracker: Arc, announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, @@ -45,7 +43,6 @@ impl Processor { Self { socket, core_config, - tracker, announce_handler, scrape_handler, whitelist_authorization, @@ -63,7 +60,6 @@ impl Processor { let response = handlers::handle_packet( request, &self.core_config, - &self.tracker, &self.announce_handler, &self.scrape_handler, &self.whitelist_authorization, diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index ced5fbf4a..2415b2631 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -15,7 +15,7 @@ use crate::bootstrap::jobs::Started; use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; -use crate::core::{whitelist, Tracker}; +use crate::core::whitelist; use crate::servers::signals::Halted; #[derive(Constructor, Copy, Clone, Debug, Display)] @@ -34,7 +34,6 @@ impl Spawner { pub fn spawn_launcher( &self, core_config: Arc, - tracker: Arc, announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, @@ -49,7 +48,6 @@ impl Spawner { tokio::spawn(async move { Launcher::run_with_graceful_shutdown( core_config, - tracker, announce_handler, scrape_handler, whitelist_authorization, diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index 4d63dc0a8..4d18593fe 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -17,7 +17,7 @@ use crate::bootstrap::jobs::Started; use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; -use crate::core::{whitelist, Tracker}; +use crate::core::whitelist; use crate::servers::registar::{ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::Halted; use crate::servers::udp::server::launcher::Launcher; @@ -68,11 +68,10 @@ impl Server { /// /// It panics if unable to receive the bound socket address from service. #[allow(clippy::too_many_arguments)] - #[instrument(skip(self, tracker, announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, ban_service, form), err, ret(Display, level = Level::INFO))] + #[instrument(skip(self, announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, ban_service, form), err, ret(Display, level = Level::INFO))] pub async fn start( self, core_config: Arc, - tracker: Arc, announce_handler: Arc, scrape_handler: Arc, whitelist_authorization: Arc, @@ -89,7 +88,6 @@ impl Server { // May need to wrap in a task to about a tokio bug. let task = self.state.spawner.spawn_launcher( core_config, - tracker, announce_handler, scrape_handler, whitelist_authorization, diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 927f76efe..3488456e7 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -15,7 +15,6 @@ use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; -use torrust_tracker_lib::core::Tracker; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::banning::BanService; @@ -27,7 +26,6 @@ where { pub config: Arc, pub database: Arc>, - pub tracker: Arc, pub in_memory_torrent_repository: Arc, pub keys_handler: Arc, pub authentication_service: Arc, @@ -66,7 +64,6 @@ impl Environment { Self { config, database: app_container.database.clone(), - tracker: app_container.tracker.clone(), in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), keys_handler: app_container.keys_handler.clone(), authentication_service: app_container.authentication_service.clone(), @@ -85,7 +82,6 @@ impl Environment { Environment { config: self.config, database: self.database.clone(), - tracker: self.tracker.clone(), in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), keys_handler: self.keys_handler.clone(), authentication_service: self.authentication_service.clone(), @@ -121,7 +117,6 @@ impl Environment { Environment { config: self.config, database: self.database, - tracker: self.tracker, in_memory_torrent_repository: self.in_memory_torrent_repository, keys_handler: self.keys_handler, authentication_service: self.authentication_service, diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 203dc880e..589430848 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -13,8 +13,8 @@ use torrust_tracker_lib::core::scrape_handler::ScrapeHandler; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; +use torrust_tracker_lib::core::whitelist; use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; -use torrust_tracker_lib::core::{whitelist, Tracker}; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; @@ -23,7 +23,6 @@ pub struct Environment { pub core_config: Arc, pub http_tracker_config: Arc, pub database: Arc>, - pub tracker: Arc, pub announce_handler: Arc, pub scrape_handler: Arc, pub in_memory_torrent_repository: Arc, @@ -68,7 +67,6 @@ impl Environment { http_tracker_config: config, core_config: Arc::new(configuration.core.clone()), database: app_container.database.clone(), - tracker: app_container.tracker.clone(), announce_handler: app_container.announce_handler.clone(), scrape_handler: app_container.scrape_handler.clone(), in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), @@ -89,7 +87,6 @@ impl Environment { http_tracker_config: self.http_tracker_config, core_config: self.core_config.clone(), database: self.database.clone(), - tracker: self.tracker.clone(), announce_handler: self.announce_handler.clone(), scrape_handler: self.scrape_handler.clone(), in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), @@ -104,7 +101,6 @@ impl Environment { .server .start( self.core_config, - self.tracker, self.announce_handler, self.scrape_handler, self.authentication_service, @@ -128,7 +124,6 @@ impl Environment { http_tracker_config: self.http_tracker_config, core_config: self.core_config, database: self.database, - tracker: self.tracker, announce_handler: self.announce_handler, scrape_handler: self.scrape_handler, in_memory_torrent_repository: self.in_memory_torrent_repository, diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 11967aeed..a6ddd7a83 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -11,7 +11,7 @@ use torrust_tracker_lib::core::scrape_handler::ScrapeHandler; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use torrust_tracker_lib::core::{whitelist, Tracker}; +use torrust_tracker_lib::core::whitelist; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::banning::BanService; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; @@ -26,7 +26,6 @@ where pub core_config: Arc, pub config: Arc, pub database: Arc>, - pub tracker: Arc, pub in_memory_torrent_repository: Arc, pub announce_handler: Arc, pub scrape_handler: Arc, @@ -68,7 +67,6 @@ impl Environment { core_config: Arc::new(configuration.core.clone()), config, database: app_container.database.clone(), - tracker: app_container.tracker.clone(), in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), announce_handler: app_container.announce_handler.clone(), scrape_handler: app_container.scrape_handler.clone(), @@ -88,7 +86,6 @@ impl Environment { core_config: self.core_config.clone(), config: self.config, database: self.database.clone(), - tracker: self.tracker.clone(), in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), announce_handler: self.announce_handler.clone(), scrape_handler: self.scrape_handler.clone(), @@ -101,7 +98,6 @@ impl Environment { .server .start( self.core_config, - self.tracker, self.announce_handler, self.scrape_handler, self.whitelist_authorization, @@ -133,7 +129,6 @@ impl Environment { core_config: self.core_config, config: self.config, database: self.database, - tracker: self.tracker, in_memory_torrent_repository: self.in_memory_torrent_repository, announce_handler: self.announce_handler, scrape_handler: self.scrape_handler, From c3f0bc76a6f5312d58cfaef73216e665606cf062 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 27 Jan 2025 18:52:02 +0000 Subject: [PATCH 0660/1297] refactor: [#1211] move tracker tests to InMemoryTorrentRepository --- src/core/mod.rs | 165 ------------------- src/core/torrent/repository/in_memory.rs | 196 ++++++++++++++++++++++- 2 files changed, 195 insertions(+), 166 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index f09e7d417..2c22f561b 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -462,11 +462,8 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; - use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; use torrust_tracker_primitives::peer::Peer; - use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; @@ -503,22 +500,6 @@ mod tests { (announce_handler, in_memory_torrent_repository, scrape_handler) } - fn initialize_in_memory_torrents_repository() -> Arc { - let config = configuration::ephemeral_public(); - - let ( - _database, - _in_memory_whitelist, - _whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - _db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - - in_memory_torrent_repository - } - #[allow(clippy::type_complexity)] fn whitelisted_tracker() -> ( Arc, @@ -659,152 +640,6 @@ mod tests { } } - #[tokio::test] - async fn it_should_return_the_peers_for_a_given_torrent() { - let in_memory_torrent_repository = initialize_in_memory_torrents_repository(); - - let info_hash = sample_info_hash(); - let peer = sample_peer(); - - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); - - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); - - assert_eq!(peers, vec![Arc::new(peer)]); - } - - /// It generates a peer id from a number where the number is the last - /// part of the peer ID. For example, for `12` it returns - /// `-qB00000000000000012`. - fn numeric_peer_id(two_digits_value: i32) -> PeerId { - // Format idx as a string with leading zeros, ensuring it has exactly 2 digits - let idx_str = format!("{two_digits_value:02}"); - - // Create the base part of the peer ID. - let base = b"-qB00000000000000000"; - - // Concatenate the base with idx bytes, ensuring the total length is 20 bytes. - let mut peer_id_bytes = [0u8; 20]; - peer_id_bytes[..base.len()].copy_from_slice(base); - peer_id_bytes[base.len() - idx_str.len()..].copy_from_slice(idx_str.as_bytes()); - - PeerId(peer_id_bytes) - } - - #[tokio::test] - async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { - let in_memory_torrent_repository = initialize_in_memory_torrents_repository(); - - let info_hash = sample_info_hash(); - - for idx in 1..=75 { - let peer = Peer { - peer_id: numeric_peer_id(idx), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - }; - - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); - } - - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); - - assert_eq!(peers.len(), 74); - } - - #[tokio::test] - async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let (_announce_handler, in_memory_torrent_repository, _scrape_handler) = public_tracker(); - - let info_hash = sample_info_hash(); - let peer = sample_peer(); - - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); - - let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); - - assert_eq!(peers, vec![]); - } - - #[tokio::test] - async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { - let (_announce_handler, in_memory_torrent_repository, _scrape_handler) = public_tracker(); - - let info_hash = sample_info_hash(); - - let excluded_peer = sample_peer(); - - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer); - - // Add 74 peers - for idx in 2..=75 { - let peer = Peer { - peer_id: numeric_peer_id(idx), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - }; - - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); - } - - let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); - - assert_eq!(peers.len(), 74); - } - - #[tokio::test] - async fn it_should_return_the_torrent_metrics() { - let in_memory_torrent_repository = initialize_in_memory_torrents_repository(); - - let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); - - let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); - - assert_eq!( - torrent_metrics, - TorrentsMetrics { - complete: 0, - downloaded: 0, - incomplete: 1, - torrents: 1, - } - ); - } - - #[tokio::test] - async fn it_should_get_many_the_torrent_metrics() { - let in_memory_torrent_repository = initialize_in_memory_torrents_repository(); - - let start_time = std::time::Instant::now(); - for i in 0..1_000_000 { - let () = in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher()); - } - let result_a = start_time.elapsed(); - - let start_time = std::time::Instant::now(); - let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); - let result_b = start_time.elapsed(); - - assert_eq!( - (torrent_metrics), - (TorrentsMetrics { - complete: 0, - downloaded: 0, - incomplete: 1_000_000, - torrents: 1_000_000, - }), - "{result_a:?} {result_b:?}" - ); - } - mod for_all_config_modes { mod handling_an_announce_request { diff --git a/src/core/torrent/repository/in_memory.rs b/src/core/torrent/repository/in_memory.rs index 7d469a0f5..50858d4f3 100644 --- a/src/core/torrent/repository/in_memory.rs +++ b/src/core/torrent/repository/in_memory.rs @@ -104,14 +104,80 @@ impl InMemoryTorrentRepository { #[cfg(test)] mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; + use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() + } + + /// Sample peer whose state is not relevant for the tests + fn sample_peer() -> Peer { + complete_peer() + } + + fn leecher() -> Peer { + incomplete_peer() + } + + /// A peer that counts as `complete` is swarm metadata + /// IMPORTANT!: it only counts if the it has been announce at least once before + /// announcing the `AnnounceEvent::Completed` event. + fn complete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + /// A peer that counts as `incomplete` is swarm metadata + fn incomplete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(1000), // Still bytes to download + event: AnnounceEvent::Started, + } + } + + /// It generates a peer id from a number where the number is the last + /// part of the peer ID. For example, for `12` it returns + /// `-qB00000000000000012`. + fn numeric_peer_id(two_digits_value: i32) -> PeerId { + // Format idx as a string with leading zeros, ensuring it has exactly 2 digits + let idx_str = format!("{two_digits_value:02}"); + + // Create the base part of the peer ID. + let base = b"-qB00000000000000000"; + + // Concatenate the base with idx bytes, ensuring the total length is 20 bytes. + let mut peer_id_bytes = [0u8; 20]; + peer_id_bytes[..base.len()].copy_from_slice(base); + peer_id_bytes[base.len() - idx_str.len()..].copy_from_slice(idx_str.as_bytes()); + + PeerId(peer_id_bytes) + } + #[tokio::test] - async fn should_collect_torrent_metrics() { + async fn it_should_collect_torrent_metrics() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -126,4 +192,132 @@ mod tests { } ); } + + #[tokio::test] + async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + + for idx in 1..=75 { + let peer = Peer { + peer_id: numeric_peer_id(idx), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + }; + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + } + + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); + + assert_eq!(peers.len(), 74); + } + + #[tokio::test] + async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + + let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); + + assert_eq!(peers, vec![]); + } + + #[tokio::test] + async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + + let excluded_peer = sample_peer(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer); + + // Add 74 peers + for idx in 2..=75 { + let peer = Peer { + peer_id: numeric_peer_id(idx), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + }; + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + } + + let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); + + assert_eq!(peers.len(), 74); + } + + #[tokio::test] + async fn it_should_return_the_torrent_metrics() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); + + let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + + assert_eq!( + torrent_metrics, + TorrentsMetrics { + complete: 0, + downloaded: 0, + incomplete: 1, + torrents: 1, + } + ); + } + + #[tokio::test] + async fn it_should_get_many_the_torrent_metrics() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let start_time = std::time::Instant::now(); + for i in 0..1_000_000 { + let () = in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher()); + } + let result_a = start_time.elapsed(); + + let start_time = std::time::Instant::now(); + let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let result_b = start_time.elapsed(); + + assert_eq!( + (torrent_metrics), + (TorrentsMetrics { + complete: 0, + downloaded: 0, + incomplete: 1_000_000, + torrents: 1_000_000, + }), + "{result_a:?} {result_b:?}" + ); + } + + #[tokio::test] + async fn it_should_return_the_peers_for_a_given_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); + + assert_eq!(peers, vec![Arc::new(peer)]); + } } From c785fd158e228eab61a6aa666b5b7120442b85dc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 07:16:01 +0000 Subject: [PATCH 0661/1297] refactor: [#1211] move tests to AnnounceHandler --- src/core/announce_handler.rs | 389 ++++++++++++++++++++++++++++++++++- src/core/mod.rs | 302 --------------------------- 2 files changed, 388 insertions(+), 303 deletions(-) diff --git a/src/core/announce_handler.rs b/src/core/announce_handler.rs index a037d33d4..9abf4c509 100644 --- a/src/core/announce_handler.rs +++ b/src/core/announce_handler.rs @@ -155,10 +155,397 @@ impl From for PeersWanted { } #[must_use] -pub fn assign_ip_address_to_peer(remote_client_ip: &IpAddr, tracker_external_ip: Option) -> IpAddr { +fn assign_ip_address_to_peer(remote_client_ip: &IpAddr, tracker_external_ip: Option) -> IpAddr { if let Some(host_ip) = tracker_external_ip.filter(|_| remote_client_ip.is_loopback()) { host_ip } else { *remote_client_ip } } + +#[cfg(test)] +mod tests { + // Integration tests for the core module. + + mod the_announce_handler { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::str::FromStr; + use std::sync::Arc; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + use torrust_tracker_test_helpers::configuration; + + use crate::app_test::initialize_tracker_dependencies; + use crate::core::announce_handler::AnnounceHandler; + use crate::core::scrape_handler::ScrapeHandler; + use crate::core::torrent::manager::TorrentsManager; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + + fn public_tracker() -> (Arc, Arc, Arc) { + let config = configuration::ephemeral_public(); + + let ( + _database, + _in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + _torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (announce_handler, in_memory_torrent_repository, scrape_handler) + } + + pub fn tracker_persisting_torrents_in_database( + ) -> (Arc, Arc, Arc) { + let mut config = configuration::ephemeral_listed(); + config.core.tracker_policy.persistent_torrent_completed_stat = true; + + let ( + _database, + _in_memory_whitelist, + _whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + (announce_handler, torrents_manager, in_memory_torrent_repository) + } + + fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() + } + + // The client peer IP + fn peer_ip() -> IpAddr { + IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) + } + + /// Sample peer whose state is not relevant for the tests + fn sample_peer() -> Peer { + complete_peer() + } + + /// Sample peer when for tests that need more than one peer + fn sample_peer_1() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000001"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Completed, + } + } + + /// Sample peer when for tests that need more than one peer + fn sample_peer_2() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000002"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8082), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Completed, + } + } + + fn seeder() -> Peer { + complete_peer() + } + + fn leecher() -> Peer { + incomplete_peer() + } + + fn started_peer() -> Peer { + incomplete_peer() + } + + fn completed_peer() -> Peer { + complete_peer() + } + + /// A peer that counts as `complete` is swarm metadata + /// IMPORTANT!: it only counts if the it has been announce at least once before + /// announcing the `AnnounceEvent::Completed` event. + fn complete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + /// A peer that counts as `incomplete` is swarm metadata + fn incomplete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(1000), // Still bytes to download + event: AnnounceEvent::Started, + } + } + + mod for_all_tracker_config_modes { + + mod handling_an_announce_request { + + use std::sync::Arc; + + use crate::core::announce_handler::tests::the_announce_handler::{ + peer_ip, public_tracker, sample_info_hash, sample_peer, sample_peer_1, sample_peer_2, + }; + use crate::core::announce_handler::PeersWanted; + + mod should_assign_the_ip_to_the_peer { + + use std::net::{IpAddr, Ipv4Addr}; + + use crate::core::announce_handler::assign_ip_address_to_peer; + + #[test] + fn using_the_source_ip_instead_of_the_ip_in_the_announce_request() { + let remote_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, None); + + assert_eq!(peer_ip, remote_ip); + } + + mod and_when_the_client_ip_is_a_ipv4_loopback_ip { + + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + use std::str::FromStr; + + use crate::core::announce_handler::assign_ip_address_to_peer; + + #[test] + fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { + let remote_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, None); + + assert_eq!(peer_ip, remote_ip); + } + + #[test] + fn it_should_use_the_external_tracker_ip_in_tracker_configuration_if_it_is_defined() { + let remote_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); + + let tracker_external_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); + + assert_eq!(peer_ip, tracker_external_ip); + } + + #[test] + fn it_should_use_the_external_ip_in_the_tracker_configuration_if_it_is_defined_even_if_the_external_ip_is_an_ipv6_ip( + ) { + let remote_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); + + let tracker_external_ip = + IpAddr::V6(Ipv6Addr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap()); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); + + assert_eq!(peer_ip, tracker_external_ip); + } + } + + mod and_when_client_ip_is_a_ipv6_loopback_ip { + + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + use std::str::FromStr; + + use crate::core::announce_handler::assign_ip_address_to_peer; + + #[test] + fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { + let remote_ip = IpAddr::V6(Ipv6Addr::LOCALHOST); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, None); + + assert_eq!(peer_ip, remote_ip); + } + + #[test] + fn it_should_use_the_external_ip_in_tracker_configuration_if_it_is_defined() { + let remote_ip = IpAddr::V6(Ipv6Addr::LOCALHOST); + + let tracker_external_ip = + IpAddr::V6(Ipv6Addr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap()); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); + + assert_eq!(peer_ip, tracker_external_ip); + } + + #[test] + fn it_should_use_the_external_ip_in_the_tracker_configuration_if_it_is_defined_even_if_the_external_ip_is_an_ipv4_ip( + ) { + let remote_ip = IpAddr::V6(Ipv6Addr::LOCALHOST); + + let tracker_external_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); + + let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); + + assert_eq!(peer_ip, tracker_external_ip); + } + } + } + + #[tokio::test] + async fn it_should_return_the_announce_data_with_an_empty_peer_list_when_it_is_the_first_announced_peer() { + let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + + let mut peer = sample_peer(); + + let announce_data = announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); + + assert_eq!(announce_data.peers, vec![]); + } + + #[tokio::test] + async fn it_should_return_the_announce_data_with_the_previously_announced_peers() { + let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + + let mut previously_announced_peer = sample_peer_1(); + announce_handler.announce( + &sample_info_hash(), + &mut previously_announced_peer, + &peer_ip(), + &PeersWanted::All, + ); + + let mut peer = sample_peer_2(); + let announce_data = announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); + + assert_eq!(announce_data.peers, vec![Arc::new(previously_announced_peer)]); + } + + mod it_should_update_the_swarm_stats_for_the_torrent { + + use crate::core::announce_handler::tests::the_announce_handler::{ + completed_peer, leecher, peer_ip, public_tracker, sample_info_hash, seeder, started_peer, + }; + use crate::core::announce_handler::PeersWanted; + + #[tokio::test] + async fn when_the_peer_is_a_seeder() { + let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + + let mut peer = seeder(); + + let announce_data = + announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); + + assert_eq!(announce_data.stats.complete, 1); + } + + #[tokio::test] + async fn when_the_peer_is_a_leecher() { + let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + + let mut peer = leecher(); + + let announce_data = + announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); + + assert_eq!(announce_data.stats.incomplete, 1); + } + + #[tokio::test] + async fn when_a_previously_announced_started_peer_has_completed_downloading() { + let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + + // We have to announce with "started" event because peer does not count if peer was not previously known + let mut started_peer = started_peer(); + announce_handler.announce(&sample_info_hash(), &mut started_peer, &peer_ip(), &PeersWanted::All); + + let mut completed_peer = completed_peer(); + let announce_data = + announce_handler.announce(&sample_info_hash(), &mut completed_peer, &peer_ip(), &PeersWanted::All); + + assert_eq!(announce_data.stats.downloaded, 1); + } + } + } + } + + mod handling_torrent_persistence { + + use aquatic_udp_protocol::AnnounceEvent; + use torrust_tracker_torrent_repository::entry::EntrySync; + + use crate::core::announce_handler::tests::the_announce_handler::{ + peer_ip, sample_info_hash, sample_peer, tracker_persisting_torrents_in_database, + }; + use crate::core::announce_handler::PeersWanted; + + #[tokio::test] + async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { + let (announce_handler, torrents_manager, in_memory_torrent_repository) = + tracker_persisting_torrents_in_database(); + + let info_hash = sample_info_hash(); + + let mut peer = sample_peer(); + + peer.event = AnnounceEvent::Started; + let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + assert_eq!(announce_data.stats.downloaded, 0); + + peer.event = AnnounceEvent::Completed; + let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + assert_eq!(announce_data.stats.downloaded, 1); + + // Remove the newly updated torrent from memory + let _unused = in_memory_torrent_repository.remove(&info_hash); + + torrents_manager.load_torrents_from_database().unwrap(); + + let torrent_entry = in_memory_torrent_repository + .get(&info_hash) + .expect("it should be able to get entry"); + + // It persists the number of completed peers. + assert_eq!(torrent_entry.get_swarm_metadata().downloaded, 1); + + // It does not persist the peers + assert!(torrent_entry.peers_is_empty()); + } + } + } +} diff --git a/src/core/mod.rs b/src/core/mod.rs index 2c22f561b..26d5a43df 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -471,7 +471,6 @@ mod tests { use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; use crate::core::services::initialize_whitelist_manager; - use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::whitelist; use crate::core::whitelist::manager::WhiteListManager; @@ -532,30 +531,6 @@ mod tests { (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) } - pub fn tracker_persisting_torrents_in_database( - ) -> (Arc, Arc, Arc) { - let mut config = configuration::ephemeral_listed(); - config.core.tracker_policy.persistent_torrent_completed_stat = true; - - let ( - _database, - _in_memory_whitelist, - _whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - (announce_handler, torrents_manager, in_memory_torrent_repository) - } - fn sample_info_hash() -> InfoHash { "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() } @@ -565,53 +540,6 @@ mod tests { IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) } - /// Sample peer whose state is not relevant for the tests - fn sample_peer() -> Peer { - complete_peer() - } - - /// Sample peer when for tests that need more than one peer - fn sample_peer_1() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000001"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), - event: AnnounceEvent::Completed, - } - } - - /// Sample peer when for tests that need more than one peer - fn sample_peer_2() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000002"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8082), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), - event: AnnounceEvent::Completed, - } - } - - fn seeder() -> Peer { - complete_peer() - } - - fn leecher() -> Peer { - incomplete_peer() - } - - fn started_peer() -> Peer { - incomplete_peer() - } - - fn completed_peer() -> Peer { - complete_peer() - } - /// A peer that counts as `complete` is swarm metadata /// IMPORTANT!: it only counts if the it has been announce at least once before /// announcing the `AnnounceEvent::Completed` event. @@ -642,190 +570,6 @@ mod tests { mod for_all_config_modes { - mod handling_an_announce_request { - - use std::sync::Arc; - - use crate::core::announce_handler::PeersWanted; - use crate::core::tests::the_tracker::{ - peer_ip, public_tracker, sample_info_hash, sample_peer, sample_peer_1, sample_peer_2, - }; - - mod should_assign_the_ip_to_the_peer { - - use std::net::{IpAddr, Ipv4Addr}; - - use crate::core::announce_handler::assign_ip_address_to_peer; - - #[test] - fn using_the_source_ip_instead_of_the_ip_in_the_announce_request() { - let remote_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, None); - - assert_eq!(peer_ip, remote_ip); - } - - mod and_when_the_client_ip_is_a_ipv4_loopback_ip { - - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; - use std::str::FromStr; - - use crate::core::announce_handler::assign_ip_address_to_peer; - - #[test] - fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { - let remote_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, None); - - assert_eq!(peer_ip, remote_ip); - } - - #[test] - fn it_should_use_the_external_tracker_ip_in_tracker_configuration_if_it_is_defined() { - let remote_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); - - let tracker_external_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); - - assert_eq!(peer_ip, tracker_external_ip); - } - - #[test] - fn it_should_use_the_external_ip_in_the_tracker_configuration_if_it_is_defined_even_if_the_external_ip_is_an_ipv6_ip( - ) { - let remote_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); - - let tracker_external_ip = - IpAddr::V6(Ipv6Addr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap()); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); - - assert_eq!(peer_ip, tracker_external_ip); - } - } - - mod and_when_client_ip_is_a_ipv6_loopback_ip { - - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; - use std::str::FromStr; - - use crate::core::announce_handler::assign_ip_address_to_peer; - - #[test] - fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { - let remote_ip = IpAddr::V6(Ipv6Addr::LOCALHOST); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, None); - - assert_eq!(peer_ip, remote_ip); - } - - #[test] - fn it_should_use_the_external_ip_in_tracker_configuration_if_it_is_defined() { - let remote_ip = IpAddr::V6(Ipv6Addr::LOCALHOST); - - let tracker_external_ip = - IpAddr::V6(Ipv6Addr::from_str("2345:0425:2CA1:0000:0000:0567:5673:23b5").unwrap()); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); - - assert_eq!(peer_ip, tracker_external_ip); - } - - #[test] - fn it_should_use_the_external_ip_in_the_tracker_configuration_if_it_is_defined_even_if_the_external_ip_is_an_ipv4_ip( - ) { - let remote_ip = IpAddr::V6(Ipv6Addr::LOCALHOST); - - let tracker_external_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); - - let peer_ip = assign_ip_address_to_peer(&remote_ip, Some(tracker_external_ip)); - - assert_eq!(peer_ip, tracker_external_ip); - } - } - } - - #[tokio::test] - async fn it_should_return_the_announce_data_with_an_empty_peer_list_when_it_is_the_first_announced_peer() { - let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); - - let mut peer = sample_peer(); - - let announce_data = announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); - - assert_eq!(announce_data.peers, vec![]); - } - - #[tokio::test] - async fn it_should_return_the_announce_data_with_the_previously_announced_peers() { - let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); - - let mut previously_announced_peer = sample_peer_1(); - announce_handler.announce( - &sample_info_hash(), - &mut previously_announced_peer, - &peer_ip(), - &PeersWanted::All, - ); - - let mut peer = sample_peer_2(); - let announce_data = announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); - - assert_eq!(announce_data.peers, vec![Arc::new(previously_announced_peer)]); - } - - mod it_should_update_the_swarm_stats_for_the_torrent { - - use crate::core::announce_handler::PeersWanted; - use crate::core::tests::the_tracker::{ - completed_peer, leecher, peer_ip, public_tracker, sample_info_hash, seeder, started_peer, - }; - - #[tokio::test] - async fn when_the_peer_is_a_seeder() { - let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); - - let mut peer = seeder(); - - let announce_data = - announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); - - assert_eq!(announce_data.stats.complete, 1); - } - - #[tokio::test] - async fn when_the_peer_is_a_leecher() { - let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); - - let mut peer = leecher(); - - let announce_data = - announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); - - assert_eq!(announce_data.stats.incomplete, 1); - } - - #[tokio::test] - async fn when_a_previously_announced_started_peer_has_completed_downloading() { - let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); - - // We have to announce with "started" event because peer does not count if peer was not previously known - let mut started_peer = started_peer(); - announce_handler.announce(&sample_info_hash(), &mut started_peer, &peer_ip(), &PeersWanted::All); - - let mut completed_peer = completed_peer(); - let announce_data = - announce_handler.announce(&sample_info_hash(), &mut completed_peer, &peer_ip(), &PeersWanted::All); - - assert_eq!(announce_data.stats.downloaded, 1); - } - } - } - mod handling_a_scrape_request { use std::net::{IpAddr, Ipv4Addr}; @@ -964,8 +708,6 @@ mod tests { } } - mod handling_an_announce_request {} - mod handling_an_scrape_request { use bittorrent_primitives::info_hash::InfoHash; @@ -1012,49 +754,5 @@ mod tests { } } } - - mod handling_torrent_persistence { - - use aquatic_udp_protocol::AnnounceEvent; - use torrust_tracker_torrent_repository::entry::EntrySync; - - use crate::core::announce_handler::PeersWanted; - use crate::core::tests::the_tracker::{ - peer_ip, sample_info_hash, sample_peer, tracker_persisting_torrents_in_database, - }; - - #[tokio::test] - async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { - let (announce_handler, torrents_manager, in_memory_torrent_repository) = - tracker_persisting_torrents_in_database(); - - let info_hash = sample_info_hash(); - - let mut peer = sample_peer(); - - peer.event = AnnounceEvent::Started; - let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); - assert_eq!(announce_data.stats.downloaded, 0); - - peer.event = AnnounceEvent::Completed; - let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); - assert_eq!(announce_data.stats.downloaded, 1); - - // Remove the newly updated torrent from memory - let _unused = in_memory_torrent_repository.remove(&info_hash); - - torrents_manager.load_torrents_from_database().unwrap(); - - let torrent_entry = in_memory_torrent_repository - .get(&info_hash) - .expect("it should be able to get entry"); - - // It persists the number of completed peers. - assert_eq!(torrent_entry.get_swarm_metadata().downloaded, 1); - - // It does not persist the peers - assert!(torrent_entry.peers_is_empty()); - } - } } } From e2d573b0d4b855cb1d2d006047899ce236a88440 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 07:33:53 +0000 Subject: [PATCH 0662/1297] refactor: [#1211] move tests to whitelist module --- src/core/announce_handler.rs | 2 - src/core/mod.rs | 84 --------------------- src/core/whitelist/authorization.rs | 82 +++++++++++++++++++++ src/core/whitelist/manager.rs | 109 ++++++++++++++++++++++++++++ src/core/whitelist/mod.rs | 82 +++++++++++++++++++++ 5 files changed, 273 insertions(+), 86 deletions(-) diff --git a/src/core/announce_handler.rs b/src/core/announce_handler.rs index 9abf4c509..2ebd4daf0 100644 --- a/src/core/announce_handler.rs +++ b/src/core/announce_handler.rs @@ -165,8 +165,6 @@ fn assign_ip_address_to_peer(remote_client_ip: &IpAddr, tracker_external_ip: Opt #[cfg(test)] mod tests { - // Integration tests for the core module. - mod the_announce_handler { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; diff --git a/src/core/mod.rs b/src/core/mod.rs index 26d5a43df..937cc4f78 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -453,8 +453,6 @@ pub mod peer_tests; #[cfg(test)] mod tests { - // Integration tests for the core module. - mod the_tracker { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; @@ -626,88 +624,6 @@ mod tests { mod configured_as_whitelisted { - mod handling_authorization { - use crate::core::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; - - #[tokio::test] - async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { - let (_announce_handler, whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); - - let info_hash = sample_info_hash(); - - let result = whitelist_manager.add_torrent_to_whitelist(&info_hash).await; - assert!(result.is_ok()); - - let result = whitelist_authorization.authorize(&info_hash).await; - assert!(result.is_ok()); - } - - #[tokio::test] - async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { - let (_announce_handler, whitelist_authorization, _whitelist_manager, _scrape_handler) = whitelisted_tracker(); - - let info_hash = sample_info_hash(); - - let result = whitelist_authorization.authorize(&info_hash).await; - assert!(result.is_err()); - } - } - - mod handling_the_torrent_whitelist { - use crate::core::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; - - // todo: after extracting the WhitelistManager from the Tracker, - // there is no need to use the tracker to test the whitelist. - // Test not using the `tracker` (`_tracker` variable) should be - // moved to the whitelist module. - - #[tokio::test] - async fn it_should_add_a_torrent_to_the_whitelist() { - let (_announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); - - let info_hash = sample_info_hash(); - - whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); - - assert!(whitelist_manager.is_info_hash_whitelisted(&info_hash).await); - } - - #[tokio::test] - async fn it_should_remove_a_torrent_from_the_whitelist() { - let (_announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); - - let info_hash = sample_info_hash(); - - whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); - - whitelist_manager.remove_torrent_from_whitelist(&info_hash).await.unwrap(); - - assert!(!whitelist_manager.is_info_hash_whitelisted(&info_hash).await); - } - - mod persistence { - use crate::core::tests::the_tracker::{sample_info_hash, whitelisted_tracker}; - - #[tokio::test] - async fn it_should_load_the_whitelist_from_the_database() { - let (_announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = - whitelisted_tracker(); - - let info_hash = sample_info_hash(); - - whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); - - whitelist_manager.remove_torrent_from_memory_whitelist(&info_hash).await; - - assert!(!whitelist_manager.is_info_hash_whitelisted(&info_hash).await); - - whitelist_manager.load_whitelist_from_database().await.unwrap(); - - assert!(whitelist_manager.is_info_hash_whitelisted(&info_hash).await); - } - } - } - mod handling_an_scrape_request { use bittorrent_primitives::info_hash::InfoHash; diff --git a/src/core/whitelist/authorization.rs b/src/core/whitelist/authorization.rs index 74029495f..55410d934 100644 --- a/src/core/whitelist/authorization.rs +++ b/src/core/whitelist/authorization.rs @@ -57,3 +57,85 @@ impl Authorization { self.in_memory_whitelist.contains(info_hash).await } } + +#[cfg(test)] +mod tests { + + use std::sync::Arc; + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_test_helpers::configuration; + + use crate::app_test::initialize_tracker_dependencies; + use crate::core::announce_handler::AnnounceHandler; + use crate::core::scrape_handler::ScrapeHandler; + use crate::core::services::initialize_whitelist_manager; + use crate::core::whitelist; + use crate::core::whitelist::manager::WhiteListManager; + + #[allow(clippy::type_complexity)] + fn whitelisted_tracker() -> ( + Arc, + Arc, + Arc, + Arc, + ) { + let config = configuration::ephemeral_listed(); + + let ( + database, + in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + _torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) + } + + fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() + } + + mod configured_as_whitelisted { + + mod handling_authorization { + use crate::core::whitelist::authorization::tests::{sample_info_hash, whitelisted_tracker}; + + #[tokio::test] + async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { + let (_announce_handler, whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + + let info_hash = sample_info_hash(); + + let result = whitelist_manager.add_torrent_to_whitelist(&info_hash).await; + assert!(result.is_ok()); + + let result = whitelist_authorization.authorize(&info_hash).await; + assert!(result.is_ok()); + } + + #[tokio::test] + async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { + let (_announce_handler, whitelist_authorization, _whitelist_manager, _scrape_handler) = whitelisted_tracker(); + + let info_hash = sample_info_hash(); + + let result = whitelist_authorization.authorize(&info_hash).await; + assert!(result.is_err()); + } + } + } +} diff --git a/src/core/whitelist/manager.rs b/src/core/whitelist/manager.rs index 757053f71..23095cfb7 100644 --- a/src/core/whitelist/manager.rs +++ b/src/core/whitelist/manager.rs @@ -89,3 +89,112 @@ impl WhiteListManager { Ok(()) } } + +#[cfg(test)] +mod tests { + + use std::sync::Arc; + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_test_helpers::configuration; + + use crate::app_test::initialize_tracker_dependencies; + use crate::core::announce_handler::AnnounceHandler; + use crate::core::scrape_handler::ScrapeHandler; + use crate::core::services::initialize_whitelist_manager; + use crate::core::whitelist; + use crate::core::whitelist::manager::WhiteListManager; + + #[allow(clippy::type_complexity)] + fn whitelisted_tracker() -> ( + Arc, + Arc, + Arc, + Arc, + ) { + let config = configuration::ephemeral_listed(); + + let ( + database, + in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + _torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) + } + + fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() + } + + mod configured_as_whitelisted { + + mod handling_the_torrent_whitelist { + use crate::core::whitelist::manager::tests::{sample_info_hash, whitelisted_tracker}; + + // todo: after extracting the WhitelistManager from the Tracker, + // there is no need to use the tracker to test the whitelist. + // Test not using the `tracker` (`_tracker` variable) should be + // moved to the whitelist module. + + #[tokio::test] + async fn it_should_add_a_torrent_to_the_whitelist() { + let (_announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + + let info_hash = sample_info_hash(); + + whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); + + assert!(whitelist_manager.is_info_hash_whitelisted(&info_hash).await); + } + + #[tokio::test] + async fn it_should_remove_a_torrent_from_the_whitelist() { + let (_announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + + let info_hash = sample_info_hash(); + + whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); + + whitelist_manager.remove_torrent_from_whitelist(&info_hash).await.unwrap(); + + assert!(!whitelist_manager.is_info_hash_whitelisted(&info_hash).await); + } + + mod persistence { + use crate::core::whitelist::manager::tests::{sample_info_hash, whitelisted_tracker}; + + #[tokio::test] + async fn it_should_load_the_whitelist_from_the_database() { + let (_announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + + let info_hash = sample_info_hash(); + + whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); + + whitelist_manager.remove_torrent_from_memory_whitelist(&info_hash).await; + + assert!(!whitelist_manager.is_info_hash_whitelisted(&info_hash).await); + + whitelist_manager.load_whitelist_from_database().await.unwrap(); + + assert!(whitelist_manager.is_info_hash_whitelisted(&info_hash).await); + } + } + } + } +} diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs index 89c69b761..cd4c238f7 100644 --- a/src/core/whitelist/mod.rs +++ b/src/core/whitelist/mod.rs @@ -1,3 +1,85 @@ pub mod authorization; pub mod manager; pub mod repository; + +#[cfg(test)] +mod tests { + + use std::sync::Arc; + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_test_helpers::configuration; + + use crate::app_test::initialize_tracker_dependencies; + use crate::core::announce_handler::AnnounceHandler; + use crate::core::scrape_handler::ScrapeHandler; + use crate::core::services::initialize_whitelist_manager; + use crate::core::whitelist; + use crate::core::whitelist::manager::WhiteListManager; + + #[allow(clippy::type_complexity)] + fn whitelisted_tracker() -> ( + Arc, + Arc, + Arc, + Arc, + ) { + let config = configuration::ephemeral_listed(); + + let ( + database, + in_memory_whitelist, + whitelist_authorization, + _authentication_service, + in_memory_torrent_repository, + db_torrent_repository, + _torrents_manager, + ) = initialize_tracker_dependencies(&config); + + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) + } + + fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() + } + + mod configured_as_whitelisted { + + mod handling_authorization { + use crate::core::whitelist::tests::{sample_info_hash, whitelisted_tracker}; + + #[tokio::test] + async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { + let (_announce_handler, whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + + let info_hash = sample_info_hash(); + + let result = whitelist_manager.add_torrent_to_whitelist(&info_hash).await; + assert!(result.is_ok()); + + let result = whitelist_authorization.authorize(&info_hash).await; + assert!(result.is_ok()); + } + + #[tokio::test] + async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { + let (_announce_handler, whitelist_authorization, _whitelist_manager, _scrape_handler) = whitelisted_tracker(); + + let info_hash = sample_info_hash(); + + let result = whitelist_authorization.authorize(&info_hash).await; + assert!(result.is_err()); + } + } + } +} From 22320f5ba009d13333d3c6f21e27be682dde2f4d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 07:39:39 +0000 Subject: [PATCH 0663/1297] refactor: [#1211] move test to torrust_tracker_primitives::core --- packages/primitives/src/core.rs | 23 +++++++++++++++++++++++ src/core/mod.rs | 21 +-------------------- 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/packages/primitives/src/core.rs b/packages/primitives/src/core.rs index 0c0f68b8b..fe69c8959 100644 --- a/packages/primitives/src/core.rs +++ b/packages/primitives/src/core.rs @@ -56,3 +56,26 @@ impl ScrapeData { self.files.insert(*info_hash, SwarmMetadata::zeroed()); } } + +#[cfg(test)] +mod tests { + use bittorrent_primitives::info_hash::InfoHash; + + use crate::core::ScrapeData; + + fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() + } + + #[test] + fn it_should_be_able_to_build_a_zeroed_scrape_data_for_a_list_of_info_hashes() { + // Zeroed scrape data is used when the authentication for the scrape request fails. + + let sample_info_hash = sample_info_hash(); + + let mut expected_scrape_data = ScrapeData::empty(); + expected_scrape_data.add_file_with_zeroed_metadata(&sample_info_hash); + + assert_eq!(ScrapeData::zeroed(&vec![sample_info_hash]), expected_scrape_data); + } +} diff --git a/src/core/mod.rs b/src/core/mod.rs index 937cc4f78..1a3c77555 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -460,7 +460,6 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; - use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; @@ -529,10 +528,6 @@ mod tests { (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) } - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() - } - // The client peer IP fn peer_ip() -> IpAddr { IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) @@ -631,21 +626,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::core::announce_handler::PeersWanted; - use crate::core::tests::the_tracker::{ - complete_peer, incomplete_peer, peer_ip, sample_info_hash, whitelisted_tracker, - }; - - #[test] - fn it_should_be_able_to_build_a_zeroed_scrape_data_for_a_list_of_info_hashes() { - // Zeroed scrape data is used when the authentication for the scrape request fails. - - let sample_info_hash = sample_info_hash(); - - let mut expected_scrape_data = ScrapeData::empty(); - expected_scrape_data.add_file_with_zeroed_metadata(&sample_info_hash); - - assert_eq!(ScrapeData::zeroed(&vec![sample_info_hash]), expected_scrape_data); - } + use crate::core::tests::the_tracker::{complete_peer, incomplete_peer, peer_ip, whitelisted_tracker}; #[tokio::test] async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { From e8a2c8b843d5e78eb2c6b0914f947dbdcd67b467 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 07:55:07 +0000 Subject: [PATCH 0664/1297] refactor: [#1211] clean tests in core mod --- src/core/mod.rs | 74 +++++++++++++++++-------------------------------- 1 file changed, 26 insertions(+), 48 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 1a3c77555..5a7bbc2fb 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -460,62 +460,38 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; - use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::initialize_whitelist_manager; + use crate::core::services::initialize_database; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use crate::core::whitelist; - use crate::core::whitelist::manager::WhiteListManager; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - fn public_tracker() -> (Arc, Arc, Arc) { + fn initialize_handlers_for_public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); - - let ( - _database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - (announce_handler, in_memory_torrent_repository, scrape_handler) + initialize_handlers(&config) } - #[allow(clippy::type_complexity)] - fn whitelisted_tracker() -> ( - Arc, - Arc, - Arc, - Arc, - ) { + fn initialize_handlers_for_listed_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_listed(); + initialize_handlers(&config) + } - let ( - database, - in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + fn initialize_handlers(config: &Configuration) -> (Arc, Arc) { + let database = initialize_database(config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + &config.core, + &in_memory_whitelist.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, @@ -525,7 +501,7 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) + (announce_handler, scrape_handler) } // The client peer IP @@ -572,11 +548,11 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::core::announce_handler::PeersWanted; - use crate::core::tests::the_tracker::{complete_peer, incomplete_peer, public_tracker}; + use crate::core::tests::the_tracker::{complete_peer, incomplete_peer, initialize_handlers_for_public_tracker}; #[tokio::test] async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() { - let (announce_handler, _in_memory_torrent_repository, scrape_handler) = public_tracker(); + let (announce_handler, scrape_handler) = initialize_handlers_for_public_tracker(); let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // # DevSkim: ignore DS173237 @@ -619,18 +595,20 @@ mod tests { mod configured_as_whitelisted { - mod handling_an_scrape_request { + mod handling_a_scrape_request { use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::core::announce_handler::PeersWanted; - use crate::core::tests::the_tracker::{complete_peer, incomplete_peer, peer_ip, whitelisted_tracker}; + use crate::core::tests::the_tracker::{ + complete_peer, incomplete_peer, initialize_handlers_for_listed_tracker, peer_ip, + }; #[tokio::test] async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { - let (announce_handler, _whitelist_authorization, _whitelist_manager, scrape_handler) = whitelisted_tracker(); + let (announce_handler, scrape_handler) = initialize_handlers_for_listed_tracker(); let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // # DevSkim: ignore DS173237 From 55dc8b0177864b8915cb0aa894f6fb7653ada5e7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 10:16:52 +0000 Subject: [PATCH 0665/1297] refactor: [#1211] clean AnnounceHandler tests --- src/core/announce_handler.rs | 97 ++++++++++++++---------------------- src/core/core_tests.rs | 33 ++++++++++++ src/core/mod.rs | 29 +---------- 3 files changed, 72 insertions(+), 87 deletions(-) create mode 100644 src/core/core_tests.rs diff --git a/src/core/announce_handler.rs b/src/core/announce_handler.rs index 2ebd4daf0..b30b071d3 100644 --- a/src/core/announce_handler.rs +++ b/src/core/announce_handler.rs @@ -177,62 +177,19 @@ mod tests { use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; - use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; + use crate::core::core_tests::initialize_handlers; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::torrent::manager::TorrentsManager; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - fn public_tracker() -> (Arc, Arc, Arc) { + fn public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); - - let ( - _database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - (announce_handler, in_memory_torrent_repository, scrape_handler) - } - - pub fn tracker_persisting_torrents_in_database( - ) -> (Arc, Arc, Arc) { - let mut config = configuration::ephemeral_listed(); - config.core.tracker_policy.persistent_torrent_completed_stat = true; - - let ( - _database, - _in_memory_whitelist, - _whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - (announce_handler, torrents_manager, in_memory_torrent_repository) + initialize_handlers(&config) } fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") } // The client peer IP @@ -426,7 +383,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_announce_data_with_an_empty_peer_list_when_it_is_the_first_announced_peer() { - let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (announce_handler, _scrape_handler) = public_tracker(); let mut peer = sample_peer(); @@ -437,7 +394,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_announce_data_with_the_previously_announced_peers() { - let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (announce_handler, _scrape_handler) = public_tracker(); let mut previously_announced_peer = sample_peer_1(); announce_handler.announce( @@ -462,7 +419,7 @@ mod tests { #[tokio::test] async fn when_the_peer_is_a_seeder() { - let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (announce_handler, _scrape_handler) = public_tracker(); let mut peer = seeder(); @@ -474,7 +431,7 @@ mod tests { #[tokio::test] async fn when_the_peer_is_a_leecher() { - let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (announce_handler, _scrape_handler) = public_tracker(); let mut peer = leecher(); @@ -486,7 +443,7 @@ mod tests { #[tokio::test] async fn when_a_previously_announced_started_peer_has_completed_downloading() { - let (announce_handler, _in_memory_torrent_repository, _scrape_handler) = public_tracker(); + let (announce_handler, _scrape_handler) = public_tracker(); // We have to announce with "started" event because peer does not count if peer was not previously known let mut started_peer = started_peer(); @@ -504,18 +461,38 @@ mod tests { mod handling_torrent_persistence { + use std::sync::Arc; + use aquatic_udp_protocol::AnnounceEvent; + use torrust_tracker_test_helpers::configuration; use torrust_tracker_torrent_repository::entry::EntrySync; - use crate::core::announce_handler::tests::the_announce_handler::{ - peer_ip, sample_info_hash, sample_peer, tracker_persisting_torrents_in_database, - }; - use crate::core::announce_handler::PeersWanted; + use crate::core::announce_handler::tests::the_announce_handler::{peer_ip, sample_info_hash, sample_peer}; + use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; + use crate::core::services::initialize_database; + use crate::core::torrent::manager::TorrentsManager; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; #[tokio::test] async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { - let (announce_handler, torrents_manager, in_memory_torrent_repository) = - tracker_persisting_torrents_in_database(); + let mut config = configuration::ephemeral_listed(); + + config.core.tracker_policy.persistent_torrent_completed_stat = true; + + let database = initialize_database(&config); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let torrents_manager = Arc::new(TorrentsManager::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); let info_hash = sample_info_hash(); diff --git a/src/core/core_tests.rs b/src/core/core_tests.rs new file mode 100644 index 000000000..6b9947700 --- /dev/null +++ b/src/core/core_tests.rs @@ -0,0 +1,33 @@ +use std::sync::Arc; + +use torrust_tracker_configuration::Configuration; + +use super::announce_handler::AnnounceHandler; +use super::scrape_handler::ScrapeHandler; +use super::services::initialize_database; +use super::torrent::repository::in_memory::InMemoryTorrentRepository; +use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use super::whitelist::repository::in_memory::InMemoryWhitelist; +use super::whitelist::{self}; + +#[must_use] +pub fn initialize_handlers(config: &Configuration) -> (Arc, Arc) { + let database = initialize_database(config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + &config.core, + &in_memory_whitelist.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (announce_handler, scrape_handler) +} diff --git a/src/core/mod.rs b/src/core/mod.rs index 5a7bbc2fb..581dd02f6 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -449,6 +449,7 @@ pub mod statistics; pub mod torrent; pub mod whitelist; +pub mod core_tests; pub mod peer_tests; #[cfg(test)] @@ -460,18 +461,13 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; - use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; use crate::core::announce_handler::AnnounceHandler; + use crate::core::core_tests::initialize_handlers; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::initialize_database; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - use crate::core::whitelist; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; fn initialize_handlers_for_public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); @@ -483,27 +479,6 @@ mod tests { initialize_handlers(&config) } - fn initialize_handlers(config: &Configuration) -> (Arc, Arc) { - let database = initialize_database(config); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( - &config.core, - &in_memory_whitelist.clone(), - )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - (announce_handler, scrape_handler) - } - // The client peer IP fn peer_ip() -> IpAddr { IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) From 65290213144799787544808db0366b47aaf975b5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 10:24:54 +0000 Subject: [PATCH 0666/1297] refactor: [#1211] remove duplicate function --- packages/primitives/src/core.rs | 11 +++++++++-- src/core/announce_handler.rs | 16 ++++++---------- src/core/core_tests.rs | 11 +++++++++++ src/core/torrent/repository/in_memory.rs | 6 +----- src/core/whitelist/authorization.rs | 8 ++------ src/core/whitelist/manager.rs | 11 ++++------- src/core/whitelist/mod.rs | 8 ++------ src/core/whitelist/repository/in_memory.rs | 6 +----- src/servers/http/v1/services/announce.rs | 8 ++------ src/servers/http/v1/services/scrape.rs | 5 +---- 10 files changed, 39 insertions(+), 51 deletions(-) diff --git a/packages/primitives/src/core.rs b/packages/primitives/src/core.rs index fe69c8959..aa2fe6926 100644 --- a/packages/primitives/src/core.rs +++ b/packages/primitives/src/core.rs @@ -59,12 +59,19 @@ impl ScrapeData { #[cfg(test)] mod tests { + use bittorrent_primitives::info_hash::InfoHash; use crate::core::ScrapeData; - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") } #[test] diff --git a/src/core/announce_handler.rs b/src/core/announce_handler.rs index b30b071d3..e19a1798b 100644 --- a/src/core/announce_handler.rs +++ b/src/core/announce_handler.rs @@ -172,7 +172,6 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; - use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; @@ -186,12 +185,6 @@ mod tests { initialize_handlers(&config) } - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 - .parse::() - .expect("String should be a valid info hash") - } - // The client peer IP fn peer_ip() -> IpAddr { IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) @@ -279,9 +272,10 @@ mod tests { use std::sync::Arc; use crate::core::announce_handler::tests::the_announce_handler::{ - peer_ip, public_tracker, sample_info_hash, sample_peer, sample_peer_1, sample_peer_2, + peer_ip, public_tracker, sample_peer, sample_peer_1, sample_peer_2, }; use crate::core::announce_handler::PeersWanted; + use crate::core::core_tests::sample_info_hash; mod should_assign_the_ip_to_the_peer { @@ -413,9 +407,10 @@ mod tests { mod it_should_update_the_swarm_stats_for_the_torrent { use crate::core::announce_handler::tests::the_announce_handler::{ - completed_peer, leecher, peer_ip, public_tracker, sample_info_hash, seeder, started_peer, + completed_peer, leecher, peer_ip, public_tracker, seeder, started_peer, }; use crate::core::announce_handler::PeersWanted; + use crate::core::core_tests::sample_info_hash; #[tokio::test] async fn when_the_peer_is_a_seeder() { @@ -467,8 +462,9 @@ mod tests { use torrust_tracker_test_helpers::configuration; use torrust_tracker_torrent_repository::entry::EntrySync; - use crate::core::announce_handler::tests::the_announce_handler::{peer_ip, sample_info_hash, sample_peer}; + use crate::core::announce_handler::tests::the_announce_handler::{peer_ip, sample_peer}; use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; + use crate::core::core_tests::sample_info_hash; use crate::core::services::initialize_database; use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; diff --git a/src/core/core_tests.rs b/src/core/core_tests.rs index 6b9947700..be93fb1dc 100644 --- a/src/core/core_tests.rs +++ b/src/core/core_tests.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::Configuration; use super::announce_handler::AnnounceHandler; @@ -10,6 +11,16 @@ use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; use super::whitelist::repository::in_memory::InMemoryWhitelist; use super::whitelist::{self}; +/// # Panics +/// +/// Will panic if the string representation of the info hash is not a valid info hash. +#[must_use] +pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") +} + #[must_use] pub fn initialize_handlers(config: &Configuration) -> (Arc, Arc) { let database = initialize_database(config); diff --git a/src/core/torrent/repository/in_memory.rs b/src/core/torrent/repository/in_memory.rs index 50858d4f3..908abd143 100644 --- a/src/core/torrent/repository/in_memory.rs +++ b/src/core/torrent/repository/in_memory.rs @@ -109,18 +109,14 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; - use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::DurationSinceUnixEpoch; + use crate::core::core_tests::sample_info_hash; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() - } - /// Sample peer whose state is not relevant for the tests fn sample_peer() -> Peer { complete_peer() diff --git a/src/core/whitelist/authorization.rs b/src/core/whitelist/authorization.rs index 55410d934..bd85a8d44 100644 --- a/src/core/whitelist/authorization.rs +++ b/src/core/whitelist/authorization.rs @@ -63,7 +63,6 @@ mod tests { use std::sync::Arc; - use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; @@ -105,14 +104,11 @@ mod tests { (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) } - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() - } - mod configured_as_whitelisted { mod handling_authorization { - use crate::core::whitelist::authorization::tests::{sample_info_hash, whitelisted_tracker}; + use crate::core::core_tests::sample_info_hash; + use crate::core::whitelist::authorization::tests::whitelisted_tracker; #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { diff --git a/src/core/whitelist/manager.rs b/src/core/whitelist/manager.rs index 23095cfb7..9a4568f88 100644 --- a/src/core/whitelist/manager.rs +++ b/src/core/whitelist/manager.rs @@ -95,7 +95,6 @@ mod tests { use std::sync::Arc; - use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; @@ -137,14 +136,11 @@ mod tests { (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) } - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() - } - mod configured_as_whitelisted { mod handling_the_torrent_whitelist { - use crate::core::whitelist::manager::tests::{sample_info_hash, whitelisted_tracker}; + use crate::core::core_tests::sample_info_hash; + use crate::core::whitelist::manager::tests::whitelisted_tracker; // todo: after extracting the WhitelistManager from the Tracker, // there is no need to use the tracker to test the whitelist. @@ -176,7 +172,8 @@ mod tests { } mod persistence { - use crate::core::whitelist::manager::tests::{sample_info_hash, whitelisted_tracker}; + use crate::core::core_tests::sample_info_hash; + use crate::core::whitelist::manager::tests::whitelisted_tracker; #[tokio::test] async fn it_should_load_the_whitelist_from_the_database() { diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs index cd4c238f7..aa06e20cc 100644 --- a/src/core/whitelist/mod.rs +++ b/src/core/whitelist/mod.rs @@ -7,7 +7,6 @@ mod tests { use std::sync::Arc; - use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_test_helpers::configuration; use crate::app_test::initialize_tracker_dependencies; @@ -49,14 +48,11 @@ mod tests { (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) } - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() - } - mod configured_as_whitelisted { mod handling_authorization { - use crate::core::whitelist::tests::{sample_info_hash, whitelisted_tracker}; + use crate::core::core_tests::sample_info_hash; + use crate::core::whitelist::tests::whitelisted_tracker; #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { diff --git a/src/core/whitelist/repository/in_memory.rs b/src/core/whitelist/repository/in_memory.rs index 8d919f1e4..f023c1610 100644 --- a/src/core/whitelist/repository/in_memory.rs +++ b/src/core/whitelist/repository/in_memory.rs @@ -32,14 +32,10 @@ impl InMemoryWhitelist { #[cfg(test)] mod tests { - use bittorrent_primitives::info_hash::InfoHash; + use crate::core::core_tests::sample_info_hash; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() // # DevSkim: ignore DS173237 - } - #[tokio::test] async fn should_allow_adding_a_new_torrent_to_the_whitelist() { let info_hash = sample_info_hash(); diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index e70377fd6..c8c2980c3 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -60,7 +60,6 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; - use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; @@ -97,10 +96,6 @@ mod tests { (core_config, announce_handler, stats_event_sender) } - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() - } - fn sample_peer_using_ipv4() -> peer::Peer { sample_peer() } @@ -140,9 +135,10 @@ mod tests { use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; + use crate::core::core_tests::sample_info_hash; use crate::core::statistics; use crate::servers::http::v1::services::announce::invoke; - use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_info_hash, sample_peer}; + use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_peer}; fn initialize_announce_handler() -> Arc { let config = configuration::ephemeral(); diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 06c21d945..6cd7213be 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -82,6 +82,7 @@ mod tests { use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; + use crate::core::core_tests::sample_info_hash; use crate::core::scrape_handler::ScrapeHandler; fn public_tracker_and_announce_and_scrape_handlers() -> (Arc, Arc) { @@ -112,10 +113,6 @@ mod tests { vec![sample_info_hash()] } - fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap() // # DevSkim: ignore DS173237 - } - fn sample_peer() -> peer::Peer { peer::Peer { peer_id: PeerId(*b"-qB00000000000000000"), From b51018fbade39baeab40aabbecc513b95294150f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 10:56:56 +0000 Subject: [PATCH 0667/1297] refactor: [#1211] extract duplicate code --- src/core/announce_handler.rs | 63 +++--------------------- src/core/core_tests.rs | 61 +++++++++++++++++++++++ src/core/mod.rs | 42 ++-------------- src/core/torrent/repository/in_memory.rs | 39 +-------------- 4 files changed, 73 insertions(+), 132 deletions(-) diff --git a/src/core/announce_handler.rs b/src/core/announce_handler.rs index e19a1798b..1a5f84d47 100644 --- a/src/core/announce_handler.rs +++ b/src/core/announce_handler.rs @@ -190,11 +190,6 @@ mod tests { IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) } - /// Sample peer whose state is not relevant for the tests - fn sample_peer() -> Peer { - complete_peer() - } - /// Sample peer when for tests that need more than one peer fn sample_peer_1() -> Peer { Peer { @@ -221,50 +216,6 @@ mod tests { } } - fn seeder() -> Peer { - complete_peer() - } - - fn leecher() -> Peer { - incomplete_peer() - } - - fn started_peer() -> Peer { - incomplete_peer() - } - - fn completed_peer() -> Peer { - complete_peer() - } - - /// A peer that counts as `complete` is swarm metadata - /// IMPORTANT!: it only counts if the it has been announce at least once before - /// announcing the `AnnounceEvent::Completed` event. - fn complete_peer() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - } - } - - /// A peer that counts as `incomplete` is swarm metadata - fn incomplete_peer() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(1000), // Still bytes to download - event: AnnounceEvent::Started, - } - } - mod for_all_tracker_config_modes { mod handling_an_announce_request { @@ -272,10 +223,10 @@ mod tests { use std::sync::Arc; use crate::core::announce_handler::tests::the_announce_handler::{ - peer_ip, public_tracker, sample_peer, sample_peer_1, sample_peer_2, + peer_ip, public_tracker, sample_peer_1, sample_peer_2, }; use crate::core::announce_handler::PeersWanted; - use crate::core::core_tests::sample_info_hash; + use crate::core::core_tests::{sample_info_hash, sample_peer}; mod should_assign_the_ip_to_the_peer { @@ -406,11 +357,9 @@ mod tests { mod it_should_update_the_swarm_stats_for_the_torrent { - use crate::core::announce_handler::tests::the_announce_handler::{ - completed_peer, leecher, peer_ip, public_tracker, seeder, started_peer, - }; + use crate::core::announce_handler::tests::the_announce_handler::{peer_ip, public_tracker}; use crate::core::announce_handler::PeersWanted; - use crate::core::core_tests::sample_info_hash; + use crate::core::core_tests::{completed_peer, leecher, sample_info_hash, seeder, started_peer}; #[tokio::test] async fn when_the_peer_is_a_seeder() { @@ -462,9 +411,9 @@ mod tests { use torrust_tracker_test_helpers::configuration; use torrust_tracker_torrent_repository::entry::EntrySync; - use crate::core::announce_handler::tests::the_announce_handler::{peer_ip, sample_peer}; + use crate::core::announce_handler::tests::the_announce_handler::peer_ip; use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; - use crate::core::core_tests::sample_info_hash; + use crate::core::core_tests::{sample_info_hash, sample_peer}; use crate::core::services::initialize_database; use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; diff --git a/src/core/core_tests.rs b/src/core/core_tests.rs index be93fb1dc..037dab5dd 100644 --- a/src/core/core_tests.rs +++ b/src/core/core_tests.rs @@ -1,7 +1,12 @@ +//! Some generic test helpers functions. +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::Configuration; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::announce_handler::AnnounceHandler; use super::scrape_handler::ScrapeHandler; @@ -21,6 +26,62 @@ pub fn sample_info_hash() -> InfoHash { .expect("String should be a valid info hash") } +/// Sample peer whose state is not relevant for the tests. +#[must_use] +pub fn sample_peer() -> Peer { + complete_peer() +} + +#[must_use] +pub fn seeder() -> Peer { + complete_peer() +} + +#[must_use] +pub fn leecher() -> Peer { + incomplete_peer() +} + +#[must_use] +pub fn started_peer() -> Peer { + incomplete_peer() +} + +#[must_use] +pub fn completed_peer() -> Peer { + complete_peer() +} + +/// A peer that counts as `complete` is swarm metadata +/// IMPORTANT!: it only counts if the it has been announce at least once before +/// announcing the `AnnounceEvent::Completed` event. +#[must_use] +pub fn complete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } +} + +/// A peer that counts as `incomplete` is swarm metadata +#[must_use] +pub fn incomplete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(1000), // Still bytes to download + event: AnnounceEvent::Started, + } +} + #[must_use] pub fn initialize_handlers(config: &Configuration) -> (Arc, Arc) { let database = initialize_database(config); diff --git a/src/core/mod.rs b/src/core/mod.rs index 581dd02f6..77d8e1450 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -455,14 +455,10 @@ pub mod peer_tests; #[cfg(test)] mod tests { mod the_tracker { - - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::net::{IpAddr, Ipv4Addr}; use std::str::FromStr; use std::sync::Arc; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; - use torrust_tracker_primitives::peer::Peer; - use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; use crate::core::announce_handler::AnnounceHandler; @@ -484,34 +480,6 @@ mod tests { IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) } - /// A peer that counts as `complete` is swarm metadata - /// IMPORTANT!: it only counts if the it has been announce at least once before - /// announcing the `AnnounceEvent::Completed` event. - fn complete_peer() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - } - } - - /// A peer that counts as `incomplete` is swarm metadata - fn incomplete_peer() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(1000), // Still bytes to download - event: AnnounceEvent::Started, - } - } - mod for_all_config_modes { mod handling_a_scrape_request { @@ -523,7 +491,8 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::core::announce_handler::PeersWanted; - use crate::core::tests::the_tracker::{complete_peer, incomplete_peer, initialize_handlers_for_public_tracker}; + use crate::core::core_tests::{complete_peer, incomplete_peer}; + use crate::core::tests::the_tracker::initialize_handlers_for_public_tracker; #[tokio::test] async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() { @@ -577,9 +546,8 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::core::announce_handler::PeersWanted; - use crate::core::tests::the_tracker::{ - complete_peer, incomplete_peer, initialize_handlers_for_listed_tracker, peer_ip, - }; + use crate::core::core_tests::{complete_peer, incomplete_peer}; + use crate::core::tests::the_tracker::{initialize_handlers_for_listed_tracker, peer_ip}; #[tokio::test] async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { diff --git a/src/core/torrent/repository/in_memory.rs b/src/core/torrent/repository/in_memory.rs index 908abd143..2e80a2e9b 100644 --- a/src/core/torrent/repository/in_memory.rs +++ b/src/core/torrent/repository/in_memory.rs @@ -114,46 +114,9 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::core::core_tests::sample_info_hash; + use crate::core::core_tests::{leecher, sample_info_hash, sample_peer}; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - /// Sample peer whose state is not relevant for the tests - fn sample_peer() -> Peer { - complete_peer() - } - - fn leecher() -> Peer { - incomplete_peer() - } - - /// A peer that counts as `complete` is swarm metadata - /// IMPORTANT!: it only counts if the it has been announce at least once before - /// announcing the `AnnounceEvent::Completed` event. - fn complete_peer() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - } - } - - /// A peer that counts as `incomplete` is swarm metadata - fn incomplete_peer() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(1000), // Still bytes to download - event: AnnounceEvent::Started, - } - } - /// It generates a peer id from a number where the number is the last /// part of the peer ID. For example, for `12` it returns /// `-qB00000000000000012`. From 7fa2b15840875c4e30cebed7cae6ba370c5ad8c7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 11:06:41 +0000 Subject: [PATCH 0668/1297] refactor: [#1211] clean tests in core::whitelist::authorization --- src/core/whitelist/authorization.rs | 45 +++++++---------------------- 1 file changed, 11 insertions(+), 34 deletions(-) diff --git a/src/core/whitelist/authorization.rs b/src/core/whitelist/authorization.rs index bd85a8d44..9d51601fd 100644 --- a/src/core/whitelist/authorization.rs +++ b/src/core/whitelist/authorization.rs @@ -65,54 +65,31 @@ mod tests { use torrust_tracker_test_helpers::configuration; - use crate::app_test::initialize_tracker_dependencies; - use crate::core::announce_handler::AnnounceHandler; - use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::initialize_whitelist_manager; - use crate::core::whitelist; + use super::Authorization; + use crate::core::services::{initialize_database, initialize_whitelist_manager}; use crate::core::whitelist::manager::WhiteListManager; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - #[allow(clippy::type_complexity)] - fn whitelisted_tracker() -> ( - Arc, - Arc, - Arc, - Arc, - ) { + fn initialize_whitelist_services() -> (Arc, Arc) { let config = configuration::ephemeral_listed(); - let ( - database, - in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - + let database = initialize_database(&config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(Authorization::new(&config.core, &in_memory_whitelist.clone())); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) + (whitelist_authorization, whitelist_manager) } mod configured_as_whitelisted { mod handling_authorization { use crate::core::core_tests::sample_info_hash; - use crate::core::whitelist::authorization::tests::whitelisted_tracker; + use crate::core::whitelist::authorization::tests::initialize_whitelist_services; #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { - let (_announce_handler, whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + let (whitelist_authorization, whitelist_manager) = initialize_whitelist_services(); let info_hash = sample_info_hash(); @@ -125,7 +102,7 @@ mod tests { #[tokio::test] async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { - let (_announce_handler, whitelist_authorization, _whitelist_manager, _scrape_handler) = whitelisted_tracker(); + let (whitelist_authorization, _whitelist_manager) = initialize_whitelist_services(); let info_hash = sample_info_hash(); From 69d4505057affbb0995db9d08e168a92980bafd7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 11:08:15 +0000 Subject: [PATCH 0669/1297] refactor: [#1211] rename type to WhitelistAuthorization --- src/app_test.rs | 4 ++-- src/bootstrap/app.rs | 2 +- src/bootstrap/jobs/http_tracker.rs | 4 ++-- src/bootstrap/jobs/udp_tracker.rs | 2 +- src/container.rs | 2 +- src/core/core_tests.rs | 2 +- src/core/scrape_handler.rs | 6 +++--- src/core/whitelist/authorization.rs | 10 +++++----- src/core/whitelist/manager.rs | 2 +- src/core/whitelist/mod.rs | 2 +- src/servers/http/server.rs | 4 ++-- src/servers/http/v1/handlers/announce.rs | 10 +++++----- src/servers/http/v1/routes.rs | 2 +- src/servers/udp/handlers.rs | 14 +++++++------- src/servers/udp/server/launcher.rs | 4 ++-- src/servers/udp/server/processor.rs | 4 ++-- src/servers/udp/server/spawner.rs | 2 +- src/servers/udp/server/states.rs | 2 +- tests/servers/http/environment.rs | 2 +- tests/servers/udp/environment.rs | 2 +- 20 files changed, 41 insertions(+), 41 deletions(-) diff --git a/src/app_test.rs b/src/app_test.rs index 5f189f391..fb1dd01c8 100644 --- a/src/app_test.rs +++ b/src/app_test.rs @@ -23,7 +23,7 @@ pub fn initialize_tracker_dependencies( ) -> ( Arc>, Arc, - Arc, + Arc, Arc, Arc, Arc, @@ -31,7 +31,7 @@ pub fn initialize_tracker_dependencies( ) { let database = initialize_database(config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( &config.core, &in_memory_whitelist.clone(), )); diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index da63048e0..c69162322 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -93,7 +93,7 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let database = initialize_database(configuration); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( &configuration.core, &in_memory_whitelist.clone(), )); diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 4a3aa7a9f..dc6ed6b60 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -52,7 +52,7 @@ pub async fn start_job( announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, stats_event_sender: Arc>>, form: ServiceRegistrationForm, version: Version, @@ -99,7 +99,7 @@ async fn start_v1( announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, stats_event_sender: Arc>>, form: ServiceRegistrationForm, ) -> JoinHandle<()> { diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 3679c3195..4f54ecb59 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -49,7 +49,7 @@ pub async fn start_job( config: &UdpTracker, announce_handler: Arc, scrape_handler: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, stats_event_sender: Arc>>, ban_service: Arc>, form: ServiceRegistrationForm, diff --git a/src/container.rs b/src/container.rs index 544abd02e..d8fae07e5 100644 --- a/src/container.rs +++ b/src/container.rs @@ -22,7 +22,7 @@ pub struct AppContainer { pub scrape_handler: Arc, pub keys_handler: Arc, pub authentication_service: Arc, - pub whitelist_authorization: Arc, + pub whitelist_authorization: Arc, pub ban_service: Arc>, pub stats_event_sender: Arc>>, pub stats_repository: Arc, diff --git a/src/core/core_tests.rs b/src/core/core_tests.rs index 037dab5dd..45949bae2 100644 --- a/src/core/core_tests.rs +++ b/src/core/core_tests.rs @@ -86,7 +86,7 @@ pub fn incomplete_peer() -> Peer { pub fn initialize_handlers(config: &Configuration) -> (Arc, Arc) { let database = initialize_database(config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( &config.core, &in_memory_whitelist.clone(), )); diff --git a/src/core/scrape_handler.rs b/src/core/scrape_handler.rs index 1d513a5a9..7de82aa06 100644 --- a/src/core/scrape_handler.rs +++ b/src/core/scrape_handler.rs @@ -9,7 +9,7 @@ use super::whitelist; pub struct ScrapeHandler { /// The service to check is a torrent is whitelisted. - whitelist_authorization: Arc, + whitelist_authorization: Arc, /// The in-memory torrents repository. in_memory_torrent_repository: Arc, @@ -18,7 +18,7 @@ pub struct ScrapeHandler { impl ScrapeHandler { #[must_use] pub fn new( - whitelist_authorization: &Arc, + whitelist_authorization: &Arc, in_memory_torrent_repository: &Arc, ) -> Self { Self { @@ -62,7 +62,7 @@ mod tests { let config = configuration::ephemeral_public(); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::Authorization::new( + let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( &config.core, &in_memory_whitelist.clone(), )); diff --git a/src/core/whitelist/authorization.rs b/src/core/whitelist/authorization.rs index 9d51601fd..e9450270f 100644 --- a/src/core/whitelist/authorization.rs +++ b/src/core/whitelist/authorization.rs @@ -8,7 +8,7 @@ use tracing::instrument; use super::repository::in_memory::InMemoryWhitelist; use crate::core::error::Error; -pub struct Authorization { +pub struct WhitelistAuthorization { /// Core tracker configuration. config: Core, @@ -16,7 +16,7 @@ pub struct Authorization { in_memory_whitelist: Arc, } -impl Authorization { +impl WhitelistAuthorization { /// Creates a new authorization instance. pub fn new(config: &Core, in_memory_whitelist: &Arc) -> Self { Self { @@ -65,17 +65,17 @@ mod tests { use torrust_tracker_test_helpers::configuration; - use super::Authorization; + use super::WhitelistAuthorization; use crate::core::services::{initialize_database, initialize_whitelist_manager}; use crate::core::whitelist::manager::WhiteListManager; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - fn initialize_whitelist_services() -> (Arc, Arc) { + fn initialize_whitelist_services() -> (Arc, Arc) { let config = configuration::ephemeral_listed(); let database = initialize_database(&config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(Authorization::new(&config.core, &in_memory_whitelist.clone())); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); (whitelist_authorization, whitelist_manager) diff --git a/src/core/whitelist/manager.rs b/src/core/whitelist/manager.rs index 9a4568f88..289dd6d5b 100644 --- a/src/core/whitelist/manager.rs +++ b/src/core/whitelist/manager.rs @@ -107,7 +107,7 @@ mod tests { #[allow(clippy::type_complexity)] fn whitelisted_tracker() -> ( Arc, - Arc, + Arc, Arc, Arc, ) { diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs index aa06e20cc..bdc09d2b1 100644 --- a/src/core/whitelist/mod.rs +++ b/src/core/whitelist/mod.rs @@ -19,7 +19,7 @@ mod tests { #[allow(clippy::type_complexity)] fn whitelisted_tracker() -> ( Arc, - Arc, + Arc, Arc, Arc, ) { diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 28f407ad3..2792697b3 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -63,7 +63,7 @@ impl Launcher { announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, stats_event_sender: Arc>>, tx_start: Sender, rx_halt: Receiver, @@ -192,7 +192,7 @@ impl HttpServer { announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, stats_event_sender: Arc>>, form: ServiceRegistrationForm, ) -> Result, Error> { diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 632688763..247c6b8c6 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -43,7 +43,7 @@ pub async fn handle_without_key( Arc, Arc, Arc, - Arc, + Arc, Arc>>, )>, ExtractRequest(announce_request): ExtractRequest, @@ -73,7 +73,7 @@ pub async fn handle_with_key( Arc, Arc, Arc, - Arc, + Arc, Arc>>, )>, ExtractRequest(announce_request): ExtractRequest, @@ -104,7 +104,7 @@ async fn handle( config: &Arc, announce_handler: &Arc, authentication_service: &Arc, - whitelist_authorization: &Arc, + whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, @@ -139,7 +139,7 @@ async fn handle_announce( core_config: &Arc, announce_handler: &Arc, authentication_service: &Arc, - whitelist_authorization: &Arc, + whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, @@ -265,7 +265,7 @@ mod tests { Arc, Arc, Arc>>, - Arc, + Arc, Arc, ); diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 757a7d1bd..f80760955 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -49,7 +49,7 @@ pub fn router( announce_handler: Arc, scrape_handler: Arc, authentication_service: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, stats_event_sender: Arc>>, server_socket_addr: SocketAddr, ) -> Router { diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 5589331a7..b96ecc154 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -64,7 +64,7 @@ pub(crate) async fn handle_packet( core_config: &Arc, announce_handler: &Arc, scrape_handler: &Arc, - whitelist_authorization: &Arc, + whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, local_addr: SocketAddr, cookie_time_values: CookieTimeValues, @@ -157,7 +157,7 @@ pub async fn handle_request( core_config: &Arc, announce_handler: &Arc, scrape_handler: &Arc, - whitelist_authorization: &Arc, + whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, cookie_time_values: CookieTimeValues, ) -> Result { @@ -247,7 +247,7 @@ pub async fn handle_announce( request: &AnnounceRequest, core_config: &Arc, announce_handler: &Arc, - whitelist_authorization: &Arc, + whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { @@ -517,7 +517,7 @@ mod tests { Arc>>, Arc, Arc, - Arc, + Arc, ); fn tracker_configuration() -> Configuration { @@ -672,7 +672,7 @@ mod tests { Arc, Arc, Arc, - Arc, + Arc, ) { let config = tracker_configuration(); @@ -1088,7 +1088,7 @@ mod tests { async fn announce_a_new_peer_using_ipv4( core_config: Arc, announce_handler: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, ) -> Response { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); @@ -1426,7 +1426,7 @@ mod tests { async fn announce_a_new_peer_using_ipv6( core_config: Arc, announce_handler: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, ) -> Response { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index f1b14860d..4aaf87ae2 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -58,7 +58,7 @@ impl Launcher { core_config: Arc, announce_handler: Arc, scrape_handler: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, ban_service: Arc>, bind_to: SocketAddr, @@ -159,7 +159,7 @@ impl Launcher { core_config: Arc, announce_handler: Arc, scrape_handler: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, ban_service: Arc>, cookie_lifetime: Duration, diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 475a36b74..24a34f98d 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -24,7 +24,7 @@ pub struct Processor { core_config: Arc, announce_handler: Arc, scrape_handler: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, cookie_lifetime: f64, } @@ -36,7 +36,7 @@ impl Processor { core_config: Arc, announce_handler: Arc, scrape_handler: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, cookie_lifetime: f64, ) -> Self { diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index 2415b2631..d5fd5d58e 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -36,7 +36,7 @@ impl Spawner { core_config: Arc, announce_handler: Arc, scrape_handler: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, ban_service: Arc>, cookie_lifetime: Duration, diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index 4d18593fe..9bcde9003 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -74,7 +74,7 @@ impl Server { core_config: Arc, announce_handler: Arc, scrape_handler: Arc, - whitelist_authorization: Arc, + whitelist_authorization: Arc, opt_stats_event_sender: Arc>>, ban_service: Arc>, form: ServiceRegistrationForm, diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 589430848..6c9f8e4b8 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -30,7 +30,7 @@ pub struct Environment { pub authentication_service: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, - pub whitelist_authorization: Arc, + pub whitelist_authorization: Arc, pub whitelist_manager: Arc, pub registar: Registar, pub server: HttpServer, diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index a6ddd7a83..b3a2670e8 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -29,7 +29,7 @@ where pub in_memory_torrent_repository: Arc, pub announce_handler: Arc, pub scrape_handler: Arc, - pub whitelist_authorization: Arc, + pub whitelist_authorization: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub ban_service: Arc>, From 115159d1c011d12aebebfba8cdbc9346ecc34c98 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 11:24:17 +0000 Subject: [PATCH 0670/1297] refactor: [#1211] clean core::whitelist module tests --- src/core/whitelist/authorization.rs | 26 ++------------ src/core/whitelist/manager.rs | 51 +++++---------------------- src/core/whitelist/mod.rs | 50 +++----------------------- src/core/whitelist/whitelist_tests.rs | 26 ++++++++++++++ 4 files changed, 42 insertions(+), 111 deletions(-) create mode 100644 src/core/whitelist/whitelist_tests.rs diff --git a/src/core/whitelist/authorization.rs b/src/core/whitelist/authorization.rs index e9450270f..1a6d8b758 100644 --- a/src/core/whitelist/authorization.rs +++ b/src/core/whitelist/authorization.rs @@ -61,35 +61,15 @@ impl WhitelistAuthorization { #[cfg(test)] mod tests { - use std::sync::Arc; - - use torrust_tracker_test_helpers::configuration; - - use super::WhitelistAuthorization; - use crate::core::services::{initialize_database, initialize_whitelist_manager}; - use crate::core::whitelist::manager::WhiteListManager; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - - fn initialize_whitelist_services() -> (Arc, Arc) { - let config = configuration::ephemeral_listed(); - - let database = initialize_database(&config); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - - (whitelist_authorization, whitelist_manager) - } - mod configured_as_whitelisted { mod handling_authorization { use crate::core::core_tests::sample_info_hash; - use crate::core::whitelist::authorization::tests::initialize_whitelist_services; + use crate::core::whitelist::whitelist_tests::initialize_whitelist_services_for_listed_tracker; #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { - let (whitelist_authorization, whitelist_manager) = initialize_whitelist_services(); + let (whitelist_authorization, whitelist_manager) = initialize_whitelist_services_for_listed_tracker(); let info_hash = sample_info_hash(); @@ -102,7 +82,7 @@ mod tests { #[tokio::test] async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { - let (whitelist_authorization, _whitelist_manager) = initialize_whitelist_services(); + let (whitelist_authorization, _whitelist_manager) = initialize_whitelist_services_for_listed_tracker(); let info_hash = sample_info_hash(); diff --git a/src/core/whitelist/manager.rs b/src/core/whitelist/manager.rs index 289dd6d5b..4f4792443 100644 --- a/src/core/whitelist/manager.rs +++ b/src/core/whitelist/manager.rs @@ -97,59 +97,26 @@ mod tests { use torrust_tracker_test_helpers::configuration; - use crate::app_test::initialize_tracker_dependencies; - use crate::core::announce_handler::AnnounceHandler; - use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::initialize_whitelist_manager; - use crate::core::whitelist; use crate::core::whitelist::manager::WhiteListManager; + use crate::core::whitelist::whitelist_tests::initialize_whitelist_services; - #[allow(clippy::type_complexity)] - fn whitelisted_tracker() -> ( - Arc, - Arc, - Arc, - Arc, - ) { + fn initialize_whitelist_manager_for_whitelisted_tracker() -> Arc { let config = configuration::ephemeral_listed(); - let ( - database, - in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); + let (_whitelist_authorization, whitelist_manager) = initialize_whitelist_services(&config); - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) + whitelist_manager } mod configured_as_whitelisted { mod handling_the_torrent_whitelist { use crate::core::core_tests::sample_info_hash; - use crate::core::whitelist::manager::tests::whitelisted_tracker; - - // todo: after extracting the WhitelistManager from the Tracker, - // there is no need to use the tracker to test the whitelist. - // Test not using the `tracker` (`_tracker` variable) should be - // moved to the whitelist module. + use crate::core::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker; #[tokio::test] async fn it_should_add_a_torrent_to_the_whitelist() { - let (_announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + let whitelist_manager = initialize_whitelist_manager_for_whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -160,7 +127,7 @@ mod tests { #[tokio::test] async fn it_should_remove_a_torrent_from_the_whitelist() { - let (_announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + let whitelist_manager = initialize_whitelist_manager_for_whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -173,11 +140,11 @@ mod tests { mod persistence { use crate::core::core_tests::sample_info_hash; - use crate::core::whitelist::manager::tests::whitelisted_tracker; + use crate::core::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker; #[tokio::test] async fn it_should_load_the_whitelist_from_the_database() { - let (_announce_handler, _whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + let whitelist_manager = initialize_whitelist_manager_for_whitelisted_tracker(); let info_hash = sample_info_hash(); diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs index bdc09d2b1..c23740111 100644 --- a/src/core/whitelist/mod.rs +++ b/src/core/whitelist/mod.rs @@ -1,62 +1,20 @@ pub mod authorization; pub mod manager; pub mod repository; +pub mod whitelist_tests; #[cfg(test)] mod tests { - use std::sync::Arc; - - use torrust_tracker_test_helpers::configuration; - - use crate::app_test::initialize_tracker_dependencies; - use crate::core::announce_handler::AnnounceHandler; - use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::initialize_whitelist_manager; - use crate::core::whitelist; - use crate::core::whitelist::manager::WhiteListManager; - - #[allow(clippy::type_complexity)] - fn whitelisted_tracker() -> ( - Arc, - Arc, - Arc, - Arc, - ) { - let config = configuration::ephemeral_listed(); - - let ( - database, - in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - (announce_handler, whitelist_authorization, whitelist_manager, scrape_handler) - } - mod configured_as_whitelisted { mod handling_authorization { use crate::core::core_tests::sample_info_hash; - use crate::core::whitelist::tests::whitelisted_tracker; + use crate::core::whitelist::whitelist_tests::initialize_whitelist_services_for_listed_tracker; #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { - let (_announce_handler, whitelist_authorization, whitelist_manager, _scrape_handler) = whitelisted_tracker(); + let (whitelist_authorization, whitelist_manager) = initialize_whitelist_services_for_listed_tracker(); let info_hash = sample_info_hash(); @@ -69,7 +27,7 @@ mod tests { #[tokio::test] async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { - let (_announce_handler, whitelist_authorization, _whitelist_manager, _scrape_handler) = whitelisted_tracker(); + let (whitelist_authorization, _whitelist_manager) = initialize_whitelist_services_for_listed_tracker(); let info_hash = sample_info_hash(); diff --git a/src/core/whitelist/whitelist_tests.rs b/src/core/whitelist/whitelist_tests.rs new file mode 100644 index 000000000..ceb2ab8a0 --- /dev/null +++ b/src/core/whitelist/whitelist_tests.rs @@ -0,0 +1,26 @@ +use std::sync::Arc; + +use torrust_tracker_configuration::Configuration; + +use super::authorization::WhitelistAuthorization; +use super::manager::WhiteListManager; +use super::repository::in_memory::InMemoryWhitelist; +use crate::core::services::{initialize_database, initialize_whitelist_manager}; + +#[must_use] +pub fn initialize_whitelist_services(config: &Configuration) -> (Arc, Arc) { + let database = initialize_database(config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + + (whitelist_authorization, whitelist_manager) +} + +#[cfg(test)] +#[must_use] +pub fn initialize_whitelist_services_for_listed_tracker() -> (Arc, Arc) { + use torrust_tracker_test_helpers::configuration; + + initialize_whitelist_services(&configuration::ephemeral_listed()) +} From 7ce52f95dc2af02f36603f31c201905dfa923e9d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 11:36:47 +0000 Subject: [PATCH 0671/1297] refactor: [#1211] rename type to WhitelistManager --- src/bootstrap/jobs/tracker_apis.rs | 6 +++--- src/container.rs | 4 ++-- src/core/services/mod.rs | 6 +++--- src/core/whitelist/manager.rs | 8 ++++---- src/core/whitelist/whitelist_tests.rs | 6 +++--- src/servers/apis/routes.rs | 4 ++-- src/servers/apis/server.rs | 6 +++--- src/servers/apis/v1/context/whitelist/handlers.rs | 8 ++++---- src/servers/apis/v1/context/whitelist/routes.rs | 4 ++-- src/servers/apis/v1/routes.rs | 4 ++-- src/servers/udp/handlers.rs | 4 ++-- tests/servers/api/environment.rs | 4 ++-- tests/servers/http/environment.rs | 4 ++-- 13 files changed, 34 insertions(+), 34 deletions(-) diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index f735bc4d7..ce6f3912c 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -34,7 +34,7 @@ use crate::core::authentication::handler::KeysHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::core::whitelist::manager::WhiteListManager; +use crate::core::whitelist::manager::WhitelistManager; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::apis::Version; use crate::servers::registar::ServiceRegistrationForm; @@ -74,7 +74,7 @@ pub async fn start_job( config: &HttpApi, in_memory_torrent_repository: Arc, keys_handler: Arc, - whitelist_manager: Arc, + whitelist_manager: Arc, ban_service: Arc>, stats_event_sender: Arc>>, stats_repository: Arc, @@ -126,7 +126,7 @@ async fn start_v1( tls: Option, in_memory_torrent_repository: Arc, keys_handler: Arc, - whitelist_manager: Arc, + whitelist_manager: Arc, ban_service: Arc>, stats_event_sender: Arc>>, stats_repository: Arc, diff --git a/src/container.rs b/src/container.rs index d8fae07e5..192fa62f1 100644 --- a/src/container.rs +++ b/src/container.rs @@ -13,7 +13,7 @@ use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use crate::core::whitelist; -use crate::core::whitelist::manager::WhiteListManager; +use crate::core::whitelist::manager::WhitelistManager; use crate::servers::udp::server::banning::BanService; pub struct AppContainer { @@ -26,7 +26,7 @@ pub struct AppContainer { pub ban_service: Arc>, pub stats_event_sender: Arc>>, pub stats_repository: Arc, - pub whitelist_manager: Arc, + pub whitelist_manager: Arc, pub in_memory_torrent_repository: Arc, pub db_torrent_repository: Arc, pub torrents_manager: Arc, diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index 73328aaeb..f2ee79993 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -14,7 +14,7 @@ use torrust_tracker_configuration::v2_0_0::database; use torrust_tracker_configuration::Configuration; use super::databases::{self, Database}; -use super::whitelist::manager::WhiteListManager; +use super::whitelist::manager::WhitelistManager; use super::whitelist::repository::in_memory::InMemoryWhitelist; use super::whitelist::repository::persisted::DatabaseWhitelist; @@ -35,7 +35,7 @@ pub fn initialize_database(config: &Configuration) -> Arc> { pub fn initialize_whitelist_manager( database: Arc>, in_memory_whitelist: Arc, -) -> Arc { +) -> Arc { let database_whitelist = Arc::new(DatabaseWhitelist::new(database)); - Arc::new(WhiteListManager::new(database_whitelist, in_memory_whitelist)) + Arc::new(WhitelistManager::new(database_whitelist, in_memory_whitelist)) } diff --git a/src/core/whitelist/manager.rs b/src/core/whitelist/manager.rs index 4f4792443..0d9751994 100644 --- a/src/core/whitelist/manager.rs +++ b/src/core/whitelist/manager.rs @@ -7,7 +7,7 @@ use super::repository::persisted::DatabaseWhitelist; use crate::core::databases; /// It handles the list of allowed torrents. Only for listed trackers. -pub struct WhiteListManager { +pub struct WhitelistManager { /// The in-memory list of allowed torrents. in_memory_whitelist: Arc, @@ -15,7 +15,7 @@ pub struct WhiteListManager { database_whitelist: Arc, } -impl WhiteListManager { +impl WhitelistManager { #[must_use] pub fn new(database_whitelist: Arc, in_memory_whitelist: Arc) -> Self { Self { @@ -97,10 +97,10 @@ mod tests { use torrust_tracker_test_helpers::configuration; - use crate::core::whitelist::manager::WhiteListManager; + use crate::core::whitelist::manager::WhitelistManager; use crate::core::whitelist::whitelist_tests::initialize_whitelist_services; - fn initialize_whitelist_manager_for_whitelisted_tracker() -> Arc { + fn initialize_whitelist_manager_for_whitelisted_tracker() -> Arc { let config = configuration::ephemeral_listed(); let (_whitelist_authorization, whitelist_manager) = initialize_whitelist_services(&config); diff --git a/src/core/whitelist/whitelist_tests.rs b/src/core/whitelist/whitelist_tests.rs index ceb2ab8a0..aa9c5ca14 100644 --- a/src/core/whitelist/whitelist_tests.rs +++ b/src/core/whitelist/whitelist_tests.rs @@ -3,12 +3,12 @@ use std::sync::Arc; use torrust_tracker_configuration::Configuration; use super::authorization::WhitelistAuthorization; -use super::manager::WhiteListManager; +use super::manager::WhitelistManager; use super::repository::in_memory::InMemoryWhitelist; use crate::core::services::{initialize_database, initialize_whitelist_manager}; #[must_use] -pub fn initialize_whitelist_services(config: &Configuration) -> (Arc, Arc) { +pub fn initialize_whitelist_services(config: &Configuration) -> (Arc, Arc) { let database = initialize_database(config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); @@ -19,7 +19,7 @@ pub fn initialize_whitelist_services(config: &Configuration) -> (Arc (Arc, Arc) { +pub fn initialize_whitelist_services_for_listed_tracker() -> (Arc, Arc) { use torrust_tracker_test_helpers::configuration; initialize_whitelist_services(&configuration::ephemeral_listed()) diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index c27b5f906..92ecb067d 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -34,7 +34,7 @@ use crate::core::authentication::handler::KeysHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::core::whitelist::manager::WhiteListManager; +use crate::core::whitelist::manager::WhitelistManager; use crate::servers::apis::API_LOG_TARGET; use crate::servers::logging::Latency; use crate::servers::udp::server::banning::BanService; @@ -53,7 +53,7 @@ use crate::servers::udp::server::banning::BanService; pub fn router( in_memory_torrent_repository: Arc, keys_handler: Arc, - whitelist_manager: Arc, + whitelist_manager: Arc, ban_service: Arc>, stats_event_sender: Arc>>, stats_repository: Arc, diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index b37f71d5b..b3621de0e 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -43,7 +43,7 @@ use crate::core::authentication::handler::KeysHandler; use crate::core::statistics; use crate::core::statistics::repository::Repository; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::core::whitelist::manager::WhiteListManager; +use crate::core::whitelist::manager::WhitelistManager; use crate::servers::apis::API_LOG_TARGET; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::logging::STARTED_ON; @@ -134,7 +134,7 @@ impl ApiServer { self, in_memory_torrent_repository: Arc, keys_handler: Arc, - whitelist_manager: Arc, + whitelist_manager: Arc, stats_event_sender: Arc>>, stats_repository: Arc, ban_service: Arc>, @@ -275,7 +275,7 @@ impl Launcher { &self, in_memory_torrent_repository: Arc, keys_handler: Arc, - whitelist_manager: Arc, + whitelist_manager: Arc, ban_service: Arc>, stats_event_sender: Arc>>, stats_repository: Arc, diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/src/servers/apis/v1/context/whitelist/handlers.rs index 473ed56c5..ebe0bb15c 100644 --- a/src/servers/apis/v1/context/whitelist/handlers.rs +++ b/src/servers/apis/v1/context/whitelist/handlers.rs @@ -10,7 +10,7 @@ use bittorrent_primitives::info_hash::InfoHash; use super::responses::{ failed_to_reload_whitelist_response, failed_to_remove_torrent_from_whitelist_response, failed_to_whitelist_torrent_response, }; -use crate::core::whitelist::manager::WhiteListManager; +use crate::core::whitelist::manager::WhitelistManager; use crate::servers::apis::v1::responses::{invalid_info_hash_param_response, ok_response}; use crate::servers::apis::InfoHashParam; @@ -24,7 +24,7 @@ use crate::servers::apis::InfoHashParam; /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#add-a-torrent-to-the-whitelist) /// for more information about this endpoint. pub async fn add_torrent_to_whitelist_handler( - State(whitelist_manager): State>, + State(whitelist_manager): State>, Path(info_hash): Path, ) -> Response { match InfoHash::from_str(&info_hash.0) { @@ -47,7 +47,7 @@ pub async fn add_torrent_to_whitelist_handler( /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#remove-a-torrent-from-the-whitelist) /// for more information about this endpoint. pub async fn remove_torrent_from_whitelist_handler( - State(whitelist_manager): State>, + State(whitelist_manager): State>, Path(info_hash): Path, ) -> Response { match InfoHash::from_str(&info_hash.0) { @@ -69,7 +69,7 @@ pub async fn remove_torrent_from_whitelist_handler( /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#reload-the-whitelist) /// for more information about this endpoint. -pub async fn reload_whitelist_handler(State(whitelist_manager): State>) -> Response { +pub async fn reload_whitelist_handler(State(whitelist_manager): State>) -> Response { match whitelist_manager.load_whitelist_from_database().await { Ok(()) => ok_response(), Err(e) => failed_to_reload_whitelist_response(e), diff --git a/src/servers/apis/v1/context/whitelist/routes.rs b/src/servers/apis/v1/context/whitelist/routes.rs index 34f1393b8..5069332af 100644 --- a/src/servers/apis/v1/context/whitelist/routes.rs +++ b/src/servers/apis/v1/context/whitelist/routes.rs @@ -11,10 +11,10 @@ use axum::routing::{delete, get, post}; use axum::Router; use super::handlers::{add_torrent_to_whitelist_handler, reload_whitelist_handler, remove_torrent_from_whitelist_handler}; -use crate::core::whitelist::manager::WhiteListManager; +use crate::core::whitelist::manager::WhitelistManager; /// It adds the routes to the router for the [`whitelist`](crate::servers::apis::v1::context::whitelist) API context. -pub fn add(prefix: &str, router: Router, whitelist_manager: &Arc) -> Router { +pub fn add(prefix: &str, router: Router, whitelist_manager: &Arc) -> Router { let prefix = format!("{prefix}/whitelist"); router diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs index 8fac453b8..87c28de08 100644 --- a/src/servers/apis/v1/routes.rs +++ b/src/servers/apis/v1/routes.rs @@ -9,7 +9,7 @@ use crate::core::authentication::handler::KeysHandler; use crate::core::statistics::event::sender::Sender; use crate::core::statistics::repository::Repository; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::core::whitelist::manager::WhiteListManager; +use crate::core::whitelist::manager::WhitelistManager; use crate::servers::udp::server::banning::BanService; /// Add the routes for the v1 API. @@ -19,7 +19,7 @@ pub fn add( router: Router, in_memory_torrent_repository: &Arc, keys_handler: &Arc, - whitelist_manager: &Arc, + whitelist_manager: &Arc, ban_service: Arc>, stats_event_sender: Arc>>, stats_repository: Arc, diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index b96ecc154..2e753404d 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -505,7 +505,7 @@ mod tests { use crate::core::statistics::event::sender::Sender; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::whitelist; - use crate::core::whitelist::manager::WhiteListManager; + use crate::core::whitelist::manager::WhitelistManager; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::CurrentClock; @@ -516,7 +516,7 @@ mod tests { Arc, Arc>>, Arc, - Arc, + Arc, Arc, ); diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 3488456e7..66018032e 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -14,7 +14,7 @@ use torrust_tracker_lib::core::databases::Database; use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; +use torrust_tracker_lib::core::whitelist::manager::WhitelistManager; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::banning::BanService; @@ -31,7 +31,7 @@ where pub authentication_service: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, - pub whitelist_manager: Arc, + pub whitelist_manager: Arc, pub ban_service: Arc>, pub registar: Registar, pub server: ApiServer, diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 6c9f8e4b8..5bf1d1c65 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -14,7 +14,7 @@ use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; use torrust_tracker_lib::core::whitelist; -use torrust_tracker_lib::core::whitelist::manager::WhiteListManager; +use torrust_tracker_lib::core::whitelist::manager::WhitelistManager; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; @@ -31,7 +31,7 @@ pub struct Environment { pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub whitelist_authorization: Arc, - pub whitelist_manager: Arc, + pub whitelist_manager: Arc, pub registar: Registar, pub server: HttpServer, } From 8f02fb936b108e1e9389f8a2e0f845e1b348102a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 16:08:50 +0000 Subject: [PATCH 0672/1297] refactor: [#1215] instantiate only needed services --- src/app_test.rs | 62 ---- src/core/services/statistics/mod.rs | 14 +- src/core/services/torrent.rs | 55 +-- src/lib.rs | 1 - src/servers/http/v1/handlers/announce.rs | 165 ++++----- src/servers/http/v1/handlers/scrape.rs | 203 ++++------ src/servers/http/v1/services/announce.rs | 62 ++-- src/servers/http/v1/services/scrape.rs | 46 +-- src/servers/udp/handlers.rs | 453 +++++++++-------------- 9 files changed, 359 insertions(+), 702 deletions(-) delete mode 100644 src/app_test.rs diff --git a/src/app_test.rs b/src/app_test.rs deleted file mode 100644 index fb1dd01c8..000000000 --- a/src/app_test.rs +++ /dev/null @@ -1,62 +0,0 @@ -//! This file contains only functions used for testing. -use std::sync::Arc; - -use torrust_tracker_configuration::Configuration; - -use crate::core::authentication::handler::KeysHandler; -use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; -use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; -use crate::core::authentication::service::{self, AuthenticationService}; -use crate::core::databases::Database; -use crate::core::services::initialize_database; -use crate::core::torrent::manager::TorrentsManager; -use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; -use crate::core::whitelist; -use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - -/// Initialize the tracker dependencies. -#[allow(clippy::type_complexity)] -#[must_use] -pub fn initialize_tracker_dependencies( - config: &Configuration, -) -> ( - Arc>, - Arc, - Arc, - Arc, - Arc, - Arc, - Arc, -) { - let database = initialize_database(config); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( - &config.core, - &in_memory_whitelist.clone(), - )); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::AuthenticationService::new(&config.core, &in_memory_key_repository)); - let _keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - let torrents_manager = Arc::new(TorrentsManager::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - ( - database, - in_memory_whitelist, - whitelist_authorization, - authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - torrents_manager, - ) -} diff --git a/src/core/services/statistics/mod.rs b/src/core/services/statistics/mod.rs index 18d96605e..79bc5f268 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/services/statistics/mod.rs @@ -117,8 +117,8 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; - use crate::app_test::initialize_tracker_dependencies; use crate::core::services::statistics::{self, get_metrics, TrackerMetrics}; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::{self}; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -131,19 +131,9 @@ mod tests { async fn the_statistics_service_should_return_the_tracker_metrics() { let config = tracker_configuration(); - let ( - _database, - _in_memory_whitelist, - _whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - _db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_repository = Arc::new(stats_repository); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let tracker_metrics = get_metrics( diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index 6ae2c26a4..d809fc266 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -112,29 +112,10 @@ pub async fn get_torrents( #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; - use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; - use crate::app_test::initialize_tracker_dependencies; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - - fn initialize_in_memory_torrent_repository(config: &Configuration) -> Arc { - let ( - _database, - _in_memory_whitelist, - _whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - _db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(config); - - in_memory_torrent_repository - } - fn sample_peer() -> peer::Peer { peer::Peer { peer_id: PeerId(*b"-qB00000000000000000"), @@ -153,17 +134,11 @@ mod tests { use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_configuration::Configuration; - use torrust_tracker_test_helpers::configuration; - use crate::core::services::torrent::tests::{initialize_in_memory_torrent_repository, sample_peer}; + use crate::core::services::torrent::tests::sample_peer; use crate::core::services::torrent::{get_torrent_info, Info}; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - pub fn tracker_configuration() -> Configuration { - configuration::ephemeral() - } - #[tokio::test] async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); @@ -179,9 +154,7 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { - let config = tracker_configuration(); - - let in_memory_torrent_repository = initialize_in_memory_torrent_repository(&config); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -210,17 +183,11 @@ mod tests { use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_configuration::Configuration; - use torrust_tracker_test_helpers::configuration; - use crate::core::services::torrent::tests::{initialize_in_memory_torrent_repository, sample_peer}; + use crate::core::services::torrent::tests::sample_peer; use crate::core::services::torrent::{get_torrents_page, BasicInfo, Pagination}; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - pub fn tracker_configuration() -> Configuration { - configuration::ephemeral() - } - #[tokio::test] async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); @@ -232,9 +199,7 @@ mod tests { #[tokio::test] async fn should_return_a_summarized_info_for_all_torrents() { - let config = tracker_configuration(); - - let in_memory_torrent_repository = initialize_in_memory_torrent_repository(&config); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); @@ -256,9 +221,7 @@ mod tests { #[tokio::test] async fn should_allow_limiting_the_number_of_torrents_in_the_result() { - let config = tracker_configuration(); - - let in_memory_torrent_repository = initialize_in_memory_torrent_repository(&config); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -279,9 +242,7 @@ mod tests { #[tokio::test] async fn should_allow_using_pagination_in_the_result() { - let config = tracker_configuration(); - - let in_memory_torrent_repository = initialize_in_memory_torrent_repository(&config); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); @@ -311,9 +272,7 @@ mod tests { #[tokio::test] async fn should_return_torrents_ordered_by_info_hash() { - let config = tracker_configuration(); - - let in_memory_torrent_repository = initialize_in_memory_torrent_repository(&config); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash1 = InfoHash::from_str(&hash1).unwrap(); diff --git a/src/lib.rs b/src/lib.rs index 8e0e64db0..212430605 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -491,7 +491,6 @@ use torrust_tracker_clock::clock; pub mod app; -pub mod app_test; pub mod bootstrap; pub mod console; pub mod container; diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 247c6b8c6..d6c850327 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -250,76 +250,73 @@ mod tests { use bittorrent_http_protocol::v1::requests::announce::Announce; use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; - use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; - use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; + use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::service::AuthenticationService; - use crate::core::services::statistics; + use crate::core::core_tests::sample_info_hash; + use crate::core::services::{initialize_database, statistics}; use crate::core::statistics::event::sender::Sender; - use crate::core::whitelist; - - type TrackerAndDeps = ( - Arc, - Arc, - Arc>>, - Arc, - Arc, - ); - - fn private_tracker() -> TrackerAndDeps { - initialize_tracker_and_deps(configuration::ephemeral_private()) + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use crate::core::whitelist::authorization::WhitelistAuthorization; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; + + struct CoreTrackerServices { + pub core_config: Arc, + pub announce_handler: Arc, + pub stats_event_sender: Arc>>, + pub whitelist_authorization: Arc, + pub authentication_service: Arc, } - fn whitelisted_tracker() -> TrackerAndDeps { - initialize_tracker_and_deps(configuration::ephemeral_listed()) + fn initialize_private_tracker() -> CoreTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_private()) } - fn tracker_on_reverse_proxy() -> TrackerAndDeps { - initialize_tracker_and_deps(configuration::ephemeral_with_reverse_proxy()) + fn initialize_listed_tracker() -> CoreTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_listed()) } - fn tracker_not_on_reverse_proxy() -> TrackerAndDeps { - initialize_tracker_and_deps(configuration::ephemeral_without_reverse_proxy()) + fn initialize_tracker_on_reverse_proxy() -> CoreTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_with_reverse_proxy()) } - /// Initialize tracker's dependencies and tracker. - fn initialize_tracker_and_deps(config: Configuration) -> TrackerAndDeps { - let ( - _database, - _in_memory_whitelist, - whitelist_authorization, - authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); + fn initialize_tracker_not_on_reverse_proxy() -> CoreTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_without_reverse_proxy()) + } + fn initialize_core_tracker_services(config: &Configuration) -> CoreTrackerServices { + let core_config = Arc::new(config.core.clone()); + let database = initialize_database(config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository)); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, &db_torrent_repository, )); - let config = Arc::new(config.core); - - ( - config, + CoreTrackerServices { + core_config, announce_handler, stats_event_sender, whitelist_authorization, authentication_service, - ) + } } fn sample_announce_request() -> Announce { Announce { - info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), + info_hash: sample_info_hash(), peer_id: PeerId(*b"-qB00000000000000001"), port: 17548, downloaded: None, @@ -348,28 +345,24 @@ mod tests { mod with_tracker_in_private_mode { use std::str::FromStr; - use std::sync::Arc; - use super::{private_tracker, sample_announce_request, sample_client_ip_sources}; + use super::{initialize_private_tracker, sample_announce_request, sample_client_ip_sources}; use crate::core::authentication; use crate::servers::http::v1::handlers::announce::handle_announce; use crate::servers::http::v1::handlers::announce::tests::assert_error_response; #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_missing() { - let (config, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = - private_tracker(); - - let stats_event_sender = Arc::new(stats_event_sender); + let core_tracker_services = initialize_private_tracker(); let maybe_key = None; let response = handle_announce( - &config, - &announce_handler, - &authentication_service, - &whitelist_authorization, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.whitelist_authorization, + &core_tracker_services.stats_event_sender, &sample_announce_request(), &sample_client_ip_sources(), maybe_key, @@ -385,21 +378,18 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_invalid() { - let (config, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = - private_tracker(); - - let stats_event_sender = Arc::new(stats_event_sender); + let core_tracker_services = initialize_private_tracker(); let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); let maybe_key = Some(unregistered_key); let response = handle_announce( - &config, - &announce_handler, - &authentication_service, - &whitelist_authorization, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.whitelist_authorization, + &core_tracker_services.stats_event_sender, &sample_announce_request(), &sample_client_ip_sources(), maybe_key, @@ -413,27 +403,22 @@ mod tests { mod with_tracker_in_listed_mode { - use std::sync::Arc; - - use super::{sample_announce_request, sample_client_ip_sources, whitelisted_tracker}; + use super::{initialize_listed_tracker, sample_announce_request, sample_client_ip_sources}; use crate::servers::http::v1::handlers::announce::handle_announce; use crate::servers::http::v1::handlers::announce::tests::assert_error_response; #[tokio::test] async fn it_should_fail_when_the_announced_torrent_is_not_whitelisted() { - let (config, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = - whitelisted_tracker(); - - let stats_event_sender = Arc::new(stats_event_sender); + let core_tracker_services = initialize_listed_tracker(); let announce_request = sample_announce_request(); let response = handle_announce( - &config, - &announce_handler, - &authentication_service, - &whitelist_authorization, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.whitelist_authorization, + &core_tracker_services.stats_event_sender, &announce_request, &sample_client_ip_sources(), None, @@ -453,20 +438,15 @@ mod tests { mod with_tracker_on_reverse_proxy { - use std::sync::Arc; - use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; - use super::{sample_announce_request, tracker_on_reverse_proxy}; + use super::{initialize_tracker_on_reverse_proxy, sample_announce_request}; use crate::servers::http::v1::handlers::announce::handle_announce; use crate::servers::http::v1::handlers::announce::tests::assert_error_response; #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let (config, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = - tracker_on_reverse_proxy(); - - let stats_event_sender = Arc::new(stats_event_sender); + let core_tracker_services = initialize_tracker_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -474,11 +454,11 @@ mod tests { }; let response = handle_announce( - &config, - &announce_handler, - &authentication_service, - &whitelist_authorization, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.whitelist_authorization, + &core_tracker_services.stats_event_sender, &sample_announce_request(), &client_ip_sources, None, @@ -495,20 +475,15 @@ mod tests { mod with_tracker_not_on_reverse_proxy { - use std::sync::Arc; - use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; - use super::{sample_announce_request, tracker_not_on_reverse_proxy}; + use super::{initialize_tracker_not_on_reverse_proxy, sample_announce_request}; use crate::servers::http::v1::handlers::announce::handle_announce; use crate::servers::http::v1::handlers::announce::tests::assert_error_response; #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let (config, announce_handler, stats_event_sender, whitelist_authorization, authentication_service) = - tracker_not_on_reverse_proxy(); - - let stats_event_sender = Arc::new(stats_event_sender); + let core_tracker_services = initialize_tracker_not_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -516,11 +491,11 @@ mod tests { }; let response = handle_announce( - &config, - &announce_handler, - &authentication_service, - &whitelist_authorization, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.whitelist_authorization, + &core_tracker_services.stats_event_sender, &sample_announce_request(), &client_ip_sources, None, diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index c4013d8e9..a197263e8 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -171,137 +171,62 @@ mod tests { use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_configuration::Core; + use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; - use crate::app_test::initialize_tracker_dependencies; + use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::service::AuthenticationService; use crate::core::scrape_handler::ScrapeHandler; use crate::core::services::statistics; - - #[allow(clippy::type_complexity)] - fn private_tracker() -> ( - Arc, - Arc, - Arc>>, - Arc, - ) { - let config = configuration::ephemeral_private(); - - let ( - _database, - _in_memory_whitelist, - whitelist_authorization, - authentication_service, - in_memory_torrent_repository, - _db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - - let stats_event_sender = Arc::new(stats_event_sender); - - let core_config = Arc::new(config.core.clone()); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - (core_config, scrape_handler, stats_event_sender, authentication_service) + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::whitelist::authorization::WhitelistAuthorization; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; + + struct CoreTrackerServices { + pub core_config: Arc, + pub scrape_handler: Arc, + pub stats_event_sender: Arc>>, + pub authentication_service: Arc, } - #[allow(clippy::type_complexity)] - fn whitelisted_tracker() -> ( - Arc, - Arc, - Arc>>, - Arc, - ) { - let config = configuration::ephemeral_listed(); - - let ( - _database, - _in_memory_whitelist, - whitelist_authorization, - authentication_service, - in_memory_torrent_repository, - _db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - - let stats_event_sender = Arc::new(stats_event_sender); - - let core_config = Arc::new(config.core.clone()); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - (core_config, scrape_handler, stats_event_sender, authentication_service) + fn initialize_private_tracker() -> CoreTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_private()) } - #[allow(clippy::type_complexity)] - fn tracker_on_reverse_proxy() -> ( - Arc, - Arc, - Arc>>, - Arc, - ) { - let config = configuration::ephemeral_with_reverse_proxy(); - - let ( - _database, - _in_memory_whitelist, - whitelist_authorization, - authentication_service, - in_memory_torrent_repository, - _db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - - let stats_event_sender = Arc::new(stats_event_sender); - - let core_config = Arc::new(config.core.clone()); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - (core_config, scrape_handler, stats_event_sender, authentication_service) + fn initialize_listed_tracker() -> CoreTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_listed()) } - #[allow(clippy::type_complexity)] - fn tracker_not_on_reverse_proxy() -> ( - Arc, - Arc, - Arc>>, - Arc, - ) { - let config = configuration::ephemeral_without_reverse_proxy(); + fn initialize_tracker_on_reverse_proxy() -> CoreTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_with_reverse_proxy()) + } - let ( - _database, - _in_memory_whitelist, - whitelist_authorization, - authentication_service, - in_memory_torrent_repository, - _db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); + fn initialize_tracker_not_on_reverse_proxy() -> CoreTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_without_reverse_proxy()) + } + fn initialize_core_tracker_services(config: &Configuration) -> CoreTrackerServices { + let core_config = Arc::new(config.core.clone()); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository)); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - - let core_config = Arc::new(config.core.clone()); - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (core_config, scrape_handler, stats_event_sender, authentication_service) + CoreTrackerServices { + core_config, + scrape_handler, + stats_event_sender, + authentication_service, + } } fn sample_scrape_request() -> Scrape { Scrape { - info_hashes: vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()], // # DevSkim: ignore DS173237 + info_hashes: vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()], // DevSkim: ignore DS173237 } } @@ -324,22 +249,22 @@ mod tests { use torrust_tracker_primitives::core::ScrapeData; - use super::{private_tracker, sample_client_ip_sources, sample_scrape_request}; + use super::{initialize_private_tracker, sample_client_ip_sources, sample_scrape_request}; use crate::core::authentication; use crate::servers::http::v1::handlers::scrape::handle_scrape; #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { - let (core_config, scrape_handler, stats_event_sender, authentication_service) = private_tracker(); + let core_tracker_services = initialize_private_tracker(); let scrape_request = sample_scrape_request(); let maybe_key = None; let scrape_data = handle_scrape( - &core_config, - &scrape_handler, - &authentication_service, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.scrape_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.stats_event_sender, &scrape_request, &sample_client_ip_sources(), maybe_key, @@ -354,17 +279,17 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() { - let (core_config, scrape_handler, stats_event_sender, authentication_service) = private_tracker(); + let core_tracker_services = initialize_private_tracker(); let scrape_request = sample_scrape_request(); let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); let maybe_key = Some(unregistered_key); let scrape_data = handle_scrape( - &core_config, - &scrape_handler, - &authentication_service, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.scrape_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.stats_event_sender, &scrape_request, &sample_client_ip_sources(), maybe_key, @@ -382,20 +307,20 @@ mod tests { use torrust_tracker_primitives::core::ScrapeData; - use super::{sample_client_ip_sources, sample_scrape_request, whitelisted_tracker}; + use super::{initialize_listed_tracker, sample_client_ip_sources, sample_scrape_request}; use crate::servers::http::v1::handlers::scrape::handle_scrape; #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() { - let (core_config, scrape_handler, stats_event_sender, authentication_service) = whitelisted_tracker(); + let core_tracker_services = initialize_listed_tracker(); let scrape_request = sample_scrape_request(); let scrape_data = handle_scrape( - &core_config, - &scrape_handler, - &authentication_service, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.scrape_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.stats_event_sender, &scrape_request, &sample_client_ip_sources(), None, @@ -413,13 +338,13 @@ mod tests { use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; - use super::{sample_scrape_request, tracker_on_reverse_proxy}; + use super::{initialize_tracker_on_reverse_proxy, sample_scrape_request}; use crate::servers::http::v1::handlers::scrape::handle_scrape; use crate::servers::http::v1::handlers::scrape::tests::assert_error_response; #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let (core_config, scrape_handler, stats_event_sender, authentication_service) = tracker_on_reverse_proxy(); + let core_tracker_services = initialize_tracker_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -427,10 +352,10 @@ mod tests { }; let response = handle_scrape( - &core_config, - &scrape_handler, - &authentication_service, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.scrape_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.stats_event_sender, &sample_scrape_request(), &client_ip_sources, None, @@ -449,13 +374,13 @@ mod tests { use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; - use super::{sample_scrape_request, tracker_not_on_reverse_proxy}; + use super::{initialize_tracker_not_on_reverse_proxy, sample_scrape_request}; use crate::servers::http::v1::handlers::scrape::handle_scrape; use crate::servers::http::v1::handlers::scrape::tests::assert_error_response; #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let (core_config, scrape_handler, stats_event_sender, authentication_service) = tracker_not_on_reverse_proxy(); + let core_tracker_services = initialize_tracker_not_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -463,10 +388,10 @@ mod tests { }; let response = handle_scrape( - &core_config, - &scrape_handler, - &authentication_service, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.scrape_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.stats_event_sender, &sample_scrape_request(), &client_ip_sources, None, diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index c8c2980c3..e96face6a 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -64,36 +64,38 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; - use crate::core::services::statistics; + use crate::core::services::{initialize_database, statistics}; use crate::core::statistics::event::sender::Sender; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - #[allow(clippy::type_complexity)] - fn public_tracker() -> (Arc, Arc, Arc>>) { + struct CoreTrackerServices { + pub core_config: Arc, + pub announce_handler: Arc, + pub stats_event_sender: Arc>>, + } + + fn initialize_core_tracker_services() -> CoreTrackerServices { let config = configuration::ephemeral_public(); - let ( - _database, - _in_memory_whitelist, - _whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); + let core_config = Arc::new(config.core.clone()); + let database = initialize_database(&config); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, &db_torrent_repository, )); - let core_config = Arc::new(config.core.clone()); - - (core_config, announce_handler, stats_event_sender) + CoreTrackerServices { + core_config, + announce_handler, + stats_event_sender, + } } fn sample_peer_using_ipv4() -> peer::Peer { @@ -133,25 +135,21 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; - use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; use crate::core::core_tests::sample_info_hash; + use crate::core::services::initialize_database; use crate::core::statistics; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use crate::servers::http::v1::services::announce::invoke; - use crate::servers::http::v1::services::announce::tests::{public_tracker, sample_peer}; + use crate::servers::http::v1::services::announce::tests::{initialize_core_tracker_services, sample_peer}; fn initialize_announce_handler() -> Arc { let config = configuration::ephemeral(); - let ( - _database, - _in_memory_whitelist, - _whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); + let database = initialize_database(&config); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); Arc::new(AnnounceHandler::new( &config.core, @@ -162,13 +160,13 @@ mod tests { #[tokio::test] async fn it_should_return_the_announce_data() { - let (core_config, announce_handler, stats_event_sender) = public_tracker(); + let core_tracker_services = initialize_core_tracker_services(); let mut peer = sample_peer(); let announce_data = invoke( - announce_handler.clone(), - stats_event_sender.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.stats_event_sender.clone(), sample_info_hash(), &mut peer, &PeersWanted::All, @@ -182,7 +180,7 @@ mod tests { complete: 1, incomplete: 0, }, - policy: core_config.announce_policy, + policy: core_tracker_services.core_config.announce_policy, }; assert_eq!(announce_data, expected_announce_data); diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 6cd7213be..7e65b9442 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -80,30 +80,28 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; use crate::core::core_tests::sample_info_hash; use crate::core::scrape_handler::ScrapeHandler; + use crate::core::services::initialize_database; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use crate::core::whitelist::authorization::WhitelistAuthorization; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - fn public_tracker_and_announce_and_scrape_handlers() -> (Arc, Arc) { + fn initialize_announce_and_scrape_handlers_for_public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); - let ( - _database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - + let database = initialize_database(&config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, &db_torrent_repository, )); - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); (announce_handler, scrape_handler) @@ -128,15 +126,9 @@ mod tests { fn initialize_scrape_handler() -> Arc { let config = configuration::ephemeral(); - let ( - _database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - _db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)) } @@ -155,8 +147,8 @@ mod tests { use crate::core::statistics; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ - initialize_scrape_handler, public_tracker_and_announce_and_scrape_handlers, sample_info_hash, sample_info_hashes, - sample_peer, + initialize_announce_and_scrape_handlers_for_public_tracker, initialize_scrape_handler, sample_info_hash, + sample_info_hashes, sample_peer, }; #[tokio::test] @@ -164,7 +156,7 @@ mod tests { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); - let (announce_handler, scrape_handler) = public_tracker_and_announce_and_scrape_handlers(); + let (announce_handler, scrape_handler) = initialize_announce_and_scrape_handlers_for_public_tracker(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; @@ -239,7 +231,7 @@ mod tests { use crate::core::statistics; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ - public_tracker_and_announce_and_scrape_handlers, sample_info_hash, sample_info_hashes, sample_peer, + initialize_announce_and_scrape_handlers_for_public_tracker, sample_info_hash, sample_info_hashes, sample_peer, }; #[tokio::test] @@ -247,7 +239,7 @@ mod tests { let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); - let (announce_handler, _scrape_handler) = public_tracker_and_announce_and_scrape_handlers(); + let (announce_handler, _scrape_handler) = initialize_announce_and_scrape_handlers_for_public_tracker(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 2e753404d..43dc69019 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -498,79 +498,68 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::gen_remote_fingerprint; - use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::{initialize_whitelist_manager, statistics}; + use crate::core::services::{initialize_database, statistics}; use crate::core::statistics::event::sender::Sender; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use crate::core::whitelist; - use crate::core::whitelist::manager::WhitelistManager; + use crate::core::whitelist::authorization::WhitelistAuthorization; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::CurrentClock; - type TrackerAndDeps = ( - Arc, - Arc, - Arc, - Arc, - Arc>>, - Arc, - Arc, - Arc, - ); - - fn tracker_configuration() -> Configuration { - default_testing_tracker_configuration() + struct CoreTrackerServices { + pub core_config: Arc, + pub announce_handler: Arc, + pub scrape_handler: Arc, + pub in_memory_torrent_repository: Arc, + pub stats_event_sender: Arc>>, + pub in_memory_whitelist: Arc, + pub whitelist_authorization: Arc, } fn default_testing_tracker_configuration() -> Configuration { configuration::ephemeral() } - fn public_tracker() -> TrackerAndDeps { - initialize_tracker_and_deps(&configuration::ephemeral_public()) + fn initialize_core_tracker_services_for_default_tracker_configuration() -> CoreTrackerServices { + initialize_core_tracker_services(&default_testing_tracker_configuration()) } - fn whitelisted_tracker() -> TrackerAndDeps { - initialize_tracker_and_deps(&configuration::ephemeral_listed()) + fn initialize_core_tracker_services_for_public_tracker() -> CoreTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_public()) } - fn initialize_tracker_and_deps(config: &Configuration) -> TrackerAndDeps { - let core_config = Arc::new(config.core.clone()); - - let ( - database, - in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(config); + fn initialize_core_tracker_services_for_listed_tracker() -> CoreTrackerServices { + initialize_core_tracker_services(&configuration::ephemeral_listed()) + } + fn initialize_core_tracker_services(config: &Configuration) -> CoreTrackerServices { + let core_config = Arc::new(config.core.clone()); + let database = initialize_database(config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, &db_torrent_repository, )); - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - ( + CoreTrackerServices { core_config, announce_handler, scrape_handler, in_memory_torrent_repository, stats_event_sender, in_memory_whitelist, - whitelist_manager, whitelist_authorization, - ) + } } fn sample_ipv4_remote_addr() -> SocketAddr { @@ -667,38 +656,6 @@ mod tests { } } - #[allow(clippy::type_complexity)] - fn test_tracker_factory() -> ( - Arc, - Arc, - Arc, - Arc, - ) { - let config = tracker_configuration(); - - let core_config = Arc::new(config.core.clone()); - - let ( - _database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); - - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - (core_config, announce_handler, scrape_handler, whitelist_authorization) - } - mod connect_request { use std::future; @@ -916,23 +873,15 @@ mod tests { use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - gen_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, sample_issue_time, - test_tracker_factory, TorrentPeerBuilder, + gen_remote_fingerprint, initialize_core_tracker_services_for_default_tracker_configuration, + initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, + sample_issue_time, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { - let ( - core_config, - announce_handler, - _scrape_handler, - in_memory_torrent_repository, - stats_event_sender, - _in_memory_whitelist, - _whitelist_manager, - whitelist_authorization, - ) = public_tracker(); + let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); let client_ip = Ipv4Addr::new(126, 0, 0, 1); let client_port = 8080; @@ -952,16 +901,18 @@ mod tests { handle_announce( remote_addr, &request, - &core_config, - &announce_handler, - &whitelist_authorization, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_tracker_services.stats_event_sender, sample_cookie_valid_range(), ) .await .unwrap(); - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()); let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) @@ -973,16 +924,7 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { - let ( - core_config, - announce_handler, - _scrape_handler, - _in_memory_torrent_repository, - stats_event_sender, - _in_memory_whitelist, - _whitelist_manager, - whitelist_authorization, - ) = public_tracker(); + let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); @@ -993,10 +935,10 @@ mod tests { let response = handle_announce( remote_addr, &request, - &core_config, - &announce_handler, - &whitelist_authorization, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_tracker_services.stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1023,16 +965,7 @@ mod tests { // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): // "Do note that most trackers will only honor the IP address field under limited circumstances." - let ( - core_config, - announce_handler, - _scrape_handler, - in_memory_torrent_repository, - stats_event_sender, - _in_memory_whitelist, - _whitelist_manager, - whitelist_authorization, - ) = public_tracker(); + let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -1055,16 +988,18 @@ mod tests { handle_announce( remote_addr, &request, - &core_config, - &announce_handler, - &whitelist_authorization, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_tracker_services.stats_event_sender, sample_cookie_valid_range(), ) .await .unwrap(); - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()); assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); } @@ -1113,21 +1048,16 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { - let ( - core_config, - announce_handler, - _scrape_handler, - in_memory_torrent_repository, - _stats_event_sender, - _in_memory_whitelist, - _whitelist_manager, - whitelist_authorization, - ) = public_tracker(); - - add_a_torrent_peer_using_ipv6(&in_memory_torrent_repository); - - let response = - announce_a_new_peer_using_ipv4(core_config.clone(), announce_handler.clone(), whitelist_authorization).await; + let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + + add_a_torrent_peer_using_ipv6(&core_tracker_services.in_memory_torrent_repository); + + let response = announce_a_new_peer_using_ipv4( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.whitelist_authorization, + ) + .await; // The response should not contain the peer using IPV6 let peers: Option>> = match response { @@ -1149,14 +1079,14 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (core_config, announce_handler, _scrape_handler, whitelist_authorization) = test_tracker_factory(); + let core_tracker_services = initialize_core_tracker_services_for_default_tracker_configuration(); handle_announce( sample_ipv4_socket_address(), &AnnounceRequestBuilder::default().into(), - &core_config, - &announce_handler, - &whitelist_authorization, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1174,21 +1104,13 @@ mod tests { use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - gen_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_issue_time, TorrentPeerBuilder, + gen_remote_fingerprint, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, + sample_issue_time, TorrentPeerBuilder, }; #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { - let ( - core_config, - announce_handler, - _scrape_handler, - in_memory_torrent_repository, - stats_event_sender, - _in_memory_whitelist, - _whitelist_manager, - whitelist_authorization, - ) = public_tracker(); + let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); let client_ip = Ipv4Addr::new(127, 0, 0, 1); let client_port = 8080; @@ -1208,18 +1130,20 @@ mod tests { handle_announce( remote_addr, &request, - &core_config, - &announce_handler, - &whitelist_authorization, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_tracker_services.stats_event_sender, sample_cookie_valid_range(), ) .await .unwrap(); - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()); - let external_ip_in_tracker_configuration = core_config.net.external_ip.unwrap(); + let external_ip_in_tracker_configuration = core_tracker_services.core_config.net.external_ip.unwrap(); let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) @@ -1250,23 +1174,15 @@ mod tests { use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - gen_remote_fingerprint, public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, sample_issue_time, - test_tracker_factory, TorrentPeerBuilder, + gen_remote_fingerprint, initialize_core_tracker_services_for_default_tracker_configuration, + initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, + sample_issue_time, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { - let ( - core_config, - announce_handler, - _scrape_handler, - in_memory_torrent_repository, - stats_event_sender, - _in_memory_whitelist, - _whitelist_manager, - whitelist_authorization, - ) = public_tracker(); + let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -1287,16 +1203,18 @@ mod tests { handle_announce( remote_addr, &request, - &core_config, - &announce_handler, - &whitelist_authorization, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_tracker_services.stats_event_sender, sample_cookie_valid_range(), ) .await .unwrap(); - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()); let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) @@ -1308,16 +1226,7 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { - let ( - core_config, - announce_handler, - _scrape_handler, - _in_memory_torrent_repository, - stats_event_sender, - _in_memory_whitelist, - _whitelist_manager, - whitelist_authorization, - ) = public_tracker(); + let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -1331,10 +1240,10 @@ mod tests { let response = handle_announce( remote_addr, &request, - &core_config, - &announce_handler, - &whitelist_authorization, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_tracker_services.stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1361,16 +1270,7 @@ mod tests { // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): // "Do note that most trackers will only honor the IP address field under limited circumstances." - let ( - core_config, - announce_handler, - _scrape_handler, - in_memory_torrent_repository, - stats_event_sender, - _in_memory_whitelist, - _whitelist_manager, - whitelist_authorization, - ) = public_tracker(); + let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -1393,16 +1293,18 @@ mod tests { handle_announce( remote_addr, &request, - &core_config, - &announce_handler, - &whitelist_authorization, - &stats_event_sender, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_tracker_services.stats_event_sender, sample_cookie_valid_range(), ) .await .unwrap(); - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()); // When using IPv6 the tracker converts the remote client ip into a IPv4 address assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); @@ -1454,21 +1356,16 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { - let ( - core_config, - announce_handler, - _scrape_handler, - in_memory_torrent_repository, - _stats_event_sender, - _in_memory_whitelist, - _whitelist_manager, - whitelist_authorization, - ) = public_tracker(); - - add_a_torrent_peer_using_ipv4(&in_memory_torrent_repository); - - let response = - announce_a_new_peer_using_ipv6(core_config.clone(), announce_handler.clone(), whitelist_authorization).await; + let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + + add_a_torrent_peer_using_ipv4(&core_tracker_services.in_memory_torrent_repository); + + let response = announce_a_new_peer_using_ipv6( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.whitelist_authorization, + ) + .await; // The response should not contain the peer using IPV4 let peers: Option>> = match response { @@ -1490,7 +1387,7 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let (core_config, announce_handler, _scrape_handler, whitelist_authorization) = test_tracker_factory(); + let core_tracker_services = initialize_core_tracker_services_for_default_tracker_configuration(); let remote_addr = sample_ipv6_remote_addr(); @@ -1501,9 +1398,9 @@ mod tests { handle_announce( remote_addr, &announce_request, - &core_config, - &announce_handler, - &whitelist_authorization, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1519,9 +1416,13 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; use mockall::predicate::eq; - use crate::app_test::initialize_tracker_dependencies; use crate::core::announce_handler::AnnounceHandler; + use crate::core::services::initialize_database; use crate::core::statistics; + use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use crate::core::whitelist::authorization::WhitelistAuthorization; + use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; @@ -1533,15 +1434,12 @@ mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - let ( - _database, - _in_memory_whitelist, - whitelist_authorization, - _authentication_service, - in_memory_torrent_repository, - db_torrent_repository, - _torrents_manager, - ) = initialize_tracker_dependencies(&config); + let database = initialize_database(&config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = + Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); stats_event_sender_mock @@ -1625,7 +1523,8 @@ mod tests { use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ - public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, sample_issue_time, + initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, + sample_issue_time, }; fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { @@ -1638,16 +1537,7 @@ mod tests { #[tokio::test] async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { - let ( - _core_config, - _announce_handler, - scrape_handler, - _in_memory_torrent_repository, - stats_event_sender, - _in_memory_whitelist, - _whitelist_manager, - _whitelist_authorization, - ) = public_tracker(); + let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); let remote_addr = sample_ipv4_remote_addr(); @@ -1663,8 +1553,8 @@ mod tests { let response = handle_scrape( remote_addr, &request, - &scrape_handler, - &stats_event_sender, + &core_tracker_services.scrape_handler, + &core_tracker_services.stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1742,24 +1632,19 @@ mod tests { mod with_a_public_tracker { use aquatic_udp_protocol::{NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; - use crate::servers::udp::handlers::tests::public_tracker; + use crate::servers::udp::handlers::tests::initialize_core_tracker_services_for_public_tracker; use crate::servers::udp::handlers::tests::scrape_request::{add_a_sample_seeder_and_scrape, match_scrape_response}; #[tokio::test] async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { - let ( - _core_config, - _announce_handler, - scrape_handler, - in_memory_torrent_repository, - _stats_event_sender, - _in_memory_whitelist, - _whitelist_manager, - _whitelist_authorization, - ) = public_tracker(); + let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); let torrent_stats = match_scrape_response( - add_a_sample_seeder_and_scrape(in_memory_torrent_repository.clone(), scrape_handler.clone()).await, + add_a_sample_seeder_and_scrape( + core_tracker_services.in_memory_torrent_repository.clone(), + core_tracker_services.scrape_handler.clone(), + ) + .await, ); let expected_torrent_stats = vec![TorrentScrapeStatistics { @@ -1779,27 +1664,25 @@ mod tests { use crate::servers::udp::handlers::tests::scrape_request::{ add_a_seeder, build_scrape_request, match_scrape_response, zeroed_torrent_statistics, }; - use crate::servers::udp::handlers::tests::{sample_cookie_valid_range, sample_ipv4_remote_addr, whitelisted_tracker}; + use crate::servers::udp::handlers::tests::{ + initialize_core_tracker_services_for_listed_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, + }; #[tokio::test] async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { - let ( - _core_config, - _announce_handler, - scrape_handler, - in_memory_torrent_repository, - stats_event_sender, - in_memory_whitelist, - _whitelist_manager, - _whitelist_authorization, - ) = whitelisted_tracker(); + let core_tracker_services = initialize_core_tracker_services_for_listed_tracker(); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); - add_a_seeder(in_memory_torrent_repository.clone(), &remote_addr, &info_hash).await; + add_a_seeder( + core_tracker_services.in_memory_torrent_repository.clone(), + &remote_addr, + &info_hash, + ) + .await; - in_memory_whitelist.add(&info_hash.0.into()).await; + core_tracker_services.in_memory_whitelist.add(&info_hash.0.into()).await; let request = build_scrape_request(&remote_addr, &info_hash); @@ -1807,8 +1690,8 @@ mod tests { handle_scrape( remote_addr, &request, - &scrape_handler, - &stats_event_sender, + &core_tracker_services.scrape_handler, + &core_tracker_services.stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1827,21 +1710,17 @@ mod tests { #[tokio::test] async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { - let ( - _core_config, - _announce_handler, - scrape_handler, - in_memory_torrent_repository, - stats_event_sender, - _in_memory_whitelist, - _whitelist_manager, - _whitelist_authorization, - ) = whitelisted_tracker(); + let core_tracker_services = initialize_core_tracker_services_for_listed_tracker(); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); - add_a_seeder(in_memory_torrent_repository.clone(), &remote_addr, &info_hash).await; + add_a_seeder( + core_tracker_services.in_memory_torrent_repository.clone(), + &remote_addr, + &info_hash, + ) + .await; let request = build_scrape_request(&remote_addr, &info_hash); @@ -1849,8 +1728,8 @@ mod tests { handle_scrape( remote_addr, &request, - &scrape_handler, - &stats_event_sender, + &core_tracker_services.scrape_handler, + &core_tracker_services.stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1885,7 +1764,8 @@ mod tests { use crate::core::statistics; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ - sample_cookie_valid_range, sample_ipv4_remote_addr, test_tracker_factory, + initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, + sample_ipv4_remote_addr, }; #[tokio::test] @@ -1901,12 +1781,12 @@ mod tests { let remote_addr = sample_ipv4_remote_addr(); - let (_core_config, _announce_handler, scrape_handler, _whitelist_authorization) = test_tracker_factory(); + let core_tracker_services = initialize_core_tracker_services_for_default_tracker_configuration(); handle_scrape( remote_addr, &sample_scrape_request(&remote_addr), - &scrape_handler, + &core_tracker_services.scrape_handler, &stats_event_sender, sample_cookie_valid_range(), ) @@ -1925,7 +1805,8 @@ mod tests { use crate::core::statistics; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ - sample_cookie_valid_range, sample_ipv6_remote_addr, test_tracker_factory, + initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, + sample_ipv6_remote_addr, }; #[tokio::test] @@ -1941,12 +1822,12 @@ mod tests { let remote_addr = sample_ipv6_remote_addr(); - let (_core_config, _announce_handler, scrape_handler, _whitelist_authorization) = test_tracker_factory(); + let core_tracker_services = initialize_core_tracker_services_for_default_tracker_configuration(); handle_scrape( remote_addr, &sample_scrape_request(&remote_addr), - &scrape_handler, + &core_tracker_services.scrape_handler, &stats_event_sender, sample_cookie_valid_range(), ) From 5342a5d65af9be07ee6d7cf7101b1e13c4d8204e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 28 Jan 2025 18:48:27 +0000 Subject: [PATCH 0673/1297] refactor: [#1217] extract UdpTrackerContainer --- src/app.rs | 20 ++----- src/bootstrap/app.rs | 9 ++-- src/bootstrap/jobs/udp_tracker.rs | 45 +++------------- src/console/profiling.rs | 3 ++ src/container.rs | 27 ++++++++++ src/main.rs | 4 ++ src/servers/udp/handlers.rs | 56 ++++++------------- src/servers/udp/server/launcher.rs | 83 ++++++----------------------- src/servers/udp/server/mod.rs | 35 +++++------- src/servers/udp/server/processor.rs | 44 ++++----------- src/servers/udp/server/spawner.rs | 33 +++--------- src/servers/udp/server/states.rs | 33 +++--------- tests/servers/udp/contract.rs | 2 +- tests/servers/udp/environment.rs | 77 ++++++++++---------------- 14 files changed, 145 insertions(+), 326 deletions(-) diff --git a/src/app.rs b/src/app.rs index 75c2e13bc..e0f231611 100644 --- a/src/app.rs +++ b/src/app.rs @@ -28,7 +28,7 @@ use torrust_tracker_configuration::Configuration; use tracing::instrument; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; -use crate::container::AppContainer; +use crate::container::{AppContainer, UdpTrackerContainer}; use crate::servers; use crate::servers::registar::Registar; @@ -39,7 +39,7 @@ use crate::servers::registar::Registar; /// - Can't retrieve tracker keys from database. /// - Can't load whitelist from database. #[instrument(skip(config, app_container))] -pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec> { +pub async fn start(config: &Configuration, app_container: &Arc) -> Vec> { if config.http_api.is_none() && (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) && (config.http_trackers.is_none() || config.http_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) @@ -78,19 +78,9 @@ pub async fn start(config: &Configuration, app_container: &AppContainer) -> Vec< udp_tracker_config.bind_address ); } else { - jobs.push( - udp_tracker::start_job( - Arc::new(config.core.clone()), - udp_tracker_config, - app_container.announce_handler.clone(), - app_container.scrape_handler.clone(), - app_container.whitelist_authorization.clone(), - app_container.stats_event_sender.clone(), - app_container.ban_service.clone(), - registar.give_form(), - ) - .await, - ); + let udp_tracker_config = Arc::new(udp_tracker_config.clone()); + let udp_tracker_container = Arc::new(UdpTrackerContainer::from_app_container(&udp_tracker_config, app_container)); + jobs.push(udp_tracker::start_job(udp_tracker_container, registar.give_form()).await); } } } else { diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index c69162322..71684a7e3 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -32,7 +32,7 @@ use crate::core::services::{initialize_database, initialize_whitelist_manager, s use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; -use crate::core::whitelist; +use crate::core::whitelist::authorization::WhitelistAuthorization; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -87,16 +87,14 @@ pub fn initialize_global_services(configuration: &Configuration) { /// It initializes the IoC Container. #[instrument(skip())] pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { + let core_config = Arc::new(configuration.core.clone()); let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let stats_repository = Arc::new(stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let database = initialize_database(configuration); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( - &configuration.core, - &in_memory_whitelist.clone(), - )); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&configuration.core, &in_memory_whitelist.clone())); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); @@ -125,6 +123,7 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); AppContainer { + core_config, database, announce_handler, scrape_handler, diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 4f54ecb59..387fdd6ae 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -8,17 +8,11 @@ //! > for the configuration options. use std::sync::Arc; -use tokio::sync::RwLock; use tokio::task::JoinHandle; -use torrust_tracker_configuration::{Core, UdpTracker}; use tracing::instrument; -use crate::core::announce_handler::AnnounceHandler; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::statistics::event::sender::Sender; -use crate::core::whitelist; +use crate::container::UdpTrackerContainer; use crate::servers::registar::ServiceRegistrationForm; -use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::spawner::Spawner; use crate::servers::udp::server::Server; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; @@ -33,41 +27,14 @@ use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// It will panic if it is unable to start the UDP service. /// It will panic if the task did not finish successfully. #[must_use] -#[allow(clippy::too_many_arguments)] #[allow(clippy::async_yields_async)] -#[instrument(skip( - config, - announce_handler, - scrape_handler, - whitelist_authorization, - stats_event_sender, - ban_service, - form -))] -pub async fn start_job( - core_config: Arc, - config: &UdpTracker, - announce_handler: Arc, - scrape_handler: Arc, - whitelist_authorization: Arc, - stats_event_sender: Arc>>, - ban_service: Arc>, - form: ServiceRegistrationForm, -) -> JoinHandle<()> { - let bind_to = config.bind_address; - let cookie_lifetime = config.cookie_lifetime; +#[instrument(skip(udp_tracker_container, form))] +pub async fn start_job(udp_tracker_container: Arc, form: ServiceRegistrationForm) -> JoinHandle<()> { + let bind_to = udp_tracker_container.udp_tracker_config.bind_address; + let cookie_lifetime = udp_tracker_container.udp_tracker_config.cookie_lifetime; let server = Server::new(Spawner::new(bind_to)) - .start( - core_config, - announce_handler, - scrape_handler, - whitelist_authorization, - stats_event_sender, - ban_service, - form, - cookie_lifetime, - ) + .start(udp_tracker_container, form, cookie_lifetime) .await .expect("it should be able to start the udp tracker"); diff --git a/src/console/profiling.rs b/src/console/profiling.rs index 318fce1e8..f3829c073 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -157,6 +157,7 @@ //! kcachegrind callgrind.out //! ``` use std::env; +use std::sync::Arc; use std::time::Duration; use tokio::time::sleep; @@ -181,6 +182,8 @@ pub async fn run() { let (config, app_container) = bootstrap::app::setup(); + let app_container = Arc::new(app_container); + let jobs = app::start(&config, &app_container).await; // Run the tracker for a fixed duration diff --git a/src/container.rs b/src/container.rs index 192fa62f1..1d137680e 100644 --- a/src/container.rs +++ b/src/container.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use tokio::sync::RwLock; +use torrust_tracker_configuration::{Core, UdpTracker}; use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::handler::KeysHandler; @@ -17,6 +18,7 @@ use crate::core::whitelist::manager::WhitelistManager; use crate::servers::udp::server::banning::BanService; pub struct AppContainer { + pub core_config: Arc, pub database: Arc>, pub announce_handler: Arc, pub scrape_handler: Arc, @@ -31,3 +33,28 @@ pub struct AppContainer { pub db_torrent_repository: Arc, pub torrents_manager: Arc, } + +pub struct UdpTrackerContainer { + pub core_config: Arc, + pub udp_tracker_config: Arc, + pub announce_handler: Arc, + pub scrape_handler: Arc, + pub whitelist_authorization: Arc, + pub stats_event_sender: Arc>>, + pub ban_service: Arc>, +} + +impl UdpTrackerContainer { + #[must_use] + pub fn from_app_container(udp_tracker_config: &Arc, app_container: &Arc) -> Self { + Self { + udp_tracker_config: udp_tracker_config.clone(), + core_config: app_container.core_config.clone(), + announce_handler: app_container.announce_handler.clone(), + scrape_handler: app_container.scrape_handler.clone(), + whitelist_authorization: app_container.whitelist_authorization.clone(), + stats_event_sender: app_container.stats_event_sender.clone(), + ban_service: app_container.ban_service.clone(), + } + } +} diff --git a/src/main.rs b/src/main.rs index f05de0327..77f6e32a3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,13 @@ +use std::sync::Arc; + use torrust_tracker_lib::{app, bootstrap}; #[tokio::main] async fn main() { let (config, app_container) = bootstrap::app::setup(); + let app_container = Arc::new(app_container); + let jobs = app::start(&config, &app_container).await; // handle the signals diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 43dc69019..992f27a44 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -11,7 +11,6 @@ use aquatic_udp_protocol::{ ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; use bittorrent_primitives::info_hash::InfoHash; -use tokio::sync::RwLock; use torrust_tracker_clock::clock::Time as _; use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; @@ -19,8 +18,8 @@ use uuid::Uuid; use zerocopy::network_endian::I32; use super::connection_cookie::{check, make}; -use super::server::banning::BanService; use super::RawRequest; +use crate::container::UdpTrackerContainer; use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; use crate::core::scrape_handler::ScrapeHandler; use crate::core::statistics::event::sender::Sender; @@ -57,18 +56,12 @@ impl CookieTimeValues { /// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. -#[allow(clippy::too_many_arguments)] -#[instrument(fields(request_id), skip(udp_request, announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, cookie_time_values, ban_service), ret(level = Level::TRACE))] +#[instrument(fields(request_id), skip(udp_request, udp_tracker_container, cookie_time_values), ret(level = Level::TRACE))] pub(crate) async fn handle_packet( udp_request: RawRequest, - core_config: &Arc, - announce_handler: &Arc, - scrape_handler: &Arc, - whitelist_authorization: &Arc, - opt_stats_event_sender: &Arc>>, + udp_tracker_container: Arc, local_addr: SocketAddr, cookie_time_values: CookieTimeValues, - ban_service: Arc>, ) -> Response { let request_id = Uuid::new_v4(); @@ -82,11 +75,7 @@ pub(crate) async fn handle_packet( Ok(request) => match handle_request( request, udp_request.from, - core_config, - announce_handler, - scrape_handler, - whitelist_authorization, - opt_stats_event_sender, + udp_tracker_container.clone(), cookie_time_values.clone(), ) .await @@ -98,7 +87,7 @@ pub(crate) async fn handle_packet( | Error::CookieValueExpired { .. } | Error::CookieValueFromFuture { .. } => { // code-review: should we include `RequestParseError` and `BadRequest`? - let mut ban_service = ban_service.write().await; + let mut ban_service = udp_tracker_container.ban_service.write().await; ban_service.increase_counter(&udp_request.from.ip()); } _ => {} @@ -108,7 +97,7 @@ pub(crate) async fn handle_packet( udp_request.from, local_addr, request_id, - opt_stats_event_sender, + &udp_tracker_container.stats_event_sender, cookie_time_values.valid_range.clone(), &e, Some(transaction_id), @@ -121,7 +110,7 @@ pub(crate) async fn handle_packet( udp_request.from, local_addr, request_id, - opt_stats_event_sender, + &udp_tracker_container.stats_event_sender, cookie_time_values.valid_range.clone(), &e, None, @@ -141,24 +130,11 @@ pub(crate) async fn handle_packet( /// # Errors /// /// If a error happens in the `handle_request` function, it will just return the `ServerError`. -#[allow(clippy::too_many_arguments)] -#[instrument(skip( - request, - remote_addr, - announce_handler, - scrape_handler, - whitelist_authorization, - opt_stats_event_sender, - cookie_time_values -))] +#[instrument(skip(request, remote_addr, udp_tracker_container, cookie_time_values))] pub async fn handle_request( request: Request, remote_addr: SocketAddr, - core_config: &Arc, - announce_handler: &Arc, - scrape_handler: &Arc, - whitelist_authorization: &Arc, - opt_stats_event_sender: &Arc>>, + udp_tracker_container: Arc, cookie_time_values: CookieTimeValues, ) -> Result { tracing::trace!("handle request"); @@ -167,7 +143,7 @@ pub async fn handle_request( Request::Connect(connect_request) => Ok(handle_connect( remote_addr, &connect_request, - opt_stats_event_sender, + &udp_tracker_container.stats_event_sender, cookie_time_values.issue_time, ) .await), @@ -175,10 +151,10 @@ pub async fn handle_request( handle_announce( remote_addr, &announce_request, - core_config, - announce_handler, - whitelist_authorization, - opt_stats_event_sender, + &udp_tracker_container.core_config, + &udp_tracker_container.announce_handler, + &udp_tracker_container.whitelist_authorization, + &udp_tracker_container.stats_event_sender, cookie_time_values.valid_range, ) .await @@ -187,8 +163,8 @@ pub async fn handle_request( handle_scrape( remote_addr, &scrape_request, - scrape_handler, - opt_stats_event_sender, + &udp_tracker_container.scrape_handler, + &udp_tracker_container.stats_event_sender, cookie_time_values.valid_range, ) .await diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 4aaf87ae2..e4edadd8f 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -6,18 +6,14 @@ use bittorrent_tracker_client::udp::client::check; use derive_more::Constructor; use futures_util::StreamExt; use tokio::select; -use tokio::sync::{oneshot, RwLock}; +use tokio::sync::oneshot; use tokio::time::interval; -use torrust_tracker_configuration::Core; use tracing::instrument; -use super::banning::BanService; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; -use crate::core::announce_handler::AnnounceHandler; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::statistics::event::sender::Sender; -use crate::core::{statistics, whitelist}; +use crate::container::UdpTrackerContainer; +use crate::core::statistics; use crate::servers::logging::STARTED_ON; use crate::servers::registar::ServiceHealthCheckJob; use crate::servers::signals::{shutdown_signal_with_message, Halted}; @@ -43,24 +39,9 @@ impl Launcher { /// It panics if unable to bind to udp socket, and get the address from the udp socket. /// It panics if unable to send address of socket. /// It panics if the udp server is loaded when the tracker is private. - #[allow(clippy::too_many_arguments)] - #[instrument(skip( - announce_handler, - scrape_handler, - whitelist_authorization, - opt_stats_event_sender, - ban_service, - bind_to, - tx_start, - rx_halt - ))] + #[instrument(skip(udp_tracker_container, bind_to, tx_start, rx_halt))] pub async fn run_with_graceful_shutdown( - core_config: Arc, - announce_handler: Arc, - scrape_handler: Arc, - whitelist_authorization: Arc, - opt_stats_event_sender: Arc>>, - ban_service: Arc>, + udp_tracker_container: Arc, bind_to: SocketAddr, cookie_lifetime: Duration, tx_start: oneshot::Sender, @@ -68,7 +49,7 @@ impl Launcher { ) { tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting on: {bind_to}"); - if core_config.private { + if udp_tracker_container.core_config.private { tracing::error!("udp services cannot be used for private trackers"); panic!("it should not use udp if using authentication"); } @@ -98,17 +79,7 @@ impl Launcher { let local_addr = local_udp_url.clone(); tokio::task::spawn(async move { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_with_graceful_shutdown::task (listening...)"); - let () = Self::run_udp_server_main( - receiver, - core_config.clone(), - announce_handler.clone(), - scrape_handler.clone(), - whitelist_authorization.clone(), - opt_stats_event_sender.clone(), - ban_service.clone(), - cookie_lifetime, - ) - .await; + let () = Self::run_udp_server_main(receiver, udp_tracker_container, cookie_lifetime).await; }) }; @@ -145,23 +116,10 @@ impl Launcher { ServiceHealthCheckJob::new(binding, info, job) } - #[allow(clippy::too_many_arguments)] - #[instrument(skip( - receiver, - announce_handler, - scrape_handler, - whitelist_authorization, - opt_stats_event_sender, - ban_service - ))] + #[instrument(skip(receiver, udp_tracker_container))] async fn run_udp_server_main( mut receiver: Receiver, - core_config: Arc, - announce_handler: Arc, - scrape_handler: Arc, - whitelist_authorization: Arc, - opt_stats_event_sender: Arc>>, - ban_service: Arc>, + udp_tracker_container: Arc, cookie_lifetime: Duration, ) { let active_requests = &mut ActiveRequests::default(); @@ -172,7 +130,7 @@ impl Launcher { let cookie_lifetime = cookie_lifetime.as_secs_f64(); - let ban_cleaner = ban_service.clone(); + let ban_cleaner = udp_tracker_container.ban_service.clone(); tokio::spawn(async move { let mut cleaner_interval = interval(Duration::from_secs(IP_BANS_RESET_INTERVAL_IN_SECS)); @@ -204,7 +162,7 @@ impl Launcher { } }; - if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { + if let Some(stats_event_sender) = udp_tracker_container.stats_event_sender.as_deref() { match req.from.ip() { IpAddr::V4(_) => { stats_event_sender.send_event(statistics::event::Event::Udp4Request).await; @@ -215,10 +173,10 @@ impl Launcher { } } - if ban_service.read().await.is_banned(&req.from.ip()) { + if udp_tracker_container.ban_service.read().await.is_banned(&req.from.ip()) { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop continue: (banned ip)"); - if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { + if let Some(stats_event_sender) = udp_tracker_container.stats_event_sender.as_deref() { stats_event_sender .send_event(statistics::event::Event::UdpRequestBanned) .await; @@ -227,15 +185,7 @@ impl Launcher { continue; } - let processor = Processor::new( - receiver.socket.clone(), - core_config.clone(), - announce_handler.clone(), - scrape_handler.clone(), - whitelist_authorization.clone(), - opt_stats_event_sender.clone(), - cookie_lifetime, - ); + let processor = Processor::new(receiver.socket.clone(), udp_tracker_container.clone(), cookie_lifetime); /* We spawn the new task even if the active requests buffer is full. This could seem counterintuitive because we are accepting @@ -248,8 +198,7 @@ impl Launcher { only adding and removing tasks without given them the chance to finish. However, the buffer is yielding before aborting one tasks, giving it the chance to finish. */ - let abort_handle: tokio::task::AbortHandle = - tokio::task::spawn(processor.process_request(req, ban_service.clone())).abort_handle(); + let abort_handle: tokio::task::AbortHandle = tokio::task::spawn(processor.process_request(req)).abort_handle(); if abort_handle.is_finished() { continue; @@ -260,7 +209,7 @@ impl Launcher { if old_request_aborted { // Evicted task from active requests buffer was aborted. - if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { + if let Some(stats_event_sender) = udp_tracker_container.stats_event_sender.as_deref() { stats_event_sender .send_event(statistics::event::Event::UdpRequestAborted) .await; diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index c87728361..941f6b5cb 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -63,6 +63,7 @@ mod tests { use super::spawner::Spawner; use super::Server; use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; + use crate::container::UdpTrackerContainer; use crate::servers::registar::Registar; #[tokio::test] @@ -71,7 +72,7 @@ mod tests { initialize_global_services(&cfg); - let app_container = initialize_app_container(&cfg); + let app_container = Arc::new(initialize_app_container(&cfg)); let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; @@ -80,17 +81,11 @@ mod tests { let stopped = Server::new(Spawner::new(bind_to)); + let udp_tracker_config = Arc::new(config.clone()); + let udp_tracker_container = Arc::new(UdpTrackerContainer::from_app_container(&udp_tracker_config, &app_container)); + let started = stopped - .start( - Arc::new(cfg.core.clone()), - app_container.announce_handler, - app_container.scrape_handler, - app_container.whitelist_authorization, - app_container.stats_event_sender, - app_container.ban_service, - register.give_form(), - config.cookie_lifetime, - ) + .start(udp_tracker_container, register.give_form(), config.cookie_lifetime) .await .expect("it should start the server"); @@ -107,25 +102,19 @@ mod tests { initialize_global_services(&cfg); - let app_container = initialize_app_container(&cfg); + let app_container = Arc::new(initialize_app_container(&cfg)); - let config = &cfg.udp_trackers.as_ref().unwrap().first().unwrap(); + let config = cfg.udp_trackers.as_ref().unwrap().first().unwrap(); let bind_to = config.bind_address; let register = &Registar::default(); let stopped = Server::new(Spawner::new(bind_to)); + let udp_tracker_config = Arc::new(config.clone()); + let udp_tracker_container = Arc::new(UdpTrackerContainer::from_app_container(&udp_tracker_config, &app_container)); + let started = stopped - .start( - Arc::new(cfg.core.clone()), - app_container.announce_handler, - app_container.scrape_handler, - app_container.whitelist_authorization, - app_container.stats_event_sender, - app_container.ban_service, - register.give_form(), - config.cookie_lifetime, - ) + .start(udp_tracker_container, register.give_form(), config.cookie_lifetime) .await .expect("it should start the server"); diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 24a34f98d..86a16d2d4 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -4,69 +4,43 @@ use std::sync::Arc; use std::time::Duration; use aquatic_udp_protocol::Response; -use tokio::sync::RwLock; use tokio::time::Instant; -use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; -use super::banning::BanService; use super::bound_socket::BoundSocket; -use crate::core::announce_handler::AnnounceHandler; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::statistics::event::sender::Sender; +use crate::container::UdpTrackerContainer; +use crate::core::statistics; use crate::core::statistics::event::UdpResponseKind; -use crate::core::{statistics, whitelist}; use crate::servers::udp::handlers::CookieTimeValues; use crate::servers::udp::{handlers, RawRequest}; pub struct Processor { socket: Arc, - core_config: Arc, - announce_handler: Arc, - scrape_handler: Arc, - whitelist_authorization: Arc, - opt_stats_event_sender: Arc>>, + udp_tracker_container: Arc, cookie_lifetime: f64, } impl Processor { #[allow(clippy::too_many_arguments)] - pub fn new( - socket: Arc, - core_config: Arc, - announce_handler: Arc, - scrape_handler: Arc, - whitelist_authorization: Arc, - opt_stats_event_sender: Arc>>, - cookie_lifetime: f64, - ) -> Self { + pub fn new(socket: Arc, udp_tracker_container: Arc, cookie_lifetime: f64) -> Self { Self { socket, - core_config, - announce_handler, - scrape_handler, - whitelist_authorization, - opt_stats_event_sender, + udp_tracker_container, cookie_lifetime, } } - #[instrument(skip(self, request, ban_service))] - pub async fn process_request(self, request: RawRequest, ban_service: Arc>) { + #[instrument(skip(self, request))] + pub async fn process_request(self, request: RawRequest) { let from = request.from; let start_time = Instant::now(); let response = handlers::handle_packet( request, - &self.core_config, - &self.announce_handler, - &self.scrape_handler, - &self.whitelist_authorization, - &self.opt_stats_event_sender, + self.udp_tracker_container.clone(), self.socket.address(), CookieTimeValues::new(self.cookie_lifetime), - ban_service, ) .await; @@ -109,7 +83,7 @@ impl Processor { tracing::debug!(%bytes_count, %sent_bytes, "sent {response_type}"); } - if let Some(stats_event_sender) = self.opt_stats_event_sender.as_deref() { + if let Some(stats_event_sender) = self.udp_tracker_container.stats_event_sender.as_deref() { match target.ip() { IpAddr::V4(_) => { stats_event_sender diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index d5fd5d58e..88ce5a245 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -5,17 +5,12 @@ use std::time::Duration; use derive_more::derive::Display; use derive_more::Constructor; -use tokio::sync::{oneshot, RwLock}; +use tokio::sync::oneshot; use tokio::task::JoinHandle; -use torrust_tracker_configuration::Core; -use super::banning::BanService; use super::launcher::Launcher; use crate::bootstrap::jobs::Started; -use crate::core::announce_handler::AnnounceHandler; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::statistics::event::sender::Sender; -use crate::core::whitelist; +use crate::container::UdpTrackerContainer; use crate::servers::signals::Halted; #[derive(Constructor, Copy, Clone, Debug, Display)] @@ -30,15 +25,10 @@ impl Spawner { /// # Panics /// /// It would panic if unable to resolve the `local_addr` from the supplied ´socket´. - #[allow(clippy::too_many_arguments)] + #[must_use] pub fn spawn_launcher( &self, - core_config: Arc, - announce_handler: Arc, - scrape_handler: Arc, - whitelist_authorization: Arc, - opt_stats_event_sender: Arc>>, - ban_service: Arc>, + udp_tracker_container: Arc, cookie_lifetime: Duration, tx_start: oneshot::Sender, rx_halt: oneshot::Receiver, @@ -46,19 +36,8 @@ impl Spawner { let spawner = Self::new(self.bind_to); tokio::spawn(async move { - Launcher::run_with_graceful_shutdown( - core_config, - announce_handler, - scrape_handler, - whitelist_authorization, - opt_stats_event_sender, - ban_service, - spawner.bind_to, - cookie_lifetime, - tx_start, - rx_halt, - ) - .await; + Launcher::run_with_graceful_shutdown(udp_tracker_container, spawner.bind_to, cookie_lifetime, tx_start, rx_halt) + .await; spawner }) } diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index 9bcde9003..abce9720a 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -5,19 +5,13 @@ use std::time::Duration; use derive_more::derive::Display; use derive_more::Constructor; -use tokio::sync::RwLock; use tokio::task::JoinHandle; -use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; -use super::banning::BanService; use super::spawner::Spawner; use super::{Server, UdpError}; use crate::bootstrap::jobs::Started; -use crate::core::announce_handler::AnnounceHandler; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::statistics::event::sender::Sender; -use crate::core::whitelist; +use crate::container::UdpTrackerContainer; use crate::servers::registar::{ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::Halted; use crate::servers::udp::server::launcher::Launcher; @@ -67,16 +61,10 @@ impl Server { /// # Panics /// /// It panics if unable to receive the bound socket address from service. - #[allow(clippy::too_many_arguments)] - #[instrument(skip(self, announce_handler, scrape_handler, whitelist_authorization, opt_stats_event_sender, ban_service, form), err, ret(Display, level = Level::INFO))] + #[instrument(skip(self, udp_tracker_container, form), err, ret(Display, level = Level::INFO))] pub async fn start( self, - core_config: Arc, - announce_handler: Arc, - scrape_handler: Arc, - whitelist_authorization: Arc, - opt_stats_event_sender: Arc>>, - ban_service: Arc>, + udp_tracker_container: Arc, form: ServiceRegistrationForm, cookie_lifetime: Duration, ) -> Result, std::io::Error> { @@ -86,17 +74,10 @@ impl Server { assert!(!tx_halt.is_closed(), "Halt channel for UDP tracker should be open"); // May need to wrap in a task to about a tokio bug. - let task = self.state.spawner.spawn_launcher( - core_config, - announce_handler, - scrape_handler, - whitelist_authorization, - opt_stats_event_sender, - ban_service, - cookie_lifetime, - tx_start, - rx_halt, - ); + let task = self + .state + .spawner + .spawn_launcher(udp_tracker_container, cookie_lifetime, tx_start, rx_halt); let local_addr = rx_start.await.expect("it should be able to start the service").address; diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index 0767d5f07..f6a1feb06 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -229,7 +229,7 @@ mod receiving_an_announce_request { logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; - let ban_service = env.ban_service.clone(); + let ban_service = env.udp_tracker_container.ban_service.clone(); let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_tracker_client) => udp_tracker_client, diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index b3a2670e8..af0b04e5c 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -2,18 +2,13 @@ use std::net::SocketAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; -use tokio::sync::RwLock; -use torrust_tracker_configuration::{Configuration, Core, UdpTracker, DEFAULT_TIMEOUT}; +use torrust_tracker_configuration::{Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; -use torrust_tracker_lib::core::announce_handler::AnnounceHandler; +use torrust_tracker_lib::container::UdpTrackerContainer; use torrust_tracker_lib::core::databases::Database; -use torrust_tracker_lib::core::scrape_handler::ScrapeHandler; -use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use torrust_tracker_lib::core::whitelist; use torrust_tracker_lib::servers::registar::Registar; -use torrust_tracker_lib::servers::udp::server::banning::BanService; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; use torrust_tracker_lib::servers::udp::server::Server; @@ -23,16 +18,12 @@ pub struct Environment where S: std::fmt::Debug + std::fmt::Display, { - pub core_config: Arc, - pub config: Arc, + pub udp_tracker_container: Arc, + pub database: Arc>, pub in_memory_torrent_repository: Arc, - pub announce_handler: Arc, - pub scrape_handler: Arc, - pub whitelist_authorization: Arc, - pub stats_event_sender: Arc>>, pub stats_repository: Arc, - pub ban_service: Arc>, + pub registar: Registar, pub server: Server, } @@ -55,25 +46,31 @@ impl Environment { let app_container = initialize_app_container(configuration); - let udp_tracker = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); + let udp_tracker_configurations = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); - let config = Arc::new(udp_tracker[0].clone()); + let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); - let bind_to = config.bind_address; + let bind_to = udp_tracker_config.bind_address; let server = Server::new(Spawner::new(bind_to)); - Self { - core_config: Arc::new(configuration.core.clone()), - config, - database: app_container.database.clone(), - in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), + let udp_tracker_container = Arc::new(UdpTrackerContainer { + udp_tracker_config: udp_tracker_config.clone(), + core_config: app_container.core_config.clone(), announce_handler: app_container.announce_handler.clone(), scrape_handler: app_container.scrape_handler.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), stats_event_sender: app_container.stats_event_sender.clone(), - stats_repository: app_container.stats_repository.clone(), ban_service: app_container.ban_service.clone(), + }); + + Self { + udp_tracker_container, + + database: app_container.database.clone(), + in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), + stats_repository: app_container.stats_repository.clone(), + registar: Registar::default(), server, } @@ -81,31 +78,19 @@ impl Environment { #[allow(dead_code)] pub async fn start(self) -> Environment { - let cookie_lifetime = self.config.cookie_lifetime; + let cookie_lifetime = self.udp_tracker_container.udp_tracker_config.cookie_lifetime; + Environment { - core_config: self.core_config.clone(), - config: self.config, + udp_tracker_container: self.udp_tracker_container.clone(), + database: self.database.clone(), in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), - announce_handler: self.announce_handler.clone(), - scrape_handler: self.scrape_handler.clone(), - whitelist_authorization: self.whitelist_authorization.clone(), - stats_event_sender: self.stats_event_sender.clone(), stats_repository: self.stats_repository.clone(), - ban_service: self.ban_service.clone(), + registar: self.registar.clone(), server: self .server - .start( - self.core_config, - self.announce_handler, - self.scrape_handler, - self.whitelist_authorization, - self.stats_event_sender, - self.ban_service, - self.registar.give_form(), - cookie_lifetime, - ) + .start(self.udp_tracker_container, self.registar.give_form(), cookie_lifetime) .await .unwrap(), } @@ -126,16 +111,12 @@ impl Environment { .expect("it should stop the environment within the timeout"); Environment { - core_config: self.core_config, - config: self.config, + udp_tracker_container: self.udp_tracker_container, + database: self.database, in_memory_torrent_repository: self.in_memory_torrent_repository, - announce_handler: self.announce_handler, - scrape_handler: self.scrape_handler, - whitelist_authorization: self.whitelist_authorization, - stats_event_sender: self.stats_event_sender, stats_repository: self.stats_repository, - ban_service: self.ban_service, + registar: Registar::default(), server: stopped.expect("it stop the udp tracker service"), } From a2bf1cd88a34deb8c6e5ea6852d6efd34dab4a0d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 29 Jan 2025 10:18:03 +0000 Subject: [PATCH 0674/1297] refactor: [torrust#1217] extract HttpTrackerContainer --- src/app.rs | 20 +++--- src/bootstrap/jobs/http_tracker.rs | 96 +++++------------------------ src/container.rs | 27 +++++++- src/servers/http/server.rs | 79 +++++------------------- src/servers/http/v1/routes.rs | 65 +++++++------------ src/servers/udp/server/processor.rs | 1 - tests/servers/http/environment.rs | 76 +++++++++-------------- tests/servers/http/v1/contract.rs | 16 +++-- 8 files changed, 127 insertions(+), 253 deletions(-) diff --git a/src/app.rs b/src/app.rs index e0f231611..617d75726 100644 --- a/src/app.rs +++ b/src/app.rs @@ -28,7 +28,7 @@ use torrust_tracker_configuration::Configuration; use tracing::instrument; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; -use crate::container::{AppContainer, UdpTrackerContainer}; +use crate::container::{AppContainer, HttpTrackerContainer, UdpTrackerContainer}; use crate::servers; use crate::servers::registar::Registar; @@ -80,6 +80,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> } else { let udp_tracker_config = Arc::new(udp_tracker_config.clone()); let udp_tracker_container = Arc::new(UdpTrackerContainer::from_app_container(&udp_tracker_config, app_container)); + jobs.push(udp_tracker::start_job(udp_tracker_container, registar.give_form()).await); } } @@ -90,18 +91,11 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> // Start the HTTP blocks if let Some(http_trackers) = &config.http_trackers { for http_tracker_config in http_trackers { - if let Some(job) = http_tracker::start_job( - http_tracker_config, - Arc::new(config.core.clone()), - app_container.announce_handler.clone(), - app_container.scrape_handler.clone(), - app_container.authentication_service.clone(), - app_container.whitelist_authorization.clone(), - app_container.stats_event_sender.clone(), - registar.give_form(), - servers::http::Version::V1, - ) - .await + let http_tracker_config = Arc::new(http_tracker_config.clone()); + let http_tracker_container = Arc::new(HttpTrackerContainer::from_app_container(&http_tracker_config, app_container)); + + if let Some(job) = + http_tracker::start_job(http_tracker_container, registar.give_form(), servers::http::Version::V1).await { jobs.push(job); }; diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index dc6ed6b60..83cc0ae02 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -15,15 +15,10 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; -use torrust_tracker_configuration::{Core, HttpTracker}; use tracing::instrument; use super::make_rust_tls; -use crate::core::announce_handler::AnnounceHandler; -use crate::core::authentication::service::AuthenticationService; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::statistics::event::sender::Sender; -use crate::core::{statistics, whitelist}; +use crate::container::HttpTrackerContainer; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::http::Version; use crate::servers::registar::ServiceRegistrationForm; @@ -36,83 +31,33 @@ use crate::servers::registar::ServiceRegistrationForm; /// # Panics /// /// It would panic if the `config::HttpTracker` struct would contain inappropriate values. -#[allow(clippy::too_many_arguments)] -#[instrument(skip( - config, - announce_handler, - scrape_handler, - authentication_service, - whitelist_authorization, - stats_event_sender, - form -))] +#[instrument(skip(http_tracker_container, form))] pub async fn start_job( - config: &HttpTracker, - core_config: Arc, - announce_handler: Arc, - scrape_handler: Arc, - authentication_service: Arc, - whitelist_authorization: Arc, - stats_event_sender: Arc>>, + http_tracker_container: Arc, form: ServiceRegistrationForm, version: Version, ) -> Option> { - let socket = config.bind_address; + let socket = http_tracker_container.http_tracker_config.bind_address; - let tls = make_rust_tls(&config.tsl_config) + let tls = make_rust_tls(&http_tracker_container.http_tracker_config.tsl_config) .await .map(|tls| tls.expect("it should have a valid http tracker tls configuration")); match version { - Version::V1 => Some( - start_v1( - socket, - tls, - core_config.clone(), - announce_handler.clone(), - scrape_handler.clone(), - authentication_service.clone(), - whitelist_authorization.clone(), - stats_event_sender.clone(), - form, - ) - .await, - ), + Version::V1 => Some(start_v1(socket, tls, http_tracker_container, form).await), } } -#[allow(clippy::too_many_arguments)] #[allow(clippy::async_yields_async)] -#[instrument(skip( - socket, - tls, - announce_handler, - scrape_handler, - whitelist_authorization, - stats_event_sender, - form -))] +#[instrument(skip(socket, tls, http_tracker_container, form))] async fn start_v1( socket: SocketAddr, tls: Option, - config: Arc, - announce_handler: Arc, - scrape_handler: Arc, - authentication_service: Arc, - whitelist_authorization: Arc, - stats_event_sender: Arc>>, + http_tracker_container: Arc, form: ServiceRegistrationForm, ) -> JoinHandle<()> { let server = HttpServer::new(Launcher::new(socket, tls)) - .start( - config, - announce_handler, - scrape_handler, - authentication_service, - whitelist_authorization, - stats_event_sender, - form, - ) + .start(http_tracker_container, form) .await .expect("it should be able to start to the http tracker"); @@ -137,6 +82,7 @@ mod tests { use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::http_tracker::start_job; + use crate::container::HttpTrackerContainer; use crate::servers::http::Version; use crate::servers::registar::Registar; @@ -144,26 +90,18 @@ mod tests { async fn it_should_start_http_tracker() { let cfg = Arc::new(ephemeral_public()); let http_tracker = cfg.http_trackers.clone().expect("missing HTTP tracker configuration"); - let config = &http_tracker[0]; + let http_tracker_config = Arc::new(http_tracker[0].clone()); initialize_global_services(&cfg); - let app_container = initialize_app_container(&cfg); + let app_container = Arc::new(initialize_app_container(&cfg)); + + let http_tracker_container = Arc::new(HttpTrackerContainer::from_app_container(&http_tracker_config, &app_container)); let version = Version::V1; - start_job( - config, - Arc::new(cfg.core.clone()), - app_container.announce_handler, - app_container.scrape_handler, - app_container.authentication_service, - app_container.whitelist_authorization, - app_container.stats_event_sender, - Registar::default().give_form(), - version, - ) - .await - .expect("it should be able to join to the http tracker start-job"); + start_job(http_tracker_container, Registar::default().give_form(), version) + .await + .expect("it should be able to join to the http tracker start-job"); } } diff --git a/src/container.rs b/src/container.rs index 1d137680e..ad1185d64 100644 --- a/src/container.rs +++ b/src/container.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use tokio::sync::RwLock; -use torrust_tracker_configuration::{Core, UdpTracker}; +use torrust_tracker_configuration::{Core, HttpTracker, UdpTracker}; use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::handler::KeysHandler; @@ -58,3 +58,28 @@ impl UdpTrackerContainer { } } } + +pub struct HttpTrackerContainer { + pub core_config: Arc, + pub http_tracker_config: Arc, + pub announce_handler: Arc, + pub scrape_handler: Arc, + pub whitelist_authorization: Arc, + pub stats_event_sender: Arc>>, + pub authentication_service: Arc, +} + +impl HttpTrackerContainer { + #[must_use] + pub fn from_app_container(http_tracker_config: &Arc, app_container: &Arc) -> Self { + Self { + http_tracker_config: http_tracker_config.clone(), + core_config: app_container.core_config.clone(), + announce_handler: app_container.announce_handler.clone(), + scrape_handler: app_container.scrape_handler.clone(), + whitelist_authorization: app_container.whitelist_authorization.clone(), + stats_event_sender: app_container.stats_event_sender.clone(), + authentication_service: app_container.authentication_service.clone(), + } + } +} diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 2792697b3..2355bedf9 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -7,15 +7,11 @@ use axum_server::Handle; use derive_more::Constructor; use futures::future::BoxFuture; use tokio::sync::oneshot::{Receiver, Sender}; -use torrust_tracker_configuration::Core; use tracing::instrument; use super::v1::routes::router; use crate::bootstrap::jobs::Started; -use crate::core::announce_handler::AnnounceHandler; -use crate::core::authentication::service::AuthenticationService; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::{statistics, whitelist}; +use crate::container::HttpTrackerContainer; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; use crate::servers::logging::STARTED_ON; @@ -46,25 +42,10 @@ pub struct Launcher { } impl Launcher { - #[allow(clippy::too_many_arguments)] - #[instrument(skip( - self, - announce_handler, - scrape_handler, - authentication_service, - whitelist_authorization, - stats_event_sender, - tx_start, - rx_halt - ))] + #[instrument(skip(self, http_tracker_container, tx_start, rx_halt))] fn start( &self, - config: Arc, - announce_handler: Arc, - scrape_handler: Arc, - authentication_service: Arc, - whitelist_authorization: Arc, - stats_event_sender: Arc>>, + http_tracker_container: Arc, tx_start: Sender, rx_halt: Receiver, ) -> BoxFuture<'static, ()> { @@ -84,15 +65,7 @@ impl Launcher { tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{}", address); - let app = router( - config, - announce_handler, - scrape_handler, - authentication_service, - whitelist_authorization, - stats_event_sender, - address, - ); + let app = router(http_tracker_container, address); let running = Box::pin(async { match tls { @@ -185,15 +158,9 @@ impl HttpServer { /// /// It would panic spawned HTTP server launcher cannot send the bound `SocketAddr` /// back to the main thread. - #[allow(clippy::too_many_arguments)] pub async fn start( self, - core_config: Arc, - announce_handler: Arc, - scrape_handler: Arc, - authentication_service: Arc, - whitelist_authorization: Arc, - stats_event_sender: Arc>>, + http_tracker_container: Arc, form: ServiceRegistrationForm, ) -> Result, Error> { let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); @@ -202,16 +169,7 @@ impl HttpServer { let launcher = self.state.launcher; let task = tokio::spawn(async move { - let server = launcher.start( - core_config, - announce_handler, - scrape_handler, - authentication_service, - whitelist_authorization, - stats_event_sender, - tx_start, - rx_halt, - ); + let server = launcher.start(http_tracker_container, tx_start, rx_halt); server.await; @@ -284,6 +242,7 @@ mod tests { use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::make_rust_tls; + use crate::container::HttpTrackerContainer; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::registar::Registar; @@ -293,30 +252,24 @@ mod tests { initialize_global_services(&cfg); - let app_container = initialize_app_container(&cfg); + let app_container = Arc::new(initialize_app_container(&cfg)); let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); - let config = &http_trackers[0]; - - let bind_to = config.bind_address; + let http_tracker_config = &http_trackers[0]; + let bind_to = http_tracker_config.bind_address; - let tls = make_rust_tls(&config.tsl_config) + let tls = make_rust_tls(&http_tracker_config.tsl_config) .await .map(|tls| tls.expect("tls config failed")); - let register = &Registar::default(); + let http_tracker_config = Arc::new(http_tracker_config.clone()); + let http_tracker_container = Arc::new(HttpTrackerContainer::from_app_container(&http_tracker_config, &app_container)); + let register = &Registar::default(); let stopped = HttpServer::new(Launcher::new(bind_to, tls)); + let started = stopped - .start( - Arc::new(cfg.core.clone()), - app_container.announce_handler, - app_container.scrape_handler, - app_container.authentication_service, - app_container.whitelist_authorization, - app_container.stats_event_sender, - register.give_form(), - ) + .start(http_tracker_container, register.give_form()) .await .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index f80760955..ed9aa05e6 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -10,7 +10,7 @@ use axum::routing::get; use axum::{BoxError, Router}; use axum_client_ip::SecureClientIpSource; use hyper::{Request, StatusCode}; -use torrust_tracker_configuration::{Core, DEFAULT_TIMEOUT}; +use torrust_tracker_configuration::DEFAULT_TIMEOUT; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; use tower_http::classify::ServerErrorsFailureClass; @@ -22,11 +22,7 @@ use tower_http::LatencyUnit; use tracing::{instrument, Level, Span}; use super::handlers::{announce, health_check, scrape}; -use crate::core::announce_handler::AnnounceHandler; -use crate::core::authentication::service::AuthenticationService; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::statistics::event::sender::Sender; -use crate::core::whitelist; +use crate::container::HttpTrackerContainer; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; use crate::servers::logging::Latency; @@ -34,25 +30,8 @@ use crate::servers::logging::Latency; /// /// > **NOTICE**: it's added a layer to get the client IP from the connection /// > info. The tracker could use the connection info to get the client IP. -#[allow(clippy::too_many_arguments)] -#[allow(clippy::needless_pass_by_value)] -#[instrument(skip( - announce_handler, - scrape_handler, - authentication_service, - whitelist_authorization, - stats_event_sender, - server_socket_addr -))] -pub fn router( - core_config: Arc, - announce_handler: Arc, - scrape_handler: Arc, - authentication_service: Arc, - whitelist_authorization: Arc, - stats_event_sender: Arc>>, - server_socket_addr: SocketAddr, -) -> Router { +#[instrument(skip(http_tracker_container, server_socket_addr))] +pub fn router(http_tracker_container: Arc, server_socket_addr: SocketAddr) -> Router { Router::new() // Health check .route("/health_check", get(health_check::handler)) @@ -60,40 +39,40 @@ pub fn router( .route( "/announce", get(announce::handle_without_key).with_state(( - core_config.clone(), - announce_handler.clone(), - authentication_service.clone(), - whitelist_authorization.clone(), - stats_event_sender.clone(), + http_tracker_container.core_config.clone(), + http_tracker_container.announce_handler.clone(), + http_tracker_container.authentication_service.clone(), + http_tracker_container.whitelist_authorization.clone(), + http_tracker_container.stats_event_sender.clone(), )), ) .route( "/announce/{key}", get(announce::handle_with_key).with_state(( - core_config.clone(), - announce_handler.clone(), - authentication_service.clone(), - whitelist_authorization.clone(), - stats_event_sender.clone(), + http_tracker_container.core_config.clone(), + http_tracker_container.announce_handler.clone(), + http_tracker_container.authentication_service.clone(), + http_tracker_container.whitelist_authorization.clone(), + http_tracker_container.stats_event_sender.clone(), )), ) // Scrape request .route( "/scrape", get(scrape::handle_without_key).with_state(( - core_config.clone(), - scrape_handler.clone(), - authentication_service.clone(), - stats_event_sender.clone(), + http_tracker_container.core_config.clone(), + http_tracker_container.scrape_handler.clone(), + http_tracker_container.authentication_service.clone(), + http_tracker_container.stats_event_sender.clone(), )), ) .route( "/scrape/{key}", get(scrape::handle_with_key).with_state(( - core_config.clone(), - scrape_handler.clone(), - authentication_service.clone(), - stats_event_sender.clone(), + http_tracker_container.core_config.clone(), + http_tracker_container.scrape_handler.clone(), + http_tracker_container.authentication_service.clone(), + http_tracker_container.stats_event_sender.clone(), )), ) // Add extension to get the client IP from the connection info diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 86a16d2d4..e2beb2377 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -21,7 +21,6 @@ pub struct Processor { } impl Processor { - #[allow(clippy::too_many_arguments)] pub fn new(socket: Arc, udp_tracker_container: Arc, cookie_lifetime: f64) -> Self { Self { socket, diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 5bf1d1c65..07ff2bc8c 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -2,36 +2,28 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; -use torrust_tracker_configuration::{Configuration, Core, HttpTracker}; +use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; -use torrust_tracker_lib::core::announce_handler::AnnounceHandler; +use torrust_tracker_lib::container::HttpTrackerContainer; use torrust_tracker_lib::core::authentication::handler::KeysHandler; -use torrust_tracker_lib::core::authentication::service::AuthenticationService; use torrust_tracker_lib::core::databases::Database; -use torrust_tracker_lib::core::scrape_handler::ScrapeHandler; -use torrust_tracker_lib::core::statistics::event::sender::Sender; use torrust_tracker_lib::core::statistics::repository::Repository; use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use torrust_tracker_lib::core::whitelist; use torrust_tracker_lib::core::whitelist::manager::WhitelistManager; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; pub struct Environment { - pub core_config: Arc, - pub http_tracker_config: Arc, + pub http_tracker_container: Arc, + pub database: Arc>, - pub announce_handler: Arc, - pub scrape_handler: Arc, pub in_memory_torrent_repository: Arc, pub keys_handler: Arc, - pub authentication_service: Arc, - pub stats_event_sender: Arc>>, pub stats_repository: Arc, - pub whitelist_authorization: Arc, pub whitelist_manager: Arc, + pub registar: Registar, pub server: HttpServer, } @@ -54,28 +46,33 @@ impl Environment { .http_trackers .clone() .expect("missing HTTP tracker configuration"); + let http_tracker_config = Arc::new(http_tracker[0].clone()); - let config = Arc::new(http_tracker[0].clone()); - - let bind_to = config.bind_address; + let bind_to = http_tracker_config.bind_address; - let tls = block_on(make_rust_tls(&config.tsl_config)).map(|tls| tls.expect("tls config failed")); + let tls = block_on(make_rust_tls(&http_tracker_config.tsl_config)).map(|tls| tls.expect("tls config failed")); let server = HttpServer::new(Launcher::new(bind_to, tls)); - Self { - http_tracker_config: config, - core_config: Arc::new(configuration.core.clone()), - database: app_container.database.clone(), + let http_tracker_container = Arc::new(HttpTrackerContainer { + core_config: app_container.core_config.clone(), + http_tracker_config: http_tracker_config.clone(), announce_handler: app_container.announce_handler.clone(), scrape_handler: app_container.scrape_handler.clone(), + whitelist_authorization: app_container.whitelist_authorization.clone(), + stats_event_sender: app_container.stats_event_sender.clone(), + authentication_service: app_container.authentication_service.clone(), + }); + + Self { + http_tracker_container, + + database: app_container.database.clone(), in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), keys_handler: app_container.keys_handler.clone(), - authentication_service: app_container.authentication_service.clone(), - stats_event_sender: app_container.stats_event_sender.clone(), stats_repository: app_container.stats_repository.clone(), - whitelist_authorization: app_container.whitelist_authorization.clone(), whitelist_manager: app_container.whitelist_manager.clone(), + registar: Registar::default(), server, } @@ -84,30 +81,18 @@ impl Environment { #[allow(dead_code)] pub async fn start(self) -> Environment { Environment { - http_tracker_config: self.http_tracker_config, - core_config: self.core_config.clone(), + http_tracker_container: self.http_tracker_container.clone(), + database: self.database.clone(), - announce_handler: self.announce_handler.clone(), - scrape_handler: self.scrape_handler.clone(), in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), keys_handler: self.keys_handler.clone(), - authentication_service: self.authentication_service.clone(), - whitelist_authorization: self.whitelist_authorization.clone(), - stats_event_sender: self.stats_event_sender.clone(), stats_repository: self.stats_repository.clone(), whitelist_manager: self.whitelist_manager.clone(), + registar: self.registar.clone(), server: self .server - .start( - self.core_config, - self.announce_handler, - self.scrape_handler, - self.authentication_service, - self.whitelist_authorization, - self.stats_event_sender, - self.registar.give_form(), - ) + .start(self.http_tracker_container, self.registar.give_form()) .await .unwrap(), } @@ -121,20 +106,15 @@ impl Environment { pub async fn stop(self) -> Environment { Environment { - http_tracker_config: self.http_tracker_config, - core_config: self.core_config, + http_tracker_container: self.http_tracker_container, + database: self.database, - announce_handler: self.announce_handler, - scrape_handler: self.scrape_handler, in_memory_torrent_repository: self.in_memory_torrent_repository, keys_handler: self.keys_handler, - authentication_service: self.authentication_service, - whitelist_authorization: self.whitelist_authorization, - stats_event_sender: self.stats_event_sender, stats_repository: self.stats_repository, whitelist_manager: self.whitelist_manager, - registar: Registar::default(), + registar: Registar::default(), server: self.server.stop().await.unwrap(), } } diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 33faf8578..f434467fc 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -449,7 +449,7 @@ mod for_all_config_modes { ) .await; - let announce_policy = env.core_config.announce_policy; + let announce_policy = env.http_tracker_container.core_config.announce_policy; assert_announce_response( response, @@ -490,7 +490,7 @@ mod for_all_config_modes { ) .await; - let announce_policy = env.core_config.announce_policy; + let announce_policy = env.http_tracker_container.core_config.announce_policy; // It should only contain the previously announced peer assert_announce_response( @@ -543,7 +543,7 @@ mod for_all_config_modes { ) .await; - let announce_policy = env.core_config.announce_policy; + let announce_policy = env.http_tracker_container.core_config.announce_policy; // The newly announced peer is not included on the response peer list, // but all the previously announced peers should be included regardless the IP version they are using. @@ -872,7 +872,10 @@ mod for_all_config_modes { let peers = env.in_memory_torrent_repository.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; - assert_eq!(peer_addr.ip(), env.core_config.net.external_ip.unwrap()); + assert_eq!( + peer_addr.ip(), + env.http_tracker_container.core_config.net.external_ip.unwrap() + ); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); env.stop().await; @@ -914,7 +917,10 @@ mod for_all_config_modes { let peers = env.in_memory_torrent_repository.get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; - assert_eq!(peer_addr.ip(), env.core_config.net.external_ip.unwrap()); + assert_eq!( + peer_addr.ip(), + env.http_tracker_container.core_config.net.external_ip.unwrap() + ); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); env.stop().await; From 66b2b5601182aa4ac8eafa767679de919bc2e665 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 29 Jan 2025 11:00:07 +0000 Subject: [PATCH 0675/1297] refactor: [torrust#1217] extract HttpApiContainer --- src/app.rs | 19 +--- src/bootstrap/jobs/tracker_apis.rs | 105 ++++-------------- src/container.rs | 29 ++++- src/servers/apis/routes.rs | 37 +----- src/servers/apis/server.rs | 87 +++------------ .../apis/v1/context/auth_key/routes.rs | 7 +- src/servers/apis/v1/context/stats/routes.rs | 21 ++-- src/servers/apis/v1/context/torrent/routes.rs | 4 +- src/servers/apis/v1/routes.rs | 35 +----- tests/servers/api/environment.rs | 85 ++++++-------- .../api/v1/contract/context/auth_key.rs | 13 ++- .../api/v1/contract/context/whitelist.rs | 46 ++++++-- 12 files changed, 174 insertions(+), 314 deletions(-) diff --git a/src/app.rs b/src/app.rs index 617d75726..13bdc904a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -28,7 +28,7 @@ use torrust_tracker_configuration::Configuration; use tracing::instrument; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; -use crate::container::{AppContainer, HttpTrackerContainer, UdpTrackerContainer}; +use crate::container::{AppContainer, HttpApiContainer, HttpTrackerContainer, UdpTrackerContainer}; use crate::servers; use crate::servers::registar::Registar; @@ -106,19 +106,10 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> // Start HTTP API if let Some(http_api_config) = &config.http_api { - if let Some(job) = tracker_apis::start_job( - http_api_config, - app_container.in_memory_torrent_repository.clone(), - app_container.keys_handler.clone(), - app_container.whitelist_manager.clone(), - app_container.ban_service.clone(), - app_container.stats_event_sender.clone(), - app_container.stats_repository.clone(), - registar.give_form(), - servers::apis::Version::V1, - ) - .await - { + let http_api_config = Arc::new(http_api_config.clone()); + let http_api_container = Arc::new(HttpApiContainer::from_app_container(&http_api_config, app_container)); + + if let Some(job) = tracker_apis::start_job(http_api_container, registar.give_form(), servers::apis::Version::V1).await { jobs.push(job); }; } else { diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index ce6f3912c..cee6cbae2 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -24,21 +24,15 @@ use std::net::SocketAddr; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; -use tokio::sync::RwLock; use tokio::task::JoinHandle; -use torrust_tracker_configuration::{AccessTokens, HttpApi}; +use torrust_tracker_configuration::AccessTokens; use tracing::instrument; use super::make_rust_tls; -use crate::core::authentication::handler::KeysHandler; -use crate::core::statistics::event::sender::Sender; -use crate::core::statistics::repository::Repository; -use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::core::whitelist::manager::WhitelistManager; +use crate::container::HttpApiContainer; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::apis::Version; use crate::servers::registar::ServiceRegistrationForm; -use crate::servers::udp::server::banning::BanService; /// This is the message that the "launcher" spawned task sends to the main /// application process to notify the API server was successfully started. @@ -60,90 +54,36 @@ pub struct ApiServerJobStarted(); /// It would panic if unable to send the `ApiServerJobStarted` notice. /// /// -#[allow(clippy::too_many_arguments)] -#[instrument(skip( - config, - keys_handler, - whitelist_manager, - ban_service, - stats_event_sender, - stats_repository, - form -))] +#[instrument(skip(http_api_container, form))] pub async fn start_job( - config: &HttpApi, - in_memory_torrent_repository: Arc, - keys_handler: Arc, - whitelist_manager: Arc, - ban_service: Arc>, - stats_event_sender: Arc>>, - stats_repository: Arc, + http_api_container: Arc, form: ServiceRegistrationForm, version: Version, ) -> Option> { - let bind_to = config.bind_address; + let bind_to = http_api_container.http_api_config.bind_address; - let tls = make_rust_tls(&config.tsl_config) + let tls = make_rust_tls(&http_api_container.http_api_config.tsl_config) .await .map(|tls| tls.expect("it should have a valid tracker api tls configuration")); - let access_tokens = Arc::new(config.access_tokens.clone()); + let access_tokens = Arc::new(http_api_container.http_api_config.access_tokens.clone()); match version { - Version::V1 => Some( - start_v1( - bind_to, - tls, - in_memory_torrent_repository.clone(), - keys_handler.clone(), - whitelist_manager.clone(), - ban_service.clone(), - stats_event_sender.clone(), - stats_repository.clone(), - form, - access_tokens, - ) - .await, - ), + Version::V1 => Some(start_v1(bind_to, tls, http_api_container, form, access_tokens).await), } } #[allow(clippy::async_yields_async)] -#[allow(clippy::too_many_arguments)] -#[instrument(skip( - socket, - tls, - keys_handler, - whitelist_manager, - ban_service, - stats_event_sender, - stats_repository, - form, - access_tokens -))] +#[instrument(skip(socket, tls, http_api_container, form, access_tokens))] async fn start_v1( socket: SocketAddr, tls: Option, - in_memory_torrent_repository: Arc, - keys_handler: Arc, - whitelist_manager: Arc, - ban_service: Arc>, - stats_event_sender: Arc>>, - stats_repository: Arc, + http_api_container: Arc, form: ServiceRegistrationForm, access_tokens: Arc, ) -> JoinHandle<()> { let server = ApiServer::new(Launcher::new(socket, tls)) - .start( - in_memory_torrent_repository, - keys_handler, - whitelist_manager, - stats_event_sender, - stats_repository, - ban_service, - form, - access_tokens, - ) + .start(http_api_container, form, access_tokens) .await .expect("it should be able to start to the tracker api"); @@ -161,32 +101,25 @@ mod tests { use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::tracker_apis::start_job; + use crate::container::HttpApiContainer; use crate::servers::apis::Version; use crate::servers::registar::Registar; #[tokio::test] async fn it_should_start_http_tracker() { let cfg = Arc::new(ephemeral_public()); - let config = &cfg.http_api.clone().unwrap(); + let http_api_config = Arc::new(cfg.http_api.clone().unwrap()); initialize_global_services(&cfg); - let app_container = initialize_app_container(&cfg); + let app_container = Arc::new(initialize_app_container(&cfg)); + + let http_api_container = Arc::new(HttpApiContainer::from_app_container(&http_api_config, &app_container)); let version = Version::V1; - start_job( - config, - app_container.in_memory_torrent_repository, - app_container.keys_handler, - app_container.whitelist_manager, - app_container.ban_service, - app_container.stats_event_sender, - app_container.stats_repository, - Registar::default().give_form(), - version, - ) - .await - .expect("it should be able to join to the tracker api start-job"); + start_job(http_api_container, Registar::default().give_form(), version) + .await + .expect("it should be able to join to the tracker api start-job"); } } diff --git a/src/container.rs b/src/container.rs index ad1185d64..1a2a029ee 100644 --- a/src/container.rs +++ b/src/container.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use tokio::sync::RwLock; -use torrust_tracker_configuration::{Core, HttpTracker, UdpTracker}; +use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; use crate::core::announce_handler::AnnounceHandler; use crate::core::authentication::handler::KeysHandler; @@ -83,3 +83,30 @@ impl HttpTrackerContainer { } } } + +pub struct HttpApiContainer { + pub core_config: Arc, + pub http_api_config: Arc, + pub in_memory_torrent_repository: Arc, + pub keys_handler: Arc, + pub whitelist_manager: Arc, + pub ban_service: Arc>, + pub stats_event_sender: Arc>>, + pub stats_repository: Arc, +} + +impl HttpApiContainer { + #[must_use] + pub fn from_app_container(http_api_config: &Arc, app_container: &Arc) -> Self { + Self { + http_api_config: http_api_config.clone(), + core_config: app_container.core_config.clone(), + in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), + keys_handler: app_container.keys_handler.clone(), + whitelist_manager: app_container.whitelist_manager.clone(), + ban_service: app_container.ban_service.clone(), + stats_event_sender: app_container.stats_event_sender.clone(), + stats_repository: app_container.stats_repository.clone(), + } + } +} diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 92ecb067d..137975259 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -15,7 +15,6 @@ use axum::response::Response; use axum::routing::get; use axum::{middleware, BoxError, Router}; use hyper::{Request, StatusCode}; -use tokio::sync::RwLock; use torrust_tracker_configuration::{AccessTokens, DEFAULT_TIMEOUT}; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; @@ -30,33 +29,14 @@ use tracing::{instrument, Level, Span}; use super::v1; use super::v1::context::health_check::handlers::health_check_handler; use super::v1::middlewares::auth::State; -use crate::core::authentication::handler::KeysHandler; -use crate::core::statistics::event::sender::Sender; -use crate::core::statistics::repository::Repository; -use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::core::whitelist::manager::WhitelistManager; +use crate::container::HttpApiContainer; use crate::servers::apis::API_LOG_TARGET; use crate::servers::logging::Latency; -use crate::servers::udp::server::banning::BanService; /// Add all API routes to the router. -#[allow(clippy::too_many_arguments)] -#[allow(clippy::needless_pass_by_value)] -#[instrument(skip( - keys_handler, - whitelist_manager, - ban_service, - stats_event_sender, - stats_repository, - access_tokens -))] +#[instrument(skip(http_api_container, access_tokens))] pub fn router( - in_memory_torrent_repository: Arc, - keys_handler: Arc, - whitelist_manager: Arc, - ban_service: Arc>, - stats_event_sender: Arc>>, - stats_repository: Arc, + http_api_container: Arc, access_tokens: Arc, server_socket_addr: SocketAddr, ) -> Router { @@ -64,16 +44,7 @@ pub fn router( let api_url_prefix = "/api"; - let router = v1::routes::add( - api_url_prefix, - router, - &in_memory_torrent_repository.clone(), - &keys_handler.clone(), - &whitelist_manager.clone(), - ban_service.clone(), - stats_event_sender.clone(), - stats_repository.clone(), - ); + let router = v1::routes::add(api_url_prefix, router, &http_api_container); let state = State { access_tokens }; diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index b3621de0e..7388a1851 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -33,23 +33,17 @@ use derive_more::Constructor; use futures::future::BoxFuture; use thiserror::Error; use tokio::sync::oneshot::{Receiver, Sender}; -use tokio::sync::RwLock; use torrust_tracker_configuration::AccessTokens; use tracing::{instrument, Level}; use super::routes::router; use crate::bootstrap::jobs::Started; -use crate::core::authentication::handler::KeysHandler; -use crate::core::statistics; -use crate::core::statistics::repository::Repository; -use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::core::whitelist::manager::WhitelistManager; +use crate::container::HttpApiContainer; use crate::servers::apis::API_LOG_TARGET; use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::logging::STARTED_ON; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{graceful_shutdown, Halted}; -use crate::servers::udp::server::banning::BanService; /// Errors that can occur when starting or stopping the API server. #[derive(Debug, Error)] @@ -128,16 +122,10 @@ impl ApiServer { /// # Panics /// /// It would panic if the bound socket address cannot be sent back to this starter. - #[allow(clippy::too_many_arguments)] - #[instrument(skip(self, in_memory_torrent_repository, keys_handler, whitelist_manager, stats_event_sender, ban_service, stats_repository, form, access_tokens), err, ret(Display, level = Level::INFO))] + #[instrument(skip(self, http_api_container, form, access_tokens), err, ret(Display, level = Level::INFO))] pub async fn start( self, - in_memory_torrent_repository: Arc, - keys_handler: Arc, - whitelist_manager: Arc, - stats_event_sender: Arc>>, - stats_repository: Arc, - ban_service: Arc>, + http_api_container: Arc, form: ServiceRegistrationForm, access_tokens: Arc, ) -> Result, Error> { @@ -149,19 +137,7 @@ impl ApiServer { let task = tokio::spawn(async move { tracing::debug!(target: API_LOG_TARGET, "Starting with launcher in spawned task ..."); - let _task = launcher - .start( - in_memory_torrent_repository, - keys_handler, - whitelist_manager, - ban_service, - stats_event_sender, - stats_repository, - access_tokens, - tx_start, - rx_halt, - ) - .await; + let _task = launcher.start(http_api_container, access_tokens, tx_start, rx_halt).await; tracing::debug!(target: API_LOG_TARGET, "Started with launcher in spawned task"); @@ -259,26 +235,10 @@ impl Launcher { /// /// Will panic if unable to bind to the socket, or unable to get the address of the bound socket. /// Will also panic if unable to send message regarding the bound socket address. - #[allow(clippy::too_many_arguments)] - #[instrument(skip( - self, - keys_handler, - whitelist_manager, - ban_service, - stats_event_sender, - stats_repository, - access_tokens, - tx_start, - rx_halt - ))] + #[instrument(skip(self, http_api_container, access_tokens, tx_start, rx_halt))] pub fn start( &self, - in_memory_torrent_repository: Arc, - keys_handler: Arc, - whitelist_manager: Arc, - ban_service: Arc>, - stats_event_sender: Arc>>, - stats_repository: Arc, + http_api_container: Arc, access_tokens: Arc, tx_start: Sender, rx_halt: Receiver, @@ -286,16 +246,7 @@ impl Launcher { let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); - let router = router( - in_memory_torrent_repository, - keys_handler, - whitelist_manager, - ban_service, - stats_event_sender, - stats_repository, - access_tokens, - address, - ); + let router = router(http_api_container, access_tokens, address); let handle = Handle::new(); @@ -347,41 +298,35 @@ mod tests { use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::make_rust_tls; + use crate::container::HttpApiContainer; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::registar::Registar; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_public()); - let config = &cfg.http_api.clone().unwrap(); + let http_api_config = Arc::new(cfg.http_api.clone().unwrap()); initialize_global_services(&cfg); - let app_container = initialize_app_container(&cfg); + let app_container = Arc::new(initialize_app_container(&cfg)); - let bind_to = config.bind_address; + let bind_to = http_api_config.bind_address; - let tls = make_rust_tls(&config.tsl_config) + let tls = make_rust_tls(&http_api_config.tsl_config) .await .map(|tls| tls.expect("tls config failed")); - let access_tokens = Arc::new(config.access_tokens.clone()); + let access_tokens = Arc::new(http_api_config.access_tokens.clone()); let stopped = ApiServer::new(Launcher::new(bind_to, tls)); let register = &Registar::default(); + let http_api_container = Arc::new(HttpApiContainer::from_app_container(&http_api_config, &app_container)); + let started = stopped - .start( - app_container.in_memory_torrent_repository, - app_container.keys_handler, - app_container.whitelist_manager, - app_container.stats_event_sender, - app_container.stats_repository, - app_container.ban_service, - register.give_form(), - access_tokens, - ) + .start(http_api_container, register.give_form(), access_tokens) .await .expect("it should start the server"); let stopped = started.stop().await.expect("it should stop the server"); diff --git a/src/servers/apis/v1/context/auth_key/routes.rs b/src/servers/apis/v1/context/auth_key/routes.rs index 45aeb02ec..ee9f3252c 100644 --- a/src/servers/apis/v1/context/auth_key/routes.rs +++ b/src/servers/apis/v1/context/auth_key/routes.rs @@ -15,7 +15,7 @@ use super::handlers::{add_auth_key_handler, delete_auth_key_handler, generate_au use crate::core::authentication::handler::KeysHandler; /// It adds the routes to the router for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. -pub fn add(prefix: &str, router: Router, keys_handler: Arc) -> Router { +pub fn add(prefix: &str, router: Router, keys_handler: &Arc) -> Router { // Keys router .route( @@ -38,5 +38,8 @@ pub fn add(prefix: &str, router: Router, keys_handler: Arc) -> Rout &format!("{prefix}/keys/reload"), get(reload_keys_handler).with_state(keys_handler.clone()), ) - .route(&format!("{prefix}/keys"), post(add_auth_key_handler).with_state(keys_handler)) + .route( + &format!("{prefix}/keys"), + post(add_auth_key_handler).with_state(keys_handler.clone()), + ) } diff --git a/src/servers/apis/v1/context/stats/routes.rs b/src/servers/apis/v1/context/stats/routes.rs index 083c72b10..4c80f110d 100644 --- a/src/servers/apis/v1/context/stats/routes.rs +++ b/src/servers/apis/v1/context/stats/routes.rs @@ -7,25 +7,18 @@ use std::sync::Arc; use axum::routing::get; use axum::Router; -use tokio::sync::RwLock; use super::handlers::get_stats_handler; -use crate::core::statistics::event::sender::Sender; -use crate::core::statistics::repository::Repository; -use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::servers::udp::server::banning::BanService; +use crate::container::HttpApiContainer; /// It adds the routes to the router for the [`stats`](crate::servers::apis::v1::context::stats) API context. -pub fn add( - prefix: &str, - router: Router, - in_memory_torrent_repository: Arc, - ban_service: Arc>, - _stats_event_sender: Arc>>, - stats_repository: Arc, -) -> Router { +pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { router.route( &format!("{prefix}/stats"), - get(get_stats_handler).with_state((in_memory_torrent_repository, ban_service, stats_repository)), + get(get_stats_handler).with_state(( + http_api_container.in_memory_torrent_repository.clone(), + http_api_container.ban_service.clone(), + http_api_container.stats_repository.clone(), + )), ) } diff --git a/src/servers/apis/v1/context/torrent/routes.rs b/src/servers/apis/v1/context/torrent/routes.rs index dc66a1753..3ea8c639c 100644 --- a/src/servers/apis/v1/context/torrent/routes.rs +++ b/src/servers/apis/v1/context/torrent/routes.rs @@ -13,7 +13,7 @@ use super::handlers::{get_torrent_handler, get_torrents_handler}; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; /// It adds the routes to the router for the [`torrent`](crate::servers::apis::v1::context::torrent) API context. -pub fn add(prefix: &str, router: Router, in_memory_torrent_repository: Arc) -> Router { +pub fn add(prefix: &str, router: Router, in_memory_torrent_repository: &Arc) -> Router { // Torrents router .route( @@ -22,6 +22,6 @@ pub fn add(prefix: &str, router: Router, in_memory_torrent_repository: Arc, - keys_handler: &Arc, - whitelist_manager: &Arc, - ban_service: Arc>, - stats_event_sender: Arc>>, - stats_repository: Arc, -) -> Router { +pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { let v1_prefix = format!("{prefix}/v1"); - let router = auth_key::routes::add(&v1_prefix, router, keys_handler.clone()); - let router = stats::routes::add( - &v1_prefix, - router, - in_memory_torrent_repository.clone(), - ban_service, - stats_event_sender, - stats_repository, - ); - let router = whitelist::routes::add(&v1_prefix, router, whitelist_manager); + let router = auth_key::routes::add(&v1_prefix, router, &http_api_container.keys_handler.clone()); + let router = stats::routes::add(&v1_prefix, router, http_api_container); + let router = whitelist::routes::add(&v1_prefix, router, &http_api_container.whitelist_manager); - torrent::routes::add(&v1_prefix, router, in_memory_torrent_repository.clone()) + torrent::routes::add(&v1_prefix, router, &http_api_container.in_memory_torrent_repository.clone()) } diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 66018032e..297e169d4 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -3,36 +3,26 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use futures::executor::block_on; -use tokio::sync::RwLock; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; -use torrust_tracker_configuration::{Configuration, HttpApi}; +use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; -use torrust_tracker_lib::core::authentication::handler::KeysHandler; +use torrust_tracker_lib::container::HttpApiContainer; use torrust_tracker_lib::core::authentication::service::AuthenticationService; use torrust_tracker_lib::core::databases::Database; -use torrust_tracker_lib::core::statistics::event::sender::Sender; -use torrust_tracker_lib::core::statistics::repository::Repository; -use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use torrust_tracker_lib::core::whitelist::manager::WhitelistManager; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; -use torrust_tracker_lib::servers::udp::server::banning::BanService; use torrust_tracker_primitives::peer; pub struct Environment where S: std::fmt::Debug + std::fmt::Display, { - pub config: Arc, + pub http_api_container: Arc, + pub database: Arc>, - pub in_memory_torrent_repository: Arc, - pub keys_handler: Arc, pub authentication_service: Arc, - pub stats_event_sender: Arc>>, - pub stats_repository: Arc, - pub whitelist_manager: Arc, - pub ban_service: Arc>, + pub registar: Registar, pub server: ApiServer, } @@ -43,7 +33,10 @@ where { /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let () = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); + let () = self + .http_api_container + .in_memory_torrent_repository + .upsert_peer(info_hash, peer); } } @@ -53,55 +46,49 @@ impl Environment { let app_container = initialize_app_container(configuration); - let config = Arc::new(configuration.http_api.clone().expect("missing API configuration")); + let http_api_config = Arc::new(configuration.http_api.clone().expect("missing API configuration")); - let bind_to = config.bind_address; + let bind_to = http_api_config.bind_address; - let tls = block_on(make_rust_tls(&config.tsl_config)).map(|tls| tls.expect("tls config failed")); + let tls = block_on(make_rust_tls(&http_api_config.tsl_config)).map(|tls| tls.expect("tls config failed")); let server = ApiServer::new(Launcher::new(bind_to, tls)); - Self { - config, - database: app_container.database.clone(), + let http_api_container = Arc::new(HttpApiContainer { + http_api_config: http_api_config.clone(), + core_config: app_container.core_config.clone(), in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), keys_handler: app_container.keys_handler.clone(), - authentication_service: app_container.authentication_service.clone(), - stats_event_sender: app_container.stats_event_sender.clone(), - stats_repository: app_container.stats_repository.clone(), whitelist_manager: app_container.whitelist_manager.clone(), ban_service: app_container.ban_service.clone(), + stats_event_sender: app_container.stats_event_sender.clone(), + stats_repository: app_container.stats_repository.clone(), + }); + + Self { + http_api_container, + + database: app_container.database.clone(), + authentication_service: app_container.authentication_service.clone(), + registar: Registar::default(), server, } } pub async fn start(self) -> Environment { - let access_tokens = Arc::new(self.config.access_tokens.clone()); + let access_tokens = Arc::new(self.http_api_container.http_api_config.access_tokens.clone()); Environment { - config: self.config, + http_api_container: self.http_api_container.clone(), + database: self.database.clone(), - in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), - keys_handler: self.keys_handler.clone(), authentication_service: self.authentication_service.clone(), - stats_event_sender: self.stats_event_sender.clone(), - stats_repository: self.stats_repository.clone(), - whitelist_manager: self.whitelist_manager.clone(), - ban_service: self.ban_service.clone(), + registar: self.registar.clone(), server: self .server - .start( - self.in_memory_torrent_repository, - self.keys_handler, - self.whitelist_manager, - self.stats_event_sender, - self.stats_repository, - self.ban_service, - self.registar.give_form(), - access_tokens, - ) + .start(self.http_api_container, self.registar.give_form(), access_tokens) .await .unwrap(), } @@ -115,15 +102,11 @@ impl Environment { pub async fn stop(self) -> Environment { Environment { - config: self.config, + http_api_container: self.http_api_container, + database: self.database, - in_memory_torrent_repository: self.in_memory_torrent_repository, - keys_handler: self.keys_handler, authentication_service: self.authentication_service, - stats_event_sender: self.stats_event_sender, - stats_repository: self.stats_repository, - whitelist_manager: self.whitelist_manager, - ban_service: self.ban_service, + registar: Registar::default(), server: self.server.stop().await.unwrap(), } @@ -134,7 +117,7 @@ impl Environment { ConnectionInfo { origin, - api_token: self.config.access_tokens.get("admin").cloned(), + api_token: self.http_api_container.http_api_config.access_tokens.get("admin").cloned(), } } diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 3b7d2d6ba..3242c3ccc 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -158,6 +158,7 @@ async fn should_allow_deleting_an_auth_key() { let seconds_valid = 60; let auth_key = env + .http_api_container .keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await @@ -292,6 +293,7 @@ async fn should_fail_when_the_auth_key_cannot_be_deleted() { let seconds_valid = 60; let auth_key = env + .http_api_container .keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await @@ -325,6 +327,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { // Generate new auth key let auth_key = env + .http_api_container .keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await @@ -345,6 +348,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { // Generate new auth key let auth_key = env + .http_api_container .keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await @@ -373,7 +377,8 @@ async fn should_allow_reloading_keys() { let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - env.keys_handler + env.http_api_container + .keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -398,7 +403,8 @@ async fn should_fail_when_keys_cannot_be_reloaded() { let request_id = Uuid::new_v4(); let seconds_valid = 60; - env.keys_handler + env.http_api_container + .keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -426,7 +432,8 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - env.keys_handler + env.http_api_container + .keys_handler .generate_auth_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index 78850d3bf..3f8271e40 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -31,7 +31,8 @@ async fn should_allow_whitelisting_a_torrent() { assert_ok(response).await; assert!( - env.whitelist_manager + env.http_api_container + .whitelist_manager .is_info_hash_whitelisted(&InfoHash::from_str(&info_hash).unwrap()) .await ); @@ -167,7 +168,11 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.http_api_container + .whitelist_manager + .add_torrent_to_whitelist(&info_hash) + .await + .unwrap(); let request_id = Uuid::new_v4(); @@ -176,7 +181,12 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { .await; assert_ok(response).await; - assert!(!env.whitelist_manager.is_info_hash_whitelisted(&info_hash).await); + assert!( + !env.http_api_container + .whitelist_manager + .is_info_hash_whitelisted(&info_hash) + .await + ); env.stop().await; } @@ -237,7 +247,11 @@ async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.http_api_container + .whitelist_manager + .add_torrent_to_whitelist(&info_hash) + .await + .unwrap(); force_database_error(&env.database); @@ -266,7 +280,11 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.http_api_container + .whitelist_manager + .add_torrent_to_whitelist(&info_hash) + .await + .unwrap(); let request_id = Uuid::new_v4(); @@ -281,7 +299,11 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica "Expected logs to contain: ERROR ... API ... request_id={request_id}" ); - env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.http_api_container + .whitelist_manager + .add_torrent_to_whitelist(&info_hash) + .await + .unwrap(); let request_id = Uuid::new_v4(); @@ -307,7 +329,11 @@ async fn should_allow_reload_the_whitelist_from_the_database() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.http_api_container + .whitelist_manager + .add_torrent_to_whitelist(&info_hash) + .await + .unwrap(); let request_id = Uuid::new_v4(); @@ -338,7 +364,11 @@ async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); let info_hash = InfoHash::from_str(&hash).unwrap(); - env.whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); + env.http_api_container + .whitelist_manager + .add_torrent_to_whitelist(&info_hash) + .await + .unwrap(); force_database_error(&env.database); From b38e4af4ca09164133a06602577ba3394dbd5b11 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 29 Jan 2025 11:34:57 +0000 Subject: [PATCH 0676/1297] chore: add DevSkim ignore DS173237 to avoid IDE warnings for infohashe values in tests. --- .../console/clients/checker/checks/http.rs | 4 ++-- .../src/console/clients/checker/checks/udp.rs | 2 +- .../src/http/client/requests/announce.rs | 2 +- .../src/http/client/requests/scrape.rs | 2 +- src/core/mod.rs | 4 ++-- src/core/scrape_handler.rs | 6 ++--- src/core/services/torrent.rs | 12 +++++----- .../v1/context/torrent/resources/torrent.rs | 8 +++---- .../servers/api/v1/contract/context/stats.rs | 2 +- .../api/v1/contract/context/torrent.rs | 24 +++++++++---------- .../api/v1/contract/context/whitelist.rs | 20 ++++++++-------- 11 files changed, 43 insertions(+), 43 deletions(-) diff --git a/console/tracker-client/src/console/clients/checker/checks/http.rs b/console/tracker-client/src/console/clients/checker/checks/http.rs index 0fd37ca48..1a69d9c22 100644 --- a/console/tracker-client/src/console/clients/checker/checks/http.rs +++ b/console/tracker-client/src/console/clients/checker/checks/http.rs @@ -61,7 +61,7 @@ pub async fn run(http_trackers: Vec, timeout: Duration) -> Vec Result { - let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // # DevSkim: ignore DS173237 + let info_hash_str = "9c38422213e30bff212b30c360d26f9a02136422".to_string(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&info_hash_str).expect("a valid info-hash is required"); let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; @@ -86,7 +86,7 @@ async fn check_http_announce(url: &Url, timeout: Duration) -> Result Result { - let info_hashes: Vec = vec!["9c38422213e30bff212b30c360d26f9a02136422".to_string()]; // # DevSkim: ignore DS173237 + let info_hashes: Vec = vec!["9c38422213e30bff212b30c360d26f9a02136422".to_string()]; // DevSkim: ignore DS173237 let query = requests::scrape::Query::try_from(info_hashes).expect("a valid array of info-hashes is required"); let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?; diff --git a/console/tracker-client/src/console/clients/checker/checks/udp.rs b/console/tracker-client/src/console/clients/checker/checks/udp.rs index 21bdcd1b7..b4edb2e2c 100644 --- a/console/tracker-client/src/console/clients/checker/checks/udp.rs +++ b/console/tracker-client/src/console/clients/checker/checks/udp.rs @@ -29,7 +29,7 @@ pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec QueryBuilder { let default_announce_query = Query { - info_hash: InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0, // # DevSkim: ignore DS173237 + info_hash: InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0, // DevSkim: ignore DS173237 peer_addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 88)), downloaded: 0, uploaded: 0, diff --git a/packages/tracker-client/src/http/client/requests/scrape.rs b/packages/tracker-client/src/http/client/requests/scrape.rs index 1b423390b..b25c3c4c7 100644 --- a/packages/tracker-client/src/http/client/requests/scrape.rs +++ b/packages/tracker-client/src/http/client/requests/scrape.rs @@ -90,7 +90,7 @@ pub struct QueryBuilder { impl Default for QueryBuilder { fn default() -> Self { let default_scrape_query = Query { - info_hash: [InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0].to_vec(), // # DevSkim: ignore DS173237 + info_hash: [InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0].to_vec(), // DevSkim: ignore DS173237 }; Self { scrape_query: default_scrape_query, diff --git a/src/core/mod.rs b/src/core/mod.rs index 77d8e1450..7d5e7d4d6 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -498,7 +498,7 @@ mod tests { async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() { let (announce_handler, scrape_handler) = initialize_handlers_for_public_tracker(); - let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // # DevSkim: ignore DS173237 + let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237 // Announce a "complete" peer for the torrent let mut complete_peer = complete_peer(); @@ -553,7 +553,7 @@ mod tests { async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { let (announce_handler, scrape_handler) = initialize_handlers_for_listed_tracker(); - let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // # DevSkim: ignore DS173237 + let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237 let mut peer = incomplete_peer(); announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); diff --git a/src/core/scrape_handler.rs b/src/core/scrape_handler.rs index 7de82aa06..33bb6ca6a 100644 --- a/src/core/scrape_handler.rs +++ b/src/core/scrape_handler.rs @@ -75,7 +75,7 @@ mod tests { async fn it_should_return_a_zeroed_swarm_metadata_for_the_requested_file_if_the_tracker_does_not_have_that_torrent() { let scrape_handler = scrape_handler(); - let info_hashes = vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()]; // # DevSkim: ignore DS173237 + let info_hashes = vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()]; // DevSkim: ignore DS173237 let scrape_data = scrape_handler.scrape(&info_hashes).await; @@ -91,8 +91,8 @@ mod tests { let scrape_handler = scrape_handler(); let info_hashes = vec![ - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), // # DevSkim: ignore DS173237 - "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1".parse::().unwrap(), // # DevSkim: ignore DS173237 + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), // DevSkim: ignore DS173237 + "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1".parse::().unwrap(), // DevSkim: ignore DS173237 ]; let scrape_data = scrape_handler.scrape(&info_hashes).await; diff --git a/src/core/services/torrent.rs b/src/core/services/torrent.rs index d809fc266..dac93ce16 100644 --- a/src/core/services/torrent.rs +++ b/src/core/services/torrent.rs @@ -145,7 +145,7 @@ mod tests { let torrent_info = get_torrent_info( in_memory_torrent_repository.clone(), - &InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(), + &InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(), // DevSkim: ignore DS173237 ) .await; @@ -156,7 +156,7 @@ mod tests { async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); @@ -201,7 +201,7 @@ mod tests { async fn should_return_a_summarized_info_for_all_torrents() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); @@ -223,7 +223,7 @@ mod tests { async fn should_allow_limiting_the_number_of_torrents_in_the_result() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash1 = InfoHash::from_str(&hash1).unwrap(); let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); @@ -244,7 +244,7 @@ mod tests { async fn should_allow_using_pagination_in_the_result() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash1 = InfoHash::from_str(&hash1).unwrap(); let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); @@ -274,7 +274,7 @@ mod tests { async fn should_return_torrents_ordered_by_info_hash() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash1 = InfoHash::from_str(&hash1).unwrap(); let () = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs index 8fbb89418..237470d88 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs @@ -122,14 +122,14 @@ mod tests { fn torrent_resource_should_be_converted_from_torrent_info() { assert_eq!( Torrent::from(Info { - info_hash: InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), + info_hash: InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), // DevSkim: ignore DS173237 seeders: 1, completed: 2, leechers: 3, peers: Some(vec![sample_peer()]), }), Torrent { - info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 seeders: 1, completed: 2, leechers: 3, @@ -142,13 +142,13 @@ mod tests { fn torrent_resource_list_item_should_be_converted_from_the_basic_torrent_info() { assert_eq!( ListItem::from(BasicInfo { - info_hash: InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), + info_hash: InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), // DevSkim: ignore DS173237 seeders: 1, completed: 2, leechers: 3, }), ListItem { - info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 seeders: 1, completed: 2, leechers: 3, diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index 2eda0ed4a..55d3cd869 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -19,7 +19,7 @@ async fn should_allow_getting_tracker_statistics() { let env = Started::new(&configuration::ephemeral().into()).await; env.add_torrent_peer( - &InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), + &InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), // DevSkim: ignore DS173237 &PeerBuilder::default().into(), ); diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index 76646db14..8aa408173 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -26,7 +26,7 @@ async fn should_allow_getting_all_torrents() { let env = Started::new(&configuration::ephemeral().into()).await; - let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); + let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()); @@ -39,7 +39,7 @@ async fn should_allow_getting_all_torrents() { assert_torrent_list( response, vec![torrent::ListItem { - info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 seeders: 1, completed: 0, leechers: 0, @@ -57,8 +57,8 @@ async fn should_allow_limiting_the_torrents_in_the_result() { let env = Started::new(&configuration::ephemeral().into()).await; // torrents are ordered alphabetically by infohashes - let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); + let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 + let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); // DevSkim: ignore DS173237 env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()); env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()); @@ -75,7 +75,7 @@ async fn should_allow_limiting_the_torrents_in_the_result() { assert_torrent_list( response, vec![torrent::ListItem { - info_hash: "0b3aea4adc213ce32295be85d3883a63bca25446".to_string(), + info_hash: "0b3aea4adc213ce32295be85d3883a63bca25446".to_string(), // DevSkim: ignore DS173237 seeders: 1, completed: 0, leechers: 0, @@ -93,8 +93,8 @@ async fn should_allow_the_torrents_result_pagination() { let env = Started::new(&configuration::ephemeral().into()).await; // torrents are ordered alphabetically by infohashes - let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); - let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); + let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 + let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); // DevSkim: ignore DS173237 env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()); env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()); @@ -111,7 +111,7 @@ async fn should_allow_the_torrents_result_pagination() { assert_torrent_list( response, vec![torrent::ListItem { - info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 seeders: 1, completed: 0, leechers: 0, @@ -296,7 +296,7 @@ async fn should_allow_getting_a_torrent_info() { let env = Started::new(&configuration::ephemeral().into()).await; - let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); + let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 let peer = PeerBuilder::default().into(); @@ -311,7 +311,7 @@ async fn should_allow_getting_a_torrent_info() { assert_torrent_info( response, Torrent { - info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), + info_hash: "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_string(), // DevSkim: ignore DS173237 seeders: 1, completed: 0, leechers: 0, @@ -330,7 +330,7 @@ async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exis let env = Started::new(&configuration::ephemeral().into()).await; let request_id = Uuid::new_v4(); - let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); + let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 let response = Client::new(env.get_connection_info()) .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) @@ -376,7 +376,7 @@ async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { let env = Started::new(&configuration::ephemeral().into()).await; - let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); + let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()); diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index 3f8271e40..945cb00b5 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -23,7 +23,7 @@ async fn should_allow_whitelisting_a_torrent() { let env = Started::new(&configuration::ephemeral().into()).await; let request_id = Uuid::new_v4(); - let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let response = Client::new(env.get_connection_info()) .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) @@ -46,7 +46,7 @@ async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() let env = Started::new(&configuration::ephemeral().into()).await; - let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let api_client = Client::new(env.get_connection_info()); @@ -73,7 +73,7 @@ async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { let env = Started::new(&configuration::ephemeral().into()).await; - let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let request_id = Uuid::new_v4(); @@ -110,7 +110,7 @@ async fn should_fail_when_the_torrent_cannot_be_whitelisted() { let env = Started::new(&configuration::ephemeral().into()).await; - let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 force_database_error(&env.database); @@ -165,7 +165,7 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { let env = Started::new(&configuration::ephemeral().into()).await; - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); env.http_api_container @@ -197,7 +197,7 @@ async fn should_not_fail_trying_to_remove_a_non_whitelisted_torrent_from_the_whi let env = Started::new(&configuration::ephemeral().into()).await; - let non_whitelisted_torrent_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let non_whitelisted_torrent_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let request_id = Uuid::new_v4(); @@ -245,7 +245,7 @@ async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { let env = Started::new(&configuration::ephemeral().into()).await; - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); env.http_api_container .whitelist_manager @@ -277,7 +277,7 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica let env = Started::new(&configuration::ephemeral().into()).await; - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); env.http_api_container @@ -327,7 +327,7 @@ async fn should_allow_reload_the_whitelist_from_the_database() { let env = Started::new(&configuration::ephemeral().into()).await; - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); env.http_api_container .whitelist_manager @@ -362,7 +362,7 @@ async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { let env = Started::new(&configuration::ephemeral().into()).await; - let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); + let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); env.http_api_container .whitelist_manager From 948cc8c2bcacc83fed4653145fcd769979c68a00 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 29 Jan 2025 12:46:10 +0000 Subject: [PATCH 0677/1297] refactor: [#1221] move core statistics mod to statistics context --- src/bootstrap/app.rs | 3 ++- src/core/services/mod.rs | 7 ------- src/core/statistics/mod.rs | 2 ++ .../statistics/mod.rs => statistics/services.rs} | 8 +++----- src/core/{services => }/statistics/setup.rs | 0 src/servers/apis/v1/context/stats/handlers.rs | 2 +- src/servers/apis/v1/context/stats/resources.rs | 4 ++-- src/servers/apis/v1/context/stats/responses.rs | 2 +- src/servers/http/v1/handlers/announce.rs | 3 ++- src/servers/http/v1/handlers/scrape.rs | 2 +- src/servers/http/v1/services/announce.rs | 3 ++- src/servers/http/v1/services/scrape.rs | 4 ++-- src/servers/udp/handlers.rs | 16 ++++++++-------- 13 files changed, 26 insertions(+), 30 deletions(-) rename src/core/{services/statistics/mod.rs => statistics/services.rs} (95%) rename src/core/{services => }/statistics/setup.rs (100%) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 71684a7e3..7661a36ec 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -28,7 +28,8 @@ use crate::core::authentication::key::repository::in_memory::InMemoryKeyReposito use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::authentication::service; use crate::core::scrape_handler::ScrapeHandler; -use crate::core::services::{initialize_database, initialize_whitelist_manager, statistics}; +use crate::core::services::{initialize_database, initialize_whitelist_manager}; +use crate::core::statistics; use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index f2ee79993..30a05a992 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -1,10 +1,3 @@ -//! Tracker domain services. Core and statistics services. -//! -//! There are two types of service: -//! -//! - [Core tracker services](crate::core::services::torrent): related to the tracker main functionalities like getting info about torrents. -//! - [Services for statistics](crate::core::services::statistics): related to tracker metrics. Aggregate data about the tracker server. -pub mod statistics; pub mod torrent; use std::sync::Arc; diff --git a/src/core/statistics/mod.rs b/src/core/statistics/mod.rs index 49a82bea9..2ffbc0c8f 100644 --- a/src/core/statistics/mod.rs +++ b/src/core/statistics/mod.rs @@ -28,3 +28,5 @@ pub mod event; pub mod keeper; pub mod metrics; pub mod repository; +pub mod services; +pub mod setup; diff --git a/src/core/services/statistics/mod.rs b/src/core/statistics/services.rs similarity index 95% rename from src/core/services/statistics/mod.rs rename to src/core/statistics/services.rs index 79bc5f268..337731aea 100644 --- a/src/core/services/statistics/mod.rs +++ b/src/core/statistics/services.rs @@ -2,7 +2,7 @@ //! //! It includes: //! -//! - A [`factory`](crate::core::services::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`factory`](crate::core::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. //! - A [`get_metrics`] service to get the tracker [`metrics`](crate::core::statistics::metrics::Metrics). //! //! Tracker metrics are collected using a Publisher-Subscribe pattern. @@ -36,8 +36,6 @@ //! // ... //! } //! ``` -pub mod setup; - use std::sync::Arc; use tokio::sync::RwLock; @@ -117,9 +115,9 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; - use crate::core::services::statistics::{self, get_metrics, TrackerMetrics}; + use crate::core::statistics::services::{get_metrics, TrackerMetrics}; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::{self}; + use crate::core::{self, statistics}; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; diff --git a/src/core/services/statistics/setup.rs b/src/core/statistics/setup.rs similarity index 100% rename from src/core/services/statistics/setup.rs rename to src/core/statistics/setup.rs diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index da87696fc..b8e7abd87 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -9,8 +9,8 @@ use serde::Deserialize; use tokio::sync::RwLock; use super::responses::{metrics_response, stats_response}; -use crate::core::services::statistics::get_metrics; use crate::core::statistics::repository::Repository; +use crate::core::statistics::services::get_metrics; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::servers::udp::server::banning::BanService; diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index c6a526a7d..97ece22fc 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -2,7 +2,7 @@ //! API context. use serde::{Deserialize, Serialize}; -use crate::core::services::statistics::TrackerMetrics; +use crate::core::statistics::services::TrackerMetrics; /// It contains all the statistics generated by the tracker. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -121,8 +121,8 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use super::Stats; - use crate::core::services::statistics::TrackerMetrics; use crate::core::statistics::metrics::Metrics; + use crate::core::statistics::services::TrackerMetrics; #[test] fn stats_resource_should_be_converted_from_tracker_metrics() { diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index a67b5328a..6fda43f8c 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -3,7 +3,7 @@ use axum::response::{IntoResponse, Json, Response}; use super::resources::Stats; -use crate::core::services::statistics::TrackerMetrics; +use crate::core::statistics::services::TrackerMetrics; /// `200` response that contains the [`Stats`] resource as json. #[must_use] diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index d6c850327..3de17df58 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -257,7 +257,8 @@ mod tests { use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::service::AuthenticationService; use crate::core::core_tests::sample_info_hash; - use crate::core::services::{initialize_database, statistics}; + use crate::core::services::initialize_database; + use crate::core::statistics; use crate::core::statistics::event::sender::Sender; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index a197263e8..35c5b1409 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -177,7 +177,7 @@ mod tests { use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::service::AuthenticationService; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::statistics; + use crate::core::statistics; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::whitelist::authorization::WhitelistAuthorization; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index e96face6a..6314c0a98 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -65,7 +65,8 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::core::announce_handler::AnnounceHandler; - use crate::core::services::{initialize_database, statistics}; + use crate::core::services::initialize_database; + use crate::core::statistics; use crate::core::statistics::event::sender::Sender; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 7e65b9442..16821e724 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -153,7 +153,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_scrape_data_for_a_torrent() { - let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let (announce_handler, scrape_handler) = initialize_announce_and_scrape_handlers_for_public_tracker(); @@ -236,7 +236,7 @@ mod tests { #[tokio::test] async fn it_should_always_return_the_zeroed_scrape_data_for_a_torrent() { - let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let (announce_handler, _scrape_handler) = initialize_announce_and_scrape_handlers_for_public_tracker(); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 992f27a44..f531718db 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -476,13 +476,13 @@ mod tests { use super::gen_remote_fingerprint; use crate::core::announce_handler::AnnounceHandler; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::{initialize_database, statistics}; + use crate::core::services::initialize_database; use crate::core::statistics::event::sender::Sender; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - use crate::core::whitelist; use crate::core::whitelist::authorization::WhitelistAuthorization; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::core::{statistics, whitelist}; use crate::CurrentClock; struct CoreTrackerServices { @@ -656,7 +656,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { - let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let request = ConnectRequest { @@ -676,7 +676,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { - let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let request = ConnectRequest { @@ -696,7 +696,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { - let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let request = ConnectRequest { @@ -1001,7 +1001,7 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); @@ -1306,7 +1306,7 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let (stats_event_sender, _stats_repository) = crate::core::services::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); @@ -1494,7 +1494,7 @@ mod tests { use super::{gen_remote_fingerprint, TorrentPeerBuilder}; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::statistics; + use crate::core::statistics; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_scrape; From d830c78cf865398ae27efbcbd519feb9040a5640 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 29 Jan 2025 13:08:16 +0000 Subject: [PATCH 0678/1297] refactor: [#1221] move core torrent mod to torrent context --- src/core/services/mod.rs | 2 -- src/core/torrent/mod.rs | 1 + src/core/{services/torrent.rs => torrent/services.rs} | 8 ++++---- src/servers/apis/v1/context/torrent/handlers.rs | 2 +- src/servers/apis/v1/context/torrent/resources/torrent.rs | 4 ++-- src/servers/apis/v1/context/torrent/responses.rs | 2 +- 6 files changed, 9 insertions(+), 10 deletions(-) rename src/core/{services/torrent.rs => torrent/services.rs} (97%) diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index 30a05a992..1050e41f8 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -1,5 +1,3 @@ -pub mod torrent; - use std::sync::Arc; use databases::driver::Driver; diff --git a/src/core/torrent/mod.rs b/src/core/torrent/mod.rs index 95a5ff1eb..2aa19130e 100644 --- a/src/core/torrent/mod.rs +++ b/src/core/torrent/mod.rs @@ -27,6 +27,7 @@ //! pub mod manager; pub mod repository; +pub mod services; use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; diff --git a/src/core/services/torrent.rs b/src/core/torrent/services.rs similarity index 97% rename from src/core/services/torrent.rs rename to src/core/torrent/services.rs index dac93ce16..5a4810412 100644 --- a/src/core/services/torrent.rs +++ b/src/core/torrent/services.rs @@ -135,9 +135,9 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; - use crate::core::services::torrent::tests::sample_peer; - use crate::core::services::torrent::{get_torrent_info, Info}; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::torrent::services::tests::sample_peer; + use crate::core::torrent::services::{get_torrent_info, Info}; #[tokio::test] async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { @@ -184,9 +184,9 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; - use crate::core::services::torrent::tests::sample_peer; - use crate::core::services::torrent::{get_torrents_page, BasicInfo, Pagination}; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core::torrent::services::tests::sample_peer; + use crate::core::torrent::services::{get_torrents_page, BasicInfo, Pagination}; #[tokio::test] async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs index 8fe20ab80..0ec90441d 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/src/servers/apis/v1/context/torrent/handlers.rs @@ -13,8 +13,8 @@ use thiserror::Error; use torrust_tracker_primitives::pagination::Pagination; use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; -use crate::core::services::torrent::{get_torrent_info, get_torrents, get_torrents_page}; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; +use crate::core::torrent::services::{get_torrent_info, get_torrents, get_torrents_page}; use crate::servers::apis::v1::responses::invalid_info_hash_param_response; use crate::servers::apis::InfoHashParam; diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs index 237470d88..c90a2a05f 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs @@ -6,7 +6,7 @@ //! the JSON response. use serde::{Deserialize, Serialize}; -use crate::core::services::torrent::{BasicInfo, Info}; +use crate::core::torrent::services::{BasicInfo, Info}; /// `Torrent` API resource. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -102,7 +102,7 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use super::Torrent; - use crate::core::services::torrent::{BasicInfo, Info}; + use crate::core::torrent::services::{BasicInfo, Info}; use crate::servers::apis::v1::context::torrent::resources::peer::Peer; use crate::servers::apis::v1::context::torrent::resources::torrent::ListItem; diff --git a/src/servers/apis/v1/context/torrent/responses.rs b/src/servers/apis/v1/context/torrent/responses.rs index 5daceaf94..5174c9abe 100644 --- a/src/servers/apis/v1/context/torrent/responses.rs +++ b/src/servers/apis/v1/context/torrent/responses.rs @@ -4,7 +4,7 @@ use axum::response::{IntoResponse, Json, Response}; use serde_json::json; use super::resources::torrent::{ListItem, Torrent}; -use crate::core::services::torrent::{BasicInfo, Info}; +use crate::core::torrent::services::{BasicInfo, Info}; /// `200` response that contains an array of /// [`ListItem`] From 716e7b2fe050b03d524a47bc9fed41646a250ff1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 29 Jan 2025 13:13:58 +0000 Subject: [PATCH 0679/1297] refactor: [#1221] move DB setup to databases context --- src/bootstrap/app.rs | 3 ++- src/core/announce_handler.rs | 2 +- src/core/authentication/handler.rs | 2 +- src/core/authentication/mod.rs | 2 +- src/core/core_tests.rs | 2 +- src/core/databases/mod.rs | 1 + src/core/databases/setup.rs | 20 ++++++++++++++++++++ src/core/services/mod.rs | 19 +------------------ src/core/whitelist/whitelist_tests.rs | 3 ++- src/servers/http/v1/handlers/announce.rs | 2 +- src/servers/http/v1/services/announce.rs | 4 ++-- src/servers/http/v1/services/scrape.rs | 2 +- src/servers/udp/handlers.rs | 4 ++-- 13 files changed, 36 insertions(+), 30 deletions(-) create mode 100644 src/core/databases/setup.rs diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 7661a36ec..44fc4ea00 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -27,8 +27,9 @@ use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::authentication::service; +use crate::core::databases::setup::initialize_database; use crate::core::scrape_handler::ScrapeHandler; -use crate::core::services::{initialize_database, initialize_whitelist_manager}; +use crate::core::services::initialize_whitelist_manager; use crate::core::statistics; use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; diff --git a/src/core/announce_handler.rs b/src/core/announce_handler.rs index 1a5f84d47..816663bf6 100644 --- a/src/core/announce_handler.rs +++ b/src/core/announce_handler.rs @@ -414,7 +414,7 @@ mod tests { use crate::core::announce_handler::tests::the_announce_handler::peer_ip; use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; use crate::core::core_tests::{sample_info_hash, sample_peer}; - use crate::core::services::initialize_database; + use crate::core::databases::setup::initialize_database; use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; diff --git a/src/core/authentication/handler.rs b/src/core/authentication/handler.rs index 5ec9a11b4..d6477a948 100644 --- a/src/core/authentication/handler.rs +++ b/src/core/authentication/handler.rs @@ -246,7 +246,7 @@ mod tests { use crate::core::authentication::handler::KeysHandler; use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; - use crate::core::services::initialize_database; + use crate::core::databases::setup::initialize_database; fn instantiate_keys_handler() -> KeysHandler { let config = configuration::ephemeral_private(); diff --git a/src/core/authentication/mod.rs b/src/core/authentication/mod.rs index 0180b3a1e..eddcc1ae7 100644 --- a/src/core/authentication/mod.rs +++ b/src/core/authentication/mod.rs @@ -27,7 +27,7 @@ mod tests { use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::core::authentication::service; use crate::core::authentication::service::AuthenticationService; - use crate::core::services::initialize_database; + use crate::core::databases::setup::initialize_database; fn instantiate_keys_manager_and_authentication() -> (Arc, Arc) { let config = configuration::ephemeral_private(); diff --git a/src/core/core_tests.rs b/src/core/core_tests.rs index 45949bae2..35d5fb9b7 100644 --- a/src/core/core_tests.rs +++ b/src/core/core_tests.rs @@ -9,8 +9,8 @@ use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::announce_handler::AnnounceHandler; +use super::databases::setup::initialize_database; use super::scrape_handler::ScrapeHandler; -use super::services::initialize_database; use super::torrent::repository::in_memory::InMemoryTorrentRepository; use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; use super::whitelist::repository::in_memory::InMemoryWhitelist; diff --git a/src/core/databases/mod.rs b/src/core/databases/mod.rs index e0b1b4f1b..dec6b799d 100644 --- a/src/core/databases/mod.rs +++ b/src/core/databases/mod.rs @@ -46,6 +46,7 @@ pub mod driver; pub mod error; pub mod mysql; +pub mod setup; pub mod sqlite; use std::marker::PhantomData; diff --git a/src/core/databases/setup.rs b/src/core/databases/setup.rs new file mode 100644 index 000000000..728913e05 --- /dev/null +++ b/src/core/databases/setup.rs @@ -0,0 +1,20 @@ +use std::sync::Arc; + +use torrust_tracker_configuration::v2_0_0::database; +use torrust_tracker_configuration::Configuration; + +use super::driver::{self, Driver}; +use super::Database; + +/// # Panics +/// +/// Will panic if database cannot be initialized. +#[must_use] +pub fn initialize_database(config: &Configuration) -> Arc> { + let driver = match config.core.database.driver { + database::Driver::Sqlite3 => Driver::Sqlite3, + database::Driver::MySQL => Driver::MySQL, + }; + + Arc::new(driver::build(&driver, &config.core.database.path).expect("Database driver build failed.")) +} diff --git a/src/core/services/mod.rs b/src/core/services/mod.rs index 1050e41f8..4d30fa966 100644 --- a/src/core/services/mod.rs +++ b/src/core/services/mod.rs @@ -1,27 +1,10 @@ use std::sync::Arc; -use databases::driver::Driver; -use torrust_tracker_configuration::v2_0_0::database; -use torrust_tracker_configuration::Configuration; - -use super::databases::{self, Database}; +use super::databases::Database; use super::whitelist::manager::WhitelistManager; use super::whitelist::repository::in_memory::InMemoryWhitelist; use super::whitelist::repository::persisted::DatabaseWhitelist; -/// # Panics -/// -/// Will panic if database cannot be initialized. -#[must_use] -pub fn initialize_database(config: &Configuration) -> Arc> { - let driver = match config.core.database.driver { - database::Driver::Sqlite3 => Driver::Sqlite3, - database::Driver::MySQL => Driver::MySQL, - }; - - Arc::new(databases::driver::build(&driver, &config.core.database.path).expect("Database driver build failed.")) -} - #[must_use] pub fn initialize_whitelist_manager( database: Arc>, diff --git a/src/core/whitelist/whitelist_tests.rs b/src/core/whitelist/whitelist_tests.rs index aa9c5ca14..cbe1e6488 100644 --- a/src/core/whitelist/whitelist_tests.rs +++ b/src/core/whitelist/whitelist_tests.rs @@ -5,7 +5,8 @@ use torrust_tracker_configuration::Configuration; use super::authorization::WhitelistAuthorization; use super::manager::WhitelistManager; use super::repository::in_memory::InMemoryWhitelist; -use crate::core::services::{initialize_database, initialize_whitelist_manager}; +use crate::core::databases::setup::initialize_database; +use crate::core::services::initialize_whitelist_manager; #[must_use] pub fn initialize_whitelist_services(config: &Configuration) -> (Arc, Arc) { diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 3de17df58..544d706fa 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -257,7 +257,7 @@ mod tests { use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::core::authentication::service::AuthenticationService; use crate::core::core_tests::sample_info_hash; - use crate::core::services::initialize_database; + use crate::core::databases::setup::initialize_database; use crate::core::statistics; use crate::core::statistics::event::sender::Sender; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 6314c0a98..ee682559e 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -65,7 +65,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::core::announce_handler::AnnounceHandler; - use crate::core::services::initialize_database; + use crate::core::databases::setup::initialize_database; use crate::core::statistics; use crate::core::statistics::event::sender::Sender; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -138,7 +138,7 @@ mod tests { use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; use crate::core::core_tests::sample_info_hash; - use crate::core::services::initialize_database; + use crate::core::databases::setup::initialize_database; use crate::core::statistics; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 16821e724..b5a858b83 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -82,8 +82,8 @@ mod tests { use crate::core::announce_handler::AnnounceHandler; use crate::core::core_tests::sample_info_hash; + use crate::core::databases::setup::initialize_database; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::initialize_database; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use crate::core::whitelist::authorization::WhitelistAuthorization; diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index f531718db..90c32771f 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -475,8 +475,8 @@ mod tests { use super::gen_remote_fingerprint; use crate::core::announce_handler::AnnounceHandler; + use crate::core::databases::setup::initialize_database; use crate::core::scrape_handler::ScrapeHandler; - use crate::core::services::initialize_database; use crate::core::statistics::event::sender::Sender; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; @@ -1393,7 +1393,7 @@ mod tests { use mockall::predicate::eq; use crate::core::announce_handler::AnnounceHandler; - use crate::core::services::initialize_database; + use crate::core::databases::setup::initialize_database; use crate::core::statistics; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; From 1db58b16603c225585842c85e9f8a759623e0722 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 29 Jan 2025 13:17:16 +0000 Subject: [PATCH 0680/1297] refactor: [#1221] move whitelist manager setup to whitelist context --- src/bootstrap/app.rs | 2 +- src/core/mod.rs | 1 - src/core/whitelist/mod.rs | 1 + src/core/{services/mod.rs => whitelist/setup.rs} | 8 ++++---- src/core/whitelist/whitelist_tests.rs | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) rename src/core/{services/mod.rs => whitelist/setup.rs} (61%) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 44fc4ea00..8a084dc7f 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -29,13 +29,13 @@ use crate::core::authentication::key::repository::persisted::DatabaseKeyReposito use crate::core::authentication::service; use crate::core::databases::setup::initialize_database; use crate::core::scrape_handler::ScrapeHandler; -use crate::core::services::initialize_whitelist_manager; use crate::core::statistics; use crate::core::torrent::manager::TorrentsManager; use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use crate::core::whitelist::authorization::WhitelistAuthorization; use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; +use crate::core::whitelist::setup::initialize_whitelist_manager; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; diff --git a/src/core/mod.rs b/src/core/mod.rs index 7d5e7d4d6..038264446 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -444,7 +444,6 @@ pub mod authentication; pub mod databases; pub mod error; pub mod scrape_handler; -pub mod services; pub mod statistics; pub mod torrent; pub mod whitelist; diff --git a/src/core/whitelist/mod.rs b/src/core/whitelist/mod.rs index c23740111..1f5f87626 100644 --- a/src/core/whitelist/mod.rs +++ b/src/core/whitelist/mod.rs @@ -1,6 +1,7 @@ pub mod authorization; pub mod manager; pub mod repository; +pub mod setup; pub mod whitelist_tests; #[cfg(test)] diff --git a/src/core/services/mod.rs b/src/core/whitelist/setup.rs similarity index 61% rename from src/core/services/mod.rs rename to src/core/whitelist/setup.rs index 4d30fa966..bdd35737c 100644 --- a/src/core/services/mod.rs +++ b/src/core/whitelist/setup.rs @@ -1,9 +1,9 @@ use std::sync::Arc; -use super::databases::Database; -use super::whitelist::manager::WhitelistManager; -use super::whitelist::repository::in_memory::InMemoryWhitelist; -use super::whitelist::repository::persisted::DatabaseWhitelist; +use super::manager::WhitelistManager; +use super::repository::in_memory::InMemoryWhitelist; +use super::repository::persisted::DatabaseWhitelist; +use crate::core::databases::Database; #[must_use] pub fn initialize_whitelist_manager( diff --git a/src/core/whitelist/whitelist_tests.rs b/src/core/whitelist/whitelist_tests.rs index cbe1e6488..38c2bbde3 100644 --- a/src/core/whitelist/whitelist_tests.rs +++ b/src/core/whitelist/whitelist_tests.rs @@ -6,7 +6,7 @@ use super::authorization::WhitelistAuthorization; use super::manager::WhitelistManager; use super::repository::in_memory::InMemoryWhitelist; use crate::core::databases::setup::initialize_database; -use crate::core::services::initialize_whitelist_manager; +use crate::core::whitelist::setup::initialize_whitelist_manager; #[must_use] pub fn initialize_whitelist_services(config: &Configuration) -> (Arc, Arc) { From 4921f7b31b73752a0822f9d808c610da4854a31d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 29 Jan 2025 13:30:08 +0000 Subject: [PATCH 0681/1297] fix: [#1221] docs links --- src/core/mod.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/core/mod.rs b/src/core/mod.rs index 038264446..125a67b5a 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -344,10 +344,10 @@ //! //! # Services //! -//! Services are domain services on top of the core tracker. Right now there are two types of service: +//! Services are domain services on top of the core tracker domain. Right now there are two types of service: //! -//! - For statistics -//! - For torrents +//! - For statistics: [`crate::core::statistics::services`] +//! - For torrents: [`crate::core::torrent::services`] //! //! Services usually format the data inside the tracker to make it easier to consume by other parts. //! They also decouple the internal data structure, used by the tracker, from the way we deliver that data to the consumers. @@ -356,8 +356,6 @@ //! //! Services can include extra features like pagination, for example. //! -//! Refer to [`services`] module for more information about services. -//! //! # Authentication //! //! One of the core `Tracker` responsibilities is to create and keep authentication keys. Auth keys are used by HTTP trackers From a5ca24460c5b06ad434f65f2e67f3aac47260b23 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 29 Jan 2025 18:10:18 +0000 Subject: [PATCH 0682/1297] refactor: [#1223] extract tracker-core workspace package --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 31 + Cargo.toml | 14 +- packages/tracker-core/Cargo.toml | 43 ++ packages/tracker-core/LICENSE | 661 ++++++++++++++++++ packages/tracker-core/README.md | 15 + .../tracker-core/migrations}/README.md | 0 ...3000_torrust_tracker_create_all_tables.sql | 0 ...rust_tracker_keys_valid_until_nullable.sql | 0 ...3000_torrust_tracker_create_all_tables.sql | 0 ...rust_tracker_keys_valid_until_nullable.sql | 0 .../tracker-core/src}/announce_handler.rs | 38 +- .../src}/authentication/handler.rs | 28 +- .../src}/authentication/key/mod.rs | 19 +- .../key/repository/in_memory.rs | 2 +- .../src}/authentication/key/repository/mod.rs | 0 .../key/repository/persisted.rs | 4 +- .../tracker-core/src}/authentication/mod.rs | 30 +- .../src}/authentication/service.rs | 6 +- .../tracker-core/src}/core_tests.rs | 0 .../tracker-core/src}/databases/driver.rs | 8 +- .../tracker-core/src}/databases/error.rs | 0 .../tracker-core/src}/databases/mod.rs | 4 +- .../tracker-core/src}/databases/mysql.rs | 4 +- .../tracker-core/src}/databases/setup.rs | 0 .../tracker-core/src}/databases/sqlite.rs | 2 +- .../tracker-core/src}/error.rs | 0 packages/tracker-core/src/lib.rs | 585 ++++++++++++++++ .../tracker-core/src}/peer_tests.rs | 0 .../tracker-core/src}/scrape_handler.rs | 6 +- .../src}/statistics/event/handler.rs | 10 +- .../src}/statistics/event/listener.rs | 2 +- .../tracker-core/src}/statistics/event/mod.rs | 0 .../src}/statistics/event/sender.rs | 0 .../tracker-core/src}/statistics/keeper.rs | 6 +- .../tracker-core/src}/statistics/metrics.rs | 0 packages/tracker-core/src/statistics/mod.rs | 32 + .../src}/statistics/repository.rs | 0 .../tracker-core/src/statistics/services.rs | 55 ++ .../tracker-core/src}/statistics/setup.rs | 2 +- .../tracker-core/src}/torrent/manager.rs | 3 +- .../tracker-core/src}/torrent/mod.rs | 0 .../src}/torrent/repository/in_memory.rs | 6 +- .../src}/torrent/repository/mod.rs | 0 .../src}/torrent/repository/persisted.rs | 4 +- .../tracker-core/src}/torrent/services.rs | 50 +- .../src}/whitelist/authorization.rs | 6 +- .../tracker-core/src}/whitelist/manager.rs | 14 +- .../tracker-core/src}/whitelist/mod.rs | 4 +- .../src}/whitelist/repository/in_memory.rs | 4 +- .../src}/whitelist/repository/mod.rs | 0 .../src}/whitelist/repository/persisted.rs | 2 +- .../tracker-core/src}/whitelist/setup.rs | 2 +- .../src}/whitelist/whitelist_tests.rs | 4 +- src/bootstrap/app.rs | 28 +- src/bootstrap/jobs/torrent_cleanup.rs | 3 +- src/container.rs | 24 +- src/core/mod.rs | 572 --------------- src/core/statistics/mod.rs | 31 - src/core/statistics/services.rs | 39 +- .../apis/v1/context/auth_key/handlers.rs | 10 +- .../apis/v1/context/auth_key/resources.rs | 5 +- .../apis/v1/context/auth_key/routes.rs | 2 +- src/servers/apis/v1/context/stats/handlers.rs | 4 +- .../apis/v1/context/stats/resources.rs | 7 +- .../apis/v1/context/stats/responses.rs | 2 +- .../apis/v1/context/torrent/handlers.rs | 21 +- .../v1/context/torrent/resources/torrent.rs | 5 +- .../apis/v1/context/torrent/responses.rs | 2 +- src/servers/apis/v1/context/torrent/routes.rs | 2 +- .../apis/v1/context/whitelist/handlers.rs | 2 +- .../apis/v1/context/whitelist/routes.rs | 2 +- .../http/v1/extractors/authentication_key.rs | 2 +- src/servers/http/v1/handlers/announce.rs | 39 +- src/servers/http/v1/handlers/common/auth.rs | 15 +- src/servers/http/v1/handlers/scrape.rs | 27 +- src/servers/http/v1/services/announce.rs | 54 +- src/servers/http/v1/services/scrape.rs | 59 +- src/servers/udp/handlers.rs | 111 +-- src/servers/udp/server/launcher.rs | 2 +- src/servers/udp/server/processor.rs | 4 +- src/shared/bit_torrent/common.rs | 6 - tests/servers/api/environment.rs | 4 +- tests/servers/api/mod.rs | 2 +- .../api/v1/contract/context/auth_key.rs | 4 +- tests/servers/http/client.rs | 2 +- tests/servers/http/connection_info.rs | 2 +- tests/servers/http/environment.rs | 10 +- tests/servers/http/v1/contract.rs | 4 +- tests/servers/udp/environment.rs | 6 +- 90 files changed, 1830 insertions(+), 991 deletions(-) create mode 100644 packages/tracker-core/Cargo.toml create mode 100644 packages/tracker-core/LICENSE create mode 100644 packages/tracker-core/README.md rename {migrations => packages/tracker-core/migrations}/README.md (100%) rename {migrations => packages/tracker-core/migrations}/mysql/20240730183000_torrust_tracker_create_all_tables.sql (100%) rename {migrations => packages/tracker-core/migrations}/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql (100%) rename {migrations => packages/tracker-core/migrations}/sqlite/20240730183000_torrust_tracker_create_all_tables.sql (100%) rename {migrations => packages/tracker-core/migrations}/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql (100%) rename {src/core => packages/tracker-core/src}/announce_handler.rs (92%) rename {src/core => packages/tracker-core/src}/authentication/handler.rs (91%) rename {src/core => packages/tracker-core/src}/authentication/key/mod.rs (95%) rename {src/core => packages/tracker-core/src}/authentication/key/repository/in_memory.rs (95%) rename {src/core => packages/tracker-core/src}/authentication/key/repository/mod.rs (100%) rename {src/core => packages/tracker-core/src}/authentication/key/repository/persisted.rs (92%) rename {src/core => packages/tracker-core/src}/authentication/mod.rs (86%) rename {src/core => packages/tracker-core/src}/authentication/service.rs (93%) rename {src/core => packages/tracker-core/src}/core_tests.rs (100%) rename {src/core => packages/tracker-core/src}/databases/driver.rs (90%) rename {src/core => packages/tracker-core/src}/databases/error.rs (100%) rename {src/core => packages/tracker-core/src}/databases/mod.rs (98%) rename {src/core => packages/tracker-core/src}/databases/mysql.rs (98%) rename {src/core => packages/tracker-core/src}/databases/setup.rs (100%) rename {src/core => packages/tracker-core/src}/databases/sqlite.rs (99%) rename {src/core => packages/tracker-core/src}/error.rs (100%) create mode 100644 packages/tracker-core/src/lib.rs rename {src/core => packages/tracker-core/src}/peer_tests.rs (100%) rename {src/core => packages/tracker-core/src}/scrape_handler.rs (95%) rename {src/core => packages/tracker-core/src}/statistics/event/handler.rs (96%) rename {src/core => packages/tracker-core/src}/statistics/event/listener.rs (84%) rename {src/core => packages/tracker-core/src}/statistics/event/mod.rs (100%) rename {src/core => packages/tracker-core/src}/statistics/event/sender.rs (100%) rename {src/core => packages/tracker-core/src}/statistics/keeper.rs (93%) rename {src/core => packages/tracker-core/src}/statistics/metrics.rs (100%) create mode 100644 packages/tracker-core/src/statistics/mod.rs rename {src/core => packages/tracker-core/src}/statistics/repository.rs (100%) create mode 100644 packages/tracker-core/src/statistics/services.rs rename {src/core => packages/tracker-core/src}/statistics/setup.rs (98%) rename {src/core => packages/tracker-core/src}/torrent/manager.rs (97%) rename {src/core => packages/tracker-core/src}/torrent/mod.rs (100%) rename {src/core => packages/tracker-core/src}/torrent/repository/in_memory.rs (98%) rename {src/core => packages/tracker-core/src}/torrent/repository/mod.rs (100%) rename {src/core => packages/tracker-core/src}/torrent/repository/persisted.rs (94%) rename {src/core => packages/tracker-core/src}/torrent/services.rs (85%) rename {src/core => packages/tracker-core/src}/whitelist/authorization.rs (93%) rename {src/core => packages/tracker-core/src}/whitelist/manager.rs (91%) rename {src/core => packages/tracker-core/src}/whitelist/mod.rs (88%) rename {src/core => packages/tracker-core/src}/whitelist/repository/in_memory.rs (94%) rename {src/core => packages/tracker-core/src}/whitelist/repository/mod.rs (100%) rename {src/core => packages/tracker-core/src}/whitelist/repository/persisted.rs (97%) rename {src/core => packages/tracker-core/src}/whitelist/setup.rs (92%) rename {src/core => packages/tracker-core/src}/whitelist/whitelist_tests.rs (89%) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index fd4e0fd5c..41b40feaa 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -57,6 +57,7 @@ jobs: run: | cargo publish -p bittorrent-http-protocol cargo publish -p bittorrent-tracker-client + cargo publish -p bittorrent-tracker-core cargo publish -p torrust-tracker cargo publish -p torrust-tracker-api-client cargo publish -p torrust-tracker-client diff --git a/Cargo.lock b/Cargo.lock index 355457721..d0d4d7e8f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -591,6 +591,36 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "bittorrent-tracker-core" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "bittorrent-http-protocol", + "bittorrent-primitives", + "chrono", + "derive_more", + "futures", + "local-ip-address", + "mockall", + "r2d2", + "r2d2_mysql", + "r2d2_sqlite", + "rand", + "serde", + "serde_json", + "thiserror 2.0.11", + "tokio", + "torrust-tracker-api-client", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-located-error", + "torrust-tracker-primitives", + "torrust-tracker-test-helpers", + "torrust-tracker-torrent-repository", + "tracing", +] + [[package]] name = "bitvec" version = "1.0.1" @@ -3931,6 +3961,7 @@ dependencies = [ "bittorrent-http-protocol", "bittorrent-primitives", "bittorrent-tracker-client", + "bittorrent-tracker-core", "bloom", "blowfish", "camino", diff --git a/Cargo.toml b/Cargo.toml index 4b4862cca..6c9f7f22d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,7 @@ axum-server = { version = "0", features = ["tls-rustls-no-provider"] } bittorrent-http-protocol = { version = "3.0.0-develop", path = "packages/http-protocol" } bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } +bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker-core" } bloom = "0.3.2" blowfish = "0" camino = { version = "1", features = ["serde", "serde1"] } @@ -90,7 +91,17 @@ uuid = { version = "1", features = ["v4"] } zerocopy = "0.7" [package.metadata.cargo-machete] -ignored = ["crossbeam-skiplist", "dashmap", "figment", "parking_lot", "serde_bytes"] +ignored = [ + "crossbeam-skiplist", + "dashmap", + "figment", + "parking_lot", + "r2d2", + "r2d2_mysql", + "r2d2_sqlite", + "serde_bytes", + "torrust-tracker-torrent-repository", +] [dev-dependencies] local-ip-address = "0" @@ -109,6 +120,7 @@ members = [ "packages/torrent-repository", "packages/tracker-api-client", "packages/tracker-client", + "packages/tracker-core", ] [profile.dev] diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml new file mode 100644 index 000000000..b38f7c90f --- /dev/null +++ b/packages/tracker-core/Cargo.toml @@ -0,0 +1,43 @@ +[package] +description = "A library with the core functionality needed to implement a BitTorrent tracker." +keywords = ["api", "bittorrent", "core", "library", "tracker"] +name = "bittorrent-tracker-core" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-http-protocol = { version = "3.0.0-develop", path = "../http-protocol" } +bittorrent-primitives = "0.1.0" +chrono = { version = "0", default-features = false, features = ["clock"] } +derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } +futures = "0" +r2d2 = "0" +r2d2_mysql = "25" +r2d2_sqlite = { version = "0", features = ["bundled"] } +rand = "0" +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["preserve_order"] } +thiserror = "2" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } +tracing = "0" + +[dev-dependencies] +local-ip-address = "0" +mockall = "0" +torrust-tracker-api-client = { version = "3.0.0-develop", path = "../tracker-api-client" } +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/tracker-core/LICENSE b/packages/tracker-core/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/tracker-core/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/tracker-core/README.md b/packages/tracker-core/README.md new file mode 100644 index 000000000..1575cda49 --- /dev/null +++ b/packages/tracker-core/README.md @@ -0,0 +1,15 @@ +# BitTorrent Core Tracker library + +A library with the core functionality needed to implement a BitTorrent tracker. + +You usually don’t need to use this library directly. Instead, you should use the [Torrust Tracker](https://github.com/torrust/torrust-tracker). If you want to build your own tracker, you can use this library as the core functionality. In that case, you should add the delivery layer (HTTP or UDP) on top of this library. + +> **Disclaimer**: This library is actively under development. We’re currently extracting and refining common types from the[Torrust Tracker](https://github.com/torrust/torrust-tracker) to make them available to the BitTorrent community in Rust. While these types are functional, they are not yet ready for use in production or third-party projects. + +## Documentation + +[Crate documentation](https://docs.rs/bittorrent-tracker-core). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/migrations/README.md b/packages/tracker-core/migrations/README.md similarity index 100% rename from migrations/README.md rename to packages/tracker-core/migrations/README.md diff --git a/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql b/packages/tracker-core/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql similarity index 100% rename from migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql rename to packages/tracker-core/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql diff --git a/migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql b/packages/tracker-core/migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql similarity index 100% rename from migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql rename to packages/tracker-core/migrations/mysql/20240730183500_torrust_tracker_keys_valid_until_nullable.sql diff --git a/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql b/packages/tracker-core/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql similarity index 100% rename from migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql rename to packages/tracker-core/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql diff --git a/migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql b/packages/tracker-core/migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql similarity index 100% rename from migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql rename to packages/tracker-core/migrations/sqlite/20240730183500_torrust_tracker_keys_valid_until_nullable.sql diff --git a/src/core/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs similarity index 92% rename from src/core/announce_handler.rs rename to packages/tracker-core/src/announce_handler.rs index 816663bf6..877555d1c 100644 --- a/src/core/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -176,9 +176,9 @@ mod tests { use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration; - use crate::core::announce_handler::AnnounceHandler; - use crate::core::core_tests::initialize_handlers; - use crate::core::scrape_handler::ScrapeHandler; + use crate::announce_handler::AnnounceHandler; + use crate::core_tests::initialize_handlers; + use crate::scrape_handler::ScrapeHandler; fn public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); @@ -222,17 +222,17 @@ mod tests { use std::sync::Arc; - use crate::core::announce_handler::tests::the_announce_handler::{ + use crate::announce_handler::tests::the_announce_handler::{ peer_ip, public_tracker, sample_peer_1, sample_peer_2, }; - use crate::core::announce_handler::PeersWanted; - use crate::core::core_tests::{sample_info_hash, sample_peer}; + use crate::announce_handler::PeersWanted; + use crate::core_tests::{sample_info_hash, sample_peer}; mod should_assign_the_ip_to_the_peer { use std::net::{IpAddr, Ipv4Addr}; - use crate::core::announce_handler::assign_ip_address_to_peer; + use crate::announce_handler::assign_ip_address_to_peer; #[test] fn using_the_source_ip_instead_of_the_ip_in_the_announce_request() { @@ -248,7 +248,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::str::FromStr; - use crate::core::announce_handler::assign_ip_address_to_peer; + use crate::announce_handler::assign_ip_address_to_peer; #[test] fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { @@ -289,7 +289,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::str::FromStr; - use crate::core::announce_handler::assign_ip_address_to_peer; + use crate::announce_handler::assign_ip_address_to_peer; #[test] fn it_should_use_the_loopback_ip_if_the_tracker_does_not_have_the_external_ip_configuration() { @@ -357,9 +357,9 @@ mod tests { mod it_should_update_the_swarm_stats_for_the_torrent { - use crate::core::announce_handler::tests::the_announce_handler::{peer_ip, public_tracker}; - use crate::core::announce_handler::PeersWanted; - use crate::core::core_tests::{completed_peer, leecher, sample_info_hash, seeder, started_peer}; + use crate::announce_handler::tests::the_announce_handler::{peer_ip, public_tracker}; + use crate::announce_handler::PeersWanted; + use crate::core_tests::{completed_peer, leecher, sample_info_hash, seeder, started_peer}; #[tokio::test] async fn when_the_peer_is_a_seeder() { @@ -411,13 +411,13 @@ mod tests { use torrust_tracker_test_helpers::configuration; use torrust_tracker_torrent_repository::entry::EntrySync; - use crate::core::announce_handler::tests::the_announce_handler::peer_ip; - use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; - use crate::core::core_tests::{sample_info_hash, sample_peer}; - use crate::core::databases::setup::initialize_database; - use crate::core::torrent::manager::TorrentsManager; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use crate::announce_handler::tests::the_announce_handler::peer_ip; + use crate::announce_handler::{AnnounceHandler, PeersWanted}; + use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::databases::setup::initialize_database; + use crate::torrent::manager::TorrentsManager; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; #[tokio::test] async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { diff --git a/src/core/authentication/handler.rs b/packages/tracker-core/src/authentication/handler.rs similarity index 91% rename from src/core/authentication/handler.rs rename to packages/tracker-core/src/authentication/handler.rs index d6477a948..1d74c7dfa 100644 --- a/src/core/authentication/handler.rs +++ b/packages/tracker-core/src/authentication/handler.rs @@ -8,8 +8,8 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::key::repository::in_memory::InMemoryKeyRepository; use super::key::repository::persisted::DatabaseKeyRepository; use super::{key, CurrentClock, Key, PeerKey}; -use crate::core::databases; -use crate::core::error::PeerKeyError; +use crate::databases; +use crate::error::PeerKeyError; /// This type contains the info needed to add a new tracker key. /// @@ -243,10 +243,10 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; - use crate::core::authentication::handler::KeysHandler; - use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; - use crate::core::databases::setup::initialize_database; + use crate::authentication::handler::KeysHandler; + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::databases::setup::initialize_database; fn instantiate_keys_handler() -> KeysHandler { let config = configuration::ephemeral_private(); @@ -280,7 +280,7 @@ mod tests { use torrust_tracker_clock::clock::Time; - use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; use crate::CurrentClock; #[tokio::test] @@ -301,9 +301,9 @@ mod tests { use torrust_tracker_clock::clock::Time; - use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; - use crate::core::authentication::handler::AddKeyRequest; - use crate::core::authentication::Key; + use crate::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::authentication::handler::AddKeyRequest; + use crate::authentication::Key; use crate::CurrentClock; #[tokio::test] @@ -329,7 +329,7 @@ mod tests { mod with_permanent_and { mod randomly_generated_keys { - use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; #[tokio::test] async fn it_should_generate_the_key() { @@ -343,9 +343,9 @@ mod tests { mod pre_generated_keys { - use crate::core::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; - use crate::core::authentication::handler::AddKeyRequest; - use crate::core::authentication::Key; + use crate::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::authentication::handler::AddKeyRequest; + use crate::authentication::Key; #[tokio::test] async fn it_should_add_a_pre_generated_key() { diff --git a/src/core/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs similarity index 95% rename from src/core/authentication/key/mod.rs rename to packages/tracker-core/src/authentication/key/mod.rs index 49d559e42..37fc4764b 100644 --- a/src/core/authentication/key/mod.rs +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -12,7 +12,7 @@ //! Keys are stored in this struct: //! //! ```rust,no_run -//! use torrust_tracker_lib::core::authentication::Key; +//! use bittorrent_tracker_core::authentication::Key; //! use torrust_tracker_primitives::DurationSinceUnixEpoch; //! //! pub struct PeerKey { @@ -28,7 +28,7 @@ //! You can generate a new key valid for `9999` seconds and `0` nanoseconds from the current time with the following: //! //! ```rust,no_run -//! use torrust_tracker_lib::core::authentication; +//! use bittorrent_tracker_core::authentication; //! use std::time::Duration; //! //! let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0))); @@ -54,9 +54,14 @@ use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; use torrust_tracker_located_error::{DynError, LocatedError}; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; use crate::CurrentClock; +/// HTTP tracker authentication key length. +/// +/// For more information see function [`generate_key`](crate::authentication::key::generate_key) to generate the +/// [`PeerKey`](crate::authentication::PeerKey). +pub const AUTH_KEY_LENGTH: usize = 32; + /// It generates a new permanent random key [`PeerKey`]. #[must_use] pub fn generate_permanent_key() -> PeerKey { @@ -200,7 +205,7 @@ impl Key { /// Error returned when a key cannot be parsed from a string. /// /// ```text -/// use torrust_tracker_lib::core::authentication::Key; +/// use bittorrent_tracker_core::authentication::Key; /// use std::str::FromStr; /// /// let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; @@ -230,7 +235,7 @@ impl FromStr for Key { } /// Verification error. Error returned when an [`PeerKey`] cannot be -/// verified with the (`crate::core::authentication::verify_key`) function. +/// verified with the (`crate::authentication::verify_key`) function. #[derive(Debug, Error)] #[allow(dead_code)] pub enum Error { @@ -261,7 +266,7 @@ mod tests { mod key { use std::str::FromStr; - use crate::core::authentication::Key; + use crate::authentication::Key; #[test] fn should_be_parsed_from_an_string() { @@ -296,7 +301,7 @@ mod tests { use torrust_tracker_clock::clock; use torrust_tracker_clock::clock::stopped::Stopped as _; - use crate::core::authentication; + use crate::authentication; #[test] fn should_be_parsed_from_an_string() { diff --git a/src/core/authentication/key/repository/in_memory.rs b/packages/tracker-core/src/authentication/key/repository/in_memory.rs similarity index 95% rename from src/core/authentication/key/repository/in_memory.rs rename to packages/tracker-core/src/authentication/key/repository/in_memory.rs index a15f9ecfa..41d34604b 100644 --- a/src/core/authentication/key/repository/in_memory.rs +++ b/packages/tracker-core/src/authentication/key/repository/in_memory.rs @@ -1,4 +1,4 @@ -use crate::core::authentication::key::{Key, PeerKey}; +use crate::authentication::key::{Key, PeerKey}; /// In-memory implementation of the authentication key repository. #[derive(Debug, Default)] diff --git a/src/core/authentication/key/repository/mod.rs b/packages/tracker-core/src/authentication/key/repository/mod.rs similarity index 100% rename from src/core/authentication/key/repository/mod.rs rename to packages/tracker-core/src/authentication/key/repository/mod.rs diff --git a/src/core/authentication/key/repository/persisted.rs b/packages/tracker-core/src/authentication/key/repository/persisted.rs similarity index 92% rename from src/core/authentication/key/repository/persisted.rs rename to packages/tracker-core/src/authentication/key/repository/persisted.rs index 736a409eb..322ab2913 100644 --- a/src/core/authentication/key/repository/persisted.rs +++ b/packages/tracker-core/src/authentication/key/repository/persisted.rs @@ -1,7 +1,7 @@ use std::sync::Arc; -use crate::core::authentication::key::{Key, PeerKey}; -use crate::core::databases::{self, Database}; +use crate::authentication::key::{Key, PeerKey}; +use crate::databases::{self, Database}; /// The database repository for the authentication keys. pub struct DatabaseKeyRepository { diff --git a/src/core/authentication/mod.rs b/packages/tracker-core/src/authentication/mod.rs similarity index 86% rename from src/core/authentication/mod.rs rename to packages/tracker-core/src/authentication/mod.rs index eddcc1ae7..9609733da 100644 --- a/src/core/authentication/mod.rs +++ b/packages/tracker-core/src/authentication/mod.rs @@ -22,12 +22,12 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; - use crate::core::authentication::handler::KeysHandler; - use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; - use crate::core::authentication::service; - use crate::core::authentication::service::AuthenticationService; - use crate::core::databases::setup::initialize_database; + use crate::authentication::handler::KeysHandler; + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::authentication::service; + use crate::authentication::service::AuthenticationService; + use crate::databases::setup::initialize_database; fn instantiate_keys_manager_and_authentication() -> (Arc, Arc) { let config = configuration::ephemeral_private(); @@ -97,11 +97,11 @@ mod tests { mod randomly_generated_keys { use std::time::Duration; - use crate::core::authentication::tests::the_tracker_configured_as_private::{ + use crate::authentication::tests::the_tracker_configured_as_private::{ instantiate_keys_manager_and_authentication, instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled, }; - use crate::core::authentication::Key; + use crate::authentication::Key; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { @@ -132,12 +132,12 @@ mod tests { mod pre_generated_keys { - use crate::core::authentication::handler::AddKeyRequest; - use crate::core::authentication::tests::the_tracker_configured_as_private::{ + use crate::authentication::handler::AddKeyRequest; + use crate::authentication::tests::the_tracker_configured_as_private::{ instantiate_keys_manager_and_authentication, instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled, }; - use crate::core::authentication::Key; + use crate::authentication::Key; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { @@ -177,7 +177,7 @@ mod tests { mod with_permanent_and { mod randomly_generated_keys { - use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication; + use crate::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { @@ -192,9 +192,9 @@ mod tests { } mod pre_generated_keys { - use crate::core::authentication::handler::AddKeyRequest; - use crate::core::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication; - use crate::core::authentication::Key; + use crate::authentication::handler::AddKeyRequest; + use crate::authentication::tests::the_tracker_configured_as_private::instantiate_keys_manager_and_authentication; + use crate::authentication::Key; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { diff --git a/src/core/authentication/service.rs b/packages/tracker-core/src/authentication/service.rs similarity index 93% rename from src/core/authentication/service.rs rename to packages/tracker-core/src/authentication/service.rs index d100e3a70..3e32bfbcb 100644 --- a/src/core/authentication/service.rs +++ b/packages/tracker-core/src/authentication/service.rs @@ -79,9 +79,9 @@ mod tests { use torrust_tracker_test_helpers::configuration; - use crate::core::authentication; - use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::core::authentication::service::AuthenticationService; + use crate::authentication; + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::service::AuthenticationService; fn instantiate_authentication() -> AuthenticationService { let config = configuration::ephemeral_private(); diff --git a/src/core/core_tests.rs b/packages/tracker-core/src/core_tests.rs similarity index 100% rename from src/core/core_tests.rs rename to packages/tracker-core/src/core_tests.rs diff --git a/src/core/databases/driver.rs b/packages/tracker-core/src/databases/driver.rs similarity index 90% rename from src/core/databases/driver.rs rename to packages/tracker-core/src/databases/driver.rs index b5cb797aa..7b532f3f0 100644 --- a/src/core/databases/driver.rs +++ b/packages/tracker-core/src/databases/driver.rs @@ -30,8 +30,8 @@ pub enum Driver { /// Example for `SQLite3`: /// /// ```text -/// use torrust_tracker_lib::core::databases; -/// use torrust_tracker_lib::core::databases::driver::Driver; +/// use bittorrent_tracker_core::databases; +/// use bittorrent_tracker_core::databases::driver::Driver; /// /// let db_driver = Driver::Sqlite3; /// let db_path = "./storage/tracker/lib/database/sqlite3.db".to_string(); @@ -41,8 +41,8 @@ pub enum Driver { /// Example for `MySQL`: /// /// ```text -/// use torrust_tracker_lib::core::databases; -/// use torrust_tracker_lib::core::databases::driver::Driver; +/// use bittorrent_tracker_core::databases; +/// use bittorrent_tracker_core::databases::driver::Driver; /// /// let db_driver = Driver::MySQL; /// let db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker".to_string(); diff --git a/src/core/databases/error.rs b/packages/tracker-core/src/databases/error.rs similarity index 100% rename from src/core/databases/error.rs rename to packages/tracker-core/src/databases/error.rs diff --git a/src/core/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs similarity index 98% rename from src/core/databases/mod.rs rename to packages/tracker-core/src/databases/mod.rs index dec6b799d..9b9ac8e9e 100644 --- a/src/core/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -55,7 +55,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::PersistentTorrents; use self::error::Error; -use crate::core::authentication::{self, Key}; +use crate::authentication::{self, Key}; struct Builder where @@ -200,7 +200,7 @@ pub trait Database: Sync + Send { /// It gets an expiring authentication key from the database. /// - /// It returns `Some(PeerKey)` if a [`PeerKey`](crate::core::authentication::PeerKey) + /// It returns `Some(PeerKey)` if a [`PeerKey`](crate::authentication::PeerKey) /// with the input [`Key`] exists, `None` otherwise. /// /// # Context: Authentication Keys diff --git a/src/core/databases/mysql.rs b/packages/tracker-core/src/databases/mysql.rs similarity index 98% rename from src/core/databases/mysql.rs rename to packages/tracker-core/src/databases/mysql.rs index 213f6300a..fb39b781d 100644 --- a/src/core/databases/mysql.rs +++ b/packages/tracker-core/src/databases/mysql.rs @@ -11,8 +11,8 @@ use torrust_tracker_primitives::PersistentTorrents; use super::driver::Driver; use super::{Database, Error}; -use crate::core::authentication::{self, Key}; -use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH; +use crate::authentication::key::AUTH_KEY_LENGTH; +use crate::authentication::{self, Key}; const DRIVER: Driver = Driver::MySQL; diff --git a/src/core/databases/setup.rs b/packages/tracker-core/src/databases/setup.rs similarity index 100% rename from src/core/databases/setup.rs rename to packages/tracker-core/src/databases/setup.rs diff --git a/src/core/databases/sqlite.rs b/packages/tracker-core/src/databases/sqlite.rs similarity index 99% rename from src/core/databases/sqlite.rs rename to packages/tracker-core/src/databases/sqlite.rs index 6fe9ac599..a7552ec11 100644 --- a/src/core/databases/sqlite.rs +++ b/packages/tracker-core/src/databases/sqlite.rs @@ -11,7 +11,7 @@ use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrents}; use super::driver::Driver; use super::{Database, Error}; -use crate::core::authentication::{self, Key}; +use crate::authentication::{self, Key}; const DRIVER: Driver = Driver::Sqlite3; diff --git a/src/core/error.rs b/packages/tracker-core/src/error.rs similarity index 100% rename from src/core/error.rs rename to packages/tracker-core/src/error.rs diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs new file mode 100644 index 000000000..2fb2d936d --- /dev/null +++ b/packages/tracker-core/src/lib.rs @@ -0,0 +1,585 @@ +//! The core `tracker` module contains the generic `BitTorrent` tracker logic which is independent of the delivery layer. +//! +//! It contains the tracker services and their dependencies. It's a domain layer which does not +//! specify how the end user should connect to the `Tracker`. +//! +//! Typically this module is intended to be used by higher modules like: +//! +//! - A UDP tracker +//! - A HTTP tracker +//! - A tracker REST API +//! +//! ```text +//! Delivery layer Domain layer +//! +//! HTTP tracker | +//! UDP tracker |> Core tracker +//! Tracker REST API | +//! ``` +//! +//! # Table of contents +//! +//! - [Tracker](#tracker) +//! - [Announce request](#announce-request) +//! - [Scrape request](#scrape-request) +//! - [Torrents](#torrents) +//! - [Peers](#peers) +//! - [Configuration](#configuration) +//! - [Services](#services) +//! - [Authentication](#authentication) +//! - [Statistics](#statistics) +//! - [Persistence](#persistence) +//! +//! # Tracker +//! +//! The `Tracker` is the main struct in this module. `The` tracker has some groups of responsibilities: +//! +//! - **Core tracker**: it handles the information about torrents and peers. +//! - **Authentication**: it handles authentication keys which are used by HTTP trackers. +//! - **Authorization**: it handles the permission to perform requests. +//! - **Whitelist**: when the tracker runs in `listed` or `private_listed` mode all operations are restricted to whitelisted torrents. +//! - **Statistics**: it keeps and serves the tracker statistics. +//! +//! Refer to [torrust-tracker-configuration](https://docs.rs/torrust-tracker-configuration) crate docs to get more information about the tracker settings. +//! +//! ## Announce request +//! +//! Handling `announce` requests is the most important task for a `BitTorrent` tracker. +//! +//! A `BitTorrent` swarm is a network of peers that are all trying to download the same torrent. +//! When a peer wants to find other peers it announces itself to the swarm via the tracker. +//! The peer sends its data to the tracker so that the tracker can add it to the swarm. +//! The tracker responds to the peer with the list of other peers in the swarm so that +//! the peer can contact them to start downloading pieces of the file from them. +//! +//! Once you have instantiated the `AnnounceHandler` you can `announce` a new [`peer::Peer`](torrust_tracker_primitives::peer::Peer) with: +//! +//! ```rust,no_run +//! use std::net::SocketAddr; +//! use std::net::IpAddr; +//! use std::net::Ipv4Addr; +//! use std::str::FromStr; +//! +//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; +//! use torrust_tracker_primitives::peer; +//! use bittorrent_primitives::info_hash::InfoHash; +//! +//! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); +//! +//! let peer = peer::Peer { +//! peer_id: PeerId(*b"-qB00000000000000001"), +//! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), +//! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), +//! uploaded: NumberOfBytes::new(0), +//! downloaded: NumberOfBytes::new(0), +//! left: NumberOfBytes::new(0), +//! event: AnnounceEvent::Completed, +//! }; +//! +//! let peer_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); +//! ``` +//! +//! ```text +//! let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip).await; +//! ``` +//! +//! The `Tracker` returns the list of peers for the torrent with the infohash `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`, +//! filtering out the peer that is making the `announce` request. +//! +//! > **NOTICE**: that the peer argument is mutable because the `Tracker` can change the peer IP if the peer is using a loopback IP. +//! +//! The `peer_ip` argument is the resolved peer ip. It's a common practice that trackers ignore the peer ip in the `announce` request params, +//! and resolve the peer ip using the IP of the client making the request. As the tracker is a domain service, the peer IP must be provided +//! for the `Tracker` user, which is usually a higher component with access the the request metadata, for example, connection data, proxy headers, +//! etcetera. +//! +//! The returned struct is: +//! +//! ```rust,no_run +//! use torrust_tracker_primitives::peer; +//! use torrust_tracker_configuration::AnnouncePolicy; +//! +//! pub struct AnnounceData { +//! pub peers: Vec, +//! pub swarm_stats: SwarmMetadata, +//! pub policy: AnnouncePolicy, // the tracker announce policy. +//! } +//! +//! pub struct SwarmMetadata { +//! pub completed: u32, // The number of peers that have ever completed downloading +//! pub seeders: u32, // The number of active peers that have completed downloading (seeders) +//! pub leechers: u32, // The number of active peers that have not completed downloading (leechers) +//! } +//! +//! // Core tracker configuration +//! pub struct AnnounceInterval { +//! // ... +//! pub interval: u32, // Interval in seconds that the client should wait between sending regular announce requests to the tracker +//! pub interval_min: u32, // Minimum announce interval. Clients must not reannounce more frequently than this +//! // ... +//! } +//! ``` +//! +//! Refer to `BitTorrent` BEPs and other sites for more information about the `announce` request: +//! +//! - [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) +//! - [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) +//! - [Vuze docs](https://wiki.vuze.com/w/Announce) +//! +//! ## Scrape request +//! +//! The `scrape` request allows clients to query metadata about the swarm in bulk. +//! +//! An `scrape` request includes a list of infohashes whose swarm metadata you want to collect. +//! +//! The returned struct is: +//! +//! ```rust,no_run +//! use bittorrent_primitives::info_hash::InfoHash; +//! use std::collections::HashMap; +//! +//! pub struct ScrapeData { +//! pub files: HashMap, +//! } +//! +//! pub struct SwarmMetadata { +//! pub complete: u32, // The number of active peers that have completed downloading (seeders) +//! pub downloaded: u32, // The number of peers that have ever completed downloading +//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) +//! } +//! ``` +//! +//! The JSON representation of a sample `scrape` response would be like the following: +//! +//! ```json +//! { +//! 'files': { +//! 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19}, +//! 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20} +//! } +//! } +//! ``` +//! +//! `xxxxxxxxxxxxxxxxxxxx` and `yyyyyyyyyyyyyyyyyyyy` are 20-byte infohash arrays. +//! There are two data structures for infohashes: byte arrays and hex strings: +//! +//! ```rust,no_run +//! use bittorrent_primitives::info_hash::InfoHash; +//! use std::str::FromStr; +//! +//! let info_hash: InfoHash = [255u8; 20].into(); +//! +//! assert_eq!( +//! info_hash, +//! InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() +//! ); +//! ``` +//! Refer to `BitTorrent` BEPs and other sites for more information about the `scrape` request: +//! +//! - [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) +//! - [BEP 15. UDP Tracker Protocol for `BitTorrent`. Scrape section](https://www.bittorrent.org/beps/bep_0015.html) +//! - [Vuze docs](https://wiki.vuze.com/w/Scrape) +//! +//! ## Torrents +//! +//! The [`torrent`] module contains all the data structures stored by the `Tracker` except for peers. +//! +//! We can represent the data stored in memory internally by the `Tracker` with this JSON object: +//! +//! ```json +//! { +//! "c1277613db1d28709b034a017ab2cae4be07ae10": { +//! "completed": 0, +//! "peers": { +//! "-qB00000000000000001": { +//! "peer_id": "-qB00000000000000001", +//! "peer_addr": "2.137.87.41:1754", +//! "updated": 1672419840, +//! "uploaded": 120, +//! "downloaded": 60, +//! "left": 60, +//! "event": "started" +//! }, +//! "-qB00000000000000002": { +//! "peer_id": "-qB00000000000000002", +//! "peer_addr": "23.17.287.141:2345", +//! "updated": 1679415984, +//! "uploaded": 80, +//! "downloaded": 20, +//! "left": 40, +//! "event": "started" +//! } +//! } +//! } +//! } +//! ``` +//! +//! The `Tracker` maintains an indexed-by-info-hash list of torrents. For each torrent, it stores a torrent `Entry`. +//! The torrent entry has two attributes: +//! +//! - `completed`: which is hte number of peers that have completed downloading the torrent file/s. As they have completed downloading, +//! they have a full version of the torrent data, and they can provide the full data to other peers. That's why they are also known as "seeders". +//! - `peers`: an indexed and orderer list of peer for the torrent. Each peer contains the data received from the peer in the `announce` request. +//! +//! The [`torrent`] module not only contains the original data obtained from peer via `announce` requests, it also contains +//! aggregate data that can be derived from the original data. For example: +//! +//! ```rust,no_run +//! pub struct SwarmMetadata { +//! pub complete: u32, // The number of active peers that have completed downloading (seeders) +//! pub downloaded: u32, // The number of peers that have ever completed downloading +//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) +//! } +//! +//! ``` +//! +//! > **NOTICE**: that `complete` or `completed` peers are the peers that have completed downloading, but only the active ones are considered "seeders". +//! +//! `SwarmMetadata` struct follows name conventions for `scrape` responses. See [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmMetadata` +//! is used for the rest of cases. +//! +//! Refer to [`torrent`] module for more details about these data structures. +//! +//! ## Peers +//! +//! A `Peer` is the struct used by the `Tracker` to keep peers data: +//! +//! ```rust,no_run +//! use std::net::SocketAddr; + +//! use aquatic_udp_protocol::PeerId; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; +//! use aquatic_udp_protocol::NumberOfBytes; +//! use aquatic_udp_protocol::AnnounceEvent; +//! +//! pub struct Peer { +//! pub peer_id: PeerId, // The peer ID +//! pub peer_addr: SocketAddr, // Peer socket address +//! pub updated: DurationSinceUnixEpoch, // Last time (timestamp) when the peer was updated +//! pub uploaded: NumberOfBytes, // Number of bytes the peer has uploaded so far +//! pub downloaded: NumberOfBytes, // Number of bytes the peer has downloaded so far +//! pub left: NumberOfBytes, // The number of bytes this peer still has to download +//! pub event: AnnounceEvent, // The event the peer has announced: `started`, `completed`, `stopped` +//! } +//! ``` +//! +//! Notice that most of the attributes are obtained from the `announce` request. +//! For example, an HTTP announce request would contain the following `GET` parameters: +//! +//! +//! +//! The `Tracker` keeps an in-memory ordered data structure with all the torrents and a list of peers for each torrent, together with some swarm metrics. +//! +//! We can represent the data stored in memory with this JSON object: +//! +//! ```json +//! { +//! "c1277613db1d28709b034a017ab2cae4be07ae10": { +//! "completed": 0, +//! "peers": { +//! "-qB00000000000000001": { +//! "peer_id": "-qB00000000000000001", +//! "peer_addr": "2.137.87.41:1754", +//! "updated": 1672419840, +//! "uploaded": 120, +//! "downloaded": 60, +//! "left": 60, +//! "event": "started" +//! }, +//! "-qB00000000000000002": { +//! "peer_id": "-qB00000000000000002", +//! "peer_addr": "23.17.287.141:2345", +//! "updated": 1679415984, +//! "uploaded": 80, +//! "downloaded": 20, +//! "left": 40, +//! "event": "started" +//! } +//! } +//! } +//! } +//! ``` +//! +//! That JSON object does not exist, it's only a representation of the `Tracker` torrents data. +//! +//! `c1277613db1d28709b034a017ab2cae4be07ae10` is the torrent infohash and `completed` contains the number of peers +//! that have a full version of the torrent data, also known as seeders. +//! +//! Refer to [`peer`](torrust_tracker_primitives::peer) for more information about peers. +//! +//! # Configuration +//! +//! You can control the behavior of this module with the module settings: +//! +//! ```toml +//! [logging] +//! threshold = "debug" +//! +//! [core] +//! inactive_peer_cleanup_interval = 600 +//! listed = false +//! private = false +//! tracker_usage_statistics = true +//! +//! [core.announce_policy] +//! interval = 120 +//! interval_min = 120 +//! +//! [core.database] +//! driver = "sqlite3" +//! path = "./storage/tracker/lib/database/sqlite3.db" +//! +//! [core.net] +//! on_reverse_proxy = false +//! external_ip = "2.137.87.41" +//! +//! [core.tracker_policy] +//! max_peer_timeout = 900 +//! persistent_torrent_completed_stat = false +//! remove_peerless_torrents = true +//! ``` +//! +//! Refer to the [`configuration` module documentation](https://docs.rs/torrust-tracker-configuration) to get more information about all options. +//! +//! # Services +//! +//! Services are domain services on top of the core tracker domain. Right now there are two types of service: +//! +//! - For statistics: [`crate::core::statistics::services`] +//! - For torrents: [`crate::core::torrent::services`] +//! +//! Services usually format the data inside the tracker to make it easier to consume by other parts. +//! They also decouple the internal data structure, used by the tracker, from the way we deliver that data to the consumers. +//! The internal data structure is designed for performance or low memory consumption. And it should be changed +//! without affecting the external consumers. +//! +//! Services can include extra features like pagination, for example. +//! +//! # Authentication +//! +//! One of the core `Tracker` responsibilities is to create and keep authentication keys. Auth keys are used by HTTP trackers +//! when the tracker is running in `private` or `private_listed` mode. +//! +//! HTTP tracker's clients need to obtain an auth key before starting requesting the tracker. Once the get one they have to include +//! a `PATH` param with the key in all the HTTP requests. For example, when a peer wants to `announce` itself it has to use the +//! HTTP tracker endpoint `GET /announce/:key`. +//! +//! The common way to obtain the keys is by using the tracker API directly or via other applications like the [Torrust Index](https://github.com/torrust/torrust-index). +//! +//! To learn more about tracker authentication, refer to the following modules : +//! +//! - [`authentication`] module. +//! - [`core`](crate::core) module. +//! - [`http`](crate::servers::http) module. +//! +//! # Statistics +//! +//! The `Tracker` keeps metrics for some events: +//! +//! ```rust,no_run +//! pub struct Metrics { +//! // IP version 4 +//! +//! // HTTP tracker +//! pub tcp4_connections_handled: u64, +//! pub tcp4_announces_handled: u64, +//! pub tcp4_scrapes_handled: u64, +//! +//! // UDP tracker +//! pub udp4_connections_handled: u64, +//! pub udp4_announces_handled: u64, +//! pub udp4_scrapes_handled: u64, +//! +//! // IP version 6 +//! +//! // HTTP tracker +//! pub tcp6_connections_handled: u64, +//! pub tcp6_announces_handled: u64, +//! pub tcp6_scrapes_handled: u64, +//! +//! // UDP tracker +//! pub udp6_connections_handled: u64, +//! pub udp6_announces_handled: u64, +//! pub udp6_scrapes_handled: u64, +//! } +//! ``` +//! +//! The metrics maintained by the `Tracker` are: +//! +//! - `connections_handled`: number of connections handled by the tracker +//! - `announces_handled`: number of `announce` requests handled by the tracker +//! - `scrapes_handled`: number of `scrape` handled requests by the tracker +//! +//! > **NOTICE**: as the HTTP tracker does not have an specific `connection` request like the UDP tracker, `connections_handled` are +//! > increased on every `announce` and `scrape` requests. +//! +//! The tracker exposes an event sender API that allows the tracker users to send events. When a higher application service handles a +//! `connection` , `announce` or `scrape` requests, it notifies the `Tracker` by sending statistics events. +//! +//! For example, the HTTP tracker would send an event like the following when it handles an `announce` request received from a peer using IP version 4. +//! +//! ```text +//! stats_event_sender.send_stats_event(statistics::event::Event::Tcp4Announce).await +//! ``` +//! +//! Refer to [`statistics`] module for more information about statistics. +//! +//! # Persistence +//! +//! Right now the `Tracker` is responsible for storing and load data into and +//! from the database, when persistence is enabled. +//! +//! There are three types of persistent object: +//! +//! - Authentication keys (only expiring keys) +//! - Torrent whitelist +//! - Torrent metrics +//! +//! Refer to [`databases`] module for more information about persistence. +pub mod announce_handler; +pub mod authentication; +pub mod databases; +pub mod error; +pub mod scrape_handler; +pub mod statistics; +pub mod torrent; +pub mod whitelist; + +pub mod core_tests; +pub mod peer_tests; + +use torrust_tracker_clock::clock; +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; + +#[cfg(test)] +mod tests { + mod the_tracker { + use std::net::{IpAddr, Ipv4Addr}; + use std::str::FromStr; + use std::sync::Arc; + + use torrust_tracker_test_helpers::configuration; + + use crate::announce_handler::AnnounceHandler; + use crate::core_tests::initialize_handlers; + use crate::scrape_handler::ScrapeHandler; + + fn initialize_handlers_for_public_tracker() -> (Arc, Arc) { + let config = configuration::ephemeral_public(); + initialize_handlers(&config) + } + + fn initialize_handlers_for_listed_tracker() -> (Arc, Arc) { + let config = configuration::ephemeral_listed(); + initialize_handlers(&config) + } + + // The client peer IP + fn peer_ip() -> IpAddr { + IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) + } + + mod for_all_config_modes { + + mod handling_a_scrape_request { + + use std::net::{IpAddr, Ipv4Addr}; + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::announce_handler::PeersWanted; + use crate::core_tests::{complete_peer, incomplete_peer}; + use crate::tests::the_tracker::initialize_handlers_for_public_tracker; + + #[tokio::test] + async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() { + let (announce_handler, scrape_handler) = initialize_handlers_for_public_tracker(); + + let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237 + + // Announce a "complete" peer for the torrent + let mut complete_peer = complete_peer(); + announce_handler.announce( + &info_hash, + &mut complete_peer, + &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10)), + &PeersWanted::All, + ); + + // Announce an "incomplete" peer for the torrent + let mut incomplete_peer = incomplete_peer(); + announce_handler.announce( + &info_hash, + &mut incomplete_peer, + &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11)), + &PeersWanted::All, + ); + + // Scrape + let scrape_data = scrape_handler.scrape(&vec![info_hash]).await; + + // The expected swarm metadata for the file + let mut expected_scrape_data = ScrapeData::empty(); + expected_scrape_data.add_file( + &info_hash, + SwarmMetadata { + complete: 0, // the "complete" peer does not count because it was not previously known + downloaded: 0, + incomplete: 1, // the "incomplete" peer we have just announced + }, + ); + + assert_eq!(scrape_data, expected_scrape_data); + } + } + } + + mod configured_as_whitelisted { + + mod handling_a_scrape_request { + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::announce_handler::PeersWanted; + use crate::core_tests::{complete_peer, incomplete_peer}; + use crate::tests::the_tracker::{initialize_handlers_for_listed_tracker, peer_ip}; + + #[tokio::test] + async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { + let (announce_handler, scrape_handler) = initialize_handlers_for_listed_tracker(); + + let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237 + + let mut peer = incomplete_peer(); + announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + + // Announce twice to force non zeroed swarm metadata + let mut peer = complete_peer(); + announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + + let scrape_data = scrape_handler.scrape(&vec![info_hash]).await; + + // The expected zeroed swarm metadata for the file + let mut expected_scrape_data = ScrapeData::empty(); + expected_scrape_data.add_file(&info_hash, SwarmMetadata::zeroed()); + + assert_eq!(scrape_data, expected_scrape_data); + } + } + } + } +} diff --git a/src/core/peer_tests.rs b/packages/tracker-core/src/peer_tests.rs similarity index 100% rename from src/core/peer_tests.rs rename to packages/tracker-core/src/peer_tests.rs diff --git a/src/core/scrape_handler.rs b/packages/tracker-core/src/scrape_handler.rs similarity index 95% rename from src/core/scrape_handler.rs rename to packages/tracker-core/src/scrape_handler.rs index 33bb6ca6a..60d15de71 100644 --- a/src/core/scrape_handler.rs +++ b/packages/tracker-core/src/scrape_handler.rs @@ -54,9 +54,9 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::ScrapeHandler; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - use crate::core::whitelist::{self}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::whitelist::{self}; fn scrape_handler() -> ScrapeHandler { let config = configuration::ephemeral_public(); diff --git a/src/core/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs similarity index 96% rename from src/core/statistics/event/handler.rs rename to packages/tracker-core/src/statistics/event/handler.rs index 3c435145a..93ac05dde 100644 --- a/src/core/statistics/event/handler.rs +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -1,5 +1,5 @@ -use crate::core::statistics::event::{Event, UdpResponseKind}; -use crate::core::statistics::repository::Repository; +use crate::statistics::event::{Event, UdpResponseKind}; +use crate::statistics::repository::Repository; pub async fn handle_event(event: Event, stats_repository: &Repository) { match event { @@ -102,9 +102,9 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { #[cfg(test)] mod tests { - use crate::core::statistics::event::handler::handle_event; - use crate::core::statistics::event::Event; - use crate::core::statistics::repository::Repository; + use crate::statistics::event::handler::handle_event; + use crate::statistics::event::Event; + use crate::statistics::repository::Repository; #[tokio::test] async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { diff --git a/src/core/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs similarity index 84% rename from src/core/statistics/event/listener.rs rename to packages/tracker-core/src/statistics/event/listener.rs index 89ed7b41a..f1a2e25de 100644 --- a/src/core/statistics/event/listener.rs +++ b/packages/tracker-core/src/statistics/event/listener.rs @@ -2,7 +2,7 @@ use tokio::sync::mpsc; use super::handler::handle_event; use super::Event; -use crate::core::statistics::repository::Repository; +use crate::statistics::repository::Repository; pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) { while let Some(event) = receiver.recv().await { diff --git a/src/core/statistics/event/mod.rs b/packages/tracker-core/src/statistics/event/mod.rs similarity index 100% rename from src/core/statistics/event/mod.rs rename to packages/tracker-core/src/statistics/event/mod.rs diff --git a/src/core/statistics/event/sender.rs b/packages/tracker-core/src/statistics/event/sender.rs similarity index 100% rename from src/core/statistics/event/sender.rs rename to packages/tracker-core/src/statistics/event/sender.rs diff --git a/src/core/statistics/keeper.rs b/packages/tracker-core/src/statistics/keeper.rs similarity index 93% rename from src/core/statistics/keeper.rs rename to packages/tracker-core/src/statistics/keeper.rs index 5427734e1..a3d4542f7 100644 --- a/src/core/statistics/keeper.rs +++ b/packages/tracker-core/src/statistics/keeper.rs @@ -51,9 +51,9 @@ impl Keeper { #[cfg(test)] mod tests { - use crate::core::statistics::event::Event; - use crate::core::statistics::keeper::Keeper; - use crate::core::statistics::metrics::Metrics; + use crate::statistics::event::Event; + use crate::statistics::keeper::Keeper; + use crate::statistics::metrics::Metrics; #[tokio::test] async fn should_contain_the_tracker_statistics() { diff --git a/src/core/statistics/metrics.rs b/packages/tracker-core/src/statistics/metrics.rs similarity index 100% rename from src/core/statistics/metrics.rs rename to packages/tracker-core/src/statistics/metrics.rs diff --git a/packages/tracker-core/src/statistics/mod.rs b/packages/tracker-core/src/statistics/mod.rs new file mode 100644 index 000000000..2ffbc0c8f --- /dev/null +++ b/packages/tracker-core/src/statistics/mod.rs @@ -0,0 +1,32 @@ +//! Structs to collect and keep tracker metrics. +//! +//! The tracker collects metrics such as: +//! +//! - Number of connections handled +//! - Number of `announce` requests handled +//! - Number of `scrape` request handled +//! +//! These metrics are collected for each connection type: UDP and HTTP and +//! also for each IP version used by the peers: IPv4 and IPv6. +//! +//! > Notice: that UDP tracker have an specific `connection` request. For the +//! > `HTTP` metrics the counter counts one connection for each `announce` or +//! > `scrape` request. +//! +//! The data is collected by using an `event-sender -> event listener` model. +//! +//! The tracker uses a [`Sender`](crate::core::statistics::event::sender::Sender) +//! instance to send an event. +//! +//! The [`statistics::keeper::Keeper`](crate::core::statistics::keeper::Keeper) listens to new +//! events and uses the [`statistics::repository::Repository`](crate::core::statistics::repository::Repository) to +//! upgrade and store metrics. +//! +//! See the [`statistics::event::Event`](crate::core::statistics::event::Event) enum to check +//! which events are available. +pub mod event; +pub mod keeper; +pub mod metrics; +pub mod repository; +pub mod services; +pub mod setup; diff --git a/src/core/statistics/repository.rs b/packages/tracker-core/src/statistics/repository.rs similarity index 100% rename from src/core/statistics/repository.rs rename to packages/tracker-core/src/statistics/repository.rs diff --git a/packages/tracker-core/src/statistics/services.rs b/packages/tracker-core/src/statistics/services.rs new file mode 100644 index 000000000..196c6b340 --- /dev/null +++ b/packages/tracker-core/src/statistics/services.rs @@ -0,0 +1,55 @@ +//! Statistics services. +//! +//! It includes: +//! +//! - A [`factory`](crate::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::core::statistics::metrics::Metrics). +//! +//! Tracker metrics are collected using a Publisher-Subscribe pattern. +//! +//! The factory function builds two structs: +//! +//! - An statistics event [`Sender`](crate::core::statistics::event::sender::Sender) +//! - An statistics [`Repository`] +//! +//! ```text +//! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); +//! ``` +//! +//! The statistics repository is responsible for storing the metrics in memory. +//! The statistics event sender allows sending events related to metrics. +//! There is an event listener that is receiving all the events and processing them with an event handler. +//! Then, the event handler updates the metrics depending on the received event. +//! +//! For example, if you send the event [`Event::Udp4Connect`](crate::core::statistics::event::Event::Udp4Connect): +//! +//! ```text +//! let result = event_sender.send_event(Event::Udp4Connect).await; +//! ``` +//! +//! Eventually the counter for UDP connections from IPv4 peers will be increased. +//! +//! ```rust,no_run +//! pub struct Metrics { +//! // ... +//! pub udp4_connections_handled: u64, // This will be incremented +//! // ... +//! } +//! ``` +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + +use crate::statistics::metrics::Metrics; + +/// All the metrics collected by the tracker. +#[derive(Debug, PartialEq)] +pub struct TrackerMetrics { + /// Domain level metrics. + /// + /// General metrics for all torrents (number of seeders, leechers, etcetera) + pub torrents_metrics: TorrentsMetrics, + + /// Application level metrics. Usage statistics/metrics. + /// + /// Metrics about how the tracker is been used (number of udp announce requests, number of http scrape requests, etcetera) + pub protocol_metrics: Metrics, +} diff --git a/src/core/statistics/setup.rs b/packages/tracker-core/src/statistics/setup.rs similarity index 98% rename from src/core/statistics/setup.rs rename to packages/tracker-core/src/statistics/setup.rs index e440a709c..701392176 100644 --- a/src/core/statistics/setup.rs +++ b/packages/tracker-core/src/statistics/setup.rs @@ -1,7 +1,7 @@ //! Setup for the tracker statistics. //! //! The [`factory`] function builds the structs needed for handling the tracker metrics. -use crate::core::statistics; +use crate::statistics; /// It builds the structs needed for handling the tracker metrics. /// diff --git a/src/core/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs similarity index 97% rename from src/core/torrent/manager.rs rename to packages/tracker-core/src/torrent/manager.rs index 261376755..4199e9944 100644 --- a/src/core/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -6,8 +6,7 @@ use torrust_tracker_configuration::Core; use super::repository::in_memory::InMemoryTorrentRepository; use super::repository::persisted::DatabasePersistentTorrentRepository; -use crate::core::databases; -use crate::CurrentClock; +use crate::{databases, CurrentClock}; pub struct TorrentsManager { /// The tracker configuration. diff --git a/src/core/torrent/mod.rs b/packages/tracker-core/src/torrent/mod.rs similarity index 100% rename from src/core/torrent/mod.rs rename to packages/tracker-core/src/torrent/mod.rs diff --git a/src/core/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs similarity index 98% rename from src/core/torrent/repository/in_memory.rs rename to packages/tracker-core/src/torrent/repository/in_memory.rs index 2e80a2e9b..b9979577a 100644 --- a/src/core/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -11,7 +11,7 @@ use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; use torrust_tracker_torrent_repository::EntryMutexStd; -use crate::core::torrent::Torrents; +use crate::torrent::Torrents; /// The in-memory torrents repository. /// @@ -114,8 +114,8 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::core::core_tests::{leecher, sample_info_hash, sample_peer}; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::core_tests::{leecher, sample_info_hash, sample_peer}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; /// It generates a peer id from a number where the number is the last /// part of the peer ID. For example, for `12` it returns diff --git a/src/core/torrent/repository/mod.rs b/packages/tracker-core/src/torrent/repository/mod.rs similarity index 100% rename from src/core/torrent/repository/mod.rs rename to packages/tracker-core/src/torrent/repository/mod.rs diff --git a/src/core/torrent/repository/persisted.rs b/packages/tracker-core/src/torrent/repository/persisted.rs similarity index 94% rename from src/core/torrent/repository/persisted.rs rename to packages/tracker-core/src/torrent/repository/persisted.rs index 86a3db0e3..77a9c23eb 100644 --- a/src/core/torrent/repository/persisted.rs +++ b/packages/tracker-core/src/torrent/repository/persisted.rs @@ -3,8 +3,8 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::PersistentTorrents; -use crate::core::databases::error::Error; -use crate::core::databases::Database; +use crate::databases::error::Error; +use crate::databases::Database; /// Torrent repository implementation that persists the torrents in a database. /// diff --git a/src/core/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs similarity index 85% rename from src/core/torrent/services.rs rename to packages/tracker-core/src/torrent/services.rs index 5a4810412..2275f20d0 100644 --- a/src/core/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -11,7 +11,7 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::peer; use torrust_tracker_torrent_repository::entry::EntrySync; -use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; +use crate::torrent::repository::in_memory::InMemoryTorrentRepository; /// It contains all the information the tracker has about a torrent #[derive(Debug, PartialEq)] @@ -44,10 +44,8 @@ pub struct BasicInfo { } /// It returns all the information the tracker has about one torrent in a [Info] struct. -pub async fn get_torrent_info( - in_memory_torrent_repository: Arc, - info_hash: &InfoHash, -) -> Option { +#[must_use] +pub fn get_torrent_info(in_memory_torrent_repository: &Arc, info_hash: &InfoHash) -> Option { let torrent_entry_option = in_memory_torrent_repository.get(info_hash); let torrent_entry = torrent_entry_option?; @@ -68,8 +66,9 @@ pub async fn get_torrent_info( } /// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list. -pub async fn get_torrents_page( - in_memory_torrent_repository: Arc, +#[must_use] +pub fn get_torrents_page( + in_memory_torrent_repository: &Arc, pagination: Option<&Pagination>, ) -> Vec { let mut basic_infos: Vec = vec![]; @@ -89,10 +88,8 @@ pub async fn get_torrents_page( } /// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list. -pub async fn get_torrents( - in_memory_torrent_repository: Arc, - info_hashes: &[InfoHash], -) -> Vec { +#[must_use] +pub fn get_torrents(in_memory_torrent_repository: &Arc, info_hashes: &[InfoHash]) -> Vec { let mut basic_infos: Vec = vec![]; for info_hash in info_hashes { @@ -135,19 +132,18 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::torrent::services::tests::sample_peer; - use crate::core::torrent::services::{get_torrent_info, Info}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::torrent::services::tests::sample_peer; + use crate::torrent::services::{get_torrent_info, Info}; #[tokio::test] async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let torrent_info = get_torrent_info( - in_memory_torrent_repository.clone(), + &in_memory_torrent_repository, &InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(), // DevSkim: ignore DS173237 - ) - .await; + ); assert!(torrent_info.is_none()); } @@ -160,9 +156,7 @@ mod tests { let info_hash = InfoHash::from_str(&hash).unwrap(); let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); - let torrent_info = get_torrent_info(in_memory_torrent_repository.clone(), &info_hash) - .await - .unwrap(); + let torrent_info = get_torrent_info(&in_memory_torrent_repository, &info_hash).unwrap(); assert_eq!( torrent_info, @@ -184,15 +178,15 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::torrent::services::tests::sample_peer; - use crate::core::torrent::services::{get_torrents_page, BasicInfo, Pagination}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::torrent::services::tests::sample_peer; + use crate::torrent::services::{get_torrents_page, BasicInfo, Pagination}; #[tokio::test] async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::default())).await; + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); assert_eq!(torrents, vec![]); } @@ -206,7 +200,7 @@ mod tests { let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); - let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::default())).await; + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); assert_eq!( torrents, @@ -235,7 +229,7 @@ mod tests { let offset = 0; let limit = 1; - let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::new(offset, limit))).await; + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::new(offset, limit))); assert_eq!(torrents.len(), 1); } @@ -256,7 +250,7 @@ mod tests { let offset = 1; let limit = 4000; - let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::new(offset, limit))).await; + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::new(offset, limit))); assert_eq!(torrents.len(), 1); assert_eq!( @@ -282,7 +276,7 @@ mod tests { let info_hash2 = InfoHash::from_str(&hash2).unwrap(); let () = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); - let torrents = get_torrents_page(in_memory_torrent_repository.clone(), Some(&Pagination::default())).await; + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); assert_eq!( torrents, diff --git a/src/core/whitelist/authorization.rs b/packages/tracker-core/src/whitelist/authorization.rs similarity index 93% rename from src/core/whitelist/authorization.rs rename to packages/tracker-core/src/whitelist/authorization.rs index 1a6d8b758..285f6613e 100644 --- a/src/core/whitelist/authorization.rs +++ b/packages/tracker-core/src/whitelist/authorization.rs @@ -6,7 +6,7 @@ use torrust_tracker_configuration::Core; use tracing::instrument; use super::repository::in_memory::InMemoryWhitelist; -use crate::core::error::Error; +use crate::error::Error; pub struct WhitelistAuthorization { /// Core tracker configuration. @@ -64,8 +64,8 @@ mod tests { mod configured_as_whitelisted { mod handling_authorization { - use crate::core::core_tests::sample_info_hash; - use crate::core::whitelist::whitelist_tests::initialize_whitelist_services_for_listed_tracker; + use crate::core_tests::sample_info_hash; + use crate::whitelist::whitelist_tests::initialize_whitelist_services_for_listed_tracker; #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { diff --git a/src/core/whitelist/manager.rs b/packages/tracker-core/src/whitelist/manager.rs similarity index 91% rename from src/core/whitelist/manager.rs rename to packages/tracker-core/src/whitelist/manager.rs index 0d9751994..c78a59470 100644 --- a/src/core/whitelist/manager.rs +++ b/packages/tracker-core/src/whitelist/manager.rs @@ -4,7 +4,7 @@ use bittorrent_primitives::info_hash::InfoHash; use super::repository::in_memory::InMemoryWhitelist; use super::repository::persisted::DatabaseWhitelist; -use crate::core::databases; +use crate::databases; /// It handles the list of allowed torrents. Only for listed trackers. pub struct WhitelistManager { @@ -97,8 +97,8 @@ mod tests { use torrust_tracker_test_helpers::configuration; - use crate::core::whitelist::manager::WhitelistManager; - use crate::core::whitelist::whitelist_tests::initialize_whitelist_services; + use crate::whitelist::manager::WhitelistManager; + use crate::whitelist::whitelist_tests::initialize_whitelist_services; fn initialize_whitelist_manager_for_whitelisted_tracker() -> Arc { let config = configuration::ephemeral_listed(); @@ -111,8 +111,8 @@ mod tests { mod configured_as_whitelisted { mod handling_the_torrent_whitelist { - use crate::core::core_tests::sample_info_hash; - use crate::core::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker; + use crate::core_tests::sample_info_hash; + use crate::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker; #[tokio::test] async fn it_should_add_a_torrent_to_the_whitelist() { @@ -139,8 +139,8 @@ mod tests { } mod persistence { - use crate::core::core_tests::sample_info_hash; - use crate::core::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker; + use crate::core_tests::sample_info_hash; + use crate::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker; #[tokio::test] async fn it_should_load_the_whitelist_from_the_database() { diff --git a/src/core/whitelist/mod.rs b/packages/tracker-core/src/whitelist/mod.rs similarity index 88% rename from src/core/whitelist/mod.rs rename to packages/tracker-core/src/whitelist/mod.rs index 1f5f87626..8521485f7 100644 --- a/src/core/whitelist/mod.rs +++ b/packages/tracker-core/src/whitelist/mod.rs @@ -10,8 +10,8 @@ mod tests { mod configured_as_whitelisted { mod handling_authorization { - use crate::core::core_tests::sample_info_hash; - use crate::core::whitelist::whitelist_tests::initialize_whitelist_services_for_listed_tracker; + use crate::core_tests::sample_info_hash; + use crate::whitelist::whitelist_tests::initialize_whitelist_services_for_listed_tracker; #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { diff --git a/src/core/whitelist/repository/in_memory.rs b/packages/tracker-core/src/whitelist/repository/in_memory.rs similarity index 94% rename from src/core/whitelist/repository/in_memory.rs rename to packages/tracker-core/src/whitelist/repository/in_memory.rs index f023c1610..befd6fed6 100644 --- a/src/core/whitelist/repository/in_memory.rs +++ b/packages/tracker-core/src/whitelist/repository/in_memory.rs @@ -33,8 +33,8 @@ impl InMemoryWhitelist { #[cfg(test)] mod tests { - use crate::core::core_tests::sample_info_hash; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::core_tests::sample_info_hash; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; #[tokio::test] async fn should_allow_adding_a_new_torrent_to_the_whitelist() { diff --git a/src/core/whitelist/repository/mod.rs b/packages/tracker-core/src/whitelist/repository/mod.rs similarity index 100% rename from src/core/whitelist/repository/mod.rs rename to packages/tracker-core/src/whitelist/repository/mod.rs diff --git a/src/core/whitelist/repository/persisted.rs b/packages/tracker-core/src/whitelist/repository/persisted.rs similarity index 97% rename from src/core/whitelist/repository/persisted.rs rename to packages/tracker-core/src/whitelist/repository/persisted.rs index fd56d56b5..c3c4a2601 100644 --- a/src/core/whitelist/repository/persisted.rs +++ b/packages/tracker-core/src/whitelist/repository/persisted.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; -use crate::core::databases::{self, Database}; +use crate::databases::{self, Database}; /// The persisted list of allowed torrents. pub struct DatabaseWhitelist { diff --git a/src/core/whitelist/setup.rs b/packages/tracker-core/src/whitelist/setup.rs similarity index 92% rename from src/core/whitelist/setup.rs rename to packages/tracker-core/src/whitelist/setup.rs index bdd35737c..5b2a5de40 100644 --- a/src/core/whitelist/setup.rs +++ b/packages/tracker-core/src/whitelist/setup.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use super::manager::WhitelistManager; use super::repository::in_memory::InMemoryWhitelist; use super::repository::persisted::DatabaseWhitelist; -use crate::core::databases::Database; +use crate::databases::Database; #[must_use] pub fn initialize_whitelist_manager( diff --git a/src/core/whitelist/whitelist_tests.rs b/packages/tracker-core/src/whitelist/whitelist_tests.rs similarity index 89% rename from src/core/whitelist/whitelist_tests.rs rename to packages/tracker-core/src/whitelist/whitelist_tests.rs index 38c2bbde3..33f5a97f7 100644 --- a/src/core/whitelist/whitelist_tests.rs +++ b/packages/tracker-core/src/whitelist/whitelist_tests.rs @@ -5,8 +5,8 @@ use torrust_tracker_configuration::Configuration; use super::authorization::WhitelistAuthorization; use super::manager::WhitelistManager; use super::repository::in_memory::InMemoryWhitelist; -use crate::core::databases::setup::initialize_database; -use crate::core::whitelist::setup::initialize_whitelist_manager; +use crate::databases::setup::initialize_database; +use crate::whitelist::setup::initialize_whitelist_manager; #[must_use] pub fn initialize_whitelist_services(config: &Configuration) -> (Arc, Arc) { diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 8a084dc7f..f7506800e 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -13,6 +13,20 @@ //! 4. Initialize the domain tracker. use std::sync::Arc; +use bittorrent_tracker_core::announce_handler::AnnounceHandler; +use bittorrent_tracker_core::authentication::handler::KeysHandler; +use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; +use bittorrent_tracker_core::authentication::key::repository::persisted::DatabaseKeyRepository; +use bittorrent_tracker_core::authentication::service; +use bittorrent_tracker_core::databases::setup::initialize_database; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use bittorrent_tracker_core::statistics; +use bittorrent_tracker_core::torrent::manager::TorrentsManager; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; +use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager; use tokio::sync::RwLock; use torrust_tracker_clock::static_time; use torrust_tracker_configuration::validator::Validator; @@ -22,20 +36,6 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; use crate::container::AppContainer; -use crate::core::announce_handler::AnnounceHandler; -use crate::core::authentication::handler::KeysHandler; -use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; -use crate::core::authentication::key::repository::persisted::DatabaseKeyRepository; -use crate::core::authentication::service; -use crate::core::databases::setup::initialize_database; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::statistics; -use crate::core::torrent::manager::TorrentsManager; -use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; -use crate::core::whitelist::authorization::WhitelistAuthorization; -use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; -use crate::core::whitelist::setup::initialize_whitelist_manager; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index 45e6e9e68..7085aa7e2 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -12,13 +12,12 @@ use std::sync::Arc; +use bittorrent_tracker_core::torrent::manager::TorrentsManager; use chrono::Utc; use tokio::task::JoinHandle; use torrust_tracker_configuration::Core; use tracing::instrument; -use crate::core::torrent::manager::TorrentsManager; - /// It starts a jobs for cleaning up the torrent data in the tracker. /// /// The cleaning task is executed on an `inactive_peer_cleanup_interval`. diff --git a/src/container.rs b/src/container.rs index 1a2a029ee..cae2d07ce 100644 --- a/src/container.rs +++ b/src/container.rs @@ -1,20 +1,20 @@ use std::sync::Arc; +use bittorrent_tracker_core::announce_handler::AnnounceHandler; +use bittorrent_tracker_core::authentication::handler::KeysHandler; +use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::databases::Database; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use bittorrent_tracker_core::statistics::event::sender::Sender; +use bittorrent_tracker_core::statistics::repository::Repository; +use bittorrent_tracker_core::torrent::manager::TorrentsManager; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use bittorrent_tracker_core::whitelist; +use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; -use crate::core::announce_handler::AnnounceHandler; -use crate::core::authentication::handler::KeysHandler; -use crate::core::authentication::service::AuthenticationService; -use crate::core::databases::Database; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::statistics::event::sender::Sender; -use crate::core::statistics::repository::Repository; -use crate::core::torrent::manager::TorrentsManager; -use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; -use crate::core::whitelist; -use crate::core::whitelist::manager::WhitelistManager; use crate::servers::udp::server::banning::BanService; pub struct AppContainer { diff --git a/src/core/mod.rs b/src/core/mod.rs index 125a67b5a..3449ec7b4 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -1,573 +1 @@ -//! The core `tracker` module contains the generic `BitTorrent` tracker logic which is independent of the delivery layer. -//! -//! It contains the tracker services and their dependencies. It's a domain layer which does not -//! specify how the end user should connect to the `Tracker`. -//! -//! Typically this module is intended to be used by higher modules like: -//! -//! - A UDP tracker -//! - A HTTP tracker -//! - A tracker REST API -//! -//! ```text -//! Delivery layer Domain layer -//! -//! HTTP tracker | -//! UDP tracker |> Core tracker -//! Tracker REST API | -//! ``` -//! -//! # Table of contents -//! -//! - [Tracker](#tracker) -//! - [Announce request](#announce-request) -//! - [Scrape request](#scrape-request) -//! - [Torrents](#torrents) -//! - [Peers](#peers) -//! - [Configuration](#configuration) -//! - [Services](#services) -//! - [Authentication](#authentication) -//! - [Statistics](#statistics) -//! - [Persistence](#persistence) -//! -//! # Tracker -//! -//! The `Tracker` is the main struct in this module. `The` tracker has some groups of responsibilities: -//! -//! - **Core tracker**: it handles the information about torrents and peers. -//! - **Authentication**: it handles authentication keys which are used by HTTP trackers. -//! - **Authorization**: it handles the permission to perform requests. -//! - **Whitelist**: when the tracker runs in `listed` or `private_listed` mode all operations are restricted to whitelisted torrents. -//! - **Statistics**: it keeps and serves the tracker statistics. -//! -//! Refer to [torrust-tracker-configuration](https://docs.rs/torrust-tracker-configuration) crate docs to get more information about the tracker settings. -//! -//! ## Announce request -//! -//! Handling `announce` requests is the most important task for a `BitTorrent` tracker. -//! -//! A `BitTorrent` swarm is a network of peers that are all trying to download the same torrent. -//! When a peer wants to find other peers it announces itself to the swarm via the tracker. -//! The peer sends its data to the tracker so that the tracker can add it to the swarm. -//! The tracker responds to the peer with the list of other peers in the swarm so that -//! the peer can contact them to start downloading pieces of the file from them. -//! -//! Once you have instantiated the `AnnounceHandler` you can `announce` a new [`peer::Peer`](torrust_tracker_primitives::peer::Peer) with: -//! -//! ```rust,no_run -//! use std::net::SocketAddr; -//! use std::net::IpAddr; -//! use std::net::Ipv4Addr; -//! use std::str::FromStr; -//! -//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; -//! use torrust_tracker_primitives::DurationSinceUnixEpoch; -//! use torrust_tracker_primitives::peer; -//! use bittorrent_primitives::info_hash::InfoHash; -//! -//! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); -//! -//! let peer = peer::Peer { -//! peer_id: PeerId(*b"-qB00000000000000001"), -//! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), -//! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), -//! uploaded: NumberOfBytes::new(0), -//! downloaded: NumberOfBytes::new(0), -//! left: NumberOfBytes::new(0), -//! event: AnnounceEvent::Completed, -//! }; -//! -//! let peer_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); -//! ``` -//! -//! ```text -//! let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip).await; -//! ``` -//! -//! The `Tracker` returns the list of peers for the torrent with the infohash `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`, -//! filtering out the peer that is making the `announce` request. -//! -//! > **NOTICE**: that the peer argument is mutable because the `Tracker` can change the peer IP if the peer is using a loopback IP. -//! -//! The `peer_ip` argument is the resolved peer ip. It's a common practice that trackers ignore the peer ip in the `announce` request params, -//! and resolve the peer ip using the IP of the client making the request. As the tracker is a domain service, the peer IP must be provided -//! for the `Tracker` user, which is usually a higher component with access the the request metadata, for example, connection data, proxy headers, -//! etcetera. -//! -//! The returned struct is: -//! -//! ```rust,no_run -//! use torrust_tracker_primitives::peer; -//! use torrust_tracker_configuration::AnnouncePolicy; -//! -//! pub struct AnnounceData { -//! pub peers: Vec, -//! pub swarm_stats: SwarmMetadata, -//! pub policy: AnnouncePolicy, // the tracker announce policy. -//! } -//! -//! pub struct SwarmMetadata { -//! pub completed: u32, // The number of peers that have ever completed downloading -//! pub seeders: u32, // The number of active peers that have completed downloading (seeders) -//! pub leechers: u32, // The number of active peers that have not completed downloading (leechers) -//! } -//! -//! // Core tracker configuration -//! pub struct AnnounceInterval { -//! // ... -//! pub interval: u32, // Interval in seconds that the client should wait between sending regular announce requests to the tracker -//! pub interval_min: u32, // Minimum announce interval. Clients must not reannounce more frequently than this -//! // ... -//! } -//! ``` -//! -//! Refer to `BitTorrent` BEPs and other sites for more information about the `announce` request: -//! -//! - [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -//! - [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) -//! - [Vuze docs](https://wiki.vuze.com/w/Announce) -//! -//! ## Scrape request -//! -//! The `scrape` request allows clients to query metadata about the swarm in bulk. -//! -//! An `scrape` request includes a list of infohashes whose swarm metadata you want to collect. -//! -//! The returned struct is: -//! -//! ```rust,no_run -//! use bittorrent_primitives::info_hash::InfoHash; -//! use std::collections::HashMap; -//! -//! pub struct ScrapeData { -//! pub files: HashMap, -//! } -//! -//! pub struct SwarmMetadata { -//! pub complete: u32, // The number of active peers that have completed downloading (seeders) -//! pub downloaded: u32, // The number of peers that have ever completed downloading -//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) -//! } -//! ``` -//! -//! The JSON representation of a sample `scrape` response would be like the following: -//! -//! ```json -//! { -//! 'files': { -//! 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19}, -//! 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20} -//! } -//! } -//! ``` -//! -//! `xxxxxxxxxxxxxxxxxxxx` and `yyyyyyyyyyyyyyyyyyyy` are 20-byte infohash arrays. -//! There are two data structures for infohashes: byte arrays and hex strings: -//! -//! ```rust,no_run -//! use bittorrent_primitives::info_hash::InfoHash; -//! use std::str::FromStr; -//! -//! let info_hash: InfoHash = [255u8; 20].into(); -//! -//! assert_eq!( -//! info_hash, -//! InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() -//! ); -//! ``` -//! Refer to `BitTorrent` BEPs and other sites for more information about the `scrape` request: -//! -//! - [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) -//! - [BEP 15. UDP Tracker Protocol for `BitTorrent`. Scrape section](https://www.bittorrent.org/beps/bep_0015.html) -//! - [Vuze docs](https://wiki.vuze.com/w/Scrape) -//! -//! ## Torrents -//! -//! The [`torrent`] module contains all the data structures stored by the `Tracker` except for peers. -//! -//! We can represent the data stored in memory internally by the `Tracker` with this JSON object: -//! -//! ```json -//! { -//! "c1277613db1d28709b034a017ab2cae4be07ae10": { -//! "completed": 0, -//! "peers": { -//! "-qB00000000000000001": { -//! "peer_id": "-qB00000000000000001", -//! "peer_addr": "2.137.87.41:1754", -//! "updated": 1672419840, -//! "uploaded": 120, -//! "downloaded": 60, -//! "left": 60, -//! "event": "started" -//! }, -//! "-qB00000000000000002": { -//! "peer_id": "-qB00000000000000002", -//! "peer_addr": "23.17.287.141:2345", -//! "updated": 1679415984, -//! "uploaded": 80, -//! "downloaded": 20, -//! "left": 40, -//! "event": "started" -//! } -//! } -//! } -//! } -//! ``` -//! -//! The `Tracker` maintains an indexed-by-info-hash list of torrents. For each torrent, it stores a torrent `Entry`. -//! The torrent entry has two attributes: -//! -//! - `completed`: which is hte number of peers that have completed downloading the torrent file/s. As they have completed downloading, -//! they have a full version of the torrent data, and they can provide the full data to other peers. That's why they are also known as "seeders". -//! - `peers`: an indexed and orderer list of peer for the torrent. Each peer contains the data received from the peer in the `announce` request. -//! -//! The [`torrent`] module not only contains the original data obtained from peer via `announce` requests, it also contains -//! aggregate data that can be derived from the original data. For example: -//! -//! ```rust,no_run -//! pub struct SwarmMetadata { -//! pub complete: u32, // The number of active peers that have completed downloading (seeders) -//! pub downloaded: u32, // The number of peers that have ever completed downloading -//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) -//! } -//! -//! ``` -//! -//! > **NOTICE**: that `complete` or `completed` peers are the peers that have completed downloading, but only the active ones are considered "seeders". -//! -//! `SwarmMetadata` struct follows name conventions for `scrape` responses. See [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmMetadata` -//! is used for the rest of cases. -//! -//! Refer to [`torrent`] module for more details about these data structures. -//! -//! ## Peers -//! -//! A `Peer` is the struct used by the `Tracker` to keep peers data: -//! -//! ```rust,no_run -//! use std::net::SocketAddr; - -//! use aquatic_udp_protocol::PeerId; -//! use torrust_tracker_primitives::DurationSinceUnixEpoch; -//! use aquatic_udp_protocol::NumberOfBytes; -//! use aquatic_udp_protocol::AnnounceEvent; -//! -//! pub struct Peer { -//! pub peer_id: PeerId, // The peer ID -//! pub peer_addr: SocketAddr, // Peer socket address -//! pub updated: DurationSinceUnixEpoch, // Last time (timestamp) when the peer was updated -//! pub uploaded: NumberOfBytes, // Number of bytes the peer has uploaded so far -//! pub downloaded: NumberOfBytes, // Number of bytes the peer has downloaded so far -//! pub left: NumberOfBytes, // The number of bytes this peer still has to download -//! pub event: AnnounceEvent, // The event the peer has announced: `started`, `completed`, `stopped` -//! } -//! ``` -//! -//! Notice that most of the attributes are obtained from the `announce` request. -//! For example, an HTTP announce request would contain the following `GET` parameters: -//! -//! -//! -//! The `Tracker` keeps an in-memory ordered data structure with all the torrents and a list of peers for each torrent, together with some swarm metrics. -//! -//! We can represent the data stored in memory with this JSON object: -//! -//! ```json -//! { -//! "c1277613db1d28709b034a017ab2cae4be07ae10": { -//! "completed": 0, -//! "peers": { -//! "-qB00000000000000001": { -//! "peer_id": "-qB00000000000000001", -//! "peer_addr": "2.137.87.41:1754", -//! "updated": 1672419840, -//! "uploaded": 120, -//! "downloaded": 60, -//! "left": 60, -//! "event": "started" -//! }, -//! "-qB00000000000000002": { -//! "peer_id": "-qB00000000000000002", -//! "peer_addr": "23.17.287.141:2345", -//! "updated": 1679415984, -//! "uploaded": 80, -//! "downloaded": 20, -//! "left": 40, -//! "event": "started" -//! } -//! } -//! } -//! } -//! ``` -//! -//! That JSON object does not exist, it's only a representation of the `Tracker` torrents data. -//! -//! `c1277613db1d28709b034a017ab2cae4be07ae10` is the torrent infohash and `completed` contains the number of peers -//! that have a full version of the torrent data, also known as seeders. -//! -//! Refer to [`peer`](torrust_tracker_primitives::peer) for more information about peers. -//! -//! # Configuration -//! -//! You can control the behavior of this module with the module settings: -//! -//! ```toml -//! [logging] -//! threshold = "debug" -//! -//! [core] -//! inactive_peer_cleanup_interval = 600 -//! listed = false -//! private = false -//! tracker_usage_statistics = true -//! -//! [core.announce_policy] -//! interval = 120 -//! interval_min = 120 -//! -//! [core.database] -//! driver = "sqlite3" -//! path = "./storage/tracker/lib/database/sqlite3.db" -//! -//! [core.net] -//! on_reverse_proxy = false -//! external_ip = "2.137.87.41" -//! -//! [core.tracker_policy] -//! max_peer_timeout = 900 -//! persistent_torrent_completed_stat = false -//! remove_peerless_torrents = true -//! ``` -//! -//! Refer to the [`configuration` module documentation](https://docs.rs/torrust-tracker-configuration) to get more information about all options. -//! -//! # Services -//! -//! Services are domain services on top of the core tracker domain. Right now there are two types of service: -//! -//! - For statistics: [`crate::core::statistics::services`] -//! - For torrents: [`crate::core::torrent::services`] -//! -//! Services usually format the data inside the tracker to make it easier to consume by other parts. -//! They also decouple the internal data structure, used by the tracker, from the way we deliver that data to the consumers. -//! The internal data structure is designed for performance or low memory consumption. And it should be changed -//! without affecting the external consumers. -//! -//! Services can include extra features like pagination, for example. -//! -//! # Authentication -//! -//! One of the core `Tracker` responsibilities is to create and keep authentication keys. Auth keys are used by HTTP trackers -//! when the tracker is running in `private` or `private_listed` mode. -//! -//! HTTP tracker's clients need to obtain an auth key before starting requesting the tracker. Once the get one they have to include -//! a `PATH` param with the key in all the HTTP requests. For example, when a peer wants to `announce` itself it has to use the -//! HTTP tracker endpoint `GET /announce/:key`. -//! -//! The common way to obtain the keys is by using the tracker API directly or via other applications like the [Torrust Index](https://github.com/torrust/torrust-index). -//! -//! To learn more about tracker authentication, refer to the following modules : -//! -//! - [`authentication`] module. -//! - [`core`](crate::core) module. -//! - [`http`](crate::servers::http) module. -//! -//! # Statistics -//! -//! The `Tracker` keeps metrics for some events: -//! -//! ```rust,no_run -//! pub struct Metrics { -//! // IP version 4 -//! -//! // HTTP tracker -//! pub tcp4_connections_handled: u64, -//! pub tcp4_announces_handled: u64, -//! pub tcp4_scrapes_handled: u64, -//! -//! // UDP tracker -//! pub udp4_connections_handled: u64, -//! pub udp4_announces_handled: u64, -//! pub udp4_scrapes_handled: u64, -//! -//! // IP version 6 -//! -//! // HTTP tracker -//! pub tcp6_connections_handled: u64, -//! pub tcp6_announces_handled: u64, -//! pub tcp6_scrapes_handled: u64, -//! -//! // UDP tracker -//! pub udp6_connections_handled: u64, -//! pub udp6_announces_handled: u64, -//! pub udp6_scrapes_handled: u64, -//! } -//! ``` -//! -//! The metrics maintained by the `Tracker` are: -//! -//! - `connections_handled`: number of connections handled by the tracker -//! - `announces_handled`: number of `announce` requests handled by the tracker -//! - `scrapes_handled`: number of `scrape` handled requests by the tracker -//! -//! > **NOTICE**: as the HTTP tracker does not have an specific `connection` request like the UDP tracker, `connections_handled` are -//! > increased on every `announce` and `scrape` requests. -//! -//! The tracker exposes an event sender API that allows the tracker users to send events. When a higher application service handles a -//! `connection` , `announce` or `scrape` requests, it notifies the `Tracker` by sending statistics events. -//! -//! For example, the HTTP tracker would send an event like the following when it handles an `announce` request received from a peer using IP version 4. -//! -//! ```text -//! stats_event_sender.send_stats_event(statistics::event::Event::Tcp4Announce).await -//! ``` -//! -//! Refer to [`statistics`] module for more information about statistics. -//! -//! # Persistence -//! -//! Right now the `Tracker` is responsible for storing and load data into and -//! from the database, when persistence is enabled. -//! -//! There are three types of persistent object: -//! -//! - Authentication keys (only expiring keys) -//! - Torrent whitelist -//! - Torrent metrics -//! -//! Refer to [`databases`] module for more information about persistence. -pub mod announce_handler; -pub mod authentication; -pub mod databases; -pub mod error; -pub mod scrape_handler; pub mod statistics; -pub mod torrent; -pub mod whitelist; - -pub mod core_tests; -pub mod peer_tests; - -#[cfg(test)] -mod tests { - mod the_tracker { - use std::net::{IpAddr, Ipv4Addr}; - use std::str::FromStr; - use std::sync::Arc; - - use torrust_tracker_test_helpers::configuration; - - use crate::core::announce_handler::AnnounceHandler; - use crate::core::core_tests::initialize_handlers; - use crate::core::scrape_handler::ScrapeHandler; - - fn initialize_handlers_for_public_tracker() -> (Arc, Arc) { - let config = configuration::ephemeral_public(); - initialize_handlers(&config) - } - - fn initialize_handlers_for_listed_tracker() -> (Arc, Arc) { - let config = configuration::ephemeral_listed(); - initialize_handlers(&config) - } - - // The client peer IP - fn peer_ip() -> IpAddr { - IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) - } - - mod for_all_config_modes { - - mod handling_a_scrape_request { - - use std::net::{IpAddr, Ipv4Addr}; - - use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::core::ScrapeData; - use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - - use crate::core::announce_handler::PeersWanted; - use crate::core::core_tests::{complete_peer, incomplete_peer}; - use crate::core::tests::the_tracker::initialize_handlers_for_public_tracker; - - #[tokio::test] - async fn it_should_return_the_swarm_metadata_for_the_requested_file_if_the_tracker_has_that_torrent() { - let (announce_handler, scrape_handler) = initialize_handlers_for_public_tracker(); - - let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237 - - // Announce a "complete" peer for the torrent - let mut complete_peer = complete_peer(); - announce_handler.announce( - &info_hash, - &mut complete_peer, - &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10)), - &PeersWanted::All, - ); - - // Announce an "incomplete" peer for the torrent - let mut incomplete_peer = incomplete_peer(); - announce_handler.announce( - &info_hash, - &mut incomplete_peer, - &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11)), - &PeersWanted::All, - ); - - // Scrape - let scrape_data = scrape_handler.scrape(&vec![info_hash]).await; - - // The expected swarm metadata for the file - let mut expected_scrape_data = ScrapeData::empty(); - expected_scrape_data.add_file( - &info_hash, - SwarmMetadata { - complete: 0, // the "complete" peer does not count because it was not previously known - downloaded: 0, - incomplete: 1, // the "incomplete" peer we have just announced - }, - ); - - assert_eq!(scrape_data, expected_scrape_data); - } - } - } - - mod configured_as_whitelisted { - - mod handling_a_scrape_request { - - use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::core::ScrapeData; - use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - - use crate::core::announce_handler::PeersWanted; - use crate::core::core_tests::{complete_peer, incomplete_peer}; - use crate::core::tests::the_tracker::{initialize_handlers_for_listed_tracker, peer_ip}; - - #[tokio::test] - async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { - let (announce_handler, scrape_handler) = initialize_handlers_for_listed_tracker(); - - let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237 - - let mut peer = incomplete_peer(); - announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); - - // Announce twice to force non zeroed swarm metadata - let mut peer = complete_peer(); - announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); - - let scrape_data = scrape_handler.scrape(&vec![info_hash]).await; - - // The expected zeroed swarm metadata for the file - let mut expected_scrape_data = ScrapeData::empty(); - expected_scrape_data.add_file(&info_hash, SwarmMetadata::zeroed()); - - assert_eq!(scrape_data, expected_scrape_data); - } - } - } - } -} diff --git a/src/core/statistics/mod.rs b/src/core/statistics/mod.rs index 2ffbc0c8f..4e379ae78 100644 --- a/src/core/statistics/mod.rs +++ b/src/core/statistics/mod.rs @@ -1,32 +1 @@ -//! Structs to collect and keep tracker metrics. -//! -//! The tracker collects metrics such as: -//! -//! - Number of connections handled -//! - Number of `announce` requests handled -//! - Number of `scrape` request handled -//! -//! These metrics are collected for each connection type: UDP and HTTP and -//! also for each IP version used by the peers: IPv4 and IPv6. -//! -//! > Notice: that UDP tracker have an specific `connection` request. For the -//! > `HTTP` metrics the counter counts one connection for each `announce` or -//! > `scrape` request. -//! -//! The data is collected by using an `event-sender -> event listener` model. -//! -//! The tracker uses a [`Sender`](crate::core::statistics::event::sender::Sender) -//! instance to send an event. -//! -//! The [`statistics::keeper::Keeper`](crate::core::statistics::keeper::Keeper) listens to new -//! events and uses the [`statistics::repository::Repository`](crate::core::statistics::repository::Repository) to -//! upgrade and store metrics. -//! -//! See the [`statistics::event::Event`](crate::core::statistics::event::Event) enum to check -//! which events are available. -pub mod event; -pub mod keeper; -pub mod metrics; -pub mod repository; pub mod services; -pub mod setup; diff --git a/src/core/statistics/services.rs b/src/core/statistics/services.rs index 337731aea..a4bcc411e 100644 --- a/src/core/statistics/services.rs +++ b/src/core/statistics/services.rs @@ -2,14 +2,14 @@ //! //! It includes: //! -//! - A [`factory`](crate::core::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. -//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::core::statistics::metrics::Metrics). +//! - A [`factory`](bittorrent_tracker_core::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`get_metrics`] service to get the tracker [`metrics`](bittorrent_tracker_core::statistics::metrics::Metrics). //! //! Tracker metrics are collected using a Publisher-Subscribe pattern. //! //! The factory function builds two structs: //! -//! - An statistics event [`Sender`](crate::core::statistics::event::sender::Sender) +//! - An statistics event [`Sender`](bittorrent_tracker_core::statistics::event::sender::Sender) //! - An statistics [`Repository`] //! //! ```text @@ -21,7 +21,7 @@ //! There is an event listener that is receiving all the events and processing them with an event handler. //! Then, the event handler updates the metrics depending on the received event. //! -//! For example, if you send the event [`Event::Udp4Connect`](crate::core::statistics::event::Event::Udp4Connect): +//! For example, if you send the event [`Event::Udp4Connect`](bittorrent_tracker_core::statistics::event::Event::Udp4Connect): //! //! ```text //! let result = event_sender.send_event(Event::Udp4Connect).await; @@ -38,28 +38,14 @@ //! ``` use std::sync::Arc; +use bittorrent_tracker_core::statistics::metrics::Metrics; +use bittorrent_tracker_core::statistics::repository::Repository; +use bittorrent_tracker_core::statistics::services::TrackerMetrics; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use tokio::sync::RwLock; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use crate::core::statistics::metrics::Metrics; -use crate::core::statistics::repository::Repository; -use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::servers::udp::server::banning::BanService; -/// All the metrics collected by the tracker. -#[derive(Debug, PartialEq)] -pub struct TrackerMetrics { - /// Domain level metrics. - /// - /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: TorrentsMetrics, - - /// Application level metrics. Usage statistics/metrics. - /// - /// Metrics about how the tracker is been used (number of udp announce requests, number of http scrape requests, etcetera) - pub protocol_metrics: Metrics, -} - /// It returns all the [`TrackerMetrics`] pub async fn get_metrics( in_memory_torrent_repository: Arc, @@ -110,14 +96,15 @@ pub async fn get_metrics( mod tests { use std::sync::Arc; + use bittorrent_tracker_core::statistics::services::TrackerMetrics; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::{self, statistics}; use tokio::sync::RwLock; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; - use crate::core::statistics::services::{get_metrics, TrackerMetrics}; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::{self, statistics}; + use crate::core::statistics::services::get_metrics; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; @@ -145,7 +132,7 @@ mod tests { tracker_metrics, TrackerMetrics { torrents_metrics: TorrentsMetrics::default(), - protocol_metrics: core::statistics::metrics::Metrics::default(), + protocol_metrics: statistics::metrics::Metrics::default(), } ); } diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index 045a9d211..7024ffeba 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -5,6 +5,8 @@ use std::time::Duration; use axum::extract::{self, Path, State}; use axum::response::Response; +use bittorrent_tracker_core::authentication::handler::{AddKeyRequest, KeysHandler}; +use bittorrent_tracker_core::authentication::Key; use serde::Deserialize; use super::forms::AddKeyForm; @@ -12,8 +14,6 @@ use super::responses::{ auth_key_response, failed_to_delete_key_response, failed_to_generate_key_response, failed_to_reload_keys_response, invalid_auth_key_duration_response, invalid_auth_key_response, }; -use crate::core::authentication::handler::{AddKeyRequest, KeysHandler}; -use crate::core::authentication::Key; use crate::servers::apis::v1::context::auth_key::resources::AuthKey; use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_response}; @@ -43,11 +43,11 @@ pub async fn add_auth_key_handler( { Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), Err(err) => match err { - crate::core::error::PeerKeyError::DurationOverflow { seconds_valid } => { + bittorrent_tracker_core::error::PeerKeyError::DurationOverflow { seconds_valid } => { invalid_auth_key_duration_response(seconds_valid) } - crate::core::error::PeerKeyError::InvalidKey { key, source } => invalid_auth_key_response(&key, source), - crate::core::error::PeerKeyError::DatabaseError { source } => failed_to_generate_key_response(source), + bittorrent_tracker_core::error::PeerKeyError::InvalidKey { key, source } => invalid_auth_key_response(&key, source), + bittorrent_tracker_core::error::PeerKeyError::DatabaseError { source } => failed_to_generate_key_response(source), }, } } diff --git a/src/servers/apis/v1/context/auth_key/resources.rs b/src/servers/apis/v1/context/auth_key/resources.rs index a65eb2ab2..8f5b4d309 100644 --- a/src/servers/apis/v1/context/auth_key/resources.rs +++ b/src/servers/apis/v1/context/auth_key/resources.rs @@ -1,10 +1,9 @@ //! API resources for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. +use bittorrent_tracker_core::authentication::{self, Key}; use serde::{Deserialize, Serialize}; use torrust_tracker_clock::conv::convert_from_iso_8601_to_timestamp; -use crate::core::authentication::{self, Key}; - /// A resource that represents an authentication key. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct AuthKey { @@ -50,11 +49,11 @@ impl From for AuthKey { mod tests { use std::time::Duration; + use bittorrent_tracker_core::authentication::{self, Key}; use torrust_tracker_clock::clock::stopped::Stopped as _; use torrust_tracker_clock::clock::{self, Time}; use super::AuthKey; - use crate::core::authentication::{self, Key}; use crate::CurrentClock; struct TestTime { diff --git a/src/servers/apis/v1/context/auth_key/routes.rs b/src/servers/apis/v1/context/auth_key/routes.rs index ee9f3252c..623fb3459 100644 --- a/src/servers/apis/v1/context/auth_key/routes.rs +++ b/src/servers/apis/v1/context/auth_key/routes.rs @@ -10,9 +10,9 @@ use std::sync::Arc; use axum::routing::{get, post}; use axum::Router; +use bittorrent_tracker_core::authentication::handler::KeysHandler; use super::handlers::{add_auth_key_handler, delete_auth_key_handler, generate_auth_key_handler, reload_keys_handler}; -use crate::core::authentication::handler::KeysHandler; /// It adds the routes to the router for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. pub fn add(prefix: &str, router: Router, keys_handler: &Arc) -> Router { diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index b8e7abd87..b4ead78ea 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -5,13 +5,13 @@ use std::sync::Arc; use axum::extract::State; use axum::response::Response; use axum_extra::extract::Query; +use bittorrent_tracker_core::statistics::repository::Repository; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use serde::Deserialize; use tokio::sync::RwLock; use super::responses::{metrics_response, stats_response}; -use crate::core::statistics::repository::Repository; use crate::core::statistics::services::get_metrics; -use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::servers::udp::server::banning::BanService; #[derive(Deserialize, Debug, Default)] diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index 97ece22fc..d4a0ec7ec 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -1,9 +1,8 @@ //! API resources for the [`stats`](crate::servers::apis::v1::context::stats) //! API context. +use bittorrent_tracker_core::statistics::services::TrackerMetrics; use serde::{Deserialize, Serialize}; -use crate::core::statistics::services::TrackerMetrics; - /// It contains all the statistics generated by the tracker. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct Stats { @@ -118,11 +117,11 @@ impl From for Stats { #[cfg(test)] mod tests { + use bittorrent_tracker_core::statistics::metrics::Metrics; + use bittorrent_tracker_core::statistics::services::TrackerMetrics; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use super::Stats; - use crate::core::statistics::metrics::Metrics; - use crate::core::statistics::services::TrackerMetrics; #[test] fn stats_resource_should_be_converted_from_tracker_metrics() { diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index 6fda43f8c..fc74b5f8d 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -1,9 +1,9 @@ //! API responses for the [`stats`](crate::servers::apis::v1::context::stats) //! API context. use axum::response::{IntoResponse, Json, Response}; +use bittorrent_tracker_core::statistics::services::TrackerMetrics; use super::resources::Stats; -use crate::core::statistics::services::TrackerMetrics; /// `200` response that contains the [`Stats`] resource as json. #[must_use] diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/src/servers/apis/v1/context/torrent/handlers.rs index 0ec90441d..ce80d8fee 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/src/servers/apis/v1/context/torrent/handlers.rs @@ -8,13 +8,13 @@ use axum::extract::{Path, State}; use axum::response::{IntoResponse, Response}; use axum_extra::extract::Query; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_tracker_core::torrent::services::{get_torrent_info, get_torrents, get_torrents_page}; use serde::{de, Deserialize, Deserializer}; use thiserror::Error; use torrust_tracker_primitives::pagination::Pagination; use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; -use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::core::torrent::services::{get_torrent_info, get_torrents, get_torrents_page}; use crate::servers::apis::v1::responses::invalid_info_hash_param_response; use crate::servers::apis::InfoHashParam; @@ -33,7 +33,7 @@ pub async fn get_torrent_handler( ) -> Response { match InfoHash::from_str(&info_hash.0) { Err(_) => invalid_info_hash_param_response(&info_hash.0), - Ok(info_hash) => match get_torrent_info(in_memory_torrent_repository.clone(), &info_hash).await { + Ok(info_hash) => match get_torrent_info(&in_memory_torrent_repository, &info_hash) { Some(info) => torrent_info_response(info).into_response(), None => torrent_not_known_response(), }, @@ -85,19 +85,14 @@ pub async fn get_torrents_handler( tracing::debug!("pagination: {:?}", pagination); if pagination.0.info_hashes.is_empty() { - torrent_list_response( - &get_torrents_page( - in_memory_torrent_repository.clone(), - Some(&Pagination::new_with_options(pagination.0.offset, pagination.0.limit)), - ) - .await, - ) + torrent_list_response(&get_torrents_page( + &in_memory_torrent_repository, + Some(&Pagination::new_with_options(pagination.0.offset, pagination.0.limit)), + )) .into_response() } else { match parse_info_hashes(pagination.0.info_hashes) { - Ok(info_hashes) => { - torrent_list_response(&get_torrents(in_memory_torrent_repository.clone(), &info_hashes).await).into_response() - } + Ok(info_hashes) => torrent_list_response(&get_torrents(&in_memory_torrent_repository, &info_hashes)).into_response(), Err(err) => match err { QueryParamError::InvalidInfoHash { info_hash } => invalid_info_hash_param_response(&info_hash), }, diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/src/servers/apis/v1/context/torrent/resources/torrent.rs index c90a2a05f..5e4da5c16 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/src/servers/apis/v1/context/torrent/resources/torrent.rs @@ -4,10 +4,9 @@ //! - `ListItem` is a list item resource on a torrent list. `ListItem` does //! include a `peers` field but it is always `None` in the struct and `null` in //! the JSON response. +use bittorrent_tracker_core::torrent::services::{BasicInfo, Info}; use serde::{Deserialize, Serialize}; -use crate::core::torrent::services::{BasicInfo, Info}; - /// `Torrent` API resource. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct Torrent { @@ -99,10 +98,10 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; + use bittorrent_tracker_core::torrent::services::{BasicInfo, Info}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use super::Torrent; - use crate::core::torrent::services::{BasicInfo, Info}; use crate::servers::apis::v1::context::torrent::resources::peer::Peer; use crate::servers::apis::v1::context::torrent::resources::torrent::ListItem; diff --git a/src/servers/apis/v1/context/torrent/responses.rs b/src/servers/apis/v1/context/torrent/responses.rs index 5174c9abe..cd359247b 100644 --- a/src/servers/apis/v1/context/torrent/responses.rs +++ b/src/servers/apis/v1/context/torrent/responses.rs @@ -1,10 +1,10 @@ //! API responses for the [`torrent`](crate::servers::apis::v1::context::torrent) //! API context. use axum::response::{IntoResponse, Json, Response}; +use bittorrent_tracker_core::torrent::services::{BasicInfo, Info}; use serde_json::json; use super::resources::torrent::{ListItem, Torrent}; -use crate::core::torrent::services::{BasicInfo, Info}; /// `200` response that contains an array of /// [`ListItem`] diff --git a/src/servers/apis/v1/context/torrent/routes.rs b/src/servers/apis/v1/context/torrent/routes.rs index 3ea8c639c..615bd8d51 100644 --- a/src/servers/apis/v1/context/torrent/routes.rs +++ b/src/servers/apis/v1/context/torrent/routes.rs @@ -8,9 +8,9 @@ use std::sync::Arc; use axum::routing::get; use axum::Router; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use super::handlers::{get_torrent_handler, get_torrents_handler}; -use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; /// It adds the routes to the router for the [`torrent`](crate::servers::apis::v1::context::torrent) API context. pub fn add(prefix: &str, router: Router, in_memory_torrent_repository: &Arc) -> Router { diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/src/servers/apis/v1/context/whitelist/handlers.rs index ebe0bb15c..e33a215f2 100644 --- a/src/servers/apis/v1/context/whitelist/handlers.rs +++ b/src/servers/apis/v1/context/whitelist/handlers.rs @@ -6,11 +6,11 @@ use std::sync::Arc; use axum::extract::{Path, State}; use axum::response::Response; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use super::responses::{ failed_to_reload_whitelist_response, failed_to_remove_torrent_from_whitelist_response, failed_to_whitelist_torrent_response, }; -use crate::core::whitelist::manager::WhitelistManager; use crate::servers::apis::v1::responses::{invalid_info_hash_param_response, ok_response}; use crate::servers::apis::InfoHashParam; diff --git a/src/servers/apis/v1/context/whitelist/routes.rs b/src/servers/apis/v1/context/whitelist/routes.rs index 5069332af..316193cd6 100644 --- a/src/servers/apis/v1/context/whitelist/routes.rs +++ b/src/servers/apis/v1/context/whitelist/routes.rs @@ -9,9 +9,9 @@ use std::sync::Arc; use axum::routing::{delete, get, post}; use axum::Router; +use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use super::handlers::{add_torrent_to_whitelist_handler, reload_whitelist_handler, remove_torrent_from_whitelist_handler}; -use crate::core::whitelist::manager::WhitelistManager; /// It adds the routes to the router for the [`whitelist`](crate::servers::apis::v1::context::whitelist) API context. pub fn add(prefix: &str, router: Router, whitelist_manager: &Arc) -> Router { diff --git a/src/servers/http/v1/extractors/authentication_key.rs b/src/servers/http/v1/extractors/authentication_key.rs index d3b77c31a..0e46b75dd 100644 --- a/src/servers/http/v1/extractors/authentication_key.rs +++ b/src/servers/http/v1/extractors/authentication_key.rs @@ -50,10 +50,10 @@ use axum::extract::{FromRequestParts, Path}; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; use bittorrent_http_protocol::v1::responses; +use bittorrent_tracker_core::authentication::Key; use hyper::StatusCode; use serde::Deserialize; -use crate::core::authentication::Key; use crate::servers::http::v1::handlers::common::auth; /// Extractor for the [`Key`] struct. diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 544d706fa..40462c31d 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -16,17 +16,18 @@ use bittorrent_http_protocol::v1::requests::announce::{Announce, Compact, Event} use bittorrent_http_protocol::v1::responses::{self}; use bittorrent_http_protocol::v1::services::peer_ip_resolver; use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; +use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; +use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::authentication::Key; +use bittorrent_tracker_core::statistics::event::sender::Sender; +use bittorrent_tracker_core::whitelist; use hyper::StatusCode; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; -use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; -use crate::core::authentication::service::AuthenticationService; -use crate::core::authentication::Key; -use crate::core::statistics::event::sender::Sender; -use crate::core::whitelist; +use super::common::auth::map_auth_error_to_error_response; use crate::servers::http::v1::extractors::announce_request::ExtractRequest; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; @@ -150,7 +151,7 @@ async fn handle_announce( match maybe_key { Some(key) => match authentication_service.authenticate(&key).await { Ok(()) => (), - Err(error) => return Err(responses::error::Error::from(error)), + Err(error) => return Err(map_auth_error_to_error_response(&error)), }, None => { return Err(responses::error::Error::from(auth::Error::MissingAuthKey { @@ -250,21 +251,20 @@ mod tests { use bittorrent_http_protocol::v1::requests::announce::Announce; use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use bittorrent_tracker_core::authentication::service::AuthenticationService; + use bittorrent_tracker_core::core_tests::sample_info_hash; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::statistics; + use bittorrent_tracker_core::statistics::event::sender::Sender; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; - use crate::core::announce_handler::AnnounceHandler; - use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::core::authentication::service::AuthenticationService; - use crate::core::core_tests::sample_info_hash; - use crate::core::databases::setup::initialize_database; - use crate::core::statistics; - use crate::core::statistics::event::sender::Sender; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - use crate::core::whitelist::authorization::WhitelistAuthorization; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - struct CoreTrackerServices { pub core_config: Arc, pub announce_handler: Arc, @@ -347,8 +347,9 @@ mod tests { use std::str::FromStr; + use bittorrent_tracker_core::authentication; + use super::{initialize_private_tracker, sample_announce_request, sample_client_ip_sources}; - use crate::core::authentication; use crate::servers::http::v1::handlers::announce::handle_announce; use crate::servers::http::v1::handlers::announce::tests::assert_error_response; diff --git a/src/servers/http/v1/handlers/common/auth.rs b/src/servers/http/v1/handlers/common/auth.rs index 5497427d8..c8625d03a 100644 --- a/src/servers/http/v1/handlers/common/auth.rs +++ b/src/servers/http/v1/handlers/common/auth.rs @@ -4,10 +4,9 @@ use std::panic::Location; use bittorrent_http_protocol::v1::responses; +use bittorrent_tracker_core::authentication; use thiserror::Error; -use crate::core::authentication; - /// Authentication error. /// /// When the tracker is private, the authentication key is required in the URL @@ -31,10 +30,12 @@ impl From for responses::error::Error { } } -impl From for responses::error::Error { - fn from(err: authentication::Error) -> Self { - responses::error::Error { - failure_reason: format!("Authentication error: {err}"), - } +#[must_use] +pub fn map_auth_error_to_error_response(err: &authentication::Error) -> responses::error::Error { + // code_review: this could not been implemented with the trait: + // impl From for responses::error::Error + // Consider moving the trait implementation to the http-protocol package. + responses::error::Error { + failure_reason: format!("Authentication error: {err}"), } } diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 35c5b1409..1b9196e25 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -12,14 +12,14 @@ use axum::response::{IntoResponse, Response}; use bittorrent_http_protocol::v1::requests::scrape::Scrape; use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; +use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::authentication::Key; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use bittorrent_tracker_core::statistics::event::sender::Sender; use hyper::StatusCode; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; -use crate::core::authentication::service::AuthenticationService; -use crate::core::authentication::Key; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::statistics::event::sender::Sender; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::extractors::scrape_request::ExtractRequest; @@ -171,21 +171,20 @@ mod tests { use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_primitives::info_hash::InfoHash; + use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use bittorrent_tracker_core::authentication::service::AuthenticationService; + use bittorrent_tracker_core::scrape_handler::ScrapeHandler; + use bittorrent_tracker_core::statistics; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; - use crate::core::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::core::authentication::service::AuthenticationService; - use crate::core::scrape_handler::ScrapeHandler; - use crate::core::statistics; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::whitelist::authorization::WhitelistAuthorization; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - struct CoreTrackerServices { pub core_config: Arc, pub scrape_handler: Arc, - pub stats_event_sender: Arc>>, + pub stats_event_sender: Arc>>, pub authentication_service: Arc, } @@ -247,10 +246,10 @@ mod tests { mod with_tracker_in_private_mode { use std::str::FromStr; + use bittorrent_tracker_core::authentication; use torrust_tracker_primitives::core::ScrapeData; use super::{initialize_private_tracker, sample_client_ip_sources, sample_scrape_request}; - use crate::core::authentication; use crate::servers::http::v1::handlers::scrape::handle_scrape; #[tokio::test] diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index ee682559e..9e74ab8a5 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -11,13 +11,12 @@ use std::net::IpAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; +use bittorrent_tracker_core::statistics; +use bittorrent_tracker_core::statistics::event::sender::Sender; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; -use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; -use crate::core::statistics::event::sender::Sender; -use crate::core::statistics::{self}; - /// The HTTP tracker `announce` service. /// /// The service sends an statistics event that increments: @@ -60,17 +59,16 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::statistics; + use bittorrent_tracker_core::statistics::event::sender::Sender; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::core::announce_handler::AnnounceHandler; - use crate::core::databases::setup::initialize_database; - use crate::core::statistics; - use crate::core::statistics::event::sender::Sender; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - struct CoreTrackerServices { pub core_config: Arc, pub announce_handler: Arc, @@ -124,11 +122,29 @@ mod tests { } } + use bittorrent_tracker_core::statistics::event::Event; + use futures::future::BoxFuture; + use mockall::mock; + use tokio::sync::mpsc::error::SendError; + + mock! { + StatsEventSender {} + impl Sender for StatsEventSender { + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; + } + } + mod with_tracker_in_any_mode { use std::future; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; + use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; + use bittorrent_tracker_core::core_tests::sample_info_hash; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::statistics; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use mockall::predicate::eq; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; @@ -136,14 +152,10 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; - use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; - use crate::core::core_tests::sample_info_hash; - use crate::core::databases::setup::initialize_database; - use crate::core::statistics; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use crate::servers::http::v1::services::announce::invoke; - use crate::servers::http::v1::services::announce::tests::{initialize_core_tracker_services, sample_peer}; + use crate::servers::http::v1::services::announce::tests::{ + initialize_core_tracker_services, sample_peer, MockStatsEventSender, + }; fn initialize_announce_handler() -> Arc { let config = configuration::ephemeral(); @@ -189,7 +201,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_announce_event_when_the_peer_uses_ipv4() { - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Tcp4Announce)) @@ -234,7 +246,7 @@ mod tests { // Tracker changes the peer IP to the tracker external IP when the peer is using the loopback IP. // Assert that the event sent is a TCP4 event - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Tcp4Announce)) @@ -260,7 +272,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_announce_event_when_the_peer_uses_ipv6_even_if_the_tracker_changes_the_peer_ip_to_ipv4() { - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Tcp6Announce)) diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index b5a858b83..59a7d34c7 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -11,12 +11,11 @@ use std::net::IpAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use bittorrent_tracker_core::statistics::event::sender::Sender; +use bittorrent_tracker_core::statistics::{self}; use torrust_tracker_primitives::core::ScrapeData; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::statistics::event::sender::Sender; -use crate::core::statistics::{self}; - /// The HTTP tracker `scrape` service. /// /// The service sends an statistics event that increments: @@ -77,18 +76,22 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::core_tests::sample_info_hash; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::scrape_handler::ScrapeHandler; + use bittorrent_tracker_core::statistics::event::sender::Sender; + use bittorrent_tracker_core::statistics::event::Event; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use futures::future::BoxFuture; + use mockall::mock; + use tokio::sync::mpsc::error::SendError; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::core::announce_handler::AnnounceHandler; - use crate::core::core_tests::sample_info_hash; - use crate::core::databases::setup::initialize_database; - use crate::core::scrape_handler::ScrapeHandler; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - use crate::core::whitelist::authorization::WhitelistAuthorization; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - fn initialize_announce_and_scrape_handlers_for_public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); @@ -133,27 +136,34 @@ mod tests { Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)) } + mock! { + StatsEventSender {} + impl Sender for StatsEventSender { + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; + } + } + mod with_real_data { use std::future; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::sync::Arc; + use bittorrent_tracker_core::announce_handler::PeersWanted; + use bittorrent_tracker_core::statistics; use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::core::announce_handler::PeersWanted; - use crate::core::statistics; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ initialize_announce_and_scrape_handlers_for_public_tracker, initialize_scrape_handler, sample_info_hash, - sample_info_hashes, sample_peer, + sample_info_hashes, sample_peer, MockStatsEventSender, }; #[tokio::test] async fn it_should_return_the_scrape_data_for_a_torrent() { - let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let (announce_handler, scrape_handler) = initialize_announce_and_scrape_handlers_for_public_tracker(); @@ -183,7 +193,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_scrape_event_when_the_peer_uses_ipv4() { - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Tcp4Scrape)) @@ -201,7 +211,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Tcp6Scrape)) @@ -224,19 +234,20 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::sync::Arc; + use bittorrent_tracker_core::announce_handler::PeersWanted; + use bittorrent_tracker_core::statistics; use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; - use crate::core::announce_handler::PeersWanted; - use crate::core::statistics; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ initialize_announce_and_scrape_handlers_for_public_tracker, sample_info_hash, sample_info_hashes, sample_peer, + MockStatsEventSender, }; #[tokio::test] async fn it_should_always_return_the_zeroed_scrape_data_for_a_torrent() { - let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let (announce_handler, _scrape_handler) = initialize_announce_and_scrape_handlers_for_public_tracker(); @@ -258,7 +269,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_scrape_event_when_the_peer_uses_ipv4() { - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Tcp4Scrape)) @@ -274,7 +285,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Tcp6Scrape)) diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 90c32771f..84b2f1db2 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -11,6 +11,10 @@ use aquatic_udp_protocol::{ ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use bittorrent_tracker_core::statistics::event::sender::Sender; +use bittorrent_tracker_core::{statistics, whitelist}; use torrust_tracker_clock::clock::Time as _; use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; @@ -20,10 +24,6 @@ use zerocopy::network_endian::I32; use super::connection_cookie::{check, make}; use super::RawRequest; use crate::container::UdpTrackerContainer; -use crate::core::announce_handler::{AnnounceHandler, PeersWanted}; -use crate::core::scrape_handler::ScrapeHandler; -use crate::core::statistics::event::sender::Sender; -use crate::core::{statistics, whitelist}; use crate::servers::udp::error::Error; use crate::servers::udp::{peer_builder, UDP_TRACKER_LOG_TARGET}; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; @@ -468,21 +468,25 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{NumberOfBytes, PeerId}; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::scrape_handler::ScrapeHandler; + use bittorrent_tracker_core::statistics::event::sender::Sender; + use bittorrent_tracker_core::statistics::event::Event; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use bittorrent_tracker_core::{statistics, whitelist}; + use futures::future::BoxFuture; + use mockall::mock; + use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_primitives::peer; use torrust_tracker_test_helpers::configuration; use super::gen_remote_fingerprint; - use crate::core::announce_handler::AnnounceHandler; - use crate::core::databases::setup::initialize_database; - use crate::core::scrape_handler::ScrapeHandler; - use crate::core::statistics::event::sender::Sender; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - use crate::core::whitelist::authorization::WhitelistAuthorization; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; - use crate::core::{statistics, whitelist}; use crate::CurrentClock; struct CoreTrackerServices { @@ -632,20 +636,28 @@ mod tests { } } + mock! { + StatsEventSender {} + impl Sender for StatsEventSender { + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; + } + } + mod connect_request { use std::future; use std::sync::Arc; use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; + use bittorrent_tracker_core::statistics; use mockall::predicate::eq; use super::{sample_ipv4_socket_address, sample_ipv6_remote_addr}; - use crate::core::statistics; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_connect; use crate::servers::udp::handlers::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv6_remote_addr_fingerprint, sample_issue_time, + MockStatsEventSender, }; fn sample_connect_request() -> ConnectRequest { @@ -656,7 +668,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { - let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let request = ConnectRequest { @@ -676,7 +688,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { - let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let request = ConnectRequest { @@ -696,7 +708,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { - let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let request = ConnectRequest { @@ -716,7 +728,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Udp4Connect)) @@ -738,7 +750,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Udp6Connect)) @@ -840,18 +852,18 @@ mod tests { AnnounceInterval, AnnounceResponse, InfoHash as AquaticInfoHash, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfPeers, PeerId as AquaticPeerId, Response, ResponsePeer, }; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::{statistics, whitelist}; use mockall::predicate::eq; use torrust_tracker_configuration::Core; - use crate::core::announce_handler::AnnounceHandler; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::{statistics, whitelist}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ gen_remote_fingerprint, initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, - sample_issue_time, TorrentPeerBuilder, + sample_issue_time, MockStatsEventSender, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; @@ -1001,7 +1013,7 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); @@ -1046,7 +1058,7 @@ mod tests { #[tokio::test] async fn should_send_the_upd4_announce_event() { - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Udp4Announce)) @@ -1141,18 +1153,18 @@ mod tests { AnnounceInterval, AnnounceResponse, InfoHash as AquaticInfoHash, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfPeers, PeerId as AquaticPeerId, Response, ResponsePeer, }; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::{statistics, whitelist}; use mockall::predicate::eq; use torrust_tracker_configuration::Core; - use crate::core::announce_handler::AnnounceHandler; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::{statistics, whitelist}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ gen_remote_fingerprint, initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, - sample_issue_time, TorrentPeerBuilder, + sample_issue_time, MockStatsEventSender, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; @@ -1306,7 +1318,7 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let (stats_event_sender, _stats_repository) = crate::core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); @@ -1354,7 +1366,7 @@ mod tests { #[tokio::test] async fn should_send_the_upd6_announce_event() { - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Udp6Announce)) @@ -1390,20 +1402,21 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::statistics; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use mockall::predicate::eq; - use crate::core::announce_handler::AnnounceHandler; - use crate::core::databases::setup::initialize_database; - use crate::core::statistics; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - use crate::core::whitelist::authorization::WhitelistAuthorization; - use crate::core::whitelist::repository::in_memory::InMemoryWhitelist; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - gen_remote_fingerprint, sample_cookie_valid_range, sample_issue_time, TrackerConfigurationBuilder, + gen_remote_fingerprint, sample_cookie_valid_range, sample_issue_time, MockStatsEventSender, + TrackerConfigurationBuilder, }; #[tokio::test] @@ -1417,7 +1430,7 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Udp6Announce)) @@ -1491,11 +1504,11 @@ mod tests { InfoHash, NumberOfDownloads, NumberOfPeers, PeerId, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; + use bittorrent_tracker_core::scrape_handler::ScrapeHandler; + use bittorrent_tracker_core::statistics; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use super::{gen_remote_fingerprint, TorrentPeerBuilder}; - use crate::core::scrape_handler::ScrapeHandler; - use crate::core::statistics; - use crate::core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ @@ -1734,19 +1747,19 @@ mod tests { use std::future; use std::sync::Arc; + use bittorrent_tracker_core::statistics; use mockall::predicate::eq; use super::sample_scrape_request; - use crate::core::statistics; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, - sample_ipv4_remote_addr, + sample_ipv4_remote_addr, MockStatsEventSender, }; #[tokio::test] async fn should_send_the_upd4_scrape_event() { - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Udp4Scrape)) @@ -1775,19 +1788,19 @@ mod tests { use std::future; use std::sync::Arc; + use bittorrent_tracker_core::statistics; use mockall::predicate::eq; use super::sample_scrape_request; - use crate::core::statistics; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, - sample_ipv6_remote_addr, + sample_ipv6_remote_addr, MockStatsEventSender, }; #[tokio::test] async fn should_send_the_upd6_scrape_event() { - let mut stats_event_sender_mock = statistics::event::sender::MockSender::new(); + let mut stats_event_sender_mock = MockStatsEventSender::new(); stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Udp6Scrape)) diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index e4edadd8f..89b9b54d9 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use std::time::Duration; use bittorrent_tracker_client::udp::client::check; +use bittorrent_tracker_core::statistics; use derive_more::Constructor; use futures_util::StreamExt; use tokio::select; @@ -13,7 +14,6 @@ use tracing::instrument; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; use crate::container::UdpTrackerContainer; -use crate::core::statistics; use crate::servers::logging::STARTED_ON; use crate::servers::registar::ServiceHealthCheckJob; use crate::servers::signals::{shutdown_signal_with_message, Halted}; diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index e2beb2377..db444a04c 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -4,13 +4,13 @@ use std::sync::Arc; use std::time::Duration; use aquatic_udp_protocol::Response; +use bittorrent_tracker_core::statistics; +use bittorrent_tracker_core::statistics::event::UdpResponseKind; use tokio::time::Instant; use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; use crate::container::UdpTrackerContainer; -use crate::core::statistics; -use crate::core::statistics::event::UdpResponseKind; use crate::servers::udp::handlers::CookieTimeValues; use crate::servers::udp::{handlers, RawRequest}; diff --git a/src/shared/bit_torrent/common.rs b/src/shared/bit_torrent/common.rs index 2f93b5a08..0364071c6 100644 --- a/src/shared/bit_torrent/common.rs +++ b/src/shared/bit_torrent/common.rs @@ -14,9 +14,3 @@ /// does not specifically mention this limit, but the limit is being used for /// both the UDP and HTTP trackers since it's applied at the domain level. pub const MAX_SCRAPE_TORRENTS: u8 = 74; - -/// HTTP tracker authentication key length. -/// -/// For more information see function [`generate_key`](crate::core::authentication::key::generate_key) to generate the -/// [`PeerKey`](crate::core::authentication::PeerKey). -pub const AUTH_KEY_LENGTH: usize = 32; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 297e169d4..219c28b6e 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -2,14 +2,14 @@ use std::net::SocketAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::databases::Database; use futures::executor::block_on; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::container::HttpApiContainer; -use torrust_tracker_lib::core::authentication::service::AuthenticationService; -use torrust_tracker_lib::core::databases::Database; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; diff --git a/tests/servers/api/mod.rs b/tests/servers/api/mod.rs index 92bc19a5f..8f5f6d016 100644 --- a/tests/servers/api/mod.rs +++ b/tests/servers/api/mod.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use torrust_tracker_lib::core::databases::Database; +use bittorrent_tracker_core::databases::Database; use torrust_tracker_lib::servers::apis::server; pub mod connection_info; diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 3242c3ccc..47cf0ecd2 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -1,8 +1,8 @@ use std::time::Duration; +use bittorrent_tracker_core::authentication::Key; use serde::Serialize; use torrust_tracker_api_client::v1::client::{headers_with_request_id, AddKeyForm, Client}; -use torrust_tracker_lib::core::authentication::Key; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; @@ -469,8 +469,8 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { mod deprecated_generate_key_endpoint { + use bittorrent_tracker_core::authentication::Key; use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; - use torrust_tracker_lib::core::authentication::Key; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; diff --git a/tests/servers/http/client.rs b/tests/servers/http/client.rs index 9fc278536..ca9703858 100644 --- a/tests/servers/http/client.rs +++ b/tests/servers/http/client.rs @@ -1,7 +1,7 @@ use std::net::IpAddr; +use bittorrent_tracker_core::authentication::Key; use reqwest::{Client as ReqwestClient, Response}; -use torrust_tracker_lib::core::authentication::Key; use super::requests::announce::{self, Query}; use super::requests::scrape; diff --git a/tests/servers/http/connection_info.rs b/tests/servers/http/connection_info.rs index 327bc0073..91486a3a7 100644 --- a/tests/servers/http/connection_info.rs +++ b/tests/servers/http/connection_info.rs @@ -1,4 +1,4 @@ -use torrust_tracker_lib::core::authentication::Key; +use bittorrent_tracker_core::authentication::Key; #[derive(Clone, Debug)] pub struct ConnectionInfo { diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 07ff2bc8c..c91be1544 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -1,16 +1,16 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::authentication::handler::KeysHandler; +use bittorrent_tracker_core::databases::Database; +use bittorrent_tracker_core::statistics::repository::Repository; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use futures::executor::block_on; use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::container::HttpTrackerContainer; -use torrust_tracker_lib::core::authentication::handler::KeysHandler; -use torrust_tracker_lib::core::databases::Database; -use torrust_tracker_lib::core::statistics::repository::Repository; -use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; -use torrust_tracker_lib::core::whitelist::manager::WhitelistManager; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index f434467fc..be603161a 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -1387,7 +1387,7 @@ mod configured_as_private { use std::time::Duration; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_lib::core::authentication::Key; + use bittorrent_tracker_core::authentication::Key; use torrust_tracker_test_helpers::configuration; use crate::common::logging; @@ -1477,7 +1477,7 @@ mod configured_as_private { use aquatic_udp_protocol::PeerId; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_lib::core::authentication::Key; + use bittorrent_tracker_core::authentication::Key; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index af0b04e5c..1483e1e5f 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -2,12 +2,12 @@ use std::net::SocketAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::databases::Database; +use bittorrent_tracker_core::statistics::repository::Repository; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use torrust_tracker_configuration::{Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::container::UdpTrackerContainer; -use torrust_tracker_lib::core::databases::Database; -use torrust_tracker_lib::core::statistics::repository::Repository; -use torrust_tracker_lib::core::torrent::repository::in_memory::InMemoryTorrentRepository; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; From 8bb376de40bd0284290a94b706b79a83cbb03996 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 30 Jan 2025 07:53:33 +0000 Subject: [PATCH 0683/1297] chore(deps): udpate dependencies ``` cargo update Updating crates.io index Locking 22 packages to latest compatible versions Updating bumpalo v3.16.0 -> v3.17.0 Updating cmake v0.1.52 -> v0.1.53 Updating cpufeatures v0.2.16 -> v0.2.17 Adding getrandom v0.3.1 Updating httparse v1.9.5 -> v1.10.0 Updating hyper v1.5.2 -> v1.6.0 Updating native-tls v0.2.12 -> v0.2.13 Updating openssl v0.10.68 -> v0.10.69 Updating openssl-probe v0.1.5 -> v0.1.6 Adding rand v0.9.0 Adding rand_chacha v0.9.0 Adding rand_core v0.9.0 Updating rustls-pki-types v1.10.1 -> v1.11.0 Updating ryu v1.0.18 -> v1.0.19 Updating serde_json v1.0.137 -> v1.0.138 Updating tempfile v3.15.0 -> v3.16.0 Updating unicode-ident v1.0.14 -> v1.0.16 Adding wasi v0.13.3+wasi-0.2.2 Updating winnow v0.6.24 -> v0.6.25 Adding wit-bindgen-rt v0.33.0 Adding zerocopy v0.8.14 Adding zerocopy-derive v0.8.14 ``` --- Cargo.lock | 193 +++++++++++++----- packages/test-helpers/src/random.rs | 6 +- .../src/authentication/key/mod.rs | 6 +- src/console/ci/e2e/tracker_container.rs | 8 +- src/shared/crypto/ephemeral_instance_keys.rs | 4 +- tests/common/fixtures.rs | 8 +- 6 files changed, 151 insertions(+), 74 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d0d4d7e8f..bbf225018 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,7 +23,7 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" dependencies = [ - "getrandom", + "getrandom 0.2.15", "once_cell", "version_check", ] @@ -146,7 +146,7 @@ dependencies = [ "quickcheck", "regex", "serde", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -158,7 +158,7 @@ dependencies = [ "aquatic_peer_id", "byteorder", "either", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -565,7 +565,7 @@ dependencies = [ "serde", "serde_json", "thiserror 1.0.69", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -588,7 +588,7 @@ dependencies = [ "torrust-tracker-located-error", "torrust-tracker-primitives", "tracing", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -606,7 +606,7 @@ dependencies = [ "r2d2", "r2d2_mysql", "r2d2_sqlite", - "rand", + "rand 0.9.0", "serde", "serde_json", "thiserror 2.0.11", @@ -735,9 +735,9 @@ checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" [[package]] name = "bumpalo" -version = "3.16.0" +version = "3.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" +checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" [[package]] name = "bytecheck" @@ -938,9 +938,9 @@ checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" [[package]] name = "cmake" -version = "0.1.52" +version = "0.1.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c682c223677e0e5b6b7f63a64b9351844c3f1b1678a68b7ee617e30fb082620e" +checksum = "e24a03c8b52922d68a1589ad61032f2c1aa5a8158d2aa0d93c6e9534944bbad6" dependencies = [ "cc", ] @@ -991,9 +991,9 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "cpufeatures" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16b80225097f2e5ae4e7179dd2266824648f3e2f49d9134d584b76389d31c4c3" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" dependencies = [ "libc", ] @@ -1598,7 +1598,19 @@ checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", - "wasi", + "wasi 0.11.0+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.13.3+wasi-0.2.2", + "windows-targets", ] [[package]] @@ -1749,9 +1761,9 @@ dependencies = [ [[package]] name = "httparse" -version = "1.9.5" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d71d3574edd2771538b901e6549113b4006ece66150fb69c0fb6d9a2adae946" +checksum = "f2d708df4e7140240a16cd6ab0ab65c972d7433ab77819ea693fde9c43811e2a" [[package]] name = "httpdate" @@ -1761,9 +1773,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.5.2" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "256fb8d4bd6413123cc9d91832d78325c48ff41677595be797d90f42969beae0" +checksum = "cc2b571658e38e0c01b1fdca3bbbe93c00d3d71693ff2770043f8c29bc7d6f80" dependencies = [ "bytes", "futures-channel", @@ -2263,7 +2275,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" dependencies = [ "libc", - "wasi", + "wasi 0.11.0+wasi-snapshot-preview1", "windows-sys 0.52.0", ] @@ -2368,7 +2380,7 @@ dependencies = [ "mysql-common-derive", "num-bigint", "num-traits", - "rand", + "rand 0.8.5", "regex", "rust_decimal", "saturating", @@ -2395,9 +2407,9 @@ dependencies = [ [[package]] name = "native-tls" -version = "0.2.12" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8614eb2c83d59d1c8cc974dd3f920198647674a0a035e1af1fa58707e317466" +checksum = "0dab59f8e050d5df8e4dd87d9206fb6f65a483e20ac9fda365ade4fab353196c" dependencies = [ "libc", "log", @@ -2518,9 +2530,9 @@ checksum = "b410bbe7e14ab526a0e86877eb47c6996a2bd7746f027ba551028c925390e4e9" [[package]] name = "openssl" -version = "0.10.68" +version = "0.10.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6174bc48f102d208783c2c84bf931bb75927a617866870de8a4ea85597f871f5" +checksum = "f5e534d133a060a3c19daec1eb3e98ec6f4685978834f2dbadfe2ec215bab64e" dependencies = [ "bitflags", "cfg-if", @@ -2544,9 +2556,9 @@ dependencies = [ [[package]] name = "openssl-probe" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" +checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" [[package]] name = "openssl-sys" @@ -2660,7 +2672,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ "phf_shared", - "rand", + "rand 0.8.5", ] [[package]] @@ -2782,7 +2794,7 @@ version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" dependencies = [ - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -2892,7 +2904,7 @@ checksum = "588f6378e4dd99458b60ec275b4477add41ce4fa9f64dcba6f15adccb19b50d6" dependencies = [ "env_logger", "log", - "rand", + "rand 0.8.5", ] [[package]] @@ -2949,8 +2961,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", - "rand_chacha", - "rand_core", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.0", + "zerocopy 0.8.14", ] [[package]] @@ -2960,7 +2983,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.0", ] [[package]] @@ -2969,7 +3002,17 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom", + "getrandom 0.2.15", +] + +[[package]] +name = "rand_core" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b08f3c9802962f7e1b25113931d94f43ed9725bebc59db9d0c3e9a23b67e15ff" +dependencies = [ + "getrandom 0.3.1", + "zerocopy 0.8.14", ] [[package]] @@ -3097,7 +3140,7 @@ checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" dependencies = [ "cc", "cfg-if", - "getrandom", + "getrandom 0.2.15", "libc", "spin", "untrusted", @@ -3197,7 +3240,7 @@ dependencies = [ "borsh", "bytes", "num-traits", - "rand", + "rand 0.8.5", "rkyv", "serde", "serde_json", @@ -3261,9 +3304,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.10.1" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2bf47e6ff922db3825eb750c4e2ff784c6ff8fb9e13046ef6a1d1c5401b0b37" +checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c" [[package]] name = "rustls-webpki" @@ -3284,9 +3327,9 @@ checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4" [[package]] name = "ryu" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" +checksum = "6ea1a2d0a644769cc99faa24c3ad26b379b786fe7c36fd3c546254801650e6dd" [[package]] name = "same-file" @@ -3416,9 +3459,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.137" +version = "1.0.138" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "930cfb6e6abf99298aaad7d29abbef7a9999a9a8806a40088f55f0dcec03146b" +checksum = "d434192e7da787e94a6ea7e9670b26a036d0ca41e0b7efb2676dd32bae872949" dependencies = [ "indexmap 2.7.1", "itoa", @@ -3710,13 +3753,13 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.15.0" +version = "3.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8a559c81686f576e8cd0290cd2a24a2a9ad80c98b3478856500fcbd7acd704" +checksum = "38c246215d7d24f48ae091a2902398798e05d978b24315d6efbc00ede9a8bb91" dependencies = [ "cfg-if", "fastrand", - "getrandom", + "getrandom 0.3.1", "once_cell", "rustix", "windows-sys 0.59.0", @@ -3986,7 +4029,7 @@ dependencies = [ "r2d2", "r2d2_mysql", "r2d2_sqlite", - "rand", + "rand 0.9.0", "regex", "reqwest", "ringbuf", @@ -4011,7 +4054,7 @@ dependencies = [ "tracing-subscriber", "url", "uuid", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -4106,14 +4149,14 @@ dependencies = [ "tdyne-peer-id-registry", "thiserror 2.0.11", "torrust-tracker-configuration", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] name = "torrust-tracker-test-helpers" version = "3.0.0-develop" dependencies = [ - "rand", + "rand 0.9.0", "torrust-tracker-configuration", ] @@ -4134,7 +4177,7 @@ dependencies = [ "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-primitives", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -4285,7 +4328,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" dependencies = [ "cfg-if", - "rand", + "rand 0.8.5", "static_assertions", ] @@ -4306,9 +4349,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.14" +version = "1.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" +checksum = "a210d160f08b701c8721ba1c726c11662f877ea6b7094007e1ca9a1041945034" [[package]] name = "unicode-xid" @@ -4358,8 +4401,8 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b3758f5e68192bb96cc8f9b7e2c2cfdabb435499a28499a42f8f984092adad4b" dependencies = [ - "getrandom", - "rand", + "getrandom 0.2.15", + "rand 0.8.5", ] [[package]] @@ -4411,6 +4454,15 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +[[package]] +name = "wasi" +version = "0.13.3+wasi-0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2" +dependencies = [ + "wit-bindgen-rt", +] + [[package]] name = "wasm-bindgen" version = "0.2.100" @@ -4646,13 +4698,22 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "0.6.24" +version = "0.6.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d71a593cc5c42ad7876e2c1fda56f314f3754c084128833e64f1345ff8a03a" +checksum = "ad699df48212c6cc6eb4435f35500ac6fd3b9913324f938aea302022ce19d310" dependencies = [ "memchr", ] +[[package]] +name = "wit-bindgen-rt" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" +dependencies = [ + "bitflags", +] + [[package]] name = "write16" version = "1.0.0" @@ -4711,7 +4772,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ "byteorder", - "zerocopy-derive", + "zerocopy-derive 0.7.35", +] + +[[package]] +name = "zerocopy" +version = "0.8.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a367f292d93d4eab890745e75a778da40909cab4d6ff8173693812f79c4a2468" +dependencies = [ + "zerocopy-derive 0.8.14", ] [[package]] @@ -4725,6 +4795,17 @@ dependencies = [ "syn 2.0.96", ] +[[package]] +name = "zerocopy-derive" +version = "0.8.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3931cb58c62c13adec22e38686b559c86a30565e16ad6e8510a337cedc611e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.96", +] + [[package]] name = "zerofrom" version = "0.1.5" diff --git a/packages/test-helpers/src/random.rs b/packages/test-helpers/src/random.rs index 2133dcd29..f096d695c 100644 --- a/packages/test-helpers/src/random.rs +++ b/packages/test-helpers/src/random.rs @@ -1,10 +1,10 @@ //! Random data generators for testing. -use rand::distributions::Alphanumeric; -use rand::{thread_rng, Rng}; +use rand::distr::Alphanumeric; +use rand::{rng, Rng}; /// Returns a random alphanumeric string of a certain size. /// /// It is useful for generating random names, IDs, etc for testing. pub fn string(size: usize) -> String { - thread_rng().sample_iter(&Alphanumeric).take(size).map(char::from).collect() + rng().sample_iter(&Alphanumeric).take(size).map(char::from).collect() } diff --git a/packages/tracker-core/src/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs index 37fc4764b..e3e7fc018 100644 --- a/packages/tracker-core/src/authentication/key/mod.rs +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -45,8 +45,8 @@ use std::sync::Arc; use std::time::Duration; use derive_more::Display; -use rand::distributions::Alphanumeric; -use rand::{thread_rng, Rng}; +use rand::distr::Alphanumeric; +use rand::{rng, Rng}; use serde::{Deserialize, Serialize}; use thiserror::Error; use torrust_tracker_clock::clock::Time; @@ -81,7 +81,7 @@ pub fn generate_permanent_key() -> PeerKey { /// * `lifetime`: if `None` the key will be permanent. #[must_use] pub fn generate_key(lifetime: Option) -> PeerKey { - let random_id: String = thread_rng() + let random_id: String = rng() .sample_iter(&Alphanumeric) .take(AUTH_KEY_LENGTH) .map(char::from) diff --git a/src/console/ci/e2e/tracker_container.rs b/src/console/ci/e2e/tracker_container.rs index 0d15035a8..a3845c103 100644 --- a/src/console/ci/e2e/tracker_container.rs +++ b/src/console/ci/e2e/tracker_container.rs @@ -1,6 +1,6 @@ use std::time::Duration; -use rand::distributions::Alphanumeric; +use rand::distr::Alphanumeric; use rand::Rng; use super::docker::{RunOptions, RunningContainer}; @@ -113,11 +113,7 @@ impl TrackerContainer { } fn generate_random_container_name(prefix: &str) -> String { - let rand_string: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(20) - .map(char::from) - .collect(); + let rand_string: String = rand::rng().sample_iter(&Alphanumeric).take(20).map(char::from).collect(); format!("{prefix}{rand_string}") } diff --git a/src/shared/crypto/ephemeral_instance_keys.rs b/src/shared/crypto/ephemeral_instance_keys.rs index d214b6e6a..df560c3f5 100644 --- a/src/shared/crypto/ephemeral_instance_keys.rs +++ b/src/shared/crypto/ephemeral_instance_keys.rs @@ -15,10 +15,10 @@ pub type CipherArrayBlowfish = GenericArray(&mut ThreadRng::default())).expect("it could not generate key"); + pub static ref RANDOM_CIPHER_BLOWFISH: CipherBlowfish = CipherBlowfish::new_from_slice(&Rng::random::(&mut ThreadRng::default())).expect("it could not generate key"); /// The constant cipher for testing. pub static ref ZEROED_TEST_CIPHER_BLOWFISH: CipherBlowfish = CipherBlowfish::new_from_slice(&[0u8; 32]).expect("it could not generate key"); diff --git a/tests/common/fixtures.rs b/tests/common/fixtures.rs index f96b03dd1..1dd85ba2d 100644 --- a/tests/common/fixtures.rs +++ b/tests/common/fixtures.rs @@ -8,7 +8,7 @@ pub fn invalid_info_hashes() -> Vec { "-1".to_string(), "1.1".to_string(), "INVALID INFOHASH".to_string(), - "9c38422213e30bff212b30c360d26f9a0213642".to_string(), // 39-char length instead of 40 + "9c38422213e30bff212b30c360d26f9a0213642".to_string(), // 39-char length instead of 40. DevSkim: ignore DS173237 "9c38422213e30bff212b30c360d26f9a0213642&".to_string(), // Invalid char ] .to_vec() @@ -16,14 +16,14 @@ pub fn invalid_info_hashes() -> Vec { /// Returns a random info hash. pub fn random_info_hash() -> InfoHash { - let mut rng = rand::thread_rng(); - let random_bytes: [u8; 20] = rand::Rng::gen(&mut rng); + let mut rng = rand::rng(); + let random_bytes: [u8; 20] = rand::Rng::random(&mut rng); InfoHash::from_bytes(&random_bytes) } /// Returns a random transaction id. pub fn random_transaction_id() -> TransactionId { - let random_value = rand::Rng::gen::(&mut rand::thread_rng()); + let random_value = rand::Rng::random::(&mut rand::rng()); TransactionId::new(random_value) } From 9fa7b6172e04d453ac19c2741af403e0bac98d4f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 30 Jan 2025 16:26:48 +0000 Subject: [PATCH 0684/1297] fix: clippy errors on nightly nightly-x86_64-unknown-linux-gnu (default) rustc 1.86.0-nightly (ae5de6c75 2025-01-29) --- contrib/bencode/src/mutable/bencode_mut.rs | 5 +---- contrib/bencode/src/reference/bencode_ref.rs | 5 +---- contrib/bencode/src/reference/decode.rs | 3 ++- packages/test-helpers/src/configuration.rs | 2 +- .../torrent-repository/tests/common/repo.rs | 2 +- packages/tracker-api-client/src/v1/client.rs | 2 +- packages/tracker-client/src/udp/client.rs | 2 +- src/app.rs | 4 ++-- src/console/ci/e2e/logs_parser.rs | 2 +- .../apis/v1/context/auth_key/handlers.rs | 18 +++++++++--------- src/servers/udp/server/launcher.rs | 2 +- tests/servers/udp/contract.rs | 12 ++++++------ 12 files changed, 27 insertions(+), 32 deletions(-) diff --git a/contrib/bencode/src/mutable/bencode_mut.rs b/contrib/bencode/src/mutable/bencode_mut.rs index a3f95dbbf..21e00f7b0 100644 --- a/contrib/bencode/src/mutable/bencode_mut.rs +++ b/contrib/bencode/src/mutable/bencode_mut.rs @@ -82,10 +82,7 @@ impl<'a> BRefAccess for BencodeMut<'a> { fn str(&self) -> Option<&str> { let bytes = self.bytes()?; - match str::from_utf8(bytes) { - Ok(n) => Some(n), - Err(_) => None, - } + str::from_utf8(bytes).ok() } fn int(&self) -> Option { diff --git a/contrib/bencode/src/reference/bencode_ref.rs b/contrib/bencode/src/reference/bencode_ref.rs index 73aaad039..20d102cb4 100644 --- a/contrib/bencode/src/reference/bencode_ref.rs +++ b/contrib/bencode/src/reference/bencode_ref.rs @@ -107,10 +107,7 @@ impl<'a> BRefAccessExt<'a> for BencodeRef<'a> { fn str_ext(&self) -> Option<&'a str> { let bytes = self.bytes_ext()?; - match str::from_utf8(bytes) { - Ok(n) => Some(n), - Err(_) => None, - } + str::from_utf8(bytes).ok() } fn bytes_ext(&self) -> Option<&'a [u8]> { diff --git a/contrib/bencode/src/reference/decode.rs b/contrib/bencode/src/reference/decode.rs index 97c5cf1ff..37ca22549 100644 --- a/contrib/bencode/src/reference/decode.rs +++ b/contrib/bencode/src/reference/decode.rs @@ -129,7 +129,8 @@ fn decode_dict( }) } _ => (), - }; + } + curr_pos = next_pos; let (value, next_pos) = decode(bytes, curr_pos, opts, depth + 1)?; diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index e5de53fc2..678f4283a 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -153,7 +153,7 @@ pub fn ephemeral_ipv6() -> Configuration { if let Some(ref mut http_api) = cfg.http_api { http_api.bind_address.clone_from(&ipv6); - }; + } if let Some(ref mut http_trackers) = cfg.http_trackers { http_trackers[0].bind_address.clone_from(&ipv6); diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index ebd829f3c..c8412952c 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -232,7 +232,7 @@ impl Repo { Repo::DashMapMutexStd(repo) => { repo.torrents.insert(*info_hash, torrent.into()); } - }; + } self.get(info_hash).await } } diff --git a/packages/tracker-api-client/src/v1/client.rs b/packages/tracker-api-client/src/v1/client.rs index d48d4c008..54daa3289 100644 --- a/packages/tracker-api-client/src/v1/client.rs +++ b/packages/tracker-api-client/src/v1/client.rs @@ -67,7 +67,7 @@ impl Client { if let Some(token) = &self.connection_info.api_token { query.add_param(QueryParam::new("token", token)); - }; + } self.get_request_with_query(path, query, headers).await } diff --git a/packages/tracker-client/src/udp/client.rs b/packages/tracker-client/src/udp/client.rs index facdfac38..89a33726d 100644 --- a/packages/tracker-client/src/udp/client.rs +++ b/packages/tracker-client/src/udp/client.rs @@ -243,7 +243,7 @@ pub async fn check(remote_addr: &SocketAddr) -> Result { match client.send(connect_request.into()).await { Ok(_) => (), Err(e) => tracing::debug!("Error: {e:?}."), - }; + } let process = move |response| { if matches!(response, Response::Connect(_connect_response)) { diff --git a/src/app.rs b/src/app.rs index 13bdc904a..d69874eb0 100644 --- a/src/app.rs +++ b/src/app.rs @@ -98,7 +98,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> http_tracker::start_job(http_tracker_container, registar.give_form(), servers::http::Version::V1).await { jobs.push(job); - }; + } } } else { tracing::info!("No HTTP blocks in configuration"); @@ -111,7 +111,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> if let Some(job) = tracker_apis::start_job(http_api_container, registar.give_form(), servers::apis::Version::V1).await { jobs.push(job); - }; + } } else { tracing::info!("No API block in configuration"); } diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index 95648a2b5..b39143c8f 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -76,7 +76,7 @@ impl RunningServices { if !line.contains(INFO_THRESHOLD) { continue; - }; + } if line.contains(UDP_TRACKER_LOG_TARGET) { if let Some(captures) = udp_re.captures(&clean_line) { diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index 7024ffeba..ca38ade37 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -22,11 +22,11 @@ use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_re /// It returns these types of responses: /// /// - `200` with a json [`AuthKey`] -/// resource. If the key was generated successfully. +/// resource. If the key was generated successfully. /// - `400` with an error if the key couldn't been added because of an invalid -/// request. +/// request. /// - `500` with serialized error in debug format. If the key couldn't be -/// generated. +/// generated. /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#generate-a-new-authentication-key) /// for more information about this endpoint. @@ -57,9 +57,9 @@ pub async fn add_auth_key_handler( /// It returns two types of responses: /// /// - `200` with an json [`AuthKey`] -/// resource. If the key was generated successfully. +/// resource. If the key was generated successfully. /// - `500` with serialized error in debug format. If the key couldn't be -/// generated. +/// generated. /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#generate-a-new-authentication-key) /// for more information about this endpoint. @@ -99,9 +99,9 @@ pub struct KeyParam(String); /// It returns two types of responses: /// /// - `200` with an json [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) -/// response. If the key was deleted successfully. +/// response. If the key was deleted successfully. /// - `500` with serialized error in debug format. If the key couldn't be -/// deleted. +/// deleted. /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#delete-an-authentication-key) /// for more information about this endpoint. @@ -124,9 +124,9 @@ pub async fn delete_auth_key_handler( /// It returns two types of responses: /// /// - `200` with an json [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) -/// response. If the keys were successfully reloaded. +/// response. If the keys were successfully reloaded. /// - `500` with serialized error in debug format. If the they couldn't be -/// reloaded. +/// reloaded. /// /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#reload-authentication-keys) /// for more information about this endpoint. diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 89b9b54d9..bbf2718ff 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -213,7 +213,7 @@ impl Launcher { stats_event_sender .send_event(statistics::event::Event::UdpRequestAborted) .await; - }; + } } } else { tokio::task::yield_now().await; diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index f6a1feb06..d38356ef4 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -25,7 +25,7 @@ async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrac match client.send(connect_request.into()).await { Ok(_) => (), Err(err) => panic!("{err}"), - }; + } let response = match client.receive().await { Ok(response) => response, @@ -52,7 +52,7 @@ async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_req match client.client.send(&empty_udp_request()).await { Ok(_) => (), Err(err) => panic!("{err}"), - }; + } let response = match client.client.receive().await { Ok(response) => response, @@ -94,7 +94,7 @@ mod receiving_a_connection_request { match client.send(connect_request.into()).await { Ok(_) => (), Err(err) => panic!("{err}"), - }; + } let response = match client.receive().await { Ok(response) => response, @@ -146,7 +146,7 @@ mod receiving_an_announce_request { match client.send(announce_request.into()).await { Ok(_) => (), Err(err) => panic!("{err}"), - }; + } match client.receive().await { Ok(response) => response, @@ -276,7 +276,7 @@ mod receiving_an_announce_request { match client.send(announce_request.into()).await { Ok(_) => (), Err(err) => panic!("{err}"), - }; + } assert!(client.receive().await.is_err()); @@ -333,7 +333,7 @@ mod receiving_an_scrape_request { match client.send(scrape_request.into()).await { Ok(_) => (), Err(err) => panic!("{err}"), - }; + } let response = match client.receive().await { Ok(response) => response, From 0ad88b620c715a9abcdbe5ad29528069716779b7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 31 Jan 2025 09:56:04 +0000 Subject: [PATCH 0685/1297] refactor: [#1228] move type from tracker-core to main lib This is the frist step in a bigger refactor. We will move statistics out of the tracker-core package into new packages. Statistics are not related to the tracker-core or enven handled there. That logic belongs to upper layers. --- packages/tracker-core/src/statistics/mod.rs | 1 - .../tracker-core/src/statistics/services.rs | 55 ------------------- src/core/statistics/services.rs | 27 ++++++--- .../apis/v1/context/stats/resources.rs | 5 +- .../apis/v1/context/stats/responses.rs | 2 +- 5 files changed, 24 insertions(+), 66 deletions(-) delete mode 100644 packages/tracker-core/src/statistics/services.rs diff --git a/packages/tracker-core/src/statistics/mod.rs b/packages/tracker-core/src/statistics/mod.rs index 2ffbc0c8f..7517bab6e 100644 --- a/packages/tracker-core/src/statistics/mod.rs +++ b/packages/tracker-core/src/statistics/mod.rs @@ -28,5 +28,4 @@ pub mod event; pub mod keeper; pub mod metrics; pub mod repository; -pub mod services; pub mod setup; diff --git a/packages/tracker-core/src/statistics/services.rs b/packages/tracker-core/src/statistics/services.rs deleted file mode 100644 index 196c6b340..000000000 --- a/packages/tracker-core/src/statistics/services.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! Statistics services. -//! -//! It includes: -//! -//! - A [`factory`](crate::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. -//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::core::statistics::metrics::Metrics). -//! -//! Tracker metrics are collected using a Publisher-Subscribe pattern. -//! -//! The factory function builds two structs: -//! -//! - An statistics event [`Sender`](crate::core::statistics::event::sender::Sender) -//! - An statistics [`Repository`] -//! -//! ```text -//! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); -//! ``` -//! -//! The statistics repository is responsible for storing the metrics in memory. -//! The statistics event sender allows sending events related to metrics. -//! There is an event listener that is receiving all the events and processing them with an event handler. -//! Then, the event handler updates the metrics depending on the received event. -//! -//! For example, if you send the event [`Event::Udp4Connect`](crate::core::statistics::event::Event::Udp4Connect): -//! -//! ```text -//! let result = event_sender.send_event(Event::Udp4Connect).await; -//! ``` -//! -//! Eventually the counter for UDP connections from IPv4 peers will be increased. -//! -//! ```rust,no_run -//! pub struct Metrics { -//! // ... -//! pub udp4_connections_handled: u64, // This will be incremented -//! // ... -//! } -//! ``` -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; - -use crate::statistics::metrics::Metrics; - -/// All the metrics collected by the tracker. -#[derive(Debug, PartialEq)] -pub struct TrackerMetrics { - /// Domain level metrics. - /// - /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: TorrentsMetrics, - - /// Application level metrics. Usage statistics/metrics. - /// - /// Metrics about how the tracker is been used (number of udp announce requests, number of http scrape requests, etcetera) - pub protocol_metrics: Metrics, -} diff --git a/src/core/statistics/services.rs b/src/core/statistics/services.rs index a4bcc411e..514f126f9 100644 --- a/src/core/statistics/services.rs +++ b/src/core/statistics/services.rs @@ -2,14 +2,14 @@ //! //! It includes: //! -//! - A [`factory`](bittorrent_tracker_core::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. -//! - A [`get_metrics`] service to get the tracker [`metrics`](bittorrent_tracker_core::statistics::metrics::Metrics). +//! - A [`factory`](crate::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::core::statistics::metrics::Metrics). //! //! Tracker metrics are collected using a Publisher-Subscribe pattern. //! //! The factory function builds two structs: //! -//! - An statistics event [`Sender`](bittorrent_tracker_core::statistics::event::sender::Sender) +//! - An statistics event [`Sender`](crate::core::statistics::event::sender::Sender) //! - An statistics [`Repository`] //! //! ```text @@ -21,7 +21,7 @@ //! There is an event listener that is receiving all the events and processing them with an event handler. //! Then, the event handler updates the metrics depending on the received event. //! -//! For example, if you send the event [`Event::Udp4Connect`](bittorrent_tracker_core::statistics::event::Event::Udp4Connect): +//! For example, if you send the event [`Event::Udp4Connect`](crate::core::statistics::event::Event::Udp4Connect): //! //! ```text //! let result = event_sender.send_event(Event::Udp4Connect).await; @@ -40,12 +40,26 @@ use std::sync::Arc; use bittorrent_tracker_core::statistics::metrics::Metrics; use bittorrent_tracker_core::statistics::repository::Repository; -use bittorrent_tracker_core::statistics::services::TrackerMetrics; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use tokio::sync::RwLock; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use crate::servers::udp::server::banning::BanService; +/// All the metrics collected by the tracker. +#[derive(Debug, PartialEq)] +pub struct TrackerMetrics { + /// Domain level metrics. + /// + /// General metrics for all torrents (number of seeders, leechers, etcetera) + pub torrents_metrics: TorrentsMetrics, + + /// Application level metrics. Usage statistics/metrics. + /// + /// Metrics about how the tracker is been used (number of udp announce requests, number of http scrape requests, etcetera) + pub protocol_metrics: Metrics, +} + /// It returns all the [`TrackerMetrics`] pub async fn get_metrics( in_memory_torrent_repository: Arc, @@ -96,7 +110,6 @@ pub async fn get_metrics( mod tests { use std::sync::Arc; - use bittorrent_tracker_core::statistics::services::TrackerMetrics; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self, statistics}; use tokio::sync::RwLock; @@ -104,7 +117,7 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; - use crate::core::statistics::services::get_metrics; + use crate::core::statistics::services::{get_metrics, TrackerMetrics}; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index d4a0ec7ec..7b2242d40 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -1,8 +1,9 @@ //! API resources for the [`stats`](crate::servers::apis::v1::context::stats) //! API context. -use bittorrent_tracker_core::statistics::services::TrackerMetrics; use serde::{Deserialize, Serialize}; +use crate::core::statistics::services::TrackerMetrics; + /// It contains all the statistics generated by the tracker. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct Stats { @@ -118,10 +119,10 @@ impl From for Stats { #[cfg(test)] mod tests { use bittorrent_tracker_core::statistics::metrics::Metrics; - use bittorrent_tracker_core::statistics::services::TrackerMetrics; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use super::Stats; + use crate::core::statistics::services::TrackerMetrics; #[test] fn stats_resource_should_be_converted_from_tracker_metrics() { diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index fc74b5f8d..6fda43f8c 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -1,9 +1,9 @@ //! API responses for the [`stats`](crate::servers::apis::v1::context::stats) //! API context. use axum::response::{IntoResponse, Json, Response}; -use bittorrent_tracker_core::statistics::services::TrackerMetrics; use super::resources::Stats; +use crate::core::statistics::services::TrackerMetrics; /// `200` response that contains the [`Stats`] resource as json. #[must_use] From 9318842a2745921e3dc4a05ed1f9b632768aaf7d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 31 Jan 2025 10:23:30 +0000 Subject: [PATCH 0686/1297] refactor: [#1228] move statistics back from tracker-core to main lib The statistics are only used at the higher levels: UDP and HTTP tracker. We will move them to new packages. --- Cargo.lock | 1 - packages/tracker-core/Cargo.toml | 1 - packages/tracker-core/src/lib.rs | 3 +- packages/tracker-core/src/statistics/mod.rs | 31 ------------ src/bootstrap/app.rs | 4 +- src/container.rs | 5 +- src/core/statistics/mod.rs | 1 - src/lib.rs | 2 +- src/{core => packages}/mod.rs | 0 .../packages}/statistics/event/handler.rs | 10 ++-- .../packages}/statistics/event/listener.rs | 2 +- .../packages}/statistics/event/mod.rs | 0 .../packages}/statistics/event/sender.rs | 4 +- .../src => src/packages}/statistics/keeper.rs | 6 +-- .../packages}/statistics/metrics.rs | 0 src/packages/statistics/mod.rs | 6 +++ .../packages}/statistics/repository.rs | 0 src/{core => packages}/statistics/services.rs | 18 +++---- .../src => src/packages}/statistics/setup.rs | 6 +-- src/servers/apis/v1/context/stats/handlers.rs | 5 +- .../apis/v1/context/stats/resources.rs | 7 +-- .../apis/v1/context/stats/responses.rs | 2 +- src/servers/http/v1/handlers/announce.rs | 10 ++-- src/servers/http/v1/handlers/scrape.rs | 7 ++- src/servers/http/v1/services/announce.rs | 17 ++++--- src/servers/http/v1/services/scrape.rs | 22 +++++---- src/servers/udp/handlers.rs | 47 +++++++++++-------- src/servers/udp/server/launcher.rs | 3 +- src/servers/udp/server/processor.rs | 5 +- tests/servers/http/environment.rs | 3 +- tests/servers/udp/environment.rs | 3 +- 31 files changed, 118 insertions(+), 113 deletions(-) delete mode 100644 packages/tracker-core/src/statistics/mod.rs delete mode 100644 src/core/statistics/mod.rs rename src/{core => packages}/mod.rs (100%) rename {packages/tracker-core/src => src/packages}/statistics/event/handler.rs (96%) rename {packages/tracker-core/src => src/packages}/statistics/event/listener.rs (83%) rename {packages/tracker-core/src => src/packages}/statistics/event/mod.rs (100%) rename {packages/tracker-core/src => src/packages}/statistics/event/sender.rs (82%) rename {packages/tracker-core/src => src/packages}/statistics/keeper.rs (92%) rename {packages/tracker-core/src => src/packages}/statistics/metrics.rs (100%) create mode 100644 src/packages/statistics/mod.rs rename {packages/tracker-core/src => src/packages}/statistics/repository.rs (100%) rename src/{core => packages}/statistics/services.rs (90%) rename {packages/tracker-core/src => src/packages}/statistics/setup.rs (82%) diff --git a/Cargo.lock b/Cargo.lock index bbf225018..d868f7452 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -600,7 +600,6 @@ dependencies = [ "bittorrent-primitives", "chrono", "derive_more", - "futures", "local-ip-address", "mockall", "r2d2", diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index b38f7c90f..7b5b1f2c2 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -20,7 +20,6 @@ bittorrent-http-protocol = { version = "3.0.0-develop", path = "../http-protocol bittorrent-primitives = "0.1.0" chrono = { version = "0", default-features = false, features = ["clock"] } derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } -futures = "0" r2d2 = "0" r2d2_mysql = "25" r2d2_sqlite = { version = "0", features = ["bundled"] } diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index 2fb2d936d..ec4371322 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -346,7 +346,7 @@ //! //! Services are domain services on top of the core tracker domain. Right now there are two types of service: //! -//! - For statistics: [`crate::core::statistics::services`] +//! - For statistics: [`crate::packages::statistics::services`] //! - For torrents: [`crate::core::torrent::services`] //! //! Services usually format the data inside the tracker to make it easier to consume by other parts. @@ -442,7 +442,6 @@ pub mod authentication; pub mod databases; pub mod error; pub mod scrape_handler; -pub mod statistics; pub mod torrent; pub mod whitelist; diff --git a/packages/tracker-core/src/statistics/mod.rs b/packages/tracker-core/src/statistics/mod.rs deleted file mode 100644 index 7517bab6e..000000000 --- a/packages/tracker-core/src/statistics/mod.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! Structs to collect and keep tracker metrics. -//! -//! The tracker collects metrics such as: -//! -//! - Number of connections handled -//! - Number of `announce` requests handled -//! - Number of `scrape` request handled -//! -//! These metrics are collected for each connection type: UDP and HTTP and -//! also for each IP version used by the peers: IPv4 and IPv6. -//! -//! > Notice: that UDP tracker have an specific `connection` request. For the -//! > `HTTP` metrics the counter counts one connection for each `announce` or -//! > `scrape` request. -//! -//! The data is collected by using an `event-sender -> event listener` model. -//! -//! The tracker uses a [`Sender`](crate::core::statistics::event::sender::Sender) -//! instance to send an event. -//! -//! The [`statistics::keeper::Keeper`](crate::core::statistics::keeper::Keeper) listens to new -//! events and uses the [`statistics::repository::Repository`](crate::core::statistics::repository::Repository) to -//! upgrade and store metrics. -//! -//! See the [`statistics::event::Event`](crate::core::statistics::event::Event) enum to check -//! which events are available. -pub mod event; -pub mod keeper; -pub mod metrics; -pub mod repository; -pub mod setup; diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index f7506800e..7313b2808 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -20,13 +20,13 @@ use bittorrent_tracker_core::authentication::key::repository::persisted::Databas use bittorrent_tracker_core::authentication::service; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::statistics; use bittorrent_tracker_core::torrent::manager::TorrentsManager; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager; +use packages::statistics; use tokio::sync::RwLock; use torrust_tracker_clock::static_time; use torrust_tracker_configuration::validator::Validator; @@ -34,12 +34,12 @@ use torrust_tracker_configuration::Configuration; use tracing::instrument; use super::config::initialize_configuration; -use crate::bootstrap; use crate::container::AppContainer; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; use crate::shared::crypto::keys::{self, Keeper as _}; +use crate::{bootstrap, packages}; /// It loads the configuration from the environment and builds app container. /// diff --git a/src/container.rs b/src/container.rs index cae2d07ce..965dbfa2a 100644 --- a/src/container.rs +++ b/src/container.rs @@ -5,16 +5,17 @@ use bittorrent_tracker_core::authentication::handler::KeysHandler; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::Database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::statistics::event::sender::Sender; -use bittorrent_tracker_core::statistics::repository::Repository; use bittorrent_tracker_core::torrent::manager::TorrentsManager; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; +use packages::statistics::event::sender::Sender; +use packages::statistics::repository::Repository; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; +use crate::packages; use crate::servers::udp::server::banning::BanService; pub struct AppContainer { diff --git a/src/core/statistics/mod.rs b/src/core/statistics/mod.rs deleted file mode 100644 index 4e379ae78..000000000 --- a/src/core/statistics/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod services; diff --git a/src/lib.rs b/src/lib.rs index 212430605..b9ab402ab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -494,7 +494,7 @@ pub mod app; pub mod bootstrap; pub mod console; pub mod container; -pub mod core; +pub mod packages; pub mod servers; pub mod shared; diff --git a/src/core/mod.rs b/src/packages/mod.rs similarity index 100% rename from src/core/mod.rs rename to src/packages/mod.rs diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/src/packages/statistics/event/handler.rs similarity index 96% rename from packages/tracker-core/src/statistics/event/handler.rs rename to src/packages/statistics/event/handler.rs index 93ac05dde..99339041a 100644 --- a/packages/tracker-core/src/statistics/event/handler.rs +++ b/src/packages/statistics/event/handler.rs @@ -1,5 +1,5 @@ -use crate::statistics::event::{Event, UdpResponseKind}; -use crate::statistics::repository::Repository; +use crate::packages::statistics::event::{Event, UdpResponseKind}; +use crate::packages::statistics::repository::Repository; pub async fn handle_event(event: Event, stats_repository: &Repository) { match event { @@ -102,9 +102,9 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { #[cfg(test)] mod tests { - use crate::statistics::event::handler::handle_event; - use crate::statistics::event::Event; - use crate::statistics::repository::Repository; + use crate::packages::statistics::event::handler::handle_event; + use crate::packages::statistics::event::Event; + use crate::packages::statistics::repository::Repository; #[tokio::test] async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { diff --git a/packages/tracker-core/src/statistics/event/listener.rs b/src/packages/statistics/event/listener.rs similarity index 83% rename from packages/tracker-core/src/statistics/event/listener.rs rename to src/packages/statistics/event/listener.rs index f1a2e25de..009784fba 100644 --- a/packages/tracker-core/src/statistics/event/listener.rs +++ b/src/packages/statistics/event/listener.rs @@ -2,7 +2,7 @@ use tokio::sync::mpsc; use super::handler::handle_event; use super::Event; -use crate::statistics::repository::Repository; +use crate::packages::statistics::repository::Repository; pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) { while let Some(event) = receiver.recv().await { diff --git a/packages/tracker-core/src/statistics/event/mod.rs b/src/packages/statistics/event/mod.rs similarity index 100% rename from packages/tracker-core/src/statistics/event/mod.rs rename to src/packages/statistics/event/mod.rs diff --git a/packages/tracker-core/src/statistics/event/sender.rs b/src/packages/statistics/event/sender.rs similarity index 82% rename from packages/tracker-core/src/statistics/event/sender.rs rename to src/packages/statistics/event/sender.rs index 1b663b5d1..b9b989053 100644 --- a/packages/tracker-core/src/statistics/event/sender.rs +++ b/src/packages/statistics/event/sender.rs @@ -13,10 +13,10 @@ pub trait Sender: Sync + Send { fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; } -/// An [`statistics::EventSender`](crate::core::statistics::event::sender::Sender) implementation. +/// An [`statistics::EventSender`](crate::packages::statistics::event::sender::Sender) implementation. /// /// It uses a channel sender to send the statistic events. The channel is created by a -/// [`statistics::Keeper`](crate::core::statistics::keeper::Keeper) +/// [`statistics::Keeper`](crate::packages::statistics::keeper::Keeper) #[allow(clippy::module_name_repetitions)] pub struct ChannelSender { pub(crate) sender: mpsc::Sender, diff --git a/packages/tracker-core/src/statistics/keeper.rs b/src/packages/statistics/keeper.rs similarity index 92% rename from packages/tracker-core/src/statistics/keeper.rs rename to src/packages/statistics/keeper.rs index a3d4542f7..493e61cb2 100644 --- a/packages/tracker-core/src/statistics/keeper.rs +++ b/src/packages/statistics/keeper.rs @@ -51,9 +51,9 @@ impl Keeper { #[cfg(test)] mod tests { - use crate::statistics::event::Event; - use crate::statistics::keeper::Keeper; - use crate::statistics::metrics::Metrics; + use crate::packages::statistics::event::Event; + use crate::packages::statistics::keeper::Keeper; + use crate::packages::statistics::metrics::Metrics; #[tokio::test] async fn should_contain_the_tracker_statistics() { diff --git a/packages/tracker-core/src/statistics/metrics.rs b/src/packages/statistics/metrics.rs similarity index 100% rename from packages/tracker-core/src/statistics/metrics.rs rename to src/packages/statistics/metrics.rs diff --git a/src/packages/statistics/mod.rs b/src/packages/statistics/mod.rs new file mode 100644 index 000000000..939a41061 --- /dev/null +++ b/src/packages/statistics/mod.rs @@ -0,0 +1,6 @@ +pub mod event; +pub mod keeper; +pub mod metrics; +pub mod repository; +pub mod services; +pub mod setup; diff --git a/packages/tracker-core/src/statistics/repository.rs b/src/packages/statistics/repository.rs similarity index 100% rename from packages/tracker-core/src/statistics/repository.rs rename to src/packages/statistics/repository.rs diff --git a/src/core/statistics/services.rs b/src/packages/statistics/services.rs similarity index 90% rename from src/core/statistics/services.rs rename to src/packages/statistics/services.rs index 514f126f9..444ba533c 100644 --- a/src/core/statistics/services.rs +++ b/src/packages/statistics/services.rs @@ -2,14 +2,14 @@ //! //! It includes: //! -//! - A [`factory`](crate::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. -//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::core::statistics::metrics::Metrics). +//! - A [`factory`](crate::packages::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::packages::statistics::metrics::Metrics). //! //! Tracker metrics are collected using a Publisher-Subscribe pattern. //! //! The factory function builds two structs: //! -//! - An statistics event [`Sender`](crate::core::statistics::event::sender::Sender) +//! - An statistics event [`Sender`](crate::packages::statistics::event::sender::Sender) //! - An statistics [`Repository`] //! //! ```text @@ -21,7 +21,7 @@ //! There is an event listener that is receiving all the events and processing them with an event handler. //! Then, the event handler updates the metrics depending on the received event. //! -//! For example, if you send the event [`Event::Udp4Connect`](crate::core::statistics::event::Event::Udp4Connect): +//! For example, if you send the event [`Event::Udp4Connect`](crate::packages::statistics::event::Event::Udp4Connect): //! //! ```text //! let result = event_sender.send_event(Event::Udp4Connect).await; @@ -38,12 +38,13 @@ //! ``` use std::sync::Arc; -use bittorrent_tracker_core::statistics::metrics::Metrics; -use bittorrent_tracker_core::statistics::repository::Repository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use packages::statistics::metrics::Metrics; +use packages::statistics::repository::Repository; use tokio::sync::RwLock; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use crate::packages; use crate::servers::udp::server::banning::BanService; /// All the metrics collected by the tracker. @@ -111,13 +112,14 @@ mod tests { use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::{self, statistics}; + use bittorrent_tracker_core::{self}; use tokio::sync::RwLock; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; - use crate::core::statistics::services::{get_metrics, TrackerMetrics}; + use crate::packages::statistics; + use crate::packages::statistics::services::{get_metrics, TrackerMetrics}; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; diff --git a/packages/tracker-core/src/statistics/setup.rs b/src/packages/statistics/setup.rs similarity index 82% rename from packages/tracker-core/src/statistics/setup.rs rename to src/packages/statistics/setup.rs index 701392176..2a187dcf0 100644 --- a/packages/tracker-core/src/statistics/setup.rs +++ b/src/packages/statistics/setup.rs @@ -1,14 +1,14 @@ //! Setup for the tracker statistics. //! //! The [`factory`] function builds the structs needed for handling the tracker metrics. -use crate::statistics; +use crate::packages::statistics; /// It builds the structs needed for handling the tracker metrics. /// /// It returns: /// -/// - An statistics event [`Sender`](crate::core::statistics::event::sender::Sender) that allows you to send events related to statistics. -/// - An statistics [`Repository`](crate::core::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. +/// - An statistics event [`Sender`](crate::packages::statistics::event::sender::Sender) that allows you to send events related to statistics. +/// - An statistics [`Repository`](crate::packages::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. /// /// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics /// events are sent are received but not dispatched to the handler. diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index b4ead78ea..ffd4f1787 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -5,13 +5,14 @@ use std::sync::Arc; use axum::extract::State; use axum::response::Response; use axum_extra::extract::Query; -use bittorrent_tracker_core::statistics::repository::Repository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use packages::statistics::repository::Repository; use serde::Deserialize; use tokio::sync::RwLock; use super::responses::{metrics_response, stats_response}; -use crate::core::statistics::services::get_metrics; +use crate::packages; +use crate::packages::statistics::services::get_metrics; use crate::servers::udp::server::banning::BanService; #[derive(Deserialize, Debug, Default)] diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index 7b2242d40..5900e293a 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -2,7 +2,7 @@ //! API context. use serde::{Deserialize, Serialize}; -use crate::core::statistics::services::TrackerMetrics; +use crate::packages::statistics::services::TrackerMetrics; /// It contains all the statistics generated by the tracker. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -118,11 +118,12 @@ impl From for Stats { #[cfg(test)] mod tests { - use bittorrent_tracker_core::statistics::metrics::Metrics; + use packages::statistics::metrics::Metrics; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use super::Stats; - use crate::core::statistics::services::TrackerMetrics; + use crate::packages::statistics::services::TrackerMetrics; + use crate::packages::{self}; #[test] fn stats_resource_should_be_converted_from_tracker_metrics() { diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index 6fda43f8c..e3b45a66b 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -3,7 +3,7 @@ use axum::response::{IntoResponse, Json, Response}; use super::resources::Stats; -use crate::core::statistics::services::TrackerMetrics; +use crate::packages::statistics::services::TrackerMetrics; /// `200` response that contains the [`Stats`] resource as json. #[must_use] diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 40462c31d..d3225ee29 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -19,9 +19,9 @@ use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::Key; -use bittorrent_tracker_core::statistics::event::sender::Sender; use bittorrent_tracker_core::whitelist; use hyper::StatusCode; +use packages::statistics::event::sender::Sender; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; @@ -33,7 +33,7 @@ use crate::servers::http::v1::extractors::authentication_key::Extract as Extract use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::handlers::common::auth; use crate::servers::http::v1::services::{self}; -use crate::CurrentClock; +use crate::{packages, CurrentClock}; /// It handles the `announce` request when the HTTP tracker does not require /// authentication (no PATH `key` parameter required). @@ -256,15 +256,17 @@ mod tests { use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::core_tests::sample_info_hash; use bittorrent_tracker_core::databases::setup::initialize_database; - use bittorrent_tracker_core::statistics; - use bittorrent_tracker_core::statistics::event::sender::Sender; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use packages::statistics; + use packages::statistics::event::sender::Sender; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; + use crate::packages; + struct CoreTrackerServices { pub core_config: Arc, pub announce_handler: Arc, diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 1b9196e25..141cf4c45 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -15,11 +15,12 @@ use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSou use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::Key; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::statistics::event::sender::Sender; use hyper::StatusCode; +use packages::statistics::event::sender::Sender; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; +use crate::packages; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::extractors::scrape_request::ExtractRequest; @@ -174,13 +175,15 @@ mod tests { use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; - use bittorrent_tracker_core::statistics; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use packages::statistics; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; + use crate::packages; + struct CoreTrackerServices { pub core_config: Arc, pub scrape_handler: Arc, diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 9e74ab8a5..61bbd93c6 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -12,11 +12,13 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; -use bittorrent_tracker_core::statistics; -use bittorrent_tracker_core::statistics::event::sender::Sender; +use packages::statistics; +use packages::statistics::event::sender::Sender; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; +use crate::packages; + /// The HTTP tracker `announce` service. /// /// The service sends an statistics event that increments: @@ -61,10 +63,10 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::databases::setup::initialize_database; - use bittorrent_tracker_core::statistics; - use bittorrent_tracker_core::statistics::event::sender::Sender; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use packages::statistics; + use packages::statistics::event::sender::Sender; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; @@ -122,11 +124,13 @@ mod tests { } } - use bittorrent_tracker_core::statistics::event::Event; use futures::future::BoxFuture; use mockall::mock; + use packages::statistics::event::Event; use tokio::sync::mpsc::error::SendError; + use crate::packages; + mock! { StatsEventSender {} impl Sender for StatsEventSender { @@ -142,16 +146,17 @@ mod tests { use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::core_tests::sample_info_hash; use bittorrent_tracker_core::databases::setup::initialize_database; - use bittorrent_tracker_core::statistics; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use mockall::predicate::eq; + use packages::statistics; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; + use crate::packages; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{ initialize_core_tracker_services, sample_peer, MockStatsEventSender, diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 59a7d34c7..1ac42ff10 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -12,10 +12,12 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::statistics::event::sender::Sender; -use bittorrent_tracker_core::statistics::{self}; +use packages::statistics::event::sender::Sender; +use packages::statistics::{self}; use torrust_tracker_primitives::core::ScrapeData; +use crate::packages; + /// The HTTP tracker `scrape` service. /// /// The service sends an statistics event that increments: @@ -80,18 +82,20 @@ mod tests { use bittorrent_tracker_core::core_tests::sample_info_hash; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; - use bittorrent_tracker_core::statistics::event::sender::Sender; - use bittorrent_tracker_core::statistics::event::Event; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; use mockall::mock; + use packages::statistics::event::sender::Sender; + use packages::statistics::event::Event; use tokio::sync::mpsc::error::SendError; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; + use crate::packages; + fn initialize_announce_and_scrape_handlers_for_public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); @@ -150,11 +154,12 @@ mod tests { use std::sync::Arc; use bittorrent_tracker_core::announce_handler::PeersWanted; - use bittorrent_tracker_core::statistics; use mockall::predicate::eq; + use packages::statistics; use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use crate::packages; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ initialize_announce_and_scrape_handlers_for_public_tracker, initialize_scrape_handler, sample_info_hash, @@ -163,7 +168,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_scrape_data_for_a_torrent() { - let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let (announce_handler, scrape_handler) = initialize_announce_and_scrape_handlers_for_public_tracker(); @@ -235,10 +240,11 @@ mod tests { use std::sync::Arc; use bittorrent_tracker_core::announce_handler::PeersWanted; - use bittorrent_tracker_core::statistics; use mockall::predicate::eq; + use packages::statistics; use torrust_tracker_primitives::core::ScrapeData; + use crate::packages; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ initialize_announce_and_scrape_handlers_for_public_tracker, sample_info_hash, sample_info_hashes, sample_peer, @@ -247,7 +253,7 @@ mod tests { #[tokio::test] async fn it_should_always_return_the_zeroed_scrape_data_for_a_torrent() { - let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let (announce_handler, _scrape_handler) = initialize_announce_and_scrape_handlers_for_public_tracker(); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 84b2f1db2..9f2562713 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -13,8 +13,8 @@ use aquatic_udp_protocol::{ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::statistics::event::sender::Sender; -use bittorrent_tracker_core::{statistics, whitelist}; +use bittorrent_tracker_core::whitelist; +use packages::statistics::event::sender::Sender; use torrust_tracker_clock::clock::Time as _; use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; @@ -24,10 +24,11 @@ use zerocopy::network_endian::I32; use super::connection_cookie::{check, make}; use super::RawRequest; use crate::container::UdpTrackerContainer; +use crate::packages::statistics; use crate::servers::udp::error::Error; use crate::servers::udp::{peer_builder, UDP_TRACKER_LOG_TARGET}; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; -use crate::CurrentClock; +use crate::{packages, CurrentClock}; #[derive(Debug, Clone, PartialEq)] pub(super) struct CookieTimeValues { @@ -471,15 +472,15 @@ mod tests { use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; - use bittorrent_tracker_core::statistics::event::sender::Sender; - use bittorrent_tracker_core::statistics::event::Event; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::whitelist; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; - use bittorrent_tracker_core::{statistics, whitelist}; use futures::future::BoxFuture; use mockall::mock; + use packages::statistics::event::sender::Sender; + use packages::statistics::event::Event; use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{Configuration, Core}; @@ -487,7 +488,8 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::gen_remote_fingerprint; - use crate::CurrentClock; + use crate::packages::statistics; + use crate::{packages, CurrentClock}; struct CoreTrackerServices { pub core_config: Arc, @@ -649,10 +651,11 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; - use bittorrent_tracker_core::statistics; use mockall::predicate::eq; + use packages::statistics; use super::{sample_ipv4_socket_address, sample_ipv6_remote_addr}; + use crate::packages; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_connect; use crate::servers::udp::handlers::tests::{ @@ -668,7 +671,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { - let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let request = ConnectRequest { @@ -688,7 +691,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { - let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let request = ConnectRequest { @@ -708,7 +711,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { - let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let request = ConnectRequest { @@ -854,10 +857,11 @@ mod tests { }; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::{statistics, whitelist}; + use bittorrent_tracker_core::whitelist; use mockall::predicate::eq; use torrust_tracker_configuration::Core; + use crate::packages::{self, statistics}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ @@ -1013,7 +1017,7 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); @@ -1155,10 +1159,11 @@ mod tests { }; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::{statistics, whitelist}; + use bittorrent_tracker_core::whitelist; use mockall::predicate::eq; use torrust_tracker_configuration::Core; + use crate::packages::{self, statistics}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ @@ -1318,7 +1323,7 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let (stats_event_sender, _stats_repository) = bittorrent_tracker_core::statistics::setup::factory(false); + let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); @@ -1404,13 +1409,14 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::databases::setup::initialize_database; - use bittorrent_tracker_core::statistics; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use mockall::predicate::eq; + use packages::statistics; + use crate::packages; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; @@ -1505,10 +1511,11 @@ mod tests { TransactionId, }; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; - use bittorrent_tracker_core::statistics; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use packages::statistics; use super::{gen_remote_fingerprint, TorrentPeerBuilder}; + use crate::packages; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ @@ -1747,10 +1754,11 @@ mod tests { use std::future; use std::sync::Arc; - use bittorrent_tracker_core::statistics; use mockall::predicate::eq; + use packages::statistics; use super::sample_scrape_request; + use crate::packages; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, @@ -1788,10 +1796,11 @@ mod tests { use std::future; use std::sync::Arc; - use bittorrent_tracker_core::statistics; use mockall::predicate::eq; + use packages::statistics; use super::sample_scrape_request; + use crate::packages; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index bbf2718ff..24872771a 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -3,9 +3,9 @@ use std::sync::Arc; use std::time::Duration; use bittorrent_tracker_client::udp::client::check; -use bittorrent_tracker_core::statistics; use derive_more::Constructor; use futures_util::StreamExt; +use packages::statistics; use tokio::select; use tokio::sync::oneshot; use tokio::time::interval; @@ -14,6 +14,7 @@ use tracing::instrument; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; use crate::container::UdpTrackerContainer; +use crate::packages; use crate::servers::logging::STARTED_ON; use crate::servers::registar::ServiceHealthCheckJob; use crate::servers::signals::{shutdown_signal_with_message, Halted}; diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index db444a04c..8a1ca64e3 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -4,13 +4,14 @@ use std::sync::Arc; use std::time::Duration; use aquatic_udp_protocol::Response; -use bittorrent_tracker_core::statistics; -use bittorrent_tracker_core::statistics::event::UdpResponseKind; +use packages::statistics; +use packages::statistics::event::UdpResponseKind; use tokio::time::Instant; use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; use crate::container::UdpTrackerContainer; +use crate::packages; use crate::servers::udp::handlers::CookieTimeValues; use crate::servers::udp::{handlers, RawRequest}; diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index c91be1544..2828982f7 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -3,14 +3,15 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::authentication::handler::KeysHandler; use bittorrent_tracker_core::databases::Database; -use bittorrent_tracker_core::statistics::repository::Repository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use futures::executor::block_on; +use packages::statistics::repository::Repository; use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::container::HttpTrackerContainer; +use torrust_tracker_lib::packages; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 1483e1e5f..8e2e31f07 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -3,11 +3,12 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::databases::Database; -use bittorrent_tracker_core::statistics::repository::Repository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use packages::statistics::repository::Repository; use torrust_tracker_configuration::{Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::container::UdpTrackerContainer; +use torrust_tracker_lib::packages; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; From f99534a89194cbe91bbe6ddac52dfa69ec5a6f7e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 31 Jan 2025 11:01:33 +0000 Subject: [PATCH 0687/1297] refactor: [#1228] split statistics mod into UDO and HTTP statistics --- src/packages/http_tracker_core/mod.rs | 1 + .../statistics/event/handler.rs | 123 +++++++++++++ .../statistics/event/listener.rs | 11 ++ .../http_tracker_core/statistics/event/mod.rs | 21 +++ .../statistics/event/sender.rs | 29 +++ .../http_tracker_core/statistics/keeper.rs | 77 ++++++++ .../http_tracker_core/statistics/metrics.rs | 30 +++ .../http_tracker_core/statistics/mod.rs | 6 + .../statistics/repository.rs | 66 +++++++ .../http_tracker_core/statistics/services.rs | 104 +++++++++++ .../http_tracker_core/statistics/setup.rs | 54 ++++++ src/packages/mod.rs | 5 + src/packages/udp_tracker_core/mod.rs | 1 + .../statistics/event/handler.rs | 154 ++++++++++++++++ .../statistics/event/listener.rs | 11 ++ .../udp_tracker_core/statistics/event/mod.rs | 47 +++++ .../statistics/event/sender.rs | 29 +++ .../udp_tracker_core/statistics/keeper.rs | 77 ++++++++ .../udp_tracker_core/statistics/metrics.rs | 67 +++++++ .../udp_tracker_core/statistics/mod.rs | 6 + .../udp_tracker_core/statistics/repository.rs | 173 ++++++++++++++++++ .../udp_tracker_core/statistics/services.rs | 146 +++++++++++++++ .../udp_tracker_core/statistics/setup.rs | 54 ++++++ 23 files changed, 1292 insertions(+) create mode 100644 src/packages/http_tracker_core/mod.rs create mode 100644 src/packages/http_tracker_core/statistics/event/handler.rs create mode 100644 src/packages/http_tracker_core/statistics/event/listener.rs create mode 100644 src/packages/http_tracker_core/statistics/event/mod.rs create mode 100644 src/packages/http_tracker_core/statistics/event/sender.rs create mode 100644 src/packages/http_tracker_core/statistics/keeper.rs create mode 100644 src/packages/http_tracker_core/statistics/metrics.rs create mode 100644 src/packages/http_tracker_core/statistics/mod.rs create mode 100644 src/packages/http_tracker_core/statistics/repository.rs create mode 100644 src/packages/http_tracker_core/statistics/services.rs create mode 100644 src/packages/http_tracker_core/statistics/setup.rs create mode 100644 src/packages/udp_tracker_core/mod.rs create mode 100644 src/packages/udp_tracker_core/statistics/event/handler.rs create mode 100644 src/packages/udp_tracker_core/statistics/event/listener.rs create mode 100644 src/packages/udp_tracker_core/statistics/event/mod.rs create mode 100644 src/packages/udp_tracker_core/statistics/event/sender.rs create mode 100644 src/packages/udp_tracker_core/statistics/keeper.rs create mode 100644 src/packages/udp_tracker_core/statistics/metrics.rs create mode 100644 src/packages/udp_tracker_core/statistics/mod.rs create mode 100644 src/packages/udp_tracker_core/statistics/repository.rs create mode 100644 src/packages/udp_tracker_core/statistics/services.rs create mode 100644 src/packages/udp_tracker_core/statistics/setup.rs diff --git a/src/packages/http_tracker_core/mod.rs b/src/packages/http_tracker_core/mod.rs new file mode 100644 index 000000000..3449ec7b4 --- /dev/null +++ b/src/packages/http_tracker_core/mod.rs @@ -0,0 +1 @@ +pub mod statistics; diff --git a/src/packages/http_tracker_core/statistics/event/handler.rs b/src/packages/http_tracker_core/statistics/event/handler.rs new file mode 100644 index 000000000..caaf5d375 --- /dev/null +++ b/src/packages/http_tracker_core/statistics/event/handler.rs @@ -0,0 +1,123 @@ +use crate::packages::http_tracker_core::statistics::event::Event; +use crate::packages::http_tracker_core::statistics::repository::Repository; + +pub async fn handle_event(event: Event, stats_repository: &Repository) { + match event { + // TCP4 + Event::Tcp4Announce => { + stats_repository.increase_tcp4_announces().await; + stats_repository.increase_tcp4_connections().await; + } + Event::Tcp4Scrape => { + stats_repository.increase_tcp4_scrapes().await; + stats_repository.increase_tcp4_connections().await; + } + + // TCP6 + Event::Tcp6Announce => { + stats_repository.increase_tcp6_announces().await; + stats_repository.increase_tcp6_connections().await; + } + Event::Tcp6Scrape => { + stats_repository.increase_tcp6_scrapes().await; + stats_repository.increase_tcp6_connections().await; + } + } + + tracing::debug!("stats: {:?}", stats_repository.get_stats().await); +} + +#[cfg(test)] +mod tests { + use crate::packages::http_tracker_core::statistics::event::handler::handle_event; + use crate::packages::http_tracker_core::statistics::event::Event; + use crate::packages::http_tracker_core::statistics::repository::Repository; + + #[tokio::test] + async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp4Announce, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp4_announces_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_announce_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp4Announce, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp4_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp4_scrapes_counter_when_it_receives_a_tcp4_scrape_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp4Scrape, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp4_scrapes_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_scrape_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp4Scrape, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp4_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp6_announces_counter_when_it_receives_a_tcp6_announce_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp6Announce, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp6_announces_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_announce_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp6Announce, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp6_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp6_scrapes_counter_when_it_receives_a_tcp6_scrape_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp6Scrape, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp6_scrapes_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_scrape_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Tcp6Scrape, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.tcp6_connections_handled, 1); + } +} diff --git a/src/packages/http_tracker_core/statistics/event/listener.rs b/src/packages/http_tracker_core/statistics/event/listener.rs new file mode 100644 index 000000000..ed574a36b --- /dev/null +++ b/src/packages/http_tracker_core/statistics/event/listener.rs @@ -0,0 +1,11 @@ +use tokio::sync::mpsc; + +use super::handler::handle_event; +use super::Event; +use crate::packages::http_tracker_core::statistics::repository::Repository; + +pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) { + while let Some(event) = receiver.recv().await { + handle_event(event, &stats_repository).await; + } +} diff --git a/src/packages/http_tracker_core/statistics/event/mod.rs b/src/packages/http_tracker_core/statistics/event/mod.rs new file mode 100644 index 000000000..e25148666 --- /dev/null +++ b/src/packages/http_tracker_core/statistics/event/mod.rs @@ -0,0 +1,21 @@ +pub mod handler; +pub mod listener; +pub mod sender; + +/// An statistics event. It is used to collect tracker metrics. +/// +/// - `Tcp` prefix means the event was triggered by the HTTP tracker +/// - `Udp` prefix means the event was triggered by the UDP tracker +/// - `4` or `6` prefixes means the IP version used by the peer +/// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection` +/// +/// > NOTE: HTTP trackers do not use `connection` requests. +#[derive(Debug, PartialEq, Eq)] +pub enum Event { + // code-review: consider one single event for request type with data: Event::Announce { scheme: HTTPorUDP, ip_version: V4orV6 } + // Attributes are enums too. + Tcp4Announce, + Tcp4Scrape, + Tcp6Announce, + Tcp6Scrape, +} diff --git a/src/packages/http_tracker_core/statistics/event/sender.rs b/src/packages/http_tracker_core/statistics/event/sender.rs new file mode 100644 index 000000000..279d50962 --- /dev/null +++ b/src/packages/http_tracker_core/statistics/event/sender.rs @@ -0,0 +1,29 @@ +use futures::future::BoxFuture; +use futures::FutureExt; +#[cfg(test)] +use mockall::{automock, predicate::str}; +use tokio::sync::mpsc; +use tokio::sync::mpsc::error::SendError; + +use super::Event; + +/// A trait to allow sending statistics events +#[cfg_attr(test, automock)] +pub trait Sender: Sync + Send { + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; +} + +/// An [`statistics::EventSender`](crate::packages::http_tracker_core::statistics::event::sender::Sender) implementation. +/// +/// It uses a channel sender to send the statistic events. The channel is created by a +/// [`statistics::Keeper`](crate::packages::http_tracker_core::statistics::keeper::Keeper) +#[allow(clippy::module_name_repetitions)] +pub struct ChannelSender { + pub(crate) sender: mpsc::Sender, +} + +impl Sender for ChannelSender { + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { + async move { Some(self.sender.send(event).await) }.boxed() + } +} diff --git a/src/packages/http_tracker_core/statistics/keeper.rs b/src/packages/http_tracker_core/statistics/keeper.rs new file mode 100644 index 000000000..01ae5e6b3 --- /dev/null +++ b/src/packages/http_tracker_core/statistics/keeper.rs @@ -0,0 +1,77 @@ +use tokio::sync::mpsc; + +use super::event::listener::dispatch_events; +use super::event::sender::{ChannelSender, Sender}; +use super::event::Event; +use super::repository::Repository; + +const CHANNEL_BUFFER_SIZE: usize = 65_535; + +/// The service responsible for keeping tracker metrics (listening to statistics events and handle them). +/// +/// It actively listen to new statistics events. When it receives a new event +/// it accordingly increases the counters. +pub struct Keeper { + pub repository: Repository, +} + +impl Default for Keeper { + fn default() -> Self { + Self::new() + } +} + +impl Keeper { + #[must_use] + pub fn new() -> Self { + Self { + repository: Repository::new(), + } + } + + #[must_use] + pub fn new_active_instance() -> (Box, Repository) { + let mut stats_tracker = Self::new(); + + let stats_event_sender = stats_tracker.run_event_listener(); + + (stats_event_sender, stats_tracker.repository) + } + + pub fn run_event_listener(&mut self) -> Box { + let (sender, receiver) = mpsc::channel::(CHANNEL_BUFFER_SIZE); + + let stats_repository = self.repository.clone(); + + tokio::spawn(async move { dispatch_events(receiver, stats_repository).await }); + + Box::new(ChannelSender { sender }) + } +} + +#[cfg(test)] +mod tests { + use crate::packages::http_tracker_core::statistics::event::Event; + use crate::packages::http_tracker_core::statistics::keeper::Keeper; + use crate::packages::http_tracker_core::statistics::metrics::Metrics; + + #[tokio::test] + async fn should_contain_the_tracker_statistics() { + let stats_tracker = Keeper::new(); + + let stats = stats_tracker.repository.get_stats().await; + + assert_eq!(stats.tcp4_announces_handled, Metrics::default().tcp4_announces_handled); + } + + #[tokio::test] + async fn should_create_an_event_sender_to_send_statistical_events() { + let mut stats_tracker = Keeper::new(); + + let event_sender = stats_tracker.run_event_listener(); + + let result = event_sender.send_event(Event::Tcp4Announce).await; + + assert!(result.is_some()); + } +} diff --git a/src/packages/http_tracker_core/statistics/metrics.rs b/src/packages/http_tracker_core/statistics/metrics.rs new file mode 100644 index 000000000..ae4db9704 --- /dev/null +++ b/src/packages/http_tracker_core/statistics/metrics.rs @@ -0,0 +1,30 @@ +/// Metrics collected by the tracker. +/// +/// - Number of connections handled +/// - Number of `announce` requests handled +/// - Number of `scrape` request handled +/// +/// These metrics are collected for each connection type: UDP and HTTP +/// and also for each IP version used by the peers: IPv4 and IPv6. +#[derive(Debug, PartialEq, Default)] +pub struct Metrics { + /// Total number of TCP (HTTP tracker) connections from IPv4 peers. + /// Since the HTTP tracker spec does not require a handshake, this metric + /// increases for every HTTP request. + pub tcp4_connections_handled: u64, + + /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. + pub tcp4_announces_handled: u64, + + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. + pub tcp4_scrapes_handled: u64, + + /// Total number of TCP (HTTP tracker) connections from IPv6 peers. + pub tcp6_connections_handled: u64, + + /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. + pub tcp6_announces_handled: u64, + + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. + pub tcp6_scrapes_handled: u64, +} diff --git a/src/packages/http_tracker_core/statistics/mod.rs b/src/packages/http_tracker_core/statistics/mod.rs new file mode 100644 index 000000000..939a41061 --- /dev/null +++ b/src/packages/http_tracker_core/statistics/mod.rs @@ -0,0 +1,6 @@ +pub mod event; +pub mod keeper; +pub mod metrics; +pub mod repository; +pub mod services; +pub mod setup; diff --git a/src/packages/http_tracker_core/statistics/repository.rs b/src/packages/http_tracker_core/statistics/repository.rs new file mode 100644 index 000000000..41f048e29 --- /dev/null +++ b/src/packages/http_tracker_core/statistics/repository.rs @@ -0,0 +1,66 @@ +use std::sync::Arc; + +use tokio::sync::{RwLock, RwLockReadGuard}; + +use super::metrics::Metrics; + +/// A repository for the tracker metrics. +#[derive(Clone)] +pub struct Repository { + pub stats: Arc>, +} + +impl Default for Repository { + fn default() -> Self { + Self::new() + } +} + +impl Repository { + #[must_use] + pub fn new() -> Self { + Self { + stats: Arc::new(RwLock::new(Metrics::default())), + } + } + + pub async fn get_stats(&self) -> RwLockReadGuard<'_, Metrics> { + self.stats.read().await + } + + pub async fn increase_tcp4_announces(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.tcp4_announces_handled += 1; + drop(stats_lock); + } + + pub async fn increase_tcp4_connections(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.tcp4_connections_handled += 1; + drop(stats_lock); + } + + pub async fn increase_tcp4_scrapes(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.tcp4_scrapes_handled += 1; + drop(stats_lock); + } + + pub async fn increase_tcp6_announces(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.tcp6_announces_handled += 1; + drop(stats_lock); + } + + pub async fn increase_tcp6_connections(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.tcp6_connections_handled += 1; + drop(stats_lock); + } + + pub async fn increase_tcp6_scrapes(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.tcp6_scrapes_handled += 1; + drop(stats_lock); + } +} diff --git a/src/packages/http_tracker_core/statistics/services.rs b/src/packages/http_tracker_core/statistics/services.rs new file mode 100644 index 000000000..11e3a70c4 --- /dev/null +++ b/src/packages/http_tracker_core/statistics/services.rs @@ -0,0 +1,104 @@ +//! Statistics services. +//! +//! It includes: +//! +//! - A [`factory`](crate::packages::http_tracker_core::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::packages::http_tracker_core::statistics::metrics::Metrics). +//! +//! Tracker metrics are collected using a Publisher-Subscribe pattern. +//! +//! The factory function builds two structs: +//! +//! - An statistics event [`Sender`](crate::packages::http_tracker_core::statistics::event::sender::Sender) +//! - An statistics [`Repository`] +//! +//! ```text +//! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); +//! ``` +//! +//! The statistics repository is responsible for storing the metrics in memory. +//! The statistics event sender allows sending events related to metrics. +//! There is an event listener that is receiving all the events and processing them with an event handler. +//! Then, the event handler updates the metrics depending on the received event. +use std::sync::Arc; + +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use packages::http_tracker_core::statistics::metrics::Metrics; +use packages::http_tracker_core::statistics::repository::Repository; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + +use crate::packages; + +/// All the metrics collected by the tracker. +#[derive(Debug, PartialEq)] +pub struct TrackerMetrics { + /// Domain level metrics. + /// + /// General metrics for all torrents (number of seeders, leechers, etcetera) + pub torrents_metrics: TorrentsMetrics, + + /// Application level metrics. Usage statistics/metrics. + /// + /// Metrics about how the tracker is been used (number of number of http scrape requests, etcetera) + pub protocol_metrics: Metrics, +} + +/// It returns all the [`TrackerMetrics`] +pub async fn get_metrics( + in_memory_torrent_repository: Arc, + stats_repository: Arc, +) -> TrackerMetrics { + let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let stats = stats_repository.get_stats().await; + + TrackerMetrics { + torrents_metrics, + protocol_metrics: Metrics { + // TCPv4 + tcp4_connections_handled: stats.tcp4_connections_handled, + tcp4_announces_handled: stats.tcp4_announces_handled, + tcp4_scrapes_handled: stats.tcp4_scrapes_handled, + // TCPv6 + tcp6_connections_handled: stats.tcp6_connections_handled, + tcp6_announces_handled: stats.tcp6_announces_handled, + tcp6_scrapes_handled: stats.tcp6_scrapes_handled, + }, + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::{self}; + use torrust_tracker_configuration::Configuration; + use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use torrust_tracker_test_helpers::configuration; + + use crate::packages::http_tracker_core::statistics; + use crate::packages::http_tracker_core::statistics::services::{get_metrics, TrackerMetrics}; + + pub fn tracker_configuration() -> Configuration { + configuration::ephemeral() + } + + #[tokio::test] + async fn the_statistics_service_should_return_the_tracker_metrics() { + let config = tracker_configuration(); + + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let stats_repository = Arc::new(stats_repository); + + let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), stats_repository.clone()).await; + + assert_eq!( + tracker_metrics, + TrackerMetrics { + torrents_metrics: TorrentsMetrics::default(), + protocol_metrics: statistics::metrics::Metrics::default(), + } + ); + } +} diff --git a/src/packages/http_tracker_core/statistics/setup.rs b/src/packages/http_tracker_core/statistics/setup.rs new file mode 100644 index 000000000..009f157d5 --- /dev/null +++ b/src/packages/http_tracker_core/statistics/setup.rs @@ -0,0 +1,54 @@ +//! Setup for the tracker statistics. +//! +//! The [`factory`] function builds the structs needed for handling the tracker metrics. +use crate::packages::http_tracker_core::statistics; + +/// It builds the structs needed for handling the tracker metrics. +/// +/// It returns: +/// +/// - An statistics event [`Sender`](crate::packages::http_tracker_core::statistics::event::sender::Sender) that allows you to send events related to statistics. +/// - An statistics [`Repository`](crate::packages::http_tracker_core::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. +/// +/// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics +/// events are sent are received but not dispatched to the handler. +#[must_use] +pub fn factory( + tracker_usage_statistics: bool, +) -> ( + Option>, + statistics::repository::Repository, +) { + let mut stats_event_sender = None; + + let mut stats_tracker = statistics::keeper::Keeper::new(); + + if tracker_usage_statistics { + stats_event_sender = Some(stats_tracker.run_event_listener()); + } + + (stats_event_sender, stats_tracker.repository) +} + +#[cfg(test)] +mod test { + use super::factory; + + #[tokio::test] + async fn should_not_send_any_event_when_statistics_are_disabled() { + let tracker_usage_statistics = false; + + let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); + + assert!(stats_event_sender.is_none()); + } + + #[tokio::test] + async fn should_send_events_when_statistics_are_enabled() { + let tracker_usage_statistics = true; + + let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); + + assert!(stats_event_sender.is_some()); + } +} diff --git a/src/packages/mod.rs b/src/packages/mod.rs index 3449ec7b4..9e0bbec90 100644 --- a/src/packages/mod.rs +++ b/src/packages/mod.rs @@ -1 +1,6 @@ +//! This module contains logic pending to be extracted into workspace packages. +//! +//! It will be moved to the directory `packages`. +pub mod http_tracker_core; pub mod statistics; +pub mod udp_tracker_core; diff --git a/src/packages/udp_tracker_core/mod.rs b/src/packages/udp_tracker_core/mod.rs new file mode 100644 index 000000000..3449ec7b4 --- /dev/null +++ b/src/packages/udp_tracker_core/mod.rs @@ -0,0 +1 @@ +pub mod statistics; diff --git a/src/packages/udp_tracker_core/statistics/event/handler.rs b/src/packages/udp_tracker_core/statistics/event/handler.rs new file mode 100644 index 000000000..d696951d3 --- /dev/null +++ b/src/packages/udp_tracker_core/statistics/event/handler.rs @@ -0,0 +1,154 @@ +use crate::packages::udp_tracker_core::statistics::event::{Event, UdpResponseKind}; +use crate::packages::udp_tracker_core::statistics::repository::Repository; + +pub async fn handle_event(event: Event, stats_repository: &Repository) { + match event { + // UDP + Event::UdpRequestAborted => { + stats_repository.increase_udp_requests_aborted().await; + } + Event::UdpRequestBanned => { + stats_repository.increase_udp_requests_banned().await; + } + + // UDP4 + Event::Udp4Request => { + stats_repository.increase_udp4_requests().await; + } + Event::Udp4Connect => { + stats_repository.increase_udp4_connections().await; + } + Event::Udp4Announce => { + stats_repository.increase_udp4_announces().await; + } + Event::Udp4Scrape => { + stats_repository.increase_udp4_scrapes().await; + } + Event::Udp4Response { + kind, + req_processing_time, + } => { + stats_repository.increase_udp4_responses().await; + + match kind { + UdpResponseKind::Connect => { + stats_repository + .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) + .await; + } + UdpResponseKind::Announce => { + stats_repository + .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) + .await; + } + UdpResponseKind::Scrape => { + stats_repository + .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) + .await; + } + UdpResponseKind::Error => {} + } + } + Event::Udp4Error => { + stats_repository.increase_udp4_errors().await; + } + + // UDP6 + Event::Udp6Request => { + stats_repository.increase_udp6_requests().await; + } + Event::Udp6Connect => { + stats_repository.increase_udp6_connections().await; + } + Event::Udp6Announce => { + stats_repository.increase_udp6_announces().await; + } + Event::Udp6Scrape => { + stats_repository.increase_udp6_scrapes().await; + } + Event::Udp6Response { + kind: _, + req_processing_time: _, + } => { + stats_repository.increase_udp6_responses().await; + } + Event::Udp6Error => { + stats_repository.increase_udp6_errors().await; + } + } + + tracing::debug!("stats: {:?}", stats_repository.get_stats().await); +} + +#[cfg(test)] +mod tests { + use crate::packages::udp_tracker_core::statistics::event::handler::handle_event; + use crate::packages::udp_tracker_core::statistics::event::Event; + use crate::packages::udp_tracker_core::statistics::repository::Repository; + + #[tokio::test] + async fn should_increase_the_udp4_connections_counter_when_it_receives_a_udp4_connect_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp4Connect, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_announces_counter_when_it_receives_a_udp4_announce_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp4Announce, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_announces_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_scrapes_counter_when_it_receives_a_udp4_scrape_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp4Scrape, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_scrapes_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_connections_counter_when_it_receives_a_udp6_connect_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp6Connect, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_announces_counter_when_it_receives_a_udp6_announce_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp6Announce, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_announces_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_scrapes_counter_when_it_receives_a_udp6_scrape_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp6Scrape, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_scrapes_handled, 1); + } +} diff --git a/src/packages/udp_tracker_core/statistics/event/listener.rs b/src/packages/udp_tracker_core/statistics/event/listener.rs new file mode 100644 index 000000000..6a84fbaa5 --- /dev/null +++ b/src/packages/udp_tracker_core/statistics/event/listener.rs @@ -0,0 +1,11 @@ +use tokio::sync::mpsc; + +use super::handler::handle_event; +use super::Event; +use crate::packages::udp_tracker_core::statistics::repository::Repository; + +pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) { + while let Some(event) = receiver.recv().await { + handle_event(event, &stats_repository).await; + } +} diff --git a/src/packages/udp_tracker_core/statistics/event/mod.rs b/src/packages/udp_tracker_core/statistics/event/mod.rs new file mode 100644 index 000000000..6a5343933 --- /dev/null +++ b/src/packages/udp_tracker_core/statistics/event/mod.rs @@ -0,0 +1,47 @@ +use std::time::Duration; + +pub mod handler; +pub mod listener; +pub mod sender; + +/// An statistics event. It is used to collect tracker metrics. +/// +/// - `Tcp` prefix means the event was triggered by the HTTP tracker +/// - `Udp` prefix means the event was triggered by the UDP tracker +/// - `4` or `6` prefixes means the IP version used by the peer +/// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection` +/// +/// > NOTE: HTTP trackers do not use `connection` requests. +#[derive(Debug, PartialEq, Eq)] +pub enum Event { + // code-review: consider one single event for request type with data: Event::Announce { scheme: HTTPorUDP, ip_version: V4orV6 } + // Attributes are enums too. + UdpRequestAborted, + UdpRequestBanned, + Udp4Request, + Udp4Connect, + Udp4Announce, + Udp4Scrape, + Udp4Response { + kind: UdpResponseKind, + req_processing_time: Duration, + }, + Udp4Error, + Udp6Request, + Udp6Connect, + Udp6Announce, + Udp6Scrape, + Udp6Response { + kind: UdpResponseKind, + req_processing_time: Duration, + }, + Udp6Error, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum UdpResponseKind { + Connect, + Announce, + Scrape, + Error, +} diff --git a/src/packages/udp_tracker_core/statistics/event/sender.rs b/src/packages/udp_tracker_core/statistics/event/sender.rs new file mode 100644 index 000000000..68e197eca --- /dev/null +++ b/src/packages/udp_tracker_core/statistics/event/sender.rs @@ -0,0 +1,29 @@ +use futures::future::BoxFuture; +use futures::FutureExt; +#[cfg(test)] +use mockall::{automock, predicate::str}; +use tokio::sync::mpsc; +use tokio::sync::mpsc::error::SendError; + +use super::Event; + +/// A trait to allow sending statistics events +#[cfg_attr(test, automock)] +pub trait Sender: Sync + Send { + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; +} + +/// An [`statistics::EventSender`](crate::packages::udp_tracker_core::statistics::event::sender::Sender) implementation. +/// +/// It uses a channel sender to send the statistic events. The channel is created by a +/// [`statistics::Keeper`](crate::packages::udp_tracker_core::statistics::keeper::Keeper) +#[allow(clippy::module_name_repetitions)] +pub struct ChannelSender { + pub(crate) sender: mpsc::Sender, +} + +impl Sender for ChannelSender { + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { + async move { Some(self.sender.send(event).await) }.boxed() + } +} diff --git a/src/packages/udp_tracker_core/statistics/keeper.rs b/src/packages/udp_tracker_core/statistics/keeper.rs new file mode 100644 index 000000000..9bd290145 --- /dev/null +++ b/src/packages/udp_tracker_core/statistics/keeper.rs @@ -0,0 +1,77 @@ +use tokio::sync::mpsc; + +use super::event::listener::dispatch_events; +use super::event::sender::{ChannelSender, Sender}; +use super::event::Event; +use super::repository::Repository; + +const CHANNEL_BUFFER_SIZE: usize = 65_535; + +/// The service responsible for keeping tracker metrics (listening to statistics events and handle them). +/// +/// It actively listen to new statistics events. When it receives a new event +/// it accordingly increases the counters. +pub struct Keeper { + pub repository: Repository, +} + +impl Default for Keeper { + fn default() -> Self { + Self::new() + } +} + +impl Keeper { + #[must_use] + pub fn new() -> Self { + Self { + repository: Repository::new(), + } + } + + #[must_use] + pub fn new_active_instance() -> (Box, Repository) { + let mut stats_tracker = Self::new(); + + let stats_event_sender = stats_tracker.run_event_listener(); + + (stats_event_sender, stats_tracker.repository) + } + + pub fn run_event_listener(&mut self) -> Box { + let (sender, receiver) = mpsc::channel::(CHANNEL_BUFFER_SIZE); + + let stats_repository = self.repository.clone(); + + tokio::spawn(async move { dispatch_events(receiver, stats_repository).await }); + + Box::new(ChannelSender { sender }) + } +} + +#[cfg(test)] +mod tests { + use crate::packages::udp_tracker_core::statistics::event::Event; + use crate::packages::udp_tracker_core::statistics::keeper::Keeper; + use crate::packages::udp_tracker_core::statistics::metrics::Metrics; + + #[tokio::test] + async fn should_contain_the_tracker_statistics() { + let stats_tracker = Keeper::new(); + + let stats = stats_tracker.repository.get_stats().await; + + assert_eq!(stats.udp4_announces_handled, Metrics::default().udp4_announces_handled); + } + + #[tokio::test] + async fn should_create_an_event_sender_to_send_statistical_events() { + let mut stats_tracker = Keeper::new(); + + let event_sender = stats_tracker.run_event_listener(); + + let result = event_sender.send_event(Event::Udp4Connect).await; + + assert!(result.is_some()); + } +} diff --git a/src/packages/udp_tracker_core/statistics/metrics.rs b/src/packages/udp_tracker_core/statistics/metrics.rs new file mode 100644 index 000000000..23357aab6 --- /dev/null +++ b/src/packages/udp_tracker_core/statistics/metrics.rs @@ -0,0 +1,67 @@ +/// Metrics collected by the tracker. +/// +/// - Number of connections handled +/// - Number of `announce` requests handled +/// - Number of `scrape` request handled +/// +/// These metrics are collected for each connection type: UDP and HTTP +/// and also for each IP version used by the peers: IPv4 and IPv6. +#[derive(Debug, PartialEq, Default)] +pub struct Metrics { + // UDP + /// Total number of UDP (UDP tracker) requests aborted. + pub udp_requests_aborted: u64, + + /// Total number of UDP (UDP tracker) requests banned. + pub udp_requests_banned: u64, + + /// Total number of banned IPs. + pub udp_banned_ips_total: u64, + + /// Average rounded time spent processing UDP connect requests. + pub udp_avg_connect_processing_time_ns: u64, + + /// Average rounded time spent processing UDP announce requests. + pub udp_avg_announce_processing_time_ns: u64, + + /// Average rounded time spent processing UDP scrape requests. + pub udp_avg_scrape_processing_time_ns: u64, + + // UDPv4 + /// Total number of UDP (UDP tracker) requests from IPv4 peers. + pub udp4_requests: u64, + + /// Total number of UDP (UDP tracker) connections from IPv4 peers. + pub udp4_connections_handled: u64, + + /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. + pub udp4_announces_handled: u64, + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. + pub udp4_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) responses from IPv4 peers. + pub udp4_responses: u64, + + /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. + pub udp4_errors_handled: u64, + + // UDPv6 + /// Total number of UDP (UDP tracker) requests from IPv6 peers. + pub udp6_requests: u64, + + /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. + pub udp6_connections_handled: u64, + + /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. + pub udp6_announces_handled: u64, + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. + pub udp6_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) responses from IPv6 peers. + pub udp6_responses: u64, + + /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. + pub udp6_errors_handled: u64, +} diff --git a/src/packages/udp_tracker_core/statistics/mod.rs b/src/packages/udp_tracker_core/statistics/mod.rs new file mode 100644 index 000000000..939a41061 --- /dev/null +++ b/src/packages/udp_tracker_core/statistics/mod.rs @@ -0,0 +1,6 @@ +pub mod event; +pub mod keeper; +pub mod metrics; +pub mod repository; +pub mod services; +pub mod setup; diff --git a/src/packages/udp_tracker_core/statistics/repository.rs b/src/packages/udp_tracker_core/statistics/repository.rs new file mode 100644 index 000000000..22e793036 --- /dev/null +++ b/src/packages/udp_tracker_core/statistics/repository.rs @@ -0,0 +1,173 @@ +use std::sync::Arc; +use std::time::Duration; + +use tokio::sync::{RwLock, RwLockReadGuard}; + +use super::metrics::Metrics; + +/// A repository for the tracker metrics. +#[derive(Clone)] +pub struct Repository { + pub stats: Arc>, +} + +impl Default for Repository { + fn default() -> Self { + Self::new() + } +} + +impl Repository { + #[must_use] + pub fn new() -> Self { + Self { + stats: Arc::new(RwLock::new(Metrics::default())), + } + } + + pub async fn get_stats(&self) -> RwLockReadGuard<'_, Metrics> { + self.stats.read().await + } + + pub async fn increase_udp_requests_aborted(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp_requests_aborted += 1; + drop(stats_lock); + } + + pub async fn increase_udp_requests_banned(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp_requests_banned += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_requests(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_requests += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_connections(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_connections_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_announces(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_announces_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_scrapes(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_scrapes_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_responses(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_responses += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_errors(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_errors_handled += 1; + drop(stats_lock); + } + + #[allow(clippy::cast_precision_loss)] + #[allow(clippy::cast_possible_truncation)] + #[allow(clippy::cast_sign_loss)] + pub async fn recalculate_udp_avg_connect_processing_time_ns(&self, req_processing_time: Duration) { + let mut stats_lock = self.stats.write().await; + + let req_processing_time = req_processing_time.as_nanos() as f64; + let udp_connections_handled = (stats_lock.udp4_connections_handled + stats_lock.udp6_connections_handled) as f64; + + let previous_avg = stats_lock.udp_avg_connect_processing_time_ns; + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_connections_handled; + + stats_lock.udp_avg_connect_processing_time_ns = new_avg.ceil() as u64; + + drop(stats_lock); + } + + #[allow(clippy::cast_precision_loss)] + #[allow(clippy::cast_possible_truncation)] + #[allow(clippy::cast_sign_loss)] + pub async fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) { + let mut stats_lock = self.stats.write().await; + + let req_processing_time = req_processing_time.as_nanos() as f64; + + let udp_announces_handled = (stats_lock.udp4_announces_handled + stats_lock.udp6_announces_handled) as f64; + + let previous_avg = stats_lock.udp_avg_announce_processing_time_ns; + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_announces_handled; + + stats_lock.udp_avg_announce_processing_time_ns = new_avg.ceil() as u64; + + drop(stats_lock); + } + + #[allow(clippy::cast_precision_loss)] + #[allow(clippy::cast_possible_truncation)] + #[allow(clippy::cast_sign_loss)] + pub async fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) { + let mut stats_lock = self.stats.write().await; + + let req_processing_time = req_processing_time.as_nanos() as f64; + let udp_scrapes_handled = (stats_lock.udp4_scrapes_handled + stats_lock.udp6_scrapes_handled) as f64; + + let previous_avg = stats_lock.udp_avg_scrape_processing_time_ns; + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_scrapes_handled; + + stats_lock.udp_avg_scrape_processing_time_ns = new_avg.ceil() as u64; + + drop(stats_lock); + } + + pub async fn increase_udp6_requests(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_requests += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_connections(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_connections_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_announces(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_announces_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_scrapes(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_scrapes_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_responses(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_responses += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_errors(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_errors_handled += 1; + drop(stats_lock); + } +} diff --git a/src/packages/udp_tracker_core/statistics/services.rs b/src/packages/udp_tracker_core/statistics/services.rs new file mode 100644 index 000000000..85ca08e54 --- /dev/null +++ b/src/packages/udp_tracker_core/statistics/services.rs @@ -0,0 +1,146 @@ +//! Statistics services. +//! +//! It includes: +//! +//! - A [`factory`](crate::packages::udp_tracker_core::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::packages::udp_tracker_core::statistics::metrics::Metrics). +//! +//! Tracker metrics are collected using a Publisher-Subscribe pattern. +//! +//! The factory function builds two structs: +//! +//! - An statistics event [`Sender`](crate::packages::udp_tracker_core::statistics::event::sender::Sender) +//! - An statistics [`Repository`] +//! +//! ```text +//! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); +//! ``` +//! +//! The statistics repository is responsible for storing the metrics in memory. +//! The statistics event sender allows sending events related to metrics. +//! There is an event listener that is receiving all the events and processing them with an event handler. +//! Then, the event handler updates the metrics depending on the received event. +//! +//! For example, if you send the event [`Event::Udp4Connect`](crate::packages::udp_tracker_core::statistics::event::Event::Udp4Connect): +//! +//! ```text +//! let result = event_sender.send_event(Event::Udp4Connect).await; +//! ``` +//! +//! Eventually the counter for UDP connections from IPv4 peers will be increased. +//! +//! ```rust,no_run +//! pub struct Metrics { +//! // ... +//! pub udp4_connections_handled: u64, // This will be incremented +//! // ... +//! } +//! ``` +use std::sync::Arc; + +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use packages::udp_tracker_core::statistics::metrics::Metrics; +use packages::udp_tracker_core::statistics::repository::Repository; +use tokio::sync::RwLock; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + +use crate::packages; +use crate::servers::udp::server::banning::BanService; + +/// All the metrics collected by the tracker. +#[derive(Debug, PartialEq)] +pub struct TrackerMetrics { + /// Domain level metrics. + /// + /// General metrics for all torrents (number of seeders, leechers, etcetera) + pub torrents_metrics: TorrentsMetrics, + + /// Application level metrics. Usage statistics/metrics. + /// + /// Metrics about how the tracker is been used (number of udp announce requests, etcetera) + pub protocol_metrics: Metrics, +} + +/// It returns all the [`TrackerMetrics`] +pub async fn get_metrics( + in_memory_torrent_repository: Arc, + ban_service: Arc>, + stats_repository: Arc, +) -> TrackerMetrics { + let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let stats = stats_repository.get_stats().await; + let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); + + TrackerMetrics { + torrents_metrics, + protocol_metrics: Metrics { + // UDP + udp_requests_aborted: stats.udp_requests_aborted, + udp_requests_banned: stats.udp_requests_banned, + udp_banned_ips_total: udp_banned_ips_total as u64, + udp_avg_connect_processing_time_ns: stats.udp_avg_connect_processing_time_ns, + udp_avg_announce_processing_time_ns: stats.udp_avg_announce_processing_time_ns, + udp_avg_scrape_processing_time_ns: stats.udp_avg_scrape_processing_time_ns, + // UDPv4 + udp4_requests: stats.udp4_requests, + udp4_connections_handled: stats.udp4_connections_handled, + udp4_announces_handled: stats.udp4_announces_handled, + udp4_scrapes_handled: stats.udp4_scrapes_handled, + udp4_responses: stats.udp4_responses, + udp4_errors_handled: stats.udp4_errors_handled, + // UDPv6 + udp6_requests: stats.udp6_requests, + udp6_connections_handled: stats.udp6_connections_handled, + udp6_announces_handled: stats.udp6_announces_handled, + udp6_scrapes_handled: stats.udp6_scrapes_handled, + udp6_responses: stats.udp6_responses, + udp6_errors_handled: stats.udp6_errors_handled, + }, + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::{self}; + use tokio::sync::RwLock; + use torrust_tracker_configuration::Configuration; + use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use torrust_tracker_test_helpers::configuration; + + use crate::packages::udp_tracker_core::statistics; + use crate::packages::udp_tracker_core::statistics::services::{get_metrics, TrackerMetrics}; + use crate::servers::udp::server::banning::BanService; + use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; + + pub fn tracker_configuration() -> Configuration { + configuration::ephemeral() + } + + #[tokio::test] + async fn the_statistics_service_should_return_the_tracker_metrics() { + let config = tracker_configuration(); + + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let stats_repository = Arc::new(stats_repository); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + + let tracker_metrics = get_metrics( + in_memory_torrent_repository.clone(), + ban_service.clone(), + stats_repository.clone(), + ) + .await; + + assert_eq!( + tracker_metrics, + TrackerMetrics { + torrents_metrics: TorrentsMetrics::default(), + protocol_metrics: statistics::metrics::Metrics::default(), + } + ); + } +} diff --git a/src/packages/udp_tracker_core/statistics/setup.rs b/src/packages/udp_tracker_core/statistics/setup.rs new file mode 100644 index 000000000..c85c715a2 --- /dev/null +++ b/src/packages/udp_tracker_core/statistics/setup.rs @@ -0,0 +1,54 @@ +//! Setup for the tracker statistics. +//! +//! The [`factory`] function builds the structs needed for handling the tracker metrics. +use crate::packages::udp_tracker_core::statistics; + +/// It builds the structs needed for handling the tracker metrics. +/// +/// It returns: +/// +/// - An statistics event [`Sender`](crate::packages::udp_tracker_core::statistics::event::sender::Sender) that allows you to send events related to statistics. +/// - An statistics [`Repository`](crate::packages::udp_tracker_core::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. +/// +/// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics +/// events are sent are received but not dispatched to the handler. +#[must_use] +pub fn factory( + tracker_usage_statistics: bool, +) -> ( + Option>, + statistics::repository::Repository, +) { + let mut stats_event_sender = None; + + let mut stats_tracker = statistics::keeper::Keeper::new(); + + if tracker_usage_statistics { + stats_event_sender = Some(stats_tracker.run_event_listener()); + } + + (stats_event_sender, stats_tracker.repository) +} + +#[cfg(test)] +mod test { + use super::factory; + + #[tokio::test] + async fn should_not_send_any_event_when_statistics_are_disabled() { + let tracker_usage_statistics = false; + + let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); + + assert!(stats_event_sender.is_none()); + } + + #[tokio::test] + async fn should_send_events_when_statistics_are_enabled() { + let tracker_usage_statistics = true; + + let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); + + assert!(stats_event_sender.is_some()); + } +} From 700c912dd8ae50ca17595d11d0051fe4d74979f7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 31 Jan 2025 11:13:26 +0000 Subject: [PATCH 0688/1297] docs: update tracker core docs Statistics are not in the package anymore. --- packages/tracker-core/src/lib.rs | 54 -------------------------------- 1 file changed, 54 deletions(-) diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index ec4371322..68bc48552 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -370,60 +370,6 @@ //! To learn more about tracker authentication, refer to the following modules : //! //! - [`authentication`] module. -//! - [`core`](crate::core) module. -//! - [`http`](crate::servers::http) module. -//! -//! # Statistics -//! -//! The `Tracker` keeps metrics for some events: -//! -//! ```rust,no_run -//! pub struct Metrics { -//! // IP version 4 -//! -//! // HTTP tracker -//! pub tcp4_connections_handled: u64, -//! pub tcp4_announces_handled: u64, -//! pub tcp4_scrapes_handled: u64, -//! -//! // UDP tracker -//! pub udp4_connections_handled: u64, -//! pub udp4_announces_handled: u64, -//! pub udp4_scrapes_handled: u64, -//! -//! // IP version 6 -//! -//! // HTTP tracker -//! pub tcp6_connections_handled: u64, -//! pub tcp6_announces_handled: u64, -//! pub tcp6_scrapes_handled: u64, -//! -//! // UDP tracker -//! pub udp6_connections_handled: u64, -//! pub udp6_announces_handled: u64, -//! pub udp6_scrapes_handled: u64, -//! } -//! ``` -//! -//! The metrics maintained by the `Tracker` are: -//! -//! - `connections_handled`: number of connections handled by the tracker -//! - `announces_handled`: number of `announce` requests handled by the tracker -//! - `scrapes_handled`: number of `scrape` handled requests by the tracker -//! -//! > **NOTICE**: as the HTTP tracker does not have an specific `connection` request like the UDP tracker, `connections_handled` are -//! > increased on every `announce` and `scrape` requests. -//! -//! The tracker exposes an event sender API that allows the tracker users to send events. When a higher application service handles a -//! `connection` , `announce` or `scrape` requests, it notifies the `Tracker` by sending statistics events. -//! -//! For example, the HTTP tracker would send an event like the following when it handles an `announce` request received from a peer using IP version 4. -//! -//! ```text -//! stats_event_sender.send_stats_event(statistics::event::Event::Tcp4Announce).await -//! ``` -//! -//! Refer to [`statistics`] module for more information about statistics. //! //! # Persistence //! From 39cbeda28e0928a7e655152b191ee81647eca520 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 31 Jan 2025 11:30:19 +0000 Subject: [PATCH 0689/1297] refactor: [#1228] add new UDP and HTTP stats services to AppContainer --- src/bootstrap/app.rs | 19 +++++++++++++++++++ src/container.rs | 6 +++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 7313b2808..550eb44f3 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -35,6 +35,7 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::container::AppContainer; +use crate::packages::{http_tracker_core, udp_tracker_core}; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; @@ -90,9 +91,23 @@ pub fn initialize_global_services(configuration: &Configuration) { #[instrument(skip())] pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let core_config = Arc::new(configuration.core.clone()); + let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); let stats_repository = Arc::new(stats_repository); + + // HTTP stats + let (http_stats_event_sender, http_stats_repository) = + http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + let http_stats_repository = Arc::new(http_stats_repository); + + // UDP stats + let (udp_stats_event_sender, udp_stats_repository) = + udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let udp_stats_repository = Arc::new(udp_stats_repository); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let database = initialize_database(configuration); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -134,7 +149,11 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { whitelist_authorization, ban_service, stats_event_sender, + http_stats_event_sender, + udp_stats_event_sender, stats_repository, + http_stats_repository, + udp_stats_repository, whitelist_manager, in_memory_torrent_repository, db_torrent_repository, diff --git a/src/container.rs b/src/container.rs index 965dbfa2a..f1996decb 100644 --- a/src/container.rs +++ b/src/container.rs @@ -15,7 +15,7 @@ use packages::statistics::repository::Repository; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; -use crate::packages; +use crate::packages::{self, http_tracker_core, udp_tracker_core}; use crate::servers::udp::server::banning::BanService; pub struct AppContainer { @@ -28,7 +28,11 @@ pub struct AppContainer { pub whitelist_authorization: Arc, pub ban_service: Arc>, pub stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, + pub udp_stats_event_sender: Arc>>, pub stats_repository: Arc, + pub http_stats_repository: Arc, + pub udp_stats_repository: Arc, pub whitelist_manager: Arc, pub in_memory_torrent_repository: Arc, pub db_torrent_repository: Arc, From 5f08b2ed509d3787c926bf55b5f58c85227af543 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 31 Jan 2025 13:41:43 +0000 Subject: [PATCH 0690/1297] refactor: [#1228] start using the http tracker stats Stats have been splited into HTTP and UDP stats. Parallel change, step 1: 1. [x] Start using HTTP Tracker Core Stats 2. [ ] Start using UDP Tracker Core Stats 3. [ ] Get metrics from HTTP and UDP Tracker Core Stats 4. [ ] Remove deprecate unified HTTP and UDP stats. --- src/container.rs | 2 + src/servers/http/v1/handlers/announce.rs | 68 +++++++++---- src/servers/http/v1/handlers/scrape.rs | 80 +++++++++++---- src/servers/http/v1/routes.rs | 4 + src/servers/http/v1/services/announce.rs | 97 +++++++++++++++--- src/servers/http/v1/services/scrape.rs | 123 ++++++++++++++++++++--- tests/servers/http/environment.rs | 1 + 7 files changed, 306 insertions(+), 69 deletions(-) diff --git a/src/container.rs b/src/container.rs index f1996decb..71c60a517 100644 --- a/src/container.rs +++ b/src/container.rs @@ -71,6 +71,7 @@ pub struct HttpTrackerContainer { pub scrape_handler: Arc, pub whitelist_authorization: Arc, pub stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, pub authentication_service: Arc, } @@ -84,6 +85,7 @@ impl HttpTrackerContainer { scrape_handler: app_container.scrape_handler.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), stats_event_sender: app_container.stats_event_sender.clone(), + http_stats_event_sender: app_container.http_stats_event_sender.clone(), authentication_service: app_container.authentication_service.clone(), } } diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index d3225ee29..594a11ea1 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -28,6 +28,7 @@ use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; use super::common::auth::map_auth_error_to_error_response; +use crate::packages::http_tracker_core; use crate::servers::http::v1::extractors::announce_request::ExtractRequest; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; @@ -46,6 +47,7 @@ pub async fn handle_without_key( Arc, Arc, Arc>>, + Arc>>, )>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, @@ -58,6 +60,7 @@ pub async fn handle_without_key( &state.2, &state.3, &state.4, + &state.5, &announce_request, &client_ip_sources, None, @@ -76,6 +79,7 @@ pub async fn handle_with_key( Arc, Arc, Arc>>, + Arc>>, )>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, @@ -89,6 +93,7 @@ pub async fn handle_with_key( &state.2, &state.3, &state.4, + &state.5, &announce_request, &client_ip_sources, Some(key), @@ -107,6 +112,7 @@ async fn handle( authentication_service: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, maybe_key: Option, @@ -117,6 +123,7 @@ async fn handle( authentication_service, whitelist_authorization, opt_stats_event_sender, + opt_http_stats_event_sender, announce_request, client_ip_sources, maybe_key, @@ -142,6 +149,7 @@ async fn handle_announce( authentication_service: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, maybe_key: Option, @@ -181,6 +189,7 @@ async fn handle_announce( let announce_data = services::announce::invoke( announce_handler.clone(), opt_stats_event_sender.clone(), + opt_http_stats_event_sender.clone(), announce_request.info_hash, &mut peer, &peers_wanted, @@ -265,7 +274,7 @@ mod tests { use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; - use crate::packages; + use crate::packages::{self, http_tracker_core}; struct CoreTrackerServices { pub core_config: Arc, @@ -275,23 +284,27 @@ mod tests { pub authentication_service: Arc, } - fn initialize_private_tracker() -> CoreTrackerServices { + struct CoreHttpTrackerServices { + pub http_stats_event_sender: Arc>>, + } + + fn initialize_private_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_private()) } - fn initialize_listed_tracker() -> CoreTrackerServices { + fn initialize_listed_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_listed()) } - fn initialize_tracker_on_reverse_proxy() -> CoreTrackerServices { + fn initialize_tracker_on_reverse_proxy() -> (CoreTrackerServices, CoreHttpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_with_reverse_proxy()) } - fn initialize_tracker_not_on_reverse_proxy() -> CoreTrackerServices { + fn initialize_tracker_not_on_reverse_proxy() -> (CoreTrackerServices, CoreHttpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_without_reverse_proxy()) } - fn initialize_core_tracker_services(config: &Configuration) -> CoreTrackerServices { + fn initialize_core_tracker_services(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) { let core_config = Arc::new(config.core.clone()); let database = initialize_database(config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -300,21 +313,31 @@ mod tests { let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository)); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, &db_torrent_repository, )); - CoreTrackerServices { - core_config, - announce_handler, - stats_event_sender, - whitelist_authorization, - authentication_service, - } + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + + // HTTP stats + let (http_stats_event_sender, http_stats_repository) = + http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + let _http_stats_repository = Arc::new(http_stats_repository); + + ( + CoreTrackerServices { + core_config, + announce_handler, + stats_event_sender, + whitelist_authorization, + authentication_service, + }, + CoreHttpTrackerServices { http_stats_event_sender }, + ) } fn sample_announce_request() -> Announce { @@ -357,7 +380,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_missing() { - let core_tracker_services = initialize_private_tracker(); + let (core_tracker_services, http_core_tracker_services) = initialize_private_tracker(); let maybe_key = None; @@ -367,6 +390,7 @@ mod tests { &core_tracker_services.authentication_service, &core_tracker_services.whitelist_authorization, &core_tracker_services.stats_event_sender, + &http_core_tracker_services.http_stats_event_sender, &sample_announce_request(), &sample_client_ip_sources(), maybe_key, @@ -382,7 +406,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_invalid() { - let core_tracker_services = initialize_private_tracker(); + let (core_tracker_services, http_core_tracker_services) = initialize_private_tracker(); let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); @@ -394,6 +418,7 @@ mod tests { &core_tracker_services.authentication_service, &core_tracker_services.whitelist_authorization, &core_tracker_services.stats_event_sender, + &http_core_tracker_services.http_stats_event_sender, &sample_announce_request(), &sample_client_ip_sources(), maybe_key, @@ -413,7 +438,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_announced_torrent_is_not_whitelisted() { - let core_tracker_services = initialize_listed_tracker(); + let (core_tracker_services, http_core_tracker_services) = initialize_listed_tracker(); let announce_request = sample_announce_request(); @@ -423,6 +448,7 @@ mod tests { &core_tracker_services.authentication_service, &core_tracker_services.whitelist_authorization, &core_tracker_services.stats_event_sender, + &http_core_tracker_services.http_stats_event_sender, &announce_request, &sample_client_ip_sources(), None, @@ -450,7 +476,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let core_tracker_services = initialize_tracker_on_reverse_proxy(); + let (core_tracker_services, http_core_tracker_services) = initialize_tracker_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -463,6 +489,7 @@ mod tests { &core_tracker_services.authentication_service, &core_tracker_services.whitelist_authorization, &core_tracker_services.stats_event_sender, + &http_core_tracker_services.http_stats_event_sender, &sample_announce_request(), &client_ip_sources, None, @@ -487,7 +514,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let core_tracker_services = initialize_tracker_not_on_reverse_proxy(); + let (core_tracker_services, http_core_tracker_services) = initialize_tracker_not_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -500,6 +527,7 @@ mod tests { &core_tracker_services.authentication_service, &core_tracker_services.whitelist_authorization, &core_tracker_services.stats_event_sender, + &http_core_tracker_services.http_stats_event_sender, &sample_announce_request(), &client_ip_sources, None, diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 141cf4c45..d41a3742f 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -20,7 +20,7 @@ use packages::statistics::event::sender::Sender; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; -use crate::packages; +use crate::packages::{self, http_tracker_core}; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::extractors::scrape_request::ExtractRequest; @@ -36,6 +36,7 @@ pub async fn handle_without_key( Arc, Arc, Arc>>, + Arc>>, )>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, @@ -47,6 +48,7 @@ pub async fn handle_without_key( &state.1, &state.2, &state.3, + &state.4, &scrape_request, &client_ip_sources, None, @@ -66,6 +68,7 @@ pub async fn handle_with_key( Arc, Arc, Arc>>, + Arc>>, )>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, @@ -78,6 +81,7 @@ pub async fn handle_with_key( &state.1, &state.2, &state.3, + &state.4, &scrape_request, &client_ip_sources, Some(key), @@ -91,6 +95,7 @@ async fn handle( scrape_handler: &Arc, authentication_service: &Arc, stats_event_sender: &Arc>>, + http_stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, maybe_key: Option, @@ -100,6 +105,7 @@ async fn handle( scrape_handler, authentication_service, stats_event_sender, + http_stats_event_sender, scrape_request, client_ip_sources, maybe_key, @@ -124,6 +130,7 @@ async fn handle_scrape( scrape_handler: &Arc, authentication_service: &Arc, opt_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, maybe_key: Option, @@ -150,9 +157,22 @@ async fn handle_scrape( }; if return_real_scrape_data { - Ok(services::scrape::invoke(scrape_handler, opt_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await) + Ok(services::scrape::invoke( + scrape_handler, + opt_stats_event_sender, + opt_http_stats_event_sender, + &scrape_request.info_hashes, + &peer_ip, + ) + .await) } else { - Ok(services::scrape::fake(opt_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await) + Ok(services::scrape::fake( + opt_stats_event_sender, + opt_http_stats_event_sender, + &scrape_request.info_hashes, + &peer_ip, + ) + .await) } } @@ -182,7 +202,7 @@ mod tests { use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; - use crate::packages; + use crate::packages::{self, http_tracker_core}; struct CoreTrackerServices { pub core_config: Arc, @@ -191,39 +211,52 @@ mod tests { pub authentication_service: Arc, } - fn initialize_private_tracker() -> CoreTrackerServices { + struct CoreHttpTrackerServices { + pub http_stats_event_sender: Arc>>, + } + + fn initialize_private_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_private()) } - fn initialize_listed_tracker() -> CoreTrackerServices { + fn initialize_listed_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_listed()) } - fn initialize_tracker_on_reverse_proxy() -> CoreTrackerServices { + fn initialize_tracker_on_reverse_proxy() -> (CoreTrackerServices, CoreHttpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_with_reverse_proxy()) } - fn initialize_tracker_not_on_reverse_proxy() -> CoreTrackerServices { + fn initialize_tracker_not_on_reverse_proxy() -> (CoreTrackerServices, CoreHttpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_without_reverse_proxy()) } - fn initialize_core_tracker_services(config: &Configuration) -> CoreTrackerServices { + fn initialize_core_tracker_services(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) { let core_config = Arc::new(config.core.clone()); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository)); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let stats_event_sender = Arc::new(stats_event_sender); - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - CoreTrackerServices { - core_config, - scrape_handler, - stats_event_sender, - authentication_service, - } + // HTTP stats + let (http_stats_event_sender, _http_stats_repository) = + http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + + ( + CoreTrackerServices { + core_config, + scrape_handler, + stats_event_sender, + authentication_service, + }, + CoreHttpTrackerServices { http_stats_event_sender }, + ) } fn sample_scrape_request() -> Scrape { @@ -257,7 +290,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { - let core_tracker_services = initialize_private_tracker(); + let (core_tracker_services, core_http_tracker_services) = initialize_private_tracker(); let scrape_request = sample_scrape_request(); let maybe_key = None; @@ -267,6 +300,7 @@ mod tests { &core_tracker_services.scrape_handler, &core_tracker_services.authentication_service, &core_tracker_services.stats_event_sender, + &core_http_tracker_services.http_stats_event_sender, &scrape_request, &sample_client_ip_sources(), maybe_key, @@ -281,7 +315,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() { - let core_tracker_services = initialize_private_tracker(); + let (core_tracker_services, core_http_tracker_services) = initialize_private_tracker(); let scrape_request = sample_scrape_request(); let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); @@ -292,6 +326,7 @@ mod tests { &core_tracker_services.scrape_handler, &core_tracker_services.authentication_service, &core_tracker_services.stats_event_sender, + &core_http_tracker_services.http_stats_event_sender, &scrape_request, &sample_client_ip_sources(), maybe_key, @@ -314,7 +349,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() { - let core_tracker_services = initialize_listed_tracker(); + let (core_tracker_services, core_http_tracker_services) = initialize_listed_tracker(); let scrape_request = sample_scrape_request(); @@ -323,6 +358,7 @@ mod tests { &core_tracker_services.scrape_handler, &core_tracker_services.authentication_service, &core_tracker_services.stats_event_sender, + &core_http_tracker_services.http_stats_event_sender, &scrape_request, &sample_client_ip_sources(), None, @@ -346,7 +382,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let core_tracker_services = initialize_tracker_on_reverse_proxy(); + let (core_tracker_services, core_http_tracker_services) = initialize_tracker_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -358,6 +394,7 @@ mod tests { &core_tracker_services.scrape_handler, &core_tracker_services.authentication_service, &core_tracker_services.stats_event_sender, + &core_http_tracker_services.http_stats_event_sender, &sample_scrape_request(), &client_ip_sources, None, @@ -382,7 +419,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let core_tracker_services = initialize_tracker_not_on_reverse_proxy(); + let (core_tracker_services, core_http_tracker_services) = initialize_tracker_not_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -394,6 +431,7 @@ mod tests { &core_tracker_services.scrape_handler, &core_tracker_services.authentication_service, &core_tracker_services.stats_event_sender, + &core_http_tracker_services.http_stats_event_sender, &sample_scrape_request(), &client_ip_sources, None, diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index ed9aa05e6..7caccb673 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -44,6 +44,7 @@ pub fn router(http_tracker_container: Arc, server_socket_a http_tracker_container.authentication_service.clone(), http_tracker_container.whitelist_authorization.clone(), http_tracker_container.stats_event_sender.clone(), + http_tracker_container.http_stats_event_sender.clone(), )), ) .route( @@ -54,6 +55,7 @@ pub fn router(http_tracker_container: Arc, server_socket_a http_tracker_container.authentication_service.clone(), http_tracker_container.whitelist_authorization.clone(), http_tracker_container.stats_event_sender.clone(), + http_tracker_container.http_stats_event_sender.clone(), )), ) // Scrape request @@ -64,6 +66,7 @@ pub fn router(http_tracker_container: Arc, server_socket_a http_tracker_container.scrape_handler.clone(), http_tracker_container.authentication_service.clone(), http_tracker_container.stats_event_sender.clone(), + http_tracker_container.http_stats_event_sender.clone(), )), ) .route( @@ -73,6 +76,7 @@ pub fn router(http_tracker_container: Arc, server_socket_a http_tracker_container.scrape_handler.clone(), http_tracker_container.authentication_service.clone(), http_tracker_container.stats_event_sender.clone(), + http_tracker_container.http_stats_event_sender.clone(), )), ) // Add extension to get the client IP from the connection info diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 61bbd93c6..e7170c7e1 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -17,7 +17,7 @@ use packages::statistics::event::sender::Sender; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; -use crate::packages; +use crate::packages::{self, http_tracker_core}; /// The HTTP tracker `announce` service. /// @@ -32,6 +32,7 @@ use crate::packages; pub async fn invoke( announce_handler: Arc, opt_stats_event_sender: Arc>>, + opt_http_stats_event_sender: Arc>>, info_hash: InfoHash, peer: &mut peer::Peer, peers_wanted: &PeersWanted, @@ -52,6 +53,21 @@ pub async fn invoke( } } + if let Some(http_stats_event_sender) = opt_http_stats_event_sender.as_deref() { + match original_peer_ip { + IpAddr::V4(_) => { + http_stats_event_sender + .send_event(http_tracker_core::statistics::event::Event::Tcp4Announce) + .await; + } + IpAddr::V6(_) => { + http_stats_event_sender + .send_event(http_tracker_core::statistics::event::Event::Tcp6Announce) + .await; + } + } + } + announce_data } @@ -77,26 +93,41 @@ mod tests { pub stats_event_sender: Arc>>, } - fn initialize_core_tracker_services() -> CoreTrackerServices { + struct CoreHttpTrackerServices { + pub http_stats_event_sender: Arc>>, + } + + fn initialize_core_tracker_services() -> (CoreTrackerServices, CoreHttpTrackerServices) { let config = configuration::ephemeral_public(); let core_config = Arc::new(config.core.clone()); let database = initialize_database(&config); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); + let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, &db_torrent_repository, )); - CoreTrackerServices { - core_config, - announce_handler, - stats_event_sender, - } + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + + // HTTP stats + let (http_stats_event_sender, http_stats_repository) = + http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + let _http_stats_repository = Arc::new(http_stats_repository); + + ( + CoreTrackerServices { + core_config, + announce_handler, + stats_event_sender, + }, + CoreHttpTrackerServices { http_stats_event_sender }, + ) } fn sample_peer_using_ipv4() -> peer::Peer { @@ -129,7 +160,7 @@ mod tests { use packages::statistics::event::Event; use tokio::sync::mpsc::error::SendError; - use crate::packages; + use crate::packages::{self, http_tracker_core}; mock! { StatsEventSender {} @@ -138,6 +169,13 @@ mod tests { } } + mock! { + HttpStatsEventSender {} + impl http_tracker_core::statistics::event::sender::Sender for HttpStatsEventSender { + fn send_event(&self, event: http_tracker_core::statistics::event::Event) -> BoxFuture<'static,Option > > > ; + } + } + mod with_tracker_in_any_mode { use std::future; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; @@ -156,10 +194,10 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; - use crate::packages; + use crate::packages::{self, http_tracker_core}; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{ - initialize_core_tracker_services, sample_peer, MockStatsEventSender, + initialize_core_tracker_services, sample_peer, MockHttpStatsEventSender, MockStatsEventSender, }; fn initialize_announce_handler() -> Arc { @@ -178,13 +216,14 @@ mod tests { #[tokio::test] async fn it_should_return_the_announce_data() { - let core_tracker_services = initialize_core_tracker_services(); + let (core_tracker_services, core_http_tracker_services) = initialize_core_tracker_services(); let mut peer = sample_peer(); let announce_data = invoke( core_tracker_services.announce_handler.clone(), core_tracker_services.stats_event_sender.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), sample_info_hash(), &mut peer, &PeersWanted::All, @@ -215,6 +254,15 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send_event() + .with(eq(http_tracker_core::statistics::event::Event::Tcp4Announce)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let http_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let announce_handler = initialize_announce_handler(); let mut peer = sample_peer_using_ipv4(); @@ -222,6 +270,7 @@ mod tests { let _announce_data = invoke( announce_handler, stats_event_sender, + http_stats_event_sender, sample_info_hash(), &mut peer, &PeersWanted::All, @@ -260,6 +309,16 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); + // Assert that the event sent is a TCP4 event + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send_event() + .with(eq(http_tracker_core::statistics::event::Event::Tcp4Announce)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let http_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let mut peer = peer_with_the_ipv4_loopback_ip(); let announce_handler = tracker_with_an_ipv6_external_ip(); @@ -267,6 +326,7 @@ mod tests { let _announce_data = invoke( announce_handler, stats_event_sender, + http_stats_event_sender, sample_info_hash(), &mut peer, &PeersWanted::All, @@ -286,6 +346,16 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); + // Assert that the event sent is a TCP4 event + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send_event() + .with(eq(http_tracker_core::statistics::event::Event::Tcp6Announce)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let http_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let announce_handler = initialize_announce_handler(); let mut peer = sample_peer_using_ipv6(); @@ -293,6 +363,7 @@ mod tests { let _announce_data = invoke( announce_handler, stats_event_sender, + http_stats_event_sender, sample_info_hash(), &mut peer, &PeersWanted::All, diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 1ac42ff10..e745609aa 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -16,7 +16,7 @@ use packages::statistics::event::sender::Sender; use packages::statistics::{self}; use torrust_tracker_primitives::core::ScrapeData; -use crate::packages; +use crate::packages::{self, http_tracker_core}; /// The HTTP tracker `scrape` service. /// @@ -31,12 +31,13 @@ use crate::packages; pub async fn invoke( scrape_handler: &Arc, opt_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, info_hashes: &Vec, original_peer_ip: &IpAddr, ) -> ScrapeData { let scrape_data = scrape_handler.scrape(info_hashes).await; - send_scrape_event(original_peer_ip, opt_stats_event_sender).await; + send_scrape_event(original_peer_ip, opt_stats_event_sender, opt_http_stats_event_sender).await; scrape_data } @@ -49,15 +50,20 @@ pub async fn invoke( /// > **NOTICE**: tracker statistics are not updated in this case. pub async fn fake( opt_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, info_hashes: &Vec, original_peer_ip: &IpAddr, ) -> ScrapeData { - send_scrape_event(original_peer_ip, opt_stats_event_sender).await; + send_scrape_event(original_peer_ip, opt_stats_event_sender, opt_http_stats_event_sender).await; ScrapeData::zeroed(info_hashes) } -async fn send_scrape_event(original_peer_ip: &IpAddr, opt_stats_event_sender: &Arc>>) { +async fn send_scrape_event( + original_peer_ip: &IpAddr, + opt_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, +) { if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { match original_peer_ip { IpAddr::V4(_) => { @@ -68,6 +74,21 @@ async fn send_scrape_event(original_peer_ip: &IpAddr, opt_stats_event_sender: &A } } } + + if let Some(http_stats_event_sender) = opt_http_stats_event_sender.as_deref() { + match original_peer_ip { + IpAddr::V4(_) => { + http_stats_event_sender + .send_event(http_tracker_core::statistics::event::Event::Tcp4Scrape) + .await; + } + IpAddr::V6(_) => { + http_stats_event_sender + .send_event(http_tracker_core::statistics::event::Event::Tcp6Scrape) + .await; + } + } + } } #[cfg(test)] @@ -94,7 +115,7 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::packages; + use crate::packages::{self, http_tracker_core}; fn initialize_announce_and_scrape_handlers_for_public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); @@ -147,6 +168,13 @@ mod tests { } } + mock! { + HttpStatsEventSender {} + impl http_tracker_core::statistics::event::sender::Sender for HttpStatsEventSender { + fn send_event(&self, event: http_tracker_core::statistics::event::Event) -> BoxFuture<'static,Option > > > ; + } + } + mod with_real_data { use std::future; @@ -159,11 +187,11 @@ mod tests { use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::packages; + use crate::packages::{self, http_tracker_core}; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ initialize_announce_and_scrape_handlers_for_public_tracker, initialize_scrape_handler, sample_info_hash, - sample_info_hashes, sample_peer, MockStatsEventSender, + sample_info_hashes, sample_peer, MockHttpStatsEventSender, MockStatsEventSender, }; #[tokio::test] @@ -171,6 +199,10 @@ mod tests { let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); + let (http_stats_event_sender, _http_stats_repository) = + packages::http_tracker_core::statistics::setup::factory(false); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + let (announce_handler, scrape_handler) = initialize_announce_and_scrape_handlers_for_public_tracker(); let info_hash = sample_info_hash(); @@ -181,7 +213,14 @@ mod tests { let original_peer_ip = peer.ip(); announce_handler.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); - let scrape_data = invoke(&scrape_handler, &stats_event_sender, &info_hashes, &original_peer_ip).await; + let scrape_data = invoke( + &scrape_handler, + &stats_event_sender, + &http_stats_event_sender, + &info_hashes, + &original_peer_ip, + ) + .await; let mut expected_scrape_data = ScrapeData::empty(); expected_scrape_data.add_file( @@ -207,11 +246,27 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send_event() + .with(eq(http_tracker_core::statistics::event::Event::Tcp4Scrape)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let http_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let scrape_handler = initialize_scrape_handler(); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); - invoke(&scrape_handler, &stats_event_sender, &sample_info_hashes(), &peer_ip).await; + invoke( + &scrape_handler, + &stats_event_sender, + &http_stats_event_sender, + &sample_info_hashes(), + &peer_ip, + ) + .await; } #[tokio::test] @@ -225,11 +280,27 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send_event() + .with(eq(http_tracker_core::statistics::event::Event::Tcp6Scrape)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let http_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let scrape_handler = initialize_scrape_handler(); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); - invoke(&scrape_handler, &stats_event_sender, &sample_info_hashes(), &peer_ip).await; + invoke( + &scrape_handler, + &stats_event_sender, + &http_stats_event_sender, + &sample_info_hashes(), + &peer_ip, + ) + .await; } } @@ -244,11 +315,11 @@ mod tests { use packages::statistics; use torrust_tracker_primitives::core::ScrapeData; - use crate::packages; + use crate::packages::{self, http_tracker_core}; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ initialize_announce_and_scrape_handlers_for_public_tracker, sample_info_hash, sample_info_hashes, sample_peer, - MockStatsEventSender, + MockHttpStatsEventSender, MockStatsEventSender, }; #[tokio::test] @@ -256,6 +327,10 @@ mod tests { let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); + let (http_stats_event_sender, _http_stats_repository) = + packages::http_tracker_core::statistics::setup::factory(false); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + let (announce_handler, _scrape_handler) = initialize_announce_and_scrape_handlers_for_public_tracker(); let info_hash = sample_info_hash(); @@ -266,7 +341,7 @@ mod tests { let original_peer_ip = peer.ip(); announce_handler.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); - let scrape_data = fake(&stats_event_sender, &info_hashes, &original_peer_ip).await; + let scrape_data = fake(&stats_event_sender, &http_stats_event_sender, &info_hashes, &original_peer_ip).await; let expected_scrape_data = ScrapeData::zeroed(&info_hashes); @@ -284,9 +359,18 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send_event() + .with(eq(http_tracker_core::statistics::event::Event::Tcp4Scrape)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let http_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); - fake(&stats_event_sender, &sample_info_hashes(), &peer_ip).await; + fake(&stats_event_sender, &http_stats_event_sender, &sample_info_hashes(), &peer_ip).await; } #[tokio::test] @@ -300,9 +384,18 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); + http_stats_event_sender_mock + .expect_send_event() + .with(eq(http_tracker_core::statistics::event::Event::Tcp6Scrape)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let http_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); - fake(&stats_event_sender, &sample_info_hashes(), &peer_ip).await; + fake(&stats_event_sender, &http_stats_event_sender, &sample_info_hashes(), &peer_ip).await; } } } diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 2828982f7..17013250a 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -62,6 +62,7 @@ impl Environment { scrape_handler: app_container.scrape_handler.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), stats_event_sender: app_container.stats_event_sender.clone(), + http_stats_event_sender: app_container.http_stats_event_sender.clone(), authentication_service: app_container.authentication_service.clone(), }); From f33665dc60fd98aa7c2d0081c83456ca41d6b3d7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 31 Jan 2025 15:55:35 +0000 Subject: [PATCH 0691/1297] refactor: [#1228] start using the udp tracker stats Parallel change, step 2: 1. [x] Start using HTTP Tracker Core Stats 2. [x] Start using UDP Tracker Core Stats 3. [ ] Get metrics from HTTP and UDP Tracker Core Stats 4. [ ] Remove deprecate unified HTTP and UDP stats. --- src/container.rs | 2 + src/servers/udp/handlers.rs | 323 +++++++++++++++++++++++----- src/servers/udp/server/launcher.rs | 29 ++- src/servers/udp/server/processor.rs | 32 ++- tests/servers/udp/environment.rs | 1 + 5 files changed, 332 insertions(+), 55 deletions(-) diff --git a/src/container.rs b/src/container.rs index 71c60a517..7b44bc834 100644 --- a/src/container.rs +++ b/src/container.rs @@ -46,6 +46,7 @@ pub struct UdpTrackerContainer { pub scrape_handler: Arc, pub whitelist_authorization: Arc, pub stats_event_sender: Arc>>, + pub udp_stats_event_sender: Arc>>, pub ban_service: Arc>, } @@ -59,6 +60,7 @@ impl UdpTrackerContainer { scrape_handler: app_container.scrape_handler.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), stats_event_sender: app_container.stats_event_sender.clone(), + udp_stats_event_sender: app_container.udp_stats_event_sender.clone(), ban_service: app_container.ban_service.clone(), } } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 9f2562713..4c943516e 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -24,7 +24,7 @@ use zerocopy::network_endian::I32; use super::connection_cookie::{check, make}; use super::RawRequest; use crate::container::UdpTrackerContainer; -use crate::packages::statistics; +use crate::packages::{statistics, udp_tracker_core}; use crate::servers::udp::error::Error; use crate::servers::udp::{peer_builder, UDP_TRACKER_LOG_TARGET}; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; @@ -99,6 +99,7 @@ pub(crate) async fn handle_packet( local_addr, request_id, &udp_tracker_container.stats_event_sender, + &udp_tracker_container.udp_stats_event_sender, cookie_time_values.valid_range.clone(), &e, Some(transaction_id), @@ -112,6 +113,7 @@ pub(crate) async fn handle_packet( local_addr, request_id, &udp_tracker_container.stats_event_sender, + &udp_tracker_container.udp_stats_event_sender, cookie_time_values.valid_range.clone(), &e, None, @@ -145,6 +147,7 @@ pub async fn handle_request( remote_addr, &connect_request, &udp_tracker_container.stats_event_sender, + &udp_tracker_container.udp_stats_event_sender, cookie_time_values.issue_time, ) .await), @@ -156,6 +159,7 @@ pub async fn handle_request( &udp_tracker_container.announce_handler, &udp_tracker_container.whitelist_authorization, &udp_tracker_container.stats_event_sender, + &udp_tracker_container.udp_stats_event_sender, cookie_time_values.valid_range, ) .await @@ -166,6 +170,7 @@ pub async fn handle_request( &scrape_request, &udp_tracker_container.scrape_handler, &udp_tracker_container.stats_event_sender, + &udp_tracker_container.udp_stats_event_sender, cookie_time_values.valid_range, ) .await @@ -179,11 +184,12 @@ pub async fn handle_request( /// # Errors /// /// This function does not ever return an error. -#[instrument(fields(transaction_id), skip(opt_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id), skip(opt_stats_event_sender, opt_udp_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_connect( remote_addr: SocketAddr, request: &ConnectRequest, opt_stats_event_sender: &Arc>>, + opt_udp_stats_event_sender: &Arc>>, cookie_issue_time: f64, ) -> Response { tracing::Span::current().record("transaction_id", request.transaction_id.0.to_string()); @@ -208,6 +214,21 @@ pub async fn handle_connect( } } + if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Connect) + .await; + } + SocketAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Connect) + .await; + } + } + } + Response::from(response) } @@ -218,7 +239,7 @@ pub async fn handle_connect( /// /// If a error happens in the `handle_announce` function, it will just return the `ServerError`. #[allow(clippy::too_many_arguments)] -#[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_handler, whitelist_authorization, opt_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_handler, whitelist_authorization, opt_stats_event_sender, opt_udp_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_announce( remote_addr: SocketAddr, request: &AnnounceRequest, @@ -226,6 +247,7 @@ pub async fn handle_announce( announce_handler: &Arc, whitelist_authorization: &Arc, opt_stats_event_sender: &Arc>>, + opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { tracing::Span::current() @@ -270,6 +292,21 @@ pub async fn handle_announce( } } + if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + match remote_client_ip { + IpAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Announce) + .await; + } + IpAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Announce) + .await; + } + } + } + #[allow(clippy::cast_possible_truncation)] if remote_addr.is_ipv4() { let announce_response = AnnounceResponse { @@ -330,12 +367,13 @@ pub async fn handle_announce( /// # Errors /// /// This function does not ever return an error. -#[instrument(fields(transaction_id, connection_id), skip(scrape_handler, opt_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id), skip(scrape_handler, opt_stats_event_sender, opt_udp_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_scrape( remote_addr: SocketAddr, request: &ScrapeRequest, scrape_handler: &Arc, opt_stats_event_sender: &Arc>>, + opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { tracing::Span::current() @@ -387,6 +425,21 @@ pub async fn handle_scrape( } } + if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Scrape) + .await; + } + SocketAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Scrape) + .await; + } + } + } + let response = ScrapeResponse { transaction_id: request.transaction_id, torrent_stats, @@ -395,12 +448,14 @@ pub async fn handle_scrape( Ok(Response::from(response)) } -#[instrument(fields(transaction_id), skip(opt_stats_event_sender), ret(level = Level::TRACE))] +#[allow(clippy::too_many_arguments)] +#[instrument(fields(transaction_id), skip(opt_stats_event_sender, opt_udp_stats_event_sender), ret(level = Level::TRACE))] async fn handle_error( remote_addr: SocketAddr, local_addr: SocketAddr, request_id: Uuid, opt_stats_event_sender: &Arc>>, + opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, e: &Error, transaction_id: Option, @@ -447,6 +502,21 @@ async fn handle_error( } } } + + if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Error) + .await; + } + SocketAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Error) + .await; + } + } + } } Response::from(ErrorResponse { @@ -488,7 +558,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::gen_remote_fingerprint; - use crate::packages::statistics; + use crate::packages::{statistics, udp_tracker_core}; use crate::{packages, CurrentClock}; struct CoreTrackerServices { @@ -501,31 +571,33 @@ mod tests { pub whitelist_authorization: Arc, } + struct CoreUdpTrackerServices { + pub udp_stats_event_sender: Arc>>, + } + fn default_testing_tracker_configuration() -> Configuration { configuration::ephemeral() } - fn initialize_core_tracker_services_for_default_tracker_configuration() -> CoreTrackerServices { + fn initialize_core_tracker_services_for_default_tracker_configuration() -> (CoreTrackerServices, CoreUdpTrackerServices) { initialize_core_tracker_services(&default_testing_tracker_configuration()) } - fn initialize_core_tracker_services_for_public_tracker() -> CoreTrackerServices { + fn initialize_core_tracker_services_for_public_tracker() -> (CoreTrackerServices, CoreUdpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_public()) } - fn initialize_core_tracker_services_for_listed_tracker() -> CoreTrackerServices { + fn initialize_core_tracker_services_for_listed_tracker() -> (CoreTrackerServices, CoreUdpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_listed()) } - fn initialize_core_tracker_services(config: &Configuration) -> CoreTrackerServices { + fn initialize_core_tracker_services(config: &Configuration) -> (CoreTrackerServices, CoreUdpTrackerServices) { let core_config = Arc::new(config.core.clone()); let database = initialize_database(config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, @@ -533,15 +605,24 @@ mod tests { )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - CoreTrackerServices { - core_config, - announce_handler, - scrape_handler, - in_memory_torrent_repository, - stats_event_sender, - in_memory_whitelist, - whitelist_authorization, - } + let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let stats_event_sender = Arc::new(stats_event_sender); + + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + ( + CoreTrackerServices { + core_config, + announce_handler, + scrape_handler, + in_memory_torrent_repository, + stats_event_sender, + in_memory_whitelist, + whitelist_authorization, + }, + CoreUdpTrackerServices { udp_stats_event_sender }, + ) } fn sample_ipv4_remote_addr() -> SocketAddr { @@ -645,6 +726,13 @@ mod tests { } } + mock! { + UdpStatsEventSender {} + impl udp_tracker_core::statistics::event::sender::Sender for UdpStatsEventSender { + fn send_event(&self, event: udp_tracker_core::statistics::event::Event) -> BoxFuture<'static,Option > > > ; + } + } + mod connect_request { use std::future; @@ -655,12 +743,12 @@ mod tests { use packages::statistics; use super::{sample_ipv4_socket_address, sample_ipv6_remote_addr}; - use crate::packages; + use crate::packages::{self, udp_tracker_core}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_connect; use crate::servers::udp::handlers::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv6_remote_addr_fingerprint, sample_issue_time, - MockStatsEventSender, + MockStatsEventSender, MockUdpStatsEventSender, }; fn sample_connect_request() -> ConnectRequest { @@ -674,11 +762,21 @@ mod tests { let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), }; - let response = handle_connect(sample_ipv4_remote_addr(), &request, &stats_event_sender, sample_issue_time()).await; + let response = handle_connect( + sample_ipv4_remote_addr(), + &request, + &stats_event_sender, + &udp_stats_event_sender, + sample_issue_time(), + ) + .await; assert_eq!( response, @@ -694,11 +792,21 @@ mod tests { let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), }; - let response = handle_connect(sample_ipv4_remote_addr(), &request, &stats_event_sender, sample_issue_time()).await; + let response = handle_connect( + sample_ipv4_remote_addr(), + &request, + &stats_event_sender, + &udp_stats_event_sender, + sample_issue_time(), + ) + .await; assert_eq!( response, @@ -714,11 +822,21 @@ mod tests { let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), }; - let response = handle_connect(sample_ipv6_remote_addr(), &request, &stats_event_sender, sample_issue_time()).await; + let response = handle_connect( + sample_ipv6_remote_addr(), + &request, + &stats_event_sender, + &udp_stats_event_sender, + sample_issue_time(), + ) + .await; assert_eq!( response, @@ -740,12 +858,22 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp4Connect)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let client_socket_address = sample_ipv4_socket_address(); handle_connect( client_socket_address, &sample_connect_request(), &stats_event_sender, + &udp_stats_event_sender, sample_issue_time(), ) .await; @@ -762,10 +890,20 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp6Connect)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + handle_connect( sample_ipv6_remote_addr(), &sample_connect_request(), &stats_event_sender, + &udp_stats_event_sender, sample_issue_time(), ) .await; @@ -861,19 +999,19 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_configuration::Core; - use crate::packages::{self, statistics}; + use crate::packages::{self, statistics, udp_tracker_core}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ gen_remote_fingerprint, initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, - sample_issue_time, MockStatsEventSender, TorrentPeerBuilder, + sample_issue_time, MockStatsEventSender, MockUdpStatsEventSender, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { - let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); let client_ip = Ipv4Addr::new(126, 0, 0, 1); let client_port = 8080; @@ -897,6 +1035,7 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, &core_tracker_services.stats_event_sender, + &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -916,7 +1055,7 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { - let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); @@ -931,6 +1070,7 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, &core_tracker_services.stats_event_sender, + &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -957,7 +1097,7 @@ mod tests { // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): // "Do note that most trackers will only honor the IP address field under limited circumstances." - let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -984,6 +1124,7 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, &core_tracker_services.stats_event_sender, + &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1020,6 +1161,10 @@ mod tests { let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); + let (udp_stats_event_sender, _udp_stats_repository) = + packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) @@ -1032,6 +1177,7 @@ mod tests { &announce_handler, &whitelist_authorization, &stats_event_sender, + &udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1040,7 +1186,7 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { - let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, _core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); add_a_torrent_peer_using_ipv6(&core_tracker_services.in_memory_torrent_repository); @@ -1071,7 +1217,17 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let core_tracker_services = initialize_core_tracker_services_for_default_tracker_configuration(); + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp4Announce)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + + let (core_tracker_services, _core_udp_tracker_services) = + initialize_core_tracker_services_for_default_tracker_configuration(); handle_announce( sample_ipv4_socket_address(), @@ -1080,6 +1236,7 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, &stats_event_sender, + &udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1102,7 +1259,8 @@ mod tests { #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { - let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); let client_ip = Ipv4Addr::new(127, 0, 0, 1); let client_port = 8080; @@ -1126,6 +1284,7 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, &core_tracker_services.stats_event_sender, + &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1163,19 +1322,19 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_configuration::Core; - use crate::packages::{self, statistics}; + use crate::packages::{self, statistics, udp_tracker_core}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ gen_remote_fingerprint, initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, - sample_issue_time, MockStatsEventSender, TorrentPeerBuilder, + sample_issue_time, MockStatsEventSender, MockUdpStatsEventSender, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { - let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -1200,6 +1359,7 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, &core_tracker_services.stats_event_sender, + &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1219,7 +1379,7 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { - let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -1237,6 +1397,7 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, &core_tracker_services.stats_event_sender, + &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1263,7 +1424,7 @@ mod tests { // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): // "Do note that most trackers will only honor the IP address field under limited circumstances." - let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -1290,6 +1451,7 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, &core_tracker_services.stats_event_sender, + &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1326,6 +1488,10 @@ mod tests { let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); + let (udp_stats_event_sender, _udp_stats_repository) = + packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); let client_port = 8080; @@ -1341,6 +1507,7 @@ mod tests { &announce_handler, &whitelist_authorization, &stats_event_sender, + &udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1349,7 +1516,7 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { - let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, _core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); add_a_torrent_peer_using_ipv4(&core_tracker_services.in_memory_torrent_repository); @@ -1380,7 +1547,17 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); - let core_tracker_services = initialize_core_tracker_services_for_default_tracker_configuration(); + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp6Announce)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + + let (core_tracker_services, _core_udp_tracker_services) = + initialize_core_tracker_services_for_default_tracker_configuration(); let remote_addr = sample_ipv6_remote_addr(); @@ -1395,6 +1572,7 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, &stats_event_sender, + &udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1416,13 +1594,13 @@ mod tests { use mockall::predicate::eq; use packages::statistics; - use crate::packages; + use crate::packages::{self, udp_tracker_core}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ gen_remote_fingerprint, sample_cookie_valid_range, sample_issue_time, MockStatsEventSender, - TrackerConfigurationBuilder, + MockUdpStatsEventSender, TrackerConfigurationBuilder, }; #[tokio::test] @@ -1445,6 +1623,15 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp6Announce)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &in_memory_torrent_repository, @@ -1480,6 +1667,7 @@ mod tests { &announce_handler, &whitelist_authorization, &stats_event_sender, + &udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1533,7 +1721,7 @@ mod tests { #[tokio::test] async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { - let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); let remote_addr = sample_ipv4_remote_addr(); @@ -1551,6 +1739,7 @@ mod tests { &request, &core_tracker_services.scrape_handler, &core_tracker_services.stats_event_sender, + &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1600,6 +1789,9 @@ mod tests { let (stats_event_sender, _stats_repository) = statistics::setup::factory(false); let stats_event_sender = Arc::new(stats_event_sender); + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -1612,6 +1804,7 @@ mod tests { &request, &scrape_handler, &stats_event_sender, + &udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1633,7 +1826,7 @@ mod tests { #[tokio::test] async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { - let core_tracker_services = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, _core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); let torrent_stats = match_scrape_response( add_a_sample_seeder_and_scrape( @@ -1666,7 +1859,7 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { - let core_tracker_services = initialize_core_tracker_services_for_listed_tracker(); + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_listed_tracker(); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -1688,6 +1881,7 @@ mod tests { &request, &core_tracker_services.scrape_handler, &core_tracker_services.stats_event_sender, + &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1706,7 +1900,7 @@ mod tests { #[tokio::test] async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { - let core_tracker_services = initialize_core_tracker_services_for_listed_tracker(); + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_listed_tracker(); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -1726,6 +1920,7 @@ mod tests { &request, &core_tracker_services.scrape_handler, &core_tracker_services.stats_event_sender, + &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1758,11 +1953,11 @@ mod tests { use packages::statistics; use super::sample_scrape_request; - use crate::packages; + use crate::packages::{self, udp_tracker_core}; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, - sample_ipv4_remote_addr, MockStatsEventSender, + sample_ipv4_remote_addr, MockStatsEventSender, MockUdpStatsEventSender, }; #[tokio::test] @@ -1776,15 +1971,26 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp4Scrape)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let remote_addr = sample_ipv4_remote_addr(); - let core_tracker_services = initialize_core_tracker_services_for_default_tracker_configuration(); + let (core_tracker_services, _core_udp_tracker_services) = + initialize_core_tracker_services_for_default_tracker_configuration(); handle_scrape( remote_addr, &sample_scrape_request(&remote_addr), &core_tracker_services.scrape_handler, &stats_event_sender, + &udp_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -1800,11 +2006,11 @@ mod tests { use packages::statistics; use super::sample_scrape_request; - use crate::packages; + use crate::packages::{self, udp_tracker_core}; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, - sample_ipv6_remote_addr, MockStatsEventSender, + sample_ipv6_remote_addr, MockStatsEventSender, MockUdpStatsEventSender, }; #[tokio::test] @@ -1818,15 +2024,26 @@ mod tests { let stats_event_sender: Arc>> = Arc::new(Some(Box::new(stats_event_sender_mock))); + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp6Scrape)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let remote_addr = sample_ipv6_remote_addr(); - let core_tracker_services = initialize_core_tracker_services_for_default_tracker_configuration(); + let (core_tracker_services, _core_udp_tracker_services) = + initialize_core_tracker_services_for_default_tracker_configuration(); handle_scrape( remote_addr, &sample_scrape_request(&remote_addr), &core_tracker_services.scrape_handler, &stats_event_sender, + &udp_stats_event_sender, sample_cookie_valid_range(), ) .await diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 24872771a..863f82e18 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -14,7 +14,7 @@ use tracing::instrument; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; use crate::container::UdpTrackerContainer; -use crate::packages; +use crate::packages::{self, udp_tracker_core}; use crate::servers::logging::STARTED_ON; use crate::servers::registar::ServiceHealthCheckJob; use crate::servers::signals::{shutdown_signal_with_message, Halted}; @@ -174,6 +174,21 @@ impl Launcher { } } + if let Some(udp_stats_event_sender) = udp_tracker_container.udp_stats_event_sender.as_deref() { + match req.from.ip() { + IpAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Request) + .await; + } + IpAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Request) + .await; + } + } + } + if udp_tracker_container.ban_service.read().await.is_banned(&req.from.ip()) { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop continue: (banned ip)"); @@ -183,6 +198,12 @@ impl Launcher { .await; } + if let Some(udp_stats_event_sender) = udp_tracker_container.udp_stats_event_sender.as_deref() { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::UdpRequestBanned) + .await; + } + continue; } @@ -215,6 +236,12 @@ impl Launcher { .send_event(statistics::event::Event::UdpRequestAborted) .await; } + + if let Some(udp_stats_event_sender) = udp_tracker_container.udp_stats_event_sender.as_deref() { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::UdpRequestAborted) + .await; + } } } else { tokio::task::yield_now().await; diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 8a1ca64e3..bbf64dfb9 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -11,7 +11,7 @@ use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; use crate::container::UdpTrackerContainer; -use crate::packages; +use crate::packages::{self, udp_tracker_core}; use crate::servers::udp::handlers::CookieTimeValues; use crate::servers::udp::{handlers, RawRequest}; @@ -68,6 +68,15 @@ impl Processor { Response::Error(_e) => UdpResponseKind::Error, }; + let udp_response_kind = match &response { + Response::Connect(_) => udp_tracker_core::statistics::event::UdpResponseKind::Connect, + Response::AnnounceIpv4(_) | Response::AnnounceIpv6(_) => { + udp_tracker_core::statistics::event::UdpResponseKind::Announce + } + Response::Scrape(_) => udp_tracker_core::statistics::event::UdpResponseKind::Scrape, + Response::Error(_e) => udp_tracker_core::statistics::event::UdpResponseKind::Error, + }; + let mut writer = Cursor::new(Vec::with_capacity(200)); match response.write_bytes(&mut writer) { @@ -103,6 +112,27 @@ impl Processor { } } } + + if let Some(udp_stats_event_sender) = self.udp_tracker_container.udp_stats_event_sender.as_deref() { + match target.ip() { + IpAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Response { + kind: udp_response_kind, + req_processing_time, + }) + .await; + } + IpAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Response { + kind: udp_response_kind, + req_processing_time, + }) + .await; + } + } + } } Err(error) => tracing::warn!(%bytes_count, %error, ?payload, "failed to send"), }; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 8e2e31f07..c8ecac1fb 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -62,6 +62,7 @@ impl Environment { scrape_handler: app_container.scrape_handler.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), stats_event_sender: app_container.stats_event_sender.clone(), + udp_stats_event_sender: app_container.udp_stats_event_sender.clone(), ban_service: app_container.ban_service.clone(), }); From 55769383f5b05bf10048de0f346ea04a2f5748aa Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 31 Jan 2025 16:20:04 +0000 Subject: [PATCH 0692/1297] refactor: [#1228] get metrics from HTTP and UDP Tracker Core Stats Stats have been splited into HTTP and UDP stats. Parallel change, step 3: 1. [x] Start using HTTP Tracker Core Stats 2. [x] Start using UDP Tracker Core Stats 3. [x] Get metrics from HTTP and UDP Tracker Core Stats 4. [ ] Remove deprecated unified HTTP and UDP stats. --- src/container.rs | 8 +- src/packages/mod.rs | 1 + src/packages/tracker_api_core/mod.rs | 1 + .../tracker_api_core/statistics/metrics.rs | 87 ++++++++++++ .../tracker_api_core/statistics/mod.rs | 2 + .../tracker_api_core/statistics/services.rs | 127 ++++++++++++++++++ src/servers/apis/v1/context/stats/handlers.rs | 14 +- .../apis/v1/context/stats/resources.rs | 6 +- .../apis/v1/context/stats/responses.rs | 2 +- src/servers/apis/v1/context/stats/routes.rs | 3 +- tests/servers/api/environment.rs | 4 +- 11 files changed, 239 insertions(+), 16 deletions(-) create mode 100644 src/packages/tracker_api_core/mod.rs create mode 100644 src/packages/tracker_api_core/statistics/metrics.rs create mode 100644 src/packages/tracker_api_core/statistics/mod.rs create mode 100644 src/packages/tracker_api_core/statistics/services.rs diff --git a/src/container.rs b/src/container.rs index 7b44bc834..ccd85c7b1 100644 --- a/src/container.rs +++ b/src/container.rs @@ -100,8 +100,8 @@ pub struct HttpApiContainer { pub keys_handler: Arc, pub whitelist_manager: Arc, pub ban_service: Arc>, - pub stats_event_sender: Arc>>, - pub stats_repository: Arc, + pub http_stats_repository: Arc, + pub udp_stats_repository: Arc, } impl HttpApiContainer { @@ -114,8 +114,8 @@ impl HttpApiContainer { keys_handler: app_container.keys_handler.clone(), whitelist_manager: app_container.whitelist_manager.clone(), ban_service: app_container.ban_service.clone(), - stats_event_sender: app_container.stats_event_sender.clone(), - stats_repository: app_container.stats_repository.clone(), + http_stats_repository: app_container.http_stats_repository.clone(), + udp_stats_repository: app_container.udp_stats_repository.clone(), } } } diff --git a/src/packages/mod.rs b/src/packages/mod.rs index 9e0bbec90..dcf4cf428 100644 --- a/src/packages/mod.rs +++ b/src/packages/mod.rs @@ -3,4 +3,5 @@ //! It will be moved to the directory `packages`. pub mod http_tracker_core; pub mod statistics; +pub mod tracker_api_core; pub mod udp_tracker_core; diff --git a/src/packages/tracker_api_core/mod.rs b/src/packages/tracker_api_core/mod.rs new file mode 100644 index 000000000..3449ec7b4 --- /dev/null +++ b/src/packages/tracker_api_core/mod.rs @@ -0,0 +1 @@ +pub mod statistics; diff --git a/src/packages/tracker_api_core/statistics/metrics.rs b/src/packages/tracker_api_core/statistics/metrics.rs new file mode 100644 index 000000000..40262efd6 --- /dev/null +++ b/src/packages/tracker_api_core/statistics/metrics.rs @@ -0,0 +1,87 @@ +/// Metrics collected by the tracker. +/// +/// - Number of connections handled +/// - Number of `announce` requests handled +/// - Number of `scrape` request handled +/// +/// These metrics are collected for each connection type: UDP and HTTP +/// and also for each IP version used by the peers: IPv4 and IPv6. +#[derive(Debug, PartialEq, Default)] +pub struct Metrics { + /// Total number of TCP (HTTP tracker) connections from IPv4 peers. + /// Since the HTTP tracker spec does not require a handshake, this metric + /// increases for every HTTP request. + pub tcp4_connections_handled: u64, + + /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. + pub tcp4_announces_handled: u64, + + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. + pub tcp4_scrapes_handled: u64, + + /// Total number of TCP (HTTP tracker) connections from IPv6 peers. + pub tcp6_connections_handled: u64, + + /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. + pub tcp6_announces_handled: u64, + + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. + pub tcp6_scrapes_handled: u64, + + // UDP + /// Total number of UDP (UDP tracker) requests aborted. + pub udp_requests_aborted: u64, + + /// Total number of UDP (UDP tracker) requests banned. + pub udp_requests_banned: u64, + + /// Total number of banned IPs. + pub udp_banned_ips_total: u64, + + /// Average rounded time spent processing UDP connect requests. + pub udp_avg_connect_processing_time_ns: u64, + + /// Average rounded time spent processing UDP announce requests. + pub udp_avg_announce_processing_time_ns: u64, + + /// Average rounded time spent processing UDP scrape requests. + pub udp_avg_scrape_processing_time_ns: u64, + + // UDPv4 + /// Total number of UDP (UDP tracker) requests from IPv4 peers. + pub udp4_requests: u64, + + /// Total number of UDP (UDP tracker) connections from IPv4 peers. + pub udp4_connections_handled: u64, + + /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. + pub udp4_announces_handled: u64, + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. + pub udp4_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) responses from IPv4 peers. + pub udp4_responses: u64, + + /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. + pub udp4_errors_handled: u64, + + // UDPv6 + /// Total number of UDP (UDP tracker) requests from IPv6 peers. + pub udp6_requests: u64, + + /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. + pub udp6_connections_handled: u64, + + /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. + pub udp6_announces_handled: u64, + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. + pub udp6_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) responses from IPv6 peers. + pub udp6_responses: u64, + + /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. + pub udp6_errors_handled: u64, +} diff --git a/src/packages/tracker_api_core/statistics/mod.rs b/src/packages/tracker_api_core/statistics/mod.rs new file mode 100644 index 000000000..a3c8a4b0e --- /dev/null +++ b/src/packages/tracker_api_core/statistics/mod.rs @@ -0,0 +1,2 @@ +pub mod metrics; +pub mod services; diff --git a/src/packages/tracker_api_core/statistics/services.rs b/src/packages/tracker_api_core/statistics/services.rs new file mode 100644 index 000000000..bb8e71ab8 --- /dev/null +++ b/src/packages/tracker_api_core/statistics/services.rs @@ -0,0 +1,127 @@ +use std::sync::Arc; + +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use packages::tracker_api_core::statistics::metrics::Metrics; +use tokio::sync::RwLock; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + +use crate::packages::{self, http_tracker_core, udp_tracker_core}; +use crate::servers::udp::server::banning::BanService; + +/// All the metrics collected by the tracker. +#[derive(Debug, PartialEq)] +pub struct TrackerMetrics { + /// Domain level metrics. + /// + /// General metrics for all torrents (number of seeders, leechers, etcetera) + pub torrents_metrics: TorrentsMetrics, + + /// Application level metrics. Usage statistics/metrics. + /// + /// Metrics about how the tracker is been used (number of udp announce requests, number of http scrape requests, etcetera) + pub protocol_metrics: Metrics, +} + +/// It returns all the [`TrackerMetrics`] +pub async fn get_metrics( + in_memory_torrent_repository: Arc, + ban_service: Arc>, + http_stats_repository: Arc, + udp_stats_repository: Arc, +) -> TrackerMetrics { + let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); + let http_stats = http_stats_repository.get_stats().await; + let udp_stats = udp_stats_repository.get_stats().await; + + TrackerMetrics { + torrents_metrics, + protocol_metrics: Metrics { + // TCPv4 + tcp4_connections_handled: http_stats.tcp4_connections_handled, + tcp4_announces_handled: http_stats.tcp4_announces_handled, + tcp4_scrapes_handled: http_stats.tcp4_scrapes_handled, + // TCPv6 + tcp6_connections_handled: http_stats.tcp6_connections_handled, + tcp6_announces_handled: http_stats.tcp6_announces_handled, + tcp6_scrapes_handled: http_stats.tcp6_scrapes_handled, + // UDP + udp_requests_aborted: udp_stats.udp_requests_aborted, + udp_requests_banned: udp_stats.udp_requests_banned, + udp_banned_ips_total: udp_banned_ips_total as u64, + udp_avg_connect_processing_time_ns: udp_stats.udp_avg_connect_processing_time_ns, + udp_avg_announce_processing_time_ns: udp_stats.udp_avg_announce_processing_time_ns, + udp_avg_scrape_processing_time_ns: udp_stats.udp_avg_scrape_processing_time_ns, + // UDPv4 + udp4_requests: udp_stats.udp4_requests, + udp4_connections_handled: udp_stats.udp4_connections_handled, + udp4_announces_handled: udp_stats.udp4_announces_handled, + udp4_scrapes_handled: udp_stats.udp4_scrapes_handled, + udp4_responses: udp_stats.udp4_responses, + udp4_errors_handled: udp_stats.udp4_errors_handled, + // UDPv6 + udp6_requests: udp_stats.udp6_requests, + udp6_connections_handled: udp_stats.udp6_connections_handled, + udp6_announces_handled: udp_stats.udp6_announces_handled, + udp6_scrapes_handled: udp_stats.udp6_scrapes_handled, + udp6_responses: udp_stats.udp6_responses, + udp6_errors_handled: udp_stats.udp6_errors_handled, + }, + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::{self}; + use tokio::sync::RwLock; + use torrust_tracker_configuration::Configuration; + use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use torrust_tracker_test_helpers::configuration; + + use crate::packages::tracker_api_core::statistics::metrics::Metrics; + use crate::packages::tracker_api_core::statistics::services::{get_metrics, TrackerMetrics}; + use crate::packages::{http_tracker_core, udp_tracker_core}; + use crate::servers::udp::server::banning::BanService; + use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; + + pub fn tracker_configuration() -> Configuration { + configuration::ephemeral() + } + + #[tokio::test] + async fn the_statistics_service_should_return_the_tracker_metrics() { + let config = tracker_configuration(); + + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + + // HTTP stats + let (_http_stats_event_sender, http_stats_repository) = + http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_repository = Arc::new(http_stats_repository); + + // UDP stats + let (_udp_stats_event_sender, udp_stats_repository) = + udp_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let udp_stats_repository = Arc::new(udp_stats_repository); + + let tracker_metrics = get_metrics( + in_memory_torrent_repository.clone(), + ban_service.clone(), + http_stats_repository.clone(), + udp_stats_repository.clone(), + ) + .await; + + assert_eq!( + tracker_metrics, + TrackerMetrics { + torrents_metrics: TorrentsMetrics::default(), + protocol_metrics: Metrics::default(), + } + ); + } +} diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index ffd4f1787..820f39909 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -6,13 +6,12 @@ use axum::extract::State; use axum::response::Response; use axum_extra::extract::Query; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use packages::statistics::repository::Repository; use serde::Deserialize; use tokio::sync::RwLock; use super::responses::{metrics_response, stats_response}; -use crate::packages; -use crate::packages::statistics::services::get_metrics; +use crate::packages::tracker_api_core::statistics::services::get_metrics; +use crate::packages::{http_tracker_core, udp_tracker_core}; use crate::servers::udp::server::banning::BanService; #[derive(Deserialize, Debug, Default)] @@ -41,10 +40,15 @@ pub struct QueryParams { /// for more information about this endpoint. #[allow(clippy::type_complexity)] pub async fn get_stats_handler( - State(state): State<(Arc, Arc>, Arc)>, + State(state): State<( + Arc, + Arc>, + Arc, + Arc, + )>, params: Query, ) -> Response { - let metrics = get_metrics(state.0.clone(), state.1.clone(), state.2.clone()).await; + let metrics = get_metrics(state.0.clone(), state.1.clone(), state.2.clone(), state.3.clone()).await; match params.0.format { Some(format) => match format { diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index 5900e293a..8477ca5cb 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -2,7 +2,7 @@ //! API context. use serde::{Deserialize, Serialize}; -use crate::packages::statistics::services::TrackerMetrics; +use crate::packages::tracker_api_core::statistics::services::TrackerMetrics; /// It contains all the statistics generated by the tracker. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -118,11 +118,11 @@ impl From for Stats { #[cfg(test)] mod tests { - use packages::statistics::metrics::Metrics; + use packages::tracker_api_core::statistics::metrics::Metrics; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use super::Stats; - use crate::packages::statistics::services::TrackerMetrics; + use crate::packages::tracker_api_core::statistics::services::TrackerMetrics; use crate::packages::{self}; #[test] diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index e3b45a66b..5a71c4235 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -3,7 +3,7 @@ use axum::response::{IntoResponse, Json, Response}; use super::resources::Stats; -use crate::packages::statistics::services::TrackerMetrics; +use crate::packages::tracker_api_core::statistics::services::TrackerMetrics; /// `200` response that contains the [`Stats`] resource as json. #[must_use] diff --git a/src/servers/apis/v1/context/stats/routes.rs b/src/servers/apis/v1/context/stats/routes.rs index 4c80f110d..e660005ec 100644 --- a/src/servers/apis/v1/context/stats/routes.rs +++ b/src/servers/apis/v1/context/stats/routes.rs @@ -18,7 +18,8 @@ pub fn add(prefix: &str, router: Router, http_api_container: &Arc { keys_handler: app_container.keys_handler.clone(), whitelist_manager: app_container.whitelist_manager.clone(), ban_service: app_container.ban_service.clone(), - stats_event_sender: app_container.stats_event_sender.clone(), - stats_repository: app_container.stats_repository.clone(), + http_stats_repository: app_container.http_stats_repository.clone(), + udp_stats_repository: app_container.udp_stats_repository.clone(), }); Self { From fd8b57a6792977e823f38f2431ef7ad83794196d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 31 Jan 2025 17:02:52 +0000 Subject: [PATCH 0693/1297] refactor: [#1228] remove deprecated unified HTTP and UDP stats Stats have been split into HTTP and UDP stats. Parallel change, step 4: 1. [x] Start using HTTP Tracker Core Stats 2. [x] Start using UDP Tracker Core Stats 3. [x] Get metrics from HTTP and UDP Tracker Core Stats 4. [x] Remove deprecated unified HTTP and UDP stats. --- src/bootstrap/app.rs | 9 +- src/container.rs | 10 +- .../http_tracker_core/statistics/services.rs | 10 +- src/packages/mod.rs | 1 - src/packages/statistics/event/handler.rs | 262 ------------------ src/packages/statistics/event/listener.rs | 11 - src/packages/statistics/event/mod.rs | 51 ---- src/packages/statistics/event/sender.rs | 29 -- src/packages/statistics/keeper.rs | 77 ----- src/packages/statistics/metrics.rs | 87 ------ src/packages/statistics/mod.rs | 6 - src/packages/statistics/repository.rs | 209 -------------- src/packages/statistics/services.rs | 154 ---------- src/packages/statistics/setup.rs | 54 ---- .../udp_tracker_core/statistics/services.rs | 9 +- src/servers/http/v1/handlers/announce.rs | 25 +- src/servers/http/v1/handlers/scrape.rs | 32 +-- src/servers/http/v1/routes.rs | 4 - src/servers/http/v1/services/announce.rs | 73 +---- src/servers/http/v1/services/scrape.rs | 116 +------- src/servers/udp/handlers.rs | 215 ++------------ src/servers/udp/server/launcher.rs | 26 +- src/servers/udp/server/processor.rs | 32 +-- tests/servers/http/environment.rs | 12 +- tests/servers/http/v1/contract.rs | 16 +- tests/servers/udp/contract.rs | 4 +- tests/servers/udp/environment.rs | 12 +- 27 files changed, 78 insertions(+), 1468 deletions(-) delete mode 100644 src/packages/statistics/event/handler.rs delete mode 100644 src/packages/statistics/event/listener.rs delete mode 100644 src/packages/statistics/event/mod.rs delete mode 100644 src/packages/statistics/event/sender.rs delete mode 100644 src/packages/statistics/keeper.rs delete mode 100644 src/packages/statistics/metrics.rs delete mode 100644 src/packages/statistics/mod.rs delete mode 100644 src/packages/statistics/repository.rs delete mode 100644 src/packages/statistics/services.rs delete mode 100644 src/packages/statistics/setup.rs diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 550eb44f3..93bbfe290 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -26,7 +26,6 @@ use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentT use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager; -use packages::statistics; use tokio::sync::RwLock; use torrust_tracker_clock::static_time; use torrust_tracker_configuration::validator::Validator; @@ -34,13 +33,13 @@ use torrust_tracker_configuration::Configuration; use tracing::instrument; use super::config::initialize_configuration; +use crate::bootstrap; use crate::container::AppContainer; use crate::packages::{http_tracker_core, udp_tracker_core}; use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; use crate::shared::crypto::keys::{self, Keeper as _}; -use crate::{bootstrap, packages}; /// It loads the configuration from the environment and builds app container. /// @@ -92,10 +91,6 @@ pub fn initialize_global_services(configuration: &Configuration) { pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let core_config = Arc::new(configuration.core.clone()); - let (stats_event_sender, stats_repository) = statistics::setup::factory(configuration.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - let stats_repository = Arc::new(stats_repository); - // HTTP stats let (http_stats_event_sender, http_stats_repository) = http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); @@ -148,10 +143,8 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { authentication_service, whitelist_authorization, ban_service, - stats_event_sender, http_stats_event_sender, udp_stats_event_sender, - stats_repository, http_stats_repository, udp_stats_repository, whitelist_manager, diff --git a/src/container.rs b/src/container.rs index ccd85c7b1..51c55e533 100644 --- a/src/container.rs +++ b/src/container.rs @@ -10,12 +10,10 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; -use packages::statistics::event::sender::Sender; -use packages::statistics::repository::Repository; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; -use crate::packages::{self, http_tracker_core, udp_tracker_core}; +use crate::packages::{http_tracker_core, udp_tracker_core}; use crate::servers::udp::server::banning::BanService; pub struct AppContainer { @@ -27,10 +25,8 @@ pub struct AppContainer { pub authentication_service: Arc, pub whitelist_authorization: Arc, pub ban_service: Arc>, - pub stats_event_sender: Arc>>, pub http_stats_event_sender: Arc>>, pub udp_stats_event_sender: Arc>>, - pub stats_repository: Arc, pub http_stats_repository: Arc, pub udp_stats_repository: Arc, pub whitelist_manager: Arc, @@ -45,7 +41,6 @@ pub struct UdpTrackerContainer { pub announce_handler: Arc, pub scrape_handler: Arc, pub whitelist_authorization: Arc, - pub stats_event_sender: Arc>>, pub udp_stats_event_sender: Arc>>, pub ban_service: Arc>, } @@ -59,7 +54,6 @@ impl UdpTrackerContainer { announce_handler: app_container.announce_handler.clone(), scrape_handler: app_container.scrape_handler.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), - stats_event_sender: app_container.stats_event_sender.clone(), udp_stats_event_sender: app_container.udp_stats_event_sender.clone(), ban_service: app_container.ban_service.clone(), } @@ -72,7 +66,6 @@ pub struct HttpTrackerContainer { pub announce_handler: Arc, pub scrape_handler: Arc, pub whitelist_authorization: Arc, - pub stats_event_sender: Arc>>, pub http_stats_event_sender: Arc>>, pub authentication_service: Arc, } @@ -86,7 +79,6 @@ impl HttpTrackerContainer { announce_handler: app_container.announce_handler.clone(), scrape_handler: app_container.scrape_handler.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), - stats_event_sender: app_container.stats_event_sender.clone(), http_stats_event_sender: app_container.http_stats_event_sender.clone(), authentication_service: app_container.authentication_service.clone(), } diff --git a/src/packages/http_tracker_core/statistics/services.rs b/src/packages/http_tracker_core/statistics/services.rs index 11e3a70c4..51065bf63 100644 --- a/src/packages/http_tracker_core/statistics/services.rs +++ b/src/packages/http_tracker_core/statistics/services.rs @@ -76,8 +76,8 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; - use crate::packages::http_tracker_core::statistics; use crate::packages::http_tracker_core::statistics::services::{get_metrics, TrackerMetrics}; + use crate::packages::http_tracker_core::{self, statistics}; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -88,10 +88,12 @@ mod tests { let config = tracker_configuration(); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let stats_repository = Arc::new(stats_repository); - let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), stats_repository.clone()).await; + let (_http_stats_event_sender, http_stats_repository) = + http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_repository = Arc::new(http_stats_repository); + + let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), http_stats_repository.clone()).await; assert_eq!( tracker_metrics, diff --git a/src/packages/mod.rs b/src/packages/mod.rs index dcf4cf428..453c3d533 100644 --- a/src/packages/mod.rs +++ b/src/packages/mod.rs @@ -2,6 +2,5 @@ //! //! It will be moved to the directory `packages`. pub mod http_tracker_core; -pub mod statistics; pub mod tracker_api_core; pub mod udp_tracker_core; diff --git a/src/packages/statistics/event/handler.rs b/src/packages/statistics/event/handler.rs deleted file mode 100644 index 99339041a..000000000 --- a/src/packages/statistics/event/handler.rs +++ /dev/null @@ -1,262 +0,0 @@ -use crate::packages::statistics::event::{Event, UdpResponseKind}; -use crate::packages::statistics::repository::Repository; - -pub async fn handle_event(event: Event, stats_repository: &Repository) { - match event { - // TCP4 - Event::Tcp4Announce => { - stats_repository.increase_tcp4_announces().await; - stats_repository.increase_tcp4_connections().await; - } - Event::Tcp4Scrape => { - stats_repository.increase_tcp4_scrapes().await; - stats_repository.increase_tcp4_connections().await; - } - - // TCP6 - Event::Tcp6Announce => { - stats_repository.increase_tcp6_announces().await; - stats_repository.increase_tcp6_connections().await; - } - Event::Tcp6Scrape => { - stats_repository.increase_tcp6_scrapes().await; - stats_repository.increase_tcp6_connections().await; - } - - // UDP - Event::UdpRequestAborted => { - stats_repository.increase_udp_requests_aborted().await; - } - Event::UdpRequestBanned => { - stats_repository.increase_udp_requests_banned().await; - } - - // UDP4 - Event::Udp4Request => { - stats_repository.increase_udp4_requests().await; - } - Event::Udp4Connect => { - stats_repository.increase_udp4_connections().await; - } - Event::Udp4Announce => { - stats_repository.increase_udp4_announces().await; - } - Event::Udp4Scrape => { - stats_repository.increase_udp4_scrapes().await; - } - Event::Udp4Response { - kind, - req_processing_time, - } => { - stats_repository.increase_udp4_responses().await; - - match kind { - UdpResponseKind::Connect => { - stats_repository - .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) - .await; - } - UdpResponseKind::Announce => { - stats_repository - .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) - .await; - } - UdpResponseKind::Scrape => { - stats_repository - .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) - .await; - } - UdpResponseKind::Error => {} - } - } - Event::Udp4Error => { - stats_repository.increase_udp4_errors().await; - } - - // UDP6 - Event::Udp6Request => { - stats_repository.increase_udp6_requests().await; - } - Event::Udp6Connect => { - stats_repository.increase_udp6_connections().await; - } - Event::Udp6Announce => { - stats_repository.increase_udp6_announces().await; - } - Event::Udp6Scrape => { - stats_repository.increase_udp6_scrapes().await; - } - Event::Udp6Response { - kind: _, - req_processing_time: _, - } => { - stats_repository.increase_udp6_responses().await; - } - Event::Udp6Error => { - stats_repository.increase_udp6_errors().await; - } - } - - tracing::debug!("stats: {:?}", stats_repository.get_stats().await); -} - -#[cfg(test)] -mod tests { - use crate::packages::statistics::event::handler::handle_event; - use crate::packages::statistics::event::Event; - use crate::packages::statistics::repository::Repository; - - #[tokio::test] - async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Tcp4Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_announce_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Tcp4Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp4_scrapes_counter_when_it_receives_a_tcp4_scrape_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Tcp4Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_scrapes_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_scrape_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Tcp4Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp6_announces_counter_when_it_receives_a_tcp6_announce_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Tcp6Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_announce_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Tcp6Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp6_scrapes_counter_when_it_receives_a_tcp6_scrape_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Tcp6Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_scrapes_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_scrape_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Tcp6Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_connections_counter_when_it_receives_a_udp4_connect_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Udp4Connect, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_announces_counter_when_it_receives_a_udp4_announce_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Udp4Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_scrapes_counter_when_it_receives_a_udp4_scrape_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Udp4Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_scrapes_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_connections_counter_when_it_receives_a_udp6_connect_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Udp6Connect, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_announces_counter_when_it_receives_a_udp6_announce_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Udp6Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_scrapes_counter_when_it_receives_a_udp6_scrape_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Udp6Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_scrapes_handled, 1); - } -} diff --git a/src/packages/statistics/event/listener.rs b/src/packages/statistics/event/listener.rs deleted file mode 100644 index 009784fba..000000000 --- a/src/packages/statistics/event/listener.rs +++ /dev/null @@ -1,11 +0,0 @@ -use tokio::sync::mpsc; - -use super::handler::handle_event; -use super::Event; -use crate::packages::statistics::repository::Repository; - -pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) { - while let Some(event) = receiver.recv().await { - handle_event(event, &stats_repository).await; - } -} diff --git a/src/packages/statistics/event/mod.rs b/src/packages/statistics/event/mod.rs deleted file mode 100644 index 905aa0372..000000000 --- a/src/packages/statistics/event/mod.rs +++ /dev/null @@ -1,51 +0,0 @@ -use std::time::Duration; - -pub mod handler; -pub mod listener; -pub mod sender; - -/// An statistics event. It is used to collect tracker metrics. -/// -/// - `Tcp` prefix means the event was triggered by the HTTP tracker -/// - `Udp` prefix means the event was triggered by the UDP tracker -/// - `4` or `6` prefixes means the IP version used by the peer -/// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection` -/// -/// > NOTE: HTTP trackers do not use `connection` requests. -#[derive(Debug, PartialEq, Eq)] -pub enum Event { - // code-review: consider one single event for request type with data: Event::Announce { scheme: HTTPorUDP, ip_version: V4orV6 } - // Attributes are enums too. - Tcp4Announce, - Tcp4Scrape, - Tcp6Announce, - Tcp6Scrape, - UdpRequestAborted, - UdpRequestBanned, - Udp4Request, - Udp4Connect, - Udp4Announce, - Udp4Scrape, - Udp4Response { - kind: UdpResponseKind, - req_processing_time: Duration, - }, - Udp4Error, - Udp6Request, - Udp6Connect, - Udp6Announce, - Udp6Scrape, - Udp6Response { - kind: UdpResponseKind, - req_processing_time: Duration, - }, - Udp6Error, -} - -#[derive(Debug, PartialEq, Eq)] -pub enum UdpResponseKind { - Connect, - Announce, - Scrape, - Error, -} diff --git a/src/packages/statistics/event/sender.rs b/src/packages/statistics/event/sender.rs deleted file mode 100644 index b9b989053..000000000 --- a/src/packages/statistics/event/sender.rs +++ /dev/null @@ -1,29 +0,0 @@ -use futures::future::BoxFuture; -use futures::FutureExt; -#[cfg(test)] -use mockall::{automock, predicate::str}; -use tokio::sync::mpsc; -use tokio::sync::mpsc::error::SendError; - -use super::Event; - -/// A trait to allow sending statistics events -#[cfg_attr(test, automock)] -pub trait Sender: Sync + Send { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; -} - -/// An [`statistics::EventSender`](crate::packages::statistics::event::sender::Sender) implementation. -/// -/// It uses a channel sender to send the statistic events. The channel is created by a -/// [`statistics::Keeper`](crate::packages::statistics::keeper::Keeper) -#[allow(clippy::module_name_repetitions)] -pub struct ChannelSender { - pub(crate) sender: mpsc::Sender, -} - -impl Sender for ChannelSender { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { - async move { Some(self.sender.send(event).await) }.boxed() - } -} diff --git a/src/packages/statistics/keeper.rs b/src/packages/statistics/keeper.rs deleted file mode 100644 index 493e61cb2..000000000 --- a/src/packages/statistics/keeper.rs +++ /dev/null @@ -1,77 +0,0 @@ -use tokio::sync::mpsc; - -use super::event::listener::dispatch_events; -use super::event::sender::{ChannelSender, Sender}; -use super::event::Event; -use super::repository::Repository; - -const CHANNEL_BUFFER_SIZE: usize = 65_535; - -/// The service responsible for keeping tracker metrics (listening to statistics events and handle them). -/// -/// It actively listen to new statistics events. When it receives a new event -/// it accordingly increases the counters. -pub struct Keeper { - pub repository: Repository, -} - -impl Default for Keeper { - fn default() -> Self { - Self::new() - } -} - -impl Keeper { - #[must_use] - pub fn new() -> Self { - Self { - repository: Repository::new(), - } - } - - #[must_use] - pub fn new_active_instance() -> (Box, Repository) { - let mut stats_tracker = Self::new(); - - let stats_event_sender = stats_tracker.run_event_listener(); - - (stats_event_sender, stats_tracker.repository) - } - - pub fn run_event_listener(&mut self) -> Box { - let (sender, receiver) = mpsc::channel::(CHANNEL_BUFFER_SIZE); - - let stats_repository = self.repository.clone(); - - tokio::spawn(async move { dispatch_events(receiver, stats_repository).await }); - - Box::new(ChannelSender { sender }) - } -} - -#[cfg(test)] -mod tests { - use crate::packages::statistics::event::Event; - use crate::packages::statistics::keeper::Keeper; - use crate::packages::statistics::metrics::Metrics; - - #[tokio::test] - async fn should_contain_the_tracker_statistics() { - let stats_tracker = Keeper::new(); - - let stats = stats_tracker.repository.get_stats().await; - - assert_eq!(stats.tcp4_announces_handled, Metrics::default().tcp4_announces_handled); - } - - #[tokio::test] - async fn should_create_an_event_sender_to_send_statistical_events() { - let mut stats_tracker = Keeper::new(); - - let event_sender = stats_tracker.run_event_listener(); - - let result = event_sender.send_event(Event::Udp4Connect).await; - - assert!(result.is_some()); - } -} diff --git a/src/packages/statistics/metrics.rs b/src/packages/statistics/metrics.rs deleted file mode 100644 index 40262efd6..000000000 --- a/src/packages/statistics/metrics.rs +++ /dev/null @@ -1,87 +0,0 @@ -/// Metrics collected by the tracker. -/// -/// - Number of connections handled -/// - Number of `announce` requests handled -/// - Number of `scrape` request handled -/// -/// These metrics are collected for each connection type: UDP and HTTP -/// and also for each IP version used by the peers: IPv4 and IPv6. -#[derive(Debug, PartialEq, Default)] -pub struct Metrics { - /// Total number of TCP (HTTP tracker) connections from IPv4 peers. - /// Since the HTTP tracker spec does not require a handshake, this metric - /// increases for every HTTP request. - pub tcp4_connections_handled: u64, - - /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. - pub tcp4_announces_handled: u64, - - /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. - pub tcp4_scrapes_handled: u64, - - /// Total number of TCP (HTTP tracker) connections from IPv6 peers. - pub tcp6_connections_handled: u64, - - /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. - pub tcp6_announces_handled: u64, - - /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. - pub tcp6_scrapes_handled: u64, - - // UDP - /// Total number of UDP (UDP tracker) requests aborted. - pub udp_requests_aborted: u64, - - /// Total number of UDP (UDP tracker) requests banned. - pub udp_requests_banned: u64, - - /// Total number of banned IPs. - pub udp_banned_ips_total: u64, - - /// Average rounded time spent processing UDP connect requests. - pub udp_avg_connect_processing_time_ns: u64, - - /// Average rounded time spent processing UDP announce requests. - pub udp_avg_announce_processing_time_ns: u64, - - /// Average rounded time spent processing UDP scrape requests. - pub udp_avg_scrape_processing_time_ns: u64, - - // UDPv4 - /// Total number of UDP (UDP tracker) requests from IPv4 peers. - pub udp4_requests: u64, - - /// Total number of UDP (UDP tracker) connections from IPv4 peers. - pub udp4_connections_handled: u64, - - /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. - pub udp4_announces_handled: u64, - - /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. - pub udp4_scrapes_handled: u64, - - /// Total number of UDP (UDP tracker) responses from IPv4 peers. - pub udp4_responses: u64, - - /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. - pub udp4_errors_handled: u64, - - // UDPv6 - /// Total number of UDP (UDP tracker) requests from IPv6 peers. - pub udp6_requests: u64, - - /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. - pub udp6_connections_handled: u64, - - /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. - pub udp6_announces_handled: u64, - - /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. - pub udp6_scrapes_handled: u64, - - /// Total number of UDP (UDP tracker) responses from IPv6 peers. - pub udp6_responses: u64, - - /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. - pub udp6_errors_handled: u64, -} diff --git a/src/packages/statistics/mod.rs b/src/packages/statistics/mod.rs deleted file mode 100644 index 939a41061..000000000 --- a/src/packages/statistics/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -pub mod event; -pub mod keeper; -pub mod metrics; -pub mod repository; -pub mod services; -pub mod setup; diff --git a/src/packages/statistics/repository.rs b/src/packages/statistics/repository.rs deleted file mode 100644 index ec5100073..000000000 --- a/src/packages/statistics/repository.rs +++ /dev/null @@ -1,209 +0,0 @@ -use std::sync::Arc; -use std::time::Duration; - -use tokio::sync::{RwLock, RwLockReadGuard}; - -use super::metrics::Metrics; - -/// A repository for the tracker metrics. -#[derive(Clone)] -pub struct Repository { - pub stats: Arc>, -} - -impl Default for Repository { - fn default() -> Self { - Self::new() - } -} - -impl Repository { - #[must_use] - pub fn new() -> Self { - Self { - stats: Arc::new(RwLock::new(Metrics::default())), - } - } - - pub async fn get_stats(&self) -> RwLockReadGuard<'_, Metrics> { - self.stats.read().await - } - - pub async fn increase_tcp4_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp4_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp4_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp4_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp4_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp4_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp6_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp6_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp6_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp6_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp6_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp6_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp_requests_aborted(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp_requests_aborted += 1; - drop(stats_lock); - } - - pub async fn increase_udp_requests_banned(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp_requests_banned += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_requests(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_requests += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_responses(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_responses += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_errors(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_errors_handled += 1; - drop(stats_lock); - } - - #[allow(clippy::cast_precision_loss)] - #[allow(clippy::cast_possible_truncation)] - #[allow(clippy::cast_sign_loss)] - pub async fn recalculate_udp_avg_connect_processing_time_ns(&self, req_processing_time: Duration) { - let mut stats_lock = self.stats.write().await; - - let req_processing_time = req_processing_time.as_nanos() as f64; - let udp_connections_handled = (stats_lock.udp4_connections_handled + stats_lock.udp6_connections_handled) as f64; - - let previous_avg = stats_lock.udp_avg_connect_processing_time_ns; - - // Moving average: https://en.wikipedia.org/wiki/Moving_average - let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_connections_handled; - - stats_lock.udp_avg_connect_processing_time_ns = new_avg.ceil() as u64; - - drop(stats_lock); - } - - #[allow(clippy::cast_precision_loss)] - #[allow(clippy::cast_possible_truncation)] - #[allow(clippy::cast_sign_loss)] - pub async fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) { - let mut stats_lock = self.stats.write().await; - - let req_processing_time = req_processing_time.as_nanos() as f64; - - let udp_announces_handled = (stats_lock.udp4_announces_handled + stats_lock.udp6_announces_handled) as f64; - - let previous_avg = stats_lock.udp_avg_announce_processing_time_ns; - - // Moving average: https://en.wikipedia.org/wiki/Moving_average - let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_announces_handled; - - stats_lock.udp_avg_announce_processing_time_ns = new_avg.ceil() as u64; - - drop(stats_lock); - } - - #[allow(clippy::cast_precision_loss)] - #[allow(clippy::cast_possible_truncation)] - #[allow(clippy::cast_sign_loss)] - pub async fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) { - let mut stats_lock = self.stats.write().await; - - let req_processing_time = req_processing_time.as_nanos() as f64; - let udp_scrapes_handled = (stats_lock.udp4_scrapes_handled + stats_lock.udp6_scrapes_handled) as f64; - - let previous_avg = stats_lock.udp_avg_scrape_processing_time_ns; - - // Moving average: https://en.wikipedia.org/wiki/Moving_average - let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_scrapes_handled; - - stats_lock.udp_avg_scrape_processing_time_ns = new_avg.ceil() as u64; - - drop(stats_lock); - } - - pub async fn increase_udp6_requests(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_requests += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_responses(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_responses += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_errors(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_errors_handled += 1; - drop(stats_lock); - } -} diff --git a/src/packages/statistics/services.rs b/src/packages/statistics/services.rs deleted file mode 100644 index 444ba533c..000000000 --- a/src/packages/statistics/services.rs +++ /dev/null @@ -1,154 +0,0 @@ -//! Statistics services. -//! -//! It includes: -//! -//! - A [`factory`](crate::packages::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. -//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::packages::statistics::metrics::Metrics). -//! -//! Tracker metrics are collected using a Publisher-Subscribe pattern. -//! -//! The factory function builds two structs: -//! -//! - An statistics event [`Sender`](crate::packages::statistics::event::sender::Sender) -//! - An statistics [`Repository`] -//! -//! ```text -//! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); -//! ``` -//! -//! The statistics repository is responsible for storing the metrics in memory. -//! The statistics event sender allows sending events related to metrics. -//! There is an event listener that is receiving all the events and processing them with an event handler. -//! Then, the event handler updates the metrics depending on the received event. -//! -//! For example, if you send the event [`Event::Udp4Connect`](crate::packages::statistics::event::Event::Udp4Connect): -//! -//! ```text -//! let result = event_sender.send_event(Event::Udp4Connect).await; -//! ``` -//! -//! Eventually the counter for UDP connections from IPv4 peers will be increased. -//! -//! ```rust,no_run -//! pub struct Metrics { -//! // ... -//! pub udp4_connections_handled: u64, // This will be incremented -//! // ... -//! } -//! ``` -use std::sync::Arc; - -use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use packages::statistics::metrics::Metrics; -use packages::statistics::repository::Repository; -use tokio::sync::RwLock; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; - -use crate::packages; -use crate::servers::udp::server::banning::BanService; - -/// All the metrics collected by the tracker. -#[derive(Debug, PartialEq)] -pub struct TrackerMetrics { - /// Domain level metrics. - /// - /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: TorrentsMetrics, - - /// Application level metrics. Usage statistics/metrics. - /// - /// Metrics about how the tracker is been used (number of udp announce requests, number of http scrape requests, etcetera) - pub protocol_metrics: Metrics, -} - -/// It returns all the [`TrackerMetrics`] -pub async fn get_metrics( - in_memory_torrent_repository: Arc, - ban_service: Arc>, - stats_repository: Arc, -) -> TrackerMetrics { - let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); - let stats = stats_repository.get_stats().await; - let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); - - TrackerMetrics { - torrents_metrics, - protocol_metrics: Metrics { - // TCPv4 - tcp4_connections_handled: stats.tcp4_connections_handled, - tcp4_announces_handled: stats.tcp4_announces_handled, - tcp4_scrapes_handled: stats.tcp4_scrapes_handled, - // TCPv6 - tcp6_connections_handled: stats.tcp6_connections_handled, - tcp6_announces_handled: stats.tcp6_announces_handled, - tcp6_scrapes_handled: stats.tcp6_scrapes_handled, - // UDP - udp_requests_aborted: stats.udp_requests_aborted, - udp_requests_banned: stats.udp_requests_banned, - udp_banned_ips_total: udp_banned_ips_total as u64, - udp_avg_connect_processing_time_ns: stats.udp_avg_connect_processing_time_ns, - udp_avg_announce_processing_time_ns: stats.udp_avg_announce_processing_time_ns, - udp_avg_scrape_processing_time_ns: stats.udp_avg_scrape_processing_time_ns, - // UDPv4 - udp4_requests: stats.udp4_requests, - udp4_connections_handled: stats.udp4_connections_handled, - udp4_announces_handled: stats.udp4_announces_handled, - udp4_scrapes_handled: stats.udp4_scrapes_handled, - udp4_responses: stats.udp4_responses, - udp4_errors_handled: stats.udp4_errors_handled, - // UDPv6 - udp6_requests: stats.udp6_requests, - udp6_connections_handled: stats.udp6_connections_handled, - udp6_announces_handled: stats.udp6_announces_handled, - udp6_scrapes_handled: stats.udp6_scrapes_handled, - udp6_responses: stats.udp6_responses, - udp6_errors_handled: stats.udp6_errors_handled, - }, - } -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - - use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::{self}; - use tokio::sync::RwLock; - use torrust_tracker_configuration::Configuration; - use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; - use torrust_tracker_test_helpers::configuration; - - use crate::packages::statistics; - use crate::packages::statistics::services::{get_metrics, TrackerMetrics}; - use crate::servers::udp::server::banning::BanService; - use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; - - pub fn tracker_configuration() -> Configuration { - configuration::ephemeral() - } - - #[tokio::test] - async fn the_statistics_service_should_return_the_tracker_metrics() { - let config = tracker_configuration(); - - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let stats_repository = Arc::new(stats_repository); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - - let tracker_metrics = get_metrics( - in_memory_torrent_repository.clone(), - ban_service.clone(), - stats_repository.clone(), - ) - .await; - - assert_eq!( - tracker_metrics, - TrackerMetrics { - torrents_metrics: TorrentsMetrics::default(), - protocol_metrics: statistics::metrics::Metrics::default(), - } - ); - } -} diff --git a/src/packages/statistics/setup.rs b/src/packages/statistics/setup.rs deleted file mode 100644 index 2a187dcf0..000000000 --- a/src/packages/statistics/setup.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! Setup for the tracker statistics. -//! -//! The [`factory`] function builds the structs needed for handling the tracker metrics. -use crate::packages::statistics; - -/// It builds the structs needed for handling the tracker metrics. -/// -/// It returns: -/// -/// - An statistics event [`Sender`](crate::packages::statistics::event::sender::Sender) that allows you to send events related to statistics. -/// - An statistics [`Repository`](crate::packages::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. -/// -/// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics -/// events are sent are received but not dispatched to the handler. -#[must_use] -pub fn factory( - tracker_usage_statistics: bool, -) -> ( - Option>, - statistics::repository::Repository, -) { - let mut stats_event_sender = None; - - let mut stats_tracker = statistics::keeper::Keeper::new(); - - if tracker_usage_statistics { - stats_event_sender = Some(stats_tracker.run_event_listener()); - } - - (stats_event_sender, stats_tracker.repository) -} - -#[cfg(test)] -mod test { - use super::factory; - - #[tokio::test] - async fn should_not_send_any_event_when_statistics_are_disabled() { - let tracker_usage_statistics = false; - - let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); - - assert!(stats_event_sender.is_none()); - } - - #[tokio::test] - async fn should_send_events_when_statistics_are_enabled() { - let tracker_usage_statistics = true; - - let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); - - assert!(stats_event_sender.is_some()); - } -} diff --git a/src/packages/udp_tracker_core/statistics/services.rs b/src/packages/udp_tracker_core/statistics/services.rs index 85ca08e54..80e1d8fb5 100644 --- a/src/packages/udp_tracker_core/statistics/services.rs +++ b/src/packages/udp_tracker_core/statistics/services.rs @@ -110,6 +110,7 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; + use crate::packages::udp_tracker_core; use crate::packages::udp_tracker_core::statistics; use crate::packages::udp_tracker_core::statistics::services::{get_metrics, TrackerMetrics}; use crate::servers::udp::server::banning::BanService; @@ -124,14 +125,16 @@ mod tests { let config = tracker_configuration(); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let (_stats_event_sender, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let stats_repository = Arc::new(stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let (_udp_stats_event_sender, udp_stats_repository) = + udp_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let udp_stats_repository = Arc::new(udp_stats_repository); + let tracker_metrics = get_metrics( in_memory_torrent_repository.clone(), ban_service.clone(), - stats_repository.clone(), + udp_stats_repository.clone(), ) .await; diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 594a11ea1..a6671e14a 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -21,7 +21,6 @@ use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::Key; use bittorrent_tracker_core::whitelist; use hyper::StatusCode; -use packages::statistics::event::sender::Sender; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; @@ -34,7 +33,7 @@ use crate::servers::http::v1::extractors::authentication_key::Extract as Extract use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::handlers::common::auth; use crate::servers::http::v1::services::{self}; -use crate::{packages, CurrentClock}; +use crate::CurrentClock; /// It handles the `announce` request when the HTTP tracker does not require /// authentication (no PATH `key` parameter required). @@ -46,7 +45,6 @@ pub async fn handle_without_key( Arc, Arc, Arc, - Arc>>, Arc>>, )>, ExtractRequest(announce_request): ExtractRequest, @@ -60,7 +58,6 @@ pub async fn handle_without_key( &state.2, &state.3, &state.4, - &state.5, &announce_request, &client_ip_sources, None, @@ -78,7 +75,6 @@ pub async fn handle_with_key( Arc, Arc, Arc, - Arc>>, Arc>>, )>, ExtractRequest(announce_request): ExtractRequest, @@ -93,7 +89,6 @@ pub async fn handle_with_key( &state.2, &state.3, &state.4, - &state.5, &announce_request, &client_ip_sources, Some(key), @@ -111,7 +106,6 @@ async fn handle( announce_handler: &Arc, authentication_service: &Arc, whitelist_authorization: &Arc, - opt_stats_event_sender: &Arc>>, opt_http_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, @@ -122,7 +116,6 @@ async fn handle( announce_handler, authentication_service, whitelist_authorization, - opt_stats_event_sender, opt_http_stats_event_sender, announce_request, client_ip_sources, @@ -148,7 +141,6 @@ async fn handle_announce( announce_handler: &Arc, authentication_service: &Arc, whitelist_authorization: &Arc, - opt_stats_event_sender: &Arc>>, opt_http_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, @@ -188,7 +180,6 @@ async fn handle_announce( let announce_data = services::announce::invoke( announce_handler.clone(), - opt_stats_event_sender.clone(), opt_http_stats_event_sender.clone(), announce_request.info_hash, &mut peer, @@ -269,17 +260,14 @@ mod tests { use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; - use packages::statistics; - use packages::statistics::event::sender::Sender; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; - use crate::packages::{self, http_tracker_core}; + use crate::packages::http_tracker_core; struct CoreTrackerServices { pub core_config: Arc, pub announce_handler: Arc, - pub stats_event_sender: Arc>>, pub whitelist_authorization: Arc, pub authentication_service: Arc, } @@ -319,9 +307,6 @@ mod tests { &db_torrent_repository, )); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - // HTTP stats let (http_stats_event_sender, http_stats_repository) = http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); @@ -332,7 +317,6 @@ mod tests { CoreTrackerServices { core_config, announce_handler, - stats_event_sender, whitelist_authorization, authentication_service, }, @@ -389,7 +373,6 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.authentication_service, &core_tracker_services.whitelist_authorization, - &core_tracker_services.stats_event_sender, &http_core_tracker_services.http_stats_event_sender, &sample_announce_request(), &sample_client_ip_sources(), @@ -417,7 +400,6 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.authentication_service, &core_tracker_services.whitelist_authorization, - &core_tracker_services.stats_event_sender, &http_core_tracker_services.http_stats_event_sender, &sample_announce_request(), &sample_client_ip_sources(), @@ -447,7 +429,6 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.authentication_service, &core_tracker_services.whitelist_authorization, - &core_tracker_services.stats_event_sender, &http_core_tracker_services.http_stats_event_sender, &announce_request, &sample_client_ip_sources(), @@ -488,7 +469,6 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.authentication_service, &core_tracker_services.whitelist_authorization, - &core_tracker_services.stats_event_sender, &http_core_tracker_services.http_stats_event_sender, &sample_announce_request(), &client_ip_sources, @@ -526,7 +506,6 @@ mod tests { &core_tracker_services.announce_handler, &core_tracker_services.authentication_service, &core_tracker_services.whitelist_authorization, - &core_tracker_services.stats_event_sender, &http_core_tracker_services.http_stats_event_sender, &sample_announce_request(), &client_ip_sources, diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index d41a3742f..09af385fb 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -16,11 +16,10 @@ use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::Key; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use hyper::StatusCode; -use packages::statistics::event::sender::Sender; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; -use crate::packages::{self, http_tracker_core}; +use crate::packages::http_tracker_core; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::extractors::scrape_request::ExtractRequest; @@ -35,7 +34,6 @@ pub async fn handle_without_key( Arc, Arc, Arc, - Arc>>, Arc>>, )>, ExtractRequest(scrape_request): ExtractRequest, @@ -48,7 +46,6 @@ pub async fn handle_without_key( &state.1, &state.2, &state.3, - &state.4, &scrape_request, &client_ip_sources, None, @@ -67,7 +64,6 @@ pub async fn handle_with_key( Arc, Arc, Arc, - Arc>>, Arc>>, )>, ExtractRequest(scrape_request): ExtractRequest, @@ -81,7 +77,6 @@ pub async fn handle_with_key( &state.1, &state.2, &state.3, - &state.4, &scrape_request, &client_ip_sources, Some(key), @@ -94,7 +89,6 @@ async fn handle( core_config: &Arc, scrape_handler: &Arc, authentication_service: &Arc, - stats_event_sender: &Arc>>, http_stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, @@ -104,7 +98,6 @@ async fn handle( core_config, scrape_handler, authentication_service, - stats_event_sender, http_stats_event_sender, scrape_request, client_ip_sources, @@ -129,7 +122,6 @@ async fn handle_scrape( core_config: &Arc, scrape_handler: &Arc, authentication_service: &Arc, - opt_stats_event_sender: &Arc>>, opt_http_stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, @@ -159,20 +151,13 @@ async fn handle_scrape( if return_real_scrape_data { Ok(services::scrape::invoke( scrape_handler, - opt_stats_event_sender, opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip, ) .await) } else { - Ok(services::scrape::fake( - opt_stats_event_sender, - opt_http_stats_event_sender, - &scrape_request.info_hashes, - &peer_ip, - ) - .await) + Ok(services::scrape::fake(opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await) } } @@ -198,16 +183,14 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; - use packages::statistics; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; - use crate::packages::{self, http_tracker_core}; + use crate::packages::http_tracker_core; struct CoreTrackerServices { pub core_config: Arc, pub scrape_handler: Arc, - pub stats_event_sender: Arc>>, pub authentication_service: Arc, } @@ -240,9 +223,6 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - // HTTP stats let (http_stats_event_sender, _http_stats_repository) = http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); @@ -252,7 +232,6 @@ mod tests { CoreTrackerServices { core_config, scrape_handler, - stats_event_sender, authentication_service, }, CoreHttpTrackerServices { http_stats_event_sender }, @@ -299,7 +278,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.scrape_handler, &core_tracker_services.authentication_service, - &core_tracker_services.stats_event_sender, &core_http_tracker_services.http_stats_event_sender, &scrape_request, &sample_client_ip_sources(), @@ -325,7 +303,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.scrape_handler, &core_tracker_services.authentication_service, - &core_tracker_services.stats_event_sender, &core_http_tracker_services.http_stats_event_sender, &scrape_request, &sample_client_ip_sources(), @@ -357,7 +334,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.scrape_handler, &core_tracker_services.authentication_service, - &core_tracker_services.stats_event_sender, &core_http_tracker_services.http_stats_event_sender, &scrape_request, &sample_client_ip_sources(), @@ -393,7 +369,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.scrape_handler, &core_tracker_services.authentication_service, - &core_tracker_services.stats_event_sender, &core_http_tracker_services.http_stats_event_sender, &sample_scrape_request(), &client_ip_sources, @@ -430,7 +405,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.scrape_handler, &core_tracker_services.authentication_service, - &core_tracker_services.stats_event_sender, &core_http_tracker_services.http_stats_event_sender, &sample_scrape_request(), &client_ip_sources, diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 7caccb673..73f4e5f29 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -43,7 +43,6 @@ pub fn router(http_tracker_container: Arc, server_socket_a http_tracker_container.announce_handler.clone(), http_tracker_container.authentication_service.clone(), http_tracker_container.whitelist_authorization.clone(), - http_tracker_container.stats_event_sender.clone(), http_tracker_container.http_stats_event_sender.clone(), )), ) @@ -54,7 +53,6 @@ pub fn router(http_tracker_container: Arc, server_socket_a http_tracker_container.announce_handler.clone(), http_tracker_container.authentication_service.clone(), http_tracker_container.whitelist_authorization.clone(), - http_tracker_container.stats_event_sender.clone(), http_tracker_container.http_stats_event_sender.clone(), )), ) @@ -65,7 +63,6 @@ pub fn router(http_tracker_container: Arc, server_socket_a http_tracker_container.core_config.clone(), http_tracker_container.scrape_handler.clone(), http_tracker_container.authentication_service.clone(), - http_tracker_container.stats_event_sender.clone(), http_tracker_container.http_stats_event_sender.clone(), )), ) @@ -75,7 +72,6 @@ pub fn router(http_tracker_container: Arc, server_socket_a http_tracker_container.core_config.clone(), http_tracker_container.scrape_handler.clone(), http_tracker_container.authentication_service.clone(), - http_tracker_container.stats_event_sender.clone(), http_tracker_container.http_stats_event_sender.clone(), )), ) diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index e7170c7e1..bc21657af 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -5,19 +5,17 @@ //! It delegates the `announce` logic to the [`AnnounceHandler`] and it returns //! the [`AnnounceData`]. //! -//! It also sends an [`statistics::event::Event`] +//! It also sends an [`http_tracker_core::statistics::event::Event`] //! because events are specific for the HTTP tracker. use std::net::IpAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; -use packages::statistics; -use packages::statistics::event::sender::Sender; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; -use crate::packages::{self, http_tracker_core}; +use crate::packages::http_tracker_core; /// The HTTP tracker `announce` service. /// @@ -31,7 +29,6 @@ use crate::packages::{self, http_tracker_core}; /// > each `announce` request. pub async fn invoke( announce_handler: Arc, - opt_stats_event_sender: Arc>>, opt_http_stats_event_sender: Arc>>, info_hash: InfoHash, peer: &mut peer::Peer, @@ -42,17 +39,6 @@ pub async fn invoke( // The tracker could change the original peer ip let announce_data = announce_handler.announce(&info_hash, peer, &original_peer_ip, peers_wanted); - if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { - match original_peer_ip { - IpAddr::V4(_) => { - stats_event_sender.send_event(statistics::event::Event::Tcp4Announce).await; - } - IpAddr::V6(_) => { - stats_event_sender.send_event(statistics::event::Event::Tcp6Announce).await; - } - } - } - if let Some(http_stats_event_sender) = opt_http_stats_event_sender.as_deref() { match original_peer_ip { IpAddr::V4(_) => { @@ -81,8 +67,6 @@ mod tests { use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - use packages::statistics; - use packages::statistics::event::sender::Sender; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; @@ -90,7 +74,6 @@ mod tests { struct CoreTrackerServices { pub core_config: Arc, pub announce_handler: Arc, - pub stats_event_sender: Arc>>, } struct CoreHttpTrackerServices { @@ -111,9 +94,6 @@ mod tests { &db_torrent_repository, )); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - // HTTP stats let (http_stats_event_sender, http_stats_repository) = http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); @@ -124,7 +104,6 @@ mod tests { CoreTrackerServices { core_config, announce_handler, - stats_event_sender, }, CoreHttpTrackerServices { http_stats_event_sender }, ) @@ -157,17 +136,9 @@ mod tests { use futures::future::BoxFuture; use mockall::mock; - use packages::statistics::event::Event; use tokio::sync::mpsc::error::SendError; - use crate::packages::{self, http_tracker_core}; - - mock! { - StatsEventSender {} - impl Sender for StatsEventSender { - fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; - } - } + use crate::packages::http_tracker_core; mock! { HttpStatsEventSender {} @@ -187,17 +158,16 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use mockall::predicate::eq; - use packages::statistics; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; - use crate::packages::{self, http_tracker_core}; + use crate::packages::http_tracker_core; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{ - initialize_core_tracker_services, sample_peer, MockHttpStatsEventSender, MockStatsEventSender, + initialize_core_tracker_services, sample_peer, MockHttpStatsEventSender, }; fn initialize_announce_handler() -> Arc { @@ -222,7 +192,6 @@ mod tests { let announce_data = invoke( core_tracker_services.announce_handler.clone(), - core_tracker_services.stats_event_sender.clone(), core_http_tracker_services.http_stats_event_sender.clone(), sample_info_hash(), &mut peer, @@ -245,15 +214,6 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_announce_event_when_the_peer_uses_ipv4() { - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Tcp4Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() @@ -269,7 +229,6 @@ mod tests { let _announce_data = invoke( announce_handler, - stats_event_sender, http_stats_event_sender, sample_info_hash(), &mut peer, @@ -299,16 +258,6 @@ mod tests { { // Tracker changes the peer IP to the tracker external IP when the peer is using the loopback IP. - // Assert that the event sent is a TCP4 event - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Tcp4Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - // Assert that the event sent is a TCP4 event let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock @@ -325,7 +274,6 @@ mod tests { let _announce_data = invoke( announce_handler, - stats_event_sender, http_stats_event_sender, sample_info_hash(), &mut peer, @@ -337,16 +285,6 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_announce_event_when_the_peer_uses_ipv6_even_if_the_tracker_changes_the_peer_ip_to_ipv4() { - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Tcp6Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - - // Assert that the event sent is a TCP4 event let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() @@ -362,7 +300,6 @@ mod tests { let _announce_data = invoke( announce_handler, - stats_event_sender, http_stats_event_sender, sample_info_hash(), &mut peer, diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index e745609aa..5325b188b 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -5,18 +5,16 @@ //! It delegates the `scrape` logic to the [`ScrapeHandler`] and it returns the //! [`ScrapeData`]. //! -//! It also sends an [`statistics::event::Event`] +//! It also sends an [`http_tracker_core::statistics::event::Event`] //! because events are specific for the HTTP tracker. use std::net::IpAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use packages::statistics::event::sender::Sender; -use packages::statistics::{self}; use torrust_tracker_primitives::core::ScrapeData; -use crate::packages::{self, http_tracker_core}; +use crate::packages::http_tracker_core; /// The HTTP tracker `scrape` service. /// @@ -30,14 +28,13 @@ use crate::packages::{self, http_tracker_core}; /// > each `scrape` request. pub async fn invoke( scrape_handler: &Arc, - opt_stats_event_sender: &Arc>>, opt_http_stats_event_sender: &Arc>>, info_hashes: &Vec, original_peer_ip: &IpAddr, ) -> ScrapeData { let scrape_data = scrape_handler.scrape(info_hashes).await; - send_scrape_event(original_peer_ip, opt_stats_event_sender, opt_http_stats_event_sender).await; + send_scrape_event(original_peer_ip, opt_http_stats_event_sender).await; scrape_data } @@ -49,32 +46,19 @@ pub async fn invoke( /// /// > **NOTICE**: tracker statistics are not updated in this case. pub async fn fake( - opt_stats_event_sender: &Arc>>, opt_http_stats_event_sender: &Arc>>, info_hashes: &Vec, original_peer_ip: &IpAddr, ) -> ScrapeData { - send_scrape_event(original_peer_ip, opt_stats_event_sender, opt_http_stats_event_sender).await; + send_scrape_event(original_peer_ip, opt_http_stats_event_sender).await; ScrapeData::zeroed(info_hashes) } async fn send_scrape_event( original_peer_ip: &IpAddr, - opt_stats_event_sender: &Arc>>, opt_http_stats_event_sender: &Arc>>, ) { - if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { - match original_peer_ip { - IpAddr::V4(_) => { - stats_event_sender.send_event(statistics::event::Event::Tcp4Scrape).await; - } - IpAddr::V6(_) => { - stats_event_sender.send_event(statistics::event::Event::Tcp6Scrape).await; - } - } - } - if let Some(http_stats_event_sender) = opt_http_stats_event_sender.as_deref() { match original_peer_ip { IpAddr::V4(_) => { @@ -109,13 +93,11 @@ mod tests { use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; use mockall::mock; - use packages::statistics::event::sender::Sender; - use packages::statistics::event::Event; use tokio::sync::mpsc::error::SendError; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::packages::{self, http_tracker_core}; + use crate::packages::http_tracker_core; fn initialize_announce_and_scrape_handlers_for_public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); @@ -161,13 +143,6 @@ mod tests { Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)) } - mock! { - StatsEventSender {} - impl Sender for StatsEventSender { - fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; - } - } - mock! { HttpStatsEventSender {} impl http_tracker_core::statistics::event::sender::Sender for HttpStatsEventSender { @@ -183,7 +158,6 @@ mod tests { use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; - use packages::statistics; use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; @@ -191,14 +165,11 @@ mod tests { use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ initialize_announce_and_scrape_handlers_for_public_tracker, initialize_scrape_handler, sample_info_hash, - sample_info_hashes, sample_peer, MockHttpStatsEventSender, MockStatsEventSender, + sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; #[tokio::test] async fn it_should_return_the_scrape_data_for_a_torrent() { - let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); - let stats_event_sender = Arc::new(stats_event_sender); - let (http_stats_event_sender, _http_stats_repository) = packages::http_tracker_core::statistics::setup::factory(false); let http_stats_event_sender = Arc::new(http_stats_event_sender); @@ -213,14 +184,7 @@ mod tests { let original_peer_ip = peer.ip(); announce_handler.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); - let scrape_data = invoke( - &scrape_handler, - &stats_event_sender, - &http_stats_event_sender, - &info_hashes, - &original_peer_ip, - ) - .await; + let scrape_data = invoke(&scrape_handler, &http_stats_event_sender, &info_hashes, &original_peer_ip).await; let mut expected_scrape_data = ScrapeData::empty(); expected_scrape_data.add_file( @@ -237,15 +201,6 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_scrape_event_when_the_peer_uses_ipv4() { - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Tcp4Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() @@ -259,27 +214,11 @@ mod tests { let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); - invoke( - &scrape_handler, - &stats_event_sender, - &http_stats_event_sender, - &sample_info_hashes(), - &peer_ip, - ) - .await; + invoke(&scrape_handler, &http_stats_event_sender, &sample_info_hashes(), &peer_ip).await; } #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Tcp6Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() @@ -293,14 +232,7 @@ mod tests { let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); - invoke( - &scrape_handler, - &stats_event_sender, - &http_stats_event_sender, - &sample_info_hashes(), - &peer_ip, - ) - .await; + invoke(&scrape_handler, &http_stats_event_sender, &sample_info_hashes(), &peer_ip).await; } } @@ -312,21 +244,17 @@ mod tests { use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; - use packages::statistics; use torrust_tracker_primitives::core::ScrapeData; use crate::packages::{self, http_tracker_core}; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ initialize_announce_and_scrape_handlers_for_public_tracker, sample_info_hash, sample_info_hashes, sample_peer, - MockHttpStatsEventSender, MockStatsEventSender, + MockHttpStatsEventSender, }; #[tokio::test] async fn it_should_always_return_the_zeroed_scrape_data_for_a_torrent() { - let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); - let stats_event_sender = Arc::new(stats_event_sender); - let (http_stats_event_sender, _http_stats_repository) = packages::http_tracker_core::statistics::setup::factory(false); let http_stats_event_sender = Arc::new(http_stats_event_sender); @@ -341,7 +269,7 @@ mod tests { let original_peer_ip = peer.ip(); announce_handler.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); - let scrape_data = fake(&stats_event_sender, &http_stats_event_sender, &info_hashes, &original_peer_ip).await; + let scrape_data = fake(&http_stats_event_sender, &info_hashes, &original_peer_ip).await; let expected_scrape_data = ScrapeData::zeroed(&info_hashes); @@ -350,15 +278,6 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_scrape_event_when_the_peer_uses_ipv4() { - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Tcp4Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() @@ -370,20 +289,11 @@ mod tests { let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); - fake(&stats_event_sender, &http_stats_event_sender, &sample_info_hashes(), &peer_ip).await; + fake(&http_stats_event_sender, &sample_info_hashes(), &peer_ip).await; } #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Tcp6Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() @@ -395,7 +305,7 @@ mod tests { let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); - fake(&stats_event_sender, &http_stats_event_sender, &sample_info_hashes(), &peer_ip).await; + fake(&http_stats_event_sender, &sample_info_hashes(), &peer_ip).await; } } } diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 4c943516e..59833b715 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -14,7 +14,6 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::whitelist; -use packages::statistics::event::sender::Sender; use torrust_tracker_clock::clock::Time as _; use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; @@ -24,11 +23,11 @@ use zerocopy::network_endian::I32; use super::connection_cookie::{check, make}; use super::RawRequest; use crate::container::UdpTrackerContainer; -use crate::packages::{statistics, udp_tracker_core}; +use crate::packages::udp_tracker_core; use crate::servers::udp::error::Error; use crate::servers::udp::{peer_builder, UDP_TRACKER_LOG_TARGET}; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; -use crate::{packages, CurrentClock}; +use crate::CurrentClock; #[derive(Debug, Clone, PartialEq)] pub(super) struct CookieTimeValues { @@ -98,7 +97,6 @@ pub(crate) async fn handle_packet( udp_request.from, local_addr, request_id, - &udp_tracker_container.stats_event_sender, &udp_tracker_container.udp_stats_event_sender, cookie_time_values.valid_range.clone(), &e, @@ -112,7 +110,6 @@ pub(crate) async fn handle_packet( udp_request.from, local_addr, request_id, - &udp_tracker_container.stats_event_sender, &udp_tracker_container.udp_stats_event_sender, cookie_time_values.valid_range.clone(), &e, @@ -146,7 +143,6 @@ pub async fn handle_request( Request::Connect(connect_request) => Ok(handle_connect( remote_addr, &connect_request, - &udp_tracker_container.stats_event_sender, &udp_tracker_container.udp_stats_event_sender, cookie_time_values.issue_time, ) @@ -158,7 +154,6 @@ pub async fn handle_request( &udp_tracker_container.core_config, &udp_tracker_container.announce_handler, &udp_tracker_container.whitelist_authorization, - &udp_tracker_container.stats_event_sender, &udp_tracker_container.udp_stats_event_sender, cookie_time_values.valid_range, ) @@ -169,7 +164,6 @@ pub async fn handle_request( remote_addr, &scrape_request, &udp_tracker_container.scrape_handler, - &udp_tracker_container.stats_event_sender, &udp_tracker_container.udp_stats_event_sender, cookie_time_values.valid_range, ) @@ -184,11 +178,10 @@ pub async fn handle_request( /// # Errors /// /// This function does not ever return an error. -#[instrument(fields(transaction_id), skip(opt_stats_event_sender, opt_udp_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_connect( remote_addr: SocketAddr, request: &ConnectRequest, - opt_stats_event_sender: &Arc>>, opt_udp_stats_event_sender: &Arc>>, cookie_issue_time: f64, ) -> Response { @@ -203,17 +196,6 @@ pub async fn handle_connect( connection_id, }; - if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { - match remote_addr { - SocketAddr::V4(_) => { - stats_event_sender.send_event(statistics::event::Event::Udp4Connect).await; - } - SocketAddr::V6(_) => { - stats_event_sender.send_event(statistics::event::Event::Udp6Connect).await; - } - } - } - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { match remote_addr { SocketAddr::V4(_) => { @@ -239,14 +221,13 @@ pub async fn handle_connect( /// /// If a error happens in the `handle_announce` function, it will just return the `ServerError`. #[allow(clippy::too_many_arguments)] -#[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_handler, whitelist_authorization, opt_stats_event_sender, opt_udp_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_handler, whitelist_authorization, opt_udp_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_announce( remote_addr: SocketAddr, request: &AnnounceRequest, core_config: &Arc, announce_handler: &Arc, whitelist_authorization: &Arc, - opt_stats_event_sender: &Arc>>, opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { @@ -281,17 +262,6 @@ pub async fn handle_announce( let response = announce_handler.announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted); - if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { - match remote_client_ip { - IpAddr::V4(_) => { - stats_event_sender.send_event(statistics::event::Event::Udp4Announce).await; - } - IpAddr::V6(_) => { - stats_event_sender.send_event(statistics::event::Event::Udp6Announce).await; - } - } - } - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { match remote_client_ip { IpAddr::V4(_) => { @@ -367,12 +337,11 @@ pub async fn handle_announce( /// # Errors /// /// This function does not ever return an error. -#[instrument(fields(transaction_id, connection_id), skip(scrape_handler, opt_stats_event_sender, opt_udp_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id), skip(scrape_handler, opt_udp_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_scrape( remote_addr: SocketAddr, request: &ScrapeRequest, scrape_handler: &Arc, - opt_stats_event_sender: &Arc>>, opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { @@ -414,17 +383,6 @@ pub async fn handle_scrape( torrent_stats.push(scrape_entry); } - if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { - match remote_addr { - SocketAddr::V4(_) => { - stats_event_sender.send_event(statistics::event::Event::Udp4Scrape).await; - } - SocketAddr::V6(_) => { - stats_event_sender.send_event(statistics::event::Event::Udp6Scrape).await; - } - } - } - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { match remote_addr { SocketAddr::V4(_) => { @@ -449,12 +407,11 @@ pub async fn handle_scrape( } #[allow(clippy::too_many_arguments)] -#[instrument(fields(transaction_id), skip(opt_stats_event_sender, opt_udp_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] async fn handle_error( remote_addr: SocketAddr, local_addr: SocketAddr, request_id: Uuid, - opt_stats_event_sender: &Arc>>, opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, e: &Error, @@ -492,17 +449,6 @@ async fn handle_error( }; if e.1.is_some() { - if let Some(stats_event_sender) = opt_stats_event_sender.as_deref() { - match remote_addr { - SocketAddr::V4(_) => { - stats_event_sender.send_event(statistics::event::Event::Udp4Error).await; - } - SocketAddr::V6(_) => { - stats_event_sender.send_event(statistics::event::Event::Udp6Error).await; - } - } - } - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { match remote_addr { SocketAddr::V4(_) => { @@ -549,8 +495,6 @@ mod tests { use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; use mockall::mock; - use packages::statistics::event::sender::Sender; - use packages::statistics::event::Event; use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{Configuration, Core}; @@ -558,7 +502,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::gen_remote_fingerprint; - use crate::packages::{statistics, udp_tracker_core}; + use crate::packages::udp_tracker_core; use crate::{packages, CurrentClock}; struct CoreTrackerServices { @@ -566,7 +510,6 @@ mod tests { pub announce_handler: Arc, pub scrape_handler: Arc, pub in_memory_torrent_repository: Arc, - pub stats_event_sender: Arc>>, pub in_memory_whitelist: Arc, pub whitelist_authorization: Arc, } @@ -605,9 +548,6 @@ mod tests { )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - let (stats_event_sender, _stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let stats_event_sender = Arc::new(stats_event_sender); - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); @@ -617,7 +557,6 @@ mod tests { announce_handler, scrape_handler, in_memory_torrent_repository, - stats_event_sender, in_memory_whitelist, whitelist_authorization, }, @@ -719,13 +658,6 @@ mod tests { } } - mock! { - StatsEventSender {} - impl Sender for StatsEventSender { - fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; - } - } - mock! { UdpStatsEventSender {} impl udp_tracker_core::statistics::event::sender::Sender for UdpStatsEventSender { @@ -740,7 +672,6 @@ mod tests { use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; use mockall::predicate::eq; - use packages::statistics; use super::{sample_ipv4_socket_address, sample_ipv6_remote_addr}; use crate::packages::{self, udp_tracker_core}; @@ -748,7 +679,7 @@ mod tests { use crate::servers::udp::handlers::handle_connect; use crate::servers::udp::handlers::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv6_remote_addr_fingerprint, sample_issue_time, - MockStatsEventSender, MockUdpStatsEventSender, + MockUdpStatsEventSender, }; fn sample_connect_request() -> ConnectRequest { @@ -759,9 +690,6 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { - let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); - let stats_event_sender = Arc::new(stats_event_sender); - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); @@ -772,7 +700,6 @@ mod tests { let response = handle_connect( sample_ipv4_remote_addr(), &request, - &stats_event_sender, &udp_stats_event_sender, sample_issue_time(), ) @@ -789,9 +716,6 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { - let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); - let stats_event_sender = Arc::new(stats_event_sender); - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); @@ -802,7 +726,6 @@ mod tests { let response = handle_connect( sample_ipv4_remote_addr(), &request, - &stats_event_sender, &udp_stats_event_sender, sample_issue_time(), ) @@ -819,9 +742,6 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { - let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); - let stats_event_sender = Arc::new(stats_event_sender); - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); @@ -832,7 +752,6 @@ mod tests { let response = handle_connect( sample_ipv6_remote_addr(), &request, - &stats_event_sender, &udp_stats_event_sender, sample_issue_time(), ) @@ -849,15 +768,6 @@ mod tests { #[tokio::test] async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Udp4Connect)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() @@ -872,7 +782,6 @@ mod tests { handle_connect( client_socket_address, &sample_connect_request(), - &stats_event_sender, &udp_stats_event_sender, sample_issue_time(), ) @@ -881,15 +790,6 @@ mod tests { #[tokio::test] async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Udp6Connect)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() @@ -902,7 +802,6 @@ mod tests { handle_connect( sample_ipv6_remote_addr(), &sample_connect_request(), - &stats_event_sender, &udp_stats_event_sender, sample_issue_time(), ) @@ -999,13 +898,13 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_configuration::Core; - use crate::packages::{self, statistics, udp_tracker_core}; + use crate::packages::{self, udp_tracker_core}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ gen_remote_fingerprint, initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, - sample_issue_time, MockStatsEventSender, MockUdpStatsEventSender, TorrentPeerBuilder, + sample_issue_time, MockUdpStatsEventSender, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; @@ -1034,7 +933,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_tracker_services.stats_event_sender, &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1069,7 +967,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_tracker_services.stats_event_sender, &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1123,7 +1020,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_tracker_services.stats_event_sender, &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1158,9 +1054,6 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); - let stats_event_sender = Arc::new(stats_event_sender); - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); @@ -1176,7 +1069,6 @@ mod tests { &core_config, &announce_handler, &whitelist_authorization, - &stats_event_sender, &udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1208,15 +1100,6 @@ mod tests { #[tokio::test] async fn should_send_the_upd4_announce_event() { - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Udp4Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() @@ -1235,7 +1118,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &stats_event_sender, &udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1283,7 +1165,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_tracker_services.stats_event_sender, &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1322,13 +1203,13 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_configuration::Core; - use crate::packages::{self, statistics, udp_tracker_core}; + use crate::packages::{self, udp_tracker_core}; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ gen_remote_fingerprint, initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, - sample_issue_time, MockStatsEventSender, MockUdpStatsEventSender, TorrentPeerBuilder, + sample_issue_time, MockUdpStatsEventSender, TorrentPeerBuilder, }; use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; @@ -1358,7 +1239,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_tracker_services.stats_event_sender, &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1396,7 +1276,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_tracker_services.stats_event_sender, &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1450,7 +1329,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_tracker_services.stats_event_sender, &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1485,9 +1363,6 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let (stats_event_sender, _stats_repository) = packages::statistics::setup::factory(false); - let stats_event_sender = Arc::new(stats_event_sender); - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); @@ -1506,7 +1381,6 @@ mod tests { &core_config, &announce_handler, &whitelist_authorization, - &stats_event_sender, &udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1538,15 +1412,6 @@ mod tests { #[tokio::test] async fn should_send_the_upd6_announce_event() { - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Udp6Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() @@ -1571,7 +1436,6 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &stats_event_sender, &udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1592,15 +1456,14 @@ mod tests { use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use mockall::predicate::eq; - use packages::statistics; - use crate::packages::{self, udp_tracker_core}; + use crate::packages::udp_tracker_core; use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ - gen_remote_fingerprint, sample_cookie_valid_range, sample_issue_time, MockStatsEventSender, - MockUdpStatsEventSender, TrackerConfigurationBuilder, + gen_remote_fingerprint, sample_cookie_valid_range, sample_issue_time, MockUdpStatsEventSender, + TrackerConfigurationBuilder, }; #[tokio::test] @@ -1614,15 +1477,6 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Udp6Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() @@ -1666,7 +1520,6 @@ mod tests { &core_config, &announce_handler, &whitelist_authorization, - &stats_event_sender, &udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1700,7 +1553,6 @@ mod tests { }; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use packages::statistics; use super::{gen_remote_fingerprint, TorrentPeerBuilder}; use crate::packages; @@ -1738,7 +1590,6 @@ mod tests { remote_addr, &request, &core_tracker_services.scrape_handler, - &core_tracker_services.stats_event_sender, &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1786,9 +1637,6 @@ mod tests { in_memory_torrent_repository: Arc, scrape_handler: Arc, ) -> Response { - let (stats_event_sender, _stats_repository) = statistics::setup::factory(false); - let stats_event_sender = Arc::new(stats_event_sender); - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); @@ -1803,7 +1651,6 @@ mod tests { remote_addr, &request, &scrape_handler, - &stats_event_sender, &udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1880,7 +1727,6 @@ mod tests { remote_addr, &request, &core_tracker_services.scrape_handler, - &core_tracker_services.stats_event_sender, &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1919,7 +1765,6 @@ mod tests { remote_addr, &request, &core_tracker_services.scrape_handler, - &core_tracker_services.stats_event_sender, &core_udp_tracker_services.udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -1950,27 +1795,17 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; - use packages::statistics; use super::sample_scrape_request; - use crate::packages::{self, udp_tracker_core}; + use crate::packages::udp_tracker_core; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, - sample_ipv4_remote_addr, MockStatsEventSender, MockUdpStatsEventSender, + sample_ipv4_remote_addr, MockUdpStatsEventSender, }; #[tokio::test] async fn should_send_the_upd4_scrape_event() { - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Udp4Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() @@ -1989,7 +1824,6 @@ mod tests { remote_addr, &sample_scrape_request(&remote_addr), &core_tracker_services.scrape_handler, - &stats_event_sender, &udp_stats_event_sender, sample_cookie_valid_range(), ) @@ -2003,27 +1837,17 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; - use packages::statistics; use super::sample_scrape_request; - use crate::packages::{self, udp_tracker_core}; + use crate::packages::udp_tracker_core; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, - sample_ipv6_remote_addr, MockStatsEventSender, MockUdpStatsEventSender, + sample_ipv6_remote_addr, MockUdpStatsEventSender, }; #[tokio::test] async fn should_send_the_upd6_scrape_event() { - let mut stats_event_sender_mock = MockStatsEventSender::new(); - stats_event_sender_mock - .expect_send_event() - .with(eq(statistics::event::Event::Udp6Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let stats_event_sender: Arc>> = - Arc::new(Some(Box::new(stats_event_sender_mock))); - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() @@ -2042,7 +1866,6 @@ mod tests { remote_addr, &sample_scrape_request(&remote_addr), &core_tracker_services.scrape_handler, - &stats_event_sender, &udp_stats_event_sender, sample_cookie_valid_range(), ) diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index 863f82e18..e640749c6 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -5,7 +5,6 @@ use std::time::Duration; use bittorrent_tracker_client::udp::client::check; use derive_more::Constructor; use futures_util::StreamExt; -use packages::statistics; use tokio::select; use tokio::sync::oneshot; use tokio::time::interval; @@ -14,7 +13,7 @@ use tracing::instrument; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; use crate::container::UdpTrackerContainer; -use crate::packages::{self, udp_tracker_core}; +use crate::packages::udp_tracker_core; use crate::servers::logging::STARTED_ON; use crate::servers::registar::ServiceHealthCheckJob; use crate::servers::signals::{shutdown_signal_with_message, Halted}; @@ -163,17 +162,6 @@ impl Launcher { } }; - if let Some(stats_event_sender) = udp_tracker_container.stats_event_sender.as_deref() { - match req.from.ip() { - IpAddr::V4(_) => { - stats_event_sender.send_event(statistics::event::Event::Udp4Request).await; - } - IpAddr::V6(_) => { - stats_event_sender.send_event(statistics::event::Event::Udp6Request).await; - } - } - } - if let Some(udp_stats_event_sender) = udp_tracker_container.udp_stats_event_sender.as_deref() { match req.from.ip() { IpAddr::V4(_) => { @@ -192,12 +180,6 @@ impl Launcher { if udp_tracker_container.ban_service.read().await.is_banned(&req.from.ip()) { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop continue: (banned ip)"); - if let Some(stats_event_sender) = udp_tracker_container.stats_event_sender.as_deref() { - stats_event_sender - .send_event(statistics::event::Event::UdpRequestBanned) - .await; - } - if let Some(udp_stats_event_sender) = udp_tracker_container.udp_stats_event_sender.as_deref() { udp_stats_event_sender .send_event(udp_tracker_core::statistics::event::Event::UdpRequestBanned) @@ -231,12 +213,6 @@ impl Launcher { if old_request_aborted { // Evicted task from active requests buffer was aborted. - if let Some(stats_event_sender) = udp_tracker_container.stats_event_sender.as_deref() { - stats_event_sender - .send_event(statistics::event::Event::UdpRequestAborted) - .await; - } - if let Some(udp_stats_event_sender) = udp_tracker_container.udp_stats_event_sender.as_deref() { udp_stats_event_sender .send_event(udp_tracker_core::statistics::event::Event::UdpRequestAborted) diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index bbf64dfb9..dc55833c2 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -4,14 +4,12 @@ use std::sync::Arc; use std::time::Duration; use aquatic_udp_protocol::Response; -use packages::statistics; -use packages::statistics::event::UdpResponseKind; use tokio::time::Instant; use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; use crate::container::UdpTrackerContainer; -use crate::packages::{self, udp_tracker_core}; +use crate::packages::udp_tracker_core; use crate::servers::udp::handlers::CookieTimeValues; use crate::servers::udp::{handlers, RawRequest}; @@ -61,13 +59,6 @@ impl Processor { Response::Error(e) => format!("Error: {e:?}"), }; - let response_kind = match &response { - Response::Connect(_) => UdpResponseKind::Connect, - Response::AnnounceIpv4(_) | Response::AnnounceIpv6(_) => UdpResponseKind::Announce, - Response::Scrape(_) => UdpResponseKind::Scrape, - Response::Error(_e) => UdpResponseKind::Error, - }; - let udp_response_kind = match &response { Response::Connect(_) => udp_tracker_core::statistics::event::UdpResponseKind::Connect, Response::AnnounceIpv4(_) | Response::AnnounceIpv6(_) => { @@ -92,27 +83,6 @@ impl Processor { tracing::debug!(%bytes_count, %sent_bytes, "sent {response_type}"); } - if let Some(stats_event_sender) = self.udp_tracker_container.stats_event_sender.as_deref() { - match target.ip() { - IpAddr::V4(_) => { - stats_event_sender - .send_event(statistics::event::Event::Udp4Response { - kind: response_kind, - req_processing_time, - }) - .await; - } - IpAddr::V6(_) => { - stats_event_sender - .send_event(statistics::event::Event::Udp6Response { - kind: response_kind, - req_processing_time, - }) - .await; - } - } - } - if let Some(udp_stats_event_sender) = self.udp_tracker_container.udp_stats_event_sender.as_deref() { match target.ip() { IpAddr::V4(_) => { diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 17013250a..97ca13e95 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -6,12 +6,11 @@ use bittorrent_tracker_core::databases::Database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use futures::executor::block_on; -use packages::statistics::repository::Repository; use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::container::HttpTrackerContainer; -use torrust_tracker_lib::packages; +use torrust_tracker_lib::packages::http_tracker_core; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; @@ -22,7 +21,7 @@ pub struct Environment { pub database: Arc>, pub in_memory_torrent_repository: Arc, pub keys_handler: Arc, - pub stats_repository: Arc, + pub http_stats_repository: Arc, pub whitelist_manager: Arc, pub registar: Registar, @@ -61,7 +60,6 @@ impl Environment { announce_handler: app_container.announce_handler.clone(), scrape_handler: app_container.scrape_handler.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), - stats_event_sender: app_container.stats_event_sender.clone(), http_stats_event_sender: app_container.http_stats_event_sender.clone(), authentication_service: app_container.authentication_service.clone(), }); @@ -72,7 +70,7 @@ impl Environment { database: app_container.database.clone(), in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), keys_handler: app_container.keys_handler.clone(), - stats_repository: app_container.stats_repository.clone(), + http_stats_repository: app_container.http_stats_repository.clone(), whitelist_manager: app_container.whitelist_manager.clone(), registar: Registar::default(), @@ -88,7 +86,7 @@ impl Environment { database: self.database.clone(), in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), keys_handler: self.keys_handler.clone(), - stats_repository: self.stats_repository.clone(), + http_stats_repository: self.http_stats_repository.clone(), whitelist_manager: self.whitelist_manager.clone(), registar: self.registar.clone(), @@ -113,7 +111,7 @@ impl Environment { database: self.database, in_memory_torrent_repository: self.in_memory_torrent_repository, keys_handler: self.keys_handler, - stats_repository: self.stats_repository, + http_stats_repository: self.http_stats_repository, whitelist_manager: self.whitelist_manager, registar: Registar::default(), diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index be603161a..48c98fa02 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -680,7 +680,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.stats_repository.get_stats().await; + let stats = env.http_stats_repository.get_stats().await; assert_eq!(stats.tcp4_connections_handled, 1); @@ -706,7 +706,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.stats_repository.get_stats().await; + let stats = env.http_stats_repository.get_stats().await; assert_eq!(stats.tcp6_connections_handled, 1); @@ -731,7 +731,7 @@ mod for_all_config_modes { ) .await; - let stats = env.stats_repository.get_stats().await; + let stats = env.http_stats_repository.get_stats().await; assert_eq!(stats.tcp6_connections_handled, 0); @@ -750,7 +750,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.stats_repository.get_stats().await; + let stats = env.http_stats_repository.get_stats().await; assert_eq!(stats.tcp4_announces_handled, 1); @@ -776,7 +776,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.stats_repository.get_stats().await; + let stats = env.http_stats_repository.get_stats().await; assert_eq!(stats.tcp6_announces_handled, 1); @@ -801,7 +801,7 @@ mod for_all_config_modes { ) .await; - let stats = env.stats_repository.get_stats().await; + let stats = env.http_stats_repository.get_stats().await; assert_eq!(stats.tcp6_announces_handled, 0); @@ -1173,7 +1173,7 @@ mod for_all_config_modes { ) .await; - let stats = env.stats_repository.get_stats().await; + let stats = env.http_stats_repository.get_stats().await; assert_eq!(stats.tcp4_scrapes_handled, 1); @@ -1205,7 +1205,7 @@ mod for_all_config_modes { ) .await; - let stats = env.stats_repository.get_stats().await; + let stats = env.http_stats_repository.get_stats().await; assert_eq!(stats.tcp6_scrapes_handled, 1); diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index d38356ef4..f6e0589f8 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -270,7 +270,7 @@ mod receiving_an_announce_request { info_hash, ); - let udp_requests_banned_before = env.stats_repository.get_stats().await.udp_requests_banned; + let udp_requests_banned_before = env.udp_stats_repository.get_stats().await.udp_requests_banned; // This should return a timeout error match client.send(announce_request.into()).await { @@ -280,7 +280,7 @@ mod receiving_an_announce_request { assert!(client.receive().await.is_err()); - let udp_requests_banned_after = env.stats_repository.get_stats().await.udp_requests_banned; + let udp_requests_banned_after = env.udp_stats_repository.get_stats().await.udp_requests_banned; let udp_banned_ips_total_after = ban_service.read().await.get_banned_ips_total(); // UDP counter for banned requests should be increased by 1 diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index c8ecac1fb..24ce7bab2 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -4,11 +4,10 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::databases::Database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use packages::statistics::repository::Repository; use torrust_tracker_configuration::{Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::container::UdpTrackerContainer; -use torrust_tracker_lib::packages; +use torrust_tracker_lib::packages::udp_tracker_core; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; @@ -23,7 +22,7 @@ where pub database: Arc>, pub in_memory_torrent_repository: Arc, - pub stats_repository: Arc, + pub udp_stats_repository: Arc, pub registar: Registar, pub server: Server, @@ -61,7 +60,6 @@ impl Environment { announce_handler: app_container.announce_handler.clone(), scrape_handler: app_container.scrape_handler.clone(), whitelist_authorization: app_container.whitelist_authorization.clone(), - stats_event_sender: app_container.stats_event_sender.clone(), udp_stats_event_sender: app_container.udp_stats_event_sender.clone(), ban_service: app_container.ban_service.clone(), }); @@ -71,7 +69,7 @@ impl Environment { database: app_container.database.clone(), in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), - stats_repository: app_container.stats_repository.clone(), + udp_stats_repository: app_container.udp_stats_repository.clone(), registar: Registar::default(), server, @@ -87,7 +85,7 @@ impl Environment { database: self.database.clone(), in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), - stats_repository: self.stats_repository.clone(), + udp_stats_repository: self.udp_stats_repository.clone(), registar: self.registar.clone(), server: self @@ -117,7 +115,7 @@ impl Environment { database: self.database, in_memory_torrent_repository: self.in_memory_torrent_repository, - stats_repository: self.stats_repository, + udp_stats_repository: self.udp_stats_repository, registar: Registar::default(), server: stopped.expect("it stop the udp tracker service"), From 8efda62509a43edd03ca53f63c981b7d8c642dcb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Feb 2025 10:32:51 +0000 Subject: [PATCH 0694/1297] test: [#1231] add tests for InMemoryKeyRepository --- packages/tracker-core/.gitignore | 1 + .../key/repository/in_memory.rs | 103 ++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 packages/tracker-core/.gitignore diff --git a/packages/tracker-core/.gitignore b/packages/tracker-core/.gitignore new file mode 100644 index 000000000..c5cb1afac --- /dev/null +++ b/packages/tracker-core/.gitignore @@ -0,0 +1 @@ +.coverage \ No newline at end of file diff --git a/packages/tracker-core/src/authentication/key/repository/in_memory.rs b/packages/tracker-core/src/authentication/key/repository/in_memory.rs index 41d34604b..0a2fc50cd 100644 --- a/packages/tracker-core/src/authentication/key/repository/in_memory.rs +++ b/packages/tracker-core/src/authentication/key/repository/in_memory.rs @@ -39,3 +39,106 @@ impl InMemoryKeyRepository { } } } + +#[cfg(test)] +mod tests { + + mod the_in_memory_key_repository_should { + use std::time::Duration; + + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::key::Key; + use crate::authentication::PeerKey; + + #[tokio::test] + async fn insert_a_new_peer_key() { + let repository = InMemoryKeyRepository::default(); + + let new_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + repository.insert(&new_peer_key).await; + + let peer_key = repository.get(&new_peer_key.key).await; + + assert_eq!(peer_key, Some(new_peer_key)); + } + + #[tokio::test] + async fn remove_a_new_peer_key() { + let repository = InMemoryKeyRepository::default(); + + let new_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + repository.insert(&new_peer_key).await; + + repository.remove(&new_peer_key.key).await; + + let peer_key = repository.get(&new_peer_key.key).await; + + assert_eq!(peer_key, None); + } + + #[tokio::test] + async fn get_a_new_peer_key_by_its_internal_key() { + let repository = InMemoryKeyRepository::default(); + + let expected_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + repository.insert(&expected_peer_key).await; + + let peer_key = repository.get(&expected_peer_key.key).await; + + assert_eq!(peer_key, Some(expected_peer_key)); + } + + #[tokio::test] + async fn clear_all_peer_keys() { + let repository = InMemoryKeyRepository::default(); + + let new_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + repository.insert(&new_peer_key).await; + + repository.clear().await; + + let peer_key = repository.get(&new_peer_key.key).await; + + assert_eq!(peer_key, None); + } + + #[tokio::test] + async fn reset_the_peer_keys_with_a_new_list_of_keys() { + let repository = InMemoryKeyRepository::default(); + + let old_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + repository.insert(&old_peer_key).await; + + let new_peer_key = PeerKey { + key: Key::new("kqdVKHlKKWXzAideqI5gvjBP4jdbe5dW").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + repository.reset_with(vec![new_peer_key.clone()]).await; + + let peer_key = repository.get(&new_peer_key.key).await; + + assert_eq!(peer_key, Some(new_peer_key)); + } + } +} From 04ee425fcc6f69b84bc2ca02d69ad41c9cfd8c41 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Feb 2025 11:18:56 +0000 Subject: [PATCH 0695/1297] chore: add todo --- packages/tracker-core/src/databases/setup.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/tracker-core/src/databases/setup.rs b/packages/tracker-core/src/databases/setup.rs index 728913e05..8d24c63b1 100644 --- a/packages/tracker-core/src/databases/setup.rs +++ b/packages/tracker-core/src/databases/setup.rs @@ -11,6 +11,8 @@ use super::Database; /// Will panic if database cannot be initialized. #[must_use] pub fn initialize_database(config: &Configuration) -> Arc> { + // todo: inject only core configuration + let driver = match config.core.database.driver { database::Driver::Sqlite3 => Driver::Sqlite3, database::Driver::MySQL => Driver::MySQL, From 7c8d2941f4152d85f7077a62f184d19a750f2c06 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Feb 2025 11:29:05 +0000 Subject: [PATCH 0696/1297] test: add tests for DatabaseKeyRepository --- .../key/repository/persisted.rs | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/packages/tracker-core/src/authentication/key/repository/persisted.rs b/packages/tracker-core/src/authentication/key/repository/persisted.rs index 322ab2913..b3948ca4f 100644 --- a/packages/tracker-core/src/authentication/key/repository/persisted.rs +++ b/packages/tracker-core/src/authentication/key/repository/persisted.rs @@ -46,3 +46,76 @@ impl DatabaseKeyRepository { Ok(keys) } } + +#[cfg(test)] +mod tests { + + mod the_persisted_key_repository_should { + + use std::time::Duration; + + use torrust_tracker_test_helpers::configuration; + + use crate::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::authentication::{Key, PeerKey}; + use crate::databases::setup::initialize_database; + + #[test] + fn persist_a_new_peer_key() { + let configuration = configuration::ephemeral_public(); + + let database = initialize_database(&configuration); + + let repository = DatabaseKeyRepository::new(&database); + + let peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + let result = repository.add(&peer_key); + + assert!(result.is_ok()); + } + + #[test] + fn remove_a_persisted_peer_key() { + let configuration = configuration::ephemeral_public(); + + let database = initialize_database(&configuration); + + let repository = DatabaseKeyRepository::new(&database); + + let peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + let _unused = repository.add(&peer_key); + + let result = repository.remove(&peer_key.key); + + assert!(result.is_ok()); + } + + #[test] + fn load_all_persisted_peer_keys() { + let configuration = configuration::ephemeral_public(); + + let database = initialize_database(&configuration); + + let repository = DatabaseKeyRepository::new(&database); + + let peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(Duration::new(9999, 0)), + }; + + let _unused = repository.add(&peer_key); + + let keys = repository.load_keys().unwrap(); + + assert_eq!(keys, vec!(peer_key)); + } + } +} From f485a525ccd0e717eef0ae005061079d16092b71 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Feb 2025 11:51:46 +0000 Subject: [PATCH 0697/1297] refactor: inject only core config in tracker core DB setup --- packages/tracker-core/src/announce_handler.rs | 2 +- .../tracker-core/src/authentication/handler.rs | 2 +- .../authentication/key/repository/persisted.rs | 6 +++--- packages/tracker-core/src/authentication/mod.rs | 2 +- packages/tracker-core/src/core_tests.rs | 2 +- packages/tracker-core/src/databases/setup.rs | 15 ++++++--------- .../tracker-core/src/whitelist/whitelist_tests.rs | 2 +- src/bootstrap/app.rs | 2 +- src/servers/http/v1/handlers/announce.rs | 2 +- src/servers/http/v1/services/announce.rs | 4 ++-- src/servers/http/v1/services/scrape.rs | 2 +- src/servers/udp/handlers.rs | 4 ++-- 12 files changed, 21 insertions(+), 24 deletions(-) diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 877555d1c..fac1df5b2 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -425,7 +425,7 @@ mod tests { config.core.tracker_policy.persistent_torrent_completed_stat = true; - let database = initialize_database(&config); + let database = initialize_database(&config.core); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let torrents_manager = Arc::new(TorrentsManager::new( diff --git a/packages/tracker-core/src/authentication/handler.rs b/packages/tracker-core/src/authentication/handler.rs index 1d74c7dfa..10ba3ecbb 100644 --- a/packages/tracker-core/src/authentication/handler.rs +++ b/packages/tracker-core/src/authentication/handler.rs @@ -266,7 +266,7 @@ mod tests { } fn instantiate_keys_handler_with_configuration(config: &Configuration) -> KeysHandler { - let database = initialize_database(config); + let database = initialize_database(&config.core); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); diff --git a/packages/tracker-core/src/authentication/key/repository/persisted.rs b/packages/tracker-core/src/authentication/key/repository/persisted.rs index b3948ca4f..60db056a5 100644 --- a/packages/tracker-core/src/authentication/key/repository/persisted.rs +++ b/packages/tracker-core/src/authentication/key/repository/persisted.rs @@ -64,7 +64,7 @@ mod tests { fn persist_a_new_peer_key() { let configuration = configuration::ephemeral_public(); - let database = initialize_database(&configuration); + let database = initialize_database(&configuration.core); let repository = DatabaseKeyRepository::new(&database); @@ -82,7 +82,7 @@ mod tests { fn remove_a_persisted_peer_key() { let configuration = configuration::ephemeral_public(); - let database = initialize_database(&configuration); + let database = initialize_database(&configuration.core); let repository = DatabaseKeyRepository::new(&database); @@ -102,7 +102,7 @@ mod tests { fn load_all_persisted_peer_keys() { let configuration = configuration::ephemeral_public(); - let database = initialize_database(&configuration); + let database = initialize_database(&configuration.core); let repository = DatabaseKeyRepository::new(&database); diff --git a/packages/tracker-core/src/authentication/mod.rs b/packages/tracker-core/src/authentication/mod.rs index 9609733da..4197f4323 100644 --- a/packages/tracker-core/src/authentication/mod.rs +++ b/packages/tracker-core/src/authentication/mod.rs @@ -49,7 +49,7 @@ mod tests { fn instantiate_keys_manager_and_authentication_with_configuration( config: &Configuration, ) -> (Arc, Arc) { - let database = initialize_database(config); + let database = initialize_database(&config.core); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); let authentication_service = Arc::new(service::AuthenticationService::new(&config.core, &in_memory_key_repository)); diff --git a/packages/tracker-core/src/core_tests.rs b/packages/tracker-core/src/core_tests.rs index 35d5fb9b7..f6b47acd0 100644 --- a/packages/tracker-core/src/core_tests.rs +++ b/packages/tracker-core/src/core_tests.rs @@ -84,7 +84,7 @@ pub fn incomplete_peer() -> Peer { #[must_use] pub fn initialize_handlers(config: &Configuration) -> (Arc, Arc) { - let database = initialize_database(config); + let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( &config.core, diff --git a/packages/tracker-core/src/databases/setup.rs b/packages/tracker-core/src/databases/setup.rs index 8d24c63b1..73ff23feb 100644 --- a/packages/tracker-core/src/databases/setup.rs +++ b/packages/tracker-core/src/databases/setup.rs @@ -1,7 +1,6 @@ use std::sync::Arc; -use torrust_tracker_configuration::v2_0_0::database; -use torrust_tracker_configuration::Configuration; +use torrust_tracker_configuration::Core; use super::driver::{self, Driver}; use super::Database; @@ -10,13 +9,11 @@ use super::Database; /// /// Will panic if database cannot be initialized. #[must_use] -pub fn initialize_database(config: &Configuration) -> Arc> { - // todo: inject only core configuration - - let driver = match config.core.database.driver { - database::Driver::Sqlite3 => Driver::Sqlite3, - database::Driver::MySQL => Driver::MySQL, +pub fn initialize_database(config: &Core) -> Arc> { + let driver = match config.database.driver { + torrust_tracker_configuration::Driver::Sqlite3 => Driver::Sqlite3, + torrust_tracker_configuration::Driver::MySQL => Driver::MySQL, }; - Arc::new(driver::build(&driver, &config.core.database.path).expect("Database driver build failed.")) + Arc::new(driver::build(&driver, &config.database.path).expect("Database driver build failed.")) } diff --git a/packages/tracker-core/src/whitelist/whitelist_tests.rs b/packages/tracker-core/src/whitelist/whitelist_tests.rs index 33f5a97f7..d2fd275f2 100644 --- a/packages/tracker-core/src/whitelist/whitelist_tests.rs +++ b/packages/tracker-core/src/whitelist/whitelist_tests.rs @@ -10,7 +10,7 @@ use crate::whitelist::setup::initialize_whitelist_manager; #[must_use] pub fn initialize_whitelist_services(config: &Configuration) -> (Arc, Arc) { - let database = initialize_database(config); + let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 93bbfe290..e0e81c70c 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -104,7 +104,7 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let udp_stats_repository = Arc::new(udp_stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let database = initialize_database(configuration); + let database = initialize_database(&configuration.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&configuration.core, &in_memory_whitelist.clone())); let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index a6671e14a..4c4aa6617 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -294,7 +294,7 @@ mod tests { fn initialize_core_tracker_services(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) { let core_config = Arc::new(config.core.clone()); - let database = initialize_database(config); + let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index bc21657af..64a29db5a 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -84,7 +84,7 @@ mod tests { let config = configuration::ephemeral_public(); let core_config = Arc::new(config.core.clone()); - let database = initialize_database(&config); + let database = initialize_database(&config.core); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); @@ -173,7 +173,7 @@ mod tests { fn initialize_announce_handler() -> Arc { let config = configuration::ephemeral(); - let database = initialize_database(&config); + let database = initialize_database(&config.core); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 5325b188b..0a3425efe 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -102,7 +102,7 @@ mod tests { fn initialize_announce_and_scrape_handlers_for_public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); - let database = initialize_database(&config); + let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index 59833b715..4f98f52d9 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -536,7 +536,7 @@ mod tests { fn initialize_core_tracker_services(config: &Configuration) -> (CoreTrackerServices, CoreUdpTrackerServices) { let core_config = Arc::new(config.core.clone()); - let database = initialize_database(config); + let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); @@ -1470,7 +1470,7 @@ mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - let database = initialize_database(&config); + let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); From e519e7f826c1aee64cc4c284b33c3f3f4a1c4843 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Feb 2025 12:14:45 +0000 Subject: [PATCH 0698/1297] refactor: [#1231] simplify tests for DatabaseKeyRepository We don't need the whole tracker config. --- packages/test-helpers/src/configuration.rs | 13 +++++++---- .../key/repository/persisted.rs | 22 +++++++++++++------ 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 678f4283a..130820334 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -1,6 +1,7 @@ //! Tracker configuration factories for testing. use std::env; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::path::PathBuf; use std::time::Duration; use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, Threshold, UdpTracker}; @@ -63,15 +64,19 @@ pub fn ephemeral() -> Configuration { tsl_config: None, }]); - // Ephemeral sqlite database - let temp_directory = env::temp_dir(); - let random_db_id = random::string(16); - let temp_file = temp_directory.join(format!("data_{random_db_id}.db")); + let temp_file = ephemeral_sqlite_database(); temp_file.to_str().unwrap().clone_into(&mut config.core.database.path); config } +#[must_use] +pub fn ephemeral_sqlite_database() -> PathBuf { + let temp_directory = env::temp_dir(); + let random_db_id = random::string(16); + temp_directory.join(format!("data_{random_db_id}.db")) +} + /// Ephemeral configuration with reverse proxy enabled. #[must_use] pub fn ephemeral_with_reverse_proxy() -> Configuration { diff --git a/packages/tracker-core/src/authentication/key/repository/persisted.rs b/packages/tracker-core/src/authentication/key/repository/persisted.rs index 60db056a5..65e56cec2 100644 --- a/packages/tracker-core/src/authentication/key/repository/persisted.rs +++ b/packages/tracker-core/src/authentication/key/repository/persisted.rs @@ -54,17 +54,25 @@ mod tests { use std::time::Duration; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_configuration::Core; + use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; use crate::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::authentication::{Key, PeerKey}; use crate::databases::setup::initialize_database; + fn ephemeral_configuration() -> Core { + let mut config = Core::default(); + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + config + } + #[test] fn persist_a_new_peer_key() { - let configuration = configuration::ephemeral_public(); + let configuration = ephemeral_configuration(); - let database = initialize_database(&configuration.core); + let database = initialize_database(&configuration); let repository = DatabaseKeyRepository::new(&database); @@ -80,9 +88,9 @@ mod tests { #[test] fn remove_a_persisted_peer_key() { - let configuration = configuration::ephemeral_public(); + let configuration = ephemeral_configuration(); - let database = initialize_database(&configuration.core); + let database = initialize_database(&configuration); let repository = DatabaseKeyRepository::new(&database); @@ -100,9 +108,9 @@ mod tests { #[test] fn load_all_persisted_peer_keys() { - let configuration = configuration::ephemeral_public(); + let configuration = ephemeral_configuration(); - let database = initialize_database(&configuration.core); + let database = initialize_database(&configuration); let repository = DatabaseKeyRepository::new(&database); From 87095400d7f91cd65c0c232e1f5bccd12af3a4a6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Feb 2025 12:18:31 +0000 Subject: [PATCH 0699/1297] refactor: [#1231] improve DatabaseKeyRepository tests --- .../src/authentication/key/repository/persisted.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/tracker-core/src/authentication/key/repository/persisted.rs b/packages/tracker-core/src/authentication/key/repository/persisted.rs index 65e56cec2..7edee62c0 100644 --- a/packages/tracker-core/src/authentication/key/repository/persisted.rs +++ b/packages/tracker-core/src/authentication/key/repository/persisted.rs @@ -82,8 +82,10 @@ mod tests { }; let result = repository.add(&peer_key); - assert!(result.is_ok()); + + let keys = repository.load_keys().unwrap(); + assert_eq!(keys, vec!(peer_key)); } #[test] @@ -102,8 +104,10 @@ mod tests { let _unused = repository.add(&peer_key); let result = repository.remove(&peer_key.key); - assert!(result.is_ok()); + + let keys = repository.load_keys().unwrap(); + assert!(keys.is_empty()); } #[test] From 0336ca7a5d404d71c4604002c8535cf6f0cba2c8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Feb 2025 12:31:45 +0000 Subject: [PATCH 0700/1297] refactor: [#1231] exctract mod --- .../src/authentication/key/mod.rs | 155 +------------ .../src/authentication/key/peer_key.rs | 206 ++++++++++++++++++ 2 files changed, 212 insertions(+), 149 deletions(-) create mode 100644 packages/tracker-core/src/authentication/key/peer_key.rs diff --git a/packages/tracker-core/src/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs index e3e7fc018..081e027bf 100644 --- a/packages/tracker-core/src/authentication/key/mod.rs +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -37,25 +37,26 @@ //! //! assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); //! ``` +pub mod peer_key; pub mod repository; use std::panic::Location; -use std::str::FromStr; use std::sync::Arc; use std::time::Duration; -use derive_more::Display; use rand::distr::Alphanumeric; use rand::{rng, Rng}; -use serde::{Deserialize, Serialize}; use thiserror::Error; use torrust_tracker_clock::clock::Time; -use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; use torrust_tracker_located_error::{DynError, LocatedError}; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::CurrentClock; +pub type PeerKey = peer_key::PeerKey; +pub type Key = peer_key::Key; +pub type ParseKeyError = peer_key::ParseKeyError; + /// HTTP tracker authentication key length. /// /// For more information see function [`generate_key`](crate::authentication::key::generate_key) to generate the @@ -130,110 +131,6 @@ pub fn verify_key_expiration(auth_key: &PeerKey) -> Result<(), Error> { } } -/// An authentication key which can potentially have an expiration time. -/// After that time is will automatically become invalid. -#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] -pub struct PeerKey { - /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` - pub key: Key, - - /// Timestamp, the key will be no longer valid after this timestamp. - /// If `None` the keys will not expire (permanent key). - pub valid_until: Option, -} - -impl std::fmt::Display for PeerKey { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self.expiry_time() { - Some(expire_time) => write!(f, "key: `{}`, valid until `{}`", self.key, expire_time), - None => write!(f, "key: `{}`, permanent", self.key), - } - } -} - -impl PeerKey { - #[must_use] - pub fn key(&self) -> Key { - self.key.clone() - } - - /// It returns the expiry time. For example, for the starting time for Unix Epoch - /// (timestamp 0) it will return a `DateTime` whose string representation is - /// `1970-01-01 00:00:00 UTC`. - /// - /// # Panics - /// - /// Will panic when the key timestamp overflows the internal i64 type. - /// (this will naturally happen in 292.5 billion years) - #[must_use] - pub fn expiry_time(&self) -> Option> { - self.valid_until.map(convert_from_timestamp_to_datetime_utc) - } -} - -/// A token used for authentication. -/// -/// - It contains only ascii alphanumeric chars: lower and uppercase letters and -/// numbers. -/// - It's a 32-char string. -#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Display, Hash)] -pub struct Key(String); - -impl Key { - /// # Errors - /// - /// Will return an error is the string represents an invalid key. - /// Valid keys can only contain 32 chars including 0-9, a-z and A-Z. - pub fn new(value: &str) -> Result { - if value.len() != AUTH_KEY_LENGTH { - return Err(ParseKeyError::InvalidKeyLength); - } - - if !value.chars().all(|c| c.is_ascii_alphanumeric()) { - return Err(ParseKeyError::InvalidChars); - } - - Ok(Self(value.to_owned())) - } - - #[must_use] - pub fn value(&self) -> &str { - &self.0 - } -} - -/// Error returned when a key cannot be parsed from a string. -/// -/// ```text -/// use bittorrent_tracker_core::authentication::Key; -/// use std::str::FromStr; -/// -/// let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; -/// let key = Key::from_str(key_string); -/// -/// assert!(key.is_ok()); -/// assert_eq!(key.unwrap().to_string(), key_string); -/// ``` -/// -/// If the string does not contains a valid key, the parser function will return -/// this error. -#[derive(Debug, Error)] -pub enum ParseKeyError { - #[error("Invalid key length. Key must be have 32 chars")] - InvalidKeyLength, - #[error("Invalid chars for key. Key can only alphanumeric chars (0-9, a-z, A-Z)")] - InvalidChars, -} - -impl FromStr for Key { - type Err = ParseKeyError; - - fn from_str(s: &str) -> Result { - Key::new(s)?; - Ok(Self(s.to_string())) - } -} - /// Verification error. Error returned when an [`PeerKey`] cannot be /// verified with the (`crate::authentication::verify_key`) function. #[derive(Debug, Error)] @@ -263,39 +160,8 @@ impl From for Error { #[cfg(test)] mod tests { - mod key { - use std::str::FromStr; - - use crate::authentication::Key; - - #[test] - fn should_be_parsed_from_an_string() { - let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; - let key = Key::from_str(key_string); - - assert!(key.is_ok()); - assert_eq!(key.unwrap().to_string(), key_string); - } - - #[test] - fn length_should_be_32() { - let key = Key::new(""); - assert!(key.is_err()); - - let string_longer_than_32 = "012345678901234567890123456789012"; // DevSkim: ignore DS173237 - let key = Key::new(string_longer_than_32); - assert!(key.is_err()); - } - - #[test] - fn should_only_include_alphanumeric_chars() { - let key = Key::new("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); - assert!(key.is_err()); - } - } - mod expiring_auth_key { - use std::str::FromStr; + use std::time::Duration; use torrust_tracker_clock::clock; @@ -303,15 +169,6 @@ mod tests { use crate::authentication; - #[test] - fn should_be_parsed_from_an_string() { - let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; - let auth_key = authentication::Key::from_str(key_string); - - assert!(auth_key.is_ok()); - assert_eq!(auth_key.unwrap().to_string(), key_string); - } - #[test] fn should_be_displayed() { // Set the time to the current time. diff --git a/packages/tracker-core/src/authentication/key/peer_key.rs b/packages/tracker-core/src/authentication/key/peer_key.rs new file mode 100644 index 000000000..c4dfc7742 --- /dev/null +++ b/packages/tracker-core/src/authentication/key/peer_key.rs @@ -0,0 +1,206 @@ +use std::str::FromStr; + +use derive_more::Display; +use serde::{Deserialize, Serialize}; +use thiserror::Error; +use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::AUTH_KEY_LENGTH; + +/// An authentication key which can potentially have an expiration time. +/// After that time is will automatically become invalid. +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] +pub struct PeerKey { + /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` + pub key: Key, + + /// Timestamp, the key will be no longer valid after this timestamp. + /// If `None` the keys will not expire (permanent key). + pub valid_until: Option, +} + +impl std::fmt::Display for PeerKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.expiry_time() { + Some(expire_time) => write!(f, "key: `{}`, valid until `{}`", self.key, expire_time), + None => write!(f, "key: `{}`, permanent", self.key), + } + } +} + +impl PeerKey { + #[must_use] + pub fn key(&self) -> Key { + self.key.clone() + } + + /// It returns the expiry time. For example, for the starting time for Unix Epoch + /// (timestamp 0) it will return a `DateTime` whose string representation is + /// `1970-01-01 00:00:00 UTC`. + /// + /// # Panics + /// + /// Will panic when the key timestamp overflows the internal i64 type. + /// (this will naturally happen in 292.5 billion years) + #[must_use] + pub fn expiry_time(&self) -> Option> { + self.valid_until.map(convert_from_timestamp_to_datetime_utc) + } +} + +/// A token used for authentication. +/// +/// - It contains only ascii alphanumeric chars: lower and uppercase letters and +/// numbers. +/// - It's a 32-char string. +#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Display, Hash)] +pub struct Key(String); + +impl Key { + /// # Errors + /// + /// Will return an error is the string represents an invalid key. + /// Valid keys can only contain 32 chars including 0-9, a-z and A-Z. + pub fn new(value: &str) -> Result { + if value.len() != AUTH_KEY_LENGTH { + return Err(ParseKeyError::InvalidKeyLength); + } + + if !value.chars().all(|c| c.is_ascii_alphanumeric()) { + return Err(ParseKeyError::InvalidChars); + } + + Ok(Self(value.to_owned())) + } + + #[must_use] + pub fn value(&self) -> &str { + &self.0 + } +} + +/// Error returned when a key cannot be parsed from a string. +/// +/// ```text +/// use bittorrent_tracker_core::authentication::Key; +/// use std::str::FromStr; +/// +/// let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; +/// let key = Key::from_str(key_string); +/// +/// assert!(key.is_ok()); +/// assert_eq!(key.unwrap().to_string(), key_string); +/// ``` +/// +/// If the string does not contains a valid key, the parser function will return +/// this error. +#[derive(Debug, Error)] +pub enum ParseKeyError { + #[error("Invalid key length. Key must be have 32 chars")] + InvalidKeyLength, + #[error("Invalid chars for key. Key can only alphanumeric chars (0-9, a-z, A-Z)")] + InvalidChars, +} + +impl FromStr for Key { + type Err = ParseKeyError; + + fn from_str(s: &str) -> Result { + Key::new(s)?; + Ok(Self(s.to_string())) + } +} + +#[cfg(test)] +mod tests { + + mod key { + use std::str::FromStr; + + use crate::authentication::Key; + + #[test] + fn should_be_parsed_from_an_string() { + let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; + let key = Key::from_str(key_string); + + assert!(key.is_ok()); + assert_eq!(key.unwrap().to_string(), key_string); + } + + #[test] + fn length_should_be_32() { + let key = Key::new(""); + assert!(key.is_err()); + + let string_longer_than_32 = "012345678901234567890123456789012"; // DevSkim: ignore DS173237 + let key = Key::new(string_longer_than_32); + assert!(key.is_err()); + } + + #[test] + fn should_only_include_alphanumeric_chars() { + let key = Key::new("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); + assert!(key.is_err()); + } + } + + mod expiring_auth_key { + use std::str::FromStr; + use std::time::Duration; + + use torrust_tracker_clock::clock; + use torrust_tracker_clock::clock::stopped::Stopped as _; + + use crate::authentication; + + #[test] + fn should_be_parsed_from_an_string() { + let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; + let auth_key = authentication::Key::from_str(key_string); + + assert!(auth_key.is_ok()); + assert_eq!(auth_key.unwrap().to_string(), key_string); + } + + #[test] + fn should_be_displayed() { + // Set the time to the current time. + clock::Stopped::local_set_to_unix_epoch(); + + let expiring_key = authentication::key::generate_key(Some(Duration::from_secs(0))); + + assert_eq!( + expiring_key.to_string(), + format!("key: `{}`, valid until `1970-01-01 00:00:00 UTC`", expiring_key.key) // cspell:disable-line + ); + } + + #[test] + fn should_be_generated_with_a_expiration_time() { + let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0))); + + assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); + } + + #[test] + fn should_be_generate_and_verified() { + // Set the time to the current time. + clock::Stopped::local_set_to_system_time_now(); + + // Make key that is valid for 19 seconds. + let expiring_key = authentication::key::generate_key(Some(Duration::from_secs(19))); + + // Mock the time has passed 10 sec. + clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); + + assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); + + // Mock the time has passed another 10 sec. + clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); + + assert!(authentication::key::verify_key_expiration(&expiring_key).is_err()); + } + } +} From 5d91a326734cfc1f35cfa6bb845cdeae82a93a49 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Feb 2025 12:59:50 +0000 Subject: [PATCH 0701/1297] test: [#1231] add more tests to peer_key mod --- .../src/authentication/key/peer_key.rs | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/packages/tracker-core/src/authentication/key/peer_key.rs b/packages/tracker-core/src/authentication/key/peer_key.rs index c4dfc7742..9b330185e 100644 --- a/packages/tracker-core/src/authentication/key/peer_key.rs +++ b/packages/tracker-core/src/authentication/key/peer_key.rs @@ -99,6 +99,7 @@ impl Key { pub enum ParseKeyError { #[error("Invalid key length. Key must be have 32 chars")] InvalidKeyLength, + #[error("Invalid chars for key. Key can only alphanumeric chars (0-9, a-z, A-Z)")] InvalidChars, } @@ -144,9 +145,16 @@ mod tests { let key = Key::new("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); assert!(key.is_err()); } + + #[test] + fn should_return_a_reference_to_the_inner_string() { + let key = Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); // DevSkim: ignore DS173237 + + assert_eq!(key.value(), "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"); // DevSkim: ignore DS173237 + } } - mod expiring_auth_key { + mod peer_key { use std::str::FromStr; use std::time::Duration; @@ -165,7 +173,7 @@ mod tests { } #[test] - fn should_be_displayed() { + fn should_be_displayed_when_it_is_expiring() { // Set the time to the current time. clock::Stopped::local_set_to_unix_epoch(); @@ -177,6 +185,16 @@ mod tests { ); } + #[test] + fn should_be_displayed_when_it_is_permanent() { + let expiring_key = authentication::key::generate_permanent_key(); + + assert_eq!( + expiring_key.to_string(), + format!("key: `{}`, permanent", expiring_key.key) // cspell:disable-line + ); + } + #[test] fn should_be_generated_with_a_expiration_time() { let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0))); From d0c7313056d0baa9f7883c2bb90cea7e00e5a419 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Feb 2025 13:23:35 +0000 Subject: [PATCH 0702/1297] refactor: [#1231] peer_key mod tests --- .../src/authentication/key/mod.rs | 16 +-- .../src/authentication/key/peer_key.rs | 107 ++++++++++-------- 2 files changed, 67 insertions(+), 56 deletions(-) diff --git a/packages/tracker-core/src/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs index 081e027bf..228e4c680 100644 --- a/packages/tracker-core/src/authentication/key/mod.rs +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -44,8 +44,6 @@ use std::panic::Location; use std::sync::Arc; use std::time::Duration; -use rand::distr::Alphanumeric; -use rand::{rng, Rng}; use thiserror::Error; use torrust_tracker_clock::clock::Time; use torrust_tracker_located_error::{DynError, LocatedError}; @@ -82,24 +80,20 @@ pub fn generate_permanent_key() -> PeerKey { /// * `lifetime`: if `None` the key will be permanent. #[must_use] pub fn generate_key(lifetime: Option) -> PeerKey { - let random_id: String = rng() - .sample_iter(&Alphanumeric) - .take(AUTH_KEY_LENGTH) - .map(char::from) - .collect(); + let random_key = Key::random(); if let Some(lifetime) = lifetime { - tracing::debug!("Generated key: {}, valid for: {:?} seconds", random_id, lifetime); + tracing::debug!("Generated key: {}, valid for: {:?} seconds", random_key, lifetime); PeerKey { - key: random_id.parse::().unwrap(), + key: random_key, valid_until: Some(CurrentClock::now_add(&lifetime).unwrap()), } } else { - tracing::debug!("Generated key: {}, permanent", random_id); + tracing::debug!("Generated key: {}, permanent", random_key); PeerKey { - key: random_id.parse::().unwrap(), + key: random_key, valid_until: None, } } diff --git a/packages/tracker-core/src/authentication/key/peer_key.rs b/packages/tracker-core/src/authentication/key/peer_key.rs index 9b330185e..a3045e54e 100644 --- a/packages/tracker-core/src/authentication/key/peer_key.rs +++ b/packages/tracker-core/src/authentication/key/peer_key.rs @@ -1,6 +1,8 @@ use std::str::FromStr; use derive_more::Display; +use rand::distr::Alphanumeric; +use rand::{rng, Rng}; use serde::{Deserialize, Serialize}; use thiserror::Error; use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; @@ -74,6 +76,20 @@ impl Key { Ok(Self(value.to_owned())) } + /// It generates a random key. + /// + /// # Panics + /// + /// Will panic if the random number generator fails to generate a valid key. + pub fn random() -> Self { + let random_id: String = rng() + .sample_iter(&Alphanumeric) + .take(AUTH_KEY_LENGTH) + .map(char::from) + .collect(); + random_id.parse::().expect("Failed to generate a valid random key") + } + #[must_use] pub fn value(&self) -> &str { &self.0 @@ -130,6 +146,11 @@ mod tests { assert_eq!(key.unwrap().to_string(), key_string); } + #[test] + fn should_be_generated_randomly() { + let _key = Key::random(); + } + #[test] fn length_should_be_32() { let key = Key::new(""); @@ -155,70 +176,66 @@ mod tests { } mod peer_key { - use std::str::FromStr; - use std::time::Duration; - use torrust_tracker_clock::clock; - use torrust_tracker_clock::clock::stopped::Stopped as _; + use std::time::Duration; - use crate::authentication; + use crate::authentication::key::peer_key::{Key, PeerKey}; #[test] - fn should_be_parsed_from_an_string() { - let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ"; - let auth_key = authentication::Key::from_str(key_string); + fn could_have_an_expiration_time() { + let expiring_key = PeerKey { + key: Key::random(), + valid_until: Some(Duration::from_secs(100)), + }; - assert!(auth_key.is_ok()); - assert_eq!(auth_key.unwrap().to_string(), key_string); + assert_eq!(expiring_key.expiry_time().unwrap().to_string(), "1970-01-01 00:01:40 UTC"); } #[test] - fn should_be_displayed_when_it_is_expiring() { - // Set the time to the current time. - clock::Stopped::local_set_to_unix_epoch(); + fn could_be_permanent() { + let permanent_key = PeerKey { + key: Key::random(), + valid_until: None, + }; - let expiring_key = authentication::key::generate_key(Some(Duration::from_secs(0))); - - assert_eq!( - expiring_key.to_string(), - format!("key: `{}`, valid until `1970-01-01 00:00:00 UTC`", expiring_key.key) // cspell:disable-line - ); + assert_eq!(permanent_key.expiry_time(), None); } - #[test] - fn should_be_displayed_when_it_is_permanent() { - let expiring_key = authentication::key::generate_permanent_key(); + mod expiring { + use std::time::Duration; - assert_eq!( - expiring_key.to_string(), - format!("key: `{}`, permanent", expiring_key.key) // cspell:disable-line - ); - } + use crate::authentication::key::peer_key::{Key, PeerKey}; - #[test] - fn should_be_generated_with_a_expiration_time() { - let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0))); + #[test] + fn should_be_displayed_when_it_is_expiring() { + let expiring_key = PeerKey { + key: Key::random(), + valid_until: Some(Duration::from_secs(100)), + }; - assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); + assert_eq!( + expiring_key.to_string(), + format!("key: `{}`, valid until `1970-01-01 00:01:40 UTC`", expiring_key.key) // cspell:disable-line + ); + } } - #[test] - fn should_be_generate_and_verified() { - // Set the time to the current time. - clock::Stopped::local_set_to_system_time_now(); - - // Make key that is valid for 19 seconds. - let expiring_key = authentication::key::generate_key(Some(Duration::from_secs(19))); - - // Mock the time has passed 10 sec. - clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); + mod permanent { - assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); + use crate::authentication::key::peer_key::{Key, PeerKey}; - // Mock the time has passed another 10 sec. - clock::Stopped::local_add(&Duration::from_secs(10)).unwrap(); + #[test] + fn should_be_displayed_when_it_is_permanent() { + let permanent_key = PeerKey { + key: Key::random(), + valid_until: None, + }; - assert!(authentication::key::verify_key_expiration(&expiring_key).is_err()); + assert_eq!( + permanent_key.to_string(), + format!("key: `{}`, permanent", permanent_key.key) // cspell:disable-line + ); + } } } } From 0d7e30e579ca61991113fd5ab96dd57a387aad3e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Feb 2025 16:01:21 +0000 Subject: [PATCH 0703/1297] refactor: [#1231] bittorrent_tracker_core::authentication::key::tests --- .../src/authentication/key/mod.rs | 46 ++++++++++++++++++- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/packages/tracker-core/src/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs index 228e4c680..bdb72b1cf 100644 --- a/packages/tracker-core/src/authentication/key/mod.rs +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -134,11 +134,13 @@ pub enum Error { KeyVerificationError { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, }, + #[error("Failed to read key: {key}, {location}")] UnableToReadKey { location: &'static Location<'static>, key: Box, }, + #[error("Key has expired, {location}")] KeyExpired { location: &'static Location<'static> }, } @@ -154,7 +156,7 @@ impl From for Error { #[cfg(test)] mod tests { - mod expiring_auth_key { + mod the_expiring_peer_key { use std::time::Duration; @@ -184,7 +186,7 @@ mod tests { } #[test] - fn should_be_generate_and_verified() { + fn expiration_verification_should_fail_when_the_key_has_expired() { // Set the time to the current time. clock::Stopped::local_set_to_system_time_now(); @@ -202,4 +204,44 @@ mod tests { assert!(authentication::key::verify_key_expiration(&expiring_key).is_err()); } } + + mod the_permanent_peer_key { + + use std::time::Duration; + + use torrust_tracker_clock::clock; + use torrust_tracker_clock::clock::stopped::Stopped as _; + + use crate::authentication; + + #[test] + fn should_be_displayed() { + // Set the time to the current time. + clock::Stopped::local_set_to_unix_epoch(); + + let expiring_key = authentication::key::generate_key(Some(Duration::from_secs(0))); + + assert_eq!( + expiring_key.to_string(), + format!("key: `{}`, valid until `1970-01-01 00:00:00 UTC`", expiring_key.key) // cspell:disable-line + ); + } + + #[test] + fn should_be_generated_without_expiration_time() { + let expiring_key = authentication::key::generate_permanent_key(); + + assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); + } + + #[test] + fn expiration_verification_should_always_succeed() { + let expiring_key = authentication::key::generate_permanent_key(); + + // Mock the time has passed 10 years. + clock::Stopped::local_add(&Duration::from_secs(10 * 365 * 24 * 60 * 60)).unwrap(); + + assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); + } + } } From 5db73be398c80d10fee73f39734c3513b5e09be9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Feb 2025 16:12:01 +0000 Subject: [PATCH 0704/1297] refactor: rename methods --- .../src/authentication/handler.rs | 36 ++++++++++--------- .../tracker-core/src/authentication/mod.rs | 23 ++++++++---- src/app.rs | 2 +- .../apis/v1/context/auth_key/handlers.rs | 9 +++-- .../api/v1/contract/context/auth_key.rs | 14 ++++---- tests/servers/http/v1/contract.rs | 4 +-- 6 files changed, 52 insertions(+), 36 deletions(-) diff --git a/packages/tracker-core/src/authentication/handler.rs b/packages/tracker-core/src/authentication/handler.rs index 10ba3ecbb..4c392ee56 100644 --- a/packages/tracker-core/src/authentication/handler.rs +++ b/packages/tracker-core/src/authentication/handler.rs @@ -54,8 +54,6 @@ impl KeysHandler { /// - The provided pre-generated key is invalid. /// - The key could not been persisted due to database issues. pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { - // code-review: all methods related to keys should be moved to a new independent "keys" service. - match add_key_req.opt_key { // Upload pre-generated key Some(pre_existing_key) => { @@ -68,7 +66,7 @@ impl KeysHandler { let key = pre_existing_key.parse::(); match key { - Ok(key) => match self.add_auth_key(key, Some(valid_until)).await { + Ok(key) => match self.add_expiring_peer_key(key, Some(valid_until)).await { Ok(auth_key) => Ok(auth_key), Err(err) => Err(PeerKeyError::DatabaseError { source: Located(err).into(), @@ -84,7 +82,7 @@ impl KeysHandler { let key = pre_existing_key.parse::(); match key { - Ok(key) => match self.add_permanent_auth_key(key).await { + Ok(key) => match self.add_permanent_peer_key(key).await { Ok(auth_key) => Ok(auth_key), Err(err) => Err(PeerKeyError::DatabaseError { source: Located(err).into(), @@ -100,14 +98,17 @@ impl KeysHandler { // Generate a new random key None => match add_key_req.opt_seconds_valid { // Expiring key - Some(seconds_valid) => match self.generate_auth_key(Some(Duration::from_secs(seconds_valid))).await { + Some(seconds_valid) => match self + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) + .await + { Ok(auth_key) => Ok(auth_key), Err(err) => Err(PeerKeyError::DatabaseError { source: Located(err).into(), }), }, // Permanent key - None => match self.generate_permanent_auth_key().await { + None => match self.generate_permanent_peer_key().await { Ok(auth_key) => Ok(auth_key), Err(err) => Err(PeerKeyError::DatabaseError { source: Located(err).into(), @@ -124,8 +125,8 @@ impl KeysHandler { /// # Errors /// /// Will return a `database::Error` if unable to add the `auth_key` to the database. - pub async fn generate_permanent_auth_key(&self) -> Result { - self.generate_auth_key(None).await + pub async fn generate_permanent_peer_key(&self) -> Result { + self.generate_expiring_peer_key(None).await } /// It generates a new expiring authentication key. @@ -140,7 +141,7 @@ impl KeysHandler { /// /// * `lifetime` - The duration in seconds for the new key. The key will be /// no longer valid after `lifetime` seconds. - pub async fn generate_auth_key(&self, lifetime: Option) -> Result { + pub async fn generate_expiring_peer_key(&self, lifetime: Option) -> Result { let peer_key = key::generate_key(lifetime); self.db_key_repository.add(&peer_key)?; @@ -162,8 +163,8 @@ impl KeysHandler { /// # Arguments /// /// * `key` - The pre-generated key. - pub async fn add_permanent_auth_key(&self, key: Key) -> Result { - self.add_auth_key(key, None).await + pub async fn add_permanent_peer_key(&self, key: Key) -> Result { + self.add_expiring_peer_key(key, None).await } /// It adds a pre-generated authentication key. @@ -180,7 +181,7 @@ impl KeysHandler { /// * `key` - The pre-generated key. /// * `lifetime` - The duration in seconds for the new key. The key will be /// no longer valid after `lifetime` seconds. - pub async fn add_auth_key( + pub async fn add_expiring_peer_key( &self, key: Key, valid_until: Option, @@ -202,7 +203,7 @@ impl KeysHandler { /// # Errors /// /// Will return a `database::Error` if unable to remove the `key` to the database. - pub async fn remove_auth_key(&self, key: &Key) -> Result<(), databases::error::Error> { + pub async fn remove_peer_key(&self, key: &Key) -> Result<(), databases::error::Error> { self.db_key_repository.remove(key)?; self.remove_in_memory_auth_key(key).await; @@ -223,7 +224,7 @@ impl KeysHandler { /// # Errors /// /// Will return a `database::Error` if unable to `load_keys` from the database. - pub async fn load_keys_from_database(&self) -> Result<(), databases::error::Error> { + pub async fn load_peer_keys_from_database(&self) -> Result<(), databases::error::Error> { let keys_from_database = self.db_key_repository.load_keys()?; self.in_memory_key_repository.reset_with(keys_from_database).await; @@ -287,7 +288,10 @@ mod tests { async fn it_should_generate_the_key() { let keys_handler = instantiate_keys_handler(); - let peer_key = keys_handler.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); + let peer_key = keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(100))) + .await + .unwrap(); assert_eq!( peer_key.valid_until, @@ -335,7 +339,7 @@ mod tests { async fn it_should_generate_the_key() { let keys_handler = instantiate_keys_handler(); - let peer_key = keys_handler.generate_permanent_auth_key().await.unwrap(); + let peer_key = keys_handler.generate_permanent_peer_key().await.unwrap(); assert_eq!(peer_key.valid_until, None); } diff --git a/packages/tracker-core/src/authentication/mod.rs b/packages/tracker-core/src/authentication/mod.rs index 4197f4323..52138d26b 100644 --- a/packages/tracker-core/src/authentication/mod.rs +++ b/packages/tracker-core/src/authentication/mod.rs @@ -65,9 +65,12 @@ mod tests { async fn it_should_remove_an_authentication_key() { let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); - let expiring_key = keys_manager.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); + let expiring_key = keys_manager + .generate_expiring_peer_key(Some(Duration::from_secs(100))) + .await + .unwrap(); - let result = keys_manager.remove_auth_key(&expiring_key.key()).await; + let result = keys_manager.remove_peer_key(&expiring_key.key()).await; assert!(result.is_ok()); @@ -79,12 +82,15 @@ mod tests { async fn it_should_load_authentication_keys_from_the_database() { let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); - let expiring_key = keys_manager.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); + let expiring_key = keys_manager + .generate_expiring_peer_key(Some(Duration::from_secs(100))) + .await + .unwrap(); // Remove the newly generated key in memory keys_manager.remove_in_memory_auth_key(&expiring_key.key()).await; - let result = keys_manager.load_keys_from_database().await; + let result = keys_manager.load_peer_keys_from_database().await; assert!(result.is_ok()); @@ -107,7 +113,10 @@ mod tests { async fn it_should_authenticate_a_peer_with_the_key() { let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); - let peer_key = keys_manager.generate_auth_key(Some(Duration::from_secs(100))).await.unwrap(); + let peer_key = keys_manager + .generate_expiring_peer_key(Some(Duration::from_secs(100))) + .await + .unwrap(); let result = authentication_service.authenticate(&peer_key.key()).await; @@ -122,7 +131,7 @@ mod tests { let past_timestamp = Duration::ZERO; let peer_key = keys_manager - .add_auth_key(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), Some(past_timestamp)) + .add_expiring_peer_key(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), Some(past_timestamp)) .await .unwrap(); @@ -183,7 +192,7 @@ mod tests { async fn it_should_authenticate_a_peer_with_the_key() { let (keys_manager, authentication_service) = instantiate_keys_manager_and_authentication(); - let peer_key = keys_manager.generate_permanent_auth_key().await.unwrap(); + let peer_key = keys_manager.generate_permanent_peer_key().await.unwrap(); let result = authentication_service.authenticate(&peer_key.key()).await; diff --git a/src/app.rs b/src/app.rs index d69874eb0..ad7524372 100644 --- a/src/app.rs +++ b/src/app.rs @@ -55,7 +55,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> if config.core.private { app_container .keys_handler - .load_keys_from_database() + .load_peer_keys_from_database() .await .expect("Could not retrieve keys from database."); } diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/src/servers/apis/v1/context/auth_key/handlers.rs index ca38ade37..c8d4c25b0 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/src/servers/apis/v1/context/auth_key/handlers.rs @@ -70,7 +70,10 @@ pub async fn generate_auth_key_handler( Path(seconds_valid_or_key): Path, ) -> Response { let seconds_valid = seconds_valid_or_key; - match keys_handler.generate_auth_key(Some(Duration::from_secs(seconds_valid))).await { + match keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) + .await + { Ok(auth_key) => auth_key_response(&AuthKey::from(auth_key)), Err(e) => failed_to_generate_key_response(e), } @@ -111,7 +114,7 @@ pub async fn delete_auth_key_handler( ) -> Response { match Key::from_str(&seconds_valid_or_key.0) { Err(_) => invalid_auth_key_param_response(&seconds_valid_or_key.0), - Ok(key) => match keys_handler.remove_auth_key(&key).await { + Ok(key) => match keys_handler.remove_peer_key(&key).await { Ok(()) => ok_response(), Err(e) => failed_to_delete_key_response(e), }, @@ -131,7 +134,7 @@ pub async fn delete_auth_key_handler( /// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#reload-authentication-keys) /// for more information about this endpoint. pub async fn reload_keys_handler(State(keys_handler): State>) -> Response { - match keys_handler.load_keys_from_database().await { + match keys_handler.load_peer_keys_from_database().await { Ok(()) => ok_response(), Err(e) => failed_to_reload_keys_response(e), } diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index 47cf0ecd2..ab9bfaf3e 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -160,7 +160,7 @@ async fn should_allow_deleting_an_auth_key() { let auth_key = env .http_api_container .keys_handler - .generate_auth_key(Some(Duration::from_secs(seconds_valid))) + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -295,7 +295,7 @@ async fn should_fail_when_the_auth_key_cannot_be_deleted() { let auth_key = env .http_api_container .keys_handler - .generate_auth_key(Some(Duration::from_secs(seconds_valid))) + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -329,7 +329,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { let auth_key = env .http_api_container .keys_handler - .generate_auth_key(Some(Duration::from_secs(seconds_valid))) + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -350,7 +350,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { let auth_key = env .http_api_container .keys_handler - .generate_auth_key(Some(Duration::from_secs(seconds_valid))) + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -379,7 +379,7 @@ async fn should_allow_reloading_keys() { let seconds_valid = 60; env.http_api_container .keys_handler - .generate_auth_key(Some(Duration::from_secs(seconds_valid))) + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -405,7 +405,7 @@ async fn should_fail_when_keys_cannot_be_reloaded() { env.http_api_container .keys_handler - .generate_auth_key(Some(Duration::from_secs(seconds_valid))) + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); @@ -434,7 +434,7 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { let seconds_valid = 60; env.http_api_container .keys_handler - .generate_auth_key(Some(Duration::from_secs(seconds_valid))) + .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 48c98fa02..bab969403 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -1404,7 +1404,7 @@ mod configured_as_private { let expiring_key = env .keys_handler - .generate_auth_key(Some(Duration::from_secs(60))) + .generate_expiring_peer_key(Some(Duration::from_secs(60))) .await .unwrap(); @@ -1553,7 +1553,7 @@ mod configured_as_private { let expiring_key = env .keys_handler - .generate_auth_key(Some(Duration::from_secs(60))) + .generate_expiring_peer_key(Some(Duration::from_secs(60))) .await .unwrap(); From e3ba1e198701e3d8cf94d274f4d6bf85b628c551 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Feb 2025 17:50:16 +0000 Subject: [PATCH 0705/1297] test: [#1231] add tests for KeysHandler --- .../src/authentication/handler.rs | 200 +++++++++++++++--- 1 file changed, 176 insertions(+), 24 deletions(-) diff --git a/packages/tracker-core/src/authentication/handler.rs b/packages/tracker-core/src/authentication/handler.rs index 4c392ee56..3643e7ece 100644 --- a/packages/tracker-core/src/authentication/handler.rs +++ b/packages/tracker-core/src/authentication/handler.rs @@ -44,7 +44,8 @@ impl KeysHandler { /// Adds new peer keys to the tracker. /// - /// Keys can be pre-generated or randomly created. They can also be permanent or expire. + /// Keys can be pre-generated or randomly created. They can also be + /// permanent or expire. /// /// # Errors /// @@ -55,8 +56,9 @@ impl KeysHandler { /// - The key could not been persisted due to database issues. pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { match add_key_req.opt_key { - // Upload pre-generated key Some(pre_existing_key) => { + // Upload pre-generated key + if let Some(seconds_valid) = add_key_req.opt_seconds_valid { // Expiring key let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(seconds_valid)) else { @@ -95,20 +97,20 @@ impl KeysHandler { } } } - // Generate a new random key None => match add_key_req.opt_seconds_valid { - // Expiring key + // Generate a new random key Some(seconds_valid) => match self .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await { + // Expiring key Ok(auth_key) => Ok(auth_key), Err(err) => Err(PeerKeyError::DatabaseError { source: Located(err).into(), }), }, - // Permanent key None => match self.generate_permanent_peer_key().await { + // Permanent key Ok(auth_key) => Ok(auth_key), Err(err) => Err(PeerKeyError::DatabaseError { source: Located(err).into(), @@ -236,7 +238,7 @@ impl KeysHandler { #[cfg(test)] mod tests { - mod the_keys_handler_when_tracker_is_configured_as_private { + mod the_keys_handler_when_the_tracker_is_configured_as_private { use std::sync::Arc; @@ -267,6 +269,8 @@ mod tests { } fn instantiate_keys_handler_with_configuration(config: &Configuration) -> KeysHandler { + // todo: pass only Core configuration + let database = initialize_database(&config.core); let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); @@ -274,22 +278,48 @@ mod tests { KeysHandler::new(&db_key_repository, &in_memory_key_repository) } - mod with_expiring_and { + mod handling_expiring_peer_keys { - mod randomly_generated_keys { + use std::time::Duration; + + use torrust_tracker_clock::clock::Time; + + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_generate_the_key() { + let keys_handler = instantiate_keys_handler(); + + let peer_key = keys_handler + .generate_expiring_peer_key(Some(Duration::from_secs(100))) + .await + .unwrap(); + + assert_eq!( + peer_key.valid_until, + Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + ); + } + + mod randomly_generated { use std::time::Duration; use torrust_tracker_clock::clock::Time; - use crate::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::authentication::handler::AddKeyRequest; use crate::CurrentClock; #[tokio::test] - async fn it_should_generate_the_key() { + async fn it_should_add_a_randomly_generated_key() { let keys_handler = instantiate_keys_handler(); let peer_key = keys_handler - .generate_expiring_peer_key(Some(Duration::from_secs(100))) + .add_peer_key(AddKeyRequest { + opt_key: None, + opt_seconds_valid: Some(100), + }) .await .unwrap(); @@ -300,14 +330,20 @@ mod tests { } } - mod pre_generated_keys { + mod pre_generated { + use std::sync::Arc; use std::time::Duration; use torrust_tracker_clock::clock::Time; - - use crate::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; - use crate::authentication::handler::AddKeyRequest; - use crate::authentication::Key; + use torrust_tracker_test_helpers::configuration; + + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::authentication::handler::{AddKeyRequest, KeysHandler}; + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::authentication::{Key, PeerKey}; + use crate::databases::setup::initialize_database; + use crate::error::PeerKeyError; use crate::CurrentClock; #[tokio::test] @@ -323,17 +359,59 @@ mod tests { .unwrap(); assert_eq!( - peer_key.valid_until, - Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) + peer_key, + PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()), + } ); } + + #[tokio::test] + async fn it_should_fail_adding_a_pre_generated_key_when_the_key_is_invalid() { + let keys_handler = instantiate_keys_handler(); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some("INVALID KEY".to_string()), + opt_seconds_valid: Some(100), + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::InvalidKey { .. })); + } + + #[tokio::test] + async fn it_should_fail_adding_a_pre_generated_key_when_there_is_a_database_error() { + let config = configuration::ephemeral_private(); + let database = initialize_database(&config.core); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + // Force database error. + // todo: extract trait for DatabaseKeyRepository to be able + // to mock it. Test should be faster if we don't have to + // create a new database. + let _unused = database.drop_database_tables(); + + let keys_handler = KeysHandler::new(&db_key_repository, &in_memory_key_repository); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(100), + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::DatabaseError { .. })); + } } } - mod with_permanent_and { + mod handling_permanent_peer_keys { mod randomly_generated_keys { - use crate::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler; #[tokio::test] async fn it_should_generate_the_key() { @@ -345,11 +423,40 @@ mod tests { } } - mod pre_generated_keys { + mod randomly_generated { - use crate::authentication::handler::tests::the_keys_handler_when_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler; use crate::authentication::handler::AddKeyRequest; - use crate::authentication::Key; + + #[tokio::test] + async fn it_should_add_a_randomly_generated_key() { + let keys_handler = instantiate_keys_handler(); + + let peer_key = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: None, + opt_seconds_valid: None, + }) + .await + .unwrap(); + + assert_eq!(peer_key.valid_until, None); + } + } + + mod pre_generated_keys { + + use std::sync::Arc; + + use torrust_tracker_test_helpers::configuration; + + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::authentication::handler::{AddKeyRequest, KeysHandler}; + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::authentication::{Key, PeerKey}; + use crate::databases::setup::initialize_database; + use crate::error::PeerKeyError; #[tokio::test] async fn it_should_add_a_pre_generated_key() { @@ -363,7 +470,52 @@ mod tests { .await .unwrap(); - assert_eq!(peer_key.valid_until, None); + assert_eq!( + peer_key, + PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: None, + } + ); + } + + #[tokio::test] + async fn it_should_fail_adding_a_pre_generated_key_when_the_key_is_invalid() { + let keys_handler = instantiate_keys_handler(); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some("INVALID KEY".to_string()), + opt_seconds_valid: None, + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::InvalidKey { .. })); + } + + #[tokio::test] + async fn it_should_fail_adding_a_pre_generated_key_when_there_is_a_database_error() { + let config = configuration::ephemeral_private(); + let database = initialize_database(&config.core); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + // Force database error. + // todo: extract trait for DatabaseKeyRepository to be able + // to mock it. Test should be faster if we don't have to + // create a new database. + let _unused = database.drop_database_tables(); + + let keys_handler = KeysHandler::new(&db_key_repository, &in_memory_key_repository); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ".to_string()), + opt_seconds_valid: None, + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::DatabaseError { .. })); } } } From bd4cef66842aaab3f23c811362ad56ceb311d4fe Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Feb 2025 08:56:31 +0000 Subject: [PATCH 0706/1297] refactor: [#1231] tests to use database mock in KeysHandler tests that require the `Database` trait. --- packages/tracker-core/Cargo.toml | 1 + .../src/authentication/handler.rs | 294 ++++++++++++------ packages/tracker-core/src/databases/mod.rs | 2 + 3 files changed, 207 insertions(+), 90 deletions(-) diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index 7b5b1f2c2..aeea30a3e 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -20,6 +20,7 @@ bittorrent-http-protocol = { version = "3.0.0-develop", path = "../http-protocol bittorrent-primitives = "0.1.0" chrono = { version = "0", default-features = false, features = ["clock"] } derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } +mockall = "0" r2d2 = "0" r2d2_mysql = "25" r2d2_sqlite = { version = "0", features = ["bundled"] } diff --git a/packages/tracker-core/src/authentication/handler.rs b/packages/tracker-core/src/authentication/handler.rs index 3643e7ece..f733f5cb6 100644 --- a/packages/tracker-core/src/authentication/handler.rs +++ b/packages/tracker-core/src/authentication/handler.rs @@ -55,68 +55,73 @@ impl KeysHandler { /// - The provided pre-generated key is invalid. /// - The key could not been persisted due to database issues. pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { - match add_key_req.opt_key { - Some(pre_existing_key) => { - // Upload pre-generated key - - if let Some(seconds_valid) = add_key_req.opt_seconds_valid { - // Expiring key - let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(seconds_valid)) else { - return Err(PeerKeyError::DurationOverflow { seconds_valid }); - }; + if let Some(pre_existing_key) = add_key_req.opt_key { + // Pre-generated key + + if let Some(seconds_valid) = add_key_req.opt_seconds_valid { + // Expiring key + + let Some(valid_until) = CurrentClock::now_add(&Duration::from_secs(seconds_valid)) else { + return Err(PeerKeyError::DurationOverflow { seconds_valid }); + }; - let key = pre_existing_key.parse::(); - - match key { - Ok(key) => match self.add_expiring_peer_key(key, Some(valid_until)).await { - Ok(auth_key) => Ok(auth_key), - Err(err) => Err(PeerKeyError::DatabaseError { - source: Located(err).into(), - }), - }, - Err(err) => Err(PeerKeyError::InvalidKey { - key: pre_existing_key, + let key = pre_existing_key.parse::(); + + match key { + Ok(key) => match self.add_expiring_peer_key(key, Some(valid_until)).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { source: Located(err).into(), }), - } - } else { - // Permanent key - let key = pre_existing_key.parse::(); - - match key { - Ok(key) => match self.add_permanent_peer_key(key).await { - Ok(auth_key) => Ok(auth_key), - Err(err) => Err(PeerKeyError::DatabaseError { - source: Located(err).into(), - }), - }, - Err(err) => Err(PeerKeyError::InvalidKey { - key: pre_existing_key, + }, + Err(err) => Err(PeerKeyError::InvalidKey { + key: pre_existing_key, + source: Located(err).into(), + }), + } + } else { + // Permanent key + + let key = pre_existing_key.parse::(); + + match key { + Ok(key) => match self.add_permanent_peer_key(key).await { + Ok(auth_key) => Ok(auth_key), + Err(err) => Err(PeerKeyError::DatabaseError { source: Located(err).into(), }), - } + }, + Err(err) => Err(PeerKeyError::InvalidKey { + key: pre_existing_key, + source: Located(err).into(), + }), } } - None => match add_key_req.opt_seconds_valid { - // Generate a new random key - Some(seconds_valid) => match self + } else { + // New randomly generate key + + if let Some(seconds_valid) = add_key_req.opt_seconds_valid { + // Expiring key + + match self .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await { - // Expiring key Ok(auth_key) => Ok(auth_key), Err(err) => Err(PeerKeyError::DatabaseError { source: Located(err).into(), }), - }, - None => match self.generate_permanent_peer_key().await { - // Permanent key + } + } else { + // Permanent key + + match self.generate_permanent_peer_key().await { Ok(auth_key) => Ok(auth_key), Err(err) => Err(PeerKeyError::DatabaseError { source: Located(err).into(), }), - }, - }, + } + } } } @@ -250,6 +255,7 @@ mod tests { use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::authentication::key::repository::persisted::DatabaseKeyRepository; use crate::databases::setup::initialize_database; + use crate::databases::Database; fn instantiate_keys_handler() -> KeysHandler { let config = configuration::ephemeral_private(); @@ -268,6 +274,13 @@ mod tests { instantiate_keys_handler_with_configuration(&config) } + fn instantiate_keys_handler_with_database(database: &Arc>) -> KeysHandler { + let db_key_repository = Arc::new(DatabaseKeyRepository::new(database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + KeysHandler::new(&db_key_repository, &in_memory_key_repository) + } + fn instantiate_keys_handler_with_configuration(config: &Configuration) -> KeysHandler { // todo: pass only Core configuration @@ -303,12 +316,22 @@ mod tests { } mod randomly_generated { + use std::panic::Location; + use std::sync::Arc; use std::time::Duration; - use torrust_tracker_clock::clock::Time; + use mockall::predicate::function; + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self, Time}; - use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler; + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{ + instantiate_keys_handler, instantiate_keys_handler_with_database, + }; use crate::authentication::handler::AddKeyRequest; + use crate::authentication::PeerKey; + use crate::databases::driver::Driver; + use crate::databases::{self, Database, MockDatabase}; + use crate::error::PeerKeyError; use crate::CurrentClock; #[tokio::test] @@ -328,21 +351,58 @@ mod tests { Some(CurrentClock::now_add(&Duration::from_secs(100)).unwrap()) ); } + + #[tokio::test] + async fn it_should_fail_adding_a_randomly_generated_key_when_there_is_a_database_error() { + clock::Stopped::local_set(&Duration::from_secs(0)); + + // The key should be valid the next 60 seconds. + let expected_valid_until = clock::Stopped::now_add(&Duration::from_secs(60)).unwrap(); + + let mut database_mock = MockDatabase::default(); + database_mock + .expect_add_key_to_keys() + .with(function(move |peer_key: &PeerKey| { + peer_key.valid_until == Some(expected_valid_until) + })) + .times(1) + .returning(|_peer_key| { + Err(databases::error::Error::InsertFailed { + location: Location::caller(), + driver: Driver::Sqlite3, + }) + }); + let database_mock: Arc> = Arc::new(Box::new(database_mock)); + + let keys_handler = instantiate_keys_handler_with_database(&database_mock); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: None, + opt_seconds_valid: Some(60), // The key is valid for 60 seconds. + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::DatabaseError { .. })); + } } mod pre_generated { + use std::panic::Location; use std::sync::Arc; use std::time::Duration; - use torrust_tracker_clock::clock::Time; - use torrust_tracker_test_helpers::configuration; + use mockall::predicate; + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self, Time}; - use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler; - use crate::authentication::handler::{AddKeyRequest, KeysHandler}; - use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{ + instantiate_keys_handler, instantiate_keys_handler_with_database, + }; + use crate::authentication::handler::AddKeyRequest; use crate::authentication::{Key, PeerKey}; - use crate::databases::setup::initialize_database; + use crate::databases::driver::Driver; + use crate::databases::{self, Database, MockDatabase}; use crate::error::PeerKeyError; use crate::CurrentClock; @@ -383,23 +443,34 @@ mod tests { #[tokio::test] async fn it_should_fail_adding_a_pre_generated_key_when_there_is_a_database_error() { - let config = configuration::ephemeral_private(); - let database = initialize_database(&config.core); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + clock::Stopped::local_set(&Duration::from_secs(0)); - // Force database error. - // todo: extract trait for DatabaseKeyRepository to be able - // to mock it. Test should be faster if we don't have to - // create a new database. - let _unused = database.drop_database_tables(); + // The key should be valid the next 60 seconds. + let expected_valid_until = clock::Stopped::now_add(&Duration::from_secs(60)).unwrap(); + let expected_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: Some(expected_valid_until), + }; - let keys_handler = KeysHandler::new(&db_key_repository, &in_memory_key_repository); + let mut database_mock = MockDatabase::default(); + database_mock + .expect_add_key_to_keys() + .with(predicate::eq(expected_peer_key)) + .times(1) + .returning(|_peer_key| { + Err(databases::error::Error::InsertFailed { + location: Location::caller(), + driver: Driver::Sqlite3, + }) + }); + let database_mock: Arc> = Arc::new(Box::new(database_mock)); + + let keys_handler = instantiate_keys_handler_with_database(&database_mock); let result = keys_handler .add_peer_key(AddKeyRequest { opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), - opt_seconds_valid: Some(100), + opt_seconds_valid: Some(60), // The key is valid for 60 seconds. }) .await; @@ -410,8 +481,21 @@ mod tests { mod handling_permanent_peer_keys { - mod randomly_generated_keys { - use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler; + mod randomly_generated { + + use std::panic::Location; + use std::sync::Arc; + + use mockall::predicate::function; + + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{ + instantiate_keys_handler, instantiate_keys_handler_with_database, + }; + use crate::authentication::handler::AddKeyRequest; + use crate::authentication::PeerKey; + use crate::databases::driver::Driver; + use crate::databases::{self, Database, MockDatabase}; + use crate::error::PeerKeyError; #[tokio::test] async fn it_should_generate_the_key() { @@ -421,12 +505,6 @@ mod tests { assert_eq!(peer_key.valid_until, None); } - } - - mod randomly_generated { - - use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler; - use crate::authentication::handler::AddKeyRequest; #[tokio::test] async fn it_should_add_a_randomly_generated_key() { @@ -442,20 +520,49 @@ mod tests { assert_eq!(peer_key.valid_until, None); } + + #[tokio::test] + async fn it_should_fail_adding_a_randomly_generated_key_when_there_is_a_database_error() { + let mut database_mock = MockDatabase::default(); + database_mock + .expect_add_key_to_keys() + .with(function(move |peer_key: &PeerKey| peer_key.valid_until.is_none())) + .times(1) + .returning(|_peer_key| { + Err(databases::error::Error::InsertFailed { + location: Location::caller(), + driver: Driver::Sqlite3, + }) + }); + let database_mock: Arc> = Arc::new(Box::new(database_mock)); + + let keys_handler = instantiate_keys_handler_with_database(&database_mock); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: None, + opt_seconds_valid: None, + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::DatabaseError { .. })); + } } mod pre_generated_keys { + use std::panic::Location; use std::sync::Arc; - use torrust_tracker_test_helpers::configuration; + use mockall::predicate; - use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::instantiate_keys_handler; - use crate::authentication::handler::{AddKeyRequest, KeysHandler}; - use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::authentication::key::repository::persisted::DatabaseKeyRepository; + use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{ + instantiate_keys_handler, instantiate_keys_handler_with_database, + }; + use crate::authentication::handler::AddKeyRequest; use crate::authentication::{Key, PeerKey}; - use crate::databases::setup::initialize_database; + use crate::databases::driver::Driver; + use crate::databases::{self, Database, MockDatabase}; use crate::error::PeerKeyError; #[tokio::test] @@ -495,22 +602,29 @@ mod tests { #[tokio::test] async fn it_should_fail_adding_a_pre_generated_key_when_there_is_a_database_error() { - let config = configuration::ephemeral_private(); - let database = initialize_database(&config.core); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - - // Force database error. - // todo: extract trait for DatabaseKeyRepository to be able - // to mock it. Test should be faster if we don't have to - // create a new database. - let _unused = database.drop_database_tables(); + let expected_peer_key = PeerKey { + key: Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(), + valid_until: None, + }; - let keys_handler = KeysHandler::new(&db_key_repository, &in_memory_key_repository); + let mut database_mock = MockDatabase::default(); + database_mock + .expect_add_key_to_keys() + .with(predicate::eq(expected_peer_key)) + .times(1) + .returning(|_peer_key| { + Err(databases::error::Error::InsertFailed { + location: Location::caller(), + driver: Driver::Sqlite3, + }) + }); + let database_mock: Arc> = Arc::new(Box::new(database_mock)); + + let keys_handler = instantiate_keys_handler_with_database(&database_mock); let result = keys_handler .add_peer_key(AddKeyRequest { - opt_key: Some("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ".to_string()), + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), opt_seconds_valid: None, }) .await; diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs index 9b9ac8e9e..f0930d05d 100644 --- a/packages/tracker-core/src/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -52,6 +52,7 @@ pub mod sqlite; use std::marker::PhantomData; use bittorrent_primitives::info_hash::InfoHash; +use mockall::automock; use torrust_tracker_primitives::PersistentTorrents; use self::error::Error; @@ -79,6 +80,7 @@ where } /// The persistence trait. It contains all the methods to interact with the database. +#[automock] pub trait Database: Sync + Send { /// It instantiates a new database driver. /// From c3117cfb961610568ab2f558a3d55f63d4dce223 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Feb 2025 12:17:13 +0000 Subject: [PATCH 0707/1297] test: [#1231] add more tests for KeysHandler --- .../tracker-core/src/authentication/handler.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/tracker-core/src/authentication/handler.rs b/packages/tracker-core/src/authentication/handler.rs index f733f5cb6..3b708a516 100644 --- a/packages/tracker-core/src/authentication/handler.rs +++ b/packages/tracker-core/src/authentication/handler.rs @@ -427,6 +427,20 @@ mod tests { ); } + #[tokio::test] + async fn it_should_fail_adding_a_pre_generated_key_when_the_key_duration_exceeds_the_maximum_duration() { + let keys_handler = instantiate_keys_handler(); + + let result = keys_handler + .add_peer_key(AddKeyRequest { + opt_key: Some(Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap().to_string()), + opt_seconds_valid: Some(u64::MAX), + }) + .await; + + assert!(matches!(result.unwrap_err(), PeerKeyError::DurationOverflow { .. })); + } + #[tokio::test] async fn it_should_fail_adding_a_pre_generated_key_when_the_key_is_invalid() { let keys_handler = instantiate_keys_handler(); From 63e773afca456ffba74683ec890f364974233d17 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Feb 2025 12:23:54 +0000 Subject: [PATCH 0708/1297] refactor: [#1231] remove dead code --- packages/tracker-core/src/authentication/handler.rs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/packages/tracker-core/src/authentication/handler.rs b/packages/tracker-core/src/authentication/handler.rs index 3b708a516..f758830ac 100644 --- a/packages/tracker-core/src/authentication/handler.rs +++ b/packages/tracker-core/src/authentication/handler.rs @@ -247,7 +247,6 @@ mod tests { use std::sync::Arc; - use torrust_tracker_configuration::v2_0_0::core::PrivateMode; use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; @@ -263,17 +262,6 @@ mod tests { instantiate_keys_handler_with_configuration(&config) } - #[allow(dead_code)] - fn instantiate_keys_handler_with_checking_keys_expiration_disabled() -> KeysHandler { - let mut config = configuration::ephemeral_private(); - - config.core.private_mode = Some(PrivateMode { - check_keys_expiration: false, - }); - - instantiate_keys_handler_with_configuration(&config) - } - fn instantiate_keys_handler_with_database(database: &Arc>) -> KeysHandler { let db_key_repository = Arc::new(DatabaseKeyRepository::new(database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); From 7d8b3948c8a977935b01affa7f4d061dec853d93 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Feb 2025 12:44:07 +0000 Subject: [PATCH 0709/1297] test: [#1231] add tests for AuthenticationService --- .../src/authentication/service.rs | 202 ++++++++++++++++-- 1 file changed, 183 insertions(+), 19 deletions(-) diff --git a/packages/tracker-core/src/authentication/service.rs b/packages/tracker-core/src/authentication/service.rs index 3e32bfbcb..98b8a3987 100644 --- a/packages/tracker-core/src/authentication/service.rs +++ b/packages/tracker-core/src/authentication/service.rs @@ -31,7 +31,7 @@ impl AuthenticationService { /// /// Will return an error if the the authentication key cannot be verified. pub async fn authenticate(&self, key: &Key) -> Result<(), Error> { - if self.is_private() { + if self.tracker_is_private() { self.verify_auth_key(key).await } else { Ok(()) @@ -40,7 +40,7 @@ impl AuthenticationService { /// Returns `true` is the tracker is in private mode. #[must_use] - pub fn is_private(&self) -> bool { + fn tracker_is_private(&self) -> bool { self.config.private } @@ -72,34 +72,198 @@ impl AuthenticationService { #[cfg(test)] mod tests { - mod the_tracker_configured_as_private { + mod the_authentication_service { - use std::str::FromStr; - use std::sync::Arc; + mod when_the_tracker_is_public { - use torrust_tracker_test_helpers::configuration; + use std::str::FromStr; + use std::sync::Arc; - use crate::authentication; - use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; - use crate::authentication::service::AuthenticationService; + use torrust_tracker_configuration::Core; - fn instantiate_authentication() -> AuthenticationService { - let config = configuration::ephemeral_private(); + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::service::AuthenticationService; + use crate::authentication::{self}; - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + fn instantiate_authentication_for_public_tracker() -> AuthenticationService { + let config = Core { + private: false, + ..Default::default() + }; - AuthenticationService::new(&config.core, &in_memory_key_repository.clone()) + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + AuthenticationService::new(&config, &in_memory_key_repository.clone()) + } + + #[tokio::test] + async fn it_should_always_authenticate_when_the_tracker_is_public() { + let authentication = instantiate_authentication_for_public_tracker(); + + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + let result = authentication.authenticate(&unregistered_key).await; + + assert!(result.is_ok()); + } } - #[tokio::test] - async fn it_should_not_authenticate_an_unregistered_key() { - let authentication = instantiate_authentication(); + mod when_the_tracker_is_private { + + use std::str::FromStr; + use std::sync::Arc; + use std::time::Duration; + + use torrust_tracker_configuration::v2_0_0::core::PrivateMode; + use torrust_tracker_configuration::Core; + + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::service::AuthenticationService; + use crate::authentication::{self, PeerKey}; + + fn instantiate_authentication_for_private_tracker() -> AuthenticationService { + let config = Core { + private: true, + ..Default::default() + }; + + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + AuthenticationService::new(&config, &in_memory_key_repository.clone()) + } + + #[tokio::test] + async fn it_should_authenticate_a_registered_key() { + let config = Core { + private: true, + ..Default::default() + }; + + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + let key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + in_memory_key_repository + .insert(&PeerKey { + key: key.clone(), + valid_until: None, + }) + .await; + + let authentication = AuthenticationService::new(&config, &in_memory_key_repository.clone()); + + let result = authentication.authenticate(&key).await; + + assert!(result.is_ok()); + } + + #[tokio::test] + async fn it_should_not_authenticate_an_unregistered_key() { + let authentication = instantiate_authentication_for_private_tracker(); + + let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + let result = authentication.authenticate(&unregistered_key).await; + + assert!(result.is_err()); + } - let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + #[tokio::test] + async fn it_should_not_authenticate_a_registered_but_expired_key_by_default() { + let config = Core { + private: true, + ..Default::default() + }; - let result = authentication.authenticate(&unregistered_key).await; + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - assert!(result.is_err()); + let key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + // Register the key with an immediate expiration date. + in_memory_key_repository + .insert(&PeerKey { + key: key.clone(), + valid_until: Some(Duration::from_secs(0)), + }) + .await; + + let authentication = AuthenticationService::new(&config, &in_memory_key_repository.clone()); + + let result = authentication.authenticate(&key).await; + + assert!(result.is_err()); + } + + #[tokio::test] + async fn it_should_not_authenticate_a_registered_but_expired_key_when_the_tracker_is_explicitly_configured_to_check_keys_expiration() { + let config = Core { + private: true, + private_mode: Some(PrivateMode { + check_keys_expiration: true, + }), + ..Default::default() + }; + + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + let key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + // Register the key with an immediate expiration date. + in_memory_key_repository + .insert(&PeerKey { + key: key.clone(), + valid_until: Some(Duration::from_secs(0)), + }) + .await; + + let authentication = AuthenticationService::new(&config, &in_memory_key_repository.clone()); + + let result = authentication.authenticate(&key).await; + + assert!(result.is_err()); + } + + mod but_the_key_expiration_check_is_disabled_by_configuration { + use std::str::FromStr; + use std::sync::Arc; + use std::time::Duration; + + use torrust_tracker_configuration::v2_0_0::core::PrivateMode; + use torrust_tracker_configuration::Core; + + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; + use crate::authentication::service::AuthenticationService; + use crate::authentication::{self, PeerKey}; + + #[tokio::test] + async fn it_should_authenticate_an_expired_registered_key() { + let config = Core { + private: true, + private_mode: Some(PrivateMode { + check_keys_expiration: false, + }), + ..Default::default() + }; + + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + + let key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + + // Register the key with an immediate expiration date. + in_memory_key_repository + .insert(&PeerKey { + key: key.clone(), + valid_until: Some(Duration::from_secs(0)), + }) + .await; + + let authentication = AuthenticationService::new(&config, &in_memory_key_repository.clone()); + + let result = authentication.authenticate(&key).await; + + assert!(result.is_ok()); + } + } } } } From 3e02b48c676c2355547bf8292fbd5a4ac6c8a349 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Feb 2025 13:18:05 +0000 Subject: [PATCH 0710/1297] test: [#1231] add more tests for authentication::service mod --- .../src/authentication/key/mod.rs | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/tracker-core/src/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs index bdb72b1cf..33b3b6099 100644 --- a/packages/tracker-core/src/authentication/key/mod.rs +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -104,10 +104,8 @@ pub fn generate_key(lifetime: Option) -> PeerKey { /// /// # Errors /// -/// Will return: -/// -/// - `Error::KeyExpired` if `auth_key.valid_until` is past the `current_time`. -/// - `Error::KeyInvalid` if `auth_key.valid_until` is past the `None`. +/// Will return a verification error [`crate::authentication::key::Error`] if +/// it cannot verify the key. pub fn verify_key_expiration(auth_key: &PeerKey) -> Result<(), Error> { let current_time: DurationSinceUnixEpoch = CurrentClock::now(); @@ -126,7 +124,7 @@ pub fn verify_key_expiration(auth_key: &PeerKey) -> Result<(), Error> { } /// Verification error. Error returned when an [`PeerKey`] cannot be -/// verified with the (`crate::authentication::verify_key`) function. +/// verified with the [`crate::authentication::key::verify_key_expiration`] function. #[derive(Debug, Error)] #[allow(dead_code)] pub enum Error { @@ -244,4 +242,17 @@ mod tests { assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); } } + + mod the_key_verification_error { + use crate::authentication::key; + + #[test] + fn could_be_a_database_error() { + let err = r2d2_sqlite::rusqlite::Error::InvalidQuery; + + let err: key::Error = err.into(); + + assert!(matches!(err, key::Error::KeyVerificationError { .. })); + } + } } From 3d89c7f8fcfd55f44692ec3163fab032426a72b7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Feb 2025 13:20:04 +0000 Subject: [PATCH 0711/1297] fix: [#1231] lint errors --- packages/tracker-core/src/authentication/service.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/tracker-core/src/authentication/service.rs b/packages/tracker-core/src/authentication/service.rs index 98b8a3987..5ca0a09ec 100644 --- a/packages/tracker-core/src/authentication/service.rs +++ b/packages/tracker-core/src/authentication/service.rs @@ -195,7 +195,8 @@ mod tests { } #[tokio::test] - async fn it_should_not_authenticate_a_registered_but_expired_key_when_the_tracker_is_explicitly_configured_to_check_keys_expiration() { + async fn it_should_not_authenticate_a_registered_but_expired_key_when_the_tracker_is_explicitly_configured_to_check_keys_expiration( + ) { let config = Core { private: true, private_mode: Some(PrivateMode { From b4a4250256c6a5511301597cae42547f070c62d3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Feb 2025 16:45:13 +0000 Subject: [PATCH 0712/1297] test: [#1235] add tests for DatabaseWhitelist --- .../src/whitelist/repository/persisted.rs | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/packages/tracker-core/src/whitelist/repository/persisted.rs b/packages/tracker-core/src/whitelist/repository/persisted.rs index c3c4a2601..a54274f16 100644 --- a/packages/tracker-core/src/whitelist/repository/persisted.rs +++ b/packages/tracker-core/src/whitelist/repository/persisted.rs @@ -60,3 +60,94 @@ impl DatabaseWhitelist { self.database.load_whitelist() } } + +#[cfg(test)] +mod tests { + mod the_persisted_whitelist_repository { + + use torrust_tracker_configuration::Core; + use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; + + use crate::core_tests::sample_info_hash; + use crate::databases::setup::initialize_database; + use crate::whitelist::repository::persisted::DatabaseWhitelist; + + fn initialize_database_whitelist() -> DatabaseWhitelist { + let configuration = ephemeral_configuration_for_listed_tracker(); + let database = initialize_database(&configuration); + DatabaseWhitelist::new(database) + } + + fn ephemeral_configuration_for_listed_tracker() -> Core { + let mut config = Core { + listed: true, + ..Default::default() + }; + + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + + config + } + + #[test] + fn should_add_a_new_infohash_to_the_list() { + let whitelist = initialize_database_whitelist(); + + let infohash = sample_info_hash(); + + let _result = whitelist.add(&infohash); + + assert_eq!(whitelist.load_from_database().unwrap(), vec!(infohash)); + } + + #[test] + fn should_remove_a_infohash_from_the_list() { + let whitelist = initialize_database_whitelist(); + + let infohash = sample_info_hash(); + + let _result = whitelist.add(&infohash); + + let _result = whitelist.remove(&infohash); + + assert_eq!(whitelist.load_from_database().unwrap(), vec!()); + } + + #[test] + fn should_load_all_infohashes_from_the_database() { + let whitelist = initialize_database_whitelist(); + + let infohash = sample_info_hash(); + + let _result = whitelist.add(&infohash); + + let result = whitelist.load_from_database().unwrap(); + + assert_eq!(result, vec!(infohash)); + } + + #[test] + fn should_not_add_the_same_infohash_to_the_list_twice() { + let whitelist = initialize_database_whitelist(); + + let infohash = sample_info_hash(); + + let _result = whitelist.add(&infohash); + let _result = whitelist.add(&infohash); + + assert_eq!(whitelist.load_from_database().unwrap(), vec!(infohash)); + } + + #[test] + fn should_not_fail_removing_an_infohash_that_is_not_in_the_list() { + let whitelist = initialize_database_whitelist(); + + let infohash = sample_info_hash(); + + let result = whitelist.remove(&infohash); + + assert!(result.is_ok()); + } + } +} From 933b6b0ef6f4c9afc48c31b8882b50bd9539e987 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Feb 2025 17:30:47 +0000 Subject: [PATCH 0713/1297] test: [#1235] add tests for WhitelistAuthorization --- .../src/whitelist/authorization.rs | 94 +++++++++++++++++-- 1 file changed, 84 insertions(+), 10 deletions(-) diff --git a/packages/tracker-core/src/whitelist/authorization.rs b/packages/tracker-core/src/whitelist/authorization.rs index 285f6613e..cb5f4acbf 100644 --- a/packages/tracker-core/src/whitelist/authorization.rs +++ b/packages/tracker-core/src/whitelist/authorization.rs @@ -61,33 +61,107 @@ impl WhitelistAuthorization { #[cfg(test)] mod tests { - mod configured_as_whitelisted { + mod the_whitelist_authorization_for_announce_and_scrape_actions { + use std::sync::Arc; + + use torrust_tracker_configuration::Core; + + use crate::whitelist::authorization::WhitelistAuthorization; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; + + fn initialize_whitelist_authorization_with(config: &Core) -> Arc { + let (whitelist_authorization, _in_memory_whitelist) = + initialize_whitelist_authorization_and_dependencies_with(config); + whitelist_authorization + } + + fn initialize_whitelist_authorization_and_dependencies_with( + config: &Core, + ) -> (Arc, Arc) { + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(config, &in_memory_whitelist.clone())); + + (whitelist_authorization, in_memory_whitelist) + } + + mod when_the_tacker_is_configured_as_listed { + + use torrust_tracker_configuration::Core; - mod handling_authorization { use crate::core_tests::sample_info_hash; - use crate::whitelist::whitelist_tests::initialize_whitelist_services_for_listed_tracker; + use crate::error::Error; + use crate::whitelist::authorization::tests::the_whitelist_authorization_for_announce_and_scrape_actions::{ + initialize_whitelist_authorization_and_dependencies_with, initialize_whitelist_authorization_with, + }; + + fn configuration_for_listed_tracker() -> Core { + Core { + listed: true, + ..Default::default() + } + } #[tokio::test] - async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { - let (whitelist_authorization, whitelist_manager) = initialize_whitelist_services_for_listed_tracker(); + async fn should_authorize_a_whitelisted_infohash() { + let (whitelist_authorization, in_memory_whitelist) = + initialize_whitelist_authorization_and_dependencies_with(&configuration_for_listed_tracker()); let info_hash = sample_info_hash(); - let result = whitelist_manager.add_torrent_to_whitelist(&info_hash).await; - assert!(result.is_ok()); + let _unused = in_memory_whitelist.add(&info_hash).await; let result = whitelist_authorization.authorize(&info_hash).await; + assert!(result.is_ok()); } #[tokio::test] - async fn it_should_not_authorize_the_announce_and_scrape_actions_on_not_whitelisted_torrents() { - let (whitelist_authorization, _whitelist_manager) = initialize_whitelist_services_for_listed_tracker(); + async fn should_not_authorize_a_non_whitelisted_infohash() { + let whitelist_authorization = initialize_whitelist_authorization_with(&configuration_for_listed_tracker()); + + let result = whitelist_authorization.authorize(&sample_info_hash()).await; + + assert!(matches!(result.unwrap_err(), Error::TorrentNotWhitelisted { .. })); + } + } + + mod when_the_tacker_is_not_configured_as_listed { + + use torrust_tracker_configuration::Core; + + use crate::core_tests::sample_info_hash; + use crate::whitelist::authorization::tests::the_whitelist_authorization_for_announce_and_scrape_actions::{ + initialize_whitelist_authorization_and_dependencies_with, initialize_whitelist_authorization_with, + }; + + fn configuration_for_non_listed_tracker() -> Core { + Core { + listed: false, + ..Default::default() + } + } + + #[tokio::test] + async fn should_authorize_a_whitelisted_infohash() { + let (whitelist_authorization, in_memory_whitelist) = + initialize_whitelist_authorization_and_dependencies_with(&configuration_for_non_listed_tracker()); let info_hash = sample_info_hash(); + let _unused = in_memory_whitelist.add(&info_hash).await; + let result = whitelist_authorization.authorize(&info_hash).await; - assert!(result.is_err()); + + assert!(result.is_ok()); + } + + #[tokio::test] + async fn should_also_authorize_a_non_whitelisted_infohash() { + let whitelist_authorization = initialize_whitelist_authorization_with(&configuration_for_non_listed_tracker()); + + let result = whitelist_authorization.authorize(&sample_info_hash()).await; + + assert!(result.is_ok()); } } } From 1735dfce6e5d44431ca568e0c330e2a18cd37167 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Feb 2025 17:39:28 +0000 Subject: [PATCH 0714/1297] refactor: [#1235] remove unused methods --- packages/tracker-core/src/whitelist/manager.rs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/packages/tracker-core/src/whitelist/manager.rs b/packages/tracker-core/src/whitelist/manager.rs index c78a59470..e810f170e 100644 --- a/packages/tracker-core/src/whitelist/manager.rs +++ b/packages/tracker-core/src/whitelist/manager.rs @@ -48,20 +48,6 @@ impl WhitelistManager { Ok(()) } - /// It removes a torrent from the whitelist in the database. - /// - /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. - pub fn remove_torrent_from_database_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { - self.database_whitelist.remove(info_hash) - } - - /// It adds a torrent from the whitelist in memory. - pub async fn add_torrent_to_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.in_memory_whitelist.add(info_hash).await - } - /// It removes a torrent from the whitelist in memory. pub async fn remove_torrent_from_memory_whitelist(&self, info_hash: &InfoHash) -> bool { self.in_memory_whitelist.remove(info_hash).await From f32f0bfc1bab808f0209a7af5454cac935a1d99b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 5 Feb 2025 08:45:31 +0000 Subject: [PATCH 0715/1297] refactor: [#1235] remove pun method only used for testing Now that we inject dependencies we can write assert using the dependencies instead of exposing public methods. --- packages/tracker-core/src/core_tests.rs | 21 +++++++ .../tracker-core/src/whitelist/manager.rs | 55 +++++++++++++------ .../src/whitelist/repository/persisted.rs | 17 +----- src/bootstrap/app.rs | 1 + src/container.rs | 2 + tests/servers/api/environment.rs | 5 ++ .../api/v1/contract/context/whitelist.rs | 12 +--- 7 files changed, 70 insertions(+), 43 deletions(-) diff --git a/packages/tracker-core/src/core_tests.rs b/packages/tracker-core/src/core_tests.rs index f6b47acd0..ac99770d4 100644 --- a/packages/tracker-core/src/core_tests.rs +++ b/packages/tracker-core/src/core_tests.rs @@ -5,8 +5,12 @@ use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::Configuration; +#[cfg(test)] +use torrust_tracker_configuration::Core; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; +#[cfg(test)] +use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; use super::announce_handler::AnnounceHandler; use super::databases::setup::initialize_database; @@ -103,3 +107,20 @@ pub fn initialize_handlers(config: &Configuration) -> (Arc, Arc (announce_handler, scrape_handler) } + +/// # Panics +/// +/// Will panic if the temporary file path is not a valid UFT string. +#[cfg(test)] +#[must_use] +pub fn ephemeral_configuration_for_listed_tracker() -> Core { + let mut config = Core { + listed: true, + ..Default::default() + }; + + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + + config +} diff --git a/packages/tracker-core/src/whitelist/manager.rs b/packages/tracker-core/src/whitelist/manager.rs index e810f170e..9d2ba249b 100644 --- a/packages/tracker-core/src/whitelist/manager.rs +++ b/packages/tracker-core/src/whitelist/manager.rs @@ -53,11 +53,6 @@ impl WhitelistManager { self.in_memory_whitelist.remove(info_hash).await } - /// It checks if a torrent is whitelisted. - pub async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { - self.in_memory_whitelist.contains(info_hash).await - } - /// It loads the whitelist from the database. /// /// # Errors @@ -81,17 +76,41 @@ mod tests { use std::sync::Arc; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_configuration::Core; + use crate::core_tests::ephemeral_configuration_for_listed_tracker; + use crate::databases::setup::initialize_database; + use crate::databases::Database; use crate::whitelist::manager::WhitelistManager; - use crate::whitelist::whitelist_tests::initialize_whitelist_services; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::whitelist::repository::persisted::DatabaseWhitelist; - fn initialize_whitelist_manager_for_whitelisted_tracker() -> Arc { - let config = configuration::ephemeral_listed(); + struct WhitelistManagerDeps { + pub _database: Arc>, + pub _database_whitelist: Arc, + pub in_memory_whitelist: Arc, + } - let (_whitelist_authorization, whitelist_manager) = initialize_whitelist_services(&config); + fn initialize_whitelist_manager_for_whitelisted_tracker() -> (Arc, Arc) { + let config = ephemeral_configuration_for_listed_tracker(); + initialize_whitelist_manager_and_deps(&config) + } - whitelist_manager + fn initialize_whitelist_manager_and_deps(config: &Core) -> (Arc, Arc) { + let database = initialize_database(config); + let database_whitelist = Arc::new(DatabaseWhitelist::new(database.clone())); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + + let whitelist_manager = Arc::new(WhitelistManager::new(database_whitelist.clone(), in_memory_whitelist.clone())); + + ( + whitelist_manager, + Arc::new(WhitelistManagerDeps { + _database: database, + _database_whitelist: database_whitelist, + in_memory_whitelist, + }), + ) } mod configured_as_whitelisted { @@ -102,18 +121,18 @@ mod tests { #[tokio::test] async fn it_should_add_a_torrent_to_the_whitelist() { - let whitelist_manager = initialize_whitelist_manager_for_whitelisted_tracker(); + let (whitelist_manager, services) = initialize_whitelist_manager_for_whitelisted_tracker(); let info_hash = sample_info_hash(); whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); - assert!(whitelist_manager.is_info_hash_whitelisted(&info_hash).await); + assert!(services.in_memory_whitelist.contains(&info_hash).await); } #[tokio::test] async fn it_should_remove_a_torrent_from_the_whitelist() { - let whitelist_manager = initialize_whitelist_manager_for_whitelisted_tracker(); + let (whitelist_manager, services) = initialize_whitelist_manager_for_whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -121,7 +140,7 @@ mod tests { whitelist_manager.remove_torrent_from_whitelist(&info_hash).await.unwrap(); - assert!(!whitelist_manager.is_info_hash_whitelisted(&info_hash).await); + assert!(!services.in_memory_whitelist.contains(&info_hash).await); } mod persistence { @@ -130,7 +149,7 @@ mod tests { #[tokio::test] async fn it_should_load_the_whitelist_from_the_database() { - let whitelist_manager = initialize_whitelist_manager_for_whitelisted_tracker(); + let (whitelist_manager, services) = initialize_whitelist_manager_for_whitelisted_tracker(); let info_hash = sample_info_hash(); @@ -138,11 +157,11 @@ mod tests { whitelist_manager.remove_torrent_from_memory_whitelist(&info_hash).await; - assert!(!whitelist_manager.is_info_hash_whitelisted(&info_hash).await); + assert!(!services.in_memory_whitelist.contains(&info_hash).await); whitelist_manager.load_whitelist_from_database().await.unwrap(); - assert!(whitelist_manager.is_info_hash_whitelisted(&info_hash).await); + assert!(services.in_memory_whitelist.contains(&info_hash).await); } } } diff --git a/packages/tracker-core/src/whitelist/repository/persisted.rs b/packages/tracker-core/src/whitelist/repository/persisted.rs index a54274f16..5101b5e35 100644 --- a/packages/tracker-core/src/whitelist/repository/persisted.rs +++ b/packages/tracker-core/src/whitelist/repository/persisted.rs @@ -65,10 +65,7 @@ impl DatabaseWhitelist { mod tests { mod the_persisted_whitelist_repository { - use torrust_tracker_configuration::Core; - use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; - - use crate::core_tests::sample_info_hash; + use crate::core_tests::{ephemeral_configuration_for_listed_tracker, sample_info_hash}; use crate::databases::setup::initialize_database; use crate::whitelist::repository::persisted::DatabaseWhitelist; @@ -78,18 +75,6 @@ mod tests { DatabaseWhitelist::new(database) } - fn ephemeral_configuration_for_listed_tracker() -> Core { - let mut config = Core { - listed: true, - ..Default::default() - }; - - let temp_file = ephemeral_sqlite_database(); - temp_file.to_str().unwrap().clone_into(&mut config.database.path); - - config - } - #[test] fn should_add_a_new_infohash_to_the_list() { let whitelist = initialize_database_whitelist(); diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index e0e81c70c..0236215f2 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -141,6 +141,7 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { scrape_handler, keys_handler, authentication_service, + in_memory_whitelist, whitelist_authorization, ban_service, http_stats_event_sender, diff --git a/src/container.rs b/src/container.rs index 51c55e533..47cc39ed3 100644 --- a/src/container.rs +++ b/src/container.rs @@ -10,6 +10,7 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; +use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; @@ -23,6 +24,7 @@ pub struct AppContainer { pub scrape_handler: Arc, pub keys_handler: Arc, pub authentication_service: Arc, + pub in_memory_whitelist: Arc, pub whitelist_authorization: Arc, pub ban_service: Arc>, pub http_stats_event_sender: Arc>>, diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 61351024d..02d6465e1 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::Database; +use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::executor::block_on; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::Configuration; @@ -22,6 +23,7 @@ where pub database: Arc>, pub authentication_service: Arc, + pub in_memory_whitelist: Arc, pub registar: Registar, pub server: ApiServer, @@ -70,6 +72,7 @@ impl Environment { database: app_container.database.clone(), authentication_service: app_container.authentication_service.clone(), + in_memory_whitelist: app_container.in_memory_whitelist.clone(), registar: Registar::default(), server, @@ -84,6 +87,7 @@ impl Environment { database: self.database.clone(), authentication_service: self.authentication_service.clone(), + in_memory_whitelist: self.in_memory_whitelist.clone(), registar: self.registar.clone(), server: self @@ -106,6 +110,7 @@ impl Environment { database: self.database, authentication_service: self.authentication_service, + in_memory_whitelist: self.in_memory_whitelist, registar: Registar::default(), server: self.server.stop().await.unwrap(), diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index 945cb00b5..ca359650f 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -31,9 +31,8 @@ async fn should_allow_whitelisting_a_torrent() { assert_ok(response).await; assert!( - env.http_api_container - .whitelist_manager - .is_info_hash_whitelisted(&InfoHash::from_str(&info_hash).unwrap()) + env.in_memory_whitelist + .contains(&InfoHash::from_str(&info_hash).unwrap()) .await ); @@ -181,12 +180,7 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { .await; assert_ok(response).await; - assert!( - !env.http_api_container - .whitelist_manager - .is_info_hash_whitelisted(&info_hash) - .await - ); + assert!(!env.in_memory_whitelist.contains(&info_hash).await); env.stop().await; } From 2862c7706c0753dcd1b5c114205336202a94cd84 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 5 Feb 2025 08:50:26 +0000 Subject: [PATCH 0716/1297] refactor: [#1235] remove another pub methog only used for testing --- packages/tracker-core/src/whitelist/manager.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/packages/tracker-core/src/whitelist/manager.rs b/packages/tracker-core/src/whitelist/manager.rs index 9d2ba249b..5efe6e15a 100644 --- a/packages/tracker-core/src/whitelist/manager.rs +++ b/packages/tracker-core/src/whitelist/manager.rs @@ -48,11 +48,6 @@ impl WhitelistManager { Ok(()) } - /// It removes a torrent from the whitelist in memory. - pub async fn remove_torrent_from_memory_whitelist(&self, info_hash: &InfoHash) -> bool { - self.in_memory_whitelist.remove(info_hash).await - } - /// It loads the whitelist from the database. /// /// # Errors @@ -155,7 +150,7 @@ mod tests { whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); - whitelist_manager.remove_torrent_from_memory_whitelist(&info_hash).await; + services.in_memory_whitelist.remove(&info_hash).await; assert!(!services.in_memory_whitelist.contains(&info_hash).await); From e994aa2d41da89a7a522a6a748712170cb3f9cb9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 5 Feb 2025 10:07:06 +0000 Subject: [PATCH 0717/1297] refactor: [#1235] WhitelistManager tests --- packages/tracker-core/src/whitelist/manager.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/tracker-core/src/whitelist/manager.rs b/packages/tracker-core/src/whitelist/manager.rs index 5efe6e15a..e1cd2f89e 100644 --- a/packages/tracker-core/src/whitelist/manager.rs +++ b/packages/tracker-core/src/whitelist/manager.rs @@ -82,7 +82,7 @@ mod tests { struct WhitelistManagerDeps { pub _database: Arc>, - pub _database_whitelist: Arc, + pub database_whitelist: Arc, pub in_memory_whitelist: Arc, } @@ -102,7 +102,7 @@ mod tests { whitelist_manager, Arc::new(WhitelistManagerDeps { _database: database, - _database_whitelist: database_whitelist, + database_whitelist, in_memory_whitelist, }), ) @@ -123,6 +123,7 @@ mod tests { whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); assert!(services.in_memory_whitelist.contains(&info_hash).await); + assert!(services.database_whitelist.load_from_database().unwrap().contains(&info_hash)); } #[tokio::test] @@ -136,6 +137,7 @@ mod tests { whitelist_manager.remove_torrent_from_whitelist(&info_hash).await.unwrap(); assert!(!services.in_memory_whitelist.contains(&info_hash).await); + assert!(!services.database_whitelist.load_from_database().unwrap().contains(&info_hash)); } mod persistence { @@ -148,11 +150,7 @@ mod tests { let info_hash = sample_info_hash(); - whitelist_manager.add_torrent_to_whitelist(&info_hash).await.unwrap(); - - services.in_memory_whitelist.remove(&info_hash).await; - - assert!(!services.in_memory_whitelist.contains(&info_hash).await); + services.database_whitelist.add(&info_hash).unwrap(); whitelist_manager.load_whitelist_from_database().await.unwrap(); From dab29d55ac30c8f70c462722f195d71230de0a40 Mon Sep 17 00:00:00 2001 From: nuts-rice Date: Wed, 5 Feb 2025 15:14:34 +0000 Subject: [PATCH 0718/1297] test: add missing tests to udp_tracker_core::statistics::event::handler --- .../statistics/event/handler.rs | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/src/packages/udp_tracker_core/statistics/event/handler.rs b/src/packages/udp_tracker_core/statistics/event/handler.rs index d696951d3..d8fa049d0 100644 --- a/src/packages/udp_tracker_core/statistics/event/handler.rs +++ b/src/packages/udp_tracker_core/statistics/event/handler.rs @@ -151,4 +151,100 @@ mod tests { assert_eq!(stats.udp6_scrapes_handled, 1); } + + #[tokio::test] + async fn should_increase_the_udp_abort_counter_when_it_receives_a_udp_abort_event() { + let stats_repository = Repository::new(); + + handle_event(Event::UdpRequestAborted, &stats_repository).await; + let stats = stats_repository.get_stats().await; + assert_eq!(stats.udp_requests_aborted, 1); + } + #[tokio::test] + async fn should_increase_the_udp_ban_counter_when_it_receives_a_udp_banned_event() { + let stats_repository = Repository::new(); + + handle_event(Event::UdpRequestBanned, &stats_repository).await; + let stats = stats_repository.get_stats().await; + assert_eq!(stats.udp_requests_banned, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_requests_counter_when_it_receives_a_udp4_request_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp4Request, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_requests, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_responses_counter_when_it_receives_a_udp4_response_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::Udp4Response { + kind: crate::packages::udp_tracker_core::statistics::event::UdpResponseKind::Announce, + req_processing_time: std::time::Duration::from_secs(1), + }, + &stats_repository, + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_responses, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_errors_counter_when_it_receives_a_udp4_error_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp4Error, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_errors_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_requests_counter_when_it_receives_a_udp6_request_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp6Request, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_requests, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_response_counter_when_it_receives_a_udp6_response_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::Udp6Response { + kind: crate::packages::udp_tracker_core::statistics::event::UdpResponseKind::Announce, + req_processing_time: std::time::Duration::from_secs(1), + }, + &stats_repository, + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_responses, 1); + } + #[tokio::test] + async fn should_increase_the_udp6_errors_counter_when_it_receives_a_udp6_error_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp6Error, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_errors_handled, 1); + } } From ed132941a83d28ad7c457dacb599bd9b32685068 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 5 Feb 2025 10:42:20 +0000 Subject: [PATCH 0719/1297] docs: add testing section to README --- packages/tracker-core/README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/tracker-core/README.md b/packages/tracker-core/README.md index 1575cda49..e36a6f4be 100644 --- a/packages/tracker-core/README.md +++ b/packages/tracker-core/README.md @@ -10,6 +10,22 @@ You usually don’t need to use this library directly. Instead, you should use t [Crate documentation](https://docs.rs/bittorrent-tracker-core). +## Testing + +Show coverage report: + +```console +cargo +stable llvm-cov +``` + +Export coverage report to `lcov` format: + +```console +cargo +stable llvm-cov --lcov --output-path=./.coverage/lcov.info +``` + +If you use Visual Studio Code, you can use the [Coverage Gutters](https://marketplace.visualstudio.com/items?itemName=semasquare.vscode-coverage-gutters) extension to view the coverage lines. + ## License The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). From 4198bc6a41d38e47b6b10d8f02e818054ef2690d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 5 Feb 2025 11:15:33 +0000 Subject: [PATCH 0720/1297] refactor: [#1240] reorganize InMemoryTorrentRepository tests We've grouped them by responsability. The responsabilities are: - To maintain the peer lists for each torrent. - To return the peer lists for a given torrent. - To return the torrent entries, which contains all the info about the torrents, including the peer lists. - To return the torrent metrics. - To return the swarm metadata for a given torrent. - To handle the persistence of the torrent entries. --- .../src/torrent/repository/in_memory.rs | 290 +++++++++++------- 1 file changed, 172 insertions(+), 118 deletions(-) diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index b9979577a..7b8b941b4 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -104,18 +104,8 @@ impl InMemoryTorrentRepository { #[cfg(test)] mod tests { - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; - use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; - use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; - use torrust_tracker_primitives::peer::Peer; - use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; - use torrust_tracker_primitives::DurationSinceUnixEpoch; - - use crate::core_tests::{leecher, sample_info_hash, sample_peer}; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use aquatic_udp_protocol::PeerId; /// It generates a peer id from a number where the number is the last /// part of the peer ID. For example, for `12` it returns @@ -135,148 +125,212 @@ mod tests { PeerId(peer_id_bytes) } - #[tokio::test] - async fn it_should_collect_torrent_metrics() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + // The `InMemoryTorrentRepository` has these responsibilities: + // - To maintain the peer lists for each torrent. + // - To return the peer lists for a given torrent. + // - To return the torrent entries, which contains all the info about the + // torrents, including the peer lists. + // - To return the torrent metrics. + // - To return the swarm metadata for a given torrent. + // - To handle the persistence of the torrent entries. + + mod maintaining_the_peer_lists { + // Methods: + // - upsert_peer + // - remove + // - remove_inactive_peers + // - remove_peerless_torrents + } - assert_eq!( - torrents_metrics, - TorrentsMetrics { - complete: 0, - downloaded: 0, - incomplete: 0, - torrents: 0 + mod returning_peer_lists_for_a_torrent { + // Methods: + // - get_peers_for + // - get_torrent_peers + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::torrent::repository::in_memory::tests::numeric_peer_id; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + + #[tokio::test] + async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + + for idx in 1..=75 { + let peer = Peer { + peer_id: numeric_peer_id(idx), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + }; + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); } - ); - } - #[tokio::test] - async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); - let info_hash = sample_info_hash(); + assert_eq!(peers.len(), 74); + } + + #[tokio::test] + async fn it_should_return_the_peers_for_a_given_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - for idx in 1..=75 { - let peer = Peer { - peer_id: numeric_peer_id(idx), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - }; + let info_hash = sample_info_hash(); + let peer = sample_peer(); let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); + + assert_eq!(peers, vec![Arc::new(peer)]); } - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); + #[tokio::test] + async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - assert_eq!(peers.len(), 74); - } + let info_hash = sample_info_hash(); + let peer = sample_peer(); - #[tokio::test] - async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); - let info_hash = sample_info_hash(); - let peer = sample_peer(); + let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + assert_eq!(peers, vec![]); + } - let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); + #[tokio::test] + async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - assert_eq!(peers, vec![]); - } + let info_hash = sample_info_hash(); - #[tokio::test] - async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let excluded_peer = sample_peer(); - let info_hash = sample_info_hash(); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer); - let excluded_peer = sample_peer(); + // Add 74 peers + for idx in 2..=75 { + let peer = Peer { + peer_id: numeric_peer_id(idx), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + }; - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + } - // Add 74 peers - for idx in 2..=75 { - let peer = Peer { - peer_id: numeric_peer_id(idx), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - }; + let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + assert_eq!(peers.len(), 74); } + } - let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); - - assert_eq!(peers.len(), 74); + mod returning_torrent_entries { + // Methods: + // - get + // - get_paginated } - #[tokio::test] - async fn it_should_return_the_torrent_metrics() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + mod returning_torrent_metrics { + // Methods: + // - get_torrents_metrics - let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); + use std::sync::Arc; - let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; + use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; - assert_eq!( - torrent_metrics, - TorrentsMetrics { - complete: 0, - downloaded: 0, - incomplete: 1, - torrents: 1, - } - ); - } + use crate::core_tests::{leecher, sample_info_hash}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - #[tokio::test] - async fn it_should_get_many_the_torrent_metrics() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + #[tokio::test] + async fn it_should_collect_torrent_metrics() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let start_time = std::time::Instant::now(); - for i in 0..1_000_000 { - let () = in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher()); + let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + + assert_eq!( + torrents_metrics, + TorrentsMetrics { + complete: 0, + downloaded: 0, + incomplete: 0, + torrents: 0 + } + ); } - let result_a = start_time.elapsed(); - - let start_time = std::time::Instant::now(); - let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); - let result_b = start_time.elapsed(); - - assert_eq!( - (torrent_metrics), - (TorrentsMetrics { - complete: 0, - downloaded: 0, - incomplete: 1_000_000, - torrents: 1_000_000, - }), - "{result_a:?} {result_b:?}" - ); - } - #[tokio::test] - async fn it_should_return_the_peers_for_a_given_torrent() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + #[tokio::test] + async fn it_should_return_the_torrent_metrics() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); - let info_hash = sample_info_hash(); - let peer = sample_peer(); + let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + assert_eq!( + torrent_metrics, + TorrentsMetrics { + complete: 0, + downloaded: 0, + incomplete: 1, + torrents: 1, + } + ); + } + + #[tokio::test] + async fn it_should_get_many_the_torrent_metrics() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); + let start_time = std::time::Instant::now(); + for i in 0..1_000_000 { + let () = in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher()); + } + let result_a = start_time.elapsed(); + + let start_time = std::time::Instant::now(); + let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let result_b = start_time.elapsed(); + + assert_eq!( + (torrent_metrics), + (TorrentsMetrics { + complete: 0, + downloaded: 0, + incomplete: 1_000_000, + torrents: 1_000_000, + }), + "{result_a:?} {result_b:?}" + ); + } + } + + mod returning_swarm_metadata { + // Methods: + // - get_swarm_metadata + } - assert_eq!(peers, vec![Arc::new(peer)]); + mod handling_persistence { + // Methods: + // - import_persistent } } From f0481575a6ceb4bb43f828fa8e0283b65374280f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 5 Feb 2025 12:36:22 +0000 Subject: [PATCH 0721/1297] test: [#1240] add tests for InMemoryTorrentRepository --- packages/tracker-core/src/announce_handler.rs | 10 +- packages/tracker-core/src/core_tests.rs | 66 +- packages/tracker-core/src/torrent/mod.rs | 6 +- .../src/torrent/repository/in_memory.rs | 775 ++++++++++++++---- 4 files changed, 667 insertions(+), 190 deletions(-) diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index fac1df5b2..aa311fe46 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -82,17 +82,11 @@ impl AnnounceHandler { /// needed for a `announce` request response. #[must_use] fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { - let swarm_metadata_before = match self.in_memory_torrent_repository.get_opt_swarm_metadata(info_hash) { - Some(swarm_metadata) => swarm_metadata, - None => SwarmMetadata::zeroed(), - }; + let swarm_metadata_before = self.in_memory_torrent_repository.get_swarm_metadata(info_hash); self.in_memory_torrent_repository.upsert_peer(info_hash, peer); - let swarm_metadata_after = match self.in_memory_torrent_repository.get_opt_swarm_metadata(info_hash) { - Some(swarm_metadata) => swarm_metadata, - None => SwarmMetadata::zeroed(), - }; + let swarm_metadata_after = self.in_memory_torrent_repository.get_swarm_metadata(info_hash); if swarm_metadata_before != swarm_metadata_after { self.persist_stats(info_hash, &swarm_metadata_after); diff --git a/packages/tracker-core/src/core_tests.rs b/packages/tracker-core/src/core_tests.rs index ac99770d4..873c5f0ae 100644 --- a/packages/tracker-core/src/core_tests.rs +++ b/packages/tracker-core/src/core_tests.rs @@ -30,10 +30,74 @@ pub fn sample_info_hash() -> InfoHash { .expect("String should be a valid info hash") } +/// # Panics +/// +/// Will panic if the string representation of the info hash is not a valid info hash. +#[must_use] +pub fn sample_info_hash_one() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") +} + +/// # Panics +/// +/// Will panic if the string representation of the info hash is not a valid info hash. +#[must_use] +pub fn sample_info_hash_two() -> InfoHash { + "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") +} + +/// # Panics +/// +/// Will panic if the string representation of the info hash is not a valid info hash. +#[must_use] +pub fn sample_info_hash_alphabetically_ordered_after_sample_info_hash_one() -> InfoHash { + "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") +} + /// Sample peer whose state is not relevant for the tests. #[must_use] pub fn sample_peer() -> Peer { - complete_peer() + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } +} + +#[must_use] +pub fn sample_peer_one() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000001"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } +} + +#[must_use] +pub fn sample_peer_two() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000002"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8082), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } } #[must_use] diff --git a/packages/tracker-core/src/torrent/mod.rs b/packages/tracker-core/src/torrent/mod.rs index 2aa19130e..340f049d2 100644 --- a/packages/tracker-core/src/torrent/mod.rs +++ b/packages/tracker-core/src/torrent/mod.rs @@ -29,6 +29,8 @@ pub mod manager; pub mod repository; pub mod services; -use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; +use torrust_tracker_torrent_repository::{EntryMutexStd, TorrentsSkipMapMutexStd}; -pub type Torrents = TorrentsSkipMapMutexStd; // Currently Used +// Currently used types from the torrent repository crate. +pub type Torrents = TorrentsSkipMapMutexStd; +pub type TorrentEntry = EntryMutexStd; diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 7b8b941b4..baa0c4fdb 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -61,16 +61,10 @@ impl InMemoryTorrentRepository { pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { match self.torrents.get(info_hash) { Some(torrent_entry) => torrent_entry.get_swarm_metadata(), - None => SwarmMetadata::default(), + None => SwarmMetadata::zeroed(), } } - /// It returns the data for a `scrape` response if the torrent is found. - #[must_use] - pub fn get_opt_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.torrents.get_swarm_metadata(info_hash) - } - /// Get torrent peers for a given torrent and client. /// /// It filters out the client making the request. @@ -105,232 +99,655 @@ impl InMemoryTorrentRepository { #[cfg(test)] mod tests { - use aquatic_udp_protocol::PeerId; + mod the_in_memory_torrent_repository { - /// It generates a peer id from a number where the number is the last - /// part of the peer ID. For example, for `12` it returns - /// `-qB00000000000000012`. - fn numeric_peer_id(two_digits_value: i32) -> PeerId { - // Format idx as a string with leading zeros, ensuring it has exactly 2 digits - let idx_str = format!("{two_digits_value:02}"); + use aquatic_udp_protocol::PeerId; - // Create the base part of the peer ID. - let base = b"-qB00000000000000000"; + /// It generates a peer id from a number where the number is the last + /// part of the peer ID. For example, for `12` it returns + /// `-qB00000000000000012`. + fn numeric_peer_id(two_digits_value: i32) -> PeerId { + // Format idx as a string with leading zeros, ensuring it has exactly 2 digits + let idx_str = format!("{two_digits_value:02}"); - // Concatenate the base with idx bytes, ensuring the total length is 20 bytes. - let mut peer_id_bytes = [0u8; 20]; - peer_id_bytes[..base.len()].copy_from_slice(base); - peer_id_bytes[base.len() - idx_str.len()..].copy_from_slice(idx_str.as_bytes()); + // Create the base part of the peer ID. + let base = b"-qB00000000000000000"; - PeerId(peer_id_bytes) - } + // Concatenate the base with idx bytes, ensuring the total length is 20 bytes. + let mut peer_id_bytes = [0u8; 20]; + peer_id_bytes[..base.len()].copy_from_slice(base); + peer_id_bytes[base.len() - idx_str.len()..].copy_from_slice(idx_str.as_bytes()); - // The `InMemoryTorrentRepository` has these responsibilities: - // - To maintain the peer lists for each torrent. - // - To return the peer lists for a given torrent. - // - To return the torrent entries, which contains all the info about the - // torrents, including the peer lists. - // - To return the torrent metrics. - // - To return the swarm metadata for a given torrent. - // - To handle the persistence of the torrent entries. - - mod maintaining_the_peer_lists { - // Methods: - // - upsert_peer - // - remove - // - remove_inactive_peers - // - remove_peerless_torrents - } + PeerId(peer_id_bytes) + } - mod returning_peer_lists_for_a_torrent { - // Methods: - // - get_peers_for - // - get_torrent_peers - - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; - - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; - use torrust_tracker_primitives::peer::Peer; - use torrust_tracker_primitives::DurationSinceUnixEpoch; - - use crate::core_tests::{sample_info_hash, sample_peer}; - use crate::torrent::repository::in_memory::tests::numeric_peer_id; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - - #[tokio::test] - async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let info_hash = sample_info_hash(); - - for idx in 1..=75 { - let peer = Peer { - peer_id: numeric_peer_id(idx), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - }; + // The `InMemoryTorrentRepository` has these responsibilities: + // - To maintain the peer lists for each torrent. + // - To maintain the the torrent entries, which contains all the info about the + // torrents, including the peer lists. + // - To return the torrent entries. + // - To return the peer lists for a given torrent. + // - To return the torrent metrics. + // - To return the swarm metadata for a given torrent. + // - To handle the persistence of the torrent entries. - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + mod maintaining_the_peer_lists { + + use std::sync::Arc; + + use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + + #[tokio::test] + async fn it_should_add_the_first_peer_to_the_torrent_peer_list() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + + assert!(in_memory_torrent_repository.get(&info_hash).is_some()); } - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); + #[tokio::test] + async fn it_should_allow_adding_the_same_peer_twice_to_the_torrent_peer_list() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - assert_eq!(peers.len(), 74); + let info_hash = sample_info_hash(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + + assert!(in_memory_torrent_repository.get(&info_hash).is_some()); + } } - #[tokio::test] - async fn it_should_return_the_peers_for_a_given_torrent() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + mod returning_peer_lists_for_a_torrent { - let info_hash = sample_info_hash(); - let peer = sample_peer(); + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); + use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::torrent::repository::in_memory::tests::the_in_memory_torrent_repository::numeric_peer_id; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - assert_eq!(peers, vec![Arc::new(peer)]); - } + #[tokio::test] + async fn it_should_return_the_peers_for_a_given_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - #[tokio::test] - async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); + + assert_eq!(peers, vec![Arc::new(peer)]); + } + + #[tokio::test] + async fn it_should_return_an_empty_list_or_peers_for_a_non_existing_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let peers = in_memory_torrent_repository.get_torrent_peers(&sample_info_hash()); + + assert!(peers.is_empty()); + } + + #[tokio::test] + async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + + for idx in 1..=75 { + let peer = Peer { + peer_id: numeric_peer_id(idx), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + }; + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + } + + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); + + assert_eq!(peers.len(), 74); + } - let info_hash = sample_info_hash(); - let peer = sample_peer(); + mod excluding_the_client_peer { - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; - let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; - assert_eq!(peers, vec![]); + use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::torrent::repository::in_memory::tests::the_in_memory_torrent_repository::numeric_peer_id; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + + #[tokio::test] + async fn it_should_return_an_empty_peer_list_for_a_non_existing_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let peers = + in_memory_torrent_repository.get_peers_for(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT); + + assert_eq!(peers, vec![]); + } + + #[tokio::test] + async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + + let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); + + assert_eq!(peers, vec![]); + } + + #[tokio::test] + async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + + let excluded_peer = sample_peer(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer); + + // Add 74 peers + for idx in 2..=75 { + let peer = Peer { + peer_id: numeric_peer_id(idx), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + }; + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + } + + let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); + + assert_eq!(peers.len(), 74); + } + } } - #[tokio::test] - async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + mod maintaining_the_torrent_entries { - let info_hash = sample_info_hash(); + use std::ops::Add; + use std::sync::Arc; + use std::time::Duration; - let excluded_peer = sample_peer(); + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_configuration::TrackerPolicy; + use torrust_tracker_primitives::DurationSinceUnixEpoch; - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer); + use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - // Add 74 peers - for idx in 2..=75 { - let peer = Peer { - peer_id: numeric_peer_id(idx), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - }; + #[tokio::test] + async fn it_should_remove_a_torrent_entry() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + + let _unused = in_memory_torrent_repository.remove(&info_hash); + + assert!(in_memory_torrent_repository.get(&info_hash).is_none()); + } + + #[tokio::test] + async fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + let mut peer = sample_peer(); + peer.updated = DurationSinceUnixEpoch::new(0, 0); let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + + // Cut off time is 1 second after the peer was updated + in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); + + assert!(!in_memory_torrent_repository + .get_torrent_peers(&info_hash) + .contains(&Arc::new(peer))); + } + + fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + // Insert a sample peer for the torrent to force adding the torrent entry + let mut peer = sample_peer(); + peer.updated = DurationSinceUnixEpoch::new(0, 0); + let () = in_memory_torrent_repository.upsert_peer(info_hash, &peer); + + // Remove the peer + in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); + + in_memory_torrent_repository } - let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); + #[tokio::test] + async fn it_should_remove_torrents_without_peers() { + let info_hash = sample_info_hash(); - assert_eq!(peers.len(), 74); + let in_memory_torrent_repository = initialize_repository_with_one_torrent_without_peers(&info_hash); + + let tracker_policy = TrackerPolicy { + remove_peerless_torrents: true, + ..Default::default() + }; + + in_memory_torrent_repository.remove_peerless_torrents(&tracker_policy); + + assert!(in_memory_torrent_repository.get(&info_hash).is_none()); + } } - } + mod returning_torrent_entries { + + use std::sync::Arc; + + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use torrust_tracker_torrent_repository::entry::EntrySync; + + use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::torrent::TorrentEntry; + + /// `TorrentEntry` data is not directly accessible. It's only + /// accessible through the trait methods. We need this temporary + /// DTO to write simple and more readable assertions. + #[derive(Debug, Clone, PartialEq)] + struct TorrentEntryInfo { + swarm_metadata: SwarmMetadata, + peers: Vec, + number_of_peers: usize, + } - mod returning_torrent_entries { - // Methods: - // - get - // - get_paginated - } + #[allow(clippy::from_over_into)] + impl Into for TorrentEntry { + fn into(self) -> TorrentEntryInfo { + TorrentEntryInfo { + swarm_metadata: self.get_swarm_metadata(), + peers: self.get_peers(None).iter().map(|peer| *peer.clone()).collect(), + number_of_peers: self.get_peers_len(), + } + } + } + + #[tokio::test] + async fn it_should_return_one_torrent_entry_by_infohash() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + + let torrent_entry = in_memory_torrent_repository.get(&info_hash).unwrap(); + + assert_eq!( + TorrentEntryInfo { + swarm_metadata: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + peers: vec!(peer), + number_of_peers: 1 + }, + torrent_entry.into() + ); + } + + mod it_should_return_many_torrent_entries { + use std::sync::Arc; - mod returning_torrent_metrics { - // Methods: - // - get_torrents_metrics + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use std::sync::Arc; + use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::torrent::repository::in_memory::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; - use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + #[tokio::test] + async fn without_pagination() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - use crate::core_tests::{leecher, sample_info_hash}; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + let info_hash = sample_info_hash(); + let peer = sample_peer(); + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); - #[tokio::test] - async fn it_should_collect_torrent_metrics() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let torrent_entries = in_memory_torrent_repository.get_paginated(None); - let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + assert_eq!(torrent_entries.len(), 1); - assert_eq!( - torrents_metrics, - TorrentsMetrics { - complete: 0, - downloaded: 0, - incomplete: 0, - torrents: 0 + let torrent_entry = torrent_entries.first().unwrap().1.clone(); + + assert_eq!( + TorrentEntryInfo { + swarm_metadata: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + peers: vec!(peer), + number_of_peers: 1 + }, + torrent_entry.into() + ); + } + + mod with_pagination { + use std::sync::Arc; + + use torrust_tracker_primitives::pagination::Pagination; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::core_tests::{ + sample_info_hash_alphabetically_ordered_after_sample_info_hash_one, sample_info_hash_one, + sample_peer_one, sample_peer_two, + }; + use crate::torrent::repository::in_memory::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + + #[tokio::test] + async fn it_should_return_the_first_page() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + // Insert one torrent entry + let info_hash_one = sample_info_hash_one(); + let peer_one = sample_peer_one(); + let () = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); + + // Insert another torrent entry + let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); + let peer_two = sample_peer_two(); + let () = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); + + // Get only the first page where page size is 1 + let torrent_entries = + in_memory_torrent_repository.get_paginated(Some(&Pagination { offset: 0, limit: 1 })); + + assert_eq!(torrent_entries.len(), 1); + + let torrent_entry = torrent_entries.first().unwrap().1.clone(); + + assert_eq!( + TorrentEntryInfo { + swarm_metadata: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + peers: vec!(peer_one), + number_of_peers: 1 + }, + torrent_entry.into() + ); + } + + #[tokio::test] + async fn it_should_return_the_second_page() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + // Insert one torrent entry + let info_hash_one = sample_info_hash_one(); + let peer_one = sample_peer_one(); + let () = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); + + // Insert another torrent entry + let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); + let peer_two = sample_peer_two(); + let () = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); + + // Get only the first page where page size is 1 + let torrent_entries = + in_memory_torrent_repository.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); + + assert_eq!(torrent_entries.len(), 1); + + let torrent_entry = torrent_entries.first().unwrap().1.clone(); + + assert_eq!( + TorrentEntryInfo { + swarm_metadata: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + peers: vec!(peer_two), + number_of_peers: 1 + }, + torrent_entry.into() + ); + } + + #[tokio::test] + async fn it_should_allow_changing_the_page_size() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + // Insert one torrent entry + let info_hash_one = sample_info_hash_one(); + let peer_one = sample_peer_one(); + let () = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); + + // Insert another torrent entry + let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); + let peer_two = sample_peer_two(); + let () = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); + + // Get only the first page where page size is 1 + let torrent_entries = + in_memory_torrent_repository.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); + + assert_eq!(torrent_entries.len(), 1); + } } - ); + } } - #[tokio::test] - async fn it_should_return_the_torrent_metrics() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + mod returning_torrent_metrics { + + use std::sync::Arc; + + use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; + use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + + use crate::core_tests::{complete_peer, leecher, sample_info_hash, seeder}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + + // todo: refactor to use test parametrization + + #[tokio::test] + async fn it_should_get_empty_torrent_metrics_when_there_are_no_torrents() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + + assert_eq!( + torrents_metrics, + TorrentsMetrics { + complete: 0, + downloaded: 0, + incomplete: 0, + torrents: 0 + } + ); + } + + #[tokio::test] + async fn it_should_return_the_torrent_metrics_when_there_is_a_leecher() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); + + let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + + assert_eq!( + torrent_metrics, + TorrentsMetrics { + complete: 0, + downloaded: 0, + incomplete: 1, + torrents: 1, + } + ); + } + + #[tokio::test] + async fn it_should_return_the_torrent_metrics_when_there_is_a_seeder() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &seeder()); + + let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + + assert_eq!( + torrent_metrics, + TorrentsMetrics { + complete: 1, + downloaded: 0, + incomplete: 0, + torrents: 1, + } + ); + } - let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); + #[tokio::test] + async fn it_should_return_the_torrent_metrics_when_there_is_a_completed_peer() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer()); + + let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + + assert_eq!( + torrent_metrics, + TorrentsMetrics { + complete: 1, + downloaded: 0, + incomplete: 0, + torrents: 1, + } + ); + } - let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + #[tokio::test] + async fn it_should_return_the_torrent_metrics_when_there_are_multiple_torrents() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - assert_eq!( - torrent_metrics, - TorrentsMetrics { - complete: 0, - downloaded: 0, - incomplete: 1, - torrents: 1, + let start_time = std::time::Instant::now(); + for i in 0..1_000_000 { + let () = in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher()); } - ); + let result_a = start_time.elapsed(); + + let start_time = std::time::Instant::now(); + let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let result_b = start_time.elapsed(); + + assert_eq!( + (torrent_metrics), + (TorrentsMetrics { + complete: 0, + downloaded: 0, + incomplete: 1_000_000, + torrents: 1_000_000, + }), + "{result_a:?} {result_b:?}" + ); + } } - #[tokio::test] - async fn it_should_get_many_the_torrent_metrics() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + mod returning_swarm_metadata { + + use std::sync::Arc; + + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::core_tests::{leecher, sample_info_hash}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + + #[tokio::test] + async fn it_should_get_swarm_metadata_for_an_existing_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let infohash = sample_info_hash(); + + let () = in_memory_torrent_repository.upsert_peer(&infohash, &leecher()); + + let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata(&infohash); - let start_time = std::time::Instant::now(); - for i in 0..1_000_000 { - let () = in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher()); + assert_eq!( + swarm_metadata, + SwarmMetadata { + complete: 0, + downloaded: 0, + incomplete: 1, + } + ); + } + + #[tokio::test] + async fn it_should_return_zeroed_swarm_metadata_for_a_non_existing_torrent() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata(&sample_info_hash()); + + assert_eq!(swarm_metadata, SwarmMetadata::zeroed()); } - let result_a = start_time.elapsed(); - - let start_time = std::time::Instant::now(); - let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); - let result_b = start_time.elapsed(); - - assert_eq!( - (torrent_metrics), - (TorrentsMetrics { - complete: 0, - downloaded: 0, - incomplete: 1_000_000, - torrents: 1_000_000, - }), - "{result_a:?} {result_b:?}" - ); } - } - mod returning_swarm_metadata { - // Methods: - // - get_swarm_metadata - } + mod handling_persistence { + + use std::sync::Arc; + + use torrust_tracker_primitives::PersistentTorrents; + + use crate::core_tests::sample_info_hash; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - mod handling_persistence { - // Methods: - // - import_persistent + #[tokio::test] + async fn it_should_allow_importing_persisted_torrent_entries() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let infohash = sample_info_hash(); + + let mut persistent_torrents = PersistentTorrents::default(); + + persistent_torrents.insert(infohash, 1); + + in_memory_torrent_repository.import_persistent(&persistent_torrents); + + let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata(&infohash); + + // Only the number of downloads is persisted. + assert_eq!(swarm_metadata.downloaded, 1); + } + } } } From 6a15e069c11dc13650250f3384d18cd4369554c7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 08:02:29 +0000 Subject: [PATCH 0722/1297] test: [#1240] add tests for DatabasePersistentTorrentRepository --- packages/primitives/src/lib.rs | 3 +- packages/tracker-core/src/core_tests.rs | 16 ++++++- .../src/torrent/repository/persisted.rs | 48 +++++++++++++++++++ 3 files changed, 65 insertions(+), 2 deletions(-) diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index 55f90ef20..ec9732778 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -18,4 +18,5 @@ use bittorrent_primitives::info_hash::InfoHash; /// Duration since the Unix Epoch. pub type DurationSinceUnixEpoch = Duration; -pub type PersistentTorrents = BTreeMap; +pub type PersistentTorrent = u32; +pub type PersistentTorrents = BTreeMap; diff --git a/packages/tracker-core/src/core_tests.rs b/packages/tracker-core/src/core_tests.rs index 873c5f0ae..53049f326 100644 --- a/packages/tracker-core/src/core_tests.rs +++ b/packages/tracker-core/src/core_tests.rs @@ -174,7 +174,21 @@ pub fn initialize_handlers(config: &Configuration) -> (Arc, Arc /// # Panics /// -/// Will panic if the temporary file path is not a valid UFT string. +/// Will panic if the temporary database file path is not a valid UFT string. +#[cfg(test)] +#[must_use] +pub fn ephemeral_configuration() -> Core { + let mut config = Core::default(); + + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + + config +} + +/// # Panics +/// +/// Will panic if the temporary database file path is not a valid UFT string. #[cfg(test)] #[must_use] pub fn ephemeral_configuration_for_listed_tracker() -> Core { diff --git a/packages/tracker-core/src/torrent/repository/persisted.rs b/packages/tracker-core/src/torrent/repository/persisted.rs index 77a9c23eb..224919d0e 100644 --- a/packages/tracker-core/src/torrent/repository/persisted.rs +++ b/packages/tracker-core/src/torrent/repository/persisted.rs @@ -42,3 +42,51 @@ impl DatabasePersistentTorrentRepository { self.database.save_persistent_torrent(info_hash, downloaded) } } + +#[cfg(test)] +mod tests { + + use torrust_tracker_primitives::PersistentTorrents; + + use super::DatabasePersistentTorrentRepository; + use crate::core_tests::{ephemeral_configuration, sample_info_hash, sample_info_hash_one, sample_info_hash_two}; + use crate::databases::setup::initialize_database; + + fn initialize_db_persistent_torrent_repository() -> DatabasePersistentTorrentRepository { + let config = ephemeral_configuration(); + let database = initialize_database(&config); + DatabasePersistentTorrentRepository::new(&database) + } + + #[test] + fn it_saves_the_numbers_of_downloads_for_a_torrent_into_the_database() { + let repository = initialize_db_persistent_torrent_repository(); + + let infohash = sample_info_hash(); + + repository.save(&infohash, 1).unwrap(); + + let torrents = repository.load_all().unwrap(); + + assert_eq!(torrents.get(&infohash), Some(1).as_ref()); + } + + #[test] + fn it_loads_the_numbers_of_downloads_for_all_torrents_from_the_database() { + let repository = initialize_db_persistent_torrent_repository(); + + let infohash_one = sample_info_hash_one(); + let infohash_two = sample_info_hash_two(); + + repository.save(&infohash_one, 1).unwrap(); + repository.save(&infohash_two, 2).unwrap(); + + let torrents = repository.load_all().unwrap(); + + let mut expected_torrents = PersistentTorrents::new(); + expected_torrents.insert(infohash_one, 1); + expected_torrents.insert(infohash_two, 2); + + assert_eq!(torrents, expected_torrents); + } +} From 0d0c601f08be8b3b4415771d32fca94d49dd5d38 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 08:13:51 +0000 Subject: [PATCH 0723/1297] test: [#1240] add tests for TorrentsManager --- packages/tracker-core/src/torrent/manager.rs | 148 +++++++++++++++++++ 1 file changed, 148 insertions(+) diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index 4199e9944..778ac6d92 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -61,3 +61,151 @@ impl TorrentsManager { } } } + +#[cfg(test)] +mod tests { + + use std::sync::Arc; + + use torrust_tracker_configuration::Core; + use torrust_tracker_torrent_repository::entry::EntrySync; + + use super::{DatabasePersistentTorrentRepository, TorrentsManager}; + use crate::core_tests::{ephemeral_configuration, sample_info_hash}; + use crate::databases::setup::initialize_database; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + + struct TorrentsManagerDeps { + config: Arc, + in_memory_torrent_repository: Arc, + database_persistent_torrent_repository: Arc, + } + + fn initialize_torrents_manager() -> (Arc, Arc) { + let config = ephemeral_configuration(); + initialize_torrents_manager_with(config.clone()) + } + + fn initialize_torrents_manager_with(config: Core) -> (Arc, Arc) { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let database = initialize_database(&config); + let database_persistent_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let torrents_manager = Arc::new(TorrentsManager::new( + &config, + &in_memory_torrent_repository, + &database_persistent_torrent_repository, + )); + + ( + torrents_manager, + Arc::new(TorrentsManagerDeps { + config: Arc::new(config), + in_memory_torrent_repository, + database_persistent_torrent_repository, + }), + ) + } + + #[test] + fn it_should_load_the_numbers_of_downloads_for_all_torrents_from_the_database() { + let (torrents_manager, services) = initialize_torrents_manager(); + + let infohash = sample_info_hash(); + + services.database_persistent_torrent_repository.save(&infohash, 1).unwrap(); + + torrents_manager.load_torrents_from_database().unwrap(); + + assert_eq!( + services + .in_memory_torrent_repository + .get(&infohash) + .unwrap() + .get_swarm_metadata() + .downloaded, + 1 + ); + } + + mod cleaning_torrents { + use std::ops::Add; + use std::sync::Arc; + use std::time::Duration; + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self}; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::core_tests::{ephemeral_configuration, sample_info_hash, sample_peer}; + use crate::torrent::manager::tests::{initialize_torrents_manager, initialize_torrents_manager_with}; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + + #[test] + fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { + let (torrents_manager, services) = initialize_torrents_manager(); + + let infohash = sample_info_hash(); + + clock::Stopped::local_set(&Duration::from_secs(0)); + + // Add a peer to the torrent + let mut peer = sample_peer(); + peer.updated = DurationSinceUnixEpoch::new(0, 0); + let () = services.in_memory_torrent_repository.upsert_peer(&infohash, &peer); + + // Simulate the time has passed 1 second more than the max peer timeout. + clock::Stopped::local_add(&Duration::from_secs( + (services.config.tracker_policy.max_peer_timeout + 1).into(), + )) + .unwrap(); + + torrents_manager.cleanup_torrents(); + + assert!(services.in_memory_torrent_repository.get(&infohash).is_none()); + } + + fn add_a_peerless_torrent(infohash: &InfoHash, in_memory_torrent_repository: &Arc) { + // Add a peer to the torrent + let mut peer = sample_peer(); + peer.updated = DurationSinceUnixEpoch::new(0, 0); + let () = in_memory_torrent_repository.upsert_peer(infohash, &peer); + + // Remove the peer. The torrent is now peerless. + in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); + } + + #[test] + fn it_should_remove_torrents_that_have_no_peers_when_it_is_configured_to_do_so() { + let mut config = ephemeral_configuration(); + config.tracker_policy.remove_peerless_torrents = true; + + let (torrents_manager, services) = initialize_torrents_manager_with(config); + + let infohash = sample_info_hash(); + + add_a_peerless_torrent(&infohash, &services.in_memory_torrent_repository); + + torrents_manager.cleanup_torrents(); + + assert!(services.in_memory_torrent_repository.get(&infohash).is_none()); + } + + #[test] + fn it_should_retain_peerless_torrents_when_it_is_configured_to_do_so() { + let mut config = ephemeral_configuration(); + config.tracker_policy.remove_peerless_torrents = false; + + let (torrents_manager, services) = initialize_torrents_manager_with(config); + + let infohash = sample_info_hash(); + + add_a_peerless_torrent(&infohash, &services.in_memory_torrent_repository); + + torrents_manager.cleanup_torrents(); + + assert!(services.in_memory_torrent_repository.get(&infohash).is_some()); + } + } +} From ef879541a34f450cdda5d448c0aad6b743eb49ab Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 08:50:05 +0000 Subject: [PATCH 0724/1297] refactor: minor changes --- packages/tracker-core/src/torrent/services.rs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index 2275f20d0..ea3966f6d 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -137,7 +137,7 @@ mod tests { use crate::torrent::services::{get_torrent_info, Info}; #[tokio::test] - async fn should_return_none_if_the_tracker_does_not_have_the_torrent() { + async fn it_should_return_none_if_the_tracker_does_not_have_the_torrent() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let torrent_info = get_torrent_info( @@ -149,7 +149,7 @@ mod tests { } #[tokio::test] - async fn should_return_the_torrent_info_if_the_tracker_has_the_torrent() { + async fn it_should_return_the_torrent_info_if_the_tracker_has_the_torrent() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 @@ -183,7 +183,7 @@ mod tests { use crate::torrent::services::{get_torrents_page, BasicInfo, Pagination}; #[tokio::test] - async fn should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { + async fn it_should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); @@ -192,7 +192,7 @@ mod tests { } #[tokio::test] - async fn should_return_a_summarized_info_for_all_torrents() { + async fn it_should_return_a_summarized_info_for_all_torrents() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 @@ -214,13 +214,13 @@ mod tests { } #[tokio::test] - async fn should_allow_limiting_the_number_of_torrents_in_the_result() { + async fn it_should_allow_limiting_the_number_of_torrents_in_the_result() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); + let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); let () = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); @@ -235,13 +235,13 @@ mod tests { } #[tokio::test] - async fn should_allow_using_pagination_in_the_result() { + async fn it_should_allow_using_pagination_in_the_result() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); + let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); let () = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); @@ -265,14 +265,14 @@ mod tests { } #[tokio::test] - async fn should_return_torrents_ordered_by_info_hash() { + async fn it_should_return_torrents_ordered_by_info_hash() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash1 = InfoHash::from_str(&hash1).unwrap(); let () = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); - let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); + let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); let () = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); From 21c865dca26b96e594a8fb1fade624bc1a58c600 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 09:11:20 +0000 Subject: [PATCH 0725/1297] test: [#1240] add tests for bittorrent_tracker_core::torrent::services --- packages/tracker-core/src/torrent/services.rs | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index ea3966f6d..c36190ed1 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -297,4 +297,44 @@ mod tests { ); } } + + mod getting_basic_torrent_info_for_multiple_torrents_at_once { + + use std::sync::Arc; + + use crate::core_tests::sample_info_hash; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::torrent::services::tests::sample_peer; + use crate::torrent::services::{get_torrents, BasicInfo}; + + #[tokio::test] + async fn it_should_return_an_empty_list_if_none_of_the_requested_torrents_is_found() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let torrent_info = get_torrents(&in_memory_torrent_repository, &[sample_info_hash()]); + + assert!(torrent_info.is_empty()); + } + + #[tokio::test] + async fn it_should_return_a_list_with_basic_info_about_the_requested_torrents() { + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let info_hash = sample_info_hash(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + + let torrent_info = get_torrents(&in_memory_torrent_repository, &[info_hash]); + + assert_eq!( + torrent_info, + vec!(BasicInfo { + info_hash, + seeders: 1, + completed: 0, + leechers: 0, + }) + ); + } + } } From b2fc66331a67d59754db700968bfd76457109135 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 10:03:30 +0000 Subject: [PATCH 0726/1297] test: [#1247] add tests for bittorrent_tracker_core::announce_handler --- packages/tracker-core/src/announce_handler.rs | 174 ++++++++++++++++-- 1 file changed, 160 insertions(+), 14 deletions(-) diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index aa311fe46..5dd4a0291 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -119,12 +119,7 @@ pub enum PeersWanted { impl PeersWanted { #[must_use] pub fn only(limit: u32) -> Self { - let amount: usize = match limit.try_into() { - Ok(amount) => amount, - Err(_) => TORRENT_PEERS_LIMIT, - }; - - Self::Only { amount } + limit.into() } fn limit(&self) -> usize { @@ -137,13 +132,29 @@ impl PeersWanted { impl From for PeersWanted { fn from(value: i32) -> Self { - if value > 0 { - match value.try_into() { - Ok(peers_wanted) => Self::Only { amount: peers_wanted }, - Err(_) => Self::All, - } - } else { - Self::All + if value <= 0 { + return PeersWanted::All; + } + + // This conversion is safe because `value > 0` + let amount = usize::try_from(value).unwrap(); + + PeersWanted::Only { + amount: amount.min(TORRENT_PEERS_LIMIT), + } + } +} + +impl From for PeersWanted { + fn from(value: u32) -> Self { + if value == 0 { + return PeersWanted::All; + } + + let amount = value as usize; + + PeersWanted::Only { + amount: amount.min(TORRENT_PEERS_LIMIT), } } } @@ -210,6 +221,19 @@ mod tests { } } + /// Sample peer when for tests that need more than two peer + fn sample_peer_3() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000003"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 3)), 8082), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Completed, + } + } + mod for_all_tracker_config_modes { mod handling_an_announce_request { @@ -217,7 +241,7 @@ mod tests { use std::sync::Arc; use crate::announce_handler::tests::the_announce_handler::{ - peer_ip, public_tracker, sample_peer_1, sample_peer_2, + peer_ip, public_tracker, sample_peer_1, sample_peer_2, sample_peer_3, }; use crate::announce_handler::PeersWanted; use crate::core_tests::{sample_info_hash, sample_peer}; @@ -349,6 +373,38 @@ mod tests { assert_eq!(announce_data.peers, vec![Arc::new(previously_announced_peer)]); } + #[tokio::test] + async fn it_should_allow_peers_to_get_only_a_subset_of_the_peers_in_the_swarm() { + let (announce_handler, _scrape_handler) = public_tracker(); + + let mut previously_announced_peer_1 = sample_peer_1(); + announce_handler.announce( + &sample_info_hash(), + &mut previously_announced_peer_1, + &peer_ip(), + &PeersWanted::All, + ); + + let mut previously_announced_peer_2 = sample_peer_2(); + announce_handler.announce( + &sample_info_hash(), + &mut previously_announced_peer_2, + &peer_ip(), + &PeersWanted::All, + ); + + let mut peer = sample_peer_3(); + let announce_data = + announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::only(1)); + + // It should return only one peer. There is no guarantee on + // which peer will be returned. + assert!( + announce_data.peers == vec![Arc::new(previously_announced_peer_1)] + || announce_data.peers == vec![Arc::new(previously_announced_peer_2)] + ); + } + mod it_should_update_the_swarm_stats_for_the_torrent { use crate::announce_handler::tests::the_announce_handler::{peer_ip, public_tracker}; @@ -461,5 +517,95 @@ mod tests { assert!(torrent_entry.peers_is_empty()); } } + + mod should_allow_the_client_peers_to_specified_the_number_of_peers_wanted { + + use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; + + use crate::announce_handler::PeersWanted; + + #[test] + fn it_should_return_the_maximin_number_of_peers_by_default() { + let peers_wanted = PeersWanted::default(); + + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + } + + #[test] + fn it_should_return_74_at_the_most_if_the_client_wants_them_all() { + let peers_wanted = PeersWanted::All; + + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + } + + #[test] + fn it_should_allow_limiting_the_peer_list() { + let peers_wanted = PeersWanted::only(10); + + assert_eq!(peers_wanted.limit(), 10); + } + + fn maximum_as_u32() -> u32 { + u32::try_from(TORRENT_PEERS_LIMIT).unwrap() + } + + fn maximum_as_i32() -> i32 { + i32::try_from(TORRENT_PEERS_LIMIT).unwrap() + } + + #[test] + fn it_should_return_the_maximum_when_wanting_more_than_the_maximum() { + let peers_wanted = PeersWanted::only(maximum_as_u32() + 1); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + } + + #[test] + fn it_should_return_the_maximum_when_wanting_only_zero() { + let peers_wanted = PeersWanted::only(0); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + } + + #[test] + fn it_should_convert_the_peers_wanted_number_from_i32() { + // Negative. It should return the maximum + let peers_wanted: PeersWanted = (-1i32).into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // Zero. It should return the maximum + let peers_wanted: PeersWanted = 0i32.into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // Greater than the maximum. It should return the maximum + let peers_wanted: PeersWanted = (maximum_as_i32() + 1).into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // The maximum + let peers_wanted: PeersWanted = (maximum_as_i32()).into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // Smaller than the maximum + let peers_wanted: PeersWanted = (maximum_as_i32() - 1).into(); + assert_eq!(i32::try_from(peers_wanted.limit()).unwrap(), maximum_as_i32() - 1); + } + + #[test] + fn it_should_convert_the_peers_wanted_number_from_u32() { + // Zero. It should return the maximum + let peers_wanted: PeersWanted = 0u32.into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // Greater than the maximum. It should return the maximum + let peers_wanted: PeersWanted = (maximum_as_u32() + 1).into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // The maximum + let peers_wanted: PeersWanted = (maximum_as_u32()).into(); + assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); + + // Smaller than the maximum + let peers_wanted: PeersWanted = (maximum_as_u32() - 1).into(); + assert_eq!(i32::try_from(peers_wanted.limit()).unwrap(), maximum_as_i32() - 1); + } + } } } From 5fdee789a5aacdcdbfad2b2b9a5ef58919c5eaa8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 11:05:45 +0000 Subject: [PATCH 0727/1297] refactor: rename enum variant --- packages/tracker-core/src/announce_handler.rs | 45 ++++++++++++------- packages/tracker-core/src/lib.rs | 8 ++-- src/servers/http/v1/handlers/announce.rs | 2 +- src/servers/http/v1/services/announce.rs | 8 ++-- src/servers/http/v1/services/scrape.rs | 4 +- 5 files changed, 39 insertions(+), 28 deletions(-) diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 5dd4a0291..85dd354bf 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -111,7 +111,7 @@ impl AnnounceHandler { pub enum PeersWanted { /// The peer wants as many peers as possible in the announce response. #[default] - All, + AsManyAsPossible, /// The peer only wants a certain amount of peers in the announce response. Only { amount: usize }, } @@ -124,7 +124,7 @@ impl PeersWanted { fn limit(&self) -> usize { match self { - PeersWanted::All => TORRENT_PEERS_LIMIT, + PeersWanted::AsManyAsPossible => TORRENT_PEERS_LIMIT, PeersWanted::Only { amount } => *amount, } } @@ -133,7 +133,7 @@ impl PeersWanted { impl From for PeersWanted { fn from(value: i32) -> Self { if value <= 0 { - return PeersWanted::All; + return PeersWanted::AsManyAsPossible; } // This conversion is safe because `value > 0` @@ -148,7 +148,7 @@ impl From for PeersWanted { impl From for PeersWanted { fn from(value: u32) -> Self { if value == 0 { - return PeersWanted::All; + return PeersWanted::AsManyAsPossible; } let amount = value as usize; @@ -350,7 +350,8 @@ mod tests { let mut peer = sample_peer(); - let announce_data = announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); + let announce_data = + announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); assert_eq!(announce_data.peers, vec![]); } @@ -364,11 +365,12 @@ mod tests { &sample_info_hash(), &mut previously_announced_peer, &peer_ip(), - &PeersWanted::All, + &PeersWanted::AsManyAsPossible, ); let mut peer = sample_peer_2(); - let announce_data = announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); + let announce_data = + announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); assert_eq!(announce_data.peers, vec![Arc::new(previously_announced_peer)]); } @@ -382,7 +384,7 @@ mod tests { &sample_info_hash(), &mut previously_announced_peer_1, &peer_ip(), - &PeersWanted::All, + &PeersWanted::AsManyAsPossible, ); let mut previously_announced_peer_2 = sample_peer_2(); @@ -390,7 +392,7 @@ mod tests { &sample_info_hash(), &mut previously_announced_peer_2, &peer_ip(), - &PeersWanted::All, + &PeersWanted::AsManyAsPossible, ); let mut peer = sample_peer_3(); @@ -418,7 +420,7 @@ mod tests { let mut peer = seeder(); let announce_data = - announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); + announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); assert_eq!(announce_data.stats.complete, 1); } @@ -430,7 +432,7 @@ mod tests { let mut peer = leecher(); let announce_data = - announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::All); + announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); assert_eq!(announce_data.stats.incomplete, 1); } @@ -441,11 +443,20 @@ mod tests { // We have to announce with "started" event because peer does not count if peer was not previously known let mut started_peer = started_peer(); - announce_handler.announce(&sample_info_hash(), &mut started_peer, &peer_ip(), &PeersWanted::All); + announce_handler.announce( + &sample_info_hash(), + &mut started_peer, + &peer_ip(), + &PeersWanted::AsManyAsPossible, + ); let mut completed_peer = completed_peer(); - let announce_data = - announce_handler.announce(&sample_info_hash(), &mut completed_peer, &peer_ip(), &PeersWanted::All); + let announce_data = announce_handler.announce( + &sample_info_hash(), + &mut completed_peer, + &peer_ip(), + &PeersWanted::AsManyAsPossible, + ); assert_eq!(announce_data.stats.downloaded, 1); } @@ -494,11 +505,11 @@ mod tests { let mut peer = sample_peer(); peer.event = AnnounceEvent::Started; - let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); assert_eq!(announce_data.stats.downloaded, 0); peer.event = AnnounceEvent::Completed; - let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); assert_eq!(announce_data.stats.downloaded, 1); // Remove the newly updated torrent from memory @@ -533,7 +544,7 @@ mod tests { #[test] fn it_should_return_74_at_the_most_if_the_client_wants_them_all() { - let peers_wanted = PeersWanted::All; + let peers_wanted = PeersWanted::AsManyAsPossible; assert_eq!(peers_wanted.limit(), TORRENT_PEERS_LIMIT); } diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index 68bc48552..9334e4a02 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -460,7 +460,7 @@ mod tests { &info_hash, &mut complete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10)), - &PeersWanted::All, + &PeersWanted::AsManyAsPossible, ); // Announce an "incomplete" peer for the torrent @@ -469,7 +469,7 @@ mod tests { &info_hash, &mut incomplete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11)), - &PeersWanted::All, + &PeersWanted::AsManyAsPossible, ); // Scrape @@ -510,11 +510,11 @@ mod tests { let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237 let mut peer = incomplete_peer(); - announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); // Announce twice to force non zeroed swarm metadata let mut peer = complete_peer(); - announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::All); + announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); let scrape_data = scrape_handler.scrape(&vec![info_hash]).await; diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 4c4aa6617..f76aa7a07 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -175,7 +175,7 @@ async fn handle_announce( let mut peer = peer_from_request(announce_request, &peer_ip); let peers_wanted = match announce_request.numwant { Some(numwant) => PeersWanted::only(numwant), - None => PeersWanted::All, + None => PeersWanted::AsManyAsPossible, }; let announce_data = services::announce::invoke( diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 64a29db5a..4de9296b3 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -195,7 +195,7 @@ mod tests { core_http_tracker_services.http_stats_event_sender.clone(), sample_info_hash(), &mut peer, - &PeersWanted::All, + &PeersWanted::AsManyAsPossible, ) .await; @@ -232,7 +232,7 @@ mod tests { http_stats_event_sender, sample_info_hash(), &mut peer, - &PeersWanted::All, + &PeersWanted::AsManyAsPossible, ) .await; } @@ -277,7 +277,7 @@ mod tests { http_stats_event_sender, sample_info_hash(), &mut peer, - &PeersWanted::All, + &PeersWanted::AsManyAsPossible, ) .await; } @@ -303,7 +303,7 @@ mod tests { http_stats_event_sender, sample_info_hash(), &mut peer, - &PeersWanted::All, + &PeersWanted::AsManyAsPossible, ) .await; } diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 0a3425efe..3a2323693 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -182,7 +182,7 @@ mod tests { // Announce a new peer to force scrape data to contain not zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); - announce_handler.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); + announce_handler.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible); let scrape_data = invoke(&scrape_handler, &http_stats_event_sender, &info_hashes, &original_peer_ip).await; @@ -267,7 +267,7 @@ mod tests { // Announce a new peer to force scrape data to contain not zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); - announce_handler.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::All); + announce_handler.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible); let scrape_data = fake(&http_stats_event_sender, &info_hashes, &original_peer_ip).await; From 58a3741db9b7b51dc65517bf9468ffde1c2fca64 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 11:52:12 +0000 Subject: [PATCH 0728/1297] refactor: [#1250] invert dependency between http-protocol and tracker-core pacakges The `tracker-core` should not depend on higher levels layers like the `http-protocol` package. --- Cargo.lock | 2 +- packages/http-protocol/Cargo.toml | 1 + packages/http-protocol/src/v1/responses/error.rs | 8 ++++++++ packages/tracker-core/Cargo.toml | 1 - packages/tracker-core/src/error.rs | 9 --------- 5 files changed, 10 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d868f7452..228640f84 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -542,6 +542,7 @@ version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", "bittorrent-primitives", + "bittorrent-tracker-core", "derive_more", "multimap", "percent-encoding", @@ -596,7 +597,6 @@ name = "bittorrent-tracker-core" version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", - "bittorrent-http-protocol", "bittorrent-primitives", "chrono", "derive_more", diff --git a/packages/http-protocol/Cargo.toml b/packages/http-protocol/Cargo.toml index 05b69d201..2d0cabf51 100644 --- a/packages/http-protocol/Cargo.toml +++ b/packages/http-protocol/Cargo.toml @@ -17,6 +17,7 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } multimap = "0" percent-encoding = "2" diff --git a/packages/http-protocol/src/v1/responses/error.rs b/packages/http-protocol/src/v1/responses/error.rs index f939ce298..cdf27e00b 100644 --- a/packages/http-protocol/src/v1/responses/error.rs +++ b/packages/http-protocol/src/v1/responses/error.rs @@ -55,6 +55,14 @@ impl From for Error { } } +impl From for Error { + fn from(err: bittorrent_tracker_core::error::Error) -> Self { + Error { + failure_reason: format!("Tracker error: {err}"), + } + } +} + #[cfg(test)] mod tests { diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index aeea30a3e..96505a7ba 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -16,7 +16,6 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" -bittorrent-http-protocol = { version = "3.0.0-develop", path = "../http-protocol" } bittorrent-primitives = "0.1.0" chrono = { version = "0", default-features = false, features = ["clock"] } derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } diff --git a/packages/tracker-core/src/error.rs b/packages/tracker-core/src/error.rs index 1d0e974e5..6fdb5b626 100644 --- a/packages/tracker-core/src/error.rs +++ b/packages/tracker-core/src/error.rs @@ -8,7 +8,6 @@ //! use std::panic::Location; -use bittorrent_http_protocol::v1::responses; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_located_error::LocatedError; @@ -54,11 +53,3 @@ pub enum PeerKeyError { source: LocatedError<'static, databases::error::Error>, }, } - -impl From for responses::error::Error { - fn from(err: Error) -> Self { - responses::error::Error { - failure_reason: format!("Tracker error: {err}"), - } - } -} From 3bb4a13127b72c8b8fa16b27d89d6f1d21d02af4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 12:21:24 +0000 Subject: [PATCH 0729/1297] refactor: [#1250] remove unused errors in tracker core --- packages/tracker-core/src/error.rs | 24 +++--------------------- 1 file changed, 3 insertions(+), 21 deletions(-) diff --git a/packages/tracker-core/src/error.rs b/packages/tracker-core/src/error.rs index 6fdb5b626..6c2e3d4c5 100644 --- a/packages/tracker-core/src/error.rs +++ b/packages/tracker-core/src/error.rs @@ -1,11 +1,4 @@ -//! Error returned by the core `Tracker`. -//! -//! Error | Context | Description -//! ---|---|--- -//! `PeerKeyNotValid` | Authentication | The supplied key is not valid. It may not be registered or expired. -//! `PeerNotAuthenticated` | Authentication | The peer did not provide the authentication key. -//! `TorrentNotWhitelisted` | Authorization | The action cannot be perform on a not-whitelisted torrent (it only applies for trackers running in `listed` or `private_listed` modes). -//! +//! Errors returned by the core tracker. use std::panic::Location; use bittorrent_primitives::info_hash::InfoHash; @@ -14,20 +7,9 @@ use torrust_tracker_located_error::LocatedError; use super::authentication::key::ParseKeyError; use super::databases; -/// Authentication or authorization error returned by the core `Tracker` +/// Authorization errors returned by the core tracker. #[derive(thiserror::Error, Debug, Clone)] pub enum Error { - // Authentication errors - #[error("The supplied key: {key:?}, is not valid: {source}")] - PeerKeyNotValid { - key: super::authentication::Key, - source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - }, - - #[error("The peer is not authenticated, {location}")] - PeerNotAuthenticated { location: &'static Location<'static> }, - - // Authorization errors #[error("The torrent: {info_hash}, is not whitelisted, {location}")] TorrentNotWhitelisted { info_hash: InfoHash, @@ -35,7 +17,7 @@ pub enum Error { }, } -/// Errors related to peers keys. +/// Peers keys errors returned by the core tracker. #[allow(clippy::module_name_repetitions)] #[derive(thiserror::Error, Debug, Clone)] pub enum PeerKeyError { From 0811d67b28a793401895fbf0f91b5e940c2624e8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 12:23:59 +0000 Subject: [PATCH 0730/1297] refactor: [#1250] rename enum --- packages/http-protocol/src/v1/responses/error.rs | 4 ++-- packages/tracker-core/src/error.rs | 4 ++-- packages/tracker-core/src/whitelist/authorization.rs | 10 +++++----- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/http-protocol/src/v1/responses/error.rs b/packages/http-protocol/src/v1/responses/error.rs index cdf27e00b..8a6b4cf55 100644 --- a/packages/http-protocol/src/v1/responses/error.rs +++ b/packages/http-protocol/src/v1/responses/error.rs @@ -55,8 +55,8 @@ impl From for Error { } } -impl From for Error { - fn from(err: bittorrent_tracker_core::error::Error) -> Self { +impl From for Error { + fn from(err: bittorrent_tracker_core::error::WhitelistError) -> Self { Error { failure_reason: format!("Tracker error: {err}"), } diff --git a/packages/tracker-core/src/error.rs b/packages/tracker-core/src/error.rs index 6c2e3d4c5..56b6e1a10 100644 --- a/packages/tracker-core/src/error.rs +++ b/packages/tracker-core/src/error.rs @@ -7,9 +7,9 @@ use torrust_tracker_located_error::LocatedError; use super::authentication::key::ParseKeyError; use super::databases; -/// Authorization errors returned by the core tracker. +/// Whitelist errors returned by the core tracker. #[derive(thiserror::Error, Debug, Clone)] -pub enum Error { +pub enum WhitelistError { #[error("The torrent: {info_hash}, is not whitelisted, {location}")] TorrentNotWhitelisted { info_hash: InfoHash, diff --git a/packages/tracker-core/src/whitelist/authorization.rs b/packages/tracker-core/src/whitelist/authorization.rs index cb5f4acbf..66f909226 100644 --- a/packages/tracker-core/src/whitelist/authorization.rs +++ b/packages/tracker-core/src/whitelist/authorization.rs @@ -6,7 +6,7 @@ use torrust_tracker_configuration::Core; use tracing::instrument; use super::repository::in_memory::InMemoryWhitelist; -use crate::error::Error; +use crate::error::WhitelistError; pub struct WhitelistAuthorization { /// Core tracker configuration. @@ -32,7 +32,7 @@ impl WhitelistAuthorization { /// Will return an error if the tracker is running in `listed` mode /// and the infohash is not whitelisted. #[instrument(skip(self, info_hash), err)] - pub async fn authorize(&self, info_hash: &InfoHash) -> Result<(), Error> { + pub async fn authorize(&self, info_hash: &InfoHash) -> Result<(), WhitelistError> { if !self.is_listed() { return Ok(()); } @@ -41,7 +41,7 @@ impl WhitelistAuthorization { return Ok(()); } - Err(Error::TorrentNotWhitelisted { + Err(WhitelistError::TorrentNotWhitelisted { info_hash: *info_hash, location: Location::caller(), }) @@ -89,7 +89,7 @@ mod tests { use torrust_tracker_configuration::Core; use crate::core_tests::sample_info_hash; - use crate::error::Error; + use crate::error::WhitelistError; use crate::whitelist::authorization::tests::the_whitelist_authorization_for_announce_and_scrape_actions::{ initialize_whitelist_authorization_and_dependencies_with, initialize_whitelist_authorization_with, }; @@ -121,7 +121,7 @@ mod tests { let result = whitelist_authorization.authorize(&sample_info_hash()).await; - assert!(matches!(result.unwrap_err(), Error::TorrentNotWhitelisted { .. })); + assert!(matches!(result.unwrap_err(), WhitelistError::TorrentNotWhitelisted { .. })); } } From ca4ead502ae94b9bb8c93a6d115fb010153e11dc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 12:59:35 +0000 Subject: [PATCH 0731/1297] test: [#1250] add tests for tracker core errors --- packages/tracker-core/src/error.rs | 83 ++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/packages/tracker-core/src/error.rs b/packages/tracker-core/src/error.rs index 56b6e1a10..515510b85 100644 --- a/packages/tracker-core/src/error.rs +++ b/packages/tracker-core/src/error.rs @@ -35,3 +35,86 @@ pub enum PeerKeyError { source: LocatedError<'static, databases::error::Error>, }, } + +#[cfg(test)] +mod tests { + + mod whitelist_error { + + use crate::core_tests::sample_info_hash; + use crate::error::WhitelistError; + + #[test] + fn torrent_not_whitelisted() { + let err = WhitelistError::TorrentNotWhitelisted { + info_hash: sample_info_hash(), + location: std::panic::Location::caller(), + }; + + let err_msg = format!("{err}"); + + assert!( + err_msg.contains(&format!("The torrent: {}, is not whitelisted", sample_info_hash())), + "Error message did not contain expected text: {err_msg}" + ); + } + } + + mod peer_key_error { + use torrust_tracker_located_error::Located; + + use crate::databases::driver::Driver; + use crate::error::PeerKeyError; + use crate::{authentication, databases}; + + #[test] + fn duration_overflow() { + let seconds_valid = 100; + + let err = PeerKeyError::DurationOverflow { seconds_valid }; + + let err_msg = format!("{err}"); + + assert!( + err_msg.contains(&format!("Invalid peer key duration: {seconds_valid}")), + "Error message did not contain expected text: {err_msg}" + ); + } + + #[test] + fn parsing_from_string() { + let err = authentication::key::ParseKeyError::InvalidKeyLength; + + let err = PeerKeyError::InvalidKey { + key: "INVALID KEY".to_string(), + source: Located(err).into(), + }; + + let err_msg = format!("{err}"); + + assert!( + err_msg.contains(&"Invalid key: INVALID KEY".to_string()), + "Error message did not contain expected text: {err_msg}" + ); + } + + #[test] + fn persisting_into_database() { + let err = databases::error::Error::InsertFailed { + location: std::panic::Location::caller(), + driver: Driver::Sqlite3, + }; + + let err = PeerKeyError::DatabaseError { + source: Located(err).into(), + }; + + let err_msg = format!("{err}"); + + assert!( + err_msg.contains(&"Can't persist key".to_string()), + "Error message did not contain expected text: {err}" + ); + } + } +} From 480933f2d6b0eacd96ac48ea6a8f5ec351fb66fd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 14:11:56 +0000 Subject: [PATCH 0732/1297] chore(deps): udpate dependencies ```output cargo update Updating crates.io index Locking 18 packages to latest compatible versions Updating bytes v1.9.0 -> v1.10.0 Updating cc v1.2.10 -> v1.2.12 Updating clap v4.5.27 -> v4.5.28 Updating clap_derive v4.5.24 -> v4.5.28 Updating once_cell v1.20.2 -> v1.20.3 Updating openssl v0.10.69 -> v0.10.70 Updating openssl-sys v0.9.104 -> v0.9.105 Updating pin-project v1.1.8 -> v1.1.9 Updating pin-project-internal v1.1.8 -> v1.1.9 Updating rustc-hash v2.1.0 -> v2.1.1 Updating rustls v0.23.21 -> v0.23.22 Updating syn v2.0.96 -> v2.0.98 Updating toml v0.8.19 -> v0.8.20 Updating toml_edit v0.22.22 -> v0.22.23 Updating uuid v1.12.1 -> v1.13.1 Updating winnow v0.6.25 -> v0.7.1 Updating zerocopy v0.8.14 -> v0.8.17 Updating zerocopy-derive v0.8.14 -> v0.8.17 ``` --- Cargo.lock | 156 ++++++++++++++++++++++++++--------------------------- 1 file changed, 78 insertions(+), 78 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 228640f84..b186f0e9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -433,7 +433,7 @@ checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -521,7 +521,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -693,7 +693,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -774,9 +774,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "325918d6fe32f23b19878fe4b34794ae41fc19ddbe53b10571a4874d44ffd39b" +checksum = "f61dac84819c6588b558454b194026eb1f09c293b9036ae9b159e74e73ab6cf9" [[package]] name = "camino" @@ -804,9 +804,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.10" +version = "1.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13208fcbb66eaeffe09b99fffbe1af420f00a7b35aa99ad683dfc1aa76145229" +checksum = "755717a7de9ec452bf7f3f1a3099085deabd7f2962b861dae91ecd7a365903d2" dependencies = [ "jobserver", "libc", @@ -897,9 +897,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.27" +version = "4.5.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "769b0145982b4b48713e01ec42d61614425f27b7058bda7180a3a41f30104796" +checksum = "3e77c3243bd94243c03672cb5154667347c457ca271254724f9f393aee1c05ff" dependencies = [ "clap_builder", "clap_derive", @@ -919,14 +919,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.24" +version = "4.5.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54b755194d6389280185988721fffba69495eed5ee9feeee9a599b53db80318c" +checksum = "bf4ced95c6f4a675af3da73304b9ac4ed991640c36374e4b46795c49e17cf1ed" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -1147,7 +1147,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -1158,7 +1158,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -1202,7 +1202,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", "unicode-xid", ] @@ -1214,7 +1214,7 @@ checksum = "ccfae181bab5ab6c5478b2ccb69e4c68a02f8c3ec72f6616bfec9dbc599d2ee0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -1235,7 +1235,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -1438,7 +1438,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -1450,7 +1450,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -1462,7 +1462,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -1540,7 +1540,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -1981,7 +1981,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -2301,7 +2301,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -2351,7 +2351,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", "termcolor", "thiserror 1.0.69", ] @@ -2517,9 +2517,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.20.2" +version = "1.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" +checksum = "945462a4b81e43c4e3ba96bd7b49d834c6f61198356aa858733bc4acf3cbe62e" [[package]] name = "oorandom" @@ -2529,9 +2529,9 @@ checksum = "b410bbe7e14ab526a0e86877eb47c6996a2bd7746f027ba551028c925390e4e9" [[package]] name = "openssl" -version = "0.10.69" +version = "0.10.70" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5e534d133a060a3c19daec1eb3e98ec6f4685978834f2dbadfe2ec215bab64e" +checksum = "61cfb4e166a8bb8c9b55c500bc2308550148ece889be90f609377e58140f42c6" dependencies = [ "bitflags", "cfg-if", @@ -2550,7 +2550,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -2561,9 +2561,9 @@ checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" [[package]] name = "openssl-sys" -version = "0.9.104" +version = "0.9.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45abf306cbf99debc8195b66b7346498d7b10c210de50418b5ccd7ceba08c741" +checksum = "8b22d5b84be05a8d6947c7cb71f7c849aa0f112acd4bf51c2a7c1c988ac0a9dc" dependencies = [ "cc", "libc", @@ -2626,7 +2626,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -2685,22 +2685,22 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.8" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e2ec53ad785f4d35dac0adea7f7dc6f1bb277ad84a680c7afefeae05d1f5916" +checksum = "dfe2e71e1471fe07709406bf725f710b02927c9c54b2b5b2ec0e8087d97c327d" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.8" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56a66c0c55993aa927429d0f8a0abfd74f084e4d9c192cffed01e418d83eefb" +checksum = "f6e859e6e5bd50440ab63c47e3ebabc90f26251f7c73c3d3e837b74a1cc3fa67" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -2850,7 +2850,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -2870,7 +2870,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", "version_check", "yansi", ] @@ -2972,7 +2972,7 @@ checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.0", - "zerocopy 0.8.14", + "zerocopy 0.8.17", ] [[package]] @@ -3011,7 +3011,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b08f3c9802962f7e1b25113931d94f43ed9725bebc59db9d0c3e9a23b67e15ff" dependencies = [ "getrandom 0.3.1", - "zerocopy 0.8.14", + "zerocopy 0.8.17", ] [[package]] @@ -3211,7 +3211,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.96", + "syn 2.0.98", "unicode-ident", ] @@ -3253,9 +3253,9 @@ checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" [[package]] name = "rustc-hash" -version = "2.1.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7fb8039b3032c191086b10f11f319a6e99e1e82889c5cc6046f515c9db1d497" +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" [[package]] name = "rustc_version" @@ -3281,9 +3281,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.21" +version = "0.23.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f287924602bf649d949c63dc8ac8b235fa5387d394020705b80c4eb597ce5b8" +checksum = "9fb9263ab4eb695e42321db096e3b8fbd715a59b154d5c88d82db2175b681ba7" dependencies = [ "once_cell", "rustls-pki-types", @@ -3440,7 +3440,7 @@ checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -3487,7 +3487,7 @@ checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -3538,7 +3538,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -3677,9 +3677,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.96" +version = "2.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80" +checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1" dependencies = [ "proc-macro2", "quote", @@ -3703,7 +3703,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -3805,7 +3805,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -3816,7 +3816,7 @@ checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -3920,7 +3920,7 @@ checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -3958,9 +3958,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.19" +version = "0.8.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1ed1f98e3fdc28d6d910e6737ae6ab1a93bf1985935a1193e68f93eeb68d24e" +checksum = "cd87a5cdd6ffab733b2f74bc4fd7ee5fff6634124999ac278c35fc78c6120148" dependencies = [ "serde", "serde_spanned", @@ -3979,9 +3979,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.22" +version = "0.22.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae48d6208a266e853d946088ed816055e556cc6028c5e8e2b84d9fa5dd7c7f5" +checksum = "02a8b472d1a3d7c18e2d61a489aee3453fd9031c33e4f55bd533f4a7adca1bee" dependencies = [ "indexmap 2.7.1", "serde", @@ -4263,7 +4263,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -4396,12 +4396,12 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.12.1" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3758f5e68192bb96cc8f9b7e2c2cfdabb435499a28499a42f8f984092adad4b" +checksum = "ced87ca4be083373936a67f8de945faa23b6b42384bd5b64434850802c6dccd0" dependencies = [ - "getrandom 0.2.15", - "rand 0.8.5", + "getrandom 0.3.1", + "rand 0.9.0", ] [[package]] @@ -4484,7 +4484,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", "wasm-bindgen-shared", ] @@ -4519,7 +4519,7 @@ checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4697,9 +4697,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "0.6.25" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad699df48212c6cc6eb4435f35500ac6fd3b9913324f938aea302022ce19d310" +checksum = "86e376c75f4f43f44db463cf729e0d3acbf954d13e22c51e26e4c264b4ab545f" dependencies = [ "memchr", ] @@ -4760,7 +4760,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", "synstructure", ] @@ -4776,11 +4776,11 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.14" +version = "0.8.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a367f292d93d4eab890745e75a778da40909cab4d6ff8173693812f79c4a2468" +checksum = "aa91407dacce3a68c56de03abe2760159582b846c6a4acd2f456618087f12713" dependencies = [ - "zerocopy-derive 0.8.14", + "zerocopy-derive 0.8.17", ] [[package]] @@ -4791,18 +4791,18 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] name = "zerocopy-derive" -version = "0.8.14" +version = "0.8.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3931cb58c62c13adec22e38686b559c86a30565e16ad6e8510a337cedc611e1" +checksum = "06718a168365cad3d5ff0bb133aad346959a2074bd4a85c121255a11304a8626" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] @@ -4822,7 +4822,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", "synstructure", ] @@ -4851,7 +4851,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.96", + "syn 2.0.98", ] [[package]] From c88ab10c751e02eb9bc8d6d63bcce90e89eff63a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 15:32:13 +0000 Subject: [PATCH 0733/1297] refactor: reorganize tracker core databases mod --- .../src/databases/{driver.rs => driver/mod.rs} | 16 ++++++++++++++-- .../src/databases/{ => driver}/mysql.rs | 3 +-- .../src/databases/{ => driver}/sqlite.rs | 3 +-- packages/tracker-core/src/databases/mod.rs | 4 ---- 4 files changed, 16 insertions(+), 10 deletions(-) rename packages/tracker-core/src/databases/{driver.rs => driver/mod.rs} (89%) rename packages/tracker-core/src/databases/{ => driver}/mysql.rs (99%) rename packages/tracker-core/src/databases/{ => driver}/sqlite.rs (99%) diff --git a/packages/tracker-core/src/databases/driver.rs b/packages/tracker-core/src/databases/driver/mod.rs similarity index 89% rename from packages/tracker-core/src/databases/driver.rs rename to packages/tracker-core/src/databases/driver/mod.rs index 7b532f3f0..651a97913 100644 --- a/packages/tracker-core/src/databases/driver.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -2,11 +2,11 @@ //! //! See [`databases::driver::build`](crate::core::databases::driver::build) //! function for more information. +use mysql::Mysql; use serde::{Deserialize, Serialize}; +use sqlite::Sqlite; use super::error::Error; -use super::mysql::Mysql; -use super::sqlite::Sqlite; use super::{Builder, Database}; /// The database management system used by the tracker. @@ -61,6 +61,18 @@ pub enum Driver { /// # Panics /// /// This function will panic if unable to create database tables. +pub mod mysql; +pub mod sqlite; + +/// It builds a new database driver. +/// +/// # Panics +/// +/// Will panic if unable to create database tables. +/// +/// # Errors +/// +/// Will return `Error` if unable to build the driver. pub fn build(driver: &Driver, db_path: &str) -> Result, Error> { let database = match driver { Driver::Sqlite3 => Builder::::build(db_path), diff --git a/packages/tracker-core/src/databases/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs similarity index 99% rename from packages/tracker-core/src/databases/mysql.rs rename to packages/tracker-core/src/databases/driver/mysql.rs index fb39b781d..b0198464c 100644 --- a/packages/tracker-core/src/databases/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -9,8 +9,7 @@ use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MySqlConnectionManager; use torrust_tracker_primitives::PersistentTorrents; -use super::driver::Driver; -use super::{Database, Error}; +use super::{Database, Driver, Error}; use crate::authentication::key::AUTH_KEY_LENGTH; use crate::authentication::{self, Key}; diff --git a/packages/tracker-core/src/databases/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs similarity index 99% rename from packages/tracker-core/src/databases/sqlite.rs rename to packages/tracker-core/src/databases/driver/sqlite.rs index a7552ec11..fa90d7930 100644 --- a/packages/tracker-core/src/databases/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -9,8 +9,7 @@ use r2d2_sqlite::rusqlite::types::Null; use r2d2_sqlite::SqliteConnectionManager; use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrents}; -use super::driver::Driver; -use super::{Database, Error}; +use super::{Database, Driver, Error}; use crate::authentication::{self, Key}; const DRIVER: Driver = Driver::Sqlite3; diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs index f0930d05d..208305211 100644 --- a/packages/tracker-core/src/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -45,9 +45,7 @@ //! > **NOTICE**: All keys must have an expiration date. pub mod driver; pub mod error; -pub mod mysql; pub mod setup; -pub mod sqlite; use std::marker::PhantomData; @@ -69,8 +67,6 @@ impl Builder where T: Database + 'static, { - /// . - /// /// # Errors /// /// Will return `r2d2::Error` if `db_path` is not able to create a database. From 3f78459208aec0945b0671a92ebc2b31c6569e32 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 15:56:13 +0000 Subject: [PATCH 0734/1297] refactor: remove constructor from Database trait For two reasons: - Drivers' dependencies migth be different in the future for different drivers. - You can have conflict when mocking the trait. See https://github.com/asomers/mockall/commit/7c54ed1999c4c44cbc0c71701d5293e781c7d7a9 --- .../tracker-core/src/databases/driver/mod.rs | 10 +++--- .../src/databases/driver/mysql.rs | 6 ++-- .../src/databases/driver/sqlite.rs | 12 ++++--- packages/tracker-core/src/databases/mod.rs | 32 ------------------- 4 files changed, 17 insertions(+), 43 deletions(-) diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index 651a97913..bdef7fcee 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; use sqlite::Sqlite; use super::error::Error; -use super::{Builder, Database}; +use super::Database; /// The database management system used by the tracker. /// @@ -74,10 +74,10 @@ pub mod sqlite; /// /// Will return `Error` if unable to build the driver. pub fn build(driver: &Driver, db_path: &str) -> Result, Error> { - let database = match driver { - Driver::Sqlite3 => Builder::::build(db_path), - Driver::MySQL => Builder::::build(db_path), - }?; + let database: Box = match driver { + Driver::Sqlite3 => Box::new(Sqlite::new(db_path)?), + Driver::MySQL => Box::new(Mysql::new(db_path)?), + }; database.create_database_tables().expect("Could not create database tables."); diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index b0198464c..69fa1240e 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -19,7 +19,7 @@ pub struct Mysql { pool: Pool, } -impl Database for Mysql { +impl Mysql { /// It instantiates a new `MySQL` database driver. /// /// Refer to [`databases::Database::new`](crate::core::databases::Database::new). @@ -27,7 +27,7 @@ impl Database for Mysql { /// # Errors /// /// Will return `r2d2::Error` if `db_path` is not able to create `MySQL` database. - fn new(db_path: &str) -> Result { + pub fn new(db_path: &str) -> Result { let opts = Opts::from_url(db_path)?; let builder = OptsBuilder::from_opts(opts); let manager = MySqlConnectionManager::new(builder); @@ -35,7 +35,9 @@ impl Database for Mysql { Ok(Self { pool }) } +} +impl Database for Mysql { /// Refer to [`databases::Database::create_database_tables`](crate::core::databases::Database::create_database_tables). fn create_database_tables(&self) -> Result<(), Error> { let create_whitelist_table = " diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs index fa90d7930..3a08406fa 100644 --- a/packages/tracker-core/src/databases/driver/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -18,7 +18,7 @@ pub struct Sqlite { pool: Pool, } -impl Database for Sqlite { +impl Sqlite { /// It instantiates a new `SQLite3` database driver. /// /// Refer to [`databases::Database::new`](crate::core::databases::Database::new). @@ -26,11 +26,15 @@ impl Database for Sqlite { /// # Errors /// /// Will return `r2d2::Error` if `db_path` is not able to create `SqLite` database. - fn new(db_path: &str) -> Result { - let cm = SqliteConnectionManager::file(db_path); - Pool::new(cm).map_or_else(|err| Err((err, Driver::Sqlite3).into()), |pool| Ok(Sqlite { pool })) + pub fn new(db_path: &str) -> Result { + let manager = SqliteConnectionManager::file(db_path); + let pool = r2d2::Pool::builder().build(manager).map_err(|e| (e, DRIVER))?; + + Ok(Self { pool }) } +} +impl Database for Sqlite { /// Refer to [`databases::Database::create_database_tables`](crate::core::databases::Database::create_database_tables). fn create_database_tables(&self) -> Result<(), Error> { let create_whitelist_table = " diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs index 208305211..010252139 100644 --- a/packages/tracker-core/src/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -47,8 +47,6 @@ pub mod driver; pub mod error; pub mod setup; -use std::marker::PhantomData; - use bittorrent_primitives::info_hash::InfoHash; use mockall::automock; use torrust_tracker_primitives::PersistentTorrents; @@ -56,39 +54,9 @@ use torrust_tracker_primitives::PersistentTorrents; use self::error::Error; use crate::authentication::{self, Key}; -struct Builder -where - T: Database, -{ - phantom: PhantomData, -} - -impl Builder -where - T: Database + 'static, -{ - /// # Errors - /// - /// Will return `r2d2::Error` if `db_path` is not able to create a database. - pub(self) fn build(db_path: &str) -> Result, Error> { - Ok(Box::new(T::new(db_path)?)) - } -} - /// The persistence trait. It contains all the methods to interact with the database. #[automock] pub trait Database: Sync + Send { - /// It instantiates a new database driver. - /// - /// # Errors - /// - /// Will return `r2d2::Error` if `db_path` is not able to create a database. - fn new(db_path: &str) -> Result - where - Self: std::marker::Sized; - - // Schema - /// It generates the database tables. SQL queries are hardcoded in the trait /// implementation. /// From 568d6d362316e08fad7b7710fbb37d9534633687 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Feb 2025 17:31:27 +0000 Subject: [PATCH 0735/1297] test: [#1251] add tests for core database driver sqlite --- .../src/databases/driver/sqlite.rs | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs index 3a08406fa..e04cf6110 100644 --- a/packages/tracker-core/src/databases/driver/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -288,3 +288,116 @@ impl Database for Sqlite { } } } + +#[cfg(test)] +mod tests { + + mod the_sqlite_driver { + use torrust_tracker_configuration::Core; + use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; + + use crate::databases::driver::sqlite::Sqlite; + use crate::databases::Database; + + fn initialize_driver_and_database() -> Sqlite { + let config = ephemeral_configuration(); + let driver = Sqlite::new(&config.database.path).unwrap(); + driver.create_database_tables().unwrap(); + driver + } + + fn ephemeral_configuration() -> Core { + let mut config = Core::default(); + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + config + } + + mod handling_torrent_persistence { + + use crate::core_tests::sample_info_hash; + use crate::databases::driver::sqlite::tests::the_sqlite_driver::initialize_driver_and_database; + use crate::databases::Database; + + #[test] + fn it_should_save_and_load_persistent_torrents() { + let driver = initialize_driver_and_database(); + + let infohash = sample_info_hash(); + + let number_of_downloads = 1; + + driver.save_persistent_torrent(&infohash, number_of_downloads).unwrap(); + + let torrents = driver.load_persistent_torrents().unwrap(); + + assert_eq!(torrents.len(), 1); + assert_eq!(torrents.get(&infohash), Some(number_of_downloads).as_ref()); + } + } + + mod handling_authentication_keys { + use std::time::Duration; + + use crate::authentication::key::{generate_key, generate_permanent_key}; + use crate::databases::driver::sqlite::tests::the_sqlite_driver::initialize_driver_and_database; + use crate::databases::Database; + + #[test] + fn it_should_save_and_load_permanent_authentication_keys() { + let driver = initialize_driver_and_database(); + + // Add a new permanent key + let peer_key = generate_permanent_key(); + driver.add_key_to_keys(&peer_key).unwrap(); + + // Get the key back + let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); + + assert_eq!(stored_peer_key, peer_key); + } + #[test] + fn it_should_save_and_load_expiring_authentication_keys() { + let driver = initialize_driver_and_database(); + + // Add a new expiring key + let peer_key = generate_key(Some(Duration::from_secs(120))); + driver.add_key_to_keys(&peer_key).unwrap(); + + // Get the key back + let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); + + /* todo: + + The expiration time recovered from the database is not the same + as the one we set. It includes a small offset (nanoseconds). + + left: PeerKey { key: Key("7HP1NslpuQn6kLVAgAF4nFpnZNSQ4hrx"), valid_until: Some(1739182308s) } + right: PeerKey { key: Key("7HP1NslpuQn6kLVAgAF4nFpnZNSQ4hrx"), valid_until: Some(1739182308.603691299s) + + */ + + assert_eq!(stored_peer_key.key(), peer_key.key()); + assert_eq!( + stored_peer_key.valid_until.unwrap().as_secs(), + peer_key.valid_until.unwrap().as_secs() + ); + } + + #[test] + fn it_should_remove_an_authentication_key() { + let driver = initialize_driver_and_database(); + + let peer_key = generate_key(None); + + // Add a new key + driver.add_key_to_keys(&peer_key).unwrap(); + + // Remove the key + driver.remove_key_from_keys(&peer_key.key()).unwrap(); + + assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); + } + } + } +} From 46949a6fe1fcc3d4f7b877d0f5e2eebf89b65db0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Feb 2025 17:27:01 +0000 Subject: [PATCH 0736/1297] test: [#1251] add tests for core database driver mysql --- .github/workflows/testing.yaml | 4 + Cargo.lock | 417 +++++++++++++++++- cSpell.json | 1 + packages/tracker-core/Cargo.toml | 11 +- .../src/databases/driver/mysql.rs | 245 ++++++++++ 5 files changed, 652 insertions(+), 26 deletions(-) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 28600dee9..671864fc9 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -146,6 +146,10 @@ jobs: name: Run Unit Tests run: cargo test --tests --benches --examples --workspace --all-targets --all-features + - id: database + name: Run MySQL Database Tests + run: TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST=true cargo test --package bittorrent-tracker-core + e2e: name: E2E runs-on: ubuntu-latest diff --git a/Cargo.lock b/Cargo.lock index b186f0e9b..2f99db113 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -314,6 +314,17 @@ version = "4.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" +[[package]] +name = "async-trait" +version = "0.1.86" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "644dd749086bf3771a2fbc5f256fdb982d53f011c7d5d560304eafeecebce79d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.98", +] + [[package]] name = "atomic" version = "0.6.0" @@ -451,11 +462,11 @@ dependencies = [ "hyper", "hyper-util", "pin-project-lite", - "rustls", + "rustls 0.23.22", "rustls-pemfile", "rustls-pki-types", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.1", "tower 0.4.13", "tower-service", ] @@ -472,7 +483,7 @@ dependencies = [ "miniz_oxide", "object", "rustc-demangle", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -608,6 +619,7 @@ dependencies = [ "rand 0.9.0", "serde", "serde_json", + "testcontainers", "thiserror 2.0.11", "tokio", "torrust-tracker-api-client", @@ -618,6 +630,7 @@ dependencies = [ "torrust-tracker-test-helpers", "torrust-tracker-torrent-repository", "tracing", + "url", ] [[package]] @@ -673,6 +686,56 @@ dependencies = [ "cipher", ] +[[package]] +name = "bollard" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aed08d3adb6ebe0eff737115056652670ae290f177759aac19c30456135f94c" +dependencies = [ + "base64 0.22.1", + "bollard-stubs", + "bytes", + "futures-core", + "futures-util", + "hex", + "home", + "http", + "http-body-util", + "hyper", + "hyper-named-pipe", + "hyper-rustls 0.26.0", + "hyper-util", + "hyperlocal-next", + "log", + "pin-project-lite", + "rustls 0.22.4", + "rustls-native-certs", + "rustls-pemfile", + "rustls-pki-types", + "serde", + "serde_derive", + "serde_json", + "serde_repr", + "serde_urlencoded", + "thiserror 1.0.69", + "tokio", + "tokio-util", + "tower-service", + "url", + "winapi", +] + +[[package]] +name = "bollard-stubs" +version = "1.44.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709d9aa1c37abb89d40f19f5d0ad6f0d88cb1581264e571c9350fc5bb89cf1c5" +dependencies = [ + "serde", + "serde_repr", + "serde_with", +] + [[package]] name = "borsh" version = "1.5.5" @@ -844,7 +907,7 @@ dependencies = [ "iana-time-zone", "num-traits", "serde", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -1227,6 +1290,27 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.48.0", +] + [[package]] name = "displaydoc" version = "0.2.5" @@ -1238,6 +1322,17 @@ dependencies = [ "syn 2.0.98", ] +[[package]] +name = "docker_credential" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31951f49556e34d90ed28342e1df7e1cb7a229c4cab0aecc627b5d91edd41d07" +dependencies = [ + "base64 0.21.7", + "serde", + "serde_json", +] + [[package]] name = "downcast" version = "0.11.0" @@ -1609,7 +1704,7 @@ dependencies = [ "cfg-if", "libc", "wasi 0.13.3+wasi-0.2.2", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -1724,6 +1819,15 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" +[[package]] +name = "home" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf" +dependencies = [ + "windows-sys 0.59.0", +] + [[package]] name = "http" version = "1.2.0" @@ -1791,6 +1895,40 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-named-pipe" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73b7d8abf35697b81a825e386fc151e0d503e8cb5fcb93cc8669c376dfd6f278" +dependencies = [ + "hex", + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", + "winapi", +] + +[[package]] +name = "hyper-rustls" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0bea761b46ae2b24eb4aef630d8d1c398157b6fc29e6350ecf090a0b70c952c" +dependencies = [ + "futures-util", + "http", + "hyper", + "hyper-util", + "log", + "rustls 0.22.4", + "rustls-native-certs", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.25.0", + "tower-service", +] + [[package]] name = "hyper-rustls" version = "0.27.5" @@ -1801,10 +1939,10 @@ dependencies = [ "http", "hyper", "hyper-util", - "rustls", + "rustls 0.23.22", "rustls-pki-types", "tokio", - "tokio-rustls", + "tokio-rustls 0.26.1", "tower-service", ] @@ -1843,6 +1981,21 @@ dependencies = [ "tracing", ] +[[package]] +name = "hyperlocal-next" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acf569d43fa9848e510358c07b80f4adf34084ddc28c6a4a651ee8474c070dcc" +dependencies = [ + "hex", + "http-body-util", + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", +] + [[package]] name = "iana-time-zone" version = "0.1.61" @@ -2151,7 +2304,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" dependencies = [ "cfg-if", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -2160,6 +2313,16 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa" +[[package]] +name = "libredox" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" +dependencies = [ + "bitflags", + "libc", +] + [[package]] name = "libsqlite3-sys" version = "0.31.0" @@ -2571,6 +2734,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "overload" version = "0.1.1" @@ -2603,7 +2772,32 @@ dependencies = [ "libc", "redox_syscall", "smallvec", - "windows-targets", + "windows-targets 0.52.6", +] + +[[package]] +name = "parse-display" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914a1c2265c98e2446911282c6ac86d8524f495792c38c5bd884f80499c7538a" +dependencies = [ + "parse-display-derive", + "regex", + "regex-syntax", +] + +[[package]] +name = "parse-display-derive" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ae7800a4c974efd12df917266338e79a7a74415173caf7e70aa0a0707345281" +dependencies = [ + "proc-macro2", + "quote", + "regex", + "regex-syntax", + "structmeta", + "syn 2.0.98", ] [[package]] @@ -3043,6 +3237,17 @@ dependencies = [ "bitflags", ] +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.15", + "libredox", + "thiserror 1.0.69", +] + [[package]] name = "regex" version = "1.11.1" @@ -3103,7 +3308,7 @@ dependencies = [ "http-body", "http-body-util", "hyper", - "hyper-rustls", + "hyper-rustls 0.27.5", "hyper-tls", "hyper-util", "ipnet", @@ -3279,6 +3484,20 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "rustls" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" +dependencies = [ + "log", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + [[package]] name = "rustls" version = "0.23.22" @@ -3292,6 +3511,19 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5bfb394eeed242e909609f56089eecfe5fda225042e8b171791b9c95f5931e5" +dependencies = [ + "openssl-probe", + "rustls-pemfile", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pemfile" version = "2.2.0" @@ -3648,6 +3880,29 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "structmeta" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e1575d8d40908d70f6fd05537266b90ae71b15dbbe7a8b7dffa2b759306d329" +dependencies = [ + "proc-macro2", + "quote", + "structmeta-derive", + "syn 2.0.98", +] + +[[package]] +name = "structmeta-derive" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.98", +] + [[package]] name = "subprocess" version = "0.2.9" @@ -3779,6 +4034,32 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" +[[package]] +name = "testcontainers" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "025e0ac563d543e0354d984540e749859a83dbe5c0afb8d458dc48d91cef2d6a" +dependencies = [ + "async-trait", + "bollard", + "bollard-stubs", + "bytes", + "dirs", + "docker_credential", + "futures", + "log", + "memchr", + "parse-display", + "serde", + "serde_json", + "serde_with", + "thiserror 1.0.69", + "tokio", + "tokio-stream", + "tokio-util", + "url", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -3933,13 +4214,35 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-rustls" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" +dependencies = [ + "rustls 0.22.4", + "rustls-pki-types", + "tokio", +] + [[package]] name = "tokio-rustls" version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f6d0975eaace0cf0fcadee4e4aaa5da15b5c079146f2cffb67c113be122bf37" dependencies = [ - "rustls", + "rustls 0.23.22", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047" +dependencies = [ + "futures-core", + "pin-project-lite", "tokio", ] @@ -4580,7 +4883,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -4591,7 +4894,7 @@ checksum = "e400001bb720a623c1c69032f8e3e4cf09984deec740f007dd2b03ec864804b0" dependencies = [ "windows-result", "windows-strings", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -4600,7 +4903,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -4610,7 +4913,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" dependencies = [ "windows-result", - "windows-targets", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", ] [[package]] @@ -4619,7 +4931,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -4628,7 +4940,22 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", ] [[package]] @@ -4637,28 +4964,46 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -4671,24 +5016,48 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" diff --git a/cSpell.json b/cSpell.json index a21e69b9f..b1e9a5e95 100644 --- a/cSpell.json +++ b/cSpell.json @@ -155,6 +155,7 @@ "taiki", "tdyne", "tempfile", + "testcontainers", "thiserror", "tlsv", "Torrentstorm", diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index 96505a7ba..46807a534 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -3,7 +3,6 @@ description = "A library with the core functionality needed to implement a BitTo keywords = ["api", "bittorrent", "core", "library", "tracker"] name = "bittorrent-tracker-core" readme = "README.md" - authors.workspace = true documentation.workspace = true edition.workspace = true @@ -27,7 +26,13 @@ rand = "0" serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } thiserror = "2" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = [ + "macros", + "net", + "rt-multi-thread", + "signal", + "sync", +] } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } @@ -40,3 +45,5 @@ local-ip-address = "0" mockall = "0" torrust-tracker-api-client = { version = "3.0.0-develop", path = "../tracker-api-client" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } +testcontainers = "0.17.0" +url = "2.5.4" diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index 69fa1240e..a30d75b90 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -252,3 +252,248 @@ impl Database for Mysql { Ok(1) } } + +#[cfg(test)] +mod tests { + /* + We run a MySQL container and run all the tests against the same container and database. + + The `Database`` trait is very simple and we only have one driver that needs + a container. In the future we might want to use different approaches like: + + - https://github.com/testcontainers/testcontainers-rs/issues/707 + - https://www.infinyon.com/blog/2021/04/rust-custom-test-harness/ + - https://github.com/torrust/torrust-tracker/blob/develop/src/bin/e2e_tests_runner.rs + + If we increase the number of methods or the number or drivers. + */ + use std::time::Duration; + + use testcontainers::runners::AsyncRunner; + use testcontainers::{ContainerAsync, GenericImage}; + use torrust_tracker_configuration::Core; + + use super::Mysql; + use crate::databases::Database; + + #[derive(Debug, Default)] + struct StoppedMysqlContainer {} + + impl StoppedMysqlContainer { + async fn run(self, config: &MysqlConfiguration) -> Result> { + let container = GenericImage::new("mysql", "8.0") + .with_env_var("MYSQL_ROOT_PASSWORD", config.db_root_password.clone()) + .with_env_var("MYSQL_DATABASE", config.database.clone()) + .with_env_var("MYSQL_ROOT_HOST", "%") + .with_exposed_port(config.internal_port) + // todo: this doesn't work + //.with_wait_for(WaitFor::message_on_stdout("ready for connections")) + .start() + .await?; + + Ok(RunningMysqlContainer::new(container, config.internal_port)) + } + } + + struct RunningMysqlContainer { + container: ContainerAsync, + internal_port: u16, + } + + impl RunningMysqlContainer { + fn new(container: ContainerAsync, internal_port: u16) -> Self { + Self { + container, + internal_port, + } + } + + async fn stop(self) { + self.container.stop().await.unwrap(); + } + + async fn get_host(&self) -> url::Host { + self.container.get_host().await.unwrap() + } + + async fn get_host_port_ipv4(&self) -> u16 { + self.container.get_host_port_ipv4(self.internal_port).await.unwrap() + } + } + + impl Default for MysqlConfiguration { + fn default() -> Self { + Self { + internal_port: 3306, + database: "torrust_tracker_test".to_string(), + db_user: "root".to_string(), + db_root_password: "test".to_string(), + } + } + } + + struct MysqlConfiguration { + pub internal_port: u16, + pub database: String, + pub db_user: String, + pub db_root_password: String, + } + + fn core_configuration(host: &url::Host, port: u16, mysql_configuration: &MysqlConfiguration) -> Core { + let mut config = Core::default(); + + let database = mysql_configuration.database.clone(); + let db_user = mysql_configuration.db_user.clone(); + let db_password = mysql_configuration.db_root_password.clone(); + + config.database.path = format!("mysql://{db_user}:{db_password}@{host}:{port}/{database}"); + + config + } + + fn initialize_driver(config: &Core) -> Mysql { + Mysql::new(&config.database.path).unwrap() + } + + async fn create_database_tables(driver: &Mysql) -> Result<(), Box> { + for _ in 0..5 { + if driver.create_database_tables().is_ok() { + return Ok(()); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + Err("MySQL is not ready after retries.".into()) + } + + #[tokio::test] + async fn run() -> Result<(), Box> { + if std::env::var("TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST").is_err() { + println!("Skipping the MySQL driver tests."); + return Ok(()); + } + + let mysql_configuration = MysqlConfiguration::default(); + + let stopped_mysql_container = StoppedMysqlContainer::default(); + + let mysql_container = stopped_mysql_container.run(&mysql_configuration).await.unwrap(); + + let host = mysql_container.get_host().await; + let port = mysql_container.get_host_port_ipv4().await; + + let config = core_configuration(&host, port, &mysql_configuration); + + let driver = initialize_driver(&config); + + // Since the interface is very simple and there are no conflicts between + // tests, we share the same database. If we want to isolate the tests in + // the future, we can create a new database for each test. + create_database_tables(&driver).await?; + + // todo: truncate tables otherwise they will increase in size over time. + // That's not a problem on CI when the database is always newly created. + + handling_torrent_persistence::it_should_save_and_load_persistent_torrents(&driver); + + // Permanent keys + //handling_authentication_keys::it_should_save_and_load_permanent_authentication_keys(&driver); + //handling_authentication_keys::it_should_remove_a_permanent_authentication_key(&driver); + + // Expiring keys + handling_authentication_keys::it_should_save_and_load_expiring_authentication_keys(&driver); + //handling_authentication_keys::it_should_remove_an_expiring_authentication_key(&driver); + + driver.drop_database_tables().unwrap(); + + mysql_container.stop().await; + + Ok(()) + } + + mod handling_torrent_persistence { + + use crate::core_tests::sample_info_hash; + use crate::databases::Database; + + pub fn it_should_save_and_load_persistent_torrents(driver: &impl Database) { + let infohash = sample_info_hash(); + + let number_of_downloads = 1; + + driver.save_persistent_torrent(&infohash, number_of_downloads).unwrap(); + + let torrents = driver.load_persistent_torrents().unwrap(); + + assert_eq!(torrents.len(), 1); + assert_eq!(torrents.get(&infohash), Some(number_of_downloads).as_ref()); + } + } + + mod handling_authentication_keys { + + use std::time::Duration; + + use crate::authentication::key::generate_key; + use crate::databases::Database; + + /*pub fn it_should_save_and_load_permanent_authentication_keys(driver: &impl Database) { + // Add a new permanent key + let peer_key = generate_permanent_key(); + driver.add_key_to_keys(&peer_key).unwrap(); + + // Get the key back + let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); + + assert_eq!(stored_peer_key, peer_key); + }*/ + + pub fn it_should_save_and_load_expiring_authentication_keys(driver: &impl Database) { + // Add a new expiring key + let peer_key = generate_key(Some(Duration::from_secs(120))); + driver.add_key_to_keys(&peer_key).unwrap(); + + // Get the key back + let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); + + /* todo: + + The expiration time recovered from the database is not the same + as the one we set. It includes a small offset (nanoseconds). + + left: PeerKey { key: Key("7HP1NslpuQn6kLVAgAF4nFpnZNSQ4hrx"), valid_until: Some(1739182308s) } + right: PeerKey { key: Key("7HP1NslpuQn6kLVAgAF4nFpnZNSQ4hrx"), valid_until: Some(1739182308.603691299s) + + */ + + assert_eq!(stored_peer_key.key(), peer_key.key()); + assert_eq!( + stored_peer_key.valid_until.unwrap().as_secs(), + peer_key.valid_until.unwrap().as_secs() + ); + } + + /*pub fn it_should_remove_a_permanent_authentication_key(driver: &impl Database) { + let peer_key = generate_permanent_key(); + + // Add a new key + driver.add_key_to_keys(&peer_key).unwrap(); + + // Remove the key + driver.remove_key_from_keys(&peer_key.key()).unwrap(); + + assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); + }*/ + + /*pub fn it_should_remove_an_expiring_authentication_key(driver: &impl Database) { + let peer_key = generate_key(Some(Duration::from_secs(120))); + + // Add a new key + driver.add_key_to_keys(&peer_key).unwrap(); + + // Remove the key + driver.remove_key_from_keys(&peer_key.key()).unwrap(); + + assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); + }*/ + } +} From 7ddacdc73d51a3365ce8068c9c8298a853e3b24d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Feb 2025 19:02:13 +0000 Subject: [PATCH 0737/1297] test: [#1251] unify test runner for sqlite and mysql drivers In the tracker-core package. --- packages/tracker-core/README.md | 8 ++ .../tracker-core/src/databases/driver/mod.rs | 130 +++++++++++++++++ .../src/databases/driver/mysql.rs | 133 ++---------------- .../src/databases/driver/sqlite.rs | 121 +++------------- 4 files changed, 172 insertions(+), 220 deletions(-) diff --git a/packages/tracker-core/README.md b/packages/tracker-core/README.md index e36a6f4be..dfb57f304 100644 --- a/packages/tracker-core/README.md +++ b/packages/tracker-core/README.md @@ -12,6 +12,14 @@ You usually don’t need to use this library directly. Instead, you should use t ## Testing +Run tests including tests for MySQL driver: + +```console +TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST=true cargo test +``` + +> NOTE: MySQL driver requires docker to run. We don't run them by default because we don't want to run them when we build container images. The Torrust Tracker container build runs unit tests for all dependencies, including this library. + Show coverage report: ```console diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index bdef7fcee..30888375e 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -83,3 +83,133 @@ pub fn build(driver: &Driver, db_path: &str) -> Result, Error> Ok(database) } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::time::Duration; + + use crate::databases::Database; + + pub async fn run_tests(driver: &Arc>) { + // Since the interface is very simple and there are no conflicts between + // tests, we share the same database. If we want to isolate the tests in + // the future, we can create a new database for each test. + create_database_tables(driver).await.unwrap(); + + // todo: truncate tables otherwise they will increase in size over time. + // That's not a problem on CI when the database is always newly created. + + handling_torrent_persistence::it_should_save_and_load_persistent_torrents(driver); + + // Permanent keys + //handling_authentication_keys::it_should_save_and_load_permanent_authentication_keys(&driver); + //handling_authentication_keys::it_should_remove_a_permanent_authentication_key(&driver); + + // Expiring keys + handling_authentication_keys::it_should_save_and_load_expiring_authentication_keys(driver); + //handling_authentication_keys::it_should_remove_an_expiring_authentication_key(&driver); + + driver.drop_database_tables().unwrap(); + } + + async fn create_database_tables(driver: &Arc>) -> Result<(), Box> { + for _ in 0..5 { + if driver.create_database_tables().is_ok() { + return Ok(()); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + Err("MySQL is not ready after retries.".into()) + } + + mod handling_torrent_persistence { + + use std::sync::Arc; + + use crate::core_tests::sample_info_hash; + use crate::databases::Database; + + pub fn it_should_save_and_load_persistent_torrents(driver: &Arc>) { + let infohash = sample_info_hash(); + + let number_of_downloads = 1; + + driver.save_persistent_torrent(&infohash, number_of_downloads).unwrap(); + + let torrents = driver.load_persistent_torrents().unwrap(); + + assert_eq!(torrents.len(), 1); + assert_eq!(torrents.get(&infohash), Some(number_of_downloads).as_ref()); + } + } + + mod handling_authentication_keys { + + use std::sync::Arc; + use std::time::Duration; + + use crate::authentication::key::generate_key; + use crate::databases::Database; + + /*pub fn it_should_save_and_load_permanent_authentication_keys(driver: &Arc>) { + // Add a new permanent key + let peer_key = generate_permanent_key(); + driver.add_key_to_keys(&peer_key).unwrap(); + + // Get the key back + let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); + + assert_eq!(stored_peer_key, peer_key); + }*/ + + pub fn it_should_save_and_load_expiring_authentication_keys(driver: &Arc>) { + // Add a new expiring key + let peer_key = generate_key(Some(Duration::from_secs(120))); + driver.add_key_to_keys(&peer_key).unwrap(); + + // Get the key back + let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); + + /* todo: + + The expiration time recovered from the database is not the same + as the one we set. It includes a small offset (nanoseconds). + + left: PeerKey { key: Key("7HP1NslpuQn6kLVAgAF4nFpnZNSQ4hrx"), valid_until: Some(1739182308s) } + right: PeerKey { key: Key("7HP1NslpuQn6kLVAgAF4nFpnZNSQ4hrx"), valid_until: Some(1739182308.603691299s) + + */ + + assert_eq!(stored_peer_key.key(), peer_key.key()); + assert_eq!( + stored_peer_key.valid_until.unwrap().as_secs(), + peer_key.valid_until.unwrap().as_secs() + ); + } + + /*pub fn it_should_remove_a_permanent_authentication_key(driver: &Arc>) { + let peer_key = generate_permanent_key(); + + // Add a new key + driver.add_key_to_keys(&peer_key).unwrap(); + + // Remove the key + driver.remove_key_from_keys(&peer_key.key()).unwrap(); + + assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); + }*/ + + /*pub fn it_should_remove_an_expiring_authentication_key(driver: &Arc>) { + let peer_key = generate_key(Some(Duration::from_secs(120))); + + // Add a new key + driver.add_key_to_keys(&peer_key).unwrap(); + + // Remove the key + driver.remove_key_from_keys(&peer_key.key()).unwrap(); + + assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); + }*/ + } +} diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index a30d75b90..39ef8f55b 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -255,9 +255,15 @@ impl Database for Mysql { #[cfg(test)] mod tests { + use std::sync::Arc; + /* We run a MySQL container and run all the tests against the same container and database. + Test for this driver are executed with: + + `TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST=true cargo test` + The `Database`` trait is very simple and we only have one driver that needs a container. In the future we might want to use different approaches like: @@ -267,13 +273,12 @@ mod tests { If we increase the number of methods or the number or drivers. */ - use std::time::Duration; - use testcontainers::runners::AsyncRunner; use testcontainers::{ContainerAsync, GenericImage}; use torrust_tracker_configuration::Core; use super::Mysql; + use crate::databases::driver::tests::run_tests; use crate::databases::Database; #[derive(Debug, Default)] @@ -351,22 +356,13 @@ mod tests { config } - fn initialize_driver(config: &Core) -> Mysql { - Mysql::new(&config.database.path).unwrap() - } - - async fn create_database_tables(driver: &Mysql) -> Result<(), Box> { - for _ in 0..5 { - if driver.create_database_tables().is_ok() { - return Ok(()); - } - tokio::time::sleep(Duration::from_secs(2)).await; - } - Err("MySQL is not ready after retries.".into()) + fn initialize_driver(config: &Core) -> Arc> { + let driver: Arc> = Arc::new(Box::new(Mysql::new(&config.database.path).unwrap())); + driver } #[tokio::test] - async fn run() -> Result<(), Box> { + async fn run_mysql_driver_tests() -> Result<(), Box> { if std::env::var("TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST").is_err() { println!("Skipping the MySQL driver tests."); return Ok(()); @@ -385,115 +381,10 @@ mod tests { let driver = initialize_driver(&config); - // Since the interface is very simple and there are no conflicts between - // tests, we share the same database. If we want to isolate the tests in - // the future, we can create a new database for each test. - create_database_tables(&driver).await?; - - // todo: truncate tables otherwise they will increase in size over time. - // That's not a problem on CI when the database is always newly created. - - handling_torrent_persistence::it_should_save_and_load_persistent_torrents(&driver); - - // Permanent keys - //handling_authentication_keys::it_should_save_and_load_permanent_authentication_keys(&driver); - //handling_authentication_keys::it_should_remove_a_permanent_authentication_key(&driver); - - // Expiring keys - handling_authentication_keys::it_should_save_and_load_expiring_authentication_keys(&driver); - //handling_authentication_keys::it_should_remove_an_expiring_authentication_key(&driver); - - driver.drop_database_tables().unwrap(); + run_tests(&driver).await; mysql_container.stop().await; Ok(()) } - - mod handling_torrent_persistence { - - use crate::core_tests::sample_info_hash; - use crate::databases::Database; - - pub fn it_should_save_and_load_persistent_torrents(driver: &impl Database) { - let infohash = sample_info_hash(); - - let number_of_downloads = 1; - - driver.save_persistent_torrent(&infohash, number_of_downloads).unwrap(); - - let torrents = driver.load_persistent_torrents().unwrap(); - - assert_eq!(torrents.len(), 1); - assert_eq!(torrents.get(&infohash), Some(number_of_downloads).as_ref()); - } - } - - mod handling_authentication_keys { - - use std::time::Duration; - - use crate::authentication::key::generate_key; - use crate::databases::Database; - - /*pub fn it_should_save_and_load_permanent_authentication_keys(driver: &impl Database) { - // Add a new permanent key - let peer_key = generate_permanent_key(); - driver.add_key_to_keys(&peer_key).unwrap(); - - // Get the key back - let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); - - assert_eq!(stored_peer_key, peer_key); - }*/ - - pub fn it_should_save_and_load_expiring_authentication_keys(driver: &impl Database) { - // Add a new expiring key - let peer_key = generate_key(Some(Duration::from_secs(120))); - driver.add_key_to_keys(&peer_key).unwrap(); - - // Get the key back - let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); - - /* todo: - - The expiration time recovered from the database is not the same - as the one we set. It includes a small offset (nanoseconds). - - left: PeerKey { key: Key("7HP1NslpuQn6kLVAgAF4nFpnZNSQ4hrx"), valid_until: Some(1739182308s) } - right: PeerKey { key: Key("7HP1NslpuQn6kLVAgAF4nFpnZNSQ4hrx"), valid_until: Some(1739182308.603691299s) - - */ - - assert_eq!(stored_peer_key.key(), peer_key.key()); - assert_eq!( - stored_peer_key.valid_until.unwrap().as_secs(), - peer_key.valid_until.unwrap().as_secs() - ); - } - - /*pub fn it_should_remove_a_permanent_authentication_key(driver: &impl Database) { - let peer_key = generate_permanent_key(); - - // Add a new key - driver.add_key_to_keys(&peer_key).unwrap(); - - // Remove the key - driver.remove_key_from_keys(&peer_key.key()).unwrap(); - - assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); - }*/ - - /*pub fn it_should_remove_an_expiring_authentication_key(driver: &impl Database) { - let peer_key = generate_key(Some(Duration::from_secs(120))); - - // Add a new key - driver.add_key_to_keys(&peer_key).unwrap(); - - // Remove the key - driver.remove_key_from_keys(&peer_key.key()).unwrap(); - - assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); - }*/ - } } diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs index e04cf6110..37f5254a5 100644 --- a/packages/tracker-core/src/databases/driver/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -292,112 +292,35 @@ impl Database for Sqlite { #[cfg(test)] mod tests { - mod the_sqlite_driver { - use torrust_tracker_configuration::Core; - use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; - - use crate::databases::driver::sqlite::Sqlite; - use crate::databases::Database; - - fn initialize_driver_and_database() -> Sqlite { - let config = ephemeral_configuration(); - let driver = Sqlite::new(&config.database.path).unwrap(); - driver.create_database_tables().unwrap(); - driver - } - - fn ephemeral_configuration() -> Core { - let mut config = Core::default(); - let temp_file = ephemeral_sqlite_database(); - temp_file.to_str().unwrap().clone_into(&mut config.database.path); - config - } - - mod handling_torrent_persistence { - - use crate::core_tests::sample_info_hash; - use crate::databases::driver::sqlite::tests::the_sqlite_driver::initialize_driver_and_database; - use crate::databases::Database; - - #[test] - fn it_should_save_and_load_persistent_torrents() { - let driver = initialize_driver_and_database(); - - let infohash = sample_info_hash(); - - let number_of_downloads = 1; - - driver.save_persistent_torrent(&infohash, number_of_downloads).unwrap(); - - let torrents = driver.load_persistent_torrents().unwrap(); - - assert_eq!(torrents.len(), 1); - assert_eq!(torrents.get(&infohash), Some(number_of_downloads).as_ref()); - } - } - - mod handling_authentication_keys { - use std::time::Duration; - - use crate::authentication::key::{generate_key, generate_permanent_key}; - use crate::databases::driver::sqlite::tests::the_sqlite_driver::initialize_driver_and_database; - use crate::databases::Database; + use std::sync::Arc; - #[test] - fn it_should_save_and_load_permanent_authentication_keys() { - let driver = initialize_driver_and_database(); + use torrust_tracker_configuration::Core; + use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; - // Add a new permanent key - let peer_key = generate_permanent_key(); - driver.add_key_to_keys(&peer_key).unwrap(); + use crate::databases::driver::sqlite::Sqlite; + use crate::databases::driver::tests::run_tests; + use crate::databases::Database; - // Get the key back - let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); - - assert_eq!(stored_peer_key, peer_key); - } - #[test] - fn it_should_save_and_load_expiring_authentication_keys() { - let driver = initialize_driver_and_database(); - - // Add a new expiring key - let peer_key = generate_key(Some(Duration::from_secs(120))); - driver.add_key_to_keys(&peer_key).unwrap(); - - // Get the key back - let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); - - /* todo: - - The expiration time recovered from the database is not the same - as the one we set. It includes a small offset (nanoseconds). - - left: PeerKey { key: Key("7HP1NslpuQn6kLVAgAF4nFpnZNSQ4hrx"), valid_until: Some(1739182308s) } - right: PeerKey { key: Key("7HP1NslpuQn6kLVAgAF4nFpnZNSQ4hrx"), valid_until: Some(1739182308.603691299s) - - */ - - assert_eq!(stored_peer_key.key(), peer_key.key()); - assert_eq!( - stored_peer_key.valid_until.unwrap().as_secs(), - peer_key.valid_until.unwrap().as_secs() - ); - } + fn ephemeral_configuration() -> Core { + let mut config = Core::default(); + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + config + } - #[test] - fn it_should_remove_an_authentication_key() { - let driver = initialize_driver_and_database(); + fn initialize_driver(config: &Core) -> Arc> { + let driver: Arc> = Arc::new(Box::new(Sqlite::new(&config.database.path).unwrap())); + driver + } - let peer_key = generate_key(None); + #[tokio::test] + async fn run_sqlite_driver_tests() -> Result<(), Box> { + let config = ephemeral_configuration(); - // Add a new key - driver.add_key_to_keys(&peer_key).unwrap(); + let driver = initialize_driver(&config); - // Remove the key - driver.remove_key_from_keys(&peer_key.key()).unwrap(); + run_tests(&driver).await; - assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); - } - } + Ok(()) } } From 595397b74d0542900ca61c585420092c86d8aee2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Feb 2025 19:36:04 +0000 Subject: [PATCH 0738/1297] fix: [#1257] bug 1. permanent keys can't be created in MySQL --- .../tracker-core/src/databases/driver/mod.rs | 9 +++++---- .../src/databases/driver/mysql.rs | 20 +++++++++---------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index 30888375e..7b42475a6 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -95,6 +95,7 @@ mod tests { // Since the interface is very simple and there are no conflicts between // tests, we share the same database. If we want to isolate the tests in // the future, we can create a new database for each test. + create_database_tables(driver).await.unwrap(); // todo: truncate tables otherwise they will increase in size over time. @@ -103,7 +104,7 @@ mod tests { handling_torrent_persistence::it_should_save_and_load_persistent_torrents(driver); // Permanent keys - //handling_authentication_keys::it_should_save_and_load_permanent_authentication_keys(&driver); + handling_authentication_keys::it_should_save_and_load_permanent_authentication_keys(driver); //handling_authentication_keys::it_should_remove_a_permanent_authentication_key(&driver); // Expiring keys @@ -149,10 +150,10 @@ mod tests { use std::sync::Arc; use std::time::Duration; - use crate::authentication::key::generate_key; + use crate::authentication::key::{generate_key, generate_permanent_key}; use crate::databases::Database; - /*pub fn it_should_save_and_load_permanent_authentication_keys(driver: &Arc>) { + pub fn it_should_save_and_load_permanent_authentication_keys(driver: &Arc>) { // Add a new permanent key let peer_key = generate_permanent_key(); driver.add_key_to_keys(&peer_key).unwrap(); @@ -161,7 +162,7 @@ mod tests { let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); assert_eq!(stored_peer_key, peer_key); - }*/ + } pub fn it_should_save_and_load_expiring_authentication_keys(driver: &Arc>) { // Add a new expiring key diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index 39ef8f55b..976a26d49 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -229,16 +229,16 @@ impl Database for Mysql { fn add_key_to_keys(&self, auth_key: &authentication::PeerKey) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - let key = auth_key.key.to_string(); - let valid_until = match auth_key.valid_until { - Some(valid_until) => valid_until.as_secs().to_string(), - None => todo!(), - }; - - conn.exec_drop( - "INSERT INTO `keys` (`key`, valid_until) VALUES (:key, :valid_until)", - params! { key, valid_until }, - )?; + match auth_key.valid_until { + Some(valid_until) => conn.exec_drop( + "INSERT INTO `keys` (`key`, valid_until) VALUES (:key, :valid_until)", + params! { "key" => auth_key.key.to_string(), "valid_until" => valid_until.as_secs().to_string() }, + )?, + None => conn.exec_drop( + "INSERT INTO `keys` (`key`) VALUES (:key)", + params! { "key" => auth_key.key.to_string() }, + )?, + } Ok(1) } From b94179dd1f742fd429b6765e3a04936cc3373331 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Feb 2025 19:41:03 +0000 Subject: [PATCH 0739/1297] fix: [#1257] bug 2. Auth keys can't be removed in MySQL --- packages/tracker-core/README.md | 4 ++-- .../tracker-core/src/databases/driver/mod.rs | 20 +++++++++++++------ .../src/databases/driver/mysql.rs | 2 +- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/tracker-core/README.md b/packages/tracker-core/README.md index dfb57f304..f80243d29 100644 --- a/packages/tracker-core/README.md +++ b/packages/tracker-core/README.md @@ -23,13 +23,13 @@ TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST=true cargo test Show coverage report: ```console -cargo +stable llvm-cov +TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST=true cargo +stable llvm-cov ``` Export coverage report to `lcov` format: ```console -cargo +stable llvm-cov --lcov --output-path=./.coverage/lcov.info +TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST=true cargo +stable llvm-cov --lcov --output-path=./.coverage/lcov.info ``` If you use Visual Studio Code, you can use the [Coverage Gutters](https://marketplace.visualstudio.com/items?itemName=semasquare.vscode-coverage-gutters) extension to view the coverage lines. diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index 7b42475a6..1f0b54a57 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -101,15 +101,23 @@ mod tests { // todo: truncate tables otherwise they will increase in size over time. // That's not a problem on CI when the database is always newly created. + // Persistent torrents (stats) + handling_torrent_persistence::it_should_save_and_load_persistent_torrents(driver); + // Authentication keys (for private trackers) + // Permanent keys handling_authentication_keys::it_should_save_and_load_permanent_authentication_keys(driver); - //handling_authentication_keys::it_should_remove_a_permanent_authentication_key(&driver); + handling_authentication_keys::it_should_remove_a_permanent_authentication_key(driver); // Expiring keys handling_authentication_keys::it_should_save_and_load_expiring_authentication_keys(driver); - //handling_authentication_keys::it_should_remove_an_expiring_authentication_key(&driver); + handling_authentication_keys::it_should_remove_an_expiring_authentication_key(driver); + + // Whitelist (for listed trackers) + + // todo driver.drop_database_tables().unwrap(); } @@ -189,7 +197,7 @@ mod tests { ); } - /*pub fn it_should_remove_a_permanent_authentication_key(driver: &Arc>) { + pub fn it_should_remove_a_permanent_authentication_key(driver: &Arc>) { let peer_key = generate_permanent_key(); // Add a new key @@ -199,9 +207,9 @@ mod tests { driver.remove_key_from_keys(&peer_key.key()).unwrap(); assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); - }*/ + } - /*pub fn it_should_remove_an_expiring_authentication_key(driver: &Arc>) { + pub fn it_should_remove_an_expiring_authentication_key(driver: &Arc>) { let peer_key = generate_key(Some(Duration::from_secs(120))); // Add a new key @@ -211,6 +219,6 @@ mod tests { driver.remove_key_from_keys(&peer_key.key()).unwrap(); assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); - }*/ + } } } diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index 976a26d49..a739832d6 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -247,7 +247,7 @@ impl Database for Mysql { fn remove_key_from_keys(&self, key: &Key) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - conn.exec_drop("DELETE FROM `keys` WHERE key = :key", params! { "key" => key.to_string() })?; + conn.exec_drop("DELETE FROM `keys` WHERE `key` = :key", params! { "key" => key.to_string() })?; Ok(1) } From 613efb26b7f020169bceb03d86300dae2d24ed10 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Feb 2025 20:30:19 +0000 Subject: [PATCH 0740/1297] fix: [#1257] bug 3. Expiring auth keys ignore fractions of seconds The `Duration` of a peer Key can have gractions of seconds. However we only store seconds (integer) in the database. When comparing peer keys we should ignore the fractions. --- .../src/authentication/key/peer_key.rs | 23 +++++++++++++++++-- .../tracker-core/src/databases/driver/mod.rs | 17 ++------------ 2 files changed, 23 insertions(+), 17 deletions(-) diff --git a/packages/tracker-core/src/authentication/key/peer_key.rs b/packages/tracker-core/src/authentication/key/peer_key.rs index a3045e54e..1d2b1fadc 100644 --- a/packages/tracker-core/src/authentication/key/peer_key.rs +++ b/packages/tracker-core/src/authentication/key/peer_key.rs @@ -1,4 +1,5 @@ use std::str::FromStr; +use std::time::Duration; use derive_more::Display; use rand::distr::Alphanumeric; @@ -12,7 +13,7 @@ use super::AUTH_KEY_LENGTH; /// An authentication key which can potentially have an expiration time. /// After that time is will automatically become invalid. -#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] +#[derive(Serialize, Deserialize, Debug, Clone)] pub struct PeerKey { /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` pub key: Key, @@ -22,6 +23,21 @@ pub struct PeerKey { pub valid_until: Option, } +impl PartialEq for PeerKey { + fn eq(&self, other: &Self) -> bool { + // We ignore the fractions of seconds when comparing the timestamps + // because we only store the seconds in the database. + self.key == other.key + && match (&self.valid_until, &other.valid_until) { + (Some(a), Some(b)) => a.as_secs() == b.as_secs(), + (None, None) => true, + _ => false, + } + } +} + +impl Eq for PeerKey {} + impl std::fmt::Display for PeerKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self.expiry_time() { @@ -47,7 +63,10 @@ impl PeerKey { /// (this will naturally happen in 292.5 billion years) #[must_use] pub fn expiry_time(&self) -> Option> { - self.valid_until.map(convert_from_timestamp_to_datetime_utc) + // We remove the fractions of seconds because we only store the seconds + // in the database. + self.valid_until + .map(|valid_until| convert_from_timestamp_to_datetime_utc(Duration::from_secs(valid_until.as_secs()))) } } diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index 1f0b54a57..557633b81 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -180,21 +180,8 @@ mod tests { // Get the key back let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); - /* todo: - - The expiration time recovered from the database is not the same - as the one we set. It includes a small offset (nanoseconds). - - left: PeerKey { key: Key("7HP1NslpuQn6kLVAgAF4nFpnZNSQ4hrx"), valid_until: Some(1739182308s) } - right: PeerKey { key: Key("7HP1NslpuQn6kLVAgAF4nFpnZNSQ4hrx"), valid_until: Some(1739182308.603691299s) - - */ - - assert_eq!(stored_peer_key.key(), peer_key.key()); - assert_eq!( - stored_peer_key.valid_until.unwrap().as_secs(), - peer_key.valid_until.unwrap().as_secs() - ); + assert_eq!(stored_peer_key, peer_key); + assert_eq!(stored_peer_key.expiry_time(), peer_key.expiry_time()); } pub fn it_should_remove_a_permanent_authentication_key(driver: &Arc>) { From b9188c74b9d2f08994ec5caf48bfba2d89b6a525 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Feb 2025 20:50:53 +0000 Subject: [PATCH 0741/1297] test: [#1251] add tests for whitelist is DB drivers --- packages/tracker-core/src/core_tests.rs | 11 ++++ .../tracker-core/src/databases/driver/mod.rs | 62 +++++++++++++++---- 2 files changed, 61 insertions(+), 12 deletions(-) diff --git a/packages/tracker-core/src/core_tests.rs b/packages/tracker-core/src/core_tests.rs index 53049f326..165c8790e 100644 --- a/packages/tracker-core/src/core_tests.rs +++ b/packages/tracker-core/src/core_tests.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; +use rand::Rng; use torrust_tracker_configuration::Configuration; #[cfg(test)] use torrust_tracker_configuration::Core; @@ -20,6 +21,16 @@ use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; use super::whitelist::repository::in_memory::InMemoryWhitelist; use super::whitelist::{self}; +/// Generates a random `InfoHash`. +#[must_use] +pub fn random_info_hash() -> InfoHash { + let mut rng = rand::rng(); + let mut random_bytes = [0u8; 20]; + rng.fill(&mut random_bytes); + + InfoHash::from_bytes(&random_bytes) +} + /// # Panics /// /// Will panic if the string representation of the info hash is not a valid info hash. diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index 557633b81..f4e165f00 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -117,7 +117,10 @@ mod tests { // Whitelist (for listed trackers) - // todo + handling_the_whitelist::it_should_add_and_get_infohashes(driver); + handling_the_whitelist::it_should_remove_an_infohash_from_the_whitelist(driver); + handling_the_whitelist::it_should_fail_trying_to_add_the_same_infohash_twice(driver); + handling_the_whitelist::it_load_the_whitelist(driver); driver.drop_database_tables().unwrap(); } @@ -129,7 +132,7 @@ mod tests { } tokio::time::sleep(Duration::from_secs(2)).await; } - Err("MySQL is not ready after retries.".into()) + Err("Database is not ready after retries.".into()) } mod handling_torrent_persistence { @@ -162,22 +165,18 @@ mod tests { use crate::databases::Database; pub fn it_should_save_and_load_permanent_authentication_keys(driver: &Arc>) { - // Add a new permanent key let peer_key = generate_permanent_key(); driver.add_key_to_keys(&peer_key).unwrap(); - // Get the key back let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); assert_eq!(stored_peer_key, peer_key); } pub fn it_should_save_and_load_expiring_authentication_keys(driver: &Arc>) { - // Add a new expiring key let peer_key = generate_key(Some(Duration::from_secs(120))); driver.add_key_to_keys(&peer_key).unwrap(); - // Get the key back let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); assert_eq!(stored_peer_key, peer_key); @@ -186,11 +185,8 @@ mod tests { pub fn it_should_remove_a_permanent_authentication_key(driver: &Arc>) { let peer_key = generate_permanent_key(); - - // Add a new key driver.add_key_to_keys(&peer_key).unwrap(); - // Remove the key driver.remove_key_from_keys(&peer_key.key()).unwrap(); assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); @@ -198,14 +194,56 @@ mod tests { pub fn it_should_remove_an_expiring_authentication_key(driver: &Arc>) { let peer_key = generate_key(Some(Duration::from_secs(120))); - - // Add a new key driver.add_key_to_keys(&peer_key).unwrap(); - // Remove the key driver.remove_key_from_keys(&peer_key.key()).unwrap(); assert!(driver.get_key_from_keys(&peer_key.key()).unwrap().is_none()); } } + + mod handling_the_whitelist { + + use std::sync::Arc; + + use crate::core_tests::random_info_hash; + use crate::databases::Database; + + pub fn it_should_add_and_get_infohashes(driver: &Arc>) { + let infohash = random_info_hash(); + + driver.add_info_hash_to_whitelist(infohash).unwrap(); + + let stored_infohash = driver.get_info_hash_from_whitelist(infohash).unwrap().unwrap(); + + assert_eq!(stored_infohash, infohash); + } + + pub fn it_should_remove_an_infohash_from_the_whitelist(driver: &Arc>) { + let infohash = random_info_hash(); + driver.add_info_hash_to_whitelist(infohash).unwrap(); + + driver.remove_info_hash_from_whitelist(infohash).unwrap(); + + assert!(driver.get_info_hash_from_whitelist(infohash).unwrap().is_none()); + } + + pub fn it_should_fail_trying_to_add_the_same_infohash_twice(driver: &Arc>) { + let infohash = random_info_hash(); + + driver.add_info_hash_to_whitelist(infohash).unwrap(); + let result = driver.add_info_hash_to_whitelist(infohash); + + assert!(result.is_err()); + } + + pub fn it_load_the_whitelist(driver: &Arc>) { + let infohash = random_info_hash(); + driver.add_info_hash_to_whitelist(infohash).unwrap(); + + let whitelist = driver.load_whitelist().unwrap(); + + assert!(whitelist.contains(&infohash)); + } + } } From 700482d14c0a5e417423548a92630f9a58f1b014 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 11 Feb 2025 10:48:29 +0000 Subject: [PATCH 0742/1297] test: [#1251] reset database before running db driver tests --- .../tracker-core/src/databases/driver/mod.rs | 21 ++++++++++++++----- .../src/databases/driver/mysql.rs | 2 +- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index f4e165f00..07d338915 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -96,10 +96,7 @@ mod tests { // tests, we share the same database. If we want to isolate the tests in // the future, we can create a new database for each test. - create_database_tables(driver).await.unwrap(); - - // todo: truncate tables otherwise they will increase in size over time. - // That's not a problem on CI when the database is always newly created. + database_setup(driver).await; // Persistent torrents (stats) @@ -121,8 +118,22 @@ mod tests { handling_the_whitelist::it_should_remove_an_infohash_from_the_whitelist(driver); handling_the_whitelist::it_should_fail_trying_to_add_the_same_infohash_twice(driver); handling_the_whitelist::it_load_the_whitelist(driver); + } - driver.drop_database_tables().unwrap(); + /// It initializes the database schema. + /// + /// Since the drop SQL queries don't check if the tables already exist, + /// we have to create them first, and then drop them. + /// + /// The method to drop tables does not use "DROP TABLE IF EXISTS". We can + /// change this function when we update the `Database::drop_database_tables` + /// method to use "DROP TABLE IF EXISTS". + async fn database_setup(driver: &Arc>) { + create_database_tables(driver).await.expect("database tables creation failed"); + driver.drop_database_tables().expect("old database tables deletion failed"); + create_database_tables(driver) + .await + .expect("database tables creation from empty schema failed"); } async fn create_database_tables(driver: &Arc>) -> Result<(), Box> { diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index a739832d6..1e1e29f36 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -264,7 +264,7 @@ mod tests { `TORRUST_TRACKER_CORE_RUN_MYSQL_DRIVER_TEST=true cargo test` - The `Database`` trait is very simple and we only have one driver that needs + The `Database` trait is very simple and we only have one driver that needs a container. In the future we might want to use different approaches like: - https://github.com/testcontainers/testcontainers-rs/issues/707 From adb96141590c7ae1bbd1bf76b1de0d54d2ca8d07 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 11 Feb 2025 11:05:52 +0000 Subject: [PATCH 0743/1297] tests: [#1251] add test for loading keys in DB drivers --- .../src/authentication/key/mod.rs | 6 +++ .../tracker-core/src/databases/driver/mod.rs | 41 +++++++++++++------ 2 files changed, 34 insertions(+), 13 deletions(-) diff --git a/packages/tracker-core/src/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs index 33b3b6099..8ec368ebc 100644 --- a/packages/tracker-core/src/authentication/key/mod.rs +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -67,6 +67,12 @@ pub fn generate_permanent_key() -> PeerKey { generate_key(None) } +/// It generates a new expiring random key [`PeerKey`]. +#[must_use] +pub fn generate_expiring_key(lifetime: Duration) -> PeerKey { + generate_key(Some(lifetime)) +} + /// It generates a new random 32-char authentication [`PeerKey`]. /// /// It can be an expiring or permanent key. diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index 07d338915..1e42e4414 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -104,6 +104,8 @@ mod tests { // Authentication keys (for private trackers) + handling_authentication_keys::it_should_load_the_keys(driver); + // Permanent keys handling_authentication_keys::it_should_save_and_load_permanent_authentication_keys(driver); handling_authentication_keys::it_should_remove_a_permanent_authentication_key(driver); @@ -114,10 +116,10 @@ mod tests { // Whitelist (for listed trackers) + handling_the_whitelist::it_should_load_the_whitelist(driver); handling_the_whitelist::it_should_add_and_get_infohashes(driver); handling_the_whitelist::it_should_remove_an_infohash_from_the_whitelist(driver); handling_the_whitelist::it_should_fail_trying_to_add_the_same_infohash_twice(driver); - handling_the_whitelist::it_load_the_whitelist(driver); } /// It initializes the database schema. @@ -172,9 +174,22 @@ mod tests { use std::sync::Arc; use std::time::Duration; - use crate::authentication::key::{generate_key, generate_permanent_key}; + use crate::authentication::key::{generate_expiring_key, generate_permanent_key}; use crate::databases::Database; + pub fn it_should_load_the_keys(driver: &Arc>) { + let permanent_peer_key = generate_permanent_key(); + driver.add_key_to_keys(&permanent_peer_key).unwrap(); + + let expiring_peer_key = generate_expiring_key(Duration::from_secs(120)); + driver.add_key_to_keys(&expiring_peer_key).unwrap(); + + let keys = driver.load_keys().unwrap(); + + assert!(keys.contains(&permanent_peer_key)); + assert!(keys.contains(&expiring_peer_key)); + } + pub fn it_should_save_and_load_permanent_authentication_keys(driver: &Arc>) { let peer_key = generate_permanent_key(); driver.add_key_to_keys(&peer_key).unwrap(); @@ -185,7 +200,7 @@ mod tests { } pub fn it_should_save_and_load_expiring_authentication_keys(driver: &Arc>) { - let peer_key = generate_key(Some(Duration::from_secs(120))); + let peer_key = generate_expiring_key(Duration::from_secs(120)); driver.add_key_to_keys(&peer_key).unwrap(); let stored_peer_key = driver.get_key_from_keys(&peer_key.key()).unwrap().unwrap(); @@ -204,7 +219,7 @@ mod tests { } pub fn it_should_remove_an_expiring_authentication_key(driver: &Arc>) { - let peer_key = generate_key(Some(Duration::from_secs(120))); + let peer_key = generate_expiring_key(Duration::from_secs(120)); driver.add_key_to_keys(&peer_key).unwrap(); driver.remove_key_from_keys(&peer_key.key()).unwrap(); @@ -220,6 +235,15 @@ mod tests { use crate::core_tests::random_info_hash; use crate::databases::Database; + pub fn it_should_load_the_whitelist(driver: &Arc>) { + let infohash = random_info_hash(); + driver.add_info_hash_to_whitelist(infohash).unwrap(); + + let whitelist = driver.load_whitelist().unwrap(); + + assert!(whitelist.contains(&infohash)); + } + pub fn it_should_add_and_get_infohashes(driver: &Arc>) { let infohash = random_info_hash(); @@ -247,14 +271,5 @@ mod tests { assert!(result.is_err()); } - - pub fn it_load_the_whitelist(driver: &Arc>) { - let infohash = random_info_hash(); - driver.add_info_hash_to_whitelist(infohash).unwrap(); - - let whitelist = driver.load_whitelist().unwrap(); - - assert!(whitelist.contains(&infohash)); - } } } From 2cd1c65cbff75895ec26dfc6943319cf2c665399 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 11 Feb 2025 11:34:43 +0000 Subject: [PATCH 0744/1297] test: [#1251] add tests for database driver error converters --- packages/tracker-core/src/databases/error.rs | 36 ++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/packages/tracker-core/src/databases/error.rs b/packages/tracker-core/src/databases/error.rs index 4d64baf48..0f3207587 100644 --- a/packages/tracker-core/src/databases/error.rs +++ b/packages/tracker-core/src/databases/error.rs @@ -102,3 +102,39 @@ impl From<(r2d2::Error, Driver)> for Error { } } } + +#[cfg(test)] +mod tests { + use r2d2_mysql::mysql; + + use crate::databases::error::Error; + + #[test] + fn it_should_build_a_database_error_from_a_rusqlite_error() { + let err: Error = r2d2_sqlite::rusqlite::Error::InvalidQuery.into(); + + assert!(matches!(err, Error::InvalidQuery { .. })); + } + + #[test] + fn it_should_build_an_specific_database_error_from_a_no_rows_returned_rusqlite_error() { + let err: Error = r2d2_sqlite::rusqlite::Error::QueryReturnedNoRows.into(); + + assert!(matches!(err, Error::QueryReturnedNoRows { .. })); + } + + #[test] + fn it_should_build_a_database_error_from_a_mysql_error() { + let url_err = mysql::error::UrlError::BadUrl; + let err: Error = r2d2_mysql::mysql::Error::UrlError(url_err).into(); + + assert!(matches!(err, Error::InvalidQuery { .. })); + } + + #[test] + fn it_should_build_a_database_error_from_a_mysql_url_error() { + let err: Error = mysql::error::UrlError::BadUrl.into(); + + assert!(matches!(err, Error::ConnectionError { .. })); + } +} From 6639c98e4d61f9f1b4e52af7d7301dcef16dce1a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 11 Feb 2025 15:29:25 +0000 Subject: [PATCH 0745/1297] refactor: [#1258] make things private or pub(crate) when possible. Limit the exposed funtionality for pacakges. Specially the new `tracker-core` package which has not been published yet. --- packages/tracker-core/src/announce_handler.rs | 8 +- .../src/authentication/handler.rs | 8 +- .../src/authentication/key/mod.rs | 8 +- .../key/repository/in_memory.rs | 9 +- .../key/repository/persisted.rs | 6 +- packages/tracker-core/src/core_tests.rs | 215 ----------------- .../tracker-core/src/databases/driver/mod.rs | 8 +- .../src/databases/driver/mysql.rs | 2 +- .../src/databases/driver/sqlite.rs | 2 +- packages/tracker-core/src/error.rs | 2 +- packages/tracker-core/src/lib.rs | 8 +- packages/tracker-core/src/test_helpers.rs | 219 ++++++++++++++++++ packages/tracker-core/src/torrent/manager.rs | 8 +- packages/tracker-core/src/torrent/mod.rs | 9 +- .../src/torrent/repository/in_memory.rs | 35 +-- .../src/torrent/repository/persisted.rs | 6 +- packages/tracker-core/src/torrent/services.rs | 2 +- .../src/whitelist/authorization.rs | 4 +- .../tracker-core/src/whitelist/manager.rs | 6 +- packages/tracker-core/src/whitelist/mod.rs | 6 +- .../src/whitelist/repository/in_memory.rs | 6 +- .../src/whitelist/repository/persisted.rs | 8 +- .../src/whitelist/test_helpers.rs | 32 +++ .../src/whitelist/whitelist_tests.rs | 27 --- src/bootstrap/app.rs | 1 + src/servers/http/mod.rs | 1 + src/servers/http/test_helpers.rs | 16 ++ src/servers/http/v1/handlers/announce.rs | 2 +- src/servers/http/v1/services/announce.rs | 2 +- src/servers/http/v1/services/scrape.rs | 11 +- 30 files changed, 357 insertions(+), 320 deletions(-) delete mode 100644 packages/tracker-core/src/core_tests.rs create mode 100644 packages/tracker-core/src/test_helpers.rs create mode 100644 packages/tracker-core/src/whitelist/test_helpers.rs delete mode 100644 packages/tracker-core/src/whitelist/whitelist_tests.rs create mode 100644 src/servers/http/test_helpers.rs diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 85dd354bf..cd0a9b861 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -182,8 +182,8 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::announce_handler::AnnounceHandler; - use crate::core_tests::initialize_handlers; use crate::scrape_handler::ScrapeHandler; + use crate::test_helpers::tests::initialize_handlers; fn public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); @@ -244,7 +244,7 @@ mod tests { peer_ip, public_tracker, sample_peer_1, sample_peer_2, sample_peer_3, }; use crate::announce_handler::PeersWanted; - use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::test_helpers::tests::{sample_info_hash, sample_peer}; mod should_assign_the_ip_to_the_peer { @@ -411,7 +411,7 @@ mod tests { use crate::announce_handler::tests::the_announce_handler::{peer_ip, public_tracker}; use crate::announce_handler::PeersWanted; - use crate::core_tests::{completed_peer, leecher, sample_info_hash, seeder, started_peer}; + use crate::test_helpers::tests::{completed_peer, leecher, sample_info_hash, seeder, started_peer}; #[tokio::test] async fn when_the_peer_is_a_seeder() { @@ -474,8 +474,8 @@ mod tests { use crate::announce_handler::tests::the_announce_handler::peer_ip; use crate::announce_handler::{AnnounceHandler, PeersWanted}; - use crate::core_tests::{sample_info_hash, sample_peer}; use crate::databases::setup::initialize_database; + use crate::test_helpers::tests::{sample_info_hash, sample_peer}; use crate::torrent::manager::TorrentsManager; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; diff --git a/packages/tracker-core/src/authentication/handler.rs b/packages/tracker-core/src/authentication/handler.rs index f758830ac..136060916 100644 --- a/packages/tracker-core/src/authentication/handler.rs +++ b/packages/tracker-core/src/authentication/handler.rs @@ -132,7 +132,7 @@ impl KeysHandler { /// # Errors /// /// Will return a `database::Error` if unable to add the `auth_key` to the database. - pub async fn generate_permanent_peer_key(&self) -> Result { + pub(crate) async fn generate_permanent_peer_key(&self) -> Result { self.generate_expiring_peer_key(None).await } @@ -170,7 +170,7 @@ impl KeysHandler { /// # Arguments /// /// * `key` - The pre-generated key. - pub async fn add_permanent_peer_key(&self, key: Key) -> Result { + pub(crate) async fn add_permanent_peer_key(&self, key: Key) -> Result { self.add_expiring_peer_key(key, None).await } @@ -188,7 +188,7 @@ impl KeysHandler { /// * `key` - The pre-generated key. /// * `lifetime` - The duration in seconds for the new key. The key will be /// no longer valid after `lifetime` seconds. - pub async fn add_expiring_peer_key( + pub(crate) async fn add_expiring_peer_key( &self, key: Key, valid_until: Option, @@ -219,7 +219,7 @@ impl KeysHandler { } /// It removes an authentication key from memory. - pub async fn remove_in_memory_auth_key(&self, key: &Key) { + pub(crate) async fn remove_in_memory_auth_key(&self, key: &Key) { self.in_memory_key_repository.remove(key).await; } diff --git a/packages/tracker-core/src/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs index 8ec368ebc..fce18c0dd 100644 --- a/packages/tracker-core/src/authentication/key/mod.rs +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -59,17 +59,19 @@ pub type ParseKeyError = peer_key::ParseKeyError; /// /// For more information see function [`generate_key`](crate::authentication::key::generate_key) to generate the /// [`PeerKey`](crate::authentication::PeerKey). -pub const AUTH_KEY_LENGTH: usize = 32; +pub(crate) const AUTH_KEY_LENGTH: usize = 32; /// It generates a new permanent random key [`PeerKey`]. +#[cfg(test)] #[must_use] -pub fn generate_permanent_key() -> PeerKey { +pub(crate) fn generate_permanent_key() -> PeerKey { generate_key(None) } /// It generates a new expiring random key [`PeerKey`]. +#[cfg(test)] #[must_use] -pub fn generate_expiring_key(lifetime: Duration) -> PeerKey { +pub(crate) fn generate_expiring_key(lifetime: Duration) -> PeerKey { generate_key(Some(lifetime)) } diff --git a/packages/tracker-core/src/authentication/key/repository/in_memory.rs b/packages/tracker-core/src/authentication/key/repository/in_memory.rs index 0a2fc50cd..13664e27c 100644 --- a/packages/tracker-core/src/authentication/key/repository/in_memory.rs +++ b/packages/tracker-core/src/authentication/key/repository/in_memory.rs @@ -9,21 +9,22 @@ pub struct InMemoryKeyRepository { impl InMemoryKeyRepository { /// It adds a new authentication key. - pub async fn insert(&self, auth_key: &PeerKey) { + pub(crate) async fn insert(&self, auth_key: &PeerKey) { self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); } /// It removes an authentication key. - pub async fn remove(&self, key: &Key) { + pub(crate) async fn remove(&self, key: &Key) { self.keys.write().await.remove(key); } - pub async fn get(&self, key: &Key) -> Option { + pub(crate) async fn get(&self, key: &Key) -> Option { self.keys.read().await.get(key).cloned() } /// It clears all the authentication keys. - pub async fn clear(&self) { + #[allow(dead_code)] + pub(crate) async fn clear(&self) { let mut keys = self.keys.write().await; keys.clear(); } diff --git a/packages/tracker-core/src/authentication/key/repository/persisted.rs b/packages/tracker-core/src/authentication/key/repository/persisted.rs index 7edee62c0..95a3b874c 100644 --- a/packages/tracker-core/src/authentication/key/repository/persisted.rs +++ b/packages/tracker-core/src/authentication/key/repository/persisted.rs @@ -21,7 +21,7 @@ impl DatabaseKeyRepository { /// # Errors /// /// Will return a `databases::error::Error` if unable to add the `auth_key` to the database. - pub fn add(&self, peer_key: &PeerKey) -> Result<(), databases::error::Error> { + pub(crate) fn add(&self, peer_key: &PeerKey) -> Result<(), databases::error::Error> { self.database.add_key_to_keys(peer_key)?; Ok(()) } @@ -31,7 +31,7 @@ impl DatabaseKeyRepository { /// # Errors /// /// Will return a `database::Error` if unable to remove the `key` from the database. - pub fn remove(&self, key: &Key) -> Result<(), databases::error::Error> { + pub(crate) fn remove(&self, key: &Key) -> Result<(), databases::error::Error> { self.database.remove_key_from_keys(key)?; Ok(()) } @@ -41,7 +41,7 @@ impl DatabaseKeyRepository { /// # Errors /// /// Will return a `database::Error` if unable to load the keys from the database. - pub fn load_keys(&self) -> Result, databases::error::Error> { + pub(crate) fn load_keys(&self) -> Result, databases::error::Error> { let keys = self.database.load_keys()?; Ok(keys) } diff --git a/packages/tracker-core/src/core_tests.rs b/packages/tracker-core/src/core_tests.rs deleted file mode 100644 index 165c8790e..000000000 --- a/packages/tracker-core/src/core_tests.rs +++ /dev/null @@ -1,215 +0,0 @@ -//! Some generic test helpers functions. -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use std::sync::Arc; - -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; -use bittorrent_primitives::info_hash::InfoHash; -use rand::Rng; -use torrust_tracker_configuration::Configuration; -#[cfg(test)] -use torrust_tracker_configuration::Core; -use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_primitives::DurationSinceUnixEpoch; -#[cfg(test)] -use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; - -use super::announce_handler::AnnounceHandler; -use super::databases::setup::initialize_database; -use super::scrape_handler::ScrapeHandler; -use super::torrent::repository::in_memory::InMemoryTorrentRepository; -use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; -use super::whitelist::repository::in_memory::InMemoryWhitelist; -use super::whitelist::{self}; - -/// Generates a random `InfoHash`. -#[must_use] -pub fn random_info_hash() -> InfoHash { - let mut rng = rand::rng(); - let mut random_bytes = [0u8; 20]; - rng.fill(&mut random_bytes); - - InfoHash::from_bytes(&random_bytes) -} - -/// # Panics -/// -/// Will panic if the string representation of the info hash is not a valid info hash. -#[must_use] -pub fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 - .parse::() - .expect("String should be a valid info hash") -} - -/// # Panics -/// -/// Will panic if the string representation of the info hash is not a valid info hash. -#[must_use] -pub fn sample_info_hash_one() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 - .parse::() - .expect("String should be a valid info hash") -} - -/// # Panics -/// -/// Will panic if the string representation of the info hash is not a valid info hash. -#[must_use] -pub fn sample_info_hash_two() -> InfoHash { - "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1" // DevSkim: ignore DS173237 - .parse::() - .expect("String should be a valid info hash") -} - -/// # Panics -/// -/// Will panic if the string representation of the info hash is not a valid info hash. -#[must_use] -pub fn sample_info_hash_alphabetically_ordered_after_sample_info_hash_one() -> InfoHash { - "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1" // DevSkim: ignore DS173237 - .parse::() - .expect("String should be a valid info hash") -} - -/// Sample peer whose state is not relevant for the tests. -#[must_use] -pub fn sample_peer() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - } -} - -#[must_use] -pub fn sample_peer_one() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000001"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - } -} - -#[must_use] -pub fn sample_peer_two() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000002"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8082), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - } -} - -#[must_use] -pub fn seeder() -> Peer { - complete_peer() -} - -#[must_use] -pub fn leecher() -> Peer { - incomplete_peer() -} - -#[must_use] -pub fn started_peer() -> Peer { - incomplete_peer() -} - -#[must_use] -pub fn completed_peer() -> Peer { - complete_peer() -} - -/// A peer that counts as `complete` is swarm metadata -/// IMPORTANT!: it only counts if the it has been announce at least once before -/// announcing the `AnnounceEvent::Completed` event. -#[must_use] -pub fn complete_peer() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - } -} - -/// A peer that counts as `incomplete` is swarm metadata -#[must_use] -pub fn incomplete_peer() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(1000), // Still bytes to download - event: AnnounceEvent::Started, - } -} - -#[must_use] -pub fn initialize_handlers(config: &Configuration) -> (Arc, Arc) { - let database = initialize_database(&config.core); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( - &config.core, - &in_memory_whitelist.clone(), - )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - (announce_handler, scrape_handler) -} - -/// # Panics -/// -/// Will panic if the temporary database file path is not a valid UFT string. -#[cfg(test)] -#[must_use] -pub fn ephemeral_configuration() -> Core { - let mut config = Core::default(); - - let temp_file = ephemeral_sqlite_database(); - temp_file.to_str().unwrap().clone_into(&mut config.database.path); - - config -} - -/// # Panics -/// -/// Will panic if the temporary database file path is not a valid UFT string. -#[cfg(test)] -#[must_use] -pub fn ephemeral_configuration_for_listed_tracker() -> Core { - let mut config = Core { - listed: true, - ..Default::default() - }; - - let temp_file = ephemeral_sqlite_database(); - temp_file.to_str().unwrap().clone_into(&mut config.database.path); - - config -} diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index 1e42e4414..2bc6a1e3c 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -73,7 +73,7 @@ pub mod sqlite; /// # Errors /// /// Will return `Error` if unable to build the driver. -pub fn build(driver: &Driver, db_path: &str) -> Result, Error> { +pub(crate) fn build(driver: &Driver, db_path: &str) -> Result, Error> { let database: Box = match driver { Driver::Sqlite3 => Box::new(Sqlite::new(db_path)?), Driver::MySQL => Box::new(Mysql::new(db_path)?), @@ -85,7 +85,7 @@ pub fn build(driver: &Driver, db_path: &str) -> Result, Error> } #[cfg(test)] -mod tests { +pub(crate) mod tests { use std::sync::Arc; use std::time::Duration; @@ -152,8 +152,8 @@ mod tests { use std::sync::Arc; - use crate::core_tests::sample_info_hash; use crate::databases::Database; + use crate::test_helpers::tests::sample_info_hash; pub fn it_should_save_and_load_persistent_torrents(driver: &Arc>) { let infohash = sample_info_hash(); @@ -232,8 +232,8 @@ mod tests { use std::sync::Arc; - use crate::core_tests::random_info_hash; use crate::databases::Database; + use crate::test_helpers::tests::random_info_hash; pub fn it_should_load_the_whitelist(driver: &Arc>) { let infohash = random_info_hash(); diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index 1e1e29f36..365bd0ad9 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -15,7 +15,7 @@ use crate::authentication::{self, Key}; const DRIVER: Driver = Driver::MySQL; -pub struct Mysql { +pub(crate) struct Mysql { pool: Pool, } diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs index 37f5254a5..36ca4eabe 100644 --- a/packages/tracker-core/src/databases/driver/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -14,7 +14,7 @@ use crate::authentication::{self, Key}; const DRIVER: Driver = Driver::Sqlite3; -pub struct Sqlite { +pub(crate) struct Sqlite { pool: Pool, } diff --git a/packages/tracker-core/src/error.rs b/packages/tracker-core/src/error.rs index 515510b85..dcdd89668 100644 --- a/packages/tracker-core/src/error.rs +++ b/packages/tracker-core/src/error.rs @@ -41,8 +41,8 @@ mod tests { mod whitelist_error { - use crate::core_tests::sample_info_hash; use crate::error::WhitelistError; + use crate::test_helpers::tests::sample_info_hash; #[test] fn torrent_not_whitelisted() { diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index 9334e4a02..ecbaef9c5 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -391,8 +391,8 @@ pub mod scrape_handler; pub mod torrent; pub mod whitelist; -pub mod core_tests; pub mod peer_tests; +pub mod test_helpers; use torrust_tracker_clock::clock; /// This code needs to be copied into each crate. @@ -416,8 +416,8 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::announce_handler::AnnounceHandler; - use crate::core_tests::initialize_handlers; use crate::scrape_handler::ScrapeHandler; + use crate::test_helpers::tests::initialize_handlers; fn initialize_handlers_for_public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); @@ -445,7 +445,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::announce_handler::PeersWanted; - use crate::core_tests::{complete_peer, incomplete_peer}; + use crate::test_helpers::tests::{complete_peer, incomplete_peer}; use crate::tests::the_tracker::initialize_handlers_for_public_tracker; #[tokio::test] @@ -500,7 +500,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::announce_handler::PeersWanted; - use crate::core_tests::{complete_peer, incomplete_peer}; + use crate::test_helpers::tests::{complete_peer, incomplete_peer}; use crate::tests::the_tracker::{initialize_handlers_for_listed_tracker, peer_ip}; #[tokio::test] diff --git a/packages/tracker-core/src/test_helpers.rs b/packages/tracker-core/src/test_helpers.rs new file mode 100644 index 000000000..06f5ce384 --- /dev/null +++ b/packages/tracker-core/src/test_helpers.rs @@ -0,0 +1,219 @@ +//! Some generic test helpers functions. + +#[cfg(test)] +pub(crate) mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_primitives::info_hash::InfoHash; + use rand::Rng; + use torrust_tracker_configuration::Configuration; + #[cfg(test)] + use torrust_tracker_configuration::Core; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + #[cfg(test)] + use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; + + use crate::announce_handler::AnnounceHandler; + use crate::databases::setup::initialize_database; + use crate::scrape_handler::ScrapeHandler; + use crate::torrent::repository::in_memory::InMemoryTorrentRepository; + use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::whitelist::{self}; + + /// Generates a random `InfoHash`. + #[must_use] + pub fn random_info_hash() -> InfoHash { + let mut rng = rand::rng(); + let mut random_bytes = [0u8; 20]; + rng.fill(&mut random_bytes); + + InfoHash::from_bytes(&random_bytes) + } + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash_one() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash_two() -> InfoHash { + "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash_alphabetically_ordered_after_sample_info_hash_one() -> InfoHash { + "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// Sample peer whose state is not relevant for the tests. + #[must_use] + pub fn sample_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + #[must_use] + pub fn sample_peer_one() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000001"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + #[must_use] + pub fn sample_peer_two() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000002"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8082), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + #[must_use] + pub fn seeder() -> Peer { + complete_peer() + } + + #[must_use] + pub fn leecher() -> Peer { + incomplete_peer() + } + + #[must_use] + pub fn started_peer() -> Peer { + incomplete_peer() + } + + #[must_use] + pub fn completed_peer() -> Peer { + complete_peer() + } + + /// A peer that counts as `complete` is swarm metadata + /// IMPORTANT!: it only counts if the it has been announce at least once before + /// announcing the `AnnounceEvent::Completed` event. + #[must_use] + pub fn complete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + /// A peer that counts as `incomplete` is swarm metadata + #[must_use] + pub fn incomplete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(1000), // Still bytes to download + event: AnnounceEvent::Started, + } + } + + #[must_use] + pub fn initialize_handlers(config: &Configuration) -> (Arc, Arc) { + let database = initialize_database(&config.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( + &config.core, + &in_memory_whitelist.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + (announce_handler, scrape_handler) + } + + /// # Panics + /// + /// Will panic if the temporary database file path is not a valid UFT string. + #[cfg(test)] + #[must_use] + pub fn ephemeral_configuration() -> Core { + let mut config = Core::default(); + + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + + config + } + + /// # Panics + /// + /// Will panic if the temporary database file path is not a valid UFT string. + #[cfg(test)] + #[must_use] + pub fn ephemeral_configuration_for_listed_tracker() -> Core { + let mut config = Core { + listed: true, + ..Default::default() + }; + + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + + config + } +} diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index 778ac6d92..9dac35258 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -16,6 +16,7 @@ pub struct TorrentsManager { in_memory_torrent_repository: Arc, /// The persistent torrents repository. + #[allow(dead_code)] db_torrent_repository: Arc, } @@ -40,7 +41,8 @@ impl TorrentsManager { /// # Errors /// /// Will return a `database::Error` if unable to load the list of `persistent_torrents` from the database. - pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { + #[allow(dead_code)] + pub(crate) fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { let persistent_torrents = self.db_torrent_repository.load_all()?; self.in_memory_torrent_repository.import_persistent(&persistent_torrents); @@ -71,8 +73,8 @@ mod tests { use torrust_tracker_torrent_repository::entry::EntrySync; use super::{DatabasePersistentTorrentRepository, TorrentsManager}; - use crate::core_tests::{ephemeral_configuration, sample_info_hash}; use crate::databases::setup::initialize_database; + use crate::test_helpers::tests::{ephemeral_configuration, sample_info_hash}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; struct TorrentsManagerDeps { @@ -138,7 +140,7 @@ mod tests { use torrust_tracker_clock::clock::{self}; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::core_tests::{ephemeral_configuration, sample_info_hash, sample_peer}; + use crate::test_helpers::tests::{ephemeral_configuration, sample_info_hash, sample_peer}; use crate::torrent::manager::tests::{initialize_torrents_manager, initialize_torrents_manager_with}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; diff --git a/packages/tracker-core/src/torrent/mod.rs b/packages/tracker-core/src/torrent/mod.rs index 340f049d2..7ca9000f8 100644 --- a/packages/tracker-core/src/torrent/mod.rs +++ b/packages/tracker-core/src/torrent/mod.rs @@ -29,8 +29,11 @@ pub mod manager; pub mod repository; pub mod services; -use torrust_tracker_torrent_repository::{EntryMutexStd, TorrentsSkipMapMutexStd}; +#[cfg(test)] +use torrust_tracker_torrent_repository::EntryMutexStd; +use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; // Currently used types from the torrent repository crate. -pub type Torrents = TorrentsSkipMapMutexStd; -pub type TorrentEntry = EntryMutexStd; +pub(crate) type Torrents = TorrentsSkipMapMutexStd; +#[cfg(test)] +pub(crate) type TorrentEntry = EntryMutexStd; diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index baa0c4fdb..26302260b 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -32,33 +32,34 @@ impl InMemoryTorrentRepository { self.torrents.upsert_peer(info_hash, peer); } + #[cfg(test)] #[must_use] - pub fn remove(&self, key: &InfoHash) -> Option { + pub(crate) fn remove(&self, key: &InfoHash) -> Option { self.torrents.remove(key) } - pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + pub(crate) fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { self.torrents.remove_inactive_peers(current_cutoff); } - pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + pub(crate) fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { self.torrents.remove_peerless_torrents(policy); } #[must_use] - pub fn get(&self, key: &InfoHash) -> Option { + pub(crate) fn get(&self, key: &InfoHash) -> Option { self.torrents.get(key) } #[must_use] - pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { self.torrents.get_paginated(pagination) } /// It returns the data for a `scrape` response or empty if the torrent is /// not found. #[must_use] - pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { + pub(crate) fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { match self.torrents.get(info_hash) { Some(torrent_entry) => torrent_entry.get_swarm_metadata(), None => SwarmMetadata::zeroed(), @@ -69,7 +70,7 @@ impl InMemoryTorrentRepository { /// /// It filters out the client making the request. #[must_use] - pub fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { + pub(crate) fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { match self.torrents.get(info_hash) { None => vec![], Some(entry) => entry.get_peers_for_client(&peer.peer_addr, Some(max(limit, TORRENT_PEERS_LIMIT))), @@ -135,7 +136,7 @@ mod tests { use std::sync::Arc; - use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::test_helpers::tests::{sample_info_hash, sample_peer}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; #[tokio::test] @@ -171,7 +172,7 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::test_helpers::tests::{sample_info_hash, sample_peer}; use crate::torrent::repository::in_memory::tests::the_in_memory_torrent_repository::numeric_peer_id; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -233,7 +234,7 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::test_helpers::tests::{sample_info_hash, sample_peer}; use crate::torrent::repository::in_memory::tests::the_in_memory_torrent_repository::numeric_peer_id; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -303,7 +304,7 @@ mod tests { use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::test_helpers::tests::{sample_info_hash, sample_peer}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; #[tokio::test] @@ -374,7 +375,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_torrent_repository::entry::EntrySync; - use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::test_helpers::tests::{sample_info_hash, sample_peer}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::torrent::TorrentEntry; @@ -429,7 +430,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::core_tests::{sample_info_hash, sample_peer}; + use crate::test_helpers::tests::{sample_info_hash, sample_peer}; use crate::torrent::repository::in_memory::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -467,7 +468,7 @@ mod tests { use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::core_tests::{ + use crate::test_helpers::tests::{ sample_info_hash_alphabetically_ordered_after_sample_info_hash_one, sample_info_hash_one, sample_peer_one, sample_peer_two, }; @@ -577,7 +578,7 @@ mod tests { use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; - use crate::core_tests::{complete_peer, leecher, sample_info_hash, seeder}; + use crate::test_helpers::tests::{complete_peer, leecher, sample_info_hash, seeder}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; // todo: refactor to use test parametrization @@ -689,7 +690,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::core_tests::{leecher, sample_info_hash}; + use crate::test_helpers::tests::{leecher, sample_info_hash}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; #[tokio::test] @@ -728,7 +729,7 @@ mod tests { use torrust_tracker_primitives::PersistentTorrents; - use crate::core_tests::sample_info_hash; + use crate::test_helpers::tests::sample_info_hash; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; #[tokio::test] diff --git a/packages/tracker-core/src/torrent/repository/persisted.rs b/packages/tracker-core/src/torrent/repository/persisted.rs index 224919d0e..0430f03bb 100644 --- a/packages/tracker-core/src/torrent/repository/persisted.rs +++ b/packages/tracker-core/src/torrent/repository/persisted.rs @@ -29,7 +29,7 @@ impl DatabasePersistentTorrentRepository { /// # Errors /// /// Will return a database `Err` if unable to load. - pub fn load_all(&self) -> Result { + pub(crate) fn load_all(&self) -> Result { self.database.load_persistent_torrents() } @@ -38,7 +38,7 @@ impl DatabasePersistentTorrentRepository { /// # Errors /// /// Will return a database `Err` if unable to save. - pub fn save(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error> { + pub(crate) fn save(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error> { self.database.save_persistent_torrent(info_hash, downloaded) } } @@ -49,8 +49,8 @@ mod tests { use torrust_tracker_primitives::PersistentTorrents; use super::DatabasePersistentTorrentRepository; - use crate::core_tests::{ephemeral_configuration, sample_info_hash, sample_info_hash_one, sample_info_hash_two}; use crate::databases::setup::initialize_database; + use crate::test_helpers::tests::{ephemeral_configuration, sample_info_hash, sample_info_hash_one, sample_info_hash_two}; fn initialize_db_persistent_torrent_repository() -> DatabasePersistentTorrentRepository { let config = ephemeral_configuration(); diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index c36190ed1..4c470bb74 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -302,7 +302,7 @@ mod tests { use std::sync::Arc; - use crate::core_tests::sample_info_hash; + use crate::test_helpers::tests::sample_info_hash; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::torrent::services::tests::sample_peer; use crate::torrent::services::{get_torrents, BasicInfo}; diff --git a/packages/tracker-core/src/whitelist/authorization.rs b/packages/tracker-core/src/whitelist/authorization.rs index 66f909226..3b7b8b4fb 100644 --- a/packages/tracker-core/src/whitelist/authorization.rs +++ b/packages/tracker-core/src/whitelist/authorization.rs @@ -88,8 +88,8 @@ mod tests { use torrust_tracker_configuration::Core; - use crate::core_tests::sample_info_hash; use crate::error::WhitelistError; + use crate::test_helpers::tests::sample_info_hash; use crate::whitelist::authorization::tests::the_whitelist_authorization_for_announce_and_scrape_actions::{ initialize_whitelist_authorization_and_dependencies_with, initialize_whitelist_authorization_with, }; @@ -129,7 +129,7 @@ mod tests { use torrust_tracker_configuration::Core; - use crate::core_tests::sample_info_hash; + use crate::test_helpers::tests::sample_info_hash; use crate::whitelist::authorization::tests::the_whitelist_authorization_for_announce_and_scrape_actions::{ initialize_whitelist_authorization_and_dependencies_with, initialize_whitelist_authorization_with, }; diff --git a/packages/tracker-core/src/whitelist/manager.rs b/packages/tracker-core/src/whitelist/manager.rs index e1cd2f89e..5ebd6db36 100644 --- a/packages/tracker-core/src/whitelist/manager.rs +++ b/packages/tracker-core/src/whitelist/manager.rs @@ -73,9 +73,9 @@ mod tests { use torrust_tracker_configuration::Core; - use crate::core_tests::ephemeral_configuration_for_listed_tracker; use crate::databases::setup::initialize_database; use crate::databases::Database; + use crate::test_helpers::tests::ephemeral_configuration_for_listed_tracker; use crate::whitelist::manager::WhitelistManager; use crate::whitelist::repository::in_memory::InMemoryWhitelist; use crate::whitelist::repository::persisted::DatabaseWhitelist; @@ -111,7 +111,7 @@ mod tests { mod configured_as_whitelisted { mod handling_the_torrent_whitelist { - use crate::core_tests::sample_info_hash; + use crate::test_helpers::tests::sample_info_hash; use crate::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker; #[tokio::test] @@ -141,7 +141,7 @@ mod tests { } mod persistence { - use crate::core_tests::sample_info_hash; + use crate::test_helpers::tests::sample_info_hash; use crate::whitelist::manager::tests::initialize_whitelist_manager_for_whitelisted_tracker; #[tokio::test] diff --git a/packages/tracker-core/src/whitelist/mod.rs b/packages/tracker-core/src/whitelist/mod.rs index 8521485f7..a39768e93 100644 --- a/packages/tracker-core/src/whitelist/mod.rs +++ b/packages/tracker-core/src/whitelist/mod.rs @@ -2,7 +2,7 @@ pub mod authorization; pub mod manager; pub mod repository; pub mod setup; -pub mod whitelist_tests; +pub mod test_helpers; #[cfg(test)] mod tests { @@ -10,8 +10,8 @@ mod tests { mod configured_as_whitelisted { mod handling_authorization { - use crate::core_tests::sample_info_hash; - use crate::whitelist::whitelist_tests::initialize_whitelist_services_for_listed_tracker; + use crate::test_helpers::tests::sample_info_hash; + use crate::whitelist::test_helpers::tests::initialize_whitelist_services_for_listed_tracker; #[tokio::test] async fn it_should_authorize_the_announce_and_scrape_actions_on_whitelisted_torrents() { diff --git a/packages/tracker-core/src/whitelist/repository/in_memory.rs b/packages/tracker-core/src/whitelist/repository/in_memory.rs index befd6fed6..4faeda784 100644 --- a/packages/tracker-core/src/whitelist/repository/in_memory.rs +++ b/packages/tracker-core/src/whitelist/repository/in_memory.rs @@ -14,7 +14,7 @@ impl InMemoryWhitelist { } /// It removes a torrent from the whitelist in memory. - pub async fn remove(&self, info_hash: &InfoHash) -> bool { + pub(crate) async fn remove(&self, info_hash: &InfoHash) -> bool { self.whitelist.write().await.remove(info_hash) } @@ -24,7 +24,7 @@ impl InMemoryWhitelist { } /// It clears the whitelist. - pub async fn clear(&self) { + pub(crate) async fn clear(&self) { let mut whitelist = self.whitelist.write().await; whitelist.clear(); } @@ -33,7 +33,7 @@ impl InMemoryWhitelist { #[cfg(test)] mod tests { - use crate::core_tests::sample_info_hash; + use crate::test_helpers::tests::sample_info_hash; use crate::whitelist::repository::in_memory::InMemoryWhitelist; #[tokio::test] diff --git a/packages/tracker-core/src/whitelist/repository/persisted.rs b/packages/tracker-core/src/whitelist/repository/persisted.rs index 5101b5e35..4773cfbe6 100644 --- a/packages/tracker-core/src/whitelist/repository/persisted.rs +++ b/packages/tracker-core/src/whitelist/repository/persisted.rs @@ -22,7 +22,7 @@ impl DatabaseWhitelist { /// # Errors /// /// Will return a `database::Error` if unable to add the `info_hash` to the whitelist database. - pub fn add(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + pub(crate) fn add(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; if is_whitelisted { @@ -39,7 +39,7 @@ impl DatabaseWhitelist { /// # Errors /// /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. - pub fn remove(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { + pub(crate) fn remove(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; if !is_whitelisted { @@ -56,7 +56,7 @@ impl DatabaseWhitelist { /// # Errors /// /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. - pub fn load_from_database(&self) -> Result, databases::error::Error> { + pub(crate) fn load_from_database(&self) -> Result, databases::error::Error> { self.database.load_whitelist() } } @@ -65,8 +65,8 @@ impl DatabaseWhitelist { mod tests { mod the_persisted_whitelist_repository { - use crate::core_tests::{ephemeral_configuration_for_listed_tracker, sample_info_hash}; use crate::databases::setup::initialize_database; + use crate::test_helpers::tests::{ephemeral_configuration_for_listed_tracker, sample_info_hash}; use crate::whitelist::repository::persisted::DatabaseWhitelist; fn initialize_database_whitelist() -> DatabaseWhitelist { diff --git a/packages/tracker-core/src/whitelist/test_helpers.rs b/packages/tracker-core/src/whitelist/test_helpers.rs new file mode 100644 index 000000000..cc30c4476 --- /dev/null +++ b/packages/tracker-core/src/whitelist/test_helpers.rs @@ -0,0 +1,32 @@ +//! Some generic test helpers functions. + +#[cfg(test)] +pub(crate) mod tests { + + use std::sync::Arc; + + use torrust_tracker_configuration::Configuration; + + use crate::databases::setup::initialize_database; + use crate::whitelist::authorization::WhitelistAuthorization; + use crate::whitelist::manager::WhitelistManager; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; + use crate::whitelist::setup::initialize_whitelist_manager; + + #[must_use] + pub fn initialize_whitelist_services(config: &Configuration) -> (Arc, Arc) { + let database = initialize_database(&config.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + + (whitelist_authorization, whitelist_manager) + } + + #[must_use] + pub fn initialize_whitelist_services_for_listed_tracker() -> (Arc, Arc) { + use torrust_tracker_test_helpers::configuration; + + initialize_whitelist_services(&configuration::ephemeral_listed()) + } +} diff --git a/packages/tracker-core/src/whitelist/whitelist_tests.rs b/packages/tracker-core/src/whitelist/whitelist_tests.rs deleted file mode 100644 index d2fd275f2..000000000 --- a/packages/tracker-core/src/whitelist/whitelist_tests.rs +++ /dev/null @@ -1,27 +0,0 @@ -use std::sync::Arc; - -use torrust_tracker_configuration::Configuration; - -use super::authorization::WhitelistAuthorization; -use super::manager::WhitelistManager; -use super::repository::in_memory::InMemoryWhitelist; -use crate::databases::setup::initialize_database; -use crate::whitelist::setup::initialize_whitelist_manager; - -#[must_use] -pub fn initialize_whitelist_services(config: &Configuration) -> (Arc, Arc) { - let database = initialize_database(&config.core); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - - (whitelist_authorization, whitelist_manager) -} - -#[cfg(test)] -#[must_use] -pub fn initialize_whitelist_services_for_listed_tracker() -> (Arc, Arc) { - use torrust_tracker_test_helpers::configuration; - - initialize_whitelist_services(&configuration::ephemeral_listed()) -} diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 0236215f2..e0d77ab8a 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -120,6 +120,7 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { )); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let torrents_manager = Arc::new(TorrentsManager::new( &configuration.core, &in_memory_torrent_repository, diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index fa0ccc776..6bc93992f 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -306,6 +306,7 @@ use serde::{Deserialize, Serialize}; pub mod server; +pub mod test_helpers; pub mod v1; pub const HTTP_TRACKER_LOG_TARGET: &str = "HTTP TRACKER"; diff --git a/src/servers/http/test_helpers.rs b/src/servers/http/test_helpers.rs new file mode 100644 index 000000000..8c3020c52 --- /dev/null +++ b/src/servers/http/test_helpers.rs @@ -0,0 +1,16 @@ +//! Some generic test helpers functions. + +#[cfg(test)] +pub(crate) mod tests { + use bittorrent_primitives::info_hash::InfoHash; + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } +} diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index f76aa7a07..64939ff48 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -254,7 +254,6 @@ mod tests { use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service::AuthenticationService; - use bittorrent_tracker_core::core_tests::sample_info_hash; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; @@ -264,6 +263,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::packages::http_tracker_core; + use crate::servers::http::test_helpers::tests::sample_info_hash; struct CoreTrackerServices { pub core_config: Arc, diff --git a/src/servers/http/v1/services/announce.rs b/src/servers/http/v1/services/announce.rs index 4de9296b3..e321ad01f 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/servers/http/v1/services/announce.rs @@ -153,7 +153,6 @@ mod tests { use std::sync::Arc; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; - use bittorrent_tracker_core::core_tests::sample_info_hash; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; @@ -165,6 +164,7 @@ mod tests { use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; use crate::packages::http_tracker_core; + use crate::servers::http::test_helpers::tests::sample_info_hash; use crate::servers::http::v1::services::announce::invoke; use crate::servers::http::v1::services::announce::tests::{ initialize_core_tracker_services, sample_peer, MockHttpStatsEventSender, diff --git a/src/servers/http/v1/services/scrape.rs b/src/servers/http/v1/services/scrape.rs index 3a2323693..e2eb4f87c 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/servers/http/v1/services/scrape.rs @@ -84,7 +84,6 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::AnnounceHandler; - use bittorrent_tracker_core::core_tests::sample_info_hash; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -98,6 +97,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::packages::http_tracker_core; + use crate::servers::http::test_helpers::tests::sample_info_hash; fn initialize_announce_and_scrape_handlers_for_public_tracker() -> (Arc, Arc) { let config = configuration::ephemeral_public(); @@ -162,10 +162,11 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::packages::{self, http_tracker_core}; + use crate::servers::http::test_helpers::tests::sample_info_hash; use crate::servers::http::v1::services::scrape::invoke; use crate::servers::http::v1::services::scrape::tests::{ - initialize_announce_and_scrape_handlers_for_public_tracker, initialize_scrape_handler, sample_info_hash, - sample_info_hashes, sample_peer, MockHttpStatsEventSender, + initialize_announce_and_scrape_handlers_for_public_tracker, initialize_scrape_handler, sample_info_hashes, + sample_peer, MockHttpStatsEventSender, }; #[tokio::test] @@ -247,10 +248,10 @@ mod tests { use torrust_tracker_primitives::core::ScrapeData; use crate::packages::{self, http_tracker_core}; + use crate::servers::http::test_helpers::tests::sample_info_hash; use crate::servers::http::v1::services::scrape::fake; use crate::servers::http::v1::services::scrape::tests::{ - initialize_announce_and_scrape_handlers_for_public_tracker, sample_info_hash, sample_info_hashes, sample_peer, - MockHttpStatsEventSender, + initialize_announce_and_scrape_handlers_for_public_tracker, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; #[tokio::test] From 74d0d2851c97ef220052bef3f1d7bf6543b49bfd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 12 Feb 2025 09:59:27 +0000 Subject: [PATCH 0746/1297] docs: [#1261] fix doc errors in tracker-core --- packages/tracker-core/src/authentication/key/mod.rs | 4 ++-- packages/tracker-core/src/databases/driver/mod.rs | 3 --- packages/tracker-core/src/databases/error.rs | 2 +- packages/tracker-core/src/databases/mod.rs | 4 ++-- packages/tracker-core/src/lib.rs | 13 ------------- 5 files changed, 5 insertions(+), 21 deletions(-) diff --git a/packages/tracker-core/src/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs index fce18c0dd..ea9edb7d5 100644 --- a/packages/tracker-core/src/authentication/key/mod.rs +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -6,7 +6,7 @@ //! //! There are services to [`generate_key`] and [`verify_key_expiration`] authentication keys. //! -//! Authentication keys are used only by [`HTTP`](crate::servers::http) trackers. All keys have an expiration time, that means +//! Authentication keys are used only by HTTP trackers. All keys have an expiration time, that means //! they are only valid during a period of time. After that time the expiring key will no longer be valid. //! //! Keys are stored in this struct: @@ -112,7 +112,7 @@ pub fn generate_key(lifetime: Option) -> PeerKey { /// /// # Errors /// -/// Will return a verification error [`crate::authentication::key::Error`] if +/// Will return a verification error [`enum@crate::authentication::key::Error`] if /// it cannot verify the key. pub fn verify_key_expiration(auth_key: &PeerKey) -> Result<(), Error> { let current_time: DurationSinceUnixEpoch = CurrentClock::now(); diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index 2bc6a1e3c..06e912f7c 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -1,7 +1,4 @@ //! Database driver factory. -//! -//! See [`databases::driver::build`](crate::core::databases::driver::build) -//! function for more information. use mysql::Mysql; use serde::{Deserialize, Serialize}; use sqlite::Sqlite; diff --git a/packages/tracker-core/src/databases/error.rs b/packages/tracker-core/src/databases/error.rs index 0f3207587..6b340080e 100644 --- a/packages/tracker-core/src/databases/error.rs +++ b/packages/tracker-core/src/databases/error.rs @@ -1,6 +1,6 @@ //! Database errors. //! -//! This module contains the [Database errors](crate::core::databases::error::Error). +//! This module contains the [Database errors](crate::databases::error::Error). use std::panic::Location; use std::sync::Arc; diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs index 010252139..1de13332f 100644 --- a/packages/tracker-core/src/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -4,8 +4,8 @@ //! //! There are two implementations of the trait (two drivers): //! -//! - [`Mysql`](crate::core::databases::mysql::Mysql) -//! - [`Sqlite`](crate::core::databases::sqlite::Sqlite) +//! - `Mysql` +//! - `Sqlite` //! //! > **NOTICE**: There are no database migrations. If there are any changes, //! > we will implemented them or provide a script to migrate to the new schema. diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index ecbaef9c5..ac6e4edac 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -25,7 +25,6 @@ //! - [Torrents](#torrents) //! - [Peers](#peers) //! - [Configuration](#configuration) -//! - [Services](#services) //! - [Authentication](#authentication) //! - [Statistics](#statistics) //! - [Persistence](#persistence) @@ -342,18 +341,6 @@ //! //! Refer to the [`configuration` module documentation](https://docs.rs/torrust-tracker-configuration) to get more information about all options. //! -//! # Services -//! -//! Services are domain services on top of the core tracker domain. Right now there are two types of service: -//! -//! - For statistics: [`crate::packages::statistics::services`] -//! - For torrents: [`crate::core::torrent::services`] -//! -//! Services usually format the data inside the tracker to make it easier to consume by other parts. -//! They also decouple the internal data structure, used by the tracker, from the way we deliver that data to the consumers. -//! The internal data structure is designed for performance or low memory consumption. And it should be changed -//! without affecting the external consumers. -//! //! Services can include extra features like pagination, for example. //! //! # Authentication From 181c27e749fe8da1f86c10960cb622bc1a5e082a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 12 Feb 2025 10:40:28 +0000 Subject: [PATCH 0747/1297] docs: [#1261] review docs for tracker-core package --- packages/http-protocol/src/v1/query.rs | 7 + packages/tracker-core/src/announce_handler.rs | 131 ++++++- .../src/authentication/handler.rs | 141 ++++--- .../src/authentication/key/mod.rs | 102 +++-- .../src/authentication/key/peer_key.rs | 103 ++++- .../key/repository/in_memory.rs | 53 ++- .../src/authentication/key/repository/mod.rs | 1 + .../key/repository/persisted.rs | 40 +- .../tracker-core/src/authentication/mod.rs | 15 + .../src/authentication/service.rs | 53 ++- .../src/databases/driver/mysql.rs | 11 + .../src/databases/driver/sqlite.rs | 23 +- packages/tracker-core/src/databases/error.rs | 38 +- packages/tracker-core/src/databases/mod.rs | 149 ++++---- packages/tracker-core/src/databases/setup.rs | 44 ++- packages/tracker-core/src/error.rs | 26 +- packages/tracker-core/src/lib.rs | 358 +++--------------- packages/tracker-core/src/scrape_handler.rs | 74 +++- packages/tracker-core/src/torrent/manager.rs | 50 ++- packages/tracker-core/src/torrent/mod.rs | 180 ++++++++- .../src/torrent/repository/in_memory.rs | 146 ++++++- .../src/torrent/repository/mod.rs | 1 + .../src/torrent/repository/persisted.rs | 52 ++- packages/tracker-core/src/torrent/services.rs | 109 +++++- .../src/whitelist/authorization.rs | 29 +- .../tracker-core/src/whitelist/manager.rs | 48 ++- packages/tracker-core/src/whitelist/mod.rs | 18 + .../src/whitelist/repository/in_memory.rs | 25 +- .../src/whitelist/repository/mod.rs | 1 + .../src/whitelist/repository/persisted.rs | 22 +- packages/tracker-core/src/whitelist/setup.rs | 26 ++ .../src/whitelist/test_helpers.rs | 7 +- 32 files changed, 1467 insertions(+), 616 deletions(-) diff --git a/packages/http-protocol/src/v1/query.rs b/packages/http-protocol/src/v1/query.rs index f77145cb6..66afddf65 100644 --- a/packages/http-protocol/src/v1/query.rs +++ b/packages/http-protocol/src/v1/query.rs @@ -249,6 +249,13 @@ mod tests { assert_eq!(query.get_param("param2"), Some("value2".to_string())); } + #[test] + fn should_ignore_duplicate_param_values_when_asked_to_return_only_one_value() { + let query = Query::from(vec![("param1", "value1"), ("param1", "value2")]); + + assert_eq!(query.get_param("param1"), Some("value1".to_string())); + } + #[test] fn should_fail_parsing_an_invalid_query_string() { let invalid_raw_query = "name=value=value"; diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index cd0a9b861..6707f1917 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -1,3 +1,95 @@ +//! Announce handler. +//! +//! Handling `announce` requests is the most important task for a `BitTorrent` +//! tracker. +//! +//! A `BitTorrent` swarm is a network of peers that are all trying to download +//! the same torrent. When a peer wants to find other peers it announces itself +//! to the swarm via the tracker. The peer sends its data to the tracker so that +//! the tracker can add it to the swarm. The tracker responds to the peer with +//! the list of other peers in the swarm so that the peer can contact them to +//! start downloading pieces of the file from them. +//! +//! Once you have instantiated the `AnnounceHandler` you can `announce` a new [`peer::Peer`](torrust_tracker_primitives) with: +//! +//! ```rust,no_run +//! use std::net::SocketAddr; +//! use std::net::IpAddr; +//! use std::net::Ipv4Addr; +//! use std::str::FromStr; +//! +//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; +//! use torrust_tracker_primitives::peer; +//! use bittorrent_primitives::info_hash::InfoHash; +//! +//! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); +//! +//! let peer = peer::Peer { +//! peer_id: PeerId(*b"-qB00000000000000001"), +//! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), +//! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), +//! uploaded: NumberOfBytes::new(0), +//! downloaded: NumberOfBytes::new(0), +//! left: NumberOfBytes::new(0), +//! event: AnnounceEvent::Completed, +//! }; +//! +//! let peer_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); +//! ``` +//! +//! ```text +//! let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip).await; +//! ``` +//! +//! The handler returns the list of peers for the torrent with the infohash +//! `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`, filtering out the peer that is +//! making the `announce` request. +//! +//! > **NOTICE**: that the peer argument is mutable because the handler can +//! > change the peer IP if the peer is using a loopback IP. +//! +//! The `peer_ip` argument is the resolved peer ip. It's a common practice that +//! trackers ignore the peer ip in the `announce` request params, and resolve +//! the peer ip using the IP of the client making the request. As the tracker is +//! a domain service, the peer IP must be provided for the handler user, which +//! is usually a higher component with access the the request metadata, for +//! example, connection data, proxy headers, etcetera. +//! +//! The returned struct is: +//! +//! ```rust,no_run +//! use torrust_tracker_primitives::peer; +//! use torrust_tracker_configuration::AnnouncePolicy; +//! +//! pub struct AnnounceData { +//! pub peers: Vec, +//! pub swarm_stats: SwarmMetadata, +//! pub policy: AnnouncePolicy, // the tracker announce policy. +//! } +//! +//! pub struct SwarmMetadata { +//! pub completed: u32, // The number of peers that have ever completed downloading +//! pub seeders: u32, // The number of active peers that have completed downloading (seeders) +//! pub leechers: u32, // The number of active peers that have not completed downloading (leechers) +//! } +//! +//! // Core tracker configuration +//! pub struct AnnounceInterval { +//! // ... +//! pub interval: u32, // Interval in seconds that the client should wait between sending regular announce requests to the tracker +//! pub interval_min: u32, // Minimum announce interval. Clients must not reannounce more frequently than this +//! // ... +//! } +//! ``` +//! +//! ## Related BEPs: +//! +//! Refer to `BitTorrent` BEPs and other sites for more information about the `announce` request: +//! +//! - [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) +//! - [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) +//! - [Vuze docs](https://wiki.vuze.com/w/Announce) use std::net::IpAddr; use std::sync::Arc; @@ -10,18 +102,20 @@ use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use super::torrent::repository::in_memory::InMemoryTorrentRepository; use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; +/// Handles `announce` requests from `BitTorrent` clients. pub struct AnnounceHandler { /// The tracker configuration. config: Core, - /// The in-memory torrents repository. + /// Repository for in-memory torrent data. in_memory_torrent_repository: Arc, - /// The persistent torrents repository. + /// Repository for persistent torrent data (database). db_torrent_repository: Arc, } impl AnnounceHandler { + /// Creates a new `AnnounceHandler`. #[must_use] pub fn new( config: &Core, @@ -35,9 +129,20 @@ impl AnnounceHandler { } } - /// It handles an announce request. + /// Processes an announce request from a peer. /// /// BEP 03: [The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html). + /// + /// # Parameters + /// + /// - `info_hash`: The unique identifier of the torrent. + /// - `peer`: The peer announcing itself (may be updated if IP is adjusted). + /// - `remote_client_ip`: The IP address of the client making the request. + /// - `peers_wanted`: Specifies how many peers the client wants in the response. + /// + /// # Returns + /// + /// An `AnnounceData` struct containing the list of peers, swarm statistics, and tracker policy. pub fn announce( &self, info_hash: &InfoHash, @@ -77,9 +182,8 @@ impl AnnounceHandler { } } - /// It updates the torrent entry in memory, it also stores in the database - /// the torrent info data which is persistent, and finally return the data - /// needed for a `announce` request response. + /// Updates the torrent data in memory, persists statistics if needed, and + /// returns the updated swarm stats. #[must_use] fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { let swarm_metadata_before = self.in_memory_torrent_repository.get_swarm_metadata(info_hash); @@ -95,7 +199,7 @@ impl AnnounceHandler { swarm_metadata_after } - /// It stores the torrents stats into the database (if persistency is enabled). + /// Persists torrent statistics to the database if persistence is enabled. fn persist_stats(&self, info_hash: &InfoHash, swarm_metadata: &SwarmMetadata) { if self.config.tracker_policy.persistent_torrent_completed_stat { let completed = swarm_metadata.downloaded; @@ -106,22 +210,25 @@ impl AnnounceHandler { } } -/// How many peers the peer announcing wants in the announce response. +/// Specifies how many peers a client wants in the announce response. #[derive(Clone, Debug, PartialEq, Default)] pub enum PeersWanted { - /// The peer wants as many peers as possible in the announce response. + /// Request as many peers as possible (default behavior). #[default] AsManyAsPossible, - /// The peer only wants a certain amount of peers in the announce response. + + /// Request a specific number of peers. Only { amount: usize }, } impl PeersWanted { + /// Request a specific number of peers. #[must_use] pub fn only(limit: u32) -> Self { limit.into() } + /// Returns the maximum number of peers allowed based on the request and tracker limit. fn limit(&self) -> usize { match self { PeersWanted::AsManyAsPossible => TORRENT_PEERS_LIMIT, @@ -159,6 +266,10 @@ impl From for PeersWanted { } } +/// Assigns the correct IP address to a peer based on tracker settings. +/// +/// If the client IP is a loopback address and the tracker has an external IP +/// configured, the external IP will be assigned to the peer. #[must_use] fn assign_ip_address_to_peer(remote_client_ip: &IpAddr, tracker_external_ip: Option) -> IpAddr { if let Some(host_ip) = tracker_external_ip.filter(|_| remote_client_ip.is_loopback()) { diff --git a/packages/tracker-core/src/authentication/handler.rs b/packages/tracker-core/src/authentication/handler.rs index 136060916..178895b8d 100644 --- a/packages/tracker-core/src/authentication/handler.rs +++ b/packages/tracker-core/src/authentication/handler.rs @@ -1,3 +1,11 @@ +//! This module implements the `KeysHandler` service +//! +//! It's responsible for managing authentication keys for the `BitTorrent` tracker. +//! +//! The service handles both persistent and in-memory storage of peer keys, and +//! supports adding new keys (either pre-generated or randomly created), +//! removing keys, and loading keys from the database into memory. Keys can be +//! either permanent or expire after a configurable duration per key. use std::sync::Arc; use std::time::Duration; @@ -11,29 +19,44 @@ use super::{key, CurrentClock, Key, PeerKey}; use crate::databases; use crate::error::PeerKeyError; -/// This type contains the info needed to add a new tracker key. +/// Contains the information needed to add a new tracker key. /// -/// You can upload a pre-generated key or let the app to generate a new one. -/// You can also set an expiration date or leave it empty (`None`) if you want -/// to create a permanent key that does not expire. +/// A new key can either be a pre-generated key provided by the user or can be +/// randomly generated by the application. Additionally, the key may be set to +/// expire after a certain number of seconds, or be permanent (if no expiration +/// is specified). #[derive(Debug)] pub struct AddKeyRequest { - /// The pre-generated key. Use `None` to generate a random key. + /// The pre-generated key as a string. If `None` the service will generate a + /// random key. pub opt_key: Option, - /// How long the key will be valid in seconds. Use `None` for permanent keys. + /// The duration (in seconds) for which the key is valid. Use `None` for + /// permanent keys. pub opt_seconds_valid: Option, } +/// The `KeysHandler` service manages the creation, addition, removal, and loading +/// of authentication keys for the tracker. +/// +/// It uses both a persistent (database) repository and an in-memory repository +/// to manage keys. pub struct KeysHandler { - /// The database repository for the authentication keys. + /// The database repository for storing authentication keys persistently. db_key_repository: Arc, - /// In-memory implementation of the authentication key repository. + /// The in-memory repository for caching authentication keys. in_memory_key_repository: Arc, } impl KeysHandler { + /// Creates a new instance of the `KeysHandler` service. + /// + /// # Parameters + /// + /// - `db_key_repository`: A shared reference to the database key repository. + /// - `in_memory_key_repository`: A shared reference to the in-memory key + /// repository. #[must_use] pub fn new(db_key_repository: &Arc, in_memory_key_repository: &Arc) -> Self { Self { @@ -42,18 +65,24 @@ impl KeysHandler { } } - /// Adds new peer keys to the tracker. + /// Adds a new peer key to the tracker. + /// + /// The key may be pre-generated or generated on-the-fly. + /// + /// Depending on whether an expiration duration is specified, the key will + /// be either expiring or permanent. /// - /// Keys can be pre-generated or randomly created. They can also be - /// permanent or expire. + /// # Parameters + /// + /// - `add_key_req`: The request containing options for key creation. /// /// # Errors /// - /// Will return an error if: + /// Returns an error if: /// - /// - The key duration overflows the duration type maximum value. + /// - The provided key duration exceeds the maximum allowed value. /// - The provided pre-generated key is invalid. - /// - The key could not been persisted due to database issues. + /// - There is an error persisting the key in the database. pub async fn add_peer_key(&self, add_key_req: AddKeyRequest) -> Result { if let Some(pre_existing_key) = add_key_req.opt_key { // Pre-generated key @@ -125,29 +154,31 @@ impl KeysHandler { } } - /// It generates a new permanent authentication key. + /// Generates a new permanent authentication key. /// - /// Authentication keys are used by HTTP trackers. + /// Permanent keys do not expire. /// /// # Errors /// - /// Will return a `database::Error` if unable to add the `auth_key` to the database. + /// Returns a `databases::error::Error` if the key cannot be persisted in + /// the database. pub(crate) async fn generate_permanent_peer_key(&self) -> Result { self.generate_expiring_peer_key(None).await } - /// It generates a new expiring authentication key. + /// Generates a new authentication key with an optional expiration lifetime. /// - /// Authentication keys are used by HTTP trackers. + /// If a `lifetime` is provided, the generated key will expire after that + /// duration. The new key is stored both in the database and in memory. /// - /// # Errors + /// # Parameters /// - /// Will return a `database::Error` if unable to add the `auth_key` to the database. + /// - `lifetime`: An optional duration specifying how long the key is valid. /// - /// # Arguments + /// # Errors /// - /// * `lifetime` - The duration in seconds for the new key. The key will be - /// no longer valid after `lifetime` seconds. + /// Returns a `databases::error::Error` if there is an issue adding the key + /// to the database. pub async fn generate_expiring_peer_key(&self, lifetime: Option) -> Result { let peer_key = key::generate_key(lifetime); @@ -158,36 +189,36 @@ impl KeysHandler { Ok(peer_key) } - /// It adds a pre-generated permanent authentication key. + /// Adds a pre-generated permanent authentication key. /// - /// Authentication keys are used by HTTP trackers. + /// Internally, this calls `add_expiring_peer_key` with no expiration. /// - /// # Errors + /// # Parameters /// - /// Will return a `database::Error` if unable to add the `auth_key` to the - /// database. For example, if the key already exist. + /// - `key`: The pre-generated key. /// - /// # Arguments + /// # Errors /// - /// * `key` - The pre-generated key. + /// Returns a `databases::error::Error` if there is an issue persisting the + /// key. pub(crate) async fn add_permanent_peer_key(&self, key: Key) -> Result { self.add_expiring_peer_key(key, None).await } - /// It adds a pre-generated authentication key. + /// Adds a pre-generated authentication key with an optional expiration. /// - /// Authentication keys are used by HTTP trackers. + /// The key is stored in both the database and the in-memory repository. /// - /// # Errors + /// # Parameters /// - /// Will return a `database::Error` if unable to add the `auth_key` to the - /// database. For example, if the key already exist. + /// - `key`: The pre-generated key. + /// - `valid_until`: An optional timestamp (as a duration since the Unix + /// epoch) after which the key expires. /// - /// # Arguments + /// # Errors /// - /// * `key` - The pre-generated key. - /// * `lifetime` - The duration in seconds for the new key. The key will be - /// no longer valid after `lifetime` seconds. + /// Returns a `databases::error::Error` if there is an issue adding the key + /// to the database. pub(crate) async fn add_expiring_peer_key( &self, key: Key, @@ -205,11 +236,18 @@ impl KeysHandler { Ok(peer_key) } - /// It removes an authentication key. + /// Removes an authentication key. + /// + /// The key is removed from both the database and the in-memory repository. + /// + /// # Parameters + /// + /// - `key`: A reference to the key to be removed. /// /// # Errors /// - /// Will return a `database::Error` if unable to remove the `key` to the database. + /// Returns a `databases::error::Error` if the key cannot be removed from + /// the database. pub async fn remove_peer_key(&self, key: &Key) -> Result<(), databases::error::Error> { self.db_key_repository.remove(key)?; @@ -218,19 +256,26 @@ impl KeysHandler { Ok(()) } - /// It removes an authentication key from memory. + /// Removes an authentication key from the in-memory repository. + /// + /// This function does not interact with the database. + /// + /// # Parameters + /// + /// - `key`: A reference to the key to be removed. pub(crate) async fn remove_in_memory_auth_key(&self, key: &Key) { self.in_memory_key_repository.remove(key).await; } - /// The `Tracker` stores the authentication keys in memory and in the - /// database. In case you need to restart the `Tracker` you can load the - /// keys from the database into memory with this function. Keys are - /// automatically stored in the database when they are generated. + /// Loads all authentication keys from the database into the in-memory + /// repository. + /// + /// This is useful during tracker startup to ensure that all persisted keys + /// are available in memory. /// /// # Errors /// - /// Will return a `database::Error` if unable to `load_keys` from the database. + /// Returns a `databases::error::Error` if there is an issue loading the keys from the database. pub async fn load_peer_keys_from_database(&self) -> Result<(), databases::error::Error> { let keys_from_database = self.db_key_repository.load_keys()?; diff --git a/packages/tracker-core/src/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs index ea9edb7d5..648143928 100644 --- a/packages/tracker-core/src/authentication/key/mod.rs +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -1,42 +1,45 @@ -//! Tracker authentication services and structs. +//! Tracker authentication services and types. //! -//! This module contains functions to handle tracker keys. -//! Tracker keys are tokens used to authenticate the tracker clients when the tracker runs -//! in `private` or `private_listed` modes. +//! This module provides functions and data structures for handling tracker keys. +//! Tracker keys are tokens used to authenticate tracker clients when the +//! tracker is running in `private` mode. //! -//! There are services to [`generate_key`] and [`verify_key_expiration`] authentication keys. +//! Authentication keys are used exclusively by HTTP trackers. Every key has an +//! expiration time, meaning that it is only valid for a predetermined period. +//! Once the expiration time is reached, an expiring key will be rejected. //! -//! Authentication keys are used only by HTTP trackers. All keys have an expiration time, that means -//! they are only valid during a period of time. After that time the expiring key will no longer be valid. +//! The primary key structure is [`PeerKey`], which couples a randomly generated +//! [`Key`] (a 32-character alphanumeric string) with an optional expiration +//! timestamp. //! -//! Keys are stored in this struct: +//! # Examples //! -//! ```rust,no_run +//! Generating a new key valid for `9999` seconds: +//! +//! ```rust +//! use bittorrent_tracker_core::authentication; +//! use std::time::Duration; +//! +//! let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0))); +//! +//! // Later, verify that the key is still valid. +//! assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); +//! ``` +//! +//! The core key types are defined as follows: +//! +//! ```rust //! use bittorrent_tracker_core::authentication::Key; //! use torrust_tracker_primitives::DurationSinceUnixEpoch; //! //! pub struct PeerKey { -//! /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` +//! /// A random 32-character authentication token (e.g., `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ`) //! pub key: Key, //! -//! /// Timestamp, the key will be no longer valid after this timestamp. -//! /// If `None` the keys will not expire (permanent key). +//! /// The timestamp after which the key expires. If `None`, the key is permanent. //! pub valid_until: Option, //! } //! ``` -//! -//! You can generate a new key valid for `9999` seconds and `0` nanoseconds from the current time with the following: -//! -//! ```rust,no_run -//! use bittorrent_tracker_core::authentication; -//! use std::time::Duration; -//! -//! let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0))); -//! -//! // And you can later verify it with: -//! -//! assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok()); -//! ``` pub mod peer_key; pub mod repository; @@ -75,17 +78,33 @@ pub(crate) fn generate_expiring_key(lifetime: Duration) -> PeerKey { generate_key(Some(lifetime)) } -/// It generates a new random 32-char authentication [`PeerKey`]. +/// Generates a new random 32-character authentication key (`PeerKey`). /// -/// It can be an expiring or permanent key. +/// If a lifetime is provided, the generated key will expire after the specified +/// duration; otherwise, the key is permanent (i.e., it never expires). /// /// # Panics /// -/// It would panic if the `lifetime: Duration` + Duration is more than `Duration::MAX`. +/// Panics if the addition of the lifetime to the current time overflows +/// (an extremely unlikely event). /// /// # Arguments /// -/// * `lifetime`: if `None` the key will be permanent. +/// * `lifetime`: An optional duration specifying how long the key is valid. +/// If `None`, the key is permanent. +/// +/// # Examples +/// +/// ```rust +/// use bittorrent_tracker_core::authentication::key; +/// use std::time::Duration; +/// +/// // Generate an expiring key valid for 3600 seconds. +/// let expiring_key = key::generate_key(Some(Duration::from_secs(3600))); +/// +/// // Generate a permanent key. +/// let permanent_key = key::generate_key(None); +/// ``` #[must_use] pub fn generate_key(lifetime: Option) -> PeerKey { let random_key = Key::random(); @@ -107,13 +126,27 @@ pub fn generate_key(lifetime: Option) -> PeerKey { } } -/// It verifies an [`PeerKey`]. It checks if the expiration date has passed. -/// Permanent keys without duration (`None`) do not expire. +/// Verifies whether a given authentication key (`PeerKey`) is still valid. +/// +/// For expiring keys, this function compares the key's expiration timestamp +/// against the current time. Permanent keys (with `None` as their expiration) +/// are always valid. /// /// # Errors /// -/// Will return a verification error [`enum@crate::authentication::key::Error`] if -/// it cannot verify the key. +/// Returns a verification error of type [`enum@Error`] if the key has expired. +/// +/// # Examples +/// +/// ```rust +/// use bittorrent_tracker_core::authentication::key; +/// use std::time::Duration; +/// +/// let expiring_key = key::generate_key(Some(Duration::from_secs(100))); +/// +/// // If the key's expiration time has passed, the verification will fail. +/// assert!(key::verify_key_expiration(&expiring_key).is_ok()); +/// ``` pub fn verify_key_expiration(auth_key: &PeerKey) -> Result<(), Error> { let current_time: DurationSinceUnixEpoch = CurrentClock::now(); @@ -136,17 +169,20 @@ pub fn verify_key_expiration(auth_key: &PeerKey) -> Result<(), Error> { #[derive(Debug, Error)] #[allow(dead_code)] pub enum Error { + /// Wraps an underlying error encountered during key verification. #[error("Key could not be verified: {source}")] KeyVerificationError { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, }, + /// Indicates that the key could not be read or found. #[error("Failed to read key: {key}, {location}")] UnableToReadKey { location: &'static Location<'static>, key: Box, }, + /// Indicates that the key has expired. #[error("Key has expired, {location}")] KeyExpired { location: &'static Location<'static> }, } diff --git a/packages/tracker-core/src/authentication/key/peer_key.rs b/packages/tracker-core/src/authentication/key/peer_key.rs index 1d2b1fadc..41aba950b 100644 --- a/packages/tracker-core/src/authentication/key/peer_key.rs +++ b/packages/tracker-core/src/authentication/key/peer_key.rs @@ -1,3 +1,13 @@ +//! Authentication keys for private trackers. +//! +//! This module defines the types and functionality for managing authentication +//! keys used by the tracker. These keys, represented by the `Key` and `PeerKey` +//! types, are essential for authenticating peers in private tracker +//! environments. +//! +//! A `Key` is a 32-character alphanumeric token, while a `PeerKey` couples a +//! `Key` with an optional expiration timestamp. If the expiration is set (via +//! `valid_until`), the key will become invalid after that time. use std::str::FromStr; use std::time::Duration; @@ -11,22 +21,42 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::AUTH_KEY_LENGTH; -/// An authentication key which can potentially have an expiration time. -/// After that time is will automatically become invalid. +/// A peer authentication key with an optional expiration time. +/// +/// A `PeerKey` associates a generated `Key` (a 32-character alphanumeric string) +/// with an optional expiration timestamp (`valid_until`). If `valid_until` is +/// `None`, the key is considered permanent. +/// +/// # Example +/// +/// ```rust +/// use std::time::Duration; +/// use bittorrent_tracker_core::authentication::key::peer_key::{Key, PeerKey}; +/// +/// let expiring_key = PeerKey { +/// key: Key::random(), +/// valid_until: Some(Duration::from_secs(3600)), // Expires in 1 hour +/// }; +/// +/// let permanent_key = PeerKey { +/// key: Key::random(), +/// valid_until: None, +/// }; +/// ``` #[derive(Serialize, Deserialize, Debug, Clone)] pub struct PeerKey { - /// Random 32-char string. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` + /// A 32-character authentication key. For example: `YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ` pub key: Key, - /// Timestamp, the key will be no longer valid after this timestamp. - /// If `None` the keys will not expire (permanent key). + /// An optional expiration timestamp. If set, the key becomes invalid after + /// this time. A value of `None` indicates a permanent key. pub valid_until: Option, } impl PartialEq for PeerKey { fn eq(&self, other: &Self) -> bool { - // We ignore the fractions of seconds when comparing the timestamps - // because we only store the seconds in the database. + // When comparing two PeerKeys, ignore fractions of seconds since only + // whole seconds are stored in the database. self.key == other.key && match (&self.valid_until, &other.valid_until) { (Some(a), Some(b)) => a.as_secs() == b.as_secs(), @@ -53,14 +83,17 @@ impl PeerKey { self.key.clone() } - /// It returns the expiry time. For example, for the starting time for Unix Epoch - /// (timestamp 0) it will return a `DateTime` whose string representation is - /// `1970-01-01 00:00:00 UTC`. + /// Computes and returns the expiration time as a UTC `DateTime`, if one + /// exists. + /// + /// The returned time is derived from the stored seconds since the Unix + /// epoch. Note that any fractional seconds are discarded since only whole + /// seconds are stored in the database. /// /// # Panics /// - /// Will panic when the key timestamp overflows the internal i64 type. - /// (this will naturally happen in 292.5 billion years) + /// Panics if the key's timestamp overflows the internal `i64` type (this is + /// extremely unlikely, happening roughly 292.5 billion years from now). #[must_use] pub fn expiry_time(&self) -> Option> { // We remove the fractions of seconds because we only store the seconds @@ -72,17 +105,37 @@ impl PeerKey { /// A token used for authentication. /// -/// - It contains only ascii alphanumeric chars: lower and uppercase letters and -/// numbers. -/// - It's a 32-char string. +/// The `Key` type encapsulates a 32-character string that must consist solely +/// of ASCII alphanumeric characters (0-9, a-z, A-Z). This key is used by the +/// tracker to authenticate peers. +/// +/// # Examples +/// +/// Creating a key from a valid string: +/// +/// ``` +/// use bittorrent_tracker_core::authentication::key::peer_key::Key; +/// let key = Key::new("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); +/// ``` +/// +/// Generating a random key: +/// +/// ``` +/// use bittorrent_tracker_core::authentication::key::peer_key::Key; +/// let random_key = Key::random(); +/// ``` #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Display, Hash)] pub struct Key(String); impl Key { + /// Constructs a new `Key` from the given string. + /// /// # Errors /// - /// Will return an error is the string represents an invalid key. - /// Valid keys can only contain 32 chars including 0-9, a-z and A-Z. + /// Returns a `ParseKeyError` if: + /// + /// - The input string does not have exactly 32 characters. + /// - The input string contains characters that are not ASCII alphanumeric. pub fn new(value: &str) -> Result { if value.len() != AUTH_KEY_LENGTH { return Err(ParseKeyError::InvalidKeyLength); @@ -95,11 +148,14 @@ impl Key { Ok(Self(value.to_owned())) } - /// It generates a random key. + /// Generates a new random authentication key. + /// + /// The random key is generated by sampling 32 ASCII alphanumeric characters. /// /// # Panics /// - /// Will panic if the random number generator fails to generate a valid key. + /// Panics if the random number generator fails to produce a valid key + /// (extremely unlikely). pub fn random() -> Self { let random_id: String = rng() .sample_iter(&Alphanumeric) @@ -115,9 +171,11 @@ impl Key { } } -/// Error returned when a key cannot be parsed from a string. +/// Errors that can occur when parsing a string into a `Key`. +/// +/// # Examples /// -/// ```text +/// ```rust /// use bittorrent_tracker_core::authentication::Key; /// use std::str::FromStr; /// @@ -132,9 +190,12 @@ impl Key { /// this error. #[derive(Debug, Error)] pub enum ParseKeyError { + /// The provided key does not have exactly 32 characters. #[error("Invalid key length. Key must be have 32 chars")] InvalidKeyLength, + /// The provided key contains invalid characters. Only ASCII alphanumeric + /// characters are allowed. #[error("Invalid chars for key. Key can only alphanumeric chars (0-9, a-z, A-Z)")] InvalidChars, } diff --git a/packages/tracker-core/src/authentication/key/repository/in_memory.rs b/packages/tracker-core/src/authentication/key/repository/in_memory.rs index 13664e27c..5911771d4 100644 --- a/packages/tracker-core/src/authentication/key/repository/in_memory.rs +++ b/packages/tracker-core/src/authentication/key/repository/in_memory.rs @@ -1,6 +1,11 @@ +//! In-memory implementation of the authentication key repository. use crate::authentication::key::{Key, PeerKey}; -/// In-memory implementation of the authentication key repository. +/// An in-memory repository for storing authentication keys. +/// +/// This repository maintains a mapping between a peer's [`Key`] and its +/// corresponding [`PeerKey`]. It is designed for use in private tracker +/// environments where keys are maintained in memory. #[derive(Debug, Default)] pub struct InMemoryKeyRepository { /// Tracker users' keys. Only for private trackers. @@ -8,28 +13,66 @@ pub struct InMemoryKeyRepository { } impl InMemoryKeyRepository { - /// It adds a new authentication key. + /// Inserts a new authentication key into the repository. + /// + /// This function acquires a write lock on the internal storage and inserts + /// the provided [`PeerKey`], using its inner [`Key`] as the map key. + /// + /// # Arguments + /// + /// * `auth_key` - A reference to the [`PeerKey`] to be inserted. pub(crate) async fn insert(&self, auth_key: &PeerKey) { self.keys.write().await.insert(auth_key.key.clone(), auth_key.clone()); } - /// It removes an authentication key. + /// Removes an authentication key from the repository. + /// + /// This function acquires a write lock on the internal storage and removes + /// the key that matches the provided [`Key`]. + /// + /// # Arguments + /// + /// * `key` - A reference to the [`Key`] corresponding to the key to be removed. pub(crate) async fn remove(&self, key: &Key) { self.keys.write().await.remove(key); } + /// Retrieves an authentication key from the repository. + /// + /// This function acquires a read lock on the internal storage and returns a + /// cloned [`PeerKey`] if the provided [`Key`] exists. + /// + /// # Arguments + /// + /// * `key` - A reference to the [`Key`] to look up. + /// + /// # Returns + /// + /// An `Option` containing the matching key if found, or `None` + /// otherwise. pub(crate) async fn get(&self, key: &Key) -> Option { self.keys.read().await.get(key).cloned() } - /// It clears all the authentication keys. + /// Clears all authentication keys from the repository. + /// + /// This function acquires a write lock on the internal storage and removes + /// all entries. #[allow(dead_code)] pub(crate) async fn clear(&self) { let mut keys = self.keys.write().await; keys.clear(); } - /// It resets the authentication keys with a new list of keys. + /// Resets the repository with a new list of authentication keys. + /// + /// This function clears all existing keys and then inserts each key from + /// the provided vector. + /// + /// # Arguments + /// + /// * `peer_keys` - A vector of [`PeerKey`] instances that will replace the + /// current set of keys. pub async fn reset_with(&self, peer_keys: Vec) { let mut keys_lock = self.keys.write().await; diff --git a/packages/tracker-core/src/authentication/key/repository/mod.rs b/packages/tracker-core/src/authentication/key/repository/mod.rs index 51723b68d..3df783622 100644 --- a/packages/tracker-core/src/authentication/key/repository/mod.rs +++ b/packages/tracker-core/src/authentication/key/repository/mod.rs @@ -1,2 +1,3 @@ +//! Key repository implementations. pub mod in_memory; pub mod persisted; diff --git a/packages/tracker-core/src/authentication/key/repository/persisted.rs b/packages/tracker-core/src/authentication/key/repository/persisted.rs index 95a3b874c..e84a23c9b 100644 --- a/packages/tracker-core/src/authentication/key/repository/persisted.rs +++ b/packages/tracker-core/src/authentication/key/repository/persisted.rs @@ -1,14 +1,28 @@ +//! The database repository for the authentication keys. use std::sync::Arc; use crate::authentication::key::{Key, PeerKey}; use crate::databases::{self, Database}; -/// The database repository for the authentication keys. +/// A repository for storing authentication keys in a persistent database. +/// +/// This repository provides methods to add, remove, and load authentication +/// keys from the underlying database. It wraps an instance of a type +/// implementing the [`Database`] trait. pub struct DatabaseKeyRepository { database: Arc>, } impl DatabaseKeyRepository { + /// Creates a new `DatabaseKeyRepository` instance. + /// + /// # Arguments + /// + /// * `database` - A shared reference to a boxed database implementation. + /// + /// # Returns + /// + /// A new instance of `DatabaseKeyRepository` #[must_use] pub fn new(database: &Arc>) -> Self { Self { @@ -16,31 +30,43 @@ impl DatabaseKeyRepository { } } - /// It adds a new key to the database. + /// Adds a new authentication key to the database. + /// + /// # Arguments + /// + /// * `peer_key` - A reference to the [`PeerKey`] to be persisted. /// /// # Errors /// - /// Will return a `databases::error::Error` if unable to add the `auth_key` to the database. + /// Returns a [`databases::error::Error`] if the key cannot be added. pub(crate) fn add(&self, peer_key: &PeerKey) -> Result<(), databases::error::Error> { self.database.add_key_to_keys(peer_key)?; Ok(()) } - /// It removes an key from the database. + /// Removes an authentication key from the database. + /// + /// # Arguments + /// + /// * `key` - A reference to the [`Key`] corresponding to the key to remove. /// /// # Errors /// - /// Will return a `database::Error` if unable to remove the `key` from the database. + /// Returns a [`databases::error::Error`] if the key cannot be removed. pub(crate) fn remove(&self, key: &Key) -> Result<(), databases::error::Error> { self.database.remove_key_from_keys(key)?; Ok(()) } - /// It loads all keys from the database. + /// Loads all authentication keys from the database. /// /// # Errors /// - /// Will return a `database::Error` if unable to load the keys from the database. + /// Returns a [`databases::error::Error`] if the keys cannot be loaded. + /// + /// # Returns + /// + /// A vector containing all persisted [`PeerKey`] entries. pub(crate) fn load_keys(&self) -> Result, databases::error::Error> { let keys = self.database.load_keys()?; Ok(keys) diff --git a/packages/tracker-core/src/authentication/mod.rs b/packages/tracker-core/src/authentication/mod.rs index 52138d26b..12b742b8b 100644 --- a/packages/tracker-core/src/authentication/mod.rs +++ b/packages/tracker-core/src/authentication/mod.rs @@ -1,3 +1,18 @@ +//! Tracker authentication services and structs. +//! +//! One of the crate responsibilities is to create and keep authentication keys. +//! Auth keys are used by HTTP trackers when the tracker is running in `private` +//! mode. +//! +//! HTTP tracker's clients need to obtain an authentication key before starting +//! requesting the tracker. Once they get one they have to include a `PATH` +//! param with the key in all the HTTP requests. For example, when a peer wants +//! to `announce` itself it has to use the HTTP tracker endpoint: +//! +//! `GET /announce/:key` +//! +//! The common way to obtain the keys is by using the tracker API directly or +//! via other applications like the [Torrust Index](https://github.com/torrust/torrust-index). use crate::CurrentClock; pub mod handler; diff --git a/packages/tracker-core/src/authentication/service.rs b/packages/tracker-core/src/authentication/service.rs index 5ca0a09ec..75b28944f 100644 --- a/packages/tracker-core/src/authentication/service.rs +++ b/packages/tracker-core/src/authentication/service.rs @@ -1,3 +1,4 @@ +//! Authentication service. use std::panic::Location; use std::sync::Arc; @@ -6,6 +7,11 @@ use torrust_tracker_configuration::Core; use super::key::repository::in_memory::InMemoryKeyRepository; use super::{key, Error, Key}; +/// The authentication service responsible for validating peer keys. +/// +/// The service uses an in-memory key repository along with the tracker +/// configuration to determine whether a given peer key is valid. In a private +/// tracker, only registered keys (and optionally unexpired keys) are allowed. #[derive(Debug)] pub struct AuthenticationService { /// The tracker configuration. @@ -16,6 +22,18 @@ pub struct AuthenticationService { } impl AuthenticationService { + /// Creates a new instance of the `AuthenticationService`. + /// + /// # Parameters + /// + /// - `config`: A reference to the tracker core configuration. + /// - `in_memory_key_repository`: A shared reference to an in-memory key + /// repository. + /// + /// # Returns + /// + /// An `AuthenticationService` instance initialized with the given + /// configuration and repository. #[must_use] pub fn new(config: &Core, in_memory_key_repository: &Arc) -> Self { Self { @@ -24,12 +42,23 @@ impl AuthenticationService { } } - /// It authenticates the peer `key` against the `Tracker` authentication - /// key list. + /// Authenticates a peer key against the tracker's authentication key list. + /// + /// For private trackers, the key must be registered (and optionally not + /// expired) to be considered valid. For public trackers, authentication + /// always succeeds. + /// + /// # Parameters + /// + /// - `key`: A reference to the peer key that needs to be authenticated. /// /// # Errors /// - /// Will return an error if the the authentication key cannot be verified. + /// Returns an error if: + /// + /// - The tracker is in private mode and the key cannot be found in the + /// repository. + /// - The key is found but fails the expiration check (if expiration is enforced). pub async fn authenticate(&self, key: &Key) -> Result<(), Error> { if self.tracker_is_private() { self.verify_auth_key(key).await @@ -44,11 +73,25 @@ impl AuthenticationService { self.config.private } - /// It verifies an authentication key. + /// Verifies the authentication key against the in-memory repository. + /// + /// This function retrieves the key from the repository. If the key is not + /// found, it returns an error with the caller's location. If the key is + /// found, the function then checks the key's expiration based on the + /// tracker configuration. The behavior differs depending on whether a + /// `private` configuration is provided and whether key expiration checking + /// is enabled. + /// + /// # Parameters + /// + /// - `key`: A reference to the peer key that needs to be verified. /// /// # Errors /// - /// Will return a `key::Error` if unable to get any `auth_key`. + /// Returns an error if: + /// + /// - The key is not found in the repository. + /// - The key fails the expiration check when such verification is required. async fn verify_auth_key(&self, key: &Key) -> Result<(), Error> { match self.in_memory_key_repository.get(key).await { None => Err(Error::UnableToReadKey { diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index 365bd0ad9..624e34c9b 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -1,4 +1,10 @@ //! The `MySQL` database driver. +//! +//! This module provides an implementation of the [`Database`] trait for `MySQL` +//! using the `r2d2_mysql` connection pool. It configures the MySQL connection +//! based on a URL, creates the necessary tables (for torrent metrics, torrent +//! whitelist, and authentication keys), and implements all CRUD operations +//! required by the persistence layer. use std::str::FromStr; use std::time::Duration; @@ -15,6 +21,11 @@ use crate::authentication::{self, Key}; const DRIVER: Driver = Driver::MySQL; +/// `MySQL` driver implementation. +/// +/// This struct encapsulates a connection pool for `MySQL`, built using the +/// `r2d2_mysql` connection manager. It implements the [`Database`] trait to +/// provide persistence operations. pub(crate) struct Mysql { pool: Pool, } diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs index 36ca4eabe..bab2fb6a7 100644 --- a/packages/tracker-core/src/databases/driver/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -1,4 +1,10 @@ //! The `SQLite3` database driver. +//! +//! This module provides an implementation of the [`Database`] trait for +//! `SQLite3` using the `r2d2_sqlite` connection pool. It defines the schema for +//! whitelist, torrent metrics, and authentication keys, and provides methods +//! to create and drop tables as well as perform CRUD operations on these +//! persistent objects. use std::panic::Location; use std::str::FromStr; @@ -14,18 +20,29 @@ use crate::authentication::{self, Key}; const DRIVER: Driver = Driver::Sqlite3; +/// `SQLite` driver implementation. +/// +/// This struct encapsulates a connection pool for `SQLite` using the `r2d2_sqlite` +/// connection manager. pub(crate) struct Sqlite { pool: Pool, } impl Sqlite { - /// It instantiates a new `SQLite3` database driver. + /// Instantiates a new `SQLite3` database driver. /// - /// Refer to [`databases::Database::new`](crate::core::databases::Database::new). + /// This function creates a connection manager for the `SQLite` database + /// located at `db_path` and then builds a connection pool using `r2d2`. If + /// the pool cannot be created, an error is returned (wrapped with the + /// appropriate driver information). + /// + /// # Arguments + /// + /// * `db_path` - A string slice representing the file path to the `SQLite` database. /// /// # Errors /// - /// Will return `r2d2::Error` if `db_path` is not able to create `SqLite` database. + /// Returns an [`Error`] if the connection pool cannot be built. pub fn new(db_path: &str) -> Result { let manager = SqliteConnectionManager::file(db_path); let pool = r2d2::Pool::builder().build(manager).map_err(|e| (e, DRIVER))?; diff --git a/packages/tracker-core/src/databases/error.rs b/packages/tracker-core/src/databases/error.rs index 6b340080e..fd9adfc22 100644 --- a/packages/tracker-core/src/databases/error.rs +++ b/packages/tracker-core/src/databases/error.rs @@ -1,6 +1,13 @@ //! Database errors. //! -//! This module contains the [Database errors](crate::databases::error::Error). +//! This module defines the [`Error`] enum used to represent errors that occur +//! during database operations. These errors encapsulate issues such as missing +//! query results, malformed queries, connection failures, and connection pool +//! creation errors. Each error variant includes contextual information such as +//! the associated database driver and, when applicable, the source error. +//! +//! External errors from database libraries (e.g., `rusqlite`, `mysql`) are +//! converted into this error type using the provided `From` implementations. use std::panic::Location; use std::sync::Arc; @@ -9,30 +16,43 @@ use torrust_tracker_located_error::{DynError, Located, LocatedError}; use super::driver::Driver; +/// Database error type that encapsulates various failures encountered during +/// database operations. #[derive(thiserror::Error, Debug, Clone)] pub enum Error { - /// The query unexpectedly returned nothing. + /// Indicates that a query unexpectedly returned no rows. + /// + /// This error variant is used when a query that is expected to return a + /// result does not. #[error("The {driver} query unexpectedly returned nothing: {source}")] QueryReturnedNoRows { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, driver: Driver, }, - /// The query was malformed. + /// Indicates that the query was malformed. + /// + /// This error variant is used when the SQL query itself is invalid or + /// improperly formatted. #[error("The {driver} query was malformed: {source}")] InvalidQuery { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, driver: Driver, }, - /// Unable to insert a record into the database + /// Indicates a failure to insert a record into the database. + /// + /// This error is raised when an insertion operation fails. #[error("Unable to insert record into {driver} database, {location}")] InsertFailed { location: &'static Location<'static>, driver: Driver, }, - /// Unable to delete a record into the database + /// Indicates a failure to delete a record from the database. + /// + /// This error includes an error code that may be returned by the database + /// driver. #[error("Failed to remove record from {driver} database, error-code: {error_code}, {location}")] DeleteFailed { location: &'static Location<'static>, @@ -40,14 +60,18 @@ pub enum Error { driver: Driver, }, - /// Unable to connect to the database + /// Indicates a failure to connect to the database. + /// + /// This error variant wraps connection-related errors, such as those caused by an invalid URL. #[error("Failed to connect to {driver} database: {source}")] ConnectionError { source: LocatedError<'static, UrlError>, driver: Driver, }, - /// Unable to create a connection pool + /// Indicates a failure to create a connection pool. + /// + /// This error variant is used when the connection pool creation (using r2d2) fails. #[error("Failed to create r2d2 {driver} connection pool: {source}")] ConnectionPool { source: LocatedError<'static, r2d2::Error>, diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs index 1de13332f..33a7e3c69 100644 --- a/packages/tracker-core/src/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -1,48 +1,51 @@ //! The persistence module. //! -//! Persistence is currently implemented with one [`Database`] trait. +//! Persistence is currently implemented using a single [`Database`] trait. //! //! There are two implementations of the trait (two drivers): //! -//! - `Mysql` -//! - `Sqlite` +//! - **`MySQL`** +//! - **`Sqlite`** //! -//! > **NOTICE**: There are no database migrations. If there are any changes, -//! > we will implemented them or provide a script to migrate to the new schema. +//! > **NOTICE**: There are no database migrations at this time. If schema +//! > changes occur, either migration functionality will be implemented or a +//! > script will be provided to migrate to the new schema. //! -//! The persistent objects are: +//! The persistent objects handled by this module include: //! -//! - [Torrent metrics](#torrent-metrics) -//! - [Torrent whitelist](torrent-whitelist) -//! - [Authentication keys](authentication-keys) +//! - **Torrent metrics**: Metrics such as the number of completed downloads for +//! each torrent. +//! - **Torrent whitelist**: A list of torrents (by infohash) that are allowed. +//! - **Authentication keys**: Expiring authentication keys used to secure +//! access to private trackers. //! -//! # Torrent metrics +//! # Torrent Metrics //! -//! Field | Sample data | Description -//! ---|---|--- -//! `id` | 1 | Autoincrement id -//! `info_hash` | `c1277613db1d28709b034a017ab2cae4be07ae10` | `BitTorrent` infohash V1 -//! `completed` | 20 | The number of peers that have ever completed downloading the torrent associated to this entry. See [`Entry`](torrust_tracker_torrent_repository::entry::Entry) for more information. +//! | Field | Sample data | Description | +//! |-------------|--------------------------------------------|-----------------------------------------------------------------------------| +//! | `id` | 1 | Auto-increment id | +//! | `info_hash` | `c1277613db1d28709b034a017ab2cae4be07ae10` | `BitTorrent` infohash V1 | +//! | `completed` | 20 | The number of peers that have completed downloading the associated torrent. | //! -//! > **NOTICE**: The peer list for a torrent is not persisted. Since peer have to re-announce themselves on intervals, the data is be -//! > regenerated again after some minutes. +//! > **NOTICE**: The peer list for a torrent is not persisted. Because peers re-announce at +//! > intervals, the peer list is regenerated periodically. //! -//! # Torrent whitelist +//! # Torrent Whitelist //! -//! Field | Sample data | Description -//! ---|---|--- -//! `id` | 1 | Autoincrement id -//! `info_hash` | `c1277613db1d28709b034a017ab2cae4be07ae10` | `BitTorrent` infohash V1 +//! | Field | Sample data | Description | +//! |-------------|--------------------------------------------|--------------------------------| +//! | `id` | 1 | Auto-increment id | +//! | `info_hash` | `c1277613db1d28709b034a017ab2cae4be07ae10` | `BitTorrent` infohash V1 | //! -//! # Authentication keys +//! # Authentication Keys //! -//! Field | Sample data | Description -//! ---|---|--- -//! `id` | 1 | Autoincrement id -//! `key` | `IrweYtVuQPGbG9Jzx1DihcPmJGGpVy82` | Token -//! `valid_until` | 1672419840 | Timestamp for the expiring date +//! | Field | Sample data | Description | +//! |---------------|------------------------------------|--------------------------------------| +//! | `id` | 1 | Auto-increment id | +//! | `key` | `IrweYtVuQPGbG9Jzx1DihcPmJGGpVy82` | Authentication token (32 chars) | +//! | `valid_until` | 1672419840 | Timestamp indicating expiration time | //! -//! > **NOTICE**: All keys must have an expiration date. +//! > **NOTICE**: All authentication keys must have an expiration date. pub mod driver; pub mod error; pub mod setup; @@ -54,143 +57,159 @@ use torrust_tracker_primitives::PersistentTorrents; use self::error::Error; use crate::authentication::{self, Key}; -/// The persistence trait. It contains all the methods to interact with the database. +/// The persistence trait. +/// +/// This trait defines all the methods required to interact with the database, +/// including creating and dropping schema tables, and CRUD operations for +/// torrent metrics, whitelists, and authentication keys. Implementations of +/// this trait must ensure that operations are safe, consistent, and report +/// errors using the [`Error`] type. #[automock] pub trait Database: Sync + Send { - /// It generates the database tables. SQL queries are hardcoded in the trait - /// implementation. + /// Creates the necessary database tables. + /// + /// The SQL queries for table creation are hardcoded in the trait implementation. /// /// # Context: Schema /// /// # Errors /// - /// Will return `Error` if unable to create own tables. + /// Returns an [`Error`] if the tables cannot be created. fn create_database_tables(&self) -> Result<(), Error>; - /// It drops the database tables. + /// Drops the database tables. + /// + /// This operation removes the persistent schema. /// /// # Context: Schema /// /// # Errors /// - /// Will return `Err` if unable to drop tables. + /// Returns an [`Error`] if the tables cannot be dropped. fn drop_database_tables(&self) -> Result<(), Error>; // Torrent Metrics - /// It loads the torrent metrics data from the database. + /// Loads torrent metrics data from the database. /// - /// It returns an array of tuples with the torrent - /// [`InfoHash`] and the - /// [`downloaded`](torrust_tracker_torrent_repository::entry::Torrent::downloaded) counter - /// which is the number of times the torrent has been downloaded. - /// See [`Entry::downloaded`](torrust_tracker_torrent_repository::entry::Torrent::downloaded). + /// This function returns the persistent torrent metrics as a collection of + /// tuples, where each tuple contains an [`InfoHash`] and the `downloaded` + /// counter (i.e. the number of times the torrent has been downloaded). /// /// # Context: Torrent Metrics /// /// # Errors /// - /// Will return `Err` if unable to load. + /// Returns an [`Error`] if the metrics cannot be loaded. fn load_persistent_torrents(&self) -> Result; - /// It saves the torrent metrics data into the database. + /// Saves torrent metrics data into the database. + /// + /// # Arguments + /// + /// * `info_hash` - A reference to the torrent's info hash. + /// * `downloaded` - The number of times the torrent has been downloaded. /// /// # Context: Torrent Metrics /// /// # Errors /// - /// Will return `Err` if unable to save. + /// Returns an [`Error`] if the metrics cannot be saved. fn save_persistent_torrent(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error>; // Whitelist - /// It loads the whitelisted torrents from the database. + /// Loads the whitelisted torrents from the database. /// /// # Context: Whitelist /// /// # Errors /// - /// Will return `Err` if unable to load. + /// Returns an [`Error`] if the whitelist cannot be loaded. fn load_whitelist(&self) -> Result, Error>; - /// It checks if the torrent is whitelisted. + /// Retrieves a whitelisted torrent from the database. /// - /// It returns `Some(InfoHash)` if the torrent is whitelisted, `None` otherwise. + /// Returns `Some(InfoHash)` if the torrent is in the whitelist, or `None` + /// otherwise. /// /// # Context: Whitelist /// /// # Errors /// - /// Will return `Err` if unable to load. + /// Returns an [`Error`] if the whitelist cannot be queried. fn get_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result, Error>; - /// It adds the torrent to the whitelist. + /// Adds a torrent to the whitelist. /// /// # Context: Whitelist /// /// # Errors /// - /// Will return `Err` if unable to save. + /// Returns an [`Error`] if the torrent cannot be added to the whitelist. fn add_info_hash_to_whitelist(&self, info_hash: InfoHash) -> Result; - /// It checks if the torrent is whitelisted. + /// Checks whether a torrent is whitelisted. + /// + /// This default implementation returns `true` if the infohash is included + /// in the whitelist, or `false` otherwise. /// /// # Context: Whitelist /// /// # Errors /// - /// Will return `Err` if unable to load. + /// Returns an [`Error`] if the whitelist cannot be queried. fn is_info_hash_whitelisted(&self, info_hash: InfoHash) -> Result { Ok(self.get_info_hash_from_whitelist(info_hash)?.is_some()) } - /// It removes the torrent from the whitelist. + /// Removes a torrent from the whitelist. /// /// # Context: Whitelist /// /// # Errors /// - /// Will return `Err` if unable to save. + /// Returns an [`Error`] if the torrent cannot be removed from the whitelist. fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result; // Authentication keys - /// It loads the expiring authentication keys from the database. + /// Loads all authentication keys from the database. /// /// # Context: Authentication Keys /// /// # Errors /// - /// Will return `Err` if unable to load. + /// Returns an [`Error`] if the keys cannot be loaded. fn load_keys(&self) -> Result, Error>; - /// It gets an expiring authentication key from the database. + /// Retrieves a specific authentication key from the database. /// - /// It returns `Some(PeerKey)` if a [`PeerKey`](crate::authentication::PeerKey) - /// with the input [`Key`] exists, `None` otherwise. + /// Returns `Some(PeerKey)` if a key corresponding to the provided [`Key`] + /// exists, or `None` otherwise. /// /// # Context: Authentication Keys /// /// # Errors /// - /// Will return `Err` if unable to load. + /// Returns an [`Error`] if the key cannot be queried. fn get_key_from_keys(&self, key: &Key) -> Result, Error>; - /// It adds an expiring authentication key to the database. + /// Adds an authentication key to the database. /// /// # Context: Authentication Keys /// /// # Errors /// - /// Will return `Err` if unable to save. + /// Returns an [`Error`] if the key cannot be saved. fn add_key_to_keys(&self, auth_key: &authentication::PeerKey) -> Result; - /// It removes an expiring authentication key from the database. + /// Removes an authentication key from the database. /// /// # Context: Authentication Keys /// /// # Errors /// - /// Will return `Err` if unable to load. + /// Returns an [`Error`] if the key cannot be removed. fn remove_key_from_keys(&self, key: &Key) -> Result; } diff --git a/packages/tracker-core/src/databases/setup.rs b/packages/tracker-core/src/databases/setup.rs index 73ff23feb..6ba9f2a64 100644 --- a/packages/tracker-core/src/databases/setup.rs +++ b/packages/tracker-core/src/databases/setup.rs @@ -1,3 +1,4 @@ +//! This module provides functionality for setting up databases. use std::sync::Arc; use torrust_tracker_configuration::Core; @@ -5,9 +6,38 @@ use torrust_tracker_configuration::Core; use super::driver::{self, Driver}; use super::Database; +/// Initializes and returns a database instance based on the provided configuration. +/// +/// This function creates a new database instance according to the settings +/// defined in the [`Core`] configuration. It selects the appropriate driver +/// (either `Sqlite3` or `MySQL`) as specified in `config.database.driver` and +/// attempts to build the database connection using the path defined in +/// `config.database.path`. +/// +/// The resulting database instance is wrapped in a shared pointer (`Arc`) to a +/// boxed trait object, allowing safe sharing of the database connection across +/// multiple threads. +/// /// # Panics /// -/// Will panic if database cannot be initialized. +/// This function will panic if the database cannot be initialized (i.e., if the +/// driver fails to build the connection). This is enforced by the use of +/// [`expect`](std::result::Result::expect) in the implementation. +/// +/// # Example +/// +/// ```rust,no_run +/// use torrust_tracker_configuration::Core; +/// use bittorrent_tracker_core::databases::setup::initialize_database; +/// +/// // Create a default configuration (ensure it is properly set up for your environment) +/// let config = Core::default(); +/// +/// // Initialize the database; this will panic if initialization fails. +/// let database = initialize_database(&config); +/// +/// // The returned database instance can now be used for persistence operations. +/// ``` #[must_use] pub fn initialize_database(config: &Core) -> Arc> { let driver = match config.database.driver { @@ -17,3 +47,15 @@ pub fn initialize_database(config: &Core) -> Arc> { Arc::new(driver::build(&driver, &config.database.path).expect("Database driver build failed.")) } + +#[cfg(test)] +mod tests { + use super::initialize_database; + use crate::test_helpers::tests::ephemeral_configuration; + + #[test] + fn it_should_initialize_the_sqlite_database() { + let config = ephemeral_configuration(); + let _database = initialize_database(&config); + } +} diff --git a/packages/tracker-core/src/error.rs b/packages/tracker-core/src/error.rs index dcdd89668..99ac48ed3 100644 --- a/packages/tracker-core/src/error.rs +++ b/packages/tracker-core/src/error.rs @@ -1,4 +1,12 @@ -//! Errors returned by the core tracker. +//! Core tracker errors. +//! +//! This module defines the error types used internally by the `BitTorrent` +//! tracker core. +//! +//! These errors encapsulate issues such as whitelisting violations, invalid +//! peer key data, and database persistence failures. Each error variant +//! includes contextual information (such as source code location) to facilitate +//! debugging. use std::panic::Location; use bittorrent_primitives::info_hash::InfoHash; @@ -7,9 +15,13 @@ use torrust_tracker_located_error::LocatedError; use super::authentication::key::ParseKeyError; use super::databases; -/// Whitelist errors returned by the core tracker. +/// Errors related to torrent whitelisting. +/// +/// This error is returned when an operation involves a torrent that is not +/// present in the whitelist. #[derive(thiserror::Error, Debug, Clone)] pub enum WhitelistError { + /// Indicates that the torrent identified by `info_hash` is not whitelisted. #[error("The torrent: {info_hash}, is not whitelisted, {location}")] TorrentNotWhitelisted { info_hash: InfoHash, @@ -17,19 +29,27 @@ pub enum WhitelistError { }, } -/// Peers keys errors returned by the core tracker. +/// Errors related to peer key operations. +/// +/// This error type covers issues encountered during the handling of peer keys, +/// including validation of key durations, parsing errors, and database +/// persistence problems. #[allow(clippy::module_name_repetitions)] #[derive(thiserror::Error, Debug, Clone)] pub enum PeerKeyError { + /// Returned when the duration specified for the peer key exceeds the + /// maximum. #[error("Invalid peer key duration: {seconds_valid:?}, is not valid")] DurationOverflow { seconds_valid: u64 }, + /// Returned when the provided peer key is invalid. #[error("Invalid key: {key}")] InvalidKey { key: String, source: LocatedError<'static, ParseKeyError>, }, + /// Returned when persisting the peer key to the database fails. #[error("Can't persist key: {source}")] DatabaseError { source: LocatedError<'static, databases::error::Error>, diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index ac6e4edac..843817deb 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -1,315 +1,57 @@ -//! The core `tracker` module contains the generic `BitTorrent` tracker logic which is independent of the delivery layer. +//! The core `bittorrent-tracker-core` crate contains the generic `BitTorrent` +//! tracker logic which is independent of the delivery layer. //! -//! It contains the tracker services and their dependencies. It's a domain layer which does not -//! specify how the end user should connect to the `Tracker`. +//! It contains the tracker services and their dependencies. It's a domain layer +//! which does not specify how the end user should connect to the `Tracker`. //! -//! Typically this module is intended to be used by higher modules like: +//! Typically this crate is intended to be used by higher components like: //! //! - A UDP tracker //! - A HTTP tracker //! - A tracker REST API //! //! ```text -//! Delivery layer Domain layer -//! -//! HTTP tracker | -//! UDP tracker |> Core tracker -//! Tracker REST API | +//! Delivery layer | Domain layer +//! ----------------------------------- +//! HTTP tracker | +//! UDP tracker |-> Core tracker +//! Tracker REST API | //! ``` //! //! # Table of contents //! -//! - [Tracker](#tracker) -//! - [Announce request](#announce-request) -//! - [Scrape request](#scrape-request) -//! - [Torrents](#torrents) -//! - [Peers](#peers) +//! - [Introduction](#introduction) //! - [Configuration](#configuration) +//! - [Announce handler](#announce-handler) +//! - [Scrape handler](#scrape-handler) //! - [Authentication](#authentication) -//! - [Statistics](#statistics) -//! - [Persistence](#persistence) -//! -//! # Tracker -//! -//! The `Tracker` is the main struct in this module. `The` tracker has some groups of responsibilities: -//! -//! - **Core tracker**: it handles the information about torrents and peers. -//! - **Authentication**: it handles authentication keys which are used by HTTP trackers. -//! - **Authorization**: it handles the permission to perform requests. -//! - **Whitelist**: when the tracker runs in `listed` or `private_listed` mode all operations are restricted to whitelisted torrents. -//! - **Statistics**: it keeps and serves the tracker statistics. -//! -//! Refer to [torrust-tracker-configuration](https://docs.rs/torrust-tracker-configuration) crate docs to get more information about the tracker settings. -//! -//! ## Announce request -//! -//! Handling `announce` requests is the most important task for a `BitTorrent` tracker. -//! -//! A `BitTorrent` swarm is a network of peers that are all trying to download the same torrent. -//! When a peer wants to find other peers it announces itself to the swarm via the tracker. -//! The peer sends its data to the tracker so that the tracker can add it to the swarm. -//! The tracker responds to the peer with the list of other peers in the swarm so that -//! the peer can contact them to start downloading pieces of the file from them. +//! - [Databases](#databases) +//! - [Torrent](#torrent) +//! - [Whitelist](#whitelist) //! -//! Once you have instantiated the `AnnounceHandler` you can `announce` a new [`peer::Peer`](torrust_tracker_primitives::peer::Peer) with: +//! # Introduction //! -//! ```rust,no_run -//! use std::net::SocketAddr; -//! use std::net::IpAddr; -//! use std::net::Ipv4Addr; -//! use std::str::FromStr; +//! The main purpose of this crate is to provide a generic `BitTorrent` tracker. //! -//! use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; -//! use torrust_tracker_primitives::DurationSinceUnixEpoch; -//! use torrust_tracker_primitives::peer; -//! use bittorrent_primitives::info_hash::InfoHash; +//! It has two main responsibilities: //! -//! let info_hash = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); +//! - To handle **announce** requests. +//! - To handle **scrape** requests. //! -//! let peer = peer::Peer { -//! peer_id: PeerId(*b"-qB00000000000000001"), -//! peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), -//! updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), -//! uploaded: NumberOfBytes::new(0), -//! downloaded: NumberOfBytes::new(0), -//! left: NumberOfBytes::new(0), -//! event: AnnounceEvent::Completed, -//! }; -//! -//! let peer_ip = IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()); -//! ``` -//! -//! ```text -//! let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip).await; -//! ``` -//! -//! The `Tracker` returns the list of peers for the torrent with the infohash `3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0`, -//! filtering out the peer that is making the `announce` request. -//! -//! > **NOTICE**: that the peer argument is mutable because the `Tracker` can change the peer IP if the peer is using a loopback IP. -//! -//! The `peer_ip` argument is the resolved peer ip. It's a common practice that trackers ignore the peer ip in the `announce` request params, -//! and resolve the peer ip using the IP of the client making the request. As the tracker is a domain service, the peer IP must be provided -//! for the `Tracker` user, which is usually a higher component with access the the request metadata, for example, connection data, proxy headers, -//! etcetera. -//! -//! The returned struct is: -//! -//! ```rust,no_run -//! use torrust_tracker_primitives::peer; -//! use torrust_tracker_configuration::AnnouncePolicy; -//! -//! pub struct AnnounceData { -//! pub peers: Vec, -//! pub swarm_stats: SwarmMetadata, -//! pub policy: AnnouncePolicy, // the tracker announce policy. -//! } -//! -//! pub struct SwarmMetadata { -//! pub completed: u32, // The number of peers that have ever completed downloading -//! pub seeders: u32, // The number of active peers that have completed downloading (seeders) -//! pub leechers: u32, // The number of active peers that have not completed downloading (leechers) -//! } -//! -//! // Core tracker configuration -//! pub struct AnnounceInterval { -//! // ... -//! pub interval: u32, // Interval in seconds that the client should wait between sending regular announce requests to the tracker -//! pub interval_min: u32, // Minimum announce interval. Clients must not reannounce more frequently than this -//! // ... -//! } -//! ``` +//! The crate has also other features: //! -//! Refer to `BitTorrent` BEPs and other sites for more information about the `announce` request: +//! - **Authentication**: It handles authentication keys which are used by HTTP trackers. +//! - **Persistence**: It handles persistence of data into a database. +//! - **Torrent**: It handles the torrent data. +//! - **Whitelist**: When the tracker runs in [`listed`](https://docs.rs/torrust-tracker-configuration/latest/torrust_tracker_configuration/type.Core.html) mode +//! all operations are restricted to whitelisted torrents. //! -//! - [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) -//! - [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html) -//! - [Vuze docs](https://wiki.vuze.com/w/Announce) -//! -//! ## Scrape request -//! -//! The `scrape` request allows clients to query metadata about the swarm in bulk. -//! -//! An `scrape` request includes a list of infohashes whose swarm metadata you want to collect. -//! -//! The returned struct is: -//! -//! ```rust,no_run -//! use bittorrent_primitives::info_hash::InfoHash; -//! use std::collections::HashMap; -//! -//! pub struct ScrapeData { -//! pub files: HashMap, -//! } -//! -//! pub struct SwarmMetadata { -//! pub complete: u32, // The number of active peers that have completed downloading (seeders) -//! pub downloaded: u32, // The number of peers that have ever completed downloading -//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) -//! } -//! ``` -//! -//! The JSON representation of a sample `scrape` response would be like the following: -//! -//! ```json -//! { -//! 'files': { -//! 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19}, -//! 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20} -//! } -//! } -//! ``` -//! -//! `xxxxxxxxxxxxxxxxxxxx` and `yyyyyyyyyyyyyyyyyyyy` are 20-byte infohash arrays. -//! There are two data structures for infohashes: byte arrays and hex strings: -//! -//! ```rust,no_run -//! use bittorrent_primitives::info_hash::InfoHash; -//! use std::str::FromStr; -//! -//! let info_hash: InfoHash = [255u8; 20].into(); -//! -//! assert_eq!( -//! info_hash, -//! InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() -//! ); -//! ``` -//! Refer to `BitTorrent` BEPs and other sites for more information about the `scrape` request: -//! -//! - [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) -//! - [BEP 15. UDP Tracker Protocol for `BitTorrent`. Scrape section](https://www.bittorrent.org/beps/bep_0015.html) -//! - [Vuze docs](https://wiki.vuze.com/w/Scrape) -//! -//! ## Torrents -//! -//! The [`torrent`] module contains all the data structures stored by the `Tracker` except for peers. -//! -//! We can represent the data stored in memory internally by the `Tracker` with this JSON object: -//! -//! ```json -//! { -//! "c1277613db1d28709b034a017ab2cae4be07ae10": { -//! "completed": 0, -//! "peers": { -//! "-qB00000000000000001": { -//! "peer_id": "-qB00000000000000001", -//! "peer_addr": "2.137.87.41:1754", -//! "updated": 1672419840, -//! "uploaded": 120, -//! "downloaded": 60, -//! "left": 60, -//! "event": "started" -//! }, -//! "-qB00000000000000002": { -//! "peer_id": "-qB00000000000000002", -//! "peer_addr": "23.17.287.141:2345", -//! "updated": 1679415984, -//! "uploaded": 80, -//! "downloaded": 20, -//! "left": 40, -//! "event": "started" -//! } -//! } -//! } -//! } -//! ``` -//! -//! The `Tracker` maintains an indexed-by-info-hash list of torrents. For each torrent, it stores a torrent `Entry`. -//! The torrent entry has two attributes: -//! -//! - `completed`: which is hte number of peers that have completed downloading the torrent file/s. As they have completed downloading, -//! they have a full version of the torrent data, and they can provide the full data to other peers. That's why they are also known as "seeders". -//! - `peers`: an indexed and orderer list of peer for the torrent. Each peer contains the data received from the peer in the `announce` request. -//! -//! The [`torrent`] module not only contains the original data obtained from peer via `announce` requests, it also contains -//! aggregate data that can be derived from the original data. For example: -//! -//! ```rust,no_run -//! pub struct SwarmMetadata { -//! pub complete: u32, // The number of active peers that have completed downloading (seeders) -//! pub downloaded: u32, // The number of peers that have ever completed downloading -//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) -//! } -//! -//! ``` -//! -//! > **NOTICE**: that `complete` or `completed` peers are the peers that have completed downloading, but only the active ones are considered "seeders". -//! -//! `SwarmMetadata` struct follows name conventions for `scrape` responses. See [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmMetadata` -//! is used for the rest of cases. -//! -//! Refer to [`torrent`] module for more details about these data structures. -//! -//! ## Peers -//! -//! A `Peer` is the struct used by the `Tracker` to keep peers data: -//! -//! ```rust,no_run -//! use std::net::SocketAddr; - -//! use aquatic_udp_protocol::PeerId; -//! use torrust_tracker_primitives::DurationSinceUnixEpoch; -//! use aquatic_udp_protocol::NumberOfBytes; -//! use aquatic_udp_protocol::AnnounceEvent; -//! -//! pub struct Peer { -//! pub peer_id: PeerId, // The peer ID -//! pub peer_addr: SocketAddr, // Peer socket address -//! pub updated: DurationSinceUnixEpoch, // Last time (timestamp) when the peer was updated -//! pub uploaded: NumberOfBytes, // Number of bytes the peer has uploaded so far -//! pub downloaded: NumberOfBytes, // Number of bytes the peer has downloaded so far -//! pub left: NumberOfBytes, // The number of bytes this peer still has to download -//! pub event: AnnounceEvent, // The event the peer has announced: `started`, `completed`, `stopped` -//! } -//! ``` -//! -//! Notice that most of the attributes are obtained from the `announce` request. -//! For example, an HTTP announce request would contain the following `GET` parameters: -//! -//! -//! -//! The `Tracker` keeps an in-memory ordered data structure with all the torrents and a list of peers for each torrent, together with some swarm metrics. -//! -//! We can represent the data stored in memory with this JSON object: -//! -//! ```json -//! { -//! "c1277613db1d28709b034a017ab2cae4be07ae10": { -//! "completed": 0, -//! "peers": { -//! "-qB00000000000000001": { -//! "peer_id": "-qB00000000000000001", -//! "peer_addr": "2.137.87.41:1754", -//! "updated": 1672419840, -//! "uploaded": 120, -//! "downloaded": 60, -//! "left": 60, -//! "event": "started" -//! }, -//! "-qB00000000000000002": { -//! "peer_id": "-qB00000000000000002", -//! "peer_addr": "23.17.287.141:2345", -//! "updated": 1679415984, -//! "uploaded": 80, -//! "downloaded": 20, -//! "left": 40, -//! "event": "started" -//! } -//! } -//! } -//! } -//! ``` -//! -//! That JSON object does not exist, it's only a representation of the `Tracker` torrents data. -//! -//! `c1277613db1d28709b034a017ab2cae4be07ae10` is the torrent infohash and `completed` contains the number of peers -//! that have a full version of the torrent data, also known as seeders. -//! -//! Refer to [`peer`](torrust_tracker_primitives::peer) for more information about peers. +//! Refer to [torrust-tracker-configuration](https://docs.rs/torrust-tracker-configuration) +//! crate docs to get more information about the tracker settings. //! //! # Configuration //! -//! You can control the behavior of this module with the module settings: +//! You can control the behavior of this crate with the `Core` settings: //! //! ```toml //! [logging] @@ -341,35 +83,41 @@ //! //! Refer to the [`configuration` module documentation](https://docs.rs/torrust-tracker-configuration) to get more information about all options. //! -//! Services can include extra features like pagination, for example. +//! # Announce handler +//! +//! The `AnnounceHandler` is responsible for handling announce requests. +//! +//! Please refer to the [`announce_handler`] documentation. +//! +//! # Scrape handler +//! +//! The `ScrapeHandler` is responsible for handling scrape requests. +//! +//! Please refer to the [`scrape_handler`] documentation. //! //! # Authentication //! -//! One of the core `Tracker` responsibilities is to create and keep authentication keys. Auth keys are used by HTTP trackers -//! when the tracker is running in `private` or `private_listed` mode. +//! The `Authentication` module is responsible for handling authentication keys which are used by HTTP trackers. +//! +//! Please refer to the [`authentication`] documentation. //! -//! HTTP tracker's clients need to obtain an auth key before starting requesting the tracker. Once the get one they have to include -//! a `PATH` param with the key in all the HTTP requests. For example, when a peer wants to `announce` itself it has to use the -//! HTTP tracker endpoint `GET /announce/:key`. +//! # Databases //! -//! The common way to obtain the keys is by using the tracker API directly or via other applications like the [Torrust Index](https://github.com/torrust/torrust-index). +//! The `Databases` module is responsible for handling persistence of data into a database. //! -//! To learn more about tracker authentication, refer to the following modules : +//! Please refer to the [`databases`] documentation. //! -//! - [`authentication`] module. +//! # Torrent //! -//! # Persistence +//! The `Torrent` module is responsible for handling the torrent data. //! -//! Right now the `Tracker` is responsible for storing and load data into and -//! from the database, when persistence is enabled. +//! Please refer to the [`torrent`] documentation. //! -//! There are three types of persistent object: +//! # Whitelist //! -//! - Authentication keys (only expiring keys) -//! - Torrent whitelist -//! - Torrent metrics +//! The `Whitelist` module is responsible for handling the whitelist. //! -//! Refer to [`databases`] module for more information about persistence. +//! Please refer to the [`whitelist`] documentation. pub mod announce_handler; pub mod authentication; pub mod databases; diff --git a/packages/tracker-core/src/scrape_handler.rs b/packages/tracker-core/src/scrape_handler.rs index 60d15de71..1e75580ab 100644 --- a/packages/tracker-core/src/scrape_handler.rs +++ b/packages/tracker-core/src/scrape_handler.rs @@ -1,3 +1,64 @@ +//! Scrape handler. +//! +//! The `scrape` request allows clients to query metadata about the swarm in bulk. +//! +//! An `scrape` request includes a list of infohashes whose swarm metadata you +//! want to collect. +//! +//! ## Scrape Response Format +//! +//! The returned struct is: +//! +//! ```rust,no_run +//! use bittorrent_primitives::info_hash::InfoHash; +//! use std::collections::HashMap; +//! +//! pub struct ScrapeData { +//! pub files: HashMap, +//! } +//! +//! pub struct SwarmMetadata { +//! pub complete: u32, // The number of active peers that have completed downloading (seeders) +//! pub downloaded: u32, // The number of peers that have ever completed downloading +//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) +//! } +//! ``` +//! +//! ## Example JSON Response +//! +//! The JSON representation of a sample `scrape` response would be like the following: +//! +//! ```json +//! { +//! 'files': { +//! 'xxxxxxxxxxxxxxxxxxxx': {'complete': 11, 'downloaded': 13772, 'incomplete': 19}, +//! 'yyyyyyyyyyyyyyyyyyyy': {'complete': 21, 'downloaded': 206, 'incomplete': 20} +//! } +//! } +//! ``` +//! +//! `xxxxxxxxxxxxxxxxxxxx` and `yyyyyyyyyyyyyyyyyyyy` are 20-byte infohash arrays. +//! There are two data structures for infohashes: byte arrays and hex strings: +//! +//! ```rust,no_run +//! use bittorrent_primitives::info_hash::InfoHash; +//! use std::str::FromStr; +//! +//! let info_hash: InfoHash = [255u8; 20].into(); +//! +//! assert_eq!( +//! info_hash, +//! InfoHash::from_str("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap() +//! ); +//! ``` +//! +//! ## References: +//! +//! Refer to `BitTorrent` BEPs and other sites for more information about the `scrape` request: +//! +//! - [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) +//! - [BEP 15. UDP Tracker Protocol for `BitTorrent`. Scrape section](https://www.bittorrent.org/beps/bep_0015.html) +//! - [Vuze docs](https://wiki.vuze.com/w/Scrape) use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; @@ -7,8 +68,9 @@ use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use super::torrent::repository::in_memory::InMemoryTorrentRepository; use super::whitelist; +/// Handles scrape requests, providing torrent swarm metadata. pub struct ScrapeHandler { - /// The service to check is a torrent is whitelisted. + /// Service for authorizing access to whitelisted torrents. whitelist_authorization: Arc, /// The in-memory torrents repository. @@ -16,6 +78,7 @@ pub struct ScrapeHandler { } impl ScrapeHandler { + /// Creates a new `ScrapeHandler` instance. #[must_use] pub fn new( whitelist_authorization: &Arc, @@ -27,9 +90,14 @@ impl ScrapeHandler { } } - /// It handles a scrape request. + /// Handles a scrape request for multiple torrents. /// - /// BEP 48: [Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html). + /// - Returns metadata for each requested torrent. + /// - If a torrent isn't whitelisted or doesn't exist, returns zeroed stats. + /// + /// # BEP Reference: + /// + /// [BEP 48: Scrape Protocol](https://www.bittorrent.org/beps/bep_0048.html) pub async fn scrape(&self, info_hashes: &Vec) -> ScrapeData { let mut scrape_data = ScrapeData::empty(); diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index 9dac35258..51df97fb5 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -1,3 +1,4 @@ +//! Torrents manager. use std::sync::Arc; use std::time::Duration; @@ -8,6 +9,18 @@ use super::repository::in_memory::InMemoryTorrentRepository; use super::repository::persisted::DatabasePersistentTorrentRepository; use crate::{databases, CurrentClock}; +/// The `TorrentsManager` is responsible for managing torrent entries by +/// integrating persistent storage and in-memory state. It provides methods to +/// load torrent data from the database into memory, and to periodically clean +/// up stale torrent entries by removing inactive peers or entire torrent +/// entries that no longer have active peers. +/// +/// This manager relies on two repositories: +/// +/// - An **in-memory repository** to provide fast access to the current torrent +/// state. +/// - A **persistent repository** that stores aggregate torrent metrics (e.g., +/// seeders count) across tracker restarts. pub struct TorrentsManager { /// The tracker configuration. config: Core, @@ -21,6 +34,19 @@ pub struct TorrentsManager { } impl TorrentsManager { + /// Creates a new instance of `TorrentsManager`. + /// + /// # Arguments + /// + /// * `config` - A reference to the tracker configuration. + /// * `in_memory_torrent_repository` - A shared reference to the in-memory + /// repository of torrents. + /// * `db_torrent_repository` - A shared reference to the persistent + /// repository for torrent metrics. + /// + /// # Returns + /// + /// A new `TorrentsManager` instance with cloned references of the provided dependencies. #[must_use] pub fn new( config: &Core, @@ -34,13 +60,16 @@ impl TorrentsManager { } } - /// It loads the torrents from database into memory. It only loads the - /// torrent entry list with the number of seeders for each torrent. Peers - /// data is not persisted. + /// Loads torrents from the persistent database into the in-memory repository. + /// + /// This function retrieves the list of persistent torrent entries (which + /// include only the aggregate metrics, not the detailed peer lists) from + /// the database, and then imports that data into the in-memory repository. /// /// # Errors /// - /// Will return a `database::Error` if unable to load the list of `persistent_torrents` from the database. + /// Returns a `databases::error::Error` if unable to load the persistent + /// torrent data. #[allow(dead_code)] pub(crate) fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { let persistent_torrents = self.db_torrent_repository.load_all()?; @@ -50,7 +79,18 @@ impl TorrentsManager { Ok(()) } - /// Remove inactive peers and (optionally) peerless torrents. + /// Cleans up torrent entries by removing inactive peers and, optionally, + /// torrents with no active peers. + /// + /// This function performs two cleanup tasks: + /// + /// 1. It removes peers from torrent entries that have not been updated + /// within a cutoff time. The cutoff time is calculated as the current + /// time minus the maximum allowed peer timeout, as specified in the + /// tracker policy. + /// 2. If the tracker is configured to remove peerless torrents + /// (`remove_peerless_torrents` is set), it removes entire torrent + /// entries that have no active peers. pub fn cleanup_torrents(&self) { let current_cutoff = CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout))) .unwrap_or_default(); diff --git a/packages/tracker-core/src/torrent/mod.rs b/packages/tracker-core/src/torrent/mod.rs index 7ca9000f8..8ee8fa6d3 100644 --- a/packages/tracker-core/src/torrent/mod.rs +++ b/packages/tracker-core/src/torrent/mod.rs @@ -1,30 +1,168 @@ -//! Structs to store the swarm data. +//! Swarm Data Structures. //! -//! There are to main data structures: +//! This module defines the primary data structures used to store and manage +//! swarm data within the tracker. In `BitTorrent` terminology, a "swarm" is +//! the collection of peers that are sharing or downloading a given torrent. //! -//! - A torrent [`Entry`](torrust_tracker_torrent_repository::entry::Entry): it contains all the information stored by the tracker for one torrent. -//! - The [`SwarmMetadata`](torrust_tracker_primitives::swarm_metadata::SwarmMetadata): it contains aggregate information that can me derived from the torrent entries. +//! There are two main types of data stored: //! -//! A "swarm" is a network of peers that are trying to download the same torrent. +//! - **Torrent Entry** (`Entry`): Contains all the information the tracker +//! stores for a single torrent, including the list of peers currently in the +//! swarm. This data is crucial for peers to locate each other and initiate +//! downloads. //! -//! The torrent entry contains the "swarm" data, which is basically the list of peers in the swarm. -//! That's the most valuable information the peer want to get from the tracker, because it allows them to -//! start downloading torrent from those peers. +//! - **Swarm Metadata** (`SwarmMetadata`): Contains aggregate data derived from +//! all torrent entries. This metadata is split into: +//! - **Active Peers Data:** Metrics related to the peers that are currently +//! active in the swarm. +//! - **Historical Data:** Metrics collected since the tracker started, such +//! as the total number of completed downloads. //! -//! The "swarm metadata" contains aggregate data derived from the torrent entries. There two types of data: +//! ## Metrics Collected //! -//! - For **active peers**: metrics related to the current active peers in the swarm. -//! - **Historical data**: since the tracker started running. +//! The tracker collects and aggregates the following metrics: //! -//! The tracker collects metrics for: +//! - The total number of peers that have completed downloading the torrent +//! since the tracker began collecting metrics. +//! - The number of completed downloads from peers that remain active (i.e., seeders). +//! - The number of active peers that have not completed downloading the torrent (i.e., leechers). //! -//! - The number of peers that have completed downloading the torrent since the tracker started collecting metrics. -//! - The number of peers that have completed downloading the torrent and are still active, that means they are actively participating in the network, -//! by announcing themselves periodically to the tracker. Since they have completed downloading they have a full copy of the torrent data. Peers with a -//! full copy of the data are called "seeders". -//! - The number of peers that have NOT completed downloading the torrent and are still active, that means they are actively participating in the network. -//! Peer that don not have a full copy of the torrent data are called "leechers". +//! This information is used both to inform peers about available connections +//! and to provide overall swarm statistics. //! +//! This module re-exports core types from the torrent repository crate to +//! simplify integration. +//! +//! ## Internal Data Structures +//! +//! The [`torrent`](crate::torrent) module contains all the data structures +//! stored by the tracker except for peers. +//! +//! We can represent the data stored in memory internally by the tracker with +//! this JSON object: +//! +//! ```json +//! { +//! "c1277613db1d28709b034a017ab2cae4be07ae10": { +//! "completed": 0, +//! "peers": { +//! "-qB00000000000000001": { +//! "peer_id": "-qB00000000000000001", +//! "peer_addr": "2.137.87.41:1754", +//! "updated": 1672419840, +//! "uploaded": 120, +//! "downloaded": 60, +//! "left": 60, +//! "event": "started" +//! }, +//! "-qB00000000000000002": { +//! "peer_id": "-qB00000000000000002", +//! "peer_addr": "23.17.287.141:2345", +//! "updated": 1679415984, +//! "uploaded": 80, +//! "downloaded": 20, +//! "left": 40, +//! "event": "started" +//! } +//! } +//! } +//! } +//! ``` +//! +//! The tracker maintains an indexed-by-info-hash list of torrents. For each +//! torrent, it stores a torrent `Entry`. The torrent entry has two attributes: +//! +//! - `completed`: which is hte number of peers that have completed downloading +//! the torrent file/s. As they have completed downloading, they have a full +//! version of the torrent data, and they can provide the full data to other +//! peers. That's why they are also known as "seeders". +//! - `peers`: an indexed and orderer list of peer for the torrent. Each peer +//! contains the data received from the peer in the `announce` request. +//! +//! The [`crate::torrent`] module not only contains the original data obtained +//! from peer via `announce` requests, it also contains aggregate data that can +//! be derived from the original data. For example: +//! +//! ```rust,no_run +//! pub struct SwarmMetadata { +//! pub complete: u32, // The number of active peers that have completed downloading (seeders) +//! pub downloaded: u32, // The number of peers that have ever completed downloading +//! pub incomplete: u32, // The number of active peers that have not completed downloading (leechers) +//! } +//! ``` +//! +//! > **NOTICE**: that `complete` or `completed` peers are the peers that have +//! > completed downloading, but only the active ones are considered "seeders". +//! +//! `SwarmMetadata` struct follows name conventions for `scrape` responses. See +//! [BEP 48](https://www.bittorrent.org/beps/bep_0048.html), while `SwarmMetadata` +//! is used for the rest of cases. +//! +//! ## Peers +//! +//! A `Peer` is the struct used by the tracker to keep peers data: +//! +//! ```rust,no_run +//! use std::net::SocketAddr; +//! use aquatic_udp_protocol::PeerId; +//! use torrust_tracker_primitives::DurationSinceUnixEpoch; +//! use aquatic_udp_protocol::NumberOfBytes; +//! use aquatic_udp_protocol::AnnounceEvent; +//! +//! pub struct Peer { +//! pub peer_id: PeerId, // The peer ID +//! pub peer_addr: SocketAddr, // Peer socket address +//! pub updated: DurationSinceUnixEpoch, // Last time (timestamp) when the peer was updated +//! pub uploaded: NumberOfBytes, // Number of bytes the peer has uploaded so far +//! pub downloaded: NumberOfBytes, // Number of bytes the peer has downloaded so far +//! pub left: NumberOfBytes, // The number of bytes this peer still has to download +//! pub event: AnnounceEvent, // The event the peer has announced: `started`, `completed`, `stopped` +//! } +//! ``` +//! +//! Notice that most of the attributes are obtained from the `announce` request. +//! For example, an HTTP announce request would contain the following `GET` parameters: +//! +//! +//! +//! The `Tracker` keeps an in-memory ordered data structure with all the torrents and a list of peers for each torrent, together with some swarm metrics. +//! +//! We can represent the data stored in memory with this JSON object: +//! +//! ```json +//! { +//! "c1277613db1d28709b034a017ab2cae4be07ae10": { +//! "completed": 0, +//! "peers": { +//! "-qB00000000000000001": { +//! "peer_id": "-qB00000000000000001", +//! "peer_addr": "2.137.87.41:1754", +//! "updated": 1672419840, +//! "uploaded": 120, +//! "downloaded": 60, +//! "left": 60, +//! "event": "started" +//! }, +//! "-qB00000000000000002": { +//! "peer_id": "-qB00000000000000002", +//! "peer_addr": "23.17.287.141:2345", +//! "updated": 1679415984, +//! "uploaded": 80, +//! "downloaded": 20, +//! "left": 40, +//! "event": "started" +//! } +//! } +//! } +//! } +//! ``` +//! +//! That JSON object does not exist, it's only a representation of the `Tracker` torrents data. +//! +//! `c1277613db1d28709b034a017ab2cae4be07ae10` is the torrent infohash and `completed` contains the number of peers +//! that have a full version of the torrent data, also known as seeders. +//! +//! Refer to [`peer`](torrust_tracker_primitives::peer) for more information about peers. pub mod manager; pub mod repository; pub mod services; @@ -33,7 +171,11 @@ pub mod services; use torrust_tracker_torrent_repository::EntryMutexStd; use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; -// Currently used types from the torrent repository crate. +/// Alias for the primary torrent collection type, implemented as a skip map +/// wrapped in a mutex. This type is used internally by the tracker to manage +/// and access torrent entries. pub(crate) type Torrents = TorrentsSkipMapMutexStd; + +/// Alias for a single torrent entry. #[cfg(test)] pub(crate) type TorrentEntry = EntryMutexStd; diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 26302260b..584feabc9 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -1,3 +1,4 @@ +//! In-memory torrents repository. use std::cmp::max; use std::sync::Arc; @@ -13,51 +14,126 @@ use torrust_tracker_torrent_repository::EntryMutexStd; use crate::torrent::Torrents; -/// The in-memory torrents repository. +/// In-memory repository for torrent entries. /// -/// There are many implementations of the repository trait. We tried with -/// different types of data structures, but the best performance was with -/// the one we use for production. We kept the other implementations for -/// reference. +/// This repository manages the torrent entries and their associated peer lists +/// in memory. It is built on top of a high-performance data structure (the +/// production implementation) and provides methods to update, query, and remove +/// torrent entries as well as to import persisted data. +/// +/// Multiple implementations were considered, and the chosen implementation is +/// used in production. Other implementations are kept for reference. #[derive(Debug, Default)] pub struct InMemoryTorrentRepository { - /// The in-memory torrents repository implementation. + /// The underlying in-memory data structure that stores torrent entries. torrents: Arc, } impl InMemoryTorrentRepository { - /// It inserts (or updates if it's already in the list) the peer in the - /// torrent entry. + /// Inserts or updates a peer in the torrent entry corresponding to the + /// given infohash. + /// + /// If the torrent entry already exists, the peer is added to its peer list; + /// otherwise, a new torrent entry is created. + /// + /// # Arguments + /// + /// * `info_hash` - The unique identifier of the torrent. + /// * `peer` - The peer to insert or update in the torrent entry. pub fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { self.torrents.upsert_peer(info_hash, peer); } + /// Removes a torrent entry from the repository. + /// + /// This method is only available in tests. It removes the torrent entry + /// associated with the given info hash and returns the removed entry if it + /// existed. + /// + /// # Arguments + /// + /// * `key` - The info hash of the torrent to remove. + /// + /// # Returns + /// + /// An `Option` containing the removed torrent entry if it existed. #[cfg(test)] #[must_use] pub(crate) fn remove(&self, key: &InfoHash) -> Option { self.torrents.remove(key) } + /// Removes inactive peers from all torrent entries. + /// + /// A peer is considered inactive if its last update timestamp is older than + /// the provided cutoff time. + /// + /// # Arguments + /// + /// * `current_cutoff` - The cutoff timestamp; peers not updated since this + /// time will be removed. pub(crate) fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { self.torrents.remove_inactive_peers(current_cutoff); } + /// Removes torrent entries that have no active peers. + /// + /// Depending on the tracker policy, torrents without any peers may be + /// removed to conserve memory. + /// + /// # Arguments + /// + /// * `policy` - The tracker policy containing the configuration for + /// removing peerless torrents. pub(crate) fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { self.torrents.remove_peerless_torrents(policy); } + /// Retrieves a torrent entry by its infohash. + /// + /// # Arguments + /// + /// * `key` - The info hash of the torrent. + /// + /// # Returns + /// + /// An `Option` containing the torrent entry if found. #[must_use] pub(crate) fn get(&self, key: &InfoHash) -> Option { self.torrents.get(key) } + /// Retrieves a paginated list of torrent entries. + /// + /// This method returns a vector of tuples, each containing an infohash and + /// its associated torrent entry. The pagination parameters (offset and limit) + /// can be used to control the size of the result set. + /// + /// # Arguments + /// + /// * `pagination` - An optional reference to a `Pagination` object. + /// + /// # Returns + /// + /// A vector of `(InfoHash, EntryMutexStd)` tuples. #[must_use] pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { self.torrents.get_paginated(pagination) } - /// It returns the data for a `scrape` response or empty if the torrent is - /// not found. + /// Retrieves swarm metadata for a given torrent. + /// + /// This method returns the swarm metadata (aggregate information such as + /// peer counts) for the torrent specified by the infohash. If the torrent + /// entry is not found, a zeroed metadata struct is returned. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// + /// # Returns + /// + /// A `SwarmMetadata` struct containing the aggregated torrent data. #[must_use] pub(crate) fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { match self.torrents.get(info_hash) { @@ -66,9 +142,23 @@ impl InMemoryTorrentRepository { } } - /// Get torrent peers for a given torrent and client. + /// Retrieves torrent peers for a given torrent and client, excluding the + /// requesting client. + /// + /// This method filters out the client making the request (based on its + /// network address) and returns up to a maximum number of peers, defined by + /// the greater of the provided limit or the global `TORRENT_PEERS_LIMIT`. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// * `peer` - The client peer that should be excluded from the returned list. + /// * `limit` - The maximum number of peers to return. + /// + /// # Returns /// - /// It filters out the client making the request. + /// A vector of peers (wrapped in `Arc`) representing the active peers for + /// the torrent, excluding the requesting client. #[must_use] pub(crate) fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { match self.torrents.get(info_hash) { @@ -77,7 +167,19 @@ impl InMemoryTorrentRepository { } } - /// Get torrent peers for a given torrent. + /// Retrieves the list of peers for a given torrent. + /// + /// This method returns up to `TORRENT_PEERS_LIMIT` peers for the torrent + /// specified by the info-hash. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// + /// # Returns + /// + /// A vector of peers (wrapped in `Arc`) representing the active peers for + /// the torrent. #[must_use] pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { match self.torrents.get(info_hash) { @@ -86,12 +188,28 @@ impl InMemoryTorrentRepository { } } - /// It calculates and returns the general [`TorrentsMetrics`]. + /// Calculates and returns overall torrent metrics. + /// + /// The returned [`TorrentsMetrics`] contains aggregate data such as the + /// total number of torrents, total complete (seeders), incomplete (leechers), + /// and downloaded counts. + /// + /// # Returns + /// + /// A [`TorrentsMetrics`] struct with the aggregated metrics. #[must_use] pub fn get_torrents_metrics(&self) -> TorrentsMetrics { self.torrents.get_metrics() } + /// Imports persistent torrent data into the in-memory repository. + /// + /// This method takes a set of persisted torrent entries (e.g., from a database) + /// and imports them into the in-memory repository for immediate access. + /// + /// # Arguments + /// + /// * `persistent_torrents` - A reference to the persisted torrent data. pub fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { self.torrents.import_persistent(persistent_torrents); } diff --git a/packages/tracker-core/src/torrent/repository/mod.rs b/packages/tracker-core/src/torrent/repository/mod.rs index 51723b68d..ae789e5e9 100644 --- a/packages/tracker-core/src/torrent/repository/mod.rs +++ b/packages/tracker-core/src/torrent/repository/mod.rs @@ -1,2 +1,3 @@ +//! Torrent repository implementations. pub mod in_memory; pub mod persisted; diff --git a/packages/tracker-core/src/torrent/repository/persisted.rs b/packages/tracker-core/src/torrent/repository/persisted.rs index 0430f03bb..694a2fe7c 100644 --- a/packages/tracker-core/src/torrent/repository/persisted.rs +++ b/packages/tracker-core/src/torrent/repository/persisted.rs @@ -1,3 +1,4 @@ +//! The repository that stored persistent torrents' data into the database. use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; @@ -6,17 +7,39 @@ use torrust_tracker_primitives::PersistentTorrents; use crate::databases::error::Error; use crate::databases::Database; -/// Torrent repository implementation that persists the torrents in a database. +/// Torrent repository implementation that persists torrent metrics in a database. /// -/// Not all the torrent in-memory data is persisted. For now only some of the -/// torrent metrics are persisted. +/// This repository persists only a subset of the torrent data: the torrent +/// metrics, specifically the number of downloads (or completed counts) for each +/// torrent. It relies on a database driver (either `SQLite3` or `MySQL`) that +/// implements the [`Database`] trait to perform the actual persistence +/// operations. +/// +/// # Note +/// +/// Not all in-memory torrent data is persisted; only the aggregate metrics are +/// stored. pub struct DatabasePersistentTorrentRepository { - /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) - /// or [`MySQL`](crate::core::databases::mysql) + /// A shared reference to the database driver implementation. + /// + /// The driver must implement the [`Database`] trait. This allows for + /// different underlying implementations (e.g., `SQLite3` or `MySQL`) to be + /// used interchangeably. database: Arc>, } impl DatabasePersistentTorrentRepository { + /// Creates a new instance of `DatabasePersistentTorrentRepository`. + /// + /// # Arguments + /// + /// * `database` - A shared reference to a boxed database driver + /// implementing the [`Database`] trait. + /// + /// # Returns + /// + /// A new `DatabasePersistentTorrentRepository` instance with a cloned + /// reference to the provided database. #[must_use] pub fn new(database: &Arc>) -> DatabasePersistentTorrentRepository { Self { @@ -24,20 +47,31 @@ impl DatabasePersistentTorrentRepository { } } - /// It loads the persistent torrents from the database. + /// Loads all persistent torrent metrics from the database. + /// + /// This function retrieves the torrent metrics (e.g., download counts) from the persistent store + /// and returns them as a [`PersistentTorrents`] map. /// /// # Errors /// - /// Will return a database `Err` if unable to load. + /// Returns an [`Error`] if the underlying database query fails. pub(crate) fn load_all(&self) -> Result { self.database.load_persistent_torrents() } - /// It saves the persistent torrent into the database. + /// Saves the persistent torrent metric into the database. + /// + /// This function stores or updates the download count for the torrent + /// identified by the provided infohash. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// * `downloaded` - The number of times the torrent has been downloaded. /// /// # Errors /// - /// Will return a database `Err` if unable to save. + /// Returns an [`Error`] if the database operation fails. pub(crate) fn save(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error> { self.database.save_persistent_torrent(info_hash, downloaded) } diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index 4c470bb74..98d25ba47 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -1,9 +1,17 @@ //! Core tracker domain services. //! -//! There are two services: +//! This module defines the primary services for retrieving torrent-related data +//! from the tracker. There are two main services: //! -//! - [`get_torrent_info`]: it returns all the data about one torrent. -//! - [`get_torrents`]: it returns data about some torrent in bulk excluding the peer list. +//! - [`get_torrent_info`]: Returns all available data (including the list of +//! peers) about a single torrent. +//! - [`get_torrents_page`] and [`get_torrents`]: Return summarized data about +//! multiple torrents, excluding the peer list. +//! +//! The full torrent info is represented by the [`Info`] struct, which includes +//! swarm data (peer list) and aggregate metrics. The [`BasicInfo`] struct +//! provides similar data but without the list of peers, making it suitable for +//! bulk queries. use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; @@ -13,37 +21,74 @@ use torrust_tracker_torrent_repository::entry::EntrySync; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; -/// It contains all the information the tracker has about a torrent +/// Full torrent information, including swarm (peer) details. +/// +/// This struct contains all the information that the tracker holds about a +/// torrent, including the infohash, aggregate swarm metrics (seeders, leechers, +/// completed downloads), and the complete list of peers in the swarm. #[derive(Debug, PartialEq)] pub struct Info { /// The infohash of the torrent this data is related to pub info_hash: InfoHash, - /// The total number of seeders for this torrent. Peer that actively serving a full copy of the torrent data + + /// The total number of seeders for this torrent. Peer that actively serving + /// a full copy of the torrent data pub seeders: u64, - /// The total number of peers that have ever complete downloading this torrent + + /// The total number of peers that have ever complete downloading this + /// torrent pub completed: u64, - /// The total number of leechers for this torrent. Peers that actively downloading this torrent + + /// The total number of leechers for this torrent. Peers that actively + /// downloading this torrent pub leechers: u64, - /// The swarm: the list of peers that are actively trying to download or serving this torrent + + /// The swarm: the list of peers that are actively trying to download or + /// serving this torrent pub peers: Option>, } -/// It contains only part of the information the tracker has about a torrent +/// Basic torrent information, excluding the list of peers. /// -/// It contains the same data as [Info] but without the list of peers in the swarm. +/// This struct contains the same aggregate metrics as [`Info`] (infohash, +/// seeders, completed, leechers) but omits the peer list. It is used when only +/// summary information is needed. #[derive(Debug, PartialEq, Clone)] pub struct BasicInfo { /// The infohash of the torrent this data is related to pub info_hash: InfoHash, - /// The total number of seeders for this torrent. Peer that actively serving a full copy of the torrent data + + /// The total number of seeders for this torrent. Peer that actively serving + /// a full copy of the torrent data pub seeders: u64, - /// The total number of peers that have ever complete downloading this torrent + + /// The total number of peers that have ever complete downloading this + /// torrent pub completed: u64, - /// The total number of leechers for this torrent. Peers that actively downloading this torrent + + /// The total number of leechers for this torrent. Peers that actively + /// downloading this torrent pub leechers: u64, } -/// It returns all the information the tracker has about one torrent in a [Info] struct. +/// Retrieves complete torrent information for a given torrent. +/// +/// This function queries the in-memory torrent repository for a torrent entry +/// matching the provided infohash. If found, it extracts the swarm metadata +/// (aggregate metrics) and the current list of peers, and returns an [`Info`] +/// struct. +/// +/// # Arguments +/// +/// * `in_memory_torrent_repository` - A shared reference to the in-memory +/// torrent repository. +/// * `info_hash` - A reference to the torrent's infohash. +/// +/// # Returns +/// +/// An [`Option`] which is: +/// - `Some(Info)` if the torrent exists in the repository. +/// - `None` if the torrent is not found. #[must_use] pub fn get_torrent_info(in_memory_torrent_repository: &Arc, info_hash: &InfoHash) -> Option { let torrent_entry_option = in_memory_torrent_repository.get(info_hash); @@ -65,7 +110,23 @@ pub fn get_torrent_info(in_memory_torrent_repository: &Arc, @@ -87,7 +148,23 @@ pub fn get_torrents_page( basic_infos } -/// It returns all the information the tracker has about multiple torrents in a [`BasicInfo`] struct, excluding the peer list. +/// Retrieves summarized torrent information for a specified list of torrents. +/// +/// This function iterates over a slice of infohashes, fetches the corresponding +/// swarm metadata from the in-memory repository (if available), and returns a +/// vector of [`BasicInfo`] structs. This function is useful for bulk queries +/// where detailed peer information is not required. +/// +/// # Arguments +/// +/// * `in_memory_torrent_repository` - A shared reference to the in-memory +/// torrent repository. +/// * `info_hashes` - A slice of infohashes for which to retrieve the torrent +/// information. +/// +/// # Returns +/// +/// A vector of [`BasicInfo`] structs for the requested torrents. #[must_use] pub fn get_torrents(in_memory_torrent_repository: &Arc, info_hashes: &[InfoHash]) -> Vec { let mut basic_infos: Vec = vec![]; diff --git a/packages/tracker-core/src/whitelist/authorization.rs b/packages/tracker-core/src/whitelist/authorization.rs index 3b7b8b4fb..a8323457b 100644 --- a/packages/tracker-core/src/whitelist/authorization.rs +++ b/packages/tracker-core/src/whitelist/authorization.rs @@ -1,3 +1,4 @@ +//! Whitelist authorization. use std::panic::Location; use std::sync::Arc; @@ -8,6 +9,10 @@ use tracing::instrument; use super::repository::in_memory::InMemoryWhitelist; use crate::error::WhitelistError; +/// Manages the authorization of torrents based on the whitelist. +/// +/// Used to determine whether a given torrent (`infohash`) is allowed +/// to be announced or scraped from the tracker. pub struct WhitelistAuthorization { /// Core tracker configuration. config: Core, @@ -17,7 +22,14 @@ pub struct WhitelistAuthorization { } impl WhitelistAuthorization { - /// Creates a new authorization instance. + /// Creates a new `WhitelistAuthorization` instance. + /// + /// # Arguments + /// - `config`: Tracker configuration. + /// - `in_memory_whitelist`: The in-memory whitelist instance. + /// + /// # Returns + /// A new `WhitelistAuthorization` instance. pub fn new(config: &Core, in_memory_whitelist: &Arc) -> Self { Self { config: config.clone(), @@ -25,12 +37,15 @@ impl WhitelistAuthorization { } } - /// It returns true if the torrent is authorized. + /// Checks whether a torrent is authorized. /// - /// # Errors + /// - If the tracker is **public**, all torrents are authorized. + /// - If the tracker is **private** (listed mode), only whitelisted torrents + /// are authorized. /// - /// Will return an error if the tracker is running in `listed` mode - /// and the infohash is not whitelisted. + /// # Errors + /// Returns `WhitelistError::TorrentNotWhitelisted` if the tracker is in `listed` mode + /// and the `info_hash` is not in the whitelist. #[instrument(skip(self, info_hash), err)] pub async fn authorize(&self, info_hash: &InfoHash) -> Result<(), WhitelistError> { if !self.is_listed() { @@ -47,12 +62,12 @@ impl WhitelistAuthorization { }) } - /// Returns `true` is the tracker is in listed mode. + /// Checks if the tracker is running in "listed" mode. fn is_listed(&self) -> bool { self.config.listed } - /// It checks if a torrent is whitelisted. + /// Checks if a torrent is present in the whitelist. async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> bool { self.in_memory_whitelist.contains(info_hash).await } diff --git a/packages/tracker-core/src/whitelist/manager.rs b/packages/tracker-core/src/whitelist/manager.rs index 5ebd6db36..452fcb6c5 100644 --- a/packages/tracker-core/src/whitelist/manager.rs +++ b/packages/tracker-core/src/whitelist/manager.rs @@ -1,3 +1,7 @@ +//! Whitelist manager. +//! +//! This module provides the `WhitelistManager` struct, which is responsible for +//! managing the whitelist of torrents. use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; @@ -5,8 +9,11 @@ use bittorrent_primitives::info_hash::InfoHash; use super::repository::in_memory::InMemoryWhitelist; use super::repository::persisted::DatabaseWhitelist; use crate::databases; - -/// It handles the list of allowed torrents. Only for listed trackers. +/// Manages the whitelist of allowed torrents. +/// +/// This structure handles both the in-memory and persistent representations of +/// the whitelist. It is primarily relevant for private trackers that restrict +/// access to specific torrents. pub struct WhitelistManager { /// The in-memory list of allowed torrents. in_memory_whitelist: Arc, @@ -16,6 +23,17 @@ pub struct WhitelistManager { } impl WhitelistManager { + /// Creates a new `WhitelistManager` instance. + /// + /// # Arguments + /// + /// - `database_whitelist`: Persistent database-backed whitelist repository. + /// - `in_memory_whitelist`: In-memory whitelist repository for fast runtime + /// access. + /// + /// # Returns + /// + /// A new `WhitelistManager` instance. #[must_use] pub fn new(database_whitelist: Arc, in_memory_whitelist: Arc) -> Self { Self { @@ -24,35 +42,39 @@ impl WhitelistManager { } } - /// It adds a torrent to the whitelist. - /// Adding torrents is not relevant to public trackers. + /// Adds a torrent to the whitelist. /// - /// # Errors + /// This operation is relevant for private trackers to control which + /// torrents are allowed. /// - /// Will return a `database::Error` if unable to add the `info_hash` into the whitelist database. + /// # Errors + /// Returns a `database::Error` if the operation fails in the database. pub async fn add_torrent_to_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { self.database_whitelist.add(info_hash)?; self.in_memory_whitelist.add(info_hash).await; Ok(()) } - /// It removes a torrent from the whitelist. - /// Removing torrents is not relevant to public trackers. + /// Removes a torrent from the whitelist. /// - /// # Errors + /// This operation is relevant for private trackers to revoke access to + /// specific torrents. /// - /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. + /// # Errors + /// Returns a `database::Error` if the operation fails in the database. pub async fn remove_torrent_from_whitelist(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { self.database_whitelist.remove(info_hash)?; self.in_memory_whitelist.remove(info_hash).await; Ok(()) } - /// It loads the whitelist from the database. + /// Loads the whitelist from the database into memory. /// - /// # Errors + /// This is useful when restarting the tracker to ensure the in-memory + /// whitelist is synchronized with the database. /// - /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. + /// # Errors + /// Returns a `database::Error` if the operation fails to load from the database. pub async fn load_whitelist_from_database(&self) -> Result<(), databases::error::Error> { let whitelisted_torrents_from_database = self.database_whitelist.load_from_database()?; diff --git a/packages/tracker-core/src/whitelist/mod.rs b/packages/tracker-core/src/whitelist/mod.rs index a39768e93..d9ad18311 100644 --- a/packages/tracker-core/src/whitelist/mod.rs +++ b/packages/tracker-core/src/whitelist/mod.rs @@ -1,3 +1,21 @@ +//! This module contains the logic to manage the torrent whitelist. +//! +//! In tracker configurations where the tracker operates in "listed" mode, only +//! torrents that have been explicitly added to the whitelist are allowed to +//! perform announce and scrape actions. This module provides all the +//! functionality required to manage such a whitelist. +//! +//! The module is organized into the following submodules: +//! +//! - **`authorization`**: Contains the logic to authorize torrents based on their +//! whitelist status. +//! - **`manager`**: Provides high-level management functions for the whitelist, +//! such as adding or removing torrents. +//! - **`repository`**: Implements persistence for whitelist data. +//! - **`setup`**: Provides initialization routines for setting up the whitelist +//! system. +//! - **`test_helpers`**: Contains helper functions and fixtures for testing +//! whitelist functionality. pub mod authorization; pub mod manager; pub mod repository; diff --git a/packages/tracker-core/src/whitelist/repository/in_memory.rs b/packages/tracker-core/src/whitelist/repository/in_memory.rs index 4faeda784..0cee3a94b 100644 --- a/packages/tracker-core/src/whitelist/repository/in_memory.rs +++ b/packages/tracker-core/src/whitelist/repository/in_memory.rs @@ -1,29 +1,42 @@ +//! The in-memory list of allowed torrents. use bittorrent_primitives::info_hash::InfoHash; -/// The in-memory list of allowed torrents. +/// In-memory whitelist to manage allowed torrents. +/// +/// Stores `InfoHash` values for quick lookup and modification. #[derive(Debug, Default)] pub struct InMemoryWhitelist { - /// The list of allowed torrents. + /// A thread-safe set of whitelisted `InfoHash` values. whitelist: tokio::sync::RwLock>, } impl InMemoryWhitelist { - /// It adds a torrent from the whitelist in memory. + /// Adds a torrent to the in-memory whitelist. + /// + /// # Returns + /// + /// - `true` if the torrent was newly added. + /// - `false` if the torrent was already in the whitelist. pub async fn add(&self, info_hash: &InfoHash) -> bool { self.whitelist.write().await.insert(*info_hash) } - /// It removes a torrent from the whitelist in memory. + /// Removes a torrent from the in-memory whitelist. + /// + /// # Returns + /// + /// - `true` if the torrent was present and removed. + /// - `false` if the torrent was not found. pub(crate) async fn remove(&self, info_hash: &InfoHash) -> bool { self.whitelist.write().await.remove(info_hash) } - /// It checks if it contains an info-hash. + /// Checks if a torrent is in the whitelist. pub async fn contains(&self, info_hash: &InfoHash) -> bool { self.whitelist.read().await.contains(info_hash) } - /// It clears the whitelist. + /// Clears all torrents from the whitelist. pub(crate) async fn clear(&self) { let mut whitelist = self.whitelist.write().await; whitelist.clear(); diff --git a/packages/tracker-core/src/whitelist/repository/mod.rs b/packages/tracker-core/src/whitelist/repository/mod.rs index 51723b68d..d900a8c29 100644 --- a/packages/tracker-core/src/whitelist/repository/mod.rs +++ b/packages/tracker-core/src/whitelist/repository/mod.rs @@ -1,2 +1,3 @@ +//! Repository implementations for the whitelist. pub mod in_memory; pub mod persisted; diff --git a/packages/tracker-core/src/whitelist/repository/persisted.rs b/packages/tracker-core/src/whitelist/repository/persisted.rs index 4773cfbe6..eec6704d6 100644 --- a/packages/tracker-core/src/whitelist/repository/persisted.rs +++ b/packages/tracker-core/src/whitelist/repository/persisted.rs @@ -1,3 +1,4 @@ +//! The repository that persists the whitelist. use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; @@ -5,6 +6,9 @@ use bittorrent_primitives::info_hash::InfoHash; use crate::databases::{self, Database}; /// The persisted list of allowed torrents. +/// +/// This repository handles adding, removing, and loading torrents +/// from a persistent database like `SQLite` or `MySQL`ç. pub struct DatabaseWhitelist { /// A database driver implementation: [`Sqlite3`](crate::core::databases::sqlite) /// or [`MySQL`](crate::core::databases::mysql) @@ -12,16 +16,17 @@ pub struct DatabaseWhitelist { } impl DatabaseWhitelist { + /// Creates a new `DatabaseWhitelist`. #[must_use] pub fn new(database: Arc>) -> Self { Self { database } } - /// It adds a torrent to the whitelist if it has not been whitelisted previously + /// Adds a torrent to the whitelist if not already present. /// /// # Errors - /// - /// Will return a `database::Error` if unable to add the `info_hash` to the whitelist database. + /// Returns a `database::Error` if unable to add the `info_hash` to the + /// whitelist. pub(crate) fn add(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; @@ -34,11 +39,10 @@ impl DatabaseWhitelist { Ok(()) } - /// It removes a torrent from the whitelist in the database. + /// Removes a torrent from the whitelist if it exists. /// /// # Errors - /// - /// Will return a `database::Error` if unable to remove the `info_hash` from the whitelist database. + /// Returns a `database::Error` if unable to remove the `info_hash`. pub(crate) fn remove(&self, info_hash: &InfoHash) -> Result<(), databases::error::Error> { let is_whitelisted = self.database.is_info_hash_whitelisted(*info_hash)?; @@ -51,11 +55,11 @@ impl DatabaseWhitelist { Ok(()) } - /// It loads the whitelist from the database. + /// Loads the entire whitelist from the database. /// /// # Errors - /// - /// Will return a `database::Error` if unable to load the list whitelisted `info_hash`s from the database. + /// Returns a `database::Error` if unable to load whitelisted `info_hash` + /// values. pub(crate) fn load_from_database(&self) -> Result, databases::error::Error> { self.database.load_whitelist() } diff --git a/packages/tracker-core/src/whitelist/setup.rs b/packages/tracker-core/src/whitelist/setup.rs index 5b2a5de40..cb18c1478 100644 --- a/packages/tracker-core/src/whitelist/setup.rs +++ b/packages/tracker-core/src/whitelist/setup.rs @@ -1,3 +1,7 @@ +//! Initializes the whitelist manager. +//! +//! This module provides functions to set up the `WhitelistManager`, which is responsible +//! for managing whitelisted torrents in both the in-memory and persistent database repositories. use std::sync::Arc; use super::manager::WhitelistManager; @@ -5,6 +9,28 @@ use super::repository::in_memory::InMemoryWhitelist; use super::repository::persisted::DatabaseWhitelist; use crate::databases::Database; +/// Initializes the `WhitelistManager` by combining in-memory and database +/// repositories. +/// +/// The `WhitelistManager` handles the operations related to whitelisted +/// torrents, such as adding, removing, and verifying torrents in the whitelist. +/// It operates with: +/// +/// 1. **In-Memory Whitelist:** Provides fast, runtime-based access to +/// whitelisted torrents. +/// 2. **Database Whitelist:** Ensures persistent storage of the whitelist data. +/// +/// # Arguments +/// +/// * `database` - An `Arc>` representing the database connection, +/// sed for persistent whitelist storage. +/// * `in_memory_whitelist` - An `Arc` representing the in-memory +/// whitelist repository for fast access. +/// +/// # Returns +/// +/// An `Arc` instance that manages both the in-memory and database +/// whitelist repositories. #[must_use] pub fn initialize_whitelist_manager( database: Arc>, diff --git a/packages/tracker-core/src/whitelist/test_helpers.rs b/packages/tracker-core/src/whitelist/test_helpers.rs index cc30c4476..cf1699be4 100644 --- a/packages/tracker-core/src/whitelist/test_helpers.rs +++ b/packages/tracker-core/src/whitelist/test_helpers.rs @@ -1,5 +1,8 @@ -//! Some generic test helpers functions. - +//! Generic test helper functions for the whitelist module. +//! +//! This module provides utility functions to initialize the whitelist services required for testing. +//! In particular, it sets up the `WhitelistAuthorization` and `WhitelistManager` services using a +//! configured database and an in-memory whitelist repository. #[cfg(test)] pub(crate) mod tests { From 35ca4280affaae18aecf84f01f952ee173cd7943 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 13 Feb 2025 12:47:19 +0000 Subject: [PATCH 0748/1297] test: [#1266] add integartion test for bittorrent_tracker_core lib --- packages/tracker-core/tests/integration.rs | 132 +++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 packages/tracker-core/tests/integration.rs diff --git a/packages/tracker-core/tests/integration.rs b/packages/tracker-core/tests/integration.rs new file mode 100644 index 000000000..4dbd60b9e --- /dev/null +++ b/packages/tracker-core/tests/integration.rs @@ -0,0 +1,132 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::str::FromStr; +use std::sync::Arc; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; +use bittorrent_tracker_core::databases::setup::initialize_database; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use bittorrent_tracker_core::whitelist; +use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use torrust_tracker_configuration::Core; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; + +/// # Panics +/// +/// Will panic if the temporary file path is not a valid UTF-8 string. +#[must_use] +pub fn ephemeral_configuration() -> Core { + let mut config = Core::default(); + + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + + config +} + +/// # Panics +/// +/// Will panic if the string representation of the info hash is not a valid infohash. +#[must_use] +pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") +} + +/// Sample peer whose state is not relevant for the tests. +#[must_use] +pub fn sample_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(remote_client_ip(), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } +} + +// The client peer IP. +#[must_use] +fn remote_client_ip() -> IpAddr { + IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) +} + +struct Container { + pub announce_handler: Arc, + pub scrape_handler: Arc, +} + +impl Container { + pub fn initialize(config: &Core) -> Self { + let database = initialize_database(config); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( + config, + &in_memory_whitelist.clone(), + )); + let announce_handler = Arc::new(AnnounceHandler::new( + config, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + Self { + announce_handler, + scrape_handler, + } + } +} + +#[tokio::test] +async fn test_announce_and_scrape_requests() { + let config = ephemeral_configuration(); + + let container = Container::initialize(&config); + + let info_hash = sample_info_hash(); + + let mut peer = sample_peer(); + + // Announce + + // First announce: download started + peer.event = AnnounceEvent::Started; + let announce_data = + container + .announce_handler + .announce(&info_hash, &mut peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible); + + // NOTICE: you don't get back the peer making the request. + assert_eq!(announce_data.peers.len(), 0); + assert_eq!(announce_data.stats.downloaded, 0); + + // Second announce: download completed + peer.event = AnnounceEvent::Completed; + let announce_data = + container + .announce_handler + .announce(&info_hash, &mut peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible); + + assert_eq!(announce_data.peers.len(), 0); + assert_eq!(announce_data.stats.downloaded, 1); + + // Scrape + + let scrape_data = container.scrape_handler.scrape(&vec![info_hash]).await; + + assert!(scrape_data.files.contains_key(&info_hash)); +} + +#[test] +fn test_scrape_request() {} From 81825c9a5b1546bda00f7ddfa70bf176937bf1a6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Feb 2025 12:32:59 +0000 Subject: [PATCH 0749/1297] refactor: [#1268] separate UDP handlers into diferent modules Following HTTP structure. --- src/servers/udp/handlers.rs | 1877 -------------------------- src/servers/udp/handlers/announce.rs | 875 ++++++++++++ src/servers/udp/handlers/connect.rs | 199 +++ src/servers/udp/handlers/error.rs | 80 ++ src/servers/udp/handlers/mod.rs | 366 +++++ src/servers/udp/handlers/scrape.rs | 429 ++++++ 6 files changed, 1949 insertions(+), 1877 deletions(-) delete mode 100644 src/servers/udp/handlers.rs create mode 100644 src/servers/udp/handlers/announce.rs create mode 100644 src/servers/udp/handlers/connect.rs create mode 100644 src/servers/udp/handlers/error.rs create mode 100644 src/servers/udp/handlers/mod.rs create mode 100644 src/servers/udp/handlers/scrape.rs diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs deleted file mode 100644 index 4f98f52d9..000000000 --- a/src/servers/udp/handlers.rs +++ /dev/null @@ -1,1877 +0,0 @@ -//! Handlers for the UDP server. -use std::hash::{DefaultHasher, Hash, Hasher as _}; -use std::net::{IpAddr, SocketAddr}; -use std::ops::Range; -use std::sync::Arc; -use std::time::Instant; - -use aquatic_udp_protocol::{ - AnnounceInterval, AnnounceRequest, AnnounceResponse, AnnounceResponseFixedData, ConnectRequest, ConnectResponse, - ErrorResponse, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfDownloads, NumberOfPeers, Port, Request, RequestParseError, Response, - ResponsePeer, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, -}; -use bittorrent_primitives::info_hash::InfoHash; -use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; -use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::whitelist; -use torrust_tracker_clock::clock::Time as _; -use torrust_tracker_configuration::Core; -use tracing::{instrument, Level}; -use uuid::Uuid; -use zerocopy::network_endian::I32; - -use super::connection_cookie::{check, make}; -use super::RawRequest; -use crate::container::UdpTrackerContainer; -use crate::packages::udp_tracker_core; -use crate::servers::udp::error::Error; -use crate::servers::udp::{peer_builder, UDP_TRACKER_LOG_TARGET}; -use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; -use crate::CurrentClock; - -#[derive(Debug, Clone, PartialEq)] -pub(super) struct CookieTimeValues { - pub(super) issue_time: f64, - pub(super) valid_range: Range, -} - -impl CookieTimeValues { - pub(super) fn new(cookie_lifetime: f64) -> Self { - let issue_time = CurrentClock::now().as_secs_f64(); - let expiry_time = issue_time - cookie_lifetime - 1.0; - let tolerance_max_time = issue_time + 1.0; - - Self { - issue_time, - valid_range: expiry_time..tolerance_max_time, - } - } -} - -/// It handles the incoming UDP packets. -/// -/// It's responsible for: -/// -/// - Parsing the incoming packet. -/// - Delegating the request to the correct handler depending on the request type. -/// -/// It will return an `Error` response if the request is invalid. -#[instrument(fields(request_id), skip(udp_request, udp_tracker_container, cookie_time_values), ret(level = Level::TRACE))] -pub(crate) async fn handle_packet( - udp_request: RawRequest, - udp_tracker_container: Arc, - local_addr: SocketAddr, - cookie_time_values: CookieTimeValues, -) -> Response { - let request_id = Uuid::new_v4(); - - tracing::Span::current().record("request_id", request_id.to_string()); - tracing::debug!("Handling Packets: {udp_request:?}"); - - let start_time = Instant::now(); - - let response = - match Request::parse_bytes(&udp_request.payload[..udp_request.payload.len()], MAX_SCRAPE_TORRENTS).map_err(Error::from) { - Ok(request) => match handle_request( - request, - udp_request.from, - udp_tracker_container.clone(), - cookie_time_values.clone(), - ) - .await - { - Ok(response) => return response, - Err((e, transaction_id)) => { - match &e { - Error::CookieValueNotNormal { .. } - | Error::CookieValueExpired { .. } - | Error::CookieValueFromFuture { .. } => { - // code-review: should we include `RequestParseError` and `BadRequest`? - let mut ban_service = udp_tracker_container.ban_service.write().await; - ban_service.increase_counter(&udp_request.from.ip()); - } - _ => {} - } - - handle_error( - udp_request.from, - local_addr, - request_id, - &udp_tracker_container.udp_stats_event_sender, - cookie_time_values.valid_range.clone(), - &e, - Some(transaction_id), - ) - .await - } - }, - Err(e) => { - handle_error( - udp_request.from, - local_addr, - request_id, - &udp_tracker_container.udp_stats_event_sender, - cookie_time_values.valid_range.clone(), - &e, - None, - ) - .await - } - }; - - let latency = start_time.elapsed(); - tracing::trace!(?latency, "responded"); - - response -} - -/// It dispatches the request to the correct handler. -/// -/// # Errors -/// -/// If a error happens in the `handle_request` function, it will just return the `ServerError`. -#[instrument(skip(request, remote_addr, udp_tracker_container, cookie_time_values))] -pub async fn handle_request( - request: Request, - remote_addr: SocketAddr, - udp_tracker_container: Arc, - cookie_time_values: CookieTimeValues, -) -> Result { - tracing::trace!("handle request"); - - match request { - Request::Connect(connect_request) => Ok(handle_connect( - remote_addr, - &connect_request, - &udp_tracker_container.udp_stats_event_sender, - cookie_time_values.issue_time, - ) - .await), - Request::Announce(announce_request) => { - handle_announce( - remote_addr, - &announce_request, - &udp_tracker_container.core_config, - &udp_tracker_container.announce_handler, - &udp_tracker_container.whitelist_authorization, - &udp_tracker_container.udp_stats_event_sender, - cookie_time_values.valid_range, - ) - .await - } - Request::Scrape(scrape_request) => { - handle_scrape( - remote_addr, - &scrape_request, - &udp_tracker_container.scrape_handler, - &udp_tracker_container.udp_stats_event_sender, - cookie_time_values.valid_range, - ) - .await - } - } -} - -/// It handles the `Connect` request. Refer to [`Connect`](crate::servers::udp#connect) -/// request for more information. -/// -/// # Errors -/// -/// This function does not ever return an error. -#[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] -pub async fn handle_connect( - remote_addr: SocketAddr, - request: &ConnectRequest, - opt_udp_stats_event_sender: &Arc>>, - cookie_issue_time: f64, -) -> Response { - tracing::Span::current().record("transaction_id", request.transaction_id.0.to_string()); - - tracing::trace!("handle connect"); - - let connection_id = make(gen_remote_fingerprint(&remote_addr), cookie_issue_time).expect("it should be a normal value"); - - let response = ConnectResponse { - transaction_id: request.transaction_id, - connection_id, - }; - - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { - match remote_addr { - SocketAddr::V4(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Connect) - .await; - } - SocketAddr::V6(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Connect) - .await; - } - } - } - - Response::from(response) -} - -/// It handles the `Announce` request. Refer to [`Announce`](crate::servers::udp#announce) -/// request for more information. -/// -/// # Errors -/// -/// If a error happens in the `handle_announce` function, it will just return the `ServerError`. -#[allow(clippy::too_many_arguments)] -#[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_handler, whitelist_authorization, opt_udp_stats_event_sender), ret(level = Level::TRACE))] -pub async fn handle_announce( - remote_addr: SocketAddr, - request: &AnnounceRequest, - core_config: &Arc, - announce_handler: &Arc, - whitelist_authorization: &Arc, - opt_udp_stats_event_sender: &Arc>>, - cookie_valid_range: Range, -) -> Result { - tracing::Span::current() - .record("transaction_id", request.transaction_id.0.to_string()) - .record("connection_id", request.connection_id.0.to_string()) - .record("info_hash", InfoHash::from_bytes(&request.info_hash.0).to_hex_string()); - - tracing::trace!("handle announce"); - - check( - &request.connection_id, - gen_remote_fingerprint(&remote_addr), - cookie_valid_range, - ) - .map_err(|e| (e, request.transaction_id))?; - - let info_hash = request.info_hash.into(); - let remote_client_ip = remote_addr.ip(); - - // Authorization - whitelist_authorization - .authorize(&info_hash) - .await - .map_err(|e| Error::TrackerError { - source: (Arc::new(e) as Arc).into(), - }) - .map_err(|e| (e, request.transaction_id))?; - - let mut peer = peer_builder::from_request(request, &remote_client_ip); - let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); - - let response = announce_handler.announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted); - - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { - match remote_client_ip { - IpAddr::V4(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Announce) - .await; - } - IpAddr::V6(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Announce) - .await; - } - } - } - - #[allow(clippy::cast_possible_truncation)] - if remote_addr.is_ipv4() { - let announce_response = AnnounceResponse { - fixed: AnnounceResponseFixedData { - transaction_id: request.transaction_id, - announce_interval: AnnounceInterval(I32::new(i64::from(core_config.announce_policy.interval) as i32)), - leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), - seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), - }, - peers: response - .peers - .iter() - .filter_map(|peer| { - if let IpAddr::V4(ip) = peer.peer_addr.ip() { - Some(ResponsePeer:: { - ip_address: ip.into(), - port: Port(peer.peer_addr.port().into()), - }) - } else { - None - } - }) - .collect(), - }; - - Ok(Response::from(announce_response)) - } else { - let announce_response = AnnounceResponse { - fixed: AnnounceResponseFixedData { - transaction_id: request.transaction_id, - announce_interval: AnnounceInterval(I32::new(i64::from(core_config.announce_policy.interval) as i32)), - leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), - seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), - }, - peers: response - .peers - .iter() - .filter_map(|peer| { - if let IpAddr::V6(ip) = peer.peer_addr.ip() { - Some(ResponsePeer:: { - ip_address: ip.into(), - port: Port(peer.peer_addr.port().into()), - }) - } else { - None - } - }) - .collect(), - }; - - Ok(Response::from(announce_response)) - } -} - -/// It handles the `Scrape` request. Refer to [`Scrape`](crate::servers::udp#scrape) -/// request for more information. -/// -/// # Errors -/// -/// This function does not ever return an error. -#[instrument(fields(transaction_id, connection_id), skip(scrape_handler, opt_udp_stats_event_sender), ret(level = Level::TRACE))] -pub async fn handle_scrape( - remote_addr: SocketAddr, - request: &ScrapeRequest, - scrape_handler: &Arc, - opt_udp_stats_event_sender: &Arc>>, - cookie_valid_range: Range, -) -> Result { - tracing::Span::current() - .record("transaction_id", request.transaction_id.0.to_string()) - .record("connection_id", request.connection_id.0.to_string()); - - tracing::trace!("handle scrape"); - - check( - &request.connection_id, - gen_remote_fingerprint(&remote_addr), - cookie_valid_range, - ) - .map_err(|e| (e, request.transaction_id))?; - - // Convert from aquatic infohashes - let mut info_hashes: Vec = vec![]; - for info_hash in &request.info_hashes { - info_hashes.push((*info_hash).into()); - } - - let scrape_data = scrape_handler.scrape(&info_hashes).await; - - let mut torrent_stats: Vec = Vec::new(); - - for file in &scrape_data.files { - let swarm_metadata = file.1; - - #[allow(clippy::cast_possible_truncation)] - let scrape_entry = { - TorrentScrapeStatistics { - seeders: NumberOfPeers(I32::new(i64::from(swarm_metadata.complete) as i32)), - completed: NumberOfDownloads(I32::new(i64::from(swarm_metadata.downloaded) as i32)), - leechers: NumberOfPeers(I32::new(i64::from(swarm_metadata.incomplete) as i32)), - } - }; - - torrent_stats.push(scrape_entry); - } - - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { - match remote_addr { - SocketAddr::V4(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Scrape) - .await; - } - SocketAddr::V6(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Scrape) - .await; - } - } - } - - let response = ScrapeResponse { - transaction_id: request.transaction_id, - torrent_stats, - }; - - Ok(Response::from(response)) -} - -#[allow(clippy::too_many_arguments)] -#[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] -async fn handle_error( - remote_addr: SocketAddr, - local_addr: SocketAddr, - request_id: Uuid, - opt_udp_stats_event_sender: &Arc>>, - cookie_valid_range: Range, - e: &Error, - transaction_id: Option, -) -> Response { - tracing::trace!("handle error"); - - match transaction_id { - Some(transaction_id) => { - let transaction_id = transaction_id.0.to_string(); - tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %e, %remote_addr, %local_addr, %request_id, %transaction_id, "response error"); - } - None => { - tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %e, %remote_addr, %local_addr, %request_id, "response error"); - } - } - - let e = if let Error::RequestParseError { request_parse_error } = e { - match request_parse_error { - RequestParseError::Sendable { - connection_id, - transaction_id, - err, - } => { - if let Err(e) = check(connection_id, gen_remote_fingerprint(&remote_addr), cookie_valid_range) { - (e.to_string(), Some(*transaction_id)) - } else { - ((*err).to_string(), Some(*transaction_id)) - } - } - RequestParseError::Unsendable { err } => (err.to_string(), transaction_id), - } - } else { - (e.to_string(), transaction_id) - }; - - if e.1.is_some() { - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { - match remote_addr { - SocketAddr::V4(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Error) - .await; - } - SocketAddr::V6(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Error) - .await; - } - } - } - } - - Response::from(ErrorResponse { - transaction_id: e.1.unwrap_or(TransactionId(I32::new(0))), - message: e.0.into(), - }) -} - -fn gen_remote_fingerprint(remote_addr: &SocketAddr) -> u64 { - let mut state = DefaultHasher::new(); - remote_addr.hash(&mut state); - state.finish() -} - -#[cfg(test)] -mod tests { - - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use std::ops::Range; - use std::sync::Arc; - - use aquatic_udp_protocol::{NumberOfBytes, PeerId}; - use bittorrent_tracker_core::announce_handler::AnnounceHandler; - use bittorrent_tracker_core::databases::setup::initialize_database; - use bittorrent_tracker_core::scrape_handler::ScrapeHandler; - use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - use bittorrent_tracker_core::whitelist; - use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; - use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; - use futures::future::BoxFuture; - use mockall::mock; - use tokio::sync::mpsc::error::SendError; - use torrust_tracker_clock::clock::Time; - use torrust_tracker_configuration::{Configuration, Core}; - use torrust_tracker_primitives::peer; - use torrust_tracker_test_helpers::configuration; - - use super::gen_remote_fingerprint; - use crate::packages::udp_tracker_core; - use crate::{packages, CurrentClock}; - - struct CoreTrackerServices { - pub core_config: Arc, - pub announce_handler: Arc, - pub scrape_handler: Arc, - pub in_memory_torrent_repository: Arc, - pub in_memory_whitelist: Arc, - pub whitelist_authorization: Arc, - } - - struct CoreUdpTrackerServices { - pub udp_stats_event_sender: Arc>>, - } - - fn default_testing_tracker_configuration() -> Configuration { - configuration::ephemeral() - } - - fn initialize_core_tracker_services_for_default_tracker_configuration() -> (CoreTrackerServices, CoreUdpTrackerServices) { - initialize_core_tracker_services(&default_testing_tracker_configuration()) - } - - fn initialize_core_tracker_services_for_public_tracker() -> (CoreTrackerServices, CoreUdpTrackerServices) { - initialize_core_tracker_services(&configuration::ephemeral_public()) - } - - fn initialize_core_tracker_services_for_listed_tracker() -> (CoreTrackerServices, CoreUdpTrackerServices) { - initialize_core_tracker_services(&configuration::ephemeral_listed()) - } - - fn initialize_core_tracker_services(config: &Configuration) -> (CoreTrackerServices, CoreUdpTrackerServices) { - let core_config = Arc::new(config.core.clone()); - let database = initialize_database(&config.core); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - - ( - CoreTrackerServices { - core_config, - announce_handler, - scrape_handler, - in_memory_torrent_repository, - in_memory_whitelist, - whitelist_authorization, - }, - CoreUdpTrackerServices { udp_stats_event_sender }, - ) - } - - fn sample_ipv4_remote_addr() -> SocketAddr { - sample_ipv4_socket_address() - } - - fn sample_ipv4_remote_addr_fingerprint() -> u64 { - gen_remote_fingerprint(&sample_ipv4_socket_address()) - } - - fn sample_ipv6_remote_addr() -> SocketAddr { - sample_ipv6_socket_address() - } - - fn sample_ipv6_remote_addr_fingerprint() -> u64 { - gen_remote_fingerprint(&sample_ipv6_socket_address()) - } - - fn sample_ipv4_socket_address() -> SocketAddr { - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) - } - - fn sample_ipv6_socket_address() -> SocketAddr { - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) - } - - fn sample_issue_time() -> f64 { - 1_000_000_000_f64 - } - - fn sample_cookie_valid_range() -> Range { - sample_issue_time() - 10.0..sample_issue_time() + 10.0 - } - - #[derive(Debug, Default)] - pub struct TorrentPeerBuilder { - peer: peer::Peer, - } - - impl TorrentPeerBuilder { - #[must_use] - pub fn new() -> Self { - Self { - peer: peer::Peer { - updated: CurrentClock::now(), - ..Default::default() - }, - } - } - - #[must_use] - pub fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { - self.peer.peer_addr = peer_addr; - self - } - - #[must_use] - pub fn with_peer_id(mut self, peer_id: PeerId) -> Self { - self.peer.peer_id = peer_id; - self - } - - #[must_use] - pub fn with_number_of_bytes_left(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes::new(left); - self - } - - #[must_use] - pub fn into(self) -> peer::Peer { - self.peer - } - } - - struct TrackerConfigurationBuilder { - configuration: Configuration, - } - - impl TrackerConfigurationBuilder { - pub fn default() -> TrackerConfigurationBuilder { - let default_configuration = default_testing_tracker_configuration(); - TrackerConfigurationBuilder { - configuration: default_configuration, - } - } - - pub fn with_external_ip(mut self, external_ip: &str) -> Self { - self.configuration.core.net.external_ip = Some(external_ip.to_owned().parse().expect("valid IP address")); - self - } - - pub fn into(self) -> Configuration { - self.configuration - } - } - - mock! { - UdpStatsEventSender {} - impl udp_tracker_core::statistics::event::sender::Sender for UdpStatsEventSender { - fn send_event(&self, event: udp_tracker_core::statistics::event::Event) -> BoxFuture<'static,Option > > > ; - } - } - - mod connect_request { - - use std::future; - use std::sync::Arc; - - use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; - use mockall::predicate::eq; - - use super::{sample_ipv4_socket_address, sample_ipv6_remote_addr}; - use crate::packages::{self, udp_tracker_core}; - use crate::servers::udp::connection_cookie::make; - use crate::servers::udp::handlers::handle_connect; - use crate::servers::udp::handlers::tests::{ - sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv6_remote_addr_fingerprint, sample_issue_time, - MockUdpStatsEventSender, - }; - - fn sample_connect_request() -> ConnectRequest { - ConnectRequest { - transaction_id: TransactionId(0i32.into()), - } - } - - #[tokio::test] - async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - - let request = ConnectRequest { - transaction_id: TransactionId(0i32.into()), - }; - - let response = handle_connect( - sample_ipv4_remote_addr(), - &request, - &udp_stats_event_sender, - sample_issue_time(), - ) - .await; - - assert_eq!( - response, - Response::Connect(ConnectResponse { - connection_id: make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), - transaction_id: request.transaction_id - }) - ); - } - - #[tokio::test] - async fn a_connect_response_should_contain_a_new_connection_id() { - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - - let request = ConnectRequest { - transaction_id: TransactionId(0i32.into()), - }; - - let response = handle_connect( - sample_ipv4_remote_addr(), - &request, - &udp_stats_event_sender, - sample_issue_time(), - ) - .await; - - assert_eq!( - response, - Response::Connect(ConnectResponse { - connection_id: make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), - transaction_id: request.transaction_id - }) - ); - } - - #[tokio::test] - async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - - let request = ConnectRequest { - transaction_id: TransactionId(0i32.into()), - }; - - let response = handle_connect( - sample_ipv6_remote_addr(), - &request, - &udp_stats_event_sender, - sample_issue_time(), - ) - .await; - - assert_eq!( - response, - Response::Connect(ConnectResponse { - connection_id: make(sample_ipv6_remote_addr_fingerprint(), sample_issue_time()).unwrap(), - transaction_id: request.transaction_id - }) - ); - } - - #[tokio::test] - async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock - .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp4Connect)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); - - let client_socket_address = sample_ipv4_socket_address(); - - handle_connect( - client_socket_address, - &sample_connect_request(), - &udp_stats_event_sender, - sample_issue_time(), - ) - .await; - } - - #[tokio::test] - async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock - .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp6Connect)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); - - handle_connect( - sample_ipv6_remote_addr(), - &sample_connect_request(), - &udp_stats_event_sender, - sample_issue_time(), - ) - .await; - } - } - - mod announce_request { - - use std::net::Ipv4Addr; - use std::num::NonZeroU16; - - use aquatic_udp_protocol::{ - AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectionId, NumberOfBytes, NumberOfPeers, - PeerId as AquaticPeerId, PeerKey, Port, TransactionId, - }; - - use super::{sample_ipv4_remote_addr_fingerprint, sample_issue_time}; - use crate::servers::udp::connection_cookie::make; - - struct AnnounceRequestBuilder { - request: AnnounceRequest, - } - - impl AnnounceRequestBuilder { - pub fn default() -> AnnounceRequestBuilder { - let client_ip = Ipv4Addr::new(126, 0, 0, 1); - let client_port = 8080; - let info_hash_aquatic = aquatic_udp_protocol::InfoHash([0u8; 20]); - - let default_request = AnnounceRequest { - connection_id: make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), - action_placeholder: AnnounceActionPlaceholder::default(), - transaction_id: TransactionId(0i32.into()), - info_hash: info_hash_aquatic, - peer_id: AquaticPeerId([255u8; 20]), - bytes_downloaded: NumberOfBytes(0i64.into()), - bytes_uploaded: NumberOfBytes(0i64.into()), - bytes_left: NumberOfBytes(0i64.into()), - event: AnnounceEvent::Started.into(), - ip_address: client_ip.into(), - key: PeerKey::new(0i32), - peers_wanted: NumberOfPeers::new(1i32), - port: Port::new(NonZeroU16::new(client_port).expect("a non-zero client port")), - }; - AnnounceRequestBuilder { - request: default_request, - } - } - - pub fn with_connection_id(mut self, connection_id: ConnectionId) -> Self { - self.request.connection_id = connection_id; - self - } - - pub fn with_info_hash(mut self, info_hash: aquatic_udp_protocol::InfoHash) -> Self { - self.request.info_hash = info_hash; - self - } - - pub fn with_peer_id(mut self, peer_id: AquaticPeerId) -> Self { - self.request.peer_id = peer_id; - self - } - - pub fn with_ip_address(mut self, ip_address: Ipv4Addr) -> Self { - self.request.ip_address = ip_address.into(); - self - } - - pub fn with_port(mut self, port: u16) -> Self { - self.request.port = Port(port.into()); - self - } - - pub fn into(self) -> AnnounceRequest { - self.request - } - } - - mod using_ipv4 { - - use std::future; - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; - - use aquatic_udp_protocol::{ - AnnounceInterval, AnnounceResponse, InfoHash as AquaticInfoHash, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfPeers, - PeerId as AquaticPeerId, Response, ResponsePeer, - }; - use bittorrent_tracker_core::announce_handler::AnnounceHandler; - use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::whitelist; - use mockall::predicate::eq; - use torrust_tracker_configuration::Core; - - use crate::packages::{self, udp_tracker_core}; - use crate::servers::udp::connection_cookie::make; - use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::tests::{ - gen_remote_fingerprint, initialize_core_tracker_services_for_default_tracker_configuration, - initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, - sample_issue_time, MockUdpStatsEventSender, TorrentPeerBuilder, - }; - use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; - - #[tokio::test] - async fn an_announced_peer_should_be_added_to_the_tracker() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - - let client_ip = Ipv4Addr::new(126, 0, 0, 1); - let client_port = 8080; - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - - let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(client_ip) - .with_port(client_port) - .into(); - - handle_announce( - remote_addr, - &request, - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - - let peers = core_tracker_services - .in_memory_torrent_repository - .get_torrent_peers(&info_hash.0.into()); - - let expected_peer = TorrentPeerBuilder::new() - .with_peer_id(peer_id) - .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip), client_port)) - .into(); - - assert_eq!(peers[0], Arc::new(expected_peer)); - } - - #[tokio::test] - async fn the_announced_peer_should_not_be_included_in_the_response() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - - let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) - .into(); - - let response = handle_announce( - remote_addr, - &request, - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - - let empty_peer_vector: Vec> = vec![]; - assert_eq!( - response, - Response::from(AnnounceResponse { - fixed: AnnounceResponseFixedData { - transaction_id: request.transaction_id, - announce_interval: AnnounceInterval(120i32.into()), - leechers: NumberOfPeers(0i32.into()), - seeders: NumberOfPeers(1i32.into()), - }, - peers: empty_peer_vector - }) - ); - } - - #[tokio::test] - async fn the_tracker_should_always_use_the_remote_client_ip_but_not_the_port_in_the_udp_request_header_instead_of_the_peer_address_in_the_announce_request( - ) { - // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): - // "Do note that most trackers will only honor the IP address field under limited circumstances." - - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - let client_port = 8080; - - let remote_client_ip = Ipv4Addr::new(126, 0, 0, 1); - let remote_client_port = 8081; - let peer_address = Ipv4Addr::new(126, 0, 0, 2); - - let remote_addr = SocketAddr::new(IpAddr::V4(remote_client_ip), remote_client_port); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(peer_address) - .with_port(client_port) - .into(); - - handle_announce( - remote_addr, - &request, - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - - let peers = core_tracker_services - .in_memory_torrent_repository - .get_torrent_peers(&info_hash.0.into()); - - assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); - } - - fn add_a_torrent_peer_using_ipv6(in_memory_torrent_repository: &Arc) { - let info_hash = AquaticInfoHash([0u8; 20]); - - let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); - let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); - let client_port = 8080; - let peer_id = AquaticPeerId([255u8; 20]); - - let peer_using_ipv6 = TorrentPeerBuilder::new() - .with_peer_id(peer_id) - .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) - .into(); - - let () = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv6); - } - - async fn announce_a_new_peer_using_ipv4( - core_config: Arc, - announce_handler: Arc, - whitelist_authorization: Arc, - ) -> Response { - let (udp_stats_event_sender, _udp_stats_repository) = - packages::udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - - let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); - let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) - .into(); - - handle_announce( - remote_addr, - &request, - &core_config, - &announce_handler, - &whitelist_authorization, - &udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap() - } - - #[tokio::test] - async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { - let (core_tracker_services, _core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - - add_a_torrent_peer_using_ipv6(&core_tracker_services.in_memory_torrent_repository); - - let response = announce_a_new_peer_using_ipv4( - core_tracker_services.core_config.clone(), - core_tracker_services.announce_handler.clone(), - core_tracker_services.whitelist_authorization, - ) - .await; - - // The response should not contain the peer using IPV6 - let peers: Option>> = match response { - Response::AnnounceIpv6(announce_response) => Some(announce_response.peers), - _ => None, - }; - let no_ipv6_peers = peers.is_none(); - assert!(no_ipv6_peers); - } - - #[tokio::test] - async fn should_send_the_upd4_announce_event() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock - .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp4Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); - - let (core_tracker_services, _core_udp_tracker_services) = - initialize_core_tracker_services_for_default_tracker_configuration(); - - handle_announce( - sample_ipv4_socket_address(), - &AnnounceRequestBuilder::default().into(), - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - } - - mod from_a_loopback_ip { - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; - - use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; - - use crate::servers::udp::connection_cookie::make; - use crate::servers::udp::handlers::handle_announce; - use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::tests::{ - gen_remote_fingerprint, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, - sample_issue_time, TorrentPeerBuilder, - }; - - #[tokio::test] - async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { - let (core_tracker_services, core_udp_tracker_services) = - initialize_core_tracker_services_for_public_tracker(); - - let client_ip = Ipv4Addr::new(127, 0, 0, 1); - let client_port = 8080; - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - - let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(client_ip) - .with_port(client_port) - .into(); - - handle_announce( - remote_addr, - &request, - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - - let peers = core_tracker_services - .in_memory_torrent_repository - .get_torrent_peers(&info_hash.0.into()); - - let external_ip_in_tracker_configuration = core_tracker_services.core_config.net.external_ip.unwrap(); - - let expected_peer = TorrentPeerBuilder::new() - .with_peer_id(peer_id) - .with_peer_address(SocketAddr::new(external_ip_in_tracker_configuration, client_port)) - .into(); - - assert_eq!(peers[0], Arc::new(expected_peer)); - } - } - } - - mod using_ipv6 { - - use std::future; - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; - - use aquatic_udp_protocol::{ - AnnounceInterval, AnnounceResponse, InfoHash as AquaticInfoHash, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfPeers, - PeerId as AquaticPeerId, Response, ResponsePeer, - }; - use bittorrent_tracker_core::announce_handler::AnnounceHandler; - use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::whitelist; - use mockall::predicate::eq; - use torrust_tracker_configuration::Core; - - use crate::packages::{self, udp_tracker_core}; - use crate::servers::udp::connection_cookie::make; - use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::tests::{ - gen_remote_fingerprint, initialize_core_tracker_services_for_default_tracker_configuration, - initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, - sample_issue_time, MockUdpStatsEventSender, TorrentPeerBuilder, - }; - use crate::servers::udp::handlers::{handle_announce, AnnounceResponseFixedData}; - - #[tokio::test] - async fn an_announced_peer_should_be_added_to_the_tracker() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - - let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); - let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); - let client_port = 8080; - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - - let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(client_ip_v4) - .with_port(client_port) - .into(); - - handle_announce( - remote_addr, - &request, - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - - let peers = core_tracker_services - .in_memory_torrent_repository - .get_torrent_peers(&info_hash.0.into()); - - let expected_peer = TorrentPeerBuilder::new() - .with_peer_id(peer_id) - .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) - .into(); - - assert_eq!(peers[0], Arc::new(expected_peer)); - } - - #[tokio::test] - async fn the_announced_peer_should_not_be_included_in_the_response() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - - let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); - let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); - - let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), 8080); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) - .into(); - - let response = handle_announce( - remote_addr, - &request, - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - - let empty_peer_vector: Vec> = vec![]; - assert_eq!( - response, - Response::from(AnnounceResponse { - fixed: AnnounceResponseFixedData { - transaction_id: request.transaction_id, - announce_interval: AnnounceInterval(120i32.into()), - leechers: NumberOfPeers(0i32.into()), - seeders: NumberOfPeers(1i32.into()), - }, - peers: empty_peer_vector - }) - ); - } - - #[tokio::test] - async fn the_tracker_should_always_use_the_remote_client_ip_but_not_the_port_in_the_udp_request_header_instead_of_the_peer_address_in_the_announce_request( - ) { - // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): - // "Do note that most trackers will only honor the IP address field under limited circumstances." - - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - let client_port = 8080; - - let remote_client_ip = "::100".parse().unwrap(); // IPV4 ::0.0.1.0 -> IPV6 = ::100 = ::ffff:0:100 = 0:0:0:0:0:ffff:0:0100 - let remote_client_port = 8081; - let peer_address = "126.0.0.1".parse().unwrap(); - - let remote_addr = SocketAddr::new(IpAddr::V6(remote_client_ip), remote_client_port); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(peer_address) - .with_port(client_port) - .into(); - - handle_announce( - remote_addr, - &request, - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - - let peers = core_tracker_services - .in_memory_torrent_repository - .get_torrent_peers(&info_hash.0.into()); - - // When using IPv6 the tracker converts the remote client ip into a IPv4 address - assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); - } - - fn add_a_torrent_peer_using_ipv4(in_memory_torrent_repository: &Arc) { - let info_hash = AquaticInfoHash([0u8; 20]); - - let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); - let client_port = 8080; - let peer_id = AquaticPeerId([255u8; 20]); - - let peer_using_ipv4 = TorrentPeerBuilder::new() - .with_peer_id(peer_id) - .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) - .into(); - - let () = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv4); - } - - async fn announce_a_new_peer_using_ipv6( - core_config: Arc, - announce_handler: Arc, - whitelist_authorization: Arc, - ) -> Response { - let (udp_stats_event_sender, _udp_stats_repository) = - packages::udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - - let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); - let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); - let client_port = 8080; - let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); - let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) - .into(); - - handle_announce( - remote_addr, - &request, - &core_config, - &announce_handler, - &whitelist_authorization, - &udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap() - } - - #[tokio::test] - async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { - let (core_tracker_services, _core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - - add_a_torrent_peer_using_ipv4(&core_tracker_services.in_memory_torrent_repository); - - let response = announce_a_new_peer_using_ipv6( - core_tracker_services.core_config.clone(), - core_tracker_services.announce_handler.clone(), - core_tracker_services.whitelist_authorization, - ) - .await; - - // The response should not contain the peer using IPV4 - let peers: Option>> = match response { - Response::AnnounceIpv4(announce_response) => Some(announce_response.peers), - _ => None, - }; - let no_ipv4_peers = peers.is_none(); - assert!(no_ipv4_peers); - } - - #[tokio::test] - async fn should_send_the_upd6_announce_event() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock - .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp6Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); - - let (core_tracker_services, _core_udp_tracker_services) = - initialize_core_tracker_services_for_default_tracker_configuration(); - - let remote_addr = sample_ipv6_remote_addr(); - - let announce_request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) - .into(); - - handle_announce( - remote_addr, - &announce_request, - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - } - - mod from_a_loopback_ip { - use std::future; - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use std::sync::Arc; - - use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; - use bittorrent_tracker_core::announce_handler::AnnounceHandler; - use bittorrent_tracker_core::databases::setup::initialize_database; - use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; - use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; - use mockall::predicate::eq; - - use crate::packages::udp_tracker_core; - use crate::servers::udp::connection_cookie::make; - use crate::servers::udp::handlers::handle_announce; - use crate::servers::udp::handlers::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::tests::{ - gen_remote_fingerprint, sample_cookie_valid_range, sample_issue_time, MockUdpStatsEventSender, - TrackerConfigurationBuilder, - }; - - #[tokio::test] - async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { - let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - - let database = initialize_database(&config.core); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = - Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock - .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp6Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); - - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); - let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); - - let client_ip_v4 = loopback_ipv4; - let client_ip_v6 = loopback_ipv6; - let client_port = 8080; - - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - - let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); - - let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(client_ip_v4) - .with_port(client_port) - .into(); - - let core_config = Arc::new(config.core.clone()); - - handle_announce( - remote_addr, - &request, - &core_config, - &announce_handler, - &whitelist_authorization, - &udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); - - let external_ip_in_tracker_configuration = core_config.net.external_ip.unwrap(); - - assert!(external_ip_in_tracker_configuration.is_ipv6()); - - // There's a special type of IPv6 addresses that provide compatibility with IPv4. - // The last 32 bits of these addresses represent an IPv4, and are represented like this: - // 1111:2222:3333:4444:5555:6666:1.2.3.4 - // - // ::127.0.0.1 is the IPV6 representation for the IPV4 address 127.0.0.1. - assert_eq!(Ok(peers[0].peer_addr.ip()), "::126.0.0.1".parse()); - } - } - } - } - - mod scrape_request { - use std::net::SocketAddr; - use std::sync::Arc; - - use aquatic_udp_protocol::{ - InfoHash, NumberOfDownloads, NumberOfPeers, PeerId, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, - TransactionId, - }; - use bittorrent_tracker_core::scrape_handler::ScrapeHandler; - use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - - use super::{gen_remote_fingerprint, TorrentPeerBuilder}; - use crate::packages; - use crate::servers::udp::connection_cookie::make; - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{ - initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, - sample_issue_time, - }; - - fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { - TorrentScrapeStatistics { - seeders: NumberOfPeers(0.into()), - completed: NumberOfDownloads(0.into()), - leechers: NumberOfPeers(0.into()), - } - } - - #[tokio::test] - async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - - let remote_addr = sample_ipv4_remote_addr(); - - let info_hash = InfoHash([0u8; 20]); - let info_hashes = vec![info_hash]; - - let request = ScrapeRequest { - connection_id: make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap(), - transaction_id: TransactionId(0i32.into()), - info_hashes, - }; - - let response = handle_scrape( - remote_addr, - &request, - &core_tracker_services.scrape_handler, - &core_udp_tracker_services.udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - - let expected_torrent_stats = vec![zeroed_torrent_statistics()]; - - assert_eq!( - response, - Response::from(ScrapeResponse { - transaction_id: request.transaction_id, - torrent_stats: expected_torrent_stats - }) - ); - } - - async fn add_a_seeder( - in_memory_torrent_repository: Arc, - remote_addr: &SocketAddr, - info_hash: &InfoHash, - ) { - let peer_id = PeerId([255u8; 20]); - - let peer = TorrentPeerBuilder::new() - .with_peer_id(peer_id) - .with_peer_address(*remote_addr) - .with_number_of_bytes_left(0) - .into(); - - let () = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer); - } - - fn build_scrape_request(remote_addr: &SocketAddr, info_hash: &InfoHash) -> ScrapeRequest { - let info_hashes = vec![*info_hash]; - - ScrapeRequest { - connection_id: make(gen_remote_fingerprint(remote_addr), sample_issue_time()).unwrap(), - transaction_id: TransactionId::new(0i32), - info_hashes, - } - } - - async fn add_a_sample_seeder_and_scrape( - in_memory_torrent_repository: Arc, - scrape_handler: Arc, - ) -> Response { - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - - let remote_addr = sample_ipv4_remote_addr(); - let info_hash = InfoHash([0u8; 20]); - - add_a_seeder(in_memory_torrent_repository.clone(), &remote_addr, &info_hash).await; - - let request = build_scrape_request(&remote_addr, &info_hash); - - handle_scrape( - remote_addr, - &request, - &scrape_handler, - &udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap() - } - - fn match_scrape_response(response: Response) -> Option { - match response { - Response::Scrape(scrape_response) => Some(scrape_response), - _ => None, - } - } - - mod with_a_public_tracker { - use aquatic_udp_protocol::{NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; - - use crate::servers::udp::handlers::tests::initialize_core_tracker_services_for_public_tracker; - use crate::servers::udp::handlers::tests::scrape_request::{add_a_sample_seeder_and_scrape, match_scrape_response}; - - #[tokio::test] - async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { - let (core_tracker_services, _core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - - let torrent_stats = match_scrape_response( - add_a_sample_seeder_and_scrape( - core_tracker_services.in_memory_torrent_repository.clone(), - core_tracker_services.scrape_handler.clone(), - ) - .await, - ); - - let expected_torrent_stats = vec![TorrentScrapeStatistics { - seeders: NumberOfPeers(1.into()), - completed: NumberOfDownloads(0.into()), - leechers: NumberOfPeers(0.into()), - }]; - - assert_eq!(torrent_stats.unwrap().torrent_stats, expected_torrent_stats); - } - } - - mod with_a_whitelisted_tracker { - use aquatic_udp_protocol::{InfoHash, NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; - - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::scrape_request::{ - add_a_seeder, build_scrape_request, match_scrape_response, zeroed_torrent_statistics, - }; - use crate::servers::udp::handlers::tests::{ - initialize_core_tracker_services_for_listed_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, - }; - - #[tokio::test] - async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_listed_tracker(); - - let remote_addr = sample_ipv4_remote_addr(); - let info_hash = InfoHash([0u8; 20]); - - add_a_seeder( - core_tracker_services.in_memory_torrent_repository.clone(), - &remote_addr, - &info_hash, - ) - .await; - - core_tracker_services.in_memory_whitelist.add(&info_hash.0.into()).await; - - let request = build_scrape_request(&remote_addr, &info_hash); - - let torrent_stats = match_scrape_response( - handle_scrape( - remote_addr, - &request, - &core_tracker_services.scrape_handler, - &core_udp_tracker_services.udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(), - ) - .unwrap(); - - let expected_torrent_stats = vec![TorrentScrapeStatistics { - seeders: NumberOfPeers(1.into()), - completed: NumberOfDownloads(0.into()), - leechers: NumberOfPeers(0.into()), - }]; - - assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); - } - - #[tokio::test] - async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_listed_tracker(); - - let remote_addr = sample_ipv4_remote_addr(); - let info_hash = InfoHash([0u8; 20]); - - add_a_seeder( - core_tracker_services.in_memory_torrent_repository.clone(), - &remote_addr, - &info_hash, - ) - .await; - - let request = build_scrape_request(&remote_addr, &info_hash); - - let torrent_stats = match_scrape_response( - handle_scrape( - remote_addr, - &request, - &core_tracker_services.scrape_handler, - &core_udp_tracker_services.udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(), - ) - .unwrap(); - - let expected_torrent_stats = vec![zeroed_torrent_statistics()]; - - assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); - } - } - - fn sample_scrape_request(remote_addr: &SocketAddr) -> ScrapeRequest { - let info_hash = InfoHash([0u8; 20]); - let info_hashes = vec![info_hash]; - - ScrapeRequest { - connection_id: make(gen_remote_fingerprint(remote_addr), sample_issue_time()).unwrap(), - transaction_id: TransactionId(0i32.into()), - info_hashes, - } - } - - mod using_ipv4 { - use std::future; - use std::sync::Arc; - - use mockall::predicate::eq; - - use super::sample_scrape_request; - use crate::packages::udp_tracker_core; - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{ - initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, - sample_ipv4_remote_addr, MockUdpStatsEventSender, - }; - - #[tokio::test] - async fn should_send_the_upd4_scrape_event() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock - .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp4Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); - - let remote_addr = sample_ipv4_remote_addr(); - - let (core_tracker_services, _core_udp_tracker_services) = - initialize_core_tracker_services_for_default_tracker_configuration(); - - handle_scrape( - remote_addr, - &sample_scrape_request(&remote_addr), - &core_tracker_services.scrape_handler, - &udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - } - } - - mod using_ipv6 { - use std::future; - use std::sync::Arc; - - use mockall::predicate::eq; - - use super::sample_scrape_request; - use crate::packages::udp_tracker_core; - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{ - initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, - sample_ipv6_remote_addr, MockUdpStatsEventSender, - }; - - #[tokio::test] - async fn should_send_the_upd6_scrape_event() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock - .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp6Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); - - let remote_addr = sample_ipv6_remote_addr(); - - let (core_tracker_services, _core_udp_tracker_services) = - initialize_core_tracker_services_for_default_tracker_configuration(); - - handle_scrape( - remote_addr, - &sample_scrape_request(&remote_addr), - &core_tracker_services.scrape_handler, - &udp_stats_event_sender, - sample_cookie_valid_range(), - ) - .await - .unwrap(); - } - } - } -} diff --git a/src/servers/udp/handlers/announce.rs b/src/servers/udp/handlers/announce.rs new file mode 100644 index 000000000..79fb91f49 --- /dev/null +++ b/src/servers/udp/handlers/announce.rs @@ -0,0 +1,875 @@ +//! UDP tracker announce handler. +use std::net::{IpAddr, SocketAddr}; +use std::ops::Range; +use std::sync::Arc; + +use aquatic_udp_protocol::{ + AnnounceInterval, AnnounceRequest, AnnounceResponse, AnnounceResponseFixedData, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfPeers, + Port, Response, ResponsePeer, TransactionId, +}; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; +use bittorrent_tracker_core::whitelist; +use torrust_tracker_configuration::Core; +use tracing::{instrument, Level}; +use zerocopy::network_endian::I32; + +use crate::packages::udp_tracker_core; +use crate::servers::udp::connection_cookie::check; +use crate::servers::udp::error::Error; +use crate::servers::udp::handlers::gen_remote_fingerprint; +use crate::servers::udp::peer_builder; + +/// It handles the `Announce` request. Refer to [`Announce`](crate::servers::udp#announce) +/// request for more information. +/// +/// # Errors +/// +/// If a error happens in the `handle_announce` function, it will just return the `ServerError`. +#[allow(clippy::too_many_arguments)] +#[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_handler, whitelist_authorization, opt_udp_stats_event_sender), ret(level = Level::TRACE))] +pub async fn handle_announce( + remote_addr: SocketAddr, + request: &AnnounceRequest, + core_config: &Arc, + announce_handler: &Arc, + whitelist_authorization: &Arc, + opt_udp_stats_event_sender: &Arc>>, + cookie_valid_range: Range, +) -> Result { + tracing::Span::current() + .record("transaction_id", request.transaction_id.0.to_string()) + .record("connection_id", request.connection_id.0.to_string()) + .record("info_hash", InfoHash::from_bytes(&request.info_hash.0).to_hex_string()); + + tracing::trace!("handle announce"); + + check( + &request.connection_id, + gen_remote_fingerprint(&remote_addr), + cookie_valid_range, + ) + .map_err(|e| (e, request.transaction_id))?; + + let info_hash = request.info_hash.into(); + let remote_client_ip = remote_addr.ip(); + + // Authorization + whitelist_authorization + .authorize(&info_hash) + .await + .map_err(|e| Error::TrackerError { + source: (Arc::new(e) as Arc).into(), + }) + .map_err(|e| (e, request.transaction_id))?; + + let mut peer = peer_builder::from_request(request, &remote_client_ip); + let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); + + let response = announce_handler.announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted); + + if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + match remote_client_ip { + IpAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Announce) + .await; + } + IpAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Announce) + .await; + } + } + } + + #[allow(clippy::cast_possible_truncation)] + if remote_addr.is_ipv4() { + let announce_response = AnnounceResponse { + fixed: AnnounceResponseFixedData { + transaction_id: request.transaction_id, + announce_interval: AnnounceInterval(I32::new(i64::from(core_config.announce_policy.interval) as i32)), + leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), + seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), + }, + peers: response + .peers + .iter() + .filter_map(|peer| { + if let IpAddr::V4(ip) = peer.peer_addr.ip() { + Some(ResponsePeer:: { + ip_address: ip.into(), + port: Port(peer.peer_addr.port().into()), + }) + } else { + None + } + }) + .collect(), + }; + + Ok(Response::from(announce_response)) + } else { + let announce_response = AnnounceResponse { + fixed: AnnounceResponseFixedData { + transaction_id: request.transaction_id, + announce_interval: AnnounceInterval(I32::new(i64::from(core_config.announce_policy.interval) as i32)), + leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), + seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), + }, + peers: response + .peers + .iter() + .filter_map(|peer| { + if let IpAddr::V6(ip) = peer.peer_addr.ip() { + Some(ResponsePeer:: { + ip_address: ip.into(), + port: Port(peer.peer_addr.port().into()), + }) + } else { + None + } + }) + .collect(), + }; + + Ok(Response::from(announce_response)) + } +} + +#[cfg(test)] +mod tests { + + mod announce_request { + + use std::net::Ipv4Addr; + use std::num::NonZeroU16; + + use aquatic_udp_protocol::{ + AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectionId, NumberOfBytes, NumberOfPeers, + PeerId as AquaticPeerId, PeerKey, Port, TransactionId, + }; + + use crate::servers::udp::connection_cookie::make; + use crate::servers::udp::handlers::tests::{sample_ipv4_remote_addr_fingerprint, sample_issue_time}; + + struct AnnounceRequestBuilder { + request: AnnounceRequest, + } + + impl AnnounceRequestBuilder { + pub fn default() -> AnnounceRequestBuilder { + let client_ip = Ipv4Addr::new(126, 0, 0, 1); + let client_port = 8080; + let info_hash_aquatic = aquatic_udp_protocol::InfoHash([0u8; 20]); + + let default_request = AnnounceRequest { + connection_id: make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + action_placeholder: AnnounceActionPlaceholder::default(), + transaction_id: TransactionId(0i32.into()), + info_hash: info_hash_aquatic, + peer_id: AquaticPeerId([255u8; 20]), + bytes_downloaded: NumberOfBytes(0i64.into()), + bytes_uploaded: NumberOfBytes(0i64.into()), + bytes_left: NumberOfBytes(0i64.into()), + event: AnnounceEvent::Started.into(), + ip_address: client_ip.into(), + key: PeerKey::new(0i32), + peers_wanted: NumberOfPeers::new(1i32), + port: Port::new(NonZeroU16::new(client_port).expect("a non-zero client port")), + }; + AnnounceRequestBuilder { + request: default_request, + } + } + + pub fn with_connection_id(mut self, connection_id: ConnectionId) -> Self { + self.request.connection_id = connection_id; + self + } + + pub fn with_info_hash(mut self, info_hash: aquatic_udp_protocol::InfoHash) -> Self { + self.request.info_hash = info_hash; + self + } + + pub fn with_peer_id(mut self, peer_id: AquaticPeerId) -> Self { + self.request.peer_id = peer_id; + self + } + + pub fn with_ip_address(mut self, ip_address: Ipv4Addr) -> Self { + self.request.ip_address = ip_address.into(); + self + } + + pub fn with_port(mut self, port: u16) -> Self { + self.request.port = Port(port.into()); + self + } + + pub fn into(self) -> AnnounceRequest { + self.request + } + } + + mod using_ipv4 { + + use std::future; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{ + AnnounceInterval, AnnounceResponse, AnnounceResponseFixedData, InfoHash as AquaticInfoHash, Ipv4AddrBytes, + Ipv6AddrBytes, NumberOfPeers, PeerId as AquaticPeerId, Response, ResponsePeer, + }; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::whitelist; + use mockall::predicate::eq; + use torrust_tracker_configuration::Core; + + use crate::packages::{self, udp_tracker_core}; + use crate::servers::udp::connection_cookie::make; + use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::servers::udp::handlers::tests::{ + initialize_core_tracker_services_for_default_tracker_configuration, + initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, + sample_issue_time, MockUdpStatsEventSender, TorrentPeerBuilder, + }; + use crate::servers::udp::handlers::{gen_remote_fingerprint, handle_announce}; + + #[tokio::test] + async fn an_announced_peer_should_be_added_to_the_tracker() { + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + + let client_ip = Ipv4Addr::new(126, 0, 0, 1); + let client_port = 8080; + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + + let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(client_ip) + .with_port(client_port) + .into(); + + handle_announce( + remote_addr, + &request, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_udp_tracker_services.udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()); + + let expected_peer = TorrentPeerBuilder::new() + .with_peer_id(peer_id) + .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip), client_port)) + .into(); + + assert_eq!(peers[0], Arc::new(expected_peer)); + } + + #[tokio::test] + async fn the_announced_peer_should_not_be_included_in_the_response() { + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + + let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .into(); + + let response = handle_announce( + remote_addr, + &request, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_udp_tracker_services.udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let empty_peer_vector: Vec> = vec![]; + assert_eq!( + response, + Response::from(AnnounceResponse { + fixed: AnnounceResponseFixedData { + transaction_id: request.transaction_id, + announce_interval: AnnounceInterval(120i32.into()), + leechers: NumberOfPeers(0i32.into()), + seeders: NumberOfPeers(1i32.into()), + }, + peers: empty_peer_vector + }) + ); + } + + #[tokio::test] + async fn the_tracker_should_always_use_the_remote_client_ip_but_not_the_port_in_the_udp_request_header_instead_of_the_peer_address_in_the_announce_request( + ) { + // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): + // "Do note that most trackers will only honor the IP address field under limited circumstances." + + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + let client_port = 8080; + + let remote_client_ip = Ipv4Addr::new(126, 0, 0, 1); + let remote_client_port = 8081; + let peer_address = Ipv4Addr::new(126, 0, 0, 2); + + let remote_addr = SocketAddr::new(IpAddr::V4(remote_client_ip), remote_client_port); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(peer_address) + .with_port(client_port) + .into(); + + handle_announce( + remote_addr, + &request, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_udp_tracker_services.udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()); + + assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); + } + + fn add_a_torrent_peer_using_ipv6(in_memory_torrent_repository: &Arc) { + let info_hash = AquaticInfoHash([0u8; 20]); + + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); + let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); + let client_port = 8080; + let peer_id = AquaticPeerId([255u8; 20]); + + let peer_using_ipv6 = TorrentPeerBuilder::new() + .with_peer_id(peer_id) + .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) + .into(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv6); + } + + async fn announce_a_new_peer_using_ipv4( + core_config: Arc, + announce_handler: Arc, + whitelist_authorization: Arc, + ) -> Response { + let (udp_stats_event_sender, _udp_stats_repository) = + packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .into(); + + handle_announce( + remote_addr, + &request, + &core_config, + &announce_handler, + &whitelist_authorization, + &udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap() + } + + #[tokio::test] + async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { + let (core_tracker_services, _core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + + add_a_torrent_peer_using_ipv6(&core_tracker_services.in_memory_torrent_repository); + + let response = announce_a_new_peer_using_ipv4( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.whitelist_authorization, + ) + .await; + + // The response should not contain the peer using IPV6 + let peers: Option>> = match response { + Response::AnnounceIpv6(announce_response) => Some(announce_response.peers), + _ => None, + }; + let no_ipv6_peers = peers.is_none(); + assert!(no_ipv6_peers); + } + + #[tokio::test] + async fn should_send_the_upd4_announce_event() { + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp4Announce)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + + let (core_tracker_services, _core_udp_tracker_services) = + initialize_core_tracker_services_for_default_tracker_configuration(); + + handle_announce( + sample_ipv4_socket_address(), + &AnnounceRequestBuilder::default().into(), + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + } + + mod from_a_loopback_ip { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; + + use crate::servers::udp::connection_cookie::make; + use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::servers::udp::handlers::tests::{ + initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_issue_time, + TorrentPeerBuilder, + }; + use crate::servers::udp::handlers::{gen_remote_fingerprint, handle_announce}; + + #[tokio::test] + async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { + let (core_tracker_services, core_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); + + let client_ip = Ipv4Addr::new(127, 0, 0, 1); + let client_port = 8080; + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + + let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(client_ip) + .with_port(client_port) + .into(); + + handle_announce( + remote_addr, + &request, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_udp_tracker_services.udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()); + + let external_ip_in_tracker_configuration = core_tracker_services.core_config.net.external_ip.unwrap(); + + let expected_peer = TorrentPeerBuilder::new() + .with_peer_id(peer_id) + .with_peer_address(SocketAddr::new(external_ip_in_tracker_configuration, client_port)) + .into(); + + assert_eq!(peers[0], Arc::new(expected_peer)); + } + } + } + + mod using_ipv6 { + + use std::future; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{ + AnnounceInterval, AnnounceResponse, AnnounceResponseFixedData, InfoHash as AquaticInfoHash, Ipv4AddrBytes, + Ipv6AddrBytes, NumberOfPeers, PeerId as AquaticPeerId, Response, ResponsePeer, + }; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::whitelist; + use mockall::predicate::eq; + use torrust_tracker_configuration::Core; + + use crate::packages::{self, udp_tracker_core}; + use crate::servers::udp::connection_cookie::make; + use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::servers::udp::handlers::tests::{ + initialize_core_tracker_services_for_default_tracker_configuration, + initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, + sample_issue_time, MockUdpStatsEventSender, TorrentPeerBuilder, + }; + use crate::servers::udp::handlers::{gen_remote_fingerprint, handle_announce}; + + #[tokio::test] + async fn an_announced_peer_should_be_added_to_the_tracker() { + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); + let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); + let client_port = 8080; + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + + let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(client_ip_v4) + .with_port(client_port) + .into(); + + handle_announce( + remote_addr, + &request, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_udp_tracker_services.udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()); + + let expected_peer = TorrentPeerBuilder::new() + .with_peer_id(peer_id) + .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) + .into(); + + assert_eq!(peers[0], Arc::new(expected_peer)); + } + + #[tokio::test] + async fn the_announced_peer_should_not_be_included_in_the_response() { + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); + let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); + + let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), 8080); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .into(); + + let response = handle_announce( + remote_addr, + &request, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_udp_tracker_services.udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let empty_peer_vector: Vec> = vec![]; + assert_eq!( + response, + Response::from(AnnounceResponse { + fixed: AnnounceResponseFixedData { + transaction_id: request.transaction_id, + announce_interval: AnnounceInterval(120i32.into()), + leechers: NumberOfPeers(0i32.into()), + seeders: NumberOfPeers(1i32.into()), + }, + peers: empty_peer_vector + }) + ); + } + + #[tokio::test] + async fn the_tracker_should_always_use_the_remote_client_ip_but_not_the_port_in_the_udp_request_header_instead_of_the_peer_address_in_the_announce_request( + ) { + // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): + // "Do note that most trackers will only honor the IP address field under limited circumstances." + + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + let client_port = 8080; + + let remote_client_ip = "::100".parse().unwrap(); // IPV4 ::0.0.1.0 -> IPV6 = ::100 = ::ffff:0:100 = 0:0:0:0:0:ffff:0:0100 + let remote_client_port = 8081; + let peer_address = "126.0.0.1".parse().unwrap(); + + let remote_addr = SocketAddr::new(IpAddr::V6(remote_client_ip), remote_client_port); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(peer_address) + .with_port(client_port) + .into(); + + handle_announce( + remote_addr, + &request, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &core_udp_tracker_services.udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let peers = core_tracker_services + .in_memory_torrent_repository + .get_torrent_peers(&info_hash.0.into()); + + // When using IPv6 the tracker converts the remote client ip into a IPv4 address + assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); + } + + fn add_a_torrent_peer_using_ipv4(in_memory_torrent_repository: &Arc) { + let info_hash = AquaticInfoHash([0u8; 20]); + + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); + let client_port = 8080; + let peer_id = AquaticPeerId([255u8; 20]); + + let peer_using_ipv4 = TorrentPeerBuilder::new() + .with_peer_id(peer_id) + .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) + .into(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv4); + } + + async fn announce_a_new_peer_using_ipv6( + core_config: Arc, + announce_handler: Arc, + whitelist_authorization: Arc, + ) -> Response { + let (udp_stats_event_sender, _udp_stats_repository) = + packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); + let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); + let client_port = 8080; + let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .into(); + + handle_announce( + remote_addr, + &request, + &core_config, + &announce_handler, + &whitelist_authorization, + &udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap() + } + + #[tokio::test] + async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { + let (core_tracker_services, _core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + + add_a_torrent_peer_using_ipv4(&core_tracker_services.in_memory_torrent_repository); + + let response = announce_a_new_peer_using_ipv6( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.whitelist_authorization, + ) + .await; + + // The response should not contain the peer using IPV4 + let peers: Option>> = match response { + Response::AnnounceIpv4(announce_response) => Some(announce_response.peers), + _ => None, + }; + let no_ipv4_peers = peers.is_none(); + assert!(no_ipv4_peers); + } + + #[tokio::test] + async fn should_send_the_upd6_announce_event() { + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp6Announce)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + + let (core_tracker_services, _core_udp_tracker_services) = + initialize_core_tracker_services_for_default_tracker_configuration(); + + let remote_addr = sample_ipv6_remote_addr(); + + let announce_request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .into(); + + handle_announce( + remote_addr, + &announce_request, + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.whitelist_authorization, + &udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + } + + mod from_a_loopback_ip { + use std::future; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use mockall::predicate::eq; + + use crate::packages::udp_tracker_core; + use crate::servers::udp::connection_cookie::make; + use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::servers::udp::handlers::tests::{ + sample_cookie_valid_range, sample_issue_time, MockUdpStatsEventSender, TrackerConfigurationBuilder, + }; + use crate::servers::udp::handlers::{gen_remote_fingerprint, handle_announce}; + + #[tokio::test] + async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { + let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); + + let database = initialize_database(&config.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = + Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp6Announce)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); + let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); + + let client_ip_v4 = loopback_ipv4; + let client_ip_v6 = loopback_ipv6; + let client_port = 8080; + + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + + let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); + + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(client_ip_v4) + .with_port(client_port) + .into(); + + let core_config = Arc::new(config.core.clone()); + + handle_announce( + remote_addr, + &request, + &core_config, + &announce_handler, + &whitelist_authorization, + &udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + + let external_ip_in_tracker_configuration = core_config.net.external_ip.unwrap(); + + assert!(external_ip_in_tracker_configuration.is_ipv6()); + + // There's a special type of IPv6 addresses that provide compatibility with IPv4. + // The last 32 bits of these addresses represent an IPv4, and are represented like this: + // 1111:2222:3333:4444:5555:6666:1.2.3.4 + // + // ::127.0.0.1 is the IPV6 representation for the IPV4 address 127.0.0.1. + assert_eq!(Ok(peers[0].peer_addr.ip()), "::126.0.0.1".parse()); + } + } + } + } +} diff --git a/src/servers/udp/handlers/connect.rs b/src/servers/udp/handlers/connect.rs new file mode 100644 index 000000000..431c3bb4d --- /dev/null +++ b/src/servers/udp/handlers/connect.rs @@ -0,0 +1,199 @@ +//! UDP tracker connect handler. +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response}; +use tracing::{instrument, Level}; + +use crate::packages::udp_tracker_core; +use crate::servers::udp::connection_cookie::make; +use crate::servers::udp::handlers::gen_remote_fingerprint; + +/// It handles the `Connect` request. Refer to [`Connect`](crate::servers::udp#connect) +/// request for more information. +/// +/// # Errors +/// +/// This function does not ever return an error. +#[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] +pub async fn handle_connect( + remote_addr: SocketAddr, + request: &ConnectRequest, + opt_udp_stats_event_sender: &Arc>>, + cookie_issue_time: f64, +) -> Response { + tracing::Span::current().record("transaction_id", request.transaction_id.0.to_string()); + + tracing::trace!("handle connect"); + + let connection_id = make(gen_remote_fingerprint(&remote_addr), cookie_issue_time).expect("it should be a normal value"); + + let response = ConnectResponse { + transaction_id: request.transaction_id, + connection_id, + }; + + if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Connect) + .await; + } + SocketAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Connect) + .await; + } + } + } + + Response::from(response) +} + +#[cfg(test)] +mod tests { + + mod connect_request { + + use std::future; + use std::sync::Arc; + + use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; + use mockall::predicate::eq; + + use crate::packages::{self, udp_tracker_core}; + use crate::servers::udp::connection_cookie::make; + use crate::servers::udp::handlers::handle_connect; + use crate::servers::udp::handlers::tests::{ + sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, + sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpStatsEventSender, + }; + + fn sample_connect_request() -> ConnectRequest { + ConnectRequest { + transaction_id: TransactionId(0i32.into()), + } + } + + #[tokio::test] + async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + let request = ConnectRequest { + transaction_id: TransactionId(0i32.into()), + }; + + let response = handle_connect( + sample_ipv4_remote_addr(), + &request, + &udp_stats_event_sender, + sample_issue_time(), + ) + .await; + + assert_eq!( + response, + Response::Connect(ConnectResponse { + connection_id: make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + transaction_id: request.transaction_id + }) + ); + } + + #[tokio::test] + async fn a_connect_response_should_contain_a_new_connection_id() { + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + let request = ConnectRequest { + transaction_id: TransactionId(0i32.into()), + }; + + let response = handle_connect( + sample_ipv4_remote_addr(), + &request, + &udp_stats_event_sender, + sample_issue_time(), + ) + .await; + + assert_eq!( + response, + Response::Connect(ConnectResponse { + connection_id: make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + transaction_id: request.transaction_id + }) + ); + } + + #[tokio::test] + async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + let request = ConnectRequest { + transaction_id: TransactionId(0i32.into()), + }; + + let response = handle_connect( + sample_ipv6_remote_addr(), + &request, + &udp_stats_event_sender, + sample_issue_time(), + ) + .await; + + assert_eq!( + response, + Response::Connect(ConnectResponse { + connection_id: make(sample_ipv6_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + transaction_id: request.transaction_id + }) + ); + } + + #[tokio::test] + async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp4Connect)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + + let client_socket_address = sample_ipv4_socket_address(); + + handle_connect( + client_socket_address, + &sample_connect_request(), + &udp_stats_event_sender, + sample_issue_time(), + ) + .await; + } + + #[tokio::test] + async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp6Connect)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + + handle_connect( + sample_ipv6_remote_addr(), + &sample_connect_request(), + &udp_stats_event_sender, + sample_issue_time(), + ) + .await; + } + } +} diff --git a/src/servers/udp/handlers/error.rs b/src/servers/udp/handlers/error.rs new file mode 100644 index 000000000..36095eeed --- /dev/null +++ b/src/servers/udp/handlers/error.rs @@ -0,0 +1,80 @@ +//! UDP tracker error handling. +use std::net::SocketAddr; +use std::ops::Range; +use std::sync::Arc; + +use aquatic_udp_protocol::{ErrorResponse, RequestParseError, Response, TransactionId}; +use tracing::{instrument, Level}; +use uuid::Uuid; +use zerocopy::network_endian::I32; + +use crate::packages::udp_tracker_core; +use crate::servers::udp::connection_cookie::check; +use crate::servers::udp::error::Error; +use crate::servers::udp::handlers::gen_remote_fingerprint; +use crate::servers::udp::UDP_TRACKER_LOG_TARGET; + +#[allow(clippy::too_many_arguments)] +#[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] +pub async fn handle_error( + remote_addr: SocketAddr, + local_addr: SocketAddr, + request_id: Uuid, + opt_udp_stats_event_sender: &Arc>>, + cookie_valid_range: Range, + e: &Error, + transaction_id: Option, +) -> Response { + tracing::trace!("handle error"); + + match transaction_id { + Some(transaction_id) => { + let transaction_id = transaction_id.0.to_string(); + tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %e, %remote_addr, %local_addr, %request_id, %transaction_id, "response error"); + } + None => { + tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %e, %remote_addr, %local_addr, %request_id, "response error"); + } + } + + let e = if let Error::RequestParseError { request_parse_error } = e { + match request_parse_error { + RequestParseError::Sendable { + connection_id, + transaction_id, + err, + } => { + if let Err(e) = check(connection_id, gen_remote_fingerprint(&remote_addr), cookie_valid_range) { + (e.to_string(), Some(*transaction_id)) + } else { + ((*err).to_string(), Some(*transaction_id)) + } + } + RequestParseError::Unsendable { err } => (err.to_string(), transaction_id), + } + } else { + (e.to_string(), transaction_id) + }; + + if e.1.is_some() { + if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Error) + .await; + } + SocketAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Error) + .await; + } + } + } + } + + Response::from(ErrorResponse { + transaction_id: e.1.unwrap_or(TransactionId(I32::new(0))), + message: e.0.into(), + }) +} diff --git a/src/servers/udp/handlers/mod.rs b/src/servers/udp/handlers/mod.rs new file mode 100644 index 000000000..252a5be02 --- /dev/null +++ b/src/servers/udp/handlers/mod.rs @@ -0,0 +1,366 @@ +//! Handlers for the UDP server. +pub mod announce; +pub mod connect; +pub mod error; +pub mod scrape; + +use std::hash::{DefaultHasher, Hash, Hasher as _}; +use std::net::SocketAddr; +use std::ops::Range; +use std::sync::Arc; +use std::time::Instant; + +use announce::handle_announce; +use aquatic_udp_protocol::{Request, Response, TransactionId}; +use connect::handle_connect; +use error::handle_error; +use scrape::handle_scrape; +use torrust_tracker_clock::clock::Time as _; +use tracing::{instrument, Level}; +use uuid::Uuid; + +use super::RawRequest; +use crate::container::UdpTrackerContainer; +use crate::servers::udp::error::Error; +use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; +use crate::CurrentClock; + +#[derive(Debug, Clone, PartialEq)] +pub(super) struct CookieTimeValues { + pub(super) issue_time: f64, + pub(super) valid_range: Range, +} + +impl CookieTimeValues { + pub(super) fn new(cookie_lifetime: f64) -> Self { + let issue_time = CurrentClock::now().as_secs_f64(); + let expiry_time = issue_time - cookie_lifetime - 1.0; + let tolerance_max_time = issue_time + 1.0; + + Self { + issue_time, + valid_range: expiry_time..tolerance_max_time, + } + } +} + +/// It handles the incoming UDP packets. +/// +/// It's responsible for: +/// +/// - Parsing the incoming packet. +/// - Delegating the request to the correct handler depending on the request type. +/// +/// It will return an `Error` response if the request is invalid. +#[instrument(fields(request_id), skip(udp_request, udp_tracker_container, cookie_time_values), ret(level = Level::TRACE))] +pub(crate) async fn handle_packet( + udp_request: RawRequest, + udp_tracker_container: Arc, + local_addr: SocketAddr, + cookie_time_values: CookieTimeValues, +) -> Response { + let request_id = Uuid::new_v4(); + + tracing::Span::current().record("request_id", request_id.to_string()); + tracing::debug!("Handling Packets: {udp_request:?}"); + + let start_time = Instant::now(); + + let response = + match Request::parse_bytes(&udp_request.payload[..udp_request.payload.len()], MAX_SCRAPE_TORRENTS).map_err(Error::from) { + Ok(request) => match handle_request( + request, + udp_request.from, + udp_tracker_container.clone(), + cookie_time_values.clone(), + ) + .await + { + Ok(response) => return response, + Err((e, transaction_id)) => { + match &e { + Error::CookieValueNotNormal { .. } + | Error::CookieValueExpired { .. } + | Error::CookieValueFromFuture { .. } => { + // code-review: should we include `RequestParseError` and `BadRequest`? + let mut ban_service = udp_tracker_container.ban_service.write().await; + ban_service.increase_counter(&udp_request.from.ip()); + } + _ => {} + } + + handle_error( + udp_request.from, + local_addr, + request_id, + &udp_tracker_container.udp_stats_event_sender, + cookie_time_values.valid_range.clone(), + &e, + Some(transaction_id), + ) + .await + } + }, + Err(e) => { + handle_error( + udp_request.from, + local_addr, + request_id, + &udp_tracker_container.udp_stats_event_sender, + cookie_time_values.valid_range.clone(), + &e, + None, + ) + .await + } + }; + + let latency = start_time.elapsed(); + tracing::trace!(?latency, "responded"); + + response +} + +/// It dispatches the request to the correct handler. +/// +/// # Errors +/// +/// If a error happens in the `handle_request` function, it will just return the `ServerError`. +#[instrument(skip(request, remote_addr, udp_tracker_container, cookie_time_values))] +pub async fn handle_request( + request: Request, + remote_addr: SocketAddr, + udp_tracker_container: Arc, + cookie_time_values: CookieTimeValues, +) -> Result { + tracing::trace!("handle request"); + + match request { + Request::Connect(connect_request) => Ok(handle_connect( + remote_addr, + &connect_request, + &udp_tracker_container.udp_stats_event_sender, + cookie_time_values.issue_time, + ) + .await), + Request::Announce(announce_request) => { + handle_announce( + remote_addr, + &announce_request, + &udp_tracker_container.core_config, + &udp_tracker_container.announce_handler, + &udp_tracker_container.whitelist_authorization, + &udp_tracker_container.udp_stats_event_sender, + cookie_time_values.valid_range, + ) + .await + } + Request::Scrape(scrape_request) => { + handle_scrape( + remote_addr, + &scrape_request, + &udp_tracker_container.scrape_handler, + &udp_tracker_container.udp_stats_event_sender, + cookie_time_values.valid_range, + ) + .await + } + } +} + +#[must_use] +pub(crate) fn gen_remote_fingerprint(remote_addr: &SocketAddr) -> u64 { + let mut state = DefaultHasher::new(); + remote_addr.hash(&mut state); + state.finish() +} + +#[cfg(test)] +pub(crate) mod tests { + + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::ops::Range; + use std::sync::Arc; + + use aquatic_udp_protocol::{NumberOfBytes, PeerId}; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::scrape_handler::ScrapeHandler; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::whitelist; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use futures::future::BoxFuture; + use mockall::mock; + use tokio::sync::mpsc::error::SendError; + use torrust_tracker_clock::clock::Time; + use torrust_tracker_configuration::{Configuration, Core}; + use torrust_tracker_primitives::peer; + use torrust_tracker_test_helpers::configuration; + + use super::gen_remote_fingerprint; + use crate::packages::udp_tracker_core; + use crate::{packages, CurrentClock}; + + pub(crate) struct CoreTrackerServices { + pub core_config: Arc, + pub announce_handler: Arc, + pub scrape_handler: Arc, + pub in_memory_torrent_repository: Arc, + pub in_memory_whitelist: Arc, + pub whitelist_authorization: Arc, + } + + pub(crate) struct CoreUdpTrackerServices { + pub udp_stats_event_sender: Arc>>, + } + + fn default_testing_tracker_configuration() -> Configuration { + configuration::ephemeral() + } + + pub(crate) fn initialize_core_tracker_services_for_default_tracker_configuration( + ) -> (CoreTrackerServices, CoreUdpTrackerServices) { + initialize_core_tracker_services(&default_testing_tracker_configuration()) + } + + pub(crate) fn initialize_core_tracker_services_for_public_tracker() -> (CoreTrackerServices, CoreUdpTrackerServices) { + initialize_core_tracker_services(&configuration::ephemeral_public()) + } + + pub(crate) fn initialize_core_tracker_services_for_listed_tracker() -> (CoreTrackerServices, CoreUdpTrackerServices) { + initialize_core_tracker_services(&configuration::ephemeral_listed()) + } + + fn initialize_core_tracker_services(config: &Configuration) -> (CoreTrackerServices, CoreUdpTrackerServices) { + let core_config = Arc::new(config.core.clone()); + let database = initialize_database(&config.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + ( + CoreTrackerServices { + core_config, + announce_handler, + scrape_handler, + in_memory_torrent_repository, + in_memory_whitelist, + whitelist_authorization, + }, + CoreUdpTrackerServices { udp_stats_event_sender }, + ) + } + + pub(crate) fn sample_ipv4_remote_addr() -> SocketAddr { + sample_ipv4_socket_address() + } + + pub(crate) fn sample_ipv4_remote_addr_fingerprint() -> u64 { + gen_remote_fingerprint(&sample_ipv4_socket_address()) + } + + pub(crate) fn sample_ipv6_remote_addr() -> SocketAddr { + sample_ipv6_socket_address() + } + + pub(crate) fn sample_ipv6_remote_addr_fingerprint() -> u64 { + gen_remote_fingerprint(&sample_ipv6_socket_address()) + } + + pub(crate) fn sample_ipv4_socket_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) + } + + fn sample_ipv6_socket_address() -> SocketAddr { + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) + } + + pub(crate) fn sample_issue_time() -> f64 { + 1_000_000_000_f64 + } + + pub(crate) fn sample_cookie_valid_range() -> Range { + sample_issue_time() - 10.0..sample_issue_time() + 10.0 + } + + #[derive(Debug, Default)] + pub(crate) struct TorrentPeerBuilder { + peer: peer::Peer, + } + + impl TorrentPeerBuilder { + #[must_use] + pub fn new() -> Self { + Self { + peer: peer::Peer { + updated: CurrentClock::now(), + ..Default::default() + }, + } + } + + #[must_use] + pub fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { + self.peer.peer_addr = peer_addr; + self + } + + #[must_use] + pub fn with_peer_id(mut self, peer_id: PeerId) -> Self { + self.peer.peer_id = peer_id; + self + } + + #[must_use] + pub fn with_number_of_bytes_left(mut self, left: i64) -> Self { + self.peer.left = NumberOfBytes::new(left); + self + } + + #[must_use] + pub fn into(self) -> peer::Peer { + self.peer + } + } + + pub(crate) struct TrackerConfigurationBuilder { + configuration: Configuration, + } + + impl TrackerConfigurationBuilder { + pub fn default() -> TrackerConfigurationBuilder { + let default_configuration = default_testing_tracker_configuration(); + TrackerConfigurationBuilder { + configuration: default_configuration, + } + } + + pub fn with_external_ip(mut self, external_ip: &str) -> Self { + self.configuration.core.net.external_ip = Some(external_ip.to_owned().parse().expect("valid IP address")); + self + } + + pub fn into(self) -> Configuration { + self.configuration + } + } + + mock! { + pub(crate) UdpStatsEventSender {} + impl udp_tracker_core::statistics::event::sender::Sender for UdpStatsEventSender { + fn send_event(&self, event: udp_tracker_core::statistics::event::Event) -> BoxFuture<'static,Option > > > ; + } + } +} diff --git a/src/servers/udp/handlers/scrape.rs b/src/servers/udp/handlers/scrape.rs new file mode 100644 index 000000000..2c8ca335a --- /dev/null +++ b/src/servers/udp/handlers/scrape.rs @@ -0,0 +1,429 @@ +//! UDP tracker scrape handler. +use std::net::SocketAddr; +use std::ops::Range; +use std::sync::Arc; + +use aquatic_udp_protocol::{ + NumberOfDownloads, NumberOfPeers, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, +}; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use tracing::{instrument, Level}; +use zerocopy::network_endian::I32; + +use crate::packages::udp_tracker_core; +use crate::servers::udp::connection_cookie::check; +use crate::servers::udp::error::Error; +use crate::servers::udp::handlers::gen_remote_fingerprint; + +/// It handles the `Scrape` request. Refer to [`Scrape`](crate::servers::udp#scrape) +/// request for more information. +/// +/// # Errors +/// +/// This function does not ever return an error. +#[instrument(fields(transaction_id, connection_id), skip(scrape_handler, opt_udp_stats_event_sender), ret(level = Level::TRACE))] +pub async fn handle_scrape( + remote_addr: SocketAddr, + request: &ScrapeRequest, + scrape_handler: &Arc, + opt_udp_stats_event_sender: &Arc>>, + cookie_valid_range: Range, +) -> Result { + tracing::Span::current() + .record("transaction_id", request.transaction_id.0.to_string()) + .record("connection_id", request.connection_id.0.to_string()); + + tracing::trace!("handle scrape"); + + check( + &request.connection_id, + gen_remote_fingerprint(&remote_addr), + cookie_valid_range, + ) + .map_err(|e| (e, request.transaction_id))?; + + // Convert from aquatic infohashes + let mut info_hashes: Vec = vec![]; + for info_hash in &request.info_hashes { + info_hashes.push((*info_hash).into()); + } + + let scrape_data = scrape_handler.scrape(&info_hashes).await; + + let mut torrent_stats: Vec = Vec::new(); + + for file in &scrape_data.files { + let swarm_metadata = file.1; + + #[allow(clippy::cast_possible_truncation)] + let scrape_entry = { + TorrentScrapeStatistics { + seeders: NumberOfPeers(I32::new(i64::from(swarm_metadata.complete) as i32)), + completed: NumberOfDownloads(I32::new(i64::from(swarm_metadata.downloaded) as i32)), + leechers: NumberOfPeers(I32::new(i64::from(swarm_metadata.incomplete) as i32)), + } + }; + + torrent_stats.push(scrape_entry); + } + + if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Scrape) + .await; + } + SocketAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Scrape) + .await; + } + } + } + + let response = ScrapeResponse { + transaction_id: request.transaction_id, + torrent_stats, + }; + + Ok(Response::from(response)) +} + +#[cfg(test)] +mod tests { + + mod scrape_request { + use std::net::SocketAddr; + use std::sync::Arc; + + use aquatic_udp_protocol::{ + InfoHash, NumberOfDownloads, NumberOfPeers, PeerId, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, + TransactionId, + }; + use bittorrent_tracker_core::scrape_handler::ScrapeHandler; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + + use crate::packages; + use crate::servers::udp::connection_cookie::make; + use crate::servers::udp::handlers::tests::{ + initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, + sample_issue_time, TorrentPeerBuilder, + }; + use crate::servers::udp::handlers::{gen_remote_fingerprint, handle_scrape}; + + fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { + TorrentScrapeStatistics { + seeders: NumberOfPeers(0.into()), + completed: NumberOfDownloads(0.into()), + leechers: NumberOfPeers(0.into()), + } + } + + #[tokio::test] + async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + + let remote_addr = sample_ipv4_remote_addr(); + + let info_hash = InfoHash([0u8; 20]); + let info_hashes = vec![info_hash]; + + let request = ScrapeRequest { + connection_id: make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap(), + transaction_id: TransactionId(0i32.into()), + info_hashes, + }; + + let response = handle_scrape( + remote_addr, + &request, + &core_tracker_services.scrape_handler, + &core_udp_tracker_services.udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + + let expected_torrent_stats = vec![zeroed_torrent_statistics()]; + + assert_eq!( + response, + Response::from(ScrapeResponse { + transaction_id: request.transaction_id, + torrent_stats: expected_torrent_stats + }) + ); + } + + async fn add_a_seeder( + in_memory_torrent_repository: Arc, + remote_addr: &SocketAddr, + info_hash: &InfoHash, + ) { + let peer_id = PeerId([255u8; 20]); + + let peer = TorrentPeerBuilder::new() + .with_peer_id(peer_id) + .with_peer_address(*remote_addr) + .with_number_of_bytes_left(0) + .into(); + + let () = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer); + } + + fn build_scrape_request(remote_addr: &SocketAddr, info_hash: &InfoHash) -> ScrapeRequest { + let info_hashes = vec![*info_hash]; + + ScrapeRequest { + connection_id: make(gen_remote_fingerprint(remote_addr), sample_issue_time()).unwrap(), + transaction_id: TransactionId::new(0i32), + info_hashes, + } + } + + async fn add_a_sample_seeder_and_scrape( + in_memory_torrent_repository: Arc, + scrape_handler: Arc, + ) -> Response { + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + let remote_addr = sample_ipv4_remote_addr(); + let info_hash = InfoHash([0u8; 20]); + + add_a_seeder(in_memory_torrent_repository.clone(), &remote_addr, &info_hash).await; + + let request = build_scrape_request(&remote_addr, &info_hash); + + handle_scrape( + remote_addr, + &request, + &scrape_handler, + &udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap() + } + + fn match_scrape_response(response: Response) -> Option { + match response { + Response::Scrape(scrape_response) => Some(scrape_response), + _ => None, + } + } + + mod with_a_public_tracker { + use aquatic_udp_protocol::{NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; + + use crate::servers::udp::handlers::scrape::tests::scrape_request::{ + add_a_sample_seeder_and_scrape, match_scrape_response, + }; + use crate::servers::udp::handlers::tests::initialize_core_tracker_services_for_public_tracker; + + #[tokio::test] + async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { + let (core_tracker_services, _core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + + let torrent_stats = match_scrape_response( + add_a_sample_seeder_and_scrape( + core_tracker_services.in_memory_torrent_repository.clone(), + core_tracker_services.scrape_handler.clone(), + ) + .await, + ); + + let expected_torrent_stats = vec![TorrentScrapeStatistics { + seeders: NumberOfPeers(1.into()), + completed: NumberOfDownloads(0.into()), + leechers: NumberOfPeers(0.into()), + }]; + + assert_eq!(torrent_stats.unwrap().torrent_stats, expected_torrent_stats); + } + } + + mod with_a_whitelisted_tracker { + use aquatic_udp_protocol::{InfoHash, NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; + + use crate::servers::udp::handlers::handle_scrape; + use crate::servers::udp::handlers::scrape::tests::scrape_request::{ + add_a_seeder, build_scrape_request, match_scrape_response, zeroed_torrent_statistics, + }; + use crate::servers::udp::handlers::tests::{ + initialize_core_tracker_services_for_listed_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, + }; + + #[tokio::test] + async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_listed_tracker(); + + let remote_addr = sample_ipv4_remote_addr(); + let info_hash = InfoHash([0u8; 20]); + + add_a_seeder( + core_tracker_services.in_memory_torrent_repository.clone(), + &remote_addr, + &info_hash, + ) + .await; + + core_tracker_services.in_memory_whitelist.add(&info_hash.0.into()).await; + + let request = build_scrape_request(&remote_addr, &info_hash); + + let torrent_stats = match_scrape_response( + handle_scrape( + remote_addr, + &request, + &core_tracker_services.scrape_handler, + &core_udp_tracker_services.udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(), + ) + .unwrap(); + + let expected_torrent_stats = vec![TorrentScrapeStatistics { + seeders: NumberOfPeers(1.into()), + completed: NumberOfDownloads(0.into()), + leechers: NumberOfPeers(0.into()), + }]; + + assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); + } + + #[tokio::test] + async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { + let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_listed_tracker(); + + let remote_addr = sample_ipv4_remote_addr(); + let info_hash = InfoHash([0u8; 20]); + + add_a_seeder( + core_tracker_services.in_memory_torrent_repository.clone(), + &remote_addr, + &info_hash, + ) + .await; + + let request = build_scrape_request(&remote_addr, &info_hash); + + let torrent_stats = match_scrape_response( + handle_scrape( + remote_addr, + &request, + &core_tracker_services.scrape_handler, + &core_udp_tracker_services.udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(), + ) + .unwrap(); + + let expected_torrent_stats = vec![zeroed_torrent_statistics()]; + + assert_eq!(torrent_stats.torrent_stats, expected_torrent_stats); + } + } + + fn sample_scrape_request(remote_addr: &SocketAddr) -> ScrapeRequest { + let info_hash = InfoHash([0u8; 20]); + let info_hashes = vec![info_hash]; + + ScrapeRequest { + connection_id: make(gen_remote_fingerprint(remote_addr), sample_issue_time()).unwrap(), + transaction_id: TransactionId(0i32.into()), + info_hashes, + } + } + + mod using_ipv4 { + use std::future; + use std::sync::Arc; + + use mockall::predicate::eq; + + use super::sample_scrape_request; + use crate::packages::udp_tracker_core; + use crate::servers::udp::handlers::handle_scrape; + use crate::servers::udp::handlers::tests::{ + initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, + sample_ipv4_remote_addr, MockUdpStatsEventSender, + }; + + #[tokio::test] + async fn should_send_the_upd4_scrape_event() { + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp4Scrape)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + + let remote_addr = sample_ipv4_remote_addr(); + + let (core_tracker_services, _core_udp_tracker_services) = + initialize_core_tracker_services_for_default_tracker_configuration(); + + handle_scrape( + remote_addr, + &sample_scrape_request(&remote_addr), + &core_tracker_services.scrape_handler, + &udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + } + } + + mod using_ipv6 { + use std::future; + use std::sync::Arc; + + use mockall::predicate::eq; + + use super::sample_scrape_request; + use crate::packages::udp_tracker_core; + use crate::servers::udp::handlers::handle_scrape; + use crate::servers::udp::handlers::tests::{ + initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, + sample_ipv6_remote_addr, MockUdpStatsEventSender, + }; + + #[tokio::test] + async fn should_send_the_upd6_scrape_event() { + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp6Scrape)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + + let remote_addr = sample_ipv6_remote_addr(); + + let (core_tracker_services, _core_udp_tracker_services) = + initialize_core_tracker_services_for_default_tracker_configuration(); + + handle_scrape( + remote_addr, + &sample_scrape_request(&remote_addr), + &core_tracker_services.scrape_handler, + &udp_stats_event_sender, + sample_cookie_valid_range(), + ) + .await + .unwrap(); + } + } + } +} From 3c07b260313bb088682e8378e7f4393340c85fc5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Feb 2025 13:44:19 +0000 Subject: [PATCH 0750/1297] refactor: [#1268] extract servers::udp::services::announce service --- src/servers/udp/handlers/announce.rs | 26 ++++++--------- src/servers/udp/mod.rs | 1 + src/servers/udp/services/announce.rs | 48 ++++++++++++++++++++++++++++ src/servers/udp/services/mod.rs | 2 ++ src/servers/udp/services/scrape.rs | 0 5 files changed, 60 insertions(+), 17 deletions(-) create mode 100644 src/servers/udp/services/announce.rs create mode 100644 src/servers/udp/services/mod.rs create mode 100644 src/servers/udp/services/scrape.rs diff --git a/src/servers/udp/handlers/announce.rs b/src/servers/udp/handlers/announce.rs index 79fb91f49..ecc4ba88f 100644 --- a/src/servers/udp/handlers/announce.rs +++ b/src/servers/udp/handlers/announce.rs @@ -18,7 +18,7 @@ use crate::packages::udp_tracker_core; use crate::servers::udp::connection_cookie::check; use crate::servers::udp::error::Error; use crate::servers::udp::handlers::gen_remote_fingerprint; -use crate::servers::udp::peer_builder; +use crate::servers::udp::{peer_builder, services}; /// It handles the `Announce` request. Refer to [`Announce`](crate::servers::udp#announce) /// request for more information. @@ -66,22 +66,14 @@ pub async fn handle_announce( let mut peer = peer_builder::from_request(request, &remote_client_ip); let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); - let response = announce_handler.announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted); - - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { - match remote_client_ip { - IpAddr::V4(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Announce) - .await; - } - IpAddr::V6(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Announce) - .await; - } - } - } + let response = services::announce::invoke( + announce_handler.clone(), + opt_udp_stats_event_sender.clone(), + info_hash, + &mut peer, + &peers_wanted, + ) + .await; #[allow(clippy::cast_possible_truncation)] if remote_addr.is_ipv4() { diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index b141cc322..604fee8fe 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -642,6 +642,7 @@ pub mod error; pub mod handlers; pub mod peer_builder; pub mod server; +pub mod services; pub const UDP_TRACKER_LOG_TARGET: &str = "UDP TRACKER"; diff --git a/src/servers/udp/services/announce.rs b/src/servers/udp/services/announce.rs new file mode 100644 index 000000000..317b1afef --- /dev/null +++ b/src/servers/udp/services/announce.rs @@ -0,0 +1,48 @@ +//! The `announce` service. +//! +//! The service is responsible for handling the `announce` requests. +//! +//! It delegates the `announce` logic to the [`AnnounceHandler`] and it returns +//! the [`AnnounceData`]. +//! +//! It also sends an [`http_tracker_core::statistics::event::Event`] +//! because events are specific for the HTTP tracker. +use std::net::IpAddr; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; +use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::peer; + +use crate::packages::udp_tracker_core; + +pub async fn invoke( + announce_handler: Arc, + opt_udp_stats_event_sender: Arc>>, + info_hash: InfoHash, + peer: &mut peer::Peer, + peers_wanted: &PeersWanted, +) -> AnnounceData { + let original_peer_ip = peer.peer_addr.ip(); + + // The tracker could change the original peer ip + let announce_data = announce_handler.announce(&info_hash, peer, &original_peer_ip, peers_wanted); + + if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + match original_peer_ip { + IpAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Announce) + .await; + } + IpAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Announce) + .await; + } + } + } + + announce_data +} diff --git a/src/servers/udp/services/mod.rs b/src/servers/udp/services/mod.rs new file mode 100644 index 000000000..776d2dfbf --- /dev/null +++ b/src/servers/udp/services/mod.rs @@ -0,0 +1,2 @@ +pub mod announce; +pub mod scrape; diff --git a/src/servers/udp/services/scrape.rs b/src/servers/udp/services/scrape.rs new file mode 100644 index 000000000..e69de29bb From dec742e2326a9e9861a1b26907c1cbfe0c127838 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Feb 2025 13:52:46 +0000 Subject: [PATCH 0751/1297] refactor: [#1268] extract servers::udp::services::scrape service --- src/servers/udp/handlers/scrape.rs | 18 ++---------- src/servers/udp/services/announce.rs | 2 +- src/servers/udp/services/scrape.rs | 43 ++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 17 deletions(-) diff --git a/src/servers/udp/handlers/scrape.rs b/src/servers/udp/handlers/scrape.rs index 2c8ca335a..d68ca07dd 100644 --- a/src/servers/udp/handlers/scrape.rs +++ b/src/servers/udp/handlers/scrape.rs @@ -15,6 +15,7 @@ use crate::packages::udp_tracker_core; use crate::servers::udp::connection_cookie::check; use crate::servers::udp::error::Error; use crate::servers::udp::handlers::gen_remote_fingerprint; +use crate::servers::udp::services; /// It handles the `Scrape` request. Refer to [`Scrape`](crate::servers::udp#scrape) /// request for more information. @@ -49,7 +50,7 @@ pub async fn handle_scrape( info_hashes.push((*info_hash).into()); } - let scrape_data = scrape_handler.scrape(&info_hashes).await; + let scrape_data = services::scrape::invoke(scrape_handler, opt_udp_stats_event_sender, &info_hashes, remote_addr).await; let mut torrent_stats: Vec = Vec::new(); @@ -68,21 +69,6 @@ pub async fn handle_scrape( torrent_stats.push(scrape_entry); } - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { - match remote_addr { - SocketAddr::V4(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Scrape) - .await; - } - SocketAddr::V6(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Scrape) - .await; - } - } - } - let response = ScrapeResponse { transaction_id: request.transaction_id, torrent_stats, diff --git a/src/servers/udp/services/announce.rs b/src/servers/udp/services/announce.rs index 317b1afef..8a046a625 100644 --- a/src/servers/udp/services/announce.rs +++ b/src/servers/udp/services/announce.rs @@ -5,7 +5,7 @@ //! It delegates the `announce` logic to the [`AnnounceHandler`] and it returns //! the [`AnnounceData`]. //! -//! It also sends an [`http_tracker_core::statistics::event::Event`] +//! It also sends an [`udp_tracker_core::statistics::event::Event`] //! because events are specific for the HTTP tracker. use std::net::IpAddr; use std::sync::Arc; diff --git a/src/servers/udp/services/scrape.rs b/src/servers/udp/services/scrape.rs index e69de29bb..7d4897564 100644 --- a/src/servers/udp/services/scrape.rs +++ b/src/servers/udp/services/scrape.rs @@ -0,0 +1,43 @@ +//! The `scrape` service. +//! +//! The service is responsible for handling the `scrape` requests. +//! +//! It delegates the `scrape` logic to the [`ScrapeHandler`] and it returns the +//! [`ScrapeData`]. +//! +//! It also sends an [`udp_tracker_core::statistics::event::Event`] +//! because events are specific for the UDP tracker. +use std::net::SocketAddr; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use torrust_tracker_primitives::core::ScrapeData; + +use crate::packages::udp_tracker_core; + +pub async fn invoke( + scrape_handler: &Arc, + opt_udp_stats_event_sender: &Arc>>, + info_hashes: &Vec, + remote_addr: SocketAddr, +) -> ScrapeData { + let scrape_data = scrape_handler.scrape(info_hashes).await; + + if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Scrape) + .await; + } + SocketAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Scrape) + .await; + } + } + } + + scrape_data +} From 73753e31f2626ff694bb0ea8994cce2877e2a637 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Feb 2025 15:41:25 +0000 Subject: [PATCH 0752/1297] [#1268] move http services to http_tracker_core package --- src/packages/http_tracker_core/mod.rs | 1 + .../http_tracker_core}/services/announce.rs | 6 +++--- .../http_tracker_core}/services/mod.rs | 0 .../http_tracker_core}/services/scrape.rs | 16 ++++++++-------- src/servers/http/v1/handlers/announce.rs | 2 +- src/servers/http/v1/handlers/scrape.rs | 2 +- src/servers/http/v1/mod.rs | 1 - 7 files changed, 14 insertions(+), 14 deletions(-) rename src/{servers/http/v1 => packages/http_tracker_core}/services/announce.rs (98%) rename src/{servers/http/v1 => packages/http_tracker_core}/services/mod.rs (100%) rename src/{servers/http/v1 => packages/http_tracker_core}/services/scrape.rs (97%) diff --git a/src/packages/http_tracker_core/mod.rs b/src/packages/http_tracker_core/mod.rs index 3449ec7b4..4f3e54857 100644 --- a/src/packages/http_tracker_core/mod.rs +++ b/src/packages/http_tracker_core/mod.rs @@ -1 +1,2 @@ +pub mod services; pub mod statistics; diff --git a/src/servers/http/v1/services/announce.rs b/src/packages/http_tracker_core/services/announce.rs similarity index 98% rename from src/servers/http/v1/services/announce.rs rename to src/packages/http_tracker_core/services/announce.rs index e321ad01f..67b5997b3 100644 --- a/src/servers/http/v1/services/announce.rs +++ b/src/packages/http_tracker_core/services/announce.rs @@ -164,11 +164,11 @@ mod tests { use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; use crate::packages::http_tracker_core; - use crate::servers::http::test_helpers::tests::sample_info_hash; - use crate::servers::http::v1::services::announce::invoke; - use crate::servers::http::v1::services::announce::tests::{ + use crate::packages::http_tracker_core::services::announce::invoke; + use crate::packages::http_tracker_core::services::announce::tests::{ initialize_core_tracker_services, sample_peer, MockHttpStatsEventSender, }; + use crate::servers::http::test_helpers::tests::sample_info_hash; fn initialize_announce_handler() -> Arc { let config = configuration::ephemeral(); diff --git a/src/servers/http/v1/services/mod.rs b/src/packages/http_tracker_core/services/mod.rs similarity index 100% rename from src/servers/http/v1/services/mod.rs rename to src/packages/http_tracker_core/services/mod.rs diff --git a/src/servers/http/v1/services/scrape.rs b/src/packages/http_tracker_core/services/scrape.rs similarity index 97% rename from src/servers/http/v1/services/scrape.rs rename to src/packages/http_tracker_core/services/scrape.rs index e2eb4f87c..8ce83212e 100644 --- a/src/servers/http/v1/services/scrape.rs +++ b/src/packages/http_tracker_core/services/scrape.rs @@ -161,13 +161,13 @@ mod tests { use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::packages::{self, http_tracker_core}; - use crate::servers::http::test_helpers::tests::sample_info_hash; - use crate::servers::http::v1::services::scrape::invoke; - use crate::servers::http::v1::services::scrape::tests::{ + use crate::packages::http_tracker_core::services::scrape::invoke; + use crate::packages::http_tracker_core::services::scrape::tests::{ initialize_announce_and_scrape_handlers_for_public_tracker, initialize_scrape_handler, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; + use crate::packages::{self, http_tracker_core}; + use crate::servers::http::test_helpers::tests::sample_info_hash; #[tokio::test] async fn it_should_return_the_scrape_data_for_a_torrent() { @@ -247,12 +247,12 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; - use crate::packages::{self, http_tracker_core}; - use crate::servers::http::test_helpers::tests::sample_info_hash; - use crate::servers::http::v1::services::scrape::fake; - use crate::servers::http::v1::services::scrape::tests::{ + use crate::packages::http_tracker_core::services::scrape::fake; + use crate::packages::http_tracker_core::services::scrape::tests::{ initialize_announce_and_scrape_handlers_for_public_tracker, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; + use crate::packages::{self, http_tracker_core}; + use crate::servers::http::test_helpers::tests::sample_info_hash; #[tokio::test] async fn it_should_always_return_the_zeroed_scrape_data_for_a_torrent() { diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 64939ff48..ffc6a7b0a 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -28,11 +28,11 @@ use torrust_tracker_primitives::peer; use super::common::auth::map_auth_error_to_error_response; use crate::packages::http_tracker_core; +use crate::packages::http_tracker_core::services::{self}; use crate::servers::http::v1::extractors::announce_request::ExtractRequest; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::handlers::common::auth; -use crate::servers::http::v1::services::{self}; use crate::CurrentClock; /// It handles the `announce` request when the HTTP tracker does not require diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 09af385fb..d2f4f9e0f 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -20,10 +20,10 @@ use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; use crate::packages::http_tracker_core; +use crate::packages::http_tracker_core::services; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::extractors::scrape_request::ExtractRequest; -use crate::servers::http::v1::services; /// It handles the `scrape` request when the HTTP tracker is configured /// to run in `public` mode. diff --git a/src/servers/http/v1/mod.rs b/src/servers/http/v1/mod.rs index 48dac5663..6e9530cb0 100644 --- a/src/servers/http/v1/mod.rs +++ b/src/servers/http/v1/mod.rs @@ -5,4 +5,3 @@ pub mod extractors; pub mod handlers; pub mod routes; -pub mod services; From e48aaf51db7d7b84899c66149ecde2c6facb0615 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Feb 2025 15:47:28 +0000 Subject: [PATCH 0753/1297] [#1268] move udp services to udp_tracker_core package --- src/packages/udp_tracker_core/mod.rs | 1 + .../udp => packages/udp_tracker_core}/services/announce.rs | 0 .../udp => packages/udp_tracker_core}/services/mod.rs | 0 .../udp => packages/udp_tracker_core}/services/scrape.rs | 0 src/servers/udp/handlers/announce.rs | 4 ++-- src/servers/udp/handlers/scrape.rs | 2 +- src/servers/udp/mod.rs | 1 - 7 files changed, 4 insertions(+), 4 deletions(-) rename src/{servers/udp => packages/udp_tracker_core}/services/announce.rs (100%) rename src/{servers/udp => packages/udp_tracker_core}/services/mod.rs (100%) rename src/{servers/udp => packages/udp_tracker_core}/services/scrape.rs (100%) diff --git a/src/packages/udp_tracker_core/mod.rs b/src/packages/udp_tracker_core/mod.rs index 3449ec7b4..4f3e54857 100644 --- a/src/packages/udp_tracker_core/mod.rs +++ b/src/packages/udp_tracker_core/mod.rs @@ -1 +1,2 @@ +pub mod services; pub mod statistics; diff --git a/src/servers/udp/services/announce.rs b/src/packages/udp_tracker_core/services/announce.rs similarity index 100% rename from src/servers/udp/services/announce.rs rename to src/packages/udp_tracker_core/services/announce.rs diff --git a/src/servers/udp/services/mod.rs b/src/packages/udp_tracker_core/services/mod.rs similarity index 100% rename from src/servers/udp/services/mod.rs rename to src/packages/udp_tracker_core/services/mod.rs diff --git a/src/servers/udp/services/scrape.rs b/src/packages/udp_tracker_core/services/scrape.rs similarity index 100% rename from src/servers/udp/services/scrape.rs rename to src/packages/udp_tracker_core/services/scrape.rs diff --git a/src/servers/udp/handlers/announce.rs b/src/servers/udp/handlers/announce.rs index ecc4ba88f..26a1a2116 100644 --- a/src/servers/udp/handlers/announce.rs +++ b/src/servers/udp/handlers/announce.rs @@ -14,11 +14,11 @@ use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; -use crate::packages::udp_tracker_core; +use crate::packages::udp_tracker_core::{self, services}; use crate::servers::udp::connection_cookie::check; use crate::servers::udp::error::Error; use crate::servers::udp::handlers::gen_remote_fingerprint; -use crate::servers::udp::{peer_builder, services}; +use crate::servers::udp::peer_builder; /// It handles the `Announce` request. Refer to [`Announce`](crate::servers::udp#announce) /// request for more information. diff --git a/src/servers/udp/handlers/scrape.rs b/src/servers/udp/handlers/scrape.rs index d68ca07dd..3b5ccf50d 100644 --- a/src/servers/udp/handlers/scrape.rs +++ b/src/servers/udp/handlers/scrape.rs @@ -12,10 +12,10 @@ use tracing::{instrument, Level}; use zerocopy::network_endian::I32; use crate::packages::udp_tracker_core; +use crate::packages::udp_tracker_core::services; use crate::servers::udp::connection_cookie::check; use crate::servers::udp::error::Error; use crate::servers::udp::handlers::gen_remote_fingerprint; -use crate::servers::udp::services; /// It handles the `Scrape` request. Refer to [`Scrape`](crate::servers::udp#scrape) /// request for more information. diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index 604fee8fe..b141cc322 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -642,7 +642,6 @@ pub mod error; pub mod handlers; pub mod peer_builder; pub mod server; -pub mod services; pub const UDP_TRACKER_LOG_TARGET: &str = "UDP TRACKER"; From 74815abeb78198e0cc234e47a4af0633247232cf Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Feb 2025 16:31:15 +0000 Subject: [PATCH 0754/1297] refactor: [#1268] move announce logic from axum to http_tracker_core package --- Cargo.lock | 1 + packages/http-protocol/Cargo.toml | 1 + packages/http-protocol/src/lib.rs | 13 ++++ .../http-protocol/src/v1/requests/announce.rs | 33 ++++++++- .../http_tracker_core/services/announce.rs | 53 ++++++++++++++ src/servers/http/v1/handlers/announce.rs | 69 ++++--------------- 6 files changed, 113 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2f99db113..408471efc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -560,6 +560,7 @@ dependencies = [ "serde", "serde_bencode", "thiserror 2.0.11", + "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-contrib-bencode", "torrust-tracker-located-error", diff --git a/packages/http-protocol/Cargo.toml b/packages/http-protocol/Cargo.toml index 2d0cabf51..e76094c1a 100644 --- a/packages/http-protocol/Cargo.toml +++ b/packages/http-protocol/Cargo.toml @@ -24,6 +24,7 @@ percent-encoding = "2" serde = { version = "1", features = ["derive"] } serde_bencode = "0" thiserror = "2" +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-contrib-bencode = { version = "3.0.0-develop", path = "../../contrib/bencode" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } diff --git a/packages/http-protocol/src/lib.rs b/packages/http-protocol/src/lib.rs index 6525a6dca..326a5b182 100644 --- a/packages/http-protocol/src/lib.rs +++ b/packages/http-protocol/src/lib.rs @@ -1,3 +1,16 @@ //! Primitive types and function for `BitTorrent` HTTP trackers. pub mod percent_encoding; pub mod v1; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/packages/http-protocol/src/v1/requests/announce.rs b/packages/http-protocol/src/v1/requests/announce.rs index 9bde7ec13..f293b9cf5 100644 --- a/packages/http-protocol/src/v1/requests/announce.rs +++ b/packages/http-protocol/src/v1/requests/announce.rs @@ -2,18 +2,21 @@ //! //! Data structures and logic for parsing the `announce` request. use std::fmt; +use std::net::{IpAddr, SocketAddr}; use std::panic::Location; use std::str::FromStr; -use aquatic_udp_protocol::{NumberOfBytes, PeerId}; +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::{self, InfoHash}; use thiserror::Error; +use torrust_tracker_clock::clock::Time; use torrust_tracker_located_error::{Located, LocatedError}; use torrust_tracker_primitives::peer; use crate::percent_encoding::{percent_decode_info_hash, percent_decode_peer_id}; use crate::v1::query::{ParseQueryError, Query}; use crate::v1::responses; +use crate::CurrentClock; // Query param names const INFO_HASH: &str = "info_hash"; @@ -373,6 +376,34 @@ fn extract_numwant(query: &Query) -> Result, ParseAnnounceQueryError } } +/// It builds a `Peer` from the announce request. +/// +/// It ignores the peer address in the announce request params. +#[must_use] +pub fn peer_from_request(announce_request: &Announce, peer_ip: &IpAddr) -> peer::Peer { + peer::Peer { + peer_id: announce_request.peer_id, + peer_addr: SocketAddr::new(*peer_ip, announce_request.port), + updated: CurrentClock::now(), + uploaded: announce_request.uploaded.unwrap_or(NumberOfBytes::new(0)), + downloaded: announce_request.downloaded.unwrap_or(NumberOfBytes::new(0)), + left: announce_request.left.unwrap_or(NumberOfBytes::new(0)), + event: map_to_torrust_event(&announce_request.event), + } +} + +#[must_use] +pub fn map_to_torrust_event(event: &Option) -> AnnounceEvent { + match event { + Some(event) => match &event { + Event::Started => AnnounceEvent::Started, + Event::Stopped => AnnounceEvent::Stopped, + Event::Completed => AnnounceEvent::Completed, + }, + None => AnnounceEvent::None, + } +} + #[cfg(test)] mod tests { diff --git a/src/packages/http_tracker_core/services/announce.rs b/src/packages/http_tracker_core/services/announce.rs index 67b5997b3..049d0d228 100644 --- a/src/packages/http_tracker_core/services/announce.rs +++ b/src/packages/http_tracker_core/services/announce.rs @@ -10,8 +10,14 @@ use std::net::IpAddr; use std::sync::Arc; +use bittorrent_http_protocol::v1::requests::announce::{peer_from_request, Announce}; +use bittorrent_http_protocol::v1::responses; +use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; +use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::whitelist; +use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; @@ -27,6 +33,53 @@ use crate::packages::http_tracker_core; /// > **NOTICE**: as the HTTP tracker does not requires a connection request /// > like the UDP tracker, the number of TCP connections is incremented for /// > each `announce` request. +/// +/// # Errors +/// +/// This function will return an error if: +/// +/// - The tracker is running in `listed` mode and the torrent is not whitelisted. +/// - There is an error when resolving the client IP address. +#[allow(clippy::too_many_arguments)] +pub async fn handle_announce( + core_config: &Arc, + announce_handler: &Arc, + _authentication_service: &Arc, + whitelist_authorization: &Arc, + opt_http_stats_event_sender: &Arc>>, + announce_request: &Announce, + client_ip_sources: &ClientIpSources, +) -> Result { + // Authorization + match whitelist_authorization.authorize(&announce_request.info_hash).await { + Ok(()) => (), + Err(error) => return Err(responses::error::Error::from(error)), + } + + let peer_ip = match peer_ip_resolver::invoke(core_config.net.on_reverse_proxy, client_ip_sources) { + Ok(peer_ip) => peer_ip, + Err(error) => return Err(responses::error::Error::from(error)), + }; + + let mut peer = peer_from_request(announce_request, &peer_ip); + + let peers_wanted = match announce_request.numwant { + Some(numwant) => PeersWanted::only(numwant), + None => PeersWanted::AsManyAsPossible, + }; + + let announce_data = invoke( + announce_handler.clone(), + opt_http_stats_event_sender.clone(), + announce_request.info_hash, + &mut peer, + &peers_wanted, + ) + .await; + + Ok(announce_data) +} + pub async fn invoke( announce_handler: Arc, opt_http_stats_event_sender: Arc>>, diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index ffc6a7b0a..977e7dd6a 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -5,35 +5,29 @@ //! //! The handlers perform the authentication and authorization of the request, //! and resolve the client IP address. -use std::net::{IpAddr, SocketAddr}; use std::panic::Location; use std::sync::Arc; -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use aquatic_udp_protocol::AnnounceEvent; use axum::extract::State; use axum::response::{IntoResponse, Response}; use bittorrent_http_protocol::v1::requests::announce::{Announce, Compact, Event}; use bittorrent_http_protocol::v1::responses::{self}; -use bittorrent_http_protocol::v1::services::peer_ip_resolver; use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; -use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; +use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::Key; use bittorrent_tracker_core::whitelist; use hyper::StatusCode; -use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; -use torrust_tracker_primitives::peer; use super::common::auth::map_auth_error_to_error_response; use crate::packages::http_tracker_core; -use crate::packages::http_tracker_core::services::{self}; use crate::servers::http::v1::extractors::announce_request::ExtractRequest; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::handlers::common::auth; -use crate::CurrentClock; /// It handles the `announce` request when the HTTP tracker does not require /// authentication (no PATH `key` parameter required). @@ -129,12 +123,6 @@ async fn handle( build_response(announce_request, announce_data) } -/* code-review: authentication, authorization and peer IP resolution could be moved - from the handler (Axum) layer into the app layer `services::announce::invoke`. - That would make the handler even simpler and the code more reusable and decoupled from Axum. - See https://github.com/torrust/torrust-tracker/discussions/240. -*/ - #[allow(clippy::too_many_arguments)] async fn handle_announce( core_config: &Arc, @@ -146,6 +134,8 @@ async fn handle_announce( client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Result { + // todo: move authentication inside `http_tracker_core::services::announce::handle_announce` + // Authentication if core_config.private { match maybe_key { @@ -161,33 +151,16 @@ async fn handle_announce( } } - // Authorization - match whitelist_authorization.authorize(&announce_request.info_hash).await { - Ok(()) => (), - Err(error) => return Err(responses::error::Error::from(error)), - } - - let peer_ip = match peer_ip_resolver::invoke(core_config.net.on_reverse_proxy, client_ip_sources) { - Ok(peer_ip) => peer_ip, - Err(error) => return Err(responses::error::Error::from(error)), - }; - - let mut peer = peer_from_request(announce_request, &peer_ip); - let peers_wanted = match announce_request.numwant { - Some(numwant) => PeersWanted::only(numwant), - None => PeersWanted::AsManyAsPossible, - }; - - let announce_data = services::announce::invoke( - announce_handler.clone(), - opt_http_stats_event_sender.clone(), - announce_request.info_hash, - &mut peer, - &peers_wanted, + http_tracker_core::services::announce::handle_announce( + &core_config.clone(), + &announce_handler.clone(), + &authentication_service.clone(), + &whitelist_authorization.clone(), + &opt_http_stats_event_sender.clone(), + announce_request, + client_ip_sources, ) - .await; - - Ok(announce_data) + .await } fn build_response(announce_request: &Announce, announce_data: AnnounceData) -> Response { @@ -202,22 +175,6 @@ fn build_response(announce_request: &Announce, announce_data: AnnounceData) -> R } } -/// It builds a `Peer` from the announce request. -/// -/// It ignores the peer address in the announce request params. -#[must_use] -fn peer_from_request(announce_request: &Announce, peer_ip: &IpAddr) -> peer::Peer { - peer::Peer { - peer_id: announce_request.peer_id, - peer_addr: SocketAddr::new(*peer_ip, announce_request.port), - updated: CurrentClock::now(), - uploaded: announce_request.uploaded.unwrap_or(NumberOfBytes::new(0)), - downloaded: announce_request.downloaded.unwrap_or(NumberOfBytes::new(0)), - left: announce_request.left.unwrap_or(NumberOfBytes::new(0)), - event: map_to_torrust_event(&announce_request.event), - } -} - #[must_use] pub fn map_to_aquatic_event(event: &Option) -> aquatic_udp_protocol::AnnounceEvent { match event { From 37a142efcea0d1c85a7a16ec67d0847414855171 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Feb 2025 16:45:35 +0000 Subject: [PATCH 0755/1297] refactor: [#1268] move scrape logic from axum to http_tracker_core package --- .../http_tracker_core/services/scrape.rs | 42 +++++++++++++++++++ src/servers/http/v1/handlers/scrape.rs | 40 ++++++------------ 2 files changed, 55 insertions(+), 27 deletions(-) diff --git a/src/packages/http_tracker_core/services/scrape.rs b/src/packages/http_tracker_core/services/scrape.rs index 8ce83212e..62f5fdf62 100644 --- a/src/packages/http_tracker_core/services/scrape.rs +++ b/src/packages/http_tracker_core/services/scrape.rs @@ -10,8 +10,13 @@ use std::net::IpAddr; use std::sync::Arc; +use bittorrent_http_protocol::v1::requests::scrape::Scrape; +use bittorrent_http_protocol::v1::responses; +use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; use crate::packages::http_tracker_core; @@ -26,6 +31,43 @@ use crate::packages::http_tracker_core; /// > **NOTICE**: as the HTTP tracker does not requires a connection request /// > like the UDP tracker, the number of TCP connections is incremented for /// > each `scrape` request. +/// +/// # Errors +/// +/// This function will return an error if: +/// +/// - There is an error when resolving the client IP address. +#[allow(clippy::too_many_arguments)] +pub async fn handle_scrape( + core_config: &Arc, + scrape_handler: &Arc, + _authentication_service: &Arc, + opt_http_stats_event_sender: &Arc>>, + scrape_request: &Scrape, + client_ip_sources: &ClientIpSources, + return_real_scrape_data: bool, +) -> Result { + // Authorization for scrape requests is handled at the `http_tracker_core` + // level for each torrent. + + let peer_ip = match peer_ip_resolver::invoke(core_config.net.on_reverse_proxy, client_ip_sources) { + Ok(peer_ip) => peer_ip, + Err(error) => return Err(responses::error::Error::from(error)), + }; + + if return_real_scrape_data { + Ok(invoke( + scrape_handler, + opt_http_stats_event_sender, + &scrape_request.info_hashes, + &peer_ip, + ) + .await) + } else { + Ok(http_tracker_core::services::scrape::fake(opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await) + } +} + pub async fn invoke( scrape_handler: &Arc, opt_http_stats_event_sender: &Arc>>, diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index d2f4f9e0f..39bebe18e 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -11,7 +11,7 @@ use axum::extract::State; use axum::response::{IntoResponse, Response}; use bittorrent_http_protocol::v1::requests::scrape::Scrape; use bittorrent_http_protocol::v1::responses; -use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; +use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::Key; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; @@ -20,7 +20,6 @@ use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; use crate::packages::http_tracker_core; -use crate::packages::http_tracker_core::services; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::extractors::scrape_request::ExtractRequest; @@ -111,12 +110,6 @@ async fn handle( build_response(scrape_data) } -/* code-review: authentication, authorization and peer IP resolution could be moved - from the handler (Axum) layer into the app layer `services::announce::invoke`. - That would make the handler even simpler and the code more reusable and decoupled from Axum. - See https://github.com/torrust/torrust-tracker/discussions/240. -*/ - #[allow(clippy::too_many_arguments)] async fn handle_scrape( core_config: &Arc, @@ -127,6 +120,8 @@ async fn handle_scrape( client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Result { + // todo: move authentication inside `http_tracker_core::services::scrape::handle_scrape` + // Authentication let return_real_scrape_data = if core_config.private { match maybe_key { @@ -140,25 +135,16 @@ async fn handle_scrape( true }; - // Authorization for scrape requests is handled at the `Tracker` level - // for each torrent. - - let peer_ip = match peer_ip_resolver::invoke(core_config.net.on_reverse_proxy, client_ip_sources) { - Ok(peer_ip) => peer_ip, - Err(error) => return Err(responses::error::Error::from(error)), - }; - - if return_real_scrape_data { - Ok(services::scrape::invoke( - scrape_handler, - opt_http_stats_event_sender, - &scrape_request.info_hashes, - &peer_ip, - ) - .await) - } else { - Ok(services::scrape::fake(opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await) - } + http_tracker_core::services::scrape::handle_scrape( + core_config, + scrape_handler, + authentication_service, + opt_http_stats_event_sender, + scrape_request, + client_ip_sources, + return_real_scrape_data, + ) + .await } fn build_response(scrape_data: ScrapeData) -> Response { From c0fc390409949ac11bde35095b58f81266d66e85 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Feb 2025 17:20:19 +0000 Subject: [PATCH 0756/1297] refactor: [#1268] move announce logic from udp server to udp_tracker_core package --- src/packages/udp_tracker_core/mod.rs | 1 + .../udp_tracker_core}/peer_builder.rs | 0 .../udp_tracker_core/services/announce.rs | 44 ++++++++++++++++++- src/servers/udp/handlers/announce.rs | 42 +++++++----------- src/servers/udp/mod.rs | 1 - 5 files changed, 60 insertions(+), 28 deletions(-) rename src/{servers/udp => packages/udp_tracker_core}/peer_builder.rs (100%) diff --git a/src/packages/udp_tracker_core/mod.rs b/src/packages/udp_tracker_core/mod.rs index 4f3e54857..3ab1d83dd 100644 --- a/src/packages/udp_tracker_core/mod.rs +++ b/src/packages/udp_tracker_core/mod.rs @@ -1,2 +1,3 @@ +pub mod peer_builder; pub mod services; pub mod statistics; diff --git a/src/servers/udp/peer_builder.rs b/src/packages/udp_tracker_core/peer_builder.rs similarity index 100% rename from src/servers/udp/peer_builder.rs rename to src/packages/udp_tracker_core/peer_builder.rs diff --git a/src/packages/udp_tracker_core/services/announce.rs b/src/packages/udp_tracker_core/services/announce.rs index 8a046a625..dec506aec 100644 --- a/src/packages/udp_tracker_core/services/announce.rs +++ b/src/packages/udp_tracker_core/services/announce.rs @@ -7,15 +7,55 @@ //! //! It also sends an [`udp_tracker_core::statistics::event::Event`] //! because events are specific for the HTTP tracker. -use std::net::IpAddr; +use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; +use aquatic_udp_protocol::AnnounceRequest; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; +use bittorrent_tracker_core::error::WhitelistError; +use bittorrent_tracker_core::whitelist; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; -use crate::packages::udp_tracker_core; +use crate::packages::udp_tracker_core::{self, peer_builder}; + +/// It handles the `Announce` request. +/// +/// # Errors +/// +/// It will return an error if: +/// +/// - The tracker is running in listed mode and the torrent is not in the +/// whitelist. +#[allow(clippy::too_many_arguments)] +pub async fn handle_announce( + remote_addr: SocketAddr, + request: &AnnounceRequest, + announce_handler: &Arc, + whitelist_authorization: &Arc, + opt_udp_stats_event_sender: &Arc>>, +) -> Result { + let info_hash = request.info_hash.into(); + let remote_client_ip = remote_addr.ip(); + + // Authorization + whitelist_authorization.authorize(&info_hash).await?; + + let mut peer = peer_builder::from_request(request, &remote_client_ip); + let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); + + let announce_data = invoke( + announce_handler.clone(), + opt_udp_stats_event_sender.clone(), + info_hash, + &mut peer, + &peers_wanted, + ) + .await; + + Ok(announce_data) +} pub async fn invoke( announce_handler: Arc, diff --git a/src/servers/udp/handlers/announce.rs b/src/servers/udp/handlers/announce.rs index 26a1a2116..2254ea979 100644 --- a/src/servers/udp/handlers/announce.rs +++ b/src/servers/udp/handlers/announce.rs @@ -8,17 +8,16 @@ use aquatic_udp_protocol::{ Port, Response, ResponsePeer, TransactionId, }; use bittorrent_primitives::info_hash::InfoHash; -use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; +use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; -use crate::packages::udp_tracker_core::{self, services}; +use crate::packages::udp_tracker_core::{self}; use crate::servers::udp::connection_cookie::check; use crate::servers::udp::error::Error; use crate::servers::udp::handlers::gen_remote_fingerprint; -use crate::servers::udp::peer_builder; /// It handles the `Announce` request. Refer to [`Announce`](crate::servers::udp#announce) /// request for more information. @@ -44,6 +43,8 @@ pub async fn handle_announce( tracing::trace!("handle announce"); + // todo: move authentication to `udp_tracker_core::services::announce::handle_announce` + check( &request.connection_id, gen_remote_fingerprint(&remote_addr), @@ -51,29 +52,20 @@ pub async fn handle_announce( ) .map_err(|e| (e, request.transaction_id))?; - let info_hash = request.info_hash.into(); - let remote_client_ip = remote_addr.ip(); - - // Authorization - whitelist_authorization - .authorize(&info_hash) - .await - .map_err(|e| Error::TrackerError { - source: (Arc::new(e) as Arc).into(), - }) - .map_err(|e| (e, request.transaction_id))?; - - let mut peer = peer_builder::from_request(request, &remote_client_ip); - let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); - - let response = services::announce::invoke( - announce_handler.clone(), - opt_udp_stats_event_sender.clone(), - info_hash, - &mut peer, - &peers_wanted, + let response = udp_tracker_core::services::announce::handle_announce( + remote_addr, + request, + announce_handler, + whitelist_authorization, + opt_udp_stats_event_sender, ) - .await; + .await + .map_err(|e| Error::TrackerError { + source: (Arc::new(e) as Arc).into(), + }) + .map_err(|e| (e, request.transaction_id))?; + + // todo: extract `build_response` function. #[allow(clippy::cast_possible_truncation)] if remote_addr.is_ipv4() { diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index b141cc322..e8410e5f0 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -640,7 +640,6 @@ use std::net::SocketAddr; pub mod connection_cookie; pub mod error; pub mod handlers; -pub mod peer_builder; pub mod server; pub const UDP_TRACKER_LOG_TARGET: &str = "UDP TRACKER"; From eca5c597a7624d2a5edfe52e042b84a8e76998ec Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Feb 2025 17:31:51 +0000 Subject: [PATCH 0757/1297] refactor: [#1268] move scrape logic from udp server to udp_tracker_core package --- .../udp_tracker_core/services/scrape.rs | 17 +++++++++++++++++ src/servers/udp/handlers/scrape.rs | 13 +++++-------- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/packages/udp_tracker_core/services/scrape.rs b/src/packages/udp_tracker_core/services/scrape.rs index 7d4897564..e47dd35b3 100644 --- a/src/packages/udp_tracker_core/services/scrape.rs +++ b/src/packages/udp_tracker_core/services/scrape.rs @@ -10,12 +10,29 @@ use std::net::SocketAddr; use std::sync::Arc; +use aquatic_udp_protocol::ScrapeRequest; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_primitives::core::ScrapeData; use crate::packages::udp_tracker_core; +/// It handles the `Scrape` request. +pub async fn handle_scrape( + remote_addr: SocketAddr, + request: &ScrapeRequest, + scrape_handler: &Arc, + opt_udp_stats_event_sender: &Arc>>, +) -> ScrapeData { + // Convert from aquatic infohashes + let mut info_hashes: Vec = vec![]; + for info_hash in &request.info_hashes { + info_hashes.push((*info_hash).into()); + } + + invoke(scrape_handler, opt_udp_stats_event_sender, &info_hashes, remote_addr).await +} + pub async fn invoke( scrape_handler: &Arc, opt_udp_stats_event_sender: &Arc>>, diff --git a/src/servers/udp/handlers/scrape.rs b/src/servers/udp/handlers/scrape.rs index 3b5ccf50d..d41563add 100644 --- a/src/servers/udp/handlers/scrape.rs +++ b/src/servers/udp/handlers/scrape.rs @@ -6,13 +6,11 @@ use std::sync::Arc; use aquatic_udp_protocol::{ NumberOfDownloads, NumberOfPeers, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; -use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; use crate::packages::udp_tracker_core; -use crate::packages::udp_tracker_core::services; use crate::servers::udp::connection_cookie::check; use crate::servers::udp::error::Error; use crate::servers::udp::handlers::gen_remote_fingerprint; @@ -37,6 +35,8 @@ pub async fn handle_scrape( tracing::trace!("handle scrape"); + // todo: move authentication to `udp_tracker_core::services::scrape::handle_scrape` + check( &request.connection_id, gen_remote_fingerprint(&remote_addr), @@ -44,13 +44,10 @@ pub async fn handle_scrape( ) .map_err(|e| (e, request.transaction_id))?; - // Convert from aquatic infohashes - let mut info_hashes: Vec = vec![]; - for info_hash in &request.info_hashes { - info_hashes.push((*info_hash).into()); - } + let scrape_data = + udp_tracker_core::services::scrape::handle_scrape(remote_addr, request, scrape_handler, opt_udp_stats_event_sender).await; - let scrape_data = services::scrape::invoke(scrape_handler, opt_udp_stats_event_sender, &info_hashes, remote_addr).await; + // todo: extract `build_response` function. let mut torrent_stats: Vec = Vec::new(); From e92a61e8070174d370ba964e50b2d99d15b4f32e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 14 Feb 2025 18:07:39 +0000 Subject: [PATCH 0758/1297] chore(deps): udpate dependencies ```output cargo update Updating crates.io index Locking 9 packages to latest compatible versions Updating cc v1.2.12 -> v1.2.14 Updating clap v4.5.28 -> v4.5.29 Updating clap_builder v4.5.27 -> v4.5.29 Updating cmake v0.1.53 -> v0.1.54 Updating miniz_oxide v0.8.3 -> v0.8.4 Updating ring v0.17.8 -> v0.17.9 Updating rustls v0.23.22 -> v0.23.23 Removing spin v0.9.8 Updating toml_edit v0.22.23 -> v0.22.24 Updating winnow v0.7.1 -> v0.7.2 ``` --- Cargo.lock | 49 +++++++++++++++++++++---------------------------- 1 file changed, 21 insertions(+), 28 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 408471efc..544ae8e0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -462,7 +462,7 @@ dependencies = [ "hyper", "hyper-util", "pin-project-lite", - "rustls 0.23.22", + "rustls 0.23.23", "rustls-pemfile", "rustls-pki-types", "tokio", @@ -868,9 +868,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.12" +version = "1.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "755717a7de9ec452bf7f3f1a3099085deabd7f2962b861dae91ecd7a365903d2" +checksum = "0c3d1b2e905a3a7b00a6141adb0e4c0bb941d11caf55349d863942a1cc44e3c9" dependencies = [ "jobserver", "libc", @@ -961,9 +961,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.28" +version = "4.5.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e77c3243bd94243c03672cb5154667347c457ca271254724f9f393aee1c05ff" +checksum = "8acebd8ad879283633b343856142139f2da2317c96b05b4dd6181c61e2480184" dependencies = [ "clap_builder", "clap_derive", @@ -971,9 +971,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.27" +version = "4.5.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b26884eb4b57140e4d2d93652abfa49498b938b3c9179f9fc487b0acc3edad7" +checksum = "f6ba32cbda51c7e1dfd49acc1457ba1a7dec5b64fe360e828acb13ca8dc9c2f9" dependencies = [ "anstream", "anstyle", @@ -1001,9 +1001,9 @@ checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" [[package]] name = "cmake" -version = "0.1.53" +version = "0.1.54" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e24a03c8b52922d68a1589ad61032f2c1aa5a8158d2aa0d93c6e9534944bbad6" +checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0" dependencies = [ "cc", ] @@ -1940,7 +1940,7 @@ dependencies = [ "http", "hyper", "hyper-util", - "rustls 0.23.22", + "rustls 0.23.23", "rustls-pki-types", "tokio", "tokio-rustls 0.26.1", @@ -2424,9 +2424,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8402cab7aefae129c6977bb0ff1b8fd9a04eb5b51efc50a70bea51cda0c7924" +checksum = "b3b1c9bd4fe1f0f8b387f6eb9eb3b4a1aa26185e5750efb9140301703f62cd1b" dependencies = [ "adler2", ] @@ -3339,15 +3339,14 @@ dependencies = [ [[package]] name = "ring" -version = "0.17.8" +version = "0.17.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" +checksum = "e75ec5e92c4d8aede845126adc388046234541629e76029599ed35a003c7ed24" dependencies = [ "cc", "cfg-if", "getrandom 0.2.15", "libc", - "spin", "untrusted", "windows-sys 0.52.0", ] @@ -3501,9 +3500,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.22" +version = "0.23.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb9263ab4eb695e42321db096e3b8fbd715a59b154d5c88d82db2175b681ba7" +checksum = "47796c98c480fce5406ef69d1c76378375492c3b0a0de587be0c1d9feb12f395" dependencies = [ "once_cell", "rustls-pki-types", @@ -3857,12 +3856,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "spin" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" - [[package]] name = "stable_deref_trait" version = "1.2.0" @@ -4232,7 +4225,7 @@ version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f6d0975eaace0cf0fcadee4e4aaa5da15b5c079146f2cffb67c113be122bf37" dependencies = [ - "rustls 0.23.22", + "rustls 0.23.23", "tokio", ] @@ -4283,9 +4276,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.23" +version = "0.22.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02a8b472d1a3d7c18e2d61a489aee3453fd9031c33e4f55bd533f4a7adca1bee" +checksum = "17b4795ff5edd201c7cd6dca065ae59972ce77d1b80fa0a84d94950ece7d1474" dependencies = [ "indexmap 2.7.1", "serde", @@ -5067,9 +5060,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86e376c75f4f43f44db463cf729e0d3acbf954d13e22c51e26e4c264b4ab545f" +checksum = "59690dea168f2198d1a3b0cac23b8063efcd11012f10ae4698f284808c8ef603" dependencies = [ "memchr", ] From 45e5ee40033e6cf27ce6a757f619c61241009416 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Sat, 15 Feb 2025 17:33:32 +0000 Subject: [PATCH 0759/1297] chore(deps): udpate dependencies ```output cargo update Updating crates.io index Locking 6 packages to latest compatible versions Updating equivalent v1.0.1 -> v1.0.2 Updating openssl v0.10.70 -> v0.10.71 Updating openssl-sys v0.9.105 -> v0.9.106 Updating smallvec v1.13.2 -> v1.14.0 Updating zerocopy v0.8.17 -> v0.8.18 Updating zerocopy-derive v0.8.17 -> v0.8.18 ``` --- Cargo.lock | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 544ae8e0d..06cde2457 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1367,9 +1367,9 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.1" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" @@ -2693,9 +2693,9 @@ checksum = "b410bbe7e14ab526a0e86877eb47c6996a2bd7746f027ba551028c925390e4e9" [[package]] name = "openssl" -version = "0.10.70" +version = "0.10.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61cfb4e166a8bb8c9b55c500bc2308550148ece889be90f609377e58140f42c6" +checksum = "5e14130c6a98cd258fdcb0fb6d744152343ff729cbfcb28c656a9d12b999fbcd" dependencies = [ "bitflags", "cfg-if", @@ -2725,9 +2725,9 @@ checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" [[package]] name = "openssl-sys" -version = "0.9.105" +version = "0.9.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b22d5b84be05a8d6947c7cb71f7c849aa0f112acd4bf51c2a7c1c988ac0a9dc" +checksum = "8bb61ea9811cc39e3c2069f40b8b8e2e70d8569b361f879786cc7ed48b777cdd" dependencies = [ "cc", "libc", @@ -3167,7 +3167,7 @@ checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.0", - "zerocopy 0.8.17", + "zerocopy 0.8.18", ] [[package]] @@ -3206,7 +3206,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b08f3c9802962f7e1b25113931d94f43ed9725bebc59db9d0c3e9a23b67e15ff" dependencies = [ "getrandom 0.3.1", - "zerocopy 0.8.17", + "zerocopy 0.8.18", ] [[package]] @@ -3842,9 +3842,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.13.2" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" +checksum = "7fcf8323ef1faaee30a44a340193b1ac6814fd9b7b4e88e9d4519a3e4abe1cfd" [[package]] name = "socket2" @@ -5139,11 +5139,11 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.17" +version = "0.8.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa91407dacce3a68c56de03abe2760159582b846c6a4acd2f456618087f12713" +checksum = "79386d31a42a4996e3336b0919ddb90f81112af416270cff95b5f5af22b839c2" dependencies = [ - "zerocopy-derive 0.8.17", + "zerocopy-derive 0.8.18", ] [[package]] @@ -5159,9 +5159,9 @@ dependencies = [ [[package]] name = "zerocopy-derive" -version = "0.8.17" +version = "0.8.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06718a168365cad3d5ff0bb133aad346959a2074bd4a85c121255a11304a8626" +checksum = "76331675d372f91bf8d17e13afbd5fe639200b73d01f0fc748bb059f9cca2db7" dependencies = [ "proc-macro2", "quote", From da1353bf1899f70e34360f43b87fe6338b801fa6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Feb 2025 09:54:49 +0000 Subject: [PATCH 0760/1297] refactor: [#1270] return errorin core announce and scrape handler - In the announce handler, it returns an error when the tracker is running in `listed` mode and the infohash is not whitelisted. This was done only in the delivery layers but not in the domain. - In the scrape handler, it does not return any errors for now, but It will allow us in the future to return errors whithout making breaking changes. --- .../http-protocol/src/v1/responses/error.rs | 18 ++- packages/tracker-core/src/announce_handler.rs | 153 +++++++++++------- packages/tracker-core/src/error.rs | 16 ++ packages/tracker-core/src/lib.rs | 58 +++---- packages/tracker-core/src/scrape_handler.rs | 17 +- packages/tracker-core/src/test_helpers.rs | 1 + packages/tracker-core/tests/integration.rs | 21 +-- src/bootstrap/app.rs | 1 + .../http_tracker_core/services/announce.rs | 37 ++++- .../http_tracker_core/services/scrape.rs | 39 +++-- .../udp_tracker_core/services/announce.rs | 17 +- .../udp_tracker_core/services/scrape.rs | 16 +- src/servers/http/v1/handlers/announce.rs | 3 +- src/servers/udp/handlers/announce.rs | 1 + src/servers/udp/handlers/mod.rs | 1 + src/servers/udp/handlers/scrape.rs | 7 +- 16 files changed, 271 insertions(+), 135 deletions(-) diff --git a/packages/http-protocol/src/v1/responses/error.rs b/packages/http-protocol/src/v1/responses/error.rs index 8a6b4cf55..2bd8cd95c 100644 --- a/packages/http-protocol/src/v1/responses/error.rs +++ b/packages/http-protocol/src/v1/responses/error.rs @@ -55,10 +55,26 @@ impl From for Error { } } +impl From for Error { + fn from(err: bittorrent_tracker_core::error::AnnounceError) -> Self { + Error { + failure_reason: format!("Tracker announce error: {err}"), + } + } +} + +impl From for Error { + fn from(err: bittorrent_tracker_core::error::ScrapeError) -> Self { + Error { + failure_reason: format!("Tracker scrape error: {err}"), + } + } +} + impl From for Error { fn from(err: bittorrent_tracker_core::error::WhitelistError) -> Self { Error { - failure_reason: format!("Tracker error: {err}"), + failure_reason: format!("Tracker whitelist error: {err}"), } } } diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 6707f1917..cd2073857 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -101,12 +101,17 @@ use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use super::torrent::repository::in_memory::InMemoryTorrentRepository; use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use crate::error::AnnounceError; +use crate::whitelist::authorization::WhitelistAuthorization; /// Handles `announce` requests from `BitTorrent` clients. pub struct AnnounceHandler { /// The tracker configuration. config: Core, + /// Service for authorizing access to whitelisted torrents. + whitelist_authorization: Arc, + /// Repository for in-memory torrent data. in_memory_torrent_repository: Arc, @@ -119,10 +124,12 @@ impl AnnounceHandler { #[must_use] pub fn new( config: &Core, + whitelist_authorization: &Arc, in_memory_torrent_repository: &Arc, db_torrent_repository: &Arc, ) -> Self { Self { + whitelist_authorization: whitelist_authorization.clone(), config: config.clone(), in_memory_torrent_repository: in_memory_torrent_repository.clone(), db_torrent_repository: db_torrent_repository.clone(), @@ -143,27 +150,23 @@ impl AnnounceHandler { /// # Returns /// /// An `AnnounceData` struct containing the list of peers, swarm statistics, and tracker policy. - pub fn announce( + /// + /// # Errors + /// + /// Returns an error if the tracker is running in `listed` mode and the + /// torrent is not whitelisted. + pub async fn announce( &self, info_hash: &InfoHash, peer: &mut peer::Peer, remote_client_ip: &IpAddr, peers_wanted: &PeersWanted, - ) -> AnnounceData { + ) -> Result { // code-review: maybe instead of mutating the peer we could just return // a tuple with the new peer and the announce data: (Peer, AnnounceData). // It could even be a different struct: `StoredPeer` or `PublicPeer`. - // code-review: in the `scrape` function we perform an authorization check. - // We check if the torrent is whitelisted. Should we also check authorization here? - // I think so because the `Tracker` has the responsibility for checking authentication and authorization. - // The `Tracker` has delegated that responsibility to the handlers - // (because we want to return a friendly error response) but that does not mean we should - // double-check authorization at this domain level too. - // I would propose to return a `Result` here. - // Besides, regarding authentication the `Tracker` is also responsible for authentication but - // we are actually handling authentication at the handlers level. So I would extract that - // responsibility into another authentication service. + self.whitelist_authorization.authorize(info_hash).await?; tracing::debug!("Before: {peer:?}"); peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); @@ -175,11 +178,11 @@ impl AnnounceHandler { .in_memory_torrent_repository .get_peers_for(info_hash, peer, peers_wanted.limit()); - AnnounceData { + Ok(AnnounceData { peers, stats, policy: self.config.announce_policy, - } + }) } /// Updates the torrent data in memory, persists statistics if needed, and @@ -461,8 +464,10 @@ mod tests { let mut peer = sample_peer(); - let announce_data = - announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); + let announce_data = announce_handler + .announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .await + .unwrap(); assert_eq!(announce_data.peers, vec![]); } @@ -472,16 +477,21 @@ mod tests { let (announce_handler, _scrape_handler) = public_tracker(); let mut previously_announced_peer = sample_peer_1(); - announce_handler.announce( - &sample_info_hash(), - &mut previously_announced_peer, - &peer_ip(), - &PeersWanted::AsManyAsPossible, - ); + announce_handler + .announce( + &sample_info_hash(), + &mut previously_announced_peer, + &peer_ip(), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); let mut peer = sample_peer_2(); - let announce_data = - announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); + let announce_data = announce_handler + .announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .await + .unwrap(); assert_eq!(announce_data.peers, vec![Arc::new(previously_announced_peer)]); } @@ -491,24 +501,32 @@ mod tests { let (announce_handler, _scrape_handler) = public_tracker(); let mut previously_announced_peer_1 = sample_peer_1(); - announce_handler.announce( - &sample_info_hash(), - &mut previously_announced_peer_1, - &peer_ip(), - &PeersWanted::AsManyAsPossible, - ); + announce_handler + .announce( + &sample_info_hash(), + &mut previously_announced_peer_1, + &peer_ip(), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); let mut previously_announced_peer_2 = sample_peer_2(); - announce_handler.announce( - &sample_info_hash(), - &mut previously_announced_peer_2, - &peer_ip(), - &PeersWanted::AsManyAsPossible, - ); + announce_handler + .announce( + &sample_info_hash(), + &mut previously_announced_peer_2, + &peer_ip(), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); let mut peer = sample_peer_3(); - let announce_data = - announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::only(1)); + let announce_data = announce_handler + .announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::only(1)) + .await + .unwrap(); // It should return only one peer. There is no guarantee on // which peer will be returned. @@ -530,8 +548,10 @@ mod tests { let mut peer = seeder(); - let announce_data = - announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); + let announce_data = announce_handler + .announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .await + .unwrap(); assert_eq!(announce_data.stats.complete, 1); } @@ -542,8 +562,10 @@ mod tests { let mut peer = leecher(); - let announce_data = - announce_handler.announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); + let announce_data = announce_handler + .announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .await + .unwrap(); assert_eq!(announce_data.stats.incomplete, 1); } @@ -554,20 +576,26 @@ mod tests { // We have to announce with "started" event because peer does not count if peer was not previously known let mut started_peer = started_peer(); - announce_handler.announce( - &sample_info_hash(), - &mut started_peer, - &peer_ip(), - &PeersWanted::AsManyAsPossible, - ); + announce_handler + .announce( + &sample_info_hash(), + &mut started_peer, + &peer_ip(), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); let mut completed_peer = completed_peer(); - let announce_data = announce_handler.announce( - &sample_info_hash(), - &mut completed_peer, - &peer_ip(), - &PeersWanted::AsManyAsPossible, - ); + let announce_data = announce_handler + .announce( + &sample_info_hash(), + &mut completed_peer, + &peer_ip(), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); assert_eq!(announce_data.stats.downloaded, 1); } @@ -590,10 +618,12 @@ mod tests { use crate::torrent::manager::TorrentsManager; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use crate::whitelist::authorization::WhitelistAuthorization; + use crate::whitelist::repository::in_memory::InMemoryWhitelist; #[tokio::test] async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { - let mut config = configuration::ephemeral_listed(); + let mut config = configuration::ephemeral_public(); config.core.tracker_policy.persistent_torrent_completed_stat = true; @@ -605,8 +635,11 @@ mod tests { &in_memory_torrent_repository, &db_torrent_repository, )); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, + &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); @@ -616,11 +649,17 @@ mod tests { let mut peer = sample_peer(); peer.event = AnnounceEvent::Started; - let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); + let announce_data = announce_handler + .announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .await + .unwrap(); assert_eq!(announce_data.stats.downloaded, 0); peer.event = AnnounceEvent::Completed; - let announce_data = announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); + let announce_data = announce_handler + .announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .await + .unwrap(); assert_eq!(announce_data.stats.downloaded, 1); // Remove the newly updated torrent from memory diff --git a/packages/tracker-core/src/error.rs b/packages/tracker-core/src/error.rs index 99ac48ed3..fed076ffa 100644 --- a/packages/tracker-core/src/error.rs +++ b/packages/tracker-core/src/error.rs @@ -15,6 +15,22 @@ use torrust_tracker_located_error::LocatedError; use super::authentication::key::ParseKeyError; use super::databases; +/// Errors related to announce requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum AnnounceError { + /// Wraps errors related to torrent whitelisting. + #[error("Whitelist error: {0}")] + Whitelist(#[from] WhitelistError), +} + +/// Errors related to scrape requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum ScrapeError { + /// Wraps errors related to torrent whitelisting. + #[error("Whitelist error: {0}")] + Whitelist(#[from] WhitelistError), +} + /// Errors related to torrent whitelisting. /// /// This error is returned when an operation involves a torrent that is not diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index 843817deb..8e73fe027 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -144,8 +144,6 @@ pub(crate) type CurrentClock = clock::Stopped; #[cfg(test)] mod tests { mod the_tracker { - use std::net::{IpAddr, Ipv4Addr}; - use std::str::FromStr; use std::sync::Arc; use torrust_tracker_test_helpers::configuration; @@ -164,11 +162,6 @@ mod tests { initialize_handlers(&config) } - // The client peer IP - fn peer_ip() -> IpAddr { - IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) - } - mod for_all_config_modes { mod handling_a_scrape_request { @@ -191,24 +184,30 @@ mod tests { // Announce a "complete" peer for the torrent let mut complete_peer = complete_peer(); - announce_handler.announce( - &info_hash, - &mut complete_peer, - &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10)), - &PeersWanted::AsManyAsPossible, - ); + announce_handler + .announce( + &info_hash, + &mut complete_peer, + &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10)), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); // Announce an "incomplete" peer for the torrent let mut incomplete_peer = incomplete_peer(); - announce_handler.announce( - &info_hash, - &mut incomplete_peer, - &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11)), - &PeersWanted::AsManyAsPossible, - ); + announce_handler + .announce( + &info_hash, + &mut incomplete_peer, + &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11)), + &PeersWanted::AsManyAsPossible, + ) + .await + .unwrap(); // Scrape - let scrape_data = scrape_handler.scrape(&vec![info_hash]).await; + let scrape_data = scrape_handler.scrape(&vec![info_hash]).await.unwrap(); // The expected swarm metadata for the file let mut expected_scrape_data = ScrapeData::empty(); @@ -234,28 +233,19 @@ mod tests { use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::announce_handler::PeersWanted; - use crate::test_helpers::tests::{complete_peer, incomplete_peer}; - use crate::tests::the_tracker::{initialize_handlers_for_listed_tracker, peer_ip}; + use crate::tests::the_tracker::initialize_handlers_for_listed_tracker; #[tokio::test] async fn it_should_return_the_zeroed_swarm_metadata_for_the_requested_file_if_it_is_not_whitelisted() { - let (announce_handler, scrape_handler) = initialize_handlers_for_listed_tracker(); - - let info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237 - - let mut peer = incomplete_peer(); - announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); + let (_announce_handler, scrape_handler) = initialize_handlers_for_listed_tracker(); - // Announce twice to force non zeroed swarm metadata - let mut peer = complete_peer(); - announce_handler.announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible); + let non_whitelisted_info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237 - let scrape_data = scrape_handler.scrape(&vec![info_hash]).await; + let scrape_data = scrape_handler.scrape(&vec![non_whitelisted_info_hash]).await.unwrap(); // The expected zeroed swarm metadata for the file let mut expected_scrape_data = ScrapeData::empty(); - expected_scrape_data.add_file(&info_hash, SwarmMetadata::zeroed()); + expected_scrape_data.add_file(&non_whitelisted_info_hash, SwarmMetadata::zeroed()); assert_eq!(scrape_data, expected_scrape_data); } diff --git a/packages/tracker-core/src/scrape_handler.rs b/packages/tracker-core/src/scrape_handler.rs index 1e75580ab..93b25dea6 100644 --- a/packages/tracker-core/src/scrape_handler.rs +++ b/packages/tracker-core/src/scrape_handler.rs @@ -67,6 +67,7 @@ use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use super::torrent::repository::in_memory::InMemoryTorrentRepository; use super::whitelist; +use crate::error::ScrapeError; /// Handles scrape requests, providing torrent swarm metadata. pub struct ScrapeHandler { @@ -95,10 +96,18 @@ impl ScrapeHandler { /// - Returns metadata for each requested torrent. /// - If a torrent isn't whitelisted or doesn't exist, returns zeroed stats. /// + /// # Errors + /// + /// It does not return any errors for the time being. The error is returned + /// to avoid breaking changes in the future if we decide to return errors. + /// For example, a new tracker configuration option could be added to return + /// an error if a torrent is not whitelisted instead of returning zeroed + /// stats. + /// /// # BEP Reference: /// /// [BEP 48: Scrape Protocol](https://www.bittorrent.org/beps/bep_0048.html) - pub async fn scrape(&self, info_hashes: &Vec) -> ScrapeData { + pub async fn scrape(&self, info_hashes: &Vec) -> Result { let mut scrape_data = ScrapeData::empty(); for info_hash in info_hashes { @@ -109,7 +118,7 @@ impl ScrapeHandler { scrape_data.add_file(info_hash, swarm_metadata); } - scrape_data + Ok(scrape_data) } } @@ -145,7 +154,7 @@ mod tests { let info_hashes = vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()]; // DevSkim: ignore DS173237 - let scrape_data = scrape_handler.scrape(&info_hashes).await; + let scrape_data = scrape_handler.scrape(&info_hashes).await.unwrap(); let mut expected_scrape_data = ScrapeData::empty(); @@ -163,7 +172,7 @@ mod tests { "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1".parse::().unwrap(), // DevSkim: ignore DS173237 ]; - let scrape_data = scrape_handler.scrape(&info_hashes).await; + let scrape_data = scrape_handler.scrape(&info_hashes).await.unwrap(); let mut expected_scrape_data = ScrapeData::empty(); expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[0]); diff --git a/packages/tracker-core/src/test_helpers.rs b/packages/tracker-core/src/test_helpers.rs index 06f5ce384..79904dec2 100644 --- a/packages/tracker-core/src/test_helpers.rs +++ b/packages/tracker-core/src/test_helpers.rs @@ -177,6 +177,7 @@ pub(crate) mod tests { let announce_handler = Arc::new(AnnounceHandler::new( &config.core, + &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); diff --git a/packages/tracker-core/tests/integration.rs b/packages/tracker-core/tests/integration.rs index 4dbd60b9e..5aaded10a 100644 --- a/packages/tracker-core/tests/integration.rs +++ b/packages/tracker-core/tests/integration.rs @@ -76,6 +76,7 @@ impl Container { )); let announce_handler = Arc::new(AnnounceHandler::new( config, + &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); @@ -102,10 +103,11 @@ async fn test_announce_and_scrape_requests() { // First announce: download started peer.event = AnnounceEvent::Started; - let announce_data = - container - .announce_handler - .announce(&info_hash, &mut peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible); + let announce_data = container + .announce_handler + .announce(&info_hash, &mut peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible) + .await + .unwrap(); // NOTICE: you don't get back the peer making the request. assert_eq!(announce_data.peers.len(), 0); @@ -113,17 +115,18 @@ async fn test_announce_and_scrape_requests() { // Second announce: download completed peer.event = AnnounceEvent::Completed; - let announce_data = - container - .announce_handler - .announce(&info_hash, &mut peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible); + let announce_data = container + .announce_handler + .announce(&info_hash, &mut peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible) + .await + .unwrap(); assert_eq!(announce_data.peers.len(), 0); assert_eq!(announce_data.stats.downloaded, 1); // Scrape - let scrape_data = container.scrape_handler.scrape(&vec![info_hash]).await; + let scrape_data = container.scrape_handler.scrape(&vec![info_hash]).await.unwrap(); assert!(scrape_data.files.contains_key(&info_hash)); } diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index e0d77ab8a..41023f2fa 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -129,6 +129,7 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let announce_handler = Arc::new(AnnounceHandler::new( &configuration.core, + &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); diff --git a/src/packages/http_tracker_core/services/announce.rs b/src/packages/http_tracker_core/services/announce.rs index 049d0d228..3b4edea4e 100644 --- a/src/packages/http_tracker_core/services/announce.rs +++ b/src/packages/http_tracker_core/services/announce.rs @@ -16,6 +16,7 @@ use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSou use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::error::AnnounceError; use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; @@ -75,22 +76,28 @@ pub async fn handle_announce( &mut peer, &peers_wanted, ) - .await; + .await + .map_err(responses::error::Error::from)?; Ok(announce_data) } +/// # Errors +/// +/// This function will return an error if the announce requests failed. pub async fn invoke( announce_handler: Arc, opt_http_stats_event_sender: Arc>>, info_hash: InfoHash, peer: &mut peer::Peer, peers_wanted: &PeersWanted, -) -> AnnounceData { +) -> Result { let original_peer_ip = peer.peer_addr.ip(); // The tracker could change the original peer ip - let announce_data = announce_handler.announce(&info_hash, peer, &original_peer_ip, peers_wanted); + let announce_data = announce_handler + .announce(&info_hash, peer, &original_peer_ip, peers_wanted) + .await?; if let Some(http_stats_event_sender) = opt_http_stats_event_sender.as_deref() { match original_peer_ip { @@ -107,7 +114,7 @@ pub async fn invoke( } } - announce_data + Ok(announce_data) } #[cfg(test)] @@ -120,6 +127,8 @@ mod tests { use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; @@ -140,9 +149,12 @@ mod tests { let database = initialize_database(&config.core); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, + &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); @@ -209,6 +221,8 @@ mod tests { use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use mockall::predicate::eq; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; @@ -229,9 +243,12 @@ mod tests { let database = initialize_database(&config.core); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); Arc::new(AnnounceHandler::new( &config.core, + &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )) @@ -250,7 +267,8 @@ mod tests { &mut peer, &PeersWanted::AsManyAsPossible, ) - .await; + .await + .unwrap(); let expected_announce_data = AnnounceData { peers: vec![], @@ -287,7 +305,8 @@ mod tests { &mut peer, &PeersWanted::AsManyAsPossible, ) - .await; + .await + .unwrap(); } fn tracker_with_an_ipv6_external_ip() -> Arc { @@ -332,7 +351,8 @@ mod tests { &mut peer, &PeersWanted::AsManyAsPossible, ) - .await; + .await + .unwrap(); } #[tokio::test] @@ -358,7 +378,8 @@ mod tests { &mut peer, &PeersWanted::AsManyAsPossible, ) - .await; + .await + .unwrap(); } } } diff --git a/src/packages/http_tracker_core/services/scrape.rs b/src/packages/http_tracker_core/services/scrape.rs index 62f5fdf62..467c69f51 100644 --- a/src/packages/http_tracker_core/services/scrape.rs +++ b/src/packages/http_tracker_core/services/scrape.rs @@ -15,6 +15,7 @@ use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::error::ScrapeError; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; @@ -56,29 +57,34 @@ pub async fn handle_scrape( }; if return_real_scrape_data { - Ok(invoke( + let scrape_data = invoke( scrape_handler, opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip, ) - .await) + .await?; + + Ok(scrape_data) } else { Ok(http_tracker_core::services::scrape::fake(opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await) } } +/// # Errors +/// +/// This function will return an error if the tracker core scrape handler fails. pub async fn invoke( scrape_handler: &Arc, opt_http_stats_event_sender: &Arc>>, info_hashes: &Vec, original_peer_ip: &IpAddr, -) -> ScrapeData { - let scrape_data = scrape_handler.scrape(info_hashes).await; +) -> Result { + let scrape_data = scrape_handler.scrape(info_hashes).await?; send_scrape_event(original_peer_ip, opt_http_stats_event_sender).await; - scrape_data + Ok(scrape_data) } /// The HTTP tracker fake `scrape` service. It returns zeroed stats. @@ -151,6 +157,7 @@ mod tests { let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, + &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); @@ -225,9 +232,14 @@ mod tests { // Announce a new peer to force scrape data to contain not zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); - announce_handler.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible); + announce_handler + .announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible) + .await + .unwrap(); - let scrape_data = invoke(&scrape_handler, &http_stats_event_sender, &info_hashes, &original_peer_ip).await; + let scrape_data = invoke(&scrape_handler, &http_stats_event_sender, &info_hashes, &original_peer_ip) + .await + .unwrap(); let mut expected_scrape_data = ScrapeData::empty(); expected_scrape_data.add_file( @@ -257,7 +269,9 @@ mod tests { let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); - invoke(&scrape_handler, &http_stats_event_sender, &sample_info_hashes(), &peer_ip).await; + invoke(&scrape_handler, &http_stats_event_sender, &sample_info_hashes(), &peer_ip) + .await + .unwrap(); } #[tokio::test] @@ -275,7 +289,9 @@ mod tests { let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); - invoke(&scrape_handler, &http_stats_event_sender, &sample_info_hashes(), &peer_ip).await; + invoke(&scrape_handler, &http_stats_event_sender, &sample_info_hashes(), &peer_ip) + .await + .unwrap(); } } @@ -310,7 +326,10 @@ mod tests { // Announce a new peer to force scrape data to contain not zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); - announce_handler.announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible); + announce_handler + .announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible) + .await + .unwrap(); let scrape_data = fake(&http_stats_event_sender, &info_hashes, &original_peer_ip).await; diff --git a/src/packages/udp_tracker_core/services/announce.rs b/src/packages/udp_tracker_core/services/announce.rs index dec506aec..29725c6d4 100644 --- a/src/packages/udp_tracker_core/services/announce.rs +++ b/src/packages/udp_tracker_core/services/announce.rs @@ -13,7 +13,7 @@ use std::sync::Arc; use aquatic_udp_protocol::AnnounceRequest; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; -use bittorrent_tracker_core::error::WhitelistError; +use bittorrent_tracker_core::error::AnnounceError; use bittorrent_tracker_core::whitelist; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; @@ -35,7 +35,7 @@ pub async fn handle_announce( announce_handler: &Arc, whitelist_authorization: &Arc, opt_udp_stats_event_sender: &Arc>>, -) -> Result { +) -> Result { let info_hash = request.info_hash.into(); let remote_client_ip = remote_addr.ip(); @@ -52,22 +52,27 @@ pub async fn handle_announce( &mut peer, &peers_wanted, ) - .await; + .await?; Ok(announce_data) } +/// # Errors +/// +/// It will return an error if the announce request fails. pub async fn invoke( announce_handler: Arc, opt_udp_stats_event_sender: Arc>>, info_hash: InfoHash, peer: &mut peer::Peer, peers_wanted: &PeersWanted, -) -> AnnounceData { +) -> Result { let original_peer_ip = peer.peer_addr.ip(); // The tracker could change the original peer ip - let announce_data = announce_handler.announce(&info_hash, peer, &original_peer_ip, peers_wanted); + let announce_data = announce_handler + .announce(&info_hash, peer, &original_peer_ip, peers_wanted) + .await?; if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { match original_peer_ip { @@ -84,5 +89,5 @@ pub async fn invoke( } } - announce_data + Ok(announce_data) } diff --git a/src/packages/udp_tracker_core/services/scrape.rs b/src/packages/udp_tracker_core/services/scrape.rs index e47dd35b3..e7608928c 100644 --- a/src/packages/udp_tracker_core/services/scrape.rs +++ b/src/packages/udp_tracker_core/services/scrape.rs @@ -12,18 +12,23 @@ use std::sync::Arc; use aquatic_udp_protocol::ScrapeRequest; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::error::ScrapeError; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_primitives::core::ScrapeData; use crate::packages::udp_tracker_core; /// It handles the `Scrape` request. +/// +/// # Errors +/// +/// It will return an error if the tracker core scrape handler returns an error. pub async fn handle_scrape( remote_addr: SocketAddr, request: &ScrapeRequest, scrape_handler: &Arc, opt_udp_stats_event_sender: &Arc>>, -) -> ScrapeData { +) -> Result { // Convert from aquatic infohashes let mut info_hashes: Vec = vec![]; for info_hash in &request.info_hashes { @@ -33,13 +38,16 @@ pub async fn handle_scrape( invoke(scrape_handler, opt_udp_stats_event_sender, &info_hashes, remote_addr).await } +/// # Errors +/// +/// It will return an error if the tracker core scrape handler returns an error. pub async fn invoke( scrape_handler: &Arc, opt_udp_stats_event_sender: &Arc>>, info_hashes: &Vec, remote_addr: SocketAddr, -) -> ScrapeData { - let scrape_data = scrape_handler.scrape(info_hashes).await; +) -> Result { + let scrape_data = scrape_handler.scrape(info_hashes).await?; if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { match remote_addr { @@ -56,5 +64,5 @@ pub async fn invoke( } } - scrape_data + Ok(scrape_data) } diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 977e7dd6a..5f25c317b 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -260,6 +260,7 @@ mod tests { let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, + &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); @@ -397,7 +398,7 @@ mod tests { assert_error_response( &response, &format!( - "Tracker error: The torrent: {}, is not whitelisted", + "Tracker whitelist error: The torrent: {}, is not whitelisted", announce_request.info_hash ), ); diff --git a/src/servers/udp/handlers/announce.rs b/src/servers/udp/handlers/announce.rs index 2254ea979..abae9651d 100644 --- a/src/servers/udp/handlers/announce.rs +++ b/src/servers/udp/handlers/announce.rs @@ -802,6 +802,7 @@ mod tests { let announce_handler = Arc::new(AnnounceHandler::new( &config.core, + &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); diff --git a/src/servers/udp/handlers/mod.rs b/src/servers/udp/handlers/mod.rs index 252a5be02..c2fabe87a 100644 --- a/src/servers/udp/handlers/mod.rs +++ b/src/servers/udp/handlers/mod.rs @@ -242,6 +242,7 @@ pub(crate) mod tests { let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, + &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); diff --git a/src/servers/udp/handlers/scrape.rs b/src/servers/udp/handlers/scrape.rs index d41563add..2b03e0dc7 100644 --- a/src/servers/udp/handlers/scrape.rs +++ b/src/servers/udp/handlers/scrape.rs @@ -45,7 +45,12 @@ pub async fn handle_scrape( .map_err(|e| (e, request.transaction_id))?; let scrape_data = - udp_tracker_core::services::scrape::handle_scrape(remote_addr, request, scrape_handler, opt_udp_stats_event_sender).await; + udp_tracker_core::services::scrape::handle_scrape(remote_addr, request, scrape_handler, opt_udp_stats_event_sender) + .await + .map_err(|e| Error::TrackerError { + source: (Arc::new(e) as Arc).into(), + }) + .map_err(|e| (e, request.transaction_id))?; // todo: extract `build_response` function. From dbee7ad3a103624a47f5b3b917961d1741a5cd4d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Feb 2025 11:28:31 +0000 Subject: [PATCH 0761/1297] refactor: [#1270] extract fn to new package udp-protocol --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 10 + Cargo.toml | 1 + packages/udp-protocol/Cargo.toml | 20 + packages/udp-protocol/LICENSE | 661 ++++++++++++++++++ packages/udp-protocol/README.md | 11 + packages/udp-protocol/src/lib.rs | 15 + .../udp-protocol/src}/peer_builder.rs | 0 src/packages/udp_tracker_core/mod.rs | 1 - .../udp_tracker_core/services/announce.rs | 3 +- src/servers/udp/handlers/announce.rs | 3 + src/servers/udp/handlers/mod.rs | 8 +- 12 files changed, 731 insertions(+), 3 deletions(-) create mode 100644 packages/udp-protocol/Cargo.toml create mode 100644 packages/udp-protocol/LICENSE create mode 100644 packages/udp-protocol/README.md create mode 100644 packages/udp-protocol/src/lib.rs rename {src/packages/udp_tracker_core => packages/udp-protocol/src}/peer_builder.rs (100%) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 41b40feaa..328bd91bb 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -58,6 +58,7 @@ jobs: cargo publish -p bittorrent-http-protocol cargo publish -p bittorrent-tracker-client cargo publish -p bittorrent-tracker-core + cargo publish -p bittorrent-udp-protocol cargo publish -p torrust-tracker cargo publish -p torrust-tracker-api-client cargo publish -p torrust-tracker-client diff --git a/Cargo.lock b/Cargo.lock index 06cde2457..07c08ab04 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -634,6 +634,15 @@ dependencies = [ "url", ] +[[package]] +name = "bittorrent-udp-protocol" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "torrust-tracker-clock", + "torrust-tracker-primitives", +] + [[package]] name = "bitvec" version = "1.0.1" @@ -4301,6 +4310,7 @@ dependencies = [ "bittorrent-primitives", "bittorrent-tracker-client", "bittorrent-tracker-core", + "bittorrent-udp-protocol", "bloom", "blowfish", "camino", diff --git a/Cargo.toml b/Cargo.toml index 6c9f7f22d..7337b49af 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,7 @@ bittorrent-http-protocol = { version = "3.0.0-develop", path = "packages/http-pr bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker-core" } +bittorrent-udp-protocol = { version = "3.0.0-develop", path = "packages/udp-protocol" } bloom = "0.3.2" blowfish = "0" camino = { version = "1", features = ["serde", "serde1"] } diff --git a/packages/udp-protocol/Cargo.toml b/packages/udp-protocol/Cargo.toml new file mode 100644 index 000000000..8f0f9fe98 --- /dev/null +++ b/packages/udp-protocol/Cargo.toml @@ -0,0 +1,20 @@ +[package] +description = "A library with the primitive types and functions for the BitTorrent UDP tracker protocol." +keywords = ["bittorrent", "library", "primitives", "udp"] +name = "bittorrent-udp-protocol" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } diff --git a/packages/udp-protocol/LICENSE b/packages/udp-protocol/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/udp-protocol/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/udp-protocol/README.md b/packages/udp-protocol/README.md new file mode 100644 index 000000000..4f63fb675 --- /dev/null +++ b/packages/udp-protocol/README.md @@ -0,0 +1,11 @@ +# BitTorrent UDP Tracker Protocol + +A library with the primitive types and functions used by BitTorrent UDP trackers. + +## Documentation + +[Crate documentation](https://docs.rs/bittorrent-udp-protocol). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/udp-protocol/src/lib.rs b/packages/udp-protocol/src/lib.rs new file mode 100644 index 000000000..f0983a7ba --- /dev/null +++ b/packages/udp-protocol/src/lib.rs @@ -0,0 +1,15 @@ +//! Primitive types and functions for `BitTorrent` UDP trackers. +pub mod peer_builder; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/src/packages/udp_tracker_core/peer_builder.rs b/packages/udp-protocol/src/peer_builder.rs similarity index 100% rename from src/packages/udp_tracker_core/peer_builder.rs rename to packages/udp-protocol/src/peer_builder.rs diff --git a/src/packages/udp_tracker_core/mod.rs b/src/packages/udp_tracker_core/mod.rs index 3ab1d83dd..4f3e54857 100644 --- a/src/packages/udp_tracker_core/mod.rs +++ b/src/packages/udp_tracker_core/mod.rs @@ -1,3 +1,2 @@ -pub mod peer_builder; pub mod services; pub mod statistics; diff --git a/src/packages/udp_tracker_core/services/announce.rs b/src/packages/udp_tracker_core/services/announce.rs index 29725c6d4..db90d445f 100644 --- a/src/packages/udp_tracker_core/services/announce.rs +++ b/src/packages/udp_tracker_core/services/announce.rs @@ -15,10 +15,11 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::error::AnnounceError; use bittorrent_tracker_core::whitelist; +use bittorrent_udp_protocol::peer_builder; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; -use crate::packages::udp_tracker_core::{self, peer_builder}; +use crate::packages::udp_tracker_core::{self}; /// It handles the `Announce` request. /// diff --git a/src/servers/udp/handlers/announce.rs b/src/servers/udp/handlers/announce.rs index abae9651d..a273a2ecb 100644 --- a/src/servers/udp/handlers/announce.rs +++ b/src/servers/udp/handlers/announce.rs @@ -261,6 +261,7 @@ mod tests { let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip), client_port)) + .updated_on(peers[0].updated) .into(); assert_eq!(peers[0], Arc::new(expected_peer)); @@ -495,6 +496,7 @@ mod tests { let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) .with_peer_address(SocketAddr::new(external_ip_in_tracker_configuration, client_port)) + .updated_on(peers[0].updated) .into(); assert_eq!(peers[0], Arc::new(expected_peer)); @@ -567,6 +569,7 @@ mod tests { let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) + .updated_on(peers[0].updated) .into(); assert_eq!(peers[0], Arc::new(expected_peer)); diff --git a/src/servers/udp/handlers/mod.rs b/src/servers/udp/handlers/mod.rs index c2fabe87a..f9f8edae7 100644 --- a/src/servers/udp/handlers/mod.rs +++ b/src/servers/udp/handlers/mod.rs @@ -196,7 +196,7 @@ pub(crate) mod tests { use tokio::sync::mpsc::error::SendError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{Configuration, Core}; - use torrust_tracker_primitives::peer; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; use super::gen_remote_fingerprint; @@ -330,6 +330,12 @@ pub(crate) mod tests { self } + #[must_use] + pub fn updated_on(mut self, updated: DurationSinceUnixEpoch) -> Self { + self.peer.updated = updated; + self + } + #[must_use] pub fn into(self) -> peer::Peer { self.peer From 096d5032d7f47a0a5202f136ba79e87fb3623dad Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Feb 2025 12:07:37 +0000 Subject: [PATCH 0762/1297] refactor: [#1270] inline http tracker announce invoke fn --- .../http-protocol/src/v1/requests/announce.rs | 11 ++ .../http_tracker_core/services/announce.rs | 184 +++++++++--------- 2 files changed, 106 insertions(+), 89 deletions(-) diff --git a/packages/http-protocol/src/v1/requests/announce.rs b/packages/http-protocol/src/v1/requests/announce.rs index f293b9cf5..66f7a1227 100644 --- a/packages/http-protocol/src/v1/requests/announce.rs +++ b/packages/http-protocol/src/v1/requests/announce.rs @@ -183,6 +183,17 @@ impl fmt::Display for Event { } } +impl From for Event { + fn from(value: aquatic_udp_protocol::request::AnnounceEvent) -> Self { + match value { + AnnounceEvent::Started => Self::Started, + AnnounceEvent::Stopped => Self::Stopped, + AnnounceEvent::Completed => Self::Completed, + AnnounceEvent::None => panic!("can't convert announce event from aquatic for None variant"), + } + } +} + /// Whether the `announce` response should be in compact mode or not. /// /// Depending on the value of this param, the tracker will return a different diff --git a/src/packages/http_tracker_core/services/announce.rs b/src/packages/http_tracker_core/services/announce.rs index 3b4edea4e..2bc421f1d 100644 --- a/src/packages/http_tracker_core/services/announce.rs +++ b/src/packages/http_tracker_core/services/announce.rs @@ -13,14 +13,11 @@ use std::sync::Arc; use bittorrent_http_protocol::v1::requests::announce::{peer_from_request, Announce}; use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; -use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::authentication::service::AuthenticationService; -use bittorrent_tracker_core::error::AnnounceError; use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; -use torrust_tracker_primitives::peer; use crate::packages::http_tracker_core; @@ -69,34 +66,11 @@ pub async fn handle_announce( None => PeersWanted::AsManyAsPossible, }; - let announce_data = invoke( - announce_handler.clone(), - opt_http_stats_event_sender.clone(), - announce_request.info_hash, - &mut peer, - &peers_wanted, - ) - .await - .map_err(responses::error::Error::from)?; - - Ok(announce_data) -} - -/// # Errors -/// -/// This function will return an error if the announce requests failed. -pub async fn invoke( - announce_handler: Arc, - opt_http_stats_event_sender: Arc>>, - info_hash: InfoHash, - peer: &mut peer::Peer, - peers_wanted: &PeersWanted, -) -> Result { let original_peer_ip = peer.peer_addr.ip(); // The tracker could change the original peer ip let announce_data = announce_handler - .announce(&info_hash, peer, &original_peer_ip, peers_wanted) + .announce(&announce_request.info_hash, &mut peer, &original_peer_ip, &peers_wanted) .await?; if let Some(http_stats_event_sender) = opt_http_stats_event_sender.as_deref() { @@ -123,19 +97,26 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_http_protocol::v1::requests::announce::Announce; + use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; - use torrust_tracker_configuration::Core; + use torrust_tracker_configuration::{Configuration, Core}; + use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; struct CoreTrackerServices { pub core_config: Arc, pub announce_handler: Arc, + pub authentication_service: Arc, + pub whitelist_authorization: Arc, } struct CoreHttpTrackerServices { @@ -143,14 +124,18 @@ mod tests { } fn initialize_core_tracker_services() -> (CoreTrackerServices, CoreHttpTrackerServices) { - let config = configuration::ephemeral_public(); + initialize_core_tracker_services_with_config(&configuration::ephemeral_public()) + } + fn initialize_core_tracker_services_with_config(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) { let core_config = Arc::new(config.core.clone()); let database = initialize_database(&config.core); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&core_config, &in_memory_key_repository)); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, @@ -169,6 +154,8 @@ mod tests { CoreTrackerServices { core_config, announce_handler, + authentication_service, + whitelist_authorization, }, CoreHttpTrackerServices { http_stats_event_sender }, ) @@ -199,11 +186,33 @@ mod tests { } } + fn sample_announce_request_for_peer(peer: Peer) -> (Announce, ClientIpSources) { + let announce_request = Announce { + info_hash: sample_info_hash(), + peer_id: peer.peer_id, + port: peer.peer_addr.port(), + uploaded: Some(peer.uploaded), + downloaded: Some(peer.downloaded), + left: Some(peer.left), + event: Some(peer.event.into()), + compact: None, + numwant: None, + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_ip: Some(peer.peer_addr.ip()), + }; + + (announce_request, client_ip_sources) + } + use futures::future::BoxFuture; use mockall::mock; use tokio::sync::mpsc::error::SendError; use crate::packages::http_tracker_core; + use crate::servers::http::test_helpers::tests::sample_info_hash; mock! { HttpStatsEventSender {} @@ -217,13 +226,8 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; - use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; - use bittorrent_tracker_core::databases::setup::initialize_database; - use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; - use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use mockall::predicate::eq; + use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; @@ -231,41 +235,28 @@ mod tests { use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; use crate::packages::http_tracker_core; - use crate::packages::http_tracker_core::services::announce::invoke; + use crate::packages::http_tracker_core::services::announce::handle_announce; use crate::packages::http_tracker_core::services::announce::tests::{ - initialize_core_tracker_services, sample_peer, MockHttpStatsEventSender, + initialize_core_tracker_services, initialize_core_tracker_services_with_config, sample_announce_request_for_peer, + sample_peer, MockHttpStatsEventSender, }; - use crate::servers::http::test_helpers::tests::sample_info_hash; - - fn initialize_announce_handler() -> Arc { - let config = configuration::ephemeral(); - - let database = initialize_database(&config.core); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); - - Arc::new(AnnounceHandler::new( - &config.core, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - )) - } #[tokio::test] async fn it_should_return_the_announce_data() { let (core_tracker_services, core_http_tracker_services) = initialize_core_tracker_services(); - let mut peer = sample_peer(); + let peer = sample_peer(); - let announce_data = invoke( - core_tracker_services.announce_handler.clone(), - core_http_tracker_services.http_stats_event_sender.clone(), - sample_info_hash(), - &mut peer, - &PeersWanted::AsManyAsPossible, + let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); + + let announce_data = handle_announce( + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.whitelist_authorization, + &core_http_tracker_services.http_stats_event_sender, + &announce_request, + &client_ip_sources, ) .await .unwrap(); @@ -294,28 +285,32 @@ mod tests { let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); - let announce_handler = initialize_announce_handler(); + let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services(); + core_http_tracker_services.http_stats_event_sender = http_stats_event_sender; - let mut peer = sample_peer_using_ipv4(); + let peer = sample_peer_using_ipv4(); - let _announce_data = invoke( - announce_handler, - http_stats_event_sender, - sample_info_hash(), - &mut peer, - &PeersWanted::AsManyAsPossible, + let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); + + let _announce_data = handle_announce( + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.whitelist_authorization, + &core_http_tracker_services.http_stats_event_sender, + &announce_request, + &client_ip_sources, ) .await .unwrap(); } - fn tracker_with_an_ipv6_external_ip() -> Arc { + fn tracker_with_an_ipv6_external_ip() -> Configuration { let mut configuration = configuration::ephemeral(); configuration.core.net.external_ip = Some(IpAddr::V6(Ipv6Addr::new( 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, ))); - - initialize_announce_handler() + configuration } fn peer_with_the_ipv4_loopback_ip() -> peer::Peer { @@ -340,16 +335,22 @@ mod tests { let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); - let mut peer = peer_with_the_ipv4_loopback_ip(); + let (core_tracker_services, mut core_http_tracker_services) = + initialize_core_tracker_services_with_config(&tracker_with_an_ipv6_external_ip()); + core_http_tracker_services.http_stats_event_sender = http_stats_event_sender; - let announce_handler = tracker_with_an_ipv6_external_ip(); + let peer = peer_with_the_ipv4_loopback_ip(); - let _announce_data = invoke( - announce_handler, - http_stats_event_sender, - sample_info_hash(), - &mut peer, - &PeersWanted::AsManyAsPossible, + let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); + + let _announce_data = handle_announce( + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.whitelist_authorization, + &core_http_tracker_services.http_stats_event_sender, + &announce_request, + &client_ip_sources, ) .await .unwrap(); @@ -367,16 +368,21 @@ mod tests { let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); - let announce_handler = initialize_announce_handler(); + let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services(); + core_http_tracker_services.http_stats_event_sender = http_stats_event_sender; - let mut peer = sample_peer_using_ipv6(); + let peer = sample_peer_using_ipv6(); - let _announce_data = invoke( - announce_handler, - http_stats_event_sender, - sample_info_hash(), - &mut peer, - &PeersWanted::AsManyAsPossible, + let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); + + let _announce_data = handle_announce( + &core_tracker_services.core_config, + &core_tracker_services.announce_handler, + &core_tracker_services.authentication_service, + &core_tracker_services.whitelist_authorization, + &core_http_tracker_services.http_stats_event_sender, + &announce_request, + &client_ip_sources, ) .await .unwrap(); From 6651343ef98c0c15c813a85fbe7e25ecf3652e81 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Feb 2025 15:54:03 +0000 Subject: [PATCH 0763/1297] refactor: [#1270] inline http tracker scrape invoke fn --- .../http_tracker_core/services/scrape.rs | 138 +++++++++++------- src/servers/http/v1/handlers/scrape.rs | 13 +- 2 files changed, 95 insertions(+), 56 deletions(-) diff --git a/src/packages/http_tracker_core/services/scrape.rs b/src/packages/http_tracker_core/services/scrape.rs index 467c69f51..667ce8d0d 100644 --- a/src/packages/http_tracker_core/services/scrape.rs +++ b/src/packages/http_tracker_core/services/scrape.rs @@ -14,8 +14,6 @@ use bittorrent_http_protocol::v1::requests::scrape::Scrape; use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; use bittorrent_primitives::info_hash::InfoHash; -use bittorrent_tracker_core::authentication::service::AuthenticationService; -use bittorrent_tracker_core::error::ScrapeError; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; @@ -42,13 +40,12 @@ use crate::packages::http_tracker_core; pub async fn handle_scrape( core_config: &Arc, scrape_handler: &Arc, - _authentication_service: &Arc, opt_http_stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, - return_real_scrape_data: bool, + return_fake_scrape_data: bool, ) -> Result { - // Authorization for scrape requests is handled at the `http_tracker_core` + // Authorization for scrape requests is handled at the `bittorrent-_racker_core` // level for each torrent. let peer_ip = match peer_ip_resolver::invoke(core_config.net.on_reverse_proxy, client_ip_sources) { @@ -56,33 +53,15 @@ pub async fn handle_scrape( Err(error) => return Err(responses::error::Error::from(error)), }; - if return_real_scrape_data { - let scrape_data = invoke( - scrape_handler, - opt_http_stats_event_sender, - &scrape_request.info_hashes, - &peer_ip, - ) - .await?; - - Ok(scrape_data) - } else { - Ok(http_tracker_core::services::scrape::fake(opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await) + if return_fake_scrape_data { + return Ok( + http_tracker_core::services::scrape::fake(opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await, + ); } -} -/// # Errors -/// -/// This function will return an error if the tracker core scrape handler fails. -pub async fn invoke( - scrape_handler: &Arc, - opt_http_stats_event_sender: &Arc>>, - info_hashes: &Vec, - original_peer_ip: &IpAddr, -) -> Result { - let scrape_data = scrape_handler.scrape(info_hashes).await?; + let scrape_data = scrape_handler.scrape(&scrape_request.info_hashes).await?; - send_scrape_event(original_peer_ip, opt_http_stats_event_sender).await; + send_scrape_event(&peer_ip, opt_http_stats_event_sender).await; Ok(scrape_data) } @@ -141,6 +120,7 @@ mod tests { use futures::future::BoxFuture; use mockall::mock; use tokio::sync::mpsc::error::SendError; + use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; @@ -148,8 +128,12 @@ mod tests { use crate::servers::http::test_helpers::tests::sample_info_hash; fn initialize_announce_and_scrape_handlers_for_public_tracker() -> (Arc, Arc) { - let config = configuration::ephemeral_public(); + initialize_announce_and_scrape_handlers_with_configuration(&configuration::ephemeral_public()) + } + fn initialize_announce_and_scrape_handlers_with_configuration( + config: &Configuration, + ) -> (Arc, Arc) { let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); @@ -182,9 +166,7 @@ mod tests { } } - fn initialize_scrape_handler() -> Arc { - let config = configuration::ephemeral(); - + fn initialize_scrape_handler_with_config(config: &Configuration) -> Arc { let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); @@ -205,31 +187,37 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::sync::Arc; + use bittorrent_http_protocol::v1::requests::scrape::Scrape; + use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use torrust_tracker_test_helpers::configuration; - use crate::packages::http_tracker_core::services::scrape::invoke; + use crate::packages::http_tracker_core::services::scrape::handle_scrape; use crate::packages::http_tracker_core::services::scrape::tests::{ - initialize_announce_and_scrape_handlers_for_public_tracker, initialize_scrape_handler, sample_info_hashes, - sample_peer, MockHttpStatsEventSender, + initialize_announce_and_scrape_handlers_with_configuration, initialize_scrape_handler_with_config, + sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::packages::{self, http_tracker_core}; use crate::servers::http::test_helpers::tests::sample_info_hash; #[tokio::test] async fn it_should_return_the_scrape_data_for_a_torrent() { + let configuration = configuration::ephemeral_public(); + let core_config = Arc::new(configuration.core.clone()); + let (http_stats_event_sender, _http_stats_repository) = packages::http_tracker_core::statistics::setup::factory(false); let http_stats_event_sender = Arc::new(http_stats_event_sender); - let (announce_handler, scrape_handler) = initialize_announce_and_scrape_handlers_for_public_tracker(); + let (announce_handler, scrape_handler) = initialize_announce_and_scrape_handlers_with_configuration(&configuration); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; - // Announce a new peer to force scrape data to contain not zeroed data + // Announce a new peer to force scrape data to contain non zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); announce_handler @@ -237,9 +225,25 @@ mod tests { .await .unwrap(); - let scrape_data = invoke(&scrape_handler, &http_stats_event_sender, &info_hashes, &original_peer_ip) - .await - .unwrap(); + let scrape_request = Scrape { + info_hashes: info_hashes.clone(), + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_ip: Some(original_peer_ip), + }; + + let scrape_data = handle_scrape( + &core_config, + &scrape_handler, + &http_stats_event_sender, + &scrape_request, + &client_ip_sources, + false, + ) + .await + .unwrap(); let mut expected_scrape_data = ScrapeData::empty(); expected_scrape_data.add_file( @@ -256,6 +260,8 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_scrape_event_when_the_peer_uses_ipv4() { + let config = configuration::ephemeral(); + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() @@ -265,17 +271,35 @@ mod tests { let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); - let scrape_handler = initialize_scrape_handler(); + let scrape_handler = initialize_scrape_handler_with_config(&config); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); - invoke(&scrape_handler, &http_stats_event_sender, &sample_info_hashes(), &peer_ip) - .await - .unwrap(); + let scrape_request = Scrape { + info_hashes: sample_info_hashes(), + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_ip: Some(peer_ip), + }; + + handle_scrape( + &Arc::new(config.core), + &scrape_handler, + &http_stats_event_sender, + &scrape_request, + &client_ip_sources, + false, + ) + .await + .unwrap(); } #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { + let config = configuration::ephemeral(); + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() @@ -285,13 +309,29 @@ mod tests { let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); - let scrape_handler = initialize_scrape_handler(); + let scrape_handler = initialize_scrape_handler_with_config(&config); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); - invoke(&scrape_handler, &http_stats_event_sender, &sample_info_hashes(), &peer_ip) - .await - .unwrap(); + let scrape_request = Scrape { + info_hashes: sample_info_hashes(), + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_ip: Some(peer_ip), + }; + + handle_scrape( + &Arc::new(config.core), + &scrape_handler, + &http_stats_event_sender, + &scrape_request, + &client_ip_sources, + false, + ) + .await + .unwrap(); } } diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 39bebe18e..2d41c2f78 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -123,26 +123,25 @@ async fn handle_scrape( // todo: move authentication inside `http_tracker_core::services::scrape::handle_scrape` // Authentication - let return_real_scrape_data = if core_config.private { + let return_fake_scrape_data = if core_config.private { match maybe_key { Some(key) => match authentication_service.authenticate(&key).await { - Ok(()) => true, - Err(_error) => false, + Ok(()) => false, + Err(_error) => true, }, - None => false, + None => true, } } else { - true + false }; http_tracker_core::services::scrape::handle_scrape( core_config, scrape_handler, - authentication_service, opt_http_stats_event_sender, scrape_request, client_ip_sources, - return_real_scrape_data, + return_fake_scrape_data, ) .await } From af28429f2c350bb866beb5e14acf0ca02dfb5af4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Feb 2025 16:10:23 +0000 Subject: [PATCH 0764/1297] refactor: [#1270] inline udp tracker announce invoke fn --- .../udp_tracker_core/services/announce.rs | 29 ++++++++++++++----- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/packages/udp_tracker_core/services/announce.rs b/src/packages/udp_tracker_core/services/announce.rs index db90d445f..5851cdc92 100644 --- a/src/packages/udp_tracker_core/services/announce.rs +++ b/src/packages/udp_tracker_core/services/announce.rs @@ -46,14 +46,27 @@ pub async fn handle_announce( let mut peer = peer_builder::from_request(request, &remote_client_ip); let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); - let announce_data = invoke( - announce_handler.clone(), - opt_udp_stats_event_sender.clone(), - info_hash, - &mut peer, - &peers_wanted, - ) - .await?; + let original_peer_ip = peer.peer_addr.ip(); + + // The tracker could change the original peer ip + let announce_data = announce_handler + .announce(&info_hash, &mut peer, &original_peer_ip, &peers_wanted) + .await?; + + if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + match original_peer_ip { + IpAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Announce) + .await; + } + IpAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Announce) + .await; + } + } + } Ok(announce_data) } From d49aebd7a14e9ff87c3fa9ce73bf5e69496fdedf Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Feb 2025 16:13:17 +0000 Subject: [PATCH 0765/1297] refactor: [#1270] inline udp tracker scrape invoke fn --- src/packages/udp_tracker_core/services/scrape.rs | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/src/packages/udp_tracker_core/services/scrape.rs b/src/packages/udp_tracker_core/services/scrape.rs index e7608928c..f12d4bc2e 100644 --- a/src/packages/udp_tracker_core/services/scrape.rs +++ b/src/packages/udp_tracker_core/services/scrape.rs @@ -35,19 +35,7 @@ pub async fn handle_scrape( info_hashes.push((*info_hash).into()); } - invoke(scrape_handler, opt_udp_stats_event_sender, &info_hashes, remote_addr).await -} - -/// # Errors -/// -/// It will return an error if the tracker core scrape handler returns an error. -pub async fn invoke( - scrape_handler: &Arc, - opt_udp_stats_event_sender: &Arc>>, - info_hashes: &Vec, - remote_addr: SocketAddr, -) -> Result { - let scrape_data = scrape_handler.scrape(info_hashes).await?; + let scrape_data = scrape_handler.scrape(&info_hashes).await?; if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { match remote_addr { From d0e693619f2322dde1866b20a4a66d453bde7504 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Feb 2025 16:27:18 +0000 Subject: [PATCH 0766/1297] refactor: simplify loop with map --- src/packages/udp_tracker_core/services/scrape.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/packages/udp_tracker_core/services/scrape.rs b/src/packages/udp_tracker_core/services/scrape.rs index f12d4bc2e..07ae452f8 100644 --- a/src/packages/udp_tracker_core/services/scrape.rs +++ b/src/packages/udp_tracker_core/services/scrape.rs @@ -30,10 +30,7 @@ pub async fn handle_scrape( opt_udp_stats_event_sender: &Arc>>, ) -> Result { // Convert from aquatic infohashes - let mut info_hashes: Vec = vec![]; - for info_hash in &request.info_hashes { - info_hashes.push((*info_hash).into()); - } + let info_hashes: Vec = request.info_hashes.iter().map(|&x| x.into()).collect(); let scrape_data = scrape_handler.scrape(&info_hashes).await?; From f6bf07050cb2c48a4af459f1143de33fb19fbb0e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Feb 2025 19:04:31 +0000 Subject: [PATCH 0767/1297] refactor: [#1275] move announce authentication in http tracker to core --- .../http-protocol/src/v1/responses/error.rs | 8 +++++ .../src/authentication/key/mod.rs | 4 +++ .../http_tracker_core/services/announce.rs | 24 +++++++++++++- .../http/v1/extractors/authentication_key.rs | 10 +++--- src/servers/http/v1/handlers/announce.rs | 31 ++++--------------- src/servers/http/v1/handlers/common/auth.rs | 7 ++--- tests/servers/http/asserts.rs | 6 +++- 7 files changed, 53 insertions(+), 37 deletions(-) diff --git a/packages/http-protocol/src/v1/responses/error.rs b/packages/http-protocol/src/v1/responses/error.rs index 2bd8cd95c..30749f73a 100644 --- a/packages/http-protocol/src/v1/responses/error.rs +++ b/packages/http-protocol/src/v1/responses/error.rs @@ -79,6 +79,14 @@ impl From for Error { } } +impl From for Error { + fn from(err: bittorrent_tracker_core::authentication::Error) -> Self { + Error { + failure_reason: format!("Tracker authentication error: {err}"), + } + } +} + #[cfg(test)] mod tests { diff --git a/packages/tracker-core/src/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs index 648143928..efc734356 100644 --- a/packages/tracker-core/src/authentication/key/mod.rs +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -185,6 +185,10 @@ pub enum Error { /// Indicates that the key has expired. #[error("Key has expired, {location}")] KeyExpired { location: &'static Location<'static> }, + + /// Indicates that the required key for authentication was not provided. + #[error("Missing authentication key, {location}")] + MissingAuthKey { location: &'static Location<'static> }, } impl From for Error { diff --git a/src/packages/http_tracker_core/services/announce.rs b/src/packages/http_tracker_core/services/announce.rs index 2bc421f1d..6c9cbec17 100644 --- a/src/packages/http_tracker_core/services/announce.rs +++ b/src/packages/http_tracker_core/services/announce.rs @@ -8,6 +8,7 @@ //! It also sends an [`http_tracker_core::statistics::event::Event`] //! because events are specific for the HTTP tracker. use std::net::IpAddr; +use std::panic::Location; use std::sync::Arc; use bittorrent_http_protocol::v1::requests::announce::{peer_from_request, Announce}; @@ -15,6 +16,7 @@ use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::authentication::{self, Key}; use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; @@ -42,12 +44,28 @@ use crate::packages::http_tracker_core; pub async fn handle_announce( core_config: &Arc, announce_handler: &Arc, - _authentication_service: &Arc, + authentication_service: &Arc, whitelist_authorization: &Arc, opt_http_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, + maybe_key: Option, ) -> Result { + // Authentication + if core_config.private { + match maybe_key { + Some(key) => match authentication_service.authenticate(&key).await { + Ok(()) => (), + Err(error) => return Err(error.into()), + }, + None => { + return Err(responses::error::Error::from(authentication::key::Error::MissingAuthKey { + location: Location::caller(), + })) + } + } + } + // Authorization match whitelist_authorization.authorize(&announce_request.info_hash).await { Ok(()) => (), @@ -257,6 +275,7 @@ mod tests { &core_http_tracker_services.http_stats_event_sender, &announce_request, &client_ip_sources, + None, ) .await .unwrap(); @@ -300,6 +319,7 @@ mod tests { &core_http_tracker_services.http_stats_event_sender, &announce_request, &client_ip_sources, + None, ) .await .unwrap(); @@ -351,6 +371,7 @@ mod tests { &core_http_tracker_services.http_stats_event_sender, &announce_request, &client_ip_sources, + None, ) .await .unwrap(); @@ -383,6 +404,7 @@ mod tests { &core_http_tracker_services.http_stats_event_sender, &announce_request, &client_ip_sources, + None, ) .await .unwrap(); diff --git a/src/servers/http/v1/extractors/authentication_key.rs b/src/servers/http/v1/extractors/authentication_key.rs index 0e46b75dd..c99c7000a 100644 --- a/src/servers/http/v1/extractors/authentication_key.rs +++ b/src/servers/http/v1/extractors/authentication_key.rs @@ -117,11 +117,6 @@ fn custom_error(rejection: &PathRejection) -> responses::error::Error { location: Location::caller(), }) } - axum::extract::rejection::PathRejection::MissingPathParams(_) => { - responses::error::Error::from(auth::Error::MissingAuthKey { - location: Location::caller(), - }) - } _ => responses::error::Error::from(auth::Error::CannotExtractKeyParam { location: Location::caller(), }), @@ -148,6 +143,9 @@ mod tests { let response = parse_key(invalid_key).unwrap_err(); - assert_error_response(&response, "Authentication error: Invalid format for authentication key param"); + assert_error_response( + &response, + "Tracker authentication error: Invalid format for authentication key param", + ); } } diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 5f25c317b..76f4e5134 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -5,7 +5,6 @@ //! //! The handlers perform the authentication and authorization of the request, //! and resolve the client IP address. -use std::panic::Location; use std::sync::Arc; use aquatic_udp_protocol::AnnounceEvent; @@ -22,12 +21,10 @@ use hyper::StatusCode; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; -use super::common::auth::map_auth_error_to_error_response; use crate::packages::http_tracker_core; use crate::servers::http::v1::extractors::announce_request::ExtractRequest; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; -use crate::servers::http::v1::handlers::common::auth; /// It handles the `announce` request when the HTTP tracker does not require /// authentication (no PATH `key` parameter required). @@ -134,23 +131,6 @@ async fn handle_announce( client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Result { - // todo: move authentication inside `http_tracker_core::services::announce::handle_announce` - - // Authentication - if core_config.private { - match maybe_key { - Some(key) => match authentication_service.authenticate(&key).await { - Ok(()) => (), - Err(error) => return Err(map_auth_error_to_error_response(&error)), - }, - None => { - return Err(responses::error::Error::from(auth::Error::MissingAuthKey { - location: Location::caller(), - })) - } - } - } - http_tracker_core::services::announce::handle_announce( &core_config.clone(), &announce_handler.clone(), @@ -159,6 +139,7 @@ async fn handle_announce( &opt_http_stats_event_sender.clone(), announce_request, client_ip_sources, + maybe_key, ) .await } @@ -339,10 +320,7 @@ mod tests { .await .unwrap_err(); - assert_error_response( - &response, - "Authentication error: Missing authentication key param for private tracker", - ); + assert_error_response(&response, "Tracker authentication error: Missing authentication key"); } #[tokio::test] @@ -366,7 +344,10 @@ mod tests { .await .unwrap_err(); - assert_error_response(&response, "Authentication error: Failed to read key"); + assert_error_response( + &response, + "Tracker authentication error: Failed to read key: YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ", + ); } } diff --git a/src/servers/http/v1/handlers/common/auth.rs b/src/servers/http/v1/handlers/common/auth.rs index c8625d03a..f45064ae3 100644 --- a/src/servers/http/v1/handlers/common/auth.rs +++ b/src/servers/http/v1/handlers/common/auth.rs @@ -14,10 +14,9 @@ use thiserror::Error; /// from the URL path. #[derive(Debug, Error)] pub enum Error { - #[error("Missing authentication key param for private tracker. Error in {location}")] - MissingAuthKey { location: &'static Location<'static> }, #[error("Invalid format for authentication key param. Error in {location}")] InvalidKeyFormat { location: &'static Location<'static> }, + #[error("Cannot extract authentication key param from URL path. Error in {location}")] CannotExtractKeyParam { location: &'static Location<'static> }, } @@ -25,7 +24,7 @@ pub enum Error { impl From for responses::error::Error { fn from(err: Error) -> Self { responses::error::Error { - failure_reason: format!("Authentication error: {err}"), + failure_reason: format!("Tracker authentication error: {err}"), } } } @@ -36,6 +35,6 @@ pub fn map_auth_error_to_error_response(err: &authentication::Error) -> response // impl From for responses::error::Error // Consider moving the trait implementation to the http-protocol package. responses::error::Error { - failure_reason: format!("Authentication error: {err}"), + failure_reason: format!("Tracker authentication error: {err}"), } } diff --git a/tests/servers/http/asserts.rs b/tests/servers/http/asserts.rs index 8d40d7e74..a68a1896e 100644 --- a/tests/servers/http/asserts.rs +++ b/tests/servers/http/asserts.rs @@ -141,5 +141,9 @@ pub async fn assert_cannot_parse_query_params_error_response(response: Response, pub async fn assert_authentication_error_response(response: Response) { assert_eq!(response.status(), 200); - assert_bencoded_error(&response.text().await.unwrap(), "Authentication error", Location::caller()); + assert_bencoded_error( + &response.text().await.unwrap(), + "Tracker authentication error", + Location::caller(), + ); } From ecc093f8f77889580177b5e8db4e6bfdab0ed594 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Feb 2025 19:23:13 +0000 Subject: [PATCH 0768/1297] refactor: [#1275] move scrape authentication in http tracker to core --- .../http_tracker_core/services/scrape.rs | 88 ++++++++++++------- src/servers/http/v1/handlers/scrape.rs | 19 +--- 2 files changed, 60 insertions(+), 47 deletions(-) diff --git a/src/packages/http_tracker_core/services/scrape.rs b/src/packages/http_tracker_core/services/scrape.rs index 667ce8d0d..7e3ea47fd 100644 --- a/src/packages/http_tracker_core/services/scrape.rs +++ b/src/packages/http_tracker_core/services/scrape.rs @@ -14,6 +14,8 @@ use bittorrent_http_protocol::v1::requests::scrape::Scrape; use bittorrent_http_protocol::v1::responses; use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::authentication::Key; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; @@ -40,12 +42,26 @@ use crate::packages::http_tracker_core; pub async fn handle_scrape( core_config: &Arc, scrape_handler: &Arc, + authentication_service: &Arc, opt_http_stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, - return_fake_scrape_data: bool, + maybe_key: Option, ) -> Result { - // Authorization for scrape requests is handled at the `bittorrent-_racker_core` + // Authentication + let return_fake_scrape_data = if core_config.private { + match maybe_key { + Some(key) => match authentication_service.authenticate(&key).await { + Ok(()) => false, + Err(_error) => true, + }, + None => true, + } + } else { + false + }; + + // Authorization for scrape requests is handled at the `bittorrent_tracker_core` // level for each torrent. let peer_ip = match peer_ip_resolver::invoke(core_config.net.on_reverse_proxy, client_ip_sources) { @@ -111,6 +127,8 @@ mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -127,27 +145,39 @@ mod tests { use crate::packages::http_tracker_core; use crate::servers::http::test_helpers::tests::sample_info_hash; - fn initialize_announce_and_scrape_handlers_for_public_tracker() -> (Arc, Arc) { - initialize_announce_and_scrape_handlers_with_configuration(&configuration::ephemeral_public()) + struct Container { + announce_handler: Arc, + scrape_handler: Arc, + authentication_service: Arc, } - fn initialize_announce_and_scrape_handlers_with_configuration( - config: &Configuration, - ) -> (Arc, Arc) { + fn initialize_services_for_public_tracker() -> Container { + initialize_services_with_configuration(&configuration::ephemeral_public()) + } + + fn initialize_services_with_configuration(config: &Configuration) -> Container { let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository)); + let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &whitelist_authorization, &in_memory_torrent_repository, &db_torrent_repository, )); + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - (announce_handler, scrape_handler) + Container { + announce_handler, + scrape_handler, + authentication_service, + } } fn sample_info_hashes() -> Vec { @@ -166,14 +196,6 @@ mod tests { } } - fn initialize_scrape_handler_with_config(config: &Configuration) -> Arc { - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)) - } - mock! { HttpStatsEventSender {} impl http_tracker_core::statistics::event::sender::Sender for HttpStatsEventSender { @@ -197,8 +219,7 @@ mod tests { use crate::packages::http_tracker_core::services::scrape::handle_scrape; use crate::packages::http_tracker_core::services::scrape::tests::{ - initialize_announce_and_scrape_handlers_with_configuration, initialize_scrape_handler_with_config, - sample_info_hashes, sample_peer, MockHttpStatsEventSender, + initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::packages::{self, http_tracker_core}; use crate::servers::http::test_helpers::tests::sample_info_hash; @@ -212,7 +233,7 @@ mod tests { packages::http_tracker_core::statistics::setup::factory(false); let http_stats_event_sender = Arc::new(http_stats_event_sender); - let (announce_handler, scrape_handler) = initialize_announce_and_scrape_handlers_with_configuration(&configuration); + let container = initialize_services_with_configuration(&configuration); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; @@ -220,7 +241,8 @@ mod tests { // Announce a new peer to force scrape data to contain non zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); - announce_handler + container + .announce_handler .announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible) .await .unwrap(); @@ -236,11 +258,12 @@ mod tests { let scrape_data = handle_scrape( &core_config, - &scrape_handler, + &container.scrape_handler, + &container.authentication_service, &http_stats_event_sender, &scrape_request, &client_ip_sources, - false, + None, ) .await .unwrap(); @@ -271,7 +294,7 @@ mod tests { let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); - let scrape_handler = initialize_scrape_handler_with_config(&config); + let container = initialize_services_with_configuration(&config); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); @@ -286,11 +309,12 @@ mod tests { handle_scrape( &Arc::new(config.core), - &scrape_handler, + &container.scrape_handler, + &container.authentication_service, &http_stats_event_sender, &scrape_request, &client_ip_sources, - false, + None, ) .await .unwrap(); @@ -309,7 +333,7 @@ mod tests { let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); - let scrape_handler = initialize_scrape_handler_with_config(&config); + let container = initialize_services_with_configuration(&config); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); @@ -324,11 +348,12 @@ mod tests { handle_scrape( &Arc::new(config.core), - &scrape_handler, + &container.scrape_handler, + &container.authentication_service, &http_stats_event_sender, &scrape_request, &client_ip_sources, - false, + None, ) .await .unwrap(); @@ -347,7 +372,7 @@ mod tests { use crate::packages::http_tracker_core::services::scrape::fake; use crate::packages::http_tracker_core::services::scrape::tests::{ - initialize_announce_and_scrape_handlers_for_public_tracker, sample_info_hashes, sample_peer, MockHttpStatsEventSender, + initialize_services_for_public_tracker, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::packages::{self, http_tracker_core}; use crate::servers::http::test_helpers::tests::sample_info_hash; @@ -358,7 +383,7 @@ mod tests { packages::http_tracker_core::statistics::setup::factory(false); let http_stats_event_sender = Arc::new(http_stats_event_sender); - let (announce_handler, _scrape_handler) = initialize_announce_and_scrape_handlers_for_public_tracker(); + let container = initialize_services_for_public_tracker(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; @@ -366,7 +391,8 @@ mod tests { // Announce a new peer to force scrape data to contain not zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); - announce_handler + container + .announce_handler .announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible) .await .unwrap(); diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 2d41c2f78..946190e8f 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -107,6 +107,7 @@ async fn handle( Ok(scrape_data) => scrape_data, Err(error) => return (StatusCode::OK, error.write()).into_response(), }; + build_response(scrape_data) } @@ -120,28 +121,14 @@ async fn handle_scrape( client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Result { - // todo: move authentication inside `http_tracker_core::services::scrape::handle_scrape` - - // Authentication - let return_fake_scrape_data = if core_config.private { - match maybe_key { - Some(key) => match authentication_service.authenticate(&key).await { - Ok(()) => false, - Err(_error) => true, - }, - None => true, - } - } else { - false - }; - http_tracker_core::services::scrape::handle_scrape( core_config, scrape_handler, + authentication_service, opt_http_stats_event_sender, scrape_request, client_ip_sources, - return_fake_scrape_data, + maybe_key, ) .await } From 694621bc63ae542afca395e376a31008b60c43fd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Feb 2025 07:53:54 +0000 Subject: [PATCH 0769/1297] refactor: [#1275] extract ConnectionCookieError enum --- src/servers/udp/connection_cookie.rs | 18 ++++++++-------- src/servers/udp/error.rs | 32 +++++++++++++++++++++------- src/servers/udp/handlers/announce.rs | 2 +- src/servers/udp/handlers/mod.rs | 13 ++++------- src/servers/udp/handlers/scrape.rs | 2 +- 5 files changed, 39 insertions(+), 28 deletions(-) diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs index 439be9da7..5d8976f0e 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/servers/udp/connection_cookie.rs @@ -82,7 +82,7 @@ use cookie_builder::{assemble, decode, disassemble, encode}; use tracing::instrument; use zerocopy::AsBytes; -use super::error::Error; +use crate::servers::udp::error::ConnectionCookieError; use crate::shared::crypto::keys::CipherArrayBlowfish; /// Generates a new connection cookie. @@ -96,9 +96,9 @@ use crate::shared::crypto::keys::CipherArrayBlowfish; /// It would panic if the cookie is not exactly 8 bytes is size. /// #[instrument(err)] -pub fn make(fingerprint: u64, issue_at: f64) -> Result { +pub fn make(fingerprint: u64, issue_at: f64) -> Result { if !issue_at.is_normal() { - return Err(Error::CookieValueNotNormal { + return Err(ConnectionCookieError::ValueNotNormal { not_normal_value: issue_at, }); } @@ -122,7 +122,7 @@ use std::ops::Range; /// /// It would panic if the range start is not smaller than it's end. #[instrument] -pub fn check(cookie: &Cookie, fingerprint: u64, valid_range: Range) -> Result { +pub fn check(cookie: &Cookie, fingerprint: u64, valid_range: Range) -> Result { assert!(valid_range.start <= valid_range.end, "range start is larger than range end"); let cookie_bytes = CipherArrayBlowfish::from_slice(cookie.0.as_bytes()); @@ -131,20 +131,20 @@ pub fn check(cookie: &Cookie, fingerprint: u64, valid_range: Range) -> Resu let issue_time = disassemble(fingerprint, cookie_bytes); if !issue_time.is_normal() { - return Err(Error::CookieValueNotNormal { + return Err(ConnectionCookieError::ValueNotNormal { not_normal_value: issue_time, }); } if issue_time < valid_range.start { - return Err(Error::CookieValueExpired { + return Err(ConnectionCookieError::ValueExpired { expired_value: issue_time, min_value: valid_range.start, }); } if issue_time > valid_range.end { - return Err(Error::CookieValueFromFuture { + return Err(ConnectionCookieError::ValueFromFuture { future_value: issue_time, max_value: valid_range.end, }); @@ -287,7 +287,7 @@ mod tests { let result = check(&cookie, fingerprint, min..max).unwrap_err(); match result { - Error::CookieValueExpired { .. } => {} // Expected error + ConnectionCookieError::ValueExpired { .. } => {} // Expected error _ => panic!("Expected ConnectionIdExpired error"), } } @@ -305,7 +305,7 @@ mod tests { let result = check(&cookie, fingerprint, min..max).unwrap_err(); match result { - Error::CookieValueFromFuture { .. } => {} // Expected error + ConnectionCookieError::ValueFromFuture { .. } => {} // Expected error _ => panic!("Expected ConnectionIdFromFuture error"), } } diff --git a/src/servers/udp/error.rs b/src/servers/udp/error.rs index cda562aed..6ba62a5e0 100644 --- a/src/servers/udp/error.rs +++ b/src/servers/udp/error.rs @@ -13,14 +13,9 @@ pub struct ConnectionCookie(pub ConnectionId); /// Error returned by the UDP server. #[derive(Error, Debug)] pub enum Error { - #[error("cookie value is not normal: {not_normal_value}")] - CookieValueNotNormal { not_normal_value: f64 }, - - #[error("cookie value is expired: {expired_value}, expected > {min_value}")] - CookieValueExpired { expired_value: f64, min_value: f64 }, - - #[error("cookie value is from future: {future_value}, expected < {max_value}")] - CookieValueFromFuture { future_value: f64, max_value: f64 }, + /// Error returned when there was an error with the connection cookie. + #[error("Connection cookie error: {source}")] + ConnectionCookieError { source: ConnectionCookieError }, #[error("error when phrasing request: {request_parse_error:?}")] RequestParseError { request_parse_error: RequestParseError }, @@ -49,8 +44,29 @@ pub enum Error { TrackerAuthenticationRequired { location: &'static Location<'static> }, } +/// Error returned when there was an error with the connection cookie. +#[derive(Error, Debug)] +pub enum ConnectionCookieError { + #[error("cookie value is not normal: {not_normal_value}")] + ValueNotNormal { not_normal_value: f64 }, + + #[error("cookie value is expired: {expired_value}, expected > {min_value}")] + ValueExpired { expired_value: f64, min_value: f64 }, + + #[error("cookie value is from future: {future_value}, expected < {max_value}")] + ValueFromFuture { future_value: f64, max_value: f64 }, +} + impl From for Error { fn from(request_parse_error: RequestParseError) -> Self { Self::RequestParseError { request_parse_error } } } + +impl From for Error { + fn from(connection_cookie_error: ConnectionCookieError) -> Self { + Self::ConnectionCookieError { + source: connection_cookie_error, + } + } +} diff --git a/src/servers/udp/handlers/announce.rs b/src/servers/udp/handlers/announce.rs index a273a2ecb..e5ee6dccf 100644 --- a/src/servers/udp/handlers/announce.rs +++ b/src/servers/udp/handlers/announce.rs @@ -50,7 +50,7 @@ pub async fn handle_announce( gen_remote_fingerprint(&remote_addr), cookie_valid_range, ) - .map_err(|e| (e, request.transaction_id))?; + .map_err(|e| (e.into(), request.transaction_id))?; let response = udp_tracker_core::services::announce::handle_announce( remote_addr, diff --git a/src/servers/udp/handlers/mod.rs b/src/servers/udp/handlers/mod.rs index f9f8edae7..2611931e3 100644 --- a/src/servers/udp/handlers/mod.rs +++ b/src/servers/udp/handlers/mod.rs @@ -78,15 +78,10 @@ pub(crate) async fn handle_packet( { Ok(response) => return response, Err((e, transaction_id)) => { - match &e { - Error::CookieValueNotNormal { .. } - | Error::CookieValueExpired { .. } - | Error::CookieValueFromFuture { .. } => { - // code-review: should we include `RequestParseError` and `BadRequest`? - let mut ban_service = udp_tracker_container.ban_service.write().await; - ban_service.increase_counter(&udp_request.from.ip()); - } - _ => {} + if let Error::ConnectionCookieError { .. } = &e { + // code-review: should we include `RequestParseError` and `BadRequest`? + let mut ban_service = udp_tracker_container.ban_service.write().await; + ban_service.increase_counter(&udp_request.from.ip()); } handle_error( diff --git a/src/servers/udp/handlers/scrape.rs b/src/servers/udp/handlers/scrape.rs index 2b03e0dc7..51a914e9f 100644 --- a/src/servers/udp/handlers/scrape.rs +++ b/src/servers/udp/handlers/scrape.rs @@ -42,7 +42,7 @@ pub async fn handle_scrape( gen_remote_fingerprint(&remote_addr), cookie_valid_range, ) - .map_err(|e| (e, request.transaction_id))?; + .map_err(|e| (e.into(), request.transaction_id))?; let scrape_data = udp_tracker_core::services::scrape::handle_scrape(remote_addr, request, scrape_handler, opt_udp_stats_event_sender) From 4fd79b798d8ef456444a02621dd348c7e3a6ac79 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Feb 2025 08:03:56 +0000 Subject: [PATCH 0770/1297] refactor: [#1275] move conenction cookie to udp_tracker_core package --- .../udp_tracker_core}/connection_cookie.rs | 15 ++++++++++++++- src/packages/udp_tracker_core/mod.rs | 1 + src/servers/udp/error.rs | 15 ++------------- src/servers/udp/handlers/announce.rs | 12 ++++++------ src/servers/udp/handlers/connect.rs | 4 ++-- src/servers/udp/handlers/error.rs | 2 +- src/servers/udp/handlers/scrape.rs | 4 ++-- src/servers/udp/mod.rs | 1 - 8 files changed, 28 insertions(+), 26 deletions(-) rename src/{servers/udp => packages/udp_tracker_core}/connection_cookie.rs (95%) diff --git a/src/servers/udp/connection_cookie.rs b/src/packages/udp_tracker_core/connection_cookie.rs similarity index 95% rename from src/servers/udp/connection_cookie.rs rename to src/packages/udp_tracker_core/connection_cookie.rs index 5d8976f0e..2d8eae335 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/packages/udp_tracker_core/connection_cookie.rs @@ -79,12 +79,25 @@ use aquatic_udp_protocol::ConnectionId as Cookie; use cookie_builder::{assemble, decode, disassemble, encode}; +use thiserror::Error; use tracing::instrument; use zerocopy::AsBytes; -use crate::servers::udp::error::ConnectionCookieError; use crate::shared::crypto::keys::CipherArrayBlowfish; +/// Error returned when there was an error with the connection cookie. +#[derive(Error, Debug)] +pub enum ConnectionCookieError { + #[error("cookie value is not normal: {not_normal_value}")] + ValueNotNormal { not_normal_value: f64 }, + + #[error("cookie value is expired: {expired_value}, expected > {min_value}")] + ValueExpired { expired_value: f64, min_value: f64 }, + + #[error("cookie value is from future: {future_value}, expected < {max_value}")] + ValueFromFuture { future_value: f64, max_value: f64 }, +} + /// Generates a new connection cookie. /// /// # Errors diff --git a/src/packages/udp_tracker_core/mod.rs b/src/packages/udp_tracker_core/mod.rs index 4f3e54857..1c93f811a 100644 --- a/src/packages/udp_tracker_core/mod.rs +++ b/src/packages/udp_tracker_core/mod.rs @@ -1,2 +1,3 @@ +pub mod connection_cookie; pub mod services; pub mod statistics; diff --git a/src/servers/udp/error.rs b/src/servers/udp/error.rs index 6ba62a5e0..81e7847c0 100644 --- a/src/servers/udp/error.rs +++ b/src/servers/udp/error.rs @@ -6,6 +6,8 @@ use derive_more::derive::Display; use thiserror::Error; use torrust_tracker_located_error::LocatedError; +use crate::packages::udp_tracker_core::connection_cookie::ConnectionCookieError; + #[derive(Display, Debug)] #[display(":?")] pub struct ConnectionCookie(pub ConnectionId); @@ -44,19 +46,6 @@ pub enum Error { TrackerAuthenticationRequired { location: &'static Location<'static> }, } -/// Error returned when there was an error with the connection cookie. -#[derive(Error, Debug)] -pub enum ConnectionCookieError { - #[error("cookie value is not normal: {not_normal_value}")] - ValueNotNormal { not_normal_value: f64 }, - - #[error("cookie value is expired: {expired_value}, expected > {min_value}")] - ValueExpired { expired_value: f64, min_value: f64 }, - - #[error("cookie value is from future: {future_value}, expected < {max_value}")] - ValueFromFuture { future_value: f64, max_value: f64 }, -} - impl From for Error { fn from(request_parse_error: RequestParseError) -> Self { Self::RequestParseError { request_parse_error } diff --git a/src/servers/udp/handlers/announce.rs b/src/servers/udp/handlers/announce.rs index e5ee6dccf..c9dd15735 100644 --- a/src/servers/udp/handlers/announce.rs +++ b/src/servers/udp/handlers/announce.rs @@ -14,8 +14,8 @@ use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; +use crate::packages::udp_tracker_core::connection_cookie::check; use crate::packages::udp_tracker_core::{self}; -use crate::servers::udp::connection_cookie::check; use crate::servers::udp::error::Error; use crate::servers::udp::handlers::gen_remote_fingerprint; @@ -134,7 +134,7 @@ mod tests { PeerId as AquaticPeerId, PeerKey, Port, TransactionId, }; - use crate::servers::udp::connection_cookie::make; + use crate::packages::udp_tracker_core::connection_cookie::make; use crate::servers::udp::handlers::tests::{sample_ipv4_remote_addr_fingerprint, sample_issue_time}; struct AnnounceRequestBuilder { @@ -213,8 +213,8 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_configuration::Core; + use crate::packages::udp_tracker_core::connection_cookie::make; use crate::packages::{self, udp_tracker_core}; - use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, @@ -447,7 +447,7 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; - use crate::servers::udp::connection_cookie::make; + use crate::packages::udp_tracker_core::connection_cookie::make; use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_issue_time, @@ -520,8 +520,8 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_configuration::Core; + use crate::packages::udp_tracker_core::connection_cookie::make; use crate::packages::{self, udp_tracker_core}; - use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, @@ -776,7 +776,7 @@ mod tests { use mockall::predicate::eq; use crate::packages::udp_tracker_core; - use crate::servers::udp::connection_cookie::make; + use crate::packages::udp_tracker_core::connection_cookie::make; use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::tests::{ sample_cookie_valid_range, sample_issue_time, MockUdpStatsEventSender, TrackerConfigurationBuilder, diff --git a/src/servers/udp/handlers/connect.rs b/src/servers/udp/handlers/connect.rs index 431c3bb4d..799e46347 100644 --- a/src/servers/udp/handlers/connect.rs +++ b/src/servers/udp/handlers/connect.rs @@ -6,7 +6,7 @@ use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response}; use tracing::{instrument, Level}; use crate::packages::udp_tracker_core; -use crate::servers::udp::connection_cookie::make; +use crate::packages::udp_tracker_core::connection_cookie::make; use crate::servers::udp::handlers::gen_remote_fingerprint; /// It handles the `Connect` request. Refer to [`Connect`](crate::servers::udp#connect) @@ -62,8 +62,8 @@ mod tests { use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; use mockall::predicate::eq; + use crate::packages::udp_tracker_core::connection_cookie::make; use crate::packages::{self, udp_tracker_core}; - use crate::servers::udp::connection_cookie::make; use crate::servers::udp::handlers::handle_connect; use crate::servers::udp::handlers::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, diff --git a/src/servers/udp/handlers/error.rs b/src/servers/udp/handlers/error.rs index 36095eeed..e5529dbdf 100644 --- a/src/servers/udp/handlers/error.rs +++ b/src/servers/udp/handlers/error.rs @@ -9,7 +9,7 @@ use uuid::Uuid; use zerocopy::network_endian::I32; use crate::packages::udp_tracker_core; -use crate::servers::udp::connection_cookie::check; +use crate::packages::udp_tracker_core::connection_cookie::check; use crate::servers::udp::error::Error; use crate::servers::udp::handlers::gen_remote_fingerprint; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; diff --git a/src/servers/udp/handlers/scrape.rs b/src/servers/udp/handlers/scrape.rs index 51a914e9f..9bc445417 100644 --- a/src/servers/udp/handlers/scrape.rs +++ b/src/servers/udp/handlers/scrape.rs @@ -11,7 +11,7 @@ use tracing::{instrument, Level}; use zerocopy::network_endian::I32; use crate::packages::udp_tracker_core; -use crate::servers::udp::connection_cookie::check; +use crate::packages::udp_tracker_core::connection_cookie::check; use crate::servers::udp::error::Error; use crate::servers::udp::handlers::gen_remote_fingerprint; @@ -94,7 +94,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::packages; - use crate::servers::udp::connection_cookie::make; + use crate::packages::udp_tracker_core::connection_cookie::make; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, sample_issue_time, TorrentPeerBuilder, diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index e8410e5f0..2f0d4e4ce 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -637,7 +637,6 @@ use std::net::SocketAddr; -pub mod connection_cookie; pub mod error; pub mod handlers; pub mod server; From 91525af0c8e6d8686187909fe8735a4a89345eb2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Feb 2025 09:09:10 +0000 Subject: [PATCH 0771/1297] refactor: [#1275] move authentication in udp tracker to core --- .../udp_tracker_core/connection_cookie.rs | 11 +++- .../udp_tracker_core/services/announce.rs | 52 ++++++++++++++++++- .../udp_tracker_core/services/scrape.rs | 51 +++++++++++++++++- src/servers/udp/error.rs | 36 ++++++++----- src/servers/udp/handlers/announce.rs | 33 ++++-------- src/servers/udp/handlers/connect.rs | 3 +- src/servers/udp/handlers/error.rs | 3 +- src/servers/udp/handlers/mod.rs | 20 +++---- src/servers/udp/handlers/scrape.rs | 25 +++------ src/servers/udp/mod.rs | 2 +- 10 files changed, 160 insertions(+), 76 deletions(-) diff --git a/src/packages/udp_tracker_core/connection_cookie.rs b/src/packages/udp_tracker_core/connection_cookie.rs index 2d8eae335..b9070c63a 100644 --- a/src/packages/udp_tracker_core/connection_cookie.rs +++ b/src/packages/udp_tracker_core/connection_cookie.rs @@ -86,7 +86,7 @@ use zerocopy::AsBytes; use crate::shared::crypto::keys::CipherArrayBlowfish; /// Error returned when there was an error with the connection cookie. -#[derive(Error, Debug)] +#[derive(Error, Debug, Clone)] pub enum ConnectionCookieError { #[error("cookie value is not normal: {not_normal_value}")] ValueNotNormal { not_normal_value: f64 }, @@ -123,6 +123,8 @@ pub fn make(fingerprint: u64, issue_at: f64) -> Result) -> Resu Ok(issue_time) } +#[must_use] +pub(crate) fn gen_remote_fingerprint(remote_addr: &SocketAddr) -> u64 { + let mut state = DefaultHasher::new(); + remote_addr.hash(&mut state); + state.finish() +} + mod cookie_builder { use cipher::{BlockDecrypt, BlockEncrypt}; use tracing::instrument; diff --git a/src/packages/udp_tracker_core/services/announce.rs b/src/packages/udp_tracker_core/services/announce.rs index 5851cdc92..a825d06ad 100644 --- a/src/packages/udp_tracker_core/services/announce.rs +++ b/src/packages/udp_tracker_core/services/announce.rs @@ -8,19 +8,57 @@ //! It also sends an [`udp_tracker_core::statistics::event::Event`] //! because events are specific for the HTTP tracker. use std::net::{IpAddr, SocketAddr}; +use std::ops::Range; use std::sync::Arc; use aquatic_udp_protocol::AnnounceRequest; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; -use bittorrent_tracker_core::error::AnnounceError; +use bittorrent_tracker_core::error::{AnnounceError, WhitelistError}; use bittorrent_tracker_core::whitelist; use bittorrent_udp_protocol::peer_builder; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; +use crate::packages::udp_tracker_core::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; use crate::packages::udp_tracker_core::{self}; +/// Errors related to announce requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum UdpAnnounceError { + /// Error returned when there was an error with the connection cookie. + #[error("Connection cookie error: {source}")] + ConnectionCookieError { source: ConnectionCookieError }, + + /// Error returned when there was an error with the tracker core announce handler. + #[error("Tracker core announce error: {source}")] + TrackerCoreAnnounceError { source: AnnounceError }, + + /// Error returned when there was an error with the tracker core whitelist. + #[error("Tracker core whitelist error: {source}")] + TrackerCoreWhitelistError { source: WhitelistError }, +} + +impl From for UdpAnnounceError { + fn from(connection_cookie_error: ConnectionCookieError) -> Self { + Self::ConnectionCookieError { + source: connection_cookie_error, + } + } +} + +impl From for UdpAnnounceError { + fn from(announce_error: AnnounceError) -> Self { + Self::TrackerCoreAnnounceError { source: announce_error } + } +} + +impl From for UdpAnnounceError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::TrackerCoreWhitelistError { source: whitelist_error } + } +} + /// It handles the `Announce` request. /// /// # Errors @@ -36,7 +74,17 @@ pub async fn handle_announce( announce_handler: &Arc, whitelist_authorization: &Arc, opt_udp_stats_event_sender: &Arc>>, -) -> Result { + cookie_valid_range: Range, +) -> Result { + // todo: return a UDP response like the HTTP tracker instead of raw AnnounceData. + + // Authentication + check( + &request.connection_id, + gen_remote_fingerprint(&remote_addr), + cookie_valid_range, + )?; + let info_hash = request.info_hash.into(); let remote_client_ip = remote_addr.ip(); diff --git a/src/packages/udp_tracker_core/services/scrape.rs b/src/packages/udp_tracker_core/services/scrape.rs index 07ae452f8..5beb54e9f 100644 --- a/src/packages/udp_tracker_core/services/scrape.rs +++ b/src/packages/udp_tracker_core/services/scrape.rs @@ -8,15 +8,53 @@ //! It also sends an [`udp_tracker_core::statistics::event::Event`] //! because events are specific for the UDP tracker. use std::net::SocketAddr; +use std::ops::Range; use std::sync::Arc; use aquatic_udp_protocol::ScrapeRequest; use bittorrent_primitives::info_hash::InfoHash; -use bittorrent_tracker_core::error::ScrapeError; +use bittorrent_tracker_core::error::{ScrapeError, WhitelistError}; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_primitives::core::ScrapeData; use crate::packages::udp_tracker_core; +use crate::packages::udp_tracker_core::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; + +/// Errors related to scrape requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum UdpScrapeError { + /// Error returned when there was an error with the connection cookie. + #[error("Connection cookie error: {source}")] + ConnectionCookieError { source: ConnectionCookieError }, + + /// Error returned when there was an error with the tracker core scrape handler. + #[error("Tracker core scrape error: {source}")] + TrackerCoreScrapeError { source: ScrapeError }, + + /// Error returned when there was an error with the tracker core whitelist. + #[error("Tracker core whitelist error: {source}")] + TrackerCoreWhitelistError { source: WhitelistError }, +} + +impl From for UdpScrapeError { + fn from(connection_cookie_error: ConnectionCookieError) -> Self { + Self::ConnectionCookieError { + source: connection_cookie_error, + } + } +} + +impl From for UdpScrapeError { + fn from(scrape_error: ScrapeError) -> Self { + Self::TrackerCoreScrapeError { source: scrape_error } + } +} + +impl From for UdpScrapeError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::TrackerCoreWhitelistError { source: whitelist_error } + } +} /// It handles the `Scrape` request. /// @@ -28,7 +66,16 @@ pub async fn handle_scrape( request: &ScrapeRequest, scrape_handler: &Arc, opt_udp_stats_event_sender: &Arc>>, -) -> Result { + cookie_valid_range: Range, +) -> Result { + // todo: return a UDP response like the HTTP tracker instead of raw ScrapeData. + + check( + &request.connection_id, + gen_remote_fingerprint(&remote_addr), + cookie_valid_range, + )?; + // Convert from aquatic infohashes let info_hashes: Vec = request.info_hashes.iter().map(|&x| x.into()).collect(); diff --git a/src/servers/udp/error.rs b/src/servers/udp/error.rs index 81e7847c0..9105ba0cb 100644 --- a/src/servers/udp/error.rs +++ b/src/servers/udp/error.rs @@ -6,7 +6,8 @@ use derive_more::derive::Display; use thiserror::Error; use torrust_tracker_located_error::LocatedError; -use crate::packages::udp_tracker_core::connection_cookie::ConnectionCookieError; +use crate::packages::udp_tracker_core::services::announce::UdpAnnounceError; +use crate::packages::udp_tracker_core::services::scrape::UdpScrapeError; #[derive(Display, Debug)] #[display(":?")] @@ -15,18 +16,17 @@ pub struct ConnectionCookie(pub ConnectionId); /// Error returned by the UDP server. #[derive(Error, Debug)] pub enum Error { - /// Error returned when there was an error with the connection cookie. - #[error("Connection cookie error: {source}")] - ConnectionCookieError { source: ConnectionCookieError }, - + /// Error returned when the request is invalid. #[error("error when phrasing request: {request_parse_error:?}")] RequestParseError { request_parse_error: RequestParseError }, - /// Error returned when the domain tracker returns an error. - #[error("tracker server error: {source}")] - TrackerError { - source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - }, + /// Error returned when the domain tracker returns an announce error. + #[error("tracker announce error: {source}")] + UdpAnnounceError { source: UdpAnnounceError }, + + /// Error returned when the domain tracker returns an scrape error. + #[error("tracker scrape error: {source}")] + UdpScrapeError { source: UdpScrapeError }, /// Error returned from a third-party library (`aquatic_udp_protocol`). #[error("internal server error: {message}, {location}")] @@ -52,10 +52,18 @@ impl From for Error { } } -impl From for Error { - fn from(connection_cookie_error: ConnectionCookieError) -> Self { - Self::ConnectionCookieError { - source: connection_cookie_error, +impl From for Error { + fn from(udp_announce_error: UdpAnnounceError) -> Self { + Self::UdpAnnounceError { + source: udp_announce_error, + } + } +} + +impl From for Error { + fn from(udp_scrape_error: UdpScrapeError) -> Self { + Self::UdpScrapeError { + source: udp_scrape_error, } } } diff --git a/src/servers/udp/handlers/announce.rs b/src/servers/udp/handlers/announce.rs index c9dd15735..48e0d6179 100644 --- a/src/servers/udp/handlers/announce.rs +++ b/src/servers/udp/handlers/announce.rs @@ -14,10 +14,8 @@ use torrust_tracker_configuration::Core; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; -use crate::packages::udp_tracker_core::connection_cookie::check; use crate::packages::udp_tracker_core::{self}; use crate::servers::udp::error::Error; -use crate::servers::udp::handlers::gen_remote_fingerprint; /// It handles the `Announce` request. Refer to [`Announce`](crate::servers::udp#announce) /// request for more information. @@ -43,27 +41,16 @@ pub async fn handle_announce( tracing::trace!("handle announce"); - // todo: move authentication to `udp_tracker_core::services::announce::handle_announce` - - check( - &request.connection_id, - gen_remote_fingerprint(&remote_addr), - cookie_valid_range, - ) - .map_err(|e| (e.into(), request.transaction_id))?; - let response = udp_tracker_core::services::announce::handle_announce( remote_addr, request, announce_handler, whitelist_authorization, opt_udp_stats_event_sender, + cookie_valid_range, ) .await - .map_err(|e| Error::TrackerError { - source: (Arc::new(e) as Arc).into(), - }) - .map_err(|e| (e, request.transaction_id))?; + .map_err(|e| (e.into(), request.transaction_id))?; // todo: extract `build_response` function. @@ -213,15 +200,15 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_configuration::Core; - use crate::packages::udp_tracker_core::connection_cookie::make; + use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use crate::packages::{self, udp_tracker_core}; use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, sample_issue_time, MockUdpStatsEventSender, TorrentPeerBuilder, }; - use crate::servers::udp::handlers::{gen_remote_fingerprint, handle_announce}; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { @@ -447,13 +434,13 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; - use crate::packages::udp_tracker_core::connection_cookie::make; + use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_issue_time, TorrentPeerBuilder, }; - use crate::servers::udp::handlers::{gen_remote_fingerprint, handle_announce}; #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { @@ -520,15 +507,15 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_configuration::Core; - use crate::packages::udp_tracker_core::connection_cookie::make; + use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use crate::packages::{self, udp_tracker_core}; use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, sample_issue_time, MockUdpStatsEventSender, TorrentPeerBuilder, }; - use crate::servers::udp::handlers::{gen_remote_fingerprint, handle_announce}; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { @@ -776,12 +763,12 @@ mod tests { use mockall::predicate::eq; use crate::packages::udp_tracker_core; - use crate::packages::udp_tracker_core::connection_cookie::make; + use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::{ sample_cookie_valid_range, sample_issue_time, MockUdpStatsEventSender, TrackerConfigurationBuilder, }; - use crate::servers::udp::handlers::{gen_remote_fingerprint, handle_announce}; #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { diff --git a/src/servers/udp/handlers/connect.rs b/src/servers/udp/handlers/connect.rs index 799e46347..bd3c4ef0a 100644 --- a/src/servers/udp/handlers/connect.rs +++ b/src/servers/udp/handlers/connect.rs @@ -6,8 +6,7 @@ use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response}; use tracing::{instrument, Level}; use crate::packages::udp_tracker_core; -use crate::packages::udp_tracker_core::connection_cookie::make; -use crate::servers::udp::handlers::gen_remote_fingerprint; +use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; /// It handles the `Connect` request. Refer to [`Connect`](crate::servers::udp#connect) /// request for more information. diff --git a/src/servers/udp/handlers/error.rs b/src/servers/udp/handlers/error.rs index e5529dbdf..6cf273e78 100644 --- a/src/servers/udp/handlers/error.rs +++ b/src/servers/udp/handlers/error.rs @@ -9,9 +9,8 @@ use uuid::Uuid; use zerocopy::network_endian::I32; use crate::packages::udp_tracker_core; -use crate::packages::udp_tracker_core::connection_cookie::check; +use crate::packages::udp_tracker_core::connection_cookie::{check, gen_remote_fingerprint}; use crate::servers::udp::error::Error; -use crate::servers::udp::handlers::gen_remote_fingerprint; use crate::servers::udp::UDP_TRACKER_LOG_TARGET; #[allow(clippy::too_many_arguments)] diff --git a/src/servers/udp/handlers/mod.rs b/src/servers/udp/handlers/mod.rs index 2611931e3..e58497d4b 100644 --- a/src/servers/udp/handlers/mod.rs +++ b/src/servers/udp/handlers/mod.rs @@ -4,7 +4,6 @@ pub mod connect; pub mod error; pub mod scrape; -use std::hash::{DefaultHasher, Hash, Hasher as _}; use std::net::SocketAddr; use std::ops::Range; use std::sync::Arc; @@ -21,6 +20,7 @@ use uuid::Uuid; use super::RawRequest; use crate::container::UdpTrackerContainer; +use crate::packages::udp_tracker_core::services::announce::UdpAnnounceError; use crate::servers::udp::error::Error; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; use crate::CurrentClock; @@ -77,8 +77,11 @@ pub(crate) async fn handle_packet( .await { Ok(response) => return response, - Err((e, transaction_id)) => { - if let Error::ConnectionCookieError { .. } = &e { + Err((error, transaction_id)) => { + if let Error::UdpAnnounceError { + source: UdpAnnounceError::ConnectionCookieError { .. }, + } = error + { // code-review: should we include `RequestParseError` and `BadRequest`? let mut ban_service = udp_tracker_container.ban_service.write().await; ban_service.increase_counter(&udp_request.from.ip()); @@ -90,7 +93,7 @@ pub(crate) async fn handle_packet( request_id, &udp_tracker_container.udp_stats_event_sender, cookie_time_values.valid_range.clone(), - &e, + &error, Some(transaction_id), ) .await @@ -163,13 +166,6 @@ pub async fn handle_request( } } -#[must_use] -pub(crate) fn gen_remote_fingerprint(remote_addr: &SocketAddr) -> u64 { - let mut state = DefaultHasher::new(); - remote_addr.hash(&mut state); - state.finish() -} - #[cfg(test)] pub(crate) mod tests { @@ -194,8 +190,8 @@ pub(crate) mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use super::gen_remote_fingerprint; use crate::packages::udp_tracker_core; + use crate::packages::udp_tracker_core::connection_cookie::gen_remote_fingerprint; use crate::{packages, CurrentClock}; pub(crate) struct CoreTrackerServices { diff --git a/src/servers/udp/handlers/scrape.rs b/src/servers/udp/handlers/scrape.rs index 9bc445417..bca284860 100644 --- a/src/servers/udp/handlers/scrape.rs +++ b/src/servers/udp/handlers/scrape.rs @@ -11,9 +11,7 @@ use tracing::{instrument, Level}; use zerocopy::network_endian::I32; use crate::packages::udp_tracker_core; -use crate::packages::udp_tracker_core::connection_cookie::check; use crate::servers::udp::error::Error; -use crate::servers::udp::handlers::gen_remote_fingerprint; /// It handles the `Scrape` request. Refer to [`Scrape`](crate::servers::udp#scrape) /// request for more information. @@ -35,23 +33,16 @@ pub async fn handle_scrape( tracing::trace!("handle scrape"); - // todo: move authentication to `udp_tracker_core::services::scrape::handle_scrape` - - check( - &request.connection_id, - gen_remote_fingerprint(&remote_addr), + let scrape_data = udp_tracker_core::services::scrape::handle_scrape( + remote_addr, + request, + scrape_handler, + opt_udp_stats_event_sender, cookie_valid_range, ) + .await .map_err(|e| (e.into(), request.transaction_id))?; - let scrape_data = - udp_tracker_core::services::scrape::handle_scrape(remote_addr, request, scrape_handler, opt_udp_stats_event_sender) - .await - .map_err(|e| Error::TrackerError { - source: (Arc::new(e) as Arc).into(), - }) - .map_err(|e| (e, request.transaction_id))?; - // todo: extract `build_response` function. let mut torrent_stats: Vec = Vec::new(); @@ -94,12 +85,12 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::packages; - use crate::packages::udp_tracker_core::connection_cookie::make; + use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, sample_issue_time, TorrentPeerBuilder, }; - use crate::servers::udp::handlers::{gen_remote_fingerprint, handle_scrape}; fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { TorrentScrapeStatistics { diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index 2f0d4e4ce..614db5bf6 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -105,7 +105,7 @@ //! connection ID = hash(client IP + current time slot + secret seed) //! ``` //! -//! The BEP-15 recommends a two-minute time slot. Refer to [`connection_cookie`] +//! The BEP-15 recommends a two-minute time slot. Refer to [`connection_cookie`](crate::packages::udp_tracker_core::connection_cookie) //! for more information about the connection ID generation with this method. //! //! #### Connect Request From 4618f706dba7c53291e3c7366fc4b1ec147d3524 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Feb 2025 09:50:03 +0000 Subject: [PATCH 0772/1297] refactor: exatract response builders for UDP handlers --- src/servers/udp/handlers/announce.rs | 28 ++++++++++++++++++---------- src/servers/udp/handlers/connect.rs | 18 ++++++++++++------ src/servers/udp/handlers/scrape.rs | 7 +++++-- 3 files changed, 35 insertions(+), 18 deletions(-) diff --git a/src/servers/udp/handlers/announce.rs b/src/servers/udp/handlers/announce.rs index 48e0d6179..1003b4041 100644 --- a/src/servers/udp/handlers/announce.rs +++ b/src/servers/udp/handlers/announce.rs @@ -11,6 +11,7 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::Core; +use torrust_tracker_primitives::core::AnnounceData; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; @@ -41,7 +42,7 @@ pub async fn handle_announce( tracing::trace!("handle announce"); - let response = udp_tracker_core::services::announce::handle_announce( + let announce_data = udp_tracker_core::services::announce::handle_announce( remote_addr, request, announce_handler, @@ -52,18 +53,25 @@ pub async fn handle_announce( .await .map_err(|e| (e.into(), request.transaction_id))?; - // todo: extract `build_response` function. + Ok(build_response(remote_addr, request, core_config, &announce_data)) +} +fn build_response( + remote_addr: SocketAddr, + request: &AnnounceRequest, + core_config: &Arc, + announce_data: &AnnounceData, +) -> Response { #[allow(clippy::cast_possible_truncation)] if remote_addr.is_ipv4() { let announce_response = AnnounceResponse { fixed: AnnounceResponseFixedData { transaction_id: request.transaction_id, announce_interval: AnnounceInterval(I32::new(i64::from(core_config.announce_policy.interval) as i32)), - leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), - seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), + leechers: NumberOfPeers(I32::new(i64::from(announce_data.stats.incomplete) as i32)), + seeders: NumberOfPeers(I32::new(i64::from(announce_data.stats.complete) as i32)), }, - peers: response + peers: announce_data .peers .iter() .filter_map(|peer| { @@ -79,16 +87,16 @@ pub async fn handle_announce( .collect(), }; - Ok(Response::from(announce_response)) + Response::from(announce_response) } else { let announce_response = AnnounceResponse { fixed: AnnounceResponseFixedData { transaction_id: request.transaction_id, announce_interval: AnnounceInterval(I32::new(i64::from(core_config.announce_policy.interval) as i32)), - leechers: NumberOfPeers(I32::new(i64::from(response.stats.incomplete) as i32)), - seeders: NumberOfPeers(I32::new(i64::from(response.stats.complete) as i32)), + leechers: NumberOfPeers(I32::new(i64::from(announce_data.stats.incomplete) as i32)), + seeders: NumberOfPeers(I32::new(i64::from(announce_data.stats.complete) as i32)), }, - peers: response + peers: announce_data .peers .iter() .filter_map(|peer| { @@ -104,7 +112,7 @@ pub async fn handle_announce( .collect(), }; - Ok(Response::from(announce_response)) + Response::from(announce_response) } } diff --git a/src/servers/udp/handlers/connect.rs b/src/servers/udp/handlers/connect.rs index bd3c4ef0a..8275d36af 100644 --- a/src/servers/udp/handlers/connect.rs +++ b/src/servers/udp/handlers/connect.rs @@ -2,7 +2,7 @@ use std::net::SocketAddr; use std::sync::Arc; -use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response}; +use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, ConnectionId, Response}; use tracing::{instrument, Level}; use crate::packages::udp_tracker_core; @@ -25,12 +25,9 @@ pub async fn handle_connect( tracing::trace!("handle connect"); - let connection_id = make(gen_remote_fingerprint(&remote_addr), cookie_issue_time).expect("it should be a normal value"); + // todo: move to connect service in udp_tracker_core - let response = ConnectResponse { - transaction_id: request.transaction_id, - connection_id, - }; + let connection_id = make(gen_remote_fingerprint(&remote_addr), cookie_issue_time).expect("it should be a normal value"); if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { match remote_addr { @@ -47,6 +44,15 @@ pub async fn handle_connect( } } + build_response(*request, connection_id) +} + +fn build_response(request: ConnectRequest, connection_id: ConnectionId) -> Response { + let response = ConnectResponse { + transaction_id: request.transaction_id, + connection_id, + }; + Response::from(response) } diff --git a/src/servers/udp/handlers/scrape.rs b/src/servers/udp/handlers/scrape.rs index bca284860..b36eb92a0 100644 --- a/src/servers/udp/handlers/scrape.rs +++ b/src/servers/udp/handlers/scrape.rs @@ -7,6 +7,7 @@ use aquatic_udp_protocol::{ NumberOfDownloads, NumberOfPeers, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use torrust_tracker_primitives::core::ScrapeData; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; @@ -43,8 +44,10 @@ pub async fn handle_scrape( .await .map_err(|e| (e.into(), request.transaction_id))?; - // todo: extract `build_response` function. + Ok(build_response(request, &scrape_data)) +} +fn build_response(request: &ScrapeRequest, scrape_data: &ScrapeData) -> Response { let mut torrent_stats: Vec = Vec::new(); for file in &scrape_data.files { @@ -67,7 +70,7 @@ pub async fn handle_scrape( torrent_stats, }; - Ok(Response::from(response)) + Response::from(response) } #[cfg(test)] From fdc2543f49691b7f5d81698f9c326cd94a78f1cc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Feb 2025 10:08:03 +0000 Subject: [PATCH 0773/1297] refactor: extract UDP connect service --- .../udp_tracker_core/services/connect.rs | 129 ++++++++++++++++++ src/packages/udp_tracker_core/services/mod.rs | 49 +++++++ src/servers/udp/handlers/connect.rs | 26 +--- 3 files changed, 180 insertions(+), 24 deletions(-) create mode 100644 src/packages/udp_tracker_core/services/connect.rs diff --git a/src/packages/udp_tracker_core/services/connect.rs b/src/packages/udp_tracker_core/services/connect.rs new file mode 100644 index 000000000..4cc8b0a3b --- /dev/null +++ b/src/packages/udp_tracker_core/services/connect.rs @@ -0,0 +1,129 @@ +//! The `connect` service. +//! +//! The service is responsible for handling the `connect` requests. +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::ConnectionId; + +use crate::packages::udp_tracker_core; +use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + +/// # Panics +/// +/// IT will panic if there was an error making the connection cookie. +pub async fn handle_connect( + remote_addr: SocketAddr, + opt_udp_stats_event_sender: &Arc>>, + cookie_issue_time: f64, +) -> ConnectionId { + // todo: return a UDP response like the HTTP tracker instead of raw ConnectionId. + + let connection_id = make(gen_remote_fingerprint(&remote_addr), cookie_issue_time).expect("it should be a normal value"); + + if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp4Connect) + .await; + } + SocketAddr::V6(_) => { + udp_stats_event_sender + .send_event(udp_tracker_core::statistics::event::Event::Udp6Connect) + .await; + } + } + } + + connection_id +} + +#[cfg(test)] +mod tests { + + mod connect_request { + + use std::future; + use std::sync::Arc; + + use mockall::predicate::eq; + + use crate::packages::udp_tracker_core::connection_cookie::make; + use crate::packages::udp_tracker_core::services::connect::handle_connect; + use crate::packages::udp_tracker_core::services::tests::{ + sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, + sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpStatsEventSender, + }; + use crate::packages::{self, udp_tracker_core}; + + #[tokio::test] + async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + let response = handle_connect(sample_ipv4_remote_addr(), &udp_stats_event_sender, sample_issue_time()).await; + + assert_eq!( + response, + make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap() + ); + } + + #[tokio::test] + async fn a_connect_response_should_contain_a_new_connection_id() { + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + let response = handle_connect(sample_ipv4_remote_addr(), &udp_stats_event_sender, sample_issue_time()).await; + + assert_eq!( + response, + make(sample_ipv4_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + ); + } + + #[tokio::test] + async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { + let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + let response = handle_connect(sample_ipv6_remote_addr(), &udp_stats_event_sender, sample_issue_time()).await; + + assert_eq!( + response, + make(sample_ipv6_remote_addr_fingerprint(), sample_issue_time()).unwrap(), + ); + } + + #[tokio::test] + async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp4Connect)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + + let client_socket_address = sample_ipv4_socket_address(); + + handle_connect(client_socket_address, &udp_stats_event_sender, sample_issue_time()).await; + } + + #[tokio::test] + async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { + let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + udp_stats_event_sender_mock + .expect_send_event() + .with(eq(udp_tracker_core::statistics::event::Event::Udp6Connect)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + + handle_connect(sample_ipv6_remote_addr(), &udp_stats_event_sender, sample_issue_time()).await; + } + } +} diff --git a/src/packages/udp_tracker_core/services/mod.rs b/src/packages/udp_tracker_core/services/mod.rs index 776d2dfbf..5b222c4d9 100644 --- a/src/packages/udp_tracker_core/services/mod.rs +++ b/src/packages/udp_tracker_core/services/mod.rs @@ -1,2 +1,51 @@ pub mod announce; +pub mod connect; pub mod scrape; + +#[cfg(test)] +pub(crate) mod tests { + + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + + use futures::future::BoxFuture; + use mockall::mock; + use tokio::sync::mpsc::error::SendError; + + use crate::packages::udp_tracker_core; + use crate::packages::udp_tracker_core::connection_cookie::gen_remote_fingerprint; + + pub(crate) fn sample_ipv4_remote_addr() -> SocketAddr { + sample_ipv4_socket_address() + } + + pub(crate) fn sample_ipv4_remote_addr_fingerprint() -> u64 { + gen_remote_fingerprint(&sample_ipv4_socket_address()) + } + + pub(crate) fn sample_ipv6_remote_addr() -> SocketAddr { + sample_ipv6_socket_address() + } + + pub(crate) fn sample_ipv6_remote_addr_fingerprint() -> u64 { + gen_remote_fingerprint(&sample_ipv6_socket_address()) + } + + pub(crate) fn sample_ipv4_socket_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) + } + + fn sample_ipv6_socket_address() -> SocketAddr { + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) + } + + pub(crate) fn sample_issue_time() -> f64 { + 1_000_000_000_f64 + } + + mock! { + pub(crate) UdpStatsEventSender {} + impl udp_tracker_core::statistics::event::sender::Sender for UdpStatsEventSender { + fn send_event(&self, event: udp_tracker_core::statistics::event::Event) -> BoxFuture<'static,Option > > > ; + } + } +} diff --git a/src/servers/udp/handlers/connect.rs b/src/servers/udp/handlers/connect.rs index 8275d36af..aae6a25f5 100644 --- a/src/servers/udp/handlers/connect.rs +++ b/src/servers/udp/handlers/connect.rs @@ -6,14 +6,9 @@ use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, ConnectionId, Respon use tracing::{instrument, Level}; use crate::packages::udp_tracker_core; -use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; /// It handles the `Connect` request. Refer to [`Connect`](crate::servers::udp#connect) /// request for more information. -/// -/// # Errors -/// -/// This function does not ever return an error. #[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_connect( remote_addr: SocketAddr, @@ -22,27 +17,10 @@ pub async fn handle_connect( cookie_issue_time: f64, ) -> Response { tracing::Span::current().record("transaction_id", request.transaction_id.0.to_string()); - tracing::trace!("handle connect"); - // todo: move to connect service in udp_tracker_core - - let connection_id = make(gen_remote_fingerprint(&remote_addr), cookie_issue_time).expect("it should be a normal value"); - - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { - match remote_addr { - SocketAddr::V4(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Connect) - .await; - } - SocketAddr::V6(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Connect) - .await; - } - } - } + let connection_id = + udp_tracker_core::services::connect::handle_connect(remote_addr, opt_udp_stats_event_sender, cookie_issue_time).await; build_response(*request, connection_id) } From fdbe97c2dc33f72bb493e9edcfa0fa54a1ec2027 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Feb 2025 10:42:01 +0000 Subject: [PATCH 0774/1297] chore(deps): udpate dependencies ``` cargo update Updating crates.io index Locking 6 packages to latest compatible versions Updating clap v4.5.29 -> v4.5.30 Updating clap_builder v4.5.29 -> v4.5.30 Updating rand_core v0.9.0 -> v0.9.1 Updating tempfile v3.16.0 -> v3.17.1 Updating typenum v1.17.0 -> v1.18.0 Updating uuid v1.13.1 -> v1.13.2 ``` --- Cargo.lock | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 07c08ab04..0a2a4f9fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -970,9 +970,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.29" +version = "4.5.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8acebd8ad879283633b343856142139f2da2317c96b05b4dd6181c61e2480184" +checksum = "92b7b18d71fad5313a1e320fa9897994228ce274b60faa4d694fe0ea89cd9e6d" dependencies = [ "clap_builder", "clap_derive", @@ -980,9 +980,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.29" +version = "4.5.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6ba32cbda51c7e1dfd49acc1457ba1a7dec5b64fe360e828acb13ca8dc9c2f9" +checksum = "a35db2071778a7344791a4fb4f95308b5673d219dee3ae348b86642574ecc90c" dependencies = [ "anstream", "anstyle", @@ -3175,7 +3175,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" dependencies = [ "rand_chacha 0.9.0", - "rand_core 0.9.0", + "rand_core 0.9.1", "zerocopy 0.8.18", ] @@ -3196,7 +3196,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core 0.9.0", + "rand_core 0.9.1", ] [[package]] @@ -3210,9 +3210,9 @@ dependencies = [ [[package]] name = "rand_core" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b08f3c9802962f7e1b25113931d94f43ed9725bebc59db9d0c3e9a23b67e15ff" +checksum = "a88e0da7a2c97baa202165137c158d0a2e824ac465d13d81046727b34cb247d3" dependencies = [ "getrandom 0.3.1", "zerocopy 0.8.18", @@ -4010,9 +4010,9 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.16.0" +version = "3.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38c246215d7d24f48ae091a2902398798e05d978b24315d6efbc00ede9a8bb91" +checksum = "22e5a0acb1f3f55f65cc4a866c361b2fb2a0ff6366785ae6fbb5f85df07ba230" dependencies = [ "cfg-if", "fastrand", @@ -4640,9 +4640,9 @@ dependencies = [ [[package]] name = "typenum" -version = "1.17.0" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" +checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" [[package]] name = "uncased" @@ -4703,9 +4703,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ced87ca4be083373936a67f8de945faa23b6b42384bd5b64434850802c6dccd0" +checksum = "8c1f41ffb7cf259f1ecc2876861a17e7142e63ead296f671f81f6ae85903e0d6" dependencies = [ "getrandom 0.3.1", "rand 0.9.0", From 84cf581f8c7417f9670c2101bcaf9149a91aba4c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Feb 2025 11:46:08 +0000 Subject: [PATCH 0775/1297] refactor: [#1282] move BanService to udp-tracker-core package --- src/bootstrap/app.rs | 2 +- src/container.rs | 5 +++-- src/packages/tracker_api_core/statistics/services.rs | 7 ++++--- .../udp_tracker_core/services}/banning.rs | 0 src/packages/udp_tracker_core/services/mod.rs | 1 + src/packages/udp_tracker_core/statistics/services.rs | 4 ++-- src/servers/apis/v1/context/stats/handlers.rs | 2 +- src/servers/udp/server/mod.rs | 1 - 8 files changed, 12 insertions(+), 10 deletions(-) rename src/{servers/udp/server => packages/udp_tracker_core/services}/banning.rs (100%) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 41023f2fa..b7ce8f21c 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -35,8 +35,8 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; use crate::container::AppContainer; +use crate::packages::udp_tracker_core::services::banning::BanService; use crate::packages::{http_tracker_core, udp_tracker_core}; -use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; use crate::shared::crypto::ephemeral_instance_keys; use crate::shared::crypto::keys::{self, Keeper as _}; diff --git a/src/container.rs b/src/container.rs index 47cc39ed3..d62f8d985 100644 --- a/src/container.rs +++ b/src/container.rs @@ -14,8 +14,9 @@ use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; -use crate::packages::{http_tracker_core, udp_tracker_core}; -use crate::servers::udp::server::banning::BanService; +use crate::packages::http_tracker_core; +use crate::packages::udp_tracker_core::services::banning::BanService; +use crate::packages::udp_tracker_core::{self}; pub struct AppContainer { pub core_config: Arc, diff --git a/src/packages/tracker_api_core/statistics/services.rs b/src/packages/tracker_api_core/statistics/services.rs index bb8e71ab8..15f976b52 100644 --- a/src/packages/tracker_api_core/statistics/services.rs +++ b/src/packages/tracker_api_core/statistics/services.rs @@ -5,8 +5,9 @@ use packages::tracker_api_core::statistics::metrics::Metrics; use tokio::sync::RwLock; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use crate::packages::{self, http_tracker_core, udp_tracker_core}; -use crate::servers::udp::server::banning::BanService; +use crate::packages::udp_tracker_core::services::banning::BanService; +use crate::packages::udp_tracker_core::{self}; +use crate::packages::{self, http_tracker_core}; /// All the metrics collected by the tracker. #[derive(Debug, PartialEq)] @@ -83,8 +84,8 @@ mod tests { use crate::packages::tracker_api_core::statistics::metrics::Metrics; use crate::packages::tracker_api_core::statistics::services::{get_metrics, TrackerMetrics}; + use crate::packages::udp_tracker_core::services::banning::BanService; use crate::packages::{http_tracker_core, udp_tracker_core}; - use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; pub fn tracker_configuration() -> Configuration { diff --git a/src/servers/udp/server/banning.rs b/src/packages/udp_tracker_core/services/banning.rs similarity index 100% rename from src/servers/udp/server/banning.rs rename to src/packages/udp_tracker_core/services/banning.rs diff --git a/src/packages/udp_tracker_core/services/mod.rs b/src/packages/udp_tracker_core/services/mod.rs index 5b222c4d9..5c7c760c8 100644 --- a/src/packages/udp_tracker_core/services/mod.rs +++ b/src/packages/udp_tracker_core/services/mod.rs @@ -1,4 +1,5 @@ pub mod announce; +pub mod banning; pub mod connect; pub mod scrape; diff --git a/src/packages/udp_tracker_core/statistics/services.rs b/src/packages/udp_tracker_core/statistics/services.rs index 80e1d8fb5..63279bc9a 100644 --- a/src/packages/udp_tracker_core/statistics/services.rs +++ b/src/packages/udp_tracker_core/statistics/services.rs @@ -45,7 +45,7 @@ use tokio::sync::RwLock; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use crate::packages; -use crate::servers::udp::server::banning::BanService; +use crate::packages::udp_tracker_core::services::banning::BanService; /// All the metrics collected by the tracker. #[derive(Debug, PartialEq)] @@ -111,9 +111,9 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::packages::udp_tracker_core; + use crate::packages::udp_tracker_core::services::banning::BanService; use crate::packages::udp_tracker_core::statistics; use crate::packages::udp_tracker_core::statistics::services::{get_metrics, TrackerMetrics}; - use crate::servers::udp::server::banning::BanService; use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; pub fn tracker_configuration() -> Configuration { diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index 820f39909..287bca5d1 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -11,8 +11,8 @@ use tokio::sync::RwLock; use super::responses::{metrics_response, stats_response}; use crate::packages::tracker_api_core::statistics::services::get_metrics; +use crate::packages::udp_tracker_core::services::banning::BanService; use crate::packages::{http_tracker_core, udp_tracker_core}; -use crate::servers::udp::server::banning::BanService; #[derive(Deserialize, Debug, Default)] #[serde(rename_all = "lowercase")] diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 941f6b5cb..2be568c89 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -6,7 +6,6 @@ use thiserror::Error; use super::RawRequest; -pub mod banning; pub mod bound_socket; pub mod launcher; pub mod processor; From 1886593b465b2a7c4b4a51eee08b3f5adce38394 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Feb 2025 12:50:51 +0000 Subject: [PATCH 0776/1297] refactor: [#1282] extract udp-tracker-core package --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 29 +- Cargo.toml | 5 +- packages/udp-tracker-core/Cargo.toml | 36 + packages/udp-tracker-core/LICENSE | 661 ++++++++++++++++++ packages/udp-tracker-core/README.md | 15 + .../src}/connection_cookie.rs | 6 +- .../src}/crypto/ephemeral_instance_keys.rs | 11 +- .../udp-tracker-core/src}/crypto/keys.rs | 24 +- .../udp-tracker-core/src}/crypto/mod.rs | 0 packages/udp-tracker-core/src/lib.rs | 13 + .../src}/services/announce.rs | 16 +- .../udp-tracker-core/src}/services/banning.rs | 2 +- .../udp-tracker-core/src}/services/connect.rs | 36 +- .../udp-tracker-core/src}/services/mod.rs | 8 +- .../udp-tracker-core/src}/services/scrape.rs | 14 +- .../src}/statistics/event/handler.rs | 14 +- .../src}/statistics/event/listener.rs | 2 +- .../src}/statistics/event/mod.rs | 0 .../src}/statistics/event/sender.rs | 4 +- .../src}/statistics/keeper.rs | 6 +- .../src}/statistics/metrics.rs | 0 .../udp-tracker-core/src}/statistics/mod.rs | 0 .../src}/statistics/repository.rs | 0 .../src}/statistics/services.rs | 26 +- .../udp-tracker-core/src}/statistics/setup.rs | 6 +- src/bootstrap/app.rs | 12 +- src/bootstrap/jobs/udp_tracker.rs | 2 +- src/console/ci/e2e/logs_parser.rs | 2 +- src/container.rs | 12 +- src/lib.rs | 3 - src/packages/mod.rs | 1 - .../tracker_api_core/statistics/services.rs | 14 +- src/packages/udp_tracker_core/mod.rs | 3 - src/servers/apis/v1/context/stats/handlers.rs | 6 +- src/servers/udp/error.rs | 5 +- src/servers/udp/handlers/announce.rs | 38 +- src/servers/udp/handlers/connect.rs | 26 +- src/servers/udp/handlers/error.rs | 15 +- src/servers/udp/handlers/mod.rs | 16 +- src/servers/udp/handlers/scrape.rs | 24 +- src/servers/udp/mod.rs | 4 +- src/servers/udp/server/bound_socket.rs | 3 +- src/servers/udp/server/launcher.rs | 18 +- src/servers/udp/server/processor.rs | 16 +- src/servers/udp/server/request_buffer.rs | 3 +- src/servers/udp/server/states.rs | 2 +- src/shared/mod.rs | 2 - tests/servers/udp/environment.rs | 4 +- 49 files changed, 937 insertions(+), 229 deletions(-) create mode 100644 packages/udp-tracker-core/Cargo.toml create mode 100644 packages/udp-tracker-core/LICENSE create mode 100644 packages/udp-tracker-core/README.md rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/connection_cookie.rs (98%) rename {src/shared => packages/udp-tracker-core/src}/crypto/ephemeral_instance_keys.rs (69%) rename {src/shared => packages/udp-tracker-core/src}/crypto/keys.rs (78%) rename {src/shared => packages/udp-tracker-core/src}/crypto/mod.rs (100%) create mode 100644 packages/udp-tracker-core/src/lib.rs rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/services/announce.rs (86%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/services/banning.rs (98%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/services/connect.rs (74%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/services/mod.rs (74%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/services/scrape.rs (83%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/statistics/event/handler.rs (92%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/statistics/event/listener.rs (79%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/statistics/event/mod.rs (100%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/statistics/event/sender.rs (79%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/statistics/keeper.rs (90%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/statistics/metrics.rs (100%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/statistics/mod.rs (100%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/statistics/repository.rs (100%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/statistics/services.rs (81%) rename {src/packages/udp_tracker_core => packages/udp-tracker-core/src}/statistics/setup.rs (79%) delete mode 100644 src/packages/udp_tracker_core/mod.rs diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 328bd91bb..cd4887cbe 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -59,6 +59,7 @@ jobs: cargo publish -p bittorrent-tracker-client cargo publish -p bittorrent-tracker-core cargo publish -p bittorrent-udp-protocol + cargo publish -p bittorrent-udp-tracker-core cargo publish -p torrust-tracker cargo publish -p torrust-tracker-api-client cargo publish -p torrust-tracker-client diff --git a/Cargo.lock b/Cargo.lock index 0a2a4f9fe..2835cd5c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -643,6 +643,30 @@ dependencies = [ "torrust-tracker-primitives", ] +[[package]] +name = "bittorrent-udp-tracker-core" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "bittorrent-primitives", + "bittorrent-tracker-core", + "bittorrent-udp-protocol", + "bloom", + "blowfish", + "cipher", + "futures", + "lazy_static", + "mockall", + "rand 0.8.5", + "thiserror 2.0.11", + "tokio", + "torrust-tracker-configuration", + "torrust-tracker-primitives", + "torrust-tracker-test-helpers", + "tracing", + "zerocopy 0.7.35", +] + [[package]] name = "bitvec" version = "1.0.1" @@ -4310,12 +4334,9 @@ dependencies = [ "bittorrent-primitives", "bittorrent-tracker-client", "bittorrent-tracker-core", - "bittorrent-udp-protocol", - "bloom", - "blowfish", + "bittorrent-udp-tracker-core", "camino", "chrono", - "cipher", "clap", "crossbeam-skiplist", "dashmap", diff --git a/Cargo.toml b/Cargo.toml index 7337b49af..b72baea5b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,12 +43,9 @@ bittorrent-http-protocol = { version = "3.0.0-develop", path = "packages/http-pr bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker-core" } -bittorrent-udp-protocol = { version = "3.0.0-develop", path = "packages/udp-protocol" } -bloom = "0.3.2" -blowfish = "0" +bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "packages/udp-tracker-core" } camino = { version = "1", features = ["serde", "serde1"] } chrono = { version = "0", default-features = false, features = ["clock"] } -cipher = "0" clap = { version = "4", features = ["derive", "env"] } crossbeam-skiplist = "0" dashmap = "6" diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml new file mode 100644 index 000000000..bfa840cc3 --- /dev/null +++ b/packages/udp-tracker-core/Cargo.toml @@ -0,0 +1,36 @@ +[package] +authors.workspace = true +description = "A library with the core functionality needed to implement a BitTorrent UDP tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = ["api", "bittorrent", "core", "library", "tracker"] +license.workspace = true +name = "bittorrent-udp-tracker-core" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +bittorrent-udp-protocol = { version = "3.0.0-develop", path = "../udp-protocol" } +bloom = "0.3.2" +blowfish = "0" +cipher = "0" +futures = "0" +lazy_static = "1" +rand = "0" +thiserror = "2" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tracing = "0" +zerocopy = "0.7" + +[dev-dependencies] +mockall = "0" +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/udp-tracker-core/LICENSE b/packages/udp-tracker-core/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/udp-tracker-core/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/udp-tracker-core/README.md b/packages/udp-tracker-core/README.md new file mode 100644 index 000000000..625e5d011 --- /dev/null +++ b/packages/udp-tracker-core/README.md @@ -0,0 +1,15 @@ +# BitTorrent UDP Tracker Core library + +A library with the core functionality needed to implement a BitTorrent UDP tracker. + +You usually don’t need to use this library directly. Instead, you should use the [Torrust Tracker](https://github.com/torrust/torrust-tracker). If you want to build your own tracker, you can use this library as the core functionality. + +> **Disclaimer**: This library is actively under development. We’re currently extracting and refining common types from the[Torrust Tracker](https://github.com/torrust/torrust-tracker) to make them available to the BitTorrent community in Rust. While these types are functional, they are not yet ready for use in production or third-party projects. + +## Documentation + +[Crate documentation](https://docs.rs/bittorrent-udp-tracker-core). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/src/packages/udp_tracker_core/connection_cookie.rs b/packages/udp-tracker-core/src/connection_cookie.rs similarity index 98% rename from src/packages/udp_tracker_core/connection_cookie.rs rename to packages/udp-tracker-core/src/connection_cookie.rs index b9070c63a..31c116400 100644 --- a/src/packages/udp_tracker_core/connection_cookie.rs +++ b/packages/udp-tracker-core/src/connection_cookie.rs @@ -83,7 +83,7 @@ use thiserror::Error; use tracing::instrument; use zerocopy::AsBytes; -use crate::shared::crypto::keys::CipherArrayBlowfish; +use crate::crypto::keys::CipherArrayBlowfish; /// Error returned when there was an error with the connection cookie. #[derive(Error, Debug, Clone)] @@ -169,7 +169,7 @@ pub fn check(cookie: &Cookie, fingerprint: u64, valid_range: Range) -> Resu } #[must_use] -pub(crate) fn gen_remote_fingerprint(remote_addr: &SocketAddr) -> u64 { +pub fn gen_remote_fingerprint(remote_addr: &SocketAddr) -> u64 { let mut state = DefaultHasher::new(); remote_addr.hash(&mut state); state.finish() @@ -183,7 +183,7 @@ mod cookie_builder { pub type CookiePlainText = CipherArrayBlowfish; pub type CookieCipherText = CipherArrayBlowfish; - use crate::shared::crypto::keys::{CipherArrayBlowfish, Current, Keeper}; + use crate::crypto::keys::{CipherArrayBlowfish, Current, Keeper}; #[instrument()] pub(super) fn assemble(fingerprint: u64, issue_at: f64) -> CookiePlainText { diff --git a/src/shared/crypto/ephemeral_instance_keys.rs b/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs similarity index 69% rename from src/shared/crypto/ephemeral_instance_keys.rs rename to packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs index df560c3f5..fcbf78288 100644 --- a/src/shared/crypto/ephemeral_instance_keys.rs +++ b/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs @@ -15,10 +15,17 @@ pub type CipherArrayBlowfish = GenericArray() + }; /// The random cipher from the seed. - pub static ref RANDOM_CIPHER_BLOWFISH: CipherBlowfish = CipherBlowfish::new_from_slice(&Rng::random::(&mut ThreadRng::default())).expect("it could not generate key"); + pub static ref RANDOM_CIPHER_BLOWFISH: CipherBlowfish = { + let mut rng = ThreadRng::default(); + let seed: Seed = rng.gen(); + CipherBlowfish::new_from_slice(&seed).expect("it could not generate key") + }; /// The constant cipher for testing. pub static ref ZEROED_TEST_CIPHER_BLOWFISH: CipherBlowfish = CipherBlowfish::new_from_slice(&[0u8; 32]).expect("it could not generate key"); diff --git a/src/shared/crypto/keys.rs b/packages/udp-tracker-core/src/crypto/keys.rs similarity index 78% rename from src/shared/crypto/keys.rs rename to packages/udp-tracker-core/src/crypto/keys.rs index 60dc16660..f9a3e361d 100644 --- a/src/shared/crypto/keys.rs +++ b/packages/udp-tracker-core/src/crypto/keys.rs @@ -7,8 +7,8 @@ use self::detail_cipher::CURRENT_CIPHER; use self::detail_seed::CURRENT_SEED; -pub use crate::shared::crypto::ephemeral_instance_keys::CipherArrayBlowfish; -use crate::shared::crypto::ephemeral_instance_keys::{CipherBlowfish, Seed, RANDOM_CIPHER_BLOWFISH, RANDOM_SEED}; +pub use crate::crypto::ephemeral_instance_keys::CipherArrayBlowfish; +use crate::crypto::ephemeral_instance_keys::{CipherBlowfish, Seed, RANDOM_CIPHER_BLOWFISH, RANDOM_SEED}; /// This trait is for structures that can keep and provide a seed. pub trait Keeper { @@ -61,7 +61,7 @@ mod tests { use super::detail_seed::ZEROED_TEST_SEED; use super::{Current, Instance, Keeper}; - use crate::shared::crypto::ephemeral_instance_keys::{CipherBlowfish, Seed, ZEROED_TEST_CIPHER_BLOWFISH}; + use crate::crypto::ephemeral_instance_keys::{CipherBlowfish, Seed, ZEROED_TEST_CIPHER_BLOWFISH}; pub struct ZeroedTest; @@ -91,7 +91,7 @@ mod tests { } mod detail_seed { - use crate::shared::crypto::ephemeral_instance_keys::Seed; + use crate::crypto::ephemeral_instance_keys::Seed; #[allow(dead_code)] pub const ZEROED_TEST_SEED: Seed = [0u8; 32]; @@ -100,13 +100,13 @@ mod detail_seed { pub use ZEROED_TEST_SEED as CURRENT_SEED; #[cfg(not(test))] - pub use crate::shared::crypto::ephemeral_instance_keys::RANDOM_SEED as CURRENT_SEED; + pub use crate::crypto::ephemeral_instance_keys::RANDOM_SEED as CURRENT_SEED; #[cfg(test)] mod tests { - use crate::shared::crypto::ephemeral_instance_keys::RANDOM_SEED; - use crate::shared::crypto::keys::detail_seed::ZEROED_TEST_SEED; - use crate::shared::crypto::keys::CURRENT_SEED; + use crate::crypto::ephemeral_instance_keys::RANDOM_SEED; + use crate::crypto::keys::detail_seed::ZEROED_TEST_SEED; + use crate::crypto::keys::CURRENT_SEED; #[test] fn it_should_have_a_zero_test_seed() { @@ -129,16 +129,16 @@ mod detail_seed { mod detail_cipher { #[allow(unused_imports)] #[cfg(not(test))] - pub use crate::shared::crypto::ephemeral_instance_keys::RANDOM_CIPHER_BLOWFISH as CURRENT_CIPHER; + pub use crate::crypto::ephemeral_instance_keys::RANDOM_CIPHER_BLOWFISH as CURRENT_CIPHER; #[cfg(test)] - pub use crate::shared::crypto::ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH as CURRENT_CIPHER; + pub use crate::crypto::ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH as CURRENT_CIPHER; #[cfg(test)] mod tests { use cipher::BlockEncrypt; - use crate::shared::crypto::ephemeral_instance_keys::{CipherArrayBlowfish, ZEROED_TEST_CIPHER_BLOWFISH}; - use crate::shared::crypto::keys::detail_cipher::CURRENT_CIPHER; + use crate::crypto::ephemeral_instance_keys::{CipherArrayBlowfish, ZEROED_TEST_CIPHER_BLOWFISH}; + use crate::crypto::keys::detail_cipher::CURRENT_CIPHER; #[test] fn it_should_default_to_zeroed_seed_when_testing() { diff --git a/src/shared/crypto/mod.rs b/packages/udp-tracker-core/src/crypto/mod.rs similarity index 100% rename from src/shared/crypto/mod.rs rename to packages/udp-tracker-core/src/crypto/mod.rs diff --git a/packages/udp-tracker-core/src/lib.rs b/packages/udp-tracker-core/src/lib.rs new file mode 100644 index 000000000..8283e08c5 --- /dev/null +++ b/packages/udp-tracker-core/src/lib.rs @@ -0,0 +1,13 @@ +pub mod connection_cookie; +pub mod crypto; +pub mod services; +pub mod statistics; + +#[macro_use] +extern crate lazy_static; + +/// The maximum number of connection id errors per ip. Clients will be banned if +/// they exceed this limit. +pub const MAX_CONNECTION_ID_ERRORS_PER_IP: u32 = 10; + +pub const UDP_TRACKER_LOG_TARGET: &str = "UDP TRACKER"; diff --git a/src/packages/udp_tracker_core/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs similarity index 86% rename from src/packages/udp_tracker_core/services/announce.rs rename to packages/udp-tracker-core/src/services/announce.rs index a825d06ad..be47b9136 100644 --- a/src/packages/udp_tracker_core/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -20,8 +20,8 @@ use bittorrent_udp_protocol::peer_builder; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; -use crate::packages::udp_tracker_core::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; -use crate::packages::udp_tracker_core::{self}; +use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; +use crate::statistics; /// Errors related to announce requests. #[derive(thiserror::Error, Debug, Clone)] @@ -73,7 +73,7 @@ pub async fn handle_announce( request: &AnnounceRequest, announce_handler: &Arc, whitelist_authorization: &Arc, - opt_udp_stats_event_sender: &Arc>>, + opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { // todo: return a UDP response like the HTTP tracker instead of raw AnnounceData. @@ -105,12 +105,12 @@ pub async fn handle_announce( match original_peer_ip { IpAddr::V4(_) => { udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Announce) + .send_event(statistics::event::Event::Udp4Announce) .await; } IpAddr::V6(_) => { udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Announce) + .send_event(statistics::event::Event::Udp6Announce) .await; } } @@ -124,7 +124,7 @@ pub async fn handle_announce( /// It will return an error if the announce request fails. pub async fn invoke( announce_handler: Arc, - opt_udp_stats_event_sender: Arc>>, + opt_udp_stats_event_sender: Arc>>, info_hash: InfoHash, peer: &mut peer::Peer, peers_wanted: &PeersWanted, @@ -140,12 +140,12 @@ pub async fn invoke( match original_peer_ip { IpAddr::V4(_) => { udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Announce) + .send_event(statistics::event::Event::Udp4Announce) .await; } IpAddr::V6(_) => { udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Announce) + .send_event(statistics::event::Event::Udp6Announce) .await; } } diff --git a/src/packages/udp_tracker_core/services/banning.rs b/packages/udp-tracker-core/src/services/banning.rs similarity index 98% rename from src/packages/udp_tracker_core/services/banning.rs rename to packages/udp-tracker-core/src/services/banning.rs index d32dfa541..8f63dd804 100644 --- a/src/packages/udp_tracker_core/services/banning.rs +++ b/packages/udp-tracker-core/src/services/banning.rs @@ -21,7 +21,7 @@ use std::net::IpAddr; use bloom::{CountingBloomFilter, ASMS}; use tokio::time::Instant; -use crate::servers::udp::UDP_TRACKER_LOG_TARGET; +use crate::UDP_TRACKER_LOG_TARGET; pub struct BanService { max_connection_id_errors_per_ip: u32, diff --git a/src/packages/udp_tracker_core/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs similarity index 74% rename from src/packages/udp_tracker_core/services/connect.rs rename to packages/udp-tracker-core/src/services/connect.rs index 4cc8b0a3b..9cb419bbc 100644 --- a/src/packages/udp_tracker_core/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -6,15 +6,15 @@ use std::sync::Arc; use aquatic_udp_protocol::ConnectionId; -use crate::packages::udp_tracker_core; -use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; +use crate::connection_cookie::{gen_remote_fingerprint, make}; +use crate::statistics; /// # Panics /// /// IT will panic if there was an error making the connection cookie. pub async fn handle_connect( remote_addr: SocketAddr, - opt_udp_stats_event_sender: &Arc>>, + opt_udp_stats_event_sender: &Arc>>, cookie_issue_time: f64, ) -> ConnectionId { // todo: return a UDP response like the HTTP tracker instead of raw ConnectionId. @@ -24,14 +24,10 @@ pub async fn handle_connect( if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { match remote_addr { SocketAddr::V4(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Connect) - .await; + udp_stats_event_sender.send_event(statistics::event::Event::Udp4Connect).await; } SocketAddr::V6(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Connect) - .await; + udp_stats_event_sender.send_event(statistics::event::Event::Udp6Connect).await; } } } @@ -49,17 +45,17 @@ mod tests { use mockall::predicate::eq; - use crate::packages::udp_tracker_core::connection_cookie::make; - use crate::packages::udp_tracker_core::services::connect::handle_connect; - use crate::packages::udp_tracker_core::services::tests::{ + use crate::connection_cookie::make; + use crate::services::connect::handle_connect; + use crate::services::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpStatsEventSender, }; - use crate::packages::{self, udp_tracker_core}; + use crate::statistics; #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let (udp_stats_event_sender, _udp_stats_repository) = statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); let response = handle_connect(sample_ipv4_remote_addr(), &udp_stats_event_sender, sample_issue_time()).await; @@ -72,7 +68,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let (udp_stats_event_sender, _udp_stats_repository) = statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); let response = handle_connect(sample_ipv4_remote_addr(), &udp_stats_event_sender, sample_issue_time()).await; @@ -85,7 +81,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let (udp_stats_event_sender, _udp_stats_repository) = statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); let response = handle_connect(sample_ipv6_remote_addr(), &udp_stats_event_sender, sample_issue_time()).await; @@ -101,10 +97,10 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp4Connect)) + .with(eq(statistics::event::Event::Udp4Connect)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = + let udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); let client_socket_address = sample_ipv4_socket_address(); @@ -117,10 +113,10 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp6Connect)) + .with(eq(statistics::event::Event::Udp6Connect)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = + let udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); handle_connect(sample_ipv6_remote_addr(), &udp_stats_event_sender, sample_issue_time()).await; diff --git a/src/packages/udp_tracker_core/services/mod.rs b/packages/udp-tracker-core/src/services/mod.rs similarity index 74% rename from src/packages/udp_tracker_core/services/mod.rs rename to packages/udp-tracker-core/src/services/mod.rs index 5c7c760c8..0fcb612e4 100644 --- a/src/packages/udp_tracker_core/services/mod.rs +++ b/packages/udp-tracker-core/src/services/mod.rs @@ -12,8 +12,8 @@ pub(crate) mod tests { use mockall::mock; use tokio::sync::mpsc::error::SendError; - use crate::packages::udp_tracker_core; - use crate::packages::udp_tracker_core::connection_cookie::gen_remote_fingerprint; + use crate::connection_cookie::gen_remote_fingerprint; + use crate::statistics; pub(crate) fn sample_ipv4_remote_addr() -> SocketAddr { sample_ipv4_socket_address() @@ -45,8 +45,8 @@ pub(crate) mod tests { mock! { pub(crate) UdpStatsEventSender {} - impl udp_tracker_core::statistics::event::sender::Sender for UdpStatsEventSender { - fn send_event(&self, event: udp_tracker_core::statistics::event::Event) -> BoxFuture<'static,Option > > > ; + impl statistics::event::sender::Sender for UdpStatsEventSender { + fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } } diff --git a/src/packages/udp_tracker_core/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs similarity index 83% rename from src/packages/udp_tracker_core/services/scrape.rs rename to packages/udp-tracker-core/src/services/scrape.rs index 5beb54e9f..bec55afe3 100644 --- a/src/packages/udp_tracker_core/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -17,8 +17,8 @@ use bittorrent_tracker_core::error::{ScrapeError, WhitelistError}; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_primitives::core::ScrapeData; -use crate::packages::udp_tracker_core; -use crate::packages::udp_tracker_core::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; +use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; +use crate::statistics; /// Errors related to scrape requests. #[derive(thiserror::Error, Debug, Clone)] @@ -65,7 +65,7 @@ pub async fn handle_scrape( remote_addr: SocketAddr, request: &ScrapeRequest, scrape_handler: &Arc, - opt_udp_stats_event_sender: &Arc>>, + opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { // todo: return a UDP response like the HTTP tracker instead of raw ScrapeData. @@ -84,14 +84,10 @@ pub async fn handle_scrape( if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { match remote_addr { SocketAddr::V4(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Scrape) - .await; + udp_stats_event_sender.send_event(statistics::event::Event::Udp4Scrape).await; } SocketAddr::V6(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Scrape) - .await; + udp_stats_event_sender.send_event(statistics::event::Event::Udp6Scrape).await; } } } diff --git a/src/packages/udp_tracker_core/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs similarity index 92% rename from src/packages/udp_tracker_core/statistics/event/handler.rs rename to packages/udp-tracker-core/src/statistics/event/handler.rs index d8fa049d0..91be32ad1 100644 --- a/src/packages/udp_tracker_core/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -1,5 +1,5 @@ -use crate::packages::udp_tracker_core::statistics::event::{Event, UdpResponseKind}; -use crate::packages::udp_tracker_core::statistics::repository::Repository; +use crate::statistics::event::{Event, UdpResponseKind}; +use crate::statistics::repository::Repository; pub async fn handle_event(event: Event, stats_repository: &Repository) { match event { @@ -82,9 +82,9 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { #[cfg(test)] mod tests { - use crate::packages::udp_tracker_core::statistics::event::handler::handle_event; - use crate::packages::udp_tracker_core::statistics::event::Event; - use crate::packages::udp_tracker_core::statistics::repository::Repository; + use crate::statistics::event::handler::handle_event; + use crate::statistics::event::Event; + use crate::statistics::repository::Repository; #[tokio::test] async fn should_increase_the_udp4_connections_counter_when_it_receives_a_udp4_connect_event() { @@ -186,7 +186,7 @@ mod tests { handle_event( Event::Udp4Response { - kind: crate::packages::udp_tracker_core::statistics::event::UdpResponseKind::Announce, + kind: crate::statistics::event::UdpResponseKind::Announce, req_processing_time: std::time::Duration::from_secs(1), }, &stats_repository, @@ -226,7 +226,7 @@ mod tests { handle_event( Event::Udp6Response { - kind: crate::packages::udp_tracker_core::statistics::event::UdpResponseKind::Announce, + kind: crate::statistics::event::UdpResponseKind::Announce, req_processing_time: std::time::Duration::from_secs(1), }, &stats_repository, diff --git a/src/packages/udp_tracker_core/statistics/event/listener.rs b/packages/udp-tracker-core/src/statistics/event/listener.rs similarity index 79% rename from src/packages/udp_tracker_core/statistics/event/listener.rs rename to packages/udp-tracker-core/src/statistics/event/listener.rs index 6a84fbaa5..f1a2e25de 100644 --- a/src/packages/udp_tracker_core/statistics/event/listener.rs +++ b/packages/udp-tracker-core/src/statistics/event/listener.rs @@ -2,7 +2,7 @@ use tokio::sync::mpsc; use super::handler::handle_event; use super::Event; -use crate::packages::udp_tracker_core::statistics::repository::Repository; +use crate::statistics::repository::Repository; pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) { while let Some(event) = receiver.recv().await { diff --git a/src/packages/udp_tracker_core/statistics/event/mod.rs b/packages/udp-tracker-core/src/statistics/event/mod.rs similarity index 100% rename from src/packages/udp_tracker_core/statistics/event/mod.rs rename to packages/udp-tracker-core/src/statistics/event/mod.rs diff --git a/src/packages/udp_tracker_core/statistics/event/sender.rs b/packages/udp-tracker-core/src/statistics/event/sender.rs similarity index 79% rename from src/packages/udp_tracker_core/statistics/event/sender.rs rename to packages/udp-tracker-core/src/statistics/event/sender.rs index 68e197eca..ca4b4e210 100644 --- a/src/packages/udp_tracker_core/statistics/event/sender.rs +++ b/packages/udp-tracker-core/src/statistics/event/sender.rs @@ -13,10 +13,10 @@ pub trait Sender: Sync + Send { fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; } -/// An [`statistics::EventSender`](crate::packages::udp_tracker_core::statistics::event::sender::Sender) implementation. +/// An [`statistics::EventSender`](crate::statistics::event::sender::Sender) implementation. /// /// It uses a channel sender to send the statistic events. The channel is created by a -/// [`statistics::Keeper`](crate::packages::udp_tracker_core::statistics::keeper::Keeper) +/// [`statistics::Keeper`](crate::statistics::keeper::Keeper) #[allow(clippy::module_name_repetitions)] pub struct ChannelSender { pub(crate) sender: mpsc::Sender, diff --git a/src/packages/udp_tracker_core/statistics/keeper.rs b/packages/udp-tracker-core/src/statistics/keeper.rs similarity index 90% rename from src/packages/udp_tracker_core/statistics/keeper.rs rename to packages/udp-tracker-core/src/statistics/keeper.rs index 9bd290145..dac7e7541 100644 --- a/src/packages/udp_tracker_core/statistics/keeper.rs +++ b/packages/udp-tracker-core/src/statistics/keeper.rs @@ -51,9 +51,9 @@ impl Keeper { #[cfg(test)] mod tests { - use crate::packages::udp_tracker_core::statistics::event::Event; - use crate::packages::udp_tracker_core::statistics::keeper::Keeper; - use crate::packages::udp_tracker_core::statistics::metrics::Metrics; + use crate::statistics::event::Event; + use crate::statistics::keeper::Keeper; + use crate::statistics::metrics::Metrics; #[tokio::test] async fn should_contain_the_tracker_statistics() { diff --git a/src/packages/udp_tracker_core/statistics/metrics.rs b/packages/udp-tracker-core/src/statistics/metrics.rs similarity index 100% rename from src/packages/udp_tracker_core/statistics/metrics.rs rename to packages/udp-tracker-core/src/statistics/metrics.rs diff --git a/src/packages/udp_tracker_core/statistics/mod.rs b/packages/udp-tracker-core/src/statistics/mod.rs similarity index 100% rename from src/packages/udp_tracker_core/statistics/mod.rs rename to packages/udp-tracker-core/src/statistics/mod.rs diff --git a/src/packages/udp_tracker_core/statistics/repository.rs b/packages/udp-tracker-core/src/statistics/repository.rs similarity index 100% rename from src/packages/udp_tracker_core/statistics/repository.rs rename to packages/udp-tracker-core/src/statistics/repository.rs diff --git a/src/packages/udp_tracker_core/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs similarity index 81% rename from src/packages/udp_tracker_core/statistics/services.rs rename to packages/udp-tracker-core/src/statistics/services.rs index 63279bc9a..486aaac06 100644 --- a/src/packages/udp_tracker_core/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -2,14 +2,14 @@ //! //! It includes: //! -//! - A [`factory`](crate::packages::udp_tracker_core::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. -//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::packages::udp_tracker_core::statistics::metrics::Metrics). +//! - A [`factory`](crate::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::statistics::metrics::Metrics). //! //! Tracker metrics are collected using a Publisher-Subscribe pattern. //! //! The factory function builds two structs: //! -//! - An statistics event [`Sender`](crate::packages::udp_tracker_core::statistics::event::sender::Sender) +//! - An statistics event [`Sender`](crate::statistics::event::sender::Sender) //! - An statistics [`Repository`] //! //! ```text @@ -21,7 +21,7 @@ //! There is an event listener that is receiving all the events and processing them with an event handler. //! Then, the event handler updates the metrics depending on the received event. //! -//! For example, if you send the event [`Event::Udp4Connect`](crate::packages::udp_tracker_core::statistics::event::Event::Udp4Connect): +//! For example, if you send the event [`Event::Udp4Connect`](crate::statistics::event::Event::Udp4Connect): //! //! ```text //! let result = event_sender.send_event(Event::Udp4Connect).await; @@ -39,13 +39,12 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use packages::udp_tracker_core::statistics::metrics::Metrics; -use packages::udp_tracker_core::statistics::repository::Repository; use tokio::sync::RwLock; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use crate::packages; -use crate::packages::udp_tracker_core::services::banning::BanService; +use crate::services::banning::BanService; +use crate::statistics::metrics::Metrics; +use crate::statistics::repository::Repository; /// All the metrics collected by the tracker. #[derive(Debug, PartialEq)] @@ -110,11 +109,9 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; - use crate::packages::udp_tracker_core; - use crate::packages::udp_tracker_core::services::banning::BanService; - use crate::packages::udp_tracker_core::statistics; - use crate::packages::udp_tracker_core::statistics::services::{get_metrics, TrackerMetrics}; - use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; + use crate::services::banning::BanService; + use crate::statistics::services::{get_metrics, TrackerMetrics}; + use crate::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -127,8 +124,7 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let (_udp_stats_event_sender, udp_stats_repository) = - udp_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let (_udp_stats_event_sender, udp_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let udp_stats_repository = Arc::new(udp_stats_repository); let tracker_metrics = get_metrics( diff --git a/src/packages/udp_tracker_core/statistics/setup.rs b/packages/udp-tracker-core/src/statistics/setup.rs similarity index 79% rename from src/packages/udp_tracker_core/statistics/setup.rs rename to packages/udp-tracker-core/src/statistics/setup.rs index c85c715a2..d3114a75e 100644 --- a/src/packages/udp_tracker_core/statistics/setup.rs +++ b/packages/udp-tracker-core/src/statistics/setup.rs @@ -1,14 +1,14 @@ //! Setup for the tracker statistics. //! //! The [`factory`] function builds the structs needed for handling the tracker metrics. -use crate::packages::udp_tracker_core::statistics; +use crate::statistics; /// It builds the structs needed for handling the tracker metrics. /// /// It returns: /// -/// - An statistics event [`Sender`](crate::packages::udp_tracker_core::statistics::event::sender::Sender) that allows you to send events related to statistics. -/// - An statistics [`Repository`](crate::packages::udp_tracker_core::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. +/// - An statistics event [`Sender`](crate::statistics::event::sender::Sender) that allows you to send events related to statistics. +/// - An statistics [`Repository`](crate::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. /// /// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics /// events are sent are received but not dispatched to the handler. diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index b7ce8f21c..9247f76bb 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -26,6 +26,10 @@ use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentT use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager; +use bittorrent_udp_tracker_core::crypto::ephemeral_instance_keys; +use bittorrent_udp_tracker_core::crypto::keys::{self, Keeper as _}; +use bittorrent_udp_tracker_core::services::banning::BanService; +use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use tokio::sync::RwLock; use torrust_tracker_clock::static_time; use torrust_tracker_configuration::validator::Validator; @@ -35,11 +39,7 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; use crate::container::AppContainer; -use crate::packages::udp_tracker_core::services::banning::BanService; -use crate::packages::{http_tracker_core, udp_tracker_core}; -use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; -use crate::shared::crypto::ephemeral_instance_keys; -use crate::shared::crypto::keys::{self, Keeper as _}; +use crate::packages::http_tracker_core; /// It loads the configuration from the environment and builds app container. /// @@ -99,7 +99,7 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { // UDP stats let (udp_stats_event_sender, udp_stats_repository) = - udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); let udp_stats_repository = Arc::new(udp_stats_repository); diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 387fdd6ae..03fe396d6 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -8,6 +8,7 @@ //! > for the configuration options. use std::sync::Arc; +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use tokio::task::JoinHandle; use tracing::instrument; @@ -15,7 +16,6 @@ use crate::container::UdpTrackerContainer; use crate::servers::registar::ServiceRegistrationForm; use crate::servers::udp::server::spawner::Spawner; use crate::servers::udp::server::Server; -use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// It starts a new UDP server with the provided configuration. /// diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index b39143c8f..8f7f6059d 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -1,11 +1,11 @@ //! Utilities to parse Torrust Tracker logs. +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use regex::Regex; use serde::{Deserialize, Serialize}; use crate::servers::health_check_api::HEALTH_CHECK_API_LOG_TARGET; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; use crate::servers::logging::STARTED_ON; -use crate::servers::udp::UDP_TRACKER_LOG_TARGET; const INFO_THRESHOLD: &str = "INFO"; diff --git a/src/container.rs b/src/container.rs index d62f8d985..d4e46b116 100644 --- a/src/container.rs +++ b/src/container.rs @@ -11,12 +11,12 @@ use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentT use bittorrent_tracker_core::whitelist; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use bittorrent_udp_tracker_core::services::banning::BanService; +use bittorrent_udp_tracker_core::{self}; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; use crate::packages::http_tracker_core; -use crate::packages::udp_tracker_core::services::banning::BanService; -use crate::packages::udp_tracker_core::{self}; pub struct AppContainer { pub core_config: Arc, @@ -29,9 +29,9 @@ pub struct AppContainer { pub whitelist_authorization: Arc, pub ban_service: Arc>, pub http_stats_event_sender: Arc>>, - pub udp_stats_event_sender: Arc>>, + pub udp_stats_event_sender: Arc>>, pub http_stats_repository: Arc, - pub udp_stats_repository: Arc, + pub udp_stats_repository: Arc, pub whitelist_manager: Arc, pub in_memory_torrent_repository: Arc, pub db_torrent_repository: Arc, @@ -44,7 +44,7 @@ pub struct UdpTrackerContainer { pub announce_handler: Arc, pub scrape_handler: Arc, pub whitelist_authorization: Arc, - pub udp_stats_event_sender: Arc>>, + pub udp_stats_event_sender: Arc>>, pub ban_service: Arc>, } @@ -96,7 +96,7 @@ pub struct HttpApiContainer { pub whitelist_manager: Arc, pub ban_service: Arc>, pub http_stats_repository: Arc, - pub udp_stats_repository: Arc, + pub udp_stats_repository: Arc, } impl HttpApiContainer { diff --git a/src/lib.rs b/src/lib.rs index b9ab402ab..210c88c14 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -498,9 +498,6 @@ pub mod packages; pub mod servers; pub mod shared; -#[macro_use] -extern crate lazy_static; - /// This code needs to be copied into each crate. /// Working version, for production. #[cfg(not(test))] diff --git a/src/packages/mod.rs b/src/packages/mod.rs index 453c3d533..f00f1ace0 100644 --- a/src/packages/mod.rs +++ b/src/packages/mod.rs @@ -3,4 +3,3 @@ //! It will be moved to the directory `packages`. pub mod http_tracker_core; pub mod tracker_api_core; -pub mod udp_tracker_core; diff --git a/src/packages/tracker_api_core/statistics/services.rs b/src/packages/tracker_api_core/statistics/services.rs index 15f976b52..d94ff5bf7 100644 --- a/src/packages/tracker_api_core/statistics/services.rs +++ b/src/packages/tracker_api_core/statistics/services.rs @@ -1,12 +1,12 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_udp_tracker_core::services::banning::BanService; +use bittorrent_udp_tracker_core::{self, statistics}; use packages::tracker_api_core::statistics::metrics::Metrics; use tokio::sync::RwLock; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use crate::packages::udp_tracker_core::services::banning::BanService; -use crate::packages::udp_tracker_core::{self}; use crate::packages::{self, http_tracker_core}; /// All the metrics collected by the tracker. @@ -28,7 +28,7 @@ pub async fn get_metrics( in_memory_torrent_repository: Arc, ban_service: Arc>, http_stats_repository: Arc, - udp_stats_repository: Arc, + udp_stats_repository: Arc, ) -> TrackerMetrics { let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); @@ -77,16 +77,16 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self}; + use bittorrent_udp_tracker_core::services::banning::BanService; + use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use tokio::sync::RwLock; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; + use crate::packages::http_tracker_core; use crate::packages::tracker_api_core::statistics::metrics::Metrics; use crate::packages::tracker_api_core::statistics::services::{get_metrics, TrackerMetrics}; - use crate::packages::udp_tracker_core::services::banning::BanService; - use crate::packages::{http_tracker_core, udp_tracker_core}; - use crate::servers::udp::server::launcher::MAX_CONNECTION_ID_ERRORS_PER_IP; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -106,7 +106,7 @@ mod tests { // UDP stats let (_udp_stats_event_sender, udp_stats_repository) = - udp_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + bittorrent_udp_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); let udp_stats_repository = Arc::new(udp_stats_repository); let tracker_metrics = get_metrics( diff --git a/src/packages/udp_tracker_core/mod.rs b/src/packages/udp_tracker_core/mod.rs deleted file mode 100644 index 1c93f811a..000000000 --- a/src/packages/udp_tracker_core/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod connection_cookie; -pub mod services; -pub mod statistics; diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index 287bca5d1..62379b6f4 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -6,13 +6,13 @@ use axum::extract::State; use axum::response::Response; use axum_extra::extract::Query; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_udp_tracker_core::services::banning::BanService; use serde::Deserialize; use tokio::sync::RwLock; use super::responses::{metrics_response, stats_response}; +use crate::packages::http_tracker_core; use crate::packages::tracker_api_core::statistics::services::get_metrics; -use crate::packages::udp_tracker_core::services::banning::BanService; -use crate::packages::{http_tracker_core, udp_tracker_core}; #[derive(Deserialize, Debug, Default)] #[serde(rename_all = "lowercase")] @@ -44,7 +44,7 @@ pub async fn get_stats_handler( Arc, Arc>, Arc, - Arc, + Arc, )>, params: Query, ) -> Response { diff --git a/src/servers/udp/error.rs b/src/servers/udp/error.rs index 9105ba0cb..93caf6853 100644 --- a/src/servers/udp/error.rs +++ b/src/servers/udp/error.rs @@ -2,13 +2,12 @@ use std::panic::Location; use aquatic_udp_protocol::{ConnectionId, RequestParseError}; +use bittorrent_udp_tracker_core::services::announce::UdpAnnounceError; +use bittorrent_udp_tracker_core::services::scrape::UdpScrapeError; use derive_more::derive::Display; use thiserror::Error; use torrust_tracker_located_error::LocatedError; -use crate::packages::udp_tracker_core::services::announce::UdpAnnounceError; -use crate::packages::udp_tracker_core::services::scrape::UdpScrapeError; - #[derive(Display, Debug)] #[display(":?")] pub struct ConnectionCookie(pub ConnectionId); diff --git a/src/servers/udp/handlers/announce.rs b/src/servers/udp/handlers/announce.rs index 1003b4041..66fc0ab42 100644 --- a/src/servers/udp/handlers/announce.rs +++ b/src/servers/udp/handlers/announce.rs @@ -10,12 +10,12 @@ use aquatic_udp_protocol::{ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::whitelist; +use bittorrent_udp_tracker_core::{services, statistics}; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; -use crate::packages::udp_tracker_core::{self}; use crate::servers::udp::error::Error; /// It handles the `Announce` request. Refer to [`Announce`](crate::servers::udp#announce) @@ -32,7 +32,7 @@ pub async fn handle_announce( core_config: &Arc, announce_handler: &Arc, whitelist_authorization: &Arc, - opt_udp_stats_event_sender: &Arc>>, + opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { tracing::Span::current() @@ -42,7 +42,7 @@ pub async fn handle_announce( tracing::trace!("handle announce"); - let announce_data = udp_tracker_core::services::announce::handle_announce( + let announce_data = services::announce::handle_announce( remote_addr, request, announce_handler, @@ -128,8 +128,8 @@ mod tests { AnnounceActionPlaceholder, AnnounceEvent, AnnounceRequest, ConnectionId, NumberOfBytes, NumberOfPeers, PeerId as AquaticPeerId, PeerKey, Port, TransactionId, }; + use bittorrent_udp_tracker_core::connection_cookie::make; - use crate::packages::udp_tracker_core::connection_cookie::make; use crate::servers::udp::handlers::tests::{sample_ipv4_remote_addr_fingerprint, sample_issue_time}; struct AnnounceRequestBuilder { @@ -205,11 +205,11 @@ mod tests { use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist; + use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use bittorrent_udp_tracker_core::statistics; use mockall::predicate::eq; use torrust_tracker_configuration::Core; - use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; - use crate::packages::{self, udp_tracker_core}; use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::{ @@ -366,7 +366,7 @@ mod tests { whitelist_authorization: Arc, ) -> Response { let (udp_stats_event_sender, _udp_stats_repository) = - packages::udp_tracker_core::statistics::setup::factory(false); + bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); @@ -414,10 +414,10 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp4Announce)) + .with(eq(statistics::event::Event::Udp4Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = + let udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); let (core_tracker_services, _core_udp_tracker_services) = @@ -441,8 +441,8 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; + use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; - use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::{ @@ -512,11 +512,11 @@ mod tests { use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist; + use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use bittorrent_udp_tracker_core::statistics; use mockall::predicate::eq; use torrust_tracker_configuration::Core; - use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; - use crate::packages::{self, udp_tracker_core}; use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::{ @@ -677,7 +677,7 @@ mod tests { whitelist_authorization: Arc, ) -> Response { let (udp_stats_event_sender, _udp_stats_repository) = - packages::udp_tracker_core::statistics::setup::factory(false); + bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); @@ -728,10 +728,10 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp6Announce)) + .with(eq(statistics::event::Event::Udp6Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = + let udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); let (core_tracker_services, _core_udp_tracker_services) = @@ -768,10 +768,10 @@ mod tests { use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use bittorrent_udp_tracker_core::{self, statistics}; use mockall::predicate::eq; - use crate::packages::udp_tracker_core; - use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::servers::udp::handlers::handle_announce; use crate::servers::udp::handlers::tests::{ @@ -792,10 +792,10 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp6Announce)) + .with(eq(statistics::event::Event::Udp6Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = + let udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); let announce_handler = Arc::new(AnnounceHandler::new( diff --git a/src/servers/udp/handlers/connect.rs b/src/servers/udp/handlers/connect.rs index aae6a25f5..b9209a115 100644 --- a/src/servers/udp/handlers/connect.rs +++ b/src/servers/udp/handlers/connect.rs @@ -3,24 +3,22 @@ use std::net::SocketAddr; use std::sync::Arc; use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, ConnectionId, Response}; +use bittorrent_udp_tracker_core::{services, statistics}; use tracing::{instrument, Level}; -use crate::packages::udp_tracker_core; - /// It handles the `Connect` request. Refer to [`Connect`](crate::servers::udp#connect) /// request for more information. #[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_connect( remote_addr: SocketAddr, request: &ConnectRequest, - opt_udp_stats_event_sender: &Arc>>, + opt_udp_stats_event_sender: &Arc>>, cookie_issue_time: f64, ) -> Response { tracing::Span::current().record("transaction_id", request.transaction_id.0.to_string()); tracing::trace!("handle connect"); - let connection_id = - udp_tracker_core::services::connect::handle_connect(remote_addr, opt_udp_stats_event_sender, cookie_issue_time).await; + let connection_id = services::connect::handle_connect(remote_addr, opt_udp_stats_event_sender, cookie_issue_time).await; build_response(*request, connection_id) } @@ -43,10 +41,10 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; + use bittorrent_udp_tracker_core::connection_cookie::make; + use bittorrent_udp_tracker_core::statistics; use mockall::predicate::eq; - use crate::packages::udp_tracker_core::connection_cookie::make; - use crate::packages::{self, udp_tracker_core}; use crate::servers::udp::handlers::handle_connect; use crate::servers::udp::handlers::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, @@ -61,7 +59,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let (udp_stats_event_sender, _udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); let request = ConnectRequest { @@ -87,7 +85,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let (udp_stats_event_sender, _udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); let request = ConnectRequest { @@ -113,7 +111,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let (udp_stats_event_sender, _udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); let request = ConnectRequest { @@ -142,10 +140,10 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp4Connect)) + .with(eq(statistics::event::Event::Udp4Connect)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = + let udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); let client_socket_address = sample_ipv4_socket_address(); @@ -164,10 +162,10 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp6Connect)) + .with(eq(statistics::event::Event::Udp6Connect)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = + let udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); handle_connect( diff --git a/src/servers/udp/handlers/error.rs b/src/servers/udp/handlers/error.rs index 6cf273e78..443f36cc0 100644 --- a/src/servers/udp/handlers/error.rs +++ b/src/servers/udp/handlers/error.rs @@ -4,14 +4,13 @@ use std::ops::Range; use std::sync::Arc; use aquatic_udp_protocol::{ErrorResponse, RequestParseError, Response, TransactionId}; +use bittorrent_udp_tracker_core::connection_cookie::{check, gen_remote_fingerprint}; +use bittorrent_udp_tracker_core::{self, statistics, UDP_TRACKER_LOG_TARGET}; use tracing::{instrument, Level}; use uuid::Uuid; use zerocopy::network_endian::I32; -use crate::packages::udp_tracker_core; -use crate::packages::udp_tracker_core::connection_cookie::{check, gen_remote_fingerprint}; use crate::servers::udp::error::Error; -use crate::servers::udp::UDP_TRACKER_LOG_TARGET; #[allow(clippy::too_many_arguments)] #[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] @@ -19,7 +18,7 @@ pub async fn handle_error( remote_addr: SocketAddr, local_addr: SocketAddr, request_id: Uuid, - opt_udp_stats_event_sender: &Arc>>, + opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, e: &Error, transaction_id: Option, @@ -59,14 +58,10 @@ pub async fn handle_error( if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { match remote_addr { SocketAddr::V4(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Error) - .await; + udp_stats_event_sender.send_event(statistics::event::Event::Udp4Error).await; } SocketAddr::V6(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Error) - .await; + udp_stats_event_sender.send_event(statistics::event::Event::Udp6Error).await; } } } diff --git a/src/servers/udp/handlers/mod.rs b/src/servers/udp/handlers/mod.rs index e58497d4b..3d378b525 100644 --- a/src/servers/udp/handlers/mod.rs +++ b/src/servers/udp/handlers/mod.rs @@ -11,6 +11,7 @@ use std::time::Instant; use announce::handle_announce; use aquatic_udp_protocol::{Request, Response, TransactionId}; +use bittorrent_udp_tracker_core::services::announce::UdpAnnounceError; use connect::handle_connect; use error::handle_error; use scrape::handle_scrape; @@ -20,7 +21,6 @@ use uuid::Uuid; use super::RawRequest; use crate::container::UdpTrackerContainer; -use crate::packages::udp_tracker_core::services::announce::UdpAnnounceError; use crate::servers::udp::error::Error; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; use crate::CurrentClock; @@ -182,6 +182,8 @@ pub(crate) mod tests { use bittorrent_tracker_core::whitelist; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use bittorrent_udp_tracker_core::connection_cookie::gen_remote_fingerprint; + use bittorrent_udp_tracker_core::{self, statistics}; use futures::future::BoxFuture; use mockall::mock; use tokio::sync::mpsc::error::SendError; @@ -190,9 +192,7 @@ pub(crate) mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::packages::udp_tracker_core; - use crate::packages::udp_tracker_core::connection_cookie::gen_remote_fingerprint; - use crate::{packages, CurrentClock}; + use crate::CurrentClock; pub(crate) struct CoreTrackerServices { pub core_config: Arc, @@ -204,7 +204,7 @@ pub(crate) mod tests { } pub(crate) struct CoreUdpTrackerServices { - pub udp_stats_event_sender: Arc>>, + pub udp_stats_event_sender: Arc>>, } fn default_testing_tracker_configuration() -> Configuration { @@ -239,7 +239,7 @@ pub(crate) mod tests { )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let (udp_stats_event_sender, _udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); ( @@ -357,8 +357,8 @@ pub(crate) mod tests { mock! { pub(crate) UdpStatsEventSender {} - impl udp_tracker_core::statistics::event::sender::Sender for UdpStatsEventSender { - fn send_event(&self, event: udp_tracker_core::statistics::event::Event) -> BoxFuture<'static,Option > > > ; + impl statistics::event::sender::Sender for UdpStatsEventSender { + fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } } diff --git a/src/servers/udp/handlers/scrape.rs b/src/servers/udp/handlers/scrape.rs index b36eb92a0..aa7287951 100644 --- a/src/servers/udp/handlers/scrape.rs +++ b/src/servers/udp/handlers/scrape.rs @@ -7,11 +7,12 @@ use aquatic_udp_protocol::{ NumberOfDownloads, NumberOfPeers, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use bittorrent_udp_tracker_core::statistics::{self}; +use bittorrent_udp_tracker_core::{self, services}; use torrust_tracker_primitives::core::ScrapeData; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; -use crate::packages::udp_tracker_core; use crate::servers::udp::error::Error; /// It handles the `Scrape` request. Refer to [`Scrape`](crate::servers::udp#scrape) @@ -25,7 +26,7 @@ pub async fn handle_scrape( remote_addr: SocketAddr, request: &ScrapeRequest, scrape_handler: &Arc, - opt_udp_stats_event_sender: &Arc>>, + opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { tracing::Span::current() @@ -34,7 +35,7 @@ pub async fn handle_scrape( tracing::trace!("handle scrape"); - let scrape_data = udp_tracker_core::services::scrape::handle_scrape( + let scrape_data = services::scrape::handle_scrape( remote_addr, request, scrape_handler, @@ -86,9 +87,8 @@ mod tests { }; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; - use crate::packages; - use crate::packages::udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, @@ -169,7 +169,7 @@ mod tests { in_memory_torrent_repository: Arc, scrape_handler: Arc, ) -> Response { - let (udp_stats_event_sender, _udp_stats_repository) = packages::udp_tracker_core::statistics::setup::factory(false); + let (udp_stats_event_sender, _udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); let remote_addr = sample_ipv4_remote_addr(); @@ -328,10 +328,10 @@ mod tests { use std::future; use std::sync::Arc; + use bittorrent_udp_tracker_core::statistics; use mockall::predicate::eq; use super::sample_scrape_request; - use crate::packages::udp_tracker_core; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, @@ -343,10 +343,10 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp4Scrape)) + .with(eq(statistics::event::Event::Udp4Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = + let udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); let remote_addr = sample_ipv4_remote_addr(); @@ -370,10 +370,10 @@ mod tests { use std::future; use std::sync::Arc; + use bittorrent_udp_tracker_core::statistics; use mockall::predicate::eq; use super::sample_scrape_request; - use crate::packages::udp_tracker_core; use crate::servers::udp::handlers::handle_scrape; use crate::servers::udp::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, @@ -385,10 +385,10 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(udp_tracker_core::statistics::event::Event::Udp6Scrape)) + .with(eq(statistics::event::Event::Udp6Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = + let udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); let remote_addr = sample_ipv6_remote_addr(); diff --git a/src/servers/udp/mod.rs b/src/servers/udp/mod.rs index 614db5bf6..1fcd49725 100644 --- a/src/servers/udp/mod.rs +++ b/src/servers/udp/mod.rs @@ -105,7 +105,7 @@ //! connection ID = hash(client IP + current time slot + secret seed) //! ``` //! -//! The BEP-15 recommends a two-minute time slot. Refer to [`connection_cookie`](crate::packages::udp_tracker_core::connection_cookie) +//! The BEP-15 recommends a two-minute time slot. Refer to [`connection_cookie`](bittorrent_udp_tracker_core::connection_cookie) //! for more information about the connection ID generation with this method. //! //! #### Connect Request @@ -641,8 +641,6 @@ pub mod error; pub mod handlers; pub mod server; -pub const UDP_TRACKER_LOG_TARGET: &str = "UDP TRACKER"; - /// Number of bytes. pub type Bytes = u64; /// The port the peer is listening on. diff --git a/src/servers/udp/server/bound_socket.rs b/src/servers/udp/server/bound_socket.rs index 658589aa6..988bfb67f 100644 --- a/src/servers/udp/server/bound_socket.rs +++ b/src/servers/udp/server/bound_socket.rs @@ -2,10 +2,9 @@ use std::fmt::Debug; use std::net::SocketAddr; use std::ops::Deref; +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use url::Url; -use crate::servers::udp::UDP_TRACKER_LOG_TARGET; - /// Wrapper for Tokio [`UdpSocket`][`tokio::net::UdpSocket`] that is bound to a particular socket. pub struct BoundSocket { socket: tokio::net::UdpSocket, diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index e640749c6..fb0033624 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use std::time::Duration; use bittorrent_tracker_client::udp::client::check; +use bittorrent_udp_tracker_core::{self, statistics, UDP_TRACKER_LOG_TARGET}; use derive_more::Constructor; use futures_util::StreamExt; use tokio::select; @@ -13,18 +14,13 @@ use tracing::instrument; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; use crate::container::UdpTrackerContainer; -use crate::packages::udp_tracker_core; use crate::servers::logging::STARTED_ON; use crate::servers::registar::ServiceHealthCheckJob; use crate::servers::signals::{shutdown_signal_with_message, Halted}; use crate::servers::udp::server::bound_socket::BoundSocket; use crate::servers::udp::server::processor::Processor; use crate::servers::udp::server::receiver::Receiver; -use crate::servers::udp::UDP_TRACKER_LOG_TARGET; -/// The maximum number of connection id errors per ip. Clients will be banned if -/// they exceed this limit. -pub const MAX_CONNECTION_ID_ERRORS_PER_IP: u32 = 10; const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 3600; /// A UDP server instance launcher. @@ -165,14 +161,10 @@ impl Launcher { if let Some(udp_stats_event_sender) = udp_tracker_container.udp_stats_event_sender.as_deref() { match req.from.ip() { IpAddr::V4(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Request) - .await; + udp_stats_event_sender.send_event(statistics::event::Event::Udp4Request).await; } IpAddr::V6(_) => { - udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Request) - .await; + udp_stats_event_sender.send_event(statistics::event::Event::Udp6Request).await; } } } @@ -182,7 +174,7 @@ impl Launcher { if let Some(udp_stats_event_sender) = udp_tracker_container.udp_stats_event_sender.as_deref() { udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::UdpRequestBanned) + .send_event(statistics::event::Event::UdpRequestBanned) .await; } @@ -215,7 +207,7 @@ impl Launcher { if let Some(udp_stats_event_sender) = udp_tracker_container.udp_stats_event_sender.as_deref() { udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::UdpRequestAborted) + .send_event(statistics::event::Event::UdpRequestAborted) .await; } } diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index dc55833c2..af4c68770 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -4,12 +4,12 @@ use std::sync::Arc; use std::time::Duration; use aquatic_udp_protocol::Response; +use bittorrent_udp_tracker_core::{self, statistics}; use tokio::time::Instant; use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; use crate::container::UdpTrackerContainer; -use crate::packages::udp_tracker_core; use crate::servers::udp::handlers::CookieTimeValues; use crate::servers::udp::{handlers, RawRequest}; @@ -60,12 +60,10 @@ impl Processor { }; let udp_response_kind = match &response { - Response::Connect(_) => udp_tracker_core::statistics::event::UdpResponseKind::Connect, - Response::AnnounceIpv4(_) | Response::AnnounceIpv6(_) => { - udp_tracker_core::statistics::event::UdpResponseKind::Announce - } - Response::Scrape(_) => udp_tracker_core::statistics::event::UdpResponseKind::Scrape, - Response::Error(_e) => udp_tracker_core::statistics::event::UdpResponseKind::Error, + Response::Connect(_) => statistics::event::UdpResponseKind::Connect, + Response::AnnounceIpv4(_) | Response::AnnounceIpv6(_) => statistics::event::UdpResponseKind::Announce, + Response::Scrape(_) => statistics::event::UdpResponseKind::Scrape, + Response::Error(_e) => statistics::event::UdpResponseKind::Error, }; let mut writer = Cursor::new(Vec::with_capacity(200)); @@ -87,7 +85,7 @@ impl Processor { match target.ip() { IpAddr::V4(_) => { udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp4Response { + .send_event(statistics::event::Event::Udp4Response { kind: udp_response_kind, req_processing_time, }) @@ -95,7 +93,7 @@ impl Processor { } IpAddr::V6(_) => { udp_stats_event_sender - .send_event(udp_tracker_core::statistics::event::Event::Udp6Response { + .send_event(statistics::event::Event::Udp6Response { kind: udp_response_kind, req_processing_time, }) diff --git a/src/servers/udp/server/request_buffer.rs b/src/servers/udp/server/request_buffer.rs index 03cb6040f..6e420306e 100644 --- a/src/servers/udp/server/request_buffer.rs +++ b/src/servers/udp/server/request_buffer.rs @@ -1,9 +1,8 @@ +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use ringbuf::traits::{Consumer, Observer, Producer}; use ringbuf::StaticRb; use tokio::task::AbortHandle; -use crate::servers::udp::UDP_TRACKER_LOG_TARGET; - /// A ring buffer for managing active UDP request abort handles. /// /// The `ActiveRequests` struct maintains a fixed-size ring buffer of abort diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index abce9720a..c74c7f4db 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -3,6 +3,7 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use derive_more::derive::Display; use derive_more::Constructor; use tokio::task::JoinHandle; @@ -15,7 +16,6 @@ use crate::container::UdpTrackerContainer; use crate::servers::registar::{ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::Halted; use crate::servers::udp::server::launcher::Launcher; -use crate::servers::udp::UDP_TRACKER_LOG_TARGET; /// A UDP server instance controller with no UDP instance running. #[allow(clippy::module_name_repetitions)] diff --git a/src/shared/mod.rs b/src/shared/mod.rs index 8c95effe1..3b4a46e67 100644 --- a/src/shared/mod.rs +++ b/src/shared/mod.rs @@ -1,6 +1,4 @@ //! Modules with generic logic used by several modules. //! //! - [`bit_torrent`]: `BitTorrent` protocol related logic. -//! - [`crypto`]: Encryption related logic. pub mod bit_torrent; -pub mod crypto; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 24ce7bab2..7a6992583 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -4,10 +4,10 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::databases::Database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_udp_tracker_core::statistics; use torrust_tracker_configuration::{Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::container::UdpTrackerContainer; -use torrust_tracker_lib::packages::udp_tracker_core; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; @@ -22,7 +22,7 @@ where pub database: Arc>, pub in_memory_torrent_repository: Arc, - pub udp_stats_repository: Arc, + pub udp_stats_repository: Arc, pub registar: Registar, pub server: Server, From 8958609385e95b380fee464ccd98d356836e0722 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Feb 2025 15:57:40 +0000 Subject: [PATCH 0777/1297] refactor: [#1281] extract http-tracker-core package --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 18 + Cargo.toml | 1 + packages/http-tracker-core/Cargo.toml | 29 + packages/http-tracker-core/LICENSE | 661 ++++++++++++++++++ packages/http-tracker-core/README.md | 15 + packages/http-tracker-core/src/lib.rs | 17 + .../src}/services/announce.rs | 39 +- .../http-tracker-core/src}/services/mod.rs | 0 .../http-tracker-core/src}/services/scrape.rs | 66 +- .../src}/statistics/event/handler.rs | 10 +- .../src}/statistics/event/listener.rs | 2 +- .../src}/statistics/event/mod.rs | 0 .../src}/statistics/event/sender.rs | 4 +- .../src}/statistics/keeper.rs | 6 +- .../src}/statistics/metrics.rs | 0 .../http-tracker-core/src}/statistics/mod.rs | 0 .../src}/statistics/repository.rs | 0 .../src}/statistics/services.rs | 18 +- .../src}/statistics/setup.rs | 6 +- src/bootstrap/app.rs | 3 +- src/container.rs | 10 +- src/packages/http_tracker_core/mod.rs | 2 - src/packages/mod.rs | 1 - .../tracker_api_core/statistics/services.rs | 7 +- src/servers/apis/v1/context/stats/handlers.rs | 3 +- src/servers/http/v1/handlers/announce.rs | 16 +- src/servers/http/v1/handlers/scrape.rs | 17 +- tests/servers/http/environment.rs | 3 +- 29 files changed, 836 insertions(+), 119 deletions(-) create mode 100644 packages/http-tracker-core/Cargo.toml create mode 100644 packages/http-tracker-core/LICENSE create mode 100644 packages/http-tracker-core/README.md create mode 100644 packages/http-tracker-core/src/lib.rs rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/services/announce.rs (89%) rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/services/mod.rs (100%) rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/services/scrape.rs (84%) rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/statistics/event/handler.rs (90%) rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/statistics/event/listener.rs (79%) rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/statistics/event/mod.rs (100%) rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/statistics/event/sender.rs (79%) rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/statistics/keeper.rs (90%) rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/statistics/metrics.rs (100%) rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/statistics/mod.rs (100%) rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/statistics/repository.rs (100%) rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/statistics/services.rs (80%) rename {src/packages/http_tracker_core => packages/http-tracker-core/src}/statistics/setup.rs (79%) delete mode 100644 src/packages/http_tracker_core/mod.rs diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index cd4887cbe..7b718bccf 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -56,6 +56,7 @@ jobs: CARGO_REGISTRY_TOKEN: "${{ secrets.TORRUST_UPDATE_CARGO_REGISTRY_TOKEN }}" run: | cargo publish -p bittorrent-http-protocol + cargo publish -p bittorrent-http-tracker-core cargo publish -p bittorrent-tracker-client cargo publish -p bittorrent-tracker-core cargo publish -p bittorrent-udp-protocol diff --git a/Cargo.lock b/Cargo.lock index 2835cd5c1..73f7dfb88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -567,6 +567,23 @@ dependencies = [ "torrust-tracker-primitives", ] +[[package]] +name = "bittorrent-http-tracker-core" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "bittorrent-http-protocol", + "bittorrent-primitives", + "bittorrent-tracker-core", + "futures", + "mockall", + "tokio", + "torrust-tracker-configuration", + "torrust-tracker-primitives", + "torrust-tracker-test-helpers", + "tracing", +] + [[package]] name = "bittorrent-primitives" version = "0.1.0" @@ -4331,6 +4348,7 @@ dependencies = [ "axum-extra", "axum-server", "bittorrent-http-protocol", + "bittorrent-http-tracker-core", "bittorrent-primitives", "bittorrent-tracker-client", "bittorrent-tracker-core", diff --git a/Cargo.toml b/Cargo.toml index b72baea5b..21c08a8b5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,7 @@ axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls-no-provider"] } bittorrent-http-protocol = { version = "3.0.0-develop", path = "packages/http-protocol" } +bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "packages/http-tracker-core" } bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker-core" } diff --git a/packages/http-tracker-core/Cargo.toml b/packages/http-tracker-core/Cargo.toml new file mode 100644 index 000000000..a1ee18f66 --- /dev/null +++ b/packages/http-tracker-core/Cargo.toml @@ -0,0 +1,29 @@ +[package] +authors.workspace = true +description = "A library with the core functionality needed to implement a BitTorrent HTTP tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = ["api", "bittorrent", "core", "library", "tracker"] +license.workspace = true +name = "bittorrent-http-tracker-core" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-http-protocol = { version = "3.0.0-develop", path = "../http-protocol" } +bittorrent-primitives = "0.1.0" +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +futures = "0" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tracing = "0" + +[dev-dependencies] +mockall = "0" +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/http-tracker-core/LICENSE b/packages/http-tracker-core/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/http-tracker-core/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/http-tracker-core/README.md b/packages/http-tracker-core/README.md new file mode 100644 index 000000000..0dd915c24 --- /dev/null +++ b/packages/http-tracker-core/README.md @@ -0,0 +1,15 @@ +# BitTorrent HTTP Tracker Core library + +A library with the core functionality needed to implement a BitTorrent HTTP tracker. + +You usually don’t need to use this library directly. Instead, you should use the [Torrust Tracker](https://github.com/torrust/torrust-tracker). If you want to build your own tracker, you can use this library as the core functionality. + +> **Disclaimer**: This library is actively under development. We’re currently extracting and refining common types from the[Torrust Tracker](https://github.com/torrust/torrust-tracker) to make them available to the BitTorrent community in Rust. While these types are functional, they are not yet ready for use in production or third-party projects. + +## Documentation + +[Crate documentation](https://docs.rs/bittorrent-http-tracker-core). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/http-tracker-core/src/lib.rs b/packages/http-tracker-core/src/lib.rs new file mode 100644 index 000000000..cb5306aa6 --- /dev/null +++ b/packages/http-tracker-core/src/lib.rs @@ -0,0 +1,17 @@ +pub mod services; +pub mod statistics; + +#[cfg(test)] +pub(crate) mod tests { + use bittorrent_primitives::info_hash::InfoHash; + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } +} diff --git a/src/packages/http_tracker_core/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs similarity index 89% rename from src/packages/http_tracker_core/services/announce.rs rename to packages/http-tracker-core/src/services/announce.rs index 6c9cbec17..aff1fc1bd 100644 --- a/src/packages/http_tracker_core/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -21,7 +21,7 @@ use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; -use crate::packages::http_tracker_core; +use crate::statistics; /// The HTTP tracker `announce` service. /// @@ -46,7 +46,7 @@ pub async fn handle_announce( announce_handler: &Arc, authentication_service: &Arc, whitelist_authorization: &Arc, - opt_http_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, maybe_key: Option, @@ -95,12 +95,12 @@ pub async fn handle_announce( match original_peer_ip { IpAddr::V4(_) => { http_stats_event_sender - .send_event(http_tracker_core::statistics::event::Event::Tcp4Announce) + .send_event(statistics::event::Event::Tcp4Announce) .await; } IpAddr::V6(_) => { http_stats_event_sender - .send_event(http_tracker_core::statistics::event::Event::Tcp6Announce) + .send_event(statistics::event::Event::Tcp6Announce) .await; } } @@ -138,7 +138,7 @@ mod tests { } struct CoreHttpTrackerServices { - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, } fn initialize_core_tracker_services() -> (CoreTrackerServices, CoreHttpTrackerServices) { @@ -163,8 +163,7 @@ mod tests { )); // HTTP stats - let (http_stats_event_sender, http_stats_repository) = - http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let (http_stats_event_sender, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); let _http_stats_repository = Arc::new(http_stats_repository); @@ -229,13 +228,13 @@ mod tests { use mockall::mock; use tokio::sync::mpsc::error::SendError; - use crate::packages::http_tracker_core; - use crate::servers::http::test_helpers::tests::sample_info_hash; + use crate::statistics; + use crate::tests::sample_info_hash; mock! { HttpStatsEventSender {} - impl http_tracker_core::statistics::event::sender::Sender for HttpStatsEventSender { - fn send_event(&self, event: http_tracker_core::statistics::event::Event) -> BoxFuture<'static,Option > > > ; + impl statistics::event::sender::Sender for HttpStatsEventSender { + fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } @@ -252,12 +251,12 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; - use crate::packages::http_tracker_core; - use crate::packages::http_tracker_core::services::announce::handle_announce; - use crate::packages::http_tracker_core::services::announce::tests::{ + use crate::services::announce::handle_announce; + use crate::services::announce::tests::{ initialize_core_tracker_services, initialize_core_tracker_services_with_config, sample_announce_request_for_peer, sample_peer, MockHttpStatsEventSender, }; + use crate::statistics; #[tokio::test] async fn it_should_return_the_announce_data() { @@ -298,10 +297,10 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(http_tracker_core::statistics::event::Event::Tcp4Announce)) + .with(eq(statistics::event::Event::Tcp4Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services(); @@ -349,10 +348,10 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(http_tracker_core::statistics::event::Event::Tcp4Announce)) + .with(eq(statistics::event::Event::Tcp4Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let (core_tracker_services, mut core_http_tracker_services) = @@ -383,10 +382,10 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(http_tracker_core::statistics::event::Event::Tcp6Announce)) + .with(eq(statistics::event::Event::Tcp6Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services(); diff --git a/src/packages/http_tracker_core/services/mod.rs b/packages/http-tracker-core/src/services/mod.rs similarity index 100% rename from src/packages/http_tracker_core/services/mod.rs rename to packages/http-tracker-core/src/services/mod.rs diff --git a/src/packages/http_tracker_core/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs similarity index 84% rename from src/packages/http_tracker_core/services/scrape.rs rename to packages/http-tracker-core/src/services/scrape.rs index 7e3ea47fd..11011f16b 100644 --- a/src/packages/http_tracker_core/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -20,7 +20,7 @@ use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; -use crate::packages::http_tracker_core; +use crate::statistics; /// The HTTP tracker `scrape` service. /// @@ -43,7 +43,7 @@ pub async fn handle_scrape( core_config: &Arc, scrape_handler: &Arc, authentication_service: &Arc, - opt_http_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, maybe_key: Option, @@ -70,9 +70,7 @@ pub async fn handle_scrape( }; if return_fake_scrape_data { - return Ok( - http_tracker_core::services::scrape::fake(opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await, - ); + return Ok(fake(opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await); } let scrape_data = scrape_handler.scrape(&scrape_request.info_hashes).await?; @@ -89,7 +87,7 @@ pub async fn handle_scrape( /// /// > **NOTICE**: tracker statistics are not updated in this case. pub async fn fake( - opt_http_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, info_hashes: &Vec, original_peer_ip: &IpAddr, ) -> ScrapeData { @@ -100,19 +98,15 @@ pub async fn fake( async fn send_scrape_event( original_peer_ip: &IpAddr, - opt_http_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, ) { if let Some(http_stats_event_sender) = opt_http_stats_event_sender.as_deref() { match original_peer_ip { IpAddr::V4(_) => { - http_stats_event_sender - .send_event(http_tracker_core::statistics::event::Event::Tcp4Scrape) - .await; + http_stats_event_sender.send_event(statistics::event::Event::Tcp4Scrape).await; } IpAddr::V6(_) => { - http_stats_event_sender - .send_event(http_tracker_core::statistics::event::Event::Tcp6Scrape) - .await; + http_stats_event_sender.send_event(statistics::event::Event::Tcp6Scrape).await; } } } @@ -142,8 +136,8 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::packages::http_tracker_core; - use crate::servers::http::test_helpers::tests::sample_info_hash; + use crate::statistics; + use crate::tests::sample_info_hash; struct Container { announce_handler: Arc, @@ -198,8 +192,8 @@ mod tests { mock! { HttpStatsEventSender {} - impl http_tracker_core::statistics::event::sender::Sender for HttpStatsEventSender { - fn send_event(&self, event: http_tracker_core::statistics::event::Event) -> BoxFuture<'static,Option > > > ; + impl statistics::event::sender::Sender for HttpStatsEventSender { + fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } @@ -217,20 +211,19 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; - use crate::packages::http_tracker_core::services::scrape::handle_scrape; - use crate::packages::http_tracker_core::services::scrape::tests::{ + use crate::services::scrape::handle_scrape; + use crate::services::scrape::tests::{ initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; - use crate::packages::{self, http_tracker_core}; - use crate::servers::http::test_helpers::tests::sample_info_hash; + use crate::statistics; + use crate::tests::sample_info_hash; #[tokio::test] async fn it_should_return_the_scrape_data_for_a_torrent() { let configuration = configuration::ephemeral_public(); let core_config = Arc::new(configuration.core.clone()); - let (http_stats_event_sender, _http_stats_repository) = - packages::http_tracker_core::statistics::setup::factory(false); + let (http_stats_event_sender, _http_stats_repository) = statistics::setup::factory(false); let http_stats_event_sender = Arc::new(http_stats_event_sender); let container = initialize_services_with_configuration(&configuration); @@ -288,10 +281,10 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(http_tracker_core::statistics::event::Event::Tcp4Scrape)) + .with(eq(statistics::event::Event::Tcp4Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let container = initialize_services_with_configuration(&config); @@ -327,10 +320,10 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(http_tracker_core::statistics::event::Event::Tcp6Scrape)) + .with(eq(statistics::event::Event::Tcp6Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let container = initialize_services_with_configuration(&config); @@ -370,17 +363,16 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; - use crate::packages::http_tracker_core::services::scrape::fake; - use crate::packages::http_tracker_core::services::scrape::tests::{ + use crate::services::scrape::fake; + use crate::services::scrape::tests::{ initialize_services_for_public_tracker, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; - use crate::packages::{self, http_tracker_core}; - use crate::servers::http::test_helpers::tests::sample_info_hash; + use crate::statistics; + use crate::tests::sample_info_hash; #[tokio::test] async fn it_should_always_return_the_zeroed_scrape_data_for_a_torrent() { - let (http_stats_event_sender, _http_stats_repository) = - packages::http_tracker_core::statistics::setup::factory(false); + let (http_stats_event_sender, _http_stats_repository) = statistics::setup::factory(false); let http_stats_event_sender = Arc::new(http_stats_event_sender); let container = initialize_services_for_public_tracker(); @@ -409,10 +401,10 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(http_tracker_core::statistics::event::Event::Tcp4Scrape)) + .with(eq(statistics::event::Event::Tcp4Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); @@ -425,10 +417,10 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(http_tracker_core::statistics::event::Event::Tcp6Scrape)) + .with(eq(statistics::event::Event::Tcp6Scrape)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); diff --git a/src/packages/http_tracker_core/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs similarity index 90% rename from src/packages/http_tracker_core/statistics/event/handler.rs rename to packages/http-tracker-core/src/statistics/event/handler.rs index caaf5d375..af323d06b 100644 --- a/src/packages/http_tracker_core/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -1,5 +1,5 @@ -use crate::packages::http_tracker_core::statistics::event::Event; -use crate::packages::http_tracker_core::statistics::repository::Repository; +use crate::statistics::event::Event; +use crate::statistics::repository::Repository; pub async fn handle_event(event: Event, stats_repository: &Repository) { match event { @@ -29,9 +29,9 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { #[cfg(test)] mod tests { - use crate::packages::http_tracker_core::statistics::event::handler::handle_event; - use crate::packages::http_tracker_core::statistics::event::Event; - use crate::packages::http_tracker_core::statistics::repository::Repository; + use crate::statistics::event::handler::handle_event; + use crate::statistics::event::Event; + use crate::statistics::repository::Repository; #[tokio::test] async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { diff --git a/src/packages/http_tracker_core/statistics/event/listener.rs b/packages/http-tracker-core/src/statistics/event/listener.rs similarity index 79% rename from src/packages/http_tracker_core/statistics/event/listener.rs rename to packages/http-tracker-core/src/statistics/event/listener.rs index ed574a36b..f1a2e25de 100644 --- a/src/packages/http_tracker_core/statistics/event/listener.rs +++ b/packages/http-tracker-core/src/statistics/event/listener.rs @@ -2,7 +2,7 @@ use tokio::sync::mpsc; use super::handler::handle_event; use super::Event; -use crate::packages::http_tracker_core::statistics::repository::Repository; +use crate::statistics::repository::Repository; pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) { while let Some(event) = receiver.recv().await { diff --git a/src/packages/http_tracker_core/statistics/event/mod.rs b/packages/http-tracker-core/src/statistics/event/mod.rs similarity index 100% rename from src/packages/http_tracker_core/statistics/event/mod.rs rename to packages/http-tracker-core/src/statistics/event/mod.rs diff --git a/src/packages/http_tracker_core/statistics/event/sender.rs b/packages/http-tracker-core/src/statistics/event/sender.rs similarity index 79% rename from src/packages/http_tracker_core/statistics/event/sender.rs rename to packages/http-tracker-core/src/statistics/event/sender.rs index 279d50962..ca4b4e210 100644 --- a/src/packages/http_tracker_core/statistics/event/sender.rs +++ b/packages/http-tracker-core/src/statistics/event/sender.rs @@ -13,10 +13,10 @@ pub trait Sender: Sync + Send { fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; } -/// An [`statistics::EventSender`](crate::packages::http_tracker_core::statistics::event::sender::Sender) implementation. +/// An [`statistics::EventSender`](crate::statistics::event::sender::Sender) implementation. /// /// It uses a channel sender to send the statistic events. The channel is created by a -/// [`statistics::Keeper`](crate::packages::http_tracker_core::statistics::keeper::Keeper) +/// [`statistics::Keeper`](crate::statistics::keeper::Keeper) #[allow(clippy::module_name_repetitions)] pub struct ChannelSender { pub(crate) sender: mpsc::Sender, diff --git a/src/packages/http_tracker_core/statistics/keeper.rs b/packages/http-tracker-core/src/statistics/keeper.rs similarity index 90% rename from src/packages/http_tracker_core/statistics/keeper.rs rename to packages/http-tracker-core/src/statistics/keeper.rs index 01ae5e6b3..ae5c3276e 100644 --- a/src/packages/http_tracker_core/statistics/keeper.rs +++ b/packages/http-tracker-core/src/statistics/keeper.rs @@ -51,9 +51,9 @@ impl Keeper { #[cfg(test)] mod tests { - use crate::packages::http_tracker_core::statistics::event::Event; - use crate::packages::http_tracker_core::statistics::keeper::Keeper; - use crate::packages::http_tracker_core::statistics::metrics::Metrics; + use crate::statistics::event::Event; + use crate::statistics::keeper::Keeper; + use crate::statistics::metrics::Metrics; #[tokio::test] async fn should_contain_the_tracker_statistics() { diff --git a/src/packages/http_tracker_core/statistics/metrics.rs b/packages/http-tracker-core/src/statistics/metrics.rs similarity index 100% rename from src/packages/http_tracker_core/statistics/metrics.rs rename to packages/http-tracker-core/src/statistics/metrics.rs diff --git a/src/packages/http_tracker_core/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs similarity index 100% rename from src/packages/http_tracker_core/statistics/mod.rs rename to packages/http-tracker-core/src/statistics/mod.rs diff --git a/src/packages/http_tracker_core/statistics/repository.rs b/packages/http-tracker-core/src/statistics/repository.rs similarity index 100% rename from src/packages/http_tracker_core/statistics/repository.rs rename to packages/http-tracker-core/src/statistics/repository.rs diff --git a/src/packages/http_tracker_core/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs similarity index 80% rename from src/packages/http_tracker_core/statistics/services.rs rename to packages/http-tracker-core/src/statistics/services.rs index 51065bf63..57806677e 100644 --- a/src/packages/http_tracker_core/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -2,14 +2,14 @@ //! //! It includes: //! -//! - A [`factory`](crate::packages::http_tracker_core::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. -//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::packages::http_tracker_core::statistics::metrics::Metrics). +//! - A [`factory`](crate::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::statistics::metrics::Metrics). //! //! Tracker metrics are collected using a Publisher-Subscribe pattern. //! //! The factory function builds two structs: //! -//! - An statistics event [`Sender`](crate::packages::http_tracker_core::statistics::event::sender::Sender) +//! - An statistics event [`Sender`](crate::statistics::event::sender::Sender) //! - An statistics [`Repository`] //! //! ```text @@ -23,11 +23,10 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use packages::http_tracker_core::statistics::metrics::Metrics; -use packages::http_tracker_core::statistics::repository::Repository; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use crate::packages; +use crate::statistics::metrics::Metrics; +use crate::statistics::repository::Repository; /// All the metrics collected by the tracker. #[derive(Debug, PartialEq)] @@ -76,8 +75,8 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; - use crate::packages::http_tracker_core::statistics::services::{get_metrics, TrackerMetrics}; - use crate::packages::http_tracker_core::{self, statistics}; + use crate::statistics; + use crate::statistics::services::{get_metrics, TrackerMetrics}; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -89,8 +88,7 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let (_http_stats_event_sender, http_stats_repository) = - http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let (_http_stats_event_sender, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let http_stats_repository = Arc::new(http_stats_repository); let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), http_stats_repository.clone()).await; diff --git a/src/packages/http_tracker_core/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs similarity index 79% rename from src/packages/http_tracker_core/statistics/setup.rs rename to packages/http-tracker-core/src/statistics/setup.rs index 009f157d5..d3114a75e 100644 --- a/src/packages/http_tracker_core/statistics/setup.rs +++ b/packages/http-tracker-core/src/statistics/setup.rs @@ -1,14 +1,14 @@ //! Setup for the tracker statistics. //! //! The [`factory`] function builds the structs needed for handling the tracker metrics. -use crate::packages::http_tracker_core::statistics; +use crate::statistics; /// It builds the structs needed for handling the tracker metrics. /// /// It returns: /// -/// - An statistics event [`Sender`](crate::packages::http_tracker_core::statistics::event::sender::Sender) that allows you to send events related to statistics. -/// - An statistics [`Repository`](crate::packages::http_tracker_core::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. +/// - An statistics event [`Sender`](crate::statistics::event::sender::Sender) that allows you to send events related to statistics. +/// - An statistics [`Repository`](crate::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. /// /// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics /// events are sent are received but not dispatched to the handler. diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 9247f76bb..2f4ff0e94 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -39,7 +39,6 @@ use tracing::instrument; use super::config::initialize_configuration; use crate::bootstrap; use crate::container::AppContainer; -use crate::packages::http_tracker_core; /// It loads the configuration from the environment and builds app container. /// @@ -93,7 +92,7 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { // HTTP stats let (http_stats_event_sender, http_stats_repository) = - http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); let http_stats_repository = Arc::new(http_stats_repository); diff --git a/src/container.rs b/src/container.rs index d4e46b116..0f4a840cf 100644 --- a/src/container.rs +++ b/src/container.rs @@ -16,8 +16,6 @@ use bittorrent_udp_tracker_core::{self}; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; -use crate::packages::http_tracker_core; - pub struct AppContainer { pub core_config: Arc, pub database: Arc>, @@ -28,9 +26,9 @@ pub struct AppContainer { pub in_memory_whitelist: Arc, pub whitelist_authorization: Arc, pub ban_service: Arc>, - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, pub udp_stats_event_sender: Arc>>, - pub http_stats_repository: Arc, + pub http_stats_repository: Arc, pub udp_stats_repository: Arc, pub whitelist_manager: Arc, pub in_memory_torrent_repository: Arc, @@ -69,7 +67,7 @@ pub struct HttpTrackerContainer { pub announce_handler: Arc, pub scrape_handler: Arc, pub whitelist_authorization: Arc, - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, pub authentication_service: Arc, } @@ -95,7 +93,7 @@ pub struct HttpApiContainer { pub keys_handler: Arc, pub whitelist_manager: Arc, pub ban_service: Arc>, - pub http_stats_repository: Arc, + pub http_stats_repository: Arc, pub udp_stats_repository: Arc, } diff --git a/src/packages/http_tracker_core/mod.rs b/src/packages/http_tracker_core/mod.rs deleted file mode 100644 index 4f3e54857..000000000 --- a/src/packages/http_tracker_core/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod services; -pub mod statistics; diff --git a/src/packages/mod.rs b/src/packages/mod.rs index f00f1ace0..7e43aa210 100644 --- a/src/packages/mod.rs +++ b/src/packages/mod.rs @@ -1,5 +1,4 @@ //! This module contains logic pending to be extracted into workspace packages. //! //! It will be moved to the directory `packages`. -pub mod http_tracker_core; pub mod tracker_api_core; diff --git a/src/packages/tracker_api_core/statistics/services.rs b/src/packages/tracker_api_core/statistics/services.rs index d94ff5bf7..bb03dd8ef 100644 --- a/src/packages/tracker_api_core/statistics/services.rs +++ b/src/packages/tracker_api_core/statistics/services.rs @@ -7,7 +7,7 @@ use packages::tracker_api_core::statistics::metrics::Metrics; use tokio::sync::RwLock; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use crate::packages::{self, http_tracker_core}; +use crate::packages::{self}; /// All the metrics collected by the tracker. #[derive(Debug, PartialEq)] @@ -27,7 +27,7 @@ pub struct TrackerMetrics { pub async fn get_metrics( in_memory_torrent_repository: Arc, ban_service: Arc>, - http_stats_repository: Arc, + http_stats_repository: Arc, udp_stats_repository: Arc, ) -> TrackerMetrics { let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -84,7 +84,6 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; - use crate::packages::http_tracker_core; use crate::packages::tracker_api_core::statistics::metrics::Metrics; use crate::packages::tracker_api_core::statistics::services::{get_metrics, TrackerMetrics}; @@ -101,7 +100,7 @@ mod tests { // HTTP stats let (_http_stats_event_sender, http_stats_repository) = - http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); let http_stats_repository = Arc::new(http_stats_repository); // UDP stats diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index 62379b6f4..cfd266c49 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -11,7 +11,6 @@ use serde::Deserialize; use tokio::sync::RwLock; use super::responses::{metrics_response, stats_response}; -use crate::packages::http_tracker_core; use crate::packages::tracker_api_core::statistics::services::get_metrics; #[derive(Deserialize, Debug, Default)] @@ -43,7 +42,7 @@ pub async fn get_stats_handler( State(state): State<( Arc, Arc>, - Arc, + Arc, Arc, )>, params: Query, diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 76f4e5134..5cd4595da 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -21,7 +21,6 @@ use hyper::StatusCode; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; -use crate::packages::http_tracker_core; use crate::servers::http::v1::extractors::announce_request::ExtractRequest; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; @@ -36,7 +35,7 @@ pub async fn handle_without_key( Arc, Arc, Arc, - Arc>>, + Arc>>, )>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, @@ -66,7 +65,7 @@ pub async fn handle_with_key( Arc, Arc, Arc, - Arc>>, + Arc>>, )>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, @@ -97,7 +96,7 @@ async fn handle( announce_handler: &Arc, authentication_service: &Arc, whitelist_authorization: &Arc, - opt_http_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, maybe_key: Option, @@ -126,12 +125,12 @@ async fn handle_announce( announce_handler: &Arc, authentication_service: &Arc, whitelist_authorization: &Arc, - opt_http_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, announce_request: &Announce, client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Result { - http_tracker_core::services::announce::handle_announce( + bittorrent_http_tracker_core::services::announce::handle_announce( &core_config.clone(), &announce_handler.clone(), &authentication_service.clone(), @@ -200,7 +199,6 @@ mod tests { use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; - use crate::packages::http_tracker_core; use crate::servers::http::test_helpers::tests::sample_info_hash; struct CoreTrackerServices { @@ -211,7 +209,7 @@ mod tests { } struct CoreHttpTrackerServices { - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, } fn initialize_private_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) { @@ -248,7 +246,7 @@ mod tests { // HTTP stats let (http_stats_event_sender, http_stats_repository) = - http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); let _http_stats_repository = Arc::new(http_stats_repository); diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index 946190e8f..ad344aa29 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -19,7 +19,6 @@ use hyper::StatusCode; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; -use crate::packages::http_tracker_core; use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; use crate::servers::http::v1::extractors::scrape_request::ExtractRequest; @@ -33,7 +32,7 @@ pub async fn handle_without_key( Arc, Arc, Arc, - Arc>>, + Arc>>, )>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, @@ -63,7 +62,7 @@ pub async fn handle_with_key( Arc, Arc, Arc, - Arc>>, + Arc>>, )>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, @@ -88,7 +87,7 @@ async fn handle( core_config: &Arc, scrape_handler: &Arc, authentication_service: &Arc, - http_stats_event_sender: &Arc>>, + http_stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, maybe_key: Option, @@ -116,12 +115,12 @@ async fn handle_scrape( core_config: &Arc, scrape_handler: &Arc, authentication_service: &Arc, - opt_http_stats_event_sender: &Arc>>, + opt_http_stats_event_sender: &Arc>>, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Result { - http_tracker_core::services::scrape::handle_scrape( + bittorrent_http_tracker_core::services::scrape::handle_scrape( core_config, scrape_handler, authentication_service, @@ -158,8 +157,6 @@ mod tests { use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; - use crate::packages::http_tracker_core; - struct CoreTrackerServices { pub core_config: Arc, pub scrape_handler: Arc, @@ -167,7 +164,7 @@ mod tests { } struct CoreHttpTrackerServices { - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, } fn initialize_private_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) { @@ -197,7 +194,7 @@ mod tests { // HTTP stats let (http_stats_event_sender, _http_stats_repository) = - http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); ( diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 97ca13e95..6621bc6ee 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -10,7 +10,6 @@ use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::container::HttpTrackerContainer; -use torrust_tracker_lib::packages::http_tracker_core; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; @@ -21,7 +20,7 @@ pub struct Environment { pub database: Arc>, pub in_memory_torrent_repository: Arc, pub keys_handler: Arc, - pub http_stats_repository: Arc, + pub http_stats_repository: Arc, pub whitelist_manager: Arc, pub registar: Registar, From 97d26294177f05d7110194758a90dfe4269dc528 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Feb 2025 17:04:47 +0000 Subject: [PATCH 0778/1297] refactor: [#1280] extract tracker-api-core package --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 16 +- Cargo.toml | 1 + packages/tracker-api-core/Cargo.toml | 25 + packages/tracker-api-core/LICENSE | 661 ++++++++++++++++++ packages/tracker-api-core/README.md | 11 + .../tracker-api-core/src/lib.rs | 0 .../src}/statistics/metrics.rs | 0 .../tracker-api-core/src}/statistics/mod.rs | 0 .../src}/statistics/services.rs | 7 +- .../src/crypto/ephemeral_instance_keys.rs | 4 +- src/lib.rs | 1 - src/packages/mod.rs | 4 - src/servers/apis/v1/context/stats/handlers.rs | 2 +- .../apis/v1/context/stats/resources.rs | 8 +- .../apis/v1/context/stats/responses.rs | 2 +- 16 files changed, 724 insertions(+), 19 deletions(-) create mode 100644 packages/tracker-api-core/Cargo.toml create mode 100644 packages/tracker-api-core/LICENSE create mode 100644 packages/tracker-api-core/README.md rename src/packages/tracker_api_core/mod.rs => packages/tracker-api-core/src/lib.rs (100%) rename {src/packages/tracker_api_core => packages/tracker-api-core/src}/statistics/metrics.rs (100%) rename {src/packages/tracker_api_core => packages/tracker-api-core/src}/statistics/mod.rs (100%) rename {src/packages/tracker_api_core => packages/tracker-api-core/src}/statistics/services.rs (95%) delete mode 100644 src/packages/mod.rs diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 7b718bccf..5b39c7f2f 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -63,6 +63,7 @@ jobs: cargo publish -p bittorrent-udp-tracker-core cargo publish -p torrust-tracker cargo publish -p torrust-tracker-api-client + cargo publish -p torrust-tracker-api-core cargo publish -p torrust-tracker-client cargo publish -p torrust-tracker-clock cargo publish -p torrust-tracker-configuration diff --git a/Cargo.lock b/Cargo.lock index 73f7dfb88..63c51dc19 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -674,7 +674,7 @@ dependencies = [ "futures", "lazy_static", "mockall", - "rand 0.8.5", + "rand 0.9.0", "thiserror 2.0.11", "tokio", "torrust-tracker-configuration", @@ -4387,6 +4387,7 @@ dependencies = [ "thiserror 2.0.11", "tokio", "torrust-tracker-api-client", + "torrust-tracker-api-core", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-located-error", @@ -4414,6 +4415,19 @@ dependencies = [ "uuid", ] +[[package]] +name = "torrust-tracker-api-core" +version = "3.0.0-develop" +dependencies = [ + "bittorrent-http-tracker-core", + "bittorrent-tracker-core", + "bittorrent-udp-tracker-core", + "tokio", + "torrust-tracker-configuration", + "torrust-tracker-primitives", + "torrust-tracker-test-helpers", +] + [[package]] name = "torrust-tracker-client" version = "3.0.0-develop" diff --git a/Cargo.toml b/Cargo.toml index 21c08a8b5..d31dcf9c4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -76,6 +76,7 @@ serde_repr = "0" serde_with = { version = "3", features = ["json"] } thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker-api-core = { version = "3.0.0-develop", path = "packages/tracker-api-core" } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "packages/located-error" } diff --git a/packages/tracker-api-core/Cargo.toml b/packages/tracker-api-core/Cargo.toml new file mode 100644 index 000000000..4fc46ed04 --- /dev/null +++ b/packages/tracker-api-core/Cargo.toml @@ -0,0 +1,25 @@ +[package] +authors.workspace = true +description = "A library with the core functionality needed to implement a BitTorrent UDP tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = ["api", "bittorrent", "core", "library", "tracker"] +license.workspace = true +name = "torrust-tracker-api-core" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "../http-tracker-core" } +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "../udp-tracker-core" } +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } + +[dev-dependencies] +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/tracker-api-core/LICENSE b/packages/tracker-api-core/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/tracker-api-core/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/tracker-api-core/README.md b/packages/tracker-api-core/README.md new file mode 100644 index 000000000..96bf17bf7 --- /dev/null +++ b/packages/tracker-api-core/README.md @@ -0,0 +1,11 @@ +# BitTorrent UDP Tracker Core library + +A library with the core functionality needed to implement the Torrust Tracker API + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-api-core). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/src/packages/tracker_api_core/mod.rs b/packages/tracker-api-core/src/lib.rs similarity index 100% rename from src/packages/tracker_api_core/mod.rs rename to packages/tracker-api-core/src/lib.rs diff --git a/src/packages/tracker_api_core/statistics/metrics.rs b/packages/tracker-api-core/src/statistics/metrics.rs similarity index 100% rename from src/packages/tracker_api_core/statistics/metrics.rs rename to packages/tracker-api-core/src/statistics/metrics.rs diff --git a/src/packages/tracker_api_core/statistics/mod.rs b/packages/tracker-api-core/src/statistics/mod.rs similarity index 100% rename from src/packages/tracker_api_core/statistics/mod.rs rename to packages/tracker-api-core/src/statistics/mod.rs diff --git a/src/packages/tracker_api_core/statistics/services.rs b/packages/tracker-api-core/src/statistics/services.rs similarity index 95% rename from src/packages/tracker_api_core/statistics/services.rs rename to packages/tracker-api-core/src/statistics/services.rs index bb03dd8ef..178c8ca0f 100644 --- a/src/packages/tracker_api_core/statistics/services.rs +++ b/packages/tracker-api-core/src/statistics/services.rs @@ -3,11 +3,10 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self, statistics}; -use packages::tracker_api_core::statistics::metrics::Metrics; use tokio::sync::RwLock; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use crate::packages::{self}; +use crate::statistics::metrics::Metrics; /// All the metrics collected by the tracker. #[derive(Debug, PartialEq)] @@ -84,8 +83,8 @@ mod tests { use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; - use crate::packages::tracker_api_core::statistics::metrics::Metrics; - use crate::packages::tracker_api_core::statistics::services::{get_metrics, TrackerMetrics}; + use crate::statistics::metrics::Metrics; + use crate::statistics::services::{get_metrics, TrackerMetrics}; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() diff --git a/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs b/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs index fcbf78288..58ba70562 100644 --- a/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs +++ b/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs @@ -17,13 +17,13 @@ lazy_static! { /// The random static seed. pub static ref RANDOM_SEED: Seed = { let mut rng = ThreadRng::default(); - rng.gen::() + rng.random::() }; /// The random cipher from the seed. pub static ref RANDOM_CIPHER_BLOWFISH: CipherBlowfish = { let mut rng = ThreadRng::default(); - let seed: Seed = rng.gen(); + let seed: Seed = rng.random(); CipherBlowfish::new_from_slice(&seed).expect("it could not generate key") }; diff --git a/src/lib.rs b/src/lib.rs index 210c88c14..a864587c5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -494,7 +494,6 @@ pub mod app; pub mod bootstrap; pub mod console; pub mod container; -pub mod packages; pub mod servers; pub mod shared; diff --git a/src/packages/mod.rs b/src/packages/mod.rs deleted file mode 100644 index 7e43aa210..000000000 --- a/src/packages/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! This module contains logic pending to be extracted into workspace packages. -//! -//! It will be moved to the directory `packages`. -pub mod tracker_api_core; diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/src/servers/apis/v1/context/stats/handlers.rs index cfd266c49..b8adfc3e3 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/src/servers/apis/v1/context/stats/handlers.rs @@ -9,9 +9,9 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use bittorrent_udp_tracker_core::services::banning::BanService; use serde::Deserialize; use tokio::sync::RwLock; +use torrust_tracker_api_core::statistics::services::get_metrics; use super::responses::{metrics_response, stats_response}; -use crate::packages::tracker_api_core::statistics::services::get_metrics; #[derive(Deserialize, Debug, Default)] #[serde(rename_all = "lowercase")] diff --git a/src/servers/apis/v1/context/stats/resources.rs b/src/servers/apis/v1/context/stats/resources.rs index 8477ca5cb..11169f31e 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/src/servers/apis/v1/context/stats/resources.rs @@ -1,8 +1,7 @@ //! API resources for the [`stats`](crate::servers::apis::v1::context::stats) //! API context. use serde::{Deserialize, Serialize}; - -use crate::packages::tracker_api_core::statistics::services::TrackerMetrics; +use torrust_tracker_api_core::statistics::services::TrackerMetrics; /// It contains all the statistics generated by the tracker. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -118,12 +117,11 @@ impl From for Stats { #[cfg(test)] mod tests { - use packages::tracker_api_core::statistics::metrics::Metrics; + use torrust_tracker_api_core::statistics::metrics::Metrics; + use torrust_tracker_api_core::statistics::services::TrackerMetrics; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use super::Stats; - use crate::packages::tracker_api_core::statistics::services::TrackerMetrics; - use crate::packages::{self}; #[test] fn stats_resource_should_be_converted_from_tracker_metrics() { diff --git a/src/servers/apis/v1/context/stats/responses.rs b/src/servers/apis/v1/context/stats/responses.rs index 5a71c4235..0b4da778f 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/src/servers/apis/v1/context/stats/responses.rs @@ -1,9 +1,9 @@ //! API responses for the [`stats`](crate::servers::apis::v1::context::stats) //! API context. use axum::response::{IntoResponse, Json, Response}; +use torrust_tracker_api_core::statistics::services::TrackerMetrics; use super::resources::Stats; -use crate::packages::tracker_api_core::statistics::services::TrackerMetrics; /// `200` response that contains the [`Stats`] resource as json. #[must_use] From 39d9706de3346c9c68a1e93d478688f2460e3216 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Feb 2025 07:19:38 +0000 Subject: [PATCH 0779/1297] refactor: [#1224] rename package to bittorrent-http-tracker-protocol --- .github/workflows/deployment.yaml | 2 +- Cargo.lock | 36 +++++++++---------- Cargo.toml | 2 +- packages/http-protocol/Cargo.toml | 2 +- packages/http-protocol/README.md | 2 +- .../http-protocol/src/percent_encoding.rs | 4 +-- packages/http-protocol/src/v1/query.rs | 8 ++--- .../http-protocol/src/v1/requests/announce.rs | 2 +- .../src/v1/responses/announce.rs | 4 +-- .../http-protocol/src/v1/responses/error.rs | 2 +- .../http-protocol/src/v1/responses/scrape.rs | 2 +- .../src/v1/services/peer_ip_resolver.rs | 4 +-- packages/http-tracker-core/Cargo.toml | 2 +- .../src/services/announce.rs | 10 +++--- .../http-tracker-core/src/services/scrape.rs | 10 +++--- src/servers/http/mod.rs | 26 +++++++------- .../http/v1/extractors/announce_request.rs | 14 ++++---- .../http/v1/extractors/authentication_key.rs | 6 ++-- .../http/v1/extractors/client_ip_sources.rs | 2 +- .../http/v1/extractors/scrape_request.rs | 14 ++++---- src/servers/http/v1/handlers/announce.rs | 16 ++++----- src/servers/http/v1/handlers/common/auth.rs | 2 +- .../http/v1/handlers/common/peer_ip.rs | 6 ++-- src/servers/http/v1/handlers/scrape.rs | 16 ++++----- 24 files changed, 97 insertions(+), 97 deletions(-) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 5b39c7f2f..67c22dd78 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -55,8 +55,8 @@ jobs: env: CARGO_REGISTRY_TOKEN: "${{ secrets.TORRUST_UPDATE_CARGO_REGISTRY_TOKEN }}" run: | - cargo publish -p bittorrent-http-protocol cargo publish -p bittorrent-http-tracker-core + cargo publish -p bittorrent-http-tracker-protocol cargo publish -p bittorrent-tracker-client cargo publish -p bittorrent-tracker-core cargo publish -p bittorrent-udp-protocol diff --git a/Cargo.lock b/Cargo.lock index 63c51dc19..28d553519 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -548,40 +548,40 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" [[package]] -name = "bittorrent-http-protocol" +name = "bittorrent-http-tracker-core" version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", + "bittorrent-http-tracker-protocol", "bittorrent-primitives", "bittorrent-tracker-core", - "derive_more", - "multimap", - "percent-encoding", - "serde", - "serde_bencode", - "thiserror 2.0.11", - "torrust-tracker-clock", + "futures", + "mockall", + "tokio", "torrust-tracker-configuration", - "torrust-tracker-contrib-bencode", - "torrust-tracker-located-error", "torrust-tracker-primitives", + "torrust-tracker-test-helpers", + "tracing", ] [[package]] -name = "bittorrent-http-tracker-core" +name = "bittorrent-http-tracker-protocol" version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", - "bittorrent-http-protocol", "bittorrent-primitives", "bittorrent-tracker-core", - "futures", - "mockall", - "tokio", + "derive_more", + "multimap", + "percent-encoding", + "serde", + "serde_bencode", + "thiserror 2.0.11", + "torrust-tracker-clock", "torrust-tracker-configuration", + "torrust-tracker-contrib-bencode", + "torrust-tracker-located-error", "torrust-tracker-primitives", - "torrust-tracker-test-helpers", - "tracing", ] [[package]] @@ -4347,8 +4347,8 @@ dependencies = [ "axum-client-ip", "axum-extra", "axum-server", - "bittorrent-http-protocol", "bittorrent-http-tracker-core", + "bittorrent-http-tracker-protocol", "bittorrent-primitives", "bittorrent-tracker-client", "bittorrent-tracker-core", diff --git a/Cargo.toml b/Cargo.toml index d31dcf9c4..1fcd189da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,7 +39,7 @@ axum = { version = "0", features = ["macros"] } axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls-no-provider"] } -bittorrent-http-protocol = { version = "3.0.0-develop", path = "packages/http-protocol" } +bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "packages/http-protocol" } bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "packages/http-tracker-core" } bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } diff --git a/packages/http-protocol/Cargo.toml b/packages/http-protocol/Cargo.toml index e76094c1a..7445b37a1 100644 --- a/packages/http-protocol/Cargo.toml +++ b/packages/http-protocol/Cargo.toml @@ -1,7 +1,7 @@ [package] description = "A library with the primitive types and functions for the BitTorrent HTTP tracker protocol." keywords = ["api", "library", "primitives"] -name = "bittorrent-http-protocol" +name = "bittorrent-http-tracker-protocol" readme = "README.md" authors.workspace = true diff --git a/packages/http-protocol/README.md b/packages/http-protocol/README.md index 62de968d9..5f0a31a78 100644 --- a/packages/http-protocol/README.md +++ b/packages/http-protocol/README.md @@ -4,7 +4,7 @@ A library with the primitive types and functions used by BitTorrent HTTP tracker ## Documentation -[Crate documentation](https://docs.rs/bittorrent-http-protocol). +[Crate documentation](https://docs.rs/bittorrent-http-tracker-protocol). ## License diff --git a/packages/http-protocol/src/percent_encoding.rs b/packages/http-protocol/src/percent_encoding.rs index b54c89a04..e58bf94be 100644 --- a/packages/http-protocol/src/percent_encoding.rs +++ b/packages/http-protocol/src/percent_encoding.rs @@ -27,7 +27,7 @@ use torrust_tracker_primitives::peer; /// /// ```rust /// use std::str::FromStr; -/// use bittorrent_http_protocol::percent_encoding::percent_decode_info_hash; +/// use bittorrent_http_tracker_protocol::percent_encoding::percent_decode_info_hash; /// use bittorrent_primitives::info_hash::InfoHash; /// use torrust_tracker_primitives::peer; /// @@ -60,7 +60,7 @@ pub fn percent_decode_info_hash(raw_info_hash: &str) -> Result().unwrap(); /// @@ -73,7 +73,7 @@ impl Query { /// Returns all the param values as a vector even if it has only one value. /// /// ```rust - /// use bittorrent_http_protocol::v1::query::Query; + /// use bittorrent_http_tracker_protocol::v1::query::Query; /// /// let query = "param1=value1".parse::().unwrap(); /// diff --git a/packages/http-protocol/src/v1/requests/announce.rs b/packages/http-protocol/src/v1/requests/announce.rs index 66f7a1227..036aa3048 100644 --- a/packages/http-protocol/src/v1/requests/announce.rs +++ b/packages/http-protocol/src/v1/requests/announce.rs @@ -34,7 +34,7 @@ const NUMWANT: &str = "numwant"; /// /// ```rust /// use aquatic_udp_protocol::{NumberOfBytes, PeerId}; -/// use bittorrent_http_protocol::v1::requests::announce::{Announce, Compact, Event}; +/// use bittorrent_http_tracker_protocol::v1::requests::announce::{Announce, Compact, Event}; /// use bittorrent_primitives::info_hash::InfoHash; /// /// let request = Announce { diff --git a/packages/http-protocol/src/v1/responses/announce.rs b/packages/http-protocol/src/v1/responses/announce.rs index df187fdd1..7175b019a 100644 --- a/packages/http-protocol/src/v1/responses/announce.rs +++ b/packages/http-protocol/src/v1/responses/announce.rs @@ -132,7 +132,7 @@ impl Into> for Compact { /// /// ```rust /// use std::net::{IpAddr, Ipv4Addr}; -/// use bittorrent_http_protocol::v1::responses::announce::{Normal, NormalPeer}; +/// use bittorrent_http_tracker_protocol::v1::responses::announce::{Normal, NormalPeer}; /// /// let peer = NormalPeer { /// peer_id: *b"-qB00000000000000001", @@ -184,7 +184,7 @@ impl From<&NormalPeer> for BencodeMut<'_> { /// /// ```rust /// use std::net::{IpAddr, Ipv4Addr}; -/// use bittorrent_http_protocol::v1::responses::announce::{Compact, CompactPeer, CompactPeerData}; +/// use bittorrent_http_tracker_protocol::v1::responses::announce::{Compact, CompactPeer, CompactPeerData}; /// /// let peer = CompactPeer::V4(CompactPeerData { /// ip: Ipv4Addr::new(0x69, 0x69, 0x69, 0x69), // 105.105.105.105 diff --git a/packages/http-protocol/src/v1/responses/error.rs b/packages/http-protocol/src/v1/responses/error.rs index 30749f73a..8dc28e938 100644 --- a/packages/http-protocol/src/v1/responses/error.rs +++ b/packages/http-protocol/src/v1/responses/error.rs @@ -27,7 +27,7 @@ impl Error { /// Returns the bencoded representation of the `Error` struct. /// /// ```rust - /// use bittorrent_http_protocol::v1::responses::error::Error; + /// use bittorrent_http_tracker_protocol::v1::responses::error::Error; /// /// let err = Error { /// failure_reason: "error message".to_owned(), diff --git a/packages/http-protocol/src/v1/responses/scrape.rs b/packages/http-protocol/src/v1/responses/scrape.rs index 6b4dcc793..022735abc 100644 --- a/packages/http-protocol/src/v1/responses/scrape.rs +++ b/packages/http-protocol/src/v1/responses/scrape.rs @@ -9,7 +9,7 @@ use torrust_tracker_primitives::core::ScrapeData; /// The `Scrape` response for the HTTP tracker. /// /// ```rust -/// use bittorrent_http_protocol::v1::responses::scrape::Bencoded; +/// use bittorrent_http_tracker_protocol::v1::responses::scrape::Bencoded; /// use bittorrent_primitives::info_hash::InfoHash; /// use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; /// use torrust_tracker_primitives::core::ScrapeData; diff --git a/packages/http-protocol/src/v1/services/peer_ip_resolver.rs b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs index f0ad6a83e..8e99b56d1 100644 --- a/packages/http-protocol/src/v1/services/peer_ip_resolver.rs +++ b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs @@ -63,7 +63,7 @@ pub enum PeerIpResolutionError { /// use std::net::IpAddr; /// use std::str::FromStr; /// -/// use bittorrent_http_protocol::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; +/// use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; /// /// let on_reverse_proxy = true; /// @@ -85,7 +85,7 @@ pub enum PeerIpResolutionError { /// use std::net::IpAddr; /// use std::str::FromStr; /// -/// use bittorrent_http_protocol::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; +/// use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; /// /// let on_reverse_proxy = false; /// diff --git a/packages/http-tracker-core/Cargo.toml b/packages/http-tracker-core/Cargo.toml index a1ee18f66..bc6a3d1b3 100644 --- a/packages/http-tracker-core/Cargo.toml +++ b/packages/http-tracker-core/Cargo.toml @@ -15,7 +15,7 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" -bittorrent-http-protocol = { version = "3.0.0-develop", path = "../http-protocol" } +bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "../http-protocol" } bittorrent-primitives = "0.1.0" bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } futures = "0" diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index aff1fc1bd..ce34ee31c 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -11,9 +11,9 @@ use std::net::IpAddr; use std::panic::Location; use std::sync::Arc; -use bittorrent_http_protocol::v1::requests::announce::{peer_from_request, Announce}; -use bittorrent_http_protocol::v1::responses; -use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; +use bittorrent_http_tracker_protocol::v1::requests::announce::{peer_from_request, Announce}; +use bittorrent_http_tracker_protocol::v1::responses; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::{self, Key}; @@ -115,8 +115,8 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; - use bittorrent_http_protocol::v1::requests::announce::Announce; - use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service::AuthenticationService; diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 11011f16b..686a849ea 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -10,9 +10,9 @@ use std::net::IpAddr; use std::sync::Arc; -use bittorrent_http_protocol::v1::requests::scrape::Scrape; -use bittorrent_http_protocol::v1::responses; -use bittorrent_http_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; +use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; +use bittorrent_http_tracker_protocol::v1::responses; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::Key; @@ -203,8 +203,8 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::sync::Arc; - use bittorrent_http_protocol::v1::requests::scrape::Scrape; - use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; diff --git a/src/servers/http/mod.rs b/src/servers/http/mod.rs index 6bc93992f..395f633cf 100644 --- a/src/servers/http/mod.rs +++ b/src/servers/http/mod.rs @@ -43,18 +43,18 @@ //! //! Parameter | Type | Description | Required | Default | Example //! ---|---|---|---|---|--- -//! [`info_hash`](bittorrent_http_protocol::v1::requests::announce::Announce::info_hash) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` +//! [`info_hash`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::info_hash) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` //! `peer_addr` | string |The IP address of the peer. | No | No | `2.137.87.41` -//! [`downloaded`](bittorrent_http_protocol::v1::requests::announce::Announce::downloaded) | positive integer |The number of bytes downloaded by the peer. | No | `0` | `0` -//! [`uploaded`](bittorrent_http_protocol::v1::requests::announce::Announce::uploaded) | positive integer | The number of bytes uploaded by the peer. | No | `0` | `0` -//! [`peer_id`](bittorrent_http_protocol::v1::requests::announce::Announce::peer_id) | percent encoded of 20-byte array | The ID of the peer. | Yes | No | `-qB00000000000000001` -//! [`port`](bittorrent_http_protocol::v1::requests::announce::Announce::port) | positive integer | The port used by the peer. | Yes | No | `17548` -//! [`left`](bittorrent_http_protocol::v1::requests::announce::Announce::left) | positive integer | The number of bytes pending to download. | No | `0` | `0` -//! [`event`](bittorrent_http_protocol::v1::requests::announce::Announce::event) | positive integer | The event that triggered the `Announce` request: `started`, `completed`, `stopped` | No | `None` | `completed` -//! [`compact`](bittorrent_http_protocol::v1::requests::announce::Announce::compact) | `0` or `1` | Whether the tracker should return a compact peer list. | No | `None` | `0` +//! [`downloaded`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::downloaded) | positive integer |The number of bytes downloaded by the peer. | No | `0` | `0` +//! [`uploaded`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::uploaded) | positive integer | The number of bytes uploaded by the peer. | No | `0` | `0` +//! [`peer_id`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::peer_id) | percent encoded of 20-byte array | The ID of the peer. | Yes | No | `-qB00000000000000001` +//! [`port`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::port) | positive integer | The port used by the peer. | Yes | No | `17548` +//! [`left`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::left) | positive integer | The number of bytes pending to download. | No | `0` | `0` +//! [`event`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::event) | positive integer | The event that triggered the `Announce` request: `started`, `completed`, `stopped` | No | `None` | `completed` +//! [`compact`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce::compact) | `0` or `1` | Whether the tracker should return a compact peer list. | No | `None` | `0` //! `numwant` | positive integer | **Not implemented**. The maximum number of peers you want in the reply. | No | `50` | `50` //! -//! Refer to the [`Announce`](bittorrent_http_protocol::v1::requests::announce::Announce) +//! Refer to the [`Announce`](bittorrent_http_tracker_protocol::v1::requests::announce::Announce) //! request for more information about the parameters. //! //! > **NOTICE**: the [BEP 03](https://www.bittorrent.org/beps/bep_0003.html) @@ -152,7 +152,7 @@ //! 000000f0: 65 e //! ``` //! -//! Refer to the [`Normal`](bittorrent_http_protocol::v1::responses::announce::Normal), i.e. `Non-Compact` +//! Refer to the [`Normal`](bittorrent_http_tracker_protocol::v1::responses::announce::Normal), i.e. `Non-Compact` //! response for more information about the response. //! //! **Sample compact response** @@ -190,7 +190,7 @@ //! 0000070: 7065 pe //! ``` //! -//! Refer to the [`Compact`](bittorrent_http_protocol::v1::responses::announce::Compact) +//! Refer to the [`Compact`](bittorrent_http_tracker_protocol::v1::responses::announce::Compact) //! response for more information about the response. //! //! **Protocol** @@ -220,12 +220,12 @@ //! //! Parameter | Type | Description | Required | Default | Example //! ---|---|---|---|---|--- -//! [`info_hash`](bittorrent_http_protocol::v1::requests::scrape::Scrape::info_hashes) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` +//! [`info_hash`](bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape::info_hashes) | percent encoded of 20-byte array | The `Info Hash` of the torrent. | Yes | No | `%81%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00` //! //! > **NOTICE**: you can scrape multiple torrents at the same time by passing //! > multiple `info_hash` parameters. //! -//! Refer to the [`Scrape`](bittorrent_http_protocol::v1::requests::scrape::Scrape) +//! Refer to the [`Scrape`](bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape) //! request for more information about the parameters. //! //! **Sample scrape URL** diff --git a/src/servers/http/v1/extractors/announce_request.rs b/src/servers/http/v1/extractors/announce_request.rs index 74c9ab8c1..3265d04cd 100644 --- a/src/servers/http/v1/extractors/announce_request.rs +++ b/src/servers/http/v1/extractors/announce_request.rs @@ -4,10 +4,10 @@ //! It parses the query parameters returning an [`Announce`] //! request. //! -//! Refer to [`Announce`](bittorrent_http_protocol::v1::requests::announce) for more +//! Refer to [`Announce`](bittorrent_http_tracker_protocol::v1::requests::announce) for more //! information about the returned structure. //! -//! It returns a bencoded [`Error`](bittorrent_http_protocol::v1::responses::error) +//! It returns a bencoded [`Error`](bittorrent_http_tracker_protocol::v1::responses::error) //! response (`500`) if the query parameters are missing or invalid. //! //! **Sample announce request** @@ -33,9 +33,9 @@ use std::panic::Location; use axum::extract::FromRequestParts; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; -use bittorrent_http_protocol::v1::query::Query; -use bittorrent_http_protocol::v1::requests::announce::{Announce, ParseAnnounceQueryError}; -use bittorrent_http_protocol::v1::responses; +use bittorrent_http_tracker_protocol::v1::query::Query; +use bittorrent_http_tracker_protocol::v1::requests::announce::{Announce, ParseAnnounceQueryError}; +use bittorrent_http_tracker_protocol::v1::responses; use futures::FutureExt; use hyper::StatusCode; @@ -87,8 +87,8 @@ mod tests { use std::str::FromStr; use aquatic_udp_protocol::{NumberOfBytes, PeerId}; - use bittorrent_http_protocol::v1::requests::announce::{Announce, Compact, Event}; - use bittorrent_http_protocol::v1::responses::error::Error; + use bittorrent_http_tracker_protocol::v1::requests::announce::{Announce, Compact, Event}; + use bittorrent_http_tracker_protocol::v1::responses::error::Error; use bittorrent_primitives::info_hash::InfoHash; use super::extract_announce_from; diff --git a/src/servers/http/v1/extractors/authentication_key.rs b/src/servers/http/v1/extractors/authentication_key.rs index c99c7000a..da4cd2217 100644 --- a/src/servers/http/v1/extractors/authentication_key.rs +++ b/src/servers/http/v1/extractors/authentication_key.rs @@ -9,7 +9,7 @@ //! It's a wrapper for Axum `Path` extractor in order to return custom //! authentication errors. //! -//! It returns a bencoded [`Error`](bittorrent_http_protocol::v1::responses::error) +//! It returns a bencoded [`Error`](bittorrent_http_tracker_protocol::v1::responses::error) //! response (`500`) if the `key` parameter are missing or invalid. //! //! **Sample authentication error responses** @@ -49,7 +49,7 @@ use axum::extract::rejection::PathRejection; use axum::extract::{FromRequestParts, Path}; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; -use bittorrent_http_protocol::v1::responses; +use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_tracker_core::authentication::Key; use hyper::StatusCode; use serde::Deserialize; @@ -126,7 +126,7 @@ fn custom_error(rejection: &PathRejection) -> responses::error::Error { #[cfg(test)] mod tests { - use bittorrent_http_protocol::v1::responses::error::Error; + use bittorrent_http_tracker_protocol::v1::responses::error::Error; use super::parse_key; diff --git a/src/servers/http/v1/extractors/client_ip_sources.rs b/src/servers/http/v1/extractors/client_ip_sources.rs index 02265554e..8c7a2bf40 100644 --- a/src/servers/http/v1/extractors/client_ip_sources.rs +++ b/src/servers/http/v1/extractors/client_ip_sources.rs @@ -42,7 +42,7 @@ use axum::extract::{ConnectInfo, FromRequestParts}; use axum::http::request::Parts; use axum::response::Response; use axum_client_ip::RightmostXForwardedFor; -use bittorrent_http_protocol::v1::services::peer_ip_resolver::ClientIpSources; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; /// Extractor for the [`ClientIpSources`] /// struct. diff --git a/src/servers/http/v1/extractors/scrape_request.rs b/src/servers/http/v1/extractors/scrape_request.rs index bacd36169..66442da95 100644 --- a/src/servers/http/v1/extractors/scrape_request.rs +++ b/src/servers/http/v1/extractors/scrape_request.rs @@ -4,10 +4,10 @@ //! It parses the query parameters returning an [`Scrape`] //! request. //! -//! Refer to [`Scrape`](bittorrent_http_protocol::v1::requests::scrape) for more +//! Refer to [`Scrape`](bittorrent_http_tracker_protocol::v1::requests::scrape) for more //! information about the returned structure. //! -//! It returns a bencoded [`Error`](bittorrent_http_protocol::v1::responses::error) +//! It returns a bencoded [`Error`](bittorrent_http_tracker_protocol::v1::responses::error) //! response (`500`) if the query parameters are missing or invalid. //! //! **Sample scrape request** @@ -33,9 +33,9 @@ use std::panic::Location; use axum::extract::FromRequestParts; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; -use bittorrent_http_protocol::v1::query::Query; -use bittorrent_http_protocol::v1::requests::scrape::{ParseScrapeQueryError, Scrape}; -use bittorrent_http_protocol::v1::responses; +use bittorrent_http_tracker_protocol::v1::query::Query; +use bittorrent_http_tracker_protocol::v1::requests::scrape::{ParseScrapeQueryError, Scrape}; +use bittorrent_http_tracker_protocol::v1::responses; use futures::FutureExt; use hyper::StatusCode; @@ -86,8 +86,8 @@ fn extract_scrape_from(maybe_raw_query: Option<&str>) -> Result Date: Wed, 19 Feb 2025 07:25:35 +0000 Subject: [PATCH 0780/1297] refactor: [#1224] rename package to bittorrent-udp-tracker-protocol --- .github/workflows/deployment.yaml | 2 +- Cargo.lock | 20 +++++++++---------- packages/udp-protocol/Cargo.toml | 2 +- packages/udp-tracker-core/Cargo.toml | 2 +- .../udp-tracker-core/src/services/announce.rs | 2 +- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 67c22dd78..0e38f5cfe 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -59,8 +59,8 @@ jobs: cargo publish -p bittorrent-http-tracker-protocol cargo publish -p bittorrent-tracker-client cargo publish -p bittorrent-tracker-core - cargo publish -p bittorrent-udp-protocol cargo publish -p bittorrent-udp-tracker-core + cargo publish -p bittorrent-udp-tracker-protocol cargo publish -p torrust-tracker cargo publish -p torrust-tracker-api-client cargo publish -p torrust-tracker-api-core diff --git a/Cargo.lock b/Cargo.lock index 28d553519..788d60d68 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -651,15 +651,6 @@ dependencies = [ "url", ] -[[package]] -name = "bittorrent-udp-protocol" -version = "3.0.0-develop" -dependencies = [ - "aquatic_udp_protocol", - "torrust-tracker-clock", - "torrust-tracker-primitives", -] - [[package]] name = "bittorrent-udp-tracker-core" version = "3.0.0-develop" @@ -667,7 +658,7 @@ dependencies = [ "aquatic_udp_protocol", "bittorrent-primitives", "bittorrent-tracker-core", - "bittorrent-udp-protocol", + "bittorrent-udp-tracker-protocol", "bloom", "blowfish", "cipher", @@ -684,6 +675,15 @@ dependencies = [ "zerocopy 0.7.35", ] +[[package]] +name = "bittorrent-udp-tracker-protocol" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "torrust-tracker-clock", + "torrust-tracker-primitives", +] + [[package]] name = "bitvec" version = "1.0.1" diff --git a/packages/udp-protocol/Cargo.toml b/packages/udp-protocol/Cargo.toml index 8f0f9fe98..31fd52af8 100644 --- a/packages/udp-protocol/Cargo.toml +++ b/packages/udp-protocol/Cargo.toml @@ -1,7 +1,7 @@ [package] description = "A library with the primitive types and functions for the BitTorrent UDP tracker protocol." keywords = ["bittorrent", "library", "primitives", "udp"] -name = "bittorrent-udp-protocol" +name = "bittorrent-udp-tracker-protocol" readme = "README.md" authors.workspace = true diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml index bfa840cc3..5f7622032 100644 --- a/packages/udp-tracker-core/Cargo.toml +++ b/packages/udp-tracker-core/Cargo.toml @@ -17,7 +17,7 @@ version.workspace = true aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } -bittorrent-udp-protocol = { version = "3.0.0-develop", path = "../udp-protocol" } +bittorrent-udp-tracker-protocol = { version = "3.0.0-develop", path = "../udp-protocol" } bloom = "0.3.2" blowfish = "0" cipher = "0" diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index be47b9136..b40162283 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -16,7 +16,7 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::error::{AnnounceError, WhitelistError}; use bittorrent_tracker_core::whitelist; -use bittorrent_udp_protocol::peer_builder; +use bittorrent_udp_tracker_protocol::peer_builder; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; From 3daf3f175b82556027641ca2f2f46e3a7a9af756 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Feb 2025 08:51:01 +0000 Subject: [PATCH 0781/1297] refactor: [#1294] extract axum-server package --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 16 + Cargo.toml | 3 +- packages/axum-server/Cargo.toml | 26 + packages/axum-server/LICENSE | 661 ++++++++++++++++++ packages/axum-server/README.md | 11 + .../axum-server/src}/custom_axum_server.rs | 0 packages/axum-server/src/lib.rs | 1 + src/servers/apis/server.rs | 2 +- src/servers/http/server.rs | 2 +- src/servers/mod.rs | 1 - 11 files changed, 720 insertions(+), 4 deletions(-) create mode 100644 packages/axum-server/Cargo.toml create mode 100644 packages/axum-server/LICENSE create mode 100644 packages/axum-server/README.md rename {src/servers => packages/axum-server/src}/custom_axum_server.rs (100%) create mode 100644 packages/axum-server/src/lib.rs diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 0e38f5cfe..7ced8af44 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -61,6 +61,7 @@ jobs: cargo publish -p bittorrent-tracker-core cargo publish -p bittorrent-udp-tracker-core cargo publish -p bittorrent-udp-tracker-protocol + cargo publish -p torrust-axum-server cargo publish -p torrust-tracker cargo publish -p torrust-tracker-api-client cargo publish -p torrust-tracker-api-core diff --git a/Cargo.lock b/Cargo.lock index 788d60d68..d1e1ac7b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4337,6 +4337,20 @@ dependencies = [ "winnow", ] +[[package]] +name = "torrust-axum-server" +version = "3.0.0-develop" +dependencies = [ + "axum-server", + "futures-util", + "http-body", + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower 0.4.13", +] + [[package]] name = "torrust-tracker" version = "3.0.0-develop" @@ -4386,6 +4400,7 @@ dependencies = [ "serde_with", "thiserror 2.0.11", "tokio", + "torrust-axum-server", "torrust-tracker-api-client", "torrust-tracker-api-core", "torrust-tracker-clock", @@ -4549,6 +4564,7 @@ dependencies = [ "futures-util", "pin-project", "pin-project-lite", + "tokio", "tower-layer", "tower-service", "tracing", diff --git a/Cargo.toml b/Cargo.toml index 1fcd189da..4283baab5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,8 +39,8 @@ axum = { version = "0", features = ["macros"] } axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls-no-provider"] } -bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "packages/http-protocol" } bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "packages/http-tracker-core" } +bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "packages/http-protocol" } bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker-core" } @@ -76,6 +76,7 @@ serde_repr = "0" serde_with = { version = "3", features = ["json"] } thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-axum-server = { version = "3.0.0-develop", path = "packages/axum-server" } torrust-tracker-api-core = { version = "3.0.0-develop", path = "packages/tracker-api-core" } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } diff --git a/packages/axum-server/Cargo.toml b/packages/axum-server/Cargo.toml new file mode 100644 index 000000000..8a4b76998 --- /dev/null +++ b/packages/axum-server/Cargo.toml @@ -0,0 +1,26 @@ +[package] +authors.workspace = true +description = "A wrapper for the Axum server for Torrust HTTP servers to add timeouts." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = ["axum", "server", "torrust", "torrust", "wrapper"] +license.workspace = true +name = "torrust-axum-server" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +axum-server = { version = "0", features = ["tls-rustls-no-provider"] } +futures-util = "0" +http-body = "1" +hyper = "1" +hyper-util = { version = "0", features = ["http1", "http2", "tokio"] } +pin-project-lite = "0" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tower = { version = "0", features = ["timeout"] } + +[dev-dependencies] diff --git a/packages/axum-server/LICENSE b/packages/axum-server/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/axum-server/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/axum-server/README.md b/packages/axum-server/README.md new file mode 100644 index 000000000..d2f396915 --- /dev/null +++ b/packages/axum-server/README.md @@ -0,0 +1,11 @@ +# Torrust Axum Server + +A wrapper for the Axum server for Torrust HTTP servers to add timeouts. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-axum-server). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/src/servers/custom_axum_server.rs b/packages/axum-server/src/custom_axum_server.rs similarity index 100% rename from src/servers/custom_axum_server.rs rename to packages/axum-server/src/custom_axum_server.rs diff --git a/packages/axum-server/src/lib.rs b/packages/axum-server/src/lib.rs new file mode 100644 index 000000000..ace51c184 --- /dev/null +++ b/packages/axum-server/src/lib.rs @@ -0,0 +1 @@ +pub mod custom_axum_server; \ No newline at end of file diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 7388a1851..7a8087215 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -33,6 +33,7 @@ use derive_more::Constructor; use futures::future::BoxFuture; use thiserror::Error; use tokio::sync::oneshot::{Receiver, Sender}; +use torrust_axum_server::custom_axum_server::{self, TimeoutAcceptor}; use torrust_tracker_configuration::AccessTokens; use tracing::{instrument, Level}; @@ -40,7 +41,6 @@ use super::routes::router; use crate::bootstrap::jobs::Started; use crate::container::HttpApiContainer; use crate::servers::apis::API_LOG_TARGET; -use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::logging::STARTED_ON; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use crate::servers::signals::{graceful_shutdown, Halted}; diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 2355bedf9..3de40e0b0 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -7,12 +7,12 @@ use axum_server::Handle; use derive_more::Constructor; use futures::future::BoxFuture; use tokio::sync::oneshot::{Receiver, Sender}; +use torrust_axum_server::custom_axum_server::{self, TimeoutAcceptor}; use tracing::instrument; use super::v1::routes::router; use crate::bootstrap::jobs::Started; use crate::container::HttpTrackerContainer; -use crate::servers::custom_axum_server::{self, TimeoutAcceptor}; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; use crate::servers::logging::STARTED_ON; use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; diff --git a/src/servers/mod.rs b/src/servers/mod.rs index 705a4728e..f9ed2d10c 100644 --- a/src/servers/mod.rs +++ b/src/servers/mod.rs @@ -1,6 +1,5 @@ //! Servers. Services that can be started and stopped. pub mod apis; -pub mod custom_axum_server; pub mod health_check_api; pub mod http; pub mod logging; From 0685f1a79e2854a377bb82246c11b72fa63eb25a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Feb 2025 09:12:57 +0000 Subject: [PATCH 0782/1297] refactor: [#1294] extract server-lib package --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 16 +- Cargo.toml | 4 +- packages/axum-server/Cargo.toml | 4 +- packages/axum-server/src/lib.rs | 3 +- packages/axum-server/src/signals.rs | 21 + packages/server-lib/Cargo.toml | 22 + packages/server-lib/LICENSE | 661 ++++++++++++++++++ packages/server-lib/README.md | 11 + packages/server-lib/src/lib.rs | 3 + .../server-lib/src}/logging.rs | 0 .../server-lib/src}/registar.rs | 0 .../server-lib/src}/signals.rs | 19 - src/app.rs | 2 +- src/bootstrap/jobs/health_check_api.rs | 6 +- src/bootstrap/jobs/http_tracker.rs | 4 +- src/bootstrap/jobs/tracker_apis.rs | 4 +- src/bootstrap/jobs/udp_tracker.rs | 2 +- src/console/ci/e2e/logs_parser.rs | 2 +- src/servers/apis/routes.rs | 2 +- src/servers/apis/server.rs | 9 +- src/servers/health_check_api/handlers.rs | 2 +- src/servers/health_check_api/server.rs | 7 +- src/servers/http/server.rs | 9 +- src/servers/http/v1/routes.rs | 2 +- src/servers/mod.rs | 3 - src/servers/udp/server/launcher.rs | 6 +- src/servers/udp/server/mod.rs | 2 +- src/servers/udp/server/spawner.rs | 2 +- src/servers/udp/server/states.rs | 4 +- tests/servers/api/environment.rs | 2 +- tests/servers/health_check_api/contract.rs | 2 +- tests/servers/health_check_api/environment.rs | 4 +- tests/servers/http/environment.rs | 2 +- tests/servers/udp/environment.rs | 2 +- 35 files changed, 778 insertions(+), 67 deletions(-) create mode 100644 packages/axum-server/src/signals.rs create mode 100644 packages/server-lib/Cargo.toml create mode 100644 packages/server-lib/LICENSE create mode 100644 packages/server-lib/README.md create mode 100644 packages/server-lib/src/lib.rs rename {src/servers => packages/server-lib/src}/logging.rs (100%) rename {src/servers => packages/server-lib/src}/registar.rs (100%) rename {src/servers => packages/server-lib/src}/signals.rs (77%) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 7ced8af44..901f9c878 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -62,6 +62,7 @@ jobs: cargo publish -p bittorrent-udp-tracker-core cargo publish -p bittorrent-udp-tracker-protocol cargo publish -p torrust-axum-server + cargo publish -p torrust-torrust-server-lib cargo publish -p torrust-tracker cargo publish -p torrust-tracker-api-client cargo publish -p torrust-tracker-api-core diff --git a/Cargo.lock b/Cargo.lock index d1e1ac7b0..a62a20619 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4348,7 +4348,19 @@ dependencies = [ "hyper-util", "pin-project-lite", "tokio", + "torrust-server-lib", "tower 0.4.13", + "tracing", +] + +[[package]] +name = "torrust-server-lib" +version = "3.0.0-develop" +dependencies = [ + "derive_more", + "tokio", + "tower-http", + "tracing", ] [[package]] @@ -4376,15 +4388,12 @@ dependencies = [ "figment", "futures", "futures-util", - "http-body", "hyper", - "hyper-util", "lazy_static", "local-ip-address", "mockall", "parking_lot", "percent-encoding", - "pin-project-lite", "r2d2", "r2d2_mysql", "r2d2_sqlite", @@ -4401,6 +4410,7 @@ dependencies = [ "thiserror 2.0.11", "tokio", "torrust-axum-server", + "torrust-server-lib", "torrust-tracker-api-client", "torrust-tracker-api-core", "torrust-tracker-clock", diff --git a/Cargo.toml b/Cargo.toml index 4283baab5..22df92b2d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,13 +54,10 @@ derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } figment = "0" futures = "0" futures-util = "0" -http-body = "1" hyper = "1" -hyper-util = { version = "0", features = ["http1", "http2", "tokio"] } lazy_static = "1" parking_lot = "0" percent-encoding = "2" -pin-project-lite = "0" r2d2 = "0" r2d2_mysql = "25" r2d2_sqlite = { version = "0", features = ["bundled"] } @@ -77,6 +74,7 @@ serde_with = { version = "3", features = ["json"] } thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-axum-server = { version = "3.0.0-develop", path = "packages/axum-server" } +torrust-server-lib = { version = "3.0.0-develop", path = "packages/server-lib" } torrust-tracker-api-core = { version = "3.0.0-develop", path = "packages/tracker-api-core" } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } diff --git a/packages/axum-server/Cargo.toml b/packages/axum-server/Cargo.toml index 8a4b76998..6604a0555 100644 --- a/packages/axum-server/Cargo.toml +++ b/packages/axum-server/Cargo.toml @@ -4,7 +4,7 @@ description = "A wrapper for the Axum server for Torrust HTTP servers to add tim documentation.workspace = true edition.workspace = true homepage.workspace = true -keywords = ["axum", "server", "torrust", "torrust", "wrapper"] +keywords = ["axum", "server", "torrust", "wrapper"] license.workspace = true name = "torrust-axum-server" publish.workspace = true @@ -21,6 +21,8 @@ hyper = "1" hyper-util = { version = "0", features = ["http1", "http2", "tokio"] } pin-project-lite = "0" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } tower = { version = "0", features = ["timeout"] } +tracing = "0" [dev-dependencies] diff --git a/packages/axum-server/src/lib.rs b/packages/axum-server/src/lib.rs index ace51c184..06de31d8c 100644 --- a/packages/axum-server/src/lib.rs +++ b/packages/axum-server/src/lib.rs @@ -1 +1,2 @@ -pub mod custom_axum_server; \ No newline at end of file +pub mod custom_axum_server; +pub mod signals; diff --git a/packages/axum-server/src/signals.rs b/packages/axum-server/src/signals.rs new file mode 100644 index 000000000..af69cbb6e --- /dev/null +++ b/packages/axum-server/src/signals.rs @@ -0,0 +1,21 @@ +use std::time::Duration; + +use tokio::time::sleep; +use torrust_server_lib::signals::{shutdown_signal_with_message, Halted}; +use tracing::instrument; + +#[instrument(skip(handle, rx_halt, message))] +pub async fn graceful_shutdown(handle: axum_server::Handle, rx_halt: tokio::sync::oneshot::Receiver, message: String) { + shutdown_signal_with_message(rx_halt, message).await; + + tracing::debug!("Sending graceful shutdown signal"); + handle.graceful_shutdown(Some(Duration::from_secs(90))); + + println!("!! shuting down in 90 seconds !!"); + + loop { + sleep(Duration::from_secs(1)).await; + + tracing::info!("remaining alive connections: {}", handle.connection_count()); + } +} diff --git a/packages/server-lib/Cargo.toml b/packages/server-lib/Cargo.toml new file mode 100644 index 000000000..b0e196d64 --- /dev/null +++ b/packages/server-lib/Cargo.toml @@ -0,0 +1,22 @@ +[package] +authors.workspace = true +description = "Common functionality used in all Torrust HTTP servers." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = ["lib", "server", "torrust"] +license.workspace = true +name = "torrust-server-lib" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } +tracing = "0" + +[dev-dependencies] diff --git a/packages/server-lib/LICENSE b/packages/server-lib/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/server-lib/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/server-lib/README.md b/packages/server-lib/README.md new file mode 100644 index 000000000..820225a00 --- /dev/null +++ b/packages/server-lib/README.md @@ -0,0 +1,11 @@ +# Torrust Server Lib + +Common functionality used in all Torrust HTTP servers. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-axum-server). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/server-lib/src/lib.rs b/packages/server-lib/src/lib.rs new file mode 100644 index 000000000..324041822 --- /dev/null +++ b/packages/server-lib/src/lib.rs @@ -0,0 +1,3 @@ +pub mod logging; +pub mod registar; +pub mod signals; diff --git a/src/servers/logging.rs b/packages/server-lib/src/logging.rs similarity index 100% rename from src/servers/logging.rs rename to packages/server-lib/src/logging.rs diff --git a/src/servers/registar.rs b/packages/server-lib/src/registar.rs similarity index 100% rename from src/servers/registar.rs rename to packages/server-lib/src/registar.rs diff --git a/src/servers/signals.rs b/packages/server-lib/src/signals.rs similarity index 77% rename from src/servers/signals.rs rename to packages/server-lib/src/signals.rs index b83dd5213..b5cff03c1 100644 --- a/src/servers/signals.rs +++ b/packages/server-lib/src/signals.rs @@ -1,8 +1,5 @@ //! This module contains functions to handle signals. -use std::time::Duration; - use derive_more::Display; -use tokio::time::sleep; use tracing::instrument; /// This is the message that the "launcher" spawned task receives from the main @@ -68,19 +65,3 @@ pub async fn shutdown_signal_with_message(rx_halt: tokio::sync::oneshot::Receive tracing::info!("{message}"); } - -#[instrument(skip(handle, rx_halt, message))] -pub async fn graceful_shutdown(handle: axum_server::Handle, rx_halt: tokio::sync::oneshot::Receiver, message: String) { - shutdown_signal_with_message(rx_halt, message).await; - - tracing::debug!("Sending graceful shutdown signal"); - handle.graceful_shutdown(Some(Duration::from_secs(90))); - - println!("!! shuting down in 90 seconds !!"); - - loop { - sleep(Duration::from_secs(1)).await; - - tracing::info!("remaining alive connections: {}", handle.connection_count()); - } -} diff --git a/src/app.rs b/src/app.rs index ad7524372..c13414b3b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -24,13 +24,13 @@ use std::sync::Arc; use tokio::task::JoinHandle; +use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::Configuration; use tracing::instrument; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; use crate::container::{AppContainer, HttpApiContainer, HttpTrackerContainer, UdpTrackerContainer}; use crate::servers; -use crate::servers::registar::Registar; /// # Panics /// diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index b6250efcc..95c3bfc24 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -16,14 +16,14 @@ use tokio::sync::oneshot; use tokio::task::JoinHandle; +use torrust_server_lib::logging::STARTED_ON; +use torrust_server_lib::registar::ServiceRegistry; +use torrust_server_lib::signals::Halted; use torrust_tracker_configuration::HealthCheckApi; use tracing::instrument; use super::Started; use crate::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; -use crate::servers::logging::STARTED_ON; -use crate::servers::registar::ServiceRegistry; -use crate::servers::signals::Halted; /// This function starts a new Health Check API server with the provided /// configuration. diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 83cc0ae02..38aeb4028 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -15,13 +15,13 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; +use torrust_server_lib::registar::ServiceRegistrationForm; use tracing::instrument; use super::make_rust_tls; use crate::container::HttpTrackerContainer; use crate::servers::http::server::{HttpServer, Launcher}; use crate::servers::http::Version; -use crate::servers::registar::ServiceRegistrationForm; /// It starts a new HTTP server with the provided configuration and version. /// @@ -78,13 +78,13 @@ async fn start_v1( mod tests { use std::sync::Arc; + use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::http_tracker::start_job; use crate::container::HttpTrackerContainer; use crate::servers::http::Version; - use crate::servers::registar::Registar; #[tokio::test] async fn it_should_start_http_tracker() { diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index cee6cbae2..1f43ee67c 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -25,6 +25,7 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; +use torrust_server_lib::registar::ServiceRegistrationForm; use torrust_tracker_configuration::AccessTokens; use tracing::instrument; @@ -32,7 +33,6 @@ use super::make_rust_tls; use crate::container::HttpApiContainer; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::apis::Version; -use crate::servers::registar::ServiceRegistrationForm; /// This is the message that the "launcher" spawned task sends to the main /// application process to notify the API server was successfully started. @@ -97,13 +97,13 @@ async fn start_v1( mod tests { use std::sync::Arc; + use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::tracker_apis::start_job; use crate::container::HttpApiContainer; use crate::servers::apis::Version; - use crate::servers::registar::Registar; #[tokio::test] async fn it_should_start_http_tracker() { diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 03fe396d6..c97e239ce 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -10,10 +10,10 @@ use std::sync::Arc; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use tokio::task::JoinHandle; +use torrust_server_lib::registar::ServiceRegistrationForm; use tracing::instrument; use crate::container::UdpTrackerContainer; -use crate::servers::registar::ServiceRegistrationForm; use crate::servers::udp::server::spawner::Spawner; use crate::servers::udp::server::Server; diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index 8f7f6059d..dd2fbdb53 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -2,10 +2,10 @@ use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use regex::Regex; use serde::{Deserialize, Serialize}; +use torrust_server_lib::logging::STARTED_ON; use crate::servers::health_check_api::HEALTH_CHECK_API_LOG_TARGET; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; -use crate::servers::logging::STARTED_ON; const INFO_THRESHOLD: &str = "INFO"; diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 137975259..f21c59207 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -15,6 +15,7 @@ use axum::response::Response; use axum::routing::get; use axum::{middleware, BoxError, Router}; use hyper::{Request, StatusCode}; +use torrust_server_lib::logging::Latency; use torrust_tracker_configuration::{AccessTokens, DEFAULT_TIMEOUT}; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; @@ -31,7 +32,6 @@ use super::v1::context::health_check::handlers::health_check_handler; use super::v1::middlewares::auth::State; use crate::container::HttpApiContainer; use crate::servers::apis::API_LOG_TARGET; -use crate::servers::logging::Latency; /// Add all API routes to the router. #[instrument(skip(http_api_container, access_tokens))] diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 7a8087215..47473d964 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -34,6 +34,10 @@ use futures::future::BoxFuture; use thiserror::Error; use tokio::sync::oneshot::{Receiver, Sender}; use torrust_axum_server::custom_axum_server::{self, TimeoutAcceptor}; +use torrust_axum_server::signals::graceful_shutdown; +use torrust_server_lib::logging::STARTED_ON; +use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; +use torrust_server_lib::signals::Halted; use torrust_tracker_configuration::AccessTokens; use tracing::{instrument, Level}; @@ -41,9 +45,6 @@ use super::routes::router; use crate::bootstrap::jobs::Started; use crate::container::HttpApiContainer; use crate::servers::apis::API_LOG_TARGET; -use crate::servers::logging::STARTED_ON; -use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; -use crate::servers::signals::{graceful_shutdown, Halted}; /// Errors that can occur when starting or stopping the API server. #[derive(Debug, Error)] @@ -294,13 +295,13 @@ impl Launcher { mod tests { use std::sync::Arc; + use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::make_rust_tls; use crate::container::HttpApiContainer; use crate::servers::apis::server::{ApiServer, Launcher}; - use crate::servers::registar::Registar; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { diff --git a/src/servers/health_check_api/handlers.rs b/src/servers/health_check_api/handlers.rs index fe65e996b..0af2ab05d 100644 --- a/src/servers/health_check_api/handlers.rs +++ b/src/servers/health_check_api/handlers.rs @@ -2,11 +2,11 @@ use std::collections::VecDeque; use axum::extract::State; use axum::Json; +use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistry}; use tracing::{instrument, Level}; use super::resources::{CheckReport, Report}; use super::responses; -use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistry}; /// Endpoint for container health check. /// diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index 42111f507..06dd5af65 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -14,6 +14,10 @@ use futures::Future; use hyper::Request; use serde_json::json; use tokio::sync::oneshot::{Receiver, Sender}; +use torrust_axum_server::signals::graceful_shutdown; +use torrust_server_lib::logging::Latency; +use torrust_server_lib::registar::ServiceRegistry; +use torrust_server_lib::signals::Halted; use tower_http::classify::ServerErrorsFailureClass; use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; @@ -25,9 +29,6 @@ use tracing::{instrument, Level, Span}; use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; use crate::servers::health_check_api::HEALTH_CHECK_API_LOG_TARGET; -use crate::servers::logging::Latency; -use crate::servers::registar::ServiceRegistry; -use crate::servers::signals::{graceful_shutdown, Halted}; /// Starts Health Check API server. /// diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 3de40e0b0..25a8e5635 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -8,15 +8,16 @@ use derive_more::Constructor; use futures::future::BoxFuture; use tokio::sync::oneshot::{Receiver, Sender}; use torrust_axum_server::custom_axum_server::{self, TimeoutAcceptor}; +use torrust_axum_server::signals::graceful_shutdown; +use torrust_server_lib::logging::STARTED_ON; +use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; +use torrust_server_lib::signals::Halted; use tracing::instrument; use super::v1::routes::router; use crate::bootstrap::jobs::Started; use crate::container::HttpTrackerContainer; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; -use crate::servers::logging::STARTED_ON; -use crate::servers::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; -use crate::servers::signals::{graceful_shutdown, Halted}; /// Error that can occur when starting or stopping the HTTP server. /// @@ -238,13 +239,13 @@ pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { mod tests { use std::sync::Arc; + use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::make_rust_tls; use crate::container::HttpTrackerContainer; use crate::servers::http::server::{HttpServer, Launcher}; - use crate::servers::registar::Registar; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 73f4e5f29..5f2d95a8e 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -10,6 +10,7 @@ use axum::routing::get; use axum::{BoxError, Router}; use axum_client_ip::SecureClientIpSource; use hyper::{Request, StatusCode}; +use torrust_server_lib::logging::Latency; use torrust_tracker_configuration::DEFAULT_TIMEOUT; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; @@ -24,7 +25,6 @@ use tracing::{instrument, Level, Span}; use super::handlers::{announce, health_check, scrape}; use crate::container::HttpTrackerContainer; use crate::servers::http::HTTP_TRACKER_LOG_TARGET; -use crate::servers::logging::Latency; /// It adds the routes to the router. /// diff --git a/src/servers/mod.rs b/src/servers/mod.rs index f9ed2d10c..eb5e5fee7 100644 --- a/src/servers/mod.rs +++ b/src/servers/mod.rs @@ -2,7 +2,4 @@ pub mod apis; pub mod health_check_api; pub mod http; -pub mod logging; -pub mod registar; -pub mod signals; pub mod udp; diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index fb0033624..f85972721 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -9,14 +9,14 @@ use futures_util::StreamExt; use tokio::select; use tokio::sync::oneshot; use tokio::time::interval; +use torrust_server_lib::logging::STARTED_ON; +use torrust_server_lib::registar::ServiceHealthCheckJob; +use torrust_server_lib::signals::{shutdown_signal_with_message, Halted}; use tracing::instrument; use super::request_buffer::ActiveRequests; use crate::bootstrap::jobs::Started; use crate::container::UdpTrackerContainer; -use crate::servers::logging::STARTED_ON; -use crate::servers::registar::ServiceHealthCheckJob; -use crate::servers::signals::{shutdown_signal_with_message, Halted}; use crate::servers::udp::server::bound_socket::BoundSocket; use crate::servers::udp::server::processor::Processor; use crate::servers::udp::server::receiver::Receiver; diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 2be568c89..85940e853 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -57,13 +57,13 @@ mod tests { use std::sync::Arc; use std::time::Duration; + use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; use super::spawner::Spawner; use super::Server; use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::container::UdpTrackerContainer; - use crate::servers::registar::Registar; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index 88ce5a245..34437cdfb 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -7,11 +7,11 @@ use derive_more::derive::Display; use derive_more::Constructor; use tokio::sync::oneshot; use tokio::task::JoinHandle; +use torrust_server_lib::signals::Halted; use super::launcher::Launcher; use crate::bootstrap::jobs::Started; use crate::container::UdpTrackerContainer; -use crate::servers::signals::Halted; #[derive(Constructor, Copy, Clone, Debug, Display)] #[display("(with socket): {bind_to}")] diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index c74c7f4db..123d7f8a5 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -7,14 +7,14 @@ use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use derive_more::derive::Display; use derive_more::Constructor; use tokio::task::JoinHandle; +use torrust_server_lib::registar::{ServiceRegistration, ServiceRegistrationForm}; +use torrust_server_lib::signals::Halted; use tracing::{instrument, Level}; use super::spawner::Spawner; use super::{Server, UdpError}; use crate::bootstrap::jobs::Started; use crate::container::UdpTrackerContainer; -use crate::servers::registar::{ServiceRegistration, ServiceRegistrationForm}; -use crate::servers::signals::Halted; use crate::servers::udp::server::launcher::Launcher; /// A UDP server instance controller with no UDP instance running. diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 02d6465e1..cc7574895 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -6,13 +6,13 @@ use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::Database; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::executor::block_on; +use torrust_server_lib::registar::Registar; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::container::HttpApiContainer; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; -use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; pub struct Environment diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index 2c7efd547..bf38e05a7 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -1,5 +1,5 @@ +use torrust_server_lib::registar::Registar; use torrust_tracker_lib::servers::health_check_api::resources::{Report, Status}; -use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_test_helpers::configuration; use crate::common::logging; diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs index 17d87d666..e364a52cb 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/tests/servers/health_check_api/environment.rs @@ -3,11 +3,11 @@ use std::sync::Arc; use tokio::sync::oneshot::{self, Sender}; use tokio::task::JoinHandle; +use torrust_server_lib::registar::Registar; +use torrust_server_lib::signals::{self, Halted}; use torrust_tracker_configuration::HealthCheckApi; use torrust_tracker_lib::bootstrap::jobs::Started; use torrust_tracker_lib::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; -use torrust_tracker_lib::servers::registar::Registar; -use torrust_tracker_lib::servers::signals::{self, Halted}; #[derive(Debug)] pub enum Error { diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 6621bc6ee..2584c51c7 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -6,12 +6,12 @@ use bittorrent_tracker_core::databases::Database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use futures::executor::block_on; +use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::container::HttpTrackerContainer; use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; -use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_primitives::peer; pub struct Environment { diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 7a6992583..67e119bb4 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -5,10 +5,10 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::databases::Database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::statistics; +use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; use torrust_tracker_lib::container::UdpTrackerContainer; -use torrust_tracker_lib::servers::registar::Registar; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; use torrust_tracker_lib::servers::udp::server::Server; From 3b5cf862a5172aac9da53d421a6e9055faa101e3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Feb 2025 11:09:11 +0000 Subject: [PATCH 0783/1297] refactor: [#1283] extract axum-http-tracker-server package --- .github/workflows/deployment.yaml | 3 + Cargo.lock | 37 +- Cargo.toml | 4 +- packages/axum-http-tracker-server/Cargo.toml | 41 ++ packages/axum-http-tracker-server/LICENSE | 661 ++++++++++++++++++ packages/axum-http-tracker-server/README.md | 11 + .../axum-http-tracker-server/src/container.rs | 17 + .../axum-http-tracker-server/src/lib.rs | 1 + .../axum-http-tracker-server/src}/server.rs | 86 ++- .../src}/test_helpers.rs | 0 .../src}/v1/extractors/announce_request.rs | 2 +- .../src}/v1/extractors/authentication_key.rs | 2 +- .../src}/v1/extractors/client_ip_sources.rs | 0 .../src}/v1/extractors/mod.rs | 0 .../src}/v1/extractors/scrape_request.rs | 2 +- .../src}/v1/handlers/announce.rs | 24 +- .../src}/v1/handlers/common/auth.rs | 0 .../src}/v1/handlers/common/mod.rs | 0 .../src}/v1/handlers/common/peer_ip.rs | 0 .../src}/v1/handlers/health_check.rs | 0 .../src}/v1/handlers/mod.rs | 0 .../src}/v1/handlers/scrape.rs | 18 +- .../axum-http-tracker-server/src}/v1/mod.rs | 0 .../src}/v1/routes.rs | 2 +- packages/axum-server/Cargo.toml | 4 + packages/axum-server/src/lib.rs | 1 + packages/axum-server/src/tsl.rs | 85 +++ packages/server-lib/src/signals.rs | 8 + src/app.rs | 12 +- src/bootstrap/jobs/health_check_api.rs | 3 +- src/bootstrap/jobs/http_tracker.rs | 14 +- src/bootstrap/jobs/mod.rs | 94 --- src/bootstrap/jobs/tracker_apis.rs | 2 +- src/console/ci/e2e/logs_parser.rs | 2 +- src/container.rs | 41 +- src/lib.rs | 10 +- src/servers/apis/server.rs | 5 +- src/servers/health_check_api/server.rs | 3 +- src/servers/mod.rs | 1 - src/servers/udp/server/launcher.rs | 3 +- src/servers/udp/server/spawner.rs | 3 +- src/servers/udp/server/states.rs | 3 +- tests/servers/api/environment.rs | 2 +- tests/servers/health_check_api/environment.rs | 3 +- tests/servers/http/environment.rs | 6 +- tests/servers/http/mod.rs | 6 +- tests/servers/http/v1/contract.rs | 2 +- 47 files changed, 1017 insertions(+), 207 deletions(-) create mode 100644 packages/axum-http-tracker-server/Cargo.toml create mode 100644 packages/axum-http-tracker-server/LICENSE create mode 100644 packages/axum-http-tracker-server/README.md create mode 100644 packages/axum-http-tracker-server/src/container.rs rename src/servers/http/mod.rs => packages/axum-http-tracker-server/src/lib.rs (99%) rename {src/servers/http => packages/axum-http-tracker-server/src}/server.rs (73%) rename {src/servers/http => packages/axum-http-tracker-server/src}/test_helpers.rs (100%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/extractors/announce_request.rs (98%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/extractors/authentication_key.rs (98%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/extractors/client_ip_sources.rs (100%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/extractors/mod.rs (100%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/extractors/scrape_request.rs (99%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/handlers/announce.rs (94%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/handlers/common/auth.rs (100%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/handlers/common/mod.rs (100%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/handlers/common/peer_ip.rs (100%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/handlers/health_check.rs (100%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/handlers/mod.rs (100%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/handlers/scrape.rs (95%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/mod.rs (100%) rename {src/servers/http => packages/axum-http-tracker-server/src}/v1/routes.rs (99%) create mode 100644 packages/axum-server/src/tsl.rs diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 901f9c878..296752df4 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -61,6 +61,7 @@ jobs: cargo publish -p bittorrent-tracker-core cargo publish -p bittorrent-udp-tracker-core cargo publish -p bittorrent-udp-tracker-protocol + cargo publish -p torrust-axum-http-tracker-server cargo publish -p torrust-axum-server cargo publish -p torrust-torrust-server-lib cargo publish -p torrust-tracker @@ -74,3 +75,5 @@ jobs: cargo publish -p torrust-tracker-primitives cargo publish -p torrust-tracker-test-helpers cargo publish -p torrust-tracker-torrent-repository + + diff --git a/Cargo.lock b/Cargo.lock index a62a20619..23092e31e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4337,18 +4337,51 @@ dependencies = [ "winnow", ] +[[package]] +name = "torrust-axum-http-tracker-server" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "axum", + "axum-client-ip", + "axum-server", + "bittorrent-http-tracker-core", + "bittorrent-http-tracker-protocol", + "bittorrent-primitives", + "bittorrent-tracker-core", + "derive_more", + "futures", + "hyper", + "reqwest", + "serde", + "thiserror 2.0.11", + "tokio", + "torrust-axum-server", + "torrust-server-lib", + "torrust-tracker-configuration", + "torrust-tracker-primitives", + "torrust-tracker-test-helpers", + "tower 0.4.13", + "tower-http", + "tracing", +] + [[package]] name = "torrust-axum-server" version = "3.0.0-develop" dependencies = [ "axum-server", + "camino", "futures-util", "http-body", "hyper", "hyper-util", "pin-project-lite", + "thiserror 2.0.11", "tokio", "torrust-server-lib", + "torrust-tracker-configuration", + "torrust-tracker-located-error", "tower 0.4.13", "tracing", ] @@ -4370,16 +4403,13 @@ dependencies = [ "anyhow", "aquatic_udp_protocol", "axum", - "axum-client-ip", "axum-extra", "axum-server", "bittorrent-http-tracker-core", - "bittorrent-http-tracker-protocol", "bittorrent-primitives", "bittorrent-tracker-client", "bittorrent-tracker-core", "bittorrent-udp-tracker-core", - "camino", "chrono", "clap", "crossbeam-skiplist", @@ -4409,6 +4439,7 @@ dependencies = [ "serde_with", "thiserror 2.0.11", "tokio", + "torrust-axum-http-tracker-server", "torrust-axum-server", "torrust-server-lib", "torrust-tracker-api-client", diff --git a/Cargo.toml b/Cargo.toml index 22df92b2d..4f8854d34 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,16 +36,13 @@ version = "3.0.0-develop" anyhow = "1" aquatic_udp_protocol = "0" axum = { version = "0", features = ["macros"] } -axum-client-ip = "0" axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls-no-provider"] } bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "packages/http-tracker-core" } -bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "packages/http-protocol" } bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker-core" } bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "packages/udp-tracker-core" } -camino = { version = "1", features = ["serde", "serde1"] } chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } crossbeam-skiplist = "0" @@ -73,6 +70,7 @@ serde_repr = "0" serde_with = { version = "3", features = ["json"] } thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "packages/axum-http-tracker-server" } torrust-axum-server = { version = "3.0.0-develop", path = "packages/axum-server" } torrust-server-lib = { version = "3.0.0-develop", path = "packages/server-lib" } torrust-tracker-api-core = { version = "3.0.0-develop", path = "packages/tracker-api-core" } diff --git a/packages/axum-http-tracker-server/Cargo.toml b/packages/axum-http-tracker-server/Cargo.toml new file mode 100644 index 000000000..b47ea23ce --- /dev/null +++ b/packages/axum-http-tracker-server/Cargo.toml @@ -0,0 +1,41 @@ +[package] +authors.workspace = true +description = "The Torrust Bittorrent HTTP tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = ["axum", "bittorrent", "http", "server", "torrust", "tracker"] +license.workspace = true +name = "torrust-axum-http-tracker-server" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +axum = { version = "0", features = ["macros"] } +axum-client-ip = "0" +axum-server = { version = "0", features = ["tls-rustls-no-provider"] } +bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "../http-tracker-core" } +bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "../http-protocol" } +bittorrent-primitives = "0.1.0" +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } +futures = "0" +hyper = "1" +reqwest = { version = "0", features = ["json"] } +serde = { version = "1", features = ["derive"] } +thiserror = "2" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } +torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tower = { version = "0", features = ["timeout"] } +tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } +tracing = "0" + +[dev-dependencies] +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/axum-http-tracker-server/LICENSE b/packages/axum-http-tracker-server/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/axum-http-tracker-server/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/axum-http-tracker-server/README.md b/packages/axum-http-tracker-server/README.md new file mode 100644 index 000000000..b7286d157 --- /dev/null +++ b/packages/axum-http-tracker-server/README.md @@ -0,0 +1,11 @@ +# Torrust Axum HTTP Tracker + +The Torrust Bittorrent HTTP tracker. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-axum-server). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/axum-http-tracker-server/src/container.rs b/packages/axum-http-tracker-server/src/container.rs new file mode 100644 index 000000000..c20a8f28f --- /dev/null +++ b/packages/axum-http-tracker-server/src/container.rs @@ -0,0 +1,17 @@ +use std::sync::Arc; + +use bittorrent_tracker_core::announce_handler::AnnounceHandler; +use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use bittorrent_tracker_core::whitelist; +use torrust_tracker_configuration::{Core, HttpTracker}; + +pub struct HttpTrackerContainer { + pub core_config: Arc, + pub http_tracker_config: Arc, + pub announce_handler: Arc, + pub scrape_handler: Arc, + pub whitelist_authorization: Arc, + pub http_stats_event_sender: Arc>>, + pub authentication_service: Arc, +} diff --git a/src/servers/http/mod.rs b/packages/axum-http-tracker-server/src/lib.rs similarity index 99% rename from src/servers/http/mod.rs rename to packages/axum-http-tracker-server/src/lib.rs index 395f633cf..fd2aa8506 100644 --- a/src/servers/http/mod.rs +++ b/packages/axum-http-tracker-server/src/lib.rs @@ -305,6 +305,7 @@ //! - [Bencode to Json Online converter](https://chocobo1.github.io/bencode_online). use serde::{Deserialize, Serialize}; +pub mod container; pub mod server; pub mod test_helpers; pub mod v1; diff --git a/src/servers/http/server.rs b/packages/axum-http-tracker-server/src/server.rs similarity index 73% rename from src/servers/http/server.rs rename to packages/axum-http-tracker-server/src/server.rs index 25a8e5635..39969907b 100644 --- a/src/servers/http/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -11,13 +11,12 @@ use torrust_axum_server::custom_axum_server::{self, TimeoutAcceptor}; use torrust_axum_server::signals::graceful_shutdown; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; -use torrust_server_lib::signals::Halted; +use torrust_server_lib::signals::{Halted, Started}; use tracing::instrument; use super::v1::routes::router; -use crate::bootstrap::jobs::Started; use crate::container::HttpTrackerContainer; -use crate::servers::http::HTTP_TRACKER_LOG_TARGET; +use crate::HTTP_TRACKER_LOG_TARGET; /// Error that can occur when starting or stopping the HTTP server. /// @@ -239,33 +238,92 @@ pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { mod tests { use std::sync::Arc; + use bittorrent_tracker_core::announce_handler::AnnounceHandler; + use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; + use bittorrent_tracker_core::authentication::service; + use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::scrape_handler::ScrapeHandler; + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; + use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; + use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; - use crate::bootstrap::jobs::make_rust_tls; use crate::container::HttpTrackerContainer; - use crate::servers::http::server::{HttpServer, Launcher}; + use crate::server::{HttpServer, Launcher}; + + pub fn initialize_container(configuration: &Configuration) -> HttpTrackerContainer { + let core_config = Arc::new(configuration.core.clone()); + + let http_trackers = configuration + .http_trackers + .clone() + .expect("missing HTTP trackers configuration"); + + let http_tracker_config = &http_trackers[0]; + + let http_tracker_config = Arc::new(http_tracker_config.clone()); + + // HTTP stats + let (http_stats_event_sender, _http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + + let database = initialize_database(&configuration.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&configuration.core, &in_memory_whitelist.clone())); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(service::AuthenticationService::new( + &configuration.core, + &in_memory_key_repository, + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let announce_handler = Arc::new(AnnounceHandler::new( + &configuration.core, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + HttpTrackerContainer { + core_config, + http_tracker_config, + announce_handler, + scrape_handler, + whitelist_authorization, + http_stats_event_sender, + authentication_service, + } + } #[tokio::test] async fn it_should_be_able_to_start_and_stop() { - let cfg = Arc::new(ephemeral_public()); + let configuration = Arc::new(ephemeral_public()); - initialize_global_services(&cfg); + let http_trackers = configuration + .http_trackers + .clone() + .expect("missing HTTP trackers configuration"); - let app_container = Arc::new(initialize_app_container(&cfg)); - - let http_trackers = cfg.http_trackers.clone().expect("missing HTTP trackers configuration"); let http_tracker_config = &http_trackers[0]; + + //initialize_global_services(&cfg); // not needed for this test + + let http_tracker_container = Arc::new(initialize_container(&configuration)); + let bind_to = http_tracker_config.bind_address; let tls = make_rust_tls(&http_tracker_config.tsl_config) .await .map(|tls| tls.expect("tls config failed")); - let http_tracker_config = Arc::new(http_tracker_config.clone()); - let http_tracker_container = Arc::new(HttpTrackerContainer::from_app_container(&http_tracker_config, &app_container)); - let register = &Registar::default(); let stopped = HttpServer::new(Launcher::new(bind_to, tls)); diff --git a/src/servers/http/test_helpers.rs b/packages/axum-http-tracker-server/src/test_helpers.rs similarity index 100% rename from src/servers/http/test_helpers.rs rename to packages/axum-http-tracker-server/src/test_helpers.rs diff --git a/src/servers/http/v1/extractors/announce_request.rs b/packages/axum-http-tracker-server/src/v1/extractors/announce_request.rs similarity index 98% rename from src/servers/http/v1/extractors/announce_request.rs rename to packages/axum-http-tracker-server/src/v1/extractors/announce_request.rs index 3265d04cd..57001a47e 100644 --- a/src/servers/http/v1/extractors/announce_request.rs +++ b/packages/axum-http-tracker-server/src/v1/extractors/announce_request.rs @@ -109,7 +109,7 @@ mod tests { assert_eq!( announce, Announce { - info_hash: InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(), + info_hash: InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(), // DevSkim: ignore DS173237 peer_id: PeerId(*b"-qB00000000000000001"), port: 17548, downloaded: Some(NumberOfBytes::new(0)), diff --git a/src/servers/http/v1/extractors/authentication_key.rs b/packages/axum-http-tracker-server/src/v1/extractors/authentication_key.rs similarity index 98% rename from src/servers/http/v1/extractors/authentication_key.rs rename to packages/axum-http-tracker-server/src/v1/extractors/authentication_key.rs index da4cd2217..89781f48b 100644 --- a/src/servers/http/v1/extractors/authentication_key.rs +++ b/packages/axum-http-tracker-server/src/v1/extractors/authentication_key.rs @@ -54,7 +54,7 @@ use bittorrent_tracker_core::authentication::Key; use hyper::StatusCode; use serde::Deserialize; -use crate::servers::http::v1::handlers::common::auth; +use crate::v1::handlers::common::auth; /// Extractor for the [`Key`] struct. pub struct Extract(pub Key); diff --git a/src/servers/http/v1/extractors/client_ip_sources.rs b/packages/axum-http-tracker-server/src/v1/extractors/client_ip_sources.rs similarity index 100% rename from src/servers/http/v1/extractors/client_ip_sources.rs rename to packages/axum-http-tracker-server/src/v1/extractors/client_ip_sources.rs diff --git a/src/servers/http/v1/extractors/mod.rs b/packages/axum-http-tracker-server/src/v1/extractors/mod.rs similarity index 100% rename from src/servers/http/v1/extractors/mod.rs rename to packages/axum-http-tracker-server/src/v1/extractors/mod.rs diff --git a/src/servers/http/v1/extractors/scrape_request.rs b/packages/axum-http-tracker-server/src/v1/extractors/scrape_request.rs similarity index 99% rename from src/servers/http/v1/extractors/scrape_request.rs rename to packages/axum-http-tracker-server/src/v1/extractors/scrape_request.rs index 66442da95..33a998ff2 100644 --- a/src/servers/http/v1/extractors/scrape_request.rs +++ b/packages/axum-http-tracker-server/src/v1/extractors/scrape_request.rs @@ -100,7 +100,7 @@ mod tests { fn test_info_hash() -> TestInfoHash { TestInfoHash { bencoded: "%3B%24U%04%CF%5F%11%BB%DB%E1%20%1C%EAjk%F4Z%EE%1B%C0".to_owned(), - value: InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(), + value: InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(), // DevSkim: ignore DS173237 } } diff --git a/src/servers/http/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs similarity index 94% rename from src/servers/http/v1/handlers/announce.rs rename to packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 1aa062faa..43122f8bd 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -21,9 +21,9 @@ use hyper::StatusCode; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; -use crate::servers::http::v1::extractors::announce_request::ExtractRequest; -use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; -use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; +use crate::v1::extractors::announce_request::ExtractRequest; +use crate::v1::extractors::authentication_key::Extract as ExtractKey; +use crate::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; /// It handles the `announce` request when the HTTP tracker does not require /// authentication (no PATH `key` parameter required). @@ -199,7 +199,7 @@ mod tests { use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; - use crate::servers::http::test_helpers::tests::sample_info_hash; + use crate::test_helpers::tests::sample_info_hash; struct CoreTrackerServices { pub core_config: Arc, @@ -296,8 +296,8 @@ mod tests { use bittorrent_tracker_core::authentication; use super::{initialize_private_tracker, sample_announce_request, sample_client_ip_sources}; - use crate::servers::http::v1::handlers::announce::handle_announce; - use crate::servers::http::v1::handlers::announce::tests::assert_error_response; + use crate::v1::handlers::announce::handle_announce; + use crate::v1::handlers::announce::tests::assert_error_response; #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_missing() { @@ -352,8 +352,8 @@ mod tests { mod with_tracker_in_listed_mode { use super::{initialize_listed_tracker, sample_announce_request, sample_client_ip_sources}; - use crate::servers::http::v1::handlers::announce::handle_announce; - use crate::servers::http::v1::handlers::announce::tests::assert_error_response; + use crate::v1::handlers::announce::handle_announce; + use crate::v1::handlers::announce::tests::assert_error_response; #[tokio::test] async fn it_should_fail_when_the_announced_torrent_is_not_whitelisted() { @@ -389,8 +389,8 @@ mod tests { use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use super::{initialize_tracker_on_reverse_proxy, sample_announce_request}; - use crate::servers::http::v1::handlers::announce::handle_announce; - use crate::servers::http::v1::handlers::announce::tests::assert_error_response; + use crate::v1::handlers::announce::handle_announce; + use crate::v1::handlers::announce::tests::assert_error_response; #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { @@ -426,8 +426,8 @@ mod tests { use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use super::{initialize_tracker_not_on_reverse_proxy, sample_announce_request}; - use crate::servers::http::v1::handlers::announce::handle_announce; - use crate::servers::http::v1::handlers::announce::tests::assert_error_response; + use crate::v1::handlers::announce::handle_announce; + use crate::v1::handlers::announce::tests::assert_error_response; #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { diff --git a/src/servers/http/v1/handlers/common/auth.rs b/packages/axum-http-tracker-server/src/v1/handlers/common/auth.rs similarity index 100% rename from src/servers/http/v1/handlers/common/auth.rs rename to packages/axum-http-tracker-server/src/v1/handlers/common/auth.rs diff --git a/src/servers/http/v1/handlers/common/mod.rs b/packages/axum-http-tracker-server/src/v1/handlers/common/mod.rs similarity index 100% rename from src/servers/http/v1/handlers/common/mod.rs rename to packages/axum-http-tracker-server/src/v1/handlers/common/mod.rs diff --git a/src/servers/http/v1/handlers/common/peer_ip.rs b/packages/axum-http-tracker-server/src/v1/handlers/common/peer_ip.rs similarity index 100% rename from src/servers/http/v1/handlers/common/peer_ip.rs rename to packages/axum-http-tracker-server/src/v1/handlers/common/peer_ip.rs diff --git a/src/servers/http/v1/handlers/health_check.rs b/packages/axum-http-tracker-server/src/v1/handlers/health_check.rs similarity index 100% rename from src/servers/http/v1/handlers/health_check.rs rename to packages/axum-http-tracker-server/src/v1/handlers/health_check.rs diff --git a/src/servers/http/v1/handlers/mod.rs b/packages/axum-http-tracker-server/src/v1/handlers/mod.rs similarity index 100% rename from src/servers/http/v1/handlers/mod.rs rename to packages/axum-http-tracker-server/src/v1/handlers/mod.rs diff --git a/src/servers/http/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs similarity index 95% rename from src/servers/http/v1/handlers/scrape.rs rename to packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index 02a5b3136..a4e20cc6f 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -19,9 +19,9 @@ use hyper::StatusCode; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; -use crate::servers::http::v1::extractors::authentication_key::Extract as ExtractKey; -use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; -use crate::servers::http::v1::extractors::scrape_request::ExtractRequest; +use crate::v1::extractors::authentication_key::Extract as ExtractKey; +use crate::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; +use crate::v1::extractors::scrape_request::ExtractRequest; /// It handles the `scrape` request when the HTTP tracker is configured /// to run in `public` mode. @@ -234,7 +234,7 @@ mod tests { use torrust_tracker_primitives::core::ScrapeData; use super::{initialize_private_tracker, sample_client_ip_sources, sample_scrape_request}; - use crate::servers::http::v1::handlers::scrape::handle_scrape; + use crate::v1::handlers::scrape::handle_scrape; #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { @@ -291,7 +291,7 @@ mod tests { use torrust_tracker_primitives::core::ScrapeData; use super::{initialize_listed_tracker, sample_client_ip_sources, sample_scrape_request}; - use crate::servers::http::v1::handlers::scrape::handle_scrape; + use crate::v1::handlers::scrape::handle_scrape; #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() { @@ -322,8 +322,8 @@ mod tests { use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use super::{initialize_tracker_on_reverse_proxy, sample_scrape_request}; - use crate::servers::http::v1::handlers::scrape::handle_scrape; - use crate::servers::http::v1::handlers::scrape::tests::assert_error_response; + use crate::v1::handlers::scrape::handle_scrape; + use crate::v1::handlers::scrape::tests::assert_error_response; #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { @@ -358,8 +358,8 @@ mod tests { use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use super::{initialize_tracker_not_on_reverse_proxy, sample_scrape_request}; - use crate::servers::http::v1::handlers::scrape::handle_scrape; - use crate::servers::http::v1::handlers::scrape::tests::assert_error_response; + use crate::v1::handlers::scrape::handle_scrape; + use crate::v1::handlers::scrape::tests::assert_error_response; #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { diff --git a/src/servers/http/v1/mod.rs b/packages/axum-http-tracker-server/src/v1/mod.rs similarity index 100% rename from src/servers/http/v1/mod.rs rename to packages/axum-http-tracker-server/src/v1/mod.rs diff --git a/src/servers/http/v1/routes.rs b/packages/axum-http-tracker-server/src/v1/routes.rs similarity index 99% rename from src/servers/http/v1/routes.rs rename to packages/axum-http-tracker-server/src/v1/routes.rs index 5f2d95a8e..2d530f633 100644 --- a/src/servers/http/v1/routes.rs +++ b/packages/axum-http-tracker-server/src/v1/routes.rs @@ -24,7 +24,7 @@ use tracing::{instrument, Level, Span}; use super::handlers::{announce, health_check, scrape}; use crate::container::HttpTrackerContainer; -use crate::servers::http::HTTP_TRACKER_LOG_TARGET; +use crate::HTTP_TRACKER_LOG_TARGET; /// It adds the routes to the router. /// diff --git a/packages/axum-server/Cargo.toml b/packages/axum-server/Cargo.toml index 6604a0555..a60bab885 100644 --- a/packages/axum-server/Cargo.toml +++ b/packages/axum-server/Cargo.toml @@ -15,13 +15,17 @@ version.workspace = true [dependencies] axum-server = { version = "0", features = ["tls-rustls-no-provider"] } +camino = { version = "1", features = ["serde", "serde1"] } futures-util = "0" http-body = "1" hyper = "1" hyper-util = { version = "0", features = ["http1", "http2", "tokio"] } pin-project-lite = "0" +thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } tower = { version = "0", features = ["timeout"] } tracing = "0" diff --git a/packages/axum-server/src/lib.rs b/packages/axum-server/src/lib.rs index 06de31d8c..88bf25f19 100644 --- a/packages/axum-server/src/lib.rs +++ b/packages/axum-server/src/lib.rs @@ -1,2 +1,3 @@ pub mod custom_axum_server; pub mod signals; +pub mod tsl; diff --git a/packages/axum-server/src/tsl.rs b/packages/axum-server/src/tsl.rs new file mode 100644 index 000000000..5d68b5b4c --- /dev/null +++ b/packages/axum-server/src/tsl.rs @@ -0,0 +1,85 @@ +use std::panic::Location; +use std::sync::Arc; + +use axum_server::tls_rustls::RustlsConfig; +use thiserror::Error; +use torrust_tracker_configuration::TslConfig; +use torrust_tracker_located_error::{DynError, LocatedError}; +use tracing::instrument; + +/// Error returned by the Bootstrap Process. +#[derive(Error, Debug)] +pub enum Error { + /// Enabled tls but missing config. + #[error("tls config missing")] + MissingTlsConfig { location: &'static Location<'static> }, + + /// Unable to parse tls Config. + #[error("bad tls config: {source}")] + BadTlsConfig { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, + }, +} + +#[instrument(skip(opt_tsl_config))] +pub async fn make_rust_tls(opt_tsl_config: &Option) -> Option> { + match opt_tsl_config { + Some(tsl_config) => { + let cert = tsl_config.ssl_cert_path.clone(); + let key = tsl_config.ssl_key_path.clone(); + + if !cert.exists() || !key.exists() { + return Some(Err(Error::MissingTlsConfig { + location: Location::caller(), + })); + } + + tracing::info!("Using https: cert path: {cert}."); + tracing::info!("Using https: key path: {key}."); + + Some( + RustlsConfig::from_pem_file(cert, key) + .await + .map_err(|err| Error::BadTlsConfig { + source: (Arc::new(err) as DynError).into(), + }), + ) + } + None => None, + } +} + +#[cfg(test)] +mod tests { + + use camino::Utf8PathBuf; + use torrust_tracker_configuration::TslConfig; + + use super::{make_rust_tls, Error}; + + #[tokio::test] + async fn it_should_error_on_bad_tls_config() { + let err = make_rust_tls(&Some(TslConfig { + ssl_cert_path: Utf8PathBuf::from("bad cert path"), + ssl_key_path: Utf8PathBuf::from("bad key path"), + })) + .await + .expect("tls_was_enabled") + .expect_err("bad_cert_and_key_files"); + + assert!(matches!(err, Error::MissingTlsConfig { location: _ })); + } + + #[tokio::test] + async fn it_should_error_on_missing_cert_or_key_paths() { + let err = make_rust_tls(&Some(TslConfig { + ssl_cert_path: Utf8PathBuf::from(""), + ssl_key_path: Utf8PathBuf::from(""), + })) + .await + .expect("tls_was_enabled") + .expect_err("missing_config"); + + assert!(matches!(err, Error::MissingTlsConfig { location: _ })); + } +} diff --git a/packages/server-lib/src/signals.rs b/packages/server-lib/src/signals.rs index b5cff03c1..63f7554c8 100644 --- a/packages/server-lib/src/signals.rs +++ b/packages/server-lib/src/signals.rs @@ -2,6 +2,14 @@ use derive_more::Display; use tracing::instrument; +/// This is the message that the "launcher" spawned task sends to the main +/// application process to notify the service was successfully started. +/// +#[derive(Debug)] +pub struct Started { + pub address: std::net::SocketAddr, +} + /// This is the message that the "launcher" spawned task receives from the main /// application process to notify the service to shutdown. /// diff --git a/src/app.rs b/src/app.rs index c13414b3b..2f712cf3a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -29,7 +29,7 @@ use torrust_tracker_configuration::Configuration; use tracing::instrument; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; -use crate::container::{AppContainer, HttpApiContainer, HttpTrackerContainer, UdpTrackerContainer}; +use crate::container::{AppContainer, HttpApiContainer, UdpTrackerContainer}; use crate::servers; /// # Panics @@ -92,10 +92,14 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> if let Some(http_trackers) = &config.http_trackers { for http_tracker_config in http_trackers { let http_tracker_config = Arc::new(http_tracker_config.clone()); - let http_tracker_container = Arc::new(HttpTrackerContainer::from_app_container(&http_tracker_config, app_container)); + let http_tracker_container = Arc::new(app_container.http_tracker_container(&http_tracker_config)); - if let Some(job) = - http_tracker::start_job(http_tracker_container, registar.give_form(), servers::http::Version::V1).await + if let Some(job) = http_tracker::start_job( + http_tracker_container, + registar.give_form(), + torrust_axum_http_tracker_server::Version::V1, + ) + .await { jobs.push(job); } diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index 95c3bfc24..d64ca0073 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -18,11 +18,10 @@ use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::ServiceRegistry; -use torrust_server_lib::signals::Halted; +use torrust_server_lib::signals::{Halted, Started}; use torrust_tracker_configuration::HealthCheckApi; use tracing::instrument; -use super::Started; use crate::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; /// This function starts a new Health Check API server with the provided diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 38aeb4028..2052bf50b 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -15,14 +15,13 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; +use torrust_axum_http_tracker_server::container::HttpTrackerContainer; +use torrust_axum_http_tracker_server::server::{HttpServer, Launcher}; +use torrust_axum_http_tracker_server::Version; +use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::ServiceRegistrationForm; use tracing::instrument; -use super::make_rust_tls; -use crate::container::HttpTrackerContainer; -use crate::servers::http::server::{HttpServer, Launcher}; -use crate::servers::http::Version; - /// It starts a new HTTP server with the provided configuration and version. /// /// Right now there is only one version but in the future we could support more than one HTTP tracker version at the same time. @@ -78,13 +77,12 @@ async fn start_v1( mod tests { use std::sync::Arc; + use torrust_axum_http_tracker_server::Version; use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; use crate::bootstrap::jobs::http_tracker::start_job; - use crate::container::HttpTrackerContainer; - use crate::servers::http::Version; #[tokio::test] async fn it_should_start_http_tracker() { @@ -96,7 +94,7 @@ mod tests { let app_container = Arc::new(initialize_app_container(&cfg)); - let http_tracker_container = Arc::new(HttpTrackerContainer::from_app_container(&http_tracker_config, &app_container)); + let http_tracker_container = Arc::new(app_container.http_tracker_container(&http_tracker_config)); let version = Version::V1; diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 6e18ec3ba..8c85ba45b 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -11,97 +11,3 @@ pub mod http_tracker; pub mod torrent_cleanup; pub mod tracker_apis; pub mod udp_tracker; - -/// This is the message that the "launcher" spawned task sends to the main -/// application process to notify the service was successfully started. -/// -#[derive(Debug)] -pub struct Started { - pub address: std::net::SocketAddr, -} - -#[instrument(skip(opt_tsl_config))] -pub async fn make_rust_tls(opt_tsl_config: &Option) -> Option> { - match opt_tsl_config { - Some(tsl_config) => { - let cert = tsl_config.ssl_cert_path.clone(); - let key = tsl_config.ssl_key_path.clone(); - - if !cert.exists() || !key.exists() { - return Some(Err(Error::MissingTlsConfig { - location: Location::caller(), - })); - } - - tracing::info!("Using https: cert path: {cert}."); - tracing::info!("Using https: key path: {key}."); - - Some( - RustlsConfig::from_pem_file(cert, key) - .await - .map_err(|err| Error::BadTlsConfig { - source: (Arc::new(err) as DynError).into(), - }), - ) - } - None => None, - } -} - -#[cfg(test)] -mod tests { - - use camino::Utf8PathBuf; - use torrust_tracker_configuration::TslConfig; - - use super::{make_rust_tls, Error}; - - #[tokio::test] - async fn it_should_error_on_bad_tls_config() { - let err = make_rust_tls(&Some(TslConfig { - ssl_cert_path: Utf8PathBuf::from("bad cert path"), - ssl_key_path: Utf8PathBuf::from("bad key path"), - })) - .await - .expect("tls_was_enabled") - .expect_err("bad_cert_and_key_files"); - - assert!(matches!(err, Error::MissingTlsConfig { location: _ })); - } - - #[tokio::test] - async fn it_should_error_on_missing_cert_or_key_paths() { - let err = make_rust_tls(&Some(TslConfig { - ssl_cert_path: Utf8PathBuf::from(""), - ssl_key_path: Utf8PathBuf::from(""), - })) - .await - .expect("tls_was_enabled") - .expect_err("missing_config"); - - assert!(matches!(err, Error::MissingTlsConfig { location: _ })); - } -} - -use std::panic::Location; -use std::sync::Arc; - -use axum_server::tls_rustls::RustlsConfig; -use thiserror::Error; -use torrust_tracker_configuration::TslConfig; -use torrust_tracker_located_error::{DynError, LocatedError}; -use tracing::instrument; - -/// Error returned by the Bootstrap Process. -#[derive(Error, Debug)] -pub enum Error { - /// Enabled tls but missing config. - #[error("tls config missing")] - MissingTlsConfig { location: &'static Location<'static> }, - - /// Unable to parse tls Config. - #[error("bad tls config: {source}")] - BadTlsConfig { - source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - }, -} diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 1f43ee67c..df736f23f 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -25,11 +25,11 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; +use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::ServiceRegistrationForm; use torrust_tracker_configuration::AccessTokens; use tracing::instrument; -use super::make_rust_tls; use crate::container::HttpApiContainer; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::apis::Version; diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index dd2fbdb53..fdbe5d9c0 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -2,10 +2,10 @@ use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use regex::Regex; use serde::{Deserialize, Serialize}; +use torrust_axum_http_tracker_server::HTTP_TRACKER_LOG_TARGET; use torrust_server_lib::logging::STARTED_ON; use crate::servers::health_check_api::HEALTH_CHECK_API_LOG_TARGET; -use crate::servers::http::HTTP_TRACKER_LOG_TARGET; const INFO_THRESHOLD: &str = "INFO"; diff --git a/src/container.rs b/src/container.rs index 0f4a840cf..57e24334b 100644 --- a/src/container.rs +++ b/src/container.rs @@ -14,6 +14,7 @@ use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self}; use tokio::sync::RwLock; +use torrust_axum_http_tracker_server::container::HttpTrackerContainer; use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; pub struct AppContainer { @@ -36,6 +37,21 @@ pub struct AppContainer { pub torrents_manager: Arc, } +impl AppContainer { + #[must_use] + pub fn http_tracker_container(&self, http_tracker_config: &Arc) -> HttpTrackerContainer { + HttpTrackerContainer { + http_tracker_config: http_tracker_config.clone(), + core_config: self.core_config.clone(), + announce_handler: self.announce_handler.clone(), + scrape_handler: self.scrape_handler.clone(), + whitelist_authorization: self.whitelist_authorization.clone(), + http_stats_event_sender: self.http_stats_event_sender.clone(), + authentication_service: self.authentication_service.clone(), + } + } +} + pub struct UdpTrackerContainer { pub core_config: Arc, pub udp_tracker_config: Arc, @@ -61,31 +77,6 @@ impl UdpTrackerContainer { } } -pub struct HttpTrackerContainer { - pub core_config: Arc, - pub http_tracker_config: Arc, - pub announce_handler: Arc, - pub scrape_handler: Arc, - pub whitelist_authorization: Arc, - pub http_stats_event_sender: Arc>>, - pub authentication_service: Arc, -} - -impl HttpTrackerContainer { - #[must_use] - pub fn from_app_container(http_tracker_config: &Arc, app_container: &Arc) -> Self { - Self { - http_tracker_config: http_tracker_config.clone(), - core_config: app_container.core_config.clone(), - announce_handler: app_container.announce_handler.clone(), - scrape_handler: app_container.scrape_handler.clone(), - whitelist_authorization: app_container.whitelist_authorization.clone(), - http_stats_event_sender: app_container.http_stats_event_sender.clone(), - authentication_service: app_container.authentication_service.clone(), - } - } -} - pub struct HttpApiContainer { pub core_config: Arc, pub http_api_config: Arc, diff --git a/src/lib.rs b/src/lib.rs index a864587c5..4f552ab34 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -57,7 +57,7 @@ //! //! - A REST [`API`](crate::servers::apis) //! - One or more [`UDP`](crate::servers::udp) trackers -//! - One or more [`HTTP`](crate::servers::http) trackers +//! - One or more [`HTTP`](torrust_axum_http_tracker_server) trackers //! //! # Installation //! @@ -124,7 +124,7 @@ //! By default the tracker uses `SQLite` and the database file name `sqlite3.db`. //! //! You only need the `tls` directory in case you are setting up SSL for the HTTP tracker or the tracker API. -//! Visit [`HTTP`](crate::servers::http) or [`API`](crate::servers::apis) if you want to know how you can use HTTPS. +//! Visit [`HTTP`](torrust_axum_http_tracker_server) or [`API`](crate::servers::apis) if you want to know how you can use HTTPS. //! //! ## Install from sources //! @@ -301,7 +301,7 @@ //! bind_address = "0.0.0.0:7070" //! ``` //! -//! Refer to the [`HTTP`](crate::servers::http) documentation for more information about the [`HTTP`](crate::servers::http) tracker. +//! Refer to the [`HTTP`](torrust_axum_http_tracker_server) documentation for more information about the [`HTTP`](torrust_axum_http_tracker_server) tracker. //! //! ### Announce //! @@ -408,7 +408,7 @@ //! - The core tracker [`core`] //! - The tracker REST [`API`](crate::servers::apis) //! - The [`UDP`](crate::servers::udp) tracker -//! - The [`HTTP`](crate::servers::http) tracker +//! - The [`HTTP`](torrust_axum_http_tracker_server) tracker //! //! ![Torrust Tracker Components](https://raw.githubusercontent.com/torrust/torrust-tracker/main/docs/media/torrust-tracker-components.png) //! @@ -452,7 +452,7 @@ //! //! HTTP tracker was the original tracker specification defined on the [BEP 3]((https://www.bittorrent.org/beps/bep_0003.html)). //! -//! See [`HTTP`](crate::servers::http) for more details on the HTTP tracker. +//! See [`HTTP`](torrust_axum_http_tracker_server) for more details on the HTTP tracker. //! //! You can find more information about UDP tracker on: //! diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 47473d964..187969f8d 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -37,12 +37,11 @@ use torrust_axum_server::custom_axum_server::{self, TimeoutAcceptor}; use torrust_axum_server::signals::graceful_shutdown; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; -use torrust_server_lib::signals::Halted; +use torrust_server_lib::signals::{Halted, Started}; use torrust_tracker_configuration::AccessTokens; use tracing::{instrument, Level}; use super::routes::router; -use crate::bootstrap::jobs::Started; use crate::container::HttpApiContainer; use crate::servers::apis::API_LOG_TARGET; @@ -295,11 +294,11 @@ impl Launcher { mod tests { use std::sync::Arc; + use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; - use crate::bootstrap::jobs::make_rust_tls; use crate::container::HttpApiContainer; use crate::servers::apis::server::{ApiServer, Launcher}; diff --git a/src/servers/health_check_api/server.rs b/src/servers/health_check_api/server.rs index 06dd5af65..6f468b98e 100644 --- a/src/servers/health_check_api/server.rs +++ b/src/servers/health_check_api/server.rs @@ -17,7 +17,7 @@ use tokio::sync::oneshot::{Receiver, Sender}; use torrust_axum_server::signals::graceful_shutdown; use torrust_server_lib::logging::Latency; use torrust_server_lib::registar::ServiceRegistry; -use torrust_server_lib::signals::Halted; +use torrust_server_lib::signals::{Halted, Started}; use tower_http::classify::ServerErrorsFailureClass; use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; @@ -26,7 +26,6 @@ use tower_http::trace::{DefaultMakeSpan, TraceLayer}; use tower_http::LatencyUnit; use tracing::{instrument, Level, Span}; -use crate::bootstrap::jobs::Started; use crate::servers::health_check_api::handlers::health_check_handler; use crate::servers::health_check_api::HEALTH_CHECK_API_LOG_TARGET; diff --git a/src/servers/mod.rs b/src/servers/mod.rs index eb5e5fee7..037179ba8 100644 --- a/src/servers/mod.rs +++ b/src/servers/mod.rs @@ -1,5 +1,4 @@ //! Servers. Services that can be started and stopped. pub mod apis; pub mod health_check_api; -pub mod http; pub mod udp; diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index f85972721..dbf0d5693 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -11,11 +11,10 @@ use tokio::sync::oneshot; use tokio::time::interval; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::ServiceHealthCheckJob; -use torrust_server_lib::signals::{shutdown_signal_with_message, Halted}; +use torrust_server_lib::signals::{shutdown_signal_with_message, Halted, Started}; use tracing::instrument; use super::request_buffer::ActiveRequests; -use crate::bootstrap::jobs::Started; use crate::container::UdpTrackerContainer; use crate::servers::udp::server::bound_socket::BoundSocket; use crate::servers::udp::server::processor::Processor; diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index 34437cdfb..fd85a57c9 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -7,10 +7,9 @@ use derive_more::derive::Display; use derive_more::Constructor; use tokio::sync::oneshot; use tokio::task::JoinHandle; -use torrust_server_lib::signals::Halted; +use torrust_server_lib::signals::{Halted, Started}; use super::launcher::Launcher; -use crate::bootstrap::jobs::Started; use crate::container::UdpTrackerContainer; #[derive(Constructor, Copy, Clone, Debug, Display)] diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index 123d7f8a5..ae499acf7 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -8,12 +8,11 @@ use derive_more::derive::Display; use derive_more::Constructor; use tokio::task::JoinHandle; use torrust_server_lib::registar::{ServiceRegistration, ServiceRegistrationForm}; -use torrust_server_lib::signals::Halted; +use torrust_server_lib::signals::{Halted, Started}; use tracing::{instrument, Level}; use super::spawner::Spawner; use super::{Server, UdpError}; -use crate::bootstrap::jobs::Started; use crate::container::UdpTrackerContainer; use crate::servers::udp::server::launcher::Launcher; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index cc7574895..b899c9f02 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -6,11 +6,11 @@ use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::Database; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::executor::block_on; +use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; -use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; use torrust_tracker_lib::container::HttpApiContainer; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_primitives::peer; diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs index e364a52cb..b83240767 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/tests/servers/health_check_api/environment.rs @@ -4,9 +4,8 @@ use std::sync::Arc; use tokio::sync::oneshot::{self, Sender}; use tokio::task::JoinHandle; use torrust_server_lib::registar::Registar; -use torrust_server_lib::signals::{self, Halted}; +use torrust_server_lib::signals::{self, Halted, Started}; use torrust_tracker_configuration::HealthCheckApi; -use torrust_tracker_lib::bootstrap::jobs::Started; use torrust_tracker_lib::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; #[derive(Debug)] diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 2584c51c7..4afb262d7 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -6,12 +6,12 @@ use bittorrent_tracker_core::databases::Database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use futures::executor::block_on; +use torrust_axum_http_tracker_server::container::HttpTrackerContainer; +use torrust_axum_http_tracker_server::server::{HttpServer, Launcher, Running, Stopped}; +use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; -use torrust_tracker_lib::bootstrap::jobs::make_rust_tls; -use torrust_tracker_lib::container::HttpTrackerContainer; -use torrust_tracker_lib::servers::http::server::{HttpServer, Launcher, Running, Stopped}; use torrust_tracker_primitives::peer; pub struct Environment { diff --git a/tests/servers/http/mod.rs b/tests/servers/http/mod.rs index adcdcbf5e..37d4dcd3d 100644 --- a/tests/servers/http/mod.rs +++ b/tests/servers/http/mod.rs @@ -5,10 +5,10 @@ pub mod requests; pub mod responses; pub mod v1; -pub type Started = environment::Environment; - use percent_encoding::NON_ALPHANUMERIC; -use torrust_tracker_lib::servers::http::server; +use torrust_axum_http_tracker_server::server; + +pub type Started = environment::Environment; pub type ByteArray20 = [u8; 20]; diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index bab969403..1931544b9 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -14,7 +14,7 @@ async fn environment_should_be_started_and_stopped() { mod for_all_config_modes { - use torrust_tracker_lib::servers::http::v1::handlers::health_check::{Report, Status}; + use torrust_axum_http_tracker_server::v1::handlers::health_check::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; From 2b72ae07ce3dbf3073c5755178663fbdc25148d0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Feb 2025 11:16:36 +0000 Subject: [PATCH 0784/1297] refactor: [#1283] move test helpers to main test mod in package --- packages/axum-http-tracker-server/src/lib.rs | 19 ++++++++++++++++++- .../src/test_helpers.rs | 16 ---------------- .../src/v1/handlers/announce.rs | 2 +- 3 files changed, 19 insertions(+), 18 deletions(-) delete mode 100644 packages/axum-http-tracker-server/src/test_helpers.rs diff --git a/packages/axum-http-tracker-server/src/lib.rs b/packages/axum-http-tracker-server/src/lib.rs index fd2aa8506..3d9f6d1b7 100644 --- a/packages/axum-http-tracker-server/src/lib.rs +++ b/packages/axum-http-tracker-server/src/lib.rs @@ -307,7 +307,6 @@ use serde::{Deserialize, Serialize}; pub mod container; pub mod server; -pub mod test_helpers; pub mod v1; pub const HTTP_TRACKER_LOG_TARGET: &str = "HTTP TRACKER"; @@ -318,3 +317,21 @@ pub enum Version { /// The `v1` version of the HTTP tracker. V1, } + +#[cfg(test)] +pub(crate) mod tests { + + pub(crate) mod helpers { + use bittorrent_primitives::info_hash::InfoHash; + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + } +} diff --git a/packages/axum-http-tracker-server/src/test_helpers.rs b/packages/axum-http-tracker-server/src/test_helpers.rs deleted file mode 100644 index 8c3020c52..000000000 --- a/packages/axum-http-tracker-server/src/test_helpers.rs +++ /dev/null @@ -1,16 +0,0 @@ -//! Some generic test helpers functions. - -#[cfg(test)] -pub(crate) mod tests { - use bittorrent_primitives::info_hash::InfoHash; - - /// # Panics - /// - /// Will panic if the string representation of the info hash is not a valid info hash. - #[must_use] - pub fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 - .parse::() - .expect("String should be a valid info hash") - } -} diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 43122f8bd..f8f551253 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -199,7 +199,7 @@ mod tests { use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; - use crate::test_helpers::tests::sample_info_hash; + use crate::tests::helpers::sample_info_hash; struct CoreTrackerServices { pub core_config: Arc, From 3e81d3ec9361bde2c15a63d4287e6bb42fda6c70 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Feb 2025 12:20:49 +0000 Subject: [PATCH 0785/1297] refactor: [#1287] extract axum-health-check-api-server package --- .github/workflows/deployment.yaml | 3 +- Cargo.lock | 18 + Cargo.toml | 1 + cSpell.json | 1 + .../axum-health-check-api-server/Cargo.toml | 29 + packages/axum-health-check-api-server/LICENSE | 661 ++++++++++++++++++ .../axum-health-check-api-server/README.md | 49 ++ .../src}/handlers.rs | 0 .../axum-health-check-api-server/src/lib.rs | 0 .../src}/resources.rs | 0 .../src}/responses.rs | 0 .../src}/server.rs | 4 +- src/bootstrap/jobs/health_check_api.rs | 3 +- src/console/ci/e2e/logs_parser.rs | 3 +- src/servers/mod.rs | 1 - tests/servers/health_check_api/contract.rs | 8 +- tests/servers/health_check_api/environment.rs | 2 +- 17 files changed, 769 insertions(+), 14 deletions(-) create mode 100644 packages/axum-health-check-api-server/Cargo.toml create mode 100644 packages/axum-health-check-api-server/LICENSE create mode 100644 packages/axum-health-check-api-server/README.md rename {src/servers/health_check_api => packages/axum-health-check-api-server/src}/handlers.rs (100%) rename src/servers/health_check_api/mod.rs => packages/axum-health-check-api-server/src/lib.rs (100%) rename {src/servers/health_check_api => packages/axum-health-check-api-server/src}/resources.rs (100%) rename {src/servers/health_check_api => packages/axum-health-check-api-server/src}/responses.rs (100%) rename {src/servers/health_check_api => packages/axum-health-check-api-server/src}/server.rs (97%) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 296752df4..5aca88ac4 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -61,6 +61,7 @@ jobs: cargo publish -p bittorrent-tracker-core cargo publish -p bittorrent-udp-tracker-core cargo publish -p bittorrent-udp-tracker-protocol + cargo publish -p torrust-axum-health-check-api-server cargo publish -p torrust-axum-http-tracker-server cargo publish -p torrust-axum-server cargo publish -p torrust-torrust-server-lib @@ -75,5 +76,3 @@ jobs: cargo publish -p torrust-tracker-primitives cargo publish -p torrust-tracker-test-helpers cargo publish -p torrust-tracker-torrent-repository - - diff --git a/Cargo.lock b/Cargo.lock index 23092e31e..1c30e5128 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4337,6 +4337,23 @@ dependencies = [ "winnow", ] +[[package]] +name = "torrust-axum-health-check-api-server" +version = "3.0.0-develop" +dependencies = [ + "axum", + "axum-server", + "futures", + "hyper", + "serde", + "serde_json", + "tokio", + "torrust-axum-server", + "torrust-server-lib", + "tower-http", + "tracing", +] + [[package]] name = "torrust-axum-http-tracker-server" version = "3.0.0-develop" @@ -4439,6 +4456,7 @@ dependencies = [ "serde_with", "thiserror 2.0.11", "tokio", + "torrust-axum-health-check-api-server", "torrust-axum-http-tracker-server", "torrust-axum-server", "torrust-server-lib", diff --git a/Cargo.toml b/Cargo.toml index 4f8854d34..20d7c00dd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,6 +70,7 @@ serde_repr = "0" serde_with = { version = "3", features = ["json"] } thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "packages/axum-health-check-api-server" } torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "packages/axum-http-tracker-server" } torrust-axum-server = { version = "3.0.0-develop", path = "packages/axum-server" } torrust-server-lib = { version = "3.0.0-develop", path = "packages/server-lib" } diff --git a/cSpell.json b/cSpell.json index b1e9a5e95..e067df932 100644 --- a/cSpell.json +++ b/cSpell.json @@ -63,6 +63,7 @@ "gecos", "Grcov", "hasher", + "healthcheck", "heaptrack", "hexlify", "hlocalhost", diff --git a/packages/axum-health-check-api-server/Cargo.toml b/packages/axum-health-check-api-server/Cargo.toml new file mode 100644 index 000000000..37e49f9e7 --- /dev/null +++ b/packages/axum-health-check-api-server/Cargo.toml @@ -0,0 +1,29 @@ +[package] +authors.workspace = true +description = "The Torrust Bittorrent HTTP tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = ["axum", "bittorrent", "healthcheck", "http", "server", "torrust", "tracker"] +license.workspace = true +name = "torrust-axum-health-check-api-server" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +axum = { version = "0", features = ["macros"] } +axum-server = { version = "0", features = ["tls-rustls-no-provider"] } +futures = "0" +hyper = "1" +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["preserve_order"] } +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } +torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } +tracing = "0" + +[dev-dependencies] diff --git a/packages/axum-health-check-api-server/LICENSE b/packages/axum-health-check-api-server/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/axum-health-check-api-server/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/axum-health-check-api-server/README.md b/packages/axum-health-check-api-server/README.md new file mode 100644 index 000000000..d4c6b4f0b --- /dev/null +++ b/packages/axum-health-check-api-server/README.md @@ -0,0 +1,49 @@ +# Torrust Axum HTTP Tracker + +The Torrust Tracker Health Check API. + +The Torrust tracker container starts a local HTTP server on port 1313 to check all services. + +It's used for the container health check. + +URL: + +Example response: + +```json +{ + "status": "Ok", + "message": "", + "details": [ + { + "binding": "0.0.0.0:6969", + "info": "checking the udp tracker health check at: 0.0.0.0:6969", + "result": { + "Ok": "Connected" + } + }, + { + "binding": "0.0.0.0:1212", + "info": "checking api health check at: http://0.0.0.0:1212/api/health_check", + "result": { + "Ok": "200 OK" + } + }, + { + "binding": "0.0.0.0:7070", + "info": "checking http tracker health check at: http://0.0.0.0:7070/health_check", + "result": { + "Ok": "200 OK" + } + } + ] +} +``` + +## Documentation + +[Crate documentation](https://docs.rs/torrust-axum-health-check-api-server). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/src/servers/health_check_api/handlers.rs b/packages/axum-health-check-api-server/src/handlers.rs similarity index 100% rename from src/servers/health_check_api/handlers.rs rename to packages/axum-health-check-api-server/src/handlers.rs diff --git a/src/servers/health_check_api/mod.rs b/packages/axum-health-check-api-server/src/lib.rs similarity index 100% rename from src/servers/health_check_api/mod.rs rename to packages/axum-health-check-api-server/src/lib.rs diff --git a/src/servers/health_check_api/resources.rs b/packages/axum-health-check-api-server/src/resources.rs similarity index 100% rename from src/servers/health_check_api/resources.rs rename to packages/axum-health-check-api-server/src/resources.rs diff --git a/src/servers/health_check_api/responses.rs b/packages/axum-health-check-api-server/src/responses.rs similarity index 100% rename from src/servers/health_check_api/responses.rs rename to packages/axum-health-check-api-server/src/responses.rs diff --git a/src/servers/health_check_api/server.rs b/packages/axum-health-check-api-server/src/server.rs similarity index 97% rename from src/servers/health_check_api/server.rs rename to packages/axum-health-check-api-server/src/server.rs index 6f468b98e..733fec3a0 100644 --- a/src/servers/health_check_api/server.rs +++ b/packages/axum-health-check-api-server/src/server.rs @@ -26,8 +26,8 @@ use tower_http::trace::{DefaultMakeSpan, TraceLayer}; use tower_http::LatencyUnit; use tracing::{instrument, Level, Span}; -use crate::servers::health_check_api::handlers::health_check_handler; -use crate::servers::health_check_api::HEALTH_CHECK_API_LOG_TARGET; +use crate::handlers::health_check_handler; +use crate::HEALTH_CHECK_API_LOG_TARGET; /// Starts Health Check API server. /// diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index d64ca0073..5d342a7f0 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -16,14 +16,13 @@ use tokio::sync::oneshot; use tokio::task::JoinHandle; +use torrust_axum_health_check_api_server::{server, HEALTH_CHECK_API_LOG_TARGET}; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::ServiceRegistry; use torrust_server_lib::signals::{Halted, Started}; use torrust_tracker_configuration::HealthCheckApi; use tracing::instrument; -use crate::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; - /// This function starts a new Health Check API server with the provided /// configuration. /// diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index fdbe5d9c0..c406fa7a5 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -2,11 +2,10 @@ use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use regex::Regex; use serde::{Deserialize, Serialize}; +use torrust_axum_health_check_api_server::HEALTH_CHECK_API_LOG_TARGET; use torrust_axum_http_tracker_server::HTTP_TRACKER_LOG_TARGET; use torrust_server_lib::logging::STARTED_ON; -use crate::servers::health_check_api::HEALTH_CHECK_API_LOG_TARGET; - const INFO_THRESHOLD: &str = "INFO"; #[derive(Serialize, Deserialize, Debug, Default)] diff --git a/src/servers/mod.rs b/src/servers/mod.rs index 037179ba8..8dea8a10d 100644 --- a/src/servers/mod.rs +++ b/src/servers/mod.rs @@ -1,4 +1,3 @@ //! Servers. Services that can be started and stopped. pub mod apis; -pub mod health_check_api; pub mod udp; diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index bf38e05a7..bde3e9f5d 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -1,5 +1,5 @@ +use torrust_axum_health_check_api_server::resources::{Report, Status}; use torrust_server_lib::registar::Registar; -use torrust_tracker_lib::servers::health_check_api::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; @@ -32,7 +32,7 @@ async fn health_check_endpoint_should_return_status_ok_when_there_is_no_services mod api { use std::sync::Arc; - use torrust_tracker_lib::servers::health_check_api::resources::{Report, Status}; + use torrust_axum_health_check_api_server::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; @@ -142,7 +142,7 @@ mod api { mod http { use std::sync::Arc; - use torrust_tracker_lib::servers::health_check_api::resources::{Report, Status}; + use torrust_axum_health_check_api_server::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; @@ -251,7 +251,7 @@ mod http { mod udp { use std::sync::Arc; - use torrust_tracker_lib::servers::health_check_api::resources::{Report, Status}; + use torrust_axum_health_check_api_server::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; diff --git a/tests/servers/health_check_api/environment.rs b/tests/servers/health_check_api/environment.rs index b83240767..f8c1209cd 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/tests/servers/health_check_api/environment.rs @@ -3,10 +3,10 @@ use std::sync::Arc; use tokio::sync::oneshot::{self, Sender}; use tokio::task::JoinHandle; +use torrust_axum_health_check_api_server::{server, HEALTH_CHECK_API_LOG_TARGET}; use torrust_server_lib::registar::Registar; use torrust_server_lib::signals::{self, Halted, Started}; use torrust_tracker_configuration::HealthCheckApi; -use torrust_tracker_lib::servers::health_check_api::{server, HEALTH_CHECK_API_LOG_TARGET}; #[derive(Debug)] pub enum Error { From 39dfbdc631bd250d98fe3e51eab9146efb73fa78 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Feb 2025 12:59:27 +0000 Subject: [PATCH 0786/1297] chore(deps): udpate dependencies ```output cargo update Updating crates.io index Locking 2 packages to latest compatible versions Updating h2 v0.4.7 -> v0.4.8 Updating unicode-ident v1.0.16 -> v1.0.17 ``` --- Cargo.lock | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1c30e5128..d0fb7a7d9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1784,9 +1784,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.7" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccae279728d634d083c00f6099cb58f01cc99c145b84b8be2f6c74618d79922e" +checksum = "5017294ff4bb30944501348f6f8e42e6ad28f42c8bbef7a74029aff064a4e3c2" dependencies = [ "atomic-waker", "bytes", @@ -4378,7 +4378,7 @@ dependencies = [ "torrust-tracker-configuration", "torrust-tracker-primitives", "torrust-tracker-test-helpers", - "tower 0.4.13", + "tower 0.5.2", "tower-http", "tracing", ] @@ -4399,7 +4399,7 @@ dependencies = [ "torrust-server-lib", "torrust-tracker-configuration", "torrust-tracker-located-error", - "tower 0.4.13", + "tower 0.5.2", "tracing", ] @@ -4623,7 +4623,6 @@ dependencies = [ "futures-util", "pin-project", "pin-project-lite", - "tokio", "tower-layer", "tower-service", "tracing", @@ -4783,9 +4782,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.16" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a210d160f08b701c8721ba1c726c11662f877ea6b7094007e1ca9a1041945034" +checksum = "00e2473a93778eb0bad35909dff6a10d28e63f792f16ed15e404fca9d5eeedbe" [[package]] name = "unicode-xid" From d4ec44e2cc62a27b0858911e3a392aa18ab56e42 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 20 Feb 2025 07:58:21 +0000 Subject: [PATCH 0787/1297] chore(deps): udpate dependencies ``` Updating crates.io index Locking 21 packages to latest compatible versions Updating anyhow v1.0.95 -> v1.0.96 Adding bitflags v1.3.2 Updating bollard v0.16.1 -> v0.18.1 Updating bollard-stubs v1.44.0-rc.2 -> v1.47.1-rc.27.3.1 Adding core-foundation v0.10.0 Removing dirs v5.0.1 Removing dirs-sys v0.4.1 Adding etcetera v0.8.0 Adding filetime v0.2.25 Removing hyper-rustls v0.26.0 Adding hyperlocal v0.9.1 Removing hyperlocal-next v0.9.0 Updating native-tls v0.2.13 -> v0.2.14 Removing option-ext v0.2.0 Adding redox_syscall v0.3.5 Removing redox_users v0.4.6 Removing rustls v0.22.4 Updating rustls-native-certs v0.7.3 -> v0.8.1 Adding security-framework v3.2.0 Updating serde v1.0.217 -> v1.0.218 Updating serde_derive v1.0.217 -> v1.0.218 Updating serde_json v1.0.138 -> v1.0.139 Updating testcontainers v0.17.0 -> v0.23.3 Removing tokio-rustls v0.25.0 Adding tokio-tar v0.3.1 Updating winnow v0.7.2 -> v0.7.3 Adding xattr v1.4.0 Updating zerocopy v0.8.18 -> v0.8.20 Updating zerocopy-derive v0.8.18 -> v0.8.20 ``` --- Cargo.lock | 285 ++++++++++++++++--------------- packages/tracker-core/Cargo.toml | 18 +- 2 files changed, 153 insertions(+), 150 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d0fb7a7d9..71ac6b225 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -131,9 +131,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.95" +version = "1.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04" +checksum = "6b964d184e89d9b6b67dd2715bc8e74cf3107fb2b529990c90cf517326150bf4" [[package]] name = "aquatic_peer_id" @@ -462,11 +462,11 @@ dependencies = [ "hyper", "hyper-util", "pin-project-lite", - "rustls 0.23.23", + "rustls", "rustls-pemfile", "rustls-pki-types", "tokio", - "tokio-rustls 0.26.1", + "tokio-rustls", "tower 0.4.13", "tower-service", ] @@ -523,7 +523,7 @@ version = "0.71.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3" dependencies = [ - "bitflags", + "bitflags 2.8.0", "cexpr", "clang-sys", "itertools 0.13.0", @@ -541,6 +541,12 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02b4ff8b16e6076c3e14220b39fbc1fabb6737522281a388998046859400895f" +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.8.0" @@ -739,9 +745,9 @@ dependencies = [ [[package]] name = "bollard" -version = "0.16.1" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aed08d3adb6ebe0eff737115056652670ae290f177759aac19c30456135f94c" +checksum = "97ccca1260af6a459d75994ad5acc1651bcabcbdbc41467cc9786519ab854c30" dependencies = [ "base64 0.22.1", "bollard-stubs", @@ -754,12 +760,12 @@ dependencies = [ "http-body-util", "hyper", "hyper-named-pipe", - "hyper-rustls 0.26.0", + "hyper-rustls", "hyper-util", - "hyperlocal-next", + "hyperlocal", "log", "pin-project-lite", - "rustls 0.22.4", + "rustls", "rustls-native-certs", "rustls-pemfile", "rustls-pki-types", @@ -768,7 +774,7 @@ dependencies = [ "serde_json", "serde_repr", "serde_urlencoded", - "thiserror 1.0.69", + "thiserror 2.0.11", "tokio", "tokio-util", "tower-service", @@ -778,9 +784,9 @@ dependencies = [ [[package]] name = "bollard-stubs" -version = "1.44.0-rc.2" +version = "1.47.1-rc.27.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709d9aa1c37abb89d40f19f5d0ad6f0d88cb1581264e571c9350fc5bb89cf1c5" +checksum = "3f179cfbddb6e77a5472703d4b30436bff32929c0aa8a9008ecf23d1d3cdd0da" dependencies = [ "serde", "serde_repr", @@ -1096,6 +1102,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b55271e5c8c478ad3f38ad24ef34923091e0548492a266d19b3c0b4d82574c63" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -1341,27 +1357,6 @@ dependencies = [ "crypto-common", ] -[[package]] -name = "dirs" -version = "5.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.48.0", -] - [[package]] name = "displaydoc" version = "0.2.5" @@ -1431,6 +1426,17 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys 0.48.0", +] + [[package]] name = "event-listener" version = "2.5.3" @@ -1492,6 +1498,18 @@ dependencies = [ "version_check", ] +[[package]] +name = "filetime" +version = "0.2.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35c0522e981e68cbfa8c3f978441a5f34b30b96e146b33cd3359176b50fe8586" +dependencies = [ + "cfg-if", + "libc", + "libredox", + "windows-sys 0.59.0", +] + [[package]] name = "flate2" version = "1.0.35" @@ -1961,25 +1979,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "hyper-rustls" -version = "0.26.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0bea761b46ae2b24eb4aef630d8d1c398157b6fc29e6350ecf090a0b70c952c" -dependencies = [ - "futures-util", - "http", - "hyper", - "hyper-util", - "log", - "rustls 0.22.4", - "rustls-native-certs", - "rustls-pki-types", - "tokio", - "tokio-rustls 0.25.0", - "tower-service", -] - [[package]] name = "hyper-rustls" version = "0.27.5" @@ -1990,10 +1989,10 @@ dependencies = [ "http", "hyper", "hyper-util", - "rustls 0.23.23", + "rustls", "rustls-pki-types", "tokio", - "tokio-rustls 0.26.1", + "tokio-rustls", "tower-service", ] @@ -2033,10 +2032,10 @@ dependencies = [ ] [[package]] -name = "hyperlocal-next" -version = "0.9.0" +name = "hyperlocal" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acf569d43fa9848e510358c07b80f4adf34084ddc28c6a4a651ee8474c070dcc" +checksum = "986c5ce3b994526b3cd75578e62554abd09f0899d6206de48b3e96ab34ccc8c7" dependencies = [ "hex", "http-body-util", @@ -2370,8 +2369,9 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ - "bitflags", + "bitflags 2.8.0", "libc", + "redox_syscall 0.5.8", ] [[package]] @@ -2579,7 +2579,7 @@ dependencies = [ "base64 0.21.7", "bigdecimal", "bindgen", - "bitflags", + "bitflags 2.8.0", "bitvec", "btoi", "byteorder", @@ -2620,9 +2620,9 @@ dependencies = [ [[package]] name = "native-tls" -version = "0.2.13" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dab59f8e050d5df8e4dd87d9206fb6f65a483e20ac9fda365ade4fab353196c" +checksum = "87de3442987e9dbec73158d5c715e7ad9072fda936bb03d19d7fa10e00520f0e" dependencies = [ "libc", "log", @@ -2630,7 +2630,7 @@ dependencies = [ "openssl-probe", "openssl-sys", "schannel", - "security-framework", + "security-framework 2.11.1", "security-framework-sys", "tempfile", ] @@ -2747,7 +2747,7 @@ version = "0.10.71" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e14130c6a98cd258fdcb0fb6d744152343ff729cbfcb28c656a9d12b999fbcd" dependencies = [ - "bitflags", + "bitflags 2.8.0", "cfg-if", "foreign-types", "libc", @@ -2785,12 +2785,6 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - [[package]] name = "overload" version = "0.1.1" @@ -2821,7 +2815,7 @@ checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", - "redox_syscall", + "redox_syscall 0.5.8", "smallvec", "windows-targets 0.52.6", ] @@ -3217,7 +3211,7 @@ checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.1", - "zerocopy 0.8.18", + "zerocopy 0.8.20", ] [[package]] @@ -3256,7 +3250,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a88e0da7a2c97baa202165137c158d0a2e824ac465d13d81046727b34cb247d3" dependencies = [ "getrandom 0.3.1", - "zerocopy 0.8.18", + "zerocopy 0.8.20", ] [[package]] @@ -3281,22 +3275,20 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.8" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" +checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" dependencies = [ - "bitflags", + "bitflags 1.3.2", ] [[package]] -name = "redox_users" -version = "0.4.6" +name = "redox_syscall" +version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" dependencies = [ - "getrandom 0.2.15", - "libredox", - "thiserror 1.0.69", + "bitflags 2.8.0", ] [[package]] @@ -3359,7 +3351,7 @@ dependencies = [ "http-body", "http-body-util", "hyper", - "hyper-rustls 0.27.5", + "hyper-rustls", "hyper-tls", "hyper-util", "ipnet", @@ -3476,7 +3468,7 @@ version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c6d5e5acb6f6129fe3f7ba0a7fc77bca1942cb568535e18e7bc40262baf3110" dependencies = [ - "bitflags", + "bitflags 2.8.0", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -3527,27 +3519,13 @@ version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags", + "bitflags 2.8.0", "errno", "libc", "linux-raw-sys", "windows-sys 0.59.0", ] -[[package]] -name = "rustls" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf4ef73721ac7bcd79b2b315da7779d8fc09718c6b3d2d1b2d94850eb8c18432" -dependencies = [ - "log", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - [[package]] name = "rustls" version = "0.23.23" @@ -3555,6 +3533,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47796c98c480fce5406ef69d1c76378375492c3b0a0de587be0c1d9feb12f395" dependencies = [ "once_cell", + "ring", "rustls-pki-types", "rustls-webpki", "subtle", @@ -3563,15 +3542,14 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.7.3" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5bfb394eeed242e909609f56089eecfe5fda225042e8b171791b9c95f5931e5" +checksum = "7fcff2dd52b58a8d98a70243663a0d234c4e2b79235637849d15913394a247d3" dependencies = [ "openssl-probe", - "rustls-pemfile", "rustls-pki-types", "schannel", - "security-framework", + "security-framework 3.2.0", ] [[package]] @@ -3663,8 +3641,21 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" dependencies = [ - "bitflags", - "core-foundation", + "bitflags 2.8.0", + "core-foundation 0.9.4", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271720403f46ca04f7ba6f55d438f8bd878d6b8ca0a1046e8228c4145bcbb316" +dependencies = [ + "bitflags 2.8.0", + "core-foundation 0.10.0", "core-foundation-sys", "libc", "security-framework-sys", @@ -3688,9 +3679,9 @@ checksum = "f79dfe2d285b0488816f30e700a7438c5a73d816b5b7d3ac72fbc48b0d185e03" [[package]] name = "serde" -version = "1.0.217" +version = "1.0.218" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70" +checksum = "e8dfc9d19bdbf6d17e22319da49161d5d0108e4188e8b680aef6299eed22df60" dependencies = [ "serde_derive", ] @@ -3716,9 +3707,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.217" +version = "1.0.218" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" +checksum = "f09503e191f4e797cb8aac08e9a4a4695c5edf6a2e70e376d961ddd5c969f82b" dependencies = [ "proc-macro2", "quote", @@ -3740,9 +3731,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.138" +version = "1.0.139" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d434192e7da787e94a6ea7e9670b26a036d0ca41e0b7efb2676dd32bae872949" +checksum = "44f86c3acccc9c65b153fe1b85a3be07fe5515274ec9f0653b4a0875731c72a6" dependencies = [ "indexmap 2.7.1", "itoa", @@ -4011,8 +4002,8 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" dependencies = [ - "bitflags", - "core-foundation", + "bitflags 2.8.0", + "core-foundation 0.9.4", "system-configuration-sys", ] @@ -4080,26 +4071,29 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "testcontainers" -version = "0.17.0" +version = "0.23.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "025e0ac563d543e0354d984540e749859a83dbe5c0afb8d458dc48d91cef2d6a" +checksum = "59a4f01f39bb10fc2a5ab23eb0d888b1e2bb168c157f61a1b98e6c501c639c74" dependencies = [ "async-trait", "bollard", "bollard-stubs", "bytes", - "dirs", "docker_credential", + "either", + "etcetera", "futures", "log", "memchr", "parse-display", + "pin-project-lite", "serde", "serde_json", "serde_with", - "thiserror 1.0.69", + "thiserror 2.0.11", "tokio", "tokio-stream", + "tokio-tar", "tokio-util", "url", ] @@ -4258,24 +4252,13 @@ dependencies = [ "tokio", ] -[[package]] -name = "tokio-rustls" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" -dependencies = [ - "rustls 0.22.4", - "rustls-pki-types", - "tokio", -] - [[package]] name = "tokio-rustls" version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f6d0975eaace0cf0fcadee4e4aaa5da15b5c079146f2cffb67c113be122bf37" dependencies = [ - "rustls 0.23.23", + "rustls", "tokio", ] @@ -4290,6 +4273,21 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tar" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d5714c010ca3e5c27114c1cdeb9d14641ace49874aa5626d7149e47aedace75" +dependencies = [ + "filetime", + "futures-core", + "libc", + "redox_syscall 0.3.5", + "tokio", + "tokio-stream", + "xattr", +] + [[package]] name = "tokio-util" version = "0.7.13" @@ -4651,7 +4649,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "403fa3b783d4b626a8ad51d766ab03cb6d2dbfc46b1c5d4448395e6628dc9697" dependencies = [ "async-compression", - "bitflags", + "bitflags 2.8.0", "bytes", "futures-core", "http", @@ -5197,9 +5195,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59690dea168f2198d1a3b0cac23b8063efcd11012f10ae4698f284808c8ef603" +checksum = "0e7f4ea97f6f78012141bcdb6a216b2609f0979ada50b20ca5b52dde2eac2bb1" dependencies = [ "memchr", ] @@ -5210,7 +5208,7 @@ version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" dependencies = [ - "bitflags", + "bitflags 2.8.0", ] [[package]] @@ -5234,6 +5232,17 @@ dependencies = [ "tap", ] +[[package]] +name = "xattr" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e105d177a3871454f754b33bb0ee637ecaaac997446375fd3e5d43a2ed00c909" +dependencies = [ + "libc", + "linux-raw-sys", + "rustix", +] + [[package]] name = "yansi" version = "1.0.1" @@ -5276,11 +5285,11 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.18" +version = "0.8.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79386d31a42a4996e3336b0919ddb90f81112af416270cff95b5f5af22b839c2" +checksum = "dde3bb8c68a8f3f1ed4ac9221aad6b10cece3e60a8e2ea54a6a2dec806d0084c" dependencies = [ - "zerocopy-derive 0.8.18", + "zerocopy-derive 0.8.20", ] [[package]] @@ -5296,9 +5305,9 @@ dependencies = [ [[package]] name = "zerocopy-derive" -version = "0.8.18" +version = "0.8.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76331675d372f91bf8d17e13afbd5fe639200b73d01f0fc748bb059f9cca2db7" +checksum = "eea57037071898bf96a6da35fd626f4f27e9cee3ead2a6c703cf09d472b2e700" dependencies = [ "proc-macro2", "quote", diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index 46807a534..5a830051e 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -1,14 +1,14 @@ [package] -description = "A library with the core functionality needed to implement a BitTorrent tracker." -keywords = ["api", "bittorrent", "core", "library", "tracker"] -name = "bittorrent-tracker-core" -readme = "README.md" authors.workspace = true +description = "A library with the core functionality needed to implement a BitTorrent tracker." documentation.workspace = true edition.workspace = true homepage.workspace = true +keywords = ["api", "bittorrent", "core", "library", "tracker"] license.workspace = true +name = "bittorrent-tracker-core" publish.workspace = true +readme = "README.md" repository.workspace = true rust-version.workspace = true version.workspace = true @@ -26,13 +26,7 @@ rand = "0" serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } thiserror = "2" -tokio = { version = "1", features = [ - "macros", - "net", - "rt-multi-thread", - "signal", - "sync", -] } +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } @@ -43,7 +37,7 @@ tracing = "0" [dev-dependencies] local-ip-address = "0" mockall = "0" +testcontainers = "0" torrust-tracker-api-client = { version = "3.0.0-develop", path = "../tracker-api-client" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } -testcontainers = "0.17.0" url = "2.5.4" From 66c70d98e9613d9f0e4d7b5c7d29c3ba824cfc54 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 20 Feb 2025 08:17:44 +0000 Subject: [PATCH 0788/1297] chore(deps): bump testcontainers from 0.17.0 to 0.23.3 --- packages/tracker-core/src/databases/driver/mysql.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index 624e34c9b..6f7deb2b9 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -268,6 +268,7 @@ impl Database for Mysql { mod tests { use std::sync::Arc; + use testcontainers::core::IntoContainerPort; /* We run a MySQL container and run all the tests against the same container and database. @@ -285,7 +286,7 @@ mod tests { If we increase the number of methods or the number or drivers. */ use testcontainers::runners::AsyncRunner; - use testcontainers::{ContainerAsync, GenericImage}; + use testcontainers::{ContainerAsync, GenericImage, ImageExt}; use torrust_tracker_configuration::Core; use super::Mysql; @@ -298,12 +299,12 @@ mod tests { impl StoppedMysqlContainer { async fn run(self, config: &MysqlConfiguration) -> Result> { let container = GenericImage::new("mysql", "8.0") + .with_exposed_port(config.internal_port.tcp()) + // todo: this does not work + //.with_wait_for(WaitFor::message_on_stdout("ready for connections")) .with_env_var("MYSQL_ROOT_PASSWORD", config.db_root_password.clone()) .with_env_var("MYSQL_DATABASE", config.database.clone()) .with_env_var("MYSQL_ROOT_HOST", "%") - .with_exposed_port(config.internal_port) - // todo: this doesn't work - //.with_wait_for(WaitFor::message_on_stdout("ready for connections")) .start() .await?; From 6e74f5f255d82d85c0a4f525be4626f3dc73c2f9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 20 Feb 2025 08:20:28 +0000 Subject: [PATCH 0789/1297] chore(deps): bump derive_more from 1.0.0 to 2.0.1 --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- packages/axum-http-tracker-server/Cargo.toml | 2 +- packages/configuration/Cargo.toml | 2 +- packages/http-protocol/Cargo.toml | 2 +- packages/primitives/Cargo.toml | 2 +- packages/server-lib/Cargo.toml | 2 +- packages/tracker-client/Cargo.toml | 2 +- packages/tracker-core/Cargo.toml | 2 +- 9 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 71ac6b225..5779f2ff9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1317,18 +1317,18 @@ dependencies = [ [[package]] name = "derive_more" -version = "1.0.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a9b99b9cbbe49445b21764dc0625032a89b145a2642e67603e1c936f5458d05" +checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678" dependencies = [ "derive_more-impl", ] [[package]] name = "derive_more-impl" -version = "1.0.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" +checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 20d7c00dd..dadd39ccf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,7 +47,7 @@ chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } crossbeam-skiplist = "0" dashmap = "6" -derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } +derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } figment = "0" futures = "0" futures-util = "0" diff --git a/packages/axum-http-tracker-server/Cargo.toml b/packages/axum-http-tracker-server/Cargo.toml index b47ea23ce..ae038cb7b 100644 --- a/packages/axum-http-tracker-server/Cargo.toml +++ b/packages/axum-http-tracker-server/Cargo.toml @@ -22,7 +22,7 @@ bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "../http-trac bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "../http-protocol" } bittorrent-primitives = "0.1.0" bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } -derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } +derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } futures = "0" hyper = "1" reqwest = { version = "0", features = ["json"] } diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 05789b882..da04f29cd 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -16,7 +16,7 @@ version.workspace = true [dependencies] camino = { version = "1", features = ["serde", "serde1"] } -derive_more = { version = "1", features = ["constructor", "display"] } +derive_more = { version = "2", features = ["constructor", "display"] } figment = { version = "0", features = ["env", "test", "toml"] } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } diff --git a/packages/http-protocol/Cargo.toml b/packages/http-protocol/Cargo.toml index 7445b37a1..7803fe78e 100644 --- a/packages/http-protocol/Cargo.toml +++ b/packages/http-protocol/Cargo.toml @@ -18,7 +18,7 @@ version.workspace = true aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } -derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } +derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } multimap = "0" percent-encoding = "2" serde = { version = "1", features = ["derive"] } diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index b83886385..1396d8bc8 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -18,7 +18,7 @@ version.workspace = true aquatic_udp_protocol = "0" binascii = "0" bittorrent-primitives = "0.1.0" -derive_more = { version = "1", features = ["constructor"] } +derive_more = { version = "2", features = ["constructor"] } serde = { version = "1", features = ["derive"] } tdyne-peer-id = "1" tdyne-peer-id-registry = "0" diff --git a/packages/server-lib/Cargo.toml b/packages/server-lib/Cargo.toml index b0e196d64..b8514fbf4 100644 --- a/packages/server-lib/Cargo.toml +++ b/packages/server-lib/Cargo.toml @@ -14,7 +14,7 @@ rust-version.workspace = true version.workspace = true [dependencies] -derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } +derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" diff --git a/packages/tracker-client/Cargo.toml b/packages/tracker-client/Cargo.toml index 67a4c767a..ef5cccaa2 100644 --- a/packages/tracker-client/Cargo.toml +++ b/packages/tracker-client/Cargo.toml @@ -17,7 +17,7 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" -derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } +derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } hyper = "1" percent-encoding = "2" reqwest = { version = "0", features = ["json"] } diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index 5a830051e..731ee900d 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -17,7 +17,7 @@ version.workspace = true aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" chrono = { version = "0", default-features = false, features = ["clock"] } -derive_more = { version = "1", features = ["as_ref", "constructor", "from"] } +derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } mockall = "0" r2d2 = "0" r2d2_mysql = "25" From bc95fc4c841674d837064099fedf040e059a20b8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 20 Feb 2025 16:08:57 +0000 Subject: [PATCH 0790/1297] docs: remove code-review comment We decided not to change it. - The returned value is simpler. - We force the initial peer to change so there is no confusion about what was the final announced peer. --- packages/tracker-core/src/announce_handler.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index cd2073857..cb48a321a 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -162,10 +162,6 @@ impl AnnounceHandler { remote_client_ip: &IpAddr, peers_wanted: &PeersWanted, ) -> Result { - // code-review: maybe instead of mutating the peer we could just return - // a tuple with the new peer and the announce data: (Peer, AnnounceData). - // It could even be a different struct: `StoredPeer` or `PublicPeer`. - self.whitelist_authorization.authorize(info_hash).await?; tracing::debug!("Before: {peer:?}"); From d48272f53fad95240660657c31b2ad47b5c38ea4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 20 Feb 2025 17:43:55 +0000 Subject: [PATCH 0791/1297] chore: [#1303] remove explicit declaration of workspace members from Cargo.toml For packages included in the main Cargo.toml file. The application works anyway because _all [path dependencies](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#specifying-path-dependencies) residing in the workspace directory automatically become members_. See https://doc.rust-lang.org/cargo/reference/workspaces.html#the-members-and-exclude-fields. We have to keep `console/tracker-client` becuase it's not included directly in the main Cargo.toml as a dependency. --- Cargo.toml | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index dadd39ccf..d3b194ed9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -108,18 +108,7 @@ torrust-tracker-api-client = { version = "3.0.0-develop", path = "packages/track torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "packages/test-helpers" } [workspace] -members = [ - "console/tracker-client", - "contrib/bencode", - "packages/configuration", - "packages/located-error", - "packages/primitives", - "packages/test-helpers", - "packages/torrent-repository", - "packages/tracker-api-client", - "packages/tracker-client", - "packages/tracker-core", -] +members = ["console/tracker-client"] [profile.dev] debug = 1 From 265da2d565bd34c90e9fc00302e3291c351e8e83 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 09:50:37 +0000 Subject: [PATCH 0792/1297] refactor: [#1298] inject only logging config in logging setup --- packages/configuration/src/lib.rs | 1 + src/bootstrap/app.rs | 2 +- src/bootstrap/logging.rs | 6 +++--- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 7e384297d..8a4d3f81e 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -37,6 +37,7 @@ pub const ENV_VAR_CONFIG_TOML_PATH: &str = "TORRUST_TRACKER_CONFIG_TOML_PATH"; pub type Configuration = v2_0_0::Configuration; pub type Core = v2_0_0::core::Core; +pub type Logging = v2_0_0::logging::Logging; pub type HealthCheckApi = v2_0_0::health_check_api::HealthCheckApi; pub type HttpApi = v2_0_0::tracker_api::HttpApi; pub type HttpTracker = v2_0_0::http_tracker::HttpTracker; diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 2f4ff0e94..420f1a981 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -182,5 +182,5 @@ pub fn initialize_static() { /// See [the logging setup](crate::bootstrap::logging::setup) for more info about logging. #[instrument(skip(config))] pub fn initialize_logging(config: &Configuration) { - bootstrap::logging::setup(config); + bootstrap::logging::setup(&config.logging); } diff --git a/src/bootstrap/logging.rs b/src/bootstrap/logging.rs index d7a100aed..ab66822a1 100644 --- a/src/bootstrap/logging.rs +++ b/src/bootstrap/logging.rs @@ -13,15 +13,15 @@ //! Refer to the [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) to know how to change log settings. use std::sync::Once; -use torrust_tracker_configuration::{Configuration, Threshold}; +use torrust_tracker_configuration::{Logging, Threshold}; use tracing::level_filters::LevelFilter; static INIT: Once = Once::new(); /// It redirects the log info to the standard output with the log threshold /// defined in the configuration. -pub fn setup(cfg: &Configuration) { - let tracing_level = map_to_tracing_level_filter(&cfg.logging.threshold); +pub fn setup(cfg: &Logging) { + let tracing_level = map_to_tracing_level_filter(&cfg.threshold); if tracing_level == LevelFilter::OFF { return; From 1bd5f0a1c76cc4cf4ef5a980508ac3ae4c65cb58 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 09:58:50 +0000 Subject: [PATCH 0793/1297] refactor: [#1298] move loggin setup to configration package It will be used in other workspace packages. --- Cargo.lock | 2 ++ packages/configuration/Cargo.toml | 2 ++ packages/configuration/src/lib.rs | 1 + .../configuration/src}/logging.rs | 3 ++- src/bootstrap/app.rs | 13 ++++++------- src/bootstrap/mod.rs | 1 - tests/common/logging.rs | 2 +- 7 files changed, 14 insertions(+), 10 deletions(-) rename {src/bootstrap => packages/configuration/src}/logging.rs (97%) diff --git a/Cargo.lock b/Cargo.lock index 5779f2ff9..981ffeba3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4547,6 +4547,8 @@ dependencies = [ "thiserror 2.0.11", "toml", "torrust-tracker-located-error", + "tracing", + "tracing-subscriber", "url", "uuid", ] diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index da04f29cd..e213f7c0c 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -24,6 +24,8 @@ serde_with = "3" thiserror = "2" toml = "0" torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } +tracing = "0" +tracing-subscriber = { version = "0", features = ["json"] } url = "2" [dev-dependencies] diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index 8a4d3f81e..d12020b8c 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -4,6 +4,7 @@ //! Torrust Tracker, which is a `BitTorrent` tracker server. //! //! The current version for configuration is [`v2_0_0`]. +pub mod logging; pub mod v2_0_0; pub mod validator; diff --git a/src/bootstrap/logging.rs b/packages/configuration/src/logging.rs similarity index 97% rename from src/bootstrap/logging.rs rename to packages/configuration/src/logging.rs index ab66822a1..b8db27b8c 100644 --- a/src/bootstrap/logging.rs +++ b/packages/configuration/src/logging.rs @@ -13,9 +13,10 @@ //! Refer to the [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) to know how to change log settings. use std::sync::Once; -use torrust_tracker_configuration::{Logging, Threshold}; use tracing::level_filters::LevelFilter; +use crate::{Logging, Threshold}; + static INIT: Once = Once::new(); /// It redirects the log info to the standard output with the log threshold diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 420f1a981..977447752 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -33,11 +33,10 @@ use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use tokio::sync::RwLock; use torrust_tracker_clock::static_time; use torrust_tracker_configuration::validator::Validator; -use torrust_tracker_configuration::Configuration; +use torrust_tracker_configuration::{logging, Configuration, Logging}; use tracing::instrument; use super::config::initialize_configuration; -use crate::bootstrap; use crate::container::AppContainer; /// It loads the configuration from the environment and builds app container. @@ -82,7 +81,7 @@ pub fn check_seed() { #[instrument(skip())] pub fn initialize_global_services(configuration: &Configuration) { initialize_static(); - initialize_logging(configuration); + initialize_logging(&configuration.logging); } /// It initializes the IoC Container. @@ -179,8 +178,8 @@ pub fn initialize_static() { /// It initializes the log threshold, format and channel. /// -/// See [the logging setup](crate::bootstrap::logging::setup) for more info about logging. -#[instrument(skip(config))] -pub fn initialize_logging(config: &Configuration) { - bootstrap::logging::setup(&config.logging); +/// See [the logging setup](torrust_tracker_configuration::logging::setup) for more info about logging. +#[instrument(skip(logging_config))] +pub fn initialize_logging(logging_config: &Logging) { + logging::setup(logging_config); } diff --git a/src/bootstrap/mod.rs b/src/bootstrap/mod.rs index 22044aafd..2f7909043 100644 --- a/src/bootstrap/mod.rs +++ b/src/bootstrap/mod.rs @@ -8,4 +8,3 @@ pub mod app; pub mod config; pub mod jobs; -pub mod logging; diff --git a/tests/common/logging.rs b/tests/common/logging.rs index f04dcdc7d..564074f3e 100644 --- a/tests/common/logging.rs +++ b/tests/common/logging.rs @@ -3,7 +3,7 @@ use std::collections::VecDeque; use std::io; use std::sync::{Mutex, MutexGuard, Once, OnceLock}; -use torrust_tracker_lib::bootstrap::logging::TraceStyle; +use torrust_tracker_configuration::logging::TraceStyle; use tracing::level_filters::LevelFilter; use tracing_subscriber::fmt::MakeWriter; From 78002d7b357d4d3c2722f5e5c1cf45b32a8db643 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 10:49:14 +0000 Subject: [PATCH 0794/1297] refactor: [#1298] remove dependency on global app container in packages To be able to move more code from the main mod to workspace packages. Packages cannot depend on global stuff. --- .../axum-http-tracker-server/src/container.rs | 45 +++++++ src/app.rs | 6 +- src/bootstrap/app.rs | 77 ++++++++++- src/bootstrap/jobs/http_tracker.rs | 8 +- src/bootstrap/jobs/tracker_apis.rs | 8 +- src/container.rs | 58 ++++---- src/servers/apis/server.rs | 8 +- src/servers/udp/server/mod.rs | 40 ++++-- tests/servers/api/environment.rs | 104 ++++++++++++--- tests/servers/http/environment.rs | 125 ++++++++++++++---- tests/servers/udp/environment.rs | 102 +++++++++++--- 11 files changed, 454 insertions(+), 127 deletions(-) diff --git a/packages/axum-http-tracker-server/src/container.rs b/packages/axum-http-tracker-server/src/container.rs index c20a8f28f..339c25778 100644 --- a/packages/axum-http-tracker-server/src/container.rs +++ b/packages/axum-http-tracker-server/src/container.rs @@ -1,9 +1,15 @@ use std::sync::Arc; use bittorrent_tracker_core::announce_handler::AnnounceHandler; +use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist; +use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; +use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::{Core, HttpTracker}; pub struct HttpTrackerContainer { @@ -15,3 +21,42 @@ pub struct HttpTrackerContainer { pub http_stats_event_sender: Arc>>, pub authentication_service: Arc, } + +#[must_use] +pub fn initialize_http_tracker_container( + core_config: &Arc, + http_tracker_config: &Arc, +) -> Arc { + // HTTP stats + let (http_stats_event_sender, _http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + + let database = initialize_database(core_config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(core_config, &in_memory_key_repository)); + + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let announce_handler = Arc::new(AnnounceHandler::new( + core_config, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + Arc::new(HttpTrackerContainer { + http_tracker_config: http_tracker_config.clone(), + core_config: core_config.clone(), + announce_handler: announce_handler.clone(), + scrape_handler: scrape_handler.clone(), + whitelist_authorization: whitelist_authorization.clone(), + http_stats_event_sender: http_stats_event_sender.clone(), + authentication_service: authentication_service.clone(), + }) +} diff --git a/src/app.rs b/src/app.rs index 2f712cf3a..3d2da4ff5 100644 --- a/src/app.rs +++ b/src/app.rs @@ -29,7 +29,7 @@ use torrust_tracker_configuration::Configuration; use tracing::instrument; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; -use crate::container::{AppContainer, HttpApiContainer, UdpTrackerContainer}; +use crate::container::AppContainer; use crate::servers; /// # Panics @@ -79,7 +79,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> ); } else { let udp_tracker_config = Arc::new(udp_tracker_config.clone()); - let udp_tracker_container = Arc::new(UdpTrackerContainer::from_app_container(&udp_tracker_config, app_container)); + let udp_tracker_container = Arc::new(app_container.udp_tracker_container(&udp_tracker_config)); jobs.push(udp_tracker::start_job(udp_tracker_container, registar.give_form()).await); } @@ -111,7 +111,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> // Start HTTP API if let Some(http_api_config) = &config.http_api { let http_api_config = Arc::new(http_api_config.clone()); - let http_api_container = Arc::new(HttpApiContainer::from_app_container(&http_api_config, app_container)); + let http_api_container = Arc::new(app_container.http_api_container(&http_api_config)); if let Some(job) = tracker_apis::start_job(http_api_container, registar.give_form(), servers::apis::Version::V1).await { jobs.push(job); diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 977447752..6be7d0aa2 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -33,11 +33,11 @@ use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use tokio::sync::RwLock; use torrust_tracker_clock::static_time; use torrust_tracker_configuration::validator::Validator; -use torrust_tracker_configuration::{logging, Configuration, Logging}; +use torrust_tracker_configuration::{logging, Configuration, Core, HttpApi, Logging, UdpTracker}; use tracing::instrument; use super::config::initialize_configuration; -use crate::container::AppContainer; +use crate::container::{AppContainer, HttpApiContainer, UdpTrackerContainer}; /// It loads the configuration from the environment and builds app container. /// @@ -155,6 +155,79 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { } } +#[must_use] +pub fn initialize_http_api_container(core_config: &Arc, http_api_config: &Arc) -> Arc { + // HTTP stats + let (_http_stats_event_sender, http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + let http_stats_repository = Arc::new(http_stats_repository); + + // UDP stats + let (_udp_stats_event_sender, udp_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + let udp_stats_repository = Arc::new(udp_stats_repository); + + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let database = initialize_database(core_config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let keys_handler = Arc::new(KeysHandler::new( + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + Arc::new(HttpApiContainer { + http_api_config: http_api_config.clone(), + core_config: core_config.clone(), + in_memory_torrent_repository: in_memory_torrent_repository.clone(), + keys_handler: keys_handler.clone(), + whitelist_manager: whitelist_manager.clone(), + ban_service: ban_service.clone(), + http_stats_repository: http_stats_repository.clone(), + udp_stats_repository: udp_stats_repository.clone(), + }) +} + +#[must_use] +pub fn initialize_udt_tracker_container( + core_config: &Arc, + udp_tracker_config: &Arc, +) -> Arc { + // UDP stats + let (udp_stats_event_sender, _udp_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let database = initialize_database(core_config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let announce_handler = Arc::new(AnnounceHandler::new( + core_config, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + Arc::new(UdpTrackerContainer { + udp_tracker_config: udp_tracker_config.clone(), + core_config: core_config.clone(), + announce_handler: announce_handler.clone(), + scrape_handler: scrape_handler.clone(), + whitelist_authorization: whitelist_authorization.clone(), + udp_stats_event_sender: udp_stats_event_sender.clone(), + ban_service: ban_service.clone(), + }) +} + /// It initializes the application static values. /// /// These values are accessible throughout the entire application: diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 2052bf50b..471f74b8b 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -77,24 +77,24 @@ async fn start_v1( mod tests { use std::sync::Arc; + use torrust_axum_http_tracker_server::container::initialize_http_tracker_container; use torrust_axum_http_tracker_server::Version; use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; + use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::http_tracker::start_job; #[tokio::test] async fn it_should_start_http_tracker() { let cfg = Arc::new(ephemeral_public()); + let core_config = Arc::new(cfg.core.clone()); let http_tracker = cfg.http_trackers.clone().expect("missing HTTP tracker configuration"); let http_tracker_config = Arc::new(http_tracker[0].clone()); initialize_global_services(&cfg); - let app_container = Arc::new(initialize_app_container(&cfg)); - - let http_tracker_container = Arc::new(app_container.http_tracker_container(&http_tracker_config)); + let http_tracker_container = initialize_http_tracker_container(&core_config, &http_tracker_config); let version = Version::V1; diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index df736f23f..8a36d74dc 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -100,21 +100,19 @@ mod tests { use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; + use crate::bootstrap::app::{initialize_global_services, initialize_http_api_container}; use crate::bootstrap::jobs::tracker_apis::start_job; - use crate::container::HttpApiContainer; use crate::servers::apis::Version; #[tokio::test] async fn it_should_start_http_tracker() { let cfg = Arc::new(ephemeral_public()); + let core_config = Arc::new(cfg.core.clone()); let http_api_config = Arc::new(cfg.http_api.clone().unwrap()); initialize_global_services(&cfg); - let app_container = Arc::new(initialize_app_container(&cfg)); - - let http_api_container = Arc::new(HttpApiContainer::from_app_container(&http_api_config, &app_container)); + let http_api_container = initialize_http_api_container(&core_config, &http_api_config); let version = Version::V1; diff --git a/src/container.rs b/src/container.rs index 57e24334b..881f50d2d 100644 --- a/src/container.rs +++ b/src/container.rs @@ -50,6 +50,33 @@ impl AppContainer { authentication_service: self.authentication_service.clone(), } } + + #[must_use] + pub fn udp_tracker_container(&self, udp_tracker_config: &Arc) -> UdpTrackerContainer { + UdpTrackerContainer { + udp_tracker_config: udp_tracker_config.clone(), + core_config: self.core_config.clone(), + announce_handler: self.announce_handler.clone(), + scrape_handler: self.scrape_handler.clone(), + whitelist_authorization: self.whitelist_authorization.clone(), + udp_stats_event_sender: self.udp_stats_event_sender.clone(), + ban_service: self.ban_service.clone(), + } + } + + #[must_use] + pub fn http_api_container(&self, http_api_config: &Arc) -> HttpApiContainer { + HttpApiContainer { + http_api_config: http_api_config.clone(), + core_config: self.core_config.clone(), + in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), + keys_handler: self.keys_handler.clone(), + whitelist_manager: self.whitelist_manager.clone(), + ban_service: self.ban_service.clone(), + http_stats_repository: self.http_stats_repository.clone(), + udp_stats_repository: self.udp_stats_repository.clone(), + } + } } pub struct UdpTrackerContainer { @@ -62,21 +89,6 @@ pub struct UdpTrackerContainer { pub ban_service: Arc>, } -impl UdpTrackerContainer { - #[must_use] - pub fn from_app_container(udp_tracker_config: &Arc, app_container: &Arc) -> Self { - Self { - udp_tracker_config: udp_tracker_config.clone(), - core_config: app_container.core_config.clone(), - announce_handler: app_container.announce_handler.clone(), - scrape_handler: app_container.scrape_handler.clone(), - whitelist_authorization: app_container.whitelist_authorization.clone(), - udp_stats_event_sender: app_container.udp_stats_event_sender.clone(), - ban_service: app_container.ban_service.clone(), - } - } -} - pub struct HttpApiContainer { pub core_config: Arc, pub http_api_config: Arc, @@ -87,19 +99,3 @@ pub struct HttpApiContainer { pub http_stats_repository: Arc, pub udp_stats_repository: Arc, } - -impl HttpApiContainer { - #[must_use] - pub fn from_app_container(http_api_config: &Arc, app_container: &Arc) -> Self { - Self { - http_api_config: http_api_config.clone(), - core_config: app_container.core_config.clone(), - in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), - keys_handler: app_container.keys_handler.clone(), - whitelist_manager: app_container.whitelist_manager.clone(), - ban_service: app_container.ban_service.clone(), - http_stats_repository: app_container.http_stats_repository.clone(), - udp_stats_repository: app_container.udp_stats_repository.clone(), - } - } -} diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 187969f8d..cf2c2e96b 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -298,19 +298,17 @@ mod tests { use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; - use crate::container::HttpApiContainer; + use crate::bootstrap::app::{initialize_global_services, initialize_http_api_container}; use crate::servers::apis::server::{ApiServer, Launcher}; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_public()); + let core_config = Arc::new(cfg.core.clone()); let http_api_config = Arc::new(cfg.http_api.clone().unwrap()); initialize_global_services(&cfg); - let app_container = Arc::new(initialize_app_container(&cfg)); - let bind_to = http_api_config.bind_address; let tls = make_rust_tls(&http_api_config.tsl_config) @@ -323,7 +321,7 @@ mod tests { let register = &Registar::default(); - let http_api_container = Arc::new(HttpApiContainer::from_app_container(&http_api_config, &app_container)); + let http_api_container = initialize_http_api_container(&core_config, &http_api_config); let started = stopped .start(http_api_container, register.give_form(), access_tokens) diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 85940e853..d40f3a97f 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -62,17 +62,23 @@ mod tests { use super::spawner::Spawner; use super::Server; - use crate::bootstrap::app::{initialize_app_container, initialize_global_services}; - use crate::container::UdpTrackerContainer; + use crate::bootstrap::app::{initialize_global_services, initialize_udt_tracker_container}; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_public()); + let core_config = Arc::new(cfg.core.clone()); + let udp_tracker_config = Arc::new( + cfg.udp_trackers + .clone() + .expect("no UDP services array config provided") + .first() + .expect("no UDP test service config provided") + .clone(), + ); initialize_global_services(&cfg); - let app_container = Arc::new(initialize_app_container(&cfg)); - let udp_trackers = cfg.udp_trackers.clone().expect("missing UDP trackers configuration"); let config = &udp_trackers[0]; let bind_to = config.bind_address; @@ -80,8 +86,7 @@ mod tests { let stopped = Server::new(Spawner::new(bind_to)); - let udp_tracker_config = Arc::new(config.clone()); - let udp_tracker_container = Arc::new(UdpTrackerContainer::from_app_container(&udp_tracker_config, &app_container)); + let udp_tracker_container = initialize_udt_tracker_container(&core_config, &udp_tracker_config); let started = stopped .start(udp_tracker_container, register.give_form(), config.cookie_lifetime) @@ -98,22 +103,31 @@ mod tests { #[tokio::test] async fn it_should_be_able_to_start_and_stop_with_wait() { let cfg = Arc::new(ephemeral_public()); + let core_config = Arc::new(cfg.core.clone()); + let udp_tracker_config = Arc::new( + cfg.udp_trackers + .clone() + .expect("no UDP services array config provided") + .first() + .expect("no UDP test service config provided") + .clone(), + ); initialize_global_services(&cfg); - let app_container = Arc::new(initialize_app_container(&cfg)); - - let config = cfg.udp_trackers.as_ref().unwrap().first().unwrap(); - let bind_to = config.bind_address; + let bind_to = udp_tracker_config.bind_address; let register = &Registar::default(); let stopped = Server::new(Spawner::new(bind_to)); - let udp_tracker_config = Arc::new(config.clone()); - let udp_tracker_container = Arc::new(UdpTrackerContainer::from_app_container(&udp_tracker_config, &app_container)); + let udp_tracker_container = initialize_udt_tracker_container(&core_config, &udp_tracker_config); let started = stopped - .start(udp_tracker_container, register.give_form(), config.cookie_lifetime) + .start( + udp_tracker_container, + register.give_form(), + udp_tracker_config.cookie_lifetime, + ) .await .expect("it should start the server"); diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index b899c9f02..7cf088568 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -2,15 +2,24 @@ use std::net::SocketAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::authentication::handler::KeysHandler; +use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; +use bittorrent_tracker_core::authentication::key::repository::persisted::DatabaseKeyRepository; use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::databases::Database; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager; +use bittorrent_udp_tracker_core::services::banning::BanService; +use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use futures::executor::block_on; +use tokio::sync::RwLock; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; -use torrust_tracker_configuration::Configuration; -use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; +use torrust_tracker_configuration::{Configuration, HttpApi}; +use torrust_tracker_lib::bootstrap::app::initialize_global_services; use torrust_tracker_lib::container::HttpApiContainer; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_primitives::peer; @@ -46,33 +55,20 @@ impl Environment { pub fn new(configuration: &Arc) -> Self { initialize_global_services(configuration); - let app_container = initialize_app_container(configuration); + let env_container = EnvContainer::initialize(configuration); - let http_api_config = Arc::new(configuration.http_api.clone().expect("missing API configuration")); + let bind_to = env_container.http_api_config.bind_address; - let bind_to = http_api_config.bind_address; - - let tls = block_on(make_rust_tls(&http_api_config.tsl_config)).map(|tls| tls.expect("tls config failed")); + let tls = block_on(make_rust_tls(&env_container.http_api_config.tsl_config)).map(|tls| tls.expect("tls config failed")); let server = ApiServer::new(Launcher::new(bind_to, tls)); - let http_api_container = Arc::new(HttpApiContainer { - http_api_config: http_api_config.clone(), - core_config: app_container.core_config.clone(), - in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), - keys_handler: app_container.keys_handler.clone(), - whitelist_manager: app_container.whitelist_manager.clone(), - ban_service: app_container.ban_service.clone(), - http_stats_repository: app_container.http_stats_repository.clone(), - udp_stats_repository: app_container.udp_stats_repository.clone(), - }); - Self { - http_api_container, + http_api_container: env_container.http_api_container, - database: app_container.database.clone(), - authentication_service: app_container.authentication_service.clone(), - in_memory_whitelist: app_container.in_memory_whitelist.clone(), + database: env_container.database.clone(), + authentication_service: env_container.authentication_service.clone(), + in_memory_whitelist: env_container.in_memory_whitelist.clone(), registar: Registar::default(), server, @@ -130,3 +126,67 @@ impl Environment { self.server.state.local_addr } } + +pub struct EnvContainer { + pub http_api_config: Arc, + pub http_api_container: Arc, + pub database: Arc>, + pub authentication_service: Arc, + pub in_memory_whitelist: Arc, +} + +impl EnvContainer { + pub fn initialize(configuration: &Configuration) -> Self { + let core_config = Arc::new(configuration.core.clone()); + let http_api_config = Arc::new( + configuration + .http_api + .clone() + .expect("missing HTTP API configuration") + .clone(), + ); + + // HTTP stats + let (_http_stats_event_sender, http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let http_stats_repository = Arc::new(http_stats_repository); + + // UDP stats + let (_udp_stats_event_sender, udp_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let udp_stats_repository = Arc::new(udp_stats_repository); + + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let database = initialize_database(&configuration.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&configuration.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + let http_api_container = Arc::new(HttpApiContainer { + http_api_config: http_api_config.clone(), + core_config: core_config.clone(), + in_memory_torrent_repository: in_memory_torrent_repository.clone(), + keys_handler: keys_handler.clone(), + whitelist_manager: whitelist_manager.clone(), + ban_service: ban_service.clone(), + http_stats_repository: http_stats_repository.clone(), + udp_stats_repository: udp_stats_repository.clone(), + }); + + Self { + http_api_config, + http_api_container, + database, + authentication_service, + in_memory_whitelist, + } + } +} diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 4afb262d7..a0164eccc 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -1,17 +1,27 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::handler::KeysHandler; +use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; +use bittorrent_tracker_core::authentication::key::repository::persisted::DatabaseKeyRepository; +use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::databases::Database; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; +use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager; use futures::executor::block_on; use torrust_axum_http_tracker_server::container::HttpTrackerContainer; use torrust_axum_http_tracker_server::server::{HttpServer, Launcher, Running, Stopped}; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; -use torrust_tracker_configuration::Configuration; -use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; +use torrust_tracker_configuration::{Configuration, Core, HttpTracker}; +use torrust_tracker_lib::bootstrap::app::initialize_global_services; use torrust_tracker_primitives::peer; pub struct Environment { @@ -39,38 +49,33 @@ impl Environment { pub fn new(configuration: &Arc) -> Self { initialize_global_services(configuration); - let app_container = initialize_app_container(configuration); + let env_container = EnvContainer::initialize(configuration); - let http_tracker = configuration - .http_trackers - .clone() - .expect("missing HTTP tracker configuration"); - let http_tracker_config = Arc::new(http_tracker[0].clone()); - - let bind_to = http_tracker_config.bind_address; + let bind_to = env_container.http_tracker_config.bind_address; - let tls = block_on(make_rust_tls(&http_tracker_config.tsl_config)).map(|tls| tls.expect("tls config failed")); + let tls = + block_on(make_rust_tls(&env_container.http_tracker_config.tsl_config)).map(|tls| tls.expect("tls config failed")); let server = HttpServer::new(Launcher::new(bind_to, tls)); let http_tracker_container = Arc::new(HttpTrackerContainer { - core_config: app_container.core_config.clone(), - http_tracker_config: http_tracker_config.clone(), - announce_handler: app_container.announce_handler.clone(), - scrape_handler: app_container.scrape_handler.clone(), - whitelist_authorization: app_container.whitelist_authorization.clone(), - http_stats_event_sender: app_container.http_stats_event_sender.clone(), - authentication_service: app_container.authentication_service.clone(), + core_config: env_container.core_config.clone(), + http_tracker_config: env_container.http_tracker_config.clone(), + announce_handler: env_container.http_tracker_container.announce_handler.clone(), + scrape_handler: env_container.http_tracker_container.scrape_handler.clone(), + whitelist_authorization: env_container.http_tracker_container.whitelist_authorization.clone(), + http_stats_event_sender: env_container.http_tracker_container.http_stats_event_sender.clone(), + authentication_service: env_container.http_tracker_container.authentication_service.clone(), }); Self { http_tracker_container, - database: app_container.database.clone(), - in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), - keys_handler: app_container.keys_handler.clone(), - http_stats_repository: app_container.http_stats_repository.clone(), - whitelist_manager: app_container.whitelist_manager.clone(), + database: env_container.database.clone(), + in_memory_torrent_repository: env_container.in_memory_torrent_repository.clone(), + keys_handler: env_container.keys_handler.clone(), + http_stats_repository: env_container.http_stats_repository.clone(), + whitelist_manager: env_container.whitelist_manager.clone(), registar: Registar::default(), server, @@ -122,3 +127,77 @@ impl Environment { &self.server.state.binding } } + +pub struct EnvContainer { + pub core_config: Arc, + pub http_tracker_config: Arc, + pub http_tracker_container: Arc, + + pub database: Arc>, + pub in_memory_torrent_repository: Arc, + pub keys_handler: Arc, + pub http_stats_repository: Arc, + pub whitelist_manager: Arc, +} + +impl EnvContainer { + pub fn initialize(configuration: &Configuration) -> Self { + let core_config = Arc::new(configuration.core.clone()); + let http_tracker_config = configuration + .http_trackers + .clone() + .expect("missing HTTP tracker configuration"); + let http_tracker_config = Arc::new(http_tracker_config[0].clone()); + + // HTTP stats + let (http_stats_event_sender, http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + let http_stats_repository = Arc::new(http_stats_repository); + + let database = initialize_database(&configuration.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&configuration.core, &in_memory_whitelist.clone())); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&configuration.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let announce_handler = Arc::new(AnnounceHandler::new( + &configuration.core, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + let http_tracker_container = Arc::new(HttpTrackerContainer { + http_tracker_config: http_tracker_config.clone(), + core_config: core_config.clone(), + announce_handler: announce_handler.clone(), + scrape_handler: scrape_handler.clone(), + whitelist_authorization: whitelist_authorization.clone(), + http_stats_event_sender: http_stats_event_sender.clone(), + authentication_service: authentication_service.clone(), + }); + + Self { + core_config, + http_tracker_config, + http_tracker_container, + + database, + in_memory_torrent_repository, + keys_handler, + http_stats_repository, + whitelist_manager, + } + } +} diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 67e119bb4..241623732 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -2,12 +2,20 @@ use std::net::SocketAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::AnnounceHandler; +use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::databases::Database; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_udp_tracker_core::statistics; +use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; +use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use bittorrent_udp_tracker_core::services::banning::BanService; +use bittorrent_udp_tracker_core::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; +use tokio::sync::RwLock; use torrust_server_lib::registar::Registar; -use torrust_tracker_configuration::{Configuration, DEFAULT_TIMEOUT}; -use torrust_tracker_lib::bootstrap::app::{initialize_app_container, initialize_global_services}; +use torrust_tracker_configuration::{Configuration, Core, UdpTracker, DEFAULT_TIMEOUT}; +use torrust_tracker_lib::bootstrap::app::initialize_global_services; use torrust_tracker_lib::container::UdpTrackerContainer; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; @@ -44,32 +52,28 @@ impl Environment { pub fn new(configuration: &Arc) -> Self { initialize_global_services(configuration); - let app_container = initialize_app_container(configuration); + let env_container = EnvContainer::initialize(configuration); - let udp_tracker_configurations = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); - - let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); - - let bind_to = udp_tracker_config.bind_address; + let bind_to = env_container.udp_tracker_config.bind_address; let server = Server::new(Spawner::new(bind_to)); let udp_tracker_container = Arc::new(UdpTrackerContainer { - udp_tracker_config: udp_tracker_config.clone(), - core_config: app_container.core_config.clone(), - announce_handler: app_container.announce_handler.clone(), - scrape_handler: app_container.scrape_handler.clone(), - whitelist_authorization: app_container.whitelist_authorization.clone(), - udp_stats_event_sender: app_container.udp_stats_event_sender.clone(), - ban_service: app_container.ban_service.clone(), + udp_tracker_config: env_container.udp_tracker_config.clone(), + core_config: env_container.core_config.clone(), + announce_handler: env_container.udp_tracker_container.announce_handler.clone(), + scrape_handler: env_container.udp_tracker_container.scrape_handler.clone(), + whitelist_authorization: env_container.udp_tracker_container.whitelist_authorization.clone(), + udp_stats_event_sender: env_container.udp_tracker_container.udp_stats_event_sender.clone(), + ban_service: env_container.udp_tracker_container.ban_service.clone(), }); Self { udp_tracker_container, - database: app_container.database.clone(), - in_memory_torrent_repository: app_container.in_memory_torrent_repository.clone(), - udp_stats_repository: app_container.udp_stats_repository.clone(), + database: env_container.database.clone(), + in_memory_torrent_repository: env_container.in_memory_torrent_repository.clone(), + udp_stats_repository: env_container.udp_stats_repository.clone(), registar: Registar::default(), server, @@ -127,6 +131,66 @@ impl Environment { } } +pub struct EnvContainer { + pub core_config: Arc, + pub udp_tracker_config: Arc, + pub udp_tracker_container: Arc, + + pub database: Arc>, + pub in_memory_torrent_repository: Arc, + pub udp_stats_repository: Arc, +} + +impl EnvContainer { + pub fn initialize(configuration: &Configuration) -> Self { + let core_config = Arc::new(configuration.core.clone()); + let udp_tracker_configurations = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); + let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); + + // UDP stats + let (udp_stats_event_sender, udp_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let udp_stats_repository = Arc::new(udp_stats_repository); + + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let database = initialize_database(&configuration.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&configuration.core, &in_memory_whitelist.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let announce_handler = Arc::new(AnnounceHandler::new( + &configuration.core, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + let udp_tracker_container = Arc::new(UdpTrackerContainer { + udp_tracker_config: udp_tracker_config.clone(), + core_config: core_config.clone(), + announce_handler: announce_handler.clone(), + scrape_handler: scrape_handler.clone(), + whitelist_authorization: whitelist_authorization.clone(), + udp_stats_event_sender: udp_stats_event_sender.clone(), + ban_service: ban_service.clone(), + }); + + Self { + core_config, + udp_tracker_config, + udp_tracker_container, + + database, + in_memory_torrent_repository, + udp_stats_repository, + } + } +} + #[cfg(test)] mod tests { use std::time::Duration; From 9ba5cdd35daa2019e73189bf3fd3fff6bf64e16c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 11:49:26 +0000 Subject: [PATCH 0795/1297] refactor: [#1298] inine function --- src/bootstrap/app.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 6be7d0aa2..bbc7fd7bc 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -33,7 +33,7 @@ use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use tokio::sync::RwLock; use torrust_tracker_clock::static_time; use torrust_tracker_configuration::validator::Validator; -use torrust_tracker_configuration::{logging, Configuration, Core, HttpApi, Logging, UdpTracker}; +use torrust_tracker_configuration::{logging, Configuration, Core, HttpApi, UdpTracker}; use tracing::instrument; use super::config::initialize_configuration; @@ -81,7 +81,7 @@ pub fn check_seed() { #[instrument(skip())] pub fn initialize_global_services(configuration: &Configuration) { initialize_static(); - initialize_logging(&configuration.logging); + logging::setup(&configuration.logging); } /// It initializes the IoC Container. @@ -248,11 +248,3 @@ pub fn initialize_static() { // Initialize the Zeroed Cipher lazy_static::initialize(&ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH); } - -/// It initializes the log threshold, format and channel. -/// -/// See [the logging setup](torrust_tracker_configuration::logging::setup) for more info about logging. -#[instrument(skip(logging_config))] -pub fn initialize_logging(logging_config: &Logging) { - logging::setup(logging_config); -} From bdec261cfac6a252dfdc846b73e4183808b2e6f8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 11:57:23 +0000 Subject: [PATCH 0796/1297] refactor: [#1298] move functions to container mod --- src/bootstrap/app.rs | 166 +---------------------------- src/bootstrap/jobs/tracker_apis.rs | 3 +- src/container.rs | 151 +++++++++++++++++++++++++- src/servers/apis/server.rs | 3 +- src/servers/udp/server/mod.rs | 3 +- 5 files changed, 157 insertions(+), 169 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index bbc7fd7bc..ec09edd51 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -11,33 +11,15 @@ //! 2. Initialize static variables. //! 3. Initialize logging. //! 4. Initialize the domain tracker. -use std::sync::Arc; - -use bittorrent_tracker_core::announce_handler::AnnounceHandler; -use bittorrent_tracker_core::authentication::handler::KeysHandler; -use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; -use bittorrent_tracker_core::authentication::key::repository::persisted::DatabaseKeyRepository; -use bittorrent_tracker_core::authentication::service; -use bittorrent_tracker_core::databases::setup::initialize_database; -use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::torrent::manager::TorrentsManager; -use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; -use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; -use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; -use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager; use bittorrent_udp_tracker_core::crypto::ephemeral_instance_keys; use bittorrent_udp_tracker_core::crypto::keys::{self, Keeper as _}; -use bittorrent_udp_tracker_core::services::banning::BanService; -use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; -use tokio::sync::RwLock; use torrust_tracker_clock::static_time; use torrust_tracker_configuration::validator::Validator; -use torrust_tracker_configuration::{logging, Configuration, Core, HttpApi, UdpTracker}; +use torrust_tracker_configuration::{logging, Configuration}; use tracing::instrument; use super::config::initialize_configuration; -use crate::container::{AppContainer, HttpApiContainer, UdpTrackerContainer}; +use crate::container::{initialize_app_container, AppContainer}; /// It loads the configuration from the environment and builds app container. /// @@ -84,150 +66,6 @@ pub fn initialize_global_services(configuration: &Configuration) { logging::setup(&configuration.logging); } -/// It initializes the IoC Container. -#[instrument(skip())] -pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { - let core_config = Arc::new(configuration.core.clone()); - - // HTTP stats - let (http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let http_stats_event_sender = Arc::new(http_stats_event_sender); - let http_stats_repository = Arc::new(http_stats_repository); - - // UDP stats - let (udp_stats_event_sender, udp_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - let udp_stats_repository = Arc::new(udp_stats_repository); - - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let database = initialize_database(&configuration.core); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&configuration.core, &in_memory_whitelist.clone())); - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::AuthenticationService::new( - &configuration.core, - &in_memory_key_repository, - )); - let keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - - let torrents_manager = Arc::new(TorrentsManager::new( - &configuration.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let announce_handler = Arc::new(AnnounceHandler::new( - &configuration.core, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - AppContainer { - core_config, - database, - announce_handler, - scrape_handler, - keys_handler, - authentication_service, - in_memory_whitelist, - whitelist_authorization, - ban_service, - http_stats_event_sender, - udp_stats_event_sender, - http_stats_repository, - udp_stats_repository, - whitelist_manager, - in_memory_torrent_repository, - db_torrent_repository, - torrents_manager, - } -} - -#[must_use] -pub fn initialize_http_api_container(core_config: &Arc, http_api_config: &Arc) -> Arc { - // HTTP stats - let (_http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); - let http_stats_repository = Arc::new(http_stats_repository); - - // UDP stats - let (_udp_stats_event_sender, udp_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); - let udp_stats_repository = Arc::new(udp_stats_repository); - - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let database = initialize_database(core_config); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - Arc::new(HttpApiContainer { - http_api_config: http_api_config.clone(), - core_config: core_config.clone(), - in_memory_torrent_repository: in_memory_torrent_repository.clone(), - keys_handler: keys_handler.clone(), - whitelist_manager: whitelist_manager.clone(), - ban_service: ban_service.clone(), - http_stats_repository: http_stats_repository.clone(), - udp_stats_repository: udp_stats_repository.clone(), - }) -} - -#[must_use] -pub fn initialize_udt_tracker_container( - core_config: &Arc, - udp_tracker_config: &Arc, -) -> Arc { - // UDP stats - let (udp_stats_event_sender, _udp_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let database = initialize_database(core_config); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - - let announce_handler = Arc::new(AnnounceHandler::new( - core_config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - Arc::new(UdpTrackerContainer { - udp_tracker_config: udp_tracker_config.clone(), - core_config: core_config.clone(), - announce_handler: announce_handler.clone(), - scrape_handler: scrape_handler.clone(), - whitelist_authorization: whitelist_authorization.clone(), - udp_stats_event_sender: udp_stats_event_sender.clone(), - ban_service: ban_service.clone(), - }) -} - /// It initializes the application static values. /// /// These values are accessible throughout the entire application: diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 8a36d74dc..66152905a 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -100,8 +100,9 @@ mod tests { use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::{initialize_global_services, initialize_http_api_container}; + use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::tracker_apis::start_job; + use crate::container::initialize_http_api_container; use crate::servers::apis::Version; #[tokio::test] diff --git a/src/container.rs b/src/container.rs index 881f50d2d..87f001b65 100644 --- a/src/container.rs +++ b/src/container.rs @@ -2,20 +2,26 @@ use std::sync::Arc; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::handler::KeysHandler; +use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; +use bittorrent_tracker_core::authentication::key::repository::persisted::DatabaseKeyRepository; use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::databases::Database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::manager::TorrentsManager; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist; +use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager; use bittorrent_udp_tracker_core::services::banning::BanService; -use bittorrent_udp_tracker_core::{self}; +use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; use torrust_axum_http_tracker_server::container::HttpTrackerContainer; -use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; +use torrust_tracker_configuration::{Configuration, Core, HttpApi, HttpTracker, UdpTracker}; +use tracing::instrument; pub struct AppContainer { pub core_config: Arc, @@ -99,3 +105,144 @@ pub struct HttpApiContainer { pub http_stats_repository: Arc, pub udp_stats_repository: Arc, } + +/// It initializes the IoC Container. +#[instrument(skip())] +pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { + let core_config = Arc::new(configuration.core.clone()); + + // HTTP stats + let (http_stats_event_sender, http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + let http_stats_repository = Arc::new(http_stats_repository); + + // UDP stats + let (udp_stats_event_sender, udp_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let udp_stats_repository = Arc::new(udp_stats_repository); + + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let database = initialize_database(&configuration.core); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&configuration.core, &in_memory_whitelist.clone())); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&configuration.core, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let torrents_manager = Arc::new(TorrentsManager::new( + &configuration.core, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let announce_handler = Arc::new(AnnounceHandler::new( + &configuration.core, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + AppContainer { + core_config, + database, + announce_handler, + scrape_handler, + keys_handler, + authentication_service, + in_memory_whitelist, + whitelist_authorization, + ban_service, + http_stats_event_sender, + udp_stats_event_sender, + http_stats_repository, + udp_stats_repository, + whitelist_manager, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + } +} + +#[must_use] +pub fn initialize_http_api_container(core_config: &Arc, http_api_config: &Arc) -> Arc { + // HTTP stats + let (_http_stats_event_sender, http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + let http_stats_repository = Arc::new(http_stats_repository); + + // UDP stats + let (_udp_stats_event_sender, udp_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + let udp_stats_repository = Arc::new(udp_stats_repository); + + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let database = initialize_database(core_config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let keys_handler = Arc::new(KeysHandler::new( + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + + Arc::new(HttpApiContainer { + http_api_config: http_api_config.clone(), + core_config: core_config.clone(), + in_memory_torrent_repository: in_memory_torrent_repository.clone(), + keys_handler: keys_handler.clone(), + whitelist_manager: whitelist_manager.clone(), + ban_service: ban_service.clone(), + http_stats_repository: http_stats_repository.clone(), + udp_stats_repository: udp_stats_repository.clone(), + }) +} + +#[must_use] +pub fn initialize_udt_tracker_container( + core_config: &Arc, + udp_tracker_config: &Arc, +) -> Arc { + // UDP stats + let (udp_stats_event_sender, _udp_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let database = initialize_database(core_config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let announce_handler = Arc::new(AnnounceHandler::new( + core_config, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + Arc::new(UdpTrackerContainer { + udp_tracker_config: udp_tracker_config.clone(), + core_config: core_config.clone(), + announce_handler: announce_handler.clone(), + scrape_handler: scrape_handler.clone(), + whitelist_authorization: whitelist_authorization.clone(), + udp_stats_event_sender: udp_stats_event_sender.clone(), + ban_service: ban_service.clone(), + }) +} diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index cf2c2e96b..42f16ab77 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -298,7 +298,8 @@ mod tests { use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::{initialize_global_services, initialize_http_api_container}; + use crate::bootstrap::app::initialize_global_services; + use crate::container::initialize_http_api_container; use crate::servers::apis::server::{ApiServer, Launcher}; #[tokio::test] diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index d40f3a97f..8e14bc8be 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -62,7 +62,8 @@ mod tests { use super::spawner::Spawner; use super::Server; - use crate::bootstrap::app::{initialize_global_services, initialize_udt_tracker_container}; + use crate::bootstrap::app::initialize_global_services; + use crate::container::initialize_udt_tracker_container; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { From 9f18c6e498f6f3324fb20ea4b42e7b84ac1ddc64 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 12:27:15 +0000 Subject: [PATCH 0797/1297] refactor: [#1298] extract TrackerCoreContainer --- packages/tracker-core/src/container.rs | 84 +++++++++++++++++++ packages/tracker-core/src/lib.rs | 1 + src/container.rs | 111 +++++++------------------ 3 files changed, 117 insertions(+), 79 deletions(-) create mode 100644 packages/tracker-core/src/container.rs diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs new file mode 100644 index 000000000..9f4d23802 --- /dev/null +++ b/packages/tracker-core/src/container.rs @@ -0,0 +1,84 @@ +use std::sync::Arc; + +use torrust_tracker_configuration::Core; + +use crate::announce_handler::AnnounceHandler; +use crate::authentication::handler::KeysHandler; +use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; +use crate::authentication::key::repository::persisted::DatabaseKeyRepository; +use crate::authentication::service::AuthenticationService; +use crate::databases::setup::initialize_database; +use crate::databases::Database; +use crate::scrape_handler::ScrapeHandler; +use crate::torrent::manager::TorrentsManager; +use crate::torrent::repository::in_memory::InMemoryTorrentRepository; +use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use crate::whitelist; +use crate::whitelist::authorization::WhitelistAuthorization; +use crate::whitelist::manager::WhitelistManager; +use crate::whitelist::repository::in_memory::InMemoryWhitelist; +use crate::whitelist::setup::initialize_whitelist_manager; + +pub struct TrackerCoreContainer { + pub core_config: Arc, + pub database: Arc>, + pub announce_handler: Arc, + pub scrape_handler: Arc, + pub keys_handler: Arc, + pub authentication_service: Arc, + pub in_memory_whitelist: Arc, + pub whitelist_authorization: Arc, + pub whitelist_manager: Arc, + pub in_memory_torrent_repository: Arc, + pub db_torrent_repository: Arc, + pub torrents_manager: Arc, +} + +impl TrackerCoreContainer { + #[must_use] + pub fn initialize(core_config: &Arc) -> Self { + let database = initialize_database(core_config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); + let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); + let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(core_config, &in_memory_key_repository)); + let keys_handler = Arc::new(KeysHandler::new( + &db_key_repository.clone(), + &in_memory_key_repository.clone(), + )); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let torrents_manager = Arc::new(TorrentsManager::new( + core_config, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let announce_handler = Arc::new(AnnounceHandler::new( + core_config, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + Self { + core_config: core_config.clone(), + database, + announce_handler, + scrape_handler, + keys_handler, + authentication_service, + in_memory_whitelist, + whitelist_authorization, + whitelist_manager, + in_memory_torrent_repository, + db_torrent_repository, + torrents_manager, + } + } +} diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index 8e73fe027..0107fb443 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -120,6 +120,7 @@ //! Please refer to the [`whitelist`] documentation. pub mod announce_handler; pub mod authentication; +pub mod container; pub mod databases; pub mod error; pub mod scrape_handler; diff --git a/src/container.rs b/src/container.rs index 87f001b65..22443aa56 100644 --- a/src/container.rs +++ b/src/container.rs @@ -2,20 +2,16 @@ use std::sync::Arc; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::handler::KeysHandler; -use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; -use bittorrent_tracker_core::authentication::key::repository::persisted::DatabaseKeyRepository; use bittorrent_tracker_core::authentication::service::AuthenticationService; -use bittorrent_tracker_core::databases::setup::initialize_database; +use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_tracker_core::databases::Database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::manager::TorrentsManager; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist; -use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; -use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; @@ -24,6 +20,7 @@ use torrust_tracker_configuration::{Configuration, Core, HttpApi, HttpTracker, U use tracing::instrument; pub struct AppContainer { + // Tracker Core Services pub core_config: Arc, pub database: Arc>, pub announce_handler: Arc, @@ -32,15 +29,17 @@ pub struct AppContainer { pub authentication_service: Arc, pub in_memory_whitelist: Arc, pub whitelist_authorization: Arc, - pub ban_service: Arc>, - pub http_stats_event_sender: Arc>>, - pub udp_stats_event_sender: Arc>>, - pub http_stats_repository: Arc, - pub udp_stats_repository: Arc, pub whitelist_manager: Arc, pub in_memory_torrent_repository: Arc, pub db_torrent_repository: Arc, pub torrents_manager: Arc, + // UDP Tracker Core Services + pub ban_service: Arc>, + pub udp_stats_event_sender: Arc>>, + // HTTP Tracker Core Services + pub http_stats_event_sender: Arc>>, + pub http_stats_repository: Arc, + pub udp_stats_repository: Arc, } impl AppContainer { @@ -111,6 +110,8 @@ pub struct HttpApiContainer { pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let core_config = Arc::new(configuration.core.clone()); + let tracker_core_container = TrackerCoreContainer::initialize(&core_config); + // HTTP stats let (http_stats_event_sender, http_stats_repository) = bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); @@ -124,58 +125,32 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { let udp_stats_repository = Arc::new(udp_stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let database = initialize_database(&configuration.core); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&configuration.core, &in_memory_whitelist.clone())); - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(AuthenticationService::new(&configuration.core, &in_memory_key_repository)); - let keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - - let torrents_manager = Arc::new(TorrentsManager::new( - &configuration.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let announce_handler = Arc::new(AnnounceHandler::new( - &configuration.core, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); AppContainer { core_config, - database, - announce_handler, - scrape_handler, - keys_handler, - authentication_service, - in_memory_whitelist, - whitelist_authorization, + database: tracker_core_container.database, + announce_handler: tracker_core_container.announce_handler, + scrape_handler: tracker_core_container.scrape_handler, + keys_handler: tracker_core_container.keys_handler, + authentication_service: tracker_core_container.authentication_service, + in_memory_whitelist: tracker_core_container.in_memory_whitelist, + whitelist_authorization: tracker_core_container.whitelist_authorization, + whitelist_manager: tracker_core_container.whitelist_manager, + in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository, + db_torrent_repository: tracker_core_container.db_torrent_repository, + torrents_manager: tracker_core_container.torrents_manager, ban_service, http_stats_event_sender, udp_stats_event_sender, http_stats_repository, udp_stats_repository, - whitelist_manager, - in_memory_torrent_repository, - db_torrent_repository, - torrents_manager, } } #[must_use] pub fn initialize_http_api_container(core_config: &Arc, http_api_config: &Arc) -> Arc { + let tracker_core_container = TrackerCoreContainer::initialize(core_config); + // HTTP stats let (_http_stats_event_sender, http_stats_repository) = bittorrent_http_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); @@ -187,23 +162,13 @@ pub fn initialize_http_api_container(core_config: &Arc, http_api_config: & let udp_stats_repository = Arc::new(udp_stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let database = initialize_database(core_config); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); Arc::new(HttpApiContainer { http_api_config: http_api_config.clone(), core_config: core_config.clone(), - in_memory_torrent_repository: in_memory_torrent_repository.clone(), - keys_handler: keys_handler.clone(), - whitelist_manager: whitelist_manager.clone(), + in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository.clone(), + keys_handler: tracker_core_container.keys_handler.clone(), + whitelist_manager: tracker_core_container.whitelist_manager.clone(), ban_service: ban_service.clone(), http_stats_repository: http_stats_repository.clone(), udp_stats_repository: udp_stats_repository.clone(), @@ -215,33 +180,21 @@ pub fn initialize_udt_tracker_container( core_config: &Arc, udp_tracker_config: &Arc, ) -> Arc { + let tracker_core_container = TrackerCoreContainer::initialize(core_config); + // UDP stats let (udp_stats_event_sender, _udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let database = initialize_database(core_config); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - - let announce_handler = Arc::new(AnnounceHandler::new( - core_config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); Arc::new(UdpTrackerContainer { udp_tracker_config: udp_tracker_config.clone(), core_config: core_config.clone(), - announce_handler: announce_handler.clone(), - scrape_handler: scrape_handler.clone(), - whitelist_authorization: whitelist_authorization.clone(), + announce_handler: tracker_core_container.announce_handler.clone(), + scrape_handler: tracker_core_container.scrape_handler.clone(), + whitelist_authorization: tracker_core_container.whitelist_authorization.clone(), udp_stats_event_sender: udp_stats_event_sender.clone(), ban_service: ban_service.clone(), }) From d1520430ff4e44d16e1cadf24fb7f94d6e27f410 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 13:50:11 +0000 Subject: [PATCH 0798/1297] refactor: [#1298] mmove HttpTrackerContainer to http-tracker-core --- packages/axum-http-tracker-server/src/lib.rs | 1 - packages/axum-http-tracker-server/src/server.rs | 4 ++-- packages/axum-http-tracker-server/src/v1/routes.rs | 2 +- .../src/container.rs | 7 ++++--- packages/http-tracker-core/src/lib.rs | 1 + src/bootstrap/jobs/http_tracker.rs | 4 ++-- src/container.rs | 2 +- tests/servers/http/environment.rs | 2 +- 8 files changed, 12 insertions(+), 11 deletions(-) rename packages/{axum-http-tracker-server => http-tracker-core}/src/container.rs (90%) diff --git a/packages/axum-http-tracker-server/src/lib.rs b/packages/axum-http-tracker-server/src/lib.rs index 3d9f6d1b7..a8823b868 100644 --- a/packages/axum-http-tracker-server/src/lib.rs +++ b/packages/axum-http-tracker-server/src/lib.rs @@ -305,7 +305,6 @@ //! - [Bencode to Json Online converter](https://chocobo1.github.io/bencode_online). use serde::{Deserialize, Serialize}; -pub mod container; pub mod server; pub mod v1; diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 39969907b..615335aba 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; +use bittorrent_http_tracker_core::container::HttpTrackerContainer; use derive_more::Constructor; use futures::future::BoxFuture; use tokio::sync::oneshot::{Receiver, Sender}; @@ -15,7 +16,6 @@ use torrust_server_lib::signals::{Halted, Started}; use tracing::instrument; use super::v1::routes::router; -use crate::container::HttpTrackerContainer; use crate::HTTP_TRACKER_LOG_TARGET; /// Error that can occur when starting or stopping the HTTP server. @@ -238,6 +238,7 @@ pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { mod tests { use std::sync::Arc; + use bittorrent_http_tracker_core::container::HttpTrackerContainer; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service; @@ -252,7 +253,6 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::container::HttpTrackerContainer; use crate::server::{HttpServer, Launcher}; pub fn initialize_container(configuration: &Configuration) -> HttpTrackerContainer { diff --git a/packages/axum-http-tracker-server/src/v1/routes.rs b/packages/axum-http-tracker-server/src/v1/routes.rs index 2d530f633..7e4b7c922 100644 --- a/packages/axum-http-tracker-server/src/v1/routes.rs +++ b/packages/axum-http-tracker-server/src/v1/routes.rs @@ -9,6 +9,7 @@ use axum::response::Response; use axum::routing::get; use axum::{BoxError, Router}; use axum_client_ip::SecureClientIpSource; +use bittorrent_http_tracker_core::container::HttpTrackerContainer; use hyper::{Request, StatusCode}; use torrust_server_lib::logging::Latency; use torrust_tracker_configuration::DEFAULT_TIMEOUT; @@ -23,7 +24,6 @@ use tower_http::LatencyUnit; use tracing::{instrument, Level, Span}; use super::handlers::{announce, health_check, scrape}; -use crate::container::HttpTrackerContainer; use crate::HTTP_TRACKER_LOG_TARGET; /// It adds the routes to the router. diff --git a/packages/axum-http-tracker-server/src/container.rs b/packages/http-tracker-core/src/container.rs similarity index 90% rename from packages/axum-http-tracker-server/src/container.rs rename to packages/http-tracker-core/src/container.rs index 339c25778..b952a5853 100644 --- a/packages/axum-http-tracker-server/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -12,13 +12,15 @@ use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::{Core, HttpTracker}; +use crate::statistics; + pub struct HttpTrackerContainer { pub core_config: Arc, pub http_tracker_config: Arc, pub announce_handler: Arc, pub scrape_handler: Arc, pub whitelist_authorization: Arc, - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, pub authentication_service: Arc, } @@ -28,8 +30,7 @@ pub fn initialize_http_tracker_container( http_tracker_config: &Arc, ) -> Arc { // HTTP stats - let (http_stats_event_sender, _http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + let (http_stats_event_sender, _http_stats_repository) = statistics::setup::factory(core_config.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); let database = initialize_database(core_config); diff --git a/packages/http-tracker-core/src/lib.rs b/packages/http-tracker-core/src/lib.rs index cb5306aa6..b42b99f8e 100644 --- a/packages/http-tracker-core/src/lib.rs +++ b/packages/http-tracker-core/src/lib.rs @@ -1,3 +1,4 @@ +pub mod container; pub mod services; pub mod statistics; diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 471f74b8b..3febf60f0 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -14,8 +14,8 @@ use std::net::SocketAddr; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; +use bittorrent_http_tracker_core::container::HttpTrackerContainer; use tokio::task::JoinHandle; -use torrust_axum_http_tracker_server::container::HttpTrackerContainer; use torrust_axum_http_tracker_server::server::{HttpServer, Launcher}; use torrust_axum_http_tracker_server::Version; use torrust_axum_server::tsl::make_rust_tls; @@ -77,7 +77,7 @@ async fn start_v1( mod tests { use std::sync::Arc; - use torrust_axum_http_tracker_server::container::initialize_http_tracker_container; + use bittorrent_http_tracker_core::container::initialize_http_tracker_container; use torrust_axum_http_tracker_server::Version; use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; diff --git a/src/container.rs b/src/container.rs index 22443aa56..692036220 100644 --- a/src/container.rs +++ b/src/container.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use bittorrent_http_tracker_core::container::HttpTrackerContainer; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::handler::KeysHandler; use bittorrent_tracker_core::authentication::service::AuthenticationService; @@ -15,7 +16,6 @@ use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; -use torrust_axum_http_tracker_server::container::HttpTrackerContainer; use torrust_tracker_configuration::{Configuration, Core, HttpApi, HttpTracker, UdpTracker}; use tracing::instrument; diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index a0164eccc..fe1a2374b 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use bittorrent_http_tracker_core::container::HttpTrackerContainer; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::handler::KeysHandler; @@ -16,7 +17,6 @@ use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager; use futures::executor::block_on; -use torrust_axum_http_tracker_server::container::HttpTrackerContainer; use torrust_axum_http_tracker_server::server::{HttpServer, Launcher, Running, Stopped}; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; From 06a29cd5856c3f1dad8c2313ee512b60e4141fd6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 13:52:21 +0000 Subject: [PATCH 0799/1297] refactor: [#1298] convert fn into static method --- packages/http-tracker-core/src/container.rs | 71 ++++++++++----------- src/bootstrap/jobs/http_tracker.rs | 4 +- 2 files changed, 37 insertions(+), 38 deletions(-) diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index b952a5853..eb19d8334 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -24,40 +24,39 @@ pub struct HttpTrackerContainer { pub authentication_service: Arc, } -#[must_use] -pub fn initialize_http_tracker_container( - core_config: &Arc, - http_tracker_config: &Arc, -) -> Arc { - // HTTP stats - let (http_stats_event_sender, _http_stats_repository) = statistics::setup::factory(core_config.tracker_usage_statistics); - let http_stats_event_sender = Arc::new(http_stats_event_sender); - - let database = initialize_database(core_config); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(AuthenticationService::new(core_config, &in_memory_key_repository)); - - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - - let announce_handler = Arc::new(AnnounceHandler::new( - core_config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - Arc::new(HttpTrackerContainer { - http_tracker_config: http_tracker_config.clone(), - core_config: core_config.clone(), - announce_handler: announce_handler.clone(), - scrape_handler: scrape_handler.clone(), - whitelist_authorization: whitelist_authorization.clone(), - http_stats_event_sender: http_stats_event_sender.clone(), - authentication_service: authentication_service.clone(), - }) +impl HttpTrackerContainer { + #[must_use] + pub fn initialize(core_config: &Arc, http_tracker_config: &Arc) -> Arc { + // HTTP stats + let (http_stats_event_sender, _http_stats_repository) = statistics::setup::factory(core_config.tracker_usage_statistics); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + + let database = initialize_database(core_config); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(core_config, &in_memory_key_repository)); + + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + + let announce_handler = Arc::new(AnnounceHandler::new( + core_config, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + + Arc::new(Self { + http_tracker_config: http_tracker_config.clone(), + core_config: core_config.clone(), + announce_handler: announce_handler.clone(), + scrape_handler: scrape_handler.clone(), + whitelist_authorization: whitelist_authorization.clone(), + http_stats_event_sender: http_stats_event_sender.clone(), + authentication_service: authentication_service.clone(), + }) + } } diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 3febf60f0..6a8c6d84c 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -77,7 +77,7 @@ async fn start_v1( mod tests { use std::sync::Arc; - use bittorrent_http_tracker_core::container::initialize_http_tracker_container; + use bittorrent_http_tracker_core::container::HttpTrackerContainer; use torrust_axum_http_tracker_server::Version; use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; @@ -94,7 +94,7 @@ mod tests { initialize_global_services(&cfg); - let http_tracker_container = initialize_http_tracker_container(&core_config, &http_tracker_config); + let http_tracker_container = HttpTrackerContainer::initialize(&core_config, &http_tracker_config); let version = Version::V1; From b562f8d19487125c6c8629a9960477a8b8408486 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 14:46:45 +0000 Subject: [PATCH 0800/1297] refacotr: [#1298] remove duplicate code --- .../axum-http-tracker-server/src/server.rs | 9 +- packages/http-tracker-core/src/container.rs | 67 +++++---- src/container.rs | 6 +- tests/servers/http/environment.rs | 139 +++--------------- tests/servers/http/v1/contract.rs | 108 ++++++++------ 5 files changed, 137 insertions(+), 192 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 615335aba..749f57e02 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -268,9 +268,10 @@ mod tests { let http_tracker_config = Arc::new(http_tracker_config.clone()); // HTTP stats - let (http_stats_event_sender, _http_stats_repository) = + let (http_stats_event_sender, http_stats_repository) = bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); + let http_stats_repository = Arc::new(http_stats_repository); let database = initialize_database(&configuration.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -294,12 +295,14 @@ mod tests { HttpTrackerContainer { core_config, - http_tracker_config, announce_handler, scrape_handler, whitelist_authorization, - http_stats_event_sender, authentication_service, + + http_tracker_config, + http_stats_event_sender, + http_stats_repository, } } diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index eb19d8334..c9945f3b1 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -1,62 +1,73 @@ use std::sync::Arc; use bittorrent_tracker_core::announce_handler::AnnounceHandler; -use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service::AuthenticationService; -use bittorrent_tracker_core::databases::setup::initialize_database; +use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist; -use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; -use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::{Core, HttpTracker}; use crate::statistics; pub struct HttpTrackerContainer { + // todo: replace with TrackerCoreContainer pub core_config: Arc, - pub http_tracker_config: Arc, pub announce_handler: Arc, pub scrape_handler: Arc, pub whitelist_authorization: Arc, - pub http_stats_event_sender: Arc>>, pub authentication_service: Arc, + + pub http_tracker_config: Arc, + pub http_stats_event_sender: Arc>>, + pub http_stats_repository: Arc, } impl HttpTrackerContainer { #[must_use] - pub fn initialize(core_config: &Arc, http_tracker_config: &Arc) -> Arc { + pub fn initialize_from( + tracker_core_container: &Arc, + http_tracker_config: &Arc, + ) -> Arc { // HTTP stats - let (http_stats_event_sender, _http_stats_repository) = statistics::setup::factory(core_config.tracker_usage_statistics); + let (http_stats_event_sender, http_stats_repository) = + statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); + let http_stats_repository = Arc::new(http_stats_repository); + + Arc::new(Self { + http_tracker_config: http_tracker_config.clone(), - let database = initialize_database(core_config); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(AuthenticationService::new(core_config, &in_memory_key_repository)); + core_config: tracker_core_container.core_config.clone(), + announce_handler: tracker_core_container.announce_handler.clone(), + scrape_handler: tracker_core_container.scrape_handler.clone(), + whitelist_authorization: tracker_core_container.whitelist_authorization.clone(), + authentication_service: tracker_core_container.authentication_service.clone(), - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + http_stats_event_sender: http_stats_event_sender.clone(), + http_stats_repository: http_stats_repository.clone(), + }) + } - let announce_handler = Arc::new(AnnounceHandler::new( - core_config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - )); + #[must_use] + pub fn initialize(core_config: &Arc, http_tracker_config: &Arc) -> Arc { + let tracker_core_container = TrackerCoreContainer::initialize(core_config); - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + // HTTP stats + let (http_stats_event_sender, http_stats_repository) = statistics::setup::factory(core_config.tracker_usage_statistics); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + let http_stats_repository = Arc::new(http_stats_repository); Arc::new(Self { http_tracker_config: http_tracker_config.clone(), + core_config: core_config.clone(), - announce_handler: announce_handler.clone(), - scrape_handler: scrape_handler.clone(), - whitelist_authorization: whitelist_authorization.clone(), + announce_handler: tracker_core_container.announce_handler.clone(), + scrape_handler: tracker_core_container.scrape_handler.clone(), + whitelist_authorization: tracker_core_container.whitelist_authorization.clone(), + authentication_service: tracker_core_container.authentication_service.clone(), + http_stats_event_sender: http_stats_event_sender.clone(), - authentication_service: authentication_service.clone(), + http_stats_repository: http_stats_repository.clone(), }) } } diff --git a/src/container.rs b/src/container.rs index 692036220..5d76a20f3 100644 --- a/src/container.rs +++ b/src/container.rs @@ -46,13 +46,15 @@ impl AppContainer { #[must_use] pub fn http_tracker_container(&self, http_tracker_config: &Arc) -> HttpTrackerContainer { HttpTrackerContainer { - http_tracker_config: http_tracker_config.clone(), core_config: self.core_config.clone(), announce_handler: self.announce_handler.clone(), scrape_handler: self.scrape_handler.clone(), whitelist_authorization: self.whitelist_authorization.clone(), - http_stats_event_sender: self.http_stats_event_sender.clone(), authentication_service: self.authentication_service.clone(), + + http_tracker_config: http_tracker_config.clone(), + http_stats_event_sender: self.http_stats_event_sender.clone(), + http_stats_repository: self.http_stats_repository.clone(), } } diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index fe1a2374b..209430d25 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -2,37 +2,17 @@ use std::sync::Arc; use bittorrent_http_tracker_core::container::HttpTrackerContainer; use bittorrent_primitives::info_hash::InfoHash; -use bittorrent_tracker_core::announce_handler::AnnounceHandler; -use bittorrent_tracker_core::authentication::handler::KeysHandler; -use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; -use bittorrent_tracker_core::authentication::key::repository::persisted::DatabaseKeyRepository; -use bittorrent_tracker_core::authentication::service::AuthenticationService; -use bittorrent_tracker_core::databases::setup::initialize_database; -use bittorrent_tracker_core::databases::Database; -use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; -use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; -use bittorrent_tracker_core::whitelist::manager::WhitelistManager; -use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; -use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager; +use bittorrent_tracker_core::container::TrackerCoreContainer; use futures::executor::block_on; use torrust_axum_http_tracker_server::server::{HttpServer, Launcher, Running, Stopped}; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; -use torrust_tracker_configuration::{Configuration, Core, HttpTracker}; +use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::initialize_global_services; use torrust_tracker_primitives::peer; pub struct Environment { - pub http_tracker_container: Arc, - - pub database: Arc>, - pub in_memory_torrent_repository: Arc, - pub keys_handler: Arc, - pub http_stats_repository: Arc, - pub whitelist_manager: Arc, - + pub container: Arc, pub registar: Registar, pub server: HttpServer, } @@ -40,7 +20,11 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let () = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); + let () = self + .container + .tracker_core_container + .in_memory_torrent_repository + .upsert_peer(info_hash, peer); } } @@ -49,34 +33,19 @@ impl Environment { pub fn new(configuration: &Arc) -> Self { initialize_global_services(configuration); - let env_container = EnvContainer::initialize(configuration); + let container = Arc::new(EnvContainer::initialize(configuration)); - let bind_to = env_container.http_tracker_config.bind_address; + let bind_to = container.http_tracker_container.http_tracker_config.bind_address; - let tls = - block_on(make_rust_tls(&env_container.http_tracker_config.tsl_config)).map(|tls| tls.expect("tls config failed")); + let tls = block_on(make_rust_tls( + &container.http_tracker_container.http_tracker_config.tsl_config, + )) + .map(|tls| tls.expect("tls config failed")); let server = HttpServer::new(Launcher::new(bind_to, tls)); - let http_tracker_container = Arc::new(HttpTrackerContainer { - core_config: env_container.core_config.clone(), - http_tracker_config: env_container.http_tracker_config.clone(), - announce_handler: env_container.http_tracker_container.announce_handler.clone(), - scrape_handler: env_container.http_tracker_container.scrape_handler.clone(), - whitelist_authorization: env_container.http_tracker_container.whitelist_authorization.clone(), - http_stats_event_sender: env_container.http_tracker_container.http_stats_event_sender.clone(), - authentication_service: env_container.http_tracker_container.authentication_service.clone(), - }); - Self { - http_tracker_container, - - database: env_container.database.clone(), - in_memory_torrent_repository: env_container.in_memory_torrent_repository.clone(), - keys_handler: env_container.keys_handler.clone(), - http_stats_repository: env_container.http_stats_repository.clone(), - whitelist_manager: env_container.whitelist_manager.clone(), - + container, registar: Registar::default(), server, } @@ -85,18 +54,11 @@ impl Environment { #[allow(dead_code)] pub async fn start(self) -> Environment { Environment { - http_tracker_container: self.http_tracker_container.clone(), - - database: self.database.clone(), - in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), - keys_handler: self.keys_handler.clone(), - http_stats_repository: self.http_stats_repository.clone(), - whitelist_manager: self.whitelist_manager.clone(), - + container: self.container.clone(), registar: self.registar.clone(), server: self .server - .start(self.http_tracker_container, self.registar.give_form()) + .start(self.container.http_tracker_container.clone(), self.registar.give_form()) .await .unwrap(), } @@ -110,14 +72,7 @@ impl Environment { pub async fn stop(self) -> Environment { Environment { - http_tracker_container: self.http_tracker_container, - - database: self.database, - in_memory_torrent_repository: self.in_memory_torrent_repository, - keys_handler: self.keys_handler, - http_stats_repository: self.http_stats_repository, - whitelist_manager: self.whitelist_manager, - + container: self.container, registar: Registar::default(), server: self.server.stop().await.unwrap(), } @@ -129,15 +84,8 @@ impl Environment { } pub struct EnvContainer { - pub core_config: Arc, - pub http_tracker_config: Arc, + pub tracker_core_container: Arc, pub http_tracker_container: Arc, - - pub database: Arc>, - pub in_memory_torrent_repository: Arc, - pub keys_handler: Arc, - pub http_stats_repository: Arc, - pub whitelist_manager: Arc, } impl EnvContainer { @@ -149,55 +97,12 @@ impl EnvContainer { .expect("missing HTTP tracker configuration"); let http_tracker_config = Arc::new(http_tracker_config[0].clone()); - // HTTP stats - let (http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let http_stats_event_sender = Arc::new(http_stats_event_sender); - let http_stats_repository = Arc::new(http_stats_repository); - - let database = initialize_database(&configuration.core); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&configuration.core, &in_memory_whitelist.clone())); - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(AuthenticationService::new(&configuration.core, &in_memory_key_repository)); - let keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - - let announce_handler = Arc::new(AnnounceHandler::new( - &configuration.core, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - let http_tracker_container = Arc::new(HttpTrackerContainer { - http_tracker_config: http_tracker_config.clone(), - core_config: core_config.clone(), - announce_handler: announce_handler.clone(), - scrape_handler: scrape_handler.clone(), - whitelist_authorization: whitelist_authorization.clone(), - http_stats_event_sender: http_stats_event_sender.clone(), - authentication_service: authentication_service.clone(), - }); + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); + let http_tracker_container = HttpTrackerContainer::initialize_from(&tracker_core_container, &http_tracker_config); Self { - core_config, - http_tracker_config, + tracker_core_container, http_tracker_container, - - database, - in_memory_torrent_repository, - keys_handler, - http_stats_repository, - whitelist_manager, } } } diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index 1931544b9..d7a09cd2d 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -444,12 +444,12 @@ mod for_all_config_modes { let response = Client::new(*env.bind_address()) .announce( &QueryBuilder::default() - .with_info_hash(&InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap()) + .with_info_hash(&InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap()) // DevSkim: ignore DS173237 .query(), ) .await; - let announce_policy = env.http_tracker_container.core_config.announce_policy; + let announce_policy = env.container.tracker_core_container.core_config.announce_policy; assert_announce_response( response, @@ -472,7 +472,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 // Peer 1 let previously_announced_peer = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); @@ -490,7 +490,7 @@ mod for_all_config_modes { ) .await; - let announce_policy = env.http_tracker_container.core_config.announce_policy; + let announce_policy = env.container.tracker_core_container.core_config.announce_policy; // It should only contain the previously announced peer assert_announce_response( @@ -514,7 +514,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 // Announce a peer using IPV4 let peer_using_ipv4 = PeerBuilder::default() @@ -543,7 +543,7 @@ mod for_all_config_modes { ) .await; - let announce_policy = env.http_tracker_container.core_config.announce_policy; + let announce_policy = env.container.tracker_core_container.core_config.announce_policy; // The newly announced peer is not included on the response peer list, // but all the previously announced peers should be included regardless the IP version they are using. @@ -568,7 +568,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 let peer = PeerBuilder::default().build(); // Add a peer @@ -597,7 +597,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 // Peer 1 let previously_announced_peer = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); @@ -638,7 +638,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 // Peer 1 let previously_announced_peer = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); @@ -680,7 +680,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.http_stats_repository.get_stats().await; + let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; assert_eq!(stats.tcp4_connections_handled, 1); @@ -706,7 +706,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.http_stats_repository.get_stats().await; + let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; assert_eq!(stats.tcp6_connections_handled, 1); @@ -731,7 +731,7 @@ mod for_all_config_modes { ) .await; - let stats = env.http_stats_repository.get_stats().await; + let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; assert_eq!(stats.tcp6_connections_handled, 0); @@ -750,7 +750,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.http_stats_repository.get_stats().await; + let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; assert_eq!(stats.tcp4_announces_handled, 1); @@ -776,7 +776,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.http_stats_repository.get_stats().await; + let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; assert_eq!(stats.tcp6_announces_handled, 1); @@ -801,7 +801,7 @@ mod for_all_config_modes { ) .await; - let stats = env.http_stats_repository.get_stats().await; + let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; assert_eq!(stats.tcp6_announces_handled, 0); @@ -816,7 +816,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 let client_ip = local_ip().unwrap(); let announce_query = QueryBuilder::default() @@ -831,7 +831,11 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.in_memory_torrent_repository.get_torrent_peers(&info_hash); + let peers = env + .container + .tracker_core_container + .in_memory_torrent_repository + .get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), client_ip); @@ -853,7 +857,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_with_external_ip(IpAddr::from_str("2.137.87.41").unwrap()).into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 let loopback_ip = IpAddr::from_str("127.0.0.1").unwrap(); let client_ip = loopback_ip; @@ -869,12 +873,16 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.in_memory_torrent_repository.get_torrent_peers(&info_hash); + let peers = env + .container + .tracker_core_container + .in_memory_torrent_repository + .get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!( peer_addr.ip(), - env.http_tracker_container.core_config.net.external_ip.unwrap() + env.container.tracker_core_container.core_config.net.external_ip.unwrap() ); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); @@ -898,7 +906,7 @@ mod for_all_config_modes { ) .await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 let loopback_ip = IpAddr::from_str("127.0.0.1").unwrap(); let client_ip = loopback_ip; @@ -914,12 +922,16 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.in_memory_torrent_repository.get_torrent_peers(&info_hash); + let peers = env + .container + .tracker_core_container + .in_memory_torrent_repository + .get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!( peer_addr.ip(), - env.http_tracker_container.core_config.net.external_ip.unwrap() + env.container.tracker_core_container.core_config.net.external_ip.unwrap() ); assert_ne!(peer_addr.ip(), IpAddr::from_str("2.2.2.2").unwrap()); @@ -939,7 +951,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_with_reverse_proxy().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 let announce_query = QueryBuilder::default().with_info_hash(&info_hash).query(); @@ -957,7 +969,11 @@ mod for_all_config_modes { assert_eq!(status, StatusCode::OK); } - let peers = env.in_memory_torrent_repository.get_torrent_peers(&info_hash); + let peers = env + .container + .tracker_core_container + .in_memory_torrent_repository + .get_torrent_peers(&info_hash); let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), IpAddr::from_str("150.172.238.178").unwrap()); @@ -1034,7 +1050,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 env.add_torrent_peer( &info_hash, @@ -1074,7 +1090,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 env.add_torrent_peer( &info_hash, @@ -1114,7 +1130,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 let response = Client::new(*env.bind_address()) .scrape( @@ -1135,8 +1151,8 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash1 = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); - let info_hash2 = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); + let info_hash1 = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 + let info_hash2 = InfoHash::from_str("3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0").unwrap(); // DevSkim: ignore DS173237 let response = Client::new(*env.bind_address()) .scrape( @@ -1163,7 +1179,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_public().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 Client::new(*env.bind_address()) .scrape( @@ -1173,7 +1189,7 @@ mod for_all_config_modes { ) .await; - let stats = env.http_stats_repository.get_stats().await; + let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; assert_eq!(stats.tcp4_scrapes_handled, 1); @@ -1195,7 +1211,7 @@ mod for_all_config_modes { let env = Started::new(&configuration::ephemeral_ipv6().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 Client::bind(*env.bind_address(), IpAddr::from_str("::1").unwrap()) .scrape( @@ -1205,7 +1221,7 @@ mod for_all_config_modes { ) .await; - let stats = env.http_stats_repository.get_stats().await; + let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; assert_eq!(stats.tcp6_scrapes_handled, 1); @@ -1265,9 +1281,11 @@ mod configured_as_whitelisted { let env = Started::new(&configuration::ephemeral_listed().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 - env.whitelist_manager + env.container + .tracker_core_container + .whitelist_manager .add_torrent_to_whitelist(&info_hash) .await .expect("should add the torrent to the whitelist"); @@ -1339,7 +1357,7 @@ mod configured_as_whitelisted { let env = Started::new(&configuration::ephemeral_listed().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 env.add_torrent_peer( &info_hash, @@ -1349,7 +1367,9 @@ mod configured_as_whitelisted { .build(), ); - env.whitelist_manager + env.container + .tracker_core_container + .whitelist_manager .add_torrent_to_whitelist(&info_hash) .await .expect("should add the torrent to the whitelist"); @@ -1403,6 +1423,8 @@ mod configured_as_private { let env = Started::new(&configuration::ephemeral_private().into()).await; let expiring_key = env + .container + .tracker_core_container .keys_handler .generate_expiring_peer_key(Some(Duration::from_secs(60))) .await @@ -1423,7 +1445,7 @@ mod configured_as_private { let env = Started::new(&configuration::ephemeral_private().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 let response = Client::new(*env.bind_address()) .announce(&QueryBuilder::default().with_info_hash(&info_hash).query()) @@ -1510,7 +1532,7 @@ mod configured_as_private { let env = Started::new(&configuration::ephemeral_private().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 env.add_torrent_peer( &info_hash, @@ -1541,7 +1563,7 @@ mod configured_as_private { let env = Started::new(&configuration::ephemeral_private().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 env.add_torrent_peer( &info_hash, @@ -1552,6 +1574,8 @@ mod configured_as_private { ); let expiring_key = env + .container + .tracker_core_container .keys_handler .generate_expiring_peer_key(Some(Duration::from_secs(60))) .await @@ -1590,7 +1614,7 @@ mod configured_as_private { let env = Started::new(&configuration::ephemeral_private().into()).await; - let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); + let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 env.add_torrent_peer( &info_hash, From 1eca6a3293cdaec2ada6ba945fec856e061bde1f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 14:49:06 +0000 Subject: [PATCH 0801/1297] refactor: [#1298] rename struct and field --- .../axum-http-tracker-server/src/server.rs | 12 ++-- .../axum-http-tracker-server/src/v1/routes.rs | 4 +- packages/http-tracker-core/src/container.rs | 4 +- src/bootstrap/jobs/http_tracker.rs | 10 ++-- src/container.rs | 6 +- tests/servers/http/environment.rs | 14 ++--- tests/servers/http/v1/contract.rs | 56 ++++++++++++++++--- 7 files changed, 73 insertions(+), 33 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 749f57e02..a5cd3bb74 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; -use bittorrent_http_tracker_core::container::HttpTrackerContainer; +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use derive_more::Constructor; use futures::future::BoxFuture; use tokio::sync::oneshot::{Receiver, Sender}; @@ -45,7 +45,7 @@ impl Launcher { #[instrument(skip(self, http_tracker_container, tx_start, rx_halt))] fn start( &self, - http_tracker_container: Arc, + http_tracker_container: Arc, tx_start: Sender, rx_halt: Receiver, ) -> BoxFuture<'static, ()> { @@ -160,7 +160,7 @@ impl HttpServer { /// back to the main thread. pub async fn start( self, - http_tracker_container: Arc, + http_tracker_container: Arc, form: ServiceRegistrationForm, ) -> Result, Error> { let (tx_start, rx_start) = tokio::sync::oneshot::channel::(); @@ -238,7 +238,7 @@ pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { mod tests { use std::sync::Arc; - use bittorrent_http_tracker_core::container::HttpTrackerContainer; + use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service; @@ -255,7 +255,7 @@ mod tests { use crate::server::{HttpServer, Launcher}; - pub fn initialize_container(configuration: &Configuration) -> HttpTrackerContainer { + pub fn initialize_container(configuration: &Configuration) -> HttpTrackerCoreContainer { let core_config = Arc::new(configuration.core.clone()); let http_trackers = configuration @@ -293,7 +293,7 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - HttpTrackerContainer { + HttpTrackerCoreContainer { core_config, announce_handler, scrape_handler, diff --git a/packages/axum-http-tracker-server/src/v1/routes.rs b/packages/axum-http-tracker-server/src/v1/routes.rs index 7e4b7c922..7a96f6014 100644 --- a/packages/axum-http-tracker-server/src/v1/routes.rs +++ b/packages/axum-http-tracker-server/src/v1/routes.rs @@ -9,7 +9,7 @@ use axum::response::Response; use axum::routing::get; use axum::{BoxError, Router}; use axum_client_ip::SecureClientIpSource; -use bittorrent_http_tracker_core::container::HttpTrackerContainer; +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use hyper::{Request, StatusCode}; use torrust_server_lib::logging::Latency; use torrust_tracker_configuration::DEFAULT_TIMEOUT; @@ -31,7 +31,7 @@ use crate::HTTP_TRACKER_LOG_TARGET; /// > **NOTICE**: it's added a layer to get the client IP from the connection /// > info. The tracker could use the connection info to get the client IP. #[instrument(skip(http_tracker_container, server_socket_addr))] -pub fn router(http_tracker_container: Arc, server_socket_addr: SocketAddr) -> Router { +pub fn router(http_tracker_container: Arc, server_socket_addr: SocketAddr) -> Router { Router::new() // Health check .route("/health_check", get(health_check::handler)) diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index c9945f3b1..5ac82000a 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -9,7 +9,7 @@ use torrust_tracker_configuration::{Core, HttpTracker}; use crate::statistics; -pub struct HttpTrackerContainer { +pub struct HttpTrackerCoreContainer { // todo: replace with TrackerCoreContainer pub core_config: Arc, pub announce_handler: Arc, @@ -22,7 +22,7 @@ pub struct HttpTrackerContainer { pub http_stats_repository: Arc, } -impl HttpTrackerContainer { +impl HttpTrackerCoreContainer { #[must_use] pub fn initialize_from( tracker_core_container: &Arc, diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 6a8c6d84c..013031395 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -14,7 +14,7 @@ use std::net::SocketAddr; use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; -use bittorrent_http_tracker_core::container::HttpTrackerContainer; +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use tokio::task::JoinHandle; use torrust_axum_http_tracker_server::server::{HttpServer, Launcher}; use torrust_axum_http_tracker_server::Version; @@ -32,7 +32,7 @@ use tracing::instrument; /// It would panic if the `config::HttpTracker` struct would contain inappropriate values. #[instrument(skip(http_tracker_container, form))] pub async fn start_job( - http_tracker_container: Arc, + http_tracker_container: Arc, form: ServiceRegistrationForm, version: Version, ) -> Option> { @@ -52,7 +52,7 @@ pub async fn start_job( async fn start_v1( socket: SocketAddr, tls: Option, - http_tracker_container: Arc, + http_tracker_container: Arc, form: ServiceRegistrationForm, ) -> JoinHandle<()> { let server = HttpServer::new(Launcher::new(socket, tls)) @@ -77,7 +77,7 @@ async fn start_v1( mod tests { use std::sync::Arc; - use bittorrent_http_tracker_core::container::HttpTrackerContainer; + use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use torrust_axum_http_tracker_server::Version; use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; @@ -94,7 +94,7 @@ mod tests { initialize_global_services(&cfg); - let http_tracker_container = HttpTrackerContainer::initialize(&core_config, &http_tracker_config); + let http_tracker_container = HttpTrackerCoreContainer::initialize(&core_config, &http_tracker_config); let version = Version::V1; diff --git a/src/container.rs b/src/container.rs index 5d76a20f3..b8e2c5d9a 100644 --- a/src/container.rs +++ b/src/container.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use bittorrent_http_tracker_core::container::HttpTrackerContainer; +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::handler::KeysHandler; use bittorrent_tracker_core::authentication::service::AuthenticationService; @@ -44,8 +44,8 @@ pub struct AppContainer { impl AppContainer { #[must_use] - pub fn http_tracker_container(&self, http_tracker_config: &Arc) -> HttpTrackerContainer { - HttpTrackerContainer { + pub fn http_tracker_container(&self, http_tracker_config: &Arc) -> HttpTrackerCoreContainer { + HttpTrackerCoreContainer { core_config: self.core_config.clone(), announce_handler: self.announce_handler.clone(), scrape_handler: self.scrape_handler.clone(), diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index 209430d25..e77cc38aa 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use bittorrent_http_tracker_core::container::HttpTrackerContainer; +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::container::TrackerCoreContainer; use futures::executor::block_on; @@ -35,10 +35,10 @@ impl Environment { let container = Arc::new(EnvContainer::initialize(configuration)); - let bind_to = container.http_tracker_container.http_tracker_config.bind_address; + let bind_to = container.http_tracker_core_container.http_tracker_config.bind_address; let tls = block_on(make_rust_tls( - &container.http_tracker_container.http_tracker_config.tsl_config, + &container.http_tracker_core_container.http_tracker_config.tsl_config, )) .map(|tls| tls.expect("tls config failed")); @@ -58,7 +58,7 @@ impl Environment { registar: self.registar.clone(), server: self .server - .start(self.container.http_tracker_container.clone(), self.registar.give_form()) + .start(self.container.http_tracker_core_container.clone(), self.registar.give_form()) .await .unwrap(), } @@ -85,7 +85,7 @@ impl Environment { pub struct EnvContainer { pub tracker_core_container: Arc, - pub http_tracker_container: Arc, + pub http_tracker_core_container: Arc, } impl EnvContainer { @@ -98,11 +98,11 @@ impl EnvContainer { let http_tracker_config = Arc::new(http_tracker_config[0].clone()); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); - let http_tracker_container = HttpTrackerContainer::initialize_from(&tracker_core_container, &http_tracker_config); + let http_tracker_container = HttpTrackerCoreContainer::initialize_from(&tracker_core_container, &http_tracker_config); Self { tracker_core_container, - http_tracker_container, + http_tracker_core_container: http_tracker_container, } } } diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index d7a09cd2d..084766593 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -680,7 +680,12 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; + let stats = env + .container + .http_tracker_core_container + .http_stats_repository + .get_stats() + .await; assert_eq!(stats.tcp4_connections_handled, 1); @@ -706,7 +711,12 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; + let stats = env + .container + .http_tracker_core_container + .http_stats_repository + .get_stats() + .await; assert_eq!(stats.tcp6_connections_handled, 1); @@ -731,7 +741,12 @@ mod for_all_config_modes { ) .await; - let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; + let stats = env + .container + .http_tracker_core_container + .http_stats_repository + .get_stats() + .await; assert_eq!(stats.tcp6_connections_handled, 0); @@ -750,7 +765,12 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; + let stats = env + .container + .http_tracker_core_container + .http_stats_repository + .get_stats() + .await; assert_eq!(stats.tcp4_announces_handled, 1); @@ -776,7 +796,12 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; + let stats = env + .container + .http_tracker_core_container + .http_stats_repository + .get_stats() + .await; assert_eq!(stats.tcp6_announces_handled, 1); @@ -801,7 +826,12 @@ mod for_all_config_modes { ) .await; - let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; + let stats = env + .container + .http_tracker_core_container + .http_stats_repository + .get_stats() + .await; assert_eq!(stats.tcp6_announces_handled, 0); @@ -1189,7 +1219,12 @@ mod for_all_config_modes { ) .await; - let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; + let stats = env + .container + .http_tracker_core_container + .http_stats_repository + .get_stats() + .await; assert_eq!(stats.tcp4_scrapes_handled, 1); @@ -1221,7 +1256,12 @@ mod for_all_config_modes { ) .await; - let stats = env.container.http_tracker_container.http_stats_repository.get_stats().await; + let stats = env + .container + .http_tracker_core_container + .http_stats_repository + .get_stats() + .await; assert_eq!(stats.tcp6_scrapes_handled, 1); From 786000bc3ac4b1c88d57c3cc1a65c113f00fdb1f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 16:07:36 +0000 Subject: [PATCH 0802/1297] refactor: [#1298] remove duplicate code --- packages/http-tracker-core/src/container.rs | 31 ++++----------------- 1 file changed, 6 insertions(+), 25 deletions(-) diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 5ac82000a..0fc313a38 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -23,49 +23,30 @@ pub struct HttpTrackerCoreContainer { } impl HttpTrackerCoreContainer { + #[must_use] + pub fn initialize(core_config: &Arc, http_tracker_config: &Arc) -> Arc { + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(core_config)); + Self::initialize_from(&tracker_core_container, http_tracker_config) + } + #[must_use] pub fn initialize_from( tracker_core_container: &Arc, http_tracker_config: &Arc, ) -> Arc { - // HTTP stats let (http_stats_event_sender, http_stats_repository) = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); let http_stats_repository = Arc::new(http_stats_repository); Arc::new(Self { - http_tracker_config: http_tracker_config.clone(), - core_config: tracker_core_container.core_config.clone(), announce_handler: tracker_core_container.announce_handler.clone(), scrape_handler: tracker_core_container.scrape_handler.clone(), whitelist_authorization: tracker_core_container.whitelist_authorization.clone(), authentication_service: tracker_core_container.authentication_service.clone(), - http_stats_event_sender: http_stats_event_sender.clone(), - http_stats_repository: http_stats_repository.clone(), - }) - } - - #[must_use] - pub fn initialize(core_config: &Arc, http_tracker_config: &Arc) -> Arc { - let tracker_core_container = TrackerCoreContainer::initialize(core_config); - - // HTTP stats - let (http_stats_event_sender, http_stats_repository) = statistics::setup::factory(core_config.tracker_usage_statistics); - let http_stats_event_sender = Arc::new(http_stats_event_sender); - let http_stats_repository = Arc::new(http_stats_repository); - - Arc::new(Self { http_tracker_config: http_tracker_config.clone(), - - core_config: core_config.clone(), - announce_handler: tracker_core_container.announce_handler.clone(), - scrape_handler: tracker_core_container.scrape_handler.clone(), - whitelist_authorization: tracker_core_container.whitelist_authorization.clone(), - authentication_service: tracker_core_container.authentication_service.clone(), - http_stats_event_sender: http_stats_event_sender.clone(), http_stats_repository: http_stats_repository.clone(), }) From de75a3267dc1d33e8fcf522e532ce1da580209eb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 16:14:59 +0000 Subject: [PATCH 0803/1297] refactor: [#1298] move UdpTrackerContainer to udp-tracker-core package --- packages/udp-tracker-core/src/container.rs | 45 ++++++++++++++++++++++ packages/udp-tracker-core/src/lib.rs | 1 + src/bootstrap/jobs/udp_tracker.rs | 2 +- src/container.rs | 38 ++---------------- src/servers/udp/handlers/mod.rs | 2 +- src/servers/udp/server/launcher.rs | 2 +- src/servers/udp/server/mod.rs | 2 +- src/servers/udp/server/processor.rs | 2 +- src/servers/udp/server/spawner.rs | 2 +- src/servers/udp/server/states.rs | 2 +- tests/servers/udp/environment.rs | 2 +- 11 files changed, 57 insertions(+), 43 deletions(-) create mode 100644 packages/udp-tracker-core/src/container.rs diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs new file mode 100644 index 000000000..51ae6e40c --- /dev/null +++ b/packages/udp-tracker-core/src/container.rs @@ -0,0 +1,45 @@ +use std::sync::Arc; + +use bittorrent_tracker_core::announce_handler::AnnounceHandler; +use bittorrent_tracker_core::container::TrackerCoreContainer; +use bittorrent_tracker_core::scrape_handler::ScrapeHandler; +use bittorrent_tracker_core::whitelist; +use tokio::sync::RwLock; +use torrust_tracker_configuration::{Core, UdpTracker}; + +use crate::services::banning::BanService; +use crate::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; + +pub struct UdpTrackerContainer { + pub core_config: Arc, + pub udp_tracker_config: Arc, + pub announce_handler: Arc, + pub scrape_handler: Arc, + pub whitelist_authorization: Arc, + pub udp_stats_event_sender: Arc>>, + pub ban_service: Arc>, +} + +#[must_use] +pub fn initialize_udt_tracker_container( + core_config: &Arc, + udp_tracker_config: &Arc, +) -> Arc { + let tracker_core_container = TrackerCoreContainer::initialize(core_config); + + // UDP stats + let (udp_stats_event_sender, _udp_stats_repository) = statistics::setup::factory(core_config.tracker_usage_statistics); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + + Arc::new(UdpTrackerContainer { + udp_tracker_config: udp_tracker_config.clone(), + core_config: core_config.clone(), + announce_handler: tracker_core_container.announce_handler.clone(), + scrape_handler: tracker_core_container.scrape_handler.clone(), + whitelist_authorization: tracker_core_container.whitelist_authorization.clone(), + udp_stats_event_sender: udp_stats_event_sender.clone(), + ban_service: ban_service.clone(), + }) +} diff --git a/packages/udp-tracker-core/src/lib.rs b/packages/udp-tracker-core/src/lib.rs index 8283e08c5..f649cbeaf 100644 --- a/packages/udp-tracker-core/src/lib.rs +++ b/packages/udp-tracker-core/src/lib.rs @@ -1,4 +1,5 @@ pub mod connection_cookie; +pub mod container; pub mod crypto; pub mod services; pub mod statistics; diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index c97e239ce..8a2fc4412 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -8,12 +8,12 @@ //! > for the configuration options. use std::sync::Arc; +use bittorrent_udp_tracker_core::container::UdpTrackerContainer; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use tokio::task::JoinHandle; use torrust_server_lib::registar::ServiceRegistrationForm; use tracing::instrument; -use crate::container::UdpTrackerContainer; use crate::servers::udp::server::spawner::Spawner; use crate::servers::udp::server::Server; diff --git a/src/container.rs b/src/container.rs index b8e2c5d9a..ee26247f7 100644 --- a/src/container.rs +++ b/src/container.rs @@ -13,6 +13,7 @@ use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentT use bittorrent_tracker_core::whitelist; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use bittorrent_udp_tracker_core::container::UdpTrackerContainer; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; @@ -33,9 +34,11 @@ pub struct AppContainer { pub in_memory_torrent_repository: Arc, pub db_torrent_repository: Arc, pub torrents_manager: Arc, + // UDP Tracker Core Services pub ban_service: Arc>, pub udp_stats_event_sender: Arc>>, + // HTTP Tracker Core Services pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, @@ -86,16 +89,6 @@ impl AppContainer { } } -pub struct UdpTrackerContainer { - pub core_config: Arc, - pub udp_tracker_config: Arc, - pub announce_handler: Arc, - pub scrape_handler: Arc, - pub whitelist_authorization: Arc, - pub udp_stats_event_sender: Arc>>, - pub ban_service: Arc>, -} - pub struct HttpApiContainer { pub core_config: Arc, pub http_api_config: Arc, @@ -176,28 +169,3 @@ pub fn initialize_http_api_container(core_config: &Arc, http_api_config: & udp_stats_repository: udp_stats_repository.clone(), }) } - -#[must_use] -pub fn initialize_udt_tracker_container( - core_config: &Arc, - udp_tracker_config: &Arc, -) -> Arc { - let tracker_core_container = TrackerCoreContainer::initialize(core_config); - - // UDP stats - let (udp_stats_event_sender, _udp_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - - Arc::new(UdpTrackerContainer { - udp_tracker_config: udp_tracker_config.clone(), - core_config: core_config.clone(), - announce_handler: tracker_core_container.announce_handler.clone(), - scrape_handler: tracker_core_container.scrape_handler.clone(), - whitelist_authorization: tracker_core_container.whitelist_authorization.clone(), - udp_stats_event_sender: udp_stats_event_sender.clone(), - ban_service: ban_service.clone(), - }) -} diff --git a/src/servers/udp/handlers/mod.rs b/src/servers/udp/handlers/mod.rs index 3d378b525..08959be35 100644 --- a/src/servers/udp/handlers/mod.rs +++ b/src/servers/udp/handlers/mod.rs @@ -11,6 +11,7 @@ use std::time::Instant; use announce::handle_announce; use aquatic_udp_protocol::{Request, Response, TransactionId}; +use bittorrent_udp_tracker_core::container::UdpTrackerContainer; use bittorrent_udp_tracker_core::services::announce::UdpAnnounceError; use connect::handle_connect; use error::handle_error; @@ -20,7 +21,6 @@ use tracing::{instrument, Level}; use uuid::Uuid; use super::RawRequest; -use crate::container::UdpTrackerContainer; use crate::servers::udp::error::Error; use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; use crate::CurrentClock; diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index dbf0d5693..d180d121c 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use std::time::Duration; use bittorrent_tracker_client::udp::client::check; +use bittorrent_udp_tracker_core::container::UdpTrackerContainer; use bittorrent_udp_tracker_core::{self, statistics, UDP_TRACKER_LOG_TARGET}; use derive_more::Constructor; use futures_util::StreamExt; @@ -15,7 +16,6 @@ use torrust_server_lib::signals::{shutdown_signal_with_message, Halted, Started} use tracing::instrument; use super::request_buffer::ActiveRequests; -use crate::container::UdpTrackerContainer; use crate::servers::udp::server::bound_socket::BoundSocket; use crate::servers::udp::server::processor::Processor; use crate::servers::udp::server::receiver::Receiver; diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index 8e14bc8be..e4b3297c7 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -57,13 +57,13 @@ mod tests { use std::sync::Arc; use std::time::Duration; + use bittorrent_udp_tracker_core::container::initialize_udt_tracker_container; use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; use super::spawner::Spawner; use super::Server; use crate::bootstrap::app::initialize_global_services; - use crate::container::initialize_udt_tracker_container; #[tokio::test] async fn it_should_be_able_to_start_and_stop() { diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index af4c68770..21679a6fc 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -4,12 +4,12 @@ use std::sync::Arc; use std::time::Duration; use aquatic_udp_protocol::Response; +use bittorrent_udp_tracker_core::container::UdpTrackerContainer; use bittorrent_udp_tracker_core::{self, statistics}; use tokio::time::Instant; use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; -use crate::container::UdpTrackerContainer; use crate::servers::udp::handlers::CookieTimeValues; use crate::servers::udp::{handlers, RawRequest}; diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index fd85a57c9..30acd36e9 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -3,6 +3,7 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; +use bittorrent_udp_tracker_core::container::UdpTrackerContainer; use derive_more::derive::Display; use derive_more::Constructor; use tokio::sync::oneshot; @@ -10,7 +11,6 @@ use tokio::task::JoinHandle; use torrust_server_lib::signals::{Halted, Started}; use super::launcher::Launcher; -use crate::container::UdpTrackerContainer; #[derive(Constructor, Copy, Clone, Debug, Display)] #[display("(with socket): {bind_to}")] diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index ae499acf7..4923d90b0 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -3,6 +3,7 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; +use bittorrent_udp_tracker_core::container::UdpTrackerContainer; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use derive_more::derive::Display; use derive_more::Constructor; @@ -13,7 +14,6 @@ use tracing::{instrument, Level}; use super::spawner::Spawner; use super::{Server, UdpError}; -use crate::container::UdpTrackerContainer; use crate::servers::udp::server::launcher::Launcher; /// A UDP server instance controller with no UDP instance running. diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 241623732..e3d354ee4 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -10,13 +10,13 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use bittorrent_udp_tracker_core::container::UdpTrackerContainer; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{Configuration, Core, UdpTracker, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::initialize_global_services; -use torrust_tracker_lib::container::UdpTrackerContainer; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; use torrust_tracker_lib::servers::udp::server::Server; From 5c1fd97093f82d347972b93e72c76a7eff772a4a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 16:17:15 +0000 Subject: [PATCH 0804/1297] refactor: [#1298] rename struct to UdpTrackerCoreContainer --- packages/udp-tracker-core/src/container.rs | 7 +++---- src/bootstrap/jobs/udp_tracker.rs | 4 ++-- src/container.rs | 6 +++--- src/servers/udp/handlers/mod.rs | 6 +++--- src/servers/udp/server/launcher.rs | 6 +++--- src/servers/udp/server/processor.rs | 6 +++--- src/servers/udp/server/spawner.rs | 4 ++-- src/servers/udp/server/states.rs | 4 ++-- tests/servers/udp/environment.rs | 22 +++++++++++----------- 9 files changed, 32 insertions(+), 33 deletions(-) diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index 51ae6e40c..e7b01835b 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -10,7 +10,7 @@ use torrust_tracker_configuration::{Core, UdpTracker}; use crate::services::banning::BanService; use crate::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; -pub struct UdpTrackerContainer { +pub struct UdpTrackerCoreContainer { pub core_config: Arc, pub udp_tracker_config: Arc, pub announce_handler: Arc, @@ -24,16 +24,15 @@ pub struct UdpTrackerContainer { pub fn initialize_udt_tracker_container( core_config: &Arc, udp_tracker_config: &Arc, -) -> Arc { +) -> Arc { let tracker_core_container = TrackerCoreContainer::initialize(core_config); - // UDP stats let (udp_stats_event_sender, _udp_stats_repository) = statistics::setup::factory(core_config.tracker_usage_statistics); let udp_stats_event_sender = Arc::new(udp_stats_event_sender); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - Arc::new(UdpTrackerContainer { + Arc::new(UdpTrackerCoreContainer { udp_tracker_config: udp_tracker_config.clone(), core_config: core_config.clone(), announce_handler: tracker_core_container.announce_handler.clone(), diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 8a2fc4412..89b2a38be 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -8,7 +8,7 @@ //! > for the configuration options. use std::sync::Arc; -use bittorrent_udp_tracker_core::container::UdpTrackerContainer; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use tokio::task::JoinHandle; use torrust_server_lib::registar::ServiceRegistrationForm; @@ -29,7 +29,7 @@ use crate::servers::udp::server::Server; #[must_use] #[allow(clippy::async_yields_async)] #[instrument(skip(udp_tracker_container, form))] -pub async fn start_job(udp_tracker_container: Arc, form: ServiceRegistrationForm) -> JoinHandle<()> { +pub async fn start_job(udp_tracker_container: Arc, form: ServiceRegistrationForm) -> JoinHandle<()> { let bind_to = udp_tracker_container.udp_tracker_config.bind_address; let cookie_lifetime = udp_tracker_container.udp_tracker_config.cookie_lifetime; diff --git a/src/container.rs b/src/container.rs index ee26247f7..921c1624f 100644 --- a/src/container.rs +++ b/src/container.rs @@ -13,7 +13,7 @@ use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentT use bittorrent_tracker_core::whitelist; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; -use bittorrent_udp_tracker_core::container::UdpTrackerContainer; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; @@ -62,8 +62,8 @@ impl AppContainer { } #[must_use] - pub fn udp_tracker_container(&self, udp_tracker_config: &Arc) -> UdpTrackerContainer { - UdpTrackerContainer { + pub fn udp_tracker_container(&self, udp_tracker_config: &Arc) -> UdpTrackerCoreContainer { + UdpTrackerCoreContainer { udp_tracker_config: udp_tracker_config.clone(), core_config: self.core_config.clone(), announce_handler: self.announce_handler.clone(), diff --git a/src/servers/udp/handlers/mod.rs b/src/servers/udp/handlers/mod.rs index 08959be35..bc876bced 100644 --- a/src/servers/udp/handlers/mod.rs +++ b/src/servers/udp/handlers/mod.rs @@ -11,7 +11,7 @@ use std::time::Instant; use announce::handle_announce; use aquatic_udp_protocol::{Request, Response, TransactionId}; -use bittorrent_udp_tracker_core::container::UdpTrackerContainer; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::announce::UdpAnnounceError; use connect::handle_connect; use error::handle_error; @@ -55,7 +55,7 @@ impl CookieTimeValues { #[instrument(fields(request_id), skip(udp_request, udp_tracker_container, cookie_time_values), ret(level = Level::TRACE))] pub(crate) async fn handle_packet( udp_request: RawRequest, - udp_tracker_container: Arc, + udp_tracker_container: Arc, local_addr: SocketAddr, cookie_time_values: CookieTimeValues, ) -> Response { @@ -128,7 +128,7 @@ pub(crate) async fn handle_packet( pub async fn handle_request( request: Request, remote_addr: SocketAddr, - udp_tracker_container: Arc, + udp_tracker_container: Arc, cookie_time_values: CookieTimeValues, ) -> Result { tracing::trace!("handle request"); diff --git a/src/servers/udp/server/launcher.rs b/src/servers/udp/server/launcher.rs index d180d121c..d66ad8d37 100644 --- a/src/servers/udp/server/launcher.rs +++ b/src/servers/udp/server/launcher.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use std::time::Duration; use bittorrent_tracker_client::udp::client::check; -use bittorrent_udp_tracker_core::container::UdpTrackerContainer; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::{self, statistics, UDP_TRACKER_LOG_TARGET}; use derive_more::Constructor; use futures_util::StreamExt; @@ -36,7 +36,7 @@ impl Launcher { /// It panics if the udp server is loaded when the tracker is private. #[instrument(skip(udp_tracker_container, bind_to, tx_start, rx_halt))] pub async fn run_with_graceful_shutdown( - udp_tracker_container: Arc, + udp_tracker_container: Arc, bind_to: SocketAddr, cookie_lifetime: Duration, tx_start: oneshot::Sender, @@ -114,7 +114,7 @@ impl Launcher { #[instrument(skip(receiver, udp_tracker_container))] async fn run_udp_server_main( mut receiver: Receiver, - udp_tracker_container: Arc, + udp_tracker_container: Arc, cookie_lifetime: Duration, ) { let active_requests = &mut ActiveRequests::default(); diff --git a/src/servers/udp/server/processor.rs b/src/servers/udp/server/processor.rs index 21679a6fc..157f3ecfe 100644 --- a/src/servers/udp/server/processor.rs +++ b/src/servers/udp/server/processor.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use std::time::Duration; use aquatic_udp_protocol::Response; -use bittorrent_udp_tracker_core::container::UdpTrackerContainer; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::{self, statistics}; use tokio::time::Instant; use tracing::{instrument, Level}; @@ -15,12 +15,12 @@ use crate::servers::udp::{handlers, RawRequest}; pub struct Processor { socket: Arc, - udp_tracker_container: Arc, + udp_tracker_container: Arc, cookie_lifetime: f64, } impl Processor { - pub fn new(socket: Arc, udp_tracker_container: Arc, cookie_lifetime: f64) -> Self { + pub fn new(socket: Arc, udp_tracker_container: Arc, cookie_lifetime: f64) -> Self { Self { socket, udp_tracker_container, diff --git a/src/servers/udp/server/spawner.rs b/src/servers/udp/server/spawner.rs index 30acd36e9..6c1f9a48e 100644 --- a/src/servers/udp/server/spawner.rs +++ b/src/servers/udp/server/spawner.rs @@ -3,7 +3,7 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; -use bittorrent_udp_tracker_core::container::UdpTrackerContainer; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use derive_more::derive::Display; use derive_more::Constructor; use tokio::sync::oneshot; @@ -27,7 +27,7 @@ impl Spawner { #[must_use] pub fn spawn_launcher( &self, - udp_tracker_container: Arc, + udp_tracker_container: Arc, cookie_lifetime: Duration, tx_start: oneshot::Sender, rx_halt: oneshot::Receiver, diff --git a/src/servers/udp/server/states.rs b/src/servers/udp/server/states.rs index 4923d90b0..3501aebf1 100644 --- a/src/servers/udp/server/states.rs +++ b/src/servers/udp/server/states.rs @@ -3,7 +3,7 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; -use bittorrent_udp_tracker_core::container::UdpTrackerContainer; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use derive_more::derive::Display; use derive_more::Constructor; @@ -63,7 +63,7 @@ impl Server { #[instrument(skip(self, udp_tracker_container, form), err, ret(Display, level = Level::INFO))] pub async fn start( self, - udp_tracker_container: Arc, + udp_tracker_container: Arc, form: ServiceRegistrationForm, cookie_lifetime: Duration, ) -> Result, std::io::Error> { diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index e3d354ee4..47260fedb 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -10,7 +10,7 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; -use bittorrent_udp_tracker_core::container::UdpTrackerContainer; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; @@ -26,7 +26,7 @@ pub struct Environment where S: std::fmt::Debug + std::fmt::Display, { - pub udp_tracker_container: Arc, + pub udp_tracker_container: Arc, pub database: Arc>, pub in_memory_torrent_repository: Arc, @@ -58,14 +58,14 @@ impl Environment { let server = Server::new(Spawner::new(bind_to)); - let udp_tracker_container = Arc::new(UdpTrackerContainer { + let udp_tracker_container = Arc::new(UdpTrackerCoreContainer { udp_tracker_config: env_container.udp_tracker_config.clone(), core_config: env_container.core_config.clone(), - announce_handler: env_container.udp_tracker_container.announce_handler.clone(), - scrape_handler: env_container.udp_tracker_container.scrape_handler.clone(), - whitelist_authorization: env_container.udp_tracker_container.whitelist_authorization.clone(), - udp_stats_event_sender: env_container.udp_tracker_container.udp_stats_event_sender.clone(), - ban_service: env_container.udp_tracker_container.ban_service.clone(), + announce_handler: env_container.udp_tracker_core_container.announce_handler.clone(), + scrape_handler: env_container.udp_tracker_core_container.scrape_handler.clone(), + whitelist_authorization: env_container.udp_tracker_core_container.whitelist_authorization.clone(), + udp_stats_event_sender: env_container.udp_tracker_core_container.udp_stats_event_sender.clone(), + ban_service: env_container.udp_tracker_core_container.ban_service.clone(), }); Self { @@ -134,7 +134,7 @@ impl Environment { pub struct EnvContainer { pub core_config: Arc, pub udp_tracker_config: Arc, - pub udp_tracker_container: Arc, + pub udp_tracker_core_container: Arc, pub database: Arc>, pub in_memory_torrent_repository: Arc, @@ -169,7 +169,7 @@ impl EnvContainer { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - let udp_tracker_container = Arc::new(UdpTrackerContainer { + let udp_tracker_container = Arc::new(UdpTrackerCoreContainer { udp_tracker_config: udp_tracker_config.clone(), core_config: core_config.clone(), announce_handler: announce_handler.clone(), @@ -182,7 +182,7 @@ impl EnvContainer { Self { core_config, udp_tracker_config, - udp_tracker_container, + udp_tracker_core_container: udp_tracker_container, database, in_memory_torrent_repository, From 292a7ebe105d5d5339e7bfd1b8dc7451768048f6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 16:28:03 +0000 Subject: [PATCH 0805/1297] refactor: [#1298] convert fn into static method --- packages/udp-tracker-core/src/container.rs | 57 +++++++++++++--------- src/container.rs | 4 +- src/servers/udp/server/mod.rs | 6 +-- tests/servers/udp/environment.rs | 8 ++- 4 files changed, 47 insertions(+), 28 deletions(-) diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index e7b01835b..62378e0af 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -11,34 +11,47 @@ use crate::services::banning::BanService; use crate::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; pub struct UdpTrackerCoreContainer { + // todo: replace with TrackerCoreContainer pub core_config: Arc, - pub udp_tracker_config: Arc, pub announce_handler: Arc, pub scrape_handler: Arc, pub whitelist_authorization: Arc, + + pub udp_tracker_config: Arc, pub udp_stats_event_sender: Arc>>, + pub udp_stats_repository: Arc, pub ban_service: Arc>, } -#[must_use] -pub fn initialize_udt_tracker_container( - core_config: &Arc, - udp_tracker_config: &Arc, -) -> Arc { - let tracker_core_container = TrackerCoreContainer::initialize(core_config); - - let (udp_stats_event_sender, _udp_stats_repository) = statistics::setup::factory(core_config.tracker_usage_statistics); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - - Arc::new(UdpTrackerCoreContainer { - udp_tracker_config: udp_tracker_config.clone(), - core_config: core_config.clone(), - announce_handler: tracker_core_container.announce_handler.clone(), - scrape_handler: tracker_core_container.scrape_handler.clone(), - whitelist_authorization: tracker_core_container.whitelist_authorization.clone(), - udp_stats_event_sender: udp_stats_event_sender.clone(), - ban_service: ban_service.clone(), - }) +impl UdpTrackerCoreContainer { + #[must_use] + pub fn initialize(core_config: &Arc, udp_tracker_config: &Arc) -> Arc { + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(core_config)); + Self::initialize_from(&tracker_core_container, udp_tracker_config) + } + + #[must_use] + pub fn initialize_from( + tracker_core_container: &Arc, + udp_tracker_config: &Arc, + ) -> Arc { + let (udp_stats_event_sender, udp_stats_repository) = + statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let udp_stats_repository = Arc::new(udp_stats_repository); + + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + + Arc::new(UdpTrackerCoreContainer { + core_config: tracker_core_container.core_config.clone(), + announce_handler: tracker_core_container.announce_handler.clone(), + scrape_handler: tracker_core_container.scrape_handler.clone(), + whitelist_authorization: tracker_core_container.whitelist_authorization.clone(), + + udp_tracker_config: udp_tracker_config.clone(), + udp_stats_event_sender: udp_stats_event_sender.clone(), + udp_stats_repository: udp_stats_repository.clone(), + ban_service: ban_service.clone(), + }) + } } diff --git a/src/container.rs b/src/container.rs index 921c1624f..e61d070d6 100644 --- a/src/container.rs +++ b/src/container.rs @@ -64,12 +64,14 @@ impl AppContainer { #[must_use] pub fn udp_tracker_container(&self, udp_tracker_config: &Arc) -> UdpTrackerCoreContainer { UdpTrackerCoreContainer { - udp_tracker_config: udp_tracker_config.clone(), core_config: self.core_config.clone(), announce_handler: self.announce_handler.clone(), scrape_handler: self.scrape_handler.clone(), whitelist_authorization: self.whitelist_authorization.clone(), + + udp_tracker_config: udp_tracker_config.clone(), udp_stats_event_sender: self.udp_stats_event_sender.clone(), + udp_stats_repository: self.udp_stats_repository.clone(), ban_service: self.ban_service.clone(), } } diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index e4b3297c7..a328c45ce 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -57,7 +57,7 @@ mod tests { use std::sync::Arc; use std::time::Duration; - use bittorrent_udp_tracker_core::container::initialize_udt_tracker_container; + use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use torrust_server_lib::registar::Registar; use torrust_tracker_test_helpers::configuration::ephemeral_public; @@ -87,7 +87,7 @@ mod tests { let stopped = Server::new(Spawner::new(bind_to)); - let udp_tracker_container = initialize_udt_tracker_container(&core_config, &udp_tracker_config); + let udp_tracker_container = UdpTrackerCoreContainer::initialize(&core_config, &udp_tracker_config); let started = stopped .start(udp_tracker_container, register.give_form(), config.cookie_lifetime) @@ -121,7 +121,7 @@ mod tests { let stopped = Server::new(Spawner::new(bind_to)); - let udp_tracker_container = initialize_udt_tracker_container(&core_config, &udp_tracker_config); + let udp_tracker_container = UdpTrackerCoreContainer::initialize(&core_config, &udp_tracker_config); let started = stopped .start( diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 47260fedb..0b2d1c79c 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -59,12 +59,14 @@ impl Environment { let server = Server::new(Spawner::new(bind_to)); let udp_tracker_container = Arc::new(UdpTrackerCoreContainer { - udp_tracker_config: env_container.udp_tracker_config.clone(), core_config: env_container.core_config.clone(), announce_handler: env_container.udp_tracker_core_container.announce_handler.clone(), scrape_handler: env_container.udp_tracker_core_container.scrape_handler.clone(), whitelist_authorization: env_container.udp_tracker_core_container.whitelist_authorization.clone(), + + udp_tracker_config: env_container.udp_tracker_config.clone(), udp_stats_event_sender: env_container.udp_tracker_core_container.udp_stats_event_sender.clone(), + udp_stats_repository: env_container.udp_tracker_core_container.udp_stats_repository.clone(), ban_service: env_container.udp_tracker_core_container.ban_service.clone(), }); @@ -170,12 +172,14 @@ impl EnvContainer { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); let udp_tracker_container = Arc::new(UdpTrackerCoreContainer { - udp_tracker_config: udp_tracker_config.clone(), core_config: core_config.clone(), announce_handler: announce_handler.clone(), scrape_handler: scrape_handler.clone(), whitelist_authorization: whitelist_authorization.clone(), + + udp_tracker_config: udp_tracker_config.clone(), udp_stats_event_sender: udp_stats_event_sender.clone(), + udp_stats_repository: udp_stats_repository.clone(), ban_service: ban_service.clone(), }); From be05211b02b960974ca2ccb384beb8b809cbc0bb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 16:37:45 +0000 Subject: [PATCH 0806/1297] refactor: [#1298] remove duplicate code --- tests/servers/udp/contract.rs | 18 ++++- tests/servers/udp/environment.rs | 123 ++++++------------------------- 2 files changed, 39 insertions(+), 102 deletions(-) diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index f6e0589f8..f0f647443 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -229,7 +229,7 @@ mod receiving_an_announce_request { logging::setup(); let env = Started::new(&configuration::ephemeral().into()).await; - let ban_service = env.udp_tracker_container.ban_service.clone(); + let ban_service = env.container.udp_tracker_core_container.ban_service.clone(); let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_tracker_client) => udp_tracker_client, @@ -270,7 +270,13 @@ mod receiving_an_announce_request { info_hash, ); - let udp_requests_banned_before = env.udp_stats_repository.get_stats().await.udp_requests_banned; + let udp_requests_banned_before = env + .container + .udp_tracker_core_container + .udp_stats_repository + .get_stats() + .await + .udp_requests_banned; // This should return a timeout error match client.send(announce_request.into()).await { @@ -280,7 +286,13 @@ mod receiving_an_announce_request { assert!(client.receive().await.is_err()); - let udp_requests_banned_after = env.udp_stats_repository.get_stats().await.udp_requests_banned; + let udp_requests_banned_after = env + .container + .udp_tracker_core_container + .udp_stats_repository + .get_stats() + .await + .udp_requests_banned; let udp_banned_ips_total_after = ban_service.read().await.get_banned_ips_total(); // UDP counter for banned requests should be increased by 1 diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 0b2d1c79c..8afaffc15 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -2,20 +2,10 @@ use std::net::SocketAddr; use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; -use bittorrent_tracker_core::announce_handler::AnnounceHandler; -use bittorrent_tracker_core::databases::setup::initialize_database; -use bittorrent_tracker_core::databases::Database; -use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; -use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; -use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; -use bittorrent_udp_tracker_core::services::banning::BanService; -use bittorrent_udp_tracker_core::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; -use tokio::sync::RwLock; use torrust_server_lib::registar::Registar; -use torrust_tracker_configuration::{Configuration, Core, UdpTracker, DEFAULT_TIMEOUT}; +use torrust_tracker_configuration::{Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_lib::bootstrap::app::initialize_global_services; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; @@ -26,12 +16,7 @@ pub struct Environment where S: std::fmt::Debug + std::fmt::Display, { - pub udp_tracker_container: Arc, - - pub database: Arc>, - pub in_memory_torrent_repository: Arc, - pub udp_stats_repository: Arc, - + pub container: Arc, pub registar: Registar, pub server: Server, } @@ -43,7 +28,11 @@ where /// Add a torrent to the tracker #[allow(dead_code)] pub fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let () = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); + let () = self + .container + .tracker_core_container + .in_memory_torrent_repository + .upsert_peer(info_hash, peer); } } @@ -52,31 +41,14 @@ impl Environment { pub fn new(configuration: &Arc) -> Self { initialize_global_services(configuration); - let env_container = EnvContainer::initialize(configuration); + let container = Arc::new(EnvContainer::initialize(configuration)); - let bind_to = env_container.udp_tracker_config.bind_address; + let bind_to = container.udp_tracker_core_container.udp_tracker_config.bind_address; let server = Server::new(Spawner::new(bind_to)); - let udp_tracker_container = Arc::new(UdpTrackerCoreContainer { - core_config: env_container.core_config.clone(), - announce_handler: env_container.udp_tracker_core_container.announce_handler.clone(), - scrape_handler: env_container.udp_tracker_core_container.scrape_handler.clone(), - whitelist_authorization: env_container.udp_tracker_core_container.whitelist_authorization.clone(), - - udp_tracker_config: env_container.udp_tracker_config.clone(), - udp_stats_event_sender: env_container.udp_tracker_core_container.udp_stats_event_sender.clone(), - udp_stats_repository: env_container.udp_tracker_core_container.udp_stats_repository.clone(), - ban_service: env_container.udp_tracker_core_container.ban_service.clone(), - }); - Self { - udp_tracker_container, - - database: env_container.database.clone(), - in_memory_torrent_repository: env_container.in_memory_torrent_repository.clone(), - udp_stats_repository: env_container.udp_stats_repository.clone(), - + container, registar: Registar::default(), server, } @@ -84,19 +56,18 @@ impl Environment { #[allow(dead_code)] pub async fn start(self) -> Environment { - let cookie_lifetime = self.udp_tracker_container.udp_tracker_config.cookie_lifetime; + let cookie_lifetime = self.container.udp_tracker_core_container.udp_tracker_config.cookie_lifetime; Environment { - udp_tracker_container: self.udp_tracker_container.clone(), - - database: self.database.clone(), - in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), - udp_stats_repository: self.udp_stats_repository.clone(), - + container: self.container.clone(), registar: self.registar.clone(), server: self .server - .start(self.udp_tracker_container, self.registar.give_form(), cookie_lifetime) + .start( + self.container.udp_tracker_core_container.clone(), + self.registar.give_form(), + cookie_lifetime, + ) .await .unwrap(), } @@ -117,12 +88,7 @@ impl Environment { .expect("it should stop the environment within the timeout"); Environment { - udp_tracker_container: self.udp_tracker_container, - - database: self.database, - in_memory_torrent_repository: self.in_memory_torrent_repository, - udp_stats_repository: self.udp_stats_repository, - + container: self.container, registar: Registar::default(), server: stopped.expect("it stop the udp tracker service"), } @@ -134,13 +100,8 @@ impl Environment { } pub struct EnvContainer { - pub core_config: Arc, - pub udp_tracker_config: Arc, + pub tracker_core_container: Arc, pub udp_tracker_core_container: Arc, - - pub database: Arc>, - pub in_memory_torrent_repository: Arc, - pub udp_stats_repository: Arc, } impl EnvContainer { @@ -149,48 +110,12 @@ impl EnvContainer { let udp_tracker_configurations = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); - // UDP stats - let (udp_stats_event_sender, udp_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - let udp_stats_repository = Arc::new(udp_stats_repository); - - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let database = initialize_database(&configuration.core); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&configuration.core, &in_memory_whitelist.clone())); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - - let announce_handler = Arc::new(AnnounceHandler::new( - &configuration.core, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - let udp_tracker_container = Arc::new(UdpTrackerCoreContainer { - core_config: core_config.clone(), - announce_handler: announce_handler.clone(), - scrape_handler: scrape_handler.clone(), - whitelist_authorization: whitelist_authorization.clone(), - - udp_tracker_config: udp_tracker_config.clone(), - udp_stats_event_sender: udp_stats_event_sender.clone(), - udp_stats_repository: udp_stats_repository.clone(), - ban_service: ban_service.clone(), - }); + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); + let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from(&tracker_core_container, &udp_tracker_config); Self { - core_config, - udp_tracker_config, - udp_tracker_core_container: udp_tracker_container, - - database, - in_memory_torrent_repository, - udp_stats_repository, + tracker_core_container, + udp_tracker_core_container, } } } From c8ec781290a064f3c976ae4ef95542aed685fb65 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 16:43:26 +0000 Subject: [PATCH 0807/1297] refactor: [#1298] move HttpApiContainer to tracker-api-core package --- packages/tracker-api-core/src/container.rs | 49 +++++++++++++++++++++ packages/tracker-api-core/src/lib.rs | 1 + src/bootstrap/jobs/tracker_apis.rs | 4 +- src/container.rs | 40 +---------------- src/servers/apis/routes.rs | 2 +- src/servers/apis/server.rs | 4 +- src/servers/apis/v1/context/stats/routes.rs | 2 +- src/servers/apis/v1/routes.rs | 2 +- tests/servers/api/environment.rs | 2 +- 9 files changed, 59 insertions(+), 47 deletions(-) create mode 100644 packages/tracker-api-core/src/container.rs diff --git a/packages/tracker-api-core/src/container.rs b/packages/tracker-api-core/src/container.rs new file mode 100644 index 000000000..9a45008cf --- /dev/null +++ b/packages/tracker-api-core/src/container.rs @@ -0,0 +1,49 @@ +use std::sync::Arc; + +use bittorrent_tracker_core::authentication::handler::KeysHandler; +use bittorrent_tracker_core::container::TrackerCoreContainer; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_tracker_core::whitelist::manager::WhitelistManager; +use bittorrent_udp_tracker_core::services::banning::BanService; +use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; +use tokio::sync::RwLock; +use torrust_tracker_configuration::{Core, HttpApi}; + +pub struct HttpApiContainer { + pub core_config: Arc, + pub http_api_config: Arc, + pub in_memory_torrent_repository: Arc, + pub keys_handler: Arc, + pub whitelist_manager: Arc, + pub ban_service: Arc>, + pub http_stats_repository: Arc, + pub udp_stats_repository: Arc, +} + +#[must_use] +pub fn initialize_http_api_container(core_config: &Arc, http_api_config: &Arc) -> Arc { + let tracker_core_container = TrackerCoreContainer::initialize(core_config); + + // HTTP stats + let (_http_stats_event_sender, http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + let http_stats_repository = Arc::new(http_stats_repository); + + // UDP stats + let (_udp_stats_event_sender, udp_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + let udp_stats_repository = Arc::new(udp_stats_repository); + + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + + Arc::new(HttpApiContainer { + http_api_config: http_api_config.clone(), + core_config: core_config.clone(), + in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository.clone(), + keys_handler: tracker_core_container.keys_handler.clone(), + whitelist_manager: tracker_core_container.whitelist_manager.clone(), + ban_service: ban_service.clone(), + http_stats_repository: http_stats_repository.clone(), + udp_stats_repository: udp_stats_repository.clone(), + }) +} diff --git a/packages/tracker-api-core/src/lib.rs b/packages/tracker-api-core/src/lib.rs index 3449ec7b4..ddf1d9afd 100644 --- a/packages/tracker-api-core/src/lib.rs +++ b/packages/tracker-api-core/src/lib.rs @@ -1 +1,2 @@ +pub mod container; pub mod statistics; diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 66152905a..fa32ce925 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -27,10 +27,10 @@ use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::ServiceRegistrationForm; +use torrust_tracker_api_core::container::HttpApiContainer; use torrust_tracker_configuration::AccessTokens; use tracing::instrument; -use crate::container::HttpApiContainer; use crate::servers::apis::server::{ApiServer, Launcher}; use crate::servers::apis::Version; @@ -98,11 +98,11 @@ mod tests { use std::sync::Arc; use torrust_server_lib::registar::Registar; + use torrust_tracker_api_core::container::initialize_http_api_container; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::tracker_apis::start_job; - use crate::container::initialize_http_api_container; use crate::servers::apis::Version; #[tokio::test] diff --git a/src/container.rs b/src/container.rs index e61d070d6..ed9688935 100644 --- a/src/container.rs +++ b/src/container.rs @@ -17,6 +17,7 @@ use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; +use torrust_tracker_api_core::container::HttpApiContainer; use torrust_tracker_configuration::{Configuration, Core, HttpApi, HttpTracker, UdpTracker}; use tracing::instrument; @@ -91,17 +92,6 @@ impl AppContainer { } } -pub struct HttpApiContainer { - pub core_config: Arc, - pub http_api_config: Arc, - pub in_memory_torrent_repository: Arc, - pub keys_handler: Arc, - pub whitelist_manager: Arc, - pub ban_service: Arc>, - pub http_stats_repository: Arc, - pub udp_stats_repository: Arc, -} - /// It initializes the IoC Container. #[instrument(skip())] pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { @@ -143,31 +133,3 @@ pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { udp_stats_repository, } } - -#[must_use] -pub fn initialize_http_api_container(core_config: &Arc, http_api_config: &Arc) -> Arc { - let tracker_core_container = TrackerCoreContainer::initialize(core_config); - - // HTTP stats - let (_http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); - let http_stats_repository = Arc::new(http_stats_repository); - - // UDP stats - let (_udp_stats_event_sender, udp_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); - let udp_stats_repository = Arc::new(udp_stats_repository); - - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - - Arc::new(HttpApiContainer { - http_api_config: http_api_config.clone(), - core_config: core_config.clone(), - in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository.clone(), - keys_handler: tracker_core_container.keys_handler.clone(), - whitelist_manager: tracker_core_container.whitelist_manager.clone(), - ban_service: ban_service.clone(), - http_stats_repository: http_stats_repository.clone(), - udp_stats_repository: udp_stats_repository.clone(), - }) -} diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index f21c59207..558d02913 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -16,6 +16,7 @@ use axum::routing::get; use axum::{middleware, BoxError, Router}; use hyper::{Request, StatusCode}; use torrust_server_lib::logging::Latency; +use torrust_tracker_api_core::container::HttpApiContainer; use torrust_tracker_configuration::{AccessTokens, DEFAULT_TIMEOUT}; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; @@ -30,7 +31,6 @@ use tracing::{instrument, Level, Span}; use super::v1; use super::v1::context::health_check::handlers::health_check_handler; use super::v1::middlewares::auth::State; -use crate::container::HttpApiContainer; use crate::servers::apis::API_LOG_TARGET; /// Add all API routes to the router. diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 42f16ab77..637ec3b2b 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -38,11 +38,11 @@ use torrust_axum_server::signals::graceful_shutdown; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use torrust_server_lib::signals::{Halted, Started}; +use torrust_tracker_api_core::container::HttpApiContainer; use torrust_tracker_configuration::AccessTokens; use tracing::{instrument, Level}; use super::routes::router; -use crate::container::HttpApiContainer; use crate::servers::apis::API_LOG_TARGET; /// Errors that can occur when starting or stopping the API server. @@ -296,10 +296,10 @@ mod tests { use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; + use torrust_tracker_api_core::container::initialize_http_api_container; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::initialize_global_services; - use crate::container::initialize_http_api_container; use crate::servers::apis::server::{ApiServer, Launcher}; #[tokio::test] diff --git a/src/servers/apis/v1/context/stats/routes.rs b/src/servers/apis/v1/context/stats/routes.rs index e660005ec..aa723f7ec 100644 --- a/src/servers/apis/v1/context/stats/routes.rs +++ b/src/servers/apis/v1/context/stats/routes.rs @@ -7,9 +7,9 @@ use std::sync::Arc; use axum::routing::get; use axum::Router; +use torrust_tracker_api_core::container::HttpApiContainer; use super::handlers::get_stats_handler; -use crate::container::HttpApiContainer; /// It adds the routes to the router for the [`stats`](crate::servers::apis::v1::context::stats) API context. pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs index e593cb140..7ea01c685 100644 --- a/src/servers/apis/v1/routes.rs +++ b/src/servers/apis/v1/routes.rs @@ -2,9 +2,9 @@ use std::sync::Arc; use axum::Router; +use torrust_tracker_api_core::container::HttpApiContainer; use super::context::{auth_key, stats, torrent, whitelist}; -use crate::container::HttpApiContainer; /// Add the routes for the v1 API. pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 7cf088568..066ad6fff 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -18,9 +18,9 @@ use tokio::sync::RwLock; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; +use torrust_tracker_api_core::container::HttpApiContainer; use torrust_tracker_configuration::{Configuration, HttpApi}; use torrust_tracker_lib::bootstrap::app::initialize_global_services; -use torrust_tracker_lib::container::HttpApiContainer; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_primitives::peer; From 3052ebe2d4bb9e1fbbe4502ac4355ee99071c393 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 16:48:31 +0000 Subject: [PATCH 0808/1297] refactor: [#1298] convert fn into static method --- packages/tracker-api-core/src/container.rs | 46 +++++++++++----------- src/bootstrap/jobs/tracker_apis.rs | 4 +- src/servers/apis/server.rs | 4 +- 3 files changed, 28 insertions(+), 26 deletions(-) diff --git a/packages/tracker-api-core/src/container.rs b/packages/tracker-api-core/src/container.rs index 9a45008cf..6dd2d80b1 100644 --- a/packages/tracker-api-core/src/container.rs +++ b/packages/tracker-api-core/src/container.rs @@ -20,30 +20,32 @@ pub struct HttpApiContainer { pub udp_stats_repository: Arc, } -#[must_use] -pub fn initialize_http_api_container(core_config: &Arc, http_api_config: &Arc) -> Arc { - let tracker_core_container = TrackerCoreContainer::initialize(core_config); +impl HttpApiContainer { + #[must_use] + pub fn initialize(core_config: &Arc, http_api_config: &Arc) -> Arc { + let tracker_core_container = TrackerCoreContainer::initialize(core_config); - // HTTP stats - let (_http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); - let http_stats_repository = Arc::new(http_stats_repository); + // HTTP stats + let (_http_stats_event_sender, http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + let http_stats_repository = Arc::new(http_stats_repository); - // UDP stats - let (_udp_stats_event_sender, udp_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); - let udp_stats_repository = Arc::new(udp_stats_repository); + // UDP stats + let (_udp_stats_event_sender, udp_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + let udp_stats_repository = Arc::new(udp_stats_repository); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - Arc::new(HttpApiContainer { - http_api_config: http_api_config.clone(), - core_config: core_config.clone(), - in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository.clone(), - keys_handler: tracker_core_container.keys_handler.clone(), - whitelist_manager: tracker_core_container.whitelist_manager.clone(), - ban_service: ban_service.clone(), - http_stats_repository: http_stats_repository.clone(), - udp_stats_repository: udp_stats_repository.clone(), - }) + Arc::new(HttpApiContainer { + http_api_config: http_api_config.clone(), + core_config: core_config.clone(), + in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository.clone(), + keys_handler: tracker_core_container.keys_handler.clone(), + whitelist_manager: tracker_core_container.whitelist_manager.clone(), + ban_service: ban_service.clone(), + http_stats_repository: http_stats_repository.clone(), + udp_stats_repository: udp_stats_repository.clone(), + }) + } } diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index fa32ce925..82dcccb00 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -98,7 +98,7 @@ mod tests { use std::sync::Arc; use torrust_server_lib::registar::Registar; - use torrust_tracker_api_core::container::initialize_http_api_container; + use torrust_tracker_api_core::container::HttpApiContainer; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::initialize_global_services; @@ -113,7 +113,7 @@ mod tests { initialize_global_services(&cfg); - let http_api_container = initialize_http_api_container(&core_config, &http_api_config); + let http_api_container = HttpApiContainer::initialize(&core_config, &http_api_config); let version = Version::V1; diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 637ec3b2b..20e350d78 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -296,7 +296,7 @@ mod tests { use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; - use torrust_tracker_api_core::container::initialize_http_api_container; + use torrust_tracker_api_core::container::HttpApiContainer; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::initialize_global_services; @@ -322,7 +322,7 @@ mod tests { let register = &Registar::default(); - let http_api_container = initialize_http_api_container(&core_config, &http_api_config); + let http_api_container = HttpApiContainer::initialize(&core_config, &http_api_config); let started = stopped .start(http_api_container, register.give_form(), access_tokens) From 3ce6fb21a4ae9d267d788193a4696c7add0276eb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 16:57:43 +0000 Subject: [PATCH 0809/1297] refactor: [#1298] reorganize code --- packages/tracker-api-core/src/container.rs | 32 ++++++++++++++++------ 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/packages/tracker-api-core/src/container.rs b/packages/tracker-api-core/src/container.rs index 6dd2d80b1..505b5d7d8 100644 --- a/packages/tracker-api-core/src/container.rs +++ b/packages/tracker-api-core/src/container.rs @@ -10,42 +10,58 @@ use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, HttpApi}; pub struct HttpApiContainer { + // todo: replace with TrackerCoreContainer pub core_config: Arc, - pub http_api_config: Arc, pub in_memory_torrent_repository: Arc, pub keys_handler: Arc, pub whitelist_manager: Arc, - pub ban_service: Arc>, + + // todo: replace with HttpTrackerCoreContainer pub http_stats_repository: Arc, + + // todo: replace with UdpTrackerCoreContainer + pub ban_service: Arc>, pub udp_stats_repository: Arc, + + pub http_api_config: Arc, } impl HttpApiContainer { #[must_use] pub fn initialize(core_config: &Arc, http_api_config: &Arc) -> Arc { - let tracker_core_container = TrackerCoreContainer::initialize(core_config); + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(core_config)); + Self::initialize_from(&tracker_core_container, http_api_config) + } + #[must_use] + pub fn initialize_from( + tracker_core_container: &Arc, + http_api_config: &Arc, + ) -> Arc { // HTTP stats let (_http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + bittorrent_http_tracker_core::statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); let http_stats_repository = Arc::new(http_stats_repository); // UDP stats let (_udp_stats_event_sender, udp_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(core_config.tracker_usage_statistics); + bittorrent_udp_tracker_core::statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); let udp_stats_repository = Arc::new(udp_stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); Arc::new(HttpApiContainer { - http_api_config: http_api_config.clone(), - core_config: core_config.clone(), + core_config: tracker_core_container.core_config.clone(), in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository.clone(), keys_handler: tracker_core_container.keys_handler.clone(), whitelist_manager: tracker_core_container.whitelist_manager.clone(), - ban_service: ban_service.clone(), + http_stats_repository: http_stats_repository.clone(), + + ban_service: ban_service.clone(), udp_stats_repository: udp_stats_repository.clone(), + + http_api_config: http_api_config.clone(), }) } } From 0a44d01a0367fe0ff23110c7b063e6e9559d6e32 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 17:29:31 +0000 Subject: [PATCH 0810/1297] refactor: [#1298] remove duplicate code --- packages/tracker-api-core/src/container.rs | 51 +++--- src/bootstrap/jobs/tracker_apis.rs | 21 ++- src/container.rs | 6 +- src/servers/apis/routes.rs | 4 +- src/servers/apis/server.rs | 17 +- src/servers/apis/v1/context/stats/routes.rs | 4 +- src/servers/apis/v1/routes.rs | 4 +- tests/servers/api/environment.rs | 150 +++++++----------- .../api/v1/contract/context/auth_key.rs | 35 ++-- .../api/v1/contract/context/whitelist.rs | 36 +++-- 10 files changed, 173 insertions(+), 155 deletions(-) diff --git a/packages/tracker-api-core/src/container.rs b/packages/tracker-api-core/src/container.rs index 505b5d7d8..6a650b052 100644 --- a/packages/tracker-api-core/src/container.rs +++ b/packages/tracker-api-core/src/container.rs @@ -1,15 +1,17 @@ use std::sync::Arc; +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_tracker_core::authentication::handler::KeysHandler; use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::banning::BanService; -use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; +use bittorrent_udp_tracker_core::{self}; use tokio::sync::RwLock; -use torrust_tracker_configuration::{Core, HttpApi}; +use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; -pub struct HttpApiContainer { +pub struct TrackerHttpApiCoreContainer { // todo: replace with TrackerCoreContainer pub core_config: Arc, pub in_memory_torrent_repository: Arc, @@ -26,40 +28,43 @@ pub struct HttpApiContainer { pub http_api_config: Arc, } -impl HttpApiContainer { +impl TrackerHttpApiCoreContainer { #[must_use] - pub fn initialize(core_config: &Arc, http_api_config: &Arc) -> Arc { + pub fn initialize( + core_config: &Arc, + http_tracker_config: &Arc, + udp_tracker_config: &Arc, + http_api_config: &Arc, + ) -> Arc { let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(core_config)); - Self::initialize_from(&tracker_core_container, http_api_config) + let http_tracker_core_container = HttpTrackerCoreContainer::initialize_from(&tracker_core_container, http_tracker_config); + let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from(&tracker_core_container, udp_tracker_config); + + Self::initialize_from( + &tracker_core_container, + &http_tracker_core_container, + &udp_tracker_core_container, + http_api_config, + ) } #[must_use] pub fn initialize_from( tracker_core_container: &Arc, + http_tracker_core_container: &Arc, + udp_tracker_core_container: &Arc, http_api_config: &Arc, - ) -> Arc { - // HTTP stats - let (_http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); - let http_stats_repository = Arc::new(http_stats_repository); - - // UDP stats - let (_udp_stats_event_sender, udp_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); - let udp_stats_repository = Arc::new(udp_stats_repository); - - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - - Arc::new(HttpApiContainer { + ) -> Arc { + Arc::new(TrackerHttpApiCoreContainer { core_config: tracker_core_container.core_config.clone(), in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository.clone(), keys_handler: tracker_core_container.keys_handler.clone(), whitelist_manager: tracker_core_container.whitelist_manager.clone(), - http_stats_repository: http_stats_repository.clone(), + http_stats_repository: http_tracker_core_container.http_stats_repository.clone(), - ban_service: ban_service.clone(), - udp_stats_repository: udp_stats_repository.clone(), + ban_service: udp_tracker_core_container.ban_service.clone(), + udp_stats_repository: udp_tracker_core_container.udp_stats_repository.clone(), http_api_config: http_api_config.clone(), }) diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 82dcccb00..458d25367 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -27,7 +27,7 @@ use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::ServiceRegistrationForm; -use torrust_tracker_api_core::container::HttpApiContainer; +use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::AccessTokens; use tracing::instrument; @@ -56,7 +56,7 @@ pub struct ApiServerJobStarted(); /// #[instrument(skip(http_api_container, form))] pub async fn start_job( - http_api_container: Arc, + http_api_container: Arc, form: ServiceRegistrationForm, version: Version, ) -> Option> { @@ -78,7 +78,7 @@ pub async fn start_job( async fn start_v1( socket: SocketAddr, tls: Option, - http_api_container: Arc, + http_api_container: Arc, form: ServiceRegistrationForm, access_tokens: Arc, ) -> JoinHandle<()> { @@ -98,7 +98,7 @@ mod tests { use std::sync::Arc; use torrust_server_lib::registar::Registar; - use torrust_tracker_api_core::container::HttpApiContainer; + use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::initialize_global_services; @@ -108,12 +108,21 @@ mod tests { #[tokio::test] async fn it_should_start_http_tracker() { let cfg = Arc::new(ephemeral_public()); + let core_config = Arc::new(cfg.core.clone()); - let http_api_config = Arc::new(cfg.http_api.clone().unwrap()); + + let http_tracker_config = cfg.http_trackers.clone().expect("missing HTTP tracker configuration"); + let http_tracker_config = Arc::new(http_tracker_config[0].clone()); + + let udp_tracker_configurations = cfg.udp_trackers.clone().expect("missing UDP tracker configuration"); + let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); + + let http_api_config = Arc::new(cfg.http_api.clone().expect("missing HTTP API configuration").clone()); initialize_global_services(&cfg); - let http_api_container = HttpApiContainer::initialize(&core_config, &http_api_config); + let http_api_container = + TrackerHttpApiCoreContainer::initialize(&core_config, &http_tracker_config, &udp_tracker_config, &http_api_config); let version = Version::V1; diff --git a/src/container.rs b/src/container.rs index ed9688935..2175c112f 100644 --- a/src/container.rs +++ b/src/container.rs @@ -17,7 +17,7 @@ use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; -use torrust_tracker_api_core::container::HttpApiContainer; +use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::{Configuration, Core, HttpApi, HttpTracker, UdpTracker}; use tracing::instrument; @@ -78,8 +78,8 @@ impl AppContainer { } #[must_use] - pub fn http_api_container(&self, http_api_config: &Arc) -> HttpApiContainer { - HttpApiContainer { + pub fn http_api_container(&self, http_api_config: &Arc) -> TrackerHttpApiCoreContainer { + TrackerHttpApiCoreContainer { http_api_config: http_api_config.clone(), core_config: self.core_config.clone(), in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index 558d02913..64f6f0cb8 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -16,7 +16,7 @@ use axum::routing::get; use axum::{middleware, BoxError, Router}; use hyper::{Request, StatusCode}; use torrust_server_lib::logging::Latency; -use torrust_tracker_api_core::container::HttpApiContainer; +use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::{AccessTokens, DEFAULT_TIMEOUT}; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; @@ -36,7 +36,7 @@ use crate::servers::apis::API_LOG_TARGET; /// Add all API routes to the router. #[instrument(skip(http_api_container, access_tokens))] pub fn router( - http_api_container: Arc, + http_api_container: Arc, access_tokens: Arc, server_socket_addr: SocketAddr, ) -> Router { diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 20e350d78..df78bf7dc 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -38,7 +38,7 @@ use torrust_axum_server::signals::graceful_shutdown; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use torrust_server_lib::signals::{Halted, Started}; -use torrust_tracker_api_core::container::HttpApiContainer; +use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::AccessTokens; use tracing::{instrument, Level}; @@ -125,7 +125,7 @@ impl ApiServer { #[instrument(skip(self, http_api_container, form, access_tokens), err, ret(Display, level = Level::INFO))] pub async fn start( self, - http_api_container: Arc, + http_api_container: Arc, form: ServiceRegistrationForm, access_tokens: Arc, ) -> Result, Error> { @@ -238,7 +238,7 @@ impl Launcher { #[instrument(skip(self, http_api_container, access_tokens, tx_start, rx_halt))] pub fn start( &self, - http_api_container: Arc, + http_api_container: Arc, access_tokens: Arc, tx_start: Sender, rx_halt: Receiver, @@ -296,7 +296,7 @@ mod tests { use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; - use torrust_tracker_api_core::container::HttpApiContainer; + use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::initialize_global_services; @@ -306,7 +306,11 @@ mod tests { async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_public()); let core_config = Arc::new(cfg.core.clone()); - let http_api_config = Arc::new(cfg.http_api.clone().unwrap()); + let http_tracker_config = cfg.http_trackers.clone().expect("missing HTTP tracker configuration"); + let http_tracker_config = Arc::new(http_tracker_config[0].clone()); + let udp_tracker_configurations = cfg.udp_trackers.clone().expect("missing UDP tracker configuration"); + let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); + let http_api_config = Arc::new(cfg.http_api.clone().expect("missing HTTP API configuration").clone()); initialize_global_services(&cfg); @@ -322,7 +326,8 @@ mod tests { let register = &Registar::default(); - let http_api_container = HttpApiContainer::initialize(&core_config, &http_api_config); + let http_api_container = + TrackerHttpApiCoreContainer::initialize(&core_config, &http_tracker_config, &udp_tracker_config, &http_api_config); let started = stopped .start(http_api_container, register.give_form(), access_tokens) diff --git a/src/servers/apis/v1/context/stats/routes.rs b/src/servers/apis/v1/context/stats/routes.rs index aa723f7ec..df198eba6 100644 --- a/src/servers/apis/v1/context/stats/routes.rs +++ b/src/servers/apis/v1/context/stats/routes.rs @@ -7,12 +7,12 @@ use std::sync::Arc; use axum::routing::get; use axum::Router; -use torrust_tracker_api_core::container::HttpApiContainer; +use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use super::handlers::get_stats_handler; /// It adds the routes to the router for the [`stats`](crate::servers::apis::v1::context::stats) API context. -pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { +pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { router.route( &format!("{prefix}/stats"), get(get_stats_handler).with_state(( diff --git a/src/servers/apis/v1/routes.rs b/src/servers/apis/v1/routes.rs index 7ea01c685..90596f0e7 100644 --- a/src/servers/apis/v1/routes.rs +++ b/src/servers/apis/v1/routes.rs @@ -2,12 +2,12 @@ use std::sync::Arc; use axum::Router; -use torrust_tracker_api_core::container::HttpApiContainer; +use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use super::context::{auth_key, stats, torrent, whitelist}; /// Add the routes for the v1 API. -pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { +pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { let v1_prefix = format!("{prefix}/v1"); let router = auth_key::routes::add(&v1_prefix, router, &http_api_container.keys_handler.clone()); diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 066ad6fff..90c58c821 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -1,25 +1,16 @@ use std::net::SocketAddr; use std::sync::Arc; +use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_primitives::info_hash::InfoHash; -use bittorrent_tracker_core::authentication::handler::KeysHandler; -use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; -use bittorrent_tracker_core::authentication::key::repository::persisted::DatabaseKeyRepository; -use bittorrent_tracker_core::authentication::service::AuthenticationService; -use bittorrent_tracker_core::databases::setup::initialize_database; -use bittorrent_tracker_core::databases::Database; -use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; -use bittorrent_tracker_core::whitelist::setup::initialize_whitelist_manager; -use bittorrent_udp_tracker_core::services::banning::BanService; -use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; +use bittorrent_tracker_core::container::TrackerCoreContainer; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use futures::executor::block_on; -use tokio::sync::RwLock; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; -use torrust_tracker_api_core::container::HttpApiContainer; -use torrust_tracker_configuration::{Configuration, HttpApi}; +use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; +use torrust_tracker_configuration::Configuration; use torrust_tracker_lib::bootstrap::app::initialize_global_services; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_primitives::peer; @@ -28,12 +19,7 @@ pub struct Environment where S: std::fmt::Debug + std::fmt::Display, { - pub http_api_container: Arc, - - pub database: Arc>, - pub authentication_service: Arc, - pub in_memory_whitelist: Arc, - + pub container: Arc, pub registar: Registar, pub server: ApiServer, } @@ -45,7 +31,8 @@ where /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { let () = self - .http_api_container + .container + .tracker_core_container .in_memory_torrent_repository .upsert_peer(info_hash, peer); } @@ -55,40 +42,43 @@ impl Environment { pub fn new(configuration: &Arc) -> Self { initialize_global_services(configuration); - let env_container = EnvContainer::initialize(configuration); + let container = Arc::new(EnvContainer::initialize(configuration)); - let bind_to = env_container.http_api_config.bind_address; + let bind_to = container.tracker_http_api_core_container.http_api_config.bind_address; - let tls = block_on(make_rust_tls(&env_container.http_api_config.tsl_config)).map(|tls| tls.expect("tls config failed")); + let tls = block_on(make_rust_tls( + &container.tracker_http_api_core_container.http_api_config.tsl_config, + )) + .map(|tls| tls.expect("tls config failed")); let server = ApiServer::new(Launcher::new(bind_to, tls)); Self { - http_api_container: env_container.http_api_container, - - database: env_container.database.clone(), - authentication_service: env_container.authentication_service.clone(), - in_memory_whitelist: env_container.in_memory_whitelist.clone(), - + container, registar: Registar::default(), server, } } pub async fn start(self) -> Environment { - let access_tokens = Arc::new(self.http_api_container.http_api_config.access_tokens.clone()); + let access_tokens = Arc::new( + self.container + .tracker_http_api_core_container + .http_api_config + .access_tokens + .clone(), + ); Environment { - http_api_container: self.http_api_container.clone(), - - database: self.database.clone(), - authentication_service: self.authentication_service.clone(), - in_memory_whitelist: self.in_memory_whitelist.clone(), - + container: self.container.clone(), registar: self.registar.clone(), server: self .server - .start(self.http_api_container, self.registar.give_form(), access_tokens) + .start( + self.container.tracker_http_api_core_container.clone(), + self.registar.give_form(), + access_tokens, + ) .await .unwrap(), } @@ -102,12 +92,7 @@ impl Environment { pub async fn stop(self) -> Environment { Environment { - http_api_container: self.http_api_container, - - database: self.database, - authentication_service: self.authentication_service, - in_memory_whitelist: self.in_memory_whitelist, - + container: self.container, registar: Registar::default(), server: self.server.stop().await.unwrap(), } @@ -118,7 +103,13 @@ impl Environment { ConnectionInfo { origin, - api_token: self.http_api_container.http_api_config.access_tokens.get("admin").cloned(), + api_token: self + .container + .tracker_http_api_core_container + .http_api_config + .access_tokens + .get("admin") + .cloned(), } } @@ -128,16 +119,23 @@ impl Environment { } pub struct EnvContainer { - pub http_api_config: Arc, - pub http_api_container: Arc, - pub database: Arc>, - pub authentication_service: Arc, - pub in_memory_whitelist: Arc, + pub tracker_core_container: Arc, + pub tracker_http_api_core_container: Arc, } impl EnvContainer { pub fn initialize(configuration: &Configuration) -> Self { let core_config = Arc::new(configuration.core.clone()); + + let http_tracker_config = configuration + .http_trackers + .clone() + .expect("missing HTTP tracker configuration"); + let http_tracker_config = Arc::new(http_tracker_config[0].clone()); + + let udp_tracker_configurations = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); + let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); + let http_api_config = Arc::new( configuration .http_api @@ -146,47 +144,21 @@ impl EnvContainer { .clone(), ); - // HTTP stats - let (_http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let http_stats_repository = Arc::new(http_stats_repository); - - // UDP stats - let (_udp_stats_event_sender, udp_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let udp_stats_repository = Arc::new(udp_stats_repository); - - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let database = initialize_database(&configuration.core); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - - let whitelist_manager = initialize_whitelist_manager(database.clone(), in_memory_whitelist.clone()); - let db_key_repository = Arc::new(DatabaseKeyRepository::new(&database)); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(AuthenticationService::new(&configuration.core, &in_memory_key_repository)); - let keys_handler = Arc::new(KeysHandler::new( - &db_key_repository.clone(), - &in_memory_key_repository.clone(), - )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let http_api_container = Arc::new(HttpApiContainer { - http_api_config: http_api_config.clone(), - core_config: core_config.clone(), - in_memory_torrent_repository: in_memory_torrent_repository.clone(), - keys_handler: keys_handler.clone(), - whitelist_manager: whitelist_manager.clone(), - ban_service: ban_service.clone(), - http_stats_repository: http_stats_repository.clone(), - udp_stats_repository: udp_stats_repository.clone(), - }); + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); + let http_tracker_core_container = + HttpTrackerCoreContainer::initialize_from(&tracker_core_container, &http_tracker_config); + let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from(&tracker_core_container, &udp_tracker_config); + + let tracker_http_api_core_container = TrackerHttpApiCoreContainer::initialize_from( + &tracker_core_container, + &http_tracker_core_container, + &udp_tracker_core_container, + &http_api_config, + ); Self { - http_api_config, - http_api_container, - database, - authentication_service, - in_memory_whitelist, + tracker_core_container, + tracker_http_api_core_container, } } } diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/tests/servers/api/v1/contract/context/auth_key.rs index ab9bfaf3e..bc6d38bae 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/tests/servers/api/v1/contract/context/auth_key.rs @@ -36,6 +36,8 @@ async fn should_allow_generating_a_new_random_auth_key() { let auth_key_resource = assert_auth_key_utf8(response).await; assert!(env + .container + .tracker_core_container .authentication_service .authenticate(&auth_key_resource.key.parse::().unwrap()) .await @@ -65,6 +67,8 @@ async fn should_allow_uploading_a_preexisting_auth_key() { let auth_key_resource = assert_auth_key_utf8(response).await; assert!(env + .container + .tracker_core_container .authentication_service .authenticate(&auth_key_resource.key.parse::().unwrap()) .await @@ -126,7 +130,7 @@ async fn should_fail_when_the_auth_key_cannot_be_generated() { let env = Started::new(&configuration::ephemeral().into()).await; - force_database_error(&env.database); + force_database_error(&env.container.tracker_core_container.database); let request_id = Uuid::new_v4(); @@ -158,7 +162,8 @@ async fn should_allow_deleting_an_auth_key() { let seconds_valid = 60; let auth_key = env - .http_api_container + .container + .tracker_core_container .keys_handler .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await @@ -293,13 +298,14 @@ async fn should_fail_when_the_auth_key_cannot_be_deleted() { let seconds_valid = 60; let auth_key = env - .http_api_container + .container + .tracker_core_container .keys_handler .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); - force_database_error(&env.database); + force_database_error(&env.container.tracker_core_container.database); let request_id = Uuid::new_v4(); @@ -327,7 +333,8 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { // Generate new auth key let auth_key = env - .http_api_container + .container + .tracker_core_container .keys_handler .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await @@ -348,7 +355,8 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { // Generate new auth key let auth_key = env - .http_api_container + .container + .tracker_core_container .keys_handler .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await @@ -377,7 +385,8 @@ async fn should_allow_reloading_keys() { let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - env.http_api_container + env.container + .tracker_core_container .keys_handler .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await @@ -403,13 +412,14 @@ async fn should_fail_when_keys_cannot_be_reloaded() { let request_id = Uuid::new_v4(); let seconds_valid = 60; - env.http_api_container + env.container + .tracker_core_container .keys_handler .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await .unwrap(); - force_database_error(&env.database); + force_database_error(&env.container.tracker_core_container.database); let response = Client::new(env.get_connection_info()) .reload_keys(Some(headers_with_request_id(request_id))) @@ -432,7 +442,8 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { let env = Started::new(&configuration::ephemeral().into()).await; let seconds_valid = 60; - env.http_api_container + env.container + .tracker_core_container .keys_handler .generate_expiring_peer_key(Some(Duration::from_secs(seconds_valid))) .await @@ -497,6 +508,8 @@ mod deprecated_generate_key_endpoint { let auth_key_resource = assert_auth_key_utf8(response).await; assert!(env + .container + .tracker_core_container .authentication_service .authenticate(&auth_key_resource.key.parse::().unwrap()) .await @@ -563,7 +576,7 @@ mod deprecated_generate_key_endpoint { let env = Started::new(&configuration::ephemeral().into()).await; - force_database_error(&env.database); + force_database_error(&env.container.tracker_core_container.database); let request_id = Uuid::new_v4(); let seconds_valid = 60; diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/tests/servers/api/v1/contract/context/whitelist.rs index ca359650f..6742da4d8 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/tests/servers/api/v1/contract/context/whitelist.rs @@ -31,7 +31,9 @@ async fn should_allow_whitelisting_a_torrent() { assert_ok(response).await; assert!( - env.in_memory_whitelist + env.container + .tracker_core_container + .in_memory_whitelist .contains(&InfoHash::from_str(&info_hash).unwrap()) .await ); @@ -111,7 +113,7 @@ async fn should_fail_when_the_torrent_cannot_be_whitelisted() { let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 - force_database_error(&env.database); + force_database_error(&env.container.tracker_core_container.database); let request_id = Uuid::new_v4(); @@ -167,7 +169,8 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - env.http_api_container + env.container + .tracker_core_container .whitelist_manager .add_torrent_to_whitelist(&info_hash) .await @@ -180,7 +183,13 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { .await; assert_ok(response).await; - assert!(!env.in_memory_whitelist.contains(&info_hash).await); + assert!( + !env.container + .tracker_core_container + .in_memory_whitelist + .contains(&info_hash) + .await + ); env.stop().await; } @@ -241,13 +250,14 @@ async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - env.http_api_container + env.container + .tracker_core_container .whitelist_manager .add_torrent_to_whitelist(&info_hash) .await .unwrap(); - force_database_error(&env.database); + force_database_error(&env.container.tracker_core_container.database); let request_id = Uuid::new_v4(); @@ -274,7 +284,8 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - env.http_api_container + env.container + .tracker_core_container .whitelist_manager .add_torrent_to_whitelist(&info_hash) .await @@ -293,7 +304,8 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica "Expected logs to contain: ERROR ... API ... request_id={request_id}" ); - env.http_api_container + env.container + .tracker_core_container .whitelist_manager .add_torrent_to_whitelist(&info_hash) .await @@ -323,7 +335,8 @@ async fn should_allow_reload_the_whitelist_from_the_database() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - env.http_api_container + env.container + .tracker_core_container .whitelist_manager .add_torrent_to_whitelist(&info_hash) .await @@ -358,13 +371,14 @@ async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - env.http_api_container + env.container + .tracker_core_container .whitelist_manager .add_torrent_to_whitelist(&info_hash) .await .unwrap(); - force_database_error(&env.database); + force_database_error(&env.container.tracker_core_container.database); let request_id = Uuid::new_v4(); From 4b250c375a8707cf9509253f180d71c763d69ca0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 17:33:48 +0000 Subject: [PATCH 0811/1297] refactor: [#1298] convert fn into static method --- src/bootstrap/app.rs | 4 +-- src/container.rs | 83 ++++++++++++++++++++++---------------------- 2 files changed, 43 insertions(+), 44 deletions(-) diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index ec09edd51..04f638a8c 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -19,7 +19,7 @@ use torrust_tracker_configuration::{logging, Configuration}; use tracing::instrument; use super::config::initialize_configuration; -use crate::container::{initialize_app_container, AppContainer}; +use crate::container::AppContainer; /// It loads the configuration from the environment and builds app container. /// @@ -42,7 +42,7 @@ pub fn setup() -> (Configuration, AppContainer) { tracing::info!("Configuration:\n{}", configuration.clone().mask_secrets().to_json()); - let app_container = initialize_app_container(&configuration); + let app_container = AppContainer::initialize(&configuration); (configuration, app_container) } diff --git a/src/container.rs b/src/container.rs index 2175c112f..495a59b09 100644 --- a/src/container.rs +++ b/src/container.rs @@ -47,6 +47,47 @@ pub struct AppContainer { } impl AppContainer { + #[instrument(skip())] + pub fn initialize(configuration: &Configuration) -> AppContainer { + let core_config = Arc::new(configuration.core.clone()); + + let tracker_core_container = TrackerCoreContainer::initialize(&core_config); + + // HTTP stats + let (http_stats_event_sender, http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + let http_stats_repository = Arc::new(http_stats_repository); + + // UDP stats + let (udp_stats_event_sender, udp_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let udp_stats_repository = Arc::new(udp_stats_repository); + + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + + AppContainer { + core_config, + database: tracker_core_container.database, + announce_handler: tracker_core_container.announce_handler, + scrape_handler: tracker_core_container.scrape_handler, + keys_handler: tracker_core_container.keys_handler, + authentication_service: tracker_core_container.authentication_service, + in_memory_whitelist: tracker_core_container.in_memory_whitelist, + whitelist_authorization: tracker_core_container.whitelist_authorization, + whitelist_manager: tracker_core_container.whitelist_manager, + in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository, + db_torrent_repository: tracker_core_container.db_torrent_repository, + torrents_manager: tracker_core_container.torrents_manager, + ban_service, + http_stats_event_sender, + udp_stats_event_sender, + http_stats_repository, + udp_stats_repository, + } + } + #[must_use] pub fn http_tracker_container(&self, http_tracker_config: &Arc) -> HttpTrackerCoreContainer { HttpTrackerCoreContainer { @@ -91,45 +132,3 @@ impl AppContainer { } } } - -/// It initializes the IoC Container. -#[instrument(skip())] -pub fn initialize_app_container(configuration: &Configuration) -> AppContainer { - let core_config = Arc::new(configuration.core.clone()); - - let tracker_core_container = TrackerCoreContainer::initialize(&core_config); - - // HTTP stats - let (http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let http_stats_event_sender = Arc::new(http_stats_event_sender); - let http_stats_repository = Arc::new(http_stats_repository); - - // UDP stats - let (udp_stats_event_sender, udp_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - let udp_stats_repository = Arc::new(udp_stats_repository); - - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - - AppContainer { - core_config, - database: tracker_core_container.database, - announce_handler: tracker_core_container.announce_handler, - scrape_handler: tracker_core_container.scrape_handler, - keys_handler: tracker_core_container.keys_handler, - authentication_service: tracker_core_container.authentication_service, - in_memory_whitelist: tracker_core_container.in_memory_whitelist, - whitelist_authorization: tracker_core_container.whitelist_authorization, - whitelist_manager: tracker_core_container.whitelist_manager, - in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository, - db_torrent_repository: tracker_core_container.db_torrent_repository, - torrents_manager: tracker_core_container.torrents_manager, - ban_service, - http_stats_event_sender, - udp_stats_event_sender, - http_stats_repository, - udp_stats_repository, - } -} From 56ae9f3447e0bb26804c0228867d20680ab3715f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Feb 2025 17:35:29 +0000 Subject: [PATCH 0812/1297] refactor: [#1298] rename method --- src/app.rs | 2 +- src/container.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app.rs b/src/app.rs index 3d2da4ff5..e94db66e3 100644 --- a/src/app.rs +++ b/src/app.rs @@ -111,7 +111,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> // Start HTTP API if let Some(http_api_config) = &config.http_api { let http_api_config = Arc::new(http_api_config.clone()); - let http_api_container = Arc::new(app_container.http_api_container(&http_api_config)); + let http_api_container = Arc::new(app_container.tracker_http_api_container(&http_api_config)); if let Some(job) = tracker_apis::start_job(http_api_container, registar.give_form(), servers::apis::Version::V1).await { jobs.push(job); diff --git a/src/container.rs b/src/container.rs index 495a59b09..6f6d9013d 100644 --- a/src/container.rs +++ b/src/container.rs @@ -119,7 +119,7 @@ impl AppContainer { } #[must_use] - pub fn http_api_container(&self, http_api_config: &Arc) -> TrackerHttpApiCoreContainer { + pub fn tracker_http_api_container(&self, http_api_config: &Arc) -> TrackerHttpApiCoreContainer { TrackerHttpApiCoreContainer { http_api_config: http_api_config.clone(), core_config: self.core_config.clone(), From 025f1008a24486cfb1ece13d2d68a9810239071d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Feb 2025 10:13:56 +0000 Subject: [PATCH 0813/1297] refactor: [#1311] move static initialization to the module where the static values are used This will alllow to initizlize static values in other packages, not only the main tracker app. --- Cargo.lock | 2 +- Cargo.toml | 1 - packages/clock/Cargo.toml | 1 + packages/clock/src/lib.rs | 16 +++++++++++++++- packages/udp-tracker-core/src/lib.rs | 16 ++++++++++++++++ src/bootstrap/app.rs | 18 ++++-------------- 6 files changed, 37 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 981ffeba3..bb2688681 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4434,7 +4434,6 @@ dependencies = [ "futures", "futures-util", "hyper", - "lazy_static", "local-ip-address", "mockall", "parking_lot", @@ -4532,6 +4531,7 @@ dependencies = [ "chrono", "lazy_static", "torrust-tracker-primitives", + "tracing", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index d3b194ed9..fbd81423d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,7 +52,6 @@ figment = "0" futures = "0" futures-util = "0" hyper = "1" -lazy_static = "1" parking_lot = "0" percent-encoding = "2" r2d2 = "0" diff --git a/packages/clock/Cargo.toml b/packages/clock/Cargo.toml index 2ede678d9..3bd00d2b0 100644 --- a/packages/clock/Cargo.toml +++ b/packages/clock/Cargo.toml @@ -18,6 +18,7 @@ version.workspace = true [dependencies] chrono = { version = "0", default-features = false, features = ["clock"] } lazy_static = "1" +tracing = "0" torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } diff --git a/packages/clock/src/lib.rs b/packages/clock/src/lib.rs index b7d20620c..ff0527714 100644 --- a/packages/clock/src/lib.rs +++ b/packages/clock/src/lib.rs @@ -22,7 +22,6 @@ //! > **NOTICE**: the timestamp does not depend on the time zone. That gives you //! > the ability to use the clock regardless of the underlying system time zone //! > configuration. See [Unix time Wikipedia entry](https://en.wikipedia.org/wiki/Unix_time). - pub mod clock; pub mod conv; pub mod static_time; @@ -30,6 +29,8 @@ pub mod static_time; #[macro_use] extern crate lazy_static; +use tracing::instrument; + /// This code needs to be copied into each crate. /// Working version, for production. #[cfg(not(test))] @@ -40,3 +41,16 @@ pub(crate) type CurrentClock = clock::Working; #[cfg(test)] #[allow(dead_code)] pub(crate) type CurrentClock = clock::Stopped; + +/// It initializes the application static values. +/// +/// These values are accessible throughout the entire application: +/// +/// - The time when the application started. +/// - An ephemeral instance random seed. This seed is used for encryption and +/// it's changed when the main application process is restarted. +#[instrument(skip())] +pub fn initialize_static() { + // Set the time of Torrust app starting + lazy_static::initialize(&static_time::TIME_AT_APP_START); +} diff --git a/packages/udp-tracker-core/src/lib.rs b/packages/udp-tracker-core/src/lib.rs index f649cbeaf..5aa714d35 100644 --- a/packages/udp-tracker-core/src/lib.rs +++ b/packages/udp-tracker-core/src/lib.rs @@ -4,6 +4,9 @@ pub mod crypto; pub mod services; pub mod statistics; +use crypto::ephemeral_instance_keys; +use tracing::instrument; + #[macro_use] extern crate lazy_static; @@ -12,3 +15,16 @@ extern crate lazy_static; pub const MAX_CONNECTION_ID_ERRORS_PER_IP: u32 = 10; pub const UDP_TRACKER_LOG_TARGET: &str = "UDP TRACKER"; + +/// It initializes the static values. +#[instrument(skip())] +pub fn initialize_static() { + // Initialize the Ephemeral Instance Random Seed + lazy_static::initialize(&ephemeral_instance_keys::RANDOM_SEED); + + // Initialize the Ephemeral Instance Random Cipher + lazy_static::initialize(&ephemeral_instance_keys::RANDOM_CIPHER_BLOWFISH); + + // Initialize the Zeroed Cipher + lazy_static::initialize(&ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH); +} diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 04f638a8c..bcf000dfd 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -11,9 +11,7 @@ //! 2. Initialize static variables. //! 3. Initialize logging. //! 4. Initialize the domain tracker. -use bittorrent_udp_tracker_core::crypto::ephemeral_instance_keys; use bittorrent_udp_tracker_core::crypto::keys::{self, Keeper as _}; -use torrust_tracker_clock::static_time; use torrust_tracker_configuration::validator::Validator; use torrust_tracker_configuration::{logging, Configuration}; use tracing::instrument; @@ -71,18 +69,10 @@ pub fn initialize_global_services(configuration: &Configuration) { /// These values are accessible throughout the entire application: /// /// - The time when the application started. -/// - An ephemeral instance random seed. This seed is used for encryption and it's changed when the main application process is restarted. +/// - An ephemeral instance random seed. This seed is used for encryption and +/// it's changed when the main application process is restarted. #[instrument(skip())] pub fn initialize_static() { - // Set the time of Torrust app starting - lazy_static::initialize(&static_time::TIME_AT_APP_START); - - // Initialize the Ephemeral Instance Random Seed - lazy_static::initialize(&ephemeral_instance_keys::RANDOM_SEED); - - // Initialize the Ephemeral Instance Random Cipher - lazy_static::initialize(&ephemeral_instance_keys::RANDOM_CIPHER_BLOWFISH); - - // Initialize the Zeroed Cipher - lazy_static::initialize(&ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH); + torrust_tracker_clock::initialize_static(); + bittorrent_udp_tracker_core::initialize_static(); } From d6e7a92bedb448ddc43bcbd878014c6e948d9a72 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Feb 2025 11:05:20 +0000 Subject: [PATCH 0814/1297] refactor: [#1311] initialize statics in each package To avoid dependency on the main app. This will allow moving code to workspace packages. --- Cargo.lock | 1 + packages/axum-http-tracker-server/Cargo.toml | 1 + packages/axum-http-tracker-server/src/server.rs | 13 +++++++++++-- src/servers/apis/server.rs | 12 +++++++++++- src/servers/udp/server/mod.rs | 12 +++++++++++- tests/servers/api/environment.rs | 13 +++++++++++-- tests/servers/http/environment.rs | 12 ++++++++++-- tests/servers/udp/environment.rs | 13 +++++++++++-- 8 files changed, 67 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bb2688681..2c6127740 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4373,6 +4373,7 @@ dependencies = [ "tokio", "torrust-axum-server", "torrust-server-lib", + "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-primitives", "torrust-tracker-test-helpers", diff --git a/packages/axum-http-tracker-server/Cargo.toml b/packages/axum-http-tracker-server/Cargo.toml index ae038cb7b..98c807a92 100644 --- a/packages/axum-http-tracker-server/Cargo.toml +++ b/packages/axum-http-tracker-server/Cargo.toml @@ -38,4 +38,5 @@ tower-http = { version = "0", features = ["compression-full", "cors", "propagate tracing = "0" [dev-dependencies] +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index a5cd3bb74..4cf5afc13 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -250,7 +250,7 @@ mod tests { use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; - use torrust_tracker_configuration::Configuration; + use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::server::{HttpServer, Launcher}; @@ -306,6 +306,15 @@ mod tests { } } + fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); + } + + fn initialize_static() { + torrust_tracker_clock::initialize_static(); + } + #[tokio::test] async fn it_should_be_able_to_start_and_stop() { let configuration = Arc::new(ephemeral_public()); @@ -317,7 +326,7 @@ mod tests { let http_tracker_config = &http_trackers[0]; - //initialize_global_services(&cfg); // not needed for this test + initialize_global_services(&configuration); let http_tracker_container = Arc::new(initialize_container(&configuration)); diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index df78bf7dc..4c3484ded 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -297,11 +297,21 @@ mod tests { use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; + use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::bootstrap::app::initialize_global_services; use crate::servers::apis::server::{ApiServer, Launcher}; + fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); + } + + fn initialize_static() { + torrust_tracker_clock::initialize_static(); + bittorrent_udp_tracker_core::initialize_static(); + } + #[tokio::test] async fn it_should_be_able_to_start_and_stop() { let cfg = Arc::new(ephemeral_public()); diff --git a/src/servers/udp/server/mod.rs b/src/servers/udp/server/mod.rs index a328c45ce..1ab79b6fe 100644 --- a/src/servers/udp/server/mod.rs +++ b/src/servers/udp/server/mod.rs @@ -59,11 +59,21 @@ mod tests { use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use torrust_server_lib::registar::Registar; + use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_test_helpers::configuration::ephemeral_public; use super::spawner::Spawner; use super::Server; - use crate::bootstrap::app::initialize_global_services; + + fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); + } + + fn initialize_static() { + torrust_tracker_clock::initialize_static(); + bittorrent_udp_tracker_core::initialize_static(); + } #[tokio::test] async fn it_should_be_able_to_start_and_stop() { diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 90c58c821..5534a99a9 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -10,8 +10,7 @@ use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; -use torrust_tracker_configuration::Configuration; -use torrust_tracker_lib::bootstrap::app::initialize_global_services; +use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_primitives::peer; @@ -162,3 +161,13 @@ impl EnvContainer { } } } + +fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); +} + +fn initialize_static() { + torrust_tracker_clock::initialize_static(); + bittorrent_udp_tracker_core::initialize_static(); +} diff --git a/tests/servers/http/environment.rs b/tests/servers/http/environment.rs index e77cc38aa..f79d42b36 100644 --- a/tests/servers/http/environment.rs +++ b/tests/servers/http/environment.rs @@ -7,8 +7,7 @@ use futures::executor::block_on; use torrust_axum_http_tracker_server::server::{HttpServer, Launcher, Running, Stopped}; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; -use torrust_tracker_configuration::Configuration; -use torrust_tracker_lib::bootstrap::app::initialize_global_services; +use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_primitives::peer; pub struct Environment { @@ -106,3 +105,12 @@ impl EnvContainer { } } } + +fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); +} + +fn initialize_static() { + torrust_tracker_clock::initialize_static(); +} diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index 8afaffc15..c53f7a723 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -5,8 +5,7 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use torrust_server_lib::registar::Registar; -use torrust_tracker_configuration::{Configuration, DEFAULT_TIMEOUT}; -use torrust_tracker_lib::bootstrap::app::initialize_global_services; +use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_lib::servers::udp::server::spawner::Spawner; use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; use torrust_tracker_lib::servers::udp::server::Server; @@ -120,6 +119,16 @@ impl EnvContainer { } } +fn initialize_global_services(configuration: &Configuration) { + initialize_static(); + logging::setup(&configuration.logging); +} + +fn initialize_static() { + torrust_tracker_clock::initialize_static(); + bittorrent_udp_tracker_core::initialize_static(); +} + #[cfg(test)] mod tests { use std::time::Duration; From b071900a8bb2d67e0c9dc792d4725c10f1fe9cbf Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Feb 2025 11:59:09 +0000 Subject: [PATCH 0815/1297] docs: fix crate docs URL --- packages/axum-http-tracker-server/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/axum-http-tracker-server/README.md b/packages/axum-http-tracker-server/README.md index b7286d157..b109a08c1 100644 --- a/packages/axum-http-tracker-server/README.md +++ b/packages/axum-http-tracker-server/README.md @@ -4,7 +4,7 @@ The Torrust Bittorrent HTTP tracker. ## Documentation -[Crate documentation](https://docs.rs/torrust-axum-server). +[Crate documentation](https://docs.rs/torrust-axum-http-tracker-server). ## License From ec6b968be3b0132a861250e0fa98b71d714287a2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Feb 2025 12:37:46 +0000 Subject: [PATCH 0816/1297] refactor: [#1284] extract udp-tracker-server package --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 33 +- Cargo.toml | 4 +- packages/axum-http-tracker-server/src/lib.rs | 2 +- .../src/v1/handlers/announce.rs | 3 - .../src/v1/handlers/mod.rs | 3 - .../src/v1/handlers/scrape.rs | 3 - .../axum-http-tracker-server/src/v1/mod.rs | 3 - packages/tracker-core/src/lib.rs | 14 + packages/udp-tracker-server/Cargo.toml | 41 ++ packages/udp-tracker-server/LICENSE | 661 ++++++++++++++++++ packages/udp-tracker-server/README.md | 11 + .../udp-tracker-server/src}/error.rs | 0 .../src}/handlers/announce.rs | 31 +- .../src}/handlers/connect.rs | 7 +- .../udp-tracker-server/src}/handlers/error.rs | 2 +- .../udp-tracker-server/src}/handlers/mod.rs | 6 +- .../src}/handlers/scrape.rs | 29 +- .../udp-tracker-server/src/lib.rs | 18 +- .../src}/server/bound_socket.rs | 0 .../src}/server/launcher.rs | 6 +- .../udp-tracker-server/src}/server/mod.rs | 0 .../src}/server/processor.rs | 4 +- .../src}/server/receiver.rs | 2 +- .../src}/server/request_buffer.rs | 0 .../udp-tracker-server/src}/server/spawner.rs | 0 .../udp-tracker-server/src}/server/states.rs | 2 +- src/bootstrap/jobs/udp_tracker.rs | 5 +- src/lib.rs | 8 +- src/servers/mod.rs | 1 - src/shared/bit_torrent/common.rs | 13 - src/shared/bit_torrent/tracker/udp/mod.rs | 3 - tests/servers/health_check_api/contract.rs | 22 +- tests/servers/udp/contract.rs | 2 +- tests/servers/udp/environment.rs | 6 +- tests/servers/udp/mod.rs | 4 +- 36 files changed, 842 insertions(+), 108 deletions(-) create mode 100644 packages/udp-tracker-server/Cargo.toml create mode 100644 packages/udp-tracker-server/LICENSE create mode 100644 packages/udp-tracker-server/README.md rename {src/servers/udp => packages/udp-tracker-server/src}/error.rs (100%) rename {src/servers/udp => packages/udp-tracker-server/src}/handlers/announce.rs (96%) rename {src/servers/udp => packages/udp-tracker-server/src}/handlers/connect.rs (96%) rename {src/servers/udp => packages/udp-tracker-server/src}/handlers/error.rs (98%) rename {src/servers/udp => packages/udp-tracker-server/src}/handlers/mod.rs (98%) rename {src/servers/udp => packages/udp-tracker-server/src}/handlers/scrape.rs (93%) rename src/servers/udp/mod.rs => packages/udp-tracker-server/src/lib.rs (98%) rename {src/servers/udp => packages/udp-tracker-server/src}/server/bound_socket.rs (100%) rename {src/servers/udp => packages/udp-tracker-server/src}/server/launcher.rs (98%) rename {src/servers/udp => packages/udp-tracker-server/src}/server/mod.rs (100%) rename {src/servers/udp => packages/udp-tracker-server/src}/server/processor.rs (97%) rename {src/servers/udp => packages/udp-tracker-server/src}/server/receiver.rs (95%) rename {src/servers/udp => packages/udp-tracker-server/src}/server/request_buffer.rs (100%) rename {src/servers/udp => packages/udp-tracker-server/src}/server/spawner.rs (100%) rename {src/servers/udp => packages/udp-tracker-server/src}/server/states.rs (98%) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 5aca88ac4..259a97728 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -76,3 +76,4 @@ jobs: cargo publish -p torrust-tracker-primitives cargo publish -p torrust-tracker-test-helpers cargo publish -p torrust-tracker-torrent-repository + cargo publish -p torrust-udp-tracker-server diff --git a/Cargo.lock b/Cargo.lock index 2c6127740..22cdc002a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4433,7 +4433,6 @@ dependencies = [ "derive_more", "figment", "futures", - "futures-util", "hyper", "local-ip-address", "mockall", @@ -4445,7 +4444,6 @@ dependencies = [ "rand 0.9.0", "regex", "reqwest", - "ringbuf", "serde", "serde_bencode", "serde_bytes", @@ -4462,10 +4460,10 @@ dependencies = [ "torrust-tracker-api-core", "torrust-tracker-clock", "torrust-tracker-configuration", - "torrust-tracker-located-error", "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-tracker-torrent-repository", + "torrust-udp-tracker-server", "tower 0.5.2", "tower-http", "tracing", @@ -4614,6 +4612,35 @@ dependencies = [ "zerocopy 0.7.35", ] +[[package]] +name = "torrust-udp-tracker-server" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "bittorrent-primitives", + "bittorrent-tracker-client", + "bittorrent-tracker-core", + "bittorrent-udp-tracker-core", + "derive_more", + "futures", + "futures-util", + "local-ip-address", + "mockall", + "ringbuf", + "thiserror 2.0.11", + "tokio", + "torrust-server-lib", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-located-error", + "torrust-tracker-primitives", + "torrust-tracker-test-helpers", + "tracing", + "url", + "uuid", + "zerocopy 0.7.35", +] + [[package]] name = "tower" version = "0.4.13" diff --git a/Cargo.toml b/Cargo.toml index fbd81423d..d8c739440 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,7 +50,6 @@ dashmap = "6" derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } figment = "0" futures = "0" -futures-util = "0" hyper = "1" parking_lot = "0" percent-encoding = "2" @@ -60,7 +59,6 @@ r2d2_sqlite = { version = "0", features = ["bundled"] } rand = "0" regex = "1" reqwest = { version = "0", features = ["json"] } -ringbuf = "0" serde = { version = "1", features = ["derive"] } serde_bencode = "0" serde_bytes = "0" @@ -76,9 +74,9 @@ torrust-server-lib = { version = "3.0.0-develop", path = "packages/server-lib" } torrust-tracker-api-core = { version = "3.0.0-develop", path = "packages/tracker-api-core" } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } -torrust-tracker-located-error = { version = "3.0.0-develop", path = "packages/located-error" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "packages/primitives" } torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "packages/torrent-repository" } +torrust-udp-tracker-server = { version = "3.0.0-develop", path = "packages/udp-tracker-server" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" diff --git a/packages/axum-http-tracker-server/src/lib.rs b/packages/axum-http-tracker-server/src/lib.rs index a8823b868..7f6bec892 100644 --- a/packages/axum-http-tracker-server/src/lib.rs +++ b/packages/axum-http-tracker-server/src/lib.rs @@ -238,7 +238,7 @@ //! `info_hash` parameters: `info_hash=%81%00%0...00%00%00&info_hash=%82%00%0...00%00%00` //! //! > **NOTICE**: the maximum number of torrents you can scrape at the same time -//! > is `74`. Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS). +//! > is `74`. Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](torrust_udp_tracker_server::MAX_SCRAPE_TORRENTS). //! //! **Sample response** //! diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index f8f551253..98b2d374c 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -1,8 +1,5 @@ //! Axum [`handlers`](axum#handlers) for the `announce` requests. //! -//! Refer to [HTTP server](crate::servers::http) for more information about the -//! `announce` request. -//! //! The handlers perform the authentication and authorization of the request, //! and resolve the client IP address. use std::sync::Arc; diff --git a/packages/axum-http-tracker-server/src/v1/handlers/mod.rs b/packages/axum-http-tracker-server/src/v1/handlers/mod.rs index f9305cf20..ce58e09b3 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/mod.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/mod.rs @@ -1,7 +1,4 @@ //! Axum [`handlers`](axum#handlers) for the HTTP server. -//! -//! Refer to the generic [HTTP server documentation](crate::servers::http) for -//! more information about the HTTP tracker. pub mod announce; pub mod common; pub mod health_check; diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index a4e20cc6f..59549128a 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -1,8 +1,5 @@ //! Axum [`handlers`](axum#handlers) for the `announce` requests. //! -//! Refer to [HTTP server](crate::servers::http) for more information about the -//! `scrape` request. -//! //! The handlers perform the authentication and authorization of the request, //! and resolve the client IP address. use std::sync::Arc; diff --git a/packages/axum-http-tracker-server/src/v1/mod.rs b/packages/axum-http-tracker-server/src/v1/mod.rs index 6e9530cb0..7b1b15138 100644 --- a/packages/axum-http-tracker-server/src/v1/mod.rs +++ b/packages/axum-http-tracker-server/src/v1/mod.rs @@ -1,7 +1,4 @@ //! HTTP server implementation for the `v1` API. -//! -//! Refer to the generic [HTTP server documentation](crate::servers::http) for -//! more information about the endpoints and their usage. pub mod extractors; pub mod handlers; pub mod routes; diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index 0107fb443..d9da9b9e7 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -131,6 +131,20 @@ pub mod peer_tests; pub mod test_helpers; use torrust_tracker_clock::clock; + +/// The maximum number of torrents that can be returned in an `scrape` response. +/// +/// The [BEP 15. UDP Tracker Protocol for `BitTorrent`](https://www.bittorrent.org/beps/bep_0015.html) +/// defines this limit: +/// +/// "Up to about 74 torrents can be scraped at once. A full scrape can't be done +/// with this protocol." +/// +/// The [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) +/// does not specifically mention this limit, but the limit is being used for +/// both the UDP and HTTP trackers since it's applied at the domain level. +pub const MAX_SCRAPE_TORRENTS: u8 = 74; + /// This code needs to be copied into each crate. /// Working version, for production. #[cfg(not(test))] diff --git a/packages/udp-tracker-server/Cargo.toml b/packages/udp-tracker-server/Cargo.toml new file mode 100644 index 000000000..7ebba677f --- /dev/null +++ b/packages/udp-tracker-server/Cargo.toml @@ -0,0 +1,41 @@ +[package] +authors.workspace = true +description = "The Torrust Bittorrent UDP tracker." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = ["axum", "bittorrent", "server", "torrust", "tracker", "udp"] +license.workspace = true +name = "torrust-udp-tracker-server" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +bittorrent-tracker-client = { version = "3.0.0-develop", path = "../tracker-client" } +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "../udp-tracker-core" } +derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } +futures = "0" +futures-util = "0" +ringbuf = "0" +thiserror = "2" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tracing = "0" +url = { version = "2", features = ["serde"] } +uuid = { version = "1", features = ["v4"] } +zerocopy = "0.7" + +[dev-dependencies] +local-ip-address = "0" +mockall = "0" +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/udp-tracker-server/LICENSE b/packages/udp-tracker-server/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/udp-tracker-server/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/udp-tracker-server/README.md b/packages/udp-tracker-server/README.md new file mode 100644 index 000000000..bdf147104 --- /dev/null +++ b/packages/udp-tracker-server/README.md @@ -0,0 +1,11 @@ +# Torrust UDP Tracker + +The Torrust Bittorrent UDP tracker. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-udp-tracker-server). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/src/servers/udp/error.rs b/packages/udp-tracker-server/src/error.rs similarity index 100% rename from src/servers/udp/error.rs rename to packages/udp-tracker-server/src/error.rs diff --git a/src/servers/udp/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs similarity index 96% rename from src/servers/udp/handlers/announce.rs rename to packages/udp-tracker-server/src/handlers/announce.rs index 66fc0ab42..7e3b8e7dd 100644 --- a/src/servers/udp/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -16,10 +16,9 @@ use torrust_tracker_primitives::core::AnnounceData; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; -use crate::servers::udp::error::Error; +use crate::error::Error; -/// It handles the `Announce` request. Refer to [`Announce`](crate::servers::udp#announce) -/// request for more information. +/// It handles the `Announce` request. /// /// # Errors /// @@ -130,7 +129,7 @@ mod tests { }; use bittorrent_udp_tracker_core::connection_cookie::make; - use crate::servers::udp::handlers::tests::{sample_ipv4_remote_addr_fingerprint, sample_issue_time}; + use crate::handlers::tests::{sample_ipv4_remote_addr_fingerprint, sample_issue_time}; struct AnnounceRequestBuilder { request: AnnounceRequest, @@ -210,9 +209,9 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_configuration::Core; - use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::handle_announce; - use crate::servers::udp::handlers::tests::{ + use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::handlers::handle_announce; + use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, sample_issue_time, MockUdpStatsEventSender, TorrentPeerBuilder, @@ -443,9 +442,9 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; - use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::handle_announce; - use crate::servers::udp::handlers::tests::{ + use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::handlers::handle_announce; + use crate::handlers::tests::{ initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_issue_time, TorrentPeerBuilder, }; @@ -517,9 +516,9 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_configuration::Core; - use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::handle_announce; - use crate::servers::udp::handlers::tests::{ + use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::handlers::handle_announce; + use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, sample_issue_time, MockUdpStatsEventSender, TorrentPeerBuilder, @@ -772,9 +771,9 @@ mod tests { use bittorrent_udp_tracker_core::{self, statistics}; use mockall::predicate::eq; - use crate::servers::udp::handlers::announce::tests::announce_request::AnnounceRequestBuilder; - use crate::servers::udp::handlers::handle_announce; - use crate::servers::udp::handlers::tests::{ + use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; + use crate::handlers::handle_announce; + use crate::handlers::tests::{ sample_cookie_valid_range, sample_issue_time, MockUdpStatsEventSender, TrackerConfigurationBuilder, }; diff --git a/src/servers/udp/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs similarity index 96% rename from src/servers/udp/handlers/connect.rs rename to packages/udp-tracker-server/src/handlers/connect.rs index b9209a115..d1c3a05d8 100644 --- a/src/servers/udp/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -6,8 +6,7 @@ use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, ConnectionId, Respon use bittorrent_udp_tracker_core::{services, statistics}; use tracing::{instrument, Level}; -/// It handles the `Connect` request. Refer to [`Connect`](crate::servers::udp#connect) -/// request for more information. +/// It handles the `Connect` request. #[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_connect( remote_addr: SocketAddr, @@ -45,8 +44,8 @@ mod tests { use bittorrent_udp_tracker_core::statistics; use mockall::predicate::eq; - use crate::servers::udp::handlers::handle_connect; - use crate::servers::udp::handlers::tests::{ + use crate::handlers::handle_connect; + use crate::handlers::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpStatsEventSender, }; diff --git a/src/servers/udp/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs similarity index 98% rename from src/servers/udp/handlers/error.rs rename to packages/udp-tracker-server/src/handlers/error.rs index 443f36cc0..4f2457126 100644 --- a/src/servers/udp/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -10,7 +10,7 @@ use tracing::{instrument, Level}; use uuid::Uuid; use zerocopy::network_endian::I32; -use crate::servers::udp::error::Error; +use crate::error::Error; #[allow(clippy::too_many_arguments)] #[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] diff --git a/src/servers/udp/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs similarity index 98% rename from src/servers/udp/handlers/mod.rs rename to packages/udp-tracker-server/src/handlers/mod.rs index bc876bced..5d7fdb3b3 100644 --- a/src/servers/udp/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -11,18 +11,18 @@ use std::time::Instant; use announce::handle_announce; use aquatic_udp_protocol::{Request, Response, TransactionId}; +use bittorrent_tracker_core::MAX_SCRAPE_TORRENTS; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::announce::UdpAnnounceError; use connect::handle_connect; use error::handle_error; use scrape::handle_scrape; -use torrust_tracker_clock::clock::Time as _; +use torrust_tracker_clock::clock::Time; use tracing::{instrument, Level}; use uuid::Uuid; use super::RawRequest; -use crate::servers::udp::error::Error; -use crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS; +use crate::error::Error; use crate::CurrentClock; #[derive(Debug, Clone, PartialEq)] diff --git a/src/servers/udp/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs similarity index 93% rename from src/servers/udp/handlers/scrape.rs rename to packages/udp-tracker-server/src/handlers/scrape.rs index aa7287951..de98b5f6d 100644 --- a/src/servers/udp/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -13,10 +13,9 @@ use torrust_tracker_primitives::core::ScrapeData; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; -use crate::servers::udp::error::Error; +use crate::error::Error; -/// It handles the `Scrape` request. Refer to [`Scrape`](crate::servers::udp#scrape) -/// request for more information. +/// It handles the `Scrape` request. /// /// # Errors /// @@ -89,8 +88,8 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{ + use crate::handlers::handle_scrape; + use crate::handlers::tests::{ initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, sample_issue_time, TorrentPeerBuilder, }; @@ -200,10 +199,8 @@ mod tests { mod with_a_public_tracker { use aquatic_udp_protocol::{NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; - use crate::servers::udp::handlers::scrape::tests::scrape_request::{ - add_a_sample_seeder_and_scrape, match_scrape_response, - }; - use crate::servers::udp::handlers::tests::initialize_core_tracker_services_for_public_tracker; + use crate::handlers::scrape::tests::scrape_request::{add_a_sample_seeder_and_scrape, match_scrape_response}; + use crate::handlers::tests::initialize_core_tracker_services_for_public_tracker; #[tokio::test] async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { @@ -230,11 +227,11 @@ mod tests { mod with_a_whitelisted_tracker { use aquatic_udp_protocol::{InfoHash, NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::scrape::tests::scrape_request::{ + use crate::handlers::handle_scrape; + use crate::handlers::scrape::tests::scrape_request::{ add_a_seeder, build_scrape_request, match_scrape_response, zeroed_torrent_statistics, }; - use crate::servers::udp::handlers::tests::{ + use crate::handlers::tests::{ initialize_core_tracker_services_for_listed_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, }; @@ -332,8 +329,8 @@ mod tests { use mockall::predicate::eq; use super::sample_scrape_request; - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{ + use crate::handlers::handle_scrape; + use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, sample_ipv4_remote_addr, MockUdpStatsEventSender, }; @@ -374,8 +371,8 @@ mod tests { use mockall::predicate::eq; use super::sample_scrape_request; - use crate::servers::udp::handlers::handle_scrape; - use crate::servers::udp::handlers::tests::{ + use crate::handlers::handle_scrape; + use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, sample_ipv6_remote_addr, MockUdpStatsEventSender, }; diff --git a/src/servers/udp/mod.rs b/packages/udp-tracker-server/src/lib.rs similarity index 98% rename from src/servers/udp/mod.rs rename to packages/udp-tracker-server/src/lib.rs index 1fcd49725..a07f2e665 100644 --- a/src/servers/udp/mod.rs +++ b/packages/udp-tracker-server/src/lib.rs @@ -475,7 +475,7 @@ //! //! > **NOTICE**: up to about 74 torrents can be scraped at once. A full scrape //! > can't be done with this protocol. This is a limitation of the UDP protocol. -//! > Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](crate::shared::bit_torrent::common::MAX_SCRAPE_TORRENTS). +//! > Defined with a hardcoded const [`MAX_SCRAPE_TORRENTS`](torrust_udp_tracker_server::MAX_SCRAPE_TORRENTS). //! > Refer to [issue 262](https://github.com/torrust/torrust-tracker/issues/262) //! > for more information about this limitation. //! @@ -637,10 +637,26 @@ use std::net::SocketAddr; +use torrust_tracker_clock::clock; + pub mod error; pub mod handlers; pub mod server; +/// The maximum number of bytes in a UDP packet. +pub const MAX_PACKET_SIZE: usize = 1496; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; + /// Number of bytes. pub type Bytes = u64; /// The port the peer is listening on. diff --git a/src/servers/udp/server/bound_socket.rs b/packages/udp-tracker-server/src/server/bound_socket.rs similarity index 100% rename from src/servers/udp/server/bound_socket.rs rename to packages/udp-tracker-server/src/server/bound_socket.rs diff --git a/src/servers/udp/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs similarity index 98% rename from src/servers/udp/server/launcher.rs rename to packages/udp-tracker-server/src/server/launcher.rs index d66ad8d37..12d9c740c 100644 --- a/src/servers/udp/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -16,9 +16,9 @@ use torrust_server_lib::signals::{shutdown_signal_with_message, Halted, Started} use tracing::instrument; use super::request_buffer::ActiveRequests; -use crate::servers::udp::server::bound_socket::BoundSocket; -use crate::servers::udp::server::processor::Processor; -use crate::servers::udp::server::receiver::Receiver; +use crate::server::bound_socket::BoundSocket; +use crate::server::processor::Processor; +use crate::server::receiver::Receiver; const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 3600; diff --git a/src/servers/udp/server/mod.rs b/packages/udp-tracker-server/src/server/mod.rs similarity index 100% rename from src/servers/udp/server/mod.rs rename to packages/udp-tracker-server/src/server/mod.rs diff --git a/src/servers/udp/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs similarity index 97% rename from src/servers/udp/server/processor.rs rename to packages/udp-tracker-server/src/server/processor.rs index 157f3ecfe..a933fdd17 100644 --- a/src/servers/udp/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -10,8 +10,8 @@ use tokio::time::Instant; use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; -use crate::servers::udp::handlers::CookieTimeValues; -use crate::servers::udp::{handlers, RawRequest}; +use crate::handlers::CookieTimeValues; +use crate::{handlers, RawRequest}; pub struct Processor { socket: Arc, diff --git a/src/servers/udp/server/receiver.rs b/packages/udp-tracker-server/src/server/receiver.rs similarity index 95% rename from src/servers/udp/server/receiver.rs rename to packages/udp-tracker-server/src/server/receiver.rs index 0176930a4..89fbed081 100644 --- a/src/servers/udp/server/receiver.rs +++ b/packages/udp-tracker-server/src/server/receiver.rs @@ -8,7 +8,7 @@ use futures::Stream; use super::bound_socket::BoundSocket; use super::RawRequest; -use crate::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; +use crate::MAX_PACKET_SIZE; pub struct Receiver { pub socket: Arc, diff --git a/src/servers/udp/server/request_buffer.rs b/packages/udp-tracker-server/src/server/request_buffer.rs similarity index 100% rename from src/servers/udp/server/request_buffer.rs rename to packages/udp-tracker-server/src/server/request_buffer.rs diff --git a/src/servers/udp/server/spawner.rs b/packages/udp-tracker-server/src/server/spawner.rs similarity index 100% rename from src/servers/udp/server/spawner.rs rename to packages/udp-tracker-server/src/server/spawner.rs diff --git a/src/servers/udp/server/states.rs b/packages/udp-tracker-server/src/server/states.rs similarity index 98% rename from src/servers/udp/server/states.rs rename to packages/udp-tracker-server/src/server/states.rs index 3501aebf1..fc700ea40 100644 --- a/src/servers/udp/server/states.rs +++ b/packages/udp-tracker-server/src/server/states.rs @@ -14,7 +14,7 @@ use tracing::{instrument, Level}; use super::spawner::Spawner; use super::{Server, UdpError}; -use crate::servers::udp::server::launcher::Launcher; +use crate::server::launcher::Launcher; /// A UDP server instance controller with no UDP instance running. #[allow(clippy::module_name_repetitions)] diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 89b2a38be..0276de1d3 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -12,11 +12,10 @@ use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use tokio::task::JoinHandle; use torrust_server_lib::registar::ServiceRegistrationForm; +use torrust_udp_tracker_server::server::spawner::Spawner; +use torrust_udp_tracker_server::server::Server; use tracing::instrument; -use crate::servers::udp::server::spawner::Spawner; -use crate::servers::udp::server::Server; - /// It starts a new UDP server with the provided configuration. /// /// It spawns a new asynchronous task for the new UDP server. diff --git a/src/lib.rs b/src/lib.rs index 4f552ab34..fa18fd7c8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,7 +56,7 @@ //! From the end-user perspective the Torrust Tracker exposes three different services. //! //! - A REST [`API`](crate::servers::apis) -//! - One or more [`UDP`](crate::servers::udp) trackers +//! - One or more [`UDP`](torrust_udp_tracker_server) trackers //! - One or more [`HTTP`](torrust_axum_http_tracker_server) trackers //! //! # Installation @@ -395,7 +395,7 @@ //! bind_address = "0.0.0.0:6969" //! ``` //! -//! Refer to the [`UDP`](crate::servers::udp) documentation for more information about the [`UDP`](crate::servers::udp) tracker. +//! Refer to the [`UDP`](torrust_udp_tracker_server) documentation for more information about the [`UDP`](torrust_udp_tracker_server) tracker. //! //! If you want to know more about the UDP tracker protocol: //! @@ -407,7 +407,7 @@ //! //! - The core tracker [`core`] //! - The tracker REST [`API`](crate::servers::apis) -//! - The [`UDP`](crate::servers::udp) tracker +//! - The [`UDP`](torrust_udp_tracker_server) tracker //! - The [`HTTP`](torrust_axum_http_tracker_server) tracker //! //! ![Torrust Tracker Components](https://raw.githubusercontent.com/torrust/torrust-tracker/main/docs/media/torrust-tracker-components.png) @@ -446,7 +446,7 @@ //! - [Wikipedia: UDP tracker](https://en.wikipedia.org/wiki/UDP_tracker) //! - [BEP 15: UDP Tracker Protocol for `BitTorrent`](https://www.bittorrent.org/beps/bep_0015.html) //! -//! See [`UDP`](crate::servers::udp) for more details on the UDP tracker. +//! See [`UDP`](torrust_udp_tracker_server) for more details on the UDP tracker. //! //! ## HTTP tracker //! diff --git a/src/servers/mod.rs b/src/servers/mod.rs index 8dea8a10d..de756162d 100644 --- a/src/servers/mod.rs +++ b/src/servers/mod.rs @@ -1,3 +1,2 @@ //! Servers. Services that can be started and stopped. pub mod apis; -pub mod udp; diff --git a/src/shared/bit_torrent/common.rs b/src/shared/bit_torrent/common.rs index 0364071c6..c954655e2 100644 --- a/src/shared/bit_torrent/common.rs +++ b/src/shared/bit_torrent/common.rs @@ -1,16 +1,3 @@ //! `BitTorrent` protocol primitive types //! //! [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) - -/// The maximum number of torrents that can be returned in an `scrape` response. -/// -/// The [BEP 15. UDP Tracker Protocol for `BitTorrent`](https://www.bittorrent.org/beps/bep_0015.html) -/// defines this limit: -/// -/// "Up to about 74 torrents can be scraped at once. A full scrape can't be done -/// with this protocol." -/// -/// The [BEP 48. Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) -/// does not specifically mention this limit, but the limit is being used for -/// both the UDP and HTTP trackers since it's applied at the domain level. -pub const MAX_SCRAPE_TORRENTS: u8 = 74; diff --git a/src/shared/bit_torrent/tracker/udp/mod.rs b/src/shared/bit_torrent/tracker/udp/mod.rs index 1ceb8a08b..eb38d99fd 100644 --- a/src/shared/bit_torrent/tracker/udp/mod.rs +++ b/src/shared/bit_torrent/tracker/udp/mod.rs @@ -1,6 +1,3 @@ -/// The maximum number of bytes in a UDP packet. -pub const MAX_PACKET_SIZE: usize = 1496; - /// A magic 64-bit integer constant defined in the protocol that is used to /// identify the protocol. pub const PROTOCOL_ID: i64 = 0x0417_2710_1980; diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index bde3e9f5d..553b68902 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -14,7 +14,7 @@ async fn health_check_endpoint_should_return_status_ok_when_there_is_no_services let env = Started::new(&configuration.health_check_api.into(), Registar::default()).await; - let response = get(&format!("http://{}/health_check", env.state.binding)).await; + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); @@ -54,7 +54,7 @@ mod api { let config = configuration.health_check_api.clone(); let env = Started::new(&config.into(), registar).await; - let response = get(&format!("http://{}/health_check", env.state.binding)).await; + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); @@ -76,7 +76,7 @@ mod api { assert_eq!( details.info, format!( - "checking api health check at: http://{}/api/health_check", + "checking api health check at: http://{}/api/health_check", // DevSkim: ignore DS137138 service.bind_address() ) ); @@ -105,7 +105,7 @@ mod api { let config = configuration.health_check_api.clone(); let env = Started::new(&config.into(), registar).await; - let response = get(&format!("http://{}/health_check", env.state.binding)).await; + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); @@ -131,7 +131,7 @@ mod api { ); assert_eq!( details.info, - format!("checking api health check at: http://{binding}/api/health_check") + format!("checking api health check at: http://{binding}/api/health_check") // DevSkim: ignore DS137138 ); env.stop().await.expect("it should stop the service"); @@ -164,7 +164,7 @@ mod http { let config = configuration.health_check_api.clone(); let env = Started::new(&config.into(), registar).await; - let response = get(&format!("http://{}/health_check", env.state.binding)).await; + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); @@ -185,7 +185,7 @@ mod http { assert_eq!( details.info, format!( - "checking http tracker health check at: http://{}/health_check", + "checking http tracker health check at: http://{}/health_check", // DevSkim: ignore DS137138 service.bind_address() ) ); @@ -214,7 +214,7 @@ mod http { let config = configuration.health_check_api.clone(); let env = Started::new(&config.into(), registar).await; - let response = get(&format!("http://{}/health_check", env.state.binding)).await; + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); @@ -240,7 +240,7 @@ mod http { ); assert_eq!( details.info, - format!("checking http tracker health check at: http://{binding}/health_check") + format!("checking http tracker health check at: http://{binding}/health_check") // DevSkim: ignore DS137138 ); env.stop().await.expect("it should stop the service"); @@ -273,7 +273,7 @@ mod udp { let config = configuration.health_check_api.clone(); let env = Started::new(&config.into(), registar).await; - let response = get(&format!("http://{}/health_check", env.state.binding)).await; + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); @@ -320,7 +320,7 @@ mod udp { let config = configuration.health_check_api.clone(); let env = Started::new(&config.into(), registar).await; - let response = get(&format!("http://{}/health_check", env.state.binding)).await; + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 assert_eq!(response.status(), 200); assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); diff --git a/tests/servers/udp/contract.rs b/tests/servers/udp/contract.rs index f0f647443..78a511bd4 100644 --- a/tests/servers/udp/contract.rs +++ b/tests/servers/udp/contract.rs @@ -8,8 +8,8 @@ use core::panic; use aquatic_udp_protocol::{ConnectRequest, ConnectionId, Response, TransactionId}; use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; -use torrust_tracker_lib::shared::bit_torrent::tracker::udp::MAX_PACKET_SIZE; use torrust_tracker_test_helpers::configuration; +use torrust_udp_tracker_server::MAX_PACKET_SIZE; use crate::common::logging; use crate::servers::udp::asserts::get_error_response_message; diff --git a/tests/servers/udp/environment.rs b/tests/servers/udp/environment.rs index c53f7a723..7d91fe535 100644 --- a/tests/servers/udp/environment.rs +++ b/tests/servers/udp/environment.rs @@ -6,10 +6,10 @@ use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; -use torrust_tracker_lib::servers::udp::server::spawner::Spawner; -use torrust_tracker_lib::servers::udp::server::states::{Running, Stopped}; -use torrust_tracker_lib::servers::udp::server::Server; use torrust_tracker_primitives::peer; +use torrust_udp_tracker_server::server::spawner::Spawner; +use torrust_udp_tracker_server::server::states::{Running, Stopped}; +use torrust_udp_tracker_server::server::Server; pub struct Environment where diff --git a/tests/servers/udp/mod.rs b/tests/servers/udp/mod.rs index 4a89b667a..c52115081 100644 --- a/tests/servers/udp/mod.rs +++ b/tests/servers/udp/mod.rs @@ -1,7 +1,7 @@ -use torrust_tracker_lib::servers::udp::server::states::Running; - pub mod asserts; pub mod contract; pub mod environment; +use torrust_udp_tracker_server::server::states::Running; + pub type Started = environment::Environment; From 35c686574973dca96b51c6cd545410395b3c2a8e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Feb 2025 12:45:29 +0000 Subject: [PATCH 0817/1297] refactor: remove unused code --- src/lib.rs | 1 - src/shared/bit_torrent/common.rs | 3 - src/shared/bit_torrent/mod.rs | 71 ----------------------- src/shared/bit_torrent/tracker/mod.rs | 1 - src/shared/bit_torrent/tracker/udp/mod.rs | 3 - src/shared/mod.rs | 4 -- 6 files changed, 83 deletions(-) delete mode 100644 src/shared/bit_torrent/common.rs delete mode 100644 src/shared/bit_torrent/mod.rs delete mode 100644 src/shared/bit_torrent/tracker/mod.rs delete mode 100644 src/shared/bit_torrent/tracker/udp/mod.rs delete mode 100644 src/shared/mod.rs diff --git a/src/lib.rs b/src/lib.rs index fa18fd7c8..100a297fe 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -495,7 +495,6 @@ pub mod bootstrap; pub mod console; pub mod container; pub mod servers; -pub mod shared; /// This code needs to be copied into each crate. /// Working version, for production. diff --git a/src/shared/bit_torrent/common.rs b/src/shared/bit_torrent/common.rs deleted file mode 100644 index c954655e2..000000000 --- a/src/shared/bit_torrent/common.rs +++ /dev/null @@ -1,3 +0,0 @@ -//! `BitTorrent` protocol primitive types -//! -//! [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html) diff --git a/src/shared/bit_torrent/mod.rs b/src/shared/bit_torrent/mod.rs deleted file mode 100644 index 7d6b12f09..000000000 --- a/src/shared/bit_torrent/mod.rs +++ /dev/null @@ -1,71 +0,0 @@ -//! Common code for the `BitTorrent` protocol. -//! -//! # Glossary -//! -//! - [Announce](#announce) -//! - [Info Hash](#info-hash) -//! - [Leecher](#leechers) -//! - [Peer ID](#peer-id) -//! - [Peer List](#peer-list) -//! - [Peer](#peer) -//! - [Scrape](#scrape) -//! - [Seeders](#seeders) -//! - [Swarm](#swarm) -//! - [Tracker](#tracker) -//! -//! Glossary of `BitTorrent` terms. -//! -//! # Announce -//! -//! A request to the tracker to announce the presence of a peer. -//! -//! ## Info Hash -//! -//! A unique identifier for a torrent. -//! -//! ## Leecher -//! -//! Peers that are only downloading data. -//! -//! ## Peer ID -//! -//! A unique identifier for a peer. -//! -//! ## Peer List -//! -//! A list of peers that are downloading a torrent. -//! -//! ## Peer -//! -//! A client that is downloading or uploading a torrent. -//! -//! ## Scrape -//! -//! A request to the tracker to get information about a torrent. -//! -//! ## Seeder -//! -//! Peers that are only uploading data. -//! -//! ## Swarm -//! -//! A group of peers that are downloading the same torrent. -//! -//! ## Tracker -//! -//! A server that keeps track of peers that are downloading a torrent. -//! -//! # Links -//! -//! Description | Link -//! ---|--- -//! `BitTorrent.org`. A forum for developers to exchange ideas about the direction of the `BitTorrent` protocol | -//! Wikipedia entry for Glossary of `BitTorrent` term | -//! `BitTorrent` Specification Wiki | -//! Vuze Wiki. A `BitTorrent` client implementation | -//! `libtorrent`. Complete C++ bittorrent implementation| -//! UDP Tracker Protocol docs by `libtorrent` | -//! Percent Encoding spec | -//!Bencode & bdecode in your browser | -pub mod common; -pub mod tracker; diff --git a/src/shared/bit_torrent/tracker/mod.rs b/src/shared/bit_torrent/tracker/mod.rs deleted file mode 100644 index 7e5aaa137..000000000 --- a/src/shared/bit_torrent/tracker/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod udp; diff --git a/src/shared/bit_torrent/tracker/udp/mod.rs b/src/shared/bit_torrent/tracker/udp/mod.rs deleted file mode 100644 index eb38d99fd..000000000 --- a/src/shared/bit_torrent/tracker/udp/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -/// A magic 64-bit integer constant defined in the protocol that is used to -/// identify the protocol. -pub const PROTOCOL_ID: i64 = 0x0417_2710_1980; diff --git a/src/shared/mod.rs b/src/shared/mod.rs deleted file mode 100644 index 3b4a46e67..000000000 --- a/src/shared/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! Modules with generic logic used by several modules. -//! -//! - [`bit_torrent`]: `BitTorrent` protocol related logic. -pub mod bit_torrent; From aa415bdc2ad7f1cfac110ee9a6bb86e2f7b07a9e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Feb 2025 16:21:05 +0000 Subject: [PATCH 0818/1297] refactor: [#1285] extract axum-tracker-api-server --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 45 +- Cargo.toml | 9 +- packages/axum-tracker-api-server/Cargo.toml | 48 ++ packages/axum-tracker-api-server/LICENSE | 661 ++++++++++++++++++ packages/axum-tracker-api-server/README.md | 11 + .../axum-tracker-api-server/src/lib.rs | 16 +- .../axum-tracker-api-server/src}/routes.rs | 2 +- .../axum-tracker-api-server/src}/server.rs | 4 +- .../src}/v1/context/auth_key/forms.rs | 0 .../src}/v1/context/auth_key/handlers.rs | 18 +- .../src}/v1/context/auth_key/mod.rs | 2 +- .../src}/v1/context/auth_key/resources.rs | 2 +- .../src}/v1/context/auth_key/responses.rs | 6 +- .../src}/v1/context/auth_key/routes.rs | 6 +- .../src}/v1/context/health_check/handlers.rs | 2 +- .../src}/v1/context/health_check/mod.rs | 2 +- .../src}/v1/context/health_check/resources.rs | 2 +- .../src}/v1/context/mod.rs | 0 .../src}/v1/context/stats/handlers.rs | 4 +- .../src}/v1/context/stats/mod.rs | 2 +- .../src}/v1/context/stats/resources.rs | 2 +- .../src}/v1/context/stats/responses.rs | 2 +- .../src}/v1/context/stats/routes.rs | 6 +- .../src}/v1/context/torrent/handlers.rs | 14 +- .../src}/v1/context/torrent/mod.rs | 4 +- .../src/v1/context/torrent/resources/mod.rs | 4 + .../src}/v1/context/torrent/resources/peer.rs | 0 .../v1/context/torrent/resources/torrent.rs | 6 +- .../src}/v1/context/torrent/responses.rs | 2 +- .../src}/v1/context/torrent/routes.rs | 6 +- .../src}/v1/context/whitelist/handlers.rs | 18 +- .../src}/v1/context/whitelist/mod.rs | 0 .../src}/v1/context/whitelist/responses.rs | 4 +- .../src}/v1/context/whitelist/routes.rs | 6 +- .../src}/v1/middlewares/auth.rs | 2 +- .../src}/v1/middlewares/mod.rs | 0 .../axum-tracker-api-server/src}/v1/mod.rs | 10 +- .../src}/v1/responses.rs | 0 .../axum-tracker-api-server/src}/v1/routes.rs | 0 src/app.rs | 9 +- src/bootstrap/jobs/tracker_apis.rs | 7 +- src/lib.rs | 15 +- .../apis/v1/context/torrent/resources/mod.rs | 4 - src/servers/mod.rs | 2 - tests/servers/api/environment.rs | 2 +- tests/servers/api/mod.rs | 2 +- tests/servers/api/v1/asserts.rs | 6 +- .../api/v1/contract/context/health_check.rs | 2 +- .../servers/api/v1/contract/context/stats.rs | 2 +- .../api/v1/contract/context/torrent.rs | 4 +- 51 files changed, 870 insertions(+), 114 deletions(-) create mode 100644 packages/axum-tracker-api-server/Cargo.toml create mode 100644 packages/axum-tracker-api-server/LICENSE create mode 100644 packages/axum-tracker-api-server/README.md rename src/servers/apis/mod.rs => packages/axum-tracker-api-server/src/lib.rs (93%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/routes.rs (99%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/server.rs (99%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/auth_key/forms.rs (100%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/auth_key/handlers.rs (83%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/auth_key/mod.rs (97%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/auth_key/resources.rs (97%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/auth_key/responses.rs (87%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/auth_key/routes.rs (87%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/health_check/handlers.rs (71%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/health_check/mod.rs (85%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/health_check/resources.rs (74%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/mod.rs (100%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/stats/handlers.rs (90%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/stats/mod.rs (93%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/stats/resources.rs (99%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/stats/responses.rs (98%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/stats/routes.rs (70%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/torrent/handlers.rs (88%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/torrent/mod.rs (92%) create mode 100644 packages/axum-tracker-api-server/src/v1/context/torrent/resources/mod.rs rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/torrent/resources/peer.rs (100%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/torrent/resources/torrent.rs (95%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/torrent/responses.rs (90%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/torrent/routes.rs (77%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/whitelist/handlers.rs (72%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/whitelist/mod.rs (100%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/whitelist/responses.rs (84%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/context/whitelist/routes.rs (82%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/middlewares/auth.rs (97%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/middlewares/mod.rs (100%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/mod.rs (58%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/responses.rs (100%) rename {src/servers/apis => packages/axum-tracker-api-server/src}/v1/routes.rs (100%) delete mode 100644 src/servers/apis/v1/context/torrent/resources/mod.rs delete mode 100644 src/servers/mod.rs diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 259a97728..e492d7490 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -64,6 +64,7 @@ jobs: cargo publish -p torrust-axum-health-check-api-server cargo publish -p torrust-axum-http-tracker-server cargo publish -p torrust-axum-server + cargo publish -p torrust-axum-tracker-api-server cargo publish -p torrust-torrust-server-lib cargo publish -p torrust-tracker cargo publish -p torrust-tracker-api-client diff --git a/Cargo.lock b/Cargo.lock index 22cdc002a..a46aa30b1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4402,6 +4402,42 @@ dependencies = [ "tracing", ] +[[package]] +name = "torrust-axum-tracker-api-server" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "axum", + "axum-extra", + "axum-server", + "bittorrent-http-tracker-core", + "bittorrent-primitives", + "bittorrent-tracker-core", + "bittorrent-udp-tracker-core", + "derive_more", + "futures", + "hyper", + "local-ip-address", + "mockall", + "reqwest", + "serde", + "serde_json", + "serde_with", + "thiserror 2.0.11", + "tokio", + "torrust-axum-server", + "torrust-server-lib", + "torrust-tracker-api-client", + "torrust-tracker-api-core", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-primitives", + "torrust-tracker-test-helpers", + "tower 0.5.2", + "tower-http", + "tracing", +] + [[package]] name = "torrust-server-lib" version = "3.0.0-develop" @@ -4418,8 +4454,6 @@ version = "3.0.0-develop" dependencies = [ "anyhow", "aquatic_udp_protocol", - "axum", - "axum-extra", "axum-server", "bittorrent-http-tracker-core", "bittorrent-primitives", @@ -4430,10 +4464,8 @@ dependencies = [ "clap", "crossbeam-skiplist", "dashmap", - "derive_more", "figment", "futures", - "hyper", "local-ip-address", "mockall", "parking_lot", @@ -4449,12 +4481,11 @@ dependencies = [ "serde_bytes", "serde_json", "serde_repr", - "serde_with", - "thiserror 2.0.11", "tokio", "torrust-axum-health-check-api-server", "torrust-axum-http-tracker-server", "torrust-axum-server", + "torrust-axum-tracker-api-server", "torrust-server-lib", "torrust-tracker-api-client", "torrust-tracker-api-core", @@ -4464,8 +4495,6 @@ dependencies = [ "torrust-tracker-test-helpers", "torrust-tracker-torrent-repository", "torrust-udp-tracker-server", - "tower 0.5.2", - "tower-http", "tracing", "tracing-subscriber", "url", diff --git a/Cargo.toml b/Cargo.toml index d8c739440..92d0aa5dc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,8 +35,6 @@ version = "3.0.0-develop" [dependencies] anyhow = "1" aquatic_udp_protocol = "0" -axum = { version = "0", features = ["macros"] } -axum-extra = { version = "0", features = ["query"] } axum-server = { version = "0", features = ["tls-rustls-no-provider"] } bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "packages/http-tracker-core" } bittorrent-primitives = "0.1.0" @@ -47,10 +45,8 @@ chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } crossbeam-skiplist = "0" dashmap = "6" -derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } figment = "0" futures = "0" -hyper = "1" parking_lot = "0" percent-encoding = "2" r2d2 = "0" @@ -64,12 +60,11 @@ serde_bencode = "0" serde_bytes = "0" serde_json = { version = "1", features = ["preserve_order"] } serde_repr = "0" -serde_with = { version = "3", features = ["json"] } -thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "packages/axum-health-check-api-server" } torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "packages/axum-http-tracker-server" } torrust-axum-server = { version = "3.0.0-develop", path = "packages/axum-server" } +torrust-axum-tracker-api-server = { version = "3.0.0-develop", path = "packages/axum-tracker-api-server" } torrust-server-lib = { version = "3.0.0-develop", path = "packages/server-lib" } torrust-tracker-api-core = { version = "3.0.0-develop", path = "packages/tracker-api-core" } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } @@ -77,8 +72,6 @@ torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/co torrust-tracker-primitives = { version = "3.0.0-develop", path = "packages/primitives" } torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "packages/torrent-repository" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "packages/udp-tracker-server" } -tower = { version = "0", features = ["timeout"] } -tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" tracing-subscriber = { version = "0", features = ["json"] } url = { version = "2", features = ["serde"] } diff --git a/packages/axum-tracker-api-server/Cargo.toml b/packages/axum-tracker-api-server/Cargo.toml new file mode 100644 index 000000000..7c7455fc4 --- /dev/null +++ b/packages/axum-tracker-api-server/Cargo.toml @@ -0,0 +1,48 @@ +[package] +authors.workspace = true +description = "The Torrust Tracker API." +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +keywords = ["axum", "bittorrent", "http", "server", "torrust", "tracker"] +license.workspace = true +name = "torrust-axum-tracker-api-server" +publish.workspace = true +readme = "README.md" +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +axum = { version = "0", features = ["macros"] } +axum-extra = { version = "0", features = ["query"] } +axum-server = { version = "0", features = ["tls-rustls-no-provider"] } +bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "../http-tracker-core" } +bittorrent-primitives = "0.1.0" +bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "../udp-tracker-core" } +derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } +futures = "0" +hyper = "1" +reqwest = { version = "0", features = ["json"] } +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["preserve_order"] } +serde_with = { version = "3", features = ["json"] } +thiserror = "2" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } +torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +torrust-tracker-api-core = { version = "3.0.0-develop", path = "../tracker-api-core" } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tower = { version = "0", features = ["timeout"] } +tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } +tracing = "0" + +[dev-dependencies] +local-ip-address = "0" +mockall = "0" +torrust-tracker-api-client = { version = "3.0.0-develop", path = "../tracker-api-client" } +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/axum-tracker-api-server/LICENSE b/packages/axum-tracker-api-server/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/axum-tracker-api-server/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/axum-tracker-api-server/README.md b/packages/axum-tracker-api-server/README.md new file mode 100644 index 000000000..6a0415828 --- /dev/null +++ b/packages/axum-tracker-api-server/README.md @@ -0,0 +1,11 @@ +# Torrust Tracker API + +The Torrust Tracker Rest API. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-axum-tracker-api-server). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/src/servers/apis/mod.rs b/packages/axum-tracker-api-server/src/lib.rs similarity index 93% rename from src/servers/apis/mod.rs rename to packages/axum-tracker-api-server/src/lib.rs index 0451b46c0..c3591908e 100644 --- a/src/servers/apis/mod.rs +++ b/packages/axum-tracker-api-server/src/lib.rs @@ -60,7 +60,7 @@ //! ``` //! //! The response will be a JSON object. For example, the [tracker statistics -//! endpoint](crate::servers::apis::v1::context::stats#get-tracker-statistics): +//! endpoint](crate::v1::context::stats#get-tracker-statistics): //! //! ```json //! { @@ -101,7 +101,7 @@ //! //! Refer to [`torrust-tracker-configuration`](torrust_tracker_configuration) //! for more information about the API configuration and to the -//! [`auth`](crate::servers::apis::v1::middlewares::auth) middleware for more +//! [`auth`](crate::v1::middlewares::auth) middleware for more //! information about the authentication process. //! //! # Setup SSL (optional) @@ -158,6 +158,18 @@ pub mod server; pub mod v1; use serde::{Deserialize, Serialize}; +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; pub const API_LOG_TARGET: &str = "API"; diff --git a/src/servers/apis/routes.rs b/packages/axum-tracker-api-server/src/routes.rs similarity index 99% rename from src/servers/apis/routes.rs rename to packages/axum-tracker-api-server/src/routes.rs index 64f6f0cb8..492e0dc37 100644 --- a/src/servers/apis/routes.rs +++ b/packages/axum-tracker-api-server/src/routes.rs @@ -31,7 +31,7 @@ use tracing::{instrument, Level, Span}; use super::v1; use super::v1::context::health_check::handlers::health_check_handler; use super::v1::middlewares::auth::State; -use crate::servers::apis::API_LOG_TARGET; +use crate::API_LOG_TARGET; /// Add all API routes to the router. #[instrument(skip(http_api_container, access_tokens))] diff --git a/src/servers/apis/server.rs b/packages/axum-tracker-api-server/src/server.rs similarity index 99% rename from src/servers/apis/server.rs rename to packages/axum-tracker-api-server/src/server.rs index 4c3484ded..65d8ca27a 100644 --- a/src/servers/apis/server.rs +++ b/packages/axum-tracker-api-server/src/server.rs @@ -43,7 +43,7 @@ use torrust_tracker_configuration::AccessTokens; use tracing::{instrument, Level}; use super::routes::router; -use crate::servers::apis::API_LOG_TARGET; +use crate::API_LOG_TARGET; /// Errors that can occur when starting or stopping the API server. #[derive(Debug, Error)] @@ -300,7 +300,7 @@ mod tests { use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use crate::servers::apis::server::{ApiServer, Launcher}; + use crate::server::{ApiServer, Launcher}; fn initialize_global_services(configuration: &Configuration) { initialize_static(); diff --git a/src/servers/apis/v1/context/auth_key/forms.rs b/packages/axum-tracker-api-server/src/v1/context/auth_key/forms.rs similarity index 100% rename from src/servers/apis/v1/context/auth_key/forms.rs rename to packages/axum-tracker-api-server/src/v1/context/auth_key/forms.rs diff --git a/src/servers/apis/v1/context/auth_key/handlers.rs b/packages/axum-tracker-api-server/src/v1/context/auth_key/handlers.rs similarity index 83% rename from src/servers/apis/v1/context/auth_key/handlers.rs rename to packages/axum-tracker-api-server/src/v1/context/auth_key/handlers.rs index c8d4c25b0..10530287c 100644 --- a/src/servers/apis/v1/context/auth_key/handlers.rs +++ b/packages/axum-tracker-api-server/src/v1/context/auth_key/handlers.rs @@ -1,4 +1,4 @@ -//! API handlers for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. +//! API handlers for the [`auth_key`](crate::v1::context::auth_key) API context. use std::str::FromStr; use std::sync::Arc; use std::time::Duration; @@ -14,8 +14,8 @@ use super::responses::{ auth_key_response, failed_to_delete_key_response, failed_to_generate_key_response, failed_to_reload_keys_response, invalid_auth_key_duration_response, invalid_auth_key_response, }; -use crate::servers::apis::v1::context::auth_key::resources::AuthKey; -use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_response}; +use crate::v1::context::auth_key::resources::AuthKey; +use crate::v1::responses::{invalid_auth_key_param_response, ok_response}; /// It handles the request to add a new authentication key. /// @@ -28,7 +28,7 @@ use crate::servers::apis::v1::responses::{invalid_auth_key_param_response, ok_re /// - `500` with serialized error in debug format. If the key couldn't be /// generated. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#generate-a-new-authentication-key) +/// Refer to the [API endpoint documentation](crate::v1::context::auth_key#generate-a-new-authentication-key) /// for more information about this endpoint. pub async fn add_auth_key_handler( State(keys_handler): State>, @@ -61,7 +61,7 @@ pub async fn add_auth_key_handler( /// - `500` with serialized error in debug format. If the key couldn't be /// generated. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#generate-a-new-authentication-key) +/// Refer to the [API endpoint documentation](crate::v1::context::auth_key#generate-a-new-authentication-key) /// for more information about this endpoint. /// /// This endpoint has been deprecated. Use [`add_auth_key_handler`]. @@ -101,12 +101,12 @@ pub struct KeyParam(String); /// /// It returns two types of responses: /// -/// - `200` with an json [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) +/// - `200` with an json [`ActionStatus::Ok`](crate::v1::responses::ActionStatus::Ok) /// response. If the key was deleted successfully. /// - `500` with serialized error in debug format. If the key couldn't be /// deleted. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#delete-an-authentication-key) +/// Refer to the [API endpoint documentation](crate::v1::context::auth_key#delete-an-authentication-key) /// for more information about this endpoint. pub async fn delete_auth_key_handler( State(keys_handler): State>, @@ -126,12 +126,12 @@ pub async fn delete_auth_key_handler( /// /// It returns two types of responses: /// -/// - `200` with an json [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) +/// - `200` with an json [`ActionStatus::Ok`](crate::v1::responses::ActionStatus::Ok) /// response. If the keys were successfully reloaded. /// - `500` with serialized error in debug format. If the they couldn't be /// reloaded. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key#reload-authentication-keys) +/// Refer to the [API endpoint documentation](crate::v1::context::auth_key#reload-authentication-keys) /// for more information about this endpoint. pub async fn reload_keys_handler(State(keys_handler): State>) -> Response { match keys_handler.load_peer_keys_from_database().await { diff --git a/src/servers/apis/v1/context/auth_key/mod.rs b/packages/axum-tracker-api-server/src/v1/context/auth_key/mod.rs similarity index 97% rename from src/servers/apis/v1/context/auth_key/mod.rs rename to packages/axum-tracker-api-server/src/v1/context/auth_key/mod.rs index b4112f21f..0a3937ef2 100644 --- a/src/servers/apis/v1/context/auth_key/mod.rs +++ b/packages/axum-tracker-api-server/src/v1/context/auth_key/mod.rs @@ -64,7 +64,7 @@ //! //! **Resource** //! -//! Refer to the API [`AuthKey`](crate::servers::apis::v1::context::auth_key::resources::AuthKey) +//! Refer to the API [`AuthKey`](crate::v1::context::auth_key::resources::AuthKey) //! resource for more information about the response attributes. //! //! # Delete an authentication key diff --git a/src/servers/apis/v1/context/auth_key/resources.rs b/packages/axum-tracker-api-server/src/v1/context/auth_key/resources.rs similarity index 97% rename from src/servers/apis/v1/context/auth_key/resources.rs rename to packages/axum-tracker-api-server/src/v1/context/auth_key/resources.rs index 8f5b4d309..357f1c365 100644 --- a/src/servers/apis/v1/context/auth_key/resources.rs +++ b/packages/axum-tracker-api-server/src/v1/context/auth_key/resources.rs @@ -1,4 +1,4 @@ -//! API resources for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. +//! API resources for the [`auth_key`](crate::v1::context::auth_key) API context. use bittorrent_tracker_core::authentication::{self, Key}; use serde::{Deserialize, Serialize}; diff --git a/src/servers/apis/v1/context/auth_key/responses.rs b/packages/axum-tracker-api-server/src/v1/context/auth_key/responses.rs similarity index 87% rename from src/servers/apis/v1/context/auth_key/responses.rs rename to packages/axum-tracker-api-server/src/v1/context/auth_key/responses.rs index 4905d9adc..8a0503703 100644 --- a/src/servers/apis/v1/context/auth_key/responses.rs +++ b/packages/axum-tracker-api-server/src/v1/context/auth_key/responses.rs @@ -1,11 +1,11 @@ -//! API responses for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. +//! API responses for the [`auth_key`](crate::v1::context::auth_key) API context. use std::error::Error; use axum::http::{header, StatusCode}; use axum::response::{IntoResponse, Response}; -use crate::servers::apis::v1::context::auth_key::resources::AuthKey; -use crate::servers::apis::v1::responses::{bad_request_response, unhandled_rejection_response}; +use crate::v1::context::auth_key::resources::AuthKey; +use crate::v1::responses::{bad_request_response, unhandled_rejection_response}; /// `200` response that contains the `AuthKey` resource as json. /// diff --git a/src/servers/apis/v1/context/auth_key/routes.rs b/packages/axum-tracker-api-server/src/v1/context/auth_key/routes.rs similarity index 87% rename from src/servers/apis/v1/context/auth_key/routes.rs rename to packages/axum-tracker-api-server/src/v1/context/auth_key/routes.rs index 623fb3459..64a0c1f11 100644 --- a/src/servers/apis/v1/context/auth_key/routes.rs +++ b/packages/axum-tracker-api-server/src/v1/context/auth_key/routes.rs @@ -1,11 +1,11 @@ -//! API routes for the [`auth_key`](crate::servers::apis::v1::context::auth_key) +//! API routes for the [`auth_key`](crate::v1::context::auth_key) //! API context. //! //! - `POST /key/:seconds_valid` //! - `DELETE /key/:key` //! - `GET /keys/reload` //! -//! Refer to the [API endpoint documentation](crate::servers::apis::v1::context::auth_key). +//! Refer to the [API endpoint documentation](crate::v1::context::auth_key). use std::sync::Arc; use axum::routing::{get, post}; @@ -14,7 +14,7 @@ use bittorrent_tracker_core::authentication::handler::KeysHandler; use super::handlers::{add_auth_key_handler, delete_auth_key_handler, generate_auth_key_handler, reload_keys_handler}; -/// It adds the routes to the router for the [`auth_key`](crate::servers::apis::v1::context::auth_key) API context. +/// It adds the routes to the router for the [`auth_key`](crate::v1::context::auth_key) API context. pub fn add(prefix: &str, router: Router, keys_handler: &Arc) -> Router { // Keys router diff --git a/src/servers/apis/v1/context/health_check/handlers.rs b/packages/axum-tracker-api-server/src/v1/context/health_check/handlers.rs similarity index 71% rename from src/servers/apis/v1/context/health_check/handlers.rs rename to packages/axum-tracker-api-server/src/v1/context/health_check/handlers.rs index bfbeab549..dfcad1f56 100644 --- a/src/servers/apis/v1/context/health_check/handlers.rs +++ b/packages/axum-tracker-api-server/src/v1/context/health_check/handlers.rs @@ -1,4 +1,4 @@ -//! API handlers for the [`stats`](crate::servers::apis::v1::context::health_check) +//! API handlers for the [`stats`](crate::v1::context::health_check) //! API context. use axum::Json; diff --git a/src/servers/apis/v1/context/health_check/mod.rs b/packages/axum-tracker-api-server/src/v1/context/health_check/mod.rs similarity index 85% rename from src/servers/apis/v1/context/health_check/mod.rs rename to packages/axum-tracker-api-server/src/v1/context/health_check/mod.rs index b73849511..6b1a1475f 100644 --- a/src/servers/apis/v1/context/health_check/mod.rs +++ b/packages/axum-tracker-api-server/src/v1/context/health_check/mod.rs @@ -28,7 +28,7 @@ //! //! **Resource** //! -//! Refer to the API [`Stats`](crate::servers::apis::v1::context::health_check::resources::Report) +//! Refer to the API [`Stats`](crate::context::health_check::resources::Report) //! resource for more information about the response attributes. pub mod handlers; pub mod resources; diff --git a/src/servers/apis/v1/context/health_check/resources.rs b/packages/axum-tracker-api-server/src/v1/context/health_check/resources.rs similarity index 74% rename from src/servers/apis/v1/context/health_check/resources.rs rename to packages/axum-tracker-api-server/src/v1/context/health_check/resources.rs index 9830e643c..5ea5871f8 100644 --- a/src/servers/apis/v1/context/health_check/resources.rs +++ b/packages/axum-tracker-api-server/src/v1/context/health_check/resources.rs @@ -1,4 +1,4 @@ -//! API resources for the [`stats`](crate::servers::apis::v1::context::health_check) +//! API resources for the [`stats`](crate::v1::context::health_check) //! API context. use serde::{Deserialize, Serialize}; diff --git a/src/servers/apis/v1/context/mod.rs b/packages/axum-tracker-api-server/src/v1/context/mod.rs similarity index 100% rename from src/servers/apis/v1/context/mod.rs rename to packages/axum-tracker-api-server/src/v1/context/mod.rs diff --git a/src/servers/apis/v1/context/stats/handlers.rs b/packages/axum-tracker-api-server/src/v1/context/stats/handlers.rs similarity index 90% rename from src/servers/apis/v1/context/stats/handlers.rs rename to packages/axum-tracker-api-server/src/v1/context/stats/handlers.rs index b8adfc3e3..e0149cb23 100644 --- a/src/servers/apis/v1/context/stats/handlers.rs +++ b/packages/axum-tracker-api-server/src/v1/context/stats/handlers.rs @@ -1,4 +1,4 @@ -//! API handlers for the [`stats`](crate::servers::apis::v1::context::stats) +//! API handlers for the [`stats`](crate::v1::context::stats) //! API context. use std::sync::Arc; @@ -35,7 +35,7 @@ pub struct QueryParams { /// You can add the GET parameter `format=prometheus` to get the stats in /// Prometheus Text Exposition Format. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::stats#get-tracker-statistics) +/// Refer to the [API endpoint documentation](crate::v1::context::stats#get-tracker-statistics) /// for more information about this endpoint. #[allow(clippy::type_complexity)] pub async fn get_stats_handler( diff --git a/src/servers/apis/v1/context/stats/mod.rs b/packages/axum-tracker-api-server/src/v1/context/stats/mod.rs similarity index 93% rename from src/servers/apis/v1/context/stats/mod.rs rename to packages/axum-tracker-api-server/src/v1/context/stats/mod.rs index 80f37f73f..5c6b0a39c 100644 --- a/src/servers/apis/v1/context/stats/mod.rs +++ b/packages/axum-tracker-api-server/src/v1/context/stats/mod.rs @@ -44,7 +44,7 @@ //! //! **Resource** //! -//! Refer to the API [`Stats`](crate::servers::apis::v1::context::stats::resources::Stats) +//! Refer to the API [`Stats`](crate::v1::context::stats::resources::Stats) //! resource for more information about the response attributes. pub mod handlers; pub mod resources; diff --git a/src/servers/apis/v1/context/stats/resources.rs b/packages/axum-tracker-api-server/src/v1/context/stats/resources.rs similarity index 99% rename from src/servers/apis/v1/context/stats/resources.rs rename to packages/axum-tracker-api-server/src/v1/context/stats/resources.rs index 11169f31e..f27050e22 100644 --- a/src/servers/apis/v1/context/stats/resources.rs +++ b/packages/axum-tracker-api-server/src/v1/context/stats/resources.rs @@ -1,4 +1,4 @@ -//! API resources for the [`stats`](crate::servers::apis::v1::context::stats) +//! API resources for the [`stats`](crate::v1::context::stats) //! API context. use serde::{Deserialize, Serialize}; use torrust_tracker_api_core::statistics::services::TrackerMetrics; diff --git a/src/servers/apis/v1/context/stats/responses.rs b/packages/axum-tracker-api-server/src/v1/context/stats/responses.rs similarity index 98% rename from src/servers/apis/v1/context/stats/responses.rs rename to packages/axum-tracker-api-server/src/v1/context/stats/responses.rs index 0b4da778f..f68c1e062 100644 --- a/src/servers/apis/v1/context/stats/responses.rs +++ b/packages/axum-tracker-api-server/src/v1/context/stats/responses.rs @@ -1,4 +1,4 @@ -//! API responses for the [`stats`](crate::servers::apis::v1::context::stats) +//! API responses for the [`stats`](crate::v1::context::stats) //! API context. use axum::response::{IntoResponse, Json, Response}; use torrust_tracker_api_core::statistics::services::TrackerMetrics; diff --git a/src/servers/apis/v1/context/stats/routes.rs b/packages/axum-tracker-api-server/src/v1/context/stats/routes.rs similarity index 70% rename from src/servers/apis/v1/context/stats/routes.rs rename to packages/axum-tracker-api-server/src/v1/context/stats/routes.rs index df198eba6..e73de8625 100644 --- a/src/servers/apis/v1/context/stats/routes.rs +++ b/packages/axum-tracker-api-server/src/v1/context/stats/routes.rs @@ -1,8 +1,8 @@ -//! API routes for the [`stats`](crate::servers::apis::v1::context::stats) API context. +//! API routes for the [`stats`](crate::v1::context::stats) API context. //! //! - `GET /stats` //! -//! Refer to the [API endpoint documentation](crate::servers::apis::v1::context::stats). +//! Refer to the [API endpoint documentation](crate::v1::context::stats). use std::sync::Arc; use axum::routing::get; @@ -11,7 +11,7 @@ use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use super::handlers::get_stats_handler; -/// It adds the routes to the router for the [`stats`](crate::servers::apis::v1::context::stats) API context. +/// It adds the routes to the router for the [`stats`](crate::v1::context::stats) API context. pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { router.route( &format!("{prefix}/stats"), diff --git a/src/servers/apis/v1/context/torrent/handlers.rs b/packages/axum-tracker-api-server/src/v1/context/torrent/handlers.rs similarity index 88% rename from src/servers/apis/v1/context/torrent/handlers.rs rename to packages/axum-tracker-api-server/src/v1/context/torrent/handlers.rs index ce80d8fee..613abbdeb 100644 --- a/src/servers/apis/v1/context/torrent/handlers.rs +++ b/packages/axum-tracker-api-server/src/v1/context/torrent/handlers.rs @@ -1,4 +1,4 @@ -//! API handlers for the [`torrent`](crate::servers::apis::v1::context::torrent) +//! API handlers for the [`torrent`](crate::v1::context::torrent) //! API context. use std::fmt; use std::str::FromStr; @@ -15,17 +15,17 @@ use thiserror::Error; use torrust_tracker_primitives::pagination::Pagination; use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; -use crate::servers::apis::v1::responses::invalid_info_hash_param_response; -use crate::servers::apis::InfoHashParam; +use crate::v1::responses::invalid_info_hash_param_response; +use crate::InfoHashParam; /// It handles the request to get the torrent data. /// /// It returns: /// -/// - `200` response with a json [`Torrent`](crate::servers::apis::v1::context::torrent::resources::torrent::Torrent). +/// - `200` response with a json [`Torrent`](crate::v1::context::torrent::resources::torrent::Torrent). /// - `500` with serialized error in debug format if the torrent is not known. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent#get-a-torrent) +/// Refer to the [API endpoint documentation](crate::v1::context::torrent#get-a-torrent) /// for more information about this endpoint. pub async fn get_torrent_handler( State(in_memory_torrent_repository): State>, @@ -74,9 +74,9 @@ pub struct QueryParams { /// It handles the request to get a list of torrents. /// -/// It returns a `200` response with a json array with [`crate::servers::apis::v1::context::torrent::resources::torrent::ListItem`] resources. +/// It returns a `200` response with a json array with [`crate::v1::context::torrent::resources::torrent::ListItem`] resources. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent#list-torrents) +/// Refer to the [API endpoint documentation](crate::v1::context::torrent#list-torrents) /// for more information about this endpoint. pub async fn get_torrents_handler( State(in_memory_torrent_repository): State>, diff --git a/src/servers/apis/v1/context/torrent/mod.rs b/packages/axum-tracker-api-server/src/v1/context/torrent/mod.rs similarity index 92% rename from src/servers/apis/v1/context/torrent/mod.rs rename to packages/axum-tracker-api-server/src/v1/context/torrent/mod.rs index 1658e1748..1a62fef25 100644 --- a/src/servers/apis/v1/context/torrent/mod.rs +++ b/packages/axum-tracker-api-server/src/v1/context/torrent/mod.rs @@ -62,7 +62,7 @@ //! //! **Resource** //! -//! Refer to the API [`Torrent`](crate::servers::apis::v1::context::torrent::resources::torrent::Torrent) +//! Refer to the API [`Torrent`](crate::v1::context::torrent::resources::torrent::Torrent) //! resource for more information about the response attributes. //! //! # List torrents @@ -102,7 +102,7 @@ //! //! **Resource** //! -//! Refer to the API [`ListItem`](crate::servers::apis::v1::context::torrent::resources::torrent::ListItem) +//! Refer to the API [`ListItem`](crate::v1::context::torrent::resources::torrent::ListItem) //! resource for more information about the attributes for a single item in the //! response. //! diff --git a/packages/axum-tracker-api-server/src/v1/context/torrent/resources/mod.rs b/packages/axum-tracker-api-server/src/v1/context/torrent/resources/mod.rs new file mode 100644 index 000000000..8e31036d3 --- /dev/null +++ b/packages/axum-tracker-api-server/src/v1/context/torrent/resources/mod.rs @@ -0,0 +1,4 @@ +//! API resources for the [`torrent`](crate::v1::context::torrent) +//! API context. +pub mod peer; +pub mod torrent; diff --git a/src/servers/apis/v1/context/torrent/resources/peer.rs b/packages/axum-tracker-api-server/src/v1/context/torrent/resources/peer.rs similarity index 100% rename from src/servers/apis/v1/context/torrent/resources/peer.rs rename to packages/axum-tracker-api-server/src/v1/context/torrent/resources/peer.rs diff --git a/src/servers/apis/v1/context/torrent/resources/torrent.rs b/packages/axum-tracker-api-server/src/v1/context/torrent/resources/torrent.rs similarity index 95% rename from src/servers/apis/v1/context/torrent/resources/torrent.rs rename to packages/axum-tracker-api-server/src/v1/context/torrent/resources/torrent.rs index 5e4da5c16..1753b60b9 100644 --- a/src/servers/apis/v1/context/torrent/resources/torrent.rs +++ b/packages/axum-tracker-api-server/src/v1/context/torrent/resources/torrent.rs @@ -21,7 +21,7 @@ pub struct Torrent { /// The torrent's leechers counter. Active peers that are downloading the /// torrent. pub leechers: u64, - /// The torrent's peers. See [`Peer`](crate::servers::apis::v1::context::torrent::resources::peer::Peer). + /// The torrent's peers. See [`Peer`](crate::v1::context::torrent::resources::peer::Peer). #[serde(skip_serializing_if = "Option::is_none")] pub peers: Option>, } @@ -102,8 +102,8 @@ mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use super::Torrent; - use crate::servers::apis::v1::context::torrent::resources::peer::Peer; - use crate::servers::apis::v1::context::torrent::resources::torrent::ListItem; + use crate::v1::context::torrent::resources::peer::Peer; + use crate::v1::context::torrent::resources::torrent::ListItem; fn sample_peer() -> peer::Peer { peer::Peer { diff --git a/src/servers/apis/v1/context/torrent/responses.rs b/packages/axum-tracker-api-server/src/v1/context/torrent/responses.rs similarity index 90% rename from src/servers/apis/v1/context/torrent/responses.rs rename to packages/axum-tracker-api-server/src/v1/context/torrent/responses.rs index cd359247b..e498c6c59 100644 --- a/src/servers/apis/v1/context/torrent/responses.rs +++ b/packages/axum-tracker-api-server/src/v1/context/torrent/responses.rs @@ -1,4 +1,4 @@ -//! API responses for the [`torrent`](crate::servers::apis::v1::context::torrent) +//! API responses for the [`torrent`](crate::v1::context::torrent) //! API context. use axum::response::{IntoResponse, Json, Response}; use bittorrent_tracker_core::torrent::services::{BasicInfo, Info}; diff --git a/src/servers/apis/v1/context/torrent/routes.rs b/packages/axum-tracker-api-server/src/v1/context/torrent/routes.rs similarity index 77% rename from src/servers/apis/v1/context/torrent/routes.rs rename to packages/axum-tracker-api-server/src/v1/context/torrent/routes.rs index 615bd8d51..678fe7783 100644 --- a/src/servers/apis/v1/context/torrent/routes.rs +++ b/packages/axum-tracker-api-server/src/v1/context/torrent/routes.rs @@ -1,9 +1,9 @@ -//! API routes for the [`torrent`](crate::servers::apis::v1::context::torrent) API context. +//! API routes for the [`torrent`](crate::v1::context::torrent) API context. //! //! - `GET /torrent/:info_hash` //! - `GET /torrents` //! -//! Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent). +//! Refer to the [API endpoint documentation](crate::v1::context::torrent). use std::sync::Arc; use axum::routing::get; @@ -12,7 +12,7 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use super::handlers::{get_torrent_handler, get_torrents_handler}; -/// It adds the routes to the router for the [`torrent`](crate::servers::apis::v1::context::torrent) API context. +/// It adds the routes to the router for the [`torrent`](crate::v1::context::torrent) API context. pub fn add(prefix: &str, router: Router, in_memory_torrent_repository: &Arc) -> Router { // Torrents router diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/packages/axum-tracker-api-server/src/v1/context/whitelist/handlers.rs similarity index 72% rename from src/servers/apis/v1/context/whitelist/handlers.rs rename to packages/axum-tracker-api-server/src/v1/context/whitelist/handlers.rs index e33a215f2..bafa8aaff 100644 --- a/src/servers/apis/v1/context/whitelist/handlers.rs +++ b/packages/axum-tracker-api-server/src/v1/context/whitelist/handlers.rs @@ -1,4 +1,4 @@ -//! API handlers for the [`whitelist`](crate::servers::apis::v1::context::whitelist) +//! API handlers for the [`whitelist`](crate::v1::context::whitelist) //! API context. use std::str::FromStr; use std::sync::Arc; @@ -11,17 +11,17 @@ use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use super::responses::{ failed_to_reload_whitelist_response, failed_to_remove_torrent_from_whitelist_response, failed_to_whitelist_torrent_response, }; -use crate::servers::apis::v1::responses::{invalid_info_hash_param_response, ok_response}; -use crate::servers::apis::InfoHashParam; +use crate::v1::responses::{invalid_info_hash_param_response, ok_response}; +use crate::InfoHashParam; /// It handles the request to add a torrent to the whitelist. /// /// It returns: /// -/// - `200` response with a [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) in json. +/// - `200` response with a [`ActionStatus::Ok`](crate::v1::responses::ActionStatus::Ok) in json. /// - `500` with serialized error in debug format if the torrent couldn't be whitelisted. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#add-a-torrent-to-the-whitelist) +/// Refer to the [API endpoint documentation](crate::v1::context::whitelist#add-a-torrent-to-the-whitelist) /// for more information about this endpoint. pub async fn add_torrent_to_whitelist_handler( State(whitelist_manager): State>, @@ -40,11 +40,11 @@ pub async fn add_torrent_to_whitelist_handler( /// /// It returns: /// -/// - `200` response with a [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) in json. +/// - `200` response with a [`ActionStatus::Ok`](crate::v1::responses::ActionStatus::Ok) in json. /// - `500` with serialized error in debug format if the torrent couldn't be /// removed from the whitelisted. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#remove-a-torrent-from-the-whitelist) +/// Refer to the [API endpoint documentation](crate::v1::context::whitelist#remove-a-torrent-from-the-whitelist) /// for more information about this endpoint. pub async fn remove_torrent_from_whitelist_handler( State(whitelist_manager): State>, @@ -63,11 +63,11 @@ pub async fn remove_torrent_from_whitelist_handler( /// /// It returns: /// -/// - `200` response with a [`ActionStatus::Ok`](crate::servers::apis::v1::responses::ActionStatus::Ok) in json. +/// - `200` response with a [`ActionStatus::Ok`](crate::v1::responses::ActionStatus::Ok) in json. /// - `500` with serialized error in debug format if the torrent whitelist /// couldn't be reloaded from the database. /// -/// Refer to the [API endpoint documentation](crate::servers::apis::v1::context::whitelist#reload-the-whitelist) +/// Refer to the [API endpoint documentation](crate::v1::context::whitelist#reload-the-whitelist) /// for more information about this endpoint. pub async fn reload_whitelist_handler(State(whitelist_manager): State>) -> Response { match whitelist_manager.load_whitelist_from_database().await { diff --git a/src/servers/apis/v1/context/whitelist/mod.rs b/packages/axum-tracker-api-server/src/v1/context/whitelist/mod.rs similarity index 100% rename from src/servers/apis/v1/context/whitelist/mod.rs rename to packages/axum-tracker-api-server/src/v1/context/whitelist/mod.rs diff --git a/src/servers/apis/v1/context/whitelist/responses.rs b/packages/axum-tracker-api-server/src/v1/context/whitelist/responses.rs similarity index 84% rename from src/servers/apis/v1/context/whitelist/responses.rs rename to packages/axum-tracker-api-server/src/v1/context/whitelist/responses.rs index ce901c2f0..1e4d66f7f 100644 --- a/src/servers/apis/v1/context/whitelist/responses.rs +++ b/packages/axum-tracker-api-server/src/v1/context/whitelist/responses.rs @@ -1,10 +1,10 @@ -//! API responses for the [`whitelist`](crate::servers::apis::v1::context::whitelist) +//! API responses for the [`whitelist`](crate::v1::context::whitelist) //! API context. use std::error::Error; use axum::response::Response; -use crate::servers::apis::v1::responses::unhandled_rejection_response; +use crate::v1::responses::unhandled_rejection_response; /// `500` error response when a torrent cannot be removed from the whitelist. #[must_use] diff --git a/src/servers/apis/v1/context/whitelist/routes.rs b/packages/axum-tracker-api-server/src/v1/context/whitelist/routes.rs similarity index 82% rename from src/servers/apis/v1/context/whitelist/routes.rs rename to packages/axum-tracker-api-server/src/v1/context/whitelist/routes.rs index 316193cd6..c99b008b3 100644 --- a/src/servers/apis/v1/context/whitelist/routes.rs +++ b/packages/axum-tracker-api-server/src/v1/context/whitelist/routes.rs @@ -1,10 +1,10 @@ -//! API routes for the [`whitelist`](crate::servers::apis::v1::context::whitelist) API context. +//! API routes for the [`whitelist`](crate::v1::context::whitelist) API context. //! //! - `POST /whitelist/:info_hash` //! - `DELETE /whitelist/:info_hash` //! - `GET /whitelist/reload` //! -//! Refer to the [API endpoint documentation](crate::servers::apis::v1::context::torrent). +//! Refer to the [API endpoint documentation](crate::v1::context::torrent). use std::sync::Arc; use axum::routing::{delete, get, post}; @@ -13,7 +13,7 @@ use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use super::handlers::{add_torrent_to_whitelist_handler, reload_whitelist_handler, remove_torrent_from_whitelist_handler}; -/// It adds the routes to the router for the [`whitelist`](crate::servers::apis::v1::context::whitelist) API context. +/// It adds the routes to the router for the [`whitelist`](crate::v1::context::whitelist) API context. pub fn add(prefix: &str, router: Router, whitelist_manager: &Arc) -> Router { let prefix = format!("{prefix}/whitelist"); diff --git a/src/servers/apis/v1/middlewares/auth.rs b/packages/axum-tracker-api-server/src/v1/middlewares/auth.rs similarity index 97% rename from src/servers/apis/v1/middlewares/auth.rs rename to packages/axum-tracker-api-server/src/v1/middlewares/auth.rs index 58219c7ca..2ec046bed 100644 --- a/src/servers/apis/v1/middlewares/auth.rs +++ b/packages/axum-tracker-api-server/src/v1/middlewares/auth.rs @@ -30,7 +30,7 @@ use axum::response::{IntoResponse, Response}; use serde::Deserialize; use torrust_tracker_configuration::AccessTokens; -use crate::servers::apis::v1::responses::unhandled_rejection_response; +use crate::v1::responses::unhandled_rejection_response; /// Container for the `token` extracted from the query params. #[derive(Deserialize, Debug)] diff --git a/src/servers/apis/v1/middlewares/mod.rs b/packages/axum-tracker-api-server/src/v1/middlewares/mod.rs similarity index 100% rename from src/servers/apis/v1/middlewares/mod.rs rename to packages/axum-tracker-api-server/src/v1/middlewares/mod.rs diff --git a/src/servers/apis/v1/mod.rs b/packages/axum-tracker-api-server/src/v1/mod.rs similarity index 58% rename from src/servers/apis/v1/mod.rs rename to packages/axum-tracker-api-server/src/v1/mod.rs index 372ae0ff9..7910d7d4d 100644 --- a/src/servers/apis/v1/mod.rs +++ b/packages/axum-tracker-api-server/src/v1/mod.rs @@ -4,17 +4,17 @@ //! //! Context | Description | Version //! ---|---|--- -//! `Stats` | Tracker statistics | [`v1`](crate::servers::apis::v1::context::stats) -//! `Torrents` | Torrents | [`v1`](crate::servers::apis::v1::context::torrent) -//! `Whitelist` | Torrents whitelist | [`v1`](crate::servers::apis::v1::context::whitelist) -//! `Authentication keys` | Authentication keys | [`v1`](crate::servers::apis::v1::context::auth_key) +//! `Stats` | Tracker statistics | [`v1`](crate::v1::context::stats) +//! `Torrents` | Torrents | [`v1`](crate::v1::context::torrent) +//! `Whitelist` | Torrents whitelist | [`v1`](crate::v1::context::whitelist) +//! `Authentication keys` | Authentication keys | [`v1`](crate::v1::context::auth_key) //! //! > **NOTICE**: //! - The authentication keys are only used by the HTTP tracker. //! - The whitelist is only used when the tracker is running in `listed` or //! `private_listed` mode. //! -//! Refer to the [authentication middleware](crate::servers::apis::v1::middlewares::auth) +//! Refer to the [authentication middleware](crate::v1::middlewares::auth) //! for more information about the authentication process. pub mod context; pub mod middlewares; diff --git a/src/servers/apis/v1/responses.rs b/packages/axum-tracker-api-server/src/v1/responses.rs similarity index 100% rename from src/servers/apis/v1/responses.rs rename to packages/axum-tracker-api-server/src/v1/responses.rs diff --git a/src/servers/apis/v1/routes.rs b/packages/axum-tracker-api-server/src/v1/routes.rs similarity index 100% rename from src/servers/apis/v1/routes.rs rename to packages/axum-tracker-api-server/src/v1/routes.rs diff --git a/src/app.rs b/src/app.rs index e94db66e3..27ffe7a4a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -30,7 +30,6 @@ use tracing::instrument; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; use crate::container::AppContainer; -use crate::servers; /// # Panics /// @@ -113,7 +112,13 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> let http_api_config = Arc::new(http_api_config.clone()); let http_api_container = Arc::new(app_container.tracker_http_api_container(&http_api_config)); - if let Some(job) = tracker_apis::start_job(http_api_container, registar.give_form(), servers::apis::Version::V1).await { + if let Some(job) = tracker_apis::start_job( + http_api_container, + registar.give_form(), + torrust_axum_tracker_api_server::Version::V1, + ) + .await + { jobs.push(job); } } else { diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 458d25367..93850d65e 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -26,14 +26,13 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; use torrust_axum_server::tsl::make_rust_tls; +use torrust_axum_tracker_api_server::server::{ApiServer, Launcher}; +use torrust_axum_tracker_api_server::Version; use torrust_server_lib::registar::ServiceRegistrationForm; use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::AccessTokens; use tracing::instrument; -use crate::servers::apis::server::{ApiServer, Launcher}; -use crate::servers::apis::Version; - /// This is the message that the "launcher" spawned task sends to the main /// application process to notify the API server was successfully started. /// @@ -97,13 +96,13 @@ async fn start_v1( mod tests { use std::sync::Arc; + use torrust_axum_tracker_api_server::Version; use torrust_server_lib::registar::Registar; use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::initialize_global_services; use crate::bootstrap::jobs::tracker_apis::start_job; - use crate::servers::apis::Version; #[tokio::test] async fn it_should_start_http_tracker() { diff --git a/src/lib.rs b/src/lib.rs index 100a297fe..5f05df8b2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -55,7 +55,7 @@ //! //! From the end-user perspective the Torrust Tracker exposes three different services. //! -//! - A REST [`API`](crate::servers::apis) +//! - A REST [`API`](torrust_axum_tracker_api_server) //! - One or more [`UDP`](torrust_udp_tracker_server) trackers //! - One or more [`HTTP`](torrust_axum_http_tracker_server) trackers //! @@ -124,7 +124,7 @@ //! By default the tracker uses `SQLite` and the database file name `sqlite3.db`. //! //! You only need the `tls` directory in case you are setting up SSL for the HTTP tracker or the tracker API. -//! Visit [`HTTP`](torrust_axum_http_tracker_server) or [`API`](crate::servers::apis) if you want to know how you can use HTTPS. +//! Visit [`HTTP`](torrust_axum_http_tracker_server) or [`API`](torrust_axum_tracker_api_server) if you want to know how you can use HTTPS. //! //! ## Install from sources //! @@ -280,7 +280,7 @@ //! } //! ``` //! -//! Refer to the [`API`](crate::servers::apis) documentation for more information about the [`API`](crate::servers::apis) endpoints. +//! Refer to the [`API`](torrust_axum_tracker_api_server) documentation for more information about the [`API`](torrust_axum_tracker_api_server) endpoints. //! //! ## HTTP tracker //! @@ -359,7 +359,7 @@ //! //! If the tracker is running in `private` or `private_listed` mode you will need to provide a valid authentication key. //! -//! Right now the only way to add new keys is via the REST [`API`](crate::servers::apis). The endpoint `POST /api/vi/key/:duration_in_seconds` +//! Right now the only way to add new keys is via the REST [`API`](torrust_axum_tracker_api_server). The endpoint `POST /api/vi/key/:duration_in_seconds` //! will return an expiring key that will be valid for `duration_in_seconds` seconds. //! //! Using `curl` you can create a 2-minute valid auth key: @@ -379,7 +379,7 @@ //! ``` //! //! You can also use the Torrust Tracker together with the [Torrust Index](https://github.com/torrust/torrust-index). If that's the case, -//! the Index will create the keys by using the tracker [API](crate::servers::apis). +//! the Index will create the keys by using the tracker [API](torrust_axum_tracker_api_server). //! //! ## UDP tracker //! @@ -406,7 +406,7 @@ //! Torrust Tracker has four main components: //! //! - The core tracker [`core`] -//! - The tracker REST [`API`](crate::servers::apis) +//! - The tracker REST [`API`](torrust_axum_tracker_api_server) //! - The [`UDP`](torrust_udp_tracker_server) tracker //! - The [`HTTP`](torrust_axum_http_tracker_server) tracker //! @@ -434,7 +434,7 @@ //! - Torrents: to get peers for a torrent //! - Whitelist: to handle the torrent whitelist when the tracker runs on `listed` or `private_listed` mode //! -//! See [`API`](crate::servers::apis) for more details on the REST API. +//! See [`API`](torrust_axum_tracker_api_server) for more details on the REST API. //! //! ## UDP tracker //! @@ -494,7 +494,6 @@ pub mod app; pub mod bootstrap; pub mod console; pub mod container; -pub mod servers; /// This code needs to be copied into each crate. /// Working version, for production. diff --git a/src/servers/apis/v1/context/torrent/resources/mod.rs b/src/servers/apis/v1/context/torrent/resources/mod.rs deleted file mode 100644 index a6dbff726..000000000 --- a/src/servers/apis/v1/context/torrent/resources/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! API resources for the [`torrent`](crate::servers::apis::v1::context::torrent) -//! API context. -pub mod peer; -pub mod torrent; diff --git a/src/servers/mod.rs b/src/servers/mod.rs deleted file mode 100644 index de756162d..000000000 --- a/src/servers/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -//! Servers. Services that can be started and stopped. -pub mod apis; diff --git a/tests/servers/api/environment.rs b/tests/servers/api/environment.rs index 5534a99a9..b9373b533 100644 --- a/tests/servers/api/environment.rs +++ b/tests/servers/api/environment.rs @@ -7,11 +7,11 @@ use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use futures::executor::block_on; use torrust_axum_server::tsl::make_rust_tls; +use torrust_axum_tracker_api_server::server::{ApiServer, Launcher, Running, Stopped}; use torrust_server_lib::registar::Registar; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::{logging, Configuration}; -use torrust_tracker_lib::servers::apis::server::{ApiServer, Launcher, Running, Stopped}; use torrust_tracker_primitives::peer; pub struct Environment diff --git a/tests/servers/api/mod.rs b/tests/servers/api/mod.rs index 8f5f6d016..1176d8a6b 100644 --- a/tests/servers/api/mod.rs +++ b/tests/servers/api/mod.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use bittorrent_tracker_core::databases::Database; -use torrust_tracker_lib::servers::apis::server; +use torrust_axum_tracker_api_server::server; pub mod connection_info; pub mod environment; diff --git a/tests/servers/api/v1/asserts.rs b/tests/servers/api/v1/asserts.rs index b56144d3f..c1a06594a 100644 --- a/tests/servers/api/v1/asserts.rs +++ b/tests/servers/api/v1/asserts.rs @@ -1,9 +1,9 @@ // code-review: should we use macros to return the exact line where the assert fails? use reqwest::Response; -use torrust_tracker_lib::servers::apis::v1::context::auth_key::resources::AuthKey; -use torrust_tracker_lib::servers::apis::v1::context::stats::resources::Stats; -use torrust_tracker_lib::servers::apis::v1::context::torrent::resources::torrent::{ListItem, Torrent}; +use torrust_axum_tracker_api_server::v1::context::auth_key::resources::AuthKey; +use torrust_axum_tracker_api_server::v1::context::stats::resources::Stats; +use torrust_axum_tracker_api_server::v1::context::torrent::resources::torrent::{ListItem, Torrent}; // Resource responses diff --git a/tests/servers/api/v1/contract/context/health_check.rs b/tests/servers/api/v1/contract/context/health_check.rs index 4d37917fc..b0812dc8c 100644 --- a/tests/servers/api/v1/contract/context/health_check.rs +++ b/tests/servers/api/v1/contract/context/health_check.rs @@ -1,5 +1,5 @@ +use torrust_axum_tracker_api_server::v1::context::health_check::resources::{Report, Status}; use torrust_tracker_api_client::v1::client::get; -use torrust_tracker_lib::servers::apis::v1::context::health_check::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use url::Url; diff --git a/tests/servers/api/v1/contract/context/stats.rs b/tests/servers/api/v1/contract/context/stats.rs index 55d3cd869..3d8e6481c 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/tests/servers/api/v1/contract/context/stats.rs @@ -1,8 +1,8 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; +use torrust_axum_tracker_api_server::v1::context::stats::resources::Stats; use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; -use torrust_tracker_lib::servers::apis::v1::context::stats::resources::Stats; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/tests/servers/api/v1/contract/context/torrent.rs index 8aa408173..c2d5bfbaf 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/tests/servers/api/v1/contract/context/torrent.rs @@ -1,10 +1,10 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; +use torrust_axum_tracker_api_server::v1::context::torrent::resources::peer::Peer; +use torrust_axum_tracker_api_server::v1::context::torrent::resources::torrent::{self, Torrent}; use torrust_tracker_api_client::common::http::{Query, QueryParam}; use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; -use torrust_tracker_lib::servers::apis::v1::context::torrent::resources::peer::Peer; -use torrust_tracker_lib::servers::apis::v1::context::torrent::resources::torrent::{self, Torrent}; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::configuration; use uuid::Uuid; From 229f9ee0de0416794b7a26aa1bbe1c0aefb6bdd2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Feb 2025 18:50:24 +0000 Subject: [PATCH 0819/1297] refactor: [#1320] move code from axum-http-tracker-server pkg to http-protocol pkg --- Cargo.lock | 1 - packages/axum-http-tracker-server/Cargo.toml | 1 - .../src/v1/extractors/authentication_key.rs | 4 +- .../src/v1/handlers/common/auth.rs | 40 ------------------- .../src/v1/handlers/common/mod.rs | 3 -- .../src/v1/handlers/common/peer_ip.rs | 30 -------------- .../src/v1/handlers/mod.rs | 1 - packages/http-protocol/src/v1/auth.rs | 17 ++++++++ packages/http-protocol/src/v1/mod.rs | 1 + .../http-protocol/src/v1/responses/error.rs | 28 +++++++++++++ 10 files changed, 47 insertions(+), 79 deletions(-) delete mode 100644 packages/axum-http-tracker-server/src/v1/handlers/common/auth.rs delete mode 100644 packages/axum-http-tracker-server/src/v1/handlers/common/mod.rs delete mode 100644 packages/axum-http-tracker-server/src/v1/handlers/common/peer_ip.rs create mode 100644 packages/http-protocol/src/v1/auth.rs diff --git a/Cargo.lock b/Cargo.lock index a46aa30b1..cead25a49 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4369,7 +4369,6 @@ dependencies = [ "hyper", "reqwest", "serde", - "thiserror 2.0.11", "tokio", "torrust-axum-server", "torrust-server-lib", diff --git a/packages/axum-http-tracker-server/Cargo.toml b/packages/axum-http-tracker-server/Cargo.toml index 98c807a92..abb419e4a 100644 --- a/packages/axum-http-tracker-server/Cargo.toml +++ b/packages/axum-http-tracker-server/Cargo.toml @@ -27,7 +27,6 @@ futures = "0" hyper = "1" reqwest = { version = "0", features = ["json"] } serde = { version = "1", features = ["derive"] } -thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } diff --git a/packages/axum-http-tracker-server/src/v1/extractors/authentication_key.rs b/packages/axum-http-tracker-server/src/v1/extractors/authentication_key.rs index 89781f48b..7dca7f42e 100644 --- a/packages/axum-http-tracker-server/src/v1/extractors/authentication_key.rs +++ b/packages/axum-http-tracker-server/src/v1/extractors/authentication_key.rs @@ -49,13 +49,11 @@ use axum::extract::rejection::PathRejection; use axum::extract::{FromRequestParts, Path}; use axum::http::request::Parts; use axum::response::{IntoResponse, Response}; -use bittorrent_http_tracker_protocol::v1::responses; +use bittorrent_http_tracker_protocol::v1::{auth, responses}; use bittorrent_tracker_core::authentication::Key; use hyper::StatusCode; use serde::Deserialize; -use crate::v1::handlers::common::auth; - /// Extractor for the [`Key`] struct. pub struct Extract(pub Key); diff --git a/packages/axum-http-tracker-server/src/v1/handlers/common/auth.rs b/packages/axum-http-tracker-server/src/v1/handlers/common/auth.rs deleted file mode 100644 index fe1dddd7d..000000000 --- a/packages/axum-http-tracker-server/src/v1/handlers/common/auth.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! HTTP server authentication error and conversion to -//! [`responses::error::Error`] -//! response. -use std::panic::Location; - -use bittorrent_http_tracker_protocol::v1::responses; -use bittorrent_tracker_core::authentication; -use thiserror::Error; - -/// Authentication error. -/// -/// When the tracker is private, the authentication key is required in the URL -/// path. These are the possible errors that can occur when extracting the key -/// from the URL path. -#[derive(Debug, Error)] -pub enum Error { - #[error("Invalid format for authentication key param. Error in {location}")] - InvalidKeyFormat { location: &'static Location<'static> }, - - #[error("Cannot extract authentication key param from URL path. Error in {location}")] - CannotExtractKeyParam { location: &'static Location<'static> }, -} - -impl From for responses::error::Error { - fn from(err: Error) -> Self { - responses::error::Error { - failure_reason: format!("Tracker authentication error: {err}"), - } - } -} - -#[must_use] -pub fn map_auth_error_to_error_response(err: &authentication::Error) -> responses::error::Error { - // code_review: this could not been implemented with the trait: - // impl From for responses::error::Error - // Consider moving the trait implementation to the http-protocol package. - responses::error::Error { - failure_reason: format!("Tracker authentication error: {err}"), - } -} diff --git a/packages/axum-http-tracker-server/src/v1/handlers/common/mod.rs b/packages/axum-http-tracker-server/src/v1/handlers/common/mod.rs deleted file mode 100644 index 30eaf37b7..000000000 --- a/packages/axum-http-tracker-server/src/v1/handlers/common/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -//! Common logic for HTTP handlers. -pub mod auth; -pub mod peer_ip; diff --git a/packages/axum-http-tracker-server/src/v1/handlers/common/peer_ip.rs b/packages/axum-http-tracker-server/src/v1/handlers/common/peer_ip.rs deleted file mode 100644 index 8d51f9817..000000000 --- a/packages/axum-http-tracker-server/src/v1/handlers/common/peer_ip.rs +++ /dev/null @@ -1,30 +0,0 @@ -//! Logic to convert peer IP resolution errors into responses. -//! -//! The HTTP tracker may fail to resolve the peer IP address. This module -//! contains the logic to convert those -//! [`PeerIpResolutionError`](bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::PeerIpResolutionError) -//! errors into responses. - -#[cfg(test)] -mod tests { - use std::panic::Location; - - use bittorrent_http_tracker_protocol::v1::responses; - use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::PeerIpResolutionError; - - fn assert_error_response(error: &responses::error::Error, error_message: &str) { - assert!( - error.failure_reason.contains(error_message), - "Error response does not contain message: '{error_message}'. Error: {error:?}" - ); - } - - #[test] - fn it_should_map_a_peer_ip_resolution_error_into_an_error_response() { - let response = responses::error::Error::from(PeerIpResolutionError::MissingRightMostXForwardedForIp { - location: Location::caller(), - }); - - assert_error_response(&response, "Error resolving peer IP"); - } -} diff --git a/packages/axum-http-tracker-server/src/v1/handlers/mod.rs b/packages/axum-http-tracker-server/src/v1/handlers/mod.rs index ce58e09b3..785213696 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/mod.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/mod.rs @@ -1,5 +1,4 @@ //! Axum [`handlers`](axum#handlers) for the HTTP server. pub mod announce; -pub mod common; pub mod health_check; pub mod scrape; diff --git a/packages/http-protocol/src/v1/auth.rs b/packages/http-protocol/src/v1/auth.rs new file mode 100644 index 000000000..ad2e59e53 --- /dev/null +++ b/packages/http-protocol/src/v1/auth.rs @@ -0,0 +1,17 @@ +use std::panic::Location; + +use thiserror::Error; + +/// Authentication error. +/// +/// When the tracker is private, the authentication key is required in the URL +/// path. These are the possible errors that can occur when extracting the key +/// from the URL path. +#[derive(Debug, Error)] +pub enum Error { + #[error("Invalid format for authentication key param. Error in {location}")] + InvalidKeyFormat { location: &'static Location<'static> }, + + #[error("Cannot extract authentication key param from URL path. Error in {location}")] + CannotExtractKeyParam { location: &'static Location<'static> }, +} diff --git a/packages/http-protocol/src/v1/mod.rs b/packages/http-protocol/src/v1/mod.rs index d52ba7609..6de653e66 100644 --- a/packages/http-protocol/src/v1/mod.rs +++ b/packages/http-protocol/src/v1/mod.rs @@ -1,3 +1,4 @@ +pub mod auth; pub mod query; pub mod requests; pub mod responses; diff --git a/packages/http-protocol/src/v1/responses/error.rs b/packages/http-protocol/src/v1/responses/error.rs index 8dc28e938..2e7a36d0a 100644 --- a/packages/http-protocol/src/v1/responses/error.rs +++ b/packages/http-protocol/src/v1/responses/error.rs @@ -13,6 +13,7 @@ //! > code. use serde::Serialize; +use crate::v1::auth; use crate::v1::services::peer_ip_resolver::PeerIpResolutionError; /// `Error` response for the HTTP tracker. @@ -47,6 +48,14 @@ impl Error { } } +impl From for Error { + fn from(err: auth::Error) -> Self { + Self { + failure_reason: format!("Tracker authentication error: {err}"), + } + } +} + impl From for Error { fn from(err: PeerIpResolutionError) -> Self { Self { @@ -89,8 +98,11 @@ impl From for Error { #[cfg(test)] mod tests { + use std::panic::Location; use super::Error; + use crate::v1::responses; + use crate::v1::services::peer_ip_resolver::PeerIpResolutionError; #[test] fn http_tracker_errors_can_be_bencoded() { @@ -100,4 +112,20 @@ mod tests { assert_eq!(err.write(), "d14:failure reason13:error messagee"); // cspell:disable-line } + + fn assert_error_response(error: &responses::error::Error, error_message: &str) { + assert!( + error.failure_reason.contains(error_message), + "Error response does not contain message: '{error_message}'. Error: {error:?}" + ); + } + + #[test] + fn it_should_map_a_peer_ip_resolution_error_into_an_error_response() { + let response = responses::error::Error::from(PeerIpResolutionError::MissingRightMostXForwardedForIp { + location: Location::caller(), + }); + + assert_error_response(&response, "Error resolving peer IP"); + } } From a841e03e98d7f27d241ea67a925455c449aaed4c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Feb 2025 08:54:29 +0000 Subject: [PATCH 0820/1297] refactor: [#1316] move health check API integration tests to pkg It moved the integration tests for the Health Check API from the main lib to the `axum-health-check-api-server`. Some tests have not been moved becuase they depend on other server pakages. They basically use the test "environments" from other servers which are not publicly exposed yet. They are only used in integration tests. We will move those environments to the corresponding server so they can be used in other packages to run the servers. --- Cargo.lock | 7 + .../axum-health-check-api-server/Cargo.toml | 5 + .../src}/environment.rs | 25 ++- .../axum-health-check-api-server/src/lib.rs | 1 + .../tests/integration.rs | 19 +++ .../tests/server/client.rs | 5 + .../tests/server/contract.rs | 29 ++++ .../tests/server/mod.rs | 2 + packages/test-helpers/Cargo.toml | 2 + packages/test-helpers/src/lib.rs | 1 + packages/test-helpers/src/logging.rs | 156 ++++++++++++++++++ tests/servers/health_check_api/contract.rs | 37 +---- tests/servers/health_check_api/mod.rs | 3 - 13 files changed, 250 insertions(+), 42 deletions(-) rename {tests/servers/health_check_api => packages/axum-health-check-api-server/src}/environment.rs (81%) create mode 100644 packages/axum-health-check-api-server/tests/integration.rs create mode 100644 packages/axum-health-check-api-server/tests/server/client.rs create mode 100644 packages/axum-health-check-api-server/tests/server/contract.rs create mode 100644 packages/axum-health-check-api-server/tests/server/mod.rs create mode 100644 packages/test-helpers/src/logging.rs diff --git a/Cargo.lock b/Cargo.lock index cead25a49..4c85cf407 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4343,13 +4343,18 @@ dependencies = [ "axum-server", "futures", "hyper", + "reqwest", "serde", "serde_json", "tokio", "torrust-axum-server", "torrust-server-lib", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-test-helpers", "tower-http", "tracing", + "tracing-subscriber", ] [[package]] @@ -4618,6 +4623,8 @@ version = "3.0.0-develop" dependencies = [ "rand 0.9.0", "torrust-tracker-configuration", + "tracing", + "tracing-subscriber", ] [[package]] diff --git a/packages/axum-health-check-api-server/Cargo.toml b/packages/axum-health-check-api-server/Cargo.toml index 37e49f9e7..17c269aae 100644 --- a/packages/axum-health-check-api-server/Cargo.toml +++ b/packages/axum-health-check-api-server/Cargo.toml @@ -23,7 +23,12 @@ serde_json = { version = "1", features = ["preserve_order"] } tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" [dev-dependencies] +reqwest = { version = "0", features = ["json"] } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } +tracing-subscriber = { version = "0", features = ["json"] } diff --git a/tests/servers/health_check_api/environment.rs b/packages/axum-health-check-api-server/src/environment.rs similarity index 81% rename from tests/servers/health_check_api/environment.rs rename to packages/axum-health-check-api-server/src/environment.rs index f8c1209cd..c1fb0547a 100644 --- a/tests/servers/health_check_api/environment.rs +++ b/packages/axum-health-check-api-server/src/environment.rs @@ -3,11 +3,14 @@ use std::sync::Arc; use tokio::sync::oneshot::{self, Sender}; use tokio::task::JoinHandle; -use torrust_axum_health_check_api_server::{server, HEALTH_CHECK_API_LOG_TARGET}; use torrust_server_lib::registar::Registar; -use torrust_server_lib::signals::{self, Halted, Started}; +use torrust_server_lib::signals::{self, Halted as SignalHalted, Started as SignalStarted}; use torrust_tracker_configuration::HealthCheckApi; +use crate::{server, HEALTH_CHECK_API_LOG_TARGET}; + +pub type Started = Environment; + #[derive(Debug)] pub enum Error { #[allow(dead_code)] @@ -30,6 +33,7 @@ pub struct Environment { } impl Environment { + #[must_use] pub fn new(config: &Arc, registar: Registar) -> Self { let bind_to = config.bind_address; @@ -41,9 +45,13 @@ impl Environment { /// Start the test environment for the Health Check API. /// It runs the API server. + /// + /// # Panics + /// + /// Will panic if it cannot start the service in a spawned task. pub async fn start(self) -> Environment { - let (tx_start, rx_start) = oneshot::channel::(); - let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); + let (tx_start, rx_start) = oneshot::channel::(); + let (tx_halt, rx_halt) = tokio::sync::oneshot::channel::(); let register = self.registar.entries(); @@ -81,10 +89,17 @@ impl Environment { Environment::::new(config, registar).start().await } + /// # Errors + /// + /// Will return an error if it cannot send the halt signal. + /// + /// # Panics + /// + /// Will panic if it cannot shutdown the service. pub async fn stop(self) -> Result, Error> { self.state .halt_task - .send(Halted::Normal) + .send(SignalHalted::Normal) .map_err(|e| Error::Error(e.to_string()))?; let bind_to = self.state.task.await.expect("it should shutdown the service"); diff --git a/packages/axum-health-check-api-server/src/lib.rs b/packages/axum-health-check-api-server/src/lib.rs index 24c5232c8..6a3b4b34d 100644 --- a/packages/axum-health-check-api-server/src/lib.rs +++ b/packages/axum-health-check-api-server/src/lib.rs @@ -1,3 +1,4 @@ +pub mod environment; pub mod handlers; pub mod resources; pub mod responses; diff --git a/packages/axum-health-check-api-server/tests/integration.rs b/packages/axum-health-check-api-server/tests/integration.rs new file mode 100644 index 000000000..13ca963a3 --- /dev/null +++ b/packages/axum-health-check-api-server/tests/integration.rs @@ -0,0 +1,19 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` +mod server; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/packages/axum-health-check-api-server/tests/server/client.rs b/packages/axum-health-check-api-server/tests/server/client.rs new file mode 100644 index 000000000..3d8bdc7d6 --- /dev/null +++ b/packages/axum-health-check-api-server/tests/server/client.rs @@ -0,0 +1,5 @@ +use reqwest::Response; + +pub async fn get(path: &str) -> Response { + reqwest::Client::builder().build().unwrap().get(path).send().await.unwrap() +} diff --git a/packages/axum-health-check-api-server/tests/server/contract.rs b/packages/axum-health-check-api-server/tests/server/contract.rs new file mode 100644 index 000000000..2bd5d292e --- /dev/null +++ b/packages/axum-health-check-api-server/tests/server/contract.rs @@ -0,0 +1,29 @@ +use torrust_axum_health_check_api_server::environment::Started; +use torrust_axum_health_check_api_server::resources::{Report, Status}; +use torrust_server_lib::registar::Registar; +use torrust_tracker_test_helpers::{configuration, logging}; + +use crate::server::client::get; + +#[tokio::test] +async fn health_check_endpoint_should_return_status_ok_when_there_is_no_services_registered() { + logging::setup(); + + let configuration = configuration::ephemeral_with_no_services(); + + let env = Started::new(&configuration.health_check_api.into(), Registar::default()).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report = response + .json::() + .await + .expect("it should be able to get the report as json"); + + assert_eq!(report.status, Status::None); + + env.stop().await.expect("it should stop the service"); +} diff --git a/packages/axum-health-check-api-server/tests/server/mod.rs b/packages/axum-health-check-api-server/tests/server/mod.rs new file mode 100644 index 000000000..2676be6f9 --- /dev/null +++ b/packages/axum-health-check-api-server/tests/server/mod.rs @@ -0,0 +1,2 @@ +pub mod client; +pub mod contract; diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index ad291d209..3495c314a 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -17,3 +17,5 @@ version.workspace = true [dependencies] rand = "0" torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +tracing = "0" +tracing-subscriber = { version = "0", features = ["json"] } diff --git a/packages/test-helpers/src/lib.rs b/packages/test-helpers/src/lib.rs index e66ea2adc..bd67ca770 100644 --- a/packages/test-helpers/src/lib.rs +++ b/packages/test-helpers/src/lib.rs @@ -2,4 +2,5 @@ //! //! A collection of functions and types to help with testing the tracker server. pub mod configuration; +pub mod logging; pub mod random; diff --git a/packages/test-helpers/src/logging.rs b/packages/test-helpers/src/logging.rs new file mode 100644 index 000000000..564074f3e --- /dev/null +++ b/packages/test-helpers/src/logging.rs @@ -0,0 +1,156 @@ +//! Setup for logging in tests. +use std::collections::VecDeque; +use std::io; +use std::sync::{Mutex, MutexGuard, Once, OnceLock}; + +use torrust_tracker_configuration::logging::TraceStyle; +use tracing::level_filters::LevelFilter; +use tracing_subscriber::fmt::MakeWriter; + +static INIT: Once = Once::new(); + +/// A global buffer containing the latest lines captured from logs. +#[doc(hidden)] +pub fn captured_logs_buffer() -> &'static Mutex { + static CAPTURED_LOGS_GLOBAL_BUFFER: OnceLock> = OnceLock::new(); + CAPTURED_LOGS_GLOBAL_BUFFER.get_or_init(|| Mutex::new(CircularBuffer::new(10000, 200))) +} + +pub fn setup() { + INIT.call_once(|| { + tracing_init(LevelFilter::ERROR, &TraceStyle::Default); + }); +} + +fn tracing_init(level_filter: LevelFilter, style: &TraceStyle) { + let mock_writer = LogCapturer::new(captured_logs_buffer()); + + let builder = tracing_subscriber::fmt() + .with_max_level(level_filter) + .with_ansi(true) + .with_test_writer() + .with_writer(mock_writer); + + let () = match style { + TraceStyle::Default => builder.init(), + TraceStyle::Pretty(display_filename) => builder.pretty().with_file(*display_filename).init(), + TraceStyle::Compact => builder.compact().init(), + TraceStyle::Json => builder.json().init(), + }; + + tracing::info!("Logging initialized"); +} + +/// It returns true is there is a log line containing all the texts passed. +/// +/// # Panics +/// +/// Will panic if it can't get the lock for the global buffer or convert it into +/// a vec. +#[must_use] +#[allow(dead_code)] +pub fn logs_contains_a_line_with(texts: &[&str]) -> bool { + // code-review: we can search directly in the buffer instead of converting + // the buffer into a string but that would slow down the tests because + // cloning should be faster that locking the buffer for searching. + // Because the buffer is not big. + let logs = String::from_utf8(captured_logs_buffer().lock().unwrap().as_vec()).unwrap(); + + for line in logs.split('\n') { + if contains(line, texts) { + return true; + } + } + + false +} + +#[allow(dead_code)] +fn contains(text: &str, texts: &[&str]) -> bool { + texts.iter().all(|&word| text.contains(word)) +} + +/// A tracing writer which captures the latests logs lines into a buffer. +/// It's used to capture the logs in the tests. +#[derive(Debug)] +pub struct LogCapturer<'a> { + logs: &'a Mutex, +} + +impl<'a> LogCapturer<'a> { + pub fn new(buf: &'a Mutex) -> Self { + Self { logs: buf } + } + + fn buf(&self) -> io::Result> { + self.logs.lock().map_err(|_| io::Error::from(io::ErrorKind::Other)) + } +} + +impl io::Write for LogCapturer<'_> { + fn write(&mut self, buf: &[u8]) -> io::Result { + print!("{}", String::from_utf8(buf.to_vec()).unwrap()); + + let mut target = self.buf()?; + + target.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.buf()?.flush() + } +} + +impl MakeWriter<'_> for LogCapturer<'_> { + type Writer = Self; + + fn make_writer(&self) -> Self::Writer { + LogCapturer::new(self.logs) + } +} + +#[derive(Debug)] +pub struct CircularBuffer { + max_size: usize, + buffer: VecDeque, +} + +impl CircularBuffer { + #[must_use] + pub fn new(max_lines: usize, average_line_size: usize) -> Self { + Self { + max_size: max_lines * average_line_size, + buffer: VecDeque::with_capacity(max_lines * average_line_size), + } + } + + /// # Errors + /// + /// Won't return any error. + #[allow(clippy::unnecessary_wraps)] + pub fn write(&mut self, buf: &[u8]) -> io::Result { + for &byte in buf { + if self.buffer.len() == self.max_size { + // Remove oldest byte to make space + self.buffer.pop_front(); + } + self.buffer.push_back(byte); + } + + Ok(buf.len()) + } + + /// # Errors + /// + /// Won't return any error. + #[allow(clippy::unnecessary_wraps)] + #[allow(clippy::unused_self)] + pub fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + + #[must_use] + pub fn as_vec(&self) -> Vec { + self.buffer.iter().copied().collect() + } +} diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index 553b68902..ab6b0d48e 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -1,44 +1,13 @@ -use torrust_axum_health_check_api_server::resources::{Report, Status}; -use torrust_server_lib::registar::Registar; -use torrust_tracker_test_helpers::configuration; - -use crate::common::logging; -use crate::servers::health_check_api::client::get; -use crate::servers::health_check_api::Started; - -#[tokio::test] -async fn health_check_endpoint_should_return_status_ok_when_there_is_no_services_registered() { - logging::setup(); - - let configuration = configuration::ephemeral_with_no_services(); - - let env = Started::new(&configuration.health_check_api.into(), Registar::default()).await; - - let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 - - assert_eq!(response.status(), 200); - assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); - - let report = response - .json::() - .await - .expect("it should be able to get the report as json"); - - assert_eq!(report.status, Status::None); - - env.stop().await.expect("it should stop the service"); -} - mod api { use std::sync::Arc; + use torrust_axum_health_check_api_server::environment::Started; use torrust_axum_health_check_api_server::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; use crate::servers::api; use crate::servers::health_check_api::client::get; - use crate::servers::health_check_api::Started; #[tokio::test] pub(crate) async fn it_should_return_good_health_for_api_service() { @@ -142,12 +111,12 @@ mod api { mod http { use std::sync::Arc; + use torrust_axum_health_check_api_server::environment::Started; use torrust_axum_health_check_api_server::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; use crate::servers::health_check_api::client::get; - use crate::servers::health_check_api::Started; use crate::servers::http; #[tokio::test] @@ -251,12 +220,12 @@ mod http { mod udp { use std::sync::Arc; + use torrust_axum_health_check_api_server::environment::Started; use torrust_axum_health_check_api_server::resources::{Report, Status}; use torrust_tracker_test_helpers::configuration; use crate::common::logging; use crate::servers::health_check_api::client::get; - use crate::servers::health_check_api::Started; use crate::servers::udp; #[tokio::test] diff --git a/tests/servers/health_check_api/mod.rs b/tests/servers/health_check_api/mod.rs index 9e15c5f62..2676be6f9 100644 --- a/tests/servers/health_check_api/mod.rs +++ b/tests/servers/health_check_api/mod.rs @@ -1,5 +1,2 @@ pub mod client; pub mod contract; -pub mod environment; - -pub type Started = environment::Environment; From 08efc3bc8e2e67823f32821268f9ecaee4145b24 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Feb 2025 09:57:51 +0000 Subject: [PATCH 0821/1297] refactor: [#1316] move tracker API integration tests to pkg --- Cargo.lock | 3 +- Cargo.toml | 1 - packages/axum-tracker-api-server/Cargo.toml | 3 ++ .../src}/environment.rs | 30 ++++++++++++++++- packages/axum-tracker-api-server/src/lib.rs | 1 + .../tests/common/fixtures.rs | 11 +++++++ .../tests/common/mod.rs | 1 + .../tests/integration.rs | 20 ++++++++++++ .../tests/server}/connection_info.rs | 0 .../tests/server}/mod.rs | 10 ++---- .../tests/server}/v1/asserts.rs | 0 .../server}/v1/contract/authentication.rs | 8 ++--- .../server}/v1/contract/context/auth_key.rs | 22 +++++++------ .../v1/contract/context/health_check.rs | 6 ++-- .../tests/server}/v1/contract/context/mod.rs | 0 .../server}/v1/contract/context/stats.rs | 10 +++--- .../server}/v1/contract/context/torrent.rs | 14 ++++---- .../server}/v1/contract/context/whitelist.rs | 15 ++++----- .../tests/server}/v1/contract/fixtures.rs | 0 .../tests/server}/v1/contract/mod.rs | 1 - .../tests/server}/v1/mod.rs | 0 .../servers/api/v1/contract/configuration.rs | 32 ------------------- tests/servers/health_check_api/contract.rs | 5 ++- tests/servers/mod.rs | 3 +- 24 files changed, 109 insertions(+), 87 deletions(-) rename {tests/servers/api => packages/axum-tracker-api-server/src}/environment.rs (86%) create mode 100644 packages/axum-tracker-api-server/tests/common/fixtures.rs create mode 100644 packages/axum-tracker-api-server/tests/common/mod.rs create mode 100644 packages/axum-tracker-api-server/tests/integration.rs rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/connection_info.rs (100%) rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/mod.rs (78%) rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/v1/asserts.rs (100%) rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/v1/contract/authentication.rs (92%) rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/v1/contract/context/auth_key.rs (95%) rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/v1/contract/context/health_check.rs (86%) rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/v1/contract/context/mod.rs (100%) rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/v1/contract/context/stats.rs (89%) rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/v1/contract/context/torrent.rs (96%) rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/v1/contract/context/whitelist.rs (96%) rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/v1/contract/fixtures.rs (100%) rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/v1/contract/mod.rs (71%) rename {tests/servers/api => packages/axum-tracker-api-server/tests/server}/v1/mod.rs (100%) delete mode 100644 tests/servers/api/v1/contract/configuration.rs diff --git a/Cargo.lock b/Cargo.lock index 4c85cf407..c753c7bc2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4440,6 +4440,8 @@ dependencies = [ "tower 0.5.2", "tower-http", "tracing", + "url", + "uuid", ] [[package]] @@ -4501,7 +4503,6 @@ dependencies = [ "torrust-udp-tracker-server", "tracing", "tracing-subscriber", - "url", "uuid", "zerocopy 0.7.35", ] diff --git a/Cargo.toml b/Cargo.toml index 92d0aa5dc..184fe38ed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -74,7 +74,6 @@ torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "packag torrust-udp-tracker-server = { version = "3.0.0-develop", path = "packages/udp-tracker-server" } tracing = "0" tracing-subscriber = { version = "0", features = ["json"] } -url = { version = "2", features = ["serde"] } uuid = { version = "1", features = ["v4"] } zerocopy = "0.7" diff --git a/packages/axum-tracker-api-server/Cargo.toml b/packages/axum-tracker-api-server/Cargo.toml index 7c7455fc4..480ee2a54 100644 --- a/packages/axum-tracker-api-server/Cargo.toml +++ b/packages/axum-tracker-api-server/Cargo.toml @@ -33,6 +33,7 @@ thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +torrust-tracker-api-client = { version = "3.0.0-develop", path = "../tracker-api-client" } torrust-tracker-api-core = { version = "3.0.0-develop", path = "../tracker-api-core" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } @@ -46,3 +47,5 @@ local-ip-address = "0" mockall = "0" torrust-tracker-api-client = { version = "3.0.0-develop", path = "../tracker-api-client" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } +url = { version = "2", features = ["serde"] } +uuid = { version = "1", features = ["v4"] } diff --git a/tests/servers/api/environment.rs b/packages/axum-tracker-api-server/src/environment.rs similarity index 86% rename from tests/servers/api/environment.rs rename to packages/axum-tracker-api-server/src/environment.rs index b9373b533..f6d6fb4e4 100644 --- a/tests/servers/api/environment.rs +++ b/packages/axum-tracker-api-server/src/environment.rs @@ -7,13 +7,16 @@ use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use futures::executor::block_on; use torrust_axum_server::tsl::make_rust_tls; -use torrust_axum_tracker_api_server::server::{ApiServer, Launcher, Running, Stopped}; use torrust_server_lib::registar::Registar; use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_primitives::peer; +use crate::server::{ApiServer, Launcher, Running, Stopped}; + +pub type Started = Environment; + pub struct Environment where S: std::fmt::Debug + std::fmt::Display, @@ -38,6 +41,11 @@ where } impl Environment { + /// # Panics + /// + /// Will panic if it cannot make the TSL configuration from the provided + /// configuration. + #[must_use] pub fn new(configuration: &Arc) -> Self { initialize_global_services(configuration); @@ -59,6 +67,9 @@ impl Environment { } } + /// # Panics + /// + /// Will panic if the server cannot be started. pub async fn start(self) -> Environment { let access_tokens = Arc::new( self.container @@ -89,6 +100,9 @@ impl Environment { Environment::::new(configuration).start().await } + /// # Panics + /// + /// Will panic if the server cannot be stopped. pub async fn stop(self) -> Environment { Environment { container: self.container, @@ -97,6 +111,11 @@ impl Environment { } } + /// # Panics + /// + /// Will panic if it cannot build the origin for the connection info from the + /// server local socket address. + #[must_use] pub fn get_connection_info(&self) -> ConnectionInfo { let origin = Origin::new(&format!("http://{}/", self.server.state.local_addr)).unwrap(); // DevSkim: ignore DS137138 @@ -112,6 +131,7 @@ impl Environment { } } + #[must_use] pub fn bind_address(&self) -> SocketAddr { self.server.state.local_addr } @@ -123,6 +143,14 @@ pub struct EnvContainer { } impl EnvContainer { + /// # Panics + /// + /// Will panic if: + /// + /// - The configuration does not contain a HTTP tracker configuration. + /// - The configuration does not contain a UDP tracker configuration. + /// - The configuration does not contain a HTTP API configuration. + #[must_use] pub fn initialize(configuration: &Configuration) -> Self { let core_config = Arc::new(configuration.core.clone()); diff --git a/packages/axum-tracker-api-server/src/lib.rs b/packages/axum-tracker-api-server/src/lib.rs index c3591908e..0ed026654 100644 --- a/packages/axum-tracker-api-server/src/lib.rs +++ b/packages/axum-tracker-api-server/src/lib.rs @@ -153,6 +153,7 @@ //! > **NOTICE**: we are using [curl](https://curl.se/) in the API examples. //! > And you have to use quotes around the URL in order to avoid unexpected //! > errors. For example: `curl "http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken"`. +pub mod environment; pub mod routes; pub mod server; pub mod v1; diff --git a/packages/axum-tracker-api-server/tests/common/fixtures.rs b/packages/axum-tracker-api-server/tests/common/fixtures.rs new file mode 100644 index 000000000..4589ea2ce --- /dev/null +++ b/packages/axum-tracker-api-server/tests/common/fixtures.rs @@ -0,0 +1,11 @@ +pub fn invalid_info_hashes() -> Vec { + [ + "0".to_string(), + "-1".to_string(), + "1.1".to_string(), + "INVALID INFOHASH".to_string(), + "9c38422213e30bff212b30c360d26f9a0213642".to_string(), // 39-char length instead of 40. DevSkim: ignore DS173237 + "9c38422213e30bff212b30c360d26f9a0213642&".to_string(), // Invalid char + ] + .to_vec() +} diff --git a/packages/axum-tracker-api-server/tests/common/mod.rs b/packages/axum-tracker-api-server/tests/common/mod.rs new file mode 100644 index 000000000..d066349cc --- /dev/null +++ b/packages/axum-tracker-api-server/tests/common/mod.rs @@ -0,0 +1 @@ +pub mod fixtures; diff --git a/packages/axum-tracker-api-server/tests/integration.rs b/packages/axum-tracker-api-server/tests/integration.rs new file mode 100644 index 000000000..878ac203d --- /dev/null +++ b/packages/axum-tracker-api-server/tests/integration.rs @@ -0,0 +1,20 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` + +use torrust_tracker_clock::clock; +mod common; +mod server; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/tests/servers/api/connection_info.rs b/packages/axum-tracker-api-server/tests/server/connection_info.rs similarity index 100% rename from tests/servers/api/connection_info.rs rename to packages/axum-tracker-api-server/tests/server/connection_info.rs diff --git a/tests/servers/api/mod.rs b/packages/axum-tracker-api-server/tests/server/mod.rs similarity index 78% rename from tests/servers/api/mod.rs rename to packages/axum-tracker-api-server/tests/server/mod.rs index 1176d8a6b..9dea49a4c 100644 --- a/tests/servers/api/mod.rs +++ b/packages/axum-tracker-api-server/tests/server/mod.rs @@ -1,13 +1,9 @@ -use std::sync::Arc; - -use bittorrent_tracker_core::databases::Database; -use torrust_axum_tracker_api_server::server; - pub mod connection_info; -pub mod environment; pub mod v1; -pub type Started = environment::Environment; +use std::sync::Arc; + +use bittorrent_tracker_core::databases::Database; /// It forces a database error by dropping all tables. That makes all queries /// fail. diff --git a/tests/servers/api/v1/asserts.rs b/packages/axum-tracker-api-server/tests/server/v1/asserts.rs similarity index 100% rename from tests/servers/api/v1/asserts.rs rename to packages/axum-tracker-api-server/tests/server/v1/asserts.rs diff --git a/tests/servers/api/v1/contract/authentication.rs b/packages/axum-tracker-api-server/tests/server/v1/contract/authentication.rs similarity index 92% rename from tests/servers/api/v1/contract/authentication.rs rename to packages/axum-tracker-api-server/tests/server/v1/contract/authentication.rs index 6cb1e52b9..5acb25a3c 100644 --- a/tests/servers/api/v1/contract/authentication.rs +++ b/packages/axum-tracker-api-server/tests/server/v1/contract/authentication.rs @@ -1,11 +1,11 @@ +use torrust_axum_tracker_api_server::environment::Started; use torrust_tracker_api_client::common::http::{Query, QueryParam}; use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; -use torrust_tracker_test_helpers::configuration; +use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; +use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; -use crate::common::logging::{self, logs_contains_a_line_with}; -use crate::servers::api::v1::asserts::{assert_token_not_valid, assert_unauthorized}; -use crate::servers::api::Started; +use crate::server::v1::asserts::{assert_token_not_valid, assert_unauthorized}; #[tokio::test] async fn should_authenticate_requests_by_using_a_token_query_param() { diff --git a/tests/servers/api/v1/contract/context/auth_key.rs b/packages/axum-tracker-api-server/tests/server/v1/contract/context/auth_key.rs similarity index 95% rename from tests/servers/api/v1/contract/context/auth_key.rs rename to packages/axum-tracker-api-server/tests/server/v1/contract/context/auth_key.rs index bc6d38bae..92e4b59fe 100644 --- a/tests/servers/api/v1/contract/context/auth_key.rs +++ b/packages/axum-tracker-api-server/tests/server/v1/contract/context/auth_key.rs @@ -2,18 +2,19 @@ use std::time::Duration; use bittorrent_tracker_core::authentication::Key; use serde::Serialize; +use torrust_axum_tracker_api_server::environment::Started; use torrust_tracker_api_client::v1::client::{headers_with_request_id, AddKeyForm, Client}; -use torrust_tracker_test_helpers::configuration; +use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; +use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; -use crate::common::logging::{self, logs_contains_a_line_with}; -use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; -use crate::servers::api::v1::asserts::{ +use crate::server::connection_info::{connection_with_invalid_token, connection_with_no_token}; +use crate::server::force_database_error; +use crate::server::v1::asserts::{ assert_auth_key_utf8, assert_failed_to_delete_key, assert_failed_to_generate_key, assert_failed_to_reload_keys, assert_invalid_auth_key_get_param, assert_invalid_auth_key_post_param, assert_ok, assert_token_not_valid, assert_unauthorized, assert_unprocessable_auth_key_duration_param, }; -use crate::servers::api::{force_database_error, Started}; #[tokio::test] async fn should_allow_generating_a_new_random_auth_key() { @@ -481,17 +482,18 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { mod deprecated_generate_key_endpoint { use bittorrent_tracker_core::authentication::Key; + use torrust_axum_tracker_api_server::environment::Started; use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; - use crate::common::logging::{self, logs_contains_a_line_with}; - use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; - use crate::servers::api::v1::asserts::{ + use crate::server::connection_info::{connection_with_invalid_token, connection_with_no_token}; + use crate::server::force_database_error; + use crate::server::v1::asserts::{ assert_auth_key_utf8, assert_failed_to_generate_key, assert_invalid_key_duration_param, assert_token_not_valid, assert_unauthorized, }; - use crate::servers::api::{force_database_error, Started}; #[tokio::test] async fn should_allow_generating_a_new_auth_key() { diff --git a/tests/servers/api/v1/contract/context/health_check.rs b/packages/axum-tracker-api-server/tests/server/v1/contract/context/health_check.rs similarity index 86% rename from tests/servers/api/v1/contract/context/health_check.rs rename to packages/axum-tracker-api-server/tests/server/v1/contract/context/health_check.rs index b0812dc8c..d543422d3 100644 --- a/tests/servers/api/v1/contract/context/health_check.rs +++ b/packages/axum-tracker-api-server/tests/server/v1/contract/context/health_check.rs @@ -1,11 +1,9 @@ +use torrust_axum_tracker_api_server::environment::Started; use torrust_axum_tracker_api_server::v1::context::health_check::resources::{Report, Status}; use torrust_tracker_api_client::v1::client::get; -use torrust_tracker_test_helpers::configuration; +use torrust_tracker_test_helpers::{configuration, logging}; use url::Url; -use crate::common::logging; -use crate::servers::api::Started; - #[tokio::test] async fn health_check_endpoint_should_return_status_ok_if_api_is_running() { logging::setup(); diff --git a/tests/servers/api/v1/contract/context/mod.rs b/packages/axum-tracker-api-server/tests/server/v1/contract/context/mod.rs similarity index 100% rename from tests/servers/api/v1/contract/context/mod.rs rename to packages/axum-tracker-api-server/tests/server/v1/contract/context/mod.rs diff --git a/tests/servers/api/v1/contract/context/stats.rs b/packages/axum-tracker-api-server/tests/server/v1/contract/context/stats.rs similarity index 89% rename from tests/servers/api/v1/contract/context/stats.rs rename to packages/axum-tracker-api-server/tests/server/v1/contract/context/stats.rs index 3d8e6481c..179e5c555 100644 --- a/tests/servers/api/v1/contract/context/stats.rs +++ b/packages/axum-tracker-api-server/tests/server/v1/contract/context/stats.rs @@ -1,16 +1,16 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; +use torrust_axum_tracker_api_server::environment::Started; use torrust_axum_tracker_api_server::v1::context::stats::resources::Stats; use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_primitives::peer::fixture::PeerBuilder; -use torrust_tracker_test_helpers::configuration; +use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; +use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; -use crate::common::logging::{self, logs_contains_a_line_with}; -use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; -use crate::servers::api::v1::asserts::{assert_stats, assert_token_not_valid, assert_unauthorized}; -use crate::servers::api::Started; +use crate::server::connection_info::{connection_with_invalid_token, connection_with_no_token}; +use crate::server::v1::asserts::{assert_stats, assert_token_not_valid, assert_unauthorized}; #[tokio::test] async fn should_allow_getting_tracker_statistics() { diff --git a/tests/servers/api/v1/contract/context/torrent.rs b/packages/axum-tracker-api-server/tests/server/v1/contract/context/torrent.rs similarity index 96% rename from tests/servers/api/v1/contract/context/torrent.rs rename to packages/axum-tracker-api-server/tests/server/v1/contract/context/torrent.rs index c2d5bfbaf..d77147f38 100644 --- a/tests/servers/api/v1/contract/context/torrent.rs +++ b/packages/axum-tracker-api-server/tests/server/v1/contract/context/torrent.rs @@ -1,24 +1,22 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; +use torrust_axum_tracker_api_server::environment::Started; use torrust_axum_tracker_api_server::v1::context::torrent::resources::peer::Peer; use torrust_axum_tracker_api_server::v1::context::torrent::resources::torrent::{self, Torrent}; use torrust_tracker_api_client::common::http::{Query, QueryParam}; use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_primitives::peer::fixture::PeerBuilder; -use torrust_tracker_test_helpers::configuration; +use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; +use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; -use crate::common::logging::{self, logs_contains_a_line_with}; -use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; -use crate::servers::api::v1::asserts::{ +use crate::server::connection_info::{connection_with_invalid_token, connection_with_no_token}; +use crate::server::v1::asserts::{ assert_bad_request, assert_invalid_infohash_param, assert_not_found, assert_token_not_valid, assert_torrent_info, assert_torrent_list, assert_torrent_not_known, assert_unauthorized, }; -use crate::servers::api::v1::contract::fixtures::{ - invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found, -}; -use crate::servers::api::Started; +use crate::server::v1::contract::fixtures::{invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found}; #[tokio::test] async fn should_allow_getting_all_torrents() { diff --git a/tests/servers/api/v1/contract/context/whitelist.rs b/packages/axum-tracker-api-server/tests/server/v1/contract/context/whitelist.rs similarity index 96% rename from tests/servers/api/v1/contract/context/whitelist.rs rename to packages/axum-tracker-api-server/tests/server/v1/contract/context/whitelist.rs index 6742da4d8..e41b74f45 100644 --- a/tests/servers/api/v1/contract/context/whitelist.rs +++ b/packages/axum-tracker-api-server/tests/server/v1/contract/context/whitelist.rs @@ -1,20 +1,19 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; +use torrust_axum_tracker_api_server::environment::Started; use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; -use torrust_tracker_test_helpers::configuration; +use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; +use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; -use crate::common::logging::{self, logs_contains_a_line_with}; -use crate::servers::api::connection_info::{connection_with_invalid_token, connection_with_no_token}; -use crate::servers::api::v1::asserts::{ +use crate::server::connection_info::{connection_with_invalid_token, connection_with_no_token}; +use crate::server::force_database_error; +use crate::server::v1::asserts::{ assert_failed_to_reload_whitelist, assert_failed_to_remove_torrent_from_whitelist, assert_failed_to_whitelist_torrent, assert_invalid_infohash_param, assert_not_found, assert_ok, assert_token_not_valid, assert_unauthorized, }; -use crate::servers::api::v1::contract::fixtures::{ - invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found, -}; -use crate::servers::api::{force_database_error, Started}; +use crate::server::v1::contract::fixtures::{invalid_infohashes_returning_bad_request, invalid_infohashes_returning_not_found}; #[tokio::test] async fn should_allow_whitelisting_a_torrent() { diff --git a/tests/servers/api/v1/contract/fixtures.rs b/packages/axum-tracker-api-server/tests/server/v1/contract/fixtures.rs similarity index 100% rename from tests/servers/api/v1/contract/fixtures.rs rename to packages/axum-tracker-api-server/tests/server/v1/contract/fixtures.rs diff --git a/tests/servers/api/v1/contract/mod.rs b/packages/axum-tracker-api-server/tests/server/v1/contract/mod.rs similarity index 71% rename from tests/servers/api/v1/contract/mod.rs rename to packages/axum-tracker-api-server/tests/server/v1/contract/mod.rs index 38b4a2b37..2a3f78afd 100644 --- a/tests/servers/api/v1/contract/mod.rs +++ b/packages/axum-tracker-api-server/tests/server/v1/contract/mod.rs @@ -1,4 +1,3 @@ pub mod authentication; -pub mod configuration; pub mod context; pub mod fixtures; diff --git a/tests/servers/api/v1/mod.rs b/packages/axum-tracker-api-server/tests/server/v1/mod.rs similarity index 100% rename from tests/servers/api/v1/mod.rs rename to packages/axum-tracker-api-server/tests/server/v1/mod.rs diff --git a/tests/servers/api/v1/contract/configuration.rs b/tests/servers/api/v1/contract/configuration.rs deleted file mode 100644 index 91aa138a8..000000000 --- a/tests/servers/api/v1/contract/configuration.rs +++ /dev/null @@ -1,32 +0,0 @@ -// use std::sync::Arc; - -// use axum_server::tls_rustls::RustlsConfig; -// use futures::executor::block_on; -// use torrust_tracker_test_helpers::configuration; - -// use crate::common::app::setup_with_configuration; -// use crate::servers::api::environment::stopped_environment; - -#[tokio::test] -#[ignore] -#[should_panic = "Could not receive bind_address."] -async fn should_fail_with_ssl_enabled_and_bad_ssl_config() { - // let tracker = setup_with_configuration(&Arc::new(configuration::ephemeral())); - - // let config = tracker.config.http_api.clone(); - - // let bind_to = config - // .bind_address - // .parse::() - // .expect("Tracker API bind_address invalid."); - - // let tls = - // if let (true, Some(cert), Some(key)) = (&true, &Some("bad cert path".to_string()), &Some("bad cert path".to_string())) { - // Some(block_on(RustlsConfig::from_pem_file(cert, key)).expect("Could not read tls cert.")) - // } else { - // None - // }; - - // let env = new_stopped(tracker, bind_to, tls); - // env.start().await; -} diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index ab6b0d48e..f42d62223 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -6,7 +6,6 @@ mod api { use torrust_tracker_test_helpers::configuration; use crate::common::logging; - use crate::servers::api; use crate::servers::health_check_api::client::get; #[tokio::test] @@ -15,7 +14,7 @@ mod api { let configuration = Arc::new(configuration::ephemeral()); - let service = api::Started::new(&configuration).await; + let service = torrust_axum_tracker_api_server::environment::Started::new(&configuration).await; let registar = service.registar.clone(); @@ -62,7 +61,7 @@ mod api { let configuration = Arc::new(configuration::ephemeral()); - let service = api::Started::new(&configuration).await; + let service = torrust_axum_tracker_api_server::environment::Started::new(&configuration).await; let binding = service.bind_address(); diff --git a/tests/servers/mod.rs b/tests/servers/mod.rs index 65e9a665b..d5eb4e916 100644 --- a/tests/servers/mod.rs +++ b/tests/servers/mod.rs @@ -1,4 +1,3 @@ -mod api; -pub mod health_check_api; +mod health_check_api; mod http; mod udp; From 92505b9c10a0f39cb6a8c1410e374285fe9a1f39 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Feb 2025 11:16:55 +0000 Subject: [PATCH 0822/1297] refactor: [#1316] UDP tracker integration tests to pkg --- Cargo.lock | 2 +- Cargo.toml | 1 - packages/udp-tracker-server/Cargo.toml | 1 + .../udp-tracker-server/src}/environment.rs | 31 ++++++++++---- packages/udp-tracker-server/src/lib.rs | 8 ++-- .../tests/common/fixtures.rs | 17 ++++++++ .../udp-tracker-server/tests/common/mod.rs | 2 + .../udp-tracker-server/tests/common/udp.rs | 41 +++++++++++++++++++ .../udp-tracker-server/tests/integration.rs | 20 +++++++++ .../tests/server}/asserts.rs | 0 .../tests/server}/contract.rs | 41 ++++++++----------- .../udp-tracker-server/tests/server/mod.rs | 2 + tests/common/fixtures.rs | 7 ---- tests/servers/health_check_api/contract.rs | 5 +-- tests/servers/mod.rs | 1 - tests/servers/udp/mod.rs | 7 ---- 16 files changed, 131 insertions(+), 55 deletions(-) rename {tests/servers/udp => packages/udp-tracker-server/src}/environment.rs (85%) create mode 100644 packages/udp-tracker-server/tests/common/fixtures.rs create mode 100644 packages/udp-tracker-server/tests/common/mod.rs create mode 100644 packages/udp-tracker-server/tests/common/udp.rs create mode 100644 packages/udp-tracker-server/tests/integration.rs rename {tests/servers/udp => packages/udp-tracker-server/tests/server}/asserts.rs (100%) rename {tests/servers/udp => packages/udp-tracker-server/tests/server}/contract.rs (88%) create mode 100644 packages/udp-tracker-server/tests/server/mod.rs delete mode 100644 tests/servers/udp/mod.rs diff --git a/Cargo.lock b/Cargo.lock index c753c7bc2..30c29b905 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4463,7 +4463,6 @@ dependencies = [ "axum-server", "bittorrent-http-tracker-core", "bittorrent-primitives", - "bittorrent-tracker-client", "bittorrent-tracker-core", "bittorrent-udp-tracker-core", "chrono", @@ -4662,6 +4661,7 @@ dependencies = [ "futures-util", "local-ip-address", "mockall", + "rand 0.8.5", "ringbuf", "thiserror 2.0.11", "tokio", diff --git a/Cargo.toml b/Cargo.toml index 184fe38ed..5b063bd14 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,6 @@ aquatic_udp_protocol = "0" axum-server = { version = "0", features = ["tls-rustls-no-provider"] } bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "packages/http-tracker-core" } bittorrent-primitives = "0.1.0" -bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker-core" } bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "packages/udp-tracker-core" } chrono = { version = "0", default-features = false, features = ["clock"] } diff --git a/packages/udp-tracker-server/Cargo.toml b/packages/udp-tracker-server/Cargo.toml index 7ebba677f..f8fcd2def 100644 --- a/packages/udp-tracker-server/Cargo.toml +++ b/packages/udp-tracker-server/Cargo.toml @@ -38,4 +38,5 @@ zerocopy = "0.7" [dev-dependencies] local-ip-address = "0" mockall = "0" +rand = "0" torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/tests/servers/udp/environment.rs b/packages/udp-tracker-server/src/environment.rs similarity index 85% rename from tests/servers/udp/environment.rs rename to packages/udp-tracker-server/src/environment.rs index 7d91fe535..0ab3bdea1 100644 --- a/tests/servers/udp/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -7,9 +7,12 @@ use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_primitives::peer; -use torrust_udp_tracker_server::server::spawner::Spawner; -use torrust_udp_tracker_server::server::states::{Running, Stopped}; -use torrust_udp_tracker_server::server::Server; + +use crate::server::spawner::Spawner; +use crate::server::states::{Running, Stopped}; +use crate::server::Server; + +pub type Started = Environment; pub struct Environment where @@ -37,6 +40,7 @@ where impl Environment { #[allow(dead_code)] + #[must_use] pub fn new(configuration: &Arc) -> Self { initialize_global_services(configuration); @@ -53,6 +57,9 @@ impl Environment { } } + /// # Panics + /// + /// Will panic if it cannot start the server. #[allow(dead_code)] pub async fn start(self) -> Environment { let cookie_lifetime = self.container.udp_tracker_core_container.udp_tracker_config.cookie_lifetime; @@ -74,12 +81,18 @@ impl Environment { } impl Environment { + /// # Panics + /// + /// Will panic if it cannot start the server within the timeout. pub async fn new(configuration: &Arc) -> Self { tokio::time::timeout(DEFAULT_TIMEOUT, Environment::::new(configuration).start()) .await .expect("it should create an environment within the timeout") } + /// # Panics + /// + /// Will panic if it cannot stop the service within the timeout. #[allow(dead_code)] pub async fn stop(self) -> Environment { let stopped = tokio::time::timeout(DEFAULT_TIMEOUT, self.server.stop()) @@ -89,10 +102,11 @@ impl Environment { Environment { container: self.container, registar: Registar::default(), - server: stopped.expect("it stop the udp tracker service"), + server: stopped.expect("it should stop the udp tracker service"), } } + #[must_use] pub fn bind_address(&self) -> SocketAddr { self.server.state.local_addr } @@ -104,6 +118,10 @@ pub struct EnvContainer { } impl EnvContainer { + /// # Panics + /// + /// Will panic if the configuration is missing the UDP tracker configuration. + #[must_use] pub fn initialize(configuration: &Configuration) -> Self { let core_config = Arc::new(configuration.core.clone()); let udp_tracker_configurations = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); @@ -134,10 +152,9 @@ mod tests { use std::time::Duration; use tokio::time::sleep; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_test_helpers::{configuration, logging}; - use crate::common::logging; - use crate::servers::udp::Started; + use crate::environment::Started; #[tokio::test] async fn it_should_make_and_stop_udp_server() { diff --git a/packages/udp-tracker-server/src/lib.rs b/packages/udp-tracker-server/src/lib.rs index a07f2e665..8e3cf503b 100644 --- a/packages/udp-tracker-server/src/lib.rs +++ b/packages/udp-tracker-server/src/lib.rs @@ -634,15 +634,15 @@ //! documentation by [Arvid Norberg](https://github.com/arvidn) was very //! supportive in the development of this documentation. Some descriptions were //! taken from the [libtorrent](https://www.rasterbar.com/products/libtorrent/udp_tracker_protocol.html). +pub mod environment; +pub mod error; +pub mod handlers; +pub mod server; use std::net::SocketAddr; use torrust_tracker_clock::clock; -pub mod error; -pub mod handlers; -pub mod server; - /// The maximum number of bytes in a UDP packet. pub const MAX_PACKET_SIZE: usize = 1496; diff --git a/packages/udp-tracker-server/tests/common/fixtures.rs b/packages/udp-tracker-server/tests/common/fixtures.rs new file mode 100644 index 000000000..477314398 --- /dev/null +++ b/packages/udp-tracker-server/tests/common/fixtures.rs @@ -0,0 +1,17 @@ +use aquatic_udp_protocol::TransactionId; +use bittorrent_primitives::info_hash::InfoHash; +use rand::prelude::*; + +/// Returns a random info hash. +pub fn random_info_hash() -> InfoHash { + let mut rng = rand::thread_rng(); + let random_bytes: [u8; 20] = rng.gen(); + + InfoHash::from_bytes(&random_bytes) +} + +/// Returns a random transaction id. +pub fn random_transaction_id() -> TransactionId { + let random_value = rand::thread_rng().gen(); + TransactionId::new(random_value) +} diff --git a/packages/udp-tracker-server/tests/common/mod.rs b/packages/udp-tracker-server/tests/common/mod.rs new file mode 100644 index 000000000..d327fd14f --- /dev/null +++ b/packages/udp-tracker-server/tests/common/mod.rs @@ -0,0 +1,2 @@ +pub mod fixtures; +pub mod udp; diff --git a/packages/udp-tracker-server/tests/common/udp.rs b/packages/udp-tracker-server/tests/common/udp.rs new file mode 100644 index 000000000..3d84e2b97 --- /dev/null +++ b/packages/udp-tracker-server/tests/common/udp.rs @@ -0,0 +1,41 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use tokio::net::UdpSocket; + +/// A generic UDP client +pub struct Client { + pub socket: Arc, +} + +impl Client { + #[allow(dead_code)] + pub async fn connected(remote_socket_addr: &SocketAddr, local_socket_addr: &SocketAddr) -> Client { + let client = Client::bind(local_socket_addr).await; + client.connect(remote_socket_addr).await; + client + } + + pub async fn bind(local_socket_addr: &SocketAddr) -> Self { + let socket = UdpSocket::bind(local_socket_addr).await.unwrap(); + Self { + socket: Arc::new(socket), + } + } + + pub async fn connect(&self, remote_address: &SocketAddr) { + self.socket.connect(remote_address).await.unwrap(); + } + + #[allow(dead_code)] + pub async fn send(&self, bytes: &[u8]) -> usize { + self.socket.writable().await.unwrap(); + self.socket.send(bytes).await.unwrap() + } + + #[allow(dead_code)] + pub async fn receive(&self, bytes: &mut [u8]) -> usize { + self.socket.readable().await.unwrap(); + self.socket.recv(bytes).await.unwrap() + } +} diff --git a/packages/udp-tracker-server/tests/integration.rs b/packages/udp-tracker-server/tests/integration.rs new file mode 100644 index 000000000..70b3aeb89 --- /dev/null +++ b/packages/udp-tracker-server/tests/integration.rs @@ -0,0 +1,20 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` +mod common; +mod server; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/tests/servers/udp/asserts.rs b/packages/udp-tracker-server/tests/server/asserts.rs similarity index 100% rename from tests/servers/udp/asserts.rs rename to packages/udp-tracker-server/tests/server/asserts.rs diff --git a/tests/servers/udp/contract.rs b/packages/udp-tracker-server/tests/server/contract.rs similarity index 88% rename from tests/servers/udp/contract.rs rename to packages/udp-tracker-server/tests/server/contract.rs index 78a511bd4..d2da552a2 100644 --- a/tests/servers/udp/contract.rs +++ b/packages/udp-tracker-server/tests/server/contract.rs @@ -8,12 +8,10 @@ use core::panic; use aquatic_udp_protocol::{ConnectRequest, ConnectionId, Response, TransactionId}; use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; -use torrust_tracker_test_helpers::configuration; +use torrust_tracker_test_helpers::{configuration, logging}; use torrust_udp_tracker_server::MAX_PACKET_SIZE; -use crate::common::logging; -use crate::servers::udp::asserts::get_error_response_message; -use crate::servers::udp::Started; +use crate::server::asserts::get_error_response_message; fn empty_udp_request() -> [u8; MAX_PACKET_SIZE] { [0; MAX_PACKET_SIZE] @@ -42,7 +40,7 @@ async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrac async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_request() { logging::setup(); - let env = Started::new(&configuration::ephemeral().into()).await; + let env = torrust_udp_tracker_server::environment::Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_client) => udp_client, @@ -70,17 +68,15 @@ mod receiving_a_connection_request { use aquatic_udp_protocol::{ConnectRequest, TransactionId}; use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_test_helpers::{configuration, logging}; - use crate::common::logging; - use crate::servers::udp::asserts::is_connect_response; - use crate::servers::udp::Started; + use crate::server::asserts::is_connect_response; #[tokio::test] async fn should_return_a_connect_response() { logging::setup(); - let env = Started::new(&configuration::ephemeral().into()).await; + let env = torrust_udp_tracker_server::environment::Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_tracker_client) => udp_tracker_client, @@ -116,13 +112,12 @@ mod receiving_an_announce_request { }; use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; use crate::common::fixtures::{random_info_hash, random_transaction_id}; - use crate::common::logging::{self, logs_contains_a_line_with}; - use crate::servers::udp::asserts::is_ipv4_announce_response; - use crate::servers::udp::contract::send_connection_request; - use crate::servers::udp::Started; + use crate::server::asserts::is_ipv4_announce_response; + use crate::server::contract::send_connection_request; pub async fn assert_send_and_get_announce( tx_id: TransactionId, @@ -181,7 +176,7 @@ mod receiving_an_announce_request { async fn should_return_an_announce_response() { logging::setup(); - let env = Started::new(&configuration::ephemeral().into()).await; + let env = torrust_udp_tracker_server::environment::Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_tracker_client) => udp_tracker_client, @@ -203,7 +198,7 @@ mod receiving_an_announce_request { async fn should_return_many_announce_response() { logging::setup(); - let env = Started::new(&configuration::ephemeral().into()).await; + let env = torrust_udp_tracker_server::environment::Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_tracker_client) => udp_tracker_client, @@ -228,7 +223,7 @@ mod receiving_an_announce_request { async fn should_ban_the_client_ip_if_it_sends_more_than_10_requests_with_a_cookie_value_not_normal() { logging::setup(); - let env = Started::new(&configuration::ephemeral().into()).await; + let env = torrust_udp_tracker_server::environment::Started::new(&configuration::ephemeral().into()).await; let ban_service = env.container.udp_tracker_core_container.ban_service.clone(); let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { @@ -309,18 +304,16 @@ mod receiving_an_scrape_request { use aquatic_udp_protocol::{ConnectionId, InfoHash, ScrapeRequest, TransactionId}; use bittorrent_tracker_client::udp::client::UdpTrackerClient; use torrust_tracker_configuration::DEFAULT_TIMEOUT; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_test_helpers::{configuration, logging}; - use crate::common::logging; - use crate::servers::udp::asserts::is_scrape_response; - use crate::servers::udp::contract::send_connection_request; - use crate::servers::udp::Started; + use crate::server::asserts::is_scrape_response; + use crate::server::contract::send_connection_request; #[tokio::test] async fn should_return_a_scrape_response() { logging::setup(); - let env = Started::new(&configuration::ephemeral().into()).await; + let env = torrust_udp_tracker_server::environment::Started::new(&configuration::ephemeral().into()).await; let client = match UdpTrackerClient::new(env.bind_address(), DEFAULT_TIMEOUT).await { Ok(udp_tracker_client) => udp_tracker_client, diff --git a/packages/udp-tracker-server/tests/server/mod.rs b/packages/udp-tracker-server/tests/server/mod.rs new file mode 100644 index 000000000..e2db6b4ce --- /dev/null +++ b/packages/udp-tracker-server/tests/server/mod.rs @@ -0,0 +1,2 @@ +pub mod asserts; +pub mod contract; diff --git a/tests/common/fixtures.rs b/tests/common/fixtures.rs index 1dd85ba2d..fa6884425 100644 --- a/tests/common/fixtures.rs +++ b/tests/common/fixtures.rs @@ -1,4 +1,3 @@ -use aquatic_udp_protocol::TransactionId; use bittorrent_primitives::info_hash::InfoHash; #[allow(dead_code)] @@ -21,9 +20,3 @@ pub fn random_info_hash() -> InfoHash { InfoHash::from_bytes(&random_bytes) } - -/// Returns a random transaction id. -pub fn random_transaction_id() -> TransactionId { - let random_value = rand::Rng::random::(&mut rand::rng()); - TransactionId::new(random_value) -} diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index f42d62223..875510db3 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -225,7 +225,6 @@ mod udp { use crate::common::logging; use crate::servers::health_check_api::client::get; - use crate::servers::udp; #[tokio::test] pub(crate) async fn it_should_return_good_health_for_udp_service() { @@ -233,7 +232,7 @@ mod udp { let configuration = Arc::new(configuration::ephemeral()); - let service = udp::Started::new(&configuration).await; + let service = torrust_udp_tracker_server::environment::Started::new(&configuration).await; let registar = service.registar.clone(); @@ -276,7 +275,7 @@ mod udp { let configuration = Arc::new(configuration::ephemeral()); - let service = udp::Started::new(&configuration).await; + let service = torrust_udp_tracker_server::environment::Started::new(&configuration).await; let binding = service.bind_address(); diff --git a/tests/servers/mod.rs b/tests/servers/mod.rs index d5eb4e916..627073101 100644 --- a/tests/servers/mod.rs +++ b/tests/servers/mod.rs @@ -1,3 +1,2 @@ mod health_check_api; mod http; -mod udp; diff --git a/tests/servers/udp/mod.rs b/tests/servers/udp/mod.rs deleted file mode 100644 index c52115081..000000000 --- a/tests/servers/udp/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub mod asserts; -pub mod contract; -pub mod environment; - -use torrust_udp_tracker_server::server::states::Running; - -pub type Started = environment::Environment; From 1aef0c193c3c2443751e944feedfc4fd51bb13e2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Feb 2025 11:47:09 +0000 Subject: [PATCH 0823/1297] refactor: [#1316] move HTTP tracker integration tests to pkg --- Cargo.lock | 16 +-- Cargo.toml | 8 -- packages/axum-http-tracker-server/Cargo.toml | 9 ++ .../src}/environment.rs | 20 +++- packages/axum-http-tracker-server/src/lib.rs | 5 +- .../tests}/common/fixtures.rs | 6 +- .../tests/common/http.rs | 54 ++++++++++ .../tests/common/mod.rs | 2 + .../tests/integration.rs | 20 ++++ .../tests/server}/asserts.rs | 2 +- .../tests/server}/client.rs | 0 .../tests/server}/mod.rs | 4 - .../tests/server}/requests/announce.rs | 2 +- .../tests/server}/requests/mod.rs | 0 .../tests/server}/requests/scrape.rs | 2 +- .../tests/server}/responses/announce.rs | 0 .../tests/server}/responses/error.rs | 0 .../tests/server}/responses/mod.rs | 0 .../tests/server}/responses/scrape.rs | 2 +- .../tests/server}/v1/contract.rs | 100 +++++++++--------- .../tests/server}/v1/mod.rs | 0 tests/common/mod.rs | 1 - tests/servers/health_check_api/contract.rs | 5 +- tests/servers/http/connection_info.rs | 16 --- tests/servers/mod.rs | 1 - 25 files changed, 172 insertions(+), 103 deletions(-) rename {tests/servers/http => packages/axum-http-tracker-server/src}/environment.rs (87%) rename {tests => packages/axum-http-tracker-server/tests}/common/fixtures.rs (83%) create mode 100644 packages/axum-http-tracker-server/tests/common/http.rs create mode 100644 packages/axum-http-tracker-server/tests/common/mod.rs create mode 100644 packages/axum-http-tracker-server/tests/integration.rs rename {tests/servers/http => packages/axum-http-tracker-server/tests/server}/asserts.rs (99%) rename {tests/servers/http => packages/axum-http-tracker-server/tests/server}/client.rs (100%) rename {tests/servers/http => packages/axum-http-tracker-server/tests/server}/mod.rs (82%) rename {tests/servers/http => packages/axum-http-tracker-server/tests/server}/requests/announce.rs (99%) rename {tests/servers/http => packages/axum-http-tracker-server/tests/server}/requests/mod.rs (100%) rename {tests/servers/http => packages/axum-http-tracker-server/tests/server}/requests/scrape.rs (97%) rename {tests/servers/http => packages/axum-http-tracker-server/tests/server}/responses/announce.rs (100%) rename {tests/servers/http => packages/axum-http-tracker-server/tests/server}/responses/error.rs (100%) rename {tests/servers/http => packages/axum-http-tracker-server/tests/server}/responses/mod.rs (100%) rename {tests/servers/http => packages/axum-http-tracker-server/tests/server}/responses/scrape.rs (99%) rename {tests/servers/http => packages/axum-http-tracker-server/tests/server}/v1/contract.rs (94%) rename {tests/servers/http => packages/axum-http-tracker-server/tests/server}/v1/mod.rs (100%) delete mode 100644 tests/servers/http/connection_info.rs diff --git a/Cargo.lock b/Cargo.lock index 30c29b905..8cc377fbb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4372,8 +4372,14 @@ dependencies = [ "derive_more", "futures", "hyper", + "local-ip-address", + "percent-encoding", + "rand 0.8.5", "reqwest", "serde", + "serde_bencode", + "serde_bytes", + "serde_repr", "tokio", "torrust-axum-server", "torrust-server-lib", @@ -4384,6 +4390,8 @@ dependencies = [ "tower 0.5.2", "tower-http", "tracing", + "uuid", + "zerocopy 0.7.35", ] [[package]] @@ -4459,10 +4467,8 @@ name = "torrust-tracker" version = "3.0.0-develop" dependencies = [ "anyhow", - "aquatic_udp_protocol", "axum-server", "bittorrent-http-tracker-core", - "bittorrent-primitives", "bittorrent-tracker-core", "bittorrent-udp-tracker-core", "chrono", @@ -4474,7 +4480,6 @@ dependencies = [ "local-ip-address", "mockall", "parking_lot", - "percent-encoding", "r2d2", "r2d2_mysql", "r2d2_sqlite", @@ -4482,10 +4487,8 @@ dependencies = [ "regex", "reqwest", "serde", - "serde_bencode", "serde_bytes", "serde_json", - "serde_repr", "tokio", "torrust-axum-health-check-api-server", "torrust-axum-http-tracker-server", @@ -4496,14 +4499,11 @@ dependencies = [ "torrust-tracker-api-core", "torrust-tracker-clock", "torrust-tracker-configuration", - "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-tracker-torrent-repository", "torrust-udp-tracker-server", "tracing", "tracing-subscriber", - "uuid", - "zerocopy 0.7.35", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 5b063bd14..40ddeca09 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,10 +34,8 @@ version = "3.0.0-develop" [dependencies] anyhow = "1" -aquatic_udp_protocol = "0" axum-server = { version = "0", features = ["tls-rustls-no-provider"] } bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "packages/http-tracker-core" } -bittorrent-primitives = "0.1.0" bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker-core" } bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "packages/udp-tracker-core" } chrono = { version = "0", default-features = false, features = ["clock"] } @@ -47,7 +45,6 @@ dashmap = "6" figment = "0" futures = "0" parking_lot = "0" -percent-encoding = "2" r2d2 = "0" r2d2_mysql = "25" r2d2_sqlite = { version = "0", features = ["bundled"] } @@ -55,10 +52,8 @@ rand = "0" regex = "1" reqwest = { version = "0", features = ["json"] } serde = { version = "1", features = ["derive"] } -serde_bencode = "0" serde_bytes = "0" serde_json = { version = "1", features = ["preserve_order"] } -serde_repr = "0" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "packages/axum-health-check-api-server" } torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "packages/axum-http-tracker-server" } @@ -68,13 +63,10 @@ torrust-server-lib = { version = "3.0.0-develop", path = "packages/server-lib" } torrust-tracker-api-core = { version = "3.0.0-develop", path = "packages/tracker-api-core" } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } -torrust-tracker-primitives = { version = "3.0.0-develop", path = "packages/primitives" } torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "packages/torrent-repository" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "packages/udp-tracker-server" } tracing = "0" tracing-subscriber = { version = "0", features = ["json"] } -uuid = { version = "1", features = ["v4"] } -zerocopy = "0.7" [package.metadata.cargo-machete] ignored = [ diff --git a/packages/axum-http-tracker-server/Cargo.toml b/packages/axum-http-tracker-server/Cargo.toml index abb419e4a..0c64ee986 100644 --- a/packages/axum-http-tracker-server/Cargo.toml +++ b/packages/axum-http-tracker-server/Cargo.toml @@ -30,6 +30,7 @@ serde = { version = "1", features = ["derive"] } tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } tower = { version = "0", features = ["timeout"] } @@ -37,5 +38,13 @@ tower-http = { version = "0", features = ["compression-full", "cors", "propagate tracing = "0" [dev-dependencies] +local-ip-address = "0" +percent-encoding = "2" +rand = "0" +serde_bencode = "0" +serde_bytes = "0" +serde_repr = "0" torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } +uuid = { version = "1", features = ["v4"] } +zerocopy = "0.7" diff --git a/tests/servers/http/environment.rs b/packages/axum-http-tracker-server/src/environment.rs similarity index 87% rename from tests/servers/http/environment.rs rename to packages/axum-http-tracker-server/src/environment.rs index f79d42b36..45cc276fd 100644 --- a/tests/servers/http/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -4,12 +4,15 @@ use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::container::TrackerCoreContainer; use futures::executor::block_on; -use torrust_axum_http_tracker_server::server::{HttpServer, Launcher, Running, Stopped}; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_primitives::peer; +use crate::server::{HttpServer, Launcher, Running, Stopped}; + +pub type Started = Environment; + pub struct Environment { pub container: Arc, pub registar: Registar, @@ -28,7 +31,11 @@ impl Environment { } impl Environment { + /// # Panics + /// + /// Will panic if it fails to make the TSL config from the configuration. #[allow(dead_code)] + #[must_use] pub fn new(configuration: &Arc) -> Self { initialize_global_services(configuration); @@ -50,6 +57,9 @@ impl Environment { } } + /// # Panics + /// + /// Will panic if the server fails to start. #[allow(dead_code)] pub async fn start(self) -> Environment { Environment { @@ -69,6 +79,9 @@ impl Environment { Environment::::new(configuration).start().await } + /// # Panics + /// + /// Will panic if the server fails to stop. pub async fn stop(self) -> Environment { Environment { container: self.container, @@ -77,6 +90,7 @@ impl Environment { } } + #[must_use] pub fn bind_address(&self) -> &std::net::SocketAddr { &self.server.state.binding } @@ -88,6 +102,10 @@ pub struct EnvContainer { } impl EnvContainer { + /// # Panics + /// + /// Will panic if the configuration is missing the HTTP tracker configuration. + #[must_use] pub fn initialize(configuration: &Configuration) -> Self { let core_config = Arc::new(configuration.core.clone()); let http_tracker_config = configuration diff --git a/packages/axum-http-tracker-server/src/lib.rs b/packages/axum-http-tracker-server/src/lib.rs index 7f6bec892..2bb6978b7 100644 --- a/packages/axum-http-tracker-server/src/lib.rs +++ b/packages/axum-http-tracker-server/src/lib.rs @@ -303,11 +303,12 @@ //! //! - [Bencode](https://en.wikipedia.org/wiki/Bencode). //! - [Bencode to Json Online converter](https://chocobo1.github.io/bencode_online). -use serde::{Deserialize, Serialize}; - +pub mod environment; pub mod server; pub mod v1; +use serde::{Deserialize, Serialize}; + pub const HTTP_TRACKER_LOG_TARGET: &str = "HTTP TRACKER"; /// The version of the HTTP tracker. diff --git a/tests/common/fixtures.rs b/packages/axum-http-tracker-server/tests/common/fixtures.rs similarity index 83% rename from tests/common/fixtures.rs rename to packages/axum-http-tracker-server/tests/common/fixtures.rs index fa6884425..995079adf 100644 --- a/tests/common/fixtures.rs +++ b/packages/axum-http-tracker-server/tests/common/fixtures.rs @@ -1,6 +1,6 @@ use bittorrent_primitives::info_hash::InfoHash; +use rand::prelude::*; -#[allow(dead_code)] pub fn invalid_info_hashes() -> Vec { [ "0".to_string(), @@ -15,8 +15,8 @@ pub fn invalid_info_hashes() -> Vec { /// Returns a random info hash. pub fn random_info_hash() -> InfoHash { - let mut rng = rand::rng(); - let random_bytes: [u8; 20] = rand::Rng::random(&mut rng); + let mut rng = rand::thread_rng(); + let random_bytes: [u8; 20] = rng.gen(); InfoHash::from_bytes(&random_bytes) } diff --git a/packages/axum-http-tracker-server/tests/common/http.rs b/packages/axum-http-tracker-server/tests/common/http.rs new file mode 100644 index 000000000..d682027fd --- /dev/null +++ b/packages/axum-http-tracker-server/tests/common/http.rs @@ -0,0 +1,54 @@ +pub type ReqwestQuery = Vec; +pub type ReqwestQueryParam = (String, String); + +/// URL Query component +#[derive(Default, Debug)] +pub struct Query { + params: Vec, +} + +impl Query { + pub fn empty() -> Self { + Self { params: vec![] } + } + + pub fn params(params: Vec) -> Self { + Self { params } + } + + pub fn add_param(&mut self, param: QueryParam) { + self.params.push(param); + } +} + +impl From for ReqwestQuery { + fn from(url_search_params: Query) -> Self { + url_search_params + .params + .iter() + .map(|param| ReqwestQueryParam::from((*param).clone())) + .collect() + } +} + +/// URL query param +#[derive(Clone, Debug)] +pub struct QueryParam { + name: String, + value: String, +} + +impl QueryParam { + pub fn new(name: &str, value: &str) -> Self { + Self { + name: name.to_string(), + value: value.to_string(), + } + } +} + +impl From for ReqwestQueryParam { + fn from(param: QueryParam) -> Self { + (param.name, param.value) + } +} diff --git a/packages/axum-http-tracker-server/tests/common/mod.rs b/packages/axum-http-tracker-server/tests/common/mod.rs new file mode 100644 index 000000000..810620359 --- /dev/null +++ b/packages/axum-http-tracker-server/tests/common/mod.rs @@ -0,0 +1,2 @@ +pub mod fixtures; +pub mod http; diff --git a/packages/axum-http-tracker-server/tests/integration.rs b/packages/axum-http-tracker-server/tests/integration.rs new file mode 100644 index 000000000..70b3aeb89 --- /dev/null +++ b/packages/axum-http-tracker-server/tests/integration.rs @@ -0,0 +1,20 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` +mod common; +mod server; + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/tests/servers/http/asserts.rs b/packages/axum-http-tracker-server/tests/server/asserts.rs similarity index 99% rename from tests/servers/http/asserts.rs rename to packages/axum-http-tracker-server/tests/server/asserts.rs index a68a1896e..7173aa8a9 100644 --- a/tests/servers/http/asserts.rs +++ b/packages/axum-http-tracker-server/tests/server/asserts.rs @@ -4,7 +4,7 @@ use reqwest::Response; use super::responses::announce::{Announce, Compact, DeserializedCompact}; use super::responses::scrape; -use crate::servers::http::responses::error::Error; +use crate::server::responses::error::Error; pub fn assert_bencoded_error(response_text: &String, expected_failure_reason: &str, location: &'static Location<'static>) { let error_failure_reason = serde_bencode::from_str::(response_text) diff --git a/tests/servers/http/client.rs b/packages/axum-http-tracker-server/tests/server/client.rs similarity index 100% rename from tests/servers/http/client.rs rename to packages/axum-http-tracker-server/tests/server/client.rs diff --git a/tests/servers/http/mod.rs b/packages/axum-http-tracker-server/tests/server/mod.rs similarity index 82% rename from tests/servers/http/mod.rs rename to packages/axum-http-tracker-server/tests/server/mod.rs index 37d4dcd3d..31b48b2f0 100644 --- a/tests/servers/http/mod.rs +++ b/packages/axum-http-tracker-server/tests/server/mod.rs @@ -1,14 +1,10 @@ pub mod asserts; pub mod client; -pub mod environment; pub mod requests; pub mod responses; pub mod v1; use percent_encoding::NON_ALPHANUMERIC; -use torrust_axum_http_tracker_server::server; - -pub type Started = environment::Environment; pub type ByteArray20 = [u8; 20]; diff --git a/tests/servers/http/requests/announce.rs b/packages/axum-http-tracker-server/tests/server/requests/announce.rs similarity index 99% rename from tests/servers/http/requests/announce.rs rename to packages/axum-http-tracker-server/tests/server/requests/announce.rs index 740c86d38..0775de7e4 100644 --- a/tests/servers/http/requests/announce.rs +++ b/packages/axum-http-tracker-server/tests/server/requests/announce.rs @@ -6,7 +6,7 @@ use aquatic_udp_protocol::PeerId; use bittorrent_primitives::info_hash::InfoHash; use serde_repr::Serialize_repr; -use crate::servers::http::{percent_encode_byte_array, ByteArray20}; +use crate::server::{percent_encode_byte_array, ByteArray20}; pub struct Query { pub info_hash: ByteArray20, diff --git a/tests/servers/http/requests/mod.rs b/packages/axum-http-tracker-server/tests/server/requests/mod.rs similarity index 100% rename from tests/servers/http/requests/mod.rs rename to packages/axum-http-tracker-server/tests/server/requests/mod.rs diff --git a/tests/servers/http/requests/scrape.rs b/packages/axum-http-tracker-server/tests/server/requests/scrape.rs similarity index 97% rename from tests/servers/http/requests/scrape.rs rename to packages/axum-http-tracker-server/tests/server/requests/scrape.rs index ecef541f1..afd8cfbe3 100644 --- a/tests/servers/http/requests/scrape.rs +++ b/packages/axum-http-tracker-server/tests/server/requests/scrape.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; -use crate::servers::http::{percent_encode_byte_array, ByteArray20}; +use crate::server::{percent_encode_byte_array, ByteArray20}; pub struct Query { pub info_hash: Vec, diff --git a/tests/servers/http/responses/announce.rs b/packages/axum-http-tracker-server/tests/server/responses/announce.rs similarity index 100% rename from tests/servers/http/responses/announce.rs rename to packages/axum-http-tracker-server/tests/server/responses/announce.rs diff --git a/tests/servers/http/responses/error.rs b/packages/axum-http-tracker-server/tests/server/responses/error.rs similarity index 100% rename from tests/servers/http/responses/error.rs rename to packages/axum-http-tracker-server/tests/server/responses/error.rs diff --git a/tests/servers/http/responses/mod.rs b/packages/axum-http-tracker-server/tests/server/responses/mod.rs similarity index 100% rename from tests/servers/http/responses/mod.rs rename to packages/axum-http-tracker-server/tests/server/responses/mod.rs diff --git a/tests/servers/http/responses/scrape.rs b/packages/axum-http-tracker-server/tests/server/responses/scrape.rs similarity index 99% rename from tests/servers/http/responses/scrape.rs rename to packages/axum-http-tracker-server/tests/server/responses/scrape.rs index fc741cbf4..5de15c731 100644 --- a/tests/servers/http/responses/scrape.rs +++ b/packages/axum-http-tracker-server/tests/server/responses/scrape.rs @@ -4,7 +4,7 @@ use std::str; use serde::{Deserialize, Serialize}; use serde_bencode::value::Value; -use crate::servers::http::{ByteArray20, InfoHash}; +use crate::server::{ByteArray20, InfoHash}; #[derive(Debug, PartialEq, Default)] pub struct Response { diff --git a/tests/servers/http/v1/contract.rs b/packages/axum-http-tracker-server/tests/server/v1/contract.rs similarity index 94% rename from tests/servers/http/v1/contract.rs rename to packages/axum-http-tracker-server/tests/server/v1/contract.rs index 084766593..b62920234 100644 --- a/tests/servers/http/v1/contract.rs +++ b/packages/axum-http-tracker-server/tests/server/v1/contract.rs @@ -1,7 +1,5 @@ -use torrust_tracker_test_helpers::configuration; - -use crate::common::logging; -use crate::servers::http::Started; +use torrust_axum_http_tracker_server::environment::Started; +use torrust_tracker_test_helpers::{configuration, logging}; #[tokio::test] async fn environment_should_be_started_and_stopped() { @@ -14,12 +12,11 @@ async fn environment_should_be_started_and_stopped() { mod for_all_config_modes { + use torrust_axum_http_tracker_server::environment::Started; use torrust_axum_http_tracker_server::v1::handlers::health_check::{Report, Status}; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_test_helpers::{configuration, logging}; - use crate::common::logging; - use crate::servers::http::client::Client; - use crate::servers::http::Started; + use crate::server::client::Client; #[tokio::test] async fn health_check_endpoint_should_return_ok_if_the_http_tracker_is_running() { @@ -37,13 +34,12 @@ mod for_all_config_modes { } mod and_running_on_reverse_proxy { - use torrust_tracker_test_helpers::configuration; + use torrust_axum_http_tracker_server::environment::Started; + use torrust_tracker_test_helpers::{configuration, logging}; - use crate::common::logging; - use crate::servers::http::asserts::assert_could_not_find_remote_address_on_x_forwarded_for_header_error_response; - use crate::servers::http::client::Client; - use crate::servers::http::requests::announce::QueryBuilder; - use crate::servers::http::Started; + use crate::server::asserts::assert_could_not_find_remote_address_on_x_forwarded_for_header_error_response; + use crate::server::client::Client; + use crate::server::requests::announce::QueryBuilder; #[tokio::test] async fn should_fail_when_the_http_request_does_not_include_the_xff_http_request_header() { @@ -102,20 +98,20 @@ mod for_all_config_modes { use local_ip_address::local_ip; use reqwest::{Response, StatusCode}; use tokio::net::TcpListener; + use torrust_axum_http_tracker_server::environment::Started; use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_test_helpers::{configuration, logging}; use crate::common::fixtures::invalid_info_hashes; - use crate::common::logging; - use crate::servers::http::asserts::{ + use crate::server::asserts::{ assert_announce_response, assert_bad_announce_request_error_response, assert_cannot_parse_query_param_error_response, assert_cannot_parse_query_params_error_response, assert_compact_announce_response, assert_empty_announce_response, assert_is_announce_response, assert_missing_query_params_for_announce_request_error_response, }; - use crate::servers::http::client::Client; - use crate::servers::http::requests::announce::{Compact, QueryBuilder}; - use crate::servers::http::responses::announce::{Announce, CompactPeer, CompactPeerList, DictionaryPeer}; - use crate::servers::http::{responses, Started}; + use crate::server::client::Client; + use crate::server::requests::announce::{Compact, QueryBuilder}; + use crate::server::responses; + use crate::server::responses::announce::{Announce, CompactPeer, CompactPeerList, DictionaryPeer}; #[tokio::test] async fn it_should_start_and_stop() { @@ -1028,19 +1024,19 @@ mod for_all_config_modes { use aquatic_udp_protocol::PeerId; use bittorrent_primitives::info_hash::InfoHash; use tokio::net::TcpListener; + use torrust_axum_http_tracker_server::environment::Started; use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_test_helpers::{configuration, logging}; use crate::common::fixtures::invalid_info_hashes; - use crate::common::logging; - use crate::servers::http::asserts::{ + use crate::server::asserts::{ assert_cannot_parse_query_params_error_response, assert_missing_query_params_for_scrape_request_error_response, assert_scrape_response, }; - use crate::servers::http::client::Client; - use crate::servers::http::requests::scrape::QueryBuilder; - use crate::servers::http::responses::scrape::{self, File, ResponseBuilder}; - use crate::servers::http::{requests, Started}; + use crate::server::client::Client; + use crate::server::requests; + use crate::server::requests::scrape::QueryBuilder; + use crate::server::responses::scrape::{self, File, ResponseBuilder}; #[tokio::test] #[allow(dead_code)] @@ -1278,15 +1274,15 @@ mod configured_as_whitelisted { use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_test_helpers::configuration; + use torrust_axum_http_tracker_server::environment::Started; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; use crate::common::fixtures::random_info_hash; - use crate::common::logging::{self, logs_contains_a_line_with}; - use crate::servers::http::asserts::{assert_is_announce_response, assert_torrent_not_in_whitelist_error_response}; - use crate::servers::http::client::Client; - use crate::servers::http::requests::announce::QueryBuilder; - use crate::servers::http::Started; + use crate::server::asserts::{assert_is_announce_response, assert_torrent_not_in_whitelist_error_response}; + use crate::server::client::Client; + use crate::server::requests::announce::QueryBuilder; #[tokio::test] async fn should_fail_if_the_torrent_is_not_in_the_whitelist() { @@ -1345,15 +1341,16 @@ mod configured_as_whitelisted { use aquatic_udp_protocol::PeerId; use bittorrent_primitives::info_hash::InfoHash; + use torrust_axum_http_tracker_server::environment::Started; use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; use crate::common::fixtures::random_info_hash; - use crate::common::logging::{self, logs_contains_a_line_with}; - use crate::servers::http::asserts::assert_scrape_response; - use crate::servers::http::client::Client; - use crate::servers::http::responses::scrape::{File, ResponseBuilder}; - use crate::servers::http::{requests, Started}; + use crate::server::asserts::assert_scrape_response; + use crate::server::client::Client; + use crate::server::requests; + use crate::server::responses::scrape::{File, ResponseBuilder}; #[tokio::test] async fn should_return_the_zeroed_file_when_the_requested_file_is_not_whitelisted() { @@ -1448,13 +1445,12 @@ mod configured_as_private { use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::authentication::Key; - use torrust_tracker_test_helpers::configuration; + use torrust_axum_http_tracker_server::environment::Started; + use torrust_tracker_test_helpers::{configuration, logging}; - use crate::common::logging; - use crate::servers::http::asserts::{assert_authentication_error_response, assert_is_announce_response}; - use crate::servers::http::client::Client; - use crate::servers::http::requests::announce::QueryBuilder; - use crate::servers::http::Started; + use crate::server::asserts::{assert_authentication_error_response, assert_is_announce_response}; + use crate::server::client::Client; + use crate::server::requests::announce::QueryBuilder; #[tokio::test] async fn should_respond_to_authenticated_peers() { @@ -1540,14 +1536,14 @@ mod configured_as_private { use aquatic_udp_protocol::PeerId; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::authentication::Key; + use torrust_axum_http_tracker_server::environment::Started; use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use torrust_tracker_test_helpers::configuration; + use torrust_tracker_test_helpers::{configuration, logging}; - use crate::common::logging; - use crate::servers::http::asserts::{assert_authentication_error_response, assert_scrape_response}; - use crate::servers::http::client::Client; - use crate::servers::http::responses::scrape::{File, ResponseBuilder}; - use crate::servers::http::{requests, Started}; + use crate::server::asserts::{assert_authentication_error_response, assert_scrape_response}; + use crate::server::client::Client; + use crate::server::requests; + use crate::server::responses::scrape::{File, ResponseBuilder}; #[tokio::test] async fn should_fail_if_the_key_query_param_cannot_be_parsed() { diff --git a/tests/servers/http/v1/mod.rs b/packages/axum-http-tracker-server/tests/server/v1/mod.rs similarity index 100% rename from tests/servers/http/v1/mod.rs rename to packages/axum-http-tracker-server/tests/server/v1/mod.rs diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 9589ccb1e..c6777573d 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,5 +1,4 @@ pub mod clock; -pub mod fixtures; pub mod http; pub mod logging; pub mod udp; diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs index 875510db3..473d52812 100644 --- a/tests/servers/health_check_api/contract.rs +++ b/tests/servers/health_check_api/contract.rs @@ -116,7 +116,6 @@ mod http { use crate::common::logging; use crate::servers::health_check_api::client::get; - use crate::servers::http; #[tokio::test] pub(crate) async fn it_should_return_good_health_for_http_service() { @@ -124,7 +123,7 @@ mod http { let configuration = Arc::new(configuration::ephemeral()); - let service = http::Started::new(&configuration).await; + let service = torrust_axum_http_tracker_server::environment::Started::new(&configuration).await; let registar = service.registar.clone(); @@ -170,7 +169,7 @@ mod http { let configuration = Arc::new(configuration::ephemeral()); - let service = http::Started::new(&configuration).await; + let service = torrust_axum_http_tracker_server::environment::Started::new(&configuration).await; let binding = *service.bind_address(); diff --git a/tests/servers/http/connection_info.rs b/tests/servers/http/connection_info.rs deleted file mode 100644 index 91486a3a7..000000000 --- a/tests/servers/http/connection_info.rs +++ /dev/null @@ -1,16 +0,0 @@ -use bittorrent_tracker_core::authentication::Key; - -#[derive(Clone, Debug)] -pub struct ConnectionInfo { - pub bind_address: String, - pub key: Option, -} - -impl ConnectionInfo { - pub fn anonymous(bind_address: &str) -> Self { - Self { - bind_address: bind_address.to_string(), - key: None, - } - } -} diff --git a/tests/servers/mod.rs b/tests/servers/mod.rs index 627073101..5aa096824 100644 --- a/tests/servers/mod.rs +++ b/tests/servers/mod.rs @@ -1,2 +1 @@ mod health_check_api; -mod http; From f783dbddf1859ba123ee31df12a84a00bbc88313 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Feb 2025 12:16:07 +0000 Subject: [PATCH 0824/1297] refactor: [#1316] move the rest of the Health Check API integration tests to the server pkg It's now possible becuase test environments have been exposed in their server packages. --- Cargo.lock | 4 + .../axum-health-check-api-server/Cargo.toml | 4 + .../tests/server/contract.rs | 309 +++++++++++++++++ tests/common/logging.rs | 156 --------- tests/common/mod.rs | 1 - tests/integration.rs | 1 - tests/servers/health_check_api/client.rs | 5 - tests/servers/health_check_api/contract.rs | 311 ------------------ tests/servers/health_check_api/mod.rs | 2 - tests/servers/mod.rs | 1 - 10 files changed, 317 insertions(+), 477 deletions(-) delete mode 100644 tests/common/logging.rs delete mode 100644 tests/servers/health_check_api/client.rs delete mode 100644 tests/servers/health_check_api/contract.rs delete mode 100644 tests/servers/health_check_api/mod.rs delete mode 100644 tests/servers/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 8cc377fbb..512383460 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4347,11 +4347,15 @@ dependencies = [ "serde", "serde_json", "tokio", + "torrust-axum-health-check-api-server", + "torrust-axum-http-tracker-server", "torrust-axum-server", + "torrust-axum-tracker-api-server", "torrust-server-lib", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-test-helpers", + "torrust-udp-tracker-server", "tower-http", "tracing", "tracing-subscriber", diff --git a/packages/axum-health-check-api-server/Cargo.toml b/packages/axum-health-check-api-server/Cargo.toml index 17c269aae..928393bee 100644 --- a/packages/axum-health-check-api-server/Cargo.toml +++ b/packages/axum-health-check-api-server/Cargo.toml @@ -29,6 +29,10 @@ tracing = "0" [dev-dependencies] reqwest = { version = "0", features = ["json"] } +torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "../axum-health-check-api-server" } +torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "../axum-http-tracker-server" } +torrust-axum-tracker-api-server = { version = "3.0.0-develop", path = "../axum-tracker-api-server" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } +torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } tracing-subscriber = { version = "0", features = ["json"] } diff --git a/packages/axum-health-check-api-server/tests/server/contract.rs b/packages/axum-health-check-api-server/tests/server/contract.rs index 2bd5d292e..96a03cca4 100644 --- a/packages/axum-health-check-api-server/tests/server/contract.rs +++ b/packages/axum-health-check-api-server/tests/server/contract.rs @@ -27,3 +27,312 @@ async fn health_check_endpoint_should_return_status_ok_when_there_is_no_services env.stop().await.expect("it should stop the service"); } + +mod api { + use std::sync::Arc; + + use torrust_axum_health_check_api_server::environment::Started; + use torrust_axum_health_check_api_server::resources::{Report, Status}; + use torrust_tracker_test_helpers::{configuration, logging}; + + use crate::server::client::get; + + #[tokio::test] + pub(crate) async fn it_should_return_good_health_for_api_service() { + logging::setup(); + + let configuration = Arc::new(configuration::ephemeral()); + + let service = torrust_axum_tracker_api_server::environment::Started::new(&configuration).await; + + let registar = service.registar.clone(); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Ok); + assert_eq!(report.message, String::new()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, service.bind_address()); + + assert_eq!(details.result, Ok("200 OK".to_string())); + + assert_eq!( + details.info, + format!( + "checking api health check at: http://{}/api/health_check", // DevSkim: ignore DS137138 + service.bind_address() + ) + ); + + env.stop().await.expect("it should stop the service"); + } + + service.stop().await; + } + + #[tokio::test] + pub(crate) async fn it_should_return_error_when_api_service_was_stopped_after_registration() { + logging::setup(); + + let configuration = Arc::new(configuration::ephemeral()); + + let service = torrust_axum_tracker_api_server::environment::Started::new(&configuration).await; + + let binding = service.bind_address(); + + let registar = service.registar.clone(); + + service.server.stop().await.expect("it should stop udp server"); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Error); + assert_eq!(report.message, "health check failed".to_string()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, binding); + assert!( + details + .result + .as_ref() + .is_err_and(|e| e.contains("error sending request for url")), + "Expected to contain, \"error sending request for url\", but have message \"{:?}\".", + details.result + ); + assert_eq!( + details.info, + format!("checking api health check at: http://{binding}/api/health_check") // DevSkim: ignore DS137138 + ); + + env.stop().await.expect("it should stop the service"); + } + } +} + +mod http { + use std::sync::Arc; + + use torrust_axum_health_check_api_server::environment::Started; + use torrust_axum_health_check_api_server::resources::{Report, Status}; + use torrust_tracker_test_helpers::{configuration, logging}; + + use crate::server::client::get; + + #[tokio::test] + pub(crate) async fn it_should_return_good_health_for_http_service() { + logging::setup(); + + let configuration = Arc::new(configuration::ephemeral()); + + let service = torrust_axum_http_tracker_server::environment::Started::new(&configuration).await; + + let registar = service.registar.clone(); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Ok); + assert_eq!(report.message, String::new()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, *service.bind_address()); + assert_eq!(details.result, Ok("200 OK".to_string())); + + assert_eq!( + details.info, + format!( + "checking http tracker health check at: http://{}/health_check", // DevSkim: ignore DS137138 + service.bind_address() + ) + ); + + env.stop().await.expect("it should stop the service"); + } + + service.stop().await; + } + + #[tokio::test] + pub(crate) async fn it_should_return_error_when_http_service_was_stopped_after_registration() { + logging::setup(); + + let configuration = Arc::new(configuration::ephemeral()); + + let service = torrust_axum_http_tracker_server::environment::Started::new(&configuration).await; + + let binding = *service.bind_address(); + + let registar = service.registar.clone(); + + service.server.stop().await.expect("it should stop udp server"); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Error); + assert_eq!(report.message, "health check failed".to_string()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, binding); + assert!( + details + .result + .as_ref() + .is_err_and(|e| e.contains("error sending request for url")), + "Expected to contain, \"error sending request for url\", but have message \"{:?}\".", + details.result + ); + assert_eq!( + details.info, + format!("checking http tracker health check at: http://{binding}/health_check") // DevSkim: ignore DS137138 + ); + + env.stop().await.expect("it should stop the service"); + } + } +} + +mod udp { + use std::sync::Arc; + + use torrust_axum_health_check_api_server::environment::Started; + use torrust_axum_health_check_api_server::resources::{Report, Status}; + use torrust_tracker_test_helpers::{configuration, logging}; + + use crate::server::client::get; + + #[tokio::test] + pub(crate) async fn it_should_return_good_health_for_udp_service() { + logging::setup(); + + let configuration = Arc::new(configuration::ephemeral()); + + let service = torrust_udp_tracker_server::environment::Started::new(&configuration).await; + + let registar = service.registar.clone(); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Ok); + assert_eq!(report.message, String::new()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, service.bind_address()); + assert_eq!(details.result, Ok("Connected".to_string())); + + assert_eq!( + details.info, + format!("checking the udp tracker health check at: {}", service.bind_address()) + ); + + env.stop().await.expect("it should stop the service"); + } + + service.stop().await; + } + + #[tokio::test] + pub(crate) async fn it_should_return_error_when_udp_service_was_stopped_after_registration() { + logging::setup(); + + let configuration = Arc::new(configuration::ephemeral()); + + let service = torrust_udp_tracker_server::environment::Started::new(&configuration).await; + + let binding = service.bind_address(); + + let registar = service.registar.clone(); + + service.server.stop().await.expect("it should stop udp server"); + + { + let config = configuration.health_check_api.clone(); + let env = Started::new(&config.into(), registar).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report: Report = response + .json() + .await + .expect("it should be able to get the report from the json"); + + assert_eq!(report.status, Status::Error); + assert_eq!(report.message, "health check failed".to_string()); + + let details = report.details.first().expect("it should have some details"); + + assert_eq!(details.binding, binding); + assert_eq!(details.result, Err("Timed Out".to_string())); + assert_eq!(details.info, format!("checking the udp tracker health check at: {binding}")); + + env.stop().await.expect("it should stop the service"); + } + } +} diff --git a/tests/common/logging.rs b/tests/common/logging.rs deleted file mode 100644 index 564074f3e..000000000 --- a/tests/common/logging.rs +++ /dev/null @@ -1,156 +0,0 @@ -//! Setup for logging in tests. -use std::collections::VecDeque; -use std::io; -use std::sync::{Mutex, MutexGuard, Once, OnceLock}; - -use torrust_tracker_configuration::logging::TraceStyle; -use tracing::level_filters::LevelFilter; -use tracing_subscriber::fmt::MakeWriter; - -static INIT: Once = Once::new(); - -/// A global buffer containing the latest lines captured from logs. -#[doc(hidden)] -pub fn captured_logs_buffer() -> &'static Mutex { - static CAPTURED_LOGS_GLOBAL_BUFFER: OnceLock> = OnceLock::new(); - CAPTURED_LOGS_GLOBAL_BUFFER.get_or_init(|| Mutex::new(CircularBuffer::new(10000, 200))) -} - -pub fn setup() { - INIT.call_once(|| { - tracing_init(LevelFilter::ERROR, &TraceStyle::Default); - }); -} - -fn tracing_init(level_filter: LevelFilter, style: &TraceStyle) { - let mock_writer = LogCapturer::new(captured_logs_buffer()); - - let builder = tracing_subscriber::fmt() - .with_max_level(level_filter) - .with_ansi(true) - .with_test_writer() - .with_writer(mock_writer); - - let () = match style { - TraceStyle::Default => builder.init(), - TraceStyle::Pretty(display_filename) => builder.pretty().with_file(*display_filename).init(), - TraceStyle::Compact => builder.compact().init(), - TraceStyle::Json => builder.json().init(), - }; - - tracing::info!("Logging initialized"); -} - -/// It returns true is there is a log line containing all the texts passed. -/// -/// # Panics -/// -/// Will panic if it can't get the lock for the global buffer or convert it into -/// a vec. -#[must_use] -#[allow(dead_code)] -pub fn logs_contains_a_line_with(texts: &[&str]) -> bool { - // code-review: we can search directly in the buffer instead of converting - // the buffer into a string but that would slow down the tests because - // cloning should be faster that locking the buffer for searching. - // Because the buffer is not big. - let logs = String::from_utf8(captured_logs_buffer().lock().unwrap().as_vec()).unwrap(); - - for line in logs.split('\n') { - if contains(line, texts) { - return true; - } - } - - false -} - -#[allow(dead_code)] -fn contains(text: &str, texts: &[&str]) -> bool { - texts.iter().all(|&word| text.contains(word)) -} - -/// A tracing writer which captures the latests logs lines into a buffer. -/// It's used to capture the logs in the tests. -#[derive(Debug)] -pub struct LogCapturer<'a> { - logs: &'a Mutex, -} - -impl<'a> LogCapturer<'a> { - pub fn new(buf: &'a Mutex) -> Self { - Self { logs: buf } - } - - fn buf(&self) -> io::Result> { - self.logs.lock().map_err(|_| io::Error::from(io::ErrorKind::Other)) - } -} - -impl io::Write for LogCapturer<'_> { - fn write(&mut self, buf: &[u8]) -> io::Result { - print!("{}", String::from_utf8(buf.to_vec()).unwrap()); - - let mut target = self.buf()?; - - target.write(buf) - } - - fn flush(&mut self) -> io::Result<()> { - self.buf()?.flush() - } -} - -impl MakeWriter<'_> for LogCapturer<'_> { - type Writer = Self; - - fn make_writer(&self) -> Self::Writer { - LogCapturer::new(self.logs) - } -} - -#[derive(Debug)] -pub struct CircularBuffer { - max_size: usize, - buffer: VecDeque, -} - -impl CircularBuffer { - #[must_use] - pub fn new(max_lines: usize, average_line_size: usize) -> Self { - Self { - max_size: max_lines * average_line_size, - buffer: VecDeque::with_capacity(max_lines * average_line_size), - } - } - - /// # Errors - /// - /// Won't return any error. - #[allow(clippy::unnecessary_wraps)] - pub fn write(&mut self, buf: &[u8]) -> io::Result { - for &byte in buf { - if self.buffer.len() == self.max_size { - // Remove oldest byte to make space - self.buffer.pop_front(); - } - self.buffer.push_back(byte); - } - - Ok(buf.len()) - } - - /// # Errors - /// - /// Won't return any error. - #[allow(clippy::unnecessary_wraps)] - #[allow(clippy::unused_self)] - pub fn flush(&mut self) -> io::Result<()> { - Ok(()) - } - - #[must_use] - pub fn as_vec(&self) -> Vec { - self.buffer.iter().copied().collect() - } -} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index c6777573d..6cb94892b 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,4 +1,3 @@ pub mod clock; pub mod http; -pub mod logging; pub mod udp; diff --git a/tests/integration.rs b/tests/integration.rs index 8e3d46826..18414db89 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -6,7 +6,6 @@ use torrust_tracker_clock::clock; mod common; -mod servers; /// This code needs to be copied into each crate. /// Working version, for production. diff --git a/tests/servers/health_check_api/client.rs b/tests/servers/health_check_api/client.rs deleted file mode 100644 index 3d8bdc7d6..000000000 --- a/tests/servers/health_check_api/client.rs +++ /dev/null @@ -1,5 +0,0 @@ -use reqwest::Response; - -pub async fn get(path: &str) -> Response { - reqwest::Client::builder().build().unwrap().get(path).send().await.unwrap() -} diff --git a/tests/servers/health_check_api/contract.rs b/tests/servers/health_check_api/contract.rs deleted file mode 100644 index 473d52812..000000000 --- a/tests/servers/health_check_api/contract.rs +++ /dev/null @@ -1,311 +0,0 @@ -mod api { - use std::sync::Arc; - - use torrust_axum_health_check_api_server::environment::Started; - use torrust_axum_health_check_api_server::resources::{Report, Status}; - use torrust_tracker_test_helpers::configuration; - - use crate::common::logging; - use crate::servers::health_check_api::client::get; - - #[tokio::test] - pub(crate) async fn it_should_return_good_health_for_api_service() { - logging::setup(); - - let configuration = Arc::new(configuration::ephemeral()); - - let service = torrust_axum_tracker_api_server::environment::Started::new(&configuration).await; - - let registar = service.registar.clone(); - - { - let config = configuration.health_check_api.clone(); - let env = Started::new(&config.into(), registar).await; - - let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 - - assert_eq!(response.status(), 200); - assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); - - let report: Report = response - .json() - .await - .expect("it should be able to get the report from the json"); - - assert_eq!(report.status, Status::Ok); - assert_eq!(report.message, String::new()); - - let details = report.details.first().expect("it should have some details"); - - assert_eq!(details.binding, service.bind_address()); - - assert_eq!(details.result, Ok("200 OK".to_string())); - - assert_eq!( - details.info, - format!( - "checking api health check at: http://{}/api/health_check", // DevSkim: ignore DS137138 - service.bind_address() - ) - ); - - env.stop().await.expect("it should stop the service"); - } - - service.stop().await; - } - - #[tokio::test] - pub(crate) async fn it_should_return_error_when_api_service_was_stopped_after_registration() { - logging::setup(); - - let configuration = Arc::new(configuration::ephemeral()); - - let service = torrust_axum_tracker_api_server::environment::Started::new(&configuration).await; - - let binding = service.bind_address(); - - let registar = service.registar.clone(); - - service.server.stop().await.expect("it should stop udp server"); - - { - let config = configuration.health_check_api.clone(); - let env = Started::new(&config.into(), registar).await; - - let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 - - assert_eq!(response.status(), 200); - assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); - - let report: Report = response - .json() - .await - .expect("it should be able to get the report from the json"); - - assert_eq!(report.status, Status::Error); - assert_eq!(report.message, "health check failed".to_string()); - - let details = report.details.first().expect("it should have some details"); - - assert_eq!(details.binding, binding); - assert!( - details - .result - .as_ref() - .is_err_and(|e| e.contains("error sending request for url")), - "Expected to contain, \"error sending request for url\", but have message \"{:?}\".", - details.result - ); - assert_eq!( - details.info, - format!("checking api health check at: http://{binding}/api/health_check") // DevSkim: ignore DS137138 - ); - - env.stop().await.expect("it should stop the service"); - } - } -} - -mod http { - use std::sync::Arc; - - use torrust_axum_health_check_api_server::environment::Started; - use torrust_axum_health_check_api_server::resources::{Report, Status}; - use torrust_tracker_test_helpers::configuration; - - use crate::common::logging; - use crate::servers::health_check_api::client::get; - - #[tokio::test] - pub(crate) async fn it_should_return_good_health_for_http_service() { - logging::setup(); - - let configuration = Arc::new(configuration::ephemeral()); - - let service = torrust_axum_http_tracker_server::environment::Started::new(&configuration).await; - - let registar = service.registar.clone(); - - { - let config = configuration.health_check_api.clone(); - let env = Started::new(&config.into(), registar).await; - - let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 - - assert_eq!(response.status(), 200); - assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); - - let report: Report = response - .json() - .await - .expect("it should be able to get the report from the json"); - - assert_eq!(report.status, Status::Ok); - assert_eq!(report.message, String::new()); - - let details = report.details.first().expect("it should have some details"); - - assert_eq!(details.binding, *service.bind_address()); - assert_eq!(details.result, Ok("200 OK".to_string())); - - assert_eq!( - details.info, - format!( - "checking http tracker health check at: http://{}/health_check", // DevSkim: ignore DS137138 - service.bind_address() - ) - ); - - env.stop().await.expect("it should stop the service"); - } - - service.stop().await; - } - - #[tokio::test] - pub(crate) async fn it_should_return_error_when_http_service_was_stopped_after_registration() { - logging::setup(); - - let configuration = Arc::new(configuration::ephemeral()); - - let service = torrust_axum_http_tracker_server::environment::Started::new(&configuration).await; - - let binding = *service.bind_address(); - - let registar = service.registar.clone(); - - service.server.stop().await.expect("it should stop udp server"); - - { - let config = configuration.health_check_api.clone(); - let env = Started::new(&config.into(), registar).await; - - let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 - - assert_eq!(response.status(), 200); - assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); - - let report: Report = response - .json() - .await - .expect("it should be able to get the report from the json"); - - assert_eq!(report.status, Status::Error); - assert_eq!(report.message, "health check failed".to_string()); - - let details = report.details.first().expect("it should have some details"); - - assert_eq!(details.binding, binding); - assert!( - details - .result - .as_ref() - .is_err_and(|e| e.contains("error sending request for url")), - "Expected to contain, \"error sending request for url\", but have message \"{:?}\".", - details.result - ); - assert_eq!( - details.info, - format!("checking http tracker health check at: http://{binding}/health_check") // DevSkim: ignore DS137138 - ); - - env.stop().await.expect("it should stop the service"); - } - } -} - -mod udp { - use std::sync::Arc; - - use torrust_axum_health_check_api_server::environment::Started; - use torrust_axum_health_check_api_server::resources::{Report, Status}; - use torrust_tracker_test_helpers::configuration; - - use crate::common::logging; - use crate::servers::health_check_api::client::get; - - #[tokio::test] - pub(crate) async fn it_should_return_good_health_for_udp_service() { - logging::setup(); - - let configuration = Arc::new(configuration::ephemeral()); - - let service = torrust_udp_tracker_server::environment::Started::new(&configuration).await; - - let registar = service.registar.clone(); - - { - let config = configuration.health_check_api.clone(); - let env = Started::new(&config.into(), registar).await; - - let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 - - assert_eq!(response.status(), 200); - assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); - - let report: Report = response - .json() - .await - .expect("it should be able to get the report from the json"); - - assert_eq!(report.status, Status::Ok); - assert_eq!(report.message, String::new()); - - let details = report.details.first().expect("it should have some details"); - - assert_eq!(details.binding, service.bind_address()); - assert_eq!(details.result, Ok("Connected".to_string())); - - assert_eq!( - details.info, - format!("checking the udp tracker health check at: {}", service.bind_address()) - ); - - env.stop().await.expect("it should stop the service"); - } - - service.stop().await; - } - - #[tokio::test] - pub(crate) async fn it_should_return_error_when_udp_service_was_stopped_after_registration() { - logging::setup(); - - let configuration = Arc::new(configuration::ephemeral()); - - let service = torrust_udp_tracker_server::environment::Started::new(&configuration).await; - - let binding = service.bind_address(); - - let registar = service.registar.clone(); - - service.server.stop().await.expect("it should stop udp server"); - - { - let config = configuration.health_check_api.clone(); - let env = Started::new(&config.into(), registar).await; - - let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 - - assert_eq!(response.status(), 200); - assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); - - let report: Report = response - .json() - .await - .expect("it should be able to get the report from the json"); - - assert_eq!(report.status, Status::Error); - assert_eq!(report.message, "health check failed".to_string()); - - let details = report.details.first().expect("it should have some details"); - - assert_eq!(details.binding, binding); - assert_eq!(details.result, Err("Timed Out".to_string())); - assert_eq!(details.info, format!("checking the udp tracker health check at: {binding}")); - - env.stop().await.expect("it should stop the service"); - } - } -} diff --git a/tests/servers/health_check_api/mod.rs b/tests/servers/health_check_api/mod.rs deleted file mode 100644 index 2676be6f9..000000000 --- a/tests/servers/health_check_api/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod client; -pub mod contract; diff --git a/tests/servers/mod.rs b/tests/servers/mod.rs deleted file mode 100644 index 5aa096824..000000000 --- a/tests/servers/mod.rs +++ /dev/null @@ -1 +0,0 @@ -mod health_check_api; From 60c582646f879427c5ae2d0b2a955eec754f9b44 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Feb 2025 12:18:34 +0000 Subject: [PATCH 0825/1297] refactor: remove duplicate test --- tests/common/clock.rs | 16 ---------------- tests/common/mod.rs | 1 - 2 files changed, 17 deletions(-) delete mode 100644 tests/common/clock.rs diff --git a/tests/common/clock.rs b/tests/common/clock.rs deleted file mode 100644 index 5d94bb83d..000000000 --- a/tests/common/clock.rs +++ /dev/null @@ -1,16 +0,0 @@ -use std::time::Duration; - -use torrust_tracker_clock::clock::Time; - -use crate::CurrentClock; - -#[test] -fn it_should_use_stopped_time_for_testing() { - assert_eq!(CurrentClock::dbg_clock_type(), "Stopped".to_owned()); - - let time = CurrentClock::now(); - std::thread::sleep(Duration::from_millis(50)); - let time_2 = CurrentClock::now(); - - assert_eq!(time, time_2); -} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 6cb94892b..b08eaa622 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,3 +1,2 @@ -pub mod clock; pub mod http; pub mod udp; From c34c8bc077df6fa0d8907ff206a6661f6b51bb58 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Feb 2025 12:19:23 +0000 Subject: [PATCH 0826/1297] refactor: [#1316] remove unsued code Integration tests have been moved to their respective server packages. --- tests/common/http.rs | 54 -------------------------------------------- tests/common/mod.rs | 2 -- tests/common/udp.rs | 41 --------------------------------- tests/integration.rs | 19 ---------------- 4 files changed, 116 deletions(-) delete mode 100644 tests/common/http.rs delete mode 100644 tests/common/mod.rs delete mode 100644 tests/common/udp.rs delete mode 100644 tests/integration.rs diff --git a/tests/common/http.rs b/tests/common/http.rs deleted file mode 100644 index d682027fd..000000000 --- a/tests/common/http.rs +++ /dev/null @@ -1,54 +0,0 @@ -pub type ReqwestQuery = Vec; -pub type ReqwestQueryParam = (String, String); - -/// URL Query component -#[derive(Default, Debug)] -pub struct Query { - params: Vec, -} - -impl Query { - pub fn empty() -> Self { - Self { params: vec![] } - } - - pub fn params(params: Vec) -> Self { - Self { params } - } - - pub fn add_param(&mut self, param: QueryParam) { - self.params.push(param); - } -} - -impl From for ReqwestQuery { - fn from(url_search_params: Query) -> Self { - url_search_params - .params - .iter() - .map(|param| ReqwestQueryParam::from((*param).clone())) - .collect() - } -} - -/// URL query param -#[derive(Clone, Debug)] -pub struct QueryParam { - name: String, - value: String, -} - -impl QueryParam { - pub fn new(name: &str, value: &str) -> Self { - Self { - name: name.to_string(), - value: value.to_string(), - } - } -} - -impl From for ReqwestQueryParam { - fn from(param: QueryParam) -> Self { - (param.name, param.value) - } -} diff --git a/tests/common/mod.rs b/tests/common/mod.rs deleted file mode 100644 index b08eaa622..000000000 --- a/tests/common/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod http; -pub mod udp; diff --git a/tests/common/udp.rs b/tests/common/udp.rs deleted file mode 100644 index 3d84e2b97..000000000 --- a/tests/common/udp.rs +++ /dev/null @@ -1,41 +0,0 @@ -use std::net::SocketAddr; -use std::sync::Arc; - -use tokio::net::UdpSocket; - -/// A generic UDP client -pub struct Client { - pub socket: Arc, -} - -impl Client { - #[allow(dead_code)] - pub async fn connected(remote_socket_addr: &SocketAddr, local_socket_addr: &SocketAddr) -> Client { - let client = Client::bind(local_socket_addr).await; - client.connect(remote_socket_addr).await; - client - } - - pub async fn bind(local_socket_addr: &SocketAddr) -> Self { - let socket = UdpSocket::bind(local_socket_addr).await.unwrap(); - Self { - socket: Arc::new(socket), - } - } - - pub async fn connect(&self, remote_address: &SocketAddr) { - self.socket.connect(remote_address).await.unwrap(); - } - - #[allow(dead_code)] - pub async fn send(&self, bytes: &[u8]) -> usize { - self.socket.writable().await.unwrap(); - self.socket.send(bytes).await.unwrap() - } - - #[allow(dead_code)] - pub async fn receive(&self, bytes: &mut [u8]) -> usize { - self.socket.readable().await.unwrap(); - self.socket.recv(bytes).await.unwrap() - } -} diff --git a/tests/integration.rs b/tests/integration.rs deleted file mode 100644 index 18414db89..000000000 --- a/tests/integration.rs +++ /dev/null @@ -1,19 +0,0 @@ -//! Integration tests. -//! -//! ```text -//! cargo test --test integration -//! ``` - -use torrust_tracker_clock::clock; -mod common; - -/// This code needs to be copied into each crate. -/// Working version, for production. -#[cfg(not(test))] -#[allow(dead_code)] -pub(crate) type CurrentClock = clock::Working; - -/// Stopped version, for testing. -#[cfg(test)] -#[allow(dead_code)] -pub(crate) type CurrentClock = clock::Stopped; From f233dd2dac8ca00394b31ff8b7e34a42628fbe7a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Feb 2025 12:23:50 +0000 Subject: [PATCH 0827/1297] refactor: remove unsued dependencies from the main Cargo.toml --- Cargo.lock | 9 --------- Cargo.toml | 22 ---------------------- 2 files changed, 31 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 512383460..966b987a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4477,21 +4477,13 @@ dependencies = [ "bittorrent-udp-tracker-core", "chrono", "clap", - "crossbeam-skiplist", - "dashmap", - "figment", "futures", "local-ip-address", "mockall", - "parking_lot", - "r2d2", - "r2d2_mysql", - "r2d2_sqlite", "rand 0.9.0", "regex", "reqwest", "serde", - "serde_bytes", "serde_json", "tokio", "torrust-axum-health-check-api-server", @@ -4504,7 +4496,6 @@ dependencies = [ "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-test-helpers", - "torrust-tracker-torrent-repository", "torrust-udp-tracker-server", "tracing", "tracing-subscriber", diff --git a/Cargo.toml b/Cargo.toml index 40ddeca09..346817e27 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,19 +40,11 @@ bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker- bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "packages/udp-tracker-core" } chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } -crossbeam-skiplist = "0" -dashmap = "6" -figment = "0" futures = "0" -parking_lot = "0" -r2d2 = "0" -r2d2_mysql = "25" -r2d2_sqlite = { version = "0", features = ["bundled"] } rand = "0" regex = "1" reqwest = { version = "0", features = ["json"] } serde = { version = "1", features = ["derive"] } -serde_bytes = "0" serde_json = { version = "1", features = ["preserve_order"] } tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "packages/axum-health-check-api-server" } @@ -63,24 +55,10 @@ torrust-server-lib = { version = "3.0.0-develop", path = "packages/server-lib" } torrust-tracker-api-core = { version = "3.0.0-develop", path = "packages/tracker-api-core" } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "packages/torrent-repository" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "packages/udp-tracker-server" } tracing = "0" tracing-subscriber = { version = "0", features = ["json"] } -[package.metadata.cargo-machete] -ignored = [ - "crossbeam-skiplist", - "dashmap", - "figment", - "parking_lot", - "r2d2", - "r2d2_mysql", - "r2d2_sqlite", - "serde_bytes", - "torrust-tracker-torrent-repository", -] - [dev-dependencies] local-ip-address = "0" mockall = "0" From 3f5080338b245dd48d306e3d793c8e2979cfd931 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Feb 2025 13:11:37 +0000 Subject: [PATCH 0828/1297] tests: scaffolding for integration tests --- tests/integration.rs | 22 +++++++++++++++++++++ tests/servers/health_check_api.rs | 32 +++++++++++++++++++++++++++++++ tests/servers/mod.rs | 1 + 3 files changed, 55 insertions(+) create mode 100644 tests/integration.rs create mode 100644 tests/servers/health_check_api.rs create mode 100644 tests/servers/mod.rs diff --git a/tests/integration.rs b/tests/integration.rs new file mode 100644 index 000000000..6a139e047 --- /dev/null +++ b/tests/integration.rs @@ -0,0 +1,22 @@ +//! Scaffolding for integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` +mod servers; + +// todo: there is only one test example that was copied from other package. +// We have to add tests for the whole app. + +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/tests/servers/health_check_api.rs b/tests/servers/health_check_api.rs new file mode 100644 index 000000000..0e66014da --- /dev/null +++ b/tests/servers/health_check_api.rs @@ -0,0 +1,32 @@ +use reqwest::Response; +use torrust_axum_health_check_api_server::environment::Started; +use torrust_axum_health_check_api_server::resources::{Report, Status}; +use torrust_server_lib::registar::Registar; +use torrust_tracker_test_helpers::{configuration, logging}; + +pub async fn get(path: &str) -> Response { + reqwest::Client::builder().build().unwrap().get(path).send().await.unwrap() +} + +#[tokio::test] +async fn the_health_check_endpoint_should_return_status_ok_when_there_is_not_any_service_registered() { + logging::setup(); + + let configuration = configuration::ephemeral_with_no_services(); + + let env = Started::new(&configuration.health_check_api.into(), Registar::default()).await; + + let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 + + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); + + let report = response + .json::() + .await + .expect("it should be able to get the report as json"); + + assert_eq!(report.status, Status::None); + + env.stop().await.expect("it should stop the service"); +} diff --git a/tests/servers/mod.rs b/tests/servers/mod.rs new file mode 100644 index 000000000..7aeefeec4 --- /dev/null +++ b/tests/servers/mod.rs @@ -0,0 +1 @@ +pub mod health_check_api; From 0c2be36c4b6184b87aff63d2a0abd9a5ce043301 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Feb 2025 16:31:57 +0000 Subject: [PATCH 0829/1297] refactor: [#1318] return error instead of response from http announce handler --- Cargo.lock | 1 + .../src/v1/handlers/announce.rs | 52 ++++++++++++--- .../tests/server/asserts.rs | 10 +++ .../tests/server/v1/contract.rs | 8 ++- .../src/v1/services/peer_ip_resolver.rs | 2 +- packages/http-tracker-core/Cargo.toml | 1 + .../src/services/announce.rs | 65 +++++++++++++++++-- .../src/authentication/key/mod.rs | 2 +- packages/tracker-core/src/error.rs | 35 ++++++++++ 9 files changed, 155 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 966b987a0..83afae727 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -563,6 +563,7 @@ dependencies = [ "bittorrent-tracker-core", "futures", "mockall", + "thiserror 2.0.11", "tokio", "torrust-tracker-configuration", "torrust-tracker-primitives", diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 98b2d374c..7855c8172 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -7,6 +7,7 @@ use std::sync::Arc; use aquatic_udp_protocol::AnnounceEvent; use axum::extract::State; use axum::response::{IntoResponse, Response}; +use bittorrent_http_tracker_core::services::announce::HttpAnnounceError; use bittorrent_http_tracker_protocol::v1::requests::announce::{Announce, Compact, Event}; use bittorrent_http_tracker_protocol::v1::responses::{self}; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -111,7 +112,12 @@ async fn handle( .await { Ok(announce_data) => announce_data, - Err(error) => return (StatusCode::OK, error.write()).into_response(), + Err(error) => { + let error_response = responses::error::Error { + failure_reason: error.to_string(), + }; + return (StatusCode::OK, error_response.write()).into_response(); + } }; build_response(announce_request, announce_data) } @@ -126,7 +132,7 @@ async fn handle_announce( announce_request: &Announce, client_ip_sources: &ClientIpSources, maybe_key: Option, -) -> Result { +) -> Result { bittorrent_http_tracker_core::services::announce::handle_announce( &core_config.clone(), &announce_handler.clone(), @@ -290,6 +296,7 @@ mod tests { use std::str::FromStr; + use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_tracker_core::authentication; use super::{initialize_private_tracker, sample_announce_request, sample_client_ip_sources}; @@ -315,7 +322,14 @@ mod tests { .await .unwrap_err(); - assert_error_response(&response, "Tracker authentication error: Missing authentication key"); + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + + assert_error_response( + &error_response, + "Tracker core error: Tracker core authentication error: Missing authentication key", + ); } #[tokio::test] @@ -339,15 +353,21 @@ mod tests { .await .unwrap_err(); + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + assert_error_response( - &response, - "Tracker authentication error: Failed to read key: YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ", + &error_response, + "Tracker core error: Tracker core authentication error: Failed to read key: YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ", ); } } mod with_tracker_in_listed_mode { + use bittorrent_http_tracker_protocol::v1::responses; + use super::{initialize_listed_tracker, sample_announce_request, sample_client_ip_sources}; use crate::v1::handlers::announce::handle_announce; use crate::v1::handlers::announce::tests::assert_error_response; @@ -371,10 +391,14 @@ mod tests { .await .unwrap_err(); + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + assert_error_response( - &response, + &error_response, &format!( - "Tracker whitelist error: The torrent: {}, is not whitelisted", + "Tracker core error: Tracker core whitelist error: The torrent: {}, is not whitelisted", announce_request.info_hash ), ); @@ -383,6 +407,7 @@ mod tests { mod with_tracker_on_reverse_proxy { + use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use super::{initialize_tracker_on_reverse_proxy, sample_announce_request}; @@ -411,8 +436,12 @@ mod tests { .await .unwrap_err(); + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + assert_error_response( - &response, + &error_response, "Error resolving peer IP: missing or invalid the right most X-Forwarded-For IP", ); } @@ -420,6 +449,7 @@ mod tests { mod with_tracker_not_on_reverse_proxy { + use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use super::{initialize_tracker_not_on_reverse_proxy, sample_announce_request}; @@ -448,8 +478,12 @@ mod tests { .await .unwrap_err(); + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + assert_error_response( - &response, + &error_response, "Error resolving peer IP: cannot get the client IP from the connection info", ); } diff --git a/packages/axum-http-tracker-server/tests/server/asserts.rs b/packages/axum-http-tracker-server/tests/server/asserts.rs index 7173aa8a9..7ab8d93e5 100644 --- a/packages/axum-http-tracker-server/tests/server/asserts.rs +++ b/packages/axum-http-tracker-server/tests/server/asserts.rs @@ -147,3 +147,13 @@ pub async fn assert_authentication_error_response(response: Response) { Location::caller(), ); } + +pub async fn assert_tracker_core_authentication_error_response(response: Response) { + assert_eq!(response.status(), 200); + + assert_bencoded_error( + &response.text().await.unwrap(), + "Tracker core error: Tracker core authentication error", + Location::caller(), + ); +} diff --git a/packages/axum-http-tracker-server/tests/server/v1/contract.rs b/packages/axum-http-tracker-server/tests/server/v1/contract.rs index b62920234..992793022 100644 --- a/packages/axum-http-tracker-server/tests/server/v1/contract.rs +++ b/packages/axum-http-tracker-server/tests/server/v1/contract.rs @@ -1448,7 +1448,9 @@ mod configured_as_private { use torrust_axum_http_tracker_server::environment::Started; use torrust_tracker_test_helpers::{configuration, logging}; - use crate::server::asserts::{assert_authentication_error_response, assert_is_announce_response}; + use crate::server::asserts::{ + assert_authentication_error_response, assert_is_announce_response, assert_tracker_core_authentication_error_response, + }; use crate::server::client::Client; use crate::server::requests::announce::QueryBuilder; @@ -1487,7 +1489,7 @@ mod configured_as_private { .announce(&QueryBuilder::default().with_info_hash(&info_hash).query()) .await; - assert_authentication_error_response(response).await; + assert_tracker_core_authentication_error_response(response).await; env.stop().await; } @@ -1522,7 +1524,7 @@ mod configured_as_private { .announce(&QueryBuilder::default().query()) .await; - assert_authentication_error_response(response).await; + assert_tracker_core_authentication_error_response(response).await; env.stop().await; } diff --git a/packages/http-protocol/src/v1/services/peer_ip_resolver.rs b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs index 8e99b56d1..bea93f1ba 100644 --- a/packages/http-protocol/src/v1/services/peer_ip_resolver.rs +++ b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs @@ -36,7 +36,7 @@ pub struct ClientIpSources { } /// The error that can occur when resolving the peer IP. -#[derive(Error, Debug)] +#[derive(Error, Debug, Clone)] pub enum PeerIpResolutionError { /// The peer IP cannot be obtained because the tracker is configured as a /// reverse proxy but the `X-Forwarded-For` HTTP header is missing or diff --git a/packages/http-tracker-core/Cargo.toml b/packages/http-tracker-core/Cargo.toml index bc6a3d1b3..1e0bcff28 100644 --- a/packages/http-tracker-core/Cargo.toml +++ b/packages/http-tracker-core/Cargo.toml @@ -19,6 +19,7 @@ bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "../http- bittorrent-primitives = "0.1.0" bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } futures = "0" +thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index ce34ee31c..2f530c654 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -12,17 +12,67 @@ use std::panic::Location; use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::announce::{peer_from_request, Announce}; -use bittorrent_http_tracker_protocol::v1::responses; -use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources, PeerIpResolutionError}; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::{self, Key}; +use bittorrent_tracker_core::error::{AnnounceError, TrackerCoreError, WhitelistError}; use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; use crate::statistics; +/// Errors related to announce requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum HttpAnnounceError { + #[error("Error resolving peer IP: {source}")] + PeerIpResolutionError { source: PeerIpResolutionError }, + + #[error("Tracker core error: {source}")] + TrackerCoreError { source: TrackerCoreError }, +} + +impl From for HttpAnnounceError { + fn from(peer_ip_resolution_error: PeerIpResolutionError) -> Self { + Self::PeerIpResolutionError { + source: peer_ip_resolution_error, + } + } +} + +impl From for HttpAnnounceError { + fn from(tracker_core_error: TrackerCoreError) -> Self { + Self::TrackerCoreError { + source: tracker_core_error, + } + } +} + +impl From for HttpAnnounceError { + fn from(announce_error: AnnounceError) -> Self { + Self::TrackerCoreError { + source: announce_error.into(), + } + } +} + +impl From for HttpAnnounceError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::TrackerCoreError { + source: whitelist_error.into(), + } + } +} + +impl From for HttpAnnounceError { + fn from(whitelist_error: authentication::key::Error) -> Self { + Self::TrackerCoreError { + source: whitelist_error.into(), + } + } +} + /// The HTTP tracker `announce` service. /// /// The service sends an statistics event that increments: @@ -50,7 +100,7 @@ pub async fn handle_announce( announce_request: &Announce, client_ip_sources: &ClientIpSources, maybe_key: Option, -) -> Result { +) -> Result { // Authentication if core_config.private { match maybe_key { @@ -59,9 +109,10 @@ pub async fn handle_announce( Err(error) => return Err(error.into()), }, None => { - return Err(responses::error::Error::from(authentication::key::Error::MissingAuthKey { + return Err(authentication::key::Error::MissingAuthKey { location: Location::caller(), - })) + } + .into()) } } } @@ -69,12 +120,12 @@ pub async fn handle_announce( // Authorization match whitelist_authorization.authorize(&announce_request.info_hash).await { Ok(()) => (), - Err(error) => return Err(responses::error::Error::from(error)), + Err(error) => return Err(error.into()), } let peer_ip = match peer_ip_resolver::invoke(core_config.net.on_reverse_proxy, client_ip_sources) { Ok(peer_ip) => peer_ip, - Err(error) => return Err(responses::error::Error::from(error)), + Err(error) => return Err(error.into()), }; let mut peer = peer_from_request(announce_request, &peer_ip); diff --git a/packages/tracker-core/src/authentication/key/mod.rs b/packages/tracker-core/src/authentication/key/mod.rs index efc734356..44bbd0688 100644 --- a/packages/tracker-core/src/authentication/key/mod.rs +++ b/packages/tracker-core/src/authentication/key/mod.rs @@ -166,7 +166,7 @@ pub fn verify_key_expiration(auth_key: &PeerKey) -> Result<(), Error> { /// Verification error. Error returned when an [`PeerKey`] cannot be /// verified with the [`crate::authentication::key::verify_key_expiration`] function. -#[derive(Debug, Error)] +#[derive(Debug, Error, Clone)] #[allow(dead_code)] pub enum Error { /// Wraps an underlying error encountered during key verification. diff --git a/packages/tracker-core/src/error.rs b/packages/tracker-core/src/error.rs index fed076ffa..f2d763233 100644 --- a/packages/tracker-core/src/error.rs +++ b/packages/tracker-core/src/error.rs @@ -14,6 +14,41 @@ use torrust_tracker_located_error::LocatedError; use super::authentication::key::ParseKeyError; use super::databases; +use crate::authentication; + +/// Wrapper for all errors returned by the tracker core. +#[derive(thiserror::Error, Debug, Clone)] +pub enum TrackerCoreError { + /// Error returned when there was an error with the tracker core announce handler. + #[error("Tracker core announce error: {source}")] + AnnounceError { source: AnnounceError }, + + /// Error returned when there was an error with the tracker core whitelist. + #[error("Tracker core whitelist error: {source}")] + WhitelistError { source: WhitelistError }, + + /// Error returned when there was an error with the authentication in the tracker core. + #[error("Tracker core authentication error: {source}")] + AuthenticationError { source: authentication::key::Error }, +} + +impl From for TrackerCoreError { + fn from(announce_error: AnnounceError) -> Self { + Self::AnnounceError { source: announce_error } + } +} + +impl From for TrackerCoreError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::WhitelistError { source: whitelist_error } + } +} + +impl From for TrackerCoreError { + fn from(whitelist_error: authentication::key::Error) -> Self { + Self::AuthenticationError { source: whitelist_error } + } +} /// Errors related to announce requests. #[derive(thiserror::Error, Debug, Clone)] From df4f7827e5b99ad3ad1e3fe6498850dce4c7731a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Feb 2025 17:03:05 +0000 Subject: [PATCH 0830/1297] refactor: [#1318] return error instead of response from http scrape handler --- .../src/v1/handlers/scrape.rs | 24 ++++++-- .../http-tracker-core/src/services/scrape.rs | 60 +++++++++++++++++-- packages/tracker-core/src/error.rs | 10 ++++ 3 files changed, 85 insertions(+), 9 deletions(-) diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index 59549128a..00046a618 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use axum::extract::State; use axum::response::{IntoResponse, Response}; +use bittorrent_http_tracker_core::services::scrape::HttpScrapeError; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -101,7 +102,12 @@ async fn handle( .await { Ok(scrape_data) => scrape_data, - Err(error) => return (StatusCode::OK, error.write()).into_response(), + Err(error) => { + let error_response = responses::error::Error { + failure_reason: error.to_string(), + }; + return (StatusCode::OK, error_response.write()).into_response(); + } }; build_response(scrape_data) @@ -116,7 +122,7 @@ async fn handle_scrape( scrape_request: &Scrape, client_ip_sources: &ClientIpSources, maybe_key: Option, -) -> Result { +) -> Result { bittorrent_http_tracker_core::services::scrape::handle_scrape( core_config, scrape_handler, @@ -316,6 +322,7 @@ mod tests { mod with_tracker_on_reverse_proxy { + use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use super::{initialize_tracker_on_reverse_proxy, sample_scrape_request}; @@ -343,8 +350,12 @@ mod tests { .await .unwrap_err(); + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + assert_error_response( - &response, + &error_response, "Error resolving peer IP: missing or invalid the right most X-Forwarded-For IP", ); } @@ -352,6 +363,7 @@ mod tests { mod with_tracker_not_on_reverse_proxy { + use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use super::{initialize_tracker_not_on_reverse_proxy, sample_scrape_request}; @@ -379,8 +391,12 @@ mod tests { .await .unwrap_err(); + let error_response = responses::error::Error { + failure_reason: response.to_string(), + }; + assert_error_response( - &response, + &error_response, "Error resolving peer IP: cannot get the client IP from the connection info", ); } diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 686a849ea..394f285ee 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -11,17 +11,67 @@ use std::net::IpAddr; use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; -use bittorrent_http_tracker_protocol::v1::responses; -use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources}; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources, PeerIpResolutionError}; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::authentication::service::AuthenticationService; -use bittorrent_tracker_core::authentication::Key; +use bittorrent_tracker_core::authentication::{self, Key}; +use bittorrent_tracker_core::error::{ScrapeError, TrackerCoreError, WhitelistError}; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; use crate::statistics; +/// Errors related to announce requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum HttpScrapeError { + #[error("Error resolving peer IP: {source}")] + PeerIpResolutionError { source: PeerIpResolutionError }, + + #[error("Tracker core error: {source}")] + TrackerCoreError { source: TrackerCoreError }, +} + +impl From for HttpScrapeError { + fn from(peer_ip_resolution_error: PeerIpResolutionError) -> Self { + Self::PeerIpResolutionError { + source: peer_ip_resolution_error, + } + } +} + +impl From for HttpScrapeError { + fn from(tracker_core_error: TrackerCoreError) -> Self { + Self::TrackerCoreError { + source: tracker_core_error, + } + } +} + +impl From for HttpScrapeError { + fn from(announce_error: ScrapeError) -> Self { + Self::TrackerCoreError { + source: announce_error.into(), + } + } +} + +impl From for HttpScrapeError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::TrackerCoreError { + source: whitelist_error.into(), + } + } +} + +impl From for HttpScrapeError { + fn from(whitelist_error: authentication::key::Error) -> Self { + Self::TrackerCoreError { + source: whitelist_error.into(), + } + } +} + /// The HTTP tracker `scrape` service. /// /// The service sends an statistics event that increments: @@ -47,7 +97,7 @@ pub async fn handle_scrape( scrape_request: &Scrape, client_ip_sources: &ClientIpSources, maybe_key: Option, -) -> Result { +) -> Result { // Authentication let return_fake_scrape_data = if core_config.private { match maybe_key { @@ -66,7 +116,7 @@ pub async fn handle_scrape( let peer_ip = match peer_ip_resolver::invoke(core_config.net.on_reverse_proxy, client_ip_sources) { Ok(peer_ip) => peer_ip, - Err(error) => return Err(responses::error::Error::from(error)), + Err(error) => return Err(error.into()), }; if return_fake_scrape_data { diff --git a/packages/tracker-core/src/error.rs b/packages/tracker-core/src/error.rs index f2d763233..0b94483eb 100644 --- a/packages/tracker-core/src/error.rs +++ b/packages/tracker-core/src/error.rs @@ -23,6 +23,10 @@ pub enum TrackerCoreError { #[error("Tracker core announce error: {source}")] AnnounceError { source: AnnounceError }, + /// Error returned when there was an error with the tracker core scrape handler. + #[error("Tracker core scrape error: {source}")] + ScrapeError { source: ScrapeError }, + /// Error returned when there was an error with the tracker core whitelist. #[error("Tracker core whitelist error: {source}")] WhitelistError { source: WhitelistError }, @@ -38,6 +42,12 @@ impl From for TrackerCoreError { } } +impl From for TrackerCoreError { + fn from(scrape_error: ScrapeError) -> Self { + Self::ScrapeError { source: scrape_error } + } +} + impl From for TrackerCoreError { fn from(whitelist_error: WhitelistError) -> Self { Self::WhitelistError { source: whitelist_error } From 3f55b9d61c44517145f86271116af872e0591dcf Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 26 Feb 2025 12:11:07 +0000 Subject: [PATCH 0831/1297] refactor: [#1319] add UDP server events We will splot UDP stats events into: - UDP core events - UDP server event This is step 1 in the refactor: - Step 1. Create UDP server events. - Step 2. Remove UDP server events from core events. --- packages/udp-tracker-server/src/lib.rs | 1 + .../src/statistics/event/handler.rs | 184 ++++++++++++++++++ .../src/statistics/event/listener.rs | 11 ++ .../src/statistics/event/mod.rs | 43 ++++ .../src/statistics/event/sender.rs | 29 +++ .../src/statistics/keeper.rs | 81 ++++++++ .../src/statistics/metrics.rs | 60 ++++++ .../udp-tracker-server/src/statistics/mod.rs | 6 + .../src/statistics/repository.rs | 173 ++++++++++++++++ .../src/statistics/services.rs | 146 ++++++++++++++ .../src/statistics/setup.rs | 54 +++++ 11 files changed, 788 insertions(+) create mode 100644 packages/udp-tracker-server/src/statistics/event/handler.rs create mode 100644 packages/udp-tracker-server/src/statistics/event/listener.rs create mode 100644 packages/udp-tracker-server/src/statistics/event/mod.rs create mode 100644 packages/udp-tracker-server/src/statistics/event/sender.rs create mode 100644 packages/udp-tracker-server/src/statistics/keeper.rs create mode 100644 packages/udp-tracker-server/src/statistics/metrics.rs create mode 100644 packages/udp-tracker-server/src/statistics/mod.rs create mode 100644 packages/udp-tracker-server/src/statistics/repository.rs create mode 100644 packages/udp-tracker-server/src/statistics/services.rs create mode 100644 packages/udp-tracker-server/src/statistics/setup.rs diff --git a/packages/udp-tracker-server/src/lib.rs b/packages/udp-tracker-server/src/lib.rs index 8e3cf503b..e02011a8b 100644 --- a/packages/udp-tracker-server/src/lib.rs +++ b/packages/udp-tracker-server/src/lib.rs @@ -638,6 +638,7 @@ pub mod environment; pub mod error; pub mod handlers; pub mod server; +pub mod statistics; use std::net::SocketAddr; diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs new file mode 100644 index 000000000..731f678a1 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -0,0 +1,184 @@ +use crate::statistics::event::{Event, UdpResponseKind}; +use crate::statistics::repository::Repository; + +pub async fn handle_event(event: Event, stats_repository: &Repository) { + match event { + // UDP + Event::UdpRequestAborted => { + stats_repository.increase_udp_requests_aborted().await; + } + Event::UdpRequestBanned => { + stats_repository.increase_udp_requests_banned().await; + } + + // UDP4 + Event::Udp4Request { kind } => { + stats_repository.increase_udp4_requests().await; + match kind { + UdpResponseKind::Connect => { + stats_repository.increase_udp4_connections().await; + } + UdpResponseKind::Announce => { + stats_repository.increase_udp4_announces().await; + } + UdpResponseKind::Scrape => { + stats_repository.increase_udp4_scrapes().await; + } + UdpResponseKind::Error => {} + } + } + Event::Udp4Response { + kind, + req_processing_time, + } => { + stats_repository.increase_udp4_responses().await; + + match kind { + UdpResponseKind::Connect => { + stats_repository + .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) + .await; + } + UdpResponseKind::Announce => { + stats_repository + .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) + .await; + } + UdpResponseKind::Scrape => { + stats_repository + .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) + .await; + } + UdpResponseKind::Error => {} + } + } + Event::Udp4Error => { + stats_repository.increase_udp4_errors().await; + } + + // UDP6 + Event::Udp6Request => { + stats_repository.increase_udp6_requests().await; + } + Event::Udp6Response { + kind: _, + req_processing_time: _, + } => { + stats_repository.increase_udp6_responses().await; + } + Event::Udp6Error => { + stats_repository.increase_udp6_errors().await; + } + } + + tracing::debug!("stats: {:?}", stats_repository.get_stats().await); +} + +#[cfg(test)] +mod tests { + use crate::statistics::event::handler::handle_event; + use crate::statistics::event::{Event, UdpResponseKind}; + use crate::statistics::repository::Repository; + + #[tokio::test] + async fn should_increase_the_udp_abort_counter_when_it_receives_a_udp_abort_event() { + let stats_repository = Repository::new(); + + handle_event(Event::UdpRequestAborted, &stats_repository).await; + let stats = stats_repository.get_stats().await; + assert_eq!(stats.udp_requests_aborted, 1); + } + #[tokio::test] + async fn should_increase_the_udp_ban_counter_when_it_receives_a_udp_banned_event() { + let stats_repository = Repository::new(); + + handle_event(Event::UdpRequestBanned, &stats_repository).await; + let stats = stats_repository.get_stats().await; + assert_eq!(stats.udp_requests_banned, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_requests_counter_when_it_receives_a_udp4_request_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::Udp4Request { + kind: UdpResponseKind::Connect, + }, + &stats_repository, + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_requests, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_responses_counter_when_it_receives_a_udp4_response_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::Udp4Response { + kind: crate::statistics::event::UdpResponseKind::Announce, + req_processing_time: std::time::Duration::from_secs(1), + }, + &stats_repository, + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_responses, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_errors_counter_when_it_receives_a_udp4_error_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp4Error, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_errors_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_requests_counter_when_it_receives_a_udp6_request_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp6Request, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_requests, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_response_counter_when_it_receives_a_udp6_response_event() { + let stats_repository = Repository::new(); + + handle_event( + Event::Udp6Response { + kind: crate::statistics::event::UdpResponseKind::Announce, + req_processing_time: std::time::Duration::from_secs(1), + }, + &stats_repository, + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_responses, 1); + } + #[tokio::test] + async fn should_increase_the_udp6_errors_counter_when_it_receives_a_udp6_error_event() { + let stats_repository = Repository::new(); + + handle_event(Event::Udp6Error, &stats_repository).await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_errors_handled, 1); + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs new file mode 100644 index 000000000..f1a2e25de --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -0,0 +1,11 @@ +use tokio::sync::mpsc; + +use super::handler::handle_event; +use super::Event; +use crate::statistics::repository::Repository; + +pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) { + while let Some(event) = receiver.recv().await { + handle_event(event, &stats_repository).await; + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/mod.rs b/packages/udp-tracker-server/src/statistics/event/mod.rs new file mode 100644 index 000000000..4f66862d6 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/mod.rs @@ -0,0 +1,43 @@ +use std::time::Duration; + +pub mod handler; +pub mod listener; +pub mod sender; + +/// An statistics event. It is used to collect tracker metrics. +/// +/// - `Tcp` prefix means the event was triggered by the HTTP tracker +/// - `Udp` prefix means the event was triggered by the UDP tracker +/// - `4` or `6` prefixes means the IP version used by the peer +/// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection` +/// +/// > NOTE: HTTP trackers do not use `connection` requests. +#[derive(Debug, PartialEq, Eq)] +pub enum Event { + // code-review: consider one single event for request type with data: Event::Announce { scheme: HTTPorUDP, ip_version: V4orV6 } + // Attributes are enums too. + UdpRequestAborted, + UdpRequestBanned, + Udp4Request { + kind: UdpResponseKind, + }, + Udp4Response { + kind: UdpResponseKind, + req_processing_time: Duration, + }, + Udp4Error, + Udp6Request, + Udp6Response { + kind: UdpResponseKind, + req_processing_time: Duration, + }, + Udp6Error, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum UdpResponseKind { + Connect, + Announce, + Scrape, + Error, +} diff --git a/packages/udp-tracker-server/src/statistics/event/sender.rs b/packages/udp-tracker-server/src/statistics/event/sender.rs new file mode 100644 index 000000000..ca4b4e210 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/sender.rs @@ -0,0 +1,29 @@ +use futures::future::BoxFuture; +use futures::FutureExt; +#[cfg(test)] +use mockall::{automock, predicate::str}; +use tokio::sync::mpsc; +use tokio::sync::mpsc::error::SendError; + +use super::Event; + +/// A trait to allow sending statistics events +#[cfg_attr(test, automock)] +pub trait Sender: Sync + Send { + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; +} + +/// An [`statistics::EventSender`](crate::statistics::event::sender::Sender) implementation. +/// +/// It uses a channel sender to send the statistic events. The channel is created by a +/// [`statistics::Keeper`](crate::statistics::keeper::Keeper) +#[allow(clippy::module_name_repetitions)] +pub struct ChannelSender { + pub(crate) sender: mpsc::Sender, +} + +impl Sender for ChannelSender { + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { + async move { Some(self.sender.send(event).await) }.boxed() + } +} diff --git a/packages/udp-tracker-server/src/statistics/keeper.rs b/packages/udp-tracker-server/src/statistics/keeper.rs new file mode 100644 index 000000000..e805a7eea --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/keeper.rs @@ -0,0 +1,81 @@ +use tokio::sync::mpsc; + +use super::event::listener::dispatch_events; +use super::event::sender::{ChannelSender, Sender}; +use super::event::Event; +use super::repository::Repository; + +const CHANNEL_BUFFER_SIZE: usize = 65_535; + +/// The service responsible for keeping tracker metrics (listening to statistics events and handle them). +/// +/// It actively listen to new statistics events. When it receives a new event +/// it accordingly increases the counters. +pub struct Keeper { + pub repository: Repository, +} + +impl Default for Keeper { + fn default() -> Self { + Self::new() + } +} + +impl Keeper { + #[must_use] + pub fn new() -> Self { + Self { + repository: Repository::new(), + } + } + + #[must_use] + pub fn new_active_instance() -> (Box, Repository) { + let mut stats_tracker = Self::new(); + + let stats_event_sender = stats_tracker.run_event_listener(); + + (stats_event_sender, stats_tracker.repository) + } + + pub fn run_event_listener(&mut self) -> Box { + let (sender, receiver) = mpsc::channel::(CHANNEL_BUFFER_SIZE); + + let stats_repository = self.repository.clone(); + + tokio::spawn(async move { dispatch_events(receiver, stats_repository).await }); + + Box::new(ChannelSender { sender }) + } +} + +#[cfg(test)] +mod tests { + use crate::statistics::event::{Event, UdpResponseKind}; + use crate::statistics::keeper::Keeper; + use crate::statistics::metrics::Metrics; + + #[tokio::test] + async fn should_contain_the_tracker_statistics() { + let stats_tracker = Keeper::new(); + + let stats = stats_tracker.repository.get_stats().await; + + assert_eq!(stats.udp4_requests, Metrics::default().udp4_requests); + } + + #[tokio::test] + async fn should_create_an_event_sender_to_send_statistical_events() { + let mut stats_tracker = Keeper::new(); + + let event_sender = stats_tracker.run_event_listener(); + + let result = event_sender + .send_event(Event::Udp4Request { + kind: UdpResponseKind::Connect, + }) + .await; + + assert!(result.is_some()); + } +} diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs new file mode 100644 index 000000000..cce618d74 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -0,0 +1,60 @@ +/// Metrics collected by the UDP tracker server. +#[derive(Debug, PartialEq, Default)] +pub struct Metrics { + // UDP + /// Total number of UDP (UDP tracker) requests aborted. + pub udp_requests_aborted: u64, + + /// Total number of UDP (UDP tracker) requests banned. + pub udp_requests_banned: u64, + + /// Total number of banned IPs. + pub udp_banned_ips_total: u64, + + /// Average rounded time spent processing UDP connect requests. + pub udp_avg_connect_processing_time_ns: u64, + + /// Average rounded time spent processing UDP announce requests. + pub udp_avg_announce_processing_time_ns: u64, + + /// Average rounded time spent processing UDP scrape requests. + pub udp_avg_scrape_processing_time_ns: u64, + + // UDPv4 + /// Total number of UDP (UDP tracker) requests from IPv4 peers. + pub udp4_requests: u64, + + /// Total number of UDP (UDP tracker) connections from IPv4 peers. + pub udp4_connections_handled: u64, + + /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. + pub udp4_announces_handled: u64, + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. + pub udp4_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) responses from IPv4 peers. + pub udp4_responses: u64, + + /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. + pub udp4_errors_handled: u64, + + // UDPv6 + /// Total number of UDP (UDP tracker) requests from IPv6 peers. + pub udp6_requests: u64, + + /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. + pub udp6_connections_handled: u64, + + /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. + pub udp6_announces_handled: u64, + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. + pub udp6_scrapes_handled: u64, + + /// Total number of UDP (UDP tracker) responses from IPv6 peers. + pub udp6_responses: u64, + + /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. + pub udp6_errors_handled: u64, +} diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs new file mode 100644 index 000000000..939a41061 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -0,0 +1,6 @@ +pub mod event; +pub mod keeper; +pub mod metrics; +pub mod repository; +pub mod services; +pub mod setup; diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs new file mode 100644 index 000000000..22e793036 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -0,0 +1,173 @@ +use std::sync::Arc; +use std::time::Duration; + +use tokio::sync::{RwLock, RwLockReadGuard}; + +use super::metrics::Metrics; + +/// A repository for the tracker metrics. +#[derive(Clone)] +pub struct Repository { + pub stats: Arc>, +} + +impl Default for Repository { + fn default() -> Self { + Self::new() + } +} + +impl Repository { + #[must_use] + pub fn new() -> Self { + Self { + stats: Arc::new(RwLock::new(Metrics::default())), + } + } + + pub async fn get_stats(&self) -> RwLockReadGuard<'_, Metrics> { + self.stats.read().await + } + + pub async fn increase_udp_requests_aborted(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp_requests_aborted += 1; + drop(stats_lock); + } + + pub async fn increase_udp_requests_banned(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp_requests_banned += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_requests(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_requests += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_connections(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_connections_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_announces(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_announces_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_scrapes(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_scrapes_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_responses(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_responses += 1; + drop(stats_lock); + } + + pub async fn increase_udp4_errors(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp4_errors_handled += 1; + drop(stats_lock); + } + + #[allow(clippy::cast_precision_loss)] + #[allow(clippy::cast_possible_truncation)] + #[allow(clippy::cast_sign_loss)] + pub async fn recalculate_udp_avg_connect_processing_time_ns(&self, req_processing_time: Duration) { + let mut stats_lock = self.stats.write().await; + + let req_processing_time = req_processing_time.as_nanos() as f64; + let udp_connections_handled = (stats_lock.udp4_connections_handled + stats_lock.udp6_connections_handled) as f64; + + let previous_avg = stats_lock.udp_avg_connect_processing_time_ns; + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_connections_handled; + + stats_lock.udp_avg_connect_processing_time_ns = new_avg.ceil() as u64; + + drop(stats_lock); + } + + #[allow(clippy::cast_precision_loss)] + #[allow(clippy::cast_possible_truncation)] + #[allow(clippy::cast_sign_loss)] + pub async fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) { + let mut stats_lock = self.stats.write().await; + + let req_processing_time = req_processing_time.as_nanos() as f64; + + let udp_announces_handled = (stats_lock.udp4_announces_handled + stats_lock.udp6_announces_handled) as f64; + + let previous_avg = stats_lock.udp_avg_announce_processing_time_ns; + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_announces_handled; + + stats_lock.udp_avg_announce_processing_time_ns = new_avg.ceil() as u64; + + drop(stats_lock); + } + + #[allow(clippy::cast_precision_loss)] + #[allow(clippy::cast_possible_truncation)] + #[allow(clippy::cast_sign_loss)] + pub async fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) { + let mut stats_lock = self.stats.write().await; + + let req_processing_time = req_processing_time.as_nanos() as f64; + let udp_scrapes_handled = (stats_lock.udp4_scrapes_handled + stats_lock.udp6_scrapes_handled) as f64; + + let previous_avg = stats_lock.udp_avg_scrape_processing_time_ns; + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_scrapes_handled; + + stats_lock.udp_avg_scrape_processing_time_ns = new_avg.ceil() as u64; + + drop(stats_lock); + } + + pub async fn increase_udp6_requests(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_requests += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_connections(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_connections_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_announces(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_announces_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_scrapes(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_scrapes_handled += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_responses(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_responses += 1; + drop(stats_lock); + } + + pub async fn increase_udp6_errors(&self) { + let mut stats_lock = self.stats.write().await; + stats_lock.udp6_errors_handled += 1; + drop(stats_lock); + } +} diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs new file mode 100644 index 000000000..d34bd3c8a --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -0,0 +1,146 @@ +//! Statistics services. +//! +//! It includes: +//! +//! - A [`factory`](crate::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. +//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::statistics::metrics::Metrics). +//! +//! Tracker metrics are collected using a Publisher-Subscribe pattern. +//! +//! The factory function builds two structs: +//! +//! - An statistics event [`Sender`](crate::statistics::event::sender::Sender) +//! - An statistics [`Repository`] +//! +//! ```text +//! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); +//! ``` +//! +//! The statistics repository is responsible for storing the metrics in memory. +//! The statistics event sender allows sending events related to metrics. +//! There is an event listener that is receiving all the events and processing them with an event handler. +//! Then, the event handler updates the metrics depending on the received event. +//! +//! For example, if you send the event [`Event::Udp4Connect`](crate::statistics::event::Event::Udp4Connect): +//! +//! ```text +//! let result = event_sender.send_event(Event::Udp4Connect).await; +//! ``` +//! +//! Eventually the counter for UDP connections from IPv4 peers will be increased. +//! +//! ```rust,no_run +//! pub struct Metrics { +//! // ... +//! pub udp4_connections_handled: u64, // This will be incremented +//! // ... +//! } +//! ``` +use std::sync::Arc; + +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_udp_tracker_core::services::banning::BanService; +use tokio::sync::RwLock; +use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + +use crate::statistics::metrics::Metrics; +use crate::statistics::repository::Repository; + +/// All the metrics collected by the tracker. +#[derive(Debug, PartialEq)] +pub struct TrackerMetrics { + /// Domain level metrics. + /// + /// General metrics for all torrents (number of seeders, leechers, etcetera) + pub torrents_metrics: TorrentsMetrics, + + /// Application level metrics. Usage statistics/metrics. + /// + /// Metrics about how the tracker is been used (number of udp announce requests, etcetera) + pub protocol_metrics: Metrics, +} + +/// It returns all the [`TrackerMetrics`] +pub async fn get_metrics( + in_memory_torrent_repository: Arc, + ban_service: Arc>, + stats_repository: Arc, +) -> TrackerMetrics { + let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let stats = stats_repository.get_stats().await; + let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); + + TrackerMetrics { + torrents_metrics, + protocol_metrics: Metrics { + // UDP + udp_requests_aborted: stats.udp_requests_aborted, + udp_requests_banned: stats.udp_requests_banned, + udp_banned_ips_total: udp_banned_ips_total as u64, + udp_avg_connect_processing_time_ns: stats.udp_avg_connect_processing_time_ns, + udp_avg_announce_processing_time_ns: stats.udp_avg_announce_processing_time_ns, + udp_avg_scrape_processing_time_ns: stats.udp_avg_scrape_processing_time_ns, + // UDPv4 + udp4_requests: stats.udp4_requests, + udp4_connections_handled: stats.udp4_connections_handled, + udp4_announces_handled: stats.udp4_announces_handled, + udp4_scrapes_handled: stats.udp4_scrapes_handled, + udp4_responses: stats.udp4_responses, + udp4_errors_handled: stats.udp4_errors_handled, + // UDPv6 + udp6_requests: stats.udp6_requests, + udp6_connections_handled: stats.udp6_connections_handled, + udp6_announces_handled: stats.udp6_announces_handled, + udp6_scrapes_handled: stats.udp6_scrapes_handled, + udp6_responses: stats.udp6_responses, + udp6_errors_handled: stats.udp6_errors_handled, + }, + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::{self}; + use bittorrent_udp_tracker_core::services::banning::BanService; + use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; + use tokio::sync::RwLock; + use torrust_tracker_configuration::Configuration; + use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use torrust_tracker_test_helpers::configuration; + + use crate::statistics; + use crate::statistics::services::{get_metrics, TrackerMetrics}; + + pub fn tracker_configuration() -> Configuration { + configuration::ephemeral() + } + + #[tokio::test] + async fn the_statistics_service_should_return_the_tracker_metrics() { + let config = tracker_configuration(); + + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + + let (_udp_stats_event_sender, udp_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let udp_stats_repository = Arc::new(udp_stats_repository); + + let tracker_metrics = get_metrics( + in_memory_torrent_repository.clone(), + ban_service.clone(), + udp_stats_repository.clone(), + ) + .await; + + assert_eq!( + tracker_metrics, + TrackerMetrics { + torrents_metrics: TorrentsMetrics::default(), + protocol_metrics: statistics::metrics::Metrics::default(), + } + ); + } +} diff --git a/packages/udp-tracker-server/src/statistics/setup.rs b/packages/udp-tracker-server/src/statistics/setup.rs new file mode 100644 index 000000000..d3114a75e --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/setup.rs @@ -0,0 +1,54 @@ +//! Setup for the tracker statistics. +//! +//! The [`factory`] function builds the structs needed for handling the tracker metrics. +use crate::statistics; + +/// It builds the structs needed for handling the tracker metrics. +/// +/// It returns: +/// +/// - An statistics event [`Sender`](crate::statistics::event::sender::Sender) that allows you to send events related to statistics. +/// - An statistics [`Repository`](crate::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. +/// +/// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics +/// events are sent are received but not dispatched to the handler. +#[must_use] +pub fn factory( + tracker_usage_statistics: bool, +) -> ( + Option>, + statistics::repository::Repository, +) { + let mut stats_event_sender = None; + + let mut stats_tracker = statistics::keeper::Keeper::new(); + + if tracker_usage_statistics { + stats_event_sender = Some(stats_tracker.run_event_listener()); + } + + (stats_event_sender, stats_tracker.repository) +} + +#[cfg(test)] +mod test { + use super::factory; + + #[tokio::test] + async fn should_not_send_any_event_when_statistics_are_disabled() { + let tracker_usage_statistics = false; + + let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); + + assert!(stats_event_sender.is_none()); + } + + #[tokio::test] + async fn should_send_events_when_statistics_are_enabled() { + let tracker_usage_statistics = true; + + let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); + + assert!(stats_event_sender.is_some()); + } +} From b8d2f762a4a7b23bebe70f31f4dca172b022e9a0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 26 Feb 2025 18:27:22 +0000 Subject: [PATCH 0832/1297] refactor: [#1319] remove UDP server events from UDP tracker core package Some events were moved from the `udp-tracker-core` package to the `udp-tracker-server` package. This commits remmoves the unused events from the `udp-tracker-core`. --- Cargo.lock | 2 + packages/axum-tracker-api-server/Cargo.toml | 1 + .../src/environment.rs | 3 + .../src/v1/context/stats/handlers.rs | 10 +- .../src/v1/context/stats/routes.rs | 3 +- packages/tracker-api-core/Cargo.toml | 1 + packages/tracker-api-core/src/container.rs | 13 +- .../src/statistics/services.rs | 53 +++-- packages/udp-tracker-core/src/container.rs | 14 +- .../udp-tracker-core/src/services/connect.rs | 18 +- .../src/statistics/event/handler.rs | 149 +------------- .../src/statistics/event/mod.rs | 24 --- .../src/statistics/metrics.rs | 39 ---- .../src/statistics/repository.rs | 107 ---------- .../src/statistics/services.rs | 34 +--- packages/udp-tracker-server/src/container.rs | 25 +++ .../udp-tracker-server/src/environment.rs | 5 + .../src/handlers/announce.rs | 192 +++++++++++++----- .../src/handlers/connect.rs | 120 ++++++++--- .../udp-tracker-server/src/handlers/error.rs | 17 +- .../udp-tracker-server/src/handlers/mod.rs | 93 ++++++--- .../udp-tracker-server/src/handlers/scrape.rs | 127 ++++++++---- packages/udp-tracker-server/src/lib.rs | 1 + .../udp-tracker-server/src/server/launcher.rs | 58 ++++-- packages/udp-tracker-server/src/server/mod.rs | 17 +- .../src/server/processor.rs | 29 ++- .../udp-tracker-server/src/server/spawner.rs | 15 +- .../udp-tracker-server/src/server/states.rs | 17 +- .../src/statistics/event/handler.rs | 52 ++--- .../src/statistics/event/mod.rs | 10 +- .../src/statistics/keeper.rs | 8 +- .../src/statistics/services.rs | 7 +- .../tests/server/contract.rs | 8 +- src/app.rs | 5 +- src/bootstrap/jobs/udp_tracker.rs | 20 +- src/container.rs | 46 +++-- 36 files changed, 712 insertions(+), 631 deletions(-) create mode 100644 packages/udp-tracker-server/src/container.rs diff --git a/Cargo.lock b/Cargo.lock index 83afae727..71140b9f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4450,6 +4450,7 @@ dependencies = [ "torrust-tracker-configuration", "torrust-tracker-primitives", "torrust-tracker-test-helpers", + "torrust-udp-tracker-server", "tower 0.5.2", "tower-http", "tracing", @@ -4525,6 +4526,7 @@ dependencies = [ "torrust-tracker-configuration", "torrust-tracker-primitives", "torrust-tracker-test-helpers", + "torrust-udp-tracker-server", ] [[package]] diff --git a/packages/axum-tracker-api-server/Cargo.toml b/packages/axum-tracker-api-server/Cargo.toml index 480ee2a54..e1deb9b8a 100644 --- a/packages/axum-tracker-api-server/Cargo.toml +++ b/packages/axum-tracker-api-server/Cargo.toml @@ -38,6 +38,7 @@ torrust-tracker-api-core = { version = "3.0.0-develop", path = "../tracker-api-c torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" diff --git a/packages/axum-tracker-api-server/src/environment.rs b/packages/axum-tracker-api-server/src/environment.rs index f6d6fb4e4..7390bc659 100644 --- a/packages/axum-tracker-api-server/src/environment.rs +++ b/packages/axum-tracker-api-server/src/environment.rs @@ -12,6 +12,7 @@ use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_primitives::peer; +use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use crate::server::{ApiServer, Launcher, Running, Stopped}; @@ -175,11 +176,13 @@ impl EnvContainer { let http_tracker_core_container = HttpTrackerCoreContainer::initialize_from(&tracker_core_container, &http_tracker_config); let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from(&tracker_core_container, &udp_tracker_config); + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); let tracker_http_api_core_container = TrackerHttpApiCoreContainer::initialize_from( &tracker_core_container, &http_tracker_core_container, &udp_tracker_core_container, + &udp_tracker_server_container, &http_api_config, ); diff --git a/packages/axum-tracker-api-server/src/v1/context/stats/handlers.rs b/packages/axum-tracker-api-server/src/v1/context/stats/handlers.rs index e0149cb23..5e23211a6 100644 --- a/packages/axum-tracker-api-server/src/v1/context/stats/handlers.rs +++ b/packages/axum-tracker-api-server/src/v1/context/stats/handlers.rs @@ -44,10 +44,18 @@ pub async fn get_stats_handler( Arc>, Arc, Arc, + Arc, )>, params: Query, ) -> Response { - let metrics = get_metrics(state.0.clone(), state.1.clone(), state.2.clone(), state.3.clone()).await; + let metrics = get_metrics( + state.0.clone(), + state.1.clone(), + state.2.clone(), + state.3.clone(), + state.4.clone(), + ) + .await; match params.0.format { Some(format) => match format { diff --git a/packages/axum-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-tracker-api-server/src/v1/context/stats/routes.rs index e73de8625..6caaf13bf 100644 --- a/packages/axum-tracker-api-server/src/v1/context/stats/routes.rs +++ b/packages/axum-tracker-api-server/src/v1/context/stats/routes.rs @@ -19,7 +19,8 @@ pub fn add(prefix: &str, router: Router, http_api_container: &Arc>, - pub udp_stats_repository: Arc, + pub udp_core_stats_repository: Arc, + + // todo: replace with UdpTrackerServerContainer + pub udp_server_stats_repository: Arc, pub http_api_config: Arc, } @@ -39,11 +43,13 @@ impl TrackerHttpApiCoreContainer { let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(core_config)); let http_tracker_core_container = HttpTrackerCoreContainer::initialize_from(&tracker_core_container, http_tracker_config); let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from(&tracker_core_container, udp_tracker_config); + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(core_config); Self::initialize_from( &tracker_core_container, &http_tracker_core_container, &udp_tracker_core_container, + &udp_tracker_server_container, http_api_config, ) } @@ -53,6 +59,7 @@ impl TrackerHttpApiCoreContainer { tracker_core_container: &Arc, http_tracker_core_container: &Arc, udp_tracker_core_container: &Arc, + udp_tracker_server_container: &Arc, http_api_config: &Arc, ) -> Arc { Arc::new(TrackerHttpApiCoreContainer { @@ -64,7 +71,9 @@ impl TrackerHttpApiCoreContainer { http_stats_repository: http_tracker_core_container.http_stats_repository.clone(), ban_service: udp_tracker_core_container.ban_service.clone(), - udp_stats_repository: udp_tracker_core_container.udp_stats_repository.clone(), + udp_core_stats_repository: udp_tracker_core_container.udp_core_stats_repository.clone(), + + udp_server_stats_repository: udp_tracker_server_container.udp_server_stats_repository.clone(), http_api_config: http_api_config.clone(), }) diff --git a/packages/tracker-api-core/src/statistics/services.rs b/packages/tracker-api-core/src/statistics/services.rs index 178c8ca0f..c4dfcf533 100644 --- a/packages/tracker-api-core/src/statistics/services.rs +++ b/packages/tracker-api-core/src/statistics/services.rs @@ -2,9 +2,10 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::services::banning::BanService; -use bittorrent_udp_tracker_core::{self, statistics}; +use bittorrent_udp_tracker_core::{self, statistics as udp_core_statistics}; use tokio::sync::RwLock; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_udp_tracker_server::statistics as udp_server_statistics; use crate::statistics::metrics::Metrics; @@ -27,12 +28,14 @@ pub async fn get_metrics( in_memory_torrent_repository: Arc, ban_service: Arc>, http_stats_repository: Arc, - udp_stats_repository: Arc, + udp_core_stats_repository: Arc, + udp_server_stats_repository: Arc, ) -> TrackerMetrics { let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); let http_stats = http_stats_repository.get_stats().await; - let udp_stats = udp_stats_repository.get_stats().await; + let udp_core_stats = udp_core_stats_repository.get_stats().await; + let udp_server_stats = udp_server_stats_repository.get_stats().await; TrackerMetrics { torrents_metrics, @@ -46,26 +49,26 @@ pub async fn get_metrics( tcp6_announces_handled: http_stats.tcp6_announces_handled, tcp6_scrapes_handled: http_stats.tcp6_scrapes_handled, // UDP - udp_requests_aborted: udp_stats.udp_requests_aborted, - udp_requests_banned: udp_stats.udp_requests_banned, + udp_requests_aborted: udp_server_stats.udp_requests_aborted, + udp_requests_banned: udp_server_stats.udp_requests_banned, udp_banned_ips_total: udp_banned_ips_total as u64, - udp_avg_connect_processing_time_ns: udp_stats.udp_avg_connect_processing_time_ns, - udp_avg_announce_processing_time_ns: udp_stats.udp_avg_announce_processing_time_ns, - udp_avg_scrape_processing_time_ns: udp_stats.udp_avg_scrape_processing_time_ns, + udp_avg_connect_processing_time_ns: udp_server_stats.udp_avg_connect_processing_time_ns, + udp_avg_announce_processing_time_ns: udp_server_stats.udp_avg_announce_processing_time_ns, + udp_avg_scrape_processing_time_ns: udp_server_stats.udp_avg_scrape_processing_time_ns, // UDPv4 - udp4_requests: udp_stats.udp4_requests, - udp4_connections_handled: udp_stats.udp4_connections_handled, - udp4_announces_handled: udp_stats.udp4_announces_handled, - udp4_scrapes_handled: udp_stats.udp4_scrapes_handled, - udp4_responses: udp_stats.udp4_responses, - udp4_errors_handled: udp_stats.udp4_errors_handled, + udp4_requests: udp_server_stats.udp4_requests, + udp4_connections_handled: udp_core_stats.udp4_connections_handled, + udp4_announces_handled: udp_core_stats.udp4_announces_handled, + udp4_scrapes_handled: udp_core_stats.udp4_scrapes_handled, + udp4_responses: udp_server_stats.udp4_responses, + udp4_errors_handled: udp_server_stats.udp4_errors_handled, // UDPv6 - udp6_requests: udp_stats.udp6_requests, - udp6_connections_handled: udp_stats.udp6_connections_handled, - udp6_announces_handled: udp_stats.udp6_announces_handled, - udp6_scrapes_handled: udp_stats.udp6_scrapes_handled, - udp6_responses: udp_stats.udp6_responses, - udp6_errors_handled: udp_stats.udp6_errors_handled, + udp6_requests: udp_server_stats.udp6_requests, + udp6_connections_handled: udp_core_stats.udp6_connections_handled, + udp6_announces_handled: udp_core_stats.udp6_announces_handled, + udp6_scrapes_handled: udp_core_stats.udp6_scrapes_handled, + udp6_responses: udp_server_stats.udp6_responses, + udp6_errors_handled: udp_server_stats.udp6_errors_handled, }, } } @@ -97,21 +100,27 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - // HTTP stats + // HTTP core stats let (_http_stats_event_sender, http_stats_repository) = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); let http_stats_repository = Arc::new(http_stats_repository); - // UDP stats + // UDP core stats let (_udp_stats_event_sender, udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); let udp_stats_repository = Arc::new(udp_stats_repository); + // UDP server stats + let (_udp_server_stats_event_sender, udp_server_stats_repository) = + torrust_udp_tracker_server::statistics::setup::factory(config.core.tracker_usage_statistics); + let udp_server_stats_repository = Arc::new(udp_server_stats_repository); + let tracker_metrics = get_metrics( in_memory_torrent_repository.clone(), ban_service.clone(), http_stats_repository.clone(), udp_stats_repository.clone(), + udp_server_stats_repository.clone(), ) .await; diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index 62378e0af..1467134c5 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -18,8 +18,8 @@ pub struct UdpTrackerCoreContainer { pub whitelist_authorization: Arc, pub udp_tracker_config: Arc, - pub udp_stats_event_sender: Arc>>, - pub udp_stats_repository: Arc, + pub udp_core_stats_event_sender: Arc>>, + pub udp_core_stats_repository: Arc, pub ban_service: Arc>, } @@ -35,10 +35,10 @@ impl UdpTrackerCoreContainer { tracker_core_container: &Arc, udp_tracker_config: &Arc, ) -> Arc { - let (udp_stats_event_sender, udp_stats_repository) = + let (udp_core_stats_event_sender, udp_core_stats_repository) = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - let udp_stats_repository = Arc::new(udp_stats_repository); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let udp_core_stats_repository = Arc::new(udp_core_stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); @@ -49,8 +49,8 @@ impl UdpTrackerCoreContainer { whitelist_authorization: tracker_core_container.whitelist_authorization.clone(), udp_tracker_config: udp_tracker_config.clone(), - udp_stats_event_sender: udp_stats_event_sender.clone(), - udp_stats_repository: udp_stats_repository.clone(), + udp_core_stats_event_sender: udp_core_stats_event_sender.clone(), + udp_core_stats_repository: udp_core_stats_repository.clone(), ban_service: ban_service.clone(), }) } diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index 9cb419bbc..3354595e5 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -55,10 +55,10 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { - let (udp_stats_event_sender, _udp_stats_repository) = statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); - let response = handle_connect(sample_ipv4_remote_addr(), &udp_stats_event_sender, sample_issue_time()).await; + let response = handle_connect(sample_ipv4_remote_addr(), &udp_core_stats_event_sender, sample_issue_time()).await; assert_eq!( response, @@ -68,10 +68,10 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { - let (udp_stats_event_sender, _udp_stats_repository) = statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); - let response = handle_connect(sample_ipv4_remote_addr(), &udp_stats_event_sender, sample_issue_time()).await; + let response = handle_connect(sample_ipv4_remote_addr(), &udp_core_stats_event_sender, sample_issue_time()).await; assert_eq!( response, @@ -81,10 +81,10 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { - let (udp_stats_event_sender, _udp_stats_repository) = statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); - let response = handle_connect(sample_ipv6_remote_addr(), &udp_stats_event_sender, sample_issue_time()).await; + let response = handle_connect(sample_ipv6_remote_addr(), &udp_core_stats_event_sender, sample_issue_time()).await; assert_eq!( response, diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index 91be32ad1..096059b91 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -1,20 +1,9 @@ -use crate::statistics::event::{Event, UdpResponseKind}; +use crate::statistics::event::Event; use crate::statistics::repository::Repository; pub async fn handle_event(event: Event, stats_repository: &Repository) { match event { - // UDP - Event::UdpRequestAborted => { - stats_repository.increase_udp_requests_aborted().await; - } - Event::UdpRequestBanned => { - stats_repository.increase_udp_requests_banned().await; - } - // UDP4 - Event::Udp4Request => { - stats_repository.increase_udp4_requests().await; - } Event::Udp4Connect => { stats_repository.increase_udp4_connections().await; } @@ -24,39 +13,8 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { Event::Udp4Scrape => { stats_repository.increase_udp4_scrapes().await; } - Event::Udp4Response { - kind, - req_processing_time, - } => { - stats_repository.increase_udp4_responses().await; - - match kind { - UdpResponseKind::Connect => { - stats_repository - .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) - .await; - } - UdpResponseKind::Announce => { - stats_repository - .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) - .await; - } - UdpResponseKind::Scrape => { - stats_repository - .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) - .await; - } - UdpResponseKind::Error => {} - } - } - Event::Udp4Error => { - stats_repository.increase_udp4_errors().await; - } // UDP6 - Event::Udp6Request => { - stats_repository.increase_udp6_requests().await; - } Event::Udp6Connect => { stats_repository.increase_udp6_connections().await; } @@ -66,15 +24,6 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { Event::Udp6Scrape => { stats_repository.increase_udp6_scrapes().await; } - Event::Udp6Response { - kind: _, - req_processing_time: _, - } => { - stats_repository.increase_udp6_responses().await; - } - Event::Udp6Error => { - stats_repository.increase_udp6_errors().await; - } } tracing::debug!("stats: {:?}", stats_repository.get_stats().await); @@ -151,100 +100,4 @@ mod tests { assert_eq!(stats.udp6_scrapes_handled, 1); } - - #[tokio::test] - async fn should_increase_the_udp_abort_counter_when_it_receives_a_udp_abort_event() { - let stats_repository = Repository::new(); - - handle_event(Event::UdpRequestAborted, &stats_repository).await; - let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp_requests_aborted, 1); - } - #[tokio::test] - async fn should_increase_the_udp_ban_counter_when_it_receives_a_udp_banned_event() { - let stats_repository = Repository::new(); - - handle_event(Event::UdpRequestBanned, &stats_repository).await; - let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp_requests_banned, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_requests_counter_when_it_receives_a_udp4_request_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Udp4Request, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_requests, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_responses_counter_when_it_receives_a_udp4_response_event() { - let stats_repository = Repository::new(); - - handle_event( - Event::Udp4Response { - kind: crate::statistics::event::UdpResponseKind::Announce, - req_processing_time: std::time::Duration::from_secs(1), - }, - &stats_repository, - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_responses, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_errors_counter_when_it_receives_a_udp4_error_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Udp4Error, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_errors_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_requests_counter_when_it_receives_a_udp6_request_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Udp6Request, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_requests, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_response_counter_when_it_receives_a_udp6_response_event() { - let stats_repository = Repository::new(); - - handle_event( - Event::Udp6Response { - kind: crate::statistics::event::UdpResponseKind::Announce, - req_processing_time: std::time::Duration::from_secs(1), - }, - &stats_repository, - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_responses, 1); - } - #[tokio::test] - async fn should_increase_the_udp6_errors_counter_when_it_receives_a_udp6_error_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Udp6Error, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_errors_handled, 1); - } } diff --git a/packages/udp-tracker-core/src/statistics/event/mod.rs b/packages/udp-tracker-core/src/statistics/event/mod.rs index 6a5343933..bfc733657 100644 --- a/packages/udp-tracker-core/src/statistics/event/mod.rs +++ b/packages/udp-tracker-core/src/statistics/event/mod.rs @@ -1,5 +1,3 @@ -use std::time::Duration; - pub mod handler; pub mod listener; pub mod sender; @@ -16,32 +14,10 @@ pub mod sender; pub enum Event { // code-review: consider one single event for request type with data: Event::Announce { scheme: HTTPorUDP, ip_version: V4orV6 } // Attributes are enums too. - UdpRequestAborted, - UdpRequestBanned, - Udp4Request, Udp4Connect, Udp4Announce, Udp4Scrape, - Udp4Response { - kind: UdpResponseKind, - req_processing_time: Duration, - }, - Udp4Error, - Udp6Request, Udp6Connect, Udp6Announce, Udp6Scrape, - Udp6Response { - kind: UdpResponseKind, - req_processing_time: Duration, - }, - Udp6Error, -} - -#[derive(Debug, PartialEq, Eq)] -pub enum UdpResponseKind { - Connect, - Announce, - Scrape, - Error, } diff --git a/packages/udp-tracker-core/src/statistics/metrics.rs b/packages/udp-tracker-core/src/statistics/metrics.rs index 23357aab6..1b3805288 100644 --- a/packages/udp-tracker-core/src/statistics/metrics.rs +++ b/packages/udp-tracker-core/src/statistics/metrics.rs @@ -8,29 +8,6 @@ /// and also for each IP version used by the peers: IPv4 and IPv6. #[derive(Debug, PartialEq, Default)] pub struct Metrics { - // UDP - /// Total number of UDP (UDP tracker) requests aborted. - pub udp_requests_aborted: u64, - - /// Total number of UDP (UDP tracker) requests banned. - pub udp_requests_banned: u64, - - /// Total number of banned IPs. - pub udp_banned_ips_total: u64, - - /// Average rounded time spent processing UDP connect requests. - pub udp_avg_connect_processing_time_ns: u64, - - /// Average rounded time spent processing UDP announce requests. - pub udp_avg_announce_processing_time_ns: u64, - - /// Average rounded time spent processing UDP scrape requests. - pub udp_avg_scrape_processing_time_ns: u64, - - // UDPv4 - /// Total number of UDP (UDP tracker) requests from IPv4 peers. - pub udp4_requests: u64, - /// Total number of UDP (UDP tracker) connections from IPv4 peers. pub udp4_connections_handled: u64, @@ -40,16 +17,6 @@ pub struct Metrics { /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. pub udp4_scrapes_handled: u64, - /// Total number of UDP (UDP tracker) responses from IPv4 peers. - pub udp4_responses: u64, - - /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. - pub udp4_errors_handled: u64, - - // UDPv6 - /// Total number of UDP (UDP tracker) requests from IPv6 peers. - pub udp6_requests: u64, - /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. pub udp6_connections_handled: u64, @@ -58,10 +25,4 @@ pub struct Metrics { /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. pub udp6_scrapes_handled: u64, - - /// Total number of UDP (UDP tracker) responses from IPv6 peers. - pub udp6_responses: u64, - - /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. - pub udp6_errors_handled: u64, } diff --git a/packages/udp-tracker-core/src/statistics/repository.rs b/packages/udp-tracker-core/src/statistics/repository.rs index 22e793036..f7609e5c2 100644 --- a/packages/udp-tracker-core/src/statistics/repository.rs +++ b/packages/udp-tracker-core/src/statistics/repository.rs @@ -1,5 +1,4 @@ use std::sync::Arc; -use std::time::Duration; use tokio::sync::{RwLock, RwLockReadGuard}; @@ -29,24 +28,6 @@ impl Repository { self.stats.read().await } - pub async fn increase_udp_requests_aborted(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp_requests_aborted += 1; - drop(stats_lock); - } - - pub async fn increase_udp_requests_banned(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp_requests_banned += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_requests(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_requests += 1; - drop(stats_lock); - } - pub async fn increase_udp4_connections(&self) { let mut stats_lock = self.stats.write().await; stats_lock.udp4_connections_handled += 1; @@ -65,82 +46,6 @@ impl Repository { drop(stats_lock); } - pub async fn increase_udp4_responses(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_responses += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_errors(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_errors_handled += 1; - drop(stats_lock); - } - - #[allow(clippy::cast_precision_loss)] - #[allow(clippy::cast_possible_truncation)] - #[allow(clippy::cast_sign_loss)] - pub async fn recalculate_udp_avg_connect_processing_time_ns(&self, req_processing_time: Duration) { - let mut stats_lock = self.stats.write().await; - - let req_processing_time = req_processing_time.as_nanos() as f64; - let udp_connections_handled = (stats_lock.udp4_connections_handled + stats_lock.udp6_connections_handled) as f64; - - let previous_avg = stats_lock.udp_avg_connect_processing_time_ns; - - // Moving average: https://en.wikipedia.org/wiki/Moving_average - let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_connections_handled; - - stats_lock.udp_avg_connect_processing_time_ns = new_avg.ceil() as u64; - - drop(stats_lock); - } - - #[allow(clippy::cast_precision_loss)] - #[allow(clippy::cast_possible_truncation)] - #[allow(clippy::cast_sign_loss)] - pub async fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) { - let mut stats_lock = self.stats.write().await; - - let req_processing_time = req_processing_time.as_nanos() as f64; - - let udp_announces_handled = (stats_lock.udp4_announces_handled + stats_lock.udp6_announces_handled) as f64; - - let previous_avg = stats_lock.udp_avg_announce_processing_time_ns; - - // Moving average: https://en.wikipedia.org/wiki/Moving_average - let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_announces_handled; - - stats_lock.udp_avg_announce_processing_time_ns = new_avg.ceil() as u64; - - drop(stats_lock); - } - - #[allow(clippy::cast_precision_loss)] - #[allow(clippy::cast_possible_truncation)] - #[allow(clippy::cast_sign_loss)] - pub async fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) { - let mut stats_lock = self.stats.write().await; - - let req_processing_time = req_processing_time.as_nanos() as f64; - let udp_scrapes_handled = (stats_lock.udp4_scrapes_handled + stats_lock.udp6_scrapes_handled) as f64; - - let previous_avg = stats_lock.udp_avg_scrape_processing_time_ns; - - // Moving average: https://en.wikipedia.org/wiki/Moving_average - let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_scrapes_handled; - - stats_lock.udp_avg_scrape_processing_time_ns = new_avg.ceil() as u64; - - drop(stats_lock); - } - - pub async fn increase_udp6_requests(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_requests += 1; - drop(stats_lock); - } - pub async fn increase_udp6_connections(&self) { let mut stats_lock = self.stats.write().await; stats_lock.udp6_connections_handled += 1; @@ -158,16 +63,4 @@ impl Repository { stats_lock.udp6_scrapes_handled += 1; drop(stats_lock); } - - pub async fn increase_udp6_responses(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_responses += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_errors(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_errors_handled += 1; - drop(stats_lock); - } } diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index 486aaac06..7ffa127e6 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -39,10 +39,8 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use tokio::sync::RwLock; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use crate::services::banning::BanService; use crate::statistics::metrics::Metrics; use crate::statistics::repository::Repository; @@ -63,37 +61,22 @@ pub struct TrackerMetrics { /// It returns all the [`TrackerMetrics`] pub async fn get_metrics( in_memory_torrent_repository: Arc, - ban_service: Arc>, stats_repository: Arc, ) -> TrackerMetrics { let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); let stats = stats_repository.get_stats().await; - let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); TrackerMetrics { torrents_metrics, protocol_metrics: Metrics { - // UDP - udp_requests_aborted: stats.udp_requests_aborted, - udp_requests_banned: stats.udp_requests_banned, - udp_banned_ips_total: udp_banned_ips_total as u64, - udp_avg_connect_processing_time_ns: stats.udp_avg_connect_processing_time_ns, - udp_avg_announce_processing_time_ns: stats.udp_avg_announce_processing_time_ns, - udp_avg_scrape_processing_time_ns: stats.udp_avg_scrape_processing_time_ns, // UDPv4 - udp4_requests: stats.udp4_requests, udp4_connections_handled: stats.udp4_connections_handled, udp4_announces_handled: stats.udp4_announces_handled, udp4_scrapes_handled: stats.udp4_scrapes_handled, - udp4_responses: stats.udp4_responses, - udp4_errors_handled: stats.udp4_errors_handled, // UDPv6 - udp6_requests: stats.udp6_requests, udp6_connections_handled: stats.udp6_connections_handled, udp6_announces_handled: stats.udp6_announces_handled, udp6_scrapes_handled: stats.udp6_scrapes_handled, - udp6_responses: stats.udp6_responses, - udp6_errors_handled: stats.udp6_errors_handled, }, } } @@ -104,14 +87,12 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self}; - use tokio::sync::RwLock; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use torrust_tracker_test_helpers::configuration; - use crate::services::banning::BanService; + use crate::statistics; use crate::statistics::services::{get_metrics, TrackerMetrics}; - use crate::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -122,17 +103,12 @@ mod tests { let config = tracker_configuration(); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let (_udp_stats_event_sender, udp_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let udp_stats_repository = Arc::new(udp_stats_repository); + let (_udp_core_stats_event_sender, udp_core_stats_repository) = + crate::statistics::setup::factory(config.core.tracker_usage_statistics); + let udp_core_stats_repository = Arc::new(udp_core_stats_repository); - let tracker_metrics = get_metrics( - in_memory_torrent_repository.clone(), - ban_service.clone(), - udp_stats_repository.clone(), - ) - .await; + let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), udp_core_stats_repository.clone()).await; assert_eq!( tracker_metrics, diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs new file mode 100644 index 000000000..36ad0e671 --- /dev/null +++ b/packages/udp-tracker-server/src/container.rs @@ -0,0 +1,25 @@ +use std::sync::Arc; + +use torrust_tracker_configuration::Core; + +use crate::statistics; + +pub struct UdpTrackerServerContainer { + pub udp_server_stats_event_sender: Arc>>, + pub udp_server_stats_repository: Arc, +} + +impl UdpTrackerServerContainer { + #[must_use] + pub fn initialize(core_config: &Arc) -> Arc { + let (udp_server_stats_event_sender, udp_server_stats_repository) = + statistics::setup::factory(core_config.tracker_usage_statistics); + let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); + let udp_server_stats_repository = Arc::new(udp_server_stats_repository); + + Arc::new(Self { + udp_server_stats_event_sender: udp_server_stats_event_sender.clone(), + udp_server_stats_repository: udp_server_stats_repository.clone(), + }) + } +} diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 0ab3bdea1..c6ec98290 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -8,6 +8,7 @@ use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_primitives::peer; +use crate::container::UdpTrackerServerContainer; use crate::server::spawner::Spawner; use crate::server::states::{Running, Stopped}; use crate::server::Server; @@ -71,6 +72,7 @@ impl Environment { .server .start( self.container.udp_tracker_core_container.clone(), + self.container.udp_tracker_server_container.clone(), self.registar.give_form(), cookie_lifetime, ) @@ -115,6 +117,7 @@ impl Environment { pub struct EnvContainer { pub tracker_core_container: Arc, pub udp_tracker_core_container: Arc, + pub udp_tracker_server_container: Arc, } impl EnvContainer { @@ -129,10 +132,12 @@ impl EnvContainer { let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from(&tracker_core_container, &udp_tracker_config); + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); Self { tracker_core_container, udp_tracker_core_container, + udp_tracker_server_container, } } } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 7e3b8e7dd..97ce6ba4a 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -10,13 +10,15 @@ use aquatic_udp_protocol::{ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::whitelist; -use bittorrent_udp_tracker_core::{services, statistics}; +use bittorrent_udp_tracker_core::{services, statistics as core_statistics}; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; use crate::error::Error; +use crate::statistics as server_statistics; +use crate::statistics::event::UdpResponseKind; /// It handles the `Announce` request. /// @@ -24,14 +26,15 @@ use crate::error::Error; /// /// If a error happens in the `handle_announce` function, it will just return the `ServerError`. #[allow(clippy::too_many_arguments)] -#[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_handler, whitelist_authorization, opt_udp_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_handler, whitelist_authorization, opt_udp_core_stats_event_sender, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_announce( remote_addr: SocketAddr, request: &AnnounceRequest, core_config: &Arc, announce_handler: &Arc, whitelist_authorization: &Arc, - opt_udp_stats_event_sender: &Arc>>, + opt_udp_core_stats_event_sender: &Arc>>, + opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { tracing::Span::current() @@ -41,12 +44,31 @@ pub async fn handle_announce( tracing::trace!("handle announce"); + if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { + match remote_addr.ip() { + IpAddr::V4(_) => { + udp_server_stats_event_sender + .send_event(server_statistics::event::Event::Udp4Request { + kind: UdpResponseKind::Announce, + }) + .await; + } + IpAddr::V6(_) => { + udp_server_stats_event_sender + .send_event(server_statistics::event::Event::Udp6Request { + kind: UdpResponseKind::Announce, + }) + .await; + } + } + } + let announce_data = services::announce::handle_announce( remote_addr, request, announce_handler, whitelist_authorization, - opt_udp_stats_event_sender, + opt_udp_core_stats_event_sender, cookie_valid_range, ) .await @@ -205,7 +227,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; - use bittorrent_udp_tracker_core::statistics; + use bittorrent_udp_tracker_core::statistics as core_statistics; use mockall::predicate::eq; use torrust_tracker_configuration::Core; @@ -214,12 +236,15 @@ mod tests { use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, - sample_issue_time, MockUdpStatsEventSender, TorrentPeerBuilder, + sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, TorrentPeerBuilder, }; + use crate::statistics as server_statistics; + use crate::statistics::event::UdpResponseKind; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); let client_ip = Ipv4Addr::new(126, 0, 0, 1); let client_port = 8080; @@ -242,7 +267,8 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, + &core_udp_tracker_services.udp_core_stats_event_sender, + &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -263,7 +289,8 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); @@ -277,7 +304,8 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, + &core_udp_tracker_services.udp_core_stats_event_sender, + &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -304,7 +332,8 @@ mod tests { // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): // "Do note that most trackers will only honor the IP address field under limited circumstances." - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -330,7 +359,8 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, + &core_udp_tracker_services.udp_core_stats_event_sender, + &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -364,9 +394,12 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let (udp_stats_event_sender, _udp_stats_repository) = + let (udp_core_stats_event_sender, _udp_core_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + + let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let request = AnnounceRequestBuilder::default() @@ -379,7 +412,8 @@ mod tests { &core_config, &announce_handler, &whitelist_authorization, - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -388,7 +422,8 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { - let (core_tracker_services, _core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); add_a_torrent_peer_using_ipv6(&core_tracker_services.in_memory_torrent_repository); @@ -410,16 +445,27 @@ mod tests { #[tokio::test] async fn should_send_the_upd4_announce_event() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); + udp_core_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Udp4Announce)) + .with(eq(core_statistics::event::Event::Udp4Announce)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let udp_core_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); - let (core_tracker_services, _core_udp_tracker_services) = + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock + .expect_send_event() + .with(eq(server_statistics::event::Event::Udp4Request { + kind: UdpResponseKind::Announce, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_server_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); + + let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); handle_announce( @@ -428,7 +474,8 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -451,7 +498,7 @@ mod tests { #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration_if_defined() { - let (core_tracker_services, core_udp_tracker_services) = + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); let client_ip = Ipv4Addr::new(127, 0, 0, 1); @@ -475,7 +522,8 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, + &core_udp_tracker_services.udp_core_stats_event_sender, + &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -512,7 +560,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; - use bittorrent_udp_tracker_core::statistics; + use bittorrent_udp_tracker_core::statistics as core_statistics; use mockall::predicate::eq; use torrust_tracker_configuration::Core; @@ -521,12 +569,15 @@ mod tests { use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, - sample_issue_time, MockUdpStatsEventSender, TorrentPeerBuilder, + sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, TorrentPeerBuilder, }; + use crate::statistics as server_statistics; + use crate::statistics::event::UdpResponseKind; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -550,7 +601,8 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, + &core_udp_tracker_services.udp_core_stats_event_sender, + &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -571,7 +623,8 @@ mod tests { #[tokio::test] async fn the_announced_peer_should_not_be_included_in_the_response() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -588,7 +641,8 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, + &core_udp_tracker_services.udp_core_stats_event_sender, + &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -615,7 +669,8 @@ mod tests { // From the BEP 15 (https://www.bittorrent.org/beps/bep_0015.html): // "Do note that most trackers will only honor the IP address field under limited circumstances." - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_service) = + initialize_core_tracker_services_for_public_tracker(); let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -641,7 +696,8 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_stats_event_sender, + &core_udp_tracker_services.udp_core_stats_event_sender, + &server_udp_tracker_service.udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -675,9 +731,12 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let (udp_stats_event_sender, _udp_stats_repository) = + let (udp_core_stats_event_sender, _udp_core_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + + let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); @@ -693,7 +752,8 @@ mod tests { &core_config, &announce_handler, &whitelist_authorization, - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -702,7 +762,8 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv6_the_response_should_not_include_peers_using_ipv4() { - let (core_tracker_services, _core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); add_a_torrent_peer_using_ipv4(&core_tracker_services.in_memory_torrent_repository); @@ -724,16 +785,27 @@ mod tests { #[tokio::test] async fn should_send_the_upd6_announce_event() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); + udp_core_stats_event_sender_mock + .expect_send_event() + .with(eq(core_statistics::event::Event::Udp6Announce)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_core_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Udp6Announce)) + .with(eq(server_statistics::event::Event::Udp6Request { + kind: UdpResponseKind::Announce, + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let udp_server_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); - let (core_tracker_services, _core_udp_tracker_services) = + let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); let remote_addr = sample_ipv6_remote_addr(); @@ -748,7 +820,8 @@ mod tests { &core_tracker_services.core_config, &core_tracker_services.announce_handler, &core_tracker_services.whitelist_authorization, - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -768,14 +841,17 @@ mod tests { use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; - use bittorrent_udp_tracker_core::{self, statistics}; + use bittorrent_udp_tracker_core::{self, statistics as core_statistics}; use mockall::predicate::eq; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::handlers::handle_announce; use crate::handlers::tests::{ - sample_cookie_valid_range, sample_issue_time, MockUdpStatsEventSender, TrackerConfigurationBuilder, + sample_cookie_valid_range, sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, + TrackerConfigurationBuilder, }; + use crate::statistics as server_statistics; + use crate::statistics::event::UdpResponseKind; #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { @@ -788,14 +864,25 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); + udp_core_stats_event_sender_mock + .expect_send_event() + .with(eq(core_statistics::event::Event::Udp6Announce)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_core_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Udp6Announce)) + .with(eq(server_statistics::event::Event::Udp6Request { + kind: UdpResponseKind::Announce, + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let udp_server_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, @@ -832,7 +919,8 @@ mod tests { &core_config, &announce_handler, &whitelist_authorization, - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index d1c3a05d8..be6dc45d4 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -1,23 +1,46 @@ //! UDP tracker connect handler. -use std::net::SocketAddr; +use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, ConnectionId, Response}; -use bittorrent_udp_tracker_core::{services, statistics}; +use bittorrent_udp_tracker_core::{services, statistics as core_statistics}; use tracing::{instrument, Level}; +use crate::statistics as server_statistics; +use crate::statistics::event::UdpResponseKind; + /// It handles the `Connect` request. -#[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id), skip(opt_udp_core_stats_event_sender, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_connect( remote_addr: SocketAddr, request: &ConnectRequest, - opt_udp_stats_event_sender: &Arc>>, + opt_udp_core_stats_event_sender: &Arc>>, + opt_udp_server_stats_event_sender: &Arc>>, cookie_issue_time: f64, ) -> Response { tracing::Span::current().record("transaction_id", request.transaction_id.0.to_string()); tracing::trace!("handle connect"); - let connection_id = services::connect::handle_connect(remote_addr, opt_udp_stats_event_sender, cookie_issue_time).await; + if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { + match remote_addr.ip() { + IpAddr::V4(_) => { + udp_server_stats_event_sender + .send_event(server_statistics::event::Event::Udp4Request { + kind: UdpResponseKind::Connect, + }) + .await; + } + IpAddr::V6(_) => { + udp_server_stats_event_sender + .send_event(server_statistics::event::Event::Udp6Request { + kind: UdpResponseKind::Connect, + }) + .await; + } + } + } + + let connection_id = services::connect::handle_connect(remote_addr, opt_udp_core_stats_event_sender, cookie_issue_time).await; build_response(*request, connection_id) } @@ -41,14 +64,16 @@ mod tests { use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; use bittorrent_udp_tracker_core::connection_cookie::make; - use bittorrent_udp_tracker_core::statistics; + use bittorrent_udp_tracker_core::statistics as core_statistics; use mockall::predicate::eq; use crate::handlers::handle_connect; use crate::handlers::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, - sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpStatsEventSender, + sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, }; + use crate::statistics as server_statistics; + use crate::statistics::event::UdpResponseKind; fn sample_connect_request() -> ConnectRequest { ConnectRequest { @@ -58,8 +83,12 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { - let (udp_stats_event_sender, _udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + + let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), @@ -68,7 +97,8 @@ mod tests { let response = handle_connect( sample_ipv4_remote_addr(), &request, - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_issue_time(), ) .await; @@ -84,8 +114,12 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { - let (udp_stats_event_sender, _udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + + let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), @@ -94,7 +128,8 @@ mod tests { let response = handle_connect( sample_ipv4_remote_addr(), &request, - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_issue_time(), ) .await; @@ -110,8 +145,12 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { - let (udp_stats_event_sender, _udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + + let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), @@ -120,7 +159,8 @@ mod tests { let response = handle_connect( sample_ipv6_remote_addr(), &request, - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_issue_time(), ) .await; @@ -136,21 +176,33 @@ mod tests { #[tokio::test] async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); + udp_core_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Udp4Connect)) + .with(eq(core_statistics::event::Event::Udp4Connect)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let udp_core_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock + .expect_send_event() + .with(eq(server_statistics::event::Event::Udp4Request { + kind: UdpResponseKind::Connect, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_server_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let client_socket_address = sample_ipv4_socket_address(); handle_connect( client_socket_address, &sample_connect_request(), - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_issue_time(), ) .await; @@ -158,19 +210,31 @@ mod tests { #[tokio::test] async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); + udp_core_stats_event_sender_mock + .expect_send_event() + .with(eq(core_statistics::event::Event::Udp6Connect)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_core_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Udp6Connect)) + .with(eq(server_statistics::event::Event::Udp6Request { + kind: UdpResponseKind::Connect, + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let udp_server_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); handle_connect( sample_ipv6_remote_addr(), &sample_connect_request(), - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_issue_time(), ) .await; diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index 4f2457126..e4bd382da 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -5,20 +5,21 @@ use std::sync::Arc; use aquatic_udp_protocol::{ErrorResponse, RequestParseError, Response, TransactionId}; use bittorrent_udp_tracker_core::connection_cookie::{check, gen_remote_fingerprint}; -use bittorrent_udp_tracker_core::{self, statistics, UDP_TRACKER_LOG_TARGET}; +use bittorrent_udp_tracker_core::{self, UDP_TRACKER_LOG_TARGET}; use tracing::{instrument, Level}; use uuid::Uuid; use zerocopy::network_endian::I32; use crate::error::Error; +use crate::statistics as server_statistics; #[allow(clippy::too_many_arguments)] -#[instrument(fields(transaction_id), skip(opt_udp_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id), skip(opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_error( remote_addr: SocketAddr, local_addr: SocketAddr, request_id: Uuid, - opt_udp_stats_event_sender: &Arc>>, + opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, e: &Error, transaction_id: Option, @@ -55,13 +56,17 @@ pub async fn handle_error( }; if e.1.is_some() { - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { + if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { match remote_addr { SocketAddr::V4(_) => { - udp_stats_event_sender.send_event(statistics::event::Event::Udp4Error).await; + udp_server_stats_event_sender + .send_event(server_statistics::event::Event::Udp4Error) + .await; } SocketAddr::V6(_) => { - udp_stats_event_sender.send_event(statistics::event::Event::Udp6Error).await; + udp_server_stats_event_sender + .send_event(server_statistics::event::Event::Udp6Error) + .await; } } } diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 5d7fdb3b3..fd0536b8b 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -22,6 +22,7 @@ use tracing::{instrument, Level}; use uuid::Uuid; use super::RawRequest; +use crate::container::UdpTrackerServerContainer; use crate::error::Error; use crate::CurrentClock; @@ -52,10 +53,11 @@ impl CookieTimeValues { /// - Delegating the request to the correct handler depending on the request type. /// /// It will return an `Error` response if the request is invalid. -#[instrument(fields(request_id), skip(udp_request, udp_tracker_container, cookie_time_values), ret(level = Level::TRACE))] +#[instrument(fields(request_id), skip(udp_request, udp_tracker_core_container, udp_tracker_server_container, cookie_time_values), ret(level = Level::TRACE))] pub(crate) async fn handle_packet( udp_request: RawRequest, - udp_tracker_container: Arc, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, local_addr: SocketAddr, cookie_time_values: CookieTimeValues, ) -> Response { @@ -71,7 +73,8 @@ pub(crate) async fn handle_packet( Ok(request) => match handle_request( request, udp_request.from, - udp_tracker_container.clone(), + udp_tracker_core_container.clone(), + udp_tracker_server_container.clone(), cookie_time_values.clone(), ) .await @@ -83,7 +86,7 @@ pub(crate) async fn handle_packet( } = error { // code-review: should we include `RequestParseError` and `BadRequest`? - let mut ban_service = udp_tracker_container.ban_service.write().await; + let mut ban_service = udp_tracker_core_container.ban_service.write().await; ban_service.increase_counter(&udp_request.from.ip()); } @@ -91,7 +94,7 @@ pub(crate) async fn handle_packet( udp_request.from, local_addr, request_id, - &udp_tracker_container.udp_stats_event_sender, + &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range.clone(), &error, Some(transaction_id), @@ -104,7 +107,7 @@ pub(crate) async fn handle_packet( udp_request.from, local_addr, request_id, - &udp_tracker_container.udp_stats_event_sender, + &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range.clone(), &e, None, @@ -124,11 +127,18 @@ pub(crate) async fn handle_packet( /// # Errors /// /// If a error happens in the `handle_request` function, it will just return the `ServerError`. -#[instrument(skip(request, remote_addr, udp_tracker_container, cookie_time_values))] +#[instrument(skip( + request, + remote_addr, + udp_tracker_core_container, + udp_tracker_server_container, + cookie_time_values +))] pub async fn handle_request( request: Request, remote_addr: SocketAddr, - udp_tracker_container: Arc, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, cookie_time_values: CookieTimeValues, ) -> Result { tracing::trace!("handle request"); @@ -137,7 +147,8 @@ pub async fn handle_request( Request::Connect(connect_request) => Ok(handle_connect( remote_addr, &connect_request, - &udp_tracker_container.udp_stats_event_sender, + &udp_tracker_core_container.udp_core_stats_event_sender, + &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.issue_time, ) .await), @@ -145,10 +156,11 @@ pub async fn handle_request( handle_announce( remote_addr, &announce_request, - &udp_tracker_container.core_config, - &udp_tracker_container.announce_handler, - &udp_tracker_container.whitelist_authorization, - &udp_tracker_container.udp_stats_event_sender, + &udp_tracker_core_container.core_config, + &udp_tracker_core_container.announce_handler, + &udp_tracker_core_container.whitelist_authorization, + &udp_tracker_core_container.udp_core_stats_event_sender, + &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range, ) .await @@ -157,8 +169,9 @@ pub async fn handle_request( handle_scrape( remote_addr, &scrape_request, - &udp_tracker_container.scrape_handler, - &udp_tracker_container.udp_stats_event_sender, + &udp_tracker_core_container.scrape_handler, + &udp_tracker_core_container.udp_core_stats_event_sender, + &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range, ) .await @@ -183,7 +196,7 @@ pub(crate) mod tests { use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::gen_remote_fingerprint; - use bittorrent_udp_tracker_core::{self, statistics}; + use bittorrent_udp_tracker_core::{self, statistics as core_statistics}; use futures::future::BoxFuture; use mockall::mock; use tokio::sync::mpsc::error::SendError; @@ -192,7 +205,7 @@ pub(crate) mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::CurrentClock; + use crate::{statistics as server_statistics, CurrentClock}; pub(crate) struct CoreTrackerServices { pub core_config: Arc, @@ -204,7 +217,11 @@ pub(crate) mod tests { } pub(crate) struct CoreUdpTrackerServices { - pub udp_stats_event_sender: Arc>>, + pub udp_core_stats_event_sender: Arc>>, + } + + pub(crate) struct ServerUdpTrackerServices { + pub udp_server_stats_event_sender: Arc>>, } fn default_testing_tracker_configuration() -> Configuration { @@ -212,19 +229,23 @@ pub(crate) mod tests { } pub(crate) fn initialize_core_tracker_services_for_default_tracker_configuration( - ) -> (CoreTrackerServices, CoreUdpTrackerServices) { + ) -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { initialize_core_tracker_services(&default_testing_tracker_configuration()) } - pub(crate) fn initialize_core_tracker_services_for_public_tracker() -> (CoreTrackerServices, CoreUdpTrackerServices) { + pub(crate) fn initialize_core_tracker_services_for_public_tracker( + ) -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_public()) } - pub(crate) fn initialize_core_tracker_services_for_listed_tracker() -> (CoreTrackerServices, CoreUdpTrackerServices) { + pub(crate) fn initialize_core_tracker_services_for_listed_tracker( + ) -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_listed()) } - fn initialize_core_tracker_services(config: &Configuration) -> (CoreTrackerServices, CoreUdpTrackerServices) { + fn initialize_core_tracker_services( + config: &Configuration, + ) -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { let core_config = Arc::new(config.core.clone()); let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -239,8 +260,12 @@ pub(crate) mod tests { )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - let (udp_stats_event_sender, _udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + + let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); ( CoreTrackerServices { @@ -251,7 +276,12 @@ pub(crate) mod tests { in_memory_whitelist, whitelist_authorization, }, - CoreUdpTrackerServices { udp_stats_event_sender }, + CoreUdpTrackerServices { + udp_core_stats_event_sender, + }, + ServerUdpTrackerServices { + udp_server_stats_event_sender, + }, ) } @@ -356,9 +386,16 @@ pub(crate) mod tests { } mock! { - pub(crate) UdpStatsEventSender {} - impl statistics::event::sender::Sender for UdpStatsEventSender { - fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + pub(crate) UdpCoreStatsEventSender {} + impl core_statistics::event::sender::Sender for UdpCoreStatsEventSender { + fn send_event(&self, event: core_statistics::event::Event) -> BoxFuture<'static,Option > > > ; + } + } + + mock! { + pub(crate) UdpServerStatsEventSender {} + impl server_statistics::event::sender::Sender for UdpServerStatsEventSender { + fn send_event(&self, event: server_statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } } diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index de98b5f6d..248f0ca12 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -1,5 +1,5 @@ //! UDP tracker scrape handler. -use std::net::SocketAddr; +use std::net::{IpAddr, SocketAddr}; use std::ops::Range; use std::sync::Arc; @@ -7,25 +7,27 @@ use aquatic_udp_protocol::{ NumberOfDownloads, NumberOfPeers, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_udp_tracker_core::statistics::{self}; -use bittorrent_udp_tracker_core::{self, services}; +use bittorrent_udp_tracker_core::{self, services, statistics as core_statistics}; use torrust_tracker_primitives::core::ScrapeData; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; use crate::error::Error; +use crate::statistics as server_statistics; +use crate::statistics::event::UdpResponseKind; /// It handles the `Scrape` request. /// /// # Errors /// /// This function does not ever return an error. -#[instrument(fields(transaction_id, connection_id), skip(scrape_handler, opt_udp_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id), skip(scrape_handler, opt_udp_core_stats_event_sender, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_scrape( remote_addr: SocketAddr, request: &ScrapeRequest, scrape_handler: &Arc, - opt_udp_stats_event_sender: &Arc>>, + opt_udp_core_stats_event_sender: &Arc>>, + opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { tracing::Span::current() @@ -34,11 +36,30 @@ pub async fn handle_scrape( tracing::trace!("handle scrape"); + if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { + match remote_addr.ip() { + IpAddr::V4(_) => { + udp_server_stats_event_sender + .send_event(server_statistics::event::Event::Udp4Request { + kind: UdpResponseKind::Scrape, + }) + .await; + } + IpAddr::V6(_) => { + udp_server_stats_event_sender + .send_event(server_statistics::event::Event::Udp6Request { + kind: UdpResponseKind::Scrape, + }) + .await; + } + } + } + let scrape_data = services::scrape::handle_scrape( remote_addr, request, scrape_handler, - opt_udp_stats_event_sender, + opt_udp_core_stats_event_sender, cookie_valid_range, ) .await @@ -104,7 +125,8 @@ mod tests { #[tokio::test] async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); let remote_addr = sample_ipv4_remote_addr(); @@ -121,7 +143,8 @@ mod tests { remote_addr, &request, &core_tracker_services.scrape_handler, - &core_udp_tracker_services.udp_stats_event_sender, + &core_udp_tracker_services.udp_core_stats_event_sender, + &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -168,8 +191,12 @@ mod tests { in_memory_torrent_repository: Arc, scrape_handler: Arc, ) -> Response { - let (udp_stats_event_sender, _udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = + bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + + let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -182,7 +209,8 @@ mod tests { remote_addr, &request, &scrape_handler, - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -204,7 +232,8 @@ mod tests { #[tokio::test] async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { - let (core_tracker_services, _core_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); + let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = + initialize_core_tracker_services_for_public_tracker(); let torrent_stats = match_scrape_response( add_a_sample_seeder_and_scrape( @@ -237,7 +266,8 @@ mod tests { #[tokio::test] async fn should_return_the_torrent_statistics_when_the_requested_torrent_is_whitelisted() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_listed_tracker(); + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_listed_tracker(); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -258,7 +288,8 @@ mod tests { remote_addr, &request, &core_tracker_services.scrape_handler, - &core_udp_tracker_services.udp_stats_event_sender, + &core_udp_tracker_services.udp_core_stats_event_sender, + &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -277,7 +308,8 @@ mod tests { #[tokio::test] async fn should_return_zeroed_statistics_when_the_requested_torrent_is_not_whitelisted() { - let (core_tracker_services, core_udp_tracker_services) = initialize_core_tracker_services_for_listed_tracker(); + let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + initialize_core_tracker_services_for_listed_tracker(); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); @@ -296,7 +328,8 @@ mod tests { remote_addr, &request, &core_tracker_services.scrape_handler, - &core_udp_tracker_services.udp_stats_event_sender, + &core_udp_tracker_services.udp_core_stats_event_sender, + &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -325,37 +358,50 @@ mod tests { use std::future; use std::sync::Arc; - use bittorrent_udp_tracker_core::statistics; + use bittorrent_udp_tracker_core::statistics as core_statistics; use mockall::predicate::eq; use super::sample_scrape_request; use crate::handlers::handle_scrape; use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, - sample_ipv4_remote_addr, MockUdpStatsEventSender, + sample_ipv4_remote_addr, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, }; + use crate::statistics as server_statistics; #[tokio::test] async fn should_send_the_upd4_scrape_event() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); + udp_core_stats_event_sender_mock + .expect_send_event() + .with(eq(core_statistics::event::Event::Udp4Scrape)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_core_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Udp4Scrape)) + .with(eq(server_statistics::event::Event::Udp4Request { + kind: server_statistics::event::UdpResponseKind::Scrape, + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let udp_server_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let remote_addr = sample_ipv4_remote_addr(); - let (core_tracker_services, _core_udp_tracker_services) = + let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); handle_scrape( remote_addr, &sample_scrape_request(&remote_addr), &core_tracker_services.scrape_handler, - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await @@ -367,37 +413,50 @@ mod tests { use std::future; use std::sync::Arc; - use bittorrent_udp_tracker_core::statistics; + use bittorrent_udp_tracker_core::statistics as core_statistics; use mockall::predicate::eq; use super::sample_scrape_request; use crate::handlers::handle_scrape; use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, - sample_ipv6_remote_addr, MockUdpStatsEventSender, + sample_ipv6_remote_addr, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, }; + use crate::statistics as server_statistics; #[tokio::test] async fn should_send_the_upd6_scrape_event() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); - udp_stats_event_sender_mock + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); + udp_core_stats_event_sender_mock + .expect_send_event() + .with(eq(core_statistics::event::Event::Udp6Scrape)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + let udp_core_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); + + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); + udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Udp6Scrape)) + .with(eq(server_statistics::event::Event::Udp6Request { + kind: server_statistics::event::UdpResponseKind::Scrape, + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let udp_server_stats_event_sender: Arc>> = + Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let remote_addr = sample_ipv6_remote_addr(); - let (core_tracker_services, _core_udp_tracker_services) = + let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); handle_scrape( remote_addr, &sample_scrape_request(&remote_addr), &core_tracker_services.scrape_handler, - &udp_stats_event_sender, + &udp_core_stats_event_sender, + &udp_server_stats_event_sender, sample_cookie_valid_range(), ) .await diff --git a/packages/udp-tracker-server/src/lib.rs b/packages/udp-tracker-server/src/lib.rs index e02011a8b..9e013bf81 100644 --- a/packages/udp-tracker-server/src/lib.rs +++ b/packages/udp-tracker-server/src/lib.rs @@ -634,6 +634,7 @@ //! documentation by [Arvid Norberg](https://github.com/arvidn) was very //! supportive in the development of this documentation. Some descriptions were //! taken from the [libtorrent](https://www.rasterbar.com/products/libtorrent/udp_tracker_protocol.html). +pub mod container; pub mod environment; pub mod error; pub mod handlers; diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index 12d9c740c..acd214ab0 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -4,7 +4,7 @@ use std::time::Duration; use bittorrent_tracker_client::udp::client::check; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; -use bittorrent_udp_tracker_core::{self, statistics, UDP_TRACKER_LOG_TARGET}; +use bittorrent_udp_tracker_core::{self, UDP_TRACKER_LOG_TARGET}; use derive_more::Constructor; use futures_util::StreamExt; use tokio::select; @@ -16,9 +16,11 @@ use torrust_server_lib::signals::{shutdown_signal_with_message, Halted, Started} use tracing::instrument; use super::request_buffer::ActiveRequests; +use crate::container::UdpTrackerServerContainer; use crate::server::bound_socket::BoundSocket; use crate::server::processor::Processor; use crate::server::receiver::Receiver; +use crate::statistics; const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 3600; @@ -34,9 +36,10 @@ impl Launcher { /// It panics if unable to bind to udp socket, and get the address from the udp socket. /// It panics if unable to send address of socket. /// It panics if the udp server is loaded when the tracker is private. - #[instrument(skip(udp_tracker_container, bind_to, tx_start, rx_halt))] + #[instrument(skip(udp_tracker_core_container, udp_tracker_server_container, bind_to, tx_start, rx_halt))] pub async fn run_with_graceful_shutdown( - udp_tracker_container: Arc, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, bind_to: SocketAddr, cookie_lifetime: Duration, tx_start: oneshot::Sender, @@ -44,7 +47,7 @@ impl Launcher { ) { tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting on: {bind_to}"); - if udp_tracker_container.core_config.private { + if udp_tracker_core_container.core_config.private { tracing::error!("udp services cannot be used for private trackers"); panic!("it should not use udp if using authentication"); } @@ -74,7 +77,13 @@ impl Launcher { let local_addr = local_udp_url.clone(); tokio::task::spawn(async move { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_with_graceful_shutdown::task (listening...)"); - let () = Self::run_udp_server_main(receiver, udp_tracker_container, cookie_lifetime).await; + let () = Self::run_udp_server_main( + receiver, + udp_tracker_core_container, + udp_tracker_server_container, + cookie_lifetime, + ) + .await; }) }; @@ -111,10 +120,11 @@ impl Launcher { ServiceHealthCheckJob::new(binding, info, job) } - #[instrument(skip(receiver, udp_tracker_container))] + #[instrument(skip(receiver, udp_tracker_core_container, udp_tracker_server_container))] async fn run_udp_server_main( mut receiver: Receiver, - udp_tracker_container: Arc, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, cookie_lifetime: Duration, ) { let active_requests = &mut ActiveRequests::default(); @@ -125,7 +135,7 @@ impl Launcher { let cookie_lifetime = cookie_lifetime.as_secs_f64(); - let ban_cleaner = udp_tracker_container.ban_service.clone(); + let ban_cleaner = udp_tracker_core_container.ban_service.clone(); tokio::spawn(async move { let mut cleaner_interval = interval(Duration::from_secs(IP_BANS_RESET_INTERVAL_IN_SECS)); @@ -157,22 +167,29 @@ impl Launcher { } }; - if let Some(udp_stats_event_sender) = udp_tracker_container.udp_stats_event_sender.as_deref() { + if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.udp_server_stats_event_sender.as_deref() + { match req.from.ip() { IpAddr::V4(_) => { - udp_stats_event_sender.send_event(statistics::event::Event::Udp4Request).await; + udp_server_stats_event_sender + .send_event(statistics::event::Event::Udp4IncomingRequest) + .await; } IpAddr::V6(_) => { - udp_stats_event_sender.send_event(statistics::event::Event::Udp6Request).await; + udp_server_stats_event_sender + .send_event(statistics::event::Event::Udp6IncomingRequest) + .await; } } } - if udp_tracker_container.ban_service.read().await.is_banned(&req.from.ip()) { + if udp_tracker_core_container.ban_service.read().await.is_banned(&req.from.ip()) { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop continue: (banned ip)"); - if let Some(udp_stats_event_sender) = udp_tracker_container.udp_stats_event_sender.as_deref() { - udp_stats_event_sender + if let Some(udp_server_stats_event_sender) = + udp_tracker_server_container.udp_server_stats_event_sender.as_deref() + { + udp_server_stats_event_sender .send_event(statistics::event::Event::UdpRequestBanned) .await; } @@ -180,7 +197,12 @@ impl Launcher { continue; } - let processor = Processor::new(receiver.socket.clone(), udp_tracker_container.clone(), cookie_lifetime); + let processor = Processor::new( + receiver.socket.clone(), + udp_tracker_core_container.clone(), + udp_tracker_server_container.clone(), + cookie_lifetime, + ); /* We spawn the new task even if the active requests buffer is full. This could seem counterintuitive because we are accepting @@ -204,8 +226,10 @@ impl Launcher { if old_request_aborted { // Evicted task from active requests buffer was aborted. - if let Some(udp_stats_event_sender) = udp_tracker_container.udp_stats_event_sender.as_deref() { - udp_stats_event_sender + if let Some(udp_server_stats_event_sender) = + udp_tracker_server_container.udp_server_stats_event_sender.as_deref() + { + udp_server_stats_event_sender .send_event(statistics::event::Event::UdpRequestAborted) .await; } diff --git a/packages/udp-tracker-server/src/server/mod.rs b/packages/udp-tracker-server/src/server/mod.rs index 1ab79b6fe..f70e28b27 100644 --- a/packages/udp-tracker-server/src/server/mod.rs +++ b/packages/udp-tracker-server/src/server/mod.rs @@ -64,6 +64,7 @@ mod tests { use super::spawner::Spawner; use super::Server; + use crate::container::UdpTrackerServerContainer; fn initialize_global_services(configuration: &Configuration) { initialize_static(); @@ -97,10 +98,16 @@ mod tests { let stopped = Server::new(Spawner::new(bind_to)); - let udp_tracker_container = UdpTrackerCoreContainer::initialize(&core_config, &udp_tracker_config); + let udp_tracker_core_container = UdpTrackerCoreContainer::initialize(&core_config, &udp_tracker_config); + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); let started = stopped - .start(udp_tracker_container, register.give_form(), config.cookie_lifetime) + .start( + udp_tracker_core_container, + udp_tracker_server_container, + register.give_form(), + config.cookie_lifetime, + ) .await .expect("it should start the server"); @@ -131,11 +138,13 @@ mod tests { let stopped = Server::new(Spawner::new(bind_to)); - let udp_tracker_container = UdpTrackerCoreContainer::initialize(&core_config, &udp_tracker_config); + let udp_tracker_core_container = UdpTrackerCoreContainer::initialize(&core_config, &udp_tracker_config); + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); let started = stopped .start( - udp_tracker_container, + udp_tracker_core_container, + udp_tracker_server_container, register.give_form(), udp_tracker_config.cookie_lifetime, ) diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs index a933fdd17..44b543571 100644 --- a/packages/udp-tracker-server/src/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -5,25 +5,33 @@ use std::time::Duration; use aquatic_udp_protocol::Response; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; -use bittorrent_udp_tracker_core::{self, statistics}; +use bittorrent_udp_tracker_core::{self}; use tokio::time::Instant; use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; +use crate::container::UdpTrackerServerContainer; use crate::handlers::CookieTimeValues; -use crate::{handlers, RawRequest}; +use crate::{handlers, statistics, RawRequest}; pub struct Processor { socket: Arc, - udp_tracker_container: Arc, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, cookie_lifetime: f64, } impl Processor { - pub fn new(socket: Arc, udp_tracker_container: Arc, cookie_lifetime: f64) -> Self { + pub fn new( + socket: Arc, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, + cookie_lifetime: f64, + ) -> Self { Self { socket, - udp_tracker_container, + udp_tracker_core_container, + udp_tracker_server_container, cookie_lifetime, } } @@ -36,7 +44,8 @@ impl Processor { let response = handlers::handle_packet( request, - self.udp_tracker_container.clone(), + self.udp_tracker_core_container.clone(), + self.udp_tracker_server_container.clone(), self.socket.address(), CookieTimeValues::new(self.cookie_lifetime), ) @@ -81,10 +90,12 @@ impl Processor { tracing::debug!(%bytes_count, %sent_bytes, "sent {response_type}"); } - if let Some(udp_stats_event_sender) = self.udp_tracker_container.udp_stats_event_sender.as_deref() { + if let Some(udp_server_stats_event_sender) = + self.udp_tracker_server_container.udp_server_stats_event_sender.as_deref() + { match target.ip() { IpAddr::V4(_) => { - udp_stats_event_sender + udp_server_stats_event_sender .send_event(statistics::event::Event::Udp4Response { kind: udp_response_kind, req_processing_time, @@ -92,7 +103,7 @@ impl Processor { .await; } IpAddr::V6(_) => { - udp_stats_event_sender + udp_server_stats_event_sender .send_event(statistics::event::Event::Udp6Response { kind: udp_response_kind, req_processing_time, diff --git a/packages/udp-tracker-server/src/server/spawner.rs b/packages/udp-tracker-server/src/server/spawner.rs index 6c1f9a48e..46916f6ae 100644 --- a/packages/udp-tracker-server/src/server/spawner.rs +++ b/packages/udp-tracker-server/src/server/spawner.rs @@ -11,6 +11,7 @@ use tokio::task::JoinHandle; use torrust_server_lib::signals::{Halted, Started}; use super::launcher::Launcher; +use crate::container::UdpTrackerServerContainer; #[derive(Constructor, Copy, Clone, Debug, Display)] #[display("(with socket): {bind_to}")] @@ -27,7 +28,8 @@ impl Spawner { #[must_use] pub fn spawn_launcher( &self, - udp_tracker_container: Arc, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, cookie_lifetime: Duration, tx_start: oneshot::Sender, rx_halt: oneshot::Receiver, @@ -35,8 +37,15 @@ impl Spawner { let spawner = Self::new(self.bind_to); tokio::spawn(async move { - Launcher::run_with_graceful_shutdown(udp_tracker_container, spawner.bind_to, cookie_lifetime, tx_start, rx_halt) - .await; + Launcher::run_with_graceful_shutdown( + udp_tracker_core_container, + udp_tracker_server_container, + spawner.bind_to, + cookie_lifetime, + tx_start, + rx_halt, + ) + .await; spawner }) } diff --git a/packages/udp-tracker-server/src/server/states.rs b/packages/udp-tracker-server/src/server/states.rs index fc700ea40..4d1c97167 100644 --- a/packages/udp-tracker-server/src/server/states.rs +++ b/packages/udp-tracker-server/src/server/states.rs @@ -14,6 +14,7 @@ use tracing::{instrument, Level}; use super::spawner::Spawner; use super::{Server, UdpError}; +use crate::container::UdpTrackerServerContainer; use crate::server::launcher::Launcher; /// A UDP server instance controller with no UDP instance running. @@ -60,10 +61,11 @@ impl Server { /// # Panics /// /// It panics if unable to receive the bound socket address from service. - #[instrument(skip(self, udp_tracker_container, form), err, ret(Display, level = Level::INFO))] + #[instrument(skip(self, udp_tracker_core_container, udp_tracker_server_container, form), err, ret(Display, level = Level::INFO))] pub async fn start( self, - udp_tracker_container: Arc, + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, form: ServiceRegistrationForm, cookie_lifetime: Duration, ) -> Result, std::io::Error> { @@ -73,10 +75,13 @@ impl Server { assert!(!tx_halt.is_closed(), "Halt channel for UDP tracker should be open"); // May need to wrap in a task to about a tokio bug. - let task = self - .state - .spawner - .spawn_launcher(udp_tracker_container, cookie_lifetime, tx_start, rx_halt); + let task = self.state.spawner.spawn_launcher( + udp_tracker_core_container, + udp_tracker_server_container, + cookie_lifetime, + tx_start, + rx_halt, + ); let local_addr = rx_start.await.expect("it should be able to start the service").address; diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 731f678a1..b3b86e20a 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -12,21 +12,21 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { } // UDP4 - Event::Udp4Request { kind } => { + Event::Udp4IncomingRequest => { stats_repository.increase_udp4_requests().await; - match kind { - UdpResponseKind::Connect => { - stats_repository.increase_udp4_connections().await; - } - UdpResponseKind::Announce => { - stats_repository.increase_udp4_announces().await; - } - UdpResponseKind::Scrape => { - stats_repository.increase_udp4_scrapes().await; - } - UdpResponseKind::Error => {} - } } + Event::Udp4Request { kind } => match kind { + UdpResponseKind::Connect => { + stats_repository.increase_udp4_connections().await; + } + UdpResponseKind::Announce => { + stats_repository.increase_udp4_announces().await; + } + UdpResponseKind::Scrape => { + stats_repository.increase_udp4_scrapes().await; + } + UdpResponseKind::Error => {} + }, Event::Udp4Response { kind, req_processing_time, @@ -57,9 +57,21 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { } // UDP6 - Event::Udp6Request => { + Event::Udp6IncomingRequest => { stats_repository.increase_udp6_requests().await; } + Event::Udp6Request { kind } => match kind { + UdpResponseKind::Connect => { + stats_repository.increase_udp6_connections().await; + } + UdpResponseKind::Announce => { + stats_repository.increase_udp6_announces().await; + } + UdpResponseKind::Scrape => { + stats_repository.increase_udp6_scrapes().await; + } + UdpResponseKind::Error => {} + }, Event::Udp6Response { kind: _, req_processing_time: _, @@ -77,7 +89,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { #[cfg(test)] mod tests { use crate::statistics::event::handler::handle_event; - use crate::statistics::event::{Event, UdpResponseKind}; + use crate::statistics::event::Event; use crate::statistics::repository::Repository; #[tokio::test] @@ -101,13 +113,7 @@ mod tests { async fn should_increase_the_udp4_requests_counter_when_it_receives_a_udp4_request_event() { let stats_repository = Repository::new(); - handle_event( - Event::Udp4Request { - kind: UdpResponseKind::Connect, - }, - &stats_repository, - ) - .await; + handle_event(Event::Udp4IncomingRequest, &stats_repository).await; let stats = stats_repository.get_stats().await; @@ -147,7 +153,7 @@ mod tests { async fn should_increase_the_udp6_requests_counter_when_it_receives_a_udp6_request_event() { let stats_repository = Repository::new(); - handle_event(Event::Udp6Request, &stats_repository).await; + handle_event(Event::Udp6IncomingRequest, &stats_repository).await; let stats = stats_repository.get_stats().await; diff --git a/packages/udp-tracker-server/src/statistics/event/mod.rs b/packages/udp-tracker-server/src/statistics/event/mod.rs index 4f66862d6..6a48b9449 100644 --- a/packages/udp-tracker-server/src/statistics/event/mod.rs +++ b/packages/udp-tracker-server/src/statistics/event/mod.rs @@ -18,6 +18,9 @@ pub enum Event { // Attributes are enums too. UdpRequestAborted, UdpRequestBanned, + + // UDP4 + Udp4IncomingRequest, Udp4Request { kind: UdpResponseKind, }, @@ -26,7 +29,12 @@ pub enum Event { req_processing_time: Duration, }, Udp4Error, - Udp6Request, + + // UDP6 + Udp6IncomingRequest, + Udp6Request { + kind: UdpResponseKind, + }, Udp6Response { kind: UdpResponseKind, req_processing_time: Duration, diff --git a/packages/udp-tracker-server/src/statistics/keeper.rs b/packages/udp-tracker-server/src/statistics/keeper.rs index e805a7eea..ae80e7970 100644 --- a/packages/udp-tracker-server/src/statistics/keeper.rs +++ b/packages/udp-tracker-server/src/statistics/keeper.rs @@ -51,7 +51,7 @@ impl Keeper { #[cfg(test)] mod tests { - use crate::statistics::event::{Event, UdpResponseKind}; + use crate::statistics::event::Event; use crate::statistics::keeper::Keeper; use crate::statistics::metrics::Metrics; @@ -70,11 +70,7 @@ mod tests { let event_sender = stats_tracker.run_event_listener(); - let result = event_sender - .send_event(Event::Udp4Request { - kind: UdpResponseKind::Connect, - }) - .await; + let result = event_sender.send_event(Event::Udp4IncomingRequest).await; assert!(result.is_some()); } diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index d34bd3c8a..92ee14f50 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -125,13 +125,14 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let (_udp_stats_event_sender, udp_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let udp_stats_repository = Arc::new(udp_stats_repository); + let (_udp_server_stats_event_sender, udp_server_stats_repository) = + statistics::setup::factory(config.core.tracker_usage_statistics); + let udp_server_stats_repository = Arc::new(udp_server_stats_repository); let tracker_metrics = get_metrics( in_memory_torrent_repository.clone(), ban_service.clone(), - udp_stats_repository.clone(), + udp_server_stats_repository.clone(), ) .await; diff --git a/packages/udp-tracker-server/tests/server/contract.rs b/packages/udp-tracker-server/tests/server/contract.rs index d2da552a2..4cb23621d 100644 --- a/packages/udp-tracker-server/tests/server/contract.rs +++ b/packages/udp-tracker-server/tests/server/contract.rs @@ -267,8 +267,8 @@ mod receiving_an_announce_request { let udp_requests_banned_before = env .container - .udp_tracker_core_container - .udp_stats_repository + .udp_tracker_server_container + .udp_server_stats_repository .get_stats() .await .udp_requests_banned; @@ -283,8 +283,8 @@ mod receiving_an_announce_request { let udp_requests_banned_after = env .container - .udp_tracker_core_container - .udp_stats_repository + .udp_tracker_server_container + .udp_server_stats_repository .get_stats() .await .udp_requests_banned; diff --git a/src/app.rs b/src/app.rs index 27ffe7a4a..5458ea600 100644 --- a/src/app.rs +++ b/src/app.rs @@ -79,8 +79,11 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> } else { let udp_tracker_config = Arc::new(udp_tracker_config.clone()); let udp_tracker_container = Arc::new(app_container.udp_tracker_container(&udp_tracker_config)); + let udp_tracker_server_container = Arc::new(app_container.udp_tracker_server_container()); - jobs.push(udp_tracker::start_job(udp_tracker_container, registar.give_form()).await); + jobs.push( + udp_tracker::start_job(udp_tracker_container, udp_tracker_server_container, registar.give_form()).await, + ); } } } else { diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 0276de1d3..2723ad9ab 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -12,6 +12,7 @@ use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use tokio::task::JoinHandle; use torrust_server_lib::registar::ServiceRegistrationForm; +use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use torrust_udp_tracker_server::server::spawner::Spawner; use torrust_udp_tracker_server::server::Server; use tracing::instrument; @@ -27,13 +28,22 @@ use tracing::instrument; /// It will panic if the task did not finish successfully. #[must_use] #[allow(clippy::async_yields_async)] -#[instrument(skip(udp_tracker_container, form))] -pub async fn start_job(udp_tracker_container: Arc, form: ServiceRegistrationForm) -> JoinHandle<()> { - let bind_to = udp_tracker_container.udp_tracker_config.bind_address; - let cookie_lifetime = udp_tracker_container.udp_tracker_config.cookie_lifetime; +#[instrument(skip(udp_tracker_core_container, udp_tracker_server_container, form))] +pub async fn start_job( + udp_tracker_core_container: Arc, + udp_tracker_server_container: Arc, + form: ServiceRegistrationForm, +) -> JoinHandle<()> { + let bind_to = udp_tracker_core_container.udp_tracker_config.bind_address; + let cookie_lifetime = udp_tracker_core_container.udp_tracker_config.cookie_lifetime; let server = Server::new(Spawner::new(bind_to)) - .start(udp_tracker_container, form, cookie_lifetime) + .start( + udp_tracker_core_container, + udp_tracker_server_container, + form, + cookie_lifetime, + ) .await .expect("it should be able to start the udp tracker"); diff --git a/src/container.rs b/src/container.rs index 6f6d9013d..b10ac9ae0 100644 --- a/src/container.rs +++ b/src/container.rs @@ -19,6 +19,7 @@ use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::{Configuration, Core, HttpApi, HttpTracker, UdpTracker}; +use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use tracing::instrument; pub struct AppContainer { @@ -38,12 +39,16 @@ pub struct AppContainer { // UDP Tracker Core Services pub ban_service: Arc>, - pub udp_stats_event_sender: Arc>>, + pub udp_core_stats_event_sender: Arc>>, + pub udp_core_stats_repository: Arc, // HTTP Tracker Core Services pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, - pub udp_stats_repository: Arc, + + // UDP Tracker Server Services + pub udp_server_stats_event_sender: Arc>>, + pub udp_server_stats_repository: Arc, } impl AppContainer { @@ -53,20 +58,26 @@ impl AppContainer { let tracker_core_container = TrackerCoreContainer::initialize(&core_config); - // HTTP stats + // HTTP core stats let (http_stats_event_sender, http_stats_repository) = bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); let http_stats_repository = Arc::new(http_stats_repository); - // UDP stats - let (udp_stats_event_sender, udp_stats_repository) = + // UDP core stats + let (udp_core_stats_event_sender, udp_core_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let udp_stats_event_sender = Arc::new(udp_stats_event_sender); - let udp_stats_repository = Arc::new(udp_stats_repository); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let udp_core_stats_repository = Arc::new(udp_core_stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + // UDP server stats + let (udp_server_stats_event_sender, udp_server_stats_repository) = + torrust_udp_tracker_server::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); + let udp_server_stats_repository = Arc::new(udp_server_stats_repository); + AppContainer { core_config, database: tracker_core_container.database, @@ -82,9 +93,11 @@ impl AppContainer { torrents_manager: tracker_core_container.torrents_manager, ban_service, http_stats_event_sender, - udp_stats_event_sender, + udp_core_stats_event_sender, http_stats_repository, - udp_stats_repository, + udp_core_stats_repository, + udp_server_stats_event_sender, + udp_server_stats_repository, } } @@ -112,8 +125,8 @@ impl AppContainer { whitelist_authorization: self.whitelist_authorization.clone(), udp_tracker_config: udp_tracker_config.clone(), - udp_stats_event_sender: self.udp_stats_event_sender.clone(), - udp_stats_repository: self.udp_stats_repository.clone(), + udp_core_stats_event_sender: self.udp_core_stats_event_sender.clone(), + udp_core_stats_repository: self.udp_core_stats_repository.clone(), ban_service: self.ban_service.clone(), } } @@ -128,7 +141,16 @@ impl AppContainer { whitelist_manager: self.whitelist_manager.clone(), ban_service: self.ban_service.clone(), http_stats_repository: self.http_stats_repository.clone(), - udp_stats_repository: self.udp_stats_repository.clone(), + udp_core_stats_repository: self.udp_core_stats_repository.clone(), + udp_server_stats_repository: self.udp_server_stats_repository.clone(), + } + } + + #[must_use] + pub fn udp_tracker_server_container(&self) -> UdpTrackerServerContainer { + UdpTrackerServerContainer { + udp_server_stats_event_sender: self.udp_server_stats_event_sender.clone(), + udp_server_stats_repository: self.udp_server_stats_repository.clone(), } } } From 5362a6daf0032fee0703bf45b9294072694a85ee Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 27 Feb 2025 15:37:56 +0000 Subject: [PATCH 0833/1297] refactor: [#1309] remove unused code adn rename function And other changes to make the convertion more explicit and clear. --- .../src/v1/handlers/announce.rs | 27 +------------------ .../http-protocol/src/v1/requests/announce.rs | 8 +++--- 2 files changed, 5 insertions(+), 30 deletions(-) diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 7855c8172..0221f8dad 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -4,11 +4,10 @@ //! and resolve the client IP address. use std::sync::Arc; -use aquatic_udp_protocol::AnnounceEvent; use axum::extract::State; use axum::response::{IntoResponse, Response}; use bittorrent_http_tracker_core::services::announce::HttpAnnounceError; -use bittorrent_http_tracker_protocol::v1::requests::announce::{Announce, Compact, Event}; +use bittorrent_http_tracker_protocol::v1::requests::announce::{Announce, Compact}; use bittorrent_http_tracker_protocol::v1::responses::{self}; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_tracker_core::announce_handler::AnnounceHandler; @@ -158,30 +157,6 @@ fn build_response(announce_request: &Announce, announce_data: AnnounceData) -> R } } -#[must_use] -pub fn map_to_aquatic_event(event: &Option) -> aquatic_udp_protocol::AnnounceEvent { - match event { - Some(event) => match &event { - Event::Started => aquatic_udp_protocol::AnnounceEvent::Started, - Event::Stopped => aquatic_udp_protocol::AnnounceEvent::Stopped, - Event::Completed => aquatic_udp_protocol::AnnounceEvent::Completed, - }, - None => aquatic_udp_protocol::AnnounceEvent::None, - } -} - -#[must_use] -pub fn map_to_torrust_event(event: &Option) -> AnnounceEvent { - match event { - Some(event) => match &event { - Event::Started => AnnounceEvent::Started, - Event::Stopped => AnnounceEvent::Stopped, - Event::Completed => AnnounceEvent::Completed, - }, - None => AnnounceEvent::None, - } -} - #[cfg(test)] mod tests { diff --git a/packages/http-protocol/src/v1/requests/announce.rs b/packages/http-protocol/src/v1/requests/announce.rs index 036aa3048..abb6d7e90 100644 --- a/packages/http-protocol/src/v1/requests/announce.rs +++ b/packages/http-protocol/src/v1/requests/announce.rs @@ -399,12 +399,12 @@ pub fn peer_from_request(announce_request: &Announce, peer_ip: &IpAddr) -> peer: uploaded: announce_request.uploaded.unwrap_or(NumberOfBytes::new(0)), downloaded: announce_request.downloaded.unwrap_or(NumberOfBytes::new(0)), left: announce_request.left.unwrap_or(NumberOfBytes::new(0)), - event: map_to_torrust_event(&announce_request.event), + event: convert_to_aquatic_event(&announce_request.event), } } #[must_use] -pub fn map_to_torrust_event(event: &Option) -> AnnounceEvent { +pub fn convert_to_aquatic_event(event: &Option) -> aquatic_udp_protocol::request::AnnounceEvent { match event { Some(event) => match &event { Event::Started => AnnounceEvent::Started, @@ -444,7 +444,7 @@ mod tests { assert_eq!( announce_request, Announce { - info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), + info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), // DevSkim: ignore DS173237 peer_id: PeerId(*b"-qB00000000000000001"), port: 17548, downloaded: None, @@ -479,7 +479,7 @@ mod tests { assert_eq!( announce_request, Announce { - info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), + info_hash: "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(), // DevSkim: ignore DS173237 peer_id: PeerId(*b"-qB00000000000000001"), port: 17548, downloaded: Some(NumberOfBytes::new(1)), From 81675988cb52b7722c027df070b805fb9c65b316 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 27 Feb 2025 16:26:01 +0000 Subject: [PATCH 0834/1297] refactor: [#1309] align our HTTP Announce Events with the aquatic one - To simplify conversions. - To properly implement BEP 3. The new `empty` option is defined in the protocol and was missing in our implementation. --- .../http-protocol/src/v1/requests/announce.rs | 44 ++++++++++++------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/packages/http-protocol/src/v1/requests/announce.rs b/packages/http-protocol/src/v1/requests/announce.rs index abb6d7e90..a04738749 100644 --- a/packages/http-protocol/src/v1/requests/announce.rs +++ b/packages/http-protocol/src/v1/requests/announce.rs @@ -145,15 +145,21 @@ pub enum ParseAnnounceQueryError { /// /// Refer to [BEP 03. The `BitTorrent Protocol` Specification](https://www.bittorrent.org/beps/bep_0003.html) /// for more information. -#[derive(PartialEq, Debug)] +#[derive(PartialEq, Debug, Clone)] pub enum Event { /// Event sent when a download first begins. Started, + /// Event sent when the downloader cease downloading. Stopped, + /// Event sent when the download is complete. - /// No `completed` is sent if the file was complete when started + /// No `completed` is sent if the file was complete when started. Completed, + + /// It is the same as not being present. If not present, this is one of the + /// announcements done at regular intervals. + Empty, } impl FromStr for Event { @@ -164,6 +170,7 @@ impl FromStr for Event { "started" => Ok(Self::Started), "stopped" => Ok(Self::Stopped), "completed" => Ok(Self::Completed), + "empty" => Ok(Self::Empty), _ => Err(ParseAnnounceQueryError::InvalidParam { param_name: EVENT.to_owned(), param_value: raw_param.to_owned(), @@ -179,17 +186,29 @@ impl fmt::Display for Event { Event::Started => write!(f, "started"), Event::Stopped => write!(f, "stopped"), Event::Completed => write!(f, "completed"), + Event::Empty => write!(f, "empty"), } } } impl From for Event { - fn from(value: aquatic_udp_protocol::request::AnnounceEvent) -> Self { - match value { + fn from(event: aquatic_udp_protocol::request::AnnounceEvent) -> Self { + match event { AnnounceEvent::Started => Self::Started, AnnounceEvent::Stopped => Self::Stopped, AnnounceEvent::Completed => Self::Completed, - AnnounceEvent::None => panic!("can't convert announce event from aquatic for None variant"), + AnnounceEvent::None => Self::Empty, + } + } +} + +impl From for aquatic_udp_protocol::request::AnnounceEvent { + fn from(event: Event) -> Self { + match event { + Event::Started => Self::Started, + Event::Stopped => Self::Stopped, + Event::Completed => Self::Completed, + Event::Empty => Self::None, } } } @@ -399,19 +418,10 @@ pub fn peer_from_request(announce_request: &Announce, peer_ip: &IpAddr) -> peer: uploaded: announce_request.uploaded.unwrap_or(NumberOfBytes::new(0)), downloaded: announce_request.downloaded.unwrap_or(NumberOfBytes::new(0)), left: announce_request.left.unwrap_or(NumberOfBytes::new(0)), - event: convert_to_aquatic_event(&announce_request.event), - } -} - -#[must_use] -pub fn convert_to_aquatic_event(event: &Option) -> aquatic_udp_protocol::request::AnnounceEvent { - match event { - Some(event) => match &event { - Event::Started => AnnounceEvent::Started, - Event::Stopped => AnnounceEvent::Stopped, - Event::Completed => AnnounceEvent::Completed, + event: match &announce_request.event { + Some(event) => event.clone().into(), + None => AnnounceEvent::None, }, - None => AnnounceEvent::None, } } From d190feee254966565dcc60c155d7942844332209 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 27 Feb 2025 18:06:10 +0000 Subject: [PATCH 0835/1297] refactor: [#1317] rename api packages To avoid future conflicts with other API implementations like GraphQL API. --- .github/workflows/deployment.yaml | 6 +- Cargo.lock | 111 +++++++++--------- Cargo.toml | 6 +- .../axum-health-check-api-server/Cargo.toml | 2 +- .../tests/server/contract.rs | 4 +- .../Cargo.toml | 8 +- .../LICENSE | 0 .../README.md | 0 .../src/environment.rs | 4 +- .../src/lib.rs | 0 .../src/routes.rs | 2 +- .../src/server.rs | 4 +- .../src/v1/context/auth_key/forms.rs | 0 .../src/v1/context/auth_key/handlers.rs | 0 .../src/v1/context/auth_key/mod.rs | 0 .../src/v1/context/auth_key/resources.rs | 0 .../src/v1/context/auth_key/responses.rs | 0 .../src/v1/context/auth_key/routes.rs | 0 .../src/v1/context/health_check/handlers.rs | 0 .../src/v1/context/health_check/mod.rs | 0 .../src/v1/context/health_check/resources.rs | 0 .../src/v1/context/mod.rs | 0 .../src/v1/context/stats/handlers.rs | 2 +- .../src/v1/context/stats/mod.rs | 0 .../src/v1/context/stats/resources.rs | 6 +- .../src/v1/context/stats/responses.rs | 2 +- .../src/v1/context/stats/routes.rs | 2 +- .../src/v1/context/torrent/handlers.rs | 0 .../src/v1/context/torrent/mod.rs | 0 .../src/v1/context/torrent/resources/mod.rs | 0 .../src/v1/context/torrent/resources/peer.rs | 0 .../v1/context/torrent/resources/torrent.rs | 0 .../src/v1/context/torrent/responses.rs | 0 .../src/v1/context/torrent/routes.rs | 0 .../src/v1/context/whitelist/handlers.rs | 0 .../src/v1/context/whitelist/mod.rs | 0 .../src/v1/context/whitelist/responses.rs | 0 .../src/v1/context/whitelist/routes.rs | 0 .../src/v1/middlewares/auth.rs | 0 .../src/v1/middlewares/mod.rs | 0 .../src/v1/mod.rs | 0 .../src/v1/responses.rs | 0 .../src/v1/routes.rs | 2 +- .../tests/common/fixtures.rs | 0 .../tests/common/mod.rs | 0 .../tests/integration.rs | 0 .../tests/server/connection_info.rs | 2 +- .../tests/server/mod.rs | 0 .../tests/server/v1/asserts.rs | 6 +- .../server/v1/contract/authentication.rs | 6 +- .../server/v1/contract/context/auth_key.rs | 8 +- .../v1/contract/context/health_check.rs | 6 +- .../tests/server/v1/contract/context/mod.rs | 0 .../tests/server/v1/contract/context/stats.rs | 6 +- .../server/v1/contract/context/torrent.rs | 10 +- .../server/v1/contract/context/whitelist.rs | 4 +- .../tests/server/v1/contract/fixtures.rs | 0 .../tests/server/v1/contract/mod.rs | 0 .../tests/server/v1/mod.rs | 0 .../Cargo.toml | 2 +- .../README.md | 0 .../docs/licenses/LICENSE-MIT_0 | 0 .../src/common/http.rs | 0 .../src/common/mod.rs | 0 .../src/connection_info.rs | 0 .../src/lib.rs | 0 .../src/v1/client.rs | 0 .../src/v1/mod.rs | 0 .../Cargo.toml | 2 +- .../LICENSE | 0 .../README.md | 0 .../src/container.rs | 0 .../src/lib.rs | 0 .../src/statistics/metrics.rs | 0 .../src/statistics/mod.rs | 0 .../src/statistics/services.rs | 0 packages/tracker-core/Cargo.toml | 2 +- src/app.rs | 2 +- src/bootstrap/jobs/tracker_apis.rs | 10 +- src/container.rs | 2 +- src/lib.rs | 14 +-- 81 files changed, 122 insertions(+), 121 deletions(-) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/Cargo.toml (86%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/LICENSE (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/README.md (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/environment.rs (97%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/lib.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/routes.rs (98%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/server.rs (98%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/auth_key/forms.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/auth_key/handlers.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/auth_key/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/auth_key/resources.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/auth_key/responses.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/auth_key/routes.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/health_check/handlers.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/health_check/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/health_check/resources.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/stats/handlers.rs (96%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/stats/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/stats/resources.rs (97%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/stats/responses.rs (98%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/stats/routes.rs (92%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/torrent/handlers.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/torrent/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/torrent/resources/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/torrent/resources/peer.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/torrent/resources/torrent.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/torrent/responses.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/torrent/routes.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/whitelist/handlers.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/whitelist/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/whitelist/responses.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/context/whitelist/routes.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/middlewares/auth.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/middlewares/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/responses.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/src/v1/routes.rs (90%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/common/fixtures.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/common/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/integration.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/connection_info.rs (75%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/v1/asserts.rs (95%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/v1/contract/authentication.rs (94%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/v1/contract/context/auth_key.rs (98%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/v1/contract/context/health_check.rs (75%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/v1/contract/context/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/v1/contract/context/stats.rs (93%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/v1/contract/context/torrent.rs (96%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/v1/contract/context/whitelist.rs (98%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/v1/contract/fixtures.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/v1/contract/mod.rs (100%) rename packages/{axum-tracker-api-server => axum-rest-tracker-api-server}/tests/server/v1/mod.rs (100%) rename packages/{tracker-api-client => rest-tracker-api-client}/Cargo.toml (93%) rename packages/{tracker-api-client => rest-tracker-api-client}/README.md (100%) rename packages/{tracker-api-client => rest-tracker-api-client}/docs/licenses/LICENSE-MIT_0 (100%) rename packages/{tracker-api-client => rest-tracker-api-client}/src/common/http.rs (100%) rename packages/{tracker-api-client => rest-tracker-api-client}/src/common/mod.rs (100%) rename packages/{tracker-api-client => rest-tracker-api-client}/src/connection_info.rs (100%) rename packages/{tracker-api-client => rest-tracker-api-client}/src/lib.rs (100%) rename packages/{tracker-api-client => rest-tracker-api-client}/src/v1/client.rs (100%) rename packages/{tracker-api-client => rest-tracker-api-client}/src/v1/mod.rs (100%) rename packages/{tracker-api-core => rest-tracker-api-core}/Cargo.toml (96%) rename packages/{tracker-api-core => rest-tracker-api-core}/LICENSE (100%) rename packages/{tracker-api-core => rest-tracker-api-core}/README.md (100%) rename packages/{tracker-api-core => rest-tracker-api-core}/src/container.rs (100%) rename packages/{tracker-api-core => rest-tracker-api-core}/src/lib.rs (100%) rename packages/{tracker-api-core => rest-tracker-api-core}/src/statistics/metrics.rs (100%) rename packages/{tracker-api-core => rest-tracker-api-core}/src/statistics/mod.rs (100%) rename packages/{tracker-api-core => rest-tracker-api-core}/src/statistics/services.rs (100%) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index e492d7490..1422ec394 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -63,12 +63,12 @@ jobs: cargo publish -p bittorrent-udp-tracker-protocol cargo publish -p torrust-axum-health-check-api-server cargo publish -p torrust-axum-http-tracker-server + cargo publish -p torrust-axum-rest-tracker-api-server cargo publish -p torrust-axum-server - cargo publish -p torrust-axum-tracker-api-server + cargo publish -p torrust-rest-tracker-api-client + cargo publish -p torrust-rest-tracker-api-core cargo publish -p torrust-torrust-server-lib cargo publish -p torrust-tracker - cargo publish -p torrust-tracker-api-client - cargo publish -p torrust-tracker-api-core cargo publish -p torrust-tracker-client cargo publish -p torrust-tracker-clock cargo publish -p torrust-tracker-configuration diff --git a/Cargo.lock b/Cargo.lock index 71140b9f7..fbb55562a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -647,7 +647,7 @@ dependencies = [ "testcontainers", "thiserror 2.0.11", "tokio", - "torrust-tracker-api-client", + "torrust-rest-tracker-api-client", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-located-error", @@ -4350,8 +4350,8 @@ dependencies = [ "tokio", "torrust-axum-health-check-api-server", "torrust-axum-http-tracker-server", + "torrust-axum-rest-tracker-api-server", "torrust-axum-server", - "torrust-axum-tracker-api-server", "torrust-server-lib", "torrust-tracker-clock", "torrust-tracker-configuration", @@ -4400,27 +4400,7 @@ dependencies = [ ] [[package]] -name = "torrust-axum-server" -version = "3.0.0-develop" -dependencies = [ - "axum-server", - "camino", - "futures-util", - "http-body", - "hyper", - "hyper-util", - "pin-project-lite", - "thiserror 2.0.11", - "tokio", - "torrust-server-lib", - "torrust-tracker-configuration", - "torrust-tracker-located-error", - "tower 0.5.2", - "tracing", -] - -[[package]] -name = "torrust-axum-tracker-api-server" +name = "torrust-axum-rest-tracker-api-server" version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", @@ -4443,21 +4423,67 @@ dependencies = [ "thiserror 2.0.11", "tokio", "torrust-axum-server", + "torrust-rest-tracker-api-client", + "torrust-rest-tracker-api-core", "torrust-server-lib", - "torrust-tracker-api-client", - "torrust-tracker-api-core", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-udp-tracker-server", - "tower 0.5.2", + "tower 0.4.13", "tower-http", "tracing", "url", "uuid", ] +[[package]] +name = "torrust-axum-server" +version = "3.0.0-develop" +dependencies = [ + "axum-server", + "camino", + "futures-util", + "http-body", + "hyper", + "hyper-util", + "pin-project-lite", + "thiserror 2.0.11", + "tokio", + "torrust-server-lib", + "torrust-tracker-configuration", + "torrust-tracker-located-error", + "tower 0.5.2", + "tracing", +] + +[[package]] +name = "torrust-rest-tracker-api-client" +version = "3.0.0-develop" +dependencies = [ + "hyper", + "reqwest", + "serde", + "thiserror 2.0.11", + "url", + "uuid", +] + +[[package]] +name = "torrust-rest-tracker-api-core" +version = "3.0.0-develop" +dependencies = [ + "bittorrent-http-tracker-core", + "bittorrent-tracker-core", + "bittorrent-udp-tracker-core", + "tokio", + "torrust-tracker-configuration", + "torrust-tracker-primitives", + "torrust-tracker-test-helpers", + "torrust-udp-tracker-server", +] + [[package]] name = "torrust-server-lib" version = "3.0.0-develop" @@ -4490,11 +4516,11 @@ dependencies = [ "tokio", "torrust-axum-health-check-api-server", "torrust-axum-http-tracker-server", + "torrust-axum-rest-tracker-api-server", "torrust-axum-server", - "torrust-axum-tracker-api-server", + "torrust-rest-tracker-api-client", + "torrust-rest-tracker-api-core", "torrust-server-lib", - "torrust-tracker-api-client", - "torrust-tracker-api-core", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-test-helpers", @@ -4503,32 +4529,6 @@ dependencies = [ "tracing-subscriber", ] -[[package]] -name = "torrust-tracker-api-client" -version = "3.0.0-develop" -dependencies = [ - "hyper", - "reqwest", - "serde", - "thiserror 2.0.11", - "url", - "uuid", -] - -[[package]] -name = "torrust-tracker-api-core" -version = "3.0.0-develop" -dependencies = [ - "bittorrent-http-tracker-core", - "bittorrent-tracker-core", - "bittorrent-udp-tracker-core", - "tokio", - "torrust-tracker-configuration", - "torrust-tracker-primitives", - "torrust-tracker-test-helpers", - "torrust-udp-tracker-server", -] - [[package]] name = "torrust-tracker-client" version = "3.0.0-develop" @@ -4685,6 +4685,7 @@ dependencies = [ "futures-util", "pin-project", "pin-project-lite", + "tokio", "tower-layer", "tower-service", "tracing", diff --git a/Cargo.toml b/Cargo.toml index 346817e27..bcac4bf66 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,10 +49,10 @@ serde_json = { version = "1", features = ["preserve_order"] } tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "packages/axum-health-check-api-server" } torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "packages/axum-http-tracker-server" } +torrust-axum-rest-tracker-api-server = { version = "3.0.0-develop", path = "packages/axum-rest-tracker-api-server" } torrust-axum-server = { version = "3.0.0-develop", path = "packages/axum-server" } -torrust-axum-tracker-api-server = { version = "3.0.0-develop", path = "packages/axum-tracker-api-server" } +torrust-rest-tracker-api-core = { version = "3.0.0-develop", path = "packages/rest-tracker-api-core" } torrust-server-lib = { version = "3.0.0-develop", path = "packages/server-lib" } -torrust-tracker-api-core = { version = "3.0.0-develop", path = "packages/tracker-api-core" } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "packages/udp-tracker-server" } @@ -62,7 +62,7 @@ tracing-subscriber = { version = "0", features = ["json"] } [dev-dependencies] local-ip-address = "0" mockall = "0" -torrust-tracker-api-client = { version = "3.0.0-develop", path = "packages/tracker-api-client" } +torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "packages/rest-tracker-api-client" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "packages/test-helpers" } [workspace] diff --git a/packages/axum-health-check-api-server/Cargo.toml b/packages/axum-health-check-api-server/Cargo.toml index 928393bee..e24e609bf 100644 --- a/packages/axum-health-check-api-server/Cargo.toml +++ b/packages/axum-health-check-api-server/Cargo.toml @@ -31,7 +31,7 @@ tracing = "0" reqwest = { version = "0", features = ["json"] } torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "../axum-health-check-api-server" } torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "../axum-http-tracker-server" } -torrust-axum-tracker-api-server = { version = "3.0.0-develop", path = "../axum-tracker-api-server" } +torrust-axum-rest-tracker-api-server = { version = "3.0.0-develop", path = "../axum-rest-tracker-api-server" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } diff --git a/packages/axum-health-check-api-server/tests/server/contract.rs b/packages/axum-health-check-api-server/tests/server/contract.rs index 96a03cca4..0e0d26b83 100644 --- a/packages/axum-health-check-api-server/tests/server/contract.rs +++ b/packages/axum-health-check-api-server/tests/server/contract.rs @@ -43,7 +43,7 @@ mod api { let configuration = Arc::new(configuration::ephemeral()); - let service = torrust_axum_tracker_api_server::environment::Started::new(&configuration).await; + let service = torrust_axum_rest_tracker_api_server::environment::Started::new(&configuration).await; let registar = service.registar.clone(); @@ -90,7 +90,7 @@ mod api { let configuration = Arc::new(configuration::ephemeral()); - let service = torrust_axum_tracker_api_server::environment::Started::new(&configuration).await; + let service = torrust_axum_rest_tracker_api_server::environment::Started::new(&configuration).await; let binding = service.bind_address(); diff --git a/packages/axum-tracker-api-server/Cargo.toml b/packages/axum-rest-tracker-api-server/Cargo.toml similarity index 86% rename from packages/axum-tracker-api-server/Cargo.toml rename to packages/axum-rest-tracker-api-server/Cargo.toml index e1deb9b8a..9c0d2bc2f 100644 --- a/packages/axum-tracker-api-server/Cargo.toml +++ b/packages/axum-rest-tracker-api-server/Cargo.toml @@ -6,7 +6,7 @@ edition.workspace = true homepage.workspace = true keywords = ["axum", "bittorrent", "http", "server", "torrust", "tracker"] license.workspace = true -name = "torrust-axum-tracker-api-server" +name = "torrust-axum-rest-tracker-api-server" publish.workspace = true readme = "README.md" repository.workspace = true @@ -32,9 +32,9 @@ serde_with = { version = "3", features = ["json"] } thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } +torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "../rest-tracker-api-client" } +torrust-rest-tracker-api-core = { version = "3.0.0-develop", path = "../rest-tracker-api-core" } torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } -torrust-tracker-api-client = { version = "3.0.0-develop", path = "../tracker-api-client" } -torrust-tracker-api-core = { version = "3.0.0-develop", path = "../tracker-api-core" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } @@ -46,7 +46,7 @@ tracing = "0" [dev-dependencies] local-ip-address = "0" mockall = "0" -torrust-tracker-api-client = { version = "3.0.0-develop", path = "../tracker-api-client" } +torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "../rest-tracker-api-client" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } url = { version = "2", features = ["serde"] } uuid = { version = "1", features = ["v4"] } diff --git a/packages/axum-tracker-api-server/LICENSE b/packages/axum-rest-tracker-api-server/LICENSE similarity index 100% rename from packages/axum-tracker-api-server/LICENSE rename to packages/axum-rest-tracker-api-server/LICENSE diff --git a/packages/axum-tracker-api-server/README.md b/packages/axum-rest-tracker-api-server/README.md similarity index 100% rename from packages/axum-tracker-api-server/README.md rename to packages/axum-rest-tracker-api-server/README.md diff --git a/packages/axum-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs similarity index 97% rename from packages/axum-tracker-api-server/src/environment.rs rename to packages/axum-rest-tracker-api-server/src/environment.rs index 7390bc659..2ee5cf744 100644 --- a/packages/axum-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -7,9 +7,9 @@ use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use futures::executor::block_on; use torrust_axum_server::tsl::make_rust_tls; +use torrust_rest_tracker_api_client::connection_info::{ConnectionInfo, Origin}; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::registar::Registar; -use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; -use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_primitives::peer; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; diff --git a/packages/axum-tracker-api-server/src/lib.rs b/packages/axum-rest-tracker-api-server/src/lib.rs similarity index 100% rename from packages/axum-tracker-api-server/src/lib.rs rename to packages/axum-rest-tracker-api-server/src/lib.rs diff --git a/packages/axum-tracker-api-server/src/routes.rs b/packages/axum-rest-tracker-api-server/src/routes.rs similarity index 98% rename from packages/axum-tracker-api-server/src/routes.rs rename to packages/axum-rest-tracker-api-server/src/routes.rs index 492e0dc37..c18451c89 100644 --- a/packages/axum-tracker-api-server/src/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/routes.rs @@ -15,8 +15,8 @@ use axum::response::Response; use axum::routing::get; use axum::{middleware, BoxError, Router}; use hyper::{Request, StatusCode}; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::logging::Latency; -use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::{AccessTokens, DEFAULT_TIMEOUT}; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; diff --git a/packages/axum-tracker-api-server/src/server.rs b/packages/axum-rest-tracker-api-server/src/server.rs similarity index 98% rename from packages/axum-tracker-api-server/src/server.rs rename to packages/axum-rest-tracker-api-server/src/server.rs index 65d8ca27a..fd8f92944 100644 --- a/packages/axum-tracker-api-server/src/server.rs +++ b/packages/axum-rest-tracker-api-server/src/server.rs @@ -35,10 +35,10 @@ use thiserror::Error; use tokio::sync::oneshot::{Receiver, Sender}; use torrust_axum_server::custom_axum_server::{self, TimeoutAcceptor}; use torrust_axum_server::signals::graceful_shutdown; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use torrust_server_lib::signals::{Halted, Started}; -use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::AccessTokens; use tracing::{instrument, Level}; @@ -295,8 +295,8 @@ mod tests { use std::sync::Arc; use torrust_axum_server::tsl::make_rust_tls; + use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::registar::Registar; - use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_test_helpers::configuration::ephemeral_public; diff --git a/packages/axum-tracker-api-server/src/v1/context/auth_key/forms.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/forms.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/auth_key/forms.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/auth_key/forms.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/auth_key/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/handlers.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/auth_key/handlers.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/auth_key/handlers.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/auth_key/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/auth_key/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/auth_key/mod.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/auth_key/resources.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/resources.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/auth_key/resources.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/auth_key/resources.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/auth_key/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/responses.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/auth_key/responses.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/auth_key/responses.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/auth_key/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/routes.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/auth_key/routes.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/auth_key/routes.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/health_check/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/health_check/handlers.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/health_check/handlers.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/health_check/handlers.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/health_check/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/health_check/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/health_check/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/health_check/mod.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/health_check/resources.rs b/packages/axum-rest-tracker-api-server/src/v1/context/health_check/resources.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/health_check/resources.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/health_check/resources.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/mod.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/stats/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs similarity index 96% rename from packages/axum-tracker-api-server/src/v1/context/stats/handlers.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs index 5e23211a6..5273df332 100644 --- a/packages/axum-tracker-api-server/src/v1/context/stats/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs @@ -9,7 +9,7 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use bittorrent_udp_tracker_core::services::banning::BanService; use serde::Deserialize; use tokio::sync::RwLock; -use torrust_tracker_api_core::statistics::services::get_metrics; +use torrust_rest_tracker_api_core::statistics::services::get_metrics; use super::responses::{metrics_response, stats_response}; diff --git a/packages/axum-tracker-api-server/src/v1/context/stats/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/stats/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/stats/mod.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/stats/resources.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs similarity index 97% rename from packages/axum-tracker-api-server/src/v1/context/stats/resources.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs index f27050e22..9a82593c7 100644 --- a/packages/axum-tracker-api-server/src/v1/context/stats/resources.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs @@ -1,7 +1,7 @@ //! API resources for the [`stats`](crate::v1::context::stats) //! API context. use serde::{Deserialize, Serialize}; -use torrust_tracker_api_core::statistics::services::TrackerMetrics; +use torrust_rest_tracker_api_core::statistics::services::TrackerMetrics; /// It contains all the statistics generated by the tracker. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -117,8 +117,8 @@ impl From for Stats { #[cfg(test)] mod tests { - use torrust_tracker_api_core::statistics::metrics::Metrics; - use torrust_tracker_api_core::statistics::services::TrackerMetrics; + use torrust_rest_tracker_api_core::statistics::metrics::Metrics; + use torrust_rest_tracker_api_core::statistics::services::TrackerMetrics; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; use super::Stats; diff --git a/packages/axum-tracker-api-server/src/v1/context/stats/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs similarity index 98% rename from packages/axum-tracker-api-server/src/v1/context/stats/responses.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs index f68c1e062..61455178c 100644 --- a/packages/axum-tracker-api-server/src/v1/context/stats/responses.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs @@ -1,7 +1,7 @@ //! API responses for the [`stats`](crate::v1::context::stats) //! API context. use axum::response::{IntoResponse, Json, Response}; -use torrust_tracker_api_core::statistics::services::TrackerMetrics; +use torrust_rest_tracker_api_core::statistics::services::TrackerMetrics; use super::resources::Stats; diff --git a/packages/axum-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs similarity index 92% rename from packages/axum-tracker-api-server/src/v1/context/stats/routes.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs index 6caaf13bf..1334c0d70 100644 --- a/packages/axum-tracker-api-server/src/v1/context/stats/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use axum::routing::get; use axum::Router; -use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use super::handlers::get_stats_handler; diff --git a/packages/axum-tracker-api-server/src/v1/context/torrent/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/handlers.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/torrent/handlers.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/torrent/handlers.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/torrent/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/torrent/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/torrent/mod.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/torrent/resources/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/torrent/resources/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/mod.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/torrent/resources/peer.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/peer.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/torrent/resources/peer.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/peer.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/torrent/resources/torrent.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/torrent.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/torrent/resources/torrent.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/torrent.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/torrent/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/responses.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/torrent/responses.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/torrent/responses.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/torrent/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/routes.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/torrent/routes.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/torrent/routes.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/whitelist/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/handlers.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/whitelist/handlers.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/whitelist/handlers.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/whitelist/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/whitelist/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/whitelist/mod.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/whitelist/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/responses.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/whitelist/responses.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/whitelist/responses.rs diff --git a/packages/axum-tracker-api-server/src/v1/context/whitelist/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/routes.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/context/whitelist/routes.rs rename to packages/axum-rest-tracker-api-server/src/v1/context/whitelist/routes.rs diff --git a/packages/axum-tracker-api-server/src/v1/middlewares/auth.rs b/packages/axum-rest-tracker-api-server/src/v1/middlewares/auth.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/middlewares/auth.rs rename to packages/axum-rest-tracker-api-server/src/v1/middlewares/auth.rs diff --git a/packages/axum-tracker-api-server/src/v1/middlewares/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/middlewares/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/middlewares/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/middlewares/mod.rs diff --git a/packages/axum-tracker-api-server/src/v1/mod.rs b/packages/axum-rest-tracker-api-server/src/v1/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/mod.rs rename to packages/axum-rest-tracker-api-server/src/v1/mod.rs diff --git a/packages/axum-tracker-api-server/src/v1/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/responses.rs similarity index 100% rename from packages/axum-tracker-api-server/src/v1/responses.rs rename to packages/axum-rest-tracker-api-server/src/v1/responses.rs diff --git a/packages/axum-tracker-api-server/src/v1/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/routes.rs similarity index 90% rename from packages/axum-tracker-api-server/src/v1/routes.rs rename to packages/axum-rest-tracker-api-server/src/v1/routes.rs index 90596f0e7..b36a20eac 100644 --- a/packages/axum-tracker-api-server/src/v1/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/routes.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use axum::Router; -use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use super::context::{auth_key, stats, torrent, whitelist}; diff --git a/packages/axum-tracker-api-server/tests/common/fixtures.rs b/packages/axum-rest-tracker-api-server/tests/common/fixtures.rs similarity index 100% rename from packages/axum-tracker-api-server/tests/common/fixtures.rs rename to packages/axum-rest-tracker-api-server/tests/common/fixtures.rs diff --git a/packages/axum-tracker-api-server/tests/common/mod.rs b/packages/axum-rest-tracker-api-server/tests/common/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/tests/common/mod.rs rename to packages/axum-rest-tracker-api-server/tests/common/mod.rs diff --git a/packages/axum-tracker-api-server/tests/integration.rs b/packages/axum-rest-tracker-api-server/tests/integration.rs similarity index 100% rename from packages/axum-tracker-api-server/tests/integration.rs rename to packages/axum-rest-tracker-api-server/tests/integration.rs diff --git a/packages/axum-tracker-api-server/tests/server/connection_info.rs b/packages/axum-rest-tracker-api-server/tests/server/connection_info.rs similarity index 75% rename from packages/axum-tracker-api-server/tests/server/connection_info.rs rename to packages/axum-rest-tracker-api-server/tests/server/connection_info.rs index e78f4cbb7..6459c9a2f 100644 --- a/packages/axum-tracker-api-server/tests/server/connection_info.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/connection_info.rs @@ -1,4 +1,4 @@ -use torrust_tracker_api_client::connection_info::{ConnectionInfo, Origin}; +use torrust_rest_tracker_api_client::connection_info::{ConnectionInfo, Origin}; pub fn connection_with_invalid_token(origin: Origin) -> ConnectionInfo { ConnectionInfo::authenticated(origin, "invalid token") diff --git a/packages/axum-tracker-api-server/tests/server/mod.rs b/packages/axum-rest-tracker-api-server/tests/server/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/tests/server/mod.rs rename to packages/axum-rest-tracker-api-server/tests/server/mod.rs diff --git a/packages/axum-tracker-api-server/tests/server/v1/asserts.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/asserts.rs similarity index 95% rename from packages/axum-tracker-api-server/tests/server/v1/asserts.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/asserts.rs index c1a06594a..abd60cf94 100644 --- a/packages/axum-tracker-api-server/tests/server/v1/asserts.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/asserts.rs @@ -1,9 +1,9 @@ // code-review: should we use macros to return the exact line where the assert fails? use reqwest::Response; -use torrust_axum_tracker_api_server::v1::context::auth_key::resources::AuthKey; -use torrust_axum_tracker_api_server::v1::context::stats::resources::Stats; -use torrust_axum_tracker_api_server::v1::context::torrent::resources::torrent::{ListItem, Torrent}; +use torrust_axum_rest_tracker_api_server::v1::context::auth_key::resources::AuthKey; +use torrust_axum_rest_tracker_api_server::v1::context::stats::resources::Stats; +use torrust_axum_rest_tracker_api_server::v1::context::torrent::resources::torrent::{ListItem, Torrent}; // Resource responses diff --git a/packages/axum-tracker-api-server/tests/server/v1/contract/authentication.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs similarity index 94% rename from packages/axum-tracker-api-server/tests/server/v1/contract/authentication.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs index 5acb25a3c..eac30d93a 100644 --- a/packages/axum-tracker-api-server/tests/server/v1/contract/authentication.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs @@ -1,6 +1,6 @@ -use torrust_axum_tracker_api_server::environment::Started; -use torrust_tracker_api_client::common::http::{Query, QueryParam}; -use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; +use torrust_axum_rest_tracker_api_server::environment::Started; +use torrust_rest_tracker_api_client::common::http::{Query, QueryParam}; +use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; diff --git a/packages/axum-tracker-api-server/tests/server/v1/contract/context/auth_key.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/auth_key.rs similarity index 98% rename from packages/axum-tracker-api-server/tests/server/v1/contract/context/auth_key.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/auth_key.rs index 92e4b59fe..f6355fc6e 100644 --- a/packages/axum-tracker-api-server/tests/server/v1/contract/context/auth_key.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/auth_key.rs @@ -2,8 +2,8 @@ use std::time::Duration; use bittorrent_tracker_core::authentication::Key; use serde::Serialize; -use torrust_axum_tracker_api_server::environment::Started; -use torrust_tracker_api_client::v1::client::{headers_with_request_id, AddKeyForm, Client}; +use torrust_axum_rest_tracker_api_server::environment::Started; +use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, AddKeyForm, Client}; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; @@ -482,8 +482,8 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { mod deprecated_generate_key_endpoint { use bittorrent_tracker_core::authentication::Key; - use torrust_axum_tracker_api_server::environment::Started; - use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; + use torrust_axum_rest_tracker_api_server::environment::Started; + use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; diff --git a/packages/axum-tracker-api-server/tests/server/v1/contract/context/health_check.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/health_check.rs similarity index 75% rename from packages/axum-tracker-api-server/tests/server/v1/contract/context/health_check.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/health_check.rs index d543422d3..3a08c6d51 100644 --- a/packages/axum-tracker-api-server/tests/server/v1/contract/context/health_check.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/health_check.rs @@ -1,6 +1,6 @@ -use torrust_axum_tracker_api_server::environment::Started; -use torrust_axum_tracker_api_server::v1::context::health_check::resources::{Report, Status}; -use torrust_tracker_api_client::v1::client::get; +use torrust_axum_rest_tracker_api_server::environment::Started; +use torrust_axum_rest_tracker_api_server::v1::context::health_check::resources::{Report, Status}; +use torrust_rest_tracker_api_client::v1::client::get; use torrust_tracker_test_helpers::{configuration, logging}; use url::Url; diff --git a/packages/axum-tracker-api-server/tests/server/v1/contract/context/mod.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/tests/server/v1/contract/context/mod.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/mod.rs diff --git a/packages/axum-tracker-api-server/tests/server/v1/contract/context/stats.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs similarity index 93% rename from packages/axum-tracker-api-server/tests/server/v1/contract/context/stats.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs index 179e5c555..1e66eb4cc 100644 --- a/packages/axum-tracker-api-server/tests/server/v1/contract/context/stats.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs @@ -1,9 +1,9 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; -use torrust_axum_tracker_api_server::environment::Started; -use torrust_axum_tracker_api_server::v1::context::stats::resources::Stats; -use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; +use torrust_axum_rest_tracker_api_server::environment::Started; +use torrust_axum_rest_tracker_api_server::v1::context::stats::resources::Stats; +use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; diff --git a/packages/axum-tracker-api-server/tests/server/v1/contract/context/torrent.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs similarity index 96% rename from packages/axum-tracker-api-server/tests/server/v1/contract/context/torrent.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs index d77147f38..b479416e4 100644 --- a/packages/axum-tracker-api-server/tests/server/v1/contract/context/torrent.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs @@ -1,11 +1,11 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; -use torrust_axum_tracker_api_server::environment::Started; -use torrust_axum_tracker_api_server::v1::context::torrent::resources::peer::Peer; -use torrust_axum_tracker_api_server::v1::context::torrent::resources::torrent::{self, Torrent}; -use torrust_tracker_api_client::common::http::{Query, QueryParam}; -use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; +use torrust_axum_rest_tracker_api_server::environment::Started; +use torrust_axum_rest_tracker_api_server::v1::context::torrent::resources::peer::Peer; +use torrust_axum_rest_tracker_api_server::v1::context::torrent::resources::torrent::{self, Torrent}; +use torrust_rest_tracker_api_client::common::http::{Query, QueryParam}; +use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; diff --git a/packages/axum-tracker-api-server/tests/server/v1/contract/context/whitelist.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/whitelist.rs similarity index 98% rename from packages/axum-tracker-api-server/tests/server/v1/contract/context/whitelist.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/whitelist.rs index e41b74f45..e8f98b8ab 100644 --- a/packages/axum-tracker-api-server/tests/server/v1/contract/context/whitelist.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/whitelist.rs @@ -1,8 +1,8 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; -use torrust_axum_tracker_api_server::environment::Started; -use torrust_tracker_api_client::v1::client::{headers_with_request_id, Client}; +use torrust_axum_rest_tracker_api_server::environment::Started; +use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; diff --git a/packages/axum-tracker-api-server/tests/server/v1/contract/fixtures.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/fixtures.rs similarity index 100% rename from packages/axum-tracker-api-server/tests/server/v1/contract/fixtures.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/contract/fixtures.rs diff --git a/packages/axum-tracker-api-server/tests/server/v1/contract/mod.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/tests/server/v1/contract/mod.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/contract/mod.rs diff --git a/packages/axum-tracker-api-server/tests/server/v1/mod.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/mod.rs similarity index 100% rename from packages/axum-tracker-api-server/tests/server/v1/mod.rs rename to packages/axum-rest-tracker-api-server/tests/server/v1/mod.rs diff --git a/packages/tracker-api-client/Cargo.toml b/packages/rest-tracker-api-client/Cargo.toml similarity index 93% rename from packages/tracker-api-client/Cargo.toml rename to packages/rest-tracker-api-client/Cargo.toml index ee45e12f7..cba580e18 100644 --- a/packages/tracker-api-client/Cargo.toml +++ b/packages/rest-tracker-api-client/Cargo.toml @@ -2,7 +2,7 @@ description = "A library to interact with the Torrust Tracker REST API." keywords = ["bittorrent", "client", "tracker"] license = "LGPL-3.0" -name = "torrust-tracker-api-client" +name = "torrust-rest-tracker-api-client" readme = "README.md" authors.workspace = true diff --git a/packages/tracker-api-client/README.md b/packages/rest-tracker-api-client/README.md similarity index 100% rename from packages/tracker-api-client/README.md rename to packages/rest-tracker-api-client/README.md diff --git a/packages/tracker-api-client/docs/licenses/LICENSE-MIT_0 b/packages/rest-tracker-api-client/docs/licenses/LICENSE-MIT_0 similarity index 100% rename from packages/tracker-api-client/docs/licenses/LICENSE-MIT_0 rename to packages/rest-tracker-api-client/docs/licenses/LICENSE-MIT_0 diff --git a/packages/tracker-api-client/src/common/http.rs b/packages/rest-tracker-api-client/src/common/http.rs similarity index 100% rename from packages/tracker-api-client/src/common/http.rs rename to packages/rest-tracker-api-client/src/common/http.rs diff --git a/packages/tracker-api-client/src/common/mod.rs b/packages/rest-tracker-api-client/src/common/mod.rs similarity index 100% rename from packages/tracker-api-client/src/common/mod.rs rename to packages/rest-tracker-api-client/src/common/mod.rs diff --git a/packages/tracker-api-client/src/connection_info.rs b/packages/rest-tracker-api-client/src/connection_info.rs similarity index 100% rename from packages/tracker-api-client/src/connection_info.rs rename to packages/rest-tracker-api-client/src/connection_info.rs diff --git a/packages/tracker-api-client/src/lib.rs b/packages/rest-tracker-api-client/src/lib.rs similarity index 100% rename from packages/tracker-api-client/src/lib.rs rename to packages/rest-tracker-api-client/src/lib.rs diff --git a/packages/tracker-api-client/src/v1/client.rs b/packages/rest-tracker-api-client/src/v1/client.rs similarity index 100% rename from packages/tracker-api-client/src/v1/client.rs rename to packages/rest-tracker-api-client/src/v1/client.rs diff --git a/packages/tracker-api-client/src/v1/mod.rs b/packages/rest-tracker-api-client/src/v1/mod.rs similarity index 100% rename from packages/tracker-api-client/src/v1/mod.rs rename to packages/rest-tracker-api-client/src/v1/mod.rs diff --git a/packages/tracker-api-core/Cargo.toml b/packages/rest-tracker-api-core/Cargo.toml similarity index 96% rename from packages/tracker-api-core/Cargo.toml rename to packages/rest-tracker-api-core/Cargo.toml index 495729e69..d9ccb5d3f 100644 --- a/packages/tracker-api-core/Cargo.toml +++ b/packages/rest-tracker-api-core/Cargo.toml @@ -6,7 +6,7 @@ edition.workspace = true homepage.workspace = true keywords = ["api", "bittorrent", "core", "library", "tracker"] license.workspace = true -name = "torrust-tracker-api-core" +name = "torrust-rest-tracker-api-core" publish.workspace = true readme = "README.md" repository.workspace = true diff --git a/packages/tracker-api-core/LICENSE b/packages/rest-tracker-api-core/LICENSE similarity index 100% rename from packages/tracker-api-core/LICENSE rename to packages/rest-tracker-api-core/LICENSE diff --git a/packages/tracker-api-core/README.md b/packages/rest-tracker-api-core/README.md similarity index 100% rename from packages/tracker-api-core/README.md rename to packages/rest-tracker-api-core/README.md diff --git a/packages/tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs similarity index 100% rename from packages/tracker-api-core/src/container.rs rename to packages/rest-tracker-api-core/src/container.rs diff --git a/packages/tracker-api-core/src/lib.rs b/packages/rest-tracker-api-core/src/lib.rs similarity index 100% rename from packages/tracker-api-core/src/lib.rs rename to packages/rest-tracker-api-core/src/lib.rs diff --git a/packages/tracker-api-core/src/statistics/metrics.rs b/packages/rest-tracker-api-core/src/statistics/metrics.rs similarity index 100% rename from packages/tracker-api-core/src/statistics/metrics.rs rename to packages/rest-tracker-api-core/src/statistics/metrics.rs diff --git a/packages/tracker-api-core/src/statistics/mod.rs b/packages/rest-tracker-api-core/src/statistics/mod.rs similarity index 100% rename from packages/tracker-api-core/src/statistics/mod.rs rename to packages/rest-tracker-api-core/src/statistics/mod.rs diff --git a/packages/tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs similarity index 100% rename from packages/tracker-api-core/src/statistics/services.rs rename to packages/rest-tracker-api-core/src/statistics/services.rs diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index 731ee900d..ac1cee88d 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -38,6 +38,6 @@ tracing = "0" local-ip-address = "0" mockall = "0" testcontainers = "0" -torrust-tracker-api-client = { version = "3.0.0-develop", path = "../tracker-api-client" } +torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "../rest-tracker-api-client" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } url = "2.5.4" diff --git a/src/app.rs b/src/app.rs index 5458ea600..60e907a88 100644 --- a/src/app.rs +++ b/src/app.rs @@ -118,7 +118,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> if let Some(job) = tracker_apis::start_job( http_api_container, registar.give_form(), - torrust_axum_tracker_api_server::Version::V1, + torrust_axum_rest_tracker_api_server::Version::V1, ) .await { diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 93850d65e..d152e853f 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -25,11 +25,11 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; use tokio::task::JoinHandle; +use torrust_axum_rest_tracker_api_server::server::{ApiServer, Launcher}; +use torrust_axum_rest_tracker_api_server::Version; use torrust_axum_server::tsl::make_rust_tls; -use torrust_axum_tracker_api_server::server::{ApiServer, Launcher}; -use torrust_axum_tracker_api_server::Version; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::registar::ServiceRegistrationForm; -use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::AccessTokens; use tracing::instrument; @@ -96,9 +96,9 @@ async fn start_v1( mod tests { use std::sync::Arc; - use torrust_axum_tracker_api_server::Version; + use torrust_axum_rest_tracker_api_server::Version; + use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::registar::Registar; - use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::bootstrap::app::initialize_global_services; diff --git a/src/container.rs b/src/container.rs index b10ac9ae0..4bdae1b29 100644 --- a/src/container.rs +++ b/src/container.rs @@ -17,7 +17,7 @@ use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; -use torrust_tracker_api_core::container::TrackerHttpApiCoreContainer; +use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::{Configuration, Core, HttpApi, HttpTracker, UdpTracker}; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use tracing::instrument; diff --git a/src/lib.rs b/src/lib.rs index 5f05df8b2..e947d2ab5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -55,7 +55,7 @@ //! //! From the end-user perspective the Torrust Tracker exposes three different services. //! -//! - A REST [`API`](torrust_axum_tracker_api_server) +//! - A REST [`API`](torrust_axum_rest_tracker_api_server) //! - One or more [`UDP`](torrust_udp_tracker_server) trackers //! - One or more [`HTTP`](torrust_axum_http_tracker_server) trackers //! @@ -124,7 +124,7 @@ //! By default the tracker uses `SQLite` and the database file name `sqlite3.db`. //! //! You only need the `tls` directory in case you are setting up SSL for the HTTP tracker or the tracker API. -//! Visit [`HTTP`](torrust_axum_http_tracker_server) or [`API`](torrust_axum_tracker_api_server) if you want to know how you can use HTTPS. +//! Visit [`HTTP`](torrust_axum_http_tracker_server) or [`API`](torrust_axum_rest_tracker_api_server) if you want to know how you can use HTTPS. //! //! ## Install from sources //! @@ -280,7 +280,7 @@ //! } //! ``` //! -//! Refer to the [`API`](torrust_axum_tracker_api_server) documentation for more information about the [`API`](torrust_axum_tracker_api_server) endpoints. +//! Refer to the [`API`](torrust_axum_rest_tracker_api_server) documentation for more information about the [`API`](torrust_axum_rest_tracker_api_server) endpoints. //! //! ## HTTP tracker //! @@ -359,7 +359,7 @@ //! //! If the tracker is running in `private` or `private_listed` mode you will need to provide a valid authentication key. //! -//! Right now the only way to add new keys is via the REST [`API`](torrust_axum_tracker_api_server). The endpoint `POST /api/vi/key/:duration_in_seconds` +//! Right now the only way to add new keys is via the REST [`API`](torrust_axum_rest_tracker_api_server). The endpoint `POST /api/vi/key/:duration_in_seconds` //! will return an expiring key that will be valid for `duration_in_seconds` seconds. //! //! Using `curl` you can create a 2-minute valid auth key: @@ -379,7 +379,7 @@ //! ``` //! //! You can also use the Torrust Tracker together with the [Torrust Index](https://github.com/torrust/torrust-index). If that's the case, -//! the Index will create the keys by using the tracker [API](torrust_axum_tracker_api_server). +//! the Index will create the keys by using the tracker [API](torrust_axum_rest_tracker_api_server). //! //! ## UDP tracker //! @@ -406,7 +406,7 @@ //! Torrust Tracker has four main components: //! //! - The core tracker [`core`] -//! - The tracker REST [`API`](torrust_axum_tracker_api_server) +//! - The tracker REST [`API`](torrust_axum_rest_tracker_api_server) //! - The [`UDP`](torrust_udp_tracker_server) tracker //! - The [`HTTP`](torrust_axum_http_tracker_server) tracker //! @@ -434,7 +434,7 @@ //! - Torrents: to get peers for a torrent //! - Whitelist: to handle the torrent whitelist when the tracker runs on `listed` or `private_listed` mode //! -//! See [`API`](torrust_axum_tracker_api_server) for more details on the REST API. +//! See [`API`](torrust_axum_rest_tracker_api_server) for more details on the REST API. //! //! ## UDP tracker //! From 5da41038f5f01a193e8fef1387e0b4af4357f3b4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 27 Feb 2025 19:11:23 +0000 Subject: [PATCH 0836/1297] chore(deps): udpate dependencies ``` cargo update Updating crates.io index Locking 24 packages to latest compatible versions Updating async-compression v0.4.18 -> v0.4.19 Updating cc v1.2.14 -> v1.2.15 Updating chrono v0.4.39 -> v0.4.40 Updating clap v4.5.30 -> v4.5.31 Updating clap_builder v4.5.30 -> v4.5.31 Updating either v1.13.0 -> v1.14.0 Updating flate2 v1.0.35 -> v1.1.0 Updating inout v0.1.3 -> v0.1.4 Updating libc v0.2.169 -> v0.2.170 Updating litemap v0.7.4 -> v0.7.5 Updating log v0.4.25 -> v0.4.26 Updating miniz_oxide v0.8.4 -> v0.8.5 Updating pem v3.0.4 -> v3.0.5 Updating portable-atomic v1.10.0 -> v1.11.0 Updating rand_core v0.9.1 -> v0.9.2 Updating redox_syscall v0.5.8 -> v0.5.9 Updating ring v0.17.9 -> v0.17.11 Updating uuid v1.13.2 -> v1.15.1 Adding windows-link v0.1.0 Updating zerofrom v0.1.5 -> v0.1.6 Updating zerofrom-derive v0.1.5 -> v0.1.6 Updating zstd v0.13.2 -> v0.13.3 Updating zstd-safe v7.2.1 -> v7.2.3 Updating zstd-sys v2.0.13+zstd.1.5.6 -> v2.0.14+zstd.1.5.7 ``` --- Cargo.lock | 115 +++++++++--------- .../tests/common/fixtures.rs | 4 +- .../tests/common/fixtures.rs | 6 +- 3 files changed, 65 insertions(+), 60 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fbb55562a..3e1cea83d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -208,9 +208,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.18" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df895a515f70646414f4b45c0b79082783b80552b373a68283012928df56f522" +checksum = "06575e6a9673580f52661c92107baabffbf41e2141373441cbcdc47cb733003c" dependencies = [ "brotli", "flate2", @@ -925,9 +925,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.14" +version = "1.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c3d1b2e905a3a7b00a6141adb0e4c0bb941d11caf55349d863942a1cc44e3c9" +checksum = "c736e259eea577f443d5c86c304f9f4ae0295c43f3ba05c21f1d66b5f06001af" dependencies = [ "jobserver", "libc", @@ -957,15 +957,15 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "chrono" -version = "0.4.39" +version = "0.4.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e36cc9d416881d2e24f9a963be5fb1cd90966419ac844274161d10488b3e825" +checksum = "1a7964611d71df112cb1730f2ee67324fcf4d0fc6606acbbe9bfe06df124637c" dependencies = [ "android-tzdata", "iana-time-zone", "num-traits", "serde", - "windows-targets 0.52.6", + "windows-link", ] [[package]] @@ -1018,9 +1018,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.30" +version = "4.5.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92b7b18d71fad5313a1e320fa9897994228ce274b60faa4d694fe0ea89cd9e6d" +checksum = "027bb0d98429ae334a8698531da7077bdf906419543a35a55c2cb1b66437d767" dependencies = [ "clap_builder", "clap_derive", @@ -1028,9 +1028,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.30" +version = "4.5.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a35db2071778a7344791a4fb4f95308b5673d219dee3ae348b86642574ecc90c" +checksum = "5589e0cba072e0f3d23791efac0fd8627b49c829c196a492e88168e6a669d863" dependencies = [ "anstream", "anstyle", @@ -1388,9 +1388,9 @@ checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" [[package]] name = "either" -version = "1.13.0" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" +checksum = "b7914353092ddf589ad78f25c5c1c21b7f80b0ff8621e7c814c3485b5306da9d" [[package]] name = "encoding_rs" @@ -1513,9 +1513,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.35" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c936bfdafb507ebbf50b8074c54fa31c5be9a1e7e5f467dd659697041407d07c" +checksum = "11faaf5a5236997af9848be0bef4db95824b1d534ebc64d0f0c6cf3e67bd38dc" dependencies = [ "crc32fast", "libz-sys", @@ -2245,9 +2245,9 @@ checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" [[package]] name = "inout" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" dependencies = [ "generic-array", ] @@ -2344,9 +2344,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.169" +version = "0.2.170" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" +checksum = "875b3680cb2f8f71bdcf9a30f38d48282f5d3c95cbf9b3fa57269bb5d5c06828" [[package]] name = "libloading" @@ -2372,7 +2372,7 @@ checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ "bitflags 2.8.0", "libc", - "redox_syscall 0.5.8", + "redox_syscall 0.5.9", ] [[package]] @@ -2405,9 +2405,9 @@ checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] name = "litemap" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ee93343901ab17bd981295f2cf0026d4ad018c7c31ba84549a4ddbb47a45104" +checksum = "23fb14cb19457329c82206317a5663005a4d404783dc74f4252769b0d5f42856" [[package]] name = "local-ip-address" @@ -2433,9 +2433,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.25" +version = "0.4.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04cbf5b083de1c7e0222a7a51dbfdba1cbe1c6ab0b15e29fff3f6c077fd9cd9f" +checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e" dependencies = [ "value-bag", ] @@ -2475,9 +2475,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3b1c9bd4fe1f0f8b387f6eb9eb3b4a1aa26185e5750efb9140301703f62cd1b" +checksum = "8e3e04debbb59698c15bacbb6d93584a8c0ca9cc3213cb423d31f760d8843ce5" dependencies = [ "adler2", ] @@ -2816,7 +2816,7 @@ checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.8", + "redox_syscall 0.5.9", "smallvec", "windows-targets 0.52.6", ] @@ -2871,9 +2871,9 @@ dependencies = [ [[package]] name = "pem" -version = "3.0.4" +version = "3.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e459365e590736a54c3fa561947c84837534b8e9af6fc5bf781307e82658fae" +checksum = "38af38e8470ac9dee3ce1bae1af9c1671fffc44ddfd8bd1d0a3445bf349a8ef3" dependencies = [ "base64 0.22.1", "serde", @@ -3017,9 +3017,9 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "280dc24453071f1b63954171985a0b0d30058d287960968b9b2aca264c8d4ee6" +checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e" [[package]] name = "powerfmt" @@ -3211,7 +3211,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" dependencies = [ "rand_chacha 0.9.0", - "rand_core 0.9.1", + "rand_core 0.9.2", "zerocopy 0.8.20", ] @@ -3232,7 +3232,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core 0.9.1", + "rand_core 0.9.2", ] [[package]] @@ -3246,9 +3246,9 @@ dependencies = [ [[package]] name = "rand_core" -version = "0.9.1" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a88e0da7a2c97baa202165137c158d0a2e824ac465d13d81046727b34cb247d3" +checksum = "7a509b1a2ffbe92afab0e55c8fd99dea1c280e8171bd2d88682bb20bc41cbc2c" dependencies = [ "getrandom 0.3.1", "zerocopy 0.8.20", @@ -3285,9 +3285,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" +checksum = "82b568323e98e49e2a0899dcee453dd679fae22d69adf9b11dd508d1549b7e2f" dependencies = [ "bitflags 2.8.0", ] @@ -3382,9 +3382,9 @@ dependencies = [ [[package]] name = "ring" -version = "0.17.9" +version = "0.17.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e75ec5e92c4d8aede845126adc388046234541629e76029599ed35a003c7ed24" +checksum = "da5349ae27d3887ca812fb375b45a4fbb36d8d12d2df394968cd86e35683fe73" dependencies = [ "cc", "cfg-if", @@ -4379,7 +4379,7 @@ dependencies = [ "hyper", "local-ip-address", "percent-encoding", - "rand 0.8.5", + "rand 0.9.0", "reqwest", "serde", "serde_bencode", @@ -4431,7 +4431,7 @@ dependencies = [ "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-udp-tracker-server", - "tower 0.4.13", + "tower 0.5.2", "tower-http", "tracing", "url", @@ -4659,7 +4659,7 @@ dependencies = [ "futures-util", "local-ip-address", "mockall", - "rand 0.8.5", + "rand 0.9.0", "ringbuf", "thiserror 2.0.11", "tokio", @@ -4685,7 +4685,6 @@ dependencies = [ "futures-util", "pin-project", "pin-project-lite", - "tokio", "tower-layer", "tower-service", "tracing", @@ -4893,9 +4892,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.13.2" +version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c1f41ffb7cf259f1ecc2876861a17e7142e63ead296f671f81f6ae85903e0d6" +checksum = "e0f540e3240398cce6128b64ba83fdbdd86129c16a3aa1a3a252efd66eb3d587" dependencies = [ "getrandom 0.3.1", "rand 0.9.0", @@ -5080,6 +5079,12 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-link" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dccfd733ce2b1753b03b6d3c65edf020262ea35e20ccdf3e288043e6dd620e3" + [[package]] name = "windows-registry" version = "0.2.0" @@ -5381,18 +5386,18 @@ dependencies = [ [[package]] name = "zerofrom" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cff3ee08c995dee1859d998dea82f7374f2826091dd9cd47def953cae446cd2e" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" dependencies = [ "zerofrom-derive", ] [[package]] name = "zerofrom-derive" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", @@ -5430,27 +5435,27 @@ dependencies = [ [[package]] name = "zstd" -version = "0.13.2" +version = "0.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcf2b778a664581e31e389454a7072dab1647606d44f7feea22cd5abb9c9f3f9" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "7.2.1" +version = "7.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54a3ab4db68cea366acc5c897c7b4d4d1b8994a9cd6e6f841f8964566a419059" +checksum = "f3051792fbdc2e1e143244dc28c60f73d8470e93f3f9cbd0ead44da5ed802722" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.0.13+zstd.1.5.6" +version = "2.0.14+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38ff0f21cfee8f97d94cef41359e0c89aa6113028ab0291aa8ca0038995a95aa" +checksum = "8fb060d4926e4ac3a3ad15d864e99ceb5f343c6b34f5bd6d81ae6ed417311be5" dependencies = [ "cc", "pkg-config", diff --git a/packages/axum-http-tracker-server/tests/common/fixtures.rs b/packages/axum-http-tracker-server/tests/common/fixtures.rs index 995079adf..2b4a42b58 100644 --- a/packages/axum-http-tracker-server/tests/common/fixtures.rs +++ b/packages/axum-http-tracker-server/tests/common/fixtures.rs @@ -15,8 +15,8 @@ pub fn invalid_info_hashes() -> Vec { /// Returns a random info hash. pub fn random_info_hash() -> InfoHash { - let mut rng = rand::thread_rng(); - let random_bytes: [u8; 20] = rng.gen(); + let mut rng = rand::rng(); + let random_bytes: [u8; 20] = rng.random(); InfoHash::from_bytes(&random_bytes) } diff --git a/packages/udp-tracker-server/tests/common/fixtures.rs b/packages/udp-tracker-server/tests/common/fixtures.rs index 477314398..f4066c67a 100644 --- a/packages/udp-tracker-server/tests/common/fixtures.rs +++ b/packages/udp-tracker-server/tests/common/fixtures.rs @@ -4,14 +4,14 @@ use rand::prelude::*; /// Returns a random info hash. pub fn random_info_hash() -> InfoHash { - let mut rng = rand::thread_rng(); - let random_bytes: [u8; 20] = rng.gen(); + let mut rng = rand::rng(); + let random_bytes: [u8; 20] = rng.random(); InfoHash::from_bytes(&random_bytes) } /// Returns a random transaction id. pub fn random_transaction_id() -> TransactionId { - let random_value = rand::thread_rng().gen(); + let random_value = rand::rng().random(); TransactionId::new(random_value) } From 89b0bfd4549d4f7eb453389ec47880ad9956d8d8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 28 Feb 2025 09:51:42 +0000 Subject: [PATCH 0837/1297] refactor: [#689] improve REST API client - Add a timeout to the requests. - Return an error in the construction if it can't build the HTTP client. - Extract constants. --- .../server/v1/contract/authentication.rs | 6 +++ .../server/v1/contract/context/auth_key.rs | 21 ++++++++++ .../tests/server/v1/contract/context/stats.rs | 3 ++ .../server/v1/contract/context/torrent.rs | 15 +++++++ .../server/v1/contract/context/whitelist.rs | 18 +++++++- .../rest-tracker-api-client/src/v1/client.rs | 42 ++++++++++++++----- 6 files changed, 93 insertions(+), 12 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs index eac30d93a..3b6419187 100644 --- a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs @@ -16,6 +16,7 @@ async fn should_authenticate_requests_by_using_a_token_query_param() { let token = env.get_connection_info().api_token.unwrap(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_request_with_query("stats", Query::params([QueryParam::new("token", &token)].to_vec()), None) .await; @@ -33,6 +34,7 @@ async fn should_not_authenticate_requests_when_the_token_is_missing() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_request_with_query("stats", Query::default(), Some(headers_with_request_id(request_id))) .await; @@ -55,6 +57,7 @@ async fn should_not_authenticate_requests_when_the_token_is_empty() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_request_with_query( "stats", Query::params([QueryParam::new("token", "")].to_vec()), @@ -81,6 +84,7 @@ async fn should_not_authenticate_requests_when_the_token_is_invalid() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_request_with_query( "stats", Query::params([QueryParam::new("token", "INVALID TOKEN")].to_vec()), @@ -108,6 +112,7 @@ async fn should_allow_the_token_query_param_to_be_at_any_position_in_the_url_que // At the beginning of the query component let response = Client::new(env.get_connection_info()) + .unwrap() .get_request(&format!("torrents?token={token}&limit=1")) .await; @@ -115,6 +120,7 @@ async fn should_allow_the_token_query_param_to_be_at_any_position_in_the_url_que // At the end of the query component let response = Client::new(env.get_connection_info()) + .unwrap() .get_request(&format!("torrents?limit=1&token={token}")) .await; diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/auth_key.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/auth_key.rs index f6355fc6e..3781f4f60 100644 --- a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/auth_key.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/auth_key.rs @@ -25,6 +25,7 @@ async fn should_allow_generating_a_new_random_auth_key() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .add_auth_key( AddKeyForm { opt_key: None, @@ -56,6 +57,7 @@ async fn should_allow_uploading_a_preexisting_auth_key() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .add_auth_key( AddKeyForm { opt_key: Some("Xc1L4PbQJSFGlrgSRZl8wxSFAuMa21z5".to_string()), @@ -87,6 +89,7 @@ async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() let request_id = Uuid::new_v4(); let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() .add_auth_key( AddKeyForm { opt_key: None, @@ -106,6 +109,7 @@ async fn should_not_allow_generating_a_new_auth_key_for_unauthenticated_users() let request_id = Uuid::new_v4(); let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() .add_auth_key( AddKeyForm { opt_key: None, @@ -136,6 +140,7 @@ async fn should_fail_when_the_auth_key_cannot_be_generated() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .add_auth_key( AddKeyForm { opt_key: None, @@ -173,6 +178,7 @@ async fn should_allow_deleting_an_auth_key() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) .await; @@ -207,6 +213,7 @@ async fn should_fail_generating_a_new_auth_key_when_the_provided_key_is_invalid( let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .post_form( "keys", &InvalidAddKeyForm { @@ -246,6 +253,7 @@ async fn should_fail_generating_a_new_auth_key_when_the_key_duration_is_invalid( let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .post_form( "keys", &InvalidAddKeyForm { @@ -282,6 +290,7 @@ async fn should_fail_deleting_an_auth_key_when_the_key_id_is_invalid() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .delete_auth_key(invalid_auth_key, Some(headers_with_request_id(request_id))) .await; @@ -311,6 +320,7 @@ async fn should_fail_when_the_auth_key_cannot_be_deleted() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) .await; @@ -344,6 +354,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { let request_id = Uuid::new_v4(); let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) .await; @@ -366,6 +377,7 @@ async fn should_not_allow_deleting_an_auth_key_for_unauthenticated_users() { let request_id = Uuid::new_v4(); let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() .delete_auth_key(&auth_key.key.to_string(), Some(headers_with_request_id(request_id))) .await; @@ -396,6 +408,7 @@ async fn should_allow_reloading_keys() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .reload_keys(Some(headers_with_request_id(request_id))) .await; @@ -423,6 +436,7 @@ async fn should_fail_when_keys_cannot_be_reloaded() { force_database_error(&env.container.tracker_core_container.database); let response = Client::new(env.get_connection_info()) + .unwrap() .reload_keys(Some(headers_with_request_id(request_id))) .await; @@ -453,6 +467,7 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { let request_id = Uuid::new_v4(); let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() .reload_keys(Some(headers_with_request_id(request_id))) .await; @@ -466,6 +481,7 @@ async fn should_not_allow_reloading_keys_for_unauthenticated_users() { let request_id = Uuid::new_v4(); let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() .reload_keys(Some(headers_with_request_id(request_id))) .await; @@ -504,6 +520,7 @@ mod deprecated_generate_key_endpoint { let seconds_valid = 60; let response = Client::new(env.get_connection_info()) + .unwrap() .generate_auth_key(seconds_valid, None) .await; @@ -530,12 +547,14 @@ mod deprecated_generate_key_endpoint { let seconds_valid = 60; let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() .generate_auth_key(seconds_valid, Some(headers_with_request_id(request_id))) .await; assert_token_not_valid(response).await; let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() .generate_auth_key(seconds_valid, None) .await; @@ -563,6 +582,7 @@ mod deprecated_generate_key_endpoint { for invalid_key_duration in invalid_key_durations { let response = Client::new(env.get_connection_info()) + .unwrap() .post_empty(&format!("key/{invalid_key_duration}"), None) .await; @@ -583,6 +603,7 @@ mod deprecated_generate_key_endpoint { let request_id = Uuid::new_v4(); let seconds_valid = 60; let response = Client::new(env.get_connection_info()) + .unwrap() .generate_auth_key(seconds_valid, Some(headers_with_request_id(request_id))) .await; diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs index 1e66eb4cc..51a4804e7 100644 --- a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs @@ -26,6 +26,7 @@ async fn should_allow_getting_tracker_statistics() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_tracker_statistics(Some(headers_with_request_id(request_id))) .await; @@ -80,6 +81,7 @@ async fn should_not_allow_getting_tracker_statistics_for_unauthenticated_users() let request_id = Uuid::new_v4(); let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() .get_tracker_statistics(Some(headers_with_request_id(request_id))) .await; @@ -93,6 +95,7 @@ async fn should_not_allow_getting_tracker_statistics_for_unauthenticated_users() let request_id = Uuid::new_v4(); let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() .get_tracker_statistics(Some(headers_with_request_id(request_id))) .await; diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs index b479416e4..42421db99 100644 --- a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs @@ -31,6 +31,7 @@ async fn should_allow_getting_all_torrents() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_torrents(Query::empty(), Some(headers_with_request_id(request_id))) .await; @@ -64,6 +65,7 @@ async fn should_allow_limiting_the_torrents_in_the_result() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_torrents( Query::params([QueryParam::new("limit", "1")].to_vec()), Some(headers_with_request_id(request_id)), @@ -100,6 +102,7 @@ async fn should_allow_the_torrents_result_pagination() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_torrents( Query::params([QueryParam::new("offset", "1")].to_vec()), Some(headers_with_request_id(request_id)), @@ -135,6 +138,7 @@ async fn should_allow_getting_a_list_of_torrents_providing_infohashes() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_torrents( Query::params( [ @@ -181,6 +185,7 @@ async fn should_fail_getting_torrents_when_the_offset_query_parameter_cannot_be_ let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_torrents( Query::params([QueryParam::new("offset", invalid_offset)].to_vec()), Some(headers_with_request_id(request_id)), @@ -209,6 +214,7 @@ async fn should_fail_getting_torrents_when_the_limit_query_parameter_cannot_be_p let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_torrents( Query::params([QueryParam::new("limit", invalid_limit)].to_vec()), Some(headers_with_request_id(request_id)), @@ -237,6 +243,7 @@ async fn should_fail_getting_torrents_when_the_info_hash_parameter_is_invalid() let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_torrents( Query::params([QueryParam::new("info_hash", invalid_info_hash)].to_vec()), Some(headers_with_request_id(request_id)), @@ -262,6 +269,7 @@ async fn should_not_allow_getting_torrents_for_unauthenticated_users() { let request_id = Uuid::new_v4(); let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() .get_torrents(Query::empty(), Some(headers_with_request_id(request_id))) .await; @@ -275,6 +283,7 @@ async fn should_not_allow_getting_torrents_for_unauthenticated_users() { let request_id = Uuid::new_v4(); let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() .get_torrents(Query::default(), Some(headers_with_request_id(request_id))) .await; @@ -303,6 +312,7 @@ async fn should_allow_getting_a_torrent_info() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) .await; @@ -331,6 +341,7 @@ async fn should_fail_while_getting_a_torrent_info_when_the_torrent_does_not_exis let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 let response = Client::new(env.get_connection_info()) + .unwrap() .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) .await; @@ -349,6 +360,7 @@ async fn should_fail_getting_a_torrent_info_when_the_provided_infohash_is_invali let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_torrent(invalid_infohash, Some(headers_with_request_id(request_id))) .await; @@ -359,6 +371,7 @@ async fn should_fail_getting_a_torrent_info_when_the_provided_infohash_is_invali let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .get_torrent(invalid_infohash, Some(headers_with_request_id(request_id))) .await; @@ -381,6 +394,7 @@ async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { let request_id = Uuid::new_v4(); let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) .await; @@ -394,6 +408,7 @@ async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { let request_id = Uuid::new_v4(); let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() .get_torrent(&info_hash.to_string(), Some(headers_with_request_id(request_id))) .await; diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/whitelist.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/whitelist.rs index e8f98b8ab..61fc233d0 100644 --- a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/whitelist.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/whitelist.rs @@ -25,6 +25,7 @@ async fn should_allow_whitelisting_a_torrent() { let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let response = Client::new(env.get_connection_info()) + .unwrap() .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) .await; @@ -48,7 +49,7 @@ async fn should_allow_whitelisting_a_torrent_that_has_been_already_whitelisted() let info_hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 - let api_client = Client::new(env.get_connection_info()); + let api_client = Client::new(env.get_connection_info()).unwrap(); let request_id = Uuid::new_v4(); @@ -78,6 +79,7 @@ async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { let request_id = Uuid::new_v4(); let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) .await; @@ -91,6 +93,7 @@ async fn should_not_allow_whitelisting_a_torrent_for_unauthenticated_users() { let request_id = Uuid::new_v4(); let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) .await; @@ -117,6 +120,7 @@ async fn should_fail_when_the_torrent_cannot_be_whitelisted() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .whitelist_a_torrent(&info_hash, Some(headers_with_request_id(request_id))) .await; @@ -140,6 +144,7 @@ async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invali for invalid_infohash in &invalid_infohashes_returning_bad_request() { let response = Client::new(env.get_connection_info()) + .unwrap() .whitelist_a_torrent(invalid_infohash, Some(headers_with_request_id(request_id))) .await; @@ -150,6 +155,7 @@ async fn should_fail_whitelisting_a_torrent_when_the_provided_infohash_is_invali for invalid_infohash in &invalid_infohashes_returning_not_found() { let response = Client::new(env.get_connection_info()) + .unwrap() .whitelist_a_torrent(invalid_infohash, Some(headers_with_request_id(request_id))) .await; @@ -178,6 +184,7 @@ async fn should_allow_removing_a_torrent_from_the_whitelist() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) .await; @@ -204,6 +211,7 @@ async fn should_not_fail_trying_to_remove_a_non_whitelisted_torrent_from_the_whi let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .remove_torrent_from_whitelist(&non_whitelisted_torrent_hash, Some(headers_with_request_id(request_id))) .await; @@ -222,6 +230,7 @@ async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_inf let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .remove_torrent_from_whitelist(invalid_infohash, Some(headers_with_request_id(request_id))) .await; @@ -232,6 +241,7 @@ async fn should_fail_removing_a_torrent_from_the_whitelist_when_the_provided_inf let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .remove_torrent_from_whitelist(invalid_infohash, Some(headers_with_request_id(request_id))) .await; @@ -261,6 +271,7 @@ async fn should_fail_when_the_torrent_cannot_be_removed_from_the_whitelist() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) .await; @@ -293,6 +304,7 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica let request_id = Uuid::new_v4(); let response = Client::new(connection_with_invalid_token(env.get_connection_info().origin)) + .unwrap() .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) .await; @@ -313,6 +325,7 @@ async fn should_not_allow_removing_a_torrent_from_the_whitelist_for_unauthentica let request_id = Uuid::new_v4(); let response = Client::new(connection_with_no_token(env.get_connection_info().origin)) + .unwrap() .remove_torrent_from_whitelist(&hash, Some(headers_with_request_id(request_id))) .await; @@ -334,6 +347,7 @@ async fn should_allow_reload_the_whitelist_from_the_database() { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); + env.container .tracker_core_container .whitelist_manager @@ -344,6 +358,7 @@ async fn should_allow_reload_the_whitelist_from_the_database() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .reload_whitelist(Some(headers_with_request_id(request_id))) .await; @@ -382,6 +397,7 @@ async fn should_fail_when_the_whitelist_cannot_be_reloaded_from_the_database() { let request_id = Uuid::new_v4(); let response = Client::new(env.get_connection_info()) + .unwrap() .reload_whitelist(Some(headers_with_request_id(request_id))) .await; diff --git a/packages/rest-tracker-api-client/src/v1/client.rs b/packages/rest-tracker-api-client/src/v1/client.rs index 54daa3289..65e3fceb8 100644 --- a/packages/rest-tracker-api-client/src/v1/client.rs +++ b/packages/rest-tracker-api-client/src/v1/client.rs @@ -1,5 +1,7 @@ +use std::time::Duration; + use hyper::HeaderMap; -use reqwest::Response; +use reqwest::{Error, Response}; use serde::Serialize; use url::Url; use uuid::Uuid; @@ -7,19 +9,31 @@ use uuid::Uuid; use crate::common::http::{Query, QueryParam, ReqwestQuery}; use crate::connection_info::ConnectionInfo; +const TOKEN_PARAM_NAME: &str = "token"; +const API_PATH: &str = "api/v1/"; +const DEFAULT_REQUEST_TIMEOUT_IN_SECS: u64 = 5; + /// API Client pub struct Client { connection_info: ConnectionInfo, base_path: String, + client: reqwest::Client, } impl Client { - #[must_use] - pub fn new(connection_info: ConnectionInfo) -> Self { - Self { + /// # Errors + /// + /// Will return an error if the HTTP client can't be created. + pub fn new(connection_info: ConnectionInfo) -> Result { + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(DEFAULT_REQUEST_TIMEOUT_IN_SECS)) + .build()?; + + Ok(Self { connection_info, - base_path: "api/v1/".to_string(), - } + base_path: API_PATH.to_string(), + client, + }) } pub async fn generate_auth_key(&self, seconds_valid: i32, headers: Option) -> Response { @@ -66,7 +80,7 @@ impl Client { let mut query: Query = params; if let Some(token) = &self.connection_info.api_token { - query.add_param(QueryParam::new("token", token)); + query.add_param(QueryParam::new(TOKEN_PARAM_NAME, token)); } self.get_request_with_query(path, query, headers).await @@ -76,7 +90,8 @@ impl Client { /// /// Will panic if the request can't be sent pub async fn post_empty(&self, path: &str, headers: Option) -> Response { - let builder = reqwest::Client::new() + let builder = self + .client .post(self.base_url(path).clone()) .query(&ReqwestQuery::from(self.query_with_token())); @@ -92,7 +107,8 @@ impl Client { /// /// Will panic if the request can't be sent pub async fn post_form(&self, path: &str, form: &T, headers: Option) -> Response { - let builder = reqwest::Client::new() + let builder = self + .client .post(self.base_url(path).clone()) .query(&ReqwestQuery::from(self.query_with_token())) .json(&form); @@ -109,7 +125,8 @@ impl Client { /// /// Will panic if the request can't be sent async fn delete(&self, path: &str, headers: Option) -> Response { - let builder = reqwest::Client::new() + let builder = self + .client .delete(self.base_url(path).clone()) .query(&ReqwestQuery::from(self.query_with_token())); @@ -145,7 +162,10 @@ impl Client { /// /// Will panic if the request can't be sent pub async fn get(path: Url, query: Option, headers: Option) -> Response { - let builder = reqwest::Client::builder().build().unwrap(); + let builder = reqwest::Client::builder() + .timeout(Duration::from_secs(DEFAULT_REQUEST_TIMEOUT_IN_SECS)) + .build() + .unwrap(); let builder = match query { Some(params) => builder.get(path).query(&ReqwestQuery::from(params)), From 9cda8ec21206572454b8615d8ad052636be678b8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 28 Feb 2025 11:17:39 +0000 Subject: [PATCH 0838/1297] refactor: [#1326] extract bittorrent_http_tracker_core::services::announce::AnnounceService --- .../axum-http-tracker-server/src/server.rs | 10 + .../src/v1/handlers/announce.rs | 169 +++--------- .../axum-http-tracker-server/src/v1/routes.rs | 16 +- packages/http-tracker-core/src/container.rs | 11 + .../src/services/announce.rs | 246 ++++++++++-------- src/container.rs | 30 ++- 6 files changed, 220 insertions(+), 262 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 4cf5afc13..6cdf28446 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -239,6 +239,7 @@ mod tests { use std::sync::Arc; use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; + use bittorrent_http_tracker_core::services::announce::AnnounceService; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service; @@ -293,6 +294,14 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + let announce_service = Arc::new(AnnounceService::new( + core_config.clone(), + announce_handler.clone(), + authentication_service.clone(), + whitelist_authorization.clone(), + http_stats_event_sender.clone(), + )); + HttpTrackerCoreContainer { core_config, announce_handler, @@ -303,6 +312,7 @@ mod tests { http_tracker_config, http_stats_event_sender, http_stats_repository, + announce_service, } } diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 0221f8dad..6c2e4b713 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -6,16 +6,12 @@ use std::sync::Arc; use axum::extract::State; use axum::response::{IntoResponse, Response}; -use bittorrent_http_tracker_core::services::announce::HttpAnnounceError; +use bittorrent_http_tracker_core::services::announce::{AnnounceService, HttpAnnounceError}; use bittorrent_http_tracker_protocol::v1::requests::announce::{Announce, Compact}; use bittorrent_http_tracker_protocol::v1::responses::{self}; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; -use bittorrent_tracker_core::announce_handler::AnnounceHandler; -use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::Key; -use bittorrent_tracker_core::whitelist; use hyper::StatusCode; -use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; use crate::v1::extractors::announce_request::ExtractRequest; @@ -25,91 +21,41 @@ use crate::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; /// It handles the `announce` request when the HTTP tracker does not require /// authentication (no PATH `key` parameter required). #[allow(clippy::unused_async)] -#[allow(clippy::type_complexity)] pub async fn handle_without_key( - State(state): State<( - Arc, - Arc, - Arc, - Arc, - Arc>>, - )>, + State(state): State>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { tracing::debug!("http announce request: {:#?}", announce_request); - handle( - &state.0, - &state.1, - &state.2, - &state.3, - &state.4, - &announce_request, - &client_ip_sources, - None, - ) - .await + handle(&state, &announce_request, &client_ip_sources, None).await } /// It handles the `announce` request when the HTTP tracker requires /// authentication (PATH `key` parameter required). #[allow(clippy::unused_async)] -#[allow(clippy::type_complexity)] pub async fn handle_with_key( - State(state): State<( - Arc, - Arc, - Arc, - Arc, - Arc>>, - )>, + State(state): State>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { tracing::debug!("http announce request: {:#?}", announce_request); - handle( - &state.0, - &state.1, - &state.2, - &state.3, - &state.4, - &announce_request, - &client_ip_sources, - Some(key), - ) - .await + handle(&state, &announce_request, &client_ip_sources, Some(key)).await } /// It handles the `announce` request. /// /// Internal implementation that handles both the `authenticated` and /// `unauthenticated` modes. -#[allow(clippy::too_many_arguments)] async fn handle( - config: &Arc, - announce_handler: &Arc, - authentication_service: &Arc, - whitelist_authorization: &Arc, - opt_http_stats_event_sender: &Arc>>, + announce_service: &Arc, announce_request: &Announce, client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Response { - let announce_data = match handle_announce( - config, - announce_handler, - authentication_service, - whitelist_authorization, - opt_http_stats_event_sender, - announce_request, - client_ip_sources, - maybe_key, - ) - .await - { + let announce_data = match handle_announce(announce_service, announce_request, client_ip_sources, maybe_key).await { Ok(announce_data) => announce_data, Err(error) => { let error_response = responses::error::Error { @@ -121,28 +67,15 @@ async fn handle( build_response(announce_request, announce_data) } -#[allow(clippy::too_many_arguments)] async fn handle_announce( - core_config: &Arc, - announce_handler: &Arc, - authentication_service: &Arc, - whitelist_authorization: &Arc, - opt_http_stats_event_sender: &Arc>>, + announce_service: &Arc, announce_request: &Announce, client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Result { - bittorrent_http_tracker_core::services::announce::handle_announce( - &core_config.clone(), - &announce_handler.clone(), - &authentication_service.clone(), - &whitelist_authorization.clone(), - &opt_http_stats_event_sender.clone(), - announce_request, - client_ip_sources, - maybe_key, - ) - .await + announce_service + .handle_announce(announce_request, client_ip_sources, maybe_key) + .await } fn build_response(announce_request: &Announce, announce_data: AnnounceData) -> Response { @@ -163,6 +96,7 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::PeerId; + use bittorrent_http_tracker_core::services::announce::AnnounceService; use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -174,39 +108,32 @@ mod tests { use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; - use torrust_tracker_configuration::{Configuration, Core}; + use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; use crate::tests::helpers::sample_info_hash; - struct CoreTrackerServices { - pub core_config: Arc, - pub announce_handler: Arc, - pub whitelist_authorization: Arc, - pub authentication_service: Arc, - } - struct CoreHttpTrackerServices { - pub http_stats_event_sender: Arc>>, + pub announce_service: Arc, } - fn initialize_private_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) { + fn initialize_private_tracker() -> CoreHttpTrackerServices { initialize_core_tracker_services(&configuration::ephemeral_private()) } - fn initialize_listed_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) { + fn initialize_listed_tracker() -> CoreHttpTrackerServices { initialize_core_tracker_services(&configuration::ephemeral_listed()) } - fn initialize_tracker_on_reverse_proxy() -> (CoreTrackerServices, CoreHttpTrackerServices) { + fn initialize_tracker_on_reverse_proxy() -> CoreHttpTrackerServices { initialize_core_tracker_services(&configuration::ephemeral_with_reverse_proxy()) } - fn initialize_tracker_not_on_reverse_proxy() -> (CoreTrackerServices, CoreHttpTrackerServices) { + fn initialize_tracker_not_on_reverse_proxy() -> CoreHttpTrackerServices { initialize_core_tracker_services(&configuration::ephemeral_without_reverse_proxy()) } - fn initialize_core_tracker_services(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) { + fn initialize_core_tracker_services(config: &Configuration) -> CoreHttpTrackerServices { let core_config = Arc::new(config.core.clone()); let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -228,15 +155,15 @@ mod tests { let http_stats_event_sender = Arc::new(http_stats_event_sender); let _http_stats_repository = Arc::new(http_stats_repository); - ( - CoreTrackerServices { - core_config, - announce_handler, - whitelist_authorization, - authentication_service, - }, - CoreHttpTrackerServices { http_stats_event_sender }, - ) + let announce_service = Arc::new(AnnounceService::new( + core_config.clone(), + announce_handler.clone(), + authentication_service.clone(), + whitelist_authorization.clone(), + http_stats_event_sender.clone(), + )); + + CoreHttpTrackerServices { announce_service } } fn sample_announce_request() -> Announce { @@ -280,16 +207,12 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_missing() { - let (core_tracker_services, http_core_tracker_services) = initialize_private_tracker(); + let http_core_tracker_services = initialize_private_tracker(); let maybe_key = None; let response = handle_announce( - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.authentication_service, - &core_tracker_services.whitelist_authorization, - &http_core_tracker_services.http_stats_event_sender, + &http_core_tracker_services.announce_service, &sample_announce_request(), &sample_client_ip_sources(), maybe_key, @@ -309,18 +232,14 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_authentication_key_is_invalid() { - let (core_tracker_services, http_core_tracker_services) = initialize_private_tracker(); + let http_core_tracker_services = initialize_private_tracker(); let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); let maybe_key = Some(unregistered_key); let response = handle_announce( - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.authentication_service, - &core_tracker_services.whitelist_authorization, - &http_core_tracker_services.http_stats_event_sender, + &http_core_tracker_services.announce_service, &sample_announce_request(), &sample_client_ip_sources(), maybe_key, @@ -349,16 +268,12 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_announced_torrent_is_not_whitelisted() { - let (core_tracker_services, http_core_tracker_services) = initialize_listed_tracker(); + let http_core_tracker_services = initialize_listed_tracker(); let announce_request = sample_announce_request(); let response = handle_announce( - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.authentication_service, - &core_tracker_services.whitelist_authorization, - &http_core_tracker_services.http_stats_event_sender, + &http_core_tracker_services.announce_service, &announce_request, &sample_client_ip_sources(), None, @@ -391,7 +306,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() { - let (core_tracker_services, http_core_tracker_services) = initialize_tracker_on_reverse_proxy(); + let http_core_tracker_services = initialize_tracker_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -399,11 +314,7 @@ mod tests { }; let response = handle_announce( - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.authentication_service, - &core_tracker_services.whitelist_authorization, - &http_core_tracker_services.http_stats_event_sender, + &http_core_tracker_services.announce_service, &sample_announce_request(), &client_ip_sources, None, @@ -433,7 +344,7 @@ mod tests { #[tokio::test] async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() { - let (core_tracker_services, http_core_tracker_services) = initialize_tracker_not_on_reverse_proxy(); + let http_core_tracker_services = initialize_tracker_not_on_reverse_proxy(); let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, @@ -441,11 +352,7 @@ mod tests { }; let response = handle_announce( - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.authentication_service, - &core_tracker_services.whitelist_authorization, - &http_core_tracker_services.http_stats_event_sender, + &http_core_tracker_services.announce_service, &sample_announce_request(), &client_ip_sources, None, diff --git a/packages/axum-http-tracker-server/src/v1/routes.rs b/packages/axum-http-tracker-server/src/v1/routes.rs index 7a96f6014..6c4005ff5 100644 --- a/packages/axum-http-tracker-server/src/v1/routes.rs +++ b/packages/axum-http-tracker-server/src/v1/routes.rs @@ -38,23 +38,11 @@ pub fn router(http_tracker_container: Arc, server_sock // Announce request .route( "/announce", - get(announce::handle_without_key).with_state(( - http_tracker_container.core_config.clone(), - http_tracker_container.announce_handler.clone(), - http_tracker_container.authentication_service.clone(), - http_tracker_container.whitelist_authorization.clone(), - http_tracker_container.http_stats_event_sender.clone(), - )), + get(announce::handle_without_key).with_state(http_tracker_container.announce_service.clone()), ) .route( "/announce/{key}", - get(announce::handle_with_key).with_state(( - http_tracker_container.core_config.clone(), - http_tracker_container.announce_handler.clone(), - http_tracker_container.authentication_service.clone(), - http_tracker_container.whitelist_authorization.clone(), - http_tracker_container.http_stats_event_sender.clone(), - )), + get(announce::handle_with_key).with_state(http_tracker_container.announce_service.clone()), ) // Scrape request .route( diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 0fc313a38..27a24b813 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -7,6 +7,7 @@ use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::{Core, HttpTracker}; +use crate::services::announce::AnnounceService; use crate::statistics; pub struct HttpTrackerCoreContainer { @@ -20,6 +21,7 @@ pub struct HttpTrackerCoreContainer { pub http_tracker_config: Arc, pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, + pub announce_service: Arc, } impl HttpTrackerCoreContainer { @@ -39,6 +41,14 @@ impl HttpTrackerCoreContainer { let http_stats_event_sender = Arc::new(http_stats_event_sender); let http_stats_repository = Arc::new(http_stats_repository); + let announce_service = Arc::new(AnnounceService::new( + tracker_core_container.core_config.clone(), + tracker_core_container.announce_handler.clone(), + tracker_core_container.authentication_service.clone(), + tracker_core_container.whitelist_authorization.clone(), + http_stats_event_sender.clone(), + )); + Arc::new(Self { core_config: tracker_core_container.core_config.clone(), announce_handler: tracker_core_container.announce_handler.clone(), @@ -49,6 +59,7 @@ impl HttpTrackerCoreContainer { http_tracker_config: http_tracker_config.clone(), http_stats_event_sender: http_stats_event_sender.clone(), http_stats_repository: http_stats_repository.clone(), + announce_service: announce_service.clone(), }) } } diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 2f530c654..5890d35c1 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -83,81 +83,105 @@ impl From for HttpAnnounceError { /// > **NOTICE**: as the HTTP tracker does not requires a connection request /// > like the UDP tracker, the number of TCP connections is incremented for /// > each `announce` request. -/// -/// # Errors -/// -/// This function will return an error if: -/// -/// - The tracker is running in `listed` mode and the torrent is not whitelisted. -/// - There is an error when resolving the client IP address. -#[allow(clippy::too_many_arguments)] -pub async fn handle_announce( - core_config: &Arc, - announce_handler: &Arc, - authentication_service: &Arc, - whitelist_authorization: &Arc, - opt_http_stats_event_sender: &Arc>>, - announce_request: &Announce, - client_ip_sources: &ClientIpSources, - maybe_key: Option, -) -> Result { - // Authentication - if core_config.private { - match maybe_key { - Some(key) => match authentication_service.authenticate(&key).await { - Ok(()) => (), - Err(error) => return Err(error.into()), - }, - None => { - return Err(authentication::key::Error::MissingAuthKey { - location: Location::caller(), +pub struct AnnounceService { + core_config: Arc, + announce_handler: Arc, + authentication_service: Arc, + whitelist_authorization: Arc, + opt_http_stats_event_sender: Arc>>, +} + +impl AnnounceService { + #[must_use] + pub fn new( + core_config: Arc, + announce_handler: Arc, + authentication_service: Arc, + whitelist_authorization: Arc, + opt_http_stats_event_sender: Arc>>, + ) -> Self { + Self { + core_config, + announce_handler, + authentication_service, + whitelist_authorization, + opt_http_stats_event_sender, + } + } + + /// Handles an announce request. + /// + /// # Errors + /// + /// This function will return an error if: + /// + /// - The tracker is running in `listed` mode and the torrent is not whitelisted. + /// - There is an error when resolving the client IP address. + pub async fn handle_announce( + &self, + announce_request: &Announce, + client_ip_sources: &ClientIpSources, + maybe_key: Option, + ) -> Result { + // Authentication + if self.core_config.private { + match maybe_key { + Some(key) => match self.authentication_service.authenticate(&key).await { + Ok(()) => (), + Err(error) => return Err(error.into()), + }, + None => { + return Err(authentication::key::Error::MissingAuthKey { + location: Location::caller(), + } + .into()) } - .into()) } } - } - // Authorization - match whitelist_authorization.authorize(&announce_request.info_hash).await { - Ok(()) => (), - Err(error) => return Err(error.into()), - } + // Authorization + match self.whitelist_authorization.authorize(&announce_request.info_hash).await { + Ok(()) => (), + Err(error) => return Err(error.into()), + } - let peer_ip = match peer_ip_resolver::invoke(core_config.net.on_reverse_proxy, client_ip_sources) { - Ok(peer_ip) => peer_ip, - Err(error) => return Err(error.into()), - }; + let peer_ip = match peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources) { + Ok(peer_ip) => peer_ip, + Err(error) => return Err(error.into()), + }; - let mut peer = peer_from_request(announce_request, &peer_ip); + let mut peer = peer_from_request(announce_request, &peer_ip); - let peers_wanted = match announce_request.numwant { - Some(numwant) => PeersWanted::only(numwant), - None => PeersWanted::AsManyAsPossible, - }; + let peers_wanted = match announce_request.numwant { + Some(numwant) => PeersWanted::only(numwant), + None => PeersWanted::AsManyAsPossible, + }; - let original_peer_ip = peer.peer_addr.ip(); + let original_peer_ip = peer.peer_addr.ip(); - // The tracker could change the original peer ip - let announce_data = announce_handler - .announce(&announce_request.info_hash, &mut peer, &original_peer_ip, &peers_wanted) - .await?; + // The tracker could change the original peer ip + let announce_data = self + .announce_handler + .announce(&announce_request.info_hash, &mut peer, &original_peer_ip, &peers_wanted) + .await?; - if let Some(http_stats_event_sender) = opt_http_stats_event_sender.as_deref() { - match original_peer_ip { - IpAddr::V4(_) => { - http_stats_event_sender - .send_event(statistics::event::Event::Tcp4Announce) - .await; - } - IpAddr::V6(_) => { - http_stats_event_sender - .send_event(statistics::event::Event::Tcp6Announce) - .await; + if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { + match original_peer_ip { + IpAddr::V4(_) => { + http_stats_event_sender + .send_event(statistics::event::Event::Tcp4Announce) + .await; + } + IpAddr::V6(_) => { + http_stats_event_sender + .send_event(statistics::event::Event::Tcp6Announce) + .await; + } } } - } - Ok(announce_data) + Ok(announce_data) + } } #[cfg(test)] @@ -302,11 +326,11 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; - use crate::services::announce::handle_announce; use crate::services::announce::tests::{ initialize_core_tracker_services, initialize_core_tracker_services_with_config, sample_announce_request_for_peer, sample_peer, MockHttpStatsEventSender, }; + use crate::services::announce::AnnounceService; use crate::statistics; #[tokio::test] @@ -317,18 +341,18 @@ mod tests { let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); - let announce_data = handle_announce( - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.authentication_service, - &core_tracker_services.whitelist_authorization, - &core_http_tracker_services.http_stats_event_sender, - &announce_request, - &client_ip_sources, - None, - ) - .await - .unwrap(); + let announce_service = AnnounceService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_tracker_services.whitelist_authorization.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let announce_data = announce_service + .handle_announce(&announce_request, &client_ip_sources, None) + .await + .unwrap(); let expected_announce_data = AnnounceData { peers: vec![], @@ -361,18 +385,18 @@ mod tests { let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); - let _announce_data = handle_announce( - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.authentication_service, - &core_tracker_services.whitelist_authorization, - &core_http_tracker_services.http_stats_event_sender, - &announce_request, - &client_ip_sources, - None, - ) - .await - .unwrap(); + let announce_service = AnnounceService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_tracker_services.whitelist_authorization.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let _announce_data = announce_service + .handle_announce(&announce_request, &client_ip_sources, None) + .await + .unwrap(); } fn tracker_with_an_ipv6_external_ip() -> Configuration { @@ -413,18 +437,18 @@ mod tests { let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); - let _announce_data = handle_announce( - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.authentication_service, - &core_tracker_services.whitelist_authorization, - &core_http_tracker_services.http_stats_event_sender, - &announce_request, - &client_ip_sources, - None, - ) - .await - .unwrap(); + let announce_service = AnnounceService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_tracker_services.whitelist_authorization.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let _announce_data = announce_service + .handle_announce(&announce_request, &client_ip_sources, None) + .await + .unwrap(); } #[tokio::test] @@ -446,18 +470,18 @@ mod tests { let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); - let _announce_data = handle_announce( - &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.authentication_service, - &core_tracker_services.whitelist_authorization, - &core_http_tracker_services.http_stats_event_sender, - &announce_request, - &client_ip_sources, - None, - ) - .await - .unwrap(); + let announce_service = AnnounceService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_tracker_services.whitelist_authorization.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let _announce_data = announce_service + .handle_announce(&announce_request, &client_ip_sources, None) + .await + .unwrap(); } } } diff --git a/src/container.rs b/src/container.rs index 4bdae1b29..fba03bf2c 100644 --- a/src/container.rs +++ b/src/container.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; +use bittorrent_http_tracker_core::services::announce::AnnounceService; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::handler::KeysHandler; use bittorrent_tracker_core::authentication::service::AuthenticationService; @@ -45,6 +46,7 @@ pub struct AppContainer { // HTTP Tracker Core Services pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, + pub http_announce_service: Arc, // UDP Tracker Server Services pub udp_server_stats_event_sender: Arc>>, @@ -58,13 +60,20 @@ impl AppContainer { let tracker_core_container = TrackerCoreContainer::initialize(&core_config); - // HTTP core stats + // HTTP Tracker Core Services let (http_stats_event_sender, http_stats_repository) = bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); let http_stats_repository = Arc::new(http_stats_repository); - - // UDP core stats + let http_announce_service = Arc::new(AnnounceService::new( + tracker_core_container.core_config.clone(), + tracker_core_container.announce_handler.clone(), + tracker_core_container.authentication_service.clone(), + tracker_core_container.whitelist_authorization.clone(), + http_stats_event_sender.clone(), + )); + + // UDP Tracker Core Services let (udp_core_stats_event_sender, udp_core_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); @@ -72,13 +81,14 @@ impl AppContainer { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - // UDP server stats + // UDP Tracker Server Services let (udp_server_stats_event_sender, udp_server_stats_repository) = torrust_udp_tracker_server::statistics::setup::factory(configuration.core.tracker_usage_statistics); let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); let udp_server_stats_repository = Arc::new(udp_server_stats_repository); AppContainer { + // Tracker Core Services core_config, database: tracker_core_container.database, announce_handler: tracker_core_container.announce_handler, @@ -91,11 +101,18 @@ impl AppContainer { in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository, db_torrent_repository: tracker_core_container.db_torrent_repository, torrents_manager: tracker_core_container.torrents_manager, + + // UDP Tracker Core Services ban_service, - http_stats_event_sender, udp_core_stats_event_sender, - http_stats_repository, udp_core_stats_repository, + + // HTTP Tracker Core Services + http_stats_event_sender, + http_stats_repository, + http_announce_service, + + // UDP Tracker Server Services udp_server_stats_event_sender, udp_server_stats_repository, } @@ -113,6 +130,7 @@ impl AppContainer { http_tracker_config: http_tracker_config.clone(), http_stats_event_sender: self.http_stats_event_sender.clone(), http_stats_repository: self.http_stats_repository.clone(), + announce_service: self.http_announce_service.clone(), } } From 8ec45ad63b400c423cdec4eee0582c94ce941441 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 28 Feb 2025 12:00:59 +0000 Subject: [PATCH 0839/1297] refactor: [#1326] extract bittorrent_http_tracker_core::services::scrape::ScrapeService --- .../axum-http-tracker-server/src/server.rs | 10 +- .../src/v1/handlers/scrape.rs | 202 ++++++------------ .../axum-http-tracker-server/src/v1/routes.rs | 14 +- packages/http-tracker-core/src/container.rs | 10 + .../http-tracker-core/src/services/scrape.rs | 160 ++++++++------ src/container.rs | 10 + 6 files changed, 191 insertions(+), 215 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 6cdf28446..15eef3c38 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -238,8 +238,8 @@ pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { mod tests { use std::sync::Arc; - use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_http_tracker_core::services::announce::AnnounceService; + use bittorrent_http_tracker_core::{container::HttpTrackerCoreContainer, services::scrape::ScrapeService}; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service; @@ -302,6 +302,13 @@ mod tests { http_stats_event_sender.clone(), )); + let scrape_service = Arc::new(ScrapeService::new( + core_config.clone(), + scrape_handler.clone(), + authentication_service.clone(), + http_stats_event_sender.clone(), + )); + HttpTrackerCoreContainer { core_config, announce_handler, @@ -313,6 +320,7 @@ mod tests { http_stats_event_sender, http_stats_repository, announce_service, + scrape_service, } } diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index 00046a618..ae3a35bd3 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -6,15 +6,12 @@ use std::sync::Arc; use axum::extract::State; use axum::response::{IntoResponse, Response}; -use bittorrent_http_tracker_core::services::scrape::HttpScrapeError; +use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; -use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::Key; -use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use hyper::StatusCode; -use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; use crate::v1::extractors::authentication_key::Extract as ExtractKey; @@ -24,29 +21,14 @@ use crate::v1::extractors::scrape_request::ExtractRequest; /// It handles the `scrape` request when the HTTP tracker is configured /// to run in `public` mode. #[allow(clippy::unused_async)] -#[allow(clippy::type_complexity)] pub async fn handle_without_key( - State(state): State<( - Arc, - Arc, - Arc, - Arc>>, - )>, + State(state): State>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { tracing::debug!("http scrape request: {:#?}", &scrape_request); - handle( - &state.0, - &state.1, - &state.2, - &state.3, - &scrape_request, - &client_ip_sources, - None, - ) - .await + handle(&state, &scrape_request, &client_ip_sources, None).await } /// It handles the `scrape` request when the HTTP tracker is configured @@ -54,52 +36,26 @@ pub async fn handle_without_key( /// /// In this case, the authentication `key` parameter is required. #[allow(clippy::unused_async)] -#[allow(clippy::type_complexity)] pub async fn handle_with_key( - State(state): State<( - Arc, - Arc, - Arc, - Arc>>, - )>, + State(state): State>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { tracing::debug!("http scrape request: {:#?}", &scrape_request); - handle( - &state.0, - &state.1, - &state.2, - &state.3, - &scrape_request, - &client_ip_sources, - Some(key), - ) - .await + handle(&state, &scrape_request, &client_ip_sources, Some(key)).await } -#[allow(clippy::too_many_arguments)] async fn handle( - core_config: &Arc, - scrape_handler: &Arc, - authentication_service: &Arc, - http_stats_event_sender: &Arc>>, + scrape_service: &Arc, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Response { - let scrape_data = match handle_scrape( - core_config, - scrape_handler, - authentication_service, - http_stats_event_sender, - scrape_request, - client_ip_sources, - maybe_key, - ) - .await + let scrape_data = match scrape_service + .handle_scrape(scrape_request, client_ip_sources, maybe_key) + .await { Ok(scrape_data) => scrape_data, Err(error) => { @@ -113,28 +69,6 @@ async fn handle( build_response(scrape_data) } -#[allow(clippy::too_many_arguments)] -async fn handle_scrape( - core_config: &Arc, - scrape_handler: &Arc, - authentication_service: &Arc, - opt_http_stats_event_sender: &Arc>>, - scrape_request: &Scrape, - client_ip_sources: &ClientIpSources, - maybe_key: Option, -) -> Result { - bittorrent_http_tracker_core::services::scrape::handle_scrape( - core_config, - scrape_handler, - authentication_service, - opt_http_stats_event_sender, - scrape_request, - client_ip_sources, - maybe_key, - ) - .await -} - fn build_response(scrape_data: ScrapeData) -> Response { let response = responses::scrape::Bencoded::from(scrape_data); @@ -233,11 +167,11 @@ mod tests { mod with_tracker_in_private_mode { use std::str::FromStr; + use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_tracker_core::authentication; use torrust_tracker_primitives::core::ScrapeData; use super::{initialize_private_tracker, sample_client_ip_sources, sample_scrape_request}; - use crate::v1::handlers::scrape::handle_scrape; #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { @@ -246,17 +180,17 @@ mod tests { let scrape_request = sample_scrape_request(); let maybe_key = None; - let scrape_data = handle_scrape( - &core_tracker_services.core_config, - &core_tracker_services.scrape_handler, - &core_tracker_services.authentication_service, - &core_http_tracker_services.http_stats_event_sender, - &scrape_request, - &sample_client_ip_sources(), - maybe_key, - ) - .await - .unwrap(); + let scrape_service = ScrapeService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.scrape_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let scrape_data = scrape_service + .handle_scrape(&scrape_request, &sample_client_ip_sources(), maybe_key) + .await + .unwrap(); let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes); @@ -271,17 +205,17 @@ mod tests { let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); let maybe_key = Some(unregistered_key); - let scrape_data = handle_scrape( - &core_tracker_services.core_config, - &core_tracker_services.scrape_handler, - &core_tracker_services.authentication_service, - &core_http_tracker_services.http_stats_event_sender, - &scrape_request, - &sample_client_ip_sources(), - maybe_key, - ) - .await - .unwrap(); + let scrape_service = ScrapeService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.scrape_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let scrape_data = scrape_service + .handle_scrape(&scrape_request, &sample_client_ip_sources(), maybe_key) + .await + .unwrap(); let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes); @@ -291,10 +225,10 @@ mod tests { mod with_tracker_in_listed_mode { + use bittorrent_http_tracker_core::services::scrape::ScrapeService; use torrust_tracker_primitives::core::ScrapeData; use super::{initialize_listed_tracker, sample_client_ip_sources, sample_scrape_request}; - use crate::v1::handlers::scrape::handle_scrape; #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() { @@ -302,17 +236,17 @@ mod tests { let scrape_request = sample_scrape_request(); - let scrape_data = handle_scrape( - &core_tracker_services.core_config, - &core_tracker_services.scrape_handler, - &core_tracker_services.authentication_service, - &core_http_tracker_services.http_stats_event_sender, - &scrape_request, - &sample_client_ip_sources(), - None, - ) - .await - .unwrap(); + let scrape_service = ScrapeService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.scrape_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let scrape_data = scrape_service + .handle_scrape(&scrape_request, &sample_client_ip_sources(), None) + .await + .unwrap(); let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes); @@ -322,11 +256,11 @@ mod tests { mod with_tracker_on_reverse_proxy { + use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use super::{initialize_tracker_on_reverse_proxy, sample_scrape_request}; - use crate::v1::handlers::scrape::handle_scrape; use crate::v1::handlers::scrape::tests::assert_error_response; #[tokio::test] @@ -338,17 +272,17 @@ mod tests { connection_info_ip: None, }; - let response = handle_scrape( - &core_tracker_services.core_config, - &core_tracker_services.scrape_handler, - &core_tracker_services.authentication_service, - &core_http_tracker_services.http_stats_event_sender, - &sample_scrape_request(), - &client_ip_sources, - None, - ) - .await - .unwrap_err(); + let scrape_service = ScrapeService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.scrape_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let response = scrape_service + .handle_scrape(&sample_scrape_request(), &client_ip_sources, None) + .await + .unwrap_err(); let error_response = responses::error::Error { failure_reason: response.to_string(), @@ -363,11 +297,11 @@ mod tests { mod with_tracker_not_on_reverse_proxy { + use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use super::{initialize_tracker_not_on_reverse_proxy, sample_scrape_request}; - use crate::v1::handlers::scrape::handle_scrape; use crate::v1::handlers::scrape::tests::assert_error_response; #[tokio::test] @@ -379,17 +313,17 @@ mod tests { connection_info_ip: None, }; - let response = handle_scrape( - &core_tracker_services.core_config, - &core_tracker_services.scrape_handler, - &core_tracker_services.authentication_service, - &core_http_tracker_services.http_stats_event_sender, - &sample_scrape_request(), - &client_ip_sources, - None, - ) - .await - .unwrap_err(); + let scrape_service = ScrapeService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.scrape_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let response = scrape_service + .handle_scrape(&sample_scrape_request(), &client_ip_sources, None) + .await + .unwrap_err(); let error_response = responses::error::Error { failure_reason: response.to_string(), diff --git a/packages/axum-http-tracker-server/src/v1/routes.rs b/packages/axum-http-tracker-server/src/v1/routes.rs index 6c4005ff5..5f666e9d4 100644 --- a/packages/axum-http-tracker-server/src/v1/routes.rs +++ b/packages/axum-http-tracker-server/src/v1/routes.rs @@ -47,21 +47,11 @@ pub fn router(http_tracker_container: Arc, server_sock // Scrape request .route( "/scrape", - get(scrape::handle_without_key).with_state(( - http_tracker_container.core_config.clone(), - http_tracker_container.scrape_handler.clone(), - http_tracker_container.authentication_service.clone(), - http_tracker_container.http_stats_event_sender.clone(), - )), + get(scrape::handle_without_key).with_state(http_tracker_container.scrape_service.clone()), ) .route( "/scrape/{key}", - get(scrape::handle_with_key).with_state(( - http_tracker_container.core_config.clone(), - http_tracker_container.scrape_handler.clone(), - http_tracker_container.authentication_service.clone(), - http_tracker_container.http_stats_event_sender.clone(), - )), + get(scrape::handle_with_key).with_state(http_tracker_container.scrape_service.clone()), ) // Add extension to get the client IP from the connection info .layer(SecureClientIpSource::ConnectInfo.into_extension()) diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 27a24b813..448dce246 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -8,6 +8,7 @@ use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::{Core, HttpTracker}; use crate::services::announce::AnnounceService; +use crate::services::scrape::ScrapeService; use crate::statistics; pub struct HttpTrackerCoreContainer { @@ -22,6 +23,7 @@ pub struct HttpTrackerCoreContainer { pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, pub announce_service: Arc, + pub scrape_service: Arc, } impl HttpTrackerCoreContainer { @@ -49,6 +51,13 @@ impl HttpTrackerCoreContainer { http_stats_event_sender.clone(), )); + let scrape_service = Arc::new(ScrapeService::new( + tracker_core_container.core_config.clone(), + tracker_core_container.scrape_handler.clone(), + tracker_core_container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + Arc::new(Self { core_config: tracker_core_container.core_config.clone(), announce_handler: tracker_core_container.announce_handler.clone(), @@ -60,6 +69,7 @@ impl HttpTrackerCoreContainer { http_stats_event_sender: http_stats_event_sender.clone(), http_stats_repository: http_stats_repository.clone(), announce_service: announce_service.clone(), + scrape_service: scrape_service.clone(), }) } } diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 394f285ee..48cee7c8c 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -71,7 +71,6 @@ impl From for HttpScrapeError { } } } - /// The HTTP tracker `scrape` service. /// /// The service sends an statistics event that increments: @@ -88,46 +87,71 @@ impl From for HttpScrapeError { /// This function will return an error if: /// /// - There is an error when resolving the client IP address. -#[allow(clippy::too_many_arguments)] -pub async fn handle_scrape( - core_config: &Arc, - scrape_handler: &Arc, - authentication_service: &Arc, - opt_http_stats_event_sender: &Arc>>, - scrape_request: &Scrape, - client_ip_sources: &ClientIpSources, - maybe_key: Option, -) -> Result { - // Authentication - let return_fake_scrape_data = if core_config.private { - match maybe_key { - Some(key) => match authentication_service.authenticate(&key).await { - Ok(()) => false, - Err(_error) => true, - }, - None => true, +pub struct ScrapeService { + core_config: Arc, + scrape_handler: Arc, + authentication_service: Arc, + opt_http_stats_event_sender: Arc>>, +} + +impl ScrapeService { + #[must_use] + pub fn new( + core_config: Arc, + scrape_handler: Arc, + authentication_service: Arc, + opt_http_stats_event_sender: Arc>>, + ) -> Self { + Self { + core_config, + scrape_handler, + authentication_service, + opt_http_stats_event_sender, } - } else { - false - }; + } - // Authorization for scrape requests is handled at the `bittorrent_tracker_core` - // level for each torrent. + /// # Errors + /// + /// This function will return an error if: + /// + /// - There is an error when resolving the client IP address. + pub async fn handle_scrape( + &self, + scrape_request: &Scrape, + client_ip_sources: &ClientIpSources, + maybe_key: Option, + ) -> Result { + // Authentication + let return_fake_scrape_data = if self.core_config.private { + match maybe_key { + Some(key) => match self.authentication_service.authenticate(&key).await { + Ok(()) => false, + Err(_error) => true, + }, + None => true, + } + } else { + false + }; - let peer_ip = match peer_ip_resolver::invoke(core_config.net.on_reverse_proxy, client_ip_sources) { - Ok(peer_ip) => peer_ip, - Err(error) => return Err(error.into()), - }; + // Authorization for scrape requests is handled at the `bittorrent_tracker_core` + // level for each torrent. - if return_fake_scrape_data { - return Ok(fake(opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await); - } + let peer_ip = match peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources) { + Ok(peer_ip) => peer_ip, + Err(error) => return Err(error.into()), + }; + + if return_fake_scrape_data { + return Ok(fake(&self.opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await); + } - let scrape_data = scrape_handler.scrape(&scrape_request.info_hashes).await?; + let scrape_data = self.scrape_handler.scrape(&scrape_request.info_hashes).await?; - send_scrape_event(&peer_ip, opt_http_stats_event_sender).await; + send_scrape_event(&peer_ip, &self.opt_http_stats_event_sender).await; - Ok(scrape_data) + Ok(scrape_data) + } } /// The HTTP tracker fake `scrape` service. It returns zeroed stats. @@ -261,10 +285,10 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; - use crate::services::scrape::handle_scrape; use crate::services::scrape::tests::{ initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; + use crate::services::scrape::ScrapeService; use crate::statistics; use crate::tests::sample_info_hash; @@ -299,17 +323,17 @@ mod tests { connection_info_ip: Some(original_peer_ip), }; - let scrape_data = handle_scrape( - &core_config, - &container.scrape_handler, - &container.authentication_service, - &http_stats_event_sender, - &scrape_request, - &client_ip_sources, - None, - ) - .await - .unwrap(); + let scrape_service = Arc::new(ScrapeService::new( + core_config.clone(), + container.scrape_handler.clone(), + container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + let scrape_data = scrape_service + .handle_scrape(&scrape_request, &client_ip_sources, None) + .await + .unwrap(); let mut expected_scrape_data = ScrapeData::empty(); expected_scrape_data.add_file( @@ -350,17 +374,17 @@ mod tests { connection_info_ip: Some(peer_ip), }; - handle_scrape( - &Arc::new(config.core), - &container.scrape_handler, - &container.authentication_service, - &http_stats_event_sender, - &scrape_request, - &client_ip_sources, - None, - ) - .await - .unwrap(); + let scrape_service = Arc::new(ScrapeService::new( + Arc::new(config.core), + container.scrape_handler.clone(), + container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + scrape_service + .handle_scrape(&scrape_request, &client_ip_sources, None) + .await + .unwrap(); } #[tokio::test] @@ -389,17 +413,17 @@ mod tests { connection_info_ip: Some(peer_ip), }; - handle_scrape( - &Arc::new(config.core), - &container.scrape_handler, - &container.authentication_service, - &http_stats_event_sender, - &scrape_request, - &client_ip_sources, - None, - ) - .await - .unwrap(); + let scrape_service = Arc::new(ScrapeService::new( + Arc::new(config.core), + container.scrape_handler.clone(), + container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + scrape_service + .handle_scrape(&scrape_request, &client_ip_sources, None) + .await + .unwrap(); } } diff --git a/src/container.rs b/src/container.rs index fba03bf2c..c9e58bdc4 100644 --- a/src/container.rs +++ b/src/container.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_http_tracker_core::services::announce::AnnounceService; +use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::handler::KeysHandler; use bittorrent_tracker_core::authentication::service::AuthenticationService; @@ -47,6 +48,7 @@ pub struct AppContainer { pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, pub http_announce_service: Arc, + pub http_scrape_service: Arc, // UDP Tracker Server Services pub udp_server_stats_event_sender: Arc>>, @@ -72,6 +74,12 @@ impl AppContainer { tracker_core_container.whitelist_authorization.clone(), http_stats_event_sender.clone(), )); + let http_scrape_service = Arc::new(ScrapeService::new( + tracker_core_container.core_config.clone(), + tracker_core_container.scrape_handler.clone(), + tracker_core_container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); // UDP Tracker Core Services let (udp_core_stats_event_sender, udp_core_stats_repository) = @@ -111,6 +119,7 @@ impl AppContainer { http_stats_event_sender, http_stats_repository, http_announce_service, + http_scrape_service, // UDP Tracker Server Services udp_server_stats_event_sender, @@ -131,6 +140,7 @@ impl AppContainer { http_stats_event_sender: self.http_stats_event_sender.clone(), http_stats_repository: self.http_stats_repository.clone(), announce_service: self.http_announce_service.clone(), + scrape_service: self.http_scrape_service.clone(), } } From 47e159e7835e375411fbfdde7cf72b790e597270 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 28 Feb 2025 12:29:32 +0000 Subject: [PATCH 0840/1297] docs: remove deprecate comments --- packages/udp-tracker-core/src/services/announce.rs | 2 -- packages/udp-tracker-core/src/services/connect.rs | 2 -- packages/udp-tracker-core/src/services/scrape.rs | 2 -- 3 files changed, 6 deletions(-) diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index b40162283..ffd382a20 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -76,8 +76,6 @@ pub async fn handle_announce( opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { - // todo: return a UDP response like the HTTP tracker instead of raw AnnounceData. - // Authentication check( &request.connection_id, diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index 3354595e5..92c51799b 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -17,8 +17,6 @@ pub async fn handle_connect( opt_udp_stats_event_sender: &Arc>>, cookie_issue_time: f64, ) -> ConnectionId { - // todo: return a UDP response like the HTTP tracker instead of raw ConnectionId. - let connection_id = make(gen_remote_fingerprint(&remote_addr), cookie_issue_time).expect("it should be a normal value"); if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index bec55afe3..04fcb2fe6 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -68,8 +68,6 @@ pub async fn handle_scrape( opt_udp_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { - // todo: return a UDP response like the HTTP tracker instead of raw ScrapeData. - check( &request.connection_id, gen_remote_fingerprint(&remote_addr), From ddfbcd286152220b055151e73a3ea1d462d6005b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 28 Feb 2025 12:33:10 +0000 Subject: [PATCH 0841/1297] fix: [#1326] formatting --- packages/axum-http-tracker-server/src/server.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 15eef3c38..ea8003a4f 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -238,8 +238,9 @@ pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { mod tests { use std::sync::Arc; + use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_http_tracker_core::services::announce::AnnounceService; - use bittorrent_http_tracker_core::{container::HttpTrackerCoreContainer, services::scrape::ScrapeService}; + use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service; From e1d9aa4655356db5e15297ab92de30235fea2043 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 28 Feb 2025 15:48:07 +0000 Subject: [PATCH 0842/1297] refactor: [#1326] extract bittorrent_udp_tracker_core::services::connect::ConnectService --- .gitignore | 3 +- cSpell.json | 1 + packages/udp-tracker-core/src/container.rs | 5 +- .../udp-tracker-core/src/services/connect.rs | 93 +++++++++++++------ packages/udp-tracker-core/src/services/mod.rs | 4 +- .../src/handlers/connect.rs | 29 ++++-- .../udp-tracker-server/src/handlers/mod.rs | 2 +- src/container.rs | 10 +- 8 files changed, 101 insertions(+), 46 deletions(-) diff --git a/.gitignore b/.gitignore index d9087bcff..8bfa717b7 100644 --- a/.gitignore +++ b/.gitignore @@ -15,4 +15,5 @@ callgrind.out codecov.json lcov.info -perf.data* \ No newline at end of file +perf.data* +rustc-ice-*.txt diff --git a/cSpell.json b/cSpell.json index e067df932..dcdcc9cf6 100644 --- a/cSpell.json +++ b/cSpell.json @@ -136,6 +136,7 @@ "routable", "rstest", "rusqlite", + "rustc", "RUSTDOCFLAGS", "RUSTFLAGS", "rustfmt", diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index 1467134c5..f64149209 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -8,6 +8,7 @@ use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, UdpTracker}; use crate::services::banning::BanService; +use crate::services::connect::ConnectService; use crate::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; pub struct UdpTrackerCoreContainer { @@ -21,6 +22,7 @@ pub struct UdpTrackerCoreContainer { pub udp_core_stats_event_sender: Arc>>, pub udp_core_stats_repository: Arc, pub ban_service: Arc>, + pub connect_service: Arc, } impl UdpTrackerCoreContainer { @@ -39,8 +41,8 @@ impl UdpTrackerCoreContainer { statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); let udp_core_stats_repository = Arc::new(udp_core_stats_repository); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender.clone())); Arc::new(UdpTrackerCoreContainer { core_config: tracker_core_container.core_config.clone(), @@ -52,6 +54,7 @@ impl UdpTrackerCoreContainer { udp_core_stats_event_sender: udp_core_stats_event_sender.clone(), udp_core_stats_repository: udp_core_stats_repository.clone(), ban_service: ban_service.clone(), + connect_service: connect_service.clone(), }) } } diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index 92c51799b..14a3068e4 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -9,28 +9,43 @@ use aquatic_udp_protocol::ConnectionId; use crate::connection_cookie::{gen_remote_fingerprint, make}; use crate::statistics; -/// # Panics +/// The `ConnectService` is responsible for handling the `connect` requests. /// -/// IT will panic if there was an error making the connection cookie. -pub async fn handle_connect( - remote_addr: SocketAddr, - opt_udp_stats_event_sender: &Arc>>, - cookie_issue_time: f64, -) -> ConnectionId { - let connection_id = make(gen_remote_fingerprint(&remote_addr), cookie_issue_time).expect("it should be a normal value"); - - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { - match remote_addr { - SocketAddr::V4(_) => { - udp_stats_event_sender.send_event(statistics::event::Event::Udp4Connect).await; - } - SocketAddr::V6(_) => { - udp_stats_event_sender.send_event(statistics::event::Event::Udp6Connect).await; - } +/// It is responsible for generating the connection cookie and sending the +/// appropriate statistics events. +pub struct ConnectService { + pub opt_udp_core_stats_event_sender: Arc>>, +} + +impl ConnectService { + #[must_use] + pub fn new(opt_udp_core_stats_event_sender: Arc>>) -> Self { + Self { + opt_udp_core_stats_event_sender, } } - connection_id + /// Handles a `connect` request. + /// + /// # Panics + /// + /// It will panic if there was an error making the connection cookie. + pub async fn handle_connect(&self, remote_addr: SocketAddr, cookie_issue_time: f64) -> ConnectionId { + let connection_id = make(gen_remote_fingerprint(&remote_addr), cookie_issue_time).expect("it should be a normal value"); + + if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + udp_stats_event_sender.send_event(statistics::event::Event::Udp4Connect).await; + } + SocketAddr::V6(_) => { + udp_stats_event_sender.send_event(statistics::event::Event::Udp6Connect).await; + } + } + } + + connection_id + } } #[cfg(test)] @@ -44,10 +59,10 @@ mod tests { use mockall::predicate::eq; use crate::connection_cookie::make; - use crate::services::connect::handle_connect; + use crate::services::connect::ConnectService; use crate::services::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, - sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpStatsEventSender, + sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpCoreStatsEventSender, }; use crate::statistics; @@ -56,7 +71,11 @@ mod tests { let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); - let response = handle_connect(sample_ipv4_remote_addr(), &udp_core_stats_event_sender, sample_issue_time()).await; + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + + let response = connect_service + .handle_connect(sample_ipv4_remote_addr(), sample_issue_time()) + .await; assert_eq!( response, @@ -69,7 +88,11 @@ mod tests { let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); - let response = handle_connect(sample_ipv4_remote_addr(), &udp_core_stats_event_sender, sample_issue_time()).await; + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + + let response = connect_service + .handle_connect(sample_ipv4_remote_addr(), sample_issue_time()) + .await; assert_eq!( response, @@ -82,7 +105,11 @@ mod tests { let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); - let response = handle_connect(sample_ipv6_remote_addr(), &udp_core_stats_event_sender, sample_issue_time()).await; + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + + let response = connect_service + .handle_connect(sample_ipv6_remote_addr(), sample_issue_time()) + .await; assert_eq!( response, @@ -92,32 +119,40 @@ mod tests { #[tokio::test] async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Udp4Connect)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = + let opt_udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); let client_socket_address = sample_ipv4_socket_address(); - handle_connect(client_socket_address, &udp_stats_event_sender, sample_issue_time()).await; + let connect_service = Arc::new(ConnectService::new(opt_udp_stats_event_sender)); + + connect_service + .handle_connect(client_socket_address, sample_issue_time()) + .await; } #[tokio::test] async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { - let mut udp_stats_event_sender_mock = MockUdpStatsEventSender::new(); + let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::Udp6Connect)) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_stats_event_sender: Arc>> = + let opt_udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); - handle_connect(sample_ipv6_remote_addr(), &udp_stats_event_sender, sample_issue_time()).await; + let connect_service = Arc::new(ConnectService::new(opt_udp_stats_event_sender)); + + connect_service + .handle_connect(sample_ipv6_remote_addr(), sample_issue_time()) + .await; } } } diff --git a/packages/udp-tracker-core/src/services/mod.rs b/packages/udp-tracker-core/src/services/mod.rs index 0fcb612e4..6aa254f41 100644 --- a/packages/udp-tracker-core/src/services/mod.rs +++ b/packages/udp-tracker-core/src/services/mod.rs @@ -44,8 +44,8 @@ pub(crate) mod tests { } mock! { - pub(crate) UdpStatsEventSender {} - impl statistics::event::sender::Sender for UdpStatsEventSender { + pub(crate) UdpCoreStatsEventSender {} + impl statistics::event::sender::Sender for UdpCoreStatsEventSender { fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index be6dc45d4..93d3bb6f1 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -3,18 +3,18 @@ use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, ConnectionId, Response}; -use bittorrent_udp_tracker_core::{services, statistics as core_statistics}; +use bittorrent_udp_tracker_core::services::connect::ConnectService; use tracing::{instrument, Level}; use crate::statistics as server_statistics; use crate::statistics::event::UdpResponseKind; /// It handles the `Connect` request. -#[instrument(fields(transaction_id), skip(opt_udp_core_stats_event_sender, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id), skip(connect_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_connect( remote_addr: SocketAddr, request: &ConnectRequest, - opt_udp_core_stats_event_sender: &Arc>>, + connect_service: &Arc, opt_udp_server_stats_event_sender: &Arc>>, cookie_issue_time: f64, ) -> Response { @@ -40,7 +40,7 @@ pub async fn handle_connect( } } - let connection_id = services::connect::handle_connect(remote_addr, opt_udp_core_stats_event_sender, cookie_issue_time).await; + let connection_id = connect_service.handle_connect(remote_addr, cookie_issue_time).await; build_response(*request, connection_id) } @@ -64,6 +64,7 @@ mod tests { use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; use bittorrent_udp_tracker_core::connection_cookie::make; + use bittorrent_udp_tracker_core::services::connect::ConnectService; use bittorrent_udp_tracker_core::statistics as core_statistics; use mockall::predicate::eq; @@ -94,10 +95,12 @@ mod tests { transaction_id: TransactionId(0i32.into()), }; + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + let response = handle_connect( sample_ipv4_remote_addr(), &request, - &udp_core_stats_event_sender, + &connect_service, &udp_server_stats_event_sender, sample_issue_time(), ) @@ -125,10 +128,12 @@ mod tests { transaction_id: TransactionId(0i32.into()), }; + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + let response = handle_connect( sample_ipv4_remote_addr(), &request, - &udp_core_stats_event_sender, + &connect_service, &udp_server_stats_event_sender, sample_issue_time(), ) @@ -156,10 +161,12 @@ mod tests { transaction_id: TransactionId(0i32.into()), }; + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + let response = handle_connect( sample_ipv6_remote_addr(), &request, - &udp_core_stats_event_sender, + &connect_service, &udp_server_stats_event_sender, sample_issue_time(), ) @@ -198,10 +205,12 @@ mod tests { let client_socket_address = sample_ipv4_socket_address(); + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + handle_connect( client_socket_address, &sample_connect_request(), - &udp_core_stats_event_sender, + &connect_service, &udp_server_stats_event_sender, sample_issue_time(), ) @@ -230,10 +239,12 @@ mod tests { let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + handle_connect( sample_ipv6_remote_addr(), &sample_connect_request(), - &udp_core_stats_event_sender, + &connect_service, &udp_server_stats_event_sender, sample_issue_time(), ) diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index fd0536b8b..eedf45e7d 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -147,7 +147,7 @@ pub async fn handle_request( Request::Connect(connect_request) => Ok(handle_connect( remote_addr, &connect_request, - &udp_tracker_core_container.udp_core_stats_event_sender, + &udp_tracker_core_container.connect_service, &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.issue_time, ) diff --git a/src/container.rs b/src/container.rs index c9e58bdc4..a53217c7c 100644 --- a/src/container.rs +++ b/src/container.rs @@ -17,6 +17,7 @@ use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::banning::BanService; +use bittorrent_udp_tracker_core::services::connect::ConnectService; use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; @@ -40,9 +41,10 @@ pub struct AppContainer { pub torrents_manager: Arc, // UDP Tracker Core Services - pub ban_service: Arc>, pub udp_core_stats_event_sender: Arc>>, pub udp_core_stats_repository: Arc, + pub ban_service: Arc>, + pub connect_service: Arc, // HTTP Tracker Core Services pub http_stats_event_sender: Arc>>, @@ -86,8 +88,8 @@ impl AppContainer { bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); let udp_core_stats_repository = Arc::new(udp_core_stats_repository); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender.clone())); // UDP Tracker Server Services let (udp_server_stats_event_sender, udp_server_stats_repository) = @@ -111,9 +113,10 @@ impl AppContainer { torrents_manager: tracker_core_container.torrents_manager, // UDP Tracker Core Services - ban_service, udp_core_stats_event_sender, udp_core_stats_repository, + ban_service, + connect_service, // HTTP Tracker Core Services http_stats_event_sender, @@ -156,6 +159,7 @@ impl AppContainer { udp_core_stats_event_sender: self.udp_core_stats_event_sender.clone(), udp_core_stats_repository: self.udp_core_stats_repository.clone(), ban_service: self.ban_service.clone(), + connect_service: self.connect_service.clone(), } } From 67d62efb12bc3154a1748916988e61cbb3c64dd5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 28 Feb 2025 17:02:02 +0000 Subject: [PATCH 0843/1297] refactor: [#1326] extract bittorrent_udp_tracker_core::services::announce::AnnounceService --- packages/udp-tracker-core/src/container.rs | 8 + .../udp-tracker-core/src/services/announce.rs | 158 ++++++++---------- .../src/handlers/announce.rs | 138 +++++---------- .../udp-tracker-server/src/handlers/mod.rs | 13 +- src/container.rs | 13 +- 5 files changed, 145 insertions(+), 185 deletions(-) diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index f64149209..e09505d64 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -7,6 +7,7 @@ use bittorrent_tracker_core::whitelist; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, UdpTracker}; +use crate::services::announce::AnnounceService; use crate::services::banning::BanService; use crate::services::connect::ConnectService; use crate::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; @@ -23,6 +24,7 @@ pub struct UdpTrackerCoreContainer { pub udp_core_stats_repository: Arc, pub ban_service: Arc>, pub connect_service: Arc, + pub announce_service: Arc, } impl UdpTrackerCoreContainer { @@ -43,6 +45,11 @@ impl UdpTrackerCoreContainer { let udp_core_stats_repository = Arc::new(udp_core_stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender.clone())); + let announce_service = Arc::new(AnnounceService::new( + tracker_core_container.announce_handler.clone(), + tracker_core_container.whitelist_authorization.clone(), + udp_core_stats_event_sender.clone(), + )); Arc::new(UdpTrackerCoreContainer { core_config: tracker_core_container.core_config.clone(), @@ -55,6 +62,7 @@ impl UdpTrackerCoreContainer { udp_core_stats_repository: udp_core_stats_repository.clone(), ban_service: ban_service.clone(), connect_service: connect_service.clone(), + announce_service: announce_service.clone(), }) } } diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index ffd382a20..051944d7e 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -12,13 +12,11 @@ use std::ops::Range; use std::sync::Arc; use aquatic_udp_protocol::AnnounceRequest; -use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::error::{AnnounceError, WhitelistError}; use bittorrent_tracker_core::whitelist; use bittorrent_udp_tracker_protocol::peer_builder; use torrust_tracker_primitives::core::AnnounceData; -use torrust_tracker_primitives::peer; use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; use crate::statistics; @@ -59,95 +57,81 @@ impl From for UdpAnnounceError { } } -/// It handles the `Announce` request. -/// -/// # Errors -/// -/// It will return an error if: -/// -/// - The tracker is running in listed mode and the torrent is not in the -/// whitelist. -#[allow(clippy::too_many_arguments)] -pub async fn handle_announce( - remote_addr: SocketAddr, - request: &AnnounceRequest, - announce_handler: &Arc, - whitelist_authorization: &Arc, - opt_udp_stats_event_sender: &Arc>>, - cookie_valid_range: Range, -) -> Result { - // Authentication - check( - &request.connection_id, - gen_remote_fingerprint(&remote_addr), - cookie_valid_range, - )?; - - let info_hash = request.info_hash.into(); - let remote_client_ip = remote_addr.ip(); - - // Authorization - whitelist_authorization.authorize(&info_hash).await?; - - let mut peer = peer_builder::from_request(request, &remote_client_ip); - let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); - - let original_peer_ip = peer.peer_addr.ip(); - - // The tracker could change the original peer ip - let announce_data = announce_handler - .announce(&info_hash, &mut peer, &original_peer_ip, &peers_wanted) - .await?; - - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { - match original_peer_ip { - IpAddr::V4(_) => { - udp_stats_event_sender - .send_event(statistics::event::Event::Udp4Announce) - .await; - } - IpAddr::V6(_) => { - udp_stats_event_sender - .send_event(statistics::event::Event::Udp6Announce) - .await; - } +/// The `AnnounceService` is responsible for handling the `announce` requests. +pub struct AnnounceService { + pub announce_handler: Arc, + pub whitelist_authorization: Arc, + pub opt_udp_core_stats_event_sender: Arc>>, +} + +impl AnnounceService { + #[must_use] + pub fn new( + announce_handler: Arc, + whitelist_authorization: Arc, + opt_udp_core_stats_event_sender: Arc>>, + ) -> Self { + Self { + announce_handler, + whitelist_authorization, + opt_udp_core_stats_event_sender, } } - Ok(announce_data) -} - -/// # Errors -/// -/// It will return an error if the announce request fails. -pub async fn invoke( - announce_handler: Arc, - opt_udp_stats_event_sender: Arc>>, - info_hash: InfoHash, - peer: &mut peer::Peer, - peers_wanted: &PeersWanted, -) -> Result { - let original_peer_ip = peer.peer_addr.ip(); - - // The tracker could change the original peer ip - let announce_data = announce_handler - .announce(&info_hash, peer, &original_peer_ip, peers_wanted) - .await?; - - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { - match original_peer_ip { - IpAddr::V4(_) => { - udp_stats_event_sender - .send_event(statistics::event::Event::Udp4Announce) - .await; - } - IpAddr::V6(_) => { - udp_stats_event_sender - .send_event(statistics::event::Event::Udp6Announce) - .await; + /// It handles the `Announce` request. + /// + /// # Errors + /// + /// It will return an error if: + /// + /// - The tracker is running in listed mode and the torrent is not in the + /// whitelist. + #[allow(clippy::too_many_arguments)] + pub async fn handle_announce( + &self, + remote_addr: SocketAddr, + request: &AnnounceRequest, + cookie_valid_range: Range, + ) -> Result { + // Authentication + check( + &request.connection_id, + gen_remote_fingerprint(&remote_addr), + cookie_valid_range, + )?; + + let info_hash = request.info_hash.into(); + let remote_client_ip = remote_addr.ip(); + + // Authorization + self.whitelist_authorization.authorize(&info_hash).await?; + + let mut peer = peer_builder::from_request(request, &remote_client_ip); + let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); + + let original_peer_ip = peer.peer_addr.ip(); + + // The tracker could change the original peer ip + let announce_data = self + .announce_handler + .announce(&info_hash, &mut peer, &original_peer_ip, &peers_wanted) + .await?; + + if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { + match original_peer_ip { + IpAddr::V4(_) => { + udp_stats_event_sender + .send_event(statistics::event::Event::Udp4Announce) + .await; + } + IpAddr::V6(_) => { + udp_stats_event_sender + .send_event(statistics::event::Event::Udp6Announce) + .await; + } } } - } - Ok(announce_data) + Ok(announce_data) + } } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 97ce6ba4a..9269dadfe 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -8,9 +8,7 @@ use aquatic_udp_protocol::{ Port, Response, ResponsePeer, TransactionId, }; use bittorrent_primitives::info_hash::InfoHash; -use bittorrent_tracker_core::announce_handler::AnnounceHandler; -use bittorrent_tracker_core::whitelist; -use bittorrent_udp_tracker_core::{services, statistics as core_statistics}; +use bittorrent_udp_tracker_core::services::announce::AnnounceService; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; use tracing::{instrument, Level}; @@ -25,15 +23,12 @@ use crate::statistics::event::UdpResponseKind; /// # Errors /// /// If a error happens in the `handle_announce` function, it will just return the `ServerError`. -#[allow(clippy::too_many_arguments)] -#[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_handler, whitelist_authorization, opt_udp_core_stats_event_sender, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_announce( + announce_service: &Arc, remote_addr: SocketAddr, request: &AnnounceRequest, core_config: &Arc, - announce_handler: &Arc, - whitelist_authorization: &Arc, - opt_udp_core_stats_event_sender: &Arc>>, opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { @@ -63,16 +58,10 @@ pub async fn handle_announce( } } - let announce_data = services::announce::handle_announce( - remote_addr, - request, - announce_handler, - whitelist_authorization, - opt_udp_core_stats_event_sender, - cookie_valid_range, - ) - .await - .map_err(|e| (e.into(), request.transaction_id))?; + let announce_data = announce_service + .handle_announce(remote_addr, request, cookie_valid_range) + .await + .map_err(|e| (e.into(), request.transaction_id))?; Ok(build_response(remote_addr, request, core_config, &announce_data)) } @@ -223,20 +212,17 @@ mod tests { AnnounceInterval, AnnounceResponse, AnnounceResponseFixedData, InfoHash as AquaticInfoHash, Ipv4AddrBytes, Ipv6AddrBytes, NumberOfPeers, PeerId as AquaticPeerId, Response, ResponsePeer, }; - use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::whitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; - use bittorrent_udp_tracker_core::statistics as core_statistics; use mockall::predicate::eq; - use torrust_tracker_configuration::Core; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::handlers::handle_announce; use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, - sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, TorrentPeerBuilder, + sample_issue_time, CoreTrackerServices, CoreUdpTrackerServices, MockUdpServerStatsEventSender, + TorrentPeerBuilder, }; use crate::statistics as server_statistics; use crate::statistics::event::UdpResponseKind; @@ -262,12 +248,10 @@ mod tests { .into(); handle_announce( + &core_udp_tracker_services.announce_service, remote_addr, &request, &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_core_stats_event_sender, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -299,12 +283,10 @@ mod tests { .into(); let response = handle_announce( + &core_udp_tracker_services.announce_service, remote_addr, &request, &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_core_stats_event_sender, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -354,12 +336,10 @@ mod tests { .into(); handle_announce( + &core_udp_tracker_services.announce_service, remote_addr, &request, &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_core_stats_event_sender, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -390,13 +370,12 @@ mod tests { } async fn announce_a_new_peer_using_ipv4( - core_config: Arc, - announce_handler: Arc, - whitelist_authorization: Arc, + core_tracker_services: Arc, + core_udp_tracker_services: Arc, ) -> Response { let (udp_core_stats_event_sender, _udp_core_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let _udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); @@ -407,12 +386,10 @@ mod tests { .into(); handle_announce( + &core_udp_tracker_services.announce_service, remote_addr, &request, - &core_config, - &announce_handler, - &whitelist_authorization, - &udp_core_stats_event_sender, + &core_tracker_services.core_config, &udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -422,17 +399,13 @@ mod tests { #[tokio::test] async fn when_the_announce_request_comes_from_a_client_using_ipv4_the_response_should_not_include_peers_using_ipv6() { - let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = + let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); add_a_torrent_peer_using_ipv6(&core_tracker_services.in_memory_torrent_repository); - let response = announce_a_new_peer_using_ipv4( - core_tracker_services.core_config.clone(), - core_tracker_services.announce_handler.clone(), - core_tracker_services.whitelist_authorization, - ) - .await; + let response = + announce_a_new_peer_using_ipv4(Arc::new(core_tracker_services), Arc::new(core_udp_tracker_services)).await; // The response should not contain the peer using IPV6 let peers: Option>> = match response { @@ -445,15 +418,6 @@ mod tests { #[tokio::test] async fn should_send_the_upd4_announce_event() { - let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); - udp_core_stats_event_sender_mock - .expect_send_event() - .with(eq(core_statistics::event::Event::Udp4Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_core_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); - let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() @@ -465,16 +429,14 @@ mod tests { let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); - let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = + let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); handle_announce( + &core_udp_tracker_services.announce_service, sample_ipv4_socket_address(), &AnnounceRequestBuilder::default().into(), &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &udp_core_stats_event_sender, &udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -517,12 +479,10 @@ mod tests { .into(); handle_announce( + &core_udp_tracker_services.announce_service, remote_addr, &request, &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_core_stats_event_sender, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -560,7 +520,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; - use bittorrent_udp_tracker_core::statistics as core_statistics; + use bittorrent_udp_tracker_core::services::announce::AnnounceService; use mockall::predicate::eq; use torrust_tracker_configuration::Core; @@ -569,7 +529,7 @@ mod tests { use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, - sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, TorrentPeerBuilder, + sample_issue_time, MockUdpServerStatsEventSender, TorrentPeerBuilder, }; use crate::statistics as server_statistics; use crate::statistics::event::UdpResponseKind; @@ -596,12 +556,10 @@ mod tests { .into(); handle_announce( + &core_udp_tracker_services.announce_service, remote_addr, &request, &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_core_stats_event_sender, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -636,12 +594,10 @@ mod tests { .into(); let response = handle_announce( + &core_udp_tracker_services.announce_service, remote_addr, &request, &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_core_stats_event_sender, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -691,12 +647,10 @@ mod tests { .into(); handle_announce( + &core_udp_tracker_services.announce_service, remote_addr, &request, &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &core_udp_tracker_services.udp_core_stats_event_sender, &server_udp_tracker_service.udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -746,13 +700,17 @@ mod tests { .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) .into(); + let announce_service = Arc::new(AnnounceService::new( + announce_handler.clone(), + whitelist_authorization.clone(), + udp_core_stats_event_sender.clone(), + )); + handle_announce( + &announce_service, remote_addr, &request, &core_config, - &announce_handler, - &whitelist_authorization, - &udp_core_stats_event_sender, &udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -785,15 +743,6 @@ mod tests { #[tokio::test] async fn should_send_the_upd6_announce_event() { - let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); - udp_core_stats_event_sender_mock - .expect_send_event() - .with(eq(core_statistics::event::Event::Udp6Announce)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_core_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); - let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() @@ -805,7 +754,7 @@ mod tests { let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); - let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = + let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); let remote_addr = sample_ipv6_remote_addr(); @@ -815,12 +764,10 @@ mod tests { .into(); handle_announce( + &core_udp_tracker_services.announce_service, remote_addr, &announce_request, &core_tracker_services.core_config, - &core_tracker_services.announce_handler, - &core_tracker_services.whitelist_authorization, - &udp_core_stats_event_sender, &udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -841,6 +788,7 @@ mod tests { use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use bittorrent_udp_tracker_core::services::announce::AnnounceService; use bittorrent_udp_tracker_core::{self, statistics as core_statistics}; use mockall::predicate::eq; @@ -913,13 +861,17 @@ mod tests { let core_config = Arc::new(config.core.clone()); + let announce_service = Arc::new(AnnounceService::new( + announce_handler.clone(), + whitelist_authorization.clone(), + udp_core_stats_event_sender.clone(), + )); + handle_announce( + &announce_service, remote_addr, &request, &core_config, - &announce_handler, - &whitelist_authorization, - &udp_core_stats_event_sender, &udp_server_stats_event_sender, sample_cookie_valid_range(), ) diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index eedf45e7d..333bf91fe 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -154,12 +154,10 @@ pub async fn handle_request( .await), Request::Announce(announce_request) => { handle_announce( + &udp_tracker_core_container.announce_service, remote_addr, &announce_request, &udp_tracker_core_container.core_config, - &udp_tracker_core_container.announce_handler, - &udp_tracker_core_container.whitelist_authorization, - &udp_tracker_core_container.udp_core_stats_event_sender, &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range, ) @@ -196,6 +194,7 @@ pub(crate) mod tests { use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::gen_remote_fingerprint; + use bittorrent_udp_tracker_core::services::announce::AnnounceService; use bittorrent_udp_tracker_core::{self, statistics as core_statistics}; use futures::future::BoxFuture; use mockall::mock; @@ -218,6 +217,7 @@ pub(crate) mod tests { pub(crate) struct CoreUdpTrackerServices { pub udp_core_stats_event_sender: Arc>>, + pub announce_service: Arc, } pub(crate) struct ServerUdpTrackerServices { @@ -267,6 +267,12 @@ pub(crate) mod tests { let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); + let announce_service = Arc::new(AnnounceService::new( + announce_handler.clone(), + whitelist_authorization.clone(), + udp_core_stats_event_sender.clone(), + )); + ( CoreTrackerServices { core_config, @@ -278,6 +284,7 @@ pub(crate) mod tests { }, CoreUdpTrackerServices { udp_core_stats_event_sender, + announce_service, }, ServerUdpTrackerServices { udp_server_stats_event_sender, diff --git a/src/container.rs b/src/container.rs index a53217c7c..3ef9b6f5b 100644 --- a/src/container.rs +++ b/src/container.rs @@ -17,7 +17,6 @@ use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::banning::BanService; -use bittorrent_udp_tracker_core::services::connect::ConnectService; use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; @@ -45,6 +44,7 @@ pub struct AppContainer { pub udp_core_stats_repository: Arc, pub ban_service: Arc>, pub connect_service: Arc, + pub announce_service: Arc, // HTTP Tracker Core Services pub http_stats_event_sender: Arc>>, @@ -89,7 +89,14 @@ impl AppContainer { let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); let udp_core_stats_repository = Arc::new(udp_core_stats_repository); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender.clone())); + let connect_service = Arc::new(bittorrent_udp_tracker_core::services::connect::ConnectService::new( + udp_core_stats_event_sender.clone(), + )); + let announce_service = Arc::new(bittorrent_udp_tracker_core::services::announce::AnnounceService::new( + tracker_core_container.announce_handler.clone(), + tracker_core_container.whitelist_authorization.clone(), + udp_core_stats_event_sender.clone(), + )); // UDP Tracker Server Services let (udp_server_stats_event_sender, udp_server_stats_repository) = @@ -117,6 +124,7 @@ impl AppContainer { udp_core_stats_repository, ban_service, connect_service, + announce_service, // HTTP Tracker Core Services http_stats_event_sender, @@ -160,6 +168,7 @@ impl AppContainer { udp_core_stats_repository: self.udp_core_stats_repository.clone(), ban_service: self.ban_service.clone(), connect_service: self.connect_service.clone(), + announce_service: self.announce_service.clone(), } } From 6a8386660f82278ed9945634a80d3c44508f3c4a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 28 Feb 2025 17:24:01 +0000 Subject: [PATCH 0844/1297] refactor: [1326] extract bittorrent_udp_tracker_core::services::scrape::ScrapeService --- packages/udp-tracker-core/src/container.rs | 7 ++ .../udp-tracker-core/src/services/scrape.rs | 77 +++++++++------ .../udp-tracker-server/src/handlers/mod.rs | 15 +-- .../udp-tracker-server/src/handlers/scrape.rs | 96 ++++++------------- src/container.rs | 7 ++ 5 files changed, 101 insertions(+), 101 deletions(-) diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index e09505d64..c4cce3dc1 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -10,6 +10,7 @@ use torrust_tracker_configuration::{Core, UdpTracker}; use crate::services::announce::AnnounceService; use crate::services::banning::BanService; use crate::services::connect::ConnectService; +use crate::services::scrape::ScrapeService; use crate::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; pub struct UdpTrackerCoreContainer { @@ -25,6 +26,7 @@ pub struct UdpTrackerCoreContainer { pub ban_service: Arc>, pub connect_service: Arc, pub announce_service: Arc, + pub scrape_service: Arc, } impl UdpTrackerCoreContainer { @@ -50,6 +52,10 @@ impl UdpTrackerCoreContainer { tracker_core_container.whitelist_authorization.clone(), udp_core_stats_event_sender.clone(), )); + let scrape_service = Arc::new(ScrapeService::new( + tracker_core_container.scrape_handler.clone(), + udp_core_stats_event_sender.clone(), + )); Arc::new(UdpTrackerCoreContainer { core_config: tracker_core_container.core_config.clone(), @@ -63,6 +69,7 @@ impl UdpTrackerCoreContainer { ban_service: ban_service.clone(), connect_service: connect_service.clone(), announce_service: announce_service.clone(), + scrape_service: scrape_service.clone(), }) } } diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index 04fcb2fe6..fddc2ec2d 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -56,39 +56,58 @@ impl From for UdpScrapeError { } } -/// It handles the `Scrape` request. -/// -/// # Errors -/// -/// It will return an error if the tracker core scrape handler returns an error. -pub async fn handle_scrape( - remote_addr: SocketAddr, - request: &ScrapeRequest, - scrape_handler: &Arc, - opt_udp_stats_event_sender: &Arc>>, - cookie_valid_range: Range, -) -> Result { - check( - &request.connection_id, - gen_remote_fingerprint(&remote_addr), - cookie_valid_range, - )?; +/// The `ScrapeService` is responsible for handling the `scrape` requests. +pub struct ScrapeService { + scrape_handler: Arc, + opt_udp_stats_event_sender: Arc>>, +} - // Convert from aquatic infohashes - let info_hashes: Vec = request.info_hashes.iter().map(|&x| x.into()).collect(); +impl ScrapeService { + /// Creates a new `ScrapeService`. + #[must_use] + pub fn new( + scrape_handler: Arc, + opt_udp_stats_event_sender: Arc>>, + ) -> Self { + Self { + scrape_handler, + opt_udp_stats_event_sender, + } + } - let scrape_data = scrape_handler.scrape(&info_hashes).await?; + /// It handles the `Scrape` request. + /// + /// # Errors + /// + /// It will return an error if the tracker core scrape handler returns an error. + pub async fn handle_scrape( + &self, + remote_addr: SocketAddr, + request: &ScrapeRequest, + cookie_valid_range: Range, + ) -> Result { + check( + &request.connection_id, + gen_remote_fingerprint(&remote_addr), + cookie_valid_range, + )?; - if let Some(udp_stats_event_sender) = opt_udp_stats_event_sender.as_deref() { - match remote_addr { - SocketAddr::V4(_) => { - udp_stats_event_sender.send_event(statistics::event::Event::Udp4Scrape).await; - } - SocketAddr::V6(_) => { - udp_stats_event_sender.send_event(statistics::event::Event::Udp6Scrape).await; + // Convert from aquatic infohashes + let info_hashes: Vec = request.info_hashes.iter().map(|&x| x.into()).collect(); + + let scrape_data = self.scrape_handler.scrape(&info_hashes).await?; + + if let Some(udp_stats_event_sender) = self.opt_udp_stats_event_sender.as_deref() { + match remote_addr { + SocketAddr::V4(_) => { + udp_stats_event_sender.send_event(statistics::event::Event::Udp4Scrape).await; + } + SocketAddr::V6(_) => { + udp_stats_event_sender.send_event(statistics::event::Event::Udp6Scrape).await; + } } } - } - Ok(scrape_data) + Ok(scrape_data) + } } diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 333bf91fe..165b307e0 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -165,10 +165,9 @@ pub async fn handle_request( } Request::Scrape(scrape_request) => { handle_scrape( + &udp_tracker_core_container.scrape_service, remote_addr, &scrape_request, - &udp_tracker_core_container.scrape_handler, - &udp_tracker_core_container.udp_core_stats_event_sender, &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range, ) @@ -195,6 +194,7 @@ pub(crate) mod tests { use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::gen_remote_fingerprint; use bittorrent_udp_tracker_core::services::announce::AnnounceService; + use bittorrent_udp_tracker_core::services::scrape::ScrapeService; use bittorrent_udp_tracker_core::{self, statistics as core_statistics}; use futures::future::BoxFuture; use mockall::mock; @@ -209,15 +209,14 @@ pub(crate) mod tests { pub(crate) struct CoreTrackerServices { pub core_config: Arc, pub announce_handler: Arc, - pub scrape_handler: Arc, pub in_memory_torrent_repository: Arc, pub in_memory_whitelist: Arc, pub whitelist_authorization: Arc, } pub(crate) struct CoreUdpTrackerServices { - pub udp_core_stats_event_sender: Arc>>, pub announce_service: Arc, + pub scrape_service: Arc, } pub(crate) struct ServerUdpTrackerServices { @@ -273,18 +272,22 @@ pub(crate) mod tests { udp_core_stats_event_sender.clone(), )); + let scrape_service = Arc::new(ScrapeService::new( + scrape_handler.clone(), + udp_core_stats_event_sender.clone(), + )); + ( CoreTrackerServices { core_config, announce_handler, - scrape_handler, in_memory_torrent_repository, in_memory_whitelist, whitelist_authorization, }, CoreUdpTrackerServices { - udp_core_stats_event_sender, announce_service, + scrape_service, }, ServerUdpTrackerServices { udp_server_stats_event_sender, diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 248f0ca12..3e6da4778 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -6,8 +6,8 @@ use std::sync::Arc; use aquatic_udp_protocol::{ NumberOfDownloads, NumberOfPeers, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; -use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_udp_tracker_core::{self, services, statistics as core_statistics}; +use bittorrent_udp_tracker_core::services::scrape::ScrapeService; +use bittorrent_udp_tracker_core::{self}; use torrust_tracker_primitives::core::ScrapeData; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; @@ -21,12 +21,11 @@ use crate::statistics::event::UdpResponseKind; /// # Errors /// /// This function does not ever return an error. -#[instrument(fields(transaction_id, connection_id), skip(scrape_handler, opt_udp_core_stats_event_sender, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] +#[instrument(fields(transaction_id, connection_id), skip(scrape_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_scrape( + scrape_service: &Arc, remote_addr: SocketAddr, request: &ScrapeRequest, - scrape_handler: &Arc, - opt_udp_core_stats_event_sender: &Arc>>, opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { @@ -55,15 +54,10 @@ pub async fn handle_scrape( } } - let scrape_data = services::scrape::handle_scrape( - remote_addr, - request, - scrape_handler, - opt_udp_core_stats_event_sender, - cookie_valid_range, - ) - .await - .map_err(|e| (e.into(), request.transaction_id))?; + let scrape_data = scrape_service + .handle_scrape(remote_addr, request, cookie_valid_range) + .await + .map_err(|e| (e.into(), request.transaction_id))?; Ok(build_response(request, &scrape_data)) } @@ -105,14 +99,13 @@ mod tests { InfoHash, NumberOfDownloads, NumberOfPeers, PeerId, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; - use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use crate::handlers::handle_scrape; use crate::handlers::tests::{ initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, - sample_issue_time, TorrentPeerBuilder, + sample_issue_time, CoreTrackerServices, CoreUdpTrackerServices, TorrentPeerBuilder, }; fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { @@ -125,7 +118,7 @@ mod tests { #[tokio::test] async fn should_return_no_stats_when_the_tracker_does_not_have_any_torrent() { - let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = + let (_core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); let remote_addr = sample_ipv4_remote_addr(); @@ -140,10 +133,9 @@ mod tests { }; let response = handle_scrape( + &core_udp_tracker_services.scrape_service, remote_addr, &request, - &core_tracker_services.scrape_handler, - &core_udp_tracker_services.udp_core_stats_event_sender, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -188,28 +180,28 @@ mod tests { } async fn add_a_sample_seeder_and_scrape( - in_memory_torrent_repository: Arc, - scrape_handler: Arc, + core_tracker_services: Arc, + core_udp_tracker_services: Arc, ) -> Response { - let (udp_core_stats_event_sender, _udp_core_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); - let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); let remote_addr = sample_ipv4_remote_addr(); let info_hash = InfoHash([0u8; 20]); - add_a_seeder(in_memory_torrent_repository.clone(), &remote_addr, &info_hash).await; + add_a_seeder( + core_tracker_services.in_memory_torrent_repository.clone(), + &remote_addr, + &info_hash, + ) + .await; let request = build_scrape_request(&remote_addr, &info_hash); handle_scrape( + &core_udp_tracker_services.scrape_service, remote_addr, &request, - &scrape_handler, - &udp_core_stats_event_sender, &udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -232,15 +224,11 @@ mod tests { #[tokio::test] async fn should_return_torrent_statistics_when_the_tracker_has_the_requested_torrent() { - let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = + let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); let torrent_stats = match_scrape_response( - add_a_sample_seeder_and_scrape( - core_tracker_services.in_memory_torrent_repository.clone(), - core_tracker_services.scrape_handler.clone(), - ) - .await, + add_a_sample_seeder_and_scrape(core_tracker_services.into(), core_udp_tracker_services.into()).await, ); let expected_torrent_stats = vec![TorrentScrapeStatistics { @@ -285,10 +273,9 @@ mod tests { let torrent_stats = match_scrape_response( handle_scrape( + &core_udp_tracker_services.scrape_service, remote_addr, &request, - &core_tracker_services.scrape_handler, - &core_udp_tracker_services.udp_core_stats_event_sender, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -325,10 +312,9 @@ mod tests { let torrent_stats = match_scrape_response( handle_scrape( + &core_udp_tracker_services.scrape_service, remote_addr, &request, - &core_tracker_services.scrape_handler, - &core_udp_tracker_services.udp_core_stats_event_sender, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -358,28 +344,18 @@ mod tests { use std::future; use std::sync::Arc; - use bittorrent_udp_tracker_core::statistics as core_statistics; use mockall::predicate::eq; use super::sample_scrape_request; use crate::handlers::handle_scrape; use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, - sample_ipv4_remote_addr, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, + sample_ipv4_remote_addr, MockUdpServerStatsEventSender, }; use crate::statistics as server_statistics; #[tokio::test] async fn should_send_the_upd4_scrape_event() { - let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); - udp_core_stats_event_sender_mock - .expect_send_event() - .with(eq(core_statistics::event::Event::Udp4Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_core_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); - let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() @@ -393,14 +369,13 @@ mod tests { let remote_addr = sample_ipv4_remote_addr(); - let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = + let (_core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); handle_scrape( + &core_udp_tracker_services.scrape_service, remote_addr, &sample_scrape_request(&remote_addr), - &core_tracker_services.scrape_handler, - &udp_core_stats_event_sender, &udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -413,28 +388,18 @@ mod tests { use std::future; use std::sync::Arc; - use bittorrent_udp_tracker_core::statistics as core_statistics; use mockall::predicate::eq; use super::sample_scrape_request; use crate::handlers::handle_scrape; use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, - sample_ipv6_remote_addr, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, + sample_ipv6_remote_addr, MockUdpServerStatsEventSender, }; use crate::statistics as server_statistics; #[tokio::test] async fn should_send_the_upd6_scrape_event() { - let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); - udp_core_stats_event_sender_mock - .expect_send_event() - .with(eq(core_statistics::event::Event::Udp6Scrape)) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); - let udp_core_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); - let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() @@ -448,14 +413,13 @@ mod tests { let remote_addr = sample_ipv6_remote_addr(); - let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = + let (_core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); handle_scrape( + &core_udp_tracker_services.scrape_service, remote_addr, &sample_scrape_request(&remote_addr), - &core_tracker_services.scrape_handler, - &udp_core_stats_event_sender, &udp_server_stats_event_sender, sample_cookie_valid_range(), ) diff --git a/src/container.rs b/src/container.rs index 3ef9b6f5b..46cf0c987 100644 --- a/src/container.rs +++ b/src/container.rs @@ -45,6 +45,7 @@ pub struct AppContainer { pub ban_service: Arc>, pub connect_service: Arc, pub announce_service: Arc, + pub scrape_service: Arc, // HTTP Tracker Core Services pub http_stats_event_sender: Arc>>, @@ -97,6 +98,10 @@ impl AppContainer { tracker_core_container.whitelist_authorization.clone(), udp_core_stats_event_sender.clone(), )); + let scrape_service = Arc::new(bittorrent_udp_tracker_core::services::scrape::ScrapeService::new( + tracker_core_container.scrape_handler.clone(), + udp_core_stats_event_sender.clone(), + )); // UDP Tracker Server Services let (udp_server_stats_event_sender, udp_server_stats_repository) = @@ -125,6 +130,7 @@ impl AppContainer { ban_service, connect_service, announce_service, + scrape_service, // HTTP Tracker Core Services http_stats_event_sender, @@ -169,6 +175,7 @@ impl AppContainer { ban_service: self.ban_service.clone(), connect_service: self.connect_service.clone(), announce_service: self.announce_service.clone(), + scrape_service: self.scrape_service.clone(), } } From ddb33812d12695ed458a3d4d8fa436898f4ff32e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 28 Feb 2025 17:44:23 +0000 Subject: [PATCH 0845/1297] refactor: rename AppContainer fields --- src/container.rs | 46 +++++++++++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/src/container.rs b/src/container.rs index 46cf0c987..07c30d604 100644 --- a/src/container.rs +++ b/src/container.rs @@ -24,6 +24,18 @@ use torrust_tracker_configuration::{Configuration, Core, HttpApi, HttpTracker, U use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use tracing::instrument; +/* todo: remove duplicate code. + + Use containers from packages as AppContainer fields: + + - bittorrent_tracker_core::container::TrackerCoreContainer + - bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer + - bittorrent_http_tracker_core::container::HttpTrackerCoreContainer + - torrust_udp_tracker_server::container::UdpTrackerServerContainer + + Container initialization is duplicated. +*/ + pub struct AppContainer { // Tracker Core Services pub core_config: Arc, @@ -42,10 +54,10 @@ pub struct AppContainer { // UDP Tracker Core Services pub udp_core_stats_event_sender: Arc>>, pub udp_core_stats_repository: Arc, - pub ban_service: Arc>, - pub connect_service: Arc, - pub announce_service: Arc, - pub scrape_service: Arc, + pub udp_ban_service: Arc>, + pub udp_connect_service: Arc, + pub udp_announce_service: Arc, + pub udp_scrape_service: Arc, // HTTP Tracker Core Services pub http_stats_event_sender: Arc>>, @@ -89,16 +101,16 @@ impl AppContainer { bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); let udp_core_stats_repository = Arc::new(udp_core_stats_repository); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let connect_service = Arc::new(bittorrent_udp_tracker_core::services::connect::ConnectService::new( + let udp_ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let udp_connect_service = Arc::new(bittorrent_udp_tracker_core::services::connect::ConnectService::new( udp_core_stats_event_sender.clone(), )); - let announce_service = Arc::new(bittorrent_udp_tracker_core::services::announce::AnnounceService::new( + let udp_announce_service = Arc::new(bittorrent_udp_tracker_core::services::announce::AnnounceService::new( tracker_core_container.announce_handler.clone(), tracker_core_container.whitelist_authorization.clone(), udp_core_stats_event_sender.clone(), )); - let scrape_service = Arc::new(bittorrent_udp_tracker_core::services::scrape::ScrapeService::new( + let udp_scrape_service = Arc::new(bittorrent_udp_tracker_core::services::scrape::ScrapeService::new( tracker_core_container.scrape_handler.clone(), udp_core_stats_event_sender.clone(), )); @@ -127,10 +139,10 @@ impl AppContainer { // UDP Tracker Core Services udp_core_stats_event_sender, udp_core_stats_repository, - ban_service, - connect_service, - announce_service, - scrape_service, + udp_ban_service, + udp_connect_service, + udp_announce_service, + udp_scrape_service, // HTTP Tracker Core Services http_stats_event_sender, @@ -172,10 +184,10 @@ impl AppContainer { udp_tracker_config: udp_tracker_config.clone(), udp_core_stats_event_sender: self.udp_core_stats_event_sender.clone(), udp_core_stats_repository: self.udp_core_stats_repository.clone(), - ban_service: self.ban_service.clone(), - connect_service: self.connect_service.clone(), - announce_service: self.announce_service.clone(), - scrape_service: self.scrape_service.clone(), + ban_service: self.udp_ban_service.clone(), + connect_service: self.udp_connect_service.clone(), + announce_service: self.udp_announce_service.clone(), + scrape_service: self.udp_scrape_service.clone(), } } @@ -187,7 +199,7 @@ impl AppContainer { in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), keys_handler: self.keys_handler.clone(), whitelist_manager: self.whitelist_manager.clone(), - ban_service: self.ban_service.clone(), + ban_service: self.udp_ban_service.clone(), http_stats_repository: self.http_stats_repository.clone(), udp_core_stats_repository: self.udp_core_stats_repository.clone(), udp_server_stats_repository: self.udp_server_stats_repository.clone(), From a8224e836e601623ff23cf572e5daebd74d8baa7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 09:16:51 +0000 Subject: [PATCH 0846/1297] docs: [#1290] add documentation for packages --- README.md | 12 +- cSpell.json | 1 + docs/index.md | 11 ++ .../packages-dependencies-http-tracker.png | Bin 0 -> 33225 bytes .../packages-dependencies-udp-tracker.png | Bin 0 -> 33537 bytes .../torrust-tracker-layers-with-packages.png | Bin 0 -> 68191 bytes docs/media/torrust-tracker-components.png | Bin 84935 -> 0 bytes docs/packages.md | 115 ++++++++++++++++++ src/lib.rs | 13 +- 9 files changed, 139 insertions(+), 13 deletions(-) create mode 100644 docs/index.md create mode 100644 docs/media/packages/packages-dependencies-http-tracker.png create mode 100644 docs/media/packages/packages-dependencies-udp-tracker.png create mode 100644 docs/media/packages/torrust-tracker-layers-with-packages.png delete mode 100644 docs/media/torrust-tracker-components.png create mode 100644 docs/packages.md diff --git a/README.md b/README.md index 6d611d9a5..671a484e6 100644 --- a/README.md +++ b/README.md @@ -40,12 +40,12 @@ Protocols: Integrations: -- [ ] Monitoring (Prometheus). +- [x] Monitoring (Prometheus). Utils: -- [ ] Tracker client. -- [ ] Tracker checker. +- [ ] Tracker client. WIP. +- [ ] Tracker checker. WIP. Others: @@ -65,6 +65,10 @@ Others: - [BEP 27]: Private Torrents. - [BEP 48]: Tracker Protocol Extension: Scrape. +## Architecture + +![Torrust Tracker Layers with main packages](./docs/media/packages/torrust-tracker-layers-with-packages.png) + ## Getting Started ### Container Version @@ -167,6 +171,8 @@ Some specific sections: - [Tracker (HTTP/TLS)][HTTP] - [Tracker (UDP)][UDP] +There is also extra documentation in the [docs](./docs) folder. + ## Benchmarking - [Benchmarking](./docs/benchmarking.md) diff --git a/cSpell.json b/cSpell.json index dcdcc9cf6..3121d6175 100644 --- a/cSpell.json +++ b/cSpell.json @@ -15,6 +15,7 @@ "bdecode", "bencode", "bencoded", + "bencoding", "beps", "binascii", "binstall", diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 000000000..873f3758b --- /dev/null +++ b/docs/index.md @@ -0,0 +1,11 @@ +# Torrust Tracker Documentation + +For more detailed instructions, please view our [crate documentation][docs]. + +- [Benchmarking](benchmarking.md) +- [Containers](containers.md) +- [Packages](packages.md) +- [Profiling](profiling.md) +- [Releases process](release_process.md) + +[docs]: https://docs.rs/torrust-tracker/latest/torrust_tracker/ diff --git a/docs/media/packages/packages-dependencies-http-tracker.png b/docs/media/packages/packages-dependencies-http-tracker.png new file mode 100644 index 0000000000000000000000000000000000000000..45dbd9839d533ae1cd548343f4190f56eac9abca GIT binary patch literal 33225 zcmdSCc|28Z+c&;wP*hZgLPV3yB}3*k&|oN;Gl$G%9c%cF4G;P^QYf zGe*cf&uqVA?M-#v&vifdbv@7f`MsZa{Xy2=YpwG<&SUr<-{Uw}_mvc6w^K4wA_%hm zyxf^92(noYK{oB!LJnv0HgI^uFEYC;vNA|oE%N~UvC;7SX(h7l2w9}5*l`5ekDNbq z>Z)_(aJ#(q0lbUUut4qmAdB-7L55CGgTy_z-}oX;^9;L}lCT9YC{g83adD{xFYK++ zzhUFsGrH_dU;Nai>G$e+9Si!Hh<|j%%3r74V(+mW1kyi6k}#LN(n1{DOk`W=06 zd>R?j_X&^JSbkGf6qQduk1~WOH(Ju~o)o zh?!|TlU9^MLZex>W~xF$aDFJ+*AYi4;ArvvkeA3It-CewjCrBYdpsM$*3O#K zUg5=ob_*eDYHHROk0`3+lasmb!%~FrJ9HxFMYzrVk-OY^vANkdSQ2r;*~y1p&k07< ztgNieySU5TrOA?=ot<5*_*AT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?>=<T+j& zvC*3=<38G1cvZ954$MgVSC`zMHg1uq@5#^2Z_Nx9J33u!UcyZbtl*3m0{t+_XZ;!s zN|V@YxB_ENGET*5F3PHq)5+1dGpH%Qt=~IZeNa;Rc5R==!EUQ=L0^_h-ExntAxDQv zFD{nF2{YrcxHSRL#3rR4%(pDWdLCo2$ zz2|2`g2y!37y=x#MEe(N%WA^s4SEXm?Y}aWp zlg`8pE$c{(KpN;a$km?hl;GZ6N-i(g>2O;rg`c#k{&d>9;qE16Z2-;?VYZoBo)LKHhAGv6 z3D5qjSXx=zR@alkVs^=MiGf{c7fmJn!6~wxV{v4ti@o#@O>&BYG*?1Z3!j4HyG-++ f=J8+5$%L4t*_e*@{)d2}1fi|2yC+4>=E8pf;Zl4@ literal 0 HcmV?d00001 diff --git a/docs/media/packages/packages-dependencies-udp-tracker.png b/docs/media/packages/packages-dependencies-udp-tracker.png new file mode 100644 index 0000000000000000000000000000000000000000..57987a31eabf33ac27ed1d51b1b659c56af28018 GIT binary patch literal 33537 zcmce;c|28X`#-)^QfbhDPGl%eGBnCenp23(vxqX53?X(QAyGnQEJ+zM+vZIfQkjQr z+mIoSDWSdD#_x46bcW|V&-3~IzMt36ALq39TI*i-aNY0geZ8;i-rhJ84!fHF&P~_`&XM;-{9%^o;5w2z~HGb|X!q7uG#HcSzdw-6gBTEamGRWgz zRj`U_vw4U!OSmV;hj&X7JlUsco z-duE{Hg?q1)u})qFv85w#QKf+zd|-zGr&KR%Zjzp=fV9WZ0P^a=kgfge}!ECZs6wpa$2p36y1@MSe6G@!`EPi5u#2`PG_Z?bxQ-StN{V}(0)!d74uZ*n7< z{Pg-7)!$uhoSix30&EyC$xpSTSTZA7EimKF!?q#&s>;fpf#nt=@>1*=;T4RkkgYT4 zbZX+|tK^)4Ym7oL?83BXT-JUkqdROwxA-Y58hej8N^-8{kjQ`CbLK%=SB+VH_pW78 zeCFjUv96@yL@@>|BEvm{crv=iQBtVI@#amj&8t7IljibgXR>}EN(`5*?XMR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Z}!$v)kKw!fg6?v z^WgZ`AZv=gwvG-Ab!_eRT#X7mTbfAn5EkA7ljP5onJO{i1tvXvRT z&yPczddiF?WOY}cf$6*)g-V}E{_JOsnO!gK$QPLG!!(_DLBKfSj$A2}b^`goSddz1 zzsy@>66avVGb-vyab6W`DeKv>OUs=fpW_IsrZ;vQWeZSmgmLDhhe9k3LNv5m+!Ifw z>=ZQeIY3d_I~(|;XUEBPSQ-pwI%`B;R6W5$8-~7`lvivNbLE+qb2}`X2$vTj?O1rH sokdcRsf=xZ+AO^NKS2qOq4`aSN(7m;>uq~U7)ENZ#(|xQ+s)4X4+0SzfdBvi literal 0 HcmV?d00001 diff --git a/docs/media/packages/torrust-tracker-layers-with-packages.png b/docs/media/packages/torrust-tracker-layers-with-packages.png new file mode 100644 index 0000000000000000000000000000000000000000..9da465806bc6eb8c151ec5a96b8d6fbc2a27f6de GIT binary patch literal 68191 zcma&N1z40_*FQRdih`sF(kUpZNJ@ud(2aB>-Cc@+2#AP;Gz!w)F@U5rN(?phP(#-+ zx%a+zthM%9Yp?a&Vakef1b9?<5D0|e`7>En2n6pp1ac+v zIyQJxvhVsGd|bD=OutmztQVjBfQs0o#^hrKqfH`N=+R(nfRxj85jz-FZ>BokA!~`MPp|#hQ zzKJg zn)z-BfsZk%UM$Q{h$IfL9FAmI0%!z*D8|(?LXKH*2q9nI3u7M4nti3lh6Ivd+4__G zw@G)zLu^PhnzZ4iiwPm7$-PG%*Fm@Te}91ofdXwbm``ZoX>jbe2<^vR(U{onS zge=ySFgfS%ljbXacj_UMD#A<6VHlcX%K8%g->;I?|L2`UDj1jkb^w7`$^5fO2xKti z@AN@cI>AHSzb#^?JGmhc`ILXE0$%`P{g2=Ovnk~NXb#ORQ*gNcxwD6dpu1E5FN^Zp zUN2u?ntIvgm7Sf3n&+d2Qs*pn4Grtn@6=)>Oibg=+279yNeAmlE`>zINm-| z4_IN;?T<9)O6preqrHlskcU6vNfOuPVr8XuN%)bSoxR;^Q9f=fpg2-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UMV81Bix%j$u%(<$01UHF zN_!glSo_9b^kM9>TCD&cEfmnK*l>4~hIs}lQ0S$XqMByLfA?oTtY2D-G|Dhj=#%o& pZ*C-i6RZF4PaESIZpbKP>I++s22WO$-X!ff%v(G+$KGqpe*qHo?Na~% literal 0 HcmV?d00001 diff --git a/docs/media/torrust-tracker-components.png b/docs/media/torrust-tracker-components.png deleted file mode 100644 index 19fe3c0b897a2413a4a6fbf807a0dbdac19b6268..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 84935 zcmdSBcR1E@-#@IaB8o_oPDx}{MluU!k5saiy~*Ahib6(YWMn5rRyGxp?3EqaN;cVk zue1BPf6w!Kp5s2A;~D?l=W$(EUBY>OKi|*i{eG?Y_ldHi6#2fR`$$Mg$YrD@RY*v7 zd?q2;`G9mgzOv-_`3U~lYa^|0M?!L-lK9_kVeAL!Nk~qR$Vgtk;T%2L=W?meWnFCM zZ(Gs_W|bN;20`k0?*mddBwsj;s3l}uicjT`&wdg79uhz~ViI$WFwx1Mn-MDe?wFs} zHMYKvx`nl&jh@E8^D$}71y4OhH=};U{Vf?2X)O_(?!bTlu2rOEW}e2UzJH*xzLNbv`9ei8`B7fq#xaVcysrz{x09Urefo58e#Ko>?97=r zg}=9x%p4X!()Zf9F}C@*$;#ZwLmi7swQ zhlv)$fsgk$H#e<+lmx$RZ%&j-F6sT^M=RFoGykNw(5||@y}h!svZ=|Y?e(?U+1U`6 z4DI6YImSw&annD4&aRk~>gIm@c&S?jU#?O#*0_7^+Chb^>}#7OiQa<=I%0D7wNV%xl$Kqq2oux*_~}zJ5(L```53z`FRQkL0;3Ar0#AFmWtYN z?rMKJs^iCh_=oKzSspK_*S^pF11oh}FTG%DKFn#Y90ej@^S!GsgQP%}lW@cu5&$)AVvBbHA zoJWrzpJ8V=HZZX0E6U5ru)^E$7}YJ0zO?RiiSj(NoNZuW5H0EvMX6_QUTo2oJw84@ zFfdS8SNHz?S=XBJ)y3aBIy$(7V+W)x1Q)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!$#4fTMu2_l%5JI1VtUPeURH z=wjJ~sEjk)&r{(Lh;(XT@4^KORzX)_S)_=Bq8e+u|FLkaxYxy#0K-2 z5N@EFLPO^A_w}9r*|sUQGOQmDaaX-`2lPo|8JW^2T|h$EPqI7!jJV@$3S4kjD;osn zDSb5S;$RVP4D$rpr{Frm+5E)`?GG?|ZUxhk1GCYs>X=oft<4>^O z7$Ptm*?nf}6EIF(oqq+Y9Tt%d#W>hSXXi||G&Tc6GF0FQCb|XeeA~7|$?UJnIF?zr z_At=9%&Xtf`vZW^oi?74>AlYA(HVf=WsN|Cf#nmd2~L<48wG62Udot$TkYgr~$yL33( zbVKzeyLdo;tG-#I)}(`Ar4ed%Ab0xir)Kfx-1Ufcglljpx*;l67X{WV*eyfpe1Jc> z1Lp6?GRrXw{>NGrxIJO1|KH5U4>-IYUPHHO+pG-9!^j)oIC7aqN|m)j_j2n8yM2zs zs|_vpj8$#EQSxVne7cd1_u8iV2AiSZ$#=ZBvp9P<_78{PKJWE-%pH4Usg8GWXs_Ki zD5V>%GFi*Xz}kClyi%>CReYR(;^Vvd_}h3se%F$ZS2zT}^DeIWU&gI{Q0BWup356c SBJPMMwE4nr**S|%`~M5@Hz=$C diff --git a/docs/packages.md b/docs/packages.md new file mode 100644 index 000000000..118046a87 --- /dev/null +++ b/docs/packages.md @@ -0,0 +1,115 @@ +# Torrust Tracker Package Architecture + +- [Package Conventions](#package-conventions) +- [Package Catalog](#package-catalog) +- [Architectural Philosophy](#architectural-philosophy) +- [Protocol Implementation Details](#protocol-implementation-details) +- [Architectural Philosophy](#architectural-philosophy) + +```output +packages/ +├── axum-health-check-api-server +├── axum-http-tracker-server +├── axum-rest-tracker-api-server +├── axum-server +├── clock +├── configuration +├── http-protocol +├── http-tracker-core +├── located-error +├── primitives +├── rest-tracker-api-client +├── rest-tracker-api-core +├── server-lib +├── test-helpers +├── torrent-repository +├── tracker-client +├── tracker-core +├── udp-protocol +├── udp-tracker-core +└── udp-tracker-server +``` + +```output +console/ +└── tracker-client # Client for interacting with trackers +``` + +```output +contrib/ +└── bencode # Community-contributed Bencode utilities +``` + +## Package Conventions + +| Prefix | Responsibility | Dependencies | +|-----------------|-----------------------------------------|---------------------------| +| `axum-*` | HTTP server components using Axum | Axum framework | +| `*-server` | Server implementations | Corresponding *-core | +| `*-core` | Domain logic & business rules | Protocol implementations | +| `*-protocol` | BitTorrent protocol implementations | BitTorrent protocol | +| `udp-*` | UDP Protocol-specific implementations | Tracker core | +| `http-*` | HTTP Protocol-specific implementations | Tracker core | + +Key Architectural Principles: + +1. **Separation of Concerns**: Servers contain only network I/O logic. +2. **Protocol Compliance**: `*-protocol` packages strictly implement BEP specifications. +3. **Extensibility**: Core logic is framework-agnostic for easy protocol additions. + +## Package Catalog + +| Package | Description | Key Responsibilities | +|---------|-------------|----------------------| +| **axum-*** | | | +| `axum-server` | Base Axum HTTP server infrastructure | HTTP server lifecycle management | +| `axum-http-tracker-server` | BitTorrent HTTP tracker (BEP 3/23) | Handle announce/scrape requests | +| `axum-rest-tracker-api-server` | Management REST API | Tracker configuration & monitoring | +| `axum-health-check-api-server` | Health monitoring endpoint | System health reporting | +| **Core Components** | | | +| `http-tracker-core` | HTTP-specific implementation | Request validation, Response formatting | +| `udp-tracker-core` | UDP-specific implementation | Connectionless request handling | +| `tracker-core` | Central tracker logic | Peer management | +| **Protocols** | | | +| `http-protocol` | HTTP tracker protocol (BEP 3/23) | Announce/scrape request parsing | +| `udp-protocol` | UDP tracker protocol (BEP 15) | UDP message framing/parsing | +| **Domain** | | | +| `torrent-repository` | Torrent metadata storage | InfoHash management, Peer coordination | +| `configuration` | Runtime configuration | Config file parsing, Environment variables | +| `primitives` | Domain-specific types | InfoHash, PeerId, Byte handling | +| **Utilities** | | | +| `clock` | Time abstraction | Mockable time source for testing | +| `located-error` | Diagnostic errors | Error tracing with source locations | +| `test-helpers` | Testing utilities | Mock servers, Test data generation | +| **Client Tools** | | | +| `tracker-client` | CLI client | Tracker interaction/testing | +| `rest-tracker-api-client` | API client library | REST API integration | + +## Protocol Implementation Details + +### HTTP Tracker (BEP 3/23) + +- `http-protocol` implements: + - URL parameter parsing + - Response bencoding + - Error code mapping + - Compact peer formatting + +### UDP Tracker (BEP 15) + +- `udp-protocol` handles: + - Connection ID management + - Message framing (32-bit big-endian) + - Transaction ID tracking + - Error response codes + +## Architectural Philosophy + +1. **Testability**: Core packages have minimal dependencies for easy unit testing +2. **Observability**: Health checks and metrics built into server packages +3. **Modularity**: Protocol implementations decoupled from transport layers +4. **Extensibility**: New protocols can be added without modifying core logic + +![Torrust Tracker Architecture Diagram](./media/packages/torrust-tracker-layers-with-packages.png) + +> Diagram shows clean separation between network I/O (servers), protocol handling, and core tracker logic diff --git a/src/lib.rs b/src/lib.rs index e947d2ab5..0aaf34fe4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -36,7 +36,7 @@ //! - [API](#api) //! - [HTTP Tracker](#http-tracker) //! - [UDP Tracker](#udp-tracker) -//! - [Components](#components) +//! - [Packages](#packages) //! - [Implemented BEPs](#implemented-beps) //! - [Contributing](#contributing) //! - [Documentation](#documentation) @@ -401,16 +401,9 @@ //! //! - [BEP 15. UDP Tracker Protocol for `BitTorrent`](https://www.bittorrent.org/beps/bep_0015.html) //! -//! # Components +//! # Packages //! -//! Torrust Tracker has four main components: -//! -//! - The core tracker [`core`] -//! - The tracker REST [`API`](torrust_axum_rest_tracker_api_server) -//! - The [`UDP`](torrust_udp_tracker_server) tracker -//! - The [`HTTP`](torrust_axum_http_tracker_server) tracker -//! -//! ![Torrust Tracker Components](https://raw.githubusercontent.com/torrust/torrust-tracker/main/docs/media/torrust-tracker-components.png) +//! ![Torrust Tracker Layers with Main Packages](https://raw.githubusercontent.com/torrust/torrust-tracker/main/docs/media/packages/torrust-tracker-layers-with-packages.png) //! //! ## Core tracker //! From b76eff6a5ec7b1d4a35007ee82826b73eaba9807 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 09:52:43 +0000 Subject: [PATCH 0847/1297] fix: clippy error ```output error: unnecessary `Debug` formatting in `format!` args --> src/console/ci/e2e/runner.rs:140:98 | 140 | let config = std::fs::read_to_string(path).with_context(|| format!("CSan't read config file {path:?}"))?; | ^^^^ | = help: use `Display` formatting and change this to `path.display()` = note: switching to `Display` formatting will change how the value is shown; escaped characters will no longer be escaped and surrounding quotes will be removed = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_debug_formatting = note: `-D clippy::unnecessary-debug-formatting` implied by `-D clippy::pedantic` = help: to override `-D clippy::pedantic` add `#[allow(clippy::unnecessary_debug_formatting)]` error: could not compile `torrust-tracker` (lib) due to 1 previous error warning: build failed, waiting for other jobs to finish... error: could not compile `torrust-tracker` (lib test) due to 1 previous error ``` --- src/console/ci/e2e/runner.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/console/ci/e2e/runner.rs b/src/console/ci/e2e/runner.rs index 118ecda42..624878c70 100644 --- a/src/console/ci/e2e/runner.rs +++ b/src/console/ci/e2e/runner.rs @@ -137,7 +137,7 @@ fn load_tracker_configuration(args: &Args) -> anyhow::Result { } fn load_config_from_file(path: &PathBuf) -> anyhow::Result { - let config = std::fs::read_to_string(path).with_context(|| format!("CSan't read config file {path:?}"))?; + let config = std::fs::read_to_string(path).with_context(|| format!("CSan't read config file {}", path.display()))?; Ok(config) } From 29344b113da9159f98c85193baec7d858b37b767 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 10:39:38 +0000 Subject: [PATCH 0848/1297] refactor: rearrange code --- .../src/services/announce.rs | 100 +++++++++--------- 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 5890d35c1..c2eba5e1a 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -23,56 +23,6 @@ use torrust_tracker_primitives::core::AnnounceData; use crate::statistics; -/// Errors related to announce requests. -#[derive(thiserror::Error, Debug, Clone)] -pub enum HttpAnnounceError { - #[error("Error resolving peer IP: {source}")] - PeerIpResolutionError { source: PeerIpResolutionError }, - - #[error("Tracker core error: {source}")] - TrackerCoreError { source: TrackerCoreError }, -} - -impl From for HttpAnnounceError { - fn from(peer_ip_resolution_error: PeerIpResolutionError) -> Self { - Self::PeerIpResolutionError { - source: peer_ip_resolution_error, - } - } -} - -impl From for HttpAnnounceError { - fn from(tracker_core_error: TrackerCoreError) -> Self { - Self::TrackerCoreError { - source: tracker_core_error, - } - } -} - -impl From for HttpAnnounceError { - fn from(announce_error: AnnounceError) -> Self { - Self::TrackerCoreError { - source: announce_error.into(), - } - } -} - -impl From for HttpAnnounceError { - fn from(whitelist_error: WhitelistError) -> Self { - Self::TrackerCoreError { - source: whitelist_error.into(), - } - } -} - -impl From for HttpAnnounceError { - fn from(whitelist_error: authentication::key::Error) -> Self { - Self::TrackerCoreError { - source: whitelist_error.into(), - } - } -} - /// The HTTP tracker `announce` service. /// /// The service sends an statistics event that increments: @@ -184,6 +134,56 @@ impl AnnounceService { } } +/// Errors related to announce requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum HttpAnnounceError { + #[error("Error resolving peer IP: {source}")] + PeerIpResolutionError { source: PeerIpResolutionError }, + + #[error("Tracker core error: {source}")] + TrackerCoreError { source: TrackerCoreError }, +} + +impl From for HttpAnnounceError { + fn from(peer_ip_resolution_error: PeerIpResolutionError) -> Self { + Self::PeerIpResolutionError { + source: peer_ip_resolution_error, + } + } +} + +impl From for HttpAnnounceError { + fn from(tracker_core_error: TrackerCoreError) -> Self { + Self::TrackerCoreError { + source: tracker_core_error, + } + } +} + +impl From for HttpAnnounceError { + fn from(announce_error: AnnounceError) -> Self { + Self::TrackerCoreError { + source: announce_error.into(), + } + } +} + +impl From for HttpAnnounceError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::TrackerCoreError { + source: whitelist_error.into(), + } + } +} + +impl From for HttpAnnounceError { + fn from(whitelist_error: authentication::key::Error) -> Self { + Self::TrackerCoreError { + source: whitelist_error.into(), + } + } +} + #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; From 5178abab373a15302482655c60b436f34e0d2c45 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 10:40:32 +0000 Subject: [PATCH 0849/1297] fix: clippy error ```output error: unnecessary `Debug` formatting in `format!` args --> console/tracker-client/src/console/clients/checker/app.rs:117:103 | 117 | let file_content = std::fs::read_to_string(path).with_context(|| format!("can't read config file {path:?}"))?; | ^^^^ | = help: use `Display` formatting and change this to `path.display()` = note: switching to `Display` formatting will change how the value is shown; escaped characters will no longer be escaped and surrounding quotes will be removed = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_debug_formatting = note: `-D clippy::unnecessary-debug-formatting` implied by `-D clippy::pedantic` = help: to override `-D clippy::pedantic` add `#[allow(clippy::unnecessary_debug_formatting)]` Checking torrust-axum-http-tracker-server v3.0.0-develop (/home/josecelano/Documents/git/committer/me/github/torrust/torrust-tracker/packages/axum-http-tracker-server) error: could not compile `torrust-tracker-client` (lib) due to 1 previous error warning: build failed, waiting for other jobs to finish... error: could not compile `torrust-tracker-client` (lib test) due to 1 previous error ``` --- console/tracker-client/src/console/clients/checker/app.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/console/tracker-client/src/console/clients/checker/app.rs b/console/tracker-client/src/console/clients/checker/app.rs index 395f65df9..88ce5a8ac 100644 --- a/console/tracker-client/src/console/clients/checker/app.rs +++ b/console/tracker-client/src/console/clients/checker/app.rs @@ -114,7 +114,7 @@ fn setup_config(args: Args) -> Result { } fn load_config_from_file(path: &PathBuf) -> Result { - let file_content = std::fs::read_to_string(path).with_context(|| format!("can't read config file {path:?}"))?; + let file_content = std::fs::read_to_string(path).with_context(|| format!("can't read config file {}", path.display()))?; parse_from_json(&file_content).context("invalid config format") } From ec0e437822dc9ad8e01f1dac55ba1eafdeedaa02 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 11:18:59 +0000 Subject: [PATCH 0850/1297] refactor: [#1338] clean bittorrent_http_tracker_core::services::announce::AnnounceService --- .../src/services/announce.rs | 82 +++++++++++-------- 1 file changed, 46 insertions(+), 36 deletions(-) diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index c2eba5e1a..959dcc615 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -13,6 +13,7 @@ use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::announce::{peer_from_request, Announce}; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources, PeerIpResolutionError}; +use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::{self, Key}; @@ -73,50 +74,61 @@ impl AnnounceService { client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Result { - // Authentication - if self.core_config.private { - match maybe_key { - Some(key) => match self.authentication_service.authenticate(&key).await { - Ok(()) => (), - Err(error) => return Err(error.into()), - }, - None => { - return Err(authentication::key::Error::MissingAuthKey { - location: Location::caller(), - } - .into()) - } - } - } + self.authenticate(maybe_key).await?; - // Authorization - match self.whitelist_authorization.authorize(&announce_request.info_hash).await { - Ok(()) => (), - Err(error) => return Err(error.into()), - } + self.authorize(announce_request.info_hash).await?; - let peer_ip = match peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources) { - Ok(peer_ip) => peer_ip, - Err(error) => return Err(error.into()), - }; + let remote_client_ip = self.resolve_remote_client_ip(client_ip_sources)?; - let mut peer = peer_from_request(announce_request, &peer_ip); + let mut peer = peer_from_request(announce_request, &remote_client_ip); - let peers_wanted = match announce_request.numwant { - Some(numwant) => PeersWanted::only(numwant), - None => PeersWanted::AsManyAsPossible, - }; - - let original_peer_ip = peer.peer_addr.ip(); + let peers_wanted = Self::peers_wanted(announce_request); - // The tracker could change the original peer ip let announce_data = self .announce_handler - .announce(&announce_request.info_hash, &mut peer, &original_peer_ip, &peers_wanted) + .announce(&announce_request.info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; + self.send_stats_event(remote_client_ip).await; + + Ok(announce_data) + } + + async fn authenticate(&self, maybe_key: Option) -> Result<(), authentication::key::Error> { + if self.core_config.private { + let key = maybe_key.ok_or(authentication::key::Error::MissingAuthKey { + location: Location::caller(), + })?; + + self.authentication_service.authenticate(&key).await?; + } + + Ok(()) + } + + async fn authorize(&self, info_hash: InfoHash) -> Result<(), WhitelistError> { + self.whitelist_authorization.authorize(&info_hash).await + } + + /// Resolves the client's real IP address considering proxy headers + fn resolve_remote_client_ip(&self, client_ip_sources: &ClientIpSources) -> Result { + match peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources) { + Ok(peer_ip) => Ok(peer_ip), + Err(error) => Err(error), + } + } + + /// Determines how many peers the client wants in the response + fn peers_wanted(announce_request: &Announce) -> PeersWanted { + match announce_request.numwant { + Some(numwant) => PeersWanted::only(numwant), + None => PeersWanted::AsManyAsPossible, + } + } + + async fn send_stats_event(&self, peer_ip: IpAddr) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { - match original_peer_ip { + match peer_ip { IpAddr::V4(_) => { http_stats_event_sender .send_event(statistics::event::Event::Tcp4Announce) @@ -129,8 +141,6 @@ impl AnnounceService { } } } - - Ok(announce_data) } } From 1b01bf09c50797ac71c12738fda572bb48e6e27b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 11:22:23 +0000 Subject: [PATCH 0851/1297] refactor: [#1338] rearrange code --- .../http-tracker-core/src/services/scrape.rs | 101 +++++++++--------- 1 file changed, 52 insertions(+), 49 deletions(-) diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 48cee7c8c..fbfa0d024 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -22,55 +22,6 @@ use torrust_tracker_primitives::core::ScrapeData; use crate::statistics; -/// Errors related to announce requests. -#[derive(thiserror::Error, Debug, Clone)] -pub enum HttpScrapeError { - #[error("Error resolving peer IP: {source}")] - PeerIpResolutionError { source: PeerIpResolutionError }, - - #[error("Tracker core error: {source}")] - TrackerCoreError { source: TrackerCoreError }, -} - -impl From for HttpScrapeError { - fn from(peer_ip_resolution_error: PeerIpResolutionError) -> Self { - Self::PeerIpResolutionError { - source: peer_ip_resolution_error, - } - } -} - -impl From for HttpScrapeError { - fn from(tracker_core_error: TrackerCoreError) -> Self { - Self::TrackerCoreError { - source: tracker_core_error, - } - } -} - -impl From for HttpScrapeError { - fn from(announce_error: ScrapeError) -> Self { - Self::TrackerCoreError { - source: announce_error.into(), - } - } -} - -impl From for HttpScrapeError { - fn from(whitelist_error: WhitelistError) -> Self { - Self::TrackerCoreError { - source: whitelist_error.into(), - } - } -} - -impl From for HttpScrapeError { - fn from(whitelist_error: authentication::key::Error) -> Self { - Self::TrackerCoreError { - source: whitelist_error.into(), - } - } -} /// The HTTP tracker `scrape` service. /// /// The service sends an statistics event that increments: @@ -110,6 +61,8 @@ impl ScrapeService { } } + /// Handles a scrape request. + /// /// # Errors /// /// This function will return an error if: @@ -186,6 +139,56 @@ async fn send_scrape_event( } } +/// Errors related to announce requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum HttpScrapeError { + #[error("Error resolving peer IP: {source}")] + PeerIpResolutionError { source: PeerIpResolutionError }, + + #[error("Tracker core error: {source}")] + TrackerCoreError { source: TrackerCoreError }, +} + +impl From for HttpScrapeError { + fn from(peer_ip_resolution_error: PeerIpResolutionError) -> Self { + Self::PeerIpResolutionError { + source: peer_ip_resolution_error, + } + } +} + +impl From for HttpScrapeError { + fn from(tracker_core_error: TrackerCoreError) -> Self { + Self::TrackerCoreError { + source: tracker_core_error, + } + } +} + +impl From for HttpScrapeError { + fn from(announce_error: ScrapeError) -> Self { + Self::TrackerCoreError { + source: announce_error.into(), + } + } +} + +impl From for HttpScrapeError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::TrackerCoreError { + source: whitelist_error.into(), + } + } +} + +impl From for HttpScrapeError { + fn from(whitelist_error: authentication::key::Error) -> Self { + Self::TrackerCoreError { + source: whitelist_error.into(), + } + } +} + #[cfg(test)] mod tests { From a42625934d2e0258a78a934458f71edebef3ffa0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 12:32:41 +0000 Subject: [PATCH 0852/1297] refactor: [#1338] bittorrent_http_tracker_core::services::scrape::ScrapeService --- .../http-tracker-core/src/services/scrape.rs | 174 +++++++++++------- 1 file changed, 109 insertions(+), 65 deletions(-) diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index fbfa0d024..dcb88508c 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -12,7 +12,6 @@ use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources, PeerIpResolutionError}; -use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::{self, Key}; use bittorrent_tracker_core::error::{ScrapeError, TrackerCoreError, WhitelistError}; @@ -63,6 +62,9 @@ impl ScrapeService { /// Handles a scrape request. /// + /// When the peer is not authenticated and the tracker is running in `private` + /// mode, the tracker returns empty stats for all the torrents. + /// /// # Errors /// /// This function will return an error if: @@ -74,67 +76,43 @@ impl ScrapeService { client_ip_sources: &ClientIpSources, maybe_key: Option, ) -> Result { - // Authentication - let return_fake_scrape_data = if self.core_config.private { - match maybe_key { - Some(key) => match self.authentication_service.authenticate(&key).await { - Ok(()) => false, - Err(_error) => true, - }, - None => true, - } + let scrape_data = if self.authentication_is_required() && !self.is_authenticated(maybe_key).await { + ScrapeData::zeroed(&scrape_request.info_hashes) } else { - false + self.scrape_handler.scrape(&scrape_request.info_hashes).await? }; - // Authorization for scrape requests is handled at the `bittorrent_tracker_core` - // level for each torrent. + let remote_client_ip = self.resolve_remote_client_ip(client_ip_sources)?; - let peer_ip = match peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources) { - Ok(peer_ip) => peer_ip, - Err(error) => return Err(error.into()), - }; + self.send_stats_event(&remote_client_ip).await; - if return_fake_scrape_data { - return Ok(fake(&self.opt_http_stats_event_sender, &scrape_request.info_hashes, &peer_ip).await); - } + Ok(scrape_data) + } - let scrape_data = self.scrape_handler.scrape(&scrape_request.info_hashes).await?; + fn authentication_is_required(&self) -> bool { + self.core_config.private + } - send_scrape_event(&peer_ip, &self.opt_http_stats_event_sender).await; + async fn is_authenticated(&self, maybe_key: Option) -> bool { + if let Some(key) = maybe_key { + return self.authentication_service.authenticate(&key).await.is_ok(); + } - Ok(scrape_data) + false } -} -/// The HTTP tracker fake `scrape` service. It returns zeroed stats. -/// -/// When the peer is not authenticated and the tracker is running in `private` mode, -/// the tracker returns empty stats for all the torrents. -/// -/// > **NOTICE**: tracker statistics are not updated in this case. -pub async fn fake( - opt_http_stats_event_sender: &Arc>>, - info_hashes: &Vec, - original_peer_ip: &IpAddr, -) -> ScrapeData { - send_scrape_event(original_peer_ip, opt_http_stats_event_sender).await; - - ScrapeData::zeroed(info_hashes) -} + /// Resolves the client's real IP address considering proxy headers. + fn resolve_remote_client_ip(&self, client_ip_sources: &ClientIpSources) -> Result { + peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources) + } -async fn send_scrape_event( - original_peer_ip: &IpAddr, - opt_http_stats_event_sender: &Arc>>, -) { - if let Some(http_stats_event_sender) = opt_http_stats_event_sender.as_deref() { - match original_peer_ip { - IpAddr::V4(_) => { - http_stats_event_sender.send_event(statistics::event::Event::Tcp4Scrape).await; - } - IpAddr::V6(_) => { - http_stats_event_sender.send_event(statistics::event::Event::Tcp6Scrape).await; - } + async fn send_stats_event(&self, original_peer_ip: &IpAddr) { + if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { + let event = match original_peer_ip { + IpAddr::V4(_) => statistics::event::Event::Tcp4Scrape, + IpAddr::V6(_) => statistics::event::Event::Tcp6Scrape, + }; + http_stats_event_sender.send_event(event).await; } } } @@ -211,7 +189,6 @@ mod tests { use tokio::sync::mpsc::error::SendError; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; - use torrust_tracker_test_helpers::configuration; use crate::statistics; use crate::tests::sample_info_hash; @@ -222,10 +199,6 @@ mod tests { authentication_service: Arc, } - fn initialize_services_for_public_tracker() -> Container { - initialize_services_with_configuration(&configuration::ephemeral_public()) - } - fn initialize_services_with_configuration(config: &Configuration) -> Container { let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -436,28 +409,34 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::sync::Arc; + use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_test_helpers::configuration; - use crate::services::scrape::fake; use crate::services::scrape::tests::{ - initialize_services_for_public_tracker, sample_info_hashes, sample_peer, MockHttpStatsEventSender, + initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; + use crate::services::scrape::ScrapeService; use crate::statistics; use crate::tests::sample_info_hash; #[tokio::test] - async fn it_should_always_return_the_zeroed_scrape_data_for_a_torrent() { + async fn it_should_return_the_zeroed_scrape_data_when_the_tracker_is_running_in_private_mode_and_the_peer_is_not_authenticated( + ) { + let config = configuration::ephemeral_private(); + + let container = initialize_services_with_configuration(&config); + let (http_stats_event_sender, _http_stats_repository) = statistics::setup::factory(false); let http_stats_event_sender = Arc::new(http_stats_event_sender); - let container = initialize_services_for_public_tracker(); - let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; - // Announce a new peer to force scrape data to contain not zeroed data + // Announce a new peer to force scrape data to contain non zeroed data let mut peer = sample_peer(); let original_peer_ip = peer.ip(); container @@ -466,7 +445,26 @@ mod tests { .await .unwrap(); - let scrape_data = fake(&http_stats_event_sender, &info_hashes, &original_peer_ip).await; + let scrape_request = Scrape { + info_hashes: sample_info_hashes(), + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_ip: Some(original_peer_ip), + }; + + let scrape_service = Arc::new(ScrapeService::new( + Arc::new(config.core), + container.scrape_handler.clone(), + container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + let scrape_data = scrape_service + .handle_scrape(&scrape_request, &client_ip_sources, None) + .await + .unwrap(); let expected_scrape_data = ScrapeData::zeroed(&info_hashes); @@ -475,6 +473,10 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_scrape_event_when_the_peer_uses_ipv4() { + let config = configuration::ephemeral(); + + let container = initialize_services_with_configuration(&config); + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() @@ -486,11 +488,34 @@ mod tests { let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); - fake(&http_stats_event_sender, &sample_info_hashes(), &peer_ip).await; + let scrape_request = Scrape { + info_hashes: sample_info_hashes(), + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_ip: Some(peer_ip), + }; + + let scrape_service = Arc::new(ScrapeService::new( + Arc::new(config.core), + container.scrape_handler.clone(), + container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + scrape_service + .handle_scrape(&scrape_request, &client_ip_sources, None) + .await + .unwrap(); } #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { + let config = configuration::ephemeral(); + + let container = initialize_services_with_configuration(&config); + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() @@ -502,7 +527,26 @@ mod tests { let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); - fake(&http_stats_event_sender, &sample_info_hashes(), &peer_ip).await; + let scrape_request = Scrape { + info_hashes: sample_info_hashes(), + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_ip: Some(peer_ip), + }; + + let scrape_service = Arc::new(ScrapeService::new( + Arc::new(config.core), + container.scrape_handler.clone(), + container.authentication_service.clone(), + http_stats_event_sender.clone(), + )); + + scrape_service + .handle_scrape(&scrape_request, &client_ip_sources, None) + .await + .unwrap(); } } } From 2a7e2cbf3b6a800650ebf6df791a914f7af985de Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 12:35:03 +0000 Subject: [PATCH 0853/1297] refactor: rearrange code --- .../udp-tracker-core/src/services/announce.rs | 72 +++++++++---------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index 051944d7e..a48242833 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -21,42 +21,6 @@ use torrust_tracker_primitives::core::AnnounceData; use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; use crate::statistics; -/// Errors related to announce requests. -#[derive(thiserror::Error, Debug, Clone)] -pub enum UdpAnnounceError { - /// Error returned when there was an error with the connection cookie. - #[error("Connection cookie error: {source}")] - ConnectionCookieError { source: ConnectionCookieError }, - - /// Error returned when there was an error with the tracker core announce handler. - #[error("Tracker core announce error: {source}")] - TrackerCoreAnnounceError { source: AnnounceError }, - - /// Error returned when there was an error with the tracker core whitelist. - #[error("Tracker core whitelist error: {source}")] - TrackerCoreWhitelistError { source: WhitelistError }, -} - -impl From for UdpAnnounceError { - fn from(connection_cookie_error: ConnectionCookieError) -> Self { - Self::ConnectionCookieError { - source: connection_cookie_error, - } - } -} - -impl From for UdpAnnounceError { - fn from(announce_error: AnnounceError) -> Self { - Self::TrackerCoreAnnounceError { source: announce_error } - } -} - -impl From for UdpAnnounceError { - fn from(whitelist_error: WhitelistError) -> Self { - Self::TrackerCoreWhitelistError { source: whitelist_error } - } -} - /// The `AnnounceService` is responsible for handling the `announce` requests. pub struct AnnounceService { pub announce_handler: Arc, @@ -135,3 +99,39 @@ impl AnnounceService { Ok(announce_data) } } + +/// Errors related to announce requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum UdpAnnounceError { + /// Error returned when there was an error with the connection cookie. + #[error("Connection cookie error: {source}")] + ConnectionCookieError { source: ConnectionCookieError }, + + /// Error returned when there was an error with the tracker core announce handler. + #[error("Tracker core announce error: {source}")] + TrackerCoreAnnounceError { source: AnnounceError }, + + /// Error returned when there was an error with the tracker core whitelist. + #[error("Tracker core whitelist error: {source}")] + TrackerCoreWhitelistError { source: WhitelistError }, +} + +impl From for UdpAnnounceError { + fn from(connection_cookie_error: ConnectionCookieError) -> Self { + Self::ConnectionCookieError { + source: connection_cookie_error, + } + } +} + +impl From for UdpAnnounceError { + fn from(announce_error: AnnounceError) -> Self { + Self::TrackerCoreAnnounceError { source: announce_error } + } +} + +impl From for UdpAnnounceError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::TrackerCoreWhitelistError { source: whitelist_error } + } +} From bb6af4dd559d7cb032e5d517f15974e9fa0100d2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 12:40:20 +0000 Subject: [PATCH 0854/1297] refactor: make service fields private --- packages/udp-tracker-core/src/services/announce.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index a48242833..0ec7b21af 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -23,9 +23,9 @@ use crate::statistics; /// The `AnnounceService` is responsible for handling the `announce` requests. pub struct AnnounceService { - pub announce_handler: Arc, - pub whitelist_authorization: Arc, - pub opt_udp_core_stats_event_sender: Arc>>, + announce_handler: Arc, + whitelist_authorization: Arc, + opt_udp_core_stats_event_sender: Arc>>, } impl AnnounceService { From 0fce925cadde7bd1343c11d2413f4a632feea567 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 12:40:51 +0000 Subject: [PATCH 0855/1297] chore: remove deprecated clippy attribute --- packages/udp-tracker-core/src/services/announce.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index 0ec7b21af..8af936a93 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -22,6 +22,10 @@ use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieEr use crate::statistics; /// The `AnnounceService` is responsible for handling the `announce` requests. +/// +/// The service sends an statistics event that increments: +/// +/// - The number of UDP `announce` requests handled by the UDP tracker. pub struct AnnounceService { announce_handler: Arc, whitelist_authorization: Arc, @@ -50,7 +54,6 @@ impl AnnounceService { /// /// - The tracker is running in listed mode and the torrent is not in the /// whitelist. - #[allow(clippy::too_many_arguments)] pub async fn handle_announce( &self, remote_addr: SocketAddr, From 9326da3c2e0e03052f8a450d36a2596ca4f93cb5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 13:00:56 +0000 Subject: [PATCH 0856/1297] refactor: [#1338] clean bittorrent_udp_tracker_core::services::announce::AnnunceService --- .../udp-tracker-core/src/services/announce.rs | 62 +++++++++++-------- 1 file changed, 35 insertions(+), 27 deletions(-) diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index 8af936a93..698f5fba6 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -12,6 +12,7 @@ use std::ops::Range; use std::sync::Arc; use aquatic_udp_protocol::AnnounceRequest; +use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::error::{AnnounceError, WhitelistError}; use bittorrent_tracker_core::whitelist; @@ -60,47 +61,54 @@ impl AnnounceService { request: &AnnounceRequest, cookie_valid_range: Range, ) -> Result { - // Authentication - check( - &request.connection_id, - gen_remote_fingerprint(&remote_addr), - cookie_valid_range, - )?; + Self::authenticate(remote_addr, request, cookie_valid_range)?; let info_hash = request.info_hash.into(); - let remote_client_ip = remote_addr.ip(); - // Authorization - self.whitelist_authorization.authorize(&info_hash).await?; + self.authorize(&info_hash).await?; + + let remote_client_ip = remote_addr.ip(); let mut peer = peer_builder::from_request(request, &remote_client_ip); - let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); - let original_peer_ip = peer.peer_addr.ip(); + let peers_wanted: PeersWanted = i32::from(request.peers_wanted.0).into(); - // The tracker could change the original peer ip let announce_data = self .announce_handler - .announce(&info_hash, &mut peer, &original_peer_ip, &peers_wanted) + .announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; - if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { - match original_peer_ip { - IpAddr::V4(_) => { - udp_stats_event_sender - .send_event(statistics::event::Event::Udp4Announce) - .await; - } - IpAddr::V6(_) => { - udp_stats_event_sender - .send_event(statistics::event::Event::Udp6Announce) - .await; - } - } - } + self.send_stats_event(remote_client_ip).await; Ok(announce_data) } + + fn authenticate( + remote_addr: SocketAddr, + request: &AnnounceRequest, + cookie_valid_range: Range, + ) -> Result { + check( + &request.connection_id, + gen_remote_fingerprint(&remote_addr), + cookie_valid_range, + ) + } + + async fn authorize(&self, info_hash: &InfoHash) -> Result<(), WhitelistError> { + self.whitelist_authorization.authorize(info_hash).await + } + + async fn send_stats_event(&self, peer_ip: IpAddr) { + if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { + let event = match peer_ip { + IpAddr::V4(_) => statistics::event::Event::Udp4Announce, + IpAddr::V6(_) => statistics::event::Event::Udp6Announce, + }; + + udp_stats_event_sender.send_event(event).await; + } + } } /// Errors related to announce requests. From 3c4dcdbc7857f48b512f16f70aa63073537ecaca Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 13:01:38 +0000 Subject: [PATCH 0857/1297] refactor: rearrange code --- .../udp-tracker-core/src/services/scrape.rs | 72 +++++++++---------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index fddc2ec2d..78c09ed94 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -20,42 +20,6 @@ use torrust_tracker_primitives::core::ScrapeData; use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; use crate::statistics; -/// Errors related to scrape requests. -#[derive(thiserror::Error, Debug, Clone)] -pub enum UdpScrapeError { - /// Error returned when there was an error with the connection cookie. - #[error("Connection cookie error: {source}")] - ConnectionCookieError { source: ConnectionCookieError }, - - /// Error returned when there was an error with the tracker core scrape handler. - #[error("Tracker core scrape error: {source}")] - TrackerCoreScrapeError { source: ScrapeError }, - - /// Error returned when there was an error with the tracker core whitelist. - #[error("Tracker core whitelist error: {source}")] - TrackerCoreWhitelistError { source: WhitelistError }, -} - -impl From for UdpScrapeError { - fn from(connection_cookie_error: ConnectionCookieError) -> Self { - Self::ConnectionCookieError { - source: connection_cookie_error, - } - } -} - -impl From for UdpScrapeError { - fn from(scrape_error: ScrapeError) -> Self { - Self::TrackerCoreScrapeError { source: scrape_error } - } -} - -impl From for UdpScrapeError { - fn from(whitelist_error: WhitelistError) -> Self { - Self::TrackerCoreWhitelistError { source: whitelist_error } - } -} - /// The `ScrapeService` is responsible for handling the `scrape` requests. pub struct ScrapeService { scrape_handler: Arc, @@ -111,3 +75,39 @@ impl ScrapeService { Ok(scrape_data) } } + +/// Errors related to scrape requests. +#[derive(thiserror::Error, Debug, Clone)] +pub enum UdpScrapeError { + /// Error returned when there was an error with the connection cookie. + #[error("Connection cookie error: {source}")] + ConnectionCookieError { source: ConnectionCookieError }, + + /// Error returned when there was an error with the tracker core scrape handler. + #[error("Tracker core scrape error: {source}")] + TrackerCoreScrapeError { source: ScrapeError }, + + /// Error returned when there was an error with the tracker core whitelist. + #[error("Tracker core whitelist error: {source}")] + TrackerCoreWhitelistError { source: WhitelistError }, +} + +impl From for UdpScrapeError { + fn from(connection_cookie_error: ConnectionCookieError) -> Self { + Self::ConnectionCookieError { + source: connection_cookie_error, + } + } +} + +impl From for UdpScrapeError { + fn from(scrape_error: ScrapeError) -> Self { + Self::TrackerCoreScrapeError { source: scrape_error } + } +} + +impl From for UdpScrapeError { + fn from(whitelist_error: WhitelistError) -> Self { + Self::TrackerCoreWhitelistError { source: whitelist_error } + } +} From f9a7bfd59b9d264e7a49aefb580b1340143d1612 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 13:18:17 +0000 Subject: [PATCH 0858/1297] refactor: [#1338] clean bittorrent_udp_tracker_core::services::scrape::ScrapeService --- .../udp-tracker-core/src/services/scrape.rs | 50 ++++++++++++------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index 78c09ed94..61301cd43 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -21,13 +21,16 @@ use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieEr use crate::statistics; /// The `ScrapeService` is responsible for handling the `scrape` requests. +/// +/// The service sends an statistics event that increments: +/// +/// - The number of UDP `scrape` requests handled by the UDP tracker. pub struct ScrapeService { scrape_handler: Arc, opt_udp_stats_event_sender: Arc>>, } impl ScrapeService { - /// Creates a new `ScrapeService`. #[must_use] pub fn new( scrape_handler: Arc, @@ -46,33 +49,46 @@ impl ScrapeService { /// It will return an error if the tracker core scrape handler returns an error. pub async fn handle_scrape( &self, - remote_addr: SocketAddr, + remote_client_addr: SocketAddr, request: &ScrapeRequest, cookie_valid_range: Range, ) -> Result { + Self::authenticate(remote_client_addr, request, cookie_valid_range)?; + + let scrape_data = self + .scrape_handler + .scrape(&Self::convert_from_aquatic(&request.info_hashes)) + .await?; + + self.send_stats_event(remote_client_addr).await; + + Ok(scrape_data) + } + + fn authenticate( + remote_addr: SocketAddr, + request: &ScrapeRequest, + cookie_valid_range: Range, + ) -> Result { check( &request.connection_id, gen_remote_fingerprint(&remote_addr), cookie_valid_range, - )?; - - // Convert from aquatic infohashes - let info_hashes: Vec = request.info_hashes.iter().map(|&x| x.into()).collect(); + ) + } - let scrape_data = self.scrape_handler.scrape(&info_hashes).await?; + fn convert_from_aquatic(aquatic_infohashes: &[aquatic_udp_protocol::common::InfoHash]) -> Vec { + aquatic_infohashes.iter().map(|&x| x.into()).collect() + } + async fn send_stats_event(&self, remote_addr: SocketAddr) { if let Some(udp_stats_event_sender) = self.opt_udp_stats_event_sender.as_deref() { - match remote_addr { - SocketAddr::V4(_) => { - udp_stats_event_sender.send_event(statistics::event::Event::Udp4Scrape).await; - } - SocketAddr::V6(_) => { - udp_stats_event_sender.send_event(statistics::event::Event::Udp6Scrape).await; - } - } + let event = match remote_addr { + SocketAddr::V4(_) => statistics::event::Event::Udp4Scrape, + SocketAddr::V6(_) => statistics::event::Event::Udp6Scrape, + }; + udp_stats_event_sender.send_event(event).await; } - - Ok(scrape_data) } } From aaf74446c12e789a53d72627709c263407510750 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 3 Mar 2025 18:18:12 +0000 Subject: [PATCH 0859/1297] chore: [#1345] add git hook scripts --- contrib/dev-tools/git/hooks/pre-commit.sh | 9 +++++++++ contrib/dev-tools/git/hooks/pre-push.sh | 10 ++++++++++ 2 files changed, 19 insertions(+) create mode 100755 contrib/dev-tools/git/hooks/pre-commit.sh create mode 100755 contrib/dev-tools/git/hooks/pre-push.sh diff --git a/contrib/dev-tools/git/hooks/pre-commit.sh b/contrib/dev-tools/git/hooks/pre-commit.sh new file mode 100755 index 000000000..37b80bb8a --- /dev/null +++ b/contrib/dev-tools/git/hooks/pre-commit.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +cargo +nightly fmt --check && + cargo +nightly check --tests --benches --examples --workspace --all-targets --all-features && + cargo +nightly doc --no-deps --bins --examples --workspace --all-features && + cargo +nightly machete && + cargo +stable build && + CARGO_INCREMENTAL=0 cargo +stable clippy --no-deps --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic && + cargo +stable test --tests --benches --examples --workspace --all-targets --all-features diff --git a/contrib/dev-tools/git/hooks/pre-push.sh b/contrib/dev-tools/git/hooks/pre-push.sh new file mode 100755 index 000000000..c1a724156 --- /dev/null +++ b/contrib/dev-tools/git/hooks/pre-push.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +cargo +nightly fmt --check && + cargo +nightly check --tests --benches --examples --workspace --all-targets --all-features && + cargo +nightly doc --no-deps --bins --examples --workspace --all-features && + cargo +nightly machete && + cargo +stable build && + CARGO_INCREMENTAL=0 cargo +stable clippy --no-deps --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic && + cargo +stable test --tests --benches --examples --workspace --all-targets --all-features && + cargo +stable run --bin e2e_tests_runner -- --config-toml-path "./share/default/config/tracker.e2e.container.sqlite3.toml" From ea802bf47f91ee0dea10b8b9e5d554526eca8268 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Mar 2025 07:25:19 +0000 Subject: [PATCH 0860/1297] chore(deps): udpate dependencies ``` cargo update Updating crates.io index Locking 32 packages to latest compatible versions Updating anyhow v1.0.96 -> v1.0.97 Updating async-compression v0.4.19 -> v0.4.20 Updating async-trait v0.1.86 -> v0.1.87 Updating bitflags v2.8.0 -> v2.9.0 Updating bytemuck v1.21.0 -> v1.22.0 Updating cc v1.2.15 -> v1.2.16 Updating httparse v1.10.0 -> v1.10.1 Updating itoa v1.0.14 -> v1.0.15 Updating pin-project v1.1.9 -> v1.1.10 Updating pin-project-internal v1.1.9 -> v1.1.10 Updating pkg-config v0.3.31 -> v0.3.32 Updating proc-macro2 v1.0.93 -> v1.0.94 Updating quote v1.0.38 -> v1.0.39 Updating rand_core v0.9.2 -> v0.9.3 Updating redox_syscall v0.5.9 -> v0.5.10 Updating rstest v0.24.0 -> v0.25.0 Updating rstest_macros v0.24.0 -> v0.25.0 Updating rustversion v1.0.19 -> v1.0.20 Updating ryu v1.0.19 -> v1.0.20 Updating semver v1.0.25 -> v1.0.26 Updating serde_bytes v0.11.15 -> v0.11.16 Updating serde_json v1.0.139 -> v1.0.140 Updating serde_path_to_error v0.1.16 -> v0.1.17 Updating serde_repr v0.1.19 -> v0.1.20 Updating syn v2.0.98 -> v2.0.99 Updating thiserror v2.0.11 -> v2.0.12 Updating thiserror-impl v2.0.11 -> v2.0.12 Updating tinyvec v1.8.1 -> v1.9.0 Updating tokio-rustls v0.26.1 -> v0.26.2 Updating unicode-ident v1.0.17 -> v1.0.18 Updating zerocopy v0.8.20 -> v0.8.21 Updating zerocopy-derive v0.8.20 -> v0.8.21 ``` --- Cargo.lock | 281 ++++++++++++++++++++++++++--------------------------- 1 file changed, 140 insertions(+), 141 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3e1cea83d..cb7ac4b80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -131,9 +131,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.96" +version = "1.0.97" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b964d184e89d9b6b67dd2715bc8e74cf3107fb2b529990c90cf517326150bf4" +checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" [[package]] name = "aquatic_peer_id" @@ -208,9 +208,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.19" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06575e6a9673580f52661c92107baabffbf41e2141373441cbcdc47cb733003c" +checksum = "310c9bcae737a48ef5cdee3174184e6d548b292739ede61a1f955ef76a738861" dependencies = [ "brotli", "flate2", @@ -316,13 +316,13 @@ checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" [[package]] name = "async-trait" -version = "0.1.86" +version = "0.1.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "644dd749086bf3771a2fbc5f256fdb982d53f011c7d5d560304eafeecebce79d" +checksum = "d556ec1359574147ec0c4fc5eb525f3f23263a592b1a9c07e0a75b427de55c97" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -444,7 +444,7 @@ checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -523,7 +523,7 @@ version = "0.71.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.0", "cexpr", "clang-sys", "itertools 0.13.0", @@ -532,7 +532,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -549,9 +549,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.8.0" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" +checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" [[package]] name = "bittorrent-http-tracker-core" @@ -563,7 +563,7 @@ dependencies = [ "bittorrent-tracker-core", "futures", "mockall", - "thiserror 2.0.11", + "thiserror 2.0.12", "tokio", "torrust-tracker-configuration", "torrust-tracker-primitives", @@ -583,7 +583,7 @@ dependencies = [ "percent-encoding", "serde", "serde_bencode", - "thiserror 2.0.11", + "thiserror 2.0.12", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-contrib-bencode", @@ -619,7 +619,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_repr", - "thiserror 2.0.11", + "thiserror 2.0.12", "tokio", "torrust-tracker-configuration", "torrust-tracker-located-error", @@ -645,7 +645,7 @@ dependencies = [ "serde", "serde_json", "testcontainers", - "thiserror 2.0.11", + "thiserror 2.0.12", "tokio", "torrust-rest-tracker-api-client", "torrust-tracker-clock", @@ -673,7 +673,7 @@ dependencies = [ "lazy_static", "mockall", "rand 0.9.0", - "thiserror 2.0.11", + "thiserror 2.0.12", "tokio", "torrust-tracker-configuration", "torrust-tracker-primitives", @@ -775,7 +775,7 @@ dependencies = [ "serde_json", "serde_repr", "serde_urlencoded", - "thiserror 2.0.11", + "thiserror 2.0.12", "tokio", "tokio-util", "tower-service", @@ -814,7 +814,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -883,9 +883,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.21.0" +version = "1.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef657dfab802224e671f5818e9a4935f9b1957ed18e58292690cc39e7a4092a3" +checksum = "b6b1fc10dbac614ebc03540c9dbd60e83887fda27794998c6528f1782047d540" [[package]] name = "byteorder" @@ -925,9 +925,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.15" +version = "1.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c736e259eea577f443d5c86c304f9f4ae0295c43f3ba05c21f1d66b5f06001af" +checksum = "be714c154be609ec7f5dad223a33bf1482fff90472de28f7362806e6d4832b8c" dependencies = [ "jobserver", "libc", @@ -1047,7 +1047,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -1278,7 +1278,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -1289,7 +1289,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -1333,7 +1333,7 @@ checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", "unicode-xid", ] @@ -1345,7 +1345,7 @@ checksum = "ccfae181bab5ab6c5478b2ccb69e4c68a02f8c3ec72f6616bfec9dbc599d2ee0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -1366,7 +1366,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -1603,7 +1603,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -1615,7 +1615,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -1627,7 +1627,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -1705,7 +1705,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -1934,9 +1934,9 @@ dependencies = [ [[package]] name = "httparse" -version = "1.10.0" +version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2d708df4e7140240a16cd6ab0ab65c972d7433ab77819ea693fde9c43811e2a" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] name = "httpdate" @@ -2185,7 +2185,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -2304,9 +2304,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.14" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "jobserver" @@ -2370,9 +2370,9 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.0", "libc", - "redox_syscall 0.5.9", + "redox_syscall 0.5.10", ] [[package]] @@ -2516,7 +2516,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -2566,7 +2566,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", "termcolor", "thiserror 1.0.69", ] @@ -2580,7 +2580,7 @@ dependencies = [ "base64 0.21.7", "bigdecimal", "bindgen", - "bitflags 2.8.0", + "bitflags 2.9.0", "bitvec", "btoi", "byteorder", @@ -2748,7 +2748,7 @@ version = "0.10.71" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e14130c6a98cd258fdcb0fb6d744152343ff729cbfcb28c656a9d12b999fbcd" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.0", "cfg-if", "foreign-types", "libc", @@ -2765,7 +2765,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -2816,7 +2816,7 @@ checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.9", + "redox_syscall 0.5.10", "smallvec", "windows-targets 0.52.6", ] @@ -2843,7 +2843,7 @@ dependencies = [ "regex", "regex-syntax", "structmeta", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -2866,7 +2866,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -2925,22 +2925,22 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfe2e71e1471fe07709406bf725f710b02927c9c54b2b5b2ec0e8087d97c327d" +checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6e859e6e5bd50440ab63c47e3ebabc90f26251f7c73c3d3e837b74a1cc3fa67" +checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -2968,9 +2968,9 @@ dependencies = [ [[package]] name = "pkg-config" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" [[package]] name = "plotters" @@ -3090,14 +3090,14 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] name = "proc-macro2" -version = "1.0.93" +version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" +checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" dependencies = [ "unicode-ident", ] @@ -3110,7 +3110,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", "version_check", "yansi", ] @@ -3148,9 +3148,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.38" +version = "1.0.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" +checksum = "c1f1914ce909e1658d9907913b4b91947430c7d9be598b15a1912935b8c04801" dependencies = [ "proc-macro2", ] @@ -3211,8 +3211,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" dependencies = [ "rand_chacha 0.9.0", - "rand_core 0.9.2", - "zerocopy 0.8.20", + "rand_core 0.9.3", + "zerocopy 0.8.21", ] [[package]] @@ -3232,7 +3232,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core 0.9.2", + "rand_core 0.9.3", ] [[package]] @@ -3246,12 +3246,11 @@ dependencies = [ [[package]] name = "rand_core" -version = "0.9.2" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a509b1a2ffbe92afab0e55c8fd99dea1c280e8171bd2d88682bb20bc41cbc2c" +checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ "getrandom 0.3.1", - "zerocopy 0.8.20", ] [[package]] @@ -3285,11 +3284,11 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.9" +version = "0.5.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82b568323e98e49e2a0899dcee453dd679fae22d69adf9b11dd508d1549b7e2f" +checksum = "0b8c0c260b63a8219631167be35e6a988e9554dbd323f8bd08439c8ed1302bd1" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.0", ] [[package]] @@ -3435,9 +3434,9 @@ dependencies = [ [[package]] name = "rstest" -version = "0.24.0" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e905296805ab93e13c1ec3a03f4b6c4f35e9498a3d5fa96dc626d22c03cd89" +checksum = "6fc39292f8613e913f7df8fa892b8944ceb47c247b78e1b1ae2f09e019be789d" dependencies = [ "futures-timer", "futures-util", @@ -3447,9 +3446,9 @@ dependencies = [ [[package]] name = "rstest_macros" -version = "0.24.0" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef0053bbffce09062bee4bcc499b0fbe7a57b879f1efe088d6d8d4c7adcdef9b" +checksum = "1f168d99749d307be9de54d23fd226628d99768225ef08f6ffb52e0182a27746" dependencies = [ "cfg-if", "glob", @@ -3459,7 +3458,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.98", + "syn 2.0.99", "unicode-ident", ] @@ -3469,7 +3468,7 @@ version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c6d5e5acb6f6129fe3f7ba0a7fc77bca1942cb568535e18e7bc40262baf3110" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.0", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -3520,7 +3519,7 @@ version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.0", "errno", "libc", "linux-raw-sys", @@ -3581,15 +3580,15 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.19" +version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4" +checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2" [[package]] name = "ryu" -version = "1.0.19" +version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea1a2d0a644769cc99faa24c3ad26b379b786fe7c36fd3c546254801650e6dd" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "same-file" @@ -3642,7 +3641,7 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.0", "core-foundation 0.9.4", "core-foundation-sys", "libc", @@ -3655,7 +3654,7 @@ version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "271720403f46ca04f7ba6f55d438f8bd878d6b8ca0a1046e8228c4145bcbb316" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.0", "core-foundation 0.10.0", "core-foundation-sys", "libc", @@ -3674,9 +3673,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.25" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f79dfe2d285b0488816f30e700a7438c5a73d816b5b7d3ac72fbc48b0d185e03" +checksum = "56e6fa9c48d24d85fb3de5ad847117517440f6beceb7798af16b4a87d616b8d0" [[package]] name = "serde" @@ -3699,9 +3698,9 @@ dependencies = [ [[package]] name = "serde_bytes" -version = "0.11.15" +version = "0.11.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "387cc504cb06bb40a96c8e04e951fe01854cf6bc921053c954e4a606d9675c6a" +checksum = "364fec0df39c49a083c9a8a18a23a6bcfd9af130fe9fe321d18520a0d113e09e" dependencies = [ "serde", ] @@ -3714,7 +3713,7 @@ checksum = "f09503e191f4e797cb8aac08e9a4a4695c5edf6a2e70e376d961ddd5c969f82b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -3732,9 +3731,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.139" +version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44f86c3acccc9c65b153fe1b85a3be07fe5515274ec9f0653b4a0875731c72a6" +checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" dependencies = [ "indexmap 2.7.1", "itoa", @@ -3745,9 +3744,9 @@ dependencies = [ [[package]] name = "serde_path_to_error" -version = "0.1.16" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af99884400da37c88f5e9146b7f1fd0fbcae8f6eec4e9da38b67d05486f814a6" +checksum = "59fab13f937fa393d08645bf3a84bdfe86e296747b506ada67bb15f10f218b2a" dependencies = [ "itoa", "serde", @@ -3755,13 +3754,13 @@ dependencies = [ [[package]] name = "serde_repr" -version = "0.1.19" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" +checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -3812,7 +3811,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -3925,7 +3924,7 @@ dependencies = [ "proc-macro2", "quote", "structmeta-derive", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -3936,7 +3935,7 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -3968,9 +3967,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.98" +version = "2.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1" +checksum = "e02e925281e18ffd9d640e234264753c43edc62d64b2d4cf898f1bc5e75f3fc2" dependencies = [ "proc-macro2", "quote", @@ -3994,7 +3993,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -4003,7 +4002,7 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.0", "core-foundation 0.9.4", "system-configuration-sys", ] @@ -4091,7 +4090,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.11", + "thiserror 2.0.12", "tokio", "tokio-stream", "tokio-tar", @@ -4110,11 +4109,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.11" +version = "2.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d452f284b73e6d76dd36758a0c8684b1d5be31f92b89d07fd5822175732206fc" +checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708" dependencies = [ - "thiserror-impl 2.0.11", + "thiserror-impl 2.0.12", ] [[package]] @@ -4125,18 +4124,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] name = "thiserror-impl" -version = "2.0.11" +version = "2.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2" +checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -4202,9 +4201,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.8.1" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "022db8904dfa342efe721985167e9fcd16c29b226db4397ed752a761cfce81e8" +checksum = "09b3661f17e86524eccd4371ab0429194e0d7c008abb45f7a7495b1719463c71" dependencies = [ "tinyvec_macros", ] @@ -4240,7 +4239,7 @@ checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -4255,9 +4254,9 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.26.1" +version = "0.26.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6d0975eaace0cf0fcadee4e4aaa5da15b5c079146f2cffb67c113be122bf37" +checksum = "8e727b36a1a0e8b74c376ac2211e40c2c8af09fb4013c60d910495810f008e9b" dependencies = [ "rustls", "tokio", @@ -4420,7 +4419,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.11", + "thiserror 2.0.12", "tokio", "torrust-axum-server", "torrust-rest-tracker-api-client", @@ -4449,7 +4448,7 @@ dependencies = [ "hyper", "hyper-util", "pin-project-lite", - "thiserror 2.0.11", + "thiserror 2.0.12", "tokio", "torrust-server-lib", "torrust-tracker-configuration", @@ -4465,7 +4464,7 @@ dependencies = [ "hyper", "reqwest", "serde", - "thiserror 2.0.11", + "thiserror 2.0.12", "url", "uuid", ] @@ -4546,7 +4545,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_json", - "thiserror 2.0.11", + "thiserror 2.0.12", "tokio", "torrust-tracker-configuration", "tracing", @@ -4574,7 +4573,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.11", + "thiserror 2.0.12", "toml", "torrust-tracker-located-error", "tracing", @@ -4588,14 +4587,14 @@ name = "torrust-tracker-contrib-bencode" version = "3.0.0-develop" dependencies = [ "criterion", - "thiserror 2.0.11", + "thiserror 2.0.12", ] [[package]] name = "torrust-tracker-located-error" version = "3.0.0-develop" dependencies = [ - "thiserror 2.0.11", + "thiserror 2.0.12", "tracing", ] @@ -4610,7 +4609,7 @@ dependencies = [ "serde", "tdyne-peer-id", "tdyne-peer-id-registry", - "thiserror 2.0.11", + "thiserror 2.0.12", "torrust-tracker-configuration", "zerocopy 0.7.35", ] @@ -4661,7 +4660,7 @@ dependencies = [ "mockall", "rand 0.9.0", "ringbuf", - "thiserror 2.0.11", + "thiserror 2.0.12", "tokio", "torrust-server-lib", "torrust-tracker-clock", @@ -4713,7 +4712,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "403fa3b783d4b626a8ad51d766ab03cb6d2dbfc46b1c5d4448395e6628dc9697" dependencies = [ "async-compression", - "bitflags 2.8.0", + "bitflags 2.9.0", "bytes", "futures-core", "http", @@ -4759,7 +4758,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -4844,9 +4843,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00e2473a93778eb0bad35909dff6a10d28e63f792f16ed15e404fca9d5eeedbe" +checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] name = "unicode-xid" @@ -4980,7 +4979,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", "wasm-bindgen-shared", ] @@ -5015,7 +5014,7 @@ checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -5278,7 +5277,7 @@ version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.0", ] [[package]] @@ -5339,7 +5338,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", "synstructure", ] @@ -5355,11 +5354,11 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.20" +version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dde3bb8c68a8f3f1ed4ac9221aad6b10cece3e60a8e2ea54a6a2dec806d0084c" +checksum = "dcf01143b2dd5d134f11f545cf9f1431b13b749695cb33bcce051e7568f99478" dependencies = [ - "zerocopy-derive 0.8.20", + "zerocopy-derive 0.8.21", ] [[package]] @@ -5370,18 +5369,18 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] name = "zerocopy-derive" -version = "0.8.20" +version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eea57037071898bf96a6da35fd626f4f27e9cee3ead2a6c703cf09d472b2e700" +checksum = "712c8386f4f4299382c9abee219bee7084f78fb939d88b6840fcc1320d5f6da2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] @@ -5401,7 +5400,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", "synstructure", ] @@ -5430,7 +5429,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.98", + "syn 2.0.99", ] [[package]] From bb96580a4bb175ecd0c31f8b9b5e5599477eca20 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Mar 2025 07:49:30 +0000 Subject: [PATCH 0861/1297] chore(deps): bump hex-literal from 0.4.1 to 1.0.0 --- Cargo.lock | 4 ++-- console/tracker-client/Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cb7ac4b80..4c7524f49 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1885,9 +1885,9 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "hex-literal" -version = "0.4.1" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" +checksum = "bcaaec4551594c969335c98c903c1397853d4198408ea609190f420500f6be71" [[package]] name = "home" diff --git a/console/tracker-client/Cargo.toml b/console/tracker-client/Cargo.toml index 4db6702cb..d4ab7c9e3 100644 --- a/console/tracker-client/Cargo.toml +++ b/console/tracker-client/Cargo.toml @@ -21,7 +21,7 @@ bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "../../packages/tracker-client" } clap = { version = "4", features = ["derive", "env"] } futures = "0" -hex-literal = "0" +hex-literal = "1" hyper = "1" reqwest = { version = "0", features = ["json"] } serde = { version = "1", features = ["derive"] } From 09396b5c647ee87218617f813325b564a71586fa Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Mar 2025 09:13:22 +0000 Subject: [PATCH 0862/1297] fix: issue generating coverage report There wass a missing feature for tokio crate in the `udp-tracker-core` package. ```output error[E0432]: unresolved import `tokio::time` --> packages/udp-tracker-core/src/services/banning.rs:22:12 | 22 | use tokio::time::Instant; | ^^^^ could not find `time` in `tokio` | note: found an item that was configured out --> /home/josecelano/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.43.0/src/lib.rs:556:13 | 556 | pub mod time; | ^^^^ note: the item is gated behind the `time` feature --> /home/josecelano/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.43.0/src/lib.rs:555:1 | 555 | / cfg_time! { 556 | | pub mod time; 557 | | } | |_^ = note: this error originates in the macro `cfg_time` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0433]: failed to resolve: could not find `time` in `tokio` --> packages/udp-tracker-core/src/services/banning.rs:40:53 | 40 | last_connection_id_errors_reset: tokio::time::Instant::now(), | ^^^^ could not find `time` in `tokio` | note: found an item that was configured out --> /home/josecelano/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.43.0/src/lib.rs:556:13 | 556 | pub mod time; | ^^^^ note: the item is gated behind the `time` feature --> /home/josecelano/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.43.0/src/lib.rs:555:1 | 555 | / cfg_time! { 556 | | pub mod time; 557 | | } | |_^ = note: this error originates in the macro `cfg_time` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider importing this struct | 18 + use std::time::Instant; | help: if you import `Instant`, refer to it directly | 40 - last_connection_id_errors_reset: tokio::time::Instant::now(), 40 + last_connection_id_errors_reset: Instant::now(), | Some errors have detailed explanations: E0432, E0433. For more information about an error, try `rustc --explain E0432`. error: could not compile `bittorrent-udp-tracker-core` (lib test) due to 2 previous errors error: process didn't exit successfully: `/home/josecelano/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/bin/cargo test --tests --manifest-path /home/josecelano/Documents/git/committer/me/github/torrust/torrust-tracker/Cargo.toml --target-dir /home/josecelano/Documents/git/committer/me/github/torrust/torrust-tracker/target/llvm-cov-target --package bittorrent-udp-tracker-core` (exit status: 101) ``` --- packages/udp-tracker-core/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml index 5f7622032..fc8e2328c 100644 --- a/packages/udp-tracker-core/Cargo.toml +++ b/packages/udp-tracker-core/Cargo.toml @@ -25,7 +25,7 @@ futures = "0" lazy_static = "1" rand = "0" thiserror = "2" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync", "time"] } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } tracing = "0" From 820329b924d92ba27c318271e6afc6bc4df98dc8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Mar 2025 16:42:43 +0000 Subject: [PATCH 0863/1297] refactor: [#1264] return wether swarm stats have change or not after upserting a peer When you upsert a new peer (announce requests) the swarm stats migth change if the peer announced that has completed the download. If that case we return `true` given the caller the opportunity to know if stats have changed. In the current implementation we get stats before and after upserintg the peer, and we compare them to check if they have changed. However stats migth have change due to a parallel (race condition) announce from another peer. This is the only way to know exactly if this announce request has altered the stats (incremented the number of downloads). --- .../src/environment.rs | 2 +- .../src/environment.rs | 2 +- .../torrent-repository/src/entry/single.rs | 2 + .../src/repository/dash_map_mutex_std.rs | 8 ++- .../torrent-repository/src/repository/mod.rs | 4 +- .../src/repository/rw_lock_std.rs | 4 +- .../src/repository/rw_lock_std_mutex_std.rs | 4 +- .../src/repository/rw_lock_std_mutex_tokio.rs | 4 +- .../src/repository/rw_lock_tokio.rs | 4 +- .../src/repository/rw_lock_tokio_mutex_std.rs | 4 +- .../repository/rw_lock_tokio_mutex_tokio.rs | 4 +- .../src/repository/skip_map_mutex_std.rs | 12 ++-- .../torrent-repository/tests/common/repo.rs | 2 +- packages/tracker-core/src/announce_handler.rs | 2 +- packages/tracker-core/src/torrent/manager.rs | 4 +- .../src/torrent/repository/in_memory.rs | 57 ++++++++++--------- packages/tracker-core/src/torrent/services.rs | 18 +++--- .../udp-tracker-server/src/environment.rs | 2 +- .../src/handlers/announce.rs | 4 +- .../udp-tracker-server/src/handlers/scrape.rs | 2 +- 20 files changed, 77 insertions(+), 68 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index 45cc276fd..97c91a8bf 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -22,7 +22,7 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let () = self + let _stats_updated = self .container .tracker_core_container .in_memory_torrent_repository diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index 2ee5cf744..9c15dd628 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -33,7 +33,7 @@ where { /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let () = self + let _stats_updated = self .container .tracker_core_container .in_memory_torrent_repository diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs index 7f8cfc4e6..27bf299bf 100644 --- a/packages/torrent-repository/src/entry/single.rs +++ b/packages/torrent-repository/src/entry/single.rs @@ -66,6 +66,8 @@ impl Entry for EntrySingle { } } _ => { + // `Started` event (first announced event) or + // `None` event (announcements done at regular intervals). drop(self.swarm.upsert(Arc::new(*peer))); } } diff --git a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs index 54a83aeb4..731280486 100644 --- a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs @@ -23,13 +23,15 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { if let Some(entry) = self.torrents.get(info_hash) { - entry.upsert_peer(peer); + entry.upsert_peer(peer) } else { let _unused = self.torrents.insert(*info_hash, Arc::default()); if let Some(entry) = self.torrents.get(info_hash) { - entry.upsert_peer(peer); + entry.upsert_peer(peer) + } else { + false } } } diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs index 14f03ed9d..bfb7f20f4 100644 --- a/packages/torrent-repository/src/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -24,7 +24,7 @@ pub trait Repository: Debug + Default + Sized + 'static { fn remove(&self, key: &InfoHash) -> Option; fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); fn remove_peerless_torrents(&self, policy: &TrackerPolicy); - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer); + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool; fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option; } @@ -37,6 +37,6 @@ pub trait RepositoryAsync: Debug + Default + Sized + 'static { fn remove(&self, key: &InfoHash) -> impl std::future::Future> + Send; fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> impl std::future::Future + Send; - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> impl std::future::Future + Send; + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> impl std::future::Future + Send; fn get_swarm_metadata(&self, info_hash: &InfoHash) -> impl std::future::Future> + Send; } diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs index 409a16498..2ff757654 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std.rs @@ -46,12 +46,12 @@ impl Repository for TorrentsRwLockStd where EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { let mut db = self.get_torrents_mut(); let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); - entry.upsert_peer(peer); + entry.upsert_peer(peer) } fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs index 8814f09ed..1f1155df5 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs @@ -33,7 +33,7 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { let maybe_entry = self.get_torrents().get(info_hash).cloned(); let entry = if let Some(entry) = maybe_entry { @@ -44,7 +44,7 @@ where entry.clone() }; - entry.upsert_peer(peer); + entry.upsert_peer(peer) } fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs index 46f4a9567..f8fd2871d 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs @@ -37,7 +37,7 @@ where EntryMutexTokio: EntryAsync, EntrySingle: Entry, { - async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { let maybe_entry = self.get_torrents().get(info_hash).cloned(); let entry = if let Some(entry) = maybe_entry { @@ -48,7 +48,7 @@ where entry.clone() }; - entry.upsert_peer(peer).await; + entry.upsert_peer(peer).await } async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs index ce6646e92..964149393 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio.rs @@ -47,12 +47,12 @@ impl RepositoryAsync for TorrentsRwLockTokio where EntrySingle: Entry, { - async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { let mut db = self.get_torrents_mut().await; let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); - entry.upsert_peer(peer); + entry.upsert_peer(peer) } async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs index 7efb093e9..c4541dea2 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs @@ -35,7 +35,7 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); let entry = if let Some(entry) = maybe_entry { @@ -46,7 +46,7 @@ where entry.clone() }; - entry.upsert_peer(peer); + entry.upsert_peer(peer) } async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs index e08a6af59..ff1e77cda 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -35,7 +35,7 @@ where EntryMutexTokio: EntryAsync, EntrySingle: Entry, { - async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); let entry = if let Some(entry) = maybe_entry { @@ -46,7 +46,7 @@ where entry.clone() }; - entry.upsert_peer(peer).await; + entry.upsert_peer(peer).await } async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index 47fe9620a..7a4e4afb9 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -23,9 +23,9 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); - entry.value().upsert_peer(peer); + entry.value().upsert_peer(peer) } fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { @@ -114,9 +114,9 @@ where EntryRwLockParkingLot: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); - entry.value().upsert_peer(peer); + entry.value().upsert_peer(peer) } fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { @@ -205,9 +205,9 @@ where EntryMutexParkingLot: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); - entry.value().upsert_peer(peer); + entry.value().upsert_peer(peer) } fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index c8412952c..809c59d2a 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -26,7 +26,7 @@ pub(crate) enum Repo { } impl Repo { - pub(crate) async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { + pub(crate) async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { match self { Repo::RwLockStd(repo) => repo.upsert_peer(info_hash, peer), Repo::RwLockStdMutexStd(repo) => repo.upsert_peer(info_hash, peer), diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index cb48a321a..db5a0ca5d 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -187,7 +187,7 @@ impl AnnounceHandler { fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { let swarm_metadata_before = self.in_memory_torrent_repository.get_swarm_metadata(info_hash); - self.in_memory_torrent_repository.upsert_peer(info_hash, peer); + let _stats_updated = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); let swarm_metadata_after = self.in_memory_torrent_repository.get_swarm_metadata(info_hash); diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index 51df97fb5..20074a5c9 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -195,7 +195,7 @@ mod tests { // Add a peer to the torrent let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let () = services.in_memory_torrent_repository.upsert_peer(&infohash, &peer); + let _stats_updated = services.in_memory_torrent_repository.upsert_peer(&infohash, &peer); // Simulate the time has passed 1 second more than the max peer timeout. clock::Stopped::local_add(&Duration::from_secs( @@ -212,7 +212,7 @@ mod tests { // Add a peer to the torrent let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let () = in_memory_torrent_repository.upsert_peer(infohash, &peer); + let _stats_updated = in_memory_torrent_repository.upsert_peer(infohash, &peer); // Remove the peer. The torrent is now peerless. in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 584feabc9..55f9c17b1 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -40,8 +40,13 @@ impl InMemoryTorrentRepository { /// /// * `info_hash` - The unique identifier of the torrent. /// * `peer` - The peer to insert or update in the torrent entry. - pub fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - self.torrents.upsert_peer(info_hash, peer); + /// + /// # Returns + /// + /// `true` if the peer stats were updated. + #[must_use] + pub fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + self.torrents.upsert_peer(info_hash, peer) } /// Removes a torrent entry from the repository. @@ -263,7 +268,7 @@ mod tests { let info_hash = sample_info_hash(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); assert!(in_memory_torrent_repository.get(&info_hash).is_some()); } @@ -274,8 +279,8 @@ mod tests { let info_hash = sample_info_hash(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); assert!(in_memory_torrent_repository.get(&info_hash).is_some()); } @@ -301,7 +306,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); @@ -334,7 +339,7 @@ mod tests { event: AnnounceEvent::Completed, }; - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); } let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); @@ -373,7 +378,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); @@ -388,7 +393,7 @@ mod tests { let excluded_peer = sample_peer(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer); // Add 74 peers for idx in 2..=75 { @@ -402,7 +407,7 @@ mod tests { event: AnnounceEvent::Completed, }; - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); } let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); @@ -430,7 +435,7 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let info_hash = sample_info_hash(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); let _unused = in_memory_torrent_repository.remove(&info_hash); @@ -445,7 +450,7 @@ mod tests { let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); // Cut off time is 1 second after the peer was updated in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); @@ -461,7 +466,7 @@ mod tests { // Insert a sample peer for the torrent to force adding the torrent entry let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let () = in_memory_torrent_repository.upsert_peer(info_hash, &peer); + let _stats_updated = in_memory_torrent_repository.upsert_peer(info_hash, &peer); // Remove the peer in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); @@ -525,7 +530,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); let torrent_entry = in_memory_torrent_repository.get(&info_hash).unwrap(); @@ -558,7 +563,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); let torrent_entries = in_memory_torrent_repository.get_paginated(None); @@ -600,12 +605,12 @@ mod tests { // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); // Get only the first page where page size is 1 let torrent_entries = @@ -636,12 +641,12 @@ mod tests { // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); // Get only the first page where page size is 1 let torrent_entries = @@ -672,12 +677,12 @@ mod tests { // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); // Get only the first page where page size is 1 let torrent_entries = @@ -722,7 +727,7 @@ mod tests { async fn it_should_return_the_torrent_metrics_when_there_is_a_leecher() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -741,7 +746,7 @@ mod tests { async fn it_should_return_the_torrent_metrics_when_there_is_a_seeder() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &seeder()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &seeder()); let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -760,7 +765,7 @@ mod tests { async fn it_should_return_the_torrent_metrics_when_there_is_a_completed_peer() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let () = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer()); let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -781,7 +786,7 @@ mod tests { let start_time = std::time::Instant::now(); for i in 0..1_000_000 { - let () = in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher()); } let result_a = start_time.elapsed(); @@ -817,7 +822,7 @@ mod tests { let infohash = sample_info_hash(); - let () = in_memory_torrent_repository.upsert_peer(&infohash, &leecher()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&infohash, &leecher()); let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata(&infohash); diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index 98d25ba47..2d072cf05 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -231,7 +231,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); let torrent_info = get_torrent_info(&in_memory_torrent_repository, &info_hash).unwrap(); @@ -275,7 +275,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); @@ -300,8 +300,8 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); - let () = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); let offset = 0; let limit = 1; @@ -321,8 +321,8 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); - let () = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); let offset = 1; let limit = 4000; @@ -347,11 +347,11 @@ mod tests { let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); @@ -399,7 +399,7 @@ mod tests { let info_hash = sample_info_hash(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _ = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); let torrent_info = get_torrents(&in_memory_torrent_repository, &[info_hash]); diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index c6ec98290..850e81d18 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -31,7 +31,7 @@ where /// Add a torrent to the tracker #[allow(dead_code)] pub fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let () = self + let _stats_updated = self .container .tracker_core_container .in_memory_torrent_repository diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 9269dadfe..071261164 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -366,7 +366,7 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv6); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv6); } async fn announce_a_new_peer_using_ipv4( @@ -677,7 +677,7 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) .into(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv4); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv4); } async fn announce_a_new_peer_using_ipv6( diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 3e6da4778..0adf10637 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -166,7 +166,7 @@ mod tests { .with_number_of_bytes_left(0) .into(); - let () = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer); + let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer); } fn build_scrape_request(remote_addr: &SocketAddr, info_hash: &InfoHash) -> ScrapeRequest { From c5db71a512df2f59e3b3ff7074acb86ad631144d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Mar 2025 17:01:55 +0000 Subject: [PATCH 0864/1297] refactor: [#1264] remove unnecessary fn call Now the `upsert_peer` fn returns `true`if the stats have changed. IN the other hand, stats migth have changed ebcuase there was a different paralell announce request (race condtions) so it migth not be needed. This removes unnecessary database queries to persits the stats. --- packages/tracker-core/src/announce_handler.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index db5a0ca5d..7903ae3e2 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -185,17 +185,15 @@ impl AnnounceHandler { /// returns the updated swarm stats. #[must_use] fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { - let swarm_metadata_before = self.in_memory_torrent_repository.get_swarm_metadata(info_hash); + let stats_updated = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); - let _stats_updated = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); + let swarm_metadata = self.in_memory_torrent_repository.get_swarm_metadata(info_hash); - let swarm_metadata_after = self.in_memory_torrent_repository.get_swarm_metadata(info_hash); - - if swarm_metadata_before != swarm_metadata_after { - self.persist_stats(info_hash, &swarm_metadata_after); + if stats_updated { + self.persist_stats(info_hash, &swarm_metadata); } - swarm_metadata_after + swarm_metadata } /// Persists torrent statistics to the database if persistence is enabled. From 2fb1c6f404499012119f01de0c31d6fd39aae78e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Mar 2025 18:37:24 +0000 Subject: [PATCH 0865/1297] reafactor: [#1264] add a DB methog to get the number of completed downloads for one torrent This will be used to preset the counter from the database when a noew torrent entry is added to the torrent repo after begin removing for a while (peerless torrents are removed). The process is: - A new torrent is announced and added to the torrent repo. - The downloads counter is 0. - One of the peers finishes downloading and the counter increases to 1. - The torrent is removed from the repo becuase none of the peer announce for a while. - A new peer announce the torrent. We have to preset the counter to 1 even if that peer has not completed downloading yet. --- .../tracker-core/src/databases/driver/mod.rs | 13 +++++++++++++ .../tracker-core/src/databases/driver/mysql.rs | 16 +++++++++++++++- .../src/databases/driver/sqlite.rs | 18 +++++++++++++++++- packages/tracker-core/src/databases/mod.rs | 13 +++++++++++-- .../src/torrent/repository/persisted.rs | 15 ++++++++++++++- 5 files changed, 70 insertions(+), 5 deletions(-) diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index 06e912f7c..bd15f8e27 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -98,6 +98,7 @@ pub(crate) mod tests { // Persistent torrents (stats) handling_torrent_persistence::it_should_save_and_load_persistent_torrents(driver); + handling_torrent_persistence::it_should_load_all_persistent_torrents(driver); // Authentication keys (for private trackers) @@ -159,6 +160,18 @@ pub(crate) mod tests { driver.save_persistent_torrent(&infohash, number_of_downloads).unwrap(); + let number_of_downloads = driver.load_persistent_torrent(&infohash).unwrap().unwrap(); + + assert_eq!(number_of_downloads, 1); + } + + pub fn it_should_load_all_persistent_torrents(driver: &Arc>) { + let infohash = sample_info_hash(); + + let number_of_downloads = 1; + + driver.save_persistent_torrent(&infohash, number_of_downloads).unwrap(); + let torrents = driver.load_persistent_torrents().unwrap(); assert_eq!(torrents.len(), 1); diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index 6f7deb2b9..c2cf24bb1 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -13,7 +13,7 @@ use r2d2::Pool; use r2d2_mysql::mysql::prelude::Queryable; use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MySqlConnectionManager; -use torrust_tracker_primitives::PersistentTorrents; +use torrust_tracker_primitives::{PersistentTorrent, PersistentTorrents}; use super::{Database, Driver, Error}; use crate::authentication::key::AUTH_KEY_LENGTH; @@ -129,6 +129,20 @@ impl Database for Mysql { Ok(torrents.iter().copied().collect()) } + /// Refer to [`databases::Database::load_persistent_torrent`](crate::core::databases::Database::load_persistent_torrent). + fn load_persistent_torrent(&self, info_hash: &InfoHash) -> Result, Error> { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let query = conn.exec_first::( + "SELECT completed FROM torrents WHERE info_hash = :info_hash", + params! { "info_hash" => info_hash.to_hex_string() }, + ); + + let persistent_torrent = query?; + + Ok(persistent_torrent) + } + /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). fn load_keys(&self) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs index bab2fb6a7..d9a2fc8d8 100644 --- a/packages/tracker-core/src/databases/driver/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -13,7 +13,7 @@ use r2d2::Pool; use r2d2_sqlite::rusqlite::params; use r2d2_sqlite::rusqlite::types::Null; use r2d2_sqlite::SqliteConnectionManager; -use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::{Database, Driver, Error}; use crate::authentication::{self, Key}; @@ -125,6 +125,22 @@ impl Database for Sqlite { Ok(torrent_iter.filter_map(std::result::Result::ok).collect()) } + /// Refer to [`databases::Database::load_persistent_torrent`](crate::core::databases::Database::load_persistent_torrent). + fn load_persistent_torrent(&self, info_hash: &InfoHash) -> Result, Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let mut stmt = conn.prepare("SELECT completed FROM torrents WHERE info_hash = ?")?; + + let mut rows = stmt.query([info_hash.to_hex_string()])?; + + let persistent_torrent = rows.next()?; + + Ok(persistent_torrent.map(|f| { + let completed: i64 = f.get(0).unwrap(); + u32::try_from(completed).unwrap() + })) + } + /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). fn load_keys(&self) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs index 33a7e3c69..1ffeb518f 100644 --- a/packages/tracker-core/src/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -52,7 +52,7 @@ pub mod setup; use bittorrent_primitives::info_hash::InfoHash; use mockall::automock; -use torrust_tracker_primitives::PersistentTorrents; +use torrust_tracker_primitives::{PersistentTorrent, PersistentTorrents}; use self::error::Error; use crate::authentication::{self, Key}; @@ -90,7 +90,7 @@ pub trait Database: Sync + Send { // Torrent Metrics - /// Loads torrent metrics data from the database. + /// Loads torrent metrics data from the database for all torrents. /// /// This function returns the persistent torrent metrics as a collection of /// tuples, where each tuple contains an [`InfoHash`] and the `downloaded` @@ -103,6 +103,15 @@ pub trait Database: Sync + Send { /// Returns an [`Error`] if the metrics cannot be loaded. fn load_persistent_torrents(&self) -> Result; + /// Loads torrent metrics data from the database for one torrent. + /// + /// # Context: Torrent Metrics + /// + /// # Errors + /// + /// Returns an [`Error`] if the metrics cannot be loaded. + fn load_persistent_torrent(&self, info_hash: &InfoHash) -> Result, Error>; + /// Saves torrent metrics data into the database. /// /// # Arguments diff --git a/packages/tracker-core/src/torrent/repository/persisted.rs b/packages/tracker-core/src/torrent/repository/persisted.rs index 694a2fe7c..89d931bb2 100644 --- a/packages/tracker-core/src/torrent/repository/persisted.rs +++ b/packages/tracker-core/src/torrent/repository/persisted.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::PersistentTorrents; +use torrust_tracker_primitives::{PersistentTorrent, PersistentTorrents}; use crate::databases::error::Error; use crate::databases::Database; @@ -59,6 +59,19 @@ impl DatabasePersistentTorrentRepository { self.database.load_persistent_torrents() } + /// Loads one persistent torrent metrics from the database. + /// + /// This function retrieves the torrent metrics (e.g., download counts) from the persistent store + /// and returns them as a [`PersistentTorrents`] map. + /// + /// # Errors + /// + /// Returns an [`Error`] if the underlying database query fails. + #[allow(dead_code)] + pub(crate) fn load(&self, info_hash: &InfoHash) -> Result, Error> { + self.database.load_persistent_torrent(info_hash) + } + /// Saves the persistent torrent metric into the database. /// /// This function stores or updates the download count for the torrent From 8a4dba3cbf7e221dd51fb4199e65b12d33143a1f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 4 Mar 2025 18:58:40 +0000 Subject: [PATCH 0866/1297] refactor: [#1264] rename variables --- .../src/environment.rs | 2 +- .../src/environment.rs | 2 +- .../torrent-repository/src/entry/single.rs | 6 +-- packages/tracker-core/src/announce_handler.rs | 4 +- packages/tracker-core/src/torrent/manager.rs | 4 +- .../src/torrent/repository/in_memory.rs | 50 ++++++++++--------- packages/tracker-core/src/torrent/services.rs | 16 +++--- .../udp-tracker-server/src/environment.rs | 2 +- .../src/handlers/announce.rs | 6 ++- .../udp-tracker-server/src/handlers/scrape.rs | 2 +- 10 files changed, 49 insertions(+), 45 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index 97c91a8bf..b7cabad0e 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -22,7 +22,7 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let _stats_updated = self + let _number_of_downloads_increased = self .container .tracker_core_container .in_memory_torrent_repository diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index 9c15dd628..f130e24f0 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -33,7 +33,7 @@ where { /// Add a torrent to the tracker pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let _stats_updated = self + let _number_of_downloads_increased = self .container .tracker_core_container .in_memory_torrent_repository diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs index 27bf299bf..0f922bd02 100644 --- a/packages/torrent-repository/src/entry/single.rs +++ b/packages/torrent-repository/src/entry/single.rs @@ -51,7 +51,7 @@ impl Entry for EntrySingle { } fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { - let mut downloaded_stats_updated: bool = false; + let mut number_of_downloads_increased: bool = false; match peer::ReadInfo::get_event(peer) { AnnounceEvent::Stopped => { @@ -62,7 +62,7 @@ impl Entry for EntrySingle { // Don't count if peer was not previously known and not already completed. if previous.is_some_and(|p| p.event != AnnounceEvent::Completed) { self.downloaded += 1; - downloaded_stats_updated = true; + number_of_downloads_increased = true; } } _ => { @@ -72,7 +72,7 @@ impl Entry for EntrySingle { } } - downloaded_stats_updated + number_of_downloads_increased } fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 7903ae3e2..28d3b252f 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -185,11 +185,11 @@ impl AnnounceHandler { /// returns the updated swarm stats. #[must_use] fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { - let stats_updated = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); + let number_of_downloads_increased = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); let swarm_metadata = self.in_memory_torrent_repository.get_swarm_metadata(info_hash); - if stats_updated { + if number_of_downloads_increased { self.persist_stats(info_hash, &swarm_metadata); } diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index 20074a5c9..e4691a86f 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -195,7 +195,7 @@ mod tests { // Add a peer to the torrent let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _stats_updated = services.in_memory_torrent_repository.upsert_peer(&infohash, &peer); + let _number_of_downloads_increased = services.in_memory_torrent_repository.upsert_peer(&infohash, &peer); // Simulate the time has passed 1 second more than the max peer timeout. clock::Stopped::local_add(&Duration::from_secs( @@ -212,7 +212,7 @@ mod tests { // Add a peer to the torrent let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _stats_updated = in_memory_torrent_repository.upsert_peer(infohash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(infohash, &peer); // Remove the peer. The torrent is now peerless. in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 55f9c17b1..bec28bcc0 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -268,7 +268,7 @@ mod tests { let info_hash = sample_info_hash(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); assert!(in_memory_torrent_repository.get(&info_hash).is_some()); } @@ -279,8 +279,8 @@ mod tests { let info_hash = sample_info_hash(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); assert!(in_memory_torrent_repository.get(&info_hash).is_some()); } @@ -306,7 +306,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); @@ -339,7 +339,7 @@ mod tests { event: AnnounceEvent::Completed, }; - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); } let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); @@ -378,7 +378,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); @@ -393,7 +393,7 @@ mod tests { let excluded_peer = sample_peer(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer); // Add 74 peers for idx in 2..=75 { @@ -407,7 +407,7 @@ mod tests { event: AnnounceEvent::Completed, }; - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); } let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); @@ -435,7 +435,7 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let info_hash = sample_info_hash(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); let _unused = in_memory_torrent_repository.remove(&info_hash); @@ -450,7 +450,7 @@ mod tests { let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); // Cut off time is 1 second after the peer was updated in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); @@ -466,7 +466,7 @@ mod tests { // Insert a sample peer for the torrent to force adding the torrent entry let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _stats_updated = in_memory_torrent_repository.upsert_peer(info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(info_hash, &peer); // Remove the peer in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); @@ -530,7 +530,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); let torrent_entry = in_memory_torrent_repository.get(&info_hash).unwrap(); @@ -563,7 +563,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); let torrent_entries = in_memory_torrent_repository.get_paginated(None); @@ -605,12 +605,12 @@ mod tests { // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); // Get only the first page where page size is 1 let torrent_entries = @@ -641,12 +641,12 @@ mod tests { // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); // Get only the first page where page size is 1 let torrent_entries = @@ -677,12 +677,12 @@ mod tests { // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); // Get only the first page where page size is 1 let torrent_entries = @@ -727,7 +727,7 @@ mod tests { async fn it_should_return_the_torrent_metrics_when_there_is_a_leecher() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -746,7 +746,7 @@ mod tests { async fn it_should_return_the_torrent_metrics_when_there_is_a_seeder() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &seeder()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &seeder()); let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -765,7 +765,8 @@ mod tests { async fn it_should_return_the_torrent_metrics_when_there_is_a_completed_peer() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer()); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer()); let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -786,7 +787,8 @@ mod tests { let start_time = std::time::Instant::now(); for i in 0..1_000_000 { - let _stats_updated = in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher()); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher()); } let result_a = start_time.elapsed(); @@ -822,7 +824,7 @@ mod tests { let infohash = sample_info_hash(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&infohash, &leecher()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&infohash, &leecher()); let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata(&infohash); diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index 2d072cf05..1d06b2945 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -231,7 +231,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); let torrent_info = get_torrent_info(&in_memory_torrent_repository, &info_hash).unwrap(); @@ -275,7 +275,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); @@ -300,8 +300,8 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); let offset = 0; let limit = 1; @@ -321,8 +321,8 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); let offset = 1; let limit = 4000; @@ -347,11 +347,11 @@ mod tests { let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 850e81d18..a04773134 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -31,7 +31,7 @@ where /// Add a torrent to the tracker #[allow(dead_code)] pub fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let _stats_updated = self + let _number_of_downloads_increased = self .container .tracker_core_container .in_memory_torrent_repository diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 071261164..c30101678 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -366,7 +366,8 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv6); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv6); } async fn announce_a_new_peer_using_ipv4( @@ -677,7 +678,8 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) .into(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv4); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv4); } async fn announce_a_new_peer_using_ipv6( diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 0adf10637..fb17ecc97 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -166,7 +166,7 @@ mod tests { .with_number_of_bytes_left(0) .into(); - let _stats_updated = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer); } fn build_scrape_request(remote_addr: &SocketAddr, info_hash: &InfoHash) -> ScrapeRequest { From 6beec3a01cf3623cb89cdd9fadafd8ad6da88041 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 5 Mar 2025 07:52:03 +0000 Subject: [PATCH 0867/1297] refactor: [#1264] add a database method to increase the number of downloads for a torrent --- .../tracker-core/src/databases/driver/mod.rs | 15 +++++ .../src/databases/driver/mysql.rs | 38 ++++++++----- .../src/databases/driver/sqlite.rs | 57 ++++++++++++------- packages/tracker-core/src/databases/error.rs | 9 +++ packages/tracker-core/src/databases/mod.rs | 13 +++++ 5 files changed, 100 insertions(+), 32 deletions(-) diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index bd15f8e27..2cedab2d7 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -99,6 +99,7 @@ pub(crate) mod tests { handling_torrent_persistence::it_should_save_and_load_persistent_torrents(driver); handling_torrent_persistence::it_should_load_all_persistent_torrents(driver); + handling_torrent_persistence::it_should_increase_the_number_of_downloads_for_a_given_torrent(driver); // Authentication keys (for private trackers) @@ -177,6 +178,20 @@ pub(crate) mod tests { assert_eq!(torrents.len(), 1); assert_eq!(torrents.get(&infohash), Some(number_of_downloads).as_ref()); } + + pub fn it_should_increase_the_number_of_downloads_for_a_given_torrent(driver: &Arc>) { + let infohash = sample_info_hash(); + + let number_of_downloads = 1; + + driver.save_persistent_torrent(&infohash, number_of_downloads).unwrap(); + + driver.increase_number_of_downloads(&infohash).unwrap(); + + let number_of_downloads = driver.load_persistent_torrent(&infohash).unwrap().unwrap(); + + assert_eq!(number_of_downloads, 2); + } } mod handling_authentication_keys { diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index c2cf24bb1..d07f061c2 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -143,6 +143,31 @@ impl Database for Mysql { Ok(persistent_torrent) } + /// Refer to [`databases::Database::save_persistent_torrent`](crate::core::databases::Database::save_persistent_torrent). + fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { + const COMMAND : &str = "INSERT INTO torrents (info_hash, completed) VALUES (:info_hash_str, :completed) ON DUPLICATE KEY UPDATE completed = VALUES(completed)"; + + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let info_hash_str = info_hash.to_string(); + + Ok(conn.exec_drop(COMMAND, params! { info_hash_str, completed })?) + } + + /// Refer to [`databases::Database::increase_number_of_downloads`](crate::core::databases::Database::increase_number_of_downloads). + fn increase_number_of_downloads(&self, info_hash: &InfoHash) -> Result<(), Error> { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let info_hash_str = info_hash.to_string(); + + conn.exec_drop( + "UPDATE torrents SET completed = completed + 1 WHERE info_hash = :info_hash_str", + params! { info_hash_str }, + )?; + + Ok(()) + } + /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). fn load_keys(&self) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -175,19 +200,6 @@ impl Database for Mysql { Ok(info_hashes) } - /// Refer to [`databases::Database::save_persistent_torrent`](crate::core::databases::Database::save_persistent_torrent). - fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { - const COMMAND : &str = "INSERT INTO torrents (info_hash, completed) VALUES (:info_hash_str, :completed) ON DUPLICATE KEY UPDATE completed = VALUES(completed)"; - - let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let info_hash_str = info_hash.to_string(); - - tracing::debug!("{}", info_hash_str); - - Ok(conn.exec_drop(COMMAND, params! { info_hash_str, completed })?) - } - /// Refer to [`databases::Database::get_info_hash_from_whitelist`](crate::core::databases::Database::get_info_hash_from_whitelist). fn get_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs index d9a2fc8d8..ffcef3d96 100644 --- a/packages/tracker-core/src/databases/driver/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -141,6 +141,44 @@ impl Database for Sqlite { })) } + /// Refer to [`databases::Database::save_persistent_torrent`](crate::core::databases::Database::save_persistent_torrent). + fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let insert = conn.execute( + "INSERT INTO torrents (info_hash, completed) VALUES (?1, ?2) ON CONFLICT(info_hash) DO UPDATE SET completed = ?2", + [info_hash.to_string(), completed.to_string()], + )?; + + if insert == 0 { + Err(Error::InsertFailed { + location: Location::caller(), + driver: DRIVER, + }) + } else { + Ok(()) + } + } + + /// Refer to [`databases::Database::increase_number_of_downloads`](crate::core::databases::Database::increase_number_of_downloads). + fn increase_number_of_downloads(&self, info_hash: &InfoHash) -> Result<(), Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let update = conn.execute( + "UPDATE torrents SET completed = completed + 1 WHERE info_hash = ?", + [info_hash.to_string()], + )?; + + if update == 0 { + Err(Error::UpdateFailed { + location: Location::caller(), + driver: DRIVER, + }) + } else { + Ok(()) + } + } + /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). fn load_keys(&self) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -185,25 +223,6 @@ impl Database for Sqlite { Ok(info_hashes) } - /// Refer to [`databases::Database::save_persistent_torrent`](crate::core::databases::Database::save_persistent_torrent). - fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { - let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - - let insert = conn.execute( - "INSERT INTO torrents (info_hash, completed) VALUES (?1, ?2) ON CONFLICT(info_hash) DO UPDATE SET completed = ?2", - [info_hash.to_string(), completed.to_string()], - )?; - - if insert == 0 { - Err(Error::InsertFailed { - location: Location::caller(), - driver: DRIVER, - }) - } else { - Ok(()) - } - } - /// Refer to [`databases::Database::get_info_hash_from_whitelist`](crate::core::databases::Database::get_info_hash_from_whitelist). fn get_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; diff --git a/packages/tracker-core/src/databases/error.rs b/packages/tracker-core/src/databases/error.rs index fd9adfc22..2df2cb277 100644 --- a/packages/tracker-core/src/databases/error.rs +++ b/packages/tracker-core/src/databases/error.rs @@ -49,6 +49,15 @@ pub enum Error { driver: Driver, }, + /// Indicates a failure to update a record into the database. + /// + /// This error is raised when an insertion operation fails. + #[error("Unable to update record into {driver} database, {location}")] + UpdateFailed { + location: &'static Location<'static>, + driver: Driver, + }, + /// Indicates a failure to delete a record from the database. /// /// This error includes an error code that may be returned by the database diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs index 1ffeb518f..fae2ce527 100644 --- a/packages/tracker-core/src/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -126,6 +126,19 @@ pub trait Database: Sync + Send { /// Returns an [`Error`] if the metrics cannot be saved. fn save_persistent_torrent(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error>; + /// Increases the number of downloads for a given torrent. + /// + /// # Arguments + /// + /// * `info_hash` - A reference to the torrent's info hash. + /// + /// # Context: Torrent Metrics + /// + /// # Errors + /// + /// Returns an [`Error`] if the query failed. + fn increase_number_of_downloads(&self, info_hash: &InfoHash) -> Result<(), Error>; + // Whitelist /// Loads the whitelisted torrents from the database. From 8f67f129fbe4a4c917b986d0b0eabc947f334906 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 5 Mar 2025 08:41:12 +0000 Subject: [PATCH 0868/1297] fix: [#1264] partially. The correct number of downloads is persited However, we still have to load the value counter from the database the first time the otrrent is added to the repository. --- packages/tracker-core/src/announce_handler.rs | 45 ++++++------------- .../src/databases/driver/sqlite.rs | 11 +---- packages/tracker-core/src/databases/mod.rs | 3 ++ packages/tracker-core/src/error.rs | 4 ++ .../src/torrent/repository/persisted.rs | 34 +++++++++++++- 5 files changed, 56 insertions(+), 41 deletions(-) diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 28d3b252f..e125adb66 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -97,7 +97,6 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::{Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use super::torrent::repository::in_memory::InMemoryTorrentRepository; use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; @@ -164,45 +163,29 @@ impl AnnounceHandler { ) -> Result { self.whitelist_authorization.authorize(info_hash).await?; - tracing::debug!("Before: {peer:?}"); peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); - tracing::debug!("After: {peer:?}"); - let stats = self.upsert_peer_and_get_stats(info_hash, peer); - - let peers = self - .in_memory_torrent_repository - .get_peers_for(info_hash, peer, peers_wanted.limit()); - - Ok(AnnounceData { - peers, - stats, - policy: self.config.announce_policy, - }) - } - - /// Updates the torrent data in memory, persists statistics if needed, and - /// returns the updated swarm stats. - #[must_use] - fn upsert_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> SwarmMetadata { let number_of_downloads_increased = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); - let swarm_metadata = self.in_memory_torrent_repository.get_swarm_metadata(info_hash); - - if number_of_downloads_increased { - self.persist_stats(info_hash, &swarm_metadata); + if self.config.tracker_policy.persistent_torrent_completed_stat && number_of_downloads_increased { + self.db_torrent_repository.increase_number_of_downloads(info_hash)?; } - swarm_metadata + Ok(self.build_announce_data(info_hash, peer, peers_wanted)) } - /// Persists torrent statistics to the database if persistence is enabled. - fn persist_stats(&self, info_hash: &InfoHash, swarm_metadata: &SwarmMetadata) { - if self.config.tracker_policy.persistent_torrent_completed_stat { - let completed = swarm_metadata.downloaded; - let info_hash = *info_hash; + /// Builds the announce data for the peer making the request. + fn build_announce_data(&self, info_hash: &InfoHash, peer: &peer::Peer, peers_wanted: &PeersWanted) -> AnnounceData { + let peers = self + .in_memory_torrent_repository + .get_peers_for(info_hash, peer, peers_wanted.limit()); - drop(self.db_torrent_repository.save(&info_hash, completed)); + let swarm_metadata = self.in_memory_torrent_repository.get_swarm_metadata(info_hash); + + AnnounceData { + peers, + stats: swarm_metadata, + policy: self.config.announce_policy, } } } diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs index ffcef3d96..d36f24f8b 100644 --- a/packages/tracker-core/src/databases/driver/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -164,19 +164,12 @@ impl Database for Sqlite { fn increase_number_of_downloads(&self, info_hash: &InfoHash) -> Result<(), Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; - let update = conn.execute( + let _ = conn.execute( "UPDATE torrents SET completed = completed + 1 WHERE info_hash = ?", [info_hash.to_string()], )?; - if update == 0 { - Err(Error::UpdateFailed { - location: Location::caller(), - driver: DRIVER, - }) - } else { - Ok(()) - } + Ok(()) } /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs index fae2ce527..2703ab8bf 100644 --- a/packages/tracker-core/src/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -128,6 +128,9 @@ pub trait Database: Sync + Send { /// Increases the number of downloads for a given torrent. /// + /// It does not create a new entry if the torrent is not found and it does + /// not return an error. + /// /// # Arguments /// /// * `info_hash` - A reference to the torrent's info hash. diff --git a/packages/tracker-core/src/error.rs b/packages/tracker-core/src/error.rs index 0b94483eb..4a35e9a0b 100644 --- a/packages/tracker-core/src/error.rs +++ b/packages/tracker-core/src/error.rs @@ -66,6 +66,10 @@ pub enum AnnounceError { /// Wraps errors related to torrent whitelisting. #[error("Whitelist error: {0}")] Whitelist(#[from] WhitelistError), + + /// Wraps errors related to database. + #[error("Database error: {0}")] + Database(#[from] databases::error::Error), } /// Errors related to scrape requests. diff --git a/packages/tracker-core/src/torrent/repository/persisted.rs b/packages/tracker-core/src/torrent/repository/persisted.rs index 89d931bb2..dec571baf 100644 --- a/packages/tracker-core/src/torrent/repository/persisted.rs +++ b/packages/tracker-core/src/torrent/repository/persisted.rs @@ -47,6 +47,26 @@ impl DatabasePersistentTorrentRepository { } } + /// Increases the number of downloads for a given torrent. + /// + /// If the torrent is not found, it creates a new entry. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// + /// # Errors + /// + /// Returns an [`Error`] if the database operation fails. + pub(crate) fn increase_number_of_downloads(&self, info_hash: &InfoHash) -> Result<(), Error> { + let torrent = self.load(info_hash)?; + + match torrent { + Some(_number_of_downloads) => self.database.increase_number_of_downloads(info_hash), + None => self.save(info_hash, 1), + } + } + /// Loads all persistent torrent metrics from the database. /// /// This function retrieves the torrent metrics (e.g., download counts) from the persistent store @@ -67,7 +87,6 @@ impl DatabasePersistentTorrentRepository { /// # Errors /// /// Returns an [`Error`] if the underlying database query fails. - #[allow(dead_code)] pub(crate) fn load(&self, info_hash: &InfoHash) -> Result, Error> { self.database.load_persistent_torrent(info_hash) } @@ -118,6 +137,19 @@ mod tests { assert_eq!(torrents.get(&infohash), Some(1).as_ref()); } + #[test] + fn it_increases_the_numbers_of_downloads_for_a_torrent_into_the_database() { + let repository = initialize_db_persistent_torrent_repository(); + + let infohash = sample_info_hash(); + + repository.increase_number_of_downloads(&infohash).unwrap(); + + let torrents = repository.load_all().unwrap(); + + assert_eq!(torrents.get(&infohash), Some(1).as_ref()); + } + #[test] fn it_loads_the_numbers_of_downloads_for_all_torrents_from_the_database() { let repository = initialize_db_persistent_torrent_repository(); From 06ef1d5fc6e3f0f06869d94e2b5e963bb6fa5fca Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 5 Mar 2025 13:10:28 +0000 Subject: [PATCH 0869/1297] fix: [#1264] number of downloads preset when torrent is persisted This fixed a bug: the number of donwloads for a torrent is not loaded from the database when the torrent is added to the in-memory torrent repository. It should be done when stats are enabled with the configuration option: persistent_torrent_completed_stat = true The patch is applied only to the torrent repository implementation we are using in prodcution (`CrossbeamSkipList`). The other implementations have this comment: ``` // todo: load persistent torrent data if provided ``` It was not implemented for the others becuase I'm considering taking the counter (for the number of downloads) out of the in-memory repository. And increase it by suing events triggered from the core tracker. I will open a new issue for that. If that's implemented we will need to remove this patch for the repository, meaning reverting cahnges in this commit. --- .../src/environment.rs | 2 +- .../src/environment.rs | 2 +- .../benches/helpers/asyn.rs | 12 ++-- .../benches/helpers/sync.rs | 12 ++-- .../src/repository/dash_map_mutex_std.rs | 6 +- .../torrent-repository/src/repository/mod.rs | 11 ++- .../src/repository/rw_lock_std.rs | 6 +- .../src/repository/rw_lock_std_mutex_std.rs | 6 +- .../src/repository/rw_lock_std_mutex_tokio.rs | 11 ++- .../src/repository/rw_lock_tokio.rs | 11 ++- .../src/repository/rw_lock_tokio_mutex_std.rs | 11 ++- .../repository/rw_lock_tokio_mutex_tokio.rs | 11 ++- .../src/repository/skip_map_mutex_std.rs | 49 +++++++++++-- .../torrent-repository/tests/common/repo.rs | 29 ++++---- .../tests/repository/mod.rs | 4 +- packages/tracker-core/src/announce_handler.rs | 10 ++- packages/tracker-core/src/torrent/manager.rs | 4 +- .../src/torrent/repository/in_memory.rs | 68 +++++++++++-------- packages/tracker-core/src/torrent/services.rs | 18 ++--- .../udp-tracker-server/src/environment.rs | 2 +- .../src/handlers/announce.rs | 4 +- .../udp-tracker-server/src/handlers/scrape.rs | 2 +- 22 files changed, 197 insertions(+), 94 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index b7cabad0e..81f0a1ef3 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -26,7 +26,7 @@ impl Environment { .container .tracker_core_container .in_memory_torrent_repository - .upsert_peer(info_hash, peer); + .upsert_peer(info_hash, peer, None); } } diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index f130e24f0..c2d89e064 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -37,7 +37,7 @@ where .container .tracker_core_container .in_memory_torrent_repository - .upsert_peer(info_hash, peer); + .upsert_peer(info_hash, peer, None); } } diff --git a/packages/torrent-repository/benches/helpers/asyn.rs b/packages/torrent-repository/benches/helpers/asyn.rs index dec3984c6..fc6b3ffb0 100644 --- a/packages/torrent-repository/benches/helpers/asyn.rs +++ b/packages/torrent-repository/benches/helpers/asyn.rs @@ -18,7 +18,7 @@ where let info_hash = InfoHash::default(); - torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER).await; + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; torrent_repository.get_swarm_metadata(&info_hash).await; } @@ -37,7 +37,7 @@ where let handles = FuturesUnordered::new(); // Add the torrent/peer to the torrent repository - torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER).await; + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; torrent_repository.get_swarm_metadata(&info_hash).await; @@ -47,7 +47,7 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER).await; + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; torrent_repository_clone.get_swarm_metadata(&info_hash).await; @@ -87,7 +87,7 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER).await; + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; torrent_repository_clone.get_swarm_metadata(&info_hash).await; @@ -123,7 +123,7 @@ where // Add the torrents/peers to the torrent repository for info_hash in &info_hashes { - torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER).await; + torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER, None).await; torrent_repository.get_swarm_metadata(info_hash).await; } @@ -133,7 +133,7 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER).await; + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; torrent_repository_clone.get_swarm_metadata(&info_hash).await; if let Some(sleep_time) = sleep { diff --git a/packages/torrent-repository/benches/helpers/sync.rs b/packages/torrent-repository/benches/helpers/sync.rs index 048e709bc..e00401446 100644 --- a/packages/torrent-repository/benches/helpers/sync.rs +++ b/packages/torrent-repository/benches/helpers/sync.rs @@ -20,7 +20,7 @@ where let info_hash = InfoHash::default(); - torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER); + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None); torrent_repository.get_swarm_metadata(&info_hash); } @@ -39,7 +39,7 @@ where let handles = FuturesUnordered::new(); // Add the torrent/peer to the torrent repository - torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER); + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None); torrent_repository.get_swarm_metadata(&info_hash); @@ -49,7 +49,7 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER); + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None); torrent_repository_clone.get_swarm_metadata(&info_hash); @@ -89,7 +89,7 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER); + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None); torrent_repository_clone.get_swarm_metadata(&info_hash); @@ -125,7 +125,7 @@ where // Add the torrents/peers to the torrent repository for info_hash in &info_hashes { - torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER); + torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER, None); torrent_repository.get_swarm_metadata(info_hash); } @@ -135,7 +135,7 @@ where let torrent_repository_clone = torrent_repository.clone(); let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER); + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None); torrent_repository_clone.get_swarm_metadata(&info_hash); if let Some(sleep_time) = sleep { diff --git a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs index 731280486..9e2b5cc59 100644 --- a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs @@ -6,7 +6,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -23,7 +23,9 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + if let Some(entry) = self.torrents.get(info_hash) { entry.upsert_peer(peer) } else { diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs index bfb7f20f4..16ebdf3c1 100644 --- a/packages/torrent-repository/src/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -3,7 +3,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; pub mod dash_map_mutex_std; pub mod rw_lock_std; @@ -24,7 +24,7 @@ pub trait Repository: Debug + Default + Sized + 'static { fn remove(&self, key: &InfoHash) -> Option; fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); fn remove_peerless_torrents(&self, policy: &TrackerPolicy); - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool; + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool; fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option; } @@ -37,6 +37,11 @@ pub trait RepositoryAsync: Debug + Default + Sized + 'static { fn remove(&self, key: &InfoHash) -> impl std::future::Future> + Send; fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> impl std::future::Future + Send; - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> impl std::future::Future + Send; + fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + opt_persistent_torrent: Option, + ) -> impl std::future::Future + Send; fn get_swarm_metadata(&self, info_hash: &InfoHash) -> impl std::future::Future> + Send; } diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs index 2ff757654..7038b0b38 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std.rs @@ -3,7 +3,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -46,7 +46,9 @@ impl Repository for TorrentsRwLockStd where EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + let mut db = self.get_torrents_mut(); let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs index 1f1155df5..a9958bd7c 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs @@ -5,7 +5,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -33,7 +33,9 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + let maybe_entry = self.get_torrents().get(info_hash).cloned(); let entry = if let Some(entry) = maybe_entry { diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs index f8fd2871d..deba42b67 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs @@ -9,7 +9,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; @@ -37,7 +37,14 @@ where EntryMutexTokio: EntryAsync, EntrySingle: Entry, { - async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + _opt_persistent_torrent: Option, + ) -> bool { + // todo: load persistent torrent data if provided + let maybe_entry = self.get_torrents().get(info_hash).cloned(); let entry = if let Some(entry) = maybe_entry { diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs index 964149393..bbda42f17 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio.rs @@ -3,7 +3,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; @@ -47,7 +47,14 @@ impl RepositoryAsync for TorrentsRwLockTokio where EntrySingle: Entry, { - async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + _opt_persistent_torrent: Option, + ) -> bool { + // todo: load persistent torrent data if provided + let mut db = self.get_torrents_mut().await; let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs index c4541dea2..551c1c5ec 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs @@ -5,7 +5,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; @@ -35,7 +35,14 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + _opt_persistent_torrent: Option, + ) -> bool { + // todo: load persistent torrent data if provided + let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); let entry = if let Some(entry) = maybe_entry { diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs index ff1e77cda..3ac859ab0 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -5,7 +5,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; @@ -35,7 +35,14 @@ where EntryMutexTokio: EntryAsync, EntrySingle: Entry, { - async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + _opt_persistent_torrent: Option, + ) -> bool { + // todo: load persistent torrent data if provided + let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); let entry = if let Some(entry) = maybe_entry { diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index 7a4e4afb9..2c4ff5ce7 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -6,7 +6,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -23,9 +23,42 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { - let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); - entry.value().upsert_peer(peer) + /// Upsert a peer into the swarm of a torrent. + /// + /// Optionally, it can also preset the number of downloads of the torrent + /// only if it's the first time the torrent is being inserted. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// * `peer` - The peer to upsert. + /// * `opt_persistent_torrent` - The optional persisted data about a torrent + /// (number of downloads for the torrent). + /// + /// # Returns + /// + /// Returns `true` if the number of downloads was increased because the peer + /// completed the download. + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool { + if let Some(existing_entry) = self.torrents.get(info_hash) { + existing_entry.value().upsert_peer(peer) + } else { + let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { + EntryMutexStd::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: number_of_downloads, + } + .into(), + ) + } else { + EntryMutexStd::default() + }; + + let inserted_entry = self.torrents.get_or_insert(*info_hash, new_entry); + + inserted_entry.value().upsert_peer(peer) + } } fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { @@ -114,7 +147,9 @@ where EntryRwLockParkingLot: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); entry.value().upsert_peer(peer) } @@ -205,7 +240,9 @@ where EntryMutexParkingLot: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); entry.value().upsert_peer(peer) } diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 809c59d2a..65ce45f8e 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -3,7 +3,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use torrust_tracker_torrent_repository::repository::{Repository as _, RepositoryAsync as _}; use torrust_tracker_torrent_repository::{ EntrySingle, TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, @@ -26,18 +26,23 @@ pub(crate) enum Repo { } impl Repo { - pub(crate) async fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + pub(crate) async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + opt_persistent_torrent: Option, + ) -> bool { match self { - Repo::RwLockStd(repo) => repo.upsert_peer(info_hash, peer), - Repo::RwLockStdMutexStd(repo) => repo.upsert_peer(info_hash, peer), - Repo::RwLockStdMutexTokio(repo) => repo.upsert_peer(info_hash, peer).await, - Repo::RwLockTokio(repo) => repo.upsert_peer(info_hash, peer).await, - Repo::RwLockTokioMutexStd(repo) => repo.upsert_peer(info_hash, peer).await, - Repo::RwLockTokioMutexTokio(repo) => repo.upsert_peer(info_hash, peer).await, - Repo::SkipMapMutexStd(repo) => repo.upsert_peer(info_hash, peer), - Repo::SkipMapMutexParkingLot(repo) => repo.upsert_peer(info_hash, peer), - Repo::SkipMapRwLockParkingLot(repo) => repo.upsert_peer(info_hash, peer), - Repo::DashMapMutexStd(repo) => repo.upsert_peer(info_hash, peer), + Repo::RwLockStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::RwLockStdMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::RwLockStdMutexTokio(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, + Repo::RwLockTokio(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, + Repo::RwLockTokioMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, + Repo::RwLockTokioMutexTokio(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, + Repo::SkipMapMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::SkipMapMutexParkingLot(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::SkipMapRwLockParkingLot(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::DashMapMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), } } diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index c5cf2059c..d38208e0d 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -562,14 +562,14 @@ async fn it_should_remove_inactive_peers( // Insert the infohash and peer into the repository // and verify there is an extra torrent entry. { - repo.upsert_peer(&info_hash, &peer).await; + repo.upsert_peer(&info_hash, &peer, None).await; assert_eq!(repo.get_metrics().await.torrents, entries.len() as u64 + 1); } // Insert the infohash and peer into the repository // and verify the swarm metadata was updated. { - repo.upsert_peer(&info_hash, &peer).await; + repo.upsert_peer(&info_hash, &peer, None).await; let stats = repo.get_swarm_metadata(&info_hash).await; assert_eq!( stats, diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index e125adb66..b858cae6c 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -163,9 +163,17 @@ impl AnnounceHandler { ) -> Result { self.whitelist_authorization.authorize(info_hash).await?; + let opt_persistent_torrent = if self.config.tracker_policy.persistent_torrent_completed_stat { + self.db_torrent_repository.load(info_hash)? + } else { + None + }; + peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); - let number_of_downloads_increased = self.in_memory_torrent_repository.upsert_peer(info_hash, peer); + let number_of_downloads_increased = + self.in_memory_torrent_repository + .upsert_peer(info_hash, peer, opt_persistent_torrent); if self.config.tracker_policy.persistent_torrent_completed_stat && number_of_downloads_increased { self.db_torrent_repository.increase_number_of_downloads(info_hash)?; diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index e4691a86f..792bb024d 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -195,7 +195,7 @@ mod tests { // Add a peer to the torrent let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = services.in_memory_torrent_repository.upsert_peer(&infohash, &peer); + let _number_of_downloads_increased = services.in_memory_torrent_repository.upsert_peer(&infohash, &peer, None); // Simulate the time has passed 1 second more than the max peer timeout. clock::Stopped::local_add(&Duration::from_secs( @@ -212,7 +212,7 @@ mod tests { // Add a peer to the torrent let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(infohash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(infohash, &peer, None); // Remove the peer. The torrent is now peerless. in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index bec28bcc0..c3852654c 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -7,7 +7,7 @@ use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; use torrust_tracker_torrent_repository::EntryMutexStd; @@ -45,8 +45,13 @@ impl InMemoryTorrentRepository { /// /// `true` if the peer stats were updated. #[must_use] - pub fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { - self.torrents.upsert_peer(info_hash, peer) + pub fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + opt_persistent_torrent: Option, + ) -> bool { + self.torrents.upsert_peer(info_hash, peer, opt_persistent_torrent) } /// Removes a torrent entry from the repository. @@ -268,7 +273,7 @@ mod tests { let info_hash = sample_info_hash(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); assert!(in_memory_torrent_repository.get(&info_hash).is_some()); } @@ -279,8 +284,8 @@ mod tests { let info_hash = sample_info_hash(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); assert!(in_memory_torrent_repository.get(&info_hash).is_some()); } @@ -306,7 +311,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); @@ -339,7 +344,7 @@ mod tests { event: AnnounceEvent::Completed, }; - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); } let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); @@ -378,7 +383,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); @@ -393,7 +398,8 @@ mod tests { let excluded_peer = sample_peer(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer, None); // Add 74 peers for idx in 2..=75 { @@ -407,7 +413,7 @@ mod tests { event: AnnounceEvent::Completed, }; - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); } let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); @@ -435,7 +441,7 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let info_hash = sample_info_hash(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); let _unused = in_memory_torrent_repository.remove(&info_hash); @@ -450,7 +456,7 @@ mod tests { let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); // Cut off time is 1 second after the peer was updated in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); @@ -466,7 +472,7 @@ mod tests { // Insert a sample peer for the torrent to force adding the torrent entry let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(info_hash, &peer, None); // Remove the peer in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); @@ -530,7 +536,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); let torrent_entry = in_memory_torrent_repository.get(&info_hash).unwrap(); @@ -563,7 +569,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); let torrent_entries = in_memory_torrent_repository.get_paginated(None); @@ -605,12 +611,14 @@ mod tests { // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); // Get only the first page where page size is 1 let torrent_entries = @@ -641,12 +649,14 @@ mod tests { // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); // Get only the first page where page size is 1 let torrent_entries = @@ -677,12 +687,14 @@ mod tests { // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); // Get only the first page where page size is 1 let torrent_entries = @@ -727,7 +739,8 @@ mod tests { async fn it_should_return_the_torrent_metrics_when_there_is_a_leecher() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher()); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher(), None); let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -746,7 +759,8 @@ mod tests { async fn it_should_return_the_torrent_metrics_when_there_is_a_seeder() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &seeder()); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &seeder(), None); let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -766,7 +780,7 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer()); + in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer(), None); let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -788,7 +802,7 @@ mod tests { let start_time = std::time::Instant::now(); for i in 0..1_000_000 { let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher()); + in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher(), None); } let result_a = start_time.elapsed(); @@ -824,7 +838,7 @@ mod tests { let infohash = sample_info_hash(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&infohash, &leecher()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&infohash, &leecher(), None); let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata(&infohash); diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index 1d06b2945..88af3b570 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -231,7 +231,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); let torrent_info = get_torrent_info(&in_memory_torrent_repository, &info_hash).unwrap(); @@ -275,7 +275,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); @@ -300,8 +300,8 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer(), None); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer(), None); let offset = 0; let limit = 1; @@ -321,8 +321,8 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer(), None); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer(), None); let offset = 1; let limit = 4000; @@ -347,11 +347,11 @@ mod tests { let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer(), None); let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer()); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer(), None); let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); @@ -399,7 +399,7 @@ mod tests { let info_hash = sample_info_hash(); - let _ = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer()); + let _ = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); let torrent_info = get_torrents(&in_memory_torrent_repository, &[info_hash]); diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index a04773134..158e39a7e 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -35,7 +35,7 @@ where .container .tracker_core_container .in_memory_torrent_repository - .upsert_peer(info_hash, peer); + .upsert_peer(info_hash, peer, None); } } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index c30101678..e56e1d831 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -367,7 +367,7 @@ mod tests { .into(); let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv6); + in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv6, None); } async fn announce_a_new_peer_using_ipv4( @@ -679,7 +679,7 @@ mod tests { .into(); let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv4); + in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv4, None); } async fn announce_a_new_peer_using_ipv6( diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index fb17ecc97..c385718a2 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -166,7 +166,7 @@ mod tests { .with_number_of_bytes_left(0) .into(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer, None); } fn build_scrape_request(remote_addr: &SocketAddr, info_hash: &InfoHash) -> ScrapeRequest { From 3c9e72f0410c66b85f955e1d9ee1bdc5fdac0adc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 5 Mar 2025 16:14:05 +0000 Subject: [PATCH 0870/1297] chore(deps): update dependencies ```output cargo update Updating crates.io index Locking 4 packages to latest compatible versions Updating bytes v1.10.0 -> v1.10.1 Updating time v0.3.37 -> v0.3.38 Updating time-core v0.1.2 -> v0.1.3 Updating time-macros v0.2.19 -> v0.2.20 ``` --- Cargo.lock | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4c7524f49..1a6a09244 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -895,9 +895,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.10.0" +version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f61dac84819c6588b558454b194026eb1f09c293b9036ae9b159e74e73ab6cf9" +checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" [[package]] name = "camino" @@ -4150,9 +4150,9 @@ dependencies = [ [[package]] name = "time" -version = "0.3.37" +version = "0.3.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35e7868883861bd0e56d9ac6efcaaca0d6d5d82a2a7ec8209ff492c07cf37b21" +checksum = "bb041120f25f8fbe8fd2dbe4671c7c2ed74d83be2e7a77529bf7e0790ae3f472" dependencies = [ "deranged", "itoa", @@ -4165,15 +4165,15 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" +checksum = "765c97a5b985b7c11d7bc27fa927dc4fe6af3a6dfb021d28deb60d3bf51e76ef" [[package]] name = "time-macros" -version = "0.2.19" +version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2834e6017e3e5e4b9834939793b282bc03b37a3336245fa820e35e233e2a85de" +checksum = "e8093bc3e81c3bc5f7879de09619d06c9a5a5e45ca44dfeeb7225bae38005c5c" dependencies = [ "num-conv", "time-core", From 99a372435eb2fb4284cba41ce892dcb395252749 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 5 Mar 2025 17:51:52 +0000 Subject: [PATCH 0871/1297] docs: add link to packages docs in the README --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 671a484e6..b7431e859 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,8 @@ Others: ![Torrust Tracker Layers with main packages](./docs/media/packages/torrust-tracker-layers-with-packages.png) +There is also extra [documentation about the packages](./docs/packages.md). + ## Getting Started ### Container Version From 2020162422f21143aabb0826a409b908cd02b82f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Mar 2025 08:36:11 +0000 Subject: [PATCH 0872/1297] chore: [#1243] minor changes in comments and format --- packages/primitives/src/swarm_metadata.rs | 15 ++++++++++----- packages/primitives/src/torrent_metrics.rs | 10 +++++++--- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/packages/primitives/src/swarm_metadata.rs b/packages/primitives/src/swarm_metadata.rs index ca880b54d..68d354e21 100644 --- a/packages/primitives/src/swarm_metadata.rs +++ b/packages/primitives/src/swarm_metadata.rs @@ -6,11 +6,16 @@ use derive_more::Constructor; /// See [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) #[derive(Copy, Clone, Debug, PartialEq, Default, Constructor)] pub struct SwarmMetadata { - /// (i.e `completed`): The number of peers that have ever completed downloading - pub downloaded: u32, // - /// (i.e `seeders`): The number of active peers that have completed downloading (seeders) - pub complete: u32, //seeders - /// (i.e `leechers`): The number of active peers that have not completed downloading (leechers) + /// (i.e `completed`): The number of peers that have ever completed + /// downloading a given torrent. + pub downloaded: u32, + + /// (i.e `seeders`): The number of active peers that have completed + /// downloading (seeders) a given torrent. + pub complete: u32, + + /// (i.e `leechers`): The number of active peers that have not completed + /// downloading (leechers) a given torrent. pub incomplete: u32, } diff --git a/packages/primitives/src/torrent_metrics.rs b/packages/primitives/src/torrent_metrics.rs index 02de02954..51c96a3ee 100644 --- a/packages/primitives/src/torrent_metrics.rs +++ b/packages/primitives/src/torrent_metrics.rs @@ -5,12 +5,16 @@ use std::ops::AddAssign; /// Metrics are aggregate values for all torrents. #[derive(Copy, Clone, Debug, PartialEq, Default)] pub struct TorrentsMetrics { - /// Total number of seeders for all torrents - pub complete: u64, - /// Total number of peers that have ever completed downloading for all torrents. + /// Total number of peers that have ever completed downloading for all + /// torrents. pub downloaded: u64, + + /// Total number of seeders for all torrents. + pub complete: u64, + /// Total number of leechers for all torrents. pub incomplete: u64, + /// Total number of torrents. pub torrents: u64, } From 144a338b9cfc4b82a0cc19be54e906684d20e8df Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Mar 2025 08:55:40 +0000 Subject: [PATCH 0873/1297] refactor: [#1243] move and rename struct and fields (AggregateSwarmMetadata) To avoid confusion with `SwarmMetadata` - `SwarmMetadata`: metrics for one torrent. - `AggregateSwarmMetadata`: metrics for all torrents. --- .../src/v1/context/stats/resources.rs | 20 ++--- .../src/v1/context/stats/responses.rs | 8 +- .../src/statistics/services.rs | 8 +- packages/primitives/src/lib.rs | 1 - packages/primitives/src/swarm_metadata.rs | 37 +++++++- packages/primitives/src/torrent_metrics.rs | 29 ------ .../src/statistics/services.rs | 8 +- .../src/repository/dash_map_mutex_std.rs | 15 ++-- .../torrent-repository/src/repository/mod.rs | 7 +- .../src/repository/rw_lock_std.rs | 15 ++-- .../src/repository/rw_lock_std_mutex_std.rs | 15 ++-- .../src/repository/rw_lock_std_mutex_tokio.rs | 15 ++-- .../src/repository/rw_lock_tokio.rs | 15 ++-- .../src/repository/rw_lock_tokio_mutex_std.rs | 15 ++-- .../repository/rw_lock_tokio_mutex_tokio.rs | 15 ++-- .../src/repository/skip_map_mutex_std.rs | 39 ++++---- .../torrent-repository/tests/common/repo.rs | 5 +- .../tests/repository/mod.rs | 20 ++--- .../src/torrent/repository/in_memory.rs | 89 +++++++++---------- .../src/statistics/services.rs | 8 +- .../src/statistics/services.rs | 8 +- 21 files changed, 191 insertions(+), 201 deletions(-) delete mode 100644 packages/primitives/src/torrent_metrics.rs diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs index 9a82593c7..9ed61cc6b 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs @@ -79,10 +79,10 @@ pub struct Stats { impl From for Stats { fn from(metrics: TrackerMetrics) -> Self { Self { - torrents: metrics.torrents_metrics.torrents, - seeders: metrics.torrents_metrics.complete, - completed: metrics.torrents_metrics.downloaded, - leechers: metrics.torrents_metrics.incomplete, + torrents: metrics.torrents_metrics.total_torrents, + seeders: metrics.torrents_metrics.total_complete, + completed: metrics.torrents_metrics.total_downloaded, + leechers: metrics.torrents_metrics.total_incomplete, // TCP tcp4_connections_handled: metrics.protocol_metrics.tcp4_connections_handled, tcp4_announces_handled: metrics.protocol_metrics.tcp4_announces_handled, @@ -119,7 +119,7 @@ impl From for Stats { mod tests { use torrust_rest_tracker_api_core::statistics::metrics::Metrics; use torrust_rest_tracker_api_core::statistics::services::TrackerMetrics; - use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use super::Stats; @@ -127,11 +127,11 @@ mod tests { fn stats_resource_should_be_converted_from_tracker_metrics() { assert_eq!( Stats::from(TrackerMetrics { - torrents_metrics: TorrentsMetrics { - complete: 1, - downloaded: 2, - incomplete: 3, - torrents: 4 + torrents_metrics: AggregateSwarmMetadata { + total_complete: 1, + total_downloaded: 2, + total_incomplete: 3, + total_torrents: 4 }, protocol_metrics: Metrics { // TCP diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs index 61455178c..6d279726c 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs @@ -16,10 +16,10 @@ pub fn stats_response(tracker_metrics: TrackerMetrics) -> Response { pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { let mut lines = vec![]; - lines.push(format!("torrents {}", tracker_metrics.torrents_metrics.torrents)); - lines.push(format!("seeders {}", tracker_metrics.torrents_metrics.complete)); - lines.push(format!("completed {}", tracker_metrics.torrents_metrics.downloaded)); - lines.push(format!("leechers {}", tracker_metrics.torrents_metrics.incomplete)); + lines.push(format!("torrents {}", tracker_metrics.torrents_metrics.total_torrents)); + lines.push(format!("seeders {}", tracker_metrics.torrents_metrics.total_complete)); + lines.push(format!("completed {}", tracker_metrics.torrents_metrics.total_downloaded)); + lines.push(format!("leechers {}", tracker_metrics.torrents_metrics.total_incomplete)); // TCP diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 57806677e..f7808440a 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -23,7 +23,7 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use crate::statistics::metrics::Metrics; use crate::statistics::repository::Repository; @@ -34,7 +34,7 @@ pub struct TrackerMetrics { /// Domain level metrics. /// /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: TorrentsMetrics, + pub torrents_metrics: AggregateSwarmMetadata, /// Application level metrics. Usage statistics/metrics. /// @@ -72,7 +72,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self}; use torrust_tracker_configuration::Configuration; - use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_tracker_test_helpers::configuration; use crate::statistics; @@ -96,7 +96,7 @@ mod tests { assert_eq!( tracker_metrics, TrackerMetrics { - torrents_metrics: TorrentsMetrics::default(), + torrents_metrics: AggregateSwarmMetadata::default(), protocol_metrics: statistics::metrics::Metrics::default(), } ); diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index ec9732778..b50516893 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -8,7 +8,6 @@ pub mod core; pub mod pagination; pub mod peer; pub mod swarm_metadata; -pub mod torrent_metrics; use std::collections::BTreeMap; use std::time::Duration; diff --git a/packages/primitives/src/swarm_metadata.rs b/packages/primitives/src/swarm_metadata.rs index 68d354e21..792eff632 100644 --- a/packages/primitives/src/swarm_metadata.rs +++ b/packages/primitives/src/swarm_metadata.rs @@ -1,20 +1,23 @@ +use std::ops::AddAssign; + use derive_more::Constructor; /// Swarm statistics for one torrent. +/// /// Swarm metadata dictionary in the scrape response. /// /// See [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) #[derive(Copy, Clone, Debug, PartialEq, Default, Constructor)] pub struct SwarmMetadata { - /// (i.e `completed`): The number of peers that have ever completed + /// (i.e `completed`): The number of peers that have ever completed /// downloading a given torrent. pub downloaded: u32, - /// (i.e `seeders`): The number of active peers that have completed + /// (i.e `seeders`): The number of active peers that have completed /// downloading (seeders) a given torrent. pub complete: u32, - /// (i.e `leechers`): The number of active peers that have not completed + /// (i.e `leechers`): The number of active peers that have not completed /// downloading (leechers) a given torrent. pub incomplete: u32, } @@ -25,3 +28,31 @@ impl SwarmMetadata { Self::default() } } + +/// Structure that holds aggregate swarm metadata. +/// +/// Metrics are aggregate values for all torrents. +#[derive(Copy, Clone, Debug, PartialEq, Default)] +pub struct AggregateSwarmMetadata { + /// Total number of peers that have ever completed downloading for all + /// torrents. + pub total_downloaded: u64, + + /// Total number of seeders for all torrents. + pub total_complete: u64, + + /// Total number of leechers for all torrents. + pub total_incomplete: u64, + + /// Total number of torrents. + pub total_torrents: u64, +} + +impl AddAssign for AggregateSwarmMetadata { + fn add_assign(&mut self, rhs: Self) { + self.total_complete += rhs.total_complete; + self.total_downloaded += rhs.total_downloaded; + self.total_incomplete += rhs.total_incomplete; + self.total_torrents += rhs.total_torrents; + } +} diff --git a/packages/primitives/src/torrent_metrics.rs b/packages/primitives/src/torrent_metrics.rs deleted file mode 100644 index 51c96a3ee..000000000 --- a/packages/primitives/src/torrent_metrics.rs +++ /dev/null @@ -1,29 +0,0 @@ -use std::ops::AddAssign; - -/// Structure that holds general `Tracker` torrents metrics. -/// -/// Metrics are aggregate values for all torrents. -#[derive(Copy, Clone, Debug, PartialEq, Default)] -pub struct TorrentsMetrics { - /// Total number of peers that have ever completed downloading for all - /// torrents. - pub downloaded: u64, - - /// Total number of seeders for all torrents. - pub complete: u64, - - /// Total number of leechers for all torrents. - pub incomplete: u64, - - /// Total number of torrents. - pub torrents: u64, -} - -impl AddAssign for TorrentsMetrics { - fn add_assign(&mut self, rhs: Self) { - self.complete += rhs.complete; - self.downloaded += rhs.downloaded; - self.incomplete += rhs.incomplete; - self.torrents += rhs.torrents; - } -} diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index c4dfcf533..ea4e159b6 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -4,7 +4,7 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self, statistics as udp_core_statistics}; use tokio::sync::RwLock; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_udp_tracker_server::statistics as udp_server_statistics; use crate::statistics::metrics::Metrics; @@ -15,7 +15,7 @@ pub struct TrackerMetrics { /// Domain level metrics. /// /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: TorrentsMetrics, + pub torrents_metrics: AggregateSwarmMetadata, /// Application level metrics. Usage statistics/metrics. /// @@ -83,7 +83,7 @@ mod tests { use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use tokio::sync::RwLock; use torrust_tracker_configuration::Configuration; - use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_tracker_test_helpers::configuration; use crate::statistics::metrics::Metrics; @@ -127,7 +127,7 @@ mod tests { assert_eq!( tracker_metrics, TrackerMetrics { - torrents_metrics: TorrentsMetrics::default(), + torrents_metrics: AggregateSwarmMetadata::default(), protocol_metrics: Metrics::default(), } ); diff --git a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs index 9e2b5cc59..d4a84caa0 100644 --- a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs @@ -4,8 +4,7 @@ use bittorrent_primitives::info_hash::InfoHash; use dashmap::DashMap; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::Repository; @@ -47,15 +46,15 @@ where maybe_entry.map(|entry| entry.clone()) } - fn get_metrics(&self) -> TorrentsMetrics { - let mut metrics = TorrentsMetrics::default(); + fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); for entry in &self.torrents { let stats = entry.value().lock().expect("it should get a lock").get_swarm_metadata(); - metrics.complete += u64::from(stats.complete); - metrics.downloaded += u64::from(stats.downloaded); - metrics.incomplete += u64::from(stats.incomplete); - metrics.torrents += 1; + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; } metrics diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs index 16ebdf3c1..9284ff6e6 100644 --- a/packages/torrent-repository/src/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -1,8 +1,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; pub mod dash_map_mutex_std; @@ -18,7 +17,7 @@ use std::fmt::Debug; pub trait Repository: Debug + Default + Sized + 'static { fn get(&self, key: &InfoHash) -> Option; - fn get_metrics(&self) -> TorrentsMetrics; + fn get_metrics(&self) -> AggregateSwarmMetadata; fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, T)>; fn import_persistent(&self, persistent_torrents: &PersistentTorrents); fn remove(&self, key: &InfoHash) -> Option; @@ -31,7 +30,7 @@ pub trait Repository: Debug + Default + Sized + 'static { #[allow(clippy::module_name_repetitions)] pub trait RepositoryAsync: Debug + Default + Sized + 'static { fn get(&self, key: &InfoHash) -> impl std::future::Future> + Send; - fn get_metrics(&self) -> impl std::future::Future + Send; + fn get_metrics(&self) -> impl std::future::Future + Send; fn get_paginated(&self, pagination: Option<&Pagination>) -> impl std::future::Future> + Send; fn import_persistent(&self, persistent_torrents: &PersistentTorrents) -> impl std::future::Future + Send; fn remove(&self, key: &InfoHash) -> impl std::future::Future> + Send; diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs index 7038b0b38..d190718af 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std.rs @@ -1,8 +1,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::Repository; @@ -65,15 +64,15 @@ where db.get(key).cloned() } - fn get_metrics(&self) -> TorrentsMetrics { - let mut metrics = TorrentsMetrics::default(); + fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); for entry in self.get_torrents().values() { let stats = entry.get_swarm_metadata(); - metrics.complete += u64::from(stats.complete); - metrics.downloaded += u64::from(stats.downloaded); - metrics.incomplete += u64::from(stats.incomplete); - metrics.torrents += 1; + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; } metrics diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs index a9958bd7c..1764b94e8 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs @@ -3,8 +3,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::Repository; @@ -60,15 +59,15 @@ where db.get(key).cloned() } - fn get_metrics(&self) -> TorrentsMetrics { - let mut metrics = TorrentsMetrics::default(); + fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); for entry in self.get_torrents().values() { let stats = entry.lock().expect("it should get a lock").get_swarm_metadata(); - metrics.complete += u64::from(stats.complete); - metrics.downloaded += u64::from(stats.downloaded); - metrics.incomplete += u64::from(stats.incomplete); - metrics.torrents += 1; + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; } metrics diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs index deba42b67..116c1ff87 100644 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs @@ -7,8 +7,7 @@ use futures::future::join_all; use futures::{Future, FutureExt}; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::RepositoryAsync; @@ -86,17 +85,17 @@ where } } - async fn get_metrics(&self) -> TorrentsMetrics { - let mut metrics = TorrentsMetrics::default(); + async fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); let entries: Vec<_> = self.get_torrents().values().cloned().collect(); for entry in entries { let stats = entry.lock().await.get_swarm_metadata(); - metrics.complete += u64::from(stats.complete); - metrics.downloaded += u64::from(stats.downloaded); - metrics.incomplete += u64::from(stats.incomplete); - metrics.torrents += 1; + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; } metrics diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs index bbda42f17..53838023d 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio.rs @@ -1,8 +1,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::RepositoryAsync; @@ -85,15 +84,15 @@ where } } - async fn get_metrics(&self) -> TorrentsMetrics { - let mut metrics = TorrentsMetrics::default(); + async fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); for entry in self.get_torrents().await.values() { let stats = entry.get_swarm_metadata(); - metrics.complete += u64::from(stats.complete); - metrics.downloaded += u64::from(stats.downloaded); - metrics.incomplete += u64::from(stats.incomplete); - metrics.torrents += 1; + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; } metrics diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs index 551c1c5ec..eb7e300fd 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs @@ -3,8 +3,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::RepositoryAsync; @@ -79,15 +78,15 @@ where } } - async fn get_metrics(&self) -> TorrentsMetrics { - let mut metrics = TorrentsMetrics::default(); + async fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); for entry in self.get_torrents().await.values() { let stats = entry.get_swarm_metadata(); - metrics.complete += u64::from(stats.complete); - metrics.downloaded += u64::from(stats.downloaded); - metrics.incomplete += u64::from(stats.incomplete); - metrics.torrents += 1; + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; } metrics diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs index 3ac859ab0..c8ebaf4d6 100644 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -3,8 +3,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::RepositoryAsync; @@ -82,15 +81,15 @@ where } } - async fn get_metrics(&self) -> TorrentsMetrics { - let mut metrics = TorrentsMetrics::default(); + async fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); for entry in self.get_torrents().await.values() { let stats = entry.get_swarm_metadata().await; - metrics.complete += u64::from(stats.complete); - metrics.downloaded += u64::from(stats.downloaded); - metrics.incomplete += u64::from(stats.incomplete); - metrics.torrents += 1; + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; } metrics diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index 2c4ff5ce7..8a15a9442 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -4,8 +4,7 @@ use bittorrent_primitives::info_hash::InfoHash; use crossbeam_skiplist::SkipMap; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use super::Repository; @@ -70,15 +69,15 @@ where maybe_entry.map(|entry| entry.value().clone()) } - fn get_metrics(&self) -> TorrentsMetrics { - let mut metrics = TorrentsMetrics::default(); + fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); for entry in &self.torrents { let stats = entry.value().lock().expect("it should get a lock").get_swarm_metadata(); - metrics.complete += u64::from(stats.complete); - metrics.downloaded += u64::from(stats.downloaded); - metrics.incomplete += u64::from(stats.incomplete); - metrics.torrents += 1; + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; } metrics @@ -163,15 +162,15 @@ where maybe_entry.map(|entry| entry.value().clone()) } - fn get_metrics(&self) -> TorrentsMetrics { - let mut metrics = TorrentsMetrics::default(); + fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); for entry in &self.torrents { let stats = entry.value().read().get_swarm_metadata(); - metrics.complete += u64::from(stats.complete); - metrics.downloaded += u64::from(stats.downloaded); - metrics.incomplete += u64::from(stats.incomplete); - metrics.torrents += 1; + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; } metrics @@ -256,15 +255,15 @@ where maybe_entry.map(|entry| entry.value().clone()) } - fn get_metrics(&self) -> TorrentsMetrics { - let mut metrics = TorrentsMetrics::default(); + fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); for entry in &self.torrents { let stats = entry.value().lock().get_swarm_metadata(); - metrics.complete += u64::from(stats.complete); - metrics.downloaded += u64::from(stats.downloaded); - metrics.incomplete += u64::from(stats.incomplete); - metrics.torrents += 1; + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; } metrics diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 65ce45f8e..224fc6aa3 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -1,8 +1,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use torrust_tracker_torrent_repository::repository::{Repository as _, RepositoryAsync as _}; use torrust_tracker_torrent_repository::{ @@ -76,7 +75,7 @@ impl Repo { } } - pub(crate) async fn get_metrics(&self) -> TorrentsMetrics { + pub(crate) async fn get_metrics(&self) -> AggregateSwarmMetadata { match self { Repo::RwLockStd(repo) => repo.get_metrics(), Repo::RwLockStdMutexStd(repo) => repo.get_metrics(), diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index d38208e0d..77977837f 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -402,19 +402,19 @@ async fn it_should_get_metrics( repo: Repo, #[case] entries: Entries, ) { - use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; make(&repo, &entries).await; - let mut metrics = TorrentsMetrics::default(); + let mut metrics = AggregateSwarmMetadata::default(); for (_, torrent) in entries { let stats = torrent.get_swarm_metadata(); - metrics.torrents += 1; - metrics.incomplete += u64::from(stats.incomplete); - metrics.complete += u64::from(stats.complete); - metrics.downloaded += u64::from(stats.downloaded); + metrics.total_torrents += 1; + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); } assert_eq!(repo.get_metrics().await, metrics); @@ -449,12 +449,12 @@ async fn it_should_import_persistent_torrents( ) { make(&repo, &entries).await; - let mut downloaded = repo.get_metrics().await.downloaded; + let mut downloaded = repo.get_metrics().await.total_downloaded; persistent_torrents.iter().for_each(|(_, d)| downloaded += u64::from(*d)); repo.import_persistent(&persistent_torrents).await; - assert_eq!(repo.get_metrics().await.downloaded, downloaded); + assert_eq!(repo.get_metrics().await.total_downloaded, downloaded); for (entry, _) in persistent_torrents { assert!(repo.get(&entry).await.is_some()); @@ -497,7 +497,7 @@ async fn it_should_remove_an_entry( assert_eq!(repo.remove(&info_hash).await, None); } - assert_eq!(repo.get_metrics().await.torrents, 0); + assert_eq!(repo.get_metrics().await.total_torrents, 0); } #[rstest] @@ -563,7 +563,7 @@ async fn it_should_remove_inactive_peers( // and verify there is an extra torrent entry. { repo.upsert_peer(&info_hash, &peer, None).await; - assert_eq!(repo.get_metrics().await.torrents, entries.len() as u64 + 1); + assert_eq!(repo.get_metrics().await.total_torrents, entries.len() as u64 + 1); } // Insert the infohash and peer into the repository diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index c3852654c..e09bede8e 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -5,8 +5,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::repository::Repository; @@ -208,7 +207,7 @@ impl InMemoryTorrentRepository { /// /// A [`TorrentsMetrics`] struct with the aggregated metrics. #[must_use] - pub fn get_torrents_metrics(&self) -> TorrentsMetrics { + pub fn get_torrents_metrics(&self) -> AggregateSwarmMetadata { self.torrents.get_metrics() } @@ -706,12 +705,12 @@ mod tests { } } - mod returning_torrent_metrics { + mod returning_aggregate_swarm_metadata { use std::sync::Arc; use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; - use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use crate::test_helpers::tests::{complete_peer, leecher, sample_info_hash, seeder}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -719,84 +718,84 @@ mod tests { // todo: refactor to use test parametrization #[tokio::test] - async fn it_should_get_empty_torrent_metrics_when_there_are_no_torrents() { + async fn it_should_get_empty_aggregate_swarm_metadata_when_there_are_no_torrents() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); assert_eq!( - torrents_metrics, - TorrentsMetrics { - complete: 0, - downloaded: 0, - incomplete: 0, - torrents: 0 + aggregate_swarm_metadata, + AggregateSwarmMetadata { + total_complete: 0, + total_downloaded: 0, + total_incomplete: 0, + total_torrents: 0 } ); } #[tokio::test] - async fn it_should_return_the_torrent_metrics_when_there_is_a_leecher() { + async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_leecher() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher(), None); - let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); assert_eq!( - torrent_metrics, - TorrentsMetrics { - complete: 0, - downloaded: 0, - incomplete: 1, - torrents: 1, + aggregate_swarm_metadata, + AggregateSwarmMetadata { + total_complete: 0, + total_downloaded: 0, + total_incomplete: 1, + total_torrents: 1, } ); } #[tokio::test] - async fn it_should_return_the_torrent_metrics_when_there_is_a_seeder() { + async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_seeder() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &seeder(), None); - let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); assert_eq!( - torrent_metrics, - TorrentsMetrics { - complete: 1, - downloaded: 0, - incomplete: 0, - torrents: 1, + aggregate_swarm_metadata, + AggregateSwarmMetadata { + total_complete: 1, + total_downloaded: 0, + total_incomplete: 0, + total_torrents: 1, } ); } #[tokio::test] - async fn it_should_return_the_torrent_metrics_when_there_is_a_completed_peer() { + async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_completed_peer() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer(), None); - let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); assert_eq!( - torrent_metrics, - TorrentsMetrics { - complete: 1, - downloaded: 0, - incomplete: 0, - torrents: 1, + aggregate_swarm_metadata, + AggregateSwarmMetadata { + total_complete: 1, + total_downloaded: 0, + total_incomplete: 0, + total_torrents: 1, } ); } #[tokio::test] - async fn it_should_return_the_torrent_metrics_when_there_are_multiple_torrents() { + async fn it_should_return_the_aggregate_swarm_metadata_when_there_are_multiple_torrents() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let start_time = std::time::Instant::now(); @@ -807,16 +806,16 @@ mod tests { let result_a = start_time.elapsed(); let start_time = std::time::Instant::now(); - let torrent_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); let result_b = start_time.elapsed(); assert_eq!( - (torrent_metrics), - (TorrentsMetrics { - complete: 0, - downloaded: 0, - incomplete: 1_000_000, - torrents: 1_000_000, + (aggregate_swarm_metadata), + (AggregateSwarmMetadata { + total_complete: 0, + total_downloaded: 0, + total_incomplete: 1_000_000, + total_torrents: 1_000_000, }), "{result_a:?} {result_b:?}" ); diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index 7ffa127e6..56814f5d5 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -39,7 +39,7 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use crate::statistics::metrics::Metrics; use crate::statistics::repository::Repository; @@ -50,7 +50,7 @@ pub struct TrackerMetrics { /// Domain level metrics. /// /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: TorrentsMetrics, + pub torrents_metrics: AggregateSwarmMetadata, /// Application level metrics. Usage statistics/metrics. /// @@ -88,7 +88,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self}; use torrust_tracker_configuration::Configuration; - use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_tracker_test_helpers::configuration; use crate::statistics; @@ -113,7 +113,7 @@ mod tests { assert_eq!( tracker_metrics, TrackerMetrics { - torrents_metrics: TorrentsMetrics::default(), + torrents_metrics: AggregateSwarmMetadata::default(), protocol_metrics: statistics::metrics::Metrics::default(), } ); diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index 92ee14f50..a16685077 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -41,7 +41,7 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::services::banning::BanService; use tokio::sync::RwLock; -use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; +use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use crate::statistics::metrics::Metrics; use crate::statistics::repository::Repository; @@ -52,7 +52,7 @@ pub struct TrackerMetrics { /// Domain level metrics. /// /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: TorrentsMetrics, + pub torrents_metrics: AggregateSwarmMetadata, /// Application level metrics. Usage statistics/metrics. /// @@ -108,7 +108,7 @@ mod tests { use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use tokio::sync::RwLock; use torrust_tracker_configuration::Configuration; - use torrust_tracker_primitives::torrent_metrics::TorrentsMetrics; + use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_tracker_test_helpers::configuration; use crate::statistics; @@ -139,7 +139,7 @@ mod tests { assert_eq!( tracker_metrics, TrackerMetrics { - torrents_metrics: TorrentsMetrics::default(), + torrents_metrics: AggregateSwarmMetadata::default(), protocol_metrics: statistics::metrics::Metrics::default(), } ); From 89607cc8025fe048a3b9ee41c8b8082b1a8d8321 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 7 Mar 2025 11:48:50 +0000 Subject: [PATCH 0874/1297] refactor: [#1342] remove counter for HTTP connetions internally The number of HTTP tracker connections don't make sense. There are connection requests only in the UDP tracker. That code is removed but, in order to keep backward compatibility, the API still exposes that value which is the: number of announce requests + number of scrape requests --- .../tests/server/v1/contract.rs | 85 ------------------- .../src/v1/context/stats/resources.rs | 2 + .../src/v1/context/stats/responses.rs | 1 + .../src/services/announce.rs | 6 +- .../http-tracker-core/src/services/scrape.rs | 6 +- .../src/statistics/event/handler.rs | 48 ----------- .../src/statistics/metrics.rs | 8 -- .../src/statistics/repository.rs | 12 --- .../src/statistics/services.rs | 2 - .../src/statistics/metrics.rs | 2 + .../src/statistics/services.rs | 10 ++- 11 files changed, 15 insertions(+), 167 deletions(-) diff --git a/packages/axum-http-tracker-server/tests/server/v1/contract.rs b/packages/axum-http-tracker-server/tests/server/v1/contract.rs index 992793022..ad5b5a482 100644 --- a/packages/axum-http-tracker-server/tests/server/v1/contract.rs +++ b/packages/axum-http-tracker-server/tests/server/v1/contract.rs @@ -666,91 +666,6 @@ mod for_all_config_modes { compact_announce.is_ok() } - #[tokio::test] - async fn should_increase_the_number_of_tcp4_connections_handled_in_statistics() { - logging::setup(); - - let env = Started::new(&configuration::ephemeral_public().into()).await; - - Client::new(*env.bind_address()) - .announce(&QueryBuilder::default().query()) - .await; - - let stats = env - .container - .http_tracker_core_container - .http_stats_repository - .get_stats() - .await; - - assert_eq!(stats.tcp4_connections_handled, 1); - - drop(stats); - - env.stop().await; - } - - #[tokio::test] - async fn should_increase_the_number_of_tcp6_connections_handled_in_statistics() { - logging::setup(); - - if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) - .await - .is_err() - { - return; // we cannot bind to a ipv6 socket, so we will skip this test - } - - let env = Started::new(&configuration::ephemeral_ipv6().into()).await; - - Client::bind(*env.bind_address(), IpAddr::from_str("::1").unwrap()) - .announce(&QueryBuilder::default().query()) - .await; - - let stats = env - .container - .http_tracker_core_container - .http_stats_repository - .get_stats() - .await; - - assert_eq!(stats.tcp6_connections_handled, 1); - - drop(stats); - - env.stop().await; - } - - #[tokio::test] - async fn should_not_increase_the_number_of_tcp6_connections_handled_if_the_client_is_not_using_an_ipv6_ip() { - logging::setup(); - - // The tracker ignores the peer address in the request param. It uses the client remote ip address. - - let env = Started::new(&configuration::ephemeral_public().into()).await; - - Client::new(*env.bind_address()) - .announce( - &QueryBuilder::default() - .with_peer_addr(&IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1))) - .query(), - ) - .await; - - let stats = env - .container - .http_tracker_core_container - .http_stats_repository - .get_stats() - .await; - - assert_eq!(stats.tcp6_connections_handled, 0); - - drop(stats); - - env.stop().await; - } - #[tokio::test] async fn should_increase_the_number_of_tcp4_announce_requests_handled_in_statistics() { logging::setup(); diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs index 9ed61cc6b..d9480259e 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs @@ -77,6 +77,7 @@ pub struct Stats { } impl From for Stats { + #[allow(deprecated)] fn from(metrics: TrackerMetrics) -> Self { Self { torrents: metrics.torrents_metrics.total_torrents, @@ -124,6 +125,7 @@ mod tests { use super::Stats; #[test] + #[allow(deprecated)] fn stats_resource_should_be_converted_from_tracker_metrics() { assert_eq!( Stats::from(TrackerMetrics { diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs index 6d279726c..853fdd2e2 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs @@ -12,6 +12,7 @@ pub fn stats_response(tracker_metrics: TrackerMetrics) -> Response { } /// `200` response that contains the [`Stats`] resource in Prometheus Text Exposition Format . +#[allow(deprecated)] #[must_use] pub fn metrics_response(tracker_metrics: &TrackerMetrics) -> Response { let mut lines = vec![]; diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 959dcc615..896387b28 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -28,12 +28,8 @@ use crate::statistics; /// /// The service sends an statistics event that increments: /// -/// - The number of TCP connections handled by the HTTP tracker. /// - The number of TCP `announce` requests handled by the HTTP tracker. -/// -/// > **NOTICE**: as the HTTP tracker does not requires a connection request -/// > like the UDP tracker, the number of TCP connections is incremented for -/// > each `announce` request. +/// - The number of TCP `scrape` requests handled by the HTTP tracker. pub struct AnnounceService { core_config: Arc, announce_handler: Arc, diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index dcb88508c..53eed0361 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -25,13 +25,9 @@ use crate::statistics; /// /// The service sends an statistics event that increments: /// -/// - The number of TCP connections handled by the HTTP tracker. +/// - The number of TCP `announce` requests handled by the HTTP tracker. /// - The number of TCP `scrape` requests handled by the HTTP tracker. /// -/// > **NOTICE**: as the HTTP tracker does not requires a connection request -/// > like the UDP tracker, the number of TCP connections is incremented for -/// > each `scrape` request. -/// /// # Errors /// /// This function will return an error if: diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index af323d06b..b0a0c186f 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -6,21 +6,17 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { // TCP4 Event::Tcp4Announce => { stats_repository.increase_tcp4_announces().await; - stats_repository.increase_tcp4_connections().await; } Event::Tcp4Scrape => { stats_repository.increase_tcp4_scrapes().await; - stats_repository.increase_tcp4_connections().await; } // TCP6 Event::Tcp6Announce => { stats_repository.increase_tcp6_announces().await; - stats_repository.increase_tcp6_connections().await; } Event::Tcp6Scrape => { stats_repository.increase_tcp6_scrapes().await; - stats_repository.increase_tcp6_connections().await; } } @@ -44,17 +40,6 @@ mod tests { assert_eq!(stats.tcp4_announces_handled, 1); } - #[tokio::test] - async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_announce_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Tcp4Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_connections_handled, 1); - } - #[tokio::test] async fn should_increase_the_tcp4_scrapes_counter_when_it_receives_a_tcp4_scrape_event() { let stats_repository = Repository::new(); @@ -66,17 +51,6 @@ mod tests { assert_eq!(stats.tcp4_scrapes_handled, 1); } - #[tokio::test] - async fn should_increase_the_tcp4_connections_counter_when_it_receives_a_tcp4_scrape_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Tcp4Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp4_connections_handled, 1); - } - #[tokio::test] async fn should_increase_the_tcp6_announces_counter_when_it_receives_a_tcp6_announce_event() { let stats_repository = Repository::new(); @@ -88,17 +62,6 @@ mod tests { assert_eq!(stats.tcp6_announces_handled, 1); } - #[tokio::test] - async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_announce_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Tcp6Announce, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_connections_handled, 1); - } - #[tokio::test] async fn should_increase_the_tcp6_scrapes_counter_when_it_receives_a_tcp6_scrape_event() { let stats_repository = Repository::new(); @@ -109,15 +72,4 @@ mod tests { assert_eq!(stats.tcp6_scrapes_handled, 1); } - - #[tokio::test] - async fn should_increase_the_tcp6_connections_counter_when_it_receives_a_tcp6_scrape_event() { - let stats_repository = Repository::new(); - - handle_event(Event::Tcp6Scrape, &stats_repository).await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.tcp6_connections_handled, 1); - } } diff --git a/packages/http-tracker-core/src/statistics/metrics.rs b/packages/http-tracker-core/src/statistics/metrics.rs index ae4db9704..6c102770b 100644 --- a/packages/http-tracker-core/src/statistics/metrics.rs +++ b/packages/http-tracker-core/src/statistics/metrics.rs @@ -8,20 +8,12 @@ /// and also for each IP version used by the peers: IPv4 and IPv6. #[derive(Debug, PartialEq, Default)] pub struct Metrics { - /// Total number of TCP (HTTP tracker) connections from IPv4 peers. - /// Since the HTTP tracker spec does not require a handshake, this metric - /// increases for every HTTP request. - pub tcp4_connections_handled: u64, - /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. pub tcp4_announces_handled: u64, /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. pub tcp4_scrapes_handled: u64, - /// Total number of TCP (HTTP tracker) connections from IPv6 peers. - pub tcp6_connections_handled: u64, - /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. pub tcp6_announces_handled: u64, diff --git a/packages/http-tracker-core/src/statistics/repository.rs b/packages/http-tracker-core/src/statistics/repository.rs index 41f048e29..5e15fc298 100644 --- a/packages/http-tracker-core/src/statistics/repository.rs +++ b/packages/http-tracker-core/src/statistics/repository.rs @@ -34,12 +34,6 @@ impl Repository { drop(stats_lock); } - pub async fn increase_tcp4_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp4_connections_handled += 1; - drop(stats_lock); - } - pub async fn increase_tcp4_scrapes(&self) { let mut stats_lock = self.stats.write().await; stats_lock.tcp4_scrapes_handled += 1; @@ -52,12 +46,6 @@ impl Repository { drop(stats_lock); } - pub async fn increase_tcp6_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp6_connections_handled += 1; - drop(stats_lock); - } - pub async fn increase_tcp6_scrapes(&self) { let mut stats_lock = self.stats.write().await; stats_lock.tcp6_scrapes_handled += 1; diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index f7808440a..dce7098b9 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -54,11 +54,9 @@ pub async fn get_metrics( torrents_metrics, protocol_metrics: Metrics { // TCPv4 - tcp4_connections_handled: stats.tcp4_connections_handled, tcp4_announces_handled: stats.tcp4_announces_handled, tcp4_scrapes_handled: stats.tcp4_scrapes_handled, // TCPv6 - tcp6_connections_handled: stats.tcp6_connections_handled, tcp6_announces_handled: stats.tcp6_announces_handled, tcp6_scrapes_handled: stats.tcp6_scrapes_handled, }, diff --git a/packages/rest-tracker-api-core/src/statistics/metrics.rs b/packages/rest-tracker-api-core/src/statistics/metrics.rs index 40262efd6..7e41cf713 100644 --- a/packages/rest-tracker-api-core/src/statistics/metrics.rs +++ b/packages/rest-tracker-api-core/src/statistics/metrics.rs @@ -11,6 +11,7 @@ pub struct Metrics { /// Total number of TCP (HTTP tracker) connections from IPv4 peers. /// Since the HTTP tracker spec does not require a handshake, this metric /// increases for every HTTP request. + #[deprecated(since = "3.1.0")] pub tcp4_connections_handled: u64, /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. @@ -20,6 +21,7 @@ pub struct Metrics { pub tcp4_scrapes_handled: u64, /// Total number of TCP (HTTP tracker) connections from IPv6 peers. + #[deprecated(since = "3.1.0")] pub tcp6_connections_handled: u64, /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index ea4e159b6..5d7629443 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -24,6 +24,7 @@ pub struct TrackerMetrics { } /// It returns all the [`TrackerMetrics`] +#[allow(deprecated)] pub async fn get_metrics( in_memory_torrent_repository: Arc, ban_service: Arc>, @@ -37,15 +38,20 @@ pub async fn get_metrics( let udp_core_stats = udp_core_stats_repository.get_stats().await; let udp_server_stats = udp_server_stats_repository.get_stats().await; + // For backward compatibility we keep the `tcp4_connections_handled` and + // `tcp6_connections_handled` metrics. They don't make sense for the HTTP + // tracker, but we keep them for now. In new major versions we should remove + // them. + TrackerMetrics { torrents_metrics, protocol_metrics: Metrics { // TCPv4 - tcp4_connections_handled: http_stats.tcp4_connections_handled, + tcp4_connections_handled: http_stats.tcp4_announces_handled + http_stats.tcp4_scrapes_handled, tcp4_announces_handled: http_stats.tcp4_announces_handled, tcp4_scrapes_handled: http_stats.tcp4_scrapes_handled, // TCPv6 - tcp6_connections_handled: http_stats.tcp6_connections_handled, + tcp6_connections_handled: http_stats.tcp6_announces_handled + http_stats.tcp6_scrapes_handled, tcp6_announces_handled: http_stats.tcp6_announces_handled, tcp6_scrapes_handled: http_stats.tcp6_scrapes_handled, // UDP From 084beb2ef6f0bdd29bbc74dbc2896a499171eb8f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Mar 2025 11:28:30 +0000 Subject: [PATCH 0875/1297] feat: [#727] allow to authenticate API via authentication header The API allos client authentication via a `token` parameter in the URL query: ```console curl http://0.0.0.0:1212/api/v1/stats?token=MyAccessToken | jq ``` Now it's also possible to do it via Authentication Header: ```console curl -H "Authorization: Bearer MyAccessToken" http://0.0.0.0:1212/api/v1/stats | jq ``` This is to avoid leaking the token in logs, proxies, etc. For now, it's only optional and recommendable. It could be mandatory in future major API versions. --- .../src/v1/middlewares/auth.rs | 85 ++++- .../server/v1/contract/authentication.rs | 325 +++++++++++++----- .../rest-tracker-api-client/src/v1/client.rs | 35 +- 3 files changed, 345 insertions(+), 100 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/src/v1/middlewares/auth.rs b/packages/axum-rest-tracker-api-server/src/v1/middlewares/auth.rs index 2ec046bed..9b5ec2320 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/middlewares/auth.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/middlewares/auth.rs @@ -1,7 +1,20 @@ //! Authentication middleware for the API. //! -//! It uses a "token" GET param to authenticate the user. URLs must be of the -//! form: +//! It uses a "token" to authenticate the user. The token must be one of the +//! `access_tokens` in the tracker [HTTP API configuration](torrust_tracker_configuration::HttpApi). +//! +//! There are two ways to provide the token: +//! +//! 1. As a `Bearer` token in the `Authorization` header. +//! 2. As a `token` GET param in the URL. +//! +//! Using the `Authorization` header: +//! +//! ```console +//! curl -H "Authorization: Bearer MyAccessToken" http://:/api/v1/ +//! ``` +//! +//! Using the `token` GET param: //! //! `http://:/api/v1/?token=`. //! @@ -21,6 +34,12 @@ //! All the tokes have the same permissions, so it is not possible to have //! different permissions for different tokens. The label is only used to //! identify the token. +//! +//! NOTICE: The token is not encrypted, so it is recommended to use HTTPS to +//! protect the token from being intercepted. +//! +//! NOTICE: If both the `Authorization` header and the `token` GET param are +//! provided, the `Authorization` header will be used. use std::sync::Arc; use axum::extract::{self}; @@ -32,6 +51,8 @@ use torrust_tracker_configuration::AccessTokens; use crate::v1::responses::unhandled_rejection_response; +pub const AUTH_BEARER_TOKEN_HEADER_PREFIX: &str = "Bearer"; + /// Container for the `token` extracted from the query params. #[derive(Deserialize, Debug)] pub struct QueryParams { @@ -43,7 +64,8 @@ pub struct State { pub access_tokens: Arc, } -/// Middleware for authentication using a "token" GET param. +/// Middleware for authentication. +/// /// The token must be one of the tokens in the tracker [HTTP API configuration](torrust_tracker_configuration::HttpApi). pub async fn auth( extract::State(state): extract::State, @@ -51,8 +73,20 @@ pub async fn auth( request: Request, next: Next, ) -> Response { - let Some(token) = params.token else { - return AuthError::Unauthorized.into_response(); + let token_from_header = match extract_bearer_token_from_header(&request) { + Ok(token) => token, + Err(err) => return err.into_response(), + }; + + let token_from_get_param = params.token.clone(); + + let provided_tokens = (token_from_header, token_from_get_param); + + let token = match provided_tokens { + (Some(token_from_header), Some(_token_from_get_param)) => token_from_header, + (Some(token_from_header), None) => token_from_header, + (None, Some(token_from_get_param)) => token_from_get_param, + (None, None) => return AuthError::Unauthorized.into_response(), }; if !authenticate(&token, &state.access_tokens) { @@ -62,11 +96,42 @@ pub async fn auth( next.run(request).await } +fn extract_bearer_token_from_header(request: &Request) -> Result, AuthError> { + let headers = request.headers(); + + let header_value = headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|header_value| header_value.to_str().ok()); + + match header_value { + None => Ok(None), + Some(header_value) => { + if header_value == AUTH_BEARER_TOKEN_HEADER_PREFIX { + // Empty token + return Ok(Some(String::new())); + } + + if !header_value.starts_with(&format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} ").to_string()) { + // Invalid token type. Missing "Bearer" prefix. + return Err(AuthError::UnknownTokenProvided); + } + + Ok(header_value + .strip_prefix(&format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} ").to_string()) + .map(std::string::ToString::to_string)) + } + } +} + enum AuthError { /// Missing token for authentication. Unauthorized, + /// Token was provided but it is not valid. TokenNotValid, + + /// Token was provided but it is not in a format that the server can't understands. + UnknownTokenProvided, } impl IntoResponse for AuthError { @@ -74,6 +139,7 @@ impl IntoResponse for AuthError { match self { AuthError::Unauthorized => unauthorized_response(), AuthError::TokenNotValid => token_not_valid_response(), + AuthError::UnknownTokenProvided => unknown_auth_data_provided_response(), } } } @@ -93,3 +159,12 @@ pub fn unauthorized_response() -> Response { pub fn token_not_valid_response() -> Response { unhandled_rejection_response("token not valid".to_string()) } + +/// `500` error response when the provided token type is not valid. +/// +/// The client has provided authentication information that the server does not +/// understand. +#[must_use] +pub fn unknown_auth_data_provided_response() -> Response { + unhandled_rejection_response("unknown token provided".to_string()) +} diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs index 3b6419187..0822f9fec 100644 --- a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs @@ -1,130 +1,275 @@ -use torrust_axum_rest_tracker_api_server::environment::Started; -use torrust_rest_tracker_api_client::common::http::{Query, QueryParam}; -use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; -use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; -use torrust_tracker_test_helpers::{configuration, logging}; -use uuid::Uuid; +mod given_that_the_token_is_only_provided_in_the_authentication_header { + use hyper::header; + use torrust_axum_rest_tracker_api_server::environment::Started; + use torrust_rest_tracker_api_client::common::http::Query; + use torrust_rest_tracker_api_client::v1::client::{ + headers_with_auth_token, headers_with_request_id, Client, AUTH_BEARER_TOKEN_HEADER_PREFIX, + }; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; + use uuid::Uuid; -use crate::server::v1::asserts::{assert_token_not_valid, assert_unauthorized}; + use crate::server::v1::asserts::assert_token_not_valid; -#[tokio::test] -async fn should_authenticate_requests_by_using_a_token_query_param() { - logging::setup(); + #[tokio::test] + async fn it_should_authenticate_requests_when_the_token_is_provided_in_the_authentication_header() { + logging::setup(); - let env = Started::new(&configuration::ephemeral().into()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let token = env.get_connection_info().api_token.unwrap(); + let token = env.get_connection_info().api_token.unwrap(); - let response = Client::new(env.get_connection_info()) - .unwrap() - .get_request_with_query("stats", Query::params([QueryParam::new("token", &token)].to_vec()), None) - .await; + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request_with_query("stats", Query::default(), Some(headers_with_auth_token(&token))) + .await; - assert_eq!(response.status(), 200); + assert_eq!(response.status(), 200); - env.stop().await; -} + env.stop().await; + } + + #[tokio::test] + async fn it_should_not_authenticate_requests_when_the_token_is_empty() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + let mut headers = headers_with_request_id(request_id); + + // Send the header with an empty token + headers.insert( + header::AUTHORIZATION, + format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} ") + .parse() + .expect("the auth token is not a valid header value"), + ); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request_with_query("stats", Query::default(), Some(headers)) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; + } -#[tokio::test] -async fn should_not_authenticate_requests_when_the_token_is_missing() { - logging::setup(); + #[tokio::test] + async fn it_should_not_authenticate_requests_when_the_token_is_invalid() { + logging::setup(); - let env = Started::new(&configuration::ephemeral().into()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let request_id = Uuid::new_v4(); + let request_id = Uuid::new_v4(); - let response = Client::new(env.get_connection_info()) - .unwrap() - .get_request_with_query("stats", Query::default(), Some(headers_with_request_id(request_id))) - .await; + let mut headers = headers_with_request_id(request_id); - assert_unauthorized(response).await; + // Send the header with an empty token + headers.insert( + header::AUTHORIZATION, + "Bearer INVALID TOKEN" + .parse() + .expect("the auth token is not a valid header value"), + ); - assert!( - logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), - "Expected logs to contain: ERROR ... API ... request_id={request_id}" - ); + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request_with_query("stats", Query::default(), Some(headers)) + .await; - env.stop().await; + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; + } } +mod given_that_the_token_is_only_provided_in_the_query_param { + + use torrust_axum_rest_tracker_api_server::environment::Started; + use torrust_rest_tracker_api_client::common::http::{Query, QueryParam}; + use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; + use uuid::Uuid; + + use crate::server::v1::asserts::assert_token_not_valid; + + #[tokio::test] + async fn it_should_authenticate_requests_when_the_token_is_provided_as_a_query_param() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let token = env.get_connection_info().api_token.unwrap(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request_with_query("stats", Query::params([QueryParam::new("token", &token)].to_vec()), None) + .await; + + assert_eq!(response.status(), 200); -#[tokio::test] -async fn should_not_authenticate_requests_when_the_token_is_empty() { - logging::setup(); + env.stop().await; + } - let env = Started::new(&configuration::ephemeral().into()).await; + #[tokio::test] + async fn it_should_not_authenticate_requests_when_the_token_is_empty() { + logging::setup(); - let request_id = Uuid::new_v4(); + let env = Started::new(&configuration::ephemeral().into()).await; - let response = Client::new(env.get_connection_info()) - .unwrap() - .get_request_with_query( - "stats", - Query::params([QueryParam::new("token", "")].to_vec()), - Some(headers_with_request_id(request_id)), - ) - .await; + let request_id = Uuid::new_v4(); - assert_token_not_valid(response).await; + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request_with_query( + "stats", + Query::params([QueryParam::new("token", "")].to_vec()), + Some(headers_with_request_id(request_id)), + ) + .await; - assert!( - logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), - "Expected logs to contain: ERROR ... API ... request_id={request_id}" - ); + assert_token_not_valid(response).await; - env.stop().await; + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; + } + + #[tokio::test] + async fn it_should_not_authenticate_requests_when_the_token_is_invalid() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let request_id = Uuid::new_v4(); + + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request_with_query( + "stats", + Query::params([QueryParam::new("token", "INVALID TOKEN")].to_vec()), + Some(headers_with_request_id(request_id)), + ) + .await; + + assert_token_not_valid(response).await; + + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); + + env.stop().await; + } + + #[tokio::test] + async fn it_should_allow_the_token_query_param_to_be_at_any_position_in_the_url_query() { + logging::setup(); + + let env = Started::new(&configuration::ephemeral().into()).await; + + let token = env.get_connection_info().api_token.unwrap(); + + // At the beginning of the query component + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request(&format!("torrents?token={token}&limit=1")) + .await; + + assert_eq!(response.status(), 200); + + // At the end of the query component + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request(&format!("torrents?limit=1&token={token}")) + .await; + + assert_eq!(response.status(), 200); + + env.stop().await; + } } -#[tokio::test] -async fn should_not_authenticate_requests_when_the_token_is_invalid() { - logging::setup(); +mod given_that_not_token_is_provided { + + use torrust_axum_rest_tracker_api_server::environment::Started; + use torrust_rest_tracker_api_client::common::http::Query; + use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; + use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; + use torrust_tracker_test_helpers::{configuration, logging}; + use uuid::Uuid; + + use crate::server::v1::asserts::assert_unauthorized; + + #[tokio::test] + async fn it_should_not_authenticate_requests_when_the_token_is_missing() { + logging::setup(); - let env = Started::new(&configuration::ephemeral().into()).await; + let env = Started::new(&configuration::ephemeral().into()).await; - let request_id = Uuid::new_v4(); + let request_id = Uuid::new_v4(); - let response = Client::new(env.get_connection_info()) - .unwrap() - .get_request_with_query( - "stats", - Query::params([QueryParam::new("token", "INVALID TOKEN")].to_vec()), - Some(headers_with_request_id(request_id)), - ) - .await; + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request_with_query("stats", Query::default(), Some(headers_with_request_id(request_id))) + .await; - assert_token_not_valid(response).await; + assert_unauthorized(response).await; - assert!( - logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), - "Expected logs to contain: ERROR ... API ... request_id={request_id}" - ); + assert!( + logs_contains_a_line_with(&["ERROR", "API", &format!("{request_id}")]), + "Expected logs to contain: ERROR ... API ... request_id={request_id}" + ); - env.stop().await; + env.stop().await; + } } -#[tokio::test] -async fn should_allow_the_token_query_param_to_be_at_any_position_in_the_url_query() { - logging::setup(); +mod given_that_token_is_provided_via_get_param_and_authentication_header { + use torrust_axum_rest_tracker_api_server::environment::Started; + use torrust_rest_tracker_api_client::common::http::{Query, QueryParam}; + use torrust_rest_tracker_api_client::v1::client::{headers_with_auth_token, Client, TOKEN_PARAM_NAME}; + use torrust_tracker_test_helpers::{configuration, logging}; - let env = Started::new(&configuration::ephemeral().into()).await; + #[tokio::test] + async fn it_should_authenticate_requests_using_the_token_provided_in_the_authentication_header() { + logging::setup(); - let token = env.get_connection_info().api_token.unwrap(); + let env = Started::new(&configuration::ephemeral().into()).await; - // At the beginning of the query component - let response = Client::new(env.get_connection_info()) - .unwrap() - .get_request(&format!("torrents?token={token}&limit=1")) - .await; + let authorized_token = env.get_connection_info().api_token.unwrap(); - assert_eq!(response.status(), 200); + let non_authorized_token = "NonAuthorizedToken"; - // At the end of the query component - let response = Client::new(env.get_connection_info()) - .unwrap() - .get_request(&format!("torrents?limit=1&token={token}")) - .await; + let response = Client::new(env.get_connection_info()) + .unwrap() + .get_request_with_query( + "stats", + Query::params([QueryParam::new(TOKEN_PARAM_NAME, non_authorized_token)].to_vec()), + Some(headers_with_auth_token(&authorized_token)), + ) + .await; - assert_eq!(response.status(), 200); + // The token provided in the query param should be ignored and the token + // in the authentication header should be used. + assert_eq!(response.status(), 200); - env.stop().await; + env.stop().await; + } } diff --git a/packages/rest-tracker-api-client/src/v1/client.rs b/packages/rest-tracker-api-client/src/v1/client.rs index 65e3fceb8..d13a567bb 100644 --- a/packages/rest-tracker-api-client/src/v1/client.rs +++ b/packages/rest-tracker-api-client/src/v1/client.rs @@ -1,6 +1,6 @@ use std::time::Duration; -use hyper::HeaderMap; +use hyper::{header, HeaderMap}; use reqwest::{Error, Response}; use serde::Serialize; use url::Url; @@ -9,7 +9,9 @@ use uuid::Uuid; use crate::common::http::{Query, QueryParam, ReqwestQuery}; use crate::connection_info::ConnectionInfo; -const TOKEN_PARAM_NAME: &str = "token"; +pub const TOKEN_PARAM_NAME: &str = "token"; +pub const AUTH_BEARER_TOKEN_HEADER_PREFIX: &str = "Bearer"; + const API_PATH: &str = "api/v1/"; const DEFAULT_REQUEST_TIMEOUT_IN_SECS: u64 = 5; @@ -180,15 +182,38 @@ pub async fn get(path: Url, query: Option, headers: Option) -> builder.send().await.unwrap() } -/// Returns a `HeaderMap` with a request id header +/// Returns a `HeaderMap` with a request id header. /// /// # Panics /// -/// Will panic if the request ID can't be parsed into a string. +/// Will panic if the request ID can't be parsed into a `HeaderValue`. #[must_use] pub fn headers_with_request_id(request_id: Uuid) -> HeaderMap { let mut headers = HeaderMap::new(); - headers.insert("x-request-id", request_id.to_string().parse().unwrap()); + headers.insert( + "x-request-id", + request_id + .to_string() + .parse() + .expect("the request ID is not a valid header value"), + ); + headers +} + +/// Returns a `HeaderMap` with an authorization token. +/// +/// # Panics +/// +/// Will panic if the token can't be parsed into a `HeaderValue`. +#[must_use] +pub fn headers_with_auth_token(token: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert( + header::AUTHORIZATION, + format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}") + .parse() + .expect("the auth token is not a valid header value"), + ); headers } From 34f2f437db7cfbce2fed5a94f906c39a7794b0f9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 10 Mar 2025 15:58:26 +0000 Subject: [PATCH 0876/1297] refactor: [#727] use the Authentication header in the API client Instead of passing the `token` via GET param. The server supports both. Since we have not released any version crate for the client yet we can use the header by deafault which is more secure. --- .../server/v1/contract/authentication.rs | 39 ++++++--- .../rest-tracker-api-client/src/v1/client.rs | 81 ++++++++++++++----- 2 files changed, 89 insertions(+), 31 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs index 0822f9fec..be291a50c 100644 --- a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/authentication.rs @@ -2,6 +2,7 @@ mod given_that_the_token_is_only_provided_in_the_authentication_header { use hyper::header; use torrust_axum_rest_tracker_api_server::environment::Started; use torrust_rest_tracker_api_client::common::http::Query; + use torrust_rest_tracker_api_client::connection_info::ConnectionInfo; use torrust_rest_tracker_api_client::v1::client::{ headers_with_auth_token, headers_with_request_id, Client, AUTH_BEARER_TOKEN_HEADER_PREFIX, }; @@ -80,7 +81,9 @@ mod given_that_the_token_is_only_provided_in_the_authentication_header { .expect("the auth token is not a valid header value"), ); - let response = Client::new(env.get_connection_info()) + let connection_info = ConnectionInfo::anonymous(env.get_connection_info().origin); + + let response = Client::new(connection_info) .unwrap() .get_request_with_query("stats", Query::default(), Some(headers)) .await; @@ -99,7 +102,8 @@ mod given_that_the_token_is_only_provided_in_the_query_param { use torrust_axum_rest_tracker_api_server::environment::Started; use torrust_rest_tracker_api_client::common::http::{Query, QueryParam}; - use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; + use torrust_rest_tracker_api_client::connection_info::ConnectionInfo; + use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client, TOKEN_PARAM_NAME}; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; @@ -114,9 +118,15 @@ mod given_that_the_token_is_only_provided_in_the_query_param { let token = env.get_connection_info().api_token.unwrap(); - let response = Client::new(env.get_connection_info()) + let connection_info = ConnectionInfo::anonymous(env.get_connection_info().origin); + + let response = Client::new(connection_info) .unwrap() - .get_request_with_query("stats", Query::params([QueryParam::new("token", &token)].to_vec()), None) + .get_request_with_query( + "stats", + Query::params([QueryParam::new(TOKEN_PARAM_NAME, &token)].to_vec()), + None, + ) .await; assert_eq!(response.status(), 200); @@ -132,11 +142,13 @@ mod given_that_the_token_is_only_provided_in_the_query_param { let request_id = Uuid::new_v4(); - let response = Client::new(env.get_connection_info()) + let connection_info = ConnectionInfo::anonymous(env.get_connection_info().origin); + + let response = Client::new(connection_info) .unwrap() .get_request_with_query( "stats", - Query::params([QueryParam::new("token", "")].to_vec()), + Query::params([QueryParam::new(TOKEN_PARAM_NAME, "")].to_vec()), Some(headers_with_request_id(request_id)), ) .await; @@ -159,11 +171,13 @@ mod given_that_the_token_is_only_provided_in_the_query_param { let request_id = Uuid::new_v4(); - let response = Client::new(env.get_connection_info()) + let connection_info = ConnectionInfo::anonymous(env.get_connection_info().origin); + + let response = Client::new(connection_info) .unwrap() .get_request_with_query( "stats", - Query::params([QueryParam::new("token", "INVALID TOKEN")].to_vec()), + Query::params([QueryParam::new(TOKEN_PARAM_NAME, "INVALID TOKEN")].to_vec()), Some(headers_with_request_id(request_id)), ) .await; @@ -186,8 +200,10 @@ mod given_that_the_token_is_only_provided_in_the_query_param { let token = env.get_connection_info().api_token.unwrap(); + let connection_info = ConnectionInfo::anonymous(env.get_connection_info().origin); + // At the beginning of the query component - let response = Client::new(env.get_connection_info()) + let response = Client::new(connection_info) .unwrap() .get_request(&format!("torrents?token={token}&limit=1")) .await; @@ -210,6 +226,7 @@ mod given_that_not_token_is_provided { use torrust_axum_rest_tracker_api_server::environment::Started; use torrust_rest_tracker_api_client::common::http::Query; + use torrust_rest_tracker_api_client::connection_info::ConnectionInfo; use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; @@ -225,7 +242,9 @@ mod given_that_not_token_is_provided { let request_id = Uuid::new_v4(); - let response = Client::new(env.get_connection_info()) + let connection_info = ConnectionInfo::anonymous(env.get_connection_info().origin); + + let response = Client::new(connection_info) .unwrap() .get_request_with_query("stats", Query::default(), Some(headers_with_request_id(request_id))) .await; diff --git a/packages/rest-tracker-api-client/src/v1/client.rs b/packages/rest-tracker-api-client/src/v1/client.rs index d13a567bb..da1b709da 100644 --- a/packages/rest-tracker-api-client/src/v1/client.rs +++ b/packages/rest-tracker-api-client/src/v1/client.rs @@ -92,16 +92,18 @@ impl Client { /// /// Will panic if the request can't be sent pub async fn post_empty(&self, path: &str, headers: Option) -> Response { - let builder = self - .client - .post(self.base_url(path).clone()) - .query(&ReqwestQuery::from(self.query_with_token())); + let builder = self.client.post(self.base_url(path).clone()); let builder = match headers { Some(headers) => builder.headers(headers), None => builder, }; + let builder = match &self.connection_info.api_token { + Some(token) => builder.header(header::AUTHORIZATION, format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}")), + None => builder, + }; + builder.send().await.unwrap() } @@ -109,17 +111,18 @@ impl Client { /// /// Will panic if the request can't be sent pub async fn post_form(&self, path: &str, form: &T, headers: Option) -> Response { - let builder = self - .client - .post(self.base_url(path).clone()) - .query(&ReqwestQuery::from(self.query_with_token())) - .json(&form); + let builder = self.client.post(self.base_url(path).clone()).json(&form); let builder = match headers { Some(headers) => builder.headers(headers), None => builder, }; + let builder = match &self.connection_info.api_token { + Some(token) => builder.header(header::AUTHORIZATION, format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}")), + None => builder, + }; + builder.send().await.unwrap() } @@ -127,34 +130,70 @@ impl Client { /// /// Will panic if the request can't be sent async fn delete(&self, path: &str, headers: Option) -> Response { - let builder = self - .client - .delete(self.base_url(path).clone()) - .query(&ReqwestQuery::from(self.query_with_token())); + let builder = self.client.delete(self.base_url(path).clone()); let builder = match headers { Some(headers) => builder.headers(headers), None => builder, }; + let builder = match &self.connection_info.api_token { + Some(token) => builder.header(header::AUTHORIZATION, format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}")), + None => builder, + }; + builder.send().await.unwrap() } + /// # Panics + /// + /// Will panic if it can't convert the authentication token to a `HeaderValue`. pub async fn get_request_with_query(&self, path: &str, params: Query, headers: Option) -> Response { - get(self.base_url(path), Some(params), headers).await + match &self.connection_info.api_token { + Some(token) => { + let headers = if let Some(headers) = headers { + // Headers provided -> add auth token if not already present + + if headers.get(header::AUTHORIZATION).is_some() { + // Auth token already present -> use provided + headers + } else { + let mut headers = headers; + + headers.insert( + header::AUTHORIZATION, + format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}") + .parse() + .expect("the auth token is not a valid header value"), + ); + + headers + } + } else { + // No headers provided -> create headers with auth token + + let mut headers = HeaderMap::new(); + + headers.insert( + header::AUTHORIZATION, + format!("{AUTH_BEARER_TOKEN_HEADER_PREFIX} {token}") + .parse() + .expect("the auth token is not a valid header value"), + ); + + headers + }; + + get(self.base_url(path), Some(params), Some(headers)).await + } + None => get(self.base_url(path), Some(params), headers).await, + } } pub async fn get_request(&self, path: &str) -> Response { get(self.base_url(path), None, None).await } - fn query_with_token(&self) -> Query { - match &self.connection_info.api_token { - Some(token) => Query::params([QueryParam::new("token", token)].to_vec()), - None => Query::default(), - } - } - fn base_url(&self, path: &str) -> Url { Url::parse(&format!("{}{}{path}", &self.connection_info.origin, &self.base_path)).unwrap() } From aedcd3e261d77c12f4d127844c84c0286da7222c Mon Sep 17 00:00:00 2001 From: Ikko Eltociear Ashimine Date: Tue, 11 Mar 2025 03:19:43 +0900 Subject: [PATCH 0877/1297] docs: update README.md minor fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b7431e859..33fc4a028 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ podman run -it docker.io/torrust/tracker:develop # Checkout repository into a new folder: git clone https://github.com/torrust/torrust-tracker.git -# Change into directory and create a empty database file: +# Change into directory and create an empty database file: cd torrust-tracker mkdir -p ./storage/tracker/lib/database/ touch ./storage/tracker/lib/database/sqlite3.db From c15573200caad686cbca63522ff1a8752760d645 Mon Sep 17 00:00:00 2001 From: nuts_rice Date: Tue, 4 Feb 2025 12:39:36 -0500 Subject: [PATCH 0878/1297] chore: barebones benchmarks for UDP and HTTP core packages - http + udp tracker core bench mods - bench sh script --- Cargo.lock | 240 ++++++++++-------- contrib/dev-tools/benches/run-benches.sh | 9 + packages/http-tracker-core/Cargo.toml | 6 + .../http-tracker-core/benches/helpers/mod.rs | 2 + .../http-tracker-core/benches/helpers/sync.rs | 31 +++ .../http-tracker-core/benches/helpers/util.rs | 118 +++++++++ .../benches/http_tracker_core_benchmark.rs | 23 ++ packages/udp-tracker-core/Cargo.toml | 6 + .../udp-tracker-core/benches/helpers/mod.rs | 2 + .../udp-tracker-core/benches/helpers/sync.rs | 21 ++ .../udp-tracker-core/benches/helpers/utils.rs | 25 ++ .../benches/udp_tracker_core_benchmark.rs | 20 ++ .../src/statistics/event/handler.rs | 125 ++++++++- 13 files changed, 515 insertions(+), 113 deletions(-) create mode 100755 contrib/dev-tools/benches/run-benches.sh create mode 100644 packages/http-tracker-core/benches/helpers/mod.rs create mode 100644 packages/http-tracker-core/benches/helpers/sync.rs create mode 100644 packages/http-tracker-core/benches/helpers/util.rs create mode 100644 packages/http-tracker-core/benches/http_tracker_core_benchmark.rs create mode 100644 packages/udp-tracker-core/benches/helpers/mod.rs create mode 100644 packages/udp-tracker-core/benches/helpers/sync.rs create mode 100644 packages/udp-tracker-core/benches/helpers/utils.rs create mode 100644 packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs diff --git a/Cargo.lock b/Cargo.lock index 1a6a09244..4d5157055 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -264,7 +264,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix", + "rustix 0.38.44", "slab", "tracing", "windows-sys 0.59.0", @@ -322,7 +322,7 @@ checksum = "d556ec1359574147ec0c4fc5eb525f3f23263a592b1a9c07e0a75b427de55c97" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -444,7 +444,7 @@ checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -532,7 +532,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -561,6 +561,7 @@ dependencies = [ "bittorrent-http-tracker-protocol", "bittorrent-primitives", "bittorrent-tracker-core", + "criterion", "futures", "mockall", "thiserror 2.0.12", @@ -669,6 +670,7 @@ dependencies = [ "bloom", "blowfish", "cipher", + "criterion", "futures", "lazy_static", "mockall", @@ -814,7 +816,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -1018,9 +1020,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.31" +version = "4.5.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "027bb0d98429ae334a8698531da7077bdf906419543a35a55c2cb1b66437d767" +checksum = "6088f3ae8c3608d19260cd7445411865a485688711b78b5be70d78cd96136f83" dependencies = [ "clap_builder", "clap_derive", @@ -1028,9 +1030,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.31" +version = "4.5.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5589e0cba072e0f3d23791efac0fd8627b49c829c196a492e88168e6a669d863" +checksum = "22a7ef7f676155edfb82daa97f99441f3ebf4a58d5e32f295a56259f1b6facc8" dependencies = [ "anstream", "anstyle", @@ -1040,14 +1042,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.28" +version = "4.5.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf4ced95c6f4a675af3da73304b9ac4ed991640c36374e4b46795c49e17cf1ed" +checksum = "09176aae279615badda0765c0c0b3f6ed53f4709118af73cf4655d85d1530cd7" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -1278,7 +1280,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -1289,7 +1291,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -1333,7 +1335,7 @@ checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", "unicode-xid", ] @@ -1345,7 +1347,7 @@ checksum = "ccfae181bab5ab6c5478b2ccb69e4c68a02f8c3ec72f6616bfec9dbc599d2ee0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -1366,7 +1368,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -1388,9 +1390,9 @@ checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" [[package]] name = "either" -version = "1.14.0" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7914353092ddf589ad78f25c5c1c21b7f80b0ff8621e7c814c3485b5306da9d" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "encoding_rs" @@ -1603,7 +1605,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -1615,7 +1617,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -1627,7 +1629,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -1705,7 +1707,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -1813,7 +1815,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.7.1", + "indexmap 2.8.0", "slab", "tokio", "tokio-util", @@ -1877,6 +1879,12 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" +[[package]] +name = "hermit-abi" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbd780fe5cc30f81464441920d82ac8740e2e46b29a6fad543ddd075229ce37e" + [[package]] name = "hex" version = "0.4.3" @@ -2185,7 +2193,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -2228,9 +2236,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.7.1" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652" +checksum = "3954d50fe15b02142bf25d3b8bdadb634ec3948f103d04ffe3031bc8fe9d7058" dependencies = [ "equivalent", "hashbrown 0.15.2", @@ -2269,11 +2277,11 @@ checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" [[package]] name = "is-terminal" -version = "0.4.15" +version = "0.4.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e19b23d53f35ce9f56aebc7d1bb4e6ac1e9c0db7ac85c8d1760c04379edced37" +checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" dependencies = [ - "hermit-abi", + "hermit-abi 0.5.0", "libc", "windows-sys 0.59.0", ] @@ -2344,9 +2352,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.170" +version = "0.2.171" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "875b3680cb2f8f71bdcf9a30f38d48282f5d3c95cbf9b3fa57269bb5d5c06828" +checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" [[package]] name = "libloading" @@ -2377,9 +2385,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.31.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8935b44e7c13394a179a438e0cebba0fe08fe01b54f152e29a93b5cf993fd4" +checksum = "fbb8270bb4060bd76c6e96f20c52d80620f1d82a3470885694e41e0f81ef6fe7" dependencies = [ "cc", "pkg-config", @@ -2403,6 +2411,12 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +[[package]] +name = "linux-raw-sys" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db9c683daf087dc577b7506e9695b3d556a9f3849903fa28186283afd6809e9" + [[package]] name = "litemap" version = "0.7.5" @@ -2516,7 +2530,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -2566,7 +2580,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", "termcolor", "thiserror 1.0.69", ] @@ -2732,15 +2746,15 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.20.3" +version = "1.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "945462a4b81e43c4e3ba96bd7b49d834c6f61198356aa858733bc4acf3cbe62e" +checksum = "cde51589ab56b20a6f686b2c68f7a0bd6add753d697abf720d63f8db3ab7b1ad" [[package]] name = "oorandom" -version = "11.1.4" +version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b410bbe7e14ab526a0e86877eb47c6996a2bd7746f027ba551028c925390e4e9" +checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "openssl" @@ -2765,7 +2779,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -2843,7 +2857,7 @@ dependencies = [ "regex", "regex-syntax", "structmeta", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -2866,7 +2880,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -2940,7 +2954,7 @@ checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -3008,9 +3022,9 @@ checksum = "a604568c3202727d1507653cb121dbd627a58684eb09a820fd746bee38b4442f" dependencies = [ "cfg-if", "concurrent-queue", - "hermit-abi", + "hermit-abi 0.4.0", "pin-project-lite", - "rustix", + "rustix 0.38.44", "tracing", "windows-sys 0.59.0", ] @@ -3029,11 +3043,11 @@ checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" [[package]] name = "ppv-lite86" -version = "0.2.20" +version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ - "zerocopy 0.7.35", + "zerocopy 0.8.23", ] [[package]] @@ -3064,9 +3078,9 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "3.2.0" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecf48c7ca261d60b74ab1a7b20da18bede46776b2e55535cb958eb595c5fa7b" +checksum = "edce586971a4dfaa28950c6f18ed55e0406c1ab88bbce2c6f6293a7aaba73d35" dependencies = [ "toml_edit", ] @@ -3090,7 +3104,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -3110,7 +3124,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", "version_check", "yansi", ] @@ -3178,9 +3192,9 @@ dependencies = [ [[package]] name = "r2d2_sqlite" -version = "0.26.0" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee025287c0188d75ae2563bcb91c9b0d1843cfc56e4bd3ab867597971b5cc256" +checksum = "180da684f0a188977d3968f139eb44260192ef8d9a5b7b7cbd01d881e0353179" dependencies = [ "r2d2", "rusqlite", @@ -3212,7 +3226,7 @@ checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.3", - "zerocopy 0.8.21", + "zerocopy 0.8.23", ] [[package]] @@ -3381,9 +3395,9 @@ dependencies = [ [[package]] name = "ring" -version = "0.17.11" +version = "0.17.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da5349ae27d3887ca812fb375b45a4fbb36d8d12d2df394968cd86e35683fe73" +checksum = "70ac5d832aa16abd7d1def883a8545280c20a60f523a370aa3a9617c2b8550ee" dependencies = [ "cc", "cfg-if", @@ -3458,15 +3472,15 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.99", + "syn 2.0.100", "unicode-ident", ] [[package]] name = "rusqlite" -version = "0.33.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c6d5e5acb6f6129fe3f7ba0a7fc77bca1942cb568535e18e7bc40262baf3110" +checksum = "37e34486da88d8e051c7c0e23c3f15fd806ea8546260aa2fec247e97242ec143" dependencies = [ "bitflags 2.9.0", "fallible-iterator", @@ -3522,7 +3536,20 @@ dependencies = [ "bitflags 2.9.0", "errno", "libc", - "linux-raw-sys", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7178faa4b75a30e269c71e61c353ce2748cf3d76f0c44c393f4e60abf49b825" +dependencies = [ + "bitflags 2.9.0", + "errno", + "libc", + "linux-raw-sys 0.9.2", "windows-sys 0.59.0", ] @@ -3679,9 +3706,9 @@ checksum = "56e6fa9c48d24d85fb3de5ad847117517440f6beceb7798af16b4a87d616b8d0" [[package]] name = "serde" -version = "1.0.218" +version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8dfc9d19bdbf6d17e22319da49161d5d0108e4188e8b680aef6299eed22df60" +checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" dependencies = [ "serde_derive", ] @@ -3698,22 +3725,22 @@ dependencies = [ [[package]] name = "serde_bytes" -version = "0.11.16" +version = "0.11.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "364fec0df39c49a083c9a8a18a23a6bcfd9af130fe9fe321d18520a0d113e09e" +checksum = "8437fd221bde2d4ca316d61b90e337e9e702b3820b87d63caa9ba6c02bd06d96" dependencies = [ "serde", ] [[package]] name = "serde_derive" -version = "1.0.218" +version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f09503e191f4e797cb8aac08e9a4a4695c5edf6a2e70e376d961ddd5c969f82b" +checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -3723,7 +3750,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d2de91cf02bbc07cde38891769ccd5d4f073d22a40683aa4bc7a95781aaa2c4" dependencies = [ "form_urlencoded", - "indexmap 2.7.1", + "indexmap 2.8.0", "itoa", "ryu", "serde", @@ -3735,7 +3762,7 @@ version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" dependencies = [ - "indexmap 2.7.1", + "indexmap 2.8.0", "itoa", "memchr", "ryu", @@ -3760,7 +3787,7 @@ checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -3794,7 +3821,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.7.1", + "indexmap 2.8.0", "serde", "serde_derive", "serde_json", @@ -3811,7 +3838,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -3924,7 +3951,7 @@ dependencies = [ "proc-macro2", "quote", "structmeta-derive", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -3935,7 +3962,7 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -3967,9 +3994,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.99" +version = "2.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e02e925281e18ffd9d640e234264753c43edc62d64b2d4cf898f1bc5e75f3fc2" +checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" dependencies = [ "proc-macro2", "quote", @@ -3993,7 +4020,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -4042,15 +4069,15 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.17.1" +version = "3.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e5a0acb1f3f55f65cc4a866c361b2fb2a0ff6366785ae6fbb5f85df07ba230" +checksum = "2c317e0a526ee6120d8dabad239c8dadca62b24b6f168914bbbc8e2fb1f0e567" dependencies = [ "cfg-if", "fastrand", "getrandom 0.3.1", "once_cell", - "rustix", + "rustix 1.0.2", "windows-sys 0.59.0", ] @@ -4124,7 +4151,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -4135,7 +4162,7 @@ checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -4150,9 +4177,9 @@ dependencies = [ [[package]] name = "time" -version = "0.3.38" +version = "0.3.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb041120f25f8fbe8fd2dbe4671c7c2ed74d83be2e7a77529bf7e0790ae3f472" +checksum = "dad298b01a40a23aac4580b67e3dbedb7cc8402f3592d7f49469de2ea4aecdd8" dependencies = [ "deranged", "itoa", @@ -4216,9 +4243,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.43.0" +version = "1.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d61fa4ffa3de412bfea335c6ecff681de2b609ba3c77ef3e00e521813a9ed9e" +checksum = "9975ea0f48b5aa3972bf2d888c238182458437cc2a19374b81b25cdf1023fb3a" dependencies = [ "backtrace", "bytes", @@ -4239,7 +4266,7 @@ checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -4328,7 +4355,7 @@ version = "0.22.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17b4795ff5edd201c7cd6dca065ae59972ce77d1b80fa0a84d94950ece7d1474" dependencies = [ - "indexmap 2.7.1", + "indexmap 2.8.0", "serde", "serde_spanned", "toml_datetime", @@ -4758,7 +4785,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -4979,7 +5006,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", "wasm-bindgen-shared", ] @@ -5014,7 +5041,7 @@ checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -5303,13 +5330,12 @@ dependencies = [ [[package]] name = "xattr" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e105d177a3871454f754b33bb0ee637ecaaac997446375fd3e5d43a2ed00c909" +checksum = "0d65cbf2f12c15564212d48f4e3dfb87923d25d611f2aed18f4cb23f0413d89e" dependencies = [ "libc", - "linux-raw-sys", - "rustix", + "rustix 1.0.2", ] [[package]] @@ -5338,7 +5364,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", "synstructure", ] @@ -5354,11 +5380,11 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.21" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf01143b2dd5d134f11f545cf9f1431b13b749695cb33bcce051e7568f99478" +checksum = "fd97444d05a4328b90e75e503a34bad781f14e28a823ad3557f0750df1ebcbc6" dependencies = [ - "zerocopy-derive 0.8.21", + "zerocopy-derive 0.8.23", ] [[package]] @@ -5369,18 +5395,18 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] name = "zerocopy-derive" -version = "0.8.21" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712c8386f4f4299382c9abee219bee7084f78fb939d88b6840fcc1320d5f6da2" +checksum = "6352c01d0edd5db859a63e2605f4ea3183ddbd15e2c4a9e7d32184df75e4f154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] @@ -5400,7 +5426,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", "synstructure", ] @@ -5429,7 +5455,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.99", + "syn 2.0.100", ] [[package]] diff --git a/contrib/dev-tools/benches/run-benches.sh b/contrib/dev-tools/benches/run-benches.sh new file mode 100755 index 000000000..0de356492 --- /dev/null +++ b/contrib/dev-tools/benches/run-benches.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +# This script is only intended to be used for local development or testing environments. + +cargo bench --package torrust-tracker-torrent-repository + +cargo bench --package bittorrent-http-tracker-core + +cargo bench --package bittorrent-udp-tracker-core diff --git a/packages/http-tracker-core/Cargo.toml b/packages/http-tracker-core/Cargo.toml index 1e0bcff28..aaf982b04 100644 --- a/packages/http-tracker-core/Cargo.toml +++ b/packages/http-tracker-core/Cargo.toml @@ -18,6 +18,7 @@ aquatic_udp_protocol = "0" bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "../http-protocol" } bittorrent-primitives = "0.1.0" bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } +criterion = { version = "0.5.1", features = ["async_tokio"] } futures = "0" thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } @@ -28,3 +29,8 @@ tracing = "0" [dev-dependencies] mockall = "0" torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } + +[[bench]] +harness = false +name = "http_tracker_core_benchmark" + diff --git a/packages/http-tracker-core/benches/helpers/mod.rs b/packages/http-tracker-core/benches/helpers/mod.rs new file mode 100644 index 000000000..4a91f2224 --- /dev/null +++ b/packages/http-tracker-core/benches/helpers/mod.rs @@ -0,0 +1,2 @@ +pub mod sync; +pub mod util; diff --git a/packages/http-tracker-core/benches/helpers/sync.rs b/packages/http-tracker-core/benches/helpers/sync.rs new file mode 100644 index 000000000..c19943b1d --- /dev/null +++ b/packages/http-tracker-core/benches/helpers/sync.rs @@ -0,0 +1,31 @@ +use std::time::{Duration, Instant}; + +use bittorrent_http_tracker_core::services::announce::AnnounceService; + +use crate::helpers::util::{initialize_core_tracker_services, sample_announce_request_for_peer, sample_peer}; + +#[must_use] +pub async fn return_announce_data_once(samples: u64) -> Duration { + let (core_tracker_services, core_http_tracker_services) = initialize_core_tracker_services(); + + let peer = sample_peer(); + + let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); + + let announce_service = AnnounceService::new( + core_tracker_services.core_config.clone(), + core_tracker_services.announce_handler.clone(), + core_tracker_services.authentication_service.clone(), + core_tracker_services.whitelist_authorization.clone(), + core_http_tracker_services.http_stats_event_sender.clone(), + ); + + let start = Instant::now(); + for _ in 0..samples { + let _announce_data = announce_service + .handle_announce(&announce_request, &client_ip_sources, None) + .await + .unwrap(); + } + start.elapsed() +} diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs new file mode 100644 index 000000000..f15e9db8f --- /dev/null +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -0,0 +1,118 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::sync::Arc; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::AnnounceHandler; +use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; +use bittorrent_tracker_core::authentication::service::AuthenticationService; +use bittorrent_tracker_core::databases::setup::initialize_database; +use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; +use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; +use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use torrust_tracker_configuration::{Configuration, Core}; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; +use torrust_tracker_test_helpers::configuration; + +pub struct CoreTrackerServices { + pub core_config: Arc, + pub announce_handler: Arc, + pub authentication_service: Arc, + pub whitelist_authorization: Arc, +} + +pub struct CoreHttpTrackerServices { + pub http_stats_event_sender: Arc>>, +} + +pub fn initialize_core_tracker_services() -> (CoreTrackerServices, CoreHttpTrackerServices) { + initialize_core_tracker_services_with_config(&configuration::ephemeral_public()) +} + +pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) { + let core_config = Arc::new(config.core.clone()); + let database = initialize_database(&config.core); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); + let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); + let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); + let authentication_service = Arc::new(AuthenticationService::new(&core_config, &in_memory_key_repository)); + + let announce_handler = Arc::new(AnnounceHandler::new( + &config.core, + &whitelist_authorization, + &in_memory_torrent_repository, + &db_torrent_repository, + )); + + // HTTP stats + let (http_stats_event_sender, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = Arc::new(http_stats_event_sender); + let _http_stats_repository = Arc::new(http_stats_repository); + + ( + CoreTrackerServices { + core_config, + announce_handler, + authentication_service, + whitelist_authorization, + }, + CoreHttpTrackerServices { http_stats_event_sender }, + ) +} + +pub fn sample_peer() -> peer::Peer { + peer::Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Started, + } +} + +pub fn sample_announce_request_for_peer(peer: Peer) -> (Announce, ClientIpSources) { + let announce_request = Announce { + info_hash: sample_info_hash(), + peer_id: peer.peer_id, + port: peer.peer_addr.port(), + uploaded: Some(peer.uploaded), + downloaded: Some(peer.downloaded), + left: Some(peer.left), + event: Some(peer.event.into()), + compact: None, + numwant: None, + }; + + let client_ip_sources = ClientIpSources { + right_most_x_forwarded_for: None, + connection_info_ip: Some(peer.peer_addr.ip()), + }; + + (announce_request, client_ip_sources) +} +#[must_use] +pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") +} + +use bittorrent_http_tracker_core::statistics; +use futures::future::BoxFuture; +use mockall::mock; +use tokio::sync::mpsc::error::SendError; + +mock! { + HttpStatsEventSender {} + impl statistics::event::sender::Sender for HttpStatsEventSender { + fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + } +} diff --git a/packages/http-tracker-core/benches/http_tracker_core_benchmark.rs b/packages/http-tracker-core/benches/http_tracker_core_benchmark.rs new file mode 100644 index 000000000..aa50ceeb9 --- /dev/null +++ b/packages/http-tracker-core/benches/http_tracker_core_benchmark.rs @@ -0,0 +1,23 @@ +mod helpers; + +use std::time::Duration; + +use criterion::{criterion_group, criterion_main, Criterion}; + +use crate::helpers::sync; + +fn announce_once(c: &mut Criterion) { + let _rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("http_tracker_handle_announce_once"); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_millis(1000)); + + group.bench_function("handle_announce_data", |b| { + b.iter(|| sync::return_announce_data_once(100)); + }); +} + +criterion_group!(benches, announce_once); +criterion_main!(benches); diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml index fc8e2328c..88bab51c1 100644 --- a/packages/udp-tracker-core/Cargo.toml +++ b/packages/udp-tracker-core/Cargo.toml @@ -21,6 +21,7 @@ bittorrent-udp-tracker-protocol = { version = "3.0.0-develop", path = "../udp-pr bloom = "0.3.2" blowfish = "0" cipher = "0" +criterion = { version = "0.5.1", features = ["async_tokio"] } futures = "0" lazy_static = "1" rand = "0" @@ -34,3 +35,8 @@ zerocopy = "0.7" [dev-dependencies] mockall = "0" torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } + +[[bench]] +harness = false +name = "udp_tracker_core_benchmark" + diff --git a/packages/udp-tracker-core/benches/helpers/mod.rs b/packages/udp-tracker-core/benches/helpers/mod.rs new file mode 100644 index 000000000..ea1959bb4 --- /dev/null +++ b/packages/udp-tracker-core/benches/helpers/mod.rs @@ -0,0 +1,2 @@ +pub mod sync; +mod utils; diff --git a/packages/udp-tracker-core/benches/helpers/sync.rs b/packages/udp-tracker-core/benches/helpers/sync.rs new file mode 100644 index 000000000..b7d8e848d --- /dev/null +++ b/packages/udp-tracker-core/benches/helpers/sync.rs @@ -0,0 +1,21 @@ +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use bittorrent_udp_tracker_core::services::connect::ConnectService; +use bittorrent_udp_tracker_core::statistics; + +use crate::helpers::utils::{sample_ipv4_remote_addr, sample_issue_time}; + +#[allow(clippy::unused_async)] +pub async fn connect_once(samples: u64) -> Duration { + let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); + let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); + let start = Instant::now(); + + for _ in 0..samples { + let _response = connect_service.handle_connect(sample_ipv4_remote_addr(), sample_issue_time()); + } + + start.elapsed() +} diff --git a/packages/udp-tracker-core/benches/helpers/utils.rs b/packages/udp-tracker-core/benches/helpers/utils.rs new file mode 100644 index 000000000..7fd6d175f --- /dev/null +++ b/packages/udp-tracker-core/benches/helpers/utils.rs @@ -0,0 +1,25 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use bittorrent_udp_tracker_core::statistics; +use futures::future::BoxFuture; +use mockall::mock; +use tokio::sync::mpsc::error::SendError; + +pub(crate) fn sample_ipv4_remote_addr() -> SocketAddr { + sample_ipv4_socket_address() +} + +pub(crate) fn sample_ipv4_socket_address() -> SocketAddr { + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) +} + +pub(crate) fn sample_issue_time() -> f64 { + 1_000_000_000_f64 +} + +mock! { + pub(crate) UdpCoreStatsEventSender {} + impl statistics::event::sender::Sender for UdpCoreStatsEventSender { + fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + } +} diff --git a/packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs b/packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs new file mode 100644 index 000000000..5bd0e27c8 --- /dev/null +++ b/packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs @@ -0,0 +1,20 @@ +mod helpers; + +use std::time::Duration; + +use criterion::{criterion_group, criterion_main, Criterion}; + +use crate::helpers::sync; + +fn bench_connect_once(c: &mut Criterion) { + let mut group = c.benchmark_group("udp_tracker/connect_once"); + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_millis(1000)); + + group.bench_function("connect_once", |b| { + b.iter(|| sync::connect_once(100)); + }); +} + +criterion_group!(benches, bench_connect_once); +criterion_main!(benches); diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index b3b86e20a..5ce9f6307 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -93,24 +93,29 @@ mod tests { use crate::statistics::repository::Repository; #[tokio::test] - async fn should_increase_the_udp_abort_counter_when_it_receives_a_udp_abort_event() { + async fn should_increase_the_number_of_aborted_requests_when_it_receives_a_udp_request_aborted_event() { let stats_repository = Repository::new(); handle_event(Event::UdpRequestAborted, &stats_repository).await; + let stats = stats_repository.get_stats().await; + assert_eq!(stats.udp_requests_aborted, 1); } + #[tokio::test] - async fn should_increase_the_udp_ban_counter_when_it_receives_a_udp_banned_event() { + async fn should_increase_the_number_of_banned_requests_when_it_receives_a_udp_request_banned_event() { let stats_repository = Repository::new(); handle_event(Event::UdpRequestBanned, &stats_repository).await; + let stats = stats_repository.get_stats().await; + assert_eq!(stats.udp_requests_banned, 1); } #[tokio::test] - async fn should_increase_the_udp4_requests_counter_when_it_receives_a_udp4_request_event() { + async fn should_increase_the_number_of_incoming_requests_when_it_receives_a_udp4_incoming_request_event() { let stats_repository = Repository::new(); handle_event(Event::Udp4IncomingRequest, &stats_repository).await; @@ -120,6 +125,74 @@ mod tests { assert_eq!(stats.udp4_requests, 1); } + #[tokio::test] + async fn should_increase_the_udp_abort_counter_when_it_receives_a_udp_abort_event() { + let stats_repository = Repository::new(); + + handle_event(Event::UdpRequestAborted, &stats_repository).await; + let stats = stats_repository.get_stats().await; + assert_eq!(stats.udp_requests_aborted, 1); + } + #[tokio::test] + async fn should_increase_the_udp_ban_counter_when_it_receives_a_udp_banned_event() { + let stats_repository = Repository::new(); + + handle_event(Event::UdpRequestBanned, &stats_repository).await; + let stats = stats_repository.get_stats().await; + assert_eq!(stats.udp_requests_banned, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_connect_requests_counter_when_it_receives_a_udp4_request_event_of_connect_kind() { + let stats_repository = Repository::new(); + + handle_event( + Event::Udp4Request { + kind: crate::statistics::event::UdpResponseKind::Connect, + }, + &stats_repository, + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_announce_requests_counter_when_it_receives_a_udp4_request_event_of_announce_kind() { + let stats_repository = Repository::new(); + + handle_event( + Event::Udp4Request { + kind: crate::statistics::event::UdpResponseKind::Announce, + }, + &stats_repository, + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_announces_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_scrape_requests_counter_when_it_receives_a_udp4_request_event_of_scrape_kind() { + let stats_repository = Repository::new(); + + handle_event( + Event::Udp4Request { + kind: crate::statistics::event::UdpResponseKind::Scrape, + }, + &stats_repository, + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_scrapes_handled, 1); + } + #[tokio::test] async fn should_increase_the_udp4_responses_counter_when_it_receives_a_udp4_response_event() { let stats_repository = Repository::new(); @@ -150,14 +223,54 @@ mod tests { } #[tokio::test] - async fn should_increase_the_udp6_requests_counter_when_it_receives_a_udp6_request_event() { + async fn should_increase_the_udp6_connect_requests_counter_when_it_receives_a_udp6_request_event_of_connect_kind() { + let stats_repository = Repository::new(); + + handle_event( + Event::Udp6Request { + kind: crate::statistics::event::UdpResponseKind::Connect, + }, + &stats_repository, + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_announce_requests_counter_when_it_receives_a_udp6_request_event_of_announce_kind() { + let stats_repository = Repository::new(); + + handle_event( + Event::Udp6Request { + kind: crate::statistics::event::UdpResponseKind::Announce, + }, + &stats_repository, + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_announces_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_scrape_requests_counter_when_it_receives_a_udp6_request_event_of_scrape_kind() { let stats_repository = Repository::new(); - handle_event(Event::Udp6IncomingRequest, &stats_repository).await; + handle_event( + Event::Udp6Request { + kind: crate::statistics::event::UdpResponseKind::Scrape, + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp6_requests, 1); + assert_eq!(stats.udp6_scrapes_handled, 1); } #[tokio::test] From 6de2dd997f8a72e2443466c437a45a97829a2507 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 11 Mar 2025 15:51:58 +0000 Subject: [PATCH 0879/1297] refactor: [#1371] add connection context to HTTP core events --- .../src/v1/handlers/announce.rs | 45 +++++++-- .../src/v1/handlers/scrape.rs | 39 ++++++-- .../axum-http-tracker-server/src/v1/routes.rs | 8 +- .../http-tracker-core/benches/helpers/sync.rs | 7 +- .../src/services/announce.rs | 63 +++++++++--- .../http-tracker-core/src/services/scrape.rs | 84 ++++++++++++---- .../src/statistics/event/handler.rs | 99 +++++++++++++++---- .../src/statistics/event/mod.rs | 23 +++-- .../src/statistics/keeper.rs | 13 ++- 9 files changed, 301 insertions(+), 80 deletions(-) diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 6c2e4b713..63ab96fe5 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -2,6 +2,7 @@ //! //! The handlers perform the authentication and authorization of the request, //! and resolve the client IP address. +use std::net::SocketAddr; use std::sync::Arc; use axum::extract::State; @@ -22,27 +23,27 @@ use crate::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; /// authentication (no PATH `key` parameter required). #[allow(clippy::unused_async)] pub async fn handle_without_key( - State(state): State>, + State(state): State<(Arc, SocketAddr)>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { tracing::debug!("http announce request: {:#?}", announce_request); - handle(&state, &announce_request, &client_ip_sources, None).await + handle(&state.0, &announce_request, &client_ip_sources, &state.1, None).await } /// It handles the `announce` request when the HTTP tracker requires /// authentication (PATH `key` parameter required). #[allow(clippy::unused_async)] pub async fn handle_with_key( - State(state): State>, + State(state): State<(Arc, SocketAddr)>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { tracing::debug!("http announce request: {:#?}", announce_request); - handle(&state, &announce_request, &client_ip_sources, Some(key)).await + handle(&state.0, &announce_request, &client_ip_sources, &state.1, Some(key)).await } /// It handles the `announce` request. @@ -53,9 +54,18 @@ async fn handle( announce_service: &Arc, announce_request: &Announce, client_ip_sources: &ClientIpSources, + server_socket_addr: &SocketAddr, maybe_key: Option, ) -> Response { - let announce_data = match handle_announce(announce_service, announce_request, client_ip_sources, maybe_key).await { + let announce_data = match handle_announce( + announce_service, + announce_request, + client_ip_sources, + server_socket_addr, + maybe_key, + ) + .await + { Ok(announce_data) => announce_data, Err(error) => { let error_response = responses::error::Error { @@ -71,10 +81,11 @@ async fn handle_announce( announce_service: &Arc, announce_request: &Announce, client_ip_sources: &ClientIpSources, + server_socket_addr: &SocketAddr, maybe_key: Option, ) -> Result { announce_service - .handle_announce(announce_request, client_ip_sources, maybe_key) + .handle_announce(announce_request, client_ip_sources, server_socket_addr, maybe_key) .await } @@ -196,6 +207,7 @@ mod tests { mod with_tracker_in_private_mode { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; use bittorrent_http_tracker_protocol::v1::responses; @@ -209,12 +221,15 @@ mod tests { async fn it_should_fail_when_the_authentication_key_is_missing() { let http_core_tracker_services = initialize_private_tracker(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let maybe_key = None; let response = handle_announce( &http_core_tracker_services.announce_service, &sample_announce_request(), &sample_client_ip_sources(), + &server_socket_addr, maybe_key, ) .await @@ -236,12 +251,15 @@ mod tests { let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let maybe_key = Some(unregistered_key); let response = handle_announce( &http_core_tracker_services.announce_service, &sample_announce_request(), &sample_client_ip_sources(), + &server_socket_addr, maybe_key, ) .await @@ -260,6 +278,8 @@ mod tests { mod with_tracker_in_listed_mode { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use bittorrent_http_tracker_protocol::v1::responses; use super::{initialize_listed_tracker, sample_announce_request, sample_client_ip_sources}; @@ -272,10 +292,13 @@ mod tests { let announce_request = sample_announce_request(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let response = handle_announce( &http_core_tracker_services.announce_service, &announce_request, &sample_client_ip_sources(), + &server_socket_addr, None, ) .await @@ -297,6 +320,8 @@ mod tests { mod with_tracker_on_reverse_proxy { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -313,10 +338,13 @@ mod tests { connection_info_ip: None, }; + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let response = handle_announce( &http_core_tracker_services.announce_service, &sample_announce_request(), &client_ip_sources, + &server_socket_addr, None, ) .await @@ -335,6 +363,8 @@ mod tests { mod with_tracker_not_on_reverse_proxy { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -351,10 +381,13 @@ mod tests { connection_info_ip: None, }; + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let response = handle_announce( &http_core_tracker_services.announce_service, &sample_announce_request(), &client_ip_sources, + &server_socket_addr, None, ) .await diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index ae3a35bd3..ca90f74c6 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -2,6 +2,7 @@ //! //! The handlers perform the authentication and authorization of the request, //! and resolve the client IP address. +use std::net::SocketAddr; use std::sync::Arc; use axum::extract::State; @@ -22,13 +23,13 @@ use crate::v1::extractors::scrape_request::ExtractRequest; /// to run in `public` mode. #[allow(clippy::unused_async)] pub async fn handle_without_key( - State(state): State>, + State(state): State<(Arc, SocketAddr)>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { tracing::debug!("http scrape request: {:#?}", &scrape_request); - handle(&state, &scrape_request, &client_ip_sources, None).await + handle(&state.0, &scrape_request, &client_ip_sources, &state.1, None).await } /// It handles the `scrape` request when the HTTP tracker is configured @@ -37,24 +38,25 @@ pub async fn handle_without_key( /// In this case, the authentication `key` parameter is required. #[allow(clippy::unused_async)] pub async fn handle_with_key( - State(state): State>, + State(state): State<(Arc, SocketAddr)>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, ) -> Response { tracing::debug!("http scrape request: {:#?}", &scrape_request); - handle(&state, &scrape_request, &client_ip_sources, Some(key)).await + handle(&state.0, &scrape_request, &client_ip_sources, &state.1, Some(key)).await } async fn handle( scrape_service: &Arc, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, + server_socket_addr: &SocketAddr, maybe_key: Option, ) -> Response { let scrape_data = match scrape_service - .handle_scrape(scrape_request, client_ip_sources, maybe_key) + .handle_scrape(scrape_request, client_ip_sources, server_socket_addr, maybe_key) .await { Ok(scrape_data) => scrape_data, @@ -165,6 +167,7 @@ mod tests { } mod with_tracker_in_private_mode { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; use bittorrent_http_tracker_core::services::scrape::ScrapeService; @@ -175,6 +178,8 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let (core_tracker_services, core_http_tracker_services) = initialize_private_tracker(); let scrape_request = sample_scrape_request(); @@ -188,7 +193,7 @@ mod tests { ); let scrape_data = scrape_service - .handle_scrape(&scrape_request, &sample_client_ip_sources(), maybe_key) + .handle_scrape(&scrape_request, &sample_client_ip_sources(), &server_socket_addr, maybe_key) .await .unwrap(); @@ -199,6 +204,8 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let (core_tracker_services, core_http_tracker_services) = initialize_private_tracker(); let scrape_request = sample_scrape_request(); @@ -213,7 +220,7 @@ mod tests { ); let scrape_data = scrape_service - .handle_scrape(&scrape_request, &sample_client_ip_sources(), maybe_key) + .handle_scrape(&scrape_request, &sample_client_ip_sources(), &server_socket_addr, maybe_key) .await .unwrap(); @@ -225,6 +232,8 @@ mod tests { mod with_tracker_in_listed_mode { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use bittorrent_http_tracker_core::services::scrape::ScrapeService; use torrust_tracker_primitives::core::ScrapeData; @@ -236,6 +245,8 @@ mod tests { let scrape_request = sample_scrape_request(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let scrape_service = ScrapeService::new( core_tracker_services.core_config.clone(), core_tracker_services.scrape_handler.clone(), @@ -244,7 +255,7 @@ mod tests { ); let scrape_data = scrape_service - .handle_scrape(&scrape_request, &sample_client_ip_sources(), None) + .handle_scrape(&scrape_request, &sample_client_ip_sources(), &server_socket_addr, None) .await .unwrap(); @@ -256,6 +267,8 @@ mod tests { mod with_tracker_on_reverse_proxy { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -272,6 +285,8 @@ mod tests { connection_info_ip: None, }; + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let scrape_service = ScrapeService::new( core_tracker_services.core_config.clone(), core_tracker_services.scrape_handler.clone(), @@ -280,7 +295,7 @@ mod tests { ); let response = scrape_service - .handle_scrape(&sample_scrape_request(), &client_ip_sources, None) + .handle_scrape(&sample_scrape_request(), &client_ip_sources, &server_socket_addr, None) .await .unwrap_err(); @@ -297,6 +312,8 @@ mod tests { mod with_tracker_not_on_reverse_proxy { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -313,6 +330,8 @@ mod tests { connection_info_ip: None, }; + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let scrape_service = ScrapeService::new( core_tracker_services.core_config.clone(), core_tracker_services.scrape_handler.clone(), @@ -321,7 +340,7 @@ mod tests { ); let response = scrape_service - .handle_scrape(&sample_scrape_request(), &client_ip_sources, None) + .handle_scrape(&sample_scrape_request(), &client_ip_sources, &server_socket_addr, None) .await .unwrap_err(); diff --git a/packages/axum-http-tracker-server/src/v1/routes.rs b/packages/axum-http-tracker-server/src/v1/routes.rs index 5f666e9d4..d5907887e 100644 --- a/packages/axum-http-tracker-server/src/v1/routes.rs +++ b/packages/axum-http-tracker-server/src/v1/routes.rs @@ -38,20 +38,20 @@ pub fn router(http_tracker_container: Arc, server_sock // Announce request .route( "/announce", - get(announce::handle_without_key).with_state(http_tracker_container.announce_service.clone()), + get(announce::handle_without_key).with_state((http_tracker_container.announce_service.clone(), server_socket_addr)), ) .route( "/announce/{key}", - get(announce::handle_with_key).with_state(http_tracker_container.announce_service.clone()), + get(announce::handle_with_key).with_state((http_tracker_container.announce_service.clone(), server_socket_addr)), ) // Scrape request .route( "/scrape", - get(scrape::handle_without_key).with_state(http_tracker_container.scrape_service.clone()), + get(scrape::handle_without_key).with_state((http_tracker_container.scrape_service.clone(), server_socket_addr)), ) .route( "/scrape/{key}", - get(scrape::handle_with_key).with_state(http_tracker_container.scrape_service.clone()), + get(scrape::handle_with_key).with_state((http_tracker_container.scrape_service.clone(), server_socket_addr)), ) // Add extension to get the client IP from the connection info .layer(SecureClientIpSource::ConnectInfo.into_extension()) diff --git a/packages/http-tracker-core/benches/helpers/sync.rs b/packages/http-tracker-core/benches/helpers/sync.rs index c19943b1d..9d41c2459 100644 --- a/packages/http-tracker-core/benches/helpers/sync.rs +++ b/packages/http-tracker-core/benches/helpers/sync.rs @@ -1,3 +1,4 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::time::{Duration, Instant}; use bittorrent_http_tracker_core::services::announce::AnnounceService; @@ -20,12 +21,16 @@ pub async fn return_announce_data_once(samples: u64) -> Duration { core_http_tracker_services.http_stats_event_sender.clone(), ); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let start = Instant::now(); + for _ in 0..samples { let _announce_data = announce_service - .handle_announce(&announce_request, &client_ip_sources, None) + .handle_announce(&announce_request, &client_ip_sources, &server_socket_addr, None) .await .unwrap(); } + start.elapsed() } diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 896387b28..b027ee0d9 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -7,7 +7,7 @@ //! //! It also sends an [`http_tracker_core::statistics::event::Event`] //! because events are specific for the HTTP tracker. -use std::net::IpAddr; +use std::net::{IpAddr, SocketAddr}; use std::panic::Location; use std::sync::Arc; @@ -68,6 +68,7 @@ impl AnnounceService { &self, announce_request: &Announce, client_ip_sources: &ClientIpSources, + server_socket_addr: &SocketAddr, maybe_key: Option, ) -> Result { self.authenticate(maybe_key).await?; @@ -85,7 +86,7 @@ impl AnnounceService { .announce(&announce_request.info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; - self.send_stats_event(remote_client_ip).await; + self.send_stats_event(remote_client_ip, *server_socket_addr).await; Ok(announce_data) } @@ -122,17 +123,27 @@ impl AnnounceService { } } - async fn send_stats_event(&self, peer_ip: IpAddr) { + async fn send_stats_event(&self, peer_ip: IpAddr, server_socket_addr: SocketAddr) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { match peer_ip { IpAddr::V4(_) => { http_stats_event_sender - .send_event(statistics::event::Event::Tcp4Announce) + .send_event(statistics::event::Event::Tcp4Announce { + connection: statistics::event::ConnectionContext { + client_ip_addr: peer_ip, + server_socket_addr, + }, + }) .await; } IpAddr::V6(_) => { http_stats_event_sender - .send_event(statistics::event::Event::Tcp6Announce) + .send_event(statistics::event::Event::Tcp6Announce { + connection: statistics::event::ConnectionContext { + client_ip_addr: peer_ip, + server_socket_addr, + }, + }) .await; } } @@ -338,6 +349,7 @@ mod tests { }; use crate::services::announce::AnnounceService; use crate::statistics; + use crate::statistics::event::ConnectionContext; #[tokio::test] async fn it_should_return_the_announce_data() { @@ -347,6 +359,8 @@ mod tests { let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let announce_service = AnnounceService::new( core_tracker_services.core_config.clone(), core_tracker_services.announce_handler.clone(), @@ -356,7 +370,7 @@ mod tests { ); let announce_data = announce_service - .handle_announce(&announce_request, &client_ip_sources, None) + .handle_announce(&announce_request, &client_ip_sources, &server_socket_addr, None) .await .unwrap(); @@ -375,16 +389,24 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_announce_event_when_the_peer_uses_ipv4() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp4Announce)) + .with(eq(statistics::event::Event::Tcp4Announce { + connection: ConnectionContext { + client_ip_addr: IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), + server_socket_addr, + }, + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services(); + core_http_tracker_services.http_stats_event_sender = http_stats_event_sender; let peer = sample_peer_using_ipv4(); @@ -400,7 +422,7 @@ mod tests { ); let _announce_data = announce_service - .handle_announce(&announce_request, &client_ip_sources, None) + .handle_announce(&announce_request, &client_ip_sources, &server_socket_addr, None) .await .unwrap(); } @@ -425,11 +447,18 @@ mod tests { { // Tracker changes the peer IP to the tracker external IP when the peer is using the loopback IP. + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + // Assert that the event sent is a TCP4 event let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp4Announce)) + .with(eq(statistics::event::Event::Tcp4Announce { + connection: ConnectionContext { + client_ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), + server_socket_addr, + }, + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let http_stats_event_sender: Arc>> = @@ -437,6 +466,7 @@ mod tests { let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services_with_config(&tracker_with_an_ipv6_external_ip()); + core_http_tracker_services.http_stats_event_sender = http_stats_event_sender; let peer = peer_with_the_ipv4_loopback_ip(); @@ -452,7 +482,7 @@ mod tests { ); let _announce_data = announce_service - .handle_announce(&announce_request, &client_ip_sources, None) + .handle_announce(&announce_request, &client_ip_sources, &server_socket_addr, None) .await .unwrap(); } @@ -460,10 +490,17 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_announce_event_when_the_peer_uses_ipv6_even_if_the_tracker_changes_the_peer_ip_to_ipv4() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp6Announce)) + .with(eq(statistics::event::Event::Tcp6Announce { + connection: ConnectionContext { + client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + server_socket_addr, + }, + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let http_stats_event_sender: Arc>> = @@ -484,8 +521,10 @@ mod tests { core_http_tracker_services.http_stats_event_sender.clone(), ); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let _announce_data = announce_service - .handle_announce(&announce_request, &client_ip_sources, None) + .handle_announce(&announce_request, &client_ip_sources, &server_socket_addr, None) .await .unwrap(); } diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 53eed0361..607ee2a3f 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -7,7 +7,7 @@ //! //! It also sends an [`http_tracker_core::statistics::event::Event`] //! because events are specific for the HTTP tracker. -use std::net::IpAddr; +use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; @@ -20,6 +20,7 @@ use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; use crate::statistics; +use crate::statistics::event::ConnectionContext; /// The HTTP tracker `scrape` service. /// @@ -70,6 +71,7 @@ impl ScrapeService { &self, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, + server_socket_addr: &SocketAddr, maybe_key: Option, ) -> Result { let scrape_data = if self.authentication_is_required() && !self.is_authenticated(maybe_key).await { @@ -80,7 +82,7 @@ impl ScrapeService { let remote_client_ip = self.resolve_remote_client_ip(client_ip_sources)?; - self.send_stats_event(&remote_client_ip).await; + self.send_stats_event(remote_client_ip, *server_socket_addr).await; Ok(scrape_data) } @@ -102,11 +104,21 @@ impl ScrapeService { peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources) } - async fn send_stats_event(&self, original_peer_ip: &IpAddr) { + async fn send_stats_event(&self, original_peer_ip: IpAddr, server_socket_addr: SocketAddr) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { let event = match original_peer_ip { - IpAddr::V4(_) => statistics::event::Event::Tcp4Scrape, - IpAddr::V6(_) => statistics::event::Event::Tcp6Scrape, + IpAddr::V4(_) => statistics::event::Event::Tcp4Scrape { + connection: ConnectionContext { + client_ip_addr: original_peer_ip, + server_socket_addr, + }, + }, + IpAddr::V6(_) => statistics::event::Event::Tcp6Scrape { + connection: ConnectionContext { + client_ip_addr: original_peer_ip, + server_socket_addr, + }, + }, }; http_stats_event_sender.send_event(event).await; } @@ -246,7 +258,7 @@ mod tests { mod with_real_data { use std::future; - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; @@ -262,6 +274,7 @@ mod tests { }; use crate::services::scrape::ScrapeService; use crate::statistics; + use crate::statistics::event::ConnectionContext; use crate::tests::sample_info_hash; #[tokio::test] @@ -295,6 +308,8 @@ mod tests { connection_info_ip: Some(original_peer_ip), }; + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let scrape_service = Arc::new(ScrapeService::new( core_config.clone(), container.scrape_handler.clone(), @@ -303,7 +318,7 @@ mod tests { )); let scrape_data = scrape_service - .handle_scrape(&scrape_request, &client_ip_sources, None) + .handle_scrape(&scrape_request, &client_ip_sources, &server_socket_addr, None) .await .unwrap(); @@ -327,7 +342,12 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp4Scrape)) + .with(eq(statistics::event::Event::Tcp4Scrape { + connection: ConnectionContext { + client_ip_addr: IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), + server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + }, + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let http_stats_event_sender: Arc>> = @@ -346,6 +366,8 @@ mod tests { connection_info_ip: Some(peer_ip), }; + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let scrape_service = Arc::new(ScrapeService::new( Arc::new(config.core), container.scrape_handler.clone(), @@ -354,19 +376,26 @@ mod tests { )); scrape_service - .handle_scrape(&scrape_request, &client_ip_sources, None) + .handle_scrape(&scrape_request, &client_ip_sources, &server_socket_addr, None) .await .unwrap(); } #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let config = configuration::ephemeral(); let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp6Scrape)) + .with(eq(statistics::event::Event::Tcp6Scrape { + connection: ConnectionContext { + client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + server_socket_addr, + }, + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let http_stats_event_sender: Arc>> = @@ -385,6 +414,8 @@ mod tests { connection_info_ip: Some(peer_ip), }; + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let scrape_service = Arc::new(ScrapeService::new( Arc::new(config.core), container.scrape_handler.clone(), @@ -393,7 +424,7 @@ mod tests { )); scrape_service - .handle_scrape(&scrape_request, &client_ip_sources, None) + .handle_scrape(&scrape_request, &client_ip_sources, &server_socket_addr, None) .await .unwrap(); } @@ -402,7 +433,7 @@ mod tests { mod with_zeroed_data { use std::future; - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; @@ -417,6 +448,7 @@ mod tests { }; use crate::services::scrape::ScrapeService; use crate::statistics; + use crate::statistics::event::ConnectionContext; use crate::tests::sample_info_hash; #[tokio::test] @@ -450,6 +482,8 @@ mod tests { connection_info_ip: Some(original_peer_ip), }; + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let scrape_service = Arc::new(ScrapeService::new( Arc::new(config.core), container.scrape_handler.clone(), @@ -458,7 +492,7 @@ mod tests { )); let scrape_data = scrape_service - .handle_scrape(&scrape_request, &client_ip_sources, None) + .handle_scrape(&scrape_request, &client_ip_sources, &server_socket_addr, None) .await .unwrap(); @@ -476,7 +510,12 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp4Scrape)) + .with(eq(statistics::event::Event::Tcp4Scrape { + connection: ConnectionContext { + client_ip_addr: IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), + server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + }, + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let http_stats_event_sender: Arc>> = @@ -493,6 +532,8 @@ mod tests { connection_info_ip: Some(peer_ip), }; + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let scrape_service = Arc::new(ScrapeService::new( Arc::new(config.core), container.scrape_handler.clone(), @@ -501,13 +542,15 @@ mod tests { )); scrape_service - .handle_scrape(&scrape_request, &client_ip_sources, None) + .handle_scrape(&scrape_request, &client_ip_sources, &server_socket_addr, None) .await .unwrap(); } #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let config = configuration::ephemeral(); let container = initialize_services_with_configuration(&config); @@ -515,7 +558,12 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp6Scrape)) + .with(eq(statistics::event::Event::Tcp6Scrape { + connection: ConnectionContext { + client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + server_socket_addr, + }, + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let http_stats_event_sender: Arc>> = @@ -532,6 +580,8 @@ mod tests { connection_info_ip: Some(peer_ip), }; + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let scrape_service = Arc::new(ScrapeService::new( Arc::new(config.core), container.scrape_handler.clone(), @@ -540,7 +590,7 @@ mod tests { )); scrape_service - .handle_scrape(&scrape_request, &client_ip_sources, None) + .handle_scrape(&scrape_request, &client_ip_sources, &server_socket_addr, None) .await .unwrap(); } diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index b0a0c186f..662c82ee2 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -1,23 +1,48 @@ +use std::net::IpAddr; + use crate::statistics::event::Event; use crate::statistics::repository::Repository; +/// # Panics +/// +/// This function panics if the client IP address is not the same as the IP +/// version of the event. pub async fn handle_event(event: Event, stats_repository: &Repository) { match event { // TCP4 - Event::Tcp4Announce => { - stats_repository.increase_tcp4_announces().await; - } - Event::Tcp4Scrape => { - stats_repository.increase_tcp4_scrapes().await; - } - + Event::Tcp4Announce { connection } => match connection.client_ip_addr { + IpAddr::V4(_) => { + stats_repository.increase_tcp4_announces().await; + } + IpAddr::V6(_) => { + panic!("A client IPv6 address was received in a TCP4 announce event"); + } + }, + Event::Tcp4Scrape { connection } => match connection.client_ip_addr { + IpAddr::V4(_) => { + stats_repository.increase_tcp4_scrapes().await; + } + IpAddr::V6(_) => { + panic!("A client IPv6 address was received in a TCP4 scrape event"); + } + }, // TCP6 - Event::Tcp6Announce => { - stats_repository.increase_tcp6_announces().await; - } - Event::Tcp6Scrape => { - stats_repository.increase_tcp6_scrapes().await; - } + Event::Tcp6Announce { connection } => match connection.client_ip_addr { + IpAddr::V4(_) => { + panic!("A client IPv4 address was received in a TCP6 announce event"); + } + IpAddr::V6(_) => { + stats_repository.increase_tcp6_announces().await; + } + }, + Event::Tcp6Scrape { connection } => match connection.client_ip_addr { + IpAddr::V4(_) => { + panic!("A client IPv4 address was received in a TCP6 scrape event"); + } + IpAddr::V6(_) => { + stats_repository.increase_tcp6_scrapes().await; + } + }, } tracing::debug!("stats: {:?}", stats_repository.get_stats().await); @@ -25,15 +50,26 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { #[cfg(test)] mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use crate::statistics::event::handler::handle_event; - use crate::statistics::event::Event; + use crate::statistics::event::{ConnectionContext, Event}; use crate::statistics::repository::Repository; #[tokio::test] async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { let stats_repository = Repository::new(); - handle_event(Event::Tcp4Announce, &stats_repository).await; + handle_event( + Event::Tcp4Announce { + connection: ConnectionContext { + client_ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), + server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + }, + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; @@ -44,7 +80,16 @@ mod tests { async fn should_increase_the_tcp4_scrapes_counter_when_it_receives_a_tcp4_scrape_event() { let stats_repository = Repository::new(); - handle_event(Event::Tcp4Scrape, &stats_repository).await; + handle_event( + Event::Tcp4Scrape { + connection: ConnectionContext { + client_ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), + server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + }, + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; @@ -55,7 +100,16 @@ mod tests { async fn should_increase_the_tcp6_announces_counter_when_it_receives_a_tcp6_announce_event() { let stats_repository = Repository::new(); - handle_event(Event::Tcp6Announce, &stats_repository).await; + handle_event( + Event::Tcp6Announce { + connection: ConnectionContext { + client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + }, + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; @@ -66,7 +120,16 @@ mod tests { async fn should_increase_the_tcp6_scrapes_counter_when_it_receives_a_tcp6_scrape_event() { let stats_repository = Repository::new(); - handle_event(Event::Tcp6Scrape, &stats_repository).await; + handle_event( + Event::Tcp6Scrape { + connection: ConnectionContext { + client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + }, + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; diff --git a/packages/http-tracker-core/src/statistics/event/mod.rs b/packages/http-tracker-core/src/statistics/event/mod.rs index e25148666..29dba0b6a 100644 --- a/packages/http-tracker-core/src/statistics/event/mod.rs +++ b/packages/http-tracker-core/src/statistics/event/mod.rs @@ -1,3 +1,5 @@ +use std::net::{IpAddr, SocketAddr}; + pub mod handler; pub mod listener; pub mod sender; @@ -5,17 +7,18 @@ pub mod sender; /// An statistics event. It is used to collect tracker metrics. /// /// - `Tcp` prefix means the event was triggered by the HTTP tracker -/// - `Udp` prefix means the event was triggered by the UDP tracker /// - `4` or `6` prefixes means the IP version used by the peer -/// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection` -/// -/// > NOTE: HTTP trackers do not use `connection` requests. +/// - Finally the event suffix is the type of request: `announce` or `scrape` #[derive(Debug, PartialEq, Eq)] pub enum Event { - // code-review: consider one single event for request type with data: Event::Announce { scheme: HTTPorUDP, ip_version: V4orV6 } - // Attributes are enums too. - Tcp4Announce, - Tcp4Scrape, - Tcp6Announce, - Tcp6Scrape, + Tcp4Announce { connection: ConnectionContext }, + Tcp4Scrape { connection: ConnectionContext }, + Tcp6Announce { connection: ConnectionContext }, + Tcp6Scrape { connection: ConnectionContext }, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct ConnectionContext { + pub client_ip_addr: IpAddr, + pub server_socket_addr: SocketAddr, } diff --git a/packages/http-tracker-core/src/statistics/keeper.rs b/packages/http-tracker-core/src/statistics/keeper.rs index ae5c3276e..bdbac8e77 100644 --- a/packages/http-tracker-core/src/statistics/keeper.rs +++ b/packages/http-tracker-core/src/statistics/keeper.rs @@ -51,7 +51,9 @@ impl Keeper { #[cfg(test)] mod tests { - use crate::statistics::event::Event; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use crate::statistics::event::{ConnectionContext, Event}; use crate::statistics::keeper::Keeper; use crate::statistics::metrics::Metrics; @@ -70,7 +72,14 @@ mod tests { let event_sender = stats_tracker.run_event_listener(); - let result = event_sender.send_event(Event::Tcp4Announce).await; + let result = event_sender + .send_event(Event::Tcp4Announce { + connection: ConnectionContext { + client_ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), + server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + }, + }) + .await; assert!(result.is_some()); } From 2de6c14bbc2967bcf45c1584e9c8b8f1786e98b5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Mar 2025 10:14:24 +0000 Subject: [PATCH 0880/1297] refactor: [#1373] merge HTTP stats events with different IP version --- .../src/services/announce.rs | 36 ++++++------------- .../http-tracker-core/src/services/scrape.rs | 23 +++++------- .../src/statistics/event/handler.rs | 32 ++++------------- .../src/statistics/event/mod.rs | 11 +++--- .../src/statistics/keeper.rs | 2 +- 5 files changed, 31 insertions(+), 73 deletions(-) diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index b027ee0d9..87250af30 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -125,28 +125,14 @@ impl AnnounceService { async fn send_stats_event(&self, peer_ip: IpAddr, server_socket_addr: SocketAddr) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { - match peer_ip { - IpAddr::V4(_) => { - http_stats_event_sender - .send_event(statistics::event::Event::Tcp4Announce { - connection: statistics::event::ConnectionContext { - client_ip_addr: peer_ip, - server_socket_addr, - }, - }) - .await; - } - IpAddr::V6(_) => { - http_stats_event_sender - .send_event(statistics::event::Event::Tcp6Announce { - connection: statistics::event::ConnectionContext { - client_ip_addr: peer_ip, - server_socket_addr, - }, - }) - .await; - } - } + http_stats_event_sender + .send_event(statistics::event::Event::TcpAnnounce { + connection: statistics::event::ConnectionContext { + client_ip_addr: peer_ip, + server_socket_addr, + }, + }) + .await; } } } @@ -394,7 +380,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp4Announce { + .with(eq(statistics::event::Event::TcpAnnounce { connection: ConnectionContext { client_ip_addr: IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), server_socket_addr, @@ -453,7 +439,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp4Announce { + .with(eq(statistics::event::Event::TcpAnnounce { connection: ConnectionContext { client_ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), server_socket_addr, @@ -495,7 +481,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp6Announce { + .with(eq(statistics::event::Event::TcpAnnounce { connection: ConnectionContext { client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), server_socket_addr, diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 607ee2a3f..31c2ce2c4 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -106,21 +106,14 @@ impl ScrapeService { async fn send_stats_event(&self, original_peer_ip: IpAddr, server_socket_addr: SocketAddr) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { - let event = match original_peer_ip { - IpAddr::V4(_) => statistics::event::Event::Tcp4Scrape { + http_stats_event_sender + .send_event(statistics::event::Event::TcpScrape { connection: ConnectionContext { client_ip_addr: original_peer_ip, server_socket_addr, }, - }, - IpAddr::V6(_) => statistics::event::Event::Tcp6Scrape { - connection: ConnectionContext { - client_ip_addr: original_peer_ip, - server_socket_addr, - }, - }, - }; - http_stats_event_sender.send_event(event).await; + }) + .await; } } } @@ -342,7 +335,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp4Scrape { + .with(eq(statistics::event::Event::TcpScrape { connection: ConnectionContext { client_ip_addr: IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), @@ -390,7 +383,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp6Scrape { + .with(eq(statistics::event::Event::TcpScrape { connection: ConnectionContext { client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), server_socket_addr, @@ -510,7 +503,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp4Scrape { + .with(eq(statistics::event::Event::TcpScrape { connection: ConnectionContext { client_ip_addr: IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), @@ -558,7 +551,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Tcp6Scrape { + .with(eq(statistics::event::Event::TcpScrape { connection: ConnectionContext { client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), server_socket_addr, diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index 662c82ee2..ea8cedc71 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -9,35 +9,17 @@ use crate::statistics::repository::Repository; /// version of the event. pub async fn handle_event(event: Event, stats_repository: &Repository) { match event { - // TCP4 - Event::Tcp4Announce { connection } => match connection.client_ip_addr { + Event::TcpAnnounce { connection } => match connection.client_ip_addr { IpAddr::V4(_) => { stats_repository.increase_tcp4_announces().await; } - IpAddr::V6(_) => { - panic!("A client IPv6 address was received in a TCP4 announce event"); - } - }, - Event::Tcp4Scrape { connection } => match connection.client_ip_addr { - IpAddr::V4(_) => { - stats_repository.increase_tcp4_scrapes().await; - } - IpAddr::V6(_) => { - panic!("A client IPv6 address was received in a TCP4 scrape event"); - } - }, - // TCP6 - Event::Tcp6Announce { connection } => match connection.client_ip_addr { - IpAddr::V4(_) => { - panic!("A client IPv4 address was received in a TCP6 announce event"); - } IpAddr::V6(_) => { stats_repository.increase_tcp6_announces().await; } }, - Event::Tcp6Scrape { connection } => match connection.client_ip_addr { + Event::TcpScrape { connection } => match connection.client_ip_addr { IpAddr::V4(_) => { - panic!("A client IPv4 address was received in a TCP6 scrape event"); + stats_repository.increase_tcp4_scrapes().await; } IpAddr::V6(_) => { stats_repository.increase_tcp6_scrapes().await; @@ -61,7 +43,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Tcp4Announce { + Event::TcpAnnounce { connection: ConnectionContext { client_ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), @@ -81,7 +63,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Tcp4Scrape { + Event::TcpScrape { connection: ConnectionContext { client_ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), @@ -101,7 +83,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Tcp6Announce { + Event::TcpAnnounce { connection: ConnectionContext { client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), @@ -121,7 +103,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Tcp6Scrape { + Event::TcpScrape { connection: ConnectionContext { client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), diff --git a/packages/http-tracker-core/src/statistics/event/mod.rs b/packages/http-tracker-core/src/statistics/event/mod.rs index 29dba0b6a..c27ce7c6d 100644 --- a/packages/http-tracker-core/src/statistics/event/mod.rs +++ b/packages/http-tracker-core/src/statistics/event/mod.rs @@ -6,15 +6,12 @@ pub mod sender; /// An statistics event. It is used to collect tracker metrics. /// -/// - `Tcp` prefix means the event was triggered by the HTTP tracker -/// - `4` or `6` prefixes means the IP version used by the peer -/// - Finally the event suffix is the type of request: `announce` or `scrape` +/// - `Tcp` prefix means the event was triggered by the HTTP tracker. +/// - The event suffix is the type of request: `announce` or `scrape`. #[derive(Debug, PartialEq, Eq)] pub enum Event { - Tcp4Announce { connection: ConnectionContext }, - Tcp4Scrape { connection: ConnectionContext }, - Tcp6Announce { connection: ConnectionContext }, - Tcp6Scrape { connection: ConnectionContext }, + TcpAnnounce { connection: ConnectionContext }, + TcpScrape { connection: ConnectionContext }, } #[derive(Debug, PartialEq, Eq)] diff --git a/packages/http-tracker-core/src/statistics/keeper.rs b/packages/http-tracker-core/src/statistics/keeper.rs index bdbac8e77..6f84e27b1 100644 --- a/packages/http-tracker-core/src/statistics/keeper.rs +++ b/packages/http-tracker-core/src/statistics/keeper.rs @@ -73,7 +73,7 @@ mod tests { let event_sender = stats_tracker.run_event_listener(); let result = event_sender - .send_event(Event::Tcp4Announce { + .send_event(Event::TcpAnnounce { connection: ConnectionContext { client_ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), From b8a3d44671cbff5486dc57ac3915ee865a1756d4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Mar 2025 10:34:27 +0000 Subject: [PATCH 0881/1297] refactor: [#1373] capture socket address from connection info in HTTP tracker Instead of only the IP. The port will be abailable in evetns so we can build metrics also using the client's port. --- .../src/v1/extractors/client_ip_sources.rs | 4 +-- .../src/v1/handlers/announce.rs | 6 ++-- .../src/v1/handlers/scrape.rs | 8 +++--- .../src/v1/services/peer_ip_resolver.rs | 28 ++++++++++--------- .../http-tracker-core/benches/helpers/util.rs | 2 +- .../src/services/announce.rs | 2 +- .../http-tracker-core/src/services/scrape.rs | 12 ++++---- .../src/statistics/event/mod.rs | 3 -- 8 files changed, 32 insertions(+), 33 deletions(-) diff --git a/packages/axum-http-tracker-server/src/v1/extractors/client_ip_sources.rs b/packages/axum-http-tracker-server/src/v1/extractors/client_ip_sources.rs index 8c7a2bf40..ed568e0b9 100644 --- a/packages/axum-http-tracker-server/src/v1/extractors/client_ip_sources.rs +++ b/packages/axum-http-tracker-server/src/v1/extractors/client_ip_sources.rs @@ -63,13 +63,13 @@ where }; let connection_info_ip = match ConnectInfo::::from_request_parts(parts, state).await { - Ok(connection_info_socket_addr) => Some(connection_info_socket_addr.0.ip()), + Ok(connection_info_socket_addr) => Some(connection_info_socket_addr.0), Err(_) => None, }; Ok(Extract(ClientIpSources { right_most_x_forwarded_for, - connection_info_ip, + connection_info_socket_address: connection_info_ip, })) } } diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 63ab96fe5..53fd38997 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -194,7 +194,7 @@ mod tests { fn sample_client_ip_sources() -> ClientIpSources { ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: None, + connection_info_socket_address: None, } } @@ -335,7 +335,7 @@ mod tests { let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: None, + connection_info_socket_address: None, }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); @@ -378,7 +378,7 @@ mod tests { let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: None, + connection_info_socket_address: None, }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index ca90f74c6..1ba89eaaf 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -79,7 +79,7 @@ fn build_response(scrape_data: ScrapeData) -> Response { #[cfg(test)] mod tests { - use std::net::IpAddr; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; use std::sync::Arc; @@ -155,7 +155,7 @@ mod tests { fn sample_client_ip_sources() -> ClientIpSources { ClientIpSources { right_most_x_forwarded_for: Some(IpAddr::from_str("203.0.113.195").unwrap()), - connection_info_ip: Some(IpAddr::from_str("203.0.113.196").unwrap()), + connection_info_socket_address: Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 8080)), } } @@ -282,7 +282,7 @@ mod tests { let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: None, + connection_info_socket_address: None, }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); @@ -327,7 +327,7 @@ mod tests { let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: None, + connection_info_socket_address: None, }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); diff --git a/packages/http-protocol/src/v1/services/peer_ip_resolver.rs b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs index bea93f1ba..b375694b9 100644 --- a/packages/http-protocol/src/v1/services/peer_ip_resolver.rs +++ b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs @@ -20,7 +20,7 @@ //! ``` //! //! Depending on the tracker configuration. -use std::net::IpAddr; +use std::net::{IpAddr, SocketAddr}; use std::panic::Location; use serde::{Deserialize, Serialize}; @@ -31,8 +31,9 @@ use thiserror::Error; pub struct ClientIpSources { /// The right most IP from the `X-Forwarded-For` HTTP header. pub right_most_x_forwarded_for: Option, - /// The IP from the connection info. - pub connection_info_ip: Option, + + /// The client's socket address from the connection info. + pub connection_info_socket_address: Option, } /// The error that can occur when resolving the peer IP. @@ -45,6 +46,7 @@ pub enum PeerIpResolutionError { "missing or invalid the right most X-Forwarded-For IP (mandatory on reverse proxy tracker configuration) in {location}" )] MissingRightMostXForwardedForIp { location: &'static Location<'static> }, + /// The peer IP cannot be obtained because the tracker is not configured as /// a reverse proxy but the connection info was not provided to the Axum /// framework via a route extension. @@ -71,7 +73,7 @@ pub enum PeerIpResolutionError { /// on_reverse_proxy, /// &ClientIpSources { /// right_most_x_forwarded_for: Some(IpAddr::from_str("203.0.113.195").unwrap()), -/// connection_info_ip: None, +/// connection_info_socket_address: None, /// }, /// ) /// .unwrap(); @@ -82,7 +84,7 @@ pub enum PeerIpResolutionError { /// With the tracker non running on reverse proxy mode: /// /// ```rust -/// use std::net::IpAddr; +/// use std::net::{IpAddr,Ipv4Addr,SocketAddr}; /// use std::str::FromStr; /// /// use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; @@ -93,7 +95,7 @@ pub enum PeerIpResolutionError { /// on_reverse_proxy, /// &ClientIpSources { /// right_most_x_forwarded_for: None, -/// connection_info_ip: Some(IpAddr::from_str("203.0.113.195").unwrap()), +/// connection_info_socket_address: Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080)) /// }, /// ) /// .unwrap(); @@ -114,8 +116,8 @@ pub fn invoke(on_reverse_proxy: bool, client_ip_sources: &ClientIpSources) -> Re } fn resolve_peer_ip_without_reverse_proxy(remote_client_ip: &ClientIpSources) -> Result { - if let Some(ip) = remote_client_ip.connection_info_ip { - Ok(ip) + if let Some(socket_addr) = remote_client_ip.connection_info_socket_address { + Ok(socket_addr.ip()) } else { Err(PeerIpResolutionError::MissingClientIp { location: Location::caller(), @@ -138,7 +140,7 @@ mod tests { use super::invoke; mod working_without_reverse_proxy { - use std::net::IpAddr; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; use super::invoke; @@ -152,7 +154,7 @@ mod tests { on_reverse_proxy, &ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: Some(IpAddr::from_str("203.0.113.195").unwrap()), + connection_info_socket_address: Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080)), }, ) .unwrap(); @@ -168,7 +170,7 @@ mod tests { on_reverse_proxy, &ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: None, + connection_info_socket_address: None, }, ) .unwrap_err(); @@ -191,7 +193,7 @@ mod tests { on_reverse_proxy, &ClientIpSources { right_most_x_forwarded_for: Some(IpAddr::from_str("203.0.113.195").unwrap()), - connection_info_ip: None, + connection_info_socket_address: None, }, ) .unwrap(); @@ -207,7 +209,7 @@ mod tests { on_reverse_proxy, &ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: None, + connection_info_socket_address: None, }, ) .unwrap_err(); diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index f15e9db8f..169c4a56a 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -93,7 +93,7 @@ pub fn sample_announce_request_for_peer(peer: Peer) -> (Announce, ClientIpSource let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: Some(peer.peer_addr.ip()), + connection_info_socket_address: Some(SocketAddr::new(peer.peer_addr.ip(), 8080)), }; (announce_request, client_ip_sources) diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 87250af30..7eb73ff53 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -296,7 +296,7 @@ mod tests { let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: Some(peer.peer_addr.ip()), + connection_info_socket_address: Some(SocketAddr::new(peer.peer_addr.ip(), 8080)), }; (announce_request, client_ip_sources) diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 31c2ce2c4..93d2688e5 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -298,7 +298,7 @@ mod tests { let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: Some(original_peer_ip), + connection_info_socket_address: Some(SocketAddr::new(original_peer_ip, 8080)), }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); @@ -356,7 +356,7 @@ mod tests { let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: Some(peer_ip), + connection_info_socket_address: Some(SocketAddr::new(peer_ip, 8080)), }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); @@ -404,7 +404,7 @@ mod tests { let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: Some(peer_ip), + connection_info_socket_address: Some(SocketAddr::new(peer_ip, 8080)), }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); @@ -472,7 +472,7 @@ mod tests { let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: Some(original_peer_ip), + connection_info_socket_address: Some(SocketAddr::new(original_peer_ip, 8080)), }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); @@ -522,7 +522,7 @@ mod tests { let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: Some(peer_ip), + connection_info_socket_address: Some(SocketAddr::new(peer_ip, 8080)), }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); @@ -570,7 +570,7 @@ mod tests { let client_ip_sources = ClientIpSources { right_most_x_forwarded_for: None, - connection_info_ip: Some(peer_ip), + connection_info_socket_address: Some(SocketAddr::new(peer_ip, 8080)), }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); diff --git a/packages/http-tracker-core/src/statistics/event/mod.rs b/packages/http-tracker-core/src/statistics/event/mod.rs index c27ce7c6d..a6e54ce83 100644 --- a/packages/http-tracker-core/src/statistics/event/mod.rs +++ b/packages/http-tracker-core/src/statistics/event/mod.rs @@ -5,9 +5,6 @@ pub mod listener; pub mod sender; /// An statistics event. It is used to collect tracker metrics. -/// -/// - `Tcp` prefix means the event was triggered by the HTTP tracker. -/// - The event suffix is the type of request: `announce` or `scrape`. #[derive(Debug, PartialEq, Eq)] pub enum Event { TcpAnnounce { connection: ConnectionContext }, From 3969c67a67fc2f2bea7a3ad4a52ec60cf8baf898 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Mar 2025 11:36:06 +0000 Subject: [PATCH 0882/1297] refactor: [1373] include client's port in stats events when provided --- .../src/services/announce.rs | 48 ++++++++------ .../http-tracker-core/src/services/scrape.rs | 66 ++++++++++++------- .../src/statistics/event/handler.rs | 40 ++++++----- .../src/statistics/event/mod.rs | 37 ++++++++++- .../src/statistics/keeper.rs | 9 +-- 5 files changed, 132 insertions(+), 68 deletions(-) diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 7eb73ff53..6b8b700c9 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -75,7 +75,7 @@ impl AnnounceService { self.authorize(announce_request.info_hash).await?; - let remote_client_ip = self.resolve_remote_client_ip(client_ip_sources)?; + let (remote_client_ip, opt_remote_client_port) = self.resolve_remote_client_address(client_ip_sources)?; let mut peer = peer_from_request(announce_request, &remote_client_ip); @@ -86,7 +86,8 @@ impl AnnounceService { .announce(&announce_request.info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; - self.send_stats_event(remote_client_ip, *server_socket_addr).await; + self.send_stats_event(remote_client_ip, opt_remote_client_port, *server_socket_addr) + .await; Ok(announce_data) } @@ -108,11 +109,24 @@ impl AnnounceService { } /// Resolves the client's real IP address considering proxy headers - fn resolve_remote_client_ip(&self, client_ip_sources: &ClientIpSources) -> Result { - match peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources) { + fn resolve_remote_client_address( + &self, + client_ip_sources: &ClientIpSources, + ) -> Result<(IpAddr, Option), PeerIpResolutionError> { + let ip = match peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources) { Ok(peer_ip) => Ok(peer_ip), Err(error) => Err(error), - } + }?; + + let port = if client_ip_sources.connection_info_socket_address.is_some() { + client_ip_sources + .connection_info_socket_address + .map(|socket_addr| socket_addr.port()) + } else { + None + }; + + Ok((ip, port)) } /// Determines how many peers the client wants in the response @@ -123,14 +137,11 @@ impl AnnounceService { } } - async fn send_stats_event(&self, peer_ip: IpAddr, server_socket_addr: SocketAddr) { + async fn send_stats_event(&self, peer_ip: IpAddr, opt_peer_ip_port: Option, server_socket_addr: SocketAddr) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { http_stats_event_sender .send_event(statistics::event::Event::TcpAnnounce { - connection: statistics::event::ConnectionContext { - client_ip_addr: peer_ip, - server_socket_addr, - }, + connection: statistics::event::ConnectionContext::new(peer_ip, opt_peer_ip_port, server_socket_addr), }) .await; } @@ -381,10 +392,7 @@ mod tests { http_stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::TcpAnnounce { - connection: ConnectionContext { - client_ip_addr: IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), - server_socket_addr, - }, + connection: ConnectionContext::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), Some(8080), server_socket_addr), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); @@ -440,10 +448,7 @@ mod tests { http_stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::TcpAnnounce { - connection: ConnectionContext { - client_ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), - server_socket_addr, - }, + connection: ConnectionContext::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), Some(8080), server_socket_addr), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); @@ -482,10 +487,11 @@ mod tests { http_stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::TcpAnnounce { - connection: ConnectionContext { - client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + connection: ConnectionContext::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + Some(8080), server_socket_addr, - }, + ), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 93d2688e5..ed927efc3 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -80,9 +80,10 @@ impl ScrapeService { self.scrape_handler.scrape(&scrape_request.info_hashes).await? }; - let remote_client_ip = self.resolve_remote_client_ip(client_ip_sources)?; + let (remote_client_ip, opt_client_port) = self.resolve_remote_client_ip(client_ip_sources)?; - self.send_stats_event(remote_client_ip, *server_socket_addr).await; + self.send_stats_event(remote_client_ip, opt_client_port, *server_socket_addr) + .await; Ok(scrape_data) } @@ -100,18 +101,33 @@ impl ScrapeService { } /// Resolves the client's real IP address considering proxy headers. - fn resolve_remote_client_ip(&self, client_ip_sources: &ClientIpSources) -> Result { - peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources) + fn resolve_remote_client_ip( + &self, + client_ip_sources: &ClientIpSources, + ) -> Result<(IpAddr, Option), PeerIpResolutionError> { + let ip = peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources)?; + + let port = if client_ip_sources.connection_info_socket_address.is_some() { + client_ip_sources + .connection_info_socket_address + .map(|socket_addr| socket_addr.port()) + } else { + None + }; + + Ok((ip, port)) } - async fn send_stats_event(&self, original_peer_ip: IpAddr, server_socket_addr: SocketAddr) { + async fn send_stats_event( + &self, + original_peer_ip: IpAddr, + opt_original_peer_port: Option, + server_socket_addr: SocketAddr, + ) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { http_stats_event_sender .send_event(statistics::event::Event::TcpScrape { - connection: ConnectionContext { - client_ip_addr: original_peer_ip, - server_socket_addr, - }, + connection: ConnectionContext::new(original_peer_ip, opt_original_peer_port, server_socket_addr), }) .await; } @@ -336,10 +352,11 @@ mod tests { http_stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::TcpScrape { - connection: ConnectionContext { - client_ip_addr: IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), - server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), - }, + connection: ConnectionContext::new( + IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), + Some(8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); @@ -384,10 +401,11 @@ mod tests { http_stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::TcpScrape { - connection: ConnectionContext { - client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + connection: ConnectionContext::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + Some(8080), server_socket_addr, - }, + ), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); @@ -504,10 +522,11 @@ mod tests { http_stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::TcpScrape { - connection: ConnectionContext { - client_ip_addr: IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), - server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), - }, + connection: ConnectionContext::new( + IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), + Some(8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); @@ -552,10 +571,11 @@ mod tests { http_stats_event_sender_mock .expect_send_event() .with(eq(statistics::event::Event::TcpScrape { - connection: ConnectionContext { - client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + connection: ConnectionContext::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + Some(8080), server_socket_addr, - }, + ), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index ea8cedc71..b8806b9d2 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -9,7 +9,7 @@ use crate::statistics::repository::Repository; /// version of the event. pub async fn handle_event(event: Event, stats_repository: &Repository) { match event { - Event::TcpAnnounce { connection } => match connection.client_ip_addr { + Event::TcpAnnounce { connection } => match connection.client_ip_addr() { IpAddr::V4(_) => { stats_repository.increase_tcp4_announces().await; } @@ -17,7 +17,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { stats_repository.increase_tcp6_announces().await; } }, - Event::TcpScrape { connection } => match connection.client_ip_addr { + Event::TcpScrape { connection } => match connection.client_ip_addr() { IpAddr::V4(_) => { stats_repository.increase_tcp4_scrapes().await; } @@ -44,10 +44,11 @@ mod tests { handle_event( Event::TcpAnnounce { - connection: ConnectionContext { - client_ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), - server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), - }, + connection: ConnectionContext::new( + IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), + Some(8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ), }, &stats_repository, ) @@ -64,10 +65,11 @@ mod tests { handle_event( Event::TcpScrape { - connection: ConnectionContext { - client_ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), - server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), - }, + connection: ConnectionContext::new( + IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), + Some(8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ), }, &stats_repository, ) @@ -84,10 +86,11 @@ mod tests { handle_event( Event::TcpAnnounce { - connection: ConnectionContext { - client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), - }, + connection: ConnectionContext::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + Some(8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ), }, &stats_repository, ) @@ -104,10 +107,11 @@ mod tests { handle_event( Event::TcpScrape { - connection: ConnectionContext { - client_ip_addr: IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), - }, + connection: ConnectionContext::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + Some(8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ), }, &stats_repository, ) diff --git a/packages/http-tracker-core/src/statistics/event/mod.rs b/packages/http-tracker-core/src/statistics/event/mod.rs index a6e54ce83..7520e1a97 100644 --- a/packages/http-tracker-core/src/statistics/event/mod.rs +++ b/packages/http-tracker-core/src/statistics/event/mod.rs @@ -13,6 +13,39 @@ pub enum Event { #[derive(Debug, PartialEq, Eq)] pub struct ConnectionContext { - pub client_ip_addr: IpAddr, - pub server_socket_addr: SocketAddr, + client: ClientConnectionContext, + server: ServerConnectionContext, +} + +impl ConnectionContext { + #[must_use] + pub fn new(client_ip_addr: IpAddr, opt_client_port: Option, server_socket_addr: SocketAddr) -> Self { + Self { + client: ClientConnectionContext { + ip_addr: client_ip_addr, + port: opt_client_port, + }, + server: ServerConnectionContext { + socket_addr: server_socket_addr, + }, + } + } + + #[must_use] + pub fn client_ip_addr(&self) -> IpAddr { + self.client.ip_addr + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct ClientConnectionContext { + ip_addr: IpAddr, + + /// It's provided if you use the `torrust-axum-http-tracker-server` crate. + port: Option, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct ServerConnectionContext { + socket_addr: SocketAddr, } diff --git a/packages/http-tracker-core/src/statistics/keeper.rs b/packages/http-tracker-core/src/statistics/keeper.rs index 6f84e27b1..783309eff 100644 --- a/packages/http-tracker-core/src/statistics/keeper.rs +++ b/packages/http-tracker-core/src/statistics/keeper.rs @@ -74,10 +74,11 @@ mod tests { let result = event_sender .send_event(Event::TcpAnnounce { - connection: ConnectionContext { - client_ip_addr: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), - server_socket_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), - }, + connection: ConnectionContext::new( + IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), + Some(8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ), }) .await; From 1f30f8ef3d734051bc5f79d76200f0a5c786a737 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Mar 2025 12:00:03 +0000 Subject: [PATCH 0883/1297] ci: update git hooks scripts To also run doctests. --- contrib/dev-tools/git/hooks/pre-commit.sh | 1 + contrib/dev-tools/git/hooks/pre-push.sh | 1 + 2 files changed, 2 insertions(+) diff --git a/contrib/dev-tools/git/hooks/pre-commit.sh b/contrib/dev-tools/git/hooks/pre-commit.sh index 37b80bb8a..c1b183fde 100755 --- a/contrib/dev-tools/git/hooks/pre-commit.sh +++ b/contrib/dev-tools/git/hooks/pre-commit.sh @@ -6,4 +6,5 @@ cargo +nightly fmt --check && cargo +nightly machete && cargo +stable build && CARGO_INCREMENTAL=0 cargo +stable clippy --no-deps --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic && + cargo +stable test --doc --workspace && cargo +stable test --tests --benches --examples --workspace --all-targets --all-features diff --git a/contrib/dev-tools/git/hooks/pre-push.sh b/contrib/dev-tools/git/hooks/pre-push.sh index c1a724156..593068cee 100755 --- a/contrib/dev-tools/git/hooks/pre-push.sh +++ b/contrib/dev-tools/git/hooks/pre-push.sh @@ -6,5 +6,6 @@ cargo +nightly fmt --check && cargo +nightly machete && cargo +stable build && CARGO_INCREMENTAL=0 cargo +stable clippy --no-deps --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic && + cargo +stable test --doc --workspace && cargo +stable test --tests --benches --examples --workspace --all-targets --all-features && cargo +stable run --bin e2e_tests_runner -- --config-toml-path "./share/default/config/tracker.e2e.container.sqlite3.toml" From 2be682e1779088432126e7a2c6ee39dd4f4b7094 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Mar 2025 17:07:55 +0000 Subject: [PATCH 0884/1297] refactor: [#1380] refactor: [#1371] add connection context to UDP core events --- .../udp-tracker-core/benches/helpers/sync.rs | 6 +- .../udp-tracker-core/src/services/announce.rs | 22 ++- .../udp-tracker-core/src/services/connect.rs | 60 ++++++-- .../udp-tracker-core/src/services/scrape.rs | 20 ++- .../src/statistics/event/handler.rs | 139 ++++++++++++++---- .../src/statistics/event/mod.rs | 35 +++-- .../udp-tracker-core/src/statistics/keeper.rs | 13 +- .../src/handlers/announce.rs | 135 ++++++++++------- .../src/handlers/connect.rs | 38 ++++- .../udp-tracker-server/src/handlers/mod.rs | 22 ++- .../udp-tracker-server/src/handlers/scrape.rs | 70 +++++---- 11 files changed, 401 insertions(+), 159 deletions(-) diff --git a/packages/udp-tracker-core/benches/helpers/sync.rs b/packages/udp-tracker-core/benches/helpers/sync.rs index b7d8e848d..ca459c640 100644 --- a/packages/udp-tracker-core/benches/helpers/sync.rs +++ b/packages/udp-tracker-core/benches/helpers/sync.rs @@ -1,3 +1,4 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -8,13 +9,16 @@ use crate::helpers::utils::{sample_ipv4_remote_addr, sample_issue_time}; #[allow(clippy::unused_async)] pub async fn connect_once(samples: u64) -> Duration { + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); let start = Instant::now(); for _ in 0..samples { - let _response = connect_service.handle_connect(sample_ipv4_remote_addr(), sample_issue_time()); + let _response = connect_service.handle_connect(client_socket_addr, server_socket_addr, sample_issue_time()); } start.elapsed() diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index 698f5fba6..22bc05a9e 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -21,6 +21,7 @@ use torrust_tracker_primitives::core::AnnounceData; use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; use crate::statistics; +use crate::statistics::event::ConnectionContext; /// The `AnnounceService` is responsible for handling the `announce` requests. /// @@ -57,17 +58,18 @@ impl AnnounceService { /// whitelist. pub async fn handle_announce( &self, - remote_addr: SocketAddr, + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, request: &AnnounceRequest, cookie_valid_range: Range, ) -> Result { - Self::authenticate(remote_addr, request, cookie_valid_range)?; + Self::authenticate(client_socket_addr, request, cookie_valid_range)?; let info_hash = request.info_hash.into(); self.authorize(&info_hash).await?; - let remote_client_ip = remote_addr.ip(); + let remote_client_ip = client_socket_addr.ip(); let mut peer = peer_builder::from_request(request, &remote_client_ip); @@ -78,7 +80,7 @@ impl AnnounceService { .announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; - self.send_stats_event(remote_client_ip).await; + self.send_stats_event(client_socket_addr, server_socket_addr).await; Ok(announce_data) } @@ -99,11 +101,15 @@ impl AnnounceService { self.whitelist_authorization.authorize(info_hash).await } - async fn send_stats_event(&self, peer_ip: IpAddr) { + async fn send_stats_event(&self, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) { if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { - let event = match peer_ip { - IpAddr::V4(_) => statistics::event::Event::Udp4Announce, - IpAddr::V6(_) => statistics::event::Event::Udp6Announce, + let event = match client_socket_addr.ip() { + IpAddr::V4(_) => statistics::event::Event::Udp4Announce { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }, + IpAddr::V6(_) => statistics::event::Event::Udp6Announce { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }, }; udp_stats_event_sender.send_event(event).await; diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index 14a3068e4..5309a79d3 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -8,6 +8,7 @@ use aquatic_udp_protocol::ConnectionId; use crate::connection_cookie::{gen_remote_fingerprint, make}; use crate::statistics; +use crate::statistics::event::ConnectionContext; /// The `ConnectService` is responsible for handling the `connect` requests. /// @@ -30,16 +31,30 @@ impl ConnectService { /// # Panics /// /// It will panic if there was an error making the connection cookie. - pub async fn handle_connect(&self, remote_addr: SocketAddr, cookie_issue_time: f64) -> ConnectionId { - let connection_id = make(gen_remote_fingerprint(&remote_addr), cookie_issue_time).expect("it should be a normal value"); + pub async fn handle_connect( + &self, + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, + cookie_issue_time: f64, + ) -> ConnectionId { + let connection_id = + make(gen_remote_fingerprint(&client_socket_addr), cookie_issue_time).expect("it should be a normal value"); if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { - match remote_addr { + match client_socket_addr { SocketAddr::V4(_) => { - udp_stats_event_sender.send_event(statistics::event::Event::Udp4Connect).await; + udp_stats_event_sender + .send_event(statistics::event::Event::Udp4Connect { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }) + .await; } SocketAddr::V6(_) => { - udp_stats_event_sender.send_event(statistics::event::Event::Udp6Connect).await; + udp_stats_event_sender + .send_event(statistics::event::Event::Udp6Connect { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }) + .await; } } } @@ -54,6 +69,7 @@ mod tests { mod connect_request { use std::future; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use mockall::predicate::eq; @@ -65,16 +81,19 @@ mod tests { sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpCoreStatsEventSender, }; use crate::statistics; + use crate::statistics::event::ConnectionContext; #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); let response = connect_service - .handle_connect(sample_ipv4_remote_addr(), sample_issue_time()) + .handle_connect(sample_ipv4_remote_addr(), server_socket_addr, sample_issue_time()) .await; assert_eq!( @@ -85,13 +104,15 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); let response = connect_service - .handle_connect(sample_ipv4_remote_addr(), sample_issue_time()) + .handle_connect(sample_ipv4_remote_addr(), server_socket_addr, sample_issue_time()) .await; assert_eq!( @@ -102,13 +123,16 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { + let client_socket_addr = sample_ipv6_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); let response = connect_service - .handle_connect(sample_ipv6_remote_addr(), sample_issue_time()) + .handle_connect(client_socket_addr, server_socket_addr, sample_issue_time()) .await; assert_eq!( @@ -119,30 +143,38 @@ mod tests { #[tokio::test] async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { + let client_socket_addr = sample_ipv4_socket_address(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Udp4Connect)) + .with(eq(statistics::event::Event::Udp4Connect { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let opt_udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); - let client_socket_address = sample_ipv4_socket_address(); - let connect_service = Arc::new(ConnectService::new(opt_udp_stats_event_sender)); connect_service - .handle_connect(client_socket_address, sample_issue_time()) + .handle_connect(client_socket_addr, server_socket_addr, sample_issue_time()) .await; } #[tokio::test] async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { + let client_socket_addr = sample_ipv6_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Udp6Connect)) + .with(eq(statistics::event::Event::Udp6Connect { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let opt_udp_stats_event_sender: Arc>> = @@ -151,7 +183,7 @@ mod tests { let connect_service = Arc::new(ConnectService::new(opt_udp_stats_event_sender)); connect_service - .handle_connect(sample_ipv6_remote_addr(), sample_issue_time()) + .handle_connect(client_socket_addr, server_socket_addr, sample_issue_time()) .await; } } diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index 61301cd43..0f1ab14d8 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -19,6 +19,7 @@ use torrust_tracker_primitives::core::ScrapeData; use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; use crate::statistics; +use crate::statistics::event::ConnectionContext; /// The `ScrapeService` is responsible for handling the `scrape` requests. /// @@ -49,18 +50,19 @@ impl ScrapeService { /// It will return an error if the tracker core scrape handler returns an error. pub async fn handle_scrape( &self, - remote_client_addr: SocketAddr, + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, request: &ScrapeRequest, cookie_valid_range: Range, ) -> Result { - Self::authenticate(remote_client_addr, request, cookie_valid_range)?; + Self::authenticate(client_socket_addr, request, cookie_valid_range)?; let scrape_data = self .scrape_handler .scrape(&Self::convert_from_aquatic(&request.info_hashes)) .await?; - self.send_stats_event(remote_client_addr).await; + self.send_stats_event(client_socket_addr, server_socket_addr).await; Ok(scrape_data) } @@ -81,11 +83,15 @@ impl ScrapeService { aquatic_infohashes.iter().map(|&x| x.into()).collect() } - async fn send_stats_event(&self, remote_addr: SocketAddr) { + async fn send_stats_event(&self, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) { if let Some(udp_stats_event_sender) = self.opt_udp_stats_event_sender.as_deref() { - let event = match remote_addr { - SocketAddr::V4(_) => statistics::event::Event::Udp4Scrape, - SocketAddr::V6(_) => statistics::event::Event::Udp6Scrape, + let event = match client_socket_addr { + SocketAddr::V4(_) => statistics::event::Event::Udp4Scrape { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }, + SocketAddr::V6(_) => statistics::event::Event::Udp6Scrape { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }, }; udp_stats_event_sender.send_event(event).await; } diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index 096059b91..1f8a64a88 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -1,29 +1,62 @@ use crate::statistics::event::Event; use crate::statistics::repository::Repository; +/// # Panics +/// +/// This function panics if the IP version does not match the event type. pub async fn handle_event(event: Event, stats_repository: &Repository) { match event { // UDP4 - Event::Udp4Connect => { - stats_repository.increase_udp4_connections().await; - } - Event::Udp4Announce => { - stats_repository.increase_udp4_announces().await; - } - Event::Udp4Scrape => { - stats_repository.increase_udp4_scrapes().await; - } + Event::Udp4Connect { context } => match context.client_socket_addr.ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_connections().await; + } + std::net::IpAddr::V6(_) => { + panic!("IP Version 6 does not match the event type for connect"); + } + }, + Event::Udp4Announce { context } => match context.client_socket_addr.ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_announces().await; + } + std::net::IpAddr::V6(_) => { + panic!("IP Version 6 does not match the event type for announce"); + } + }, + Event::Udp4Scrape { context } => match context.client_socket_addr.ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_scrapes().await; + } + std::net::IpAddr::V6(_) => { + panic!("IP Version 6 does not match the event type for scrape"); + } + }, // UDP6 - Event::Udp6Connect => { - stats_repository.increase_udp6_connections().await; - } - Event::Udp6Announce => { - stats_repository.increase_udp6_announces().await; - } - Event::Udp6Scrape => { - stats_repository.increase_udp6_scrapes().await; - } + Event::Udp6Connect { context } => match context.client_socket_addr.ip() { + std::net::IpAddr::V4(_) => { + panic!("IP Version 4 does not match the event type for connect"); + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_connections().await; + } + }, + Event::Udp6Announce { context } => match context.client_socket_addr.ip() { + std::net::IpAddr::V4(_) => { + panic!("IP Version 4 does not match the event type for announce"); + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_announces().await; + } + }, + Event::Udp6Scrape { context } => match context.client_socket_addr.ip() { + std::net::IpAddr::V4(_) => { + panic!("IP Version 4 does not match the event type for scrape"); + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_scrapes().await; + } + }, } tracing::debug!("stats: {:?}", stats_repository.get_stats().await); @@ -31,15 +64,26 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { #[cfg(test)] mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use crate::statistics::event::handler::handle_event; - use crate::statistics::event::Event; + use crate::statistics::event::{ConnectionContext, Event}; use crate::statistics::repository::Repository; #[tokio::test] async fn should_increase_the_udp4_connections_counter_when_it_receives_a_udp4_connect_event() { let stats_repository = Repository::new(); - handle_event(Event::Udp4Connect, &stats_repository).await; + handle_event( + Event::Udp4Connect { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; @@ -50,7 +94,16 @@ mod tests { async fn should_increase_the_udp4_announces_counter_when_it_receives_a_udp4_announce_event() { let stats_repository = Repository::new(); - handle_event(Event::Udp4Announce, &stats_repository).await; + handle_event( + Event::Udp4Announce { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; @@ -61,7 +114,16 @@ mod tests { async fn should_increase_the_udp4_scrapes_counter_when_it_receives_a_udp4_scrape_event() { let stats_repository = Repository::new(); - handle_event(Event::Udp4Scrape, &stats_repository).await; + handle_event( + Event::Udp4Scrape { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; @@ -72,7 +134,16 @@ mod tests { async fn should_increase_the_udp6_connections_counter_when_it_receives_a_udp6_connect_event() { let stats_repository = Repository::new(); - handle_event(Event::Udp6Connect, &stats_repository).await; + handle_event( + Event::Udp6Connect { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; @@ -83,7 +154,16 @@ mod tests { async fn should_increase_the_udp6_announces_counter_when_it_receives_a_udp6_announce_event() { let stats_repository = Repository::new(); - handle_event(Event::Udp6Announce, &stats_repository).await; + handle_event( + Event::Udp6Announce { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; @@ -94,7 +174,16 @@ mod tests { async fn should_increase_the_udp6_scrapes_counter_when_it_receives_a_udp6_scrape_event() { let stats_repository = Repository::new(); - handle_event(Event::Udp6Scrape, &stats_repository).await; + handle_event( + Event::Udp6Scrape { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; diff --git a/packages/udp-tracker-core/src/statistics/event/mod.rs b/packages/udp-tracker-core/src/statistics/event/mod.rs index bfc733657..f460f0113 100644 --- a/packages/udp-tracker-core/src/statistics/event/mod.rs +++ b/packages/udp-tracker-core/src/statistics/event/mod.rs @@ -1,23 +1,36 @@ +use std::net::SocketAddr; + pub mod handler; pub mod listener; pub mod sender; /// An statistics event. It is used to collect tracker metrics. /// -/// - `Tcp` prefix means the event was triggered by the HTTP tracker /// - `Udp` prefix means the event was triggered by the UDP tracker /// - `4` or `6` prefixes means the IP version used by the peer /// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection` -/// -/// > NOTE: HTTP trackers do not use `connection` requests. #[derive(Debug, PartialEq, Eq)] pub enum Event { - // code-review: consider one single event for request type with data: Event::Announce { scheme: HTTPorUDP, ip_version: V4orV6 } - // Attributes are enums too. - Udp4Connect, - Udp4Announce, - Udp4Scrape, - Udp6Connect, - Udp6Announce, - Udp6Scrape, + Udp4Connect { context: ConnectionContext }, + Udp4Announce { context: ConnectionContext }, + Udp4Scrape { context: ConnectionContext }, + Udp6Connect { context: ConnectionContext }, + Udp6Announce { context: ConnectionContext }, + Udp6Scrape { context: ConnectionContext }, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct ConnectionContext { + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, +} + +impl ConnectionContext { + #[must_use] + pub fn new(client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) -> Self { + Self { + client_socket_addr, + server_socket_addr, + } + } } diff --git a/packages/udp-tracker-core/src/statistics/keeper.rs b/packages/udp-tracker-core/src/statistics/keeper.rs index dac7e7541..9d0768e31 100644 --- a/packages/udp-tracker-core/src/statistics/keeper.rs +++ b/packages/udp-tracker-core/src/statistics/keeper.rs @@ -51,7 +51,9 @@ impl Keeper { #[cfg(test)] mod tests { - use crate::statistics::event::Event; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use crate::statistics::event::{ConnectionContext, Event}; use crate::statistics::keeper::Keeper; use crate::statistics::metrics::Metrics; @@ -70,7 +72,14 @@ mod tests { let event_sender = stats_tracker.run_event_listener(); - let result = event_sender.send_event(Event::Udp4Connect).await; + let result = event_sender + .send_event(Event::Udp4Connect { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), + }) + .await; assert!(result.is_some()); } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index e56e1d831..d18a81329 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -26,7 +26,8 @@ use crate::statistics::event::UdpResponseKind; #[instrument(fields(transaction_id, connection_id, info_hash), skip(announce_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_announce( announce_service: &Arc, - remote_addr: SocketAddr, + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, request: &AnnounceRequest, core_config: &Arc, opt_udp_server_stats_event_sender: &Arc>>, @@ -40,7 +41,7 @@ pub async fn handle_announce( tracing::trace!("handle announce"); if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { - match remote_addr.ip() { + match client_socket_addr.ip() { IpAddr::V4(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp4Request { @@ -59,11 +60,11 @@ pub async fn handle_announce( } let announce_data = announce_service - .handle_announce(remote_addr, request, cookie_valid_range) + .handle_announce(client_socket_addr, server_socket_addr, request, cookie_valid_range) .await .map_err(|e| (e.into(), request.transaction_id))?; - Ok(build_response(remote_addr, request, core_config, &announce_data)) + Ok(build_response(client_socket_addr, request, core_config, &announce_data)) } fn build_response( @@ -237,10 +238,11 @@ mod tests { let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); - let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); + let client_socket_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip) @@ -249,7 +251,8 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &core_tracker_services.core_config, &server_udp_tracker_services.udp_server_stats_event_sender, @@ -276,15 +279,17 @@ mod tests { let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + let client_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) .into(); let response = handle_announce( &core_udp_tracker_services.announce_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &core_tracker_services.core_config, &server_udp_tracker_services.udp_server_stats_event_sender, @@ -325,10 +330,11 @@ mod tests { let remote_client_port = 8081; let peer_address = Ipv4Addr::new(126, 0, 0, 2); - let remote_addr = SocketAddr::new(IpAddr::V4(remote_client_ip), remote_client_port); + let client_socket_addr = SocketAddr::new(IpAddr::V4(remote_client_ip), remote_client_port); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(peer_address) @@ -337,7 +343,8 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &core_tracker_services.core_config, &server_udp_tracker_services.udp_server_stats_event_sender, @@ -381,14 +388,17 @@ mod tests { let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); - let remote_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + let client_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) .into(); handle_announce( &core_udp_tracker_services.announce_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &core_tracker_services.core_config, &udp_server_stats_event_sender, @@ -433,9 +443,13 @@ mod tests { let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); + let client_socket_addr = sample_ipv4_socket_address(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + handle_announce( &core_udp_tracker_services.announce_service, - sample_ipv4_socket_address(), + client_socket_addr, + server_socket_addr, &AnnounceRequestBuilder::default().into(), &core_tracker_services.core_config, &udp_server_stats_event_sender, @@ -469,10 +483,11 @@ mod tests { let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); - let remote_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); + let client_socket_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip) @@ -481,7 +496,8 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &core_tracker_services.core_config, &server_udp_tracker_services.udp_server_stats_event_sender, @@ -510,7 +526,7 @@ mod tests { mod using_ipv6 { use std::future; - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::{ @@ -546,10 +562,11 @@ mod tests { let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); - let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); + let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip_v4) @@ -558,7 +575,8 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &core_tracker_services.core_config, &server_udp_tracker_services.udp_server_stats_event_sender, @@ -588,15 +606,17 @@ mod tests { let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); - let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), 8080); + let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), 8080); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) .into(); let response = handle_announce( &core_udp_tracker_services.announce_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &core_tracker_services.core_config, &server_udp_tracker_services.udp_server_stats_event_sender, @@ -637,10 +657,11 @@ mod tests { let remote_client_port = 8081; let peer_address = "126.0.0.1".parse().unwrap(); - let remote_addr = SocketAddr::new(IpAddr::V6(remote_client_ip), remote_client_port); + let client_socket_addr = SocketAddr::new(IpAddr::V6(remote_client_ip), remote_client_port); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(peer_address) @@ -649,7 +670,8 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &core_tracker_services.core_config, &server_udp_tracker_service.udp_server_stats_event_sender, @@ -697,9 +719,12 @@ mod tests { let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); let client_port = 8080; - let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); + + let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) .into(); let announce_service = Arc::new(AnnounceService::new( @@ -710,7 +735,8 @@ mod tests { handle_announce( &announce_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &core_config, &udp_server_stats_event_sender, @@ -759,15 +785,17 @@ mod tests { let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); - let remote_addr = sample_ipv6_remote_addr(); + let client_socket_addr = sample_ipv6_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); let announce_request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) .into(); handle_announce( &core_udp_tracker_services.announce_service, - remote_addr, + client_socket_addr, + server_socket_addr, &announce_request, &core_tracker_services.core_config, &udp_server_stats_event_sender, @@ -791,6 +819,7 @@ mod tests { use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use bittorrent_udp_tracker_core::services::announce::AnnounceService; + use bittorrent_udp_tracker_core::statistics::event::ConnectionContext; use bittorrent_udp_tracker_core::{self, statistics as core_statistics}; use mockall::predicate::eq; @@ -807,6 +836,19 @@ mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); + let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); + let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); + + let client_ip_v4 = loopback_ipv4; + let client_ip_v6 = loopback_ipv6; + let client_port = 8080; + + let info_hash = AquaticInfoHash([0u8; 20]); + let peer_id = AquaticPeerId([255u8; 20]); + + let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); + let server_socket_addr = config.udp_trackers.clone().unwrap()[0].bind_address; + let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = @@ -817,7 +859,9 @@ mod tests { let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send_event() - .with(eq(core_statistics::event::Event::Udp6Announce)) + .with(eq(core_statistics::event::Event::Udp6Announce { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let udp_core_stats_event_sender: Arc>> = @@ -841,20 +885,8 @@ mod tests { &db_torrent_repository, )); - let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); - let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); - - let client_ip_v4 = loopback_ipv4; - let client_ip_v6 = loopback_ipv6; - let client_port = 8080; - - let info_hash = AquaticInfoHash([0u8; 20]); - let peer_id = AquaticPeerId([255u8; 20]); - - let remote_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); - let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap()) + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) .with_info_hash(info_hash) .with_peer_id(peer_id) .with_ip_address(client_ip_v4) @@ -871,7 +903,8 @@ mod tests { handle_announce( &announce_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &core_config, &udp_server_stats_event_sender, diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 93d3bb6f1..e3070264d 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -13,6 +13,7 @@ use crate::statistics::event::UdpResponseKind; #[instrument(fields(transaction_id), skip(connect_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_connect( remote_addr: SocketAddr, + server_addr: SocketAddr, request: &ConnectRequest, connect_service: &Arc, opt_udp_server_stats_event_sender: &Arc>>, @@ -40,7 +41,9 @@ pub async fn handle_connect( } } - let connection_id = connect_service.handle_connect(remote_addr, cookie_issue_time).await; + let connection_id = connect_service + .handle_connect(remote_addr, server_addr, cookie_issue_time) + .await; build_response(*request, connection_id) } @@ -60,12 +63,14 @@ mod tests { mod connect_request { use std::future; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; use bittorrent_udp_tracker_core::connection_cookie::make; use bittorrent_udp_tracker_core::services::connect::ConnectService; use bittorrent_udp_tracker_core::statistics as core_statistics; + use bittorrent_udp_tracker_core::statistics::event::ConnectionContext; use mockall::predicate::eq; use crate::handlers::handle_connect; @@ -84,6 +89,8 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); @@ -99,6 +106,7 @@ mod tests { let response = handle_connect( sample_ipv4_remote_addr(), + server_socket_addr, &request, &connect_service, &udp_server_stats_event_sender, @@ -117,6 +125,8 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); @@ -132,6 +142,7 @@ mod tests { let response = handle_connect( sample_ipv4_remote_addr(), + server_socket_addr, &request, &connect_service, &udp_server_stats_event_sender, @@ -150,6 +161,8 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let (udp_core_stats_event_sender, _udp_core_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); @@ -165,6 +178,7 @@ mod tests { let response = handle_connect( sample_ipv6_remote_addr(), + server_socket_addr, &request, &connect_service, &udp_server_stats_event_sender, @@ -183,10 +197,15 @@ mod tests { #[tokio::test] async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { + let client_socket_addr = sample_ipv4_socket_address(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send_event() - .with(eq(core_statistics::event::Event::Udp4Connect)) + .with(eq(core_statistics::event::Event::Udp4Connect { + context: core_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let udp_core_stats_event_sender: Arc>> = @@ -203,12 +222,11 @@ mod tests { let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); - let client_socket_address = sample_ipv4_socket_address(); - let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); handle_connect( - client_socket_address, + client_socket_addr, + server_socket_addr, &sample_connect_request(), &connect_service, &udp_server_stats_event_sender, @@ -219,10 +237,15 @@ mod tests { #[tokio::test] async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { + let client_socket_addr = sample_ipv6_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send_event() - .with(eq(core_statistics::event::Event::Udp6Connect)) + .with(eq(core_statistics::event::Event::Udp6Connect { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); let udp_core_stats_event_sender: Arc>> = @@ -242,7 +265,8 @@ mod tests { let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); handle_connect( - sample_ipv6_remote_addr(), + client_socket_addr, + server_socket_addr, &sample_connect_request(), &connect_service, &udp_server_stats_event_sender, diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 165b307e0..162af3020 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -58,7 +58,7 @@ pub(crate) async fn handle_packet( udp_request: RawRequest, udp_tracker_core_container: Arc, udp_tracker_server_container: Arc, - local_addr: SocketAddr, + server_socket_addr: SocketAddr, cookie_time_values: CookieTimeValues, ) -> Response { let request_id = Uuid::new_v4(); @@ -73,6 +73,7 @@ pub(crate) async fn handle_packet( Ok(request) => match handle_request( request, udp_request.from, + server_socket_addr, udp_tracker_core_container.clone(), udp_tracker_server_container.clone(), cookie_time_values.clone(), @@ -92,7 +93,7 @@ pub(crate) async fn handle_packet( handle_error( udp_request.from, - local_addr, + server_socket_addr, request_id, &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range.clone(), @@ -105,7 +106,7 @@ pub(crate) async fn handle_packet( Err(e) => { handle_error( udp_request.from, - local_addr, + server_socket_addr, request_id, &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range.clone(), @@ -129,14 +130,16 @@ pub(crate) async fn handle_packet( /// If a error happens in the `handle_request` function, it will just return the `ServerError`. #[instrument(skip( request, - remote_addr, + client_socket_addr, + server_socket_addr, udp_tracker_core_container, udp_tracker_server_container, cookie_time_values ))] pub async fn handle_request( request: Request, - remote_addr: SocketAddr, + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, udp_tracker_core_container: Arc, udp_tracker_server_container: Arc, cookie_time_values: CookieTimeValues, @@ -145,7 +148,8 @@ pub async fn handle_request( match request { Request::Connect(connect_request) => Ok(handle_connect( - remote_addr, + client_socket_addr, + server_socket_addr, &connect_request, &udp_tracker_core_container.connect_service, &udp_tracker_server_container.udp_server_stats_event_sender, @@ -155,7 +159,8 @@ pub async fn handle_request( Request::Announce(announce_request) => { handle_announce( &udp_tracker_core_container.announce_service, - remote_addr, + client_socket_addr, + server_socket_addr, &announce_request, &udp_tracker_core_container.core_config, &udp_tracker_server_container.udp_server_stats_event_sender, @@ -166,7 +171,8 @@ pub async fn handle_request( Request::Scrape(scrape_request) => { handle_scrape( &udp_tracker_core_container.scrape_service, - remote_addr, + client_socket_addr, + server_socket_addr, &scrape_request, &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range, diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index c385718a2..e820b2e96 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -24,7 +24,8 @@ use crate::statistics::event::UdpResponseKind; #[instrument(fields(transaction_id, connection_id), skip(scrape_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_scrape( scrape_service: &Arc, - remote_addr: SocketAddr, + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, request: &ScrapeRequest, opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, @@ -36,7 +37,7 @@ pub async fn handle_scrape( tracing::trace!("handle scrape"); if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { - match remote_addr.ip() { + match client_socket_addr.ip() { IpAddr::V4(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp4Request { @@ -55,7 +56,7 @@ pub async fn handle_scrape( } let scrape_data = scrape_service - .handle_scrape(remote_addr, request, cookie_valid_range) + .handle_scrape(client_socket_addr, server_socket_addr, request, cookie_valid_range) .await .map_err(|e| (e.into(), request.transaction_id))?; @@ -92,7 +93,7 @@ fn build_response(request: &ScrapeRequest, scrape_data: &ScrapeData) -> Response mod tests { mod scrape_request { - use std::net::SocketAddr; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::{ @@ -121,20 +122,22 @@ mod tests { let (_core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - let remote_addr = sample_ipv4_remote_addr(); + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let info_hash = InfoHash([0u8; 20]); let info_hashes = vec![info_hash]; let request = ScrapeRequest { - connection_id: make(gen_remote_fingerprint(&remote_addr), sample_issue_time()).unwrap(), + connection_id: make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap(), transaction_id: TransactionId(0i32.into()), info_hashes, }; let response = handle_scrape( &core_udp_tracker_services.scrape_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), @@ -186,21 +189,24 @@ mod tests { let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); - let remote_addr = sample_ipv4_remote_addr(); + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let info_hash = InfoHash([0u8; 20]); add_a_seeder( core_tracker_services.in_memory_torrent_repository.clone(), - &remote_addr, + &client_socket_addr, &info_hash, ) .await; - let request = build_scrape_request(&remote_addr, &info_hash); + let request = build_scrape_request(&client_socket_addr, &info_hash); handle_scrape( &core_udp_tracker_services.scrape_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &udp_server_stats_event_sender, sample_cookie_valid_range(), @@ -242,6 +248,8 @@ mod tests { } mod with_a_whitelisted_tracker { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use aquatic_udp_protocol::{InfoHash, NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; use crate::handlers::handle_scrape; @@ -257,24 +265,27 @@ mod tests { let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = initialize_core_tracker_services_for_listed_tracker(); - let remote_addr = sample_ipv4_remote_addr(); + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let info_hash = InfoHash([0u8; 20]); add_a_seeder( core_tracker_services.in_memory_torrent_repository.clone(), - &remote_addr, + &client_socket_addr, &info_hash, ) .await; core_tracker_services.in_memory_whitelist.add(&info_hash.0.into()).await; - let request = build_scrape_request(&remote_addr, &info_hash); + let request = build_scrape_request(&client_socket_addr, &info_hash); let torrent_stats = match_scrape_response( handle_scrape( &core_udp_tracker_services.scrape_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), @@ -298,22 +309,25 @@ mod tests { let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = initialize_core_tracker_services_for_listed_tracker(); - let remote_addr = sample_ipv4_remote_addr(); + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let info_hash = InfoHash([0u8; 20]); add_a_seeder( core_tracker_services.in_memory_torrent_repository.clone(), - &remote_addr, + &client_socket_addr, &info_hash, ) .await; - let request = build_scrape_request(&remote_addr, &info_hash); + let request = build_scrape_request(&client_socket_addr, &info_hash); let torrent_stats = match_scrape_response( handle_scrape( &core_udp_tracker_services.scrape_service, - remote_addr, + client_socket_addr, + server_socket_addr, &request, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), @@ -342,6 +356,7 @@ mod tests { mod using_ipv4 { use std::future; + use std::net::{IpAddr, Ipv6Addr, SocketAddr}; use std::sync::Arc; use mockall::predicate::eq; @@ -367,15 +382,17 @@ mod tests { let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); - let remote_addr = sample_ipv4_remote_addr(); + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); let (_core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); handle_scrape( &core_udp_tracker_services.scrape_service, - remote_addr, - &sample_scrape_request(&remote_addr), + client_socket_addr, + server_socket_addr, + &sample_scrape_request(&client_socket_addr), &udp_server_stats_event_sender, sample_cookie_valid_range(), ) @@ -386,6 +403,7 @@ mod tests { mod using_ipv6 { use std::future; + use std::net::{IpAddr, Ipv6Addr, SocketAddr}; use std::sync::Arc; use mockall::predicate::eq; @@ -411,15 +429,17 @@ mod tests { let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); - let remote_addr = sample_ipv6_remote_addr(); + let client_socket_addr = sample_ipv6_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); let (_core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); handle_scrape( &core_udp_tracker_services.scrape_service, - remote_addr, - &sample_scrape_request(&remote_addr), + client_socket_addr, + server_socket_addr, + &sample_scrape_request(&client_socket_addr), &udp_server_stats_event_sender, sample_cookie_valid_range(), ) From 8603f8b871bb10c3d86449d9ff471d1af5d26c92 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Mar 2025 17:25:41 +0000 Subject: [PATCH 0885/1297] refactor: [#1380] refactor: [#1373] merge UDP stats events with different IP version --- .../udp-tracker-core/src/services/announce.rs | 15 ++---- .../udp-tracker-core/src/services/connect.rs | 25 +++------- .../udp-tracker-core/src/services/scrape.rs | 12 ++--- .../src/statistics/event/handler.rs | 49 +++++-------------- .../src/statistics/event/mod.rs | 22 +++++---- .../udp-tracker-core/src/statistics/keeper.rs | 2 +- .../src/handlers/announce.rs | 2 +- .../src/handlers/connect.rs | 4 +- 8 files changed, 44 insertions(+), 87 deletions(-) diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index 22bc05a9e..f745a90fd 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -7,7 +7,7 @@ //! //! It also sends an [`udp_tracker_core::statistics::event::Event`] //! because events are specific for the HTTP tracker. -use std::net::{IpAddr, SocketAddr}; +use std::net::SocketAddr; use std::ops::Range; use std::sync::Arc; @@ -103,16 +103,11 @@ impl AnnounceService { async fn send_stats_event(&self, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) { if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { - let event = match client_socket_addr.ip() { - IpAddr::V4(_) => statistics::event::Event::Udp4Announce { + udp_stats_event_sender + .send_event(statistics::event::Event::UdpAnnounce { context: ConnectionContext::new(client_socket_addr, server_socket_addr), - }, - IpAddr::V6(_) => statistics::event::Event::Udp6Announce { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - }, - }; - - udp_stats_event_sender.send_event(event).await; + }) + .await; } } } diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index 5309a79d3..c3c2459cd 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -41,22 +41,11 @@ impl ConnectService { make(gen_remote_fingerprint(&client_socket_addr), cookie_issue_time).expect("it should be a normal value"); if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { - match client_socket_addr { - SocketAddr::V4(_) => { - udp_stats_event_sender - .send_event(statistics::event::Event::Udp4Connect { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - }) - .await; - } - SocketAddr::V6(_) => { - udp_stats_event_sender - .send_event(statistics::event::Event::Udp6Connect { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - }) - .await; - } - } + udp_stats_event_sender + .send_event(statistics::event::Event::UdpConnect { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }) + .await; } connection_id @@ -149,7 +138,7 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Udp4Connect { + .with(eq(statistics::event::Event::UdpConnect { context: ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) @@ -172,7 +161,7 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::Udp6Connect { + .with(eq(statistics::event::Event::UdpConnect { context: ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index 0f1ab14d8..446c1182f 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -85,15 +85,11 @@ impl ScrapeService { async fn send_stats_event(&self, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) { if let Some(udp_stats_event_sender) = self.opt_udp_stats_event_sender.as_deref() { - let event = match client_socket_addr { - SocketAddr::V4(_) => statistics::event::Event::Udp4Scrape { + udp_stats_event_sender + .send_event(statistics::event::Event::UdpScrape { context: ConnectionContext::new(client_socket_addr, server_socket_addr), - }, - SocketAddr::V6(_) => statistics::event::Event::Udp6Scrape { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - }, - }; - udp_stats_event_sender.send_event(event).await; + }) + .await; } } } diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index 1f8a64a88..98860592f 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -6,52 +6,25 @@ use crate::statistics::repository::Repository; /// This function panics if the IP version does not match the event type. pub async fn handle_event(event: Event, stats_repository: &Repository) { match event { - // UDP4 - Event::Udp4Connect { context } => match context.client_socket_addr.ip() { + Event::UdpConnect { context } => match context.client_socket_addr.ip() { std::net::IpAddr::V4(_) => { stats_repository.increase_udp4_connections().await; } - std::net::IpAddr::V6(_) => { - panic!("IP Version 6 does not match the event type for connect"); - } - }, - Event::Udp4Announce { context } => match context.client_socket_addr.ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_announces().await; - } - std::net::IpAddr::V6(_) => { - panic!("IP Version 6 does not match the event type for announce"); - } - }, - Event::Udp4Scrape { context } => match context.client_socket_addr.ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_scrapes().await; - } - std::net::IpAddr::V6(_) => { - panic!("IP Version 6 does not match the event type for scrape"); - } - }, - - // UDP6 - Event::Udp6Connect { context } => match context.client_socket_addr.ip() { - std::net::IpAddr::V4(_) => { - panic!("IP Version 4 does not match the event type for connect"); - } std::net::IpAddr::V6(_) => { stats_repository.increase_udp6_connections().await; } }, - Event::Udp6Announce { context } => match context.client_socket_addr.ip() { + Event::UdpAnnounce { context } => match context.client_socket_addr.ip() { std::net::IpAddr::V4(_) => { - panic!("IP Version 4 does not match the event type for announce"); + stats_repository.increase_udp4_announces().await; } std::net::IpAddr::V6(_) => { stats_repository.increase_udp6_announces().await; } }, - Event::Udp6Scrape { context } => match context.client_socket_addr.ip() { + Event::UdpScrape { context } => match context.client_socket_addr.ip() { std::net::IpAddr::V4(_) => { - panic!("IP Version 4 does not match the event type for scrape"); + stats_repository.increase_udp4_scrapes().await; } std::net::IpAddr::V6(_) => { stats_repository.increase_udp6_scrapes().await; @@ -75,7 +48,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp4Connect { + Event::UdpConnect { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -95,7 +68,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp4Announce { + Event::UdpAnnounce { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -115,7 +88,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp4Scrape { + Event::UdpScrape { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -135,7 +108,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp6Connect { + Event::UdpConnect { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), @@ -155,7 +128,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp6Announce { + Event::UdpAnnounce { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), @@ -175,7 +148,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp6Scrape { + Event::UdpScrape { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), diff --git a/packages/udp-tracker-core/src/statistics/event/mod.rs b/packages/udp-tracker-core/src/statistics/event/mod.rs index f460f0113..05de5d118 100644 --- a/packages/udp-tracker-core/src/statistics/event/mod.rs +++ b/packages/udp-tracker-core/src/statistics/event/mod.rs @@ -6,17 +6,13 @@ pub mod sender; /// An statistics event. It is used to collect tracker metrics. /// -/// - `Udp` prefix means the event was triggered by the UDP tracker -/// - `4` or `6` prefixes means the IP version used by the peer -/// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection` +/// - `Udp` prefix means the event was triggered by the UDP tracker. +/// - The event suffix is the type of request: `announce`, `scrape` or `connection`. #[derive(Debug, PartialEq, Eq)] pub enum Event { - Udp4Connect { context: ConnectionContext }, - Udp4Announce { context: ConnectionContext }, - Udp4Scrape { context: ConnectionContext }, - Udp6Connect { context: ConnectionContext }, - Udp6Announce { context: ConnectionContext }, - Udp6Scrape { context: ConnectionContext }, + UdpConnect { context: ConnectionContext }, + UdpAnnounce { context: ConnectionContext }, + UdpScrape { context: ConnectionContext }, } #[derive(Debug, PartialEq, Eq)] @@ -33,4 +29,12 @@ impl ConnectionContext { server_socket_addr, } } + + pub fn client_socket_addr(&self) -> SocketAddr { + self.client_socket_addr + } + + pub fn server_socket_addr(&self) -> SocketAddr { + self.server_socket_addr + } } diff --git a/packages/udp-tracker-core/src/statistics/keeper.rs b/packages/udp-tracker-core/src/statistics/keeper.rs index 9d0768e31..e46e634e8 100644 --- a/packages/udp-tracker-core/src/statistics/keeper.rs +++ b/packages/udp-tracker-core/src/statistics/keeper.rs @@ -73,7 +73,7 @@ mod tests { let event_sender = stats_tracker.run_event_listener(); let result = event_sender - .send_event(Event::Udp4Connect { + .send_event(Event::UdpConnect { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index d18a81329..a0aabb765 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -859,7 +859,7 @@ mod tests { let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send_event() - .with(eq(core_statistics::event::Event::Udp6Announce { + .with(eq(core_statistics::event::Event::UdpAnnounce { context: ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index e3070264d..bac3d7961 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -203,7 +203,7 @@ mod tests { let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send_event() - .with(eq(core_statistics::event::Event::Udp4Connect { + .with(eq(core_statistics::event::Event::UdpConnect { context: core_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) @@ -243,7 +243,7 @@ mod tests { let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send_event() - .with(eq(core_statistics::event::Event::Udp6Connect { + .with(eq(core_statistics::event::Event::UdpConnect { context: ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) From 74ffa4cfd2549fdc28484f3c4cb8844eaf6c61cf Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 17 Mar 2025 18:30:09 +0000 Subject: [PATCH 0886/1297] refactor: [#1382] error request kind in UDP req does not make sense --- .../src/statistics/event/mod.rs | 2 + .../src/handlers/announce.rs | 18 ++--- .../src/handlers/connect.rs | 12 ++-- .../udp-tracker-server/src/handlers/scrape.rs | 10 +-- .../src/server/processor.rs | 12 +++- .../src/statistics/event/handler.rs | 70 ++++++++++--------- .../src/statistics/event/mod.rs | 13 ++-- 7 files changed, 77 insertions(+), 60 deletions(-) diff --git a/packages/udp-tracker-core/src/statistics/event/mod.rs b/packages/udp-tracker-core/src/statistics/event/mod.rs index 05de5d118..216562506 100644 --- a/packages/udp-tracker-core/src/statistics/event/mod.rs +++ b/packages/udp-tracker-core/src/statistics/event/mod.rs @@ -30,10 +30,12 @@ impl ConnectionContext { } } + #[must_use] pub fn client_socket_addr(&self) -> SocketAddr { self.client_socket_addr } + #[must_use] pub fn server_socket_addr(&self) -> SocketAddr { self.server_socket_addr } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index a0aabb765..38fe5acc6 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -16,7 +16,7 @@ use zerocopy::network_endian::I32; use crate::error::Error; use crate::statistics as server_statistics; -use crate::statistics::event::UdpResponseKind; +use crate::statistics::event::UdpRequestKind; /// It handles the `Announce` request. /// @@ -45,14 +45,14 @@ pub async fn handle_announce( IpAddr::V4(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp4Request { - kind: UdpResponseKind::Announce, + kind: UdpRequestKind::Announce, }) .await; } IpAddr::V6(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp6Request { - kind: UdpResponseKind::Announce, + kind: UdpRequestKind::Announce, }) .await; } @@ -226,7 +226,7 @@ mod tests { TorrentPeerBuilder, }; use crate::statistics as server_statistics; - use crate::statistics::event::UdpResponseKind; + use crate::statistics::event::UdpRequestKind; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { @@ -433,7 +433,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp4Request { - kind: UdpResponseKind::Announce, + kind: UdpRequestKind::Announce, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); @@ -549,7 +549,7 @@ mod tests { sample_issue_time, MockUdpServerStatsEventSender, TorrentPeerBuilder, }; use crate::statistics as server_statistics; - use crate::statistics::event::UdpResponseKind; + use crate::statistics::event::UdpRequestKind; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { @@ -775,7 +775,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp6Request { - kind: UdpResponseKind::Announce, + kind: UdpRequestKind::Announce, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); @@ -830,7 +830,7 @@ mod tests { TrackerConfigurationBuilder, }; use crate::statistics as server_statistics; - use crate::statistics::event::UdpResponseKind; + use crate::statistics::event::UdpRequestKind; #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { @@ -871,7 +871,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp6Request { - kind: UdpResponseKind::Announce, + kind: UdpRequestKind::Announce, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index bac3d7961..2111e7584 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -7,7 +7,7 @@ use bittorrent_udp_tracker_core::services::connect::ConnectService; use tracing::{instrument, Level}; use crate::statistics as server_statistics; -use crate::statistics::event::UdpResponseKind; +use crate::statistics::event::UdpRequestKind; /// It handles the `Connect` request. #[instrument(fields(transaction_id), skip(connect_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] @@ -27,14 +27,14 @@ pub async fn handle_connect( IpAddr::V4(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp4Request { - kind: UdpResponseKind::Connect, + kind: UdpRequestKind::Connect, }) .await; } IpAddr::V6(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp6Request { - kind: UdpResponseKind::Connect, + kind: UdpRequestKind::Connect, }) .await; } @@ -79,7 +79,7 @@ mod tests { sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, }; use crate::statistics as server_statistics; - use crate::statistics::event::UdpResponseKind; + use crate::statistics::event::UdpRequestKind; fn sample_connect_request() -> ConnectRequest { ConnectRequest { @@ -215,7 +215,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp4Request { - kind: UdpResponseKind::Connect, + kind: UdpRequestKind::Connect, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); @@ -255,7 +255,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp6Request { - kind: UdpResponseKind::Connect, + kind: UdpRequestKind::Connect, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index e820b2e96..137c8a3cb 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -14,7 +14,7 @@ use zerocopy::network_endian::I32; use crate::error::Error; use crate::statistics as server_statistics; -use crate::statistics::event::UdpResponseKind; +use crate::statistics::event::UdpRequestKind; /// It handles the `Scrape` request. /// @@ -41,14 +41,14 @@ pub async fn handle_scrape( IpAddr::V4(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp4Request { - kind: UdpResponseKind::Scrape, + kind: UdpRequestKind::Scrape, }) .await; } IpAddr::V6(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp6Request { - kind: UdpResponseKind::Scrape, + kind: UdpRequestKind::Scrape, }) .await; } @@ -375,7 +375,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp4Request { - kind: server_statistics::event::UdpResponseKind::Scrape, + kind: server_statistics::event::UdpRequestKind::Scrape, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); @@ -422,7 +422,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp6Request { - kind: server_statistics::event::UdpResponseKind::Scrape, + kind: server_statistics::event::UdpRequestKind::Scrape, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs index 44b543571..52188c4c2 100644 --- a/packages/udp-tracker-server/src/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -69,9 +69,15 @@ impl Processor { }; let udp_response_kind = match &response { - Response::Connect(_) => statistics::event::UdpResponseKind::Connect, - Response::AnnounceIpv4(_) | Response::AnnounceIpv6(_) => statistics::event::UdpResponseKind::Announce, - Response::Scrape(_) => statistics::event::UdpResponseKind::Scrape, + Response::Connect(_) => statistics::event::UdpResponseKind::Ok { + req_kind: statistics::event::UdpRequestKind::Connect, + }, + Response::AnnounceIpv4(_) | Response::AnnounceIpv6(_) => statistics::event::UdpResponseKind::Ok { + req_kind: statistics::event::UdpRequestKind::Announce, + }, + Response::Scrape(_) => statistics::event::UdpResponseKind::Ok { + req_kind: statistics::event::UdpRequestKind::Scrape, + }, Response::Error(_e) => statistics::event::UdpResponseKind::Error, }; diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 5ce9f6307..7c7e4a8e7 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -1,4 +1,4 @@ -use crate::statistics::event::{Event, UdpResponseKind}; +use crate::statistics::event::{Event, UdpRequestKind, UdpResponseKind}; use crate::statistics::repository::Repository; pub async fn handle_event(event: Event, stats_repository: &Repository) { @@ -16,16 +16,15 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { stats_repository.increase_udp4_requests().await; } Event::Udp4Request { kind } => match kind { - UdpResponseKind::Connect => { + UdpRequestKind::Connect => { stats_repository.increase_udp4_connections().await; } - UdpResponseKind::Announce => { + UdpRequestKind::Announce => { stats_repository.increase_udp4_announces().await; } - UdpResponseKind::Scrape => { + UdpRequestKind::Scrape => { stats_repository.increase_udp4_scrapes().await; } - UdpResponseKind::Error => {} }, Event::Udp4Response { kind, @@ -34,21 +33,23 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { stats_repository.increase_udp4_responses().await; match kind { - UdpResponseKind::Connect => { - stats_repository - .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) - .await; - } - UdpResponseKind::Announce => { - stats_repository - .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) - .await; - } - UdpResponseKind::Scrape => { - stats_repository - .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) - .await; - } + UdpResponseKind::Ok { req_kind } => match req_kind { + UdpRequestKind::Connect => { + stats_repository + .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) + .await; + } + UdpRequestKind::Announce => { + stats_repository + .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) + .await; + } + UdpRequestKind::Scrape => { + stats_repository + .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) + .await; + } + }, UdpResponseKind::Error => {} } } @@ -61,16 +62,15 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { stats_repository.increase_udp6_requests().await; } Event::Udp6Request { kind } => match kind { - UdpResponseKind::Connect => { + UdpRequestKind::Connect => { stats_repository.increase_udp6_connections().await; } - UdpResponseKind::Announce => { + UdpRequestKind::Announce => { stats_repository.increase_udp6_announces().await; } - UdpResponseKind::Scrape => { + UdpRequestKind::Scrape => { stats_repository.increase_udp6_scrapes().await; } - UdpResponseKind::Error => {} }, Event::Udp6Response { kind: _, @@ -89,7 +89,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { #[cfg(test)] mod tests { use crate::statistics::event::handler::handle_event; - use crate::statistics::event::Event; + use crate::statistics::event::{Event, UdpRequestKind}; use crate::statistics::repository::Repository; #[tokio::test] @@ -148,7 +148,7 @@ mod tests { handle_event( Event::Udp4Request { - kind: crate::statistics::event::UdpResponseKind::Connect, + kind: crate::statistics::event::UdpRequestKind::Connect, }, &stats_repository, ) @@ -165,7 +165,7 @@ mod tests { handle_event( Event::Udp4Request { - kind: crate::statistics::event::UdpResponseKind::Announce, + kind: crate::statistics::event::UdpRequestKind::Announce, }, &stats_repository, ) @@ -182,7 +182,7 @@ mod tests { handle_event( Event::Udp4Request { - kind: crate::statistics::event::UdpResponseKind::Scrape, + kind: crate::statistics::event::UdpRequestKind::Scrape, }, &stats_repository, ) @@ -199,7 +199,9 @@ mod tests { handle_event( Event::Udp4Response { - kind: crate::statistics::event::UdpResponseKind::Announce, + kind: crate::statistics::event::UdpResponseKind::Ok { + req_kind: UdpRequestKind::Announce, + }, req_processing_time: std::time::Duration::from_secs(1), }, &stats_repository, @@ -228,7 +230,7 @@ mod tests { handle_event( Event::Udp6Request { - kind: crate::statistics::event::UdpResponseKind::Connect, + kind: crate::statistics::event::UdpRequestKind::Connect, }, &stats_repository, ) @@ -245,7 +247,7 @@ mod tests { handle_event( Event::Udp6Request { - kind: crate::statistics::event::UdpResponseKind::Announce, + kind: crate::statistics::event::UdpRequestKind::Announce, }, &stats_repository, ) @@ -262,7 +264,7 @@ mod tests { handle_event( Event::Udp6Request { - kind: crate::statistics::event::UdpResponseKind::Scrape, + kind: crate::statistics::event::UdpRequestKind::Scrape, }, &stats_repository, ) @@ -279,7 +281,9 @@ mod tests { handle_event( Event::Udp6Response { - kind: crate::statistics::event::UdpResponseKind::Announce, + kind: crate::statistics::event::UdpResponseKind::Ok { + req_kind: UdpRequestKind::Announce, + }, req_processing_time: std::time::Duration::from_secs(1), }, &stats_repository, diff --git a/packages/udp-tracker-server/src/statistics/event/mod.rs b/packages/udp-tracker-server/src/statistics/event/mod.rs index 6a48b9449..3b14806aa 100644 --- a/packages/udp-tracker-server/src/statistics/event/mod.rs +++ b/packages/udp-tracker-server/src/statistics/event/mod.rs @@ -22,7 +22,7 @@ pub enum Event { // UDP4 Udp4IncomingRequest, Udp4Request { - kind: UdpResponseKind, + kind: UdpRequestKind, }, Udp4Response { kind: UdpResponseKind, @@ -33,7 +33,7 @@ pub enum Event { // UDP6 Udp6IncomingRequest, Udp6Request { - kind: UdpResponseKind, + kind: UdpRequestKind, }, Udp6Response { kind: UdpResponseKind, @@ -43,9 +43,14 @@ pub enum Event { } #[derive(Debug, PartialEq, Eq)] -pub enum UdpResponseKind { +pub enum UdpRequestKind { Connect, Announce, Scrape, - Error, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum UdpResponseKind { + Ok { req_kind: UdpRequestKind }, + Error, // todo: add the request kind `{ req_kind: Option(UdpRequestKind) }` when we know it. } From e4c6000645bca78ba6d69900574931603b4581f1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Mar 2025 08:46:29 +0000 Subject: [PATCH 0887/1297] refactor: [#1382] add connection context to UDP server events --- .../src/handlers/announce.rs | 22 +- .../src/handlers/connect.rs | 17 +- .../udp-tracker-server/src/handlers/error.rs | 21 +- .../udp-tracker-server/src/handlers/scrape.rs | 20 +- .../udp-tracker-server/src/server/launcher.rs | 23 +- .../src/server/processor.rs | 13 +- .../src/statistics/event/handler.rs | 273 ++++++++++++++---- .../src/statistics/event/mod.rs | 60 +++- .../src/statistics/keeper.rs | 13 +- 9 files changed, 357 insertions(+), 105 deletions(-) diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 38fe5acc6..41e40695d 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -16,7 +16,7 @@ use zerocopy::network_endian::I32; use crate::error::Error; use crate::statistics as server_statistics; -use crate::statistics::event::UdpRequestKind; +use crate::statistics::event::{ConnectionContext, UdpRequestKind}; /// It handles the `Announce` request. /// @@ -45,6 +45,7 @@ pub async fn handle_announce( IpAddr::V4(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp4Request { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, }) .await; @@ -52,6 +53,7 @@ pub async fn handle_announce( IpAddr::V6(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp6Request { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, }) .await; @@ -429,10 +431,14 @@ mod tests { #[tokio::test] async fn should_send_the_upd4_announce_event() { + let client_socket_addr = sample_ipv4_socket_address(); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp4Request { + context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, })) .times(1) @@ -443,9 +449,6 @@ mod tests { let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); - let client_socket_addr = sample_ipv4_socket_address(); - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); - handle_announce( &core_udp_tracker_services.announce_service, client_socket_addr, @@ -771,10 +774,14 @@ mod tests { #[tokio::test] async fn should_send_the_upd6_announce_event() { + let client_socket_addr = sample_ipv6_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp6Request { + context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, })) .times(1) @@ -785,9 +792,6 @@ mod tests { let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); - let client_socket_addr = sample_ipv6_remote_addr(); - let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); - let announce_request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) .into(); @@ -819,7 +823,6 @@ mod tests { use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use bittorrent_udp_tracker_core::services::announce::AnnounceService; - use bittorrent_udp_tracker_core::statistics::event::ConnectionContext; use bittorrent_udp_tracker_core::{self, statistics as core_statistics}; use mockall::predicate::eq; @@ -860,7 +863,7 @@ mod tests { udp_core_stats_event_sender_mock .expect_send_event() .with(eq(core_statistics::event::Event::UdpAnnounce { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: core_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); @@ -871,6 +874,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp6Request { + context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, })) .times(1) diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 2111e7584..3e0012d7d 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -7,13 +7,13 @@ use bittorrent_udp_tracker_core::services::connect::ConnectService; use tracing::{instrument, Level}; use crate::statistics as server_statistics; -use crate::statistics::event::UdpRequestKind; +use crate::statistics::event::{ConnectionContext, UdpRequestKind}; /// It handles the `Connect` request. #[instrument(fields(transaction_id), skip(connect_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_connect( - remote_addr: SocketAddr, - server_addr: SocketAddr, + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, request: &ConnectRequest, connect_service: &Arc, opt_udp_server_stats_event_sender: &Arc>>, @@ -23,10 +23,11 @@ pub async fn handle_connect( tracing::trace!("handle connect"); if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { - match remote_addr.ip() { + match client_socket_addr.ip() { IpAddr::V4(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp4Request { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Connect, }) .await; @@ -34,6 +35,7 @@ pub async fn handle_connect( IpAddr::V6(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp6Request { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Connect, }) .await; @@ -42,7 +44,7 @@ pub async fn handle_connect( } let connection_id = connect_service - .handle_connect(remote_addr, server_addr, cookie_issue_time) + .handle_connect(client_socket_addr, server_socket_addr, cookie_issue_time) .await; build_response(*request, connection_id) @@ -70,7 +72,6 @@ mod tests { use bittorrent_udp_tracker_core::connection_cookie::make; use bittorrent_udp_tracker_core::services::connect::ConnectService; use bittorrent_udp_tracker_core::statistics as core_statistics; - use bittorrent_udp_tracker_core::statistics::event::ConnectionContext; use mockall::predicate::eq; use crate::handlers::handle_connect; @@ -215,6 +216,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp4Request { + context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Connect, })) .times(1) @@ -244,7 +246,7 @@ mod tests { udp_core_stats_event_sender_mock .expect_send_event() .with(eq(core_statistics::event::Event::UdpConnect { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: core_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(()))))); @@ -255,6 +257,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp6Request { + context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Connect, })) .times(1) diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index e4bd382da..df553be9f 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -12,12 +12,13 @@ use zerocopy::network_endian::I32; use crate::error::Error; use crate::statistics as server_statistics; +use crate::statistics::event::ConnectionContext; #[allow(clippy::too_many_arguments)] #[instrument(fields(transaction_id), skip(opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_error( - remote_addr: SocketAddr, - local_addr: SocketAddr, + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, request_id: Uuid, opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, @@ -29,10 +30,10 @@ pub async fn handle_error( match transaction_id { Some(transaction_id) => { let transaction_id = transaction_id.0.to_string(); - tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %e, %remote_addr, %local_addr, %request_id, %transaction_id, "response error"); + tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %e, %client_socket_addr, %server_socket_addr, %request_id, %transaction_id, "response error"); } None => { - tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %e, %remote_addr, %local_addr, %request_id, "response error"); + tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %e, %client_socket_addr, %server_socket_addr, %request_id, "response error"); } } @@ -43,7 +44,7 @@ pub async fn handle_error( transaction_id, err, } => { - if let Err(e) = check(connection_id, gen_remote_fingerprint(&remote_addr), cookie_valid_range) { + if let Err(e) = check(connection_id, gen_remote_fingerprint(&client_socket_addr), cookie_valid_range) { (e.to_string(), Some(*transaction_id)) } else { ((*err).to_string(), Some(*transaction_id)) @@ -57,15 +58,19 @@ pub async fn handle_error( if e.1.is_some() { if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { - match remote_addr { + match client_socket_addr { SocketAddr::V4(_) => { udp_server_stats_event_sender - .send_event(server_statistics::event::Event::Udp4Error) + .send_event(server_statistics::event::Event::Udp4Error { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }) .await; } SocketAddr::V6(_) => { udp_server_stats_event_sender - .send_event(server_statistics::event::Event::Udp6Error) + .send_event(server_statistics::event::Event::Udp6Error { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }) .await; } } diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 137c8a3cb..5f33f55ad 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -14,7 +14,7 @@ use zerocopy::network_endian::I32; use crate::error::Error; use crate::statistics as server_statistics; -use crate::statistics::event::UdpRequestKind; +use crate::statistics::event::{ConnectionContext, UdpRequestKind}; /// It handles the `Scrape` request. /// @@ -41,6 +41,7 @@ pub async fn handle_scrape( IpAddr::V4(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp4Request { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Scrape, }) .await; @@ -48,6 +49,7 @@ pub async fn handle_scrape( IpAddr::V6(_) => { udp_server_stats_event_sender .send_event(server_statistics::event::Event::Udp6Request { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Scrape, }) .await; @@ -368,13 +370,18 @@ mod tests { sample_ipv4_remote_addr, MockUdpServerStatsEventSender, }; use crate::statistics as server_statistics; + use crate::statistics::event::ConnectionContext; #[tokio::test] async fn should_send_the_upd4_scrape_event() { + let client_socket_addr = sample_ipv4_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp4Request { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: server_statistics::event::UdpRequestKind::Scrape, })) .times(1) @@ -382,9 +389,6 @@ mod tests { let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); - let client_socket_addr = sample_ipv4_remote_addr(); - let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); - let (_core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); @@ -415,13 +419,18 @@ mod tests { sample_ipv6_remote_addr, MockUdpServerStatsEventSender, }; use crate::statistics as server_statistics; + use crate::statistics::event::ConnectionContext; #[tokio::test] async fn should_send_the_upd6_scrape_event() { + let client_socket_addr = sample_ipv6_remote_addr(); + let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() .with(eq(server_statistics::event::Event::Udp6Request { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: server_statistics::event::UdpRequestKind::Scrape, })) .times(1) @@ -429,9 +438,6 @@ mod tests { let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); - let client_socket_addr = sample_ipv6_remote_addr(); - let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); - let (_core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index acd214ab0..0dfbba174 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -21,6 +21,7 @@ use crate::server::bound_socket::BoundSocket; use crate::server::processor::Processor; use crate::server::receiver::Receiver; use crate::statistics; +use crate::statistics::event::ConnectionContext; const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 3600; @@ -129,9 +130,9 @@ impl Launcher { ) { let active_requests = &mut ActiveRequests::default(); - let addr = receiver.bound_socket_address(); + let server_socket_addr = receiver.bound_socket_address(); - let local_addr = format!("udp://{addr}"); + let local_addr = format!("udp://{server_socket_addr}"); let cookie_lifetime = cookie_lifetime.as_secs_f64(); @@ -167,17 +168,23 @@ impl Launcher { } }; + let client_socket_addr = req.from; + if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.udp_server_stats_event_sender.as_deref() { match req.from.ip() { IpAddr::V4(_) => { udp_server_stats_event_sender - .send_event(statistics::event::Event::Udp4IncomingRequest) + .send_event(statistics::event::Event::Udp4IncomingRequest { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }) .await; } IpAddr::V6(_) => { udp_server_stats_event_sender - .send_event(statistics::event::Event::Udp6IncomingRequest) + .send_event(statistics::event::Event::Udp6IncomingRequest { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }) .await; } } @@ -190,7 +197,9 @@ impl Launcher { udp_tracker_server_container.udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(statistics::event::Event::UdpRequestBanned) + .send_event(statistics::event::Event::UdpRequestBanned { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }) .await; } @@ -230,7 +239,9 @@ impl Launcher { udp_tracker_server_container.udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(statistics::event::Event::UdpRequestAborted) + .send_event(statistics::event::Event::UdpRequestAborted { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }) .await; } } diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs index 52188c4c2..999d74d00 100644 --- a/packages/udp-tracker-server/src/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -12,6 +12,7 @@ use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; use crate::container::UdpTrackerServerContainer; use crate::handlers::CookieTimeValues; +use crate::statistics::event::ConnectionContext; use crate::{handlers, statistics, RawRequest}; pub struct Processor { @@ -38,7 +39,7 @@ impl Processor { #[instrument(skip(self, request))] pub async fn process_request(self, request: RawRequest) { - let from = request.from; + let client_socket_addr = request.from; let start_time = Instant::now(); @@ -53,11 +54,11 @@ impl Processor { let elapsed_time = start_time.elapsed(); - self.send_response(from, response, elapsed_time).await; + self.send_response(client_socket_addr, response, elapsed_time).await; } #[instrument(skip(self))] - async fn send_response(self, target: SocketAddr, response: Response, req_processing_time: Duration) { + async fn send_response(self, client_socket_addr: SocketAddr, response: Response, req_processing_time: Duration) { tracing::debug!("send response"); let response_type = match &response { @@ -88,7 +89,7 @@ impl Processor { let bytes_count = writer.get_ref().len(); let payload = writer.get_ref(); - let () = match self.send_packet(&target, payload).await { + let () = match self.send_packet(&client_socket_addr, payload).await { Ok(sent_bytes) => { if tracing::event_enabled!(Level::TRACE) { tracing::debug!(%bytes_count, %sent_bytes, ?payload, "sent {response_type}"); @@ -99,10 +100,11 @@ impl Processor { if let Some(udp_server_stats_event_sender) = self.udp_tracker_server_container.udp_server_stats_event_sender.as_deref() { - match target.ip() { + match client_socket_addr.ip() { IpAddr::V4(_) => { udp_server_stats_event_sender .send_event(statistics::event::Event::Udp4Response { + context: ConnectionContext::new(client_socket_addr, self.socket.address()), kind: udp_response_kind, req_processing_time, }) @@ -111,6 +113,7 @@ impl Processor { IpAddr::V6(_) => { udp_server_stats_event_sender .send_event(statistics::event::Event::Udp6Response { + context: ConnectionContext::new(client_socket_addr, self.socket.address()), kind: udp_response_kind, req_processing_time, }) diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 7c7e4a8e7..bda07f678 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -1,85 +1,161 @@ use crate::statistics::event::{Event, UdpRequestKind, UdpResponseKind}; use crate::statistics::repository::Repository; +/// # Panics +/// +/// This function panics if the client IP version does not match the expected +/// version. +#[allow(clippy::too_many_lines)] pub async fn handle_event(event: Event, stats_repository: &Repository) { match event { // UDP - Event::UdpRequestAborted => { + Event::UdpRequestAborted { .. } => { stats_repository.increase_udp_requests_aborted().await; } - Event::UdpRequestBanned => { + Event::UdpRequestBanned { .. } => { stats_repository.increase_udp_requests_banned().await; } // UDP4 - Event::Udp4IncomingRequest => { - stats_repository.increase_udp4_requests().await; + Event::Udp4IncomingRequest { context } => { + if context.client_socket_addr.is_ipv4() { + stats_repository.increase_udp4_requests().await; + } else { + panic!("Client IP version does not match the expected version IPv4 for incoming request"); + } } - Event::Udp4Request { kind } => match kind { + Event::Udp4Request { context, kind } => match kind { UdpRequestKind::Connect => { - stats_repository.increase_udp4_connections().await; + if context.client_socket_addr.is_ipv4() { + stats_repository.increase_udp4_connections().await; + } else { + panic!("Client IP version does not match the expected version IPv4 for connect request"); + } } UdpRequestKind::Announce => { - stats_repository.increase_udp4_announces().await; + if context.client_socket_addr.is_ipv4() { + stats_repository.increase_udp4_announces().await; + } else { + panic!("Client IP version does not match the expected version IPv4 for announce request"); + } } UdpRequestKind::Scrape => { - stats_repository.increase_udp4_scrapes().await; + if context.client_socket_addr.is_ipv4() { + stats_repository.increase_udp4_scrapes().await; + } else { + panic!("Client IP version does not match the expected version IPv4 for scrape request"); + } } }, Event::Udp4Response { + context, kind, req_processing_time, } => { - stats_repository.increase_udp4_responses().await; - - match kind { - UdpResponseKind::Ok { req_kind } => match req_kind { - UdpRequestKind::Connect => { - stats_repository - .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) - .await; - } - UdpRequestKind::Announce => { - stats_repository - .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) - .await; - } - UdpRequestKind::Scrape => { - stats_repository - .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) - .await; - } - }, - UdpResponseKind::Error => {} + if context.client_socket_addr.is_ipv4() { + stats_repository.increase_udp4_responses().await; + + match kind { + UdpResponseKind::Ok { req_kind } => match req_kind { + UdpRequestKind::Connect => { + stats_repository + .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) + .await; + } + UdpRequestKind::Announce => { + stats_repository + .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) + .await; + } + UdpRequestKind::Scrape => { + stats_repository + .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) + .await; + } + }, + UdpResponseKind::Error => {} + } + } else { + panic!("Client IP version does not match the expected version IPv4 for response"); } } - Event::Udp4Error => { - stats_repository.increase_udp4_errors().await; + Event::Udp4Error { context } => { + if context.client_socket_addr.is_ipv4() { + stats_repository.increase_udp4_errors().await; + } else { + panic!("Client IP version does not match the expected version IPv4 for error"); + } } // UDP6 - Event::Udp6IncomingRequest => { - stats_repository.increase_udp6_requests().await; + Event::Udp6IncomingRequest { context } => { + if context.client_socket_addr.is_ipv6() { + stats_repository.increase_udp6_requests().await; + } else { + panic!("Client IP version does not match the expected version IPv6 for incoming request"); + } } - Event::Udp6Request { kind } => match kind { + Event::Udp6Request { context, kind } => match kind { UdpRequestKind::Connect => { - stats_repository.increase_udp6_connections().await; + if context.client_socket_addr.is_ipv6() { + stats_repository.increase_udp6_connections().await; + } else { + panic!("Client IP version does not match the expected version IPv6 for connect request"); + } } UdpRequestKind::Announce => { - stats_repository.increase_udp6_announces().await; + if context.client_socket_addr.is_ipv6() { + stats_repository.increase_udp6_announces().await; + } else { + panic!("Client IP version does not match the expected version IPv6 for announce request"); + } } UdpRequestKind::Scrape => { - stats_repository.increase_udp6_scrapes().await; + if context.client_socket_addr.is_ipv6() { + stats_repository.increase_udp6_scrapes().await; + } else { + panic!("Client IP version does not match the expected version IPv6 for scrape request"); + } } }, Event::Udp6Response { - kind: _, - req_processing_time: _, + context, + kind, + req_processing_time, } => { - stats_repository.increase_udp6_responses().await; + if context.client_socket_addr.is_ipv6() { + stats_repository.increase_udp6_responses().await; + + match kind { + UdpResponseKind::Ok { req_kind } => match req_kind { + UdpRequestKind::Connect => { + stats_repository + .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) + .await; + } + UdpRequestKind::Announce => { + stats_repository + .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) + .await; + } + UdpRequestKind::Scrape => { + stats_repository + .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) + .await; + } + }, + UdpResponseKind::Error => {} + } + } else { + panic!("Client IP version does not match the expected version IPv6 for response"); + } } - Event::Udp6Error => { - stats_repository.increase_udp6_errors().await; + Event::Udp6Error { context } => { + if context.client_socket_addr.is_ipv6() { + stats_repository.increase_udp6_errors().await; + } else { + panic!("Client IP version does not match the expected version IPv6 for error"); + } } } @@ -88,15 +164,26 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { #[cfg(test)] mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use crate::statistics::event::handler::handle_event; - use crate::statistics::event::{Event, UdpRequestKind}; + use crate::statistics::event::{ConnectionContext, Event, UdpRequestKind}; use crate::statistics::repository::Repository; #[tokio::test] async fn should_increase_the_number_of_aborted_requests_when_it_receives_a_udp_request_aborted_event() { let stats_repository = Repository::new(); - handle_event(Event::UdpRequestAborted, &stats_repository).await; + handle_event( + Event::UdpRequestAborted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; @@ -107,7 +194,16 @@ mod tests { async fn should_increase_the_number_of_banned_requests_when_it_receives_a_udp_request_banned_event() { let stats_repository = Repository::new(); - handle_event(Event::UdpRequestBanned, &stats_repository).await; + handle_event( + Event::UdpRequestBanned { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; @@ -118,7 +214,16 @@ mod tests { async fn should_increase_the_number_of_incoming_requests_when_it_receives_a_udp4_incoming_request_event() { let stats_repository = Repository::new(); - handle_event(Event::Udp4IncomingRequest, &stats_repository).await; + handle_event( + Event::Udp4IncomingRequest { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; @@ -129,7 +234,16 @@ mod tests { async fn should_increase_the_udp_abort_counter_when_it_receives_a_udp_abort_event() { let stats_repository = Repository::new(); - handle_event(Event::UdpRequestAborted, &stats_repository).await; + handle_event( + Event::UdpRequestAborted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; assert_eq!(stats.udp_requests_aborted, 1); } @@ -137,7 +251,16 @@ mod tests { async fn should_increase_the_udp_ban_counter_when_it_receives_a_udp_banned_event() { let stats_repository = Repository::new(); - handle_event(Event::UdpRequestBanned, &stats_repository).await; + handle_event( + Event::UdpRequestBanned { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; assert_eq!(stats.udp_requests_banned, 1); } @@ -148,6 +271,10 @@ mod tests { handle_event( Event::Udp4Request { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), kind: crate::statistics::event::UdpRequestKind::Connect, }, &stats_repository, @@ -165,6 +292,10 @@ mod tests { handle_event( Event::Udp4Request { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), kind: crate::statistics::event::UdpRequestKind::Announce, }, &stats_repository, @@ -182,6 +313,10 @@ mod tests { handle_event( Event::Udp4Request { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), kind: crate::statistics::event::UdpRequestKind::Scrape, }, &stats_repository, @@ -199,6 +334,10 @@ mod tests { handle_event( Event::Udp4Response { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), kind: crate::statistics::event::UdpResponseKind::Ok { req_kind: UdpRequestKind::Announce, }, @@ -217,7 +356,16 @@ mod tests { async fn should_increase_the_udp4_errors_counter_when_it_receives_a_udp4_error_event() { let stats_repository = Repository::new(); - handle_event(Event::Udp4Error, &stats_repository).await; + handle_event( + Event::Udp4Error { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; @@ -230,6 +378,10 @@ mod tests { handle_event( Event::Udp6Request { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ), kind: crate::statistics::event::UdpRequestKind::Connect, }, &stats_repository, @@ -247,6 +399,10 @@ mod tests { handle_event( Event::Udp6Request { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ), kind: crate::statistics::event::UdpRequestKind::Announce, }, &stats_repository, @@ -264,6 +420,10 @@ mod tests { handle_event( Event::Udp6Request { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ), kind: crate::statistics::event::UdpRequestKind::Scrape, }, &stats_repository, @@ -281,6 +441,10 @@ mod tests { handle_event( Event::Udp6Response { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ), kind: crate::statistics::event::UdpResponseKind::Ok { req_kind: UdpRequestKind::Announce, }, @@ -298,7 +462,16 @@ mod tests { async fn should_increase_the_udp6_errors_counter_when_it_receives_a_udp6_error_event() { let stats_repository = Repository::new(); - handle_event(Event::Udp6Error, &stats_repository).await; + handle_event( + Event::Udp6Error { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ), + }, + &stats_repository, + ) + .await; let stats = stats_repository.get_stats().await; diff --git a/packages/udp-tracker-server/src/statistics/event/mod.rs b/packages/udp-tracker-server/src/statistics/event/mod.rs index 3b14806aa..64e2cb9c1 100644 --- a/packages/udp-tracker-server/src/statistics/event/mod.rs +++ b/packages/udp-tracker-server/src/statistics/event/mod.rs @@ -1,3 +1,4 @@ +use std::net::SocketAddr; use std::time::Duration; pub mod handler; @@ -6,40 +7,51 @@ pub mod sender; /// An statistics event. It is used to collect tracker metrics. /// -/// - `Tcp` prefix means the event was triggered by the HTTP tracker /// - `Udp` prefix means the event was triggered by the UDP tracker /// - `4` or `6` prefixes means the IP version used by the peer /// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection` -/// -/// > NOTE: HTTP trackers do not use `connection` requests. #[derive(Debug, PartialEq, Eq)] pub enum Event { - // code-review: consider one single event for request type with data: Event::Announce { scheme: HTTPorUDP, ip_version: V4orV6 } - // Attributes are enums too. - UdpRequestAborted, - UdpRequestBanned, + UdpRequestAborted { + context: ConnectionContext, + }, + UdpRequestBanned { + context: ConnectionContext, + }, // UDP4 - Udp4IncomingRequest, + Udp4IncomingRequest { + context: ConnectionContext, + }, Udp4Request { + context: ConnectionContext, kind: UdpRequestKind, }, Udp4Response { + context: ConnectionContext, kind: UdpResponseKind, req_processing_time: Duration, }, - Udp4Error, + Udp4Error { + context: ConnectionContext, + }, // UDP6 - Udp6IncomingRequest, + Udp6IncomingRequest { + context: ConnectionContext, + }, Udp6Request { + context: ConnectionContext, kind: UdpRequestKind, }, Udp6Response { + context: ConnectionContext, kind: UdpResponseKind, req_processing_time: Duration, }, - Udp6Error, + Udp6Error { + context: ConnectionContext, + }, } #[derive(Debug, PartialEq, Eq)] @@ -54,3 +66,29 @@ pub enum UdpResponseKind { Ok { req_kind: UdpRequestKind }, Error, // todo: add the request kind `{ req_kind: Option(UdpRequestKind) }` when we know it. } + +#[derive(Debug, PartialEq, Eq)] +pub struct ConnectionContext { + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, +} + +impl ConnectionContext { + #[must_use] + pub fn new(client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) -> Self { + Self { + client_socket_addr, + server_socket_addr, + } + } + + #[must_use] + pub fn client_socket_addr(&self) -> SocketAddr { + self.client_socket_addr + } + + #[must_use] + pub fn server_socket_addr(&self) -> SocketAddr { + self.server_socket_addr + } +} diff --git a/packages/udp-tracker-server/src/statistics/keeper.rs b/packages/udp-tracker-server/src/statistics/keeper.rs index ae80e7970..a6e6dde70 100644 --- a/packages/udp-tracker-server/src/statistics/keeper.rs +++ b/packages/udp-tracker-server/src/statistics/keeper.rs @@ -51,7 +51,9 @@ impl Keeper { #[cfg(test)] mod tests { - use crate::statistics::event::Event; + use std::net::{IpAddr, Ipv6Addr, SocketAddr}; + + use crate::statistics::event::{ConnectionContext, Event}; use crate::statistics::keeper::Keeper; use crate::statistics::metrics::Metrics; @@ -70,7 +72,14 @@ mod tests { let event_sender = stats_tracker.run_event_listener(); - let result = event_sender.send_event(Event::Udp4IncomingRequest).await; + let result = event_sender + .send_event(Event::Udp4IncomingRequest { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ), + }) + .await; assert!(result.is_some()); } From 203a1b45e4e34103b9788393533e79613aab3dfa Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Mar 2025 10:36:50 +0000 Subject: [PATCH 0888/1297] refactor: [#1382] merge UDP server stats events with different IP version --- .../src/handlers/announce.rs | 30 +-- .../src/handlers/connect.rs | 30 +-- .../udp-tracker-server/src/handlers/error.rs | 21 +- .../udp-tracker-server/src/handlers/scrape.rs | 30 +-- .../udp-tracker-server/src/server/launcher.rs | 23 +- .../src/server/processor.rs | 29 +-- .../src/statistics/event/handler.rs | 200 ++++++------------ .../src/statistics/event/mod.rs | 35 +-- .../src/statistics/keeper.rs | 2 +- 9 files changed, 120 insertions(+), 280 deletions(-) diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 41e40695d..6b5cbb42b 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -41,24 +41,12 @@ pub async fn handle_announce( tracing::trace!("handle announce"); if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { - match client_socket_addr.ip() { - IpAddr::V4(_) => { - udp_server_stats_event_sender - .send_event(server_statistics::event::Event::Udp4Request { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - kind: UdpRequestKind::Announce, - }) - .await; - } - IpAddr::V6(_) => { - udp_server_stats_event_sender - .send_event(server_statistics::event::Event::Udp6Request { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - kind: UdpRequestKind::Announce, - }) - .await; - } - } + udp_server_stats_event_sender + .send_event(server_statistics::event::Event::UdpRequest { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + kind: UdpRequestKind::Announce, + }) + .await; } let announce_data = announce_service @@ -437,7 +425,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::Udp4Request { + .with(eq(server_statistics::event::Event::UdpRequest { context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, })) @@ -780,7 +768,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::Udp6Request { + .with(eq(server_statistics::event::Event::UdpRequest { context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, })) @@ -873,7 +861,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::Udp6Request { + .with(eq(server_statistics::event::Event::UdpRequest { context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, })) diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 3e0012d7d..7d96f4cbd 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -1,5 +1,5 @@ //! UDP tracker connect handler. -use std::net::{IpAddr, SocketAddr}; +use std::net::SocketAddr; use std::sync::Arc; use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, ConnectionId, Response}; @@ -23,24 +23,12 @@ pub async fn handle_connect( tracing::trace!("handle connect"); if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { - match client_socket_addr.ip() { - IpAddr::V4(_) => { - udp_server_stats_event_sender - .send_event(server_statistics::event::Event::Udp4Request { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - kind: UdpRequestKind::Connect, - }) - .await; - } - IpAddr::V6(_) => { - udp_server_stats_event_sender - .send_event(server_statistics::event::Event::Udp6Request { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - kind: UdpRequestKind::Connect, - }) - .await; - } - } + udp_server_stats_event_sender + .send_event(server_statistics::event::Event::UdpRequest { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + kind: UdpRequestKind::Connect, + }) + .await; } let connection_id = connect_service @@ -215,7 +203,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::Udp4Request { + .with(eq(server_statistics::event::Event::UdpRequest { context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Connect, })) @@ -256,7 +244,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::Udp6Request { + .with(eq(server_statistics::event::Event::UdpRequest { context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Connect, })) diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index df553be9f..cb341bc5c 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -58,22 +58,11 @@ pub async fn handle_error( if e.1.is_some() { if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { - match client_socket_addr { - SocketAddr::V4(_) => { - udp_server_stats_event_sender - .send_event(server_statistics::event::Event::Udp4Error { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - }) - .await; - } - SocketAddr::V6(_) => { - udp_server_stats_event_sender - .send_event(server_statistics::event::Event::Udp6Error { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - }) - .await; - } - } + udp_server_stats_event_sender + .send_event(server_statistics::event::Event::UdpError { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }) + .await; } } diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 5f33f55ad..7597c9b8e 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -1,5 +1,5 @@ //! UDP tracker scrape handler. -use std::net::{IpAddr, SocketAddr}; +use std::net::SocketAddr; use std::ops::Range; use std::sync::Arc; @@ -37,24 +37,12 @@ pub async fn handle_scrape( tracing::trace!("handle scrape"); if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { - match client_socket_addr.ip() { - IpAddr::V4(_) => { - udp_server_stats_event_sender - .send_event(server_statistics::event::Event::Udp4Request { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - kind: UdpRequestKind::Scrape, - }) - .await; - } - IpAddr::V6(_) => { - udp_server_stats_event_sender - .send_event(server_statistics::event::Event::Udp6Request { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - kind: UdpRequestKind::Scrape, - }) - .await; - } - } + udp_server_stats_event_sender + .send_event(server_statistics::event::Event::UdpRequest { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + kind: UdpRequestKind::Scrape, + }) + .await; } let scrape_data = scrape_service @@ -380,7 +368,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::Udp4Request { + .with(eq(server_statistics::event::Event::UdpRequest { context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: server_statistics::event::UdpRequestKind::Scrape, })) @@ -429,7 +417,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::Udp6Request { + .with(eq(server_statistics::event::Event::UdpRequest { context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: server_statistics::event::UdpRequestKind::Scrape, })) diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index 0dfbba174..a3da6a2a8 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -1,4 +1,4 @@ -use std::net::{IpAddr, SocketAddr}; +use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; @@ -172,22 +172,11 @@ impl Launcher { if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.udp_server_stats_event_sender.as_deref() { - match req.from.ip() { - IpAddr::V4(_) => { - udp_server_stats_event_sender - .send_event(statistics::event::Event::Udp4IncomingRequest { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - }) - .await; - } - IpAddr::V6(_) => { - udp_server_stats_event_sender - .send_event(statistics::event::Event::Udp6IncomingRequest { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), - }) - .await; - } - } + udp_server_stats_event_sender + .send_event(statistics::event::Event::UdpIncomingRequest { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), + }) + .await; } if udp_tracker_core_container.ban_service.read().await.is_banned(&req.from.ip()) { diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs index 999d74d00..acf8e8ae3 100644 --- a/packages/udp-tracker-server/src/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -1,5 +1,5 @@ use std::io::Cursor; -use std::net::{IpAddr, SocketAddr}; +use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; @@ -100,26 +100,13 @@ impl Processor { if let Some(udp_server_stats_event_sender) = self.udp_tracker_server_container.udp_server_stats_event_sender.as_deref() { - match client_socket_addr.ip() { - IpAddr::V4(_) => { - udp_server_stats_event_sender - .send_event(statistics::event::Event::Udp4Response { - context: ConnectionContext::new(client_socket_addr, self.socket.address()), - kind: udp_response_kind, - req_processing_time, - }) - .await; - } - IpAddr::V6(_) => { - udp_server_stats_event_sender - .send_event(statistics::event::Event::Udp6Response { - context: ConnectionContext::new(client_socket_addr, self.socket.address()), - kind: udp_response_kind, - req_processing_time, - }) - .await; - } - } + udp_server_stats_event_sender + .send_event(statistics::event::Event::UdpResponse { + context: ConnectionContext::new(client_socket_addr, self.socket.address()), + kind: udp_response_kind, + req_processing_time, + }) + .await; } } Err(error) => tracing::warn!(%bytes_count, %error, ?payload, "failed to send"), diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index bda07f678..5200561c7 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -8,155 +8,89 @@ use crate::statistics::repository::Repository; #[allow(clippy::too_many_lines)] pub async fn handle_event(event: Event, stats_repository: &Repository) { match event { - // UDP Event::UdpRequestAborted { .. } => { stats_repository.increase_udp_requests_aborted().await; } Event::UdpRequestBanned { .. } => { stats_repository.increase_udp_requests_banned().await; } - - // UDP4 - Event::Udp4IncomingRequest { context } => { - if context.client_socket_addr.is_ipv4() { + Event::UdpIncomingRequest { context } => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { stats_repository.increase_udp4_requests().await; - } else { - panic!("Client IP version does not match the expected version IPv4 for incoming request"); - } - } - Event::Udp4Request { context, kind } => match kind { - UdpRequestKind::Connect => { - if context.client_socket_addr.is_ipv4() { - stats_repository.increase_udp4_connections().await; - } else { - panic!("Client IP version does not match the expected version IPv4 for connect request"); - } } - UdpRequestKind::Announce => { - if context.client_socket_addr.is_ipv4() { - stats_repository.increase_udp4_announces().await; - } else { - panic!("Client IP version does not match the expected version IPv4 for announce request"); - } - } - UdpRequestKind::Scrape => { - if context.client_socket_addr.is_ipv4() { - stats_repository.increase_udp4_scrapes().await; - } else { - panic!("Client IP version does not match the expected version IPv4 for scrape request"); - } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_requests().await; } }, - Event::Udp4Response { - context, - kind, - req_processing_time, - } => { - if context.client_socket_addr.is_ipv4() { - stats_repository.increase_udp4_responses().await; - - match kind { - UdpResponseKind::Ok { req_kind } => match req_kind { - UdpRequestKind::Connect => { - stats_repository - .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) - .await; - } - UdpRequestKind::Announce => { - stats_repository - .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) - .await; - } - UdpRequestKind::Scrape => { - stats_repository - .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) - .await; - } - }, - UdpResponseKind::Error => {} + Event::UdpRequest { context, kind } => match kind { + UdpRequestKind::Connect => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_connections().await; } - } else { - panic!("Client IP version does not match the expected version IPv4 for response"); - } - } - Event::Udp4Error { context } => { - if context.client_socket_addr.is_ipv4() { - stats_repository.increase_udp4_errors().await; - } else { - panic!("Client IP version does not match the expected version IPv4 for error"); - } - } - - // UDP6 - Event::Udp6IncomingRequest { context } => { - if context.client_socket_addr.is_ipv6() { - stats_repository.increase_udp6_requests().await; - } else { - panic!("Client IP version does not match the expected version IPv6 for incoming request"); - } - } - Event::Udp6Request { context, kind } => match kind { - UdpRequestKind::Connect => { - if context.client_socket_addr.is_ipv6() { + std::net::IpAddr::V6(_) => { stats_repository.increase_udp6_connections().await; - } else { - panic!("Client IP version does not match the expected version IPv6 for connect request"); } - } - UdpRequestKind::Announce => { - if context.client_socket_addr.is_ipv6() { + }, + UdpRequestKind::Announce => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_announces().await; + } + std::net::IpAddr::V6(_) => { stats_repository.increase_udp6_announces().await; - } else { - panic!("Client IP version does not match the expected version IPv6 for announce request"); } - } - UdpRequestKind::Scrape => { - if context.client_socket_addr.is_ipv6() { + }, + UdpRequestKind::Scrape => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_scrapes().await; + } + std::net::IpAddr::V6(_) => { stats_repository.increase_udp6_scrapes().await; - } else { - panic!("Client IP version does not match the expected version IPv6 for scrape request"); } - } + }, }, - Event::Udp6Response { + Event::UdpResponse { context, kind, req_processing_time, } => { - if context.client_socket_addr.is_ipv6() { - stats_repository.increase_udp6_responses().await; - - match kind { - UdpResponseKind::Ok { req_kind } => match req_kind { - UdpRequestKind::Connect => { - stats_repository - .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) - .await; - } - UdpRequestKind::Announce => { - stats_repository - .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) - .await; - } - UdpRequestKind::Scrape => { - stats_repository - .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) - .await; - } - }, - UdpResponseKind::Error => {} + match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_responses().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_responses().await; } - } else { - panic!("Client IP version does not match the expected version IPv6 for response"); + } + + match kind { + UdpResponseKind::Ok { req_kind } => match req_kind { + UdpRequestKind::Connect => { + stats_repository + .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) + .await; + } + UdpRequestKind::Announce => { + stats_repository + .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) + .await; + } + UdpRequestKind::Scrape => { + stats_repository + .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) + .await; + } + }, + UdpResponseKind::Error => {} } } - Event::Udp6Error { context } => { - if context.client_socket_addr.is_ipv6() { + Event::UdpError { context } => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_errors().await; + } + std::net::IpAddr::V6(_) => { stats_repository.increase_udp6_errors().await; - } else { - panic!("Client IP version does not match the expected version IPv6 for error"); } - } + }, } tracing::debug!("stats: {:?}", stats_repository.get_stats().await); @@ -215,7 +149,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp4IncomingRequest { + Event::UdpIncomingRequest { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -270,7 +204,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp4Request { + Event::UdpRequest { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -291,7 +225,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp4Request { + Event::UdpRequest { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -312,7 +246,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp4Request { + Event::UdpRequest { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -333,7 +267,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp4Response { + Event::UdpResponse { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -357,7 +291,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp4Error { + Event::UdpError { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -377,7 +311,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp6Request { + Event::UdpRequest { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), @@ -398,7 +332,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp6Request { + Event::UdpRequest { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), @@ -419,7 +353,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp6Request { + Event::UdpRequest { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), @@ -440,7 +374,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp6Response { + Event::UdpResponse { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), @@ -463,7 +397,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::Udp6Error { + Event::UdpError { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), diff --git a/packages/udp-tracker-server/src/statistics/event/mod.rs b/packages/udp-tracker-server/src/statistics/event/mod.rs index 64e2cb9c1..b22cd455d 100644 --- a/packages/udp-tracker-server/src/statistics/event/mod.rs +++ b/packages/udp-tracker-server/src/statistics/event/mod.rs @@ -6,50 +6,27 @@ pub mod listener; pub mod sender; /// An statistics event. It is used to collect tracker metrics. -/// -/// - `Udp` prefix means the event was triggered by the UDP tracker -/// - `4` or `6` prefixes means the IP version used by the peer -/// - Finally the event suffix is the type of request: `announce`, `scrape` or `connection` #[derive(Debug, PartialEq, Eq)] pub enum Event { - UdpRequestAborted { + UdpIncomingRequest { context: ConnectionContext, }, - UdpRequestBanned { - context: ConnectionContext, - }, - - // UDP4 - Udp4IncomingRequest { - context: ConnectionContext, - }, - Udp4Request { - context: ConnectionContext, - kind: UdpRequestKind, - }, - Udp4Response { - context: ConnectionContext, - kind: UdpResponseKind, - req_processing_time: Duration, - }, - Udp4Error { + UdpRequestAborted { context: ConnectionContext, }, - - // UDP6 - Udp6IncomingRequest { + UdpRequestBanned { context: ConnectionContext, }, - Udp6Request { + UdpRequest { context: ConnectionContext, kind: UdpRequestKind, }, - Udp6Response { + UdpResponse { context: ConnectionContext, kind: UdpResponseKind, req_processing_time: Duration, }, - Udp6Error { + UdpError { context: ConnectionContext, }, } diff --git a/packages/udp-tracker-server/src/statistics/keeper.rs b/packages/udp-tracker-server/src/statistics/keeper.rs index a6e6dde70..c29dcb1b2 100644 --- a/packages/udp-tracker-server/src/statistics/keeper.rs +++ b/packages/udp-tracker-server/src/statistics/keeper.rs @@ -73,7 +73,7 @@ mod tests { let event_sender = stats_tracker.run_event_listener(); let result = event_sender - .send_event(Event::Udp4IncomingRequest { + .send_event(Event::UdpIncomingRequest { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), From 625d20adf7a502ecbab01b21bbaf5002635418f6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Mar 2025 10:50:33 +0000 Subject: [PATCH 0889/1297] refactor: [#1382] rename torrust_udp_tracker_server::statistics::event::Event::UdpRequest --- .../udp-tracker-server/src/handlers/announce.rs | 8 ++++---- .../udp-tracker-server/src/handlers/connect.rs | 6 +++--- packages/udp-tracker-server/src/handlers/scrape.rs | 6 +++--- .../src/statistics/event/handler.rs | 14 +++++++------- .../udp-tracker-server/src/statistics/event/mod.rs | 2 +- 5 files changed, 18 insertions(+), 18 deletions(-) diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 6b5cbb42b..32c9e0cbd 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -42,7 +42,7 @@ pub async fn handle_announce( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(server_statistics::event::Event::UdpRequest { + .send_event(server_statistics::event::Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, }) @@ -425,7 +425,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequest { + .with(eq(server_statistics::event::Event::UdpRequestAccepted { context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, })) @@ -768,7 +768,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequest { + .with(eq(server_statistics::event::Event::UdpRequestAccepted { context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, })) @@ -861,7 +861,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequest { + .with(eq(server_statistics::event::Event::UdpRequestAccepted { context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, })) diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 7d96f4cbd..c38eb56e5 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -24,7 +24,7 @@ pub async fn handle_connect( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(server_statistics::event::Event::UdpRequest { + .send_event(server_statistics::event::Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Connect, }) @@ -203,7 +203,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequest { + .with(eq(server_statistics::event::Event::UdpRequestAccepted { context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Connect, })) @@ -244,7 +244,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequest { + .with(eq(server_statistics::event::Event::UdpRequestAccepted { context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Connect, })) diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 7597c9b8e..aeca7bd12 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -38,7 +38,7 @@ pub async fn handle_scrape( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(server_statistics::event::Event::UdpRequest { + .send_event(server_statistics::event::Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Scrape, }) @@ -368,7 +368,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequest { + .with(eq(server_statistics::event::Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: server_statistics::event::UdpRequestKind::Scrape, })) @@ -417,7 +417,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequest { + .with(eq(server_statistics::event::Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: server_statistics::event::UdpRequestKind::Scrape, })) diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 5200561c7..03bfeae65 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -22,7 +22,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { stats_repository.increase_udp6_requests().await; } }, - Event::UdpRequest { context, kind } => match kind { + Event::UdpRequestAccepted { context, kind } => match kind { UdpRequestKind::Connect => match context.client_socket_addr().ip() { std::net::IpAddr::V4(_) => { stats_repository.increase_udp4_connections().await; @@ -204,7 +204,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::UdpRequest { + Event::UdpRequestAccepted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -225,7 +225,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::UdpRequest { + Event::UdpRequestAccepted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -246,7 +246,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::UdpRequest { + Event::UdpRequestAccepted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -311,7 +311,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::UdpRequest { + Event::UdpRequestAccepted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), @@ -332,7 +332,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::UdpRequest { + Event::UdpRequestAccepted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), @@ -353,7 +353,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::UdpRequest { + Event::UdpRequestAccepted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), diff --git a/packages/udp-tracker-server/src/statistics/event/mod.rs b/packages/udp-tracker-server/src/statistics/event/mod.rs index b22cd455d..207916846 100644 --- a/packages/udp-tracker-server/src/statistics/event/mod.rs +++ b/packages/udp-tracker-server/src/statistics/event/mod.rs @@ -17,7 +17,7 @@ pub enum Event { UdpRequestBanned { context: ConnectionContext, }, - UdpRequest { + UdpRequestAccepted { context: ConnectionContext, kind: UdpRequestKind, }, From 27e2db4b8f7515cf9ae5c08232431ae5719f8b7a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Mar 2025 11:31:33 +0000 Subject: [PATCH 0890/1297] refactor: [#1382] include req kin in UDP error response if it's known It could be unkown if the request couldb be parsed succesfully. --- .../src/handlers/announce.rs | 4 +- .../udp-tracker-server/src/handlers/error.rs | 3 +- .../udp-tracker-server/src/handlers/mod.rs | 60 ++++++++++++------- .../udp-tracker-server/src/handlers/scrape.rs | 4 +- .../src/server/processor.rs | 17 ++++-- .../src/statistics/event/handler.rs | 2 +- .../src/statistics/event/mod.rs | 19 ++++-- 7 files changed, 71 insertions(+), 38 deletions(-) diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 32c9e0cbd..5cc3cf3c8 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -32,7 +32,7 @@ pub async fn handle_announce( core_config: &Arc, opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, -) -> Result { +) -> Result { tracing::Span::current() .record("transaction_id", request.transaction_id.0.to_string()) .record("connection_id", request.connection_id.0.to_string()) @@ -52,7 +52,7 @@ pub async fn handle_announce( let announce_data = announce_service .handle_announce(client_socket_addr, server_socket_addr, request, cookie_valid_range) .await - .map_err(|e| (e.into(), request.transaction_id))?; + .map_err(|e| (e.into(), request.transaction_id, UdpRequestKind::Announce))?; Ok(build_response(client_socket_addr, request, core_config, &announce_data)) } diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index cb341bc5c..d1ffe2fd4 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -12,11 +12,12 @@ use zerocopy::network_endian::I32; use crate::error::Error; use crate::statistics as server_statistics; -use crate::statistics::event::ConnectionContext; +use crate::statistics::event::{ConnectionContext, UdpRequestKind}; #[allow(clippy::too_many_arguments)] #[instrument(fields(transaction_id), skip(opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_error( + req_kind: Option, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr, request_id: Uuid, diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 162af3020..e346d1953 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -24,6 +24,7 @@ use uuid::Uuid; use super::RawRequest; use crate::container::UdpTrackerServerContainer; use crate::error::Error; +use crate::statistics::event::UdpRequestKind; use crate::CurrentClock; #[derive(Debug, Clone, PartialEq)] @@ -60,7 +61,7 @@ pub(crate) async fn handle_packet( udp_tracker_server_container: Arc, server_socket_addr: SocketAddr, cookie_time_values: CookieTimeValues, -) -> Response { +) -> (Response, Option) { let request_id = Uuid::new_v4(); tracing::Span::current().record("request_id", request_id.to_string()); @@ -68,7 +69,7 @@ pub(crate) async fn handle_packet( let start_time = Instant::now(); - let response = + let (response, opt_req_kind) = match Request::parse_bytes(&udp_request.payload[..udp_request.payload.len()], MAX_SCRAPE_TORRENTS).map_err(Error::from) { Ok(request) => match handle_request( request, @@ -80,8 +81,8 @@ pub(crate) async fn handle_packet( ) .await { - Ok(response) => return response, - Err((error, transaction_id)) => { + Ok((response, req_kid)) => return (response, Some(req_kid)), + Err((error, transaction_id, req_kind)) => { if let Error::UdpAnnounceError { source: UdpAnnounceError::ConnectionCookieError { .. }, } = error @@ -91,7 +92,8 @@ pub(crate) async fn handle_packet( ban_service.increase_counter(&udp_request.from.ip()); } - handle_error( + let response = handle_error( + Some(req_kind.clone()), udp_request.from, server_socket_addr, request_id, @@ -100,11 +102,14 @@ pub(crate) async fn handle_packet( &error, Some(transaction_id), ) - .await + .await; + + (response, Some(req_kind)) } }, Err(e) => { - handle_error( + let response = handle_error( + None, udp_request.from, server_socket_addr, request_id, @@ -113,14 +118,16 @@ pub(crate) async fn handle_packet( &e, None, ) - .await + .await; + + (response, None) } }; let latency = start_time.elapsed(); tracing::trace!(?latency, "responded"); - response + (response, opt_req_kind) } /// It dispatches the request to the correct handler. @@ -143,21 +150,24 @@ pub async fn handle_request( udp_tracker_core_container: Arc, udp_tracker_server_container: Arc, cookie_time_values: CookieTimeValues, -) -> Result { +) -> Result<(Response, UdpRequestKind), (Error, TransactionId, UdpRequestKind)> { tracing::trace!("handle request"); match request { - Request::Connect(connect_request) => Ok(handle_connect( - client_socket_addr, - server_socket_addr, - &connect_request, - &udp_tracker_core_container.connect_service, - &udp_tracker_server_container.udp_server_stats_event_sender, - cookie_time_values.issue_time, - ) - .await), + Request::Connect(connect_request) => Ok(( + handle_connect( + client_socket_addr, + server_socket_addr, + &connect_request, + &udp_tracker_core_container.connect_service, + &udp_tracker_server_container.udp_server_stats_event_sender, + cookie_time_values.issue_time, + ) + .await, + UdpRequestKind::Connect, + )), Request::Announce(announce_request) => { - handle_announce( + match handle_announce( &udp_tracker_core_container.announce_service, client_socket_addr, server_socket_addr, @@ -167,9 +177,13 @@ pub async fn handle_request( cookie_time_values.valid_range, ) .await + { + Ok(response) => Ok((response, UdpRequestKind::Announce)), + Err(err) => Err(err), + } } Request::Scrape(scrape_request) => { - handle_scrape( + match handle_scrape( &udp_tracker_core_container.scrape_service, client_socket_addr, server_socket_addr, @@ -178,6 +192,10 @@ pub async fn handle_request( cookie_time_values.valid_range, ) .await + { + Ok(response) => Ok((response, UdpRequestKind::Scrape)), + Err(err) => Err(err), + } } } } diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index aeca7bd12..db6b4a18b 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -29,7 +29,7 @@ pub async fn handle_scrape( request: &ScrapeRequest, opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, -) -> Result { +) -> Result { tracing::Span::current() .record("transaction_id", request.transaction_id.0.to_string()) .record("connection_id", request.connection_id.0.to_string()); @@ -48,7 +48,7 @@ pub async fn handle_scrape( let scrape_data = scrape_service .handle_scrape(client_socket_addr, server_socket_addr, request, cookie_valid_range) .await - .map_err(|e| (e.into(), request.transaction_id))?; + .map_err(|e| (e.into(), request.transaction_id, UdpRequestKind::Scrape))?; Ok(build_response(request, &scrape_data)) } diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs index acf8e8ae3..59d21673f 100644 --- a/packages/udp-tracker-server/src/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -12,7 +12,7 @@ use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; use crate::container::UdpTrackerServerContainer; use crate::handlers::CookieTimeValues; -use crate::statistics::event::ConnectionContext; +use crate::statistics::event::{ConnectionContext, UdpRequestKind}; use crate::{handlers, statistics, RawRequest}; pub struct Processor { @@ -43,7 +43,7 @@ impl Processor { let start_time = Instant::now(); - let response = handlers::handle_packet( + let (response, opt_req_kind) = handlers::handle_packet( request, self.udp_tracker_core_container.clone(), self.udp_tracker_server_container.clone(), @@ -54,11 +54,18 @@ impl Processor { let elapsed_time = start_time.elapsed(); - self.send_response(client_socket_addr, response, elapsed_time).await; + self.send_response(client_socket_addr, response, opt_req_kind, elapsed_time) + .await; } #[instrument(skip(self))] - async fn send_response(self, client_socket_addr: SocketAddr, response: Response, req_processing_time: Duration) { + async fn send_response( + self, + client_socket_addr: SocketAddr, + response: Response, + opt_req_kind: Option, + req_processing_time: Duration, + ) { tracing::debug!("send response"); let response_type = match &response { @@ -79,7 +86,7 @@ impl Processor { Response::Scrape(_) => statistics::event::UdpResponseKind::Ok { req_kind: statistics::event::UdpRequestKind::Scrape, }, - Response::Error(_e) => statistics::event::UdpResponseKind::Error, + Response::Error(_e) => statistics::event::UdpResponseKind::Error { opt_req_kind: None }, }; let mut writer = Cursor::new(Vec::with_capacity(200)); diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 03bfeae65..75441f7e4 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -80,7 +80,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { .await; } }, - UdpResponseKind::Error => {} + UdpResponseKind::Error { opt_req_kind: _ } => {} } } Event::UdpError { context } => match context.client_socket_addr().ip() { diff --git a/packages/udp-tracker-server/src/statistics/event/mod.rs b/packages/udp-tracker-server/src/statistics/event/mod.rs index 207916846..1516d79c3 100644 --- a/packages/udp-tracker-server/src/statistics/event/mod.rs +++ b/packages/udp-tracker-server/src/statistics/event/mod.rs @@ -6,7 +6,7 @@ pub mod listener; pub mod sender; /// An statistics event. It is used to collect tracker metrics. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { UdpIncomingRequest { context: ConnectionContext, @@ -31,20 +31,27 @@ pub enum Event { }, } -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone)] pub enum UdpRequestKind { Connect, Announce, Scrape, } -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone)] pub enum UdpResponseKind { - Ok { req_kind: UdpRequestKind }, - Error, // todo: add the request kind `{ req_kind: Option(UdpRequestKind) }` when we know it. + Ok { + req_kind: UdpRequestKind, + }, + + /// There was an error handling the requests. The error contains the request + /// kind if the request was parsed successfully. + Error { + opt_req_kind: Option, + }, } -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone)] pub struct ConnectionContext { client_socket_addr: SocketAddr, server_socket_addr: SocketAddr, From 9a8a0dc0e575c127c032649de9e6b9155e1cc329 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Mar 2025 11:46:17 +0000 Subject: [PATCH 0891/1297] refactor: [#1382] rename UDP server event enum variants --- packages/udp-tracker-server/src/server/launcher.rs | 2 +- packages/udp-tracker-server/src/server/processor.rs | 2 +- .../udp-tracker-server/src/statistics/event/handler.rs | 10 +++++----- .../udp-tracker-server/src/statistics/event/mod.rs | 6 +++--- packages/udp-tracker-server/src/statistics/keeper.rs | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index a3da6a2a8..c6a105230 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -173,7 +173,7 @@ impl Launcher { if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(statistics::event::Event::UdpIncomingRequest { + .send_event(statistics::event::Event::UdpRequestReceived { context: ConnectionContext::new(client_socket_addr, server_socket_addr), }) .await; diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs index 59d21673f..4d1e4429a 100644 --- a/packages/udp-tracker-server/src/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -108,7 +108,7 @@ impl Processor { self.udp_tracker_server_container.udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(statistics::event::Event::UdpResponse { + .send_event(statistics::event::Event::UdpResponseSent { context: ConnectionContext::new(client_socket_addr, self.socket.address()), kind: udp_response_kind, req_processing_time, diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 75441f7e4..6abf7d3c7 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -14,7 +14,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { Event::UdpRequestBanned { .. } => { stats_repository.increase_udp_requests_banned().await; } - Event::UdpIncomingRequest { context } => match context.client_socket_addr().ip() { + Event::UdpRequestReceived { context } => match context.client_socket_addr().ip() { std::net::IpAddr::V4(_) => { stats_repository.increase_udp4_requests().await; } @@ -48,7 +48,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { } }, }, - Event::UdpResponse { + Event::UdpResponseSent { context, kind, req_processing_time, @@ -149,7 +149,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::UdpIncomingRequest { + Event::UdpRequestReceived { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -267,7 +267,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::UdpResponse { + Event::UdpResponseSent { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), @@ -374,7 +374,7 @@ mod tests { let stats_repository = Repository::new(); handle_event( - Event::UdpResponse { + Event::UdpResponseSent { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), diff --git a/packages/udp-tracker-server/src/statistics/event/mod.rs b/packages/udp-tracker-server/src/statistics/event/mod.rs index 1516d79c3..1b0be960b 100644 --- a/packages/udp-tracker-server/src/statistics/event/mod.rs +++ b/packages/udp-tracker-server/src/statistics/event/mod.rs @@ -8,7 +8,7 @@ pub mod sender; /// An statistics event. It is used to collect tracker metrics. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { - UdpIncomingRequest { + UdpRequestReceived { context: ConnectionContext, }, UdpRequestAborted { @@ -21,7 +21,7 @@ pub enum Event { context: ConnectionContext, kind: UdpRequestKind, }, - UdpResponse { + UdpResponseSent { context: ConnectionContext, kind: UdpResponseKind, req_processing_time: Duration, @@ -44,7 +44,7 @@ pub enum UdpResponseKind { req_kind: UdpRequestKind, }, - /// There was an error handling the requests. The error contains the request + /// There was an error handling the request. The error contains the request /// kind if the request was parsed successfully. Error { opt_req_kind: Option, diff --git a/packages/udp-tracker-server/src/statistics/keeper.rs b/packages/udp-tracker-server/src/statistics/keeper.rs index c29dcb1b2..4ce832227 100644 --- a/packages/udp-tracker-server/src/statistics/keeper.rs +++ b/packages/udp-tracker-server/src/statistics/keeper.rs @@ -73,7 +73,7 @@ mod tests { let event_sender = stats_tracker.run_event_listener(); let result = event_sender - .send_event(Event::UdpIncomingRequest { + .send_event(Event::UdpRequestReceived { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), From e729a5fb7a53f26c722902e18e66972dad9cd309 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Mar 2025 15:29:32 +0000 Subject: [PATCH 0892/1297] refactor: [#1386] remove dependency on UDP core metrics from API --- .../src/v1/context/stats/handlers.rs | 10 +--------- .../src/v1/context/stats/routes.rs | 1 - .../src/statistics/services.rs | 20 ++++++++----------- 3 files changed, 9 insertions(+), 22 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs index 5273df332..484c12ff9 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs @@ -43,19 +43,11 @@ pub async fn get_stats_handler( Arc, Arc>, Arc, - Arc, Arc, )>, params: Query, ) -> Response { - let metrics = get_metrics( - state.0.clone(), - state.1.clone(), - state.2.clone(), - state.3.clone(), - state.4.clone(), - ) - .await; + let metrics = get_metrics(state.0.clone(), state.1.clone(), state.2.clone(), state.3.clone()).await; match params.0.format { Some(format) => match format { diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs index 1334c0d70..49ba9e829 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs @@ -19,7 +19,6 @@ pub fn add(prefix: &str, router: Router, http_api_container: &Arc, ban_service: Arc>, http_stats_repository: Arc, - udp_core_stats_repository: Arc, udp_server_stats_repository: Arc, ) -> TrackerMetrics { let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); let http_stats = http_stats_repository.get_stats().await; - let udp_core_stats = udp_core_stats_repository.get_stats().await; let udp_server_stats = udp_server_stats_repository.get_stats().await; // For backward compatibility we keep the `tcp4_connections_handled` and @@ -63,16 +61,16 @@ pub async fn get_metrics( udp_avg_scrape_processing_time_ns: udp_server_stats.udp_avg_scrape_processing_time_ns, // UDPv4 udp4_requests: udp_server_stats.udp4_requests, - udp4_connections_handled: udp_core_stats.udp4_connections_handled, - udp4_announces_handled: udp_core_stats.udp4_announces_handled, - udp4_scrapes_handled: udp_core_stats.udp4_scrapes_handled, + udp4_connections_handled: udp_server_stats.udp4_connections_handled, + udp4_announces_handled: udp_server_stats.udp4_announces_handled, + udp4_scrapes_handled: udp_server_stats.udp4_scrapes_handled, udp4_responses: udp_server_stats.udp4_responses, udp4_errors_handled: udp_server_stats.udp4_errors_handled, // UDPv6 udp6_requests: udp_server_stats.udp6_requests, - udp6_connections_handled: udp_core_stats.udp6_connections_handled, - udp6_announces_handled: udp_core_stats.udp6_announces_handled, - udp6_scrapes_handled: udp_core_stats.udp6_scrapes_handled, + udp6_connections_handled: udp_server_stats.udp6_connections_handled, + udp6_announces_handled: udp_server_stats.udp6_announces_handled, + udp6_scrapes_handled: udp_server_stats.udp6_scrapes_handled, udp6_responses: udp_server_stats.udp6_responses, udp6_errors_handled: udp_server_stats.udp6_errors_handled, }, @@ -112,9 +110,8 @@ mod tests { let http_stats_repository = Arc::new(http_stats_repository); // UDP core stats - let (_udp_stats_event_sender, udp_stats_repository) = + let (_udp_stats_event_sender, _udp_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); - let udp_stats_repository = Arc::new(udp_stats_repository); // UDP server stats let (_udp_server_stats_event_sender, udp_server_stats_repository) = @@ -125,7 +122,6 @@ mod tests { in_memory_torrent_repository.clone(), ban_service.clone(), http_stats_repository.clone(), - udp_stats_repository.clone(), udp_server_stats_repository.clone(), ) .await; From 64c7b21fb812fd14e4865de1500a718b8bbd4929 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Mar 2025 16:19:29 +0000 Subject: [PATCH 0893/1297] refactor: [#1388] minor changes to HTTP core events --- .../src/statistics/event/mod.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/event/mod.rs b/packages/http-tracker-core/src/statistics/event/mod.rs index 7520e1a97..2964956d8 100644 --- a/packages/http-tracker-core/src/statistics/event/mod.rs +++ b/packages/http-tracker-core/src/statistics/event/mod.rs @@ -5,13 +5,13 @@ pub mod listener; pub mod sender; /// An statistics event. It is used to collect tracker metrics. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { TcpAnnounce { connection: ConnectionContext }, TcpScrape { connection: ConnectionContext }, } -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone)] pub struct ConnectionContext { client: ClientConnectionContext, server: ServerConnectionContext, @@ -35,9 +35,19 @@ impl ConnectionContext { pub fn client_ip_addr(&self) -> IpAddr { self.client.ip_addr } + + #[must_use] + pub fn client_port(&self) -> Option { + self.client.port + } + + #[must_use] + pub fn server_socket_addr(&self) -> SocketAddr { + self.server.socket_addr + } } -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone)] pub struct ClientConnectionContext { ip_addr: IpAddr, @@ -45,7 +55,7 @@ pub struct ClientConnectionContext { port: Option, } -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone)] pub struct ServerConnectionContext { socket_addr: SocketAddr, } From 5f9c4d3f2a04289055e6ccfc2f530cb82d3f47ea Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 18 Mar 2025 17:04:55 +0000 Subject: [PATCH 0894/1297] refactor: [#1388] change channel in HTTP core from mpsc to broadcast Stats events were introduced to collect tracker metrics. We only have global metrics (aggregate metrics for all UDP and HTTP trackers). This will change in the future. We will have: - Segregated metrics: one listeners per tracker (per socket). - Generic events: there could be other event consumers. Events will be decoupled from stats. This change allows multiple receivers in the channel. For now, we one use one listener but with this change will be easy to add more. --- .../http-tracker-core/benches/helpers/util.rs | 4 +- .../src/services/announce.rs | 10 ++--- .../http-tracker-core/src/services/scrape.rs | 12 +++--- .../src/statistics/event/listener.rs | 14 +++++-- .../src/statistics/event/sender.rs | 12 +++--- .../src/statistics/keeper.rs | 41 +------------------ .../http-tracker-core/src/statistics/setup.rs | 19 +++++++-- 7 files changed, 46 insertions(+), 66 deletions(-) diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 169c4a56a..19010041e 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -108,11 +108,11 @@ pub fn sample_info_hash() -> InfoHash { use bittorrent_http_tracker_core::statistics; use futures::future::BoxFuture; use mockall::mock; -use tokio::sync::mpsc::error::SendError; +use tokio::sync::broadcast::error::SendError; mock! { HttpStatsEventSender {} impl statistics::event::sender::Sender for HttpStatsEventSender { - fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 6b8b700c9..25fc1b861 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -315,7 +315,7 @@ mod tests { use futures::future::BoxFuture; use mockall::mock; - use tokio::sync::mpsc::error::SendError; + use tokio::sync::broadcast::error::SendError; use crate::statistics; use crate::tests::sample_info_hash; @@ -323,7 +323,7 @@ mod tests { mock! { HttpStatsEventSender {} impl statistics::event::sender::Sender for HttpStatsEventSender { - fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } @@ -395,7 +395,7 @@ mod tests { connection: ConnectionContext::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), Some(8080), server_socket_addr), })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); @@ -451,7 +451,7 @@ mod tests { connection: ConnectionContext::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), Some(8080), server_socket_addr), })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); @@ -494,7 +494,7 @@ mod tests { ), })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index ed927efc3..6341ed301 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -203,7 +203,7 @@ mod tests { use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; use mockall::mock; - use tokio::sync::mpsc::error::SendError; + use tokio::sync::broadcast::error::SendError; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; @@ -260,7 +260,7 @@ mod tests { mock! { HttpStatsEventSender {} impl statistics::event::sender::Sender for HttpStatsEventSender { - fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } @@ -359,7 +359,7 @@ mod tests { ), })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); @@ -408,7 +408,7 @@ mod tests { ), })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); @@ -529,7 +529,7 @@ mod tests { ), })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); @@ -578,7 +578,7 @@ mod tests { ), })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); diff --git a/packages/http-tracker-core/src/statistics/event/listener.rs b/packages/http-tracker-core/src/statistics/event/listener.rs index f1a2e25de..a70992a02 100644 --- a/packages/http-tracker-core/src/statistics/event/listener.rs +++ b/packages/http-tracker-core/src/statistics/event/listener.rs @@ -1,11 +1,17 @@ -use tokio::sync::mpsc; +use tokio::sync::broadcast; use super::handler::handle_event; use super::Event; use crate::statistics::repository::Repository; -pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) { - while let Some(event) = receiver.recv().await { - handle_event(event, &stats_repository).await; +pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { + loop { + match receiver.recv().await { + Ok(event) => handle_event(event, &stats_repository).await, + Err(e) => { + tracing::error!("Error receiving http tracker core event: {:?}", e); + break; + } + } } } diff --git a/packages/http-tracker-core/src/statistics/event/sender.rs b/packages/http-tracker-core/src/statistics/event/sender.rs index ca4b4e210..9092a8e0b 100644 --- a/packages/http-tracker-core/src/statistics/event/sender.rs +++ b/packages/http-tracker-core/src/statistics/event/sender.rs @@ -2,15 +2,15 @@ use futures::future::BoxFuture; use futures::FutureExt; #[cfg(test)] use mockall::{automock, predicate::str}; -use tokio::sync::mpsc; -use tokio::sync::mpsc::error::SendError; +use tokio::sync::broadcast; +use tokio::sync::broadcast::error::SendError; use super::Event; /// A trait to allow sending statistics events #[cfg_attr(test, automock)] pub trait Sender: Sync + Send { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; } /// An [`statistics::EventSender`](crate::statistics::event::sender::Sender) implementation. @@ -19,11 +19,11 @@ pub trait Sender: Sync + Send { /// [`statistics::Keeper`](crate::statistics::keeper::Keeper) #[allow(clippy::module_name_repetitions)] pub struct ChannelSender { - pub(crate) sender: mpsc::Sender, + pub(crate) sender: broadcast::Sender, } impl Sender for ChannelSender { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { - async move { Some(self.sender.send(event).await) }.boxed() + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { + async move { Some(self.sender.send(event)) }.boxed() } } diff --git a/packages/http-tracker-core/src/statistics/keeper.rs b/packages/http-tracker-core/src/statistics/keeper.rs index 783309eff..f4428ec70 100644 --- a/packages/http-tracker-core/src/statistics/keeper.rs +++ b/packages/http-tracker-core/src/statistics/keeper.rs @@ -1,12 +1,9 @@ -use tokio::sync::mpsc; +use tokio::sync::broadcast::Receiver; use super::event::listener::dispatch_events; -use super::event::sender::{ChannelSender, Sender}; use super::event::Event; use super::repository::Repository; -const CHANNEL_BUFFER_SIZE: usize = 65_535; - /// The service responsible for keeping tracker metrics (listening to statistics events and handle them). /// /// It actively listen to new statistics events. When it receives a new event @@ -29,31 +26,16 @@ impl Keeper { } } - #[must_use] - pub fn new_active_instance() -> (Box, Repository) { - let mut stats_tracker = Self::new(); - - let stats_event_sender = stats_tracker.run_event_listener(); - - (stats_event_sender, stats_tracker.repository) - } - - pub fn run_event_listener(&mut self) -> Box { - let (sender, receiver) = mpsc::channel::(CHANNEL_BUFFER_SIZE); - + pub fn run_event_listener(&mut self, receiver: Receiver) { let stats_repository = self.repository.clone(); tokio::spawn(async move { dispatch_events(receiver, stats_repository).await }); - - Box::new(ChannelSender { sender }) } } #[cfg(test)] mod tests { - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use crate::statistics::event::{ConnectionContext, Event}; use crate::statistics::keeper::Keeper; use crate::statistics::metrics::Metrics; @@ -65,23 +47,4 @@ mod tests { assert_eq!(stats.tcp4_announces_handled, Metrics::default().tcp4_announces_handled); } - - #[tokio::test] - async fn should_create_an_event_sender_to_send_statistical_events() { - let mut stats_tracker = Keeper::new(); - - let event_sender = stats_tracker.run_event_listener(); - - let result = event_sender - .send_event(Event::TcpAnnounce { - connection: ConnectionContext::new( - IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), - Some(8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), - ), - }) - .await; - - assert!(result.is_some()); - } } diff --git a/packages/http-tracker-core/src/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs index d3114a75e..a9ac751c6 100644 --- a/packages/http-tracker-core/src/statistics/setup.rs +++ b/packages/http-tracker-core/src/statistics/setup.rs @@ -1,8 +1,13 @@ //! Setup for the tracker statistics. //! //! The [`factory`] function builds the structs needed for handling the tracker metrics. +use tokio::sync::broadcast; + +use super::event::sender::ChannelSender; use crate::statistics; +const CHANNEL_CAPACITY: usize = 1024; + /// It builds the structs needed for handling the tracker metrics. /// /// It returns: @@ -19,15 +24,21 @@ pub fn factory( Option>, statistics::repository::Repository, ) { - let mut stats_event_sender = None; + let mut stats_event_sender: Option> = None; - let mut stats_tracker = statistics::keeper::Keeper::new(); + let mut keeper = statistics::keeper::Keeper::new(); if tracker_usage_statistics { - stats_event_sender = Some(stats_tracker.run_event_listener()); + let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); + + let receiver = sender.subscribe(); + + stats_event_sender = Some(Box::new(ChannelSender { sender })); + + keeper.run_event_listener(receiver); } - (stats_event_sender, stats_tracker.repository) + (stats_event_sender, keeper.repository) } #[cfg(test)] From d2de1de84c0fc8469018c10271e4ca2f150631c9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Mar 2025 08:02:58 +0000 Subject: [PATCH 0895/1297] refactor: [#1389] change channel in UDP core from mpsc to broadcast --- .../udp-tracker-core/benches/helpers/utils.rs | 4 +- .../udp-tracker-core/src/services/connect.rs | 4 +- packages/udp-tracker-core/src/services/mod.rs | 4 +- .../src/statistics/event/listener.rs | 14 +++++-- .../src/statistics/event/mod.rs | 4 +- .../src/statistics/event/sender.rs | 12 +++--- .../udp-tracker-core/src/statistics/keeper.rs | 41 +------------------ .../udp-tracker-core/src/statistics/setup.rs | 19 +++++++-- .../src/handlers/announce.rs | 2 +- .../src/handlers/connect.rs | 4 +- .../udp-tracker-server/src/handlers/mod.rs | 7 ++-- 11 files changed, 48 insertions(+), 67 deletions(-) diff --git a/packages/udp-tracker-core/benches/helpers/utils.rs b/packages/udp-tracker-core/benches/helpers/utils.rs index 7fd6d175f..aed4d9542 100644 --- a/packages/udp-tracker-core/benches/helpers/utils.rs +++ b/packages/udp-tracker-core/benches/helpers/utils.rs @@ -3,7 +3,7 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use bittorrent_udp_tracker_core::statistics; use futures::future::BoxFuture; use mockall::mock; -use tokio::sync::mpsc::error::SendError; +use tokio::sync::broadcast::error::SendError; pub(crate) fn sample_ipv4_remote_addr() -> SocketAddr { sample_ipv4_socket_address() @@ -20,6 +20,6 @@ pub(crate) fn sample_issue_time() -> f64 { mock! { pub(crate) UdpCoreStatsEventSender {} impl statistics::event::sender::Sender for UdpCoreStatsEventSender { - fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index c3c2459cd..fb28fe70b 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -142,7 +142,7 @@ mod tests { context: ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let opt_udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); @@ -165,7 +165,7 @@ mod tests { context: ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let opt_udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); diff --git a/packages/udp-tracker-core/src/services/mod.rs b/packages/udp-tracker-core/src/services/mod.rs index 6aa254f41..55a533a22 100644 --- a/packages/udp-tracker-core/src/services/mod.rs +++ b/packages/udp-tracker-core/src/services/mod.rs @@ -10,7 +10,7 @@ pub(crate) mod tests { use futures::future::BoxFuture; use mockall::mock; - use tokio::sync::mpsc::error::SendError; + use tokio::sync::broadcast::error::SendError; use crate::connection_cookie::gen_remote_fingerprint; use crate::statistics; @@ -46,7 +46,7 @@ pub(crate) mod tests { mock! { pub(crate) UdpCoreStatsEventSender {} impl statistics::event::sender::Sender for UdpCoreStatsEventSender { - fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } } diff --git a/packages/udp-tracker-core/src/statistics/event/listener.rs b/packages/udp-tracker-core/src/statistics/event/listener.rs index f1a2e25de..36b1e7a22 100644 --- a/packages/udp-tracker-core/src/statistics/event/listener.rs +++ b/packages/udp-tracker-core/src/statistics/event/listener.rs @@ -1,11 +1,17 @@ -use tokio::sync::mpsc; +use tokio::sync::broadcast; use super::handler::handle_event; use super::Event; use crate::statistics::repository::Repository; -pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) { - while let Some(event) = receiver.recv().await { - handle_event(event, &stats_repository).await; +pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { + loop { + match receiver.recv().await { + Ok(event) => handle_event(event, &stats_repository).await, + Err(e) => { + tracing::error!("Error receiving udp tracker core event: {:?}", e); + break; + } + } } } diff --git a/packages/udp-tracker-core/src/statistics/event/mod.rs b/packages/udp-tracker-core/src/statistics/event/mod.rs index 216562506..2e8ae39a9 100644 --- a/packages/udp-tracker-core/src/statistics/event/mod.rs +++ b/packages/udp-tracker-core/src/statistics/event/mod.rs @@ -8,14 +8,14 @@ pub mod sender; /// /// - `Udp` prefix means the event was triggered by the UDP tracker. /// - The event suffix is the type of request: `announce`, `scrape` or `connection`. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { UdpConnect { context: ConnectionContext }, UdpAnnounce { context: ConnectionContext }, UdpScrape { context: ConnectionContext }, } -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone)] pub struct ConnectionContext { client_socket_addr: SocketAddr, server_socket_addr: SocketAddr, diff --git a/packages/udp-tracker-core/src/statistics/event/sender.rs b/packages/udp-tracker-core/src/statistics/event/sender.rs index ca4b4e210..9092a8e0b 100644 --- a/packages/udp-tracker-core/src/statistics/event/sender.rs +++ b/packages/udp-tracker-core/src/statistics/event/sender.rs @@ -2,15 +2,15 @@ use futures::future::BoxFuture; use futures::FutureExt; #[cfg(test)] use mockall::{automock, predicate::str}; -use tokio::sync::mpsc; -use tokio::sync::mpsc::error::SendError; +use tokio::sync::broadcast; +use tokio::sync::broadcast::error::SendError; use super::Event; /// A trait to allow sending statistics events #[cfg_attr(test, automock)] pub trait Sender: Sync + Send { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; } /// An [`statistics::EventSender`](crate::statistics::event::sender::Sender) implementation. @@ -19,11 +19,11 @@ pub trait Sender: Sync + Send { /// [`statistics::Keeper`](crate::statistics::keeper::Keeper) #[allow(clippy::module_name_repetitions)] pub struct ChannelSender { - pub(crate) sender: mpsc::Sender, + pub(crate) sender: broadcast::Sender, } impl Sender for ChannelSender { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { - async move { Some(self.sender.send(event).await) }.boxed() + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { + async move { Some(self.sender.send(event)) }.boxed() } } diff --git a/packages/udp-tracker-core/src/statistics/keeper.rs b/packages/udp-tracker-core/src/statistics/keeper.rs index e46e634e8..f06642908 100644 --- a/packages/udp-tracker-core/src/statistics/keeper.rs +++ b/packages/udp-tracker-core/src/statistics/keeper.rs @@ -1,12 +1,9 @@ -use tokio::sync::mpsc; +use tokio::sync::broadcast::Receiver; use super::event::listener::dispatch_events; -use super::event::sender::{ChannelSender, Sender}; use super::event::Event; use super::repository::Repository; -const CHANNEL_BUFFER_SIZE: usize = 65_535; - /// The service responsible for keeping tracker metrics (listening to statistics events and handle them). /// /// It actively listen to new statistics events. When it receives a new event @@ -29,31 +26,15 @@ impl Keeper { } } - #[must_use] - pub fn new_active_instance() -> (Box, Repository) { - let mut stats_tracker = Self::new(); - - let stats_event_sender = stats_tracker.run_event_listener(); - - (stats_event_sender, stats_tracker.repository) - } - - pub fn run_event_listener(&mut self) -> Box { - let (sender, receiver) = mpsc::channel::(CHANNEL_BUFFER_SIZE); - + pub fn run_event_listener(&mut self, receiver: Receiver) { let stats_repository = self.repository.clone(); tokio::spawn(async move { dispatch_events(receiver, stats_repository).await }); - - Box::new(ChannelSender { sender }) } } #[cfg(test)] mod tests { - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - - use crate::statistics::event::{ConnectionContext, Event}; use crate::statistics::keeper::Keeper; use crate::statistics::metrics::Metrics; @@ -65,22 +46,4 @@ mod tests { assert_eq!(stats.udp4_announces_handled, Metrics::default().udp4_announces_handled); } - - #[tokio::test] - async fn should_create_an_event_sender_to_send_statistical_events() { - let mut stats_tracker = Keeper::new(); - - let event_sender = stats_tracker.run_event_listener(); - - let result = event_sender - .send_event(Event::UdpConnect { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), - ), - }) - .await; - - assert!(result.is_some()); - } } diff --git a/packages/udp-tracker-core/src/statistics/setup.rs b/packages/udp-tracker-core/src/statistics/setup.rs index d3114a75e..a9ac751c6 100644 --- a/packages/udp-tracker-core/src/statistics/setup.rs +++ b/packages/udp-tracker-core/src/statistics/setup.rs @@ -1,8 +1,13 @@ //! Setup for the tracker statistics. //! //! The [`factory`] function builds the structs needed for handling the tracker metrics. +use tokio::sync::broadcast; + +use super::event::sender::ChannelSender; use crate::statistics; +const CHANNEL_CAPACITY: usize = 1024; + /// It builds the structs needed for handling the tracker metrics. /// /// It returns: @@ -19,15 +24,21 @@ pub fn factory( Option>, statistics::repository::Repository, ) { - let mut stats_event_sender = None; + let mut stats_event_sender: Option> = None; - let mut stats_tracker = statistics::keeper::Keeper::new(); + let mut keeper = statistics::keeper::Keeper::new(); if tracker_usage_statistics { - stats_event_sender = Some(stats_tracker.run_event_listener()); + let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); + + let receiver = sender.subscribe(); + + stats_event_sender = Some(Box::new(ChannelSender { sender })); + + keeper.run_event_listener(receiver); } - (stats_event_sender, stats_tracker.repository) + (stats_event_sender, keeper.repository) } #[cfg(test)] diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 5cc3cf3c8..1988f3d79 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -854,7 +854,7 @@ mod tests { context: core_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let udp_core_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index c38eb56e5..7e96ce37a 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -196,7 +196,7 @@ mod tests { context: core_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let udp_core_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); @@ -237,7 +237,7 @@ mod tests { context: core_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let udp_core_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index e346d1953..771147b4a 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -222,7 +222,8 @@ pub(crate) mod tests { use bittorrent_udp_tracker_core::{self, statistics as core_statistics}; use futures::future::BoxFuture; use mockall::mock; - use tokio::sync::mpsc::error::SendError; + use tokio::sync::broadcast::error::SendError; + use tokio::sync::mpsc::error::SendError as MpscSendError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; @@ -422,14 +423,14 @@ pub(crate) mod tests { mock! { pub(crate) UdpCoreStatsEventSender {} impl core_statistics::event::sender::Sender for UdpCoreStatsEventSender { - fn send_event(&self, event: core_statistics::event::Event) -> BoxFuture<'static,Option > > > ; + fn send_event(&self, event: core_statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } mock! { pub(crate) UdpServerStatsEventSender {} impl server_statistics::event::sender::Sender for UdpServerStatsEventSender { - fn send_event(&self, event: server_statistics::event::Event) -> BoxFuture<'static,Option > > > ; + fn send_event(&self, event: server_statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } } From 37c8f2bc8187197e81b1d7a338e490b739fe438e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Mar 2025 09:03:10 +0000 Subject: [PATCH 0896/1297] refactor: [#1390] change channel in UDP server from mpsc to broadcast --- .../src/handlers/announce.rs | 6 +-- .../src/handlers/connect.rs | 4 +- .../udp-tracker-server/src/handlers/mod.rs | 3 +- .../udp-tracker-server/src/handlers/scrape.rs | 4 +- .../src/statistics/event/listener.rs | 14 +++++-- .../src/statistics/event/sender.rs | 12 +++--- .../src/statistics/keeper.rs | 41 +------------------ .../src/statistics/setup.rs | 19 +++++++-- 8 files changed, 41 insertions(+), 62 deletions(-) diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 1988f3d79..a2cb55e59 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -430,7 +430,7 @@ mod tests { kind: UdpRequestKind::Announce, })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); @@ -773,7 +773,7 @@ mod tests { kind: UdpRequestKind::Announce, })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); @@ -866,7 +866,7 @@ mod tests { kind: UdpRequestKind::Announce, })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 7e96ce37a..992ef459d 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -208,7 +208,7 @@ mod tests { kind: UdpRequestKind::Connect, })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); @@ -249,7 +249,7 @@ mod tests { kind: UdpRequestKind::Connect, })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 771147b4a..e573cc184 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -223,7 +223,6 @@ pub(crate) mod tests { use futures::future::BoxFuture; use mockall::mock; use tokio::sync::broadcast::error::SendError; - use tokio::sync::mpsc::error::SendError as MpscSendError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; @@ -430,7 +429,7 @@ pub(crate) mod tests { mock! { pub(crate) UdpServerStatsEventSender {} impl server_statistics::event::sender::Sender for UdpServerStatsEventSender { - fn send_event(&self, event: server_statistics::event::Event) -> BoxFuture<'static,Option > > > ; + fn send_event(&self, event: server_statistics::event::Event) -> BoxFuture<'static,Option > > > ; } } } diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index db6b4a18b..fbf2b7c43 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -373,7 +373,7 @@ mod tests { kind: server_statistics::event::UdpRequestKind::Scrape, })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); @@ -422,7 +422,7 @@ mod tests { kind: server_statistics::event::UdpRequestKind::Scrape, })) .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(()))))); + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index f1a2e25de..b755cbf18 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -1,11 +1,17 @@ -use tokio::sync::mpsc; +use tokio::sync::broadcast; use super::handler::handle_event; use super::Event; use crate::statistics::repository::Repository; -pub async fn dispatch_events(mut receiver: mpsc::Receiver, stats_repository: Repository) { - while let Some(event) = receiver.recv().await { - handle_event(event, &stats_repository).await; +pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { + loop { + match receiver.recv().await { + Ok(event) => handle_event(event, &stats_repository).await, + Err(e) => { + tracing::error!("Error receiving udp tracker server event: {:?}", e); + break; + } + } } } diff --git a/packages/udp-tracker-server/src/statistics/event/sender.rs b/packages/udp-tracker-server/src/statistics/event/sender.rs index ca4b4e210..9092a8e0b 100644 --- a/packages/udp-tracker-server/src/statistics/event/sender.rs +++ b/packages/udp-tracker-server/src/statistics/event/sender.rs @@ -2,15 +2,15 @@ use futures::future::BoxFuture; use futures::FutureExt; #[cfg(test)] use mockall::{automock, predicate::str}; -use tokio::sync::mpsc; -use tokio::sync::mpsc::error::SendError; +use tokio::sync::broadcast; +use tokio::sync::broadcast::error::SendError; use super::Event; /// A trait to allow sending statistics events #[cfg_attr(test, automock)] pub trait Sender: Sync + Send { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; } /// An [`statistics::EventSender`](crate::statistics::event::sender::Sender) implementation. @@ -19,11 +19,11 @@ pub trait Sender: Sync + Send { /// [`statistics::Keeper`](crate::statistics::keeper::Keeper) #[allow(clippy::module_name_repetitions)] pub struct ChannelSender { - pub(crate) sender: mpsc::Sender, + pub(crate) sender: broadcast::Sender, } impl Sender for ChannelSender { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { - async move { Some(self.sender.send(event).await) }.boxed() + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { + async move { Some(self.sender.send(event)) }.boxed() } } diff --git a/packages/udp-tracker-server/src/statistics/keeper.rs b/packages/udp-tracker-server/src/statistics/keeper.rs index 4ce832227..099e0d0aa 100644 --- a/packages/udp-tracker-server/src/statistics/keeper.rs +++ b/packages/udp-tracker-server/src/statistics/keeper.rs @@ -1,12 +1,9 @@ -use tokio::sync::mpsc; +use tokio::sync::broadcast::Receiver; use super::event::listener::dispatch_events; -use super::event::sender::{ChannelSender, Sender}; use super::event::Event; use super::repository::Repository; -const CHANNEL_BUFFER_SIZE: usize = 65_535; - /// The service responsible for keeping tracker metrics (listening to statistics events and handle them). /// /// It actively listen to new statistics events. When it receives a new event @@ -29,31 +26,15 @@ impl Keeper { } } - #[must_use] - pub fn new_active_instance() -> (Box, Repository) { - let mut stats_tracker = Self::new(); - - let stats_event_sender = stats_tracker.run_event_listener(); - - (stats_event_sender, stats_tracker.repository) - } - - pub fn run_event_listener(&mut self) -> Box { - let (sender, receiver) = mpsc::channel::(CHANNEL_BUFFER_SIZE); - + pub fn run_event_listener(&mut self, receiver: Receiver) { let stats_repository = self.repository.clone(); tokio::spawn(async move { dispatch_events(receiver, stats_repository).await }); - - Box::new(ChannelSender { sender }) } } #[cfg(test)] mod tests { - use std::net::{IpAddr, Ipv6Addr, SocketAddr}; - - use crate::statistics::event::{ConnectionContext, Event}; use crate::statistics::keeper::Keeper; use crate::statistics::metrics::Metrics; @@ -65,22 +46,4 @@ mod tests { assert_eq!(stats.udp4_requests, Metrics::default().udp4_requests); } - - #[tokio::test] - async fn should_create_an_event_sender_to_send_statistical_events() { - let mut stats_tracker = Keeper::new(); - - let event_sender = stats_tracker.run_event_listener(); - - let result = event_sender - .send_event(Event::UdpRequestReceived { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), - ), - }) - .await; - - assert!(result.is_some()); - } } diff --git a/packages/udp-tracker-server/src/statistics/setup.rs b/packages/udp-tracker-server/src/statistics/setup.rs index d3114a75e..a9ac751c6 100644 --- a/packages/udp-tracker-server/src/statistics/setup.rs +++ b/packages/udp-tracker-server/src/statistics/setup.rs @@ -1,8 +1,13 @@ //! Setup for the tracker statistics. //! //! The [`factory`] function builds the structs needed for handling the tracker metrics. +use tokio::sync::broadcast; + +use super::event::sender::ChannelSender; use crate::statistics; +const CHANNEL_CAPACITY: usize = 1024; + /// It builds the structs needed for handling the tracker metrics. /// /// It returns: @@ -19,15 +24,21 @@ pub fn factory( Option>, statistics::repository::Repository, ) { - let mut stats_event_sender = None; + let mut stats_event_sender: Option> = None; - let mut stats_tracker = statistics::keeper::Keeper::new(); + let mut keeper = statistics::keeper::Keeper::new(); if tracker_usage_statistics { - stats_event_sender = Some(stats_tracker.run_event_listener()); + let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); + + let receiver = sender.subscribe(); + + stats_event_sender = Some(Box::new(ChannelSender { sender })); + + keeper.run_event_listener(receiver); } - (stats_event_sender, stats_tracker.repository) + (stats_event_sender, keeper.repository) } #[cfg(test)] From 3d2243b9b032318568ae2dfdd311d2239bacfcc9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Mar 2025 11:57:12 +0000 Subject: [PATCH 0897/1297] refactor: [#1396] extract event module in HTTP core --- .../src/v1/handlers/scrape.rs | 2 +- .../http-tracker-core/benches/helpers/util.rs | 9 +-- packages/http-tracker-core/src/container.rs | 4 +- packages/http-tracker-core/src/event/mod.rs | 59 +++++++++++++++++++ .../src/{statistics => }/event/sender.rs | 7 +-- packages/http-tracker-core/src/lib.rs | 1 + .../src/services/announce.rs | 38 ++++++------ .../http-tracker-core/src/services/scrape.rs | 40 ++++++------- .../src/statistics/event/handler.rs | 4 +- .../src/statistics/event/listener.rs | 2 +- .../src/statistics/event/mod.rs | 59 ------------------- .../src/statistics/keeper.rs | 2 +- .../http-tracker-core/src/statistics/setup.rs | 13 ++-- src/container.rs | 2 +- 14 files changed, 119 insertions(+), 123 deletions(-) create mode 100644 packages/http-tracker-core/src/event/mod.rs rename packages/http-tracker-core/src/{statistics => }/event/sender.rs (70%) diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index 1ba89eaaf..e9544c983 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -103,7 +103,7 @@ mod tests { } struct CoreHttpTrackerServices { - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, } fn initialize_private_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) { diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 19010041e..dff516063 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -26,7 +26,7 @@ pub struct CoreTrackerServices { } pub struct CoreHttpTrackerServices { - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, } pub fn initialize_core_tracker_services() -> (CoreTrackerServices, CoreHttpTrackerServices) { @@ -105,14 +105,15 @@ pub fn sample_info_hash() -> InfoHash { .expect("String should be a valid info hash") } -use bittorrent_http_tracker_core::statistics; +use bittorrent_http_tracker_core::event::Event; +use bittorrent_http_tracker_core::{event, statistics}; use futures::future::BoxFuture; use mockall::mock; use tokio::sync::broadcast::error::SendError; mock! { HttpStatsEventSender {} - impl statistics::event::sender::Sender for HttpStatsEventSender { - fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + impl event::sender::Sender for HttpStatsEventSender { + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 448dce246..bb9b5014c 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -9,7 +9,7 @@ use torrust_tracker_configuration::{Core, HttpTracker}; use crate::services::announce::AnnounceService; use crate::services::scrape::ScrapeService; -use crate::statistics; +use crate::{event, statistics}; pub struct HttpTrackerCoreContainer { // todo: replace with TrackerCoreContainer @@ -20,7 +20,7 @@ pub struct HttpTrackerCoreContainer { pub authentication_service: Arc, pub http_tracker_config: Arc, - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, pub announce_service: Arc, pub scrape_service: Arc, diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs new file mode 100644 index 000000000..da824c240 --- /dev/null +++ b/packages/http-tracker-core/src/event/mod.rs @@ -0,0 +1,59 @@ +use std::net::{IpAddr, SocketAddr}; + +pub mod sender; + +/// An event. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum Event { + TcpAnnounce { connection: ConnectionContext }, + TcpScrape { connection: ConnectionContext }, +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct ConnectionContext { + client: ClientConnectionContext, + server: ServerConnectionContext, +} + +impl ConnectionContext { + #[must_use] + pub fn new(client_ip_addr: IpAddr, opt_client_port: Option, server_socket_addr: SocketAddr) -> Self { + Self { + client: ClientConnectionContext { + ip_addr: client_ip_addr, + port: opt_client_port, + }, + server: ServerConnectionContext { + socket_addr: server_socket_addr, + }, + } + } + + #[must_use] + pub fn client_ip_addr(&self) -> IpAddr { + self.client.ip_addr + } + + #[must_use] + pub fn client_port(&self) -> Option { + self.client.port + } + + #[must_use] + pub fn server_socket_addr(&self) -> SocketAddr { + self.server.socket_addr + } +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct ClientConnectionContext { + ip_addr: IpAddr, + + /// It's provided if you use the `torrust-axum-http-tracker-server` crate. + port: Option, +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct ServerConnectionContext { + socket_addr: SocketAddr, +} diff --git a/packages/http-tracker-core/src/statistics/event/sender.rs b/packages/http-tracker-core/src/event/sender.rs similarity index 70% rename from packages/http-tracker-core/src/statistics/event/sender.rs rename to packages/http-tracker-core/src/event/sender.rs index 9092a8e0b..59ab4496b 100644 --- a/packages/http-tracker-core/src/statistics/event/sender.rs +++ b/packages/http-tracker-core/src/event/sender.rs @@ -7,16 +7,13 @@ use tokio::sync::broadcast::error::SendError; use super::Event; -/// A trait to allow sending statistics events +/// A trait to allow sending events. #[cfg_attr(test, automock)] pub trait Sender: Sync + Send { fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; } -/// An [`statistics::EventSender`](crate::statistics::event::sender::Sender) implementation. -/// -/// It uses a channel sender to send the statistic events. The channel is created by a -/// [`statistics::Keeper`](crate::statistics::keeper::Keeper) +/// An event sender implementation using a broadcast channel. #[allow(clippy::module_name_repetitions)] pub struct ChannelSender { pub(crate) sender: broadcast::Sender, diff --git a/packages/http-tracker-core/src/lib.rs b/packages/http-tracker-core/src/lib.rs index b42b99f8e..0b0b3ba78 100644 --- a/packages/http-tracker-core/src/lib.rs +++ b/packages/http-tracker-core/src/lib.rs @@ -1,4 +1,5 @@ pub mod container; +pub mod event; pub mod services; pub mod statistics; diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 25fc1b861..cd7417e98 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -5,7 +5,7 @@ //! It delegates the `announce` logic to the [`AnnounceHandler`] and it returns //! the [`AnnounceData`]. //! -//! It also sends an [`http_tracker_core::statistics::event::Event`] +//! It also sends an [`http_tracker_core::event::Event`] //! because events are specific for the HTTP tracker. use std::net::{IpAddr, SocketAddr}; use std::panic::Location; @@ -22,7 +22,8 @@ use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; -use crate::statistics; +use crate::event; +use crate::event::Event; /// The HTTP tracker `announce` service. /// @@ -35,7 +36,7 @@ pub struct AnnounceService { announce_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, - opt_http_stats_event_sender: Arc>>, + opt_http_stats_event_sender: Arc>>, } impl AnnounceService { @@ -45,7 +46,7 @@ impl AnnounceService { announce_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, - opt_http_stats_event_sender: Arc>>, + opt_http_stats_event_sender: Arc>>, ) -> Self { Self { core_config, @@ -140,8 +141,8 @@ impl AnnounceService { async fn send_stats_event(&self, peer_ip: IpAddr, opt_peer_ip_port: Option, server_socket_addr: SocketAddr) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { http_stats_event_sender - .send_event(statistics::event::Event::TcpAnnounce { - connection: statistics::event::ConnectionContext::new(peer_ip, opt_peer_ip_port, server_socket_addr), + .send_event(Event::TcpAnnounce { + connection: event::ConnectionContext::new(peer_ip, opt_peer_ip_port, server_socket_addr), }) .await; } @@ -227,7 +228,7 @@ mod tests { } struct CoreHttpTrackerServices { - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, } fn initialize_core_tracker_services() -> (CoreTrackerServices, CoreHttpTrackerServices) { @@ -317,13 +318,14 @@ mod tests { use mockall::mock; use tokio::sync::broadcast::error::SendError; - use crate::statistics; + use crate::event::Event; use crate::tests::sample_info_hash; + use crate::{event, statistics}; mock! { HttpStatsEventSender {} - impl statistics::event::sender::Sender for HttpStatsEventSender { - fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + impl event::sender::Sender for HttpStatsEventSender { + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } @@ -340,13 +342,13 @@ mod tests { use torrust_tracker_test_helpers::configuration; use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; + use crate::event; + use crate::event::{ConnectionContext, Event}; use crate::services::announce::tests::{ initialize_core_tracker_services, initialize_core_tracker_services_with_config, sample_announce_request_for_peer, sample_peer, MockHttpStatsEventSender, }; use crate::services::announce::AnnounceService; - use crate::statistics; - use crate::statistics::event::ConnectionContext; #[tokio::test] async fn it_should_return_the_announce_data() { @@ -391,12 +393,12 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::TcpAnnounce { + .with(eq(Event::TcpAnnounce { connection: ConnectionContext::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), Some(8080), server_socket_addr), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services(); @@ -447,12 +449,12 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::TcpAnnounce { + .with(eq(Event::TcpAnnounce { connection: ConnectionContext::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), Some(8080), server_socket_addr), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let (core_tracker_services, mut core_http_tracker_services) = @@ -486,7 +488,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::TcpAnnounce { + .with(eq(Event::TcpAnnounce { connection: ConnectionContext::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), Some(8080), @@ -495,7 +497,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services(); diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 6341ed301..1f4c14b5a 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -19,8 +19,8 @@ use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; -use crate::statistics; -use crate::statistics::event::ConnectionContext; +use crate::event; +use crate::event::{ConnectionContext, Event}; /// The HTTP tracker `scrape` service. /// @@ -38,7 +38,7 @@ pub struct ScrapeService { core_config: Arc, scrape_handler: Arc, authentication_service: Arc, - opt_http_stats_event_sender: Arc>>, + opt_http_stats_event_sender: Arc>>, } impl ScrapeService { @@ -47,7 +47,7 @@ impl ScrapeService { core_config: Arc, scrape_handler: Arc, authentication_service: Arc, - opt_http_stats_event_sender: Arc>>, + opt_http_stats_event_sender: Arc>>, ) -> Self { Self { core_config, @@ -126,7 +126,7 @@ impl ScrapeService { ) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { http_stats_event_sender - .send_event(statistics::event::Event::TcpScrape { + .send_event(Event::TcpScrape { connection: ConnectionContext::new(original_peer_ip, opt_original_peer_port, server_socket_addr), }) .await; @@ -207,7 +207,7 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; - use crate::statistics; + use crate::event::{self, Event}; use crate::tests::sample_info_hash; struct Container { @@ -259,8 +259,8 @@ mod tests { mock! { HttpStatsEventSender {} - impl statistics::event::sender::Sender for HttpStatsEventSender { - fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + impl event::sender::Sender for HttpStatsEventSender { + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } @@ -278,13 +278,13 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; + use crate::event::{ConnectionContext, Event}; use crate::services::scrape::tests::{ initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::services::scrape::ScrapeService; - use crate::statistics; - use crate::statistics::event::ConnectionContext; use crate::tests::sample_info_hash; + use crate::{event, statistics}; #[tokio::test] async fn it_should_return_the_scrape_data_for_a_torrent() { @@ -351,7 +351,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::TcpScrape { + .with(eq(Event::TcpScrape { connection: ConnectionContext::new( IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), Some(8080), @@ -360,7 +360,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let container = initialize_services_with_configuration(&config); @@ -400,7 +400,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::TcpScrape { + .with(eq(Event::TcpScrape { connection: ConnectionContext::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), Some(8080), @@ -409,7 +409,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let container = initialize_services_with_configuration(&config); @@ -454,13 +454,13 @@ mod tests { use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_test_helpers::configuration; + use crate::event::{ConnectionContext, Event}; use crate::services::scrape::tests::{ initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::services::scrape::ScrapeService; - use crate::statistics; - use crate::statistics::event::ConnectionContext; use crate::tests::sample_info_hash; + use crate::{event, statistics}; #[tokio::test] async fn it_should_return_the_zeroed_scrape_data_when_the_tracker_is_running_in_private_mode_and_the_peer_is_not_authenticated( @@ -521,7 +521,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::TcpScrape { + .with(eq(Event::TcpScrape { connection: ConnectionContext::new( IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), Some(8080), @@ -530,7 +530,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); @@ -570,7 +570,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::TcpScrape { + .with(eq(Event::TcpScrape { connection: ConnectionContext::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), Some(8080), @@ -579,7 +579,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index b8806b9d2..700e39476 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -1,6 +1,6 @@ use std::net::IpAddr; -use crate::statistics::event::Event; +use crate::event::Event; use crate::statistics::repository::Repository; /// # Panics @@ -34,8 +34,8 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use crate::event::{ConnectionContext, Event}; use crate::statistics::event::handler::handle_event; - use crate::statistics::event::{ConnectionContext, Event}; use crate::statistics::repository::Repository; #[tokio::test] diff --git a/packages/http-tracker-core/src/statistics/event/listener.rs b/packages/http-tracker-core/src/statistics/event/listener.rs index a70992a02..a03a56a21 100644 --- a/packages/http-tracker-core/src/statistics/event/listener.rs +++ b/packages/http-tracker-core/src/statistics/event/listener.rs @@ -1,7 +1,7 @@ use tokio::sync::broadcast; use super::handler::handle_event; -use super::Event; +use crate::event::Event; use crate::statistics::repository::Repository; pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { diff --git a/packages/http-tracker-core/src/statistics/event/mod.rs b/packages/http-tracker-core/src/statistics/event/mod.rs index 2964956d8..dae683398 100644 --- a/packages/http-tracker-core/src/statistics/event/mod.rs +++ b/packages/http-tracker-core/src/statistics/event/mod.rs @@ -1,61 +1,2 @@ -use std::net::{IpAddr, SocketAddr}; - pub mod handler; pub mod listener; -pub mod sender; - -/// An statistics event. It is used to collect tracker metrics. -#[derive(Debug, PartialEq, Eq, Clone)] -pub enum Event { - TcpAnnounce { connection: ConnectionContext }, - TcpScrape { connection: ConnectionContext }, -} - -#[derive(Debug, PartialEq, Eq, Clone)] -pub struct ConnectionContext { - client: ClientConnectionContext, - server: ServerConnectionContext, -} - -impl ConnectionContext { - #[must_use] - pub fn new(client_ip_addr: IpAddr, opt_client_port: Option, server_socket_addr: SocketAddr) -> Self { - Self { - client: ClientConnectionContext { - ip_addr: client_ip_addr, - port: opt_client_port, - }, - server: ServerConnectionContext { - socket_addr: server_socket_addr, - }, - } - } - - #[must_use] - pub fn client_ip_addr(&self) -> IpAddr { - self.client.ip_addr - } - - #[must_use] - pub fn client_port(&self) -> Option { - self.client.port - } - - #[must_use] - pub fn server_socket_addr(&self) -> SocketAddr { - self.server.socket_addr - } -} - -#[derive(Debug, PartialEq, Eq, Clone)] -pub struct ClientConnectionContext { - ip_addr: IpAddr, - - /// It's provided if you use the `torrust-axum-http-tracker-server` crate. - port: Option, -} - -#[derive(Debug, PartialEq, Eq, Clone)] -pub struct ServerConnectionContext { - socket_addr: SocketAddr, -} diff --git a/packages/http-tracker-core/src/statistics/keeper.rs b/packages/http-tracker-core/src/statistics/keeper.rs index f4428ec70..01a7a1569 100644 --- a/packages/http-tracker-core/src/statistics/keeper.rs +++ b/packages/http-tracker-core/src/statistics/keeper.rs @@ -1,8 +1,8 @@ use tokio::sync::broadcast::Receiver; use super::event::listener::dispatch_events; -use super::event::Event; use super::repository::Repository; +use crate::event::Event; /// The service responsible for keeping tracker metrics (listening to statistics events and handle them). /// diff --git a/packages/http-tracker-core/src/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs index a9ac751c6..ca31e5d52 100644 --- a/packages/http-tracker-core/src/statistics/setup.rs +++ b/packages/http-tracker-core/src/statistics/setup.rs @@ -3,8 +3,8 @@ //! The [`factory`] function builds the structs needed for handling the tracker metrics. use tokio::sync::broadcast; -use super::event::sender::ChannelSender; -use crate::statistics; +use crate::event::sender::ChannelSender; +use crate::{event, statistics}; const CHANNEL_CAPACITY: usize = 1024; @@ -18,13 +18,8 @@ const CHANNEL_CAPACITY: usize = 1024; /// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics /// events are sent are received but not dispatched to the handler. #[must_use] -pub fn factory( - tracker_usage_statistics: bool, -) -> ( - Option>, - statistics::repository::Repository, -) { - let mut stats_event_sender: Option> = None; +pub fn factory(tracker_usage_statistics: bool) -> (Option>, statistics::repository::Repository) { + let mut stats_event_sender: Option> = None; let mut keeper = statistics::keeper::Keeper::new(); diff --git a/src/container.rs b/src/container.rs index 07c30d604..1c8c9c1d3 100644 --- a/src/container.rs +++ b/src/container.rs @@ -60,7 +60,7 @@ pub struct AppContainer { pub udp_scrape_service: Arc, // HTTP Tracker Core Services - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, pub http_announce_service: Arc, pub http_scrape_service: Arc, From 7e364d14ca468105054e42a92b19719209c63e38 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Mar 2025 16:18:17 +0000 Subject: [PATCH 0898/1297] refactor: [#1396] move event channel creation to events mod in HTTP tracker core --- .../http-tracker-core/src/event/sender.rs | 23 +++++++++--- .../http-tracker-core/src/statistics/setup.rs | 35 +++++++++---------- 2 files changed, 35 insertions(+), 23 deletions(-) diff --git a/packages/http-tracker-core/src/event/sender.rs b/packages/http-tracker-core/src/event/sender.rs index 59ab4496b..e9431abf2 100644 --- a/packages/http-tracker-core/src/event/sender.rs +++ b/packages/http-tracker-core/src/event/sender.rs @@ -7,20 +7,35 @@ use tokio::sync::broadcast::error::SendError; use super::Event; -/// A trait to allow sending events. +const CHANNEL_CAPACITY: usize = 1024; + +/// A trait for sending sending. #[cfg_attr(test, automock)] pub trait Sender: Sync + Send { fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; } /// An event sender implementation using a broadcast channel. -#[allow(clippy::module_name_repetitions)] -pub struct ChannelSender { +pub struct Broadcaster { pub(crate) sender: broadcast::Sender, } -impl Sender for ChannelSender { +impl Sender for Broadcaster { fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { async move { Some(self.sender.send(event)) }.boxed() } } + +impl Default for Broadcaster { + fn default() -> Self { + let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); + Self { sender } + } +} + +impl Broadcaster { + #[must_use] + pub fn subscribe(&self) -> broadcast::Receiver { + self.sender.subscribe() + } +} diff --git a/packages/http-tracker-core/src/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs index ca31e5d52..e2974e4c0 100644 --- a/packages/http-tracker-core/src/statistics/setup.rs +++ b/packages/http-tracker-core/src/statistics/setup.rs @@ -1,39 +1,36 @@ //! Setup for the tracker statistics. //! //! The [`factory`] function builds the structs needed for handling the tracker metrics. -use tokio::sync::broadcast; - -use crate::event::sender::ChannelSender; +use crate::event::sender::Broadcaster; use crate::{event, statistics}; -const CHANNEL_CAPACITY: usize = 1024; - /// It builds the structs needed for handling the tracker metrics. /// /// It returns: /// -/// - An statistics event [`Sender`](crate::statistics::event::sender::Sender) that allows you to send events related to statistics. -/// - An statistics [`Repository`](crate::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. +/// - An event [`Sender`](crate::event::sender::Sender) that allows you to send +/// events related to statistics. +/// - An statistics [`Repository`](crate::statistics::repository::Repository) +/// which is an in-memory repository for the tracker metrics. /// -/// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics -/// events are sent are received but not dispatched to the handler. +/// When the input argument `tracker_usage_statistics`is false the setup does +/// not run the event listeners, consequently the statistics events are sent are +/// received but not dispatched to the handler. #[must_use] pub fn factory(tracker_usage_statistics: bool) -> (Option>, statistics::repository::Repository) { - let mut stats_event_sender: Option> = None; - let mut keeper = statistics::keeper::Keeper::new(); - if tracker_usage_statistics { - let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); + let opt_event_sender: Option> = if tracker_usage_statistics { + let broadcaster = Broadcaster::default(); - let receiver = sender.subscribe(); + keeper.run_event_listener(broadcaster.subscribe()); - stats_event_sender = Some(Box::new(ChannelSender { sender })); - - keeper.run_event_listener(receiver); - } + Some(Box::new(broadcaster)) + } else { + None + }; - (stats_event_sender, keeper.repository) + (opt_event_sender, keeper.repository) } #[cfg(test)] From ed9383610337492ca3d6f7f7c499fd4ba735cbc6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Mar 2025 16:44:43 +0000 Subject: [PATCH 0899/1297] refactor: [#1397] extract event module in UDP core --- .../udp-tracker-core/benches/helpers/utils.rs | 7 +-- packages/udp-tracker-core/src/container.rs | 4 +- packages/udp-tracker-core/src/event/mod.rs | 40 +++++++++++++++++ .../src/{statistics => }/event/sender.rs | 28 ++++++++---- packages/udp-tracker-core/src/lib.rs | 1 + .../udp-tracker-core/src/services/announce.rs | 9 ++-- .../udp-tracker-core/src/services/connect.rs | 21 +++++---- packages/udp-tracker-core/src/services/mod.rs | 7 +-- .../udp-tracker-core/src/services/scrape.rs | 9 ++-- .../src/statistics/event/handler.rs | 4 +- .../src/statistics/event/listener.rs | 2 +- .../src/statistics/event/mod.rs | 40 ----------------- .../udp-tracker-core/src/statistics/keeper.rs | 2 +- .../src/statistics/services.rs | 2 +- .../udp-tracker-core/src/statistics/setup.rs | 44 ++++++++----------- .../src/handlers/announce.rs | 8 ++-- .../src/handlers/connect.rs | 14 +++--- .../udp-tracker-server/src/handlers/mod.rs | 6 +-- src/container.rs | 2 +- 19 files changed, 127 insertions(+), 123 deletions(-) create mode 100644 packages/udp-tracker-core/src/event/mod.rs rename packages/udp-tracker-core/src/{statistics => }/event/sender.rs (54%) diff --git a/packages/udp-tracker-core/benches/helpers/utils.rs b/packages/udp-tracker-core/benches/helpers/utils.rs index aed4d9542..f6c2f6fad 100644 --- a/packages/udp-tracker-core/benches/helpers/utils.rs +++ b/packages/udp-tracker-core/benches/helpers/utils.rs @@ -1,6 +1,7 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use bittorrent_udp_tracker_core::statistics; +use bittorrent_udp_tracker_core::event; +use bittorrent_udp_tracker_core::event::Event; use futures::future::BoxFuture; use mockall::mock; use tokio::sync::broadcast::error::SendError; @@ -19,7 +20,7 @@ pub(crate) fn sample_issue_time() -> f64 { mock! { pub(crate) UdpCoreStatsEventSender {} - impl statistics::event::sender::Sender for UdpCoreStatsEventSender { - fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + impl event::sender::Sender for UdpCoreStatsEventSender { + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index c4cce3dc1..aaa07f150 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -11,7 +11,7 @@ use crate::services::announce::AnnounceService; use crate::services::banning::BanService; use crate::services::connect::ConnectService; use crate::services::scrape::ScrapeService; -use crate::{statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; +use crate::{event, statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; pub struct UdpTrackerCoreContainer { // todo: replace with TrackerCoreContainer @@ -21,7 +21,7 @@ pub struct UdpTrackerCoreContainer { pub whitelist_authorization: Arc, pub udp_tracker_config: Arc, - pub udp_core_stats_event_sender: Arc>>, + pub udp_core_stats_event_sender: Arc>>, pub udp_core_stats_repository: Arc, pub ban_service: Arc>, pub connect_service: Arc, diff --git a/packages/udp-tracker-core/src/event/mod.rs b/packages/udp-tracker-core/src/event/mod.rs new file mode 100644 index 000000000..48a5b501b --- /dev/null +++ b/packages/udp-tracker-core/src/event/mod.rs @@ -0,0 +1,40 @@ +use std::net::SocketAddr; + +pub mod sender; + +/// An statistics event. It is used to collect tracker metrics. +/// +/// - `Udp` prefix means the event was triggered by the UDP tracker. +/// - The event suffix is the type of request: `announce`, `scrape` or `connection`. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum Event { + UdpConnect { context: ConnectionContext }, + UdpAnnounce { context: ConnectionContext }, + UdpScrape { context: ConnectionContext }, +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct ConnectionContext { + pub client_socket_addr: SocketAddr, + pub server_socket_addr: SocketAddr, +} + +impl ConnectionContext { + #[must_use] + pub fn new(client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) -> Self { + Self { + client_socket_addr, + server_socket_addr, + } + } + + #[must_use] + pub fn client_socket_addr(&self) -> SocketAddr { + self.client_socket_addr + } + + #[must_use] + pub fn server_socket_addr(&self) -> SocketAddr { + self.server_socket_addr + } +} diff --git a/packages/udp-tracker-core/src/statistics/event/sender.rs b/packages/udp-tracker-core/src/event/sender.rs similarity index 54% rename from packages/udp-tracker-core/src/statistics/event/sender.rs rename to packages/udp-tracker-core/src/event/sender.rs index 9092a8e0b..e9431abf2 100644 --- a/packages/udp-tracker-core/src/statistics/event/sender.rs +++ b/packages/udp-tracker-core/src/event/sender.rs @@ -7,23 +7,35 @@ use tokio::sync::broadcast::error::SendError; use super::Event; -/// A trait to allow sending statistics events +const CHANNEL_CAPACITY: usize = 1024; + +/// A trait for sending sending. #[cfg_attr(test, automock)] pub trait Sender: Sync + Send { fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; } -/// An [`statistics::EventSender`](crate::statistics::event::sender::Sender) implementation. -/// -/// It uses a channel sender to send the statistic events. The channel is created by a -/// [`statistics::Keeper`](crate::statistics::keeper::Keeper) -#[allow(clippy::module_name_repetitions)] -pub struct ChannelSender { +/// An event sender implementation using a broadcast channel. +pub struct Broadcaster { pub(crate) sender: broadcast::Sender, } -impl Sender for ChannelSender { +impl Sender for Broadcaster { fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { async move { Some(self.sender.send(event)) }.boxed() } } + +impl Default for Broadcaster { + fn default() -> Self { + let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); + Self { sender } + } +} + +impl Broadcaster { + #[must_use] + pub fn subscribe(&self) -> broadcast::Receiver { + self.sender.subscribe() + } +} diff --git a/packages/udp-tracker-core/src/lib.rs b/packages/udp-tracker-core/src/lib.rs index 5aa714d35..94ce93068 100644 --- a/packages/udp-tracker-core/src/lib.rs +++ b/packages/udp-tracker-core/src/lib.rs @@ -1,6 +1,7 @@ pub mod connection_cookie; pub mod container; pub mod crypto; +pub mod event; pub mod services; pub mod statistics; diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index f745a90fd..bba9b51fc 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -20,8 +20,7 @@ use bittorrent_udp_tracker_protocol::peer_builder; use torrust_tracker_primitives::core::AnnounceData; use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; -use crate::statistics; -use crate::statistics::event::ConnectionContext; +use crate::event::{self, ConnectionContext, Event}; /// The `AnnounceService` is responsible for handling the `announce` requests. /// @@ -31,7 +30,7 @@ use crate::statistics::event::ConnectionContext; pub struct AnnounceService { announce_handler: Arc, whitelist_authorization: Arc, - opt_udp_core_stats_event_sender: Arc>>, + opt_udp_core_stats_event_sender: Arc>>, } impl AnnounceService { @@ -39,7 +38,7 @@ impl AnnounceService { pub fn new( announce_handler: Arc, whitelist_authorization: Arc, - opt_udp_core_stats_event_sender: Arc>>, + opt_udp_core_stats_event_sender: Arc>>, ) -> Self { Self { announce_handler, @@ -104,7 +103,7 @@ impl AnnounceService { async fn send_stats_event(&self, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) { if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { udp_stats_event_sender - .send_event(statistics::event::Event::UdpAnnounce { + .send_event(Event::UdpAnnounce { context: ConnectionContext::new(client_socket_addr, server_socket_addr), }) .await; diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index fb28fe70b..e543fbb1e 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -7,20 +7,19 @@ use std::sync::Arc; use aquatic_udp_protocol::ConnectionId; use crate::connection_cookie::{gen_remote_fingerprint, make}; -use crate::statistics; -use crate::statistics::event::ConnectionContext; +use crate::event::{self, ConnectionContext, Event}; /// The `ConnectService` is responsible for handling the `connect` requests. /// /// It is responsible for generating the connection cookie and sending the /// appropriate statistics events. pub struct ConnectService { - pub opt_udp_core_stats_event_sender: Arc>>, + pub opt_udp_core_stats_event_sender: Arc>>, } impl ConnectService { #[must_use] - pub fn new(opt_udp_core_stats_event_sender: Arc>>) -> Self { + pub fn new(opt_udp_core_stats_event_sender: Arc>>) -> Self { Self { opt_udp_core_stats_event_sender, } @@ -42,7 +41,7 @@ impl ConnectService { if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { udp_stats_event_sender - .send_event(statistics::event::Event::UdpConnect { + .send_event(Event::UdpConnect { context: ConnectionContext::new(client_socket_addr, server_socket_addr), }) .await; @@ -64,13 +63,13 @@ mod tests { use mockall::predicate::eq; use crate::connection_cookie::make; + use crate::event::{ConnectionContext, Event}; use crate::services::connect::ConnectService; use crate::services::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpCoreStatsEventSender, }; - use crate::statistics; - use crate::statistics::event::ConnectionContext; + use crate::{event, statistics}; #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { @@ -138,12 +137,12 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::UdpConnect { + .with(eq(Event::UdpConnect { context: ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let opt_udp_stats_event_sender: Arc>> = + let opt_udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); let connect_service = Arc::new(ConnectService::new(opt_udp_stats_event_sender)); @@ -161,12 +160,12 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() - .with(eq(statistics::event::Event::UdpConnect { + .with(eq(Event::UdpConnect { context: ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let opt_udp_stats_event_sender: Arc>> = + let opt_udp_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); let connect_service = Arc::new(ConnectService::new(opt_udp_stats_event_sender)); diff --git a/packages/udp-tracker-core/src/services/mod.rs b/packages/udp-tracker-core/src/services/mod.rs index 55a533a22..ac82d71e8 100644 --- a/packages/udp-tracker-core/src/services/mod.rs +++ b/packages/udp-tracker-core/src/services/mod.rs @@ -13,7 +13,8 @@ pub(crate) mod tests { use tokio::sync::broadcast::error::SendError; use crate::connection_cookie::gen_remote_fingerprint; - use crate::statistics; + use crate::event; + use crate::event::Event; pub(crate) fn sample_ipv4_remote_addr() -> SocketAddr { sample_ipv4_socket_address() @@ -45,8 +46,8 @@ pub(crate) mod tests { mock! { pub(crate) UdpCoreStatsEventSender {} - impl statistics::event::sender::Sender for UdpCoreStatsEventSender { - fn send_event(&self, event: statistics::event::Event) -> BoxFuture<'static,Option > > > ; + impl event::sender::Sender for UdpCoreStatsEventSender { + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } } diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index 446c1182f..9f0941c2a 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -18,8 +18,7 @@ use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_primitives::core::ScrapeData; use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; -use crate::statistics; -use crate::statistics::event::ConnectionContext; +use crate::event::{self, ConnectionContext, Event}; /// The `ScrapeService` is responsible for handling the `scrape` requests. /// @@ -28,14 +27,14 @@ use crate::statistics::event::ConnectionContext; /// - The number of UDP `scrape` requests handled by the UDP tracker. pub struct ScrapeService { scrape_handler: Arc, - opt_udp_stats_event_sender: Arc>>, + opt_udp_stats_event_sender: Arc>>, } impl ScrapeService { #[must_use] pub fn new( scrape_handler: Arc, - opt_udp_stats_event_sender: Arc>>, + opt_udp_stats_event_sender: Arc>>, ) -> Self { Self { scrape_handler, @@ -86,7 +85,7 @@ impl ScrapeService { async fn send_stats_event(&self, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) { if let Some(udp_stats_event_sender) = self.opt_udp_stats_event_sender.as_deref() { udp_stats_event_sender - .send_event(statistics::event::Event::UdpScrape { + .send_event(Event::UdpScrape { context: ConnectionContext::new(client_socket_addr, server_socket_addr), }) .await; diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index 98860592f..a9ac0dade 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -1,4 +1,4 @@ -use crate::statistics::event::Event; +use crate::event::Event; use crate::statistics::repository::Repository; /// # Panics @@ -39,8 +39,8 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use crate::event::{ConnectionContext, Event}; use crate::statistics::event::handler::handle_event; - use crate::statistics::event::{ConnectionContext, Event}; use crate::statistics::repository::Repository; #[tokio::test] diff --git a/packages/udp-tracker-core/src/statistics/event/listener.rs b/packages/udp-tracker-core/src/statistics/event/listener.rs index 36b1e7a22..f3afafc4f 100644 --- a/packages/udp-tracker-core/src/statistics/event/listener.rs +++ b/packages/udp-tracker-core/src/statistics/event/listener.rs @@ -1,7 +1,7 @@ use tokio::sync::broadcast; use super::handler::handle_event; -use super::Event; +use crate::event::Event; use crate::statistics::repository::Repository; pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { diff --git a/packages/udp-tracker-core/src/statistics/event/mod.rs b/packages/udp-tracker-core/src/statistics/event/mod.rs index 2e8ae39a9..dae683398 100644 --- a/packages/udp-tracker-core/src/statistics/event/mod.rs +++ b/packages/udp-tracker-core/src/statistics/event/mod.rs @@ -1,42 +1,2 @@ -use std::net::SocketAddr; - pub mod handler; pub mod listener; -pub mod sender; - -/// An statistics event. It is used to collect tracker metrics. -/// -/// - `Udp` prefix means the event was triggered by the UDP tracker. -/// - The event suffix is the type of request: `announce`, `scrape` or `connection`. -#[derive(Debug, PartialEq, Eq, Clone)] -pub enum Event { - UdpConnect { context: ConnectionContext }, - UdpAnnounce { context: ConnectionContext }, - UdpScrape { context: ConnectionContext }, -} - -#[derive(Debug, PartialEq, Eq, Clone)] -pub struct ConnectionContext { - client_socket_addr: SocketAddr, - server_socket_addr: SocketAddr, -} - -impl ConnectionContext { - #[must_use] - pub fn new(client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) -> Self { - Self { - client_socket_addr, - server_socket_addr, - } - } - - #[must_use] - pub fn client_socket_addr(&self) -> SocketAddr { - self.client_socket_addr - } - - #[must_use] - pub fn server_socket_addr(&self) -> SocketAddr { - self.server_socket_addr - } -} diff --git a/packages/udp-tracker-core/src/statistics/keeper.rs b/packages/udp-tracker-core/src/statistics/keeper.rs index f06642908..16ea51aac 100644 --- a/packages/udp-tracker-core/src/statistics/keeper.rs +++ b/packages/udp-tracker-core/src/statistics/keeper.rs @@ -1,8 +1,8 @@ use tokio::sync::broadcast::Receiver; use super::event::listener::dispatch_events; -use super::event::Event; use super::repository::Repository; +use crate::event::Event; /// The service responsible for keeping tracker metrics (listening to statistics events and handle them). /// diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index 56814f5d5..d3c1d4710 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -9,7 +9,7 @@ //! //! The factory function builds two structs: //! -//! - An statistics event [`Sender`](crate::statistics::event::sender::Sender) +//! - An event [`Sender`](crate::event::sender::Sender) //! - An statistics [`Repository`] //! //! ```text diff --git a/packages/udp-tracker-core/src/statistics/setup.rs b/packages/udp-tracker-core/src/statistics/setup.rs index a9ac751c6..e2974e4c0 100644 --- a/packages/udp-tracker-core/src/statistics/setup.rs +++ b/packages/udp-tracker-core/src/statistics/setup.rs @@ -1,44 +1,36 @@ //! Setup for the tracker statistics. //! //! The [`factory`] function builds the structs needed for handling the tracker metrics. -use tokio::sync::broadcast; - -use super::event::sender::ChannelSender; -use crate::statistics; - -const CHANNEL_CAPACITY: usize = 1024; +use crate::event::sender::Broadcaster; +use crate::{event, statistics}; /// It builds the structs needed for handling the tracker metrics. /// /// It returns: /// -/// - An statistics event [`Sender`](crate::statistics::event::sender::Sender) that allows you to send events related to statistics. -/// - An statistics [`Repository`](crate::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. +/// - An event [`Sender`](crate::event::sender::Sender) that allows you to send +/// events related to statistics. +/// - An statistics [`Repository`](crate::statistics::repository::Repository) +/// which is an in-memory repository for the tracker metrics. /// -/// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics -/// events are sent are received but not dispatched to the handler. +/// When the input argument `tracker_usage_statistics`is false the setup does +/// not run the event listeners, consequently the statistics events are sent are +/// received but not dispatched to the handler. #[must_use] -pub fn factory( - tracker_usage_statistics: bool, -) -> ( - Option>, - statistics::repository::Repository, -) { - let mut stats_event_sender: Option> = None; - +pub fn factory(tracker_usage_statistics: bool) -> (Option>, statistics::repository::Repository) { let mut keeper = statistics::keeper::Keeper::new(); - if tracker_usage_statistics { - let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); + let opt_event_sender: Option> = if tracker_usage_statistics { + let broadcaster = Broadcaster::default(); - let receiver = sender.subscribe(); + keeper.run_event_listener(broadcaster.subscribe()); - stats_event_sender = Some(Box::new(ChannelSender { sender })); - - keeper.run_event_listener(receiver); - } + Some(Box::new(broadcaster)) + } else { + None + }; - (stats_event_sender, keeper.repository) + (opt_event_sender, keeper.repository) } #[cfg(test)] diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index a2cb55e59..a26961a05 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -811,7 +811,7 @@ mod tests { use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use bittorrent_udp_tracker_core::services::announce::AnnounceService; - use bittorrent_udp_tracker_core::{self, statistics as core_statistics}; + use bittorrent_udp_tracker_core::{self, event as core_event}; use mockall::predicate::eq; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; @@ -850,12 +850,12 @@ mod tests { let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send_event() - .with(eq(core_statistics::event::Event::UdpAnnounce { - context: core_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), + .with(eq(core_event::Event::UdpAnnounce { + context: core_event::ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_core_stats_event_sender: Arc>> = + let udp_core_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 992ef459d..aae9f1136 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -58,8 +58,8 @@ mod tests { use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; use bittorrent_udp_tracker_core::connection_cookie::make; + use bittorrent_udp_tracker_core::event as core_event; use bittorrent_udp_tracker_core::services::connect::ConnectService; - use bittorrent_udp_tracker_core::statistics as core_statistics; use mockall::predicate::eq; use crate::handlers::handle_connect; @@ -192,12 +192,12 @@ mod tests { let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send_event() - .with(eq(core_statistics::event::Event::UdpConnect { - context: core_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), + .with(eq(core_event::Event::UdpConnect { + context: core_event::ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_core_stats_event_sender: Arc>> = + let udp_core_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); @@ -233,12 +233,12 @@ mod tests { let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send_event() - .with(eq(core_statistics::event::Event::UdpConnect { - context: core_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), + .with(eq(core_event::Event::UdpConnect { + context: core_event::ConnectionContext::new(client_socket_addr, server_socket_addr), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_core_stats_event_sender: Arc>> = + let udp_core_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index e573cc184..98f7a2fa2 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -219,7 +219,7 @@ pub(crate) mod tests { use bittorrent_udp_tracker_core::connection_cookie::gen_remote_fingerprint; use bittorrent_udp_tracker_core::services::announce::AnnounceService; use bittorrent_udp_tracker_core::services::scrape::ScrapeService; - use bittorrent_udp_tracker_core::{self, statistics as core_statistics}; + use bittorrent_udp_tracker_core::{self, event as core_event}; use futures::future::BoxFuture; use mockall::mock; use tokio::sync::broadcast::error::SendError; @@ -421,8 +421,8 @@ pub(crate) mod tests { mock! { pub(crate) UdpCoreStatsEventSender {} - impl core_statistics::event::sender::Sender for UdpCoreStatsEventSender { - fn send_event(&self, event: core_statistics::event::Event) -> BoxFuture<'static,Option > > > ; + impl core_event::sender::Sender for UdpCoreStatsEventSender { + fn send_event(&self, event: core_event::Event) -> BoxFuture<'static,Option > > > ; } } diff --git a/src/container.rs b/src/container.rs index 1c8c9c1d3..7822b5d61 100644 --- a/src/container.rs +++ b/src/container.rs @@ -52,7 +52,7 @@ pub struct AppContainer { pub torrents_manager: Arc, // UDP Tracker Core Services - pub udp_core_stats_event_sender: Arc>>, + pub udp_core_stats_event_sender: Arc>>, pub udp_core_stats_repository: Arc, pub udp_ban_service: Arc>, pub udp_connect_service: Arc, From d8f1696141c065ac41ae81182752da4e1c7714de Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Mar 2025 17:03:47 +0000 Subject: [PATCH 0900/1297] refactor: [#1398] extract event module in UDP server --- packages/udp-tracker-server/src/container.rs | 4 +- packages/udp-tracker-server/src/event/mod.rs | 76 +++++++++++++++++++ .../src/{statistics => }/event/sender.rs | 28 +++++-- .../src/handlers/announce.rs | 34 ++++----- .../src/handlers/connect.rs | 22 +++--- .../udp-tracker-server/src/handlers/error.rs | 7 +- .../udp-tracker-server/src/handlers/mod.rs | 10 +-- .../udp-tracker-server/src/handlers/scrape.rs | 26 +++---- packages/udp-tracker-server/src/lib.rs | 1 + .../udp-tracker-server/src/server/launcher.rs | 9 +-- .../src/server/processor.rs | 20 ++--- .../src/statistics/event/handler.rs | 20 ++--- .../src/statistics/event/listener.rs | 2 +- .../src/statistics/event/mod.rs | 76 ------------------- .../src/statistics/keeper.rs | 2 +- .../src/statistics/setup.rs | 47 +++++------- src/container.rs | 2 +- 17 files changed, 191 insertions(+), 195 deletions(-) create mode 100644 packages/udp-tracker-server/src/event/mod.rs rename packages/udp-tracker-server/src/{statistics => }/event/sender.rs (54%) diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs index 36ad0e671..0c8039b26 100644 --- a/packages/udp-tracker-server/src/container.rs +++ b/packages/udp-tracker-server/src/container.rs @@ -2,10 +2,10 @@ use std::sync::Arc; use torrust_tracker_configuration::Core; -use crate::statistics; +use crate::{event, statistics}; pub struct UdpTrackerServerContainer { - pub udp_server_stats_event_sender: Arc>>, + pub udp_server_stats_event_sender: Arc>>, pub udp_server_stats_repository: Arc, } diff --git a/packages/udp-tracker-server/src/event/mod.rs b/packages/udp-tracker-server/src/event/mod.rs new file mode 100644 index 000000000..adc1396cc --- /dev/null +++ b/packages/udp-tracker-server/src/event/mod.rs @@ -0,0 +1,76 @@ +use std::net::SocketAddr; +use std::time::Duration; + +pub mod sender; + +/// An statistics event. It is used to collect tracker metrics. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum Event { + UdpRequestReceived { + context: ConnectionContext, + }, + UdpRequestAborted { + context: ConnectionContext, + }, + UdpRequestBanned { + context: ConnectionContext, + }, + UdpRequestAccepted { + context: ConnectionContext, + kind: UdpRequestKind, + }, + UdpResponseSent { + context: ConnectionContext, + kind: UdpResponseKind, + req_processing_time: Duration, + }, + UdpError { + context: ConnectionContext, + }, +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum UdpRequestKind { + Connect, + Announce, + Scrape, +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum UdpResponseKind { + Ok { + req_kind: UdpRequestKind, + }, + + /// There was an error handling the request. The error contains the request + /// kind if the request was parsed successfully. + Error { + opt_req_kind: Option, + }, +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct ConnectionContext { + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, +} + +impl ConnectionContext { + #[must_use] + pub fn new(client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) -> Self { + Self { + client_socket_addr, + server_socket_addr, + } + } + + #[must_use] + pub fn client_socket_addr(&self) -> SocketAddr { + self.client_socket_addr + } + + #[must_use] + pub fn server_socket_addr(&self) -> SocketAddr { + self.server_socket_addr + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/sender.rs b/packages/udp-tracker-server/src/event/sender.rs similarity index 54% rename from packages/udp-tracker-server/src/statistics/event/sender.rs rename to packages/udp-tracker-server/src/event/sender.rs index 9092a8e0b..e9431abf2 100644 --- a/packages/udp-tracker-server/src/statistics/event/sender.rs +++ b/packages/udp-tracker-server/src/event/sender.rs @@ -7,23 +7,35 @@ use tokio::sync::broadcast::error::SendError; use super::Event; -/// A trait to allow sending statistics events +const CHANNEL_CAPACITY: usize = 1024; + +/// A trait for sending sending. #[cfg_attr(test, automock)] pub trait Sender: Sync + Send { fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; } -/// An [`statistics::EventSender`](crate::statistics::event::sender::Sender) implementation. -/// -/// It uses a channel sender to send the statistic events. The channel is created by a -/// [`statistics::Keeper`](crate::statistics::keeper::Keeper) -#[allow(clippy::module_name_repetitions)] -pub struct ChannelSender { +/// An event sender implementation using a broadcast channel. +pub struct Broadcaster { pub(crate) sender: broadcast::Sender, } -impl Sender for ChannelSender { +impl Sender for Broadcaster { fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { async move { Some(self.sender.send(event)) }.boxed() } } + +impl Default for Broadcaster { + fn default() -> Self { + let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); + Self { sender } + } +} + +impl Broadcaster { + #[must_use] + pub fn subscribe(&self) -> broadcast::Receiver { + self.sender.subscribe() + } +} diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index a26961a05..5df46125d 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -15,8 +15,7 @@ use tracing::{instrument, Level}; use zerocopy::network_endian::I32; use crate::error::Error; -use crate::statistics as server_statistics; -use crate::statistics::event::{ConnectionContext, UdpRequestKind}; +use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; /// It handles the `Announce` request. /// @@ -30,7 +29,7 @@ pub async fn handle_announce( server_socket_addr: SocketAddr, request: &AnnounceRequest, core_config: &Arc, - opt_udp_server_stats_event_sender: &Arc>>, + opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { tracing::Span::current() @@ -42,7 +41,7 @@ pub async fn handle_announce( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(server_statistics::event::Event::UdpRequestAccepted { + .send_event(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, }) @@ -207,6 +206,7 @@ mod tests { use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use mockall::predicate::eq; + use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::handlers::handle_announce; use crate::handlers::tests::{ @@ -215,8 +215,6 @@ mod tests { sample_issue_time, CoreTrackerServices, CoreUdpTrackerServices, MockUdpServerStatsEventSender, TorrentPeerBuilder, }; - use crate::statistics as server_statistics; - use crate::statistics::event::UdpRequestKind; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { @@ -425,13 +423,13 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequestAccepted { - context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), + .with(eq(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = @@ -532,6 +530,7 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_configuration::Core; + use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::handlers::handle_announce; use crate::handlers::tests::{ @@ -539,8 +538,6 @@ mod tests { initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, sample_issue_time, MockUdpServerStatsEventSender, TorrentPeerBuilder, }; - use crate::statistics as server_statistics; - use crate::statistics::event::UdpRequestKind; #[tokio::test] async fn an_announced_peer_should_be_added_to_the_tracker() { @@ -768,13 +765,13 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequestAccepted { - context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), + .with(eq(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = @@ -814,14 +811,13 @@ mod tests { use bittorrent_udp_tracker_core::{self, event as core_event}; use mockall::predicate::eq; + use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::handlers::handle_announce; use crate::handlers::tests::{ sample_cookie_valid_range, sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, TrackerConfigurationBuilder, }; - use crate::statistics as server_statistics; - use crate::statistics::event::UdpRequestKind; #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { @@ -861,13 +857,13 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequestAccepted { - context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), + .with(eq(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Announce, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let announce_handler = Arc::new(AnnounceHandler::new( diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index aae9f1136..a0fbaead3 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -6,8 +6,7 @@ use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, ConnectionId, Respon use bittorrent_udp_tracker_core::services::connect::ConnectService; use tracing::{instrument, Level}; -use crate::statistics as server_statistics; -use crate::statistics::event::{ConnectionContext, UdpRequestKind}; +use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; /// It handles the `Connect` request. #[instrument(fields(transaction_id), skip(connect_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] @@ -16,7 +15,7 @@ pub async fn handle_connect( server_socket_addr: SocketAddr, request: &ConnectRequest, connect_service: &Arc, - opt_udp_server_stats_event_sender: &Arc>>, + opt_udp_server_stats_event_sender: &Arc>>, cookie_issue_time: f64, ) -> Response { tracing::Span::current().record("transaction_id", request.transaction_id.0.to_string()); @@ -24,7 +23,7 @@ pub async fn handle_connect( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(server_statistics::event::Event::UdpRequestAccepted { + .send_event(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Connect, }) @@ -62,13 +61,12 @@ mod tests { use bittorrent_udp_tracker_core::services::connect::ConnectService; use mockall::predicate::eq; + use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; use crate::handlers::handle_connect; use crate::handlers::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, }; - use crate::statistics as server_statistics; - use crate::statistics::event::UdpRequestKind; fn sample_connect_request() -> ConnectRequest { ConnectRequest { @@ -203,13 +201,13 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequestAccepted { - context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), + .with(eq(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Connect, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -244,13 +242,13 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequestAccepted { - context: server_statistics::event::ConnectionContext::new(client_socket_addr, server_socket_addr), + .with(eq(Event::UdpRequestAccepted { + context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Connect, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index d1ffe2fd4..70c33b5ba 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -11,8 +11,7 @@ use uuid::Uuid; use zerocopy::network_endian::I32; use crate::error::Error; -use crate::statistics as server_statistics; -use crate::statistics::event::{ConnectionContext, UdpRequestKind}; +use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; #[allow(clippy::too_many_arguments)] #[instrument(fields(transaction_id), skip(opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] @@ -21,7 +20,7 @@ pub async fn handle_error( client_socket_addr: SocketAddr, server_socket_addr: SocketAddr, request_id: Uuid, - opt_udp_server_stats_event_sender: &Arc>>, + opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, e: &Error, transaction_id: Option, @@ -60,7 +59,7 @@ pub async fn handle_error( if e.1.is_some() { if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(server_statistics::event::Event::UdpError { + .send_event(Event::UdpError { context: ConnectionContext::new(client_socket_addr, server_socket_addr), }) .await; diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 98f7a2fa2..61f7bb187 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -24,7 +24,7 @@ use uuid::Uuid; use super::RawRequest; use crate::container::UdpTrackerServerContainer; use crate::error::Error; -use crate::statistics::event::UdpRequestKind; +use crate::event::UdpRequestKind; use crate::CurrentClock; #[derive(Debug, Clone, PartialEq)] @@ -228,7 +228,7 @@ pub(crate) mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::{statistics as server_statistics, CurrentClock}; + use crate::{event as server_event, CurrentClock}; pub(crate) struct CoreTrackerServices { pub core_config: Arc, @@ -244,7 +244,7 @@ pub(crate) mod tests { } pub(crate) struct ServerUdpTrackerServices { - pub udp_server_stats_event_sender: Arc>>, + pub udp_server_stats_event_sender: Arc>>, } fn default_testing_tracker_configuration() -> Configuration { @@ -428,8 +428,8 @@ pub(crate) mod tests { mock! { pub(crate) UdpServerStatsEventSender {} - impl server_statistics::event::sender::Sender for UdpServerStatsEventSender { - fn send_event(&self, event: server_statistics::event::Event) -> BoxFuture<'static,Option > > > ; + impl server_event::sender::Sender for UdpServerStatsEventSender { + fn send_event(&self, event: server_event::Event) -> BoxFuture<'static,Option > > > ; } } } diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index fbf2b7c43..ac0faef61 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -13,8 +13,7 @@ use tracing::{instrument, Level}; use zerocopy::network_endian::I32; use crate::error::Error; -use crate::statistics as server_statistics; -use crate::statistics::event::{ConnectionContext, UdpRequestKind}; +use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; /// It handles the `Scrape` request. /// @@ -27,7 +26,7 @@ pub async fn handle_scrape( client_socket_addr: SocketAddr, server_socket_addr: SocketAddr, request: &ScrapeRequest, - opt_udp_server_stats_event_sender: &Arc>>, + opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, ) -> Result { tracing::Span::current() @@ -38,7 +37,7 @@ pub async fn handle_scrape( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(server_statistics::event::Event::UdpRequestAccepted { + .send_event(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_socket_addr), kind: UdpRequestKind::Scrape, }) @@ -352,13 +351,13 @@ mod tests { use mockall::predicate::eq; use super::sample_scrape_request; + use crate::event; + use crate::event::{ConnectionContext, Event, UdpRequestKind}; use crate::handlers::handle_scrape; use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, sample_ipv4_remote_addr, MockUdpServerStatsEventSender, }; - use crate::statistics as server_statistics; - use crate::statistics::event::ConnectionContext; #[tokio::test] async fn should_send_the_upd4_scrape_event() { @@ -368,13 +367,13 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequestAccepted { + .with(eq(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_socket_addr), - kind: server_statistics::event::UdpRequestKind::Scrape, + kind: UdpRequestKind::Scrape, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let (_core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = @@ -401,13 +400,12 @@ mod tests { use mockall::predicate::eq; use super::sample_scrape_request; + use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; use crate::handlers::handle_scrape; use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, sample_ipv6_remote_addr, MockUdpServerStatsEventSender, }; - use crate::statistics as server_statistics; - use crate::statistics::event::ConnectionContext; #[tokio::test] async fn should_send_the_upd6_scrape_event() { @@ -417,13 +415,13 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() - .with(eq(server_statistics::event::Event::UdpRequestAccepted { + .with(eq(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_socket_addr), - kind: server_statistics::event::UdpRequestKind::Scrape, + kind: UdpRequestKind::Scrape, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: Arc>> = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let (_core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = diff --git a/packages/udp-tracker-server/src/lib.rs b/packages/udp-tracker-server/src/lib.rs index 9e013bf81..ff53adcfb 100644 --- a/packages/udp-tracker-server/src/lib.rs +++ b/packages/udp-tracker-server/src/lib.rs @@ -637,6 +637,7 @@ pub mod container; pub mod environment; pub mod error; +pub mod event; pub mod handlers; pub mod server; pub mod statistics; diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index c6a105230..c98db0500 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -17,11 +17,10 @@ use tracing::instrument; use super::request_buffer::ActiveRequests; use crate::container::UdpTrackerServerContainer; +use crate::event::{ConnectionContext, Event}; use crate::server::bound_socket::BoundSocket; use crate::server::processor::Processor; use crate::server::receiver::Receiver; -use crate::statistics; -use crate::statistics::event::ConnectionContext; const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 3600; @@ -173,7 +172,7 @@ impl Launcher { if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(statistics::event::Event::UdpRequestReceived { + .send_event(Event::UdpRequestReceived { context: ConnectionContext::new(client_socket_addr, server_socket_addr), }) .await; @@ -186,7 +185,7 @@ impl Launcher { udp_tracker_server_container.udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(statistics::event::Event::UdpRequestBanned { + .send_event(Event::UdpRequestBanned { context: ConnectionContext::new(client_socket_addr, server_socket_addr), }) .await; @@ -228,7 +227,7 @@ impl Launcher { udp_tracker_server_container.udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(statistics::event::Event::UdpRequestAborted { + .send_event(Event::UdpRequestAborted { context: ConnectionContext::new(client_socket_addr, server_socket_addr), }) .await; diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs index 4d1e4429a..02e084356 100644 --- a/packages/udp-tracker-server/src/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -11,9 +11,9 @@ use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; use crate::container::UdpTrackerServerContainer; +use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; use crate::handlers::CookieTimeValues; -use crate::statistics::event::{ConnectionContext, UdpRequestKind}; -use crate::{handlers, statistics, RawRequest}; +use crate::{handlers, RawRequest}; pub struct Processor { socket: Arc, @@ -77,16 +77,16 @@ impl Processor { }; let udp_response_kind = match &response { - Response::Connect(_) => statistics::event::UdpResponseKind::Ok { - req_kind: statistics::event::UdpRequestKind::Connect, + Response::Connect(_) => event::UdpResponseKind::Ok { + req_kind: event::UdpRequestKind::Connect, }, - Response::AnnounceIpv4(_) | Response::AnnounceIpv6(_) => statistics::event::UdpResponseKind::Ok { - req_kind: statistics::event::UdpRequestKind::Announce, + Response::AnnounceIpv4(_) | Response::AnnounceIpv6(_) => event::UdpResponseKind::Ok { + req_kind: event::UdpRequestKind::Announce, }, - Response::Scrape(_) => statistics::event::UdpResponseKind::Ok { - req_kind: statistics::event::UdpRequestKind::Scrape, + Response::Scrape(_) => event::UdpResponseKind::Ok { + req_kind: event::UdpRequestKind::Scrape, }, - Response::Error(_e) => statistics::event::UdpResponseKind::Error { opt_req_kind: None }, + Response::Error(_e) => event::UdpResponseKind::Error { opt_req_kind: None }, }; let mut writer = Cursor::new(Vec::with_capacity(200)); @@ -108,7 +108,7 @@ impl Processor { self.udp_tracker_server_container.udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(statistics::event::Event::UdpResponseSent { + .send_event(Event::UdpResponseSent { context: ConnectionContext::new(client_socket_addr, self.socket.address()), kind: udp_response_kind, req_processing_time, diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 6abf7d3c7..f65a1e567 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -1,4 +1,4 @@ -use crate::statistics::event::{Event, UdpRequestKind, UdpResponseKind}; +use crate::event::{Event, UdpRequestKind, UdpResponseKind}; use crate::statistics::repository::Repository; /// # Panics @@ -100,8 +100,8 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use crate::event::{ConnectionContext, Event, UdpRequestKind}; use crate::statistics::event::handler::handle_event; - use crate::statistics::event::{ConnectionContext, Event, UdpRequestKind}; use crate::statistics::repository::Repository; #[tokio::test] @@ -209,7 +209,7 @@ mod tests { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), ), - kind: crate::statistics::event::UdpRequestKind::Connect, + kind: crate::event::UdpRequestKind::Connect, }, &stats_repository, ) @@ -230,7 +230,7 @@ mod tests { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), ), - kind: crate::statistics::event::UdpRequestKind::Announce, + kind: crate::event::UdpRequestKind::Announce, }, &stats_repository, ) @@ -251,7 +251,7 @@ mod tests { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), ), - kind: crate::statistics::event::UdpRequestKind::Scrape, + kind: crate::event::UdpRequestKind::Scrape, }, &stats_repository, ) @@ -272,7 +272,7 @@ mod tests { SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), ), - kind: crate::statistics::event::UdpResponseKind::Ok { + kind: crate::event::UdpResponseKind::Ok { req_kind: UdpRequestKind::Announce, }, req_processing_time: std::time::Duration::from_secs(1), @@ -316,7 +316,7 @@ mod tests { SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), ), - kind: crate::statistics::event::UdpRequestKind::Connect, + kind: crate::event::UdpRequestKind::Connect, }, &stats_repository, ) @@ -337,7 +337,7 @@ mod tests { SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), ), - kind: crate::statistics::event::UdpRequestKind::Announce, + kind: crate::event::UdpRequestKind::Announce, }, &stats_repository, ) @@ -358,7 +358,7 @@ mod tests { SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), ), - kind: crate::statistics::event::UdpRequestKind::Scrape, + kind: crate::event::UdpRequestKind::Scrape, }, &stats_repository, ) @@ -379,7 +379,7 @@ mod tests { SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), ), - kind: crate::statistics::event::UdpResponseKind::Ok { + kind: crate::event::UdpResponseKind::Ok { req_kind: UdpRequestKind::Announce, }, req_processing_time: std::time::Duration::from_secs(1), diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index b755cbf18..b23260747 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -1,7 +1,7 @@ use tokio::sync::broadcast; use super::handler::handle_event; -use super::Event; +use crate::event::Event; use crate::statistics::repository::Repository; pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { diff --git a/packages/udp-tracker-server/src/statistics/event/mod.rs b/packages/udp-tracker-server/src/statistics/event/mod.rs index 1b0be960b..dae683398 100644 --- a/packages/udp-tracker-server/src/statistics/event/mod.rs +++ b/packages/udp-tracker-server/src/statistics/event/mod.rs @@ -1,78 +1,2 @@ -use std::net::SocketAddr; -use std::time::Duration; - pub mod handler; pub mod listener; -pub mod sender; - -/// An statistics event. It is used to collect tracker metrics. -#[derive(Debug, PartialEq, Eq, Clone)] -pub enum Event { - UdpRequestReceived { - context: ConnectionContext, - }, - UdpRequestAborted { - context: ConnectionContext, - }, - UdpRequestBanned { - context: ConnectionContext, - }, - UdpRequestAccepted { - context: ConnectionContext, - kind: UdpRequestKind, - }, - UdpResponseSent { - context: ConnectionContext, - kind: UdpResponseKind, - req_processing_time: Duration, - }, - UdpError { - context: ConnectionContext, - }, -} - -#[derive(Debug, PartialEq, Eq, Clone)] -pub enum UdpRequestKind { - Connect, - Announce, - Scrape, -} - -#[derive(Debug, PartialEq, Eq, Clone)] -pub enum UdpResponseKind { - Ok { - req_kind: UdpRequestKind, - }, - - /// There was an error handling the request. The error contains the request - /// kind if the request was parsed successfully. - Error { - opt_req_kind: Option, - }, -} - -#[derive(Debug, PartialEq, Eq, Clone)] -pub struct ConnectionContext { - client_socket_addr: SocketAddr, - server_socket_addr: SocketAddr, -} - -impl ConnectionContext { - #[must_use] - pub fn new(client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) -> Self { - Self { - client_socket_addr, - server_socket_addr, - } - } - - #[must_use] - pub fn client_socket_addr(&self) -> SocketAddr { - self.client_socket_addr - } - - #[must_use] - pub fn server_socket_addr(&self) -> SocketAddr { - self.server_socket_addr - } -} diff --git a/packages/udp-tracker-server/src/statistics/keeper.rs b/packages/udp-tracker-server/src/statistics/keeper.rs index 099e0d0aa..62216ce88 100644 --- a/packages/udp-tracker-server/src/statistics/keeper.rs +++ b/packages/udp-tracker-server/src/statistics/keeper.rs @@ -1,8 +1,8 @@ use tokio::sync::broadcast::Receiver; use super::event::listener::dispatch_events; -use super::event::Event; use super::repository::Repository; +use crate::event::Event; /// The service responsible for keeping tracker metrics (listening to statistics events and handle them). /// diff --git a/packages/udp-tracker-server/src/statistics/setup.rs b/packages/udp-tracker-server/src/statistics/setup.rs index a9ac751c6..d8cc7bca9 100644 --- a/packages/udp-tracker-server/src/statistics/setup.rs +++ b/packages/udp-tracker-server/src/statistics/setup.rs @@ -1,44 +1,37 @@ //! Setup for the tracker statistics. //! -//! The [`factory`] function builds the structs needed for handling the tracker metrics. -use tokio::sync::broadcast; - -use super::event::sender::ChannelSender; -use crate::statistics; - -const CHANNEL_CAPACITY: usize = 1024; +//! The [`factory`] function builds the structs needed for handling the tracker +//! metrics. +use crate::event::sender::Broadcaster; +use crate::{event, statistics}; /// It builds the structs needed for handling the tracker metrics. /// /// It returns: /// -/// - An statistics event [`Sender`](crate::statistics::event::sender::Sender) that allows you to send events related to statistics. -/// - An statistics [`Repository`](crate::statistics::repository::Repository) which is an in-memory repository for the tracker metrics. +/// - An event [`Sender`](crate::event::sender::Sender) that allows you to send +/// events related to statistics. +/// - An statistics [`Repository`](crate::statistics::repository::Repository) +/// which is an in-memory repository for the tracker metrics. /// -/// When the input argument `tracker_usage_statistics`is false the setup does not run the event listeners, consequently the statistics -/// events are sent are received but not dispatched to the handler. +/// When the input argument `tracker_usage_statistics`is false the setup does +/// not run the event listeners, consequently the statistics events are sent are +/// received but not dispatched to the handler. #[must_use] -pub fn factory( - tracker_usage_statistics: bool, -) -> ( - Option>, - statistics::repository::Repository, -) { - let mut stats_event_sender: Option> = None; - +pub fn factory(tracker_usage_statistics: bool) -> (Option>, statistics::repository::Repository) { let mut keeper = statistics::keeper::Keeper::new(); - if tracker_usage_statistics { - let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); + let opt_event_sender: Option> = if tracker_usage_statistics { + let broadcaster = Broadcaster::default(); - let receiver = sender.subscribe(); + keeper.run_event_listener(broadcaster.subscribe()); - stats_event_sender = Some(Box::new(ChannelSender { sender })); - - keeper.run_event_listener(receiver); - } + Some(Box::new(broadcaster)) + } else { + None + }; - (stats_event_sender, keeper.repository) + (opt_event_sender, keeper.repository) } #[cfg(test)] diff --git a/src/container.rs b/src/container.rs index 7822b5d61..3fcda55f0 100644 --- a/src/container.rs +++ b/src/container.rs @@ -66,7 +66,7 @@ pub struct AppContainer { pub http_scrape_service: Arc, // UDP Tracker Server Services - pub udp_server_stats_event_sender: Arc>>, + pub udp_server_stats_event_sender: Arc>>, pub udp_server_stats_repository: Arc, } From 055db4e67dd89183a9e838ba101c0567479de45c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Mar 2025 17:06:18 +0000 Subject: [PATCH 0901/1297] docs: [#1395] minor changes in comments --- packages/http-tracker-core/src/event/mod.rs | 2 +- packages/udp-tracker-core/src/event/mod.rs | 5 +---- packages/udp-tracker-server/src/event/mod.rs | 2 +- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index da824c240..3db258238 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -2,7 +2,7 @@ use std::net::{IpAddr, SocketAddr}; pub mod sender; -/// An event. +/// A HTTP core event. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { TcpAnnounce { connection: ConnectionContext }, diff --git a/packages/udp-tracker-core/src/event/mod.rs b/packages/udp-tracker-core/src/event/mod.rs index 48a5b501b..04b3170e2 100644 --- a/packages/udp-tracker-core/src/event/mod.rs +++ b/packages/udp-tracker-core/src/event/mod.rs @@ -2,10 +2,7 @@ use std::net::SocketAddr; pub mod sender; -/// An statistics event. It is used to collect tracker metrics. -/// -/// - `Udp` prefix means the event was triggered by the UDP tracker. -/// - The event suffix is the type of request: `announce`, `scrape` or `connection`. +/// A UDP core event. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { UdpConnect { context: ConnectionContext }, diff --git a/packages/udp-tracker-server/src/event/mod.rs b/packages/udp-tracker-server/src/event/mod.rs index adc1396cc..0adf29c8b 100644 --- a/packages/udp-tracker-server/src/event/mod.rs +++ b/packages/udp-tracker-server/src/event/mod.rs @@ -3,7 +3,7 @@ use std::time::Duration; pub mod sender; -/// An statistics event. It is used to collect tracker metrics. +/// A UDP server event. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { UdpRequestReceived { From 9eba80fa62f0f8e971c3c6fd726c681eb1fdd2fa Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 19 Mar 2025 17:07:31 +0000 Subject: [PATCH 0902/1297] refactor: [#1395] rename send_stats_event to send_event Events are now generic even if they are only used for stats for now. --- packages/http-tracker-core/src/services/announce.rs | 4 ++-- packages/http-tracker-core/src/services/scrape.rs | 10 ++-------- packages/udp-tracker-core/src/services/announce.rs | 4 ++-- packages/udp-tracker-core/src/services/scrape.rs | 4 ++-- 4 files changed, 8 insertions(+), 14 deletions(-) diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index cd7417e98..f8d2e0b11 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -87,7 +87,7 @@ impl AnnounceService { .announce(&announce_request.info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; - self.send_stats_event(remote_client_ip, opt_remote_client_port, *server_socket_addr) + self.send_event(remote_client_ip, opt_remote_client_port, *server_socket_addr) .await; Ok(announce_data) @@ -138,7 +138,7 @@ impl AnnounceService { } } - async fn send_stats_event(&self, peer_ip: IpAddr, opt_peer_ip_port: Option, server_socket_addr: SocketAddr) { + async fn send_event(&self, peer_ip: IpAddr, opt_peer_ip_port: Option, server_socket_addr: SocketAddr) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { http_stats_event_sender .send_event(Event::TcpAnnounce { diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 1f4c14b5a..c9b3182f8 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -82,8 +82,7 @@ impl ScrapeService { let (remote_client_ip, opt_client_port) = self.resolve_remote_client_ip(client_ip_sources)?; - self.send_stats_event(remote_client_ip, opt_client_port, *server_socket_addr) - .await; + self.send_event(remote_client_ip, opt_client_port, *server_socket_addr).await; Ok(scrape_data) } @@ -118,12 +117,7 @@ impl ScrapeService { Ok((ip, port)) } - async fn send_stats_event( - &self, - original_peer_ip: IpAddr, - opt_original_peer_port: Option, - server_socket_addr: SocketAddr, - ) { + async fn send_event(&self, original_peer_ip: IpAddr, opt_original_peer_port: Option, server_socket_addr: SocketAddr) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { http_stats_event_sender .send_event(Event::TcpScrape { diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index bba9b51fc..d99618316 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -79,7 +79,7 @@ impl AnnounceService { .announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; - self.send_stats_event(client_socket_addr, server_socket_addr).await; + self.send_event(client_socket_addr, server_socket_addr).await; Ok(announce_data) } @@ -100,7 +100,7 @@ impl AnnounceService { self.whitelist_authorization.authorize(info_hash).await } - async fn send_stats_event(&self, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) { + async fn send_event(&self, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) { if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { udp_stats_event_sender .send_event(Event::UdpAnnounce { diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index 9f0941c2a..3b6898311 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -61,7 +61,7 @@ impl ScrapeService { .scrape(&Self::convert_from_aquatic(&request.info_hashes)) .await?; - self.send_stats_event(client_socket_addr, server_socket_addr).await; + self.send_event(client_socket_addr, server_socket_addr).await; Ok(scrape_data) } @@ -82,7 +82,7 @@ impl ScrapeService { aquatic_infohashes.iter().map(|&x| x.into()).collect() } - async fn send_stats_event(&self, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) { + async fn send_event(&self, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) { if let Some(udp_stats_event_sender) = self.opt_udp_stats_event_sender.as_deref() { udp_stats_event_sender .send_event(Event::UdpScrape { From 57d884d8dd6128a019ad5253eb094507689cb83b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Mar 2025 09:52:31 +0000 Subject: [PATCH 0903/1297] refactor: [#1401] add config option to enable/disable tracker usage stats per server It does not have any effect yet. --- packages/configuration/src/v2_0_0/core.rs | 1 + packages/configuration/src/v2_0_0/http_tracker.rs | 9 +++++++++ packages/configuration/src/v2_0_0/udp_tracker.rs | 9 +++++++++ packages/test-helpers/src/configuration.rs | 2 ++ 4 files changed, 21 insertions(+) diff --git a/packages/configuration/src/v2_0_0/core.rs b/packages/configuration/src/v2_0_0/core.rs index ed3e6aeb7..32dac8b3c 100644 --- a/packages/configuration/src/v2_0_0/core.rs +++ b/packages/configuration/src/v2_0_0/core.rs @@ -103,6 +103,7 @@ impl Core { fn default_tracker_policy() -> TrackerPolicy { TrackerPolicy::default() } + fn default_tracker_usage_statistics() -> bool { true } diff --git a/packages/configuration/src/v2_0_0/http_tracker.rs b/packages/configuration/src/v2_0_0/http_tracker.rs index 42ec02bf2..b3b21bda8 100644 --- a/packages/configuration/src/v2_0_0/http_tracker.rs +++ b/packages/configuration/src/v2_0_0/http_tracker.rs @@ -19,6 +19,10 @@ pub struct HttpTracker { /// TSL config. #[serde(default = "HttpTracker::default_tsl_config")] pub tsl_config: Option, + + /// Weather the tracker should collect statistics about tracker usage. + #[serde(default = "HttpTracker::default_tracker_usage_statistics")] + pub tracker_usage_statistics: bool, } impl Default for HttpTracker { @@ -26,6 +30,7 @@ impl Default for HttpTracker { Self { bind_address: Self::default_bind_address(), tsl_config: Self::default_tsl_config(), + tracker_usage_statistics: Self::default_tracker_usage_statistics(), } } } @@ -38,4 +43,8 @@ impl HttpTracker { fn default_tsl_config() -> Option { None } + + fn default_tracker_usage_statistics() -> bool { + false + } } diff --git a/packages/configuration/src/v2_0_0/udp_tracker.rs b/packages/configuration/src/v2_0_0/udp_tracker.rs index 0eee87700..9918bc1fa 100644 --- a/packages/configuration/src/v2_0_0/udp_tracker.rs +++ b/packages/configuration/src/v2_0_0/udp_tracker.rs @@ -16,12 +16,17 @@ pub struct UdpTracker { /// the client as the `ConnectionId`. #[serde(default = "UdpTracker::default_cookie_lifetime")] pub cookie_lifetime: Duration, + + /// Weather the tracker should collect statistics about tracker usage. + #[serde(default = "UdpTracker::default_tracker_usage_statistics")] + pub tracker_usage_statistics: bool, } impl Default for UdpTracker { fn default() -> Self { Self { bind_address: Self::default_bind_address(), cookie_lifetime: Self::default_cookie_lifetime(), + tracker_usage_statistics: Self::default_tracker_usage_statistics(), } } } @@ -34,4 +39,8 @@ impl UdpTracker { fn default_cookie_lifetime() -> Duration { Duration::from_secs(120) } + + fn default_tracker_usage_statistics() -> bool { + false + } } diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 130820334..986981b1f 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -55,6 +55,7 @@ pub fn ephemeral() -> Configuration { config.udp_trackers = Some(vec![UdpTracker { bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), udp_port), cookie_lifetime: Duration::from_secs(120), + tracker_usage_statistics: true, }]); // Ephemeral socket address for HTTP tracker @@ -62,6 +63,7 @@ pub fn ephemeral() -> Configuration { config.http_trackers = Some(vec![HttpTracker { bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), http_port), tsl_config: None, + tracker_usage_statistics: true, }]); let temp_file = ephemeral_sqlite_database(); From 82bacf042ecb92cbf97c492f0f64a88654ccc954 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Mar 2025 16:33:12 +0000 Subject: [PATCH 0904/1297] chore: enable seggregate stats for dev env by default --- share/default/config/tracker.development.sqlite3.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index 96addaf87..d07868c51 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -12,9 +12,11 @@ private = false [[udp_trackers]] bind_address = "0.0.0.0:6969" +tracker_usage_statistics = true [[http_trackers]] bind_address = "0.0.0.0:7070" +tracker_usage_statistics = true [http_api] bind_address = "0.0.0.0:1212" From c7297c16ae7e8a71b0ea1aa45bef77246be469bc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Mar 2025 16:34:45 +0000 Subject: [PATCH 0905/1297] chore: add a second HTTP and UDP tracker in dev env We will start making changes in the `AppContainer` and services. Having more than one server of the same type could help to detect bugs prematurely. --- share/default/config/tracker.development.sqlite3.toml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index d07868c51..333c6d66c 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -10,6 +10,10 @@ threshold = "info" listed = false private = false +[[udp_trackers]] +bind_address = "0.0.0.0:6868" +tracker_usage_statistics = true + [[udp_trackers]] bind_address = "0.0.0.0:6969" tracker_usage_statistics = true @@ -18,6 +22,10 @@ tracker_usage_statistics = true bind_address = "0.0.0.0:7070" tracker_usage_statistics = true +[[http_trackers]] +bind_address = "0.0.0.0:7171" +tracker_usage_statistics = true + [http_api] bind_address = "0.0.0.0:1212" From 9cee15ee22230e304588bf4f1312abd0bc567bf9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Mar 2025 17:05:50 +0000 Subject: [PATCH 0906/1297] refactor: encapsule fiel in AppContainer for TrackerCoreContainer --- src/app.rs | 7 ++++- src/container.rs | 69 ++++++++++++------------------------------------ 2 files changed, 23 insertions(+), 53 deletions(-) diff --git a/src/app.rs b/src/app.rs index 60e907a88..fb8a459ea 100644 --- a/src/app.rs +++ b/src/app.rs @@ -53,6 +53,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> // Load peer keys if config.core.private { app_container + .tracker_core_container .keys_handler .load_peer_keys_from_database() .await @@ -62,6 +63,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> // Load whitelisted torrents if config.core.listed { app_container + .tracker_core_container .whitelist_manager .load_whitelist_from_database() .await @@ -130,7 +132,10 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> // Start runners to remove torrents without peers, every interval if config.core.inactive_peer_cleanup_interval > 0 { - jobs.push(torrent_cleanup::start_job(&config.core, &app_container.torrents_manager)); + jobs.push(torrent_cleanup::start_job( + &config.core, + &app_container.tracker_core_container.torrents_manager, + )); } // Start Health Check API diff --git a/src/container.rs b/src/container.rs index 3fcda55f0..b02dc8811 100644 --- a/src/container.rs +++ b/src/container.rs @@ -3,24 +3,13 @@ use std::sync::Arc; use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_http_tracker_core::services::announce::AnnounceService; use bittorrent_http_tracker_core::services::scrape::ScrapeService; -use bittorrent_tracker_core::announce_handler::AnnounceHandler; -use bittorrent_tracker_core::authentication::handler::KeysHandler; -use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::container::TrackerCoreContainer; -use bittorrent_tracker_core::databases::Database; -use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::torrent::manager::TorrentsManager; -use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; -use bittorrent_tracker_core::whitelist; -use bittorrent_tracker_core::whitelist::manager::WhitelistManager; -use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; -use torrust_tracker_configuration::{Configuration, Core, HttpApi, HttpTracker, UdpTracker}; +use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, UdpTracker}; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use tracing::instrument; @@ -28,7 +17,6 @@ use tracing::instrument; Use containers from packages as AppContainer fields: - - bittorrent_tracker_core::container::TrackerCoreContainer - bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer - bittorrent_http_tracker_core::container::HttpTrackerCoreContainer - torrust_udp_tracker_server::container::UdpTrackerServerContainer @@ -37,19 +25,7 @@ use tracing::instrument; */ pub struct AppContainer { - // Tracker Core Services - pub core_config: Arc, - pub database: Arc>, - pub announce_handler: Arc, - pub scrape_handler: Arc, - pub keys_handler: Arc, - pub authentication_service: Arc, - pub in_memory_whitelist: Arc, - pub whitelist_authorization: Arc, - pub whitelist_manager: Arc, - pub in_memory_torrent_repository: Arc, - pub db_torrent_repository: Arc, - pub torrents_manager: Arc, + pub tracker_core_container: TrackerCoreContainer, // UDP Tracker Core Services pub udp_core_stats_event_sender: Arc>>, @@ -122,19 +98,7 @@ impl AppContainer { let udp_server_stats_repository = Arc::new(udp_server_stats_repository); AppContainer { - // Tracker Core Services - core_config, - database: tracker_core_container.database, - announce_handler: tracker_core_container.announce_handler, - scrape_handler: tracker_core_container.scrape_handler, - keys_handler: tracker_core_container.keys_handler, - authentication_service: tracker_core_container.authentication_service, - in_memory_whitelist: tracker_core_container.in_memory_whitelist, - whitelist_authorization: tracker_core_container.whitelist_authorization, - whitelist_manager: tracker_core_container.whitelist_manager, - in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository, - db_torrent_repository: tracker_core_container.db_torrent_repository, - torrents_manager: tracker_core_container.torrents_manager, + tracker_core_container, // UDP Tracker Core Services udp_core_stats_event_sender, @@ -159,11 +123,11 @@ impl AppContainer { #[must_use] pub fn http_tracker_container(&self, http_tracker_config: &Arc) -> HttpTrackerCoreContainer { HttpTrackerCoreContainer { - core_config: self.core_config.clone(), - announce_handler: self.announce_handler.clone(), - scrape_handler: self.scrape_handler.clone(), - whitelist_authorization: self.whitelist_authorization.clone(), - authentication_service: self.authentication_service.clone(), + core_config: self.tracker_core_container.core_config.clone(), + announce_handler: self.tracker_core_container.announce_handler.clone(), + scrape_handler: self.tracker_core_container.scrape_handler.clone(), + whitelist_authorization: self.tracker_core_container.whitelist_authorization.clone(), + authentication_service: self.tracker_core_container.authentication_service.clone(), http_tracker_config: http_tracker_config.clone(), http_stats_event_sender: self.http_stats_event_sender.clone(), @@ -176,10 +140,10 @@ impl AppContainer { #[must_use] pub fn udp_tracker_container(&self, udp_tracker_config: &Arc) -> UdpTrackerCoreContainer { UdpTrackerCoreContainer { - core_config: self.core_config.clone(), - announce_handler: self.announce_handler.clone(), - scrape_handler: self.scrape_handler.clone(), - whitelist_authorization: self.whitelist_authorization.clone(), + core_config: self.tracker_core_container.core_config.clone(), + announce_handler: self.tracker_core_container.announce_handler.clone(), + scrape_handler: self.tracker_core_container.scrape_handler.clone(), + whitelist_authorization: self.tracker_core_container.whitelist_authorization.clone(), udp_tracker_config: udp_tracker_config.clone(), udp_core_stats_event_sender: self.udp_core_stats_event_sender.clone(), @@ -194,11 +158,12 @@ impl AppContainer { #[must_use] pub fn tracker_http_api_container(&self, http_api_config: &Arc) -> TrackerHttpApiCoreContainer { TrackerHttpApiCoreContainer { + core_config: self.tracker_core_container.core_config.clone(), + in_memory_torrent_repository: self.tracker_core_container.in_memory_torrent_repository.clone(), + keys_handler: self.tracker_core_container.keys_handler.clone(), + whitelist_manager: self.tracker_core_container.whitelist_manager.clone(), + http_api_config: http_api_config.clone(), - core_config: self.core_config.clone(), - in_memory_torrent_repository: self.in_memory_torrent_repository.clone(), - keys_handler: self.keys_handler.clone(), - whitelist_manager: self.whitelist_manager.clone(), ban_service: self.udp_ban_service.clone(), http_stats_repository: self.http_stats_repository.clone(), udp_core_stats_repository: self.udp_core_stats_repository.clone(), From 0d42586c6034e535ce2a9f812bb2327f6fd3b80b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Mar 2025 17:29:29 +0000 Subject: [PATCH 0907/1297] refactor: encapsule field TrackerCoreContainer in HttpTrackerCoreContainer --- .../axum-http-tracker-server/src/server.rs | 51 ++++--------------- packages/http-tracker-core/src/container.rs | 19 +------ src/container.rs | 11 ++-- 3 files changed, 15 insertions(+), 66 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index ea8003a4f..f14a33602 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -241,15 +241,7 @@ mod tests { use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_http_tracker_core::services::announce::AnnounceService; use bittorrent_http_tracker_core::services::scrape::ScrapeService; - use bittorrent_tracker_core::announce_handler::AnnounceHandler; - use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; - use bittorrent_tracker_core::authentication::service; - use bittorrent_tracker_core::databases::setup::initialize_database; - use bittorrent_tracker_core::scrape_handler::ScrapeHandler; - use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; - use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; - use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use bittorrent_tracker_core::container::TrackerCoreContainer; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; @@ -275,48 +267,25 @@ mod tests { let http_stats_event_sender = Arc::new(http_stats_event_sender); let http_stats_repository = Arc::new(http_stats_repository); - let database = initialize_database(&configuration.core); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&configuration.core, &in_memory_whitelist.clone())); - let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); - let authentication_service = Arc::new(service::AuthenticationService::new( - &configuration.core, - &in_memory_key_repository, - )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - - let announce_handler = Arc::new(AnnounceHandler::new( - &configuration.core, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); let announce_service = Arc::new(AnnounceService::new( - core_config.clone(), - announce_handler.clone(), - authentication_service.clone(), - whitelist_authorization.clone(), + tracker_core_container.core_config.clone(), + tracker_core_container.announce_handler.clone(), + tracker_core_container.authentication_service.clone(), + tracker_core_container.whitelist_authorization.clone(), http_stats_event_sender.clone(), )); let scrape_service = Arc::new(ScrapeService::new( - core_config.clone(), - scrape_handler.clone(), - authentication_service.clone(), + tracker_core_container.core_config.clone(), + tracker_core_container.scrape_handler.clone(), + tracker_core_container.authentication_service.clone(), http_stats_event_sender.clone(), )); HttpTrackerCoreContainer { - core_config, - announce_handler, - scrape_handler, - whitelist_authorization, - authentication_service, - + tracker_core_container, http_tracker_config, http_stats_event_sender, http_stats_repository, diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index bb9b5014c..ce577f1d8 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -1,10 +1,6 @@ use std::sync::Arc; -use bittorrent_tracker_core::announce_handler::AnnounceHandler; -use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::container::TrackerCoreContainer; -use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::{Core, HttpTracker}; use crate::services::announce::AnnounceService; @@ -12,13 +8,7 @@ use crate::services::scrape::ScrapeService; use crate::{event, statistics}; pub struct HttpTrackerCoreContainer { - // todo: replace with TrackerCoreContainer - pub core_config: Arc, - pub announce_handler: Arc, - pub scrape_handler: Arc, - pub whitelist_authorization: Arc, - pub authentication_service: Arc, - + pub tracker_core_container: Arc, pub http_tracker_config: Arc, pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, @@ -59,12 +49,7 @@ impl HttpTrackerCoreContainer { )); Arc::new(Self { - core_config: tracker_core_container.core_config.clone(), - announce_handler: tracker_core_container.announce_handler.clone(), - scrape_handler: tracker_core_container.scrape_handler.clone(), - whitelist_authorization: tracker_core_container.whitelist_authorization.clone(), - authentication_service: tracker_core_container.authentication_service.clone(), - + tracker_core_container: tracker_core_container.clone(), http_tracker_config: http_tracker_config.clone(), http_stats_event_sender: http_stats_event_sender.clone(), http_stats_repository: http_stats_repository.clone(), diff --git a/src/container.rs b/src/container.rs index b02dc8811..ce236dc58 100644 --- a/src/container.rs +++ b/src/container.rs @@ -25,7 +25,7 @@ use tracing::instrument; */ pub struct AppContainer { - pub tracker_core_container: TrackerCoreContainer, + pub tracker_core_container: Arc, // UDP Tracker Core Services pub udp_core_stats_event_sender: Arc>>, @@ -51,7 +51,7 @@ impl AppContainer { pub fn initialize(configuration: &Configuration) -> AppContainer { let core_config = Arc::new(configuration.core.clone()); - let tracker_core_container = TrackerCoreContainer::initialize(&core_config); + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); // HTTP Tracker Core Services let (http_stats_event_sender, http_stats_repository) = @@ -123,12 +123,7 @@ impl AppContainer { #[must_use] pub fn http_tracker_container(&self, http_tracker_config: &Arc) -> HttpTrackerCoreContainer { HttpTrackerCoreContainer { - core_config: self.tracker_core_container.core_config.clone(), - announce_handler: self.tracker_core_container.announce_handler.clone(), - scrape_handler: self.tracker_core_container.scrape_handler.clone(), - whitelist_authorization: self.tracker_core_container.whitelist_authorization.clone(), - authentication_service: self.tracker_core_container.authentication_service.clone(), - + tracker_core_container: self.tracker_core_container.clone(), http_tracker_config: http_tracker_config.clone(), http_stats_event_sender: self.http_stats_event_sender.clone(), http_stats_repository: self.http_stats_repository.clone(), From 239f352ab590ac4e1e908dd5b123ed09e60b59a9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Mar 2025 17:35:58 +0000 Subject: [PATCH 0908/1297] refactor: encapsule field TrackerCoreContainer in UdpTrackerCoreContainer --- packages/udp-tracker-core/src/container.rs | 16 ++-------------- packages/udp-tracker-server/src/handlers/mod.rs | 2 +- .../udp-tracker-server/src/server/launcher.rs | 2 +- src/container.rs | 6 +----- 4 files changed, 5 insertions(+), 21 deletions(-) diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index aaa07f150..2ab578151 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -1,9 +1,6 @@ use std::sync::Arc; -use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::container::TrackerCoreContainer; -use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::whitelist; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, UdpTracker}; @@ -14,12 +11,7 @@ use crate::services::scrape::ScrapeService; use crate::{event, statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; pub struct UdpTrackerCoreContainer { - // todo: replace with TrackerCoreContainer - pub core_config: Arc, - pub announce_handler: Arc, - pub scrape_handler: Arc, - pub whitelist_authorization: Arc, - + pub tracker_core_container: Arc, pub udp_tracker_config: Arc, pub udp_core_stats_event_sender: Arc>>, pub udp_core_stats_repository: Arc, @@ -58,11 +50,7 @@ impl UdpTrackerCoreContainer { )); Arc::new(UdpTrackerCoreContainer { - core_config: tracker_core_container.core_config.clone(), - announce_handler: tracker_core_container.announce_handler.clone(), - scrape_handler: tracker_core_container.scrape_handler.clone(), - whitelist_authorization: tracker_core_container.whitelist_authorization.clone(), - + tracker_core_container: tracker_core_container.clone(), udp_tracker_config: udp_tracker_config.clone(), udp_core_stats_event_sender: udp_core_stats_event_sender.clone(), udp_core_stats_repository: udp_core_stats_repository.clone(), diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 61f7bb187..34ac374fa 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -172,7 +172,7 @@ pub async fn handle_request( client_socket_addr, server_socket_addr, &announce_request, - &udp_tracker_core_container.core_config, + &udp_tracker_core_container.tracker_core_container.core_config, &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range, ) diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index c98db0500..b21ac11ba 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -47,7 +47,7 @@ impl Launcher { ) { tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting on: {bind_to}"); - if udp_tracker_core_container.core_config.private { + if udp_tracker_core_container.tracker_core_container.core_config.private { tracing::error!("udp services cannot be used for private trackers"); panic!("it should not use udp if using authentication"); } diff --git a/src/container.rs b/src/container.rs index ce236dc58..bb872d98f 100644 --- a/src/container.rs +++ b/src/container.rs @@ -135,11 +135,7 @@ impl AppContainer { #[must_use] pub fn udp_tracker_container(&self, udp_tracker_config: &Arc) -> UdpTrackerCoreContainer { UdpTrackerCoreContainer { - core_config: self.tracker_core_container.core_config.clone(), - announce_handler: self.tracker_core_container.announce_handler.clone(), - scrape_handler: self.tracker_core_container.scrape_handler.clone(), - whitelist_authorization: self.tracker_core_container.whitelist_authorization.clone(), - + tracker_core_container: self.tracker_core_container.clone(), udp_tracker_config: udp_tracker_config.clone(), udp_core_stats_event_sender: self.udp_core_stats_event_sender.clone(), udp_core_stats_repository: self.udp_core_stats_repository.clone(), From c785d545771921d8dc66287493231cc6252da968 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 21 Mar 2025 17:40:42 +0000 Subject: [PATCH 0909/1297] refactor: encapsule field TrackerCoreContainer in TrackerHttpApiCoreContainer --- .../src/v1/context/stats/routes.rs | 2 +- .../src/v1/routes.rs | 18 +++++++++++++--- .../rest-tracker-api-core/src/container.rs | 21 ++----------------- src/container.rs | 17 +-------------- 4 files changed, 19 insertions(+), 39 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs index 49ba9e829..e92b5b34d 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs @@ -16,7 +16,7 @@ pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { let v1_prefix = format!("{prefix}/v1"); - let router = auth_key::routes::add(&v1_prefix, router, &http_api_container.keys_handler.clone()); + let router = auth_key::routes::add( + &v1_prefix, + router, + &http_api_container.tracker_core_container.keys_handler.clone(), + ); let router = stats::routes::add(&v1_prefix, router, http_api_container); - let router = whitelist::routes::add(&v1_prefix, router, &http_api_container.whitelist_manager); + let router = whitelist::routes::add( + &v1_prefix, + router, + &http_api_container.tracker_core_container.whitelist_manager, + ); - torrent::routes::add(&v1_prefix, router, &http_api_container.in_memory_torrent_repository.clone()) + torrent::routes::add( + &v1_prefix, + router, + &http_api_container.tracker_core_container.in_memory_torrent_repository.clone(), + ) } diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs index eb770c1c5..c6a46a195 100644 --- a/packages/rest-tracker-api-core/src/container.rs +++ b/packages/rest-tracker-api-core/src/container.rs @@ -1,10 +1,7 @@ use std::sync::Arc; use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; -use bittorrent_tracker_core::authentication::handler::KeysHandler; use bittorrent_tracker_core::container::TrackerCoreContainer; -use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self}; @@ -13,22 +10,11 @@ use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; pub struct TrackerHttpApiCoreContainer { - // todo: replace with TrackerCoreContainer - pub core_config: Arc, - pub in_memory_torrent_repository: Arc, - pub keys_handler: Arc, - pub whitelist_manager: Arc, - - // todo: replace with HttpTrackerCoreContainer + pub tracker_core_container: Arc, pub http_stats_repository: Arc, - - // todo: replace with UdpTrackerCoreContainer pub ban_service: Arc>, pub udp_core_stats_repository: Arc, - - // todo: replace with UdpTrackerServerContainer pub udp_server_stats_repository: Arc, - pub http_api_config: Arc, } @@ -63,10 +49,7 @@ impl TrackerHttpApiCoreContainer { http_api_config: &Arc, ) -> Arc { Arc::new(TrackerHttpApiCoreContainer { - core_config: tracker_core_container.core_config.clone(), - in_memory_torrent_repository: tracker_core_container.in_memory_torrent_repository.clone(), - keys_handler: tracker_core_container.keys_handler.clone(), - whitelist_manager: tracker_core_container.whitelist_manager.clone(), + tracker_core_container: tracker_core_container.clone(), http_stats_repository: http_tracker_core_container.http_stats_repository.clone(), diff --git a/src/container.rs b/src/container.rs index bb872d98f..d3253b5d9 100644 --- a/src/container.rs +++ b/src/container.rs @@ -13,17 +13,6 @@ use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, UdpTrac use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use tracing::instrument; -/* todo: remove duplicate code. - - Use containers from packages as AppContainer fields: - - - bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer - - bittorrent_http_tracker_core::container::HttpTrackerCoreContainer - - torrust_udp_tracker_server::container::UdpTrackerServerContainer - - Container initialization is duplicated. -*/ - pub struct AppContainer { pub tracker_core_container: Arc, @@ -149,11 +138,7 @@ impl AppContainer { #[must_use] pub fn tracker_http_api_container(&self, http_api_config: &Arc) -> TrackerHttpApiCoreContainer { TrackerHttpApiCoreContainer { - core_config: self.tracker_core_container.core_config.clone(), - in_memory_torrent_repository: self.tracker_core_container.in_memory_torrent_repository.clone(), - keys_handler: self.tracker_core_container.keys_handler.clone(), - whitelist_manager: self.tracker_core_container.whitelist_manager.clone(), - + tracker_core_container: self.tracker_core_container.clone(), http_api_config: http_api_config.clone(), ban_service: self.udp_ban_service.clone(), http_stats_repository: self.http_stats_repository.clone(), From c7c87a20d0a176f3d5f1a26c82aee594ece04845 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Mar 2025 07:11:45 +0000 Subject: [PATCH 0910/1297] chore(deps): udpate dependencies ``` cargo update Updating crates.io index Locking 53 packages to latest compatible versions Updating async-compression v0.4.20 -> v0.4.21 Updating async-std v1.13.0 -> v1.13.1 Updating async-trait v0.1.87 -> v0.1.88 Updating axum-server v0.7.1 -> v0.7.2 Updating borsh v1.5.5 -> v1.5.6 Updating borsh-derive v1.5.5 -> v1.5.6 Updating cc v1.2.16 -> v1.2.17 Updating deranged v0.3.11 -> v0.4.1 Updating foldhash v0.1.4 -> v0.1.5 Adding fs-err v3.1.0 Updating getrandom v0.3.1 -> v0.3.2 Updating half v2.4.1 -> v2.5.0 Updating http v1.2.0 -> v1.3.1 Updating http-body-util v0.1.2 -> v0.1.3 Updating iana-time-zone v0.1.61 -> v0.1.62 Updating libz-sys v1.1.21 -> v1.1.22 Updating linux-raw-sys v0.9.2 -> v0.9.3 Updating once_cell v1.21.0 -> v1.21.1 Removing pin-project v1.1.10 Removing pin-project-internal v1.1.10 Updating quote v1.0.39 -> v1.0.40 Adding r-efi v5.2.0 Updating reqwest v0.12.12 -> v0.12.15 Updating ring v0.17.13 -> v0.17.14 Updating rust_decimal v1.36.0 -> v1.37.1 Updating rustix v1.0.2 -> v1.0.3 Updating rustls v0.23.23 -> v0.23.25 Updating rustls-webpki v0.102.8 -> v0.103.0 Updating tempfile v3.18.0 -> v3.19.1 Updating time v0.3.39 -> v0.3.41 Updating time-core v0.1.3 -> v0.1.4 Updating time-macros v0.2.20 -> v0.2.22 Updating tokio v1.44.0 -> v1.44.1 Updating tokio-util v0.7.13 -> v0.7.14 Removing tower v0.4.13 Updating uuid v1.15.1 -> v1.16.0 Updating wasi v0.13.3+wasi-0.2.2 -> v0.14.2+wasi-0.2.4 Updating windows-link v0.1.0 -> v0.1.1 Updating windows-registry v0.2.0 -> v0.4.0 Updating windows-result v0.2.0 -> v0.3.2 Updating windows-strings v0.1.0 -> v0.3.1 Adding windows-targets v0.53.0 Adding windows_aarch64_gnullvm v0.53.0 Adding windows_aarch64_msvc v0.53.0 Adding windows_i686_gnu v0.53.0 Adding windows_i686_gnullvm v0.53.0 Adding windows_i686_msvc v0.53.0 Adding windows_x86_64_gnu v0.53.0 Adding windows_x86_64_gnullvm v0.53.0 Adding windows_x86_64_msvc v0.53.0 Updating winnow v0.7.3 -> v0.7.4 Updating wit-bindgen-rt v0.33.0 -> v0.39.0 Updating zerocopy v0.8.23 -> v0.8.24 Updating zerocopy-derive v0.8.23 -> v0.8.24 Updating zstd-safe v7.2.3 -> v7.2.4 Updating zstd-sys v2.0.14+zstd.1.5.7 -> v2.0.15+zstd.1.5.7 ``` --- Cargo.lock | 334 ++++++++++++++++++++++++++++++----------------------- 1 file changed, 188 insertions(+), 146 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4d5157055..076449944 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -208,9 +208,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.20" +version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "310c9bcae737a48ef5cdee3174184e6d548b292739ede61a1f955ef76a738861" +checksum = "c0cf008e5e1a9e9e22a7d3c9a4992e21a350290069e36d8fb72304ed17e8f2d2" dependencies = [ "brotli", "flate2", @@ -283,9 +283,9 @@ dependencies = [ [[package]] name = "async-std" -version = "1.13.0" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c634475f29802fde2b8f0b505b1bd00dfe4df7d4a000f0b36f7671197d5c3615" +checksum = "730294c1c08c2e0f85759590518f6333f0d5a0a766a27d519c1b244c3dfd8a24" dependencies = [ "async-attributes", "async-channel 1.9.0", @@ -316,9 +316,9 @@ checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" [[package]] name = "async-trait" -version = "0.1.87" +version = "0.1.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d556ec1359574147ec0c4fc5eb525f3f23263a592b1a9c07e0a75b427de55c97" +checksum = "e539d3fca749fcee5236ab05e93a52867dd549cc157c8cb7f99595f3cedffdb5" dependencies = [ "proc-macro2", "quote", @@ -375,7 +375,7 @@ dependencies = [ "serde_urlencoded", "sync_wrapper", "tokio", - "tower 0.5.2", + "tower", "tower-layer", "tower-service", "tracing", @@ -431,7 +431,7 @@ dependencies = [ "serde", "serde_html_form", "serde_path_to_error", - "tower 0.5.2", + "tower", "tower-layer", "tower-service", ] @@ -449,16 +449,15 @@ dependencies = [ [[package]] name = "axum-server" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56bac90848f6a9393ac03c63c640925c4b7c8ca21654de40d53f55964667c7d8" +checksum = "495c05f60d6df0093e8fb6e74aa5846a0ad06abaf96d76166283720bf740f8ab" dependencies = [ "arc-swap", "bytes", - "futures-util", + "fs-err", "http", "http-body", - "http-body-util", "hyper", "hyper-util", "pin-project-lite", @@ -467,7 +466,6 @@ dependencies = [ "rustls-pki-types", "tokio", "tokio-rustls", - "tower 0.4.13", "tower-service", ] @@ -798,9 +796,9 @@ dependencies = [ [[package]] name = "borsh" -version = "1.5.5" +version = "1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5430e3be710b68d984d1391c854eb431a9d548640711faa54eecb1df93db91cc" +checksum = "b2b74d67a0fc0af8e9823b79fd1c43a0900e5a8f0e0f4cc9210796bf3a820126" dependencies = [ "borsh-derive", "cfg_aliases", @@ -808,9 +806,9 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.5.5" +version = "1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8b668d39970baad5356d7c83a86fee3a539e6f93bf6764c97368243e17a0487" +checksum = "2d37ed1b2c9b78421218a0b4f6d8349132d6ec2cfeba1cfb0118b0a8e268df9e" dependencies = [ "once_cell", "proc-macro-crate", @@ -927,9 +925,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.16" +version = "1.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be714c154be609ec7f5dad223a33bf1482fff90472de28f7362806e6d4832b8c" +checksum = "1fcb57c740ae1daf453ae85f16e37396f672b039e00d9d866e07ddb24e328e3a" dependencies = [ "jobserver", "libc", @@ -1310,9 +1308,9 @@ dependencies = [ [[package]] name = "deranged" -version = "0.3.11" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +checksum = "28cfac68e08048ae1883171632c2aef3ebc555621ae56fbccce1cbf22dd7f058" dependencies = [ "powerfmt", "serde", @@ -1532,9 +1530,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "foldhash" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0d2fde1f7b3d48b8395d5f2de76c18a528bd6a9cdde438df747bfcba3e05d6f" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" [[package]] name = "foreign-types" @@ -1632,6 +1630,16 @@ dependencies = [ "syn 2.0.100", ] +[[package]] +name = "fs-err" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f89bda4c2a21204059a977ed3bfe746677dfd137b83c339e702b0ac91d482aa" +dependencies = [ + "autocfg", + "tokio", +] + [[package]] name = "funty" version = "2.0.0" @@ -1769,14 +1777,14 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8" +checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" dependencies = [ "cfg-if", "libc", - "wasi 0.13.3+wasi-0.2.2", - "windows-targets 0.52.6", + "r-efi", + "wasi 0.14.2+wasi-0.2.4", ] [[package]] @@ -1824,9 +1832,9 @@ dependencies = [ [[package]] name = "half" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dd08c532ae367adf81c312a4580bc67f1d0fe8bc9c460520283f4c0ff277888" +checksum = "7db2ff139bba50379da6aa0766b52fdcb62cb5b263009b09ed58ba604e14bbd1" dependencies = [ "cfg-if", "crunchy", @@ -1908,9 +1916,9 @@ dependencies = [ [[package]] name = "http" -version = "1.2.0" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f16ca2af56261c99fba8bac40a10251ce8188205a4c448fbb745a2e4daa76fea" +checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" dependencies = [ "bytes", "fnv", @@ -1929,12 +1937,12 @@ dependencies = [ [[package]] name = "http-body-util" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" dependencies = [ "bytes", - "futures-util", + "futures-core", "http", "http-body", "pin-project-lite", @@ -2057,14 +2065,15 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.61" +version = "0.1.62" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" +checksum = "b2fd658b06e56721792c5df4475705b6cda790e9298d19d2f8af083457bcd127" dependencies = [ "android_system_properties", "core-foundation-sys", "iana-time-zone-haiku", "js-sys", + "log", "wasm-bindgen", "windows-core", ] @@ -2396,9 +2405,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.21" +version = "1.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df9b68e50e6e0b26f672573834882eb57759f6db9b3be2ea3c35c91188bb4eaa" +checksum = "8b70e7a7df205e92a1a4cd9aaae7898dac0aa555503cc0a649494d0d60e7651d" dependencies = [ "cc", "pkg-config", @@ -2413,9 +2422,9 @@ checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] name = "linux-raw-sys" -version = "0.9.2" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db9c683daf087dc577b7506e9695b3d556a9f3849903fa28186283afd6809e9" +checksum = "fe7db12097d22ec582439daf8618b8fdd1a7bef6270e9af3b1ebcd30893cf413" [[package]] name = "litemap" @@ -2746,9 +2755,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.21.0" +version = "1.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cde51589ab56b20a6f686b2c68f7a0bd6add753d697abf720d63f8db3ab7b1ad" +checksum = "d75b0bedcc4fe52caa0e03d9f1151a323e4aa5e2d78ba3580400cd3c9e2bc4bc" [[package]] name = "oorandom" @@ -2937,26 +2946,6 @@ dependencies = [ "siphasher", ] -[[package]] -name = "pin-project" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.100", -] - [[package]] name = "pin-project-lite" version = "0.2.16" @@ -3047,7 +3036,7 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ - "zerocopy 0.8.23", + "zerocopy 0.8.24", ] [[package]] @@ -3162,13 +3151,19 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.39" +version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1f1914ce909e1658d9907913b4b91947430c7d9be598b15a1912935b8c04801" +checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" + [[package]] name = "r2d2" version = "0.8.10" @@ -3226,7 +3221,7 @@ checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.3", - "zerocopy 0.8.23", + "zerocopy 0.8.24", ] [[package]] @@ -3264,7 +3259,7 @@ version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ - "getrandom 0.3.1", + "getrandom 0.3.2", ] [[package]] @@ -3351,9 +3346,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.12" +version = "0.12.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43e734407157c3c2034e0258f5e4473ddb361b1e85f95a66690d67264d7cd1da" +checksum = "d19c46a6fdd48bc4dab94b6103fccc55d34c67cc0ad04653aad4ea2a07cd7bbb" dependencies = [ "base64 0.22.1", "bytes", @@ -3384,7 +3379,7 @@ dependencies = [ "system-configuration", "tokio", "tokio-native-tls", - "tower 0.5.2", + "tower", "tower-service", "url", "wasm-bindgen", @@ -3395,9 +3390,9 @@ dependencies = [ [[package]] name = "ring" -version = "0.17.13" +version = "0.17.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ac5d832aa16abd7d1def883a8545280c20a60f523a370aa3a9617c2b8550ee" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" dependencies = [ "cc", "cfg-if", @@ -3492,9 +3487,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.36.0" +version = "1.37.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b082d80e3e3cc52b2ed634388d436fe1f4de6af5786cc2de9ba9737527bdf555" +checksum = "faa7de2ba56ac291bd90c6b9bece784a52ae1411f9506544b3eae36dd2356d50" dependencies = [ "arrayvec", "borsh", @@ -3542,22 +3537,22 @@ dependencies = [ [[package]] name = "rustix" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7178faa4b75a30e269c71e61c353ce2748cf3d76f0c44c393f4e60abf49b825" +checksum = "e56a18552996ac8d29ecc3b190b4fdbb2d91ca4ec396de7bbffaf43f3d637e96" dependencies = [ "bitflags 2.9.0", "errno", "libc", - "linux-raw-sys 0.9.2", + "linux-raw-sys 0.9.3", "windows-sys 0.59.0", ] [[package]] name = "rustls" -version = "0.23.23" +version = "0.23.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47796c98c480fce5406ef69d1c76378375492c3b0a0de587be0c1d9feb12f395" +checksum = "822ee9188ac4ec04a2f0531e55d035fb2de73f18b41a63c70c2712503b6fb13c" dependencies = [ "once_cell", "ring", @@ -3596,9 +3591,9 @@ checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c" [[package]] name = "rustls-webpki" -version = "0.102.8" +version = "0.103.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" +checksum = "0aa4eeac2588ffff23e9d7a7e9b3f971c5fb5b7ebc9452745e0c232c64f83b2f" dependencies = [ "ring", "rustls-pki-types", @@ -4069,15 +4064,14 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.18.0" +version = "3.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c317e0a526ee6120d8dabad239c8dadca62b24b6f168914bbbc8e2fb1f0e567" +checksum = "7437ac7763b9b123ccf33c338a5cc1bac6f69b45a136c19bdd8a65e3916435bf" dependencies = [ - "cfg-if", "fastrand", - "getrandom 0.3.1", + "getrandom 0.3.2", "once_cell", - "rustix 1.0.2", + "rustix 1.0.3", "windows-sys 0.59.0", ] @@ -4177,9 +4171,9 @@ dependencies = [ [[package]] name = "time" -version = "0.3.39" +version = "0.3.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dad298b01a40a23aac4580b67e3dbedb7cc8402f3592d7f49469de2ea4aecdd8" +checksum = "8a7619e19bc266e0f9c5e6686659d394bc57973859340060a69221e57dbc0c40" dependencies = [ "deranged", "itoa", @@ -4192,15 +4186,15 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "765c97a5b985b7c11d7bc27fa927dc4fe6af3a6dfb021d28deb60d3bf51e76ef" +checksum = "c9e9a38711f559d9e3ce1cdb06dd7c5b8ea546bc90052da6d06bb76da74bb07c" [[package]] name = "time-macros" -version = "0.2.20" +version = "0.2.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8093bc3e81c3bc5f7879de09619d06c9a5a5e45ca44dfeeb7225bae38005c5c" +checksum = "3526739392ec93fd8b359c8e98514cb3e8e021beb4e5f597b00a0221f8ed8a49" dependencies = [ "num-conv", "time-core", @@ -4243,9 +4237,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.44.0" +version = "1.44.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9975ea0f48b5aa3972bf2d888c238182458437cc2a19374b81b25cdf1023fb3a" +checksum = "f382da615b842244d4b8738c82ed1275e6c5dd90c459a30941cd07080b06c91a" dependencies = [ "backtrace", "bytes", @@ -4317,9 +4311,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.13" +version = "0.7.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7fcaa8d55a2bdd6b83ace262b016eca0d79ee02818c5c1bcdf0305114081078" +checksum = "6b9590b93e6fcc1739458317cccd391ad3955e2bde8913edf6f95f9e65a8f034" dependencies = [ "bytes", "futures-core", @@ -4418,7 +4412,7 @@ dependencies = [ "torrust-tracker-configuration", "torrust-tracker-primitives", "torrust-tracker-test-helpers", - "tower 0.5.2", + "tower", "tower-http", "tracing", "uuid", @@ -4457,7 +4451,7 @@ dependencies = [ "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-udp-tracker-server", - "tower 0.5.2", + "tower", "tower-http", "tracing", "url", @@ -4480,7 +4474,7 @@ dependencies = [ "torrust-server-lib", "torrust-tracker-configuration", "torrust-tracker-located-error", - "tower 0.5.2", + "tower", "tracing", ] @@ -4701,21 +4695,6 @@ dependencies = [ "zerocopy 0.7.35", ] -[[package]] -name = "tower" -version = "0.4.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" -dependencies = [ - "futures-core", - "futures-util", - "pin-project", - "pin-project-lite", - "tower-layer", - "tower-service", - "tracing", -] - [[package]] name = "tower" version = "0.5.2" @@ -4918,11 +4897,11 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.15.1" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0f540e3240398cce6128b64ba83fdbdd86129c16a3aa1a3a252efd66eb3d587" +checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9" dependencies = [ - "getrandom 0.3.1", + "getrandom 0.3.2", "rand 0.9.0", ] @@ -4977,9 +4956,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasi" -version = "0.13.3+wasi-0.2.2" +version = "0.14.2+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2" +checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" dependencies = [ "wit-bindgen-rt", ] @@ -5107,38 +5086,37 @@ dependencies = [ [[package]] name = "windows-link" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dccfd733ce2b1753b03b6d3c65edf020262ea35e20ccdf3e288043e6dd620e3" +checksum = "76840935b766e1b0a05c0066835fb9ec80071d4c09a16f6bd5f7e655e3c14c38" [[package]] name = "windows-registry" -version = "0.2.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e400001bb720a623c1c69032f8e3e4cf09984deec740f007dd2b03ec864804b0" +checksum = "4286ad90ddb45071efd1a66dfa43eb02dd0dfbae1545ad6cc3c51cf34d7e8ba3" dependencies = [ "windows-result", "windows-strings", - "windows-targets 0.52.6", + "windows-targets 0.53.0", ] [[package]] name = "windows-result" -version = "0.2.0" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +checksum = "c64fd11a4fd95df68efcfee5f44a294fe71b8bc6a91993e2791938abcc712252" dependencies = [ - "windows-targets 0.52.6", + "windows-link", ] [[package]] name = "windows-strings" -version = "0.1.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +checksum = "87fa48cc5d406560701792be122a10132491cff9d0aeb23583cc2dcafc847319" dependencies = [ - "windows-result", - "windows-targets 0.52.6", + "windows-link", ] [[package]] @@ -5192,13 +5170,29 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", + "windows_i686_gnullvm 0.52.6", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-targets" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e4c7e8ceaaf9cb7d7507c974735728ab453b67ef8f18febdd7c11fe59dca8b" +dependencies = [ + "windows_aarch64_gnullvm 0.53.0", + "windows_aarch64_msvc 0.53.0", + "windows_i686_gnu 0.53.0", + "windows_i686_gnullvm 0.53.0", + "windows_i686_msvc 0.53.0", + "windows_x86_64_gnu 0.53.0", + "windows_x86_64_gnullvm 0.53.0", + "windows_x86_64_msvc 0.53.0", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -5211,6 +5205,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" + [[package]] name = "windows_aarch64_msvc" version = "0.48.5" @@ -5223,6 +5223,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" + [[package]] name = "windows_i686_gnu" version = "0.48.5" @@ -5235,12 +5241,24 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" + [[package]] name = "windows_i686_msvc" version = "0.48.5" @@ -5253,6 +5271,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" + [[package]] name = "windows_x86_64_gnu" version = "0.48.5" @@ -5265,6 +5289,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" + [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" @@ -5277,6 +5307,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" + [[package]] name = "windows_x86_64_msvc" version = "0.48.5" @@ -5289,20 +5325,26 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" + [[package]] name = "winnow" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e7f4ea97f6f78012141bcdb6a216b2609f0979ada50b20ca5b52dde2eac2bb1" +checksum = "0e97b544156e9bebe1a0ffbc03484fc1ffe3100cbce3ffb17eac35f7cdd7ab36" dependencies = [ "memchr", ] [[package]] name = "wit-bindgen-rt" -version = "0.33.0" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" +checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ "bitflags 2.9.0", ] @@ -5335,7 +5377,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d65cbf2f12c15564212d48f4e3dfb87923d25d611f2aed18f4cb23f0413d89e" dependencies = [ "libc", - "rustix 1.0.2", + "rustix 1.0.3", ] [[package]] @@ -5380,11 +5422,11 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.23" +version = "0.8.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd97444d05a4328b90e75e503a34bad781f14e28a823ad3557f0750df1ebcbc6" +checksum = "2586fea28e186957ef732a5f8b3be2da217d65c5969d4b1e17f973ebbe876879" dependencies = [ - "zerocopy-derive 0.8.23", + "zerocopy-derive 0.8.24", ] [[package]] @@ -5400,9 +5442,9 @@ dependencies = [ [[package]] name = "zerocopy-derive" -version = "0.8.23" +version = "0.8.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6352c01d0edd5db859a63e2605f4ea3183ddbd15e2c4a9e7d32184df75e4f154" +checksum = "a996a8f63c5c4448cd959ac1bab0aaa3306ccfd060472f85943ee0750f0169be" dependencies = [ "proc-macro2", "quote", @@ -5469,18 +5511,18 @@ dependencies = [ [[package]] name = "zstd-safe" -version = "7.2.3" +version = "7.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3051792fbdc2e1e143244dc28c60f73d8470e93f3f9cbd0ead44da5ed802722" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.0.14+zstd.1.5.7" +version = "2.0.15+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fb060d4926e4ac3a3ad15d864e99ceb5f343c6b34f5bd6d81ae6ed417311be5" +checksum = "eb81183ddd97d0c74cedf1d50d85c8d08c1b8b68ee863bdee9e706eedba1a237" dependencies = [ "cc", "pkg-config", From a6608cbb8bc0aa1d3207d8a69bdcfa785cc463fe Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Mar 2025 08:26:15 +0000 Subject: [PATCH 0911/1297] fix: clippy errors --- packages/rest-tracker-api-client/src/v1/client.rs | 11 ++++++----- packages/tracker-client/src/http/client/mod.rs | 13 +++++++------ src/bootstrap/jobs/health_check_api.rs | 2 +- src/bootstrap/jobs/tracker_apis.rs | 2 +- 4 files changed, 15 insertions(+), 13 deletions(-) diff --git a/packages/rest-tracker-api-client/src/v1/client.rs b/packages/rest-tracker-api-client/src/v1/client.rs index da1b709da..3137b8b41 100644 --- a/packages/rest-tracker-api-client/src/v1/client.rs +++ b/packages/rest-tracker-api-client/src/v1/client.rs @@ -16,10 +16,11 @@ const API_PATH: &str = "api/v1/"; const DEFAULT_REQUEST_TIMEOUT_IN_SECS: u64 = 5; /// API Client +#[allow(clippy::struct_field_names)] pub struct Client { connection_info: ConnectionInfo, base_path: String, - client: reqwest::Client, + http_client: reqwest::Client, } impl Client { @@ -34,7 +35,7 @@ impl Client { Ok(Self { connection_info, base_path: API_PATH.to_string(), - client, + http_client: client, }) } @@ -92,7 +93,7 @@ impl Client { /// /// Will panic if the request can't be sent pub async fn post_empty(&self, path: &str, headers: Option) -> Response { - let builder = self.client.post(self.base_url(path).clone()); + let builder = self.http_client.post(self.base_url(path).clone()); let builder = match headers { Some(headers) => builder.headers(headers), @@ -111,7 +112,7 @@ impl Client { /// /// Will panic if the request can't be sent pub async fn post_form(&self, path: &str, form: &T, headers: Option) -> Response { - let builder = self.client.post(self.base_url(path).clone()).json(&form); + let builder = self.http_client.post(self.base_url(path).clone()).json(&form); let builder = match headers { Some(headers) => builder.headers(headers), @@ -130,7 +131,7 @@ impl Client { /// /// Will panic if the request can't be sent async fn delete(&self, path: &str, headers: Option) -> Response { - let builder = self.client.delete(self.base_url(path).clone()); + let builder = self.http_client.delete(self.base_url(path).clone()); let builder = match headers { Some(headers) => builder.headers(headers), diff --git a/packages/tracker-client/src/http/client/mod.rs b/packages/tracker-client/src/http/client/mod.rs index 3c904a7c9..50e979c79 100644 --- a/packages/tracker-client/src/http/client/mod.rs +++ b/packages/tracker-client/src/http/client/mod.rs @@ -23,8 +23,9 @@ pub enum Error { } /// HTTP Tracker Client +#[allow(clippy::struct_field_names)] pub struct Client { - client: reqwest::Client, + http_client: reqwest::Client, base_url: Url, key: Option, } @@ -49,7 +50,7 @@ impl Client { Ok(Self { base_url, - client, + http_client: client, key: None, }) } @@ -68,7 +69,7 @@ impl Client { Ok(Self { base_url, - client, + http_client: client, key: None, }) } @@ -84,7 +85,7 @@ impl Client { Ok(Self { base_url, - client, + http_client: client, key: Some(key), }) } @@ -159,7 +160,7 @@ impl Client { /// /// This method fails if there was an error while sending request. pub async fn get(&self, path: &str) -> Result { - self.client + self.http_client .get(self.build_url(path)) .send() .await @@ -170,7 +171,7 @@ impl Client { /// /// This method fails if there was an error while sending request. pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Result { - self.client + self.http_client .get(self.build_url(path)) .header(key, value) .send() diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index 5d342a7f0..7c529fadd 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -3,7 +3,7 @@ //! The [`health_check_api::start_job`](crate::bootstrap::jobs::health_check_api::start_job) //! function starts the Health Check REST API. //! -//! The [`health_check_api::start_job`](crate::bootstrap::jobs::health_check_api::start_job) +//! The [`health_check_api::start_job`](crate::bootstrap::jobs::health_check_api::start_job) //! function spawns a new asynchronous task, that tasks is the "**launcher**". //! The "**launcher**" starts the actual server and sends a message back //! to the main application. diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index d152e853f..9f3964c20 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -7,7 +7,7 @@ //! > versions. API consumers can choose which version to use. The API version is //! > part of the URL, for example: `http://localhost:1212/api/v1/stats`. //! -//! The [`tracker_apis::start_job`](crate::bootstrap::jobs::tracker_apis::start_job) +//! The [`tracker_apis::start_job`](crate::bootstrap::jobs::tracker_apis::start_job) //! function spawns a new asynchronous task, that tasks is the "**launcher**". //! The "**launcher**" starts the actual server and sends a message back //! to the main application. The main application waits until receives From 85109900a9e8c6d943246e0cfd8fc32ddcf22d47 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Mar 2025 12:15:47 +0000 Subject: [PATCH 0912/1297] test: [#1407] add test for global metrics with 2 http trackers A new integration test that checks that the global metrics are udapted when you run 2 HTTP trackers. Ony one metric is checked in this test. It uses fixed port that migth conflict with other running instances in the future. We should use a random free port if we run more integration tests like this in the future. --- Cargo.lock | 2 + Cargo.toml | 2 + src/app.rs | 2 + tests/servers/api/contract/mod.rs | 1 + tests/servers/api/contract/stats/mod.rs | 95 +++++++++++++++++++++++++ tests/servers/api/mod.rs | 1 + tests/servers/mod.rs | 1 + 7 files changed, 104 insertions(+) create mode 100644 tests/servers/api/contract/mod.rs create mode 100644 tests/servers/api/contract/stats/mod.rs create mode 100644 tests/servers/api/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 076449944..055c02a9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4521,6 +4521,8 @@ dependencies = [ "anyhow", "axum-server", "bittorrent-http-tracker-core", + "bittorrent-primitives", + "bittorrent-tracker-client", "bittorrent-tracker-core", "bittorrent-udp-tracker-core", "chrono", diff --git a/Cargo.toml b/Cargo.toml index bcac4bf66..91393ad72 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,6 +60,8 @@ tracing = "0" tracing-subscriber = { version = "0", features = ["json"] } [dev-dependencies] +bittorrent-primitives = "0.1.0" +bittorrent-tracker-client = { version = "3.0.0-develop", path = "packages/tracker-client" } local-ip-address = "0" mockall = "0" torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "packages/rest-tracker-api-client" } diff --git a/src/app.rs b/src/app.rs index fb8a459ea..fcd650c24 100644 --- a/src/app.rs +++ b/src/app.rs @@ -138,6 +138,8 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> )); } + println!("Registar entries: {:?}", registar.entries()); + // Start Health Check API jobs.push(health_check_api::start_job(&config.health_check_api, registar.entries()).await); diff --git a/tests/servers/api/contract/mod.rs b/tests/servers/api/contract/mod.rs new file mode 100644 index 000000000..9d34677fc --- /dev/null +++ b/tests/servers/api/contract/mod.rs @@ -0,0 +1 @@ +pub mod stats; diff --git a/tests/servers/api/contract/stats/mod.rs b/tests/servers/api/contract/stats/mod.rs new file mode 100644 index 000000000..fa7b4e6aa --- /dev/null +++ b/tests/servers/api/contract/stats/mod.rs @@ -0,0 +1,95 @@ +use std::env; +use std::str::FromStr as _; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_client::http::client::requests::announce::QueryBuilder; +use bittorrent_tracker_client::http::client::Client as HttpTrackerClient; +use reqwest::Url; +use serde::Deserialize; +use tokio::time::Duration; +use torrust_rest_tracker_api_client::connection_info::{ConnectionInfo, Origin}; +use torrust_rest_tracker_api_client::v1::client::Client as TrackerApiClient; +use torrust_tracker_lib::{app, bootstrap}; + +#[tokio::test] +async fn the_stats_api_endpoint_should_return_the_global_stats() { + // Logging must be OFF otherwise your will get the following error: + // `Unable to install global subscriber: SetGlobalDefaultError("a global default trace dispatcher has already been set")` + // That's because we can't initialize the logger twice. + // You can enable it if you run only this test. + let config_with_two_http_trackers = r#" + [metadata] + app = "torrust-tracker" + purpose = "configuration" + schema_version = "2.0.0" + + [logging] + threshold = "off" + + [core] + listed = false + private = false + + [[http_trackers]] + bind_address = "0.0.0.0:7272" + tracker_usage_statistics = true + + [[http_trackers]] + bind_address = "0.0.0.0:7373" + tracker_usage_statistics = true + + [http_api] + bind_address = "0.0.0.0:1414" + + [http_api.access_tokens] + admin = "MyAccessToken" + "#; + + env::set_var("TORRUST_TRACKER_CONFIG_TOML", config_with_two_http_trackers); + + let (config, app_container) = bootstrap::app::setup(); + + let app_container = Arc::new(app_container); + + let _jobs = app::start(&config, &app_container).await; + + announce_to_tracker("http://127.0.0.1:7272").await; + announce_to_tracker("http://127.0.0.1:7373").await; + + let partial_metrics = get_partial_metrics("http://127.0.0.1:1414", "MyAccessToken").await; + + assert_eq!(partial_metrics.tcp4_announces_handled, 2); +} + +/// Make a sample announce request to the tracker. +async fn announce_to_tracker(tracker_url: &str) { + let response = HttpTrackerClient::new(Url::parse(tracker_url).unwrap(), Duration::from_secs(1)) + .unwrap() + .announce( + &QueryBuilder::with_default_values() + .with_info_hash(&InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap()) // DevSkim: ignore DS173237 + .query(), + ) + .await; + + assert!(response.is_ok()); +} + +/// Metrics only relevant to the test. +#[derive(Deserialize)] +struct PartialMetrics { + tcp4_announces_handled: u64, +} + +async fn get_partial_metrics(aip_url: &str, token: &str) -> PartialMetrics { + let response = TrackerApiClient::new(ConnectionInfo::authenticated(Origin::new(aip_url).unwrap(), token)) + .unwrap() + .get_tracker_statistics(None) + .await; + + response + .json::() + .await + .expect("Failed to parse JSON response") +} diff --git a/tests/servers/api/mod.rs b/tests/servers/api/mod.rs new file mode 100644 index 000000000..2943dbb50 --- /dev/null +++ b/tests/servers/api/mod.rs @@ -0,0 +1 @@ +pub mod contract; diff --git a/tests/servers/mod.rs b/tests/servers/mod.rs index 7aeefeec4..0bbd5c433 100644 --- a/tests/servers/mod.rs +++ b/tests/servers/mod.rs @@ -1 +1,2 @@ +pub mod api; pub mod health_check_api; From eeea77a9c61d59ef90124639519b8c945b36d1e4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Mar 2025 12:24:26 +0000 Subject: [PATCH 0913/1297] chore: remove sample integration test now that we have a real one. --- tests/integration.rs | 7 ++++--- tests/servers/health_check_api.rs | 32 ------------------------------- tests/servers/mod.rs | 1 - 3 files changed, 4 insertions(+), 36 deletions(-) delete mode 100644 tests/servers/health_check_api.rs diff --git a/tests/integration.rs b/tests/integration.rs index 6a139e047..92289c415 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -1,13 +1,14 @@ //! Scaffolding for integration tests. //! +//! Integration tests are used to test the interaction between multiple modules, +//! multiple running trackers, etc. Tests for one specific module should be in +//! the corresponding package. +//! //! ```text //! cargo test --test integration //! ``` mod servers; -// todo: there is only one test example that was copied from other package. -// We have to add tests for the whole app. - use torrust_tracker_clock::clock; /// This code needs to be copied into each crate. diff --git a/tests/servers/health_check_api.rs b/tests/servers/health_check_api.rs deleted file mode 100644 index 0e66014da..000000000 --- a/tests/servers/health_check_api.rs +++ /dev/null @@ -1,32 +0,0 @@ -use reqwest::Response; -use torrust_axum_health_check_api_server::environment::Started; -use torrust_axum_health_check_api_server::resources::{Report, Status}; -use torrust_server_lib::registar::Registar; -use torrust_tracker_test_helpers::{configuration, logging}; - -pub async fn get(path: &str) -> Response { - reqwest::Client::builder().build().unwrap().get(path).send().await.unwrap() -} - -#[tokio::test] -async fn the_health_check_endpoint_should_return_status_ok_when_there_is_not_any_service_registered() { - logging::setup(); - - let configuration = configuration::ephemeral_with_no_services(); - - let env = Started::new(&configuration.health_check_api.into(), Registar::default()).await; - - let response = get(&format!("http://{}/health_check", env.state.binding)).await; // DevSkim: ignore DS137138 - - assert_eq!(response.status(), 200); - assert_eq!(response.headers().get("content-type").unwrap(), "application/json"); - - let report = response - .json::() - .await - .expect("it should be able to get the report as json"); - - assert_eq!(report.status, Status::None); - - env.stop().await.expect("it should stop the service"); -} diff --git a/tests/servers/mod.rs b/tests/servers/mod.rs index 0bbd5c433..e5fdf85ee 100644 --- a/tests/servers/mod.rs +++ b/tests/servers/mod.rs @@ -1,2 +1 @@ pub mod api; -pub mod health_check_api; From 398ad9bad7fa7af67ddfe8de5dbc356871ed51b4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Mar 2025 12:33:50 +0000 Subject: [PATCH 0914/1297] refactor: remove duplicate code --- src/app.rs | 15 +++++++++++++-- src/console/profiling.rs | 2 +- src/main.rs | 10 ++-------- tests/servers/api/contract/stats/mod.rs | 9 ++------- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/app.rs b/src/app.rs index fcd650c24..007eb16d0 100644 --- a/src/app.rs +++ b/src/app.rs @@ -28,9 +28,20 @@ use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::Configuration; use tracing::instrument; +use crate::bootstrap; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; use crate::container::AppContainer; +pub async fn run() -> (Arc, Vec>, Registar) { + let (config, app_container) = bootstrap::app::setup(); + + let app_container = Arc::new(app_container); + + let (jobs, registar) = start(&config, &app_container).await; + + (app_container, jobs, registar) +} + /// # Panics /// /// Will panic if: @@ -38,7 +49,7 @@ use crate::container::AppContainer; /// - Can't retrieve tracker keys from database. /// - Can't load whitelist from database. #[instrument(skip(config, app_container))] -pub async fn start(config: &Configuration, app_container: &Arc) -> Vec> { +pub async fn start(config: &Configuration, app_container: &Arc) -> (Vec>, Registar) { if config.http_api.is_none() && (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) && (config.http_trackers.is_none() || config.http_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) @@ -143,5 +154,5 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> // Start Health Check API jobs.push(health_check_api::start_job(&config.health_check_api, registar.entries()).await); - jobs + (jobs, registar) } diff --git a/src/console/profiling.rs b/src/console/profiling.rs index f3829c073..ffbd835fb 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -184,7 +184,7 @@ pub async fn run() { let app_container = Arc::new(app_container); - let jobs = app::start(&config, &app_container).await; + let (jobs, _registar) = app::start(&config, &app_container).await; // Run the tracker for a fixed duration let run_duration = sleep(Duration::from_secs(duration_secs)); diff --git a/src/main.rs b/src/main.rs index 77f6e32a3..cc7c202c4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,14 +1,8 @@ -use std::sync::Arc; - -use torrust_tracker_lib::{app, bootstrap}; +use torrust_tracker_lib::app; #[tokio::main] async fn main() { - let (config, app_container) = bootstrap::app::setup(); - - let app_container = Arc::new(app_container); - - let jobs = app::start(&config, &app_container).await; + let (_app_container, jobs, _registar) = app::run().await; // handle the signals tokio::select! { diff --git a/tests/servers/api/contract/stats/mod.rs b/tests/servers/api/contract/stats/mod.rs index fa7b4e6aa..c31ab1907 100644 --- a/tests/servers/api/contract/stats/mod.rs +++ b/tests/servers/api/contract/stats/mod.rs @@ -1,6 +1,5 @@ use std::env; use std::str::FromStr as _; -use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_client::http::client::requests::announce::QueryBuilder; @@ -10,7 +9,7 @@ use serde::Deserialize; use tokio::time::Duration; use torrust_rest_tracker_api_client::connection_info::{ConnectionInfo, Origin}; use torrust_rest_tracker_api_client::v1::client::Client as TrackerApiClient; -use torrust_tracker_lib::{app, bootstrap}; +use torrust_tracker_lib::app; #[tokio::test] async fn the_stats_api_endpoint_should_return_the_global_stats() { @@ -48,11 +47,7 @@ async fn the_stats_api_endpoint_should_return_the_global_stats() { env::set_var("TORRUST_TRACKER_CONFIG_TOML", config_with_two_http_trackers); - let (config, app_container) = bootstrap::app::setup(); - - let app_container = Arc::new(app_container); - - let _jobs = app::start(&config, &app_container).await; + let (_app_container, _jobs, _registar) = app::run().await; announce_to_tracker("http://127.0.0.1:7272").await; announce_to_tracker("http://127.0.0.1:7373").await; From 4e59dd7879b96a8f07c49725b2ab930d241d834b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Mar 2025 12:36:35 +0000 Subject: [PATCH 0915/1297] refactor: [#1407] rename --- tests/servers/api/contract/stats/mod.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/servers/api/contract/stats/mod.rs b/tests/servers/api/contract/stats/mod.rs index c31ab1907..a645fd7e1 100644 --- a/tests/servers/api/contract/stats/mod.rs +++ b/tests/servers/api/contract/stats/mod.rs @@ -52,9 +52,9 @@ async fn the_stats_api_endpoint_should_return_the_global_stats() { announce_to_tracker("http://127.0.0.1:7272").await; announce_to_tracker("http://127.0.0.1:7373").await; - let partial_metrics = get_partial_metrics("http://127.0.0.1:1414", "MyAccessToken").await; + let global_stats = get_tracker_statistics("http://127.0.0.1:1414", "MyAccessToken").await; - assert_eq!(partial_metrics.tcp4_announces_handled, 2); + assert_eq!(global_stats.tcp4_announces_handled, 2); } /// Make a sample announce request to the tracker. @@ -71,20 +71,20 @@ async fn announce_to_tracker(tracker_url: &str) { assert!(response.is_ok()); } -/// Metrics only relevant to the test. +/// Global statistics with only metrics relevant to the test. #[derive(Deserialize)] -struct PartialMetrics { +struct PartialGlobalStatistics { tcp4_announces_handled: u64, } -async fn get_partial_metrics(aip_url: &str, token: &str) -> PartialMetrics { +async fn get_tracker_statistics(aip_url: &str, token: &str) -> PartialGlobalStatistics { let response = TrackerApiClient::new(ConnectionInfo::authenticated(Origin::new(aip_url).unwrap(), token)) .unwrap() .get_tracker_statistics(None) .await; response - .json::() + .json::() .await .expect("Failed to parse JSON response") } From aff065cbbde622decf8555bb870e07efb9b3dde6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Mar 2025 13:10:21 +0000 Subject: [PATCH 0916/1297] fix: [#1407] docker build after adding new integration test --- .gitignore | 1 + tests/servers/api/contract/stats/mod.rs | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/.gitignore b/.gitignore index 8bfa717b7..fd83ee918 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ /tracker.toml callgrind.out codecov.json +integration_tests_sqlite3.db lcov.info perf.data* rustc-ice-*.txt diff --git a/tests/servers/api/contract/stats/mod.rs b/tests/servers/api/contract/stats/mod.rs index a645fd7e1..016a372dd 100644 --- a/tests/servers/api/contract/stats/mod.rs +++ b/tests/servers/api/contract/stats/mod.rs @@ -30,6 +30,10 @@ async fn the_stats_api_endpoint_should_return_the_global_stats() { listed = false private = false + [core.database] + driver = "sqlite3" + path = "./integration_tests_sqlite3.db" + [[http_trackers]] bind_address = "0.0.0.0:7272" tracker_usage_statistics = true From b53da0736078719364fa98e07071ce8adc90b63c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 24 Mar 2025 13:11:28 +0000 Subject: [PATCH 0917/1297] refactor: [#1407] remove duplicate code --- src/console/profiling.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/console/profiling.rs b/src/console/profiling.rs index ffbd835fb..426712c34 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -157,12 +157,11 @@ //! kcachegrind callgrind.out //! ``` use std::env; -use std::sync::Arc; use std::time::Duration; use tokio::time::sleep; -use crate::{app, bootstrap}; +use crate::app; pub async fn run() { // Parse command line arguments @@ -180,11 +179,7 @@ pub async fn run() { return; }; - let (config, app_container) = bootstrap::app::setup(); - - let app_container = Arc::new(app_container); - - let (jobs, _registar) = app::start(&config, &app_container).await; + let (_app_container, jobs, _registar) = app::run().await; // Run the tracker for a fixed duration let run_duration = sleep(Duration::from_secs(duration_secs)); From af80adaa053d4b19ee8e65bffd0c256ed72e5469 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Mar 2025 10:16:24 +0000 Subject: [PATCH 0918/1297] refactor: [#1411] store instance containers in app container --- Cargo.lock | 1 + Cargo.toml | 1 + .../rest-tracker-api-core/src/container.rs | 2 +- src/app.rs | 16 +-- src/container.rs | 131 ++++++++++++++---- 5 files changed, 113 insertions(+), 38 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 055c02a9e..c4755225f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4535,6 +4535,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "thiserror 2.0.12", "tokio", "torrust-axum-health-check-api-server", "torrust-axum-http-tracker-server", diff --git a/Cargo.toml b/Cargo.toml index 91393ad72..9243ed483 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,7 @@ regex = "1" reqwest = { version = "0", features = ["json"] } serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } +thiserror = "2.0.12" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "packages/axum-health-check-api-server" } torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "packages/axum-http-tracker-server" } diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs index c6a46a195..be5e9d7f6 100644 --- a/packages/rest-tracker-api-core/src/container.rs +++ b/packages/rest-tracker-api-core/src/container.rs @@ -10,12 +10,12 @@ use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; pub struct TrackerHttpApiCoreContainer { + pub http_api_config: Arc, pub tracker_core_container: Arc, pub http_stats_repository: Arc, pub ban_service: Arc>, pub udp_core_stats_repository: Arc, pub udp_server_stats_repository: Arc, - pub http_api_config: Arc, } impl TrackerHttpApiCoreContainer { diff --git a/src/app.rs b/src/app.rs index 007eb16d0..5eb162e18 100644 --- a/src/app.rs +++ b/src/app.rs @@ -90,9 +90,10 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> udp_tracker_config.bind_address ); } else { - let udp_tracker_config = Arc::new(udp_tracker_config.clone()); - let udp_tracker_container = Arc::new(app_container.udp_tracker_container(&udp_tracker_config)); - let udp_tracker_server_container = Arc::new(app_container.udp_tracker_server_container()); + let udp_tracker_container = app_container + .udp_tracker_container(udp_tracker_config.bind_address) + .expect("Could not create UDP tracker container"); + let udp_tracker_server_container = app_container.udp_tracker_server_container(); jobs.push( udp_tracker::start_job(udp_tracker_container, udp_tracker_server_container, registar.give_form()).await, @@ -106,8 +107,9 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> // Start the HTTP blocks if let Some(http_trackers) = &config.http_trackers { for http_tracker_config in http_trackers { - let http_tracker_config = Arc::new(http_tracker_config.clone()); - let http_tracker_container = Arc::new(app_container.http_tracker_container(&http_tracker_config)); + let http_tracker_container = app_container + .http_tracker_container(http_tracker_config.bind_address) + .expect("Could not create HTTP tracker container"); if let Some(job) = http_tracker::start_job( http_tracker_container, @@ -126,7 +128,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> // Start HTTP API if let Some(http_api_config) = &config.http_api { let http_api_config = Arc::new(http_api_config.clone()); - let http_api_container = Arc::new(app_container.tracker_http_api_container(&http_api_config)); + let http_api_container = app_container.tracker_http_api_container(&http_api_config); if let Some(job) = tracker_apis::start_job( http_api_container, @@ -149,8 +151,6 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> )); } - println!("Registar entries: {:?}", registar.entries()); - // Start Health Check API jobs.push(health_check_api::start_job(&config.health_check_api, registar.entries()).await); diff --git a/src/container.rs b/src/container.rs index d3253b5d9..e55a1d2f8 100644 --- a/src/container.rs +++ b/src/container.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; +use std::net::SocketAddr; use std::sync::Arc; use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; @@ -9,12 +11,22 @@ use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; use tokio::sync::RwLock; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; -use torrust_tracker_configuration::{Configuration, HttpApi, HttpTracker, UdpTracker}; +use torrust_tracker_configuration::{Configuration, HttpApi}; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use tracing::instrument; +#[derive(thiserror::Error, Debug, Clone)] +pub enum Error { + #[error("There is not a HTTP tracker server instance bound to the socket address: {bind_address}")] + MissingHttpTrackerCoreContainer { bind_address: SocketAddr }, + + #[error("There is not a UDP tracker server instance bound to the socket address: {bind_address}")] + MissingUdpTrackerCoreContainer { bind_address: SocketAddr }, +} + pub struct AppContainer { pub tracker_core_container: Arc, + pub http_api_config: Arc>, // UDP Tracker Core Services pub udp_core_stats_event_sender: Arc>>, @@ -33,6 +45,13 @@ pub struct AppContainer { // UDP Tracker Server Services pub udp_server_stats_event_sender: Arc>>, pub udp_server_stats_repository: Arc, + + // UDP Tracker Server Container + pub udp_tracker_server_container: Arc, + + // Tracker Instance Containers + pub http_tracker_containers: Arc>>, + pub udp_tracker_containers: Arc>>, } impl AppContainer { @@ -40,6 +59,8 @@ impl AppContainer { pub fn initialize(configuration: &Configuration) -> AppContainer { let core_config = Arc::new(configuration.core.clone()); + let http_api_config = Arc::new(configuration.http_api.clone()); + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); // HTTP Tracker Core Services @@ -86,8 +107,59 @@ impl AppContainer { let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); let udp_server_stats_repository = Arc::new(udp_server_stats_repository); + // UDP Tracker Server Container + let udp_tracker_server_container = Arc::new(UdpTrackerServerContainer { + udp_server_stats_event_sender: udp_server_stats_event_sender.clone(), + udp_server_stats_repository: udp_server_stats_repository.clone(), + }); + + // Tracker Instance Containers + + let mut http_tracker_containers = HashMap::new(); + + if let Some(http_trackers) = &configuration.http_trackers { + for http_tracker_config in http_trackers { + http_tracker_containers.insert( + http_tracker_config.bind_address, + Arc::new(HttpTrackerCoreContainer { + tracker_core_container: tracker_core_container.clone(), + http_tracker_config: Arc::new(http_tracker_config.clone()), + http_stats_event_sender: http_stats_event_sender.clone(), + http_stats_repository: http_stats_repository.clone(), + announce_service: http_announce_service.clone(), + scrape_service: http_scrape_service.clone(), + }), + ); + } + } + + let http_tracker_containers = Arc::new(http_tracker_containers); + + let mut udp_tracker_containers = HashMap::new(); + + if let Some(udp_trackers) = &configuration.udp_trackers { + for udp_tracker_config in udp_trackers { + udp_tracker_containers.insert( + udp_tracker_config.bind_address, + Arc::new(UdpTrackerCoreContainer { + tracker_core_container: tracker_core_container.clone(), + udp_tracker_config: Arc::new(udp_tracker_config.clone()), + udp_core_stats_event_sender: udp_core_stats_event_sender.clone(), + udp_core_stats_repository: udp_core_stats_repository.clone(), + ban_service: udp_ban_service.clone(), + connect_service: udp_connect_service.clone(), + announce_service: udp_announce_service.clone(), + scrape_service: udp_scrape_service.clone(), + }), + ); + } + } + + let udp_tracker_containers = Arc::new(udp_tracker_containers); + AppContainer { tracker_core_container, + http_api_config, // UDP Tracker Core Services udp_core_stats_event_sender, @@ -106,37 +178,45 @@ impl AppContainer { // UDP Tracker Server Services udp_server_stats_event_sender, udp_server_stats_repository, + + // UDP Tracker Server Container + udp_tracker_server_container, + + // Tracker Instance Containers + http_tracker_containers, + udp_tracker_containers, } } #[must_use] - pub fn http_tracker_container(&self, http_tracker_config: &Arc) -> HttpTrackerCoreContainer { - HttpTrackerCoreContainer { - tracker_core_container: self.tracker_core_container.clone(), - http_tracker_config: http_tracker_config.clone(), - http_stats_event_sender: self.http_stats_event_sender.clone(), - http_stats_repository: self.http_stats_repository.clone(), - announce_service: self.http_announce_service.clone(), - scrape_service: self.http_scrape_service.clone(), + pub fn udp_tracker_server_container(&self) -> Arc { + self.udp_tracker_server_container.clone() + } + + /// # Errors + /// + /// Return an error if there is no HTTP tracker server instance bound to the + /// socket address. + pub fn http_tracker_container(&self, bind_address: SocketAddr) -> Result, Error> { + match self.http_tracker_containers.get(&bind_address) { + Some(http_tracker_container) => Ok(http_tracker_container.clone()), + None => Err(Error::MissingHttpTrackerCoreContainer { bind_address }), } } - #[must_use] - pub fn udp_tracker_container(&self, udp_tracker_config: &Arc) -> UdpTrackerCoreContainer { - UdpTrackerCoreContainer { - tracker_core_container: self.tracker_core_container.clone(), - udp_tracker_config: udp_tracker_config.clone(), - udp_core_stats_event_sender: self.udp_core_stats_event_sender.clone(), - udp_core_stats_repository: self.udp_core_stats_repository.clone(), - ban_service: self.udp_ban_service.clone(), - connect_service: self.udp_connect_service.clone(), - announce_service: self.udp_announce_service.clone(), - scrape_service: self.udp_scrape_service.clone(), + /// # Errors + /// + /// Return an error if there is no UDP tracker server instance bound to the + /// socket address. + pub fn udp_tracker_container(&self, bind_address: SocketAddr) -> Result, Error> { + match self.udp_tracker_containers.get(&bind_address) { + Some(udp_tracker_container) => Ok(udp_tracker_container.clone()), + None => Err(Error::MissingUdpTrackerCoreContainer { bind_address }), } } #[must_use] - pub fn tracker_http_api_container(&self, http_api_config: &Arc) -> TrackerHttpApiCoreContainer { + pub fn tracker_http_api_container(&self, http_api_config: &Arc) -> Arc { TrackerHttpApiCoreContainer { tracker_core_container: self.tracker_core_container.clone(), http_api_config: http_api_config.clone(), @@ -145,13 +225,6 @@ impl AppContainer { udp_core_stats_repository: self.udp_core_stats_repository.clone(), udp_server_stats_repository: self.udp_server_stats_repository.clone(), } - } - - #[must_use] - pub fn udp_tracker_server_container(&self) -> UdpTrackerServerContainer { - UdpTrackerServerContainer { - udp_server_stats_event_sender: self.udp_server_stats_event_sender.clone(), - udp_server_stats_repository: self.udp_server_stats_repository.clone(), - } + .into() } } From fdf2055ef0ffa98af765e272e4fa2c56a9ee09a9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Mar 2025 11:01:00 +0000 Subject: [PATCH 0919/1297] refactor: [#1411] remove duplicate code for HttpTrackerCoreServices initialization --- .../src/environment.rs | 3 +- .../src/environment.rs | 2 +- packages/http-tracker-core/src/container.rs | 58 ++++++++++++++----- .../rest-tracker-api-core/src/container.rs | 3 +- src/container.rs | 52 ++++------------- 5 files changed, 59 insertions(+), 59 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index 81f0a1ef3..a89d9af08 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -115,7 +115,8 @@ impl EnvContainer { let http_tracker_config = Arc::new(http_tracker_config[0].clone()); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); - let http_tracker_container = HttpTrackerCoreContainer::initialize_from(&tracker_core_container, &http_tracker_config); + let http_tracker_container = + HttpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &http_tracker_config); Self { tracker_core_container, diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index c2d89e064..96295a5d3 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -174,7 +174,7 @@ impl EnvContainer { let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); let http_tracker_core_container = - HttpTrackerCoreContainer::initialize_from(&tracker_core_container, &http_tracker_config); + HttpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &http_tracker_config); let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from(&tracker_core_container, &udp_tracker_config); let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index ce577f1d8..7fc2f48a6 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -5,11 +5,14 @@ use torrust_tracker_configuration::{Core, HttpTracker}; use crate::services::announce::AnnounceService; use crate::services::scrape::ScrapeService; -use crate::{event, statistics}; +use crate::{event, services, statistics}; pub struct HttpTrackerCoreContainer { - pub tracker_core_container: Arc, pub http_tracker_config: Arc, + + pub tracker_core_container: Arc, + + // `HttpTrackerCoreServices` pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, pub announce_service: Arc, @@ -20,28 +23,57 @@ impl HttpTrackerCoreContainer { #[must_use] pub fn initialize(core_config: &Arc, http_tracker_config: &Arc) -> Arc { let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(core_config)); - Self::initialize_from(&tracker_core_container, http_tracker_config) + Self::initialize_from_tracker_core(&tracker_core_container, http_tracker_config) } #[must_use] - pub fn initialize_from( + pub fn initialize_from_tracker_core( tracker_core_container: &Arc, http_tracker_config: &Arc, ) -> Arc { + let http_tracker_core_services = HttpTrackerCoreServices::initialize_from(tracker_core_container); + Self::initialize_from_services(tracker_core_container, &http_tracker_core_services, http_tracker_config) + } + + #[must_use] + pub fn initialize_from_services( + tracker_core_container: &Arc, + http_tracker_core_services: &Arc, + http_tracker_config: &Arc, + ) -> Arc { + Arc::new(Self { + tracker_core_container: tracker_core_container.clone(), + http_tracker_config: http_tracker_config.clone(), + http_stats_event_sender: http_tracker_core_services.http_stats_event_sender.clone(), + http_stats_repository: http_tracker_core_services.http_stats_repository.clone(), + announce_service: http_tracker_core_services.http_announce_service.clone(), + scrape_service: http_tracker_core_services.http_scrape_service.clone(), + }) + } +} + +pub struct HttpTrackerCoreServices { + pub http_stats_event_sender: Arc>>, + pub http_stats_repository: Arc, + pub http_announce_service: Arc, + pub http_scrape_service: Arc, +} + +impl HttpTrackerCoreServices { + #[must_use] + pub fn initialize_from(tracker_core_container: &Arc) -> Arc { let (http_stats_event_sender, http_stats_repository) = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); let http_stats_repository = Arc::new(http_stats_repository); - - let announce_service = Arc::new(AnnounceService::new( + let http_announce_service = Arc::new(AnnounceService::new( tracker_core_container.core_config.clone(), tracker_core_container.announce_handler.clone(), tracker_core_container.authentication_service.clone(), tracker_core_container.whitelist_authorization.clone(), http_stats_event_sender.clone(), )); - - let scrape_service = Arc::new(ScrapeService::new( + let http_scrape_service = Arc::new(ScrapeService::new( tracker_core_container.core_config.clone(), tracker_core_container.scrape_handler.clone(), tracker_core_container.authentication_service.clone(), @@ -49,12 +81,10 @@ impl HttpTrackerCoreContainer { )); Arc::new(Self { - tracker_core_container: tracker_core_container.clone(), - http_tracker_config: http_tracker_config.clone(), - http_stats_event_sender: http_stats_event_sender.clone(), - http_stats_repository: http_stats_repository.clone(), - announce_service: announce_service.clone(), - scrape_service: scrape_service.clone(), + http_stats_event_sender, + http_stats_repository, + http_announce_service, + http_scrape_service, }) } } diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs index be5e9d7f6..040c16b26 100644 --- a/packages/rest-tracker-api-core/src/container.rs +++ b/packages/rest-tracker-api-core/src/container.rs @@ -27,7 +27,8 @@ impl TrackerHttpApiCoreContainer { http_api_config: &Arc, ) -> Arc { let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(core_config)); - let http_tracker_core_container = HttpTrackerCoreContainer::initialize_from(&tracker_core_container, http_tracker_config); + let http_tracker_core_container = + HttpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, http_tracker_config); let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from(&tracker_core_container, udp_tracker_config); let udp_tracker_server_container = UdpTrackerServerContainer::initialize(core_config); diff --git a/src/container.rs b/src/container.rs index e55a1d2f8..f311453d1 100644 --- a/src/container.rs +++ b/src/container.rs @@ -2,9 +2,7 @@ use std::collections::HashMap; use std::net::SocketAddr; use std::sync::Arc; -use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; -use bittorrent_http_tracker_core::services::announce::AnnounceService; -use bittorrent_http_tracker_core::services::scrape::ScrapeService; +use bittorrent_http_tracker_core::container::{HttpTrackerCoreContainer, HttpTrackerCoreServices}; use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::services::banning::BanService; @@ -27,6 +25,7 @@ pub enum Error { pub struct AppContainer { pub tracker_core_container: Arc, pub http_api_config: Arc>, + pub http_tracker_core_services: Arc, // UDP Tracker Core Services pub udp_core_stats_event_sender: Arc>>, @@ -36,12 +35,6 @@ pub struct AppContainer { pub udp_announce_service: Arc, pub udp_scrape_service: Arc, - // HTTP Tracker Core Services - pub http_stats_event_sender: Arc>>, - pub http_stats_repository: Arc, - pub http_announce_service: Arc, - pub http_scrape_service: Arc, - // UDP Tracker Server Services pub udp_server_stats_event_sender: Arc>>, pub udp_server_stats_repository: Arc, @@ -63,24 +56,7 @@ impl AppContainer { let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); - // HTTP Tracker Core Services - let (http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let http_stats_event_sender = Arc::new(http_stats_event_sender); - let http_stats_repository = Arc::new(http_stats_repository); - let http_announce_service = Arc::new(AnnounceService::new( - tracker_core_container.core_config.clone(), - tracker_core_container.announce_handler.clone(), - tracker_core_container.authentication_service.clone(), - tracker_core_container.whitelist_authorization.clone(), - http_stats_event_sender.clone(), - )); - let http_scrape_service = Arc::new(ScrapeService::new( - tracker_core_container.core_config.clone(), - tracker_core_container.scrape_handler.clone(), - tracker_core_container.authentication_service.clone(), - http_stats_event_sender.clone(), - )); + let http_tracker_core_services = HttpTrackerCoreServices::initialize_from(&tracker_core_container); // UDP Tracker Core Services let (udp_core_stats_event_sender, udp_core_stats_repository) = @@ -121,14 +97,11 @@ impl AppContainer { for http_tracker_config in http_trackers { http_tracker_containers.insert( http_tracker_config.bind_address, - Arc::new(HttpTrackerCoreContainer { - tracker_core_container: tracker_core_container.clone(), - http_tracker_config: Arc::new(http_tracker_config.clone()), - http_stats_event_sender: http_stats_event_sender.clone(), - http_stats_repository: http_stats_repository.clone(), - announce_service: http_announce_service.clone(), - scrape_service: http_scrape_service.clone(), - }), + HttpTrackerCoreContainer::initialize_from_services( + &tracker_core_container, + &http_tracker_core_services, + &Arc::new(http_tracker_config.clone()), + ), ); } } @@ -160,6 +133,7 @@ impl AppContainer { AppContainer { tracker_core_container, http_api_config, + http_tracker_core_services, // UDP Tracker Core Services udp_core_stats_event_sender, @@ -169,12 +143,6 @@ impl AppContainer { udp_announce_service, udp_scrape_service, - // HTTP Tracker Core Services - http_stats_event_sender, - http_stats_repository, - http_announce_service, - http_scrape_service, - // UDP Tracker Server Services udp_server_stats_event_sender, udp_server_stats_repository, @@ -221,7 +189,7 @@ impl AppContainer { tracker_core_container: self.tracker_core_container.clone(), http_api_config: http_api_config.clone(), ban_service: self.udp_ban_service.clone(), - http_stats_repository: self.http_stats_repository.clone(), + http_stats_repository: self.http_tracker_core_services.http_stats_repository.clone(), udp_core_stats_repository: self.udp_core_stats_repository.clone(), udp_server_stats_repository: self.udp_server_stats_repository.clone(), } From 4c7feb5397690fb598f3795beaf68f9f9911d50a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Mar 2025 11:19:14 +0000 Subject: [PATCH 0920/1297] refactor: [#1411] remove duplicate code for UdpTrackerCoreServices initialization --- .../src/environment.rs | 3 +- .../rest-tracker-api-core/src/container.rs | 3 +- packages/udp-tracker-core/src/container.rs | 65 +++++++++++++++---- .../udp-tracker-server/src/environment.rs | 3 +- src/container.rs | 62 ++++-------------- 5 files changed, 70 insertions(+), 66 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index 96295a5d3..275d72574 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -175,7 +175,8 @@ impl EnvContainer { let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); let http_tracker_core_container = HttpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &http_tracker_config); - let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from(&tracker_core_container, &udp_tracker_config); + let udp_tracker_core_container = + UdpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &udp_tracker_config); let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); let tracker_http_api_core_container = TrackerHttpApiCoreContainer::initialize_from( diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs index 040c16b26..329c77eed 100644 --- a/packages/rest-tracker-api-core/src/container.rs +++ b/packages/rest-tracker-api-core/src/container.rs @@ -29,7 +29,8 @@ impl TrackerHttpApiCoreContainer { let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(core_config)); let http_tracker_core_container = HttpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, http_tracker_config); - let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from(&tracker_core_container, udp_tracker_config); + let udp_tracker_core_container = + UdpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, udp_tracker_config); let udp_tracker_server_container = UdpTrackerServerContainer::initialize(core_config); Self::initialize_from( diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index 2ab578151..79ce15d01 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -8,11 +8,14 @@ use crate::services::announce::AnnounceService; use crate::services::banning::BanService; use crate::services::connect::ConnectService; use crate::services::scrape::ScrapeService; -use crate::{event, statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; +use crate::{event, services, statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; pub struct UdpTrackerCoreContainer { - pub tracker_core_container: Arc, pub udp_tracker_config: Arc, + + pub tracker_core_container: Arc, + + // `UdpTrackerCoreServices` pub udp_core_stats_event_sender: Arc>>, pub udp_core_stats_repository: Arc, pub ban_service: Arc>, @@ -25,14 +28,52 @@ impl UdpTrackerCoreContainer { #[must_use] pub fn initialize(core_config: &Arc, udp_tracker_config: &Arc) -> Arc { let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(core_config)); - Self::initialize_from(&tracker_core_container, udp_tracker_config) + Self::initialize_from_tracker_core(&tracker_core_container, udp_tracker_config) } #[must_use] - pub fn initialize_from( + pub fn initialize_from_tracker_core( tracker_core_container: &Arc, udp_tracker_config: &Arc, ) -> Arc { + let udp_tracker_core_services = UdpTrackerCoreServices::initialize_from(tracker_core_container); + Self::initialize_from_services(tracker_core_container, &udp_tracker_core_services, udp_tracker_config) + } + + #[must_use] + pub fn initialize_from_services( + tracker_core_container: &Arc, + udp_tracker_core_services: &Arc, + udp_tracker_config: &Arc, + ) -> Arc { + Arc::new(Self { + udp_tracker_config: udp_tracker_config.clone(), + + tracker_core_container: tracker_core_container.clone(), + + // `UdpTrackerCoreServices` + udp_core_stats_event_sender: udp_tracker_core_services.udp_core_stats_event_sender.clone(), + udp_core_stats_repository: udp_tracker_core_services.udp_core_stats_repository.clone(), + ban_service: udp_tracker_core_services.udp_ban_service.clone(), + connect_service: udp_tracker_core_services.udp_connect_service.clone(), + announce_service: udp_tracker_core_services.udp_announce_service.clone(), + scrape_service: udp_tracker_core_services.udp_scrape_service.clone(), + }) + } +} + +pub struct UdpTrackerCoreServices { + pub udp_core_stats_event_sender: Arc>>, + pub udp_core_stats_repository: Arc, + pub udp_ban_service: Arc>, + pub udp_connect_service: Arc, + pub udp_announce_service: Arc, + pub udp_scrape_service: Arc, +} + +impl UdpTrackerCoreServices { + #[must_use] + pub fn initialize_from(tracker_core_container: &Arc) -> Arc { let (udp_core_stats_event_sender, udp_core_stats_repository) = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); @@ -49,15 +90,13 @@ impl UdpTrackerCoreContainer { udp_core_stats_event_sender.clone(), )); - Arc::new(UdpTrackerCoreContainer { - tracker_core_container: tracker_core_container.clone(), - udp_tracker_config: udp_tracker_config.clone(), - udp_core_stats_event_sender: udp_core_stats_event_sender.clone(), - udp_core_stats_repository: udp_core_stats_repository.clone(), - ban_service: ban_service.clone(), - connect_service: connect_service.clone(), - announce_service: announce_service.clone(), - scrape_service: scrape_service.clone(), + Arc::new(Self { + udp_core_stats_event_sender, + udp_core_stats_repository, + udp_ban_service: ban_service, + udp_connect_service: connect_service, + udp_announce_service: announce_service, + udp_scrape_service: scrape_service, }) } } diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 158e39a7e..b97da90ad 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -131,7 +131,8 @@ impl EnvContainer { let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); - let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from(&tracker_core_container, &udp_tracker_config); + let udp_tracker_core_container = + UdpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &udp_tracker_config); let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); Self { diff --git a/src/container.rs b/src/container.rs index f311453d1..ce5eb8ae9 100644 --- a/src/container.rs +++ b/src/container.rs @@ -4,10 +4,8 @@ use std::sync::Arc; use bittorrent_http_tracker_core::container::{HttpTrackerCoreContainer, HttpTrackerCoreServices}; use bittorrent_tracker_core::container::TrackerCoreContainer; -use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; -use bittorrent_udp_tracker_core::services::banning::BanService; -use bittorrent_udp_tracker_core::{self, MAX_CONNECTION_ID_ERRORS_PER_IP}; -use tokio::sync::RwLock; +use bittorrent_udp_tracker_core::container::{UdpTrackerCoreContainer, UdpTrackerCoreServices}; +use bittorrent_udp_tracker_core::{self}; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_tracker_configuration::{Configuration, HttpApi}; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; @@ -26,14 +24,7 @@ pub struct AppContainer { pub tracker_core_container: Arc, pub http_api_config: Arc>, pub http_tracker_core_services: Arc, - - // UDP Tracker Core Services - pub udp_core_stats_event_sender: Arc>>, - pub udp_core_stats_repository: Arc, - pub udp_ban_service: Arc>, - pub udp_connect_service: Arc, - pub udp_announce_service: Arc, - pub udp_scrape_service: Arc, + pub udp_tracker_core_services: Arc, // UDP Tracker Server Services pub udp_server_stats_event_sender: Arc>>, @@ -58,24 +49,7 @@ impl AppContainer { let http_tracker_core_services = HttpTrackerCoreServices::initialize_from(&tracker_core_container); - // UDP Tracker Core Services - let (udp_core_stats_event_sender, udp_core_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); - let udp_core_stats_repository = Arc::new(udp_core_stats_repository); - let udp_ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let udp_connect_service = Arc::new(bittorrent_udp_tracker_core::services::connect::ConnectService::new( - udp_core_stats_event_sender.clone(), - )); - let udp_announce_service = Arc::new(bittorrent_udp_tracker_core::services::announce::AnnounceService::new( - tracker_core_container.announce_handler.clone(), - tracker_core_container.whitelist_authorization.clone(), - udp_core_stats_event_sender.clone(), - )); - let udp_scrape_service = Arc::new(bittorrent_udp_tracker_core::services::scrape::ScrapeService::new( - tracker_core_container.scrape_handler.clone(), - udp_core_stats_event_sender.clone(), - )); + let udp_tracker_core_services = UdpTrackerCoreServices::initialize_from(&tracker_core_container); // UDP Tracker Server Services let (udp_server_stats_event_sender, udp_server_stats_repository) = @@ -114,16 +88,11 @@ impl AppContainer { for udp_tracker_config in udp_trackers { udp_tracker_containers.insert( udp_tracker_config.bind_address, - Arc::new(UdpTrackerCoreContainer { - tracker_core_container: tracker_core_container.clone(), - udp_tracker_config: Arc::new(udp_tracker_config.clone()), - udp_core_stats_event_sender: udp_core_stats_event_sender.clone(), - udp_core_stats_repository: udp_core_stats_repository.clone(), - ban_service: udp_ban_service.clone(), - connect_service: udp_connect_service.clone(), - announce_service: udp_announce_service.clone(), - scrape_service: udp_scrape_service.clone(), - }), + UdpTrackerCoreContainer::initialize_from_services( + &tracker_core_container, + &udp_tracker_core_services, + &Arc::new(udp_tracker_config.clone()), + ), ); } } @@ -134,14 +103,7 @@ impl AppContainer { tracker_core_container, http_api_config, http_tracker_core_services, - - // UDP Tracker Core Services - udp_core_stats_event_sender, - udp_core_stats_repository, - udp_ban_service, - udp_connect_service, - udp_announce_service, - udp_scrape_service, + udp_tracker_core_services, // UDP Tracker Server Services udp_server_stats_event_sender, @@ -188,9 +150,9 @@ impl AppContainer { TrackerHttpApiCoreContainer { tracker_core_container: self.tracker_core_container.clone(), http_api_config: http_api_config.clone(), - ban_service: self.udp_ban_service.clone(), + ban_service: self.udp_tracker_core_services.udp_ban_service.clone(), http_stats_repository: self.http_tracker_core_services.http_stats_repository.clone(), - udp_core_stats_repository: self.udp_core_stats_repository.clone(), + udp_core_stats_repository: self.udp_tracker_core_services.udp_core_stats_repository.clone(), udp_server_stats_repository: self.udp_server_stats_repository.clone(), } .into() From 60ed2e4a6894da61a9bcec9b7139866b000a9093 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Mar 2025 11:34:51 +0000 Subject: [PATCH 0921/1297] refactor: [#1411] remove duplicate code for UdpTrackerServerServices initialization --- packages/udp-tracker-server/src/container.rs | 17 ++++++++++++ src/container.rs | 28 +++++--------------- 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs index 0c8039b26..2b1ce8c99 100644 --- a/packages/udp-tracker-server/src/container.rs +++ b/packages/udp-tracker-server/src/container.rs @@ -10,6 +10,23 @@ pub struct UdpTrackerServerContainer { } impl UdpTrackerServerContainer { + #[must_use] + pub fn initialize(core_config: &Arc) -> Arc { + let udp_tracker_server_services = UdpTrackerServerServices::initialize(core_config); + + Arc::new(Self { + udp_server_stats_event_sender: udp_tracker_server_services.udp_server_stats_event_sender.clone(), + udp_server_stats_repository: udp_tracker_server_services.udp_server_stats_repository.clone(), + }) + } +} + +pub struct UdpTrackerServerServices { + pub udp_server_stats_event_sender: Arc>>, + pub udp_server_stats_repository: Arc, +} + +impl UdpTrackerServerServices { #[must_use] pub fn initialize(core_config: &Arc) -> Arc { let (udp_server_stats_event_sender, udp_server_stats_repository) = diff --git a/src/container.rs b/src/container.rs index ce5eb8ae9..aa832cac4 100644 --- a/src/container.rs +++ b/src/container.rs @@ -21,15 +21,12 @@ pub enum Error { } pub struct AppContainer { - pub tracker_core_container: Arc, pub http_api_config: Arc>, + + pub tracker_core_container: Arc, pub http_tracker_core_services: Arc, pub udp_tracker_core_services: Arc, - // UDP Tracker Server Services - pub udp_server_stats_event_sender: Arc>>, - pub udp_server_stats_repository: Arc, - // UDP Tracker Server Container pub udp_tracker_server_container: Arc, @@ -51,17 +48,7 @@ impl AppContainer { let udp_tracker_core_services = UdpTrackerCoreServices::initialize_from(&tracker_core_container); - // UDP Tracker Server Services - let (udp_server_stats_event_sender, udp_server_stats_repository) = - torrust_udp_tracker_server::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); - let udp_server_stats_repository = Arc::new(udp_server_stats_repository); - - // UDP Tracker Server Container - let udp_tracker_server_container = Arc::new(UdpTrackerServerContainer { - udp_server_stats_event_sender: udp_server_stats_event_sender.clone(), - udp_server_stats_repository: udp_server_stats_repository.clone(), - }); + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); // Tracker Instance Containers @@ -100,15 +87,12 @@ impl AppContainer { let udp_tracker_containers = Arc::new(udp_tracker_containers); AppContainer { - tracker_core_container, http_api_config, + + tracker_core_container, http_tracker_core_services, udp_tracker_core_services, - // UDP Tracker Server Services - udp_server_stats_event_sender, - udp_server_stats_repository, - // UDP Tracker Server Container udp_tracker_server_container, @@ -153,7 +137,7 @@ impl AppContainer { ban_service: self.udp_tracker_core_services.udp_ban_service.clone(), http_stats_repository: self.http_tracker_core_services.http_stats_repository.clone(), udp_core_stats_repository: self.udp_tracker_core_services.udp_core_stats_repository.clone(), - udp_server_stats_repository: self.udp_server_stats_repository.clone(), + udp_server_stats_repository: self.udp_tracker_server_container.udp_server_stats_repository.clone(), } .into() } From ef5dc322b58aa6fa17997ca5f34bdb715911862a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Mar 2025 11:42:47 +0000 Subject: [PATCH 0922/1297] refactor: [#1411] reorganize fields in AppContainer --- src/container.rs | 62 ++++++++++++++++++++++++++++-------------------- 1 file changed, 36 insertions(+), 26 deletions(-) diff --git a/src/container.rs b/src/container.rs index aa832cac4..918a6ea03 100644 --- a/src/container.rs +++ b/src/container.rs @@ -21,42 +21,44 @@ pub enum Error { } pub struct AppContainer { + // Configuration pub http_api_config: Arc>, + // Core pub tracker_core_container: Arc, + + // HTTP pub http_tracker_core_services: Arc, - pub udp_tracker_core_services: Arc, + pub http_tracker_instance_containers: Arc>>, - // UDP Tracker Server Container + // UDP + pub udp_tracker_core_services: Arc, pub udp_tracker_server_container: Arc, - - // Tracker Instance Containers - pub http_tracker_containers: Arc>>, - pub udp_tracker_containers: Arc>>, + pub udp_tracker_instance_containers: Arc>>, } impl AppContainer { #[instrument(skip())] pub fn initialize(configuration: &Configuration) -> AppContainer { + // Configuration + let core_config = Arc::new(configuration.core.clone()); let http_api_config = Arc::new(configuration.http_api.clone()); - let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); + // Core - let http_tracker_core_services = HttpTrackerCoreServices::initialize_from(&tracker_core_container); - - let udp_tracker_core_services = UdpTrackerCoreServices::initialize_from(&tracker_core_container); + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); - let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); + // HTTP - // Tracker Instance Containers + let http_tracker_core_services = HttpTrackerCoreServices::initialize_from(&tracker_core_container); - let mut http_tracker_containers = HashMap::new(); + let mut http_tracker_instance_containers = HashMap::new(); if let Some(http_trackers) = &configuration.http_trackers { for http_tracker_config in http_trackers { - http_tracker_containers.insert( + http_tracker_instance_containers.insert( http_tracker_config.bind_address, HttpTrackerCoreContainer::initialize_from_services( &tracker_core_container, @@ -67,13 +69,19 @@ impl AppContainer { } } - let http_tracker_containers = Arc::new(http_tracker_containers); + let http_tracker_instance_containers = Arc::new(http_tracker_instance_containers); + + // UDP + + let udp_tracker_core_services = UdpTrackerCoreServices::initialize_from(&tracker_core_container); + + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); - let mut udp_tracker_containers = HashMap::new(); + let mut udp_tracker_instance_containers = HashMap::new(); if let Some(udp_trackers) = &configuration.udp_trackers { for udp_tracker_config in udp_trackers { - udp_tracker_containers.insert( + udp_tracker_instance_containers.insert( udp_tracker_config.bind_address, UdpTrackerCoreContainer::initialize_from_services( &tracker_core_container, @@ -84,21 +92,23 @@ impl AppContainer { } } - let udp_tracker_containers = Arc::new(udp_tracker_containers); + let udp_tracker_instance_containers = Arc::new(udp_tracker_instance_containers); AppContainer { + // Configuration http_api_config, + // Core tracker_core_container, + + // HTTP http_tracker_core_services, - udp_tracker_core_services, + http_tracker_instance_containers, - // UDP Tracker Server Container + // UDP + udp_tracker_core_services, udp_tracker_server_container, - - // Tracker Instance Containers - http_tracker_containers, - udp_tracker_containers, + udp_tracker_instance_containers, } } @@ -112,7 +122,7 @@ impl AppContainer { /// Return an error if there is no HTTP tracker server instance bound to the /// socket address. pub fn http_tracker_container(&self, bind_address: SocketAddr) -> Result, Error> { - match self.http_tracker_containers.get(&bind_address) { + match self.http_tracker_instance_containers.get(&bind_address) { Some(http_tracker_container) => Ok(http_tracker_container.clone()), None => Err(Error::MissingHttpTrackerCoreContainer { bind_address }), } @@ -123,7 +133,7 @@ impl AppContainer { /// Return an error if there is no UDP tracker server instance bound to the /// socket address. pub fn udp_tracker_container(&self, bind_address: SocketAddr) -> Result, Error> { - match self.udp_tracker_containers.get(&bind_address) { + match self.udp_tracker_instance_containers.get(&bind_address) { Some(udp_tracker_container) => Ok(udp_tracker_container.clone()), None => Err(Error::MissingUdpTrackerCoreContainer { bind_address }), } From 299d0f3ea7566a73aa1edeedef839d92d9545896 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 25 Mar 2025 11:56:10 +0000 Subject: [PATCH 0923/1297] refactor: [#1411] extract static methods in AppContainer --- src/container.rs | 87 ++++++++++++++++++++++++++++++------------------ 1 file changed, 55 insertions(+), 32 deletions(-) diff --git a/src/container.rs b/src/container.rs index 918a6ea03..7742d8e40 100644 --- a/src/container.rs +++ b/src/container.rs @@ -54,22 +54,11 @@ impl AppContainer { let http_tracker_core_services = HttpTrackerCoreServices::initialize_from(&tracker_core_container); - let mut http_tracker_instance_containers = HashMap::new(); - - if let Some(http_trackers) = &configuration.http_trackers { - for http_tracker_config in http_trackers { - http_tracker_instance_containers.insert( - http_tracker_config.bind_address, - HttpTrackerCoreContainer::initialize_from_services( - &tracker_core_container, - &http_tracker_core_services, - &Arc::new(http_tracker_config.clone()), - ), - ); - } - } - - let http_tracker_instance_containers = Arc::new(http_tracker_instance_containers); + let http_tracker_instance_containers = Self::initialize_http_tracker_instance_containers( + configuration, + &tracker_core_container, + &http_tracker_core_services, + ); // UDP @@ -77,22 +66,8 @@ impl AppContainer { let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); - let mut udp_tracker_instance_containers = HashMap::new(); - - if let Some(udp_trackers) = &configuration.udp_trackers { - for udp_tracker_config in udp_trackers { - udp_tracker_instance_containers.insert( - udp_tracker_config.bind_address, - UdpTrackerCoreContainer::initialize_from_services( - &tracker_core_container, - &udp_tracker_core_services, - &Arc::new(udp_tracker_config.clone()), - ), - ); - } - } - - let udp_tracker_instance_containers = Arc::new(udp_tracker_instance_containers); + let udp_tracker_instance_containers = + Self::initialize_udp_tracker_instance_containers(configuration, &tracker_core_container, &udp_tracker_core_services); AppContainer { // Configuration @@ -151,4 +126,52 @@ impl AppContainer { } .into() } + + #[must_use] + fn initialize_http_tracker_instance_containers( + configuration: &Configuration, + tracker_core_container: &Arc, + http_tracker_core_services: &Arc, + ) -> Arc>> { + let mut http_tracker_instance_containers = HashMap::new(); + + if let Some(http_trackers) = &configuration.http_trackers { + for http_tracker_config in http_trackers { + http_tracker_instance_containers.insert( + http_tracker_config.bind_address, + HttpTrackerCoreContainer::initialize_from_services( + tracker_core_container, + http_tracker_core_services, + &Arc::new(http_tracker_config.clone()), + ), + ); + } + } + + Arc::new(http_tracker_instance_containers) + } + + #[must_use] + fn initialize_udp_tracker_instance_containers( + configuration: &Configuration, + tracker_core_container: &Arc, + udp_tracker_core_services: &Arc, + ) -> Arc>> { + let mut udp_tracker_instance_containers = HashMap::new(); + + if let Some(udp_trackers) = &configuration.udp_trackers { + for udp_tracker_config in udp_trackers { + udp_tracker_instance_containers.insert( + udp_tracker_config.bind_address, + UdpTrackerCoreContainer::initialize_from_services( + tracker_core_container, + udp_tracker_core_services, + &Arc::new(udp_tracker_config.clone()), + ), + ); + } + } + + Arc::new(udp_tracker_instance_containers) + } } From 99aa2594751dcb0a307817b21871eb5bd2fe8cff Mon Sep 17 00:00:00 2001 From: nuts_rice Date: Tue, 25 Mar 2025 11:56:25 -0400 Subject: [PATCH 0924/1297] health_check: service_type field --- packages/axum-health-check-api-server/src/handlers.rs | 1 + packages/axum-health-check-api-server/src/resources.rs | 1 + packages/axum-http-tracker-server/src/server.rs | 3 ++- packages/axum-rest-tracker-api-server/src/server.rs | 4 +++- packages/server-lib/src/registar.rs | 1 + packages/udp-tracker-server/src/server/launcher.rs | 3 ++- 6 files changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/axum-health-check-api-server/src/handlers.rs b/packages/axum-health-check-api-server/src/handlers.rs index 0af2ab05d..7e54d36ec 100644 --- a/packages/axum-health-check-api-server/src/handlers.rs +++ b/packages/axum-health-check-api-server/src/handlers.rs @@ -33,6 +33,7 @@ pub(crate) async fn health_check_handler(State(register): State CheckReport { binding: c.binding, info: c.info.clone(), + service_type: c.service_type, result: c.job.await.expect("it should be able to join into the checking function"), } }) diff --git a/packages/axum-health-check-api-server/src/resources.rs b/packages/axum-health-check-api-server/src/resources.rs index 3302fb966..c01547fad 100644 --- a/packages/axum-health-check-api-server/src/resources.rs +++ b/packages/axum-health-check-api-server/src/resources.rs @@ -12,6 +12,7 @@ pub enum Status { #[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct CheckReport { pub binding: SocketAddr, + pub service_type: String, pub info: String, pub result: Result, } diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index f14a33602..cc965e1d7 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -18,6 +18,7 @@ use tracing::instrument; use super::v1::routes::router; use crate::HTTP_TRACKER_LOG_TARGET; +const TYPE_STRING: &str = "http_tracker"; /// Error that can occur when starting or stopping the HTTP server. /// /// Some errors triggered while starting the server are: @@ -231,7 +232,7 @@ pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { } }); - ServiceHealthCheckJob::new(*binding, info, job) + ServiceHealthCheckJob::new(*binding, info, TYPE_STRING.to_string(), job) } #[cfg(test)] diff --git a/packages/axum-rest-tracker-api-server/src/server.rs b/packages/axum-rest-tracker-api-server/src/server.rs index fd8f92944..4d41347ab 100644 --- a/packages/axum-rest-tracker-api-server/src/server.rs +++ b/packages/axum-rest-tracker-api-server/src/server.rs @@ -45,6 +45,8 @@ use tracing::{instrument, Level}; use super::routes::router; use crate::API_LOG_TARGET; +const TYPE_STRING: &str = "tracker_rest_api"; + /// Errors that can occur when starting or stopping the API server. #[derive(Debug, Error)] pub enum Error { @@ -204,7 +206,7 @@ pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { Err(err) => Err(err.to_string()), } }); - ServiceHealthCheckJob::new(*binding, info, job) + ServiceHealthCheckJob::new(*binding, info, TYPE_STRING.to_string(), job) } /// A struct responsible for starting the API server. diff --git a/packages/server-lib/src/registar.rs b/packages/server-lib/src/registar.rs index 6b67188dc..0a0e9ada0 100644 --- a/packages/server-lib/src/registar.rs +++ b/packages/server-lib/src/registar.rs @@ -18,6 +18,7 @@ pub type ServiceHeathCheckResult = Result; pub struct ServiceHealthCheckJob { pub binding: SocketAddr, pub info: String, + pub service_type: String, pub job: JoinHandle, } diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index b21ac11ba..6473f300b 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -24,6 +24,7 @@ use crate::server::receiver::Receiver; const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 3600; +const TYPE_STRING: &str = "udp_tracker"; /// A UDP server instance launcher. #[derive(Constructor)] pub struct Launcher; @@ -117,7 +118,7 @@ impl Launcher { let job = tokio::spawn(async move { check(&binding).await }); - ServiceHealthCheckJob::new(binding, info, job) + ServiceHealthCheckJob::new(binding, info, TYPE_STRING.to_string(), job) } #[instrument(skip(receiver, udp_tracker_core_container, udp_tracker_server_container))] From abfb7331cfb01f2104804a8c7db25a79555c80a7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 26 Mar 2025 17:06:56 +0000 Subject: [PATCH 0925/1297] feat: [#1409] add listen_url field to the health check API ```json { "status": "Ok", "message": "", "details": [ { "listen_url": "http://0.0.0.0:7070/", "binding": "0.0.0.0:7070", "service_type": "http_tracker", "info": "checking http tracker health check at: http://0.0.0.0:7070/health_check", "result": { "Ok": "200 OK" } } ] } ``` The `binding` is not removed for back compatibility. --- Cargo.lock | 2 ++ .../axum-health-check-api-server/Cargo.toml | 1 + .../src/handlers.rs | 1 + .../src/resources.rs | 2 ++ .../axum-health-check-api-server/src/server.rs | 6 +++++- .../axum-http-tracker-server/src/server.rs | 18 ++++++++++++------ .../axum-rest-tracker-api-server/Cargo.toml | 1 + .../axum-rest-tracker-api-server/src/server.rs | 15 +++++++++------ packages/server-lib/Cargo.toml | 1 + packages/server-lib/src/logging.rs | 2 +- packages/server-lib/src/registar.rs | 7 +++++-- packages/server-lib/src/signals.rs | 2 ++ .../udp-tracker-server/src/server/launcher.rs | 8 +++++--- .../udp-tracker-server/src/server/states.rs | 7 +++++-- src/console/ci/e2e/logs_parser.rs | 8 ++++---- 15 files changed, 56 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c4755225f..c2d68639a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4380,6 +4380,7 @@ dependencies = [ "tower-http", "tracing", "tracing-subscriber", + "url", ] [[package]] @@ -4512,6 +4513,7 @@ dependencies = [ "tokio", "tower-http", "tracing", + "url", ] [[package]] diff --git a/packages/axum-health-check-api-server/Cargo.toml b/packages/axum-health-check-api-server/Cargo.toml index e24e609bf..6766ce587 100644 --- a/packages/axum-health-check-api-server/Cargo.toml +++ b/packages/axum-health-check-api-server/Cargo.toml @@ -26,6 +26,7 @@ torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" +url = "2.5.4" [dev-dependencies] reqwest = { version = "0", features = ["json"] } diff --git a/packages/axum-health-check-api-server/src/handlers.rs b/packages/axum-health-check-api-server/src/handlers.rs index 7e54d36ec..66390f089 100644 --- a/packages/axum-health-check-api-server/src/handlers.rs +++ b/packages/axum-health-check-api-server/src/handlers.rs @@ -31,6 +31,7 @@ pub(crate) async fn health_check_handler(State(register): State let jobs = checks.drain(..).map(|c| { tokio::spawn(async move { CheckReport { + listen_url: c.listen_url.clone(), binding: c.binding, info: c.info.clone(), service_type: c.service_type, diff --git a/packages/axum-health-check-api-server/src/resources.rs b/packages/axum-health-check-api-server/src/resources.rs index c01547fad..24079b00f 100644 --- a/packages/axum-health-check-api-server/src/resources.rs +++ b/packages/axum-health-check-api-server/src/resources.rs @@ -1,6 +1,7 @@ use std::net::SocketAddr; use serde::{Deserialize, Serialize}; +use url::Url; #[derive(Copy, Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] pub enum Status { @@ -11,6 +12,7 @@ pub enum Status { #[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct CheckReport { + pub listen_url: Url, pub binding: SocketAddr, pub service_type: String, pub info: String, diff --git a/packages/axum-health-check-api-server/src/server.rs b/packages/axum-health-check-api-server/src/server.rs index 733fec3a0..cc721f5eb 100644 --- a/packages/axum-health-check-api-server/src/server.rs +++ b/packages/axum-health-check-api-server/src/server.rs @@ -25,6 +25,7 @@ use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; use tower_http::LatencyUnit; use tracing::{instrument, Level, Span}; +use url::Url; use crate::handlers::health_check_handler; use crate::HEALTH_CHECK_API_LOG_TARGET; @@ -101,6 +102,9 @@ pub fn start( let socket = std::net::TcpListener::bind(bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); + let protocol = "http"; // The health check API only supports HTTP directly now. Use a reverse proxy for HTTPS. + let listen_url = + Url::parse(&format!("{protocol}://{address}")).expect("Could not parse internal service url for health check API."); let handle = Handle::new(); @@ -116,7 +120,7 @@ pub fn start( .handle(handle) .serve(router.into_make_service_with_connect_info::()); - tx.send(Started { address }) + tx.send(Started { listen_url, address }) .expect("the Health Check API server should not be dropped"); running diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index cc965e1d7..eefb124e8 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -7,6 +7,7 @@ use axum_server::Handle; use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use derive_more::Constructor; use futures::future::BoxFuture; +use reqwest::Url; use tokio::sync::oneshot::{Receiver, Sender}; use torrust_axum_server::custom_axum_server::{self, TimeoutAcceptor}; use torrust_axum_server::signals::graceful_shutdown; @@ -63,8 +64,10 @@ impl Launcher { let tls = self.tls.clone(); let protocol = if tls.is_some() { "https" } else { "http" }; + let listen_url = + Url::parse(&format!("{protocol}://{address}")).expect("Could not parse internal service url for HTTP tracker."); - tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{}", address); + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{address}"); let app = router(http_tracker_container, address); @@ -90,7 +93,7 @@ impl Launcher { tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); tx_start - .send(Started { address }) + .send(Started { listen_url, address }) .expect("the HTTP(s) Tracker service should not be dropped"); running @@ -177,9 +180,12 @@ impl HttpServer { launcher }); - let binding = rx_start.await.expect("it should be able to start the service").address; + let started = rx_start.await.expect("it should be able to start the service"); - form.send(ServiceRegistration::new(binding, check_fn)) + let listen_url = started.listen_url; + let binding = started.address; + + form.send(ServiceRegistration::new(listen_url, binding, check_fn)) .expect("it should be able to send service registration"); Ok(HttpServer { @@ -220,7 +226,7 @@ impl HttpServer { /// This function will return an error if unable to connect. /// Or if the request returns an error. #[must_use] -pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { +pub fn check_fn(listen_url: &Url, binding: &SocketAddr) -> ServiceHealthCheckJob { let url = format!("http://{binding}/health_check"); // DevSkim: ignore DS137138 let info = format!("checking http tracker health check at: {url}"); @@ -232,7 +238,7 @@ pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { } }); - ServiceHealthCheckJob::new(*binding, info, TYPE_STRING.to_string(), job) + ServiceHealthCheckJob::new(listen_url.clone(), *binding, info, TYPE_STRING.to_string(), job) } #[cfg(test)] diff --git a/packages/axum-rest-tracker-api-server/Cargo.toml b/packages/axum-rest-tracker-api-server/Cargo.toml index 9c0d2bc2f..42fe68584 100644 --- a/packages/axum-rest-tracker-api-server/Cargo.toml +++ b/packages/axum-rest-tracker-api-server/Cargo.toml @@ -42,6 +42,7 @@ torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" +url = "2" [dev-dependencies] local-ip-address = "0" diff --git a/packages/axum-rest-tracker-api-server/src/server.rs b/packages/axum-rest-tracker-api-server/src/server.rs index 4d41347ab..20775dbc1 100644 --- a/packages/axum-rest-tracker-api-server/src/server.rs +++ b/packages/axum-rest-tracker-api-server/src/server.rs @@ -41,6 +41,7 @@ use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, S use torrust_server_lib::signals::{Halted, Started}; use torrust_tracker_configuration::AccessTokens; use tracing::{instrument, Level}; +use url::Url; use super::routes::router; use crate::API_LOG_TARGET; @@ -148,7 +149,7 @@ impl ApiServer { let api_server = match rx_start.await { Ok(started) => { - form.send(ServiceRegistration::new(started.address, check_fn)) + form.send(ServiceRegistration::new(started.listen_url, started.address, check_fn)) .expect("it should be able to send service registration"); ApiServer { @@ -195,7 +196,7 @@ impl ApiServer { /// Or if there request returns an error code. #[must_use] #[instrument(skip())] -pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { +pub fn check_fn(listen_url: &Url, binding: &SocketAddr) -> ServiceHealthCheckJob { let url = format!("http://{binding}/api/health_check"); // DevSkim: ignore DS137138 let info = format!("checking api health check at: {url}"); @@ -206,7 +207,7 @@ pub fn check_fn(binding: &SocketAddr) -> ServiceHealthCheckJob { Err(err) => Err(err.to_string()), } }); - ServiceHealthCheckJob::new(*binding, info, TYPE_STRING.to_string(), job) + ServiceHealthCheckJob::new(listen_url.clone(), *binding, info, TYPE_STRING.to_string(), job) } /// A struct responsible for starting the API server. @@ -260,8 +261,10 @@ impl Launcher { let tls = self.tls.clone(); let protocol = if tls.is_some() { "https" } else { "http" }; + let listen_url = + Url::parse(&format!("{protocol}://{address}")).expect("Could not parse internal service url for tracker API."); - tracing::info!(target: API_LOG_TARGET, "Starting on {protocol}://{}", address); + tracing::info!(target: API_LOG_TARGET, "Starting on: {protocol}://{address}"); let running = Box::pin(async { match tls { @@ -282,10 +285,10 @@ impl Launcher { } }); - tracing::info!(target: API_LOG_TARGET, "{STARTED_ON} {protocol}://{}", address); + tracing::info!(target: API_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); tx_start - .send(Started { address }) + .send(Started { listen_url, address }) .expect("the HTTP(s) Tracker API service should not be dropped"); running diff --git a/packages/server-lib/Cargo.toml b/packages/server-lib/Cargo.toml index b8514fbf4..514828953 100644 --- a/packages/server-lib/Cargo.toml +++ b/packages/server-lib/Cargo.toml @@ -18,5 +18,6 @@ derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" +url = "2.5.4" [dev-dependencies] diff --git a/packages/server-lib/src/logging.rs b/packages/server-lib/src/logging.rs index c503cfd35..c63ba3caf 100644 --- a/packages/server-lib/src/logging.rs +++ b/packages/server-lib/src/logging.rs @@ -10,7 +10,7 @@ use tower_http::LatencyUnit; /// ```text /// 2024-06-25T12:36:25.025312Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969 /// 2024-06-25T12:36:25.025445Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 -/// 2024-06-25T12:36:25.025527Z INFO API: Started on http://0.0.0.0:1212 +/// 2024-06-25T12:36:25.025527Z INFO API: Started on: http://0.0.0.0:1212 /// 2024-06-25T12:36:25.025580Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 /// ``` pub const STARTED_ON: &str = "Started on"; diff --git a/packages/server-lib/src/registar.rs b/packages/server-lib/src/registar.rs index 0a0e9ada0..9d36cf1fe 100644 --- a/packages/server-lib/src/registar.rs +++ b/packages/server-lib/src/registar.rs @@ -7,6 +7,7 @@ use std::sync::Arc; use derive_more::Constructor; use tokio::sync::Mutex; use tokio::task::JoinHandle; +use url::Url; /// A [`ServiceHeathCheckResult`] is returned by a completed health check. pub type ServiceHeathCheckResult = Result; @@ -16,6 +17,7 @@ pub type ServiceHeathCheckResult = Result; /// The `job` awaits a [`ServiceHeathCheckResult`]. #[derive(Debug, Constructor)] pub struct ServiceHealthCheckJob { + pub listen_url: Url, pub binding: SocketAddr, pub info: String, pub service_type: String, @@ -25,13 +27,14 @@ pub struct ServiceHealthCheckJob { /// The function specification [`FnSpawnServiceHeathCheck`]. /// /// A function fulfilling this specification will spawn a new [`ServiceHealthCheckJob`]. -pub type FnSpawnServiceHeathCheck = fn(&SocketAddr) -> ServiceHealthCheckJob; +pub type FnSpawnServiceHeathCheck = fn(&Url, &SocketAddr) -> ServiceHealthCheckJob; /// A [`ServiceRegistration`] is provided to the [`Registar`] for registration. /// /// Each registration includes a function that fulfils the [`FnSpawnServiceHeathCheck`] specification. #[derive(Clone, Debug, Constructor)] pub struct ServiceRegistration { + listen_url: Url, binding: SocketAddr, check_fn: FnSpawnServiceHeathCheck, } @@ -39,7 +42,7 @@ pub struct ServiceRegistration { impl ServiceRegistration { #[must_use] pub fn spawn_check(&self) -> ServiceHealthCheckJob { - (self.check_fn)(&self.binding) + (self.check_fn)(&self.listen_url, &self.binding) } } diff --git a/packages/server-lib/src/signals.rs b/packages/server-lib/src/signals.rs index 63f7554c8..94ee474ea 100644 --- a/packages/server-lib/src/signals.rs +++ b/packages/server-lib/src/signals.rs @@ -1,12 +1,14 @@ //! This module contains functions to handle signals. use derive_more::Display; use tracing::instrument; +use url::Url; /// This is the message that the "launcher" spawned task sends to the main /// application process to notify the service was successfully started. /// #[derive(Debug)] pub struct Started { + pub listen_url: Url, pub address: std::net::SocketAddr, } diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index 6473f300b..67e2ceed6 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -14,6 +14,7 @@ use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::ServiceHealthCheckJob; use torrust_server_lib::signals::{shutdown_signal_with_message, Halted, Started}; use tracing::instrument; +use url::Url; use super::request_buffer::ActiveRequests; use crate::container::UdpTrackerServerContainer; @@ -65,6 +66,7 @@ impl Launcher { } }; + let listen_url = bound_socket.url().clone(); let address = bound_socket.address(); let local_udp_url = bound_socket.url().to_string(); @@ -89,7 +91,7 @@ impl Launcher { }; tx_start - .send(Started { address }) + .send(Started { listen_url, address }) .expect("the UDP Tracker service should not be dropped"); tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (started)"); @@ -112,13 +114,13 @@ impl Launcher { #[must_use] #[instrument(skip(binding))] - pub fn check(binding: &SocketAddr) -> ServiceHealthCheckJob { + pub fn check(listen_url: &Url, binding: &SocketAddr) -> ServiceHealthCheckJob { let binding = *binding; let info = format!("checking the udp tracker health check at: {binding}"); let job = tokio::spawn(async move { check(&binding).await }); - ServiceHealthCheckJob::new(binding, info, TYPE_STRING.to_string(), job) + ServiceHealthCheckJob::new(listen_url.clone(), binding, info, TYPE_STRING.to_string(), job) } #[instrument(skip(receiver, udp_tracker_core_container, udp_tracker_server_container))] diff --git a/packages/udp-tracker-server/src/server/states.rs b/packages/udp-tracker-server/src/server/states.rs index 4d1c97167..f10a02fb7 100644 --- a/packages/udp-tracker-server/src/server/states.rs +++ b/packages/udp-tracker-server/src/server/states.rs @@ -83,9 +83,12 @@ impl Server { rx_halt, ); - let local_addr = rx_start.await.expect("it should be able to start the service").address; + let started = rx_start.await.expect("it should be able to start the service"); - form.send(ServiceRegistration::new(local_addr, Launcher::check)) + let listen_url = started.listen_url; + let local_addr = started.address; + + form.send(ServiceRegistration::new(listen_url, local_addr, Launcher::check)) .expect("it should be able to send service registration"); let running_udp_server: Server = Server { diff --git a/src/console/ci/e2e/logs_parser.rs b/src/console/ci/e2e/logs_parser.rs index c406fa7a5..e8b6b3b8f 100644 --- a/src/console/ci/e2e/logs_parser.rs +++ b/src/console/ci/e2e/logs_parser.rs @@ -31,8 +31,8 @@ impl RunningServices { /// 2024-06-10T16:07:39.990303Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070 /// 2024-06-10T16:07:39.990439Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 /// 2024-06-10T16:07:39.990448Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled - /// 2024-06-10T16:07:39.990563Z INFO API: Starting on http://127.0.0.1:1212 - /// 2024-06-10T16:07:39.990565Z INFO API: Started on http://127.0.0.1:1212 + /// 2024-06-10T16:07:39.990563Z INFO API: Starting on: http://127.0.0.1:1212 + /// 2024-06-10T16:07:39.990565Z INFO API: Started on: http://127.0.0.1:1212 /// 2024-06-10T16:07:39.990577Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 /// 2024-06-10T16:07:39.990638Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 /// ``` @@ -122,8 +122,8 @@ mod tests { 2024-06-10T16:07:39.990303Z INFO HTTP TRACKER: Starting on: http://0.0.0.0:7070 2024-06-10T16:07:39.990439Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070 2024-06-10T16:07:39.990448Z INFO torrust_tracker::bootstrap::jobs: TLS not enabled - 2024-06-10T16:07:39.990563Z INFO API: Starting on http://127.0.0.1:1212 - 2024-06-10T16:07:39.990565Z INFO API: Started on http://127.0.0.1:1212 + 2024-06-10T16:07:39.990563Z INFO API: Starting on: http://127.0.0.1:1212 + 2024-06-10T16:07:39.990565Z INFO API: Started on: http://127.0.0.1:1212 2024-06-10T16:07:39.990577Z INFO HEALTH CHECK API: Starting on: http://127.0.0.1:1313 2024-06-10T16:07:39.990638Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313 "; From 376c1df2d63e7f29ba17d23f10d763a68918fa6f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 28 Mar 2025 12:24:45 +0000 Subject: [PATCH 0926/1297] fix: missing feature in package cargo config --- packages/server-lib/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/server-lib/Cargo.toml b/packages/server-lib/Cargo.toml index 514828953..25a63e99d 100644 --- a/packages/server-lib/Cargo.toml +++ b/packages/server-lib/Cargo.toml @@ -14,7 +14,7 @@ rust-version.workspace = true version.workspace = true [dependencies] -derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } +derive_more = { version = "2", features = ["as_ref", "constructor", "display", "from"] } tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" From 29fa324417201eb6a8ec0103e7fb200ca46670d2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 28 Mar 2025 17:12:01 +0000 Subject: [PATCH 0927/1297] refactor: [#1422] extract type ServiceBinding Refactor: extract type `ServiceBinding`. It's the protocol + socket binding address for a service. - Protocols are only: udp, http and https (protocols used by the tracker now). - The port must be greater than zero (already assigned). - Any protocol and port combination is possible. For example: http protocol with a port different than 80. --- Cargo.lock | 6 +- .../axum-health-check-api-server/Cargo.toml | 1 + .../src/handlers.rs | 4 +- .../src/resources.rs | 2 +- .../src/server.rs | 14 +- .../axum-http-tracker-server/src/server.rs | 22 +- .../src/server.rs | 20 +- packages/primitives/Cargo.toml | 4 + packages/primitives/src/lib.rs | 1 + packages/primitives/src/service_binding.rs | 188 ++++++++++++++++++ packages/server-lib/Cargo.toml | 3 +- packages/server-lib/src/registar.rs | 17 +- packages/server-lib/src/signals.rs | 4 +- packages/tracker-client/src/udp/client.rs | 7 +- .../src/server/bound_socket.rs | 10 + .../udp-tracker-server/src/server/launcher.rs | 22 +- .../udp-tracker-server/src/server/states.rs | 4 +- 17 files changed, 274 insertions(+), 55 deletions(-) create mode 100644 packages/primitives/src/service_binding.rs diff --git a/Cargo.lock b/Cargo.lock index c2d68639a..328e2db93 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4375,6 +4375,7 @@ dependencies = [ "torrust-server-lib", "torrust-tracker-clock", "torrust-tracker-configuration", + "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-udp-tracker-server", "tower-http", @@ -4510,10 +4511,11 @@ name = "torrust-server-lib" version = "3.0.0-develop" dependencies = [ "derive_more", + "rstest", "tokio", + "torrust-tracker-primitives", "tower-http", "tracing", - "url", ] [[package]] @@ -4632,11 +4634,13 @@ dependencies = [ "binascii", "bittorrent-primitives", "derive_more", + "rstest", "serde", "tdyne-peer-id", "tdyne-peer-id-registry", "thiserror 2.0.12", "torrust-tracker-configuration", + "url", "zerocopy 0.7.35", ] diff --git a/packages/axum-health-check-api-server/Cargo.toml b/packages/axum-health-check-api-server/Cargo.toml index 6766ce587..e0504f7df 100644 --- a/packages/axum-health-check-api-server/Cargo.toml +++ b/packages/axum-health-check-api-server/Cargo.toml @@ -24,6 +24,7 @@ tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" url = "2.5.4" diff --git a/packages/axum-health-check-api-server/src/handlers.rs b/packages/axum-health-check-api-server/src/handlers.rs index 66390f089..a26c901d7 100644 --- a/packages/axum-health-check-api-server/src/handlers.rs +++ b/packages/axum-health-check-api-server/src/handlers.rs @@ -31,8 +31,8 @@ pub(crate) async fn health_check_handler(State(register): State let jobs = checks.drain(..).map(|c| { tokio::spawn(async move { CheckReport { - listen_url: c.listen_url.clone(), - binding: c.binding, + service_binding: c.service_binding.url(), + binding: c.service_binding.bind_address(), info: c.info.clone(), service_type: c.service_type, result: c.job.await.expect("it should be able to join into the checking function"), diff --git a/packages/axum-health-check-api-server/src/resources.rs b/packages/axum-health-check-api-server/src/resources.rs index 24079b00f..44e64b24c 100644 --- a/packages/axum-health-check-api-server/src/resources.rs +++ b/packages/axum-health-check-api-server/src/resources.rs @@ -12,7 +12,7 @@ pub enum Status { #[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)] pub struct CheckReport { - pub listen_url: Url, + pub service_binding: Url, pub binding: SocketAddr, pub service_type: String, pub info: String, diff --git a/packages/axum-health-check-api-server/src/server.rs b/packages/axum-health-check-api-server/src/server.rs index cc721f5eb..8b37f1828 100644 --- a/packages/axum-health-check-api-server/src/server.rs +++ b/packages/axum-health-check-api-server/src/server.rs @@ -18,6 +18,7 @@ use torrust_axum_server::signals::graceful_shutdown; use torrust_server_lib::logging::Latency; use torrust_server_lib::registar::ServiceRegistry; use torrust_server_lib::signals::{Halted, Started}; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use tower_http::classify::ServerErrorsFailureClass; use tower_http::compression::CompressionLayer; use tower_http::propagate_header::PropagateHeaderLayer; @@ -25,7 +26,6 @@ use tower_http::request_id::{MakeRequestUuid, SetRequestIdLayer}; use tower_http::trace::{DefaultMakeSpan, TraceLayer}; use tower_http::LatencyUnit; use tracing::{instrument, Level, Span}; -use url::Url; use crate::handlers::health_check_handler; use crate::HEALTH_CHECK_API_LOG_TARGET; @@ -102,9 +102,8 @@ pub fn start( let socket = std::net::TcpListener::bind(bind_to).expect("Could not bind tcp_listener to address."); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); - let protocol = "http"; // The health check API only supports HTTP directly now. Use a reverse proxy for HTTPS. - let listen_url = - Url::parse(&format!("{protocol}://{address}")).expect("Could not parse internal service url for health check API."); + let protocol = Protocol::HTTP; // The health check API only supports HTTP directly now. Use a reverse proxy for HTTPS. + let service_binding = ServiceBinding::new(protocol.clone(), address).expect("Service binding creation failed"); let handle = Handle::new(); @@ -120,8 +119,11 @@ pub fn start( .handle(handle) .serve(router.into_make_service_with_connect_info::()); - tx.send(Started { listen_url, address }) - .expect("the Health Check API server should not be dropped"); + tx.send(Started { + service_binding, + address, + }) + .expect("the Health Check API server should not be dropped"); running } diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index eefb124e8..610f70020 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -7,13 +7,13 @@ use axum_server::Handle; use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use derive_more::Constructor; use futures::future::BoxFuture; -use reqwest::Url; use tokio::sync::oneshot::{Receiver, Sender}; use torrust_axum_server::custom_axum_server::{self, TimeoutAcceptor}; use torrust_axum_server::signals::graceful_shutdown; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use torrust_server_lib::signals::{Halted, Started}; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use tracing::instrument; use super::v1::routes::router; @@ -63,9 +63,8 @@ impl Launcher { )); let tls = self.tls.clone(); - let protocol = if tls.is_some() { "https" } else { "http" }; - let listen_url = - Url::parse(&format!("{protocol}://{address}")).expect("Could not parse internal service url for HTTP tracker."); + let protocol = if tls.is_some() { Protocol::HTTPS } else { Protocol::HTTP }; + let service_binding = ServiceBinding::new(protocol.clone(), address).expect("Service binding creation failed"); tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{address}"); @@ -93,7 +92,10 @@ impl Launcher { tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); tx_start - .send(Started { listen_url, address }) + .send(Started { + service_binding, + address, + }) .expect("the HTTP(s) Tracker service should not be dropped"); running @@ -182,10 +184,10 @@ impl HttpServer { let started = rx_start.await.expect("it should be able to start the service"); - let listen_url = started.listen_url; + let listen_url = started.service_binding; let binding = started.address; - form.send(ServiceRegistration::new(listen_url, binding, check_fn)) + form.send(ServiceRegistration::new(listen_url, check_fn)) .expect("it should be able to send service registration"); Ok(HttpServer { @@ -226,8 +228,8 @@ impl HttpServer { /// This function will return an error if unable to connect. /// Or if the request returns an error. #[must_use] -pub fn check_fn(listen_url: &Url, binding: &SocketAddr) -> ServiceHealthCheckJob { - let url = format!("http://{binding}/health_check"); // DevSkim: ignore DS137138 +pub fn check_fn(service_binding: &ServiceBinding) -> ServiceHealthCheckJob { + let url = format!("http://{}/health_check", service_binding.bind_address()); // DevSkim: ignore DS137138 let info = format!("checking http tracker health check at: {url}"); @@ -238,7 +240,7 @@ pub fn check_fn(listen_url: &Url, binding: &SocketAddr) -> ServiceHealthCheckJob } }); - ServiceHealthCheckJob::new(listen_url.clone(), *binding, info, TYPE_STRING.to_string(), job) + ServiceHealthCheckJob::new(service_binding.clone(), info, TYPE_STRING.to_string(), job) } #[cfg(test)] diff --git a/packages/axum-rest-tracker-api-server/src/server.rs b/packages/axum-rest-tracker-api-server/src/server.rs index 20775dbc1..cbd4948ff 100644 --- a/packages/axum-rest-tracker-api-server/src/server.rs +++ b/packages/axum-rest-tracker-api-server/src/server.rs @@ -40,8 +40,8 @@ use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistrationForm}; use torrust_server_lib::signals::{Halted, Started}; use torrust_tracker_configuration::AccessTokens; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use tracing::{instrument, Level}; -use url::Url; use super::routes::router; use crate::API_LOG_TARGET; @@ -149,7 +149,7 @@ impl ApiServer { let api_server = match rx_start.await { Ok(started) => { - form.send(ServiceRegistration::new(started.listen_url, started.address, check_fn)) + form.send(ServiceRegistration::new(started.service_binding, check_fn)) .expect("it should be able to send service registration"); ApiServer { @@ -196,8 +196,8 @@ impl ApiServer { /// Or if there request returns an error code. #[must_use] #[instrument(skip())] -pub fn check_fn(listen_url: &Url, binding: &SocketAddr) -> ServiceHealthCheckJob { - let url = format!("http://{binding}/api/health_check"); // DevSkim: ignore DS137138 +pub fn check_fn(service_binding: &ServiceBinding) -> ServiceHealthCheckJob { + let url = format!("http://{}/api/health_check", service_binding.bind_address()); // DevSkim: ignore DS137138 let info = format!("checking api health check at: {url}"); @@ -207,7 +207,7 @@ pub fn check_fn(listen_url: &Url, binding: &SocketAddr) -> ServiceHealthCheckJob Err(err) => Err(err.to_string()), } }); - ServiceHealthCheckJob::new(listen_url.clone(), *binding, info, TYPE_STRING.to_string(), job) + ServiceHealthCheckJob::new(service_binding.clone(), info, TYPE_STRING.to_string(), job) } /// A struct responsible for starting the API server. @@ -260,9 +260,8 @@ impl Launcher { )); let tls = self.tls.clone(); - let protocol = if tls.is_some() { "https" } else { "http" }; - let listen_url = - Url::parse(&format!("{protocol}://{address}")).expect("Could not parse internal service url for tracker API."); + let protocol = if tls.is_some() { Protocol::HTTPS } else { Protocol::HTTP }; + let service_binding = ServiceBinding::new(protocol.clone(), address).expect("Service binding creation failed"); tracing::info!(target: API_LOG_TARGET, "Starting on: {protocol}://{address}"); @@ -288,7 +287,10 @@ impl Launcher { tracing::info!(target: API_LOG_TARGET, "{STARTED_ON}: {protocol}://{}", address); tx_start - .send(Started { listen_url, address }) + .send(Started { + service_binding, + address, + }) .expect("the HTTP(s) Tracker API service should not be dropped"); running diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index 1396d8bc8..21fab09bf 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -24,4 +24,8 @@ tdyne-peer-id = "1" tdyne-peer-id-registry = "0" thiserror = "2" torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +url = "2.5.4" zerocopy = "0.7" + +[dev-dependencies] +rstest = "0.25.0" diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index b50516893..c901e5276 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -7,6 +7,7 @@ pub mod core; pub mod pagination; pub mod peer; +pub mod service_binding; pub mod swarm_metadata; use std::collections::BTreeMap; diff --git a/packages/primitives/src/service_binding.rs b/packages/primitives/src/service_binding.rs new file mode 100644 index 000000000..dbbb32fd5 --- /dev/null +++ b/packages/primitives/src/service_binding.rs @@ -0,0 +1,188 @@ +use std::fmt; +use std::net::SocketAddr; + +use serde::{Deserialize, Serialize}; +use url::Url; + +/// Represents the supported network protocols. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub enum Protocol { + UDP, + HTTP, + HTTPS, +} + +impl fmt::Display for Protocol { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let proto_str = match self { + Protocol::UDP => "udp", + Protocol::HTTP => "http", + Protocol::HTTPS => "https", + }; + write!(f, "{proto_str}") + } +} + +#[derive(thiserror::Error, Debug, Clone)] +pub enum Error { + #[error("The port number cannot be zero. It must be an assigned valid port.")] + PortZeroNotAllowed, +} + +/// Represents a network service binding, encapsulating protocol and socket +/// address. +/// +/// This struct is used to define how a service binds to a network interface and +/// port. +/// +/// It's an URL without path and some restrictions: +/// +/// - Only some schemes are accepted: `udp`, `http`, `https`. +/// - The port number must be greater than zero. The service should be already +/// listening on that port. +/// - The authority part of the URL must be a valid socket address (wildcard is +/// accepted). +/// +/// Besides it accepts some non well-formed URLs, like: +/// or . Those URLs are not valid because they use non +/// standard ports (80 and 443). +/// +/// NOTICE: It does not represent a public valid URL clients can connect to. It +/// represents the service's internal URL configuration after assigning a port. +/// If the port in the configuration is not zero, it's basically the same +/// information you get from the configuration (binding address + protocol). +/// +/// # Examples +/// +/// ``` +/// use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +/// use torrust_tracker_primitives::service_binding::{ServiceBinding, Protocol}; +/// +/// let service_binding = ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(); +/// +/// assert_eq!(service_binding.url().to_string(), "http://127.0.0.1:7070/".to_string()); +/// ``` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub struct ServiceBinding { + /// The network protocol used by the service (UDP, HTTP, HTTPS). + protocol: Protocol, + + /// The socket address (IP and port) to which the service binds. + bind_address: SocketAddr, +} + +impl ServiceBinding { + /// # Errors + /// + /// This function will return an error if the port number is zero. + pub fn new(protocol: Protocol, bind_address: SocketAddr) -> Result { + if bind_address.port() == 0 { + return Err(Error::PortZeroNotAllowed); + } + + Ok(Self { protocol, bind_address }) + } + + #[must_use] + pub fn bind_address(&self) -> SocketAddr { + self.bind_address + } + + /// # Panics + /// + /// It never panics because the URL is always valid. + #[must_use] + pub fn url(&self) -> Url { + Url::parse(&format!("{}://{}", self.protocol, self.bind_address)) + .expect("Service binding can always be parsed into a URL") + } +} + +impl From for Url { + fn from(service_binding: ServiceBinding) -> Self { + service_binding.url() + } +} + +impl fmt::Display for ServiceBinding { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.url()) + } +} + +#[cfg(test)] +mod tests { + + mod the_service_binding { + use std::net::SocketAddr; + use std::str::FromStr; + + use rstest::rstest; + use url::Url; + + use crate::service_binding::{Error, Protocol, ServiceBinding}; + + #[rstest] + #[case("wildcard_ip", Protocol::UDP, SocketAddr::from_str("0.0.0.0:6969").unwrap())] + #[case("udp_service", Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap())] + #[case("http_service", Protocol::HTTP, SocketAddr::from_str("127.0.0.1:7070").unwrap())] + #[case("https_service", Protocol::HTTPS, SocketAddr::from_str("127.0.0.1:7070").unwrap())] + fn should_allow_a_subset_of_urls(#[case] case: &str, #[case] protocol: Protocol, #[case] bind_address: SocketAddr) { + let service_binding = ServiceBinding::new(protocol.clone(), bind_address); + + assert!(service_binding.is_ok(), "{}", format!("{case} failed: {service_binding:?}")); + } + + #[test] + fn should_not_allow_undefined_port_zero() { + let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:0").unwrap()); + + assert!(matches!(service_binding, Err(Error::PortZeroNotAllowed))); + } + + #[test] + fn should_return_the_bind_address() { + let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap(); + + assert_eq!( + service_binding.bind_address(), + SocketAddr::from_str("127.0.0.1:6969").unwrap() + ); + } + + #[test] + fn should_return_the_corresponding_url() { + let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap(); + + assert_eq!(service_binding.url(), Url::parse("udp://127.0.0.1:6969").unwrap()); + } + + #[test] + fn should_be_converted_into_an_url() { + let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap(); + + let url: Url = service_binding.clone().into(); + + assert_eq!(url, Url::parse("udp://127.0.0.1:6969").unwrap()); + } + + #[rstest] + #[case("udp_service", Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap(), "udp://127.0.0.1:6969")] + #[case("http_service", Protocol::HTTP, SocketAddr::from_str("127.0.0.1:7070").unwrap(), "http://127.0.0.1:7070/")] + #[case("https_service", Protocol::HTTPS, SocketAddr::from_str("127.0.0.1:7070").unwrap(), "https://127.0.0.1:7070/")] + fn should_always_have_a_corresponding_unique_url( + #[case] case: &str, + #[case] protocol: Protocol, + #[case] bind_address: SocketAddr, + #[case] expected_url: String, + ) { + let service_binding = ServiceBinding::new(protocol.clone(), bind_address).unwrap(); + + assert_eq!( + service_binding.url().to_string(), + expected_url, + "{case} failed: {service_binding:?}", + ); + } + } +} diff --git a/packages/server-lib/Cargo.toml b/packages/server-lib/Cargo.toml index 25a63e99d..1d30e7fb5 100644 --- a/packages/server-lib/Cargo.toml +++ b/packages/server-lib/Cargo.toml @@ -16,8 +16,9 @@ version.workspace = true [dependencies] derive_more = { version = "2", features = ["as_ref", "constructor", "display", "from"] } tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" -url = "2.5.4" [dev-dependencies] +rstest = "0.25.0" diff --git a/packages/server-lib/src/registar.rs b/packages/server-lib/src/registar.rs index 9d36cf1fe..efa94034b 100644 --- a/packages/server-lib/src/registar.rs +++ b/packages/server-lib/src/registar.rs @@ -1,13 +1,12 @@ //! Registar. Registers Services for Health Check. use std::collections::HashMap; -use std::net::SocketAddr; use std::sync::Arc; use derive_more::Constructor; use tokio::sync::Mutex; use tokio::task::JoinHandle; -use url::Url; +use torrust_tracker_primitives::service_binding::ServiceBinding; /// A [`ServiceHeathCheckResult`] is returned by a completed health check. pub type ServiceHeathCheckResult = Result; @@ -17,8 +16,7 @@ pub type ServiceHeathCheckResult = Result; /// The `job` awaits a [`ServiceHeathCheckResult`]. #[derive(Debug, Constructor)] pub struct ServiceHealthCheckJob { - pub listen_url: Url, - pub binding: SocketAddr, + pub service_binding: ServiceBinding, pub info: String, pub service_type: String, pub job: JoinHandle, @@ -27,22 +25,21 @@ pub struct ServiceHealthCheckJob { /// The function specification [`FnSpawnServiceHeathCheck`]. /// /// A function fulfilling this specification will spawn a new [`ServiceHealthCheckJob`]. -pub type FnSpawnServiceHeathCheck = fn(&Url, &SocketAddr) -> ServiceHealthCheckJob; +pub type FnSpawnServiceHeathCheck = fn(&ServiceBinding) -> ServiceHealthCheckJob; /// A [`ServiceRegistration`] is provided to the [`Registar`] for registration. /// /// Each registration includes a function that fulfils the [`FnSpawnServiceHeathCheck`] specification. #[derive(Clone, Debug, Constructor)] pub struct ServiceRegistration { - listen_url: Url, - binding: SocketAddr, + service_binding: ServiceBinding, check_fn: FnSpawnServiceHeathCheck, } impl ServiceRegistration { #[must_use] pub fn spawn_check(&self) -> ServiceHealthCheckJob { - (self.check_fn)(&self.listen_url, &self.binding) + (self.check_fn)(&self.service_binding) } } @@ -50,7 +47,7 @@ impl ServiceRegistration { pub type ServiceRegistrationForm = tokio::sync::oneshot::Sender; /// The [`ServiceRegistry`] contains each unique [`ServiceRegistration`] by it's [`SocketAddr`]. -pub type ServiceRegistry = Arc>>; +pub type ServiceRegistry = Arc>>; /// The [`Registar`] manages the [`ServiceRegistry`]. #[derive(Clone, Debug)] @@ -93,7 +90,7 @@ impl Registar { let mut mutex = self.registry.lock().await; - mutex.insert(service_registration.binding, service_registration); + mutex.insert(service_registration.service_binding.clone(), service_registration); } /// Returns the [`ServiceRegistry`] of services diff --git a/packages/server-lib/src/signals.rs b/packages/server-lib/src/signals.rs index 94ee474ea..581729e57 100644 --- a/packages/server-lib/src/signals.rs +++ b/packages/server-lib/src/signals.rs @@ -1,14 +1,14 @@ //! This module contains functions to handle signals. use derive_more::Display; +use torrust_tracker_primitives::service_binding::ServiceBinding; use tracing::instrument; -use url::Url; /// This is the message that the "launcher" spawned task sends to the main /// application process to notify the service was successfully started. /// #[derive(Debug)] pub struct Started { - pub listen_url: Url, + pub service_binding: ServiceBinding, pub address: std::net::SocketAddr, } diff --git a/packages/tracker-client/src/udp/client.rs b/packages/tracker-client/src/udp/client.rs index 89a33726d..1c5ffd901 100644 --- a/packages/tracker-client/src/udp/client.rs +++ b/packages/tracker-client/src/udp/client.rs @@ -8,6 +8,7 @@ use aquatic_udp_protocol::{ConnectRequest, Request, Response, TransactionId}; use tokio::net::UdpSocket; use tokio::time; use torrust_tracker_configuration::DEFAULT_TIMEOUT; +use torrust_tracker_primitives::service_binding::ServiceBinding; use zerocopy::network_endian::I32; use super::Error; @@ -230,10 +231,12 @@ impl UdpTrackerClient { /// /// # Errors /// -pub async fn check(remote_addr: &SocketAddr) -> Result { +pub async fn check(service_binding: &ServiceBinding) -> Result { + let remote_addr = service_binding.bind_address(); + tracing::debug!("Checking Service (detail): {remote_addr:?}."); - match UdpTrackerClient::new(*remote_addr, DEFAULT_TIMEOUT).await { + match UdpTrackerClient::new(remote_addr, DEFAULT_TIMEOUT).await { Ok(client) => { let connect_request = ConnectRequest { transaction_id: TransactionId(I32::new(123)), diff --git a/packages/udp-tracker-server/src/server/bound_socket.rs b/packages/udp-tracker-server/src/server/bound_socket.rs index 988bfb67f..6b81545d2 100644 --- a/packages/udp-tracker-server/src/server/bound_socket.rs +++ b/packages/udp-tracker-server/src/server/bound_socket.rs @@ -3,6 +3,7 @@ use std::net::SocketAddr; use std::ops::Deref; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use url::Url; /// Wrapper for Tokio [`UdpSocket`][`tokio::net::UdpSocket`] that is bound to a particular socket. @@ -47,6 +48,15 @@ impl BoundSocket { pub fn url(&self) -> Url { Url::parse(&format!("udp://{}", self.address())).expect("UDP socket address should be valid") } + + /// # Panics + /// + /// It should never panic because the conversion to a [`ServiceBinding`] + /// is infallible. + #[must_use] + pub fn service_binding(&self) -> ServiceBinding { + ServiceBinding::new(Protocol::UDP, self.address()).expect("Conversion to ServiceBinding should not fail") + } } impl Deref for BoundSocket { diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index 67e2ceed6..fd689a96f 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -13,8 +13,8 @@ use tokio::time::interval; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::ServiceHealthCheckJob; use torrust_server_lib::signals::{shutdown_signal_with_message, Halted, Started}; +use torrust_tracker_primitives::service_binding::ServiceBinding; use tracing::instrument; -use url::Url; use super::request_buffer::ActiveRequests; use crate::container::UdpTrackerServerContainer; @@ -66,7 +66,7 @@ impl Launcher { } }; - let listen_url = bound_socket.url().clone(); + let service_binding = bound_socket.service_binding().clone(); let address = bound_socket.address(); let local_udp_url = bound_socket.url().to_string(); @@ -91,7 +91,10 @@ impl Launcher { }; tx_start - .send(Started { listen_url, address }) + .send(Started { + service_binding, + address, + }) .expect("the UDP Tracker service should not be dropped"); tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_udp_url, "Udp::run_with_graceful_shutdown (started)"); @@ -113,14 +116,15 @@ impl Launcher { } #[must_use] - #[instrument(skip(binding))] - pub fn check(listen_url: &Url, binding: &SocketAddr) -> ServiceHealthCheckJob { - let binding = *binding; - let info = format!("checking the udp tracker health check at: {binding}"); + #[instrument(skip(service_binding))] + pub fn check(service_binding: &ServiceBinding) -> ServiceHealthCheckJob { + let info = format!("checking the udp tracker health check at: {}", service_binding.bind_address()); + + let service_binding_clone = service_binding.clone(); - let job = tokio::spawn(async move { check(&binding).await }); + let job = tokio::spawn(async move { check(&service_binding_clone).await }); - ServiceHealthCheckJob::new(listen_url.clone(), binding, info, TYPE_STRING.to_string(), job) + ServiceHealthCheckJob::new(service_binding.clone(), info, TYPE_STRING.to_string(), job) } #[instrument(skip(receiver, udp_tracker_core_container, udp_tracker_server_container))] diff --git a/packages/udp-tracker-server/src/server/states.rs b/packages/udp-tracker-server/src/server/states.rs index f10a02fb7..4ad059095 100644 --- a/packages/udp-tracker-server/src/server/states.rs +++ b/packages/udp-tracker-server/src/server/states.rs @@ -85,10 +85,10 @@ impl Server { let started = rx_start.await.expect("it should be able to start the service"); - let listen_url = started.listen_url; + let service_binding = started.service_binding; let local_addr = started.address; - form.send(ServiceRegistration::new(listen_url, local_addr, Launcher::check)) + form.send(ServiceRegistration::new(service_binding, Launcher::check)) .expect("it should be able to send service registration"); let running_udp_server: Server = Server { From 8c4403300418f3bb67ab738e9015fbad7e6f0e37 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 31 Mar 2025 11:55:00 +0100 Subject: [PATCH 0928/1297] feat: [#1424] add ServiceBinding to HTTP core events --- .../axum-http-tracker-server/src/server.rs | 2 +- .../src/v1/handlers/announce.rs | 33 ++++++++----- .../src/v1/handlers/scrape.rs | 39 +++++++++++---- .../axum-http-tracker-server/src/v1/routes.rs | 24 ++++++--- .../http-tracker-core/benches/helpers/sync.rs | 4 +- packages/http-tracker-core/src/event/mod.rs | 10 ++-- .../src/services/announce.rs | 39 ++++++++++----- .../http-tracker-core/src/services/scrape.rs | 49 +++++++++++++------ .../src/statistics/event/handler.rs | 10 ++-- 9 files changed, 144 insertions(+), 66 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 610f70020..eea00c142 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -68,7 +68,7 @@ impl Launcher { tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{address}"); - let app = router(http_tracker_container, address); + let app = router(http_tracker_container, service_binding.clone()); let running = Box::pin(async { match tls { diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 53fd38997..296cefcd5 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -2,7 +2,6 @@ //! //! The handlers perform the authentication and authorization of the request, //! and resolve the client IP address. -use std::net::SocketAddr; use std::sync::Arc; use axum::extract::State; @@ -14,6 +13,7 @@ use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSo use bittorrent_tracker_core::authentication::Key; use hyper::StatusCode; use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::v1::extractors::announce_request::ExtractRequest; use crate::v1::extractors::authentication_key::Extract as ExtractKey; @@ -23,7 +23,7 @@ use crate::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; /// authentication (no PATH `key` parameter required). #[allow(clippy::unused_async)] pub async fn handle_without_key( - State(state): State<(Arc, SocketAddr)>, + State(state): State<(Arc, ServiceBinding)>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { @@ -36,7 +36,7 @@ pub async fn handle_without_key( /// authentication (PATH `key` parameter required). #[allow(clippy::unused_async)] pub async fn handle_with_key( - State(state): State<(Arc, SocketAddr)>, + State(state): State<(Arc, ServiceBinding)>, ExtractRequest(announce_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, @@ -54,14 +54,14 @@ async fn handle( announce_service: &Arc, announce_request: &Announce, client_ip_sources: &ClientIpSources, - server_socket_addr: &SocketAddr, + server_service_binding: &ServiceBinding, maybe_key: Option, ) -> Response { let announce_data = match handle_announce( announce_service, announce_request, client_ip_sources, - server_socket_addr, + server_service_binding, maybe_key, ) .await @@ -81,11 +81,11 @@ async fn handle_announce( announce_service: &Arc, announce_request: &Announce, client_ip_sources: &ClientIpSources, - server_socket_addr: &SocketAddr, + server_service_binding: &ServiceBinding, maybe_key: Option, ) -> Result { announce_service - .handle_announce(announce_request, client_ip_sources, server_socket_addr, maybe_key) + .handle_announce(announce_request, client_ip_sources, server_service_binding, maybe_key) .await } @@ -212,6 +212,7 @@ mod tests { use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_tracker_core::authentication; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::{initialize_private_tracker, sample_announce_request, sample_client_ip_sources}; use crate::v1::handlers::announce::handle_announce; @@ -222,6 +223,7 @@ mod tests { let http_core_tracker_services = initialize_private_tracker(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let maybe_key = None; @@ -229,7 +231,7 @@ mod tests { &http_core_tracker_services.announce_service, &sample_announce_request(), &sample_client_ip_sources(), - &server_socket_addr, + &server_service_binding, maybe_key, ) .await @@ -252,6 +254,7 @@ mod tests { let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let maybe_key = Some(unregistered_key); @@ -259,7 +262,7 @@ mod tests { &http_core_tracker_services.announce_service, &sample_announce_request(), &sample_client_ip_sources(), - &server_socket_addr, + &server_service_binding, maybe_key, ) .await @@ -281,6 +284,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use bittorrent_http_tracker_protocol::v1::responses; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::{initialize_listed_tracker, sample_announce_request, sample_client_ip_sources}; use crate::v1::handlers::announce::handle_announce; @@ -293,12 +297,13 @@ mod tests { let announce_request = sample_announce_request(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let response = handle_announce( &http_core_tracker_services.announce_service, &announce_request, &sample_client_ip_sources(), - &server_socket_addr, + &server_service_binding, None, ) .await @@ -324,6 +329,7 @@ mod tests { use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::{initialize_tracker_on_reverse_proxy, sample_announce_request}; use crate::v1::handlers::announce::handle_announce; @@ -339,12 +345,13 @@ mod tests { }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let response = handle_announce( &http_core_tracker_services.announce_service, &sample_announce_request(), &client_ip_sources, - &server_socket_addr, + &server_service_binding, None, ) .await @@ -367,6 +374,7 @@ mod tests { use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::{initialize_tracker_not_on_reverse_proxy, sample_announce_request}; use crate::v1::handlers::announce::handle_announce; @@ -382,12 +390,13 @@ mod tests { }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let response = handle_announce( &http_core_tracker_services.announce_service, &sample_announce_request(), &client_ip_sources, - &server_socket_addr, + &server_service_binding, None, ) .await diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index e9544c983..e5d94a072 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -2,7 +2,6 @@ //! //! The handlers perform the authentication and authorization of the request, //! and resolve the client IP address. -use std::net::SocketAddr; use std::sync::Arc; use axum::extract::State; @@ -14,6 +13,7 @@ use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSo use bittorrent_tracker_core::authentication::Key; use hyper::StatusCode; use torrust_tracker_primitives::core::ScrapeData; +use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::v1::extractors::authentication_key::Extract as ExtractKey; use crate::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources; @@ -23,7 +23,7 @@ use crate::v1::extractors::scrape_request::ExtractRequest; /// to run in `public` mode. #[allow(clippy::unused_async)] pub async fn handle_without_key( - State(state): State<(Arc, SocketAddr)>, + State(state): State<(Arc, ServiceBinding)>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ) -> Response { @@ -38,7 +38,7 @@ pub async fn handle_without_key( /// In this case, the authentication `key` parameter is required. #[allow(clippy::unused_async)] pub async fn handle_with_key( - State(state): State<(Arc, SocketAddr)>, + State(state): State<(Arc, ServiceBinding)>, ExtractRequest(scrape_request): ExtractRequest, ExtractClientIpSources(client_ip_sources): ExtractClientIpSources, ExtractKey(key): ExtractKey, @@ -52,11 +52,11 @@ async fn handle( scrape_service: &Arc, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, - server_socket_addr: &SocketAddr, + server_service_binding: &ServiceBinding, maybe_key: Option, ) -> Response { let scrape_data = match scrape_service - .handle_scrape(scrape_request, client_ip_sources, server_socket_addr, maybe_key) + .handle_scrape(scrape_request, client_ip_sources, server_service_binding, maybe_key) .await { Ok(scrape_data) => scrape_data, @@ -173,12 +173,14 @@ mod tests { use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_tracker_core::authentication; use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::{initialize_private_tracker, sample_client_ip_sources, sample_scrape_request}; #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let (core_tracker_services, core_http_tracker_services) = initialize_private_tracker(); @@ -193,7 +195,12 @@ mod tests { ); let scrape_data = scrape_service - .handle_scrape(&scrape_request, &sample_client_ip_sources(), &server_socket_addr, maybe_key) + .handle_scrape( + &scrape_request, + &sample_client_ip_sources(), + &server_service_binding, + maybe_key, + ) .await .unwrap(); @@ -205,6 +212,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let (core_tracker_services, core_http_tracker_services) = initialize_private_tracker(); @@ -220,7 +228,12 @@ mod tests { ); let scrape_data = scrape_service - .handle_scrape(&scrape_request, &sample_client_ip_sources(), &server_socket_addr, maybe_key) + .handle_scrape( + &scrape_request, + &sample_client_ip_sources(), + &server_service_binding, + maybe_key, + ) .await .unwrap(); @@ -236,6 +249,7 @@ mod tests { use bittorrent_http_tracker_core::services::scrape::ScrapeService; use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::{initialize_listed_tracker, sample_client_ip_sources, sample_scrape_request}; @@ -246,6 +260,7 @@ mod tests { let scrape_request = sample_scrape_request(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = ScrapeService::new( core_tracker_services.core_config.clone(), @@ -255,7 +270,7 @@ mod tests { ); let scrape_data = scrape_service - .handle_scrape(&scrape_request, &sample_client_ip_sources(), &server_socket_addr, None) + .handle_scrape(&scrape_request, &sample_client_ip_sources(), &server_service_binding, None) .await .unwrap(); @@ -272,6 +287,7 @@ mod tests { use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::{initialize_tracker_on_reverse_proxy, sample_scrape_request}; use crate::v1::handlers::scrape::tests::assert_error_response; @@ -286,6 +302,7 @@ mod tests { }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = ScrapeService::new( core_tracker_services.core_config.clone(), @@ -295,7 +312,7 @@ mod tests { ); let response = scrape_service - .handle_scrape(&sample_scrape_request(), &client_ip_sources, &server_socket_addr, None) + .handle_scrape(&sample_scrape_request(), &client_ip_sources, &server_service_binding, None) .await .unwrap_err(); @@ -317,6 +334,7 @@ mod tests { use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::{initialize_tracker_not_on_reverse_proxy, sample_scrape_request}; use crate::v1::handlers::scrape::tests::assert_error_response; @@ -331,6 +349,7 @@ mod tests { }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = ScrapeService::new( core_tracker_services.core_config.clone(), @@ -340,7 +359,7 @@ mod tests { ); let response = scrape_service - .handle_scrape(&sample_scrape_request(), &client_ip_sources, &server_socket_addr, None) + .handle_scrape(&sample_scrape_request(), &client_ip_sources, &server_service_binding, None) .await .unwrap_err(); diff --git a/packages/axum-http-tracker-server/src/v1/routes.rs b/packages/axum-http-tracker-server/src/v1/routes.rs index d5907887e..3fe467a0d 100644 --- a/packages/axum-http-tracker-server/src/v1/routes.rs +++ b/packages/axum-http-tracker-server/src/v1/routes.rs @@ -1,5 +1,4 @@ //! HTTP server routes for version `v1`. -use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; @@ -13,6 +12,7 @@ use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use hyper::{Request, StatusCode}; use torrust_server_lib::logging::Latency; use torrust_tracker_configuration::DEFAULT_TIMEOUT; +use torrust_tracker_primitives::service_binding::ServiceBinding; use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; use tower_http::classify::ServerErrorsFailureClass; @@ -30,28 +30,38 @@ use crate::HTTP_TRACKER_LOG_TARGET; /// /// > **NOTICE**: it's added a layer to get the client IP from the connection /// > info. The tracker could use the connection info to get the client IP. -#[instrument(skip(http_tracker_container, server_socket_addr))] -pub fn router(http_tracker_container: Arc, server_socket_addr: SocketAddr) -> Router { +#[instrument(skip(http_tracker_container, server_service_binding))] +pub fn router(http_tracker_container: Arc, server_service_binding: ServiceBinding) -> Router { + let server_socket_addr = server_service_binding.bind_address(); + Router::new() // Health check .route("/health_check", get(health_check::handler)) // Announce request .route( "/announce", - get(announce::handle_without_key).with_state((http_tracker_container.announce_service.clone(), server_socket_addr)), + get(announce::handle_without_key).with_state(( + http_tracker_container.announce_service.clone(), + server_service_binding.clone(), + )), ) .route( "/announce/{key}", - get(announce::handle_with_key).with_state((http_tracker_container.announce_service.clone(), server_socket_addr)), + get(announce::handle_with_key).with_state(( + http_tracker_container.announce_service.clone(), + server_service_binding.clone(), + )), ) // Scrape request .route( "/scrape", - get(scrape::handle_without_key).with_state((http_tracker_container.scrape_service.clone(), server_socket_addr)), + get(scrape::handle_without_key) + .with_state((http_tracker_container.scrape_service.clone(), server_service_binding.clone())), ) .route( "/scrape/{key}", - get(scrape::handle_with_key).with_state((http_tracker_container.scrape_service.clone(), server_socket_addr)), + get(scrape::handle_with_key) + .with_state((http_tracker_container.scrape_service.clone(), server_service_binding.clone())), ) // Add extension to get the client IP from the connection info .layer(SecureClientIpSource::ConnectInfo.into_extension()) diff --git a/packages/http-tracker-core/benches/helpers/sync.rs b/packages/http-tracker-core/benches/helpers/sync.rs index 9d41c2459..e0f022108 100644 --- a/packages/http-tracker-core/benches/helpers/sync.rs +++ b/packages/http-tracker-core/benches/helpers/sync.rs @@ -2,6 +2,7 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::time::{Duration, Instant}; use bittorrent_http_tracker_core::services::announce::AnnounceService; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::helpers::util::{initialize_core_tracker_services, sample_announce_request_for_peer, sample_peer}; @@ -22,12 +23,13 @@ pub async fn return_announce_data_once(samples: u64) -> Duration { ); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let start = Instant::now(); for _ in 0..samples { let _announce_data = announce_service - .handle_announce(&announce_request, &client_ip_sources, &server_socket_addr, None) + .handle_announce(&announce_request, &client_ip_sources, &server_service_binding, None) .await .unwrap(); } diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index 3db258238..7caf8a596 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -1,5 +1,7 @@ use std::net::{IpAddr, SocketAddr}; +use torrust_tracker_primitives::service_binding::ServiceBinding; + pub mod sender; /// A HTTP core event. @@ -17,14 +19,14 @@ pub struct ConnectionContext { impl ConnectionContext { #[must_use] - pub fn new(client_ip_addr: IpAddr, opt_client_port: Option, server_socket_addr: SocketAddr) -> Self { + pub fn new(client_ip_addr: IpAddr, opt_client_port: Option, server_service_binding: ServiceBinding) -> Self { Self { client: ClientConnectionContext { ip_addr: client_ip_addr, port: opt_client_port, }, server: ServerConnectionContext { - socket_addr: server_socket_addr, + service_binding: server_service_binding, }, } } @@ -41,7 +43,7 @@ impl ConnectionContext { #[must_use] pub fn server_socket_addr(&self) -> SocketAddr { - self.server.socket_addr + self.server.service_binding.bind_address() } } @@ -55,5 +57,5 @@ pub struct ClientConnectionContext { #[derive(Debug, PartialEq, Eq, Clone)] pub struct ServerConnectionContext { - socket_addr: SocketAddr, + service_binding: ServiceBinding, } diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index f8d2e0b11..c249cb4db 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -7,7 +7,7 @@ //! //! It also sends an [`http_tracker_core::event::Event`] //! because events are specific for the HTTP tracker. -use std::net::{IpAddr, SocketAddr}; +use std::net::IpAddr; use std::panic::Location; use std::sync::Arc; @@ -21,6 +21,7 @@ use bittorrent_tracker_core::error::{AnnounceError, TrackerCoreError, WhitelistE use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::event; use crate::event::Event; @@ -69,7 +70,7 @@ impl AnnounceService { &self, announce_request: &Announce, client_ip_sources: &ClientIpSources, - server_socket_addr: &SocketAddr, + server_service_binding: &ServiceBinding, maybe_key: Option, ) -> Result { self.authenticate(maybe_key).await?; @@ -87,7 +88,7 @@ impl AnnounceService { .announce(&announce_request.info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; - self.send_event(remote_client_ip, opt_remote_client_port, *server_socket_addr) + self.send_event(remote_client_ip, opt_remote_client_port, server_service_binding.clone()) .await; Ok(announce_data) @@ -138,11 +139,11 @@ impl AnnounceService { } } - async fn send_event(&self, peer_ip: IpAddr, opt_peer_ip_port: Option, server_socket_addr: SocketAddr) { + async fn send_event(&self, peer_ip: IpAddr, opt_peer_ip_port: Option, server_service_binding: ServiceBinding) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { http_stats_event_sender .send_event(Event::TcpAnnounce { - connection: event::ConnectionContext::new(peer_ip, opt_peer_ip_port, server_socket_addr), + connection: event::ConnectionContext::new(peer_ip, opt_peer_ip_port, server_service_binding), }) .await; } @@ -338,6 +339,7 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; @@ -359,6 +361,7 @@ mod tests { let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let announce_service = AnnounceService::new( core_tracker_services.core_config.clone(), @@ -369,7 +372,7 @@ mod tests { ); let announce_data = announce_service - .handle_announce(&announce_request, &client_ip_sources, &server_socket_addr, None) + .handle_announce(&announce_request, &client_ip_sources, &server_service_binding, None) .await .unwrap(); @@ -389,12 +392,17 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_announce_event_when_the_peer_uses_ipv4() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() .with(eq(Event::TcpAnnounce { - connection: ConnectionContext::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), Some(8080), server_socket_addr), + connection: ConnectionContext::new( + IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), + Some(8080), + server_service_binding.clone(), + ), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -418,7 +426,7 @@ mod tests { ); let _announce_data = announce_service - .handle_announce(&announce_request, &client_ip_sources, &server_socket_addr, None) + .handle_announce(&announce_request, &client_ip_sources, &server_service_binding, None) .await .unwrap(); } @@ -444,13 +452,18 @@ mod tests { // Tracker changes the peer IP to the tracker external IP when the peer is using the loopback IP. let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); // Assert that the event sent is a TCP4 event let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() .with(eq(Event::TcpAnnounce { - connection: ConnectionContext::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), Some(8080), server_socket_addr), + connection: ConnectionContext::new( + IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), + Some(8080), + server_service_binding.clone(), + ), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -475,7 +488,7 @@ mod tests { ); let _announce_data = announce_service - .handle_announce(&announce_request, &client_ip_sources, &server_socket_addr, None) + .handle_announce(&announce_request, &client_ip_sources, &server_service_binding, None) .await .unwrap(); } @@ -484,6 +497,7 @@ mod tests { async fn it_should_send_the_tcp_6_announce_event_when_the_peer_uses_ipv6_even_if_the_tracker_changes_the_peer_ip_to_ipv4() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock @@ -492,7 +506,7 @@ mod tests { connection: ConnectionContext::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), Some(8080), - server_socket_addr, + server_service_binding, ), })) .times(1) @@ -516,9 +530,10 @@ mod tests { ); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let _announce_data = announce_service - .handle_announce(&announce_request, &client_ip_sources, &server_socket_addr, None) + .handle_announce(&announce_request, &client_ip_sources, &server_service_binding, None) .await .unwrap(); } diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index c9b3182f8..baa406e63 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -7,7 +7,7 @@ //! //! It also sends an [`http_tracker_core::statistics::event::Event`] //! because events are specific for the HTTP tracker. -use std::net::{IpAddr, SocketAddr}; +use std::net::IpAddr; use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; @@ -18,6 +18,7 @@ use bittorrent_tracker_core::error::{ScrapeError, TrackerCoreError, WhitelistErr use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; +use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::event; use crate::event::{ConnectionContext, Event}; @@ -71,7 +72,7 @@ impl ScrapeService { &self, scrape_request: &Scrape, client_ip_sources: &ClientIpSources, - server_socket_addr: &SocketAddr, + server_service_binding: &ServiceBinding, maybe_key: Option, ) -> Result { let scrape_data = if self.authentication_is_required() && !self.is_authenticated(maybe_key).await { @@ -82,7 +83,8 @@ impl ScrapeService { let (remote_client_ip, opt_client_port) = self.resolve_remote_client_ip(client_ip_sources)?; - self.send_event(remote_client_ip, opt_client_port, *server_socket_addr).await; + self.send_event(remote_client_ip, opt_client_port, server_service_binding.clone()) + .await; Ok(scrape_data) } @@ -117,11 +119,16 @@ impl ScrapeService { Ok((ip, port)) } - async fn send_event(&self, original_peer_ip: IpAddr, opt_original_peer_port: Option, server_socket_addr: SocketAddr) { + async fn send_event( + &self, + original_peer_ip: IpAddr, + opt_original_peer_port: Option, + server_service_binding: ServiceBinding, + ) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { http_stats_event_sender .send_event(Event::TcpScrape { - connection: ConnectionContext::new(original_peer_ip, opt_original_peer_port, server_socket_addr), + connection: ConnectionContext::new(original_peer_ip, opt_original_peer_port, server_service_binding), }) .await; } @@ -269,6 +276,7 @@ mod tests { use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; @@ -312,6 +320,7 @@ mod tests { }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = Arc::new(ScrapeService::new( core_config.clone(), @@ -321,7 +330,7 @@ mod tests { )); let scrape_data = scrape_service - .handle_scrape(&scrape_request, &client_ip_sources, &server_socket_addr, None) + .handle_scrape(&scrape_request, &client_ip_sources, &server_service_binding, None) .await .unwrap(); @@ -349,7 +358,8 @@ mod tests { connection: ConnectionContext::new( IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), Some(8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)) + .unwrap(), ), })) .times(1) @@ -371,6 +381,7 @@ mod tests { }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = Arc::new(ScrapeService::new( Arc::new(config.core), @@ -380,7 +391,7 @@ mod tests { )); scrape_service - .handle_scrape(&scrape_request, &client_ip_sources, &server_socket_addr, None) + .handle_scrape(&scrape_request, &client_ip_sources, &server_service_binding, None) .await .unwrap(); } @@ -388,6 +399,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let config = configuration::ephemeral(); @@ -398,7 +410,7 @@ mod tests { connection: ConnectionContext::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), Some(8080), - server_socket_addr, + server_service_binding, ), })) .times(1) @@ -420,6 +432,7 @@ mod tests { }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = Arc::new(ScrapeService::new( Arc::new(config.core), @@ -429,7 +442,7 @@ mod tests { )); scrape_service - .handle_scrape(&scrape_request, &client_ip_sources, &server_socket_addr, None) + .handle_scrape(&scrape_request, &client_ip_sources, &server_service_binding, None) .await .unwrap(); } @@ -446,6 +459,7 @@ mod tests { use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_test_helpers::configuration; use crate::event::{ConnectionContext, Event}; @@ -488,6 +502,7 @@ mod tests { }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = Arc::new(ScrapeService::new( Arc::new(config.core), @@ -497,7 +512,7 @@ mod tests { )); let scrape_data = scrape_service - .handle_scrape(&scrape_request, &client_ip_sources, &server_socket_addr, None) + .handle_scrape(&scrape_request, &client_ip_sources, &server_service_binding, None) .await .unwrap(); @@ -519,7 +534,8 @@ mod tests { connection: ConnectionContext::new( IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), Some(8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)) + .unwrap(), ), })) .times(1) @@ -539,6 +555,7 @@ mod tests { }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = Arc::new(ScrapeService::new( Arc::new(config.core), @@ -548,7 +565,7 @@ mod tests { )); scrape_service - .handle_scrape(&scrape_request, &client_ip_sources, &server_socket_addr, None) + .handle_scrape(&scrape_request, &client_ip_sources, &server_service_binding, None) .await .unwrap(); } @@ -556,6 +573,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let config = configuration::ephemeral(); @@ -568,7 +586,7 @@ mod tests { connection: ConnectionContext::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), Some(8080), - server_socket_addr, + server_service_binding, ), })) .times(1) @@ -588,6 +606,7 @@ mod tests { }; let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = Arc::new(ScrapeService::new( Arc::new(config.core), @@ -597,7 +616,7 @@ mod tests { )); scrape_service - .handle_scrape(&scrape_request, &client_ip_sources, &server_socket_addr, None) + .handle_scrape(&scrape_request, &client_ip_sources, &server_service_binding, None) .await .unwrap(); } diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index 700e39476..0df1c41d3 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -34,6 +34,8 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::event::{ConnectionContext, Event}; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; @@ -47,7 +49,7 @@ mod tests { connection: ConnectionContext::new( IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), Some(8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), }, &stats_repository, @@ -68,7 +70,7 @@ mod tests { connection: ConnectionContext::new( IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), Some(8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), }, &stats_repository, @@ -89,7 +91,7 @@ mod tests { connection: ConnectionContext::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), Some(8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), }, &stats_repository, @@ -110,7 +112,7 @@ mod tests { connection: ConnectionContext::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), Some(8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), }, &stats_repository, From 0784a9e4b3054a0f27564c37c1f782288feb51e6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 31 Mar 2025 13:02:42 +0100 Subject: [PATCH 0929/1297] feat: [#1424] add ServiceBinding to UDP events --- .../udp-tracker-core/benches/helpers/sync.rs | 4 +- packages/udp-tracker-core/src/event/mod.rs | 10 +- .../udp-tracker-core/src/services/announce.rs | 9 +- .../udp-tracker-core/src/services/connect.rs | 25 +++-- .../udp-tracker-core/src/services/scrape.rs | 9 +- .../src/statistics/event/handler.rs | 38 ++++++-- packages/udp-tracker-server/src/event/mod.rs | 10 +- .../src/handlers/announce.rs | 61 ++++++++---- .../src/handlers/connect.rs | 31 ++++--- .../udp-tracker-server/src/handlers/error.rs | 7 +- .../udp-tracker-server/src/handlers/mod.rs | 19 ++-- .../udp-tracker-server/src/handlers/scrape.rs | 33 ++++--- .../udp-tracker-server/src/server/launcher.rs | 16 +++- .../src/server/processor.rs | 14 ++- .../src/statistics/event/handler.rs | 92 ++++++++++++++++--- 15 files changed, 270 insertions(+), 108 deletions(-) diff --git a/packages/udp-tracker-core/benches/helpers/sync.rs b/packages/udp-tracker-core/benches/helpers/sync.rs index ca459c640..b61204586 100644 --- a/packages/udp-tracker-core/benches/helpers/sync.rs +++ b/packages/udp-tracker-core/benches/helpers/sync.rs @@ -4,6 +4,7 @@ use std::time::{Duration, Instant}; use bittorrent_udp_tracker_core::services::connect::ConnectService; use bittorrent_udp_tracker_core::statistics; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::helpers::utils::{sample_ipv4_remote_addr, sample_issue_time}; @@ -11,6 +12,7 @@ use crate::helpers::utils::{sample_ipv4_remote_addr, sample_issue_time}; pub async fn connect_once(samples: u64) -> Duration { let client_socket_addr = sample_ipv4_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); @@ -18,7 +20,7 @@ pub async fn connect_once(samples: u64) -> Duration { let start = Instant::now(); for _ in 0..samples { - let _response = connect_service.handle_connect(client_socket_addr, server_socket_addr, sample_issue_time()); + let _response = connect_service.handle_connect(client_socket_addr, server_service_binding.clone(), sample_issue_time()); } start.elapsed() diff --git a/packages/udp-tracker-core/src/event/mod.rs b/packages/udp-tracker-core/src/event/mod.rs index 04b3170e2..e25f557e2 100644 --- a/packages/udp-tracker-core/src/event/mod.rs +++ b/packages/udp-tracker-core/src/event/mod.rs @@ -1,5 +1,7 @@ use std::net::SocketAddr; +use torrust_tracker_primitives::service_binding::ServiceBinding; + pub mod sender; /// A UDP core event. @@ -13,15 +15,15 @@ pub enum Event { #[derive(Debug, PartialEq, Eq, Clone)] pub struct ConnectionContext { pub client_socket_addr: SocketAddr, - pub server_socket_addr: SocketAddr, + pub server_service_binding: ServiceBinding, } impl ConnectionContext { #[must_use] - pub fn new(client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) -> Self { + pub fn new(client_socket_addr: SocketAddr, server_service_binding: ServiceBinding) -> Self { Self { client_socket_addr, - server_socket_addr, + server_service_binding, } } @@ -32,6 +34,6 @@ impl ConnectionContext { #[must_use] pub fn server_socket_addr(&self) -> SocketAddr { - self.server_socket_addr + self.server_service_binding.bind_address() } } diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index d99618316..0a9bf6b82 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -18,6 +18,7 @@ use bittorrent_tracker_core::error::{AnnounceError, WhitelistError}; use bittorrent_tracker_core::whitelist; use bittorrent_udp_tracker_protocol::peer_builder; use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; use crate::event::{self, ConnectionContext, Event}; @@ -58,7 +59,7 @@ impl AnnounceService { pub async fn handle_announce( &self, client_socket_addr: SocketAddr, - server_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, request: &AnnounceRequest, cookie_valid_range: Range, ) -> Result { @@ -79,7 +80,7 @@ impl AnnounceService { .announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; - self.send_event(client_socket_addr, server_socket_addr).await; + self.send_event(client_socket_addr, server_service_binding).await; Ok(announce_data) } @@ -100,11 +101,11 @@ impl AnnounceService { self.whitelist_authorization.authorize(info_hash).await } - async fn send_event(&self, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) { + async fn send_event(&self, client_socket_addr: SocketAddr, server_service_binding: ServiceBinding) { if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { udp_stats_event_sender .send_event(Event::UdpAnnounce { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding), }) .await; } diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index e543fbb1e..92bcd299f 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -5,6 +5,7 @@ use std::net::SocketAddr; use std::sync::Arc; use aquatic_udp_protocol::ConnectionId; +use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::connection_cookie::{gen_remote_fingerprint, make}; use crate::event::{self, ConnectionContext, Event}; @@ -33,7 +34,7 @@ impl ConnectService { pub async fn handle_connect( &self, client_socket_addr: SocketAddr, - server_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, cookie_issue_time: f64, ) -> ConnectionId { let connection_id = @@ -42,7 +43,7 @@ impl ConnectService { if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { udp_stats_event_sender .send_event(Event::UdpConnect { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding), }) .await; } @@ -61,6 +62,7 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::connection_cookie::make; use crate::event::{ConnectionContext, Event}; @@ -74,6 +76,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); @@ -81,7 +84,7 @@ mod tests { let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); let response = connect_service - .handle_connect(sample_ipv4_remote_addr(), server_socket_addr, sample_issue_time()) + .handle_connect(sample_ipv4_remote_addr(), server_service_binding, sample_issue_time()) .await; assert_eq!( @@ -93,6 +96,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); @@ -100,7 +104,7 @@ mod tests { let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); let response = connect_service - .handle_connect(sample_ipv4_remote_addr(), server_socket_addr, sample_issue_time()) + .handle_connect(sample_ipv4_remote_addr(), server_service_binding, sample_issue_time()) .await; assert_eq!( @@ -113,6 +117,7 @@ mod tests { async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { let client_socket_addr = sample_ipv6_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); @@ -120,7 +125,7 @@ mod tests { let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); let response = connect_service - .handle_connect(client_socket_addr, server_socket_addr, sample_issue_time()) + .handle_connect(client_socket_addr, server_service_binding, sample_issue_time()) .await; assert_eq!( @@ -133,12 +138,13 @@ mod tests { async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { let client_socket_addr = sample_ipv4_socket_address(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() .with(eq(Event::UdpConnect { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -148,7 +154,7 @@ mod tests { let connect_service = Arc::new(ConnectService::new(opt_udp_stats_event_sender)); connect_service - .handle_connect(client_socket_addr, server_socket_addr, sample_issue_time()) + .handle_connect(client_socket_addr, server_service_binding, sample_issue_time()) .await; } @@ -156,12 +162,13 @@ mod tests { async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { let client_socket_addr = sample_ipv6_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_stats_event_sender_mock .expect_send_event() .with(eq(Event::UdpConnect { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -171,7 +178,7 @@ mod tests { let connect_service = Arc::new(ConnectService::new(opt_udp_stats_event_sender)); connect_service - .handle_connect(client_socket_addr, server_socket_addr, sample_issue_time()) + .handle_connect(client_socket_addr, server_service_binding, sample_issue_time()) .await; } } diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index 3b6898311..6ee64111c 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -16,6 +16,7 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::error::{ScrapeError, WhitelistError}; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use torrust_tracker_primitives::core::ScrapeData; +use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; use crate::event::{self, ConnectionContext, Event}; @@ -50,7 +51,7 @@ impl ScrapeService { pub async fn handle_scrape( &self, client_socket_addr: SocketAddr, - server_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, request: &ScrapeRequest, cookie_valid_range: Range, ) -> Result { @@ -61,7 +62,7 @@ impl ScrapeService { .scrape(&Self::convert_from_aquatic(&request.info_hashes)) .await?; - self.send_event(client_socket_addr, server_socket_addr).await; + self.send_event(client_socket_addr, server_service_binding).await; Ok(scrape_data) } @@ -82,11 +83,11 @@ impl ScrapeService { aquatic_infohashes.iter().map(|&x| x.into()).collect() } - async fn send_event(&self, client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) { + async fn send_event(&self, client_socket_addr: SocketAddr, server_service_binding: ServiceBinding) { if let Some(udp_stats_event_sender) = self.opt_udp_stats_event_sender.as_deref() { udp_stats_event_sender .send_event(Event::UdpScrape { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding), }) .await; } diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index a9ac0dade..3968ca4e7 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -39,6 +39,8 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::event::{ConnectionContext, Event}; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; @@ -51,7 +53,11 @@ mod tests { Event::UdpConnect { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, @@ -71,7 +77,11 @@ mod tests { Event::UdpAnnounce { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, @@ -91,7 +101,11 @@ mod tests { Event::UdpScrape { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, @@ -111,7 +125,11 @@ mod tests { Event::UdpConnect { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, @@ -131,7 +149,11 @@ mod tests { Event::UdpAnnounce { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, @@ -151,7 +173,11 @@ mod tests { Event::UdpScrape { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, diff --git a/packages/udp-tracker-server/src/event/mod.rs b/packages/udp-tracker-server/src/event/mod.rs index 0adf29c8b..68f07cfd6 100644 --- a/packages/udp-tracker-server/src/event/mod.rs +++ b/packages/udp-tracker-server/src/event/mod.rs @@ -1,6 +1,8 @@ use std::net::SocketAddr; use std::time::Duration; +use torrust_tracker_primitives::service_binding::ServiceBinding; + pub mod sender; /// A UDP server event. @@ -52,15 +54,15 @@ pub enum UdpResponseKind { #[derive(Debug, PartialEq, Eq, Clone)] pub struct ConnectionContext { client_socket_addr: SocketAddr, - server_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, } impl ConnectionContext { #[must_use] - pub fn new(client_socket_addr: SocketAddr, server_socket_addr: SocketAddr) -> Self { + pub fn new(client_socket_addr: SocketAddr, server_service_binding: ServiceBinding) -> Self { Self { client_socket_addr, - server_socket_addr, + server_service_binding, } } @@ -71,6 +73,6 @@ impl ConnectionContext { #[must_use] pub fn server_socket_addr(&self) -> SocketAddr { - self.server_socket_addr + self.server_service_binding.bind_address() } } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 5df46125d..1cf0f0b7d 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -11,6 +11,7 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_udp_tracker_core::services::announce::AnnounceService; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::service_binding::ServiceBinding; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; @@ -26,7 +27,7 @@ use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; pub async fn handle_announce( announce_service: &Arc, client_socket_addr: SocketAddr, - server_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, request: &AnnounceRequest, core_config: &Arc, opt_udp_server_stats_event_sender: &Arc>>, @@ -42,14 +43,14 @@ pub async fn handle_announce( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender .send_event(Event::UdpRequestAccepted { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Announce, }) .await; } let announce_data = announce_service - .handle_announce(client_socket_addr, server_socket_addr, request, cookie_valid_range) + .handle_announce(client_socket_addr, server_service_binding, request, cookie_valid_range) .await .map_err(|e| (e.into(), request.transaction_id, UdpRequestKind::Announce))?; @@ -205,6 +206,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use mockall::predicate::eq; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; @@ -228,6 +230,7 @@ mod tests { let client_socket_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) @@ -240,7 +243,7 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &core_tracker_services.core_config, &server_udp_tracker_services.udp_server_stats_event_sender, @@ -269,6 +272,7 @@ mod tests { let client_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) @@ -277,7 +281,7 @@ mod tests { let response = handle_announce( &core_udp_tracker_services.announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &core_tracker_services.core_config, &server_udp_tracker_services.udp_server_stats_event_sender, @@ -320,6 +324,7 @@ mod tests { let client_socket_addr = SocketAddr::new(IpAddr::V4(remote_client_ip), remote_client_port); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) @@ -332,7 +337,7 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &core_tracker_services.core_config, &server_udp_tracker_services.udp_server_stats_event_sender, @@ -378,6 +383,7 @@ mod tests { let client_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) @@ -386,7 +392,7 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &core_tracker_services.core_config, &udp_server_stats_event_sender, @@ -419,12 +425,13 @@ mod tests { async fn should_send_the_upd4_announce_event() { let client_socket_addr = sample_ipv4_socket_address(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() .with(eq(Event::UdpRequestAccepted { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Announce, })) .times(1) @@ -438,7 +445,7 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &AnnounceRequestBuilder::default().into(), &core_tracker_services.core_config, &udp_server_stats_event_sender, @@ -454,6 +461,7 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::handlers::handle_announce; @@ -474,6 +482,7 @@ mod tests { let client_socket_addr = SocketAddr::new(IpAddr::V4(client_ip), client_port); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) @@ -486,7 +495,7 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &core_tracker_services.core_config, &server_udp_tracker_services.udp_server_stats_event_sender, @@ -529,6 +538,7 @@ mod tests { use bittorrent_udp_tracker_core::services::announce::AnnounceService; use mockall::predicate::eq; use torrust_tracker_configuration::Core; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; @@ -552,6 +562,7 @@ mod tests { let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) @@ -564,7 +575,7 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &core_tracker_services.core_config, &server_udp_tracker_services.udp_server_stats_event_sender, @@ -596,6 +607,7 @@ mod tests { let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), 8080); let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) @@ -604,7 +616,7 @@ mod tests { let response = handle_announce( &core_udp_tracker_services.announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &core_tracker_services.core_config, &server_udp_tracker_services.udp_server_stats_event_sender, @@ -647,6 +659,7 @@ mod tests { let client_socket_addr = SocketAddr::new(IpAddr::V6(remote_client_ip), remote_client_port); let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) @@ -659,7 +672,7 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &core_tracker_services.core_config, &server_udp_tracker_service.udp_server_stats_event_sender, @@ -710,6 +723,7 @@ mod tests { let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let request = AnnounceRequestBuilder::default() .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) @@ -724,7 +738,7 @@ mod tests { handle_announce( &announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &core_config, &udp_server_stats_event_sender, @@ -761,12 +775,13 @@ mod tests { async fn should_send_the_upd6_announce_event() { let client_socket_addr = sample_ipv6_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() .with(eq(Event::UdpRequestAccepted { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Announce, })) .times(1) @@ -784,7 +799,7 @@ mod tests { handle_announce( &core_udp_tracker_services.announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &announce_request, &core_tracker_services.core_config, &udp_server_stats_event_sender, @@ -810,6 +825,7 @@ mod tests { use bittorrent_udp_tracker_core::services::announce::AnnounceService; use bittorrent_udp_tracker_core::{self, event as core_event}; use mockall::predicate::eq; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; @@ -834,7 +850,12 @@ mod tests { let peer_id = AquaticPeerId([255u8; 20]); let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); - let server_socket_addr = config.udp_trackers.clone().unwrap()[0].bind_address; + let mut server_socket_addr = config.udp_trackers.clone().unwrap()[0].bind_address; + if server_socket_addr.port() == 0 { + // Port 0 cannot be use in service binding + server_socket_addr.set_port(6969); + } + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -847,7 +868,7 @@ mod tests { udp_core_stats_event_sender_mock .expect_send_event() .with(eq(core_event::Event::UdpAnnounce { - context: core_event::ConnectionContext::new(client_socket_addr, server_socket_addr), + context: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -858,7 +879,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(Event::UdpRequestAccepted { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Announce, })) .times(1) @@ -892,7 +913,7 @@ mod tests { handle_announce( &announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &core_config, &udp_server_stats_event_sender, diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index a0fbaead3..88f0b7f3a 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, ConnectionId, Response}; use bittorrent_udp_tracker_core::services::connect::ConnectService; +use torrust_tracker_primitives::service_binding::ServiceBinding; use tracing::{instrument, Level}; use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; @@ -12,7 +13,7 @@ use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; #[instrument(fields(transaction_id), skip(connect_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] pub async fn handle_connect( client_socket_addr: SocketAddr, - server_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, request: &ConnectRequest, connect_service: &Arc, opt_udp_server_stats_event_sender: &Arc>>, @@ -24,14 +25,14 @@ pub async fn handle_connect( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender .send_event(Event::UdpRequestAccepted { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Connect, }) .await; } let connection_id = connect_service - .handle_connect(client_socket_addr, server_socket_addr, cookie_issue_time) + .handle_connect(client_socket_addr, server_service_binding, cookie_issue_time) .await; build_response(*request, connection_id) @@ -60,6 +61,7 @@ mod tests { use bittorrent_udp_tracker_core::event as core_event; use bittorrent_udp_tracker_core::services::connect::ConnectService; use mockall::predicate::eq; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; use crate::handlers::handle_connect; @@ -77,6 +79,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let (udp_core_stats_event_sender, _udp_core_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); @@ -93,7 +96,7 @@ mod tests { let response = handle_connect( sample_ipv4_remote_addr(), - server_socket_addr, + server_service_binding, &request, &connect_service, &udp_server_stats_event_sender, @@ -113,6 +116,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let (udp_core_stats_event_sender, _udp_core_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); @@ -129,7 +133,7 @@ mod tests { let response = handle_connect( sample_ipv4_remote_addr(), - server_socket_addr, + server_service_binding, &request, &connect_service, &udp_server_stats_event_sender, @@ -149,6 +153,7 @@ mod tests { #[tokio::test] async fn a_connect_response_should_contain_a_new_connection_id_ipv6() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let (udp_core_stats_event_sender, _udp_core_stats_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); @@ -165,7 +170,7 @@ mod tests { let response = handle_connect( sample_ipv6_remote_addr(), - server_socket_addr, + server_service_binding, &request, &connect_service, &udp_server_stats_event_sender, @@ -186,12 +191,13 @@ mod tests { async fn it_should_send_the_upd4_connect_event_when_a_client_tries_to_connect_using_a_ip4_socket_address() { let client_socket_addr = sample_ipv4_socket_address(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send_event() .with(eq(core_event::Event::UdpConnect { - context: core_event::ConnectionContext::new(client_socket_addr, server_socket_addr), + context: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -202,7 +208,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(Event::UdpRequestAccepted { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Connect, })) .times(1) @@ -214,7 +220,7 @@ mod tests { handle_connect( client_socket_addr, - server_socket_addr, + server_service_binding, &sample_connect_request(), &connect_service, &udp_server_stats_event_sender, @@ -227,12 +233,13 @@ mod tests { async fn it_should_send_the_upd6_connect_event_when_a_client_tries_to_connect_using_a_ip6_socket_address() { let client_socket_addr = sample_ipv6_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send_event() .with(eq(core_event::Event::UdpConnect { - context: core_event::ConnectionContext::new(client_socket_addr, server_socket_addr), + context: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -243,7 +250,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(Event::UdpRequestAccepted { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Connect, })) .times(1) @@ -255,7 +262,7 @@ mod tests { handle_connect( client_socket_addr, - server_socket_addr, + server_service_binding, &sample_connect_request(), &connect_service, &udp_server_stats_event_sender, diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index 70c33b5ba..6a1bce51c 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use aquatic_udp_protocol::{ErrorResponse, RequestParseError, Response, TransactionId}; use bittorrent_udp_tracker_core::connection_cookie::{check, gen_remote_fingerprint}; use bittorrent_udp_tracker_core::{self, UDP_TRACKER_LOG_TARGET}; +use torrust_tracker_primitives::service_binding::ServiceBinding; use tracing::{instrument, Level}; use uuid::Uuid; use zerocopy::network_endian::I32; @@ -18,7 +19,7 @@ use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; pub async fn handle_error( req_kind: Option, client_socket_addr: SocketAddr, - server_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, request_id: Uuid, opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, @@ -27,6 +28,8 @@ pub async fn handle_error( ) -> Response { tracing::trace!("handle error"); + let server_socket_addr = server_service_binding.bind_address(); + match transaction_id { Some(transaction_id) => { let transaction_id = transaction_id.0.to_string(); @@ -60,7 +63,7 @@ pub async fn handle_error( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender .send_event(Event::UdpError { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding), }) .await; } diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 34ac374fa..f8ca9d8ea 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -18,6 +18,7 @@ use connect::handle_connect; use error::handle_error; use scrape::handle_scrape; use torrust_tracker_clock::clock::Time; +use torrust_tracker_primitives::service_binding::ServiceBinding; use tracing::{instrument, Level}; use uuid::Uuid; @@ -59,7 +60,7 @@ pub(crate) async fn handle_packet( udp_request: RawRequest, udp_tracker_core_container: Arc, udp_tracker_server_container: Arc, - server_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, cookie_time_values: CookieTimeValues, ) -> (Response, Option) { let request_id = Uuid::new_v4(); @@ -74,7 +75,7 @@ pub(crate) async fn handle_packet( Ok(request) => match handle_request( request, udp_request.from, - server_socket_addr, + server_service_binding.clone(), udp_tracker_core_container.clone(), udp_tracker_server_container.clone(), cookie_time_values.clone(), @@ -95,7 +96,7 @@ pub(crate) async fn handle_packet( let response = handle_error( Some(req_kind.clone()), udp_request.from, - server_socket_addr, + server_service_binding, request_id, &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range.clone(), @@ -111,7 +112,7 @@ pub(crate) async fn handle_packet( let response = handle_error( None, udp_request.from, - server_socket_addr, + server_service_binding, request_id, &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range.clone(), @@ -138,7 +139,7 @@ pub(crate) async fn handle_packet( #[instrument(skip( request, client_socket_addr, - server_socket_addr, + server_service_binding, udp_tracker_core_container, udp_tracker_server_container, cookie_time_values @@ -146,7 +147,7 @@ pub(crate) async fn handle_packet( pub async fn handle_request( request: Request, client_socket_addr: SocketAddr, - server_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, udp_tracker_core_container: Arc, udp_tracker_server_container: Arc, cookie_time_values: CookieTimeValues, @@ -157,7 +158,7 @@ pub async fn handle_request( Request::Connect(connect_request) => Ok(( handle_connect( client_socket_addr, - server_socket_addr, + server_service_binding, &connect_request, &udp_tracker_core_container.connect_service, &udp_tracker_server_container.udp_server_stats_event_sender, @@ -170,7 +171,7 @@ pub async fn handle_request( match handle_announce( &udp_tracker_core_container.announce_service, client_socket_addr, - server_socket_addr, + server_service_binding, &announce_request, &udp_tracker_core_container.tracker_core_container.core_config, &udp_tracker_server_container.udp_server_stats_event_sender, @@ -186,7 +187,7 @@ pub async fn handle_request( match handle_scrape( &udp_tracker_core_container.scrape_service, client_socket_addr, - server_socket_addr, + server_service_binding, &scrape_request, &udp_tracker_server_container.udp_server_stats_event_sender, cookie_time_values.valid_range, diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index ac0faef61..35b5ee65c 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -9,6 +9,7 @@ use aquatic_udp_protocol::{ use bittorrent_udp_tracker_core::services::scrape::ScrapeService; use bittorrent_udp_tracker_core::{self}; use torrust_tracker_primitives::core::ScrapeData; +use torrust_tracker_primitives::service_binding::ServiceBinding; use tracing::{instrument, Level}; use zerocopy::network_endian::I32; @@ -24,7 +25,7 @@ use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; pub async fn handle_scrape( scrape_service: &Arc, client_socket_addr: SocketAddr, - server_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, request: &ScrapeRequest, opt_udp_server_stats_event_sender: &Arc>>, cookie_valid_range: Range, @@ -38,14 +39,14 @@ pub async fn handle_scrape( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender .send_event(Event::UdpRequestAccepted { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Scrape, }) .await; } let scrape_data = scrape_service - .handle_scrape(client_socket_addr, server_socket_addr, request, cookie_valid_range) + .handle_scrape(client_socket_addr, server_service_binding, request, cookie_valid_range) .await .map_err(|e| (e.into(), request.transaction_id, UdpRequestKind::Scrape))?; @@ -91,6 +92,7 @@ mod tests { }; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::handlers::handle_scrape; use crate::handlers::tests::{ @@ -113,6 +115,7 @@ mod tests { let client_socket_addr = sample_ipv4_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let info_hash = InfoHash([0u8; 20]); let info_hashes = vec![info_hash]; @@ -126,7 +129,7 @@ mod tests { let response = handle_scrape( &core_udp_tracker_services.scrape_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), @@ -180,6 +183,7 @@ mod tests { let client_socket_addr = sample_ipv4_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let info_hash = InfoHash([0u8; 20]); @@ -195,7 +199,7 @@ mod tests { handle_scrape( &core_udp_tracker_services.scrape_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &udp_server_stats_event_sender, sample_cookie_valid_range(), @@ -240,6 +244,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use aquatic_udp_protocol::{InfoHash, NumberOfDownloads, NumberOfPeers, TorrentScrapeStatistics}; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::handlers::handle_scrape; use crate::handlers::scrape::tests::scrape_request::{ @@ -256,6 +261,7 @@ mod tests { let client_socket_addr = sample_ipv4_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let info_hash = InfoHash([0u8; 20]); @@ -274,7 +280,7 @@ mod tests { handle_scrape( &core_udp_tracker_services.scrape_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), @@ -300,6 +306,7 @@ mod tests { let client_socket_addr = sample_ipv4_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let info_hash = InfoHash([0u8; 20]); @@ -316,7 +323,7 @@ mod tests { handle_scrape( &core_udp_tracker_services.scrape_service, client_socket_addr, - server_socket_addr, + server_service_binding, &request, &server_udp_tracker_services.udp_server_stats_event_sender, sample_cookie_valid_range(), @@ -349,6 +356,7 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::sample_scrape_request; use crate::event; @@ -363,12 +371,13 @@ mod tests { async fn should_send_the_upd4_scrape_event() { let client_socket_addr = sample_ipv4_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() .with(eq(Event::UdpRequestAccepted { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Scrape, })) .times(1) @@ -382,7 +391,7 @@ mod tests { handle_scrape( &core_udp_tracker_services.scrape_service, client_socket_addr, - server_socket_addr, + server_service_binding, &sample_scrape_request(&client_socket_addr), &udp_server_stats_event_sender, sample_cookie_valid_range(), @@ -398,6 +407,7 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::sample_scrape_request; use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; @@ -411,12 +421,13 @@ mod tests { async fn should_send_the_upd6_scrape_event() { let client_socket_addr = sample_ipv6_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); + let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send_event() .with(eq(Event::UdpRequestAccepted { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Scrape, })) .times(1) @@ -430,7 +441,7 @@ mod tests { handle_scrape( &core_udp_tracker_services.scrape_service, client_socket_addr, - server_socket_addr, + server_service_binding, &sample_scrape_request(&client_socket_addr), &udp_server_stats_event_sender, sample_cookie_valid_range(), diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index fd689a96f..5de41066f 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -13,7 +13,7 @@ use tokio::time::interval; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::ServiceHealthCheckJob; use torrust_server_lib::signals::{shutdown_signal_with_message, Halted, Started}; -use torrust_tracker_primitives::service_binding::ServiceBinding; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use tracing::instrument; use super::request_buffer::ActiveRequests; @@ -138,7 +138,10 @@ impl Launcher { let server_socket_addr = receiver.bound_socket_address(); - let local_addr = format!("udp://{server_socket_addr}"); + let server_service_binding = + ServiceBinding::new(Protocol::UDP, server_socket_addr).expect("Bound socket to service binding should not fail"); + + let local_addr = server_service_binding.clone().to_string(); let cookie_lifetime = cookie_lifetime.as_secs_f64(); @@ -156,6 +159,9 @@ impl Launcher { }); loop { + let server_service_binding = + ServiceBinding::new(Protocol::UDP, server_socket_addr).expect("Bound socket to service binding should not fail"); + if let Some(req) = { tracing::trace!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server (wait for request)"); receiver.next().await @@ -180,7 +186,7 @@ impl Launcher { { udp_server_stats_event_sender .send_event(Event::UdpRequestReceived { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), }) .await; } @@ -193,7 +199,7 @@ impl Launcher { { udp_server_stats_event_sender .send_event(Event::UdpRequestBanned { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), }) .await; } @@ -235,7 +241,7 @@ impl Launcher { { udp_server_stats_event_sender .send_event(Event::UdpRequestAborted { - context: ConnectionContext::new(client_socket_addr, server_socket_addr), + context: ConnectionContext::new(client_socket_addr, server_service_binding), }) .await; } diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs index 02e084356..5e98b0361 100644 --- a/packages/udp-tracker-server/src/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -7,6 +7,7 @@ use aquatic_udp_protocol::Response; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::{self}; use tokio::time::Instant; +use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use tracing::{instrument, Level}; use super::bound_socket::BoundSocket; @@ -20,20 +21,29 @@ pub struct Processor { udp_tracker_core_container: Arc, udp_tracker_server_container: Arc, cookie_lifetime: f64, + server_service_binding: ServiceBinding, } impl Processor { + /// # Panics + /// + /// It will panic if a bound socket address port is 0. It should never + /// happen. pub fn new( socket: Arc, udp_tracker_core_container: Arc, udp_tracker_server_container: Arc, cookie_lifetime: f64, ) -> Self { + let server_service_binding = + ServiceBinding::new(Protocol::UDP, socket.address()).expect("Bound socket port should't be 0"); + Self { socket, udp_tracker_core_container, udp_tracker_server_container, cookie_lifetime, + server_service_binding, } } @@ -47,7 +57,7 @@ impl Processor { request, self.udp_tracker_core_container.clone(), self.udp_tracker_server_container.clone(), - self.socket.address(), + self.server_service_binding.clone(), CookieTimeValues::new(self.cookie_lifetime), ) .await; @@ -109,7 +119,7 @@ impl Processor { { udp_server_stats_event_sender .send_event(Event::UdpResponseSent { - context: ConnectionContext::new(client_socket_addr, self.socket.address()), + context: ConnectionContext::new(client_socket_addr, self.server_service_binding), kind: udp_response_kind, req_processing_time, }) diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index f65a1e567..b06c8d725 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -100,6 +100,8 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::event::{ConnectionContext, Event, UdpRequestKind}; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; @@ -112,7 +114,11 @@ mod tests { Event::UdpRequestAborted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, @@ -132,7 +138,11 @@ mod tests { Event::UdpRequestBanned { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, @@ -152,7 +162,11 @@ mod tests { Event::UdpRequestReceived { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, @@ -172,7 +186,11 @@ mod tests { Event::UdpRequestAborted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, @@ -189,7 +207,11 @@ mod tests { Event::UdpRequestBanned { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, @@ -207,7 +229,11 @@ mod tests { Event::UdpRequestAccepted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), kind: crate::event::UdpRequestKind::Connect, }, @@ -228,7 +254,11 @@ mod tests { Event::UdpRequestAccepted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), kind: crate::event::UdpRequestKind::Announce, }, @@ -249,7 +279,11 @@ mod tests { Event::UdpRequestAccepted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), kind: crate::event::UdpRequestKind::Scrape, }, @@ -270,7 +304,11 @@ mod tests { Event::UdpResponseSent { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), kind: crate::event::UdpResponseKind::Ok { req_kind: UdpRequestKind::Announce, @@ -294,7 +332,11 @@ mod tests { Event::UdpError { context: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, @@ -314,7 +356,11 @@ mod tests { Event::UdpRequestAccepted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), ), kind: crate::event::UdpRequestKind::Connect, }, @@ -335,7 +381,11 @@ mod tests { Event::UdpRequestAccepted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), ), kind: crate::event::UdpRequestKind::Announce, }, @@ -356,7 +406,11 @@ mod tests { Event::UdpRequestAccepted { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), ), kind: crate::event::UdpRequestKind::Scrape, }, @@ -377,7 +431,11 @@ mod tests { Event::UdpResponseSent { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), ), kind: crate::event::UdpResponseKind::Ok { req_kind: UdpRequestKind::Announce, @@ -400,7 +458,11 @@ mod tests { Event::UdpError { context: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), ), }, &stats_repository, From a46011637ab11a0aef09ac70985069efe50364f9 Mon Sep 17 00:00:00 2001 From: Victor Bjelkholm Date: Fri, 4 Apr 2025 13:56:49 +0200 Subject: [PATCH 0930/1297] Change rustdoc docs to only compile+run in release mode As-is, it asks the user to do a release mode build first, then after creating the directories, then do a debug mode build + run. This commit simplifies it and avoids compiling the tracker in both debug and release mode, and instead only compiles+run with release mode --- src/lib.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 0aaf34fe4..b26960899 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -138,7 +138,6 @@ //! ```text //! git clone https://github.com/torrust/torrust-tracker.git \ //! && cd torrust-tracker \ -//! && cargo build --release \ //! && mkdir -p ./storage/tracker/etc \ //! && mkdir -p ./storage/tracker/lib/database \ //! && mkdir -p ./storage/tracker/lib/tls \ @@ -149,7 +148,7 @@ //! compile and after being compiled it will start running the tracker. //! //! ```text -//! cargo run +//! cargo run --release //! ``` //! //! ## Run with docker From 8a169b1f48f662e941a5ca7f4911b365325bebe1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 8 Apr 2025 17:59:00 +0100 Subject: [PATCH 0931/1297] feat: add protocol method to ServiceBinding --- packages/primitives/src/service_binding.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/primitives/src/service_binding.rs b/packages/primitives/src/service_binding.rs index dbbb32fd5..30eb1aa9e 100644 --- a/packages/primitives/src/service_binding.rs +++ b/packages/primitives/src/service_binding.rs @@ -83,6 +83,12 @@ impl ServiceBinding { Ok(Self { protocol, bind_address }) } + /// Returns the protocol used by the service. + #[must_use] + pub fn protocol(&self) -> Protocol { + self.protocol.clone() + } + #[must_use] pub fn bind_address(&self) -> SocketAddr { self.bind_address From 730de9ff633fe0b444cac784d33adae204a13d2d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 8 Apr 2025 18:01:34 +0100 Subject: [PATCH 0932/1297] feat: [#1403] add new package for extendable labeled metrics This package allow creating collection of metrics that can have labels. It's similar to the `metrics` crate. There are two types of metrics: - Counter - Gauge For example, you can increase a counter with: ```rust let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); let mut metric_collection = MetricCollection::new( // Collection of counter-type metrics MetricKindCollection::new(vec![ Metric::new( MetricName::new("test_counter"), SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())])) ]), // Empty colelction of gauge-type metrics MetricKindCollection::new(vec![]) ); metric_collection.increase_counter(&MetricName::new("test_counter"), &label_set, time); ``` Metric colelctions are serializable into JSON and exportable to Prometheus format. --- .github/workflows/deployment.yaml | 1 + cSpell.json | 6 + packages/metrics/.gitignore | 1 + packages/metrics/Cargo.toml | 29 + packages/metrics/LICENSE | 661 +++++++++++++++ packages/metrics/README.md | 15 + packages/metrics/src/counter.rs | 81 ++ packages/metrics/src/gauge.rs | 83 ++ packages/metrics/src/label/mod.rs | 9 + packages/metrics/src/label/name.rs | 117 +++ packages/metrics/src/label/pair.rs | 29 + packages/metrics/src/label/set.rs | 340 ++++++++ packages/metrics/src/label/value.rs | 32 + packages/metrics/src/lib.rs | 29 + packages/metrics/src/metric/description.rs | 29 + packages/metrics/src/metric/mod.rs | 192 +++++ packages/metrics/src/metric/name.rs | 92 +++ packages/metrics/src/metric_collection.rs | 759 ++++++++++++++++++ packages/metrics/src/prometheus.rs | 15 + packages/metrics/src/sample.rs | 355 ++++++++ packages/metrics/src/sample_collection.rs | 411 ++++++++++ .../src/thread_safe_metric_collection.rs | 92 +++ packages/metrics/src/unit.rs | 25 + 23 files changed, 3403 insertions(+) create mode 100644 packages/metrics/.gitignore create mode 100644 packages/metrics/Cargo.toml create mode 100644 packages/metrics/LICENSE create mode 100644 packages/metrics/README.md create mode 100644 packages/metrics/src/counter.rs create mode 100644 packages/metrics/src/gauge.rs create mode 100644 packages/metrics/src/label/mod.rs create mode 100644 packages/metrics/src/label/name.rs create mode 100644 packages/metrics/src/label/pair.rs create mode 100644 packages/metrics/src/label/set.rs create mode 100644 packages/metrics/src/label/value.rs create mode 100644 packages/metrics/src/lib.rs create mode 100644 packages/metrics/src/metric/description.rs create mode 100644 packages/metrics/src/metric/mod.rs create mode 100644 packages/metrics/src/metric/name.rs create mode 100644 packages/metrics/src/metric_collection.rs create mode 100644 packages/metrics/src/prometheus.rs create mode 100644 packages/metrics/src/sample.rs create mode 100644 packages/metrics/src/sample_collection.rs create mode 100644 packages/metrics/src/thread_safe_metric_collection.rs create mode 100644 packages/metrics/src/unit.rs diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 1422ec394..983817273 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -74,6 +74,7 @@ jobs: cargo publish -p torrust-tracker-configuration cargo publish -p torrust-tracker-contrib-bencode cargo publish -p torrust-tracker-located-error + cargo publish -p torrust-tracker-metrics cargo publish -p torrust-tracker-primitives cargo publish -p torrust-tracker-test-helpers cargo publish -p torrust-tracker-torrent-repository diff --git a/cSpell.json b/cSpell.json index 3121d6175..e384a08d9 100644 --- a/cSpell.json +++ b/cSpell.json @@ -59,9 +59,11 @@ "Eray", "filesd", "flamegraph", + "formatjson", "Freebox", "Frostegård", "gecos", + "Gibibytes", "Grcov", "hasher", "healthcheck", @@ -86,6 +88,7 @@ "kcachegrind", "kexec", "keyout", + "Kibibytes", "kptr", "lcov", "leecher", @@ -96,12 +99,14 @@ "LOGNAME", "Lphant", "matchmakes", + "Mebibytes", "metainfo", "middlewares", "misresolved", "mockall", "multimap", "myacicontext", + "ñaca", "Naim", "nanos", "newkey", @@ -157,6 +162,7 @@ "Swiftbit", "taiki", "tdyne", + "Tebibytes", "tempfile", "testcontainers", "thiserror", diff --git a/packages/metrics/.gitignore b/packages/metrics/.gitignore new file mode 100644 index 000000000..0b1372e5c --- /dev/null +++ b/packages/metrics/.gitignore @@ -0,0 +1 @@ +./.coverage diff --git a/packages/metrics/Cargo.toml b/packages/metrics/Cargo.toml new file mode 100644 index 000000000..6520cf244 --- /dev/null +++ b/packages/metrics/Cargo.toml @@ -0,0 +1,29 @@ +[package] +description = "A library with the primitive types shared by the Torrust tracker packages." +keywords = ["api", "library", "metrics"] +name = "torrust-tracker-metrics" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +chrono = { version = "0", default-features = false, features = ["clock"] } +derive_more = { version = "2", features = ["constructor"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1.0.140" +thiserror = "2" +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } + +[dev-dependencies] +approx = "0.5.1" +formatjson = "0.3.1" +pretty_assertions = "1.4.1" +rstest = "0.25.0" diff --git a/packages/metrics/LICENSE b/packages/metrics/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/metrics/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/metrics/README.md b/packages/metrics/README.md new file mode 100644 index 000000000..627640eec --- /dev/null +++ b/packages/metrics/README.md @@ -0,0 +1,15 @@ +# Torrust Tracker Metrics + +A library with the metrics types used by the [Torrust Tracker](https://github.com/torrust/torrust-tracker) packages. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-metrics). + +## Acknowledgements + +We copied some parts like units or function names and signatures from the crate [metrics](https://crates.io/crates/metrics) because we wanted to make it compatible as much as possible with it. In the future, we may consider using the `metrics` crate directly instead of maintaining our own version. + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/metrics/src/counter.rs b/packages/metrics/src/counter.rs new file mode 100644 index 000000000..3a816c75b --- /dev/null +++ b/packages/metrics/src/counter.rs @@ -0,0 +1,81 @@ +use derive_more::Display; +use serde::{Deserialize, Serialize}; + +use super::prometheus::PrometheusSerializable; + +#[derive(Debug, Display, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Counter(u64); + +impl Counter { + #[must_use] + pub fn new(value: u64) -> Self { + Self(value) + } + + #[must_use] + pub fn value(&self) -> u64 { + self.0 + } + + pub fn increment(&mut self, value: u64) { + self.0 += value; + } +} + +impl From for Counter { + fn from(value: u64) -> Self { + Self(value) + } +} + +impl From for u64 { + fn from(counter: Counter) -> Self { + counter.value() + } +} + +impl PrometheusSerializable for Counter { + fn to_prometheus(&self) -> String { + format!("{}", self.value()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_should_be_created_from_integer_values() { + let counter = Counter::new(0); + assert_eq!(counter.value(), 0); + } + + #[test] + fn it_could_be_converted_from_u64() { + let counter: Counter = 42.into(); + assert_eq!(counter.value(), 42); + } + + #[test] + fn it_could_be_converted_into_u64() { + let counter = Counter::new(42); + let value: u64 = counter.into(); + assert_eq!(value, 42); + } + + #[test] + fn it_could_be_incremented() { + let mut counter = Counter::new(0); + counter.increment(1); + assert_eq!(counter.value(), 1); + + counter.increment(2); + assert_eq!(counter.value(), 3); + } + + #[test] + fn it_serializes_to_prometheus() { + let counter = Counter::new(42); + assert_eq!(counter.to_prometheus(), "42"); + } +} diff --git a/packages/metrics/src/gauge.rs b/packages/metrics/src/gauge.rs new file mode 100644 index 000000000..61ff3024c --- /dev/null +++ b/packages/metrics/src/gauge.rs @@ -0,0 +1,83 @@ +use derive_more::Display; +use serde::{Deserialize, Serialize}; + +use super::prometheus::PrometheusSerializable; + +#[derive(Debug, Display, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Gauge(f64); + +impl Gauge { + #[must_use] + pub fn new(value: f64) -> Self { + Self(value) + } + + #[must_use] + pub fn value(&self) -> f64 { + self.0 + } + + pub fn set(&mut self, value: f64) { + self.0 = value; + } +} + +impl From for Gauge { + fn from(value: f64) -> Self { + Self(value) + } +} + +impl From for f64 { + fn from(counter: Gauge) -> Self { + counter.value() + } +} + +impl PrometheusSerializable for Gauge { + fn to_prometheus(&self) -> String { + format!("{}", self.value()) + } +} + +#[cfg(test)] +mod tests { + use approx::assert_relative_eq; + + use super::*; + + #[test] + fn it_should_be_created_from_integer_values() { + let gauge = Gauge::new(0.0); + assert_relative_eq!(gauge.value(), 0.0); + } + + #[test] + fn it_could_be_converted_from_u64() { + let gauge: Gauge = 42.0.into(); + assert_relative_eq!(gauge.value(), 42.0); + } + + #[test] + fn it_could_be_converted_into_i64() { + let gauge = Gauge::new(42.0); + let value: f64 = gauge.into(); + assert_relative_eq!(value, 42.0); + } + + #[test] + fn it_could_be_set() { + let mut gauge = Gauge::new(0.0); + gauge.set(1.0); + assert_relative_eq!(gauge.value(), 1.0); + } + + #[test] + fn it_serializes_to_prometheus() { + let counter = Gauge::new(42.0); + assert_eq!(counter.to_prometheus(), "42"); + + let counter = Gauge::new(42.1); + assert_eq!(counter.to_prometheus(), "42.1"); + } +} diff --git a/packages/metrics/src/label/mod.rs b/packages/metrics/src/label/mod.rs new file mode 100644 index 000000000..b5fd3b745 --- /dev/null +++ b/packages/metrics/src/label/mod.rs @@ -0,0 +1,9 @@ +mod name; +mod pair; +mod set; +mod value; + +pub type LabelName = name::LabelName; +pub type LabelValue = value::LabelValue; +pub type LabelPair = pair::LabelPair; +pub type LabelSet = set::LabelSet; diff --git a/packages/metrics/src/label/name.rs b/packages/metrics/src/label/name.rs new file mode 100644 index 000000000..22e75572f --- /dev/null +++ b/packages/metrics/src/label/name.rs @@ -0,0 +1,117 @@ +use derive_more::Display; +use serde::{Deserialize, Serialize}; + +use crate::prometheus::PrometheusSerializable; + +#[derive(Debug, Display, Clone, Eq, PartialEq, Default, Deserialize, Serialize, Hash, Ord, PartialOrd)] +pub struct LabelName(String); + +impl LabelName { + /// Creates a new `LabelName` instance. + /// + /// # Panics + /// + /// Panics if the provided name is empty. + #[must_use] + pub fn new(name: &str) -> Self { + assert!( + !name.is_empty(), + "Label name cannot be empty. It must have at least one character." + ); + + Self(name.to_owned()) + } +} + +impl PrometheusSerializable for LabelName { + /// In Prometheus: + /// + /// - Labels may contain ASCII letters, numbers, as well as underscores. + /// They must match the regex [a-zA-Z_][a-zA-Z0-9_]*. + /// - Label names beginning with __ (two "_") are reserved for internal + /// use. + /// - Label values may contain any Unicode characters. + /// - Labels with an empty label value are considered equivalent to + /// labels that do not exist. + /// + /// The label name is changed: + /// + /// - If a label name starts with, or contains, an invalid character: + /// replace character with underscore. + /// - If th label name starts with two underscores: + /// add additional underscore (three underscores total) + fn to_prometheus(&self) -> String { + // Replace invalid characters with underscore + let processed: String = self + .0 + .chars() + .enumerate() + .map(|(i, c)| { + if i == 0 { + if c.is_ascii_alphabetic() || c == '_' { + c + } else { + '_' + } + } else if c.is_ascii_alphanumeric() || c == '_' { + c + } else { + '_' + } + }) + .collect(); + + // If the label name starts with two underscores, add an additional + if processed.starts_with("__") && !processed.starts_with("___") { + format!("_{processed}") + } else { + processed + } + } +} +#[cfg(test)] +mod tests { + mod serialization_of_label_name_to_prometheus { + use rstest::rstest; + + use crate::label::LabelName; + use crate::prometheus::PrometheusSerializable; + + #[rstest] + #[case("1 valid name", "valid_name", "valid_name")] + #[case("2 leading underscore", "_leading_underscore", "_leading_underscore")] + #[case("3 leading lowercase", "v123", "v123")] + #[case("4 leading uppercase", "V123", "V123")] + fn valid_names_in_prometheus(#[case] case: &str, #[case] input: &str, #[case] output: &str) { + assert_eq!(LabelName::new(input).to_prometheus(), output, "{case} failed: {input:?}"); + } + + #[rstest] + #[case("1 invalid start 1", "9invalid_start", "_invalid_start")] + #[case("2 invalid start 2", "@test", "_test")] + #[case("3 invalid dash", "invalid-char", "invalid_char")] + #[case("4 invalid spaces", "spaces are bad", "spaces_are_bad")] + #[case("5 invalid special chars", "a!b@c#d$e%f^g&h*i(j)", "a_b_c_d_e_f_g_h_i_j_")] + #[case("6 invalid colon", "my:metric/version", "my_metric_version")] + #[case("7 all invalid characters", "!@#$%^&*()", "__________")] + #[case("8 non_ascii_characters", "ñaca©", "_aca_")] + fn names_that_need_changes_in_prometheus(#[case] case: &str, #[case] input: &str, #[case] output: &str) { + assert_eq!(LabelName::new(input).to_prometheus(), output, "{case} failed: {input:?}"); + } + + #[rstest] + #[case("1 double underscore start", "__private", "___private")] + #[case("2 double underscore only", "__", "___")] + #[case("3 processed to double underscore", "^^name", "___name")] + #[case("4 processed to double underscore after first char", "0__name", "___name")] + fn names_starting_with_double_underscore(#[case] case: &str, #[case] input: &str, #[case] output: &str) { + assert_eq!(LabelName::new(input).to_prometheus(), output, "{case} failed: {input:?}"); + } + + #[test] + #[should_panic(expected = "Label name cannot be empty. It must have at least one character.")] + fn empty_name() { + let _name = LabelName::new(""); + } + } +} diff --git a/packages/metrics/src/label/pair.rs b/packages/metrics/src/label/pair.rs new file mode 100644 index 000000000..c89c726bd --- /dev/null +++ b/packages/metrics/src/label/pair.rs @@ -0,0 +1,29 @@ +use super::{LabelName, LabelValue}; +use crate::prometheus::PrometheusSerializable; + +pub type LabelPair = (LabelName, LabelValue); + +// Generic implementation for any tuple (A, B) where A and B implement PrometheusSerializable +impl PrometheusSerializable for (A, B) { + fn to_prometheus(&self) -> String { + format!("{}=\"{}\"", self.0.to_prometheus(), self.1.to_prometheus()) + } +} + +#[cfg(test)] +mod tests { + mod serialization_of_label_pair_to_prometheus { + use super::super::LabelName; + use crate::label::LabelValue; + use crate::prometheus::PrometheusSerializable; + + #[test] + fn test_label_pair_serialization_to_prometheus() { + let label_pair = (LabelName::new("label_name"), LabelValue::new("value")); + assert_eq!(label_pair.to_prometheus(), r#"label_name="value""#); + + let label_pair = (&LabelName::new("label_name"), &LabelValue::new("value")); + assert_eq!(label_pair.to_prometheus(), r#"label_name="value""#); + } + } +} diff --git a/packages/metrics/src/label/set.rs b/packages/metrics/src/label/set.rs new file mode 100644 index 000000000..f46b01095 --- /dev/null +++ b/packages/metrics/src/label/set.rs @@ -0,0 +1,340 @@ +use std::collections::BTreeMap; +use std::fmt::Display; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +use super::{LabelName, LabelPair, LabelValue}; +use crate::prometheus::PrometheusSerializable; + +#[derive(Debug, Clone, Eq, PartialEq, Default, Ord, PartialOrd, Hash)] +pub struct LabelSet { + items: BTreeMap, +} + +impl LabelSet { + /// Insert a new label pair or update the value of an existing label. + pub fn upsert(&mut self, key: LabelName, value: LabelValue) { + self.items.insert(key, value); + } +} + +impl Display for LabelSet { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let items = self + .items + .iter() + .map(|(key, value)| format!("{key}=\"{value}\"")) + .collect::>() + .join(","); + + write!(f, "{{{items}}}") + } +} + +impl From> for LabelSet { + fn from(values: BTreeMap) -> Self { + Self { items: values } + } +} + +impl From> for LabelSet { + fn from(vec: Vec<(&str, &str)>) -> Self { + let mut items = BTreeMap::new(); + + for (name, value) in vec { + items.insert(LabelName::new(name), LabelValue::new(value)); + } + + Self { items } + } +} + +impl From> for LabelSet { + fn from(vec: Vec<(String, String)>) -> Self { + let mut items = BTreeMap::new(); + + for (name, value) in vec { + items.insert(LabelName::new(&name), LabelValue::new(&value)); + } + + Self { items } + } +} + +impl From> for LabelSet { + fn from(vec: Vec) -> Self { + let mut items = BTreeMap::new(); + + for (key, value) in vec { + items.insert(key, value); + } + + Self { items } + } +} + +impl From> for LabelSet { + fn from(vec: Vec) -> Self { + let mut items = BTreeMap::new(); + + for serialized_label in vec { + items.insert(serialized_label.name, serialized_label.value); + } + + Self { items } + } +} + +impl From<[LabelPair; N]> for LabelSet { + fn from(arr: [LabelPair; N]) -> Self { + let values = BTreeMap::from(arr); + Self { items: values } + } +} + +impl From<[(String, String); N]> for LabelSet { + fn from(arr: [(String, String); N]) -> Self { + let values = arr + .iter() + .map(|(name, value)| (LabelName::new(name), LabelValue::new(value))) + .collect::>(); + Self { items: values } + } +} + +impl From<[(&str, &str); N]> for LabelSet { + fn from(arr: [(&str, &str); N]) -> Self { + let values = arr + .iter() + .map(|(name, value)| (LabelName::new(name), LabelValue::new(value))) + .collect::>(); + Self { items: values } + } +} + +impl From for LabelSet { + fn from(label_pair: LabelPair) -> Self { + let mut set = BTreeMap::new(); + + set.insert(label_pair.0, label_pair.1); + + Self { items: set } + } +} + +#[derive(Debug, Clone, Eq, PartialEq, Default, Deserialize, Serialize)] +struct SerializedLabel { + name: LabelName, + value: LabelValue, +} + +impl Serialize for LabelSet { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.items + .iter() + .map(|(key, value)| SerializedLabel { + name: key.clone(), + value: value.clone(), + }) + .collect::>() + .serialize(serializer) + } +} + +impl<'de> Deserialize<'de> for LabelSet { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let serialized_labels = Vec::::deserialize(deserializer)?; + + Ok(LabelSet::from(serialized_labels)) + } +} + +impl PrometheusSerializable for LabelSet { + fn to_prometheus(&self) -> String { + let items = self.items.iter().fold(String::new(), |mut output, label_pair| { + if !output.is_empty() { + output.push(','); + } + + output.push_str(&label_pair.to_prometheus()); + + output + }); + + format!("{{{items}}}") + } +} + +#[cfg(test)] +mod tests { + + use std::collections::BTreeMap; + + use pretty_assertions::assert_eq; + + use super::{LabelName, LabelValue}; + use crate::label::LabelSet; + use crate::prometheus::PrometheusSerializable; + + fn sample_vec_of_label_pairs() -> Vec<(LabelName, LabelValue)> { + sample_array_of_label_pairs().into() + } + + fn sample_array_of_label_pairs() -> [(LabelName, LabelValue); 3] { + [ + (LabelName::new("server_service_binding_protocol"), LabelValue::new("http")), + (LabelName::new("server_service_binding_ip"), LabelValue::new("0.0.0.0")), + (LabelName::new("server_service_binding_port"), LabelValue::new("7070")), + ] + } + + #[test] + fn it_should_allow_instantiation_from_an_array_of_label_pairs() { + let label_set: LabelSet = sample_array_of_label_pairs().into(); + + assert_eq!( + label_set, + LabelSet { + items: BTreeMap::from(sample_array_of_label_pairs()) + } + ); + } + + #[test] + fn it_should_allow_instantiation_from_a_vec_of_label_pairs() { + let label_set: LabelSet = sample_vec_of_label_pairs().into(); + + assert_eq!( + label_set, + LabelSet { + items: BTreeMap::from(sample_array_of_label_pairs()) + } + ); + } + + #[test] + fn it_should_allow_instantiation_from_a_b_tree_map() { + let label_set: LabelSet = BTreeMap::from(sample_array_of_label_pairs()).into(); + + assert_eq!( + label_set, + LabelSet { + items: BTreeMap::from(sample_array_of_label_pairs()) + } + ); + } + + #[test] + fn it_should_allow_instantiation_from_a_label_pair() { + let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + + assert_eq!( + label_set, + LabelSet { + items: BTreeMap::from([(LabelName::new("label_name"), LabelValue::new("value"))]) + } + ); + } + + #[test] + fn it_should_allow_inserting_a_new_label_pair() { + let mut label_set = LabelSet::default(); + + label_set.upsert(LabelName::new("label_name"), LabelValue::new("value")); + + assert_eq!( + label_set.items.get(&LabelName::new("label_name")).unwrap(), + &LabelValue::new("value") + ); + } + + #[test] + fn it_should_allow_updating_a_label_value() { + let mut label_set = LabelSet::default(); + + label_set.upsert(LabelName::new("label_name"), LabelValue::new("old value")); + label_set.upsert(LabelName::new("label_name"), LabelValue::new("new value")); + + assert_eq!( + label_set.items.get(&LabelName::new("label_name")).unwrap(), + &LabelValue::new("new value") + ); + } + + #[test] + fn it_should_allow_serializing_to_json_as_an_array_of_label_objects() { + let label_set = LabelSet::from((LabelName::new("label_name"), LabelValue::new("label value"))); + + let json = serde_json::to_string(&label_set).unwrap(); + + assert_eq!( + formatjson::format_json(&json).unwrap(), + formatjson::format_json( + r#" + [ + { + "name": "label_name", + "value": "label value" + } + ] + "# + ) + .unwrap() + ); + } + + #[test] + fn it_should_allow_deserializing_from_json_as_an_array_of_label_objects() { + let json = formatjson::format_json( + r#" + [ + { + "name": "label_name", + "value": "label value" + } + ] + "#, + ) + .unwrap(); + + let label_set: LabelSet = serde_json::from_str(&json).unwrap(); + + assert_eq!( + label_set, + LabelSet::from((LabelName::new("label_name"), LabelValue::new("label value"))) + ); + } + + #[test] + fn it_should_allow_serializing_to_prometheus_format() { + let label_set = LabelSet::from((LabelName::new("label_name"), LabelValue::new("label value"))); + + assert_eq!(label_set.to_prometheus(), r#"{label_name="label value"}"#); + } + + #[test] + fn it_should_alphabetically_order_labels_in_prometheus_format() { + let label_set = LabelSet::from([ + (LabelName::new("b_label_name"), LabelValue::new("b label value")), + (LabelName::new("a_label_name"), LabelValue::new("a label value")), + ]); + + assert_eq!( + label_set.to_prometheus(), + r#"{a_label_name="a label value",b_label_name="b label value"}"# + ); + } + + #[test] + fn it_should_allow_displaying() { + let label_set = LabelSet::from((LabelName::new("label_name"), LabelValue::new("label value"))); + + assert_eq!(label_set.to_string(), r#"{label_name="label value"}"#); + } +} diff --git a/packages/metrics/src/label/value.rs b/packages/metrics/src/label/value.rs new file mode 100644 index 000000000..ce657250c --- /dev/null +++ b/packages/metrics/src/label/value.rs @@ -0,0 +1,32 @@ +use derive_more::Display; +use serde::{Deserialize, Serialize}; + +use crate::prometheus::PrometheusSerializable; + +#[derive(Debug, Display, Clone, Eq, PartialEq, Default, Deserialize, Serialize, Hash, Ord, PartialOrd)] +pub struct LabelValue(String); + +impl LabelValue { + #[must_use] + pub fn new(value: &str) -> Self { + Self(value.to_owned()) + } +} + +impl PrometheusSerializable for LabelValue { + fn to_prometheus(&self) -> String { + self.0.clone() + } +} + +#[cfg(test)] +mod tests { + use crate::label::value::LabelValue; + use crate::prometheus::PrometheusSerializable; + + #[test] + fn it_serializes_to_prometheus() { + let label_value = LabelValue::new("value"); + assert_eq!(label_value.to_prometheus(), "value"); + } +} diff --git a/packages/metrics/src/lib.rs b/packages/metrics/src/lib.rs new file mode 100644 index 000000000..1cb0df195 --- /dev/null +++ b/packages/metrics/src/lib.rs @@ -0,0 +1,29 @@ +pub mod counter; +pub mod gauge; +pub mod label; +pub mod metric; +pub mod metric_collection; +pub mod prometheus; +pub mod sample; +pub mod sample_collection; +pub mod thread_safe_metric_collection; +pub mod unit; + +#[cfg(test)] +mod tests { + /// It removes leading and trailing whitespace from each line, and empty lines. + pub fn format_prometheus_output(output: &str) -> String { + output + .lines() + .map(str::trim) + .filter(|line| !line.is_empty()) + .collect::>() + .join("\n") + } + + pub fn sort_lines(s: &str) -> String { + let mut lines: Vec<&str> = s.split('\n').collect(); + lines.sort_unstable(); + lines.join("\n") + } +} diff --git a/packages/metrics/src/metric/description.rs b/packages/metrics/src/metric/description.rs new file mode 100644 index 000000000..8a50dee90 --- /dev/null +++ b/packages/metrics/src/metric/description.rs @@ -0,0 +1,29 @@ +use derive_more::Display; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Display, Clone, Eq, PartialEq, Default, Deserialize, Serialize, Hash, Ord, PartialOrd)] +pub struct MetricDescription(String); + +impl MetricDescription { + #[must_use] + pub fn new(name: &str) -> Self { + Self(name.to_owned()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_should_be_created_from_a_string_reference() { + let metric = MetricDescription::new("Metric description"); + assert_eq!(metric.0, "Metric description"); + } + + #[test] + fn it_should_be_displayed() { + let metric = MetricDescription::new("Metric description"); + assert_eq!(metric.to_string(), "Metric description"); + } +} diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs new file mode 100644 index 000000000..0d79a24d3 --- /dev/null +++ b/packages/metrics/src/metric/mod.rs @@ -0,0 +1,192 @@ +pub mod description; +pub mod name; + +use serde::{Deserialize, Serialize}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::counter::Counter; +use super::label::LabelSet; +use super::prometheus::PrometheusSerializable; +use super::sample::Sample; +use super::sample_collection::SampleCollection; +use crate::gauge::Gauge; + +pub type MetricName = name::MetricName; + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Metric { + name: MetricName, + + #[serde(rename = "samples")] + sample_collection: SampleCollection, +} + +impl Metric { + #[must_use] + pub fn new(name: MetricName, samples: SampleCollection) -> Self { + Self { + name, + sample_collection: samples, + } + } + + #[must_use] + pub fn name(&self) -> &MetricName { + &self.name + } + + #[must_use] + pub fn get_sample(&self, label_set: &LabelSet) -> Option<&Sample> { + self.sample_collection.get(label_set) + } + + #[must_use] + pub fn number_of_samples(&self) -> usize { + self.sample_collection.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.sample_collection.is_empty() + } +} + +impl Metric { + pub fn increment(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + self.sample_collection.increment(label_set, time); + } +} + +impl Metric { + pub fn set(&mut self, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { + self.sample_collection.set(label_set, value, time); + } +} + +impl PrometheusSerializable for Metric { + fn to_prometheus(&self) -> String { + let samples: Vec = self + .sample_collection + .iter() + .map(|(_label_set, sample)| { + format!( + "{}{} {}", + self.name.to_prometheus(), + sample.labels().to_prometheus(), + sample.value().to_prometheus() + ) + }) + .collect(); + samples.join("\n") + } +} + +#[cfg(test)] +mod tests { + mod for_generic_metrics { + use super::super::*; + use crate::gauge::Gauge; + use crate::label::{LabelName, LabelValue}; + + #[test] + fn it_should_be_empty_when_it_does_not_have_any_sample() { + let name = MetricName::new("test_metric"); + + let samples = SampleCollection::::default(); + + let metric = Metric::::new(name.clone(), samples); + + assert!(metric.is_empty()); + } + + fn counter_metric_with_one_sample() -> Metric { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + let name = MetricName::new("test_metric"); + + let label_set: LabelSet = [(LabelName::new("server_binding_protocol"), LabelValue::new("http"))].into(); + + let samples = SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set.clone())]); + + Metric::::new(name.clone(), samples) + } + + #[test] + fn it_should_return_the_number_of_samples() { + assert_eq!(counter_metric_with_one_sample().number_of_samples(), 1); + } + + #[test] + fn it_should_return_zero_number_of_samples_for_an_empty_metric() { + let name = MetricName::new("test_metric"); + + let samples = SampleCollection::::default(); + + let metric = Metric::::new(name.clone(), samples); + + assert_eq!(metric.number_of_samples(), 0); + } + } + + mod for_counter_metrics { + use super::super::*; + use crate::counter::Counter; + use crate::label::{LabelName, LabelValue}; + + #[test] + fn it_should_be_created_from_its_name_and_a_collection_of_samples() { + let name = MetricName::new("test_metric"); + + let samples = SampleCollection::::default(); + + let _metric = Metric::::new(name, samples); + } + + #[test] + fn it_should_allow_incrementing_a_sample() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + let name = MetricName::new("test_metric"); + + let label_set: LabelSet = [(LabelName::new("server_binding_protocol"), LabelValue::new("http"))].into(); + + let samples = SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set.clone())]); + + let metric = Metric::::new(name.clone(), samples); + + assert_eq!(metric.get_sample(&label_set).unwrap().value().value(), 1); + } + } + + mod for_gauge_metrics { + use approx::assert_relative_eq; + + use super::super::*; + use crate::gauge::Gauge; + use crate::label::{LabelName, LabelValue}; + + #[test] + fn it_should_be_created_from_its_name_and_a_collection_of_samples() { + let name = MetricName::new("test_metric"); + + let samples = SampleCollection::::default(); + + let _metric = Metric::::new(name, samples); + } + + #[test] + fn it_should_allow_setting_a_sample() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + let name = MetricName::new("test_metric"); + + let label_set: LabelSet = [(LabelName::new("server_binding_protocol"), LabelValue::new("http"))].into(); + + let samples = SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set.clone())]); + + let metric = Metric::::new(name.clone(), samples); + + assert_relative_eq!(metric.get_sample(&label_set).unwrap().value().value(), 1.0); + } + } +} diff --git a/packages/metrics/src/metric/name.rs b/packages/metrics/src/metric/name.rs new file mode 100644 index 000000000..c904f34d3 --- /dev/null +++ b/packages/metrics/src/metric/name.rs @@ -0,0 +1,92 @@ +use derive_more::Display; +use serde::{Deserialize, Serialize}; + +use crate::prometheus::PrometheusSerializable; + +#[derive(Debug, Display, Clone, Eq, PartialEq, Default, Deserialize, Serialize, Hash, Ord, PartialOrd)] +pub struct MetricName(String); + +impl MetricName { + /// Creates a new `MetricName` instance. + /// + /// # Panics + /// + /// Panics if the provided name is empty. + #[must_use] + pub fn new(name: &str) -> Self { + assert!( + !name.is_empty(), + "Metric name cannot be empty. It must have at least one character." + ); + + Self(name.to_owned()) + } +} + +impl PrometheusSerializable for MetricName { + fn to_prometheus(&self) -> String { + // Metric names may contain ASCII letters, digits, underscores, and + // colons. It must match the regex [a-zA-Z_:][a-zA-Z0-9_:]*. + // If the metric name starts with, or contains, an invalid character: + // replace character with underscore. + + self.0 + .chars() + .enumerate() + .map(|(i, c)| { + if i == 0 { + if c.is_ascii_alphabetic() || c == '_' || c == ':' { + c + } else { + '_' + } + } else if c.is_ascii_alphanumeric() || c == '_' || c == ':' { + c + } else { + '_' + } + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + + mod serialization_of_metric_name_to_prometheus { + + use rstest::rstest; + + use crate::metric::MetricName; + use crate::prometheus::PrometheusSerializable; + + #[rstest] + #[case("valid name", "valid_name", "valid_name")] + #[case("leading underscore", "_leading_underscore", "_leading_underscore")] + #[case("leading colon", ":leading_colon", ":leading_colon")] + #[case("leading lowercase", "v123", "v123")] + #[case("leading uppercase", "V123", "V123")] + fn valid_names_in_prometheus(#[case] case: &str, #[case] input: &str, #[case] output: &str) { + assert_eq!(MetricName::new(input).to_prometheus(), output, "{case} failed: {input:?}"); + } + + #[rstest] + #[case("invalid start 1", "9invalid_start", "_invalid_start")] + #[case("invalid start 2", "@test", "_test")] + #[case("invalid dash", "invalid-char", "invalid_char")] + #[case("invalid spaces", "spaces are bad", "spaces_are_bad")] + #[case("invalid special chars", "a!b@c#d$e%f^g&h*i(j)", "a_b_c_d_e_f_g_h_i_j_")] + #[case("invalid slash", "my:metric/version", "my:metric_version")] + #[case("all invalid characters", "!@#$%^&*()", "__________")] + #[case("non_ascii_characters", "ñaca©", "_aca_")] + fn names_that_need_changes_in_prometheus(#[case] case: &str, #[case] input: &str, #[case] output: &str) { + assert_eq!(MetricName::new(input).to_prometheus(), output, "{case} failed: {input:?}"); + } + + #[test] + #[should_panic(expected = "Metric name cannot be empty. It must have at least one character.")] + fn empty_name() { + let _name = MetricName::new(""); + } + } +} diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs new file mode 100644 index 000000000..588194e5f --- /dev/null +++ b/packages/metrics/src/metric_collection.rs @@ -0,0 +1,759 @@ +use std::collections::{HashMap, HashSet}; + +use serde::ser::{SerializeSeq, Serializer}; +use serde::{Deserialize, Deserializer, Serialize}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::counter::Counter; +use super::gauge::Gauge; +use super::label::LabelSet; +use super::metric::{Metric, MetricName}; +use super::prometheus::PrometheusSerializable; +use crate::metric::description::MetricDescription; +use crate::sample_collection::SampleCollection; +use crate::unit::Unit; + +// todo: serialize in a deterministic order. For example: +// - First the counter metrics ordered by name. +// - Then the gauge metrics ordered by name. + +/// Use this type only when behind a lock that guarantees thread-safety. +/// Otherwise, there could be race conditions that lead to duplicate metric +/// names in different metric types. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct MetricCollection { + counters: MetricKindCollection, + gauges: MetricKindCollection, +} + +impl MetricCollection { + /// # Panics + /// + /// Panics if there are duplicate metric names across counters and gauges. + #[must_use] + pub fn new(counters: MetricKindCollection, gauges: MetricKindCollection) -> Self { + // Check for name collisions across metric types + let counter_names: HashSet<_> = counters.names().collect(); + let gauge_names: HashSet<_> = gauges.names().collect(); + + assert!( + counter_names.is_disjoint(&gauge_names), + "Metric names must be unique across counters and gauges" + ); + + Self { counters, gauges } + } + + /// Merges another `MetricCollection` into this one. + /// + /// # Errors + /// + /// Returns an error if a metric name already exists in the current collection. + pub fn merge(&mut self, other: &Self) -> Result<(), MergeError> { + self.counters.merge(&other.counters)?; + self.gauges.merge(&other.gauges)?; + Ok(()) + } + + // Counter-specific methods + + pub fn describe_counter(&mut self, name: &MetricName, _opt_unit: Option, _opt_description: Option) { + self.counters.ensure_metric_exists(name); + } + + #[must_use] + pub fn get_counter_value(&self, name: &MetricName, label_set: &LabelSet) -> Counter { + self.counters.get_value(name, label_set) + } + + /// # Panics + /// + /// Panics if a gauge with the same name already exists. + pub fn increase_counter(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + assert!( + !self.gauges.metrics.contains_key(name), + "Cannot create counter with name '{name}': a gauge with this name already exists", + ); + + self.counters.increment(name, label_set, time); + } + + pub fn ensure_counter_exists(&mut self, name: &MetricName) { + self.counters.ensure_metric_exists(name); + } + + // Gauge-specific methods + + pub fn describe_gauge(&mut self, name: &MetricName, _opt_unit: Option, _opt_description: Option) { + self.gauges.ensure_metric_exists(name); + } + + #[must_use] + pub fn get_gauge_value(&self, name: &MetricName, label_set: &LabelSet) -> Gauge { + self.gauges.get_value(name, label_set) + } + + /// # Panics + /// + /// Panics if a counter with the same name already exists. + pub fn set_gauge(&mut self, name: &MetricName, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { + assert!( + !self.counters.metrics.contains_key(name), + "Cannot create gauge with name '{name}': a counter with this name already exists" + ); + + self.gauges.set(name, label_set, value, time); + } + + pub fn ensure_gauge_exists(&mut self, name: &MetricName) { + self.gauges.ensure_metric_exists(name); + } +} + +#[derive(thiserror::Error, Debug, Clone)] +pub enum MergeError { + #[error("Cannot merge metric '{metric_name}': it already exists in the current collection")] + MetricNameAlreadyExists { metric_name: MetricName }, +} + +/// Implements serialization for `MetricCollection`. +impl Serialize for MetricCollection { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + #[derive(Serialize)] + #[serde(tag = "kind", rename_all = "lowercase")] + enum SerializableMetric<'a> { + Counter(&'a Metric), + Gauge(&'a Metric), + } + + let mut seq = serializer.serialize_seq(Some(self.counters.metrics.len() + self.gauges.metrics.len()))?; + + for metric in self.counters.metrics.values() { + seq.serialize_element(&SerializableMetric::Counter(metric))?; + } + + for metric in self.gauges.metrics.values() { + seq.serialize_element(&SerializableMetric::Gauge(metric))?; + } + + seq.end() + } +} + +impl<'de> Deserialize<'de> for MetricCollection { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + #[derive(Deserialize)] + #[serde(tag = "kind", rename_all = "lowercase")] + enum MetricPayload { + Counter(Metric), + Gauge(Metric), + } + + let payload = Vec::::deserialize(deserializer)?; + + let mut counters = Vec::new(); + let mut gauges = Vec::new(); + + for metric in payload { + match metric { + MetricPayload::Counter(counter) => counters.push(counter), + MetricPayload::Gauge(gauge) => gauges.push(gauge), + } + } + + Ok(MetricCollection::new( + MetricKindCollection::new(counters), + MetricKindCollection::new(gauges), + )) + } +} + +impl PrometheusSerializable for MetricCollection { + fn to_prometheus(&self) -> String { + self.counters + .metrics + .values() + .filter(|metric| !metric.is_empty()) + .map(Metric::::to_prometheus) + .chain( + self.gauges + .metrics + .values() + .filter(|metric| !metric.is_empty()) + .map(Metric::::to_prometheus), + ) + .collect::>() + .join("\n") + } +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct MetricKindCollection { + metrics: HashMap>, +} + +impl MetricKindCollection { + /// Creates a new `MetricKindCollection` from a vector of metrics + /// + /// # Panics + /// + /// Panics if duplicate metric names are found + #[must_use] + pub fn new(metrics: Vec>) -> Self { + let mut map = HashMap::with_capacity(metrics.len()); + + for metric in metrics { + assert!( + map.insert(metric.name().clone(), metric).is_none(), + "Duplicate MetricName found in MetricKindCollection" + ); + } + Self { metrics: map } + } + + /// Returns an iterator over all metric names in this collection. + pub fn names(&self) -> impl Iterator { + self.metrics.keys() + } + + pub fn ensure_metric_exists(&mut self, name: &MetricName) { + if !self.metrics.contains_key(name) { + self.metrics + .insert(name.clone(), Metric::new(name.clone(), SampleCollection::new(vec![]))); + } + } +} + +impl MetricKindCollection { + /// Merges another `MetricKindCollection` into this one. + /// + /// # Errors + /// + /// Returns an error if a metric name already exists in the current collection. + pub fn merge(&mut self, other: &Self) -> Result<(), MergeError> { + // Check for name collisions + for metric_name in other.metrics.keys() { + if self.metrics.contains_key(metric_name) { + return Err(MergeError::MetricNameAlreadyExists { + metric_name: metric_name.clone(), + }); + } + } + + for (metric_name, metric) in &other.metrics { + if self.metrics.insert(metric_name.clone(), metric.clone()).is_some() { + return Err(MergeError::MetricNameAlreadyExists { + metric_name: metric_name.clone(), + }); + } + } + + Ok(()) + } +} + +impl MetricKindCollection { + /// Increments the counter for the given metric name and labels. + /// + /// If the metric name does not exist, it will be created. + /// + /// # Panics + /// + /// Panics if the metric does not exist and it could not be created. + pub fn increment(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + self.ensure_metric_exists(name); + + let metric = self.metrics.get_mut(name).expect("Counter metric should exist"); + + metric.increment(label_set, time); + } + + #[must_use] + pub fn get_value(&self, name: &MetricName, label_set: &LabelSet) -> Counter { + self.metrics + .get(name) + .and_then(|metric| metric.get_sample(label_set)) + .map_or(Counter::default(), |sample| sample.value().clone()) + } +} + +impl MetricKindCollection { + /// Sets the gauge for the given metric name and labels. + /// + /// If the metric name does not exist, it will be created. + /// + /// # Panics + /// + /// Panics if the metric does not exist and it could not be created. + pub fn set(&mut self, name: &MetricName, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { + self.ensure_metric_exists(name); + + let metric = self.metrics.get_mut(name).expect("Gauge metric should exist"); + + metric.set(label_set, value, time); + } + + #[must_use] + pub fn get_value(&self, name: &MetricName, label_set: &LabelSet) -> Gauge { + self.metrics + .get(name) + .and_then(|metric| metric.get_sample(label_set)) + .map_or(Gauge::default(), |sample| sample.value().clone()) + } +} + +#[cfg(test)] +mod tests { + + use pretty_assertions::assert_eq; + + use super::*; + use crate::label::{LabelName, LabelValue}; + use crate::sample::Sample; + use crate::tests::{format_prometheus_output, sort_lines}; + + /// Fixture for testing serialization and deserialization of `MetricCollection`. + /// + /// It contains a default `MetricCollection` object, its JSON representation, + /// and its Prometheus format representation. + struct MetricCollectionFixture { + pub object: MetricCollection, + pub json: String, + pub prometheus: String, + } + + impl Default for MetricCollectionFixture { + fn default() -> Self { + Self { + object: Self::object(), + json: Self::json(), + prometheus: Self::prometheus(), + } + } + } + + impl MetricCollectionFixture { + fn deconstruct(&self) -> (MetricCollection, String, String) { + (self.object.clone(), self.json.clone(), self.prometheus.clone()) + } + + fn object() -> MetricCollection { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + let label_set_1: LabelSet = [ + (LabelName::new("server_binding_protocol"), LabelValue::new("http")), + (LabelName::new("server_binding_ip"), LabelValue::new("0.0.0.0")), + (LabelName::new("server_binding_port"), LabelValue::new("7070")), + ] + .into(); + + MetricCollection::new( + MetricKindCollection::new(vec![Metric::new( + MetricName::new("http_tracker_core_announce_requests_received_total"), + SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set_1.clone())]), + )]), + MetricKindCollection::new(vec![Metric::new( + MetricName::new("udp_tracker_server_performance_avg_announce_processing_time_ns"), + SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set_1.clone())]), + )]), + ) + } + + fn json() -> String { + r#" + [ + { + "kind":"counter", + "name":"http_tracker_core_announce_requests_received_total", + "samples":[ + { + "value":1, + "update_at":"2025-04-02T00:00:00+00:00", + "labels":[ + { + "name":"server_binding_ip", + "value":"0.0.0.0" + }, + { + "name":"server_binding_port", + "value":"7070" + }, + { + "name":"server_binding_protocol", + "value":"http" + } + ] + } + ] + }, + { + "kind":"gauge", + "name":"udp_tracker_server_performance_avg_announce_processing_time_ns", + "samples":[ + { + "value":1.0, + "update_at":"2025-04-02T00:00:00+00:00", + "labels":[ + { + "name":"server_binding_ip", + "value":"0.0.0.0" + }, + { + "name":"server_binding_port", + "value":"7070" + }, + { + "name":"server_binding_protocol", + "value":"http" + } + ] + } + ] + } + ] + "# + .to_owned() + } + + fn prometheus() -> String { + format_prometheus_output( + r#" + http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 + udp_tracker_server_performance_avg_announce_processing_time_ns{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 + "#, + ) + } + } + + #[test] + #[should_panic(expected = "Metric names must be unique across counters and gauges")] + fn it_should_not_allow_duplicate_names_across_types() { + let counter = MetricKindCollection::new(vec![Metric::new( + MetricName::new("test_metric"), + SampleCollection::new(vec![]), + )]); + + let gauge = MetricKindCollection::new(vec![Metric::new( + MetricName::new("test_metric"), + SampleCollection::new(vec![]), + )]); + + let _unused = MetricCollection::new(counter, gauge); + } + + #[test] + #[should_panic(expected = "Cannot create gauge with name 'test_metric': a counter with this name already exists")] + fn it_should_not_allow_creating_a_gauge_with_the_same_name_as_a_counter() { + let mut collection = MetricCollection::default(); + let label_set = LabelSet::default(); + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + // First create a counter + collection.increase_counter(&MetricName::new("test_metric"), &label_set, time); + + // Then try to create a gauge with the same name - this should panic + collection.set_gauge(&MetricName::new("test_metric"), &label_set, 1.0, time); + } + + #[test] + #[should_panic(expected = "Cannot create counter with name 'test_metric': a gauge with this name already exists")] + fn it_should_not_allow_creating_a_counter_with_the_same_name_as_a_gauge() { + let mut collection = MetricCollection::default(); + let label_set = LabelSet::default(); + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + // First set the gauge + collection.set_gauge(&MetricName::new("test_metric"), &label_set, 1.0, time); + + // Then try to create a counter with the same name - this should panic + collection.increase_counter(&MetricName::new("test_metric"), &label_set, time); + } + + #[test] + fn it_should_allow_serializing_to_json() { + // todo: this test does work with metric with multiple samples becuase + // samples are not serialized in the same order as they are created. + let (metric_collection, expected_json, _expected_prometheus) = MetricCollectionFixture::default().deconstruct(); + + let json = serde_json::to_string_pretty(&metric_collection).unwrap(); + + assert_eq!( + serde_json::from_str::(&json).unwrap(), + serde_json::from_str::(&expected_json).unwrap() + ); + } + + #[test] + fn it_should_allow_deserializing_from_json() { + let (expected_metric_collection, metric_collection_json, _expected_prometheus) = + MetricCollectionFixture::default().deconstruct(); + + let metric_collection: MetricCollection = serde_json::from_str(&metric_collection_json).unwrap(); + + assert_eq!(metric_collection, expected_metric_collection); + } + + #[test] + fn it_should_allow_serializing_to_prometheus_format() { + let (metric_collection, _expected_json, expected_prometheus) = MetricCollectionFixture::default().deconstruct(); + + let prometheus_output = metric_collection.to_prometheus(); + + assert_eq!(prometheus_output, expected_prometheus); + } + + #[test] + fn it_should_allow_serializing_to_prometheus_format_with_multiple_samples_per_metric() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + let label_set_1: LabelSet = [ + (LabelName::new("server_binding_protocol"), LabelValue::new("http")), + (LabelName::new("server_binding_ip"), LabelValue::new("0.0.0.0")), + (LabelName::new("server_binding_port"), LabelValue::new("7070")), + ] + .into(); + + let label_set_2: LabelSet = [ + (LabelName::new("server_binding_protocol"), LabelValue::new("http")), + (LabelName::new("server_binding_ip"), LabelValue::new("0.0.0.0")), + (LabelName::new("server_binding_port"), LabelValue::new("7171")), + ] + .into(); + + let metric_collection = MetricCollection::new( + MetricKindCollection::new(vec![Metric::new( + MetricName::new("http_tracker_core_announce_requests_received_total"), + SampleCollection::new(vec![ + Sample::new(Counter::new(1), time, label_set_1.clone()), + Sample::new(Counter::new(2), time, label_set_2.clone()), + ]), + )]), + MetricKindCollection::new(vec![]), + ); + + let prometheus_output = metric_collection.to_prometheus(); + + let expected_prometheus_output = format_prometheus_output( + r#" + http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7171",server_binding_protocol="http"} 2 + http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 + "#, + ); + + // code-review: samples are not serialized in the same order as they are created. + // Should we use a deterministic order? + + assert_eq!(sort_lines(&prometheus_output), sort_lines(&expected_prometheus_output)); + } + + #[test] + fn it_should_exclude_metrics_without_samples_from_prometheus_format() { + let mut counters = MetricKindCollection::new(vec![]); + let mut gauges = MetricKindCollection::new(vec![]); + + counters.ensure_metric_exists(&MetricName::new("test_counter")); + gauges.ensure_metric_exists(&MetricName::new("test_gauge")); + + let metric_collection = MetricCollection::new(counters, gauges); + + let prometheus_output = metric_collection.to_prometheus(); + + assert_eq!(prometheus_output, ""); + } + + mod for_counters { + + use pretty_assertions::assert_eq; + + use super::*; + use crate::label::{LabelName, LabelValue}; + use crate::sample::Sample; + + #[test] + fn it_should_increase_a_preexistent_counter() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + + let mut metric_collection = MetricCollection::new( + MetricKindCollection::new(vec![Metric::new( + MetricName::new("test_counter"), + SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]), + )]), + MetricKindCollection::new(vec![]), + ); + + metric_collection.increase_counter(&MetricName::new("test_counter"), &label_set, time); + metric_collection.increase_counter(&MetricName::new("test_counter"), &label_set, time); + + assert_eq!( + metric_collection.get_counter_value(&MetricName::new("test_counter"), &label_set), + Counter::new(2) + ); + } + + #[test] + fn it_should_automatically_create_a_counter_when_increasing_if_it_does_not_exist() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + + let mut metric_collection = + MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); + + metric_collection.increase_counter(&MetricName::new("test_counter"), &label_set, time); + metric_collection.increase_counter(&MetricName::new("test_counter"), &label_set, time); + + assert_eq!( + metric_collection.get_counter_value(&MetricName::new("test_counter"), &label_set), + Counter::new(2) + ); + } + + #[test] + fn it_should_allow_making_sure_a_counter_exists_without_increasing_it() { + let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + + let mut metric_collection = + MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); + + metric_collection.ensure_counter_exists(&MetricName::new("test_counter")); + + assert_eq!( + metric_collection.get_counter_value(&MetricName::new("test_counter"), &label_set), + Counter::default() + ); + } + + #[test] + fn it_should_allow_describing_a_counter_before_using_it() { + let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + + let mut metric_collection = + MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); + + metric_collection.describe_counter(&MetricName::new("test_counter"), None, None); + + assert_eq!( + metric_collection.get_counter_value(&MetricName::new("test_counter"), &label_set), + Counter::default() + ); + } + + #[test] + #[should_panic(expected = "Duplicate MetricName found in MetricKindCollection")] + fn it_should_not_allow_duplicate_metric_names_when_instantiating() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + + let _unused = MetricKindCollection::new(vec![ + Metric::new( + MetricName::new("test_counter"), + SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]), + ), + Metric::new( + MetricName::new("test_counter"), + SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]), + ), + ]); + } + } + + mod for_gauges { + + use pretty_assertions::assert_eq; + + use super::*; + use crate::label::{LabelName, LabelValue}; + use crate::sample::Sample; + + #[test] + fn it_should_set_a_preexistent_gauge() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + + let mut metric_collection = MetricCollection::new( + MetricKindCollection::new(vec![]), + MetricKindCollection::new(vec![Metric::new( + MetricName::new("test_gauge"), + SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]), + )]), + ); + + metric_collection.set_gauge(&MetricName::new("test_gauge"), &label_set, 1.0, time); + + assert_eq!( + metric_collection.get_gauge_value(&MetricName::new("test_gauge"), &label_set), + Gauge::new(1.0) + ); + } + + #[test] + fn it_should_automatically_create_a_gauge_when_setting_if_it_does_not_exist() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + + let mut metric_collection = + MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); + + metric_collection.set_gauge(&MetricName::new("test_gauge"), &label_set, 1.0, time); + + assert_eq!( + metric_collection.get_gauge_value(&MetricName::new("test_gauge"), &label_set), + Gauge::new(1.0) + ); + } + + #[test] + fn it_should_allow_making_sure_a_gauge_exists_without_increasing_it() { + let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + + let mut metric_collection = + MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); + + metric_collection.ensure_gauge_exists(&MetricName::new("test_gauge")); + + assert_eq!( + metric_collection.get_gauge_value(&MetricName::new("test_gauge"), &label_set), + Gauge::default() + ); + } + + #[test] + fn it_should_allow_describing_a_gauge_before_using_it() { + let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + + let mut metric_collection = + MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); + + metric_collection.describe_gauge(&MetricName::new("test_gauge"), None, None); + + assert_eq!( + metric_collection.get_gauge_value(&MetricName::new("test_gauge"), &label_set), + Gauge::default() + ); + } + + #[test] + #[should_panic(expected = "Duplicate MetricName found in MetricKindCollection")] + fn it_should_not_allow_duplicate_metric_names_when_instantiating() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + + let _unused = MetricKindCollection::new(vec![ + Metric::new( + MetricName::new("test_gauge"), + SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]), + ), + Metric::new( + MetricName::new("test_gauge"), + SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]), + ), + ]); + } + } +} diff --git a/packages/metrics/src/prometheus.rs b/packages/metrics/src/prometheus.rs new file mode 100644 index 000000000..bf058e442 --- /dev/null +++ b/packages/metrics/src/prometheus.rs @@ -0,0 +1,15 @@ +pub trait PrometheusSerializable { + /// Convert the implementing type into a Prometheus exposition format string. + /// + /// # Returns + /// + /// A `String` containing the serialized representation. + fn to_prometheus(&self) -> String; +} + +// Blanket implementation for references +impl PrometheusSerializable for &T { + fn to_prometheus(&self) -> String { + (*self).to_prometheus() + } +} diff --git a/packages/metrics/src/sample.rs b/packages/metrics/src/sample.rs new file mode 100644 index 000000000..eddb2eefc --- /dev/null +++ b/packages/metrics/src/sample.rs @@ -0,0 +1,355 @@ +use chrono::{DateTime, Utc}; +use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::counter::Counter; +use super::gauge::Gauge; +use super::label::LabelSet; +use super::prometheus::PrometheusSerializable; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Sample { + value: T, + + #[serde(serialize_with = "serialize_duration", deserialize_with = "deserialize_duration")] + update_at: DurationSinceUnixEpoch, + + #[serde(rename = "labels")] + label_set: LabelSet, +} + +impl Sample { + #[must_use] + pub fn new(value: T, update_at: DurationSinceUnixEpoch, label_set: LabelSet) -> Self { + Self { + value, + update_at, + label_set, + } + } + + #[must_use] + pub fn labels(&self) -> &LabelSet { + &self.label_set + } + + #[must_use] + pub fn value(&self) -> &T { + &self.value + } + + #[must_use] + pub fn update_at(&self) -> DurationSinceUnixEpoch { + self.update_at + } + + fn set_update_at(&mut self, time: DurationSinceUnixEpoch) { + self.update_at = time; + } +} + +impl PrometheusSerializable for Sample { + fn to_prometheus(&self) -> String { + format!("{} {}", self.label_set.to_prometheus(), self.value.to_prometheus()) + } +} + +impl Sample { + pub fn increment(&mut self, time: DurationSinceUnixEpoch) { + self.value.increment(1); + self.set_update_at(time); + } +} + +impl Sample { + pub fn set(&mut self, value: f64, time: DurationSinceUnixEpoch) { + self.value.set(value); + self.set_update_at(time); + } +} + +/// Serializes the `update_at` field as a string in ISO 8601 format (RFC 3339). +/// +/// # Errors +/// +/// Returns an error if: +/// - The conversion from `u64` to `i64` fails. +/// - The timestamp is invalid. +fn serialize_duration(duration: &DurationSinceUnixEpoch, serializer: S) -> Result +where + S: Serializer, +{ + let secs = i64::try_from(duration.as_secs()).map_err(|_| serde::ser::Error::custom("Timestamp too large"))?; + let nanos = duration.subsec_nanos(); + + let datetime = DateTime::from_timestamp(secs, nanos).ok_or_else(|| serde::ser::Error::custom("Invalid timestamp"))?; + + serializer.serialize_str(&datetime.to_rfc3339()) // Serializes as ISO 8601 (RFC 3339) +} + +fn deserialize_duration<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + // Deserialize theISO 8601 (RFC 3339) formatted string + let datetime_str = String::deserialize(deserializer)?; + + let datetime = + DateTime::parse_from_rfc3339(&datetime_str).map_err(|e| de::Error::custom(format!("Invalid datetime format: {e}")))?; + + let datetime_utc = datetime.with_timezone(&Utc); + + let secs = u64::try_from(datetime_utc.timestamp()).map_err(|_| de::Error::custom("Timestamp out of range"))?; + + Ok(DurationSinceUnixEpoch::new(secs, datetime_utc.timestamp_subsec_nanos())) +} + +#[cfg(test)] +mod tests { + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use super::*; + + // Helper function to create a sample update time. + fn updated_at_time() -> DurationSinceUnixEpoch { + DurationSinceUnixEpoch::from_secs(1_743_552_000) + } + + #[test] + fn it_should_have_a_value() { + let sample = Sample::new( + 42, + DurationSinceUnixEpoch::from_secs(1_743_552_000), + LabelSet::from(vec![("test", "label")]), + ); + + assert_eq!(sample.value(), &42); + } + + #[test] + fn it_should_record_the_latest_update_time() { + let sample = Sample::new( + 42, + DurationSinceUnixEpoch::from_secs(1_743_552_000), + LabelSet::from(vec![("test", "label")]), + ); + + assert_eq!(sample.update_at(), updated_at_time()); + } + + #[test] + fn it_should_include_a_label_set() { + let sample = Sample::new( + 42, + DurationSinceUnixEpoch::from_secs(1_743_552_000), + LabelSet::from(vec![("test", "label")]), + ); + + assert_eq!(sample.labels(), &LabelSet::from(vec![("test", "label")])); + } + + mod for_counter_type_sample { + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::label::LabelSet; + use crate::prometheus::PrometheusSerializable; + use crate::sample::tests::updated_at_time; + use crate::sample::{Counter, Sample}; + + #[test] + fn it_should_allow_a_counter_type_value() { + let sample = Sample::new( + Counter::new(42), + DurationSinceUnixEpoch::from_secs(1_743_552_000), + LabelSet::from(vec![("label_name", "label vale")]), + ); + + assert_eq!(sample.value(), &Counter::new(42)); + } + + #[test] + fn it_should_allow_incrementing_the_counter() { + let mut sample = Sample::new(Counter::default(), DurationSinceUnixEpoch::default(), LabelSet::default()); + + sample.increment(updated_at_time()); + + assert_eq!(sample.value(), &Counter::new(1)); + } + + #[test] + fn it_should_record_the_latest_update_time_when_the_counter_is_incremented() { + let mut sample = Sample::new(Counter::default(), DurationSinceUnixEpoch::default(), LabelSet::default()); + + let time = updated_at_time(); + + sample.increment(time); + + assert_eq!(sample.update_at(), time); + } + + #[test] + fn it_should_allow_exporting_to_prometheus_format() { + let counter = Counter::new(42); + + let labels = LabelSet::from(vec![("label_name", "label_value"), ("method", "GET")]); + + let sample = Sample::new(counter, DurationSinceUnixEpoch::default(), labels); + + assert_eq!(sample.to_prometheus(), r#"{label_name="label_value",method="GET"} 42"#); + } + } + mod for_gauge_type_sample { + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::label::LabelSet; + use crate::prometheus::PrometheusSerializable; + use crate::sample::tests::updated_at_time; + use crate::sample::{Gauge, Sample}; + + #[test] + fn it_should_allow_a_counter_type_value() { + let sample = Sample::new( + Gauge::new(42.0), + DurationSinceUnixEpoch::from_secs(1_743_552_000), + LabelSet::from(vec![("label_name", "label vale")]), + ); + + assert_eq!(sample.value(), &Gauge::new(42.0)); + } + + #[test] + fn it_should_allow_incrementing_the_counter() { + let mut sample = Sample::new(Gauge::default(), DurationSinceUnixEpoch::default(), LabelSet::default()); + + sample.set(1.0, updated_at_time()); + + assert_eq!(sample.value(), &Gauge::new(1.0)); + } + + #[test] + fn it_should_record_the_latest_update_time_when_the_counter_is_incremented() { + let mut sample = Sample::new(Gauge::default(), DurationSinceUnixEpoch::default(), LabelSet::default()); + + let time = updated_at_time(); + + sample.set(1.0, time); + + assert_eq!(sample.update_at(), time); + } + + #[test] + fn it_should_allow_exporting_to_prometheus_format() { + let counter = Gauge::new(42.0); + + let labels = LabelSet::from(vec![("label_name", "label_value"), ("method", "GET")]); + + let sample = Sample::new(counter, DurationSinceUnixEpoch::default(), labels); + + assert_eq!(sample.to_prometheus(), r#"{label_name="label_value",method="GET"} 42"#); + } + } + + mod serialization_to_json { + use pretty_assertions::assert_eq; + use serde_json::json; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::label::LabelSet; + use crate::sample::tests::updated_at_time; + use crate::sample::Sample; + + #[test] + fn test_serialization_round_trip() { + let original = Sample { + value: 42, + update_at: updated_at_time(), + label_set: LabelSet::from(vec![("test", "serialization")]), + }; + + let json = serde_json::to_string(&original).unwrap(); + let deserialized: Sample = serde_json::from_str(&json).unwrap(); + + assert_eq!(original.value, deserialized.value); + assert_eq!(original.update_at, deserialized.update_at); + assert_eq!(original.label_set, deserialized.label_set); + } + + #[test] + fn test_rfc3339_serialization_format_for_update_time() { + let sample = Sample::new( + 42, + DurationSinceUnixEpoch::new(1_743_552_000, 100), + LabelSet::from(vec![("label_name", "label value")]), + ); + + let json = serde_json::to_string(&sample).unwrap(); + + let expected_json = r#" + { + "value": 42, + "update_at": "2025-04-02T00:00:00.000000100+00:00", + "labels": [ + { + "name": "label_name", + "value": "label value" + } + ] + } + "#; + + assert_eq!( + serde_json::from_str::(&json).unwrap(), + serde_json::from_str::(expected_json).unwrap() + ); + } + + #[test] + fn test_invalid_update_timestamp_serialization() { + let timestamp_too_large = DurationSinceUnixEpoch::new(i64::MAX as u64 + 1, 0); + + let sample = Sample::new(42, timestamp_too_large, LabelSet::from(vec![("label_name", "label value")])); + + let result = serde_json::to_string(&sample); + + assert!(result.is_err()); + assert!(result.unwrap_err().to_string().contains("Timestamp too large")); + } + + #[test] + fn test_invalid_update_datetime_deserialization() { + let invalid_json = json!( + r#" + { + "value": 42, + "update_at": "1-1-2023T25:00:00Z", + "labels": [ + { + "name": "label_name", + "value": "label value" + } + ] + } + "# + ); + + let result: Result = serde_json::from_value(invalid_json); + + assert!(result.unwrap_err().to_string().contains("invalid type")); + } + + #[test] + fn test_update_datetime_high_precision_nanoseconds() { + let sample = Sample::new( + 42, + DurationSinceUnixEpoch::new(1_743_552_000, 100), + LabelSet::from(vec![("label_name", "label value")]), + ); + + let json = serde_json::to_string(&sample).unwrap(); + + let deserialized: Sample = serde_json::from_str(&json).unwrap(); + + assert_eq!(deserialized, sample); + } + } +} diff --git a/packages/metrics/src/sample_collection.rs b/packages/metrics/src/sample_collection.rs new file mode 100644 index 000000000..02977597f --- /dev/null +++ b/packages/metrics/src/sample_collection.rs @@ -0,0 +1,411 @@ +use std::collections::hash_map::Iter; +use std::collections::{HashMap, HashSet}; + +use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::counter::Counter; +use super::gauge::Gauge; +use super::label::LabelSet; +use super::prometheus::PrometheusSerializable; +use super::sample::Sample; + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct SampleCollection { + samples: HashMap>, +} + +impl SampleCollection { + // IMPORTANT: It should never allow mutation of the samples because it would + // break the invariants. If the sample's `LabelSet` is changed, it can + // create duplicate `LabelSet`s even if the `LabelSet` in the `HashMap` key + // is unique. + + /// # Panics + /// + /// Panics if there are duplicate `LabelSets` in the provided samples. + #[must_use] + pub fn new(samples: Vec>) -> Self { + let mut map = HashMap::with_capacity(samples.len()); + + for sample in samples { + assert!( + map.insert(sample.labels().clone(), sample).is_none(), + "Duplicate LabelSet found in SampleCollection" + ); + } + + Self { samples: map } + } + + #[must_use] + pub fn get(&self, label: &LabelSet) -> Option<&Sample> { + self.samples.get(label) + } + + #[must_use] + pub fn len(&self) -> usize { + self.samples.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.samples.is_empty() + } + + #[must_use] + #[allow(clippy::iter_without_into_iter)] + pub fn iter(&self) -> Iter<'_, LabelSet, Sample> { + self.samples.iter() + } +} + +impl SampleCollection { + pub fn increment(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + let sample = self + .samples + .entry(label_set.clone()) + .or_insert_with(|| Sample::new(Counter::default(), time, label_set.clone())); + + sample.increment(time); + } +} + +impl SampleCollection { + pub fn set(&mut self, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { + let sample = self + .samples + .entry(label_set.clone()) + .or_insert_with(|| Sample::new(Gauge::default(), time, label_set.clone())); + + sample.set(value, time); + } +} + +impl Serialize for SampleCollection { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let samples: Vec<&Sample> = self.samples.values().collect(); + samples.serialize(serializer) + } +} + +impl<'de, T> Deserialize<'de> for SampleCollection +where + T: Deserialize<'de>, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + // First deserialize into a temporary Vec + let samples = Vec::>::deserialize(deserializer)?; + + // Check for duplicate label sets + let mut seen_labels = HashSet::new(); + + for sample in &samples { + if !seen_labels.insert(sample.labels()) { + return Err(de::Error::custom(format!("Duplicate label set found: {}", sample.labels()))); + } + } + + // Convert to HashMap-based storage + Ok(SampleCollection::new(samples)) + } +} + +impl PrometheusSerializable for SampleCollection { + fn to_prometheus(&self) -> String { + let mut output = String::new(); + + for sample in self.samples.values() { + output.push_str(&sample.to_prometheus()); + } + + output + } +} + +#[cfg(test)] +mod tests { + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::counter::Counter; + use crate::label::LabelSet; + use crate::prometheus::PrometheusSerializable; + use crate::sample::Sample; + use crate::sample_collection::SampleCollection; + use crate::tests::format_prometheus_output; + + fn sample_update_time() -> DurationSinceUnixEpoch { + DurationSinceUnixEpoch::from_secs(1_743_552_000) + } + + #[test] + #[should_panic(expected = "Duplicate LabelSet found in SampleCollection")] + fn it_should_fail_trying_to_create_a_sample_collection_with_duplicate_label_sets() { + let samples = vec![ + Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), + Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), + ]; + + let _unused = SampleCollection::new(samples); + } + + #[test] + fn it_should_return_a_sample_searching_by_label_set_with_one_empty_label_set() { + let label_set = LabelSet::default(); + + let sample = Sample::new(Counter::default(), sample_update_time(), label_set.clone()); + + let collection = SampleCollection::new(vec![sample.clone()]); + + let retrieved = collection.get(&label_set); + + assert_eq!(retrieved.unwrap(), &sample); + } + + #[test] + fn it_should_return_a_sample_searching_by_label_set_with_two_label_sets() { + let label_set_1 = LabelSet::from(vec![("label_name_1", "label value 1")]); + let label_set_2 = LabelSet::from(vec![("label_name_2", "label value 2")]); + + let sample_1 = Sample::new(Counter::new(1), sample_update_time(), label_set_1.clone()); + let sample_2 = Sample::new(Counter::new(2), sample_update_time(), label_set_2.clone()); + + let collection = SampleCollection::new(vec![sample_1.clone(), sample_2.clone()]); + + let retrieved = collection.get(&label_set_1); + assert_eq!(retrieved.unwrap(), &sample_1); + + let retrieved = collection.get(&label_set_2); + assert_eq!(retrieved.unwrap(), &sample_2); + } + + #[test] + fn it_should_return_the_number_of_samples_in_the_collection() { + let samples = vec![Sample::new(Counter::default(), sample_update_time(), LabelSet::default())]; + let collection = SampleCollection::new(samples); + assert_eq!(collection.len(), 1); + } + + #[test] + fn it_should_return_zero_number_of_samples_when_empty() { + let empty = SampleCollection::::default(); + assert_eq!(empty.len(), 0); + } + + #[test] + fn it_should_indicate_is_it_is_empty() { + let empty = SampleCollection::::default(); + assert!(empty.is_empty()); + + let samples = vec![Sample::new(Counter::default(), sample_update_time(), LabelSet::default())]; + let collection = SampleCollection::new(samples); + assert!(!collection.is_empty()); + } + + #[test] + fn it_should_be_serializable_and_deserializable_for_json_format() { + let sample = Sample::new(Counter::default(), sample_update_time(), LabelSet::default()); + let collection = SampleCollection::new(vec![sample]); + + let serialized = serde_json::to_string(&collection).unwrap(); + let deserialized: SampleCollection = serde_json::from_str(&serialized).unwrap(); + + assert_eq!(deserialized, collection); + } + + #[test] + fn it_should_fail_deserializing_from_json_with_duplicate_label_sets() { + let samples = vec![ + Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), + Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), + ]; + + let serialized = serde_json::to_string(&samples).unwrap(); + + let result: Result, _> = serde_json::from_str(&serialized); + + assert!(result.is_err()); + } + + #[test] + fn it_should_be_exportable_to_prometheus_format_when_empty() { + let sample = Sample::new(Counter::default(), sample_update_time(), LabelSet::default()); + let collection = SampleCollection::new(vec![sample]); + + let prometheus_output = collection.to_prometheus(); + + assert!(!prometheus_output.is_empty()); + } + + #[test] + fn it_should_be_exportable_to_prometheus_format() { + let sample = Sample::new( + Counter::new(1), + sample_update_time(), + LabelSet::from(vec![("labe_name_1", "label value value 1")]), + ); + + let collection = SampleCollection::new(vec![sample]); + + let prometheus_output = collection.to_prometheus(); + + let expected_prometheus_output = format_prometheus_output("{labe_name_1=\"label value value 1\"} 1"); + + assert_eq!(prometheus_output, expected_prometheus_output); + } + + #[cfg(test)] + mod for_counters { + + use std::ops::Add; + + use super::super::LabelSet; + use super::*; + + #[test] + fn it_should_increment_the_counter_for_a_preexisting_label_set() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::default(); + + // Initialize the sample + collection.increment(&label_set, sample_update_time()); + + // Verify initial state + let sample = collection.get(&label_set).unwrap(); + assert_eq!(sample.value(), &Counter::new(1)); + + // Increment again + collection.increment(&label_set, sample_update_time()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Counter::new(2)); + } + + #[test] + fn it_should_allow_increment_the_counter_for_a_non_existent_label_set() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::default(); + + // Increment a non-existent label + collection.increment(&label_set, sample_update_time()); + + // Verify the label exists + assert!(collection.get(&label_set).is_some()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Counter::new(1)); + } + + #[test] + fn it_should_update_the_latest_update_time_when_incremented() { + let label_set = LabelSet::default(); + let initial_time = sample_update_time(); + + let mut collection = SampleCollection::default(); + collection.increment(&label_set, initial_time); + + // Increment with a new time + let new_time = initial_time.add(DurationSinceUnixEpoch::from_secs(1)); + collection.increment(&label_set, new_time); + + let sample = collection.get(&label_set).unwrap(); + assert_eq!(sample.update_at(), new_time); + assert_eq!(*sample.value(), Counter::new(2)); + } + + #[test] + fn it_should_increment_the_counter_for_multiple_labels() { + let label1 = LabelSet::from([("name", "value1")]); + let label2 = LabelSet::from([("name", "value2")]); + let now = sample_update_time(); + + let mut collection = SampleCollection::default(); + + collection.increment(&label1, now); + collection.increment(&label2, now); + + assert_eq!(collection.get(&label1).unwrap().value(), &Counter::new(1)); + assert_eq!(collection.get(&label2).unwrap().value(), &Counter::new(1)); + assert_eq!(collection.len(), 2); + } + } + + #[cfg(test)] + mod for_gauges { + + use std::ops::Add; + + use super::super::LabelSet; + use super::*; + use crate::gauge::Gauge; + + #[test] + fn it_should_increment_the_gauge_for_a_preexisting_label_set() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::default(); + + // Initialize the sample + collection.set(&label_set, 1.0, sample_update_time()); + + // Verify initial state + let sample = collection.get(&label_set).unwrap(); + assert_eq!(sample.value(), &Gauge::new(1.0)); + + // Set again + collection.set(&label_set, 2.0, sample_update_time()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Gauge::new(2.0)); + } + + #[test] + fn it_should_allow_increment_the_gauge_for_a_non_existent_label_set() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::default(); + + // Set a non-existent label + collection.set(&label_set, 1.0, sample_update_time()); + + // Verify the label exists + assert!(collection.get(&label_set).is_some()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Gauge::new(1.0)); + } + + #[test] + fn it_should_update_the_latest_update_time_when_incremented() { + let label_set = LabelSet::default(); + let initial_time = sample_update_time(); + + let mut collection = SampleCollection::default(); + collection.set(&label_set, 1.0, initial_time); + + // Set with a new time + let new_time = initial_time.add(DurationSinceUnixEpoch::from_secs(1)); + collection.set(&label_set, 2.0, new_time); + + let sample = collection.get(&label_set).unwrap(); + assert_eq!(sample.update_at(), new_time); + assert_eq!(*sample.value(), Gauge::new(2.0)); + } + + #[test] + fn it_should_increment_the_gauge_for_multiple_labels() { + let label1 = LabelSet::from([("name", "value1")]); + let label2 = LabelSet::from([("name", "value2")]); + let now = sample_update_time(); + + let mut collection = SampleCollection::default(); + + collection.set(&label1, 1.0, now); + collection.set(&label2, 2.0, now); + + assert_eq!(collection.get(&label1).unwrap().value(), &Gauge::new(1.0)); + assert_eq!(collection.get(&label2).unwrap().value(), &Gauge::new(2.0)); + assert_eq!(collection.len(), 2); + } + } +} diff --git a/packages/metrics/src/thread_safe_metric_collection.rs b/packages/metrics/src/thread_safe_metric_collection.rs new file mode 100644 index 000000000..d9774c9af --- /dev/null +++ b/packages/metrics/src/thread_safe_metric_collection.rs @@ -0,0 +1,92 @@ +use std::sync::RwLock; + +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::counter::Counter; +use crate::gauge::Gauge; +use crate::label::LabelSet; +use crate::metric::description::MetricDescription; +use crate::metric::MetricName; +use crate::metric_collection::{MetricCollection, MetricKindCollection}; +use crate::unit::Unit; + +/* code-review: + + This might be not necessary, since the `MetricCollection` doesn't expose + any method to mutate the collection items directly. + +*/ + +/// A thread-safe wrapper around `MetricCollection` that allows concurrent +/// access to the metrics collection. +/// +/// It protects the `MetricCollection` invariant: +/// +/// "Metric's names must be unique in the collection for all types of metrics." +#[derive(Debug, Default)] +pub struct ThreadSafeMetricCollection { + inner: RwLock, +} + +impl ThreadSafeMetricCollection { + #[must_use] + pub fn new(counters: MetricKindCollection, gauges: MetricKindCollection) -> Self { + Self { + inner: RwLock::new(MetricCollection::new(counters, gauges)), + } + } + + // Counter-specific methods + + /// # Panics + /// + /// Panics if it can't get write access to the inner collection. + pub fn describe_counter(&mut self, name: &MetricName, _opt_unit: Option, _opt_description: Option) { + self.inner.write().unwrap().ensure_counter_exists(name); + } + + /// It allows to describe a counter metric so the metrics appear in the JSON + /// response even if there are no samples yet. + /// + /// # Panics + /// + /// Panics if it can't get read access to the inner collection. + #[must_use] + pub fn get_counter_value(&self, name: &MetricName, label_set: &LabelSet) -> Counter { + self.inner.read().unwrap().get_counter_value(name, label_set) + } + + /// # Panics + /// + /// Panics if it can't get write access to the inner collection. + pub fn increase_counter(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + self.inner.write().unwrap().increase_counter(name, label_set, time); + } + + // Gauge-specific methods + + /// It allows to describe a gauge metric so the metrics appear in the JSON + /// response even if there are no samples yet. + /// + /// # Panics + /// + /// Panics if it can't get write access to the inner collection. + pub fn describe_gauge(&mut self, name: &MetricName, _opt_unit: Option, _opt_description: Option) { + self.inner.write().unwrap().ensure_gauge_exists(name); + } + + /// # Panics + /// + /// Panics if it can't get read access to the inner collection. + #[must_use] + pub fn get_gauge_value(&self, name: &MetricName, label_set: &LabelSet) -> Gauge { + self.inner.read().unwrap().get_gauge_value(name, label_set) + } + + /// # Panics + /// + /// Panics if it can't get write access to the inner collection. + pub fn set_gauge(&mut self, name: &MetricName, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { + self.inner.write().unwrap().set_gauge(name, label_set, value, time); + } +} diff --git a/packages/metrics/src/unit.rs b/packages/metrics/src/unit.rs new file mode 100644 index 000000000..b98e6836d --- /dev/null +++ b/packages/metrics/src/unit.rs @@ -0,0 +1,25 @@ +//! This module defines the `Unit` enum, which represents various units of +//! measurement. +//! +//! The `Unit` enum is used to specify the unit of measurement for metrics. +//! +//! They were copied from the `metrics` crate, to allow future compatibility. +pub enum Unit { + Count, + Percent, + Seconds, + Milliseconds, + Microseconds, + Nanoseconds, + Tebibytes, + Gibibytes, + Mebibytes, + Kibibytes, + Bytes, + TerabitsPerSecond, + GigabitsPerSecond, + MegabitsPerSecond, + KilobitsPerSecond, + BitsPerSecond, + CountPerSecond, +} From d7178180dedb65318ec88429beb3b7c684d2ee6d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 8 Apr 2025 18:10:59 +0100 Subject: [PATCH 0933/1297] feat: [#1403] add extendable-labeled metrics to http-tracker-core and expose in REST API **URL:** http://0.0.0.0:1212/api/v1/metrics?token=MyAccessToken **Sample response:** ```json { "metrics":[ { "kind":"counter", "name":"http_tracker_core_announce_requests_received_total", "samples":[ { "value":1, "update_at":"2025-04-02T00:00:00+00:00", "labels":[ { "name":"server_binding_ip", "value":"0.0.0.0" }, { "name":"server_binding_port", "value":"7070" }, { "name":"server_binding_protocol", "value":"http" } ] } ] }, { "kind":"gauge", "name":"udp_tracker_server_performance_avg_announce_processing_time_ns", "samples":[ { "value":1.0, "update_at":"2025-04-02T00:00:00+00:00", "labels":[ { "name":"server_binding_ip", "value":"0.0.0.0" }, { "name":"server_binding_port", "value":"7070" }, { "name":"server_binding_protocol", "value":"http" } ] } ] } ] } ``` **URL:** http://0.0.0.0:1212/api/v1/stats?token=MyAccessToken&format=prometheus ``` http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 udp_tracker_server_performance_avg_announce_processing_time_ns{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 ``` --- Cargo.lock | 169 ++++++++++++++++++ .../axum-rest-tracker-api-server/Cargo.toml | 1 + .../src/v1/context/stats/handlers.rs | 33 +++- .../src/v1/context/stats/resources.rs | 18 +- .../src/v1/context/stats/responses.rs | 16 +- .../src/v1/context/stats/routes.rs | 30 ++-- packages/http-tracker-core/Cargo.toml | 6 +- packages/http-tracker-core/src/event/mod.rs | 20 +++ packages/http-tracker-core/src/lib.rs | 13 ++ .../src/statistics/event/handler.rs | 68 +++++-- .../src/statistics/event/listener.rs | 4 +- .../src/statistics/metrics.rs | 28 ++- .../http-tracker-core/src/statistics/mod.rs | 24 +++ .../src/statistics/repository.rs | 16 +- .../src/statistics/services.rs | 6 +- packages/rest-tracker-api-core/Cargo.toml | 1 + .../src/statistics/services.rs | 25 +++ 17 files changed, 432 insertions(+), 46 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 328e2db93..fdba742dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -135,6 +135,15 @@ version = "1.0.97" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + [[package]] name = "aquatic_peer_id" version = "0.9.0" @@ -484,6 +493,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "backtrace-ext" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "537beee3be4a18fb023b570f80e3ae28003db9167a751266b259926e25539d50" +dependencies = [ + "backtrace", +] + [[package]] name = "base64" version = "0.21.7" @@ -560,11 +578,16 @@ dependencies = [ "bittorrent-primitives", "bittorrent-tracker-core", "criterion", + "formatjson", "futures", "mockall", + "serde", + "serde_json", "thiserror 2.0.12", "tokio", + "torrust-tracker-clock", "torrust-tracker-configuration", + "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", "tracing", @@ -1348,6 +1371,12 @@ dependencies = [ "syn 2.0.100", ] +[[package]] +name = "diff" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" + [[package]] name = "digest" version = "0.10.7" @@ -1558,6 +1587,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "formatjson" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d3ba17cfe2aff8969f35b2bffec13b34756c51ea53eadcc5d5446f71370e2ed" +dependencies = [ + "miette", + "thiserror 1.0.69", +] + [[package]] name = "forwarded-header-value" version = "0.1.1" @@ -2295,6 +2334,12 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "is_ci" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7655c9839580ee829dfacba1d1278c2b7883e50a277ff7541299489d6bdfdc45" + [[package]] name = "is_terminal_polyfill" version = "1.70.1" @@ -2484,6 +2529,37 @@ version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" +[[package]] +name = "miette" +version = "7.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a955165f87b37fd1862df2a59547ac542c77ef6d17c666f619d1ad22dd89484" +dependencies = [ + "backtrace", + "backtrace-ext", + "cfg-if", + "miette-derive", + "owo-colors", + "supports-color", + "supports-hyperlinks", + "supports-unicode", + "terminal_size", + "textwrap", + "thiserror 1.0.69", + "unicode-width 0.1.14", +] + +[[package]] +name = "miette-derive" +version = "7.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf45bf44ab49be92fd1227a3be6fc6f617f1a337c06af54981048574d8783147" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.100", +] + [[package]] name = "mime" version = "0.3.17" @@ -2815,6 +2891,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" +[[package]] +name = "owo-colors" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1036865bb9422d3300cf723f657c2851d0e9ab12567854b1f4eba3d77decf564" + [[package]] name = "parking" version = "2.2.1" @@ -3065,6 +3147,16 @@ dependencies = [ "termtree", ] +[[package]] +name = "pretty_assertions" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" +dependencies = [ + "diff", + "yansi", +] + [[package]] name = "proc-macro-crate" version = "3.3.0" @@ -3976,6 +4068,27 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "supports-color" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c64fc7232dd8d2e4ac5ce4ef302b1d81e0b80d055b9d77c7c4f51f6aa4c867d6" +dependencies = [ + "is_ci", +] + +[[package]] +name = "supports-hyperlinks" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "804f44ed3c63152de6a9f90acbea1a110441de43006ea51bcce8f436196a288b" + +[[package]] +name = "supports-unicode" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7401a30af6cb5818bb64852270bb722533397edcfc7344954a38f420819ece2" + [[package]] name = "syn" version = "1.0.109" @@ -4084,6 +4197,16 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "terminal_size" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45c6481c4829e4cc63825e62c49186a34538b7b2750b73b266581ffb612fb5ed" +dependencies = [ + "rustix 1.0.3", + "windows-sys 0.59.0", +] + [[package]] name = "termtree" version = "0.5.1" @@ -4119,6 +4242,16 @@ dependencies = [ "url", ] +[[package]] +name = "textwrap" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057" +dependencies = [ + "unicode-linebreak", + "unicode-width 0.2.0", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -4450,6 +4583,7 @@ dependencies = [ "torrust-server-lib", "torrust-tracker-clock", "torrust-tracker-configuration", + "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-udp-tracker-server", @@ -4501,6 +4635,7 @@ dependencies = [ "bittorrent-udp-tracker-core", "tokio", "torrust-tracker-configuration", + "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-udp-tracker-server", @@ -4626,6 +4761,22 @@ dependencies = [ "tracing", ] +[[package]] +name = "torrust-tracker-metrics" +version = "3.0.0-develop" +dependencies = [ + "approx", + "chrono", + "derive_more", + "formatjson", + "pretty_assertions", + "rstest", + "serde", + "serde_json", + "thiserror 2.0.12", + "torrust-tracker-primitives", +] + [[package]] name = "torrust-tracker-primitives" version = "3.0.0-develop" @@ -4862,6 +5013,24 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unicode-width" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" + [[package]] name = "unicode-xid" version = "0.2.6" diff --git a/packages/axum-rest-tracker-api-server/Cargo.toml b/packages/axum-rest-tracker-api-server/Cargo.toml index 42fe68584..d1491c96e 100644 --- a/packages/axum-rest-tracker-api-server/Cargo.toml +++ b/packages/axum-rest-tracker-api-server/Cargo.toml @@ -37,6 +37,7 @@ torrust-rest-tracker-api-core = { version = "3.0.0-develop", path = "../rest-tra torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } tower = { version = "0", features = ["timeout"] } diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs index 484c12ff9..26c812037 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs @@ -9,9 +9,9 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use bittorrent_udp_tracker_core::services::banning::BanService; use serde::Deserialize; use tokio::sync::RwLock; -use torrust_rest_tracker_api_core::statistics::services::get_metrics; +use torrust_rest_tracker_api_core::statistics::services::{get_labeled_metrics, get_metrics}; -use super::responses::{metrics_response, stats_response}; +use super::responses::{labeled_metrics_response, labeled_stats_response, metrics_response, stats_response}; #[derive(Deserialize, Debug, Default)] #[serde(rename_all = "lowercase")] @@ -28,7 +28,7 @@ pub struct QueryParams { pub format: Option, } -/// It handles the request to get the tracker statistics. +/// It handles the request to get the tracker global metrics. /// /// By default it returns a `200` response with the stats in JSON format. /// @@ -57,3 +57,30 @@ pub async fn get_stats_handler( None => stats_response(metrics), } } + +/// It handles the request to get the tracker extendable metrics. +/// +/// By default it returns a `200` response with the stats in JSON format. +/// +/// You can add the GET parameter `format=prometheus` to get the stats in +/// Prometheus Text Exposition Format. +#[allow(clippy::type_complexity)] +pub async fn get_metrics_handler( + State(state): State<( + Arc, + Arc>, + Arc, + Arc, + )>, + params: Query, +) -> Response { + let metrics = get_labeled_metrics(state.0.clone(), state.1.clone(), state.2.clone(), state.3.clone()).await; + + match params.0.format { + Some(format) => match format { + Format::Json => labeled_stats_response(metrics), + Format::Prometheus => labeled_metrics_response(&metrics), + }, + None => labeled_stats_response(metrics), + } +} diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs index d9480259e..8fcfd1be0 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs @@ -1,7 +1,8 @@ //! API resources for the [`stats`](crate::v1::context::stats) //! API context. use serde::{Deserialize, Serialize}; -use torrust_rest_tracker_api_core::statistics::services::TrackerMetrics; +use torrust_rest_tracker_api_core::statistics::services::{TrackerLabeledMetrics, TrackerMetrics}; +use torrust_tracker_metrics::metric_collection::MetricCollection; /// It contains all the statistics generated by the tracker. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] @@ -116,6 +117,21 @@ impl From for Stats { } } +/// It contains all the statistics generated by the tracker. +#[derive(Serialize, Debug, PartialEq)] +pub struct LabeledStats { + metrics: MetricCollection, +} + +impl From for LabeledStats { + #[allow(deprecated)] + fn from(metrics: TrackerLabeledMetrics) -> Self { + Self { + metrics: metrics.metrics, + } + } +} + #[cfg(test)] mod tests { use torrust_rest_tracker_api_core::statistics::metrics::Metrics; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs index 853fdd2e2..e79f7e562 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/responses.rs @@ -1,9 +1,21 @@ //! API responses for the [`stats`](crate::v1::context::stats) //! API context. use axum::response::{IntoResponse, Json, Response}; -use torrust_rest_tracker_api_core::statistics::services::TrackerMetrics; +use torrust_rest_tracker_api_core::statistics::services::{TrackerLabeledMetrics, TrackerMetrics}; +use torrust_tracker_metrics::prometheus::PrometheusSerializable; -use super::resources::Stats; +use super::resources::{LabeledStats, Stats}; + +/// `200` response that contains the [`LabeledStats`] resource as json. +#[must_use] +pub fn labeled_stats_response(tracker_metrics: TrackerLabeledMetrics) -> Response { + Json(LabeledStats::from(tracker_metrics)).into_response() +} + +#[must_use] +pub fn labeled_metrics_response(tracker_metrics: &TrackerLabeledMetrics) -> Response { + tracker_metrics.metrics.to_prometheus().into_response() +} /// `200` response that contains the [`Stats`] resource as json. #[must_use] diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs index e92b5b34d..d516e5ffb 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs @@ -9,17 +9,27 @@ use axum::routing::get; use axum::Router; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; -use super::handlers::get_stats_handler; +use super::handlers::{get_metrics_handler, get_stats_handler}; /// It adds the routes to the router for the [`stats`](crate::v1::context::stats) API context. pub fn add(prefix: &str, router: Router, http_api_container: &Arc) -> Router { - router.route( - &format!("{prefix}/stats"), - get(get_stats_handler).with_state(( - http_api_container.tracker_core_container.in_memory_torrent_repository.clone(), - http_api_container.ban_service.clone(), - http_api_container.http_stats_repository.clone(), - http_api_container.udp_server_stats_repository.clone(), - )), - ) + router + .route( + &format!("{prefix}/stats"), + get(get_stats_handler).with_state(( + http_api_container.tracker_core_container.in_memory_torrent_repository.clone(), + http_api_container.ban_service.clone(), + http_api_container.http_stats_repository.clone(), + http_api_container.udp_server_stats_repository.clone(), + )), + ) + .route( + &format!("{prefix}/metrics"), + get(get_metrics_handler).with_state(( + http_api_container.tracker_core_container.in_memory_torrent_repository.clone(), + http_api_container.ban_service.clone(), + http_api_container.http_stats_repository.clone(), + http_api_container.udp_server_stats_repository.clone(), + )), + ) } diff --git a/packages/http-tracker-core/Cargo.toml b/packages/http-tracker-core/Cargo.toml index aaf982b04..8bd54a483 100644 --- a/packages/http-tracker-core/Cargo.toml +++ b/packages/http-tracker-core/Cargo.toml @@ -20,17 +20,21 @@ bittorrent-primitives = "0.1.0" bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } criterion = { version = "0.5.1", features = ["async_tokio"] } futures = "0" +serde = "1.0.219" thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } tracing = "0" [dev-dependencies] +formatjson = "0.3.1" mockall = "0" +serde_json = "1.0.140" torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } [[bench]] harness = false name = "http_tracker_core_benchmark" - diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index 7caf8a596..d235c179f 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -1,5 +1,6 @@ use std::net::{IpAddr, SocketAddr}; +use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; use torrust_tracker_primitives::service_binding::ServiceBinding; pub mod sender; @@ -59,3 +60,22 @@ pub struct ClientConnectionContext { pub struct ServerConnectionContext { service_binding: ServiceBinding, } + +impl From for LabelSet { + fn from(connection_context: ConnectionContext) -> Self { + LabelSet::from([ + ( + LabelName::new("server_binding_protocol"), + LabelValue::new(&connection_context.server.service_binding.protocol().to_string()), + ), + ( + LabelName::new("server_binding_ip"), + LabelValue::new(&connection_context.server.service_binding.bind_address().ip().to_string()), + ), + ( + LabelName::new("server_binding_port"), + LabelValue::new(&connection_context.server.service_binding.bind_address().port().to_string()), + ), + ]) + } +} diff --git a/packages/http-tracker-core/src/lib.rs b/packages/http-tracker-core/src/lib.rs index 0b0b3ba78..cdb26ca89 100644 --- a/packages/http-tracker-core/src/lib.rs +++ b/packages/http-tracker-core/src/lib.rs @@ -1,8 +1,21 @@ +use torrust_tracker_clock::clock; + pub mod container; pub mod event; pub mod services; pub mod statistics; +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; + #[cfg(test)] pub(crate) mod tests { use bittorrent_primitives::info_hash::InfoHash; diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index 0df1c41d3..046cb7775 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -1,5 +1,9 @@ use std::net::IpAddr; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + use crate::event::Event; use crate::statistics::repository::Repository; @@ -7,24 +11,52 @@ use crate::statistics::repository::Repository; /// /// This function panics if the client IP address is not the same as the IP /// version of the event. -pub async fn handle_event(event: Event, stats_repository: &Repository) { +pub async fn handle_event(event: Event, stats_repository: &Repository, now: DurationSinceUnixEpoch) { match event { - Event::TcpAnnounce { connection } => match connection.client_ip_addr() { - IpAddr::V4(_) => { - stats_repository.increase_tcp4_announces().await; - } - IpAddr::V6(_) => { - stats_repository.increase_tcp6_announces().await; - } - }, - Event::TcpScrape { connection } => match connection.client_ip_addr() { - IpAddr::V4(_) => { - stats_repository.increase_tcp4_scrapes().await; + Event::TcpAnnounce { connection } => { + // Global fixed metrics + + match connection.client_ip_addr() { + IpAddr::V4(_) => { + stats_repository.increase_tcp4_announces().await; + } + IpAddr::V6(_) => { + stats_repository.increase_tcp6_announces().await; + } } - IpAddr::V6(_) => { - stats_repository.increase_tcp6_scrapes().await; + + // Extendable metrics + + stats_repository + .increase_counter( + &MetricName::new("http_tracker_core_announce_requests_received_total"), + &LabelSet::from(connection), + now, + ) + .await; + } + Event::TcpScrape { connection } => { + // Global fixed metrics + + match connection.client_ip_addr() { + IpAddr::V4(_) => { + stats_repository.increase_tcp4_scrapes().await; + } + IpAddr::V6(_) => { + stats_repository.increase_tcp6_scrapes().await; + } } - }, + + // Extendable metrics + + stats_repository + .increase_counter( + &MetricName::new("http_tracker_core_scrape_requests_received_total"), + &LabelSet::from(connection), + now, + ) + .await; + } } tracing::debug!("stats: {:?}", stats_repository.get_stats().await); @@ -34,11 +66,13 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{ConnectionContext, Event}; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; + use crate::CurrentClock; #[tokio::test] async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { @@ -53,6 +87,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -74,6 +109,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -95,6 +131,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -116,6 +153,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; diff --git a/packages/http-tracker-core/src/statistics/event/listener.rs b/packages/http-tracker-core/src/statistics/event/listener.rs index a03a56a21..ca53a20bb 100644 --- a/packages/http-tracker-core/src/statistics/event/listener.rs +++ b/packages/http-tracker-core/src/statistics/event/listener.rs @@ -1,13 +1,15 @@ use tokio::sync::broadcast; +use torrust_tracker_clock::clock::Time; use super::handler::handle_event; use crate::event::Event; use crate::statistics::repository::Repository; +use crate::CurrentClock; pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { loop { match receiver.recv().await { - Ok(event) => handle_event(event, &stats_repository).await, + Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, Err(e) => { tracing::error!("Error receiving http tracker core event: {:?}", e); break; diff --git a/packages/http-tracker-core/src/statistics/metrics.rs b/packages/http-tracker-core/src/statistics/metrics.rs index 6c102770b..0b442c1cb 100644 --- a/packages/http-tracker-core/src/statistics/metrics.rs +++ b/packages/http-tracker-core/src/statistics/metrics.rs @@ -1,12 +1,11 @@ +use serde::Serialize; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::MetricCollection; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + /// Metrics collected by the tracker. -/// -/// - Number of connections handled -/// - Number of `announce` requests handled -/// - Number of `scrape` request handled -/// -/// These metrics are collected for each connection type: UDP and HTTP -/// and also for each IP version used by the peers: IPv4 and IPv6. -#[derive(Debug, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq, Default, Serialize)] pub struct Metrics { /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. pub tcp4_announces_handled: u64, @@ -19,4 +18,17 @@ pub struct Metrics { /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. pub tcp6_scrapes_handled: u64, + + /// A collection of metrics. + pub metric_collection: MetricCollection, +} + +impl Metrics { + pub fn increase_counter(&mut self, metric_name: &MetricName, labels: &LabelSet, now: DurationSinceUnixEpoch) { + self.metric_collection.increase_counter(metric_name, labels, now); + } + + pub fn set_gauge(&mut self, metric_name: &MetricName, labels: &LabelSet, value: f64, now: DurationSinceUnixEpoch) { + self.metric_collection.set_gauge(metric_name, labels, value, now); + } } diff --git a/packages/http-tracker-core/src/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs index 939a41061..dd365495d 100644 --- a/packages/http-tracker-core/src/statistics/mod.rs +++ b/packages/http-tracker-core/src/statistics/mod.rs @@ -4,3 +4,27 @@ pub mod metrics; pub mod repository; pub mod services; pub mod setup; + +use metrics::Metrics; +use torrust_tracker_metrics::metric::description::MetricDescription; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::unit::Unit; + +#[must_use] +pub fn describe_metrics() -> Metrics { + let mut metrics = Metrics::default(); + + metrics.metric_collection.describe_counter( + &MetricName::new("http_tracker_core_announce_requests_received_total"), + Some(Unit::Count), + Some(MetricDescription::new("Total number of announce requests received")), + ); + + metrics.metric_collection.describe_counter( + &MetricName::new("http_tracker_core_scrape_requests_received_total"), + Some(Unit::Count), + Some(MetricDescription::new("Total number of scrape requests received")), + ); + + metrics +} diff --git a/packages/http-tracker-core/src/statistics/repository.rs b/packages/http-tracker-core/src/statistics/repository.rs index 5e15fc298..88345722b 100644 --- a/packages/http-tracker-core/src/statistics/repository.rs +++ b/packages/http-tracker-core/src/statistics/repository.rs @@ -1,7 +1,11 @@ use std::sync::Arc; use tokio::sync::{RwLock, RwLockReadGuard}; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use super::describe_metrics; use super::metrics::Metrics; /// A repository for the tracker metrics. @@ -19,9 +23,9 @@ impl Default for Repository { impl Repository { #[must_use] pub fn new() -> Self { - Self { - stats: Arc::new(RwLock::new(Metrics::default())), - } + let stats = Arc::new(RwLock::new(describe_metrics())); + + Self { stats } } pub async fn get_stats(&self) -> RwLockReadGuard<'_, Metrics> { @@ -51,4 +55,10 @@ impl Repository { stats_lock.tcp6_scrapes_handled += 1; drop(stats_lock); } + + pub async fn increase_counter(&self, metric_name: &MetricName, labels: &LabelSet, now: DurationSinceUnixEpoch) { + let mut stats_lock = self.stats.write().await; + stats_lock.increase_counter(metric_name, labels, now); + drop(stats_lock); + } } diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index dce7098b9..418b0d082 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -59,6 +59,8 @@ pub async fn get_metrics( // TCPv6 tcp6_announces_handled: stats.tcp6_announces_handled, tcp6_scrapes_handled: stats.tcp6_scrapes_handled, + // Samples + metric_collection: stats.metric_collection.clone(), }, } } @@ -73,8 +75,8 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_tracker_test_helpers::configuration; - use crate::statistics; use crate::statistics::services::{get_metrics, TrackerMetrics}; + use crate::statistics::{self, describe_metrics}; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -95,7 +97,7 @@ mod tests { tracker_metrics, TrackerMetrics { torrents_metrics: AggregateSwarmMetadata::default(), - protocol_metrics: statistics::metrics::Metrics::default(), + protocol_metrics: describe_metrics(), } ); } diff --git a/packages/rest-tracker-api-core/Cargo.toml b/packages/rest-tracker-api-core/Cargo.toml index d9ccb5d3f..0077572fb 100644 --- a/packages/rest-tracker-api-core/Cargo.toml +++ b/packages/rest-tracker-api-core/Cargo.toml @@ -19,6 +19,7 @@ bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "../udp-tracker-core" } tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index c40f7c82e..d18f6598d 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -4,6 +4,7 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self}; use tokio::sync::RwLock; +use torrust_tracker_metrics::metric_collection::MetricCollection; use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_udp_tracker_server::statistics as udp_server_statistics; @@ -77,6 +78,30 @@ pub async fn get_metrics( } } +#[derive(Debug, PartialEq)] +pub struct TrackerLabeledMetrics { + pub metrics: MetricCollection, +} + +/// It returns all the [`TrackerLabeledMetrics`] +#[allow(deprecated)] +pub async fn get_labeled_metrics( + in_memory_torrent_repository: Arc, + ban_service: Arc>, + http_stats_repository: Arc, + udp_server_stats_repository: Arc, +) -> TrackerLabeledMetrics { + let _torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let _udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); + let _udp_server_stats = udp_server_stats_repository.get_stats().await; + + let http_stats = http_stats_repository.get_stats().await; + + TrackerLabeledMetrics { + metrics: http_stats.metric_collection.clone(), + } +} + #[cfg(test)] mod tests { use std::sync::Arc; From 9d0933712f35d7555d7bdfe2e92e1607b2cbff92 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 9 Apr 2025 13:01:58 +0100 Subject: [PATCH 0934/1297] feat: [#1403] add extendable-labeled metrics to udp-tracker-core --- Cargo.lock | 3 + packages/http-tracker-core/src/lib.rs | 4 +- .../http-tracker-core/src/statistics/mod.rs | 4 +- packages/udp-tracker-core/Cargo.toml | 4 +- packages/udp-tracker-core/src/event/mod.rs | 20 ++++ packages/udp-tracker-core/src/lib.rs | 13 +++ .../src/statistics/event/handler.rs | 98 ++++++++++++++----- .../src/statistics/event/listener.rs | 4 +- .../src/statistics/metrics.rs | 21 +++- .../udp-tracker-core/src/statistics/mod.rs | 30 ++++++ .../src/statistics/repository.rs | 12 ++- .../src/statistics/services.rs | 6 +- 12 files changed, 187 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fdba742dc..700781fcf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -696,9 +696,12 @@ dependencies = [ "lazy_static", "mockall", "rand 0.9.0", + "serde", "thiserror 2.0.12", "tokio", + "torrust-tracker-clock", "torrust-tracker-configuration", + "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", "tracing", diff --git a/packages/http-tracker-core/src/lib.rs b/packages/http-tracker-core/src/lib.rs index cdb26ca89..2260242e0 100644 --- a/packages/http-tracker-core/src/lib.rs +++ b/packages/http-tracker-core/src/lib.rs @@ -1,10 +1,10 @@ -use torrust_tracker_clock::clock; - pub mod container; pub mod event; pub mod services; pub mod statistics; +use torrust_tracker_clock::clock; + /// This code needs to be copied into each crate. /// Working version, for production. #[cfg(not(test))] diff --git a/packages/http-tracker-core/src/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs index dd365495d..8148df3c1 100644 --- a/packages/http-tracker-core/src/statistics/mod.rs +++ b/packages/http-tracker-core/src/statistics/mod.rs @@ -17,13 +17,13 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_counter( &MetricName::new("http_tracker_core_announce_requests_received_total"), Some(Unit::Count), - Some(MetricDescription::new("Total number of announce requests received")), + Some(MetricDescription::new("Total number of HTTP announce requests received")), ); metrics.metric_collection.describe_counter( &MetricName::new("http_tracker_core_scrape_requests_received_total"), Some(Unit::Count), - Some(MetricDescription::new("Total number of scrape requests received")), + Some(MetricDescription::new("Total number of HTTP scrape requests received")), ); metrics diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml index 88bab51c1..0354777db 100644 --- a/packages/udp-tracker-core/Cargo.toml +++ b/packages/udp-tracker-core/Cargo.toml @@ -25,9 +25,12 @@ criterion = { version = "0.5.1", features = ["async_tokio"] } futures = "0" lazy_static = "1" rand = "0" +serde = "1.0.219" thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync", "time"] } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } tracing = "0" zerocopy = "0.7" @@ -39,4 +42,3 @@ torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-help [[bench]] harness = false name = "udp_tracker_core_benchmark" - diff --git a/packages/udp-tracker-core/src/event/mod.rs b/packages/udp-tracker-core/src/event/mod.rs index e25f557e2..6cb43e5a1 100644 --- a/packages/udp-tracker-core/src/event/mod.rs +++ b/packages/udp-tracker-core/src/event/mod.rs @@ -1,5 +1,6 @@ use std::net::SocketAddr; +use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; use torrust_tracker_primitives::service_binding::ServiceBinding; pub mod sender; @@ -37,3 +38,22 @@ impl ConnectionContext { self.server_service_binding.bind_address() } } + +impl From for LabelSet { + fn from(connection_context: ConnectionContext) -> Self { + LabelSet::from([ + ( + LabelName::new("server_binding_protocol"), + LabelValue::new(&connection_context.server_service_binding.protocol().to_string()), + ), + ( + LabelName::new("server_binding_ip"), + LabelValue::new(&connection_context.server_service_binding.bind_address().ip().to_string()), + ), + ( + LabelName::new("server_binding_port"), + LabelValue::new(&connection_context.server_service_binding.bind_address().port().to_string()), + ), + ]) + } +} diff --git a/packages/udp-tracker-core/src/lib.rs b/packages/udp-tracker-core/src/lib.rs index 94ce93068..8e937e79c 100644 --- a/packages/udp-tracker-core/src/lib.rs +++ b/packages/udp-tracker-core/src/lib.rs @@ -5,6 +5,19 @@ pub mod event; pub mod services; pub mod statistics; +use torrust_tracker_clock::clock; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; + use crypto::ephemeral_instance_keys; use tracing::instrument; diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index 3968ca4e7..a910d9373 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -1,35 +1,81 @@ +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + use crate::event::Event; use crate::statistics::repository::Repository; /// # Panics /// /// This function panics if the IP version does not match the event type. -pub async fn handle_event(event: Event, stats_repository: &Repository) { +pub async fn handle_event(event: Event, stats_repository: &Repository, now: DurationSinceUnixEpoch) { match event { - Event::UdpConnect { context } => match context.client_socket_addr.ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_connections().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_connections().await; - } - }, - Event::UdpAnnounce { context } => match context.client_socket_addr.ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_announces().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_announces().await; + Event::UdpConnect { context } => { + // Global fixed metrics + + match context.client_socket_addr.ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_connections().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_connections().await; + } } - }, - Event::UdpScrape { context } => match context.client_socket_addr.ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_scrapes().await; + + // Extendable metrics + + stats_repository + .increase_counter( + &MetricName::new("udp_tracker_core_connect_requests_received_total"), + &LabelSet::from(context), + now, + ) + .await; + } + Event::UdpAnnounce { context } => { + // Global fixed metrics + + match context.client_socket_addr.ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_announces().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_announces().await; + } } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_scrapes().await; + + // Extendable metrics + + stats_repository + .increase_counter( + &MetricName::new("udp_tracker_core_announce_requests_received_total"), + &LabelSet::from(context), + now, + ) + .await; + } + Event::UdpScrape { context } => { + // Global fixed metrics + + match context.client_socket_addr.ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_scrapes().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_scrapes().await; + } } - }, + + // Extendable metrics + + stats_repository + .increase_counter( + &MetricName::new("udp_tracker_core_scrape_requests_received_total"), + &LabelSet::from(context), + now, + ) + .await; + } } tracing::debug!("stats: {:?}", stats_repository.get_stats().await); @@ -39,11 +85,13 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{ConnectionContext, Event}; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; + use crate::CurrentClock; #[tokio::test] async fn should_increase_the_udp4_connections_counter_when_it_receives_a_udp4_connect_event() { @@ -61,6 +109,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -85,6 +134,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -109,6 +159,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -133,6 +184,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -157,6 +209,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -181,6 +234,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; diff --git a/packages/udp-tracker-core/src/statistics/event/listener.rs b/packages/udp-tracker-core/src/statistics/event/listener.rs index f3afafc4f..8fc82fbcb 100644 --- a/packages/udp-tracker-core/src/statistics/event/listener.rs +++ b/packages/udp-tracker-core/src/statistics/event/listener.rs @@ -1,13 +1,15 @@ use tokio::sync::broadcast; +use torrust_tracker_clock::clock::Time; use super::handler::handle_event; use crate::event::Event; use crate::statistics::repository::Repository; +use crate::CurrentClock; pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { loop { match receiver.recv().await { - Ok(event) => handle_event(event, &stats_repository).await, + Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, Err(e) => { tracing::error!("Error receiving udp tracker core event: {:?}", e); break; diff --git a/packages/udp-tracker-core/src/statistics/metrics.rs b/packages/udp-tracker-core/src/statistics/metrics.rs index 1b3805288..23cec8036 100644 --- a/packages/udp-tracker-core/src/statistics/metrics.rs +++ b/packages/udp-tracker-core/src/statistics/metrics.rs @@ -1,3 +1,9 @@ +use serde::Serialize; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::MetricCollection; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + /// Metrics collected by the tracker. /// /// - Number of connections handled @@ -6,7 +12,7 @@ /// /// These metrics are collected for each connection type: UDP and HTTP /// and also for each IP version used by the peers: IPv4 and IPv6. -#[derive(Debug, PartialEq, Default)] +#[derive(Debug, PartialEq, Default, Serialize)] pub struct Metrics { /// Total number of UDP (UDP tracker) connections from IPv4 peers. pub udp4_connections_handled: u64, @@ -25,4 +31,17 @@ pub struct Metrics { /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. pub udp6_scrapes_handled: u64, + + /// A collection of metrics. + pub metric_collection: MetricCollection, +} + +impl Metrics { + pub fn increase_counter(&mut self, metric_name: &MetricName, labels: &LabelSet, now: DurationSinceUnixEpoch) { + self.metric_collection.increase_counter(metric_name, labels, now); + } + + pub fn set_gauge(&mut self, metric_name: &MetricName, labels: &LabelSet, value: f64, now: DurationSinceUnixEpoch) { + self.metric_collection.set_gauge(metric_name, labels, value, now); + } } diff --git a/packages/udp-tracker-core/src/statistics/mod.rs b/packages/udp-tracker-core/src/statistics/mod.rs index 939a41061..cdba76df3 100644 --- a/packages/udp-tracker-core/src/statistics/mod.rs +++ b/packages/udp-tracker-core/src/statistics/mod.rs @@ -4,3 +4,33 @@ pub mod metrics; pub mod repository; pub mod services; pub mod setup; + +use metrics::Metrics; +use torrust_tracker_metrics::metric::description::MetricDescription; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::unit::Unit; + +#[must_use] +pub fn describe_metrics() -> Metrics { + let mut metrics = Metrics::default(); + + metrics.metric_collection.describe_counter( + &MetricName::new("udp_tracker_core_connect_requests_received_total"), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP connect requests received")), + ); + + metrics.metric_collection.describe_counter( + &MetricName::new("udp_tracker_core_announce_requests_received_total"), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP announce requests received")), + ); + + metrics.metric_collection.describe_counter( + &MetricName::new("udp_tracker_core_scrape_requests_received_total"), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP scrape requests received")), + ); + + metrics +} diff --git a/packages/udp-tracker-core/src/statistics/repository.rs b/packages/udp-tracker-core/src/statistics/repository.rs index f7609e5c2..49c91c751 100644 --- a/packages/udp-tracker-core/src/statistics/repository.rs +++ b/packages/udp-tracker-core/src/statistics/repository.rs @@ -1,7 +1,11 @@ use std::sync::Arc; use tokio::sync::{RwLock, RwLockReadGuard}; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use super::describe_metrics; use super::metrics::Metrics; /// A repository for the tracker metrics. @@ -20,7 +24,7 @@ impl Repository { #[must_use] pub fn new() -> Self { Self { - stats: Arc::new(RwLock::new(Metrics::default())), + stats: Arc::new(RwLock::new(describe_metrics())), } } @@ -63,4 +67,10 @@ impl Repository { stats_lock.udp6_scrapes_handled += 1; drop(stats_lock); } + + pub async fn increase_counter(&self, metric_name: &MetricName, labels: &LabelSet, now: DurationSinceUnixEpoch) { + let mut stats_lock = self.stats.write().await; + stats_lock.increase_counter(metric_name, labels, now); + drop(stats_lock); + } } diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index d3c1d4710..7dbbfc947 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -77,6 +77,8 @@ pub async fn get_metrics( udp6_connections_handled: stats.udp6_connections_handled, udp6_announces_handled: stats.udp6_announces_handled, udp6_scrapes_handled: stats.udp6_scrapes_handled, + // Samples + metric_collection: stats.metric_collection.clone(), }, } } @@ -91,7 +93,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_tracker_test_helpers::configuration; - use crate::statistics; + use crate::statistics::describe_metrics; use crate::statistics::services::{get_metrics, TrackerMetrics}; pub fn tracker_configuration() -> Configuration { @@ -114,7 +116,7 @@ mod tests { tracker_metrics, TrackerMetrics { torrents_metrics: AggregateSwarmMetadata::default(), - protocol_metrics: statistics::metrics::Metrics::default(), + protocol_metrics: describe_metrics(), } ); } From 3f51afcd49c67fe1816abada3293d6b1808ef74e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 9 Apr 2025 13:46:48 +0100 Subject: [PATCH 0935/1297] feat: [#1403] expose udp-tracker-core metrics expose in REST API --- .../src/v1/context/stats/handlers.rs | 10 ++++++++- .../src/v1/context/stats/routes.rs | 1 + .../src/statistics/services.rs | 22 +++++++++++++++---- 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs index 26c812037..17d3e4f2d 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs @@ -70,11 +70,19 @@ pub async fn get_metrics_handler( Arc, Arc>, Arc, + Arc, Arc, )>, params: Query, ) -> Response { - let metrics = get_labeled_metrics(state.0.clone(), state.1.clone(), state.2.clone(), state.3.clone()).await; + let metrics = get_labeled_metrics( + state.0.clone(), + state.1.clone(), + state.2.clone(), + state.3.clone(), + state.4.clone(), + ) + .await; match params.0.format { Some(format) => match format { diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs index d516e5ffb..c19f08b2a 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs @@ -29,6 +29,7 @@ pub fn add(prefix: &str, router: Router, http_api_container: &Arc, ban_service: Arc>, http_stats_repository: Arc, + udp_stats_repository: Arc, udp_server_stats_repository: Arc, ) -> TrackerLabeledMetrics { let _torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); @@ -96,10 +102,18 @@ pub async fn get_labeled_metrics( let _udp_server_stats = udp_server_stats_repository.get_stats().await; let http_stats = http_stats_repository.get_stats().await; - - TrackerLabeledMetrics { - metrics: http_stats.metric_collection.clone(), - } + let udp_stats_repository = udp_stats_repository.get_stats().await; + + // Merge the metrics from the HTTP and UDP metrics + let mut metrics = MetricCollection::default(); + metrics + .merge(&http_stats.metric_collection) + .expect("msg: failed to merge HTTP core metrics"); + metrics + .merge(&udp_stats_repository.metric_collection) + .expect("failed to merge UDP core metrics"); + + TrackerLabeledMetrics { metrics } } #[cfg(test)] From 786f6f0cf646bf0d435d99403bc0fdff4b6f8d7f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 9 Apr 2025 16:28:59 +0100 Subject: [PATCH 0936/1297] feat: [#1403] add extendable-labeled metrics to udp-tracker-server --- Cargo.lock | 2 + packages/metrics/src/label/value.rs | 6 + .../src/statistics/services.rs | 2 +- packages/udp-tracker-server/Cargo.toml | 2 + packages/udp-tracker-server/src/event/mod.rs | 32 +++ .../src/statistics/event/handler.rs | 222 ++++++++++++++---- .../src/statistics/event/listener.rs | 4 +- .../src/statistics/metrics.rs | 21 +- .../udp-tracker-server/src/statistics/mod.rs | 72 ++++++ .../src/statistics/repository.rs | 30 ++- .../src/statistics/services.rs | 6 +- 11 files changed, 344 insertions(+), 55 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 700781fcf..5feea957d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4844,12 +4844,14 @@ dependencies = [ "mockall", "rand 0.9.0", "ringbuf", + "serde", "thiserror 2.0.12", "tokio", "torrust-server-lib", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-located-error", + "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", "tracing", diff --git a/packages/metrics/src/label/value.rs b/packages/metrics/src/label/value.rs index ce657250c..528a0e2ab 100644 --- a/packages/metrics/src/label/value.rs +++ b/packages/metrics/src/label/value.rs @@ -11,6 +11,12 @@ impl LabelValue { pub fn new(value: &str) -> Self { Self(value.to_owned()) } + + /// Empty label values are ignored in Prometheus. + #[must_use] + pub fn ignore() -> Self { + Self(String::default()) + } } impl PrometheusSerializable for LabelValue { diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index 7dbbfc947..d9b016b0d 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -77,7 +77,7 @@ pub async fn get_metrics( udp6_connections_handled: stats.udp6_connections_handled, udp6_announces_handled: stats.udp6_announces_handled, udp6_scrapes_handled: stats.udp6_scrapes_handled, - // Samples + // Extendable metrics metric_collection: stats.metric_collection.clone(), }, } diff --git a/packages/udp-tracker-server/Cargo.toml b/packages/udp-tracker-server/Cargo.toml index f8fcd2def..23719d141 100644 --- a/packages/udp-tracker-server/Cargo.toml +++ b/packages/udp-tracker-server/Cargo.toml @@ -23,12 +23,14 @@ derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } futures = "0" futures-util = "0" ringbuf = "0" +serde = "1.0.219" thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } tracing = "0" url = { version = "2", features = ["serde"] } diff --git a/packages/udp-tracker-server/src/event/mod.rs b/packages/udp-tracker-server/src/event/mod.rs index 68f07cfd6..316e1a414 100644 --- a/packages/udp-tracker-server/src/event/mod.rs +++ b/packages/udp-tracker-server/src/event/mod.rs @@ -1,6 +1,8 @@ +use std::fmt; use std::net::SocketAddr; use std::time::Duration; +use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; use torrust_tracker_primitives::service_binding::ServiceBinding; pub mod sender; @@ -38,6 +40,17 @@ pub enum UdpRequestKind { Scrape, } +impl fmt::Display for UdpRequestKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let proto_str = match self { + UdpRequestKind::Connect => "connect", + UdpRequestKind::Announce => "announce", + UdpRequestKind::Scrape => "scrape", + }; + write!(f, "{proto_str}") + } +} + #[derive(Debug, PartialEq, Eq, Clone)] pub enum UdpResponseKind { Ok { @@ -76,3 +89,22 @@ impl ConnectionContext { self.server_service_binding.bind_address() } } + +impl From for LabelSet { + fn from(connection_context: ConnectionContext) -> Self { + LabelSet::from([ + ( + LabelName::new("server_binding_protocol"), + LabelValue::new(&connection_context.server_service_binding.protocol().to_string()), + ), + ( + LabelName::new("server_binding_ip"), + LabelValue::new(&connection_context.server_service_binding.bind_address().ip().to_string()), + ), + ( + LabelName::new("server_binding_port"), + LabelValue::new(&connection_context.server_service_binding.bind_address().port().to_string()), + ), + ]) + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index b06c8d725..91f5cef0c 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -1,3 +1,7 @@ +use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + use crate::event::{Event, UdpRequestKind, UdpResponseKind}; use crate::statistics::repository::Repository; @@ -6,53 +10,103 @@ use crate::statistics::repository::Repository; /// This function panics if the client IP version does not match the expected /// version. #[allow(clippy::too_many_lines)] -pub async fn handle_event(event: Event, stats_repository: &Repository) { +pub async fn handle_event(event: Event, stats_repository: &Repository, now: DurationSinceUnixEpoch) { match event { - Event::UdpRequestAborted { .. } => { + Event::UdpRequestAborted { context } => { + // Global fixed metrics stats_repository.increase_udp_requests_aborted().await; + + // Extendable metrics + stats_repository + .increase_counter( + &MetricName::new("udp_tracker_server_requests_aborted_total"), + &LabelSet::from(context), + now, + ) + .await; } - Event::UdpRequestBanned { .. } => { + Event::UdpRequestBanned { context } => { + // Global fixed metrics stats_repository.increase_udp_requests_banned().await; + + // Extendable metrics + stats_repository + .increase_counter( + &MetricName::new("udp_tracker_server_requests_banned_total"), + &LabelSet::from(context), + now, + ) + .await; } - Event::UdpRequestReceived { context } => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_requests().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_requests().await; - } - }, - Event::UdpRequestAccepted { context, kind } => match kind { - UdpRequestKind::Connect => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_connections().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_connections().await; - } - }, - UdpRequestKind::Announce => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_announces().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_announces().await; - } - }, - UdpRequestKind::Scrape => match context.client_socket_addr().ip() { + Event::UdpRequestReceived { context } => { + // Global fixed metrics + match context.client_socket_addr().ip() { std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_scrapes().await; + stats_repository.increase_udp4_requests().await; } std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_scrapes().await; + stats_repository.increase_udp6_requests().await; } - }, - }, + } + + // Extendable metrics + stats_repository + .increase_counter( + &MetricName::new("udp_tracker_server_requests_received_total"), + &LabelSet::from(context), + now, + ) + .await; + } + Event::UdpRequestAccepted { context, kind } => { + // Global fixed metrics + match kind { + UdpRequestKind::Connect => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_connections().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_connections().await; + } + }, + UdpRequestKind::Announce => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_announces().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_announces().await; + } + }, + UdpRequestKind::Scrape => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_scrapes().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_scrapes().await; + } + }, + } + + // Extendable metrics + + let mut label_set = LabelSet::from(context); + + label_set.upsert(LabelName::new("kind"), LabelValue::new(&kind.to_string())); + + stats_repository + .increase_counter( + &MetricName::new("udp_tracker_server_requests_accepted_total"), + &label_set, + now, + ) + .await; + } Event::UdpResponseSent { context, kind, req_processing_time, } => { + // Global fixed metrics match context.client_socket_addr().ip() { std::net::IpAddr::V4(_) => { stats_repository.increase_udp4_responses().await; @@ -62,35 +116,94 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { } } - match kind { + let (result_label_value, kind_label_value) = match kind { UdpResponseKind::Ok { req_kind } => match req_kind { UdpRequestKind::Connect => { - stats_repository + let new_avg = stats_repository .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) .await; + + // Extendable metrics + stats_repository + .set_gauge( + &MetricName::new("udp_tracker_server_performance_avg_connect_processing_time_ns"), + &LabelSet::from(context.clone()), + new_avg, + now, + ) + .await; + + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Connect.to_string())) } UdpRequestKind::Announce => { - stats_repository + let new_avg = stats_repository .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) .await; + + // Extendable metrics + stats_repository + .set_gauge( + &MetricName::new("udp_tracker_server_performance_avg_announce_processing_time_ns"), + &LabelSet::from(context.clone()), + new_avg, + now, + ) + .await; + + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Connect.to_string())) } UdpRequestKind::Scrape => { - stats_repository + let new_avg = stats_repository .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) .await; + + // Extendable metrics + stats_repository + .set_gauge( + &MetricName::new("udp_tracker_server_performance_avg_scrape_processing_time_ns"), + &LabelSet::from(context.clone()), + new_avg, + now, + ) + .await; + + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Connect.to_string())) } }, - UdpResponseKind::Error { opt_req_kind: _ } => {} - } + UdpResponseKind::Error { opt_req_kind: _ } => (LabelValue::new("ok"), LabelValue::ignore()), + }; + + // Extendable metrics + + let mut label_set = LabelSet::from(context); + + label_set.upsert(LabelName::new("result"), result_label_value); + label_set.upsert(LabelName::new("kind"), kind_label_value); + + stats_repository + .increase_counter(&MetricName::new("udp_tracker_server_responses_sent_total"), &label_set, now) + .await; } - Event::UdpError { context } => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_errors().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_errors().await; + Event::UdpError { context } => { + // Global fixed metrics + match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_errors().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_errors().await; + } } - }, + + // Extendable metrics + stats_repository + .increase_counter( + &MetricName::new("udp_tracker_server_errors_total"), + &LabelSet::from(context), + now, + ) + .await; + } } tracing::debug!("stats: {:?}", stats_repository.get_stats().await); @@ -100,11 +213,13 @@ pub async fn handle_event(event: Event, stats_repository: &Repository) { mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{ConnectionContext, Event, UdpRequestKind}; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; + use crate::CurrentClock; #[tokio::test] async fn should_increase_the_number_of_aborted_requests_when_it_receives_a_udp_request_aborted_event() { @@ -122,6 +237,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -146,6 +262,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -170,6 +287,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -194,6 +312,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; let stats = stats_repository.get_stats().await; @@ -215,6 +334,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; let stats = stats_repository.get_stats().await; @@ -238,6 +358,7 @@ mod tests { kind: crate::event::UdpRequestKind::Connect, }, &stats_repository, + CurrentClock::now(), ) .await; @@ -263,6 +384,7 @@ mod tests { kind: crate::event::UdpRequestKind::Announce, }, &stats_repository, + CurrentClock::now(), ) .await; @@ -288,6 +410,7 @@ mod tests { kind: crate::event::UdpRequestKind::Scrape, }, &stats_repository, + CurrentClock::now(), ) .await; @@ -316,6 +439,7 @@ mod tests { req_processing_time: std::time::Duration::from_secs(1), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -340,6 +464,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -365,6 +490,7 @@ mod tests { kind: crate::event::UdpRequestKind::Connect, }, &stats_repository, + CurrentClock::now(), ) .await; @@ -390,6 +516,7 @@ mod tests { kind: crate::event::UdpRequestKind::Announce, }, &stats_repository, + CurrentClock::now(), ) .await; @@ -415,6 +542,7 @@ mod tests { kind: crate::event::UdpRequestKind::Scrape, }, &stats_repository, + CurrentClock::now(), ) .await; @@ -443,6 +571,7 @@ mod tests { req_processing_time: std::time::Duration::from_secs(1), }, &stats_repository, + CurrentClock::now(), ) .await; @@ -466,6 +595,7 @@ mod tests { ), }, &stats_repository, + CurrentClock::now(), ) .await; diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index b23260747..c50ce70c9 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -1,13 +1,15 @@ use tokio::sync::broadcast; +use torrust_tracker_clock::clock::Time; use super::handler::handle_event; use crate::event::Event; use crate::statistics::repository::Repository; +use crate::CurrentClock; pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { loop { match receiver.recv().await { - Ok(event) => handle_event(event, &stats_repository).await, + Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, Err(e) => { tracing::error!("Error receiving udp tracker server event: {:?}", e); break; diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index cce618d74..4fe07e7da 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -1,5 +1,11 @@ +use serde::Serialize; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::MetricCollection; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + /// Metrics collected by the UDP tracker server. -#[derive(Debug, PartialEq, Default)] +#[derive(Debug, PartialEq, Default, Serialize)] pub struct Metrics { // UDP /// Total number of UDP (UDP tracker) requests aborted. @@ -57,4 +63,17 @@ pub struct Metrics { /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. pub udp6_errors_handled: u64, + + /// A collection of metrics. + pub metric_collection: MetricCollection, +} + +impl Metrics { + pub fn increase_counter(&mut self, metric_name: &MetricName, labels: &LabelSet, now: DurationSinceUnixEpoch) { + self.metric_collection.increase_counter(metric_name, labels, now); + } + + pub fn set_gauge(&mut self, metric_name: &MetricName, labels: &LabelSet, value: f64, now: DurationSinceUnixEpoch) { + self.metric_collection.set_gauge(metric_name, labels, value, now); + } } diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index 939a41061..535031483 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -4,3 +4,75 @@ pub mod metrics; pub mod repository; pub mod services; pub mod setup; + +use metrics::Metrics; +use torrust_tracker_metrics::metric::description::MetricDescription; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::unit::Unit; + +#[must_use] +pub fn describe_metrics() -> Metrics { + let mut metrics = Metrics::default(); + + metrics.metric_collection.describe_counter( + &MetricName::new("udp_tracker_server_requests_aborted_total"), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP requests aborted")), + ); + + metrics.metric_collection.describe_counter( + &MetricName::new("udp_tracker_server_requests_banned_total"), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP requests banned")), + ); + + metrics.metric_collection.describe_counter( + &MetricName::new("udp_tracker_server_requests_received_total"), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP requests received")), + ); + + metrics.metric_collection.describe_counter( + &MetricName::new("udp_tracker_server_requests_accepted_total"), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP requests accepted")), + ); + + metrics.metric_collection.describe_counter( + &MetricName::new("udp_tracker_server_responses_sent_total"), + Some(Unit::Count), + Some(MetricDescription::new("Total number of UDP responses sent")), + ); + + metrics.metric_collection.describe_counter( + &MetricName::new("udp_tracker_server_errors_total"), + Some(Unit::Count), + Some(MetricDescription::new("Total number of errors processing UDP requests")), + ); + + metrics.metric_collection.describe_gauge( + &MetricName::new("udp_tracker_server_performance_avg_connect_processing_time_ns"), + Some(Unit::Nanoseconds), + Some(MetricDescription::new( + "Average time to process a UDP connect request in nanoseconds", + )), + ); + + metrics.metric_collection.describe_gauge( + &MetricName::new("udp_tracker_server_performance_avg_announce_processing_time_ns"), + Some(Unit::Nanoseconds), + Some(MetricDescription::new( + "Average time to process a UDP announce request in nanoseconds", + )), + ); + + metrics.metric_collection.describe_gauge( + &MetricName::new("udp_tracker_server_performance_avg_scrape_processing_time_ns"), + Some(Unit::Nanoseconds), + Some(MetricDescription::new( + "Average time to process a UDP scrape request in nanoseconds", + )), + ); + + metrics +} diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index 22e793036..c33c1231c 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -2,7 +2,11 @@ use std::sync::Arc; use std::time::Duration; use tokio::sync::{RwLock, RwLockReadGuard}; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use super::describe_metrics; use super::metrics::Metrics; /// A repository for the tracker metrics. @@ -21,7 +25,7 @@ impl Repository { #[must_use] pub fn new() -> Self { Self { - stats: Arc::new(RwLock::new(Metrics::default())), + stats: Arc::new(RwLock::new(describe_metrics())), } } @@ -80,7 +84,7 @@ impl Repository { #[allow(clippy::cast_precision_loss)] #[allow(clippy::cast_possible_truncation)] #[allow(clippy::cast_sign_loss)] - pub async fn recalculate_udp_avg_connect_processing_time_ns(&self, req_processing_time: Duration) { + pub async fn recalculate_udp_avg_connect_processing_time_ns(&self, req_processing_time: Duration) -> f64 { let mut stats_lock = self.stats.write().await; let req_processing_time = req_processing_time.as_nanos() as f64; @@ -94,12 +98,14 @@ impl Repository { stats_lock.udp_avg_connect_processing_time_ns = new_avg.ceil() as u64; drop(stats_lock); + + new_avg } #[allow(clippy::cast_precision_loss)] #[allow(clippy::cast_possible_truncation)] #[allow(clippy::cast_sign_loss)] - pub async fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) { + pub async fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) -> f64 { let mut stats_lock = self.stats.write().await; let req_processing_time = req_processing_time.as_nanos() as f64; @@ -114,12 +120,14 @@ impl Repository { stats_lock.udp_avg_announce_processing_time_ns = new_avg.ceil() as u64; drop(stats_lock); + + new_avg } #[allow(clippy::cast_precision_loss)] #[allow(clippy::cast_possible_truncation)] #[allow(clippy::cast_sign_loss)] - pub async fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) { + pub async fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) -> f64 { let mut stats_lock = self.stats.write().await; let req_processing_time = req_processing_time.as_nanos() as f64; @@ -133,6 +141,8 @@ impl Repository { stats_lock.udp_avg_scrape_processing_time_ns = new_avg.ceil() as u64; drop(stats_lock); + + new_avg } pub async fn increase_udp6_requests(&self) { @@ -170,4 +180,16 @@ impl Repository { stats_lock.udp6_errors_handled += 1; drop(stats_lock); } + + pub async fn increase_counter(&self, metric_name: &MetricName, labels: &LabelSet, now: DurationSinceUnixEpoch) { + let mut stats_lock = self.stats.write().await; + stats_lock.increase_counter(metric_name, labels, now); + drop(stats_lock); + } + + pub async fn set_gauge(&self, metric_name: &MetricName, labels: &LabelSet, value: f64, now: DurationSinceUnixEpoch) { + let mut stats_lock = self.stats.write().await; + stats_lock.set_gauge(metric_name, labels, value, now); + drop(stats_lock); + } } diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index a16685077..b84bf4cd0 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -94,6 +94,8 @@ pub async fn get_metrics( udp6_scrapes_handled: stats.udp6_scrapes_handled, udp6_responses: stats.udp6_responses, udp6_errors_handled: stats.udp6_errors_handled, + // Extendable metrics + metric_collection: stats.metric_collection.clone(), }, } } @@ -111,8 +113,8 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_tracker_test_helpers::configuration; - use crate::statistics; use crate::statistics::services::{get_metrics, TrackerMetrics}; + use crate::statistics::{self, describe_metrics}; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -140,7 +142,7 @@ mod tests { tracker_metrics, TrackerMetrics { torrents_metrics: AggregateSwarmMetadata::default(), - protocol_metrics: statistics::metrics::Metrics::default(), + protocol_metrics: describe_metrics(), } ); } From af8dbfa665feafcf12942dfdc7b672db1fd60416 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 9 Apr 2025 16:37:47 +0100 Subject: [PATCH 0937/1297] feat: [#1403] expose udp-tracker-server metrics expose in REST API --- packages/rest-tracker-api-core/src/statistics/services.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 037563b11..9277df92b 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -99,12 +99,12 @@ pub async fn get_labeled_metrics( ) -> TrackerLabeledMetrics { let _torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); let _udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); - let _udp_server_stats = udp_server_stats_repository.get_stats().await; let http_stats = http_stats_repository.get_stats().await; let udp_stats_repository = udp_stats_repository.get_stats().await; + let udp_server_stats = udp_server_stats_repository.get_stats().await; - // Merge the metrics from the HTTP and UDP metrics + // Merge all the metrics into a single collection let mut metrics = MetricCollection::default(); metrics .merge(&http_stats.metric_collection) @@ -112,6 +112,9 @@ pub async fn get_labeled_metrics( metrics .merge(&udp_stats_repository.metric_collection) .expect("failed to merge UDP core metrics"); + metrics + .merge(&udp_server_stats.metric_collection) + .expect("failed to merge UDP server metrics"); TrackerLabeledMetrics { metrics } } From 017d977344408eb4e1295ed2c7c26916aea20fdd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 10 Apr 2025 12:58:28 +0100 Subject: [PATCH 0938/1297] refactor: [#1403] remove unused code After discussing with @da2ce7 we don't think this is necessary. --- packages/metrics/src/lib.rs | 1 - .../src/thread_safe_metric_collection.rs | 92 ------------------- 2 files changed, 93 deletions(-) delete mode 100644 packages/metrics/src/thread_safe_metric_collection.rs diff --git a/packages/metrics/src/lib.rs b/packages/metrics/src/lib.rs index 1cb0df195..fd677b891 100644 --- a/packages/metrics/src/lib.rs +++ b/packages/metrics/src/lib.rs @@ -6,7 +6,6 @@ pub mod metric_collection; pub mod prometheus; pub mod sample; pub mod sample_collection; -pub mod thread_safe_metric_collection; pub mod unit; #[cfg(test)] diff --git a/packages/metrics/src/thread_safe_metric_collection.rs b/packages/metrics/src/thread_safe_metric_collection.rs deleted file mode 100644 index d9774c9af..000000000 --- a/packages/metrics/src/thread_safe_metric_collection.rs +++ /dev/null @@ -1,92 +0,0 @@ -use std::sync::RwLock; - -use torrust_tracker_primitives::DurationSinceUnixEpoch; - -use crate::counter::Counter; -use crate::gauge::Gauge; -use crate::label::LabelSet; -use crate::metric::description::MetricDescription; -use crate::metric::MetricName; -use crate::metric_collection::{MetricCollection, MetricKindCollection}; -use crate::unit::Unit; - -/* code-review: - - This might be not necessary, since the `MetricCollection` doesn't expose - any method to mutate the collection items directly. - -*/ - -/// A thread-safe wrapper around `MetricCollection` that allows concurrent -/// access to the metrics collection. -/// -/// It protects the `MetricCollection` invariant: -/// -/// "Metric's names must be unique in the collection for all types of metrics." -#[derive(Debug, Default)] -pub struct ThreadSafeMetricCollection { - inner: RwLock, -} - -impl ThreadSafeMetricCollection { - #[must_use] - pub fn new(counters: MetricKindCollection, gauges: MetricKindCollection) -> Self { - Self { - inner: RwLock::new(MetricCollection::new(counters, gauges)), - } - } - - // Counter-specific methods - - /// # Panics - /// - /// Panics if it can't get write access to the inner collection. - pub fn describe_counter(&mut self, name: &MetricName, _opt_unit: Option, _opt_description: Option) { - self.inner.write().unwrap().ensure_counter_exists(name); - } - - /// It allows to describe a counter metric so the metrics appear in the JSON - /// response even if there are no samples yet. - /// - /// # Panics - /// - /// Panics if it can't get read access to the inner collection. - #[must_use] - pub fn get_counter_value(&self, name: &MetricName, label_set: &LabelSet) -> Counter { - self.inner.read().unwrap().get_counter_value(name, label_set) - } - - /// # Panics - /// - /// Panics if it can't get write access to the inner collection. - pub fn increase_counter(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { - self.inner.write().unwrap().increase_counter(name, label_set, time); - } - - // Gauge-specific methods - - /// It allows to describe a gauge metric so the metrics appear in the JSON - /// response even if there are no samples yet. - /// - /// # Panics - /// - /// Panics if it can't get write access to the inner collection. - pub fn describe_gauge(&mut self, name: &MetricName, _opt_unit: Option, _opt_description: Option) { - self.inner.write().unwrap().ensure_gauge_exists(name); - } - - /// # Panics - /// - /// Panics if it can't get read access to the inner collection. - #[must_use] - pub fn get_gauge_value(&self, name: &MetricName, label_set: &LabelSet) -> Gauge { - self.inner.read().unwrap().get_gauge_value(name, label_set) - } - - /// # Panics - /// - /// Panics if it can't get write access to the inner collection. - pub fn set_gauge(&mut self, name: &MetricName, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { - self.inner.write().unwrap().set_gauge(name, label_set, value, time); - } -} From 5099e90816324e3104684cf07b386714fe25388a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 10 Apr 2025 16:34:59 +0100 Subject: [PATCH 0939/1297] refactor: [#1403] extract Measurement strcut To remove duplicate data. LabelSet is the HashMap key and it was also included in the HashMap value. --- packages/metrics/src/metric/mod.rs | 15 ++-- packages/metrics/src/metric_collection.rs | 4 +- packages/metrics/src/sample.rs | 85 ++++++++++++++++++----- packages/metrics/src/sample_collection.rs | 40 ++++++----- 4 files changed, 101 insertions(+), 43 deletions(-) diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index 0d79a24d3..edea035bb 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -7,9 +7,9 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::counter::Counter; use super::label::LabelSet; use super::prometheus::PrometheusSerializable; -use super::sample::Sample; use super::sample_collection::SampleCollection; use crate::gauge::Gauge; +use crate::sample::Measurement; pub type MetricName = name::MetricName; @@ -36,7 +36,7 @@ impl Metric { } #[must_use] - pub fn get_sample(&self, label_set: &LabelSet) -> Option<&Sample> { + pub fn get_sample_data(&self, label_set: &LabelSet) -> Option<&Measurement> { self.sample_collection.get(label_set) } @@ -68,11 +68,11 @@ impl PrometheusSerializable for Metric { let samples: Vec = self .sample_collection .iter() - .map(|(_label_set, sample)| { + .map(|(label_set, sample)| { format!( "{}{} {}", self.name.to_prometheus(), - sample.labels().to_prometheus(), + label_set.to_prometheus(), sample.value().to_prometheus() ) }) @@ -87,6 +87,7 @@ mod tests { use super::super::*; use crate::gauge::Gauge; use crate::label::{LabelName, LabelValue}; + use crate::sample::Sample; #[test] fn it_should_be_empty_when_it_does_not_have_any_sample() { @@ -132,6 +133,7 @@ mod tests { use super::super::*; use crate::counter::Counter; use crate::label::{LabelName, LabelValue}; + use crate::sample::Sample; #[test] fn it_should_be_created_from_its_name_and_a_collection_of_samples() { @@ -154,7 +156,7 @@ mod tests { let metric = Metric::::new(name.clone(), samples); - assert_eq!(metric.get_sample(&label_set).unwrap().value().value(), 1); + assert_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1); } } @@ -164,6 +166,7 @@ mod tests { use super::super::*; use crate::gauge::Gauge; use crate::label::{LabelName, LabelValue}; + use crate::sample::Sample; #[test] fn it_should_be_created_from_its_name_and_a_collection_of_samples() { @@ -186,7 +189,7 @@ mod tests { let metric = Metric::::new(name.clone(), samples); - assert_relative_eq!(metric.get_sample(&label_set).unwrap().value().value(), 1.0); + assert_relative_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1.0); } } } diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index 588194e5f..ac62a7e8a 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -278,7 +278,7 @@ impl MetricKindCollection { pub fn get_value(&self, name: &MetricName, label_set: &LabelSet) -> Counter { self.metrics .get(name) - .and_then(|metric| metric.get_sample(label_set)) + .and_then(|metric| metric.get_sample_data(label_set)) .map_or(Counter::default(), |sample| sample.value().clone()) } } @@ -303,7 +303,7 @@ impl MetricKindCollection { pub fn get_value(&self, name: &MetricName, label_set: &LabelSet) -> Gauge { self.metrics .get(name) - .and_then(|metric| metric.get_sample(label_set)) + .and_then(|metric| metric.get_sample_data(label_set)) .map_or(Gauge::default(), |sample| sample.value().clone()) } } diff --git a/packages/metrics/src/sample.rs b/packages/metrics/src/sample.rs index eddb2eefc..2b1fb4cc2 100644 --- a/packages/metrics/src/sample.rs +++ b/packages/metrics/src/sample.rs @@ -9,10 +9,8 @@ use super::prometheus::PrometheusSerializable; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Sample { - value: T, - - #[serde(serialize_with = "serialize_duration", deserialize_with = "deserialize_duration")] - update_at: DurationSinceUnixEpoch, + #[serde(flatten)] + measurement: Measurement, #[serde(rename = "labels")] label_set: LabelSet, @@ -21,17 +19,68 @@ pub struct Sample { impl Sample { #[must_use] pub fn new(value: T, update_at: DurationSinceUnixEpoch, label_set: LabelSet) -> Self { + let data = Measurement { value, update_at }; + Self { - value, - update_at, + measurement: data, label_set, } } + #[must_use] + pub fn measurement(&self) -> &Measurement { + &self.measurement + } + + #[must_use] + pub fn value(&self) -> &T { + &self.measurement.value + } + + #[must_use] + pub fn update_at(&self) -> DurationSinceUnixEpoch { + self.measurement.update_at + } + #[must_use] pub fn labels(&self) -> &LabelSet { &self.label_set } +} + +impl PrometheusSerializable for Sample { + fn to_prometheus(&self) -> String { + format!("{} {}", self.label_set.to_prometheus(), self.measurement.to_prometheus()) + } +} + +impl Sample { + pub fn increment(&mut self, time: DurationSinceUnixEpoch) { + self.measurement.increment(time); + } +} + +impl Sample { + pub fn set(&mut self, value: f64, time: DurationSinceUnixEpoch) { + self.measurement.set(value, time); + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Measurement { + /// The value of the sample. + value: T, + + /// The time when the sample was last updated. + #[serde(serialize_with = "serialize_duration", deserialize_with = "deserialize_duration")] + update_at: DurationSinceUnixEpoch, +} + +impl Measurement { + #[must_use] + pub fn new(value: T, update_at: DurationSinceUnixEpoch) -> Self { + Self { value, update_at } + } #[must_use] pub fn value(&self) -> &T { @@ -48,20 +97,26 @@ impl Sample { } } -impl PrometheusSerializable for Sample { +impl From> for (LabelSet, Measurement) { + fn from(sample: Sample) -> Self { + (sample.label_set, sample.measurement) + } +} + +impl PrometheusSerializable for Measurement { fn to_prometheus(&self) -> String { - format!("{} {}", self.label_set.to_prometheus(), self.value.to_prometheus()) + self.value.to_prometheus() } } -impl Sample { +impl Measurement { pub fn increment(&mut self, time: DurationSinceUnixEpoch) { self.value.increment(1); self.set_update_at(time); } } -impl Sample { +impl Measurement { pub fn set(&mut self, value: f64, time: DurationSinceUnixEpoch) { self.value.set(value); self.set_update_at(time); @@ -260,17 +315,13 @@ mod tests { #[test] fn test_serialization_round_trip() { - let original = Sample { - value: 42, - update_at: updated_at_time(), - label_set: LabelSet::from(vec![("test", "serialization")]), - }; + let original = Sample::new(42, updated_at_time(), LabelSet::from(vec![("test", "serialization")])); let json = serde_json::to_string(&original).unwrap(); let deserialized: Sample = serde_json::from_str(&json).unwrap(); - assert_eq!(original.value, deserialized.value); - assert_eq!(original.update_at, deserialized.update_at); + assert_eq!(original.measurement.value, deserialized.measurement.value); + assert_eq!(original.measurement.update_at, deserialized.measurement.update_at); assert_eq!(original.label_set, deserialized.label_set); } diff --git a/packages/metrics/src/sample_collection.rs b/packages/metrics/src/sample_collection.rs index 02977597f..c6dc4e27d 100644 --- a/packages/metrics/src/sample_collection.rs +++ b/packages/metrics/src/sample_collection.rs @@ -1,5 +1,6 @@ use std::collections::hash_map::Iter; use std::collections::{HashMap, HashSet}; +use std::fmt::Write as _; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use torrust_tracker_primitives::DurationSinceUnixEpoch; @@ -9,28 +10,26 @@ use super::gauge::Gauge; use super::label::LabelSet; use super::prometheus::PrometheusSerializable; use super::sample::Sample; +use crate::sample::Measurement; #[derive(Debug, Clone, Default, PartialEq)] pub struct SampleCollection { - samples: HashMap>, + samples: HashMap>, } impl SampleCollection { - // IMPORTANT: It should never allow mutation of the samples because it would - // break the invariants. If the sample's `LabelSet` is changed, it can - // create duplicate `LabelSet`s even if the `LabelSet` in the `HashMap` key - // is unique. - /// # Panics /// /// Panics if there are duplicate `LabelSets` in the provided samples. #[must_use] pub fn new(samples: Vec>) -> Self { - let mut map = HashMap::with_capacity(samples.len()); + let mut map: HashMap> = HashMap::with_capacity(samples.len()); for sample in samples { + let (label_set, sample_data): (LabelSet, Measurement) = sample.into(); + assert!( - map.insert(sample.labels().clone(), sample).is_none(), + map.insert(label_set, sample_data).is_none(), "Duplicate LabelSet found in SampleCollection" ); } @@ -39,7 +38,7 @@ impl SampleCollection { } #[must_use] - pub fn get(&self, label: &LabelSet) -> Option<&Sample> { + pub fn get(&self, label: &LabelSet) -> Option<&Measurement> { self.samples.get(label) } @@ -55,7 +54,7 @@ impl SampleCollection { #[must_use] #[allow(clippy::iter_without_into_iter)] - pub fn iter(&self) -> Iter<'_, LabelSet, Sample> { + pub fn iter(&self) -> Iter<'_, LabelSet, Measurement> { self.samples.iter() } } @@ -65,7 +64,7 @@ impl SampleCollection { let sample = self .samples .entry(label_set.clone()) - .or_insert_with(|| Sample::new(Counter::default(), time, label_set.clone())); + .or_insert_with(|| Measurement::new(Counter::default(), time)); sample.increment(time); } @@ -76,7 +75,7 @@ impl SampleCollection { let sample = self .samples .entry(label_set.clone()) - .or_insert_with(|| Sample::new(Gauge::default(), time, label_set.clone())); + .or_insert_with(|| Measurement::new(Gauge::default(), time)); sample.set(value, time); } @@ -87,7 +86,12 @@ impl Serialize for SampleCollection { where S: Serializer, { - let samples: Vec<&Sample> = self.samples.values().collect(); + let mut samples: Vec> = vec![]; + + for (label_set, sample_data) in &self.samples { + samples.push(Sample::new(sample_data.value(), sample_data.update_at(), label_set.clone())); + } + samples.serialize(serializer) } } @@ -121,8 +125,8 @@ impl PrometheusSerializable for SampleCollection { fn to_prometheus(&self) -> String { let mut output = String::new(); - for sample in self.samples.values() { - output.push_str(&sample.to_prometheus()); + for (label_set, sample_data) in &self.samples { + let _ = write!(output, "{} {}", label_set.to_prometheus(), sample_data.to_prometheus()); } output @@ -165,7 +169,7 @@ mod tests { let retrieved = collection.get(&label_set); - assert_eq!(retrieved.unwrap(), &sample); + assert_eq!(retrieved.unwrap(), sample.measurement()); } #[test] @@ -179,10 +183,10 @@ mod tests { let collection = SampleCollection::new(vec![sample_1.clone(), sample_2.clone()]); let retrieved = collection.get(&label_set_1); - assert_eq!(retrieved.unwrap(), &sample_1); + assert_eq!(retrieved.unwrap(), sample_1.measurement()); let retrieved = collection.get(&label_set_2); - assert_eq!(retrieved.unwrap(), &sample_2); + assert_eq!(retrieved.unwrap(), sample_2.measurement()); } #[test] From e3b84a4e4a5b12f26132f74405483a6448da017a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 10 Apr 2025 16:45:56 +0100 Subject: [PATCH 0940/1297] feat: [#1403] rename field update_at to recorded_at in metrics Sample The new name is more common in the context of metrics and time-series data packages like Prometheus. --- packages/metrics/src/metric_collection.rs | 4 +-- packages/metrics/src/sample.rs | 40 +++++++++++------------ packages/metrics/src/sample_collection.rs | 6 ++-- 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index ac62a7e8a..d0ed96554 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -374,7 +374,7 @@ mod tests { "samples":[ { "value":1, - "update_at":"2025-04-02T00:00:00+00:00", + "recorded_at":"2025-04-02T00:00:00+00:00", "labels":[ { "name":"server_binding_ip", @@ -398,7 +398,7 @@ mod tests { "samples":[ { "value":1.0, - "update_at":"2025-04-02T00:00:00+00:00", + "recorded_at":"2025-04-02T00:00:00+00:00", "labels":[ { "name":"server_binding_ip", diff --git a/packages/metrics/src/sample.rs b/packages/metrics/src/sample.rs index 2b1fb4cc2..5567dffec 100644 --- a/packages/metrics/src/sample.rs +++ b/packages/metrics/src/sample.rs @@ -18,8 +18,8 @@ pub struct Sample { impl Sample { #[must_use] - pub fn new(value: T, update_at: DurationSinceUnixEpoch, label_set: LabelSet) -> Self { - let data = Measurement { value, update_at }; + pub fn new(value: T, recorded_at: DurationSinceUnixEpoch, label_set: LabelSet) -> Self { + let data = Measurement { value, recorded_at }; Self { measurement: data, @@ -38,8 +38,8 @@ impl Sample { } #[must_use] - pub fn update_at(&self) -> DurationSinceUnixEpoch { - self.measurement.update_at + pub fn recorded_at(&self) -> DurationSinceUnixEpoch { + self.measurement.recorded_at } #[must_use] @@ -73,13 +73,13 @@ pub struct Measurement { /// The time when the sample was last updated. #[serde(serialize_with = "serialize_duration", deserialize_with = "deserialize_duration")] - update_at: DurationSinceUnixEpoch, + recorded_at: DurationSinceUnixEpoch, } impl Measurement { #[must_use] - pub fn new(value: T, update_at: DurationSinceUnixEpoch) -> Self { - Self { value, update_at } + pub fn new(value: T, recorded_at: DurationSinceUnixEpoch) -> Self { + Self { value, recorded_at } } #[must_use] @@ -88,12 +88,12 @@ impl Measurement { } #[must_use] - pub fn update_at(&self) -> DurationSinceUnixEpoch { - self.update_at + pub fn recorded_at(&self) -> DurationSinceUnixEpoch { + self.recorded_at } - fn set_update_at(&mut self, time: DurationSinceUnixEpoch) { - self.update_at = time; + fn set_recorded_at(&mut self, time: DurationSinceUnixEpoch) { + self.recorded_at = time; } } @@ -112,18 +112,18 @@ impl PrometheusSerializable for Measurement { impl Measurement { pub fn increment(&mut self, time: DurationSinceUnixEpoch) { self.value.increment(1); - self.set_update_at(time); + self.set_recorded_at(time); } } impl Measurement { pub fn set(&mut self, value: f64, time: DurationSinceUnixEpoch) { self.value.set(value); - self.set_update_at(time); + self.set_recorded_at(time); } } -/// Serializes the `update_at` field as a string in ISO 8601 format (RFC 3339). +/// Serializes the `recorded_at` field as a string in ISO 8601 format (RFC 3339). /// /// # Errors /// @@ -189,7 +189,7 @@ mod tests { LabelSet::from(vec![("test", "label")]), ); - assert_eq!(sample.update_at(), updated_at_time()); + assert_eq!(sample.recorded_at(), updated_at_time()); } #[test] @@ -239,7 +239,7 @@ mod tests { sample.increment(time); - assert_eq!(sample.update_at(), time); + assert_eq!(sample.recorded_at(), time); } #[test] @@ -289,7 +289,7 @@ mod tests { sample.set(1.0, time); - assert_eq!(sample.update_at(), time); + assert_eq!(sample.recorded_at(), time); } #[test] @@ -321,7 +321,7 @@ mod tests { let deserialized: Sample = serde_json::from_str(&json).unwrap(); assert_eq!(original.measurement.value, deserialized.measurement.value); - assert_eq!(original.measurement.update_at, deserialized.measurement.update_at); + assert_eq!(original.measurement.recorded_at, deserialized.measurement.recorded_at); assert_eq!(original.label_set, deserialized.label_set); } @@ -338,7 +338,7 @@ mod tests { let expected_json = r#" { "value": 42, - "update_at": "2025-04-02T00:00:00.000000100+00:00", + "recorded_at": "2025-04-02T00:00:00.000000100+00:00", "labels": [ { "name": "label_name", @@ -372,7 +372,7 @@ mod tests { r#" { "value": 42, - "update_at": "1-1-2023T25:00:00Z", + "recorded_at": "1-1-2023T25:00:00Z", "labels": [ { "name": "label_name", diff --git a/packages/metrics/src/sample_collection.rs b/packages/metrics/src/sample_collection.rs index c6dc4e27d..436a4bc7d 100644 --- a/packages/metrics/src/sample_collection.rs +++ b/packages/metrics/src/sample_collection.rs @@ -89,7 +89,7 @@ impl Serialize for SampleCollection { let mut samples: Vec> = vec![]; for (label_set, sample_data) in &self.samples { - samples.push(Sample::new(sample_data.value(), sample_data.update_at(), label_set.clone())); + samples.push(Sample::new(sample_data.value(), sample_data.recorded_at(), label_set.clone())); } samples.serialize(serializer) @@ -317,7 +317,7 @@ mod tests { collection.increment(&label_set, new_time); let sample = collection.get(&label_set).unwrap(); - assert_eq!(sample.update_at(), new_time); + assert_eq!(sample.recorded_at(), new_time); assert_eq!(*sample.value(), Counter::new(2)); } @@ -392,7 +392,7 @@ mod tests { collection.set(&label_set, 2.0, new_time); let sample = collection.get(&label_set).unwrap(); - assert_eq!(sample.update_at(), new_time); + assert_eq!(sample.recorded_at(), new_time); assert_eq!(*sample.value(), Gauge::new(2.0)); } From 3ef9e13f0eb8f91bec853ce7f57df8acec5af976 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 11 Apr 2025 11:20:15 +0100 Subject: [PATCH 0941/1297] chore(deps): udpate dependencies ```output cargo update Updating crates.io index Locking 48 packages to latest compatible versions Updating async-compression v0.4.21 -> v0.4.22 Updating axum v0.8.1 -> v0.8.3 Updating axum-core v0.5.0 -> v0.5.2 Updating axum-extra v0.10.0 -> v0.10.1 Updating bigdecimal v0.4.7 -> v0.4.8 Updating borsh v1.5.6 -> v1.5.7 Updating borsh-derive v1.5.6 -> v1.5.7 Updating cc v1.2.17 -> v1.2.19 Updating clap v4.5.32 -> v4.5.35 Updating clap_builder v4.5.32 -> v4.5.35 Updating crossbeam-channel v0.5.14 -> v0.5.15 Updating darling v0.20.10 -> v0.20.11 Updating darling_core v0.20.10 -> v0.20.11 Updating darling_macro v0.20.10 -> v0.20.11 Downgrading deranged v0.4.1 -> v0.4.0 Updating errno v0.3.10 -> v0.3.11 Updating event-listener-strategy v0.5.3 -> v0.5.4 Updating flate2 v1.1.0 -> v1.1.1 Updating fragile v2.0.0 -> v2.0.1 Updating half v2.5.0 -> v2.6.0 Updating hyper-util v0.1.10 -> v0.1.11 Updating iana-time-zone v0.1.62 -> v0.1.63 Updating icu_locid_transform_data v1.5.0 -> v1.5.1 Updating icu_normalizer_data v1.5.0 -> v1.5.1 Updating icu_properties_data v1.5.0 -> v1.5.1 Updating indexmap v2.8.0 -> v2.9.0 Updating jobserver v0.1.32 -> v0.1.33 Updating linux-raw-sys v0.9.3 -> v0.9.4 Updating log v0.4.26 -> v0.4.27 Updating miniz_oxide v0.8.5 -> v0.8.8 Updating once_cell v1.21.1 -> v1.21.3 Updating openssl v0.10.71 -> v0.10.72 Updating openssl-sys v0.9.106 -> v0.9.107 Adding portable-atomic-util v0.2.4 Updating redox_syscall v0.5.10 -> v0.5.11 Updating ringbuf v0.4.7 -> v0.4.8 Updating rustix v1.0.3 -> v1.0.5 Updating rustls v0.23.25 -> v0.23.26 Updating rustls-webpki v0.103.0 -> v0.103.1 Updating smallvec v1.14.0 -> v1.15.0 Updating socket2 v0.5.8 -> v0.5.9 Updating tokio v1.44.1 -> v1.44.2 Updating value-bag v1.10.0 -> v1.11.1 Updating windows-core v0.52.0 -> v0.61.0 Adding windows-implement v0.60.0 Adding windows-interface v0.59.1 Adding windows-strings v0.4.0 Updating winnow v0.7.4 -> v0.7.6 ``` --- Cargo.lock | 252 +++++++++++++++++++++++++++++++---------------------- 1 file changed, 150 insertions(+), 102 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5feea957d..c3fb651ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -217,9 +217,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.21" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0cf008e5e1a9e9e22a7d3c9a4992e21a350290069e36d8fb72304ed17e8f2d2" +checksum = "59a194f9d963d8099596278594b3107448656ba73831c9d8c783e613ce86da64" dependencies = [ "brotli", "flate2", @@ -357,9 +357,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "axum" -version = "0.8.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d6fd624c75e18b3b4c6b9caf42b1afe24437daaee904069137d8bab077be8b8" +checksum = "de45108900e1f9b9242f7f2e254aa3e2c029c921c258fe9e6b4217eeebd54288" dependencies = [ "axum-core", "axum-macros", @@ -403,12 +403,12 @@ dependencies = [ [[package]] name = "axum-core" -version = "0.5.0" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df1362f362fd16024ae199c1970ce98f9661bf5ef94b9808fee734bc3698b733" +checksum = "68464cd0412f486726fb3373129ef5d2993f90c34bc2bc1c1e9943b2f4fc7ca6" dependencies = [ "bytes", - "futures-util", + "futures-core", "http", "http-body", "http-body-util", @@ -423,9 +423,9 @@ dependencies = [ [[package]] name = "axum-extra" -version = "0.10.0" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460fc6f625a1f7705c6cf62d0d070794e94668988b1c38111baeec177c715f7b" +checksum = "45bf463831f5131b7d3c756525b305d40f1185b688565648a92e1392ca35713d" dependencies = [ "axum", "axum-core", @@ -437,6 +437,7 @@ dependencies = [ "http-body-util", "mime", "pin-project-lite", + "rustversion", "serde", "serde_html_form", "serde_path_to_error", @@ -516,9 +517,9 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "bigdecimal" -version = "0.4.7" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f31f3af01c5c65a07985c804d3366560e6fa7883d640a122819b14ec327482c" +checksum = "1a22f228ab7a1b23027ccc6c350b72868017af7ea8356fbdf19f8d991c690013" dependencies = [ "autocfg", "libm", @@ -822,9 +823,9 @@ dependencies = [ [[package]] name = "borsh" -version = "1.5.6" +version = "1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b74d67a0fc0af8e9823b79fd1c43a0900e5a8f0e0f4cc9210796bf3a820126" +checksum = "ad8646f98db542e39fc66e68a20b2144f6a732636df7c2354e74645faaa433ce" dependencies = [ "borsh-derive", "cfg_aliases", @@ -832,9 +833,9 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.5.6" +version = "1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d37ed1b2c9b78421218a0b4f6d8349132d6ec2cfeba1cfb0118b0a8e268df9e" +checksum = "fdd1d3c0c2f5833f22386f252fe8ed005c7f59fdcddeef025c01b4c3b9fd9ac3" dependencies = [ "once_cell", "proc-macro-crate", @@ -951,9 +952,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.17" +version = "1.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fcb57c740ae1daf453ae85f16e37396f672b039e00d9d866e07ddb24e328e3a" +checksum = "8e3a13707ac958681c13b39b458c073d0d9bc8a22cb1b2f4c8e55eb72c13f362" dependencies = [ "jobserver", "libc", @@ -1044,9 +1045,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.32" +version = "4.5.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6088f3ae8c3608d19260cd7445411865a485688711b78b5be70d78cd96136f83" +checksum = "d8aa86934b44c19c50f87cc2790e19f54f7a67aedb64101c2e1a2e5ecfb73944" dependencies = [ "clap_builder", "clap_derive", @@ -1054,9 +1055,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.32" +version = "4.5.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22a7ef7f676155edfb82daa97f99441f3ebf4a58d5e32f295a56259f1b6facc8" +checksum = "2414dbb2dd0695280da6ea9261e327479e9d37b0630f6b53ba2a11c60c679fd9" dependencies = [ "anstream", "anstyle", @@ -1216,9 +1217,9 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.14" +version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06ba6d68e24814cb8de6bb986db8222d3a027d15872cabc0d18817bc3c0e4471" +checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" dependencies = [ "crossbeam-utils", ] @@ -1285,9 +1286,9 @@ dependencies = [ [[package]] name = "darling" -version = "0.20.10" +version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" dependencies = [ "darling_core", "darling_macro", @@ -1295,9 +1296,9 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.20.10" +version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95133861a8032aaea082871032f5815eb9e98cef03fa916ab4500513994df9e5" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" dependencies = [ "fnv", "ident_case", @@ -1309,9 +1310,9 @@ dependencies = [ [[package]] name = "darling_macro" -version = "0.20.10" +version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ "darling_core", "quote", @@ -1334,9 +1335,9 @@ dependencies = [ [[package]] name = "deranged" -version = "0.4.1" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cfac68e08048ae1883171632c2aef3ebc555621ae56fbccce1cbf22dd7f058" +checksum = "9c9e6a11ca8224451684bc0d7d5a7adbf8f2fd6887261a1cfc3c0432f9d4068e" dependencies = [ "powerfmt", "serde", @@ -1451,9 +1452,9 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" -version = "0.3.10" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" +checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e" dependencies = [ "libc", "windows-sys 0.59.0", @@ -1489,9 +1490,9 @@ dependencies = [ [[package]] name = "event-listener-strategy" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c3e4e0dd3673c1139bf041f3008816d9cf2946bbfac2945c09e523b8d7b05b2" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" dependencies = [ "event-listener 5.4.0", "pin-project-lite", @@ -1545,9 +1546,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11faaf5a5236997af9848be0bef4db95824b1d534ebc64d0f0c6cf3e67bd38dc" +checksum = "7ced92e76e966ca2fd84c8f7aa01a4aea65b0eb6648d72f7c8f3e2764a67fece" dependencies = [ "crc32fast", "libz-sys", @@ -1612,9 +1613,9 @@ dependencies = [ [[package]] name = "fragile" -version = "2.0.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" +checksum = "28dd6caf6059519a65843af8fe2a3ae298b14b80179855aeb4adc2c1934ee619" [[package]] name = "frunk" @@ -1865,7 +1866,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.8.0", + "indexmap 2.9.0", "slab", "tokio", "tokio-util", @@ -1874,9 +1875,9 @@ dependencies = [ [[package]] name = "half" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7db2ff139bba50379da6aa0766b52fdcb62cb5b263009b09ed58ba604e14bbd1" +checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9" dependencies = [ "cfg-if", "crunchy", @@ -2073,9 +2074,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.10" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df2dcfbe0677734ab2f3ffa7fa7bfd4706bfdc1ef393f2ee30184aed67e631b4" +checksum = "497bbc33a26fdd4af9ed9c70d63f61cf56a938375fbb32df34db9b1cd6d643f2" dependencies = [ "bytes", "futures-channel", @@ -2083,6 +2084,7 @@ dependencies = [ "http", "http-body", "hyper", + "libc", "pin-project-lite", "socket2", "tokio", @@ -2107,9 +2109,9 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.62" +version = "0.1.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2fd658b06e56721792c5df4475705b6cda790e9298d19d2f8af083457bcd127" +checksum = "b0c919e5debc312ad217002b8048a17b7d83f80703865bbfcfebb0458b0b27d8" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -2170,9 +2172,9 @@ dependencies = [ [[package]] name = "icu_locid_transform_data" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e" +checksum = "7515e6d781098bf9f7205ab3fc7e9709d34554ae0b21ddbcb5febfa4bc7df11d" [[package]] name = "icu_normalizer" @@ -2194,9 +2196,9 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516" +checksum = "c5e8338228bdc8ab83303f16b797e177953730f601a96c25d10cb3ab0daa0cb7" [[package]] name = "icu_properties" @@ -2215,9 +2217,9 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569" +checksum = "85fb8799753b75aee8d2a21d7c14d9f38921b54b3dbda10f5a3c7a7b82dba5e2" [[package]] name = "icu_provider" @@ -2287,9 +2289,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.8.0" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3954d50fe15b02142bf25d3b8bdadb634ec3948f103d04ffe3031bc8fe9d7058" +checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e" dependencies = [ "equivalent", "hashbrown 0.15.2", @@ -2375,10 +2377,11 @@ checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "jobserver" -version = "0.1.32" +version = "0.1.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0" +checksum = "38f262f097c174adebe41eb73d66ae9c06b2844fb0da69969647bbddd9b0538a" dependencies = [ + "getrandom 0.3.2", "libc", ] @@ -2437,7 +2440,7 @@ checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ "bitflags 2.9.0", "libc", - "redox_syscall 0.5.10", + "redox_syscall 0.5.11", ] [[package]] @@ -2470,9 +2473,9 @@ checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] name = "linux-raw-sys" -version = "0.9.3" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe7db12097d22ec582439daf8618b8fdd1a7bef6270e9af3b1ebcd30893cf413" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" [[package]] name = "litemap" @@ -2504,9 +2507,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.26" +version = "0.4.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e" +checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" dependencies = [ "value-bag", ] @@ -2577,9 +2580,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.8.5" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e3e04debbb59698c15bacbb6d93584a8c0ca9cc3213cb423d31f760d8843ce5" +checksum = "3be647b768db090acb35d5ec5db2b0e1f1de11133ca123b9eacf5137868f892a" dependencies = [ "adler2", ] @@ -2834,9 +2837,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.21.1" +version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d75b0bedcc4fe52caa0e03d9f1151a323e4aa5e2d78ba3580400cd3c9e2bc4bc" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] name = "oorandom" @@ -2846,9 +2849,9 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "openssl" -version = "0.10.71" +version = "0.10.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e14130c6a98cd258fdcb0fb6d744152343ff729cbfcb28c656a9d12b999fbcd" +checksum = "fedfea7d58a1f73118430a55da6a286e7b044961736ce96a16a17068ea25e5da" dependencies = [ "bitflags 2.9.0", "cfg-if", @@ -2878,9 +2881,9 @@ checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" [[package]] name = "openssl-sys" -version = "0.9.106" +version = "0.9.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bb61ea9811cc39e3c2069f40b8b8e2e70d8569b361f879786cc7ed48b777cdd" +checksum = "8288979acd84749c744a9014b4382d42b8f7b2592847b5afb2ed29e5d16ede07" dependencies = [ "cc", "libc", @@ -2924,7 +2927,7 @@ checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.10", + "redox_syscall 0.5.11", "smallvec", "windows-targets 0.52.6", ] @@ -3109,6 +3112,15 @@ version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e" +[[package]] +name = "portable-atomic-util" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507" +dependencies = [ + "portable-atomic", +] + [[package]] name = "powerfmt" version = "0.2.0" @@ -3388,9 +3400,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.10" +version = "0.5.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b8c0c260b63a8219631167be35e6a988e9554dbd323f8bd08439c8ed1302bd1" +checksum = "d2f103c6d277498fbceb16e84d317e2a400f160f46904d5f5410848c829511a3" dependencies = [ "bitflags 2.9.0", ] @@ -3499,12 +3511,13 @@ dependencies = [ [[package]] name = "ringbuf" -version = "0.4.7" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "726bb493fe9cac765e8f96a144c3a8396bdf766dedad22e504b70b908dcbceb4" +checksum = "fe47b720588c8702e34b5979cb3271a8b1842c7cb6f57408efa70c779363488c" dependencies = [ "crossbeam-utils", "portable-atomic", + "portable-atomic-util", ] [[package]] @@ -3632,22 +3645,22 @@ dependencies = [ [[package]] name = "rustix" -version = "1.0.3" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e56a18552996ac8d29ecc3b190b4fdbb2d91ca4ec396de7bbffaf43f3d637e96" +checksum = "d97817398dd4bb2e6da002002db259209759911da105da92bec29ccb12cf58bf" dependencies = [ "bitflags 2.9.0", "errno", "libc", - "linux-raw-sys 0.9.3", + "linux-raw-sys 0.9.4", "windows-sys 0.59.0", ] [[package]] name = "rustls" -version = "0.23.25" +version = "0.23.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "822ee9188ac4ec04a2f0531e55d035fb2de73f18b41a63c70c2712503b6fb13c" +checksum = "df51b5869f3a441595eac5e8ff14d486ff285f7b8c0df8770e49c3b56351f0f0" dependencies = [ "once_cell", "ring", @@ -3686,9 +3699,9 @@ checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c" [[package]] name = "rustls-webpki" -version = "0.103.0" +version = "0.103.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aa4eeac2588ffff23e9d7a7e9b3f971c5fb5b7ebc9452745e0c232c64f83b2f" +checksum = "fef8b8769aaccf73098557a87cd1816b4f9c7c16811c9c77142aa695c16f2c03" dependencies = [ "ring", "rustls-pki-types", @@ -3840,7 +3853,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d2de91cf02bbc07cde38891769ccd5d4f073d22a40683aa4bc7a95781aaa2c4" dependencies = [ "form_urlencoded", - "indexmap 2.8.0", + "indexmap 2.9.0", "itoa", "ryu", "serde", @@ -3852,7 +3865,7 @@ version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" dependencies = [ - "indexmap 2.8.0", + "indexmap 2.9.0", "itoa", "memchr", "ryu", @@ -3911,7 +3924,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.8.0", + "indexmap 2.9.0", "serde", "serde_derive", "serde_json", @@ -4000,15 +4013,15 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.14.0" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcf8323ef1faaee30a44a340193b1ac6814fd9b7b4e88e9d4519a3e4abe1cfd" +checksum = "8917285742e9f3e1683f0a9c4e6b57960b7314d0b08d30d1ecd426713ee2eee9" [[package]] name = "socket2" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c970269d99b64e60ec3bd6ad27270092a5394c4e309314b18ae3fe575695fbe8" +checksum = "4f5fd57c80058a56cf5c777ab8a126398ece8e442983605d280a44ce79d0edef" dependencies = [ "libc", "windows-sys 0.52.0", @@ -4187,7 +4200,7 @@ dependencies = [ "fastrand", "getrandom 0.3.2", "once_cell", - "rustix 1.0.3", + "rustix 1.0.5", "windows-sys 0.59.0", ] @@ -4206,7 +4219,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45c6481c4829e4cc63825e62c49186a34538b7b2750b73b266581ffb612fb5ed" dependencies = [ - "rustix 1.0.3", + "rustix 1.0.5", "windows-sys 0.59.0", ] @@ -4373,9 +4386,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.44.1" +version = "1.44.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f382da615b842244d4b8738c82ed1275e6c5dd90c459a30941cd07080b06c91a" +checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48" dependencies = [ "backtrace", "bytes", @@ -4485,7 +4498,7 @@ version = "0.22.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17b4795ff5edd201c7cd6dca065ae59972ce77d1b80fa0a84d94950ece7d1474" dependencies = [ - "indexmap 2.8.0", + "indexmap 2.9.0", "serde", "serde_spanned", "toml_datetime", @@ -5096,9 +5109,9 @@ checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" [[package]] name = "value-bag" -version = "1.10.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ef4c4aa54d5d05a279399bfa921ec387b7aba77caf7a682ae8d86785b8fdad2" +checksum = "943ce29a8a743eb10d6082545d861b24f9d1b160b7d741e0f2cdf726bec909c5" [[package]] name = "vcpkg" @@ -5260,11 +5273,37 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-core" -version = "0.52.0" +version = "0.61.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +checksum = "4763c1de310c86d75a878046489e2e5ba02c649d185f21c67d4cf8a56d098980" dependencies = [ - "windows-targets 0.52.6", + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings 0.4.0", +] + +[[package]] +name = "windows-implement" +version = "0.60.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.100", +] + +[[package]] +name = "windows-interface" +version = "0.59.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.100", ] [[package]] @@ -5280,7 +5319,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4286ad90ddb45071efd1a66dfa43eb02dd0dfbae1545ad6cc3c51cf34d7e8ba3" dependencies = [ "windows-result", - "windows-strings", + "windows-strings 0.3.1", "windows-targets 0.53.0", ] @@ -5302,6 +5341,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-strings" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2ba9642430ee452d5a7aa78d72907ebe8cfda358e8cb7918a2050581322f97" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-sys" version = "0.48.0" @@ -5516,9 +5564,9 @@ checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" [[package]] name = "winnow" -version = "0.7.4" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e97b544156e9bebe1a0ffbc03484fc1ffe3100cbce3ffb17eac35f7cdd7ab36" +checksum = "63d3fcd9bba44b03821e7d699eeee959f3126dcc4aa8e4ae18ec617c2a5cea10" dependencies = [ "memchr", ] @@ -5560,7 +5608,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d65cbf2f12c15564212d48f4e3dfb87923d25d611f2aed18f4cb23f0413d89e" dependencies = [ "libc", - "rustix 1.0.3", + "rustix 1.0.5", ] [[package]] From 4205c7184d32c3bf953101d8bad335ad12025a55 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 11 Apr 2025 15:58:56 +0100 Subject: [PATCH 0942/1297] fix: [#1441] do not reveal API token in logs --- src/container.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/container.rs b/src/container.rs index 7742d8e40..9df9c9611 100644 --- a/src/container.rs +++ b/src/container.rs @@ -38,7 +38,7 @@ pub struct AppContainer { } impl AppContainer { - #[instrument(skip())] + #[instrument(skip(configuration))] pub fn initialize(configuration: &Configuration) -> AppContainer { // Configuration From 15a34c7fa3aa3d2cf28d8e42c3529bd9135a5b92 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 11 Apr 2025 16:15:29 +0100 Subject: [PATCH 0943/1297] feat: [#1438] merge UDP tracker core metrics Extract `request_kind` label. Putting the request type in the metric name does not make sense. The purpose of the refactor to build the new extendable-labeled metrics was to start using labels to group metrics instead of changes in metric's names. From this: ``` udp_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="6969",server_binding_protocol="udp"} 619656 udp_tracker_core_connect_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="6969",server_binding_protocol="udp"} 308493 udp_tracker_core_scrape_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="6969",server_binding_protocol="udp"} 32487 ``` To this: ``` udp_tracker_core_requests_received_total{request_kind="announce",server_binding_ip="0.0.0.0",server_binding_port="6969",server_binding_protocol="udp"} 619656 udp_tracker_core_requests_received_total{request_kind="connect",server_binding_ip="0.0.0.0",server_binding_port="6969",server_binding_protocol="udp"} 308493 udp_tracker_core_requests_received_total{request_kind="scrape",server_binding_ip="0.0.0.0",server_binding_port="6969",server_binding_protocol="udp"} 32487 ``` --- .../src/statistics/event/handler.rs | 30 +++++++++---------- .../udp-tracker-core/src/statistics/mod.rs | 18 +++-------- 2 files changed, 18 insertions(+), 30 deletions(-) diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index a910d9373..59c382755 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -1,9 +1,10 @@ -use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; use torrust_tracker_metrics::metric::MetricName; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; /// # Panics /// @@ -24,12 +25,11 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics + let mut label_set = LabelSet::from(context); + label_set.upsert(LabelName::new("request_kind"), LabelValue::new("connect")); + stats_repository - .increase_counter( - &MetricName::new("udp_tracker_core_connect_requests_received_total"), - &LabelSet::from(context), - now, - ) + .increase_counter(&MetricName::new(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) .await; } Event::UdpAnnounce { context } => { @@ -46,12 +46,11 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics + let mut label_set = LabelSet::from(context); + label_set.upsert(LabelName::new("request_kind"), LabelValue::new("announce")); + stats_repository - .increase_counter( - &MetricName::new("udp_tracker_core_announce_requests_received_total"), - &LabelSet::from(context), - now, - ) + .increase_counter(&MetricName::new(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) .await; } Event::UdpScrape { context } => { @@ -68,12 +67,11 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics + let mut label_set = LabelSet::from(context); + label_set.upsert(LabelName::new("request_kind"), LabelValue::new("scrape")); + stats_repository - .increase_counter( - &MetricName::new("udp_tracker_core_scrape_requests_received_total"), - &LabelSet::from(context), - now, - ) + .increase_counter(&MetricName::new(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) .await; } } diff --git a/packages/udp-tracker-core/src/statistics/mod.rs b/packages/udp-tracker-core/src/statistics/mod.rs index cdba76df3..bc4d8d836 100644 --- a/packages/udp-tracker-core/src/statistics/mod.rs +++ b/packages/udp-tracker-core/src/statistics/mod.rs @@ -10,26 +10,16 @@ use torrust_tracker_metrics::metric::description::MetricDescription; use torrust_tracker_metrics::metric::MetricName; use torrust_tracker_metrics::unit::Unit; +const UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL: &str = "udp_tracker_core_requests_received_total"; + #[must_use] pub fn describe_metrics() -> Metrics { let mut metrics = Metrics::default(); metrics.metric_collection.describe_counter( - &MetricName::new("udp_tracker_core_connect_requests_received_total"), - Some(Unit::Count), - Some(MetricDescription::new("Total number of UDP connect requests received")), - ); - - metrics.metric_collection.describe_counter( - &MetricName::new("udp_tracker_core_announce_requests_received_total"), - Some(Unit::Count), - Some(MetricDescription::new("Total number of UDP announce requests received")), - ); - - metrics.metric_collection.describe_counter( - &MetricName::new("udp_tracker_core_scrape_requests_received_total"), + &MetricName::new(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), - Some(MetricDescription::new("Total number of UDP scrape requests received")), + Some(MetricDescription::new("Total number of UDP requests received")), ); metrics From 44c700d3bc8c0f8e5457b75de12fdf14cc80fb58 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 11 Apr 2025 16:27:40 +0100 Subject: [PATCH 0944/1297] feat: [#1438] merge UDP tracker core metrics Extract `request_kind` label. Putting the request type in the metric name does not make sense. The purpose of the refactor to build the new extendable-labeled metrics was to start using labels to group metrics instead of changes in metric's names. From this: ``` http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 http_tracker_core_scrape_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 ``` To this: ``` http_tracker_core_requests_received_total{request_kind="announce",server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 http_tracker_core_requests_received_total{request_kind="scrape", server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 ``` --- .../src/statistics/event/handler.rs | 21 +++++++++---------- .../http-tracker-core/src/statistics/mod.rs | 12 ++++------- 2 files changed, 14 insertions(+), 19 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index 046cb7775..0baec1cd9 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -1,11 +1,12 @@ use std::net::IpAddr; -use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; use torrust_tracker_metrics::metric::MetricName; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; use crate::statistics::repository::Repository; +use crate::statistics::HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; /// # Panics /// @@ -27,12 +28,11 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics + let mut label_set = LabelSet::from(connection); + label_set.upsert(LabelName::new("request_kind"), LabelValue::new("announce")); + stats_repository - .increase_counter( - &MetricName::new("http_tracker_core_announce_requests_received_total"), - &LabelSet::from(connection), - now, - ) + .increase_counter(&MetricName::new(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) .await; } Event::TcpScrape { connection } => { @@ -49,12 +49,11 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics + let mut label_set = LabelSet::from(connection); + label_set.upsert(LabelName::new("request_kind"), LabelValue::new("scrape")); + stats_repository - .increase_counter( - &MetricName::new("http_tracker_core_scrape_requests_received_total"), - &LabelSet::from(connection), - now, - ) + .increase_counter(&MetricName::new(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) .await; } } diff --git a/packages/http-tracker-core/src/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs index 8148df3c1..026c435af 100644 --- a/packages/http-tracker-core/src/statistics/mod.rs +++ b/packages/http-tracker-core/src/statistics/mod.rs @@ -10,20 +10,16 @@ use torrust_tracker_metrics::metric::description::MetricDescription; use torrust_tracker_metrics::metric::MetricName; use torrust_tracker_metrics::unit::Unit; +const HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL: &str = "http_tracker_core_requests_received_total"; + #[must_use] pub fn describe_metrics() -> Metrics { let mut metrics = Metrics::default(); metrics.metric_collection.describe_counter( - &MetricName::new("http_tracker_core_announce_requests_received_total"), - Some(Unit::Count), - Some(MetricDescription::new("Total number of HTTP announce requests received")), - ); - - metrics.metric_collection.describe_counter( - &MetricName::new("http_tracker_core_scrape_requests_received_total"), + &MetricName::new(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), - Some(MetricDescription::new("Total number of HTTP scrape requests received")), + Some(MetricDescription::new("Total number of HTTP requests received")), ); metrics From 5f57f7889f60dc862b3bcdc05e8c88255643a82c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 11 Apr 2025 16:53:22 +0100 Subject: [PATCH 0945/1297] feat: [#1438] merge UDP tracker server metrics - Rename label `kind` to `request_kind`. It's more explicit. There could be other "kind" of things in the future. - Remove the empty label `kind=""` when the response is an error. - Fix result label for error response. - Merge performace metrics in one and convert request kind into a label: ``` udp_tracker_server_performance_avg_connect_processing_time_ns{request_kind="connect"} udp_tracker_server_performance_avg_connect_processing_time_ns{request_kind="announce"} udp_tracker_server_performance_avg_connect_processing_time_ns{request_kind="scrape"} ``` --- .../src/statistics/event/handler.rs | 56 ++++++++++++------- .../udp-tracker-server/src/statistics/mod.rs | 38 +++++-------- 2 files changed, 51 insertions(+), 43 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 91f5cef0c..4c10576c0 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -4,6 +4,12 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::{Event, UdpRequestKind, UdpResponseKind}; use crate::statistics::repository::Repository; +use crate::statistics::{ + UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, + UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL, + UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL, + UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL, +}; /// # Panics /// @@ -19,7 +25,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics stats_repository .increase_counter( - &MetricName::new("udp_tracker_server_requests_aborted_total"), + &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &LabelSet::from(context), now, ) @@ -32,7 +38,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics stats_repository .increase_counter( - &MetricName::new("udp_tracker_server_requests_banned_total"), + &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), &LabelSet::from(context), now, ) @@ -52,7 +58,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics stats_repository .increase_counter( - &MetricName::new("udp_tracker_server_requests_received_total"), + &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &LabelSet::from(context), now, ) @@ -94,11 +100,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura label_set.upsert(LabelName::new("kind"), LabelValue::new(&kind.to_string())); stats_repository - .increase_counter( - &MetricName::new("udp_tracker_server_requests_accepted_total"), - &label_set, - now, - ) + .increase_counter(&MetricName::new(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &label_set, now) .await; } Event::UdpResponseSent { @@ -124,10 +126,14 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura .await; // Extendable metrics + + let mut label_set = LabelSet::from(context.clone()); + label_set.upsert(LabelName::new("request_kind"), LabelValue::new(&req_kind.to_string())); + stats_repository .set_gauge( - &MetricName::new("udp_tracker_server_performance_avg_connect_processing_time_ns"), - &LabelSet::from(context.clone()), + &MetricName::new(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &label_set, new_avg, now, ) @@ -141,16 +147,20 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura .await; // Extendable metrics + + let mut label_set = LabelSet::from(context.clone()); + label_set.upsert(LabelName::new("request_kind"), LabelValue::new(&req_kind.to_string())); + stats_repository .set_gauge( - &MetricName::new("udp_tracker_server_performance_avg_announce_processing_time_ns"), - &LabelSet::from(context.clone()), + &MetricName::new(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &label_set, new_avg, now, ) .await; - (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Connect.to_string())) + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Announce.to_string())) } UdpRequestKind::Scrape => { let new_avg = stats_repository @@ -158,30 +168,36 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura .await; // Extendable metrics + + let mut label_set = LabelSet::from(context.clone()); + label_set.upsert(LabelName::new("request_kind"), LabelValue::new(&req_kind.to_string())); + stats_repository .set_gauge( - &MetricName::new("udp_tracker_server_performance_avg_scrape_processing_time_ns"), - &LabelSet::from(context.clone()), + &MetricName::new(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &label_set, new_avg, now, ) .await; - (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Connect.to_string())) + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Scrape.to_string())) } }, - UdpResponseKind::Error { opt_req_kind: _ } => (LabelValue::new("ok"), LabelValue::ignore()), + UdpResponseKind::Error { opt_req_kind: _ } => (LabelValue::new("error"), LabelValue::ignore()), }; // Extendable metrics let mut label_set = LabelSet::from(context); + if result_label_value == LabelValue::new("ok") { + label_set.upsert(LabelName::new("request_kind"), kind_label_value); + } label_set.upsert(LabelName::new("result"), result_label_value); - label_set.upsert(LabelName::new("kind"), kind_label_value); stats_repository - .increase_counter(&MetricName::new("udp_tracker_server_responses_sent_total"), &label_set, now) + .increase_counter(&MetricName::new(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &label_set, now) .await; } Event::UdpError { context } => { @@ -198,7 +214,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics stats_repository .increase_counter( - &MetricName::new("udp_tracker_server_errors_total"), + &MetricName::new(UDP_TRACKER_SERVER_ERRORS_TOTAL), &LabelSet::from(context), now, ) diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index 535031483..523cd4bac 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -10,69 +10,61 @@ use torrust_tracker_metrics::metric::description::MetricDescription; use torrust_tracker_metrics::metric::MetricName; use torrust_tracker_metrics::unit::Unit; +const UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL: &str = "udp_tracker_server_requests_aborted_total"; +const UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL: &str = "udp_tracker_server_requests_banned_total"; +const UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL: &str = "udp_tracker_server_requests_received_total"; +const UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL: &str = "udp_tracker_server_requests_accepted_total"; +const UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL: &str = "udp_tracker_server_responses_sent_total"; +const UDP_TRACKER_SERVER_ERRORS_TOTAL: &str = "udp_tracker_server_errors_total"; +const UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS: &str = "udp_tracker_server_performance_avg_processing_time_ns"; + #[must_use] pub fn describe_metrics() -> Metrics { let mut metrics = Metrics::default(); metrics.metric_collection.describe_counter( - &MetricName::new("udp_tracker_server_requests_aborted_total"), + &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of UDP requests aborted")), ); metrics.metric_collection.describe_counter( - &MetricName::new("udp_tracker_server_requests_banned_total"), + &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of UDP requests banned")), ); metrics.metric_collection.describe_counter( - &MetricName::new("udp_tracker_server_requests_received_total"), + &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of UDP requests received")), ); metrics.metric_collection.describe_counter( - &MetricName::new("udp_tracker_server_requests_accepted_total"), + &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of UDP requests accepted")), ); metrics.metric_collection.describe_counter( - &MetricName::new("udp_tracker_server_responses_sent_total"), + &MetricName::new(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of UDP responses sent")), ); metrics.metric_collection.describe_counter( - &MetricName::new("udp_tracker_server_errors_total"), + &MetricName::new(UDP_TRACKER_SERVER_ERRORS_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of errors processing UDP requests")), ); metrics.metric_collection.describe_gauge( - &MetricName::new("udp_tracker_server_performance_avg_connect_processing_time_ns"), + &MetricName::new(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), Some(Unit::Nanoseconds), Some(MetricDescription::new( "Average time to process a UDP connect request in nanoseconds", )), ); - metrics.metric_collection.describe_gauge( - &MetricName::new("udp_tracker_server_performance_avg_announce_processing_time_ns"), - Some(Unit::Nanoseconds), - Some(MetricDescription::new( - "Average time to process a UDP announce request in nanoseconds", - )), - ); - - metrics.metric_collection.describe_gauge( - &MetricName::new("udp_tracker_server_performance_avg_scrape_processing_time_ns"), - Some(Unit::Nanoseconds), - Some(MetricDescription::new( - "Average time to process a UDP scrape request in nanoseconds", - )), - ); - metrics } From ed8acac48e2ac538dc6e959d35c22badaae8d683 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 14 Apr 2025 11:12:54 +0100 Subject: [PATCH 0946/1297] fix: [#1449] increase broadcast channel capacity for events channel to avoid lagged listeners. This does not fix the problem. Stats listener migth loose events and keep imprecise metrics. --- packages/http-tracker-core/src/event/sender.rs | 2 +- packages/udp-tracker-core/src/event/sender.rs | 2 +- packages/udp-tracker-server/src/event/sender.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/http-tracker-core/src/event/sender.rs b/packages/http-tracker-core/src/event/sender.rs index e9431abf2..511a381d0 100644 --- a/packages/http-tracker-core/src/event/sender.rs +++ b/packages/http-tracker-core/src/event/sender.rs @@ -7,7 +7,7 @@ use tokio::sync::broadcast::error::SendError; use super::Event; -const CHANNEL_CAPACITY: usize = 1024; +const CHANNEL_CAPACITY: usize = 32768; /// A trait for sending sending. #[cfg_attr(test, automock)] diff --git a/packages/udp-tracker-core/src/event/sender.rs b/packages/udp-tracker-core/src/event/sender.rs index e9431abf2..511a381d0 100644 --- a/packages/udp-tracker-core/src/event/sender.rs +++ b/packages/udp-tracker-core/src/event/sender.rs @@ -7,7 +7,7 @@ use tokio::sync::broadcast::error::SendError; use super::Event; -const CHANNEL_CAPACITY: usize = 1024; +const CHANNEL_CAPACITY: usize = 32768; /// A trait for sending sending. #[cfg_attr(test, automock)] diff --git a/packages/udp-tracker-server/src/event/sender.rs b/packages/udp-tracker-server/src/event/sender.rs index e9431abf2..511a381d0 100644 --- a/packages/udp-tracker-server/src/event/sender.rs +++ b/packages/udp-tracker-server/src/event/sender.rs @@ -7,7 +7,7 @@ use tokio::sync::broadcast::error::SendError; use super::Event; -const CHANNEL_CAPACITY: usize = 1024; +const CHANNEL_CAPACITY: usize = 32768; /// A trait for sending sending. #[cfg_attr(test, automock)] From 6fdbc47d23fb4d246284a27721235134ac34038f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 14 Apr 2025 11:32:50 +0100 Subject: [PATCH 0947/1297] fix: [#1449] don't stop stats listeners when lagged If the stats listener is lagged we continue processing new events even if metrics become imprecise after it. This is a temporary solution. See https://github.com/torrust/torrust-tracker/issues/1449. --- packages/http-tracker-core/src/lib.rs | 2 ++ .../src/statistics/event/listener.rs | 14 +++++++++++--- .../src/statistics/event/listener.rs | 14 +++++++++++--- .../src/statistics/event/listener.rs | 13 +++++++++++-- src/bootstrap/jobs/torrent_cleanup.rs | 2 +- 5 files changed, 36 insertions(+), 9 deletions(-) diff --git a/packages/http-tracker-core/src/lib.rs b/packages/http-tracker-core/src/lib.rs index 2260242e0..c4f131bcb 100644 --- a/packages/http-tracker-core/src/lib.rs +++ b/packages/http-tracker-core/src/lib.rs @@ -16,6 +16,8 @@ pub(crate) type CurrentClock = clock::Working; #[allow(dead_code)] pub(crate) type CurrentClock = clock::Stopped; +pub const HTTP_TRACKER_LOG_TARGET: &str = "HTTP TRACKER"; + #[cfg(test)] pub(crate) mod tests { use bittorrent_primitives::info_hash::InfoHash; diff --git a/packages/http-tracker-core/src/statistics/event/listener.rs b/packages/http-tracker-core/src/statistics/event/listener.rs index ca53a20bb..5e87b47df 100644 --- a/packages/http-tracker-core/src/statistics/event/listener.rs +++ b/packages/http-tracker-core/src/statistics/event/listener.rs @@ -4,15 +4,23 @@ use torrust_tracker_clock::clock::Time; use super::handler::handle_event; use crate::event::Event; use crate::statistics::repository::Repository; -use crate::CurrentClock; +use crate::{CurrentClock, HTTP_TRACKER_LOG_TARGET}; pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { loop { match receiver.recv().await { Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, Err(e) => { - tracing::error!("Error receiving http tracker core event: {:?}", e); - break; + match e { + broadcast::error::RecvError::Closed => { + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Http core statistics receiver closed."); + break; + } + broadcast::error::RecvError::Lagged(n) => { + // From now on, metrics will be imprecise + tracing::warn!(target: HTTP_TRACKER_LOG_TARGET, "Http core statistics receiver lagged by {} events.", n); + } + } } } } diff --git a/packages/udp-tracker-core/src/statistics/event/listener.rs b/packages/udp-tracker-core/src/statistics/event/listener.rs index 8fc82fbcb..888fb8204 100644 --- a/packages/udp-tracker-core/src/statistics/event/listener.rs +++ b/packages/udp-tracker-core/src/statistics/event/listener.rs @@ -4,15 +4,23 @@ use torrust_tracker_clock::clock::Time; use super::handler::handle_event; use crate::event::Event; use crate::statistics::repository::Repository; -use crate::CurrentClock; +use crate::{CurrentClock, UDP_TRACKER_LOG_TARGET}; pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { loop { match receiver.recv().await { Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, Err(e) => { - tracing::error!("Error receiving udp tracker core event: {:?}", e); - break; + match e { + broadcast::error::RecvError::Closed => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp core statistics receiver closed."); + break; + } + broadcast::error::RecvError::Lagged(n) => { + // From now on, metrics will be imprecise + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp core statistics receiver lagged by {} events.", n); + } + } } } } diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index c50ce70c9..cf348ea17 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -1,3 +1,4 @@ +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use tokio::sync::broadcast; use torrust_tracker_clock::clock::Time; @@ -11,8 +12,16 @@ pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_rep match receiver.recv().await { Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, Err(e) => { - tracing::error!("Error receiving udp tracker server event: {:?}", e); - break; + match e { + broadcast::error::RecvError::Closed => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp server statistics receiver closed."); + break; + } + broadcast::error::RecvError::Lagged(n) => { + // From now on, metrics will be imprecise + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp server statistics receiver lagged by {} events.", n); + } + } } } } diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index 7085aa7e2..54b1eeef7 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -37,7 +37,7 @@ pub fn start_job(config: &Core, torrents_manager: &Arc) -> Join loop { tokio::select! { _ = tokio::signal::ctrl_c() => { - tracing::info!("Stopping torrent cleanup job.."); + tracing::info!("Stopping torrent cleanup job ..."); break; } _ = interval.tick() => { From bc9942f1823d16cc88c2aa43e3d0b39f0e0f2ee1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 14 Apr 2025 16:23:02 +0100 Subject: [PATCH 0948/1297] ci: [#1454] remove contract workflow Since we have moved most of the tests to workspace crates, the report only contains a few tests. Therefore, I think it's not useful anymore. It's consuming resources and making the execution of PR checks slower. --- .github/workflows/contract.yaml | 58 --------------------------------- 1 file changed, 58 deletions(-) delete mode 100644 .github/workflows/contract.yaml diff --git a/.github/workflows/contract.yaml b/.github/workflows/contract.yaml deleted file mode 100644 index 2777417e3..000000000 --- a/.github/workflows/contract.yaml +++ /dev/null @@ -1,58 +0,0 @@ -name: Contract - -on: - push: - pull_request: - -env: - CARGO_TERM_COLOR: always - -jobs: - contract: - name: Contract - runs-on: ubuntu-latest - - strategy: - matrix: - toolchain: [nightly, stable] - - steps: - - id: checkout - name: Checkout Repository - uses: actions/checkout@v4 - - - id: setup - name: Setup Toolchain - uses: dtolnay/rust-toolchain@stable - with: - toolchain: ${{ matrix.toolchain }} - components: llvm-tools-preview - - - id: cache - name: Enable Job Cache - uses: Swatinem/rust-cache@v2 - - - id: tools - name: Install Tools - uses: taiki-e/install-action@v2 - with: - tool: cargo-llvm-cov, cargo-nextest - - - id: pretty-test - name: Install pretty-test - run: cargo install cargo-pretty-test - - - id: contract - name: Run contract - run: | - cargo test --lib --bins - cargo pretty-test --lib --bins - - - id: summary - name: Generate contract Summary - run: | - echo "### Tracker Living Contract! :rocket:" >> $GITHUB_STEP_SUMMARY - cargo pretty-test --lib --bins --color=never >> $GITHUB_STEP_SUMMARY - echo '```console' >> $GITHUB_STEP_SUMMARY - echo "$OUTPUT" >> $GITHUB_STEP_SUMMARY - echo '```' >> $GITHUB_STEP_SUMMARY From c4239ebd3a121e4760c6ae43dcdd6dc6c5efdf87 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 14 Apr 2025 18:06:33 +0100 Subject: [PATCH 0949/1297] fix: [#1452] increase IP bans reset interval to 24 hours --- packages/udp-tracker-server/src/server/launcher.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index 5de41066f..d62a4d04e 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -23,7 +23,7 @@ use crate::server::bound_socket::BoundSocket; use crate::server::processor::Processor; use crate::server::receiver::Receiver; -const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 3600; +const IP_BANS_RESET_INTERVAL_IN_SECS: u64 = 3600 * 24; const TYPE_STRING: &str = "udp_tracker"; /// A UDP server instance launcher. From 8f2def13925e1497c0cdf493fcf584cfab38315c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 15 Apr 2025 09:32:57 +0100 Subject: [PATCH 0950/1297] chore(deps): udpate dependencies ``` cargo update Updating crates.io index Locking 5 packages to latest compatible versions Updating anyhow v1.0.97 -> v1.0.98 Updating clap v4.5.35 -> v4.5.36 Updating clap_builder v4.5.35 -> v4.5.36 Updating h2 v0.4.8 -> v0.4.9 Updating libc v0.2.171 -> v0.2.172 ``` --- Cargo.lock | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c3fb651ef..e05894e3c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -131,9 +131,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.97" +version = "1.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" +checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487" [[package]] name = "approx" @@ -1045,9 +1045,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.35" +version = "4.5.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8aa86934b44c19c50f87cc2790e19f54f7a67aedb64101c2e1a2e5ecfb73944" +checksum = "2df961d8c8a0d08aa9945718ccf584145eee3f3aa06cddbeac12933781102e04" dependencies = [ "clap_builder", "clap_derive", @@ -1055,9 +1055,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.35" +version = "4.5.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2414dbb2dd0695280da6ea9261e327479e9d37b0630f6b53ba2a11c60c679fd9" +checksum = "132dbda40fb6753878316a489d5a1242a8ef2f0d9e47ba01c951ea8aa7d013a5" dependencies = [ "anstream", "anstyle", @@ -1856,9 +1856,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.8" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5017294ff4bb30944501348f6f8e42e6ad28f42c8bbef7a74029aff064a4e3c2" +checksum = "75249d144030531f8dee69fe9cea04d3edf809a017ae445e2abdff6629e86633" dependencies = [ "atomic-waker", "bytes", @@ -2412,9 +2412,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.171" +version = "0.2.172" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" +checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" [[package]] name = "libloading" From fc14a818c820bb4249a0b83ec0b5128e946a2686 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 15 Apr 2025 10:59:45 +0100 Subject: [PATCH 0951/1297] refactor: [#1445] new macro to create metric names --- packages/metrics/src/metric/name.rs | 59 +++++++++++++---------------- 1 file changed, 27 insertions(+), 32 deletions(-) diff --git a/packages/metrics/src/metric/name.rs b/packages/metrics/src/metric/name.rs index c904f34d3..453d5c777 100644 --- a/packages/metrics/src/metric/name.rs +++ b/packages/metrics/src/metric/name.rs @@ -14,11 +14,7 @@ impl MetricName { /// Panics if the provided name is empty. #[must_use] pub fn new(name: &str) -> Self { - assert!( - !name.is_empty(), - "Metric name cannot be empty. It must have at least one character." - ); - + assert!(!name.is_empty(), "Metric name cannot be empty."); Self(name.to_owned()) } } @@ -50,43 +46,42 @@ impl PrometheusSerializable for MetricName { } } +#[macro_export] +macro_rules! metric_name { + ("") => { + compile_error!("Metric name cannot be empty"); + }; + ($name:literal) => { + $crate::metric::name::MetricName::new($name) + }; +} + #[cfg(test)] mod tests { mod serialization_of_metric_name_to_prometheus { - use rstest::rstest; - - use crate::metric::MetricName; use crate::prometheus::PrometheusSerializable; - #[rstest] - #[case("valid name", "valid_name", "valid_name")] - #[case("leading underscore", "_leading_underscore", "_leading_underscore")] - #[case("leading colon", ":leading_colon", ":leading_colon")] - #[case("leading lowercase", "v123", "v123")] - #[case("leading uppercase", "V123", "V123")] - fn valid_names_in_prometheus(#[case] case: &str, #[case] input: &str, #[case] output: &str) { - assert_eq!(MetricName::new(input).to_prometheus(), output, "{case} failed: {input:?}"); - } - - #[rstest] - #[case("invalid start 1", "9invalid_start", "_invalid_start")] - #[case("invalid start 2", "@test", "_test")] - #[case("invalid dash", "invalid-char", "invalid_char")] - #[case("invalid spaces", "spaces are bad", "spaces_are_bad")] - #[case("invalid special chars", "a!b@c#d$e%f^g&h*i(j)", "a_b_c_d_e_f_g_h_i_j_")] - #[case("invalid slash", "my:metric/version", "my:metric_version")] - #[case("all invalid characters", "!@#$%^&*()", "__________")] - #[case("non_ascii_characters", "ñaca©", "_aca_")] - fn names_that_need_changes_in_prometheus(#[case] case: &str, #[case] input: &str, #[case] output: &str) { - assert_eq!(MetricName::new(input).to_prometheus(), output, "{case} failed: {input:?}"); + #[test] + fn valid_names_in_prometheus() { + assert_eq!(metric_name!("valid_name").to_prometheus(), "valid_name"); + assert_eq!(metric_name!("_leading_underscore").to_prometheus(), "_leading_underscore"); + assert_eq!(metric_name!(":leading_colon").to_prometheus(), ":leading_colon"); + assert_eq!(metric_name!("v123").to_prometheus(), "v123"); // leading lowercase + assert_eq!(metric_name!("V123").to_prometheus(), "V123"); // leading lowercase } #[test] - #[should_panic(expected = "Metric name cannot be empty. It must have at least one character.")] - fn empty_name() { - let _name = MetricName::new(""); + fn names_that_need_changes_in_prometheus() { + assert_eq!(metric_name!("9invalid_start").to_prometheus(), "_invalid_start"); + assert_eq!(metric_name!("@test").to_prometheus(), "_test"); + assert_eq!(metric_name!("invalid-char").to_prometheus(), "invalid_char"); + assert_eq!(metric_name!("spaces are bad").to_prometheus(), "spaces_are_bad"); + assert_eq!(metric_name!("a!b@c#d$e%f^g&h*i(j)").to_prometheus(), "a_b_c_d_e_f_g_h_i_j_"); + assert_eq!(metric_name!("my:metric/version").to_prometheus(), "my:metric_version"); + assert_eq!(metric_name!("!@#$%^&*()").to_prometheus(), "__________"); + assert_eq!(metric_name!("ñaca©").to_prometheus(), "_aca_"); } } } From 5497970f86edbb6da3ae327d29e26eabd4c6b7bc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 15 Apr 2025 11:25:01 +0100 Subject: [PATCH 0952/1297] refactor: [#1445] replace metric name constructor by macro --- .../src/statistics/event/handler.rs | 6 +- .../http-tracker-core/src/statistics/mod.rs | 4 +- packages/metrics/src/metric/mod.rs | 17 ++-- packages/metrics/src/metric/name.rs | 3 + packages/metrics/src/metric_collection.rs | 79 +++++++++---------- .../src/statistics/event/handler.rs | 8 +- .../udp-tracker-core/src/statistics/mod.rs | 4 +- .../src/statistics/event/handler.rs | 24 +++--- .../udp-tracker-server/src/statistics/mod.rs | 16 ++-- 9 files changed, 79 insertions(+), 82 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index 0baec1cd9..6e37b0209 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -1,7 +1,7 @@ use std::net::IpAddr; use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; -use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; @@ -32,7 +32,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura label_set.upsert(LabelName::new("request_kind"), LabelValue::new("announce")); stats_repository - .increase_counter(&MetricName::new(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) + .increase_counter(&metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) .await; } Event::TcpScrape { connection } => { @@ -53,7 +53,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura label_set.upsert(LabelName::new("request_kind"), LabelValue::new("scrape")); stats_repository - .increase_counter(&MetricName::new(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) + .increase_counter(&metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) .await; } } diff --git a/packages/http-tracker-core/src/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs index 026c435af..a5d6d37a5 100644 --- a/packages/http-tracker-core/src/statistics/mod.rs +++ b/packages/http-tracker-core/src/statistics/mod.rs @@ -7,7 +7,7 @@ pub mod setup; use metrics::Metrics; use torrust_tracker_metrics::metric::description::MetricDescription; -use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_name; use torrust_tracker_metrics::unit::Unit; const HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL: &str = "http_tracker_core_requests_received_total"; @@ -17,7 +17,7 @@ pub fn describe_metrics() -> Metrics { let mut metrics = Metrics::default(); metrics.metric_collection.describe_counter( - &MetricName::new(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of HTTP requests received")), ); diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index edea035bb..95e35b520 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -87,11 +87,12 @@ mod tests { use super::super::*; use crate::gauge::Gauge; use crate::label::{LabelName, LabelValue}; + use crate::metric_name; use crate::sample::Sample; #[test] fn it_should_be_empty_when_it_does_not_have_any_sample() { - let name = MetricName::new("test_metric"); + let name = metric_name!("test_metric"); let samples = SampleCollection::::default(); @@ -103,7 +104,7 @@ mod tests { fn counter_metric_with_one_sample() -> Metric { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); - let name = MetricName::new("test_metric"); + let name = metric_name!("test_metric"); let label_set: LabelSet = [(LabelName::new("server_binding_protocol"), LabelValue::new("http"))].into(); @@ -119,7 +120,7 @@ mod tests { #[test] fn it_should_return_zero_number_of_samples_for_an_empty_metric() { - let name = MetricName::new("test_metric"); + let name = metric_name!("test_metric"); let samples = SampleCollection::::default(); @@ -133,11 +134,12 @@ mod tests { use super::super::*; use crate::counter::Counter; use crate::label::{LabelName, LabelValue}; + use crate::metric_name; use crate::sample::Sample; #[test] fn it_should_be_created_from_its_name_and_a_collection_of_samples() { - let name = MetricName::new("test_metric"); + let name = metric_name!("test_metric"); let samples = SampleCollection::::default(); @@ -148,7 +150,7 @@ mod tests { fn it_should_allow_incrementing_a_sample() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); - let name = MetricName::new("test_metric"); + let name = metric_name!("test_metric"); let label_set: LabelSet = [(LabelName::new("server_binding_protocol"), LabelValue::new("http"))].into(); @@ -166,11 +168,12 @@ mod tests { use super::super::*; use crate::gauge::Gauge; use crate::label::{LabelName, LabelValue}; + use crate::metric_name; use crate::sample::Sample; #[test] fn it_should_be_created_from_its_name_and_a_collection_of_samples() { - let name = MetricName::new("test_metric"); + let name = metric_name!("test_metric"); let samples = SampleCollection::::default(); @@ -181,7 +184,7 @@ mod tests { fn it_should_allow_setting_a_sample() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); - let name = MetricName::new("test_metric"); + let name = metric_name!("test_metric"); let label_set: LabelSet = [(LabelName::new("server_binding_protocol"), LabelValue::new("http"))].into(); diff --git a/packages/metrics/src/metric/name.rs b/packages/metrics/src/metric/name.rs index 453d5c777..41f5e7058 100644 --- a/packages/metrics/src/metric/name.rs +++ b/packages/metrics/src/metric/name.rs @@ -54,6 +54,9 @@ macro_rules! metric_name { ($name:literal) => { $crate::metric::name::MetricName::new($name) }; + ($name:ident) => { + $crate::metric::name::MetricName::new($name) + }; } #[cfg(test)] diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index d0ed96554..eb75e5c77 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -315,6 +315,7 @@ mod tests { use super::*; use crate::label::{LabelName, LabelValue}; + use crate::metric_name; use crate::sample::Sample; use crate::tests::{format_prometheus_output, sort_lines}; @@ -355,11 +356,11 @@ mod tests { MetricCollection::new( MetricKindCollection::new(vec![Metric::new( - MetricName::new("http_tracker_core_announce_requests_received_total"), + metric_name!("http_tracker_core_announce_requests_received_total"), SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set_1.clone())]), )]), MetricKindCollection::new(vec![Metric::new( - MetricName::new("udp_tracker_server_performance_avg_announce_processing_time_ns"), + metric_name!("udp_tracker_server_performance_avg_announce_processing_time_ns"), SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set_1.clone())]), )]), ) @@ -434,15 +435,9 @@ mod tests { #[test] #[should_panic(expected = "Metric names must be unique across counters and gauges")] fn it_should_not_allow_duplicate_names_across_types() { - let counter = MetricKindCollection::new(vec![Metric::new( - MetricName::new("test_metric"), - SampleCollection::new(vec![]), - )]); + let counter = MetricKindCollection::new(vec![Metric::new(metric_name!("test_metric"), SampleCollection::new(vec![]))]); - let gauge = MetricKindCollection::new(vec![Metric::new( - MetricName::new("test_metric"), - SampleCollection::new(vec![]), - )]); + let gauge = MetricKindCollection::new(vec![Metric::new(metric_name!("test_metric"), SampleCollection::new(vec![]))]); let _unused = MetricCollection::new(counter, gauge); } @@ -455,10 +450,10 @@ mod tests { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); // First create a counter - collection.increase_counter(&MetricName::new("test_metric"), &label_set, time); + collection.increase_counter(&metric_name!("test_metric"), &label_set, time); // Then try to create a gauge with the same name - this should panic - collection.set_gauge(&MetricName::new("test_metric"), &label_set, 1.0, time); + collection.set_gauge(&metric_name!("test_metric"), &label_set, 1.0, time); } #[test] @@ -469,15 +464,15 @@ mod tests { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); // First set the gauge - collection.set_gauge(&MetricName::new("test_metric"), &label_set, 1.0, time); + collection.set_gauge(&metric_name!("test_metric"), &label_set, 1.0, time); // Then try to create a counter with the same name - this should panic - collection.increase_counter(&MetricName::new("test_metric"), &label_set, time); + collection.increase_counter(&metric_name!("test_metric"), &label_set, time); } #[test] fn it_should_allow_serializing_to_json() { - // todo: this test does work with metric with multiple samples becuase + // todo: this test does work with metric with multiple samples because // samples are not serialized in the same order as they are created. let (metric_collection, expected_json, _expected_prometheus) = MetricCollectionFixture::default().deconstruct(); @@ -528,7 +523,7 @@ mod tests { let metric_collection = MetricCollection::new( MetricKindCollection::new(vec![Metric::new( - MetricName::new("http_tracker_core_announce_requests_received_total"), + metric_name!("http_tracker_core_announce_requests_received_total"), SampleCollection::new(vec![ Sample::new(Counter::new(1), time, label_set_1.clone()), Sample::new(Counter::new(2), time, label_set_2.clone()), @@ -557,8 +552,8 @@ mod tests { let mut counters = MetricKindCollection::new(vec![]); let mut gauges = MetricKindCollection::new(vec![]); - counters.ensure_metric_exists(&MetricName::new("test_counter")); - gauges.ensure_metric_exists(&MetricName::new("test_gauge")); + counters.ensure_metric_exists(&metric_name!("test_counter")); + gauges.ensure_metric_exists(&metric_name!("test_gauge")); let metric_collection = MetricCollection::new(counters, gauges); @@ -582,17 +577,17 @@ mod tests { let mut metric_collection = MetricCollection::new( MetricKindCollection::new(vec![Metric::new( - MetricName::new("test_counter"), + metric_name!("test_counter"), SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]), )]), MetricKindCollection::new(vec![]), ); - metric_collection.increase_counter(&MetricName::new("test_counter"), &label_set, time); - metric_collection.increase_counter(&MetricName::new("test_counter"), &label_set, time); + metric_collection.increase_counter(&metric_name!("test_counter"), &label_set, time); + metric_collection.increase_counter(&metric_name!("test_counter"), &label_set, time); assert_eq!( - metric_collection.get_counter_value(&MetricName::new("test_counter"), &label_set), + metric_collection.get_counter_value(&metric_name!("test_counter"), &label_set), Counter::new(2) ); } @@ -605,11 +600,11 @@ mod tests { let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); - metric_collection.increase_counter(&MetricName::new("test_counter"), &label_set, time); - metric_collection.increase_counter(&MetricName::new("test_counter"), &label_set, time); + metric_collection.increase_counter(&metric_name!("test_counter"), &label_set, time); + metric_collection.increase_counter(&metric_name!("test_counter"), &label_set, time); assert_eq!( - metric_collection.get_counter_value(&MetricName::new("test_counter"), &label_set), + metric_collection.get_counter_value(&metric_name!("test_counter"), &label_set), Counter::new(2) ); } @@ -621,10 +616,10 @@ mod tests { let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); - metric_collection.ensure_counter_exists(&MetricName::new("test_counter")); + metric_collection.ensure_counter_exists(&metric_name!("test_counter")); assert_eq!( - metric_collection.get_counter_value(&MetricName::new("test_counter"), &label_set), + metric_collection.get_counter_value(&metric_name!("test_counter"), &label_set), Counter::default() ); } @@ -636,10 +631,10 @@ mod tests { let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); - metric_collection.describe_counter(&MetricName::new("test_counter"), None, None); + metric_collection.describe_counter(&metric_name!("test_counter"), None, None); assert_eq!( - metric_collection.get_counter_value(&MetricName::new("test_counter"), &label_set), + metric_collection.get_counter_value(&metric_name!("test_counter"), &label_set), Counter::default() ); } @@ -652,11 +647,11 @@ mod tests { let _unused = MetricKindCollection::new(vec![ Metric::new( - MetricName::new("test_counter"), + metric_name!("test_counter"), SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]), ), Metric::new( - MetricName::new("test_counter"), + metric_name!("test_counter"), SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]), ), ]); @@ -679,15 +674,15 @@ mod tests { let mut metric_collection = MetricCollection::new( MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![Metric::new( - MetricName::new("test_gauge"), + metric_name!("test_gauge"), SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]), )]), ); - metric_collection.set_gauge(&MetricName::new("test_gauge"), &label_set, 1.0, time); + metric_collection.set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time); assert_eq!( - metric_collection.get_gauge_value(&MetricName::new("test_gauge"), &label_set), + metric_collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), Gauge::new(1.0) ); } @@ -700,10 +695,10 @@ mod tests { let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); - metric_collection.set_gauge(&MetricName::new("test_gauge"), &label_set, 1.0, time); + metric_collection.set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time); assert_eq!( - metric_collection.get_gauge_value(&MetricName::new("test_gauge"), &label_set), + metric_collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), Gauge::new(1.0) ); } @@ -715,10 +710,10 @@ mod tests { let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); - metric_collection.ensure_gauge_exists(&MetricName::new("test_gauge")); + metric_collection.ensure_gauge_exists(&metric_name!("test_gauge")); assert_eq!( - metric_collection.get_gauge_value(&MetricName::new("test_gauge"), &label_set), + metric_collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), Gauge::default() ); } @@ -730,10 +725,10 @@ mod tests { let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); - metric_collection.describe_gauge(&MetricName::new("test_gauge"), None, None); + metric_collection.describe_gauge(&metric_name!("test_gauge"), None, None); assert_eq!( - metric_collection.get_gauge_value(&MetricName::new("test_gauge"), &label_set), + metric_collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), Gauge::default() ); } @@ -746,11 +741,11 @@ mod tests { let _unused = MetricKindCollection::new(vec![ Metric::new( - MetricName::new("test_gauge"), + metric_name!("test_gauge"), SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]), ), Metric::new( - MetricName::new("test_gauge"), + metric_name!("test_gauge"), SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]), ), ]); diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index 59c382755..dcb512783 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -1,5 +1,5 @@ use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; -use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; @@ -29,7 +29,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura label_set.upsert(LabelName::new("request_kind"), LabelValue::new("connect")); stats_repository - .increase_counter(&MetricName::new(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) + .increase_counter(&metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) .await; } Event::UdpAnnounce { context } => { @@ -50,7 +50,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura label_set.upsert(LabelName::new("request_kind"), LabelValue::new("announce")); stats_repository - .increase_counter(&MetricName::new(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) + .increase_counter(&metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) .await; } Event::UdpScrape { context } => { @@ -71,7 +71,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura label_set.upsert(LabelName::new("request_kind"), LabelValue::new("scrape")); stats_repository - .increase_counter(&MetricName::new(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) + .increase_counter(&metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) .await; } } diff --git a/packages/udp-tracker-core/src/statistics/mod.rs b/packages/udp-tracker-core/src/statistics/mod.rs index bc4d8d836..40a30f51b 100644 --- a/packages/udp-tracker-core/src/statistics/mod.rs +++ b/packages/udp-tracker-core/src/statistics/mod.rs @@ -7,7 +7,7 @@ pub mod setup; use metrics::Metrics; use torrust_tracker_metrics::metric::description::MetricDescription; -use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_name; use torrust_tracker_metrics::unit::Unit; const UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL: &str = "udp_tracker_core_requests_received_total"; @@ -17,7 +17,7 @@ pub fn describe_metrics() -> Metrics { let mut metrics = Metrics::default(); metrics.metric_collection.describe_counter( - &MetricName::new(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of UDP requests received")), ); diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 4c10576c0..721d415ea 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -1,5 +1,5 @@ use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; -use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::{Event, UdpRequestKind, UdpResponseKind}; @@ -25,7 +25,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics stats_repository .increase_counter( - &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &LabelSet::from(context), now, ) @@ -38,7 +38,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics stats_repository .increase_counter( - &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), &LabelSet::from(context), now, ) @@ -58,7 +58,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics stats_repository .increase_counter( - &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &LabelSet::from(context), now, ) @@ -100,7 +100,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura label_set.upsert(LabelName::new("kind"), LabelValue::new(&kind.to_string())); stats_repository - .increase_counter(&MetricName::new(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &label_set, now) + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &label_set, now) .await; } Event::UdpResponseSent { @@ -132,7 +132,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura stats_repository .set_gauge( - &MetricName::new(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), &label_set, new_avg, now, @@ -153,7 +153,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura stats_repository .set_gauge( - &MetricName::new(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), &label_set, new_avg, now, @@ -174,7 +174,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura stats_repository .set_gauge( - &MetricName::new(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), &label_set, new_avg, now, @@ -197,7 +197,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura label_set.upsert(LabelName::new("result"), result_label_value); stats_repository - .increase_counter(&MetricName::new(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &label_set, now) + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &label_set, now) .await; } Event::UdpError { context } => { @@ -213,11 +213,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics stats_repository - .increase_counter( - &MetricName::new(UDP_TRACKER_SERVER_ERRORS_TOTAL), - &LabelSet::from(context), - now, - ) + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &LabelSet::from(context), now) .await; } } diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index 523cd4bac..4eea13224 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -7,7 +7,7 @@ pub mod setup; use metrics::Metrics; use torrust_tracker_metrics::metric::description::MetricDescription; -use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_name; use torrust_tracker_metrics::unit::Unit; const UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL: &str = "udp_tracker_server_requests_aborted_total"; @@ -23,43 +23,43 @@ pub fn describe_metrics() -> Metrics { let mut metrics = Metrics::default(); metrics.metric_collection.describe_counter( - &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of UDP requests aborted")), ); metrics.metric_collection.describe_counter( - &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of UDP requests banned")), ); metrics.metric_collection.describe_counter( - &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of UDP requests received")), ); metrics.metric_collection.describe_counter( - &MetricName::new(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of UDP requests accepted")), ); metrics.metric_collection.describe_counter( - &MetricName::new(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), + &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of UDP responses sent")), ); metrics.metric_collection.describe_counter( - &MetricName::new(UDP_TRACKER_SERVER_ERRORS_TOTAL), + &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), Some(Unit::Count), Some(MetricDescription::new("Total number of errors processing UDP requests")), ); metrics.metric_collection.describe_gauge( - &MetricName::new(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), Some(Unit::Nanoseconds), Some(MetricDescription::new( "Average time to process a UDP connect request in nanoseconds", From 7a24f855c1ac129bba890a72a9ccf9355bba2b85 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 15 Apr 2025 11:38:53 +0100 Subject: [PATCH 0953/1297] refactor: [#1445] new macro to create metric label names --- packages/metrics/src/label/name.rs | 27 ++++++++++++++++++--------- packages/metrics/src/metric/name.rs | 7 +++++++ 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/packages/metrics/src/label/name.rs b/packages/metrics/src/label/name.rs index 22e75572f..194aeb2b3 100644 --- a/packages/metrics/src/label/name.rs +++ b/packages/metrics/src/label/name.rs @@ -14,11 +14,7 @@ impl LabelName { /// Panics if the provided name is empty. #[must_use] pub fn new(name: &str) -> Self { - assert!( - !name.is_empty(), - "Label name cannot be empty. It must have at least one character." - ); - + assert!(!name.is_empty(), "Label name cannot be empty."); Self(name.to_owned()) } } @@ -69,6 +65,19 @@ impl PrometheusSerializable for LabelName { } } } + +#[macro_export] +macro_rules! label_name { + ("") => { + compile_error!("Label name cannot be empty"); + }; + ($name:literal) => { + $crate::label::name::LabelName::new($name) + }; + ($name:ident) => { + $crate::label::name::LabelName::new($name) + }; +} #[cfg(test)] mod tests { mod serialization_of_label_name_to_prometheus { @@ -83,7 +92,7 @@ mod tests { #[case("3 leading lowercase", "v123", "v123")] #[case("4 leading uppercase", "V123", "V123")] fn valid_names_in_prometheus(#[case] case: &str, #[case] input: &str, #[case] output: &str) { - assert_eq!(LabelName::new(input).to_prometheus(), output, "{case} failed: {input:?}"); + assert_eq!(label_name!(input).to_prometheus(), output, "{case} failed: {input:?}"); } #[rstest] @@ -96,7 +105,7 @@ mod tests { #[case("7 all invalid characters", "!@#$%^&*()", "__________")] #[case("8 non_ascii_characters", "ñaca©", "_aca_")] fn names_that_need_changes_in_prometheus(#[case] case: &str, #[case] input: &str, #[case] output: &str) { - assert_eq!(LabelName::new(input).to_prometheus(), output, "{case} failed: {input:?}"); + assert_eq!(label_name!(input).to_prometheus(), output, "{case} failed: {input:?}"); } #[rstest] @@ -105,11 +114,11 @@ mod tests { #[case("3 processed to double underscore", "^^name", "___name")] #[case("4 processed to double underscore after first char", "0__name", "___name")] fn names_starting_with_double_underscore(#[case] case: &str, #[case] input: &str, #[case] output: &str) { - assert_eq!(LabelName::new(input).to_prometheus(), output, "{case} failed: {input:?}"); + assert_eq!(label_name!(input).to_prometheus(), output, "{case} failed: {input:?}"); } #[test] - #[should_panic(expected = "Label name cannot be empty. It must have at least one character.")] + #[should_panic(expected = "Label name cannot be empty.")] fn empty_name() { let _name = LabelName::new(""); } diff --git a/packages/metrics/src/metric/name.rs b/packages/metrics/src/metric/name.rs index 41f5e7058..09c8c9e6d 100644 --- a/packages/metrics/src/metric/name.rs +++ b/packages/metrics/src/metric/name.rs @@ -64,6 +64,7 @@ mod tests { mod serialization_of_metric_name_to_prometheus { + use crate::metric::name::MetricName; use crate::prometheus::PrometheusSerializable; #[test] @@ -86,5 +87,11 @@ mod tests { assert_eq!(metric_name!("!@#$%^&*()").to_prometheus(), "__________"); assert_eq!(metric_name!("ñaca©").to_prometheus(), "_aca_"); } + + #[test] + #[should_panic(expected = "Metric name cannot be empty.")] + fn empty_name() { + let _name = MetricName::new(""); + } } } From 4d68267fff03505c9de1aca279a45a07b0ba32cc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 15 Apr 2025 11:51:21 +0100 Subject: [PATCH 0954/1297] refactor: [#1445] replace metric label name constructor by macro --- packages/http-tracker-core/src/event/mod.rs | 9 ++-- .../src/statistics/event/handler.rs | 8 ++-- packages/metrics/src/label/mod.rs | 4 +- packages/metrics/src/label/pair.rs | 6 +-- packages/metrics/src/label/set.rs | 33 ++++++------- packages/metrics/src/metric/mod.rs | 18 ++++---- packages/metrics/src/metric_collection.rs | 46 +++++++++---------- packages/udp-tracker-core/src/event/mod.rs | 9 ++-- .../src/statistics/event/handler.rs | 10 ++-- packages/udp-tracker-server/src/event/mod.rs | 9 ++-- .../src/statistics/event/handler.rs | 16 +++---- 11 files changed, 86 insertions(+), 82 deletions(-) diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index d235c179f..ae997156a 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -1,6 +1,7 @@ use std::net::{IpAddr, SocketAddr}; -use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::label_name; use torrust_tracker_primitives::service_binding::ServiceBinding; pub mod sender; @@ -65,15 +66,15 @@ impl From for LabelSet { fn from(connection_context: ConnectionContext) -> Self { LabelSet::from([ ( - LabelName::new("server_binding_protocol"), + label_name!("server_binding_protocol"), LabelValue::new(&connection_context.server.service_binding.protocol().to_string()), ), ( - LabelName::new("server_binding_ip"), + label_name!("server_binding_ip"), LabelValue::new(&connection_context.server.service_binding.bind_address().ip().to_string()), ), ( - LabelName::new("server_binding_port"), + label_name!("server_binding_port"), LabelValue::new(&connection_context.server.service_binding.bind_address().port().to_string()), ), ]) diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index 6e37b0209..cea224d04 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -1,7 +1,7 @@ use std::net::IpAddr; -use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; -use torrust_tracker_metrics::metric_name; +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::{label_name, metric_name}; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; @@ -29,7 +29,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics let mut label_set = LabelSet::from(connection); - label_set.upsert(LabelName::new("request_kind"), LabelValue::new("announce")); + label_set.upsert(label_name!("request_kind"), LabelValue::new("announce")); stats_repository .increase_counter(&metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) @@ -50,7 +50,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics let mut label_set = LabelSet::from(connection); - label_set.upsert(LabelName::new("request_kind"), LabelValue::new("scrape")); + label_set.upsert(label_name!("request_kind"), LabelValue::new("scrape")); stats_repository .increase_counter(&metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) diff --git a/packages/metrics/src/label/mod.rs b/packages/metrics/src/label/mod.rs index b5fd3b745..880fdbbb1 100644 --- a/packages/metrics/src/label/mod.rs +++ b/packages/metrics/src/label/mod.rs @@ -1,7 +1,7 @@ -mod name; +pub mod name; mod pair; mod set; -mod value; +pub mod value; pub type LabelName = name::LabelName; pub type LabelValue = value::LabelValue; diff --git a/packages/metrics/src/label/pair.rs b/packages/metrics/src/label/pair.rs index c89c726bd..858902451 100644 --- a/packages/metrics/src/label/pair.rs +++ b/packages/metrics/src/label/pair.rs @@ -13,16 +13,16 @@ impl PrometheusSerializabl #[cfg(test)] mod tests { mod serialization_of_label_pair_to_prometheus { - use super::super::LabelName; use crate::label::LabelValue; + use crate::label_name; use crate::prometheus::PrometheusSerializable; #[test] fn test_label_pair_serialization_to_prometheus() { - let label_pair = (LabelName::new("label_name"), LabelValue::new("value")); + let label_pair = (label_name!("label_name"), LabelValue::new("value")); assert_eq!(label_pair.to_prometheus(), r#"label_name="value""#); - let label_pair = (&LabelName::new("label_name"), &LabelValue::new("value")); + let label_pair = (&label_name!("label_name"), &LabelValue::new("value")); assert_eq!(label_pair.to_prometheus(), r#"label_name="value""#); } } diff --git a/packages/metrics/src/label/set.rs b/packages/metrics/src/label/set.rs index f46b01095..2b6334fc7 100644 --- a/packages/metrics/src/label/set.rs +++ b/packages/metrics/src/label/set.rs @@ -180,6 +180,7 @@ mod tests { use super::{LabelName, LabelValue}; use crate::label::LabelSet; + use crate::label_name; use crate::prometheus::PrometheusSerializable; fn sample_vec_of_label_pairs() -> Vec<(LabelName, LabelValue)> { @@ -188,9 +189,9 @@ mod tests { fn sample_array_of_label_pairs() -> [(LabelName, LabelValue); 3] { [ - (LabelName::new("server_service_binding_protocol"), LabelValue::new("http")), - (LabelName::new("server_service_binding_ip"), LabelValue::new("0.0.0.0")), - (LabelName::new("server_service_binding_port"), LabelValue::new("7070")), + (label_name!("server_service_binding_protocol"), LabelValue::new("http")), + (label_name!("server_service_binding_ip"), LabelValue::new("0.0.0.0")), + (label_name!("server_service_binding_port"), LabelValue::new("7070")), ] } @@ -232,12 +233,12 @@ mod tests { #[test] fn it_should_allow_instantiation_from_a_label_pair() { - let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); assert_eq!( label_set, LabelSet { - items: BTreeMap::from([(LabelName::new("label_name"), LabelValue::new("value"))]) + items: BTreeMap::from([(label_name!("label_name"), LabelValue::new("value"))]) } ); } @@ -246,10 +247,10 @@ mod tests { fn it_should_allow_inserting_a_new_label_pair() { let mut label_set = LabelSet::default(); - label_set.upsert(LabelName::new("label_name"), LabelValue::new("value")); + label_set.upsert(label_name!("label_name"), LabelValue::new("value")); assert_eq!( - label_set.items.get(&LabelName::new("label_name")).unwrap(), + label_set.items.get(&label_name!("label_name")).unwrap(), &LabelValue::new("value") ); } @@ -258,18 +259,18 @@ mod tests { fn it_should_allow_updating_a_label_value() { let mut label_set = LabelSet::default(); - label_set.upsert(LabelName::new("label_name"), LabelValue::new("old value")); - label_set.upsert(LabelName::new("label_name"), LabelValue::new("new value")); + label_set.upsert(label_name!("label_name"), LabelValue::new("old value")); + label_set.upsert(label_name!("label_name"), LabelValue::new("new value")); assert_eq!( - label_set.items.get(&LabelName::new("label_name")).unwrap(), + label_set.items.get(&label_name!("label_name")).unwrap(), &LabelValue::new("new value") ); } #[test] fn it_should_allow_serializing_to_json_as_an_array_of_label_objects() { - let label_set = LabelSet::from((LabelName::new("label_name"), LabelValue::new("label value"))); + let label_set = LabelSet::from((label_name!("label_name"), LabelValue::new("label value"))); let json = serde_json::to_string(&label_set).unwrap(); @@ -307,13 +308,13 @@ mod tests { assert_eq!( label_set, - LabelSet::from((LabelName::new("label_name"), LabelValue::new("label value"))) + LabelSet::from((label_name!("label_name"), LabelValue::new("label value"))) ); } #[test] fn it_should_allow_serializing_to_prometheus_format() { - let label_set = LabelSet::from((LabelName::new("label_name"), LabelValue::new("label value"))); + let label_set = LabelSet::from((label_name!("label_name"), LabelValue::new("label value"))); assert_eq!(label_set.to_prometheus(), r#"{label_name="label value"}"#); } @@ -321,8 +322,8 @@ mod tests { #[test] fn it_should_alphabetically_order_labels_in_prometheus_format() { let label_set = LabelSet::from([ - (LabelName::new("b_label_name"), LabelValue::new("b label value")), - (LabelName::new("a_label_name"), LabelValue::new("a label value")), + (label_name!("b_label_name"), LabelValue::new("b label value")), + (label_name!("a_label_name"), LabelValue::new("a label value")), ]); assert_eq!( @@ -333,7 +334,7 @@ mod tests { #[test] fn it_should_allow_displaying() { - let label_set = LabelSet::from((LabelName::new("label_name"), LabelValue::new("label value"))); + let label_set = LabelSet::from((label_name!("label_name"), LabelValue::new("label value"))); assert_eq!(label_set.to_string(), r#"{label_name="label value"}"#); } diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index 95e35b520..777981fd8 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -86,9 +86,9 @@ mod tests { mod for_generic_metrics { use super::super::*; use crate::gauge::Gauge; - use crate::label::{LabelName, LabelValue}; - use crate::metric_name; + use crate::label::LabelValue; use crate::sample::Sample; + use crate::{label_name, metric_name}; #[test] fn it_should_be_empty_when_it_does_not_have_any_sample() { @@ -106,7 +106,7 @@ mod tests { let name = metric_name!("test_metric"); - let label_set: LabelSet = [(LabelName::new("server_binding_protocol"), LabelValue::new("http"))].into(); + let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); let samples = SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set.clone())]); @@ -133,9 +133,9 @@ mod tests { mod for_counter_metrics { use super::super::*; use crate::counter::Counter; - use crate::label::{LabelName, LabelValue}; - use crate::metric_name; + use crate::label::LabelValue; use crate::sample::Sample; + use crate::{label_name, metric_name}; #[test] fn it_should_be_created_from_its_name_and_a_collection_of_samples() { @@ -152,7 +152,7 @@ mod tests { let name = metric_name!("test_metric"); - let label_set: LabelSet = [(LabelName::new("server_binding_protocol"), LabelValue::new("http"))].into(); + let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); let samples = SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set.clone())]); @@ -167,9 +167,9 @@ mod tests { use super::super::*; use crate::gauge::Gauge; - use crate::label::{LabelName, LabelValue}; - use crate::metric_name; + use crate::label::LabelValue; use crate::sample::Sample; + use crate::{label_name, metric_name}; #[test] fn it_should_be_created_from_its_name_and_a_collection_of_samples() { @@ -186,7 +186,7 @@ mod tests { let name = metric_name!("test_metric"); - let label_set: LabelSet = [(LabelName::new("server_binding_protocol"), LabelValue::new("http"))].into(); + let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); let samples = SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set.clone())]); diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index eb75e5c77..5b3f92a19 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -314,10 +314,10 @@ mod tests { use pretty_assertions::assert_eq; use super::*; - use crate::label::{LabelName, LabelValue}; - use crate::metric_name; + use crate::label::LabelValue; use crate::sample::Sample; use crate::tests::{format_prometheus_output, sort_lines}; + use crate::{label_name, metric_name}; /// Fixture for testing serialization and deserialization of `MetricCollection`. /// @@ -348,9 +348,9 @@ mod tests { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); let label_set_1: LabelSet = [ - (LabelName::new("server_binding_protocol"), LabelValue::new("http")), - (LabelName::new("server_binding_ip"), LabelValue::new("0.0.0.0")), - (LabelName::new("server_binding_port"), LabelValue::new("7070")), + (label_name!("server_binding_protocol"), LabelValue::new("http")), + (label_name!("server_binding_ip"), LabelValue::new("0.0.0.0")), + (label_name!("server_binding_port"), LabelValue::new("7070")), ] .into(); @@ -508,16 +508,16 @@ mod tests { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); let label_set_1: LabelSet = [ - (LabelName::new("server_binding_protocol"), LabelValue::new("http")), - (LabelName::new("server_binding_ip"), LabelValue::new("0.0.0.0")), - (LabelName::new("server_binding_port"), LabelValue::new("7070")), + (label_name!("server_binding_protocol"), LabelValue::new("http")), + (label_name!("server_binding_ip"), LabelValue::new("0.0.0.0")), + (label_name!("server_binding_port"), LabelValue::new("7070")), ] .into(); let label_set_2: LabelSet = [ - (LabelName::new("server_binding_protocol"), LabelValue::new("http")), - (LabelName::new("server_binding_ip"), LabelValue::new("0.0.0.0")), - (LabelName::new("server_binding_port"), LabelValue::new("7171")), + (label_name!("server_binding_protocol"), LabelValue::new("http")), + (label_name!("server_binding_ip"), LabelValue::new("0.0.0.0")), + (label_name!("server_binding_port"), LabelValue::new("7171")), ] .into(); @@ -567,13 +567,13 @@ mod tests { use pretty_assertions::assert_eq; use super::*; - use crate::label::{LabelName, LabelValue}; + use crate::label::LabelValue; use crate::sample::Sample; #[test] fn it_should_increase_a_preexistent_counter() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); - let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = MetricCollection::new( MetricKindCollection::new(vec![Metric::new( @@ -595,7 +595,7 @@ mod tests { #[test] fn it_should_automatically_create_a_counter_when_increasing_if_it_does_not_exist() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); - let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); @@ -611,7 +611,7 @@ mod tests { #[test] fn it_should_allow_making_sure_a_counter_exists_without_increasing_it() { - let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); @@ -626,7 +626,7 @@ mod tests { #[test] fn it_should_allow_describing_a_counter_before_using_it() { - let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); @@ -643,7 +643,7 @@ mod tests { #[should_panic(expected = "Duplicate MetricName found in MetricKindCollection")] fn it_should_not_allow_duplicate_metric_names_when_instantiating() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); - let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let _unused = MetricKindCollection::new(vec![ Metric::new( @@ -663,13 +663,13 @@ mod tests { use pretty_assertions::assert_eq; use super::*; - use crate::label::{LabelName, LabelValue}; + use crate::label::LabelValue; use crate::sample::Sample; #[test] fn it_should_set_a_preexistent_gauge() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); - let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = MetricCollection::new( MetricKindCollection::new(vec![]), @@ -690,7 +690,7 @@ mod tests { #[test] fn it_should_automatically_create_a_gauge_when_setting_if_it_does_not_exist() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); - let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); @@ -705,7 +705,7 @@ mod tests { #[test] fn it_should_allow_making_sure_a_gauge_exists_without_increasing_it() { - let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); @@ -720,7 +720,7 @@ mod tests { #[test] fn it_should_allow_describing_a_gauge_before_using_it() { - let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); @@ -737,7 +737,7 @@ mod tests { #[should_panic(expected = "Duplicate MetricName found in MetricKindCollection")] fn it_should_not_allow_duplicate_metric_names_when_instantiating() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); - let label_set: LabelSet = (LabelName::new("label_name"), LabelValue::new("value")).into(); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let _unused = MetricKindCollection::new(vec![ Metric::new( diff --git a/packages/udp-tracker-core/src/event/mod.rs b/packages/udp-tracker-core/src/event/mod.rs index 6cb43e5a1..ddcba7792 100644 --- a/packages/udp-tracker-core/src/event/mod.rs +++ b/packages/udp-tracker-core/src/event/mod.rs @@ -1,6 +1,7 @@ use std::net::SocketAddr; -use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::label_name; use torrust_tracker_primitives::service_binding::ServiceBinding; pub mod sender; @@ -43,15 +44,15 @@ impl From for LabelSet { fn from(connection_context: ConnectionContext) -> Self { LabelSet::from([ ( - LabelName::new("server_binding_protocol"), + label_name!("server_binding_protocol"), LabelValue::new(&connection_context.server_service_binding.protocol().to_string()), ), ( - LabelName::new("server_binding_ip"), + label_name!("server_binding_ip"), LabelValue::new(&connection_context.server_service_binding.bind_address().ip().to_string()), ), ( - LabelName::new("server_binding_port"), + label_name!("server_binding_port"), LabelValue::new(&connection_context.server_service_binding.bind_address().port().to_string()), ), ]) diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index dcb512783..13a4840d5 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -1,5 +1,5 @@ -use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; -use torrust_tracker_metrics::metric_name; +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::{label_name, metric_name}; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; @@ -26,7 +26,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics let mut label_set = LabelSet::from(context); - label_set.upsert(LabelName::new("request_kind"), LabelValue::new("connect")); + label_set.upsert(label_name!("request_kind"), LabelValue::new("connect")); stats_repository .increase_counter(&metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) @@ -47,7 +47,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics let mut label_set = LabelSet::from(context); - label_set.upsert(LabelName::new("request_kind"), LabelValue::new("announce")); + label_set.upsert(label_name!("request_kind"), LabelValue::new("announce")); stats_repository .increase_counter(&metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) @@ -68,7 +68,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics let mut label_set = LabelSet::from(context); - label_set.upsert(LabelName::new("request_kind"), LabelValue::new("scrape")); + label_set.upsert(label_name!("request_kind"), LabelValue::new("scrape")); stats_repository .increase_counter(&metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) diff --git a/packages/udp-tracker-server/src/event/mod.rs b/packages/udp-tracker-server/src/event/mod.rs index 316e1a414..0236b26a9 100644 --- a/packages/udp-tracker-server/src/event/mod.rs +++ b/packages/udp-tracker-server/src/event/mod.rs @@ -2,7 +2,8 @@ use std::fmt; use std::net::SocketAddr; use std::time::Duration; -use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::label_name; use torrust_tracker_primitives::service_binding::ServiceBinding; pub mod sender; @@ -94,15 +95,15 @@ impl From for LabelSet { fn from(connection_context: ConnectionContext) -> Self { LabelSet::from([ ( - LabelName::new("server_binding_protocol"), + label_name!("server_binding_protocol"), LabelValue::new(&connection_context.server_service_binding.protocol().to_string()), ), ( - LabelName::new("server_binding_ip"), + label_name!("server_binding_ip"), LabelValue::new(&connection_context.server_service_binding.bind_address().ip().to_string()), ), ( - LabelName::new("server_binding_port"), + label_name!("server_binding_port"), LabelValue::new(&connection_context.server_service_binding.bind_address().port().to_string()), ), ]) diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 721d415ea..430bbc34c 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -1,5 +1,5 @@ -use torrust_tracker_metrics::label::{LabelName, LabelSet, LabelValue}; -use torrust_tracker_metrics::metric_name; +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::{label_name, metric_name}; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::{Event, UdpRequestKind, UdpResponseKind}; @@ -97,7 +97,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura let mut label_set = LabelSet::from(context); - label_set.upsert(LabelName::new("kind"), LabelValue::new(&kind.to_string())); + label_set.upsert(label_name!("kind"), LabelValue::new(&kind.to_string())); stats_repository .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &label_set, now) @@ -128,7 +128,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics let mut label_set = LabelSet::from(context.clone()); - label_set.upsert(LabelName::new("request_kind"), LabelValue::new(&req_kind.to_string())); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); stats_repository .set_gauge( @@ -149,7 +149,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics let mut label_set = LabelSet::from(context.clone()); - label_set.upsert(LabelName::new("request_kind"), LabelValue::new(&req_kind.to_string())); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); stats_repository .set_gauge( @@ -170,7 +170,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura // Extendable metrics let mut label_set = LabelSet::from(context.clone()); - label_set.upsert(LabelName::new("request_kind"), LabelValue::new(&req_kind.to_string())); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); stats_repository .set_gauge( @@ -192,9 +192,9 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura let mut label_set = LabelSet::from(context); if result_label_value == LabelValue::new("ok") { - label_set.upsert(LabelName::new("request_kind"), kind_label_value); + label_set.upsert(label_name!("request_kind"), kind_label_value); } - label_set.upsert(LabelName::new("result"), result_label_value); + label_set.upsert(label_name!("result"), result_label_value); stats_repository .increase_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &label_set, now) From d263be70a5ed5c5f64c4ed296f0a930c1c48dee7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 15 Apr 2025 12:20:23 +0100 Subject: [PATCH 0955/1297] refactor: [#1445] return optionals for metric values in metric collection --- packages/metrics/src/metric_collection.rs | 60 ++++++++++------------- 1 file changed, 25 insertions(+), 35 deletions(-) diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index 5b3f92a19..c4db0706f 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -62,7 +62,12 @@ impl MetricCollection { } #[must_use] - pub fn get_counter_value(&self, name: &MetricName, label_set: &LabelSet) -> Counter { + pub fn contains_counter(&self, name: &MetricName) -> bool { + self.counters.metrics.contains_key(name) + } + + #[must_use] + pub fn get_counter_value(&self, name: &MetricName, label_set: &LabelSet) -> Option { self.counters.get_value(name, label_set) } @@ -89,7 +94,12 @@ impl MetricCollection { } #[must_use] - pub fn get_gauge_value(&self, name: &MetricName, label_set: &LabelSet) -> Gauge { + pub fn contains_gauge(&self, name: &MetricName) -> bool { + self.gauges.metrics.contains_key(name) + } + + #[must_use] + pub fn get_gauge_value(&self, name: &MetricName, label_set: &LabelSet) -> Option { self.gauges.get_value(name, label_set) } @@ -275,11 +285,11 @@ impl MetricKindCollection { } #[must_use] - pub fn get_value(&self, name: &MetricName, label_set: &LabelSet) -> Counter { + pub fn get_value(&self, name: &MetricName, label_set: &LabelSet) -> Option { self.metrics .get(name) .and_then(|metric| metric.get_sample_data(label_set)) - .map_or(Counter::default(), |sample| sample.value().clone()) + .map(|sample| sample.value().clone()) } } @@ -300,11 +310,11 @@ impl MetricKindCollection { } #[must_use] - pub fn get_value(&self, name: &MetricName, label_set: &LabelSet) -> Gauge { + pub fn get_value(&self, name: &MetricName, label_set: &LabelSet) -> Option { self.metrics .get(name) .and_then(|metric| metric.get_sample_data(label_set)) - .map_or(Gauge::default(), |sample| sample.value().clone()) + .map(|sample| sample.value().clone()) } } @@ -588,7 +598,7 @@ mod tests { assert_eq!( metric_collection.get_counter_value(&metric_name!("test_counter"), &label_set), - Counter::new(2) + Some(Counter::new(2)) ); } @@ -605,38 +615,28 @@ mod tests { assert_eq!( metric_collection.get_counter_value(&metric_name!("test_counter"), &label_set), - Counter::new(2) + Some(Counter::new(2)) ); } #[test] fn it_should_allow_making_sure_a_counter_exists_without_increasing_it() { - let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); - let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); metric_collection.ensure_counter_exists(&metric_name!("test_counter")); - assert_eq!( - metric_collection.get_counter_value(&metric_name!("test_counter"), &label_set), - Counter::default() - ); + assert!(metric_collection.contains_counter(&metric_name!("test_counter"))); } #[test] fn it_should_allow_describing_a_counter_before_using_it() { - let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); - let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); metric_collection.describe_counter(&metric_name!("test_counter"), None, None); - assert_eq!( - metric_collection.get_counter_value(&metric_name!("test_counter"), &label_set), - Counter::default() - ); + assert!(metric_collection.contains_counter(&metric_name!("test_counter"))); } #[test] @@ -683,7 +683,7 @@ mod tests { assert_eq!( metric_collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), - Gauge::new(1.0) + Some(Gauge::new(1.0)) ); } @@ -699,38 +699,28 @@ mod tests { assert_eq!( metric_collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), - Gauge::new(1.0) + Some(Gauge::new(1.0)) ); } #[test] - fn it_should_allow_making_sure_a_gauge_exists_without_increasing_it() { - let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); - + fn it_should_allow_making_sure_a_gauge_exists_without_setting_it() { let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); metric_collection.ensure_gauge_exists(&metric_name!("test_gauge")); - assert_eq!( - metric_collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), - Gauge::default() - ); + assert!(metric_collection.contains_gauge(&metric_name!("test_gauge"))); } #[test] fn it_should_allow_describing_a_gauge_before_using_it() { - let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); - let mut metric_collection = MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); metric_collection.describe_gauge(&metric_name!("test_gauge"), None, None); - assert_eq!( - metric_collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), - Gauge::default() - ); + assert!(metric_collection.contains_gauge(&metric_name!("test_gauge"))); } #[test] From 785a978e0d2ac45d70dc6f5c2a4109ced175d4d9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 15 Apr 2025 13:03:15 +0100 Subject: [PATCH 0956/1297] refactor: [#1445] remove panic from MetricColelction::new method --- packages/metrics/src/metric_collection.rs | 64 +++++++++++++---------- 1 file changed, 35 insertions(+), 29 deletions(-) diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index c4db0706f..29da4e509 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -27,21 +27,20 @@ pub struct MetricCollection { } impl MetricCollection { - /// # Panics + /// # Errors /// - /// Panics if there are duplicate metric names across counters and gauges. - #[must_use] - pub fn new(counters: MetricKindCollection, gauges: MetricKindCollection) -> Self { + /// Returns an error if there are duplicate metric names across counters and + /// gauges. + pub fn new(counters: MetricKindCollection, gauges: MetricKindCollection) -> Result { // Check for name collisions across metric types let counter_names: HashSet<_> = counters.names().collect(); let gauge_names: HashSet<_> = gauges.names().collect(); - assert!( - counter_names.is_disjoint(&gauge_names), - "Metric names must be unique across counters and gauges" - ); + if !counter_names.is_disjoint(&gauge_names) { + return Err(Error::DuplicateMetricNames); + } - Self { counters, gauges } + Ok(Self { counters, gauges }) } /// Merges another `MetricCollection` into this one. @@ -49,7 +48,7 @@ impl MetricCollection { /// # Errors /// /// Returns an error if a metric name already exists in the current collection. - pub fn merge(&mut self, other: &Self) -> Result<(), MergeError> { + pub fn merge(&mut self, other: &Self) -> Result<(), Error> { self.counters.merge(&other.counters)?; self.gauges.merge(&other.gauges)?; Ok(()) @@ -121,9 +120,12 @@ impl MetricCollection { } #[derive(thiserror::Error, Debug, Clone)] -pub enum MergeError { +pub enum Error { + #[error("Metric names must be unique across counters and gauges.")] + DuplicateMetricNames, + #[error("Cannot merge metric '{metric_name}': it already exists in the current collection")] - MetricNameAlreadyExists { metric_name: MetricName }, + MetricNameCollisionInMerge { metric_name: MetricName }, } /// Implements serialization for `MetricCollection`. @@ -177,10 +179,10 @@ impl<'de> Deserialize<'de> for MetricCollection { } } - Ok(MetricCollection::new( - MetricKindCollection::new(counters), - MetricKindCollection::new(gauges), - )) + let metric_collection = MetricCollection::new(MetricKindCollection::new(counters), MetricKindCollection::new(gauges)) + .map_err(serde::de::Error::custom)?; + + Ok(metric_collection) } } @@ -246,11 +248,11 @@ impl MetricKindCollection { /// # Errors /// /// Returns an error if a metric name already exists in the current collection. - pub fn merge(&mut self, other: &Self) -> Result<(), MergeError> { + pub fn merge(&mut self, other: &Self) -> Result<(), Error> { // Check for name collisions for metric_name in other.metrics.keys() { if self.metrics.contains_key(metric_name) { - return Err(MergeError::MetricNameAlreadyExists { + return Err(Error::MetricNameCollisionInMerge { metric_name: metric_name.clone(), }); } @@ -258,7 +260,7 @@ impl MetricKindCollection { for (metric_name, metric) in &other.metrics { if self.metrics.insert(metric_name.clone(), metric.clone()).is_some() { - return Err(MergeError::MetricNameAlreadyExists { + return Err(Error::MetricNameCollisionInMerge { metric_name: metric_name.clone(), }); } @@ -374,6 +376,7 @@ mod tests { SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set_1.clone())]), )]), ) + .unwrap() } fn json() -> String { @@ -540,7 +543,8 @@ mod tests { ]), )]), MetricKindCollection::new(vec![]), - ); + ) + .unwrap(); let prometheus_output = metric_collection.to_prometheus(); @@ -565,7 +569,7 @@ mod tests { counters.ensure_metric_exists(&metric_name!("test_counter")); gauges.ensure_metric_exists(&metric_name!("test_gauge")); - let metric_collection = MetricCollection::new(counters, gauges); + let metric_collection = MetricCollection::new(counters, gauges).unwrap(); let prometheus_output = metric_collection.to_prometheus(); @@ -591,7 +595,8 @@ mod tests { SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]), )]), MetricKindCollection::new(vec![]), - ); + ) + .unwrap(); metric_collection.increase_counter(&metric_name!("test_counter"), &label_set, time); metric_collection.increase_counter(&metric_name!("test_counter"), &label_set, time); @@ -608,7 +613,7 @@ mod tests { let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = - MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); + MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])).unwrap(); metric_collection.increase_counter(&metric_name!("test_counter"), &label_set, time); metric_collection.increase_counter(&metric_name!("test_counter"), &label_set, time); @@ -622,7 +627,7 @@ mod tests { #[test] fn it_should_allow_making_sure_a_counter_exists_without_increasing_it() { let mut metric_collection = - MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); + MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])).unwrap(); metric_collection.ensure_counter_exists(&metric_name!("test_counter")); @@ -632,7 +637,7 @@ mod tests { #[test] fn it_should_allow_describing_a_counter_before_using_it() { let mut metric_collection = - MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); + MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])).unwrap(); metric_collection.describe_counter(&metric_name!("test_counter"), None, None); @@ -677,7 +682,8 @@ mod tests { metric_name!("test_gauge"), SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]), )]), - ); + ) + .unwrap(); metric_collection.set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time); @@ -693,7 +699,7 @@ mod tests { let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = - MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); + MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])).unwrap(); metric_collection.set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time); @@ -706,7 +712,7 @@ mod tests { #[test] fn it_should_allow_making_sure_a_gauge_exists_without_setting_it() { let mut metric_collection = - MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); + MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])).unwrap(); metric_collection.ensure_gauge_exists(&metric_name!("test_gauge")); @@ -716,7 +722,7 @@ mod tests { #[test] fn it_should_allow_describing_a_gauge_before_using_it() { let mut metric_collection = - MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])); + MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])).unwrap(); metric_collection.describe_gauge(&metric_name!("test_gauge"), None, None); From 42e1524c560f546d0b57c61b50bf83c928112990 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 15 Apr 2025 16:21:49 +0100 Subject: [PATCH 0957/1297] refactor: [#1445] return errors instead of panicking in the MetricCollection struct --- .../src/statistics/event/handler.rs | 16 +- .../src/statistics/metrics.rs | 27 ++- .../src/statistics/repository.rs | 18 +- packages/metrics/src/metric_collection.rs | 229 +++++++++++------- .../src/statistics/event/handler.rs | 24 +- .../src/statistics/metrics.rs | 29 ++- .../src/statistics/repository.rs | 18 +- .../src/statistics/event/handler.rs | 72 ++++-- .../src/statistics/metrics.rs | 27 ++- .../src/statistics/repository.rs | 36 ++- 10 files changed, 363 insertions(+), 133 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index cea224d04..182c86b01 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -31,9 +31,13 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura let mut label_set = LabelSet::from(connection); label_set.upsert(label_name!("request_kind"), LabelValue::new("announce")); - stats_repository + match stats_repository .increase_counter(&metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; } Event::TcpScrape { connection } => { // Global fixed metrics @@ -52,9 +56,13 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura let mut label_set = LabelSet::from(connection); label_set.upsert(label_name!("request_kind"), LabelValue::new("scrape")); - stats_repository + match stats_repository .increase_counter(&metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; } } diff --git a/packages/http-tracker-core/src/statistics/metrics.rs b/packages/http-tracker-core/src/statistics/metrics.rs index 0b442c1cb..bf053b04e 100644 --- a/packages/http-tracker-core/src/statistics/metrics.rs +++ b/packages/http-tracker-core/src/statistics/metrics.rs @@ -1,7 +1,7 @@ use serde::Serialize; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; -use torrust_tracker_metrics::metric_collection::MetricCollection; +use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; use torrust_tracker_primitives::DurationSinceUnixEpoch; /// Metrics collected by the tracker. @@ -24,11 +24,28 @@ pub struct Metrics { } impl Metrics { - pub fn increase_counter(&mut self, metric_name: &MetricName, labels: &LabelSet, now: DurationSinceUnixEpoch) { - self.metric_collection.increase_counter(metric_name, labels, now); + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increase_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increase_counter(metric_name, labels, now) } - pub fn set_gauge(&mut self, metric_name: &MetricName, labels: &LabelSet, value: f64, now: DurationSinceUnixEpoch) { - self.metric_collection.set_gauge(metric_name, labels, value, now); + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn set_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_gauge(metric_name, labels, value, now) } } diff --git a/packages/http-tracker-core/src/statistics/repository.rs b/packages/http-tracker-core/src/statistics/repository.rs index 88345722b..d5e718821 100644 --- a/packages/http-tracker-core/src/statistics/repository.rs +++ b/packages/http-tracker-core/src/statistics/repository.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use tokio::sync::{RwLock, RwLockReadGuard}; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::Error; use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::describe_metrics; @@ -56,9 +57,22 @@ impl Repository { drop(stats_lock); } - pub async fn increase_counter(&self, metric_name: &MetricName, labels: &LabelSet, now: DurationSinceUnixEpoch) { + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increase the counter. + pub async fn increase_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { let mut stats_lock = self.stats.write().await; - stats_lock.increase_counter(metric_name, labels, now); + + let result = stats_lock.increase_counter(metric_name, labels, now); + drop(stats_lock); + + result } } diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index 29da4e509..c719e6054 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -13,13 +13,10 @@ use crate::metric::description::MetricDescription; use crate::sample_collection::SampleCollection; use crate::unit::Unit; -// todo: serialize in a deterministic order. For example: +// code-review: serialize in a deterministic order? For example: // - First the counter metrics ordered by name. // - Then the gauge metrics ordered by name. -/// Use this type only when behind a lock that guarantees thread-safety. -/// Otherwise, there could be race conditions that lead to duplicate metric -/// names in different metric types. #[derive(Debug, Clone, Default, PartialEq)] pub struct MetricCollection { counters: MetricKindCollection, @@ -37,7 +34,10 @@ impl MetricCollection { let gauge_names: HashSet<_> = gauges.names().collect(); if !counter_names.is_disjoint(&gauge_names) { - return Err(Error::DuplicateMetricNames); + return Err(Error::MetricNameCollisionInConstructor { + counter_names: counter_names.iter().map(std::string::ToString::to_string).collect(), + gauge_names: gauge_names.iter().map(std::string::ToString::to_string).collect(), + }); } Ok(Self { counters, gauges }) @@ -70,16 +70,25 @@ impl MetricCollection { self.counters.get_value(name, label_set) } - /// # Panics + /// # Errors /// - /// Panics if a gauge with the same name already exists. - pub fn increase_counter(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { - assert!( - !self.gauges.metrics.contains_key(name), - "Cannot create counter with name '{name}': a gauge with this name already exists", - ); + /// Return an error if a metrics of a different type with the same name + /// already exists. + pub fn increase_counter( + &mut self, + name: &MetricName, + label_set: &LabelSet, + time: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + if self.gauges.metrics.contains_key(name) { + return Err(Error::MetricNameCollisionAdding { + metric_name: name.clone(), + }); + } self.counters.increment(name, label_set, time); + + Ok(()) } pub fn ensure_counter_exists(&mut self, name: &MetricName) { @@ -102,16 +111,26 @@ impl MetricCollection { self.gauges.get_value(name, label_set) } - /// # Panics + /// # Errors /// - /// Panics if a counter with the same name already exists. - pub fn set_gauge(&mut self, name: &MetricName, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { - assert!( - !self.counters.metrics.contains_key(name), - "Cannot create gauge with name '{name}': a counter with this name already exists" - ); + /// Return an error if a metrics of a different type with the same name + /// already exists. + pub fn set_gauge( + &mut self, + name: &MetricName, + label_set: &LabelSet, + value: f64, + time: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + if self.counters.metrics.contains_key(name) { + return Err(Error::MetricNameCollisionAdding { + metric_name: name.clone(), + }); + } self.gauges.set(name, label_set, value, time); + + Ok(()) } pub fn ensure_gauge_exists(&mut self, name: &MetricName) { @@ -121,11 +140,20 @@ impl MetricCollection { #[derive(thiserror::Error, Debug, Clone)] pub enum Error { - #[error("Metric names must be unique across counters and gauges.")] - DuplicateMetricNames, + #[error("Metric names must be unique across all metrics types.")] + MetricNameCollisionInConstructor { + counter_names: Vec, + gauge_names: Vec, + }, + + #[error("Found duplicate metric name in list. Metric names must be unique across all metrics types.")] + DuplicateMetricNameInList { metric_name: MetricName }, #[error("Cannot merge metric '{metric_name}': it already exists in the current collection")] MetricNameCollisionInMerge { metric_name: MetricName }, + + #[error("Cannot create metric with name '{metric_name}': another metric with this name already exists")] + MetricNameCollisionAdding { metric_name: MetricName }, } /// Implements serialization for `MetricCollection`. @@ -179,8 +207,10 @@ impl<'de> Deserialize<'de> for MetricCollection { } } - let metric_collection = MetricCollection::new(MetricKindCollection::new(counters), MetricKindCollection::new(gauges)) - .map_err(serde::de::Error::custom)?; + let counters = MetricKindCollection::new(counters).map_err(serde::de::Error::custom)?; + let gauges = MetricKindCollection::new(gauges).map_err(serde::de::Error::custom)?; + + let metric_collection = MetricCollection::new(counters, gauges).map_err(serde::de::Error::custom)?; Ok(metric_collection) } @@ -213,20 +243,21 @@ pub struct MetricKindCollection { impl MetricKindCollection { /// Creates a new `MetricKindCollection` from a vector of metrics /// - /// # Panics + /// # Errors /// - /// Panics if duplicate metric names are found - #[must_use] - pub fn new(metrics: Vec>) -> Self { + /// Returns an error if duplicate metric names are passed. + pub fn new(metrics: Vec>) -> Result { let mut map = HashMap::with_capacity(metrics.len()); for metric in metrics { - assert!( - map.insert(metric.name().clone(), metric).is_none(), - "Duplicate MetricName found in MetricKindCollection" - ); + let metric_name = metric.name().clone(); + + if let Some(_old_metric) = map.insert(metric.name().clone(), metric) { + return Err(Error::DuplicateMetricNameInList { metric_name }); + } } - Self { metrics: map } + + Ok(Self { metrics: map }) } /// Returns an iterator over all metric names in this collection. @@ -234,10 +265,18 @@ impl MetricKindCollection { self.metrics.keys() } + /// # Panics + /// + /// It should not panic as long as empty sample collections are allowed. pub fn ensure_metric_exists(&mut self, name: &MetricName) { if !self.metrics.contains_key(name) { - self.metrics - .insert(name.clone(), Metric::new(name.clone(), SampleCollection::new(vec![]))); + self.metrics.insert( + name.clone(), + Metric::new( + name.clone(), + SampleCollection::new(vec![]).expect("Empty sample collection creation should not fail"), + ), + ); } } } @@ -369,12 +408,14 @@ mod tests { MetricCollection::new( MetricKindCollection::new(vec![Metric::new( metric_name!("http_tracker_core_announce_requests_received_total"), - SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set_1.clone())]), - )]), + SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set_1.clone())]).unwrap(), + )]) + .unwrap(), MetricKindCollection::new(vec![Metric::new( metric_name!("udp_tracker_server_performance_avg_announce_processing_time_ns"), - SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set_1.clone())]), - )]), + SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set_1.clone())]).unwrap(), + )]) + .unwrap(), ) .unwrap() } @@ -446,41 +487,47 @@ mod tests { } #[test] - #[should_panic(expected = "Metric names must be unique across counters and gauges")] fn it_should_not_allow_duplicate_names_across_types() { - let counter = MetricKindCollection::new(vec![Metric::new(metric_name!("test_metric"), SampleCollection::new(vec![]))]); - - let gauge = MetricKindCollection::new(vec![Metric::new(metric_name!("test_metric"), SampleCollection::new(vec![]))]); + let counters = + MetricKindCollection::new(vec![Metric::new(metric_name!("test_metric"), SampleCollection::default())]).unwrap(); + let gauges = + MetricKindCollection::new(vec![Metric::new(metric_name!("test_metric"), SampleCollection::default())]).unwrap(); - let _unused = MetricCollection::new(counter, gauge); + assert!(MetricCollection::new(counters, gauges).is_err()); } #[test] - #[should_panic(expected = "Cannot create gauge with name 'test_metric': a counter with this name already exists")] fn it_should_not_allow_creating_a_gauge_with_the_same_name_as_a_counter() { let mut collection = MetricCollection::default(); let label_set = LabelSet::default(); let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); // First create a counter - collection.increase_counter(&metric_name!("test_metric"), &label_set, time); + collection + .increase_counter(&metric_name!("test_metric"), &label_set, time) + .unwrap(); + + // Then try to create a gauge with the same name + let result = collection.set_gauge(&metric_name!("test_metric"), &label_set, 1.0, time); - // Then try to create a gauge with the same name - this should panic - collection.set_gauge(&metric_name!("test_metric"), &label_set, 1.0, time); + assert!(result.is_err()); } #[test] - #[should_panic(expected = "Cannot create counter with name 'test_metric': a gauge with this name already exists")] fn it_should_not_allow_creating_a_counter_with_the_same_name_as_a_gauge() { let mut collection = MetricCollection::default(); let label_set = LabelSet::default(); let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); // First set the gauge - collection.set_gauge(&metric_name!("test_metric"), &label_set, 1.0, time); + collection + .set_gauge(&metric_name!("test_metric"), &label_set, 1.0, time) + .unwrap(); + + // Then try to create a counter with the same name + let result = collection.increase_counter(&metric_name!("test_metric"), &label_set, time); - // Then try to create a counter with the same name - this should panic - collection.increase_counter(&metric_name!("test_metric"), &label_set, time); + assert!(result.is_err()); } #[test] @@ -540,9 +587,11 @@ mod tests { SampleCollection::new(vec![ Sample::new(Counter::new(1), time, label_set_1.clone()), Sample::new(Counter::new(2), time, label_set_2.clone()), - ]), - )]), - MetricKindCollection::new(vec![]), + ]) + .unwrap(), + )]) + .unwrap(), + MetricKindCollection::default(), ) .unwrap(); @@ -563,8 +612,8 @@ mod tests { #[test] fn it_should_exclude_metrics_without_samples_from_prometheus_format() { - let mut counters = MetricKindCollection::new(vec![]); - let mut gauges = MetricKindCollection::new(vec![]); + let mut counters = MetricKindCollection::default(); + let mut gauges = MetricKindCollection::default(); counters.ensure_metric_exists(&metric_name!("test_counter")); gauges.ensure_metric_exists(&metric_name!("test_gauge")); @@ -592,14 +641,19 @@ mod tests { let mut metric_collection = MetricCollection::new( MetricKindCollection::new(vec![Metric::new( metric_name!("test_counter"), - SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]), - )]), - MetricKindCollection::new(vec![]), + SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(), + )]) + .unwrap(), + MetricKindCollection::default(), ) .unwrap(); - metric_collection.increase_counter(&metric_name!("test_counter"), &label_set, time); - metric_collection.increase_counter(&metric_name!("test_counter"), &label_set, time); + metric_collection + .increase_counter(&metric_name!("test_counter"), &label_set, time) + .unwrap(); + metric_collection + .increase_counter(&metric_name!("test_counter"), &label_set, time) + .unwrap(); assert_eq!( metric_collection.get_counter_value(&metric_name!("test_counter"), &label_set), @@ -613,10 +667,14 @@ mod tests { let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = - MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])).unwrap(); + MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); - metric_collection.increase_counter(&metric_name!("test_counter"), &label_set, time); - metric_collection.increase_counter(&metric_name!("test_counter"), &label_set, time); + metric_collection + .increase_counter(&metric_name!("test_counter"), &label_set, time) + .unwrap(); + metric_collection + .increase_counter(&metric_name!("test_counter"), &label_set, time) + .unwrap(); assert_eq!( metric_collection.get_counter_value(&metric_name!("test_counter"), &label_set), @@ -627,7 +685,7 @@ mod tests { #[test] fn it_should_allow_making_sure_a_counter_exists_without_increasing_it() { let mut metric_collection = - MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])).unwrap(); + MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); metric_collection.ensure_counter_exists(&metric_name!("test_counter")); @@ -637,7 +695,7 @@ mod tests { #[test] fn it_should_allow_describing_a_counter_before_using_it() { let mut metric_collection = - MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])).unwrap(); + MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); metric_collection.describe_counter(&metric_name!("test_counter"), None, None); @@ -645,21 +703,22 @@ mod tests { } #[test] - #[should_panic(expected = "Duplicate MetricName found in MetricKindCollection")] fn it_should_not_allow_duplicate_metric_names_when_instantiating() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); - let _unused = MetricKindCollection::new(vec![ + let result = MetricKindCollection::new(vec![ Metric::new( metric_name!("test_counter"), - SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]), + SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(), ), Metric::new( metric_name!("test_counter"), - SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]), + SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(), ), ]); + + assert!(result.is_err()); } } @@ -677,15 +736,18 @@ mod tests { let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = MetricCollection::new( - MetricKindCollection::new(vec![]), + MetricKindCollection::default(), MetricKindCollection::new(vec![Metric::new( metric_name!("test_gauge"), - SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]), - )]), + SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(), + )]) + .unwrap(), ) .unwrap(); - metric_collection.set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time); + metric_collection + .set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time) + .unwrap(); assert_eq!( metric_collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), @@ -699,9 +761,11 @@ mod tests { let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); let mut metric_collection = - MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])).unwrap(); + MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); - metric_collection.set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time); + metric_collection + .set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time) + .unwrap(); assert_eq!( metric_collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), @@ -712,7 +776,7 @@ mod tests { #[test] fn it_should_allow_making_sure_a_gauge_exists_without_setting_it() { let mut metric_collection = - MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])).unwrap(); + MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); metric_collection.ensure_gauge_exists(&metric_name!("test_gauge")); @@ -722,7 +786,7 @@ mod tests { #[test] fn it_should_allow_describing_a_gauge_before_using_it() { let mut metric_collection = - MetricCollection::new(MetricKindCollection::new(vec![]), MetricKindCollection::new(vec![])).unwrap(); + MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); metric_collection.describe_gauge(&metric_name!("test_gauge"), None, None); @@ -730,21 +794,22 @@ mod tests { } #[test] - #[should_panic(expected = "Duplicate MetricName found in MetricKindCollection")] fn it_should_not_allow_duplicate_metric_names_when_instantiating() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); - let _unused = MetricKindCollection::new(vec![ + let result = MetricKindCollection::new(vec![ Metric::new( metric_name!("test_gauge"), - SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]), + SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(), ), Metric::new( metric_name!("test_gauge"), - SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]), + SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(), ), ]); + + assert!(result.is_err()); } } } diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index 13a4840d5..2680c442f 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -28,9 +28,13 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura let mut label_set = LabelSet::from(context); label_set.upsert(label_name!("request_kind"), LabelValue::new("connect")); - stats_repository + match stats_repository .increase_counter(&metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; } Event::UdpAnnounce { context } => { // Global fixed metrics @@ -49,9 +53,13 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura let mut label_set = LabelSet::from(context); label_set.upsert(label_name!("request_kind"), LabelValue::new("announce")); - stats_repository + match stats_repository .increase_counter(&metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; } Event::UdpScrape { context } => { // Global fixed metrics @@ -70,9 +78,13 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura let mut label_set = LabelSet::from(context); label_set.upsert(label_name!("request_kind"), LabelValue::new("scrape")); - stats_repository + match stats_repository .increase_counter(&metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; } } diff --git a/packages/udp-tracker-core/src/statistics/metrics.rs b/packages/udp-tracker-core/src/statistics/metrics.rs index 23cec8036..94aa7d08f 100644 --- a/packages/udp-tracker-core/src/statistics/metrics.rs +++ b/packages/udp-tracker-core/src/statistics/metrics.rs @@ -1,7 +1,7 @@ use serde::Serialize; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; -use torrust_tracker_metrics::metric_collection::MetricCollection; +use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; use torrust_tracker_primitives::DurationSinceUnixEpoch; /// Metrics collected by the tracker. @@ -37,11 +37,30 @@ pub struct Metrics { } impl Metrics { - pub fn increase_counter(&mut self, metric_name: &MetricName, labels: &LabelSet, now: DurationSinceUnixEpoch) { - self.metric_collection.increase_counter(metric_name, labels, now); + /// # Errors + /// + /// This function returns an error if the metric does not exist and it + /// cannot be created. + pub fn increase_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increase_counter(metric_name, labels, now) } - pub fn set_gauge(&mut self, metric_name: &MetricName, labels: &LabelSet, value: f64, now: DurationSinceUnixEpoch) { - self.metric_collection.set_gauge(metric_name, labels, value, now); + /// # Errors + /// + /// This function returns an error if the metric does not exist and it + /// cannot be created. + pub fn set_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_gauge(metric_name, labels, value, now) } } diff --git a/packages/udp-tracker-core/src/statistics/repository.rs b/packages/udp-tracker-core/src/statistics/repository.rs index 49c91c751..c68fa14f7 100644 --- a/packages/udp-tracker-core/src/statistics/repository.rs +++ b/packages/udp-tracker-core/src/statistics/repository.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use tokio::sync::{RwLock, RwLockReadGuard}; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::Error; use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::describe_metrics; @@ -68,9 +69,22 @@ impl Repository { drop(stats_lock); } - pub async fn increase_counter(&self, metric_name: &MetricName, labels: &LabelSet, now: DurationSinceUnixEpoch) { + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increase the counter. + pub async fn increase_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { let mut stats_lock = self.stats.write().await; - stats_lock.increase_counter(metric_name, labels, now); + + let result = stats_lock.increase_counter(metric_name, labels, now); + drop(stats_lock); + + result } } diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 430bbc34c..092ce93f2 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -23,26 +23,34 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura stats_repository.increase_udp_requests_aborted().await; // Extendable metrics - stats_repository + match stats_repository .increase_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &LabelSet::from(context), now, ) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; } Event::UdpRequestBanned { context } => { // Global fixed metrics stats_repository.increase_udp_requests_banned().await; // Extendable metrics - stats_repository + match stats_repository .increase_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), &LabelSet::from(context), now, ) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; } Event::UdpRequestReceived { context } => { // Global fixed metrics @@ -56,13 +64,17 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura } // Extendable metrics - stats_repository + match stats_repository .increase_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &LabelSet::from(context), now, ) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; } Event::UdpRequestAccepted { context, kind } => { // Global fixed metrics @@ -99,9 +111,13 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura label_set.upsert(label_name!("kind"), LabelValue::new(&kind.to_string())); - stats_repository + match stats_repository .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &label_set, now) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; } Event::UdpResponseSent { context, @@ -130,14 +146,18 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura let mut label_set = LabelSet::from(context.clone()); label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); - stats_repository + match stats_repository .set_gauge( &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), &label_set, new_avg, now, ) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Connect.to_string())) } @@ -151,14 +171,18 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura let mut label_set = LabelSet::from(context.clone()); label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); - stats_repository + match stats_repository .set_gauge( &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), &label_set, new_avg, now, ) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Announce.to_string())) } @@ -172,14 +196,18 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura let mut label_set = LabelSet::from(context.clone()); label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); - stats_repository + match stats_repository .set_gauge( &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), &label_set, new_avg, now, ) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Scrape.to_string())) } @@ -196,9 +224,13 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura } label_set.upsert(label_name!("result"), result_label_value); - stats_repository + match stats_repository .increase_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &label_set, now) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; } Event::UdpError { context } => { // Global fixed metrics @@ -212,9 +244,13 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura } // Extendable metrics - stats_repository + match stats_repository .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &LabelSet::from(context), now) - .await; + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; } } diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index 4fe07e7da..7b18f6418 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -1,7 +1,7 @@ use serde::Serialize; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; -use torrust_tracker_metrics::metric_collection::MetricCollection; +use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; use torrust_tracker_primitives::DurationSinceUnixEpoch; /// Metrics collected by the UDP tracker server. @@ -69,11 +69,28 @@ pub struct Metrics { } impl Metrics { - pub fn increase_counter(&mut self, metric_name: &MetricName, labels: &LabelSet, now: DurationSinceUnixEpoch) { - self.metric_collection.increase_counter(metric_name, labels, now); + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increase_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increase_counter(metric_name, labels, now) } - pub fn set_gauge(&mut self, metric_name: &MetricName, labels: &LabelSet, value: f64, now: DurationSinceUnixEpoch) { - self.metric_collection.set_gauge(metric_name, labels, value, now); + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn set_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_gauge(metric_name, labels, value, now) } } diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index c33c1231c..1a1db89c7 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -4,6 +4,7 @@ use std::time::Duration; use tokio::sync::{RwLock, RwLockReadGuard}; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::Error; use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::describe_metrics; @@ -181,15 +182,42 @@ impl Repository { drop(stats_lock); } - pub async fn increase_counter(&self, metric_name: &MetricName, labels: &LabelSet, now: DurationSinceUnixEpoch) { + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increase the counter. + pub async fn increase_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { let mut stats_lock = self.stats.write().await; - stats_lock.increase_counter(metric_name, labels, now); + + let result = stats_lock.increase_counter(metric_name, labels, now); + drop(stats_lock); + + result } - pub async fn set_gauge(&self, metric_name: &MetricName, labels: &LabelSet, value: f64, now: DurationSinceUnixEpoch) { + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increase the counter. + pub async fn set_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { let mut stats_lock = self.stats.write().await; - stats_lock.set_gauge(metric_name, labels, value, now); + + let result = stats_lock.set_gauge(metric_name, labels, value, now); + drop(stats_lock); + + result } } From 2ccb247ff5e890708fdfd3d89ba3bac8c659b6d7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 15 Apr 2025 16:44:52 +0100 Subject: [PATCH 0958/1297] refactor: [#1445] return errors instead of panicking in the SampleCollection struct --- packages/metrics/src/metric/mod.rs | 6 +-- packages/metrics/src/sample_collection.rs | 65 ++++++++++++----------- 2 files changed, 37 insertions(+), 34 deletions(-) diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index 777981fd8..ecce90f18 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -108,7 +108,7 @@ mod tests { let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); - let samples = SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set.clone())]); + let samples = SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set.clone())]).unwrap(); Metric::::new(name.clone(), samples) } @@ -154,7 +154,7 @@ mod tests { let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); - let samples = SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set.clone())]); + let samples = SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set.clone())]).unwrap(); let metric = Metric::::new(name.clone(), samples); @@ -188,7 +188,7 @@ mod tests { let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); - let samples = SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set.clone())]); + let samples = SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set.clone())]).unwrap(); let metric = Metric::::new(name.clone(), samples); diff --git a/packages/metrics/src/sample_collection.rs b/packages/metrics/src/sample_collection.rs index 436a4bc7d..49c839673 100644 --- a/packages/metrics/src/sample_collection.rs +++ b/packages/metrics/src/sample_collection.rs @@ -1,8 +1,8 @@ use std::collections::hash_map::Iter; -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::fmt::Write as _; -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::counter::Counter; @@ -18,23 +18,28 @@ pub struct SampleCollection { } impl SampleCollection { - /// # Panics + /// Creates a new `MetricKindCollection` from a vector of metrics /// - /// Panics if there are duplicate `LabelSets` in the provided samples. - #[must_use] - pub fn new(samples: Vec>) -> Self { + /// # Errors + /// + /// Returns an error if there are duplicate `LabelSets` in the provided + /// samples. + pub fn new(samples: Vec>) -> Result { let mut map: HashMap> = HashMap::with_capacity(samples.len()); for sample in samples { let (label_set, sample_data): (LabelSet, Measurement) = sample.into(); - assert!( - map.insert(label_set, sample_data).is_none(), - "Duplicate LabelSet found in SampleCollection" - ); + let label_set_clone = label_set.clone(); + + if let Some(_old_measurement) = map.insert(label_set, sample_data) { + return Err(Error::DuplicateLabelSetInList { + label_set: label_set_clone, + }); + } } - Self { samples: map } + Ok(Self { samples: map }) } #[must_use] @@ -59,6 +64,12 @@ impl SampleCollection { } } +#[derive(thiserror::Error, Debug, Clone)] +pub enum Error { + #[error("Found duplicate label set in list. Label set must be unique in a SampleCollection.")] + DuplicateLabelSetInList { label_set: LabelSet }, +} + impl SampleCollection { pub fn increment(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { let sample = self @@ -104,20 +115,11 @@ where where D: Deserializer<'de>, { - // First deserialize into a temporary Vec let samples = Vec::>::deserialize(deserializer)?; - // Check for duplicate label sets - let mut seen_labels = HashSet::new(); + let sample_collection = SampleCollection::new(samples).map_err(serde::de::Error::custom)?; - for sample in &samples { - if !seen_labels.insert(sample.labels()) { - return Err(de::Error::custom(format!("Duplicate label set found: {}", sample.labels()))); - } - } - - // Convert to HashMap-based storage - Ok(SampleCollection::new(samples)) + Ok(sample_collection) } } @@ -149,14 +151,15 @@ mod tests { } #[test] - #[should_panic(expected = "Duplicate LabelSet found in SampleCollection")] fn it_should_fail_trying_to_create_a_sample_collection_with_duplicate_label_sets() { let samples = vec![ Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), ]; - let _unused = SampleCollection::new(samples); + let result = SampleCollection::new(samples); + + assert!(result.is_err()); } #[test] @@ -165,7 +168,7 @@ mod tests { let sample = Sample::new(Counter::default(), sample_update_time(), label_set.clone()); - let collection = SampleCollection::new(vec![sample.clone()]); + let collection = SampleCollection::new(vec![sample.clone()]).unwrap(); let retrieved = collection.get(&label_set); @@ -180,7 +183,7 @@ mod tests { let sample_1 = Sample::new(Counter::new(1), sample_update_time(), label_set_1.clone()); let sample_2 = Sample::new(Counter::new(2), sample_update_time(), label_set_2.clone()); - let collection = SampleCollection::new(vec![sample_1.clone(), sample_2.clone()]); + let collection = SampleCollection::new(vec![sample_1.clone(), sample_2.clone()]).unwrap(); let retrieved = collection.get(&label_set_1); assert_eq!(retrieved.unwrap(), sample_1.measurement()); @@ -192,7 +195,7 @@ mod tests { #[test] fn it_should_return_the_number_of_samples_in_the_collection() { let samples = vec![Sample::new(Counter::default(), sample_update_time(), LabelSet::default())]; - let collection = SampleCollection::new(samples); + let collection = SampleCollection::new(samples).unwrap(); assert_eq!(collection.len(), 1); } @@ -208,14 +211,14 @@ mod tests { assert!(empty.is_empty()); let samples = vec![Sample::new(Counter::default(), sample_update_time(), LabelSet::default())]; - let collection = SampleCollection::new(samples); + let collection = SampleCollection::new(samples).unwrap(); assert!(!collection.is_empty()); } #[test] fn it_should_be_serializable_and_deserializable_for_json_format() { let sample = Sample::new(Counter::default(), sample_update_time(), LabelSet::default()); - let collection = SampleCollection::new(vec![sample]); + let collection = SampleCollection::new(vec![sample]).unwrap(); let serialized = serde_json::to_string(&collection).unwrap(); let deserialized: SampleCollection = serde_json::from_str(&serialized).unwrap(); @@ -240,7 +243,7 @@ mod tests { #[test] fn it_should_be_exportable_to_prometheus_format_when_empty() { let sample = Sample::new(Counter::default(), sample_update_time(), LabelSet::default()); - let collection = SampleCollection::new(vec![sample]); + let collection = SampleCollection::new(vec![sample]).unwrap(); let prometheus_output = collection.to_prometheus(); @@ -255,7 +258,7 @@ mod tests { LabelSet::from(vec![("labe_name_1", "label value value 1")]), ); - let collection = SampleCollection::new(vec![sample]); + let collection = SampleCollection::new(vec![sample]).unwrap(); let prometheus_output = collection.to_prometheus(); From 13ea09183a8b8eb6e632b63aa6a831efe5509917 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 21 Apr 2025 09:57:11 +0100 Subject: [PATCH 0959/1297] feat: [#1445] add logs to the event listener's initialization --- packages/http-tracker-core/src/statistics/keeper.rs | 9 ++++++++- packages/udp-tracker-core/src/statistics/keeper.rs | 9 ++++++++- packages/udp-tracker-server/src/statistics/keeper.rs | 9 ++++++++- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/keeper.rs b/packages/http-tracker-core/src/statistics/keeper.rs index 01a7a1569..1b69f032d 100644 --- a/packages/http-tracker-core/src/statistics/keeper.rs +++ b/packages/http-tracker-core/src/statistics/keeper.rs @@ -3,6 +3,7 @@ use tokio::sync::broadcast::Receiver; use super::event::listener::dispatch_events; use super::repository::Repository; use crate::event::Event; +use crate::HTTP_TRACKER_LOG_TARGET; /// The service responsible for keeping tracker metrics (listening to statistics events and handle them). /// @@ -29,7 +30,13 @@ impl Keeper { pub fn run_event_listener(&mut self, receiver: Receiver) { let stats_repository = self.repository.clone(); - tokio::spawn(async move { dispatch_events(receiver, stats_repository).await }); + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting HTTP tracker core event listener"); + + tokio::spawn(async move { + dispatch_events(receiver, stats_repository).await; + + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "HTTP tracker core event listener finished"); + }); } } diff --git a/packages/udp-tracker-core/src/statistics/keeper.rs b/packages/udp-tracker-core/src/statistics/keeper.rs index 16ea51aac..d72dcb260 100644 --- a/packages/udp-tracker-core/src/statistics/keeper.rs +++ b/packages/udp-tracker-core/src/statistics/keeper.rs @@ -3,6 +3,7 @@ use tokio::sync::broadcast::Receiver; use super::event::listener::dispatch_events; use super::repository::Repository; use crate::event::Event; +use crate::UDP_TRACKER_LOG_TARGET; /// The service responsible for keeping tracker metrics (listening to statistics events and handle them). /// @@ -29,7 +30,13 @@ impl Keeper { pub fn run_event_listener(&mut self, receiver: Receiver) { let stats_repository = self.repository.clone(); - tokio::spawn(async move { dispatch_events(receiver, stats_repository).await }); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker core event listener"); + + tokio::spawn(async move { + dispatch_events(receiver, stats_repository).await; + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker core event listener finished"); + }); } } diff --git a/packages/udp-tracker-server/src/statistics/keeper.rs b/packages/udp-tracker-server/src/statistics/keeper.rs index 62216ce88..c200b4cdf 100644 --- a/packages/udp-tracker-server/src/statistics/keeper.rs +++ b/packages/udp-tracker-server/src/statistics/keeper.rs @@ -1,3 +1,4 @@ +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use tokio::sync::broadcast::Receiver; use super::event::listener::dispatch_events; @@ -29,7 +30,13 @@ impl Keeper { pub fn run_event_listener(&mut self, receiver: Receiver) { let stats_repository = self.repository.clone(); - tokio::spawn(async move { dispatch_events(receiver, stats_repository).await }); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker server event listener"); + + tokio::spawn(async move { + dispatch_events(receiver, stats_repository).await; + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker core server listener finished"); + }); } } From 482a1be9f46234db628b260b148cf5102d83f53d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 21 Apr 2025 10:24:50 +0100 Subject: [PATCH 0960/1297] feat: [#1445] add request kind label to total errors metric --- packages/metrics/src/label/value.rs | 6 ++++++ packages/udp-tracker-server/src/event/mod.rs | 1 + packages/udp-tracker-server/src/handlers/error.rs | 1 + .../src/statistics/event/handler.rs | 13 +++++++++++-- 4 files changed, 19 insertions(+), 2 deletions(-) diff --git a/packages/metrics/src/label/value.rs b/packages/metrics/src/label/value.rs index 528a0e2ab..ffdbce333 100644 --- a/packages/metrics/src/label/value.rs +++ b/packages/metrics/src/label/value.rs @@ -25,6 +25,12 @@ impl PrometheusSerializable for LabelValue { } } +impl From for LabelValue { + fn from(value: String) -> Self { + Self(value) + } +} + #[cfg(test)] mod tests { use crate::label::value::LabelValue; diff --git a/packages/udp-tracker-server/src/event/mod.rs b/packages/udp-tracker-server/src/event/mod.rs index 0236b26a9..a1770acc0 100644 --- a/packages/udp-tracker-server/src/event/mod.rs +++ b/packages/udp-tracker-server/src/event/mod.rs @@ -31,6 +31,7 @@ pub enum Event { }, UdpError { context: ConnectionContext, + kind: Option, }, } diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index 6a1bce51c..9d9ee8b1d 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -64,6 +64,7 @@ pub async fn handle_error( udp_server_stats_event_sender .send_event(Event::UdpError { context: ConnectionContext::new(client_socket_addr, server_service_binding), + kind: req_kind, }) .await; } diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 092ce93f2..22253852c 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -232,7 +232,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura Err(err) => tracing::error!("Failed to increase the counter: {}", err), }; } - Event::UdpError { context } => { + Event::UdpError { context, kind } => { // Global fixed metrics match context.client_socket_addr().ip() { std::net::IpAddr::V4(_) => { @@ -244,8 +244,15 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura } // Extendable metrics + + let mut label_set = LabelSet::from(context); + + if let Some(kind) = kind { + label_set.upsert(label_name!("request_kind"), kind.to_string().into()); + } + match stats_repository - .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &LabelSet::from(context), now) + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &label_set, now) .await { Ok(()) => {} @@ -510,6 +517,7 @@ mod tests { ) .unwrap(), ), + kind: None, }, &stats_repository, CurrentClock::now(), @@ -641,6 +649,7 @@ mod tests { ) .unwrap(), ), + kind: None, }, &stats_repository, CurrentClock::now(), From ad782eb3dd66dbd2f125aed4bf99b61ec464ee8a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 21 Apr 2025 10:25:26 +0100 Subject: [PATCH 0961/1297] refactor: [#1445] rename metric label --- packages/udp-tracker-server/src/statistics/event/handler.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 22253852c..1e1502339 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -109,7 +109,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura let mut label_set = LabelSet::from(context); - label_set.upsert(label_name!("kind"), LabelValue::new(&kind.to_string())); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&kind.to_string())); match stats_repository .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &label_set, now) From f9ad729f2899ddd351506adb240757b73bbaa309 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 21 Apr 2025 10:49:13 +0100 Subject: [PATCH 0962/1297] feat: [#1445] add logs for metrics initialization --- Cargo.lock | 1 + packages/metrics/Cargo.toml | 1 + packages/metrics/src/lib.rs | 2 ++ packages/metrics/src/metric_collection.rs | 7 +++++-- packages/metrics/src/unit.rs | 1 + 5 files changed, 10 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e05894e3c..b72047f37 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4791,6 +4791,7 @@ dependencies = [ "serde_json", "thiserror 2.0.12", "torrust-tracker-primitives", + "tracing", ] [[package]] diff --git a/packages/metrics/Cargo.toml b/packages/metrics/Cargo.toml index 6520cf244..0597785f4 100644 --- a/packages/metrics/Cargo.toml +++ b/packages/metrics/Cargo.toml @@ -21,6 +21,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1.0.140" thiserror = "2" torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tracing = "0.1.41" [dev-dependencies] approx = "0.5.1" diff --git a/packages/metrics/src/lib.rs b/packages/metrics/src/lib.rs index fd677b891..95d70bf6c 100644 --- a/packages/metrics/src/lib.rs +++ b/packages/metrics/src/lib.rs @@ -8,6 +8,8 @@ pub mod sample; pub mod sample_collection; pub mod unit; +pub const METRICS_TARGET: &str = "METRICS"; + #[cfg(test)] mod tests { /// It removes leading and trailing whitespace from each line, and empty lines. diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index c719e6054..6a2a7735d 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -12,6 +12,7 @@ use super::prometheus::PrometheusSerializable; use crate::metric::description::MetricDescription; use crate::sample_collection::SampleCollection; use crate::unit::Unit; +use crate::METRICS_TARGET; // code-review: serialize in a deterministic order? For example: // - First the counter metrics ordered by name. @@ -56,7 +57,8 @@ impl MetricCollection { // Counter-specific methods - pub fn describe_counter(&mut self, name: &MetricName, _opt_unit: Option, _opt_description: Option) { + pub fn describe_counter(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option) { + tracing::info!(target: METRICS_TARGET, type = "counter", name = name.to_string(), unit = ?opt_unit, description = ?opt_description); self.counters.ensure_metric_exists(name); } @@ -97,7 +99,8 @@ impl MetricCollection { // Gauge-specific methods - pub fn describe_gauge(&mut self, name: &MetricName, _opt_unit: Option, _opt_description: Option) { + pub fn describe_gauge(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option) { + tracing::info!(target: METRICS_TARGET, type = "gauge", name = name.to_string(), unit = ?opt_unit, description = ?opt_description); self.gauges.ensure_metric_exists(name); } diff --git a/packages/metrics/src/unit.rs b/packages/metrics/src/unit.rs index b98e6836d..f7a528bed 100644 --- a/packages/metrics/src/unit.rs +++ b/packages/metrics/src/unit.rs @@ -4,6 +4,7 @@ //! The `Unit` enum is used to specify the unit of measurement for metrics. //! //! They were copied from the `metrics` crate, to allow future compatibility. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Unit { Count, Percent, From 4be6c974d08ca4fcd0ed0549dcdd1e8e60fa79aa Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 08:20:28 +0100 Subject: [PATCH 0963/1297] chore(deps): udpate dependencies ``` cargo update Updating crates.io index Locking 7 packages to latest compatible versions Updating brotli-decompressor v4.0.2 -> v4.0.3 Updating clap v4.5.36 -> v4.5.37 Updating clap_builder v4.5.36 -> v4.5.37 Updating libm v0.2.11 -> v0.2.12 Updating proc-macro2 v1.0.94 -> v1.0.95 Updating rand v0.9.0 -> v0.9.1 Updating signal-hook-registry v1.4.2 -> v1.4.5 ``` --- Cargo.lock | 43 +++++++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b72047f37..370562982 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -664,7 +664,7 @@ dependencies = [ "r2d2", "r2d2_mysql", "r2d2_sqlite", - "rand 0.9.0", + "rand 0.9.1", "serde", "serde_json", "testcontainers", @@ -696,7 +696,7 @@ dependencies = [ "futures", "lazy_static", "mockall", - "rand 0.9.0", + "rand 0.9.1", "serde", "thiserror 2.0.12", "tokio", @@ -857,9 +857,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "4.0.2" +version = "4.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74fa05ad7d803d413eb8380983b092cbbaf9a85f151b871360e7b00cd7060b37" +checksum = "a334ef7c9e23abf0ce748e8cd309037da93e606ad52eb372e4ce327a0dcfbdfd" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -1045,9 +1045,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.36" +version = "4.5.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2df961d8c8a0d08aa9945718ccf584145eee3f3aa06cddbeac12933781102e04" +checksum = "eccb054f56cbd38340b380d4a8e69ef1f02f1af43db2f0cc817a4774d80ae071" dependencies = [ "clap_builder", "clap_derive", @@ -1055,9 +1055,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.36" +version = "4.5.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "132dbda40fb6753878316a489d5a1242a8ef2f0d9e47ba01c951ea8aa7d013a5" +checksum = "efd9466fac8543255d3b1fcad4762c5e116ffe808c8a3043d4263cd4fd4862a2" dependencies = [ "anstream", "anstyle", @@ -2428,9 +2428,9 @@ dependencies = [ [[package]] name = "libm" -version = "0.2.11" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa" +checksum = "e6d154aedcb0b7a1e91a3fddbe2a8350d3da76ac9d0220ae20da5c7aa8269612" [[package]] name = "libredox" @@ -3205,9 +3205,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.94" +version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" +checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" dependencies = [ "unicode-ident", ] @@ -3322,13 +3322,12 @@ dependencies = [ [[package]] name = "rand" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" +checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.3", - "zerocopy 0.8.24", ] [[package]] @@ -3983,9 +3982,9 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "signal-hook-registry" -version = "1.4.2" +version = "1.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" +checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410" dependencies = [ "libc", ] @@ -4550,7 +4549,7 @@ dependencies = [ "hyper", "local-ip-address", "percent-encoding", - "rand 0.9.0", + "rand 0.9.1", "reqwest", "serde", "serde_bencode", @@ -4685,7 +4684,7 @@ dependencies = [ "futures", "local-ip-address", "mockall", - "rand 0.9.0", + "rand 0.9.1", "regex", "reqwest", "serde", @@ -4816,7 +4815,7 @@ dependencies = [ name = "torrust-tracker-test-helpers" version = "3.0.0-develop" dependencies = [ - "rand 0.9.0", + "rand 0.9.1", "torrust-tracker-configuration", "tracing", "tracing-subscriber", @@ -4856,7 +4855,7 @@ dependencies = [ "futures-util", "local-ip-address", "mockall", - "rand 0.9.0", + "rand 0.9.1", "ringbuf", "serde", "thiserror 2.0.12", @@ -5099,7 +5098,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9" dependencies = [ "getrandom 0.3.2", - "rand 0.9.0", + "rand 0.9.1", ] [[package]] From 53c869476813d9d729abc1b4df2ec842e6a99633 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 10:14:24 +0100 Subject: [PATCH 0964/1297] fix: clippy errors --- packages/http-tracker-core/src/statistics/mod.rs | 2 +- packages/metrics/src/metric_collection.rs | 4 ++-- packages/udp-tracker-core/src/statistics/mod.rs | 2 +- packages/udp-tracker-server/src/statistics/mod.rs | 14 +++++++------- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs index a5d6d37a5..d7a8da402 100644 --- a/packages/http-tracker-core/src/statistics/mod.rs +++ b/packages/http-tracker-core/src/statistics/mod.rs @@ -19,7 +19,7 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_counter( &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), - Some(MetricDescription::new("Total number of HTTP requests received")), + Some(&MetricDescription::new("Total number of HTTP requests received")), ); metrics diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index 6a2a7735d..9e89c3c4b 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -57,7 +57,7 @@ impl MetricCollection { // Counter-specific methods - pub fn describe_counter(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option) { + pub fn describe_counter(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option<&MetricDescription>) { tracing::info!(target: METRICS_TARGET, type = "counter", name = name.to_string(), unit = ?opt_unit, description = ?opt_description); self.counters.ensure_metric_exists(name); } @@ -99,7 +99,7 @@ impl MetricCollection { // Gauge-specific methods - pub fn describe_gauge(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option) { + pub fn describe_gauge(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option<&MetricDescription>) { tracing::info!(target: METRICS_TARGET, type = "gauge", name = name.to_string(), unit = ?opt_unit, description = ?opt_description); self.gauges.ensure_metric_exists(name); } diff --git a/packages/udp-tracker-core/src/statistics/mod.rs b/packages/udp-tracker-core/src/statistics/mod.rs index 40a30f51b..ec37deae7 100644 --- a/packages/udp-tracker-core/src/statistics/mod.rs +++ b/packages/udp-tracker-core/src/statistics/mod.rs @@ -19,7 +19,7 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), - Some(MetricDescription::new("Total number of UDP requests received")), + Some(&MetricDescription::new("Total number of UDP requests received")), ); metrics diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index 4eea13224..45c696fdb 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -25,43 +25,43 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), Some(Unit::Count), - Some(MetricDescription::new("Total number of UDP requests aborted")), + Some(&MetricDescription::new("Total number of UDP requests aborted")), ); metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), Some(Unit::Count), - Some(MetricDescription::new("Total number of UDP requests banned")), + Some(&MetricDescription::new("Total number of UDP requests banned")), ); metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), - Some(MetricDescription::new("Total number of UDP requests received")), + Some(&MetricDescription::new("Total number of UDP requests received")), ); metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), Some(Unit::Count), - Some(MetricDescription::new("Total number of UDP requests accepted")), + Some(&MetricDescription::new("Total number of UDP requests accepted")), ); metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), Some(Unit::Count), - Some(MetricDescription::new("Total number of UDP responses sent")), + Some(&MetricDescription::new("Total number of UDP responses sent")), ); metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), Some(Unit::Count), - Some(MetricDescription::new("Total number of errors processing UDP requests")), + Some(&MetricDescription::new("Total number of errors processing UDP requests")), ); metrics.metric_collection.describe_gauge( &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), Some(Unit::Nanoseconds), - Some(MetricDescription::new( + Some(&MetricDescription::new( "Average time to process a UDP connect request in nanoseconds", )), ); From a67e137f73e3c2b7b9c6eef32a6001a3a6017c3e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 12:00:15 +0100 Subject: [PATCH 0965/1297] feat: [#1376] add peer info to TcpAnnounce event --- packages/http-tracker-core/src/event/mod.rs | 18 +- packages/http-tracker-core/src/lib.rs | 29 +++ .../src/services/announce.rs | 213 ++++++++++++------ .../src/statistics/event/handler.rs | 9 +- 4 files changed, 200 insertions(+), 69 deletions(-) diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index ae997156a..0490fe2be 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -2,6 +2,7 @@ use std::net::{IpAddr, SocketAddr}; use torrust_tracker_metrics::label::{LabelSet, LabelValue}; use torrust_tracker_metrics::label_name; +use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::service_binding::ServiceBinding; pub mod sender; @@ -9,8 +10,21 @@ pub mod sender; /// A HTTP core event. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { - TcpAnnounce { connection: ConnectionContext }, - TcpScrape { connection: ConnectionContext }, + TcpAnnounce { + connection: ConnectionContext, + + /// The peer that is announcing itself to the tracker. + announced_peer: Peer, + + /// The peer that is added to the tracker. + /// + /// It might not be the same as the `announced_peer` because the tracker + /// can change the peer's IP address. + added_peer: Peer, + }, + TcpScrape { + connection: ConnectionContext, + }, } #[derive(Debug, PartialEq, Eq, Clone)] diff --git a/packages/http-tracker-core/src/lib.rs b/packages/http-tracker-core/src/lib.rs index c4f131bcb..1692a68fa 100644 --- a/packages/http-tracker-core/src/lib.rs +++ b/packages/http-tracker-core/src/lib.rs @@ -20,7 +20,11 @@ pub const HTTP_TRACKER_LOG_TARGET: &str = "HTTP TRACKER"; #[cfg(test)] pub(crate) mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; /// # Panics /// @@ -31,4 +35,29 @@ pub(crate) mod tests { .parse::() .expect("String should be a valid info hash") } + + pub fn sample_peer_using_ipv4() -> peer::Peer { + sample_peer() + } + + pub fn sample_peer_using_ipv6() -> peer::Peer { + let mut peer = sample_peer(); + peer.peer_addr = SocketAddr::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + 8080, + ); + peer + } + + pub fn sample_peer() -> peer::Peer { + peer::Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Started, + } + } } diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index c249cb4db..3ac4de1b9 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -21,6 +21,7 @@ use bittorrent_tracker_core::error::{AnnounceError, TrackerCoreError, WhitelistE use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::event; @@ -81,6 +82,8 @@ impl AnnounceService { let mut peer = peer_from_request(announce_request, &remote_client_ip); + let announced_peer = peer; + let peers_wanted = Self::peers_wanted(announce_request); let announce_data = self @@ -88,8 +91,16 @@ impl AnnounceService { .announce(&announce_request.info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; - self.send_event(remote_client_ip, opt_remote_client_port, server_service_binding.clone()) - .await; + let added_peer = peer; + + self.send_event( + remote_client_ip, + opt_remote_client_port, + server_service_binding.clone(), + announced_peer, + added_peer, + ) + .await; Ok(announce_data) } @@ -139,13 +150,24 @@ impl AnnounceService { } } - async fn send_event(&self, peer_ip: IpAddr, opt_peer_ip_port: Option, server_service_binding: ServiceBinding) { + async fn send_event( + &self, + peer_ip: IpAddr, + opt_peer_ip_port: Option, + server_service_binding: ServiceBinding, + announced_peer: Peer, + added_peer: Peer, + ) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { - http_stats_event_sender - .send_event(Event::TcpAnnounce { - connection: event::ConnectionContext::new(peer_ip, opt_peer_ip_port, server_service_binding), - }) - .await; + let event = Event::TcpAnnounce { + connection: event::ConnectionContext::new(peer_ip, opt_peer_ip_port, server_service_binding), + announced_peer, + added_peer, + }; + + tracing::debug!("Sending TcpAnnounce event: {:?}", event); + + http_stats_event_sender.send_event(event).await; } } } @@ -202,10 +224,9 @@ impl From for HttpAnnounceError { #[cfg(test)] mod tests { - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::net::SocketAddr; use std::sync::Arc; - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_tracker_core::announce_handler::AnnounceHandler; @@ -218,7 +239,6 @@ mod tests { use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_primitives::peer::Peer; - use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; struct CoreTrackerServices { @@ -269,31 +289,6 @@ mod tests { ) } - fn sample_peer_using_ipv4() -> peer::Peer { - sample_peer() - } - - fn sample_peer_using_ipv6() -> peer::Peer { - let mut peer = sample_peer(); - peer.peer_addr = SocketAddr::new( - IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - 8080, - ); - peer - } - - fn sample_peer() -> peer::Peer { - peer::Peer { - peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), - event: AnnounceEvent::Started, - } - } - fn sample_announce_request_for_peer(peer: Peer) -> (Announce, ClientIpSources) { let announce_request = Announce { info_hash: sample_info_hash(), @@ -335,7 +330,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; - use mockall::predicate::eq; + use mockall::predicate::{self}; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; @@ -343,14 +338,14 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; - use super::{sample_peer_using_ipv4, sample_peer_using_ipv6}; use crate::event; use crate::event::{ConnectionContext, Event}; use crate::services::announce::tests::{ initialize_core_tracker_services, initialize_core_tracker_services_with_config, sample_announce_request_for_peer, - sample_peer, MockHttpStatsEventSender, + MockHttpStatsEventSender, }; use crate::services::announce::AnnounceService; + use crate::tests::{sample_peer, sample_peer_using_ipv4, sample_peer_using_ipv6}; #[tokio::test] async fn it_should_return_the_announce_data() { @@ -393,16 +388,46 @@ mod tests { async fn it_should_send_the_tcp_4_announce_event_when_the_peer_uses_ipv4() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + let peer = sample_peer_using_ipv4(); + + let server_service_binding_clone = server_service_binding.clone(); + let peer_copy = peer; let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(Event::TcpAnnounce { - connection: ConnectionContext::new( - IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), - Some(8080), - server_service_binding.clone(), - ), + .with(predicate::function(move |event| { + let mut announced_peer = peer_copy; + announced_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + + let mut added_peer = peer; + added_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + + let expected_event = Event::TcpAnnounce { + connection: ConnectionContext::new( + IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), + Some(8080), + server_service_binding.clone(), + ), + announced_peer, + added_peer, + }; + + match (event, expected_event) { + ( + Event::TcpAnnounce { + connection: a_conn, + announced_peer: a1, + added_peer: a2, + }, + Event::TcpAnnounce { + connection: b_conn, + announced_peer: b1, + added_peer: b2, + }, + ) => *a_conn == b_conn && a1.peer_addr == b1.peer_addr && a2.peer_addr == b2.peer_addr, + _ => false, + } })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -413,8 +438,6 @@ mod tests { core_http_tracker_services.http_stats_event_sender = http_stats_event_sender; - let peer = sample_peer_using_ipv4(); - let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); let announce_service = AnnounceService::new( @@ -426,7 +449,7 @@ mod tests { ); let _announce_data = announce_service - .handle_announce(&announce_request, &client_ip_sources, &server_service_binding, None) + .handle_announce(&announce_request, &client_ip_sources, &server_service_binding_clone, None) .await .unwrap(); } @@ -453,20 +476,53 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + let peer = peer_with_the_ipv4_loopback_ip(); + + let server_service_binding_clone = server_service_binding.clone(); + let peer_copy = peer; - // Assert that the event sent is a TCP4 event let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(Event::TcpAnnounce { - connection: ConnectionContext::new( - IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), - Some(8080), - server_service_binding.clone(), - ), + .with(predicate::function(move |event| { + let mut announced_peer = peer_copy; + announced_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); + + let mut added_peer = peer; + added_peer.peer_addr = SocketAddr::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + 8080, + ); + + let expected_event = Event::TcpAnnounce { + connection: ConnectionContext::new( + IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), + Some(8080), + server_service_binding.clone(), + ), + announced_peer, + added_peer, + }; + + match (event, expected_event) { + ( + Event::TcpAnnounce { + connection: a_conn, + announced_peer: a1, + added_peer: a2, + }, + Event::TcpAnnounce { + connection: b_conn, + announced_peer: b1, + added_peer: b2, + }, + ) => *a_conn == b_conn && a1.peer_addr == b1.peer_addr && a2.peer_addr == b2.peer_addr, + _ => false, + } })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + let http_stats_event_sender: Arc>> = Arc::new(Some(Box::new(http_stats_event_sender_mock))); @@ -475,8 +531,6 @@ mod tests { core_http_tracker_services.http_stats_event_sender = http_stats_event_sender; - let peer = peer_with_the_ipv4_loopback_ip(); - let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); let announce_service = AnnounceService::new( @@ -488,7 +542,7 @@ mod tests { ); let _announce_data = announce_service - .handle_announce(&announce_request, &client_ip_sources, &server_service_binding, None) + .handle_announce(&announce_request, &client_ip_sources, &server_service_binding_clone, None) .await .unwrap(); } @@ -498,16 +552,45 @@ mod tests { { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); + let peer = sample_peer_using_ipv6(); + + let peer_copy = peer; let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() - .with(eq(Event::TcpAnnounce { - connection: ConnectionContext::new( - IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - Some(8080), - server_service_binding, - ), + .with(predicate::function(move |event| { + let announced_peer = peer_copy; + //announced_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + + let added_peer = peer; + //added_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + + let expected_event = Event::TcpAnnounce { + connection: ConnectionContext::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + Some(8080), + server_service_binding.clone(), + ), + announced_peer, + added_peer, + }; + + match (event, expected_event) { + ( + Event::TcpAnnounce { + connection: a_conn, + announced_peer: a1, + added_peer: a2, + }, + Event::TcpAnnounce { + connection: b_conn, + announced_peer: b1, + added_peer: b2, + }, + ) => *a_conn == b_conn && a1.peer_addr == b1.peer_addr && a2.peer_addr == b2.peer_addr, + _ => false, + } })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -517,8 +600,6 @@ mod tests { let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services(); core_http_tracker_services.http_stats_event_sender = http_stats_event_sender; - let peer = sample_peer_using_ipv6(); - let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); let announce_service = AnnounceService::new( diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index 182c86b01..b24ddfde6 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -14,7 +14,7 @@ use crate::statistics::HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; /// version of the event. pub async fn handle_event(event: Event, stats_repository: &Repository, now: DurationSinceUnixEpoch) { match event { - Event::TcpAnnounce { connection } => { + Event::TcpAnnounce { connection, .. } => { // Global fixed metrics match connection.client_ip_addr() { @@ -79,11 +79,13 @@ mod tests { use crate::event::{ConnectionContext, Event}; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; + use crate::tests::{sample_peer_using_ipv4, sample_peer_using_ipv6}; use crate::CurrentClock; #[tokio::test] async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { let stats_repository = Repository::new(); + let peer = sample_peer_using_ipv4(); handle_event( Event::TcpAnnounce { @@ -92,6 +94,8 @@ mod tests { Some(8080), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), + announced_peer: peer, + added_peer: peer, }, &stats_repository, CurrentClock::now(), @@ -128,6 +132,7 @@ mod tests { #[tokio::test] async fn should_increase_the_tcp6_announces_counter_when_it_receives_a_tcp6_announce_event() { let stats_repository = Repository::new(); + let peer = sample_peer_using_ipv6(); handle_event( Event::TcpAnnounce { @@ -136,6 +141,8 @@ mod tests { Some(8080), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), + announced_peer: peer, + added_peer: peer, }, &stats_repository, CurrentClock::now(), From 5d479b79030050aad0692af80be2212197c8f195 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 12:05:25 +0100 Subject: [PATCH 0966/1297] chore: add logs for sending TcpScrape event --- packages/http-tracker-core/src/services/scrape.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index baa406e63..072c76bb7 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -126,11 +126,13 @@ impl ScrapeService { server_service_binding: ServiceBinding, ) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { - http_stats_event_sender - .send_event(Event::TcpScrape { - connection: ConnectionContext::new(original_peer_ip, opt_original_peer_port, server_service_binding), - }) - .await; + let event = Event::TcpScrape { + connection: ConnectionContext::new(original_peer_ip, opt_original_peer_port, server_service_binding), + }; + + tracing::debug!("Sending TcpScrape event: {:?}", event); + + http_stats_event_sender.send_event(event).await; } } } From 4566ad58ee42ce0d6d56657a335ee98d4ef86b8b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 12:13:31 +0100 Subject: [PATCH 0967/1297] test: add test for Peer comparison --- packages/primitives/src/peer.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index c8ff1791d..20fc4bcb4 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -513,6 +513,22 @@ pub mod fixture { #[cfg(test)] pub mod test { + + mod peer { + use crate::peer::fixture::PeerBuilder; + + #[test] + fn should_be_comparable() { + let seeder1 = PeerBuilder::seeder().build(); + let seeder2 = PeerBuilder::seeder().build(); + + let leecher1 = PeerBuilder::leecher().build(); + + assert!(seeder1 == seeder2); + assert!(seeder1 != leecher1); + } + } + mod torrent_peer_id { use aquatic_udp_protocol::PeerId; From 92f049e786dac3999aa2d15a18ee9d1fae4ba1ba Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 12:24:42 +0100 Subject: [PATCH 0968/1297] tests: add tests for HTTP tracker core events comparison This test has been added becuase this code was not working: ```rust let mut announced_peer = peer_copy; announced_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); let mut added_peer = peer; added_peer.peer_addr = SocketAddr::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), 8080, ); let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() .with(eq(Event::TcpAnnounce { connection: ConnectionContext::new( IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), Some(8080), server_service_binding, ), announced_peer: peer, added_peer: peer, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); ``` using the same events: Event sent: TcpAnnounce { connection: ConnectionContext { client: ClientConnectionContext { ip_addr: 127.0.0.1, port: Some(8080) }, server: ServerConnectionContext { service_binding: ServiceBinding { protocol: HTTP, bind_address: 127.0.0.1:7070 } } }, announced_peer: Peer { peer_id: PeerId([45, 113, 66, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48]), peer_addr: 127.0.0.1:8080, updated: 1745316858.487824645s, uploaded: NumberOfBytes(I64(0)), downloaded: NumberOfBytes(I64(0)), left: NumberOfBytes(I64(0)), event: Started }, added_peer: Peer { peer_id: PeerId([45, 113, 66, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48]), peer_addr: [6969:6969:6969:6969:6969:6969:6969:6969]:8080, updated: 1745316858.487824645s, uploaded: NumberOfBytes(I64(0)), downloaded: NumberOfBytes(I64(0)), left: NumberOfBytes(I64(0)), event: Started } } Event expected in the mock: TcpAnnounce { connection: ConnectionContext { client: ClientConnectionContext { ip_addr: 127.0.0.1, port: Some(8080) }, server: ServerConnectionContext { service_binding: ServiceBinding { protocol: HTTP, bind_address: 127.0.0.1:7070 } } }, announced_peer: Peer { peer_id: PeerId([45, 113, 66, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48]), peer_addr: 127.0.0.1:8080, updated: 1745316858.487824645s, uploaded: NumberOfBytes(I64(0)), downloaded: NumberOfBytes(I64(0)), left: NumberOfBytes(I64(0)), event: Started }, added_peer: Peer { peer_id: PeerId([45, 113, 66, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48]), peer_addr: [6969:6969:6969:6969:6969:6969:6969:6969]:8080, updated: 1745316858.487824645s, uploaded: NumberOfBytes(I64(0)), downloaded: NumberOfBytes(I64(0)), left: NumberOfBytes(I64(0)), event: Started } } That's one of the reasons why the expectation was changed. The other reason is the only relevant part for the peer in the test is the updated peer address. --- packages/http-tracker-core/src/event/mod.rs | 41 +++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index 0490fe2be..2eac2b9d6 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -94,3 +94,44 @@ impl From for LabelSet { ]) } } + +#[cfg(test)] +pub mod test { + + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::service_binding::Protocol; + + #[test] + fn events_should_be_comparable() { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use torrust_tracker_primitives::service_binding::ServiceBinding; + + use crate::event::{ConnectionContext, Event}; + + let event1 = Event::TcpAnnounce { + connection: ConnectionContext::new( + IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), + Some(8080), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), + ), + announced_peer: Peer::default(), + added_peer: Peer::default(), + }; + + let event2 = Event::TcpAnnounce { + connection: ConnectionContext::new( + IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), + Some(8080), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), + ), + announced_peer: Peer::default(), + added_peer: Peer::default(), + }; + + let event1_clone = event1.clone(); + + assert!(event1 == event1_clone); + assert!(event1 != event2); + } +} From 657a5d0c0ac1c7094d59e0c8de6783b38b9d0eb8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 16:36:21 +0100 Subject: [PATCH 0969/1297] refactor: [#1376] remove initial peer state from event. Only the peer IP may change before adding the peer to the swarm, and the original remote client ip is already included in the `ConnectionCotext`. --- packages/http-tracker-core/src/event/mod.rs | 22 ++-- .../src/services/announce.rs | 100 ++++++------------ .../src/statistics/event/handler.rs | 12 +-- packages/primitives/src/peer.rs | 2 + 4 files changed, 46 insertions(+), 90 deletions(-) diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index 2eac2b9d6..5e2a0f384 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -2,7 +2,7 @@ use std::net::{IpAddr, SocketAddr}; use torrust_tracker_metrics::label::{LabelSet, LabelValue}; use torrust_tracker_metrics::label_name; -use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; pub mod sender; @@ -12,15 +12,7 @@ pub mod sender; pub enum Event { TcpAnnounce { connection: ConnectionContext, - - /// The peer that is announcing itself to the tracker. - announced_peer: Peer, - - /// The peer that is added to the tracker. - /// - /// It might not be the same as the `announced_peer` because the tracker - /// can change the peer's IP address. - added_peer: Peer, + announcement: PeerAnnouncement, }, TcpScrape { connection: ConnectionContext, @@ -109,14 +101,15 @@ pub mod test { use crate::event::{ConnectionContext, Event}; + let remote_client_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); + let event1 = Event::TcpAnnounce { connection: ConnectionContext::new( - IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), + remote_client_ip, Some(8080), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), - announced_peer: Peer::default(), - added_peer: Peer::default(), + announcement: Peer::default(), }; let event2 = Event::TcpAnnounce { @@ -125,8 +118,7 @@ pub mod test { Some(8080), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), - announced_peer: Peer::default(), - added_peer: Peer::default(), + announcement: Peer::default(), }; let event1_clone = event1.clone(); diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 3ac4de1b9..c27d3dbee 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -21,7 +21,7 @@ use bittorrent_tracker_core::error::{AnnounceError, TrackerCoreError, WhitelistE use bittorrent_tracker_core::whitelist; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::AnnounceData; -use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::event; @@ -78,12 +78,10 @@ impl AnnounceService { self.authorize(announce_request.info_hash).await?; - let (remote_client_ip, opt_remote_client_port) = self.resolve_remote_client_address(client_ip_sources)?; + let (remote_client_ip, opt_remote_client_port) = self.resolve_remote_client_ip(client_ip_sources)?; let mut peer = peer_from_request(announce_request, &remote_client_ip); - let announced_peer = peer; - let peers_wanted = Self::peers_wanted(announce_request); let announce_data = self @@ -91,16 +89,8 @@ impl AnnounceService { .announce(&announce_request.info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; - let added_peer = peer; - - self.send_event( - remote_client_ip, - opt_remote_client_port, - server_service_binding.clone(), - announced_peer, - added_peer, - ) - .await; + self.send_event(remote_client_ip, opt_remote_client_port, server_service_binding.clone(), peer) + .await; Ok(announce_data) } @@ -122,7 +112,7 @@ impl AnnounceService { } /// Resolves the client's real IP address considering proxy headers - fn resolve_remote_client_address( + fn resolve_remote_client_ip( &self, client_ip_sources: &ClientIpSources, ) -> Result<(IpAddr, Option), PeerIpResolutionError> { @@ -152,17 +142,15 @@ impl AnnounceService { async fn send_event( &self, - peer_ip: IpAddr, + remote_client_ip: IpAddr, opt_peer_ip_port: Option, server_service_binding: ServiceBinding, - announced_peer: Peer, - added_peer: Peer, + announcement: PeerAnnouncement, ) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { let event = Event::TcpAnnounce { - connection: event::ConnectionContext::new(peer_ip, opt_peer_ip_port, server_service_binding), - announced_peer, - added_peer, + connection: event::ConnectionContext::new(remote_client_ip, opt_peer_ip_port, server_service_binding), + announcement, }; tracing::debug!("Sending TcpAnnounce event: {:?}", event); @@ -389,6 +377,7 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let peer = sample_peer_using_ipv4(); + let remote_client_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); let server_service_binding_clone = server_service_binding.clone(); let peer_copy = peer; @@ -400,32 +389,25 @@ mod tests { let mut announced_peer = peer_copy; announced_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); - let mut added_peer = peer; - added_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); + let mut announcement = peer; + announcement.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let expected_event = Event::TcpAnnounce { - connection: ConnectionContext::new( - IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), - Some(8080), - server_service_binding.clone(), - ), - announced_peer, - added_peer, + connection: ConnectionContext::new(remote_client_ip, Some(8080), server_service_binding.clone()), + announcement, }; match (event, expected_event) { ( Event::TcpAnnounce { connection: a_conn, - announced_peer: a1, - added_peer: a2, + announcement: a2, }, Event::TcpAnnounce { connection: b_conn, - announced_peer: b1, - added_peer: b2, + announcement: b2, }, - ) => *a_conn == b_conn && a1.peer_addr == b1.peer_addr && a2.peer_addr == b2.peer_addr, + ) => *a_conn == b_conn && a2.peer_addr == b2.peer_addr, _ => false, } })) @@ -477,6 +459,7 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let peer = peer_with_the_ipv4_loopback_ip(); + let remote_client_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let server_service_binding_clone = server_service_binding.clone(); let peer_copy = peer; @@ -488,35 +471,28 @@ mod tests { let mut announced_peer = peer_copy; announced_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); - let mut added_peer = peer; - added_peer.peer_addr = SocketAddr::new( + let mut peer_announcement = peer; + peer_announcement.peer_addr = SocketAddr::new( IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), 8080, ); let expected_event = Event::TcpAnnounce { - connection: ConnectionContext::new( - IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), - Some(8080), - server_service_binding.clone(), - ), - announced_peer, - added_peer, + connection: ConnectionContext::new(remote_client_ip, Some(8080), server_service_binding.clone()), + announcement: peer_announcement, }; match (event, expected_event) { ( Event::TcpAnnounce { connection: a_conn, - announced_peer: a1, - added_peer: a2, + announcement: a2, }, Event::TcpAnnounce { connection: b_conn, - announced_peer: b1, - added_peer: b2, + announcement: b2, }, - ) => *a_conn == b_conn && a1.peer_addr == b1.peer_addr && a2.peer_addr == b2.peer_addr, + ) => *a_conn == b_conn && a2.peer_addr == b2.peer_addr, _ => false, } })) @@ -553,42 +529,28 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let peer = sample_peer_using_ipv6(); - - let peer_copy = peer; + let remote_client_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock .expect_send_event() .with(predicate::function(move |event| { - let announced_peer = peer_copy; - //announced_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); - - let added_peer = peer; - //added_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); - let expected_event = Event::TcpAnnounce { - connection: ConnectionContext::new( - IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - Some(8080), - server_service_binding.clone(), - ), - announced_peer, - added_peer, + connection: ConnectionContext::new(remote_client_ip, Some(8080), server_service_binding.clone()), + announcement: peer, }; match (event, expected_event) { ( Event::TcpAnnounce { connection: a_conn, - announced_peer: a1, - added_peer: a2, + announcement: a2, }, Event::TcpAnnounce { connection: b_conn, - announced_peer: b1, - added_peer: b2, + announcement: b2, }, - ) => *a_conn == b_conn && a1.peer_addr == b1.peer_addr && a2.peer_addr == b2.peer_addr, + ) => *a_conn == b_conn && a2.peer_addr == b2.peer_addr, _ => false, } })) diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index b24ddfde6..df8f29175 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -86,16 +86,16 @@ mod tests { async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { let stats_repository = Repository::new(); let peer = sample_peer_using_ipv4(); + let remote_client_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)); handle_event( Event::TcpAnnounce { connection: ConnectionContext::new( - IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), + remote_client_ip, Some(8080), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), - announced_peer: peer, - added_peer: peer, + announcement: peer, }, &stats_repository, CurrentClock::now(), @@ -133,16 +133,16 @@ mod tests { async fn should_increase_the_tcp6_announces_counter_when_it_receives_a_tcp6_announce_event() { let stats_repository = Repository::new(); let peer = sample_peer_using_ipv6(); + let remote_client_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); handle_event( Event::TcpAnnounce { connection: ConnectionContext::new( - IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + remote_client_ip, Some(8080), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), - announced_peer: peer, - added_peer: peer, + announcement: peer, }, &stats_repository, CurrentClock::now(), diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index 20fc4bcb4..bd753b220 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -32,6 +32,8 @@ use zerocopy::FromBytes as _; use crate::DurationSinceUnixEpoch; +pub type PeerAnnouncement = Peer; + /// Peer struct used by the core `Tracker`. /// /// A sample peer: From bc02e9bd0690f46b19e9bdd06b53fb4795512e98 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 16:54:17 +0100 Subject: [PATCH 0970/1297] feat: [#1376] add info-hash to bittorrent_http_tracker_core::event::TcpAnnounce --- packages/http-tracker-core/src/event/mod.rs | 31 ++++++++++ .../src/services/announce.rs | 61 ++++++------------- .../src/statistics/event/handler.rs | 4 +- 3 files changed, 52 insertions(+), 44 deletions(-) diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index 5e2a0f384..9f7635ffe 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -1,5 +1,6 @@ use std::net::{IpAddr, SocketAddr}; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_metrics::label::{LabelSet, LabelValue}; use torrust_tracker_metrics::label_name; use torrust_tracker_primitives::peer::PeerAnnouncement; @@ -12,6 +13,7 @@ pub mod sender; pub enum Event { TcpAnnounce { connection: ConnectionContext, + info_hash: InfoHash, announcement: PeerAnnouncement, }, TcpScrape { @@ -93,6 +95,32 @@ pub mod test { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::service_binding::Protocol; + use super::Event; + use crate::tests::sample_info_hash; + + #[must_use] + pub fn events_match(event: &Event, expected_event: &Event) -> bool { + match (event, expected_event) { + ( + Event::TcpAnnounce { + connection, + info_hash, + announcement, + }, + Event::TcpAnnounce { + connection: expected_connection, + info_hash: expected_info_hash, + announcement: expected_announcement, + }, + ) => { + *connection == *expected_connection + && *info_hash == *expected_info_hash + && announcement.peer_addr == expected_announcement.peer_addr + } + _ => false, + } + } + #[test] fn events_should_be_comparable() { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; @@ -102,6 +130,7 @@ pub mod test { use crate::event::{ConnectionContext, Event}; let remote_client_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); + let info_hash = sample_info_hash(); let event1 = Event::TcpAnnounce { connection: ConnectionContext::new( @@ -109,6 +138,7 @@ pub mod test { Some(8080), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), + info_hash, announcement: Peer::default(), }; @@ -118,6 +148,7 @@ pub mod test { Some(8080), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), + info_hash, announcement: Peer::default(), }; diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index c27d3dbee..8dedeade7 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -89,8 +89,14 @@ impl AnnounceService { .announce(&announce_request.info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; - self.send_event(remote_client_ip, opt_remote_client_port, server_service_binding.clone(), peer) - .await; + self.send_event( + announce_request.info_hash, + remote_client_ip, + opt_remote_client_port, + server_service_binding.clone(), + peer, + ) + .await; Ok(announce_data) } @@ -142,6 +148,7 @@ impl AnnounceService { async fn send_event( &self, + info_hash: InfoHash, remote_client_ip: IpAddr, opt_peer_ip_port: Option, server_service_binding: ServiceBinding, @@ -150,6 +157,7 @@ impl AnnounceService { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { let event = Event::TcpAnnounce { connection: event::ConnectionContext::new(remote_client_ip, opt_peer_ip_port, server_service_binding), + info_hash, announcement, }; @@ -327,13 +335,14 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::event; + use crate::event::test::events_match; use crate::event::{ConnectionContext, Event}; use crate::services::announce::tests::{ initialize_core_tracker_services, initialize_core_tracker_services_with_config, sample_announce_request_for_peer, MockHttpStatsEventSender, }; use crate::services::announce::AnnounceService; - use crate::tests::{sample_peer, sample_peer_using_ipv4, sample_peer_using_ipv6}; + use crate::tests::{sample_info_hash, sample_peer, sample_peer_using_ipv4, sample_peer_using_ipv6}; #[tokio::test] async fn it_should_return_the_announce_data() { @@ -394,22 +403,11 @@ mod tests { let expected_event = Event::TcpAnnounce { connection: ConnectionContext::new(remote_client_ip, Some(8080), server_service_binding.clone()), + info_hash: sample_info_hash(), announcement, }; - match (event, expected_event) { - ( - Event::TcpAnnounce { - connection: a_conn, - announcement: a2, - }, - Event::TcpAnnounce { - connection: b_conn, - announcement: b2, - }, - ) => *a_conn == b_conn && a2.peer_addr == b2.peer_addr, - _ => false, - } + events_match(event, &expected_event) })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -479,22 +477,11 @@ mod tests { let expected_event = Event::TcpAnnounce { connection: ConnectionContext::new(remote_client_ip, Some(8080), server_service_binding.clone()), + info_hash: sample_info_hash(), announcement: peer_announcement, }; - match (event, expected_event) { - ( - Event::TcpAnnounce { - connection: a_conn, - announcement: a2, - }, - Event::TcpAnnounce { - connection: b_conn, - announcement: b2, - }, - ) => *a_conn == b_conn && a2.peer_addr == b2.peer_addr, - _ => false, - } + events_match(event, &expected_event) })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -537,22 +524,10 @@ mod tests { .with(predicate::function(move |event| { let expected_event = Event::TcpAnnounce { connection: ConnectionContext::new(remote_client_ip, Some(8080), server_service_binding.clone()), + info_hash: sample_info_hash(), announcement: peer, }; - - match (event, expected_event) { - ( - Event::TcpAnnounce { - connection: a_conn, - announcement: a2, - }, - Event::TcpAnnounce { - connection: b_conn, - announcement: b2, - }, - ) => *a_conn == b_conn && a2.peer_addr == b2.peer_addr, - _ => false, - } + events_match(event, &expected_event) })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index df8f29175..6dce6c4f4 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -79,7 +79,7 @@ mod tests { use crate::event::{ConnectionContext, Event}; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; - use crate::tests::{sample_peer_using_ipv4, sample_peer_using_ipv6}; + use crate::tests::{sample_info_hash, sample_peer_using_ipv4, sample_peer_using_ipv6}; use crate::CurrentClock; #[tokio::test] @@ -95,6 +95,7 @@ mod tests { Some(8080), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), + info_hash: sample_info_hash(), announcement: peer, }, &stats_repository, @@ -142,6 +143,7 @@ mod tests { Some(8080), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), + info_hash: sample_info_hash(), announcement: peer, }, &stats_repository, From 7ed750020af1a2b5ba075714c765db2e51d410b4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 17:05:14 +0100 Subject: [PATCH 0971/1297] refactor: extract fn for duplicate code --- .../src/services/announce.rs | 27 +++-------------- .../http-tracker-core/src/services/mod.rs | 29 +++++++++++++++++++ .../http-tracker-core/src/services/scrape.rs | 24 +++------------ 3 files changed, 37 insertions(+), 43 deletions(-) diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 8dedeade7..8d52302de 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -12,7 +12,7 @@ use std::panic::Location; use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::announce::{peer_from_request, Announce}; -use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources, PeerIpResolutionError}; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ClientIpSources, PeerIpResolutionError}; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::authentication::service::AuthenticationService; @@ -24,6 +24,7 @@ use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; +use super::resolve_remote_client_ip; use crate::event; use crate::event::Event; @@ -78,7 +79,8 @@ impl AnnounceService { self.authorize(announce_request.info_hash).await?; - let (remote_client_ip, opt_remote_client_port) = self.resolve_remote_client_ip(client_ip_sources)?; + let (remote_client_ip, opt_remote_client_port) = + resolve_remote_client_ip(self.core_config.net.on_reverse_proxy, client_ip_sources)?; let mut peer = peer_from_request(announce_request, &remote_client_ip); @@ -117,27 +119,6 @@ impl AnnounceService { self.whitelist_authorization.authorize(&info_hash).await } - /// Resolves the client's real IP address considering proxy headers - fn resolve_remote_client_ip( - &self, - client_ip_sources: &ClientIpSources, - ) -> Result<(IpAddr, Option), PeerIpResolutionError> { - let ip = match peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources) { - Ok(peer_ip) => Ok(peer_ip), - Err(error) => Err(error), - }?; - - let port = if client_ip_sources.connection_info_socket_address.is_some() { - client_ip_sources - .connection_info_socket_address - .map(|socket_addr| socket_addr.port()) - } else { - None - }; - - Ok((ip, port)) - } - /// Determines how many peers the client wants in the response fn peers_wanted(announce_request: &Announce) -> PeersWanted { match announce_request.numwant { diff --git a/packages/http-tracker-core/src/services/mod.rs b/packages/http-tracker-core/src/services/mod.rs index ce99c6856..ad127324a 100644 --- a/packages/http-tracker-core/src/services/mod.rs +++ b/packages/http-tracker-core/src/services/mod.rs @@ -5,5 +5,34 @@ //! servers. //! //! Refer to [`torrust_tracker`](crate) documentation. + +use std::net::IpAddr; + +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources, PeerIpResolutionError}; pub mod announce; pub mod scrape; + +/// Resolves the client's real IP address considering proxy headers +/// +/// # Errors +/// +/// This function returns an error if the IP address cannot be resolved. +pub fn resolve_remote_client_ip( + on_reverse_proxy: bool, + client_ip_sources: &ClientIpSources, +) -> Result<(IpAddr, Option), PeerIpResolutionError> { + let ip = match peer_ip_resolver::invoke(on_reverse_proxy, client_ip_sources) { + Ok(peer_ip) => Ok(peer_ip), + Err(error) => Err(error), + }?; + + let port = if client_ip_sources.connection_info_socket_address.is_some() { + client_ip_sources + .connection_info_socket_address + .map(|socket_addr| socket_addr.port()) + } else { + None + }; + + Ok((ip, port)) +} diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 072c76bb7..b7fc5a813 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -11,7 +11,7 @@ use std::net::IpAddr; use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; -use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources, PeerIpResolutionError}; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ClientIpSources, PeerIpResolutionError}; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::{self, Key}; use bittorrent_tracker_core::error::{ScrapeError, TrackerCoreError, WhitelistError}; @@ -20,6 +20,7 @@ use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::service_binding::ServiceBinding; +use super::resolve_remote_client_ip; use crate::event; use crate::event::{ConnectionContext, Event}; @@ -81,7 +82,8 @@ impl ScrapeService { self.scrape_handler.scrape(&scrape_request.info_hashes).await? }; - let (remote_client_ip, opt_client_port) = self.resolve_remote_client_ip(client_ip_sources)?; + let (remote_client_ip, opt_client_port) = + resolve_remote_client_ip(self.core_config.net.on_reverse_proxy, client_ip_sources)?; self.send_event(remote_client_ip, opt_client_port, server_service_binding.clone()) .await; @@ -101,24 +103,6 @@ impl ScrapeService { false } - /// Resolves the client's real IP address considering proxy headers. - fn resolve_remote_client_ip( - &self, - client_ip_sources: &ClientIpSources, - ) -> Result<(IpAddr, Option), PeerIpResolutionError> { - let ip = peer_ip_resolver::invoke(self.core_config.net.on_reverse_proxy, client_ip_sources)?; - - let port = if client_ip_sources.connection_info_socket_address.is_some() { - client_ip_sources - .connection_info_socket_address - .map(|socket_addr| socket_addr.port()) - } else { - None - }; - - Ok((ip, port)) - } - async fn send_event( &self, original_peer_ip: IpAddr, From a422e4ee737aec0ea78aa361b2fc36bbe45733a1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 17:20:14 +0100 Subject: [PATCH 0972/1297] refactor: extract type RemoteClientAddr --- packages/http-tracker-core/src/event/mod.rs | 35 ++++++++++------- .../src/services/announce.rs | 34 ++++++++++------- .../http-tracker-core/src/services/mod.rs | 19 ++++++++-- .../http-tracker-core/src/services/scrape.rs | 38 +++++++++---------- .../src/statistics/event/handler.rs | 16 ++++---- 5 files changed, 82 insertions(+), 60 deletions(-) diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index 9f7635ffe..07d27127a 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -6,6 +6,8 @@ use torrust_tracker_metrics::label_name; use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; +use crate::services::RemoteClientAddr; + pub mod sender; /// A HTTP core event. @@ -29,12 +31,9 @@ pub struct ConnectionContext { impl ConnectionContext { #[must_use] - pub fn new(client_ip_addr: IpAddr, opt_client_port: Option, server_service_binding: ServiceBinding) -> Self { + pub fn new(remote_client_addr: RemoteClientAddr, server_service_binding: ServiceBinding) -> Self { Self { - client: ClientConnectionContext { - ip_addr: client_ip_addr, - port: opt_client_port, - }, + client: ClientConnectionContext { remote_client_addr }, server: ServerConnectionContext { service_binding: server_service_binding, }, @@ -43,12 +42,12 @@ impl ConnectionContext { #[must_use] pub fn client_ip_addr(&self) -> IpAddr { - self.client.ip_addr + self.client.ip_addr() } #[must_use] pub fn client_port(&self) -> Option { - self.client.port + self.client.port() } #[must_use] @@ -59,10 +58,19 @@ impl ConnectionContext { #[derive(Debug, PartialEq, Eq, Clone)] pub struct ClientConnectionContext { - ip_addr: IpAddr, + remote_client_addr: RemoteClientAddr, +} + +impl ClientConnectionContext { + #[must_use] + pub fn ip_addr(&self) -> IpAddr { + self.remote_client_addr.ip + } - /// It's provided if you use the `torrust-axum-http-tracker-server` crate. - port: Option, + #[must_use] + pub fn port(&self) -> Option { + self.remote_client_addr.port + } } #[derive(Debug, PartialEq, Eq, Clone)] @@ -96,6 +104,7 @@ pub mod test { use torrust_tracker_primitives::service_binding::Protocol; use super::Event; + use crate::services::RemoteClientAddr; use crate::tests::sample_info_hash; #[must_use] @@ -134,8 +143,7 @@ pub mod test { let event1 = Event::TcpAnnounce { connection: ConnectionContext::new( - remote_client_ip, - Some(8080), + RemoteClientAddr::new(remote_client_ip, Some(8080)), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), info_hash, @@ -144,8 +152,7 @@ pub mod test { let event2 = Event::TcpAnnounce { connection: ConnectionContext::new( - IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), - Some(8080), + RemoteClientAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), Some(8080)), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), info_hash, diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 8d52302de..a0c31585e 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -7,7 +7,6 @@ //! //! It also sends an [`http_tracker_core::event::Event`] //! because events are specific for the HTTP tracker. -use std::net::IpAddr; use std::panic::Location; use std::sync::Arc; @@ -24,7 +23,7 @@ use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; -use super::resolve_remote_client_ip; +use super::{resolve_remote_client_addr, RemoteClientAddr}; use crate::event; use crate::event::Event; @@ -79,22 +78,20 @@ impl AnnounceService { self.authorize(announce_request.info_hash).await?; - let (remote_client_ip, opt_remote_client_port) = - resolve_remote_client_ip(self.core_config.net.on_reverse_proxy, client_ip_sources)?; + let remote_client_addr = resolve_remote_client_addr(self.core_config.net.on_reverse_proxy, client_ip_sources)?; - let mut peer = peer_from_request(announce_request, &remote_client_ip); + let mut peer = peer_from_request(announce_request, &remote_client_addr.ip); let peers_wanted = Self::peers_wanted(announce_request); let announce_data = self .announce_handler - .announce(&announce_request.info_hash, &mut peer, &remote_client_ip, &peers_wanted) + .announce(&announce_request.info_hash, &mut peer, &remote_client_addr.ip, &peers_wanted) .await?; self.send_event( announce_request.info_hash, - remote_client_ip, - opt_remote_client_port, + remote_client_addr, server_service_binding.clone(), peer, ) @@ -130,14 +127,13 @@ impl AnnounceService { async fn send_event( &self, info_hash: InfoHash, - remote_client_ip: IpAddr, - opt_peer_ip_port: Option, + remote_client_addr: RemoteClientAddr, server_service_binding: ServiceBinding, announcement: PeerAnnouncement, ) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { let event = Event::TcpAnnounce { - connection: event::ConnectionContext::new(remote_client_ip, opt_peer_ip_port, server_service_binding), + connection: event::ConnectionContext::new(remote_client_addr, server_service_binding), info_hash, announcement, }; @@ -323,6 +319,7 @@ mod tests { MockHttpStatsEventSender, }; use crate::services::announce::AnnounceService; + use crate::services::RemoteClientAddr; use crate::tests::{sample_info_hash, sample_peer, sample_peer_using_ipv4, sample_peer_using_ipv6}; #[tokio::test] @@ -383,7 +380,10 @@ mod tests { announcement.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let expected_event = Event::TcpAnnounce { - connection: ConnectionContext::new(remote_client_ip, Some(8080), server_service_binding.clone()), + connection: ConnectionContext::new( + RemoteClientAddr::new(remote_client_ip, Some(8080)), + server_service_binding.clone(), + ), info_hash: sample_info_hash(), announcement, }; @@ -457,7 +457,10 @@ mod tests { ); let expected_event = Event::TcpAnnounce { - connection: ConnectionContext::new(remote_client_ip, Some(8080), server_service_binding.clone()), + connection: ConnectionContext::new( + RemoteClientAddr::new(remote_client_ip, Some(8080)), + server_service_binding.clone(), + ), info_hash: sample_info_hash(), announcement: peer_announcement, }; @@ -504,7 +507,10 @@ mod tests { .expect_send_event() .with(predicate::function(move |event| { let expected_event = Event::TcpAnnounce { - connection: ConnectionContext::new(remote_client_ip, Some(8080), server_service_binding.clone()), + connection: ConnectionContext::new( + RemoteClientAddr::new(remote_client_ip, Some(8080)), + server_service_binding.clone(), + ), info_hash: sample_info_hash(), announcement: peer, }; diff --git a/packages/http-tracker-core/src/services/mod.rs b/packages/http-tracker-core/src/services/mod.rs index ad127324a..5ec6dd22d 100644 --- a/packages/http-tracker-core/src/services/mod.rs +++ b/packages/http-tracker-core/src/services/mod.rs @@ -12,15 +12,28 @@ use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, Cli pub mod announce; pub mod scrape; +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct RemoteClientAddr { + pub ip: IpAddr, + pub port: Option, +} + +impl RemoteClientAddr { + #[must_use] + pub fn new(ip: IpAddr, port: Option) -> Self { + Self { ip, port } + } +} + /// Resolves the client's real IP address considering proxy headers /// /// # Errors /// /// This function returns an error if the IP address cannot be resolved. -pub fn resolve_remote_client_ip( +pub fn resolve_remote_client_addr( on_reverse_proxy: bool, client_ip_sources: &ClientIpSources, -) -> Result<(IpAddr, Option), PeerIpResolutionError> { +) -> Result { let ip = match peer_ip_resolver::invoke(on_reverse_proxy, client_ip_sources) { Ok(peer_ip) => Ok(peer_ip), Err(error) => Err(error), @@ -34,5 +47,5 @@ pub fn resolve_remote_client_ip( None }; - Ok((ip, port)) + Ok(RemoteClientAddr { ip, port }) } diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index b7fc5a813..e206b909c 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -7,7 +7,6 @@ //! //! It also sends an [`http_tracker_core::statistics::event::Event`] //! because events are specific for the HTTP tracker. -use std::net::IpAddr; use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; @@ -20,7 +19,7 @@ use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::service_binding::ServiceBinding; -use super::resolve_remote_client_ip; +use super::{resolve_remote_client_addr, RemoteClientAddr}; use crate::event; use crate::event::{ConnectionContext, Event}; @@ -82,11 +81,9 @@ impl ScrapeService { self.scrape_handler.scrape(&scrape_request.info_hashes).await? }; - let (remote_client_ip, opt_client_port) = - resolve_remote_client_ip(self.core_config.net.on_reverse_proxy, client_ip_sources)?; + let remote_client_addr = resolve_remote_client_addr(self.core_config.net.on_reverse_proxy, client_ip_sources)?; - self.send_event(remote_client_ip, opt_client_port, server_service_binding.clone()) - .await; + self.send_event(remote_client_addr, server_service_binding.clone()).await; Ok(scrape_data) } @@ -103,15 +100,10 @@ impl ScrapeService { false } - async fn send_event( - &self, - original_peer_ip: IpAddr, - opt_original_peer_port: Option, - server_service_binding: ServiceBinding, - ) { + async fn send_event(&self, remote_client_addr: RemoteClientAddr, server_service_binding: ServiceBinding) { if let Some(http_stats_event_sender) = self.opt_http_stats_event_sender.as_deref() { let event = Event::TcpScrape { - connection: ConnectionContext::new(original_peer_ip, opt_original_peer_port, server_service_binding), + connection: ConnectionContext::new(remote_client_addr, server_service_binding), }; tracing::debug!("Sending TcpScrape event: {:?}", event); @@ -271,6 +263,7 @@ mod tests { initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::services::scrape::ScrapeService; + use crate::services::RemoteClientAddr; use crate::tests::sample_info_hash; use crate::{event, statistics}; @@ -342,8 +335,7 @@ mod tests { .expect_send_event() .with(eq(Event::TcpScrape { connection: ConnectionContext::new( - IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), - Some(8080), + RemoteClientAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), Some(8080)), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)) .unwrap(), ), @@ -394,8 +386,10 @@ mod tests { .expect_send_event() .with(eq(Event::TcpScrape { connection: ConnectionContext::new( - IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - Some(8080), + RemoteClientAddr::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + Some(8080), + ), server_service_binding, ), })) @@ -453,6 +447,7 @@ mod tests { initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::services::scrape::ScrapeService; + use crate::services::RemoteClientAddr; use crate::tests::sample_info_hash; use crate::{event, statistics}; @@ -518,8 +513,7 @@ mod tests { .expect_send_event() .with(eq(Event::TcpScrape { connection: ConnectionContext::new( - IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), - Some(8080), + RemoteClientAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), Some(8080)), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)) .unwrap(), ), @@ -570,8 +564,10 @@ mod tests { .expect_send_event() .with(eq(Event::TcpScrape { connection: ConnectionContext::new( - IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - Some(8080), + RemoteClientAddr::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + Some(8080), + ), server_service_binding, ), })) diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index 6dce6c4f4..d59c640c1 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -77,6 +77,7 @@ mod tests { use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{ConnectionContext, Event}; + use crate::services::RemoteClientAddr; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; use crate::tests::{sample_info_hash, sample_peer_using_ipv4, sample_peer_using_ipv6}; @@ -91,8 +92,7 @@ mod tests { handle_event( Event::TcpAnnounce { connection: ConnectionContext::new( - remote_client_ip, - Some(8080), + RemoteClientAddr::new(remote_client_ip, Some(8080)), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), info_hash: sample_info_hash(), @@ -115,8 +115,7 @@ mod tests { handle_event( Event::TcpScrape { connection: ConnectionContext::new( - IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), - Some(8080), + RemoteClientAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), Some(8080)), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), }, @@ -139,8 +138,7 @@ mod tests { handle_event( Event::TcpAnnounce { connection: ConnectionContext::new( - remote_client_ip, - Some(8080), + RemoteClientAddr::new(remote_client_ip, Some(8080)), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), info_hash: sample_info_hash(), @@ -163,8 +161,10 @@ mod tests { handle_event( Event::TcpScrape { connection: ConnectionContext::new( - IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), - Some(8080), + RemoteClientAddr::new( + IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + Some(8080), + ), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), }, From 2670a0a8d3fa57224c0b2343c1ab4eca685e62ac Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 18:11:38 +0100 Subject: [PATCH 0973/1297] refactor: [#1384] rename fields --- packages/udp-tracker-core/src/event/mod.rs | 6 +++--- .../udp-tracker-core/src/services/announce.rs | 2 +- .../udp-tracker-core/src/services/connect.rs | 6 +++--- .../udp-tracker-core/src/services/scrape.rs | 2 +- .../src/statistics/event/handler.rs | 18 +++++++++--------- .../src/handlers/announce.rs | 2 +- .../udp-tracker-server/src/handlers/connect.rs | 4 ++-- 7 files changed, 20 insertions(+), 20 deletions(-) diff --git a/packages/udp-tracker-core/src/event/mod.rs b/packages/udp-tracker-core/src/event/mod.rs index ddcba7792..6785fd34d 100644 --- a/packages/udp-tracker-core/src/event/mod.rs +++ b/packages/udp-tracker-core/src/event/mod.rs @@ -9,9 +9,9 @@ pub mod sender; /// A UDP core event. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { - UdpConnect { context: ConnectionContext }, - UdpAnnounce { context: ConnectionContext }, - UdpScrape { context: ConnectionContext }, + UdpConnect { connection: ConnectionContext }, + UdpAnnounce { connection: ConnectionContext }, + UdpScrape { connection: ConnectionContext }, } #[derive(Debug, PartialEq, Eq, Clone)] diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index 0a9bf6b82..2f2c3e093 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -105,7 +105,7 @@ impl AnnounceService { if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { udp_stats_event_sender .send_event(Event::UdpAnnounce { - context: ConnectionContext::new(client_socket_addr, server_service_binding), + connection: ConnectionContext::new(client_socket_addr, server_service_binding), }) .await; } diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index 92bcd299f..df3db6c4b 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -43,7 +43,7 @@ impl ConnectService { if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { udp_stats_event_sender .send_event(Event::UdpConnect { - context: ConnectionContext::new(client_socket_addr, server_service_binding), + connection: ConnectionContext::new(client_socket_addr, server_service_binding), }) .await; } @@ -144,7 +144,7 @@ mod tests { udp_stats_event_sender_mock .expect_send_event() .with(eq(Event::UdpConnect { - context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + connection: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -168,7 +168,7 @@ mod tests { udp_stats_event_sender_mock .expect_send_event() .with(eq(Event::UdpConnect { - context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + connection: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index 6ee64111c..c20e9b16c 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -87,7 +87,7 @@ impl ScrapeService { if let Some(udp_stats_event_sender) = self.opt_udp_stats_event_sender.as_deref() { udp_stats_event_sender .send_event(Event::UdpScrape { - context: ConnectionContext::new(client_socket_addr, server_service_binding), + connection: ConnectionContext::new(client_socket_addr, server_service_binding), }) .await; } diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index 2680c442f..18a331581 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -11,7 +11,7 @@ use crate::statistics::UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; /// This function panics if the IP version does not match the event type. pub async fn handle_event(event: Event, stats_repository: &Repository, now: DurationSinceUnixEpoch) { match event { - Event::UdpConnect { context } => { + Event::UdpConnect { connection: context } => { // Global fixed metrics match context.client_socket_addr.ip() { @@ -36,7 +36,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura Err(err) => tracing::error!("Failed to increase the counter: {}", err), }; } - Event::UdpAnnounce { context } => { + Event::UdpAnnounce { connection: context } => { // Global fixed metrics match context.client_socket_addr.ip() { @@ -61,7 +61,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura Err(err) => tracing::error!("Failed to increase the counter: {}", err), }; } - Event::UdpScrape { context } => { + Event::UdpScrape { connection: context } => { // Global fixed metrics match context.client_socket_addr.ip() { @@ -109,7 +109,7 @@ mod tests { handle_event( Event::UdpConnect { - context: ConnectionContext::new( + connection: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), ServiceBinding::new( Protocol::UDP, @@ -134,7 +134,7 @@ mod tests { handle_event( Event::UdpAnnounce { - context: ConnectionContext::new( + connection: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), ServiceBinding::new( Protocol::UDP, @@ -159,7 +159,7 @@ mod tests { handle_event( Event::UdpScrape { - context: ConnectionContext::new( + connection: ConnectionContext::new( SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), ServiceBinding::new( Protocol::UDP, @@ -184,7 +184,7 @@ mod tests { handle_event( Event::UdpConnect { - context: ConnectionContext::new( + connection: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), ServiceBinding::new( Protocol::UDP, @@ -209,7 +209,7 @@ mod tests { handle_event( Event::UdpAnnounce { - context: ConnectionContext::new( + connection: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), ServiceBinding::new( Protocol::UDP, @@ -234,7 +234,7 @@ mod tests { handle_event( Event::UdpScrape { - context: ConnectionContext::new( + connection: ConnectionContext::new( SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), ServiceBinding::new( Protocol::UDP, diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 1cf0f0b7d..0020a5f3a 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -868,7 +868,7 @@ mod tests { udp_core_stats_event_sender_mock .expect_send_event() .with(eq(core_event::Event::UdpAnnounce { - context: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + connection: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 88f0b7f3a..aef8833b9 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -197,7 +197,7 @@ mod tests { udp_core_stats_event_sender_mock .expect_send_event() .with(eq(core_event::Event::UdpConnect { - context: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + connection: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -239,7 +239,7 @@ mod tests { udp_core_stats_event_sender_mock .expect_send_event() .with(eq(core_event::Event::UdpConnect { - context: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + connection: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); From 1477975a10ec233b888d1bd4997738bea95f00ec Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 19:30:07 +0100 Subject: [PATCH 0974/1297] feat: [#1384] enrich bittorrent_udp_tracker_core::event::Event::UdpAnnounce Added: - info-hash - peer announcement info Following the same chage as in the HTTP tracker core. --- packages/udp-tracker-core/src/event/mod.rs | 16 +++++-- packages/udp-tracker-core/src/lib.rs | 15 +++++++ .../udp-tracker-core/src/services/announce.rs | 28 +++++++++--- .../udp-tracker-core/src/services/scrape.rs | 12 ++--- .../src/statistics/event/handler.rs | 8 +++- .../src/handlers/announce.rs | 28 +++++++++--- packages/udp-tracker-server/src/lib.rs | 44 +++++++++++++++++++ 7 files changed, 130 insertions(+), 21 deletions(-) diff --git a/packages/udp-tracker-core/src/event/mod.rs b/packages/udp-tracker-core/src/event/mod.rs index 6785fd34d..1ec502572 100644 --- a/packages/udp-tracker-core/src/event/mod.rs +++ b/packages/udp-tracker-core/src/event/mod.rs @@ -1,7 +1,9 @@ use std::net::SocketAddr; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_metrics::label::{LabelSet, LabelValue}; use torrust_tracker_metrics::label_name; +use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; pub mod sender; @@ -9,9 +11,17 @@ pub mod sender; /// A UDP core event. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { - UdpConnect { connection: ConnectionContext }, - UdpAnnounce { connection: ConnectionContext }, - UdpScrape { connection: ConnectionContext }, + UdpConnect { + connection: ConnectionContext, + }, + UdpAnnounce { + connection: ConnectionContext, + info_hash: InfoHash, + announcement: PeerAnnouncement, + }, + UdpScrape { + connection: ConnectionContext, + }, } #[derive(Debug, PartialEq, Eq, Clone)] diff --git a/packages/udp-tracker-core/src/lib.rs b/packages/udp-tracker-core/src/lib.rs index 8e937e79c..2c1943853 100644 --- a/packages/udp-tracker-core/src/lib.rs +++ b/packages/udp-tracker-core/src/lib.rs @@ -42,3 +42,18 @@ pub fn initialize_static() { // Initialize the Zeroed Cipher lazy_static::initialize(&ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH); } + +#[cfg(test)] +pub(crate) mod tests { + use bittorrent_primitives::info_hash::InfoHash; + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } +} diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index 2f2c3e093..def24ffd7 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -18,6 +18,7 @@ use bittorrent_tracker_core::error::{AnnounceError, WhitelistError}; use bittorrent_tracker_core::whitelist; use bittorrent_udp_tracker_protocol::peer_builder; use torrust_tracker_primitives::core::AnnounceData; +use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; @@ -80,7 +81,8 @@ impl AnnounceService { .announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; - self.send_event(client_socket_addr, server_service_binding).await; + self.send_event(info_hash, peer, client_socket_addr, server_service_binding) + .await; Ok(announce_data) } @@ -101,13 +103,25 @@ impl AnnounceService { self.whitelist_authorization.authorize(info_hash).await } - async fn send_event(&self, client_socket_addr: SocketAddr, server_service_binding: ServiceBinding) { + async fn send_event( + &self, + info_hash: InfoHash, + announcement: PeerAnnouncement, + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, + ) { if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { - udp_stats_event_sender - .send_event(Event::UdpAnnounce { - connection: ConnectionContext::new(client_socket_addr, server_service_binding), - }) - .await; + let event = Event::UdpAnnounce { + connection: ConnectionContext::new(client_socket_addr, server_service_binding), + info_hash, + announcement, + }; + + tracing::debug!(target = crate::UDP_TRACKER_LOG_TARGET, "Sending UdpAnnounce event: {event:?}"); + + println!("Sending UdpAnnounce event: {event:?}"); + + udp_stats_event_sender.send_event(event).await; } } } diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index c20e9b16c..5b2cf7d46 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -85,11 +85,13 @@ impl ScrapeService { async fn send_event(&self, client_socket_addr: SocketAddr, server_service_binding: ServiceBinding) { if let Some(udp_stats_event_sender) = self.opt_udp_stats_event_sender.as_deref() { - udp_stats_event_sender - .send_event(Event::UdpScrape { - connection: ConnectionContext::new(client_socket_addr, server_service_binding), - }) - .await; + let event = Event::UdpScrape { + connection: ConnectionContext::new(client_socket_addr, server_service_binding), + }; + + tracing::debug!(target = crate::UDP_TRACKER_LOG_TARGET, "Sending UdpScrape event: {event:?}"); + + udp_stats_event_sender.send_event(event).await; } } } diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index 18a331581..039b6b0d5 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -36,7 +36,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura Err(err) => tracing::error!("Failed to increase the counter: {}", err), }; } - Event::UdpAnnounce { connection: context } => { + Event::UdpAnnounce { connection: context, .. } => { // Global fixed metrics match context.client_socket_addr.ip() { @@ -96,11 +96,13 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{ConnectionContext, Event}; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; + use crate::tests::sample_info_hash; use crate::CurrentClock; #[tokio::test] @@ -142,6 +144,8 @@ mod tests { ) .unwrap(), ), + info_hash: sample_info_hash(), + announcement: PeerAnnouncement::default(), }, &stats_repository, CurrentClock::now(), @@ -217,6 +221,8 @@ mod tests { ) .unwrap(), ), + info_hash: sample_info_hash(), + announcement: PeerAnnouncement::default(), }, &stats_repository, CurrentClock::now(), diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 0020a5f3a..7e6d42834 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -824,7 +824,7 @@ mod tests { use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use bittorrent_udp_tracker_core::services::announce::AnnounceService; use bittorrent_udp_tracker_core::{self, event as core_event}; - use mockall::predicate::eq; + use mockall::predicate::{self, eq}; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; @@ -834,6 +834,7 @@ mod tests { sample_cookie_valid_range, sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, TrackerConfigurationBuilder, }; + use crate::tests::{announce_events_match, sample_peer}; #[tokio::test] async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { @@ -848,6 +849,11 @@ mod tests { let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); + let mut announcement = sample_peer(); + announcement.peer_id = peer_id; + announcement.peer_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x7e00, 1)), client_port); + + println!("announcement.peer_addr: {}", announcement.peer_addr); let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let mut server_socket_addr = config.udp_trackers.clone().unwrap()[0].bind_address; @@ -856,6 +862,7 @@ mod tests { server_socket_addr.set_port(6969); } let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + let server_service_binding_clone = server_service_binding.clone(); let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -867,8 +874,17 @@ mod tests { let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send_event() - .with(eq(core_event::Event::UdpAnnounce { - connection: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + .with(predicate::function(move |event| { + let expected_event = core_event::Event::UdpAnnounce { + connection: core_event::ConnectionContext::new( + client_socket_addr, + server_service_binding.clone(), + ), + info_hash: info_hash.into(), + announcement, + }; + + announce_events_match(event, &expected_event) })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -879,7 +895,7 @@ mod tests { udp_server_stats_event_sender_mock .expect_send_event() .with(eq(Event::UdpRequestAccepted { - context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), + context: ConnectionContext::new(client_socket_addr, server_service_binding_clone.clone()), kind: UdpRequestKind::Announce, })) .times(1) @@ -913,7 +929,7 @@ mod tests { handle_announce( &announce_service, client_socket_addr, - server_service_binding, + server_service_binding_clone, &request, &core_config, &udp_server_stats_event_sender, @@ -928,6 +944,8 @@ mod tests { assert!(external_ip_in_tracker_configuration.is_ipv6()); + println!("Peer addr: {}", peers[0].peer_addr.ip()); + // There's a special type of IPv6 addresses that provide compatibility with IPv4. // The last 32 bits of these addresses represent an IPv4, and are represented like this: // 1111:2222:3333:4444:5555:6666:1.2.3.4 diff --git a/packages/udp-tracker-server/src/lib.rs b/packages/udp-tracker-server/src/lib.rs index ff53adcfb..741c81b07 100644 --- a/packages/udp-tracker-server/src/lib.rs +++ b/packages/udp-tracker-server/src/lib.rs @@ -673,3 +673,47 @@ pub struct RawRequest { payload: Vec, from: SocketAddr, } + +#[cfg(test)] +pub(crate) mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_udp_tracker_core::event::Event; + use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + + pub fn sample_peer() -> peer::Peer { + peer::Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), + event: AnnounceEvent::Started, + } + } + + #[must_use] + pub fn announce_events_match(event: &Event, expected_event: &Event) -> bool { + match (event, expected_event) { + ( + Event::UdpAnnounce { + connection, + info_hash, + announcement, + }, + Event::UdpAnnounce { + connection: expected_connection, + info_hash: expected_info_hash, + announcement: expected_announcement, + }, + ) => { + *connection == *expected_connection + && *info_hash == *expected_info_hash + && announcement.peer_addr == expected_announcement.peer_addr + } + _ => false, + } + } +} From f5bdec51ed46b8c14a6a0e140555d7034e73199f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 19:33:24 +0100 Subject: [PATCH 0975/1297] refactor: [#1376] rename function --- packages/http-tracker-core/src/event/mod.rs | 2 +- packages/http-tracker-core/src/services/announce.rs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index 07d27127a..2e856c694 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -108,7 +108,7 @@ pub mod test { use crate::tests::sample_info_hash; #[must_use] - pub fn events_match(event: &Event, expected_event: &Event) -> bool { + pub fn announce_events_match(event: &Event, expected_event: &Event) -> bool { match (event, expected_event) { ( Event::TcpAnnounce { diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index a0c31585e..eafe63ea1 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -312,7 +312,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::event; - use crate::event::test::events_match; + use crate::event::test::announce_events_match; use crate::event::{ConnectionContext, Event}; use crate::services::announce::tests::{ initialize_core_tracker_services, initialize_core_tracker_services_with_config, sample_announce_request_for_peer, @@ -388,7 +388,7 @@ mod tests { announcement, }; - events_match(event, &expected_event) + announce_events_match(event, &expected_event) })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -465,7 +465,7 @@ mod tests { announcement: peer_announcement, }; - events_match(event, &expected_event) + announce_events_match(event, &expected_event) })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -514,7 +514,7 @@ mod tests { info_hash: sample_info_hash(), announcement: peer, }; - events_match(event, &expected_event) + announce_events_match(event, &expected_event) })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); From 925fc938f58e5e74a08b03ead9ff776b5dfefe28 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 19:47:41 +0100 Subject: [PATCH 0976/1297] test: [#1384,#1376] add comment to mock time In order to be able to compare full events. --- packages/http-tracker-core/src/event/mod.rs | 10 ++++++++++ packages/udp-tracker-server/src/lib.rs | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index 2e856c694..921c4e32c 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -124,7 +124,17 @@ pub mod test { ) => { *connection == *expected_connection && *info_hash == *expected_info_hash + && announcement.peer_id == expected_announcement.peer_id && announcement.peer_addr == expected_announcement.peer_addr + // Events can't be compared due to the `updated` field. + // The `announcement.uploaded` contains the current time + // when the test is executed. + // todo: mock time + //&& announcement.updated == expected_announcement.updated + && announcement.uploaded == expected_announcement.uploaded + && announcement.downloaded == expected_announcement.downloaded + && announcement.left == expected_announcement.left + && announcement.event == expected_announcement.event } _ => false, } diff --git a/packages/udp-tracker-server/src/lib.rs b/packages/udp-tracker-server/src/lib.rs index 741c81b07..996c41917 100644 --- a/packages/udp-tracker-server/src/lib.rs +++ b/packages/udp-tracker-server/src/lib.rs @@ -711,7 +711,17 @@ pub(crate) mod tests { ) => { *connection == *expected_connection && *info_hash == *expected_info_hash + && announcement.peer_id == expected_announcement.peer_id && announcement.peer_addr == expected_announcement.peer_addr + // Events can't be compared due to the `updated` field. + // The `announcement.uploaded` contains the current time + // when the test is executed. + // todo: mock time + //&& announcement.updated == expected_announcement.updated + && announcement.uploaded == expected_announcement.uploaded + && announcement.downloaded == expected_announcement.downloaded + && announcement.left == expected_announcement.left + && announcement.event == expected_announcement.event } _ => false, } From e9ec15a45d19daeb1fca4d84b982f24f0de51417 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 22 Apr 2025 19:48:42 +0100 Subject: [PATCH 0977/1297] chore: remove print statment from tests --- packages/udp-tracker-server/src/handlers/announce.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 7e6d42834..0167553f2 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -853,8 +853,6 @@ mod tests { announcement.peer_id = peer_id; announcement.peer_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x7e00, 1)), client_port); - println!("announcement.peer_addr: {}", announcement.peer_addr); - let client_socket_addr = SocketAddr::new(IpAddr::V6(client_ip_v6), client_port); let mut server_socket_addr = config.udp_trackers.clone().unwrap()[0].bind_address; if server_socket_addr.port() == 0 { @@ -944,8 +942,6 @@ mod tests { assert!(external_ip_in_tracker_configuration.is_ipv6()); - println!("Peer addr: {}", peers[0].peer_addr.ip()); - // There's a special type of IPv6 addresses that provide compatibility with IPv4. // The last 32 bits of these addresses represent an IPv4, and are represented like this: // 1111:2222:3333:4444:5555:6666:1.2.3.4 From e0162d1bcd0cfaae93d14394b3cfba3f9bed89f6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 23 Apr 2025 13:16:13 +0100 Subject: [PATCH 0978/1297] refactor: the remote client IP resolution code - [x] Extract `ReverseProxyMode` flag. - [x] Extract `RemoteClientAddr` type. - [x] Add IP wrapper `ResolvedIp` to track IP source. - [x] Move all code to the `http-protocol` package. - [x] Other improvements. --- .../src/v1/services/peer_ip_resolver.rs | 240 ++++++++++-------- packages/http-tracker-core/src/event/mod.rs | 16 +- .../src/services/announce.rs | 24 +- .../http-tracker-core/src/services/mod.rs | 42 --- .../http-tracker-core/src/services/scrape.rs | 31 ++- .../src/statistics/event/handler.rs | 15 +- 6 files changed, 195 insertions(+), 173 deletions(-) diff --git a/packages/http-protocol/src/v1/services/peer_ip_resolver.rs b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs index b375694b9..ceaa7e11c 100644 --- a/packages/http-protocol/src/v1/services/peer_ip_resolver.rs +++ b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs @@ -1,4 +1,4 @@ -//! This service resolves the peer IP from the request. +//! This service resolves the remote client address. //! //! The peer IP is used to identify the peer in the tracker. It's the peer IP //! that is used in the `announce` responses (peer list). And it's also used to @@ -12,20 +12,65 @@ //! X-Forwarded-For: 126.0.0.1 X-Forwarded-For: 126.0.0.1,126.0.0.2 //! ``` //! -//! This service returns two options for the peer IP: +//! This `ClientIpSources` contains two options for the peer IP: //! //! ```text //! right_most_x_forwarded_for = 126.0.0.2 //! connection_info_ip = 126.0.0.3 //! ``` //! -//! Depending on the tracker configuration. +//! Which one to use depends on the `ReverseProxyMode`. use std::net::{IpAddr, SocketAddr}; use std::panic::Location; use serde::{Deserialize, Serialize}; use thiserror::Error; +/// Resolves the client's real address considering proxy headers. Port is also +/// included when available. +/// +/// # Errors +/// +/// This function returns an error if the IP address cannot be resolved. +pub fn resolve_remote_client_addr( + reverse_proxy_mode: &ReverseProxyMode, + client_ip_sources: &ClientIpSources, +) -> Result { + let ip = match reverse_proxy_mode { + ReverseProxyMode::Enabled => ResolvedIp::FromXForwardedFor(client_ip_sources.try_client_ip_from_proxy_header()?), + ReverseProxyMode::Disabled => ResolvedIp::FromSocketAddr(client_ip_sources.try_client_ip_from_connection_info()?), + }; + + let port = client_ip_sources.client_port_from_connection_info(); + + Ok(RemoteClientAddr::new(ip, port)) +} + +/// This struct indicates whether the tracker is running on reverse proxy mode. +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Copy)] +pub enum ReverseProxyMode { + Enabled, + Disabled, +} + +impl From for bool { + fn from(reverse_proxy_mode: ReverseProxyMode) -> Self { + match reverse_proxy_mode { + ReverseProxyMode::Enabled => true, + ReverseProxyMode::Disabled => false, + } + } +} + +impl From for ReverseProxyMode { + fn from(reverse_proxy_mode: bool) -> Self { + if reverse_proxy_mode { + ReverseProxyMode::Enabled + } else { + ReverseProxyMode::Disabled + } + } +} /// This struct contains the sources from which the peer IP can be obtained. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] pub struct ClientIpSources { @@ -36,6 +81,36 @@ pub struct ClientIpSources { pub connection_info_socket_address: Option, } +impl ClientIpSources { + fn try_client_ip_from_connection_info(&self) -> Result { + if let Some(socket_addr) = self.connection_info_socket_address { + Ok(socket_addr.ip()) + } else { + Err(PeerIpResolutionError::MissingClientIp { + location: Location::caller(), + }) + } + } + + fn try_client_ip_from_proxy_header(&self) -> Result { + if let Some(ip) = self.right_most_x_forwarded_for { + Ok(ip) + } else { + Err(PeerIpResolutionError::MissingRightMostXForwardedForIp { + location: Location::caller(), + }) + } + } + + fn client_port_from_connection_info(&self) -> Option { + if self.connection_info_socket_address.is_some() { + self.connection_info_socket_address.map(|socket_addr| socket_addr.port()) + } else { + None + } + } +} + /// The error that can occur when resolving the peer IP. #[derive(Error, Debug, Clone)] pub enum PeerIpResolutionError { @@ -54,104 +129,57 @@ pub enum PeerIpResolutionError { MissingClientIp { location: &'static Location<'static> }, } -/// Resolves the peer IP from the request. -/// -/// Given the sources from which the peer IP can be obtained, this function -/// resolves the peer IP according to the tracker configuration. -/// -/// With the tracker running on reverse proxy mode: -/// -/// ```rust -/// use std::net::IpAddr; -/// use std::str::FromStr; -/// -/// use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; -/// -/// let on_reverse_proxy = true; -/// -/// let ip = invoke( -/// on_reverse_proxy, -/// &ClientIpSources { -/// right_most_x_forwarded_for: Some(IpAddr::from_str("203.0.113.195").unwrap()), -/// connection_info_socket_address: None, -/// }, -/// ) -/// .unwrap(); -/// -/// assert_eq!(ip, IpAddr::from_str("203.0.113.195").unwrap()); -/// ``` -/// -/// With the tracker non running on reverse proxy mode: -/// -/// ```rust -/// use std::net::{IpAddr,Ipv4Addr,SocketAddr}; -/// use std::str::FromStr; -/// -/// use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; -/// -/// let on_reverse_proxy = false; -/// -/// let ip = invoke( -/// on_reverse_proxy, -/// &ClientIpSources { -/// right_most_x_forwarded_for: None, -/// connection_info_socket_address: Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080)) -/// }, -/// ) -/// .unwrap(); -/// -/// assert_eq!(ip, IpAddr::from_str("203.0.113.195").unwrap()); -/// ``` -/// -/// # Errors -/// -/// Will return an error if the peer IP cannot be obtained according to the configuration. -/// For example, if the IP is extracted from an HTTP header which is missing in the request. -pub fn invoke(on_reverse_proxy: bool, client_ip_sources: &ClientIpSources) -> Result { - if on_reverse_proxy { - resolve_peer_ip_on_reverse_proxy(client_ip_sources) - } else { - resolve_peer_ip_without_reverse_proxy(client_ip_sources) - } +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Copy)] +pub struct RemoteClientAddr { + ip: ResolvedIp, + port: Option, } -fn resolve_peer_ip_without_reverse_proxy(remote_client_ip: &ClientIpSources) -> Result { - if let Some(socket_addr) = remote_client_ip.connection_info_socket_address { - Ok(socket_addr.ip()) - } else { - Err(PeerIpResolutionError::MissingClientIp { - location: Location::caller(), - }) +impl RemoteClientAddr { + #[must_use] + pub fn new(ip: ResolvedIp, port: Option) -> Self { + Self { ip, port } + } + + #[must_use] + pub fn ip(&self) -> IpAddr { + match self.ip { + ResolvedIp::FromSocketAddr(ip) | ResolvedIp::FromXForwardedFor(ip) => ip, + } } -} -fn resolve_peer_ip_on_reverse_proxy(remote_client_ip: &ClientIpSources) -> Result { - if let Some(ip) = remote_client_ip.right_most_x_forwarded_for { - Ok(ip) - } else { - Err(PeerIpResolutionError::MissingRightMostXForwardedForIp { - location: Location::caller(), - }) + #[must_use] + pub fn port(&self) -> Option { + self.port } } +/// This enum indicates the source of the resolved IP address. +#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Copy)] +pub enum ResolvedIp { + FromXForwardedFor(IpAddr), + FromSocketAddr(IpAddr), +} + #[cfg(test)] mod tests { - use super::invoke; + use super::resolve_remote_client_addr; mod working_without_reverse_proxy { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; - use super::invoke; - use crate::v1::services::peer_ip_resolver::{ClientIpSources, PeerIpResolutionError}; + use super::resolve_remote_client_addr; + use crate::v1::services::peer_ip_resolver::{ + ClientIpSources, PeerIpResolutionError, RemoteClientAddr, ResolvedIp, ReverseProxyMode, + }; #[test] - fn it_should_get_the_peer_ip_from_the_connection_info() { - let on_reverse_proxy = false; + fn it_should_get_the_remote_client_address_from_the_connection_info() { + let reverse_proxy_mode = ReverseProxyMode::Disabled; - let ip = invoke( - on_reverse_proxy, + let ip = resolve_remote_client_addr( + &reverse_proxy_mode, &ClientIpSources { right_most_x_forwarded_for: None, connection_info_socket_address: Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080)), @@ -159,15 +187,21 @@ mod tests { ) .unwrap(); - assert_eq!(ip, IpAddr::from_str("203.0.113.195").unwrap()); + assert_eq!( + ip, + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::from_str("203.0.113.195").unwrap()), + Some(8080) + ) + ); } #[test] - fn it_should_return_an_error_if_it_cannot_get_the_peer_ip_from_the_connection_info() { - let on_reverse_proxy = false; + fn it_should_return_an_error_if_it_cannot_get_the_remote_client_ip_from_the_connection_info() { + let reverse_proxy_mode = ReverseProxyMode::Disabled; - let error = invoke( - on_reverse_proxy, + let error = resolve_remote_client_addr( + &reverse_proxy_mode, &ClientIpSources { right_most_x_forwarded_for: None, connection_info_socket_address: None, @@ -179,18 +213,20 @@ mod tests { } } - mod working_on_reverse_proxy { + mod working_on_reverse_proxy_mode { use std::net::IpAddr; use std::str::FromStr; - use crate::v1::services::peer_ip_resolver::{invoke, ClientIpSources, PeerIpResolutionError}; + use crate::v1::services::peer_ip_resolver::{ + resolve_remote_client_addr, ClientIpSources, PeerIpResolutionError, RemoteClientAddr, ResolvedIp, ReverseProxyMode, + }; #[test] - fn it_should_get_the_peer_ip_from_the_right_most_ip_in_the_x_forwarded_for_header() { - let on_reverse_proxy = true; + fn it_should_get_the_remote_client_ip_from_the_right_most_ip_in_the_x_forwarded_for_header() { + let reverse_proxy_mode = ReverseProxyMode::Enabled; - let ip = invoke( - on_reverse_proxy, + let ip = resolve_remote_client_addr( + &reverse_proxy_mode, &ClientIpSources { right_most_x_forwarded_for: Some(IpAddr::from_str("203.0.113.195").unwrap()), connection_info_socket_address: None, @@ -198,15 +234,21 @@ mod tests { ) .unwrap(); - assert_eq!(ip, IpAddr::from_str("203.0.113.195").unwrap()); + assert_eq!( + ip, + RemoteClientAddr::new( + ResolvedIp::FromXForwardedFor(IpAddr::from_str("203.0.113.195").unwrap()), + None + ) + ); } #[test] fn it_should_return_an_error_if_it_cannot_get_the_right_most_ip_from_the_x_forwarded_for_header() { - let on_reverse_proxy = true; + let reverse_proxy_mode = ReverseProxyMode::Enabled; - let error = invoke( - on_reverse_proxy, + let error = resolve_remote_client_addr( + &reverse_proxy_mode, &ClientIpSources { right_most_x_forwarded_for: None, connection_info_socket_address: None, diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index 921c4e32c..4f0b84e48 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -1,13 +1,12 @@ use std::net::{IpAddr, SocketAddr}; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::RemoteClientAddr; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_metrics::label::{LabelSet, LabelValue}; use torrust_tracker_metrics::label_name; use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; -use crate::services::RemoteClientAddr; - pub mod sender; /// A HTTP core event. @@ -64,12 +63,12 @@ pub struct ClientConnectionContext { impl ClientConnectionContext { #[must_use] pub fn ip_addr(&self) -> IpAddr { - self.remote_client_addr.ip + self.remote_client_addr.ip() } #[must_use] pub fn port(&self) -> Option { - self.remote_client_addr.port + self.remote_client_addr.port() } } @@ -100,11 +99,11 @@ impl From for LabelSet { #[cfg(test)] pub mod test { + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{RemoteClientAddr, ResolvedIp}; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::service_binding::Protocol; use super::Event; - use crate::services::RemoteClientAddr; use crate::tests::sample_info_hash; #[must_use] @@ -153,7 +152,7 @@ pub mod test { let event1 = Event::TcpAnnounce { connection: ConnectionContext::new( - RemoteClientAddr::new(remote_client_ip, Some(8080)), + RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), info_hash, @@ -162,7 +161,10 @@ pub mod test { let event2 = Event::TcpAnnounce { connection: ConnectionContext::new( - RemoteClientAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), Some(8080)), + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2))), + Some(8080), + ), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), info_hash, diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index eafe63ea1..fa0c0c38c 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -11,7 +11,9 @@ use std::panic::Location; use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::announce::{peer_from_request, Announce}; -use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ClientIpSources, PeerIpResolutionError}; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ + resolve_remote_client_addr, ClientIpSources, PeerIpResolutionError, RemoteClientAddr, +}; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; use bittorrent_tracker_core::authentication::service::AuthenticationService; @@ -23,7 +25,6 @@ use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; -use super::{resolve_remote_client_addr, RemoteClientAddr}; use crate::event; use crate::event::Event; @@ -78,15 +79,20 @@ impl AnnounceService { self.authorize(announce_request.info_hash).await?; - let remote_client_addr = resolve_remote_client_addr(self.core_config.net.on_reverse_proxy, client_ip_sources)?; + let remote_client_addr = resolve_remote_client_addr(&self.core_config.net.on_reverse_proxy.into(), client_ip_sources)?; - let mut peer = peer_from_request(announce_request, &remote_client_addr.ip); + let mut peer = peer_from_request(announce_request, &remote_client_addr.ip()); let peers_wanted = Self::peers_wanted(announce_request); let announce_data = self .announce_handler - .announce(&announce_request.info_hash, &mut peer, &remote_client_addr.ip, &peers_wanted) + .announce( + &announce_request.info_hash, + &mut peer, + &remote_client_addr.ip(), + &peers_wanted, + ) .await?; self.send_event( @@ -303,6 +309,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{RemoteClientAddr, ResolvedIp}; use mockall::predicate::{self}; use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::core::AnnounceData; @@ -319,7 +326,6 @@ mod tests { MockHttpStatsEventSender, }; use crate::services::announce::AnnounceService; - use crate::services::RemoteClientAddr; use crate::tests::{sample_info_hash, sample_peer, sample_peer_using_ipv4, sample_peer_using_ipv6}; #[tokio::test] @@ -381,7 +387,7 @@ mod tests { let expected_event = Event::TcpAnnounce { connection: ConnectionContext::new( - RemoteClientAddr::new(remote_client_ip, Some(8080)), + RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), server_service_binding.clone(), ), info_hash: sample_info_hash(), @@ -458,7 +464,7 @@ mod tests { let expected_event = Event::TcpAnnounce { connection: ConnectionContext::new( - RemoteClientAddr::new(remote_client_ip, Some(8080)), + RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), server_service_binding.clone(), ), info_hash: sample_info_hash(), @@ -508,7 +514,7 @@ mod tests { .with(predicate::function(move |event| { let expected_event = Event::TcpAnnounce { connection: ConnectionContext::new( - RemoteClientAddr::new(remote_client_ip, Some(8080)), + RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), server_service_binding.clone(), ), info_hash: sample_info_hash(), diff --git a/packages/http-tracker-core/src/services/mod.rs b/packages/http-tracker-core/src/services/mod.rs index 5ec6dd22d..ce99c6856 100644 --- a/packages/http-tracker-core/src/services/mod.rs +++ b/packages/http-tracker-core/src/services/mod.rs @@ -5,47 +5,5 @@ //! servers. //! //! Refer to [`torrust_tracker`](crate) documentation. - -use std::net::IpAddr; - -use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{self, ClientIpSources, PeerIpResolutionError}; pub mod announce; pub mod scrape; - -#[derive(Debug, PartialEq, Eq, Clone)] -pub struct RemoteClientAddr { - pub ip: IpAddr, - pub port: Option, -} - -impl RemoteClientAddr { - #[must_use] - pub fn new(ip: IpAddr, port: Option) -> Self { - Self { ip, port } - } -} - -/// Resolves the client's real IP address considering proxy headers -/// -/// # Errors -/// -/// This function returns an error if the IP address cannot be resolved. -pub fn resolve_remote_client_addr( - on_reverse_proxy: bool, - client_ip_sources: &ClientIpSources, -) -> Result { - let ip = match peer_ip_resolver::invoke(on_reverse_proxy, client_ip_sources) { - Ok(peer_ip) => Ok(peer_ip), - Err(error) => Err(error), - }?; - - let port = if client_ip_sources.connection_info_socket_address.is_some() { - client_ip_sources - .connection_info_socket_address - .map(|socket_addr| socket_addr.port()) - } else { - None - }; - - Ok(RemoteClientAddr { ip, port }) -} diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index e206b909c..5e8f54cc1 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -10,7 +10,9 @@ use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; -use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ClientIpSources, PeerIpResolutionError}; +use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ + resolve_remote_client_addr, ClientIpSources, PeerIpResolutionError, RemoteClientAddr, +}; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::authentication::{self, Key}; use bittorrent_tracker_core::error::{ScrapeError, TrackerCoreError, WhitelistError}; @@ -19,7 +21,6 @@ use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::service_binding::ServiceBinding; -use super::{resolve_remote_client_addr, RemoteClientAddr}; use crate::event; use crate::event::{ConnectionContext, Event}; @@ -81,7 +82,7 @@ impl ScrapeService { self.scrape_handler.scrape(&scrape_request.info_hashes).await? }; - let remote_client_addr = resolve_remote_client_addr(self.core_config.net.on_reverse_proxy, client_ip_sources)?; + let remote_client_addr = resolve_remote_client_addr(&self.core_config.net.on_reverse_proxy.into(), client_ip_sources)?; self.send_event(remote_client_addr, server_service_binding.clone()).await; @@ -250,7 +251,7 @@ mod tests { use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; - use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ClientIpSources, RemoteClientAddr, ResolvedIp}; use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; @@ -263,7 +264,6 @@ mod tests { initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::services::scrape::ScrapeService; - use crate::services::RemoteClientAddr; use crate::tests::sample_info_hash; use crate::{event, statistics}; @@ -335,7 +335,10 @@ mod tests { .expect_send_event() .with(eq(Event::TcpScrape { connection: ConnectionContext::new( - RemoteClientAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), Some(8080)), + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1))), + Some(8080), + ), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)) .unwrap(), ), @@ -387,7 +390,9 @@ mod tests { .with(eq(Event::TcpScrape { connection: ConnectionContext::new( RemoteClientAddr::new( - IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + ResolvedIp::FromSocketAddr(IpAddr::V6(Ipv6Addr::new( + 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, + ))), Some(8080), ), server_service_binding, @@ -435,7 +440,7 @@ mod tests { use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; - use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ClientIpSources, RemoteClientAddr, ResolvedIp}; use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; use torrust_tracker_primitives::core::ScrapeData; @@ -447,7 +452,6 @@ mod tests { initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::services::scrape::ScrapeService; - use crate::services::RemoteClientAddr; use crate::tests::sample_info_hash; use crate::{event, statistics}; @@ -513,7 +517,10 @@ mod tests { .expect_send_event() .with(eq(Event::TcpScrape { connection: ConnectionContext::new( - RemoteClientAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), Some(8080)), + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1))), + Some(8080), + ), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)) .unwrap(), ), @@ -565,7 +572,9 @@ mod tests { .with(eq(Event::TcpScrape { connection: ConnectionContext::new( RemoteClientAddr::new( - IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + ResolvedIp::FromSocketAddr(IpAddr::V6(Ipv6Addr::new( + 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, + ))), Some(8080), ), server_service_binding, diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index d59c640c1..7e8338edf 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -73,11 +73,11 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{RemoteClientAddr, ResolvedIp}; use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{ConnectionContext, Event}; - use crate::services::RemoteClientAddr; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; use crate::tests::{sample_info_hash, sample_peer_using_ipv4, sample_peer_using_ipv6}; @@ -92,7 +92,7 @@ mod tests { handle_event( Event::TcpAnnounce { connection: ConnectionContext::new( - RemoteClientAddr::new(remote_client_ip, Some(8080)), + RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), info_hash: sample_info_hash(), @@ -115,7 +115,10 @@ mod tests { handle_event( Event::TcpScrape { connection: ConnectionContext::new( - RemoteClientAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), Some(8080)), + RemoteClientAddr::new( + ResolvedIp::FromSocketAddr(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2))), + Some(8080), + ), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), }, @@ -138,7 +141,7 @@ mod tests { handle_event( Event::TcpAnnounce { connection: ConnectionContext::new( - RemoteClientAddr::new(remote_client_ip, Some(8080)), + RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), ), info_hash: sample_info_hash(), @@ -162,7 +165,9 @@ mod tests { Event::TcpScrape { connection: ConnectionContext::new( RemoteClientAddr::new( - IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)), + ResolvedIp::FromSocketAddr(IpAddr::V6(Ipv6Addr::new( + 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, + ))), Some(8080), ), ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), From 00e43ca396cef6c24eef96ee7395e95baa6346e5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 23 Apr 2025 17:23:09 +0100 Subject: [PATCH 0979/1297] refactor: move Registar to AppContainer --- src/app.rs | 26 +++++++++++++------------ src/console/profiling.rs | 2 +- src/container.rs | 11 +++++++++++ src/main.rs | 2 +- tests/servers/api/contract/stats/mod.rs | 2 +- 5 files changed, 28 insertions(+), 15 deletions(-) diff --git a/src/app.rs b/src/app.rs index 5eb162e18..365aae392 100644 --- a/src/app.rs +++ b/src/app.rs @@ -24,7 +24,6 @@ use std::sync::Arc; use tokio::task::JoinHandle; -use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::Configuration; use tracing::instrument; @@ -32,14 +31,14 @@ use crate::bootstrap; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; use crate::container::AppContainer; -pub async fn run() -> (Arc, Vec>, Registar) { +pub async fn run() -> (Arc, Vec>) { let (config, app_container) = bootstrap::app::setup(); let app_container = Arc::new(app_container); - let (jobs, registar) = start(&config, &app_container).await; + let jobs = start(&config, &app_container).await; - (app_container, jobs, registar) + (app_container, jobs) } /// # Panics @@ -49,7 +48,7 @@ pub async fn run() -> (Arc, Vec>, Registar) { /// - Can't retrieve tracker keys from database. /// - Can't load whitelist from database. #[instrument(skip(config, app_container))] -pub async fn start(config: &Configuration, app_container: &Arc) -> (Vec>, Registar) { +pub async fn start(config: &Configuration, app_container: &Arc) -> Vec> { if config.http_api.is_none() && (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) && (config.http_trackers.is_none() || config.http_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) @@ -59,8 +58,6 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> let mut jobs: Vec> = Vec::new(); - let registar = Registar::default(); - // Load peer keys if config.core.private { app_container @@ -96,7 +93,12 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> let udp_tracker_server_container = app_container.udp_tracker_server_container(); jobs.push( - udp_tracker::start_job(udp_tracker_container, udp_tracker_server_container, registar.give_form()).await, + udp_tracker::start_job( + udp_tracker_container, + udp_tracker_server_container, + app_container.registar.give_form(), + ) + .await, ); } } @@ -113,7 +115,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> if let Some(job) = http_tracker::start_job( http_tracker_container, - registar.give_form(), + app_container.registar.give_form(), torrust_axum_http_tracker_server::Version::V1, ) .await @@ -132,7 +134,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> if let Some(job) = tracker_apis::start_job( http_api_container, - registar.give_form(), + app_container.registar.give_form(), torrust_axum_rest_tracker_api_server::Version::V1, ) .await @@ -152,7 +154,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> } // Start Health Check API - jobs.push(health_check_api::start_job(&config.health_check_api, registar.entries()).await); + jobs.push(health_check_api::start_job(&config.health_check_api, app_container.registar.entries()).await); - (jobs, registar) + jobs } diff --git a/src/console/profiling.rs b/src/console/profiling.rs index 426712c34..3ed9c6389 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -179,7 +179,7 @@ pub async fn run() { return; }; - let (_app_container, jobs, _registar) = app::run().await; + let (_app_container, jobs) = app::run().await; // Run the tracker for a fixed duration let run_duration = sleep(Duration::from_secs(duration_secs)); diff --git a/src/container.rs b/src/container.rs index 9df9c9611..537be2605 100644 --- a/src/container.rs +++ b/src/container.rs @@ -7,6 +7,7 @@ use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::{UdpTrackerCoreContainer, UdpTrackerCoreServices}; use bittorrent_udp_tracker_core::{self}; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; +use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{Configuration, HttpApi}; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use tracing::instrument; @@ -24,6 +25,9 @@ pub struct AppContainer { // Configuration pub http_api_config: Arc>, + // Registar + pub registar: Arc, + // Core pub tracker_core_container: Arc, @@ -46,6 +50,10 @@ impl AppContainer { let http_api_config = Arc::new(configuration.http_api.clone()); + // Registar + + let registar = Arc::new(Registar::default()); + // Core let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); @@ -73,6 +81,9 @@ impl AppContainer { // Configuration http_api_config, + // Registar + registar, + // Core tracker_core_container, diff --git a/src/main.rs b/src/main.rs index cc7c202c4..de73d0a15 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,7 @@ use torrust_tracker_lib::app; #[tokio::main] async fn main() { - let (_app_container, jobs, _registar) = app::run().await; + let (_app_container, jobs) = app::run().await; // handle the signals tokio::select! { diff --git a/tests/servers/api/contract/stats/mod.rs b/tests/servers/api/contract/stats/mod.rs index 016a372dd..d50bc58a5 100644 --- a/tests/servers/api/contract/stats/mod.rs +++ b/tests/servers/api/contract/stats/mod.rs @@ -51,7 +51,7 @@ async fn the_stats_api_endpoint_should_return_the_global_stats() { env::set_var("TORRUST_TRACKER_CONFIG_TOML", config_with_two_http_trackers); - let (_app_container, _jobs, _registar) = app::run().await; + let (_app_container, _jobs) = app::run().await; announce_to_tracker("http://127.0.0.1:7272").await; announce_to_tracker("http://127.0.0.1:7373").await; From 56c3bd1b3c50b74fb03a5c73e6a10c541a96016a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 23 Apr 2025 17:35:46 +0100 Subject: [PATCH 0980/1297] refactor: update logs messages --- src/console/profiling.rs | 3 ++- src/main.rs | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/console/profiling.rs b/src/console/profiling.rs index 3ed9c6389..873dbb574 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -189,7 +189,8 @@ pub async fn run() { tracing::info!("Torrust timed shutdown.."); }, _ = tokio::signal::ctrl_c() => { - tracing::info!("Torrust shutting down via Ctrl+C ..."); + tracing::info!("Torrust tracker shutting down via Ctrl+C ..."); + // Await for all jobs to shutdown futures::future::join_all(jobs).await; } diff --git a/src/main.rs b/src/main.rs index de73d0a15..8ba4311f7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,11 +7,12 @@ async fn main() { // handle the signals tokio::select! { _ = tokio::signal::ctrl_c() => { - tracing::info!("Torrust shutting down ..."); + tracing::info!("Torrust tracker shutting down ..."); // Await for all jobs to shutdown futures::future::join_all(jobs).await; - tracing::info!("Torrust successfully shutdown."); + + tracing::info!("Torrust tracker successfully shutdown."); } } } From d80bfc0772ffee2bc40883540bee33bcce58d83b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 23 Apr 2025 18:08:51 +0100 Subject: [PATCH 0981/1297] refactor: extract functions in app start --- src/app.rs | 120 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 81 insertions(+), 39 deletions(-) diff --git a/src/app.rs b/src/app.rs index 365aae392..d394fe644 100644 --- a/src/app.rs +++ b/src/app.rs @@ -24,11 +24,11 @@ use std::sync::Arc; use tokio::task::JoinHandle; -use torrust_tracker_configuration::Configuration; +use torrust_tracker_configuration::{Configuration, HttpTracker, UdpTracker}; use tracing::instrument; -use crate::bootstrap; use crate::bootstrap::jobs::{health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; +use crate::bootstrap::{self}; use crate::container::AppContainer; pub async fn run() -> (Arc, Vec>) { @@ -41,6 +41,8 @@ pub async fn run() -> (Arc, Vec>) { (app_container, jobs) } +/// Starts the tracker application. +/// /// # Panics /// /// Will panic if: @@ -49,16 +51,40 @@ pub async fn run() -> (Arc, Vec>) { /// - Can't load whitelist from database. #[instrument(skip(config, app_container))] pub async fn start(config: &Configuration, app_container: &Arc) -> Vec> { + warn_if_no_services_enabled(config); + + load_data_from_database(config, app_container).await; + + start_jobs(config, app_container).await +} + +async fn load_data_from_database(config: &Configuration, app_container: &Arc) { + load_peer_keys(config, app_container).await; + load_whitelisted_torrents(config, app_container).await; +} + +async fn start_jobs(config: &Configuration, app_container: &Arc) -> Vec> { + let mut jobs: Vec> = Vec::new(); + + start_the_udp_instances(config, app_container, &mut jobs).await; + start_the_http_instances(config, app_container, &mut jobs).await; + start_the_http_api(config, app_container, &mut jobs).await; + start_torrent_cleanup(config, app_container, &mut jobs); + start_health_check_api(config, app_container, &mut jobs).await; + + jobs +} + +fn warn_if_no_services_enabled(config: &Configuration) { if config.http_api.is_none() && (config.udp_trackers.is_none() || config.udp_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) && (config.http_trackers.is_none() || config.http_trackers.as_ref().map_or(true, std::vec::Vec::is_empty)) { tracing::warn!("No services enabled in configuration"); } +} - let mut jobs: Vec> = Vec::new(); - - // Load peer keys +async fn load_peer_keys(config: &Configuration, app_container: &Arc) { if config.core.private { app_container .tracker_core_container @@ -67,8 +93,9 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> .await .expect("Could not retrieve keys from database."); } +} - // Load whitelisted torrents +async fn load_whitelisted_torrents(config: &Configuration, app_container: &Arc) { if config.core.listed { app_container .tracker_core_container @@ -77,8 +104,9 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> .await .expect("Could not load whitelist from database."); } +} - // Start the UDP blocks +async fn start_the_udp_instances(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { if let Some(udp_trackers) = &config.udp_trackers { for udp_tracker_config in udp_trackers { if config.core.private { @@ -87,47 +115,61 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> udp_tracker_config.bind_address ); } else { - let udp_tracker_container = app_container - .udp_tracker_container(udp_tracker_config.bind_address) - .expect("Could not create UDP tracker container"); - let udp_tracker_server_container = app_container.udp_tracker_server_container(); - - jobs.push( - udp_tracker::start_job( - udp_tracker_container, - udp_tracker_server_container, - app_container.registar.give_form(), - ) - .await, - ); + start_udp_instance(udp_tracker_config, app_container, jobs).await; } } } else { tracing::info!("No UDP blocks in configuration"); } +} + +async fn start_udp_instance(udp_tracker_config: &UdpTracker, app_container: &Arc, jobs: &mut Vec>) { + let udp_tracker_container = app_container + .udp_tracker_container(udp_tracker_config.bind_address) + .expect("Could not create UDP tracker container"); + let udp_tracker_server_container = app_container.udp_tracker_server_container(); - // Start the HTTP blocks + jobs.push( + udp_tracker::start_job( + udp_tracker_container, + udp_tracker_server_container, + app_container.registar.give_form(), + ) + .await, + ); +} + +async fn start_the_http_instances(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { if let Some(http_trackers) = &config.http_trackers { for http_tracker_config in http_trackers { - let http_tracker_container = app_container - .http_tracker_container(http_tracker_config.bind_address) - .expect("Could not create HTTP tracker container"); - - if let Some(job) = http_tracker::start_job( - http_tracker_container, - app_container.registar.give_form(), - torrust_axum_http_tracker_server::Version::V1, - ) - .await - { - jobs.push(job); - } + start_http_instance(http_tracker_config, app_container, jobs).await; } } else { tracing::info!("No HTTP blocks in configuration"); } +} + +async fn start_http_instance( + http_tracker_config: &HttpTracker, + app_container: &Arc, + jobs: &mut Vec>, +) { + let http_tracker_container = app_container + .http_tracker_container(http_tracker_config.bind_address) + .expect("Could not create HTTP tracker container"); + + if let Some(job) = http_tracker::start_job( + http_tracker_container, + app_container.registar.give_form(), + torrust_axum_http_tracker_server::Version::V1, + ) + .await + { + jobs.push(job); + } +} - // Start HTTP API +async fn start_the_http_api(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { if let Some(http_api_config) = &config.http_api { let http_api_config = Arc::new(http_api_config.clone()); let http_api_container = app_container.tracker_http_api_container(&http_api_config); @@ -144,17 +186,17 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> } else { tracing::info!("No API block in configuration"); } +} - // Start runners to remove torrents without peers, every interval +fn start_torrent_cleanup(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { if config.core.inactive_peer_cleanup_interval > 0 { jobs.push(torrent_cleanup::start_job( &config.core, &app_container.tracker_core_container.torrents_manager, )); } +} - // Start Health Check API +async fn start_health_check_api(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { jobs.push(health_check_api::start_job(&config.health_check_api, app_container.registar.entries()).await); - - jobs } From 17fb90943bdb95ab7ed1da72589f34e9a0a9d356 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 23 Apr 2025 19:56:49 +0100 Subject: [PATCH 0982/1297] refactor: [#1444] http core event listener start in app start. Step 1 This is the first step in a bigger refactor to move the start of event listeners from app container instantiation to app start (jobs creation). --- .../axum-http-tracker-server/src/server.rs | 1 - packages/http-tracker-core/src/container.rs | 1 - .../http-tracker-core/src/event/sender.rs | 1 + .../src/statistics/event/handler.rs | 12 ++--- .../src/statistics/event/listener.rs | 4 +- .../src/statistics/keeper.rs | 45 +++++++++++++++---- .../src/statistics/services.rs | 3 +- .../http-tracker-core/src/statistics/setup.rs | 31 ++++++++----- .../src/statistics/services.rs | 1 - 9 files changed, 67 insertions(+), 32 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index eea00c142..896922751 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -274,7 +274,6 @@ mod tests { let (http_stats_event_sender, http_stats_repository) = bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); - let http_stats_repository = Arc::new(http_stats_repository); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 7fc2f48a6..913236483 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -65,7 +65,6 @@ impl HttpTrackerCoreServices { let (http_stats_event_sender, http_stats_repository) = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); let http_stats_event_sender = Arc::new(http_stats_event_sender); - let http_stats_repository = Arc::new(http_stats_repository); let http_announce_service = Arc::new(AnnounceService::new( tracker_core_container.core_config.clone(), tracker_core_container.announce_handler.clone(), diff --git a/packages/http-tracker-core/src/event/sender.rs b/packages/http-tracker-core/src/event/sender.rs index 511a381d0..b720926bb 100644 --- a/packages/http-tracker-core/src/event/sender.rs +++ b/packages/http-tracker-core/src/event/sender.rs @@ -16,6 +16,7 @@ pub trait Sender: Sync + Send { } /// An event sender implementation using a broadcast channel. +#[derive(Clone)] pub struct Broadcaster { pub(crate) sender: broadcast::Sender, } diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index 7e8338edf..8d2ad1aa2 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -1,4 +1,5 @@ use std::net::IpAddr; +use std::sync::Arc; use torrust_tracker_metrics::label::{LabelSet, LabelValue}; use torrust_tracker_metrics::{label_name, metric_name}; @@ -12,7 +13,7 @@ use crate::statistics::HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; /// /// This function panics if the client IP address is not the same as the IP /// version of the event. -pub async fn handle_event(event: Event, stats_repository: &Repository, now: DurationSinceUnixEpoch) { +pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { match event { Event::TcpAnnounce { connection, .. } => { // Global fixed metrics @@ -72,6 +73,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{RemoteClientAddr, ResolvedIp}; use torrust_tracker_clock::clock::Time; @@ -85,7 +87,7 @@ mod tests { #[tokio::test] async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { - let stats_repository = Repository::new(); + let stats_repository = Arc::new(Repository::new()); let peer = sample_peer_using_ipv4(); let remote_client_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)); @@ -110,7 +112,7 @@ mod tests { #[tokio::test] async fn should_increase_the_tcp4_scrapes_counter_when_it_receives_a_tcp4_scrape_event() { - let stats_repository = Repository::new(); + let stats_repository = Arc::new(Repository::new()); handle_event( Event::TcpScrape { @@ -134,7 +136,7 @@ mod tests { #[tokio::test] async fn should_increase_the_tcp6_announces_counter_when_it_receives_a_tcp6_announce_event() { - let stats_repository = Repository::new(); + let stats_repository = Arc::new(Repository::new()); let peer = sample_peer_using_ipv6(); let remote_client_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); @@ -159,7 +161,7 @@ mod tests { #[tokio::test] async fn should_increase_the_tcp6_scrapes_counter_when_it_receives_a_tcp6_scrape_event() { - let stats_repository = Repository::new(); + let stats_repository = Arc::new(Repository::new()); handle_event( Event::TcpScrape { diff --git a/packages/http-tracker-core/src/statistics/event/listener.rs b/packages/http-tracker-core/src/statistics/event/listener.rs index 5e87b47df..00fce6b77 100644 --- a/packages/http-tracker-core/src/statistics/event/listener.rs +++ b/packages/http-tracker-core/src/statistics/event/listener.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use tokio::sync::broadcast; use torrust_tracker_clock::clock::Time; @@ -6,7 +8,7 @@ use crate::event::Event; use crate::statistics::repository::Repository; use crate::{CurrentClock, HTTP_TRACKER_LOG_TARGET}; -pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { +pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Arc) { loop { match receiver.recv().await { Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, diff --git a/packages/http-tracker-core/src/statistics/keeper.rs b/packages/http-tracker-core/src/statistics/keeper.rs index 1b69f032d..fad9382d7 100644 --- a/packages/http-tracker-core/src/statistics/keeper.rs +++ b/packages/http-tracker-core/src/statistics/keeper.rs @@ -1,8 +1,10 @@ -use tokio::sync::broadcast::Receiver; +use std::sync::Arc; + +use tokio::task::JoinHandle; use super::event::listener::dispatch_events; use super::repository::Repository; -use crate::event::Event; +use crate::event::sender::{self, Broadcaster}; use crate::HTTP_TRACKER_LOG_TARGET; /// The service responsible for keeping tracker metrics (listening to statistics events and handle them). @@ -10,25 +12,50 @@ use crate::HTTP_TRACKER_LOG_TARGET; /// It actively listen to new statistics events. When it receives a new event /// it accordingly increases the counters. pub struct Keeper { - pub repository: Repository, + pub enable_sender: bool, + pub broadcaster: Broadcaster, + pub repository: Arc, } impl Default for Keeper { fn default() -> Self { - Self::new() + let enable_sender = true; + let broadcaster = Broadcaster::default(); + let repository = Arc::new(Repository::new()); + + Self::new(enable_sender, broadcaster, repository) } } impl Keeper { + /// Creates a new instance of [`Keeper`]. #[must_use] - pub fn new() -> Self { + pub fn new(enable_sender: bool, broadcaster: Broadcaster, repository: Arc) -> Self { Self { - repository: Repository::new(), + enable_sender, + broadcaster, + repository, + } + } + + #[must_use] + pub fn sender(&self) -> Option> { + if self.enable_sender { + Some(Box::new(self.broadcaster.clone())) + } else { + None } } - pub fn run_event_listener(&mut self, receiver: Receiver) { + #[must_use] + pub fn repository(&self) -> Arc { + self.repository.clone() + } + + #[must_use] + pub fn run_event_listener(&self) -> JoinHandle<()> { let stats_repository = self.repository.clone(); + let receiver = self.broadcaster.subscribe(); tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting HTTP tracker core event listener"); @@ -36,7 +63,7 @@ impl Keeper { dispatch_events(receiver, stats_repository).await; tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "HTTP tracker core event listener finished"); - }); + }) } } @@ -48,7 +75,7 @@ mod tests { #[tokio::test] async fn should_contain_the_tracker_statistics() { - let stats_tracker = Keeper::new(); + let stats_tracker = Keeper::default(); let stats = stats_tracker.repository.get_stats().await; diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 418b0d082..2895d1b6d 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -89,9 +89,8 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let (_http_stats_event_sender, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_repository = Arc::new(http_stats_repository); - let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), http_stats_repository.clone()).await; + let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), http_stats_repository).await; assert_eq!( tracker_metrics, diff --git a/packages/http-tracker-core/src/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs index e2974e4c0..e2b252c23 100644 --- a/packages/http-tracker-core/src/statistics/setup.rs +++ b/packages/http-tracker-core/src/statistics/setup.rs @@ -1,8 +1,12 @@ //! Setup for the tracker statistics. //! //! The [`factory`] function builds the structs needed for handling the tracker metrics. +use std::sync::Arc; + +use super::keeper::Keeper; +use super::repository::Repository; +use crate::event; use crate::event::sender::Broadcaster; -use crate::{event, statistics}; /// It builds the structs needed for handling the tracker metrics. /// @@ -17,20 +21,23 @@ use crate::{event, statistics}; /// not run the event listeners, consequently the statistics events are sent are /// received but not dispatched to the handler. #[must_use] -pub fn factory(tracker_usage_statistics: bool) -> (Option>, statistics::repository::Repository) { - let mut keeper = statistics::keeper::Keeper::new(); - - let opt_event_sender: Option> = if tracker_usage_statistics { - let broadcaster = Broadcaster::default(); +pub fn factory(tracker_usage_statistics: bool) -> (Option>, Arc) { + let keeper = keeper_factory(tracker_usage_statistics); - keeper.run_event_listener(broadcaster.subscribe()); + if tracker_usage_statistics { + // todo: this should be started like the other jobs during `app::start` + // and keep the join handle in a list of jobs. + let _unused = keeper.run_event_listener(); + } - Some(Box::new(broadcaster)) - } else { - None - }; + (keeper.sender(), keeper.repository()) +} - (opt_event_sender, keeper.repository) +#[must_use] +pub fn keeper_factory(tracker_usage_statistics: bool) -> Arc { + let broadcaster = Broadcaster::default(); + let repository = Arc::new(Repository::new()); + Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone(), repository.clone())) } #[cfg(test)] diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 9277df92b..744c8fd7c 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -149,7 +149,6 @@ mod tests { // HTTP core stats let (_http_stats_event_sender, http_stats_repository) = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_repository = Arc::new(http_stats_repository); // UDP core stats let (_udp_stats_event_sender, _udp_stats_repository) = From 07d13146f5cd13055a37323e12fbf9f970f41379 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 24 Apr 2025 15:54:47 +0100 Subject: [PATCH 0983/1297] refactor: [#1444] http core event listener start in app start. Step 2 --- .../axum-http-tracker-server/src/server.rs | 14 +++++--- .../src/v1/handlers/announce.rs | 15 ++++++--- .../src/v1/handlers/scrape.rs | 14 +++++--- .../http-tracker-core/benches/helpers/util.rs | 25 ++++++++------ packages/http-tracker-core/src/container.rs | 15 +++++++-- .../src/services/announce.rs | 14 +++++--- .../http-tracker-core/src/services/scrape.rs | 12 ++++--- .../src/statistics/keeper.rs | 6 ++-- .../src/statistics/services.rs | 11 ++++++- .../http-tracker-core/src/statistics/setup.rs | 33 ++++++++++--------- .../src/statistics/services.rs | 11 +++++-- 11 files changed, 115 insertions(+), 55 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 896922751..40620674f 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -270,10 +270,16 @@ mod tests { let http_tracker_config = Arc::new(http_tracker_config.clone()); - // HTTP stats - let (http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let http_stats_event_sender = Arc::new(http_stats_event_sender); + // HTTP core stats + let keeper = bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let http_stats_event_sender = keeper.sender(); + let http_stats_repository = keeper.repository(); + + if configuration.core.tracker_usage_statistics { + // todo: this should be started like the other jobs during `app::start` + // and keep the join handle in a list of jobs. + let _unused = keeper.run_event_listener(); + } let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 296cefcd5..3729f5bdc 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -160,11 +160,16 @@ mod tests { &db_torrent_repository, )); - // HTTP stats - let (http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_event_sender = Arc::new(http_stats_event_sender); - let _http_stats_repository = Arc::new(http_stats_repository); + // HTTP core stats + let keeper = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = keeper.sender(); + let _http_stats_repository = keeper.repository(); + + if config.core.tracker_usage_statistics { + // todo: this should be started like the other jobs during `app::start` + // and keep the join handle in a list of jobs. + let _unused = keeper.run_event_listener(); + } let announce_service = Arc::new(AnnounceService::new( core_config.clone(), diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index e5d94a072..9e5fafd46 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -131,10 +131,16 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - // HTTP stats - let (http_stats_event_sender, _http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_event_sender = Arc::new(http_stats_event_sender); + // HTTP core stats + let keeper = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = keeper.sender(); + let _http_stats_repository = keeper.repository(); + + if config.core.tracker_usage_statistics { + // todo: this should be started like the other jobs during `app::start` + // and keep the join handle in a list of jobs. + let _unused = keeper.run_event_listener(); + } ( CoreTrackerServices { diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index dff516063..957f70444 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -2,6 +2,8 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use bittorrent_http_tracker_core::event::Event; +use bittorrent_http_tracker_core::{event, statistics}; use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_primitives::info_hash::InfoHash; @@ -13,6 +15,9 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use futures::future::BoxFuture; +use mockall::mock; +use tokio::sync::broadcast::error::SendError; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; @@ -50,10 +55,16 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( &db_torrent_repository, )); - // HTTP stats - let (http_stats_event_sender, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_event_sender = Arc::new(http_stats_event_sender); - let _http_stats_repository = Arc::new(http_stats_repository); + // HTTP core stats + let keeper = statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = keeper.sender(); + let _http_stats_repository = keeper.repository(); + + if config.core.tracker_usage_statistics { + // todo: this should be started like the other jobs during `app::start` + // and keep the join handle in a list of jobs. + let _unused = keeper.run_event_listener(); + } ( CoreTrackerServices { @@ -105,12 +116,6 @@ pub fn sample_info_hash() -> InfoHash { .expect("String should be a valid info hash") } -use bittorrent_http_tracker_core::event::Event; -use bittorrent_http_tracker_core::{event, statistics}; -use futures::future::BoxFuture; -use mockall::mock; -use tokio::sync::broadcast::error::SendError; - mock! { HttpStatsEventSender {} impl event::sender::Sender for HttpStatsEventSender { diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 913236483..302a4fbbe 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -62,9 +62,17 @@ pub struct HttpTrackerCoreServices { impl HttpTrackerCoreServices { #[must_use] pub fn initialize_from(tracker_core_container: &Arc) -> Arc { - let (http_stats_event_sender, http_stats_repository) = - statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); - let http_stats_event_sender = Arc::new(http_stats_event_sender); + // HTTP core stats + let keeper = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); + let http_stats_event_sender = keeper.sender(); + let http_stats_repository = keeper.repository(); + + if tracker_core_container.core_config.tracker_usage_statistics { + // todo: this should be started like the other jobs during `app::start` + // and keep the join handle in a list of jobs. + let _unused = keeper.run_event_listener(); + } + let http_announce_service = Arc::new(AnnounceService::new( tracker_core_container.core_config.clone(), tracker_core_container.announce_handler.clone(), @@ -72,6 +80,7 @@ impl HttpTrackerCoreServices { tracker_core_container.whitelist_authorization.clone(), http_stats_event_sender.clone(), )); + let http_scrape_service = Arc::new(ScrapeService::new( tracker_core_container.core_config.clone(), tracker_core_container.scrape_handler.clone(), diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index fa0c0c38c..a3014873e 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -252,10 +252,16 @@ mod tests { &db_torrent_repository, )); - // HTTP stats - let (http_stats_event_sender, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_event_sender = Arc::new(http_stats_event_sender); - let _http_stats_repository = Arc::new(http_stats_repository); + // HTTP core stats + let keeper = statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = keeper.sender(); + let _http_stats_repository = keeper.repository(); + + if config.core.tracker_usage_statistics { + // todo: this should be started like the other jobs during `app::start` + // and keep the join handle in a list of jobs. + let _unused = keeper.run_event_listener(); + } ( CoreTrackerServices { diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 5e8f54cc1..21308a6aa 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -272,8 +272,10 @@ mod tests { let configuration = configuration::ephemeral_public(); let core_config = Arc::new(configuration.core.clone()); - let (http_stats_event_sender, _http_stats_repository) = statistics::setup::factory(false); - let http_stats_event_sender = Arc::new(http_stats_event_sender); + // HTTP core stats + let keeper = statistics::setup::factory(false); + let http_stats_event_sender = keeper.sender(); + let _http_stats_repository = keeper.repository(); let container = initialize_services_with_configuration(&configuration); @@ -462,8 +464,10 @@ mod tests { let container = initialize_services_with_configuration(&config); - let (http_stats_event_sender, _http_stats_repository) = statistics::setup::factory(false); - let http_stats_event_sender = Arc::new(http_stats_event_sender); + // HTTP core stats + let keeper = statistics::setup::factory(false); + let http_stats_event_sender = keeper.sender(); + let _http_stats_repository = keeper.repository(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; diff --git a/packages/http-tracker-core/src/statistics/keeper.rs b/packages/http-tracker-core/src/statistics/keeper.rs index fad9382d7..4c0f7c916 100644 --- a/packages/http-tracker-core/src/statistics/keeper.rs +++ b/packages/http-tracker-core/src/statistics/keeper.rs @@ -39,11 +39,11 @@ impl Keeper { } #[must_use] - pub fn sender(&self) -> Option> { + pub fn sender(&self) -> Arc>> { if self.enable_sender { - Some(Box::new(self.broadcaster.clone())) + Arc::new(Some(Box::new(self.broadcaster.clone()))) } else { - None + Arc::new(None) } } diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 2895d1b6d..172e7b9ab 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -88,7 +88,16 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let (_http_stats_event_sender, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + // HTTP core stats + let keeper = statistics::setup::factory(config.core.tracker_usage_statistics); + let _http_stats_event_sender = keeper.sender(); + let http_stats_repository = keeper.repository(); + + if config.core.tracker_usage_statistics { + // todo: this should be started like the other jobs during `app::start` + // and keep the join handle in a list of jobs. + let _unused = keeper.run_event_listener(); + } let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), http_stats_repository).await; diff --git a/packages/http-tracker-core/src/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs index e2b252c23..565e86fd4 100644 --- a/packages/http-tracker-core/src/statistics/setup.rs +++ b/packages/http-tracker-core/src/statistics/setup.rs @@ -5,7 +5,6 @@ use std::sync::Arc; use super::keeper::Keeper; use super::repository::Repository; -use crate::event; use crate::event::sender::Broadcaster; /// It builds the structs needed for handling the tracker metrics. @@ -21,16 +20,8 @@ use crate::event::sender::Broadcaster; /// not run the event listeners, consequently the statistics events are sent are /// received but not dispatched to the handler. #[must_use] -pub fn factory(tracker_usage_statistics: bool) -> (Option>, Arc) { - let keeper = keeper_factory(tracker_usage_statistics); - - if tracker_usage_statistics { - // todo: this should be started like the other jobs during `app::start` - // and keep the join handle in a list of jobs. - let _unused = keeper.run_event_listener(); - } - - (keeper.sender(), keeper.repository()) +pub fn factory(tracker_usage_statistics: bool) -> Arc { + keeper_factory(tracker_usage_statistics) } #[must_use] @@ -48,17 +39,29 @@ mod test { async fn should_not_send_any_event_when_statistics_are_disabled() { let tracker_usage_statistics = false; - let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); + // HTTP core stats + let keeper = factory(tracker_usage_statistics); + let http_stats_event_sender = keeper.sender(); + let _http_stats_repository = keeper.repository(); + + if tracker_usage_statistics { + // todo: this should be started like the other jobs during `app::start` + // and keep the join handle in a list of jobs. + let _unused = keeper.run_event_listener(); + } - assert!(stats_event_sender.is_none()); + assert!(http_stats_event_sender.is_none()); } #[tokio::test] async fn should_send_events_when_statistics_are_enabled() { let tracker_usage_statistics = true; - let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); + // HTTP core stats + let keeper = factory(tracker_usage_statistics); + let http_stats_event_sender = keeper.sender(); + let _http_stats_repository = keeper.repository(); - assert!(stats_event_sender.is_some()); + assert!(http_stats_event_sender.is_some()); } } diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 744c8fd7c..ac8948e42 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -147,8 +147,15 @@ mod tests { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); // HTTP core stats - let (_http_stats_event_sender, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let keeper = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let _http_stats_event_sender = keeper.sender(); + let http_stats_repository = keeper.repository(); + + if config.core.tracker_usage_statistics { + // todo: this should be started like the other jobs during `app::start` + // and keep the join handle in a list of jobs. + let _unused = keeper.run_event_listener(); + } // UDP core stats let (_udp_stats_event_sender, _udp_stats_repository) = From b2cf5d9e921326e6d5f163023fa563ee49a583de Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 24 Apr 2025 15:59:26 +0100 Subject: [PATCH 0984/1297] refactor: [#1444] rename variable --- packages/axum-http-tracker-server/src/server.rs | 9 +++++---- .../src/v1/handlers/announce.rs | 9 +++++---- .../src/v1/handlers/scrape.rs | 9 +++++---- packages/http-tracker-core/benches/helpers/util.rs | 8 ++++---- packages/http-tracker-core/src/container.rs | 8 ++++---- .../http-tracker-core/src/services/announce.rs | 8 ++++---- packages/http-tracker-core/src/services/scrape.rs | 12 ++++++------ .../http-tracker-core/src/statistics/services.rs | 8 ++++---- packages/http-tracker-core/src/statistics/setup.rs | 14 +++++++------- .../src/statistics/services.rs | 9 +++++---- 10 files changed, 49 insertions(+), 45 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 40620674f..52085f822 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -271,14 +271,15 @@ mod tests { let http_tracker_config = Arc::new(http_tracker_config.clone()); // HTTP core stats - let keeper = bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let http_stats_event_sender = keeper.sender(); - let http_stats_repository = keeper.repository(); + let http_core_stats_keeper = + bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let http_stats_event_sender = http_core_stats_keeper.sender(); + let http_stats_repository = http_core_stats_keeper.repository(); if configuration.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = keeper.run_event_listener(); + let _unused = http_core_stats_keeper.run_event_listener(); } let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 3729f5bdc..5c08e97eb 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -161,14 +161,15 @@ mod tests { )); // HTTP core stats - let keeper = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_event_sender = keeper.sender(); - let _http_stats_repository = keeper.repository(); + let http_core_stats_keeper = + bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = http_core_stats_keeper.sender(); + let _http_stats_repository = http_core_stats_keeper.repository(); if config.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = keeper.run_event_listener(); + let _unused = http_core_stats_keeper.run_event_listener(); } let announce_service = Arc::new(AnnounceService::new( diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index 9e5fafd46..76390ea0d 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -132,14 +132,15 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); // HTTP core stats - let keeper = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_event_sender = keeper.sender(); - let _http_stats_repository = keeper.repository(); + let http_core_stats_keeper = + bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = http_core_stats_keeper.sender(); + let _http_stats_repository = http_core_stats_keeper.repository(); if config.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = keeper.run_event_listener(); + let _unused = http_core_stats_keeper.run_event_listener(); } ( diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 957f70444..3ef1ccf46 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -56,14 +56,14 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( )); // HTTP core stats - let keeper = statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_event_sender = keeper.sender(); - let _http_stats_repository = keeper.repository(); + let http_core_stats_keeper = statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = http_core_stats_keeper.sender(); + let _http_stats_repository = http_core_stats_keeper.repository(); if config.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = keeper.run_event_listener(); + let _unused = http_core_stats_keeper.run_event_listener(); } ( diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 302a4fbbe..0b8bd9337 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -63,14 +63,14 @@ impl HttpTrackerCoreServices { #[must_use] pub fn initialize_from(tracker_core_container: &Arc) -> Arc { // HTTP core stats - let keeper = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); - let http_stats_event_sender = keeper.sender(); - let http_stats_repository = keeper.repository(); + let http_core_stats_keeper = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); + let http_stats_event_sender = http_core_stats_keeper.sender(); + let http_stats_repository = http_core_stats_keeper.repository(); if tracker_core_container.core_config.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = keeper.run_event_listener(); + let _unused = http_core_stats_keeper.run_event_listener(); } let http_announce_service = Arc::new(AnnounceService::new( diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index a3014873e..5e50ebd8f 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -253,14 +253,14 @@ mod tests { )); // HTTP core stats - let keeper = statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_event_sender = keeper.sender(); - let _http_stats_repository = keeper.repository(); + let http_core_stats_keeper = statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = http_core_stats_keeper.sender(); + let _http_stats_repository = http_core_stats_keeper.repository(); if config.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = keeper.run_event_listener(); + let _unused = http_core_stats_keeper.run_event_listener(); } ( diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 21308a6aa..7cd1a5991 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -273,9 +273,9 @@ mod tests { let core_config = Arc::new(configuration.core.clone()); // HTTP core stats - let keeper = statistics::setup::factory(false); - let http_stats_event_sender = keeper.sender(); - let _http_stats_repository = keeper.repository(); + let http_core_stats_keeper = statistics::setup::factory(false); + let http_stats_event_sender = http_core_stats_keeper.sender(); + let _http_stats_repository = http_core_stats_keeper.repository(); let container = initialize_services_with_configuration(&configuration); @@ -465,9 +465,9 @@ mod tests { let container = initialize_services_with_configuration(&config); // HTTP core stats - let keeper = statistics::setup::factory(false); - let http_stats_event_sender = keeper.sender(); - let _http_stats_repository = keeper.repository(); + let http_core_stats_keeper = statistics::setup::factory(false); + let http_stats_event_sender = http_core_stats_keeper.sender(); + let _http_stats_repository = http_core_stats_keeper.repository(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 172e7b9ab..94ade2e45 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -89,14 +89,14 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); // HTTP core stats - let keeper = statistics::setup::factory(config.core.tracker_usage_statistics); - let _http_stats_event_sender = keeper.sender(); - let http_stats_repository = keeper.repository(); + let http_core_stats_keeper = statistics::setup::factory(config.core.tracker_usage_statistics); + let _http_stats_event_sender = http_core_stats_keeper.sender(); + let http_stats_repository = http_core_stats_keeper.repository(); if config.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = keeper.run_event_listener(); + let _unused = http_core_stats_keeper.run_event_listener(); } let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), http_stats_repository).await; diff --git a/packages/http-tracker-core/src/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs index 565e86fd4..a78c53f6d 100644 --- a/packages/http-tracker-core/src/statistics/setup.rs +++ b/packages/http-tracker-core/src/statistics/setup.rs @@ -40,14 +40,14 @@ mod test { let tracker_usage_statistics = false; // HTTP core stats - let keeper = factory(tracker_usage_statistics); - let http_stats_event_sender = keeper.sender(); - let _http_stats_repository = keeper.repository(); + let http_core_stats_keeper = factory(tracker_usage_statistics); + let http_stats_event_sender = http_core_stats_keeper.sender(); + let _http_stats_repository = http_core_stats_keeper.repository(); if tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = keeper.run_event_listener(); + let _unused = http_core_stats_keeper.run_event_listener(); } assert!(http_stats_event_sender.is_none()); @@ -58,9 +58,9 @@ mod test { let tracker_usage_statistics = true; // HTTP core stats - let keeper = factory(tracker_usage_statistics); - let http_stats_event_sender = keeper.sender(); - let _http_stats_repository = keeper.repository(); + let http_core_stats_keeper = factory(tracker_usage_statistics); + let http_stats_event_sender = http_core_stats_keeper.sender(); + let _http_stats_repository = http_core_stats_keeper.repository(); assert!(http_stats_event_sender.is_some()); } diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index ac8948e42..93c8951f7 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -147,14 +147,15 @@ mod tests { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); // HTTP core stats - let keeper = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); - let _http_stats_event_sender = keeper.sender(); - let http_stats_repository = keeper.repository(); + let http_core_stats_keeper = + bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let _http_stats_event_sender = http_core_stats_keeper.sender(); + let http_stats_repository = http_core_stats_keeper.repository(); if config.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = keeper.run_event_listener(); + let _unused = http_core_stats_keeper.run_event_listener(); } // UDP core stats From 5906037113a0d5a83b5451db790eb0fdcbc84ae6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 24 Apr 2025 16:09:31 +0100 Subject: [PATCH 0985/1297] refactor: [#1444] http core event listener start in app start. Step 3 --- packages/axum-http-tracker-server/src/server.rs | 1 + packages/http-tracker-core/src/container.rs | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 52085f822..a169e2565 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -302,6 +302,7 @@ mod tests { HttpTrackerCoreContainer { tracker_core_container, http_tracker_config, + http_core_stats_keeper, http_stats_event_sender, http_stats_repository, announce_service, diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 0b8bd9337..c41fac6dc 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -13,6 +13,7 @@ pub struct HttpTrackerCoreContainer { pub tracker_core_container: Arc, // `HttpTrackerCoreServices` + pub http_core_stats_keeper: Arc, pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, pub announce_service: Arc, @@ -44,6 +45,7 @@ impl HttpTrackerCoreContainer { Arc::new(Self { tracker_core_container: tracker_core_container.clone(), http_tracker_config: http_tracker_config.clone(), + http_core_stats_keeper: http_tracker_core_services.http_core_stats_keeper.clone(), http_stats_event_sender: http_tracker_core_services.http_stats_event_sender.clone(), http_stats_repository: http_tracker_core_services.http_stats_repository.clone(), announce_service: http_tracker_core_services.http_announce_service.clone(), @@ -53,6 +55,7 @@ impl HttpTrackerCoreContainer { } pub struct HttpTrackerCoreServices { + pub http_core_stats_keeper: Arc, pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, pub http_announce_service: Arc, @@ -89,6 +92,7 @@ impl HttpTrackerCoreServices { )); Arc::new(Self { + http_core_stats_keeper, http_stats_event_sender, http_stats_repository, http_announce_service, From 6d49a1308384812563cd165879237e89ee3e5528 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 24 Apr 2025 16:11:34 +0100 Subject: [PATCH 0986/1297] refactor: [#1444] rename fields --- .../axum-http-tracker-server/src/server.rs | 6 ++-- .../tests/server/v1/contract.rs | 35 +++---------------- packages/http-tracker-core/src/container.rs | 12 +++---- .../rest-tracker-api-core/src/container.rs | 2 +- 4 files changed, 15 insertions(+), 40 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index a169e2565..bf694de79 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -302,9 +302,9 @@ mod tests { HttpTrackerCoreContainer { tracker_core_container, http_tracker_config, - http_core_stats_keeper, - http_stats_event_sender, - http_stats_repository, + stats_keeper: http_core_stats_keeper, + stats_event_sender: http_stats_event_sender, + stats_repository: http_stats_repository, announce_service, scrape_service, } diff --git a/packages/axum-http-tracker-server/tests/server/v1/contract.rs b/packages/axum-http-tracker-server/tests/server/v1/contract.rs index ad5b5a482..37d96052f 100644 --- a/packages/axum-http-tracker-server/tests/server/v1/contract.rs +++ b/packages/axum-http-tracker-server/tests/server/v1/contract.rs @@ -676,12 +676,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env - .container - .http_tracker_core_container - .http_stats_repository - .get_stats() - .await; + let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; assert_eq!(stats.tcp4_announces_handled, 1); @@ -707,12 +702,7 @@ mod for_all_config_modes { .announce(&QueryBuilder::default().query()) .await; - let stats = env - .container - .http_tracker_core_container - .http_stats_repository - .get_stats() - .await; + let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; assert_eq!(stats.tcp6_announces_handled, 1); @@ -737,12 +727,7 @@ mod for_all_config_modes { ) .await; - let stats = env - .container - .http_tracker_core_container - .http_stats_repository - .get_stats() - .await; + let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; assert_eq!(stats.tcp6_announces_handled, 0); @@ -1130,12 +1115,7 @@ mod for_all_config_modes { ) .await; - let stats = env - .container - .http_tracker_core_container - .http_stats_repository - .get_stats() - .await; + let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; assert_eq!(stats.tcp4_scrapes_handled, 1); @@ -1167,12 +1147,7 @@ mod for_all_config_modes { ) .await; - let stats = env - .container - .http_tracker_core_container - .http_stats_repository - .get_stats() - .await; + let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; assert_eq!(stats.tcp6_scrapes_handled, 1); diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index c41fac6dc..0fcf6338c 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -13,9 +13,9 @@ pub struct HttpTrackerCoreContainer { pub tracker_core_container: Arc, // `HttpTrackerCoreServices` - pub http_core_stats_keeper: Arc, - pub http_stats_event_sender: Arc>>, - pub http_stats_repository: Arc, + pub stats_keeper: Arc, + pub stats_event_sender: Arc>>, + pub stats_repository: Arc, pub announce_service: Arc, pub scrape_service: Arc, } @@ -45,9 +45,9 @@ impl HttpTrackerCoreContainer { Arc::new(Self { tracker_core_container: tracker_core_container.clone(), http_tracker_config: http_tracker_config.clone(), - http_core_stats_keeper: http_tracker_core_services.http_core_stats_keeper.clone(), - http_stats_event_sender: http_tracker_core_services.http_stats_event_sender.clone(), - http_stats_repository: http_tracker_core_services.http_stats_repository.clone(), + stats_keeper: http_tracker_core_services.http_core_stats_keeper.clone(), + stats_event_sender: http_tracker_core_services.http_stats_event_sender.clone(), + stats_repository: http_tracker_core_services.http_stats_repository.clone(), announce_service: http_tracker_core_services.http_announce_service.clone(), scrape_service: http_tracker_core_services.http_scrape_service.clone(), }) diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs index 329c77eed..4451eb2c4 100644 --- a/packages/rest-tracker-api-core/src/container.rs +++ b/packages/rest-tracker-api-core/src/container.rs @@ -53,7 +53,7 @@ impl TrackerHttpApiCoreContainer { Arc::new(TrackerHttpApiCoreContainer { tracker_core_container: tracker_core_container.clone(), - http_stats_repository: http_tracker_core_container.http_stats_repository.clone(), + http_stats_repository: http_tracker_core_container.stats_repository.clone(), ban_service: udp_tracker_core_container.ban_service.clone(), udp_core_stats_repository: udp_tracker_core_container.udp_core_stats_repository.clone(), From 19bb37d980601a2b7ca1e135734cd2f764a880c0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 24 Apr 2025 16:14:19 +0100 Subject: [PATCH 0987/1297] refactor: [#1444] renaem variables --- packages/axum-http-tracker-server/src/server.rs | 10 +++++----- .../src/v1/handlers/announce.rs | 9 ++++----- .../src/v1/handlers/scrape.rs | 9 ++++----- packages/http-tracker-core/benches/helpers/util.rs | 8 ++++---- packages/http-tracker-core/src/container.rs | 14 +++++++------- .../http-tracker-core/src/services/announce.rs | 8 ++++---- packages/http-tracker-core/src/services/scrape.rs | 12 ++++++------ .../http-tracker-core/src/statistics/services.rs | 8 ++++---- packages/http-tracker-core/src/statistics/setup.rs | 14 +++++++------- .../src/statistics/services.rs | 9 ++++----- 10 files changed, 49 insertions(+), 52 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index bf694de79..95a13ab1c 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -271,15 +271,15 @@ mod tests { let http_tracker_config = Arc::new(http_tracker_config.clone()); // HTTP core stats - let http_core_stats_keeper = + let http_stats_keeper = bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); - let http_stats_event_sender = http_core_stats_keeper.sender(); - let http_stats_repository = http_core_stats_keeper.repository(); + let http_stats_event_sender = http_stats_keeper.sender(); + let http_stats_repository = http_stats_keeper.repository(); if configuration.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = http_core_stats_keeper.run_event_listener(); + let _unused = http_stats_keeper.run_event_listener(); } let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); @@ -302,7 +302,7 @@ mod tests { HttpTrackerCoreContainer { tracker_core_container, http_tracker_config, - stats_keeper: http_core_stats_keeper, + stats_keeper: http_stats_keeper, stats_event_sender: http_stats_event_sender, stats_repository: http_stats_repository, announce_service, diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 5c08e97eb..b4c54ce09 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -161,15 +161,14 @@ mod tests { )); // HTTP core stats - let http_core_stats_keeper = - bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_event_sender = http_core_stats_keeper.sender(); - let _http_stats_repository = http_core_stats_keeper.repository(); + let http_stats_keeper = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = http_stats_keeper.sender(); + let _http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = http_core_stats_keeper.run_event_listener(); + let _unused = http_stats_keeper.run_event_listener(); } let announce_service = Arc::new(AnnounceService::new( diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index 76390ea0d..e4ba6ed51 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -132,15 +132,14 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); // HTTP core stats - let http_core_stats_keeper = - bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_event_sender = http_core_stats_keeper.sender(); - let _http_stats_repository = http_core_stats_keeper.repository(); + let http_stats_keeper = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = http_stats_keeper.sender(); + let _http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = http_core_stats_keeper.run_event_listener(); + let _unused = http_stats_keeper.run_event_listener(); } ( diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 3ef1ccf46..fc8969c10 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -56,14 +56,14 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( )); // HTTP core stats - let http_core_stats_keeper = statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_event_sender = http_core_stats_keeper.sender(); - let _http_stats_repository = http_core_stats_keeper.repository(); + let http_stats_keeper = statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = http_stats_keeper.sender(); + let _http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = http_core_stats_keeper.run_event_listener(); + let _unused = http_stats_keeper.run_event_listener(); } ( diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 0fcf6338c..381d1f770 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -45,7 +45,7 @@ impl HttpTrackerCoreContainer { Arc::new(Self { tracker_core_container: tracker_core_container.clone(), http_tracker_config: http_tracker_config.clone(), - stats_keeper: http_tracker_core_services.http_core_stats_keeper.clone(), + stats_keeper: http_tracker_core_services.http_stats_keeper.clone(), stats_event_sender: http_tracker_core_services.http_stats_event_sender.clone(), stats_repository: http_tracker_core_services.http_stats_repository.clone(), announce_service: http_tracker_core_services.http_announce_service.clone(), @@ -55,7 +55,7 @@ impl HttpTrackerCoreContainer { } pub struct HttpTrackerCoreServices { - pub http_core_stats_keeper: Arc, + pub http_stats_keeper: Arc, pub http_stats_event_sender: Arc>>, pub http_stats_repository: Arc, pub http_announce_service: Arc, @@ -66,14 +66,14 @@ impl HttpTrackerCoreServices { #[must_use] pub fn initialize_from(tracker_core_container: &Arc) -> Arc { // HTTP core stats - let http_core_stats_keeper = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); - let http_stats_event_sender = http_core_stats_keeper.sender(); - let http_stats_repository = http_core_stats_keeper.repository(); + let http_stats_keeper = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); + let http_stats_event_sender = http_stats_keeper.sender(); + let http_stats_repository = http_stats_keeper.repository(); if tracker_core_container.core_config.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = http_core_stats_keeper.run_event_listener(); + let _unused = http_stats_keeper.run_event_listener(); } let http_announce_service = Arc::new(AnnounceService::new( @@ -92,7 +92,7 @@ impl HttpTrackerCoreServices { )); Arc::new(Self { - http_core_stats_keeper, + http_stats_keeper, http_stats_event_sender, http_stats_repository, http_announce_service, diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 5e50ebd8f..07d576aca 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -253,14 +253,14 @@ mod tests { )); // HTTP core stats - let http_core_stats_keeper = statistics::setup::factory(config.core.tracker_usage_statistics); - let http_stats_event_sender = http_core_stats_keeper.sender(); - let _http_stats_repository = http_core_stats_keeper.repository(); + let http_stats_keeper = statistics::setup::factory(config.core.tracker_usage_statistics); + let http_stats_event_sender = http_stats_keeper.sender(); + let _http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = http_core_stats_keeper.run_event_listener(); + let _unused = http_stats_keeper.run_event_listener(); } ( diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 7cd1a5991..23f1566b3 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -273,9 +273,9 @@ mod tests { let core_config = Arc::new(configuration.core.clone()); // HTTP core stats - let http_core_stats_keeper = statistics::setup::factory(false); - let http_stats_event_sender = http_core_stats_keeper.sender(); - let _http_stats_repository = http_core_stats_keeper.repository(); + let http_stats_keeper = statistics::setup::factory(false); + let http_stats_event_sender = http_stats_keeper.sender(); + let _http_stats_repository = http_stats_keeper.repository(); let container = initialize_services_with_configuration(&configuration); @@ -465,9 +465,9 @@ mod tests { let container = initialize_services_with_configuration(&config); // HTTP core stats - let http_core_stats_keeper = statistics::setup::factory(false); - let http_stats_event_sender = http_core_stats_keeper.sender(); - let _http_stats_repository = http_core_stats_keeper.repository(); + let http_stats_keeper = statistics::setup::factory(false); + let http_stats_event_sender = http_stats_keeper.sender(); + let _http_stats_repository = http_stats_keeper.repository(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 94ade2e45..4a27b3267 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -89,14 +89,14 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); // HTTP core stats - let http_core_stats_keeper = statistics::setup::factory(config.core.tracker_usage_statistics); - let _http_stats_event_sender = http_core_stats_keeper.sender(); - let http_stats_repository = http_core_stats_keeper.repository(); + let http_stats_keeper = statistics::setup::factory(config.core.tracker_usage_statistics); + let _http_stats_event_sender = http_stats_keeper.sender(); + let http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = http_core_stats_keeper.run_event_listener(); + let _unused = http_stats_keeper.run_event_listener(); } let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), http_stats_repository).await; diff --git a/packages/http-tracker-core/src/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs index a78c53f6d..bac9303a6 100644 --- a/packages/http-tracker-core/src/statistics/setup.rs +++ b/packages/http-tracker-core/src/statistics/setup.rs @@ -40,14 +40,14 @@ mod test { let tracker_usage_statistics = false; // HTTP core stats - let http_core_stats_keeper = factory(tracker_usage_statistics); - let http_stats_event_sender = http_core_stats_keeper.sender(); - let _http_stats_repository = http_core_stats_keeper.repository(); + let http_stats_keeper = factory(tracker_usage_statistics); + let http_stats_event_sender = http_stats_keeper.sender(); + let _http_stats_repository = http_stats_keeper.repository(); if tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = http_core_stats_keeper.run_event_listener(); + let _unused = http_stats_keeper.run_event_listener(); } assert!(http_stats_event_sender.is_none()); @@ -58,9 +58,9 @@ mod test { let tracker_usage_statistics = true; // HTTP core stats - let http_core_stats_keeper = factory(tracker_usage_statistics); - let http_stats_event_sender = http_core_stats_keeper.sender(); - let _http_stats_repository = http_core_stats_keeper.repository(); + let http_stats_keeper = factory(tracker_usage_statistics); + let http_stats_event_sender = http_stats_keeper.sender(); + let _http_stats_repository = http_stats_keeper.repository(); assert!(http_stats_event_sender.is_some()); } diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 93c8951f7..93bbc7e1c 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -147,15 +147,14 @@ mod tests { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); // HTTP core stats - let http_core_stats_keeper = - bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); - let _http_stats_event_sender = http_core_stats_keeper.sender(); - let http_stats_repository = http_core_stats_keeper.repository(); + let http_stats_keeper = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let _http_stats_event_sender = http_stats_keeper.sender(); + let http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { // todo: this should be started like the other jobs during `app::start` // and keep the join handle in a list of jobs. - let _unused = http_core_stats_keeper.run_event_listener(); + let _unused = http_stats_keeper.run_event_listener(); } // UDP core stats From 2d9af45fca91845af1446c8719f8f38626784d21 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 24 Apr 2025 16:16:49 +0100 Subject: [PATCH 0988/1297] chore: [#1444] event listener has to be run manually on tests We are moving the execution of the event listener from AppContainer initialization to jobs start. However, in tests we still have to run it manually if we need it. --- packages/axum-http-tracker-server/src/server.rs | 2 -- packages/axum-http-tracker-server/src/v1/handlers/announce.rs | 2 -- packages/axum-http-tracker-server/src/v1/handlers/scrape.rs | 2 -- packages/http-tracker-core/benches/helpers/util.rs | 2 -- packages/http-tracker-core/src/services/announce.rs | 2 -- packages/http-tracker-core/src/statistics/services.rs | 2 -- packages/http-tracker-core/src/statistics/setup.rs | 2 -- packages/rest-tracker-api-core/src/statistics/services.rs | 2 -- 8 files changed, 16 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 95a13ab1c..3d7adfaf2 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -277,8 +277,6 @@ mod tests { let http_stats_repository = http_stats_keeper.repository(); if configuration.core.tracker_usage_statistics { - // todo: this should be started like the other jobs during `app::start` - // and keep the join handle in a list of jobs. let _unused = http_stats_keeper.run_event_listener(); } diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index b4c54ce09..ddeff3ea4 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -166,8 +166,6 @@ mod tests { let _http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { - // todo: this should be started like the other jobs during `app::start` - // and keep the join handle in a list of jobs. let _unused = http_stats_keeper.run_event_listener(); } diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index e4ba6ed51..67c75d6ed 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -137,8 +137,6 @@ mod tests { let _http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { - // todo: this should be started like the other jobs during `app::start` - // and keep the join handle in a list of jobs. let _unused = http_stats_keeper.run_event_listener(); } diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index fc8969c10..6bfbcffd6 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -61,8 +61,6 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( let _http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { - // todo: this should be started like the other jobs during `app::start` - // and keep the join handle in a list of jobs. let _unused = http_stats_keeper.run_event_listener(); } diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 07d576aca..c4c94474f 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -258,8 +258,6 @@ mod tests { let _http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { - // todo: this should be started like the other jobs during `app::start` - // and keep the join handle in a list of jobs. let _unused = http_stats_keeper.run_event_listener(); } diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 4a27b3267..7e4f03492 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -94,8 +94,6 @@ mod tests { let http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { - // todo: this should be started like the other jobs during `app::start` - // and keep the join handle in a list of jobs. let _unused = http_stats_keeper.run_event_listener(); } diff --git a/packages/http-tracker-core/src/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs index bac9303a6..f1f907b2e 100644 --- a/packages/http-tracker-core/src/statistics/setup.rs +++ b/packages/http-tracker-core/src/statistics/setup.rs @@ -45,8 +45,6 @@ mod test { let _http_stats_repository = http_stats_keeper.repository(); if tracker_usage_statistics { - // todo: this should be started like the other jobs during `app::start` - // and keep the join handle in a list of jobs. let _unused = http_stats_keeper.run_event_listener(); } diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 93bbc7e1c..a299ccbaa 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -152,8 +152,6 @@ mod tests { let http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { - // todo: this should be started like the other jobs during `app::start` - // and keep the join handle in a list of jobs. let _unused = http_stats_keeper.run_event_listener(); } From 07c58580e421ae3f32b32462d197db6732eb4ed6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 24 Apr 2025 16:51:06 +0100 Subject: [PATCH 0989/1297] refactor: [#1444] http core event listener start in app start. Step 4 --- .../src/environment.rs | 37 ++++++++++++++++--- packages/http-tracker-core/src/container.rs | 6 --- .../http-tracker-core/src/statistics/setup.rs | 12 ------ src/app.rs | 21 +++++++++++ 4 files changed, 52 insertions(+), 24 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index a89d9af08..30755b452 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -4,6 +4,7 @@ use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::container::TrackerCoreContainer; use futures::executor::block_on; +use tokio::task::JoinHandle; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; @@ -17,6 +18,7 @@ pub struct Environment { pub container: Arc, pub registar: Registar, pub server: HttpServer, + pub event_listener_job: Option>, } impl Environment { @@ -54,22 +56,32 @@ impl Environment { container, registar: Registar::default(), server, + event_listener_job: None, } } + /// Starts the test environment and return a running environment. + /// /// # Panics /// /// Will panic if the server fails to start. #[allow(dead_code)] pub async fn start(self) -> Environment { + // Start the event listener + let event_listener_job = self.container.http_tracker_core_container.stats_keeper.run_event_listener(); + + // Start the server + let server = self + .server + .start(self.container.http_tracker_core_container.clone(), self.registar.give_form()) + .await + .unwrap(); + Environment { container: self.container.clone(), registar: self.registar.clone(), - server: self - .server - .start(self.container.http_tracker_core_container.clone(), self.registar.give_form()) - .await - .unwrap(), + server, + event_listener_job: Some(event_listener_job), } } } @@ -79,14 +91,27 @@ impl Environment { Environment::::new(configuration).start().await } + /// Stops the test environment and return a stopped environment. + /// /// # Panics /// /// Will panic if the server fails to stop. pub async fn stop(self) -> Environment { + // Stop the event listener + if let Some(event_listener_job) = self.event_listener_job { + // todo: send a message to the event listener to stop and wait for + // it to finish + event_listener_job.abort(); + } + + // Stop the server + let server = self.server.stop().await.expect("Failed to stop the http tracker server"); + Environment { container: self.container, registar: Registar::default(), - server: self.server.stop().await.unwrap(), + server, + event_listener_job: None, } } diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 381d1f770..e685dd521 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -70,12 +70,6 @@ impl HttpTrackerCoreServices { let http_stats_event_sender = http_stats_keeper.sender(); let http_stats_repository = http_stats_keeper.repository(); - if tracker_core_container.core_config.tracker_usage_statistics { - // todo: this should be started like the other jobs during `app::start` - // and keep the join handle in a list of jobs. - let _unused = http_stats_keeper.run_event_listener(); - } - let http_announce_service = Arc::new(AnnounceService::new( tracker_core_container.core_config.clone(), tracker_core_container.announce_handler.clone(), diff --git a/packages/http-tracker-core/src/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs index f1f907b2e..09f077507 100644 --- a/packages/http-tracker-core/src/statistics/setup.rs +++ b/packages/http-tracker-core/src/statistics/setup.rs @@ -7,18 +7,6 @@ use super::keeper::Keeper; use super::repository::Repository; use crate::event::sender::Broadcaster; -/// It builds the structs needed for handling the tracker metrics. -/// -/// It returns: -/// -/// - An event [`Sender`](crate::event::sender::Sender) that allows you to send -/// events related to statistics. -/// - An statistics [`Repository`](crate::statistics::repository::Repository) -/// which is an in-memory repository for the tracker metrics. -/// -/// When the input argument `tracker_usage_statistics`is false the setup does -/// not run the event listeners, consequently the statistics events are sent are -/// received but not dispatched to the handler. #[must_use] pub fn factory(tracker_usage_statistics: bool) -> Arc { keeper_factory(tracker_usage_statistics) diff --git a/src/app.rs b/src/app.rs index d394fe644..555900315 100644 --- a/src/app.rs +++ b/src/app.rs @@ -66,6 +66,7 @@ async fn load_data_from_database(config: &Configuration, app_container: &Arc) -> Vec> { let mut jobs: Vec> = Vec::new(); + start_http_core_event_listener(config, app_container); start_the_udp_instances(config, app_container, &mut jobs).await; start_the_http_instances(config, app_container, &mut jobs).await; start_the_http_api(config, app_container, &mut jobs).await; @@ -106,6 +107,26 @@ async fn load_whitelisted_torrents(config: &Configuration, app_container: &Arc) { + if config.core.tracker_usage_statistics { + let _job = app_container + .http_tracker_core_services + .http_stats_keeper + .run_event_listener(); + + // todo: this cannot be enabled otherwise the application never ends + // because the event listener never stops. You see this console message + // forever: + // + // !! shuting down in 90 seconds !! + // 2025-04-24T15:27:45.454101Z INFO graceful_shutdown: torrust_axum_server::signals: remaining alive connections: 0 + // + // Depends on: https://github.com/torrust/torrust-tracker/issues/1405 + + //jobs.push(job); + } +} + async fn start_the_udp_instances(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { if let Some(udp_trackers) = &config.udp_trackers { for udp_tracker_config in udp_trackers { From 2fa4e15d7e44859e9da51ab77305ca6d73f1ddd8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 11:24:53 +0100 Subject: [PATCH 0990/1297] refactor: [#1444] udp core event listener start in app start --- .../src/environment.rs | 4 +- .../src/statistics/services.rs | 4 +- .../udp-tracker-core/benches/helpers/sync.rs | 4 +- packages/udp-tracker-core/src/container.rs | 11 ++-- packages/udp-tracker-core/src/event/sender.rs | 1 + .../udp-tracker-core/src/services/connect.rs | 12 ++-- .../src/statistics/event/listener.rs | 4 +- .../udp-tracker-core/src/statistics/keeper.rs | 50 ++++++++++++---- .../src/statistics/services.rs | 5 +- .../udp-tracker-core/src/statistics/setup.rs | 59 +++++++++---------- .../udp-tracker-server/src/environment.rs | 51 +++++++++++----- .../src/handlers/announce.rs | 9 +-- .../src/handlers/connect.rs | 15 ++--- .../udp-tracker-server/src/handlers/mod.rs | 5 +- src/app.rs | 18 ++++++ 15 files changed, 155 insertions(+), 97 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index 30755b452..f278ad29f 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -75,7 +75,7 @@ impl Environment { .server .start(self.container.http_tracker_core_container.clone(), self.registar.give_form()) .await - .unwrap(); + .expect("Failed to start the HTTP tracker server"); Environment { container: self.container.clone(), @@ -105,7 +105,7 @@ impl Environment { } // Stop the server - let server = self.server.stop().await.expect("Failed to stop the http tracker server"); + let server = self.server.stop().await.expect("Failed to stop the HTTP tracker server"); Environment { container: self.container, diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index a299ccbaa..093971b34 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -155,9 +155,7 @@ mod tests { let _unused = http_stats_keeper.run_event_listener(); } - // UDP core stats - let (_udp_stats_event_sender, _udp_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + // UDP core stats (not used in this test) // UDP server stats let (_udp_server_stats_event_sender, udp_server_stats_repository) = diff --git a/packages/udp-tracker-core/benches/helpers/sync.rs b/packages/udp-tracker-core/benches/helpers/sync.rs index b61204586..926916d61 100644 --- a/packages/udp-tracker-core/benches/helpers/sync.rs +++ b/packages/udp-tracker-core/benches/helpers/sync.rs @@ -14,8 +14,8 @@ pub async fn connect_once(samples: u64) -> Duration { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let keeper = statistics::setup::factory(false); + let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); let start = Instant::now(); diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index 79ce15d01..0a1bf54d4 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -16,6 +16,7 @@ pub struct UdpTrackerCoreContainer { pub tracker_core_container: Arc, // `UdpTrackerCoreServices` + pub stats_keeper: Arc, pub udp_core_stats_event_sender: Arc>>, pub udp_core_stats_repository: Arc, pub ban_service: Arc>, @@ -52,6 +53,7 @@ impl UdpTrackerCoreContainer { tracker_core_container: tracker_core_container.clone(), // `UdpTrackerCoreServices` + stats_keeper: udp_tracker_core_services.stats_keeper.clone(), udp_core_stats_event_sender: udp_tracker_core_services.udp_core_stats_event_sender.clone(), udp_core_stats_repository: udp_tracker_core_services.udp_core_stats_repository.clone(), ban_service: udp_tracker_core_services.udp_ban_service.clone(), @@ -63,6 +65,7 @@ impl UdpTrackerCoreContainer { } pub struct UdpTrackerCoreServices { + pub stats_keeper: Arc, pub udp_core_stats_event_sender: Arc>>, pub udp_core_stats_repository: Arc, pub udp_ban_service: Arc>, @@ -74,10 +77,9 @@ pub struct UdpTrackerCoreServices { impl UdpTrackerCoreServices { #[must_use] pub fn initialize_from(tracker_core_container: &Arc) -> Arc { - let (udp_core_stats_event_sender, udp_core_stats_repository) = - statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); - let udp_core_stats_repository = Arc::new(udp_core_stats_repository); + let keeper = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); + let udp_core_stats_event_sender = keeper.sender(); + let udp_core_stats_repository = keeper.repository(); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender.clone())); let announce_service = Arc::new(AnnounceService::new( @@ -91,6 +93,7 @@ impl UdpTrackerCoreServices { )); Arc::new(Self { + stats_keeper: keeper, udp_core_stats_event_sender, udp_core_stats_repository, udp_ban_service: ban_service, diff --git a/packages/udp-tracker-core/src/event/sender.rs b/packages/udp-tracker-core/src/event/sender.rs index 511a381d0..b720926bb 100644 --- a/packages/udp-tracker-core/src/event/sender.rs +++ b/packages/udp-tracker-core/src/event/sender.rs @@ -16,6 +16,7 @@ pub trait Sender: Sync + Send { } /// An event sender implementation using a broadcast channel. +#[derive(Clone)] pub struct Broadcaster { pub(crate) sender: broadcast::Sender, } diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index df3db6c4b..c6c1c098f 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -78,8 +78,8 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let keeper = statistics::setup::factory(false); + let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -98,8 +98,8 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let keeper = statistics::setup::factory(false); + let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -119,8 +119,8 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (udp_core_stats_event_sender, _udp_core_stats_repository) = statistics::setup::factory(false); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let keeper = statistics::setup::factory(false); + let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); diff --git a/packages/udp-tracker-core/src/statistics/event/listener.rs b/packages/udp-tracker-core/src/statistics/event/listener.rs index 888fb8204..835283d1e 100644 --- a/packages/udp-tracker-core/src/statistics/event/listener.rs +++ b/packages/udp-tracker-core/src/statistics/event/listener.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use tokio::sync::broadcast; use torrust_tracker_clock::clock::Time; @@ -6,7 +8,7 @@ use crate::event::Event; use crate::statistics::repository::Repository; use crate::{CurrentClock, UDP_TRACKER_LOG_TARGET}; -pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { +pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Arc) { loop { match receiver.recv().await { Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, diff --git a/packages/udp-tracker-core/src/statistics/keeper.rs b/packages/udp-tracker-core/src/statistics/keeper.rs index d72dcb260..8acecc585 100644 --- a/packages/udp-tracker-core/src/statistics/keeper.rs +++ b/packages/udp-tracker-core/src/statistics/keeper.rs @@ -1,8 +1,10 @@ -use tokio::sync::broadcast::Receiver; +use std::sync::Arc; + +use tokio::task::JoinHandle; use super::event::listener::dispatch_events; use super::repository::Repository; -use crate::event::Event; +use crate::event::sender::{self, Broadcaster}; use crate::UDP_TRACKER_LOG_TARGET; /// The service responsible for keeping tracker metrics (listening to statistics events and handle them). @@ -10,44 +12,70 @@ use crate::UDP_TRACKER_LOG_TARGET; /// It actively listen to new statistics events. When it receives a new event /// it accordingly increases the counters. pub struct Keeper { - pub repository: Repository, + pub enable_sender: bool, + pub broadcaster: Broadcaster, + pub repository: Arc, } impl Default for Keeper { fn default() -> Self { - Self::new() + let enable_sender = true; + let broadcaster = Broadcaster::default(); + let repository = Arc::new(Repository::new()); + + Self::new(enable_sender, broadcaster, repository) } } impl Keeper { + /// Creates a new instance of [`Keeper`]. #[must_use] - pub fn new() -> Self { + pub fn new(enable_sender: bool, broadcaster: Broadcaster, repository: Arc) -> Self { Self { - repository: Repository::new(), + enable_sender, + broadcaster, + repository, + } + } + + #[must_use] + pub fn sender(&self) -> Arc>> { + if self.enable_sender { + Arc::new(Some(Box::new(self.broadcaster.clone()))) + } else { + Arc::new(None) } } - pub fn run_event_listener(&mut self, receiver: Receiver) { + #[must_use] + pub fn repository(&self) -> Arc { + self.repository.clone() + } + + #[must_use] + pub fn run_event_listener(&self) -> JoinHandle<()> { let stats_repository = self.repository.clone(); + let receiver = self.broadcaster.subscribe(); - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker core event listener"); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting HTTP tracker core event listener"); tokio::spawn(async move { dispatch_events(receiver, stats_repository).await; - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker core event listener finished"); - }); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "HTTP tracker core event listener finished"); + }) } } #[cfg(test)] mod tests { + use crate::statistics::keeper::Keeper; use crate::statistics::metrics::Metrics; #[tokio::test] async fn should_contain_the_tracker_statistics() { - let stats_tracker = Keeper::new(); + let stats_tracker = Keeper::default(); let stats = stats_tracker.repository.get_stats().await; diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index d9b016b0d..e1aa66f67 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -106,9 +106,8 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let (_udp_core_stats_event_sender, udp_core_stats_repository) = - crate::statistics::setup::factory(config.core.tracker_usage_statistics); - let udp_core_stats_repository = Arc::new(udp_core_stats_repository); + let keeper = crate::statistics::setup::factory(config.core.tracker_usage_statistics); + let udp_core_stats_repository = keeper.repository(); let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), udp_core_stats_repository.clone()).await; diff --git a/packages/udp-tracker-core/src/statistics/setup.rs b/packages/udp-tracker-core/src/statistics/setup.rs index e2974e4c0..6466ac58b 100644 --- a/packages/udp-tracker-core/src/statistics/setup.rs +++ b/packages/udp-tracker-core/src/statistics/setup.rs @@ -1,38 +1,23 @@ //! Setup for the tracker statistics. //! //! The [`factory`] function builds the structs needed for handling the tracker metrics. -use crate::event::sender::Broadcaster; -use crate::{event, statistics}; - -/// It builds the structs needed for handling the tracker metrics. -/// -/// It returns: -/// -/// - An event [`Sender`](crate::event::sender::Sender) that allows you to send -/// events related to statistics. -/// - An statistics [`Repository`](crate::statistics::repository::Repository) -/// which is an in-memory repository for the tracker metrics. -/// -/// When the input argument `tracker_usage_statistics`is false the setup does -/// not run the event listeners, consequently the statistics events are sent are -/// received but not dispatched to the handler. -#[must_use] -pub fn factory(tracker_usage_statistics: bool) -> (Option>, statistics::repository::Repository) { - let mut keeper = statistics::keeper::Keeper::new(); - - let opt_event_sender: Option> = if tracker_usage_statistics { - let broadcaster = Broadcaster::default(); +use std::sync::Arc; - keeper.run_event_listener(broadcaster.subscribe()); - - Some(Box::new(broadcaster)) - } else { - None - }; +use super::keeper::Keeper; +use super::repository::Repository; +use crate::event::sender::Broadcaster; - (opt_event_sender, keeper.repository) +#[must_use] +pub fn factory(tracker_usage_statistics: bool) -> Arc { + keeper_factory(tracker_usage_statistics) } +#[must_use] +pub fn keeper_factory(tracker_usage_statistics: bool) -> Arc { + let broadcaster = Broadcaster::default(); + let repository = Arc::new(Repository::new()); + Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone(), repository.clone())) +} #[cfg(test)] mod test { use super::factory; @@ -41,17 +26,27 @@ mod test { async fn should_not_send_any_event_when_statistics_are_disabled() { let tracker_usage_statistics = false; - let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); + // UDP core stats + let http_stats_keeper = factory(tracker_usage_statistics); + let http_stats_event_sender = http_stats_keeper.sender(); + let _http_stats_repository = http_stats_keeper.repository(); + + if tracker_usage_statistics { + let _unused = http_stats_keeper.run_event_listener(); + } - assert!(stats_event_sender.is_none()); + assert!(http_stats_event_sender.is_none()); } #[tokio::test] async fn should_send_events_when_statistics_are_enabled() { let tracker_usage_statistics = true; - let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); + // UDP core stats + let http_stats_keeper = factory(tracker_usage_statistics); + let http_stats_event_sender = http_stats_keeper.sender(); + let _http_stats_repository = http_stats_keeper.repository(); - assert!(stats_event_sender.is_some()); + assert!(http_stats_event_sender.is_some()); } } diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index b97da90ad..3115d3b0b 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; +use tokio::task::JoinHandle; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_primitives::peer; @@ -22,6 +23,7 @@ where pub container: Arc, pub registar: Registar, pub server: Server, + pub udp_core_event_listener_job: Option>, } impl Environment @@ -55,29 +57,38 @@ impl Environment { container, registar: Registar::default(), server, + udp_core_event_listener_job: None, } } + /// Starts the test environment and return a running environment. + /// /// # Panics /// /// Will panic if it cannot start the server. #[allow(dead_code)] pub async fn start(self) -> Environment { let cookie_lifetime = self.container.udp_tracker_core_container.udp_tracker_config.cookie_lifetime; + // Start the UDP tracker core event listener + let udp_core_event_listener_job = Some(self.container.udp_tracker_core_container.stats_keeper.run_event_listener()); + + // Start the UDP tracker server + let server = self + .server + .start( + self.container.udp_tracker_core_container.clone(), + self.container.udp_tracker_server_container.clone(), + self.registar.give_form(), + cookie_lifetime, + ) + .await + .expect("Failed to start the UDP tracker server"); Environment { container: self.container.clone(), registar: self.registar.clone(), - server: self - .server - .start( - self.container.udp_tracker_core_container.clone(), - self.container.udp_tracker_server_container.clone(), - self.registar.give_form(), - cookie_lifetime, - ) - .await - .unwrap(), + server, + udp_core_event_listener_job, } } } @@ -89,22 +100,34 @@ impl Environment { pub async fn new(configuration: &Arc) -> Self { tokio::time::timeout(DEFAULT_TIMEOUT, Environment::::new(configuration).start()) .await - .expect("it should create an environment within the timeout") + .expect("Failed to create a UDP tracker server running environment within the timeout") } + /// Stops the test environment and return a stopped environment. + /// /// # Panics /// /// Will panic if it cannot stop the service within the timeout. #[allow(dead_code)] pub async fn stop(self) -> Environment { - let stopped = tokio::time::timeout(DEFAULT_TIMEOUT, self.server.stop()) + // Stop the event listener + if let Some(udp_core_event_listener_job) = self.udp_core_event_listener_job { + // todo: send a message to the event listener to stop and wait for + // it to finish + udp_core_event_listener_job.abort(); + } + + // Stop the server + let server = tokio::time::timeout(DEFAULT_TIMEOUT, self.server.stop()) .await - .expect("it should stop the environment within the timeout"); + .expect("Failed to stop the UDP tracker server within the timeout") + .expect("Failed to stop the UDP tracker server"); Environment { container: self.container, registar: Registar::default(), - server: stopped.expect("it should stop the udp tracker service"), + server, + udp_core_event_listener_job: None, } } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 0167553f2..38b42a0b6 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -374,10 +374,6 @@ mod tests { core_tracker_services: Arc, core_udp_tracker_services: Arc, ) -> Response { - let (udp_core_stats_event_sender, _udp_core_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(false); - let _udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); - let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); @@ -710,9 +706,8 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let (udp_core_stats_event_sender, _udp_core_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = keeper.sender(); let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index aef8833b9..9ea36903c 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -81,9 +81,8 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (udp_core_stats_event_sender, _udp_core_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = keeper.sender(); let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); @@ -118,9 +117,8 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (udp_core_stats_event_sender, _udp_core_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = keeper.sender(); let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); @@ -155,9 +153,8 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (udp_core_stats_event_sender, _udp_core_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = keeper.sender(); let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index f8ca9d8ea..bc39f63ae 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -284,9 +284,8 @@ pub(crate) mod tests { )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - let (udp_core_stats_event_sender, _udp_core_stats_repository) = - bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_core_stats_event_sender = Arc::new(udp_core_stats_event_sender); + let keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = keeper.sender(); let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); diff --git a/src/app.rs b/src/app.rs index 555900315..a0f63094b 100644 --- a/src/app.rs +++ b/src/app.rs @@ -67,6 +67,7 @@ async fn start_jobs(config: &Configuration, app_container: &Arc) - let mut jobs: Vec> = Vec::new(); start_http_core_event_listener(config, app_container); + start_udp_core_event_listener(config, app_container); start_the_udp_instances(config, app_container, &mut jobs).await; start_the_http_instances(config, app_container, &mut jobs).await; start_the_http_api(config, app_container, &mut jobs).await; @@ -127,6 +128,23 @@ fn start_http_core_event_listener(config: &Configuration, app_container: &Arc) { + if config.core.tracker_usage_statistics { + let _job = app_container.udp_tracker_core_services.stats_keeper.run_event_listener(); + + // todo: this cannot be enabled otherwise the application never ends + // because the event listener never stops. You see this console message + // forever: + // + // !! shuting down in 90 seconds !! + // 2025-04-24T15:27:45.454101Z INFO graceful_shutdown: torrust_axum_server::signals: remaining alive connections: 0 + // + // Depends on: https://github.com/torrust/torrust-tracker/issues/1405 + + //jobs.push(job); + } +} + async fn start_the_udp_instances(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { if let Some(udp_trackers) = &config.udp_trackers { for udp_tracker_config in udp_trackers { From 74e174d377264bee10b89c258f3917b9074d1215 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 13:10:30 +0100 Subject: [PATCH 0991/1297] refactor: [#1444] udp server event listener start in app start --- .../src/statistics/services.rs | 4 +- packages/udp-tracker-server/src/container.rs | 11 ++-- .../udp-tracker-server/src/environment.rs | 23 ++++++- .../udp-tracker-server/src/event/sender.rs | 1 + .../src/handlers/announce.rs | 12 ++-- .../src/handlers/connect.rs | 24 ++++---- .../udp-tracker-server/src/handlers/mod.rs | 8 +-- .../udp-tracker-server/src/handlers/scrape.rs | 4 +- .../src/statistics/event/listener.rs | 4 +- .../src/statistics/keeper.rs | 52 ++++++++++++---- .../src/statistics/services.rs | 5 +- .../src/statistics/setup.rs | 61 +++++++++---------- src/app.rs | 21 +++++++ 13 files changed, 149 insertions(+), 81 deletions(-) diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 093971b34..95e21633a 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -158,9 +158,9 @@ mod tests { // UDP core stats (not used in this test) // UDP server stats - let (_udp_server_stats_event_sender, udp_server_stats_repository) = + let udp_server_stats_keeper = torrust_udp_tracker_server::statistics::setup::factory(config.core.tracker_usage_statistics); - let udp_server_stats_repository = Arc::new(udp_server_stats_repository); + let udp_server_stats_repository = udp_server_stats_keeper.repository(); let tracker_metrics = get_metrics( in_memory_torrent_repository.clone(), diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs index 2b1ce8c99..89740cf77 100644 --- a/packages/udp-tracker-server/src/container.rs +++ b/packages/udp-tracker-server/src/container.rs @@ -5,6 +5,7 @@ use torrust_tracker_configuration::Core; use crate::{event, statistics}; pub struct UdpTrackerServerContainer { + pub udp_server_stats_keeper: Arc, pub udp_server_stats_event_sender: Arc>>, pub udp_server_stats_repository: Arc, } @@ -15,6 +16,7 @@ impl UdpTrackerServerContainer { let udp_tracker_server_services = UdpTrackerServerServices::initialize(core_config); Arc::new(Self { + udp_server_stats_keeper: udp_tracker_server_services.udp_server_stats_keeper.clone(), udp_server_stats_event_sender: udp_tracker_server_services.udp_server_stats_event_sender.clone(), udp_server_stats_repository: udp_tracker_server_services.udp_server_stats_repository.clone(), }) @@ -22,6 +24,7 @@ impl UdpTrackerServerContainer { } pub struct UdpTrackerServerServices { + pub udp_server_stats_keeper: Arc, pub udp_server_stats_event_sender: Arc>>, pub udp_server_stats_repository: Arc, } @@ -29,12 +32,12 @@ pub struct UdpTrackerServerServices { impl UdpTrackerServerServices { #[must_use] pub fn initialize(core_config: &Arc) -> Arc { - let (udp_server_stats_event_sender, udp_server_stats_repository) = - statistics::setup::factory(core_config.tracker_usage_statistics); - let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); - let udp_server_stats_repository = Arc::new(udp_server_stats_repository); + let udp_server_stats_keeper = statistics::setup::factory(core_config.tracker_usage_statistics); + let udp_server_stats_event_sender = udp_server_stats_keeper.sender(); + let udp_server_stats_repository = udp_server_stats_keeper.repository(); Arc::new(Self { + udp_server_stats_keeper: udp_server_stats_keeper.clone(), udp_server_stats_event_sender: udp_server_stats_event_sender.clone(), udp_server_stats_repository: udp_server_stats_repository.clone(), }) diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 3115d3b0b..2b31e78bd 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -24,6 +24,7 @@ where pub registar: Registar, pub server: Server, pub udp_core_event_listener_job: Option>, + pub udp_server_event_listener_job: Option>, } impl Environment @@ -58,6 +59,7 @@ impl Environment { registar: Registar::default(), server, udp_core_event_listener_job: None, + udp_server_event_listener_job: None, } } @@ -72,6 +74,14 @@ impl Environment { // Start the UDP tracker core event listener let udp_core_event_listener_job = Some(self.container.udp_tracker_core_container.stats_keeper.run_event_listener()); + // Start the UDP tracker server event listener + let udp_server_event_listener_job = Some( + self.container + .udp_tracker_server_container + .udp_server_stats_keeper + .run_event_listener(), + ); + // Start the UDP tracker server let server = self .server @@ -89,6 +99,7 @@ impl Environment { registar: self.registar.clone(), server, udp_core_event_listener_job, + udp_server_event_listener_job, } } } @@ -110,14 +121,21 @@ impl Environment { /// Will panic if it cannot stop the service within the timeout. #[allow(dead_code)] pub async fn stop(self) -> Environment { - // Stop the event listener + // Stop the UDP tracker core event listener if let Some(udp_core_event_listener_job) = self.udp_core_event_listener_job { // todo: send a message to the event listener to stop and wait for // it to finish udp_core_event_listener_job.abort(); } - // Stop the server + // Stop the UDP tracker server event listener + if let Some(udp_server_event_listener_job) = self.udp_server_event_listener_job { + // todo: send a message to the event listener to stop and wait for + // it to finish + udp_server_event_listener_job.abort(); + } + + // Stop the UDP tracker server let server = tokio::time::timeout(DEFAULT_TIMEOUT, self.server.stop()) .await .expect("Failed to stop the UDP tracker server within the timeout") @@ -128,6 +146,7 @@ impl Environment { registar: Registar::default(), server, udp_core_event_listener_job: None, + udp_server_event_listener_job: None, } } diff --git a/packages/udp-tracker-server/src/event/sender.rs b/packages/udp-tracker-server/src/event/sender.rs index 511a381d0..b720926bb 100644 --- a/packages/udp-tracker-server/src/event/sender.rs +++ b/packages/udp-tracker-server/src/event/sender.rs @@ -16,6 +16,7 @@ pub trait Sender: Sync + Send { } /// An event sender implementation using a broadcast channel. +#[derive(Clone)] pub struct Broadcaster { pub(crate) sender: broadcast::Sender, } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 38b42a0b6..9dd7156b1 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -374,8 +374,8 @@ mod tests { core_tracker_services: Arc, core_udp_tracker_services: Arc, ) -> Response { - let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); - let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); + let keeper = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = keeper.sender(); let client_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); @@ -706,11 +706,11 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_core_stats_event_sender = keeper.sender(); + let core_keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = core_keeper.sender(); - let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); - let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); + let server_keeper = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = server_keeper.sender(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 9ea36903c..fb05b3693 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -81,11 +81,11 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_core_stats_event_sender = keeper.sender(); + let core_keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = core_keeper.sender(); - let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); - let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); + let server_keeper = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = server_keeper.sender(); let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), @@ -117,11 +117,11 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_core_stats_event_sender = keeper.sender(); + let core_keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = core_keeper.sender(); - let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); - let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); + let server_keeper = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = server_keeper.sender(); let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), @@ -153,11 +153,11 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_core_stats_event_sender = keeper.sender(); + let core_keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = core_keeper.sender(); - let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); - let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); + let server_keeper = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = server_keeper.sender(); let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index bc39f63ae..0ad593bb2 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -284,11 +284,11 @@ pub(crate) mod tests { )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - let keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); - let udp_core_stats_event_sender = keeper.sender(); + let core_keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_stats_event_sender = core_keeper.sender(); - let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); - let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); + let server_keeper = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = server_keeper.sender(); let announce_service = Arc::new(AnnounceService::new( announce_handler.clone(), diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 35b5ee65c..cef896d73 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -178,8 +178,8 @@ mod tests { core_tracker_services: Arc, core_udp_tracker_services: Arc, ) -> Response { - let (udp_server_stats_event_sender, _udp_server_stats_repository) = crate::statistics::setup::factory(false); - let udp_server_stats_event_sender = Arc::new(udp_server_stats_event_sender); + let keeper = crate::statistics::setup::factory(false); + let udp_server_stats_event_sender = keeper.sender(); let client_socket_addr = sample_ipv4_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index cf348ea17..80c9f8d21 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use tokio::sync::broadcast; use torrust_tracker_clock::clock::Time; @@ -7,7 +9,7 @@ use crate::event::Event; use crate::statistics::repository::Repository; use crate::CurrentClock; -pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Repository) { +pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Arc) { loop { match receiver.recv().await { Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, diff --git a/packages/udp-tracker-server/src/statistics/keeper.rs b/packages/udp-tracker-server/src/statistics/keeper.rs index c200b4cdf..1d525e7b3 100644 --- a/packages/udp-tracker-server/src/statistics/keeper.rs +++ b/packages/udp-tracker-server/src/statistics/keeper.rs @@ -1,56 +1,84 @@ +use std::sync::Arc; + use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; -use tokio::sync::broadcast::Receiver; +use tokio::task::JoinHandle; use super::event::listener::dispatch_events; use super::repository::Repository; -use crate::event::Event; +use crate::event::sender::{self, Broadcaster}; /// The service responsible for keeping tracker metrics (listening to statistics events and handle them). /// /// It actively listen to new statistics events. When it receives a new event /// it accordingly increases the counters. pub struct Keeper { - pub repository: Repository, + pub enable_sender: bool, + pub broadcaster: Broadcaster, + pub repository: Arc, } impl Default for Keeper { fn default() -> Self { - Self::new() + let enable_sender = true; + let broadcaster = Broadcaster::default(); + let repository = Arc::new(Repository::new()); + + Self::new(enable_sender, broadcaster, repository) } } impl Keeper { + /// Creates a new instance of [`Keeper`]. #[must_use] - pub fn new() -> Self { + pub fn new(enable_sender: bool, broadcaster: Broadcaster, repository: Arc) -> Self { Self { - repository: Repository::new(), + enable_sender, + broadcaster, + repository, + } + } + + #[must_use] + pub fn sender(&self) -> Arc>> { + if self.enable_sender { + Arc::new(Some(Box::new(self.broadcaster.clone()))) + } else { + Arc::new(None) } } - pub fn run_event_listener(&mut self, receiver: Receiver) { + #[must_use] + pub fn repository(&self) -> Arc { + self.repository.clone() + } + + #[must_use] + pub fn run_event_listener(&self) -> JoinHandle<()> { let stats_repository = self.repository.clone(); + let receiver = self.broadcaster.subscribe(); - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker server event listener"); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting HTTP tracker core event listener"); tokio::spawn(async move { dispatch_events(receiver, stats_repository).await; - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker core server listener finished"); - }); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "HTTP tracker core event listener finished"); + }) } } #[cfg(test)] mod tests { + use crate::statistics::keeper::Keeper; use crate::statistics::metrics::Metrics; #[tokio::test] async fn should_contain_the_tracker_statistics() { - let stats_tracker = Keeper::new(); + let stats_tracker = Keeper::default(); let stats = stats_tracker.repository.get_stats().await; - assert_eq!(stats.udp4_requests, Metrics::default().udp4_requests); + assert_eq!(stats.udp4_announces_handled, Metrics::default().udp4_announces_handled); } } diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index b84bf4cd0..22f3f4754 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -127,9 +127,8 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let (_udp_server_stats_event_sender, udp_server_stats_repository) = - statistics::setup::factory(config.core.tracker_usage_statistics); - let udp_server_stats_repository = Arc::new(udp_server_stats_repository); + let keeper = statistics::setup::factory(config.core.tracker_usage_statistics); + let udp_server_stats_repository = keeper.repository(); let tracker_metrics = get_metrics( in_memory_torrent_repository.clone(), diff --git a/packages/udp-tracker-server/src/statistics/setup.rs b/packages/udp-tracker-server/src/statistics/setup.rs index d8cc7bca9..09f077507 100644 --- a/packages/udp-tracker-server/src/statistics/setup.rs +++ b/packages/udp-tracker-server/src/statistics/setup.rs @@ -1,37 +1,22 @@ //! Setup for the tracker statistics. //! -//! The [`factory`] function builds the structs needed for handling the tracker -//! metrics. -use crate::event::sender::Broadcaster; -use crate::{event, statistics}; - -/// It builds the structs needed for handling the tracker metrics. -/// -/// It returns: -/// -/// - An event [`Sender`](crate::event::sender::Sender) that allows you to send -/// events related to statistics. -/// - An statistics [`Repository`](crate::statistics::repository::Repository) -/// which is an in-memory repository for the tracker metrics. -/// -/// When the input argument `tracker_usage_statistics`is false the setup does -/// not run the event listeners, consequently the statistics events are sent are -/// received but not dispatched to the handler. -#[must_use] -pub fn factory(tracker_usage_statistics: bool) -> (Option>, statistics::repository::Repository) { - let mut keeper = statistics::keeper::Keeper::new(); +//! The [`factory`] function builds the structs needed for handling the tracker metrics. +use std::sync::Arc; - let opt_event_sender: Option> = if tracker_usage_statistics { - let broadcaster = Broadcaster::default(); - - keeper.run_event_listener(broadcaster.subscribe()); +use super::keeper::Keeper; +use super::repository::Repository; +use crate::event::sender::Broadcaster; - Some(Box::new(broadcaster)) - } else { - None - }; +#[must_use] +pub fn factory(tracker_usage_statistics: bool) -> Arc { + keeper_factory(tracker_usage_statistics) +} - (opt_event_sender, keeper.repository) +#[must_use] +pub fn keeper_factory(tracker_usage_statistics: bool) -> Arc { + let broadcaster = Broadcaster::default(); + let repository = Arc::new(Repository::new()); + Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone(), repository.clone())) } #[cfg(test)] @@ -42,17 +27,27 @@ mod test { async fn should_not_send_any_event_when_statistics_are_disabled() { let tracker_usage_statistics = false; - let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); + // HTTP core stats + let http_stats_keeper = factory(tracker_usage_statistics); + let http_stats_event_sender = http_stats_keeper.sender(); + let _http_stats_repository = http_stats_keeper.repository(); + + if tracker_usage_statistics { + let _unused = http_stats_keeper.run_event_listener(); + } - assert!(stats_event_sender.is_none()); + assert!(http_stats_event_sender.is_none()); } #[tokio::test] async fn should_send_events_when_statistics_are_enabled() { let tracker_usage_statistics = true; - let (stats_event_sender, _stats_repository) = factory(tracker_usage_statistics); + // HTTP core stats + let http_stats_keeper = factory(tracker_usage_statistics); + let http_stats_event_sender = http_stats_keeper.sender(); + let _http_stats_repository = http_stats_keeper.repository(); - assert!(stats_event_sender.is_some()); + assert!(http_stats_event_sender.is_some()); } } diff --git a/src/app.rs b/src/app.rs index a0f63094b..67380d30d 100644 --- a/src/app.rs +++ b/src/app.rs @@ -68,6 +68,7 @@ async fn start_jobs(config: &Configuration, app_container: &Arc) - start_http_core_event_listener(config, app_container); start_udp_core_event_listener(config, app_container); + start_udp_server_event_listener(config, app_container); start_the_udp_instances(config, app_container, &mut jobs).await; start_the_http_instances(config, app_container, &mut jobs).await; start_the_http_api(config, app_container, &mut jobs).await; @@ -145,6 +146,26 @@ fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc) { + if config.core.tracker_usage_statistics { + let _job = app_container + .udp_tracker_server_container + .udp_server_stats_keeper + .run_event_listener(); + + // todo: this cannot be enabled otherwise the application never ends + // because the event listener never stops. You see this console message + // forever: + // + // !! shuting down in 90 seconds !! + // 2025-04-24T15:27:45.454101Z INFO graceful_shutdown: torrust_axum_server::signals: remaining alive connections: 0 + // + // Depends on: https://github.com/torrust/torrust-tracker/issues/1405 + + //jobs.push(job); + } +} + async fn start_the_udp_instances(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { if let Some(udp_trackers) = &config.udp_trackers { for udp_tracker_config in udp_trackers { From 6d50a784239945299c63116fe5434da92fd0dd6e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 13:52:55 +0100 Subject: [PATCH 0992/1297] refactor: normalize container field names --- packages/http-tracker-core/src/container.rs | 30 +++++++------- .../rest-tracker-api-core/src/container.rs | 4 +- packages/udp-tracker-core/src/container.rs | 40 +++++++++---------- packages/udp-tracker-server/src/container.rs | 24 +++++------ .../udp-tracker-server/src/environment.rs | 7 +--- .../udp-tracker-server/src/handlers/mod.rs | 10 ++--- .../udp-tracker-server/src/server/launcher.rs | 11 ++--- .../src/server/processor.rs | 2 +- .../tests/server/contract.rs | 4 +- src/app.rs | 10 +---- src/container.rs | 8 ++-- 11 files changed, 67 insertions(+), 83 deletions(-) diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index e685dd521..496856494 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -45,21 +45,21 @@ impl HttpTrackerCoreContainer { Arc::new(Self { tracker_core_container: tracker_core_container.clone(), http_tracker_config: http_tracker_config.clone(), - stats_keeper: http_tracker_core_services.http_stats_keeper.clone(), - stats_event_sender: http_tracker_core_services.http_stats_event_sender.clone(), - stats_repository: http_tracker_core_services.http_stats_repository.clone(), - announce_service: http_tracker_core_services.http_announce_service.clone(), - scrape_service: http_tracker_core_services.http_scrape_service.clone(), + stats_keeper: http_tracker_core_services.stats_keeper.clone(), + stats_event_sender: http_tracker_core_services.stats_event_sender.clone(), + stats_repository: http_tracker_core_services.stats_repository.clone(), + announce_service: http_tracker_core_services.announce_service.clone(), + scrape_service: http_tracker_core_services.scrape_service.clone(), }) } } pub struct HttpTrackerCoreServices { - pub http_stats_keeper: Arc, - pub http_stats_event_sender: Arc>>, - pub http_stats_repository: Arc, - pub http_announce_service: Arc, - pub http_scrape_service: Arc, + pub stats_keeper: Arc, + pub stats_event_sender: Arc>>, + pub stats_repository: Arc, + pub announce_service: Arc, + pub scrape_service: Arc, } impl HttpTrackerCoreServices { @@ -86,11 +86,11 @@ impl HttpTrackerCoreServices { )); Arc::new(Self { - http_stats_keeper, - http_stats_event_sender, - http_stats_repository, - http_announce_service, - http_scrape_service, + stats_keeper: http_stats_keeper, + stats_event_sender: http_stats_event_sender, + stats_repository: http_stats_repository, + announce_service: http_announce_service, + scrape_service: http_scrape_service, }) } } diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs index 4451eb2c4..ec3786dfb 100644 --- a/packages/rest-tracker-api-core/src/container.rs +++ b/packages/rest-tracker-api-core/src/container.rs @@ -56,9 +56,9 @@ impl TrackerHttpApiCoreContainer { http_stats_repository: http_tracker_core_container.stats_repository.clone(), ban_service: udp_tracker_core_container.ban_service.clone(), - udp_core_stats_repository: udp_tracker_core_container.udp_core_stats_repository.clone(), + udp_core_stats_repository: udp_tracker_core_container.stats_repository.clone(), - udp_server_stats_repository: udp_tracker_server_container.udp_server_stats_repository.clone(), + udp_server_stats_repository: udp_tracker_server_container.stats_repository.clone(), http_api_config: http_api_config.clone(), }) diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index 0a1bf54d4..ef66e9b7e 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -17,8 +17,8 @@ pub struct UdpTrackerCoreContainer { // `UdpTrackerCoreServices` pub stats_keeper: Arc, - pub udp_core_stats_event_sender: Arc>>, - pub udp_core_stats_repository: Arc, + pub stats_event_sender: Arc>>, + pub stats_repository: Arc, pub ban_service: Arc>, pub connect_service: Arc, pub announce_service: Arc, @@ -54,24 +54,24 @@ impl UdpTrackerCoreContainer { // `UdpTrackerCoreServices` stats_keeper: udp_tracker_core_services.stats_keeper.clone(), - udp_core_stats_event_sender: udp_tracker_core_services.udp_core_stats_event_sender.clone(), - udp_core_stats_repository: udp_tracker_core_services.udp_core_stats_repository.clone(), - ban_service: udp_tracker_core_services.udp_ban_service.clone(), - connect_service: udp_tracker_core_services.udp_connect_service.clone(), - announce_service: udp_tracker_core_services.udp_announce_service.clone(), - scrape_service: udp_tracker_core_services.udp_scrape_service.clone(), + stats_event_sender: udp_tracker_core_services.stats_event_sender.clone(), + stats_repository: udp_tracker_core_services.stats_repository.clone(), + ban_service: udp_tracker_core_services.ban_service.clone(), + connect_service: udp_tracker_core_services.connect_service.clone(), + announce_service: udp_tracker_core_services.announce_service.clone(), + scrape_service: udp_tracker_core_services.scrape_service.clone(), }) } } pub struct UdpTrackerCoreServices { pub stats_keeper: Arc, - pub udp_core_stats_event_sender: Arc>>, - pub udp_core_stats_repository: Arc, - pub udp_ban_service: Arc>, - pub udp_connect_service: Arc, - pub udp_announce_service: Arc, - pub udp_scrape_service: Arc, + pub stats_event_sender: Arc>>, + pub stats_repository: Arc, + pub ban_service: Arc>, + pub connect_service: Arc, + pub announce_service: Arc, + pub scrape_service: Arc, } impl UdpTrackerCoreServices { @@ -94,12 +94,12 @@ impl UdpTrackerCoreServices { Arc::new(Self { stats_keeper: keeper, - udp_core_stats_event_sender, - udp_core_stats_repository, - udp_ban_service: ban_service, - udp_connect_service: connect_service, - udp_announce_service: announce_service, - udp_scrape_service: scrape_service, + stats_event_sender: udp_core_stats_event_sender, + stats_repository: udp_core_stats_repository, + ban_service, + connect_service, + announce_service, + scrape_service, }) } } diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs index 89740cf77..64d01e754 100644 --- a/packages/udp-tracker-server/src/container.rs +++ b/packages/udp-tracker-server/src/container.rs @@ -5,9 +5,9 @@ use torrust_tracker_configuration::Core; use crate::{event, statistics}; pub struct UdpTrackerServerContainer { - pub udp_server_stats_keeper: Arc, - pub udp_server_stats_event_sender: Arc>>, - pub udp_server_stats_repository: Arc, + pub stats_keeper: Arc, + pub stats_event_sender: Arc>>, + pub stats_repository: Arc, } impl UdpTrackerServerContainer { @@ -16,17 +16,17 @@ impl UdpTrackerServerContainer { let udp_tracker_server_services = UdpTrackerServerServices::initialize(core_config); Arc::new(Self { - udp_server_stats_keeper: udp_tracker_server_services.udp_server_stats_keeper.clone(), - udp_server_stats_event_sender: udp_tracker_server_services.udp_server_stats_event_sender.clone(), - udp_server_stats_repository: udp_tracker_server_services.udp_server_stats_repository.clone(), + stats_keeper: udp_tracker_server_services.stats_keeper.clone(), + stats_event_sender: udp_tracker_server_services.stats_event_sender.clone(), + stats_repository: udp_tracker_server_services.stats_repository.clone(), }) } } pub struct UdpTrackerServerServices { - pub udp_server_stats_keeper: Arc, - pub udp_server_stats_event_sender: Arc>>, - pub udp_server_stats_repository: Arc, + pub stats_keeper: Arc, + pub stats_event_sender: Arc>>, + pub stats_repository: Arc, } impl UdpTrackerServerServices { @@ -37,9 +37,9 @@ impl UdpTrackerServerServices { let udp_server_stats_repository = udp_server_stats_keeper.repository(); Arc::new(Self { - udp_server_stats_keeper: udp_server_stats_keeper.clone(), - udp_server_stats_event_sender: udp_server_stats_event_sender.clone(), - udp_server_stats_repository: udp_server_stats_repository.clone(), + stats_keeper: udp_server_stats_keeper.clone(), + stats_event_sender: udp_server_stats_event_sender.clone(), + stats_repository: udp_server_stats_repository.clone(), }) } } diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 2b31e78bd..cda8cd678 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -75,12 +75,7 @@ impl Environment { let udp_core_event_listener_job = Some(self.container.udp_tracker_core_container.stats_keeper.run_event_listener()); // Start the UDP tracker server event listener - let udp_server_event_listener_job = Some( - self.container - .udp_tracker_server_container - .udp_server_stats_keeper - .run_event_listener(), - ); + let udp_server_event_listener_job = Some(self.container.udp_tracker_server_container.stats_keeper.run_event_listener()); // Start the UDP tracker server let server = self diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 0ad593bb2..8ef053684 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -98,7 +98,7 @@ pub(crate) async fn handle_packet( udp_request.from, server_service_binding, request_id, - &udp_tracker_server_container.udp_server_stats_event_sender, + &udp_tracker_server_container.stats_event_sender, cookie_time_values.valid_range.clone(), &error, Some(transaction_id), @@ -114,7 +114,7 @@ pub(crate) async fn handle_packet( udp_request.from, server_service_binding, request_id, - &udp_tracker_server_container.udp_server_stats_event_sender, + &udp_tracker_server_container.stats_event_sender, cookie_time_values.valid_range.clone(), &e, None, @@ -161,7 +161,7 @@ pub async fn handle_request( server_service_binding, &connect_request, &udp_tracker_core_container.connect_service, - &udp_tracker_server_container.udp_server_stats_event_sender, + &udp_tracker_server_container.stats_event_sender, cookie_time_values.issue_time, ) .await, @@ -174,7 +174,7 @@ pub async fn handle_request( server_service_binding, &announce_request, &udp_tracker_core_container.tracker_core_container.core_config, - &udp_tracker_server_container.udp_server_stats_event_sender, + &udp_tracker_server_container.stats_event_sender, cookie_time_values.valid_range, ) .await @@ -189,7 +189,7 @@ pub async fn handle_request( client_socket_addr, server_service_binding, &scrape_request, - &udp_tracker_server_container.udp_server_stats_event_sender, + &udp_tracker_server_container.stats_event_sender, cookie_time_values.valid_range, ) .await diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index d62a4d04e..02b9c8d74 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -182,8 +182,7 @@ impl Launcher { let client_socket_addr = req.from; - if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.udp_server_stats_event_sender.as_deref() - { + if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.stats_event_sender.as_deref() { udp_server_stats_event_sender .send_event(Event::UdpRequestReceived { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), @@ -194,9 +193,7 @@ impl Launcher { if udp_tracker_core_container.ban_service.read().await.is_banned(&req.from.ip()) { tracing::debug!(target: UDP_TRACKER_LOG_TARGET, local_addr, "Udp::run_udp_server::loop continue: (banned ip)"); - if let Some(udp_server_stats_event_sender) = - udp_tracker_server_container.udp_server_stats_event_sender.as_deref() - { + if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.stats_event_sender.as_deref() { udp_server_stats_event_sender .send_event(Event::UdpRequestBanned { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), @@ -236,9 +233,7 @@ impl Launcher { if old_request_aborted { // Evicted task from active requests buffer was aborted. - if let Some(udp_server_stats_event_sender) = - udp_tracker_server_container.udp_server_stats_event_sender.as_deref() - { + if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.stats_event_sender.as_deref() { udp_server_stats_event_sender .send_event(Event::UdpRequestAborted { context: ConnectionContext::new(client_socket_addr, server_service_binding), diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs index 5e98b0361..297919bc3 100644 --- a/packages/udp-tracker-server/src/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -115,7 +115,7 @@ impl Processor { } if let Some(udp_server_stats_event_sender) = - self.udp_tracker_server_container.udp_server_stats_event_sender.as_deref() + self.udp_tracker_server_container.stats_event_sender.as_deref() { udp_server_stats_event_sender .send_event(Event::UdpResponseSent { diff --git a/packages/udp-tracker-server/tests/server/contract.rs b/packages/udp-tracker-server/tests/server/contract.rs index 4cb23621d..860fd1f0b 100644 --- a/packages/udp-tracker-server/tests/server/contract.rs +++ b/packages/udp-tracker-server/tests/server/contract.rs @@ -268,7 +268,7 @@ mod receiving_an_announce_request { let udp_requests_banned_before = env .container .udp_tracker_server_container - .udp_server_stats_repository + .stats_repository .get_stats() .await .udp_requests_banned; @@ -284,7 +284,7 @@ mod receiving_an_announce_request { let udp_requests_banned_after = env .container .udp_tracker_server_container - .udp_server_stats_repository + .stats_repository .get_stats() .await .udp_requests_banned; diff --git a/src/app.rs b/src/app.rs index 67380d30d..41d8b67d1 100644 --- a/src/app.rs +++ b/src/app.rs @@ -111,10 +111,7 @@ async fn load_whitelisted_torrents(config: &Configuration, app_container: &Arc) { if config.core.tracker_usage_statistics { - let _job = app_container - .http_tracker_core_services - .http_stats_keeper - .run_event_listener(); + let _job = app_container.http_tracker_core_services.stats_keeper.run_event_listener(); // todo: this cannot be enabled otherwise the application never ends // because the event listener never stops. You see this console message @@ -148,10 +145,7 @@ fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc) { if config.core.tracker_usage_statistics { - let _job = app_container - .udp_tracker_server_container - .udp_server_stats_keeper - .run_event_listener(); + let _job = app_container.udp_tracker_server_container.stats_keeper.run_event_listener(); // todo: this cannot be enabled otherwise the application never ends // because the event listener never stops. You see this console message diff --git a/src/container.rs b/src/container.rs index 537be2605..93f1fb4d7 100644 --- a/src/container.rs +++ b/src/container.rs @@ -130,10 +130,10 @@ impl AppContainer { TrackerHttpApiCoreContainer { tracker_core_container: self.tracker_core_container.clone(), http_api_config: http_api_config.clone(), - ban_service: self.udp_tracker_core_services.udp_ban_service.clone(), - http_stats_repository: self.http_tracker_core_services.http_stats_repository.clone(), - udp_core_stats_repository: self.udp_tracker_core_services.udp_core_stats_repository.clone(), - udp_server_stats_repository: self.udp_tracker_server_container.udp_server_stats_repository.clone(), + ban_service: self.udp_tracker_core_services.ban_service.clone(), + http_stats_repository: self.http_tracker_core_services.stats_repository.clone(), + udp_core_stats_repository: self.udp_tracker_core_services.stats_repository.clone(), + udp_server_stats_repository: self.udp_tracker_server_container.stats_repository.clone(), } .into() } From f25438af244a7601c482e9a78897548927de1bf3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 16:42:16 +0100 Subject: [PATCH 0993/1297] refactor: [#1478] decouple events from stats in http core keeper --- .../src/environment.rs | 6 ++- .../axum-http-tracker-server/src/server.rs | 6 +-- .../src/v1/handlers/announce.rs | 7 +-- .../src/v1/handlers/scrape.rs | 7 +-- .../http-tracker-core/benches/helpers/util.rs | 6 +-- packages/http-tracker-core/src/container.rs | 4 +- .../src/services/announce.rs | 6 +-- .../http-tracker-core/src/services/scrape.rs | 6 +-- .../src/statistics/event/listener.rs | 18 ++++++- .../src/statistics/keeper.rs | 52 +++---------------- .../src/statistics/services.rs | 7 ++- .../http-tracker-core/src/statistics/setup.rs | 17 +++--- .../src/statistics/services.rs | 8 +-- src/app.rs | 6 ++- 14 files changed, 69 insertions(+), 87 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index f278ad29f..ffba790c2 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; +use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::container::TrackerCoreContainer; use futures::executor::block_on; @@ -68,7 +69,10 @@ impl Environment { #[allow(dead_code)] pub async fn start(self) -> Environment { // Start the event listener - let event_listener_job = self.container.http_tracker_core_container.stats_keeper.run_event_listener(); + let event_listener_job = run_event_listener( + self.container.http_tracker_core_container.stats_keeper.receiver(), + &self.container.http_tracker_core_container.stats_repository, + ); // Start the server let server = self diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 3d7adfaf2..f15dc4258 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -250,6 +250,7 @@ mod tests { use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use bittorrent_http_tracker_core::services::announce::AnnounceService; use bittorrent_http_tracker_core::services::scrape::ScrapeService; + use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; use bittorrent_tracker_core::container::TrackerCoreContainer; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; @@ -271,13 +272,12 @@ mod tests { let http_tracker_config = Arc::new(http_tracker_config.clone()); // HTTP core stats - let http_stats_keeper = + let (http_stats_keeper, http_stats_repository) = bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); let http_stats_event_sender = http_stats_keeper.sender(); - let http_stats_repository = http_stats_keeper.repository(); if configuration.core.tracker_usage_statistics { - let _unused = http_stats_keeper.run_event_listener(); + let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); } let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index ddeff3ea4..eb3e21b7e 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -108,6 +108,7 @@ mod tests { use aquatic_udp_protocol::PeerId; use bittorrent_http_tracker_core::services::announce::AnnounceService; + use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -161,12 +162,12 @@ mod tests { )); // HTTP core stats - let http_stats_keeper = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let (http_stats_keeper, http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); let http_stats_event_sender = http_stats_keeper.sender(); - let _http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { - let _unused = http_stats_keeper.run_event_listener(); + let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); } let announce_service = Arc::new(AnnounceService::new( diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index 67c75d6ed..0cd36c7ab 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -83,6 +83,7 @@ mod tests { use std::str::FromStr; use std::sync::Arc; + use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -132,12 +133,12 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); // HTTP core stats - let http_stats_keeper = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let (http_stats_keeper, http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); let http_stats_event_sender = http_stats_keeper.sender(); - let _http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { - let _unused = http_stats_keeper.run_event_listener(); + let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); } ( diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 6bfbcffd6..590d55a15 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_http_tracker_core::event::Event; +use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; use bittorrent_http_tracker_core::{event, statistics}; use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -56,12 +57,11 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( )); // HTTP core stats - let http_stats_keeper = statistics::setup::factory(config.core.tracker_usage_statistics); + let (http_stats_keeper, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let http_stats_event_sender = http_stats_keeper.sender(); - let _http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { - let _unused = http_stats_keeper.run_event_listener(); + let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); } ( diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 496856494..707d2d148 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -66,9 +66,9 @@ impl HttpTrackerCoreServices { #[must_use] pub fn initialize_from(tracker_core_container: &Arc) -> Arc { // HTTP core stats - let http_stats_keeper = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); + let (http_stats_keeper, http_stats_repository) = + statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); let http_stats_event_sender = http_stats_keeper.sender(); - let http_stats_repository = http_stats_keeper.repository(); let http_announce_service = Arc::new(AnnounceService::new( tracker_core_container.core_config.clone(), diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index c4c94474f..17a1e5417 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -253,12 +253,11 @@ mod tests { )); // HTTP core stats - let http_stats_keeper = statistics::setup::factory(config.core.tracker_usage_statistics); + let (http_stats_keeper, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let http_stats_event_sender = http_stats_keeper.sender(); - let _http_stats_repository = http_stats_keeper.repository(); if config.core.tracker_usage_statistics { - let _unused = http_stats_keeper.run_event_listener(); + let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); } ( @@ -298,6 +297,7 @@ mod tests { use tokio::sync::broadcast::error::SendError; use crate::event::Event; + use crate::statistics::event::listener::run_event_listener; use crate::tests::sample_info_hash; use crate::{event, statistics}; diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 23f1566b3..13cf68070 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -273,9 +273,8 @@ mod tests { let core_config = Arc::new(configuration.core.clone()); // HTTP core stats - let http_stats_keeper = statistics::setup::factory(false); + let (http_stats_keeper, _http_stats_repository) = statistics::setup::factory(false); let http_stats_event_sender = http_stats_keeper.sender(); - let _http_stats_repository = http_stats_keeper.repository(); let container = initialize_services_with_configuration(&configuration); @@ -465,9 +464,8 @@ mod tests { let container = initialize_services_with_configuration(&config); // HTTP core stats - let http_stats_keeper = statistics::setup::factory(false); + let (http_stats_keeper, _http_stats_repository) = statistics::setup::factory(false); let http_stats_event_sender = http_stats_keeper.sender(); - let _http_stats_repository = http_stats_keeper.repository(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; diff --git a/packages/http-tracker-core/src/statistics/event/listener.rs b/packages/http-tracker-core/src/statistics/event/listener.rs index 00fce6b77..98711f2f5 100644 --- a/packages/http-tracker-core/src/statistics/event/listener.rs +++ b/packages/http-tracker-core/src/statistics/event/listener.rs @@ -1,6 +1,7 @@ use std::sync::Arc; -use tokio::sync::broadcast; +use tokio::sync::broadcast::{self, Receiver}; +use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; use super::handler::handle_event; @@ -8,7 +9,20 @@ use crate::event::Event; use crate::statistics::repository::Repository; use crate::{CurrentClock, HTTP_TRACKER_LOG_TARGET}; -pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Arc) { +#[must_use] +pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { + let stats_repository = repository.clone(); + + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting HTTP tracker core event listener"); + + tokio::spawn(async move { + dispatch_events(receiver, stats_repository).await; + + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "HTTP tracker core event listener finished"); + }) +} + +async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Arc) { loop { match receiver.recv().await { Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, diff --git a/packages/http-tracker-core/src/statistics/keeper.rs b/packages/http-tracker-core/src/statistics/keeper.rs index 4c0f7c916..9ae0564ce 100644 --- a/packages/http-tracker-core/src/statistics/keeper.rs +++ b/packages/http-tracker-core/src/statistics/keeper.rs @@ -1,40 +1,30 @@ use std::sync::Arc; -use tokio::task::JoinHandle; +use tokio::sync::broadcast::Receiver; -use super::event::listener::dispatch_events; -use super::repository::Repository; use crate::event::sender::{self, Broadcaster}; -use crate::HTTP_TRACKER_LOG_TARGET; +use crate::event::Event; -/// The service responsible for keeping tracker metrics (listening to statistics events and handle them). -/// -/// It actively listen to new statistics events. When it receives a new event -/// it accordingly increases the counters. pub struct Keeper { pub enable_sender: bool, pub broadcaster: Broadcaster, - pub repository: Arc, } impl Default for Keeper { fn default() -> Self { let enable_sender = true; let broadcaster = Broadcaster::default(); - let repository = Arc::new(Repository::new()); - Self::new(enable_sender, broadcaster, repository) + Self::new(enable_sender, broadcaster) } } impl Keeper { - /// Creates a new instance of [`Keeper`]. #[must_use] - pub fn new(enable_sender: bool, broadcaster: Broadcaster, repository: Arc) -> Self { + pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { Self { enable_sender, broadcaster, - repository, } } @@ -48,37 +38,7 @@ impl Keeper { } #[must_use] - pub fn repository(&self) -> Arc { - self.repository.clone() - } - - #[must_use] - pub fn run_event_listener(&self) -> JoinHandle<()> { - let stats_repository = self.repository.clone(); - let receiver = self.broadcaster.subscribe(); - - tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting HTTP tracker core event listener"); - - tokio::spawn(async move { - dispatch_events(receiver, stats_repository).await; - - tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "HTTP tracker core event listener finished"); - }) - } -} - -#[cfg(test)] -mod tests { - - use crate::statistics::keeper::Keeper; - use crate::statistics::metrics::Metrics; - - #[tokio::test] - async fn should_contain_the_tracker_statistics() { - let stats_tracker = Keeper::default(); - - let stats = stats_tracker.repository.get_stats().await; - - assert_eq!(stats.tcp4_announces_handled, Metrics::default().tcp4_announces_handled); + pub fn receiver(&self) -> Receiver { + self.broadcaster.subscribe() } } diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 7e4f03492..58cb57c53 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -75,6 +75,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_tracker_test_helpers::configuration; + use crate::statistics::event::listener::run_event_listener; use crate::statistics::services::{get_metrics, TrackerMetrics}; use crate::statistics::{self, describe_metrics}; @@ -89,12 +90,10 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); // HTTP core stats - let http_stats_keeper = statistics::setup::factory(config.core.tracker_usage_statistics); - let _http_stats_event_sender = http_stats_keeper.sender(); - let http_stats_repository = http_stats_keeper.repository(); + let (http_stats_keeper, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); if config.core.tracker_usage_statistics { - let _unused = http_stats_keeper.run_event_listener(); + let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); } let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), http_stats_repository).await; diff --git a/packages/http-tracker-core/src/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs index 09f077507..f4d7a2827 100644 --- a/packages/http-tracker-core/src/statistics/setup.rs +++ b/packages/http-tracker-core/src/statistics/setup.rs @@ -8,32 +8,34 @@ use super::repository::Repository; use crate::event::sender::Broadcaster; #[must_use] -pub fn factory(tracker_usage_statistics: bool) -> Arc { +pub fn factory(tracker_usage_statistics: bool) -> (Arc, Arc) { keeper_factory(tracker_usage_statistics) } #[must_use] -pub fn keeper_factory(tracker_usage_statistics: bool) -> Arc { +pub fn keeper_factory(tracker_usage_statistics: bool) -> (Arc, Arc) { let broadcaster = Broadcaster::default(); let repository = Arc::new(Repository::new()); - Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone(), repository.clone())) + let keeper = Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone())); + + (keeper, repository) } #[cfg(test)] mod test { use super::factory; + use crate::statistics::event::listener::run_event_listener; #[tokio::test] async fn should_not_send_any_event_when_statistics_are_disabled() { let tracker_usage_statistics = false; // HTTP core stats - let http_stats_keeper = factory(tracker_usage_statistics); + let (http_stats_keeper, http_stats_repository) = factory(tracker_usage_statistics); let http_stats_event_sender = http_stats_keeper.sender(); - let _http_stats_repository = http_stats_keeper.repository(); if tracker_usage_statistics { - let _unused = http_stats_keeper.run_event_listener(); + let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); } assert!(http_stats_event_sender.is_none()); @@ -44,9 +46,8 @@ mod test { let tracker_usage_statistics = true; // HTTP core stats - let http_stats_keeper = factory(tracker_usage_statistics); + let (http_stats_keeper, _http_stats_repository) = factory(tracker_usage_statistics); let http_stats_event_sender = http_stats_keeper.sender(); - let _http_stats_repository = http_stats_keeper.repository(); assert!(http_stats_event_sender.is_some()); } diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 95e21633a..087807557 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -123,6 +123,7 @@ pub async fn get_labeled_metrics( mod tests { use std::sync::Arc; + use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self}; use bittorrent_udp_tracker_core::services::banning::BanService; @@ -147,12 +148,11 @@ mod tests { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); // HTTP core stats - let http_stats_keeper = bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); - let _http_stats_event_sender = http_stats_keeper.sender(); - let http_stats_repository = http_stats_keeper.repository(); + let (http_stats_keeper, http_stats_repository) = + bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); if config.core.tracker_usage_statistics { - let _unused = http_stats_keeper.run_event_listener(); + let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); } // UDP core stats (not used in this test) diff --git a/src/app.rs b/src/app.rs index 41d8b67d1..ddb60425c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -23,6 +23,7 @@ //! - Tracker REST API: the tracker API can be enabled/disabled. use std::sync::Arc; +use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; use tokio::task::JoinHandle; use torrust_tracker_configuration::{Configuration, HttpTracker, UdpTracker}; use tracing::instrument; @@ -111,7 +112,10 @@ async fn load_whitelisted_torrents(config: &Configuration, app_container: &Arc) { if config.core.tracker_usage_statistics { - let _job = app_container.http_tracker_core_services.stats_keeper.run_event_listener(); + let _job = run_event_listener( + app_container.http_tracker_core_services.stats_keeper.receiver(), + &app_container.http_tracker_core_services.stats_repository, + ); // todo: this cannot be enabled otherwise the application never ends // because the event listener never stops. You see this console message From f9f13a454edf4767a8bcd6d03f6e374910929509 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 17:14:48 +0100 Subject: [PATCH 0994/1297] refactor: [#1478] decouple events from stats in udp core keeper --- .../udp-tracker-core/benches/helpers/sync.rs | 2 +- packages/udp-tracker-core/src/container.rs | 4 +- .../udp-tracker-core/src/services/connect.rs | 6 +-- .../src/statistics/event/listener.rs | 18 ++++++- .../udp-tracker-core/src/statistics/keeper.rs | 52 +++---------------- .../src/statistics/services.rs | 5 +- .../udp-tracker-core/src/statistics/setup.rs | 21 ++++---- .../udp-tracker-server/src/environment.rs | 6 ++- .../src/handlers/announce.rs | 2 +- .../src/handlers/connect.rs | 6 +-- .../udp-tracker-server/src/handlers/mod.rs | 2 +- src/app.rs | 8 +-- 12 files changed, 56 insertions(+), 76 deletions(-) diff --git a/packages/udp-tracker-core/benches/helpers/sync.rs b/packages/udp-tracker-core/benches/helpers/sync.rs index 926916d61..25d2b55b8 100644 --- a/packages/udp-tracker-core/benches/helpers/sync.rs +++ b/packages/udp-tracker-core/benches/helpers/sync.rs @@ -14,7 +14,7 @@ pub async fn connect_once(samples: u64) -> Duration { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let keeper = statistics::setup::factory(false); + let (keeper, _repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); let start = Instant::now(); diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index ef66e9b7e..6fe6d2bdf 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -77,9 +77,9 @@ pub struct UdpTrackerCoreServices { impl UdpTrackerCoreServices { #[must_use] pub fn initialize_from(tracker_core_container: &Arc) -> Arc { - let keeper = statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); + let (keeper, udp_core_stats_repository) = + statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); let udp_core_stats_event_sender = keeper.sender(); - let udp_core_stats_repository = keeper.repository(); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender.clone())); let announce_service = Arc::new(AnnounceService::new( diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index c6c1c098f..1626aa8d4 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -78,7 +78,7 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let keeper = statistics::setup::factory(false); + let (keeper, _repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -98,7 +98,7 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let keeper = statistics::setup::factory(false); + let (keeper, _repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -119,7 +119,7 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let keeper = statistics::setup::factory(false); + let (keeper, _repository) = statistics::setup::factory(false); let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); diff --git a/packages/udp-tracker-core/src/statistics/event/listener.rs b/packages/udp-tracker-core/src/statistics/event/listener.rs index 835283d1e..5aa510d04 100644 --- a/packages/udp-tracker-core/src/statistics/event/listener.rs +++ b/packages/udp-tracker-core/src/statistics/event/listener.rs @@ -1,6 +1,7 @@ use std::sync::Arc; -use tokio::sync::broadcast; +use tokio::sync::broadcast::{self, Receiver}; +use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; use super::handler::handle_event; @@ -8,7 +9,20 @@ use crate::event::Event; use crate::statistics::repository::Repository; use crate::{CurrentClock, UDP_TRACKER_LOG_TARGET}; -pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Arc) { +#[must_use] +pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { + let stats_repository = repository.clone(); + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker core event listener"); + + tokio::spawn(async move { + dispatch_events(receiver, stats_repository).await; + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker core event listener finished"); + }) +} + +async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Arc) { loop { match receiver.recv().await { Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, diff --git a/packages/udp-tracker-core/src/statistics/keeper.rs b/packages/udp-tracker-core/src/statistics/keeper.rs index 8acecc585..9ae0564ce 100644 --- a/packages/udp-tracker-core/src/statistics/keeper.rs +++ b/packages/udp-tracker-core/src/statistics/keeper.rs @@ -1,40 +1,30 @@ use std::sync::Arc; -use tokio::task::JoinHandle; +use tokio::sync::broadcast::Receiver; -use super::event::listener::dispatch_events; -use super::repository::Repository; use crate::event::sender::{self, Broadcaster}; -use crate::UDP_TRACKER_LOG_TARGET; +use crate::event::Event; -/// The service responsible for keeping tracker metrics (listening to statistics events and handle them). -/// -/// It actively listen to new statistics events. When it receives a new event -/// it accordingly increases the counters. pub struct Keeper { pub enable_sender: bool, pub broadcaster: Broadcaster, - pub repository: Arc, } impl Default for Keeper { fn default() -> Self { let enable_sender = true; let broadcaster = Broadcaster::default(); - let repository = Arc::new(Repository::new()); - Self::new(enable_sender, broadcaster, repository) + Self::new(enable_sender, broadcaster) } } impl Keeper { - /// Creates a new instance of [`Keeper`]. #[must_use] - pub fn new(enable_sender: bool, broadcaster: Broadcaster, repository: Arc) -> Self { + pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { Self { enable_sender, broadcaster, - repository, } } @@ -48,37 +38,7 @@ impl Keeper { } #[must_use] - pub fn repository(&self) -> Arc { - self.repository.clone() - } - - #[must_use] - pub fn run_event_listener(&self) -> JoinHandle<()> { - let stats_repository = self.repository.clone(); - let receiver = self.broadcaster.subscribe(); - - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting HTTP tracker core event listener"); - - tokio::spawn(async move { - dispatch_events(receiver, stats_repository).await; - - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "HTTP tracker core event listener finished"); - }) - } -} - -#[cfg(test)] -mod tests { - - use crate::statistics::keeper::Keeper; - use crate::statistics::metrics::Metrics; - - #[tokio::test] - async fn should_contain_the_tracker_statistics() { - let stats_tracker = Keeper::default(); - - let stats = stats_tracker.repository.get_stats().await; - - assert_eq!(stats.udp4_announces_handled, Metrics::default().udp4_announces_handled); + pub fn receiver(&self) -> Receiver { + self.broadcaster.subscribe() } } diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index e1aa66f67..aedd78ecd 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -106,10 +106,9 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let keeper = crate::statistics::setup::factory(config.core.tracker_usage_statistics); - let udp_core_stats_repository = keeper.repository(); + let (_keeper, repository) = crate::statistics::setup::factory(config.core.tracker_usage_statistics); - let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), udp_core_stats_repository.clone()).await; + let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), repository.clone()).await; assert_eq!( tracker_metrics, diff --git a/packages/udp-tracker-core/src/statistics/setup.rs b/packages/udp-tracker-core/src/statistics/setup.rs index 6466ac58b..8e07719ed 100644 --- a/packages/udp-tracker-core/src/statistics/setup.rs +++ b/packages/udp-tracker-core/src/statistics/setup.rs @@ -8,31 +8,33 @@ use super::repository::Repository; use crate::event::sender::Broadcaster; #[must_use] -pub fn factory(tracker_usage_statistics: bool) -> Arc { +pub fn factory(tracker_usage_statistics: bool) -> (Arc, Arc) { keeper_factory(tracker_usage_statistics) } #[must_use] -pub fn keeper_factory(tracker_usage_statistics: bool) -> Arc { +pub fn keeper_factory(tracker_usage_statistics: bool) -> (Arc, Arc) { let broadcaster = Broadcaster::default(); let repository = Arc::new(Repository::new()); - Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone(), repository.clone())) + let keeper = Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone())); + + (keeper, repository) } #[cfg(test)] mod test { use super::factory; + use crate::statistics::event::listener::run_event_listener; #[tokio::test] async fn should_not_send_any_event_when_statistics_are_disabled() { let tracker_usage_statistics = false; // UDP core stats - let http_stats_keeper = factory(tracker_usage_statistics); - let http_stats_event_sender = http_stats_keeper.sender(); - let _http_stats_repository = http_stats_keeper.repository(); + let (stats_keeper, stats_repository) = factory(tracker_usage_statistics); + let http_stats_event_sender = stats_keeper.sender(); if tracker_usage_statistics { - let _unused = http_stats_keeper.run_event_listener(); + let _unused = run_event_listener(stats_keeper.receiver(), &stats_repository); } assert!(http_stats_event_sender.is_none()); @@ -43,9 +45,8 @@ mod test { let tracker_usage_statistics = true; // UDP core stats - let http_stats_keeper = factory(tracker_usage_statistics); - let http_stats_event_sender = http_stats_keeper.sender(); - let _http_stats_repository = http_stats_keeper.repository(); + let (stats_keeper, _stats_repository) = factory(tracker_usage_statistics); + let http_stats_event_sender = stats_keeper.sender(); assert!(http_stats_event_sender.is_some()); } diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index cda8cd678..2d3347bf9 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; +use bittorrent_udp_tracker_core::statistics::event::listener::run_event_listener; use tokio::task::JoinHandle; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; @@ -72,7 +73,10 @@ impl Environment { pub async fn start(self) -> Environment { let cookie_lifetime = self.container.udp_tracker_core_container.udp_tracker_config.cookie_lifetime; // Start the UDP tracker core event listener - let udp_core_event_listener_job = Some(self.container.udp_tracker_core_container.stats_keeper.run_event_listener()); + let udp_core_event_listener_job = Some(run_event_listener( + self.container.udp_tracker_core_container.stats_keeper.receiver(), + &self.container.udp_tracker_core_container.stats_repository, + )); // Start the UDP tracker server event listener let udp_server_event_listener_job = Some(self.container.udp_tracker_server_container.stats_keeper.run_event_listener()); diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 9dd7156b1..d4dc66492 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -706,7 +706,7 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let core_keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = core_keeper.sender(); let server_keeper = crate::statistics::setup::factory(false); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index fb05b3693..263d58e17 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -81,7 +81,7 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let core_keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = core_keeper.sender(); let server_keeper = crate::statistics::setup::factory(false); @@ -117,7 +117,7 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let core_keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = core_keeper.sender(); let server_keeper = crate::statistics::setup::factory(false); @@ -153,7 +153,7 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let core_keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = core_keeper.sender(); let server_keeper = crate::statistics::setup::factory(false); diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 8ef053684..fdc014825 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -284,7 +284,7 @@ pub(crate) mod tests { )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - let core_keeper = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = core_keeper.sender(); let server_keeper = crate::statistics::setup::factory(false); diff --git a/src/app.rs b/src/app.rs index ddb60425c..ba1f28a1c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -23,7 +23,6 @@ //! - Tracker REST API: the tracker API can be enabled/disabled. use std::sync::Arc; -use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; use tokio::task::JoinHandle; use torrust_tracker_configuration::{Configuration, HttpTracker, UdpTracker}; use tracing::instrument; @@ -112,7 +111,7 @@ async fn load_whitelisted_torrents(config: &Configuration, app_container: &Arc) { if config.core.tracker_usage_statistics { - let _job = run_event_listener( + let _job = bittorrent_http_tracker_core::statistics::event::listener::run_event_listener( app_container.http_tracker_core_services.stats_keeper.receiver(), &app_container.http_tracker_core_services.stats_repository, ); @@ -132,7 +131,10 @@ fn start_http_core_event_listener(config: &Configuration, app_container: &Arc) { if config.core.tracker_usage_statistics { - let _job = app_container.udp_tracker_core_services.stats_keeper.run_event_listener(); + let _job = bittorrent_udp_tracker_core::statistics::event::listener::run_event_listener( + app_container.udp_tracker_core_services.stats_keeper.receiver(), + &app_container.udp_tracker_core_services.stats_repository, + ); // todo: this cannot be enabled otherwise the application never ends // because the event listener never stops. You see this console message From 5f383572c735d36cef11dfe21474de6f35717eb8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 17:36:15 +0100 Subject: [PATCH 0995/1297] refactor: [#1478] decouple events from stats in udp server keeper --- .../src/statistics/services.rs | 3 +- packages/udp-tracker-server/src/container.rs | 4 +- .../udp-tracker-server/src/environment.rs | 8 +-- .../src/handlers/announce.rs | 4 +- .../src/handlers/connect.rs | 6 +-- .../udp-tracker-server/src/handlers/mod.rs | 2 +- .../udp-tracker-server/src/handlers/scrape.rs | 2 +- .../src/statistics/event/listener.rs | 18 ++++++- .../src/statistics/keeper.rs | 52 +++---------------- .../src/statistics/services.rs | 5 +- .../src/statistics/setup.rs | 25 ++++----- src/app.rs | 5 +- 12 files changed, 56 insertions(+), 78 deletions(-) diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 087807557..176c045d6 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -158,9 +158,8 @@ mod tests { // UDP core stats (not used in this test) // UDP server stats - let udp_server_stats_keeper = + let (_udp_server_stats_keeper, udp_server_stats_repository) = torrust_udp_tracker_server::statistics::setup::factory(config.core.tracker_usage_statistics); - let udp_server_stats_repository = udp_server_stats_keeper.repository(); let tracker_metrics = get_metrics( in_memory_torrent_repository.clone(), diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs index 64d01e754..4898cb57d 100644 --- a/packages/udp-tracker-server/src/container.rs +++ b/packages/udp-tracker-server/src/container.rs @@ -32,9 +32,9 @@ pub struct UdpTrackerServerServices { impl UdpTrackerServerServices { #[must_use] pub fn initialize(core_config: &Arc) -> Arc { - let udp_server_stats_keeper = statistics::setup::factory(core_config.tracker_usage_statistics); + let (udp_server_stats_keeper, udp_server_stats_repository) = + statistics::setup::factory(core_config.tracker_usage_statistics); let udp_server_stats_event_sender = udp_server_stats_keeper.sender(); - let udp_server_stats_repository = udp_server_stats_keeper.repository(); Arc::new(Self { stats_keeper: udp_server_stats_keeper.clone(), diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 2d3347bf9..7d70317aa 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -4,7 +4,6 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; -use bittorrent_udp_tracker_core::statistics::event::listener::run_event_listener; use tokio::task::JoinHandle; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; @@ -73,13 +72,16 @@ impl Environment { pub async fn start(self) -> Environment { let cookie_lifetime = self.container.udp_tracker_core_container.udp_tracker_config.cookie_lifetime; // Start the UDP tracker core event listener - let udp_core_event_listener_job = Some(run_event_listener( + let udp_core_event_listener_job = Some(bittorrent_udp_tracker_core::statistics::event::listener::run_event_listener( self.container.udp_tracker_core_container.stats_keeper.receiver(), &self.container.udp_tracker_core_container.stats_repository, )); // Start the UDP tracker server event listener - let udp_server_event_listener_job = Some(self.container.udp_tracker_server_container.stats_keeper.run_event_listener()); + let udp_server_event_listener_job = Some(crate::statistics::event::listener::run_event_listener( + self.container.udp_tracker_server_container.stats_keeper.receiver(), + &self.container.udp_tracker_server_container.stats_repository, + )); // Start the UDP tracker server let server = self diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index d4dc66492..f12bf3d13 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -374,7 +374,7 @@ mod tests { core_tracker_services: Arc, core_udp_tracker_services: Arc, ) -> Response { - let keeper = crate::statistics::setup::factory(false); + let (keeper, _repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = keeper.sender(); let client_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); @@ -709,7 +709,7 @@ mod tests { let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = core_keeper.sender(); - let server_keeper = crate::statistics::setup::factory(false); + let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = server_keeper.sender(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 263d58e17..264cd426d 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -84,7 +84,7 @@ mod tests { let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = core_keeper.sender(); - let server_keeper = crate::statistics::setup::factory(false); + let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = server_keeper.sender(); let request = ConnectRequest { @@ -120,7 +120,7 @@ mod tests { let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = core_keeper.sender(); - let server_keeper = crate::statistics::setup::factory(false); + let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = server_keeper.sender(); let request = ConnectRequest { @@ -156,7 +156,7 @@ mod tests { let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = core_keeper.sender(); - let server_keeper = crate::statistics::setup::factory(false); + let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = server_keeper.sender(); let request = ConnectRequest { diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index fdc014825..2905b20a9 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -287,7 +287,7 @@ pub(crate) mod tests { let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); let udp_core_stats_event_sender = core_keeper.sender(); - let server_keeper = crate::statistics::setup::factory(false); + let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = server_keeper.sender(); let announce_service = Arc::new(AnnounceService::new( diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index cef896d73..78a01fe6d 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -178,7 +178,7 @@ mod tests { core_tracker_services: Arc, core_udp_tracker_services: Arc, ) -> Response { - let keeper = crate::statistics::setup::factory(false); + let (keeper, _repository) = crate::statistics::setup::factory(false); let udp_server_stats_event_sender = keeper.sender(); let client_socket_addr = sample_ipv4_remote_addr(); diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index 80c9f8d21..8e8cc5195 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -1,7 +1,8 @@ use std::sync::Arc; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; -use tokio::sync::broadcast; +use tokio::sync::broadcast::{self, Receiver}; +use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; use super::handler::handle_event; @@ -9,7 +10,20 @@ use crate::event::Event; use crate::statistics::repository::Repository; use crate::CurrentClock; -pub async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Arc) { +#[must_use] +pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { + let stats_repository = repository.clone(); + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker server event listener"); + + tokio::spawn(async move { + dispatch_events(receiver, stats_repository).await; + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "DP tracker server event listener finished"); + }) +} + +async fn dispatch_events(mut receiver: broadcast::Receiver, stats_repository: Arc) { loop { match receiver.recv().await { Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, diff --git a/packages/udp-tracker-server/src/statistics/keeper.rs b/packages/udp-tracker-server/src/statistics/keeper.rs index 1d525e7b3..9ae0564ce 100644 --- a/packages/udp-tracker-server/src/statistics/keeper.rs +++ b/packages/udp-tracker-server/src/statistics/keeper.rs @@ -1,40 +1,30 @@ use std::sync::Arc; -use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; -use tokio::task::JoinHandle; +use tokio::sync::broadcast::Receiver; -use super::event::listener::dispatch_events; -use super::repository::Repository; use crate::event::sender::{self, Broadcaster}; +use crate::event::Event; -/// The service responsible for keeping tracker metrics (listening to statistics events and handle them). -/// -/// It actively listen to new statistics events. When it receives a new event -/// it accordingly increases the counters. pub struct Keeper { pub enable_sender: bool, pub broadcaster: Broadcaster, - pub repository: Arc, } impl Default for Keeper { fn default() -> Self { let enable_sender = true; let broadcaster = Broadcaster::default(); - let repository = Arc::new(Repository::new()); - Self::new(enable_sender, broadcaster, repository) + Self::new(enable_sender, broadcaster) } } impl Keeper { - /// Creates a new instance of [`Keeper`]. #[must_use] - pub fn new(enable_sender: bool, broadcaster: Broadcaster, repository: Arc) -> Self { + pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { Self { enable_sender, broadcaster, - repository, } } @@ -48,37 +38,7 @@ impl Keeper { } #[must_use] - pub fn repository(&self) -> Arc { - self.repository.clone() - } - - #[must_use] - pub fn run_event_listener(&self) -> JoinHandle<()> { - let stats_repository = self.repository.clone(); - let receiver = self.broadcaster.subscribe(); - - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting HTTP tracker core event listener"); - - tokio::spawn(async move { - dispatch_events(receiver, stats_repository).await; - - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "HTTP tracker core event listener finished"); - }) - } -} - -#[cfg(test)] -mod tests { - - use crate::statistics::keeper::Keeper; - use crate::statistics::metrics::Metrics; - - #[tokio::test] - async fn should_contain_the_tracker_statistics() { - let stats_tracker = Keeper::default(); - - let stats = stats_tracker.repository.get_stats().await; - - assert_eq!(stats.udp4_announces_handled, Metrics::default().udp4_announces_handled); + pub fn receiver(&self) -> Receiver { + self.broadcaster.subscribe() } } diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index 22f3f4754..f8c385535 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -127,13 +127,12 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let keeper = statistics::setup::factory(config.core.tracker_usage_statistics); - let udp_server_stats_repository = keeper.repository(); + let (_keeper, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); let tracker_metrics = get_metrics( in_memory_torrent_repository.clone(), ban_service.clone(), - udp_server_stats_repository.clone(), + stats_repository.clone(), ) .await; diff --git a/packages/udp-tracker-server/src/statistics/setup.rs b/packages/udp-tracker-server/src/statistics/setup.rs index 09f077507..b504ae41d 100644 --- a/packages/udp-tracker-server/src/statistics/setup.rs +++ b/packages/udp-tracker-server/src/statistics/setup.rs @@ -8,35 +8,37 @@ use super::repository::Repository; use crate::event::sender::Broadcaster; #[must_use] -pub fn factory(tracker_usage_statistics: bool) -> Arc { +pub fn factory(tracker_usage_statistics: bool) -> (Arc, Arc) { keeper_factory(tracker_usage_statistics) } #[must_use] -pub fn keeper_factory(tracker_usage_statistics: bool) -> Arc { +pub fn keeper_factory(tracker_usage_statistics: bool) -> (Arc, Arc) { let broadcaster = Broadcaster::default(); let repository = Arc::new(Repository::new()); - Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone(), repository.clone())) + let keeper = Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone())); + + (keeper, repository) } #[cfg(test)] mod test { use super::factory; + use crate::statistics::event::listener::run_event_listener; #[tokio::test] async fn should_not_send_any_event_when_statistics_are_disabled() { let tracker_usage_statistics = false; // HTTP core stats - let http_stats_keeper = factory(tracker_usage_statistics); - let http_stats_event_sender = http_stats_keeper.sender(); - let _http_stats_repository = http_stats_keeper.repository(); + let (stats_keeper, stats_repository) = factory(tracker_usage_statistics); + let stats_event_sender = stats_keeper.sender(); if tracker_usage_statistics { - let _unused = http_stats_keeper.run_event_listener(); + let _unused = run_event_listener(stats_keeper.receiver(), &stats_repository); } - assert!(http_stats_event_sender.is_none()); + assert!(stats_event_sender.is_none()); } #[tokio::test] @@ -44,10 +46,9 @@ mod test { let tracker_usage_statistics = true; // HTTP core stats - let http_stats_keeper = factory(tracker_usage_statistics); - let http_stats_event_sender = http_stats_keeper.sender(); - let _http_stats_repository = http_stats_keeper.repository(); + let (stats_keeper, _stats_repository) = factory(tracker_usage_statistics); + let stats_event_sender = stats_keeper.sender(); - assert!(http_stats_event_sender.is_some()); + assert!(stats_event_sender.is_some()); } } diff --git a/src/app.rs b/src/app.rs index ba1f28a1c..b01dc9c36 100644 --- a/src/app.rs +++ b/src/app.rs @@ -151,7 +151,10 @@ fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc) { if config.core.tracker_usage_statistics { - let _job = app_container.udp_tracker_server_container.stats_keeper.run_event_listener(); + let _job = torrust_udp_tracker_server::statistics::event::listener::run_event_listener( + app_container.udp_tracker_server_container.stats_keeper.receiver(), + &app_container.udp_tracker_server_container.stats_repository, + ); // todo: this cannot be enabled otherwise the application never ends // because the event listener never stops. You see this console message From a055ab9787a5d9b7cf876ff7004c4cf6e3155d33 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 17:41:26 +0100 Subject: [PATCH 0996/1297] refactor: [#1478] inline keeper_factory fn --- packages/http-tracker-core/src/statistics/setup.rs | 5 ----- packages/udp-tracker-core/src/statistics/setup.rs | 6 +----- packages/udp-tracker-server/src/statistics/setup.rs | 5 ----- 3 files changed, 1 insertion(+), 15 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs index f4d7a2827..84f48e09b 100644 --- a/packages/http-tracker-core/src/statistics/setup.rs +++ b/packages/http-tracker-core/src/statistics/setup.rs @@ -9,11 +9,6 @@ use crate::event::sender::Broadcaster; #[must_use] pub fn factory(tracker_usage_statistics: bool) -> (Arc, Arc) { - keeper_factory(tracker_usage_statistics) -} - -#[must_use] -pub fn keeper_factory(tracker_usage_statistics: bool) -> (Arc, Arc) { let broadcaster = Broadcaster::default(); let repository = Arc::new(Repository::new()); let keeper = Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone())); diff --git a/packages/udp-tracker-core/src/statistics/setup.rs b/packages/udp-tracker-core/src/statistics/setup.rs index 8e07719ed..66d7522dc 100644 --- a/packages/udp-tracker-core/src/statistics/setup.rs +++ b/packages/udp-tracker-core/src/statistics/setup.rs @@ -9,17 +9,13 @@ use crate::event::sender::Broadcaster; #[must_use] pub fn factory(tracker_usage_statistics: bool) -> (Arc, Arc) { - keeper_factory(tracker_usage_statistics) -} - -#[must_use] -pub fn keeper_factory(tracker_usage_statistics: bool) -> (Arc, Arc) { let broadcaster = Broadcaster::default(); let repository = Arc::new(Repository::new()); let keeper = Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone())); (keeper, repository) } + #[cfg(test)] mod test { use super::factory; diff --git a/packages/udp-tracker-server/src/statistics/setup.rs b/packages/udp-tracker-server/src/statistics/setup.rs index b504ae41d..2e9881c3d 100644 --- a/packages/udp-tracker-server/src/statistics/setup.rs +++ b/packages/udp-tracker-server/src/statistics/setup.rs @@ -9,11 +9,6 @@ use crate::event::sender::Broadcaster; #[must_use] pub fn factory(tracker_usage_statistics: bool) -> (Arc, Arc) { - keeper_factory(tracker_usage_statistics) -} - -#[must_use] -pub fn keeper_factory(tracker_usage_statistics: bool) -> (Arc, Arc) { let broadcaster = Broadcaster::default(); let repository = Arc::new(Repository::new()); let keeper = Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone())); From cc7ead8863d40bdcf52726ff05752b3ba976b1e6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 18:07:10 +0100 Subject: [PATCH 0997/1297] refactor: [#1478] inline factory fn in http core stats --- .../axum-http-tracker-server/src/server.rs | 12 ++++- .../src/v1/handlers/announce.rs | 12 ++++- .../src/v1/handlers/scrape.rs | 12 ++++- .../http-tracker-core/benches/helpers/util.rs | 13 ++++- packages/http-tracker-core/src/container.rs | 12 ++++- .../src/services/announce.rs | 13 ++++- .../http-tracker-core/src/services/scrape.rs | 16 ++++-- .../http-tracker-core/src/statistics/mod.rs | 1 - .../src/statistics/services.rs | 12 ++++- .../http-tracker-core/src/statistics/setup.rs | 49 ------------------- .../src/statistics/services.rs | 11 ++++- 11 files changed, 93 insertions(+), 70 deletions(-) delete mode 100644 packages/http-tracker-core/src/statistics/setup.rs diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index f15dc4258..8a3b5325a 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -248,9 +248,12 @@ mod tests { use std::sync::Arc; use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; + use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::services::announce::AnnounceService; use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; + use bittorrent_http_tracker_core::statistics::keeper::Keeper; + use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_tracker_core::container::TrackerCoreContainer; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; @@ -272,8 +275,13 @@ mod tests { let http_tracker_config = Arc::new(http_tracker_config.clone()); // HTTP core stats - let (http_stats_keeper, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(configuration.core.tracker_usage_statistics); + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_keeper = Arc::new(Keeper::new( + configuration.core.tracker_usage_statistics, + http_core_broadcaster.clone(), + )); + let http_stats_event_sender = http_stats_keeper.sender(); if configuration.core.tracker_usage_statistics { diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index eb3e21b7e..98cf34259 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -107,8 +107,11 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::PeerId; + use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::services::announce::AnnounceService; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; + use bittorrent_http_tracker_core::statistics::keeper::Keeper; + use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -162,8 +165,13 @@ mod tests { )); // HTTP core stats - let (http_stats_keeper, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_keeper = Arc::new(Keeper::new( + config.core.tracker_usage_statistics, + http_core_broadcaster.clone(), + )); + let http_stats_event_sender = http_stats_keeper.sender(); if config.core.tracker_usage_statistics { diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index 0cd36c7ab..fc88bbde9 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -83,7 +83,10 @@ mod tests { use std::str::FromStr; use std::sync::Arc; + use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; + use bittorrent_http_tracker_core::statistics::keeper::Keeper; + use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -133,8 +136,13 @@ mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); // HTTP core stats - let (http_stats_keeper, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_keeper = Arc::new(Keeper::new( + config.core.tracker_usage_statistics, + http_core_broadcaster.clone(), + )); + let http_stats_event_sender = http_stats_keeper.sender(); if config.core.tracker_usage_statistics { diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 590d55a15..9c45417d4 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -2,9 +2,12 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use bittorrent_http_tracker_core::event; +use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::event::Event; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; -use bittorrent_http_tracker_core::{event, statistics}; +use bittorrent_http_tracker_core::statistics::keeper::Keeper; +use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_primitives::info_hash::InfoHash; @@ -57,7 +60,13 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( )); // HTTP core stats - let (http_stats_keeper, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_keeper = Arc::new(Keeper::new( + config.core.tracker_usage_statistics, + http_core_broadcaster.clone(), + )); + let http_stats_event_sender = http_stats_keeper.sender(); if config.core.tracker_usage_statistics { diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 707d2d148..060e6289a 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -3,8 +3,11 @@ use std::sync::Arc; use bittorrent_tracker_core::container::TrackerCoreContainer; use torrust_tracker_configuration::{Core, HttpTracker}; +use crate::event::sender::Broadcaster; use crate::services::announce::AnnounceService; use crate::services::scrape::ScrapeService; +use crate::statistics::keeper::Keeper; +use crate::statistics::repository::Repository; use crate::{event, services, statistics}; pub struct HttpTrackerCoreContainer { @@ -66,8 +69,13 @@ impl HttpTrackerCoreServices { #[must_use] pub fn initialize_from(tracker_core_container: &Arc) -> Arc { // HTTP core stats - let (http_stats_keeper, http_stats_repository) = - statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_keeper = Arc::new(Keeper::new( + tracker_core_container.core_config.tracker_usage_statistics, + http_core_broadcaster.clone(), + )); + let http_stats_event_sender = http_stats_keeper.sender(); let http_announce_service = Arc::new(AnnounceService::new( diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 17a1e5417..9dc5cc42a 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -253,7 +253,13 @@ mod tests { )); // HTTP core stats - let (http_stats_keeper, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_keeper = Arc::new(Keeper::new( + config.core.tracker_usage_statistics, + http_core_broadcaster.clone(), + )); + let http_stats_event_sender = http_stats_keeper.sender(); if config.core.tracker_usage_statistics { @@ -296,10 +302,13 @@ mod tests { use mockall::mock; use tokio::sync::broadcast::error::SendError; + use crate::event; + use crate::event::sender::Broadcaster; use crate::event::Event; use crate::statistics::event::listener::run_event_listener; + use crate::statistics::keeper::Keeper; + use crate::statistics::repository::Repository; use crate::tests::sample_info_hash; - use crate::{event, statistics}; mock! { HttpStatsEventSender {} diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 13cf68070..c018f2f0b 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -259,13 +259,15 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; + use crate::event; + use crate::event::sender::Broadcaster; use crate::event::{ConnectionContext, Event}; use crate::services::scrape::tests::{ initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::services::scrape::ScrapeService; + use crate::statistics::keeper::Keeper; use crate::tests::sample_info_hash; - use crate::{event, statistics}; #[tokio::test] async fn it_should_return_the_scrape_data_for_a_torrent() { @@ -273,7 +275,9 @@ mod tests { let core_config = Arc::new(configuration.core.clone()); // HTTP core stats - let (http_stats_keeper, _http_stats_repository) = statistics::setup::factory(false); + let http_core_broadcaster = Broadcaster::default(); + let http_stats_keeper = Arc::new(Keeper::new(false, http_core_broadcaster.clone())); + let http_stats_event_sender = http_stats_keeper.sender(); let container = initialize_services_with_configuration(&configuration); @@ -448,13 +452,15 @@ mod tests { use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_test_helpers::configuration; + use crate::event; + use crate::event::sender::Broadcaster; use crate::event::{ConnectionContext, Event}; use crate::services::scrape::tests::{ initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::services::scrape::ScrapeService; + use crate::statistics::keeper::Keeper; use crate::tests::sample_info_hash; - use crate::{event, statistics}; #[tokio::test] async fn it_should_return_the_zeroed_scrape_data_when_the_tracker_is_running_in_private_mode_and_the_peer_is_not_authenticated( @@ -464,7 +470,9 @@ mod tests { let container = initialize_services_with_configuration(&config); // HTTP core stats - let (http_stats_keeper, _http_stats_repository) = statistics::setup::factory(false); + let http_core_broadcaster = Broadcaster::default(); + let http_stats_keeper = Arc::new(Keeper::new(false, http_core_broadcaster.clone())); + let http_stats_event_sender = http_stats_keeper.sender(); let info_hash = sample_info_hash(); diff --git a/packages/http-tracker-core/src/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs index d7a8da402..e91181953 100644 --- a/packages/http-tracker-core/src/statistics/mod.rs +++ b/packages/http-tracker-core/src/statistics/mod.rs @@ -3,7 +3,6 @@ pub mod keeper; pub mod metrics; pub mod repository; pub mod services; -pub mod setup; use metrics::Metrics; use torrust_tracker_metrics::metric::description::MetricDescription; diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 58cb57c53..19132e713 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -75,9 +75,12 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_tracker_test_helpers::configuration; + use crate::event::sender::Broadcaster; + use crate::statistics::describe_metrics; use crate::statistics::event::listener::run_event_listener; + use crate::statistics::keeper::Keeper; + use crate::statistics::repository::Repository; use crate::statistics::services::{get_metrics, TrackerMetrics}; - use crate::statistics::{self, describe_metrics}; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -90,7 +93,12 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); // HTTP core stats - let (http_stats_keeper, http_stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_keeper = Arc::new(Keeper::new( + config.core.tracker_usage_statistics, + http_core_broadcaster.clone(), + )); if config.core.tracker_usage_statistics { let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); diff --git a/packages/http-tracker-core/src/statistics/setup.rs b/packages/http-tracker-core/src/statistics/setup.rs deleted file mode 100644 index 84f48e09b..000000000 --- a/packages/http-tracker-core/src/statistics/setup.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Setup for the tracker statistics. -//! -//! The [`factory`] function builds the structs needed for handling the tracker metrics. -use std::sync::Arc; - -use super::keeper::Keeper; -use super::repository::Repository; -use crate::event::sender::Broadcaster; - -#[must_use] -pub fn factory(tracker_usage_statistics: bool) -> (Arc, Arc) { - let broadcaster = Broadcaster::default(); - let repository = Arc::new(Repository::new()); - let keeper = Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone())); - - (keeper, repository) -} - -#[cfg(test)] -mod test { - use super::factory; - use crate::statistics::event::listener::run_event_listener; - - #[tokio::test] - async fn should_not_send_any_event_when_statistics_are_disabled() { - let tracker_usage_statistics = false; - - // HTTP core stats - let (http_stats_keeper, http_stats_repository) = factory(tracker_usage_statistics); - let http_stats_event_sender = http_stats_keeper.sender(); - - if tracker_usage_statistics { - let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); - } - - assert!(http_stats_event_sender.is_none()); - } - - #[tokio::test] - async fn should_send_events_when_statistics_are_enabled() { - let tracker_usage_statistics = true; - - // HTTP core stats - let (http_stats_keeper, _http_stats_repository) = factory(tracker_usage_statistics); - let http_stats_event_sender = http_stats_keeper.sender(); - - assert!(http_stats_event_sender.is_some()); - } -} diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 176c045d6..552bda627 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -123,7 +123,10 @@ pub async fn get_labeled_metrics( mod tests { use std::sync::Arc; + use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; + use bittorrent_http_tracker_core::statistics::keeper::Keeper; + use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self}; use bittorrent_udp_tracker_core::services::banning::BanService; @@ -148,8 +151,12 @@ mod tests { let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); // HTTP core stats - let (http_stats_keeper, http_stats_repository) = - bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics); + let http_core_broadcaster = Broadcaster::default(); + let http_stats_repository = Arc::new(Repository::new()); + let http_stats_keeper = Arc::new(Keeper::new( + config.core.tracker_usage_statistics, + http_core_broadcaster.clone(), + )); if config.core.tracker_usage_statistics { let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); From 8e8b1dd6189937ad153c7419cf5481a45ab6cb07 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 18:20:59 +0100 Subject: [PATCH 0998/1297] refactor: [#1478] inline factory fn in udp core stats --- .../udp-tracker-core/benches/helpers/sync.rs | 7 ++- packages/udp-tracker-core/src/container.rs | 12 ++++- .../udp-tracker-core/src/services/connect.rs | 13 +++-- .../udp-tracker-core/src/statistics/mod.rs | 1 - .../src/statistics/services.rs | 10 +++- .../udp-tracker-core/src/statistics/setup.rs | 49 ------------------- .../src/handlers/announce.rs | 5 +- .../src/handlers/connect.rs | 12 +++-- .../udp-tracker-server/src/handlers/mod.rs | 7 ++- 9 files changed, 52 insertions(+), 64 deletions(-) delete mode 100644 packages/udp-tracker-core/src/statistics/setup.rs diff --git a/packages/udp-tracker-core/benches/helpers/sync.rs b/packages/udp-tracker-core/benches/helpers/sync.rs index 25d2b55b8..a64bb0bdf 100644 --- a/packages/udp-tracker-core/benches/helpers/sync.rs +++ b/packages/udp-tracker-core/benches/helpers/sync.rs @@ -2,8 +2,9 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use std::time::{Duration, Instant}; +use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::connect::ConnectService; -use bittorrent_udp_tracker_core::statistics; +use bittorrent_udp_tracker_core::statistics::keeper::Keeper; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::helpers::utils::{sample_ipv4_remote_addr, sample_issue_time}; @@ -14,7 +15,9 @@ pub async fn connect_once(samples: u64) -> Duration { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (keeper, _repository) = statistics::setup::factory(false); + let udp_core_broadcaster = Broadcaster::default(); + let keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); let start = Instant::now(); diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index 6fe6d2bdf..34d48a7eb 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -4,10 +4,13 @@ use bittorrent_tracker_core::container::TrackerCoreContainer; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, UdpTracker}; +use crate::event::sender::Broadcaster; use crate::services::announce::AnnounceService; use crate::services::banning::BanService; use crate::services::connect::ConnectService; use crate::services::scrape::ScrapeService; +use crate::statistics::keeper::Keeper; +use crate::statistics::repository::Repository; use crate::{event, services, statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; pub struct UdpTrackerCoreContainer { @@ -77,8 +80,13 @@ pub struct UdpTrackerCoreServices { impl UdpTrackerCoreServices { #[must_use] pub fn initialize_from(tracker_core_container: &Arc) -> Arc { - let (keeper, udp_core_stats_repository) = - statistics::setup::factory(tracker_core_container.core_config.tracker_usage_statistics); + let udp_core_broadcaster = Broadcaster::default(); + let udp_core_stats_repository = Arc::new(Repository::new()); + let keeper = Arc::new(Keeper::new( + tracker_core_container.core_config.tracker_usage_statistics, + udp_core_broadcaster.clone(), + )); + let udp_core_stats_event_sender = keeper.sender(); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender.clone())); diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index 1626aa8d4..2073ad943 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -65,20 +65,23 @@ mod tests { use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::connection_cookie::make; + use crate::event; + use crate::event::sender::Broadcaster; use crate::event::{ConnectionContext, Event}; use crate::services::connect::ConnectService; use crate::services::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpCoreStatsEventSender, }; - use crate::{event, statistics}; + use crate::statistics::keeper::Keeper; #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (keeper, _repository) = statistics::setup::factory(false); + let udp_core_broadcaster = Broadcaster::default(); + let keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -98,7 +101,8 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (keeper, _repository) = statistics::setup::factory(false); + let udp_core_broadcaster = Broadcaster::default(); + let keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -119,7 +123,8 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (keeper, _repository) = statistics::setup::factory(false); + let udp_core_broadcaster = Broadcaster::default(); + let keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); diff --git a/packages/udp-tracker-core/src/statistics/mod.rs b/packages/udp-tracker-core/src/statistics/mod.rs index ec37deae7..ba0b24530 100644 --- a/packages/udp-tracker-core/src/statistics/mod.rs +++ b/packages/udp-tracker-core/src/statistics/mod.rs @@ -3,7 +3,6 @@ pub mod keeper; pub mod metrics; pub mod repository; pub mod services; -pub mod setup; use metrics::Metrics; use torrust_tracker_metrics::metric::description::MetricDescription; diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index aedd78ecd..cace8d8ba 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -93,7 +93,10 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_tracker_test_helpers::configuration; + use crate::event::sender::Broadcaster; use crate::statistics::describe_metrics; + use crate::statistics::keeper::Keeper; + use crate::statistics::repository::Repository; use crate::statistics::services::{get_metrics, TrackerMetrics}; pub fn tracker_configuration() -> Configuration { @@ -106,7 +109,12 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let (_keeper, repository) = crate::statistics::setup::factory(config.core.tracker_usage_statistics); + let udp_core_broadcaster = Broadcaster::default(); + let repository = Arc::new(Repository::new()); + let _keeper = Arc::new(Keeper::new( + config.core.tracker_usage_statistics, + udp_core_broadcaster.clone(), + )); let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), repository.clone()).await; diff --git a/packages/udp-tracker-core/src/statistics/setup.rs b/packages/udp-tracker-core/src/statistics/setup.rs deleted file mode 100644 index 66d7522dc..000000000 --- a/packages/udp-tracker-core/src/statistics/setup.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Setup for the tracker statistics. -//! -//! The [`factory`] function builds the structs needed for handling the tracker metrics. -use std::sync::Arc; - -use super::keeper::Keeper; -use super::repository::Repository; -use crate::event::sender::Broadcaster; - -#[must_use] -pub fn factory(tracker_usage_statistics: bool) -> (Arc, Arc) { - let broadcaster = Broadcaster::default(); - let repository = Arc::new(Repository::new()); - let keeper = Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone())); - - (keeper, repository) -} - -#[cfg(test)] -mod test { - use super::factory; - use crate::statistics::event::listener::run_event_listener; - - #[tokio::test] - async fn should_not_send_any_event_when_statistics_are_disabled() { - let tracker_usage_statistics = false; - - // UDP core stats - let (stats_keeper, stats_repository) = factory(tracker_usage_statistics); - let http_stats_event_sender = stats_keeper.sender(); - - if tracker_usage_statistics { - let _unused = run_event_listener(stats_keeper.receiver(), &stats_repository); - } - - assert!(http_stats_event_sender.is_none()); - } - - #[tokio::test] - async fn should_send_events_when_statistics_are_enabled() { - let tracker_usage_statistics = true; - - // UDP core stats - let (stats_keeper, _stats_repository) = factory(tracker_usage_statistics); - let http_stats_event_sender = stats_keeper.sender(); - - assert!(http_stats_event_sender.is_some()); - } -} diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index f12bf3d13..6345d39ab 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -531,7 +531,9 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::announce::AnnounceService; + use bittorrent_udp_tracker_core::statistics::keeper::Keeper; use mockall::predicate::eq; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -706,7 +708,8 @@ mod tests { announce_handler: Arc, whitelist_authorization: Arc, ) -> Response { - let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_broadcaster = Broadcaster::default(); + let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 264cd426d..c31e89cff 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -59,7 +59,9 @@ mod tests { use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; use bittorrent_udp_tracker_core::connection_cookie::make; use bittorrent_udp_tracker_core::event as core_event; + use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::connect::ConnectService; + use bittorrent_udp_tracker_core::statistics::keeper::Keeper; use mockall::predicate::eq; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -81,7 +83,8 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_broadcaster = Broadcaster::default(); + let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); @@ -117,7 +120,8 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_broadcaster = Broadcaster::default(); + let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); @@ -153,7 +157,9 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); - let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_broadcaster = Broadcaster::default(); + let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = core_keeper.sender(); let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 2905b20a9..18078f987 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -218,8 +218,10 @@ pub(crate) mod tests { use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::gen_remote_fingerprint; + use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::announce::AnnounceService; use bittorrent_udp_tracker_core::services::scrape::ScrapeService; + use bittorrent_udp_tracker_core::statistics::keeper::Keeper; use bittorrent_udp_tracker_core::{self, event as core_event}; use futures::future::BoxFuture; use mockall::mock; @@ -229,6 +231,7 @@ pub(crate) mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; + use crate::statistics::repository::Repository; use crate::{event as server_event, CurrentClock}; pub(crate) struct CoreTrackerServices { @@ -284,7 +287,9 @@ pub(crate) mod tests { )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - let (core_keeper, _core_repository) = bittorrent_udp_tracker_core::statistics::setup::factory(false); + let udp_core_broadcaster = Broadcaster::default(); + let _core_repository = Arc::new(Repository::new()); + let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); From a660be8b0f231b4a0e22897caaf2b3d82ddefd4f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 18:35:18 +0100 Subject: [PATCH 0999/1297] refactor: [#1478] inline factory fn in udp server stats --- .../src/statistics/services.rs | 5 +- packages/udp-tracker-server/src/container.rs | 15 ++++-- .../src/handlers/announce.rs | 8 ++- .../src/handlers/connect.rs | 12 +++-- .../udp-tracker-server/src/handlers/mod.rs | 6 +-- .../udp-tracker-server/src/handlers/scrape.rs | 6 ++- .../udp-tracker-server/src/statistics/mod.rs | 1 - .../src/statistics/services.rs | 12 ++++- .../src/statistics/setup.rs | 49 ------------------- 9 files changed, 46 insertions(+), 68 deletions(-) delete mode 100644 packages/udp-tracker-server/src/statistics/setup.rs diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 552bda627..08997fc63 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -162,11 +162,8 @@ mod tests { let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); } - // UDP core stats (not used in this test) - // UDP server stats - let (_udp_server_stats_keeper, udp_server_stats_repository) = - torrust_udp_tracker_server::statistics::setup::factory(config.core.tracker_usage_statistics); + let udp_server_stats_repository = Arc::new(torrust_udp_tracker_server::statistics::repository::Repository::new()); let tracker_metrics = get_metrics( in_memory_torrent_repository.clone(), diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs index 4898cb57d..3cba43d0e 100644 --- a/packages/udp-tracker-server/src/container.rs +++ b/packages/udp-tracker-server/src/container.rs @@ -2,7 +2,11 @@ use std::sync::Arc; use torrust_tracker_configuration::Core; -use crate::{event, statistics}; +use crate::event::sender::Broadcaster; +use crate::event::{self}; +use crate::statistics; +use crate::statistics::keeper::Keeper; +use crate::statistics::repository::Repository; pub struct UdpTrackerServerContainer { pub stats_keeper: Arc, @@ -32,8 +36,13 @@ pub struct UdpTrackerServerServices { impl UdpTrackerServerServices { #[must_use] pub fn initialize(core_config: &Arc) -> Arc { - let (udp_server_stats_keeper, udp_server_stats_repository) = - statistics::setup::factory(core_config.tracker_usage_statistics); + let udp_server_broadcaster = Broadcaster::default(); + let udp_server_stats_repository = Arc::new(Repository::new()); + let udp_server_stats_keeper = Arc::new(Keeper::new( + core_config.tracker_usage_statistics, + udp_server_broadcaster.clone(), + )); + let udp_server_stats_event_sender = udp_server_stats_keeper.sender(); Arc::new(Self { diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 6345d39ab..3879816c5 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -374,7 +374,9 @@ mod tests { core_tracker_services: Arc, core_udp_tracker_services: Arc, ) -> Response { - let (keeper, _repository) = crate::statistics::setup::factory(false); + let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); + let keeper = Arc::new(crate::statistics::keeper::Keeper::new(false, udp_server_broadcaster.clone())); + let udp_server_stats_event_sender = keeper.sender(); let client_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); @@ -712,7 +714,9 @@ mod tests { let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); - let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); + let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); + let server_keeper = Arc::new(crate::statistics::keeper::Keeper::new(false, udp_server_broadcaster.clone())); + let udp_server_stats_event_sender = server_keeper.sender(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index c31e89cff..6e9c75612 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -87,7 +87,9 @@ mod tests { let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); - let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); + let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); + let server_keeper = Arc::new(crate::statistics::keeper::Keeper::new(false, udp_server_broadcaster.clone())); + let udp_server_stats_event_sender = server_keeper.sender(); let request = ConnectRequest { @@ -124,7 +126,9 @@ mod tests { let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); - let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); + let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); + let server_keeper = Arc::new(crate::statistics::keeper::Keeper::new(false, udp_server_broadcaster.clone())); + let udp_server_stats_event_sender = server_keeper.sender(); let request = ConnectRequest { @@ -162,7 +166,9 @@ mod tests { let udp_core_stats_event_sender = core_keeper.sender(); - let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); + let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); + let server_keeper = Arc::new(crate::statistics::keeper::Keeper::new(false, udp_server_broadcaster.clone())); + let udp_server_stats_event_sender = server_keeper.sender(); let request = ConnectRequest { diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 18078f987..b4845c043 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -231,7 +231,6 @@ pub(crate) mod tests { use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::statistics::repository::Repository; use crate::{event as server_event, CurrentClock}; pub(crate) struct CoreTrackerServices { @@ -288,11 +287,12 @@ pub(crate) mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); let udp_core_broadcaster = Broadcaster::default(); - let _core_repository = Arc::new(Repository::new()); let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); - let (server_keeper, _server_repository) = crate::statistics::setup::factory(false); + let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); + let server_keeper = Arc::new(crate::statistics::keeper::Keeper::new(false, udp_server_broadcaster.clone())); + let udp_server_stats_event_sender = server_keeper.sender(); let announce_service = Arc::new(AnnounceService::new( diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 78a01fe6d..5f85e2dfa 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -94,11 +94,13 @@ mod tests { use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::event::sender::Broadcaster; use crate::handlers::handle_scrape; use crate::handlers::tests::{ initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, sample_issue_time, CoreTrackerServices, CoreUdpTrackerServices, TorrentPeerBuilder, }; + use crate::statistics::keeper::Keeper; fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { TorrentScrapeStatistics { @@ -178,7 +180,9 @@ mod tests { core_tracker_services: Arc, core_udp_tracker_services: Arc, ) -> Response { - let (keeper, _repository) = crate::statistics::setup::factory(false); + let udp_server_broadcaster = Broadcaster::default(); + let keeper = Arc::new(Keeper::new(false, udp_server_broadcaster.clone())); + let udp_server_stats_event_sender = keeper.sender(); let client_socket_addr = sample_ipv4_remote_addr(); diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index 45c696fdb..16b7adbd8 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -3,7 +3,6 @@ pub mod keeper; pub mod metrics; pub mod repository; pub mod services; -pub mod setup; use metrics::Metrics; use torrust_tracker_metrics::metric::description::MetricDescription; diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index f8c385535..1593031c1 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -113,8 +113,11 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_tracker_test_helpers::configuration; + use crate::event::sender::Broadcaster; + use crate::statistics::describe_metrics; + use crate::statistics::keeper::Keeper; + use crate::statistics::repository::Repository; use crate::statistics::services::{get_metrics, TrackerMetrics}; - use crate::statistics::{self, describe_metrics}; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() @@ -127,7 +130,12 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let (_keeper, stats_repository) = statistics::setup::factory(config.core.tracker_usage_statistics); + let udp_server_broadcaster = Broadcaster::default(); + let stats_repository = Arc::new(Repository::new()); + let _keeper = Arc::new(Keeper::new( + config.core.tracker_usage_statistics, + udp_server_broadcaster.clone(), + )); let tracker_metrics = get_metrics( in_memory_torrent_repository.clone(), diff --git a/packages/udp-tracker-server/src/statistics/setup.rs b/packages/udp-tracker-server/src/statistics/setup.rs deleted file mode 100644 index 2e9881c3d..000000000 --- a/packages/udp-tracker-server/src/statistics/setup.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Setup for the tracker statistics. -//! -//! The [`factory`] function builds the structs needed for handling the tracker metrics. -use std::sync::Arc; - -use super::keeper::Keeper; -use super::repository::Repository; -use crate::event::sender::Broadcaster; - -#[must_use] -pub fn factory(tracker_usage_statistics: bool) -> (Arc, Arc) { - let broadcaster = Broadcaster::default(); - let repository = Arc::new(Repository::new()); - let keeper = Arc::new(Keeper::new(tracker_usage_statistics, broadcaster.clone())); - - (keeper, repository) -} - -#[cfg(test)] -mod test { - use super::factory; - use crate::statistics::event::listener::run_event_listener; - - #[tokio::test] - async fn should_not_send_any_event_when_statistics_are_disabled() { - let tracker_usage_statistics = false; - - // HTTP core stats - let (stats_keeper, stats_repository) = factory(tracker_usage_statistics); - let stats_event_sender = stats_keeper.sender(); - - if tracker_usage_statistics { - let _unused = run_event_listener(stats_keeper.receiver(), &stats_repository); - } - - assert!(stats_event_sender.is_none()); - } - - #[tokio::test] - async fn should_send_events_when_statistics_are_enabled() { - let tracker_usage_statistics = true; - - // HTTP core stats - let (stats_keeper, _stats_repository) = factory(tracker_usage_statistics); - let stats_event_sender = stats_keeper.sender(); - - assert!(stats_event_sender.is_some()); - } -} From 8a9314beff884f7b2dd1c2be90dc7464df542b62 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 18:41:24 +0100 Subject: [PATCH 1000/1297] refactor: [#1478] rename Keeper to EventBus --- packages/axum-http-tracker-server/src/server.rs | 4 ++-- .../src/v1/handlers/announce.rs | 4 ++-- .../src/v1/handlers/scrape.rs | 4 ++-- packages/http-tracker-core/benches/helpers/util.rs | 4 ++-- packages/http-tracker-core/src/container.rs | 8 ++++---- .../http-tracker-core/src/services/announce.rs | 4 ++-- packages/http-tracker-core/src/services/scrape.rs | 8 ++++---- .../src/statistics/{keeper.rs => event_bus.rs} | 6 +++--- packages/http-tracker-core/src/statistics/mod.rs | 2 +- .../http-tracker-core/src/statistics/services.rs | 4 ++-- .../src/statistics/services.rs | 4 ++-- packages/udp-tracker-core/benches/helpers/sync.rs | 4 ++-- packages/udp-tracker-core/src/container.rs | 8 ++++---- packages/udp-tracker-core/src/services/connect.rs | 8 ++++---- .../src/statistics/{keeper.rs => event_bus.rs} | 6 +++--- packages/udp-tracker-core/src/statistics/mod.rs | 2 +- .../udp-tracker-core/src/statistics/services.rs | 4 ++-- packages/udp-tracker-server/src/container.rs | 8 ++++---- .../udp-tracker-server/src/handlers/announce.rs | 8 ++++---- .../udp-tracker-server/src/handlers/connect.rs | 14 +++++++------- packages/udp-tracker-server/src/handlers/mod.rs | 9 ++++++--- packages/udp-tracker-server/src/handlers/scrape.rs | 4 ++-- .../src/statistics/{keeper.rs => event_bus.rs} | 6 +++--- packages/udp-tracker-server/src/statistics/mod.rs | 2 +- .../udp-tracker-server/src/statistics/services.rs | 4 ++-- 25 files changed, 71 insertions(+), 68 deletions(-) rename packages/http-tracker-core/src/statistics/{keeper.rs => event_bus.rs} (93%) rename packages/udp-tracker-core/src/statistics/{keeper.rs => event_bus.rs} (93%) rename packages/udp-tracker-server/src/statistics/{keeper.rs => event_bus.rs} (93%) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 8a3b5325a..a2d0bc52c 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -252,7 +252,7 @@ mod tests { use bittorrent_http_tracker_core::services::announce::AnnounceService; use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; - use bittorrent_http_tracker_core::statistics::keeper::Keeper; + use bittorrent_http_tracker_core::statistics::event_bus::EventBus; use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_tracker_core::container::TrackerCoreContainer; use torrust_axum_server::tsl::make_rust_tls; @@ -277,7 +277,7 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(Keeper::new( + let http_stats_keeper = Arc::new(EventBus::new( configuration.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 98cf34259..31c1df471 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -110,7 +110,7 @@ mod tests { use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::services::announce::AnnounceService; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; - use bittorrent_http_tracker_core::statistics::keeper::Keeper; + use bittorrent_http_tracker_core::statistics::event_bus::EventBus; use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; use bittorrent_http_tracker_protocol::v1::responses; @@ -167,7 +167,7 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(Keeper::new( + let http_stats_keeper = Arc::new(EventBus::new( config.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index fc88bbde9..3a026a77c 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -85,7 +85,7 @@ mod tests { use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; - use bittorrent_http_tracker_core::statistics::keeper::Keeper; + use bittorrent_http_tracker_core::statistics::event_bus::EventBus; use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; use bittorrent_http_tracker_protocol::v1::responses; @@ -138,7 +138,7 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(Keeper::new( + let http_stats_keeper = Arc::new(EventBus::new( config.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 9c45417d4..82a00d5b9 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -6,7 +6,7 @@ use bittorrent_http_tracker_core::event; use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::event::Event; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; -use bittorrent_http_tracker_core::statistics::keeper::Keeper; +use bittorrent_http_tracker_core::statistics::event_bus::EventBus; use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; @@ -62,7 +62,7 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(Keeper::new( + let http_stats_keeper = Arc::new(EventBus::new( config.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 060e6289a..3cf344755 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -6,7 +6,7 @@ use torrust_tracker_configuration::{Core, HttpTracker}; use crate::event::sender::Broadcaster; use crate::services::announce::AnnounceService; use crate::services::scrape::ScrapeService; -use crate::statistics::keeper::Keeper; +use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; use crate::{event, services, statistics}; @@ -16,7 +16,7 @@ pub struct HttpTrackerCoreContainer { pub tracker_core_container: Arc, // `HttpTrackerCoreServices` - pub stats_keeper: Arc, + pub stats_keeper: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub announce_service: Arc, @@ -58,7 +58,7 @@ impl HttpTrackerCoreContainer { } pub struct HttpTrackerCoreServices { - pub stats_keeper: Arc, + pub stats_keeper: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub announce_service: Arc, @@ -71,7 +71,7 @@ impl HttpTrackerCoreServices { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(Keeper::new( + let http_stats_keeper = Arc::new(EventBus::new( tracker_core_container.core_config.tracker_usage_statistics, http_core_broadcaster.clone(), )); diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 9dc5cc42a..a1e69d2cc 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -255,7 +255,7 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(Keeper::new( + let http_stats_keeper = Arc::new(EventBus::new( config.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); @@ -306,7 +306,7 @@ mod tests { use crate::event::sender::Broadcaster; use crate::event::Event; use crate::statistics::event::listener::run_event_listener; - use crate::statistics::keeper::Keeper; + use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; use crate::tests::sample_info_hash; diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index c018f2f0b..2b5f74c83 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -266,7 +266,7 @@ mod tests { initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::services::scrape::ScrapeService; - use crate::statistics::keeper::Keeper; + use crate::statistics::event_bus::EventBus; use crate::tests::sample_info_hash; #[tokio::test] @@ -276,7 +276,7 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); - let http_stats_keeper = Arc::new(Keeper::new(false, http_core_broadcaster.clone())); + let http_stats_keeper = Arc::new(EventBus::new(false, http_core_broadcaster.clone())); let http_stats_event_sender = http_stats_keeper.sender(); @@ -459,7 +459,7 @@ mod tests { initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::services::scrape::ScrapeService; - use crate::statistics::keeper::Keeper; + use crate::statistics::event_bus::EventBus; use crate::tests::sample_info_hash; #[tokio::test] @@ -471,7 +471,7 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); - let http_stats_keeper = Arc::new(Keeper::new(false, http_core_broadcaster.clone())); + let http_stats_keeper = Arc::new(EventBus::new(false, http_core_broadcaster.clone())); let http_stats_event_sender = http_stats_keeper.sender(); diff --git a/packages/http-tracker-core/src/statistics/keeper.rs b/packages/http-tracker-core/src/statistics/event_bus.rs similarity index 93% rename from packages/http-tracker-core/src/statistics/keeper.rs rename to packages/http-tracker-core/src/statistics/event_bus.rs index 9ae0564ce..2d22c0a90 100644 --- a/packages/http-tracker-core/src/statistics/keeper.rs +++ b/packages/http-tracker-core/src/statistics/event_bus.rs @@ -5,12 +5,12 @@ use tokio::sync::broadcast::Receiver; use crate::event::sender::{self, Broadcaster}; use crate::event::Event; -pub struct Keeper { +pub struct EventBus { pub enable_sender: bool, pub broadcaster: Broadcaster, } -impl Default for Keeper { +impl Default for EventBus { fn default() -> Self { let enable_sender = true; let broadcaster = Broadcaster::default(); @@ -19,7 +19,7 @@ impl Default for Keeper { } } -impl Keeper { +impl EventBus { #[must_use] pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { Self { diff --git a/packages/http-tracker-core/src/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs index e91181953..da2f0acd4 100644 --- a/packages/http-tracker-core/src/statistics/mod.rs +++ b/packages/http-tracker-core/src/statistics/mod.rs @@ -1,5 +1,5 @@ pub mod event; -pub mod keeper; +pub mod event_bus; pub mod metrics; pub mod repository; pub mod services; diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 19132e713..c695f6d4f 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -78,7 +78,7 @@ mod tests { use crate::event::sender::Broadcaster; use crate::statistics::describe_metrics; use crate::statistics::event::listener::run_event_listener; - use crate::statistics::keeper::Keeper; + use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; use crate::statistics::services::{get_metrics, TrackerMetrics}; @@ -95,7 +95,7 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(Keeper::new( + let http_stats_keeper = Arc::new(EventBus::new( config.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 08997fc63..cb09a3907 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -125,7 +125,7 @@ mod tests { use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; - use bittorrent_http_tracker_core::statistics::keeper::Keeper; + use bittorrent_http_tracker_core::statistics::event_bus::EventBus; use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self}; @@ -153,7 +153,7 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(Keeper::new( + let http_stats_keeper = Arc::new(EventBus::new( config.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); diff --git a/packages/udp-tracker-core/benches/helpers/sync.rs b/packages/udp-tracker-core/benches/helpers/sync.rs index a64bb0bdf..c465ae996 100644 --- a/packages/udp-tracker-core/benches/helpers/sync.rs +++ b/packages/udp-tracker-core/benches/helpers/sync.rs @@ -4,7 +4,7 @@ use std::time::{Duration, Instant}; use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::connect::ConnectService; -use bittorrent_udp_tracker_core::statistics::keeper::Keeper; +use bittorrent_udp_tracker_core::statistics::event_bus::EventBus; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::helpers::utils::{sample_ipv4_remote_addr, sample_issue_time}; @@ -16,7 +16,7 @@ pub async fn connect_once(samples: u64) -> Duration { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); + let keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index 34d48a7eb..bc0d8ba4b 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -9,7 +9,7 @@ use crate::services::announce::AnnounceService; use crate::services::banning::BanService; use crate::services::connect::ConnectService; use crate::services::scrape::ScrapeService; -use crate::statistics::keeper::Keeper; +use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; use crate::{event, services, statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; @@ -19,7 +19,7 @@ pub struct UdpTrackerCoreContainer { pub tracker_core_container: Arc, // `UdpTrackerCoreServices` - pub stats_keeper: Arc, + pub stats_keeper: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub ban_service: Arc>, @@ -68,7 +68,7 @@ impl UdpTrackerCoreContainer { } pub struct UdpTrackerCoreServices { - pub stats_keeper: Arc, + pub stats_keeper: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub ban_service: Arc>, @@ -82,7 +82,7 @@ impl UdpTrackerCoreServices { pub fn initialize_from(tracker_core_container: &Arc) -> Arc { let udp_core_broadcaster = Broadcaster::default(); let udp_core_stats_repository = Arc::new(Repository::new()); - let keeper = Arc::new(Keeper::new( + let keeper = Arc::new(EventBus::new( tracker_core_container.core_config.tracker_usage_statistics, udp_core_broadcaster.clone(), )); diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index 2073ad943..7ea8b0882 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -73,7 +73,7 @@ mod tests { sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpCoreStatsEventSender, }; - use crate::statistics::keeper::Keeper; + use crate::statistics::event_bus::EventBus; #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { @@ -81,7 +81,7 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); + let keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -102,7 +102,7 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); + let keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -124,7 +124,7 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); + let keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = keeper.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); diff --git a/packages/udp-tracker-core/src/statistics/keeper.rs b/packages/udp-tracker-core/src/statistics/event_bus.rs similarity index 93% rename from packages/udp-tracker-core/src/statistics/keeper.rs rename to packages/udp-tracker-core/src/statistics/event_bus.rs index 9ae0564ce..2d22c0a90 100644 --- a/packages/udp-tracker-core/src/statistics/keeper.rs +++ b/packages/udp-tracker-core/src/statistics/event_bus.rs @@ -5,12 +5,12 @@ use tokio::sync::broadcast::Receiver; use crate::event::sender::{self, Broadcaster}; use crate::event::Event; -pub struct Keeper { +pub struct EventBus { pub enable_sender: bool, pub broadcaster: Broadcaster, } -impl Default for Keeper { +impl Default for EventBus { fn default() -> Self { let enable_sender = true; let broadcaster = Broadcaster::default(); @@ -19,7 +19,7 @@ impl Default for Keeper { } } -impl Keeper { +impl EventBus { #[must_use] pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { Self { diff --git a/packages/udp-tracker-core/src/statistics/mod.rs b/packages/udp-tracker-core/src/statistics/mod.rs index ba0b24530..f4e6f06a6 100644 --- a/packages/udp-tracker-core/src/statistics/mod.rs +++ b/packages/udp-tracker-core/src/statistics/mod.rs @@ -1,5 +1,5 @@ pub mod event; -pub mod keeper; +pub mod event_bus; pub mod metrics; pub mod repository; pub mod services; diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index cace8d8ba..22d84c931 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -95,7 +95,7 @@ mod tests { use crate::event::sender::Broadcaster; use crate::statistics::describe_metrics; - use crate::statistics::keeper::Keeper; + use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; use crate::statistics::services::{get_metrics, TrackerMetrics}; @@ -111,7 +111,7 @@ mod tests { let udp_core_broadcaster = Broadcaster::default(); let repository = Arc::new(Repository::new()); - let _keeper = Arc::new(Keeper::new( + let _keeper = Arc::new(EventBus::new( config.core.tracker_usage_statistics, udp_core_broadcaster.clone(), )); diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs index 3cba43d0e..0ad611070 100644 --- a/packages/udp-tracker-server/src/container.rs +++ b/packages/udp-tracker-server/src/container.rs @@ -5,11 +5,11 @@ use torrust_tracker_configuration::Core; use crate::event::sender::Broadcaster; use crate::event::{self}; use crate::statistics; -use crate::statistics::keeper::Keeper; +use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; pub struct UdpTrackerServerContainer { - pub stats_keeper: Arc, + pub stats_keeper: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, } @@ -28,7 +28,7 @@ impl UdpTrackerServerContainer { } pub struct UdpTrackerServerServices { - pub stats_keeper: Arc, + pub stats_keeper: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, } @@ -38,7 +38,7 @@ impl UdpTrackerServerServices { pub fn initialize(core_config: &Arc) -> Arc { let udp_server_broadcaster = Broadcaster::default(); let udp_server_stats_repository = Arc::new(Repository::new()); - let udp_server_stats_keeper = Arc::new(Keeper::new( + let udp_server_stats_keeper = Arc::new(EventBus::new( core_config.tracker_usage_statistics, udp_server_broadcaster.clone(), )); diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 3879816c5..d060269f5 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -375,7 +375,7 @@ mod tests { core_udp_tracker_services: Arc, ) -> Response { let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let keeper = Arc::new(crate::statistics::keeper::Keeper::new(false, udp_server_broadcaster.clone())); + let keeper = Arc::new(crate::statistics::event_bus::EventBus::new(false, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = keeper.sender(); @@ -535,7 +535,7 @@ mod tests { use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::announce::AnnounceService; - use bittorrent_udp_tracker_core::statistics::keeper::Keeper; + use bittorrent_udp_tracker_core::statistics::event_bus::EventBus; use mockall::predicate::eq; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -711,11 +711,11 @@ mod tests { whitelist_authorization: Arc, ) -> Response { let udp_core_broadcaster = Broadcaster::default(); - let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); + let core_keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_keeper = Arc::new(crate::statistics::keeper::Keeper::new(false, udp_server_broadcaster.clone())); + let server_keeper = Arc::new(crate::statistics::event_bus::EventBus::new(false, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = server_keeper.sender(); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 6e9c75612..9bfc8eaa6 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -61,7 +61,7 @@ mod tests { use bittorrent_udp_tracker_core::event as core_event; use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::connect::ConnectService; - use bittorrent_udp_tracker_core::statistics::keeper::Keeper; + use bittorrent_udp_tracker_core::statistics::event_bus::EventBus; use mockall::predicate::eq; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -84,11 +84,11 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); + let core_keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_keeper = Arc::new(crate::statistics::keeper::Keeper::new(false, udp_server_broadcaster.clone())); + let server_keeper = Arc::new(crate::statistics::event_bus::EventBus::new(false, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = server_keeper.sender(); @@ -123,11 +123,11 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); + let core_keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_keeper = Arc::new(crate::statistics::keeper::Keeper::new(false, udp_server_broadcaster.clone())); + let server_keeper = Arc::new(crate::statistics::event_bus::EventBus::new(false, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = server_keeper.sender(); @@ -162,12 +162,12 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); + let core_keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_keeper = Arc::new(crate::statistics::keeper::Keeper::new(false, udp_server_broadcaster.clone())); + let server_keeper = Arc::new(crate::statistics::event_bus::EventBus::new(false, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = server_keeper.sender(); diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index b4845c043..b53f1e2ee 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -221,7 +221,7 @@ pub(crate) mod tests { use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::announce::AnnounceService; use bittorrent_udp_tracker_core::services::scrape::ScrapeService; - use bittorrent_udp_tracker_core::statistics::keeper::Keeper; + use bittorrent_udp_tracker_core::statistics::event_bus::EventBus; use bittorrent_udp_tracker_core::{self, event as core_event}; use futures::future::BoxFuture; use mockall::mock; @@ -287,11 +287,14 @@ pub(crate) mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); let udp_core_broadcaster = Broadcaster::default(); - let core_keeper = Arc::new(Keeper::new(false, udp_core_broadcaster.clone())); + let core_keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_keeper.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_keeper = Arc::new(crate::statistics::keeper::Keeper::new(false, udp_server_broadcaster.clone())); + let server_keeper = Arc::new(crate::statistics::event_bus::EventBus::new( + false, + udp_server_broadcaster.clone(), + )); let udp_server_stats_event_sender = server_keeper.sender(); diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 5f85e2dfa..1533a2146 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -100,7 +100,7 @@ mod tests { initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, sample_issue_time, CoreTrackerServices, CoreUdpTrackerServices, TorrentPeerBuilder, }; - use crate::statistics::keeper::Keeper; + use crate::statistics::event_bus::EventBus; fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { TorrentScrapeStatistics { @@ -181,7 +181,7 @@ mod tests { core_udp_tracker_services: Arc, ) -> Response { let udp_server_broadcaster = Broadcaster::default(); - let keeper = Arc::new(Keeper::new(false, udp_server_broadcaster.clone())); + let keeper = Arc::new(EventBus::new(false, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = keeper.sender(); diff --git a/packages/udp-tracker-server/src/statistics/keeper.rs b/packages/udp-tracker-server/src/statistics/event_bus.rs similarity index 93% rename from packages/udp-tracker-server/src/statistics/keeper.rs rename to packages/udp-tracker-server/src/statistics/event_bus.rs index 9ae0564ce..2d22c0a90 100644 --- a/packages/udp-tracker-server/src/statistics/keeper.rs +++ b/packages/udp-tracker-server/src/statistics/event_bus.rs @@ -5,12 +5,12 @@ use tokio::sync::broadcast::Receiver; use crate::event::sender::{self, Broadcaster}; use crate::event::Event; -pub struct Keeper { +pub struct EventBus { pub enable_sender: bool, pub broadcaster: Broadcaster, } -impl Default for Keeper { +impl Default for EventBus { fn default() -> Self { let enable_sender = true; let broadcaster = Broadcaster::default(); @@ -19,7 +19,7 @@ impl Default for Keeper { } } -impl Keeper { +impl EventBus { #[must_use] pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { Self { diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index 16b7adbd8..9b6afc889 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -1,5 +1,5 @@ pub mod event; -pub mod keeper; +pub mod event_bus; pub mod metrics; pub mod repository; pub mod services; diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index 1593031c1..ca2cff7e8 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -115,7 +115,7 @@ mod tests { use crate::event::sender::Broadcaster; use crate::statistics::describe_metrics; - use crate::statistics::keeper::Keeper; + use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; use crate::statistics::services::{get_metrics, TrackerMetrics}; @@ -132,7 +132,7 @@ mod tests { let udp_server_broadcaster = Broadcaster::default(); let stats_repository = Arc::new(Repository::new()); - let _keeper = Arc::new(Keeper::new( + let _keeper = Arc::new(EventBus::new( config.core.tracker_usage_statistics, udp_server_broadcaster.clone(), )); From c103b60f889dc45d808c699b9e8366934de8d3df Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 18:47:59 +0100 Subject: [PATCH 1001/1297] refactor: [#1478] rename Keeper variables --- .../axum-http-tracker-server/src/server.rs | 8 ++--- .../src/v1/handlers/announce.rs | 6 ++-- .../src/v1/handlers/scrape.rs | 6 ++-- .../http-tracker-core/benches/helpers/util.rs | 6 ++-- packages/http-tracker-core/src/container.rs | 6 ++-- .../src/services/announce.rs | 6 ++-- .../http-tracker-core/src/services/scrape.rs | 8 ++--- .../src/statistics/services.rs | 4 +-- .../src/statistics/services.rs | 4 +-- .../udp-tracker-core/benches/helpers/sync.rs | 4 +-- packages/udp-tracker-core/src/container.rs | 6 ++-- .../udp-tracker-core/src/services/connect.rs | 12 +++---- .../src/statistics/services.rs | 15 --------- packages/udp-tracker-server/src/container.rs | 6 ++-- .../src/handlers/announce.rs | 18 ++++++---- .../src/handlers/connect.rs | 33 ++++++++++++------- .../udp-tracker-server/src/handlers/mod.rs | 8 ++--- .../udp-tracker-server/src/handlers/scrape.rs | 4 +-- .../src/statistics/services.rs | 15 --------- 19 files changed, 80 insertions(+), 95 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index a2d0bc52c..9367e6a77 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -277,15 +277,15 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(EventBus::new( + let http_stats_event_bus = Arc::new(EventBus::new( configuration.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); - let http_stats_event_sender = http_stats_keeper.sender(); + let http_stats_event_sender = http_stats_event_bus.sender(); if configuration.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); } let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); @@ -308,7 +308,7 @@ mod tests { HttpTrackerCoreContainer { tracker_core_container, http_tracker_config, - stats_keeper: http_stats_keeper, + stats_keeper: http_stats_event_bus, stats_event_sender: http_stats_event_sender, stats_repository: http_stats_repository, announce_service, diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 31c1df471..64d01dde6 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -167,15 +167,15 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(EventBus::new( + let http_stats_event_bus = Arc::new(EventBus::new( config.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); - let http_stats_event_sender = http_stats_keeper.sender(); + let http_stats_event_sender = http_stats_event_bus.sender(); if config.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); } let announce_service = Arc::new(AnnounceService::new( diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index 3a026a77c..ae99ea89f 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -138,15 +138,15 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(EventBus::new( + let http_stats_event_bus = Arc::new(EventBus::new( config.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); - let http_stats_event_sender = http_stats_keeper.sender(); + let http_stats_event_sender = http_stats_event_bus.sender(); if config.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); } ( diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 82a00d5b9..532ee21bf 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -62,15 +62,15 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(EventBus::new( + let http_stats_event_bus = Arc::new(EventBus::new( config.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); - let http_stats_event_sender = http_stats_keeper.sender(); + let http_stats_event_sender = http_stats_event_bus.sender(); if config.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); } ( diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 3cf344755..7486efe5b 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -71,12 +71,12 @@ impl HttpTrackerCoreServices { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(EventBus::new( + let http_stats_event_bus = Arc::new(EventBus::new( tracker_core_container.core_config.tracker_usage_statistics, http_core_broadcaster.clone(), )); - let http_stats_event_sender = http_stats_keeper.sender(); + let http_stats_event_sender = http_stats_event_bus.sender(); let http_announce_service = Arc::new(AnnounceService::new( tracker_core_container.core_config.clone(), @@ -94,7 +94,7 @@ impl HttpTrackerCoreServices { )); Arc::new(Self { - stats_keeper: http_stats_keeper, + stats_keeper: http_stats_event_bus, stats_event_sender: http_stats_event_sender, stats_repository: http_stats_repository, announce_service: http_announce_service, diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index a1e69d2cc..2c1e14b19 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -255,15 +255,15 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(EventBus::new( + let http_stats_event_bus = Arc::new(EventBus::new( config.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); - let http_stats_event_sender = http_stats_keeper.sender(); + let http_stats_event_sender = http_stats_event_bus.sender(); if config.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); } ( diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 2b5f74c83..f86615b9d 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -276,9 +276,9 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); - let http_stats_keeper = Arc::new(EventBus::new(false, http_core_broadcaster.clone())); + let http_stats_event_bus = Arc::new(EventBus::new(false, http_core_broadcaster.clone())); - let http_stats_event_sender = http_stats_keeper.sender(); + let http_stats_event_sender = http_stats_event_bus.sender(); let container = initialize_services_with_configuration(&configuration); @@ -471,9 +471,9 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); - let http_stats_keeper = Arc::new(EventBus::new(false, http_core_broadcaster.clone())); + let http_stats_event_bus = Arc::new(EventBus::new(false, http_core_broadcaster.clone())); - let http_stats_event_sender = http_stats_keeper.sender(); + let http_stats_event_sender = http_stats_event_bus.sender(); let info_hash = sample_info_hash(); let info_hashes = vec![info_hash]; diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index c695f6d4f..2cc96c15b 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -95,13 +95,13 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(EventBus::new( + let http_stats_event_bus = Arc::new(EventBus::new( config.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); if config.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); } let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), http_stats_repository).await; diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index cb09a3907..85af56801 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -153,13 +153,13 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); - let http_stats_keeper = Arc::new(EventBus::new( + let http_stats_event_bus = Arc::new(EventBus::new( config.core.tracker_usage_statistics, http_core_broadcaster.clone(), )); if config.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_keeper.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); } // UDP server stats diff --git a/packages/udp-tracker-core/benches/helpers/sync.rs b/packages/udp-tracker-core/benches/helpers/sync.rs index c465ae996..64eff2b48 100644 --- a/packages/udp-tracker-core/benches/helpers/sync.rs +++ b/packages/udp-tracker-core/benches/helpers/sync.rs @@ -16,9 +16,9 @@ pub async fn connect_once(samples: u64) -> Duration { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); - let udp_core_stats_event_sender = keeper.sender(); + let udp_core_stats_event_sender = event_bus.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); let start = Instant::now(); diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index bc0d8ba4b..3244b57b4 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -82,12 +82,12 @@ impl UdpTrackerCoreServices { pub fn initialize_from(tracker_core_container: &Arc) -> Arc { let udp_core_broadcaster = Broadcaster::default(); let udp_core_stats_repository = Arc::new(Repository::new()); - let keeper = Arc::new(EventBus::new( + let event_bus = Arc::new(EventBus::new( tracker_core_container.core_config.tracker_usage_statistics, udp_core_broadcaster.clone(), )); - let udp_core_stats_event_sender = keeper.sender(); + let udp_core_stats_event_sender = event_bus.sender(); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender.clone())); let announce_service = Arc::new(AnnounceService::new( @@ -101,7 +101,7 @@ impl UdpTrackerCoreServices { )); Arc::new(Self { - stats_keeper: keeper, + stats_keeper: event_bus, stats_event_sender: udp_core_stats_event_sender, stats_repository: udp_core_stats_repository, ban_service, diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index 7ea8b0882..81d9219e2 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -81,8 +81,8 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); - let udp_core_stats_event_sender = keeper.sender(); + let event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = event_bus.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -102,8 +102,8 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); - let udp_core_stats_event_sender = keeper.sender(); + let event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = event_bus.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -124,8 +124,8 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); - let udp_core_stats_event_sender = keeper.sender(); + let event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = event_bus.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index 22d84c931..aa10e4acd 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -89,32 +89,17 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self}; - use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; - use torrust_tracker_test_helpers::configuration; - use crate::event::sender::Broadcaster; use crate::statistics::describe_metrics; - use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; use crate::statistics::services::{get_metrics, TrackerMetrics}; - pub fn tracker_configuration() -> Configuration { - configuration::ephemeral() - } - #[tokio::test] async fn the_statistics_service_should_return_the_tracker_metrics() { - let config = tracker_configuration(); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let udp_core_broadcaster = Broadcaster::default(); let repository = Arc::new(Repository::new()); - let _keeper = Arc::new(EventBus::new( - config.core.tracker_usage_statistics, - udp_core_broadcaster.clone(), - )); let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), repository.clone()).await; diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs index 0ad611070..e1dbdfece 100644 --- a/packages/udp-tracker-server/src/container.rs +++ b/packages/udp-tracker-server/src/container.rs @@ -38,15 +38,15 @@ impl UdpTrackerServerServices { pub fn initialize(core_config: &Arc) -> Arc { let udp_server_broadcaster = Broadcaster::default(); let udp_server_stats_repository = Arc::new(Repository::new()); - let udp_server_stats_keeper = Arc::new(EventBus::new( + let udp_server_stats_event_bus = Arc::new(EventBus::new( core_config.tracker_usage_statistics, udp_server_broadcaster.clone(), )); - let udp_server_stats_event_sender = udp_server_stats_keeper.sender(); + let udp_server_stats_event_sender = udp_server_stats_event_bus.sender(); Arc::new(Self { - stats_keeper: udp_server_stats_keeper.clone(), + stats_keeper: udp_server_stats_event_bus.clone(), stats_event_sender: udp_server_stats_event_sender.clone(), stats_repository: udp_server_stats_repository.clone(), }) diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index d060269f5..452a12d65 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -375,9 +375,12 @@ mod tests { core_udp_tracker_services: Arc, ) -> Response { let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let keeper = Arc::new(crate::statistics::event_bus::EventBus::new(false, udp_server_broadcaster.clone())); + let event_bus = Arc::new(crate::statistics::event_bus::EventBus::new( + false, + udp_server_broadcaster.clone(), + )); - let udp_server_stats_event_sender = keeper.sender(); + let udp_server_stats_event_sender = event_bus.sender(); let client_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); @@ -711,13 +714,16 @@ mod tests { whitelist_authorization: Arc, ) -> Response { let udp_core_broadcaster = Broadcaster::default(); - let core_keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); - let udp_core_stats_event_sender = core_keeper.sender(); + let core_event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_keeper = Arc::new(crate::statistics::event_bus::EventBus::new(false, udp_server_broadcaster.clone())); + let server_event_bus = Arc::new(crate::statistics::event_bus::EventBus::new( + false, + udp_server_broadcaster.clone(), + )); - let udp_server_stats_event_sender = server_keeper.sender(); + let udp_server_stats_event_sender = server_event_bus.sender(); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); let client_ip_v6 = client_ip_v4.to_ipv6_compatible(); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 9bfc8eaa6..f08084a20 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -84,13 +84,16 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let core_keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); - let udp_core_stats_event_sender = core_keeper.sender(); + let core_event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_keeper = Arc::new(crate::statistics::event_bus::EventBus::new(false, udp_server_broadcaster.clone())); + let server_event_bus = Arc::new(crate::statistics::event_bus::EventBus::new( + false, + udp_server_broadcaster.clone(), + )); - let udp_server_stats_event_sender = server_keeper.sender(); + let udp_server_stats_event_sender = server_event_bus.sender(); let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), @@ -123,13 +126,16 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let core_keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); - let udp_core_stats_event_sender = core_keeper.sender(); + let core_event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_keeper = Arc::new(crate::statistics::event_bus::EventBus::new(false, udp_server_broadcaster.clone())); + let server_event_bus = Arc::new(crate::statistics::event_bus::EventBus::new( + false, + udp_server_broadcaster.clone(), + )); - let udp_server_stats_event_sender = server_keeper.sender(); + let udp_server_stats_event_sender = server_event_bus.sender(); let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), @@ -162,14 +168,17 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let core_keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let core_event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); - let udp_core_stats_event_sender = core_keeper.sender(); + let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_keeper = Arc::new(crate::statistics::event_bus::EventBus::new(false, udp_server_broadcaster.clone())); + let server_event_bus = Arc::new(crate::statistics::event_bus::EventBus::new( + false, + udp_server_broadcaster.clone(), + )); - let udp_server_stats_event_sender = server_keeper.sender(); + let udp_server_stats_event_sender = server_event_bus.sender(); let request = ConnectRequest { transaction_id: TransactionId(0i32.into()), diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index b53f1e2ee..43c6c63b7 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -287,16 +287,16 @@ pub(crate) mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); let udp_core_broadcaster = Broadcaster::default(); - let core_keeper = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); - let udp_core_stats_event_sender = core_keeper.sender(); + let core_event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_keeper = Arc::new(crate::statistics::event_bus::EventBus::new( + let server_event_bus = Arc::new(crate::statistics::event_bus::EventBus::new( false, udp_server_broadcaster.clone(), )); - let udp_server_stats_event_sender = server_keeper.sender(); + let udp_server_stats_event_sender = server_event_bus.sender(); let announce_service = Arc::new(AnnounceService::new( announce_handler.clone(), diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 1533a2146..b945913ad 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -181,9 +181,9 @@ mod tests { core_udp_tracker_services: Arc, ) -> Response { let udp_server_broadcaster = Broadcaster::default(); - let keeper = Arc::new(EventBus::new(false, udp_server_broadcaster.clone())); + let event_bus = Arc::new(EventBus::new(false, udp_server_broadcaster.clone())); - let udp_server_stats_event_sender = keeper.sender(); + let udp_server_stats_event_sender = event_bus.sender(); let client_socket_addr = sample_ipv4_remote_addr(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index ca2cff7e8..4db80c465 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -109,33 +109,18 @@ mod tests { use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use tokio::sync::RwLock; - use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; - use torrust_tracker_test_helpers::configuration; - use crate::event::sender::Broadcaster; use crate::statistics::describe_metrics; - use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; use crate::statistics::services::{get_metrics, TrackerMetrics}; - pub fn tracker_configuration() -> Configuration { - configuration::ephemeral() - } - #[tokio::test] async fn the_statistics_service_should_return_the_tracker_metrics() { - let config = tracker_configuration(); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); - let udp_server_broadcaster = Broadcaster::default(); let stats_repository = Arc::new(Repository::new()); - let _keeper = Arc::new(EventBus::new( - config.core.tracker_usage_statistics, - udp_server_broadcaster.clone(), - )); let tracker_metrics = get_metrics( in_memory_torrent_repository.clone(), From b32072c5982708486012ef86d88735b985baf6ff Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 18:51:00 +0100 Subject: [PATCH 1002/1297] refactor: [#1478] rename struct fields for Keeper type --- packages/axum-http-tracker-server/src/environment.rs | 2 +- packages/axum-http-tracker-server/src/server.rs | 2 +- packages/http-tracker-core/src/container.rs | 8 ++++---- packages/udp-tracker-core/src/container.rs | 8 ++++---- packages/udp-tracker-server/src/container.rs | 8 ++++---- packages/udp-tracker-server/src/environment.rs | 4 ++-- src/app.rs | 6 +++--- 7 files changed, 19 insertions(+), 19 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index ffba790c2..aeb53a710 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -70,7 +70,7 @@ impl Environment { pub async fn start(self) -> Environment { // Start the event listener let event_listener_job = run_event_listener( - self.container.http_tracker_core_container.stats_keeper.receiver(), + self.container.http_tracker_core_container.event_bus.receiver(), &self.container.http_tracker_core_container.stats_repository, ); diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 9367e6a77..209925c04 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -308,7 +308,7 @@ mod tests { HttpTrackerCoreContainer { tracker_core_container, http_tracker_config, - stats_keeper: http_stats_event_bus, + event_bus: http_stats_event_bus, stats_event_sender: http_stats_event_sender, stats_repository: http_stats_repository, announce_service, diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 7486efe5b..647c065df 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -16,7 +16,7 @@ pub struct HttpTrackerCoreContainer { pub tracker_core_container: Arc, // `HttpTrackerCoreServices` - pub stats_keeper: Arc, + pub event_bus: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub announce_service: Arc, @@ -48,7 +48,7 @@ impl HttpTrackerCoreContainer { Arc::new(Self { tracker_core_container: tracker_core_container.clone(), http_tracker_config: http_tracker_config.clone(), - stats_keeper: http_tracker_core_services.stats_keeper.clone(), + event_bus: http_tracker_core_services.event_bus.clone(), stats_event_sender: http_tracker_core_services.stats_event_sender.clone(), stats_repository: http_tracker_core_services.stats_repository.clone(), announce_service: http_tracker_core_services.announce_service.clone(), @@ -58,7 +58,7 @@ impl HttpTrackerCoreContainer { } pub struct HttpTrackerCoreServices { - pub stats_keeper: Arc, + pub event_bus: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub announce_service: Arc, @@ -94,7 +94,7 @@ impl HttpTrackerCoreServices { )); Arc::new(Self { - stats_keeper: http_stats_event_bus, + event_bus: http_stats_event_bus, stats_event_sender: http_stats_event_sender, stats_repository: http_stats_repository, announce_service: http_announce_service, diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index 3244b57b4..e229fe1a4 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -19,7 +19,7 @@ pub struct UdpTrackerCoreContainer { pub tracker_core_container: Arc, // `UdpTrackerCoreServices` - pub stats_keeper: Arc, + pub event_bus: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub ban_service: Arc>, @@ -56,7 +56,7 @@ impl UdpTrackerCoreContainer { tracker_core_container: tracker_core_container.clone(), // `UdpTrackerCoreServices` - stats_keeper: udp_tracker_core_services.stats_keeper.clone(), + event_bus: udp_tracker_core_services.event_bus.clone(), stats_event_sender: udp_tracker_core_services.stats_event_sender.clone(), stats_repository: udp_tracker_core_services.stats_repository.clone(), ban_service: udp_tracker_core_services.ban_service.clone(), @@ -68,7 +68,7 @@ impl UdpTrackerCoreContainer { } pub struct UdpTrackerCoreServices { - pub stats_keeper: Arc, + pub event_bus: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub ban_service: Arc>, @@ -101,7 +101,7 @@ impl UdpTrackerCoreServices { )); Arc::new(Self { - stats_keeper: event_bus, + event_bus, stats_event_sender: udp_core_stats_event_sender, stats_repository: udp_core_stats_repository, ban_service, diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs index e1dbdfece..debeb0ecf 100644 --- a/packages/udp-tracker-server/src/container.rs +++ b/packages/udp-tracker-server/src/container.rs @@ -9,7 +9,7 @@ use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; pub struct UdpTrackerServerContainer { - pub stats_keeper: Arc, + pub event_bus: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, } @@ -20,7 +20,7 @@ impl UdpTrackerServerContainer { let udp_tracker_server_services = UdpTrackerServerServices::initialize(core_config); Arc::new(Self { - stats_keeper: udp_tracker_server_services.stats_keeper.clone(), + event_bus: udp_tracker_server_services.event_bus.clone(), stats_event_sender: udp_tracker_server_services.stats_event_sender.clone(), stats_repository: udp_tracker_server_services.stats_repository.clone(), }) @@ -28,7 +28,7 @@ impl UdpTrackerServerContainer { } pub struct UdpTrackerServerServices { - pub stats_keeper: Arc, + pub event_bus: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, } @@ -46,7 +46,7 @@ impl UdpTrackerServerServices { let udp_server_stats_event_sender = udp_server_stats_event_bus.sender(); Arc::new(Self { - stats_keeper: udp_server_stats_event_bus.clone(), + event_bus: udp_server_stats_event_bus.clone(), stats_event_sender: udp_server_stats_event_sender.clone(), stats_repository: udp_server_stats_repository.clone(), }) diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 7d70317aa..962442fde 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -73,13 +73,13 @@ impl Environment { let cookie_lifetime = self.container.udp_tracker_core_container.udp_tracker_config.cookie_lifetime; // Start the UDP tracker core event listener let udp_core_event_listener_job = Some(bittorrent_udp_tracker_core::statistics::event::listener::run_event_listener( - self.container.udp_tracker_core_container.stats_keeper.receiver(), + self.container.udp_tracker_core_container.event_bus.receiver(), &self.container.udp_tracker_core_container.stats_repository, )); // Start the UDP tracker server event listener let udp_server_event_listener_job = Some(crate::statistics::event::listener::run_event_listener( - self.container.udp_tracker_server_container.stats_keeper.receiver(), + self.container.udp_tracker_server_container.event_bus.receiver(), &self.container.udp_tracker_server_container.stats_repository, )); diff --git a/src/app.rs b/src/app.rs index b01dc9c36..5d07eb8b3 100644 --- a/src/app.rs +++ b/src/app.rs @@ -112,7 +112,7 @@ async fn load_whitelisted_torrents(config: &Configuration, app_container: &Arc) { if config.core.tracker_usage_statistics { let _job = bittorrent_http_tracker_core::statistics::event::listener::run_event_listener( - app_container.http_tracker_core_services.stats_keeper.receiver(), + app_container.http_tracker_core_services.event_bus.receiver(), &app_container.http_tracker_core_services.stats_repository, ); @@ -132,7 +132,7 @@ fn start_http_core_event_listener(config: &Configuration, app_container: &Arc) { if config.core.tracker_usage_statistics { let _job = bittorrent_udp_tracker_core::statistics::event::listener::run_event_listener( - app_container.udp_tracker_core_services.stats_keeper.receiver(), + app_container.udp_tracker_core_services.event_bus.receiver(), &app_container.udp_tracker_core_services.stats_repository, ); @@ -152,7 +152,7 @@ fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc) { if config.core.tracker_usage_statistics { let _job = torrust_udp_tracker_server::statistics::event::listener::run_event_listener( - app_container.udp_tracker_server_container.stats_keeper.receiver(), + app_container.udp_tracker_server_container.event_bus.receiver(), &app_container.udp_tracker_server_container.stats_repository, ); From b0951aad2a1027a5640a93f1870b83e4e7a651c9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 18:58:33 +0100 Subject: [PATCH 1003/1297] refactor: [#1478] move EventBus to event mod --- packages/axum-http-tracker-server/src/server.rs | 2 +- .../src/v1/handlers/announce.rs | 2 +- .../src/v1/handlers/scrape.rs | 2 +- .../http-tracker-core/benches/helpers/util.rs | 2 +- packages/http-tracker-core/src/container.rs | 6 +++--- .../{statistics/event_bus.rs => event/bus.rs} | 0 packages/http-tracker-core/src/event/mod.rs | 5 +++-- .../http-tracker-core/src/services/announce.rs | 2 +- .../http-tracker-core/src/services/scrape.rs | 4 ++-- .../http-tracker-core/src/statistics/mod.rs | 1 - .../src/statistics/services.rs | 2 +- .../src/statistics/services.rs | 2 +- .../udp-tracker-core/benches/helpers/sync.rs | 2 +- packages/udp-tracker-core/src/container.rs | 6 +++--- .../{statistics/event_bus.rs => event/bus.rs} | 0 packages/udp-tracker-core/src/event/mod.rs | 5 +++-- .../udp-tracker-core/src/services/connect.rs | 2 +- packages/udp-tracker-core/src/statistics/mod.rs | 1 - packages/udp-tracker-server/src/container.rs | 6 +++--- .../{statistics/event_bus.rs => event/bus.rs} | 0 packages/udp-tracker-server/src/event/mod.rs | 5 +++-- .../udp-tracker-server/src/handlers/announce.rs | 12 +++--------- .../udp-tracker-server/src/handlers/connect.rs | 17 ++++------------- packages/udp-tracker-server/src/handlers/mod.rs | 7 ++----- .../udp-tracker-server/src/handlers/scrape.rs | 2 +- .../udp-tracker-server/src/statistics/mod.rs | 1 - 26 files changed, 39 insertions(+), 57 deletions(-) rename packages/http-tracker-core/src/{statistics/event_bus.rs => event/bus.rs} (100%) rename packages/udp-tracker-core/src/{statistics/event_bus.rs => event/bus.rs} (100%) rename packages/udp-tracker-server/src/{statistics/event_bus.rs => event/bus.rs} (100%) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 209925c04..41a9dec6d 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -248,11 +248,11 @@ mod tests { use std::sync::Arc; use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; + use bittorrent_http_tracker_core::event::bus::EventBus; use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::services::announce::AnnounceService; use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; - use bittorrent_http_tracker_core::statistics::event_bus::EventBus; use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_tracker_core::container::TrackerCoreContainer; use torrust_axum_server::tsl::make_rust_tls; diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 64d01dde6..7489211a9 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -107,10 +107,10 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::PeerId; + use bittorrent_http_tracker_core::event::bus::EventBus; use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::services::announce::AnnounceService; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; - use bittorrent_http_tracker_core::statistics::event_bus::EventBus; use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; use bittorrent_http_tracker_protocol::v1::responses; diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index ae99ea89f..7f1247173 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -83,9 +83,9 @@ mod tests { use std::str::FromStr; use std::sync::Arc; + use bittorrent_http_tracker_core::event::bus::EventBus; use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; - use bittorrent_http_tracker_core::statistics::event_bus::EventBus; use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; use bittorrent_http_tracker_protocol::v1::responses; diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 532ee21bf..9d2d80da3 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -3,10 +3,10 @@ use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_http_tracker_core::event; +use bittorrent_http_tracker_core::event::bus::EventBus; use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::event::Event; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; -use bittorrent_http_tracker_core::statistics::event_bus::EventBus; use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 647c065df..c3ed8a0c7 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -3,10 +3,10 @@ use std::sync::Arc; use bittorrent_tracker_core::container::TrackerCoreContainer; use torrust_tracker_configuration::{Core, HttpTracker}; +use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::services::announce::AnnounceService; use crate::services::scrape::ScrapeService; -use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; use crate::{event, services, statistics}; @@ -16,7 +16,7 @@ pub struct HttpTrackerCoreContainer { pub tracker_core_container: Arc, // `HttpTrackerCoreServices` - pub event_bus: Arc, + pub event_bus: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub announce_service: Arc, @@ -58,7 +58,7 @@ impl HttpTrackerCoreContainer { } pub struct HttpTrackerCoreServices { - pub event_bus: Arc, + pub event_bus: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub announce_service: Arc, diff --git a/packages/http-tracker-core/src/statistics/event_bus.rs b/packages/http-tracker-core/src/event/bus.rs similarity index 100% rename from packages/http-tracker-core/src/statistics/event_bus.rs rename to packages/http-tracker-core/src/event/bus.rs diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index 4f0b84e48..5b1c64dca 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -1,3 +1,6 @@ +pub mod bus; +pub mod sender; + use std::net::{IpAddr, SocketAddr}; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::RemoteClientAddr; @@ -7,8 +10,6 @@ use torrust_tracker_metrics::label_name; use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; -pub mod sender; - /// A HTTP core event. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 2c1e14b19..bef7449b7 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -303,10 +303,10 @@ mod tests { use tokio::sync::broadcast::error::SendError; use crate::event; + use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::Event; use crate::statistics::event::listener::run_event_listener; - use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; use crate::tests::sample_info_hash; diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index f86615b9d..a0ae73d97 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -260,13 +260,13 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::event; + use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::{ConnectionContext, Event}; use crate::services::scrape::tests::{ initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::services::scrape::ScrapeService; - use crate::statistics::event_bus::EventBus; use crate::tests::sample_info_hash; #[tokio::test] @@ -453,13 +453,13 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::event; + use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::{ConnectionContext, Event}; use crate::services::scrape::tests::{ initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, }; use crate::services::scrape::ScrapeService; - use crate::statistics::event_bus::EventBus; use crate::tests::sample_info_hash; #[tokio::test] diff --git a/packages/http-tracker-core/src/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs index da2f0acd4..f949babbd 100644 --- a/packages/http-tracker-core/src/statistics/mod.rs +++ b/packages/http-tracker-core/src/statistics/mod.rs @@ -1,5 +1,4 @@ pub mod event; -pub mod event_bus; pub mod metrics; pub mod repository; pub mod services; diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 2cc96c15b..7f3c365d4 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -75,10 +75,10 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; use torrust_tracker_test_helpers::configuration; + use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::statistics::describe_metrics; use crate::statistics::event::listener::run_event_listener; - use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; use crate::statistics::services::{get_metrics, TrackerMetrics}; diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 85af56801..9489a5e3e 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -123,9 +123,9 @@ pub async fn get_labeled_metrics( mod tests { use std::sync::Arc; + use bittorrent_http_tracker_core::event::bus::EventBus; use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; - use bittorrent_http_tracker_core::statistics::event_bus::EventBus; use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self}; diff --git a/packages/udp-tracker-core/benches/helpers/sync.rs b/packages/udp-tracker-core/benches/helpers/sync.rs index 64eff2b48..1814a865e 100644 --- a/packages/udp-tracker-core/benches/helpers/sync.rs +++ b/packages/udp-tracker-core/benches/helpers/sync.rs @@ -2,9 +2,9 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use std::time::{Duration, Instant}; +use bittorrent_udp_tracker_core::event::bus::EventBus; use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::connect::ConnectService; -use bittorrent_udp_tracker_core::statistics::event_bus::EventBus; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::helpers::utils::{sample_ipv4_remote_addr, sample_issue_time}; diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index e229fe1a4..c1dd0461f 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -4,12 +4,12 @@ use bittorrent_tracker_core::container::TrackerCoreContainer; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, UdpTracker}; +use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::services::announce::AnnounceService; use crate::services::banning::BanService; use crate::services::connect::ConnectService; use crate::services::scrape::ScrapeService; -use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; use crate::{event, services, statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; @@ -19,7 +19,7 @@ pub struct UdpTrackerCoreContainer { pub tracker_core_container: Arc, // `UdpTrackerCoreServices` - pub event_bus: Arc, + pub event_bus: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub ban_service: Arc>, @@ -68,7 +68,7 @@ impl UdpTrackerCoreContainer { } pub struct UdpTrackerCoreServices { - pub event_bus: Arc, + pub event_bus: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, pub ban_service: Arc>, diff --git a/packages/udp-tracker-core/src/statistics/event_bus.rs b/packages/udp-tracker-core/src/event/bus.rs similarity index 100% rename from packages/udp-tracker-core/src/statistics/event_bus.rs rename to packages/udp-tracker-core/src/event/bus.rs diff --git a/packages/udp-tracker-core/src/event/mod.rs b/packages/udp-tracker-core/src/event/mod.rs index 1ec502572..babc05fcc 100644 --- a/packages/udp-tracker-core/src/event/mod.rs +++ b/packages/udp-tracker-core/src/event/mod.rs @@ -1,3 +1,6 @@ +pub mod bus; +pub mod sender; + use std::net::SocketAddr; use bittorrent_primitives::info_hash::InfoHash; @@ -6,8 +9,6 @@ use torrust_tracker_metrics::label_name; use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; -pub mod sender; - /// A UDP core event. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index 81d9219e2..b40af901c 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -66,6 +66,7 @@ mod tests { use crate::connection_cookie::make; use crate::event; + use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::{ConnectionContext, Event}; use crate::services::connect::ConnectService; @@ -73,7 +74,6 @@ mod tests { sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpCoreStatsEventSender, }; - use crate::statistics::event_bus::EventBus; #[tokio::test] async fn a_connect_response_should_contain_the_same_transaction_id_as_the_connect_request() { diff --git a/packages/udp-tracker-core/src/statistics/mod.rs b/packages/udp-tracker-core/src/statistics/mod.rs index f4e6f06a6..9eb85d7f1 100644 --- a/packages/udp-tracker-core/src/statistics/mod.rs +++ b/packages/udp-tracker-core/src/statistics/mod.rs @@ -1,5 +1,4 @@ pub mod event; -pub mod event_bus; pub mod metrics; pub mod repository; pub mod services; diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs index debeb0ecf..121737d92 100644 --- a/packages/udp-tracker-server/src/container.rs +++ b/packages/udp-tracker-server/src/container.rs @@ -2,14 +2,14 @@ use std::sync::Arc; use torrust_tracker_configuration::Core; +use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::{self}; use crate::statistics; -use crate::statistics::event_bus::EventBus; use crate::statistics::repository::Repository; pub struct UdpTrackerServerContainer { - pub event_bus: Arc, + pub event_bus: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, } @@ -28,7 +28,7 @@ impl UdpTrackerServerContainer { } pub struct UdpTrackerServerServices { - pub event_bus: Arc, + pub event_bus: Arc, pub stats_event_sender: Arc>>, pub stats_repository: Arc, } diff --git a/packages/udp-tracker-server/src/statistics/event_bus.rs b/packages/udp-tracker-server/src/event/bus.rs similarity index 100% rename from packages/udp-tracker-server/src/statistics/event_bus.rs rename to packages/udp-tracker-server/src/event/bus.rs diff --git a/packages/udp-tracker-server/src/event/mod.rs b/packages/udp-tracker-server/src/event/mod.rs index a1770acc0..a2140a11c 100644 --- a/packages/udp-tracker-server/src/event/mod.rs +++ b/packages/udp-tracker-server/src/event/mod.rs @@ -1,3 +1,6 @@ +pub mod bus; +pub mod sender; + use std::fmt; use std::net::SocketAddr; use std::time::Duration; @@ -6,8 +9,6 @@ use torrust_tracker_metrics::label::{LabelSet, LabelValue}; use torrust_tracker_metrics::label_name; use torrust_tracker_primitives::service_binding::ServiceBinding; -pub mod sender; - /// A UDP server event. #[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 452a12d65..f8b2092b5 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -375,10 +375,7 @@ mod tests { core_udp_tracker_services: Arc, ) -> Response { let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let event_bus = Arc::new(crate::statistics::event_bus::EventBus::new( - false, - udp_server_broadcaster.clone(), - )); + let event_bus = Arc::new(crate::event::bus::EventBus::new(false, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = event_bus.sender(); @@ -536,9 +533,9 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use bittorrent_udp_tracker_core::event::bus::EventBus; use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::announce::AnnounceService; - use bittorrent_udp_tracker_core::statistics::event_bus::EventBus; use mockall::predicate::eq; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -718,10 +715,7 @@ mod tests { let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_event_bus = Arc::new(crate::statistics::event_bus::EventBus::new( - false, - udp_server_broadcaster.clone(), - )); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new(false, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = server_event_bus.sender(); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index f08084a20..85bfda680 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -59,9 +59,9 @@ mod tests { use aquatic_udp_protocol::{ConnectRequest, ConnectResponse, Response, TransactionId}; use bittorrent_udp_tracker_core::connection_cookie::make; use bittorrent_udp_tracker_core::event as core_event; + use bittorrent_udp_tracker_core::event::bus::EventBus; use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::connect::ConnectService; - use bittorrent_udp_tracker_core::statistics::event_bus::EventBus; use mockall::predicate::eq; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -88,10 +88,7 @@ mod tests { let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_event_bus = Arc::new(crate::statistics::event_bus::EventBus::new( - false, - udp_server_broadcaster.clone(), - )); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new(false, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = server_event_bus.sender(); @@ -130,10 +127,7 @@ mod tests { let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_event_bus = Arc::new(crate::statistics::event_bus::EventBus::new( - false, - udp_server_broadcaster.clone(), - )); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new(false, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = server_event_bus.sender(); @@ -173,10 +167,7 @@ mod tests { let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_event_bus = Arc::new(crate::statistics::event_bus::EventBus::new( - false, - udp_server_broadcaster.clone(), - )); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new(false, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = server_event_bus.sender(); diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 43c6c63b7..dde8f0cc8 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -218,10 +218,10 @@ pub(crate) mod tests { use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::gen_remote_fingerprint; + use bittorrent_udp_tracker_core::event::bus::EventBus; use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::announce::AnnounceService; use bittorrent_udp_tracker_core::services::scrape::ScrapeService; - use bittorrent_udp_tracker_core::statistics::event_bus::EventBus; use bittorrent_udp_tracker_core::{self, event as core_event}; use futures::future::BoxFuture; use mockall::mock; @@ -291,10 +291,7 @@ pub(crate) mod tests { let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_event_bus = Arc::new(crate::statistics::event_bus::EventBus::new( - false, - udp_server_broadcaster.clone(), - )); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new(false, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = server_event_bus.sender(); diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index b945913ad..5774bc8e6 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -94,13 +94,13 @@ mod tests { use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::handlers::handle_scrape; use crate::handlers::tests::{ initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, sample_issue_time, CoreTrackerServices, CoreUdpTrackerServices, TorrentPeerBuilder, }; - use crate::statistics::event_bus::EventBus; fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { TorrentScrapeStatistics { diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index 9b6afc889..8f6e9becf 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -1,5 +1,4 @@ pub mod event; -pub mod event_bus; pub mod metrics; pub mod repository; pub mod services; From 36f94df982110c22eb8f8096bc04c92f96c06762 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 25 Apr 2025 20:58:03 +0100 Subject: [PATCH 1004/1297] chore(deps): udpate dependencies ``` cargo update Updating crates.io index Locking 14 packages to latest compatible versions Updating async-compression v0.4.22 -> v0.4.23 Updating brotli v7.0.0 -> v8.0.0 Updating brotli-decompressor v4.0.3 -> v5.0.0 Updating cc v1.2.19 -> v1.2.20 Updating getrandom v0.2.15 -> v0.2.16 Updating libm v0.2.12 -> v0.2.13 Updating libsqlite3-sys v0.32.0 -> v0.33.0 Updating local-ip-address v0.6.3 -> v0.6.4 Updating r2d2_sqlite v0.27.0 -> v0.28.0 Updating rusqlite v0.34.0 -> v0.35.0 Updating tokio-util v0.7.14 -> v0.7.15 Updating winnow v0.7.6 -> v0.7.7 Updating zerocopy v0.8.24 -> v0.8.25 Updating zerocopy-derive v0.8.24 -> v0.8.25 ``` --- Cargo.lock | 68 +++++++++++++++++++++++++++--------------------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 370562982..8f7b1ef6f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,7 +23,7 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" dependencies = [ - "getrandom 0.2.15", + "getrandom 0.2.16", "once_cell", "version_check", ] @@ -217,9 +217,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.22" +version = "0.4.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a194f9d963d8099596278594b3107448656ba73831c9d8c783e613ce86da64" +checksum = "b37fc50485c4f3f736a4fb14199f6d5f5ba008d7f28fe710306c92780f004c07" dependencies = [ "brotli", "flate2", @@ -846,9 +846,9 @@ dependencies = [ [[package]] name = "brotli" -version = "7.0.0" +version = "8.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc97b8f16f944bba54f0433f07e30be199b6dc2bd25937444bbad560bcea29bd" +checksum = "cf19e729cdbd51af9a397fb9ef8ac8378007b797f8273cfbfdf45dcaa316167b" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -857,9 +857,9 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "4.0.3" +version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a334ef7c9e23abf0ce748e8cd309037da93e606ad52eb372e4ce327a0dcfbdfd" +checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -952,9 +952,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.19" +version = "1.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e3a13707ac958681c13b39b458c073d0d9bc8a22cb1b2f4c8e55eb72c13f362" +checksum = "04da6a0d40b948dfc4fa8f5bbf402b0fc1a64a28dbf7d12ffd683550f2c1b63a" dependencies = [ "jobserver", "libc", @@ -1809,9 +1809,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "libc", @@ -2428,9 +2428,9 @@ dependencies = [ [[package]] name = "libm" -version = "0.2.12" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d154aedcb0b7a1e91a3fddbe2a8350d3da76ac9d0220ae20da5c7aa8269612" +checksum = "c9627da5196e5d8ed0b0495e61e518847578da83483c37288316d9b2e03a7f72" [[package]] name = "libredox" @@ -2445,9 +2445,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.32.0" +version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbb8270bb4060bd76c6e96f20c52d80620f1d82a3470885694e41e0f81ef6fe7" +checksum = "947e6816f7825b2b45027c2c32e7085da9934defa535de4a6a46b10a4d5257fa" dependencies = [ "cc", "pkg-config", @@ -2485,13 +2485,13 @@ checksum = "23fb14cb19457329c82206317a5663005a4d404783dc74f4252769b0d5f42856" [[package]] name = "local-ip-address" -version = "0.6.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3669cf5561f8d27e8fc84cc15e58350e70f557d4d65f70e3154e54cd2f8e1782" +checksum = "c986b1747bbd3666abe4d57c64e60e6a82c2216140d8b12d5ceb33feb9de44b3" dependencies = [ "libc", "neli", - "thiserror 1.0.69", + "thiserror 2.0.12", "windows-sys 0.59.0", ] @@ -3133,7 +3133,7 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ - "zerocopy 0.8.24", + "zerocopy 0.8.25", ] [[package]] @@ -3294,9 +3294,9 @@ dependencies = [ [[package]] name = "r2d2_sqlite" -version = "0.27.0" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "180da684f0a188977d3968f139eb44260192ef8d9a5b7b7cbd01d881e0353179" +checksum = "8998443b32daee2ad6f528afb19ad77c4a8acc4d8d55b3e5072ed42862fe261a" dependencies = [ "r2d2", "rusqlite", @@ -3356,7 +3356,7 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom 0.2.15", + "getrandom 0.2.16", ] [[package]] @@ -3502,7 +3502,7 @@ checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" dependencies = [ "cc", "cfg-if", - "getrandom 0.2.15", + "getrandom 0.2.16", "libc", "untrusted", "windows-sys 0.52.0", @@ -3580,9 +3580,9 @@ dependencies = [ [[package]] name = "rusqlite" -version = "0.34.0" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37e34486da88d8e051c7c0e23c3f15fd806ea8546260aa2fec247e97242ec143" +checksum = "a22715a5d6deef63c637207afbe68d0c72c3f8d0022d7cf9714c442d6157606b" dependencies = [ "bitflags 2.9.0", "fallible-iterator", @@ -4459,9 +4459,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.14" +version = "0.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b9590b93e6fcc1739458317cccd391ad3955e2bde8913edf6f95f9e65a8f034" +checksum = "66a539a9ad6d5d281510d5bd368c973d636c02dbf8a67300bfb6b950696ad7df" dependencies = [ "bytes", "futures-core", @@ -5564,9 +5564,9 @@ checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" [[package]] name = "winnow" -version = "0.7.6" +version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63d3fcd9bba44b03821e7d699eeee959f3126dcc4aa8e4ae18ec617c2a5cea10" +checksum = "6cb8234a863ea0e8cd7284fcdd4f145233eb00fee02bbdd9861aec44e6477bc5" dependencies = [ "memchr", ] @@ -5653,11 +5653,11 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.24" +version = "0.8.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2586fea28e186957ef732a5f8b3be2da217d65c5969d4b1e17f973ebbe876879" +checksum = "a1702d9583232ddb9174e01bb7c15a2ab8fb1bc6f227aa1233858c351a3ba0cb" dependencies = [ - "zerocopy-derive 0.8.24", + "zerocopy-derive 0.8.25", ] [[package]] @@ -5673,9 +5673,9 @@ dependencies = [ [[package]] name = "zerocopy-derive" -version = "0.8.24" +version = "0.8.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a996a8f63c5c4448cd959ac1bab0aaa3306ccfd060472f85943ee0750f0169be" +checksum = "28a6e20d751156648aa063f3800b706ee209a32c0b4d9f24be3d980b01be55ef" dependencies = [ "proc-macro2", "quote", From 05bfd65b99396fd2bc1cb3c7b7cf538e72d1b2f2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 28 Apr 2025 10:30:37 +0100 Subject: [PATCH 1005/1297] fet: [#1480] new events pacakge It will contain shared logic for handling events in other packages. --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 9 + Cargo.toml | 2 +- packages/events/.gitignore | 1 + packages/events/Cargo.toml | 22 + packages/events/LICENSE | 661 ++++++++++++++++++++++++++++++ packages/events/README.md | 11 + packages/events/src/lib.rs | 2 + 8 files changed, 708 insertions(+), 1 deletion(-) create mode 100644 packages/events/.gitignore create mode 100644 packages/events/Cargo.toml create mode 100644 packages/events/LICENSE create mode 100644 packages/events/README.md create mode 100644 packages/events/src/lib.rs diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 983817273..2ef298eab 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -73,6 +73,7 @@ jobs: cargo publish -p torrust-tracker-clock cargo publish -p torrust-tracker-configuration cargo publish -p torrust-tracker-contrib-bencode + cargo publish -p torrust-tracker-events cargo publish -p torrust-tracker-located-error cargo publish -p torrust-tracker-metrics cargo publish -p torrust-tracker-primitives diff --git a/Cargo.lock b/Cargo.lock index 8f7b1ef6f..e00040f18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4768,6 +4768,15 @@ dependencies = [ "thiserror 2.0.12", ] +[[package]] +name = "torrust-tracker-events" +version = "3.0.0-develop" +dependencies = [ + "futures", + "mockall", + "tokio", +] + [[package]] name = "torrust-tracker-located-error" version = "3.0.0-develop" diff --git a/Cargo.toml b/Cargo.toml index 9243ed483..9b348bfdc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "packages/ torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "packages/test-helpers" } [workspace] -members = ["console/tracker-client"] +members = ["console/tracker-client", "packages/events"] [profile.dev] debug = 1 diff --git a/packages/events/.gitignore b/packages/events/.gitignore new file mode 100644 index 000000000..0b1372e5c --- /dev/null +++ b/packages/events/.gitignore @@ -0,0 +1 @@ +./.coverage diff --git a/packages/events/Cargo.toml b/packages/events/Cargo.toml new file mode 100644 index 000000000..86d6e38f4 --- /dev/null +++ b/packages/events/Cargo.toml @@ -0,0 +1,22 @@ +[package] +description = "A library with functionality to handle events in Torrust tracker packages." +keywords = ["events", "library", "rust", "torrust", "tracker"] +name = "torrust-tracker-events" +readme = "README.md" + +authors.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +futures = "0" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } + +[dev-dependencies] +mockall = "0" diff --git a/packages/events/LICENSE b/packages/events/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/events/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/events/README.md b/packages/events/README.md new file mode 100644 index 000000000..42a5a2f61 --- /dev/null +++ b/packages/events/README.md @@ -0,0 +1,11 @@ +# Torrust Tracker Events + +A library with functionality to handle events in [Torrust Tracker](https://github.com/torrust/torrust-tracker) packages. + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-events). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/events/src/lib.rs b/packages/events/src/lib.rs new file mode 100644 index 000000000..7d59598c3 --- /dev/null +++ b/packages/events/src/lib.rs @@ -0,0 +1,2 @@ +/// Target for tracing crate logs. +pub const EVENTS_TARGET: &str = "EVENTS"; From ff9d1f0b19610af58d2b7f6447873b1c60038687 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 28 Apr 2025 11:06:37 +0100 Subject: [PATCH 1006/1297] feat: [#1480] add event sender trait --- packages/events/src/lib.rs | 2 ++ packages/events/src/sender.rs | 15 +++++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 packages/events/src/sender.rs diff --git a/packages/events/src/lib.rs b/packages/events/src/lib.rs index 7d59598c3..8d7ba2f39 100644 --- a/packages/events/src/lib.rs +++ b/packages/events/src/lib.rs @@ -1,2 +1,4 @@ +pub mod sender; + /// Target for tracing crate logs. pub const EVENTS_TARGET: &str = "EVENTS"; diff --git a/packages/events/src/sender.rs b/packages/events/src/sender.rs new file mode 100644 index 000000000..fe8c6575e --- /dev/null +++ b/packages/events/src/sender.rs @@ -0,0 +1,15 @@ +use futures::future::BoxFuture; +#[cfg(test)] +use mockall::{automock, predicate::str}; +use tokio::sync::broadcast::error::SendError; + +/// Target for tracing crate logs. +pub const EVENTS_TARGET: &str = "EVENTS"; + +/// A trait for sending events. +#[cfg_attr(test, automock(type Event=();))] +pub trait Sender: Sync + Send { + type Event: Send + Clone; + + fn send_event(&self, event: Self::Event) -> BoxFuture<'_, Option>>>; +} From 5ae485d368576db2a29cfd5396160b9e3354bdb0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 28 Apr 2025 11:08:12 +0100 Subject: [PATCH 1007/1297] feat: [#1480] add event sender based on tokio broadcast channel --- packages/events/src/broadcaster.rs | 36 ++++++++++++++++++++++++++++++ packages/events/src/lib.rs | 1 + 2 files changed, 37 insertions(+) create mode 100644 packages/events/src/broadcaster.rs diff --git a/packages/events/src/broadcaster.rs b/packages/events/src/broadcaster.rs new file mode 100644 index 000000000..8f947cc67 --- /dev/null +++ b/packages/events/src/broadcaster.rs @@ -0,0 +1,36 @@ +use futures::future::BoxFuture; +use futures::FutureExt; +use tokio::sync::broadcast::error::SendError; +use tokio::sync::broadcast::{self}; + +use crate::sender::Sender; + +const CHANNEL_CAPACITY: usize = 32768; + +/// An event sender implementation using a broadcast channel. +#[derive(Clone)] +pub struct Broadcaster { + pub(crate) sender: broadcast::Sender, +} + +impl Sender for Broadcaster { + type Event = E; + + fn send_event(&self, event: E) -> BoxFuture<'_, Option>>> { + async move { Some(self.sender.send(event)) }.boxed() + } +} + +impl Default for Broadcaster { + fn default() -> Self { + let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); + Self { sender } + } +} + +impl Broadcaster { + #[must_use] + pub fn subscribe(&self) -> broadcast::Receiver { + self.sender.subscribe() + } +} diff --git a/packages/events/src/lib.rs b/packages/events/src/lib.rs index 8d7ba2f39..154d78f63 100644 --- a/packages/events/src/lib.rs +++ b/packages/events/src/lib.rs @@ -1,3 +1,4 @@ +pub mod broadcaster; pub mod sender; /// Target for tracing crate logs. From 934d45e40a71dfc5e3df038a89e242fbf758abd3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 28 Apr 2025 11:37:44 +0100 Subject: [PATCH 1008/1297] feat: [#1480] add generic EventBus to events package --- packages/events/src/bus.rs | 44 ++++++++++++++++++++++++++++++++++++++ packages/events/src/lib.rs | 1 + 2 files changed, 45 insertions(+) create mode 100644 packages/events/src/bus.rs diff --git a/packages/events/src/bus.rs b/packages/events/src/bus.rs new file mode 100644 index 000000000..d58c8f76d --- /dev/null +++ b/packages/events/src/bus.rs @@ -0,0 +1,44 @@ +use std::sync::Arc; + +use tokio::sync::broadcast::Receiver; + +use crate::broadcaster::Broadcaster; +use crate::sender; + +pub struct EventBus { + pub enable_sender: bool, + pub broadcaster: Broadcaster, +} + +impl Default for EventBus { + fn default() -> Self { + let enable_sender = true; + let broadcaster = Broadcaster::::default(); + + Self::new(enable_sender, broadcaster) + } +} + +impl EventBus { + #[must_use] + pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { + Self { + enable_sender, + broadcaster, + } + } + + #[must_use] + pub fn sender(&self) -> Arc>>> { + if self.enable_sender { + Arc::new(Some(Box::new(self.broadcaster.clone()))) + } else { + Arc::new(None) + } + } + + #[must_use] + pub fn receiver(&self) -> Receiver { + self.broadcaster.subscribe() + } +} diff --git a/packages/events/src/lib.rs b/packages/events/src/lib.rs index 154d78f63..3b02d5d49 100644 --- a/packages/events/src/lib.rs +++ b/packages/events/src/lib.rs @@ -1,4 +1,5 @@ pub mod broadcaster; +pub mod bus; pub mod sender; /// Target for tracing crate logs. From 29b00c800283b55ae936e926b83700d8eea57160 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 28 Apr 2025 12:11:06 +0100 Subject: [PATCH 1009/1297] refactor: [#1480] use the new events crate in http-tracker-core pkg --- Cargo.lock | 2 + packages/axum-http-tracker-server/Cargo.toml | 1 + .../src/v1/handlers/scrape.rs | 2 +- packages/http-tracker-core/Cargo.toml | 1 + .../http-tracker-core/benches/helpers/util.rs | 9 ++-- packages/http-tracker-core/src/container.rs | 4 +- packages/http-tracker-core/src/event/bus.rs | 43 +------------------ .../http-tracker-core/src/event/sender.rs | 42 ++---------------- .../src/services/announce.rs | 23 +++++----- .../http-tracker-core/src/services/scrape.rs | 25 +++++------ .../src/statistics/services.rs | 2 +- 11 files changed, 37 insertions(+), 117 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e00040f18..2b76781bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -588,6 +588,7 @@ dependencies = [ "tokio", "torrust-tracker-clock", "torrust-tracker-configuration", + "torrust-tracker-events", "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", @@ -4560,6 +4561,7 @@ dependencies = [ "torrust-server-lib", "torrust-tracker-clock", "torrust-tracker-configuration", + "torrust-tracker-events", "torrust-tracker-primitives", "torrust-tracker-test-helpers", "tower", diff --git a/packages/axum-http-tracker-server/Cargo.toml b/packages/axum-http-tracker-server/Cargo.toml index 0c64ee986..1b4627d41 100644 --- a/packages/axum-http-tracker-server/Cargo.toml +++ b/packages/axum-http-tracker-server/Cargo.toml @@ -45,6 +45,7 @@ serde_bencode = "0" serde_bytes = "0" serde_repr = "0" torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } uuid = { version = "1", features = ["v4"] } zerocopy = "0.7" diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index 7f1247173..330e7c13e 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -107,7 +107,7 @@ mod tests { } struct CoreHttpTrackerServices { - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: bittorrent_http_tracker_core::event::sender::Sender, } fn initialize_private_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) { diff --git a/packages/http-tracker-core/Cargo.toml b/packages/http-tracker-core/Cargo.toml index 8bd54a483..5473c5a25 100644 --- a/packages/http-tracker-core/Cargo.toml +++ b/packages/http-tracker-core/Cargo.toml @@ -25,6 +25,7 @@ thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } tracing = "0" diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 9d2d80da3..26c59a9d5 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -2,7 +2,6 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; -use bittorrent_http_tracker_core::event; use bittorrent_http_tracker_core::event::bus::EventBus; use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::event::Event; @@ -35,7 +34,7 @@ pub struct CoreTrackerServices { } pub struct CoreHttpTrackerServices { - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: bittorrent_http_tracker_core::event::sender::Sender, } pub fn initialize_core_tracker_services() -> (CoreTrackerServices, CoreHttpTrackerServices) { @@ -125,7 +124,9 @@ pub fn sample_info_hash() -> InfoHash { mock! { HttpStatsEventSender {} - impl event::sender::Sender for HttpStatsEventSender { - fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; + impl torrust_tracker_events::sender::Sender for HttpStatsEventSender { + type Event = Event; + + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index c3ed8a0c7..681d4a4f4 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -17,7 +17,7 @@ pub struct HttpTrackerCoreContainer { // `HttpTrackerCoreServices` pub event_bus: Arc, - pub stats_event_sender: Arc>>, + pub stats_event_sender: event::sender::Sender, pub stats_repository: Arc, pub announce_service: Arc, pub scrape_service: Arc, @@ -59,7 +59,7 @@ impl HttpTrackerCoreContainer { pub struct HttpTrackerCoreServices { pub event_bus: Arc, - pub stats_event_sender: Arc>>, + pub stats_event_sender: event::sender::Sender, pub stats_repository: Arc, pub announce_service: Arc, pub scrape_service: Arc, diff --git a/packages/http-tracker-core/src/event/bus.rs b/packages/http-tracker-core/src/event/bus.rs index 2d22c0a90..02bf71d2f 100644 --- a/packages/http-tracker-core/src/event/bus.rs +++ b/packages/http-tracker-core/src/event/bus.rs @@ -1,44 +1,3 @@ -use std::sync::Arc; - -use tokio::sync::broadcast::Receiver; - -use crate::event::sender::{self, Broadcaster}; use crate::event::Event; -pub struct EventBus { - pub enable_sender: bool, - pub broadcaster: Broadcaster, -} - -impl Default for EventBus { - fn default() -> Self { - let enable_sender = true; - let broadcaster = Broadcaster::default(); - - Self::new(enable_sender, broadcaster) - } -} - -impl EventBus { - #[must_use] - pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { - Self { - enable_sender, - broadcaster, - } - } - - #[must_use] - pub fn sender(&self) -> Arc>> { - if self.enable_sender { - Arc::new(Some(Box::new(self.broadcaster.clone()))) - } else { - Arc::new(None) - } - } - - #[must_use] - pub fn receiver(&self) -> Receiver { - self.broadcaster.subscribe() - } -} +pub type EventBus = torrust_tracker_events::bus::EventBus; diff --git a/packages/http-tracker-core/src/event/sender.rs b/packages/http-tracker-core/src/event/sender.rs index b720926bb..37f64573d 100644 --- a/packages/http-tracker-core/src/event/sender.rs +++ b/packages/http-tracker-core/src/event/sender.rs @@ -1,42 +1,6 @@ -use futures::future::BoxFuture; -use futures::FutureExt; -#[cfg(test)] -use mockall::{automock, predicate::str}; -use tokio::sync::broadcast; -use tokio::sync::broadcast::error::SendError; +use std::sync::Arc; use super::Event; -const CHANNEL_CAPACITY: usize = 32768; - -/// A trait for sending sending. -#[cfg_attr(test, automock)] -pub trait Sender: Sync + Send { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; -} - -/// An event sender implementation using a broadcast channel. -#[derive(Clone)] -pub struct Broadcaster { - pub(crate) sender: broadcast::Sender, -} - -impl Sender for Broadcaster { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { - async move { Some(self.sender.send(event)) }.boxed() - } -} - -impl Default for Broadcaster { - fn default() -> Self { - let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); - Self { sender } - } -} - -impl Broadcaster { - #[must_use] - pub fn subscribe(&self) -> broadcast::Receiver { - self.sender.subscribe() - } -} +pub type Sender = Arc>>>; +pub type Broadcaster = torrust_tracker_events::broadcaster::Broadcaster; diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index bef7449b7..feecb03b1 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -39,7 +39,7 @@ pub struct AnnounceService { announce_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, - opt_http_stats_event_sender: Arc>>, + opt_http_stats_event_sender: event::sender::Sender, } impl AnnounceService { @@ -49,7 +49,7 @@ impl AnnounceService { announce_handler: Arc, authentication_service: Arc, whitelist_authorization: Arc, - opt_http_stats_event_sender: Arc>>, + opt_http_stats_event_sender: event::sender::Sender, ) -> Self { Self { core_config, @@ -228,7 +228,7 @@ mod tests { } struct CoreHttpTrackerServices { - pub http_stats_event_sender: Arc>>, + pub http_stats_event_sender: crate::event::sender::Sender, } fn initialize_core_tracker_services() -> (CoreTrackerServices, CoreHttpTrackerServices) { @@ -302,7 +302,6 @@ mod tests { use mockall::mock; use tokio::sync::broadcast::error::SendError; - use crate::event; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::Event; @@ -312,8 +311,10 @@ mod tests { mock! { HttpStatsEventSender {} - impl event::sender::Sender for HttpStatsEventSender { - fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; + impl torrust_tracker_events::sender::Sender for HttpStatsEventSender { + type Event = Event; + + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } @@ -331,7 +332,6 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; - use crate::event; use crate::event::test::announce_events_match; use crate::event::{ConnectionContext, Event}; use crate::services::announce::tests::{ @@ -411,8 +411,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let http_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services(); @@ -489,8 +488,7 @@ mod tests { .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let http_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services_with_config(&tracker_with_an_ipv6_external_ip()); @@ -537,8 +535,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let http_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let (core_tracker_services, mut core_http_tracker_services) = initialize_core_tracker_services(); core_http_tracker_services.http_stats_event_sender = http_stats_event_sender; diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index a0ae73d97..6ffc4a5f6 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -21,7 +21,6 @@ use torrust_tracker_configuration::Core; use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::service_binding::ServiceBinding; -use crate::event; use crate::event::{ConnectionContext, Event}; /// The HTTP tracker `scrape` service. @@ -40,7 +39,7 @@ pub struct ScrapeService { core_config: Arc, scrape_handler: Arc, authentication_service: Arc, - opt_http_stats_event_sender: Arc>>, + opt_http_stats_event_sender: crate::event::sender::Sender, } impl ScrapeService { @@ -49,7 +48,7 @@ impl ScrapeService { core_config: Arc, scrape_handler: Arc, authentication_service: Arc, - opt_http_stats_event_sender: Arc>>, + opt_http_stats_event_sender: crate::event::sender::Sender, ) -> Self { Self { core_config, @@ -187,7 +186,7 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; - use crate::event::{self, Event}; + use crate::event::Event; use crate::tests::sample_info_hash; struct Container { @@ -239,7 +238,9 @@ mod tests { mock! { HttpStatsEventSender {} - impl event::sender::Sender for HttpStatsEventSender { + impl torrust_tracker_events::sender::Sender for HttpStatsEventSender { + type Event = Event; + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } @@ -259,7 +260,6 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_test_helpers::configuration; - use crate::event; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::{ConnectionContext, Event}; @@ -350,8 +350,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let http_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let container = initialize_services_with_configuration(&config); @@ -405,8 +404,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let http_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let container = initialize_services_with_configuration(&config); @@ -452,7 +450,6 @@ mod tests { use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_test_helpers::configuration; - use crate::event; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::{ConnectionContext, Event}; @@ -537,8 +534,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let http_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let peer_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); @@ -592,8 +588,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let http_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(http_stats_event_sender_mock))); + let http_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(http_stats_event_sender_mock))); let peer_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 7f3c365d4..e2fbfedd0 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -9,7 +9,7 @@ //! //! The factory function builds two structs: //! -//! - An statistics event [`Sender`](crate::statistics::event::sender::Sender) +//! - An statistics event [`Sender`](torrust_tracker_events::sender::Sender) //! - An statistics [`Repository`] //! //! ```text From efed46c6b53fe453e84095f7eaa724f5a8a72aeb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 28 Apr 2025 12:53:15 +0100 Subject: [PATCH 1010/1297] refactor: [#1480] use the new events crate in udp-tracker-core pkg --- Cargo.lock | 2 + packages/udp-tracker-core/Cargo.toml | 1 + .../udp-tracker-core/benches/helpers/utils.rs | 7 +-- packages/udp-tracker-core/src/container.rs | 4 +- packages/udp-tracker-core/src/event/bus.rs | 43 +------------------ packages/udp-tracker-core/src/event/sender.rs | 42 ++---------------- .../udp-tracker-core/src/services/announce.rs | 6 +-- .../udp-tracker-core/src/services/connect.rs | 14 +++--- packages/udp-tracker-core/src/services/mod.rs | 7 +-- .../udp-tracker-core/src/services/scrape.rs | 9 ++-- packages/udp-tracker-server/Cargo.toml | 1 + .../src/handlers/announce.rs | 2 +- .../src/handlers/connect.rs | 4 +- .../udp-tracker-server/src/handlers/mod.rs | 6 ++- 14 files changed, 36 insertions(+), 112 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2b76781bc..f5cba3708 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -703,6 +703,7 @@ dependencies = [ "tokio", "torrust-tracker-clock", "torrust-tracker-configuration", + "torrust-tracker-events", "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", @@ -4874,6 +4875,7 @@ dependencies = [ "torrust-server-lib", "torrust-tracker-clock", "torrust-tracker-configuration", + "torrust-tracker-events", "torrust-tracker-located-error", "torrust-tracker-metrics", "torrust-tracker-primitives", diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml index 0354777db..6cf250074 100644 --- a/packages/udp-tracker-core/Cargo.toml +++ b/packages/udp-tracker-core/Cargo.toml @@ -30,6 +30,7 @@ thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync", "time"] } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } tracing = "0" diff --git a/packages/udp-tracker-core/benches/helpers/utils.rs b/packages/udp-tracker-core/benches/helpers/utils.rs index f6c2f6fad..e560e36fe 100644 --- a/packages/udp-tracker-core/benches/helpers/utils.rs +++ b/packages/udp-tracker-core/benches/helpers/utils.rs @@ -1,6 +1,5 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use bittorrent_udp_tracker_core::event; use bittorrent_udp_tracker_core::event::Event; use futures::future::BoxFuture; use mockall::mock; @@ -20,7 +19,9 @@ pub(crate) fn sample_issue_time() -> f64 { mock! { pub(crate) UdpCoreStatsEventSender {} - impl event::sender::Sender for UdpCoreStatsEventSender { - fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; + impl torrust_tracker_events::sender::Sender for UdpCoreStatsEventSender { + type Event = Event; + + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index c1dd0461f..98c01a703 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -20,7 +20,7 @@ pub struct UdpTrackerCoreContainer { // `UdpTrackerCoreServices` pub event_bus: Arc, - pub stats_event_sender: Arc>>, + pub stats_event_sender: crate::event::sender::Sender, pub stats_repository: Arc, pub ban_service: Arc>, pub connect_service: Arc, @@ -69,7 +69,7 @@ impl UdpTrackerCoreContainer { pub struct UdpTrackerCoreServices { pub event_bus: Arc, - pub stats_event_sender: Arc>>, + pub stats_event_sender: crate::event::sender::Sender, pub stats_repository: Arc, pub ban_service: Arc>, pub connect_service: Arc, diff --git a/packages/udp-tracker-core/src/event/bus.rs b/packages/udp-tracker-core/src/event/bus.rs index 2d22c0a90..02bf71d2f 100644 --- a/packages/udp-tracker-core/src/event/bus.rs +++ b/packages/udp-tracker-core/src/event/bus.rs @@ -1,44 +1,3 @@ -use std::sync::Arc; - -use tokio::sync::broadcast::Receiver; - -use crate::event::sender::{self, Broadcaster}; use crate::event::Event; -pub struct EventBus { - pub enable_sender: bool, - pub broadcaster: Broadcaster, -} - -impl Default for EventBus { - fn default() -> Self { - let enable_sender = true; - let broadcaster = Broadcaster::default(); - - Self::new(enable_sender, broadcaster) - } -} - -impl EventBus { - #[must_use] - pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { - Self { - enable_sender, - broadcaster, - } - } - - #[must_use] - pub fn sender(&self) -> Arc>> { - if self.enable_sender { - Arc::new(Some(Box::new(self.broadcaster.clone()))) - } else { - Arc::new(None) - } - } - - #[must_use] - pub fn receiver(&self) -> Receiver { - self.broadcaster.subscribe() - } -} +pub type EventBus = torrust_tracker_events::bus::EventBus; diff --git a/packages/udp-tracker-core/src/event/sender.rs b/packages/udp-tracker-core/src/event/sender.rs index b720926bb..37f64573d 100644 --- a/packages/udp-tracker-core/src/event/sender.rs +++ b/packages/udp-tracker-core/src/event/sender.rs @@ -1,42 +1,6 @@ -use futures::future::BoxFuture; -use futures::FutureExt; -#[cfg(test)] -use mockall::{automock, predicate::str}; -use tokio::sync::broadcast; -use tokio::sync::broadcast::error::SendError; +use std::sync::Arc; use super::Event; -const CHANNEL_CAPACITY: usize = 32768; - -/// A trait for sending sending. -#[cfg_attr(test, automock)] -pub trait Sender: Sync + Send { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; -} - -/// An event sender implementation using a broadcast channel. -#[derive(Clone)] -pub struct Broadcaster { - pub(crate) sender: broadcast::Sender, -} - -impl Sender for Broadcaster { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { - async move { Some(self.sender.send(event)) }.boxed() - } -} - -impl Default for Broadcaster { - fn default() -> Self { - let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); - Self { sender } - } -} - -impl Broadcaster { - #[must_use] - pub fn subscribe(&self) -> broadcast::Receiver { - self.sender.subscribe() - } -} +pub type Sender = Arc>>>; +pub type Broadcaster = torrust_tracker_events::broadcaster::Broadcaster; diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index def24ffd7..481c3d7ca 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -22,7 +22,7 @@ use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; -use crate::event::{self, ConnectionContext, Event}; +use crate::event::{ConnectionContext, Event}; /// The `AnnounceService` is responsible for handling the `announce` requests. /// @@ -32,7 +32,7 @@ use crate::event::{self, ConnectionContext, Event}; pub struct AnnounceService { announce_handler: Arc, whitelist_authorization: Arc, - opt_udp_core_stats_event_sender: Arc>>, + opt_udp_core_stats_event_sender: crate::event::sender::Sender, } impl AnnounceService { @@ -40,7 +40,7 @@ impl AnnounceService { pub fn new( announce_handler: Arc, whitelist_authorization: Arc, - opt_udp_core_stats_event_sender: Arc>>, + opt_udp_core_stats_event_sender: crate::event::sender::Sender, ) -> Self { Self { announce_handler, diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index b40af901c..a69c84686 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -2,25 +2,24 @@ //! //! The service is responsible for handling the `connect` requests. use std::net::SocketAddr; -use std::sync::Arc; use aquatic_udp_protocol::ConnectionId; use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::connection_cookie::{gen_remote_fingerprint, make}; -use crate::event::{self, ConnectionContext, Event}; +use crate::event::{ConnectionContext, Event}; /// The `ConnectService` is responsible for handling the `connect` requests. /// /// It is responsible for generating the connection cookie and sending the /// appropriate statistics events. pub struct ConnectService { - pub opt_udp_core_stats_event_sender: Arc>>, + pub opt_udp_core_stats_event_sender: crate::event::sender::Sender, } impl ConnectService { #[must_use] - pub fn new(opt_udp_core_stats_event_sender: Arc>>) -> Self { + pub fn new(opt_udp_core_stats_event_sender: crate::event::sender::Sender) -> Self { Self { opt_udp_core_stats_event_sender, } @@ -65,7 +64,6 @@ mod tests { use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::connection_cookie::make; - use crate::event; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::{ConnectionContext, Event}; @@ -153,8 +151,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let opt_udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let opt_udp_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); let connect_service = Arc::new(ConnectService::new(opt_udp_stats_event_sender)); @@ -177,8 +174,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let opt_udp_stats_event_sender: Arc>> = - Arc::new(Some(Box::new(udp_stats_event_sender_mock))); + let opt_udp_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(udp_stats_event_sender_mock))); let connect_service = Arc::new(ConnectService::new(opt_udp_stats_event_sender)); diff --git a/packages/udp-tracker-core/src/services/mod.rs b/packages/udp-tracker-core/src/services/mod.rs index ac82d71e8..8cbae4584 100644 --- a/packages/udp-tracker-core/src/services/mod.rs +++ b/packages/udp-tracker-core/src/services/mod.rs @@ -13,7 +13,6 @@ pub(crate) mod tests { use tokio::sync::broadcast::error::SendError; use crate::connection_cookie::gen_remote_fingerprint; - use crate::event; use crate::event::Event; pub(crate) fn sample_ipv4_remote_addr() -> SocketAddr { @@ -46,8 +45,10 @@ pub(crate) mod tests { mock! { pub(crate) UdpCoreStatsEventSender {} - impl event::sender::Sender for UdpCoreStatsEventSender { - fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; + impl torrust_tracker_events::sender::Sender for UdpCoreStatsEventSender { + type Event = Event; + + fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } } diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index 5b2cf7d46..14ba95834 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -19,7 +19,7 @@ use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; -use crate::event::{self, ConnectionContext, Event}; +use crate::event::{ConnectionContext, Event}; /// The `ScrapeService` is responsible for handling the `scrape` requests. /// @@ -28,15 +28,12 @@ use crate::event::{self, ConnectionContext, Event}; /// - The number of UDP `scrape` requests handled by the UDP tracker. pub struct ScrapeService { scrape_handler: Arc, - opt_udp_stats_event_sender: Arc>>, + opt_udp_stats_event_sender: crate::event::sender::Sender, } impl ScrapeService { #[must_use] - pub fn new( - scrape_handler: Arc, - opt_udp_stats_event_sender: Arc>>, - ) -> Self { + pub fn new(scrape_handler: Arc, opt_udp_stats_event_sender: crate::event::sender::Sender) -> Self { Self { scrape_handler, opt_udp_stats_event_sender, diff --git a/packages/udp-tracker-server/Cargo.toml b/packages/udp-tracker-server/Cargo.toml index 23719d141..4d0296461 100644 --- a/packages/udp-tracker-server/Cargo.toml +++ b/packages/udp-tracker-server/Cargo.toml @@ -29,6 +29,7 @@ tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index f8b2092b5..2f6b71a6a 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -888,7 +888,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_core_stats_event_sender: Arc>> = + let udp_core_stats_event_sender: bittorrent_udp_tracker_core::event::sender::Sender = Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 85bfda680..a950e2c69 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -210,7 +210,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_core_stats_event_sender: Arc>> = + let udp_core_stats_event_sender: bittorrent_udp_tracker_core::event::sender::Sender = Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); @@ -252,7 +252,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_core_stats_event_sender: Arc>> = + let udp_core_stats_event_sender: bittorrent_udp_tracker_core::event::sender::Sender = Arc::new(Some(Box::new(udp_core_stats_event_sender_mock))); let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index dde8f0cc8..6a78d881e 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -426,8 +426,10 @@ pub(crate) mod tests { mock! { pub(crate) UdpCoreStatsEventSender {} - impl core_event::sender::Sender for UdpCoreStatsEventSender { - fn send_event(&self, event: core_event::Event) -> BoxFuture<'static,Option > > > ; + impl torrust_tracker_events::sender::Sender for UdpCoreStatsEventSender { + type Event = core_event::Event; + + fn send_event(&self, event: core_event::Event) -> BoxFuture<'static,Option > > > ; } } From e434e10bd8a355e657609e0da5f8845a811730f5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 28 Apr 2025 16:24:36 +0100 Subject: [PATCH 1011/1297] refactor: [#1480] use the new events crate in udp-tracker-server pkg --- packages/udp-tracker-server/src/container.rs | 4 +- packages/udp-tracker-server/src/event/bus.rs | 43 +------------------ .../udp-tracker-server/src/event/sender.rs | 42 ++---------------- .../src/handlers/announce.rs | 16 +++---- .../src/handlers/connect.rs | 10 ++--- .../udp-tracker-server/src/handlers/error.rs | 5 +-- .../udp-tracker-server/src/handlers/mod.rs | 8 ++-- .../udp-tracker-server/src/handlers/scrape.rs | 11 +++-- 8 files changed, 31 insertions(+), 108 deletions(-) diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs index 121737d92..a0bc8f35b 100644 --- a/packages/udp-tracker-server/src/container.rs +++ b/packages/udp-tracker-server/src/container.rs @@ -10,7 +10,7 @@ use crate::statistics::repository::Repository; pub struct UdpTrackerServerContainer { pub event_bus: Arc, - pub stats_event_sender: Arc>>, + pub stats_event_sender: crate::event::sender::Sender, pub stats_repository: Arc, } @@ -29,7 +29,7 @@ impl UdpTrackerServerContainer { pub struct UdpTrackerServerServices { pub event_bus: Arc, - pub stats_event_sender: Arc>>, + pub stats_event_sender: crate::event::sender::Sender, pub stats_repository: Arc, } diff --git a/packages/udp-tracker-server/src/event/bus.rs b/packages/udp-tracker-server/src/event/bus.rs index 2d22c0a90..02bf71d2f 100644 --- a/packages/udp-tracker-server/src/event/bus.rs +++ b/packages/udp-tracker-server/src/event/bus.rs @@ -1,44 +1,3 @@ -use std::sync::Arc; - -use tokio::sync::broadcast::Receiver; - -use crate::event::sender::{self, Broadcaster}; use crate::event::Event; -pub struct EventBus { - pub enable_sender: bool, - pub broadcaster: Broadcaster, -} - -impl Default for EventBus { - fn default() -> Self { - let enable_sender = true; - let broadcaster = Broadcaster::default(); - - Self::new(enable_sender, broadcaster) - } -} - -impl EventBus { - #[must_use] - pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { - Self { - enable_sender, - broadcaster, - } - } - - #[must_use] - pub fn sender(&self) -> Arc>> { - if self.enable_sender { - Arc::new(Some(Box::new(self.broadcaster.clone()))) - } else { - Arc::new(None) - } - } - - #[must_use] - pub fn receiver(&self) -> Receiver { - self.broadcaster.subscribe() - } -} +pub type EventBus = torrust_tracker_events::bus::EventBus; diff --git a/packages/udp-tracker-server/src/event/sender.rs b/packages/udp-tracker-server/src/event/sender.rs index b720926bb..37f64573d 100644 --- a/packages/udp-tracker-server/src/event/sender.rs +++ b/packages/udp-tracker-server/src/event/sender.rs @@ -1,42 +1,6 @@ -use futures::future::BoxFuture; -use futures::FutureExt; -#[cfg(test)] -use mockall::{automock, predicate::str}; -use tokio::sync::broadcast; -use tokio::sync::broadcast::error::SendError; +use std::sync::Arc; use super::Event; -const CHANNEL_CAPACITY: usize = 32768; - -/// A trait for sending sending. -#[cfg_attr(test, automock)] -pub trait Sender: Sync + Send { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>>; -} - -/// An event sender implementation using a broadcast channel. -#[derive(Clone)] -pub struct Broadcaster { - pub(crate) sender: broadcast::Sender, -} - -impl Sender for Broadcaster { - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { - async move { Some(self.sender.send(event)) }.boxed() - } -} - -impl Default for Broadcaster { - fn default() -> Self { - let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); - Self { sender } - } -} - -impl Broadcaster { - #[must_use] - pub fn subscribe(&self) -> broadcast::Receiver { - self.sender.subscribe() - } -} +pub type Sender = Arc>>>; +pub type Broadcaster = torrust_tracker_events::broadcaster::Broadcaster; diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 2f6b71a6a..2fbddb544 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -16,7 +16,7 @@ use tracing::{instrument, Level}; use zerocopy::network_endian::I32; use crate::error::Error; -use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; +use crate::event::{ConnectionContext, Event, UdpRequestKind}; /// It handles the `Announce` request. /// @@ -30,7 +30,7 @@ pub async fn handle_announce( server_service_binding: ServiceBinding, request: &AnnounceRequest, core_config: &Arc, - opt_udp_server_stats_event_sender: &Arc>>, + opt_udp_server_stats_event_sender: &crate::event::sender::Sender, cookie_valid_range: Range, ) -> Result { tracing::Span::current() @@ -208,7 +208,7 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; - use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; + use crate::event::{ConnectionContext, Event, UdpRequestKind}; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::handlers::handle_announce; use crate::handlers::tests::{ @@ -434,7 +434,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = @@ -540,7 +540,7 @@ mod tests { use torrust_tracker_configuration::Core; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; - use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; + use crate::event::{ConnectionContext, Event, UdpRequestKind}; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::handlers::handle_announce; use crate::handlers::tests::{ @@ -788,7 +788,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = @@ -829,7 +829,7 @@ mod tests { use mockall::predicate::{self, eq}; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; - use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; + use crate::event::{ConnectionContext, Event, UdpRequestKind}; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::handlers::handle_announce; use crate::handlers::tests::{ @@ -900,7 +900,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let announce_handler = Arc::new(AnnounceHandler::new( diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index a950e2c69..9f00298eb 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -7,7 +7,7 @@ use bittorrent_udp_tracker_core::services::connect::ConnectService; use torrust_tracker_primitives::service_binding::ServiceBinding; use tracing::{instrument, Level}; -use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; +use crate::event::{ConnectionContext, Event, UdpRequestKind}; /// It handles the `Connect` request. #[instrument(fields(transaction_id), skip(connect_service, opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] @@ -16,7 +16,7 @@ pub async fn handle_connect( server_service_binding: ServiceBinding, request: &ConnectRequest, connect_service: &Arc, - opt_udp_server_stats_event_sender: &Arc>>, + opt_udp_server_stats_event_sender: &crate::event::sender::Sender, cookie_issue_time: f64, ) -> Response { tracing::Span::current().record("transaction_id", request.transaction_id.0.to_string()); @@ -65,7 +65,7 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; - use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; + use crate::event::{ConnectionContext, Event, UdpRequestKind}; use crate::handlers::handle_connect; use crate::handlers::tests::{ sample_ipv4_remote_addr, sample_ipv4_remote_addr_fingerprint, sample_ipv4_socket_address, sample_ipv6_remote_addr, @@ -222,7 +222,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -264,7 +264,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index 9d9ee8b1d..04b8d073b 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -1,7 +1,6 @@ //! UDP tracker error handling. use std::net::SocketAddr; use std::ops::Range; -use std::sync::Arc; use aquatic_udp_protocol::{ErrorResponse, RequestParseError, Response, TransactionId}; use bittorrent_udp_tracker_core::connection_cookie::{check, gen_remote_fingerprint}; @@ -12,7 +11,7 @@ use uuid::Uuid; use zerocopy::network_endian::I32; use crate::error::Error; -use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; +use crate::event::{ConnectionContext, Event, UdpRequestKind}; #[allow(clippy::too_many_arguments)] #[instrument(fields(transaction_id), skip(opt_udp_server_stats_event_sender), ret(level = Level::TRACE))] @@ -21,7 +20,7 @@ pub async fn handle_error( client_socket_addr: SocketAddr, server_service_binding: ServiceBinding, request_id: Uuid, - opt_udp_server_stats_event_sender: &Arc>>, + opt_udp_server_stats_event_sender: &crate::event::sender::Sender, cookie_valid_range: Range, e: &Error, transaction_id: Option, diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 6a78d881e..18e85e0ce 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -247,7 +247,7 @@ pub(crate) mod tests { } pub(crate) struct ServerUdpTrackerServices { - pub udp_server_stats_event_sender: Arc>>, + pub udp_server_stats_event_sender: crate::event::sender::Sender, } fn default_testing_tracker_configuration() -> Configuration { @@ -435,8 +435,10 @@ pub(crate) mod tests { mock! { pub(crate) UdpServerStatsEventSender {} - impl server_event::sender::Sender for UdpServerStatsEventSender { - fn send_event(&self, event: server_event::Event) -> BoxFuture<'static,Option > > > ; + impl torrust_tracker_events::sender::Sender for UdpServerStatsEventSender { + type Event = server_event::Event; + + fn send_event(&self, event: server_event::Event) -> BoxFuture<'static,Option > > > ; } } } diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 5774bc8e6..b7be10f29 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -14,7 +14,7 @@ use tracing::{instrument, Level}; use zerocopy::network_endian::I32; use crate::error::Error; -use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; +use crate::event::{ConnectionContext, Event, UdpRequestKind}; /// It handles the `Scrape` request. /// @@ -27,7 +27,7 @@ pub async fn handle_scrape( client_socket_addr: SocketAddr, server_service_binding: ServiceBinding, request: &ScrapeRequest, - opt_udp_server_stats_event_sender: &Arc>>, + opt_udp_server_stats_event_sender: &crate::event::sender::Sender, cookie_valid_range: Range, ) -> Result { tracing::Span::current() @@ -363,7 +363,6 @@ mod tests { use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::sample_scrape_request; - use crate::event; use crate::event::{ConnectionContext, Event, UdpRequestKind}; use crate::handlers::handle_scrape; use crate::handlers::tests::{ @@ -386,7 +385,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let (_core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = @@ -414,7 +413,7 @@ mod tests { use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::sample_scrape_request; - use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; + use crate::event::{ConnectionContext, Event, UdpRequestKind}; use crate::handlers::handle_scrape; use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, sample_cookie_valid_range, @@ -436,7 +435,7 @@ mod tests { })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - let udp_server_stats_event_sender: Arc>> = + let udp_server_stats_event_sender: crate::event::sender::Sender = Arc::new(Some(Box::new(udp_server_stats_event_sender_mock))); let (_core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = From 540520c12dd1619dcf67131af8aab648c5760789 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 28 Apr 2025 16:53:12 +0100 Subject: [PATCH 1012/1297] chore: remove unneded explicit pkg inclusion in workspace --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 9b348bfdc..9243ed483 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "packages/ torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "packages/test-helpers" } [workspace] -members = ["console/tracker-client", "packages/events"] +members = ["console/tracker-client"] [profile.dev] debug = 1 From d4343c02e9e0b0f95536164827dfbc016368d243 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 28 Apr 2025 17:59:39 +0100 Subject: [PATCH 1013/1297] fix: [#1485] remove duplicate const --- packages/events/src/sender.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/packages/events/src/sender.rs b/packages/events/src/sender.rs index fe8c6575e..0d901cb82 100644 --- a/packages/events/src/sender.rs +++ b/packages/events/src/sender.rs @@ -3,9 +3,6 @@ use futures::future::BoxFuture; use mockall::{automock, predicate::str}; use tokio::sync::broadcast::error::SendError; -/// Target for tracing crate logs. -pub const EVENTS_TARGET: &str = "EVENTS"; - /// A trait for sending events. #[cfg_attr(test, automock(type Event=();))] pub trait Sender: Sync + Send { From e3703c10660c88ee3b2399a69964b626186e8b27 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 28 Apr 2025 18:47:52 +0100 Subject: [PATCH 1014/1297] feat: [#1485] add Receiver trait to events package --- packages/events/src/broadcaster.rs | 27 ++++++++++++------- packages/events/src/bus.rs | 8 +++--- packages/events/src/lib.rs | 1 + packages/events/src/receiver.rs | 12 +++++++++ packages/http-tracker-core/src/event/mod.rs | 1 + .../http-tracker-core/src/event/receiver.rs | 3 +++ .../src/statistics/event/listener.rs | 8 +++--- packages/udp-tracker-core/src/event/mod.rs | 1 + .../udp-tracker-core/src/event/receiver.rs | 3 +++ .../src/statistics/event/listener.rs | 8 +++--- packages/udp-tracker-server/src/event/mod.rs | 1 + .../udp-tracker-server/src/event/receiver.rs | 3 +++ .../src/statistics/event/listener.rs | 8 +++--- 13 files changed, 58 insertions(+), 26 deletions(-) create mode 100644 packages/events/src/receiver.rs create mode 100644 packages/http-tracker-core/src/event/receiver.rs create mode 100644 packages/udp-tracker-core/src/event/receiver.rs create mode 100644 packages/udp-tracker-server/src/event/receiver.rs diff --git a/packages/events/src/broadcaster.rs b/packages/events/src/broadcaster.rs index 8f947cc67..137e9680c 100644 --- a/packages/events/src/broadcaster.rs +++ b/packages/events/src/broadcaster.rs @@ -1,8 +1,9 @@ use futures::future::BoxFuture; use futures::FutureExt; -use tokio::sync::broadcast::error::SendError; +use tokio::sync::broadcast::error::{RecvError, SendError}; use tokio::sync::broadcast::{self}; +use crate::receiver::Receiver; use crate::sender::Sender; const CHANNEL_CAPACITY: usize = 32768; @@ -13,14 +14,6 @@ pub struct Broadcaster { pub(crate) sender: broadcast::Sender, } -impl Sender for Broadcaster { - type Event = E; - - fn send_event(&self, event: E) -> BoxFuture<'_, Option>>> { - async move { Some(self.sender.send(event)) }.boxed() - } -} - impl Default for Broadcaster { fn default() -> Self { let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); @@ -34,3 +27,19 @@ impl Broadcaster { self.sender.subscribe() } } + +impl Sender for Broadcaster { + type Event = E; + + fn send_event(&self, event: E) -> BoxFuture<'_, Option>>> { + async move { Some(self.sender.send(event)) }.boxed() + } +} + +impl Receiver for broadcast::Receiver { + type Event = E; + + fn recv(&mut self) -> BoxFuture<'_, Result> { + async move { self.recv().await }.boxed() + } +} diff --git a/packages/events/src/bus.rs b/packages/events/src/bus.rs index d58c8f76d..b714741b2 100644 --- a/packages/events/src/bus.rs +++ b/packages/events/src/bus.rs @@ -1,9 +1,7 @@ use std::sync::Arc; -use tokio::sync::broadcast::Receiver; - use crate::broadcaster::Broadcaster; -use crate::sender; +use crate::{receiver, sender}; pub struct EventBus { pub enable_sender: bool, @@ -38,7 +36,7 @@ impl EventBus { } #[must_use] - pub fn receiver(&self) -> Receiver { - self.broadcaster.subscribe() + pub fn receiver(&self) -> Box> { + Box::new(self.broadcaster.subscribe()) } } diff --git a/packages/events/src/lib.rs b/packages/events/src/lib.rs index 3b02d5d49..d933b304c 100644 --- a/packages/events/src/lib.rs +++ b/packages/events/src/lib.rs @@ -1,5 +1,6 @@ pub mod broadcaster; pub mod bus; +pub mod receiver; pub mod sender; /// Target for tracing crate logs. diff --git a/packages/events/src/receiver.rs b/packages/events/src/receiver.rs new file mode 100644 index 000000000..bdbd91616 --- /dev/null +++ b/packages/events/src/receiver.rs @@ -0,0 +1,12 @@ +use futures::future::BoxFuture; +#[cfg(test)] +use mockall::{automock, predicate::str}; +use tokio::sync::broadcast::error::RecvError; + +/// A trait for receiving events. +#[cfg_attr(test, automock(type Event=();))] +pub trait Receiver: Sync + Send { + type Event: Send + Clone; + + fn recv(&mut self) -> BoxFuture<'_, Result>; +} diff --git a/packages/http-tracker-core/src/event/mod.rs b/packages/http-tracker-core/src/event/mod.rs index 5b1c64dca..ad62b0fdc 100644 --- a/packages/http-tracker-core/src/event/mod.rs +++ b/packages/http-tracker-core/src/event/mod.rs @@ -1,4 +1,5 @@ pub mod bus; +pub mod receiver; pub mod sender; use std::net::{IpAddr, SocketAddr}; diff --git a/packages/http-tracker-core/src/event/receiver.rs b/packages/http-tracker-core/src/event/receiver.rs new file mode 100644 index 000000000..8d8e94b64 --- /dev/null +++ b/packages/http-tracker-core/src/event/receiver.rs @@ -0,0 +1,3 @@ +use super::Event; + +pub type Receiver = Box>; diff --git a/packages/http-tracker-core/src/statistics/event/listener.rs b/packages/http-tracker-core/src/statistics/event/listener.rs index 98711f2f5..333f4e588 100644 --- a/packages/http-tracker-core/src/statistics/event/listener.rs +++ b/packages/http-tracker-core/src/statistics/event/listener.rs @@ -1,16 +1,16 @@ use std::sync::Arc; -use tokio::sync::broadcast::{self, Receiver}; +use tokio::sync::broadcast::{self}; use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; use super::handler::handle_event; -use crate::event::Event; +use crate::event::receiver::Receiver; use crate::statistics::repository::Repository; use crate::{CurrentClock, HTTP_TRACKER_LOG_TARGET}; #[must_use] -pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { +pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { let stats_repository = repository.clone(); tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting HTTP tracker core event listener"); @@ -22,7 +22,7 @@ pub fn run_event_listener(receiver: Receiver, repository: &Arc, stats_repository: Arc) { +async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { loop { match receiver.recv().await { Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, diff --git a/packages/udp-tracker-core/src/event/mod.rs b/packages/udp-tracker-core/src/event/mod.rs index babc05fcc..9bdbd7449 100644 --- a/packages/udp-tracker-core/src/event/mod.rs +++ b/packages/udp-tracker-core/src/event/mod.rs @@ -1,4 +1,5 @@ pub mod bus; +pub mod receiver; pub mod sender; use std::net::SocketAddr; diff --git a/packages/udp-tracker-core/src/event/receiver.rs b/packages/udp-tracker-core/src/event/receiver.rs new file mode 100644 index 000000000..8d8e94b64 --- /dev/null +++ b/packages/udp-tracker-core/src/event/receiver.rs @@ -0,0 +1,3 @@ +use super::Event; + +pub type Receiver = Box>; diff --git a/packages/udp-tracker-core/src/statistics/event/listener.rs b/packages/udp-tracker-core/src/statistics/event/listener.rs index 5aa510d04..a8a491e37 100644 --- a/packages/udp-tracker-core/src/statistics/event/listener.rs +++ b/packages/udp-tracker-core/src/statistics/event/listener.rs @@ -1,16 +1,16 @@ use std::sync::Arc; -use tokio::sync::broadcast::{self, Receiver}; +use tokio::sync::broadcast::{self}; use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; use super::handler::handle_event; -use crate::event::Event; +use crate::event::receiver::Receiver; use crate::statistics::repository::Repository; use crate::{CurrentClock, UDP_TRACKER_LOG_TARGET}; #[must_use] -pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { +pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { let stats_repository = repository.clone(); tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker core event listener"); @@ -22,7 +22,7 @@ pub fn run_event_listener(receiver: Receiver, repository: &Arc, stats_repository: Arc) { +async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { loop { match receiver.recv().await { Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, diff --git a/packages/udp-tracker-server/src/event/mod.rs b/packages/udp-tracker-server/src/event/mod.rs index a2140a11c..9ebbc18ef 100644 --- a/packages/udp-tracker-server/src/event/mod.rs +++ b/packages/udp-tracker-server/src/event/mod.rs @@ -1,4 +1,5 @@ pub mod bus; +pub mod receiver; pub mod sender; use std::fmt; diff --git a/packages/udp-tracker-server/src/event/receiver.rs b/packages/udp-tracker-server/src/event/receiver.rs new file mode 100644 index 000000000..8d8e94b64 --- /dev/null +++ b/packages/udp-tracker-server/src/event/receiver.rs @@ -0,0 +1,3 @@ +use super::Event; + +pub type Receiver = Box>; diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index 8e8cc5195..386a4fc33 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -1,17 +1,17 @@ use std::sync::Arc; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; -use tokio::sync::broadcast::{self, Receiver}; +use tokio::sync::broadcast::{self}; use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; use super::handler::handle_event; -use crate::event::Event; +use crate::event::receiver::Receiver; use crate::statistics::repository::Repository; use crate::CurrentClock; #[must_use] -pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { +pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { let stats_repository = repository.clone(); tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker server event listener"); @@ -23,7 +23,7 @@ pub fn run_event_listener(receiver: Receiver, repository: &Arc, stats_repository: Arc) { +async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { loop { match receiver.recv().await { Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, From 3057f486d3a58ed5e4150790433ac5568ec3d55f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 29 Apr 2025 08:07:31 +0100 Subject: [PATCH 1015/1297] refactor: [#1485] decouple events traits from tokio broadcast channel implementation --- packages/events/src/broadcaster.rs | 24 ++++++++++++---- packages/events/src/receiver.rs | 28 ++++++++++++++++++- packages/events/src/sender.rs | 15 +++++++++- .../http-tracker-core/benches/helpers/util.rs | 2 +- .../src/services/announce.rs | 2 +- .../http-tracker-core/src/services/scrape.rs | 2 +- .../src/statistics/event/listener.rs | 6 ++-- .../udp-tracker-core/benches/helpers/utils.rs | 2 +- packages/udp-tracker-core/src/services/mod.rs | 2 +- .../src/statistics/event/listener.rs | 6 ++-- .../udp-tracker-server/src/handlers/mod.rs | 2 +- .../src/statistics/event/listener.rs | 6 ++-- 12 files changed, 75 insertions(+), 22 deletions(-) diff --git a/packages/events/src/broadcaster.rs b/packages/events/src/broadcaster.rs index 137e9680c..6373a14d6 100644 --- a/packages/events/src/broadcaster.rs +++ b/packages/events/src/broadcaster.rs @@ -1,10 +1,9 @@ use futures::future::BoxFuture; use futures::FutureExt; -use tokio::sync::broadcast::error::{RecvError, SendError}; use tokio::sync::broadcast::{self}; -use crate::receiver::Receiver; -use crate::sender::Sender; +use crate::receiver::{Receiver, RecvError}; +use crate::sender::{SendError, Sender}; const CHANNEL_CAPACITY: usize = 32768; @@ -32,7 +31,7 @@ impl Sender for Broadcaster { type Event = E; fn send_event(&self, event: E) -> BoxFuture<'_, Option>>> { - async move { Some(self.sender.send(event)) }.boxed() + async move { Some(self.sender.send(event).map_err(std::convert::Into::into)) }.boxed() } } @@ -40,6 +39,21 @@ impl Receiver for broadcast::Receiver { type Event = E; fn recv(&mut self) -> BoxFuture<'_, Result> { - async move { self.recv().await }.boxed() + async move { self.recv().await.map_err(std::convert::Into::into) }.boxed() + } +} + +impl From> for SendError { + fn from(err: broadcast::error::SendError) -> Self { + SendError(err.0) + } +} + +impl From for RecvError { + fn from(err: broadcast::error::RecvError) -> Self { + match err { + broadcast::error::RecvError::Lagged(amt) => RecvError::Lagged(amt), + broadcast::error::RecvError::Closed => RecvError::Closed, + } } } diff --git a/packages/events/src/receiver.rs b/packages/events/src/receiver.rs index bdbd91616..15adb816a 100644 --- a/packages/events/src/receiver.rs +++ b/packages/events/src/receiver.rs @@ -1,7 +1,8 @@ +use std::fmt; + use futures::future::BoxFuture; #[cfg(test)] use mockall::{automock, predicate::str}; -use tokio::sync::broadcast::error::RecvError; /// A trait for receiving events. #[cfg_attr(test, automock(type Event=();))] @@ -10,3 +11,28 @@ pub trait Receiver: Sync + Send { fn recv(&mut self) -> BoxFuture<'_, Result>; } + +/// An error returned from the [`recv`] function on a [`Receiver`]. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum RecvError { + /// There are no more active senders implying no further messages will ever + /// be sent. + Closed, + + /// The receiver lagged too far behind. Attempting to receive again will + /// return the oldest message still retained by the channel. + /// + /// Includes the number of skipped messages. + Lagged(u64), +} + +impl fmt::Display for RecvError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + RecvError::Closed => write!(f, "channel closed"), + RecvError::Lagged(amt) => write!(f, "channel lagged by {amt}"), + } + } +} + +impl std::error::Error for RecvError {} diff --git a/packages/events/src/sender.rs b/packages/events/src/sender.rs index 0d901cb82..e9205a7dd 100644 --- a/packages/events/src/sender.rs +++ b/packages/events/src/sender.rs @@ -1,7 +1,8 @@ +use std::fmt; + use futures::future::BoxFuture; #[cfg(test)] use mockall::{automock, predicate::str}; -use tokio::sync::broadcast::error::SendError; /// A trait for sending events. #[cfg_attr(test, automock(type Event=();))] @@ -10,3 +11,15 @@ pub trait Sender: Sync + Send { fn send_event(&self, event: Self::Event) -> BoxFuture<'_, Option>>>; } + +/// Error returned by the [`send_event`] function on a [`Sender`]. +#[derive(Debug)] +pub struct SendError(pub Event); + +impl fmt::Display for SendError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "channel closed") + } +} + +impl std::error::Error for SendError {} diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 26c59a9d5..b50c9538b 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -20,8 +20,8 @@ use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; use mockall::mock; -use tokio::sync::broadcast::error::SendError; use torrust_tracker_configuration::{Configuration, Core}; +use torrust_tracker_events::sender::SendError; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index feecb03b1..a9a75a786 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -300,7 +300,7 @@ mod tests { use futures::future::BoxFuture; use mockall::mock; - use tokio::sync::broadcast::error::SendError; + use torrust_tracker_events::sender::SendError; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 6ffc4a5f6..2322e6850 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -182,8 +182,8 @@ mod tests { use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; use mockall::mock; - use tokio::sync::broadcast::error::SendError; use torrust_tracker_configuration::Configuration; + use torrust_tracker_events::sender::SendError; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use crate::event::Event; diff --git a/packages/http-tracker-core/src/statistics/event/listener.rs b/packages/http-tracker-core/src/statistics/event/listener.rs index 333f4e588..37710fb2d 100644 --- a/packages/http-tracker-core/src/statistics/event/listener.rs +++ b/packages/http-tracker-core/src/statistics/event/listener.rs @@ -1,8 +1,8 @@ use std::sync::Arc; -use tokio::sync::broadcast::{self}; use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; +use torrust_tracker_events::receiver::RecvError; use super::handler::handle_event; use crate::event::receiver::Receiver; @@ -28,11 +28,11 @@ async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc handle_event(event, &stats_repository, CurrentClock::now()).await, Err(e) => { match e { - broadcast::error::RecvError::Closed => { + RecvError::Closed => { tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Http core statistics receiver closed."); break; } - broadcast::error::RecvError::Lagged(n) => { + RecvError::Lagged(n) => { // From now on, metrics will be imprecise tracing::warn!(target: HTTP_TRACKER_LOG_TARGET, "Http core statistics receiver lagged by {} events.", n); } diff --git a/packages/udp-tracker-core/benches/helpers/utils.rs b/packages/udp-tracker-core/benches/helpers/utils.rs index e560e36fe..06fa8e6c1 100644 --- a/packages/udp-tracker-core/benches/helpers/utils.rs +++ b/packages/udp-tracker-core/benches/helpers/utils.rs @@ -3,7 +3,7 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use bittorrent_udp_tracker_core::event::Event; use futures::future::BoxFuture; use mockall::mock; -use tokio::sync::broadcast::error::SendError; +use torrust_tracker_events::sender::SendError; pub(crate) fn sample_ipv4_remote_addr() -> SocketAddr { sample_ipv4_socket_address() diff --git a/packages/udp-tracker-core/src/services/mod.rs b/packages/udp-tracker-core/src/services/mod.rs index 8cbae4584..b471edbd1 100644 --- a/packages/udp-tracker-core/src/services/mod.rs +++ b/packages/udp-tracker-core/src/services/mod.rs @@ -10,7 +10,7 @@ pub(crate) mod tests { use futures::future::BoxFuture; use mockall::mock; - use tokio::sync::broadcast::error::SendError; + use torrust_tracker_events::sender::SendError; use crate::connection_cookie::gen_remote_fingerprint; use crate::event::Event; diff --git a/packages/udp-tracker-core/src/statistics/event/listener.rs b/packages/udp-tracker-core/src/statistics/event/listener.rs index a8a491e37..0344fc668 100644 --- a/packages/udp-tracker-core/src/statistics/event/listener.rs +++ b/packages/udp-tracker-core/src/statistics/event/listener.rs @@ -1,8 +1,8 @@ use std::sync::Arc; -use tokio::sync::broadcast::{self}; use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; +use torrust_tracker_events::receiver::RecvError; use super::handler::handle_event; use crate::event::receiver::Receiver; @@ -28,11 +28,11 @@ async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc handle_event(event, &stats_repository, CurrentClock::now()).await, Err(e) => { match e { - broadcast::error::RecvError::Closed => { + RecvError::Closed => { tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp core statistics receiver closed."); break; } - broadcast::error::RecvError::Lagged(n) => { + RecvError::Lagged(n) => { // From now on, metrics will be imprecise tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp core statistics receiver lagged by {} events.", n); } diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 18e85e0ce..72ef6c536 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -225,9 +225,9 @@ pub(crate) mod tests { use bittorrent_udp_tracker_core::{self, event as core_event}; use futures::future::BoxFuture; use mockall::mock; - use tokio::sync::broadcast::error::SendError; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{Configuration, Core}; + use torrust_tracker_events::sender::SendError; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index 386a4fc33..0167b34f6 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -1,9 +1,9 @@ use std::sync::Arc; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; -use tokio::sync::broadcast::{self}; use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; +use torrust_tracker_events::receiver::RecvError; use super::handler::handle_event; use crate::event::receiver::Receiver; @@ -29,11 +29,11 @@ async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc handle_event(event, &stats_repository, CurrentClock::now()).await, Err(e) => { match e { - broadcast::error::RecvError::Closed => { + RecvError::Closed => { tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp server statistics receiver closed."); break; } - broadcast::error::RecvError::Lagged(n) => { + RecvError::Lagged(n) => { // From now on, metrics will be imprecise tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp server statistics receiver lagged by {} events.", n); } From f546bc19b29dfa3a6a0cef990371f1fc0faef4be Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 29 Apr 2025 08:15:39 +0100 Subject: [PATCH 1016/1297] refactor: [#1485] normalize event type parameter name in events pkg --- packages/events/src/broadcaster.rs | 24 ++++++++++++------------ packages/events/src/bus.rs | 16 ++++++++-------- packages/events/src/sender.rs | 2 +- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/packages/events/src/broadcaster.rs b/packages/events/src/broadcaster.rs index 6373a14d6..8be6b0acc 100644 --- a/packages/events/src/broadcaster.rs +++ b/packages/events/src/broadcaster.rs @@ -9,42 +9,42 @@ const CHANNEL_CAPACITY: usize = 32768; /// An event sender implementation using a broadcast channel. #[derive(Clone)] -pub struct Broadcaster { - pub(crate) sender: broadcast::Sender, +pub struct Broadcaster { + pub(crate) sender: broadcast::Sender, } -impl Default for Broadcaster { +impl Default for Broadcaster { fn default() -> Self { let (sender, _) = broadcast::channel(CHANNEL_CAPACITY); Self { sender } } } -impl Broadcaster { +impl Broadcaster { #[must_use] - pub fn subscribe(&self) -> broadcast::Receiver { + pub fn subscribe(&self) -> broadcast::Receiver { self.sender.subscribe() } } -impl Sender for Broadcaster { - type Event = E; +impl Sender for Broadcaster { + type Event = Event; - fn send_event(&self, event: E) -> BoxFuture<'_, Option>>> { + fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { async move { Some(self.sender.send(event).map_err(std::convert::Into::into)) }.boxed() } } -impl Receiver for broadcast::Receiver { - type Event = E; +impl Receiver for broadcast::Receiver { + type Event = Event; fn recv(&mut self) -> BoxFuture<'_, Result> { async move { self.recv().await.map_err(std::convert::Into::into) }.boxed() } } -impl From> for SendError { - fn from(err: broadcast::error::SendError) -> Self { +impl From> for SendError { + fn from(err: broadcast::error::SendError) -> Self { SendError(err.0) } } diff --git a/packages/events/src/bus.rs b/packages/events/src/bus.rs index b714741b2..7e4d3a859 100644 --- a/packages/events/src/bus.rs +++ b/packages/events/src/bus.rs @@ -3,23 +3,23 @@ use std::sync::Arc; use crate::broadcaster::Broadcaster; use crate::{receiver, sender}; -pub struct EventBus { +pub struct EventBus { pub enable_sender: bool, - pub broadcaster: Broadcaster, + pub broadcaster: Broadcaster, } -impl Default for EventBus { +impl Default for EventBus { fn default() -> Self { let enable_sender = true; - let broadcaster = Broadcaster::::default(); + let broadcaster = Broadcaster::::default(); Self::new(enable_sender, broadcaster) } } -impl EventBus { +impl EventBus { #[must_use] - pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { + pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { Self { enable_sender, broadcaster, @@ -27,7 +27,7 @@ impl EventBus { } #[must_use] - pub fn sender(&self) -> Arc>>> { + pub fn sender(&self) -> Arc>>> { if self.enable_sender { Arc::new(Some(Box::new(self.broadcaster.clone()))) } else { @@ -36,7 +36,7 @@ impl EventBus { } #[must_use] - pub fn receiver(&self) -> Box> { + pub fn receiver(&self) -> Box> { Box::new(self.broadcaster.subscribe()) } } diff --git a/packages/events/src/sender.rs b/packages/events/src/sender.rs index e9205a7dd..f5b715524 100644 --- a/packages/events/src/sender.rs +++ b/packages/events/src/sender.rs @@ -22,4 +22,4 @@ impl fmt::Display for SendError { } } -impl std::error::Error for SendError {} +impl std::error::Error for SendError {} From c2df95f24b4119c2a92771a720841ded632ea69a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 29 Apr 2025 08:20:29 +0100 Subject: [PATCH 1017/1297] refactor: [#1485] rename trait fn send_event to send --- packages/events/src/broadcaster.rs | 2 +- packages/events/src/sender.rs | 4 ++-- packages/http-tracker-core/benches/helpers/util.rs | 2 +- packages/http-tracker-core/src/services/announce.rs | 10 +++++----- packages/http-tracker-core/src/services/scrape.rs | 12 ++++++------ packages/udp-tracker-core/benches/helpers/utils.rs | 2 +- packages/udp-tracker-core/src/services/announce.rs | 2 +- packages/udp-tracker-core/src/services/connect.rs | 6 +++--- packages/udp-tracker-core/src/services/mod.rs | 2 +- packages/udp-tracker-core/src/services/scrape.rs | 2 +- packages/udp-tracker-server/src/handlers/announce.rs | 10 +++++----- packages/udp-tracker-server/src/handlers/connect.rs | 10 +++++----- packages/udp-tracker-server/src/handlers/error.rs | 2 +- packages/udp-tracker-server/src/handlers/mod.rs | 4 ++-- packages/udp-tracker-server/src/handlers/scrape.rs | 6 +++--- packages/udp-tracker-server/src/server/launcher.rs | 6 +++--- packages/udp-tracker-server/src/server/processor.rs | 2 +- 17 files changed, 42 insertions(+), 42 deletions(-) diff --git a/packages/events/src/broadcaster.rs b/packages/events/src/broadcaster.rs index 8be6b0acc..caf0d3c85 100644 --- a/packages/events/src/broadcaster.rs +++ b/packages/events/src/broadcaster.rs @@ -30,7 +30,7 @@ impl Broadcaster { impl Sender for Broadcaster { type Event = Event; - fn send_event(&self, event: Event) -> BoxFuture<'_, Option>>> { + fn send(&self, event: Event) -> BoxFuture<'_, Option>>> { async move { Some(self.sender.send(event).map_err(std::convert::Into::into)) }.boxed() } } diff --git a/packages/events/src/sender.rs b/packages/events/src/sender.rs index f5b715524..b979fa481 100644 --- a/packages/events/src/sender.rs +++ b/packages/events/src/sender.rs @@ -9,10 +9,10 @@ use mockall::{automock, predicate::str}; pub trait Sender: Sync + Send { type Event: Send + Clone; - fn send_event(&self, event: Self::Event) -> BoxFuture<'_, Option>>>; + fn send(&self, event: Self::Event) -> BoxFuture<'_, Option>>>; } -/// Error returned by the [`send_event`] function on a [`Sender`]. +/// Error returned by the [`send`] function on a [`Sender`]. #[derive(Debug)] pub struct SendError(pub Event); diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index b50c9538b..7ee91a2c4 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -127,6 +127,6 @@ mock! { impl torrust_tracker_events::sender::Sender for HttpStatsEventSender { type Event = Event; - fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; + fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index a9a75a786..22e30e650 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -146,7 +146,7 @@ impl AnnounceService { tracing::debug!("Sending TcpAnnounce event: {:?}", event); - http_stats_event_sender.send_event(event).await; + http_stats_event_sender.send(event).await; } } } @@ -314,7 +314,7 @@ mod tests { impl torrust_tracker_events::sender::Sender for HttpStatsEventSender { type Event = Event; - fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; + fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } @@ -390,7 +390,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(predicate::function(move |event| { let mut announced_peer = peer_copy; announced_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080); @@ -463,7 +463,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(predicate::function(move |event| { let mut announced_peer = peer_copy; announced_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); @@ -521,7 +521,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(predicate::function(move |event| { let expected_event = Event::TcpAnnounce { connection: ConnectionContext::new( diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 2322e6850..5b58bff22 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -108,7 +108,7 @@ impl ScrapeService { tracing::debug!("Sending TcpScrape event: {:?}", event); - http_stats_event_sender.send_event(event).await; + http_stats_event_sender.send(event).await; } } } @@ -241,7 +241,7 @@ mod tests { impl torrust_tracker_events::sender::Sender for HttpStatsEventSender { type Event = Event; - fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; + fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } @@ -337,7 +337,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::TcpScrape { connection: ConnectionContext::new( RemoteClientAddr::new( @@ -390,7 +390,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::TcpScrape { connection: ConnectionContext::new( RemoteClientAddr::new( @@ -521,7 +521,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::TcpScrape { connection: ConnectionContext::new( RemoteClientAddr::new( @@ -574,7 +574,7 @@ mod tests { let mut http_stats_event_sender_mock = MockHttpStatsEventSender::new(); http_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::TcpScrape { connection: ConnectionContext::new( RemoteClientAddr::new( diff --git a/packages/udp-tracker-core/benches/helpers/utils.rs b/packages/udp-tracker-core/benches/helpers/utils.rs index 06fa8e6c1..f04805001 100644 --- a/packages/udp-tracker-core/benches/helpers/utils.rs +++ b/packages/udp-tracker-core/benches/helpers/utils.rs @@ -22,6 +22,6 @@ mock! { impl torrust_tracker_events::sender::Sender for UdpCoreStatsEventSender { type Event = Event; - fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; + fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index 481c3d7ca..499da2945 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -121,7 +121,7 @@ impl AnnounceService { println!("Sending UdpAnnounce event: {event:?}"); - udp_stats_event_sender.send_event(event).await; + udp_stats_event_sender.send(event).await; } } } diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index a69c84686..a5837dfcc 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -41,7 +41,7 @@ impl ConnectService { if let Some(udp_stats_event_sender) = self.opt_udp_core_stats_event_sender.as_deref() { udp_stats_event_sender - .send_event(Event::UdpConnect { + .send(Event::UdpConnect { connection: ConnectionContext::new(client_socket_addr, server_service_binding), }) .await; @@ -145,7 +145,7 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::UdpConnect { connection: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) @@ -168,7 +168,7 @@ mod tests { let mut udp_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::UdpConnect { connection: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) diff --git a/packages/udp-tracker-core/src/services/mod.rs b/packages/udp-tracker-core/src/services/mod.rs index b471edbd1..64e357b1c 100644 --- a/packages/udp-tracker-core/src/services/mod.rs +++ b/packages/udp-tracker-core/src/services/mod.rs @@ -48,7 +48,7 @@ pub(crate) mod tests { impl torrust_tracker_events::sender::Sender for UdpCoreStatsEventSender { type Event = Event; - fn send_event(&self, event: Event) -> BoxFuture<'static,Option > > > ; + fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } } diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index 14ba95834..b42004f63 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -88,7 +88,7 @@ impl ScrapeService { tracing::debug!(target = crate::UDP_TRACKER_LOG_TARGET, "Sending UdpScrape event: {event:?}"); - udp_stats_event_sender.send_event(event).await; + udp_stats_event_sender.send(event).await; } } } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 2fbddb544..3086ad14d 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -42,7 +42,7 @@ pub async fn handle_announce( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(Event::UdpRequestAccepted { + .send(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Announce, }) @@ -427,7 +427,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Announce, @@ -781,7 +781,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Announce, @@ -873,7 +873,7 @@ mod tests { let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(predicate::function(move |event| { let expected_event = core_event::Event::UdpAnnounce { connection: core_event::ConnectionContext::new( @@ -893,7 +893,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding_clone.clone()), kind: UdpRequestKind::Announce, diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 9f00298eb..f56500af4 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -24,7 +24,7 @@ pub async fn handle_connect( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(Event::UdpRequestAccepted { + .send(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Connect, }) @@ -204,7 +204,7 @@ mod tests { let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(core_event::Event::UdpConnect { connection: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) @@ -215,7 +215,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Connect, @@ -246,7 +246,7 @@ mod tests { let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(core_event::Event::UdpConnect { connection: core_event::ConnectionContext::new(client_socket_addr, server_service_binding.clone()), })) @@ -257,7 +257,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Connect, diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index 04b8d073b..6259e26ca 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -61,7 +61,7 @@ pub async fn handle_error( if e.1.is_some() { if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(Event::UdpError { + .send(Event::UdpError { context: ConnectionContext::new(client_socket_addr, server_service_binding), kind: req_kind, }) diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 72ef6c536..d39ad0972 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -429,7 +429,7 @@ pub(crate) mod tests { impl torrust_tracker_events::sender::Sender for UdpCoreStatsEventSender { type Event = core_event::Event; - fn send_event(&self, event: core_event::Event) -> BoxFuture<'static,Option > > > ; + fn send(&self, event: core_event::Event) -> BoxFuture<'static,Option > > > ; } } @@ -438,7 +438,7 @@ pub(crate) mod tests { impl torrust_tracker_events::sender::Sender for UdpServerStatsEventSender { type Event = server_event::Event; - fn send_event(&self, event: server_event::Event) -> BoxFuture<'static,Option > > > ; + fn send(&self, event: server_event::Event) -> BoxFuture<'static,Option > > > ; } } } diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index b7be10f29..6f3dd0e1a 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -38,7 +38,7 @@ pub async fn handle_scrape( if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(Event::UdpRequestAccepted { + .send(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Scrape, }) @@ -378,7 +378,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Scrape, @@ -428,7 +428,7 @@ mod tests { let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock - .expect_send_event() + .expect_send() .with(eq(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), kind: UdpRequestKind::Scrape, diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index 02b9c8d74..a514921cc 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -184,7 +184,7 @@ impl Launcher { if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(Event::UdpRequestReceived { + .send(Event::UdpRequestReceived { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), }) .await; @@ -195,7 +195,7 @@ impl Launcher { if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(Event::UdpRequestBanned { + .send(Event::UdpRequestBanned { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), }) .await; @@ -235,7 +235,7 @@ impl Launcher { if let Some(udp_server_stats_event_sender) = udp_tracker_server_container.stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(Event::UdpRequestAborted { + .send(Event::UdpRequestAborted { context: ConnectionContext::new(client_socket_addr, server_service_binding), }) .await; diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs index 297919bc3..6b877f85b 100644 --- a/packages/udp-tracker-server/src/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -118,7 +118,7 @@ impl Processor { self.udp_tracker_server_container.stats_event_sender.as_deref() { udp_server_stats_event_sender - .send_event(Event::UdpResponseSent { + .send(Event::UdpResponseSent { context: ConnectionContext::new(client_socket_addr, self.server_service_binding), kind: udp_response_kind, req_processing_time, From 8f5b57e04471d56b1e6e7eade3249a954b1f8666 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 29 Apr 2025 08:42:22 +0100 Subject: [PATCH 1018/1297] refactor: [#1485] replace Arc) { - if config.core.tracker_usage_statistics { - let _job = bittorrent_http_tracker_core::statistics::event::listener::run_event_listener( - app_container.http_tracker_core_services.event_bus.receiver(), - &app_container.http_tracker_core_services.stats_repository, - ); - - // todo: this cannot be enabled otherwise the application never ends - // because the event listener never stops. You see this console message - // forever: - // - // !! shuting down in 90 seconds !! - // 2025-04-24T15:27:45.454101Z INFO graceful_shutdown: torrust_axum_server::signals: remaining alive connections: 0 - // - // Depends on: https://github.com/torrust/torrust-tracker/issues/1405 - - //jobs.push(job); - } + let _job = jobs::http_tracker_core::start_event_listener(config, app_container); + + // todo: this cannot be enabled otherwise the application never ends + // because the event listener never stops. You see this console message + // forever: + // + // !! shuting down in 90 seconds !! + // 2025-04-24T15:27:45.454101Z INFO graceful_shutdown: torrust_axum_server::signals: remaining alive connections: 0 + // + // Depends on: https://github.com/torrust/torrust-tracker/issues/1405 } fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc) { - if config.core.tracker_usage_statistics { - let _job = bittorrent_udp_tracker_core::statistics::event::listener::run_event_listener( - app_container.udp_tracker_core_services.event_bus.receiver(), - &app_container.udp_tracker_core_services.stats_repository, - ); - - // todo: this cannot be enabled otherwise the application never ends - // because the event listener never stops. You see this console message - // forever: - // - // !! shuting down in 90 seconds !! - // 2025-04-24T15:27:45.454101Z INFO graceful_shutdown: torrust_axum_server::signals: remaining alive connections: 0 - // - // Depends on: https://github.com/torrust/torrust-tracker/issues/1405 - - //jobs.push(job); - } + let _job = jobs::udp_tracker_core::start_event_listener(config, app_container); + + // todo: the job cannot be added in the jobs vector otherwise the application never ends + // because the event listener never stops. You see this console message + // forever: + // + // !! shuting down in 90 seconds !! + // 2025-04-24T15:27:45.454101Z INFO graceful_shutdown: torrust_axum_server::signals: remaining alive connections: 0 + // + // Depends on: https://github.com/torrust/torrust-tracker/issues/1405 } fn start_udp_server_event_listener(config: &Configuration, app_container: &Arc) { - if config.core.tracker_usage_statistics { - let _job = torrust_udp_tracker_server::statistics::event::listener::run_event_listener( - app_container.udp_tracker_server_container.event_bus.receiver(), - &app_container.udp_tracker_server_container.stats_repository, - ); - - // todo: this cannot be enabled otherwise the application never ends - // because the event listener never stops. You see this console message - // forever: - // - // !! shuting down in 90 seconds !! - // 2025-04-24T15:27:45.454101Z INFO graceful_shutdown: torrust_axum_server::signals: remaining alive connections: 0 - // - // Depends on: https://github.com/torrust/torrust-tracker/issues/1405 - - //jobs.push(job); - } + let _job = jobs::udp_tracker_server::start_event_listener(config, app_container); + + // todo: the job cannot be added in the jobs vector otherwise the application never ends + // because the event listener never stops. You see this console message + // forever: + // + // !! shuting down in 90 seconds !! + // 2025-04-24T15:27:45.454101Z INFO graceful_shutdown: torrust_axum_server::signals: remaining alive connections: 0 + // + // Depends on: https://github.com/torrust/torrust-tracker/issues/1405 } async fn start_the_udp_instances(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { diff --git a/src/bootstrap/jobs/http_tracker_core.rs b/src/bootstrap/jobs/http_tracker_core.rs new file mode 100644 index 000000000..952c80b40 --- /dev/null +++ b/src/bootstrap/jobs/http_tracker_core.rs @@ -0,0 +1,20 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use torrust_tracker_configuration::Configuration; + +use crate::container::AppContainer; + +pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { + if config.core.tracker_usage_statistics { + let job = bittorrent_http_tracker_core::statistics::event::listener::run_event_listener( + app_container.http_tracker_core_services.event_bus.receiver(), + &app_container.http_tracker_core_services.stats_repository, + ); + + Some(job) + } else { + tracing::info!("HTTP tracker core event listener job is disabled."); + None + } +} diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 8c85ba45b..947b01565 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -7,7 +7,10 @@ //! //! This modules contains all the functions needed to start those jobs. pub mod health_check_api; +pub mod http_tracker_core; pub mod http_tracker; pub mod torrent_cleanup; pub mod tracker_apis; +pub mod udp_tracker_core; +pub mod udp_tracker_server; pub mod udp_tracker; diff --git a/src/bootstrap/jobs/udp_tracker_core.rs b/src/bootstrap/jobs/udp_tracker_core.rs new file mode 100644 index 000000000..689fa8301 --- /dev/null +++ b/src/bootstrap/jobs/udp_tracker_core.rs @@ -0,0 +1,19 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use torrust_tracker_configuration::Configuration; + +use crate::container::AppContainer; + +pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { + if config.core.tracker_usage_statistics { + let job = bittorrent_udp_tracker_core::statistics::event::listener::run_event_listener( + app_container.udp_tracker_core_services.event_bus.receiver(), + &app_container.udp_tracker_core_services.stats_repository, + ); + Some(job) + } else { + tracing::info!("UDP tracker core event listener job is disabled."); + None + } +} diff --git a/src/bootstrap/jobs/udp_tracker_server.rs b/src/bootstrap/jobs/udp_tracker_server.rs new file mode 100644 index 000000000..42ac2d03e --- /dev/null +++ b/src/bootstrap/jobs/udp_tracker_server.rs @@ -0,0 +1,19 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use torrust_tracker_configuration::Configuration; + +use crate::container::AppContainer; + +pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { + if config.core.tracker_usage_statistics { + let job = torrust_udp_tracker_server::statistics::event::listener::run_event_listener( + app_container.udp_tracker_server_container.event_bus.receiver(), + &app_container.udp_tracker_server_container.stats_repository, + ); + Some(job) + } else { + tracing::info!("UDP tracker server event listener job is disabled."); + None + } +} From faf8111f696e0b4ccb178aa4cfe50f05ce24cb50 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 29 Apr 2025 16:05:15 +0100 Subject: [PATCH 1027/1297] fix: [#1477] shutdown event listeners on CRTL+c signal This fixes the problem of adding the jobs for event listeners in the main app JoinHandle vector. It was not possible to add the handles for those tokio tasks becuase in the main app we wait for all jobs and those jobs never end. ```rust async fn main() { let (_app_container, jobs) = app::run().await; // handle the signals tokio::select! { _ = tokio::signal::ctrl_c() => { tracing::info!("Torrust tracker shutting down ..."); // Await for all jobs to shutdown futures::future::join_all(jobs).await; tracing::info!("Torrust tracker successfully shutdown."); } } } ``` Now, we can wait for them becuase they listen for the halt signal. We will implement the shutdown in a different way in a new PR. See https://github.com/torrust/torrust-tracker/issues/1405 Instead of listen to the CRTL+c signal the main app will send a "stop" event to the listeners. The final goal it only the main app listen for this external signal and it propagates the shutdown in cascade via normal internal messages or channels. --- .../src/statistics/event/listener.rs | 36 +++++++++---- .../src/statistics/event/listener.rs | 35 +++++++++---- .../src/statistics/event/listener.rs | 37 +++++++++----- src/app.rs | 51 +++++++------------ src/bootstrap/jobs/mod.rs | 4 +- 5 files changed, 94 insertions(+), 69 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/event/listener.rs b/packages/http-tracker-core/src/statistics/event/listener.rs index 37710fb2d..6730d4c70 100644 --- a/packages/http-tracker-core/src/statistics/event/listener.rs +++ b/packages/http-tracker-core/src/statistics/event/listener.rs @@ -23,18 +23,32 @@ pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> J } async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { + let shutdown_signal = tokio::signal::ctrl_c(); + + tokio::pin!(shutdown_signal); + loop { - match receiver.recv().await { - Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, - Err(e) => { - match e { - RecvError::Closed => { - tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Http core statistics receiver closed."); - break; - } - RecvError::Lagged(n) => { - // From now on, metrics will be imprecise - tracing::warn!(target: HTTP_TRACKER_LOG_TARGET, "Http core statistics receiver lagged by {} events.", n); + tokio::select! { + biased; + + _ = &mut shutdown_signal => { + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Received Ctrl+C, shutting down HTTP tracker core event listener."); + break; + } + + result = receiver.recv() => { + match result { + Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, + Err(e) => { + match e { + RecvError::Closed => { + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Http core statistics receiver closed."); + break; + } + RecvError::Lagged(n) => { + tracing::warn!(target: HTTP_TRACKER_LOG_TARGET, "Http core statistics receiver lagged by {} events.", n); + } + } } } } diff --git a/packages/udp-tracker-core/src/statistics/event/listener.rs b/packages/udp-tracker-core/src/statistics/event/listener.rs index 0344fc668..9b6f2e574 100644 --- a/packages/udp-tracker-core/src/statistics/event/listener.rs +++ b/packages/udp-tracker-core/src/statistics/event/listener.rs @@ -23,18 +23,31 @@ pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> J } async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { + let shutdown_signal = tokio::signal::ctrl_c(); + tokio::pin!(shutdown_signal); + loop { - match receiver.recv().await { - Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, - Err(e) => { - match e { - RecvError::Closed => { - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp core statistics receiver closed."); - break; - } - RecvError::Lagged(n) => { - // From now on, metrics will be imprecise - tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp core statistics receiver lagged by {} events.", n); + tokio::select! { + biased; + + _ = &mut shutdown_signal => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Received Ctrl+C, shutting down UDP tracker core event listener."); + break; + } + + result = receiver.recv() => { + match result { + Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, + Err(e) => { + match e { + RecvError::Closed => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp core statistics receiver closed."); + break; + } + RecvError::Lagged(n) => { + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp core statistics receiver lagged by {} events.", n); + } + } } } } diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index 0167b34f6..d805cc87f 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -19,23 +19,36 @@ pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> J tokio::spawn(async move { dispatch_events(receiver, stats_repository).await; - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "DP tracker server event listener finished"); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker server event listener finished"); }) } async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { + let shutdown_signal = tokio::signal::ctrl_c(); + tokio::pin!(shutdown_signal); + loop { - match receiver.recv().await { - Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, - Err(e) => { - match e { - RecvError::Closed => { - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp server statistics receiver closed."); - break; - } - RecvError::Lagged(n) => { - // From now on, metrics will be imprecise - tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp server statistics receiver lagged by {} events.", n); + tokio::select! { + biased; + + _ = &mut shutdown_signal => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Received Ctrl+C, shutting down UDP tracker server event listener."); + break; + } + + result = receiver.recv() => { + match result { + Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, + Err(e) => { + match e { + RecvError::Closed => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp server statistics receiver closed."); + break; + } + RecvError::Lagged(n) => { + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp server statistics receiver lagged by {} events.", n); + } + } } } } diff --git a/src/app.rs b/src/app.rs index cd41bcd85..fcce6336c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -66,9 +66,9 @@ async fn load_data_from_database(config: &Configuration, app_container: &Arc) -> Vec> { let mut jobs: Vec> = Vec::new(); - start_http_core_event_listener(config, app_container); - start_udp_core_event_listener(config, app_container); - start_udp_server_event_listener(config, app_container); + start_http_core_event_listener(config, app_container, &mut jobs); + start_udp_core_event_listener(config, app_container, &mut jobs); + start_udp_server_event_listener(config, app_container, &mut jobs); start_the_udp_instances(config, app_container, &mut jobs).await; start_the_http_instances(config, app_container, &mut jobs).await; start_the_http_api(config, app_container, &mut jobs).await; @@ -109,43 +109,28 @@ async fn load_whitelisted_torrents(config: &Configuration, app_container: &Arc) { - let _job = jobs::http_tracker_core::start_event_listener(config, app_container); +fn start_http_core_event_listener(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { + let opt_job = jobs::http_tracker_core::start_event_listener(config, app_container); - // todo: this cannot be enabled otherwise the application never ends - // because the event listener never stops. You see this console message - // forever: - // - // !! shuting down in 90 seconds !! - // 2025-04-24T15:27:45.454101Z INFO graceful_shutdown: torrust_axum_server::signals: remaining alive connections: 0 - // - // Depends on: https://github.com/torrust/torrust-tracker/issues/1405 + if let Some(job) = opt_job { + jobs.push(job); + } } -fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc) { - let _job = jobs::udp_tracker_core::start_event_listener(config, app_container); +fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { + let opt_job = jobs::udp_tracker_core::start_event_listener(config, app_container); - // todo: the job cannot be added in the jobs vector otherwise the application never ends - // because the event listener never stops. You see this console message - // forever: - // - // !! shuting down in 90 seconds !! - // 2025-04-24T15:27:45.454101Z INFO graceful_shutdown: torrust_axum_server::signals: remaining alive connections: 0 - // - // Depends on: https://github.com/torrust/torrust-tracker/issues/1405 + if let Some(job) = opt_job { + jobs.push(job); + } } -fn start_udp_server_event_listener(config: &Configuration, app_container: &Arc) { - let _job = jobs::udp_tracker_server::start_event_listener(config, app_container); +fn start_udp_server_event_listener(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { + let opt_job = jobs::udp_tracker_server::start_event_listener(config, app_container); - // todo: the job cannot be added in the jobs vector otherwise the application never ends - // because the event listener never stops. You see this console message - // forever: - // - // !! shuting down in 90 seconds !! - // 2025-04-24T15:27:45.454101Z INFO graceful_shutdown: torrust_axum_server::signals: remaining alive connections: 0 - // - // Depends on: https://github.com/torrust/torrust-tracker/issues/1405 + if let Some(job) = opt_job { + jobs.push(job); + } } async fn start_the_udp_instances(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 947b01565..579618d09 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -7,10 +7,10 @@ //! //! This modules contains all the functions needed to start those jobs. pub mod health_check_api; -pub mod http_tracker_core; pub mod http_tracker; +pub mod http_tracker_core; pub mod torrent_cleanup; pub mod tracker_apis; +pub mod udp_tracker; pub mod udp_tracker_core; pub mod udp_tracker_server; -pub mod udp_tracker; From 53fdafdaabec22001038831758611a28e8970b82 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 29 Apr 2025 17:43:13 +0100 Subject: [PATCH 1028/1297] feat: [#1477] extract JobManager to handle jobs It: - Give a name to all jobs so they can be identify later in logs. - Wait for all jobs to finish when the app receives teh halt signal (CRTL+c) - Only waits for a grace period per job. - Shows a message when a job don't complete in time. This could be improved in the future: - By showing a message every second while we are waiting for a job to finish. - Waiting for all of them in paralell. --- src/app.rs | 113 ++++++++++++++++++---------------- src/bootstrap/jobs/manager.rs | 89 ++++++++++++++++++++++++++ src/bootstrap/jobs/mod.rs | 1 + src/console/profiling.rs | 3 +- src/main.rs | 6 +- 5 files changed, 154 insertions(+), 58 deletions(-) create mode 100644 src/bootstrap/jobs/manager.rs diff --git a/src/app.rs b/src/app.rs index fcce6336c..8f5c6ca4c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -23,15 +23,15 @@ //! - Tracker REST API: the tracker API can be enabled/disabled. use std::sync::Arc; -use tokio::task::JoinHandle; use torrust_tracker_configuration::{Configuration, HttpTracker, UdpTracker}; use tracing::instrument; +use crate::bootstrap::jobs::manager::JobManager; use crate::bootstrap::jobs::{self, health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; use crate::bootstrap::{self}; use crate::container::AppContainer; -pub async fn run() -> (Arc, Vec>) { +pub async fn run() -> (Arc, JobManager) { let (config, app_container) = bootstrap::app::setup(); let app_container = Arc::new(app_container); @@ -50,7 +50,7 @@ pub async fn run() -> (Arc, Vec>) { /// - Can't retrieve tracker keys from database. /// - Can't load whitelist from database. #[instrument(skip(config, app_container))] -pub async fn start(config: &Configuration, app_container: &Arc) -> Vec> { +pub async fn start(config: &Configuration, app_container: &Arc) -> JobManager { warn_if_no_services_enabled(config); load_data_from_database(config, app_container).await; @@ -63,19 +63,19 @@ async fn load_data_from_database(config: &Configuration, app_container: &Arc) -> Vec> { - let mut jobs: Vec> = Vec::new(); +async fn start_jobs(config: &Configuration, app_container: &Arc) -> JobManager { + let mut job_manager = JobManager::new(); - start_http_core_event_listener(config, app_container, &mut jobs); - start_udp_core_event_listener(config, app_container, &mut jobs); - start_udp_server_event_listener(config, app_container, &mut jobs); - start_the_udp_instances(config, app_container, &mut jobs).await; - start_the_http_instances(config, app_container, &mut jobs).await; - start_the_http_api(config, app_container, &mut jobs).await; - start_torrent_cleanup(config, app_container, &mut jobs); - start_health_check_api(config, app_container, &mut jobs).await; + start_http_core_event_listener(config, app_container, &mut job_manager); + start_udp_core_event_listener(config, app_container, &mut job_manager); + start_udp_server_event_listener(config, app_container, &mut job_manager); + start_the_udp_instances(config, app_container, &mut job_manager).await; + start_the_http_instances(config, app_container, &mut job_manager).await; + start_the_http_api(config, app_container, &mut job_manager).await; + start_torrent_cleanup(config, app_container, &mut job_manager); + start_health_check_api(config, app_container, &mut job_manager).await; - jobs + job_manager } fn warn_if_no_services_enabled(config: &Configuration) { @@ -109,40 +109,40 @@ async fn load_whitelisted_torrents(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { - let opt_job = jobs::http_tracker_core::start_event_listener(config, app_container); +fn start_http_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + let opt_handle = jobs::http_tracker_core::start_event_listener(config, app_container); - if let Some(job) = opt_job { - jobs.push(job); + if let Some(handle) = opt_handle { + job_manager.push("http_core_event_listener", handle); } } -fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { - let opt_job = jobs::udp_tracker_core::start_event_listener(config, app_container); +fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + let opt_handle = jobs::udp_tracker_core::start_event_listener(config, app_container); - if let Some(job) = opt_job { - jobs.push(job); + if let Some(handle) = opt_handle { + job_manager.push("udp_core_event_listener", handle); } } -fn start_udp_server_event_listener(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { - let opt_job = jobs::udp_tracker_server::start_event_listener(config, app_container); +fn start_udp_server_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + let opt_handle = jobs::udp_tracker_server::start_event_listener(config, app_container); - if let Some(job) = opt_job { - jobs.push(job); + if let Some(handle) = opt_handle { + job_manager.push("udp_server_event_listener", handle); } } -async fn start_the_udp_instances(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { +async fn start_the_udp_instances(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { if let Some(udp_trackers) = &config.udp_trackers { - for udp_tracker_config in udp_trackers { + for (idx, udp_tracker_config) in udp_trackers.iter().enumerate() { if config.core.private { tracing::warn!( "Could not start UDP tracker on: {} while in private mode. UDP is not safe for private trackers!", udp_tracker_config.bind_address ); } else { - start_udp_instance(udp_tracker_config, app_container, jobs).await; + start_udp_instance(idx, udp_tracker_config, app_container, job_manager).await; } } } else { @@ -150,26 +150,31 @@ async fn start_the_udp_instances(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { +async fn start_udp_instance( + idx: usize, + udp_tracker_config: &UdpTracker, + app_container: &Arc, + job_manager: &mut JobManager, +) { let udp_tracker_container = app_container .udp_tracker_container(udp_tracker_config.bind_address) .expect("Could not create UDP tracker container"); let udp_tracker_server_container = app_container.udp_tracker_server_container(); - jobs.push( - udp_tracker::start_job( - udp_tracker_container, - udp_tracker_server_container, - app_container.registar.give_form(), - ) - .await, - ); + let handle = udp_tracker::start_job( + udp_tracker_container, + udp_tracker_server_container, + app_container.registar.give_form(), + ) + .await; + + job_manager.push(format!("udp_instance_{}_{}", idx, udp_tracker_config.bind_address), handle); } -async fn start_the_http_instances(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { +async fn start_the_http_instances(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { if let Some(http_trackers) = &config.http_trackers { - for http_tracker_config in http_trackers { - start_http_instance(http_tracker_config, app_container, jobs).await; + for (idx, http_tracker_config) in http_trackers.iter().enumerate() { + start_http_instance(idx, http_tracker_config, app_container, job_manager).await; } } else { tracing::info!("No HTTP blocks in configuration"); @@ -177,26 +182,27 @@ async fn start_the_http_instances(config: &Configuration, app_container: &Arc, - jobs: &mut Vec>, + job_manager: &mut JobManager, ) { let http_tracker_container = app_container .http_tracker_container(http_tracker_config.bind_address) .expect("Could not create HTTP tracker container"); - if let Some(job) = http_tracker::start_job( + if let Some(handle) = http_tracker::start_job( http_tracker_container, app_container.registar.give_form(), torrust_axum_http_tracker_server::Version::V1, ) .await { - jobs.push(job); + job_manager.push(format!("http_instance_{}_{}", idx, http_tracker_config.bind_address), handle); } } -async fn start_the_http_api(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { +async fn start_the_http_api(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { if let Some(http_api_config) = &config.http_api { let http_api_config = Arc::new(http_api_config.clone()); let http_api_container = app_container.tracker_http_api_container(&http_api_config); @@ -208,22 +214,23 @@ async fn start_the_http_api(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { +fn start_torrent_cleanup(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { if config.core.inactive_peer_cleanup_interval > 0 { - jobs.push(torrent_cleanup::start_job( - &config.core, - &app_container.tracker_core_container.torrents_manager, - )); + let handle = torrent_cleanup::start_job(&config.core, &app_container.tracker_core_container.torrents_manager); + + job_manager.push("torrent_cleanup", handle); } } -async fn start_health_check_api(config: &Configuration, app_container: &Arc, jobs: &mut Vec>) { - jobs.push(health_check_api::start_job(&config.health_check_api, app_container.registar.entries()).await); +async fn start_health_check_api(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + let handle = health_check_api::start_job(&config.health_check_api, app_container.registar.entries()).await; + + job_manager.push("health_check_api", handle); } diff --git a/src/bootstrap/jobs/manager.rs b/src/bootstrap/jobs/manager.rs new file mode 100644 index 000000000..5beab3224 --- /dev/null +++ b/src/bootstrap/jobs/manager.rs @@ -0,0 +1,89 @@ +use std::time::Duration; + +use tokio::task::JoinHandle; +use tokio::time::timeout; +use tracing::{info, warn}; + +/// Represents a named background job. +#[derive(Debug)] +pub struct Job { + pub name: String, + pub handle: JoinHandle<()>, +} + +impl Job { + pub fn new>(name: N, handle: JoinHandle<()>) -> Self { + Self { + name: name.into(), + handle, + } + } +} + +/// Manages multiple background jobs. +#[derive(Debug, Default)] +pub struct JobManager { + jobs: Vec, +} + +impl JobManager { + #[must_use] + pub fn new() -> Self { + Self { jobs: Vec::new() } + } + + pub fn push>(&mut self, name: N, handle: JoinHandle<()>) { + self.jobs.push(Job::new(name, handle)); + } + + /// Waits sequentially for all jobs to complete, with a graceful timeout per + /// job. + pub async fn wait_for_all(mut self, grace_period: Duration) { + for job in self.jobs.drain(..) { + let name = job.name.clone(); + + info!(job = %name, "Waiting for job to finish (timeout of {} seconds) ...", grace_period.as_secs()); + + if let Ok(result) = timeout(grace_period, job.handle).await { + if let Err(e) = result { + warn!(job = %name, "Job return an error: {:?}", e); + } else { + info!(job = %name, "Job completed gracefully"); + } + } else { + warn!(job = %name, "Job did not complete in time"); + } + } + } +} + +#[cfg(test)] +mod tests { + use tokio::time::Duration; + + use super::*; + + #[tokio::test] + async fn it_should_wait_for_all_jobs_to_finish() { + let mut manager = JobManager::new(); + + manager.push("job1", tokio::spawn(async {})); + manager.push("job2", tokio::spawn(async {})); + + manager.wait_for_all(Duration::from_secs(1)).await; + } + + #[tokio::test] + async fn it_should_log_when_a_job_panics() { + let mut manager = JobManager::new(); + + manager.push( + "panic_job", + tokio::spawn(async { + panic!("expected panic"); + }), + ); + + manager.wait_for_all(Duration::from_secs(1)).await; + } +} diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 579618d09..2e3d798ad 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -9,6 +9,7 @@ pub mod health_check_api; pub mod http_tracker; pub mod http_tracker_core; +pub mod manager; pub mod torrent_cleanup; pub mod tracker_apis; pub mod udp_tracker; diff --git a/src/console/profiling.rs b/src/console/profiling.rs index 873dbb574..df44f4009 100644 --- a/src/console/profiling.rs +++ b/src/console/profiling.rs @@ -191,8 +191,7 @@ pub async fn run() { _ = tokio::signal::ctrl_c() => { tracing::info!("Torrust tracker shutting down via Ctrl+C ..."); - // Await for all jobs to shutdown - futures::future::join_all(jobs).await; + jobs.wait_for_all(Duration::from_secs(10)).await; } } diff --git a/src/main.rs b/src/main.rs index 8ba4311f7..a49c3aeba 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,16 +1,16 @@ +use std::time::Duration; + use torrust_tracker_lib::app; #[tokio::main] async fn main() { let (_app_container, jobs) = app::run().await; - // handle the signals tokio::select! { _ = tokio::signal::ctrl_c() => { tracing::info!("Torrust tracker shutting down ..."); - // Await for all jobs to shutdown - futures::future::join_all(jobs).await; + jobs.wait_for_all(Duration::from_secs(10)).await; tracing::info!("Torrust tracker successfully shutdown."); } From 8f42271efad18c7fe3563440156fee8b0f719d7f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 29 Apr 2025 17:52:49 +0100 Subject: [PATCH 1029/1297] chore: [#1477] remove unused dependency --- Cargo.lock | 1 - Cargo.toml | 1 - 2 files changed, 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f5cba3708..686af7854 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4684,7 +4684,6 @@ dependencies = [ "bittorrent-udp-tracker-core", "chrono", "clap", - "futures", "local-ip-address", "mockall", "rand 0.9.1", diff --git a/Cargo.toml b/Cargo.toml index 9243ed483..c5ce7c216 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,7 +40,6 @@ bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker- bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "packages/udp-tracker-core" } chrono = { version = "0", default-features = false, features = ["clock"] } clap = { version = "4", features = ["derive", "env"] } -futures = "0" rand = "0" regex = "1" reqwest = { version = "0", features = ["json"] } From 3d53b236d914282937790e3ec4ab3bff1b2dcb27 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 30 Apr 2025 11:35:05 +0100 Subject: [PATCH 1030/1297] feat: [#1491] copy torrent repo benchmarking into a new pkg It will be removed from the `torrent-repository` package, keeping only data strcutures used in production. --- .github/workflows/deployment.yaml | 1 + Cargo.lock | 20 + Cargo.toml | 2 +- .../Cargo.toml | 38 ++ .../torrent-repository-benchmarking/README.md | 32 + .../benches/helpers/asyn.rs | 153 +++++ .../benches/helpers/mod.rs | 3 + .../benches/helpers/sync.rs | 155 +++++ .../benches/helpers/utils.rs | 41 ++ .../benches/repository_benchmark.rs | 270 ++++++++ .../src/entry/mod.rs | 92 +++ .../src/entry/mutex_parking_lot.rs | 49 ++ .../src/entry/mutex_std.rs | 51 ++ .../src/entry/mutex_tokio.rs | 49 ++ .../src/entry/peer_list.rs | 286 ++++++++ .../src/entry/rw_lock_parking_lot.rs | 49 ++ .../src/entry/single.rs | 81 +++ .../src/lib.rs | 44 ++ .../src/repository/dash_map_mutex_std.rs | 111 +++ .../src/repository/mod.rs | 46 ++ .../src/repository/rw_lock_std.rs | 132 ++++ .../src/repository/rw_lock_std_mutex_std.rs | 130 ++++ .../src/repository/rw_lock_std_mutex_tokio.rs | 167 +++++ .../src/repository/rw_lock_tokio.rs | 138 ++++ .../src/repository/rw_lock_tokio_mutex_std.rs | 135 ++++ .../repository/rw_lock_tokio_mutex_tokio.rs | 148 ++++ .../src/repository/skip_map_mutex_std.rs | 328 +++++++++ .../tests/common/mod.rs | 3 + .../tests/common/repo.rs | 242 +++++++ .../tests/common/torrent.rs | 101 +++ .../tests/common/torrent_peer_builder.rs | 90 +++ .../tests/entry/mod.rs | 443 ++++++++++++ .../tests/integration.rs | 22 + .../tests/repository/mod.rs | 639 ++++++++++++++++++ 34 files changed, 4290 insertions(+), 1 deletion(-) create mode 100644 packages/torrent-repository-benchmarking/Cargo.toml create mode 100644 packages/torrent-repository-benchmarking/README.md create mode 100644 packages/torrent-repository-benchmarking/benches/helpers/asyn.rs create mode 100644 packages/torrent-repository-benchmarking/benches/helpers/mod.rs create mode 100644 packages/torrent-repository-benchmarking/benches/helpers/sync.rs create mode 100644 packages/torrent-repository-benchmarking/benches/helpers/utils.rs create mode 100644 packages/torrent-repository-benchmarking/benches/repository_benchmark.rs create mode 100644 packages/torrent-repository-benchmarking/src/entry/mod.rs create mode 100644 packages/torrent-repository-benchmarking/src/entry/mutex_parking_lot.rs create mode 100644 packages/torrent-repository-benchmarking/src/entry/mutex_std.rs create mode 100644 packages/torrent-repository-benchmarking/src/entry/mutex_tokio.rs create mode 100644 packages/torrent-repository-benchmarking/src/entry/peer_list.rs create mode 100644 packages/torrent-repository-benchmarking/src/entry/rw_lock_parking_lot.rs create mode 100644 packages/torrent-repository-benchmarking/src/entry/single.rs create mode 100644 packages/torrent-repository-benchmarking/src/lib.rs create mode 100644 packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs create mode 100644 packages/torrent-repository-benchmarking/src/repository/mod.rs create mode 100644 packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs create mode 100644 packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs create mode 100644 packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs create mode 100644 packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs create mode 100644 packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs create mode 100644 packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs create mode 100644 packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs create mode 100644 packages/torrent-repository-benchmarking/tests/common/mod.rs create mode 100644 packages/torrent-repository-benchmarking/tests/common/repo.rs create mode 100644 packages/torrent-repository-benchmarking/tests/common/torrent.rs create mode 100644 packages/torrent-repository-benchmarking/tests/common/torrent_peer_builder.rs create mode 100644 packages/torrent-repository-benchmarking/tests/entry/mod.rs create mode 100644 packages/torrent-repository-benchmarking/tests/integration.rs create mode 100644 packages/torrent-repository-benchmarking/tests/repository/mod.rs diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 2ef298eab..d62b4bbcc 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -78,5 +78,6 @@ jobs: cargo publish -p torrust-tracker-metrics cargo publish -p torrust-tracker-primitives cargo publish -p torrust-tracker-test-helpers + cargo publish -p torrust-tracker-torrent-benchmarking cargo publish -p torrust-tracker-torrent-repository cargo publish -p torrust-udp-tracker-server diff --git a/Cargo.lock b/Cargo.lock index 686af7854..da46a5a8f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4852,6 +4852,26 @@ dependencies = [ "zerocopy 0.7.35", ] +[[package]] +name = "torrust-tracker-torrent-repository-benchmarking" +version = "3.0.0-develop" +dependencies = [ + "aquatic_udp_protocol", + "async-std", + "bittorrent-primitives", + "criterion", + "crossbeam-skiplist", + "dashmap", + "futures", + "parking_lot", + "rstest", + "tokio", + "torrust-tracker-clock", + "torrust-tracker-configuration", + "torrust-tracker-primitives", + "zerocopy 0.7.35", +] + [[package]] name = "torrust-udp-tracker-server" version = "3.0.0-develop" diff --git a/Cargo.toml b/Cargo.toml index c5ce7c216..a15ff78df 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,7 +68,7 @@ torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "packages/ torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "packages/test-helpers" } [workspace] -members = ["console/tracker-client"] +members = ["console/tracker-client", "packages/torrent-repository-benchmarking"] [profile.dev] debug = 1 diff --git a/packages/torrent-repository-benchmarking/Cargo.toml b/packages/torrent-repository-benchmarking/Cargo.toml new file mode 100644 index 000000000..1a93c513c --- /dev/null +++ b/packages/torrent-repository-benchmarking/Cargo.toml @@ -0,0 +1,38 @@ +[package] +description = "A library to runt benchmarking for different implementations of a repository of torrents files and their peers." +keywords = ["library", "repository", "torrents"] +name = "torrust-tracker-torrent-repository-benchmarking" +readme = "README.md" + +authors.workspace = true +categories.workspace = true +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +license.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +aquatic_udp_protocol = "0" +bittorrent-primitives = "0.1.0" +crossbeam-skiplist = "0" +dashmap = "6" +futures = "0" +parking_lot = "0" +tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } +torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +zerocopy = "0.7" + +[dev-dependencies] +async-std = { version = "1", features = ["attributes", "tokio1"] } +criterion = { version = "0", features = ["async_tokio"] } +rstest = "0" + +[[bench]] +harness = false +name = "repository_benchmark" diff --git a/packages/torrent-repository-benchmarking/README.md b/packages/torrent-repository-benchmarking/README.md new file mode 100644 index 000000000..f248ca0da --- /dev/null +++ b/packages/torrent-repository-benchmarking/README.md @@ -0,0 +1,32 @@ +# Torrust Tracker Torrent Repository Benchmarking + +A library to runt benchmarking for different implementations of a repository of torrents files and their peers. Torrent repositories are used by the [Torrust Tracker](https://github.com/torrust/torrust-tracker). + +## Benchmarking + +```console +cargo bench -p torrust-tracker-torrent-repository +``` + +Example partial output: + +```output + Running benches/repository_benchmark.rs (target/release/deps/repository_benchmark-a9b0013c8d09c3c3) +add_one_torrent/RwLockStd + time: [63.057 ns 63.242 ns 63.506 ns] +Found 12 outliers among 100 measurements (12.00%) + 2 (2.00%) low severe + 2 (2.00%) low mild + 2 (2.00%) high mild + 6 (6.00%) high severe +add_one_torrent/RwLockStdMutexStd + time: [62.505 ns 63.077 ns 63.817 ns] +``` + +## Documentation + +[Crate documentation](https://docs.rs/torrust-tracker-torrent-repository). + +## License + +The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). diff --git a/packages/torrent-repository-benchmarking/benches/helpers/asyn.rs b/packages/torrent-repository-benchmarking/benches/helpers/asyn.rs new file mode 100644 index 000000000..4deb1955a --- /dev/null +++ b/packages/torrent-repository-benchmarking/benches/helpers/asyn.rs @@ -0,0 +1,153 @@ +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use bittorrent_primitives::info_hash::InfoHash; +use futures::stream::FuturesUnordered; +use torrust_tracker_torrent_repository_benchmarking::repository::RepositoryAsync; + +use super::utils::{generate_unique_info_hashes, DEFAULT_PEER}; + +pub async fn add_one_torrent(samples: u64) -> Duration +where + V: RepositoryAsync + Default, +{ + let start = Instant::now(); + + for _ in 0..samples { + let torrent_repository = V::default(); + + let info_hash = InfoHash::default(); + + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; + + torrent_repository.get_swarm_metadata(&info_hash).await; + } + + start.elapsed() +} + +// Add one torrent ten thousand times in parallel (depending on the set worker threads) +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: u64, sleep: Option) -> Duration +where + V: RepositoryAsync + Default, + Arc: Clone + Send + Sync + 'static, +{ + let torrent_repository = Arc::::default(); + let info_hash = InfoHash::default(); + let handles = FuturesUnordered::new(); + + // Add the torrent/peer to the torrent repository + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; + + torrent_repository.get_swarm_metadata(&info_hash).await; + + let start = Instant::now(); + + for _ in 0..samples { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; + + torrent_repository_clone.get_swarm_metadata(&info_hash).await; + + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() +} + +// Add ten thousand torrents in parallel (depending on the set worker threads) +pub async fn add_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: u64, + sleep: Option, +) -> Duration +where + V: RepositoryAsync + Default, + Arc: Clone + Send + Sync + 'static, +{ + let torrent_repository = Arc::::default(); + let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in a usize")); + let handles = FuturesUnordered::new(); + + let start = Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; + + torrent_repository_clone.get_swarm_metadata(&info_hash).await; + + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() +} + +// Async update ten thousand torrents in parallel (depending on the set worker threads) +pub async fn update_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: u64, + sleep: Option, +) -> Duration +where + V: RepositoryAsync + Default, + Arc: Clone + Send + Sync + 'static, +{ + let torrent_repository = Arc::::default(); + let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in usize")); + let handles = FuturesUnordered::new(); + + // Add the torrents/peers to the torrent repository + for info_hash in &info_hashes { + torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER, None).await; + torrent_repository.get_swarm_metadata(info_hash).await; + } + + let start = Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; + torrent_repository_clone.get_swarm_metadata(&info_hash).await; + + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() +} diff --git a/packages/torrent-repository-benchmarking/benches/helpers/mod.rs b/packages/torrent-repository-benchmarking/benches/helpers/mod.rs new file mode 100644 index 000000000..1026aa4bf --- /dev/null +++ b/packages/torrent-repository-benchmarking/benches/helpers/mod.rs @@ -0,0 +1,3 @@ +pub mod asyn; +pub mod sync; +pub mod utils; diff --git a/packages/torrent-repository-benchmarking/benches/helpers/sync.rs b/packages/torrent-repository-benchmarking/benches/helpers/sync.rs new file mode 100644 index 000000000..2cefb5a4a --- /dev/null +++ b/packages/torrent-repository-benchmarking/benches/helpers/sync.rs @@ -0,0 +1,155 @@ +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use bittorrent_primitives::info_hash::InfoHash; +use futures::stream::FuturesUnordered; +use torrust_tracker_torrent_repository_benchmarking::repository::Repository; + +use super::utils::{generate_unique_info_hashes, DEFAULT_PEER}; + +// Simply add one torrent +#[must_use] +pub fn add_one_torrent(samples: u64) -> Duration +where + V: Repository + Default, +{ + let start = Instant::now(); + + for _ in 0..samples { + let torrent_repository = V::default(); + + let info_hash = InfoHash::default(); + + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None); + + torrent_repository.get_swarm_metadata(&info_hash); + } + + start.elapsed() +} + +// Add one torrent ten thousand times in parallel (depending on the set worker threads) +pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: u64, sleep: Option) -> Duration +where + V: Repository + Default, + Arc: Clone + Send + Sync + 'static, +{ + let torrent_repository = Arc::::default(); + let info_hash = InfoHash::default(); + let handles = FuturesUnordered::new(); + + // Add the torrent/peer to the torrent repository + torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None); + + torrent_repository.get_swarm_metadata(&info_hash); + + let start = Instant::now(); + + for _ in 0..samples { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None); + + torrent_repository_clone.get_swarm_metadata(&info_hash); + + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() +} + +// Add ten thousand torrents in parallel (depending on the set worker threads) +pub async fn add_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: u64, + sleep: Option, +) -> Duration +where + V: Repository + Default, + Arc: Clone + Send + Sync + 'static, +{ + let torrent_repository = Arc::::default(); + let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in a usize")); + let handles = FuturesUnordered::new(); + + let start = Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None); + + torrent_repository_clone.get_swarm_metadata(&info_hash); + + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() +} + +// Update ten thousand torrents in parallel (depending on the set worker threads) +pub async fn update_multiple_torrents_in_parallel( + runtime: &tokio::runtime::Runtime, + samples: u64, + sleep: Option, +) -> Duration +where + V: Repository + Default, + Arc: Clone + Send + Sync + 'static, +{ + let torrent_repository = Arc::::default(); + let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in usize")); + let handles = FuturesUnordered::new(); + + // Add the torrents/peers to the torrent repository + for info_hash in &info_hashes { + torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER, None); + torrent_repository.get_swarm_metadata(info_hash); + } + + let start = Instant::now(); + + for info_hash in info_hashes { + let torrent_repository_clone = torrent_repository.clone(); + + let handle = runtime.spawn(async move { + torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None); + torrent_repository_clone.get_swarm_metadata(&info_hash); + + if let Some(sleep_time) = sleep { + let start_time = std::time::Instant::now(); + + while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} + } + }); + + handles.push(handle); + } + + // Await all tasks + futures::future::join_all(handles).await; + + start.elapsed() +} diff --git a/packages/torrent-repository-benchmarking/benches/helpers/utils.rs b/packages/torrent-repository-benchmarking/benches/helpers/utils.rs new file mode 100644 index 000000000..51b09ec0f --- /dev/null +++ b/packages/torrent-repository-benchmarking/benches/helpers/utils.rs @@ -0,0 +1,41 @@ +use std::collections::HashSet; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use zerocopy::I64; + +pub const DEFAULT_PEER: Peer = Peer { + peer_id: PeerId([0; 20]), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::from_secs(0), + uploaded: NumberOfBytes(I64::ZERO), + downloaded: NumberOfBytes(I64::ZERO), + left: NumberOfBytes(I64::ZERO), + event: AnnounceEvent::Started, +}; + +#[must_use] +#[allow(clippy::missing_panics_doc)] +pub fn generate_unique_info_hashes(size: usize) -> Vec { + let mut result = HashSet::new(); + + let mut bytes = [0u8; 20]; + + #[allow(clippy::cast_possible_truncation)] + for i in 0..size { + bytes[0] = (i & 0xFF) as u8; + bytes[1] = ((i >> 8) & 0xFF) as u8; + bytes[2] = ((i >> 16) & 0xFF) as u8; + bytes[3] = ((i >> 24) & 0xFF) as u8; + + let info_hash = InfoHash::from_bytes(&bytes); + result.insert(info_hash); + } + + assert_eq!(result.len(), size); + + result.into_iter().collect() +} diff --git a/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs b/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs new file mode 100644 index 000000000..a58207492 --- /dev/null +++ b/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs @@ -0,0 +1,270 @@ +use std::time::Duration; + +mod helpers; + +use criterion::{criterion_group, criterion_main, Criterion}; +use torrust_tracker_torrent_repository_benchmarking::{ + TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, + TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexParkingLot, TorrentsSkipMapMutexStd, + TorrentsSkipMapRwLockParkingLot, +}; + +use crate::helpers::{asyn, sync}; + +fn add_one_torrent(c: &mut Criterion) { + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("add_one_torrent"); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_millis(1000)); + + group.bench_function("RwLockStd", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.bench_function("RwLockStdMutexStd", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.bench_function("RwLockStdMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(asyn::add_one_torrent::); + }); + + group.bench_function("RwLockTokio", |b| { + b.to_async(&rt).iter_custom(asyn::add_one_torrent::); + }); + + group.bench_function("RwLockTokioMutexStd", |b| { + b.to_async(&rt) + .iter_custom(asyn::add_one_torrent::); + }); + + group.bench_function("RwLockTokioMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(asyn::add_one_torrent::); + }); + + group.bench_function("SkipMapMutexStd", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.bench_function("SkipMapMutexParkingLot", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.bench_function("SkipMapRwLockParkingLot", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.bench_function("DashMapMutexStd", |b| { + b.iter_custom(sync::add_one_torrent::); + }); + + group.finish(); +} + +fn add_multiple_torrents_in_parallel(c: &mut Criterion) { + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("add_multiple_torrents_in_parallel"); + + //group.sampling_mode(criterion::SamplingMode::Flat); + //group.sample_size(10); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_millis(1000)); + + group.bench_function("RwLockStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapMutexParkingLot", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapRwLockParkingLot", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("DashMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.finish(); +} + +fn update_one_torrent_in_parallel(c: &mut Criterion) { + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("update_one_torrent_in_parallel"); + + //group.sampling_mode(criterion::SamplingMode::Flat); + //group.sample_size(10); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_millis(1000)); + + group.bench_function("RwLockStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapMutexParkingLot", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapRwLockParkingLot", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("DashMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); + }); + + group.finish(); +} + +fn update_multiple_torrents_in_parallel(c: &mut Criterion) { + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); + + let mut group = c.benchmark_group("update_multiple_torrents_in_parallel"); + + //group.sampling_mode(criterion::SamplingMode::Flat); + //group.sample_size(10); + + group.warm_up_time(Duration::from_millis(500)); + group.measurement_time(Duration::from_millis(1000)); + + group.bench_function("RwLockStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockStdMutexTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokio", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| asyn::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("RwLockTokioMutexTokio", |b| { + b.to_async(&rt).iter_custom(|iters| { + asyn::update_multiple_torrents_in_parallel::(&rt, iters, None) + }); + }); + + group.bench_function("SkipMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.bench_function("SkipMapMutexParkingLot", |b| { + b.to_async(&rt).iter_custom(|iters| { + sync::update_multiple_torrents_in_parallel::(&rt, iters, None) + }); + }); + + group.bench_function("SkipMapRwLockParkingLot", |b| { + b.to_async(&rt).iter_custom(|iters| { + sync::update_multiple_torrents_in_parallel::(&rt, iters, None) + }); + }); + + group.bench_function("DashMapMutexStd", |b| { + b.to_async(&rt) + .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); + }); + + group.finish(); +} + +criterion_group!( + benches, + add_one_torrent, + add_multiple_torrents_in_parallel, + update_one_torrent_in_parallel, + update_multiple_torrents_in_parallel +); +criterion_main!(benches); diff --git a/packages/torrent-repository-benchmarking/src/entry/mod.rs b/packages/torrent-repository-benchmarking/src/entry/mod.rs new file mode 100644 index 000000000..b920839d9 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/mod.rs @@ -0,0 +1,92 @@ +use std::fmt::Debug; +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use self::peer_list::PeerList; + +pub mod mutex_parking_lot; +pub mod mutex_std; +pub mod mutex_tokio; +pub mod peer_list; +pub mod rw_lock_parking_lot; +pub mod single; + +pub trait Entry { + /// It returns the swarm metadata (statistics) as a struct: + /// + /// `(seeders, completed, leechers)` + fn get_swarm_metadata(&self) -> SwarmMetadata; + + /// Returns True if Still a Valid Entry according to the Tracker Policy + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool; + + /// Returns True if the Peers is Empty + fn peers_is_empty(&self) -> bool; + + /// Returns the number of Peers + fn get_peers_len(&self) -> usize; + + /// Get all swarm peers, optionally limiting the result. + fn get_peers(&self, limit: Option) -> Vec>; + + /// It returns the list of peers for a given peer client, optionally limiting the + /// result. + /// + /// It filters out the input peer, typically because we want to return this + /// list of peers to that client peer. + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec>; + + /// It updates a peer and returns true if the number of complete downloads have increased. + /// + /// The number of peers that have complete downloading is synchronously updated when peers are updated. + /// That's the total torrent downloads counter. + fn upsert_peer(&mut self, peer: &peer::Peer) -> bool; + + /// It removes peer from the swarm that have not been updated for more than `current_cutoff` seconds + fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch); +} + +#[allow(clippy::module_name_repetitions)] +pub trait EntrySync { + fn get_swarm_metadata(&self) -> SwarmMetadata; + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool; + fn peers_is_empty(&self) -> bool; + fn get_peers_len(&self) -> usize; + fn get_peers(&self, limit: Option) -> Vec>; + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec>; + fn upsert_peer(&self, peer: &peer::Peer) -> bool; + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); +} + +#[allow(clippy::module_name_repetitions)] +pub trait EntryAsync { + fn get_swarm_metadata(&self) -> impl std::future::Future + Send; + fn meets_retaining_policy(self, policy: &TrackerPolicy) -> impl std::future::Future + Send; + fn peers_is_empty(&self) -> impl std::future::Future + Send; + fn get_peers_len(&self) -> impl std::future::Future + Send; + fn get_peers(&self, limit: Option) -> impl std::future::Future>> + Send; + fn get_peers_for_client( + &self, + client: &SocketAddr, + limit: Option, + ) -> impl std::future::Future>> + Send; + fn upsert_peer(self, peer: &peer::Peer) -> impl std::future::Future + Send; + fn remove_inactive_peers(self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; +} + +/// A data structure containing all the information about a torrent in the tracker. +/// +/// This is the tracker entry for a given torrent and contains the swarm data, +/// that's the list of all the peers trying to download the same torrent. +/// The tracker keeps one entry like this for every torrent. +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Torrent { + /// A network of peers that are all trying to download the torrent associated to this entry + pub(crate) swarm: PeerList, + /// The number of peers that have ever completed downloading the torrent associated to this entry + pub(crate) downloaded: u32, +} diff --git a/packages/torrent-repository-benchmarking/src/entry/mutex_parking_lot.rs b/packages/torrent-repository-benchmarking/src/entry/mutex_parking_lot.rs new file mode 100644 index 000000000..738c3ff9d --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/mutex_parking_lot.rs @@ -0,0 +1,49 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use super::{Entry, EntrySync}; +use crate::{EntryMutexParkingLot, EntrySingle}; + +impl EntrySync for EntryMutexParkingLot { + fn get_swarm_metadata(&self) -> SwarmMetadata { + self.lock().get_swarm_metadata() + } + + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + self.lock().meets_retaining_policy(policy) + } + + fn peers_is_empty(&self) -> bool { + self.lock().peers_is_empty() + } + + fn get_peers_len(&self) -> usize { + self.lock().get_peers_len() + } + + fn get_peers(&self, limit: Option) -> Vec> { + self.lock().get_peers(limit) + } + + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.lock().get_peers_for_client(client, limit) + } + + fn upsert_peer(&self, peer: &peer::Peer) -> bool { + self.lock().upsert_peer(peer) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + self.lock().remove_inactive_peers(current_cutoff); + } +} + +impl From for EntryMutexParkingLot { + fn from(entry: EntrySingle) -> Self { + Arc::new(parking_lot::Mutex::new(entry)) + } +} diff --git a/packages/torrent-repository-benchmarking/src/entry/mutex_std.rs b/packages/torrent-repository-benchmarking/src/entry/mutex_std.rs new file mode 100644 index 000000000..0ab70a96f --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/mutex_std.rs @@ -0,0 +1,51 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use super::{Entry, EntrySync}; +use crate::{EntryMutexStd, EntrySingle}; + +impl EntrySync for EntryMutexStd { + fn get_swarm_metadata(&self) -> SwarmMetadata { + self.lock().expect("it should get a lock").get_swarm_metadata() + } + + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + self.lock().expect("it should get a lock").meets_retaining_policy(policy) + } + + fn peers_is_empty(&self) -> bool { + self.lock().expect("it should get a lock").peers_is_empty() + } + + fn get_peers_len(&self) -> usize { + self.lock().expect("it should get a lock").get_peers_len() + } + + fn get_peers(&self, limit: Option) -> Vec> { + self.lock().expect("it should get lock").get_peers(limit) + } + + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.lock().expect("it should get lock").get_peers_for_client(client, limit) + } + + fn upsert_peer(&self, peer: &peer::Peer) -> bool { + self.lock().expect("it should lock the entry").upsert_peer(peer) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + self.lock() + .expect("it should lock the entry") + .remove_inactive_peers(current_cutoff); + } +} + +impl From for EntryMutexStd { + fn from(entry: EntrySingle) -> Self { + Arc::new(std::sync::Mutex::new(entry)) + } +} diff --git a/packages/torrent-repository-benchmarking/src/entry/mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/entry/mutex_tokio.rs new file mode 100644 index 000000000..6db789a72 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/mutex_tokio.rs @@ -0,0 +1,49 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use super::{Entry, EntryAsync}; +use crate::{EntryMutexTokio, EntrySingle}; + +impl EntryAsync for EntryMutexTokio { + async fn get_swarm_metadata(&self) -> SwarmMetadata { + self.lock().await.get_swarm_metadata() + } + + async fn meets_retaining_policy(self, policy: &TrackerPolicy) -> bool { + self.lock().await.meets_retaining_policy(policy) + } + + async fn peers_is_empty(&self) -> bool { + self.lock().await.peers_is_empty() + } + + async fn get_peers_len(&self) -> usize { + self.lock().await.get_peers_len() + } + + async fn get_peers(&self, limit: Option) -> Vec> { + self.lock().await.get_peers(limit) + } + + async fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.lock().await.get_peers_for_client(client, limit) + } + + async fn upsert_peer(self, peer: &peer::Peer) -> bool { + self.lock().await.upsert_peer(peer) + } + + async fn remove_inactive_peers(self, current_cutoff: DurationSinceUnixEpoch) { + self.lock().await.remove_inactive_peers(current_cutoff); + } +} + +impl From for EntryMutexTokio { + fn from(entry: EntrySingle) -> Self { + Arc::new(tokio::sync::Mutex::new(entry)) + } +} diff --git a/packages/torrent-repository-benchmarking/src/entry/peer_list.rs b/packages/torrent-repository-benchmarking/src/entry/peer_list.rs new file mode 100644 index 000000000..33270cf27 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/peer_list.rs @@ -0,0 +1,286 @@ +//! A peer list. +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::PeerId; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +// code-review: the current implementation uses the peer Id as the ``BTreeMap`` +// key. That would allow adding two identical peers except for the Id. +// For example, two peers with the same socket address but a different peer Id +// would be allowed. That would lead to duplicated peers in the tracker responses. + +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct PeerList { + peers: std::collections::BTreeMap>, +} + +impl PeerList { + #[must_use] + pub fn len(&self) -> usize { + self.peers.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.peers.is_empty() + } + + pub fn upsert(&mut self, value: Arc) -> Option> { + self.peers.insert(value.peer_id, value) + } + + pub fn remove(&mut self, key: &PeerId) -> Option> { + self.peers.remove(key) + } + + pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + self.peers + .retain(|_, peer| peer::ReadInfo::get_updated(peer) > current_cutoff); + } + + #[must_use] + pub fn get(&self, peer_id: &PeerId) -> Option<&Arc> { + self.peers.get(peer_id) + } + + #[must_use] + pub fn get_all(&self, limit: Option) -> Vec> { + match limit { + Some(limit) => self.peers.values().take(limit).cloned().collect(), + None => self.peers.values().cloned().collect(), + } + } + + #[must_use] + pub fn seeders_and_leechers(&self) -> (usize, usize) { + let seeders = self.peers.values().filter(|peer| peer.is_seeder()).count(); + let leechers = self.len() - seeders; + + (seeders, leechers) + } + + #[must_use] + pub fn get_peers_excluding_addr(&self, peer_addr: &SocketAddr, limit: Option) -> Vec> { + match limit { + Some(limit) => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *peer_addr) + // Limit the number of peers on the result + .take(limit) + .cloned() + .collect(), + None => self + .peers + .values() + // Take peers which are not the client peer + .filter(|peer| peer::ReadInfo::get_address(peer.as_ref()) != *peer_addr) + .cloned() + .collect(), + } + } +} + +#[cfg(test)] +mod tests { + + mod it_should { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::PeerId; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::entry::peer_list::PeerList; + + #[test] + fn be_empty_when_no_peers_have_been_inserted() { + let peer_list = PeerList::default(); + + assert!(peer_list.is_empty()); + } + + #[test] + fn have_zero_length_when_no_peers_have_been_inserted() { + let peer_list = PeerList::default(); + + assert_eq!(peer_list.len(), 0); + } + + #[test] + fn allow_inserting_a_new_peer() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + assert_eq!(peer_list.upsert(peer.into()), None); + } + + #[test] + fn allow_updating_a_preexisting_peer() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + assert_eq!(peer_list.upsert(peer.into()), Some(Arc::new(peer))); + } + + #[test] + fn allow_getting_all_peers() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + assert_eq!(peer_list.get_all(None), [Arc::new(peer)]); + } + + #[test] + fn allow_getting_one_peer_by_id() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + assert_eq!(peer_list.get(&peer.peer_id), Some(Arc::new(peer)).as_ref()); + } + + #[test] + fn increase_the_number_of_peers_after_inserting_a_new_one() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + assert_eq!(peer_list.len(), 1); + } + + #[test] + fn decrease_the_number_of_peers_after_removing_one() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + peer_list.remove(&peer.peer_id); + + assert!(peer_list.is_empty()); + } + + #[test] + fn allow_removing_an_existing_peer() { + let mut peer_list = PeerList::default(); + + let peer = PeerBuilder::default().build(); + + peer_list.upsert(peer.into()); + + peer_list.remove(&peer.peer_id); + + assert_eq!(peer_list.get(&peer.peer_id), None); + } + + #[test] + fn allow_getting_all_peers_excluding_peers_with_a_given_address() { + let mut peer_list = PeerList::default(); + + let peer1 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .build(); + peer_list.upsert(peer1.into()); + + let peer2 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000002")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) + .build(); + peer_list.upsert(peer2.into()); + + assert_eq!(peer_list.get_peers_excluding_addr(&peer2.peer_addr, None), [Arc::new(peer1)]); + } + + #[test] + fn return_the_number_of_seeders_in_the_list() { + let mut peer_list = PeerList::default(); + + let seeder = PeerBuilder::seeder().build(); + let leecher = PeerBuilder::leecher().build(); + + peer_list.upsert(seeder.into()); + peer_list.upsert(leecher.into()); + + let (seeders, _leechers) = peer_list.seeders_and_leechers(); + + assert_eq!(seeders, 1); + } + + #[test] + fn return_the_number_of_leechers_in_the_list() { + let mut peer_list = PeerList::default(); + + let seeder = PeerBuilder::seeder().build(); + let leecher = PeerBuilder::leecher().build(); + + peer_list.upsert(seeder.into()); + peer_list.upsert(leecher.into()); + + let (_seeders, leechers) = peer_list.seeders_and_leechers(); + + assert_eq!(leechers, 1); + } + + #[test] + fn remove_inactive_peers() { + let mut peer_list = PeerList::default(); + let one_second = DurationSinceUnixEpoch::new(1, 0); + + // Insert the peer + let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); + let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); + peer_list.upsert(peer.into()); + + // Remove peers not updated since one second after inserting the peer + peer_list.remove_inactive_peers(last_update_time + one_second); + + assert_eq!(peer_list.len(), 0); + } + + #[test] + fn not_remove_active_peers() { + let mut peer_list = PeerList::default(); + let one_second = DurationSinceUnixEpoch::new(1, 0); + + // Insert the peer + let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); + let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); + peer_list.upsert(peer.into()); + + // Remove peers not updated since one second before inserting the peer. + peer_list.remove_inactive_peers(last_update_time - one_second); + + assert_eq!(peer_list.len(), 1); + } + + #[test] + fn allow_inserting_two_identical_peers_except_for_the_id() { + let mut peer_list = PeerList::default(); + + let peer1 = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); + peer_list.upsert(peer1.into()); + + let peer2 = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000002")).build(); + peer_list.upsert(peer2.into()); + + assert_eq!(peer_list.len(), 2); + } + } +} diff --git a/packages/torrent-repository-benchmarking/src/entry/rw_lock_parking_lot.rs b/packages/torrent-repository-benchmarking/src/entry/rw_lock_parking_lot.rs new file mode 100644 index 000000000..ac0dc0b30 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/rw_lock_parking_lot.rs @@ -0,0 +1,49 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use super::{Entry, EntrySync}; +use crate::{EntryRwLockParkingLot, EntrySingle}; + +impl EntrySync for EntryRwLockParkingLot { + fn get_swarm_metadata(&self) -> SwarmMetadata { + self.read().get_swarm_metadata() + } + + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + self.read().meets_retaining_policy(policy) + } + + fn peers_is_empty(&self) -> bool { + self.read().peers_is_empty() + } + + fn get_peers_len(&self) -> usize { + self.read().get_peers_len() + } + + fn get_peers(&self, limit: Option) -> Vec> { + self.read().get_peers(limit) + } + + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.read().get_peers_for_client(client, limit) + } + + fn upsert_peer(&self, peer: &peer::Peer) -> bool { + self.write().upsert_peer(peer) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + self.write().remove_inactive_peers(current_cutoff); + } +} + +impl From for EntryRwLockParkingLot { + fn from(entry: EntrySingle) -> Self { + Arc::new(parking_lot::RwLock::new(entry)) + } +} diff --git a/packages/torrent-repository-benchmarking/src/entry/single.rs b/packages/torrent-repository-benchmarking/src/entry/single.rs new file mode 100644 index 000000000..0f922bd02 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/entry/single.rs @@ -0,0 +1,81 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::AnnounceEvent; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::peer::{self}; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::Entry; +use crate::EntrySingle; + +impl Entry for EntrySingle { + #[allow(clippy::cast_possible_truncation)] + fn get_swarm_metadata(&self) -> SwarmMetadata { + let (seeders, leechers) = self.swarm.seeders_and_leechers(); + + SwarmMetadata { + downloaded: self.downloaded, + complete: seeders as u32, + incomplete: leechers as u32, + } + } + + fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + if policy.persistent_torrent_completed_stat && self.downloaded > 0 { + return true; + } + + if policy.remove_peerless_torrents && self.swarm.is_empty() { + return false; + } + + true + } + + fn peers_is_empty(&self) -> bool { + self.swarm.is_empty() + } + + fn get_peers_len(&self) -> usize { + self.swarm.len() + } + + fn get_peers(&self, limit: Option) -> Vec> { + self.swarm.get_all(limit) + } + + fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.swarm.get_peers_excluding_addr(client, limit) + } + + fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { + let mut number_of_downloads_increased: bool = false; + + match peer::ReadInfo::get_event(peer) { + AnnounceEvent::Stopped => { + drop(self.swarm.remove(&peer::ReadInfo::get_id(peer))); + } + AnnounceEvent::Completed => { + let previous = self.swarm.upsert(Arc::new(*peer)); + // Don't count if peer was not previously known and not already completed. + if previous.is_some_and(|p| p.event != AnnounceEvent::Completed) { + self.downloaded += 1; + number_of_downloads_increased = true; + } + } + _ => { + // `Started` event (first announced event) or + // `None` event (announcements done at regular intervals). + drop(self.swarm.upsert(Arc::new(*peer))); + } + } + + number_of_downloads_increased + } + + fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + self.swarm.remove_inactive_peers(current_cutoff); + } +} diff --git a/packages/torrent-repository-benchmarking/src/lib.rs b/packages/torrent-repository-benchmarking/src/lib.rs new file mode 100644 index 000000000..a8955808e --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/lib.rs @@ -0,0 +1,44 @@ +use std::sync::Arc; + +use repository::dash_map_mutex_std::XacrimonDashMap; +use repository::rw_lock_std::RwLockStd; +use repository::rw_lock_tokio::RwLockTokio; +use repository::skip_map_mutex_std::CrossbeamSkipList; +use torrust_tracker_clock::clock; + +pub mod entry; +pub mod repository; + +// Repo Entries + +pub type EntrySingle = entry::Torrent; +pub type EntryMutexStd = Arc>; +pub type EntryMutexTokio = Arc>; +pub type EntryMutexParkingLot = Arc>; +pub type EntryRwLockParkingLot = Arc>; + +// Repos + +pub type TorrentsRwLockStd = RwLockStd; +pub type TorrentsRwLockStdMutexStd = RwLockStd; +pub type TorrentsRwLockStdMutexTokio = RwLockStd; +pub type TorrentsRwLockTokio = RwLockTokio; +pub type TorrentsRwLockTokioMutexStd = RwLockTokio; +pub type TorrentsRwLockTokioMutexTokio = RwLockTokio; + +pub type TorrentsSkipMapMutexStd = CrossbeamSkipList; +pub type TorrentsSkipMapMutexParkingLot = CrossbeamSkipList; +pub type TorrentsSkipMapRwLockParkingLot = CrossbeamSkipList; + +pub type TorrentsDashMapMutexStd = XacrimonDashMap; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs new file mode 100644 index 000000000..d4a84caa0 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs @@ -0,0 +1,111 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use dashmap::DashMap; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; + +use super::Repository; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntrySync}; +use crate::{EntryMutexStd, EntrySingle}; + +#[derive(Default, Debug)] +pub struct XacrimonDashMap { + pub torrents: DashMap, +} + +impl Repository for XacrimonDashMap +where + EntryMutexStd: EntrySync, + EntrySingle: Entry, +{ + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + + if let Some(entry) = self.torrents.get(info_hash) { + entry.upsert_peer(peer) + } else { + let _unused = self.torrents.insert(*info_hash, Arc::default()); + if let Some(entry) = self.torrents.get(info_hash) { + entry.upsert_peer(peer) + } else { + false + } + } + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) + } + + fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.torrents.get(key); + maybe_entry.map(|entry| entry.clone()) + } + + fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); + + for entry in &self.torrents { + let stats = entry.value().lock().expect("it should get a lock").get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + match pagination { + Some(pagination) => self + .torrents + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .torrents + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + for (info_hash, completed) in persistent_torrents { + if self.torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexStd::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + self.torrents.insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|(_key, value)| value.clone()) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { + entry.value().remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + self.torrents.retain(|_, entry| entry.meets_retaining_policy(policy)); + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/mod.rs b/packages/torrent-repository-benchmarking/src/repository/mod.rs new file mode 100644 index 000000000..9284ff6e6 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/mod.rs @@ -0,0 +1,46 @@ +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; + +pub mod dash_map_mutex_std; +pub mod rw_lock_std; +pub mod rw_lock_std_mutex_std; +pub mod rw_lock_std_mutex_tokio; +pub mod rw_lock_tokio; +pub mod rw_lock_tokio_mutex_std; +pub mod rw_lock_tokio_mutex_tokio; +pub mod skip_map_mutex_std; + +use std::fmt::Debug; + +pub trait Repository: Debug + Default + Sized + 'static { + fn get(&self, key: &InfoHash) -> Option; + fn get_metrics(&self) -> AggregateSwarmMetadata; + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, T)>; + fn import_persistent(&self, persistent_torrents: &PersistentTorrents); + fn remove(&self, key: &InfoHash) -> Option; + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); + fn remove_peerless_torrents(&self, policy: &TrackerPolicy); + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool; + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option; +} + +#[allow(clippy::module_name_repetitions)] +pub trait RepositoryAsync: Debug + Default + Sized + 'static { + fn get(&self, key: &InfoHash) -> impl std::future::Future> + Send; + fn get_metrics(&self) -> impl std::future::Future + Send; + fn get_paginated(&self, pagination: Option<&Pagination>) -> impl std::future::Future> + Send; + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) -> impl std::future::Future + Send; + fn remove(&self, key: &InfoHash) -> impl std::future::Future> + Send; + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> impl std::future::Future + Send; + fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + opt_persistent_torrent: Option, + ) -> impl std::future::Future + Send; + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> impl std::future::Future> + Send; +} diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs new file mode 100644 index 000000000..d190718af --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs @@ -0,0 +1,132 @@ +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; + +use super::Repository; +use crate::entry::peer_list::PeerList; +use crate::entry::Entry; +use crate::{EntrySingle, TorrentsRwLockStd}; + +#[derive(Default, Debug)] +pub struct RwLockStd { + pub(crate) torrents: std::sync::RwLock>, +} + +impl RwLockStd { + /// # Panics + /// + /// Panics if unable to get a lock. + pub fn write( + &self, + ) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { + self.torrents.write().expect("it should get lock") + } +} + +impl TorrentsRwLockStd { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("it should get the read lock") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("it should get the write lock") + } +} + +impl Repository for TorrentsRwLockStd +where + EntrySingle: Entry, +{ + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + + let mut db = self.get_torrents_mut(); + + let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); + + entry.upsert_peer(peer) + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.get(info_hash).map(|entry| entry.get_swarm_metadata()) + } + + fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); + + for entry in self.get_torrents().values() { + let stats = entry.get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut(); + + for (info_hash, downloaded) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = EntrySingle { + swarm: PeerList::default(), + downloaded: *downloaded, + }; + + torrents.insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let mut db = self.get_torrents_mut(); + let entries = db.values_mut(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.meets_retaining_policy(policy)); + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs new file mode 100644 index 000000000..1764b94e8 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs @@ -0,0 +1,130 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; + +use super::Repository; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntrySync}; +use crate::{EntryMutexStd, EntrySingle, TorrentsRwLockStdMutexStd}; + +impl TorrentsRwLockStdMutexStd { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl Repository for TorrentsRwLockStdMutexStd +where + EntryMutexStd: EntrySync, + EntrySingle: Entry, +{ + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + + let maybe_entry = self.get_torrents().get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut(); + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.upsert_peer(peer) + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.get_torrents() + .get(info_hash) + .map(super::super::entry::EntrySync::get_swarm_metadata) + } + + fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); + + for entry in self.get_torrents().values() { + let stats = entry.lock().expect("it should get a lock").get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexStd::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + torrents.insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let db = self.get_torrents(); + let entries = db.values().cloned(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut(); + + db.retain(|_, e| e.lock().expect("it should lock entry").meets_retaining_policy(policy)); + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs new file mode 100644 index 000000000..116c1ff87 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs @@ -0,0 +1,167 @@ +use std::iter::zip; +use std::pin::Pin; +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use futures::future::join_all; +use futures::{Future, FutureExt}; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; + +use super::RepositoryAsync; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntryAsync}; +use crate::{EntryMutexTokio, EntrySingle, TorrentsRwLockStdMutexTokio}; + +impl TorrentsRwLockStdMutexTokio { + fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().expect("unable to get torrent list") + } + + fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().expect("unable to get writable torrent list") + } +} + +impl RepositoryAsync for TorrentsRwLockStdMutexTokio +where + EntryMutexTokio: EntryAsync, + EntrySingle: Entry, +{ + async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + _opt_persistent_torrent: Option, + ) -> bool { + // todo: load persistent torrent data if provided + + let maybe_entry = self.get_torrents().get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut(); + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.upsert_peer(peer).await + } + + async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + let maybe_entry = self.get_torrents().get(info_hash).cloned(); + + match maybe_entry { + Some(entry) => Some(entry.get_swarm_metadata().await), + None => None, + } + } + + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents(); + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexTokio)> { + let db = self.get_torrents(); + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); + + let entries: Vec<_> = self.get_torrents().values().cloned().collect(); + + for entry in entries { + let stats = entry.lock().await.get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut db = self.get_torrents_mut(); + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if db.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexTokio::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + db.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut(); + db.remove(key) + } + + async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let handles: Vec + Send>>>; + { + let db = self.get_torrents(); + handles = db + .values() + .cloned() + .map(|e| e.remove_inactive_peers(current_cutoff).boxed()) + .collect(); + } + join_all(handles).await; + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let handles: Vec> + Send>>>; + + { + let db = self.get_torrents(); + + handles = zip(db.keys().copied(), db.values().cloned()) + .map(|(infohash, torrent)| { + torrent + .meets_retaining_policy(policy) + .map(move |should_be_retained| if should_be_retained { None } else { Some(infohash) }) + .boxed() + }) + .collect::>(); + } + + let not_good = join_all(handles).await; + + let mut db = self.get_torrents_mut(); + + for remove in not_good.into_iter().flatten() { + drop(db.remove(&remove)); + } + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs new file mode 100644 index 000000000..53838023d --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs @@ -0,0 +1,138 @@ +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; + +use super::RepositoryAsync; +use crate::entry::peer_list::PeerList; +use crate::entry::Entry; +use crate::{EntrySingle, TorrentsRwLockTokio}; + +#[derive(Default, Debug)] +pub struct RwLockTokio { + pub(crate) torrents: tokio::sync::RwLock>, +} + +impl RwLockTokio { + pub fn write( + &self, + ) -> impl std::future::Future< + Output = tokio::sync::RwLockWriteGuard<'_, std::collections::BTreeMap>, + > { + self.torrents.write() + } +} + +impl TorrentsRwLockTokio { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl RepositoryAsync for TorrentsRwLockTokio +where + EntrySingle: Entry, +{ + async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + _opt_persistent_torrent: Option, + ) -> bool { + // todo: load persistent torrent data if provided + + let mut db = self.get_torrents_mut().await; + + let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); + + entry.upsert_peer(peer) + } + + async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.get(info_hash).await.map(|entry| entry.get_swarm_metadata()) + } + + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); + + for entry in self.get_torrents().await.values() { + let stats = entry.get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + }; + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let mut db = self.get_torrents_mut().await; + let entries = db.values_mut(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff); + } + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.meets_retaining_policy(policy)); + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs new file mode 100644 index 000000000..eb7e300fd --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs @@ -0,0 +1,135 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; + +use super::RepositoryAsync; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntrySync}; +use crate::{EntryMutexStd, EntrySingle, TorrentsRwLockTokioMutexStd}; + +impl TorrentsRwLockTokioMutexStd { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl RepositoryAsync for TorrentsRwLockTokioMutexStd +where + EntryMutexStd: EntrySync, + EntrySingle: Entry, +{ + async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + _opt_persistent_torrent: Option, + ) -> bool { + // todo: load persistent torrent data if provided + + let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut().await; + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.upsert_peer(peer) + } + + async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.get(info_hash).await.map(|entry| entry.get_swarm_metadata()) + } + + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); + + for entry in self.get_torrents().await.values() { + let stats = entry.get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut torrents = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexStd::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + torrents.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let db = self.get_torrents().await; + let entries = db.values().cloned(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff); + } + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + db.retain(|_, e| e.lock().expect("it should lock entry").meets_retaining_policy(policy)); + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs new file mode 100644 index 000000000..c8ebaf4d6 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -0,0 +1,148 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; + +use super::RepositoryAsync; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntryAsync}; +use crate::{EntryMutexTokio, EntrySingle, TorrentsRwLockTokioMutexTokio}; + +impl TorrentsRwLockTokioMutexTokio { + async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.read().await + } + + async fn get_torrents_mut<'a>( + &'a self, + ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> + where + std::collections::BTreeMap: 'a, + { + self.torrents.write().await + } +} + +impl RepositoryAsync for TorrentsRwLockTokioMutexTokio +where + EntryMutexTokio: EntryAsync, + EntrySingle: Entry, +{ + async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + _opt_persistent_torrent: Option, + ) -> bool { + // todo: load persistent torrent data if provided + + let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); + + let entry = if let Some(entry) = maybe_entry { + entry + } else { + let mut db = self.get_torrents_mut().await; + let entry = db.entry(*info_hash).or_insert(Arc::default()); + entry.clone() + }; + + entry.upsert_peer(peer).await + } + + async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + match self.get(info_hash).await { + Some(entry) => Some(entry.get_swarm_metadata().await), + None => None, + } + } + + async fn get(&self, key: &InfoHash) -> Option { + let db = self.get_torrents().await; + db.get(key).cloned() + } + + async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexTokio)> { + let db = self.get_torrents().await; + + match pagination { + Some(pagination) => db + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|(a, b)| (*a, b.clone())) + .collect(), + None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), + } + } + + async fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); + + for entry in self.get_torrents().await.values() { + let stats = entry.get_swarm_metadata().await; + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + let mut db = self.get_torrents_mut().await; + + for (info_hash, completed) in persistent_torrents { + // Skip if torrent entry already exists + if db.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexTokio::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + db.insert(*info_hash, entry); + } + } + + async fn remove(&self, key: &InfoHash) -> Option { + let mut db = self.get_torrents_mut().await; + db.remove(key) + } + + async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + let db = self.get_torrents().await; + let entries = db.values().cloned(); + + for entry in entries { + entry.remove_inactive_peers(current_cutoff).await; + } + } + + async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + let mut db = self.get_torrents_mut().await; + + let mut not_good = Vec::::default(); + + for (&infohash, torrent) in db.iter() { + if !torrent.clone().meets_retaining_policy(policy).await { + not_good.push(infohash); + } + } + + for remove in not_good { + drop(db.remove(&remove)); + } + } +} diff --git a/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs new file mode 100644 index 000000000..8a15a9442 --- /dev/null +++ b/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs @@ -0,0 +1,328 @@ +use std::sync::Arc; + +use bittorrent_primitives::info_hash::InfoHash; +use crossbeam_skiplist::SkipMap; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; + +use super::Repository; +use crate::entry::peer_list::PeerList; +use crate::entry::{Entry, EntrySync}; +use crate::{EntryMutexParkingLot, EntryMutexStd, EntryRwLockParkingLot, EntrySingle}; + +#[derive(Default, Debug)] +pub struct CrossbeamSkipList { + pub torrents: SkipMap, +} + +impl Repository for CrossbeamSkipList +where + EntryMutexStd: EntrySync, + EntrySingle: Entry, +{ + /// Upsert a peer into the swarm of a torrent. + /// + /// Optionally, it can also preset the number of downloads of the torrent + /// only if it's the first time the torrent is being inserted. + /// + /// # Arguments + /// + /// * `info_hash` - The info hash of the torrent. + /// * `peer` - The peer to upsert. + /// * `opt_persistent_torrent` - The optional persisted data about a torrent + /// (number of downloads for the torrent). + /// + /// # Returns + /// + /// Returns `true` if the number of downloads was increased because the peer + /// completed the download. + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool { + if let Some(existing_entry) = self.torrents.get(info_hash) { + existing_entry.value().upsert_peer(peer) + } else { + let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { + EntryMutexStd::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: number_of_downloads, + } + .into(), + ) + } else { + EntryMutexStd::default() + }; + + let inserted_entry = self.torrents.get_or_insert(*info_hash, new_entry); + + inserted_entry.value().upsert_peer(peer) + } + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) + } + + fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.torrents.get(key); + maybe_entry.map(|entry| entry.value().clone()) + } + + fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); + + for entry in &self.torrents { + let stats = entry.value().lock().expect("it should get a lock").get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + match pagination { + Some(pagination) => self + .torrents + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .torrents + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + for (info_hash, completed) in persistent_torrents { + if self.torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexStd::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + // Since SkipMap is lock-free the torrent could have been inserted + // after checking if it exists. + self.torrents.get_or_insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|entry| entry.value().clone()) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { + entry.value().remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + for entry in &self.torrents { + if entry.value().meets_retaining_policy(policy) { + continue; + } + + entry.remove(); + } + } +} + +impl Repository for CrossbeamSkipList +where + EntryRwLockParkingLot: EntrySync, + EntrySingle: Entry, +{ + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + + let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); + entry.value().upsert_peer(peer) + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) + } + + fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.torrents.get(key); + maybe_entry.map(|entry| entry.value().clone()) + } + + fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); + + for entry in &self.torrents { + let stats = entry.value().read().get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryRwLockParkingLot)> { + match pagination { + Some(pagination) => self + .torrents + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .torrents + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + for (info_hash, completed) in persistent_torrents { + if self.torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryRwLockParkingLot::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + // Since SkipMap is lock-free the torrent could have been inserted + // after checking if it exists. + self.torrents.get_or_insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|entry| entry.value().clone()) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { + entry.value().remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + for entry in &self.torrents { + if entry.value().meets_retaining_policy(policy) { + continue; + } + + entry.remove(); + } + } +} + +impl Repository for CrossbeamSkipList +where + EntryMutexParkingLot: EntrySync, + EntrySingle: Entry, +{ + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + // todo: load persistent torrent data if provided + + let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); + entry.value().upsert_peer(peer) + } + + fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) + } + + fn get(&self, key: &InfoHash) -> Option { + let maybe_entry = self.torrents.get(key); + maybe_entry.map(|entry| entry.value().clone()) + } + + fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); + + for entry in &self.torrents { + let stats = entry.value().lock().get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; + } + + metrics + } + + fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexParkingLot)> { + match pagination { + Some(pagination) => self + .torrents + .iter() + .skip(pagination.offset as usize) + .take(pagination.limit as usize) + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + None => self + .torrents + .iter() + .map(|entry| (*entry.key(), entry.value().clone())) + .collect(), + } + } + + fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + for (info_hash, completed) in persistent_torrents { + if self.torrents.contains_key(info_hash) { + continue; + } + + let entry = EntryMutexParkingLot::new( + EntrySingle { + swarm: PeerList::default(), + downloaded: *completed, + } + .into(), + ); + + // Since SkipMap is lock-free the torrent could have been inserted + // after checking if it exists. + self.torrents.get_or_insert(*info_hash, entry); + } + } + + fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|entry| entry.value().clone()) + } + + fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { + entry.value().remove_inactive_peers(current_cutoff); + } + } + + fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + for entry in &self.torrents { + if entry.value().meets_retaining_policy(policy) { + continue; + } + + entry.remove(); + } + } +} diff --git a/packages/torrent-repository-benchmarking/tests/common/mod.rs b/packages/torrent-repository-benchmarking/tests/common/mod.rs new file mode 100644 index 000000000..efdf7f742 --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/common/mod.rs @@ -0,0 +1,3 @@ +pub mod repo; +pub mod torrent; +pub mod torrent_peer_builder; diff --git a/packages/torrent-repository-benchmarking/tests/common/repo.rs b/packages/torrent-repository-benchmarking/tests/common/repo.rs new file mode 100644 index 000000000..6c5c6ff77 --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/common/repo.rs @@ -0,0 +1,242 @@ +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_torrent_repository_benchmarking::repository::{Repository as _, RepositoryAsync as _}; +use torrust_tracker_torrent_repository_benchmarking::{ + EntrySingle, TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, + TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexParkingLot, + TorrentsSkipMapMutexStd, TorrentsSkipMapRwLockParkingLot, +}; + +#[derive(Debug)] +pub(crate) enum Repo { + RwLockStd(TorrentsRwLockStd), + RwLockStdMutexStd(TorrentsRwLockStdMutexStd), + RwLockStdMutexTokio(TorrentsRwLockStdMutexTokio), + RwLockTokio(TorrentsRwLockTokio), + RwLockTokioMutexStd(TorrentsRwLockTokioMutexStd), + RwLockTokioMutexTokio(TorrentsRwLockTokioMutexTokio), + SkipMapMutexStd(TorrentsSkipMapMutexStd), + SkipMapMutexParkingLot(TorrentsSkipMapMutexParkingLot), + SkipMapRwLockParkingLot(TorrentsSkipMapRwLockParkingLot), + DashMapMutexStd(TorrentsDashMapMutexStd), +} + +impl Repo { + pub(crate) async fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + opt_persistent_torrent: Option, + ) -> bool { + match self { + Repo::RwLockStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::RwLockStdMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::RwLockStdMutexTokio(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, + Repo::RwLockTokio(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, + Repo::RwLockTokioMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, + Repo::RwLockTokioMutexTokio(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, + Repo::SkipMapMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::SkipMapMutexParkingLot(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::SkipMapRwLockParkingLot(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + Repo::DashMapMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), + } + } + + pub(crate) async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + match self { + Repo::RwLockStd(repo) => repo.get_swarm_metadata(info_hash), + Repo::RwLockStdMutexStd(repo) => repo.get_swarm_metadata(info_hash), + Repo::RwLockStdMutexTokio(repo) => repo.get_swarm_metadata(info_hash).await, + Repo::RwLockTokio(repo) => repo.get_swarm_metadata(info_hash).await, + Repo::RwLockTokioMutexStd(repo) => repo.get_swarm_metadata(info_hash).await, + Repo::RwLockTokioMutexTokio(repo) => repo.get_swarm_metadata(info_hash).await, + Repo::SkipMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), + Repo::SkipMapMutexParkingLot(repo) => repo.get_swarm_metadata(info_hash), + Repo::SkipMapRwLockParkingLot(repo) => repo.get_swarm_metadata(info_hash), + Repo::DashMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), + } + } + + pub(crate) async fn get(&self, key: &InfoHash) -> Option { + match self { + Repo::RwLockStd(repo) => repo.get(key), + Repo::RwLockStdMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), + Repo::RwLockStdMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), + Repo::RwLockTokio(repo) => repo.get(key).await, + Repo::RwLockTokioMutexStd(repo) => Some(repo.get(key).await?.lock().unwrap().clone()), + Repo::RwLockTokioMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), + Repo::SkipMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), + Repo::SkipMapMutexParkingLot(repo) => Some(repo.get(key)?.lock().clone()), + Repo::SkipMapRwLockParkingLot(repo) => Some(repo.get(key)?.read().clone()), + Repo::DashMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), + } + } + + pub(crate) async fn get_metrics(&self) -> AggregateSwarmMetadata { + match self { + Repo::RwLockStd(repo) => repo.get_metrics(), + Repo::RwLockStdMutexStd(repo) => repo.get_metrics(), + Repo::RwLockStdMutexTokio(repo) => repo.get_metrics().await, + Repo::RwLockTokio(repo) => repo.get_metrics().await, + Repo::RwLockTokioMutexStd(repo) => repo.get_metrics().await, + Repo::RwLockTokioMutexTokio(repo) => repo.get_metrics().await, + Repo::SkipMapMutexStd(repo) => repo.get_metrics(), + Repo::SkipMapMutexParkingLot(repo) => repo.get_metrics(), + Repo::SkipMapRwLockParkingLot(repo) => repo.get_metrics(), + Repo::DashMapMutexStd(repo) => repo.get_metrics(), + } + } + + pub(crate) async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { + match self { + Repo::RwLockStd(repo) => repo.get_paginated(pagination), + Repo::RwLockStdMutexStd(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) + .collect(), + Repo::RwLockStdMutexTokio(repo) => { + let mut v: Vec<(InfoHash, EntrySingle)> = vec![]; + + for (i, t) in repo.get_paginated(pagination).await { + v.push((i, t.lock().await.clone())); + } + v + } + Repo::RwLockTokio(repo) => repo.get_paginated(pagination).await, + Repo::RwLockTokioMutexStd(repo) => repo + .get_paginated(pagination) + .await + .iter() + .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) + .collect(), + Repo::RwLockTokioMutexTokio(repo) => { + let mut v: Vec<(InfoHash, EntrySingle)> = vec![]; + + for (i, t) in repo.get_paginated(pagination).await { + v.push((i, t.lock().await.clone())); + } + v + } + Repo::SkipMapMutexStd(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) + .collect(), + Repo::SkipMapMutexParkingLot(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.lock().clone())) + .collect(), + Repo::SkipMapRwLockParkingLot(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.read().clone())) + .collect(), + Repo::DashMapMutexStd(repo) => repo + .get_paginated(pagination) + .iter() + .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) + .collect(), + } + } + + pub(crate) async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + match self { + Repo::RwLockStd(repo) => repo.import_persistent(persistent_torrents), + Repo::RwLockStdMutexStd(repo) => repo.import_persistent(persistent_torrents), + Repo::RwLockStdMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, + Repo::RwLockTokio(repo) => repo.import_persistent(persistent_torrents).await, + Repo::RwLockTokioMutexStd(repo) => repo.import_persistent(persistent_torrents).await, + Repo::RwLockTokioMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, + Repo::SkipMapMutexStd(repo) => repo.import_persistent(persistent_torrents), + Repo::SkipMapMutexParkingLot(repo) => repo.import_persistent(persistent_torrents), + Repo::SkipMapRwLockParkingLot(repo) => repo.import_persistent(persistent_torrents), + Repo::DashMapMutexStd(repo) => repo.import_persistent(persistent_torrents), + } + } + + pub(crate) async fn remove(&self, key: &InfoHash) -> Option { + match self { + Repo::RwLockStd(repo) => repo.remove(key), + Repo::RwLockStdMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), + Repo::RwLockStdMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), + Repo::RwLockTokio(repo) => repo.remove(key).await, + Repo::RwLockTokioMutexStd(repo) => Some(repo.remove(key).await?.lock().unwrap().clone()), + Repo::RwLockTokioMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), + Repo::SkipMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), + Repo::SkipMapMutexParkingLot(repo) => Some(repo.remove(key)?.lock().clone()), + Repo::SkipMapRwLockParkingLot(repo) => Some(repo.remove(key)?.write().clone()), + Repo::DashMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), + } + } + + pub(crate) async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + match self { + Repo::RwLockStd(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::RwLockStdMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::RwLockStdMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::RwLockTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::RwLockTokioMutexStd(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::RwLockTokioMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, + Repo::SkipMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::SkipMapMutexParkingLot(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::SkipMapRwLockParkingLot(repo) => repo.remove_inactive_peers(current_cutoff), + Repo::DashMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), + } + } + + pub(crate) async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + match self { + Repo::RwLockStd(repo) => repo.remove_peerless_torrents(policy), + Repo::RwLockStdMutexStd(repo) => repo.remove_peerless_torrents(policy), + Repo::RwLockStdMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, + Repo::RwLockTokio(repo) => repo.remove_peerless_torrents(policy).await, + Repo::RwLockTokioMutexStd(repo) => repo.remove_peerless_torrents(policy).await, + Repo::RwLockTokioMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, + Repo::SkipMapMutexStd(repo) => repo.remove_peerless_torrents(policy), + Repo::SkipMapMutexParkingLot(repo) => repo.remove_peerless_torrents(policy), + Repo::SkipMapRwLockParkingLot(repo) => repo.remove_peerless_torrents(policy), + Repo::DashMapMutexStd(repo) => repo.remove_peerless_torrents(policy), + } + } + + pub(crate) async fn insert(&self, info_hash: &InfoHash, torrent: EntrySingle) -> Option { + match self { + Repo::RwLockStd(repo) => { + repo.write().insert(*info_hash, torrent); + } + Repo::RwLockStdMutexStd(repo) => { + repo.write().insert(*info_hash, torrent.into()); + } + Repo::RwLockStdMutexTokio(repo) => { + repo.write().insert(*info_hash, torrent.into()); + } + Repo::RwLockTokio(repo) => { + repo.write().await.insert(*info_hash, torrent); + } + Repo::RwLockTokioMutexStd(repo) => { + repo.write().await.insert(*info_hash, torrent.into()); + } + Repo::RwLockTokioMutexTokio(repo) => { + repo.write().await.insert(*info_hash, torrent.into()); + } + Repo::SkipMapMutexStd(repo) => { + repo.torrents.insert(*info_hash, torrent.into()); + } + Repo::SkipMapMutexParkingLot(repo) => { + repo.torrents.insert(*info_hash, torrent.into()); + } + Repo::SkipMapRwLockParkingLot(repo) => { + repo.torrents.insert(*info_hash, torrent.into()); + } + Repo::DashMapMutexStd(repo) => { + repo.torrents.insert(*info_hash, torrent.into()); + } + } + self.get(info_hash).await + } +} diff --git a/packages/torrent-repository-benchmarking/tests/common/torrent.rs b/packages/torrent-repository-benchmarking/tests/common/torrent.rs new file mode 100644 index 000000000..02874f9fc --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/common/torrent.rs @@ -0,0 +1,101 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; +use torrust_tracker_torrent_repository_benchmarking::entry::{Entry as _, EntryAsync as _, EntrySync as _}; +use torrust_tracker_torrent_repository_benchmarking::{ + EntryMutexParkingLot, EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle, +}; + +#[derive(Debug, Clone)] +pub(crate) enum Torrent { + Single(EntrySingle), + MutexStd(EntryMutexStd), + MutexTokio(EntryMutexTokio), + MutexParkingLot(EntryMutexParkingLot), + RwLockParkingLot(EntryRwLockParkingLot), +} + +impl Torrent { + pub(crate) async fn get_stats(&self) -> SwarmMetadata { + match self { + Torrent::Single(entry) => entry.get_swarm_metadata(), + Torrent::MutexStd(entry) => entry.get_swarm_metadata(), + Torrent::MutexTokio(entry) => entry.clone().get_swarm_metadata().await, + Torrent::MutexParkingLot(entry) => entry.clone().get_swarm_metadata(), + Torrent::RwLockParkingLot(entry) => entry.clone().get_swarm_metadata(), + } + } + + pub(crate) async fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + match self { + Torrent::Single(entry) => entry.meets_retaining_policy(policy), + Torrent::MutexStd(entry) => entry.meets_retaining_policy(policy), + Torrent::MutexTokio(entry) => entry.clone().meets_retaining_policy(policy).await, + Torrent::MutexParkingLot(entry) => entry.meets_retaining_policy(policy), + Torrent::RwLockParkingLot(entry) => entry.meets_retaining_policy(policy), + } + } + + pub(crate) async fn peers_is_empty(&self) -> bool { + match self { + Torrent::Single(entry) => entry.peers_is_empty(), + Torrent::MutexStd(entry) => entry.peers_is_empty(), + Torrent::MutexTokio(entry) => entry.clone().peers_is_empty().await, + Torrent::MutexParkingLot(entry) => entry.peers_is_empty(), + Torrent::RwLockParkingLot(entry) => entry.peers_is_empty(), + } + } + + pub(crate) async fn get_peers_len(&self) -> usize { + match self { + Torrent::Single(entry) => entry.get_peers_len(), + Torrent::MutexStd(entry) => entry.get_peers_len(), + Torrent::MutexTokio(entry) => entry.clone().get_peers_len().await, + Torrent::MutexParkingLot(entry) => entry.get_peers_len(), + Torrent::RwLockParkingLot(entry) => entry.get_peers_len(), + } + } + + pub(crate) async fn get_peers(&self, limit: Option) -> Vec> { + match self { + Torrent::Single(entry) => entry.get_peers(limit), + Torrent::MutexStd(entry) => entry.get_peers(limit), + Torrent::MutexTokio(entry) => entry.clone().get_peers(limit).await, + Torrent::MutexParkingLot(entry) => entry.get_peers(limit), + Torrent::RwLockParkingLot(entry) => entry.get_peers(limit), + } + } + + pub(crate) async fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + match self { + Torrent::Single(entry) => entry.get_peers_for_client(client, limit), + Torrent::MutexStd(entry) => entry.get_peers_for_client(client, limit), + Torrent::MutexTokio(entry) => entry.clone().get_peers_for_client(client, limit).await, + Torrent::MutexParkingLot(entry) => entry.get_peers_for_client(client, limit), + Torrent::RwLockParkingLot(entry) => entry.get_peers_for_client(client, limit), + } + } + + pub(crate) async fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { + match self { + Torrent::Single(entry) => entry.upsert_peer(peer), + Torrent::MutexStd(entry) => entry.upsert_peer(peer), + Torrent::MutexTokio(entry) => entry.clone().upsert_peer(peer).await, + Torrent::MutexParkingLot(entry) => entry.upsert_peer(peer), + Torrent::RwLockParkingLot(entry) => entry.upsert_peer(peer), + } + } + + pub(crate) async fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + match self { + Torrent::Single(entry) => entry.remove_inactive_peers(current_cutoff), + Torrent::MutexStd(entry) => entry.remove_inactive_peers(current_cutoff), + Torrent::MutexTokio(entry) => entry.clone().remove_inactive_peers(current_cutoff).await, + Torrent::MutexParkingLot(entry) => entry.remove_inactive_peers(current_cutoff), + Torrent::RwLockParkingLot(entry) => entry.remove_inactive_peers(current_cutoff), + } + } +} diff --git a/packages/torrent-repository-benchmarking/tests/common/torrent_peer_builder.rs b/packages/torrent-repository-benchmarking/tests/common/torrent_peer_builder.rs new file mode 100644 index 000000000..33120180d --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/common/torrent_peer_builder.rs @@ -0,0 +1,90 @@ +use std::net::SocketAddr; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; + +use crate::CurrentClock; + +#[derive(Debug, Default)] +struct TorrentPeerBuilder { + peer: peer::Peer, +} + +#[allow(dead_code)] +impl TorrentPeerBuilder { + #[must_use] + fn new() -> Self { + Self { + peer: peer::Peer { + updated: CurrentClock::now(), + ..Default::default() + }, + } + } + + #[must_use] + fn with_event_completed(mut self) -> Self { + self.peer.event = AnnounceEvent::Completed; + self + } + + #[must_use] + fn with_event_started(mut self) -> Self { + self.peer.event = AnnounceEvent::Started; + self + } + + #[must_use] + fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { + self.peer.peer_addr = peer_addr; + self + } + + #[must_use] + fn with_peer_id(mut self, peer_id: PeerId) -> Self { + self.peer.peer_id = peer_id; + self + } + + #[must_use] + fn with_number_of_bytes_left(mut self, left: i64) -> Self { + self.peer.left = NumberOfBytes::new(left); + self + } + + #[must_use] + fn updated_at(mut self, updated: DurationSinceUnixEpoch) -> Self { + self.peer.updated = updated; + self + } + + #[must_use] + fn into(self) -> peer::Peer { + self.peer + } +} + +/// A torrent seeder is a peer with 0 bytes left to download which +/// has not announced it has stopped +#[must_use] +pub fn a_completed_peer(id: i32) -> peer::Peer { + let peer_id = peer::Id::new(id); + TorrentPeerBuilder::new() + .with_number_of_bytes_left(0) + .with_event_completed() + .with_peer_id(*peer_id) + .into() +} + +/// A torrent leecher is a peer that is not a seeder. +/// Leecher: left > 0 OR event = Stopped +#[must_use] +pub fn a_started_peer(id: i32) -> peer::Peer { + let peer_id = peer::Id::new(id); + TorrentPeerBuilder::new() + .with_number_of_bytes_left(1) + .with_event_started() + .with_peer_id(*peer_id) + .into() +} diff --git a/packages/torrent-repository-benchmarking/tests/entry/mod.rs b/packages/torrent-repository-benchmarking/tests/entry/mod.rs new file mode 100644 index 000000000..b46c05415 --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/entry/mod.rs @@ -0,0 +1,443 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::ops::Sub; +use std::time::Duration; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use rstest::{fixture, rstest}; +use torrust_tracker_clock::clock::stopped::Stopped as _; +use torrust_tracker_clock::clock::{self, Time as _}; +use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; +use torrust_tracker_primitives::peer; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_torrent_repository_benchmarking::{ + EntryMutexParkingLot, EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle, +}; + +use crate::common::torrent::Torrent; +use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; +use crate::CurrentClock; + +#[fixture] +fn single() -> Torrent { + Torrent::Single(EntrySingle::default()) +} +#[fixture] +fn mutex_std() -> Torrent { + Torrent::MutexStd(EntryMutexStd::default()) +} + +#[fixture] +fn mutex_tokio() -> Torrent { + Torrent::MutexTokio(EntryMutexTokio::default()) +} + +#[fixture] +fn mutex_parking_lot() -> Torrent { + Torrent::MutexParkingLot(EntryMutexParkingLot::default()) +} + +#[fixture] +fn rw_lock_parking_lot() -> Torrent { + Torrent::RwLockParkingLot(EntryRwLockParkingLot::default()) +} + +#[fixture] +fn policy_none() -> TrackerPolicy { + TrackerPolicy::new(0, false, false) +} + +#[fixture] +fn policy_persist() -> TrackerPolicy { + TrackerPolicy::new(0, true, false) +} + +#[fixture] +fn policy_remove() -> TrackerPolicy { + TrackerPolicy::new(0, false, true) +} + +#[fixture] +fn policy_remove_persist() -> TrackerPolicy { + TrackerPolicy::new(0, true, true) +} + +pub enum Makes { + Empty, + Started, + Completed, + Downloaded, + Three, +} + +async fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { + match makes { + Makes::Empty => vec![], + Makes::Started => { + let peer = a_started_peer(1); + torrent.upsert_peer(&peer).await; + vec![peer] + } + Makes::Completed => { + let peer = a_completed_peer(2); + torrent.upsert_peer(&peer).await; + vec![peer] + } + Makes::Downloaded => { + let mut peer = a_started_peer(3); + torrent.upsert_peer(&peer).await; + peer.event = AnnounceEvent::Completed; + peer.left = NumberOfBytes::new(0); + torrent.upsert_peer(&peer).await; + vec![peer] + } + Makes::Three => { + let peer_1 = a_started_peer(1); + torrent.upsert_peer(&peer_1).await; + + let peer_2 = a_completed_peer(2); + torrent.upsert_peer(&peer_2).await; + + let mut peer_3 = a_started_peer(3); + torrent.upsert_peer(&peer_3).await; + peer_3.event = AnnounceEvent::Completed; + peer_3.left = NumberOfBytes::new(0); + torrent.upsert_peer(&peer_3).await; + vec![peer_1, peer_2, peer_3] + } + } +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[tokio::test] +async fn it_should_be_empty_by_default( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + + assert_eq!(torrent.get_peers_len().await, 0); +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_check_if_entry_should_be_retained_based_on_the_tracker_policy( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, + #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, +) { + make(&mut torrent, makes).await; + + let has_peers = !torrent.peers_is_empty().await; + let has_downloads = torrent.get_stats().await.downloaded != 0; + + match (policy.remove_peerless_torrents, policy.persistent_torrent_completed_stat) { + // remove torrents without peers, and keep completed download stats + (true, true) => match (has_peers, has_downloads) { + // no peers, but has downloads + // peers, with or without downloads + (false, true) | (true, true | false) => assert!(torrent.meets_retaining_policy(&policy).await), + // no peers and no downloads + (false, false) => assert!(!torrent.meets_retaining_policy(&policy).await), + }, + // remove torrents without peers and drop completed download stats + (true, false) => match (has_peers, has_downloads) { + // peers, with or without downloads + (true, true | false) => assert!(torrent.meets_retaining_policy(&policy).await), + // no peers and with or without downloads + (false, true | false) => assert!(!torrent.meets_retaining_policy(&policy).await), + }, + // keep torrents without peers, but keep or drop completed download stats + (false, true | false) => assert!(torrent.meets_retaining_policy(&policy).await), + } +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_get_peers_for_torrent_entry( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + let peers = make(&mut torrent, makes).await; + + let torrent_peers = torrent.get_peers(None).await; + + assert_eq!(torrent_peers.len(), peers.len()); + + for peer in torrent_peers { + assert!(peers.contains(&peer)); + } +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_update_a_peer(#[values(single(), mutex_std(), mutex_tokio())] mut torrent: Torrent, #[case] makes: &Makes) { + make(&mut torrent, makes).await; + + // Make and insert a new peer. + let mut peer = a_started_peer(-1); + torrent.upsert_peer(&peer).await; + + // Get the Inserted Peer by Id. + let peers = torrent.get_peers(None).await; + let original = peers + .iter() + .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) + .expect("it should find peer by id"); + + assert_eq!(original.event, AnnounceEvent::Started, "it should be as created"); + + // Announce "Completed" torrent download event. + peer.event = AnnounceEvent::Completed; + torrent.upsert_peer(&peer).await; + + // Get the Updated Peer by Id. + let peers = torrent.get_peers(None).await; + let updated = peers + .iter() + .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) + .expect("it should find peer by id"); + + assert_eq!(updated.event, AnnounceEvent::Completed, "it should be updated"); +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_remove_a_peer_upon_stopped_announcement( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + use torrust_tracker_primitives::peer::ReadInfo as _; + + make(&mut torrent, makes).await; + + let mut peer = a_started_peer(-1); + + torrent.upsert_peer(&peer).await; + + // The started peer should be inserted. + let peers = torrent.get_peers(None).await; + let original = peers + .iter() + .find(|p| p.get_id() == peer.get_id()) + .expect("it should find peer by id"); + + assert_eq!(original.event, AnnounceEvent::Started); + + // Change peer to "Stopped" and insert. + peer.event = AnnounceEvent::Stopped; + torrent.upsert_peer(&peer).await; + + // It should be removed now. + let peers = torrent.get_peers(None).await; + + assert_eq!( + peers.iter().find(|p| p.get_id() == peer.get_id()), + None, + "it should be removed" + ); +} + +#[rstest] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloaded_statistic( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + let downloaded = torrent.get_stats().await.downloaded; + + let peers = torrent.get_peers(None).await; + let mut peer = **peers.first().expect("there should be a peer"); + + let is_already_completed = peer.event == AnnounceEvent::Completed; + + // Announce "Completed" torrent download event. + peer.event = AnnounceEvent::Completed; + + torrent.upsert_peer(&peer).await; + let stats = torrent.get_stats().await; + + if is_already_completed { + assert_eq!(stats.downloaded, downloaded); + } else { + assert_eq!(stats.downloaded, downloaded + 1); + } +} + +#[rstest] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_update_a_peer_as_a_seeder( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + let peers = make(&mut torrent, makes).await; + let completed = u32::try_from(peers.iter().filter(|p| p.is_seeder()).count()).expect("it_should_not_be_so_many"); + + let peers = torrent.get_peers(None).await; + let mut peer = **peers.first().expect("there should be a peer"); + + let is_already_non_left = peer.left == NumberOfBytes::new(0); + + // Set Bytes Left to Zero + peer.left = NumberOfBytes::new(0); + torrent.upsert_peer(&peer).await; + let stats = torrent.get_stats().await; + + if is_already_non_left { + // it was already complete + assert_eq!(stats.complete, completed); + } else { + // now it is complete + assert_eq!(stats.complete, completed + 1); + } +} + +#[rstest] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_update_a_peer_as_incomplete( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + let peers = make(&mut torrent, makes).await; + let incomplete = u32::try_from(peers.iter().filter(|p| !p.is_seeder()).count()).expect("it should not be so many"); + + let peers = torrent.get_peers(None).await; + let mut peer = **peers.first().expect("there should be a peer"); + + let completed_already = peer.left == NumberOfBytes::new(0); + + // Set Bytes Left to no Zero + peer.left = NumberOfBytes::new(1); + torrent.upsert_peer(&peer).await; + let stats = torrent.get_stats().await; + + if completed_already { + // now it is incomplete + assert_eq!(stats.incomplete, incomplete + 1); + } else { + // was already incomplete + assert_eq!(stats.incomplete, incomplete); + } +} + +#[rstest] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_get_peers_excluding_the_client_socket( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + + let peers = torrent.get_peers(None).await; + let mut peer = **peers.first().expect("there should be a peer"); + + let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8081); + + // for this test, we should not already use this socket. + assert_ne!(peer.peer_addr, socket); + + // it should get the peer as it dose not share the socket. + assert!(torrent.get_peers_for_client(&socket, None).await.contains(&peer.into())); + + // set the address to the socket. + peer.peer_addr = socket; + torrent.upsert_peer(&peer).await; // Add peer + + // It should not include the peer that has the same socket. + assert!(!torrent.get_peers_for_client(&socket, None).await.contains(&peer.into())); +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_limit_the_number_of_peers_returned( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + make(&mut torrent, makes).await; + + // We add one more peer than the scrape limit + for peer_number in 1..=74 + 1 { + let mut peer = a_started_peer(1); + peer.peer_id = *peer::Id::new(peer_number); + torrent.upsert_peer(&peer).await; + } + + let peers = torrent.get_peers(Some(TORRENT_PEERS_LIMIT)).await; + + assert_eq!(peers.len(), 74); +} + +#[rstest] +#[case::empty(&Makes::Empty)] +#[case::started(&Makes::Started)] +#[case::completed(&Makes::Completed)] +#[case::downloaded(&Makes::Downloaded)] +#[case::three(&Makes::Three)] +#[tokio::test] +async fn it_should_remove_inactive_peers_beyond_cutoff( + #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[case] makes: &Makes, +) { + const TIMEOUT: Duration = Duration::from_secs(120); + const EXPIRE: Duration = Duration::from_secs(121); + + let peers = make(&mut torrent, makes).await; + + let mut peer = a_completed_peer(-1); + + let now = clock::Working::now(); + clock::Stopped::local_set(&now); + + peer.updated = now.sub(EXPIRE); + + torrent.upsert_peer(&peer).await; + + assert_eq!(torrent.get_peers_len().await, peers.len() + 1); + + let current_cutoff = CurrentClock::now_sub(&TIMEOUT).unwrap_or_default(); + torrent.remove_inactive_peers(current_cutoff).await; + + assert_eq!(torrent.get_peers_len().await, peers.len()); +} diff --git a/packages/torrent-repository-benchmarking/tests/integration.rs b/packages/torrent-repository-benchmarking/tests/integration.rs new file mode 100644 index 000000000..5aab67b03 --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/integration.rs @@ -0,0 +1,22 @@ +//! Integration tests. +//! +//! ```text +//! cargo test --test integration +//! ``` + +use torrust_tracker_clock::clock; + +pub mod common; +mod entry; +mod repository; + +/// This code needs to be copied into each crate. +/// Working version, for production. +#[cfg(not(test))] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Working; + +/// Stopped version, for testing. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) type CurrentClock = clock::Stopped; diff --git a/packages/torrent-repository-benchmarking/tests/repository/mod.rs b/packages/torrent-repository-benchmarking/tests/repository/mod.rs new file mode 100644 index 000000000..6973f38bd --- /dev/null +++ b/packages/torrent-repository-benchmarking/tests/repository/mod.rs @@ -0,0 +1,639 @@ +use std::collections::{BTreeMap, HashSet}; +use std::hash::{DefaultHasher, Hash, Hasher}; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use bittorrent_primitives::info_hash::InfoHash; +use rstest::{fixture, rstest}; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::pagination::Pagination; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::PersistentTorrents; +use torrust_tracker_torrent_repository_benchmarking::entry::Entry as _; +use torrust_tracker_torrent_repository_benchmarking::repository::dash_map_mutex_std::XacrimonDashMap; +use torrust_tracker_torrent_repository_benchmarking::repository::rw_lock_std::RwLockStd; +use torrust_tracker_torrent_repository_benchmarking::repository::rw_lock_tokio::RwLockTokio; +use torrust_tracker_torrent_repository_benchmarking::repository::skip_map_mutex_std::CrossbeamSkipList; +use torrust_tracker_torrent_repository_benchmarking::EntrySingle; + +use crate::common::repo::Repo; +use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; + +#[fixture] +fn standard() -> Repo { + Repo::RwLockStd(RwLockStd::default()) +} + +#[fixture] +fn standard_mutex() -> Repo { + Repo::RwLockStdMutexStd(RwLockStd::default()) +} + +#[fixture] +fn standard_tokio() -> Repo { + Repo::RwLockStdMutexTokio(RwLockStd::default()) +} + +#[fixture] +fn tokio_std() -> Repo { + Repo::RwLockTokio(RwLockTokio::default()) +} + +#[fixture] +fn tokio_mutex() -> Repo { + Repo::RwLockTokioMutexStd(RwLockTokio::default()) +} + +#[fixture] +fn tokio_tokio() -> Repo { + Repo::RwLockTokioMutexTokio(RwLockTokio::default()) +} + +#[fixture] +fn skip_list_mutex_std() -> Repo { + Repo::SkipMapMutexStd(CrossbeamSkipList::default()) +} + +#[fixture] +fn skip_list_mutex_parking_lot() -> Repo { + Repo::SkipMapMutexParkingLot(CrossbeamSkipList::default()) +} + +#[fixture] +fn skip_list_rw_lock_parking_lot() -> Repo { + Repo::SkipMapRwLockParkingLot(CrossbeamSkipList::default()) +} + +#[fixture] +fn dash_map_std() -> Repo { + Repo::DashMapMutexStd(XacrimonDashMap::default()) +} + +type Entries = Vec<(InfoHash, EntrySingle)>; + +#[fixture] +fn empty() -> Entries { + vec![] +} + +#[fixture] +fn default() -> Entries { + vec![(InfoHash::default(), EntrySingle::default())] +} + +#[fixture] +fn started() -> Entries { + let mut torrent = EntrySingle::default(); + torrent.upsert_peer(&a_started_peer(1)); + vec![(InfoHash::default(), torrent)] +} + +#[fixture] +fn completed() -> Entries { + let mut torrent = EntrySingle::default(); + torrent.upsert_peer(&a_completed_peer(2)); + vec![(InfoHash::default(), torrent)] +} + +#[fixture] +fn downloaded() -> Entries { + let mut torrent = EntrySingle::default(); + let mut peer = a_started_peer(3); + torrent.upsert_peer(&peer); + peer.event = AnnounceEvent::Completed; + peer.left = NumberOfBytes::new(0); + torrent.upsert_peer(&peer); + vec![(InfoHash::default(), torrent)] +} + +#[fixture] +fn three() -> Entries { + let mut started = EntrySingle::default(); + let started_h = &mut DefaultHasher::default(); + started.upsert_peer(&a_started_peer(1)); + started.hash(started_h); + + let mut completed = EntrySingle::default(); + let completed_h = &mut DefaultHasher::default(); + completed.upsert_peer(&a_completed_peer(2)); + completed.hash(completed_h); + + let mut downloaded = EntrySingle::default(); + let downloaded_h = &mut DefaultHasher::default(); + let mut downloaded_peer = a_started_peer(3); + downloaded.upsert_peer(&downloaded_peer); + downloaded_peer.event = AnnounceEvent::Completed; + downloaded_peer.left = NumberOfBytes::new(0); + downloaded.upsert_peer(&downloaded_peer); + downloaded.hash(downloaded_h); + + vec![ + (InfoHash::from(&started_h.clone()), started), + (InfoHash::from(&completed_h.clone()), completed), + (InfoHash::from(&downloaded_h.clone()), downloaded), + ] +} + +#[fixture] +fn many_out_of_order() -> Entries { + let mut entries: HashSet<(InfoHash, EntrySingle)> = HashSet::default(); + + for i in 0..408 { + let mut entry = EntrySingle::default(); + entry.upsert_peer(&a_started_peer(i)); + + entries.insert((InfoHash::from(&i), entry)); + } + + // we keep the random order from the hashed set for the vector. + entries.iter().map(|(i, e)| (*i, e.clone())).collect() +} + +#[fixture] +fn many_hashed_in_order() -> Entries { + let mut entries: BTreeMap = BTreeMap::default(); + + for i in 0..408 { + let mut entry = EntrySingle::default(); + entry.upsert_peer(&a_started_peer(i)); + + let hash: &mut DefaultHasher = &mut DefaultHasher::default(); + hash.write_i32(i); + + entries.insert(InfoHash::from(&hash.clone()), entry); + } + + // We return the entries in-order from from the b-tree map. + entries.iter().map(|(i, e)| (*i, e.clone())).collect() +} + +#[fixture] +fn persistent_empty() -> PersistentTorrents { + PersistentTorrents::default() +} + +#[fixture] +fn persistent_single() -> PersistentTorrents { + let hash = &mut DefaultHasher::default(); + + hash.write_u8(1); + let t = [(InfoHash::from(&hash.clone()), 0_u32)]; + + t.iter().copied().collect() +} + +#[fixture] +fn persistent_three() -> PersistentTorrents { + let hash = &mut DefaultHasher::default(); + + hash.write_u8(1); + let info_1 = InfoHash::from(&hash.clone()); + hash.write_u8(2); + let info_2 = InfoHash::from(&hash.clone()); + hash.write_u8(3); + let info_3 = InfoHash::from(&hash.clone()); + + let t = [(info_1, 1_u32), (info_2, 2_u32), (info_3, 3_u32)]; + + t.iter().copied().collect() +} + +async fn make(repo: &Repo, entries: &Entries) { + for (info_hash, entry) in entries { + repo.insert(info_hash, entry.clone()).await; + } +} + +#[fixture] +fn paginated_limit_zero() -> Pagination { + Pagination::new(0, 0) +} + +#[fixture] +fn paginated_limit_one() -> Pagination { + Pagination::new(0, 1) +} + +#[fixture] +fn paginated_limit_one_offset_one() -> Pagination { + Pagination::new(1, 1) +} + +#[fixture] +fn policy_none() -> TrackerPolicy { + TrackerPolicy::new(0, false, false) +} + +#[fixture] +fn policy_persist() -> TrackerPolicy { + TrackerPolicy::new(0, true, false) +} + +#[fixture] +fn policy_remove() -> TrackerPolicy { + TrackerPolicy::new(0, false, true) +} + +#[fixture] +fn policy_remove_persist() -> TrackerPolicy { + TrackerPolicy::new(0, true, true) +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_get_a_torrent_entry( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot(), + dash_map_std() + )] + repo: Repo, + #[case] entries: Entries, +) { + make(&repo, &entries).await; + + if let Some((info_hash, torrent)) = entries.first() { + assert_eq!(repo.get(info_hash).await, Some(torrent.clone())); + } else { + assert_eq!(repo.get(&InfoHash::default()).await, None); + } +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot() + )] + repo: Repo, + #[case] entries: Entries, + many_out_of_order: Entries, +) { + make(&repo, &entries).await; + + let entries_a = repo.get_paginated(None).await.iter().map(|(i, _)| *i).collect::>(); + + make(&repo, &many_out_of_order).await; + + let entries_b = repo.get_paginated(None).await.iter().map(|(i, _)| *i).collect::>(); + + let is_equal = entries_b.iter().take(entries_a.len()).copied().collect::>() == entries_a; + + let is_sorted = entries_b.windows(2).all(|w| w[0] <= w[1]); + + assert!( + is_equal || is_sorted, + "The order is unstable: {is_equal}, or is sorted {is_sorted}." + ); +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_get_paginated( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot() + )] + repo: Repo, + #[case] entries: Entries, + #[values(paginated_limit_zero(), paginated_limit_one(), paginated_limit_one_offset_one())] paginated: Pagination, +) { + make(&repo, &entries).await; + + let mut info_hashes = repo.get_paginated(None).await.iter().map(|(i, _)| *i).collect::>(); + info_hashes.sort(); + + match paginated { + // it should return empty if limit is zero. + Pagination { limit: 0, .. } => assert_eq!(repo.get_paginated(Some(&paginated)).await, vec![]), + + // it should return a single entry if the limit is one. + Pagination { limit: 1, offset: 0 } => { + if info_hashes.is_empty() { + assert_eq!(repo.get_paginated(Some(&paginated)).await.len(), 0); + } else { + let page = repo.get_paginated(Some(&paginated)).await; + assert_eq!(page.len(), 1); + assert_eq!(page.first().map(|(i, _)| i), info_hashes.first()); + } + } + + // it should return the only the second entry if both the limit and the offset are one. + Pagination { limit: 1, offset: 1 } => { + if info_hashes.len() > 1 { + let page = repo.get_paginated(Some(&paginated)).await; + assert_eq!(page.len(), 1); + assert_eq!(page[0].0, info_hashes[1]); + } + } + // the other cases are not yet tested. + _ => {} + } +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_get_metrics( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot(), + dash_map_std() + )] + repo: Repo, + #[case] entries: Entries, +) { + use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; + + make(&repo, &entries).await; + + let mut metrics = AggregateSwarmMetadata::default(); + + for (_, torrent) in entries { + let stats = torrent.get_swarm_metadata(); + + metrics.total_torrents += 1; + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + } + + assert_eq!(repo.get_metrics().await, metrics); +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_import_persistent_torrents( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot(), + dash_map_std() + )] + repo: Repo, + #[case] entries: Entries, + #[values(persistent_empty(), persistent_single(), persistent_three())] persistent_torrents: PersistentTorrents, +) { + make(&repo, &entries).await; + + let mut downloaded = repo.get_metrics().await.total_downloaded; + persistent_torrents.iter().for_each(|(_, d)| downloaded += u64::from(*d)); + + repo.import_persistent(&persistent_torrents).await; + + assert_eq!(repo.get_metrics().await.total_downloaded, downloaded); + + for (entry, _) in persistent_torrents { + assert!(repo.get(&entry).await.is_some()); + } +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_remove_an_entry( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot(), + dash_map_std() + )] + repo: Repo, + #[case] entries: Entries, +) { + make(&repo, &entries).await; + + for (info_hash, torrent) in entries { + assert_eq!(repo.get(&info_hash).await, Some(torrent.clone())); + assert_eq!(repo.remove(&info_hash).await, Some(torrent)); + + assert_eq!(repo.get(&info_hash).await, None); + assert_eq!(repo.remove(&info_hash).await, None); + } + + assert_eq!(repo.get_metrics().await.total_torrents, 0); +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_remove_inactive_peers( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot(), + dash_map_std() + )] + repo: Repo, + #[case] entries: Entries, +) { + use std::ops::Sub as _; + use std::time::Duration; + + use torrust_tracker_clock::clock::stopped::Stopped as _; + use torrust_tracker_clock::clock::{self, Time as _}; + use torrust_tracker_primitives::peer; + + use crate::CurrentClock; + + const TIMEOUT: Duration = Duration::from_secs(120); + const EXPIRE: Duration = Duration::from_secs(121); + + make(&repo, &entries).await; + + let info_hash: InfoHash; + let mut peer: peer::Peer; + + // Generate a new infohash and peer. + { + let hash = &mut DefaultHasher::default(); + hash.write_u8(255); + info_hash = InfoHash::from(&hash.clone()); + peer = a_completed_peer(-1); + } + + // Set the last updated time of the peer to be 121 seconds ago. + { + let now = clock::Working::now(); + clock::Stopped::local_set(&now); + + peer.updated = now.sub(EXPIRE); + } + + // Insert the infohash and peer into the repository + // and verify there is an extra torrent entry. + { + repo.upsert_peer(&info_hash, &peer, None).await; + assert_eq!(repo.get_metrics().await.total_torrents, entries.len() as u64 + 1); + } + + // Insert the infohash and peer into the repository + // and verify the swarm metadata was updated. + { + repo.upsert_peer(&info_hash, &peer, None).await; + let stats = repo.get_swarm_metadata(&info_hash).await; + assert_eq!( + stats, + Some(SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }) + ); + } + + // Verify that this new peer was inserted into the repository. + { + let entry = repo.get(&info_hash).await.expect("it_should_get_some"); + assert!(entry.get_peers(None).contains(&peer.into())); + } + + // Remove peers that have not been updated since the timeout (120 seconds ago). + { + repo.remove_inactive_peers(CurrentClock::now_sub(&TIMEOUT).expect("it should get a time passed")) + .await; + } + + // Verify that the this peer was removed from the repository. + { + let entry = repo.get(&info_hash).await.expect("it_should_get_some"); + assert!(!entry.get_peers(None).contains(&peer.into())); + } +} + +#[rstest] +#[case::empty(empty())] +#[case::default(default())] +#[case::started(started())] +#[case::completed(completed())] +#[case::downloaded(downloaded())] +#[case::three(three())] +#[case::out_of_order(many_out_of_order())] +#[case::in_order(many_hashed_in_order())] +#[tokio::test] +async fn it_should_remove_peerless_torrents( + #[values( + standard(), + standard_mutex(), + standard_tokio(), + tokio_std(), + tokio_mutex(), + tokio_tokio(), + skip_list_mutex_std(), + skip_list_mutex_parking_lot(), + skip_list_rw_lock_parking_lot(), + dash_map_std() + )] + repo: Repo, + #[case] entries: Entries, + #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, +) { + make(&repo, &entries).await; + + repo.remove_peerless_torrents(&policy).await; + + let torrents = repo.get_paginated(None).await; + + for (_, entry) in torrents { + assert!(entry.meets_retaining_policy(&policy)); + } +} From 16a6d08bf49531b482c2d8f7f47f2de0a01352b4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 30 Apr 2025 11:54:37 +0100 Subject: [PATCH 1031/1297] feat!: [#1491] remove unused torrent repositories Repositories that are not used in production. THey have been moved to a new package `torrent-repository-benchmarking`. --- Cargo.lock | 3 - packages/torrent-repository/Cargo.toml | 7 - .../benches/helpers/asyn.rs | 153 ---------- .../torrent-repository/benches/helpers/mod.rs | 3 - .../benches/helpers/sync.rs | 155 ---------- .../benches/helpers/utils.rs | 41 --- .../benches/repository_benchmark.rs | 270 ------------------ packages/torrent-repository/src/lib.rs | 17 +- .../src/repository/dash_map_mutex_std.rs | 111 ------- .../torrent-repository/src/repository/mod.rs | 7 - .../src/repository/rw_lock_std.rs | 132 --------- .../src/repository/rw_lock_std_mutex_std.rs | 130 --------- .../src/repository/rw_lock_std_mutex_tokio.rs | 167 ----------- .../src/repository/rw_lock_tokio.rs | 138 --------- .../src/repository/rw_lock_tokio_mutex_std.rs | 135 --------- .../repository/rw_lock_tokio_mutex_tokio.rs | 148 ---------- .../torrent-repository/tests/common/repo.rs | 182 +----------- .../tests/repository/mod.rs | 249 +++------------- 18 files changed, 61 insertions(+), 1987 deletions(-) delete mode 100644 packages/torrent-repository/benches/helpers/asyn.rs delete mode 100644 packages/torrent-repository/benches/helpers/mod.rs delete mode 100644 packages/torrent-repository/benches/helpers/sync.rs delete mode 100644 packages/torrent-repository/benches/helpers/utils.rs delete mode 100644 packages/torrent-repository/benches/repository_benchmark.rs delete mode 100644 packages/torrent-repository/src/repository/dash_map_mutex_std.rs delete mode 100644 packages/torrent-repository/src/repository/rw_lock_std.rs delete mode 100644 packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs delete mode 100644 packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs delete mode 100644 packages/torrent-repository/src/repository/rw_lock_tokio.rs delete mode 100644 packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs delete mode 100644 packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs diff --git a/Cargo.lock b/Cargo.lock index da46a5a8f..5bce85e46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4841,15 +4841,12 @@ dependencies = [ "bittorrent-primitives", "criterion", "crossbeam-skiplist", - "dashmap", - "futures", "parking_lot", "rstest", "tokio", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-primitives", - "zerocopy 0.7.35", ] [[package]] diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 2097d57d2..d12dcbf44 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -19,20 +19,13 @@ version.workspace = true aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" crossbeam-skiplist = "0" -dashmap = "6" -futures = "0" parking_lot = "0" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -zerocopy = "0.7" [dev-dependencies] async-std = { version = "1", features = ["attributes", "tokio1"] } criterion = { version = "0", features = ["async_tokio"] } rstest = "0" - -[[bench]] -harness = false -name = "repository_benchmark" diff --git a/packages/torrent-repository/benches/helpers/asyn.rs b/packages/torrent-repository/benches/helpers/asyn.rs deleted file mode 100644 index fc6b3ffb0..000000000 --- a/packages/torrent-repository/benches/helpers/asyn.rs +++ /dev/null @@ -1,153 +0,0 @@ -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use bittorrent_primitives::info_hash::InfoHash; -use futures::stream::FuturesUnordered; -use torrust_tracker_torrent_repository::repository::RepositoryAsync; - -use super::utils::{generate_unique_info_hashes, DEFAULT_PEER}; - -pub async fn add_one_torrent(samples: u64) -> Duration -where - V: RepositoryAsync + Default, -{ - let start = Instant::now(); - - for _ in 0..samples { - let torrent_repository = V::default(); - - let info_hash = InfoHash::default(); - - torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; - - torrent_repository.get_swarm_metadata(&info_hash).await; - } - - start.elapsed() -} - -// Add one torrent ten thousand times in parallel (depending on the set worker threads) -pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: u64, sleep: Option) -> Duration -where - V: RepositoryAsync + Default, - Arc: Clone + Send + Sync + 'static, -{ - let torrent_repository = Arc::::default(); - let info_hash = InfoHash::default(); - let handles = FuturesUnordered::new(); - - // Add the torrent/peer to the torrent repository - torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; - - torrent_repository.get_swarm_metadata(&info_hash).await; - - let start = Instant::now(); - - for _ in 0..samples { - let torrent_repository_clone = torrent_repository.clone(); - - let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; - - torrent_repository_clone.get_swarm_metadata(&info_hash).await; - - if let Some(sleep_time) = sleep { - let start_time = std::time::Instant::now(); - - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); - - handles.push(handle); - } - - // Await all tasks - futures::future::join_all(handles).await; - - start.elapsed() -} - -// Add ten thousand torrents in parallel (depending on the set worker threads) -pub async fn add_multiple_torrents_in_parallel( - runtime: &tokio::runtime::Runtime, - samples: u64, - sleep: Option, -) -> Duration -where - V: RepositoryAsync + Default, - Arc: Clone + Send + Sync + 'static, -{ - let torrent_repository = Arc::::default(); - let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in a usize")); - let handles = FuturesUnordered::new(); - - let start = Instant::now(); - - for info_hash in info_hashes { - let torrent_repository_clone = torrent_repository.clone(); - - let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; - - torrent_repository_clone.get_swarm_metadata(&info_hash).await; - - if let Some(sleep_time) = sleep { - let start_time = std::time::Instant::now(); - - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); - - handles.push(handle); - } - - // Await all tasks - futures::future::join_all(handles).await; - - start.elapsed() -} - -// Async update ten thousand torrents in parallel (depending on the set worker threads) -pub async fn update_multiple_torrents_in_parallel( - runtime: &tokio::runtime::Runtime, - samples: u64, - sleep: Option, -) -> Duration -where - V: RepositoryAsync + Default, - Arc: Clone + Send + Sync + 'static, -{ - let torrent_repository = Arc::::default(); - let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in usize")); - let handles = FuturesUnordered::new(); - - // Add the torrents/peers to the torrent repository - for info_hash in &info_hashes { - torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER, None).await; - torrent_repository.get_swarm_metadata(info_hash).await; - } - - let start = Instant::now(); - - for info_hash in info_hashes { - let torrent_repository_clone = torrent_repository.clone(); - - let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None).await; - torrent_repository_clone.get_swarm_metadata(&info_hash).await; - - if let Some(sleep_time) = sleep { - let start_time = std::time::Instant::now(); - - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); - - handles.push(handle); - } - - // Await all tasks - futures::future::join_all(handles).await; - - start.elapsed() -} diff --git a/packages/torrent-repository/benches/helpers/mod.rs b/packages/torrent-repository/benches/helpers/mod.rs deleted file mode 100644 index 1026aa4bf..000000000 --- a/packages/torrent-repository/benches/helpers/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod asyn; -pub mod sync; -pub mod utils; diff --git a/packages/torrent-repository/benches/helpers/sync.rs b/packages/torrent-repository/benches/helpers/sync.rs deleted file mode 100644 index e00401446..000000000 --- a/packages/torrent-repository/benches/helpers/sync.rs +++ /dev/null @@ -1,155 +0,0 @@ -use std::sync::Arc; -use std::time::{Duration, Instant}; - -use bittorrent_primitives::info_hash::InfoHash; -use futures::stream::FuturesUnordered; -use torrust_tracker_torrent_repository::repository::Repository; - -use super::utils::{generate_unique_info_hashes, DEFAULT_PEER}; - -// Simply add one torrent -#[must_use] -pub fn add_one_torrent(samples: u64) -> Duration -where - V: Repository + Default, -{ - let start = Instant::now(); - - for _ in 0..samples { - let torrent_repository = V::default(); - - let info_hash = InfoHash::default(); - - torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None); - - torrent_repository.get_swarm_metadata(&info_hash); - } - - start.elapsed() -} - -// Add one torrent ten thousand times in parallel (depending on the set worker threads) -pub async fn update_one_torrent_in_parallel(runtime: &tokio::runtime::Runtime, samples: u64, sleep: Option) -> Duration -where - V: Repository + Default, - Arc: Clone + Send + Sync + 'static, -{ - let torrent_repository = Arc::::default(); - let info_hash = InfoHash::default(); - let handles = FuturesUnordered::new(); - - // Add the torrent/peer to the torrent repository - torrent_repository.upsert_peer(&info_hash, &DEFAULT_PEER, None); - - torrent_repository.get_swarm_metadata(&info_hash); - - let start = Instant::now(); - - for _ in 0..samples { - let torrent_repository_clone = torrent_repository.clone(); - - let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None); - - torrent_repository_clone.get_swarm_metadata(&info_hash); - - if let Some(sleep_time) = sleep { - let start_time = std::time::Instant::now(); - - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); - - handles.push(handle); - } - - // Await all tasks - futures::future::join_all(handles).await; - - start.elapsed() -} - -// Add ten thousand torrents in parallel (depending on the set worker threads) -pub async fn add_multiple_torrents_in_parallel( - runtime: &tokio::runtime::Runtime, - samples: u64, - sleep: Option, -) -> Duration -where - V: Repository + Default, - Arc: Clone + Send + Sync + 'static, -{ - let torrent_repository = Arc::::default(); - let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in a usize")); - let handles = FuturesUnordered::new(); - - let start = Instant::now(); - - for info_hash in info_hashes { - let torrent_repository_clone = torrent_repository.clone(); - - let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None); - - torrent_repository_clone.get_swarm_metadata(&info_hash); - - if let Some(sleep_time) = sleep { - let start_time = std::time::Instant::now(); - - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); - - handles.push(handle); - } - - // Await all tasks - futures::future::join_all(handles).await; - - start.elapsed() -} - -// Update ten thousand torrents in parallel (depending on the set worker threads) -pub async fn update_multiple_torrents_in_parallel( - runtime: &tokio::runtime::Runtime, - samples: u64, - sleep: Option, -) -> Duration -where - V: Repository + Default, - Arc: Clone + Send + Sync + 'static, -{ - let torrent_repository = Arc::::default(); - let info_hashes = generate_unique_info_hashes(samples.try_into().expect("it should fit in usize")); - let handles = FuturesUnordered::new(); - - // Add the torrents/peers to the torrent repository - for info_hash in &info_hashes { - torrent_repository.upsert_peer(info_hash, &DEFAULT_PEER, None); - torrent_repository.get_swarm_metadata(info_hash); - } - - let start = Instant::now(); - - for info_hash in info_hashes { - let torrent_repository_clone = torrent_repository.clone(); - - let handle = runtime.spawn(async move { - torrent_repository_clone.upsert_peer(&info_hash, &DEFAULT_PEER, None); - torrent_repository_clone.get_swarm_metadata(&info_hash); - - if let Some(sleep_time) = sleep { - let start_time = std::time::Instant::now(); - - while start_time.elapsed().as_nanos() < u128::from(sleep_time) {} - } - }); - - handles.push(handle); - } - - // Await all tasks - futures::future::join_all(handles).await; - - start.elapsed() -} diff --git a/packages/torrent-repository/benches/helpers/utils.rs b/packages/torrent-repository/benches/helpers/utils.rs deleted file mode 100644 index 51b09ec0f..000000000 --- a/packages/torrent-repository/benches/helpers/utils.rs +++ /dev/null @@ -1,41 +0,0 @@ -use std::collections::HashSet; -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; -use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_primitives::DurationSinceUnixEpoch; -use zerocopy::I64; - -pub const DEFAULT_PEER: Peer = Peer { - peer_id: PeerId([0; 20]), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), - updated: DurationSinceUnixEpoch::from_secs(0), - uploaded: NumberOfBytes(I64::ZERO), - downloaded: NumberOfBytes(I64::ZERO), - left: NumberOfBytes(I64::ZERO), - event: AnnounceEvent::Started, -}; - -#[must_use] -#[allow(clippy::missing_panics_doc)] -pub fn generate_unique_info_hashes(size: usize) -> Vec { - let mut result = HashSet::new(); - - let mut bytes = [0u8; 20]; - - #[allow(clippy::cast_possible_truncation)] - for i in 0..size { - bytes[0] = (i & 0xFF) as u8; - bytes[1] = ((i >> 8) & 0xFF) as u8; - bytes[2] = ((i >> 16) & 0xFF) as u8; - bytes[3] = ((i >> 24) & 0xFF) as u8; - - let info_hash = InfoHash::from_bytes(&bytes); - result.insert(info_hash); - } - - assert_eq!(result.len(), size); - - result.into_iter().collect() -} diff --git a/packages/torrent-repository/benches/repository_benchmark.rs b/packages/torrent-repository/benches/repository_benchmark.rs deleted file mode 100644 index 4e50f1454..000000000 --- a/packages/torrent-repository/benches/repository_benchmark.rs +++ /dev/null @@ -1,270 +0,0 @@ -use std::time::Duration; - -mod helpers; - -use criterion::{criterion_group, criterion_main, Criterion}; -use torrust_tracker_torrent_repository::{ - TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, - TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexParkingLot, TorrentsSkipMapMutexStd, - TorrentsSkipMapRwLockParkingLot, -}; - -use crate::helpers::{asyn, sync}; - -fn add_one_torrent(c: &mut Criterion) { - let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); - - let mut group = c.benchmark_group("add_one_torrent"); - - group.warm_up_time(Duration::from_millis(500)); - group.measurement_time(Duration::from_millis(1000)); - - group.bench_function("RwLockStd", |b| { - b.iter_custom(sync::add_one_torrent::); - }); - - group.bench_function("RwLockStdMutexStd", |b| { - b.iter_custom(sync::add_one_torrent::); - }); - - group.bench_function("RwLockStdMutexTokio", |b| { - b.to_async(&rt) - .iter_custom(asyn::add_one_torrent::); - }); - - group.bench_function("RwLockTokio", |b| { - b.to_async(&rt).iter_custom(asyn::add_one_torrent::); - }); - - group.bench_function("RwLockTokioMutexStd", |b| { - b.to_async(&rt) - .iter_custom(asyn::add_one_torrent::); - }); - - group.bench_function("RwLockTokioMutexTokio", |b| { - b.to_async(&rt) - .iter_custom(asyn::add_one_torrent::); - }); - - group.bench_function("SkipMapMutexStd", |b| { - b.iter_custom(sync::add_one_torrent::); - }); - - group.bench_function("SkipMapMutexParkingLot", |b| { - b.iter_custom(sync::add_one_torrent::); - }); - - group.bench_function("SkipMapRwLockParkingLot", |b| { - b.iter_custom(sync::add_one_torrent::); - }); - - group.bench_function("DashMapMutexStd", |b| { - b.iter_custom(sync::add_one_torrent::); - }); - - group.finish(); -} - -fn add_multiple_torrents_in_parallel(c: &mut Criterion) { - let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); - - let mut group = c.benchmark_group("add_multiple_torrents_in_parallel"); - - //group.sampling_mode(criterion::SamplingMode::Flat); - //group.sample_size(10); - - group.warm_up_time(Duration::from_millis(500)); - group.measurement_time(Duration::from_millis(1000)); - - group.bench_function("RwLockStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockStdMutexStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockStdMutexTokio", |b| { - b.to_async(&rt) - .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockTokio", |b| { - b.to_async(&rt) - .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockTokioMutexStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockTokioMutexTokio", |b| { - b.to_async(&rt) - .iter_custom(|iters| asyn::add_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("SkipMapMutexStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("SkipMapMutexParkingLot", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("SkipMapRwLockParkingLot", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("DashMapMutexStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::add_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.finish(); -} - -fn update_one_torrent_in_parallel(c: &mut Criterion) { - let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); - - let mut group = c.benchmark_group("update_one_torrent_in_parallel"); - - //group.sampling_mode(criterion::SamplingMode::Flat); - //group.sample_size(10); - - group.warm_up_time(Duration::from_millis(500)); - group.measurement_time(Duration::from_millis(1000)); - - group.bench_function("RwLockStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockStdMutexStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockStdMutexTokio", |b| { - b.to_async(&rt) - .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockTokio", |b| { - b.to_async(&rt) - .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockTokioMutexStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockTokioMutexTokio", |b| { - b.to_async(&rt) - .iter_custom(|iters| asyn::update_one_torrent_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("SkipMapMutexStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("SkipMapMutexParkingLot", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("SkipMapRwLockParkingLot", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("DashMapMutexStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::update_one_torrent_in_parallel::(&rt, iters, None)); - }); - - group.finish(); -} - -fn update_multiple_torrents_in_parallel(c: &mut Criterion) { - let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).build().unwrap(); - - let mut group = c.benchmark_group("update_multiple_torrents_in_parallel"); - - //group.sampling_mode(criterion::SamplingMode::Flat); - //group.sample_size(10); - - group.warm_up_time(Duration::from_millis(500)); - group.measurement_time(Duration::from_millis(1000)); - - group.bench_function("RwLockStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockStdMutexStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockStdMutexTokio", |b| { - b.to_async(&rt) - .iter_custom(|iters| asyn::update_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockTokio", |b| { - b.to_async(&rt) - .iter_custom(|iters| asyn::update_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockTokioMutexStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| asyn::update_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("RwLockTokioMutexTokio", |b| { - b.to_async(&rt).iter_custom(|iters| { - asyn::update_multiple_torrents_in_parallel::(&rt, iters, None) - }); - }); - - group.bench_function("SkipMapMutexStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.bench_function("SkipMapMutexParkingLot", |b| { - b.to_async(&rt).iter_custom(|iters| { - sync::update_multiple_torrents_in_parallel::(&rt, iters, None) - }); - }); - - group.bench_function("SkipMapRwLockParkingLot", |b| { - b.to_async(&rt).iter_custom(|iters| { - sync::update_multiple_torrents_in_parallel::(&rt, iters, None) - }); - }); - - group.bench_function("DashMapMutexStd", |b| { - b.to_async(&rt) - .iter_custom(|iters| sync::update_multiple_torrents_in_parallel::(&rt, iters, None)); - }); - - group.finish(); -} - -criterion_group!( - benches, - add_one_torrent, - add_multiple_torrents_in_parallel, - update_one_torrent_in_parallel, - update_multiple_torrents_in_parallel -); -criterion_main!(benches); diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index a8955808e..b4ee5298e 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,8 +1,5 @@ use std::sync::Arc; -use repository::dash_map_mutex_std::XacrimonDashMap; -use repository::rw_lock_std::RwLockStd; -use repository::rw_lock_tokio::RwLockTokio; use repository::skip_map_mutex_std::CrossbeamSkipList; use torrust_tracker_clock::clock; @@ -17,20 +14,8 @@ pub type EntryMutexTokio = Arc>; pub type EntryMutexParkingLot = Arc>; pub type EntryRwLockParkingLot = Arc>; -// Repos - -pub type TorrentsRwLockStd = RwLockStd; -pub type TorrentsRwLockStdMutexStd = RwLockStd; -pub type TorrentsRwLockStdMutexTokio = RwLockStd; -pub type TorrentsRwLockTokio = RwLockTokio; -pub type TorrentsRwLockTokioMutexStd = RwLockTokio; -pub type TorrentsRwLockTokioMutexTokio = RwLockTokio; - +// Repository pub type TorrentsSkipMapMutexStd = CrossbeamSkipList; -pub type TorrentsSkipMapMutexParkingLot = CrossbeamSkipList; -pub type TorrentsSkipMapRwLockParkingLot = CrossbeamSkipList; - -pub type TorrentsDashMapMutexStd = XacrimonDashMap; /// This code needs to be copied into each crate. /// Working version, for production. diff --git a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository/src/repository/dash_map_mutex_std.rs deleted file mode 100644 index d4a84caa0..000000000 --- a/packages/torrent-repository/src/repository/dash_map_mutex_std.rs +++ /dev/null @@ -1,111 +0,0 @@ -use std::sync::Arc; - -use bittorrent_primitives::info_hash::InfoHash; -use dashmap::DashMap; -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; - -use super::Repository; -use crate::entry::peer_list::PeerList; -use crate::entry::{Entry, EntrySync}; -use crate::{EntryMutexStd, EntrySingle}; - -#[derive(Default, Debug)] -pub struct XacrimonDashMap { - pub torrents: DashMap, -} - -impl Repository for XacrimonDashMap -where - EntryMutexStd: EntrySync, - EntrySingle: Entry, -{ - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { - // todo: load persistent torrent data if provided - - if let Some(entry) = self.torrents.get(info_hash) { - entry.upsert_peer(peer) - } else { - let _unused = self.torrents.insert(*info_hash, Arc::default()); - if let Some(entry) = self.torrents.get(info_hash) { - entry.upsert_peer(peer) - } else { - false - } - } - } - - fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) - } - - fn get(&self, key: &InfoHash) -> Option { - let maybe_entry = self.torrents.get(key); - maybe_entry.map(|entry| entry.clone()) - } - - fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); - - for entry in &self.torrents { - let stats = entry.value().lock().expect("it should get a lock").get_swarm_metadata(); - metrics.total_complete += u64::from(stats.complete); - metrics.total_downloaded += u64::from(stats.downloaded); - metrics.total_incomplete += u64::from(stats.incomplete); - metrics.total_torrents += 1; - } - - metrics - } - - fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { - match pagination { - Some(pagination) => self - .torrents - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|entry| (*entry.key(), entry.value().clone())) - .collect(), - None => self - .torrents - .iter() - .map(|entry| (*entry.key(), entry.value().clone())) - .collect(), - } - } - - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - for (info_hash, completed) in persistent_torrents { - if self.torrents.contains_key(info_hash) { - continue; - } - - let entry = EntryMutexStd::new( - EntrySingle { - swarm: PeerList::default(), - downloaded: *completed, - } - .into(), - ); - - self.torrents.insert(*info_hash, entry); - } - } - - fn remove(&self, key: &InfoHash) -> Option { - self.torrents.remove(key).map(|(_key, value)| value.clone()) - } - - fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - for entry in &self.torrents { - entry.value().remove_inactive_peers(current_cutoff); - } - } - - fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - self.torrents.retain(|_, entry| entry.meets_retaining_policy(policy)); - } -} diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs index 9284ff6e6..96c71f3a0 100644 --- a/packages/torrent-repository/src/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -4,13 +4,6 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -pub mod dash_map_mutex_std; -pub mod rw_lock_std; -pub mod rw_lock_std_mutex_std; -pub mod rw_lock_std_mutex_tokio; -pub mod rw_lock_tokio; -pub mod rw_lock_tokio_mutex_std; -pub mod rw_lock_tokio_mutex_tokio; pub mod skip_map_mutex_std; use std::fmt::Debug; diff --git a/packages/torrent-repository/src/repository/rw_lock_std.rs b/packages/torrent-repository/src/repository/rw_lock_std.rs deleted file mode 100644 index d190718af..000000000 --- a/packages/torrent-repository/src/repository/rw_lock_std.rs +++ /dev/null @@ -1,132 +0,0 @@ -use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; - -use super::Repository; -use crate::entry::peer_list::PeerList; -use crate::entry::Entry; -use crate::{EntrySingle, TorrentsRwLockStd}; - -#[derive(Default, Debug)] -pub struct RwLockStd { - pub(crate) torrents: std::sync::RwLock>, -} - -impl RwLockStd { - /// # Panics - /// - /// Panics if unable to get a lock. - pub fn write( - &self, - ) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap> { - self.torrents.write().expect("it should get lock") - } -} - -impl TorrentsRwLockStd { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().expect("it should get the read lock") - } - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().expect("it should get the write lock") - } -} - -impl Repository for TorrentsRwLockStd -where - EntrySingle: Entry, -{ - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { - // todo: load persistent torrent data if provided - - let mut db = self.get_torrents_mut(); - - let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); - - entry.upsert_peer(peer) - } - - fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.get(info_hash).map(|entry| entry.get_swarm_metadata()) - } - - fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents(); - db.get(key).cloned() - } - - fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); - - for entry in self.get_torrents().values() { - let stats = entry.get_swarm_metadata(); - metrics.total_complete += u64::from(stats.complete); - metrics.total_downloaded += u64::from(stats.downloaded); - metrics.total_incomplete += u64::from(stats.incomplete); - metrics.total_torrents += 1; - } - - metrics - } - - fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { - let db = self.get_torrents(); - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut torrents = self.get_torrents_mut(); - - for (info_hash, downloaded) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(info_hash) { - continue; - } - - let entry = EntrySingle { - swarm: PeerList::default(), - downloaded: *downloaded, - }; - - torrents.insert(*info_hash, entry); - } - } - - fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut(); - db.remove(key) - } - - fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - let mut db = self.get_torrents_mut(); - let entries = db.values_mut(); - - for entry in entries { - entry.remove_inactive_peers(current_cutoff); - } - } - - fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - let mut db = self.get_torrents_mut(); - - db.retain(|_, e| e.meets_retaining_policy(policy)); - } -} diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs deleted file mode 100644 index 1764b94e8..000000000 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_std.rs +++ /dev/null @@ -1,130 +0,0 @@ -use std::sync::Arc; - -use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; - -use super::Repository; -use crate::entry::peer_list::PeerList; -use crate::entry::{Entry, EntrySync}; -use crate::{EntryMutexStd, EntrySingle, TorrentsRwLockStdMutexStd}; - -impl TorrentsRwLockStdMutexStd { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().expect("unable to get torrent list") - } - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().expect("unable to get writable torrent list") - } -} - -impl Repository for TorrentsRwLockStdMutexStd -where - EntryMutexStd: EntrySync, - EntrySingle: Entry, -{ - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { - // todo: load persistent torrent data if provided - - let maybe_entry = self.get_torrents().get(info_hash).cloned(); - - let entry = if let Some(entry) = maybe_entry { - entry - } else { - let mut db = self.get_torrents_mut(); - let entry = db.entry(*info_hash).or_insert(Arc::default()); - entry.clone() - }; - - entry.upsert_peer(peer) - } - - fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.get_torrents() - .get(info_hash) - .map(super::super::entry::EntrySync::get_swarm_metadata) - } - - fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents(); - db.get(key).cloned() - } - - fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); - - for entry in self.get_torrents().values() { - let stats = entry.lock().expect("it should get a lock").get_swarm_metadata(); - metrics.total_complete += u64::from(stats.complete); - metrics.total_downloaded += u64::from(stats.downloaded); - metrics.total_incomplete += u64::from(stats.incomplete); - metrics.total_torrents += 1; - } - - metrics - } - - fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { - let db = self.get_torrents(); - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut torrents = self.get_torrents_mut(); - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(info_hash) { - continue; - } - - let entry = EntryMutexStd::new( - EntrySingle { - swarm: PeerList::default(), - downloaded: *completed, - } - .into(), - ); - - torrents.insert(*info_hash, entry); - } - } - - fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut(); - db.remove(key) - } - - fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - let db = self.get_torrents(); - let entries = db.values().cloned(); - - for entry in entries { - entry.remove_inactive_peers(current_cutoff); - } - } - - fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - let mut db = self.get_torrents_mut(); - - db.retain(|_, e| e.lock().expect("it should lock entry").meets_retaining_policy(policy)); - } -} diff --git a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs deleted file mode 100644 index 116c1ff87..000000000 --- a/packages/torrent-repository/src/repository/rw_lock_std_mutex_tokio.rs +++ /dev/null @@ -1,167 +0,0 @@ -use std::iter::zip; -use std::pin::Pin; -use std::sync::Arc; - -use bittorrent_primitives::info_hash::InfoHash; -use futures::future::join_all; -use futures::{Future, FutureExt}; -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; - -use super::RepositoryAsync; -use crate::entry::peer_list::PeerList; -use crate::entry::{Entry, EntryAsync}; -use crate::{EntryMutexTokio, EntrySingle, TorrentsRwLockStdMutexTokio}; - -impl TorrentsRwLockStdMutexTokio { - fn get_torrents<'a>(&'a self) -> std::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().expect("unable to get torrent list") - } - - fn get_torrents_mut<'a>(&'a self) -> std::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().expect("unable to get writable torrent list") - } -} - -impl RepositoryAsync for TorrentsRwLockStdMutexTokio -where - EntryMutexTokio: EntryAsync, - EntrySingle: Entry, -{ - async fn upsert_peer( - &self, - info_hash: &InfoHash, - peer: &peer::Peer, - _opt_persistent_torrent: Option, - ) -> bool { - // todo: load persistent torrent data if provided - - let maybe_entry = self.get_torrents().get(info_hash).cloned(); - - let entry = if let Some(entry) = maybe_entry { - entry - } else { - let mut db = self.get_torrents_mut(); - let entry = db.entry(*info_hash).or_insert(Arc::default()); - entry.clone() - }; - - entry.upsert_peer(peer).await - } - - async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - let maybe_entry = self.get_torrents().get(info_hash).cloned(); - - match maybe_entry { - Some(entry) => Some(entry.get_swarm_metadata().await), - None => None, - } - } - - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents(); - db.get(key).cloned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexTokio)> { - let db = self.get_torrents(); - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); - - let entries: Vec<_> = self.get_torrents().values().cloned().collect(); - - for entry in entries { - let stats = entry.lock().await.get_swarm_metadata(); - metrics.total_complete += u64::from(stats.complete); - metrics.total_downloaded += u64::from(stats.downloaded); - metrics.total_incomplete += u64::from(stats.incomplete); - metrics.total_torrents += 1; - } - - metrics - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut db = self.get_torrents_mut(); - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if db.contains_key(info_hash) { - continue; - } - - let entry = EntryMutexTokio::new( - EntrySingle { - swarm: PeerList::default(), - downloaded: *completed, - } - .into(), - ); - - db.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut(); - db.remove(key) - } - - async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - let handles: Vec + Send>>>; - { - let db = self.get_torrents(); - handles = db - .values() - .cloned() - .map(|e| e.remove_inactive_peers(current_cutoff).boxed()) - .collect(); - } - join_all(handles).await; - } - - async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - let handles: Vec> + Send>>>; - - { - let db = self.get_torrents(); - - handles = zip(db.keys().copied(), db.values().cloned()) - .map(|(infohash, torrent)| { - torrent - .meets_retaining_policy(policy) - .map(move |should_be_retained| if should_be_retained { None } else { Some(infohash) }) - .boxed() - }) - .collect::>(); - } - - let not_good = join_all(handles).await; - - let mut db = self.get_torrents_mut(); - - for remove in not_good.into_iter().flatten() { - drop(db.remove(&remove)); - } - } -} diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio.rs deleted file mode 100644 index 53838023d..000000000 --- a/packages/torrent-repository/src/repository/rw_lock_tokio.rs +++ /dev/null @@ -1,138 +0,0 @@ -use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; - -use super::RepositoryAsync; -use crate::entry::peer_list::PeerList; -use crate::entry::Entry; -use crate::{EntrySingle, TorrentsRwLockTokio}; - -#[derive(Default, Debug)] -pub struct RwLockTokio { - pub(crate) torrents: tokio::sync::RwLock>, -} - -impl RwLockTokio { - pub fn write( - &self, - ) -> impl std::future::Future< - Output = tokio::sync::RwLockWriteGuard<'_, std::collections::BTreeMap>, - > { - self.torrents.write() - } -} - -impl TorrentsRwLockTokio { - async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().await - } - - async fn get_torrents_mut<'a>( - &'a self, - ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().await - } -} - -impl RepositoryAsync for TorrentsRwLockTokio -where - EntrySingle: Entry, -{ - async fn upsert_peer( - &self, - info_hash: &InfoHash, - peer: &peer::Peer, - _opt_persistent_torrent: Option, - ) -> bool { - // todo: load persistent torrent data if provided - - let mut db = self.get_torrents_mut().await; - - let entry = db.entry(*info_hash).or_insert(EntrySingle::default()); - - entry.upsert_peer(peer) - } - - async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.get(info_hash).await.map(|entry| entry.get_swarm_metadata()) - } - - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents().await; - db.get(key).cloned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { - let db = self.get_torrents().await; - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); - - for entry in self.get_torrents().await.values() { - let stats = entry.get_swarm_metadata(); - metrics.total_complete += u64::from(stats.complete); - metrics.total_downloaded += u64::from(stats.downloaded); - metrics.total_incomplete += u64::from(stats.incomplete); - metrics.total_torrents += 1; - } - - metrics - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut torrents = self.get_torrents_mut().await; - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(info_hash) { - continue; - } - - let entry = EntrySingle { - swarm: PeerList::default(), - downloaded: *completed, - }; - - torrents.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut().await; - db.remove(key) - } - - async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - let mut db = self.get_torrents_mut().await; - let entries = db.values_mut(); - - for entry in entries { - entry.remove_inactive_peers(current_cutoff); - } - } - - async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - let mut db = self.get_torrents_mut().await; - - db.retain(|_, e| e.meets_retaining_policy(policy)); - } -} diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs deleted file mode 100644 index eb7e300fd..000000000 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_std.rs +++ /dev/null @@ -1,135 +0,0 @@ -use std::sync::Arc; - -use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; - -use super::RepositoryAsync; -use crate::entry::peer_list::PeerList; -use crate::entry::{Entry, EntrySync}; -use crate::{EntryMutexStd, EntrySingle, TorrentsRwLockTokioMutexStd}; - -impl TorrentsRwLockTokioMutexStd { - async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().await - } - - async fn get_torrents_mut<'a>( - &'a self, - ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().await - } -} - -impl RepositoryAsync for TorrentsRwLockTokioMutexStd -where - EntryMutexStd: EntrySync, - EntrySingle: Entry, -{ - async fn upsert_peer( - &self, - info_hash: &InfoHash, - peer: &peer::Peer, - _opt_persistent_torrent: Option, - ) -> bool { - // todo: load persistent torrent data if provided - - let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); - - let entry = if let Some(entry) = maybe_entry { - entry - } else { - let mut db = self.get_torrents_mut().await; - let entry = db.entry(*info_hash).or_insert(Arc::default()); - entry.clone() - }; - - entry.upsert_peer(peer) - } - - async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.get(info_hash).await.map(|entry| entry.get_swarm_metadata()) - } - - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents().await; - db.get(key).cloned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { - let db = self.get_torrents().await; - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); - - for entry in self.get_torrents().await.values() { - let stats = entry.get_swarm_metadata(); - metrics.total_complete += u64::from(stats.complete); - metrics.total_downloaded += u64::from(stats.downloaded); - metrics.total_incomplete += u64::from(stats.incomplete); - metrics.total_torrents += 1; - } - - metrics - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut torrents = self.get_torrents_mut().await; - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if torrents.contains_key(info_hash) { - continue; - } - - let entry = EntryMutexStd::new( - EntrySingle { - swarm: PeerList::default(), - downloaded: *completed, - } - .into(), - ); - - torrents.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut().await; - db.remove(key) - } - - async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - let db = self.get_torrents().await; - let entries = db.values().cloned(); - - for entry in entries { - entry.remove_inactive_peers(current_cutoff); - } - } - - async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - let mut db = self.get_torrents_mut().await; - - db.retain(|_, e| e.lock().expect("it should lock entry").meets_retaining_policy(policy)); - } -} diff --git a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs deleted file mode 100644 index c8ebaf4d6..000000000 --- a/packages/torrent-repository/src/repository/rw_lock_tokio_mutex_tokio.rs +++ /dev/null @@ -1,148 +0,0 @@ -use std::sync::Arc; - -use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; - -use super::RepositoryAsync; -use crate::entry::peer_list::PeerList; -use crate::entry::{Entry, EntryAsync}; -use crate::{EntryMutexTokio, EntrySingle, TorrentsRwLockTokioMutexTokio}; - -impl TorrentsRwLockTokioMutexTokio { - async fn get_torrents<'a>(&'a self) -> tokio::sync::RwLockReadGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.read().await - } - - async fn get_torrents_mut<'a>( - &'a self, - ) -> tokio::sync::RwLockWriteGuard<'a, std::collections::BTreeMap> - where - std::collections::BTreeMap: 'a, - { - self.torrents.write().await - } -} - -impl RepositoryAsync for TorrentsRwLockTokioMutexTokio -where - EntryMutexTokio: EntryAsync, - EntrySingle: Entry, -{ - async fn upsert_peer( - &self, - info_hash: &InfoHash, - peer: &peer::Peer, - _opt_persistent_torrent: Option, - ) -> bool { - // todo: load persistent torrent data if provided - - let maybe_entry = self.get_torrents().await.get(info_hash).cloned(); - - let entry = if let Some(entry) = maybe_entry { - entry - } else { - let mut db = self.get_torrents_mut().await; - let entry = db.entry(*info_hash).or_insert(Arc::default()); - entry.clone() - }; - - entry.upsert_peer(peer).await - } - - async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - match self.get(info_hash).await { - Some(entry) => Some(entry.get_swarm_metadata().await), - None => None, - } - } - - async fn get(&self, key: &InfoHash) -> Option { - let db = self.get_torrents().await; - db.get(key).cloned() - } - - async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexTokio)> { - let db = self.get_torrents().await; - - match pagination { - Some(pagination) => db - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|(a, b)| (*a, b.clone())) - .collect(), - None => db.iter().map(|(a, b)| (*a, b.clone())).collect(), - } - } - - async fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); - - for entry in self.get_torrents().await.values() { - let stats = entry.get_swarm_metadata().await; - metrics.total_complete += u64::from(stats.complete); - metrics.total_downloaded += u64::from(stats.downloaded); - metrics.total_incomplete += u64::from(stats.incomplete); - metrics.total_torrents += 1; - } - - metrics - } - - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - let mut db = self.get_torrents_mut().await; - - for (info_hash, completed) in persistent_torrents { - // Skip if torrent entry already exists - if db.contains_key(info_hash) { - continue; - } - - let entry = EntryMutexTokio::new( - EntrySingle { - swarm: PeerList::default(), - downloaded: *completed, - } - .into(), - ); - - db.insert(*info_hash, entry); - } - } - - async fn remove(&self, key: &InfoHash) -> Option { - let mut db = self.get_torrents_mut().await; - db.remove(key) - } - - async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - let db = self.get_torrents().await; - let entries = db.values().cloned(); - - for entry in entries { - entry.remove_inactive_peers(current_cutoff).await; - } - } - - async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - let mut db = self.get_torrents_mut().await; - - let mut not_good = Vec::::default(); - - for (&infohash, torrent) in db.iter() { - if !torrent.clone().meets_retaining_policy(policy).await { - not_good.push(infohash); - } - } - - for remove in not_good { - drop(db.remove(&remove)); - } - } -} diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 224fc6aa3..95dd3f5ad 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -3,240 +3,84 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use torrust_tracker_torrent_repository::repository::{Repository as _, RepositoryAsync as _}; -use torrust_tracker_torrent_repository::{ - EntrySingle, TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, - TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexParkingLot, - TorrentsSkipMapMutexStd, TorrentsSkipMapRwLockParkingLot, -}; +use torrust_tracker_torrent_repository::repository::Repository as _; +use torrust_tracker_torrent_repository::{EntrySingle, TorrentsSkipMapMutexStd}; #[derive(Debug)] pub(crate) enum Repo { - RwLockStd(TorrentsRwLockStd), - RwLockStdMutexStd(TorrentsRwLockStdMutexStd), - RwLockStdMutexTokio(TorrentsRwLockStdMutexTokio), - RwLockTokio(TorrentsRwLockTokio), - RwLockTokioMutexStd(TorrentsRwLockTokioMutexStd), - RwLockTokioMutexTokio(TorrentsRwLockTokioMutexTokio), SkipMapMutexStd(TorrentsSkipMapMutexStd), - SkipMapMutexParkingLot(TorrentsSkipMapMutexParkingLot), - SkipMapRwLockParkingLot(TorrentsSkipMapRwLockParkingLot), - DashMapMutexStd(TorrentsDashMapMutexStd), } impl Repo { - pub(crate) async fn upsert_peer( + pub(crate) fn upsert_peer( &self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option, ) -> bool { match self { - Repo::RwLockStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), - Repo::RwLockStdMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), - Repo::RwLockStdMutexTokio(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, - Repo::RwLockTokio(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, - Repo::RwLockTokioMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, - Repo::RwLockTokioMutexTokio(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent).await, Repo::SkipMapMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), - Repo::SkipMapMutexParkingLot(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), - Repo::SkipMapRwLockParkingLot(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), - Repo::DashMapMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), } } - pub(crate) async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + pub(crate) fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { match self { - Repo::RwLockStd(repo) => repo.get_swarm_metadata(info_hash), - Repo::RwLockStdMutexStd(repo) => repo.get_swarm_metadata(info_hash), - Repo::RwLockStdMutexTokio(repo) => repo.get_swarm_metadata(info_hash).await, - Repo::RwLockTokio(repo) => repo.get_swarm_metadata(info_hash).await, - Repo::RwLockTokioMutexStd(repo) => repo.get_swarm_metadata(info_hash).await, - Repo::RwLockTokioMutexTokio(repo) => repo.get_swarm_metadata(info_hash).await, Repo::SkipMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), - Repo::SkipMapMutexParkingLot(repo) => repo.get_swarm_metadata(info_hash), - Repo::SkipMapRwLockParkingLot(repo) => repo.get_swarm_metadata(info_hash), - Repo::DashMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), } } - pub(crate) async fn get(&self, key: &InfoHash) -> Option { + pub(crate) fn get(&self, key: &InfoHash) -> Option { match self { - Repo::RwLockStd(repo) => repo.get(key), - Repo::RwLockStdMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), - Repo::RwLockStdMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), - Repo::RwLockTokio(repo) => repo.get(key).await, - Repo::RwLockTokioMutexStd(repo) => Some(repo.get(key).await?.lock().unwrap().clone()), - Repo::RwLockTokioMutexTokio(repo) => Some(repo.get(key).await?.lock().await.clone()), Repo::SkipMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), - Repo::SkipMapMutexParkingLot(repo) => Some(repo.get(key)?.lock().clone()), - Repo::SkipMapRwLockParkingLot(repo) => Some(repo.get(key)?.read().clone()), - Repo::DashMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), } } - pub(crate) async fn get_metrics(&self) -> AggregateSwarmMetadata { + pub(crate) fn get_metrics(&self) -> AggregateSwarmMetadata { match self { - Repo::RwLockStd(repo) => repo.get_metrics(), - Repo::RwLockStdMutexStd(repo) => repo.get_metrics(), - Repo::RwLockStdMutexTokio(repo) => repo.get_metrics().await, - Repo::RwLockTokio(repo) => repo.get_metrics().await, - Repo::RwLockTokioMutexStd(repo) => repo.get_metrics().await, - Repo::RwLockTokioMutexTokio(repo) => repo.get_metrics().await, Repo::SkipMapMutexStd(repo) => repo.get_metrics(), - Repo::SkipMapMutexParkingLot(repo) => repo.get_metrics(), - Repo::SkipMapRwLockParkingLot(repo) => repo.get_metrics(), - Repo::DashMapMutexStd(repo) => repo.get_metrics(), } } - pub(crate) async fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { + pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { match self { - Repo::RwLockStd(repo) => repo.get_paginated(pagination), - Repo::RwLockStdMutexStd(repo) => repo - .get_paginated(pagination) - .iter() - .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) - .collect(), - Repo::RwLockStdMutexTokio(repo) => { - let mut v: Vec<(InfoHash, EntrySingle)> = vec![]; - - for (i, t) in repo.get_paginated(pagination).await { - v.push((i, t.lock().await.clone())); - } - v - } - Repo::RwLockTokio(repo) => repo.get_paginated(pagination).await, - Repo::RwLockTokioMutexStd(repo) => repo - .get_paginated(pagination) - .await - .iter() - .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) - .collect(), - Repo::RwLockTokioMutexTokio(repo) => { - let mut v: Vec<(InfoHash, EntrySingle)> = vec![]; - - for (i, t) in repo.get_paginated(pagination).await { - v.push((i, t.lock().await.clone())); - } - v - } Repo::SkipMapMutexStd(repo) => repo .get_paginated(pagination) .iter() .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) .collect(), - Repo::SkipMapMutexParkingLot(repo) => repo - .get_paginated(pagination) - .iter() - .map(|(i, t)| (*i, t.lock().clone())) - .collect(), - Repo::SkipMapRwLockParkingLot(repo) => repo - .get_paginated(pagination) - .iter() - .map(|(i, t)| (*i, t.read().clone())) - .collect(), - Repo::DashMapMutexStd(repo) => repo - .get_paginated(pagination) - .iter() - .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) - .collect(), } } - pub(crate) async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + pub(crate) fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { match self { - Repo::RwLockStd(repo) => repo.import_persistent(persistent_torrents), - Repo::RwLockStdMutexStd(repo) => repo.import_persistent(persistent_torrents), - Repo::RwLockStdMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, - Repo::RwLockTokio(repo) => repo.import_persistent(persistent_torrents).await, - Repo::RwLockTokioMutexStd(repo) => repo.import_persistent(persistent_torrents).await, - Repo::RwLockTokioMutexTokio(repo) => repo.import_persistent(persistent_torrents).await, Repo::SkipMapMutexStd(repo) => repo.import_persistent(persistent_torrents), - Repo::SkipMapMutexParkingLot(repo) => repo.import_persistent(persistent_torrents), - Repo::SkipMapRwLockParkingLot(repo) => repo.import_persistent(persistent_torrents), - Repo::DashMapMutexStd(repo) => repo.import_persistent(persistent_torrents), } } - pub(crate) async fn remove(&self, key: &InfoHash) -> Option { + pub(crate) fn remove(&self, key: &InfoHash) -> Option { match self { - Repo::RwLockStd(repo) => repo.remove(key), - Repo::RwLockStdMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), - Repo::RwLockStdMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), - Repo::RwLockTokio(repo) => repo.remove(key).await, - Repo::RwLockTokioMutexStd(repo) => Some(repo.remove(key).await?.lock().unwrap().clone()), - Repo::RwLockTokioMutexTokio(repo) => Some(repo.remove(key).await?.lock().await.clone()), Repo::SkipMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), - Repo::SkipMapMutexParkingLot(repo) => Some(repo.remove(key)?.lock().clone()), - Repo::SkipMapRwLockParkingLot(repo) => Some(repo.remove(key)?.write().clone()), - Repo::DashMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), } } - pub(crate) async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + pub(crate) fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { match self { - Repo::RwLockStd(repo) => repo.remove_inactive_peers(current_cutoff), - Repo::RwLockStdMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), - Repo::RwLockStdMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, - Repo::RwLockTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, - Repo::RwLockTokioMutexStd(repo) => repo.remove_inactive_peers(current_cutoff).await, - Repo::RwLockTokioMutexTokio(repo) => repo.remove_inactive_peers(current_cutoff).await, Repo::SkipMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), - Repo::SkipMapMutexParkingLot(repo) => repo.remove_inactive_peers(current_cutoff), - Repo::SkipMapRwLockParkingLot(repo) => repo.remove_inactive_peers(current_cutoff), - Repo::DashMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), } } - pub(crate) async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + pub(crate) fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { match self { - Repo::RwLockStd(repo) => repo.remove_peerless_torrents(policy), - Repo::RwLockStdMutexStd(repo) => repo.remove_peerless_torrents(policy), - Repo::RwLockStdMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, - Repo::RwLockTokio(repo) => repo.remove_peerless_torrents(policy).await, - Repo::RwLockTokioMutexStd(repo) => repo.remove_peerless_torrents(policy).await, - Repo::RwLockTokioMutexTokio(repo) => repo.remove_peerless_torrents(policy).await, Repo::SkipMapMutexStd(repo) => repo.remove_peerless_torrents(policy), - Repo::SkipMapMutexParkingLot(repo) => repo.remove_peerless_torrents(policy), - Repo::SkipMapRwLockParkingLot(repo) => repo.remove_peerless_torrents(policy), - Repo::DashMapMutexStd(repo) => repo.remove_peerless_torrents(policy), } } - pub(crate) async fn insert(&self, info_hash: &InfoHash, torrent: EntrySingle) -> Option { + pub(crate) fn insert(&self, info_hash: &InfoHash, torrent: EntrySingle) -> Option { match self { - Repo::RwLockStd(repo) => { - repo.write().insert(*info_hash, torrent); - } - Repo::RwLockStdMutexStd(repo) => { - repo.write().insert(*info_hash, torrent.into()); - } - Repo::RwLockStdMutexTokio(repo) => { - repo.write().insert(*info_hash, torrent.into()); - } - Repo::RwLockTokio(repo) => { - repo.write().await.insert(*info_hash, torrent); - } - Repo::RwLockTokioMutexStd(repo) => { - repo.write().await.insert(*info_hash, torrent.into()); - } - Repo::RwLockTokioMutexTokio(repo) => { - repo.write().await.insert(*info_hash, torrent.into()); - } Repo::SkipMapMutexStd(repo) => { repo.torrents.insert(*info_hash, torrent.into()); } - Repo::SkipMapMutexParkingLot(repo) => { - repo.torrents.insert(*info_hash, torrent.into()); - } - Repo::SkipMapRwLockParkingLot(repo) => { - repo.torrents.insert(*info_hash, torrent.into()); - } - Repo::DashMapMutexStd(repo) => { - repo.torrents.insert(*info_hash, torrent.into()); - } } - self.get(info_hash).await + self.get(info_hash) } } diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 77977837f..d0ef61e81 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -9,65 +9,17 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::PersistentTorrents; use torrust_tracker_torrent_repository::entry::Entry as _; -use torrust_tracker_torrent_repository::repository::dash_map_mutex_std::XacrimonDashMap; -use torrust_tracker_torrent_repository::repository::rw_lock_std::RwLockStd; -use torrust_tracker_torrent_repository::repository::rw_lock_tokio::RwLockTokio; use torrust_tracker_torrent_repository::repository::skip_map_mutex_std::CrossbeamSkipList; use torrust_tracker_torrent_repository::EntrySingle; use crate::common::repo::Repo; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; -#[fixture] -fn standard() -> Repo { - Repo::RwLockStd(RwLockStd::default()) -} - -#[fixture] -fn standard_mutex() -> Repo { - Repo::RwLockStdMutexStd(RwLockStd::default()) -} - -#[fixture] -fn standard_tokio() -> Repo { - Repo::RwLockStdMutexTokio(RwLockStd::default()) -} - -#[fixture] -fn tokio_std() -> Repo { - Repo::RwLockTokio(RwLockTokio::default()) -} - -#[fixture] -fn tokio_mutex() -> Repo { - Repo::RwLockTokioMutexStd(RwLockTokio::default()) -} - -#[fixture] -fn tokio_tokio() -> Repo { - Repo::RwLockTokioMutexTokio(RwLockTokio::default()) -} - #[fixture] fn skip_list_mutex_std() -> Repo { Repo::SkipMapMutexStd(CrossbeamSkipList::default()) } -#[fixture] -fn skip_list_mutex_parking_lot() -> Repo { - Repo::SkipMapMutexParkingLot(CrossbeamSkipList::default()) -} - -#[fixture] -fn skip_list_rw_lock_parking_lot() -> Repo { - Repo::SkipMapRwLockParkingLot(CrossbeamSkipList::default()) -} - -#[fixture] -fn dash_map_std() -> Repo { - Repo::DashMapMutexStd(XacrimonDashMap::default()) -} - type Entries = Vec<(InfoHash, EntrySingle)>; #[fixture] @@ -197,9 +149,9 @@ fn persistent_three() -> PersistentTorrents { t.iter().copied().collect() } -async fn make(repo: &Repo, entries: &Entries) { +fn make(repo: &Repo, entries: &Entries) { for (info_hash, entry) in entries { - repo.insert(info_hash, entry.clone()).await; + repo.insert(info_hash, entry.clone()); } } @@ -248,28 +200,13 @@ fn policy_remove_persist() -> TrackerPolicy { #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_get_a_torrent_entry( - #[values( - standard(), - standard_mutex(), - standard_tokio(), - tokio_std(), - tokio_mutex(), - tokio_tokio(), - skip_list_mutex_std(), - skip_list_mutex_parking_lot(), - skip_list_rw_lock_parking_lot(), - dash_map_std() - )] - repo: Repo, - #[case] entries: Entries, -) { - make(&repo, &entries).await; +async fn it_should_get_a_torrent_entry(#[values(skip_list_mutex_std())] repo: Repo, #[case] entries: Entries) { + make(&repo, &entries); if let Some((info_hash, torrent)) = entries.first() { - assert_eq!(repo.get(info_hash).await, Some(torrent.clone())); + assert_eq!(repo.get(info_hash), Some(torrent.clone())); } else { - assert_eq!(repo.get(&InfoHash::default()).await, None); + assert_eq!(repo.get(&InfoHash::default()), None); } } @@ -284,28 +221,17 @@ async fn it_should_get_a_torrent_entry( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( - #[values( - standard(), - standard_mutex(), - standard_tokio(), - tokio_std(), - tokio_mutex(), - tokio_tokio(), - skip_list_mutex_std(), - skip_list_mutex_parking_lot(), - skip_list_rw_lock_parking_lot() - )] - repo: Repo, + #[values(skip_list_mutex_std())] repo: Repo, #[case] entries: Entries, many_out_of_order: Entries, ) { - make(&repo, &entries).await; + make(&repo, &entries); - let entries_a = repo.get_paginated(None).await.iter().map(|(i, _)| *i).collect::>(); + let entries_a = repo.get_paginated(None).iter().map(|(i, _)| *i).collect::>(); - make(&repo, &many_out_of_order).await; + make(&repo, &many_out_of_order); - let entries_b = repo.get_paginated(None).await.iter().map(|(i, _)| *i).collect::>(); + let entries_b = repo.get_paginated(None).iter().map(|(i, _)| *i).collect::>(); let is_equal = entries_b.iter().take(entries_a.len()).copied().collect::>() == entries_a; @@ -328,36 +254,25 @@ async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_get_paginated( - #[values( - standard(), - standard_mutex(), - standard_tokio(), - tokio_std(), - tokio_mutex(), - tokio_tokio(), - skip_list_mutex_std(), - skip_list_mutex_parking_lot(), - skip_list_rw_lock_parking_lot() - )] - repo: Repo, + #[values(skip_list_mutex_std())] repo: Repo, #[case] entries: Entries, #[values(paginated_limit_zero(), paginated_limit_one(), paginated_limit_one_offset_one())] paginated: Pagination, ) { - make(&repo, &entries).await; + make(&repo, &entries); - let mut info_hashes = repo.get_paginated(None).await.iter().map(|(i, _)| *i).collect::>(); + let mut info_hashes = repo.get_paginated(None).iter().map(|(i, _)| *i).collect::>(); info_hashes.sort(); match paginated { // it should return empty if limit is zero. - Pagination { limit: 0, .. } => assert_eq!(repo.get_paginated(Some(&paginated)).await, vec![]), + Pagination { limit: 0, .. } => assert_eq!(repo.get_paginated(Some(&paginated)), vec![]), // it should return a single entry if the limit is one. Pagination { limit: 1, offset: 0 } => { if info_hashes.is_empty() { - assert_eq!(repo.get_paginated(Some(&paginated)).await.len(), 0); + assert_eq!(repo.get_paginated(Some(&paginated)).len(), 0); } else { - let page = repo.get_paginated(Some(&paginated)).await; + let page = repo.get_paginated(Some(&paginated)); assert_eq!(page.len(), 1); assert_eq!(page.first().map(|(i, _)| i), info_hashes.first()); } @@ -366,7 +281,7 @@ async fn it_should_get_paginated( // it should return the only the second entry if both the limit and the offset are one. Pagination { limit: 1, offset: 1 } => { if info_hashes.len() > 1 { - let page = repo.get_paginated(Some(&paginated)).await; + let page = repo.get_paginated(Some(&paginated)); assert_eq!(page.len(), 1); assert_eq!(page[0].0, info_hashes[1]); } @@ -386,25 +301,10 @@ async fn it_should_get_paginated( #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_get_metrics( - #[values( - standard(), - standard_mutex(), - standard_tokio(), - tokio_std(), - tokio_mutex(), - tokio_tokio(), - skip_list_mutex_std(), - skip_list_mutex_parking_lot(), - skip_list_rw_lock_parking_lot(), - dash_map_std() - )] - repo: Repo, - #[case] entries: Entries, -) { +async fn it_should_get_metrics(#[values(skip_list_mutex_std())] repo: Repo, #[case] entries: Entries) { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; - make(&repo, &entries).await; + make(&repo, &entries); let mut metrics = AggregateSwarmMetadata::default(); @@ -417,7 +317,7 @@ async fn it_should_get_metrics( metrics.total_downloaded += u64::from(stats.downloaded); } - assert_eq!(repo.get_metrics().await, metrics); + assert_eq!(repo.get_metrics(), metrics); } #[rstest] @@ -431,33 +331,21 @@ async fn it_should_get_metrics( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_import_persistent_torrents( - #[values( - standard(), - standard_mutex(), - standard_tokio(), - tokio_std(), - tokio_mutex(), - tokio_tokio(), - skip_list_mutex_std(), - skip_list_mutex_parking_lot(), - skip_list_rw_lock_parking_lot(), - dash_map_std() - )] - repo: Repo, + #[values(skip_list_mutex_std())] repo: Repo, #[case] entries: Entries, #[values(persistent_empty(), persistent_single(), persistent_three())] persistent_torrents: PersistentTorrents, ) { - make(&repo, &entries).await; + make(&repo, &entries); - let mut downloaded = repo.get_metrics().await.total_downloaded; + let mut downloaded = repo.get_metrics().total_downloaded; persistent_torrents.iter().for_each(|(_, d)| downloaded += u64::from(*d)); - repo.import_persistent(&persistent_torrents).await; + repo.import_persistent(&persistent_torrents); - assert_eq!(repo.get_metrics().await.total_downloaded, downloaded); + assert_eq!(repo.get_metrics().total_downloaded, downloaded); for (entry, _) in persistent_torrents { - assert!(repo.get(&entry).await.is_some()); + assert!(repo.get(&entry).is_some()); } } @@ -471,33 +359,18 @@ async fn it_should_import_persistent_torrents( #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_remove_an_entry( - #[values( - standard(), - standard_mutex(), - standard_tokio(), - tokio_std(), - tokio_mutex(), - tokio_tokio(), - skip_list_mutex_std(), - skip_list_mutex_parking_lot(), - skip_list_rw_lock_parking_lot(), - dash_map_std() - )] - repo: Repo, - #[case] entries: Entries, -) { - make(&repo, &entries).await; +async fn it_should_remove_an_entry(#[values(skip_list_mutex_std())] repo: Repo, #[case] entries: Entries) { + make(&repo, &entries); for (info_hash, torrent) in entries { - assert_eq!(repo.get(&info_hash).await, Some(torrent.clone())); - assert_eq!(repo.remove(&info_hash).await, Some(torrent)); + assert_eq!(repo.get(&info_hash), Some(torrent.clone())); + assert_eq!(repo.remove(&info_hash), Some(torrent)); - assert_eq!(repo.get(&info_hash).await, None); - assert_eq!(repo.remove(&info_hash).await, None); + assert_eq!(repo.get(&info_hash), None); + assert_eq!(repo.remove(&info_hash), None); } - assert_eq!(repo.get_metrics().await.total_torrents, 0); + assert_eq!(repo.get_metrics().total_torrents, 0); } #[rstest] @@ -510,22 +383,7 @@ async fn it_should_remove_an_entry( #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_remove_inactive_peers( - #[values( - standard(), - standard_mutex(), - standard_tokio(), - tokio_std(), - tokio_mutex(), - tokio_tokio(), - skip_list_mutex_std(), - skip_list_mutex_parking_lot(), - skip_list_rw_lock_parking_lot(), - dash_map_std() - )] - repo: Repo, - #[case] entries: Entries, -) { +async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: Repo, #[case] entries: Entries) { use std::ops::Sub as _; use std::time::Duration; @@ -538,7 +396,7 @@ async fn it_should_remove_inactive_peers( const TIMEOUT: Duration = Duration::from_secs(120); const EXPIRE: Duration = Duration::from_secs(121); - make(&repo, &entries).await; + make(&repo, &entries); let info_hash: InfoHash; let mut peer: peer::Peer; @@ -562,15 +420,15 @@ async fn it_should_remove_inactive_peers( // Insert the infohash and peer into the repository // and verify there is an extra torrent entry. { - repo.upsert_peer(&info_hash, &peer, None).await; - assert_eq!(repo.get_metrics().await.total_torrents, entries.len() as u64 + 1); + repo.upsert_peer(&info_hash, &peer, None); + assert_eq!(repo.get_metrics().total_torrents, entries.len() as u64 + 1); } // Insert the infohash and peer into the repository // and verify the swarm metadata was updated. { - repo.upsert_peer(&info_hash, &peer, None).await; - let stats = repo.get_swarm_metadata(&info_hash).await; + repo.upsert_peer(&info_hash, &peer, None); + let stats = repo.get_swarm_metadata(&info_hash); assert_eq!( stats, Some(SwarmMetadata { @@ -583,19 +441,18 @@ async fn it_should_remove_inactive_peers( // Verify that this new peer was inserted into the repository. { - let entry = repo.get(&info_hash).await.expect("it_should_get_some"); + let entry = repo.get(&info_hash).expect("it_should_get_some"); assert!(entry.get_peers(None).contains(&peer.into())); } // Remove peers that have not been updated since the timeout (120 seconds ago). { - repo.remove_inactive_peers(CurrentClock::now_sub(&TIMEOUT).expect("it should get a time passed")) - .await; + repo.remove_inactive_peers(CurrentClock::now_sub(&TIMEOUT).expect("it should get a time passed")); } // Verify that the this peer was removed from the repository. { - let entry = repo.get(&info_hash).await.expect("it_should_get_some"); + let entry = repo.get(&info_hash).expect("it_should_get_some"); assert!(!entry.get_peers(None).contains(&peer.into())); } } @@ -611,27 +468,15 @@ async fn it_should_remove_inactive_peers( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_remove_peerless_torrents( - #[values( - standard(), - standard_mutex(), - standard_tokio(), - tokio_std(), - tokio_mutex(), - tokio_tokio(), - skip_list_mutex_std(), - skip_list_mutex_parking_lot(), - skip_list_rw_lock_parking_lot(), - dash_map_std() - )] - repo: Repo, + #[values(skip_list_mutex_std())] repo: Repo, #[case] entries: Entries, #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, ) { - make(&repo, &entries).await; + make(&repo, &entries); - repo.remove_peerless_torrents(&policy).await; + repo.remove_peerless_torrents(&policy); - let torrents = repo.get_paginated(None).await; + let torrents = repo.get_paginated(None); for (_, entry) in torrents { assert!(entry.meets_retaining_policy(&policy)); From b2a96842e87e0c1bcb5b3ad140865b760b17683b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 30 Apr 2025 12:55:48 +0100 Subject: [PATCH 1032/1297] feat!: [#1491] remove unused torrent repository entry types Entry types that are not used in production. They have been moved to a new package `torrent-repository-benchmarking`. --- Cargo.lock | 1 - packages/torrent-repository/Cargo.toml | 1 - packages/torrent-repository/src/entry/mod.rs | 3 - .../src/entry/mutex_parking_lot.rs | 49 ----- .../src/entry/mutex_tokio.rs | 49 ----- .../src/entry/rw_lock_parking_lot.rs | 49 ----- packages/torrent-repository/src/lib.rs | 4 - .../src/repository/skip_map_mutex_std.rs | 190 +----------------- .../tests/common/torrent.rs | 49 +---- .../torrent-repository/tests/entry/mod.rs | 167 +++++++-------- 10 files changed, 80 insertions(+), 482 deletions(-) delete mode 100644 packages/torrent-repository/src/entry/mutex_parking_lot.rs delete mode 100644 packages/torrent-repository/src/entry/mutex_tokio.rs delete mode 100644 packages/torrent-repository/src/entry/rw_lock_parking_lot.rs diff --git a/Cargo.lock b/Cargo.lock index 5bce85e46..db6838e66 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4841,7 +4841,6 @@ dependencies = [ "bittorrent-primitives", "criterion", "crossbeam-skiplist", - "parking_lot", "rstest", "tokio", "torrust-tracker-clock", diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index d12dcbf44..6fc5f483b 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -19,7 +19,6 @@ version.workspace = true aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" crossbeam-skiplist = "0" -parking_lot = "0" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index b920839d9..ddd567a57 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -8,11 +8,8 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use self::peer_list::PeerList; -pub mod mutex_parking_lot; pub mod mutex_std; -pub mod mutex_tokio; pub mod peer_list; -pub mod rw_lock_parking_lot; pub mod single; pub trait Entry { diff --git a/packages/torrent-repository/src/entry/mutex_parking_lot.rs b/packages/torrent-repository/src/entry/mutex_parking_lot.rs deleted file mode 100644 index 738c3ff9d..000000000 --- a/packages/torrent-repository/src/entry/mutex_parking_lot.rs +++ /dev/null @@ -1,49 +0,0 @@ -use std::net::SocketAddr; -use std::sync::Arc; - -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; - -use super::{Entry, EntrySync}; -use crate::{EntryMutexParkingLot, EntrySingle}; - -impl EntrySync for EntryMutexParkingLot { - fn get_swarm_metadata(&self) -> SwarmMetadata { - self.lock().get_swarm_metadata() - } - - fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { - self.lock().meets_retaining_policy(policy) - } - - fn peers_is_empty(&self) -> bool { - self.lock().peers_is_empty() - } - - fn get_peers_len(&self) -> usize { - self.lock().get_peers_len() - } - - fn get_peers(&self, limit: Option) -> Vec> { - self.lock().get_peers(limit) - } - - fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { - self.lock().get_peers_for_client(client, limit) - } - - fn upsert_peer(&self, peer: &peer::Peer) -> bool { - self.lock().upsert_peer(peer) - } - - fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - self.lock().remove_inactive_peers(current_cutoff); - } -} - -impl From for EntryMutexParkingLot { - fn from(entry: EntrySingle) -> Self { - Arc::new(parking_lot::Mutex::new(entry)) - } -} diff --git a/packages/torrent-repository/src/entry/mutex_tokio.rs b/packages/torrent-repository/src/entry/mutex_tokio.rs deleted file mode 100644 index 6db789a72..000000000 --- a/packages/torrent-repository/src/entry/mutex_tokio.rs +++ /dev/null @@ -1,49 +0,0 @@ -use std::net::SocketAddr; -use std::sync::Arc; - -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; - -use super::{Entry, EntryAsync}; -use crate::{EntryMutexTokio, EntrySingle}; - -impl EntryAsync for EntryMutexTokio { - async fn get_swarm_metadata(&self) -> SwarmMetadata { - self.lock().await.get_swarm_metadata() - } - - async fn meets_retaining_policy(self, policy: &TrackerPolicy) -> bool { - self.lock().await.meets_retaining_policy(policy) - } - - async fn peers_is_empty(&self) -> bool { - self.lock().await.peers_is_empty() - } - - async fn get_peers_len(&self) -> usize { - self.lock().await.get_peers_len() - } - - async fn get_peers(&self, limit: Option) -> Vec> { - self.lock().await.get_peers(limit) - } - - async fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { - self.lock().await.get_peers_for_client(client, limit) - } - - async fn upsert_peer(self, peer: &peer::Peer) -> bool { - self.lock().await.upsert_peer(peer) - } - - async fn remove_inactive_peers(self, current_cutoff: DurationSinceUnixEpoch) { - self.lock().await.remove_inactive_peers(current_cutoff); - } -} - -impl From for EntryMutexTokio { - fn from(entry: EntrySingle) -> Self { - Arc::new(tokio::sync::Mutex::new(entry)) - } -} diff --git a/packages/torrent-repository/src/entry/rw_lock_parking_lot.rs b/packages/torrent-repository/src/entry/rw_lock_parking_lot.rs deleted file mode 100644 index ac0dc0b30..000000000 --- a/packages/torrent-repository/src/entry/rw_lock_parking_lot.rs +++ /dev/null @@ -1,49 +0,0 @@ -use std::net::SocketAddr; -use std::sync::Arc; - -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; - -use super::{Entry, EntrySync}; -use crate::{EntryRwLockParkingLot, EntrySingle}; - -impl EntrySync for EntryRwLockParkingLot { - fn get_swarm_metadata(&self) -> SwarmMetadata { - self.read().get_swarm_metadata() - } - - fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { - self.read().meets_retaining_policy(policy) - } - - fn peers_is_empty(&self) -> bool { - self.read().peers_is_empty() - } - - fn get_peers_len(&self) -> usize { - self.read().get_peers_len() - } - - fn get_peers(&self, limit: Option) -> Vec> { - self.read().get_peers(limit) - } - - fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { - self.read().get_peers_for_client(client, limit) - } - - fn upsert_peer(&self, peer: &peer::Peer) -> bool { - self.write().upsert_peer(peer) - } - - fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - self.write().remove_inactive_peers(current_cutoff); - } -} - -impl From for EntryRwLockParkingLot { - fn from(entry: EntrySingle) -> Self { - Arc::new(parking_lot::RwLock::new(entry)) - } -} diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index b4ee5298e..26434b1d4 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -7,12 +7,8 @@ pub mod entry; pub mod repository; // Repo Entries - pub type EntrySingle = entry::Torrent; pub type EntryMutexStd = Arc>; -pub type EntryMutexTokio = Arc>; -pub type EntryMutexParkingLot = Arc>; -pub type EntryRwLockParkingLot = Arc>; // Repository pub type TorrentsSkipMapMutexStd = CrossbeamSkipList; diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index 8a15a9442..f91334bab 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -1,5 +1,3 @@ -use std::sync::Arc; - use bittorrent_primitives::info_hash::InfoHash; use crossbeam_skiplist::SkipMap; use torrust_tracker_configuration::TrackerPolicy; @@ -10,7 +8,7 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent use super::Repository; use crate::entry::peer_list::PeerList; use crate::entry::{Entry, EntrySync}; -use crate::{EntryMutexParkingLot, EntryMutexStd, EntryRwLockParkingLot, EntrySingle}; +use crate::{EntryMutexStd, EntrySingle}; #[derive(Default, Debug)] pub struct CrossbeamSkipList { @@ -140,189 +138,3 @@ where } } } - -impl Repository for CrossbeamSkipList -where - EntryRwLockParkingLot: EntrySync, - EntrySingle: Entry, -{ - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { - // todo: load persistent torrent data if provided - - let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); - entry.value().upsert_peer(peer) - } - - fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) - } - - fn get(&self, key: &InfoHash) -> Option { - let maybe_entry = self.torrents.get(key); - maybe_entry.map(|entry| entry.value().clone()) - } - - fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); - - for entry in &self.torrents { - let stats = entry.value().read().get_swarm_metadata(); - metrics.total_complete += u64::from(stats.complete); - metrics.total_downloaded += u64::from(stats.downloaded); - metrics.total_incomplete += u64::from(stats.incomplete); - metrics.total_torrents += 1; - } - - metrics - } - - fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryRwLockParkingLot)> { - match pagination { - Some(pagination) => self - .torrents - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|entry| (*entry.key(), entry.value().clone())) - .collect(), - None => self - .torrents - .iter() - .map(|entry| (*entry.key(), entry.value().clone())) - .collect(), - } - } - - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - for (info_hash, completed) in persistent_torrents { - if self.torrents.contains_key(info_hash) { - continue; - } - - let entry = EntryRwLockParkingLot::new( - EntrySingle { - swarm: PeerList::default(), - downloaded: *completed, - } - .into(), - ); - - // Since SkipMap is lock-free the torrent could have been inserted - // after checking if it exists. - self.torrents.get_or_insert(*info_hash, entry); - } - } - - fn remove(&self, key: &InfoHash) -> Option { - self.torrents.remove(key).map(|entry| entry.value().clone()) - } - - fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - for entry in &self.torrents { - entry.value().remove_inactive_peers(current_cutoff); - } - } - - fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - for entry in &self.torrents { - if entry.value().meets_retaining_policy(policy) { - continue; - } - - entry.remove(); - } - } -} - -impl Repository for CrossbeamSkipList -where - EntryMutexParkingLot: EntrySync, - EntrySingle: Entry, -{ - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { - // todo: load persistent torrent data if provided - - let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); - entry.value().upsert_peer(peer) - } - - fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) - } - - fn get(&self, key: &InfoHash) -> Option { - let maybe_entry = self.torrents.get(key); - maybe_entry.map(|entry| entry.value().clone()) - } - - fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); - - for entry in &self.torrents { - let stats = entry.value().lock().get_swarm_metadata(); - metrics.total_complete += u64::from(stats.complete); - metrics.total_downloaded += u64::from(stats.downloaded); - metrics.total_incomplete += u64::from(stats.incomplete); - metrics.total_torrents += 1; - } - - metrics - } - - fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexParkingLot)> { - match pagination { - Some(pagination) => self - .torrents - .iter() - .skip(pagination.offset as usize) - .take(pagination.limit as usize) - .map(|entry| (*entry.key(), entry.value().clone())) - .collect(), - None => self - .torrents - .iter() - .map(|entry| (*entry.key(), entry.value().clone())) - .collect(), - } - } - - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - for (info_hash, completed) in persistent_torrents { - if self.torrents.contains_key(info_hash) { - continue; - } - - let entry = EntryMutexParkingLot::new( - EntrySingle { - swarm: PeerList::default(), - downloaded: *completed, - } - .into(), - ); - - // Since SkipMap is lock-free the torrent could have been inserted - // after checking if it exists. - self.torrents.get_or_insert(*info_hash, entry); - } - } - - fn remove(&self, key: &InfoHash) -> Option { - self.torrents.remove(key).map(|entry| entry.value().clone()) - } - - fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - for entry in &self.torrents { - entry.value().remove_inactive_peers(current_cutoff); - } - } - - fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - for entry in &self.torrents { - if entry.value().meets_retaining_policy(policy) { - continue; - } - - entry.remove(); - } - } -} diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index 927f13169..649c35cce 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -4,98 +4,69 @@ use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; -use torrust_tracker_torrent_repository::entry::{Entry as _, EntryAsync as _, EntrySync as _}; -use torrust_tracker_torrent_repository::{ - EntryMutexParkingLot, EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle, -}; +use torrust_tracker_torrent_repository::entry::{Entry as _, EntrySync as _}; +use torrust_tracker_torrent_repository::{EntryMutexStd, EntrySingle}; #[derive(Debug, Clone)] pub(crate) enum Torrent { Single(EntrySingle), MutexStd(EntryMutexStd), - MutexTokio(EntryMutexTokio), - MutexParkingLot(EntryMutexParkingLot), - RwLockParkingLot(EntryRwLockParkingLot), } impl Torrent { - pub(crate) async fn get_stats(&self) -> SwarmMetadata { + pub(crate) fn get_stats(&self) -> SwarmMetadata { match self { Torrent::Single(entry) => entry.get_swarm_metadata(), Torrent::MutexStd(entry) => entry.get_swarm_metadata(), - Torrent::MutexTokio(entry) => entry.clone().get_swarm_metadata().await, - Torrent::MutexParkingLot(entry) => entry.clone().get_swarm_metadata(), - Torrent::RwLockParkingLot(entry) => entry.clone().get_swarm_metadata(), } } - pub(crate) async fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + pub(crate) fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { match self { Torrent::Single(entry) => entry.meets_retaining_policy(policy), Torrent::MutexStd(entry) => entry.meets_retaining_policy(policy), - Torrent::MutexTokio(entry) => entry.clone().meets_retaining_policy(policy).await, - Torrent::MutexParkingLot(entry) => entry.meets_retaining_policy(policy), - Torrent::RwLockParkingLot(entry) => entry.meets_retaining_policy(policy), } } - pub(crate) async fn peers_is_empty(&self) -> bool { + pub(crate) fn peers_is_empty(&self) -> bool { match self { Torrent::Single(entry) => entry.peers_is_empty(), Torrent::MutexStd(entry) => entry.peers_is_empty(), - Torrent::MutexTokio(entry) => entry.clone().peers_is_empty().await, - Torrent::MutexParkingLot(entry) => entry.peers_is_empty(), - Torrent::RwLockParkingLot(entry) => entry.peers_is_empty(), } } - pub(crate) async fn get_peers_len(&self) -> usize { + pub(crate) fn get_peers_len(&self) -> usize { match self { Torrent::Single(entry) => entry.get_peers_len(), Torrent::MutexStd(entry) => entry.get_peers_len(), - Torrent::MutexTokio(entry) => entry.clone().get_peers_len().await, - Torrent::MutexParkingLot(entry) => entry.get_peers_len(), - Torrent::RwLockParkingLot(entry) => entry.get_peers_len(), } } - pub(crate) async fn get_peers(&self, limit: Option) -> Vec> { + pub(crate) fn get_peers(&self, limit: Option) -> Vec> { match self { Torrent::Single(entry) => entry.get_peers(limit), Torrent::MutexStd(entry) => entry.get_peers(limit), - Torrent::MutexTokio(entry) => entry.clone().get_peers(limit).await, - Torrent::MutexParkingLot(entry) => entry.get_peers(limit), - Torrent::RwLockParkingLot(entry) => entry.get_peers(limit), } } - pub(crate) async fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + pub(crate) fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { match self { Torrent::Single(entry) => entry.get_peers_for_client(client, limit), Torrent::MutexStd(entry) => entry.get_peers_for_client(client, limit), - Torrent::MutexTokio(entry) => entry.clone().get_peers_for_client(client, limit).await, - Torrent::MutexParkingLot(entry) => entry.get_peers_for_client(client, limit), - Torrent::RwLockParkingLot(entry) => entry.get_peers_for_client(client, limit), } } - pub(crate) async fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { + pub(crate) fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { match self { Torrent::Single(entry) => entry.upsert_peer(peer), Torrent::MutexStd(entry) => entry.upsert_peer(peer), - Torrent::MutexTokio(entry) => entry.clone().upsert_peer(peer).await, - Torrent::MutexParkingLot(entry) => entry.upsert_peer(peer), - Torrent::RwLockParkingLot(entry) => entry.upsert_peer(peer), } } - pub(crate) async fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + pub(crate) fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { match self { Torrent::Single(entry) => entry.remove_inactive_peers(current_cutoff), Torrent::MutexStd(entry) => entry.remove_inactive_peers(current_cutoff), - Torrent::MutexTokio(entry) => entry.clone().remove_inactive_peers(current_cutoff).await, - Torrent::MutexParkingLot(entry) => entry.remove_inactive_peers(current_cutoff), - Torrent::RwLockParkingLot(entry) => entry.remove_inactive_peers(current_cutoff), } } } diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index 43d7f94da..0fb8e8d88 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -9,9 +9,7 @@ use torrust_tracker_clock::clock::{self, Time as _}; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_torrent_repository::{ - EntryMutexParkingLot, EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle, -}; +use torrust_tracker_torrent_repository::{EntryMutexStd, EntrySingle}; use crate::common::torrent::Torrent; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; @@ -26,21 +24,6 @@ fn mutex_std() -> Torrent { Torrent::MutexStd(EntryMutexStd::default()) } -#[fixture] -fn mutex_tokio() -> Torrent { - Torrent::MutexTokio(EntryMutexTokio::default()) -} - -#[fixture] -fn mutex_parking_lot() -> Torrent { - Torrent::MutexParkingLot(EntryMutexParkingLot::default()) -} - -#[fixture] -fn rw_lock_parking_lot() -> Torrent { - Torrent::RwLockParkingLot(EntryRwLockParkingLot::default()) -} - #[fixture] fn policy_none() -> TrackerPolicy { TrackerPolicy::new(0, false, false) @@ -69,39 +52,39 @@ pub enum Makes { Three, } -async fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { +fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { match makes { Makes::Empty => vec![], Makes::Started => { let peer = a_started_peer(1); - torrent.upsert_peer(&peer).await; + torrent.upsert_peer(&peer); vec![peer] } Makes::Completed => { let peer = a_completed_peer(2); - torrent.upsert_peer(&peer).await; + torrent.upsert_peer(&peer); vec![peer] } Makes::Downloaded => { let mut peer = a_started_peer(3); - torrent.upsert_peer(&peer).await; + torrent.upsert_peer(&peer); peer.event = AnnounceEvent::Completed; peer.left = NumberOfBytes::new(0); - torrent.upsert_peer(&peer).await; + torrent.upsert_peer(&peer); vec![peer] } Makes::Three => { let peer_1 = a_started_peer(1); - torrent.upsert_peer(&peer_1).await; + torrent.upsert_peer(&peer_1); let peer_2 = a_completed_peer(2); - torrent.upsert_peer(&peer_2).await; + torrent.upsert_peer(&peer_2); let mut peer_3 = a_started_peer(3); - torrent.upsert_peer(&peer_3).await; + torrent.upsert_peer(&peer_3); peer_3.event = AnnounceEvent::Completed; peer_3.left = NumberOfBytes::new(0); - torrent.upsert_peer(&peer_3).await; + torrent.upsert_peer(&peer_3); vec![peer_1, peer_2, peer_3] } } @@ -110,13 +93,10 @@ async fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { #[rstest] #[case::empty(&Makes::Empty)] #[tokio::test] -async fn it_should_be_empty_by_default( - #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, - #[case] makes: &Makes, -) { - make(&mut torrent, makes).await; +async fn it_should_be_empty_by_default(#[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes) { + make(&mut torrent, makes); - assert_eq!(torrent.get_peers_len().await, 0); + assert_eq!(torrent.get_peers_len(), 0); } #[rstest] @@ -127,33 +107,33 @@ async fn it_should_be_empty_by_default( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_check_if_entry_should_be_retained_based_on_the_tracker_policy( - #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes, #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, ) { - make(&mut torrent, makes).await; + make(&mut torrent, makes); - let has_peers = !torrent.peers_is_empty().await; - let has_downloads = torrent.get_stats().await.downloaded != 0; + let has_peers = !torrent.peers_is_empty(); + let has_downloads = torrent.get_stats().downloaded != 0; match (policy.remove_peerless_torrents, policy.persistent_torrent_completed_stat) { // remove torrents without peers, and keep completed download stats (true, true) => match (has_peers, has_downloads) { // no peers, but has downloads // peers, with or without downloads - (false, true) | (true, true | false) => assert!(torrent.meets_retaining_policy(&policy).await), + (false, true) | (true, true | false) => assert!(torrent.meets_retaining_policy(&policy)), // no peers and no downloads - (false, false) => assert!(!torrent.meets_retaining_policy(&policy).await), + (false, false) => assert!(!torrent.meets_retaining_policy(&policy)), }, // remove torrents without peers and drop completed download stats (true, false) => match (has_peers, has_downloads) { // peers, with or without downloads - (true, true | false) => assert!(torrent.meets_retaining_policy(&policy).await), + (true, true | false) => assert!(torrent.meets_retaining_policy(&policy)), // no peers and with or without downloads - (false, true | false) => assert!(!torrent.meets_retaining_policy(&policy).await), + (false, true | false) => assert!(!torrent.meets_retaining_policy(&policy)), }, // keep torrents without peers, but keep or drop completed download stats - (false, true | false) => assert!(torrent.meets_retaining_policy(&policy).await), + (false, true | false) => assert!(torrent.meets_retaining_policy(&policy)), } } @@ -164,13 +144,10 @@ async fn it_should_check_if_entry_should_be_retained_based_on_the_tracker_policy #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_get_peers_for_torrent_entry( - #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, - #[case] makes: &Makes, -) { - let peers = make(&mut torrent, makes).await; +async fn it_should_get_peers_for_torrent_entry(#[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes) { + let peers = make(&mut torrent, makes); - let torrent_peers = torrent.get_peers(None).await; + let torrent_peers = torrent.get_peers(None); assert_eq!(torrent_peers.len(), peers.len()); @@ -186,15 +163,15 @@ async fn it_should_get_peers_for_torrent_entry( #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_update_a_peer(#[values(single(), mutex_std(), mutex_tokio())] mut torrent: Torrent, #[case] makes: &Makes) { - make(&mut torrent, makes).await; +async fn it_should_update_a_peer(#[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes) { + make(&mut torrent, makes); // Make and insert a new peer. let mut peer = a_started_peer(-1); - torrent.upsert_peer(&peer).await; + torrent.upsert_peer(&peer); // Get the Inserted Peer by Id. - let peers = torrent.get_peers(None).await; + let peers = torrent.get_peers(None); let original = peers .iter() .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) @@ -204,10 +181,10 @@ async fn it_should_update_a_peer(#[values(single(), mutex_std(), mutex_tokio())] // Announce "Completed" torrent download event. peer.event = AnnounceEvent::Completed; - torrent.upsert_peer(&peer).await; + torrent.upsert_peer(&peer); // Get the Updated Peer by Id. - let peers = torrent.get_peers(None).await; + let peers = torrent.get_peers(None); let updated = peers .iter() .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) @@ -224,19 +201,19 @@ async fn it_should_update_a_peer(#[values(single(), mutex_std(), mutex_tokio())] #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_remove_a_peer_upon_stopped_announcement( - #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes, ) { use torrust_tracker_primitives::peer::ReadInfo as _; - make(&mut torrent, makes).await; + make(&mut torrent, makes); let mut peer = a_started_peer(-1); - torrent.upsert_peer(&peer).await; + torrent.upsert_peer(&peer); // The started peer should be inserted. - let peers = torrent.get_peers(None).await; + let peers = torrent.get_peers(None); let original = peers .iter() .find(|p| p.get_id() == peer.get_id()) @@ -246,10 +223,10 @@ async fn it_should_remove_a_peer_upon_stopped_announcement( // Change peer to "Stopped" and insert. peer.event = AnnounceEvent::Stopped; - torrent.upsert_peer(&peer).await; + torrent.upsert_peer(&peer); // It should be removed now. - let peers = torrent.get_peers(None).await; + let peers = torrent.get_peers(None); assert_eq!( peers.iter().find(|p| p.get_id() == peer.get_id()), @@ -265,13 +242,13 @@ async fn it_should_remove_a_peer_upon_stopped_announcement( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloaded_statistic( - #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes, ) { - make(&mut torrent, makes).await; - let downloaded = torrent.get_stats().await.downloaded; + make(&mut torrent, makes); + let downloaded = torrent.get_stats().downloaded; - let peers = torrent.get_peers(None).await; + let peers = torrent.get_peers(None); let mut peer = **peers.first().expect("there should be a peer"); let is_already_completed = peer.event == AnnounceEvent::Completed; @@ -279,8 +256,8 @@ async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloade // Announce "Completed" torrent download event. peer.event = AnnounceEvent::Completed; - torrent.upsert_peer(&peer).await; - let stats = torrent.get_stats().await; + torrent.upsert_peer(&peer); + let stats = torrent.get_stats(); if is_already_completed { assert_eq!(stats.downloaded, downloaded); @@ -295,22 +272,19 @@ async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloade #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_update_a_peer_as_a_seeder( - #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, - #[case] makes: &Makes, -) { - let peers = make(&mut torrent, makes).await; +async fn it_should_update_a_peer_as_a_seeder(#[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes) { + let peers = make(&mut torrent, makes); let completed = u32::try_from(peers.iter().filter(|p| p.is_seeder()).count()).expect("it_should_not_be_so_many"); - let peers = torrent.get_peers(None).await; + let peers = torrent.get_peers(None); let mut peer = **peers.first().expect("there should be a peer"); let is_already_non_left = peer.left == NumberOfBytes::new(0); // Set Bytes Left to Zero peer.left = NumberOfBytes::new(0); - torrent.upsert_peer(&peer).await; - let stats = torrent.get_stats().await; + torrent.upsert_peer(&peer); + let stats = torrent.get_stats(); if is_already_non_left { // it was already complete @@ -327,22 +301,19 @@ async fn it_should_update_a_peer_as_a_seeder( #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_update_a_peer_as_incomplete( - #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, - #[case] makes: &Makes, -) { - let peers = make(&mut torrent, makes).await; +async fn it_should_update_a_peer_as_incomplete(#[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes) { + let peers = make(&mut torrent, makes); let incomplete = u32::try_from(peers.iter().filter(|p| !p.is_seeder()).count()).expect("it should not be so many"); - let peers = torrent.get_peers(None).await; + let peers = torrent.get_peers(None); let mut peer = **peers.first().expect("there should be a peer"); let completed_already = peer.left == NumberOfBytes::new(0); // Set Bytes Left to no Zero peer.left = NumberOfBytes::new(1); - torrent.upsert_peer(&peer).await; - let stats = torrent.get_stats().await; + torrent.upsert_peer(&peer); + let stats = torrent.get_stats(); if completed_already { // now it is incomplete @@ -360,12 +331,12 @@ async fn it_should_update_a_peer_as_incomplete( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_get_peers_excluding_the_client_socket( - #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes, ) { - make(&mut torrent, makes).await; + make(&mut torrent, makes); - let peers = torrent.get_peers(None).await; + let peers = torrent.get_peers(None); let mut peer = **peers.first().expect("there should be a peer"); let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8081); @@ -374,14 +345,14 @@ async fn it_should_get_peers_excluding_the_client_socket( assert_ne!(peer.peer_addr, socket); // it should get the peer as it dose not share the socket. - assert!(torrent.get_peers_for_client(&socket, None).await.contains(&peer.into())); + assert!(torrent.get_peers_for_client(&socket, None).contains(&peer.into())); // set the address to the socket. peer.peer_addr = socket; - torrent.upsert_peer(&peer).await; // Add peer + torrent.upsert_peer(&peer); // Add peer // It should not include the peer that has the same socket. - assert!(!torrent.get_peers_for_client(&socket, None).await.contains(&peer.into())); + assert!(!torrent.get_peers_for_client(&socket, None).contains(&peer.into())); } #[rstest] @@ -392,19 +363,19 @@ async fn it_should_get_peers_excluding_the_client_socket( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_limit_the_number_of_peers_returned( - #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes, ) { - make(&mut torrent, makes).await; + make(&mut torrent, makes); // We add one more peer than the scrape limit for peer_number in 1..=74 + 1 { let mut peer = a_started_peer(1); peer.peer_id = *peer::Id::new(peer_number); - torrent.upsert_peer(&peer).await; + torrent.upsert_peer(&peer); } - let peers = torrent.get_peers(Some(TORRENT_PEERS_LIMIT)).await; + let peers = torrent.get_peers(Some(TORRENT_PEERS_LIMIT)); assert_eq!(peers.len(), 74); } @@ -417,13 +388,13 @@ async fn it_should_limit_the_number_of_peers_returned( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_remove_inactive_peers_beyond_cutoff( - #[values(single(), mutex_std(), mutex_tokio(), mutex_parking_lot(), rw_lock_parking_lot())] mut torrent: Torrent, + #[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes, ) { const TIMEOUT: Duration = Duration::from_secs(120); const EXPIRE: Duration = Duration::from_secs(121); - let peers = make(&mut torrent, makes).await; + let peers = make(&mut torrent, makes); let mut peer = a_completed_peer(-1); @@ -432,12 +403,12 @@ async fn it_should_remove_inactive_peers_beyond_cutoff( peer.updated = now.sub(EXPIRE); - torrent.upsert_peer(&peer).await; + torrent.upsert_peer(&peer); - assert_eq!(torrent.get_peers_len().await, peers.len() + 1); + assert_eq!(torrent.get_peers_len(), peers.len() + 1); let current_cutoff = CurrentClock::now_sub(&TIMEOUT).unwrap_or_default(); - torrent.remove_inactive_peers(current_cutoff).await; + torrent.remove_inactive_peers(current_cutoff); - assert_eq!(torrent.get_peers_len().await, peers.len()); + assert_eq!(torrent.get_peers_len(), peers.len()); } From 89123fa397f1ffa4bad2e2a912ba03a85cff9920 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 30 Apr 2025 14:19:34 +0100 Subject: [PATCH 1033/1297] feat!: [#1491] remove unused traits RepositoryAsync and EntryAsync They have been moved to a new package `torrent-repository-benchmarking`. --- packages/torrent-repository/src/entry/mod.rs | 16 ---------------- .../torrent-repository/src/repository/mod.rs | 18 ------------------ 2 files changed, 34 deletions(-) diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index ddd567a57..24e85ae94 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -59,22 +59,6 @@ pub trait EntrySync { fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); } -#[allow(clippy::module_name_repetitions)] -pub trait EntryAsync { - fn get_swarm_metadata(&self) -> impl std::future::Future + Send; - fn meets_retaining_policy(self, policy: &TrackerPolicy) -> impl std::future::Future + Send; - fn peers_is_empty(&self) -> impl std::future::Future + Send; - fn get_peers_len(&self) -> impl std::future::Future + Send; - fn get_peers(&self, limit: Option) -> impl std::future::Future>> + Send; - fn get_peers_for_client( - &self, - client: &SocketAddr, - limit: Option, - ) -> impl std::future::Future>> + Send; - fn upsert_peer(self, peer: &peer::Peer) -> impl std::future::Future + Send; - fn remove_inactive_peers(self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; -} - /// A data structure containing all the information about a torrent in the tracker. /// /// This is the tracker entry for a given torrent and contains the swarm data, diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs index 96c71f3a0..850289a01 100644 --- a/packages/torrent-repository/src/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -19,21 +19,3 @@ pub trait Repository: Debug + Default + Sized + 'static { fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool; fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option; } - -#[allow(clippy::module_name_repetitions)] -pub trait RepositoryAsync: Debug + Default + Sized + 'static { - fn get(&self, key: &InfoHash) -> impl std::future::Future> + Send; - fn get_metrics(&self) -> impl std::future::Future + Send; - fn get_paginated(&self, pagination: Option<&Pagination>) -> impl std::future::Future> + Send; - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) -> impl std::future::Future + Send; - fn remove(&self, key: &InfoHash) -> impl std::future::Future> + Send; - fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; - fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> impl std::future::Future + Send; - fn upsert_peer( - &self, - info_hash: &InfoHash, - peer: &peer::Peer, - opt_persistent_torrent: Option, - ) -> impl std::future::Future + Send; - fn get_swarm_metadata(&self, info_hash: &InfoHash) -> impl std::future::Future> + Send; -} From 382e0af7c9a694fcd2f97825bc16fc1e8784d16e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 30 Apr 2025 17:13:07 +0100 Subject: [PATCH 1034/1297] faet!: [#1491] remove unused trait Repository --- .../torrent-repository/src/repository/mod.rs | 20 ------------- .../src/repository/skip_map_mutex_std.rs | 29 ++++++++++++------- .../torrent-repository/tests/common/repo.rs | 1 - .../src/torrent/repository/in_memory.rs | 1 - 4 files changed, 18 insertions(+), 33 deletions(-) diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs index 850289a01..3b8259f9d 100644 --- a/packages/torrent-repository/src/repository/mod.rs +++ b/packages/torrent-repository/src/repository/mod.rs @@ -1,21 +1 @@ -use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; - pub mod skip_map_mutex_std; - -use std::fmt::Debug; - -pub trait Repository: Debug + Default + Sized + 'static { - fn get(&self, key: &InfoHash) -> Option; - fn get_metrics(&self) -> AggregateSwarmMetadata; - fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, T)>; - fn import_persistent(&self, persistent_torrents: &PersistentTorrents); - fn remove(&self, key: &InfoHash) -> Option; - fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); - fn remove_peerless_torrents(&self, policy: &TrackerPolicy); - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool; - fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option; -} diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index f91334bab..0d13e39b2 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -5,7 +5,6 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use super::Repository; use crate::entry::peer_list::PeerList; use crate::entry::{Entry, EntrySync}; use crate::{EntryMutexStd, EntrySingle}; @@ -15,7 +14,7 @@ pub struct CrossbeamSkipList { pub torrents: SkipMap, } -impl Repository for CrossbeamSkipList +impl CrossbeamSkipList where EntryMutexStd: EntrySync, EntrySingle: Entry, @@ -36,7 +35,12 @@ where /// /// Returns `true` if the number of downloads was increased because the peer /// completed the download. - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool { + pub fn upsert_peer( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + opt_persistent_torrent: Option, + ) -> bool { if let Some(existing_entry) = self.torrents.get(info_hash) { existing_entry.value().upsert_peer(peer) } else { @@ -58,16 +62,19 @@ where } } - fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) } - fn get(&self, key: &InfoHash) -> Option { + pub fn get(&self, key: &InfoHash) -> Option { let maybe_entry = self.torrents.get(key); maybe_entry.map(|entry| entry.value().clone()) } - fn get_metrics(&self) -> AggregateSwarmMetadata { + /// # Panics + /// + /// This function panics if the lock for the entry cannot be obtained. + pub fn get_metrics(&self) -> AggregateSwarmMetadata { let mut metrics = AggregateSwarmMetadata::default(); for entry in &self.torrents { @@ -81,7 +88,7 @@ where metrics } - fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { match pagination { Some(pagination) => self .torrents @@ -98,7 +105,7 @@ where } } - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + pub fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { for (info_hash, completed) in persistent_torrents { if self.torrents.contains_key(info_hash) { continue; @@ -118,17 +125,17 @@ where } } - fn remove(&self, key: &InfoHash) -> Option { + pub fn remove(&self, key: &InfoHash) -> Option { self.torrents.remove(key).map(|entry| entry.value().clone()) } - fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { for entry in &self.torrents { entry.value().remove_inactive_peers(current_cutoff); } } - fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { for entry in &self.torrents { if entry.value().meets_retaining_policy(policy) { continue; diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 95dd3f5ad..54f6ba486 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -3,7 +3,6 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use torrust_tracker_torrent_repository::repository::Repository as _; use torrust_tracker_torrent_repository::{EntrySingle, TorrentsSkipMapMutexStd}; #[derive(Debug)] diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index e09bede8e..142338eea 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -8,7 +8,6 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use torrust_tracker_torrent_repository::entry::EntrySync; -use torrust_tracker_torrent_repository::repository::Repository; use torrust_tracker_torrent_repository::EntryMutexStd; use crate::torrent::Torrents; From ecd2266fdc913099c172097a6677498b60a64686 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 30 Apr 2025 21:22:34 +0100 Subject: [PATCH 1035/1297] feat!: [#1491] remove unused traits Entry and EntrySync This is part of a bigger refactor makeing the torrent-repositoru package impler. Only using types used in production and removing traits that only have one implementation. --- packages/torrent-repository/src/entry/mod.rs | 55 +------------------ .../torrent-repository/src/entry/mutex_std.rs | 51 ----------------- .../torrent-repository/src/entry/single.rs | 25 +++++---- .../src/repository/skip_map_mutex_std.rs | 55 +++++++++++++++---- .../torrent-repository/tests/common/repo.rs | 4 +- .../tests/common/torrent.rs | 29 +++++++--- .../tests/repository/mod.rs | 1 - packages/tracker-core/src/announce_handler.rs | 15 ++++- packages/tracker-core/src/torrent/manager.rs | 3 +- .../src/torrent/repository/in_memory.rs | 36 +++++++++--- packages/tracker-core/src/torrent/services.rs | 33 +++++++++-- 11 files changed, 153 insertions(+), 154 deletions(-) delete mode 100644 packages/torrent-repository/src/entry/mutex_std.rs diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index 24e85ae94..4b1201730 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -1,64 +1,10 @@ use std::fmt::Debug; -use std::net::SocketAddr; -use std::sync::Arc; - -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use self::peer_list::PeerList; -pub mod mutex_std; pub mod peer_list; pub mod single; -pub trait Entry { - /// It returns the swarm metadata (statistics) as a struct: - /// - /// `(seeders, completed, leechers)` - fn get_swarm_metadata(&self) -> SwarmMetadata; - - /// Returns True if Still a Valid Entry according to the Tracker Policy - fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool; - - /// Returns True if the Peers is Empty - fn peers_is_empty(&self) -> bool; - - /// Returns the number of Peers - fn get_peers_len(&self) -> usize; - - /// Get all swarm peers, optionally limiting the result. - fn get_peers(&self, limit: Option) -> Vec>; - - /// It returns the list of peers for a given peer client, optionally limiting the - /// result. - /// - /// It filters out the input peer, typically because we want to return this - /// list of peers to that client peer. - fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec>; - - /// It updates a peer and returns true if the number of complete downloads have increased. - /// - /// The number of peers that have complete downloading is synchronously updated when peers are updated. - /// That's the total torrent downloads counter. - fn upsert_peer(&mut self, peer: &peer::Peer) -> bool; - - /// It removes peer from the swarm that have not been updated for more than `current_cutoff` seconds - fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch); -} - -#[allow(clippy::module_name_repetitions)] -pub trait EntrySync { - fn get_swarm_metadata(&self) -> SwarmMetadata; - fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool; - fn peers_is_empty(&self) -> bool; - fn get_peers_len(&self) -> usize; - fn get_peers(&self, limit: Option) -> Vec>; - fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec>; - fn upsert_peer(&self, peer: &peer::Peer) -> bool; - fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); -} - /// A data structure containing all the information about a torrent in the tracker. /// /// This is the tracker entry for a given torrent and contains the swarm data, @@ -68,6 +14,7 @@ pub trait EntrySync { pub struct Torrent { /// A network of peers that are all trying to download the torrent associated to this entry pub(crate) swarm: PeerList, + /// The number of peers that have ever completed downloading the torrent associated to this entry pub(crate) downloaded: u32, } diff --git a/packages/torrent-repository/src/entry/mutex_std.rs b/packages/torrent-repository/src/entry/mutex_std.rs deleted file mode 100644 index 0ab70a96f..000000000 --- a/packages/torrent-repository/src/entry/mutex_std.rs +++ /dev/null @@ -1,51 +0,0 @@ -use std::net::SocketAddr; -use std::sync::Arc; - -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; - -use super::{Entry, EntrySync}; -use crate::{EntryMutexStd, EntrySingle}; - -impl EntrySync for EntryMutexStd { - fn get_swarm_metadata(&self) -> SwarmMetadata { - self.lock().expect("it should get a lock").get_swarm_metadata() - } - - fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { - self.lock().expect("it should get a lock").meets_retaining_policy(policy) - } - - fn peers_is_empty(&self) -> bool { - self.lock().expect("it should get a lock").peers_is_empty() - } - - fn get_peers_len(&self) -> usize { - self.lock().expect("it should get a lock").get_peers_len() - } - - fn get_peers(&self, limit: Option) -> Vec> { - self.lock().expect("it should get lock").get_peers(limit) - } - - fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { - self.lock().expect("it should get lock").get_peers_for_client(client, limit) - } - - fn upsert_peer(&self, peer: &peer::Peer) -> bool { - self.lock().expect("it should lock the entry").upsert_peer(peer) - } - - fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - self.lock() - .expect("it should lock the entry") - .remove_inactive_peers(current_cutoff); - } -} - -impl From for EntryMutexStd { - fn from(entry: EntrySingle) -> Self { - Arc::new(std::sync::Mutex::new(entry)) - } -} diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs index 0f922bd02..44f1012e1 100644 --- a/packages/torrent-repository/src/entry/single.rs +++ b/packages/torrent-repository/src/entry/single.rs @@ -7,12 +7,12 @@ use torrust_tracker_primitives::peer::{self}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use super::Entry; use crate::EntrySingle; -impl Entry for EntrySingle { +impl EntrySingle { #[allow(clippy::cast_possible_truncation)] - fn get_swarm_metadata(&self) -> SwarmMetadata { + #[must_use] + pub fn get_swarm_metadata(&self) -> SwarmMetadata { let (seeders, leechers) = self.swarm.seeders_and_leechers(); SwarmMetadata { @@ -22,7 +22,8 @@ impl Entry for EntrySingle { } } - fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + #[must_use] + pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { if policy.persistent_torrent_completed_stat && self.downloaded > 0 { return true; } @@ -34,23 +35,27 @@ impl Entry for EntrySingle { true } - fn peers_is_empty(&self) -> bool { + #[must_use] + pub fn peers_is_empty(&self) -> bool { self.swarm.is_empty() } - fn get_peers_len(&self) -> usize { + #[must_use] + pub fn get_peers_len(&self) -> usize { self.swarm.len() } - fn get_peers(&self, limit: Option) -> Vec> { + #[must_use] + pub fn get_peers(&self, limit: Option) -> Vec> { self.swarm.get_all(limit) } - fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + #[must_use] + pub fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { self.swarm.get_peers_excluding_addr(client, limit) } - fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { + pub fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { let mut number_of_downloads_increased: bool = false; match peer::ReadInfo::get_event(peer) { @@ -75,7 +80,7 @@ impl Entry for EntrySingle { number_of_downloads_increased } - fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { self.swarm.remove_inactive_peers(current_cutoff); } } diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index 0d13e39b2..3c806ed69 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -6,7 +6,6 @@ use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMe use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use crate::entry::peer_list::PeerList; -use crate::entry::{Entry, EntrySync}; use crate::{EntryMutexStd, EntrySingle}; #[derive(Default, Debug)] @@ -14,11 +13,7 @@ pub struct CrossbeamSkipList { pub torrents: SkipMap, } -impl CrossbeamSkipList -where - EntryMutexStd: EntrySync, - EntrySingle: Entry, -{ +impl CrossbeamSkipList { /// Upsert a peer into the swarm of a torrent. /// /// Optionally, it can also preset the number of downloads of the torrent @@ -35,6 +30,10 @@ where /// /// Returns `true` if the number of downloads was increased because the peer /// completed the download. + /// + /// # Panics + /// + /// This function panics if the lock for the entry cannot be obtained. pub fn upsert_peer( &self, info_hash: &InfoHash, @@ -42,7 +41,11 @@ where opt_persistent_torrent: Option, ) -> bool { if let Some(existing_entry) = self.torrents.get(info_hash) { - existing_entry.value().upsert_peer(peer) + existing_entry + .value() + .lock() + .expect("can't acquire lock for torrent entry") + .upsert_peer(peer) } else { let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { EntryMutexStd::new( @@ -58,12 +61,27 @@ where let inserted_entry = self.torrents.get_or_insert(*info_hash, new_entry); - inserted_entry.value().upsert_peer(peer) + let number_of_downloads_increased = inserted_entry + .value() + .lock() + .expect("can't acquire lock for torrent entry") + .upsert_peer(peer); + + number_of_downloads_increased } } + /// # Panics + /// + /// This function panics if the lock for the entry cannot be obtained. pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.torrents.get(info_hash).map(|entry| entry.value().get_swarm_metadata()) + self.torrents.get(info_hash).map(|entry| { + entry + .value() + .lock() + .expect("can't acquire lock for torrent entry") + .get_swarm_metadata() + }) } pub fn get(&self, key: &InfoHash) -> Option { @@ -129,15 +147,30 @@ where self.torrents.remove(key).map(|entry| entry.value().clone()) } + /// # Panics + /// + /// This function panics if the lock for the entry cannot be obtained. pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { for entry in &self.torrents { - entry.value().remove_inactive_peers(current_cutoff); + entry + .value() + .lock() + .expect("can't acquire lock for torrent entry") + .remove_inactive_peers(current_cutoff); } } + /// # Panics + /// + /// This function panics if the lock for the entry cannot be obtained. pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { for entry in &self.torrents { - if entry.value().meets_retaining_policy(policy) { + if entry + .value() + .lock() + .expect("can't acquire lock for torrent entry") + .meets_retaining_policy(policy) + { continue; } diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 54f6ba486..41df77bf9 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -1,3 +1,5 @@ +use std::sync::{Arc, Mutex}; + use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; @@ -77,7 +79,7 @@ impl Repo { pub(crate) fn insert(&self, info_hash: &InfoHash, torrent: EntrySingle) -> Option { match self { Repo::SkipMapMutexStd(repo) => { - repo.torrents.insert(*info_hash, torrent.into()); + repo.torrents.insert(*info_hash, Arc::new(Mutex::new(torrent))); } } self.get(info_hash) diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index 649c35cce..84ea79eef 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -4,7 +4,6 @@ use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; -use torrust_tracker_torrent_repository::entry::{Entry as _, EntrySync as _}; use torrust_tracker_torrent_repository::{EntryMutexStd, EntrySingle}; #[derive(Debug, Clone)] @@ -17,56 +16,68 @@ impl Torrent { pub(crate) fn get_stats(&self) -> SwarmMetadata { match self { Torrent::Single(entry) => entry.get_swarm_metadata(), - Torrent::MutexStd(entry) => entry.get_swarm_metadata(), + Torrent::MutexStd(entry) => entry + .lock() + .expect("can't acquire lock for torrent entry") + .get_swarm_metadata(), } } pub(crate) fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { match self { Torrent::Single(entry) => entry.meets_retaining_policy(policy), - Torrent::MutexStd(entry) => entry.meets_retaining_policy(policy), + Torrent::MutexStd(entry) => entry + .lock() + .expect("can't acquire lock for torrent entry") + .meets_retaining_policy(policy), } } pub(crate) fn peers_is_empty(&self) -> bool { match self { Torrent::Single(entry) => entry.peers_is_empty(), - Torrent::MutexStd(entry) => entry.peers_is_empty(), + Torrent::MutexStd(entry) => entry.lock().expect("can't acquire lock for torrent entry").peers_is_empty(), } } pub(crate) fn get_peers_len(&self) -> usize { match self { Torrent::Single(entry) => entry.get_peers_len(), - Torrent::MutexStd(entry) => entry.get_peers_len(), + Torrent::MutexStd(entry) => entry.lock().expect("can't acquire lock for torrent entry").get_peers_len(), } } pub(crate) fn get_peers(&self, limit: Option) -> Vec> { match self { Torrent::Single(entry) => entry.get_peers(limit), - Torrent::MutexStd(entry) => entry.get_peers(limit), + Torrent::MutexStd(entry) => entry.lock().expect("can't acquire lock for torrent entry").get_peers(limit), } } pub(crate) fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { match self { Torrent::Single(entry) => entry.get_peers_for_client(client, limit), - Torrent::MutexStd(entry) => entry.get_peers_for_client(client, limit), + Torrent::MutexStd(entry) => entry + .lock() + .expect("can't acquire lock for torrent entry") + .get_peers_for_client(client, limit), } } pub(crate) fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { match self { Torrent::Single(entry) => entry.upsert_peer(peer), - Torrent::MutexStd(entry) => entry.upsert_peer(peer), + Torrent::MutexStd(entry) => entry.lock().expect("can't acquire lock for torrent entry").upsert_peer(peer), } } pub(crate) fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { match self { Torrent::Single(entry) => entry.remove_inactive_peers(current_cutoff), - Torrent::MutexStd(entry) => entry.remove_inactive_peers(current_cutoff), + Torrent::MutexStd(entry) => entry + .lock() + .expect("can't acquire lock for torrent entry") + .remove_inactive_peers(current_cutoff), } } } diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index d0ef61e81..ae0066b25 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -8,7 +8,6 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::PersistentTorrents; -use torrust_tracker_torrent_repository::entry::Entry as _; use torrust_tracker_torrent_repository::repository::skip_map_mutex_std::CrossbeamSkipList; use torrust_tracker_torrent_repository::EntrySingle; diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index b858cae6c..ac70c6f86 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -594,7 +594,6 @@ mod tests { use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_test_helpers::configuration; - use torrust_tracker_torrent_repository::entry::EntrySync; use crate::announce_handler::tests::the_announce_handler::peer_ip; use crate::announce_handler::{AnnounceHandler, PeersWanted}; @@ -657,10 +656,20 @@ mod tests { .expect("it should be able to get entry"); // It persists the number of completed peers. - assert_eq!(torrent_entry.get_swarm_metadata().downloaded, 1); + assert_eq!( + torrent_entry + .lock() + .expect("can't acquire lock for torrent entry") + .get_swarm_metadata() + .downloaded, + 1 + ); // It does not persist the peers - assert!(torrent_entry.peers_is_empty()); + assert!(torrent_entry + .lock() + .expect("can't acquire lock for torrent entry") + .peers_is_empty()); } } diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index 792bb024d..a69f8282b 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -110,7 +110,6 @@ mod tests { use std::sync::Arc; use torrust_tracker_configuration::Core; - use torrust_tracker_torrent_repository::entry::EntrySync; use super::{DatabasePersistentTorrentRepository, TorrentsManager}; use crate::databases::setup::initialize_database; @@ -164,6 +163,8 @@ mod tests { .in_memory_torrent_repository .get(&infohash) .unwrap() + .lock() + .expect("can't acquire lock for torrent entry") .get_swarm_metadata() .downloaded, 1 diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 142338eea..746de190f 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -7,7 +7,6 @@ use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use torrust_tracker_torrent_repository::entry::EntrySync; use torrust_tracker_torrent_repository::EntryMutexStd; use crate::torrent::Torrents; @@ -145,7 +144,10 @@ impl InMemoryTorrentRepository { #[must_use] pub(crate) fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { match self.torrents.get(info_hash) { - Some(torrent_entry) => torrent_entry.get_swarm_metadata(), + Some(torrent_entry) => torrent_entry + .lock() + .expect("can't acquire lock for torrent entry") + .get_swarm_metadata(), None => SwarmMetadata::zeroed(), } } @@ -171,7 +173,10 @@ impl InMemoryTorrentRepository { pub(crate) fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { match self.torrents.get(info_hash) { None => vec![], - Some(entry) => entry.get_peers_for_client(&peer.peer_addr, Some(max(limit, TORRENT_PEERS_LIMIT))), + Some(entry) => entry + .lock() + .expect("can't acquire lock for torrent entry") + .get_peers_for_client(&peer.peer_addr, Some(max(limit, TORRENT_PEERS_LIMIT))), } } @@ -188,11 +193,18 @@ impl InMemoryTorrentRepository { /// /// A vector of peers (wrapped in `Arc`) representing the active peers for /// the torrent. + /// + /// # Panics + /// + /// This function panics if the lock for the torrent entry cannot be obtained. #[must_use] pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { match self.torrents.get(info_hash) { None => vec![], - Some(entry) => entry.get_peers(Some(TORRENT_PEERS_LIMIT)), + Some(entry) => entry + .lock() + .expect("can't acquire lock for torrent entry") + .get_peers(Some(TORRENT_PEERS_LIMIT)), } } @@ -500,7 +512,6 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use torrust_tracker_torrent_repository::entry::EntrySync; use crate::test_helpers::tests::{sample_info_hash, sample_peer}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -520,9 +531,18 @@ mod tests { impl Into for TorrentEntry { fn into(self) -> TorrentEntryInfo { TorrentEntryInfo { - swarm_metadata: self.get_swarm_metadata(), - peers: self.get_peers(None).iter().map(|peer| *peer.clone()).collect(), - number_of_peers: self.get_peers_len(), + swarm_metadata: self + .lock() + .expect("can't acquire lock for torrent entry") + .get_swarm_metadata(), + peers: self + .lock() + .expect("can't acquire lock for torrent entry") + .get_peers(None) + .iter() + .map(|peer| *peer.clone()) + .collect(), + number_of_peers: self.lock().expect("can't acquire lock for torrent entry").get_peers_len(), } } } diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index 88af3b570..2bf4bba71 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -17,7 +17,6 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::peer; -use torrust_tracker_torrent_repository::entry::EntrySync; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -89,15 +88,25 @@ pub struct BasicInfo { /// An [`Option`] which is: /// - `Some(Info)` if the torrent exists in the repository. /// - `None` if the torrent is not found. +/// +/// # Panics +/// +/// This function panics if the lock for the torrent entry cannot be obtained. #[must_use] pub fn get_torrent_info(in_memory_torrent_repository: &Arc, info_hash: &InfoHash) -> Option { let torrent_entry_option = in_memory_torrent_repository.get(info_hash); let torrent_entry = torrent_entry_option?; - let stats = torrent_entry.get_swarm_metadata(); + let stats = torrent_entry + .lock() + .expect("can't acquire lock for torrent entry") + .get_swarm_metadata(); - let peers = torrent_entry.get_peers(None); + let peers = torrent_entry + .lock() + .expect("can't acquire lock for torrent entry") + .get_peers(None); let peers = Some(peers.iter().map(|peer| (**peer)).collect()); @@ -127,6 +136,10 @@ pub fn get_torrent_info(in_memory_torrent_repository: &Arc, @@ -135,7 +148,10 @@ pub fn get_torrents_page( let mut basic_infos: Vec = vec![]; for (info_hash, torrent_entry) in in_memory_torrent_repository.get_paginated(pagination) { - let stats = torrent_entry.get_swarm_metadata(); + let stats = torrent_entry + .lock() + .expect("can't acquire lock for torrent entry") + .get_swarm_metadata(); basic_infos.push(BasicInfo { info_hash, @@ -165,12 +181,19 @@ pub fn get_torrents_page( /// # Returns /// /// A vector of [`BasicInfo`] structs for the requested torrents. +/// +/// # Panics +/// +/// This function panics if the lock for the torrent entry cannot be obtained. #[must_use] pub fn get_torrents(in_memory_torrent_repository: &Arc, info_hashes: &[InfoHash]) -> Vec { let mut basic_infos: Vec = vec![]; for info_hash in info_hashes { - if let Some(stats) = in_memory_torrent_repository.get(info_hash).map(|t| t.get_swarm_metadata()) { + if let Some(stats) = in_memory_torrent_repository + .get(info_hash) + .map(|t| t.lock().expect("can't acquire lock for torrent entry").get_swarm_metadata()) + { basic_infos.push(BasicInfo { info_hash: *info_hash, seeders: u64::from(stats.complete), From e0a4aac879c801f7ea0f646e62dd4d293b803a39 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 30 Apr 2025 22:12:10 +0100 Subject: [PATCH 1036/1297] feat!: [#1491] remove unneeded generic --- packages/torrent-repository/src/lib.rs | 3 +-- .../torrent-repository/src/repository/skip_map_mutex_std.rs | 6 +++--- packages/torrent-repository/tests/repository/mod.rs | 5 ++--- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 26434b1d4..846545387 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,6 +1,5 @@ use std::sync::Arc; -use repository::skip_map_mutex_std::CrossbeamSkipList; use torrust_tracker_clock::clock; pub mod entry; @@ -11,7 +10,7 @@ pub type EntrySingle = entry::Torrent; pub type EntryMutexStd = Arc>; // Repository -pub type TorrentsSkipMapMutexStd = CrossbeamSkipList; +pub type TorrentsSkipMapMutexStd = repository::skip_map_mutex_std::TorrentsSkipMapMutexStd; /// This code needs to be copied into each crate. /// Working version, for production. diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index 3c806ed69..fb287b0f1 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -9,11 +9,11 @@ use crate::entry::peer_list::PeerList; use crate::{EntryMutexStd, EntrySingle}; #[derive(Default, Debug)] -pub struct CrossbeamSkipList { - pub torrents: SkipMap, +pub struct TorrentsSkipMapMutexStd { + pub torrents: SkipMap, } -impl CrossbeamSkipList { +impl TorrentsSkipMapMutexStd { /// Upsert a peer into the swarm of a torrent. /// /// Optionally, it can also preset the number of downloads of the torrent diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index ae0066b25..066c6d5c3 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -8,15 +8,14 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::PersistentTorrents; -use torrust_tracker_torrent_repository::repository::skip_map_mutex_std::CrossbeamSkipList; -use torrust_tracker_torrent_repository::EntrySingle; +use torrust_tracker_torrent_repository::{EntrySingle, TorrentsSkipMapMutexStd}; use crate::common::repo::Repo; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; #[fixture] fn skip_list_mutex_std() -> Repo { - Repo::SkipMapMutexStd(CrossbeamSkipList::default()) + Repo::SkipMapMutexStd(TorrentsSkipMapMutexStd::default()) } type Entries = Vec<(InfoHash, EntrySingle)>; From e87479e0ba34ce21089cd6934f593b824d871d50 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 30 Apr 2025 22:18:16 +0100 Subject: [PATCH 1037/1297] refactor: [#1491] extract mod torrent --- packages/torrent-repository/src/entry/mod.rs | 19 +------------------ .../torrent-repository/src/entry/torrent.rs | 17 +++++++++++++++++ packages/torrent-repository/src/lib.rs | 4 ++-- 3 files changed, 20 insertions(+), 20 deletions(-) create mode 100644 packages/torrent-repository/src/entry/torrent.rs diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index 4b1201730..610750bb3 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -1,20 +1,3 @@ -use std::fmt::Debug; - -use self::peer_list::PeerList; - pub mod peer_list; pub mod single; - -/// A data structure containing all the information about a torrent in the tracker. -/// -/// This is the tracker entry for a given torrent and contains the swarm data, -/// that's the list of all the peers trying to download the same torrent. -/// The tracker keeps one entry like this for every torrent. -#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct Torrent { - /// A network of peers that are all trying to download the torrent associated to this entry - pub(crate) swarm: PeerList, - - /// The number of peers that have ever completed downloading the torrent associated to this entry - pub(crate) downloaded: u32, -} +pub mod torrent; diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs new file mode 100644 index 000000000..8b923d880 --- /dev/null +++ b/packages/torrent-repository/src/entry/torrent.rs @@ -0,0 +1,17 @@ +use std::fmt::Debug; + +use super::peer_list::PeerList; + +/// A data structure containing all the information about a torrent in the tracker. +/// +/// This is the tracker entry for a given torrent and contains the swarm data, +/// that's the list of all the peers trying to download the same torrent. +/// The tracker keeps one entry like this for every torrent. +#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Torrent { + /// A network of peers that are all trying to download the torrent associated to this entry + pub(crate) swarm: PeerList, + + /// The number of peers that have ever completed downloading the torrent associated to this entry + pub(crate) downloaded: u32, +} diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 846545387..75a711198 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -6,8 +6,8 @@ pub mod entry; pub mod repository; // Repo Entries -pub type EntrySingle = entry::Torrent; -pub type EntryMutexStd = Arc>; +pub type EntrySingle = entry::torrent::Torrent; +pub type EntryMutexStd = Arc>; // Repository pub type TorrentsSkipMapMutexStd = repository::skip_map_mutex_std::TorrentsSkipMapMutexStd; From f868b04a4d5cebb926e850cb95f124df31d55cf4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 30 Apr 2025 22:22:22 +0100 Subject: [PATCH 1038/1297] refactor: [#1491] put implementation and type in the same module --- packages/torrent-repository/src/entry/mod.rs | 1 - .../torrent-repository/src/entry/single.rs | 86 ------------------- .../torrent-repository/src/entry/torrent.rs | 84 ++++++++++++++++++ 3 files changed, 84 insertions(+), 87 deletions(-) delete mode 100644 packages/torrent-repository/src/entry/single.rs diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index 610750bb3..785672be5 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -1,3 +1,2 @@ pub mod peer_list; -pub mod single; pub mod torrent; diff --git a/packages/torrent-repository/src/entry/single.rs b/packages/torrent-repository/src/entry/single.rs deleted file mode 100644 index 44f1012e1..000000000 --- a/packages/torrent-repository/src/entry/single.rs +++ /dev/null @@ -1,86 +0,0 @@ -use std::net::SocketAddr; -use std::sync::Arc; - -use aquatic_udp_protocol::AnnounceEvent; -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::peer::{self}; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::DurationSinceUnixEpoch; - -use crate::EntrySingle; - -impl EntrySingle { - #[allow(clippy::cast_possible_truncation)] - #[must_use] - pub fn get_swarm_metadata(&self) -> SwarmMetadata { - let (seeders, leechers) = self.swarm.seeders_and_leechers(); - - SwarmMetadata { - downloaded: self.downloaded, - complete: seeders as u32, - incomplete: leechers as u32, - } - } - - #[must_use] - pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { - if policy.persistent_torrent_completed_stat && self.downloaded > 0 { - return true; - } - - if policy.remove_peerless_torrents && self.swarm.is_empty() { - return false; - } - - true - } - - #[must_use] - pub fn peers_is_empty(&self) -> bool { - self.swarm.is_empty() - } - - #[must_use] - pub fn get_peers_len(&self) -> usize { - self.swarm.len() - } - - #[must_use] - pub fn get_peers(&self, limit: Option) -> Vec> { - self.swarm.get_all(limit) - } - - #[must_use] - pub fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { - self.swarm.get_peers_excluding_addr(client, limit) - } - - pub fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { - let mut number_of_downloads_increased: bool = false; - - match peer::ReadInfo::get_event(peer) { - AnnounceEvent::Stopped => { - drop(self.swarm.remove(&peer::ReadInfo::get_id(peer))); - } - AnnounceEvent::Completed => { - let previous = self.swarm.upsert(Arc::new(*peer)); - // Don't count if peer was not previously known and not already completed. - if previous.is_some_and(|p| p.event != AnnounceEvent::Completed) { - self.downloaded += 1; - number_of_downloads_increased = true; - } - } - _ => { - // `Started` event (first announced event) or - // `None` event (announcements done at regular intervals). - drop(self.swarm.upsert(Arc::new(*peer))); - } - } - - number_of_downloads_increased - } - - pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { - self.swarm.remove_inactive_peers(current_cutoff); - } -} diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs index 8b923d880..8d09a140f 100644 --- a/packages/torrent-repository/src/entry/torrent.rs +++ b/packages/torrent-repository/src/entry/torrent.rs @@ -1,4 +1,12 @@ use std::fmt::Debug; +use std::net::SocketAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::AnnounceEvent; +use torrust_tracker_configuration::TrackerPolicy; +use torrust_tracker_primitives::peer::{self}; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::peer_list::PeerList; @@ -15,3 +23,79 @@ pub struct Torrent { /// The number of peers that have ever completed downloading the torrent associated to this entry pub(crate) downloaded: u32, } + +impl Torrent { + #[allow(clippy::cast_possible_truncation)] + #[must_use] + pub fn get_swarm_metadata(&self) -> SwarmMetadata { + let (seeders, leechers) = self.swarm.seeders_and_leechers(); + + SwarmMetadata { + downloaded: self.downloaded, + complete: seeders as u32, + incomplete: leechers as u32, + } + } + + #[must_use] + pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + if policy.persistent_torrent_completed_stat && self.downloaded > 0 { + return true; + } + + if policy.remove_peerless_torrents && self.swarm.is_empty() { + return false; + } + + true + } + + #[must_use] + pub fn peers_is_empty(&self) -> bool { + self.swarm.is_empty() + } + + #[must_use] + pub fn get_peers_len(&self) -> usize { + self.swarm.len() + } + + #[must_use] + pub fn get_peers(&self, limit: Option) -> Vec> { + self.swarm.get_all(limit) + } + + #[must_use] + pub fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + self.swarm.get_peers_excluding_addr(client, limit) + } + + pub fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { + let mut number_of_downloads_increased: bool = false; + + match peer::ReadInfo::get_event(peer) { + AnnounceEvent::Stopped => { + drop(self.swarm.remove(&peer::ReadInfo::get_id(peer))); + } + AnnounceEvent::Completed => { + let previous = self.swarm.upsert(Arc::new(*peer)); + // Don't count if peer was not previously known and not already completed. + if previous.is_some_and(|p| p.event != AnnounceEvent::Completed) { + self.downloaded += 1; + number_of_downloads_increased = true; + } + } + _ => { + // `Started` event (first announced event) or + // `None` event (announcements done at regular intervals). + drop(self.swarm.upsert(Arc::new(*peer))); + } + } + + number_of_downloads_increased + } + + pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + self.swarm.remove_inactive_peers(current_cutoff); + } +} From 0acfc8f55152aa62b186e6ced2459204211a901f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 30 Apr 2025 22:28:11 +0100 Subject: [PATCH 1039/1297] refactor: [#1491] remove unneeded type alias EntrySingle --- packages/torrent-repository/src/lib.rs | 3 +-- .../src/repository/skip_map_mutex_std.rs | 7 ++--- .../torrent-repository/tests/common/repo.rs | 11 ++++---- .../tests/common/torrent.rs | 4 +-- .../torrent-repository/tests/entry/mod.rs | 4 +-- .../tests/repository/mod.rs | 27 ++++++++++--------- 6 files changed, 29 insertions(+), 27 deletions(-) diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 75a711198..3948261fe 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -5,8 +5,7 @@ use torrust_tracker_clock::clock; pub mod entry; pub mod repository; -// Repo Entries -pub type EntrySingle = entry::torrent::Torrent; +// Repo Entry pub type EntryMutexStd = Arc>; // Repository diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs index fb287b0f1..117c2cff9 100644 --- a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository/src/repository/skip_map_mutex_std.rs @@ -6,7 +6,8 @@ use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMe use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use crate::entry::peer_list::PeerList; -use crate::{EntryMutexStd, EntrySingle}; +use crate::entry::torrent::Torrent; +use crate::EntryMutexStd; #[derive(Default, Debug)] pub struct TorrentsSkipMapMutexStd { @@ -49,7 +50,7 @@ impl TorrentsSkipMapMutexStd { } else { let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { EntryMutexStd::new( - EntrySingle { + Torrent { swarm: PeerList::default(), downloaded: number_of_downloads, } @@ -130,7 +131,7 @@ impl TorrentsSkipMapMutexStd { } let entry = EntryMutexStd::new( - EntrySingle { + Torrent { swarm: PeerList::default(), downloaded: *completed, } diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 41df77bf9..5dc38003c 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -5,7 +5,8 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use torrust_tracker_torrent_repository::{EntrySingle, TorrentsSkipMapMutexStd}; +use torrust_tracker_torrent_repository::entry::torrent::Torrent; +use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; #[derive(Debug)] pub(crate) enum Repo { @@ -30,7 +31,7 @@ impl Repo { } } - pub(crate) fn get(&self, key: &InfoHash) -> Option { + pub(crate) fn get(&self, key: &InfoHash) -> Option { match self { Repo::SkipMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), } @@ -42,7 +43,7 @@ impl Repo { } } - pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntrySingle)> { + pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, Torrent)> { match self { Repo::SkipMapMutexStd(repo) => repo .get_paginated(pagination) @@ -58,7 +59,7 @@ impl Repo { } } - pub(crate) fn remove(&self, key: &InfoHash) -> Option { + pub(crate) fn remove(&self, key: &InfoHash) -> Option { match self { Repo::SkipMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), } @@ -76,7 +77,7 @@ impl Repo { } } - pub(crate) fn insert(&self, info_hash: &InfoHash, torrent: EntrySingle) -> Option { + pub(crate) fn insert(&self, info_hash: &InfoHash, torrent: Torrent) -> Option { match self { Repo::SkipMapMutexStd(repo) => { repo.torrents.insert(*info_hash, Arc::new(Mutex::new(torrent))); diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index 84ea79eef..4ef202431 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -4,11 +4,11 @@ use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; -use torrust_tracker_torrent_repository::{EntryMutexStd, EntrySingle}; +use torrust_tracker_torrent_repository::{entry, EntryMutexStd}; #[derive(Debug, Clone)] pub(crate) enum Torrent { - Single(EntrySingle), + Single(entry::torrent::Torrent), MutexStd(EntryMutexStd), } diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index 0fb8e8d88..9d01354ef 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -9,7 +9,7 @@ use torrust_tracker_clock::clock::{self, Time as _}; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_torrent_repository::{EntryMutexStd, EntrySingle}; +use torrust_tracker_torrent_repository::{entry, EntryMutexStd}; use crate::common::torrent::Torrent; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; @@ -17,7 +17,7 @@ use crate::CurrentClock; #[fixture] fn single() -> Torrent { - Torrent::Single(EntrySingle::default()) + Torrent::Single(entry::torrent::Torrent::default()) } #[fixture] fn mutex_std() -> Torrent { diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 066c6d5c3..55dbd6cc7 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -8,7 +8,8 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::PersistentTorrents; -use torrust_tracker_torrent_repository::{EntrySingle, TorrentsSkipMapMutexStd}; +use torrust_tracker_torrent_repository::entry::torrent::Torrent; +use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; use crate::common::repo::Repo; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; @@ -18,7 +19,7 @@ fn skip_list_mutex_std() -> Repo { Repo::SkipMapMutexStd(TorrentsSkipMapMutexStd::default()) } -type Entries = Vec<(InfoHash, EntrySingle)>; +type Entries = Vec<(InfoHash, Torrent)>; #[fixture] fn empty() -> Entries { @@ -27,26 +28,26 @@ fn empty() -> Entries { #[fixture] fn default() -> Entries { - vec![(InfoHash::default(), EntrySingle::default())] + vec![(InfoHash::default(), Torrent::default())] } #[fixture] fn started() -> Entries { - let mut torrent = EntrySingle::default(); + let mut torrent = Torrent::default(); torrent.upsert_peer(&a_started_peer(1)); vec![(InfoHash::default(), torrent)] } #[fixture] fn completed() -> Entries { - let mut torrent = EntrySingle::default(); + let mut torrent = Torrent::default(); torrent.upsert_peer(&a_completed_peer(2)); vec![(InfoHash::default(), torrent)] } #[fixture] fn downloaded() -> Entries { - let mut torrent = EntrySingle::default(); + let mut torrent = Torrent::default(); let mut peer = a_started_peer(3); torrent.upsert_peer(&peer); peer.event = AnnounceEvent::Completed; @@ -57,17 +58,17 @@ fn downloaded() -> Entries { #[fixture] fn three() -> Entries { - let mut started = EntrySingle::default(); + let mut started = Torrent::default(); let started_h = &mut DefaultHasher::default(); started.upsert_peer(&a_started_peer(1)); started.hash(started_h); - let mut completed = EntrySingle::default(); + let mut completed = Torrent::default(); let completed_h = &mut DefaultHasher::default(); completed.upsert_peer(&a_completed_peer(2)); completed.hash(completed_h); - let mut downloaded = EntrySingle::default(); + let mut downloaded = Torrent::default(); let downloaded_h = &mut DefaultHasher::default(); let mut downloaded_peer = a_started_peer(3); downloaded.upsert_peer(&downloaded_peer); @@ -85,10 +86,10 @@ fn three() -> Entries { #[fixture] fn many_out_of_order() -> Entries { - let mut entries: HashSet<(InfoHash, EntrySingle)> = HashSet::default(); + let mut entries: HashSet<(InfoHash, Torrent)> = HashSet::default(); for i in 0..408 { - let mut entry = EntrySingle::default(); + let mut entry = Torrent::default(); entry.upsert_peer(&a_started_peer(i)); entries.insert((InfoHash::from(&i), entry)); @@ -100,10 +101,10 @@ fn many_out_of_order() -> Entries { #[fixture] fn many_hashed_in_order() -> Entries { - let mut entries: BTreeMap = BTreeMap::default(); + let mut entries: BTreeMap = BTreeMap::default(); for i in 0..408 { - let mut entry = EntrySingle::default(); + let mut entry = Torrent::default(); entry.upsert_peer(&a_started_peer(i)); let hash: &mut DefaultHasher = &mut DefaultHasher::default(); From 2b0727e0925d9ee35bed8e5f297eaa38c068dda5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 May 2025 12:41:34 +0100 Subject: [PATCH 1040/1297] refactor: [#1491] reorganize repository module --- packages/torrent-repository/src/lib.rs | 2 +- .../src/{repository/skip_map_mutex_std.rs => repository.rs} | 0 packages/torrent-repository/src/repository/mod.rs | 1 - 3 files changed, 1 insertion(+), 2 deletions(-) rename packages/torrent-repository/src/{repository/skip_map_mutex_std.rs => repository.rs} (100%) delete mode 100644 packages/torrent-repository/src/repository/mod.rs diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 3948261fe..87f763ebb 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -9,7 +9,7 @@ pub mod repository; pub type EntryMutexStd = Arc>; // Repository -pub type TorrentsSkipMapMutexStd = repository::skip_map_mutex_std::TorrentsSkipMapMutexStd; +pub type TorrentsSkipMapMutexStd = repository::TorrentsSkipMapMutexStd; /// This code needs to be copied into each crate. /// Working version, for production. diff --git a/packages/torrent-repository/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository/src/repository.rs similarity index 100% rename from packages/torrent-repository/src/repository/skip_map_mutex_std.rs rename to packages/torrent-repository/src/repository.rs diff --git a/packages/torrent-repository/src/repository/mod.rs b/packages/torrent-repository/src/repository/mod.rs deleted file mode 100644 index 3b8259f9d..000000000 --- a/packages/torrent-repository/src/repository/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod skip_map_mutex_std; From f106c01203d6c1260d33759ab2d045cc8cb7ebe3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 May 2025 12:54:43 +0100 Subject: [PATCH 1041/1297] refactor: [#1491] move type alias to torrent-repository pkg --- packages/torrent-repository/src/lib.rs | 14 ++++++++++---- packages/torrent-repository/tests/common/repo.rs | 4 ++-- .../torrent-repository/tests/common/torrent.rs | 4 ++-- packages/torrent-repository/tests/entry/mod.rs | 4 ++-- .../torrent-repository/tests/repository/mod.rs | 4 ++-- packages/tracker-core/src/torrent/mod.rs | 13 ------------- .../src/torrent/repository/in_memory.rs | 14 ++++++-------- 7 files changed, 24 insertions(+), 33 deletions(-) diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 87f763ebb..865d819e3 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,15 +1,21 @@ -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use torrust_tracker_clock::clock; pub mod entry; pub mod repository; -// Repo Entry -pub type EntryMutexStd = Arc>; +// Repo entry +pub type TorrentEntry = EntryMutexStd; // Repository -pub type TorrentsSkipMapMutexStd = repository::TorrentsSkipMapMutexStd; +pub type Torrents = TorrentsSkipMapMutexStd; + +// The internal type of the entry +pub(crate) type EntryMutexStd = Arc>; + +// The internal type of the repository +pub(crate) type TorrentsSkipMapMutexStd = repository::TorrentsSkipMapMutexStd; /// This code needs to be copied into each crate. /// Working version, for production. diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 5dc38003c..357b39776 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -6,11 +6,11 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use torrust_tracker_torrent_repository::entry::torrent::Torrent; -use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; +use torrust_tracker_torrent_repository::Torrents; #[derive(Debug)] pub(crate) enum Repo { - SkipMapMutexStd(TorrentsSkipMapMutexStd), + SkipMapMutexStd(Torrents), } impl Repo { diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index 4ef202431..1cca7740d 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -4,12 +4,12 @@ use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; -use torrust_tracker_torrent_repository::{entry, EntryMutexStd}; +use torrust_tracker_torrent_repository::{entry, TorrentEntry}; #[derive(Debug, Clone)] pub(crate) enum Torrent { Single(entry::torrent::Torrent), - MutexStd(EntryMutexStd), + MutexStd(TorrentEntry), } impl Torrent { diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index 9d01354ef..e04bd004d 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -9,7 +9,7 @@ use torrust_tracker_clock::clock::{self, Time as _}; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_torrent_repository::{entry, EntryMutexStd}; +use torrust_tracker_torrent_repository::{entry, TorrentEntry}; use crate::common::torrent::Torrent; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; @@ -21,7 +21,7 @@ fn single() -> Torrent { } #[fixture] fn mutex_std() -> Torrent { - Torrent::MutexStd(EntryMutexStd::default()) + Torrent::MutexStd(TorrentEntry::default()) } #[fixture] diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 55dbd6cc7..d997cfd7c 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -9,14 +9,14 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::PersistentTorrents; use torrust_tracker_torrent_repository::entry::torrent::Torrent; -use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; +use torrust_tracker_torrent_repository::Torrents; use crate::common::repo::Repo; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; #[fixture] fn skip_list_mutex_std() -> Repo { - Repo::SkipMapMutexStd(TorrentsSkipMapMutexStd::default()) + Repo::SkipMapMutexStd(Torrents::default()) } type Entries = Vec<(InfoHash, Torrent)>; diff --git a/packages/tracker-core/src/torrent/mod.rs b/packages/tracker-core/src/torrent/mod.rs index 8ee8fa6d3..01d33b893 100644 --- a/packages/tracker-core/src/torrent/mod.rs +++ b/packages/tracker-core/src/torrent/mod.rs @@ -166,16 +166,3 @@ pub mod manager; pub mod repository; pub mod services; - -#[cfg(test)] -use torrust_tracker_torrent_repository::EntryMutexStd; -use torrust_tracker_torrent_repository::TorrentsSkipMapMutexStd; - -/// Alias for the primary torrent collection type, implemented as a skip map -/// wrapped in a mutex. This type is used internally by the tracker to manage -/// and access torrent entries. -pub(crate) type Torrents = TorrentsSkipMapMutexStd; - -/// Alias for a single torrent entry. -#[cfg(test)] -pub(crate) type TorrentEntry = EntryMutexStd; diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 746de190f..be758f990 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -7,9 +7,7 @@ use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use torrust_tracker_torrent_repository::EntryMutexStd; - -use crate::torrent::Torrents; +use torrust_tracker_torrent_repository::{TorrentEntry, Torrents}; /// In-memory repository for torrent entries. /// @@ -66,7 +64,7 @@ impl InMemoryTorrentRepository { /// An `Option` containing the removed torrent entry if it existed. #[cfg(test)] #[must_use] - pub(crate) fn remove(&self, key: &InfoHash) -> Option { + pub(crate) fn remove(&self, key: &InfoHash) -> Option { self.torrents.remove(key) } @@ -106,7 +104,7 @@ impl InMemoryTorrentRepository { /// /// An `Option` containing the torrent entry if found. #[must_use] - pub(crate) fn get(&self, key: &InfoHash) -> Option { + pub(crate) fn get(&self, key: &InfoHash) -> Option { self.torrents.get(key) } @@ -122,9 +120,9 @@ impl InMemoryTorrentRepository { /// /// # Returns /// - /// A vector of `(InfoHash, EntryMutexStd)` tuples. + /// A vector of `(InfoHash, TorrentEntry)` tuples. #[must_use] - pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, TorrentEntry)> { self.torrents.get_paginated(pagination) } @@ -512,10 +510,10 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use torrust_tracker_torrent_repository::TorrentEntry; use crate::test_helpers::tests::{sample_info_hash, sample_peer}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::torrent::TorrentEntry; /// `TorrentEntry` data is not directly accessible. It's only /// accessible through the trait methods. We need this temporary From 71aa8d039488004504b7e45034cf4e9bc35b38ec Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 May 2025 17:27:37 +0100 Subject: [PATCH 1042/1297] fix: [#1491] deadlock running tests I don't know why it was not happening before. The previous changes only: - Remove types aliases. - Remove generics. - Remove unused traits. However the concrete type for the repository should be the same after monomorphization. --- Cargo.lock | 1 + packages/torrent-repository/Cargo.toml | 1 + packages/torrent-repository/src/repository.rs | 12 ++++----- .../src/torrent/repository/in_memory.rs | 25 ++++++++----------- packages/tracker-core/src/torrent/services.rs | 10 +++++--- 5 files changed, 25 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index db6838e66..c301879f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4846,6 +4846,7 @@ dependencies = [ "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-primitives", + "tracing", ] [[package]] diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 6fc5f483b..0a4fe5261 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -23,6 +23,7 @@ tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tracing = "0" [dev-dependencies] async-std = { version = "1", features = ["attributes", "tokio1"] } diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index 117c2cff9..c08adbfae 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -42,12 +42,16 @@ impl TorrentsSkipMapMutexStd { opt_persistent_torrent: Option, ) -> bool { if let Some(existing_entry) = self.torrents.get(info_hash) { + tracing::debug!("Torrent already exists: {:?}", info_hash); + existing_entry .value() .lock() .expect("can't acquire lock for torrent entry") .upsert_peer(peer) } else { + tracing::debug!("Inserting new torrent: {:?}", info_hash); + let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { EntryMutexStd::new( Torrent { @@ -62,13 +66,9 @@ impl TorrentsSkipMapMutexStd { let inserted_entry = self.torrents.get_or_insert(*info_hash, new_entry); - let number_of_downloads_increased = inserted_entry - .value() - .lock() - .expect("can't acquire lock for torrent entry") - .upsert_peer(peer); + let mut torrent_guard = inserted_entry.value().lock().expect("can't acquire lock for torrent entry"); - number_of_downloads_increased + torrent_guard.upsert_peer(peer) } } diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index be758f990..d12919da8 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -528,20 +528,17 @@ mod tests { #[allow(clippy::from_over_into)] impl Into for TorrentEntry { fn into(self) -> TorrentEntryInfo { - TorrentEntryInfo { - swarm_metadata: self - .lock() - .expect("can't acquire lock for torrent entry") - .get_swarm_metadata(), - peers: self - .lock() - .expect("can't acquire lock for torrent entry") - .get_peers(None) - .iter() - .map(|peer| *peer.clone()) - .collect(), - number_of_peers: self.lock().expect("can't acquire lock for torrent entry").get_peers_len(), - } + let torrent_guard = self.lock().expect("can't acquire lock for torrent entry"); + + let torrent_entry_info = TorrentEntryInfo { + swarm_metadata: torrent_guard.get_swarm_metadata(), + peers: torrent_guard.get_peers(None).iter().map(|peer| *peer.clone()).collect(), + number_of_peers: torrent_guard.get_peers_len(), + }; + + drop(torrent_guard); + + torrent_entry_info } } diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index 2bf4bba71..30055b150 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -190,10 +190,12 @@ pub fn get_torrents(in_memory_torrent_repository: &Arc = vec![]; for info_hash in info_hashes { - if let Some(stats) = in_memory_torrent_repository - .get(info_hash) - .map(|t| t.lock().expect("can't acquire lock for torrent entry").get_swarm_metadata()) - { + if let Some(stats) = in_memory_torrent_repository.get(info_hash).map(|torrent_entry| { + torrent_entry + .lock() + .expect("can't acquire lock for torrent entry") + .get_swarm_metadata() + }) { basic_infos.push(BasicInfo { info_hash: *info_hash, seeders: u64::from(stats.complete), From 9be7c6857b5bc7d7e430c046632817ab96801d90 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 May 2025 18:21:28 +0100 Subject: [PATCH 1043/1297] refactor: [#1491] remove redundant type aliases --- packages/torrent-repository/src/entry/mod.rs | 4 ++++ packages/torrent-repository/src/lib.rs | 19 ++++--------------- packages/torrent-repository/src/repository.rs | 16 ++++++++-------- 3 files changed, 16 insertions(+), 23 deletions(-) diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index 785672be5..5f8ccfcc5 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -1,2 +1,6 @@ pub mod peer_list; pub mod torrent; + +use std::sync::{Arc, Mutex}; + +pub type TorrentEntry = Arc>; diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 865d819e3..b96858b82 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,23 +1,12 @@ -use std::sync::{Arc, Mutex}; - -use torrust_tracker_clock::clock; - pub mod entry; pub mod repository; -// Repo entry -pub type TorrentEntry = EntryMutexStd; - -// Repository -pub type Torrents = TorrentsSkipMapMutexStd; - -// The internal type of the entry -pub(crate) type EntryMutexStd = Arc>; +use torrust_tracker_clock::clock; -// The internal type of the repository -pub(crate) type TorrentsSkipMapMutexStd = repository::TorrentsSkipMapMutexStd; +pub type TorrentEntry = entry::TorrentEntry; +pub type Torrent = entry::torrent::Torrent; +pub type Torrents = repository::TorrentsSkipMapMutexStd; -/// This code needs to be copied into each crate. /// Working version, for production. #[cfg(not(test))] #[allow(dead_code)] diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index c08adbfae..ad0520c0c 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -7,11 +7,11 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent use crate::entry::peer_list::PeerList; use crate::entry::torrent::Torrent; -use crate::EntryMutexStd; +use crate::TorrentEntry; #[derive(Default, Debug)] pub struct TorrentsSkipMapMutexStd { - pub torrents: SkipMap, + pub torrents: SkipMap, } impl TorrentsSkipMapMutexStd { @@ -53,7 +53,7 @@ impl TorrentsSkipMapMutexStd { tracing::debug!("Inserting new torrent: {:?}", info_hash); let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { - EntryMutexStd::new( + TorrentEntry::new( Torrent { swarm: PeerList::default(), downloaded: number_of_downloads, @@ -61,7 +61,7 @@ impl TorrentsSkipMapMutexStd { .into(), ) } else { - EntryMutexStd::default() + TorrentEntry::default() }; let inserted_entry = self.torrents.get_or_insert(*info_hash, new_entry); @@ -85,7 +85,7 @@ impl TorrentsSkipMapMutexStd { }) } - pub fn get(&self, key: &InfoHash) -> Option { + pub fn get(&self, key: &InfoHash) -> Option { let maybe_entry = self.torrents.get(key); maybe_entry.map(|entry| entry.value().clone()) } @@ -107,7 +107,7 @@ impl TorrentsSkipMapMutexStd { metrics } - pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, EntryMutexStd)> { + pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, TorrentEntry)> { match pagination { Some(pagination) => self .torrents @@ -130,7 +130,7 @@ impl TorrentsSkipMapMutexStd { continue; } - let entry = EntryMutexStd::new( + let entry = TorrentEntry::new( Torrent { swarm: PeerList::default(), downloaded: *completed, @@ -144,7 +144,7 @@ impl TorrentsSkipMapMutexStd { } } - pub fn remove(&self, key: &InfoHash) -> Option { + pub fn remove(&self, key: &InfoHash) -> Option { self.torrents.remove(key).map(|entry| entry.value().clone()) } From df005336859eda533808a9a4d4047499b6550e9a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 1 May 2025 18:32:13 +0100 Subject: [PATCH 1044/1297] refactor: [#1491] rename main types in torrent-repository pkg --- packages/torrent-repository/src/entry/mod.rs | 4 --- .../torrent-repository/src/entry/torrent.rs | 4 +-- packages/torrent-repository/src/lib.rs | 8 +++-- packages/torrent-repository/src/repository.rs | 26 ++++++++-------- .../torrent-repository/tests/common/repo.rs | 14 ++++----- .../tests/common/torrent.rs | 6 ++-- .../torrent-repository/tests/entry/mod.rs | 6 ++-- .../tests/repository/mod.rs | 30 +++++++++---------- .../src/torrent/repository/in_memory.rs | 14 ++++----- 9 files changed, 55 insertions(+), 57 deletions(-) diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index 5f8ccfcc5..785672be5 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -1,6 +1,2 @@ pub mod peer_list; pub mod torrent; - -use std::sync::{Arc, Mutex}; - -pub type TorrentEntry = Arc>; diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs index 8d09a140f..1cc0f7ba2 100644 --- a/packages/torrent-repository/src/entry/torrent.rs +++ b/packages/torrent-repository/src/entry/torrent.rs @@ -16,7 +16,7 @@ use super::peer_list::PeerList; /// that's the list of all the peers trying to download the same torrent. /// The tracker keeps one entry like this for every torrent. #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct Torrent { +pub struct TrackedTorrent { /// A network of peers that are all trying to download the torrent associated to this entry pub(crate) swarm: PeerList, @@ -24,7 +24,7 @@ pub struct Torrent { pub(crate) downloaded: u32, } -impl Torrent { +impl TrackedTorrent { #[allow(clippy::cast_possible_truncation)] #[must_use] pub fn get_swarm_metadata(&self) -> SwarmMetadata { diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index b96858b82..70ec23906 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,11 +1,13 @@ pub mod entry; pub mod repository; +use std::sync::{Arc, Mutex}; + use torrust_tracker_clock::clock; -pub type TorrentEntry = entry::TorrentEntry; -pub type Torrent = entry::torrent::Torrent; -pub type Torrents = repository::TorrentsSkipMapMutexStd; +pub type TorrentRepository = repository::TorrentRepository; +pub type TrackedTorrentHandle = Arc>; +pub type TrackedTorrent = entry::torrent::TrackedTorrent; /// Working version, for production. #[cfg(not(test))] diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index ad0520c0c..25163f4ec 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -6,15 +6,15 @@ use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMe use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use crate::entry::peer_list::PeerList; -use crate::entry::torrent::Torrent; -use crate::TorrentEntry; +use crate::entry::torrent::TrackedTorrent; +use crate::TrackedTorrentHandle; #[derive(Default, Debug)] -pub struct TorrentsSkipMapMutexStd { - pub torrents: SkipMap, +pub struct TorrentRepository { + pub torrents: SkipMap, } -impl TorrentsSkipMapMutexStd { +impl TorrentRepository { /// Upsert a peer into the swarm of a torrent. /// /// Optionally, it can also preset the number of downloads of the torrent @@ -53,15 +53,15 @@ impl TorrentsSkipMapMutexStd { tracing::debug!("Inserting new torrent: {:?}", info_hash); let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { - TorrentEntry::new( - Torrent { + TrackedTorrentHandle::new( + TrackedTorrent { swarm: PeerList::default(), downloaded: number_of_downloads, } .into(), ) } else { - TorrentEntry::default() + TrackedTorrentHandle::default() }; let inserted_entry = self.torrents.get_or_insert(*info_hash, new_entry); @@ -85,7 +85,7 @@ impl TorrentsSkipMapMutexStd { }) } - pub fn get(&self, key: &InfoHash) -> Option { + pub fn get(&self, key: &InfoHash) -> Option { let maybe_entry = self.torrents.get(key); maybe_entry.map(|entry| entry.value().clone()) } @@ -107,7 +107,7 @@ impl TorrentsSkipMapMutexStd { metrics } - pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, TorrentEntry)> { + pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, TrackedTorrentHandle)> { match pagination { Some(pagination) => self .torrents @@ -130,8 +130,8 @@ impl TorrentsSkipMapMutexStd { continue; } - let entry = TorrentEntry::new( - Torrent { + let entry = TrackedTorrentHandle::new( + TrackedTorrent { swarm: PeerList::default(), downloaded: *completed, } @@ -144,7 +144,7 @@ impl TorrentsSkipMapMutexStd { } } - pub fn remove(&self, key: &InfoHash) -> Option { + pub fn remove(&self, key: &InfoHash) -> Option { self.torrents.remove(key).map(|entry| entry.value().clone()) } diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 357b39776..0055f6bee 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -5,12 +5,12 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use torrust_tracker_torrent_repository::entry::torrent::Torrent; -use torrust_tracker_torrent_repository::Torrents; +use torrust_tracker_torrent_repository::entry::torrent::TrackedTorrent; +use torrust_tracker_torrent_repository::TorrentRepository; #[derive(Debug)] pub(crate) enum Repo { - SkipMapMutexStd(Torrents), + SkipMapMutexStd(TorrentRepository), } impl Repo { @@ -31,7 +31,7 @@ impl Repo { } } - pub(crate) fn get(&self, key: &InfoHash) -> Option { + pub(crate) fn get(&self, key: &InfoHash) -> Option { match self { Repo::SkipMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), } @@ -43,7 +43,7 @@ impl Repo { } } - pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, Torrent)> { + pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, TrackedTorrent)> { match self { Repo::SkipMapMutexStd(repo) => repo .get_paginated(pagination) @@ -59,7 +59,7 @@ impl Repo { } } - pub(crate) fn remove(&self, key: &InfoHash) -> Option { + pub(crate) fn remove(&self, key: &InfoHash) -> Option { match self { Repo::SkipMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), } @@ -77,7 +77,7 @@ impl Repo { } } - pub(crate) fn insert(&self, info_hash: &InfoHash, torrent: Torrent) -> Option { + pub(crate) fn insert(&self, info_hash: &InfoHash, torrent: TrackedTorrent) -> Option { match self { Repo::SkipMapMutexStd(repo) => { repo.torrents.insert(*info_hash, Arc::new(Mutex::new(torrent))); diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index 1cca7740d..9fdabd136 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -4,12 +4,12 @@ use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; -use torrust_tracker_torrent_repository::{entry, TorrentEntry}; +use torrust_tracker_torrent_repository::{entry, TrackedTorrentHandle}; #[derive(Debug, Clone)] pub(crate) enum Torrent { - Single(entry::torrent::Torrent), - MutexStd(TorrentEntry), + Single(entry::torrent::TrackedTorrent), + MutexStd(TrackedTorrentHandle), } impl Torrent { diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index e04bd004d..27bb5f238 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -9,7 +9,7 @@ use torrust_tracker_clock::clock::{self, Time as _}; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_torrent_repository::{entry, TorrentEntry}; +use torrust_tracker_torrent_repository::{entry, TrackedTorrentHandle}; use crate::common::torrent::Torrent; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; @@ -17,11 +17,11 @@ use crate::CurrentClock; #[fixture] fn single() -> Torrent { - Torrent::Single(entry::torrent::Torrent::default()) + Torrent::Single(entry::torrent::TrackedTorrent::default()) } #[fixture] fn mutex_std() -> Torrent { - Torrent::MutexStd(TorrentEntry::default()) + Torrent::MutexStd(TrackedTorrentHandle::default()) } #[fixture] diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index d997cfd7c..06ee1d622 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -8,18 +8,18 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::PersistentTorrents; -use torrust_tracker_torrent_repository::entry::torrent::Torrent; -use torrust_tracker_torrent_repository::Torrents; +use torrust_tracker_torrent_repository::entry::torrent::TrackedTorrent; +use torrust_tracker_torrent_repository::TorrentRepository; use crate::common::repo::Repo; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; #[fixture] fn skip_list_mutex_std() -> Repo { - Repo::SkipMapMutexStd(Torrents::default()) + Repo::SkipMapMutexStd(TorrentRepository::default()) } -type Entries = Vec<(InfoHash, Torrent)>; +type Entries = Vec<(InfoHash, TrackedTorrent)>; #[fixture] fn empty() -> Entries { @@ -28,26 +28,26 @@ fn empty() -> Entries { #[fixture] fn default() -> Entries { - vec![(InfoHash::default(), Torrent::default())] + vec![(InfoHash::default(), TrackedTorrent::default())] } #[fixture] fn started() -> Entries { - let mut torrent = Torrent::default(); + let mut torrent = TrackedTorrent::default(); torrent.upsert_peer(&a_started_peer(1)); vec![(InfoHash::default(), torrent)] } #[fixture] fn completed() -> Entries { - let mut torrent = Torrent::default(); + let mut torrent = TrackedTorrent::default(); torrent.upsert_peer(&a_completed_peer(2)); vec![(InfoHash::default(), torrent)] } #[fixture] fn downloaded() -> Entries { - let mut torrent = Torrent::default(); + let mut torrent = TrackedTorrent::default(); let mut peer = a_started_peer(3); torrent.upsert_peer(&peer); peer.event = AnnounceEvent::Completed; @@ -58,17 +58,17 @@ fn downloaded() -> Entries { #[fixture] fn three() -> Entries { - let mut started = Torrent::default(); + let mut started = TrackedTorrent::default(); let started_h = &mut DefaultHasher::default(); started.upsert_peer(&a_started_peer(1)); started.hash(started_h); - let mut completed = Torrent::default(); + let mut completed = TrackedTorrent::default(); let completed_h = &mut DefaultHasher::default(); completed.upsert_peer(&a_completed_peer(2)); completed.hash(completed_h); - let mut downloaded = Torrent::default(); + let mut downloaded = TrackedTorrent::default(); let downloaded_h = &mut DefaultHasher::default(); let mut downloaded_peer = a_started_peer(3); downloaded.upsert_peer(&downloaded_peer); @@ -86,10 +86,10 @@ fn three() -> Entries { #[fixture] fn many_out_of_order() -> Entries { - let mut entries: HashSet<(InfoHash, Torrent)> = HashSet::default(); + let mut entries: HashSet<(InfoHash, TrackedTorrent)> = HashSet::default(); for i in 0..408 { - let mut entry = Torrent::default(); + let mut entry = TrackedTorrent::default(); entry.upsert_peer(&a_started_peer(i)); entries.insert((InfoHash::from(&i), entry)); @@ -101,10 +101,10 @@ fn many_out_of_order() -> Entries { #[fixture] fn many_hashed_in_order() -> Entries { - let mut entries: BTreeMap = BTreeMap::default(); + let mut entries: BTreeMap = BTreeMap::default(); for i in 0..408 { - let mut entry = Torrent::default(); + let mut entry = TrackedTorrent::default(); entry.upsert_peer(&a_started_peer(i)); let hash: &mut DefaultHasher = &mut DefaultHasher::default(); diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index d12919da8..83715789c 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -7,7 +7,7 @@ use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use torrust_tracker_torrent_repository::{TorrentEntry, Torrents}; +use torrust_tracker_torrent_repository::{TorrentRepository, TrackedTorrentHandle}; /// In-memory repository for torrent entries. /// @@ -21,7 +21,7 @@ use torrust_tracker_torrent_repository::{TorrentEntry, Torrents}; #[derive(Debug, Default)] pub struct InMemoryTorrentRepository { /// The underlying in-memory data structure that stores torrent entries. - torrents: Arc, + torrents: Arc, } impl InMemoryTorrentRepository { @@ -64,7 +64,7 @@ impl InMemoryTorrentRepository { /// An `Option` containing the removed torrent entry if it existed. #[cfg(test)] #[must_use] - pub(crate) fn remove(&self, key: &InfoHash) -> Option { + pub(crate) fn remove(&self, key: &InfoHash) -> Option { self.torrents.remove(key) } @@ -104,7 +104,7 @@ impl InMemoryTorrentRepository { /// /// An `Option` containing the torrent entry if found. #[must_use] - pub(crate) fn get(&self, key: &InfoHash) -> Option { + pub(crate) fn get(&self, key: &InfoHash) -> Option { self.torrents.get(key) } @@ -122,7 +122,7 @@ impl InMemoryTorrentRepository { /// /// A vector of `(InfoHash, TorrentEntry)` tuples. #[must_use] - pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, TorrentEntry)> { + pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, TrackedTorrentHandle)> { self.torrents.get_paginated(pagination) } @@ -510,7 +510,7 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use torrust_tracker_torrent_repository::TorrentEntry; + use torrust_tracker_torrent_repository::TrackedTorrentHandle; use crate::test_helpers::tests::{sample_info_hash, sample_peer}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -526,7 +526,7 @@ mod tests { } #[allow(clippy::from_over_into)] - impl Into for TorrentEntry { + impl Into for TrackedTorrentHandle { fn into(self) -> TorrentEntryInfo { let torrent_guard = self.lock().expect("can't acquire lock for torrent entry"); From 21b18e4844a042269b6f2a2854c1b3b0ad07649d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 2 May 2025 11:22:01 +0100 Subject: [PATCH 1045/1297] refactor: [#1491] move functionality from InMemoryTorrentRepository to TorrentRepository InMemoryTorrentRepository is now a wrapper over TorrentRepository. It's planned to make the InMemoryTorrentRepository responsible for triggering events. --- Cargo.lock | 2 + packages/torrent-repository/Cargo.toml | 2 + packages/torrent-repository/src/lib.rs | 120 +++ packages/torrent-repository/src/repository.rs | 902 +++++++++++++++++- packages/tracker-core/src/announce_handler.rs | 2 +- packages/tracker-core/src/scrape_handler.rs | 2 +- packages/tracker-core/src/test_helpers.rs | 36 - .../src/torrent/repository/in_memory.rs | 709 +------------- 8 files changed, 994 insertions(+), 781 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c301879f2..02e674e95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4841,11 +4841,13 @@ dependencies = [ "bittorrent-primitives", "criterion", "crossbeam-skiplist", + "rand 0.8.5", "rstest", "tokio", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-primitives", + "torrust-tracker-test-helpers", "tracing", ] diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 0a4fe5261..e584fadf4 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -28,4 +28,6 @@ tracing = "0" [dev-dependencies] async-std = { version = "1", features = ["attributes", "tokio1"] } criterion = { version = "0", features = ["async_tokio"] } +rand = "0" rstest = "0" +torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 70ec23906..f2e2c643c 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -18,3 +18,123 @@ pub(crate) type CurrentClock = clock::Working; #[cfg(test)] #[allow(dead_code)] pub(crate) type CurrentClock = clock::Stopped; + +#[cfg(test)] +pub(crate) mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash_one() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// # Panics + /// + /// Will panic if the string representation of the info hash is not a valid info hash. + #[must_use] + pub fn sample_info_hash_alphabetically_ordered_after_sample_info_hash_one() -> InfoHash { + "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") + } + + /// Sample peer whose state is not relevant for the tests. + #[must_use] + pub fn sample_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + #[must_use] + pub fn sample_peer_one() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000001"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + #[must_use] + pub fn sample_peer_two() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000002"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8082), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + #[must_use] + pub fn seeder() -> Peer { + complete_peer() + } + + #[must_use] + pub fn leecher() -> Peer { + incomplete_peer() + } + + /// A peer that counts as `complete` is swarm metadata + /// IMPORTANT!: it only counts if the it has been announce at least once before + /// announcing the `AnnounceEvent::Completed` event. + #[must_use] + pub fn complete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } + } + + /// A peer that counts as `incomplete` is swarm metadata + #[must_use] + pub fn incomplete_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(1000), // Still bytes to download + event: AnnounceEvent::Started, + } + } +} diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index 25163f4ec..6c8a7c9b4 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use bittorrent_primitives::info_hash::InfoHash; use crossbeam_skiplist::SkipMap; use torrust_tracker_configuration::TrackerPolicy; @@ -47,7 +49,7 @@ impl TorrentRepository { existing_entry .value() .lock() - .expect("can't acquire lock for torrent entry") + .expect("can't acquire lock for tracked torrent handle") .upsert_peer(peer) } else { tracing::debug!("Inserting new torrent: {:?}", info_hash); @@ -66,47 +68,64 @@ impl TorrentRepository { let inserted_entry = self.torrents.get_or_insert(*info_hash, new_entry); - let mut torrent_guard = inserted_entry.value().lock().expect("can't acquire lock for torrent entry"); + let mut torrent_guard = inserted_entry + .value() + .lock() + .expect("can't acquire lock for tracked torrent handle"); torrent_guard.upsert_peer(peer) } } + /// Removes a torrent entry from the repository. + /// + /// # Returns + /// + /// An `Option` containing the removed torrent entry if it existed. + #[must_use] + pub fn remove(&self, key: &InfoHash) -> Option { + self.torrents.remove(key).map(|entry| entry.value().clone()) + } + + /// Removes inactive peers from all torrent entries. + /// + /// A peer is considered inactive if its last update timestamp is older than + /// the provided cutoff time. + /// /// # Panics /// /// This function panics if the lock for the entry cannot be obtained. - pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.torrents.get(info_hash).map(|entry| { + pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + for entry in &self.torrents { entry .value() .lock() - .expect("can't acquire lock for torrent entry") - .get_swarm_metadata() - }) + .expect("can't acquire lock for tracked torrent handle") + .remove_inactive_peers(current_cutoff); + } } + /// Retrieves a tracked torrent handle by its infohash. + /// + /// # Returns + /// + /// An `Option` containing the tracked torrent handle if found. + #[must_use] pub fn get(&self, key: &InfoHash) -> Option { let maybe_entry = self.torrents.get(key); maybe_entry.map(|entry| entry.value().clone()) } - /// # Panics + /// Retrieves a paginated list of tracked torrent handles. /// - /// This function panics if the lock for the entry cannot be obtained. - pub fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); - - for entry in &self.torrents { - let stats = entry.value().lock().expect("it should get a lock").get_swarm_metadata(); - metrics.total_complete += u64::from(stats.complete); - metrics.total_downloaded += u64::from(stats.downloaded); - metrics.total_incomplete += u64::from(stats.incomplete); - metrics.total_torrents += 1; - } - - metrics - } - + /// This method returns a vector of tuples, each containing an infohash and + /// its associated tracked torrent handle. The pagination parameters + /// (offset and limit) can be used to control the size of the result set. + /// + /// # Returns + /// + /// A vector of `(InfoHash, TorrentEntry)` tuples. + #[must_use] pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, TrackedTorrentHandle)> { match pagination { Some(pagination) => self @@ -124,6 +143,132 @@ impl TorrentRepository { } } + /// Retrieves swarm metadata for a given torrent. + /// + /// # Returns + /// + /// A `SwarmMetadata` struct containing the aggregated torrent data if found. + /// + /// # Panics + /// + /// This function panics if the lock for the entry cannot be obtained. + #[must_use] + pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrents.get(info_hash).map(|entry| { + entry + .value() + .lock() + .expect("can't acquire lock for tracked torrent handle") + .get_swarm_metadata() + }) + } + + /// Retrieves swarm metadata for a given torrent. + /// + /// # Returns + /// + /// A `SwarmMetadata` struct containing the aggregated torrent data if it's + /// found or a zeroed metadata struct if not. + #[must_use] + pub fn get_swarm_metadata_or_default(&self, info_hash: &InfoHash) -> SwarmMetadata { + match self.get_swarm_metadata(info_hash) { + Some(swarm_metadata) => swarm_metadata, + None => SwarmMetadata::zeroed(), + } + } + + /// Retrieves torrent peers for a given torrent and client, excluding the + /// requesting client. + /// + /// This method filters out the client making the request (based on its + /// network address) and returns up to a maximum number of peers, defined by + /// the greater of the provided limit or the global `TORRENT_PEERS_LIMIT`. + /// + /// # Returns + /// + /// A vector of peers (wrapped in `Arc`) representing the active peers for + /// the torrent, excluding the requesting client. + /// + /// # Panics + /// + /// This function panics if the lock for the torrent entry cannot be obtained. + #[must_use] + pub fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { + match self.get(info_hash) { + None => vec![], + Some(entry) => entry + .lock() + .expect("can't acquire lock for tracked torrent handle") + .get_peers_for_client(&peer.peer_addr, Some(limit)), + } + } + + /// Retrieves the list of peers for a given torrent. + /// + /// This method returns up to `TORRENT_PEERS_LIMIT` peers for the torrent + /// specified by the info-hash. + /// + /// # Returns + /// + /// A vector of peers (wrapped in `Arc`) representing the active peers for + /// the torrent. + /// + /// # Panics + /// + /// This function panics if the lock for the torrent entry cannot be obtained. + #[must_use] + pub fn get_torrent_peers(&self, info_hash: &InfoHash, limit: usize) -> Vec> { + match self.get(info_hash) { + None => vec![], + Some(entry) => entry + .lock() + .expect("can't acquire lock for tracked torrent handle") + .get_peers(Some(limit)), + } + } + + /// Removes torrent entries that have no active peers. + /// + /// Depending on the tracker policy, torrents without any peers may be + /// removed to conserve memory. + /// + /// # Panics + /// + /// This function panics if the lock for the entry cannot be obtained. + pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + for entry in &self.torrents { + if entry + .value() + .lock() + .expect("can't acquire lock for tracked torrent handle") + .meets_retaining_policy(policy) + { + continue; + } + + entry.remove(); + } + } + + /// Calculates and returns overall torrent metrics. + /// + /// The returned [`AggregateSwarmMetadata`] contains aggregate data such as + /// the total number of torrents, total complete (seeders), incomplete + /// (leechers), and downloaded counts. + /// + /// # Returns + /// + /// A [`AggregateSwarmMetadata`] struct with the aggregated metrics. + #[must_use] + pub fn get_torrents_metrics(&self) -> AggregateSwarmMetadata { + self.get_metrics() + } + + /// Imports persistent torrent data into the in-memory repository. + /// + /// This method takes a set of persisted torrent entries (e.g., from a + /// database) and imports them into the in-memory repository for immediate + /// access. pub fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { for (info_hash, completed) in persistent_torrents { if self.torrents.contains_key(info_hash) { @@ -144,38 +289,707 @@ impl TorrentRepository { } } - pub fn remove(&self, key: &InfoHash) -> Option { - self.torrents.remove(key).map(|entry| entry.value().clone()) - } - + /// Calculates and returns overall torrent metrics. + /// + /// The returned [`AggregateSwarmMetadata`] contains aggregate data such as + /// the total number of torrents, total complete (seeders), incomplete + /// (leechers), and downloaded counts. + /// + /// # Returns + /// + /// A [`AggregateSwarmMetadata`] struct with the aggregated metrics. + /// /// # Panics /// /// This function panics if the lock for the entry cannot be obtained. - pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + #[must_use] + pub fn get_metrics(&self) -> AggregateSwarmMetadata { + let mut metrics = AggregateSwarmMetadata::default(); + for entry in &self.torrents { - entry + let stats = entry .value() .lock() - .expect("can't acquire lock for torrent entry") - .remove_inactive_peers(current_cutoff); + .expect("can't acquire lock for tracked torrent handle") + .get_swarm_metadata(); + metrics.total_complete += u64::from(stats.complete); + metrics.total_downloaded += u64::from(stats.downloaded); + metrics.total_incomplete += u64::from(stats.incomplete); + metrics.total_torrents += 1; } + + metrics } +} - /// # Panics - /// - /// This function panics if the lock for the entry cannot be obtained. - pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - for entry in &self.torrents { - if entry - .value() - .lock() - .expect("can't acquire lock for torrent entry") - .meets_retaining_policy(policy) - { - continue; +#[cfg(test)] +mod tests { + + mod the_in_memory_torrent_repository { + + use aquatic_udp_protocol::PeerId; + + /// It generates a peer id from a number where the number is the last + /// part of the peer ID. For example, for `12` it returns + /// `-qB00000000000000012`. + fn numeric_peer_id(two_digits_value: i32) -> PeerId { + // Format idx as a string with leading zeros, ensuring it has exactly 2 digits + let idx_str = format!("{two_digits_value:02}"); + + // Create the base part of the peer ID. + let base = b"-qB00000000000000000"; + + // Concatenate the base with idx bytes, ensuring the total length is 20 bytes. + let mut peer_id_bytes = [0u8; 20]; + peer_id_bytes[..base.len()].copy_from_slice(base); + peer_id_bytes[base.len() - idx_str.len()..].copy_from_slice(idx_str.as_bytes()); + + PeerId(peer_id_bytes) + } + + // The `TorrentRepository` has these responsibilities: + // - To maintain the peer lists for each torrent. + // - To maintain the the torrent entries, which contains all the info about the + // torrents, including the peer lists. + // - To return the torrent entries. + // - To return the peer lists for a given torrent. + // - To return the torrent metrics. + // - To return the swarm metadata for a given torrent. + // - To handle the persistence of the torrent entries. + + mod maintaining_the_peer_lists { + + use std::sync::Arc; + + use crate::repository::TorrentRepository; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn it_should_add_the_first_peer_to_the_torrent_peer_list() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let info_hash = sample_info_hash(); + + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + + assert!(in_memory_torrent_repository.get(&info_hash).is_some()); } - entry.remove(); + #[tokio::test] + async fn it_should_allow_adding_the_same_peer_twice_to_the_torrent_peer_list() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let info_hash = sample_info_hash(); + + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + + assert!(in_memory_torrent_repository.get(&info_hash).is_some()); + } + } + + mod returning_peer_lists_for_a_torrent { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::repository::tests::the_in_memory_torrent_repository::numeric_peer_id; + use crate::repository::TorrentRepository; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn it_should_return_the_peers_for_a_given_torrent() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash, 74); + + assert_eq!(peers, vec![Arc::new(peer)]); + } + + #[tokio::test] + async fn it_should_return_an_empty_list_or_peers_for_a_non_existing_torrent() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let peers = in_memory_torrent_repository.get_torrent_peers(&sample_info_hash(), 74); + + assert!(peers.is_empty()); + } + + #[tokio::test] + async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let info_hash = sample_info_hash(); + + for idx in 1..=75 { + let peer = Peer { + peer_id: numeric_peer_id(idx), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + }; + + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + } + + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash, 74); + + assert_eq!(peers.len(), 74); + } + + mod excluding_the_client_peer { + + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; + use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::repository::tests::the_in_memory_torrent_repository::numeric_peer_id; + use crate::repository::TorrentRepository; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn it_should_return_an_empty_peer_list_for_a_non_existing_torrent() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let peers = + in_memory_torrent_repository.get_peers_for(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT); + + assert_eq!(peers, vec![]); + } + + #[tokio::test] + async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + + let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); + + assert_eq!(peers, vec![]); + } + + #[tokio::test] + async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let info_hash = sample_info_hash(); + + let excluded_peer = sample_peer(); + + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer, None); + + // Add 74 peers + for idx in 2..=75 { + let peer = Peer { + peer_id: numeric_peer_id(idx), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + }; + + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + } + + let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); + + assert_eq!(peers.len(), 74); + } + } + } + + mod maintaining_the_torrent_entries { + + use std::ops::Add; + use std::sync::Arc; + use std::time::Duration; + + use bittorrent_primitives::info_hash::InfoHash; + use torrust_tracker_configuration::TrackerPolicy; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::repository::TorrentRepository; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn it_should_remove_a_torrent_entry() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let info_hash = sample_info_hash(); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + + let _unused = in_memory_torrent_repository.remove(&info_hash); + + assert!(in_memory_torrent_repository.get(&info_hash).is_none()); + } + + #[tokio::test] + async fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let info_hash = sample_info_hash(); + let mut peer = sample_peer(); + peer.updated = DurationSinceUnixEpoch::new(0, 0); + + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + + // Cut off time is 1 second after the peer was updated + in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); + + assert!(!in_memory_torrent_repository + .get_torrent_peers(&info_hash, 74) + .contains(&Arc::new(peer))); + } + + fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + // Insert a sample peer for the torrent to force adding the torrent entry + let mut peer = sample_peer(); + peer.updated = DurationSinceUnixEpoch::new(0, 0); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(info_hash, &peer, None); + + // Remove the peer + in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); + + in_memory_torrent_repository + } + + #[tokio::test] + async fn it_should_remove_torrents_without_peers() { + let info_hash = sample_info_hash(); + + let in_memory_torrent_repository = initialize_repository_with_one_torrent_without_peers(&info_hash); + + let tracker_policy = TrackerPolicy { + remove_peerless_torrents: true, + ..Default::default() + }; + + in_memory_torrent_repository.remove_peerless_torrents(&tracker_policy); + + assert!(in_memory_torrent_repository.get(&info_hash).is_none()); + } + } + mod returning_torrent_entries { + + use std::sync::Arc; + + use torrust_tracker_primitives::peer::Peer; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::repository::TorrentRepository; + use crate::tests::{sample_info_hash, sample_peer}; + use crate::TrackedTorrentHandle; + + /// `TorrentEntry` data is not directly accessible. It's only + /// accessible through the trait methods. We need this temporary + /// DTO to write simple and more readable assertions. + #[derive(Debug, Clone, PartialEq)] + struct TorrentEntryInfo { + swarm_metadata: SwarmMetadata, + peers: Vec, + number_of_peers: usize, + } + + #[allow(clippy::from_over_into)] + impl Into for TrackedTorrentHandle { + fn into(self) -> TorrentEntryInfo { + let torrent_guard = self.lock().expect("can't acquire lock for tracked torrent handle"); + + let torrent_entry_info = TorrentEntryInfo { + swarm_metadata: torrent_guard.get_swarm_metadata(), + peers: torrent_guard.get_peers(None).iter().map(|peer| *peer.clone()).collect(), + number_of_peers: torrent_guard.get_peers_len(), + }; + + drop(torrent_guard); + + torrent_entry_info + } + } + + #[tokio::test] + async fn it_should_return_one_torrent_entry_by_infohash() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + + let torrent_entry = in_memory_torrent_repository.get(&info_hash).unwrap(); + + assert_eq!( + TorrentEntryInfo { + swarm_metadata: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + peers: vec!(peer), + number_of_peers: 1 + }, + torrent_entry.into() + ); + } + + mod it_should_return_many_torrent_entries { + use std::sync::Arc; + + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::repository::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; + use crate::repository::TorrentRepository; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn without_pagination() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + + let torrent_entries = in_memory_torrent_repository.get_paginated(None); + + assert_eq!(torrent_entries.len(), 1); + + let torrent_entry = torrent_entries.first().unwrap().1.clone(); + + assert_eq!( + TorrentEntryInfo { + swarm_metadata: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + peers: vec!(peer), + number_of_peers: 1 + }, + torrent_entry.into() + ); + } + + mod with_pagination { + use std::sync::Arc; + + use torrust_tracker_primitives::pagination::Pagination; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::repository::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; + use crate::repository::TorrentRepository; + use crate::tests::{ + sample_info_hash_alphabetically_ordered_after_sample_info_hash_one, sample_info_hash_one, + sample_peer_one, sample_peer_two, + }; + + #[tokio::test] + async fn it_should_return_the_first_page() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + // Insert one torrent entry + let info_hash_one = sample_info_hash_one(); + let peer_one = sample_peer_one(); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); + + // Insert another torrent entry + let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); + let peer_two = sample_peer_two(); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); + + // Get only the first page where page size is 1 + let torrent_entries = + in_memory_torrent_repository.get_paginated(Some(&Pagination { offset: 0, limit: 1 })); + + assert_eq!(torrent_entries.len(), 1); + + let torrent_entry = torrent_entries.first().unwrap().1.clone(); + + assert_eq!( + TorrentEntryInfo { + swarm_metadata: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + peers: vec!(peer_one), + number_of_peers: 1 + }, + torrent_entry.into() + ); + } + + #[tokio::test] + async fn it_should_return_the_second_page() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + // Insert one torrent entry + let info_hash_one = sample_info_hash_one(); + let peer_one = sample_peer_one(); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); + + // Insert another torrent entry + let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); + let peer_two = sample_peer_two(); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); + + // Get only the first page where page size is 1 + let torrent_entries = + in_memory_torrent_repository.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); + + assert_eq!(torrent_entries.len(), 1); + + let torrent_entry = torrent_entries.first().unwrap().1.clone(); + + assert_eq!( + TorrentEntryInfo { + swarm_metadata: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + peers: vec!(peer_two), + number_of_peers: 1 + }, + torrent_entry.into() + ); + } + + #[tokio::test] + async fn it_should_allow_changing_the_page_size() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + // Insert one torrent entry + let info_hash_one = sample_info_hash_one(); + let peer_one = sample_peer_one(); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); + + // Insert another torrent entry + let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); + let peer_two = sample_peer_two(); + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); + + // Get only the first page where page size is 1 + let torrent_entries = + in_memory_torrent_repository.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); + + assert_eq!(torrent_entries.len(), 1); + } + } + } + } + + mod returning_aggregate_swarm_metadata { + + use std::sync::Arc; + + use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; + use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; + + use crate::repository::TorrentRepository; + use crate::tests::{complete_peer, leecher, sample_info_hash, seeder}; + + // todo: refactor to use test parametrization + + #[tokio::test] + async fn it_should_get_empty_aggregate_swarm_metadata_when_there_are_no_torrents() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); + + assert_eq!( + aggregate_swarm_metadata, + AggregateSwarmMetadata { + total_complete: 0, + total_downloaded: 0, + total_incomplete: 0, + total_torrents: 0 + } + ); + } + + #[tokio::test] + async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_leecher() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher(), None); + + let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); + + assert_eq!( + aggregate_swarm_metadata, + AggregateSwarmMetadata { + total_complete: 0, + total_downloaded: 0, + total_incomplete: 1, + total_torrents: 1, + } + ); + } + + #[tokio::test] + async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_seeder() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &seeder(), None); + + let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); + + assert_eq!( + aggregate_swarm_metadata, + AggregateSwarmMetadata { + total_complete: 1, + total_downloaded: 0, + total_incomplete: 0, + total_torrents: 1, + } + ); + } + + #[tokio::test] + async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_completed_peer() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer(), None); + + let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); + + assert_eq!( + aggregate_swarm_metadata, + AggregateSwarmMetadata { + total_complete: 1, + total_downloaded: 0, + total_incomplete: 0, + total_torrents: 1, + } + ); + } + + #[tokio::test] + async fn it_should_return_the_aggregate_swarm_metadata_when_there_are_multiple_torrents() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let start_time = std::time::Instant::now(); + for i in 0..1_000_000 { + let _number_of_downloads_increased = + in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher(), None); + } + let result_a = start_time.elapsed(); + + let start_time = std::time::Instant::now(); + let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); + let result_b = start_time.elapsed(); + + assert_eq!( + (aggregate_swarm_metadata), + (AggregateSwarmMetadata { + total_complete: 0, + total_downloaded: 0, + total_incomplete: 1_000_000, + total_torrents: 1_000_000, + }), + "{result_a:?} {result_b:?}" + ); + } + } + + mod returning_swarm_metadata { + + use std::sync::Arc; + + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + + use crate::repository::TorrentRepository; + use crate::tests::{leecher, sample_info_hash}; + + #[tokio::test] + async fn it_should_get_swarm_metadata_for_an_existing_torrent() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let infohash = sample_info_hash(); + + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&infohash, &leecher(), None); + + let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata_or_default(&infohash); + + assert_eq!( + swarm_metadata, + SwarmMetadata { + complete: 0, + downloaded: 0, + incomplete: 1, + } + ); + } + + #[tokio::test] + async fn it_should_return_zeroed_swarm_metadata_for_a_non_existing_torrent() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata_or_default(&sample_info_hash()); + + assert_eq!(swarm_metadata, SwarmMetadata::zeroed()); + } + } + + mod handling_persistence { + + use std::sync::Arc; + + use torrust_tracker_primitives::PersistentTorrents; + + use crate::repository::TorrentRepository; + use crate::tests::sample_info_hash; + + #[tokio::test] + async fn it_should_allow_importing_persisted_torrent_entries() { + let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + + let infohash = sample_info_hash(); + + let mut persistent_torrents = PersistentTorrents::default(); + + persistent_torrents.insert(infohash, 1); + + in_memory_torrent_repository.import_persistent(&persistent_torrents); + + let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata_or_default(&infohash); + + // Only the number of downloads is persisted. + assert_eq!(swarm_metadata.downloaded, 1); + } } } } diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index ac70c6f86..76f28aafd 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -188,7 +188,7 @@ impl AnnounceHandler { .in_memory_torrent_repository .get_peers_for(info_hash, peer, peers_wanted.limit()); - let swarm_metadata = self.in_memory_torrent_repository.get_swarm_metadata(info_hash); + let swarm_metadata = self.in_memory_torrent_repository.get_swarm_metadata_or_default(info_hash); AnnounceData { peers, diff --git a/packages/tracker-core/src/scrape_handler.rs b/packages/tracker-core/src/scrape_handler.rs index 93b25dea6..5d78c7d90 100644 --- a/packages/tracker-core/src/scrape_handler.rs +++ b/packages/tracker-core/src/scrape_handler.rs @@ -112,7 +112,7 @@ impl ScrapeHandler { for info_hash in info_hashes { let swarm_metadata = match self.whitelist_authorization.authorize(info_hash).await { - Ok(()) => self.in_memory_torrent_repository.get_swarm_metadata(info_hash), + Ok(()) => self.in_memory_torrent_repository.get_swarm_metadata_or_default(info_hash), Err(_) => SwarmMetadata::zeroed(), }; scrape_data.add_file(info_hash, swarm_metadata); diff --git a/packages/tracker-core/src/test_helpers.rs b/packages/tracker-core/src/test_helpers.rs index 79904dec2..0d7ca012f 100644 --- a/packages/tracker-core/src/test_helpers.rs +++ b/packages/tracker-core/src/test_helpers.rs @@ -64,16 +64,6 @@ pub(crate) mod tests { .expect("String should be a valid info hash") } - /// # Panics - /// - /// Will panic if the string representation of the info hash is not a valid info hash. - #[must_use] - pub fn sample_info_hash_alphabetically_ordered_after_sample_info_hash_one() -> InfoHash { - "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1" // DevSkim: ignore DS173237 - .parse::() - .expect("String should be a valid info hash") - } - /// Sample peer whose state is not relevant for the tests. #[must_use] pub fn sample_peer() -> Peer { @@ -88,32 +78,6 @@ pub(crate) mod tests { } } - #[must_use] - pub fn sample_peer_one() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000001"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8081), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - } - } - - #[must_use] - pub fn sample_peer_two() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000002"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8082), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - } - } - #[must_use] pub fn seeder() -> Peer { complete_peer() diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 83715789c..f622e909f 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -140,14 +140,8 @@ impl InMemoryTorrentRepository { /// /// A `SwarmMetadata` struct containing the aggregated torrent data. #[must_use] - pub(crate) fn get_swarm_metadata(&self, info_hash: &InfoHash) -> SwarmMetadata { - match self.torrents.get(info_hash) { - Some(torrent_entry) => torrent_entry - .lock() - .expect("can't acquire lock for torrent entry") - .get_swarm_metadata(), - None => SwarmMetadata::zeroed(), - } + pub(crate) fn get_swarm_metadata_or_default(&self, info_hash: &InfoHash) -> SwarmMetadata { + self.torrents.get_swarm_metadata_or_default(info_hash) } /// Retrieves torrent peers for a given torrent and client, excluding the @@ -169,13 +163,7 @@ impl InMemoryTorrentRepository { /// the torrent, excluding the requesting client. #[must_use] pub(crate) fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { - match self.torrents.get(info_hash) { - None => vec![], - Some(entry) => entry - .lock() - .expect("can't acquire lock for torrent entry") - .get_peers_for_client(&peer.peer_addr, Some(max(limit, TORRENT_PEERS_LIMIT))), - } + self.torrents.get_peers_for(info_hash, peer, max(limit, TORRENT_PEERS_LIMIT)) } /// Retrieves the list of peers for a given torrent. @@ -197,27 +185,22 @@ impl InMemoryTorrentRepository { /// This function panics if the lock for the torrent entry cannot be obtained. #[must_use] pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { - match self.torrents.get(info_hash) { - None => vec![], - Some(entry) => entry - .lock() - .expect("can't acquire lock for torrent entry") - .get_peers(Some(TORRENT_PEERS_LIMIT)), - } + // todo: pass the limit as an argument like `get_peers_for` + self.torrents.get_torrent_peers(info_hash, TORRENT_PEERS_LIMIT) } /// Calculates and returns overall torrent metrics. /// - /// The returned [`TorrentsMetrics`] contains aggregate data such as the - /// total number of torrents, total complete (seeders), incomplete (leechers), - /// and downloaded counts. + /// The returned [`AggregateSwarmMetadata`] contains aggregate data such as + /// the total number of torrents, total complete (seeders), incomplete + /// (leechers), and downloaded counts. /// /// # Returns /// - /// A [`TorrentsMetrics`] struct with the aggregated metrics. + /// A [`AggregateSwarmMetadata`] struct with the aggregated metrics. #[must_use] pub fn get_torrents_metrics(&self) -> AggregateSwarmMetadata { - self.torrents.get_metrics() + self.torrents.get_torrents_metrics() } /// Imports persistent torrent data into the in-memory repository. @@ -232,675 +215,3 @@ impl InMemoryTorrentRepository { self.torrents.import_persistent(persistent_torrents); } } - -#[cfg(test)] -mod tests { - - mod the_in_memory_torrent_repository { - - use aquatic_udp_protocol::PeerId; - - /// It generates a peer id from a number where the number is the last - /// part of the peer ID. For example, for `12` it returns - /// `-qB00000000000000012`. - fn numeric_peer_id(two_digits_value: i32) -> PeerId { - // Format idx as a string with leading zeros, ensuring it has exactly 2 digits - let idx_str = format!("{two_digits_value:02}"); - - // Create the base part of the peer ID. - let base = b"-qB00000000000000000"; - - // Concatenate the base with idx bytes, ensuring the total length is 20 bytes. - let mut peer_id_bytes = [0u8; 20]; - peer_id_bytes[..base.len()].copy_from_slice(base); - peer_id_bytes[base.len() - idx_str.len()..].copy_from_slice(idx_str.as_bytes()); - - PeerId(peer_id_bytes) - } - - // The `InMemoryTorrentRepository` has these responsibilities: - // - To maintain the peer lists for each torrent. - // - To maintain the the torrent entries, which contains all the info about the - // torrents, including the peer lists. - // - To return the torrent entries. - // - To return the peer lists for a given torrent. - // - To return the torrent metrics. - // - To return the swarm metadata for a given torrent. - // - To handle the persistence of the torrent entries. - - mod maintaining_the_peer_lists { - - use std::sync::Arc; - - use crate::test_helpers::tests::{sample_info_hash, sample_peer}; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - - #[tokio::test] - async fn it_should_add_the_first_peer_to_the_torrent_peer_list() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let info_hash = sample_info_hash(); - - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); - - assert!(in_memory_torrent_repository.get(&info_hash).is_some()); - } - - #[tokio::test] - async fn it_should_allow_adding_the_same_peer_twice_to_the_torrent_peer_list() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let info_hash = sample_info_hash(); - - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); - - assert!(in_memory_torrent_repository.get(&info_hash).is_some()); - } - } - - mod returning_peer_lists_for_a_torrent { - - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; - - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - use torrust_tracker_primitives::peer::Peer; - use torrust_tracker_primitives::DurationSinceUnixEpoch; - - use crate::test_helpers::tests::{sample_info_hash, sample_peer}; - use crate::torrent::repository::in_memory::tests::the_in_memory_torrent_repository::numeric_peer_id; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - - #[tokio::test] - async fn it_should_return_the_peers_for_a_given_torrent() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let info_hash = sample_info_hash(); - let peer = sample_peer(); - - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); - - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); - - assert_eq!(peers, vec![Arc::new(peer)]); - } - - #[tokio::test] - async fn it_should_return_an_empty_list_or_peers_for_a_non_existing_torrent() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let peers = in_memory_torrent_repository.get_torrent_peers(&sample_info_hash()); - - assert!(peers.is_empty()); - } - - #[tokio::test] - async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let info_hash = sample_info_hash(); - - for idx in 1..=75 { - let peer = Peer { - peer_id: numeric_peer_id(idx), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - }; - - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); - } - - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash); - - assert_eq!(peers.len(), 74); - } - - mod excluding_the_client_peer { - - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; - - use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; - use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; - use torrust_tracker_primitives::peer::Peer; - use torrust_tracker_primitives::DurationSinceUnixEpoch; - - use crate::test_helpers::tests::{sample_info_hash, sample_peer}; - use crate::torrent::repository::in_memory::tests::the_in_memory_torrent_repository::numeric_peer_id; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - - #[tokio::test] - async fn it_should_return_an_empty_peer_list_for_a_non_existing_torrent() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let peers = - in_memory_torrent_repository.get_peers_for(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT); - - assert_eq!(peers, vec![]); - } - - #[tokio::test] - async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let info_hash = sample_info_hash(); - let peer = sample_peer(); - - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); - - let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); - - assert_eq!(peers, vec![]); - } - - #[tokio::test] - async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let info_hash = sample_info_hash(); - - let excluded_peer = sample_peer(); - - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer, None); - - // Add 74 peers - for idx in 2..=75 { - let peer = Peer { - peer_id: numeric_peer_id(idx), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, idx.try_into().unwrap())), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - }; - - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); - } - - let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); - - assert_eq!(peers.len(), 74); - } - } - } - - mod maintaining_the_torrent_entries { - - use std::ops::Add; - use std::sync::Arc; - use std::time::Duration; - - use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_configuration::TrackerPolicy; - use torrust_tracker_primitives::DurationSinceUnixEpoch; - - use crate::test_helpers::tests::{sample_info_hash, sample_peer}; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - - #[tokio::test] - async fn it_should_remove_a_torrent_entry() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let info_hash = sample_info_hash(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); - - let _unused = in_memory_torrent_repository.remove(&info_hash); - - assert!(in_memory_torrent_repository.get(&info_hash).is_none()); - } - - #[tokio::test] - async fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let info_hash = sample_info_hash(); - let mut peer = sample_peer(); - peer.updated = DurationSinceUnixEpoch::new(0, 0); - - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); - - // Cut off time is 1 second after the peer was updated - in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); - - assert!(!in_memory_torrent_repository - .get_torrent_peers(&info_hash) - .contains(&Arc::new(peer))); - } - - fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - // Insert a sample peer for the torrent to force adding the torrent entry - let mut peer = sample_peer(); - peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(info_hash, &peer, None); - - // Remove the peer - in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); - - in_memory_torrent_repository - } - - #[tokio::test] - async fn it_should_remove_torrents_without_peers() { - let info_hash = sample_info_hash(); - - let in_memory_torrent_repository = initialize_repository_with_one_torrent_without_peers(&info_hash); - - let tracker_policy = TrackerPolicy { - remove_peerless_torrents: true, - ..Default::default() - }; - - in_memory_torrent_repository.remove_peerless_torrents(&tracker_policy); - - assert!(in_memory_torrent_repository.get(&info_hash).is_none()); - } - } - mod returning_torrent_entries { - - use std::sync::Arc; - - use torrust_tracker_primitives::peer::Peer; - use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use torrust_tracker_torrent_repository::TrackedTorrentHandle; - - use crate::test_helpers::tests::{sample_info_hash, sample_peer}; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - - /// `TorrentEntry` data is not directly accessible. It's only - /// accessible through the trait methods. We need this temporary - /// DTO to write simple and more readable assertions. - #[derive(Debug, Clone, PartialEq)] - struct TorrentEntryInfo { - swarm_metadata: SwarmMetadata, - peers: Vec, - number_of_peers: usize, - } - - #[allow(clippy::from_over_into)] - impl Into for TrackedTorrentHandle { - fn into(self) -> TorrentEntryInfo { - let torrent_guard = self.lock().expect("can't acquire lock for torrent entry"); - - let torrent_entry_info = TorrentEntryInfo { - swarm_metadata: torrent_guard.get_swarm_metadata(), - peers: torrent_guard.get_peers(None).iter().map(|peer| *peer.clone()).collect(), - number_of_peers: torrent_guard.get_peers_len(), - }; - - drop(torrent_guard); - - torrent_entry_info - } - } - - #[tokio::test] - async fn it_should_return_one_torrent_entry_by_infohash() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let info_hash = sample_info_hash(); - let peer = sample_peer(); - - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); - - let torrent_entry = in_memory_torrent_repository.get(&info_hash).unwrap(); - - assert_eq!( - TorrentEntryInfo { - swarm_metadata: SwarmMetadata { - downloaded: 0, - complete: 1, - incomplete: 0 - }, - peers: vec!(peer), - number_of_peers: 1 - }, - torrent_entry.into() - ); - } - - mod it_should_return_many_torrent_entries { - use std::sync::Arc; - - use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - - use crate::test_helpers::tests::{sample_info_hash, sample_peer}; - use crate::torrent::repository::in_memory::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - - #[tokio::test] - async fn without_pagination() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let info_hash = sample_info_hash(); - let peer = sample_peer(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); - - let torrent_entries = in_memory_torrent_repository.get_paginated(None); - - assert_eq!(torrent_entries.len(), 1); - - let torrent_entry = torrent_entries.first().unwrap().1.clone(); - - assert_eq!( - TorrentEntryInfo { - swarm_metadata: SwarmMetadata { - downloaded: 0, - complete: 1, - incomplete: 0 - }, - peers: vec!(peer), - number_of_peers: 1 - }, - torrent_entry.into() - ); - } - - mod with_pagination { - use std::sync::Arc; - - use torrust_tracker_primitives::pagination::Pagination; - use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - - use crate::test_helpers::tests::{ - sample_info_hash_alphabetically_ordered_after_sample_info_hash_one, sample_info_hash_one, - sample_peer_one, sample_peer_two, - }; - use crate::torrent::repository::in_memory::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - - #[tokio::test] - async fn it_should_return_the_first_page() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - // Insert one torrent entry - let info_hash_one = sample_info_hash_one(); - let peer_one = sample_peer_one(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); - - // Insert another torrent entry - let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); - let peer_two = sample_peer_two(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); - - // Get only the first page where page size is 1 - let torrent_entries = - in_memory_torrent_repository.get_paginated(Some(&Pagination { offset: 0, limit: 1 })); - - assert_eq!(torrent_entries.len(), 1); - - let torrent_entry = torrent_entries.first().unwrap().1.clone(); - - assert_eq!( - TorrentEntryInfo { - swarm_metadata: SwarmMetadata { - downloaded: 0, - complete: 1, - incomplete: 0 - }, - peers: vec!(peer_one), - number_of_peers: 1 - }, - torrent_entry.into() - ); - } - - #[tokio::test] - async fn it_should_return_the_second_page() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - // Insert one torrent entry - let info_hash_one = sample_info_hash_one(); - let peer_one = sample_peer_one(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); - - // Insert another torrent entry - let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); - let peer_two = sample_peer_two(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); - - // Get only the first page where page size is 1 - let torrent_entries = - in_memory_torrent_repository.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); - - assert_eq!(torrent_entries.len(), 1); - - let torrent_entry = torrent_entries.first().unwrap().1.clone(); - - assert_eq!( - TorrentEntryInfo { - swarm_metadata: SwarmMetadata { - downloaded: 0, - complete: 1, - incomplete: 0 - }, - peers: vec!(peer_two), - number_of_peers: 1 - }, - torrent_entry.into() - ); - } - - #[tokio::test] - async fn it_should_allow_changing_the_page_size() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - // Insert one torrent entry - let info_hash_one = sample_info_hash_one(); - let peer_one = sample_peer_one(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); - - // Insert another torrent entry - let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); - let peer_two = sample_peer_two(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); - - // Get only the first page where page size is 1 - let torrent_entries = - in_memory_torrent_repository.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); - - assert_eq!(torrent_entries.len(), 1); - } - } - } - } - - mod returning_aggregate_swarm_metadata { - - use std::sync::Arc; - - use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; - use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; - - use crate::test_helpers::tests::{complete_peer, leecher, sample_info_hash, seeder}; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - - // todo: refactor to use test parametrization - - #[tokio::test] - async fn it_should_get_empty_aggregate_swarm_metadata_when_there_are_no_torrents() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); - - assert_eq!( - aggregate_swarm_metadata, - AggregateSwarmMetadata { - total_complete: 0, - total_downloaded: 0, - total_incomplete: 0, - total_torrents: 0 - } - ); - } - - #[tokio::test] - async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_leecher() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher(), None); - - let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); - - assert_eq!( - aggregate_swarm_metadata, - AggregateSwarmMetadata { - total_complete: 0, - total_downloaded: 0, - total_incomplete: 1, - total_torrents: 1, - } - ); - } - - #[tokio::test] - async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_seeder() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &seeder(), None); - - let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); - - assert_eq!( - aggregate_swarm_metadata, - AggregateSwarmMetadata { - total_complete: 1, - total_downloaded: 0, - total_incomplete: 0, - total_torrents: 1, - } - ); - } - - #[tokio::test] - async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_completed_peer() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer(), None); - - let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); - - assert_eq!( - aggregate_swarm_metadata, - AggregateSwarmMetadata { - total_complete: 1, - total_downloaded: 0, - total_incomplete: 0, - total_torrents: 1, - } - ); - } - - #[tokio::test] - async fn it_should_return_the_aggregate_swarm_metadata_when_there_are_multiple_torrents() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let start_time = std::time::Instant::now(); - for i in 0..1_000_000 { - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher(), None); - } - let result_a = start_time.elapsed(); - - let start_time = std::time::Instant::now(); - let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); - let result_b = start_time.elapsed(); - - assert_eq!( - (aggregate_swarm_metadata), - (AggregateSwarmMetadata { - total_complete: 0, - total_downloaded: 0, - total_incomplete: 1_000_000, - total_torrents: 1_000_000, - }), - "{result_a:?} {result_b:?}" - ); - } - } - - mod returning_swarm_metadata { - - use std::sync::Arc; - - use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - - use crate::test_helpers::tests::{leecher, sample_info_hash}; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - - #[tokio::test] - async fn it_should_get_swarm_metadata_for_an_existing_torrent() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let infohash = sample_info_hash(); - - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&infohash, &leecher(), None); - - let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata(&infohash); - - assert_eq!( - swarm_metadata, - SwarmMetadata { - complete: 0, - downloaded: 0, - incomplete: 1, - } - ); - } - - #[tokio::test] - async fn it_should_return_zeroed_swarm_metadata_for_a_non_existing_torrent() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata(&sample_info_hash()); - - assert_eq!(swarm_metadata, SwarmMetadata::zeroed()); - } - } - - mod handling_persistence { - - use std::sync::Arc; - - use torrust_tracker_primitives::PersistentTorrents; - - use crate::test_helpers::tests::sample_info_hash; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - - #[tokio::test] - async fn it_should_allow_importing_persisted_torrent_entries() { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - let infohash = sample_info_hash(); - - let mut persistent_torrents = PersistentTorrents::default(); - - persistent_torrents.insert(infohash, 1); - - in_memory_torrent_repository.import_persistent(&persistent_torrents); - - let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata(&infohash); - - // Only the number of downloads is persisted. - assert_eq!(swarm_metadata.downloaded, 1); - } - } - } -} From 32acbb1dd48ad71cce2b050e6726ff440b969a00 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 2 May 2025 11:32:16 +0100 Subject: [PATCH 1046/1297] refactor: [#1491] rename method --- .../src/statistics/services.rs | 2 +- .../src/statistics/services.rs | 4 +-- packages/torrent-repository/src/repository.rs | 26 +++++-------------- .../torrent-repository/tests/common/repo.rs | 2 +- .../src/torrent/repository/in_memory.rs | 4 +-- .../src/statistics/services.rs | 2 +- .../src/statistics/services.rs | 2 +- 7 files changed, 14 insertions(+), 28 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index e2fbfedd0..1c5890ea8 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -47,7 +47,7 @@ pub async fn get_metrics( in_memory_torrent_repository: Arc, stats_repository: Arc, ) -> TrackerMetrics { - let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata(); let stats = stats_repository.get_stats().await; TrackerMetrics { diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 9489a5e3e..8d5b7514a 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -32,7 +32,7 @@ pub async fn get_metrics( http_stats_repository: Arc, udp_server_stats_repository: Arc, ) -> TrackerMetrics { - let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata(); let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); let http_stats = http_stats_repository.get_stats().await; let udp_server_stats = udp_server_stats_repository.get_stats().await; @@ -97,7 +97,7 @@ pub async fn get_labeled_metrics( udp_stats_repository: Arc, udp_server_stats_repository: Arc, ) -> TrackerLabeledMetrics { - let _torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let _torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata(); let _udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); let http_stats = http_stats_repository.get_stats().await; diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index 6c8a7c9b4..f5c4d7129 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -250,20 +250,6 @@ impl TorrentRepository { } } - /// Calculates and returns overall torrent metrics. - /// - /// The returned [`AggregateSwarmMetadata`] contains aggregate data such as - /// the total number of torrents, total complete (seeders), incomplete - /// (leechers), and downloaded counts. - /// - /// # Returns - /// - /// A [`AggregateSwarmMetadata`] struct with the aggregated metrics. - #[must_use] - pub fn get_torrents_metrics(&self) -> AggregateSwarmMetadata { - self.get_metrics() - } - /// Imports persistent torrent data into the in-memory repository. /// /// This method takes a set of persisted torrent entries (e.g., from a @@ -303,7 +289,7 @@ impl TorrentRepository { /// /// This function panics if the lock for the entry cannot be obtained. #[must_use] - pub fn get_metrics(&self) -> AggregateSwarmMetadata { + pub fn get_aggregate_swarm_metadata(&self) -> AggregateSwarmMetadata { let mut metrics = AggregateSwarmMetadata::default(); for entry in &self.torrents { @@ -824,7 +810,7 @@ mod tests { async fn it_should_get_empty_aggregate_swarm_metadata_when_there_are_no_torrents() { let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); - let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); + let aggregate_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata(); assert_eq!( aggregate_swarm_metadata, @@ -844,7 +830,7 @@ mod tests { let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher(), None); - let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); + let aggregate_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata(); assert_eq!( aggregate_swarm_metadata, @@ -864,7 +850,7 @@ mod tests { let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &seeder(), None); - let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); + let aggregate_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata(); assert_eq!( aggregate_swarm_metadata, @@ -884,7 +870,7 @@ mod tests { let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer(), None); - let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); + let aggregate_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata(); assert_eq!( aggregate_swarm_metadata, @@ -909,7 +895,7 @@ mod tests { let result_a = start_time.elapsed(); let start_time = std::time::Instant::now(); - let aggregate_swarm_metadata = in_memory_torrent_repository.get_torrents_metrics(); + let aggregate_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata(); let result_b = start_time.elapsed(); assert_eq!( diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs index 0055f6bee..eb500114e 100644 --- a/packages/torrent-repository/tests/common/repo.rs +++ b/packages/torrent-repository/tests/common/repo.rs @@ -39,7 +39,7 @@ impl Repo { pub(crate) fn get_metrics(&self) -> AggregateSwarmMetadata { match self { - Repo::SkipMapMutexStd(repo) => repo.get_metrics(), + Repo::SkipMapMutexStd(repo) => repo.get_aggregate_swarm_metadata(), } } diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index f622e909f..e362b20c1 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -199,8 +199,8 @@ impl InMemoryTorrentRepository { /// /// A [`AggregateSwarmMetadata`] struct with the aggregated metrics. #[must_use] - pub fn get_torrents_metrics(&self) -> AggregateSwarmMetadata { - self.torrents.get_torrents_metrics() + pub fn get_aggregate_swarm_metadata(&self) -> AggregateSwarmMetadata { + self.torrents.get_aggregate_swarm_metadata() } /// Imports persistent torrent data into the in-memory repository. diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index aa10e4acd..c76f02040 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -63,7 +63,7 @@ pub async fn get_metrics( in_memory_torrent_repository: Arc, stats_repository: Arc, ) -> TrackerMetrics { - let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata(); let stats = stats_repository.get_stats().await; TrackerMetrics { diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index 4db80c465..a2215067b 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -66,7 +66,7 @@ pub async fn get_metrics( ban_service: Arc>, stats_repository: Arc, ) -> TrackerMetrics { - let torrents_metrics = in_memory_torrent_repository.get_torrents_metrics(); + let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata(); let stats = stats_repository.get_stats().await; let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); From 09bbef77d9c5ed0df86e9dd61a8a3736817effbb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 2 May 2025 11:45:09 +0100 Subject: [PATCH 1047/1297] refactor: [#1491] rename varaible --- packages/torrent-repository/src/repository.rs | 174 ++++++++---------- 1 file changed, 79 insertions(+), 95 deletions(-) diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index f5c4d7129..f6ede60de 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -352,25 +352,25 @@ mod tests { #[tokio::test] async fn it_should_add_the_first_peer_to_the_torrent_peer_list() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let info_hash = sample_info_hash(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); - assert!(in_memory_torrent_repository.get(&info_hash).is_some()); + assert!(torrent_repository.get(&info_hash).is_some()); } #[tokio::test] async fn it_should_allow_adding_the_same_peer_twice_to_the_torrent_peer_list() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let info_hash = sample_info_hash(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); - assert!(in_memory_torrent_repository.get(&info_hash).is_some()); + assert!(torrent_repository.get(&info_hash).is_some()); } } @@ -389,30 +389,30 @@ mod tests { #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash, 74); + let peers = torrent_repository.get_torrent_peers(&info_hash, 74); assert_eq!(peers, vec![Arc::new(peer)]); } #[tokio::test] async fn it_should_return_an_empty_list_or_peers_for_a_non_existing_torrent() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); - let peers = in_memory_torrent_repository.get_torrent_peers(&sample_info_hash(), 74); + let peers = torrent_repository.get_torrent_peers(&sample_info_hash(), 74); assert!(peers.is_empty()); } #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let info_hash = sample_info_hash(); @@ -427,10 +427,10 @@ mod tests { event: AnnounceEvent::Completed, }; - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); } - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash, 74); + let peers = torrent_repository.get_torrent_peers(&info_hash, 74); assert_eq!(peers.len(), 74); } @@ -451,38 +451,36 @@ mod tests { #[tokio::test] async fn it_should_return_an_empty_peer_list_for_a_non_existing_torrent() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); - let peers = - in_memory_torrent_repository.get_peers_for(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT); + let peers = torrent_repository.get_peers_for(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT); assert_eq!(peers, vec![]); } #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); - let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); + let peers = torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); assert_eq!(peers, vec![]); } #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let info_hash = sample_info_hash(); let excluded_peer = sample_peer(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash, &excluded_peer, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &excluded_peer, None); // Add 74 peers for idx in 2..=75 { @@ -496,10 +494,10 @@ mod tests { event: AnnounceEvent::Completed, }; - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); } - let peers = in_memory_torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); + let peers = torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); assert_eq!(peers.len(), 74); } @@ -521,62 +519,60 @@ mod tests { #[tokio::test] async fn it_should_remove_a_torrent_entry() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let info_hash = sample_info_hash(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); - let _unused = in_memory_torrent_repository.remove(&info_hash); + let _unused = torrent_repository.remove(&info_hash); - assert!(in_memory_torrent_repository.get(&info_hash).is_none()); + assert!(torrent_repository.get(&info_hash).is_none()); } #[tokio::test] async fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let info_hash = sample_info_hash(); let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); // Cut off time is 1 second after the peer was updated - in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); + torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); - assert!(!in_memory_torrent_repository - .get_torrent_peers(&info_hash, 74) - .contains(&Arc::new(peer))); + assert!(!torrent_repository.get_torrent_peers(&info_hash, 74).contains(&Arc::new(peer))); } fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); // Insert a sample peer for the torrent to force adding the torrent entry let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(info_hash, &peer, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(info_hash, &peer, None); // Remove the peer - in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); + torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); - in_memory_torrent_repository + torrent_repository } #[tokio::test] async fn it_should_remove_torrents_without_peers() { let info_hash = sample_info_hash(); - let in_memory_torrent_repository = initialize_repository_with_one_torrent_without_peers(&info_hash); + let torrent_repository = initialize_repository_with_one_torrent_without_peers(&info_hash); let tracker_policy = TrackerPolicy { remove_peerless_torrents: true, ..Default::default() }; - in_memory_torrent_repository.remove_peerless_torrents(&tracker_policy); + torrent_repository.remove_peerless_torrents(&tracker_policy); - assert!(in_memory_torrent_repository.get(&info_hash).is_none()); + assert!(torrent_repository.get(&info_hash).is_none()); } } mod returning_torrent_entries { @@ -619,14 +615,14 @@ mod tests { #[tokio::test] async fn it_should_return_one_torrent_entry_by_infohash() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); - let torrent_entry = in_memory_torrent_repository.get(&info_hash).unwrap(); + let torrent_entry = torrent_repository.get(&info_hash).unwrap(); assert_eq!( TorrentEntryInfo { @@ -653,13 +649,13 @@ mod tests { #[tokio::test] async fn without_pagination() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); - let torrent_entries = in_memory_torrent_repository.get_paginated(None); + let torrent_entries = torrent_repository.get_paginated(None); assert_eq!(torrent_entries.len(), 1); @@ -694,23 +690,20 @@ mod tests { #[tokio::test] async fn it_should_return_the_first_page() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); // Get only the first page where page size is 1 - let torrent_entries = - in_memory_torrent_repository.get_paginated(Some(&Pagination { offset: 0, limit: 1 })); + let torrent_entries = torrent_repository.get_paginated(Some(&Pagination { offset: 0, limit: 1 })); assert_eq!(torrent_entries.len(), 1); @@ -732,23 +725,20 @@ mod tests { #[tokio::test] async fn it_should_return_the_second_page() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); // Get only the first page where page size is 1 - let torrent_entries = - in_memory_torrent_repository.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); + let torrent_entries = torrent_repository.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); assert_eq!(torrent_entries.len(), 1); @@ -770,23 +760,20 @@ mod tests { #[tokio::test] async fn it_should_allow_changing_the_page_size() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); // Get only the first page where page size is 1 - let torrent_entries = - in_memory_torrent_repository.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); + let torrent_entries = torrent_repository.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); assert_eq!(torrent_entries.len(), 1); } @@ -808,9 +795,9 @@ mod tests { #[tokio::test] async fn it_should_get_empty_aggregate_swarm_metadata_when_there_are_no_torrents() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); - let aggregate_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata(); + let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata(); assert_eq!( aggregate_swarm_metadata, @@ -825,12 +812,11 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_leecher() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &leecher(), None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&sample_info_hash(), &leecher(), None); - let aggregate_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata(); + let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata(); assert_eq!( aggregate_swarm_metadata, @@ -845,12 +831,11 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_seeder() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &seeder(), None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&sample_info_hash(), &seeder(), None); - let aggregate_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata(); + let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata(); assert_eq!( aggregate_swarm_metadata, @@ -865,12 +850,11 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_completed_peer() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer(), None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer(), None); - let aggregate_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata(); + let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata(); assert_eq!( aggregate_swarm_metadata, @@ -885,17 +869,17 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_are_multiple_torrents() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let start_time = std::time::Instant::now(); for i in 0..1_000_000 { let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher(), None); + torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher(), None); } let result_a = start_time.elapsed(); let start_time = std::time::Instant::now(); - let aggregate_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata(); + let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata(); let result_b = start_time.elapsed(); assert_eq!( @@ -922,13 +906,13 @@ mod tests { #[tokio::test] async fn it_should_get_swarm_metadata_for_an_existing_torrent() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let infohash = sample_info_hash(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&infohash, &leecher(), None); + let _number_of_downloads_increased = torrent_repository.upsert_peer(&infohash, &leecher(), None); - let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata_or_default(&infohash); + let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&infohash); assert_eq!( swarm_metadata, @@ -942,9 +926,9 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_for_a_non_existing_torrent() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); - let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata_or_default(&sample_info_hash()); + let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&sample_info_hash()); assert_eq!(swarm_metadata, SwarmMetadata::zeroed()); } @@ -961,7 +945,7 @@ mod tests { #[tokio::test] async fn it_should_allow_importing_persisted_torrent_entries() { - let in_memory_torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(TorrentRepository::default()); let infohash = sample_info_hash(); @@ -969,9 +953,9 @@ mod tests { persistent_torrents.insert(infohash, 1); - in_memory_torrent_repository.import_persistent(&persistent_torrents); + torrent_repository.import_persistent(&persistent_torrents); - let swarm_metadata = in_memory_torrent_repository.get_swarm_metadata_or_default(&infohash); + let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&infohash); // Only the number of downloads is persisted. assert_eq!(swarm_metadata.downloaded, 1); From 1f5d18fa001929caab10fd9d8089ca30874916bc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 2 May 2025 11:59:59 +0100 Subject: [PATCH 1048/1297] refactor: [#1491] remove duplicate code --- packages/torrent-repository/src/lib.rs | 12 +++- packages/torrent-repository/src/repository.rs | 56 +++++-------------- .../tests/common/torrent.rs | 30 +++------- packages/tracker-core/src/announce_handler.rs | 15 +---- packages/tracker-core/src/torrent/manager.rs | 4 +- packages/tracker-core/src/torrent/services.rs | 26 +++------ 6 files changed, 46 insertions(+), 97 deletions(-) diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index f2e2c643c..d7042a1fd 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,7 +1,7 @@ pub mod entry; pub mod repository; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, MutexGuard}; use torrust_tracker_clock::clock; @@ -19,6 +19,16 @@ pub(crate) type CurrentClock = clock::Working; #[allow(dead_code)] pub(crate) type CurrentClock = clock::Stopped; +pub trait LockTrackedTorrent { + fn lock_or_panic(&self) -> MutexGuard<'_, TrackedTorrent>; +} + +impl LockTrackedTorrent for Arc> { + fn lock_or_panic(&self) -> MutexGuard<'_, TrackedTorrent> { + self.lock().expect("can't acquire lock for tracked torrent handle") + } +} + #[cfg(test)] pub(crate) mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index f6ede60de..8e67f2487 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -9,7 +9,7 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent use crate::entry::peer_list::PeerList; use crate::entry::torrent::TrackedTorrent; -use crate::TrackedTorrentHandle; +use crate::{LockTrackedTorrent, TrackedTorrentHandle}; #[derive(Default, Debug)] pub struct TorrentRepository { @@ -46,11 +46,7 @@ impl TorrentRepository { if let Some(existing_entry) = self.torrents.get(info_hash) { tracing::debug!("Torrent already exists: {:?}", info_hash); - existing_entry - .value() - .lock() - .expect("can't acquire lock for tracked torrent handle") - .upsert_peer(peer) + existing_entry.value().lock_or_panic().upsert_peer(peer) } else { tracing::debug!("Inserting new torrent: {:?}", info_hash); @@ -68,10 +64,7 @@ impl TorrentRepository { let inserted_entry = self.torrents.get_or_insert(*info_hash, new_entry); - let mut torrent_guard = inserted_entry - .value() - .lock() - .expect("can't acquire lock for tracked torrent handle"); + let mut torrent_guard = inserted_entry.value().lock_or_panic(); torrent_guard.upsert_peer(peer) } @@ -97,11 +90,7 @@ impl TorrentRepository { /// This function panics if the lock for the entry cannot be obtained. pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { for entry in &self.torrents { - entry - .value() - .lock() - .expect("can't acquire lock for tracked torrent handle") - .remove_inactive_peers(current_cutoff); + entry.value().lock_or_panic().remove_inactive_peers(current_cutoff); } } @@ -154,13 +143,9 @@ impl TorrentRepository { /// This function panics if the lock for the entry cannot be obtained. #[must_use] pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.torrents.get(info_hash).map(|entry| { - entry - .value() - .lock() - .expect("can't acquire lock for tracked torrent handle") - .get_swarm_metadata() - }) + self.torrents + .get(info_hash) + .map(|entry| entry.value().lock_or_panic().get_swarm_metadata()) } /// Retrieves swarm metadata for a given torrent. @@ -196,10 +181,7 @@ impl TorrentRepository { pub fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { match self.get(info_hash) { None => vec![], - Some(entry) => entry - .lock() - .expect("can't acquire lock for tracked torrent handle") - .get_peers_for_client(&peer.peer_addr, Some(limit)), + Some(entry) => entry.lock_or_panic().get_peers_for_client(&peer.peer_addr, Some(limit)), } } @@ -220,10 +202,7 @@ impl TorrentRepository { pub fn get_torrent_peers(&self, info_hash: &InfoHash, limit: usize) -> Vec> { match self.get(info_hash) { None => vec![], - Some(entry) => entry - .lock() - .expect("can't acquire lock for tracked torrent handle") - .get_peers(Some(limit)), + Some(entry) => entry.lock_or_panic().get_peers(Some(limit)), } } @@ -237,12 +216,7 @@ impl TorrentRepository { /// This function panics if the lock for the entry cannot be obtained. pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { for entry in &self.torrents { - if entry - .value() - .lock() - .expect("can't acquire lock for tracked torrent handle") - .meets_retaining_policy(policy) - { + if entry.value().lock_or_panic().meets_retaining_policy(policy) { continue; } @@ -293,11 +267,7 @@ impl TorrentRepository { let mut metrics = AggregateSwarmMetadata::default(); for entry in &self.torrents { - let stats = entry - .value() - .lock() - .expect("can't acquire lock for tracked torrent handle") - .get_swarm_metadata(); + let stats = entry.value().lock_or_panic().get_swarm_metadata(); metrics.total_complete += u64::from(stats.complete); metrics.total_downloaded += u64::from(stats.downloaded); metrics.total_incomplete += u64::from(stats.incomplete); @@ -584,7 +554,7 @@ mod tests { use crate::repository::TorrentRepository; use crate::tests::{sample_info_hash, sample_peer}; - use crate::TrackedTorrentHandle; + use crate::{LockTrackedTorrent, TrackedTorrentHandle}; /// `TorrentEntry` data is not directly accessible. It's only /// accessible through the trait methods. We need this temporary @@ -599,7 +569,7 @@ mod tests { #[allow(clippy::from_over_into)] impl Into for TrackedTorrentHandle { fn into(self) -> TorrentEntryInfo { - let torrent_guard = self.lock().expect("can't acquire lock for tracked torrent handle"); + let torrent_guard = self.lock_or_panic(); let torrent_entry_info = TorrentEntryInfo { swarm_metadata: torrent_guard.get_swarm_metadata(), diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index 9fdabd136..ffa3c6d71 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; -use torrust_tracker_torrent_repository::{entry, TrackedTorrentHandle}; +use torrust_tracker_torrent_repository::{entry, LockTrackedTorrent, TrackedTorrentHandle}; #[derive(Debug, Clone)] pub(crate) enum Torrent { @@ -16,68 +16,56 @@ impl Torrent { pub(crate) fn get_stats(&self) -> SwarmMetadata { match self { Torrent::Single(entry) => entry.get_swarm_metadata(), - Torrent::MutexStd(entry) => entry - .lock() - .expect("can't acquire lock for torrent entry") - .get_swarm_metadata(), + Torrent::MutexStd(entry) => entry.lock_or_panic().get_swarm_metadata(), } } pub(crate) fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { match self { Torrent::Single(entry) => entry.meets_retaining_policy(policy), - Torrent::MutexStd(entry) => entry - .lock() - .expect("can't acquire lock for torrent entry") - .meets_retaining_policy(policy), + Torrent::MutexStd(entry) => entry.lock_or_panic().meets_retaining_policy(policy), } } pub(crate) fn peers_is_empty(&self) -> bool { match self { Torrent::Single(entry) => entry.peers_is_empty(), - Torrent::MutexStd(entry) => entry.lock().expect("can't acquire lock for torrent entry").peers_is_empty(), + Torrent::MutexStd(entry) => entry.lock_or_panic().peers_is_empty(), } } pub(crate) fn get_peers_len(&self) -> usize { match self { Torrent::Single(entry) => entry.get_peers_len(), - Torrent::MutexStd(entry) => entry.lock().expect("can't acquire lock for torrent entry").get_peers_len(), + Torrent::MutexStd(entry) => entry.lock_or_panic().get_peers_len(), } } pub(crate) fn get_peers(&self, limit: Option) -> Vec> { match self { Torrent::Single(entry) => entry.get_peers(limit), - Torrent::MutexStd(entry) => entry.lock().expect("can't acquire lock for torrent entry").get_peers(limit), + Torrent::MutexStd(entry) => entry.lock_or_panic().get_peers(limit), } } pub(crate) fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { match self { Torrent::Single(entry) => entry.get_peers_for_client(client, limit), - Torrent::MutexStd(entry) => entry - .lock() - .expect("can't acquire lock for torrent entry") - .get_peers_for_client(client, limit), + Torrent::MutexStd(entry) => entry.lock_or_panic().get_peers_for_client(client, limit), } } pub(crate) fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { match self { Torrent::Single(entry) => entry.upsert_peer(peer), - Torrent::MutexStd(entry) => entry.lock().expect("can't acquire lock for torrent entry").upsert_peer(peer), + Torrent::MutexStd(entry) => entry.lock_or_panic().upsert_peer(peer), } } pub(crate) fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { match self { Torrent::Single(entry) => entry.remove_inactive_peers(current_cutoff), - Torrent::MutexStd(entry) => entry - .lock() - .expect("can't acquire lock for torrent entry") - .remove_inactive_peers(current_cutoff), + Torrent::MutexStd(entry) => entry.lock_or_panic().remove_inactive_peers(current_cutoff), } } } diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 76f28aafd..6174190dc 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -594,6 +594,7 @@ mod tests { use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_test_helpers::configuration; + use torrust_tracker_torrent_repository::LockTrackedTorrent; use crate::announce_handler::tests::the_announce_handler::peer_ip; use crate::announce_handler::{AnnounceHandler, PeersWanted}; @@ -656,20 +657,10 @@ mod tests { .expect("it should be able to get entry"); // It persists the number of completed peers. - assert_eq!( - torrent_entry - .lock() - .expect("can't acquire lock for torrent entry") - .get_swarm_metadata() - .downloaded, - 1 - ); + assert_eq!(torrent_entry.lock_or_panic().get_swarm_metadata().downloaded, 1); // It does not persist the peers - assert!(torrent_entry - .lock() - .expect("can't acquire lock for torrent entry") - .peers_is_empty()); + assert!(torrent_entry.lock_or_panic().peers_is_empty()); } } diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index a69f8282b..ae7c61741 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -110,6 +110,7 @@ mod tests { use std::sync::Arc; use torrust_tracker_configuration::Core; + use torrust_tracker_torrent_repository::LockTrackedTorrent; use super::{DatabasePersistentTorrentRepository, TorrentsManager}; use crate::databases::setup::initialize_database; @@ -163,8 +164,7 @@ mod tests { .in_memory_torrent_repository .get(&infohash) .unwrap() - .lock() - .expect("can't acquire lock for torrent entry") + .lock_or_panic() .get_swarm_metadata() .downloaded, 1 diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index 30055b150..37846b4e3 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -17,6 +17,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::peer; +use torrust_tracker_torrent_repository::LockTrackedTorrent; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -98,15 +99,9 @@ pub fn get_torrent_info(in_memory_torrent_repository: &Arc = vec![]; for (info_hash, torrent_entry) in in_memory_torrent_repository.get_paginated(pagination) { - let stats = torrent_entry - .lock() - .expect("can't acquire lock for torrent entry") - .get_swarm_metadata(); + let stats = torrent_entry.lock_or_panic().get_swarm_metadata(); basic_infos.push(BasicInfo { info_hash, @@ -190,12 +182,10 @@ pub fn get_torrents(in_memory_torrent_repository: &Arc = vec![]; for info_hash in info_hashes { - if let Some(stats) = in_memory_torrent_repository.get(info_hash).map(|torrent_entry| { - torrent_entry - .lock() - .expect("can't acquire lock for torrent entry") - .get_swarm_metadata() - }) { + if let Some(stats) = in_memory_torrent_repository + .get(info_hash) + .map(|torrent_entry| torrent_entry.lock_or_panic().get_swarm_metadata()) + { basic_infos.push(BasicInfo { info_hash: *info_hash, seeders: u64::from(stats.complete), From 7215f6e4d9073a781dc2bf2d4a99a5b629530567 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 2 May 2025 12:30:37 +0100 Subject: [PATCH 1049/1297] refactor: [#1491] clean tests in torrent-repository Unneeded wrapper for TorrentRepository now that there is only one implementaion. --- .../torrent-repository/tests/common/mod.rs | 1 - .../torrent-repository/tests/common/repo.rs | 88 ------------------- .../tests/repository/mod.rs | 79 +++++++++++------ 3 files changed, 50 insertions(+), 118 deletions(-) delete mode 100644 packages/torrent-repository/tests/common/repo.rs diff --git a/packages/torrent-repository/tests/common/mod.rs b/packages/torrent-repository/tests/common/mod.rs index efdf7f742..e083a05cc 100644 --- a/packages/torrent-repository/tests/common/mod.rs +++ b/packages/torrent-repository/tests/common/mod.rs @@ -1,3 +1,2 @@ -pub mod repo; pub mod torrent; pub mod torrent_peer_builder; diff --git a/packages/torrent-repository/tests/common/repo.rs b/packages/torrent-repository/tests/common/repo.rs deleted file mode 100644 index eb500114e..000000000 --- a/packages/torrent-repository/tests/common/repo.rs +++ /dev/null @@ -1,88 +0,0 @@ -use std::sync::{Arc, Mutex}; - -use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use torrust_tracker_torrent_repository::entry::torrent::TrackedTorrent; -use torrust_tracker_torrent_repository::TorrentRepository; - -#[derive(Debug)] -pub(crate) enum Repo { - SkipMapMutexStd(TorrentRepository), -} - -impl Repo { - pub(crate) fn upsert_peer( - &self, - info_hash: &InfoHash, - peer: &peer::Peer, - opt_persistent_torrent: Option, - ) -> bool { - match self { - Repo::SkipMapMutexStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), - } - } - - pub(crate) fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - match self { - Repo::SkipMapMutexStd(repo) => repo.get_swarm_metadata(info_hash), - } - } - - pub(crate) fn get(&self, key: &InfoHash) -> Option { - match self { - Repo::SkipMapMutexStd(repo) => Some(repo.get(key)?.lock().unwrap().clone()), - } - } - - pub(crate) fn get_metrics(&self) -> AggregateSwarmMetadata { - match self { - Repo::SkipMapMutexStd(repo) => repo.get_aggregate_swarm_metadata(), - } - } - - pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, TrackedTorrent)> { - match self { - Repo::SkipMapMutexStd(repo) => repo - .get_paginated(pagination) - .iter() - .map(|(i, t)| (*i, t.lock().expect("it should get a lock").clone())) - .collect(), - } - } - - pub(crate) fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - match self { - Repo::SkipMapMutexStd(repo) => repo.import_persistent(persistent_torrents), - } - } - - pub(crate) fn remove(&self, key: &InfoHash) -> Option { - match self { - Repo::SkipMapMutexStd(repo) => Some(repo.remove(key)?.lock().unwrap().clone()), - } - } - - pub(crate) fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - match self { - Repo::SkipMapMutexStd(repo) => repo.remove_inactive_peers(current_cutoff), - } - } - - pub(crate) fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - match self { - Repo::SkipMapMutexStd(repo) => repo.remove_peerless_torrents(policy), - } - } - - pub(crate) fn insert(&self, info_hash: &InfoHash, torrent: TrackedTorrent) -> Option { - match self { - Repo::SkipMapMutexStd(repo) => { - repo.torrents.insert(*info_hash, Arc::new(Mutex::new(torrent))); - } - } - self.get(info_hash) - } -} diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 06ee1d622..9701fc53d 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -1,5 +1,6 @@ use std::collections::{BTreeMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::{Arc, Mutex}; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use bittorrent_primitives::info_hash::InfoHash; @@ -9,14 +10,13 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::PersistentTorrents; use torrust_tracker_torrent_repository::entry::torrent::TrackedTorrent; -use torrust_tracker_torrent_repository::TorrentRepository; +use torrust_tracker_torrent_repository::{LockTrackedTorrent, TorrentRepository}; -use crate::common::repo::Repo; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; #[fixture] -fn skip_list_mutex_std() -> Repo { - Repo::SkipMapMutexStd(TorrentRepository::default()) +fn skip_list_mutex_std() -> TorrentRepository { + TorrentRepository::default() } type Entries = Vec<(InfoHash, TrackedTorrent)>; @@ -148,9 +148,10 @@ fn persistent_three() -> PersistentTorrents { t.iter().copied().collect() } -fn make(repo: &Repo, entries: &Entries) { +fn make(repo: &TorrentRepository, entries: &Entries) { for (info_hash, entry) in entries { - repo.insert(info_hash, entry.clone()); + let new = Arc::new(Mutex::new(entry.clone())); + repo.torrents.insert(*info_hash, new); } } @@ -199,13 +200,16 @@ fn policy_remove_persist() -> TrackerPolicy { #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_get_a_torrent_entry(#[values(skip_list_mutex_std())] repo: Repo, #[case] entries: Entries) { +async fn it_should_get_a_torrent_entry(#[values(skip_list_mutex_std())] repo: TorrentRepository, #[case] entries: Entries) { make(&repo, &entries); if let Some((info_hash, torrent)) = entries.first() { - assert_eq!(repo.get(info_hash), Some(torrent.clone())); + assert_eq!( + Some(repo.get(info_hash).unwrap().lock_or_panic().clone()), + Some(torrent.clone()) + ); } else { - assert_eq!(repo.get(&InfoHash::default()), None); + assert!(repo.get(&InfoHash::default()).is_none()); } } @@ -220,7 +224,7 @@ async fn it_should_get_a_torrent_entry(#[values(skip_list_mutex_std())] repo: Re #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( - #[values(skip_list_mutex_std())] repo: Repo, + #[values(skip_list_mutex_std())] repo: TorrentRepository, #[case] entries: Entries, many_out_of_order: Entries, ) { @@ -253,7 +257,7 @@ async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_get_paginated( - #[values(skip_list_mutex_std())] repo: Repo, + #[values(skip_list_mutex_std())] repo: TorrentRepository, #[case] entries: Entries, #[values(paginated_limit_zero(), paginated_limit_one(), paginated_limit_one_offset_one())] paginated: Pagination, ) { @@ -264,7 +268,15 @@ async fn it_should_get_paginated( match paginated { // it should return empty if limit is zero. - Pagination { limit: 0, .. } => assert_eq!(repo.get_paginated(Some(&paginated)), vec![]), + Pagination { limit: 0, .. } => { + let torrents: Vec<(InfoHash, TrackedTorrent)> = repo + .get_paginated(Some(&paginated)) + .iter() + .map(|(i, lock_tracked_torrent)| (*i, lock_tracked_torrent.lock_or_panic().clone())) + .collect(); + + assert_eq!(torrents, vec![]); + } // it should return a single entry if the limit is one. Pagination { limit: 1, offset: 0 } => { @@ -300,7 +312,7 @@ async fn it_should_get_paginated( #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_get_metrics(#[values(skip_list_mutex_std())] repo: Repo, #[case] entries: Entries) { +async fn it_should_get_metrics(#[values(skip_list_mutex_std())] repo: TorrentRepository, #[case] entries: Entries) { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; make(&repo, &entries); @@ -316,7 +328,7 @@ async fn it_should_get_metrics(#[values(skip_list_mutex_std())] repo: Repo, #[ca metrics.total_downloaded += u64::from(stats.downloaded); } - assert_eq!(repo.get_metrics(), metrics); + assert_eq!(repo.get_aggregate_swarm_metadata(), metrics); } #[rstest] @@ -330,18 +342,18 @@ async fn it_should_get_metrics(#[values(skip_list_mutex_std())] repo: Repo, #[ca #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_import_persistent_torrents( - #[values(skip_list_mutex_std())] repo: Repo, + #[values(skip_list_mutex_std())] repo: TorrentRepository, #[case] entries: Entries, #[values(persistent_empty(), persistent_single(), persistent_three())] persistent_torrents: PersistentTorrents, ) { make(&repo, &entries); - let mut downloaded = repo.get_metrics().total_downloaded; + let mut downloaded = repo.get_aggregate_swarm_metadata().total_downloaded; persistent_torrents.iter().for_each(|(_, d)| downloaded += u64::from(*d)); repo.import_persistent(&persistent_torrents); - assert_eq!(repo.get_metrics().total_downloaded, downloaded); + assert_eq!(repo.get_aggregate_swarm_metadata().total_downloaded, downloaded); for (entry, _) in persistent_torrents { assert!(repo.get(&entry).is_some()); @@ -358,18 +370,21 @@ async fn it_should_import_persistent_torrents( #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_remove_an_entry(#[values(skip_list_mutex_std())] repo: Repo, #[case] entries: Entries) { +async fn it_should_remove_an_entry(#[values(skip_list_mutex_std())] repo: TorrentRepository, #[case] entries: Entries) { make(&repo, &entries); for (info_hash, torrent) in entries { - assert_eq!(repo.get(&info_hash), Some(torrent.clone())); - assert_eq!(repo.remove(&info_hash), Some(torrent)); + assert_eq!( + Some(repo.get(&info_hash).unwrap().lock_or_panic().clone()), + Some(torrent.clone()) + ); + assert_eq!(Some(repo.remove(&info_hash).unwrap().lock_or_panic().clone()), Some(torrent)); - assert_eq!(repo.get(&info_hash), None); - assert_eq!(repo.remove(&info_hash), None); + assert!(repo.get(&info_hash).is_none()); + assert!(repo.remove(&info_hash).is_none()); } - assert_eq!(repo.get_metrics().total_torrents, 0); + assert_eq!(repo.get_aggregate_swarm_metadata().total_torrents, 0); } #[rstest] @@ -382,7 +397,7 @@ async fn it_should_remove_an_entry(#[values(skip_list_mutex_std())] repo: Repo, #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: Repo, #[case] entries: Entries) { +async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: TorrentRepository, #[case] entries: Entries) { use std::ops::Sub as _; use std::time::Duration; @@ -420,7 +435,7 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: // and verify there is an extra torrent entry. { repo.upsert_peer(&info_hash, &peer, None); - assert_eq!(repo.get_metrics().total_torrents, entries.len() as u64 + 1); + assert_eq!(repo.get_aggregate_swarm_metadata().total_torrents, entries.len() as u64 + 1); } // Insert the infohash and peer into the repository @@ -440,7 +455,8 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: // Verify that this new peer was inserted into the repository. { - let entry = repo.get(&info_hash).expect("it_should_get_some"); + let lock_tracked_torrent = repo.get(&info_hash).expect("it_should_get_some"); + let entry = lock_tracked_torrent.lock_or_panic(); assert!(entry.get_peers(None).contains(&peer.into())); } @@ -451,7 +467,8 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: // Verify that the this peer was removed from the repository. { - let entry = repo.get(&info_hash).expect("it_should_get_some"); + let lock_tracked_torrent = repo.get(&info_hash).expect("it_should_get_some"); + let entry = lock_tracked_torrent.lock_or_panic(); assert!(!entry.get_peers(None).contains(&peer.into())); } } @@ -467,7 +484,7 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_remove_peerless_torrents( - #[values(skip_list_mutex_std())] repo: Repo, + #[values(skip_list_mutex_std())] repo: TorrentRepository, #[case] entries: Entries, #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, ) { @@ -475,7 +492,11 @@ async fn it_should_remove_peerless_torrents( repo.remove_peerless_torrents(&policy); - let torrents = repo.get_paginated(None); + let torrents: Vec<(InfoHash, TrackedTorrent)> = repo + .get_paginated(None) + .iter() + .map(|(i, lock_tracked_torrent)| (*i, lock_tracked_torrent.lock_or_panic().clone())) + .collect(); for (_, entry) in torrents { assert!(entry.meets_retaining_policy(&policy)); From 62e57ae27cf24d250bfef6414a2f22ccef7d9b72 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 2 May 2025 13:19:54 +0100 Subject: [PATCH 1050/1297] chore(deps): udpate dependencies ``` cargo update Updating crates.io index Locking 18 packages to latest compatible versions Updating async-executor v1.13.1 -> v1.13.2 Updating axum v0.8.3 -> v0.8.4 Updating bytemuck v1.22.0 -> v1.23.0 Updating cc v1.2.20 -> v1.2.21 Updating chrono v0.4.40 -> v0.4.41 Updating hashbrown v0.15.2 -> v0.15.3 Updating miette v7.5.0 -> v7.6.0 Updating miette-derive v7.5.0 -> v7.6.0 Updating openssl-sys v0.9.107 -> v0.9.108 Updating rustix v1.0.5 -> v1.0.7 Updating sha2 v0.10.8 -> v0.10.9 Updating syn v2.0.100 -> v2.0.101 Updating synstructure v0.13.1 -> v0.13.2 Updating toml v0.8.20 -> v0.8.22 Updating toml_datetime v0.6.8 -> v0.6.9 Updating toml_edit v0.22.24 -> v0.22.26 Adding toml_write v0.1.1 Updating winnow v0.7.7 -> v0.7.8 ``` --- Cargo.lock | 177 ++++++++++++++++++++++++++++------------------------- 1 file changed, 92 insertions(+), 85 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 02e674e95..eea957f88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -233,14 +233,15 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30ca9a001c1e8ba5149f91a74362376cc6bc5b919d92d988668657bd570bdcec" +checksum = "bb812ffb58524bdd10860d7d974e2f01cc0950c2438a74ee5ec2e2280c6c4ffa" dependencies = [ "async-task", "concurrent-queue", "fastrand", "futures-lite", + "pin-project-lite", "slab", ] @@ -331,7 +332,7 @@ checksum = "e539d3fca749fcee5236ab05e93a52867dd549cc157c8cb7f99595f3cedffdb5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -357,9 +358,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "axum" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de45108900e1f9b9242f7f2e254aa3e2c029c921c258fe9e6b4217eeebd54288" +checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5" dependencies = [ "axum-core", "axum-macros", @@ -454,7 +455,7 @@ checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -549,7 +550,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -843,7 +844,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -912,9 +913,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.22.0" +version = "1.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6b1fc10dbac614ebc03540c9dbd60e83887fda27794998c6528f1782047d540" +checksum = "9134a6ef01ce4b366b50689c94f82c14bc72bc5d0386829828a2e2752ef7958c" [[package]] name = "byteorder" @@ -954,9 +955,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.20" +version = "1.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04da6a0d40b948dfc4fa8f5bbf402b0fc1a64a28dbf7d12ffd683550f2c1b63a" +checksum = "8691782945451c1c383942c4874dbe63814f61cb57ef773cda2972682b7bb3c0" dependencies = [ "jobserver", "libc", @@ -986,9 +987,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "chrono" -version = "0.4.40" +version = "0.4.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a7964611d71df112cb1730f2ee67324fcf4d0fc6606acbbe9bfe06df124637c" +checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d" dependencies = [ "android-tzdata", "iana-time-zone", @@ -1076,7 +1077,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -1307,7 +1308,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -1318,7 +1319,7 @@ checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ "darling_core", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -1362,7 +1363,7 @@ checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", "unicode-xid", ] @@ -1374,7 +1375,7 @@ checksum = "ccfae181bab5ab6c5478b2ccb69e4c68a02f8c3ec72f6616bfec9dbc599d2ee0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -1401,7 +1402,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -1648,7 +1649,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -1660,7 +1661,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -1672,7 +1673,7 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -1760,7 +1761,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -1902,9 +1903,9 @@ checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" [[package]] name = "hashbrown" -version = "0.15.2" +version = "0.15.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289" +checksum = "84b26c544d002229e640969970a2e74021aadf6e2f96372b9c58eff97de08eb3" dependencies = [ "allocator-api2", "equivalent", @@ -1917,7 +1918,7 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" dependencies = [ - "hashbrown 0.15.2", + "hashbrown 0.15.3", ] [[package]] @@ -2248,7 +2249,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -2296,7 +2297,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e" dependencies = [ "equivalent", - "hashbrown 0.15.2", + "hashbrown 0.15.3", "serde", ] @@ -2522,7 +2523,7 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" dependencies = [ - "hashbrown 0.15.2", + "hashbrown 0.15.3", ] [[package]] @@ -2539,9 +2540,9 @@ checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "miette" -version = "7.5.0" +version = "7.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a955165f87b37fd1862df2a59547ac542c77ef6d17c666f619d1ad22dd89484" +checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" dependencies = [ "backtrace", "backtrace-ext", @@ -2553,19 +2554,18 @@ dependencies = [ "supports-unicode", "terminal_size", "textwrap", - "thiserror 1.0.69", "unicode-width 0.1.14", ] [[package]] name = "miette-derive" -version = "7.5.0" +version = "7.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf45bf44ab49be92fd1227a3be6fc6f617f1a337c06af54981048574d8783147" +checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -2623,7 +2623,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -2673,7 +2673,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", "termcolor", "thiserror 1.0.69", ] @@ -2872,7 +2872,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -2883,9 +2883,9 @@ checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" [[package]] name = "openssl-sys" -version = "0.9.107" +version = "0.9.108" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8288979acd84749c744a9014b4382d42b8f7b2592847b5afb2ed29e5d16ede07" +checksum = "e145e1651e858e820e4860f7b9c5e169bc1d8ce1c86043be79fa7b7634821847" dependencies = [ "cc", "libc", @@ -2956,7 +2956,7 @@ dependencies = [ "regex", "regex-syntax", "structmeta", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -2979,7 +2979,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -3202,7 +3202,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -3222,7 +3222,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", "version_check", "yansi", ] @@ -3576,7 +3576,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.100", + "syn 2.0.101", "unicode-ident", ] @@ -3646,9 +3646,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.0.5" +version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d97817398dd4bb2e6da002002db259209759911da105da92bec29ccb12cf58bf" +checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266" dependencies = [ "bitflags 2.9.0", "errno", @@ -3844,7 +3844,7 @@ checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -3891,7 +3891,7 @@ checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -3942,7 +3942,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -3958,9 +3958,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.10.8" +version = "0.10.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures", @@ -4055,7 +4055,7 @@ dependencies = [ "proc-macro2", "quote", "structmeta-derive", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -4066,7 +4066,7 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -4119,9 +4119,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.100" +version = "2.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" +checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf" dependencies = [ "proc-macro2", "quote", @@ -4139,13 +4139,13 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.13.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -4201,7 +4201,7 @@ dependencies = [ "fastrand", "getrandom 0.3.2", "once_cell", - "rustix 1.0.5", + "rustix 1.0.7", "windows-sys 0.59.0", ] @@ -4220,7 +4220,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45c6481c4829e4cc63825e62c49186a34538b7b2750b73b266581ffb612fb5ed" dependencies = [ - "rustix 1.0.5", + "rustix 1.0.7", "windows-sys 0.59.0", ] @@ -4295,7 +4295,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -4306,7 +4306,7 @@ checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -4410,7 +4410,7 @@ checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -4474,9 +4474,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.20" +version = "0.8.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd87a5cdd6ffab733b2f74bc4fd7ee5fff6634124999ac278c35fc78c6120148" +checksum = "05ae329d1f08c4d17a59bed7ff5b5a769d062e64a62d34a3261b219e62cd5aae" dependencies = [ "serde", "serde_spanned", @@ -4486,26 +4486,33 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.6.8" +version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" +checksum = "3da5db5a963e24bc68be8b17b6fa82814bb22ee8660f192bb182771d498f09a3" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.22.24" +version = "0.22.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17b4795ff5edd201c7cd6dca065ae59972ce77d1b80fa0a84d94950ece7d1474" +checksum = "310068873db2c5b3e7659d2cc35d21855dbafa50d1ce336397c666e3cb08137e" dependencies = [ "indexmap 2.9.0", "serde", "serde_spanned", "toml_datetime", + "toml_write", "winnow", ] +[[package]] +name = "toml_write" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfb942dfe1d8e29a7ee7fcbde5bd2b9a25fb89aa70caea2eba3bee836ff41076" + [[package]] name = "torrust-axum-health-check-api-server" version = "3.0.0-develop" @@ -4841,7 +4848,7 @@ dependencies = [ "bittorrent-primitives", "criterion", "crossbeam-skiplist", - "rand 0.8.5", + "rand 0.9.1", "rstest", "tokio", "torrust-tracker-clock", @@ -4973,7 +4980,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -5212,7 +5219,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", "wasm-bindgen-shared", ] @@ -5247,7 +5254,7 @@ checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -5323,7 +5330,7 @@ checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -5334,7 +5341,7 @@ checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -5595,9 +5602,9 @@ checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" [[package]] name = "winnow" -version = "0.7.7" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cb8234a863ea0e8cd7284fcdd4f145233eb00fee02bbdd9861aec44e6477bc5" +checksum = "9e27d6ad3dac991091e4d35de9ba2d2d00647c5d0fc26c5496dee55984ae111b" dependencies = [ "memchr", ] @@ -5639,7 +5646,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d65cbf2f12c15564212d48f4e3dfb87923d25d611f2aed18f4cb23f0413d89e" dependencies = [ "libc", - "rustix 1.0.5", + "rustix 1.0.7", ] [[package]] @@ -5668,7 +5675,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", "synstructure", ] @@ -5699,7 +5706,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -5710,7 +5717,7 @@ checksum = "28a6e20d751156648aa063f3800b706ee209a32c0b4d9f24be3d980b01be55ef" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] @@ -5730,7 +5737,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", "synstructure", ] @@ -5759,7 +5766,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn 2.0.101", ] [[package]] From cb51ec9b355f38fe1c604900a10c4728deea5005 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 5 May 2025 17:12:35 +0100 Subject: [PATCH 1051/1297] docs: [#1495] improve torrent-repository pkg readme --- packages/torrent-repository/README.md | 30 +++++++++------------------ 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/packages/torrent-repository/README.md b/packages/torrent-repository/README.md index ffc71f1d7..a8c55746b 100644 --- a/packages/torrent-repository/README.md +++ b/packages/torrent-repository/README.md @@ -2,26 +2,16 @@ A library to provide a torrent repository to the [Torrust Tracker](https://github.com/torrust/torrust-tracker). -## Benchmarking - -```console -cargo bench -p torrust-tracker-torrent-repository -``` - -Example partial output: - -```output - Running benches/repository_benchmark.rs (target/release/deps/repository_benchmark-a9b0013c8d09c3c3) -add_one_torrent/RwLockStd - time: [63.057 ns 63.242 ns 63.506 ns] -Found 12 outliers among 100 measurements (12.00%) - 2 (2.00%) low severe - 2 (2.00%) low mild - 2 (2.00%) high mild - 6 (6.00%) high severe -add_one_torrent/RwLockStdMutexStd - time: [62.505 ns 63.077 ns 63.817 ns] -``` +Its main responsibilities include: + +- Managing Torrent Entries: It stores, retrieves, and manages torrent entries, which are torrents being tracked. +- Persistence: It supports lading tracked torrents from a persistent storage, ensuring that torrent data can be restored across restarts. +- Pagination and sorting: It provides paginated and stable/sorted access to torrent entries. +- Peer management: It manages peers associated with torrents, including removing inactive peers and handling torrents with no peers (peerless torrents). +- Policy handling: It supports different policies for handling torrents, such as persisting, removing, or custom policies for torrents with no peers. +- Metrics: It can provide metrics about the torrents, such as counts or statuses, likely for monitoring or statistics. + +This repo is a core component for managing the state and lifecycle of torrents and their peers in a BitTorrent tracker, with peer management, and flexible policies. ## Documentation From 15c14c50268c8b4567ab7d26503a11432c17bc9d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 5 May 2025 17:29:21 +0100 Subject: [PATCH 1052/1297] refactor: [#1495] rename PeerList to Swarm --- packages/torrent-repository/src/entry/mod.rs | 2 +- .../src/entry/{peer_list.rs => swarm.rs} | 112 +++++++++--------- .../torrent-repository/src/entry/torrent.rs | 4 +- packages/torrent-repository/src/repository.rs | 6 +- 4 files changed, 63 insertions(+), 61 deletions(-) rename packages/torrent-repository/src/entry/{peer_list.rs => swarm.rs} (68%) diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index 785672be5..94fdcc58e 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -1,2 +1,2 @@ -pub mod peer_list; +pub mod swarm; pub mod torrent; diff --git a/packages/torrent-repository/src/entry/peer_list.rs b/packages/torrent-repository/src/entry/swarm.rs similarity index 68% rename from packages/torrent-repository/src/entry/peer_list.rs rename to packages/torrent-repository/src/entry/swarm.rs index 33270cf27..0395361a3 100644 --- a/packages/torrent-repository/src/entry/peer_list.rs +++ b/packages/torrent-repository/src/entry/swarm.rs @@ -1,9 +1,11 @@ //! A peer list. +use std::collections::BTreeMap; use std::net::SocketAddr; use std::sync::Arc; use aquatic_udp_protocol::PeerId; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; +use torrust_tracker_primitives::peer::{self, Peer}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; // code-review: the current implementation uses the peer Id as the ``BTreeMap`` // key. That would allow adding two identical peers except for the Id. @@ -11,11 +13,11 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; // would be allowed. That would lead to duplicated peers in the tracker responses. #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct PeerList { - peers: std::collections::BTreeMap>, +pub struct Swarm { + peers: BTreeMap>, } -impl PeerList { +impl Swarm { #[must_use] pub fn len(&self) -> usize { self.peers.len() @@ -94,193 +96,193 @@ mod tests { use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::entry::peer_list::PeerList; + use crate::entry::swarm::Swarm; #[test] fn be_empty_when_no_peers_have_been_inserted() { - let peer_list = PeerList::default(); + let swarm = Swarm::default(); - assert!(peer_list.is_empty()); + assert!(swarm.is_empty()); } #[test] fn have_zero_length_when_no_peers_have_been_inserted() { - let peer_list = PeerList::default(); + let swarm = Swarm::default(); - assert_eq!(peer_list.len(), 0); + assert_eq!(swarm.len(), 0); } #[test] fn allow_inserting_a_new_peer() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let peer = PeerBuilder::default().build(); - assert_eq!(peer_list.upsert(peer.into()), None); + assert_eq!(swarm.upsert(peer.into()), None); } #[test] fn allow_updating_a_preexisting_peer() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let peer = PeerBuilder::default().build(); - peer_list.upsert(peer.into()); + swarm.upsert(peer.into()); - assert_eq!(peer_list.upsert(peer.into()), Some(Arc::new(peer))); + assert_eq!(swarm.upsert(peer.into()), Some(Arc::new(peer))); } #[test] fn allow_getting_all_peers() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let peer = PeerBuilder::default().build(); - peer_list.upsert(peer.into()); + swarm.upsert(peer.into()); - assert_eq!(peer_list.get_all(None), [Arc::new(peer)]); + assert_eq!(swarm.get_all(None), [Arc::new(peer)]); } #[test] fn allow_getting_one_peer_by_id() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let peer = PeerBuilder::default().build(); - peer_list.upsert(peer.into()); + swarm.upsert(peer.into()); - assert_eq!(peer_list.get(&peer.peer_id), Some(Arc::new(peer)).as_ref()); + assert_eq!(swarm.get(&peer.peer_id), Some(Arc::new(peer)).as_ref()); } #[test] fn increase_the_number_of_peers_after_inserting_a_new_one() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let peer = PeerBuilder::default().build(); - peer_list.upsert(peer.into()); + swarm.upsert(peer.into()); - assert_eq!(peer_list.len(), 1); + assert_eq!(swarm.len(), 1); } #[test] fn decrease_the_number_of_peers_after_removing_one() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let peer = PeerBuilder::default().build(); - peer_list.upsert(peer.into()); + swarm.upsert(peer.into()); - peer_list.remove(&peer.peer_id); + swarm.remove(&peer.peer_id); - assert!(peer_list.is_empty()); + assert!(swarm.is_empty()); } #[test] fn allow_removing_an_existing_peer() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let peer = PeerBuilder::default().build(); - peer_list.upsert(peer.into()); + swarm.upsert(peer.into()); - peer_list.remove(&peer.peer_id); + swarm.remove(&peer.peer_id); - assert_eq!(peer_list.get(&peer.peer_id), None); + assert_eq!(swarm.get(&peer.peer_id), None); } #[test] fn allow_getting_all_peers_excluding_peers_with_a_given_address() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let peer1 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - peer_list.upsert(peer1.into()); + swarm.upsert(peer1.into()); let peer2 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) .build(); - peer_list.upsert(peer2.into()); + swarm.upsert(peer2.into()); - assert_eq!(peer_list.get_peers_excluding_addr(&peer2.peer_addr, None), [Arc::new(peer1)]); + assert_eq!(swarm.get_peers_excluding_addr(&peer2.peer_addr, None), [Arc::new(peer1)]); } #[test] fn return_the_number_of_seeders_in_the_list() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - peer_list.upsert(seeder.into()); - peer_list.upsert(leecher.into()); + swarm.upsert(seeder.into()); + swarm.upsert(leecher.into()); - let (seeders, _leechers) = peer_list.seeders_and_leechers(); + let (seeders, _leechers) = swarm.seeders_and_leechers(); assert_eq!(seeders, 1); } #[test] fn return_the_number_of_leechers_in_the_list() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - peer_list.upsert(seeder.into()); - peer_list.upsert(leecher.into()); + swarm.upsert(seeder.into()); + swarm.upsert(leecher.into()); - let (_seeders, leechers) = peer_list.seeders_and_leechers(); + let (_seeders, leechers) = swarm.seeders_and_leechers(); assert_eq!(leechers, 1); } #[test] fn remove_inactive_peers() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let one_second = DurationSinceUnixEpoch::new(1, 0); // Insert the peer let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - peer_list.upsert(peer.into()); + swarm.upsert(peer.into()); // Remove peers not updated since one second after inserting the peer - peer_list.remove_inactive_peers(last_update_time + one_second); + swarm.remove_inactive_peers(last_update_time + one_second); - assert_eq!(peer_list.len(), 0); + assert_eq!(swarm.len(), 0); } #[test] fn not_remove_active_peers() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let one_second = DurationSinceUnixEpoch::new(1, 0); // Insert the peer let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - peer_list.upsert(peer.into()); + swarm.upsert(peer.into()); // Remove peers not updated since one second before inserting the peer. - peer_list.remove_inactive_peers(last_update_time - one_second); + swarm.remove_inactive_peers(last_update_time - one_second); - assert_eq!(peer_list.len(), 1); + assert_eq!(swarm.len(), 1); } #[test] fn allow_inserting_two_identical_peers_except_for_the_id() { - let mut peer_list = PeerList::default(); + let mut swarm = Swarm::default(); let peer1 = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); - peer_list.upsert(peer1.into()); + swarm.upsert(peer1.into()); let peer2 = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000002")).build(); - peer_list.upsert(peer2.into()); + swarm.upsert(peer2.into()); - assert_eq!(peer_list.len(), 2); + assert_eq!(swarm.len(), 2); } } } diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs index 1cc0f7ba2..48f1a2df1 100644 --- a/packages/torrent-repository/src/entry/torrent.rs +++ b/packages/torrent-repository/src/entry/torrent.rs @@ -8,7 +8,7 @@ use torrust_tracker_primitives::peer::{self}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use super::peer_list::PeerList; +use super::swarm::Swarm; /// A data structure containing all the information about a torrent in the tracker. /// @@ -18,7 +18,7 @@ use super::peer_list::PeerList; #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TrackedTorrent { /// A network of peers that are all trying to download the torrent associated to this entry - pub(crate) swarm: PeerList, + pub(crate) swarm: Swarm, /// The number of peers that have ever completed downloading the torrent associated to this entry pub(crate) downloaded: u32, diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index 8e67f2487..0c387071c 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -7,7 +7,7 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use crate::entry::peer_list::PeerList; +use crate::entry::swarm::Swarm; use crate::entry::torrent::TrackedTorrent; use crate::{LockTrackedTorrent, TrackedTorrentHandle}; @@ -53,7 +53,7 @@ impl TorrentRepository { let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { TrackedTorrentHandle::new( TrackedTorrent { - swarm: PeerList::default(), + swarm: Swarm::default(), downloaded: number_of_downloads, } .into(), @@ -237,7 +237,7 @@ impl TorrentRepository { let entry = TrackedTorrentHandle::new( TrackedTorrent { - swarm: PeerList::default(), + swarm: Swarm::default(), downloaded: *completed, } .into(), From 2882705fbab880ae57cebad4944e6d2452eb63fd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 5 May 2025 20:57:27 +0100 Subject: [PATCH 1053/1297] refactor: [#1495] use SocketAddr as key for peers in Swarm This change prevents duplicate peers with the same address but different IDs, ensuring more accurate peer tracking. --- .../tests/server/asserts.rs | 1 + .../tests/server/requests/announce.rs | 5 ++ .../tests/server/v1/contract.rs | 46 +++++++++++--- .../torrent-repository/src/entry/swarm.rs | 62 ++++++++++++------- .../torrent-repository/src/entry/torrent.rs | 2 +- .../tests/common/torrent_peer_builder.rs | 18 +++++- .../torrent-repository/tests/entry/mod.rs | 3 +- packages/tracker-core/src/lib.rs | 8 +-- packages/tracker-core/src/test_helpers.rs | 6 +- 9 files changed, 109 insertions(+), 42 deletions(-) diff --git a/packages/axum-http-tracker-server/tests/server/asserts.rs b/packages/axum-http-tracker-server/tests/server/asserts.rs index 7ab8d93e5..a82014e16 100644 --- a/packages/axum-http-tracker-server/tests/server/asserts.rs +++ b/packages/axum-http-tracker-server/tests/server/asserts.rs @@ -22,6 +22,7 @@ pub fn assert_bencoded_error(response_text: &String, expected_failure_reason: &s ); } +#[allow(dead_code)] pub async fn assert_empty_announce_response(response: Response) { assert_eq!(response.status(), 200); let announce_response: Announce = serde_bencode::from_str(&response.text().await.unwrap()).unwrap(); diff --git a/packages/axum-http-tracker-server/tests/server/requests/announce.rs b/packages/axum-http-tracker-server/tests/server/requests/announce.rs index 0775de7e4..5a670b618 100644 --- a/packages/axum-http-tracker-server/tests/server/requests/announce.rs +++ b/packages/axum-http-tracker-server/tests/server/requests/announce.rs @@ -126,6 +126,11 @@ impl QueryBuilder { self } + pub fn with_port(mut self, port: u16) -> Self { + self.announce_query.port = port; + self + } + pub fn without_compact(mut self) -> Self { self.announce_query.compact = None; self diff --git a/packages/axum-http-tracker-server/tests/server/v1/contract.rs b/packages/axum-http-tracker-server/tests/server/v1/contract.rs index 37d96052f..d1f52d55a 100644 --- a/packages/axum-http-tracker-server/tests/server/v1/contract.rs +++ b/packages/axum-http-tracker-server/tests/server/v1/contract.rs @@ -105,8 +105,8 @@ mod for_all_config_modes { use crate::common::fixtures::invalid_info_hashes; use crate::server::asserts::{ assert_announce_response, assert_bad_announce_request_error_response, assert_cannot_parse_query_param_error_response, - assert_cannot_parse_query_params_error_response, assert_compact_announce_response, assert_empty_announce_response, - assert_is_announce_response, assert_missing_query_params_for_announce_request_error_response, + assert_cannot_parse_query_params_error_response, assert_compact_announce_response, assert_is_announce_response, + assert_missing_query_params_for_announce_request_error_response, }; use crate::server::client::Client; use crate::server::requests::announce::{Compact, QueryBuilder}; @@ -559,7 +559,8 @@ mod for_all_config_modes { } #[tokio::test] - async fn should_consider_two_peers_to_be_the_same_when_they_have_the_same_peer_id_even_if_the_ip_is_different() { + async fn should_consider_two_peers_to_be_the_same_when_they_have_the_same_socket_address_even_if_the_peer_id_is_different( + ) { logging::setup(); let env = Started::new(&configuration::ephemeral_public().into()).await; @@ -567,19 +568,44 @@ mod for_all_config_modes { let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); // DevSkim: ignore DS173237 let peer = PeerBuilder::default().build(); - // Add a peer - env.add_torrent_peer(&info_hash, &peer); - - let announce_query = QueryBuilder::default() + let announce_query_1 = QueryBuilder::default() .with_info_hash(&info_hash) .with_peer_id(&peer.peer_id) + .with_peer_addr(&peer.peer_addr.ip()) + .with_port(peer.peer_addr.port()) + .query(); + + let announce_query_2 = QueryBuilder::default() + .with_info_hash(&info_hash) + .with_peer_id(&PeerId(*b"-qB00000000000000002")) // Different peer ID + .with_peer_addr(&peer.peer_addr.ip()) + .with_port(peer.peer_addr.port()) .query(); - assert_ne!(peer.peer_addr.ip(), announce_query.peer_addr); + // Same peer socket address + assert_eq!(announce_query_1.peer_addr, announce_query_2.peer_addr); + assert_eq!(announce_query_1.port, announce_query_2.port); + + // Different peer ID + assert_ne!(announce_query_1.peer_id, announce_query_2.peer_id); - let response = Client::new(*env.bind_address()).announce(&announce_query).await; + let _response = Client::new(*env.bind_address()).announce(&announce_query_1).await; + let response = Client::new(*env.bind_address()).announce(&announce_query_2).await; - assert_empty_announce_response(response).await; + let announce_policy = env.container.tracker_core_container.core_config.announce_policy; + + // The response should contain only the first peer. + assert_announce_response( + response, + &Announce { + complete: 1, + incomplete: 0, + interval: announce_policy.interval, + min_interval: announce_policy.interval_min, + peers: vec![], + }, + ) + .await; env.stop().await; } diff --git a/packages/torrent-repository/src/entry/swarm.rs b/packages/torrent-repository/src/entry/swarm.rs index 0395361a3..d6a7df102 100644 --- a/packages/torrent-repository/src/entry/swarm.rs +++ b/packages/torrent-repository/src/entry/swarm.rs @@ -3,18 +3,12 @@ use std::collections::BTreeMap; use std::net::SocketAddr; use std::sync::Arc; -use aquatic_udp_protocol::PeerId; use torrust_tracker_primitives::peer::{self, Peer}; use torrust_tracker_primitives::DurationSinceUnixEpoch; -// code-review: the current implementation uses the peer Id as the ``BTreeMap`` -// key. That would allow adding two identical peers except for the Id. -// For example, two peers with the same socket address but a different peer Id -// would be allowed. That would lead to duplicated peers in the tracker responses. - #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Swarm { - peers: BTreeMap>, + peers: BTreeMap>, } impl Swarm { @@ -28,12 +22,12 @@ impl Swarm { self.peers.is_empty() } - pub fn upsert(&mut self, value: Arc) -> Option> { - self.peers.insert(value.peer_id, value) + pub fn upsert(&mut self, peer: Arc) -> Option> { + self.peers.insert(peer.peer_addr, peer) } - pub fn remove(&mut self, key: &PeerId) -> Option> { - self.peers.remove(key) + pub fn remove(&mut self, peer: &Peer) -> Option> { + self.peers.remove(&peer.peer_addr) } pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { @@ -42,12 +36,12 @@ impl Swarm { } #[must_use] - pub fn get(&self, peer_id: &PeerId) -> Option<&Arc> { - self.peers.get(peer_id) + pub fn get(&self, peer_addr: &SocketAddr) -> Option<&Arc> { + self.peers.get(peer_addr) } #[must_use] - pub fn get_all(&self, limit: Option) -> Vec> { + pub fn get_all(&self, limit: Option) -> Vec> { match limit { Some(limit) => self.peers.values().take(limit).cloned().collect(), None => self.peers.values().cloned().collect(), @@ -151,7 +145,7 @@ mod tests { swarm.upsert(peer.into()); - assert_eq!(swarm.get(&peer.peer_id), Some(Arc::new(peer)).as_ref()); + assert_eq!(swarm.get(&peer.peer_addr), Some(Arc::new(peer)).as_ref()); } #[test] @@ -173,7 +167,7 @@ mod tests { swarm.upsert(peer.into()); - swarm.remove(&peer.peer_id); + swarm.remove(&peer); assert!(swarm.is_empty()); } @@ -186,9 +180,9 @@ mod tests { swarm.upsert(peer.into()); - swarm.remove(&peer.peer_id); + swarm.remove(&peer); - assert_eq!(swarm.get(&peer.peer_id), None); + assert_eq!(swarm.get(&peer.peer_addr), None); } #[test] @@ -273,16 +267,42 @@ mod tests { } #[test] - fn allow_inserting_two_identical_peers_except_for_the_id() { + fn allow_inserting_two_identical_peers_except_for_the_socket_address() { let mut swarm = Swarm::default(); - let peer1 = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); + let peer1 = PeerBuilder::default() + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .build(); swarm.upsert(peer1.into()); - let peer2 = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000002")).build(); + let peer2 = PeerBuilder::default() + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) + .build(); swarm.upsert(peer2.into()); assert_eq!(swarm.len(), 2); } + + #[test] + fn not_allow_inserting_two_peers_with_different_peer_id_but_the_same_socket_address() { + let mut swarm = Swarm::default(); + + // When that happens the peer ID will be changed in the swarm. + // In practice, it's like if the peer had changed its ID. + + let peer1 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .build(); + swarm.upsert(peer1.into()); + + let peer2 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000002")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .build(); + swarm.upsert(peer2.into()); + + assert_eq!(swarm.len(), 1); + } } } diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs index 48f1a2df1..b251699ec 100644 --- a/packages/torrent-repository/src/entry/torrent.rs +++ b/packages/torrent-repository/src/entry/torrent.rs @@ -75,7 +75,7 @@ impl TrackedTorrent { match peer::ReadInfo::get_event(peer) { AnnounceEvent::Stopped => { - drop(self.swarm.remove(&peer::ReadInfo::get_id(peer))); + drop(self.swarm.remove(peer)); } AnnounceEvent::Completed => { let previous = self.swarm.upsert(Arc::new(*peer)); diff --git a/packages/torrent-repository/tests/common/torrent_peer_builder.rs b/packages/torrent-repository/tests/common/torrent_peer_builder.rs index 33120180d..0c065e670 100644 --- a/packages/torrent-repository/tests/common/torrent_peer_builder.rs +++ b/packages/torrent-repository/tests/common/torrent_peer_builder.rs @@ -1,4 +1,4 @@ -use std::net::SocketAddr; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use torrust_tracker_clock::clock::Time; @@ -67,24 +67,40 @@ impl TorrentPeerBuilder { /// A torrent seeder is a peer with 0 bytes left to download which /// has not announced it has stopped +#[allow(clippy::cast_sign_loss)] +#[allow(clippy::cast_possible_truncation)] #[must_use] pub fn a_completed_peer(id: i32) -> peer::Peer { let peer_id = peer::Id::new(id); + let peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), id as u16); + TorrentPeerBuilder::new() .with_number_of_bytes_left(0) .with_event_completed() .with_peer_id(*peer_id) + .with_peer_address(peer_addr) .into() } /// A torrent leecher is a peer that is not a seeder. /// Leecher: left > 0 OR event = Stopped +/// +/// # Panics +/// +/// This function panics if proved id can't be converted into a valid socket address port. +/// +/// The `id` argument is used to identify the peer in both the `peer_id` and the `peer_addr`. +#[allow(clippy::cast_sign_loss)] +#[allow(clippy::cast_possible_truncation)] #[must_use] pub fn a_started_peer(id: i32) -> peer::Peer { let peer_id = peer::Id::new(id); + let peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), id as u16); + TorrentPeerBuilder::new() .with_number_of_bytes_left(1) .with_event_started() .with_peer_id(*peer_id) + .with_peer_address(peer_addr) .into() } diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index 27bb5f238..5f958f05c 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -370,8 +370,7 @@ async fn it_should_limit_the_number_of_peers_returned( // We add one more peer than the scrape limit for peer_number in 1..=74 + 1 { - let mut peer = a_started_peer(1); - peer.peer_id = *peer::Id::new(peer_number); + let peer = a_started_peer(peer_number); torrent.upsert_peer(&peer); } diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index d9da9b9e7..82ebac3c6 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -224,14 +224,14 @@ mod tests { // Scrape let scrape_data = scrape_handler.scrape(&vec![info_hash]).await.unwrap(); - // The expected swarm metadata for the file + // The expected swarm metadata for the torrent let mut expected_scrape_data = ScrapeData::empty(); expected_scrape_data.add_file( &info_hash, SwarmMetadata { - complete: 0, // the "complete" peer does not count because it was not previously known - downloaded: 0, - incomplete: 1, // the "incomplete" peer we have just announced + complete: 1, // the "incomplete" announced + downloaded: 0, // the "complete" peer download does not count because it was not previously known + incomplete: 1, // the "incomplete" peer announced }, ); diff --git a/packages/tracker-core/src/test_helpers.rs b/packages/tracker-core/src/test_helpers.rs index 0d7ca012f..04fe4133b 100644 --- a/packages/tracker-core/src/test_helpers.rs +++ b/packages/tracker-core/src/test_helpers.rs @@ -104,7 +104,7 @@ pub(crate) mod tests { #[must_use] pub fn complete_peer() -> Peer { Peer { - peer_id: PeerId(*b"-qB00000000000000000"), + peer_id: PeerId(*b"-qB00000000000000001"), peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), @@ -118,8 +118,8 @@ pub(crate) mod tests { #[must_use] pub fn incomplete_peer() -> Peer { Peer { - peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)), 8080), + peer_id: PeerId(*b"-qB00000000000000002"), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 2)), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), downloaded: NumberOfBytes::new(0), From 0a4c8050515825244ee4e62ccea0332deb83a84a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 08:49:46 +0100 Subject: [PATCH 1054/1297] refactor: [#1495] add SwarmMetadata to Swarm - Moved responsability for keeping metadata to the Swarm type. - Number of seeder and leechers is now calculated when the Swarm changes not on-demand. We avoid iterating over the peers to get the number of seeders and leechers. - The number of downloads is also calculate now in the Swarm. It will be removed from the TrackedTorrent. --- packages/primitives/src/swarm_metadata.rs | 17 +- .../torrent-repository/src/entry/swarm.rs | 652 +++++++++++++----- 2 files changed, 503 insertions(+), 166 deletions(-) diff --git a/packages/primitives/src/swarm_metadata.rs b/packages/primitives/src/swarm_metadata.rs index 792eff632..a70298d71 100644 --- a/packages/primitives/src/swarm_metadata.rs +++ b/packages/primitives/src/swarm_metadata.rs @@ -7,7 +7,7 @@ use derive_more::Constructor; /// Swarm metadata dictionary in the scrape response. /// /// See [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html) -#[derive(Copy, Clone, Debug, PartialEq, Default, Constructor)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Constructor)] pub struct SwarmMetadata { /// (i.e `completed`): The number of peers that have ever completed /// downloading a given torrent. @@ -27,6 +27,21 @@ impl SwarmMetadata { pub fn zeroed() -> Self { Self::default() } + + #[must_use] + pub fn downloads(&self) -> u32 { + self.downloaded + } + + #[must_use] + pub fn seeders(&self) -> u32 { + self.complete + } + + #[must_use] + pub fn leechers(&self) -> u32 { + self.incomplete + } } /// Structure that holds aggregate swarm metadata. diff --git a/packages/torrent-repository/src/entry/swarm.rs b/packages/torrent-repository/src/entry/swarm.rs index d6a7df102..7331d4504 100644 --- a/packages/torrent-repository/src/entry/swarm.rs +++ b/packages/torrent-repository/src/entry/swarm.rs @@ -1,14 +1,18 @@ -//! A peer list. +//! A swarm is a collection of peers that are all trying to download the same +//! torrent. use std::collections::BTreeMap; use std::net::SocketAddr; use std::sync::Arc; +use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_primitives::peer::{self, Peer}; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Swarm { peers: BTreeMap>, + metadata: SwarmMetadata, } impl Swarm { @@ -23,16 +27,82 @@ impl Swarm { } pub fn upsert(&mut self, peer: Arc) -> Option> { - self.peers.insert(peer.peer_addr, peer) + let new_peer_is_seeder = peer.is_seeder(); + let new_peer_completed = peer.event == AnnounceEvent::Completed; + + if let Some(old_peer) = self.peers.insert(peer.peer_addr, peer) { + // A peer has been updated in the swarm. + + // Check if the peer has changed its from leecher to seeder or vice versa. + if old_peer.is_seeder() != new_peer_is_seeder { + if new_peer_is_seeder { + self.metadata.complete += 1; + self.metadata.incomplete -= 1; + } else { + self.metadata.complete -= 1; + self.metadata.incomplete += 1; + } + } + + // Check if the peer has completed downloading the torrent. + if new_peer_completed && old_peer.event != AnnounceEvent::Completed { + self.metadata.downloaded += 1; + } + + Some(old_peer) + } else { + // A new peer has been added to the swarm. + + // Check if the peer is a seeder or a leecher. + if new_peer_is_seeder { + self.metadata.complete += 1; + } else { + self.metadata.incomplete += 1; + } + + // Check if the peer has completed downloading the torrent. + if new_peer_completed { + // Don't increment `downloaded` here: we only count transitions + // from a known peer + } + + None + } } pub fn remove(&mut self, peer: &Peer) -> Option> { - self.peers.remove(&peer.peer_addr) + match self.peers.remove(&peer.peer_addr) { + Some(old_peer) => { + // A peer has been removed from the swarm. + + // Check if the peer was a seeder or a leecher. + if old_peer.is_seeder() { + self.metadata.complete -= 1; + } else { + self.metadata.incomplete -= 1; + } + + Some(old_peer) + } + None => None, + } } pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { - self.peers - .retain(|_, peer| peer::ReadInfo::get_updated(peer) > current_cutoff); + self.peers.retain(|_, peer| { + let is_active = peer::ReadInfo::get_updated(peer) > current_cutoff; + + if !is_active { + // Update the metadata when removing a peer. + if peer.is_seeder() { + self.metadata.complete -= 1; + } else { + self.metadata.incomplete -= 1; + } + } + + is_active + }); } #[must_use] @@ -48,14 +118,6 @@ impl Swarm { } } - #[must_use] - pub fn seeders_and_leechers(&self) -> (usize, usize) { - let seeders = self.peers.values().filter(|peer| peer.is_seeder()).count(); - let leechers = self.len() - seeders; - - (seeders, leechers) - } - #[must_use] pub fn get_peers_excluding_addr(&self, peer_addr: &SocketAddr, limit: Option) -> Vec> { match limit { @@ -77,232 +139,492 @@ impl Swarm { .collect(), } } + + #[must_use] + pub fn metadata(&self) -> SwarmMetadata { + self.metadata + } + + /// Returns the number of seeders and leechers in the swarm. + /// + /// # Panics + /// + /// This function will panic if the `complete` or `incomplete` fields in the + /// `metadata` field cannot be converted to `usize`. + #[must_use] + pub fn seeders_and_leechers(&self) -> (usize, usize) { + let seeders = self + .metadata + .complete + .try_into() + .expect("Failed to convert 'complete' (seeders) count to usize"); + let leechers = self + .metadata + .incomplete + .try_into() + .expect("Failed to convert 'incomplete' (leechers) count to usize"); + + (seeders, leechers) + } } #[cfg(test)] mod tests { - mod it_should { - use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; - use aquatic_udp_protocol::PeerId; - use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use torrust_tracker_primitives::DurationSinceUnixEpoch; + use aquatic_udp_protocol::PeerId; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::entry::swarm::Swarm; + use crate::entry::swarm::Swarm; - #[test] - fn be_empty_when_no_peers_have_been_inserted() { - let swarm = Swarm::default(); + #[test] + fn it_should_be_empty_when_no_peers_have_been_inserted() { + let swarm = Swarm::default(); - assert!(swarm.is_empty()); - } + assert!(swarm.is_empty()); + } - #[test] - fn have_zero_length_when_no_peers_have_been_inserted() { - let swarm = Swarm::default(); + #[test] + fn it_should_have_zero_length_when_no_peers_have_been_inserted() { + let swarm = Swarm::default(); - assert_eq!(swarm.len(), 0); - } + assert_eq!(swarm.len(), 0); + } - #[test] - fn allow_inserting_a_new_peer() { - let mut swarm = Swarm::default(); + #[test] + fn it_should_allow_inserting_a_new_peer() { + let mut swarm = Swarm::default(); - let peer = PeerBuilder::default().build(); + let peer = PeerBuilder::default().build(); - assert_eq!(swarm.upsert(peer.into()), None); - } + assert_eq!(swarm.upsert(peer.into()), None); + } - #[test] - fn allow_updating_a_preexisting_peer() { - let mut swarm = Swarm::default(); + #[test] + fn it_should_allow_updating_a_preexisting_peer() { + let mut swarm = Swarm::default(); - let peer = PeerBuilder::default().build(); + let peer = PeerBuilder::default().build(); - swarm.upsert(peer.into()); + swarm.upsert(peer.into()); - assert_eq!(swarm.upsert(peer.into()), Some(Arc::new(peer))); - } + assert_eq!(swarm.upsert(peer.into()), Some(Arc::new(peer))); + } - #[test] - fn allow_getting_all_peers() { - let mut swarm = Swarm::default(); + #[test] + fn it_should_allow_getting_all_peers() { + let mut swarm = Swarm::default(); - let peer = PeerBuilder::default().build(); + let peer = PeerBuilder::default().build(); - swarm.upsert(peer.into()); + swarm.upsert(peer.into()); - assert_eq!(swarm.get_all(None), [Arc::new(peer)]); - } + assert_eq!(swarm.get_all(None), [Arc::new(peer)]); + } - #[test] - fn allow_getting_one_peer_by_id() { - let mut swarm = Swarm::default(); + #[test] + fn it_should_allow_getting_one_peer_by_id() { + let mut swarm = Swarm::default(); - let peer = PeerBuilder::default().build(); + let peer = PeerBuilder::default().build(); - swarm.upsert(peer.into()); + swarm.upsert(peer.into()); - assert_eq!(swarm.get(&peer.peer_addr), Some(Arc::new(peer)).as_ref()); - } + assert_eq!(swarm.get(&peer.peer_addr), Some(Arc::new(peer)).as_ref()); + } - #[test] - fn increase_the_number_of_peers_after_inserting_a_new_one() { - let mut swarm = Swarm::default(); + #[test] + fn it_should_increase_the_number_of_peers_after_inserting_a_new_one() { + let mut swarm = Swarm::default(); - let peer = PeerBuilder::default().build(); + let peer = PeerBuilder::default().build(); - swarm.upsert(peer.into()); + swarm.upsert(peer.into()); - assert_eq!(swarm.len(), 1); - } + assert_eq!(swarm.len(), 1); + } - #[test] - fn decrease_the_number_of_peers_after_removing_one() { - let mut swarm = Swarm::default(); + #[test] + fn it_should_decrease_the_number_of_peers_after_removing_one() { + let mut swarm = Swarm::default(); - let peer = PeerBuilder::default().build(); + let peer = PeerBuilder::default().build(); - swarm.upsert(peer.into()); + swarm.upsert(peer.into()); - swarm.remove(&peer); + swarm.remove(&peer); - assert!(swarm.is_empty()); - } + assert!(swarm.is_empty()); + } - #[test] - fn allow_removing_an_existing_peer() { - let mut swarm = Swarm::default(); + #[test] + fn it_should_allow_removing_an_existing_peer() { + let mut swarm = Swarm::default(); - let peer = PeerBuilder::default().build(); + let peer = PeerBuilder::default().build(); - swarm.upsert(peer.into()); + swarm.upsert(peer.into()); - swarm.remove(&peer); + let old = swarm.remove(&peer); - assert_eq!(swarm.get(&peer.peer_addr), None); - } + assert_eq!(old, Some(Arc::new(peer))); + assert_eq!(swarm.get(&peer.peer_addr), None); + } - #[test] - fn allow_getting_all_peers_excluding_peers_with_a_given_address() { - let mut swarm = Swarm::default(); + #[test] + fn it_should_allow_removing_a_non_existing_peer() { + let mut swarm = Swarm::default(); - let peer1 = PeerBuilder::default() - .with_peer_id(&PeerId(*b"-qB00000000000000001")) - .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) - .build(); - swarm.upsert(peer1.into()); + let peer = PeerBuilder::default().build(); - let peer2 = PeerBuilder::default() - .with_peer_id(&PeerId(*b"-qB00000000000000002")) - .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) - .build(); - swarm.upsert(peer2.into()); + assert_eq!(swarm.remove(&peer), None); + } - assert_eq!(swarm.get_peers_excluding_addr(&peer2.peer_addr, None), [Arc::new(peer1)]); - } + #[test] + fn it_should_allow_getting_all_peers_excluding_peers_with_a_given_address() { + let mut swarm = Swarm::default(); - #[test] - fn return_the_number_of_seeders_in_the_list() { - let mut swarm = Swarm::default(); + let peer1 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .build(); + swarm.upsert(peer1.into()); - let seeder = PeerBuilder::seeder().build(); - let leecher = PeerBuilder::leecher().build(); + let peer2 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000002")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) + .build(); + swarm.upsert(peer2.into()); - swarm.upsert(seeder.into()); - swarm.upsert(leecher.into()); + assert_eq!(swarm.get_peers_excluding_addr(&peer2.peer_addr, None), [Arc::new(peer1)]); + } - let (seeders, _leechers) = swarm.seeders_and_leechers(); + #[test] + fn it_should_remove_inactive_peers() { + let mut swarm = Swarm::default(); + let one_second = DurationSinceUnixEpoch::new(1, 0); - assert_eq!(seeders, 1); - } + // Insert the peer + let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); + let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); + swarm.upsert(peer.into()); + + // Remove peers not updated since one second after inserting the peer + swarm.remove_inactive_peers(last_update_time + one_second); - #[test] - fn return_the_number_of_leechers_in_the_list() { - let mut swarm = Swarm::default(); + assert_eq!(swarm.len(), 0); + } - let seeder = PeerBuilder::seeder().build(); - let leecher = PeerBuilder::leecher().build(); + #[test] + fn it_should_not_remove_active_peers() { + let mut swarm = Swarm::default(); + let one_second = DurationSinceUnixEpoch::new(1, 0); - swarm.upsert(seeder.into()); - swarm.upsert(leecher.into()); + // Insert the peer + let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); + let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); + swarm.upsert(peer.into()); - let (_seeders, leechers) = swarm.seeders_and_leechers(); + // Remove peers not updated since one second before inserting the peer. + swarm.remove_inactive_peers(last_update_time - one_second); - assert_eq!(leechers, 1); - } + assert_eq!(swarm.len(), 1); + } + + #[test] + fn it_should_allow_inserting_two_identical_peers_except_for_the_socket_address() { + let mut swarm = Swarm::default(); + + let peer1 = PeerBuilder::default() + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .build(); + swarm.upsert(peer1.into()); + + let peer2 = PeerBuilder::default() + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) + .build(); + swarm.upsert(peer2.into()); + + assert_eq!(swarm.len(), 2); + } + + #[test] + fn it_should_not_allow_inserting_two_peers_with_different_peer_id_but_the_same_socket_address() { + let mut swarm = Swarm::default(); + + // When that happens the peer ID will be changed in the swarm. + // In practice, it's like if the peer had changed its ID. + + let peer1 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000001")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .build(); + swarm.upsert(peer1.into()); + + let peer2 = PeerBuilder::default() + .with_peer_id(&PeerId(*b"-qB00000000000000002")) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .build(); + swarm.upsert(peer2.into()); + + assert_eq!(swarm.len(), 1); + } + + #[test] + fn it_should_return_the_metadata() { + let mut swarm = Swarm::default(); + + let seeder = PeerBuilder::seeder().build(); + let leecher = PeerBuilder::leecher().build(); + + swarm.upsert(seeder.into()); + swarm.upsert(leecher.into()); + + assert_eq!( + swarm.metadata(), + SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 1, + } + ); + } + + #[test] + fn it_should_return_the_number_of_seeders_in_the_list() { + let mut swarm = Swarm::default(); + + let seeder = PeerBuilder::seeder().build(); + let leecher = PeerBuilder::leecher().build(); + + swarm.upsert(seeder.into()); + swarm.upsert(leecher.into()); + + let (seeders, _leechers) = swarm.seeders_and_leechers(); + + assert_eq!(seeders, 1); + } + + #[test] + fn it_should_return_the_number_of_leechers_in_the_list() { + let mut swarm = Swarm::default(); - #[test] - fn remove_inactive_peers() { - let mut swarm = Swarm::default(); - let one_second = DurationSinceUnixEpoch::new(1, 0); + let seeder = PeerBuilder::seeder().build(); + let leecher = PeerBuilder::leecher().build(); - // Insert the peer - let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); - let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - swarm.upsert(peer.into()); + swarm.upsert(seeder.into()); + swarm.upsert(leecher.into()); - // Remove peers not updated since one second after inserting the peer - swarm.remove_inactive_peers(last_update_time + one_second); + let (_seeders, leechers) = swarm.seeders_and_leechers(); - assert_eq!(swarm.len(), 0); + assert_eq!(leechers, 1); + } + + mod updating_the_swarm_metadata { + + mod when_a_new_peer_is_added { + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + + use crate::entry::swarm::Swarm; + + #[test] + fn it_should_increase_the_number_of_leechers_if_the_new_peer_is_a_leecher_() { + let mut swarm = Swarm::default(); + + let leechers = swarm.metadata().leechers(); + + let leecher = PeerBuilder::leecher().build(); + + swarm.upsert(leecher.into()); + + assert_eq!(swarm.metadata().leechers(), leechers + 1); + } + + #[test] + fn it_should_increase_the_number_of_seeders_if_the_new_peer_is_a_seeder() { + let mut swarm = Swarm::default(); + + let seeders = swarm.metadata().seeders(); + + let seeder = PeerBuilder::seeder().build(); + + swarm.upsert(seeder.into()); + + assert_eq!(swarm.metadata().seeders(), seeders + 1); + } + + #[test] + fn it_should_not_increasing_the_number_of_downloads_if_the_new_peer_has_completed_downloading_as_it_was_not_previously_known( + ) { + let mut swarm = Swarm::default(); + + let downloads = swarm.metadata().downloads(); + + let seeder = PeerBuilder::seeder().build(); + + swarm.upsert(seeder.into()); + + assert_eq!(swarm.metadata().downloads(), downloads); + } } - #[test] - fn not_remove_active_peers() { - let mut swarm = Swarm::default(); - let one_second = DurationSinceUnixEpoch::new(1, 0); + mod when_a_peer_is_removed { + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + + use crate::entry::swarm::Swarm; + + #[test] + fn it_should_decrease_the_number_of_leechers_if_the_removed_peer_was_a_leecher() { + let mut swarm = Swarm::default(); + + let leecher = PeerBuilder::leecher().build(); + + swarm.upsert(leecher.into()); + + let leechers = swarm.metadata().leechers(); + + swarm.remove(&leecher); - // Insert the peer - let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); - let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - swarm.upsert(peer.into()); + assert_eq!(swarm.metadata().leechers(), leechers - 1); + } - // Remove peers not updated since one second before inserting the peer. - swarm.remove_inactive_peers(last_update_time - one_second); + #[test] + fn it_should_decrease_the_number_of_seeders_if_the_removed_peer_was_a_seeder() { + let mut swarm = Swarm::default(); - assert_eq!(swarm.len(), 1); + let seeder = PeerBuilder::seeder().build(); + + swarm.upsert(seeder.into()); + + let seeders = swarm.metadata().seeders(); + + swarm.remove(&seeder); + + assert_eq!(swarm.metadata().seeders(), seeders - 1); + } } - #[test] - fn allow_inserting_two_identical_peers_except_for_the_socket_address() { - let mut swarm = Swarm::default(); + mod when_a_peer_is_removed_due_to_inactivity { + use std::time::Duration; + + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + + use crate::entry::swarm::Swarm; + + #[test] + fn it_should_decrease_the_number_of_leechers_when_a_removed_peer_is_a_leecher() { + let mut swarm = Swarm::default(); + + let leecher = PeerBuilder::leecher().build(); - let peer1 = PeerBuilder::default() - .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) - .build(); - swarm.upsert(peer1.into()); + swarm.upsert(leecher.into()); - let peer2 = PeerBuilder::default() - .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) - .build(); - swarm.upsert(peer2.into()); + let leechers = swarm.metadata().leechers(); - assert_eq!(swarm.len(), 2); + swarm.remove_inactive_peers(leecher.updated + Duration::from_secs(1)); + + assert_eq!(swarm.metadata().leechers(), leechers - 1); + } + + #[test] + fn it_should_decrease_the_number_of_seeders_when_the_removed_peer_is_a_seeder() { + let mut swarm = Swarm::default(); + + let seeder = PeerBuilder::seeder().build(); + + swarm.upsert(seeder.into()); + + let seeders = swarm.metadata().seeders(); + + swarm.remove_inactive_peers(seeder.updated + Duration::from_secs(1)); + + assert_eq!(swarm.metadata().seeders(), seeders - 1); + } } - #[test] - fn not_allow_inserting_two_peers_with_different_peer_id_but_the_same_socket_address() { - let mut swarm = Swarm::default(); + mod for_changes_in_existing_peers { + use aquatic_udp_protocol::NumberOfBytes; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + + use crate::entry::swarm::Swarm; + + #[test] + fn it_should_increase_seeders_and_decreasing_leechers_when_the_peer_changes_from_leecher_to_seeder_() { + let mut swarm = Swarm::default(); + + let mut peer = PeerBuilder::leecher().build(); + + swarm.upsert(peer.into()); + + let leechers = swarm.metadata().leechers(); + let seeders = swarm.metadata().seeders(); + + peer.left = NumberOfBytes::new(0); // Convert to seeder + + swarm.upsert(peer.into()); + + assert_eq!(swarm.metadata().seeders(), seeders + 1); + assert_eq!(swarm.metadata().leechers(), leechers - 1); + } + + #[test] + fn it_should_increase_leechers_and_decreasing_seeders_when_the_peer_changes_from_seeder_to_leecher() { + let mut swarm = Swarm::default(); + + let mut peer = PeerBuilder::seeder().build(); + + swarm.upsert(peer.into()); + + let leechers = swarm.metadata().leechers(); + let seeders = swarm.metadata().seeders(); + + peer.left = NumberOfBytes::new(10); // Convert to leecher + + swarm.upsert(peer.into()); + + assert_eq!(swarm.metadata().leechers(), leechers + 1); + assert_eq!(swarm.metadata().seeders(), seeders - 1); + } + + #[test] + fn it_should_increase_the_number_of_downloads_when_the_peer_announces_completed_downloading() { + let mut swarm = Swarm::default(); + + let mut peer = PeerBuilder::leecher().build(); + + swarm.upsert(peer.into()); + + let downloads = swarm.metadata().downloads(); + + peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; + + swarm.upsert(peer.into()); + + assert_eq!(swarm.metadata().downloads(), downloads + 1); + } + + #[test] + fn it_should_not_increasing_the_number_of_downloads_when_the_peer_announces_completed_downloading_twice_() { + let mut swarm = Swarm::default(); + + let mut peer = PeerBuilder::leecher().build(); + + swarm.upsert(peer.into()); + + let downloads = swarm.metadata().downloads(); - // When that happens the peer ID will be changed in the swarm. - // In practice, it's like if the peer had changed its ID. + peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; - let peer1 = PeerBuilder::default() - .with_peer_id(&PeerId(*b"-qB00000000000000001")) - .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) - .build(); - swarm.upsert(peer1.into()); + swarm.upsert(peer.into()); - let peer2 = PeerBuilder::default() - .with_peer_id(&PeerId(*b"-qB00000000000000002")) - .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) - .build(); - swarm.upsert(peer2.into()); + swarm.upsert(peer.into()); - assert_eq!(swarm.len(), 1); + assert_eq!(swarm.metadata().downloads(), downloads + 1); + } } } } From 61560a8bd27a4eedb8d19bde450fce39474fc076 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 11:36:01 +0100 Subject: [PATCH 1055/1297] chore: add gitignore to torrent-repository pkg --- packages/torrent-repository/.gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 packages/torrent-repository/.gitignore diff --git a/packages/torrent-repository/.gitignore b/packages/torrent-repository/.gitignore new file mode 100644 index 000000000..c9907ae11 --- /dev/null +++ b/packages/torrent-repository/.gitignore @@ -0,0 +1 @@ +/.coverage/ From f73c56698c94e2d2e5e177e470c8a9c291ab791e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 16:21:39 +0100 Subject: [PATCH 1056/1297] refactor: [#1495] some renamings in Swarm type --- .../torrent-repository/src/entry/swarm.rs | 142 +++++++++--------- .../torrent-repository/src/entry/torrent.rs | 10 +- 2 files changed, 76 insertions(+), 76 deletions(-) diff --git a/packages/torrent-repository/src/entry/swarm.rs b/packages/torrent-repository/src/entry/swarm.rs index 7331d4504..05c09b68e 100644 --- a/packages/torrent-repository/src/entry/swarm.rs +++ b/packages/torrent-repository/src/entry/swarm.rs @@ -5,37 +5,27 @@ use std::net::SocketAddr; use std::sync::Arc; use aquatic_udp_protocol::AnnounceEvent; -use torrust_tracker_primitives::peer::{self, Peer}; +use torrust_tracker_primitives::peer::{self, Peer, PeerAnnouncement}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Swarm { - peers: BTreeMap>, + peers: BTreeMap>, metadata: SwarmMetadata, } impl Swarm { - #[must_use] - pub fn len(&self) -> usize { - self.peers.len() - } - - #[must_use] - pub fn is_empty(&self) -> bool { - self.peers.is_empty() - } - - pub fn upsert(&mut self, peer: Arc) -> Option> { - let new_peer_is_seeder = peer.is_seeder(); - let new_peer_completed = peer.event == AnnounceEvent::Completed; + pub fn handle_announce(&mut self, incoming_announce: Arc) -> Option> { + let is_now_seeder = incoming_announce.is_seeder(); + let has_completed = incoming_announce.event == AnnounceEvent::Completed; - if let Some(old_peer) = self.peers.insert(peer.peer_addr, peer) { + if let Some(old_announce) = self.peers.insert(incoming_announce.peer_addr, incoming_announce) { // A peer has been updated in the swarm. // Check if the peer has changed its from leecher to seeder or vice versa. - if old_peer.is_seeder() != new_peer_is_seeder { - if new_peer_is_seeder { + if old_announce.is_seeder() != is_now_seeder { + if is_now_seeder { self.metadata.complete += 1; self.metadata.incomplete -= 1; } else { @@ -45,23 +35,23 @@ impl Swarm { } // Check if the peer has completed downloading the torrent. - if new_peer_completed && old_peer.event != AnnounceEvent::Completed { + if has_completed && old_announce.event != AnnounceEvent::Completed { self.metadata.downloaded += 1; } - Some(old_peer) + Some(old_announce) } else { // A new peer has been added to the swarm. // Check if the peer is a seeder or a leecher. - if new_peer_is_seeder { + if is_now_seeder { self.metadata.complete += 1; } else { self.metadata.incomplete += 1; } // Check if the peer has completed downloading the torrent. - if new_peer_completed { + if has_completed { // Don't increment `downloaded` here: we only count transitions // from a known peer } @@ -70,8 +60,8 @@ impl Swarm { } } - pub fn remove(&mut self, peer: &Peer) -> Option> { - match self.peers.remove(&peer.peer_addr) { + pub fn remove(&mut self, peer_to_remove: &Peer) -> Option> { + match self.peers.remove(&peer_to_remove.peer_addr) { Some(old_peer) => { // A peer has been removed from the swarm. @@ -88,7 +78,7 @@ impl Swarm { } } - pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + pub fn remove_inactive(&mut self, current_cutoff: DurationSinceUnixEpoch) { self.peers.retain(|_, peer| { let is_active = peer::ReadInfo::get_updated(peer) > current_cutoff; @@ -111,7 +101,7 @@ impl Swarm { } #[must_use] - pub fn get_all(&self, limit: Option) -> Vec> { + pub fn peers(&self, limit: Option) -> Vec> { match limit { Some(limit) => self.peers.values().take(limit).cloned().collect(), None => self.peers.values().cloned().collect(), @@ -119,7 +109,7 @@ impl Swarm { } #[must_use] - pub fn get_peers_excluding_addr(&self, peer_addr: &SocketAddr, limit: Option) -> Vec> { + pub fn peers_excluding(&self, peer_addr: &SocketAddr, limit: Option) -> Vec> { match limit { Some(limit) => self .peers @@ -166,6 +156,16 @@ impl Swarm { (seeders, leechers) } + + #[must_use] + pub fn len(&self) -> usize { + self.peers.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.peers.is_empty() + } } #[cfg(test)] @@ -201,7 +201,7 @@ mod tests { let peer = PeerBuilder::default().build(); - assert_eq!(swarm.upsert(peer.into()), None); + assert_eq!(swarm.handle_announce(peer.into()), None); } #[test] @@ -210,9 +210,9 @@ mod tests { let peer = PeerBuilder::default().build(); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); - assert_eq!(swarm.upsert(peer.into()), Some(Arc::new(peer))); + assert_eq!(swarm.handle_announce(peer.into()), Some(Arc::new(peer))); } #[test] @@ -221,9 +221,9 @@ mod tests { let peer = PeerBuilder::default().build(); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); - assert_eq!(swarm.get_all(None), [Arc::new(peer)]); + assert_eq!(swarm.peers(None), [Arc::new(peer)]); } #[test] @@ -232,7 +232,7 @@ mod tests { let peer = PeerBuilder::default().build(); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); assert_eq!(swarm.get(&peer.peer_addr), Some(Arc::new(peer)).as_ref()); } @@ -243,7 +243,7 @@ mod tests { let peer = PeerBuilder::default().build(); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); assert_eq!(swarm.len(), 1); } @@ -254,7 +254,7 @@ mod tests { let peer = PeerBuilder::default().build(); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); swarm.remove(&peer); @@ -267,7 +267,7 @@ mod tests { let peer = PeerBuilder::default().build(); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); let old = swarm.remove(&peer); @@ -292,15 +292,15 @@ mod tests { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.upsert(peer1.into()); + swarm.handle_announce(peer1.into()); let peer2 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) .build(); - swarm.upsert(peer2.into()); + swarm.handle_announce(peer2.into()); - assert_eq!(swarm.get_peers_excluding_addr(&peer2.peer_addr, None), [Arc::new(peer1)]); + assert_eq!(swarm.peers_excluding(&peer2.peer_addr, None), [Arc::new(peer1)]); } #[test] @@ -311,10 +311,10 @@ mod tests { // Insert the peer let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); // Remove peers not updated since one second after inserting the peer - swarm.remove_inactive_peers(last_update_time + one_second); + swarm.remove_inactive(last_update_time + one_second); assert_eq!(swarm.len(), 0); } @@ -327,10 +327,10 @@ mod tests { // Insert the peer let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); // Remove peers not updated since one second before inserting the peer. - swarm.remove_inactive_peers(last_update_time - one_second); + swarm.remove_inactive(last_update_time - one_second); assert_eq!(swarm.len(), 1); } @@ -342,12 +342,12 @@ mod tests { let peer1 = PeerBuilder::default() .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.upsert(peer1.into()); + swarm.handle_announce(peer1.into()); let peer2 = PeerBuilder::default() .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) .build(); - swarm.upsert(peer2.into()); + swarm.handle_announce(peer2.into()); assert_eq!(swarm.len(), 2); } @@ -363,13 +363,13 @@ mod tests { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.upsert(peer1.into()); + swarm.handle_announce(peer1.into()); let peer2 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.upsert(peer2.into()); + swarm.handle_announce(peer2.into()); assert_eq!(swarm.len(), 1); } @@ -381,8 +381,8 @@ mod tests { let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - swarm.upsert(seeder.into()); - swarm.upsert(leecher.into()); + swarm.handle_announce(seeder.into()); + swarm.handle_announce(leecher.into()); assert_eq!( swarm.metadata(), @@ -401,8 +401,8 @@ mod tests { let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - swarm.upsert(seeder.into()); - swarm.upsert(leecher.into()); + swarm.handle_announce(seeder.into()); + swarm.handle_announce(leecher.into()); let (seeders, _leechers) = swarm.seeders_and_leechers(); @@ -416,8 +416,8 @@ mod tests { let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - swarm.upsert(seeder.into()); - swarm.upsert(leecher.into()); + swarm.handle_announce(seeder.into()); + swarm.handle_announce(leecher.into()); let (_seeders, leechers) = swarm.seeders_and_leechers(); @@ -439,7 +439,7 @@ mod tests { let leecher = PeerBuilder::leecher().build(); - swarm.upsert(leecher.into()); + swarm.handle_announce(leecher.into()); assert_eq!(swarm.metadata().leechers(), leechers + 1); } @@ -452,7 +452,7 @@ mod tests { let seeder = PeerBuilder::seeder().build(); - swarm.upsert(seeder.into()); + swarm.handle_announce(seeder.into()); assert_eq!(swarm.metadata().seeders(), seeders + 1); } @@ -466,7 +466,7 @@ mod tests { let seeder = PeerBuilder::seeder().build(); - swarm.upsert(seeder.into()); + swarm.handle_announce(seeder.into()); assert_eq!(swarm.metadata().downloads(), downloads); } @@ -483,7 +483,7 @@ mod tests { let leecher = PeerBuilder::leecher().build(); - swarm.upsert(leecher.into()); + swarm.handle_announce(leecher.into()); let leechers = swarm.metadata().leechers(); @@ -498,7 +498,7 @@ mod tests { let seeder = PeerBuilder::seeder().build(); - swarm.upsert(seeder.into()); + swarm.handle_announce(seeder.into()); let seeders = swarm.metadata().seeders(); @@ -521,11 +521,11 @@ mod tests { let leecher = PeerBuilder::leecher().build(); - swarm.upsert(leecher.into()); + swarm.handle_announce(leecher.into()); let leechers = swarm.metadata().leechers(); - swarm.remove_inactive_peers(leecher.updated + Duration::from_secs(1)); + swarm.remove_inactive(leecher.updated + Duration::from_secs(1)); assert_eq!(swarm.metadata().leechers(), leechers - 1); } @@ -536,11 +536,11 @@ mod tests { let seeder = PeerBuilder::seeder().build(); - swarm.upsert(seeder.into()); + swarm.handle_announce(seeder.into()); let seeders = swarm.metadata().seeders(); - swarm.remove_inactive_peers(seeder.updated + Duration::from_secs(1)); + swarm.remove_inactive(seeder.updated + Duration::from_secs(1)); assert_eq!(swarm.metadata().seeders(), seeders - 1); } @@ -558,14 +558,14 @@ mod tests { let mut peer = PeerBuilder::leecher().build(); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); let leechers = swarm.metadata().leechers(); let seeders = swarm.metadata().seeders(); peer.left = NumberOfBytes::new(0); // Convert to seeder - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); assert_eq!(swarm.metadata().seeders(), seeders + 1); assert_eq!(swarm.metadata().leechers(), leechers - 1); @@ -577,14 +577,14 @@ mod tests { let mut peer = PeerBuilder::seeder().build(); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); let leechers = swarm.metadata().leechers(); let seeders = swarm.metadata().seeders(); peer.left = NumberOfBytes::new(10); // Convert to leecher - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); assert_eq!(swarm.metadata().leechers(), leechers + 1); assert_eq!(swarm.metadata().seeders(), seeders - 1); @@ -596,13 +596,13 @@ mod tests { let mut peer = PeerBuilder::leecher().build(); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); let downloads = swarm.metadata().downloads(); peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); assert_eq!(swarm.metadata().downloads(), downloads + 1); } @@ -613,15 +613,15 @@ mod tests { let mut peer = PeerBuilder::leecher().build(); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); let downloads = swarm.metadata().downloads(); peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); - swarm.upsert(peer.into()); + swarm.handle_announce(peer.into()); assert_eq!(swarm.metadata().downloads(), downloads + 1); } diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs index b251699ec..3a895008f 100644 --- a/packages/torrent-repository/src/entry/torrent.rs +++ b/packages/torrent-repository/src/entry/torrent.rs @@ -62,12 +62,12 @@ impl TrackedTorrent { #[must_use] pub fn get_peers(&self, limit: Option) -> Vec> { - self.swarm.get_all(limit) + self.swarm.peers(limit) } #[must_use] pub fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { - self.swarm.get_peers_excluding_addr(client, limit) + self.swarm.peers_excluding(client, limit) } pub fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { @@ -78,7 +78,7 @@ impl TrackedTorrent { drop(self.swarm.remove(peer)); } AnnounceEvent::Completed => { - let previous = self.swarm.upsert(Arc::new(*peer)); + let previous = self.swarm.handle_announce(Arc::new(*peer)); // Don't count if peer was not previously known and not already completed. if previous.is_some_and(|p| p.event != AnnounceEvent::Completed) { self.downloaded += 1; @@ -88,7 +88,7 @@ impl TrackedTorrent { _ => { // `Started` event (first announced event) or // `None` event (announcements done at regular intervals). - drop(self.swarm.upsert(Arc::new(*peer))); + drop(self.swarm.handle_announce(Arc::new(*peer))); } } @@ -96,6 +96,6 @@ impl TrackedTorrent { } pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { - self.swarm.remove_inactive_peers(current_cutoff); + self.swarm.remove_inactive(current_cutoff); } } From 82bbfe3fcfa2768d527efbddff26ec44e0bee136 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 17:11:23 +0100 Subject: [PATCH 1057/1297] refactor: [#1495] move logic from TackedTorrent to Swarm --- .../torrent-repository/src/entry/swarm.rs | 118 ++++++++++++------ .../torrent-repository/src/entry/torrent.rs | 54 ++++---- packages/torrent-repository/src/repository.rs | 10 +- .../tests/common/torrent.rs | 16 +-- .../tests/repository/mod.rs | 24 ++-- packages/tracker-core/src/announce_handler.rs | 2 +- packages/tracker-core/src/torrent/services.rs | 2 +- 7 files changed, 128 insertions(+), 98 deletions(-) diff --git a/packages/torrent-repository/src/entry/swarm.rs b/packages/torrent-repository/src/entry/swarm.rs index 05c09b68e..5d97655ea 100644 --- a/packages/torrent-repository/src/entry/swarm.rs +++ b/packages/torrent-repository/src/entry/swarm.rs @@ -16,7 +16,20 @@ pub struct Swarm { } impl Swarm { - pub fn handle_announce(&mut self, incoming_announce: Arc) -> Option> { + pub fn handle_announcement(&mut self, incoming_announce: &PeerAnnouncement) -> bool { + let mut downloads_increased: bool = false; + + let _previous_peer = match peer::ReadInfo::get_event(incoming_announce) { + AnnounceEvent::Started | AnnounceEvent::None | AnnounceEvent::Completed => { + self.upsert_peer(Arc::new(*incoming_announce), &mut downloads_increased) + } + AnnounceEvent::Stopped => self.remove(incoming_announce), + }; + + downloads_increased + } + + pub fn upsert_peer(&mut self, incoming_announce: Arc, downloads_increased: &mut bool) -> Option> { let is_now_seeder = incoming_announce.is_seeder(); let has_completed = incoming_announce.event == AnnounceEvent::Completed; @@ -37,6 +50,7 @@ impl Swarm { // Check if the peer has completed downloading the torrent. if has_completed && old_announce.event != AnnounceEvent::Completed { self.metadata.downloaded += 1; + *downloads_increased = true; } Some(old_announce) @@ -198,30 +212,33 @@ mod tests { #[test] fn it_should_allow_inserting_a_new_peer() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - assert_eq!(swarm.handle_announce(peer.into()), None); + assert_eq!(swarm.upsert_peer(peer.into(), &mut downloads_increased), None); } #[test] fn it_should_allow_updating_a_preexisting_peer() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); - assert_eq!(swarm.handle_announce(peer.into()), Some(Arc::new(peer))); + assert_eq!(swarm.upsert_peer(peer.into(), &mut downloads_increased), Some(Arc::new(peer))); } #[test] fn it_should_allow_getting_all_peers() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); assert_eq!(swarm.peers(None), [Arc::new(peer)]); } @@ -229,10 +246,11 @@ mod tests { #[test] fn it_should_allow_getting_one_peer_by_id() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); assert_eq!(swarm.get(&peer.peer_addr), Some(Arc::new(peer)).as_ref()); } @@ -240,10 +258,11 @@ mod tests { #[test] fn it_should_increase_the_number_of_peers_after_inserting_a_new_one() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); assert_eq!(swarm.len(), 1); } @@ -251,10 +270,11 @@ mod tests { #[test] fn it_should_decrease_the_number_of_peers_after_removing_one() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); swarm.remove(&peer); @@ -264,10 +284,11 @@ mod tests { #[test] fn it_should_allow_removing_an_existing_peer() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); let old = swarm.remove(&peer); @@ -287,18 +308,19 @@ mod tests { #[test] fn it_should_allow_getting_all_peers_excluding_peers_with_a_given_address() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let peer1 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.handle_announce(peer1.into()); + swarm.upsert_peer(peer1.into(), &mut downloads_increased); let peer2 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) .build(); - swarm.handle_announce(peer2.into()); + swarm.upsert_peer(peer2.into(), &mut downloads_increased); assert_eq!(swarm.peers_excluding(&peer2.peer_addr, None), [Arc::new(peer1)]); } @@ -306,12 +328,13 @@ mod tests { #[test] fn it_should_remove_inactive_peers() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let one_second = DurationSinceUnixEpoch::new(1, 0); // Insert the peer let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); // Remove peers not updated since one second after inserting the peer swarm.remove_inactive(last_update_time + one_second); @@ -322,12 +345,13 @@ mod tests { #[test] fn it_should_not_remove_active_peers() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let one_second = DurationSinceUnixEpoch::new(1, 0); // Insert the peer let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); // Remove peers not updated since one second before inserting the peer. swarm.remove_inactive(last_update_time - one_second); @@ -338,16 +362,17 @@ mod tests { #[test] fn it_should_allow_inserting_two_identical_peers_except_for_the_socket_address() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let peer1 = PeerBuilder::default() .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.handle_announce(peer1.into()); + swarm.upsert_peer(peer1.into(), &mut downloads_increased); let peer2 = PeerBuilder::default() .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) .build(); - swarm.handle_announce(peer2.into()); + swarm.upsert_peer(peer2.into(), &mut downloads_increased); assert_eq!(swarm.len(), 2); } @@ -355,6 +380,7 @@ mod tests { #[test] fn it_should_not_allow_inserting_two_peers_with_different_peer_id_but_the_same_socket_address() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; // When that happens the peer ID will be changed in the swarm. // In practice, it's like if the peer had changed its ID. @@ -363,13 +389,13 @@ mod tests { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.handle_announce(peer1.into()); + swarm.upsert_peer(peer1.into(), &mut downloads_increased); let peer2 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.handle_announce(peer2.into()); + swarm.upsert_peer(peer2.into(), &mut downloads_increased); assert_eq!(swarm.len(), 1); } @@ -377,12 +403,13 @@ mod tests { #[test] fn it_should_return_the_metadata() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - swarm.handle_announce(seeder.into()); - swarm.handle_announce(leecher.into()); + swarm.upsert_peer(seeder.into(), &mut downloads_increased); + swarm.upsert_peer(leecher.into(), &mut downloads_increased); assert_eq!( swarm.metadata(), @@ -397,12 +424,13 @@ mod tests { #[test] fn it_should_return_the_number_of_seeders_in_the_list() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - swarm.handle_announce(seeder.into()); - swarm.handle_announce(leecher.into()); + swarm.upsert_peer(seeder.into(), &mut downloads_increased); + swarm.upsert_peer(leecher.into(), &mut downloads_increased); let (seeders, _leechers) = swarm.seeders_and_leechers(); @@ -412,12 +440,13 @@ mod tests { #[test] fn it_should_return_the_number_of_leechers_in_the_list() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - swarm.handle_announce(seeder.into()); - swarm.handle_announce(leecher.into()); + swarm.upsert_peer(seeder.into(), &mut downloads_increased); + swarm.upsert_peer(leecher.into(), &mut downloads_increased); let (_seeders, leechers) = swarm.seeders_and_leechers(); @@ -434,12 +463,13 @@ mod tests { #[test] fn it_should_increase_the_number_of_leechers_if_the_new_peer_is_a_leecher_() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let leechers = swarm.metadata().leechers(); let leecher = PeerBuilder::leecher().build(); - swarm.handle_announce(leecher.into()); + swarm.upsert_peer(leecher.into(), &mut downloads_increased); assert_eq!(swarm.metadata().leechers(), leechers + 1); } @@ -447,12 +477,13 @@ mod tests { #[test] fn it_should_increase_the_number_of_seeders_if_the_new_peer_is_a_seeder() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let seeders = swarm.metadata().seeders(); let seeder = PeerBuilder::seeder().build(); - swarm.handle_announce(seeder.into()); + swarm.upsert_peer(seeder.into(), &mut downloads_increased); assert_eq!(swarm.metadata().seeders(), seeders + 1); } @@ -461,12 +492,13 @@ mod tests { fn it_should_not_increasing_the_number_of_downloads_if_the_new_peer_has_completed_downloading_as_it_was_not_previously_known( ) { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let downloads = swarm.metadata().downloads(); let seeder = PeerBuilder::seeder().build(); - swarm.handle_announce(seeder.into()); + swarm.upsert_peer(seeder.into(), &mut downloads_increased); assert_eq!(swarm.metadata().downloads(), downloads); } @@ -480,10 +512,11 @@ mod tests { #[test] fn it_should_decrease_the_number_of_leechers_if_the_removed_peer_was_a_leecher() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let leecher = PeerBuilder::leecher().build(); - swarm.handle_announce(leecher.into()); + swarm.upsert_peer(leecher.into(), &mut downloads_increased); let leechers = swarm.metadata().leechers(); @@ -495,10 +528,11 @@ mod tests { #[test] fn it_should_decrease_the_number_of_seeders_if_the_removed_peer_was_a_seeder() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); - swarm.handle_announce(seeder.into()); + swarm.upsert_peer(seeder.into(), &mut downloads_increased); let seeders = swarm.metadata().seeders(); @@ -518,10 +552,11 @@ mod tests { #[test] fn it_should_decrease_the_number_of_leechers_when_a_removed_peer_is_a_leecher() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let leecher = PeerBuilder::leecher().build(); - swarm.handle_announce(leecher.into()); + swarm.upsert_peer(leecher.into(), &mut downloads_increased); let leechers = swarm.metadata().leechers(); @@ -533,10 +568,11 @@ mod tests { #[test] fn it_should_decrease_the_number_of_seeders_when_the_removed_peer_is_a_seeder() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); - swarm.handle_announce(seeder.into()); + swarm.upsert_peer(seeder.into(), &mut downloads_increased); let seeders = swarm.metadata().seeders(); @@ -555,17 +591,18 @@ mod tests { #[test] fn it_should_increase_seeders_and_decreasing_leechers_when_the_peer_changes_from_leecher_to_seeder_() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let mut peer = PeerBuilder::leecher().build(); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); let leechers = swarm.metadata().leechers(); let seeders = swarm.metadata().seeders(); peer.left = NumberOfBytes::new(0); // Convert to seeder - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); assert_eq!(swarm.metadata().seeders(), seeders + 1); assert_eq!(swarm.metadata().leechers(), leechers - 1); @@ -574,17 +611,18 @@ mod tests { #[test] fn it_should_increase_leechers_and_decreasing_seeders_when_the_peer_changes_from_seeder_to_leecher() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let mut peer = PeerBuilder::seeder().build(); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); let leechers = swarm.metadata().leechers(); let seeders = swarm.metadata().seeders(); peer.left = NumberOfBytes::new(10); // Convert to leecher - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); assert_eq!(swarm.metadata().leechers(), leechers + 1); assert_eq!(swarm.metadata().seeders(), seeders - 1); @@ -593,16 +631,17 @@ mod tests { #[test] fn it_should_increase_the_number_of_downloads_when_the_peer_announces_completed_downloading() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let mut peer = PeerBuilder::leecher().build(); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); let downloads = swarm.metadata().downloads(); peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); assert_eq!(swarm.metadata().downloads(), downloads + 1); } @@ -610,18 +649,19 @@ mod tests { #[test] fn it_should_not_increasing_the_number_of_downloads_when_the_peer_announces_completed_downloading_twice_() { let mut swarm = Swarm::default(); + let mut downloads_increased = false; let mut peer = PeerBuilder::leecher().build(); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); let downloads = swarm.metadata().downloads(); peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); - swarm.handle_announce(peer.into()); + swarm.upsert_peer(peer.into(), &mut downloads_increased); assert_eq!(swarm.metadata().downloads(), downloads + 1); } diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs index 3a895008f..b92ca5243 100644 --- a/packages/torrent-repository/src/entry/torrent.rs +++ b/packages/torrent-repository/src/entry/torrent.rs @@ -2,7 +2,6 @@ use std::fmt::Debug; use std::net::SocketAddr; use std::sync::Arc; -use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::peer::{self}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; @@ -10,35 +9,41 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::swarm::Swarm; -/// A data structure containing all the information about a torrent in the tracker. +/// A data structure containing all the information about a torrent in the +/// tracker. /// /// This is the tracker entry for a given torrent and contains the swarm data, /// that's the list of all the peers trying to download the same torrent. +/// /// The tracker keeps one entry like this for every torrent. #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TrackedTorrent { - /// A network of peers that are all trying to download the torrent associated to this entry + /// A network of peers that are all trying to download the torrent. pub(crate) swarm: Swarm, - /// The number of peers that have ever completed downloading the torrent associated to this entry + /// The number of peers that have ever completed downloading the torrent. + /// This value is can be persistent so it's loaded from the database when + /// the tracker starts. pub(crate) downloaded: u32, } impl TrackedTorrent { - #[allow(clippy::cast_possible_truncation)] #[must_use] pub fn get_swarm_metadata(&self) -> SwarmMetadata { - let (seeders, leechers) = self.swarm.seeders_and_leechers(); + let metadata = self.swarm.metadata(); SwarmMetadata { downloaded: self.downloaded, - complete: seeders as u32, - incomplete: leechers as u32, + complete: metadata.complete, + incomplete: metadata.incomplete, } } + /// Returns true if the torrents meets the retention policy, meaning that + /// it should be kept in the tracker. #[must_use] pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + // code-review: why? if policy.persistent_torrent_completed_stat && self.downloaded > 0 { return true; } @@ -51,17 +56,17 @@ impl TrackedTorrent { } #[must_use] - pub fn peers_is_empty(&self) -> bool { + pub fn swarm_is_empty(&self) -> bool { self.swarm.is_empty() } #[must_use] - pub fn get_peers_len(&self) -> usize { + pub fn swarm_len(&self) -> usize { self.swarm.len() } #[must_use] - pub fn get_peers(&self, limit: Option) -> Vec> { + pub fn swarm_peers(&self, limit: Option) -> Vec> { self.swarm.peers(limit) } @@ -70,29 +75,14 @@ impl TrackedTorrent { self.swarm.peers_excluding(client, limit) } - pub fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { - let mut number_of_downloads_increased: bool = false; - - match peer::ReadInfo::get_event(peer) { - AnnounceEvent::Stopped => { - drop(self.swarm.remove(peer)); - } - AnnounceEvent::Completed => { - let previous = self.swarm.handle_announce(Arc::new(*peer)); - // Don't count if peer was not previously known and not already completed. - if previous.is_some_and(|p| p.event != AnnounceEvent::Completed) { - self.downloaded += 1; - number_of_downloads_increased = true; - } - } - _ => { - // `Started` event (first announced event) or - // `None` event (announcements done at regular intervals). - drop(self.swarm.handle_announce(Arc::new(*peer))); - } + pub fn handle_announcement(&mut self, peer: &peer::Peer) -> bool { + let downloads_increased = self.swarm.handle_announcement(peer); + + if downloads_increased { + self.downloaded += 1; } - number_of_downloads_increased + downloads_increased } pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index 0c387071c..69bfcf17b 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -46,7 +46,7 @@ impl TorrentRepository { if let Some(existing_entry) = self.torrents.get(info_hash) { tracing::debug!("Torrent already exists: {:?}", info_hash); - existing_entry.value().lock_or_panic().upsert_peer(peer) + existing_entry.value().lock_or_panic().handle_announcement(peer) } else { tracing::debug!("Inserting new torrent: {:?}", info_hash); @@ -66,7 +66,7 @@ impl TorrentRepository { let mut torrent_guard = inserted_entry.value().lock_or_panic(); - torrent_guard.upsert_peer(peer) + torrent_guard.handle_announcement(peer) } } @@ -202,7 +202,7 @@ impl TorrentRepository { pub fn get_torrent_peers(&self, info_hash: &InfoHash, limit: usize) -> Vec> { match self.get(info_hash) { None => vec![], - Some(entry) => entry.lock_or_panic().get_peers(Some(limit)), + Some(entry) => entry.lock_or_panic().swarm_peers(Some(limit)), } } @@ -573,8 +573,8 @@ mod tests { let torrent_entry_info = TorrentEntryInfo { swarm_metadata: torrent_guard.get_swarm_metadata(), - peers: torrent_guard.get_peers(None).iter().map(|peer| *peer.clone()).collect(), - number_of_peers: torrent_guard.get_peers_len(), + peers: torrent_guard.swarm_peers(None).iter().map(|peer| *peer.clone()).collect(), + number_of_peers: torrent_guard.swarm_len(), }; drop(torrent_guard); diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index ffa3c6d71..f8be53361 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -29,22 +29,22 @@ impl Torrent { pub(crate) fn peers_is_empty(&self) -> bool { match self { - Torrent::Single(entry) => entry.peers_is_empty(), - Torrent::MutexStd(entry) => entry.lock_or_panic().peers_is_empty(), + Torrent::Single(entry) => entry.swarm_is_empty(), + Torrent::MutexStd(entry) => entry.lock_or_panic().swarm_is_empty(), } } pub(crate) fn get_peers_len(&self) -> usize { match self { - Torrent::Single(entry) => entry.get_peers_len(), - Torrent::MutexStd(entry) => entry.lock_or_panic().get_peers_len(), + Torrent::Single(entry) => entry.swarm_len(), + Torrent::MutexStd(entry) => entry.lock_or_panic().swarm_len(), } } pub(crate) fn get_peers(&self, limit: Option) -> Vec> { match self { - Torrent::Single(entry) => entry.get_peers(limit), - Torrent::MutexStd(entry) => entry.lock_or_panic().get_peers(limit), + Torrent::Single(entry) => entry.swarm_peers(limit), + Torrent::MutexStd(entry) => entry.lock_or_panic().swarm_peers(limit), } } @@ -57,8 +57,8 @@ impl Torrent { pub(crate) fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { match self { - Torrent::Single(entry) => entry.upsert_peer(peer), - Torrent::MutexStd(entry) => entry.lock_or_panic().upsert_peer(peer), + Torrent::Single(entry) => entry.handle_announcement(peer), + Torrent::MutexStd(entry) => entry.lock_or_panic().handle_announcement(peer), } } diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 9701fc53d..40dcff6db 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -34,14 +34,14 @@ fn default() -> Entries { #[fixture] fn started() -> Entries { let mut torrent = TrackedTorrent::default(); - torrent.upsert_peer(&a_started_peer(1)); + torrent.handle_announcement(&a_started_peer(1)); vec![(InfoHash::default(), torrent)] } #[fixture] fn completed() -> Entries { let mut torrent = TrackedTorrent::default(); - torrent.upsert_peer(&a_completed_peer(2)); + torrent.handle_announcement(&a_completed_peer(2)); vec![(InfoHash::default(), torrent)] } @@ -49,10 +49,10 @@ fn completed() -> Entries { fn downloaded() -> Entries { let mut torrent = TrackedTorrent::default(); let mut peer = a_started_peer(3); - torrent.upsert_peer(&peer); + torrent.handle_announcement(&peer); peer.event = AnnounceEvent::Completed; peer.left = NumberOfBytes::new(0); - torrent.upsert_peer(&peer); + torrent.handle_announcement(&peer); vec![(InfoHash::default(), torrent)] } @@ -60,21 +60,21 @@ fn downloaded() -> Entries { fn three() -> Entries { let mut started = TrackedTorrent::default(); let started_h = &mut DefaultHasher::default(); - started.upsert_peer(&a_started_peer(1)); + started.handle_announcement(&a_started_peer(1)); started.hash(started_h); let mut completed = TrackedTorrent::default(); let completed_h = &mut DefaultHasher::default(); - completed.upsert_peer(&a_completed_peer(2)); + completed.handle_announcement(&a_completed_peer(2)); completed.hash(completed_h); let mut downloaded = TrackedTorrent::default(); let downloaded_h = &mut DefaultHasher::default(); let mut downloaded_peer = a_started_peer(3); - downloaded.upsert_peer(&downloaded_peer); + downloaded.handle_announcement(&downloaded_peer); downloaded_peer.event = AnnounceEvent::Completed; downloaded_peer.left = NumberOfBytes::new(0); - downloaded.upsert_peer(&downloaded_peer); + downloaded.handle_announcement(&downloaded_peer); downloaded.hash(downloaded_h); vec![ @@ -90,7 +90,7 @@ fn many_out_of_order() -> Entries { for i in 0..408 { let mut entry = TrackedTorrent::default(); - entry.upsert_peer(&a_started_peer(i)); + entry.handle_announcement(&a_started_peer(i)); entries.insert((InfoHash::from(&i), entry)); } @@ -105,7 +105,7 @@ fn many_hashed_in_order() -> Entries { for i in 0..408 { let mut entry = TrackedTorrent::default(); - entry.upsert_peer(&a_started_peer(i)); + entry.handle_announcement(&a_started_peer(i)); let hash: &mut DefaultHasher = &mut DefaultHasher::default(); hash.write_i32(i); @@ -457,7 +457,7 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: { let lock_tracked_torrent = repo.get(&info_hash).expect("it_should_get_some"); let entry = lock_tracked_torrent.lock_or_panic(); - assert!(entry.get_peers(None).contains(&peer.into())); + assert!(entry.swarm_peers(None).contains(&peer.into())); } // Remove peers that have not been updated since the timeout (120 seconds ago). @@ -469,7 +469,7 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: { let lock_tracked_torrent = repo.get(&info_hash).expect("it_should_get_some"); let entry = lock_tracked_torrent.lock_or_panic(); - assert!(!entry.get_peers(None).contains(&peer.into())); + assert!(!entry.swarm_peers(None).contains(&peer.into())); } } diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 6174190dc..ece0c87e6 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -660,7 +660,7 @@ mod tests { assert_eq!(torrent_entry.lock_or_panic().get_swarm_metadata().downloaded, 1); // It does not persist the peers - assert!(torrent_entry.lock_or_panic().peers_is_empty()); + assert!(torrent_entry.lock_or_panic().swarm_is_empty()); } } diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index 37846b4e3..b748cd3a0 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -101,7 +101,7 @@ pub fn get_torrent_info(in_memory_torrent_repository: &Arc Date: Tue, 6 May 2025 17:21:36 +0100 Subject: [PATCH 1058/1297] refactor: [#1495] make TrackedTorrent fields private --- packages/torrent-repository/src/entry/torrent.rs | 9 +++++++-- packages/torrent-repository/src/repository.rs | 16 ++-------------- 2 files changed, 9 insertions(+), 16 deletions(-) diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs index b92ca5243..25c76c25c 100644 --- a/packages/torrent-repository/src/entry/torrent.rs +++ b/packages/torrent-repository/src/entry/torrent.rs @@ -19,15 +19,20 @@ use super::swarm::Swarm; #[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TrackedTorrent { /// A network of peers that are all trying to download the torrent. - pub(crate) swarm: Swarm, + swarm: Swarm, /// The number of peers that have ever completed downloading the torrent. /// This value is can be persistent so it's loaded from the database when /// the tracker starts. - pub(crate) downloaded: u32, + downloaded: u32, } impl TrackedTorrent { + #[must_use] + pub fn new(swarm: Swarm, downloaded: u32) -> Self { + Self { swarm, downloaded } + } + #[must_use] pub fn get_swarm_metadata(&self) -> SwarmMetadata { let metadata = self.swarm.metadata(); diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index 69bfcf17b..6977893b7 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -51,13 +51,7 @@ impl TorrentRepository { tracing::debug!("Inserting new torrent: {:?}", info_hash); let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { - TrackedTorrentHandle::new( - TrackedTorrent { - swarm: Swarm::default(), - downloaded: number_of_downloads, - } - .into(), - ) + TrackedTorrentHandle::new(TrackedTorrent::new(Swarm::default(), number_of_downloads).into()) } else { TrackedTorrentHandle::default() }; @@ -235,13 +229,7 @@ impl TorrentRepository { continue; } - let entry = TrackedTorrentHandle::new( - TrackedTorrent { - swarm: Swarm::default(), - downloaded: *completed, - } - .into(), - ); + let entry = TrackedTorrentHandle::new(TrackedTorrent::new(Swarm::default(), *completed).into()); // Since SkipMap is lock-free the torrent could have been inserted // after checking if it exists. From 3fb117b2b78768d26d9db31df56c6dd59909932e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 17:31:15 +0100 Subject: [PATCH 1059/1297] refactor: [#1495] initialize number of downloads in Swarm to persisted value --- packages/torrent-repository/src/entry/swarm.rs | 8 ++++++++ packages/torrent-repository/src/repository.rs | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/torrent-repository/src/entry/swarm.rs b/packages/torrent-repository/src/entry/swarm.rs index 5d97655ea..44cdaf7aa 100644 --- a/packages/torrent-repository/src/entry/swarm.rs +++ b/packages/torrent-repository/src/entry/swarm.rs @@ -16,6 +16,14 @@ pub struct Swarm { } impl Swarm { + #[must_use] + pub fn new(downloaded: u32) -> Self { + Self { + peers: BTreeMap::new(), + metadata: SwarmMetadata::new(downloaded, 0, 0), + } + } + pub fn handle_announcement(&mut self, incoming_announce: &PeerAnnouncement) -> bool { let mut downloads_increased: bool = false; diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index 6977893b7..fa3d77f95 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -51,7 +51,7 @@ impl TorrentRepository { tracing::debug!("Inserting new torrent: {:?}", info_hash); let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { - TrackedTorrentHandle::new(TrackedTorrent::new(Swarm::default(), number_of_downloads).into()) + TrackedTorrentHandle::new(TrackedTorrent::new(Swarm::new(number_of_downloads), number_of_downloads).into()) } else { TrackedTorrentHandle::default() }; From ec597f020e4d0a063ba9979cbe2038396272600c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 17:38:42 +0100 Subject: [PATCH 1060/1297] refactor: [#1495] get the number of downloads from Swarm instead of from TrackedTorrent --- packages/torrent-repository/src/entry/torrent.rs | 8 +------- packages/torrent-repository/src/repository.rs | 2 +- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs index 25c76c25c..7a31ff5a0 100644 --- a/packages/torrent-repository/src/entry/torrent.rs +++ b/packages/torrent-repository/src/entry/torrent.rs @@ -35,13 +35,7 @@ impl TrackedTorrent { #[must_use] pub fn get_swarm_metadata(&self) -> SwarmMetadata { - let metadata = self.swarm.metadata(); - - SwarmMetadata { - downloaded: self.downloaded, - complete: metadata.complete, - incomplete: metadata.incomplete, - } + self.swarm.metadata() } /// Returns true if the torrents meets the retention policy, meaning that diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index fa3d77f95..cb64474c8 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -229,7 +229,7 @@ impl TorrentRepository { continue; } - let entry = TrackedTorrentHandle::new(TrackedTorrent::new(Swarm::default(), *completed).into()); + let entry = TrackedTorrentHandle::new(TrackedTorrent::new(Swarm::new(*completed), *completed).into()); // Since SkipMap is lock-free the torrent could have been inserted // after checking if it exists. From 23ce6e4731e617c455a760e586c614e332813881 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 17:41:56 +0100 Subject: [PATCH 1061/1297] refactor: [#1495]remove unused field in TrackedTorrent --- .../torrent-repository/src/entry/torrent.rs | 19 ++++--------------- packages/torrent-repository/src/repository.rs | 4 ++-- 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs index 7a31ff5a0..c13db59a1 100644 --- a/packages/torrent-repository/src/entry/torrent.rs +++ b/packages/torrent-repository/src/entry/torrent.rs @@ -20,17 +20,12 @@ use super::swarm::Swarm; pub struct TrackedTorrent { /// A network of peers that are all trying to download the torrent. swarm: Swarm, - - /// The number of peers that have ever completed downloading the torrent. - /// This value is can be persistent so it's loaded from the database when - /// the tracker starts. - downloaded: u32, } impl TrackedTorrent { #[must_use] - pub fn new(swarm: Swarm, downloaded: u32) -> Self { - Self { swarm, downloaded } + pub fn new(swarm: Swarm) -> Self { + Self { swarm } } #[must_use] @@ -43,7 +38,7 @@ impl TrackedTorrent { #[must_use] pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { // code-review: why? - if policy.persistent_torrent_completed_stat && self.downloaded > 0 { + if policy.persistent_torrent_completed_stat && self.get_swarm_metadata().downloaded > 0 { return true; } @@ -75,13 +70,7 @@ impl TrackedTorrent { } pub fn handle_announcement(&mut self, peer: &peer::Peer) -> bool { - let downloads_increased = self.swarm.handle_announcement(peer); - - if downloads_increased { - self.downloaded += 1; - } - - downloads_increased + self.swarm.handle_announcement(peer) } pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index cb64474c8..babca5f5d 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -51,7 +51,7 @@ impl TorrentRepository { tracing::debug!("Inserting new torrent: {:?}", info_hash); let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { - TrackedTorrentHandle::new(TrackedTorrent::new(Swarm::new(number_of_downloads), number_of_downloads).into()) + TrackedTorrentHandle::new(TrackedTorrent::new(Swarm::new(number_of_downloads)).into()) } else { TrackedTorrentHandle::default() }; @@ -229,7 +229,7 @@ impl TorrentRepository { continue; } - let entry = TrackedTorrentHandle::new(TrackedTorrent::new(Swarm::new(*completed), *completed).into()); + let entry = TrackedTorrentHandle::new(TrackedTorrent::new(Swarm::new(*completed)).into()); // Since SkipMap is lock-free the torrent could have been inserted // after checking if it exists. From ef7292f424158b07789da2d9b883ac7a8853e230 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 17:52:00 +0100 Subject: [PATCH 1062/1297] refactor: [#1495] move logic from TrackedTorrent to Swarm --- packages/torrent-repository/src/entry/swarm.rs | 17 +++++++++++++++++ .../torrent-repository/src/entry/torrent.rs | 13 +------------ 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/packages/torrent-repository/src/entry/swarm.rs b/packages/torrent-repository/src/entry/swarm.rs index 44cdaf7aa..eb7aebfe4 100644 --- a/packages/torrent-repository/src/entry/swarm.rs +++ b/packages/torrent-repository/src/entry/swarm.rs @@ -5,6 +5,7 @@ use std::net::SocketAddr; use std::sync::Arc; use aquatic_udp_protocol::AnnounceEvent; +use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::peer::{self, Peer, PeerAnnouncement}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; @@ -188,6 +189,22 @@ impl Swarm { pub fn is_empty(&self) -> bool { self.peers.is_empty() } + + /// Returns true if the torrents meets the retention policy, meaning that + /// it should be kept in the tracker. + #[must_use] + pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { + // code-review: why? + if policy.persistent_torrent_completed_stat && self.metadata().downloaded > 0 { + return true; + } + + if policy.remove_peerless_torrents && self.is_empty() { + return false; + } + + true + } } #[cfg(test)] diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs index c13db59a1..44d5f226a 100644 --- a/packages/torrent-repository/src/entry/torrent.rs +++ b/packages/torrent-repository/src/entry/torrent.rs @@ -33,20 +33,9 @@ impl TrackedTorrent { self.swarm.metadata() } - /// Returns true if the torrents meets the retention policy, meaning that - /// it should be kept in the tracker. #[must_use] pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { - // code-review: why? - if policy.persistent_torrent_completed_stat && self.get_swarm_metadata().downloaded > 0 { - return true; - } - - if policy.remove_peerless_torrents && self.swarm.is_empty() { - return false; - } - - true + self.swarm.meets_retaining_policy(policy) } #[must_use] From b6afed5c9f2900d41c02478d73aaa7f53f70b6fa Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 17:54:05 +0100 Subject: [PATCH 1063/1297] refactor: [#1495] rename methods --- .../torrent-repository/src/entry/torrent.rs | 12 +++++----- packages/torrent-repository/src/repository.rs | 16 ++++++------- .../tests/common/torrent.rs | 24 +++++++++---------- .../tests/repository/mod.rs | 6 ++--- packages/tracker-core/src/announce_handler.rs | 4 ++-- packages/tracker-core/src/torrent/manager.rs | 2 +- packages/tracker-core/src/torrent/services.rs | 8 +++---- 7 files changed, 36 insertions(+), 36 deletions(-) diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs index 44d5f226a..69a809a37 100644 --- a/packages/torrent-repository/src/entry/torrent.rs +++ b/packages/torrent-repository/src/entry/torrent.rs @@ -29,7 +29,7 @@ impl TrackedTorrent { } #[must_use] - pub fn get_swarm_metadata(&self) -> SwarmMetadata { + pub fn metadata(&self) -> SwarmMetadata { self.swarm.metadata() } @@ -39,22 +39,22 @@ impl TrackedTorrent { } #[must_use] - pub fn swarm_is_empty(&self) -> bool { + pub fn is_empty(&self) -> bool { self.swarm.is_empty() } #[must_use] - pub fn swarm_len(&self) -> usize { + pub fn len(&self) -> usize { self.swarm.len() } #[must_use] - pub fn swarm_peers(&self, limit: Option) -> Vec> { + pub fn peers(&self, limit: Option) -> Vec> { self.swarm.peers(limit) } #[must_use] - pub fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { + pub fn peers_excluding(&self, client: &SocketAddr, limit: Option) -> Vec> { self.swarm.peers_excluding(client, limit) } @@ -62,7 +62,7 @@ impl TrackedTorrent { self.swarm.handle_announcement(peer) } - pub fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { + pub fn remove_inactive(&mut self, current_cutoff: DurationSinceUnixEpoch) { self.swarm.remove_inactive(current_cutoff); } } diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index babca5f5d..1706937fc 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -84,7 +84,7 @@ impl TorrentRepository { /// This function panics if the lock for the entry cannot be obtained. pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { for entry in &self.torrents { - entry.value().lock_or_panic().remove_inactive_peers(current_cutoff); + entry.value().lock_or_panic().remove_inactive(current_cutoff); } } @@ -139,7 +139,7 @@ impl TorrentRepository { pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { self.torrents .get(info_hash) - .map(|entry| entry.value().lock_or_panic().get_swarm_metadata()) + .map(|entry| entry.value().lock_or_panic().metadata()) } /// Retrieves swarm metadata for a given torrent. @@ -175,7 +175,7 @@ impl TorrentRepository { pub fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { match self.get(info_hash) { None => vec![], - Some(entry) => entry.lock_or_panic().get_peers_for_client(&peer.peer_addr, Some(limit)), + Some(entry) => entry.lock_or_panic().peers_excluding(&peer.peer_addr, Some(limit)), } } @@ -196,7 +196,7 @@ impl TorrentRepository { pub fn get_torrent_peers(&self, info_hash: &InfoHash, limit: usize) -> Vec> { match self.get(info_hash) { None => vec![], - Some(entry) => entry.lock_or_panic().swarm_peers(Some(limit)), + Some(entry) => entry.lock_or_panic().peers(Some(limit)), } } @@ -255,7 +255,7 @@ impl TorrentRepository { let mut metrics = AggregateSwarmMetadata::default(); for entry in &self.torrents { - let stats = entry.value().lock_or_panic().get_swarm_metadata(); + let stats = entry.value().lock_or_panic().metadata(); metrics.total_complete += u64::from(stats.complete); metrics.total_downloaded += u64::from(stats.downloaded); metrics.total_incomplete += u64::from(stats.incomplete); @@ -560,9 +560,9 @@ mod tests { let torrent_guard = self.lock_or_panic(); let torrent_entry_info = TorrentEntryInfo { - swarm_metadata: torrent_guard.get_swarm_metadata(), - peers: torrent_guard.swarm_peers(None).iter().map(|peer| *peer.clone()).collect(), - number_of_peers: torrent_guard.swarm_len(), + swarm_metadata: torrent_guard.metadata(), + peers: torrent_guard.peers(None).iter().map(|peer| *peer.clone()).collect(), + number_of_peers: torrent_guard.len(), }; drop(torrent_guard); diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index f8be53361..242ffec70 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -15,8 +15,8 @@ pub(crate) enum Torrent { impl Torrent { pub(crate) fn get_stats(&self) -> SwarmMetadata { match self { - Torrent::Single(entry) => entry.get_swarm_metadata(), - Torrent::MutexStd(entry) => entry.lock_or_panic().get_swarm_metadata(), + Torrent::Single(entry) => entry.metadata(), + Torrent::MutexStd(entry) => entry.lock_or_panic().metadata(), } } @@ -29,29 +29,29 @@ impl Torrent { pub(crate) fn peers_is_empty(&self) -> bool { match self { - Torrent::Single(entry) => entry.swarm_is_empty(), - Torrent::MutexStd(entry) => entry.lock_or_panic().swarm_is_empty(), + Torrent::Single(entry) => entry.is_empty(), + Torrent::MutexStd(entry) => entry.lock_or_panic().is_empty(), } } pub(crate) fn get_peers_len(&self) -> usize { match self { - Torrent::Single(entry) => entry.swarm_len(), - Torrent::MutexStd(entry) => entry.lock_or_panic().swarm_len(), + Torrent::Single(entry) => entry.len(), + Torrent::MutexStd(entry) => entry.lock_or_panic().len(), } } pub(crate) fn get_peers(&self, limit: Option) -> Vec> { match self { - Torrent::Single(entry) => entry.swarm_peers(limit), - Torrent::MutexStd(entry) => entry.lock_or_panic().swarm_peers(limit), + Torrent::Single(entry) => entry.peers(limit), + Torrent::MutexStd(entry) => entry.lock_or_panic().peers(limit), } } pub(crate) fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { match self { - Torrent::Single(entry) => entry.get_peers_for_client(client, limit), - Torrent::MutexStd(entry) => entry.lock_or_panic().get_peers_for_client(client, limit), + Torrent::Single(entry) => entry.peers_excluding(client, limit), + Torrent::MutexStd(entry) => entry.lock_or_panic().peers_excluding(client, limit), } } @@ -64,8 +64,8 @@ impl Torrent { pub(crate) fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { match self { - Torrent::Single(entry) => entry.remove_inactive_peers(current_cutoff), - Torrent::MutexStd(entry) => entry.lock_or_panic().remove_inactive_peers(current_cutoff), + Torrent::Single(entry) => entry.remove_inactive(current_cutoff), + Torrent::MutexStd(entry) => entry.lock_or_panic().remove_inactive(current_cutoff), } } } diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 40dcff6db..783606a40 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -320,7 +320,7 @@ async fn it_should_get_metrics(#[values(skip_list_mutex_std())] repo: TorrentRep let mut metrics = AggregateSwarmMetadata::default(); for (_, torrent) in entries { - let stats = torrent.get_swarm_metadata(); + let stats = torrent.metadata(); metrics.total_torrents += 1; metrics.total_incomplete += u64::from(stats.incomplete); @@ -457,7 +457,7 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: { let lock_tracked_torrent = repo.get(&info_hash).expect("it_should_get_some"); let entry = lock_tracked_torrent.lock_or_panic(); - assert!(entry.swarm_peers(None).contains(&peer.into())); + assert!(entry.peers(None).contains(&peer.into())); } // Remove peers that have not been updated since the timeout (120 seconds ago). @@ -469,7 +469,7 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: { let lock_tracked_torrent = repo.get(&info_hash).expect("it_should_get_some"); let entry = lock_tracked_torrent.lock_or_panic(); - assert!(!entry.swarm_peers(None).contains(&peer.into())); + assert!(!entry.peers(None).contains(&peer.into())); } } diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index ece0c87e6..fac0a38c8 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -657,10 +657,10 @@ mod tests { .expect("it should be able to get entry"); // It persists the number of completed peers. - assert_eq!(torrent_entry.lock_or_panic().get_swarm_metadata().downloaded, 1); + assert_eq!(torrent_entry.lock_or_panic().metadata().downloaded, 1); // It does not persist the peers - assert!(torrent_entry.lock_or_panic().swarm_is_empty()); + assert!(torrent_entry.lock_or_panic().is_empty()); } } diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index ae7c61741..5c8352f11 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -165,7 +165,7 @@ mod tests { .get(&infohash) .unwrap() .lock_or_panic() - .get_swarm_metadata() + .metadata() .downloaded, 1 ); diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index b748cd3a0..a35fd7aed 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -99,9 +99,9 @@ pub fn get_torrent_info(in_memory_torrent_repository: &Arc = vec![]; for (info_hash, torrent_entry) in in_memory_torrent_repository.get_paginated(pagination) { - let stats = torrent_entry.lock_or_panic().get_swarm_metadata(); + let stats = torrent_entry.lock_or_panic().metadata(); basic_infos.push(BasicInfo { info_hash, @@ -184,7 +184,7 @@ pub fn get_torrents(in_memory_torrent_repository: &Arc Date: Tue, 6 May 2025 18:05:59 +0100 Subject: [PATCH 1064/1297] refactor: [#1495] remove unneeded TrackedTorrent (wrapper over Swarm) --- packages/torrent-repository/src/entry/mod.rs | 1 - .../torrent-repository/src/entry/torrent.rs | 68 ------------------- packages/torrent-repository/src/lib.rs | 10 +-- packages/torrent-repository/src/repository.rs | 5 +- .../tests/common/torrent.rs | 2 +- .../torrent-repository/tests/entry/mod.rs | 2 +- .../tests/repository/mod.rs | 30 ++++---- 7 files changed, 24 insertions(+), 94 deletions(-) delete mode 100644 packages/torrent-repository/src/entry/torrent.rs diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs index 94fdcc58e..899c10d57 100644 --- a/packages/torrent-repository/src/entry/mod.rs +++ b/packages/torrent-repository/src/entry/mod.rs @@ -1,2 +1 @@ pub mod swarm; -pub mod torrent; diff --git a/packages/torrent-repository/src/entry/torrent.rs b/packages/torrent-repository/src/entry/torrent.rs deleted file mode 100644 index 69a809a37..000000000 --- a/packages/torrent-repository/src/entry/torrent.rs +++ /dev/null @@ -1,68 +0,0 @@ -use std::fmt::Debug; -use std::net::SocketAddr; -use std::sync::Arc; - -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::peer::{self}; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::DurationSinceUnixEpoch; - -use super::swarm::Swarm; - -/// A data structure containing all the information about a torrent in the -/// tracker. -/// -/// This is the tracker entry for a given torrent and contains the swarm data, -/// that's the list of all the peers trying to download the same torrent. -/// -/// The tracker keeps one entry like this for every torrent. -#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct TrackedTorrent { - /// A network of peers that are all trying to download the torrent. - swarm: Swarm, -} - -impl TrackedTorrent { - #[must_use] - pub fn new(swarm: Swarm) -> Self { - Self { swarm } - } - - #[must_use] - pub fn metadata(&self) -> SwarmMetadata { - self.swarm.metadata() - } - - #[must_use] - pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { - self.swarm.meets_retaining_policy(policy) - } - - #[must_use] - pub fn is_empty(&self) -> bool { - self.swarm.is_empty() - } - - #[must_use] - pub fn len(&self) -> usize { - self.swarm.len() - } - - #[must_use] - pub fn peers(&self, limit: Option) -> Vec> { - self.swarm.peers(limit) - } - - #[must_use] - pub fn peers_excluding(&self, client: &SocketAddr, limit: Option) -> Vec> { - self.swarm.peers_excluding(client, limit) - } - - pub fn handle_announcement(&mut self, peer: &peer::Peer) -> bool { - self.swarm.handle_announcement(peer) - } - - pub fn remove_inactive(&mut self, current_cutoff: DurationSinceUnixEpoch) { - self.swarm.remove_inactive(current_cutoff); - } -} diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index d7042a1fd..12b205681 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -6,8 +6,8 @@ use std::sync::{Arc, Mutex, MutexGuard}; use torrust_tracker_clock::clock; pub type TorrentRepository = repository::TorrentRepository; -pub type TrackedTorrentHandle = Arc>; -pub type TrackedTorrent = entry::torrent::TrackedTorrent; +pub type TrackedTorrentHandle = Arc>; +pub type Swarm = entry::swarm::Swarm; /// Working version, for production. #[cfg(not(test))] @@ -20,11 +20,11 @@ pub(crate) type CurrentClock = clock::Working; pub(crate) type CurrentClock = clock::Stopped; pub trait LockTrackedTorrent { - fn lock_or_panic(&self) -> MutexGuard<'_, TrackedTorrent>; + fn lock_or_panic(&self) -> MutexGuard<'_, Swarm>; } -impl LockTrackedTorrent for Arc> { - fn lock_or_panic(&self) -> MutexGuard<'_, TrackedTorrent> { +impl LockTrackedTorrent for Arc> { + fn lock_or_panic(&self) -> MutexGuard<'_, Swarm> { self.lock().expect("can't acquire lock for tracked torrent handle") } } diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index 1706937fc..2a5a38a3f 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -8,7 +8,6 @@ use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMe use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use crate::entry::swarm::Swarm; -use crate::entry::torrent::TrackedTorrent; use crate::{LockTrackedTorrent, TrackedTorrentHandle}; #[derive(Default, Debug)] @@ -51,7 +50,7 @@ impl TorrentRepository { tracing::debug!("Inserting new torrent: {:?}", info_hash); let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { - TrackedTorrentHandle::new(TrackedTorrent::new(Swarm::new(number_of_downloads)).into()) + TrackedTorrentHandle::new(Swarm::new(number_of_downloads).into()) } else { TrackedTorrentHandle::default() }; @@ -229,7 +228,7 @@ impl TorrentRepository { continue; } - let entry = TrackedTorrentHandle::new(TrackedTorrent::new(Swarm::new(*completed)).into()); + let entry = TrackedTorrentHandle::new(Swarm::new(*completed).into()); // Since SkipMap is lock-free the torrent could have been inserted // after checking if it exists. diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index 242ffec70..e991cc7c9 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -8,7 +8,7 @@ use torrust_tracker_torrent_repository::{entry, LockTrackedTorrent, TrackedTorre #[derive(Debug, Clone)] pub(crate) enum Torrent { - Single(entry::torrent::TrackedTorrent), + Single(entry::swarm::Swarm), MutexStd(TrackedTorrentHandle), } diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index 5f958f05c..ab1848ed1 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -17,7 +17,7 @@ use crate::CurrentClock; #[fixture] fn single() -> Torrent { - Torrent::Single(entry::torrent::TrackedTorrent::default()) + Torrent::Single(entry::swarm::Swarm::default()) } #[fixture] fn mutex_std() -> Torrent { diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 783606a40..3515a38cc 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -9,7 +9,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::PersistentTorrents; -use torrust_tracker_torrent_repository::entry::torrent::TrackedTorrent; +use torrust_tracker_torrent_repository::entry::swarm::Swarm; use torrust_tracker_torrent_repository::{LockTrackedTorrent, TorrentRepository}; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; @@ -19,7 +19,7 @@ fn skip_list_mutex_std() -> TorrentRepository { TorrentRepository::default() } -type Entries = Vec<(InfoHash, TrackedTorrent)>; +type Entries = Vec<(InfoHash, Swarm)>; #[fixture] fn empty() -> Entries { @@ -28,26 +28,26 @@ fn empty() -> Entries { #[fixture] fn default() -> Entries { - vec![(InfoHash::default(), TrackedTorrent::default())] + vec![(InfoHash::default(), Swarm::default())] } #[fixture] fn started() -> Entries { - let mut torrent = TrackedTorrent::default(); + let mut torrent = Swarm::default(); torrent.handle_announcement(&a_started_peer(1)); vec![(InfoHash::default(), torrent)] } #[fixture] fn completed() -> Entries { - let mut torrent = TrackedTorrent::default(); + let mut torrent = Swarm::default(); torrent.handle_announcement(&a_completed_peer(2)); vec![(InfoHash::default(), torrent)] } #[fixture] fn downloaded() -> Entries { - let mut torrent = TrackedTorrent::default(); + let mut torrent = Swarm::default(); let mut peer = a_started_peer(3); torrent.handle_announcement(&peer); peer.event = AnnounceEvent::Completed; @@ -58,17 +58,17 @@ fn downloaded() -> Entries { #[fixture] fn three() -> Entries { - let mut started = TrackedTorrent::default(); + let mut started = Swarm::default(); let started_h = &mut DefaultHasher::default(); started.handle_announcement(&a_started_peer(1)); started.hash(started_h); - let mut completed = TrackedTorrent::default(); + let mut completed = Swarm::default(); let completed_h = &mut DefaultHasher::default(); completed.handle_announcement(&a_completed_peer(2)); completed.hash(completed_h); - let mut downloaded = TrackedTorrent::default(); + let mut downloaded = Swarm::default(); let downloaded_h = &mut DefaultHasher::default(); let mut downloaded_peer = a_started_peer(3); downloaded.handle_announcement(&downloaded_peer); @@ -86,10 +86,10 @@ fn three() -> Entries { #[fixture] fn many_out_of_order() -> Entries { - let mut entries: HashSet<(InfoHash, TrackedTorrent)> = HashSet::default(); + let mut entries: HashSet<(InfoHash, Swarm)> = HashSet::default(); for i in 0..408 { - let mut entry = TrackedTorrent::default(); + let mut entry = Swarm::default(); entry.handle_announcement(&a_started_peer(i)); entries.insert((InfoHash::from(&i), entry)); @@ -101,10 +101,10 @@ fn many_out_of_order() -> Entries { #[fixture] fn many_hashed_in_order() -> Entries { - let mut entries: BTreeMap = BTreeMap::default(); + let mut entries: BTreeMap = BTreeMap::default(); for i in 0..408 { - let mut entry = TrackedTorrent::default(); + let mut entry = Swarm::default(); entry.handle_announcement(&a_started_peer(i)); let hash: &mut DefaultHasher = &mut DefaultHasher::default(); @@ -269,7 +269,7 @@ async fn it_should_get_paginated( match paginated { // it should return empty if limit is zero. Pagination { limit: 0, .. } => { - let torrents: Vec<(InfoHash, TrackedTorrent)> = repo + let torrents: Vec<(InfoHash, Swarm)> = repo .get_paginated(Some(&paginated)) .iter() .map(|(i, lock_tracked_torrent)| (*i, lock_tracked_torrent.lock_or_panic().clone())) @@ -492,7 +492,7 @@ async fn it_should_remove_peerless_torrents( repo.remove_peerless_torrents(&policy); - let torrents: Vec<(InfoHash, TrackedTorrent)> = repo + let torrents: Vec<(InfoHash, Swarm)> = repo .get_paginated(None) .iter() .map(|(i, lock_tracked_torrent)| (*i, lock_tracked_torrent.lock_or_panic().clone())) From 030ae26bd27a8742c757badb992d807d9af7171b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 18:12:14 +0100 Subject: [PATCH 1065/1297] refactor: [#1495] reorganize torrent-repository mod --- packages/torrent-repository/src/entry/mod.rs | 1 - packages/torrent-repository/src/lib.rs | 4 ++-- packages/torrent-repository/src/repository.rs | 2 +- packages/torrent-repository/src/{entry => }/swarm.rs | 10 +++++----- packages/torrent-repository/tests/common/torrent.rs | 4 ++-- packages/torrent-repository/tests/entry/mod.rs | 4 ++-- packages/torrent-repository/tests/repository/mod.rs | 2 +- 7 files changed, 13 insertions(+), 14 deletions(-) delete mode 100644 packages/torrent-repository/src/entry/mod.rs rename packages/torrent-repository/src/{entry => }/swarm.rs (99%) diff --git a/packages/torrent-repository/src/entry/mod.rs b/packages/torrent-repository/src/entry/mod.rs deleted file mode 100644 index 899c10d57..000000000 --- a/packages/torrent-repository/src/entry/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod swarm; diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 12b205681..3748cb171 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,5 +1,5 @@ -pub mod entry; pub mod repository; +pub mod swarm; use std::sync::{Arc, Mutex, MutexGuard}; @@ -7,7 +7,7 @@ use torrust_tracker_clock::clock; pub type TorrentRepository = repository::TorrentRepository; pub type TrackedTorrentHandle = Arc>; -pub type Swarm = entry::swarm::Swarm; +pub type Swarm = swarm::Swarm; /// Working version, for production. #[cfg(not(test))] diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index 2a5a38a3f..2c1330c20 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -7,7 +7,7 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use crate::entry::swarm::Swarm; +use crate::swarm::Swarm; use crate::{LockTrackedTorrent, TrackedTorrentHandle}; #[derive(Default, Debug)] diff --git a/packages/torrent-repository/src/entry/swarm.rs b/packages/torrent-repository/src/swarm.rs similarity index 99% rename from packages/torrent-repository/src/entry/swarm.rs rename to packages/torrent-repository/src/swarm.rs index eb7aebfe4..78602f3d9 100644 --- a/packages/torrent-repository/src/entry/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -218,7 +218,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::entry::swarm::Swarm; + use crate::swarm::Swarm; #[test] fn it_should_be_empty_when_no_peers_have_been_inserted() { @@ -483,7 +483,7 @@ mod tests { mod when_a_new_peer_is_added { use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::entry::swarm::Swarm; + use crate::swarm::Swarm; #[test] fn it_should_increase_the_number_of_leechers_if_the_new_peer_is_a_leecher_() { @@ -532,7 +532,7 @@ mod tests { mod when_a_peer_is_removed { use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::entry::swarm::Swarm; + use crate::swarm::Swarm; #[test] fn it_should_decrease_the_number_of_leechers_if_the_removed_peer_was_a_leecher() { @@ -572,7 +572,7 @@ mod tests { use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::entry::swarm::Swarm; + use crate::swarm::Swarm; #[test] fn it_should_decrease_the_number_of_leechers_when_a_removed_peer_is_a_leecher() { @@ -611,7 +611,7 @@ mod tests { use aquatic_udp_protocol::NumberOfBytes; use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::entry::swarm::Swarm; + use crate::swarm::Swarm; #[test] fn it_should_increase_seeders_and_decreasing_leechers_when_the_peer_changes_from_leecher_to_seeder_() { diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index e991cc7c9..197032cb4 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -4,11 +4,11 @@ use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; -use torrust_tracker_torrent_repository::{entry, LockTrackedTorrent, TrackedTorrentHandle}; +use torrust_tracker_torrent_repository::{swarm, LockTrackedTorrent, TrackedTorrentHandle}; #[derive(Debug, Clone)] pub(crate) enum Torrent { - Single(entry::swarm::Swarm), + Single(swarm::Swarm), MutexStd(TrackedTorrentHandle), } diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index ab1848ed1..9b16f8c4a 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -9,7 +9,7 @@ use torrust_tracker_clock::clock::{self, Time as _}; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_torrent_repository::{entry, TrackedTorrentHandle}; +use torrust_tracker_torrent_repository::{swarm, TrackedTorrentHandle}; use crate::common::torrent::Torrent; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; @@ -17,7 +17,7 @@ use crate::CurrentClock; #[fixture] fn single() -> Torrent { - Torrent::Single(entry::swarm::Swarm::default()) + Torrent::Single(swarm::Swarm::default()) } #[fixture] fn mutex_std() -> Torrent { diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 3515a38cc..1595db335 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -9,7 +9,7 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::PersistentTorrents; -use torrust_tracker_torrent_repository::entry::swarm::Swarm; +use torrust_tracker_torrent_repository::swarm::Swarm; use torrust_tracker_torrent_repository::{LockTrackedTorrent, TorrentRepository}; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; From 78d4b83b4e3ab36bd9f8252768142b09f74c6786 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 18:13:09 +0100 Subject: [PATCH 1066/1297] refactor: [#1495] rename TrackedTorrentHandle to SwarmHandle --- packages/torrent-repository/src/lib.rs | 2 +- packages/torrent-repository/src/repository.rs | 20 +++++++++---------- .../tests/common/torrent.rs | 4 ++-- .../torrent-repository/tests/entry/mod.rs | 4 ++-- .../src/torrent/repository/in_memory.rs | 8 ++++---- 5 files changed, 19 insertions(+), 19 deletions(-) diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 3748cb171..76ef6c784 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -6,7 +6,7 @@ use std::sync::{Arc, Mutex, MutexGuard}; use torrust_tracker_clock::clock; pub type TorrentRepository = repository::TorrentRepository; -pub type TrackedTorrentHandle = Arc>; +pub type SwarmHandle = Arc>; pub type Swarm = swarm::Swarm; /// Working version, for production. diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/repository.rs index 2c1330c20..fd30b4714 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/repository.rs @@ -8,11 +8,11 @@ use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMe use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use crate::swarm::Swarm; -use crate::{LockTrackedTorrent, TrackedTorrentHandle}; +use crate::{LockTrackedTorrent, SwarmHandle}; #[derive(Default, Debug)] pub struct TorrentRepository { - pub torrents: SkipMap, + pub torrents: SkipMap, } impl TorrentRepository { @@ -50,9 +50,9 @@ impl TorrentRepository { tracing::debug!("Inserting new torrent: {:?}", info_hash); let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { - TrackedTorrentHandle::new(Swarm::new(number_of_downloads).into()) + SwarmHandle::new(Swarm::new(number_of_downloads).into()) } else { - TrackedTorrentHandle::default() + SwarmHandle::default() }; let inserted_entry = self.torrents.get_or_insert(*info_hash, new_entry); @@ -69,7 +69,7 @@ impl TorrentRepository { /// /// An `Option` containing the removed torrent entry if it existed. #[must_use] - pub fn remove(&self, key: &InfoHash) -> Option { + pub fn remove(&self, key: &InfoHash) -> Option { self.torrents.remove(key).map(|entry| entry.value().clone()) } @@ -93,7 +93,7 @@ impl TorrentRepository { /// /// An `Option` containing the tracked torrent handle if found. #[must_use] - pub fn get(&self, key: &InfoHash) -> Option { + pub fn get(&self, key: &InfoHash) -> Option { let maybe_entry = self.torrents.get(key); maybe_entry.map(|entry| entry.value().clone()) } @@ -108,7 +108,7 @@ impl TorrentRepository { /// /// A vector of `(InfoHash, TorrentEntry)` tuples. #[must_use] - pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, TrackedTorrentHandle)> { + pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, SwarmHandle)> { match pagination { Some(pagination) => self .torrents @@ -228,7 +228,7 @@ impl TorrentRepository { continue; } - let entry = TrackedTorrentHandle::new(Swarm::new(*completed).into()); + let entry = SwarmHandle::new(Swarm::new(*completed).into()); // Since SkipMap is lock-free the torrent could have been inserted // after checking if it exists. @@ -541,7 +541,7 @@ mod tests { use crate::repository::TorrentRepository; use crate::tests::{sample_info_hash, sample_peer}; - use crate::{LockTrackedTorrent, TrackedTorrentHandle}; + use crate::{LockTrackedTorrent, SwarmHandle}; /// `TorrentEntry` data is not directly accessible. It's only /// accessible through the trait methods. We need this temporary @@ -554,7 +554,7 @@ mod tests { } #[allow(clippy::from_over_into)] - impl Into for TrackedTorrentHandle { + impl Into for SwarmHandle { fn into(self) -> TorrentEntryInfo { let torrent_guard = self.lock_or_panic(); diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs index 197032cb4..a1899621f 100644 --- a/packages/torrent-repository/tests/common/torrent.rs +++ b/packages/torrent-repository/tests/common/torrent.rs @@ -4,12 +4,12 @@ use std::sync::Arc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; -use torrust_tracker_torrent_repository::{swarm, LockTrackedTorrent, TrackedTorrentHandle}; +use torrust_tracker_torrent_repository::{swarm, LockTrackedTorrent, SwarmHandle}; #[derive(Debug, Clone)] pub(crate) enum Torrent { Single(swarm::Swarm), - MutexStd(TrackedTorrentHandle), + MutexStd(SwarmHandle), } impl Torrent { diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index 9b16f8c4a..4607fd9c7 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -9,7 +9,7 @@ use torrust_tracker_clock::clock::{self, Time as _}; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_torrent_repository::{swarm, TrackedTorrentHandle}; +use torrust_tracker_torrent_repository::{swarm, SwarmHandle}; use crate::common::torrent::Torrent; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; @@ -21,7 +21,7 @@ fn single() -> Torrent { } #[fixture] fn mutex_std() -> Torrent { - Torrent::MutexStd(TrackedTorrentHandle::default()) + Torrent::MutexStd(SwarmHandle::default()) } #[fixture] diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index e362b20c1..98d7eb682 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -7,7 +7,7 @@ use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use torrust_tracker_torrent_repository::{TorrentRepository, TrackedTorrentHandle}; +use torrust_tracker_torrent_repository::{SwarmHandle, TorrentRepository}; /// In-memory repository for torrent entries. /// @@ -64,7 +64,7 @@ impl InMemoryTorrentRepository { /// An `Option` containing the removed torrent entry if it existed. #[cfg(test)] #[must_use] - pub(crate) fn remove(&self, key: &InfoHash) -> Option { + pub(crate) fn remove(&self, key: &InfoHash) -> Option { self.torrents.remove(key) } @@ -104,7 +104,7 @@ impl InMemoryTorrentRepository { /// /// An `Option` containing the torrent entry if found. #[must_use] - pub(crate) fn get(&self, key: &InfoHash) -> Option { + pub(crate) fn get(&self, key: &InfoHash) -> Option { self.torrents.get(key) } @@ -122,7 +122,7 @@ impl InMemoryTorrentRepository { /// /// A vector of `(InfoHash, TorrentEntry)` tuples. #[must_use] - pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, TrackedTorrentHandle)> { + pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, SwarmHandle)> { self.torrents.get_paginated(pagination) } From 0411a9a464554e039cbdd806c95b9bdd443ef155 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 18:16:05 +0100 Subject: [PATCH 1067/1297] refactor: [#1495] rename TorrentRepository to Swarms --- packages/torrent-repository/src/lib.rs | 4 +- .../src/{repository.rs => swarms.rs} | 108 +++++++++--------- .../tests/repository/mod.rs | 26 ++--- .../src/torrent/repository/in_memory.rs | 4 +- 4 files changed, 71 insertions(+), 71 deletions(-) rename packages/torrent-repository/src/{repository.rs => swarms.rs} (90%) diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 76ef6c784..f120afe88 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,11 +1,11 @@ -pub mod repository; +pub mod swarms; pub mod swarm; use std::sync::{Arc, Mutex, MutexGuard}; use torrust_tracker_clock::clock; -pub type TorrentRepository = repository::TorrentRepository; +pub type Swarms = swarms::Swarms; pub type SwarmHandle = Arc>; pub type Swarm = swarm::Swarm; diff --git a/packages/torrent-repository/src/repository.rs b/packages/torrent-repository/src/swarms.rs similarity index 90% rename from packages/torrent-repository/src/repository.rs rename to packages/torrent-repository/src/swarms.rs index fd30b4714..b5b891a2b 100644 --- a/packages/torrent-repository/src/repository.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -11,11 +11,11 @@ use crate::swarm::Swarm; use crate::{LockTrackedTorrent, SwarmHandle}; #[derive(Default, Debug)] -pub struct TorrentRepository { - pub torrents: SkipMap, +pub struct Swarms { + pub swarms: SkipMap, } -impl TorrentRepository { +impl Swarms { /// Upsert a peer into the swarm of a torrent. /// /// Optionally, it can also preset the number of downloads of the torrent @@ -42,7 +42,7 @@ impl TorrentRepository { peer: &peer::Peer, opt_persistent_torrent: Option, ) -> bool { - if let Some(existing_entry) = self.torrents.get(info_hash) { + if let Some(existing_entry) = self.swarms.get(info_hash) { tracing::debug!("Torrent already exists: {:?}", info_hash); existing_entry.value().lock_or_panic().handle_announcement(peer) @@ -55,7 +55,7 @@ impl TorrentRepository { SwarmHandle::default() }; - let inserted_entry = self.torrents.get_or_insert(*info_hash, new_entry); + let inserted_entry = self.swarms.get_or_insert(*info_hash, new_entry); let mut torrent_guard = inserted_entry.value().lock_or_panic(); @@ -70,7 +70,7 @@ impl TorrentRepository { /// An `Option` containing the removed torrent entry if it existed. #[must_use] pub fn remove(&self, key: &InfoHash) -> Option { - self.torrents.remove(key).map(|entry| entry.value().clone()) + self.swarms.remove(key).map(|entry| entry.value().clone()) } /// Removes inactive peers from all torrent entries. @@ -82,7 +82,7 @@ impl TorrentRepository { /// /// This function panics if the lock for the entry cannot be obtained. pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - for entry in &self.torrents { + for entry in &self.swarms { entry.value().lock_or_panic().remove_inactive(current_cutoff); } } @@ -94,7 +94,7 @@ impl TorrentRepository { /// An `Option` containing the tracked torrent handle if found. #[must_use] pub fn get(&self, key: &InfoHash) -> Option { - let maybe_entry = self.torrents.get(key); + let maybe_entry = self.swarms.get(key); maybe_entry.map(|entry| entry.value().clone()) } @@ -111,14 +111,14 @@ impl TorrentRepository { pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, SwarmHandle)> { match pagination { Some(pagination) => self - .torrents + .swarms .iter() .skip(pagination.offset as usize) .take(pagination.limit as usize) .map(|entry| (*entry.key(), entry.value().clone())) .collect(), None => self - .torrents + .swarms .iter() .map(|entry| (*entry.key(), entry.value().clone())) .collect(), @@ -136,7 +136,7 @@ impl TorrentRepository { /// This function panics if the lock for the entry cannot be obtained. #[must_use] pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.torrents + self.swarms .get(info_hash) .map(|entry| entry.value().lock_or_panic().metadata()) } @@ -208,7 +208,7 @@ impl TorrentRepository { /// /// This function panics if the lock for the entry cannot be obtained. pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - for entry in &self.torrents { + for entry in &self.swarms { if entry.value().lock_or_panic().meets_retaining_policy(policy) { continue; } @@ -224,7 +224,7 @@ impl TorrentRepository { /// access. pub fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { for (info_hash, completed) in persistent_torrents { - if self.torrents.contains_key(info_hash) { + if self.swarms.contains_key(info_hash) { continue; } @@ -232,7 +232,7 @@ impl TorrentRepository { // Since SkipMap is lock-free the torrent could have been inserted // after checking if it exists. - self.torrents.get_or_insert(*info_hash, entry); + self.swarms.get_or_insert(*info_hash, entry); } } @@ -253,7 +253,7 @@ impl TorrentRepository { pub fn get_aggregate_swarm_metadata(&self) -> AggregateSwarmMetadata { let mut metrics = AggregateSwarmMetadata::default(); - for entry in &self.torrents { + for entry in &self.swarms { let stats = entry.value().lock_or_panic().metadata(); metrics.total_complete += u64::from(stats.complete); metrics.total_downloaded += u64::from(stats.downloaded); @@ -304,12 +304,12 @@ mod tests { use std::sync::Arc; - use crate::repository::TorrentRepository; + use crate::swarms::Swarms; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] async fn it_should_add_the_first_peer_to_the_torrent_peer_list() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); @@ -320,7 +320,7 @@ mod tests { #[tokio::test] async fn it_should_allow_adding_the_same_peer_twice_to_the_torrent_peer_list() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); @@ -340,13 +340,13 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::repository::tests::the_in_memory_torrent_repository::numeric_peer_id; - use crate::repository::TorrentRepository; + use crate::swarms::tests::the_in_memory_torrent_repository::numeric_peer_id; + use crate::swarms::Swarms; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); @@ -360,7 +360,7 @@ mod tests { #[tokio::test] async fn it_should_return_an_empty_list_or_peers_for_a_non_existing_torrent() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let peers = torrent_repository.get_torrent_peers(&sample_info_hash(), 74); @@ -369,7 +369,7 @@ mod tests { #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); @@ -402,13 +402,13 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::repository::tests::the_in_memory_torrent_repository::numeric_peer_id; - use crate::repository::TorrentRepository; + use crate::swarms::tests::the_in_memory_torrent_repository::numeric_peer_id; + use crate::swarms::Swarms; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] async fn it_should_return_an_empty_peer_list_for_a_non_existing_torrent() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let peers = torrent_repository.get_peers_for(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT); @@ -417,7 +417,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); @@ -431,7 +431,7 @@ mod tests { #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); @@ -471,12 +471,12 @@ mod tests { use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::repository::TorrentRepository; + use crate::swarms::Swarms; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] async fn it_should_remove_a_torrent_entry() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); @@ -488,7 +488,7 @@ mod tests { #[tokio::test] async fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); let mut peer = sample_peer(); @@ -502,8 +502,8 @@ mod tests { assert!(!torrent_repository.get_torrent_peers(&info_hash, 74).contains(&Arc::new(peer))); } - fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { - let torrent_repository = Arc::new(TorrentRepository::default()); + fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { + let torrent_repository = Arc::new(Swarms::default()); // Insert a sample peer for the torrent to force adding the torrent entry let mut peer = sample_peer(); @@ -539,7 +539,7 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::repository::TorrentRepository; + use crate::swarms::Swarms; use crate::tests::{sample_info_hash, sample_peer}; use crate::{LockTrackedTorrent, SwarmHandle}; @@ -572,7 +572,7 @@ mod tests { #[tokio::test] async fn it_should_return_one_torrent_entry_by_infohash() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); @@ -600,13 +600,13 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::repository::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; - use crate::repository::TorrentRepository; + use crate::swarms::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; + use crate::swarms::Swarms; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] async fn without_pagination() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); @@ -638,8 +638,8 @@ mod tests { use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::repository::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; - use crate::repository::TorrentRepository; + use crate::swarms::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; + use crate::swarms::Swarms; use crate::tests::{ sample_info_hash_alphabetically_ordered_after_sample_info_hash_one, sample_info_hash_one, sample_peer_one, sample_peer_two, @@ -647,7 +647,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_first_page() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); // Insert one torrent entry let info_hash_one = sample_info_hash_one(); @@ -682,7 +682,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_second_page() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); // Insert one torrent entry let info_hash_one = sample_info_hash_one(); @@ -717,7 +717,7 @@ mod tests { #[tokio::test] async fn it_should_allow_changing_the_page_size() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); // Insert one torrent entry let info_hash_one = sample_info_hash_one(); @@ -745,14 +745,14 @@ mod tests { use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; - use crate::repository::TorrentRepository; + use crate::swarms::Swarms; use crate::tests::{complete_peer, leecher, sample_info_hash, seeder}; // todo: refactor to use test parametrization #[tokio::test] async fn it_should_get_empty_aggregate_swarm_metadata_when_there_are_no_torrents() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata(); @@ -769,7 +769,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_leecher() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let _number_of_downloads_increased = torrent_repository.upsert_peer(&sample_info_hash(), &leecher(), None); @@ -788,7 +788,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_seeder() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let _number_of_downloads_increased = torrent_repository.upsert_peer(&sample_info_hash(), &seeder(), None); @@ -807,7 +807,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_completed_peer() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let _number_of_downloads_increased = torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer(), None); @@ -826,7 +826,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_are_multiple_torrents() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let start_time = std::time::Instant::now(); for i in 0..1_000_000 { @@ -858,12 +858,12 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::repository::TorrentRepository; + use crate::swarms::Swarms; use crate::tests::{leecher, sample_info_hash}; #[tokio::test] async fn it_should_get_swarm_metadata_for_an_existing_torrent() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let infohash = sample_info_hash(); @@ -883,7 +883,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_for_a_non_existing_torrent() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&sample_info_hash()); @@ -897,12 +897,12 @@ mod tests { use torrust_tracker_primitives::PersistentTorrents; - use crate::repository::TorrentRepository; + use crate::swarms::Swarms; use crate::tests::sample_info_hash; #[tokio::test] async fn it_should_allow_importing_persisted_torrent_entries() { - let torrent_repository = Arc::new(TorrentRepository::default()); + let torrent_repository = Arc::new(Swarms::default()); let infohash = sample_info_hash(); diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 1595db335..4c9053b7e 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -10,13 +10,13 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::PersistentTorrents; use torrust_tracker_torrent_repository::swarm::Swarm; -use torrust_tracker_torrent_repository::{LockTrackedTorrent, TorrentRepository}; +use torrust_tracker_torrent_repository::{LockTrackedTorrent, Swarms}; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; #[fixture] -fn skip_list_mutex_std() -> TorrentRepository { - TorrentRepository::default() +fn skip_list_mutex_std() -> Swarms { + Swarms::default() } type Entries = Vec<(InfoHash, Swarm)>; @@ -148,10 +148,10 @@ fn persistent_three() -> PersistentTorrents { t.iter().copied().collect() } -fn make(repo: &TorrentRepository, entries: &Entries) { +fn make(repo: &Swarms, entries: &Entries) { for (info_hash, entry) in entries { let new = Arc::new(Mutex::new(entry.clone())); - repo.torrents.insert(*info_hash, new); + repo.swarms.insert(*info_hash, new); } } @@ -200,7 +200,7 @@ fn policy_remove_persist() -> TrackerPolicy { #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_get_a_torrent_entry(#[values(skip_list_mutex_std())] repo: TorrentRepository, #[case] entries: Entries) { +async fn it_should_get_a_torrent_entry(#[values(skip_list_mutex_std())] repo: Swarms, #[case] entries: Entries) { make(&repo, &entries); if let Some((info_hash, torrent)) = entries.first() { @@ -224,7 +224,7 @@ async fn it_should_get_a_torrent_entry(#[values(skip_list_mutex_std())] repo: To #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( - #[values(skip_list_mutex_std())] repo: TorrentRepository, + #[values(skip_list_mutex_std())] repo: Swarms, #[case] entries: Entries, many_out_of_order: Entries, ) { @@ -257,7 +257,7 @@ async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_get_paginated( - #[values(skip_list_mutex_std())] repo: TorrentRepository, + #[values(skip_list_mutex_std())] repo: Swarms, #[case] entries: Entries, #[values(paginated_limit_zero(), paginated_limit_one(), paginated_limit_one_offset_one())] paginated: Pagination, ) { @@ -312,7 +312,7 @@ async fn it_should_get_paginated( #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_get_metrics(#[values(skip_list_mutex_std())] repo: TorrentRepository, #[case] entries: Entries) { +async fn it_should_get_metrics(#[values(skip_list_mutex_std())] repo: Swarms, #[case] entries: Entries) { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; make(&repo, &entries); @@ -342,7 +342,7 @@ async fn it_should_get_metrics(#[values(skip_list_mutex_std())] repo: TorrentRep #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_import_persistent_torrents( - #[values(skip_list_mutex_std())] repo: TorrentRepository, + #[values(skip_list_mutex_std())] repo: Swarms, #[case] entries: Entries, #[values(persistent_empty(), persistent_single(), persistent_three())] persistent_torrents: PersistentTorrents, ) { @@ -370,7 +370,7 @@ async fn it_should_import_persistent_torrents( #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_remove_an_entry(#[values(skip_list_mutex_std())] repo: TorrentRepository, #[case] entries: Entries) { +async fn it_should_remove_an_entry(#[values(skip_list_mutex_std())] repo: Swarms, #[case] entries: Entries) { make(&repo, &entries); for (info_hash, torrent) in entries { @@ -397,7 +397,7 @@ async fn it_should_remove_an_entry(#[values(skip_list_mutex_std())] repo: Torren #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: TorrentRepository, #[case] entries: Entries) { +async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: Swarms, #[case] entries: Entries) { use std::ops::Sub as _; use std::time::Duration; @@ -484,7 +484,7 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_remove_peerless_torrents( - #[values(skip_list_mutex_std())] repo: TorrentRepository, + #[values(skip_list_mutex_std())] repo: Swarms, #[case] entries: Entries, #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, ) { diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 98d7eb682..67e532e86 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -7,7 +7,7 @@ use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use torrust_tracker_torrent_repository::{SwarmHandle, TorrentRepository}; +use torrust_tracker_torrent_repository::{SwarmHandle, Swarms}; /// In-memory repository for torrent entries. /// @@ -21,7 +21,7 @@ use torrust_tracker_torrent_repository::{SwarmHandle, TorrentRepository}; #[derive(Debug, Default)] pub struct InMemoryTorrentRepository { /// The underlying in-memory data structure that stores torrent entries. - torrents: Arc, + torrents: Arc, } impl InMemoryTorrentRepository { From 0f4596ef7de53e5806520cb7126e8234d28ab9ce Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 18:31:21 +0100 Subject: [PATCH 1068/1297] fix: [#1495] formatting --- packages/torrent-repository/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index f120afe88..c985f7a2b 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,5 +1,5 @@ -pub mod swarms; pub mod swarm; +pub mod swarms; use std::sync::{Arc, Mutex, MutexGuard}; From 34c159a161b7c167730f6c139dd3cb608173d37a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 18:48:48 +0100 Subject: [PATCH 1069/1297] refactor: [#1495] update method Swarm::meets_retaining_policy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Changed from: ``` /// Returns true if the torrents meets the retention policy, meaning that /// it should be kept in the tracker. pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { if policy.persistent_torrent_completed_stat && self.metadata().downloaded > 0 { return true; } if policy.remove_peerless_torrents && self.is_empty() { return false; } true } ``` To: ``` pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { !(policy.remove_peerless_torrents && self.is_empty()) } ``` I think the first condition was introduced to avoid loosing the number of downloads we¡hen the torrent is removed becuase there are no peers. Now, we load that number from database when the torrent is added again after removing it from the tracker. --- packages/torrent-repository/src/swarm.rs | 38 +++++++++++++++++------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 78602f3d9..1a17a2fb6 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -190,20 +190,11 @@ impl Swarm { self.peers.is_empty() } - /// Returns true if the torrents meets the retention policy, meaning that + /// Returns true if the swarm meets the retention policy, meaning that /// it should be kept in the tracker. #[must_use] pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { - // code-review: why? - if policy.persistent_torrent_completed_stat && self.metadata().downloaded > 0 { - return true; - } - - if policy.remove_peerless_torrents && self.is_empty() { - return false; - } - - true + !(policy.remove_peerless_torrents && self.is_empty()) } } @@ -214,6 +205,7 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::PeerId; + use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; @@ -384,6 +376,30 @@ mod tests { assert_eq!(swarm.len(), 1); } + #[test] + fn it_should_be_kept_when_empty_if_the_tracker_policy_is_not_to_remove_peerless_torrents() { + let empty_swarm = Swarm::default(); + + let policy = TrackerPolicy { + remove_peerless_torrents: false, + ..Default::default() + }; + + assert!(empty_swarm.meets_retaining_policy(&policy)); + } + + #[test] + fn it_should_be_removed_when_empty_if_the_tracker_policy_is_to_remove_peerless_torrents() { + let empty_swarm = Swarm::default(); + + let policy = TrackerPolicy { + remove_peerless_torrents: true, + ..Default::default() + }; + + assert!(!empty_swarm.meets_retaining_policy(&policy)); + } + #[test] fn it_should_allow_inserting_two_identical_peers_except_for_the_socket_address() { let mut swarm = Swarm::default(); From 728de220693828e056b8f5069ddff19589b6825a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 6 May 2025 18:55:41 +0100 Subject: [PATCH 1070/1297] docs: [#1495] add todo --- packages/torrent-repository/src/swarms.rs | 1 + packages/torrent-repository/tests/repository/mod.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index b5b891a2b..936f49d22 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -12,6 +12,7 @@ use crate::{LockTrackedTorrent, SwarmHandle}; #[derive(Default, Debug)] pub struct Swarms { + // todo: this needs to be public only to insert a peerless torrent (empty swarm). pub swarms: SkipMap, } diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/repository/mod.rs index 4c9053b7e..071a187fa 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/repository/mod.rs @@ -151,6 +151,7 @@ fn persistent_three() -> PersistentTorrents { fn make(repo: &Swarms, entries: &Entries) { for (info_hash, entry) in entries { let new = Arc::new(Mutex::new(entry.clone())); + // todo: use a public method to insert an empty swarm. repo.swarms.insert(*info_hash, new); } } From 6f5cb279083ee3b8b47f849e111019dfdea9c3b3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 7 May 2025 10:03:18 +0100 Subject: [PATCH 1071/1297] refactor: [#1495] remove test for SwarmHandle Integration tests will be removed becuase unit tests have been added. Besides, there is no point in testing only the wrapper. SwarmHandle in only a wrapper over Swarm. --- .../torrent-repository/tests/common/mod.rs | 1 - .../tests/common/torrent.rs | 71 ---------- .../torrent-repository/tests/entry/mod.rs | 127 ++++++++---------- 3 files changed, 55 insertions(+), 144 deletions(-) delete mode 100644 packages/torrent-repository/tests/common/torrent.rs diff --git a/packages/torrent-repository/tests/common/mod.rs b/packages/torrent-repository/tests/common/mod.rs index e083a05cc..c77ca2769 100644 --- a/packages/torrent-repository/tests/common/mod.rs +++ b/packages/torrent-repository/tests/common/mod.rs @@ -1,2 +1 @@ -pub mod torrent; pub mod torrent_peer_builder; diff --git a/packages/torrent-repository/tests/common/torrent.rs b/packages/torrent-repository/tests/common/torrent.rs deleted file mode 100644 index a1899621f..000000000 --- a/packages/torrent-repository/tests/common/torrent.rs +++ /dev/null @@ -1,71 +0,0 @@ -use std::net::SocketAddr; -use std::sync::Arc; - -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; -use torrust_tracker_torrent_repository::{swarm, LockTrackedTorrent, SwarmHandle}; - -#[derive(Debug, Clone)] -pub(crate) enum Torrent { - Single(swarm::Swarm), - MutexStd(SwarmHandle), -} - -impl Torrent { - pub(crate) fn get_stats(&self) -> SwarmMetadata { - match self { - Torrent::Single(entry) => entry.metadata(), - Torrent::MutexStd(entry) => entry.lock_or_panic().metadata(), - } - } - - pub(crate) fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { - match self { - Torrent::Single(entry) => entry.meets_retaining_policy(policy), - Torrent::MutexStd(entry) => entry.lock_or_panic().meets_retaining_policy(policy), - } - } - - pub(crate) fn peers_is_empty(&self) -> bool { - match self { - Torrent::Single(entry) => entry.is_empty(), - Torrent::MutexStd(entry) => entry.lock_or_panic().is_empty(), - } - } - - pub(crate) fn get_peers_len(&self) -> usize { - match self { - Torrent::Single(entry) => entry.len(), - Torrent::MutexStd(entry) => entry.lock_or_panic().len(), - } - } - - pub(crate) fn get_peers(&self, limit: Option) -> Vec> { - match self { - Torrent::Single(entry) => entry.peers(limit), - Torrent::MutexStd(entry) => entry.lock_or_panic().peers(limit), - } - } - - pub(crate) fn get_peers_for_client(&self, client: &SocketAddr, limit: Option) -> Vec> { - match self { - Torrent::Single(entry) => entry.peers_excluding(client, limit), - Torrent::MutexStd(entry) => entry.lock_or_panic().peers_excluding(client, limit), - } - } - - pub(crate) fn upsert_peer(&mut self, peer: &peer::Peer) -> bool { - match self { - Torrent::Single(entry) => entry.handle_announcement(peer), - Torrent::MutexStd(entry) => entry.lock_or_panic().handle_announcement(peer), - } - } - - pub(crate) fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) { - match self { - Torrent::Single(entry) => entry.remove_inactive(current_cutoff), - Torrent::MutexStd(entry) => entry.lock_or_panic().remove_inactive(current_cutoff), - } - } -} diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/entry/mod.rs index 4607fd9c7..491b77a90 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/entry/mod.rs @@ -9,19 +9,14 @@ use torrust_tracker_clock::clock::{self, Time as _}; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::peer; use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_torrent_repository::{swarm, SwarmHandle}; +use torrust_tracker_torrent_repository::Swarm; -use crate::common::torrent::Torrent; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; use crate::CurrentClock; #[fixture] -fn single() -> Torrent { - Torrent::Single(swarm::Swarm::default()) -} -#[fixture] -fn mutex_std() -> Torrent { - Torrent::MutexStd(SwarmHandle::default()) +fn single() -> Swarm { + Swarm::default() } #[fixture] @@ -52,39 +47,39 @@ pub enum Makes { Three, } -fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { +fn make(torrent: &mut Swarm, makes: &Makes) -> Vec { match makes { Makes::Empty => vec![], Makes::Started => { let peer = a_started_peer(1); - torrent.upsert_peer(&peer); + torrent.handle_announcement(&peer); vec![peer] } Makes::Completed => { let peer = a_completed_peer(2); - torrent.upsert_peer(&peer); + torrent.handle_announcement(&peer); vec![peer] } Makes::Downloaded => { let mut peer = a_started_peer(3); - torrent.upsert_peer(&peer); + torrent.handle_announcement(&peer); peer.event = AnnounceEvent::Completed; peer.left = NumberOfBytes::new(0); - torrent.upsert_peer(&peer); + torrent.handle_announcement(&peer); vec![peer] } Makes::Three => { let peer_1 = a_started_peer(1); - torrent.upsert_peer(&peer_1); + torrent.handle_announcement(&peer_1); let peer_2 = a_completed_peer(2); - torrent.upsert_peer(&peer_2); + torrent.handle_announcement(&peer_2); let mut peer_3 = a_started_peer(3); - torrent.upsert_peer(&peer_3); + torrent.handle_announcement(&peer_3); peer_3.event = AnnounceEvent::Completed; peer_3.left = NumberOfBytes::new(0); - torrent.upsert_peer(&peer_3); + torrent.handle_announcement(&peer_3); vec![peer_1, peer_2, peer_3] } } @@ -93,10 +88,10 @@ fn make(torrent: &mut Torrent, makes: &Makes) -> Vec { #[rstest] #[case::empty(&Makes::Empty)] #[tokio::test] -async fn it_should_be_empty_by_default(#[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes) { +async fn it_should_be_empty_by_default(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { make(&mut torrent, makes); - assert_eq!(torrent.get_peers_len(), 0); + assert_eq!(torrent.len(), 0); } #[rstest] @@ -107,14 +102,14 @@ async fn it_should_be_empty_by_default(#[values(single(), mutex_std())] mut torr #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_check_if_entry_should_be_retained_based_on_the_tracker_policy( - #[values(single(), mutex_std())] mut torrent: Torrent, + #[values(single())] mut torrent: Swarm, #[case] makes: &Makes, #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, ) { make(&mut torrent, makes); - let has_peers = !torrent.peers_is_empty(); - let has_downloads = torrent.get_stats().downloaded != 0; + let has_peers = !torrent.is_empty(); + let has_downloads = torrent.metadata().downloaded != 0; match (policy.remove_peerless_torrents, policy.persistent_torrent_completed_stat) { // remove torrents without peers, and keep completed download stats @@ -144,10 +139,10 @@ async fn it_should_check_if_entry_should_be_retained_based_on_the_tracker_policy #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_get_peers_for_torrent_entry(#[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes) { +async fn it_should_get_peers_for_torrent_entry(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { let peers = make(&mut torrent, makes); - let torrent_peers = torrent.get_peers(None); + let torrent_peers = torrent.peers(None); assert_eq!(torrent_peers.len(), peers.len()); @@ -163,15 +158,15 @@ async fn it_should_get_peers_for_torrent_entry(#[values(single(), mutex_std())] #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_update_a_peer(#[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes) { +async fn it_should_update_a_peer(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { make(&mut torrent, makes); // Make and insert a new peer. let mut peer = a_started_peer(-1); - torrent.upsert_peer(&peer); + torrent.handle_announcement(&peer); // Get the Inserted Peer by Id. - let peers = torrent.get_peers(None); + let peers = torrent.peers(None); let original = peers .iter() .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) @@ -181,10 +176,10 @@ async fn it_should_update_a_peer(#[values(single(), mutex_std())] mut torrent: T // Announce "Completed" torrent download event. peer.event = AnnounceEvent::Completed; - torrent.upsert_peer(&peer); + torrent.handle_announcement(&peer); // Get the Updated Peer by Id. - let peers = torrent.get_peers(None); + let peers = torrent.peers(None); let updated = peers .iter() .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) @@ -200,20 +195,17 @@ async fn it_should_update_a_peer(#[values(single(), mutex_std())] mut torrent: T #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_remove_a_peer_upon_stopped_announcement( - #[values(single(), mutex_std())] mut torrent: Torrent, - #[case] makes: &Makes, -) { +async fn it_should_remove_a_peer_upon_stopped_announcement(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { use torrust_tracker_primitives::peer::ReadInfo as _; make(&mut torrent, makes); let mut peer = a_started_peer(-1); - torrent.upsert_peer(&peer); + torrent.handle_announcement(&peer); // The started peer should be inserted. - let peers = torrent.get_peers(None); + let peers = torrent.peers(None); let original = peers .iter() .find(|p| p.get_id() == peer.get_id()) @@ -223,10 +215,10 @@ async fn it_should_remove_a_peer_upon_stopped_announcement( // Change peer to "Stopped" and insert. peer.event = AnnounceEvent::Stopped; - torrent.upsert_peer(&peer); + torrent.handle_announcement(&peer); // It should be removed now. - let peers = torrent.get_peers(None); + let peers = torrent.peers(None); assert_eq!( peers.iter().find(|p| p.get_id() == peer.get_id()), @@ -242,13 +234,13 @@ async fn it_should_remove_a_peer_upon_stopped_announcement( #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloaded_statistic( - #[values(single(), mutex_std())] mut torrent: Torrent, + #[values(single())] mut torrent: Swarm, #[case] makes: &Makes, ) { make(&mut torrent, makes); - let downloaded = torrent.get_stats().downloaded; + let downloaded = torrent.metadata().downloaded; - let peers = torrent.get_peers(None); + let peers = torrent.peers(None); let mut peer = **peers.first().expect("there should be a peer"); let is_already_completed = peer.event == AnnounceEvent::Completed; @@ -256,8 +248,8 @@ async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloade // Announce "Completed" torrent download event. peer.event = AnnounceEvent::Completed; - torrent.upsert_peer(&peer); - let stats = torrent.get_stats(); + torrent.handle_announcement(&peer); + let stats = torrent.metadata(); if is_already_completed { assert_eq!(stats.downloaded, downloaded); @@ -272,19 +264,19 @@ async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloade #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_update_a_peer_as_a_seeder(#[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes) { +async fn it_should_update_a_peer_as_a_seeder(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { let peers = make(&mut torrent, makes); let completed = u32::try_from(peers.iter().filter(|p| p.is_seeder()).count()).expect("it_should_not_be_so_many"); - let peers = torrent.get_peers(None); + let peers = torrent.peers(None); let mut peer = **peers.first().expect("there should be a peer"); let is_already_non_left = peer.left == NumberOfBytes::new(0); // Set Bytes Left to Zero peer.left = NumberOfBytes::new(0); - torrent.upsert_peer(&peer); - let stats = torrent.get_stats(); + torrent.handle_announcement(&peer); + let stats = torrent.metadata(); if is_already_non_left { // it was already complete @@ -301,19 +293,19 @@ async fn it_should_update_a_peer_as_a_seeder(#[values(single(), mutex_std())] mu #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_update_a_peer_as_incomplete(#[values(single(), mutex_std())] mut torrent: Torrent, #[case] makes: &Makes) { +async fn it_should_update_a_peer_as_incomplete(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { let peers = make(&mut torrent, makes); let incomplete = u32::try_from(peers.iter().filter(|p| !p.is_seeder()).count()).expect("it should not be so many"); - let peers = torrent.get_peers(None); + let peers = torrent.peers(None); let mut peer = **peers.first().expect("there should be a peer"); let completed_already = peer.left == NumberOfBytes::new(0); // Set Bytes Left to no Zero peer.left = NumberOfBytes::new(1); - torrent.upsert_peer(&peer); - let stats = torrent.get_stats(); + torrent.handle_announcement(&peer); + let stats = torrent.metadata(); if completed_already { // now it is incomplete @@ -330,13 +322,10 @@ async fn it_should_update_a_peer_as_incomplete(#[values(single(), mutex_std())] #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_get_peers_excluding_the_client_socket( - #[values(single(), mutex_std())] mut torrent: Torrent, - #[case] makes: &Makes, -) { +async fn it_should_get_peers_excluding_the_client_socket(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { make(&mut torrent, makes); - let peers = torrent.get_peers(None); + let peers = torrent.peers(None); let mut peer = **peers.first().expect("there should be a peer"); let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8081); @@ -345,14 +334,14 @@ async fn it_should_get_peers_excluding_the_client_socket( assert_ne!(peer.peer_addr, socket); // it should get the peer as it dose not share the socket. - assert!(torrent.get_peers_for_client(&socket, None).contains(&peer.into())); + assert!(torrent.peers_excluding(&socket, None).contains(&peer.into())); // set the address to the socket. peer.peer_addr = socket; - torrent.upsert_peer(&peer); // Add peer + torrent.handle_announcement(&peer); // Add peer // It should not include the peer that has the same socket. - assert!(!torrent.get_peers_for_client(&socket, None).contains(&peer.into())); + assert!(!torrent.peers_excluding(&socket, None).contains(&peer.into())); } #[rstest] @@ -362,19 +351,16 @@ async fn it_should_get_peers_excluding_the_client_socket( #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_limit_the_number_of_peers_returned( - #[values(single(), mutex_std())] mut torrent: Torrent, - #[case] makes: &Makes, -) { +async fn it_should_limit_the_number_of_peers_returned(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { make(&mut torrent, makes); // We add one more peer than the scrape limit for peer_number in 1..=74 + 1 { let peer = a_started_peer(peer_number); - torrent.upsert_peer(&peer); + torrent.handle_announcement(&peer); } - let peers = torrent.get_peers(Some(TORRENT_PEERS_LIMIT)); + let peers = torrent.peers(Some(TORRENT_PEERS_LIMIT)); assert_eq!(peers.len(), 74); } @@ -386,10 +372,7 @@ async fn it_should_limit_the_number_of_peers_returned( #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_remove_inactive_peers_beyond_cutoff( - #[values(single(), mutex_std())] mut torrent: Torrent, - #[case] makes: &Makes, -) { +async fn it_should_remove_inactive_peers_beyond_cutoff(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { const TIMEOUT: Duration = Duration::from_secs(120); const EXPIRE: Duration = Duration::from_secs(121); @@ -402,12 +385,12 @@ async fn it_should_remove_inactive_peers_beyond_cutoff( peer.updated = now.sub(EXPIRE); - torrent.upsert_peer(&peer); + torrent.handle_announcement(&peer); - assert_eq!(torrent.get_peers_len(), peers.len() + 1); + assert_eq!(torrent.len(), peers.len() + 1); let current_cutoff = CurrentClock::now_sub(&TIMEOUT).unwrap_or_default(); - torrent.remove_inactive_peers(current_cutoff); + torrent.remove_inactive(current_cutoff); - assert_eq!(torrent.get_peers_len(), peers.len()); + assert_eq!(torrent.len(), peers.len()); } From 5413e597b7054a4ea7f32a4f36ce9b801c78e832 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 7 May 2025 10:15:40 +0100 Subject: [PATCH 1072/1297] refactor: [#1495] renamings to follow latest changes in torrent-repository pkg --- .../torrent-repository/tests/integration.rs | 4 +- .../tests/{entry => swarm}/mod.rs | 128 +++++++++--------- .../tests/{repository => swarms}/mod.rs | 99 +++++++------- .../src/torrent/repository/in_memory.rs | 26 ++-- 4 files changed, 130 insertions(+), 127 deletions(-) rename packages/torrent-repository/tests/{entry => swarm}/mod.rs (73%) rename packages/torrent-repository/tests/{repository => swarms}/mod.rs (81%) diff --git a/packages/torrent-repository/tests/integration.rs b/packages/torrent-repository/tests/integration.rs index 5aab67b03..b3e057075 100644 --- a/packages/torrent-repository/tests/integration.rs +++ b/packages/torrent-repository/tests/integration.rs @@ -7,8 +7,8 @@ use torrust_tracker_clock::clock; pub mod common; -mod entry; -mod repository; +mod swarm; +mod swarms; /// This code needs to be copied into each crate. /// Working version, for production. diff --git a/packages/torrent-repository/tests/entry/mod.rs b/packages/torrent-repository/tests/swarm/mod.rs similarity index 73% rename from packages/torrent-repository/tests/entry/mod.rs rename to packages/torrent-repository/tests/swarm/mod.rs index 491b77a90..d529b0243 100644 --- a/packages/torrent-repository/tests/entry/mod.rs +++ b/packages/torrent-repository/tests/swarm/mod.rs @@ -15,7 +15,7 @@ use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; use crate::CurrentClock; #[fixture] -fn single() -> Swarm { +fn swarm() -> Swarm { Swarm::default() } @@ -47,39 +47,39 @@ pub enum Makes { Three, } -fn make(torrent: &mut Swarm, makes: &Makes) -> Vec { +fn make(swarm: &mut Swarm, makes: &Makes) -> Vec { match makes { Makes::Empty => vec![], Makes::Started => { let peer = a_started_peer(1); - torrent.handle_announcement(&peer); + swarm.handle_announcement(&peer); vec![peer] } Makes::Completed => { let peer = a_completed_peer(2); - torrent.handle_announcement(&peer); + swarm.handle_announcement(&peer); vec![peer] } Makes::Downloaded => { let mut peer = a_started_peer(3); - torrent.handle_announcement(&peer); + swarm.handle_announcement(&peer); peer.event = AnnounceEvent::Completed; peer.left = NumberOfBytes::new(0); - torrent.handle_announcement(&peer); + swarm.handle_announcement(&peer); vec![peer] } Makes::Three => { let peer_1 = a_started_peer(1); - torrent.handle_announcement(&peer_1); + swarm.handle_announcement(&peer_1); let peer_2 = a_completed_peer(2); - torrent.handle_announcement(&peer_2); + swarm.handle_announcement(&peer_2); let mut peer_3 = a_started_peer(3); - torrent.handle_announcement(&peer_3); + swarm.handle_announcement(&peer_3); peer_3.event = AnnounceEvent::Completed; peer_3.left = NumberOfBytes::new(0); - torrent.handle_announcement(&peer_3); + swarm.handle_announcement(&peer_3); vec![peer_1, peer_2, peer_3] } } @@ -88,10 +88,10 @@ fn make(torrent: &mut Swarm, makes: &Makes) -> Vec { #[rstest] #[case::empty(&Makes::Empty)] #[tokio::test] -async fn it_should_be_empty_by_default(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { - make(&mut torrent, makes); +async fn it_should_be_empty_by_default(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { + make(&mut swarm, makes); - assert_eq!(torrent.len(), 0); + assert_eq!(swarm.len(), 0); } #[rstest] @@ -102,33 +102,33 @@ async fn it_should_be_empty_by_default(#[values(single())] mut torrent: Swarm, # #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_check_if_entry_should_be_retained_based_on_the_tracker_policy( - #[values(single())] mut torrent: Swarm, + #[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes, #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, ) { - make(&mut torrent, makes); + make(&mut swarm, makes); - let has_peers = !torrent.is_empty(); - let has_downloads = torrent.metadata().downloaded != 0; + let has_peers = !swarm.is_empty(); + let has_downloads = swarm.metadata().downloaded != 0; match (policy.remove_peerless_torrents, policy.persistent_torrent_completed_stat) { // remove torrents without peers, and keep completed download stats (true, true) => match (has_peers, has_downloads) { // no peers, but has downloads // peers, with or without downloads - (false, true) | (true, true | false) => assert!(torrent.meets_retaining_policy(&policy)), + (false, true) | (true, true | false) => assert!(swarm.meets_retaining_policy(&policy)), // no peers and no downloads - (false, false) => assert!(!torrent.meets_retaining_policy(&policy)), + (false, false) => assert!(!swarm.meets_retaining_policy(&policy)), }, // remove torrents without peers and drop completed download stats (true, false) => match (has_peers, has_downloads) { // peers, with or without downloads - (true, true | false) => assert!(torrent.meets_retaining_policy(&policy)), + (true, true | false) => assert!(swarm.meets_retaining_policy(&policy)), // no peers and with or without downloads - (false, true | false) => assert!(!torrent.meets_retaining_policy(&policy)), + (false, true | false) => assert!(!swarm.meets_retaining_policy(&policy)), }, // keep torrents without peers, but keep or drop completed download stats - (false, true | false) => assert!(torrent.meets_retaining_policy(&policy)), + (false, true | false) => assert!(swarm.meets_retaining_policy(&policy)), } } @@ -139,10 +139,10 @@ async fn it_should_check_if_entry_should_be_retained_based_on_the_tracker_policy #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_get_peers_for_torrent_entry(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { - let peers = make(&mut torrent, makes); +async fn it_should_get_peers_for_torrent_entry(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { + let peers = make(&mut swarm, makes); - let torrent_peers = torrent.peers(None); + let torrent_peers = swarm.peers(None); assert_eq!(torrent_peers.len(), peers.len()); @@ -158,15 +158,15 @@ async fn it_should_get_peers_for_torrent_entry(#[values(single())] mut torrent: #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_update_a_peer(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { - make(&mut torrent, makes); +async fn it_should_update_a_peer(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { + make(&mut swarm, makes); // Make and insert a new peer. let mut peer = a_started_peer(-1); - torrent.handle_announcement(&peer); + swarm.handle_announcement(&peer); // Get the Inserted Peer by Id. - let peers = torrent.peers(None); + let peers = swarm.peers(None); let original = peers .iter() .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) @@ -176,10 +176,10 @@ async fn it_should_update_a_peer(#[values(single())] mut torrent: Swarm, #[case] // Announce "Completed" torrent download event. peer.event = AnnounceEvent::Completed; - torrent.handle_announcement(&peer); + swarm.handle_announcement(&peer); // Get the Updated Peer by Id. - let peers = torrent.peers(None); + let peers = swarm.peers(None); let updated = peers .iter() .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) @@ -195,17 +195,17 @@ async fn it_should_update_a_peer(#[values(single())] mut torrent: Swarm, #[case] #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_remove_a_peer_upon_stopped_announcement(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { +async fn it_should_remove_a_peer_upon_stopped_announcement(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { use torrust_tracker_primitives::peer::ReadInfo as _; - make(&mut torrent, makes); + make(&mut swarm, makes); let mut peer = a_started_peer(-1); - torrent.handle_announcement(&peer); + swarm.handle_announcement(&peer); // The started peer should be inserted. - let peers = torrent.peers(None); + let peers = swarm.peers(None); let original = peers .iter() .find(|p| p.get_id() == peer.get_id()) @@ -215,10 +215,10 @@ async fn it_should_remove_a_peer_upon_stopped_announcement(#[values(single())] m // Change peer to "Stopped" and insert. peer.event = AnnounceEvent::Stopped; - torrent.handle_announcement(&peer); + swarm.handle_announcement(&peer); // It should be removed now. - let peers = torrent.peers(None); + let peers = swarm.peers(None); assert_eq!( peers.iter().find(|p| p.get_id() == peer.get_id()), @@ -234,7 +234,7 @@ async fn it_should_remove_a_peer_upon_stopped_announcement(#[values(single())] m #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloaded_statistic( - #[values(single())] mut torrent: Swarm, + #[values(swarm())] mut torrent: Swarm, #[case] makes: &Makes, ) { make(&mut torrent, makes); @@ -264,19 +264,19 @@ async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloade #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_update_a_peer_as_a_seeder(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { - let peers = make(&mut torrent, makes); +async fn it_should_update_a_peer_as_a_seeder(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { + let peers = make(&mut swarm, makes); let completed = u32::try_from(peers.iter().filter(|p| p.is_seeder()).count()).expect("it_should_not_be_so_many"); - let peers = torrent.peers(None); + let peers = swarm.peers(None); let mut peer = **peers.first().expect("there should be a peer"); let is_already_non_left = peer.left == NumberOfBytes::new(0); // Set Bytes Left to Zero peer.left = NumberOfBytes::new(0); - torrent.handle_announcement(&peer); - let stats = torrent.metadata(); + swarm.handle_announcement(&peer); + let stats = swarm.metadata(); if is_already_non_left { // it was already complete @@ -293,19 +293,19 @@ async fn it_should_update_a_peer_as_a_seeder(#[values(single())] mut torrent: Sw #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_update_a_peer_as_incomplete(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { - let peers = make(&mut torrent, makes); +async fn it_should_update_a_peer_as_incomplete(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { + let peers = make(&mut swarm, makes); let incomplete = u32::try_from(peers.iter().filter(|p| !p.is_seeder()).count()).expect("it should not be so many"); - let peers = torrent.peers(None); + let peers = swarm.peers(None); let mut peer = **peers.first().expect("there should be a peer"); let completed_already = peer.left == NumberOfBytes::new(0); // Set Bytes Left to no Zero peer.left = NumberOfBytes::new(1); - torrent.handle_announcement(&peer); - let stats = torrent.metadata(); + swarm.handle_announcement(&peer); + let stats = swarm.metadata(); if completed_already { // now it is incomplete @@ -322,10 +322,10 @@ async fn it_should_update_a_peer_as_incomplete(#[values(single())] mut torrent: #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_get_peers_excluding_the_client_socket(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { - make(&mut torrent, makes); +async fn it_should_get_peers_excluding_the_client_socket(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { + make(&mut swarm, makes); - let peers = torrent.peers(None); + let peers = swarm.peers(None); let mut peer = **peers.first().expect("there should be a peer"); let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8081); @@ -334,14 +334,14 @@ async fn it_should_get_peers_excluding_the_client_socket(#[values(single())] mut assert_ne!(peer.peer_addr, socket); // it should get the peer as it dose not share the socket. - assert!(torrent.peers_excluding(&socket, None).contains(&peer.into())); + assert!(swarm.peers_excluding(&socket, None).contains(&peer.into())); // set the address to the socket. peer.peer_addr = socket; - torrent.handle_announcement(&peer); // Add peer + swarm.handle_announcement(&peer); // Add peer // It should not include the peer that has the same socket. - assert!(!torrent.peers_excluding(&socket, None).contains(&peer.into())); + assert!(!swarm.peers_excluding(&socket, None).contains(&peer.into())); } #[rstest] @@ -351,16 +351,16 @@ async fn it_should_get_peers_excluding_the_client_socket(#[values(single())] mut #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_limit_the_number_of_peers_returned(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { - make(&mut torrent, makes); +async fn it_should_limit_the_number_of_peers_returned(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { + make(&mut swarm, makes); // We add one more peer than the scrape limit for peer_number in 1..=74 + 1 { let peer = a_started_peer(peer_number); - torrent.handle_announcement(&peer); + swarm.handle_announcement(&peer); } - let peers = torrent.peers(Some(TORRENT_PEERS_LIMIT)); + let peers = swarm.peers(Some(TORRENT_PEERS_LIMIT)); assert_eq!(peers.len(), 74); } @@ -372,11 +372,11 @@ async fn it_should_limit_the_number_of_peers_returned(#[values(single())] mut to #[case::downloaded(&Makes::Downloaded)] #[case::three(&Makes::Three)] #[tokio::test] -async fn it_should_remove_inactive_peers_beyond_cutoff(#[values(single())] mut torrent: Swarm, #[case] makes: &Makes) { +async fn it_should_remove_inactive_peers_beyond_cutoff(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { const TIMEOUT: Duration = Duration::from_secs(120); const EXPIRE: Duration = Duration::from_secs(121); - let peers = make(&mut torrent, makes); + let peers = make(&mut swarm, makes); let mut peer = a_completed_peer(-1); @@ -385,12 +385,12 @@ async fn it_should_remove_inactive_peers_beyond_cutoff(#[values(single())] mut t peer.updated = now.sub(EXPIRE); - torrent.handle_announcement(&peer); + swarm.handle_announcement(&peer); - assert_eq!(torrent.len(), peers.len() + 1); + assert_eq!(swarm.len(), peers.len() + 1); let current_cutoff = CurrentClock::now_sub(&TIMEOUT).unwrap_or_default(); - torrent.remove_inactive(current_cutoff); + swarm.remove_inactive(current_cutoff); - assert_eq!(torrent.len(), peers.len()); + assert_eq!(swarm.len(), peers.len()); } diff --git a/packages/torrent-repository/tests/repository/mod.rs b/packages/torrent-repository/tests/swarms/mod.rs similarity index 81% rename from packages/torrent-repository/tests/repository/mod.rs rename to packages/torrent-repository/tests/swarms/mod.rs index 071a187fa..20c6255fa 100644 --- a/packages/torrent-repository/tests/repository/mod.rs +++ b/packages/torrent-repository/tests/swarms/mod.rs @@ -15,7 +15,7 @@ use torrust_tracker_torrent_repository::{LockTrackedTorrent, Swarms}; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; #[fixture] -fn skip_list_mutex_std() -> Swarms { +fn swarms() -> Swarms { Swarms::default() } @@ -33,27 +33,27 @@ fn default() -> Entries { #[fixture] fn started() -> Entries { - let mut torrent = Swarm::default(); - torrent.handle_announcement(&a_started_peer(1)); - vec![(InfoHash::default(), torrent)] + let mut swarm = Swarm::default(); + swarm.handle_announcement(&a_started_peer(1)); + vec![(InfoHash::default(), swarm)] } #[fixture] fn completed() -> Entries { - let mut torrent = Swarm::default(); - torrent.handle_announcement(&a_completed_peer(2)); - vec![(InfoHash::default(), torrent)] + let mut swarm = Swarm::default(); + swarm.handle_announcement(&a_completed_peer(2)); + vec![(InfoHash::default(), swarm)] } #[fixture] fn downloaded() -> Entries { - let mut torrent = Swarm::default(); + let mut swarm = Swarm::default(); let mut peer = a_started_peer(3); - torrent.handle_announcement(&peer); + swarm.handle_announcement(&peer); peer.event = AnnounceEvent::Completed; peer.left = NumberOfBytes::new(0); - torrent.handle_announcement(&peer); - vec![(InfoHash::default(), torrent)] + swarm.handle_announcement(&peer); + vec![(InfoHash::default(), swarm)] } #[fixture] @@ -201,13 +201,13 @@ fn policy_remove_persist() -> TrackerPolicy { #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_get_a_torrent_entry(#[values(skip_list_mutex_std())] repo: Swarms, #[case] entries: Entries) { +async fn it_should_get_a_torrent_entry(#[values(swarms())] repo: Swarms, #[case] entries: Entries) { make(&repo, &entries); - if let Some((info_hash, torrent)) = entries.first() { + if let Some((info_hash, swarm)) = entries.first() { assert_eq!( Some(repo.get(info_hash).unwrap().lock_or_panic().clone()), - Some(torrent.clone()) + Some(swarm.clone()) ); } else { assert!(repo.get(&InfoHash::default()).is_none()); @@ -225,7 +225,7 @@ async fn it_should_get_a_torrent_entry(#[values(skip_list_mutex_std())] repo: Sw #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( - #[values(skip_list_mutex_std())] repo: Swarms, + #[values(swarms())] repo: Swarms, #[case] entries: Entries, many_out_of_order: Entries, ) { @@ -258,7 +258,7 @@ async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_get_paginated( - #[values(skip_list_mutex_std())] repo: Swarms, + #[values(swarms())] repo: Swarms, #[case] entries: Entries, #[values(paginated_limit_zero(), paginated_limit_one(), paginated_limit_one_offset_one())] paginated: Pagination, ) { @@ -270,13 +270,13 @@ async fn it_should_get_paginated( match paginated { // it should return empty if limit is zero. Pagination { limit: 0, .. } => { - let torrents: Vec<(InfoHash, Swarm)> = repo + let swarms: Vec<(InfoHash, Swarm)> = repo .get_paginated(Some(&paginated)) .iter() - .map(|(i, lock_tracked_torrent)| (*i, lock_tracked_torrent.lock_or_panic().clone())) + .map(|(i, swarm_handle)| (*i, swarm_handle.lock_or_panic().clone())) .collect(); - assert_eq!(torrents, vec![]); + assert_eq!(swarms, vec![]); } // it should return a single entry if the limit is one. @@ -313,10 +313,10 @@ async fn it_should_get_paginated( #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_get_metrics(#[values(skip_list_mutex_std())] repo: Swarms, #[case] entries: Entries) { +async fn it_should_get_metrics(#[values(swarms())] swarms: Swarms, #[case] entries: Entries) { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; - make(&repo, &entries); + make(&swarms, &entries); let mut metrics = AggregateSwarmMetadata::default(); @@ -329,7 +329,7 @@ async fn it_should_get_metrics(#[values(skip_list_mutex_std())] repo: Swarms, #[ metrics.total_downloaded += u64::from(stats.downloaded); } - assert_eq!(repo.get_aggregate_swarm_metadata(), metrics); + assert_eq!(swarms.get_aggregate_swarm_metadata(), metrics); } #[rstest] @@ -343,21 +343,21 @@ async fn it_should_get_metrics(#[values(skip_list_mutex_std())] repo: Swarms, #[ #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_import_persistent_torrents( - #[values(skip_list_mutex_std())] repo: Swarms, + #[values(swarms())] swarms: Swarms, #[case] entries: Entries, #[values(persistent_empty(), persistent_single(), persistent_three())] persistent_torrents: PersistentTorrents, ) { - make(&repo, &entries); + make(&swarms, &entries); - let mut downloaded = repo.get_aggregate_swarm_metadata().total_downloaded; + let mut downloaded = swarms.get_aggregate_swarm_metadata().total_downloaded; persistent_torrents.iter().for_each(|(_, d)| downloaded += u64::from(*d)); - repo.import_persistent(&persistent_torrents); + swarms.import_persistent(&persistent_torrents); - assert_eq!(repo.get_aggregate_swarm_metadata().total_downloaded, downloaded); + assert_eq!(swarms.get_aggregate_swarm_metadata().total_downloaded, downloaded); for (entry, _) in persistent_torrents { - assert!(repo.get(&entry).is_some()); + assert!(swarms.get(&entry).is_some()); } } @@ -371,21 +371,24 @@ async fn it_should_import_persistent_torrents( #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_remove_an_entry(#[values(skip_list_mutex_std())] repo: Swarms, #[case] entries: Entries) { - make(&repo, &entries); +async fn it_should_remove_an_entry(#[values(swarms())] swarms: Swarms, #[case] entries: Entries) { + make(&swarms, &entries); for (info_hash, torrent) in entries { assert_eq!( - Some(repo.get(&info_hash).unwrap().lock_or_panic().clone()), + Some(swarms.get(&info_hash).unwrap().lock_or_panic().clone()), Some(torrent.clone()) ); - assert_eq!(Some(repo.remove(&info_hash).unwrap().lock_or_panic().clone()), Some(torrent)); + assert_eq!( + Some(swarms.remove(&info_hash).unwrap().lock_or_panic().clone()), + Some(torrent) + ); - assert!(repo.get(&info_hash).is_none()); - assert!(repo.remove(&info_hash).is_none()); + assert!(swarms.get(&info_hash).is_none()); + assert!(swarms.remove(&info_hash).is_none()); } - assert_eq!(repo.get_aggregate_swarm_metadata().total_torrents, 0); + assert_eq!(swarms.get_aggregate_swarm_metadata().total_torrents, 0); } #[rstest] @@ -398,7 +401,7 @@ async fn it_should_remove_an_entry(#[values(skip_list_mutex_std())] repo: Swarms #[case::out_of_order(many_out_of_order())] #[case::in_order(many_hashed_in_order())] #[tokio::test] -async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: Swarms, #[case] entries: Entries) { +async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[case] entries: Entries) { use std::ops::Sub as _; use std::time::Duration; @@ -411,7 +414,7 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: const TIMEOUT: Duration = Duration::from_secs(120); const EXPIRE: Duration = Duration::from_secs(121); - make(&repo, &entries); + make(&swarms, &entries); let info_hash: InfoHash; let mut peer: peer::Peer; @@ -435,15 +438,15 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: // Insert the infohash and peer into the repository // and verify there is an extra torrent entry. { - repo.upsert_peer(&info_hash, &peer, None); - assert_eq!(repo.get_aggregate_swarm_metadata().total_torrents, entries.len() as u64 + 1); + swarms.upsert_peer(&info_hash, &peer, None); + assert_eq!(swarms.get_aggregate_swarm_metadata().total_torrents, entries.len() as u64 + 1); } // Insert the infohash and peer into the repository // and verify the swarm metadata was updated. { - repo.upsert_peer(&info_hash, &peer, None); - let stats = repo.get_swarm_metadata(&info_hash); + swarms.upsert_peer(&info_hash, &peer, None); + let stats = swarms.get_swarm_metadata(&info_hash); assert_eq!( stats, Some(SwarmMetadata { @@ -456,19 +459,19 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: // Verify that this new peer was inserted into the repository. { - let lock_tracked_torrent = repo.get(&info_hash).expect("it_should_get_some"); + let lock_tracked_torrent = swarms.get(&info_hash).expect("it_should_get_some"); let entry = lock_tracked_torrent.lock_or_panic(); assert!(entry.peers(None).contains(&peer.into())); } // Remove peers that have not been updated since the timeout (120 seconds ago). { - repo.remove_inactive_peers(CurrentClock::now_sub(&TIMEOUT).expect("it should get a time passed")); + swarms.remove_inactive_peers(CurrentClock::now_sub(&TIMEOUT).expect("it should get a time passed")); } // Verify that the this peer was removed from the repository. { - let lock_tracked_torrent = repo.get(&info_hash).expect("it_should_get_some"); + let lock_tracked_torrent = swarms.get(&info_hash).expect("it_should_get_some"); let entry = lock_tracked_torrent.lock_or_panic(); assert!(!entry.peers(None).contains(&peer.into())); } @@ -485,15 +488,15 @@ async fn it_should_remove_inactive_peers(#[values(skip_list_mutex_std())] repo: #[case::in_order(many_hashed_in_order())] #[tokio::test] async fn it_should_remove_peerless_torrents( - #[values(skip_list_mutex_std())] repo: Swarms, + #[values(swarms())] swarms: Swarms, #[case] entries: Entries, #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, ) { - make(&repo, &entries); + make(&swarms, &entries); - repo.remove_peerless_torrents(&policy); + swarms.remove_peerless_torrents(&policy); - let torrents: Vec<(InfoHash, Swarm)> = repo + let torrents: Vec<(InfoHash, Swarm)> = swarms .get_paginated(None) .iter() .map(|(i, lock_tracked_torrent)| (*i, lock_tracked_torrent.lock_or_panic().clone())) diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 67e532e86..5902f6735 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -20,8 +20,8 @@ use torrust_tracker_torrent_repository::{SwarmHandle, Swarms}; /// used in production. Other implementations are kept for reference. #[derive(Debug, Default)] pub struct InMemoryTorrentRepository { - /// The underlying in-memory data structure that stores torrent entries. - torrents: Arc, + /// The underlying in-memory data structure that stores swarms data. + swarms: Arc, } impl InMemoryTorrentRepository { @@ -46,7 +46,7 @@ impl InMemoryTorrentRepository { peer: &peer::Peer, opt_persistent_torrent: Option, ) -> bool { - self.torrents.upsert_peer(info_hash, peer, opt_persistent_torrent) + self.swarms.upsert_peer(info_hash, peer, opt_persistent_torrent) } /// Removes a torrent entry from the repository. @@ -65,7 +65,7 @@ impl InMemoryTorrentRepository { #[cfg(test)] #[must_use] pub(crate) fn remove(&self, key: &InfoHash) -> Option { - self.torrents.remove(key) + self.swarms.remove(key) } /// Removes inactive peers from all torrent entries. @@ -78,7 +78,7 @@ impl InMemoryTorrentRepository { /// * `current_cutoff` - The cutoff timestamp; peers not updated since this /// time will be removed. pub(crate) fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - self.torrents.remove_inactive_peers(current_cutoff); + self.swarms.remove_inactive_peers(current_cutoff); } /// Removes torrent entries that have no active peers. @@ -91,7 +91,7 @@ impl InMemoryTorrentRepository { /// * `policy` - The tracker policy containing the configuration for /// removing peerless torrents. pub(crate) fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - self.torrents.remove_peerless_torrents(policy); + self.swarms.remove_peerless_torrents(policy); } /// Retrieves a torrent entry by its infohash. @@ -105,7 +105,7 @@ impl InMemoryTorrentRepository { /// An `Option` containing the torrent entry if found. #[must_use] pub(crate) fn get(&self, key: &InfoHash) -> Option { - self.torrents.get(key) + self.swarms.get(key) } /// Retrieves a paginated list of torrent entries. @@ -123,7 +123,7 @@ impl InMemoryTorrentRepository { /// A vector of `(InfoHash, TorrentEntry)` tuples. #[must_use] pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, SwarmHandle)> { - self.torrents.get_paginated(pagination) + self.swarms.get_paginated(pagination) } /// Retrieves swarm metadata for a given torrent. @@ -141,7 +141,7 @@ impl InMemoryTorrentRepository { /// A `SwarmMetadata` struct containing the aggregated torrent data. #[must_use] pub(crate) fn get_swarm_metadata_or_default(&self, info_hash: &InfoHash) -> SwarmMetadata { - self.torrents.get_swarm_metadata_or_default(info_hash) + self.swarms.get_swarm_metadata_or_default(info_hash) } /// Retrieves torrent peers for a given torrent and client, excluding the @@ -163,7 +163,7 @@ impl InMemoryTorrentRepository { /// the torrent, excluding the requesting client. #[must_use] pub(crate) fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { - self.torrents.get_peers_for(info_hash, peer, max(limit, TORRENT_PEERS_LIMIT)) + self.swarms.get_peers_for(info_hash, peer, max(limit, TORRENT_PEERS_LIMIT)) } /// Retrieves the list of peers for a given torrent. @@ -186,7 +186,7 @@ impl InMemoryTorrentRepository { #[must_use] pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { // todo: pass the limit as an argument like `get_peers_for` - self.torrents.get_torrent_peers(info_hash, TORRENT_PEERS_LIMIT) + self.swarms.get_torrent_peers(info_hash, TORRENT_PEERS_LIMIT) } /// Calculates and returns overall torrent metrics. @@ -200,7 +200,7 @@ impl InMemoryTorrentRepository { /// A [`AggregateSwarmMetadata`] struct with the aggregated metrics. #[must_use] pub fn get_aggregate_swarm_metadata(&self) -> AggregateSwarmMetadata { - self.torrents.get_aggregate_swarm_metadata() + self.swarms.get_aggregate_swarm_metadata() } /// Imports persistent torrent data into the in-memory repository. @@ -212,6 +212,6 @@ impl InMemoryTorrentRepository { /// /// * `persistent_torrents` - A reference to the persisted torrent data. pub fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { - self.torrents.import_persistent(persistent_torrents); + self.swarms.import_persistent(persistent_torrents); } } From 6d50fa083cd334bfc1f23a96d3754e98ed6ae51b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 7 May 2025 11:45:50 +0100 Subject: [PATCH 1073/1297] refactor: [#1495] remove panics from Swarms type They have been moved one level up to the InMemoryTorrentRepository type. We should buble them up to the final user, returing an error in the UDP or HTTP tracker when the swarm handle lock cannot be adquired. A new issues will be opened to address that. --- Cargo.lock | 2 +- packages/torrent-repository/Cargo.toml | 2 +- packages/torrent-repository/src/lib.rs | 2 +- packages/torrent-repository/src/swarms.rs | 189 +++++++++++------- .../torrent-repository/tests/swarms/mod.rs | 25 ++- .../src/torrent/repository/in_memory.rs | 54 ++++- 6 files changed, 182 insertions(+), 92 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index eea957f88..093b8e9b0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4850,12 +4850,12 @@ dependencies = [ "crossbeam-skiplist", "rand 0.9.1", "rstest", + "thiserror 2.0.12", "tokio", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-primitives", "torrust-tracker-test-helpers", - "tracing", ] [[package]] diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index e584fadf4..2cc02a720 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -19,11 +19,11 @@ version.workspace = true aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" crossbeam-skiplist = "0" +thiserror = "2.0.12" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -tracing = "0" [dev-dependencies] async-std = { version = "1", features = ["attributes", "tokio1"] } diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index c985f7a2b..a4e7d9c5d 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -23,7 +23,7 @@ pub trait LockTrackedTorrent { fn lock_or_panic(&self) -> MutexGuard<'_, Swarm>; } -impl LockTrackedTorrent for Arc> { +impl LockTrackedTorrent for SwarmHandle { fn lock_or_panic(&self) -> MutexGuard<'_, Swarm> { self.lock().expect("can't acquire lock for tracked torrent handle") } diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 936f49d22..222bea60a 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -8,7 +8,7 @@ use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMe use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use crate::swarm::Swarm; -use crate::{LockTrackedTorrent, SwarmHandle}; +use crate::SwarmHandle; #[derive(Default, Debug)] pub struct Swarms { @@ -34,33 +34,31 @@ impl Swarms { /// Returns `true` if the number of downloads was increased because the peer /// completed the download. /// - /// # Panics + /// # Errors /// - /// This function panics if the lock for the entry cannot be obtained. + /// This function panics if the lock for the swarm handle cannot be acquired. pub fn upsert_peer( &self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option, - ) -> bool { - if let Some(existing_entry) = self.swarms.get(info_hash) { - tracing::debug!("Torrent already exists: {:?}", info_hash); + ) -> Result { + if let Some(existing_swarm_handle) = self.swarms.get(info_hash) { + let mut swarm = existing_swarm_handle.value().lock()?; - existing_entry.value().lock_or_panic().handle_announcement(peer) + Ok(swarm.handle_announcement(peer)) } else { - tracing::debug!("Inserting new torrent: {:?}", info_hash); - - let new_entry = if let Some(number_of_downloads) = opt_persistent_torrent { + let new_swarm_handle = if let Some(number_of_downloads) = opt_persistent_torrent { SwarmHandle::new(Swarm::new(number_of_downloads).into()) } else { SwarmHandle::default() }; - let inserted_entry = self.swarms.get_or_insert(*info_hash, new_entry); + let inserted_swarm_handle = self.swarms.get_or_insert(*info_hash, new_swarm_handle); - let mut torrent_guard = inserted_entry.value().lock_or_panic(); + let mut swarm = inserted_swarm_handle.value().lock()?; - torrent_guard.handle_announcement(peer) + Ok(swarm.handle_announcement(peer)) } } @@ -79,13 +77,17 @@ impl Swarms { /// A peer is considered inactive if its last update timestamp is older than /// the provided cutoff time. /// - /// # Panics + /// # Errors /// - /// This function panics if the lock for the entry cannot be obtained. - pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - for entry in &self.swarms { - entry.value().lock_or_panic().remove_inactive(current_cutoff); + /// This function returns an error if it fails to acquire the lock for any + /// swarm handle. + pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> Result<(), Error> { + for swarm_handle in &self.swarms { + let mut swarm = swarm_handle.value().lock()?; + swarm.remove_inactive(current_cutoff); } + + Ok(()) } /// Retrieves a tracked torrent handle by its infohash. @@ -132,14 +134,17 @@ impl Swarms { /// /// A `SwarmMetadata` struct containing the aggregated torrent data if found. /// - /// # Panics + /// # Errors /// - /// This function panics if the lock for the entry cannot be obtained. - #[must_use] - pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.swarms - .get(info_hash) - .map(|entry| entry.value().lock_or_panic().metadata()) + /// This function panics if the lock for the swarm handle cannot be acquired. + pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Result, Error> { + match self.swarms.get(info_hash) { + None => Ok(None), + Some(swarm_handle) => { + let swarm = swarm_handle.value().lock()?; + Ok(Some(swarm.metadata())) + } + } } /// Retrieves swarm metadata for a given torrent. @@ -148,11 +153,16 @@ impl Swarms { /// /// A `SwarmMetadata` struct containing the aggregated torrent data if it's /// found or a zeroed metadata struct if not. - #[must_use] - pub fn get_swarm_metadata_or_default(&self, info_hash: &InfoHash) -> SwarmMetadata { + /// + /// # Errors + /// + /// This function returns an error if it fails to acquire the lock for the + /// swarm handle. + pub fn get_swarm_metadata_or_default(&self, info_hash: &InfoHash) -> Result { match self.get_swarm_metadata(info_hash) { - Some(swarm_metadata) => swarm_metadata, - None => SwarmMetadata::zeroed(), + Ok(Some(swarm_metadata)) => Ok(swarm_metadata), + Ok(None) => Ok(SwarmMetadata::zeroed()), + Err(err) => Err(err), } } @@ -168,14 +178,17 @@ impl Swarms { /// A vector of peers (wrapped in `Arc`) representing the active peers for /// the torrent, excluding the requesting client. /// - /// # Panics + /// # Errors /// - /// This function panics if the lock for the torrent entry cannot be obtained. - #[must_use] - pub fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { + /// This function returns an error if it fails to acquire the lock for the + /// swarm handle. + pub fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Result>, Error> { match self.get(info_hash) { - None => vec![], - Some(entry) => entry.lock_or_panic().peers_excluding(&peer.peer_addr, Some(limit)), + None => Ok(vec![]), + Some(swarm_handle) => { + let swarm = swarm_handle.lock()?; + Ok(swarm.peers_excluding(&peer.peer_addr, Some(limit))) + } } } @@ -189,14 +202,17 @@ impl Swarms { /// A vector of peers (wrapped in `Arc`) representing the active peers for /// the torrent. /// - /// # Panics + /// # Errors /// - /// This function panics if the lock for the torrent entry cannot be obtained. - #[must_use] - pub fn get_torrent_peers(&self, info_hash: &InfoHash, limit: usize) -> Vec> { + /// This function returns an error if it fails to acquire the lock for the + /// swarm handle. + pub fn get_torrent_peers(&self, info_hash: &InfoHash, limit: usize) -> Result>, Error> { match self.get(info_hash) { - None => vec![], - Some(entry) => entry.lock_or_panic().peers(Some(limit)), + None => Ok(vec![]), + Some(swarm_handle) => { + let swarm = swarm_handle.lock()?; + Ok(swarm.peers(Some(limit))) + } } } @@ -205,17 +221,22 @@ impl Swarms { /// Depending on the tracker policy, torrents without any peers may be /// removed to conserve memory. /// - /// # Panics + /// # Errors /// - /// This function panics if the lock for the entry cannot be obtained. - pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - for entry in &self.swarms { - if entry.value().lock_or_panic().meets_retaining_policy(policy) { + /// This function returns an error if it fails to acquire the lock for any + /// swarm handle. + pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> Result<(), Error> { + for swarm_handle in &self.swarms { + let swarm = swarm_handle.value().lock()?; + + if swarm.meets_retaining_policy(policy) { continue; } - entry.remove(); + swarm_handle.remove(); } + + Ok(()) } /// Imports persistent torrent data into the in-memory repository. @@ -247,22 +268,35 @@ impl Swarms { /// /// A [`AggregateSwarmMetadata`] struct with the aggregated metrics. /// - /// # Panics + /// # Errors /// - /// This function panics if the lock for the entry cannot be obtained. - #[must_use] - pub fn get_aggregate_swarm_metadata(&self) -> AggregateSwarmMetadata { + /// This function returns an error if it fails to acquire the lock for any + /// swarm handle. + pub fn get_aggregate_swarm_metadata(&self) -> Result { let mut metrics = AggregateSwarmMetadata::default(); for entry in &self.swarms { - let stats = entry.value().lock_or_panic().metadata(); + let swarm = entry.value().lock()?; + let stats = swarm.metadata(); metrics.total_complete += u64::from(stats.complete); metrics.total_downloaded += u64::from(stats.downloaded); metrics.total_incomplete += u64::from(stats.incomplete); metrics.total_torrents += 1; } - metrics + Ok(metrics) + } +} + +#[derive(thiserror::Error, Debug, Clone)] +pub enum Error { + #[error("Can't acquire swarm lock")] + CannotAcquireSwarmLock, +} + +impl From>> for Error { + fn from(_error: std::sync::PoisonError>) -> Self { + Error::CannotAcquireSwarmLock } } @@ -354,7 +388,7 @@ mod tests { let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); - let peers = torrent_repository.get_torrent_peers(&info_hash, 74); + let peers = torrent_repository.get_torrent_peers(&info_hash, 74).unwrap(); assert_eq!(peers, vec![Arc::new(peer)]); } @@ -363,7 +397,7 @@ mod tests { async fn it_should_return_an_empty_list_or_peers_for_a_non_existing_torrent() { let torrent_repository = Arc::new(Swarms::default()); - let peers = torrent_repository.get_torrent_peers(&sample_info_hash(), 74); + let peers = torrent_repository.get_torrent_peers(&sample_info_hash(), 74).unwrap(); assert!(peers.is_empty()); } @@ -388,7 +422,7 @@ mod tests { let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); } - let peers = torrent_repository.get_torrent_peers(&info_hash, 74); + let peers = torrent_repository.get_torrent_peers(&info_hash, 74).unwrap(); assert_eq!(peers.len(), 74); } @@ -411,7 +445,9 @@ mod tests { async fn it_should_return_an_empty_peer_list_for_a_non_existing_torrent() { let torrent_repository = Arc::new(Swarms::default()); - let peers = torrent_repository.get_peers_for(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT); + let peers = torrent_repository + .get_peers_for(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT) + .unwrap(); assert_eq!(peers, vec![]); } @@ -425,7 +461,9 @@ mod tests { let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); - let peers = torrent_repository.get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT); + let peers = torrent_repository + .get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT) + .unwrap(); assert_eq!(peers, vec![]); } @@ -455,7 +493,9 @@ mod tests { let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); } - let peers = torrent_repository.get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT); + let peers = torrent_repository + .get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT) + .unwrap(); assert_eq!(peers.len(), 74); } @@ -498,9 +538,14 @@ mod tests { let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); // Cut off time is 1 second after the peer was updated - torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); + torrent_repository + .remove_inactive_peers(peer.updated.add(Duration::from_secs(1))) + .unwrap(); - assert!(!torrent_repository.get_torrent_peers(&info_hash, 74).contains(&Arc::new(peer))); + assert!(!torrent_repository + .get_torrent_peers(&info_hash, 74) + .unwrap() + .contains(&Arc::new(peer))); } fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { @@ -512,7 +557,9 @@ mod tests { let _number_of_downloads_increased = torrent_repository.upsert_peer(info_hash, &peer, None); // Remove the peer - torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); + torrent_repository + .remove_inactive_peers(peer.updated.add(Duration::from_secs(1))) + .unwrap(); torrent_repository } @@ -528,7 +575,7 @@ mod tests { ..Default::default() }; - torrent_repository.remove_peerless_torrents(&tracker_policy); + torrent_repository.remove_peerless_torrents(&tracker_policy).unwrap(); assert!(torrent_repository.get(&info_hash).is_none()); } @@ -755,7 +802,7 @@ mod tests { async fn it_should_get_empty_aggregate_swarm_metadata_when_there_are_no_torrents() { let torrent_repository = Arc::new(Swarms::default()); - let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata(); + let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata().unwrap(); assert_eq!( aggregate_swarm_metadata, @@ -774,7 +821,7 @@ mod tests { let _number_of_downloads_increased = torrent_repository.upsert_peer(&sample_info_hash(), &leecher(), None); - let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata(); + let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata().unwrap(); assert_eq!( aggregate_swarm_metadata, @@ -793,7 +840,7 @@ mod tests { let _number_of_downloads_increased = torrent_repository.upsert_peer(&sample_info_hash(), &seeder(), None); - let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata(); + let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata().unwrap(); assert_eq!( aggregate_swarm_metadata, @@ -812,7 +859,7 @@ mod tests { let _number_of_downloads_increased = torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer(), None); - let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata(); + let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata().unwrap(); assert_eq!( aggregate_swarm_metadata, @@ -837,7 +884,7 @@ mod tests { let result_a = start_time.elapsed(); let start_time = std::time::Instant::now(); - let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata(); + let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata().unwrap(); let result_b = start_time.elapsed(); assert_eq!( @@ -870,7 +917,7 @@ mod tests { let _number_of_downloads_increased = torrent_repository.upsert_peer(&infohash, &leecher(), None); - let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&infohash); + let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&infohash).unwrap(); assert_eq!( swarm_metadata, @@ -886,7 +933,7 @@ mod tests { async fn it_should_return_zeroed_swarm_metadata_for_a_non_existing_torrent() { let torrent_repository = Arc::new(Swarms::default()); - let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&sample_info_hash()); + let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&sample_info_hash()).unwrap(); assert_eq!(swarm_metadata, SwarmMetadata::zeroed()); } @@ -913,7 +960,7 @@ mod tests { torrent_repository.import_persistent(&persistent_torrents); - let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&infohash); + let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&infohash).unwrap(); // Only the number of downloads is persisted. assert_eq!(swarm_metadata.downloaded, 1); diff --git a/packages/torrent-repository/tests/swarms/mod.rs b/packages/torrent-repository/tests/swarms/mod.rs index 20c6255fa..82247bfcb 100644 --- a/packages/torrent-repository/tests/swarms/mod.rs +++ b/packages/torrent-repository/tests/swarms/mod.rs @@ -329,7 +329,7 @@ async fn it_should_get_metrics(#[values(swarms())] swarms: Swarms, #[case] entri metrics.total_downloaded += u64::from(stats.downloaded); } - assert_eq!(swarms.get_aggregate_swarm_metadata(), metrics); + assert_eq!(swarms.get_aggregate_swarm_metadata().unwrap(), metrics); } #[rstest] @@ -349,12 +349,12 @@ async fn it_should_import_persistent_torrents( ) { make(&swarms, &entries); - let mut downloaded = swarms.get_aggregate_swarm_metadata().total_downloaded; + let mut downloaded = swarms.get_aggregate_swarm_metadata().unwrap().total_downloaded; persistent_torrents.iter().for_each(|(_, d)| downloaded += u64::from(*d)); swarms.import_persistent(&persistent_torrents); - assert_eq!(swarms.get_aggregate_swarm_metadata().total_downloaded, downloaded); + assert_eq!(swarms.get_aggregate_swarm_metadata().unwrap().total_downloaded, downloaded); for (entry, _) in persistent_torrents { assert!(swarms.get(&entry).is_some()); @@ -388,7 +388,7 @@ async fn it_should_remove_an_entry(#[values(swarms())] swarms: Swarms, #[case] e assert!(swarms.remove(&info_hash).is_none()); } - assert_eq!(swarms.get_aggregate_swarm_metadata().total_torrents, 0); + assert_eq!(swarms.get_aggregate_swarm_metadata().unwrap().total_torrents, 0); } #[rstest] @@ -438,15 +438,18 @@ async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[c // Insert the infohash and peer into the repository // and verify there is an extra torrent entry. { - swarms.upsert_peer(&info_hash, &peer, None); - assert_eq!(swarms.get_aggregate_swarm_metadata().total_torrents, entries.len() as u64 + 1); + swarms.upsert_peer(&info_hash, &peer, None).unwrap(); + assert_eq!( + swarms.get_aggregate_swarm_metadata().unwrap().total_torrents, + entries.len() as u64 + 1 + ); } // Insert the infohash and peer into the repository // and verify the swarm metadata was updated. { - swarms.upsert_peer(&info_hash, &peer, None); - let stats = swarms.get_swarm_metadata(&info_hash); + swarms.upsert_peer(&info_hash, &peer, None).unwrap(); + let stats = swarms.get_swarm_metadata(&info_hash).unwrap(); assert_eq!( stats, Some(SwarmMetadata { @@ -466,7 +469,9 @@ async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[c // Remove peers that have not been updated since the timeout (120 seconds ago). { - swarms.remove_inactive_peers(CurrentClock::now_sub(&TIMEOUT).expect("it should get a time passed")); + swarms + .remove_inactive_peers(CurrentClock::now_sub(&TIMEOUT).expect("it should get a time passed")) + .unwrap(); } // Verify that the this peer was removed from the repository. @@ -494,7 +499,7 @@ async fn it_should_remove_peerless_torrents( ) { make(&swarms, &entries); - swarms.remove_peerless_torrents(&policy); + swarms.remove_peerless_torrents(&policy).unwrap(); let torrents: Vec<(InfoHash, Swarm)> = swarms .get_paginated(None) diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 5902f6735..8c93f3605 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -39,6 +39,10 @@ impl InMemoryTorrentRepository { /// # Returns /// /// `true` if the peer stats were updated. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. #[must_use] pub fn upsert_peer( &self, @@ -46,7 +50,9 @@ impl InMemoryTorrentRepository { peer: &peer::Peer, opt_persistent_torrent: Option, ) -> bool { - self.swarms.upsert_peer(info_hash, peer, opt_persistent_torrent) + self.swarms + .upsert_peer(info_hash, peer, opt_persistent_torrent) + .expect("Failed to upsert the peer in swarms") } /// Removes a torrent entry from the repository. @@ -77,8 +83,14 @@ impl InMemoryTorrentRepository { /// /// * `current_cutoff` - The cutoff timestamp; peers not updated since this /// time will be removed. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. pub(crate) fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { - self.swarms.remove_inactive_peers(current_cutoff); + self.swarms + .remove_inactive_peers(current_cutoff) + .expect("Failed to remove inactive peers from swarms"); } /// Removes torrent entries that have no active peers. @@ -90,8 +102,14 @@ impl InMemoryTorrentRepository { /// /// * `policy` - The tracker policy containing the configuration for /// removing peerless torrents. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. pub(crate) fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { - self.swarms.remove_peerless_torrents(policy); + self.swarms + .remove_peerless_torrents(policy) + .expect("Failed to remove peerless torrents from swarms"); } /// Retrieves a torrent entry by its infohash. @@ -139,9 +157,15 @@ impl InMemoryTorrentRepository { /// # Returns /// /// A `SwarmMetadata` struct containing the aggregated torrent data. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error.s #[must_use] pub(crate) fn get_swarm_metadata_or_default(&self, info_hash: &InfoHash) -> SwarmMetadata { - self.swarms.get_swarm_metadata_or_default(info_hash) + self.swarms + .get_swarm_metadata_or_default(info_hash) + .expect("Failed to get swarm metadata") } /// Retrieves torrent peers for a given torrent and client, excluding the @@ -161,9 +185,15 @@ impl InMemoryTorrentRepository { /// /// A vector of peers (wrapped in `Arc`) representing the active peers for /// the torrent, excluding the requesting client. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. #[must_use] pub(crate) fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { - self.swarms.get_peers_for(info_hash, peer, max(limit, TORRENT_PEERS_LIMIT)) + self.swarms + .get_peers_for(info_hash, peer, max(limit, TORRENT_PEERS_LIMIT)) + .expect("Failed to get other peers in swarm") } /// Retrieves the list of peers for a given torrent. @@ -182,11 +212,13 @@ impl InMemoryTorrentRepository { /// /// # Panics /// - /// This function panics if the lock for the torrent entry cannot be obtained. + /// This function panics if the underling swarms return an error. #[must_use] pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { // todo: pass the limit as an argument like `get_peers_for` - self.swarms.get_torrent_peers(info_hash, TORRENT_PEERS_LIMIT) + self.swarms + .get_torrent_peers(info_hash, TORRENT_PEERS_LIMIT) + .expect("Failed to get other peers in swarm") } /// Calculates and returns overall torrent metrics. @@ -198,9 +230,15 @@ impl InMemoryTorrentRepository { /// # Returns /// /// A [`AggregateSwarmMetadata`] struct with the aggregated metrics. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. #[must_use] pub fn get_aggregate_swarm_metadata(&self) -> AggregateSwarmMetadata { - self.swarms.get_aggregate_swarm_metadata() + self.swarms + .get_aggregate_swarm_metadata() + .expect("Failed to get aggregate swarm metadata") } /// Imports persistent torrent data into the in-memory repository. From 31f1fbf32216fbb1f1fc43c5c103af44e25bb462 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 7 May 2025 12:07:15 +0100 Subject: [PATCH 1074/1297] refactgor: [#1495] make field private It was public only to allow setting a pre-defined state in tests. A new public method have been adding temporarily to explain its usage. --- packages/torrent-repository/src/swarms.rs | 14 +++++++++++--- packages/torrent-repository/tests/swarms/mod.rs | 9 +++------ 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 222bea60a..34cd52d3b 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -1,4 +1,4 @@ -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use bittorrent_primitives::info_hash::InfoHash; use crossbeam_skiplist::SkipMap; @@ -12,8 +12,7 @@ use crate::SwarmHandle; #[derive(Default, Debug)] pub struct Swarms { - // todo: this needs to be public only to insert a peerless torrent (empty swarm). - pub swarms: SkipMap, + swarms: SkipMap, } impl Swarms { @@ -62,6 +61,15 @@ impl Swarms { } } + /// Inserts a new swarm. It's only used for testing purposes. It allows to + /// pre-define the initial state of the swarm without having to go through + /// the upsert process. + pub fn insert_swarm(&self, info_hash: &InfoHash, swarm: Swarm) { + // code-review: swarms builder? + let swarm_handle = Arc::new(Mutex::new(swarm)); + self.swarms.insert(*info_hash, swarm_handle); + } + /// Removes a torrent entry from the repository. /// /// # Returns diff --git a/packages/torrent-repository/tests/swarms/mod.rs b/packages/torrent-repository/tests/swarms/mod.rs index 82247bfcb..43571eb83 100644 --- a/packages/torrent-repository/tests/swarms/mod.rs +++ b/packages/torrent-repository/tests/swarms/mod.rs @@ -1,6 +1,5 @@ use std::collections::{BTreeMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; -use std::sync::{Arc, Mutex}; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use bittorrent_primitives::info_hash::InfoHash; @@ -148,11 +147,9 @@ fn persistent_three() -> PersistentTorrents { t.iter().copied().collect() } -fn make(repo: &Swarms, entries: &Entries) { - for (info_hash, entry) in entries { - let new = Arc::new(Mutex::new(entry.clone())); - // todo: use a public method to insert an empty swarm. - repo.swarms.insert(*info_hash, new); +fn make(swarms: &Swarms, entries: &Entries) { + for (info_hash, swarm) in entries { + swarms.insert_swarm(info_hash, swarm.clone()); } } From 5c2c1e0f77c767a945823fb3abf7091caeb17129 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 7 May 2025 12:13:42 +0100 Subject: [PATCH 1075/1297] feat: [#1495] add len and is_empty methods to Swarms type --- packages/torrent-repository/src/swarms.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 34cd52d3b..a03b9d7e6 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -294,6 +294,16 @@ impl Swarms { Ok(metrics) } + + #[must_use] + pub fn len(&self) -> usize { + self.swarms.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.swarms.is_empty() + } } #[derive(thiserror::Error, Debug, Clone)] From 5b3142f6bae735750aa0ebead74b3587bb441f01 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 7 May 2025 12:17:35 +0100 Subject: [PATCH 1076/1297] refactor: [#1495] refactor Swarms::upsert_peer --- packages/torrent-repository/src/swarms.rs | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index a03b9d7e6..fb6652ba5 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -42,23 +42,17 @@ impl Swarms { peer: &peer::Peer, opt_persistent_torrent: Option, ) -> Result { - if let Some(existing_swarm_handle) = self.swarms.get(info_hash) { - let mut swarm = existing_swarm_handle.value().lock()?; - - Ok(swarm.handle_announcement(peer)) + let swarm_handle = if let Some(number_of_downloads) = opt_persistent_torrent { + SwarmHandle::new(Swarm::new(number_of_downloads).into()) } else { - let new_swarm_handle = if let Some(number_of_downloads) = opt_persistent_torrent { - SwarmHandle::new(Swarm::new(number_of_downloads).into()) - } else { - SwarmHandle::default() - }; + SwarmHandle::default() + }; - let inserted_swarm_handle = self.swarms.get_or_insert(*info_hash, new_swarm_handle); + let swarm_handle = self.swarms.get_or_insert(*info_hash, swarm_handle); - let mut swarm = inserted_swarm_handle.value().lock()?; + let mut swarm = swarm_handle.value().lock()?; - Ok(swarm.handle_announcement(peer)) - } + Ok(swarm.handle_announcement(peer)) } /// Inserts a new swarm. It's only used for testing purposes. It allows to From 4d91738d05cc2220ebdea4cb512badbf1809074f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 7 May 2025 12:58:21 +0100 Subject: [PATCH 1077/1297] refactor: [#1495] renamings in torrent-repository pkg --- packages/torrent-repository/src/swarms.rs | 189 +++++++++--------- .../torrent-repository/tests/swarms/mod.rs | 6 +- .../src/torrent/repository/in_memory.rs | 6 +- 3 files changed, 102 insertions(+), 99 deletions(-) diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index fb6652ba5..828e8c030 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -36,7 +36,7 @@ impl Swarms { /// # Errors /// /// This function panics if the lock for the swarm handle cannot be acquired. - pub fn upsert_peer( + pub fn handle_announcement( &self, info_hash: &InfoHash, peer: &peer::Peer, @@ -55,11 +55,13 @@ impl Swarms { Ok(swarm.handle_announcement(peer)) } - /// Inserts a new swarm. It's only used for testing purposes. It allows to - /// pre-define the initial state of the swarm without having to go through - /// the upsert process. - pub fn insert_swarm(&self, info_hash: &InfoHash, swarm: Swarm) { + /// Inserts a new swarm. + pub fn insert(&self, info_hash: &InfoHash, swarm: Swarm) { // code-review: swarms builder? + // It's only used for testing purposes. It allows to pre-define the + // initial state of the swarm without having to go through the upsert + // process. + let swarm_handle = Arc::new(Mutex::new(swarm)); self.swarms.insert(*info_hash, swarm_handle); } @@ -184,7 +186,12 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for the /// swarm handle. - pub fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Result>, Error> { + pub fn get_peers_peers_excluding( + &self, + info_hash: &InfoHash, + peer: &peer::Peer, + limit: usize, + ) -> Result>, Error> { match self.get(info_hash) { None => Ok(vec![]), Some(swarm_handle) => { @@ -208,7 +215,7 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for the /// swarm handle. - pub fn get_torrent_peers(&self, info_hash: &InfoHash, limit: usize) -> Result>, Error> { + pub fn get_swarm_peers(&self, info_hash: &InfoHash, limit: usize) -> Result>, Error> { match self.get(info_hash) { None => Ok(vec![]), Some(swarm_handle) => { @@ -356,25 +363,25 @@ mod tests { #[tokio::test] async fn it_should_add_the_first_peer_to_the_torrent_peer_list() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &sample_peer(), None); - assert!(torrent_repository.get(&info_hash).is_some()); + assert!(swarms.get(&info_hash).is_some()); } #[tokio::test] async fn it_should_allow_adding_the_same_peer_twice_to_the_torrent_peer_list() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &sample_peer(), None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &sample_peer(), None); - assert!(torrent_repository.get(&info_hash).is_some()); + assert!(swarms.get(&info_hash).is_some()); } } @@ -393,30 +400,30 @@ mod tests { #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); - let peers = torrent_repository.get_torrent_peers(&info_hash, 74).unwrap(); + let peers = swarms.get_swarm_peers(&info_hash, 74).unwrap(); assert_eq!(peers, vec![Arc::new(peer)]); } #[tokio::test] async fn it_should_return_an_empty_list_or_peers_for_a_non_existing_torrent() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); - let peers = torrent_repository.get_torrent_peers(&sample_info_hash(), 74).unwrap(); + let peers = swarms.get_swarm_peers(&sample_info_hash(), 74).unwrap(); assert!(peers.is_empty()); } #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); @@ -431,10 +438,10 @@ mod tests { event: AnnounceEvent::Completed, }; - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); } - let peers = torrent_repository.get_torrent_peers(&info_hash, 74).unwrap(); + let peers = swarms.get_swarm_peers(&info_hash, 74).unwrap(); assert_eq!(peers.len(), 74); } @@ -455,10 +462,10 @@ mod tests { #[tokio::test] async fn it_should_return_an_empty_peer_list_for_a_non_existing_torrent() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); - let peers = torrent_repository - .get_peers_for(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT) + let peers = swarms + .get_peers_peers_excluding(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT) .unwrap(); assert_eq!(peers, vec![]); @@ -466,15 +473,15 @@ mod tests { #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); - let peers = torrent_repository - .get_peers_for(&info_hash, &peer, TORRENT_PEERS_LIMIT) + let peers = swarms + .get_peers_peers_excluding(&info_hash, &peer, TORRENT_PEERS_LIMIT) .unwrap(); assert_eq!(peers, vec![]); @@ -482,13 +489,13 @@ mod tests { #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); let excluded_peer = sample_peer(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &excluded_peer, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &excluded_peer, None); // Add 74 peers for idx in 2..=75 { @@ -502,11 +509,11 @@ mod tests { event: AnnounceEvent::Completed, }; - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); } - let peers = torrent_repository - .get_peers_for(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT) + let peers = swarms + .get_peers_peers_excluding(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT) .unwrap(); assert_eq!(peers.len(), 74); @@ -529,67 +536,64 @@ mod tests { #[tokio::test] async fn it_should_remove_a_torrent_entry() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &sample_peer(), None); - let _unused = torrent_repository.remove(&info_hash); + let _unused = swarms.remove(&info_hash); - assert!(torrent_repository.get(&info_hash).is_none()); + assert!(swarms.get(&info_hash).is_none()); } #[tokio::test] async fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); // Cut off time is 1 second after the peer was updated - torrent_repository + swarms .remove_inactive_peers(peer.updated.add(Duration::from_secs(1))) .unwrap(); - assert!(!torrent_repository - .get_torrent_peers(&info_hash, 74) - .unwrap() - .contains(&Arc::new(peer))); + assert!(!swarms.get_swarm_peers(&info_hash, 74).unwrap().contains(&Arc::new(peer))); } fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); // Insert a sample peer for the torrent to force adding the torrent entry let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = torrent_repository.upsert_peer(info_hash, &peer, None); + let _number_of_downloads_increased = swarms.handle_announcement(info_hash, &peer, None); // Remove the peer - torrent_repository + swarms .remove_inactive_peers(peer.updated.add(Duration::from_secs(1))) .unwrap(); - torrent_repository + swarms } #[tokio::test] async fn it_should_remove_torrents_without_peers() { let info_hash = sample_info_hash(); - let torrent_repository = initialize_repository_with_one_torrent_without_peers(&info_hash); + let swarms = initialize_repository_with_one_torrent_without_peers(&info_hash); let tracker_policy = TrackerPolicy { remove_peerless_torrents: true, ..Default::default() }; - torrent_repository.remove_peerless_torrents(&tracker_policy).unwrap(); + swarms.remove_peerless_torrents(&tracker_policy).unwrap(); - assert!(torrent_repository.get(&info_hash).is_none()); + assert!(swarms.get(&info_hash).is_none()); } } mod returning_torrent_entries { @@ -632,14 +636,14 @@ mod tests { #[tokio::test] async fn it_should_return_one_torrent_entry_by_infohash() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); - let torrent_entry = torrent_repository.get(&info_hash).unwrap(); + let torrent_entry = swarms.get(&info_hash).unwrap(); assert_eq!( TorrentEntryInfo { @@ -666,13 +670,13 @@ mod tests { #[tokio::test] async fn without_pagination() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash, &peer, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); - let torrent_entries = torrent_repository.get_paginated(None); + let torrent_entries = swarms.get_paginated(None); assert_eq!(torrent_entries.len(), 1); @@ -707,20 +711,20 @@ mod tests { #[tokio::test] async fn it_should_return_the_first_page() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash_one, &peer_one, None); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash_one, &peer_two, None); // Get only the first page where page size is 1 - let torrent_entries = torrent_repository.get_paginated(Some(&Pagination { offset: 0, limit: 1 })); + let torrent_entries = swarms.get_paginated(Some(&Pagination { offset: 0, limit: 1 })); assert_eq!(torrent_entries.len(), 1); @@ -742,20 +746,20 @@ mod tests { #[tokio::test] async fn it_should_return_the_second_page() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash_one, &peer_one, None); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash_one, &peer_two, None); // Get only the first page where page size is 1 - let torrent_entries = torrent_repository.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); + let torrent_entries = swarms.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); assert_eq!(torrent_entries.len(), 1); @@ -777,20 +781,20 @@ mod tests { #[tokio::test] async fn it_should_allow_changing_the_page_size() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash_one, &peer_one, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash_one, &peer_one, None); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&info_hash_one, &peer_two, None); + let _number_of_downloads_increased = swarms.handle_announcement(&info_hash_one, &peer_two, None); // Get only the first page where page size is 1 - let torrent_entries = torrent_repository.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); + let torrent_entries = swarms.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); assert_eq!(torrent_entries.len(), 1); } @@ -812,9 +816,9 @@ mod tests { #[tokio::test] async fn it_should_get_empty_aggregate_swarm_metadata_when_there_are_no_torrents() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); - let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata().unwrap(); + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); assert_eq!( aggregate_swarm_metadata, @@ -829,11 +833,11 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_leecher() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&sample_info_hash(), &leecher(), None); + let _number_of_downloads_increased = swarms.handle_announcement(&sample_info_hash(), &leecher(), None); - let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata().unwrap(); + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); assert_eq!( aggregate_swarm_metadata, @@ -848,11 +852,11 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_seeder() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&sample_info_hash(), &seeder(), None); + let _number_of_downloads_increased = swarms.handle_announcement(&sample_info_hash(), &seeder(), None); - let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata().unwrap(); + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); assert_eq!( aggregate_swarm_metadata, @@ -867,11 +871,11 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_completed_peer() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&sample_info_hash(), &complete_peer(), None); + let _number_of_downloads_increased = swarms.handle_announcement(&sample_info_hash(), &complete_peer(), None); - let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata().unwrap(); + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); assert_eq!( aggregate_swarm_metadata, @@ -886,17 +890,16 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_are_multiple_torrents() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let start_time = std::time::Instant::now(); for i in 0..1_000_000 { - let _number_of_downloads_increased = - torrent_repository.upsert_peer(&gen_seeded_infohash(&i), &leecher(), None); + let _number_of_downloads_increased = swarms.handle_announcement(&gen_seeded_infohash(&i), &leecher(), None); } let result_a = start_time.elapsed(); let start_time = std::time::Instant::now(); - let aggregate_swarm_metadata = torrent_repository.get_aggregate_swarm_metadata().unwrap(); + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); let result_b = start_time.elapsed(); assert_eq!( @@ -923,13 +926,13 @@ mod tests { #[tokio::test] async fn it_should_get_swarm_metadata_for_an_existing_torrent() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let infohash = sample_info_hash(); - let _number_of_downloads_increased = torrent_repository.upsert_peer(&infohash, &leecher(), None); + let _number_of_downloads_increased = swarms.handle_announcement(&infohash, &leecher(), None); - let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&infohash).unwrap(); + let swarm_metadata = swarms.get_swarm_metadata_or_default(&infohash).unwrap(); assert_eq!( swarm_metadata, @@ -943,9 +946,9 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_for_a_non_existing_torrent() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); - let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&sample_info_hash()).unwrap(); + let swarm_metadata = swarms.get_swarm_metadata_or_default(&sample_info_hash()).unwrap(); assert_eq!(swarm_metadata, SwarmMetadata::zeroed()); } @@ -962,7 +965,7 @@ mod tests { #[tokio::test] async fn it_should_allow_importing_persisted_torrent_entries() { - let torrent_repository = Arc::new(Swarms::default()); + let swarms = Arc::new(Swarms::default()); let infohash = sample_info_hash(); @@ -970,9 +973,9 @@ mod tests { persistent_torrents.insert(infohash, 1); - torrent_repository.import_persistent(&persistent_torrents); + swarms.import_persistent(&persistent_torrents); - let swarm_metadata = torrent_repository.get_swarm_metadata_or_default(&infohash).unwrap(); + let swarm_metadata = swarms.get_swarm_metadata_or_default(&infohash).unwrap(); // Only the number of downloads is persisted. assert_eq!(swarm_metadata.downloaded, 1); diff --git a/packages/torrent-repository/tests/swarms/mod.rs b/packages/torrent-repository/tests/swarms/mod.rs index 43571eb83..8e58b9e76 100644 --- a/packages/torrent-repository/tests/swarms/mod.rs +++ b/packages/torrent-repository/tests/swarms/mod.rs @@ -149,7 +149,7 @@ fn persistent_three() -> PersistentTorrents { fn make(swarms: &Swarms, entries: &Entries) { for (info_hash, swarm) in entries { - swarms.insert_swarm(info_hash, swarm.clone()); + swarms.insert(info_hash, swarm.clone()); } } @@ -435,7 +435,7 @@ async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[c // Insert the infohash and peer into the repository // and verify there is an extra torrent entry. { - swarms.upsert_peer(&info_hash, &peer, None).unwrap(); + swarms.handle_announcement(&info_hash, &peer, None).unwrap(); assert_eq!( swarms.get_aggregate_swarm_metadata().unwrap().total_torrents, entries.len() as u64 + 1 @@ -445,7 +445,7 @@ async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[c // Insert the infohash and peer into the repository // and verify the swarm metadata was updated. { - swarms.upsert_peer(&info_hash, &peer, None).unwrap(); + swarms.handle_announcement(&info_hash, &peer, None).unwrap(); let stats = swarms.get_swarm_metadata(&info_hash).unwrap(); assert_eq!( stats, diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 8c93f3605..38593bf3c 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -51,7 +51,7 @@ impl InMemoryTorrentRepository { opt_persistent_torrent: Option, ) -> bool { self.swarms - .upsert_peer(info_hash, peer, opt_persistent_torrent) + .handle_announcement(info_hash, peer, opt_persistent_torrent) .expect("Failed to upsert the peer in swarms") } @@ -192,7 +192,7 @@ impl InMemoryTorrentRepository { #[must_use] pub(crate) fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { self.swarms - .get_peers_for(info_hash, peer, max(limit, TORRENT_PEERS_LIMIT)) + .get_peers_peers_excluding(info_hash, peer, max(limit, TORRENT_PEERS_LIMIT)) .expect("Failed to get other peers in swarm") } @@ -217,7 +217,7 @@ impl InMemoryTorrentRepository { pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { // todo: pass the limit as an argument like `get_peers_for` self.swarms - .get_torrent_peers(info_hash, TORRENT_PEERS_LIMIT) + .get_swarm_peers(info_hash, TORRENT_PEERS_LIMIT) .expect("Failed to get other peers in swarm") } From 4b5e914ad90c7a36552574eca65600c69c24e3f6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 7 May 2025 14:20:45 +0100 Subject: [PATCH 1078/1297] chore(deps): update dependencies ```output cargo update Updating crates.io index Locking 15 packages to latest compatible versions Updating backtrace v0.3.74 -> v0.3.75 Updating brotli v8.0.0 -> v8.0.1 Updating docker_credential v1.3.1 -> v1.3.2 Updating etcetera v0.8.0 -> v0.10.0 Updating h2 v0.4.9 -> v0.4.10 Updating hermit-abi v0.5.0 -> v0.5.1 Updating libm v0.2.13 -> v0.2.15 Updating local-ip-address v0.6.4 -> v0.6.5 Updating redox_syscall v0.5.11 -> v0.5.12 Updating rustls v0.23.26 -> v0.23.27 Updating rustls-pki-types v1.11.0 -> v1.12.0 Updating rustls-webpki v0.103.1 -> v0.103.2 Updating testcontainers v0.23.3 -> v0.24.0 Updating tokio v1.44.2 -> v1.45.0 Removing windows-sys v0.48.0 Removing windows-targets v0.48.5 Removing windows_aarch64_gnullvm v0.48.5 Removing windows_aarch64_msvc v0.48.5 Removing windows_i686_gnu v0.48.5 Removing windows_i686_msvc v0.48.5 Removing windows_x86_64_gnu v0.48.5 Removing windows_x86_64_gnullvm v0.48.5 Removing windows_x86_64_msvc v0.48.5 Updating winnow v0.7.8 -> v0.7.10 ``` --- Cargo.lock | 137 +++++++++++++++-------------------------------------- 1 file changed, 37 insertions(+), 100 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 093b8e9b0..80f98db36 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -482,9 +482,9 @@ dependencies = [ [[package]] name = "backtrace" -version = "0.3.74" +version = "0.3.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" +checksum = "6806a6321ec58106fea15becdad98371e28d92ccbc7c8f1b3b6dd724fe8f1002" dependencies = [ "addr2line", "cfg-if", @@ -849,9 +849,9 @@ dependencies = [ [[package]] name = "brotli" -version = "8.0.0" +version = "8.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf19e729cdbd51af9a397fb9ef8ac8378007b797f8273cfbfdf45dcaa316167b" +checksum = "9991eea70ea4f293524138648e41ee89b0b2b12ddef3b255effa43c8056e0e0d" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -1407,9 +1407,9 @@ dependencies = [ [[package]] name = "docker_credential" -version = "1.3.1" +version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31951f49556e34d90ed28342e1df7e1cb7a229c4cab0aecc627b5d91edd41d07" +checksum = "1d89dfcba45b4afad7450a99b39e751590463e45c04728cf555d36bb66940de8" dependencies = [ "base64 0.21.7", "serde", @@ -1465,13 +1465,13 @@ dependencies = [ [[package]] name = "etcetera" -version = "0.8.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +checksum = "26c7b13d0780cb82722fd59f6f57f925e143427e4a75313a6c77243bf5326ae6" dependencies = [ "cfg-if", "home", - "windows-sys 0.48.0", + "windows-sys 0.59.0", ] [[package]] @@ -1859,9 +1859,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.9" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75249d144030531f8dee69fe9cea04d3edf809a017ae445e2abdff6629e86633" +checksum = "a9421a676d1b147b16b82c9225157dc629087ef8ec4d5e2960f9437a90dac0a5" dependencies = [ "atomic-waker", "bytes", @@ -1935,9 +1935,9 @@ checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" [[package]] name = "hermit-abi" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbd780fe5cc30f81464441920d82ac8740e2e46b29a6fad543ddd075229ce37e" +checksum = "f154ce46856750ed433c8649605bf7ed2de3bc35fd9d2a9f30cddd873c80cb08" [[package]] name = "hex" @@ -2337,7 +2337,7 @@ version = "0.4.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" dependencies = [ - "hermit-abi 0.5.0", + "hermit-abi 0.5.1", "libc", "windows-sys 0.59.0", ] @@ -2431,9 +2431,9 @@ dependencies = [ [[package]] name = "libm" -version = "0.2.13" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9627da5196e5d8ed0b0495e61e518847578da83483c37288316d9b2e03a7f72" +checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" [[package]] name = "libredox" @@ -2443,7 +2443,7 @@ checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ "bitflags 2.9.0", "libc", - "redox_syscall 0.5.11", + "redox_syscall 0.5.12", ] [[package]] @@ -2488,9 +2488,9 @@ checksum = "23fb14cb19457329c82206317a5663005a4d404783dc74f4252769b0d5f42856" [[package]] name = "local-ip-address" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c986b1747bbd3666abe4d57c64e60e6a82c2216140d8b12d5ceb33feb9de44b3" +checksum = "656b3b27f8893f7bbf9485148ff9a65f019e3f33bd5cdc87c83cab16b3fd9ec8" dependencies = [ "libc", "neli", @@ -2929,7 +2929,7 @@ checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.11", + "redox_syscall 0.5.12", "smallvec", "windows-targets 0.52.6", ] @@ -3401,9 +3401,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.11" +version = "0.5.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2f103c6d277498fbceb16e84d317e2a400f160f46904d5f5410848c829511a3" +checksum = "928fca9cf2aa042393a8325b9ead81d2f0df4cb12e1e24cef072922ccd99c5af" dependencies = [ "bitflags 2.9.0", ] @@ -3659,9 +3659,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.26" +version = "0.23.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df51b5869f3a441595eac5e8ff14d486ff285f7b8c0df8770e49c3b56351f0f0" +checksum = "730944ca083c1c233a75c09f199e973ca499344a2b7ba9e755c457e86fb4a321" dependencies = [ "once_cell", "ring", @@ -3694,15 +3694,18 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "917ce264624a4b4db1c364dcc35bfca9ded014d0a958cd47ad3e960e988ea51c" +checksum = "229a4a4c221013e7e1f1a043678c5cc39fe5171437c88fb47151a21e6f5b5c79" +dependencies = [ + "zeroize", +] [[package]] name = "rustls-webpki" -version = "0.103.1" +version = "0.103.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fef8b8769aaccf73098557a87cd1816b4f9c7c16811c9c77142aa695c16f2c03" +checksum = "7149975849f1abb3832b246010ef62ccc80d3a76169517ada7188252b9cfb437" dependencies = [ "ring", "rustls-pki-types", @@ -4232,9 +4235,9 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "testcontainers" -version = "0.23.3" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a4f01f39bb10fc2a5ab23eb0d888b1e2bb168c157f61a1b98e6c501c639c74" +checksum = "23bb7577dca13ad86a78e8271ef5d322f37229ec83b8d98da6d996c588a1ddb1" dependencies = [ "async-trait", "bollard", @@ -4387,9 +4390,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.44.2" +version = "1.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48" +checksum = "2513ca694ef9ede0fb23fe71a4ee4107cb102b9dc1930f6d0fd77aae068ae165" dependencies = [ "backtrace", "bytes", @@ -5388,15 +5391,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", -] - [[package]] name = "windows-sys" version = "0.52.0" @@ -5415,21 +5409,6 @@ dependencies = [ "windows-targets 0.52.6", ] -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - [[package]] name = "windows-targets" version = "0.52.6" @@ -5462,12 +5441,6 @@ dependencies = [ "windows_x86_64_msvc 0.53.0", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -5480,12 +5453,6 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" @@ -5498,12 +5465,6 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -5528,12 +5489,6 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - [[package]] name = "windows_i686_msvc" version = "0.52.6" @@ -5546,12 +5501,6 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" @@ -5564,12 +5513,6 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" @@ -5582,12 +5525,6 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -5602,9 +5539,9 @@ checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" [[package]] name = "winnow" -version = "0.7.8" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e27d6ad3dac991091e4d35de9ba2d2d00647c5d0fc26c5496dee55984ae111b" +checksum = "c06928c8748d81b05c9be96aad92e1b6ff01833332f281e8cfca3be4b35fc9ec" dependencies = [ "memchr", ] From 32a37d148ca1258d47a9bcf3fbbfb3a3d99a1ba8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 7 May 2025 17:06:24 +0100 Subject: [PATCH 1079/1297] fix: [#1502] bug in total number of downloads for all torrents metric Relates to: https://github.com/torrust/torrust-tracker/pull/1497/commits/34c159a161b7c167730f6c139dd3cb608173d37a A couple of days ago, I made a change in [this commit](https://github.com/torrust/torrust-tracker/pull/1497/commits/34c159a161b7c167730f6c139dd3cb608173d37a). I changed the `Swarm::meets_retaining_policy` method from: ``` /// Returns true if the torrents meets the retention policy, meaning that /// it should be kept in the tracker. pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { if policy.persistent_torrent_completed_stat && self.metadata().downloaded > 0 { return true; } if policy.remove_peerless_torrents && self.is_empty() { return false; } true } ``` To: ``` pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { !(policy.remove_peerless_torrents && self.is_empty()) } ``` I thought this code was not needed: ```rust if policy.persistent_torrent_completed_stat && self.metadata().downloaded > 0 { return true; } ``` However, it's needed. One of the metrics returned by the tracker API is the **total number of downloads for all torrents**. ```json { "torrents": 320961, "seeders": 189885, "completed": 975119, <- this "leechers": 231044, ... } ``` That metric is always stored in memory but can optionally persist into the database. It's important to highlight that the metric represents: - The total number of downloads for **ALL** torrents ever, when the metric is persisted. - The total number of downloads for **ALL** torrents since the tracker started, when the metric is not persisted. It could be mixed up with another internal metric (not exposed via the API), which is the same counter but only for ONE swarm (one torrent). - The total number of downloads for **ONE** concrete torrent ever, when the metric is persisted. - The total number of downloads for **ONE** concrete torrent since the tracker started, when the metric is not persisted. The bug affects the first metric. The exposed via the API. The problem is that this feature conflicts with removing the peerless torrents. When removing the peerless torrents config option is enabled, the counter is lost unless it is persisted. Becuase the counter values are stored in the "Swarm" together with the list of peers. If statistics persistence is enabled, that's not a problem. When the torrent is removed from the tracker (from the swarms or swarm collection), the counter is initialised again if the torrent is added. In other words, if a new peer starts the swarm again, the number of downloads is loaded from the database. However, that works for the counter of each torrent (swarm) but not for the overall counter (the sum of downloads for all torrents). That metric is not stored anywhere. It's calculated on demand by iterating all the swarms and summing up the total for each torrent, giving the total amount of downloads for **ALL** torrents. When the torrent is removed, the downloads for that torrent don't count in the total. That is the reason we have to keep the torrent (swarm) in memory, even if it does not have any peer (and it should be removed according to the other config flag). The removed line: ```rust if policy.persistent_torrent_completed_stat && self.metadata().downloaded > 0 { return true; } ``` does that. **When the stats persistence is disabled**, that's one way to store the value. Alternatively, we could add another cache for the data and never remove that value. The current solution has a problem: It can make the tracker consume a lot of memory because peerless torrents are not removed in practice (even if it's configured to be). **When the stats persistence is enabled,** we can simply return the value from the database. **NOTICE:** that the value is used in the scrape response, so it might be convenient to have a cache in memory anyway. - [x] Revert the change to fix the bug asap. - [x] Write a unit test. This behaviour was not covered by any test (or documented). - [ ] Add an in-memory cache value in `Swarms` type to store the total for all torrents, regardless of which are the current active swarms. --- packages/torrent-repository/src/swarm.rs | 122 +++++++++++++++++++---- 1 file changed, 102 insertions(+), 20 deletions(-) diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 1a17a2fb6..e5b5d598c 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -191,10 +191,20 @@ impl Swarm { } /// Returns true if the swarm meets the retention policy, meaning that - /// it should be kept in the tracker. + /// it should be kept in the list of swarms. #[must_use] pub fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool { - !(policy.remove_peerless_torrents && self.is_empty()) + !self.should_be_removed(policy) + } + + fn should_be_removed(&self, policy: &TrackerPolicy) -> bool { + // If the policy is to remove peerless torrents and the swarm is empty (no peers), + (policy.remove_peerless_torrents && self.is_empty()) + // but not when the policy is to persist torrent stats and the + // torrent has been downloaded at least once. + // (because the only way to store the counter is to keep the swarm in memory. + // See https://github.com/torrust/torrust-tracker/issues/1502) + && !(policy.persistent_torrent_completed_stat && self.metadata().downloaded > 0) } } @@ -205,7 +215,6 @@ mod tests { use std::sync::Arc; use aquatic_udp_protocol::PeerId; - use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; @@ -376,28 +385,101 @@ mod tests { assert_eq!(swarm.len(), 1); } - #[test] - fn it_should_be_kept_when_empty_if_the_tracker_policy_is_not_to_remove_peerless_torrents() { - let empty_swarm = Swarm::default(); + mod for_retaining_policy { - let policy = TrackerPolicy { - remove_peerless_torrents: false, - ..Default::default() - }; + use torrust_tracker_configuration::TrackerPolicy; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; - assert!(empty_swarm.meets_retaining_policy(&policy)); - } + use crate::Swarm; - #[test] - fn it_should_be_removed_when_empty_if_the_tracker_policy_is_to_remove_peerless_torrents() { - let empty_swarm = Swarm::default(); + fn empty_swarm() -> Swarm { + Swarm::default() + } - let policy = TrackerPolicy { - remove_peerless_torrents: true, - ..Default::default() - }; + fn not_empty_swarm() -> Swarm { + let mut swarm = Swarm::default(); + swarm.upsert_peer(PeerBuilder::default().build().into(), &mut false); + swarm + } + + fn not_empty_swarm_with_downloads() -> Swarm { + let mut swarm = Swarm::default(); + + let mut peer = PeerBuilder::leecher().build(); + let mut downloads_increased = false; + + swarm.upsert_peer(peer.into(), &mut downloads_increased); + + peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; + + swarm.upsert_peer(peer.into(), &mut downloads_increased); + + assert!(swarm.metadata().downloads() > 0); + + swarm + } + + fn remove_peerless_torrents_policy() -> TrackerPolicy { + TrackerPolicy { + remove_peerless_torrents: true, + ..Default::default() + } + } + + fn don_not_remove_peerless_torrents_policy() -> TrackerPolicy { + TrackerPolicy { + remove_peerless_torrents: false, + ..Default::default() + } + } - assert!(!empty_swarm.meets_retaining_policy(&policy)); + mod when_removing_peerless_torrents_is_enabled { + + use torrust_tracker_configuration::TrackerPolicy; + + use crate::swarm::tests::for_retaining_policy::{ + empty_swarm, not_empty_swarm, not_empty_swarm_with_downloads, remove_peerless_torrents_policy, + }; + + #[test] + fn it_should_be_removed_if_the_swarm_is_empty() { + assert!(empty_swarm().should_be_removed(&remove_peerless_torrents_policy())); + } + + #[test] + fn it_should_not_be_removed_is_the_swarm_is_not_empty() { + assert!(!not_empty_swarm().should_be_removed(&remove_peerless_torrents_policy())); + } + + #[test] + fn it_should_not_be_removed_even_if_the_swarm_is_empty_if_we_need_to_track_stats_for_downloads_and_there_has_been_downloads( + ) { + let policy = TrackerPolicy { + remove_peerless_torrents: true, + persistent_torrent_completed_stat: true, + ..Default::default() + }; + + assert!(!not_empty_swarm_with_downloads().should_be_removed(&policy)); + } + } + + mod when_removing_peerless_torrents_is_disabled { + + use crate::swarm::tests::for_retaining_policy::{ + don_not_remove_peerless_torrents_policy, empty_swarm, not_empty_swarm, + }; + + #[test] + fn it_should_not_be_removed_even_if_the_swarm_is_empty() { + assert!(!empty_swarm().should_be_removed(&don_not_remove_peerless_torrents_policy())); + } + + #[test] + fn it_should_not_be_removed_is_the_swarm_is_not_empty() { + assert!(!not_empty_swarm().should_be_removed(&don_not_remove_peerless_torrents_policy())); + } + } } #[test] From 57b4822b74c4c8f81f81006dfbb45fb6bbde4e4f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 8 May 2025 11:01:43 +0100 Subject: [PATCH 1080/1297] refactor: remove debug print --- packages/udp-tracker-core/src/services/announce.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index 499da2945..6ea237d84 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -119,8 +119,6 @@ impl AnnounceService { tracing::debug!(target = crate::UDP_TRACKER_LOG_TARGET, "Sending UdpAnnounce event: {event:?}"); - println!("Sending UdpAnnounce event: {event:?}"); - udp_stats_event_sender.send(event).await; } } From f11dfccc852605304a9923d10036a5a7d7502e28 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 8 May 2025 11:04:11 +0100 Subject: [PATCH 1081/1297] feat: [#1502] adding logs for debugging This adds more logs to the torrent's cleanup process. It would be helpful to find the bug described in the issue https://github.com/torrust/torrust-tracker/issues/1502. However, it will be useful afterwards. Sample output: ```output 2025-05-08T10:01:18.417631Z INFO torrust_tracker_lib::bootstrap::jobs::torrent_cleanup: Cleaning up torrents (executed every 60 secs) ... 2025-05-08T10:01:18.417661Z INFO bittorrent_tracker_core::torrent::manager: torrents=1 downloads=2 seeders=2 leechers=0 2025-05-08T10:01:18.417666Z INFO bittorrent_tracker_core::torrent::manager: peerless_torrents=0 peers=2 2025-05-08T10:01:18.417670Z INFO torrust_tracker_torrent_repository::swarms: Removing inactive peers since: 2025-05-08T10:00:48.417669546Z ... 2025-05-08T10:01:18.417676Z INFO torrust_tracker_torrent_repository::swarms: Inactive peers removed: 2 2025-05-08T10:01:18.417679Z INFO bittorrent_tracker_core::torrent::manager: torrents=1 downloads=2 seeders=0 leechers=0 2025-05-08T10:01:18.417682Z INFO bittorrent_tracker_core::torrent::manager: peerless_torrents=1 peers=0 2025-05-08T10:01:18.417685Z INFO torrust_tracker_torrent_repository::swarms: Removing peerless torrents ... 2025-05-08T10:01:18.417688Z INFO torrust_tracker_torrent_repository::swarms: Peerless torrents removed: 0 2025-05-08T10:01:18.417690Z INFO bittorrent_tracker_core::torrent::manager: torrents=1 downloads=2 seeders=0 leechers=0 2025-05-08T10:01:18.417693Z INFO bittorrent_tracker_core::torrent::manager: peerless_torrents=1 peers=0 2025-05-08T10:01:18.417697Z INFO torrust_tracker_lib::bootstrap::jobs::torrent_cleanup: Cleaned up torrents in: 0 ms ``` --- Cargo.lock | 1 + packages/torrent-repository/Cargo.toml | 1 + packages/torrent-repository/src/swarm.rs | 13 +- packages/torrent-repository/src/swarms.rs | 124 ++++++++++++++---- packages/tracker-core/src/torrent/manager.rs | 35 +++++ .../src/torrent/repository/in_memory.rs | 22 ++++ .../config/tracker.development.sqlite3.toml | 6 + src/bootstrap/jobs/torrent_cleanup.rs | 5 +- 8 files changed, 181 insertions(+), 26 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 80f98db36..04ce8ad8c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4859,6 +4859,7 @@ dependencies = [ "torrust-tracker-configuration", "torrust-tracker-primitives", "torrust-tracker-test-helpers", + "tracing", ] [[package]] diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 2cc02a720..3396cd961 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -24,6 +24,7 @@ tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +tracing = "0" [dev-dependencies] async-std = { version = "1", features = ["attributes", "tokio1"] } diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index e5b5d598c..4437ca410 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -101,7 +101,9 @@ impl Swarm { } } - pub fn remove_inactive(&mut self, current_cutoff: DurationSinceUnixEpoch) { + pub fn remove_inactive(&mut self, current_cutoff: DurationSinceUnixEpoch) -> u64 { + let mut inactive_peers_removed = 0; + self.peers.retain(|_, peer| { let is_active = peer::ReadInfo::get_updated(peer) > current_cutoff; @@ -112,10 +114,14 @@ impl Swarm { } else { self.metadata.incomplete -= 1; } + + inactive_peers_removed += 1; } is_active }); + + inactive_peers_removed } #[must_use] @@ -190,6 +196,11 @@ impl Swarm { self.peers.is_empty() } + #[must_use] + pub fn is_peerless(&self) -> bool { + self.is_empty() + } + /// Returns true if the swarm meets the retention policy, meaning that /// it should be kept in the list of swarms. #[must_use] diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 828e8c030..0746e19a8 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -2,6 +2,7 @@ use std::sync::{Arc, Mutex}; use bittorrent_primitives::info_hash::InfoHash; use crossbeam_skiplist::SkipMap; +use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; @@ -76,24 +77,6 @@ impl Swarms { self.swarms.remove(key).map(|entry| entry.value().clone()) } - /// Removes inactive peers from all torrent entries. - /// - /// A peer is considered inactive if its last update timestamp is older than - /// the provided cutoff time. - /// - /// # Errors - /// - /// This function returns an error if it fails to acquire the lock for any - /// swarm handle. - pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> Result<(), Error> { - for swarm_handle in &self.swarms { - let mut swarm = swarm_handle.value().lock()?; - swarm.remove_inactive(current_cutoff); - } - - Ok(()) - } - /// Retrieves a tracked torrent handle by its infohash. /// /// # Returns @@ -225,6 +208,34 @@ impl Swarms { } } + /// Removes inactive peers from all torrent entries. + /// + /// A peer is considered inactive if its last update timestamp is older than + /// the provided cutoff time. + /// + /// # Errors + /// + /// This function returns an error if it fails to acquire the lock for any + /// swarm handle. + pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> Result { + tracing::info!( + "Removing inactive peers since: {:?} ...", + convert_from_timestamp_to_datetime_utc(current_cutoff) + ); + + let mut inactive_peers_removed = 0; + + for swarm_handle in &self.swarms { + let mut swarm = swarm_handle.value().lock()?; + let removed = swarm.remove_inactive(current_cutoff); + inactive_peers_removed += removed; + } + + tracing::info!("Inactive peers removed: {inactive_peers_removed}"); + + Ok(inactive_peers_removed) + } + /// Removes torrent entries that have no active peers. /// /// Depending on the tracker policy, torrents without any peers may be @@ -234,7 +245,11 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for any /// swarm handle. - pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> Result<(), Error> { + pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> Result { + tracing::info!("Removing peerless torrents ..."); + + let mut peerless_torrents_removed = 0; + for swarm_handle in &self.swarms { let swarm = swarm_handle.value().lock()?; @@ -243,9 +258,13 @@ impl Swarms { } swarm_handle.remove(); + + peerless_torrents_removed += 1; } - Ok(()) + tracing::info!("Peerless torrents removed: {peerless_torrents_removed}"); + + Ok(peerless_torrents_removed) } /// Imports persistent torrent data into the in-memory repository. @@ -253,7 +272,11 @@ impl Swarms { /// This method takes a set of persisted torrent entries (e.g., from a /// database) and imports them into the in-memory repository for immediate /// access. - pub fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + pub fn import_persistent(&self, persistent_torrents: &PersistentTorrents) -> u64 { + tracing::info!("Importing persisted info about torrents ..."); + + let mut torrents_imported = 0; + for (info_hash, completed) in persistent_torrents { if self.swarms.contains_key(info_hash) { continue; @@ -264,7 +287,13 @@ impl Swarms { // Since SkipMap is lock-free the torrent could have been inserted // after checking if it exists. self.swarms.get_or_insert(*info_hash, entry); + + torrents_imported += 1; } + + tracing::info!("Imported torrents: {torrents_imported}"); + + torrents_imported } /// Calculates and returns overall torrent metrics. @@ -284,9 +313,11 @@ impl Swarms { pub fn get_aggregate_swarm_metadata(&self) -> Result { let mut metrics = AggregateSwarmMetadata::default(); - for entry in &self.swarms { - let swarm = entry.value().lock()?; + for swarm_handle in &self.swarms { + let swarm = swarm_handle.value().lock()?; + let stats = swarm.metadata(); + metrics.total_complete += u64::from(stats.complete); metrics.total_downloaded += u64::from(stats.downloaded); metrics.total_incomplete += u64::from(stats.incomplete); @@ -296,6 +327,53 @@ impl Swarms { Ok(metrics) } + /// Counts the number of torrents that are peerless (i.e., have no active + /// peers). + /// + /// # Returns + /// + /// A `usize` representing the number of peerless torrents. + /// + /// # Errors + /// + /// This function returns an error if it fails to acquire the lock for any + /// swarm handle. + pub fn count_peerless_torrents(&self) -> Result { + let mut peerless_torrents = 0; + + for swarm_handle in &self.swarms { + let swarm = swarm_handle.value().lock()?; + + if swarm.is_peerless() { + peerless_torrents += 1; + } + } + + Ok(peerless_torrents) + } + + /// Counts the total number of peers across all torrents. + /// + /// # Returns + /// + /// A `usize` representing the total number of peers. + /// + /// # Errors + /// + /// This function returns an error if it fails to acquire the lock for any + /// swarm handle. + pub fn count_peers(&self) -> Result { + let mut peers = 0; + + for swarm_handle in &self.swarms { + let swarm = swarm_handle.value().lock()?; + + peers += swarm.len(); + } + + Ok(peers) + } + #[must_use] pub fn len(&self) -> usize { self.swarms.len() diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index 5c8352f11..5afbcecf2 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -92,16 +92,51 @@ impl TorrentsManager { /// (`remove_peerless_torrents` is set), it removes entire torrent /// entries that have no active peers. pub fn cleanup_torrents(&self) { + self.log_aggregate_swarm_metadata(); + + self.remove_inactive_peers(); + + self.log_aggregate_swarm_metadata(); + + self.remove_peerless_torrents(); + + self.log_aggregate_swarm_metadata(); + } + + fn remove_inactive_peers(&self) { let current_cutoff = CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout))) .unwrap_or_default(); self.in_memory_torrent_repository.remove_inactive_peers(current_cutoff); + } + fn remove_peerless_torrents(&self) { if self.config.tracker_policy.remove_peerless_torrents { self.in_memory_torrent_repository .remove_peerless_torrents(&self.config.tracker_policy); } } + + fn log_aggregate_swarm_metadata(&self) { + // Pre-calculated data + let aggregate_swarm_metadata = self.in_memory_torrent_repository.get_aggregate_swarm_metadata(); + + tracing::info!(name: "pre_calculated_aggregate_swarm_metadata", + torrents = aggregate_swarm_metadata.total_torrents, + downloads = aggregate_swarm_metadata.total_downloaded, + seeders = aggregate_swarm_metadata.total_complete, + leechers = aggregate_swarm_metadata.total_incomplete, + ); + + // Hot data (iterating over data structures) + let peerless_torrents = self.in_memory_torrent_repository.count_peerless_torrents(); + let peers = self.in_memory_torrent_repository.count_peers(); + + tracing::info!(name: "hot_aggregate_swarm_metadata", + peerless_torrents = peerless_torrents, + peers = peers, + ); + } } #[cfg(test)] diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 38593bf3c..ffb53edad 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -241,6 +241,28 @@ impl InMemoryTorrentRepository { .expect("Failed to get aggregate swarm metadata") } + /// Counts the number of peerless torrents in the repository. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. + #[must_use] + pub fn count_peerless_torrents(&self) -> usize { + self.swarms + .count_peerless_torrents() + .expect("Failed to count peerless torrents") + } + + /// Counts the number of peers in the repository. + /// + /// # Panics + /// + /// This function panics if the underling swarms return an error. + #[must_use] + pub fn count_peers(&self) -> usize { + self.swarms.count_peers().expect("Failed to count peers") + } + /// Imports persistent torrent data into the in-memory repository. /// /// This method takes a set of persisted torrent entries (e.g., from a database) diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index 333c6d66c..8d03f2300 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -7,9 +7,15 @@ schema_version = "2.0.0" threshold = "info" [core] +#inactive_peer_cleanup_interval = 60 listed = false private = false +#[core.tracker_policy] +#max_peer_timeout = 30 +#persistent_torrent_completed_stat = true +#remove_peerless_torrents = true + [[udp_trackers]] bind_address = "0.0.0.0:6868" tracker_usage_statistics = true diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index 54b1eeef7..0107b5370 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -28,6 +28,7 @@ use tracing::instrument; pub fn start_job(config: &Core, torrents_manager: &Arc) -> JoinHandle<()> { let weak_torrents_manager = std::sync::Arc::downgrade(torrents_manager); let interval = config.inactive_peer_cleanup_interval; + let interval_in_secs = interval; tokio::spawn(async move { let interval = std::time::Duration::from_secs(interval); @@ -43,9 +44,9 @@ pub fn start_job(config: &Core, torrents_manager: &Arc) -> Join _ = interval.tick() => { if let Some(torrents_manager) = weak_torrents_manager.upgrade() { let start_time = Utc::now().time(); - tracing::info!("Cleaning up torrents.."); + tracing::info!("Cleaning up torrents (executed every {} secs) ...", interval_in_secs); torrents_manager.cleanup_torrents(); - tracing::info!("Cleaned up torrents in: {}ms", (Utc::now().time() - start_time).num_milliseconds()); + tracing::info!("Cleaned up torrents in: {} ms", (Utc::now().time() - start_time).num_milliseconds()); } else { break; } From 46c7eae0fd53cbfc628ed85676eec8cee681f283 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 8 May 2025 16:42:17 +0100 Subject: [PATCH 1082/1297] dev: enable persistence for downdloads in dev config There are no performance problems in dev env, so it's better to enable as many features as possible to tests them while developing. --- share/default/config/tracker.development.sqlite3.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index 8d03f2300..488743eb9 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -11,9 +11,9 @@ threshold = "info" listed = false private = false -#[core.tracker_policy] +[core.tracker_policy] #max_peer_timeout = 30 -#persistent_torrent_completed_stat = true +persistent_torrent_completed_stat = true #remove_peerless_torrents = true [[udp_trackers]] From ced2788a2854203be9653169d23e65415d7b4972 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 8 May 2025 16:54:06 +0100 Subject: [PATCH 1083/1297] fix: [#1502] import torrents' download counters from DB when the tracker starts. In the current implementation all torrents that have benn downloaded at least once have to be in memory initializting the counter. Otherwise, the global counter for downloads for all torrents only includes downloads for the torrents being currently tracker by the tracker. --- packages/tracker-core/src/torrent/manager.rs | 5 ++--- src/app.rs | 11 +++++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index 5afbcecf2..aaac811f2 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -60,7 +60,7 @@ impl TorrentsManager { } } - /// Loads torrents from the persistent database into the in-memory repository. + /// Loads torrents from the database into the in-memory repository. /// /// This function retrieves the list of persistent torrent entries (which /// include only the aggregate metrics, not the detailed peer lists) from @@ -70,8 +70,7 @@ impl TorrentsManager { /// /// Returns a `databases::error::Error` if unable to load the persistent /// torrent data. - #[allow(dead_code)] - pub(crate) fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { + pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { let persistent_torrents = self.db_torrent_repository.load_all()?; self.in_memory_torrent_repository.import_persistent(&persistent_torrents); diff --git a/src/app.rs b/src/app.rs index 8f5c6ca4c..7bfa5296a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -61,6 +61,7 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> async fn load_data_from_database(config: &Configuration, app_container: &Arc) { load_peer_keys(config, app_container).await; load_whitelisted_torrents(config, app_container).await; + load_torrents_from_database(config, app_container); } async fn start_jobs(config: &Configuration, app_container: &Arc) -> JobManager { @@ -109,6 +110,16 @@ async fn load_whitelisted_torrents(config: &Configuration, app_container: &Arc) { + if config.core.tracker_policy.persistent_torrent_completed_stat { + app_container + .tracker_core_container + .torrents_manager + .load_torrents_from_database() + .expect("Could not load torrents from database."); + } +} + fn start_http_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { let opt_handle = jobs::http_tracker_core::start_event_listener(config, app_container); From 632185bf2237affb044f5c5f32c458061b460f40 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 8 May 2025 17:02:04 +0100 Subject: [PATCH 1084/1297] refactor: tracing spwams to use structure formats When possible prefer this with "variable=value" format: ``` imported_torrents=2 ``` To this: ``` Imported torrents: 2 ``` It's easier to parse and less likely to be changed. --- packages/torrent-repository/src/swarms.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 0746e19a8..a140663c9 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -231,7 +231,7 @@ impl Swarms { inactive_peers_removed += removed; } - tracing::info!("Inactive peers removed: {inactive_peers_removed}"); + tracing::info!(inactive_peers_removed = inactive_peers_removed); Ok(inactive_peers_removed) } @@ -262,7 +262,7 @@ impl Swarms { peerless_torrents_removed += 1; } - tracing::info!("Peerless torrents removed: {peerless_torrents_removed}"); + tracing::info!(peerless_torrents_removed = peerless_torrents_removed); Ok(peerless_torrents_removed) } @@ -291,7 +291,7 @@ impl Swarms { torrents_imported += 1; } - tracing::info!("Imported torrents: {torrents_imported}"); + tracing::info!(imported_torrents = torrents_imported); torrents_imported } From cb487f36588c681988f5f4c75eacf87a8539dc1c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 9 May 2025 08:35:40 +0100 Subject: [PATCH 1085/1297] fix: [#1510] disable torrent stats importation at start When the tracker starts, if stats persistence is enabled, all torrents that have ever been downloaded are loaded into memory (`Swarms` type) with their download counter. That's the current way to count all downloads and expose that metric. However, it does not work with **millions of torrents** (like in the tracker demo) becuase: - It's too slow. - It consumes too much memory (all torrents that have ever been downloaded have to be loaded). A new solution is needed to keep that metric, but in the meantime, this disables that feature, producing these effects: - Non-accurate value for downloads when the tracker is restarted. - Increasing indefinitely the number of torrents in memory even if the "remove peerless torrents" policy is enabled (becuase this feature overrides that policy and peerless torrents are kept in memory). --- src/app.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/app.rs b/src/app.rs index 7bfa5296a..93035ee99 100644 --- a/src/app.rs +++ b/src/app.rs @@ -61,7 +61,12 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> async fn load_data_from_database(config: &Configuration, app_container: &Arc) { load_peer_keys(config, app_container).await; load_whitelisted_torrents(config, app_container).await; - load_torrents_from_database(config, app_container); + // todo: disabled because of performance issues. + // The tracker demo has a lot of torrents and loading them all at once is not + // efficient. We also load them on demand but the total number of downloads + // metric is not accurate because not all torrents are loaded. + // See: https://github.com/torrust/torrust-tracker/issues/1510 + //load_torrents_from_database(config, app_container); } async fn start_jobs(config: &Configuration, app_container: &Arc) -> JobManager { @@ -110,6 +115,7 @@ async fn load_whitelisted_torrents(config: &Configuration, app_container: &Arc) { if config.core.tracker_policy.persistent_torrent_completed_stat { app_container From 243c25484ce796db48d3532eadd6b76c7fd4f3eb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 13 May 2025 10:34:36 +0100 Subject: [PATCH 1086/1297] feat: allow incrementing/decrementing gauge metrics --- packages/metrics/src/gauge.rs | 22 +++++++ packages/metrics/src/metric/mod.rs | 8 +++ packages/metrics/src/metric_collection.rs | 62 ++++++++++++++++++++ packages/metrics/src/sample.rs | 38 +++++++++++- packages/metrics/src/sample_collection.rs | 70 +++++++++++++++++++---- 5 files changed, 187 insertions(+), 13 deletions(-) diff --git a/packages/metrics/src/gauge.rs b/packages/metrics/src/gauge.rs index 61ff3024c..3f6089955 100644 --- a/packages/metrics/src/gauge.rs +++ b/packages/metrics/src/gauge.rs @@ -20,6 +20,14 @@ impl Gauge { pub fn set(&mut self, value: f64) { self.0 = value; } + + pub fn increment(&mut self, value: f64) { + self.0 += value; + } + + pub fn decrement(&mut self, value: f64) { + self.0 -= value; + } } impl From for Gauge { @@ -72,6 +80,20 @@ mod tests { assert_relative_eq!(gauge.value(), 1.0); } + #[test] + fn it_could_be_incremented() { + let mut gauge = Gauge::new(0.0); + gauge.increment(1.0); + assert_relative_eq!(gauge.value(), 1.0); + } + + #[test] + fn it_could_be_decremented() { + let mut gauge = Gauge::new(1.0); + gauge.decrement(1.0); + assert_relative_eq!(gauge.value(), 0.0); + } + #[test] fn it_serializes_to_prometheus() { let counter = Gauge::new(42.0); diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index ecce90f18..05779f09f 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -61,6 +61,14 @@ impl Metric { pub fn set(&mut self, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { self.sample_collection.set(label_set, value, time); } + + pub fn increment(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + self.sample_collection.increment(label_set, time); + } + + pub fn decrement(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + self.sample_collection.decrement(label_set, time); + } } impl PrometheusSerializable for Metric { diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index 9e89c3c4b..438f3b03a 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -136,6 +136,38 @@ impl MetricCollection { Ok(()) } + /// # Errors + /// + /// Return an error if a metrics of a different type with the same name + /// already exists. + pub fn increase_gauge(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) -> Result<(), Error> { + if self.counters.metrics.contains_key(name) { + return Err(Error::MetricNameCollisionAdding { + metric_name: name.clone(), + }); + } + + self.gauges.increment(name, label_set, time); + + Ok(()) + } + + /// # Errors + /// + /// Return an error if a metrics of a different type with the same name + /// already exists. + pub fn decrease_gauge(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) -> Result<(), Error> { + if self.counters.metrics.contains_key(name) { + return Err(Error::MetricNameCollisionAdding { + metric_name: name.clone(), + }); + } + + self.gauges.decrement(name, label_set, time); + + Ok(()) + } + pub fn ensure_gauge_exists(&mut self, name: &MetricName) { self.gauges.ensure_metric_exists(name); } @@ -353,6 +385,36 @@ impl MetricKindCollection { metric.set(label_set, value, time); } + /// Increments the gauge for the given metric name and labels. + /// + /// If the metric name does not exist, it will be created. + /// + /// # Panics + /// + /// Panics if the metric does not exist and it could not be created. + pub fn increment(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + self.ensure_metric_exists(name); + + let metric = self.metrics.get_mut(name).expect("Gauge metric should exist"); + + metric.increment(label_set, time); + } + + /// Decrements the gauge for the given metric name and labels. + /// + /// If the metric name does not exist, it will be created. + /// + /// # Panics + /// + /// Panics if the metric does not exist and it could not be created. + pub fn decrement(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + self.ensure_metric_exists(name); + + let metric = self.metrics.get_mut(name).expect("Gauge metric should exist"); + + metric.decrement(label_set, time); + } + #[must_use] pub fn get_value(&self, name: &MetricName, label_set: &LabelSet) -> Option { self.metrics diff --git a/packages/metrics/src/sample.rs b/packages/metrics/src/sample.rs index 5567dffec..4621c9906 100644 --- a/packages/metrics/src/sample.rs +++ b/packages/metrics/src/sample.rs @@ -64,6 +64,14 @@ impl Sample { pub fn set(&mut self, value: f64, time: DurationSinceUnixEpoch) { self.measurement.set(value, time); } + + pub fn increment(&mut self, time: DurationSinceUnixEpoch) { + self.measurement.increment(time); + } + + pub fn decrement(&mut self, time: DurationSinceUnixEpoch) { + self.measurement.decrement(time); + } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -121,6 +129,16 @@ impl Measurement { self.value.set(value); self.set_recorded_at(time); } + + pub fn increment(&mut self, time: DurationSinceUnixEpoch) { + self.value.increment(1.0); + self.set_recorded_at(time); + } + + pub fn decrement(&mut self, time: DurationSinceUnixEpoch) { + self.value.decrement(1.0); + self.set_recorded_at(time); + } } /// Serializes the `recorded_at` field as a string in ISO 8601 format (RFC 3339). @@ -273,7 +291,7 @@ mod tests { } #[test] - fn it_should_allow_incrementing_the_counter() { + fn it_should_allow_setting_a_value() { let mut sample = Sample::new(Gauge::default(), DurationSinceUnixEpoch::default(), LabelSet::default()); sample.set(1.0, updated_at_time()); @@ -281,6 +299,24 @@ mod tests { assert_eq!(sample.value(), &Gauge::new(1.0)); } + #[test] + fn it_should_allow_incrementing_the_value() { + let mut sample = Sample::new(Gauge::new(0.0), DurationSinceUnixEpoch::default(), LabelSet::default()); + + sample.increment(updated_at_time()); + + assert_eq!(sample.value(), &Gauge::new(1.0)); + } + + #[test] + fn it_should_allow_decrementing_the_value() { + let mut sample = Sample::new(Gauge::new(1.0), DurationSinceUnixEpoch::default(), LabelSet::default()); + + sample.decrement(updated_at_time()); + + assert_eq!(sample.value(), &Gauge::new(0.0)); + } + #[test] fn it_should_record_the_latest_update_time_when_the_counter_is_incremented() { let mut sample = Sample::new(Gauge::default(), DurationSinceUnixEpoch::default(), LabelSet::default()); diff --git a/packages/metrics/src/sample_collection.rs b/packages/metrics/src/sample_collection.rs index 49c839673..ea6b4d4af 100644 --- a/packages/metrics/src/sample_collection.rs +++ b/packages/metrics/src/sample_collection.rs @@ -90,6 +90,24 @@ impl SampleCollection { sample.set(value, time); } + + pub fn increment(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + let sample = self + .samples + .entry(label_set.clone()) + .or_insert_with(|| Measurement::new(Gauge::default(), time)); + + sample.increment(time); + } + + pub fn decrement(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { + let sample = self + .samples + .entry(label_set.clone()) + .or_insert_with(|| Measurement::new(Gauge::default(), time)); + + sample.decrement(time); + } } impl Serialize for SampleCollection { @@ -278,7 +296,7 @@ mod tests { #[test] fn it_should_increment_the_counter_for_a_preexisting_label_set() { let label_set = LabelSet::default(); - let mut collection = SampleCollection::default(); + let mut collection = SampleCollection::::default(); // Initialize the sample collection.increment(&label_set, sample_update_time()); @@ -296,7 +314,7 @@ mod tests { #[test] fn it_should_allow_increment_the_counter_for_a_non_existent_label_set() { let label_set = LabelSet::default(); - let mut collection = SampleCollection::default(); + let mut collection = SampleCollection::::default(); // Increment a non-existent label collection.increment(&label_set, sample_update_time()); @@ -312,7 +330,7 @@ mod tests { let label_set = LabelSet::default(); let initial_time = sample_update_time(); - let mut collection = SampleCollection::default(); + let mut collection = SampleCollection::::default(); collection.increment(&label_set, initial_time); // Increment with a new time @@ -330,7 +348,7 @@ mod tests { let label2 = LabelSet::from([("name", "value2")]); let now = sample_update_time(); - let mut collection = SampleCollection::default(); + let mut collection = SampleCollection::::default(); collection.increment(&label1, now); collection.increment(&label2, now); @@ -351,9 +369,9 @@ mod tests { use crate::gauge::Gauge; #[test] - fn it_should_increment_the_gauge_for_a_preexisting_label_set() { + fn it_should_allow_setting_the_gauge_for_a_preexisting_label_set() { let label_set = LabelSet::default(); - let mut collection = SampleCollection::default(); + let mut collection = SampleCollection::::default(); // Initialize the sample collection.set(&label_set, 1.0, sample_update_time()); @@ -369,9 +387,9 @@ mod tests { } #[test] - fn it_should_allow_increment_the_gauge_for_a_non_existent_label_set() { + fn it_should_allow_setting_the_gauge_for_a_non_existent_label_set() { let label_set = LabelSet::default(); - let mut collection = SampleCollection::default(); + let mut collection = SampleCollection::::default(); // Set a non-existent label collection.set(&label_set, 1.0, sample_update_time()); @@ -383,11 +401,11 @@ mod tests { } #[test] - fn it_should_update_the_latest_update_time_when_incremented() { + fn it_should_update_the_latest_update_time_when_setting() { let label_set = LabelSet::default(); let initial_time = sample_update_time(); - let mut collection = SampleCollection::default(); + let mut collection = SampleCollection::::default(); collection.set(&label_set, 1.0, initial_time); // Set with a new time @@ -400,12 +418,12 @@ mod tests { } #[test] - fn it_should_increment_the_gauge_for_multiple_labels() { + fn it_should_allow_setting_the_gauge_for_multiple_labels() { let label1 = LabelSet::from([("name", "value1")]); let label2 = LabelSet::from([("name", "value2")]); let now = sample_update_time(); - let mut collection = SampleCollection::default(); + let mut collection = SampleCollection::::default(); collection.set(&label1, 1.0, now); collection.set(&label2, 2.0, now); @@ -414,5 +432,33 @@ mod tests { assert_eq!(collection.get(&label2).unwrap().value(), &Gauge::new(2.0)); assert_eq!(collection.len(), 2); } + + #[test] + fn it_should_allow_incrementing_the_gauge() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::::default(); + + // Initialize the sample + collection.set(&label_set, 1.0, sample_update_time()); + + // Increment + collection.increment(&label_set, sample_update_time()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Gauge::new(2.0)); + } + + #[test] + fn it_should_allow_decrementing_the_gauge() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::::default(); + + // Initialize the sample + collection.set(&label_set, 1.0, sample_update_time()); + + // Increment + collection.decrement(&label_set, sample_update_time()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Gauge::new(0.0)); + } } } From 2522ad4ccff7bbc0010581d10bdc2f32abc90555 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 9 May 2025 16:40:14 +0100 Subject: [PATCH 1087/1297] feat: [#1358] basic scaffolding for events in torrent-repository pkg TODO: - Run the event listener for the torrent-repository package when the tracker starts. - Inject enven sender in `Swarms` and `Swarm` type to send events. - Trigger events and process them to update the metrics. - Expose the metrics via the `metrics` API endpoint. - ... --- Cargo.lock | 3 + packages/torrent-repository/Cargo.toml | 3 + packages/torrent-repository/src/event.rs | 44 ++++++++++++++ packages/torrent-repository/src/lib.rs | 4 ++ .../src/statistics/event/handler.rs | 21 +++++++ .../src/statistics/event/listener.rs | 57 +++++++++++++++++++ .../src/statistics/event/mod.rs | 2 + .../src/statistics/metrics.rs | 39 +++++++++++++ .../torrent-repository/src/statistics/mod.rs | 34 +++++++++++ .../src/statistics/repository.rs | 54 ++++++++++++++++++ 10 files changed, 261 insertions(+) create mode 100644 packages/torrent-repository/src/event.rs create mode 100644 packages/torrent-repository/src/statistics/event/handler.rs create mode 100644 packages/torrent-repository/src/statistics/event/listener.rs create mode 100644 packages/torrent-repository/src/statistics/event/mod.rs create mode 100644 packages/torrent-repository/src/statistics/metrics.rs create mode 100644 packages/torrent-repository/src/statistics/mod.rs create mode 100644 packages/torrent-repository/src/statistics/repository.rs diff --git a/Cargo.lock b/Cargo.lock index 04ce8ad8c..90a6354bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4853,10 +4853,13 @@ dependencies = [ "crossbeam-skiplist", "rand 0.9.1", "rstest", + "serde", "thiserror 2.0.12", "tokio", "torrust-tracker-clock", "torrust-tracker-configuration", + "torrust-tracker-events", + "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", "tracing", diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 3396cd961..77192c7cf 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -19,10 +19,13 @@ version.workspace = true aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" crossbeam-skiplist = "0" +serde = "1.0.219" thiserror = "2.0.12" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } tracing = "0" diff --git a/packages/torrent-repository/src/event.rs b/packages/torrent-repository/src/event.rs new file mode 100644 index 000000000..57fe7bc4b --- /dev/null +++ b/packages/torrent-repository/src/event.rs @@ -0,0 +1,44 @@ +use std::net::SocketAddr; + +use aquatic_udp_protocol::PeerId; +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_primitives::peer::PeerAnnouncement; + +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum Event { + TorrentAdded { + info_hash: InfoHash, + announcement: PeerAnnouncement, + }, + TorrentRemoved { + info_hash: InfoHash, + }, + PeerAdded { + announcement: PeerAnnouncement, + }, + PeerRemoved { + socket_addr: SocketAddr, + peer_id: PeerId, + }, +} + +pub mod sender { + use std::sync::Arc; + + use super::Event; + + pub type Sender = Option>>; + pub type Broadcaster = torrust_tracker_events::broadcaster::Broadcaster; +} + +pub mod receiver { + use super::Event; + + pub type Receiver = Box>; +} + +pub mod bus { + use crate::event::Event; + + pub type EventBus = torrust_tracker_events::bus::EventBus; +} diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index a4e7d9c5d..0d455177c 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,3 +1,5 @@ +pub mod event; +pub mod statistics; pub mod swarm; pub mod swarms; @@ -19,6 +21,8 @@ pub(crate) type CurrentClock = clock::Working; #[allow(dead_code)] pub(crate) type CurrentClock = clock::Stopped; +pub const TORRENT_REPOSITORY_LOG_TARGET: &str = "TORRENT_REPOSITORY"; + pub trait LockTrackedTorrent { fn lock_or_panic(&self) -> MutexGuard<'_, Swarm>; } diff --git a/packages/torrent-repository/src/statistics/event/handler.rs b/packages/torrent-repository/src/statistics/event/handler.rs new file mode 100644 index 000000000..d68df0b1b --- /dev/null +++ b/packages/torrent-repository/src/statistics/event/handler.rs @@ -0,0 +1,21 @@ +use std::sync::Arc; + +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::Event; +use crate::statistics::repository::Repository; + +/// # Panics +/// +/// This function panics if the client IP address is not the same as the IP +/// version of the event. +pub async fn handle_event(_event: Event, stats_repository: &Arc, _now: DurationSinceUnixEpoch) { + /*match event { + Event::TorrentAdded { .. } => {} + Event::TorrentRemoved { .. } => {} + Event::PeerAdded { .. } => {} + Event::PeerRemoved { .. } => {} + }*/ + + tracing::debug!("metrics: {:?}", stats_repository.get_metrics().await); +} diff --git a/packages/torrent-repository/src/statistics/event/listener.rs b/packages/torrent-repository/src/statistics/event/listener.rs new file mode 100644 index 000000000..f3b534332 --- /dev/null +++ b/packages/torrent-repository/src/statistics/event/listener.rs @@ -0,0 +1,57 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_events::receiver::RecvError; + +use super::handler::handle_event; +use crate::event::receiver::Receiver; +use crate::statistics::repository::Repository; +use crate::{CurrentClock, TORRENT_REPOSITORY_LOG_TARGET}; + +#[must_use] +pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { + let stats_repository = repository.clone(); + + tracing::info!(target: TORRENT_REPOSITORY_LOG_TARGET, "Starting torrent repository event listener"); + + tokio::spawn(async move { + dispatch_events(receiver, stats_repository).await; + + tracing::info!(target: TORRENT_REPOSITORY_LOG_TARGET, "Torrent repository listener finished"); + }) +} + +async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { + let shutdown_signal = tokio::signal::ctrl_c(); + + tokio::pin!(shutdown_signal); + + loop { + tokio::select! { + biased; + + _ = &mut shutdown_signal => { + tracing::info!(target: TORRENT_REPOSITORY_LOG_TARGET, "Received Ctrl+C, shutting down torrent repository event listener."); + break; + } + + result = receiver.recv() => { + match result { + Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, + Err(e) => { + match e { + RecvError::Closed => { + tracing::info!(target: TORRENT_REPOSITORY_LOG_TARGET, "Torrent repository event receiver closed."); + break; + } + RecvError::Lagged(n) => { + tracing::warn!(target: TORRENT_REPOSITORY_LOG_TARGET, "Torrent repository event receiver lagged by {} events.", n); + } + } + } + } + } + } + } +} diff --git a/packages/torrent-repository/src/statistics/event/mod.rs b/packages/torrent-repository/src/statistics/event/mod.rs new file mode 100644 index 000000000..dae683398 --- /dev/null +++ b/packages/torrent-repository/src/statistics/event/mod.rs @@ -0,0 +1,2 @@ +pub mod handler; +pub mod listener; diff --git a/packages/torrent-repository/src/statistics/metrics.rs b/packages/torrent-repository/src/statistics/metrics.rs new file mode 100644 index 000000000..6ee275e63 --- /dev/null +++ b/packages/torrent-repository/src/statistics/metrics.rs @@ -0,0 +1,39 @@ +use serde::Serialize; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +/// Metrics collected by the torrent repository. +#[derive(Debug, Clone, PartialEq, Default, Serialize)] +pub struct Metrics { + /// A collection of metrics. + pub metric_collection: MetricCollection, +} + +impl Metrics { + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increase_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increase_counter(metric_name, labels, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn set_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_gauge(metric_name, labels, value, now) + } +} diff --git a/packages/torrent-repository/src/statistics/mod.rs b/packages/torrent-repository/src/statistics/mod.rs new file mode 100644 index 000000000..b0dce479f --- /dev/null +++ b/packages/torrent-repository/src/statistics/mod.rs @@ -0,0 +1,34 @@ +pub mod event; +pub mod metrics; +pub mod repository; + +use metrics::Metrics; +use torrust_tracker_metrics::metric::description::MetricDescription; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_metrics::unit::Unit; + +const TORRENT_REPOSITORY_RUNTIME_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_runtime_torrents_downloads_total"; +const TORRENT_REPOSITORY_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_persistent_torrents_downloads_total"; + +#[must_use] +pub fn describe_metrics() -> Metrics { + let mut metrics = Metrics::default(); + + metrics.metric_collection.describe_counter( + &metric_name!(TORRENT_REPOSITORY_RUNTIME_TORRENTS_DOWNLOADS_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new( + "The total number of torrent downloads since the tracker process started.", + )), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(TORRENT_REPOSITORY_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new( + "The total number of torrent downloads since persistent statistics were enabled the first time.", + )), + ); + + metrics +} diff --git a/packages/torrent-repository/src/statistics/repository.rs b/packages/torrent-repository/src/statistics/repository.rs new file mode 100644 index 000000000..9fdff7008 --- /dev/null +++ b/packages/torrent-repository/src/statistics/repository.rs @@ -0,0 +1,54 @@ +use std::sync::Arc; + +use tokio::sync::{RwLock, RwLockReadGuard}; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::Error; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::describe_metrics; +use super::metrics::Metrics; + +/// A repository for the torrent repository metrics. +#[derive(Clone)] +pub struct Repository { + pub stats: Arc>, +} + +impl Default for Repository { + fn default() -> Self { + Self::new() + } +} + +impl Repository { + #[must_use] + pub fn new() -> Self { + let stats = Arc::new(RwLock::new(describe_metrics())); + + Self { stats } + } + + pub async fn get_metrics(&self) -> RwLockReadGuard<'_, Metrics> { + self.stats.read().await + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increase the counter. + pub async fn increase_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.increase_counter(metric_name, labels, now); + + drop(stats_lock); + + result + } +} From f986bdaf2396dc7a921a86ed168d3bd684c64931 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 9 May 2025 17:18:55 +0100 Subject: [PATCH 1088/1297] feat: [#1358] add the and run the event listener when the tracker starts This creates independent services that are not used yet in the tracker-core, meaning the `Swarms` object created in the `TorrentRepositoryContainer` will not store any torrent yet. The tracker core is still creating its own fresh instance. --- Cargo.lock | 1 + Cargo.toml | 1 + packages/torrent-repository/src/container.rs | 37 ++++++++++++++++++++ packages/torrent-repository/src/lib.rs | 1 + src/app.rs | 14 ++++++++ src/bootstrap/jobs/mod.rs | 1 + src/bootstrap/jobs/torrent_repository.rs | 20 +++++++++++ src/container.rs | 11 ++++++ 8 files changed, 86 insertions(+) create mode 100644 packages/torrent-repository/src/container.rs create mode 100644 src/bootstrap/jobs/torrent_repository.rs diff --git a/Cargo.lock b/Cargo.lock index 90a6354bc..5f024dcc2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4713,6 +4713,7 @@ dependencies = [ "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-test-helpers", + "torrust-tracker-torrent-repository", "torrust-udp-tracker-server", "tracing", "tracing-subscriber", diff --git a/Cargo.toml b/Cargo.toml index a15ff78df..219701d03 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,6 +55,7 @@ torrust-rest-tracker-api-core = { version = "3.0.0-develop", path = "packages/re torrust-server-lib = { version = "3.0.0-develop", path = "packages/server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "packages/torrent-repository" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "packages/udp-tracker-server" } tracing = "0" tracing-subscriber = { version = "0", features = ["json"] } diff --git a/packages/torrent-repository/src/container.rs b/packages/torrent-repository/src/container.rs new file mode 100644 index 000000000..7522c7956 --- /dev/null +++ b/packages/torrent-repository/src/container.rs @@ -0,0 +1,37 @@ +use std::sync::Arc; + +use crate::event::bus::EventBus; +use crate::event::sender::Broadcaster; +use crate::event::{self}; +use crate::statistics::repository::Repository; +use crate::{statistics, Swarms}; + +pub struct TorrentRepositoryContainer { + pub swarms: Arc, + pub event_bus: Arc, + pub stats_event_sender: event::sender::Sender, + pub stats_repository: Arc, +} + +impl TorrentRepositoryContainer { + #[must_use] + pub fn initialize() -> Self { + let swarms = Arc::new(Swarms::default()); + + // Torrent repository stats + let broadcaster = Broadcaster::default(); + let stats_repository = Arc::new(Repository::new()); + + // todo: add a config option to enable/disable stats for this package + let event_bus = Arc::new(EventBus::new(true, broadcaster.clone())); + + let stats_event_sender = event_bus.sender(); + + Self { + swarms, + event_bus, + stats_event_sender, + stats_repository, + } + } +} diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index 0d455177c..c6790c4db 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -1,3 +1,4 @@ +pub mod container; pub mod event; pub mod statistics; pub mod swarm; diff --git a/src/app.rs b/src/app.rs index 93035ee99..ca8b7a5c3 100644 --- a/src/app.rs +++ b/src/app.rs @@ -72,9 +72,11 @@ async fn load_data_from_database(config: &Configuration, app_container: &Arc) -> JobManager { let mut job_manager = JobManager::new(); + start_torrent_repository_event_listener(config, app_container, &mut job_manager); start_http_core_event_listener(config, app_container, &mut job_manager); start_udp_core_event_listener(config, app_container, &mut job_manager); start_udp_server_event_listener(config, app_container, &mut job_manager); + start_the_udp_instances(config, app_container, &mut job_manager).await; start_the_http_instances(config, app_container, &mut job_manager).await; start_the_http_api(config, app_container, &mut job_manager).await; @@ -126,6 +128,18 @@ fn load_torrents_from_database(config: &Configuration, app_container: &Arc, + job_manager: &mut JobManager, +) { + let opt_handle = jobs::torrent_repository::start_event_listener(config, app_container); + + if let Some(handle) = opt_handle { + job_manager.push("torrent_repository_event_listener", handle); + } +} + fn start_http_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { let opt_handle = jobs::http_tracker_core::start_event_listener(config, app_container); diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index 2e3d798ad..b311c6da6 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -11,6 +11,7 @@ pub mod http_tracker; pub mod http_tracker_core; pub mod manager; pub mod torrent_cleanup; +pub mod torrent_repository; pub mod tracker_apis; pub mod udp_tracker; pub mod udp_tracker_core; diff --git a/src/bootstrap/jobs/torrent_repository.rs b/src/bootstrap/jobs/torrent_repository.rs new file mode 100644 index 000000000..2125de554 --- /dev/null +++ b/src/bootstrap/jobs/torrent_repository.rs @@ -0,0 +1,20 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use torrust_tracker_configuration::Configuration; + +use crate::container::AppContainer; + +pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { + if config.core.tracker_usage_statistics { + let job = torrust_tracker_torrent_repository::statistics::event::listener::run_event_listener( + app_container.torrent_repository_container.event_bus.receiver(), + &app_container.torrent_repository_container.stats_repository, + ); + + Some(job) + } else { + tracing::info!("HTTP tracker core event listener job is disabled."); + None + } +} diff --git a/src/container.rs b/src/container.rs index 93f1fb4d7..016b4a881 100644 --- a/src/container.rs +++ b/src/container.rs @@ -9,6 +9,7 @@ use bittorrent_udp_tracker_core::{self}; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{Configuration, HttpApi}; +use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use tracing::instrument; @@ -28,6 +29,9 @@ pub struct AppContainer { // Registar pub registar: Arc, + // Torrent Repository + pub torrent_repository_container: Arc, + // Core pub tracker_core_container: Arc, @@ -54,6 +58,10 @@ impl AppContainer { let registar = Arc::new(Registar::default()); + // Torrent Repository + + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + // Core let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); @@ -84,6 +92,9 @@ impl AppContainer { // Registar registar, + // Torrent Repository + torrent_repository_container, + // Core tracker_core_container, From 95766bb9897a8ecec544bf6d38bcfd532c1d0ea9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 9 May 2025 17:44:26 +0100 Subject: [PATCH 1089/1297] feat: [#1358] inject Swarms into InMemoryTorrentRepository in production code todo: do the same for testing code. --- packages/torrent-repository/src/swarms.rs | 4 +++- packages/tracker-core/src/container.rs | 15 ++++++++++++++- .../src/torrent/repository/in_memory.rs | 5 +++++ src/container.rs | 5 ++++- 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index a140663c9..9dddaa0c0 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -9,7 +9,7 @@ use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMe use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; use crate::swarm::Swarm; -use crate::SwarmHandle; +use crate::{SwarmHandle, TORRENT_REPOSITORY_LOG_TARGET}; #[derive(Default, Debug)] pub struct Swarms { @@ -43,6 +43,8 @@ impl Swarms { peer: &peer::Peer, opt_persistent_torrent: Option, ) -> Result { + tracing::trace!(target: TORRENT_REPOSITORY_LOG_TARGET, "Handling announcement for torrent: {info_hash}"); + let swarm_handle = if let Some(number_of_downloads) = opt_persistent_torrent { SwarmHandle::new(Swarm::new(number_of_downloads).into()) } else { diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs index 9f4d23802..3f35c3943 100644 --- a/packages/tracker-core/src/container.rs +++ b/packages/tracker-core/src/container.rs @@ -1,6 +1,8 @@ use std::sync::Arc; use torrust_tracker_configuration::Core; +use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; +use torrust_tracker_torrent_repository::Swarms; use crate::announce_handler::AnnounceHandler; use crate::authentication::handler::KeysHandler; @@ -35,8 +37,19 @@ pub struct TrackerCoreContainer { } impl TrackerCoreContainer { + #[must_use] + pub fn initialize_from(core_config: &Arc, torrent_repository_container: &Arc) -> Self { + Self::inner_initialize(core_config, &torrent_repository_container.swarms) + } + #[must_use] pub fn initialize(core_config: &Arc) -> Self { + let swarms = Arc::new(Swarms::default()); + Self::inner_initialize(core_config, &swarms) + } + + #[must_use] + fn inner_initialize(core_config: &Arc, swarms: &Arc) -> Self { let database = initialize_database(core_config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); @@ -48,7 +61,7 @@ impl TrackerCoreContainer { &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new(swarms.clone())); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let torrents_manager = Arc::new(TorrentsManager::new( diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index ffb53edad..c8e593471 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -25,6 +25,11 @@ pub struct InMemoryTorrentRepository { } impl InMemoryTorrentRepository { + #[must_use] + pub fn new(swarms: Arc) -> Self { + Self { swarms } + } + /// Inserts or updates a peer in the torrent entry corresponding to the /// given infohash. /// diff --git a/src/container.rs b/src/container.rs index 016b4a881..838de58d6 100644 --- a/src/container.rs +++ b/src/container.rs @@ -64,7 +64,10 @@ impl AppContainer { // Core - let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + &core_config, + &torrent_repository_container, + )); // HTTP From 41f402292a8b4661cf3d9ca0032d9f506ba0ea43 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 12 May 2025 11:10:13 +0100 Subject: [PATCH 1090/1297] feat: [#1358] inject Swarms into InMemoryTorrentRepository in testing code --- Cargo.lock | 6 ++++++ packages/axum-http-tracker-server/Cargo.toml | 1 + .../axum-http-tracker-server/src/environment.rs | 9 ++++++++- packages/axum-http-tracker-server/src/server.rs | 8 +++++++- packages/axum-rest-tracker-api-server/Cargo.toml | 1 + .../src/environment.rs | 11 ++++++++++- packages/http-tracker-core/Cargo.toml | 1 + packages/http-tracker-core/src/container.rs | 10 +++++++++- packages/rest-tracker-api-core/Cargo.toml | 1 + packages/rest-tracker-api-core/src/container.rs | 11 ++++++++++- packages/tracker-core/src/container.rs | 14 +------------- packages/udp-tracker-core/Cargo.toml | 1 + packages/udp-tracker-core/src/container.rs | 10 +++++++++- packages/udp-tracker-server/Cargo.toml | 1 + packages/udp-tracker-server/src/environment.rs | 10 +++++++++- 15 files changed, 75 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5f024dcc2..b39355065 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -593,6 +593,7 @@ dependencies = [ "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", + "torrust-tracker-torrent-repository", "tracing", ] @@ -708,6 +709,7 @@ dependencies = [ "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", + "torrust-tracker-torrent-repository", "tracing", "zerocopy 0.7.35", ] @@ -4575,6 +4577,7 @@ dependencies = [ "torrust-tracker-events", "torrust-tracker-primitives", "torrust-tracker-test-helpers", + "torrust-tracker-torrent-repository", "tower", "tower-http", "tracing", @@ -4614,6 +4617,7 @@ dependencies = [ "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", + "torrust-tracker-torrent-repository", "torrust-udp-tracker-server", "tower", "tower-http", @@ -4666,6 +4670,7 @@ dependencies = [ "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", + "torrust-tracker-torrent-repository", "torrust-udp-tracker-server", ] @@ -4913,6 +4918,7 @@ dependencies = [ "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", + "torrust-tracker-torrent-repository", "tracing", "url", "uuid", diff --git a/packages/axum-http-tracker-server/Cargo.toml b/packages/axum-http-tracker-server/Cargo.toml index 1b4627d41..81831a614 100644 --- a/packages/axum-http-tracker-server/Cargo.toml +++ b/packages/axum-http-tracker-server/Cargo.toml @@ -33,6 +33,7 @@ torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index aeb53a710..b9ac6bdbb 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -10,6 +10,7 @@ use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_primitives::peer; +use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; use crate::server::{HttpServer, Launcher, Running, Stopped}; @@ -143,7 +144,13 @@ impl EnvContainer { .expect("missing HTTP tracker configuration"); let http_tracker_config = Arc::new(http_tracker_config[0].clone()); - let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + &core_config, + &torrent_repository_container, + )); + let http_tracker_container = HttpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &http_tracker_config); diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index ff1650b9c..3904449fa 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -260,6 +260,7 @@ mod tests { use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_test_helpers::configuration::ephemeral_public; + use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; use crate::server::{HttpServer, Launcher}; @@ -289,7 +290,12 @@ mod tests { let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); } - let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + &core_config, + &torrent_repository_container, + )); let announce_service = Arc::new(AnnounceService::new( tracker_core_container.core_config.clone(), diff --git a/packages/axum-rest-tracker-api-server/Cargo.toml b/packages/axum-rest-tracker-api-server/Cargo.toml index d1491c96e..296f77d61 100644 --- a/packages/axum-rest-tracker-api-server/Cargo.toml +++ b/packages/axum-rest-tracker-api-server/Cargo.toml @@ -39,6 +39,7 @@ torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index 275d72574..0758b38d1 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -12,6 +12,7 @@ use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_primitives::peer; +use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use crate::server::{ApiServer, Launcher, Running, Stopped}; @@ -172,11 +173,19 @@ impl EnvContainer { .clone(), ); - let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + &core_config, + &torrent_repository_container, + )); + let http_tracker_core_container = HttpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &http_tracker_config); + let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &udp_tracker_config); + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); let tracker_http_api_core_container = TrackerHttpApiCoreContainer::initialize_from( diff --git a/packages/http-tracker-core/Cargo.toml b/packages/http-tracker-core/Cargo.toml index 5473c5a25..37b540e39 100644 --- a/packages/http-tracker-core/Cargo.toml +++ b/packages/http-tracker-core/Cargo.toml @@ -28,6 +28,7 @@ torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configur torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } tracing = "0" [dev-dependencies] diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 681d4a4f4..922273610 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use bittorrent_tracker_core::container::TrackerCoreContainer; use torrust_tracker_configuration::{Core, HttpTracker}; +use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; @@ -26,7 +27,13 @@ pub struct HttpTrackerCoreContainer { impl HttpTrackerCoreContainer { #[must_use] pub fn initialize(core_config: &Arc, http_tracker_config: &Arc) -> Arc { - let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(core_config)); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + core_config, + &torrent_repository_container, + )); + Self::initialize_from_tracker_core(&tracker_core_container, http_tracker_config) } @@ -36,6 +43,7 @@ impl HttpTrackerCoreContainer { http_tracker_config: &Arc, ) -> Arc { let http_tracker_core_services = HttpTrackerCoreServices::initialize_from(tracker_core_container); + Self::initialize_from_services(tracker_core_container, &http_tracker_core_services, http_tracker_config) } diff --git a/packages/rest-tracker-api-core/Cargo.toml b/packages/rest-tracker-api-core/Cargo.toml index 0077572fb..de1946239 100644 --- a/packages/rest-tracker-api-core/Cargo.toml +++ b/packages/rest-tracker-api-core/Cargo.toml @@ -21,6 +21,7 @@ tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } [dev-dependencies] diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs index ec3786dfb..327ab4bd6 100644 --- a/packages/rest-tracker-api-core/src/container.rs +++ b/packages/rest-tracker-api-core/src/container.rs @@ -7,6 +7,7 @@ use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self}; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; +use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; pub struct TrackerHttpApiCoreContainer { @@ -26,11 +27,19 @@ impl TrackerHttpApiCoreContainer { udp_tracker_config: &Arc, http_api_config: &Arc, ) -> Arc { - let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(core_config)); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + core_config, + &torrent_repository_container, + )); + let http_tracker_core_container = HttpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, http_tracker_config); + let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, udp_tracker_config); + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(core_config); Self::initialize_from( diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs index 3f35c3943..f4fb272de 100644 --- a/packages/tracker-core/src/container.rs +++ b/packages/tracker-core/src/container.rs @@ -2,7 +2,6 @@ use std::sync::Arc; use torrust_tracker_configuration::Core; use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; -use torrust_tracker_torrent_repository::Swarms; use crate::announce_handler::AnnounceHandler; use crate::authentication::handler::KeysHandler; @@ -39,17 +38,6 @@ pub struct TrackerCoreContainer { impl TrackerCoreContainer { #[must_use] pub fn initialize_from(core_config: &Arc, torrent_repository_container: &Arc) -> Self { - Self::inner_initialize(core_config, &torrent_repository_container.swarms) - } - - #[must_use] - pub fn initialize(core_config: &Arc) -> Self { - let swarms = Arc::new(Swarms::default()); - Self::inner_initialize(core_config, &swarms) - } - - #[must_use] - fn inner_initialize(core_config: &Arc, swarms: &Arc) -> Self { let database = initialize_database(core_config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); @@ -61,7 +49,7 @@ impl TrackerCoreContainer { &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new(swarms.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new(torrent_repository_container.swarms.clone())); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let torrents_manager = Arc::new(TorrentsManager::new( diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml index 6cf250074..9a27ec826 100644 --- a/packages/udp-tracker-core/Cargo.toml +++ b/packages/udp-tracker-core/Cargo.toml @@ -33,6 +33,7 @@ torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configur torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } tracing = "0" zerocopy = "0.7" diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index 98c01a703..2b6567ec0 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use bittorrent_tracker_core::container::TrackerCoreContainer; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, UdpTracker}; +use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; @@ -31,7 +32,13 @@ pub struct UdpTrackerCoreContainer { impl UdpTrackerCoreContainer { #[must_use] pub fn initialize(core_config: &Arc, udp_tracker_config: &Arc) -> Arc { - let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(core_config)); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + core_config, + &torrent_repository_container, + )); + Self::initialize_from_tracker_core(&tracker_core_container, udp_tracker_config) } @@ -41,6 +48,7 @@ impl UdpTrackerCoreContainer { udp_tracker_config: &Arc, ) -> Arc { let udp_tracker_core_services = UdpTrackerCoreServices::initialize_from(tracker_core_container); + Self::initialize_from_services(tracker_core_container, &udp_tracker_core_services, udp_tracker_config) } diff --git a/packages/udp-tracker-server/Cargo.toml b/packages/udp-tracker-server/Cargo.toml index 4d0296461..a0c129acb 100644 --- a/packages/udp-tracker-server/Cargo.toml +++ b/packages/udp-tracker-server/Cargo.toml @@ -33,6 +33,7 @@ torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } tracing = "0" url = { version = "2", features = ["serde"] } uuid = { version = "1", features = ["v4"] } diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 962442fde..e3667e74a 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -8,6 +8,7 @@ use tokio::task::JoinHandle; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_primitives::peer; +use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; use crate::container::UdpTrackerServerContainer; use crate::server::spawner::Spawner; @@ -173,9 +174,16 @@ impl EnvContainer { let udp_tracker_configurations = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); - let tracker_core_container = Arc::new(TrackerCoreContainer::initialize(&core_config)); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + &core_config, + &torrent_repository_container, + )); + let udp_tracker_core_container = UdpTrackerCoreContainer::initialize_from_tracker_core(&tracker_core_container, &udp_tracker_config); + let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); Self { From 68b930d4b4e89c3003fb38689f6c2b3c32bb06d2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 12 May 2025 11:30:29 +0100 Subject: [PATCH 1091/1297] feat: [#1495] expose new torrent-repositoru metrics via the REST API These are the new metrics in JSON format: http://localhost:1212/api/v1/metrics?token=MyAccessToken ```json { "metrics": [ { "kind": "counter", "name": "torrent_repository_persistent_torrents_downloads_total", "samples": [] }, { "kind": "counter", "name": "torrent_repository_runtime_torrents_downloads_total", "samples": [] } ] } ``` --- .../src/environment.rs | 1 + .../src/v1/context/stats/handlers.rs | 2 ++ .../src/v1/context/stats/routes.rs | 1 + .../rest-tracker-api-core/src/container.rs | 22 ++++++++++++++++--- .../src/statistics/services.rs | 6 +++++ src/container.rs | 9 ++++++-- 6 files changed, 36 insertions(+), 5 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index 0758b38d1..ae3eadb31 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -189,6 +189,7 @@ impl EnvContainer { let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); let tracker_http_api_core_container = TrackerHttpApiCoreContainer::initialize_from( + &torrent_repository_container, &tracker_core_container, &http_tracker_core_container, &udp_tracker_core_container, diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs index 17d3e4f2d..552958d74 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs @@ -69,6 +69,7 @@ pub async fn get_metrics_handler( State(state): State<( Arc, Arc>, + Arc, Arc, Arc, Arc, @@ -81,6 +82,7 @@ pub async fn get_metrics_handler( state.2.clone(), state.3.clone(), state.4.clone(), + state.5.clone(), ) .await; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs index c19f08b2a..3eeaa8bf4 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs @@ -28,6 +28,7 @@ pub fn add(prefix: &str, router: Router, http_api_container: &Arc, + + // Torrent repository + pub torrent_repository_container: Arc, + + // Tracker core pub tracker_core_container: Arc, + + // HTTP tracker core pub http_stats_repository: Arc, + + // UDP tracker core pub ban_service: Arc>, pub udp_core_stats_repository: Arc, pub udp_server_stats_repository: Arc, @@ -43,6 +52,7 @@ impl TrackerHttpApiCoreContainer { let udp_tracker_server_container = UdpTrackerServerContainer::initialize(core_config); Self::initialize_from( + &torrent_repository_container, &tracker_core_container, &http_tracker_core_container, &udp_tracker_core_container, @@ -53,6 +63,7 @@ impl TrackerHttpApiCoreContainer { #[must_use] pub fn initialize_from( + torrent_repository_container: &Arc, tracker_core_container: &Arc, http_tracker_core_container: &Arc, udp_tracker_core_container: &Arc, @@ -60,16 +71,21 @@ impl TrackerHttpApiCoreContainer { http_api_config: &Arc, ) -> Arc { Arc::new(TrackerHttpApiCoreContainer { + http_api_config: http_api_config.clone(), + + // Torrent repository + torrent_repository_container: torrent_repository_container.clone(), + + // Tracker core tracker_core_container: tracker_core_container.clone(), + // HTTP tracker core http_stats_repository: http_tracker_core_container.stats_repository.clone(), + // UDP tracker core ban_service: udp_tracker_core_container.ban_service.clone(), udp_core_stats_repository: udp_tracker_core_container.stats_repository.clone(), - udp_server_stats_repository: udp_tracker_server_container.stats_repository.clone(), - - http_api_config: http_api_config.clone(), }) } } diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 8d5b7514a..b8c2f3f1d 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -93,6 +93,7 @@ pub struct TrackerLabeledMetrics { pub async fn get_labeled_metrics( in_memory_torrent_repository: Arc, ban_service: Arc>, + swarms_stats_repository: Arc, http_stats_repository: Arc, udp_stats_repository: Arc, udp_server_stats_repository: Arc, @@ -100,12 +101,17 @@ pub async fn get_labeled_metrics( let _torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata(); let _udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); + let swarms_stats = swarms_stats_repository.get_metrics().await; let http_stats = http_stats_repository.get_stats().await; let udp_stats_repository = udp_stats_repository.get_stats().await; let udp_server_stats = udp_server_stats_repository.get_stats().await; // Merge all the metrics into a single collection let mut metrics = MetricCollection::default(); + + metrics + .merge(&swarms_stats.metric_collection) + .expect("msg: failed to merge torrent repository metrics"); metrics .merge(&http_stats.metric_collection) .expect("msg: failed to merge HTTP core metrics"); diff --git a/src/container.rs b/src/container.rs index 838de58d6..273425fc1 100644 --- a/src/container.rs +++ b/src/container.rs @@ -142,10 +142,15 @@ impl AppContainer { #[must_use] pub fn tracker_http_api_container(&self, http_api_config: &Arc) -> Arc { TrackerHttpApiCoreContainer { - tracker_core_container: self.tracker_core_container.clone(), http_api_config: http_api_config.clone(), - ban_service: self.udp_tracker_core_services.ban_service.clone(), + + torrent_repository_container: self.torrent_repository_container.clone(), + + tracker_core_container: self.tracker_core_container.clone(), + http_stats_repository: self.http_tracker_core_services.stats_repository.clone(), + + ban_service: self.udp_tracker_core_services.ban_service.clone(), udp_core_stats_repository: self.udp_tracker_core_services.stats_repository.clone(), udp_server_stats_repository: self.udp_tracker_server_container.stats_repository.clone(), } From 2c479a1baa112a4bd86eeb686bc018c3e4f08716 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 12 May 2025 16:38:25 +0100 Subject: [PATCH 1092/1297] refactor: [#1358] inject event sender in Swarms type --- .../src/environment.rs | 8 +- .../tests/server/v1/contract.rs | 31 ++-- .../src/environment.rs | 8 +- .../tests/server/v1/contract/context/stats.rs | 3 +- .../server/v1/contract/context/torrent.rs | 18 +-- packages/events/src/sender.rs | 1 + packages/torrent-repository/src/container.rs | 4 +- .../src/statistics/event/handler.rs | 26 +++- packages/torrent-repository/src/swarms.rs | 140 ++++++++++++------ .../torrent-repository/tests/swarms/mod.rs | 8 +- packages/tracker-core/src/announce_handler.rs | 14 +- packages/tracker-core/src/torrent/manager.rs | 30 ++-- .../src/torrent/repository/in_memory.rs | 9 +- packages/tracker-core/src/torrent/services.rs | 36 +++-- .../udp-tracker-server/src/environment.rs | 5 +- .../src/handlers/announce.rs | 18 ++- .../udp-tracker-server/src/handlers/scrape.rs | 4 +- 17 files changed, 231 insertions(+), 132 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index b9ac6bdbb..078bda9e5 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -25,12 +25,12 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker - pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let _number_of_downloads_increased = self - .container + pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + self.container .tracker_core_container .in_memory_torrent_repository - .upsert_peer(info_hash, peer, None); + .upsert_peer(info_hash, peer, None) + .await } } diff --git a/packages/axum-http-tracker-server/tests/server/v1/contract.rs b/packages/axum-http-tracker-server/tests/server/v1/contract.rs index d1f52d55a..afd4d3168 100644 --- a/packages/axum-http-tracker-server/tests/server/v1/contract.rs +++ b/packages/axum-http-tracker-server/tests/server/v1/contract.rs @@ -474,7 +474,7 @@ mod for_all_config_modes { let previously_announced_peer = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); // Add the Peer 1 - env.add_torrent_peer(&info_hash, &previously_announced_peer); + env.add_torrent_peer(&info_hash, &previously_announced_peer).await; // Announce the new Peer 2. This new peer is non included on the response peer list let response = Client::new(*env.bind_address()) @@ -517,7 +517,7 @@ mod for_all_config_modes { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0x69, 0x69, 0x69, 0x69)), 8080)) .build(); - env.add_torrent_peer(&info_hash, &peer_using_ipv4); + env.add_torrent_peer(&info_hash, &peer_using_ipv4).await; // Announce a peer using IPV6 let peer_using_ipv6 = PeerBuilder::default() @@ -527,7 +527,7 @@ mod for_all_config_modes { 8080, )) .build(); - env.add_torrent_peer(&info_hash, &peer_using_ipv6); + env.add_torrent_peer(&info_hash, &peer_using_ipv6).await; // Announce the new Peer. let response = Client::new(*env.bind_address()) @@ -625,7 +625,7 @@ mod for_all_config_modes { let previously_announced_peer = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); // Add the Peer 1 - env.add_torrent_peer(&info_hash, &previously_announced_peer); + env.add_torrent_peer(&info_hash, &previously_announced_peer).await; // Announce the new Peer 2 accepting compact responses let response = Client::new(*env.bind_address()) @@ -666,7 +666,7 @@ mod for_all_config_modes { let previously_announced_peer = PeerBuilder::default().with_peer_id(&PeerId(*b"-qB00000000000000001")).build(); // Add the Peer 1 - env.add_torrent_peer(&info_hash, &previously_announced_peer); + env.add_torrent_peer(&info_hash, &previously_announced_peer).await; // Announce the new Peer 2 without passing the "compact" param // By default it should respond with the compact peer list @@ -1010,7 +1010,8 @@ mod for_all_config_modes { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), - ); + ) + .await; let response = Client::new(*env.bind_address()) .scrape( @@ -1050,7 +1051,8 @@ mod for_all_config_modes { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_no_bytes_pending_to_download() .build(), - ); + ) + .await; let response = Client::new(*env.bind_address()) .scrape( @@ -1282,7 +1284,8 @@ mod configured_as_whitelisted { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), - ); + ) + .await; let response = Client::new(*env.bind_address()) .scrape( @@ -1318,7 +1321,8 @@ mod configured_as_whitelisted { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), - ); + ) + .await; env.container .tracker_core_container @@ -1494,7 +1498,8 @@ mod configured_as_private { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), - ); + ) + .await; let response = Client::new(*env.bind_address()) .scrape( @@ -1525,7 +1530,8 @@ mod configured_as_private { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), - ); + ) + .await; let expiring_key = env .container @@ -1576,7 +1582,8 @@ mod configured_as_private { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_bytes_pending_to_download(1) .build(), - ); + ) + .await; let false_key: Key = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ".parse().unwrap(); diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index ae3eadb31..e4a83d15d 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -33,12 +33,12 @@ where S: std::fmt::Debug + std::fmt::Display, { /// Add a torrent to the tracker - pub fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let _number_of_downloads_increased = self - .container + pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + self.container .tracker_core_container .in_memory_torrent_repository - .upsert_peer(info_hash, peer, None); + .upsert_peer(info_hash, peer, None) + .await } } diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs index 51a4804e7..7cae0abbf 100644 --- a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/stats.rs @@ -21,7 +21,8 @@ async fn should_allow_getting_tracker_statistics() { env.add_torrent_peer( &InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(), // DevSkim: ignore DS173237 &PeerBuilder::default().into(), - ); + ) + .await; let request_id = Uuid::new_v4(); diff --git a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs index 42421db99..ae9819785 100644 --- a/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs +++ b/packages/axum-rest-tracker-api-server/tests/server/v1/contract/context/torrent.rs @@ -26,7 +26,7 @@ async fn should_allow_getting_all_torrents() { let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 - env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()); + env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()).await; let request_id = Uuid::new_v4(); @@ -59,8 +59,8 @@ async fn should_allow_limiting_the_torrents_in_the_result() { let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); // DevSkim: ignore DS173237 - env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()); - env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()); + env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; let request_id = Uuid::new_v4(); @@ -96,8 +96,8 @@ async fn should_allow_the_torrents_result_pagination() { let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); // DevSkim: ignore DS173237 - env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()); - env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()); + env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; let request_id = Uuid::new_v4(); @@ -132,8 +132,8 @@ async fn should_allow_getting_a_list_of_torrents_providing_infohashes() { let info_hash_1 = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 let info_hash_2 = InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(); // DevSkim: ignore DS173237 - env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()); - env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()); + env.add_torrent_peer(&info_hash_1, &PeerBuilder::default().into()).await; + env.add_torrent_peer(&info_hash_2, &PeerBuilder::default().into()).await; let request_id = Uuid::new_v4(); @@ -307,7 +307,7 @@ async fn should_allow_getting_a_torrent_info() { let peer = PeerBuilder::default().into(); - env.add_torrent_peer(&info_hash, &peer); + env.add_torrent_peer(&info_hash, &peer).await; let request_id = Uuid::new_v4(); @@ -389,7 +389,7 @@ async fn should_not_allow_getting_a_torrent_info_for_unauthenticated_users() { let info_hash = InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(); // DevSkim: ignore DS173237 - env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()); + env.add_torrent_peer(&info_hash, &PeerBuilder::default().into()).await; let request_id = Uuid::new_v4(); diff --git a/packages/events/src/sender.rs b/packages/events/src/sender.rs index 9fc77f650..3dccade4c 100644 --- a/packages/events/src/sender.rs +++ b/packages/events/src/sender.rs @@ -1,4 +1,5 @@ use std::fmt; +use std::fmt::Debug; use futures::future::BoxFuture; #[cfg(test)] diff --git a/packages/torrent-repository/src/container.rs b/packages/torrent-repository/src/container.rs index 7522c7956..50a6b8b9c 100644 --- a/packages/torrent-repository/src/container.rs +++ b/packages/torrent-repository/src/container.rs @@ -16,8 +16,6 @@ pub struct TorrentRepositoryContainer { impl TorrentRepositoryContainer { #[must_use] pub fn initialize() -> Self { - let swarms = Arc::new(Swarms::default()); - // Torrent repository stats let broadcaster = Broadcaster::default(); let stats_repository = Arc::new(Repository::new()); @@ -27,6 +25,8 @@ impl TorrentRepositoryContainer { let stats_event_sender = event_bus.sender(); + let swarms = Arc::new(Swarms::new(stats_event_sender.clone())); + Self { swarms, event_bus, diff --git a/packages/torrent-repository/src/statistics/event/handler.rs b/packages/torrent-repository/src/statistics/event/handler.rs index d68df0b1b..2073575a8 100644 --- a/packages/torrent-repository/src/statistics/event/handler.rs +++ b/packages/torrent-repository/src/statistics/event/handler.rs @@ -9,13 +9,25 @@ use crate::statistics::repository::Repository; /// /// This function panics if the client IP address is not the same as the IP /// version of the event. -pub async fn handle_event(_event: Event, stats_repository: &Arc, _now: DurationSinceUnixEpoch) { - /*match event { - Event::TorrentAdded { .. } => {} - Event::TorrentRemoved { .. } => {} - Event::PeerAdded { .. } => {} - Event::PeerRemoved { .. } => {} - }*/ +pub async fn handle_event(event: Event, stats_repository: &Arc, _now: DurationSinceUnixEpoch) { + match event { + Event::TorrentAdded { info_hash, .. } => { + // todo: update metrics + tracing::debug!("Torrent added {info_hash}"); + } + Event::TorrentRemoved { info_hash } => { + // todo: update metrics + tracing::debug!("Torrent removed {info_hash}"); + } + Event::PeerAdded { announcement } => { + // todo: update metrics + tracing::debug!("Peer added {announcement:?}"); + } + Event::PeerRemoved { socket_addr, peer_id } => { + // todo: update metrics + tracing::debug!("Peer removed: socket address {socket_addr:?}, peer ID: {peer_id:?}"); + } + } tracing::debug!("metrics: {:?}", stats_repository.get_metrics().await); } diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 9dddaa0c0..d92e1755a 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -8,15 +8,26 @@ use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use crate::event::sender::Sender; +use crate::event::Event; use crate::swarm::Swarm; -use crate::{SwarmHandle, TORRENT_REPOSITORY_LOG_TARGET}; +use crate::SwarmHandle; -#[derive(Default, Debug)] +#[derive(Default)] pub struct Swarms { swarms: SkipMap, + event_sender: Sender, } impl Swarms { + #[must_use] + pub fn new(event_sender: Sender) -> Self { + Self { + swarms: SkipMap::new(), + event_sender, + } + } + /// Upsert a peer into the swarm of a torrent. /// /// Optionally, it can also preset the number of downloads of the torrent @@ -37,36 +48,55 @@ impl Swarms { /// # Errors /// /// This function panics if the lock for the swarm handle cannot be acquired. - pub fn handle_announcement( + pub async fn handle_announcement( &self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option, ) -> Result { - tracing::trace!(target: TORRENT_REPOSITORY_LOG_TARGET, "Handling announcement for torrent: {info_hash}"); + let swarm_handle = match self.swarms.get(info_hash) { + None => { + let new_swarm_handle = if let Some(number_of_downloads) = opt_persistent_torrent { + SwarmHandle::new(Swarm::new(number_of_downloads).into()) + } else { + SwarmHandle::default() + }; - let swarm_handle = if let Some(number_of_downloads) = opt_persistent_torrent { - SwarmHandle::new(Swarm::new(number_of_downloads).into()) - } else { - SwarmHandle::default() - }; + let new_swarm_handle = self.swarms.get_or_insert(*info_hash, new_swarm_handle); - let swarm_handle = self.swarms.get_or_insert(*info_hash, swarm_handle); + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::TorrentAdded { + info_hash: *info_hash, + announcement: *peer, + }) + .await; + } + + new_swarm_handle + } + Some(existing_swarm_handle) => existing_swarm_handle, + }; let mut swarm = swarm_handle.value().lock()?; Ok(swarm.handle_announcement(peer)) } - /// Inserts a new swarm. + /// Inserts a new swarm. Only used for testing purposes. pub fn insert(&self, info_hash: &InfoHash, swarm: Swarm) { - // code-review: swarms builder? + // code-review: swarms builder? or constructor from vec? // It's only used for testing purposes. It allows to pre-define the // initial state of the swarm without having to go through the upsert // process. let swarm_handle = Arc::new(Mutex::new(swarm)); + self.swarms.insert(*info_hash, swarm_handle); + + // IMPORTANT: Notice this does not send an event because is used only + // for testing purposes. The event is sent only when the torrent is + // announced for the first time. } /// Removes a torrent entry from the repository. @@ -75,8 +105,14 @@ impl Swarms { /// /// An `Option` containing the removed torrent entry if it existed. #[must_use] - pub fn remove(&self, key: &InfoHash) -> Option { - self.swarms.remove(key).map(|entry| entry.value().clone()) + pub async fn remove(&self, key: &InfoHash) -> Option { + let swarm_handle = self.swarms.remove(key).map(|entry| entry.value().clone()); + + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender.send(Event::TorrentRemoved { info_hash: *key }).await; + } + + swarm_handle } /// Retrieves a tracked torrent handle by its infohash. @@ -402,7 +438,7 @@ impl From>> for Error { #[cfg(test)] mod tests { - mod the_in_memory_torrent_repository { + mod the_swarm_repository { use aquatic_udp_protocol::PeerId; @@ -447,7 +483,7 @@ mod tests { let info_hash = sample_info_hash(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &sample_peer(), None); + swarms.handle_announcement(&info_hash, &sample_peer(), None).await.unwrap(); assert!(swarms.get(&info_hash).is_some()); } @@ -458,8 +494,8 @@ mod tests { let info_hash = sample_info_hash(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &sample_peer(), None); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &sample_peer(), None); + swarms.handle_announcement(&info_hash, &sample_peer(), None).await.unwrap(); + swarms.handle_announcement(&info_hash, &sample_peer(), None).await.unwrap(); assert!(swarms.get(&info_hash).is_some()); } @@ -474,7 +510,7 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::swarms::tests::the_in_memory_torrent_repository::numeric_peer_id; + use crate::swarms::tests::the_swarm_repository::numeric_peer_id; use crate::swarms::Swarms; use crate::tests::{sample_info_hash, sample_peer}; @@ -485,7 +521,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); let peers = swarms.get_swarm_peers(&info_hash, 74).unwrap(); @@ -518,7 +554,7 @@ mod tests { event: AnnounceEvent::Completed, }; - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); } let peers = swarms.get_swarm_peers(&info_hash, 74).unwrap(); @@ -536,7 +572,7 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::swarms::tests::the_in_memory_torrent_repository::numeric_peer_id; + use crate::swarms::tests::the_swarm_repository::numeric_peer_id; use crate::swarms::Swarms; use crate::tests::{sample_info_hash, sample_peer}; @@ -558,7 +594,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); let peers = swarms .get_peers_peers_excluding(&info_hash, &peer, TORRENT_PEERS_LIMIT) @@ -575,7 +611,7 @@ mod tests { let excluded_peer = sample_peer(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &excluded_peer, None); + swarms.handle_announcement(&info_hash, &excluded_peer, None).await.unwrap(); // Add 74 peers for idx in 2..=75 { @@ -589,7 +625,7 @@ mod tests { event: AnnounceEvent::Completed, }; - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); } let peers = swarms @@ -619,9 +655,9 @@ mod tests { let swarms = Arc::new(Swarms::default()); let info_hash = sample_info_hash(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &sample_peer(), None); + swarms.handle_announcement(&info_hash, &sample_peer(), None).await.unwrap(); - let _unused = swarms.remove(&info_hash); + let _unused = swarms.remove(&info_hash).await; assert!(swarms.get(&info_hash).is_none()); } @@ -634,7 +670,7 @@ mod tests { let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); // Cut off time is 1 second after the peer was updated swarms @@ -644,13 +680,13 @@ mod tests { assert!(!swarms.get_swarm_peers(&info_hash, 74).unwrap().contains(&Arc::new(peer))); } - fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { + async fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { let swarms = Arc::new(Swarms::default()); // Insert a sample peer for the torrent to force adding the torrent entry let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = swarms.handle_announcement(info_hash, &peer, None); + swarms.handle_announcement(info_hash, &peer, None).await.unwrap(); // Remove the peer swarms @@ -664,7 +700,7 @@ mod tests { async fn it_should_remove_torrents_without_peers() { let info_hash = sample_info_hash(); - let swarms = initialize_repository_with_one_torrent_without_peers(&info_hash); + let swarms = initialize_repository_with_one_torrent_without_peers(&info_hash).await; let tracker_policy = TrackerPolicy { remove_peerless_torrents: true, @@ -721,7 +757,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); let torrent_entry = swarms.get(&info_hash).unwrap(); @@ -744,7 +780,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::swarms::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; + use crate::swarms::tests::the_swarm_repository::returning_torrent_entries::TorrentEntryInfo; use crate::swarms::Swarms; use crate::tests::{sample_info_hash, sample_peer}; @@ -754,7 +790,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash, &peer, None); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); let torrent_entries = swarms.get_paginated(None); @@ -782,7 +818,7 @@ mod tests { use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::swarms::tests::the_in_memory_torrent_repository::returning_torrent_entries::TorrentEntryInfo; + use crate::swarms::tests::the_swarm_repository::returning_torrent_entries::TorrentEntryInfo; use crate::swarms::Swarms; use crate::tests::{ sample_info_hash_alphabetically_ordered_after_sample_info_hash_one, sample_info_hash_one, @@ -796,12 +832,12 @@ mod tests { // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash_one, &peer_one, None); + swarms.handle_announcement(&info_hash_one, &peer_one, None).await.unwrap(); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash_one, &peer_two, None); + swarms.handle_announcement(&info_hash_one, &peer_two, None).await.unwrap(); // Get only the first page where page size is 1 let torrent_entries = swarms.get_paginated(Some(&Pagination { offset: 0, limit: 1 })); @@ -831,12 +867,12 @@ mod tests { // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash_one, &peer_one, None); + swarms.handle_announcement(&info_hash_one, &peer_one, None).await.unwrap(); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash_one, &peer_two, None); + swarms.handle_announcement(&info_hash_one, &peer_two, None).await.unwrap(); // Get only the first page where page size is 1 let torrent_entries = swarms.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); @@ -866,12 +902,12 @@ mod tests { // Insert one torrent entry let info_hash_one = sample_info_hash_one(); let peer_one = sample_peer_one(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash_one, &peer_one, None); + swarms.handle_announcement(&info_hash_one, &peer_one, None).await.unwrap(); // Insert another torrent entry let info_hash_one = sample_info_hash_alphabetically_ordered_after_sample_info_hash_one(); let peer_two = sample_peer_two(); - let _number_of_downloads_increased = swarms.handle_announcement(&info_hash_one, &peer_two, None); + swarms.handle_announcement(&info_hash_one, &peer_two, None).await.unwrap(); // Get only the first page where page size is 1 let torrent_entries = swarms.get_paginated(Some(&Pagination { offset: 1, limit: 1 })); @@ -915,7 +951,10 @@ mod tests { async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_leecher() { let swarms = Arc::new(Swarms::default()); - let _number_of_downloads_increased = swarms.handle_announcement(&sample_info_hash(), &leecher(), None); + swarms + .handle_announcement(&sample_info_hash(), &leecher(), None) + .await + .unwrap(); let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); @@ -934,7 +973,10 @@ mod tests { async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_seeder() { let swarms = Arc::new(Swarms::default()); - let _number_of_downloads_increased = swarms.handle_announcement(&sample_info_hash(), &seeder(), None); + swarms + .handle_announcement(&sample_info_hash(), &seeder(), None) + .await + .unwrap(); let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); @@ -953,7 +995,10 @@ mod tests { async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_completed_peer() { let swarms = Arc::new(Swarms::default()); - let _number_of_downloads_increased = swarms.handle_announcement(&sample_info_hash(), &complete_peer(), None); + swarms + .handle_announcement(&sample_info_hash(), &complete_peer(), None) + .await + .unwrap(); let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); @@ -974,7 +1019,10 @@ mod tests { let start_time = std::time::Instant::now(); for i in 0..1_000_000 { - let _number_of_downloads_increased = swarms.handle_announcement(&gen_seeded_infohash(&i), &leecher(), None); + swarms + .handle_announcement(&gen_seeded_infohash(&i), &leecher(), None) + .await + .unwrap(); } let result_a = start_time.elapsed(); @@ -1010,7 +1058,7 @@ mod tests { let infohash = sample_info_hash(); - let _number_of_downloads_increased = swarms.handle_announcement(&infohash, &leecher(), None); + swarms.handle_announcement(&infohash, &leecher(), None).await.unwrap(); let swarm_metadata = swarms.get_swarm_metadata_or_default(&infohash).unwrap(); diff --git a/packages/torrent-repository/tests/swarms/mod.rs b/packages/torrent-repository/tests/swarms/mod.rs index 8e58b9e76..975457cca 100644 --- a/packages/torrent-repository/tests/swarms/mod.rs +++ b/packages/torrent-repository/tests/swarms/mod.rs @@ -377,12 +377,12 @@ async fn it_should_remove_an_entry(#[values(swarms())] swarms: Swarms, #[case] e Some(torrent.clone()) ); assert_eq!( - Some(swarms.remove(&info_hash).unwrap().lock_or_panic().clone()), + Some(swarms.remove(&info_hash).await.unwrap().lock_or_panic().clone()), Some(torrent) ); assert!(swarms.get(&info_hash).is_none()); - assert!(swarms.remove(&info_hash).is_none()); + assert!(swarms.remove(&info_hash).await.is_none()); } assert_eq!(swarms.get_aggregate_swarm_metadata().unwrap().total_torrents, 0); @@ -435,7 +435,7 @@ async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[c // Insert the infohash and peer into the repository // and verify there is an extra torrent entry. { - swarms.handle_announcement(&info_hash, &peer, None).unwrap(); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); assert_eq!( swarms.get_aggregate_swarm_metadata().unwrap().total_torrents, entries.len() as u64 + 1 @@ -445,7 +445,7 @@ async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[c // Insert the infohash and peer into the repository // and verify the swarm metadata was updated. { - swarms.handle_announcement(&info_hash, &peer, None).unwrap(); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); let stats = swarms.get_swarm_metadata(&info_hash).unwrap(); assert_eq!( stats, diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index fac0a38c8..00d42174a 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -171,9 +171,10 @@ impl AnnounceHandler { peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); - let number_of_downloads_increased = - self.in_memory_torrent_repository - .upsert_peer(info_hash, peer, opt_persistent_torrent); + let number_of_downloads_increased = self + .in_memory_torrent_repository + .upsert_peer(info_hash, peer, opt_persistent_torrent) + .await; if self.config.tracker_policy.persistent_torrent_completed_stat && number_of_downloads_increased { self.db_torrent_repository.increase_number_of_downloads(info_hash)?; @@ -594,7 +595,7 @@ mod tests { use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_test_helpers::configuration; - use torrust_tracker_torrent_repository::LockTrackedTorrent; + use torrust_tracker_torrent_repository::{LockTrackedTorrent, Swarms}; use crate::announce_handler::tests::the_announce_handler::peer_ip; use crate::announce_handler::{AnnounceHandler, PeersWanted}; @@ -613,7 +614,8 @@ mod tests { config.core.tracker_policy.persistent_torrent_completed_stat = true; let database = initialize_database(&config.core); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let swarms = Arc::new(Swarms::default()); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new(swarms)); let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); let torrents_manager = Arc::new(TorrentsManager::new( &config.core, @@ -648,7 +650,7 @@ mod tests { assert_eq!(announce_data.stats.downloaded, 1); // Remove the newly updated torrent from memory - let _unused = in_memory_torrent_repository.remove(&info_hash); + let _unused = in_memory_torrent_repository.remove(&info_hash).await; torrents_manager.load_torrents_from_database().unwrap(); diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index aaac811f2..dec52daac 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -144,7 +144,7 @@ mod tests { use std::sync::Arc; use torrust_tracker_configuration::Core; - use torrust_tracker_torrent_repository::LockTrackedTorrent; + use torrust_tracker_torrent_repository::{LockTrackedTorrent, Swarms}; use super::{DatabasePersistentTorrentRepository, TorrentsManager}; use crate::databases::setup::initialize_database; @@ -163,7 +163,8 @@ mod tests { } fn initialize_torrents_manager_with(config: Core) -> (Arc, Arc) { - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); + let swarms = Arc::new(Swarms::default()); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new(swarms)); let database = initialize_database(&config); let database_persistent_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); @@ -219,8 +220,8 @@ mod tests { use crate::torrent::manager::tests::{initialize_torrents_manager, initialize_torrents_manager_with}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - #[test] - fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { + #[tokio::test] + async fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { let (torrents_manager, services) = initialize_torrents_manager(); let infohash = sample_info_hash(); @@ -230,7 +231,10 @@ mod tests { // Add a peer to the torrent let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = services.in_memory_torrent_repository.upsert_peer(&infohash, &peer, None); + let _number_of_downloads_increased = services + .in_memory_torrent_repository + .upsert_peer(&infohash, &peer, None) + .await; // Simulate the time has passed 1 second more than the max peer timeout. clock::Stopped::local_add(&Duration::from_secs( @@ -243,18 +247,18 @@ mod tests { assert!(services.in_memory_torrent_repository.get(&infohash).is_none()); } - fn add_a_peerless_torrent(infohash: &InfoHash, in_memory_torrent_repository: &Arc) { + async fn add_a_peerless_torrent(infohash: &InfoHash, in_memory_torrent_repository: &Arc) { // Add a peer to the torrent let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(infohash, &peer, None); + let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(infohash, &peer, None).await; // Remove the peer. The torrent is now peerless. in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); } - #[test] - fn it_should_remove_torrents_that_have_no_peers_when_it_is_configured_to_do_so() { + #[tokio::test] + async fn it_should_remove_torrents_that_have_no_peers_when_it_is_configured_to_do_so() { let mut config = ephemeral_configuration(); config.tracker_policy.remove_peerless_torrents = true; @@ -262,15 +266,15 @@ mod tests { let infohash = sample_info_hash(); - add_a_peerless_torrent(&infohash, &services.in_memory_torrent_repository); + add_a_peerless_torrent(&infohash, &services.in_memory_torrent_repository).await; torrents_manager.cleanup_torrents(); assert!(services.in_memory_torrent_repository.get(&infohash).is_none()); } - #[test] - fn it_should_retain_peerless_torrents_when_it_is_configured_to_do_so() { + #[tokio::test] + async fn it_should_retain_peerless_torrents_when_it_is_configured_to_do_so() { let mut config = ephemeral_configuration(); config.tracker_policy.remove_peerless_torrents = false; @@ -278,7 +282,7 @@ mod tests { let infohash = sample_info_hash(); - add_a_peerless_torrent(&infohash, &services.in_memory_torrent_repository); + add_a_peerless_torrent(&infohash, &services.in_memory_torrent_repository).await; torrents_manager.cleanup_torrents(); diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index c8e593471..37d9d3f5c 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -18,7 +18,7 @@ use torrust_tracker_torrent_repository::{SwarmHandle, Swarms}; /// /// Multiple implementations were considered, and the chosen implementation is /// used in production. Other implementations are kept for reference. -#[derive(Debug, Default)] +#[derive(Default)] pub struct InMemoryTorrentRepository { /// The underlying in-memory data structure that stores swarms data. swarms: Arc, @@ -49,7 +49,7 @@ impl InMemoryTorrentRepository { /// /// This function panics if the underling swarms return an error. #[must_use] - pub fn upsert_peer( + pub async fn upsert_peer( &self, info_hash: &InfoHash, peer: &peer::Peer, @@ -57,6 +57,7 @@ impl InMemoryTorrentRepository { ) -> bool { self.swarms .handle_announcement(info_hash, peer, opt_persistent_torrent) + .await .expect("Failed to upsert the peer in swarms") } @@ -75,8 +76,8 @@ impl InMemoryTorrentRepository { /// An `Option` containing the removed torrent entry if it existed. #[cfg(test)] #[must_use] - pub(crate) fn remove(&self, key: &InfoHash) -> Option { - self.swarms.remove(key) + pub(crate) async fn remove(&self, key: &InfoHash) -> Option { + self.swarms.remove(key).await } /// Removes inactive peers from all torrent entries. diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index a35fd7aed..14a4f58f5 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -246,7 +246,9 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + let _number_of_downloads_increased = in_memory_torrent_repository + .upsert_peer(&info_hash, &sample_peer(), None) + .await; let torrent_info = get_torrent_info(&in_memory_torrent_repository, &info_hash).unwrap(); @@ -290,7 +292,9 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + let _number_of_downloads_increased = in_memory_torrent_repository + .upsert_peer(&info_hash, &sample_peer(), None) + .await; let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); @@ -315,8 +319,12 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer(), None); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer(), None); + let _number_of_downloads_increased = in_memory_torrent_repository + .upsert_peer(&info_hash1, &sample_peer(), None) + .await; + let _number_of_downloads_increased = in_memory_torrent_repository + .upsert_peer(&info_hash2, &sample_peer(), None) + .await; let offset = 0; let limit = 1; @@ -336,8 +344,12 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer(), None); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer(), None); + let _number_of_downloads_increased = in_memory_torrent_repository + .upsert_peer(&info_hash1, &sample_peer(), None) + .await; + let _number_of_downloads_increased = in_memory_torrent_repository + .upsert_peer(&info_hash2, &sample_peer(), None) + .await; let offset = 1; let limit = 4000; @@ -362,11 +374,15 @@ mod tests { let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash1, &sample_peer(), None); + let _number_of_downloads_increased = in_memory_torrent_repository + .upsert_peer(&info_hash1, &sample_peer(), None) + .await; let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash2, &sample_peer(), None); + let _number_of_downloads_increased = in_memory_torrent_repository + .upsert_peer(&info_hash2, &sample_peer(), None) + .await; let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); @@ -414,7 +430,9 @@ mod tests { let info_hash = sample_info_hash(); - let _ = in_memory_torrent_repository.upsert_peer(&info_hash, &sample_peer(), None); + let _ = in_memory_torrent_repository + .upsert_peer(&info_hash, &sample_peer(), None) + .await; let torrent_info = get_torrents(&in_memory_torrent_repository, &[info_hash]); diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index e3667e74a..6dae3d860 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -34,12 +34,13 @@ where { /// Add a torrent to the tracker #[allow(dead_code)] - pub fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { + pub async fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { let _number_of_downloads_increased = self .container .tracker_core_container .in_memory_torrent_repository - .upsert_peer(info_hash, peer, None); + .upsert_peer(info_hash, peer, None) + .await; } } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 5311531aa..ba0721289 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -353,7 +353,7 @@ mod tests { assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); } - fn add_a_torrent_peer_using_ipv6(in_memory_torrent_repository: &Arc) { + async fn add_a_torrent_peer_using_ipv6(in_memory_torrent_repository: &Arc) { let info_hash = AquaticInfoHash([0u8; 20]); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); @@ -366,8 +366,9 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv6, None); + let _number_of_downloads_increased = in_memory_torrent_repository + .upsert_peer(&info_hash.0.into(), &peer_using_ipv6, None) + .await; } async fn announce_a_new_peer_using_ipv4( @@ -405,7 +406,7 @@ mod tests { let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - add_a_torrent_peer_using_ipv6(&core_tracker_services.in_memory_torrent_repository); + add_a_torrent_peer_using_ipv6(&core_tracker_services.in_memory_torrent_repository).await; let response = announce_a_new_peer_using_ipv4(Arc::new(core_tracker_services), Arc::new(core_udp_tracker_services)).await; @@ -689,7 +690,7 @@ mod tests { assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); } - fn add_a_torrent_peer_using_ipv4(in_memory_torrent_repository: &Arc) { + async fn add_a_torrent_peer_using_ipv4(in_memory_torrent_repository: &Arc) { let info_hash = AquaticInfoHash([0u8; 20]); let client_ip_v4 = Ipv4Addr::new(126, 0, 0, 1); @@ -701,8 +702,9 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) .into(); - let _number_of_downloads_increased = - in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer_using_ipv4, None); + let _number_of_downloads_increased = in_memory_torrent_repository + .upsert_peer(&info_hash.0.into(), &peer_using_ipv4, None) + .await; } async fn announce_a_new_peer_using_ipv6( @@ -755,7 +757,7 @@ mod tests { let (core_tracker_services, _core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - add_a_torrent_peer_using_ipv4(&core_tracker_services.in_memory_torrent_repository); + add_a_torrent_peer_using_ipv4(&core_tracker_services.in_memory_torrent_repository).await; let response = announce_a_new_peer_using_ipv6( core_tracker_services.core_config.clone(), diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 5cc84acd6..34d5a5ce2 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -163,7 +163,9 @@ mod tests { .with_number_of_bytes_left(0) .into(); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(&info_hash.0.into(), &peer, None); + let _number_of_downloads_increased = in_memory_torrent_repository + .upsert_peer(&info_hash.0.into(), &peer, None) + .await; } fn build_scrape_request(remote_addr: &SocketAddr, info_hash: &InfoHash) -> ScrapeRequest { From 6d95d1ad22f87c46310a14f47736e52bac07d993 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 12 May 2025 19:12:58 +0100 Subject: [PATCH 1093/1297] refactor: [#1358] inject event sender in Swarm type It required to use `tokio::sync::Mutex` for the `SwarmHandle` (`Arc>`). Otherwise it's not safe to pass the Swarm lock between threads. --- Cargo.lock | 1 + .../tests/server/v1/contract.rs | 12 +- .../src/v1/context/torrent/handlers.rs | 17 +- .../src/statistics/services.rs | 2 +- .../src/statistics/services.rs | 2 +- packages/torrent-repository/Cargo.toml | 1 + packages/torrent-repository/src/lib.rs | 13 +- packages/torrent-repository/src/swarm.rs | 295 +++++++++++------- packages/torrent-repository/src/swarms.rs | 140 +++++---- .../torrent-repository/tests/swarm/mod.rs | 60 ++-- .../torrent-repository/tests/swarms/mod.rs | 198 ++++++------ packages/tracker-core/src/announce_handler.rs | 18 +- packages/tracker-core/src/scrape_handler.rs | 6 +- packages/tracker-core/src/torrent/manager.rs | 48 +-- .../src/torrent/repository/in_memory.rs | 25 +- packages/tracker-core/src/torrent/services.rs | 51 +-- .../src/statistics/services.rs | 2 +- .../src/handlers/announce.rs | 17 +- .../src/statistics/services.rs | 2 +- src/bootstrap/jobs/torrent_cleanup.rs | 2 +- 20 files changed, 510 insertions(+), 402 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b39355065..ddf163cc6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4857,6 +4857,7 @@ dependencies = [ "bittorrent-primitives", "criterion", "crossbeam-skiplist", + "futures", "rand 0.9.1", "rstest", "serde", diff --git a/packages/axum-http-tracker-server/tests/server/v1/contract.rs b/packages/axum-http-tracker-server/tests/server/v1/contract.rs index afd4d3168..d864ba67c 100644 --- a/packages/axum-http-tracker-server/tests/server/v1/contract.rs +++ b/packages/axum-http-tracker-server/tests/server/v1/contract.rs @@ -787,7 +787,8 @@ mod for_all_config_modes { .container .tracker_core_container .in_memory_torrent_repository - .get_torrent_peers(&info_hash); + .get_torrent_peers(&info_hash) + .await; let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), client_ip); @@ -829,7 +830,8 @@ mod for_all_config_modes { .container .tracker_core_container .in_memory_torrent_repository - .get_torrent_peers(&info_hash); + .get_torrent_peers(&info_hash) + .await; let peer_addr = peers[0].peer_addr; assert_eq!( @@ -878,7 +880,8 @@ mod for_all_config_modes { .container .tracker_core_container .in_memory_torrent_repository - .get_torrent_peers(&info_hash); + .get_torrent_peers(&info_hash) + .await; let peer_addr = peers[0].peer_addr; assert_eq!( @@ -925,7 +928,8 @@ mod for_all_config_modes { .container .tracker_core_container .in_memory_torrent_repository - .get_torrent_peers(&info_hash); + .get_torrent_peers(&info_hash) + .await; let peer_addr = peers[0].peer_addr; assert_eq!(peer_addr.ip(), IpAddr::from_str("150.172.238.178").unwrap()); diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/torrent/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/handlers.rs index 613abbdeb..eecbd9ac3 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/torrent/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/handlers.rs @@ -33,7 +33,7 @@ pub async fn get_torrent_handler( ) -> Response { match InfoHash::from_str(&info_hash.0) { Err(_) => invalid_info_hash_param_response(&info_hash.0), - Ok(info_hash) => match get_torrent_info(&in_memory_torrent_repository, &info_hash) { + Ok(info_hash) => match get_torrent_info(&in_memory_torrent_repository, &info_hash).await { Some(info) => torrent_info_response(info).into_response(), None => torrent_not_known_response(), }, @@ -85,14 +85,19 @@ pub async fn get_torrents_handler( tracing::debug!("pagination: {:?}", pagination); if pagination.0.info_hashes.is_empty() { - torrent_list_response(&get_torrents_page( - &in_memory_torrent_repository, - Some(&Pagination::new_with_options(pagination.0.offset, pagination.0.limit)), - )) + torrent_list_response( + &get_torrents_page( + &in_memory_torrent_repository, + Some(&Pagination::new_with_options(pagination.0.offset, pagination.0.limit)), + ) + .await, + ) .into_response() } else { match parse_info_hashes(pagination.0.info_hashes) { - Ok(info_hashes) => torrent_list_response(&get_torrents(&in_memory_torrent_repository, &info_hashes)).into_response(), + Ok(info_hashes) => { + torrent_list_response(&get_torrents(&in_memory_torrent_repository, &info_hashes).await).into_response() + } Err(err) => match err { QueryParamError::InvalidInfoHash { info_hash } => invalid_info_hash_param_response(&info_hash), }, diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 1c5890ea8..3c8a4fa43 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -47,7 +47,7 @@ pub async fn get_metrics( in_memory_torrent_repository: Arc, stats_repository: Arc, ) -> TrackerMetrics { - let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata(); + let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; let stats = stats_repository.get_stats().await; TrackerMetrics { diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index b8c2f3f1d..aad31a323 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -32,7 +32,7 @@ pub async fn get_metrics( http_stats_repository: Arc, udp_server_stats_repository: Arc, ) -> TrackerMetrics { - let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata(); + let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); let http_stats = http_stats_repository.get_stats().await; let udp_server_stats = udp_server_stats_repository.get_stats().await; diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 77192c7cf..1c7cc09fe 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -19,6 +19,7 @@ version.workspace = true aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" crossbeam-skiplist = "0" +futures = "0" serde = "1.0.219" thiserror = "2.0.12" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } diff --git a/packages/torrent-repository/src/lib.rs b/packages/torrent-repository/src/lib.rs index c6790c4db..3adf2f18d 100644 --- a/packages/torrent-repository/src/lib.rs +++ b/packages/torrent-repository/src/lib.rs @@ -4,8 +4,9 @@ pub mod statistics; pub mod swarm; pub mod swarms; -use std::sync::{Arc, Mutex, MutexGuard}; +use std::sync::Arc; +use tokio::sync::Mutex; use torrust_tracker_clock::clock; pub type Swarms = swarms::Swarms; @@ -24,16 +25,6 @@ pub(crate) type CurrentClock = clock::Stopped; pub const TORRENT_REPOSITORY_LOG_TARGET: &str = "TORRENT_REPOSITORY"; -pub trait LockTrackedTorrent { - fn lock_or_panic(&self) -> MutexGuard<'_, Swarm>; -} - -impl LockTrackedTorrent for SwarmHandle { - fn lock_or_panic(&self) -> MutexGuard<'_, Swarm> { - self.lock().expect("can't acquire lock for tracked torrent handle") - } -} - #[cfg(test)] pub(crate) mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 4437ca410..d1918bd24 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -1,6 +1,8 @@ //! A swarm is a collection of peers that are all trying to download the same //! torrent. use std::collections::BTreeMap; +use std::fmt::Debug; +use std::hash::{Hash, Hasher}; use std::net::SocketAddr; use std::sync::Arc; @@ -10,37 +12,72 @@ use torrust_tracker_primitives::peer::{self, Peer, PeerAnnouncement}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; -#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +use crate::event::sender::Sender; +use crate::event::Event; + +#[derive(Clone, Default)] pub struct Swarm { peers: BTreeMap>, metadata: SwarmMetadata, + event_sender: Sender, +} + +#[allow(clippy::missing_fields_in_debug)] +impl Debug for Swarm { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Swarm") + .field("peers", &self.peers) + .field("metadata", &self.metadata) + .finish() + } +} + +impl Hash for Swarm { + fn hash(&self, state: &mut H) { + self.peers.hash(state); + self.metadata.hash(state); + } +} + +impl PartialEq for Swarm { + fn eq(&self, other: &Self) -> bool { + self.peers == other.peers && self.metadata == other.metadata + } } +impl Eq for Swarm {} + impl Swarm { #[must_use] - pub fn new(downloaded: u32) -> Self { + pub fn new(downloaded: u32, event_sender: Sender) -> Self { Self { peers: BTreeMap::new(), metadata: SwarmMetadata::new(downloaded, 0, 0), + event_sender, } } - pub fn handle_announcement(&mut self, incoming_announce: &PeerAnnouncement) -> bool { + pub async fn handle_announcement(&mut self, incoming_announce: &PeerAnnouncement) -> bool { let mut downloads_increased: bool = false; let _previous_peer = match peer::ReadInfo::get_event(incoming_announce) { AnnounceEvent::Started | AnnounceEvent::None | AnnounceEvent::Completed => { - self.upsert_peer(Arc::new(*incoming_announce), &mut downloads_increased) + self.upsert_peer(Arc::new(*incoming_announce), &mut downloads_increased).await } - AnnounceEvent::Stopped => self.remove(incoming_announce), + AnnounceEvent::Stopped => self.remove(incoming_announce).await, }; downloads_increased } - pub fn upsert_peer(&mut self, incoming_announce: Arc, downloads_increased: &mut bool) -> Option> { + pub async fn upsert_peer( + &mut self, + incoming_announce: Arc, + downloads_increased: &mut bool, + ) -> Option> { let is_now_seeder = incoming_announce.is_seeder(); let has_completed = incoming_announce.event == AnnounceEvent::Completed; + let announcement = incoming_announce.clone(); if let Some(old_announce) = self.peers.insert(incoming_announce.peer_addr, incoming_announce) { // A peer has been updated in the swarm. @@ -79,11 +116,19 @@ impl Swarm { // from a known peer } + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerAdded { + announcement: *announcement, + }) + .await; + } + None } } - pub fn remove(&mut self, peer_to_remove: &Peer) -> Option> { + pub async fn remove(&mut self, peer_to_remove: &Peer) -> Option> { match self.peers.remove(&peer_to_remove.peer_addr) { Some(old_peer) => { // A peer has been removed from the swarm. @@ -95,6 +140,15 @@ impl Swarm { self.metadata.incomplete -= 1; } + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerRemoved { + socket_addr: old_peer.peer_addr, + peer_id: old_peer.peer_id, + }) + .await; + } + Some(old_peer) } None => None, @@ -246,104 +300,107 @@ mod tests { assert_eq!(swarm.len(), 0); } - #[test] - fn it_should_allow_inserting_a_new_peer() { + #[tokio::test] + async fn it_should_allow_inserting_a_new_peer() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - assert_eq!(swarm.upsert_peer(peer.into(), &mut downloads_increased), None); + assert_eq!(swarm.upsert_peer(peer.into(), &mut downloads_increased).await, None); } - #[test] - fn it_should_allow_updating_a_preexisting_peer() { + #[tokio::test] + async fn it_should_allow_updating_a_preexisting_peer() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; - assert_eq!(swarm.upsert_peer(peer.into(), &mut downloads_increased), Some(Arc::new(peer))); + assert_eq!( + swarm.upsert_peer(peer.into(), &mut downloads_increased).await, + Some(Arc::new(peer)) + ); } - #[test] - fn it_should_allow_getting_all_peers() { + #[tokio::test] + async fn it_should_allow_getting_all_peers() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; assert_eq!(swarm.peers(None), [Arc::new(peer)]); } - #[test] - fn it_should_allow_getting_one_peer_by_id() { + #[tokio::test] + async fn it_should_allow_getting_one_peer_by_id() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; assert_eq!(swarm.get(&peer.peer_addr), Some(Arc::new(peer)).as_ref()); } - #[test] - fn it_should_increase_the_number_of_peers_after_inserting_a_new_one() { + #[tokio::test] + async fn it_should_increase_the_number_of_peers_after_inserting_a_new_one() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; assert_eq!(swarm.len(), 1); } - #[test] - fn it_should_decrease_the_number_of_peers_after_removing_one() { + #[tokio::test] + async fn it_should_decrease_the_number_of_peers_after_removing_one() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; - swarm.remove(&peer); + swarm.remove(&peer).await; assert!(swarm.is_empty()); } - #[test] - fn it_should_allow_removing_an_existing_peer() { + #[tokio::test] + async fn it_should_allow_removing_an_existing_peer() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; - let old = swarm.remove(&peer); + let old = swarm.remove(&peer).await; assert_eq!(old, Some(Arc::new(peer))); assert_eq!(swarm.get(&peer.peer_addr), None); } - #[test] - fn it_should_allow_removing_a_non_existing_peer() { + #[tokio::test] + async fn it_should_allow_removing_a_non_existing_peer() { let mut swarm = Swarm::default(); let peer = PeerBuilder::default().build(); - assert_eq!(swarm.remove(&peer), None); + assert_eq!(swarm.remove(&peer).await, None); } - #[test] - fn it_should_allow_getting_all_peers_excluding_peers_with_a_given_address() { + #[tokio::test] + async fn it_should_allow_getting_all_peers_excluding_peers_with_a_given_address() { let mut swarm = Swarm::default(); let mut downloads_increased = false; @@ -351,19 +408,19 @@ mod tests { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.upsert_peer(peer1.into(), &mut downloads_increased); + swarm.upsert_peer(peer1.into(), &mut downloads_increased).await; let peer2 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) .build(); - swarm.upsert_peer(peer2.into(), &mut downloads_increased); + swarm.upsert_peer(peer2.into(), &mut downloads_increased).await; assert_eq!(swarm.peers_excluding(&peer2.peer_addr, None), [Arc::new(peer1)]); } - #[test] - fn it_should_remove_inactive_peers() { + #[tokio::test] + async fn it_should_remove_inactive_peers() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let one_second = DurationSinceUnixEpoch::new(1, 0); @@ -371,7 +428,7 @@ mod tests { // Insert the peer let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; // Remove peers not updated since one second after inserting the peer swarm.remove_inactive(last_update_time + one_second); @@ -379,8 +436,8 @@ mod tests { assert_eq!(swarm.len(), 0); } - #[test] - fn it_should_not_remove_active_peers() { + #[tokio::test] + async fn it_should_not_remove_active_peers() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let one_second = DurationSinceUnixEpoch::new(1, 0); @@ -388,7 +445,7 @@ mod tests { // Insert the peer let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; // Remove peers not updated since one second before inserting the peer. swarm.remove_inactive(last_update_time - one_second); @@ -407,23 +464,23 @@ mod tests { Swarm::default() } - fn not_empty_swarm() -> Swarm { + async fn not_empty_swarm() -> Swarm { let mut swarm = Swarm::default(); - swarm.upsert_peer(PeerBuilder::default().build().into(), &mut false); + swarm.upsert_peer(PeerBuilder::default().build().into(), &mut false).await; swarm } - fn not_empty_swarm_with_downloads() -> Swarm { + async fn not_empty_swarm_with_downloads() -> Swarm { let mut swarm = Swarm::default(); let mut peer = PeerBuilder::leecher().build(); let mut downloads_increased = false; - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; assert!(swarm.metadata().downloads() > 0); @@ -457,13 +514,13 @@ mod tests { assert!(empty_swarm().should_be_removed(&remove_peerless_torrents_policy())); } - #[test] - fn it_should_not_be_removed_is_the_swarm_is_not_empty() { - assert!(!not_empty_swarm().should_be_removed(&remove_peerless_torrents_policy())); + #[tokio::test] + async fn it_should_not_be_removed_is_the_swarm_is_not_empty() { + assert!(!not_empty_swarm().await.should_be_removed(&remove_peerless_torrents_policy())); } - #[test] - fn it_should_not_be_removed_even_if_the_swarm_is_empty_if_we_need_to_track_stats_for_downloads_and_there_has_been_downloads( + #[tokio::test] + async fn it_should_not_be_removed_even_if_the_swarm_is_empty_if_we_need_to_track_stats_for_downloads_and_there_has_been_downloads( ) { let policy = TrackerPolicy { remove_peerless_torrents: true, @@ -471,7 +528,7 @@ mod tests { ..Default::default() }; - assert!(!not_empty_swarm_with_downloads().should_be_removed(&policy)); + assert!(!not_empty_swarm_with_downloads().await.should_be_removed(&policy)); } } @@ -486,33 +543,35 @@ mod tests { assert!(!empty_swarm().should_be_removed(&don_not_remove_peerless_torrents_policy())); } - #[test] - fn it_should_not_be_removed_is_the_swarm_is_not_empty() { - assert!(!not_empty_swarm().should_be_removed(&don_not_remove_peerless_torrents_policy())); + #[tokio::test] + async fn it_should_not_be_removed_is_the_swarm_is_not_empty() { + assert!(!not_empty_swarm() + .await + .should_be_removed(&don_not_remove_peerless_torrents_policy())); } } } - #[test] - fn it_should_allow_inserting_two_identical_peers_except_for_the_socket_address() { + #[tokio::test] + async fn it_should_allow_inserting_two_identical_peers_except_for_the_socket_address() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let peer1 = PeerBuilder::default() .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.upsert_peer(peer1.into(), &mut downloads_increased); + swarm.upsert_peer(peer1.into(), &mut downloads_increased).await; let peer2 = PeerBuilder::default() .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) .build(); - swarm.upsert_peer(peer2.into(), &mut downloads_increased); + swarm.upsert_peer(peer2.into(), &mut downloads_increased).await; assert_eq!(swarm.len(), 2); } - #[test] - fn it_should_not_allow_inserting_two_peers_with_different_peer_id_but_the_same_socket_address() { + #[tokio::test] + async fn it_should_not_allow_inserting_two_peers_with_different_peer_id_but_the_same_socket_address() { let mut swarm = Swarm::default(); let mut downloads_increased = false; @@ -523,27 +582,27 @@ mod tests { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.upsert_peer(peer1.into(), &mut downloads_increased); + swarm.upsert_peer(peer1.into(), &mut downloads_increased).await; let peer2 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.upsert_peer(peer2.into(), &mut downloads_increased); + swarm.upsert_peer(peer2.into(), &mut downloads_increased).await; assert_eq!(swarm.len(), 1); } - #[test] - fn it_should_return_the_metadata() { + #[tokio::test] + async fn it_should_return_the_metadata() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased); - swarm.upsert_peer(leecher.into(), &mut downloads_increased); + swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; + swarm.upsert_peer(leecher.into(), &mut downloads_increased).await; assert_eq!( swarm.metadata(), @@ -555,32 +614,32 @@ mod tests { ); } - #[test] - fn it_should_return_the_number_of_seeders_in_the_list() { + #[tokio::test] + async fn it_should_return_the_number_of_seeders_in_the_list() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased); - swarm.upsert_peer(leecher.into(), &mut downloads_increased); + swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; + swarm.upsert_peer(leecher.into(), &mut downloads_increased).await; let (seeders, _leechers) = swarm.seeders_and_leechers(); assert_eq!(seeders, 1); } - #[test] - fn it_should_return_the_number_of_leechers_in_the_list() { + #[tokio::test] + async fn it_should_return_the_number_of_leechers_in_the_list() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased); - swarm.upsert_peer(leecher.into(), &mut downloads_increased); + swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; + swarm.upsert_peer(leecher.into(), &mut downloads_increased).await; let (_seeders, leechers) = swarm.seeders_and_leechers(); @@ -594,8 +653,8 @@ mod tests { use crate::swarm::Swarm; - #[test] - fn it_should_increase_the_number_of_leechers_if_the_new_peer_is_a_leecher_() { + #[tokio::test] + async fn it_should_increase_the_number_of_leechers_if_the_new_peer_is_a_leecher_() { let mut swarm = Swarm::default(); let mut downloads_increased = false; @@ -603,13 +662,13 @@ mod tests { let leecher = PeerBuilder::leecher().build(); - swarm.upsert_peer(leecher.into(), &mut downloads_increased); + swarm.upsert_peer(leecher.into(), &mut downloads_increased).await; assert_eq!(swarm.metadata().leechers(), leechers + 1); } - #[test] - fn it_should_increase_the_number_of_seeders_if_the_new_peer_is_a_seeder() { + #[tokio::test] + async fn it_should_increase_the_number_of_seeders_if_the_new_peer_is_a_seeder() { let mut swarm = Swarm::default(); let mut downloads_increased = false; @@ -617,13 +676,13 @@ mod tests { let seeder = PeerBuilder::seeder().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased); + swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; assert_eq!(swarm.metadata().seeders(), seeders + 1); } - #[test] - fn it_should_not_increasing_the_number_of_downloads_if_the_new_peer_has_completed_downloading_as_it_was_not_previously_known( + #[tokio::test] + async fn it_should_not_increasing_the_number_of_downloads_if_the_new_peer_has_completed_downloading_as_it_was_not_previously_known( ) { let mut swarm = Swarm::default(); let mut downloads_increased = false; @@ -632,7 +691,7 @@ mod tests { let seeder = PeerBuilder::seeder().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased); + swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; assert_eq!(swarm.metadata().downloads(), downloads); } @@ -643,34 +702,34 @@ mod tests { use crate::swarm::Swarm; - #[test] - fn it_should_decrease_the_number_of_leechers_if_the_removed_peer_was_a_leecher() { + #[tokio::test] + async fn it_should_decrease_the_number_of_leechers_if_the_removed_peer_was_a_leecher() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let leecher = PeerBuilder::leecher().build(); - swarm.upsert_peer(leecher.into(), &mut downloads_increased); + swarm.upsert_peer(leecher.into(), &mut downloads_increased).await; let leechers = swarm.metadata().leechers(); - swarm.remove(&leecher); + swarm.remove(&leecher).await; assert_eq!(swarm.metadata().leechers(), leechers - 1); } - #[test] - fn it_should_decrease_the_number_of_seeders_if_the_removed_peer_was_a_seeder() { + #[tokio::test] + async fn it_should_decrease_the_number_of_seeders_if_the_removed_peer_was_a_seeder() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased); + swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; let seeders = swarm.metadata().seeders(); - swarm.remove(&seeder); + swarm.remove(&seeder).await; assert_eq!(swarm.metadata().seeders(), seeders - 1); } @@ -683,14 +742,14 @@ mod tests { use crate::swarm::Swarm; - #[test] - fn it_should_decrease_the_number_of_leechers_when_a_removed_peer_is_a_leecher() { + #[tokio::test] + async fn it_should_decrease_the_number_of_leechers_when_a_removed_peer_is_a_leecher() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let leecher = PeerBuilder::leecher().build(); - swarm.upsert_peer(leecher.into(), &mut downloads_increased); + swarm.upsert_peer(leecher.into(), &mut downloads_increased).await; let leechers = swarm.metadata().leechers(); @@ -699,14 +758,14 @@ mod tests { assert_eq!(swarm.metadata().leechers(), leechers - 1); } - #[test] - fn it_should_decrease_the_number_of_seeders_when_the_removed_peer_is_a_seeder() { + #[tokio::test] + async fn it_should_decrease_the_number_of_seeders_when_the_removed_peer_is_a_seeder() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased); + swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; let seeders = swarm.metadata().seeders(); @@ -722,80 +781,80 @@ mod tests { use crate::swarm::Swarm; - #[test] - fn it_should_increase_seeders_and_decreasing_leechers_when_the_peer_changes_from_leecher_to_seeder_() { + #[tokio::test] + async fn it_should_increase_seeders_and_decreasing_leechers_when_the_peer_changes_from_leecher_to_seeder_() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let mut peer = PeerBuilder::leecher().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; let leechers = swarm.metadata().leechers(); let seeders = swarm.metadata().seeders(); peer.left = NumberOfBytes::new(0); // Convert to seeder - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; assert_eq!(swarm.metadata().seeders(), seeders + 1); assert_eq!(swarm.metadata().leechers(), leechers - 1); } - #[test] - fn it_should_increase_leechers_and_decreasing_seeders_when_the_peer_changes_from_seeder_to_leecher() { + #[tokio::test] + async fn it_should_increase_leechers_and_decreasing_seeders_when_the_peer_changes_from_seeder_to_leecher() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let mut peer = PeerBuilder::seeder().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; let leechers = swarm.metadata().leechers(); let seeders = swarm.metadata().seeders(); peer.left = NumberOfBytes::new(10); // Convert to leecher - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; assert_eq!(swarm.metadata().leechers(), leechers + 1); assert_eq!(swarm.metadata().seeders(), seeders - 1); } - #[test] - fn it_should_increase_the_number_of_downloads_when_the_peer_announces_completed_downloading() { + #[tokio::test] + async fn it_should_increase_the_number_of_downloads_when_the_peer_announces_completed_downloading() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let mut peer = PeerBuilder::leecher().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; let downloads = swarm.metadata().downloads(); peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; assert_eq!(swarm.metadata().downloads(), downloads + 1); } - #[test] - fn it_should_not_increasing_the_number_of_downloads_when_the_peer_announces_completed_downloading_twice_() { + #[tokio::test] + async fn it_should_not_increasing_the_number_of_downloads_when_the_peer_announces_completed_downloading_twice_() { let mut swarm = Swarm::default(); let mut downloads_increased = false; let mut peer = PeerBuilder::leecher().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; let downloads = swarm.metadata().downloads(); peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; - swarm.upsert_peer(peer.into(), &mut downloads_increased); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; assert_eq!(swarm.metadata().downloads(), downloads + 1); } diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index d92e1755a..277a85cc2 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -1,7 +1,8 @@ -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use crossbeam_skiplist::SkipMap; +use tokio::sync::Mutex; use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; @@ -48,6 +49,7 @@ impl Swarms { /// # Errors /// /// This function panics if the lock for the swarm handle cannot be acquired. + #[allow(clippy::await_holding_lock)] pub async fn handle_announcement( &self, info_hash: &InfoHash, @@ -57,7 +59,7 @@ impl Swarms { let swarm_handle = match self.swarms.get(info_hash) { None => { let new_swarm_handle = if let Some(number_of_downloads) = opt_persistent_torrent { - SwarmHandle::new(Swarm::new(number_of_downloads).into()) + SwarmHandle::new(Swarm::new(number_of_downloads, self.event_sender.clone()).into()) } else { SwarmHandle::default() }; @@ -78,9 +80,11 @@ impl Swarms { Some(existing_swarm_handle) => existing_swarm_handle, }; - let mut swarm = swarm_handle.value().lock()?; + let mut swarm = swarm_handle.value().lock().await; - Ok(swarm.handle_announcement(peer)) + let downloads_increased = swarm.handle_announcement(peer).await; + + Ok(downloads_increased) } /// Inserts a new swarm. Only used for testing purposes. @@ -162,11 +166,11 @@ impl Swarms { /// # Errors /// /// This function panics if the lock for the swarm handle cannot be acquired. - pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Result, Error> { + pub async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Result, Error> { match self.swarms.get(info_hash) { None => Ok(None), Some(swarm_handle) => { - let swarm = swarm_handle.value().lock()?; + let swarm = swarm_handle.value().lock().await; Ok(Some(swarm.metadata())) } } @@ -183,8 +187,8 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for the /// swarm handle. - pub fn get_swarm_metadata_or_default(&self, info_hash: &InfoHash) -> Result { - match self.get_swarm_metadata(info_hash) { + pub async fn get_swarm_metadata_or_default(&self, info_hash: &InfoHash) -> Result { + match self.get_swarm_metadata(info_hash).await { Ok(Some(swarm_metadata)) => Ok(swarm_metadata), Ok(None) => Ok(SwarmMetadata::zeroed()), Err(err) => Err(err), @@ -207,7 +211,7 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for the /// swarm handle. - pub fn get_peers_peers_excluding( + pub async fn get_peers_peers_excluding( &self, info_hash: &InfoHash, peer: &peer::Peer, @@ -216,7 +220,7 @@ impl Swarms { match self.get(info_hash) { None => Ok(vec![]), Some(swarm_handle) => { - let swarm = swarm_handle.lock()?; + let swarm = swarm_handle.lock().await; Ok(swarm.peers_excluding(&peer.peer_addr, Some(limit))) } } @@ -236,11 +240,11 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for the /// swarm handle. - pub fn get_swarm_peers(&self, info_hash: &InfoHash, limit: usize) -> Result>, Error> { + pub async fn get_swarm_peers(&self, info_hash: &InfoHash, limit: usize) -> Result>, Error> { match self.get(info_hash) { None => Ok(vec![]), Some(swarm_handle) => { - let swarm = swarm_handle.lock()?; + let swarm = swarm_handle.lock().await; Ok(swarm.peers(Some(limit))) } } @@ -255,7 +259,7 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for any /// swarm handle. - pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> Result { + pub async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> Result { tracing::info!( "Removing inactive peers since: {:?} ...", convert_from_timestamp_to_datetime_utc(current_cutoff) @@ -264,7 +268,7 @@ impl Swarms { let mut inactive_peers_removed = 0; for swarm_handle in &self.swarms { - let mut swarm = swarm_handle.value().lock()?; + let mut swarm = swarm_handle.value().lock().await; let removed = swarm.remove_inactive(current_cutoff); inactive_peers_removed += removed; } @@ -283,13 +287,13 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for any /// swarm handle. - pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> Result { + pub async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> Result { tracing::info!("Removing peerless torrents ..."); let mut peerless_torrents_removed = 0; for swarm_handle in &self.swarms { - let swarm = swarm_handle.value().lock()?; + let swarm = swarm_handle.value().lock().await; if swarm.meets_retaining_policy(policy) { continue; @@ -320,7 +324,7 @@ impl Swarms { continue; } - let entry = SwarmHandle::new(Swarm::new(*completed).into()); + let entry = SwarmHandle::new(Swarm::new(*completed, self.event_sender.clone()).into()); // Since SkipMap is lock-free the torrent could have been inserted // after checking if it exists. @@ -348,11 +352,11 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for any /// swarm handle. - pub fn get_aggregate_swarm_metadata(&self) -> Result { + pub async fn get_aggregate_swarm_metadata(&self) -> Result { let mut metrics = AggregateSwarmMetadata::default(); for swarm_handle in &self.swarms { - let swarm = swarm_handle.value().lock()?; + let swarm = swarm_handle.value().lock().await; let stats = swarm.metadata(); @@ -376,11 +380,11 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for any /// swarm handle. - pub fn count_peerless_torrents(&self) -> Result { + pub async fn count_peerless_torrents(&self) -> Result { let mut peerless_torrents = 0; for swarm_handle in &self.swarms { - let swarm = swarm_handle.value().lock()?; + let swarm = swarm_handle.value().lock().await; if swarm.is_peerless() { peerless_torrents += 1; @@ -400,11 +404,11 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for any /// swarm handle. - pub fn count_peers(&self) -> Result { + pub async fn count_peers(&self) -> Result { let mut peers = 0; for swarm_handle in &self.swarms { - let swarm = swarm_handle.value().lock()?; + let swarm = swarm_handle.value().lock().await; peers += swarm.len(); } @@ -424,16 +428,7 @@ impl Swarms { } #[derive(thiserror::Error, Debug, Clone)] -pub enum Error { - #[error("Can't acquire swarm lock")] - CannotAcquireSwarmLock, -} - -impl From>> for Error { - fn from(_error: std::sync::PoisonError>) -> Self { - Error::CannotAcquireSwarmLock - } -} +pub enum Error {} #[cfg(test)] mod tests { @@ -523,7 +518,7 @@ mod tests { swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); - let peers = swarms.get_swarm_peers(&info_hash, 74).unwrap(); + let peers = swarms.get_swarm_peers(&info_hash, 74).await.unwrap(); assert_eq!(peers, vec![Arc::new(peer)]); } @@ -532,7 +527,7 @@ mod tests { async fn it_should_return_an_empty_list_or_peers_for_a_non_existing_torrent() { let swarms = Arc::new(Swarms::default()); - let peers = swarms.get_swarm_peers(&sample_info_hash(), 74).unwrap(); + let peers = swarms.get_swarm_peers(&sample_info_hash(), 74).await.unwrap(); assert!(peers.is_empty()); } @@ -557,7 +552,7 @@ mod tests { swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); } - let peers = swarms.get_swarm_peers(&info_hash, 74).unwrap(); + let peers = swarms.get_swarm_peers(&info_hash, 74).await.unwrap(); assert_eq!(peers.len(), 74); } @@ -582,6 +577,7 @@ mod tests { let peers = swarms .get_peers_peers_excluding(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT) + .await .unwrap(); assert_eq!(peers, vec![]); @@ -598,6 +594,7 @@ mod tests { let peers = swarms .get_peers_peers_excluding(&info_hash, &peer, TORRENT_PEERS_LIMIT) + .await .unwrap(); assert_eq!(peers, vec![]); @@ -630,6 +627,7 @@ mod tests { let peers = swarms .get_peers_peers_excluding(&info_hash, &excluded_peer, TORRENT_PEERS_LIMIT) + .await .unwrap(); assert_eq!(peers.len(), 74); @@ -675,9 +673,14 @@ mod tests { // Cut off time is 1 second after the peer was updated swarms .remove_inactive_peers(peer.updated.add(Duration::from_secs(1))) + .await .unwrap(); - assert!(!swarms.get_swarm_peers(&info_hash, 74).unwrap().contains(&Arc::new(peer))); + assert!(!swarms + .get_swarm_peers(&info_hash, 74) + .await + .unwrap() + .contains(&Arc::new(peer))); } async fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { @@ -691,6 +694,7 @@ mod tests { // Remove the peer swarms .remove_inactive_peers(peer.updated.add(Duration::from_secs(1))) + .await .unwrap(); swarms @@ -707,7 +711,7 @@ mod tests { ..Default::default() }; - swarms.remove_peerless_torrents(&tracker_policy).unwrap(); + swarms.remove_peerless_torrents(&tracker_policy).await.unwrap(); assert!(swarms.get(&info_hash).is_none()); } @@ -721,7 +725,7 @@ mod tests { use crate::swarms::Swarms; use crate::tests::{sample_info_hash, sample_peer}; - use crate::{LockTrackedTorrent, SwarmHandle}; + use crate::{Swarm, SwarmHandle}; /// `TorrentEntry` data is not directly accessible. It's only /// accessible through the trait methods. We need this temporary @@ -733,19 +737,19 @@ mod tests { number_of_peers: usize, } + async fn torrent_entry_info(swarm_handle: SwarmHandle) -> TorrentEntryInfo { + let torrent_guard = swarm_handle.lock().await; + torrent_guard.clone().into() + } + #[allow(clippy::from_over_into)] - impl Into for SwarmHandle { + impl Into for Swarm { fn into(self) -> TorrentEntryInfo { - let torrent_guard = self.lock_or_panic(); - let torrent_entry_info = TorrentEntryInfo { - swarm_metadata: torrent_guard.metadata(), - peers: torrent_guard.peers(None).iter().map(|peer| *peer.clone()).collect(), - number_of_peers: torrent_guard.len(), + swarm_metadata: self.metadata(), + peers: self.peers(None).iter().map(|peer| *peer.clone()).collect(), + number_of_peers: self.len(), }; - - drop(torrent_guard); - torrent_entry_info } } @@ -759,7 +763,7 @@ mod tests { swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); - let torrent_entry = swarms.get(&info_hash).unwrap(); + let torrent_entry_info = torrent_entry_info(swarms.get(&info_hash).unwrap()).await; assert_eq!( TorrentEntryInfo { @@ -771,7 +775,7 @@ mod tests { peers: vec!(peer), number_of_peers: 1 }, - torrent_entry.into() + torrent_entry_info ); } @@ -780,7 +784,9 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::swarms::tests::the_swarm_repository::returning_torrent_entries::TorrentEntryInfo; + use crate::swarms::tests::the_swarm_repository::returning_torrent_entries::{ + torrent_entry_info, TorrentEntryInfo, + }; use crate::swarms::Swarms; use crate::tests::{sample_info_hash, sample_peer}; @@ -796,7 +802,7 @@ mod tests { assert_eq!(torrent_entries.len(), 1); - let torrent_entry = torrent_entries.first().unwrap().1.clone(); + let torrent_entry = torrent_entry_info(torrent_entries.first().unwrap().1.clone()).await; assert_eq!( TorrentEntryInfo { @@ -808,7 +814,7 @@ mod tests { peers: vec!(peer), number_of_peers: 1 }, - torrent_entry.into() + torrent_entry ); } @@ -818,7 +824,9 @@ mod tests { use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::swarms::tests::the_swarm_repository::returning_torrent_entries::TorrentEntryInfo; + use crate::swarms::tests::the_swarm_repository::returning_torrent_entries::{ + torrent_entry_info, TorrentEntryInfo, + }; use crate::swarms::Swarms; use crate::tests::{ sample_info_hash_alphabetically_ordered_after_sample_info_hash_one, sample_info_hash_one, @@ -844,7 +852,7 @@ mod tests { assert_eq!(torrent_entries.len(), 1); - let torrent_entry = torrent_entries.first().unwrap().1.clone(); + let torrent_entry_info = torrent_entry_info(torrent_entries.first().unwrap().1.clone()).await; assert_eq!( TorrentEntryInfo { @@ -856,7 +864,7 @@ mod tests { peers: vec!(peer_one), number_of_peers: 1 }, - torrent_entry.into() + torrent_entry_info ); } @@ -879,7 +887,7 @@ mod tests { assert_eq!(torrent_entries.len(), 1); - let torrent_entry = torrent_entries.first().unwrap().1.clone(); + let torrent_entry_info = torrent_entry_info(torrent_entries.first().unwrap().1.clone()).await; assert_eq!( TorrentEntryInfo { @@ -891,7 +899,7 @@ mod tests { peers: vec!(peer_two), number_of_peers: 1 }, - torrent_entry.into() + torrent_entry_info ); } @@ -934,7 +942,7 @@ mod tests { async fn it_should_get_empty_aggregate_swarm_metadata_when_there_are_no_torrents() { let swarms = Arc::new(Swarms::default()); - let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().await.unwrap(); assert_eq!( aggregate_swarm_metadata, @@ -956,7 +964,7 @@ mod tests { .await .unwrap(); - let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().await.unwrap(); assert_eq!( aggregate_swarm_metadata, @@ -978,7 +986,7 @@ mod tests { .await .unwrap(); - let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().await.unwrap(); assert_eq!( aggregate_swarm_metadata, @@ -1000,7 +1008,7 @@ mod tests { .await .unwrap(); - let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().await.unwrap(); assert_eq!( aggregate_swarm_metadata, @@ -1027,7 +1035,7 @@ mod tests { let result_a = start_time.elapsed(); let start_time = std::time::Instant::now(); - let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().unwrap(); + let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().await.unwrap(); let result_b = start_time.elapsed(); assert_eq!( @@ -1060,7 +1068,7 @@ mod tests { swarms.handle_announcement(&infohash, &leecher(), None).await.unwrap(); - let swarm_metadata = swarms.get_swarm_metadata_or_default(&infohash).unwrap(); + let swarm_metadata = swarms.get_swarm_metadata_or_default(&infohash).await.unwrap(); assert_eq!( swarm_metadata, @@ -1076,7 +1084,7 @@ mod tests { async fn it_should_return_zeroed_swarm_metadata_for_a_non_existing_torrent() { let swarms = Arc::new(Swarms::default()); - let swarm_metadata = swarms.get_swarm_metadata_or_default(&sample_info_hash()).unwrap(); + let swarm_metadata = swarms.get_swarm_metadata_or_default(&sample_info_hash()).await.unwrap(); assert_eq!(swarm_metadata, SwarmMetadata::zeroed()); } @@ -1103,7 +1111,7 @@ mod tests { swarms.import_persistent(&persistent_torrents); - let swarm_metadata = swarms.get_swarm_metadata_or_default(&infohash).unwrap(); + let swarm_metadata = swarms.get_swarm_metadata_or_default(&infohash).await.unwrap(); // Only the number of downloads is persisted. assert_eq!(swarm_metadata.downloaded, 1); diff --git a/packages/torrent-repository/tests/swarm/mod.rs b/packages/torrent-repository/tests/swarm/mod.rs index d529b0243..1f5d0b737 100644 --- a/packages/torrent-repository/tests/swarm/mod.rs +++ b/packages/torrent-repository/tests/swarm/mod.rs @@ -47,39 +47,39 @@ pub enum Makes { Three, } -fn make(swarm: &mut Swarm, makes: &Makes) -> Vec { +async fn make(swarm: &mut Swarm, makes: &Makes) -> Vec { match makes { Makes::Empty => vec![], Makes::Started => { let peer = a_started_peer(1); - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; vec![peer] } Makes::Completed => { let peer = a_completed_peer(2); - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; vec![peer] } Makes::Downloaded => { let mut peer = a_started_peer(3); - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; peer.event = AnnounceEvent::Completed; peer.left = NumberOfBytes::new(0); - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; vec![peer] } Makes::Three => { let peer_1 = a_started_peer(1); - swarm.handle_announcement(&peer_1); + swarm.handle_announcement(&peer_1).await; let peer_2 = a_completed_peer(2); - swarm.handle_announcement(&peer_2); + swarm.handle_announcement(&peer_2).await; let mut peer_3 = a_started_peer(3); - swarm.handle_announcement(&peer_3); + swarm.handle_announcement(&peer_3).await; peer_3.event = AnnounceEvent::Completed; peer_3.left = NumberOfBytes::new(0); - swarm.handle_announcement(&peer_3); + swarm.handle_announcement(&peer_3).await; vec![peer_1, peer_2, peer_3] } } @@ -89,7 +89,7 @@ fn make(swarm: &mut Swarm, makes: &Makes) -> Vec { #[case::empty(&Makes::Empty)] #[tokio::test] async fn it_should_be_empty_by_default(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - make(&mut swarm, makes); + make(&mut swarm, makes).await; assert_eq!(swarm.len(), 0); } @@ -106,7 +106,7 @@ async fn it_should_check_if_entry_should_be_retained_based_on_the_tracker_policy #[case] makes: &Makes, #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, ) { - make(&mut swarm, makes); + make(&mut swarm, makes).await; let has_peers = !swarm.is_empty(); let has_downloads = swarm.metadata().downloaded != 0; @@ -140,7 +140,7 @@ async fn it_should_check_if_entry_should_be_retained_based_on_the_tracker_policy #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_get_peers_for_torrent_entry(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - let peers = make(&mut swarm, makes); + let peers = make(&mut swarm, makes).await; let torrent_peers = swarm.peers(None); @@ -159,11 +159,11 @@ async fn it_should_get_peers_for_torrent_entry(#[values(swarm())] mut swarm: Swa #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_update_a_peer(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - make(&mut swarm, makes); + make(&mut swarm, makes).await; // Make and insert a new peer. let mut peer = a_started_peer(-1); - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; // Get the Inserted Peer by Id. let peers = swarm.peers(None); @@ -176,7 +176,7 @@ async fn it_should_update_a_peer(#[values(swarm())] mut swarm: Swarm, #[case] ma // Announce "Completed" torrent download event. peer.event = AnnounceEvent::Completed; - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; // Get the Updated Peer by Id. let peers = swarm.peers(None); @@ -198,11 +198,11 @@ async fn it_should_update_a_peer(#[values(swarm())] mut swarm: Swarm, #[case] ma async fn it_should_remove_a_peer_upon_stopped_announcement(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { use torrust_tracker_primitives::peer::ReadInfo as _; - make(&mut swarm, makes); + make(&mut swarm, makes).await; let mut peer = a_started_peer(-1); - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; // The started peer should be inserted. let peers = swarm.peers(None); @@ -215,7 +215,7 @@ async fn it_should_remove_a_peer_upon_stopped_announcement(#[values(swarm())] mu // Change peer to "Stopped" and insert. peer.event = AnnounceEvent::Stopped; - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; // It should be removed now. let peers = swarm.peers(None); @@ -237,7 +237,7 @@ async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloade #[values(swarm())] mut torrent: Swarm, #[case] makes: &Makes, ) { - make(&mut torrent, makes); + make(&mut torrent, makes).await; let downloaded = torrent.metadata().downloaded; let peers = torrent.peers(None); @@ -248,7 +248,7 @@ async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloade // Announce "Completed" torrent download event. peer.event = AnnounceEvent::Completed; - torrent.handle_announcement(&peer); + torrent.handle_announcement(&peer).await; let stats = torrent.metadata(); if is_already_completed { @@ -265,7 +265,7 @@ async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloade #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_update_a_peer_as_a_seeder(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - let peers = make(&mut swarm, makes); + let peers = make(&mut swarm, makes).await; let completed = u32::try_from(peers.iter().filter(|p| p.is_seeder()).count()).expect("it_should_not_be_so_many"); let peers = swarm.peers(None); @@ -275,7 +275,7 @@ async fn it_should_update_a_peer_as_a_seeder(#[values(swarm())] mut swarm: Swarm // Set Bytes Left to Zero peer.left = NumberOfBytes::new(0); - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; let stats = swarm.metadata(); if is_already_non_left { @@ -294,7 +294,7 @@ async fn it_should_update_a_peer_as_a_seeder(#[values(swarm())] mut swarm: Swarm #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_update_a_peer_as_incomplete(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - let peers = make(&mut swarm, makes); + let peers = make(&mut swarm, makes).await; let incomplete = u32::try_from(peers.iter().filter(|p| !p.is_seeder()).count()).expect("it should not be so many"); let peers = swarm.peers(None); @@ -304,7 +304,7 @@ async fn it_should_update_a_peer_as_incomplete(#[values(swarm())] mut swarm: Swa // Set Bytes Left to no Zero peer.left = NumberOfBytes::new(1); - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; let stats = swarm.metadata(); if completed_already { @@ -323,7 +323,7 @@ async fn it_should_update_a_peer_as_incomplete(#[values(swarm())] mut swarm: Swa #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_get_peers_excluding_the_client_socket(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - make(&mut swarm, makes); + make(&mut swarm, makes).await; let peers = swarm.peers(None); let mut peer = **peers.first().expect("there should be a peer"); @@ -338,7 +338,7 @@ async fn it_should_get_peers_excluding_the_client_socket(#[values(swarm())] mut // set the address to the socket. peer.peer_addr = socket; - swarm.handle_announcement(&peer); // Add peer + swarm.handle_announcement(&peer).await; // Add peer // It should not include the peer that has the same socket. assert!(!swarm.peers_excluding(&socket, None).contains(&peer.into())); @@ -352,12 +352,12 @@ async fn it_should_get_peers_excluding_the_client_socket(#[values(swarm())] mut #[case::three(&Makes::Three)] #[tokio::test] async fn it_should_limit_the_number_of_peers_returned(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - make(&mut swarm, makes); + make(&mut swarm, makes).await; // We add one more peer than the scrape limit for peer_number in 1..=74 + 1 { let peer = a_started_peer(peer_number); - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; } let peers = swarm.peers(Some(TORRENT_PEERS_LIMIT)); @@ -376,7 +376,7 @@ async fn it_should_remove_inactive_peers_beyond_cutoff(#[values(swarm())] mut sw const TIMEOUT: Duration = Duration::from_secs(120); const EXPIRE: Duration = Duration::from_secs(121); - let peers = make(&mut swarm, makes); + let peers = make(&mut swarm, makes).await; let mut peer = a_completed_peer(-1); @@ -385,7 +385,7 @@ async fn it_should_remove_inactive_peers_beyond_cutoff(#[values(swarm())] mut sw peer.updated = now.sub(EXPIRE); - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; assert_eq!(swarm.len(), peers.len() + 1); diff --git a/packages/torrent-repository/tests/swarms/mod.rs b/packages/torrent-repository/tests/swarms/mod.rs index 975457cca..d8ee354c8 100644 --- a/packages/torrent-repository/tests/swarms/mod.rs +++ b/packages/torrent-repository/tests/swarms/mod.rs @@ -3,13 +3,14 @@ use std::hash::{DefaultHasher, Hash, Hasher}; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; use bittorrent_primitives::info_hash::InfoHash; +use futures::future::join_all; use rstest::{fixture, rstest}; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::PersistentTorrents; use torrust_tracker_torrent_repository::swarm::Swarm; -use torrust_tracker_torrent_repository::{LockTrackedTorrent, Swarms}; +use torrust_tracker_torrent_repository::Swarms; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; @@ -31,49 +32,49 @@ fn default() -> Entries { } #[fixture] -fn started() -> Entries { +async fn started() -> Entries { let mut swarm = Swarm::default(); - swarm.handle_announcement(&a_started_peer(1)); + swarm.handle_announcement(&a_started_peer(1)).await; vec![(InfoHash::default(), swarm)] } #[fixture] -fn completed() -> Entries { +async fn completed() -> Entries { let mut swarm = Swarm::default(); - swarm.handle_announcement(&a_completed_peer(2)); + swarm.handle_announcement(&a_completed_peer(2)).await; vec![(InfoHash::default(), swarm)] } #[fixture] -fn downloaded() -> Entries { +async fn downloaded() -> Entries { let mut swarm = Swarm::default(); let mut peer = a_started_peer(3); - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; peer.event = AnnounceEvent::Completed; peer.left = NumberOfBytes::new(0); - swarm.handle_announcement(&peer); + swarm.handle_announcement(&peer).await; vec![(InfoHash::default(), swarm)] } #[fixture] -fn three() -> Entries { +async fn three() -> Entries { let mut started = Swarm::default(); let started_h = &mut DefaultHasher::default(); - started.handle_announcement(&a_started_peer(1)); + started.handle_announcement(&a_started_peer(1)).await; started.hash(started_h); let mut completed = Swarm::default(); let completed_h = &mut DefaultHasher::default(); - completed.handle_announcement(&a_completed_peer(2)); + completed.handle_announcement(&a_completed_peer(2)).await; completed.hash(completed_h); let mut downloaded = Swarm::default(); let downloaded_h = &mut DefaultHasher::default(); let mut downloaded_peer = a_started_peer(3); - downloaded.handle_announcement(&downloaded_peer); + downloaded.handle_announcement(&downloaded_peer).await; downloaded_peer.event = AnnounceEvent::Completed; downloaded_peer.left = NumberOfBytes::new(0); - downloaded.handle_announcement(&downloaded_peer); + downloaded.handle_announcement(&downloaded_peer).await; downloaded.hash(downloaded_h); vec![ @@ -84,12 +85,12 @@ fn three() -> Entries { } #[fixture] -fn many_out_of_order() -> Entries { +async fn many_out_of_order() -> Entries { let mut entries: HashSet<(InfoHash, Swarm)> = HashSet::default(); for i in 0..408 { let mut entry = Swarm::default(); - entry.handle_announcement(&a_started_peer(i)); + entry.handle_announcement(&a_started_peer(i)).await; entries.insert((InfoHash::from(&i), entry)); } @@ -99,12 +100,12 @@ fn many_out_of_order() -> Entries { } #[fixture] -fn many_hashed_in_order() -> Entries { +async fn many_hashed_in_order() -> Entries { let mut entries: BTreeMap = BTreeMap::default(); for i in 0..408 { let mut entry = Swarm::default(); - entry.handle_announcement(&a_started_peer(i)); + entry.handle_announcement(&a_started_peer(i)).await; let hash: &mut DefaultHasher = &mut DefaultHasher::default(); hash.write_i32(i); @@ -191,21 +192,18 @@ fn policy_remove_persist() -> TrackerPolicy { #[rstest] #[case::empty(empty())] #[case::default(default())] -#[case::started(started())] -#[case::completed(completed())] -#[case::downloaded(downloaded())] -#[case::three(three())] -#[case::out_of_order(many_out_of_order())] -#[case::in_order(many_hashed_in_order())] +#[case::started(started().await)] +#[case::completed(completed().await)] +#[case::downloaded(downloaded().await)] +#[case::three(three().await)] +#[case::out_of_order(many_out_of_order().await)] +#[case::in_order(many_hashed_in_order().await)] #[tokio::test] async fn it_should_get_a_torrent_entry(#[values(swarms())] repo: Swarms, #[case] entries: Entries) { make(&repo, &entries); if let Some((info_hash, swarm)) = entries.first() { - assert_eq!( - Some(repo.get(info_hash).unwrap().lock_or_panic().clone()), - Some(swarm.clone()) - ); + assert_eq!(Some(repo.get(info_hash).unwrap().lock().await.clone()), Some(swarm.clone())); } else { assert!(repo.get(&InfoHash::default()).is_none()); } @@ -214,23 +212,23 @@ async fn it_should_get_a_torrent_entry(#[values(swarms())] repo: Swarms, #[case] #[rstest] #[case::empty(empty())] #[case::default(default())] -#[case::started(started())] -#[case::completed(completed())] -#[case::downloaded(downloaded())] -#[case::three(three())] -#[case::out_of_order(many_out_of_order())] -#[case::in_order(many_hashed_in_order())] +#[case::started(started().await)] +#[case::completed(completed().await)] +#[case::downloaded(downloaded().await)] +#[case::three(three().await)] +#[case::out_of_order(many_out_of_order().await)] +#[case::in_order(many_hashed_in_order().await)] #[tokio::test] async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( #[values(swarms())] repo: Swarms, #[case] entries: Entries, - many_out_of_order: Entries, + #[future] many_out_of_order: Entries, ) { make(&repo, &entries); let entries_a = repo.get_paginated(None).iter().map(|(i, _)| *i).collect::>(); - make(&repo, &many_out_of_order); + make(&repo, &many_out_of_order.await); let entries_b = repo.get_paginated(None).iter().map(|(i, _)| *i).collect::>(); @@ -247,12 +245,12 @@ async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( #[rstest] #[case::empty(empty())] #[case::default(default())] -#[case::started(started())] -#[case::completed(completed())] -#[case::downloaded(downloaded())] -#[case::three(three())] -#[case::out_of_order(many_out_of_order())] -#[case::in_order(many_hashed_in_order())] +#[case::started(started().await)] +#[case::completed(completed().await)] +#[case::downloaded(downloaded().await)] +#[case::three(three().await)] +#[case::out_of_order(many_out_of_order().await)] +#[case::in_order(many_hashed_in_order().await)] #[tokio::test] async fn it_should_get_paginated( #[values(swarms())] repo: Swarms, @@ -267,11 +265,15 @@ async fn it_should_get_paginated( match paginated { // it should return empty if limit is zero. Pagination { limit: 0, .. } => { - let swarms: Vec<(InfoHash, Swarm)> = repo - .get_paginated(Some(&paginated)) - .iter() - .map(|(i, swarm_handle)| (*i, swarm_handle.lock_or_panic().clone())) - .collect(); + let page = repo.get_paginated(Some(&paginated)); + + let futures = page.iter().map(|(i, swarm_handle)| { + let i = *i; + let swarm_handle = swarm_handle.clone(); + async move { (i, swarm_handle.lock().await.clone()) } + }); + + let swarms: Vec<(InfoHash, Swarm)> = join_all(futures).await; assert_eq!(swarms, vec![]); } @@ -287,7 +289,7 @@ async fn it_should_get_paginated( } } - // it should return the only the second entry if both the limit and the offset are one. + // it should return only the second entry if both the limit and the offset are one. Pagination { limit: 1, offset: 1 } => { if info_hashes.len() > 1 { let page = repo.get_paginated(Some(&paginated)); @@ -295,7 +297,7 @@ async fn it_should_get_paginated( assert_eq!(page[0].0, info_hashes[1]); } } - // the other cases are not yet tested. + _ => {} } } @@ -303,12 +305,12 @@ async fn it_should_get_paginated( #[rstest] #[case::empty(empty())] #[case::default(default())] -#[case::started(started())] -#[case::completed(completed())] -#[case::downloaded(downloaded())] -#[case::three(three())] -#[case::out_of_order(many_out_of_order())] -#[case::in_order(many_hashed_in_order())] +#[case::started(started().await)] +#[case::completed(completed().await)] +#[case::downloaded(downloaded().await)] +#[case::three(three().await)] +#[case::out_of_order(many_out_of_order().await)] +#[case::in_order(many_hashed_in_order().await)] #[tokio::test] async fn it_should_get_metrics(#[values(swarms())] swarms: Swarms, #[case] entries: Entries) { use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; @@ -326,18 +328,18 @@ async fn it_should_get_metrics(#[values(swarms())] swarms: Swarms, #[case] entri metrics.total_downloaded += u64::from(stats.downloaded); } - assert_eq!(swarms.get_aggregate_swarm_metadata().unwrap(), metrics); + assert_eq!(swarms.get_aggregate_swarm_metadata().await.unwrap(), metrics); } #[rstest] #[case::empty(empty())] #[case::default(default())] -#[case::started(started())] -#[case::completed(completed())] -#[case::downloaded(downloaded())] -#[case::three(three())] -#[case::out_of_order(many_out_of_order())] -#[case::in_order(many_hashed_in_order())] +#[case::started(started().await)] +#[case::completed(completed().await)] +#[case::downloaded(downloaded().await)] +#[case::three(three().await)] +#[case::out_of_order(many_out_of_order().await)] +#[case::in_order(many_hashed_in_order().await)] #[tokio::test] async fn it_should_import_persistent_torrents( #[values(swarms())] swarms: Swarms, @@ -346,12 +348,15 @@ async fn it_should_import_persistent_torrents( ) { make(&swarms, &entries); - let mut downloaded = swarms.get_aggregate_swarm_metadata().unwrap().total_downloaded; + let mut downloaded = swarms.get_aggregate_swarm_metadata().await.unwrap().total_downloaded; persistent_torrents.iter().for_each(|(_, d)| downloaded += u64::from(*d)); swarms.import_persistent(&persistent_torrents); - assert_eq!(swarms.get_aggregate_swarm_metadata().unwrap().total_downloaded, downloaded); + assert_eq!( + swarms.get_aggregate_swarm_metadata().await.unwrap().total_downloaded, + downloaded + ); for (entry, _) in persistent_torrents { assert!(swarms.get(&entry).is_some()); @@ -361,23 +366,23 @@ async fn it_should_import_persistent_torrents( #[rstest] #[case::empty(empty())] #[case::default(default())] -#[case::started(started())] -#[case::completed(completed())] -#[case::downloaded(downloaded())] -#[case::three(three())] -#[case::out_of_order(many_out_of_order())] -#[case::in_order(many_hashed_in_order())] +#[case::started(started().await)] +#[case::completed(completed().await)] +#[case::downloaded(downloaded().await)] +#[case::three(three().await)] +#[case::out_of_order(many_out_of_order().await)] +#[case::in_order(many_hashed_in_order().await)] #[tokio::test] async fn it_should_remove_an_entry(#[values(swarms())] swarms: Swarms, #[case] entries: Entries) { make(&swarms, &entries); for (info_hash, torrent) in entries { assert_eq!( - Some(swarms.get(&info_hash).unwrap().lock_or_panic().clone()), + Some(swarms.get(&info_hash).unwrap().lock().await.clone()), Some(torrent.clone()) ); assert_eq!( - Some(swarms.remove(&info_hash).await.unwrap().lock_or_panic().clone()), + Some(swarms.remove(&info_hash).await.unwrap().lock().await.clone()), Some(torrent) ); @@ -385,18 +390,18 @@ async fn it_should_remove_an_entry(#[values(swarms())] swarms: Swarms, #[case] e assert!(swarms.remove(&info_hash).await.is_none()); } - assert_eq!(swarms.get_aggregate_swarm_metadata().unwrap().total_torrents, 0); + assert_eq!(swarms.get_aggregate_swarm_metadata().await.unwrap().total_torrents, 0); } #[rstest] #[case::empty(empty())] #[case::default(default())] -#[case::started(started())] -#[case::completed(completed())] -#[case::downloaded(downloaded())] -#[case::three(three())] -#[case::out_of_order(many_out_of_order())] -#[case::in_order(many_hashed_in_order())] +#[case::started(started().await)] +#[case::completed(completed().await)] +#[case::downloaded(downloaded().await)] +#[case::three(three().await)] +#[case::out_of_order(many_out_of_order().await)] +#[case::in_order(many_hashed_in_order().await)] #[tokio::test] async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[case] entries: Entries) { use std::ops::Sub as _; @@ -437,7 +442,7 @@ async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[c { swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); assert_eq!( - swarms.get_aggregate_swarm_metadata().unwrap().total_torrents, + swarms.get_aggregate_swarm_metadata().await.unwrap().total_torrents, entries.len() as u64 + 1 ); } @@ -446,7 +451,7 @@ async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[c // and verify the swarm metadata was updated. { swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); - let stats = swarms.get_swarm_metadata(&info_hash).unwrap(); + let stats = swarms.get_swarm_metadata(&info_hash).await.unwrap(); assert_eq!( stats, Some(SwarmMetadata { @@ -460,7 +465,7 @@ async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[c // Verify that this new peer was inserted into the repository. { let lock_tracked_torrent = swarms.get(&info_hash).expect("it_should_get_some"); - let entry = lock_tracked_torrent.lock_or_panic(); + let entry = lock_tracked_torrent.lock().await; assert!(entry.peers(None).contains(&peer.into())); } @@ -468,13 +473,14 @@ async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[c { swarms .remove_inactive_peers(CurrentClock::now_sub(&TIMEOUT).expect("it should get a time passed")) + .await .unwrap(); } // Verify that the this peer was removed from the repository. { let lock_tracked_torrent = swarms.get(&info_hash).expect("it_should_get_some"); - let entry = lock_tracked_torrent.lock_or_panic(); + let entry = lock_tracked_torrent.lock().await; assert!(!entry.peers(None).contains(&peer.into())); } } @@ -482,12 +488,12 @@ async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[c #[rstest] #[case::empty(empty())] #[case::default(default())] -#[case::started(started())] -#[case::completed(completed())] -#[case::downloaded(downloaded())] -#[case::three(three())] -#[case::out_of_order(many_out_of_order())] -#[case::in_order(many_hashed_in_order())] +#[case::started(started().await)] +#[case::completed(completed().await)] +#[case::downloaded(downloaded().await)] +#[case::three(three().await)] +#[case::out_of_order(many_out_of_order().await)] +#[case::in_order(many_hashed_in_order().await)] #[tokio::test] async fn it_should_remove_peerless_torrents( #[values(swarms())] swarms: Swarms, @@ -496,13 +502,17 @@ async fn it_should_remove_peerless_torrents( ) { make(&swarms, &entries); - swarms.remove_peerless_torrents(&policy).unwrap(); + swarms.remove_peerless_torrents(&policy).await.unwrap(); + + let paginated = swarms.get_paginated(None); // ← store the result in a named variable + + let futures = paginated.iter().map(|(i, swarm_handle)| { + let i = *i; + let swarm_handle = swarm_handle.clone(); + async move { (i, swarm_handle.lock().await.clone()) } + }); - let torrents: Vec<(InfoHash, Swarm)> = swarms - .get_paginated(None) - .iter() - .map(|(i, lock_tracked_torrent)| (*i, lock_tracked_torrent.lock_or_panic().clone())) - .collect(); + let torrents: Vec<(InfoHash, Swarm)> = join_all(futures).await; for (_, entry) in torrents { assert!(entry.meets_retaining_policy(&policy)); diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 00d42174a..a2e8db743 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -180,16 +180,20 @@ impl AnnounceHandler { self.db_torrent_repository.increase_number_of_downloads(info_hash)?; } - Ok(self.build_announce_data(info_hash, peer, peers_wanted)) + Ok(self.build_announce_data(info_hash, peer, peers_wanted).await) } /// Builds the announce data for the peer making the request. - fn build_announce_data(&self, info_hash: &InfoHash, peer: &peer::Peer, peers_wanted: &PeersWanted) -> AnnounceData { + async fn build_announce_data(&self, info_hash: &InfoHash, peer: &peer::Peer, peers_wanted: &PeersWanted) -> AnnounceData { let peers = self .in_memory_torrent_repository - .get_peers_for(info_hash, peer, peers_wanted.limit()); + .get_peers_for(info_hash, peer, peers_wanted.limit()) + .await; - let swarm_metadata = self.in_memory_torrent_repository.get_swarm_metadata_or_default(info_hash); + let swarm_metadata = self + .in_memory_torrent_repository + .get_swarm_metadata_or_default(info_hash) + .await; AnnounceData { peers, @@ -595,7 +599,7 @@ mod tests { use aquatic_udp_protocol::AnnounceEvent; use torrust_tracker_test_helpers::configuration; - use torrust_tracker_torrent_repository::{LockTrackedTorrent, Swarms}; + use torrust_tracker_torrent_repository::Swarms; use crate::announce_handler::tests::the_announce_handler::peer_ip; use crate::announce_handler::{AnnounceHandler, PeersWanted}; @@ -659,10 +663,10 @@ mod tests { .expect("it should be able to get entry"); // It persists the number of completed peers. - assert_eq!(torrent_entry.lock_or_panic().metadata().downloaded, 1); + assert_eq!(torrent_entry.lock().await.metadata().downloaded, 1); // It does not persist the peers - assert!(torrent_entry.lock_or_panic().is_empty()); + assert!(torrent_entry.lock().await.is_empty()); } } diff --git a/packages/tracker-core/src/scrape_handler.rs b/packages/tracker-core/src/scrape_handler.rs index 5d78c7d90..443d989a6 100644 --- a/packages/tracker-core/src/scrape_handler.rs +++ b/packages/tracker-core/src/scrape_handler.rs @@ -112,7 +112,11 @@ impl ScrapeHandler { for info_hash in info_hashes { let swarm_metadata = match self.whitelist_authorization.authorize(info_hash).await { - Ok(()) => self.in_memory_torrent_repository.get_swarm_metadata_or_default(info_hash), + Ok(()) => { + self.in_memory_torrent_repository + .get_swarm_metadata_or_default(info_hash) + .await + } Err(_) => SwarmMetadata::zeroed(), }; scrape_data.add_file(info_hash, swarm_metadata); diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index dec52daac..bc193bd4f 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -90,35 +90,36 @@ impl TorrentsManager { /// 2. If the tracker is configured to remove peerless torrents /// (`remove_peerless_torrents` is set), it removes entire torrent /// entries that have no active peers. - pub fn cleanup_torrents(&self) { - self.log_aggregate_swarm_metadata(); + pub async fn cleanup_torrents(&self) { + self.log_aggregate_swarm_metadata().await; - self.remove_inactive_peers(); + self.remove_inactive_peers().await; - self.log_aggregate_swarm_metadata(); + self.log_aggregate_swarm_metadata().await; - self.remove_peerless_torrents(); + self.remove_peerless_torrents().await; - self.log_aggregate_swarm_metadata(); + self.log_aggregate_swarm_metadata().await; } - fn remove_inactive_peers(&self) { + async fn remove_inactive_peers(&self) { let current_cutoff = CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout))) .unwrap_or_default(); - self.in_memory_torrent_repository.remove_inactive_peers(current_cutoff); + self.in_memory_torrent_repository.remove_inactive_peers(current_cutoff).await; } - fn remove_peerless_torrents(&self) { + async fn remove_peerless_torrents(&self) { if self.config.tracker_policy.remove_peerless_torrents { self.in_memory_torrent_repository - .remove_peerless_torrents(&self.config.tracker_policy); + .remove_peerless_torrents(&self.config.tracker_policy) + .await; } } - fn log_aggregate_swarm_metadata(&self) { + async fn log_aggregate_swarm_metadata(&self) { // Pre-calculated data - let aggregate_swarm_metadata = self.in_memory_torrent_repository.get_aggregate_swarm_metadata(); + let aggregate_swarm_metadata = self.in_memory_torrent_repository.get_aggregate_swarm_metadata().await; tracing::info!(name: "pre_calculated_aggregate_swarm_metadata", torrents = aggregate_swarm_metadata.total_torrents, @@ -128,8 +129,8 @@ impl TorrentsManager { ); // Hot data (iterating over data structures) - let peerless_torrents = self.in_memory_torrent_repository.count_peerless_torrents(); - let peers = self.in_memory_torrent_repository.count_peers(); + let peerless_torrents = self.in_memory_torrent_repository.count_peerless_torrents().await; + let peers = self.in_memory_torrent_repository.count_peers().await; tracing::info!(name: "hot_aggregate_swarm_metadata", peerless_torrents = peerless_torrents, @@ -144,7 +145,7 @@ mod tests { use std::sync::Arc; use torrust_tracker_configuration::Core; - use torrust_tracker_torrent_repository::{LockTrackedTorrent, Swarms}; + use torrust_tracker_torrent_repository::Swarms; use super::{DatabasePersistentTorrentRepository, TorrentsManager}; use crate::databases::setup::initialize_database; @@ -184,8 +185,8 @@ mod tests { ) } - #[test] - fn it_should_load_the_numbers_of_downloads_for_all_torrents_from_the_database() { + #[tokio::test] + async fn it_should_load_the_numbers_of_downloads_for_all_torrents_from_the_database() { let (torrents_manager, services) = initialize_torrents_manager(); let infohash = sample_info_hash(); @@ -199,7 +200,8 @@ mod tests { .in_memory_torrent_repository .get(&infohash) .unwrap() - .lock_or_panic() + .lock() + .await .metadata() .downloaded, 1 @@ -242,7 +244,7 @@ mod tests { )) .unwrap(); - torrents_manager.cleanup_torrents(); + torrents_manager.cleanup_torrents().await; assert!(services.in_memory_torrent_repository.get(&infohash).is_none()); } @@ -254,7 +256,9 @@ mod tests { let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(infohash, &peer, None).await; // Remove the peer. The torrent is now peerless. - in_memory_torrent_repository.remove_inactive_peers(peer.updated.add(Duration::from_secs(1))); + in_memory_torrent_repository + .remove_inactive_peers(peer.updated.add(Duration::from_secs(1))) + .await; } #[tokio::test] @@ -268,7 +272,7 @@ mod tests { add_a_peerless_torrent(&infohash, &services.in_memory_torrent_repository).await; - torrents_manager.cleanup_torrents(); + torrents_manager.cleanup_torrents().await; assert!(services.in_memory_torrent_repository.get(&infohash).is_none()); } @@ -284,7 +288,7 @@ mod tests { add_a_peerless_torrent(&infohash, &services.in_memory_torrent_repository).await; - torrents_manager.cleanup_torrents(); + torrents_manager.cleanup_torrents().await; assert!(services.in_memory_torrent_repository.get(&infohash).is_some()); } diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 37d9d3f5c..311480306 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -93,9 +93,10 @@ impl InMemoryTorrentRepository { /// # Panics /// /// This function panics if the underling swarms return an error. - pub(crate) fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { + pub(crate) async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) { self.swarms .remove_inactive_peers(current_cutoff) + .await .expect("Failed to remove inactive peers from swarms"); } @@ -112,9 +113,10 @@ impl InMemoryTorrentRepository { /// # Panics /// /// This function panics if the underling swarms return an error. - pub(crate) fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { + pub(crate) async fn remove_peerless_torrents(&self, policy: &TrackerPolicy) { self.swarms .remove_peerless_torrents(policy) + .await .expect("Failed to remove peerless torrents from swarms"); } @@ -168,9 +170,10 @@ impl InMemoryTorrentRepository { /// /// This function panics if the underling swarms return an error.s #[must_use] - pub(crate) fn get_swarm_metadata_or_default(&self, info_hash: &InfoHash) -> SwarmMetadata { + pub(crate) async fn get_swarm_metadata_or_default(&self, info_hash: &InfoHash) -> SwarmMetadata { self.swarms .get_swarm_metadata_or_default(info_hash) + .await .expect("Failed to get swarm metadata") } @@ -196,9 +199,10 @@ impl InMemoryTorrentRepository { /// /// This function panics if the underling swarms return an error. #[must_use] - pub(crate) fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { + pub(crate) async fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec> { self.swarms .get_peers_peers_excluding(info_hash, peer, max(limit, TORRENT_PEERS_LIMIT)) + .await .expect("Failed to get other peers in swarm") } @@ -220,10 +224,11 @@ impl InMemoryTorrentRepository { /// /// This function panics if the underling swarms return an error. #[must_use] - pub fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { + pub async fn get_torrent_peers(&self, info_hash: &InfoHash) -> Vec> { // todo: pass the limit as an argument like `get_peers_for` self.swarms .get_swarm_peers(info_hash, TORRENT_PEERS_LIMIT) + .await .expect("Failed to get other peers in swarm") } @@ -241,9 +246,10 @@ impl InMemoryTorrentRepository { /// /// This function panics if the underling swarms return an error. #[must_use] - pub fn get_aggregate_swarm_metadata(&self) -> AggregateSwarmMetadata { + pub async fn get_aggregate_swarm_metadata(&self) -> AggregateSwarmMetadata { self.swarms .get_aggregate_swarm_metadata() + .await .expect("Failed to get aggregate swarm metadata") } @@ -253,9 +259,10 @@ impl InMemoryTorrentRepository { /// /// This function panics if the underling swarms return an error. #[must_use] - pub fn count_peerless_torrents(&self) -> usize { + pub async fn count_peerless_torrents(&self) -> usize { self.swarms .count_peerless_torrents() + .await .expect("Failed to count peerless torrents") } @@ -265,8 +272,8 @@ impl InMemoryTorrentRepository { /// /// This function panics if the underling swarms return an error. #[must_use] - pub fn count_peers(&self) -> usize { - self.swarms.count_peers().expect("Failed to count peers") + pub async fn count_peers(&self) -> usize { + self.swarms.count_peers().await.expect("Failed to count peers") } /// Imports persistent torrent data into the in-memory repository. diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index 14a4f58f5..97694a80f 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -17,7 +17,6 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::peer; -use torrust_tracker_torrent_repository::LockTrackedTorrent; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -94,14 +93,17 @@ pub struct BasicInfo { /// /// This function panics if the lock for the torrent entry cannot be obtained. #[must_use] -pub fn get_torrent_info(in_memory_torrent_repository: &Arc, info_hash: &InfoHash) -> Option { +pub async fn get_torrent_info( + in_memory_torrent_repository: &Arc, + info_hash: &InfoHash, +) -> Option { let torrent_entry_option = in_memory_torrent_repository.get(info_hash); let torrent_entry = torrent_entry_option?; - let stats = torrent_entry.lock_or_panic().metadata(); + let stats = torrent_entry.lock().await.metadata(); - let peers = torrent_entry.lock_or_panic().peers(None); + let peers = torrent_entry.lock().await.peers(None); let peers = Some(peers.iter().map(|peer| (**peer)).collect()); @@ -136,14 +138,14 @@ pub fn get_torrent_info(in_memory_torrent_repository: &Arc, pagination: Option<&Pagination>, ) -> Vec { let mut basic_infos: Vec = vec![]; for (info_hash, torrent_entry) in in_memory_torrent_repository.get_paginated(pagination) { - let stats = torrent_entry.lock_or_panic().metadata(); + let stats = torrent_entry.lock().await.metadata(); basic_infos.push(BasicInfo { info_hash, @@ -178,19 +180,21 @@ pub fn get_torrents_page( /// /// This function panics if the lock for the torrent entry cannot be obtained. #[must_use] -pub fn get_torrents(in_memory_torrent_repository: &Arc, info_hashes: &[InfoHash]) -> Vec { +pub async fn get_torrents( + in_memory_torrent_repository: &Arc, + info_hashes: &[InfoHash], +) -> Vec { let mut basic_infos: Vec = vec![]; for info_hash in info_hashes { - if let Some(stats) = in_memory_torrent_repository - .get(info_hash) - .map(|torrent_entry| torrent_entry.lock_or_panic().metadata()) - { + if let Some(torrent_entry) = in_memory_torrent_repository.get(info_hash) { + let metadata = torrent_entry.lock().await.metadata(); + basic_infos.push(BasicInfo { info_hash: *info_hash, - seeders: u64::from(stats.complete), - completed: u64::from(stats.downloaded), - leechers: u64::from(stats.incomplete), + seeders: u64::from(metadata.complete), + completed: u64::from(metadata.downloaded), + leechers: u64::from(metadata.incomplete), }); } } @@ -235,7 +239,8 @@ mod tests { let torrent_info = get_torrent_info( &in_memory_torrent_repository, &InfoHash::from_str("0b3aea4adc213ce32295be85d3883a63bca25446").unwrap(), // DevSkim: ignore DS173237 - ); + ) + .await; assert!(torrent_info.is_none()); } @@ -250,7 +255,7 @@ mod tests { .upsert_peer(&info_hash, &sample_peer(), None) .await; - let torrent_info = get_torrent_info(&in_memory_torrent_repository, &info_hash).unwrap(); + let torrent_info = get_torrent_info(&in_memory_torrent_repository, &info_hash).await.unwrap(); assert_eq!( torrent_info, @@ -280,7 +285,7 @@ mod tests { async fn it_should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())).await; assert_eq!(torrents, vec![]); } @@ -296,7 +301,7 @@ mod tests { .upsert_peer(&info_hash, &sample_peer(), None) .await; - let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())).await; assert_eq!( torrents, @@ -329,7 +334,7 @@ mod tests { let offset = 0; let limit = 1; - let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::new(offset, limit))); + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::new(offset, limit))).await; assert_eq!(torrents.len(), 1); } @@ -354,7 +359,7 @@ mod tests { let offset = 1; let limit = 4000; - let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::new(offset, limit))); + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::new(offset, limit))).await; assert_eq!(torrents.len(), 1); assert_eq!( @@ -384,7 +389,7 @@ mod tests { .upsert_peer(&info_hash2, &sample_peer(), None) .await; - let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())); + let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())).await; assert_eq!( torrents, @@ -419,7 +424,7 @@ mod tests { async fn it_should_return_an_empty_list_if_none_of_the_requested_torrents_is_found() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let torrent_info = get_torrents(&in_memory_torrent_repository, &[sample_info_hash()]); + let torrent_info = get_torrents(&in_memory_torrent_repository, &[sample_info_hash()]).await; assert!(torrent_info.is_empty()); } @@ -434,7 +439,7 @@ mod tests { .upsert_peer(&info_hash, &sample_peer(), None) .await; - let torrent_info = get_torrents(&in_memory_torrent_repository, &[info_hash]); + let torrent_info = get_torrents(&in_memory_torrent_repository, &[info_hash]).await; assert_eq!( torrent_info, diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index c76f02040..20ba2ea7f 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -63,7 +63,7 @@ pub async fn get_metrics( in_memory_torrent_repository: Arc, stats_repository: Arc, ) -> TrackerMetrics { - let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata(); + let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; let stats = stats_repository.get_stats().await; TrackerMetrics { diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index ba0721289..86e7888f2 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -254,7 +254,8 @@ mod tests { let peers = core_tracker_services .in_memory_torrent_repository - .get_torrent_peers(&info_hash.0.into()); + .get_torrent_peers(&info_hash.0.into()) + .await; let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) @@ -348,7 +349,8 @@ mod tests { let peers = core_tracker_services .in_memory_torrent_repository - .get_torrent_peers(&info_hash.0.into()); + .get_torrent_peers(&info_hash.0.into()) + .await; assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V4(remote_client_ip), client_port)); } @@ -505,7 +507,8 @@ mod tests { let peers = core_tracker_services .in_memory_torrent_repository - .get_torrent_peers(&info_hash.0.into()); + .get_torrent_peers(&info_hash.0.into()) + .await; let external_ip_in_tracker_configuration = core_tracker_services.core_config.net.external_ip.unwrap(); @@ -587,7 +590,8 @@ mod tests { let peers = core_tracker_services .in_memory_torrent_repository - .get_torrent_peers(&info_hash.0.into()); + .get_torrent_peers(&info_hash.0.into()) + .await; let expected_peer = TorrentPeerBuilder::new() .with_peer_id(peer_id) @@ -684,7 +688,8 @@ mod tests { let peers = core_tracker_services .in_memory_torrent_repository - .get_torrent_peers(&info_hash.0.into()); + .get_torrent_peers(&info_hash.0.into()) + .await; // When using IPv6 the tracker converts the remote client ip into a IPv4 address assert_eq!(peers[0].peer_addr, SocketAddr::new(IpAddr::V6(remote_client_ip), client_port)); @@ -940,7 +945,7 @@ mod tests { .await .unwrap(); - let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()); + let peers = in_memory_torrent_repository.get_torrent_peers(&info_hash.0.into()).await; let external_ip_in_tracker_configuration = core_config.net.external_ip.unwrap(); diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index a2215067b..c8b24a744 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -66,7 +66,7 @@ pub async fn get_metrics( ban_service: Arc>, stats_repository: Arc, ) -> TrackerMetrics { - let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata(); + let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; let stats = stats_repository.get_stats().await; let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index 0107b5370..8a3a71a44 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -45,7 +45,7 @@ pub fn start_job(config: &Core, torrents_manager: &Arc) -> Join if let Some(torrents_manager) = weak_torrents_manager.upgrade() { let start_time = Utc::now().time(); tracing::info!("Cleaning up torrents (executed every {} secs) ...", interval_in_secs); - torrents_manager.cleanup_torrents(); + torrents_manager.cleanup_torrents().await; tracing::info!("Cleaned up torrents in: {} ms", (Utc::now().time() - start_time).num_milliseconds()); } else { break; From 1eb545c0fb233bba0206c2557401c2b4c686cc3a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 13 May 2025 09:16:15 +0100 Subject: [PATCH 1094/1297] feat: [#1358] remove persistent metric from torrent-repository pkg This package dones not have persistence. Persistence is only handle in the `tracker-core` pacakge. The metric will be included there. --- packages/torrent-repository/src/statistics/mod.rs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/packages/torrent-repository/src/statistics/mod.rs b/packages/torrent-repository/src/statistics/mod.rs index b0dce479f..fc8f1e1e8 100644 --- a/packages/torrent-repository/src/statistics/mod.rs +++ b/packages/torrent-repository/src/statistics/mod.rs @@ -8,7 +8,6 @@ use torrust_tracker_metrics::metric_name; use torrust_tracker_metrics::unit::Unit; const TORRENT_REPOSITORY_RUNTIME_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_runtime_torrents_downloads_total"; -const TORRENT_REPOSITORY_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_persistent_torrents_downloads_total"; #[must_use] pub fn describe_metrics() -> Metrics { @@ -22,13 +21,5 @@ pub fn describe_metrics() -> Metrics { )), ); - metrics.metric_collection.describe_counter( - &metric_name!(TORRENT_REPOSITORY_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), - Some(Unit::Count), - Some(&MetricDescription::new( - "The total number of torrent downloads since persistent statistics were enabled the first time.", - )), - ); - metrics } From 29a2dfd80dd76176ed517534ae5f0bf75a59c50a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 13 May 2025 13:47:34 +0100 Subject: [PATCH 1095/1297] dev: change default config Decrease torrent cleanup interval and peer timeout to do manual tests faster. --- share/default/config/tracker.development.sqlite3.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index 488743eb9..89d700132 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -7,14 +7,14 @@ schema_version = "2.0.0" threshold = "info" [core] -#inactive_peer_cleanup_interval = 60 +inactive_peer_cleanup_interval = 60 listed = false private = false [core.tracker_policy] -#max_peer_timeout = 30 +max_peer_timeout = 30 persistent_torrent_completed_stat = true -#remove_peerless_torrents = true +remove_peerless_torrents = true [[udp_trackers]] bind_address = "0.0.0.0:6868" From d47483ff065b65f3ab51e27a481bf82c5048e3c6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 13 May 2025 13:52:47 +0100 Subject: [PATCH 1096/1297] feat: [#1358] new metric in torrent-repository: total number of torrents --- .../src/statistics/event/handler.rs | 4 -- packages/metrics/src/metric_collection.rs | 14 +++++- .../src/statistics/event/handler.rs | 29 ++++++++---- .../src/statistics/metrics.rs | 26 ++++++++++- .../torrent-repository/src/statistics/mod.rs | 7 +++ .../src/statistics/repository.rs | 44 +++++++++++++++++-- packages/torrent-repository/src/swarms.rs | 6 +++ 7 files changed, 111 insertions(+), 19 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index 8d2ad1aa2..f5506f6e3 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -9,10 +9,6 @@ use crate::event::Event; use crate::statistics::repository::Repository; use crate::statistics::HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; -/// # Panics -/// -/// This function panics if the client IP address is not the same as the IP -/// version of the event. pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { match event { Event::TcpAnnounce { connection, .. } => { diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index 438f3b03a..83b08f178 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -140,7 +140,12 @@ impl MetricCollection { /// /// Return an error if a metrics of a different type with the same name /// already exists. - pub fn increase_gauge(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) -> Result<(), Error> { + pub fn increment_gauge( + &mut self, + name: &MetricName, + label_set: &LabelSet, + time: DurationSinceUnixEpoch, + ) -> Result<(), Error> { if self.counters.metrics.contains_key(name) { return Err(Error::MetricNameCollisionAdding { metric_name: name.clone(), @@ -156,7 +161,12 @@ impl MetricCollection { /// /// Return an error if a metrics of a different type with the same name /// already exists. - pub fn decrease_gauge(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) -> Result<(), Error> { + pub fn decrement_gauge( + &mut self, + name: &MetricName, + label_set: &LabelSet, + time: DurationSinceUnixEpoch, + ) -> Result<(), Error> { if self.counters.metrics.contains_key(name) { return Err(Error::MetricNameCollisionAdding { metric_name: name.clone(), diff --git a/packages/torrent-repository/src/statistics/event/handler.rs b/packages/torrent-repository/src/statistics/event/handler.rs index 2073575a8..6428bbeb7 100644 --- a/packages/torrent-repository/src/statistics/event/handler.rs +++ b/packages/torrent-repository/src/statistics/event/handler.rs @@ -1,23 +1,36 @@ use std::sync::Arc; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; use crate::statistics::repository::Repository; +use crate::statistics::TORRENT_REPOSITORY_TORRENTS_TOTAL; -/// # Panics -/// -/// This function panics if the client IP address is not the same as the IP -/// version of the event. -pub async fn handle_event(event: Event, stats_repository: &Arc, _now: DurationSinceUnixEpoch) { +pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { match event { Event::TorrentAdded { info_hash, .. } => { - // todo: update metrics tracing::debug!("Torrent added {info_hash}"); + + match stats_repository + .increment_gauge(&metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), &LabelSet::default(), now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increment the gauge: {}", err), + }; } Event::TorrentRemoved { info_hash } => { - // todo: update metrics tracing::debug!("Torrent removed {info_hash}"); + + match stats_repository + .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), &LabelSet::default(), now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to decrement the gauge: {}", err), + }; } Event::PeerAdded { announcement } => { // todo: update metrics @@ -28,6 +41,4 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, _now tracing::debug!("Peer removed: socket address {socket_addr:?}, peer ID: {peer_id:?}"); } } - - tracing::debug!("metrics: {:?}", stats_repository.get_metrics().await); } diff --git a/packages/torrent-repository/src/statistics/metrics.rs b/packages/torrent-repository/src/statistics/metrics.rs index 6ee275e63..f8ab3f9d9 100644 --- a/packages/torrent-repository/src/statistics/metrics.rs +++ b/packages/torrent-repository/src/statistics/metrics.rs @@ -15,7 +15,7 @@ impl Metrics { /// # Errors /// /// Returns an error if the metric does not exist and it cannot be created. - pub fn increase_counter( + pub fn increment_counter( &mut self, metric_name: &MetricName, labels: &LabelSet, @@ -36,4 +36,28 @@ impl Metrics { ) -> Result<(), Error> { self.metric_collection.set_gauge(metric_name, labels, value, now) } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increment_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increment_gauge(metric_name, labels, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn decrement_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.decrement_gauge(metric_name, labels, now) + } } diff --git a/packages/torrent-repository/src/statistics/mod.rs b/packages/torrent-repository/src/statistics/mod.rs index fc8f1e1e8..f1507b7bb 100644 --- a/packages/torrent-repository/src/statistics/mod.rs +++ b/packages/torrent-repository/src/statistics/mod.rs @@ -7,12 +7,19 @@ use torrust_tracker_metrics::metric::description::MetricDescription; use torrust_tracker_metrics::metric_name; use torrust_tracker_metrics::unit::Unit; +const TORRENT_REPOSITORY_TORRENTS_TOTAL: &str = "torrent_repository_torrents_total"; const TORRENT_REPOSITORY_RUNTIME_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_runtime_torrents_downloads_total"; #[must_use] pub fn describe_metrics() -> Metrics { let mut metrics = Metrics::default(); + metrics.metric_collection.describe_gauge( + &metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new("The total number of torrents.")), + ); + metrics.metric_collection.describe_counter( &metric_name!(TORRENT_REPOSITORY_RUNTIME_TORRENTS_DOWNLOADS_TOTAL), Some(Unit::Count), diff --git a/packages/torrent-repository/src/statistics/repository.rs b/packages/torrent-repository/src/statistics/repository.rs index 9fdff7008..a8cb8549e 100644 --- a/packages/torrent-repository/src/statistics/repository.rs +++ b/packages/torrent-repository/src/statistics/repository.rs @@ -36,8 +36,8 @@ impl Repository { /// # Errors /// /// This function will return an error if the metric collection fails to - /// increase the counter. - pub async fn increase_counter( + /// increment the counter. + pub async fn increment_counter( &self, metric_name: &MetricName, labels: &LabelSet, @@ -45,7 +45,45 @@ impl Repository { ) -> Result<(), Error> { let mut stats_lock = self.stats.write().await; - let result = stats_lock.increase_counter(metric_name, labels, now); + let result = stats_lock.increment_counter(metric_name, labels, now); + + drop(stats_lock); + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increment the gauge. + pub async fn increment_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.increment_gauge(metric_name, labels, now); + + drop(stats_lock); + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// decrement the gauge. + pub async fn decrement_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.decrement_gauge(metric_name, labels, now); drop(stats_lock); diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 277a85cc2..41123fd50 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -299,9 +299,15 @@ impl Swarms { continue; } + let info_hash = *swarm_handle.key(); + swarm_handle.remove(); peerless_torrents_removed += 1; + + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender.send(Event::TorrentRemoved { info_hash }).await; + } } tracing::info!(peerless_torrents_removed = peerless_torrents_removed); From ba2033bf60d3b9e56fe8063d57db648fa39858ce Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 13 May 2025 15:08:40 +0100 Subject: [PATCH 1097/1297] fix: [#1358] trigger PeerRemoved event when peer is removed due to inactivity --- packages/torrent-repository/src/event.rs | 2 +- .../src/statistics/event/handler.rs | 5 ++- packages/torrent-repository/src/swarm.rs | 38 ++++++++++++++----- packages/torrent-repository/src/swarms.rs | 4 +- .../torrent-repository/tests/swarm/mod.rs | 2 +- 5 files changed, 36 insertions(+), 15 deletions(-) diff --git a/packages/torrent-repository/src/event.rs b/packages/torrent-repository/src/event.rs index 57fe7bc4b..1184714ae 100644 --- a/packages/torrent-repository/src/event.rs +++ b/packages/torrent-repository/src/event.rs @@ -17,7 +17,7 @@ pub enum Event { announcement: PeerAnnouncement, }, PeerRemoved { - socket_addr: SocketAddr, + peer_addr: SocketAddr, peer_id: PeerId, }, } diff --git a/packages/torrent-repository/src/statistics/event/handler.rs b/packages/torrent-repository/src/statistics/event/handler.rs index 6428bbeb7..8022102d9 100644 --- a/packages/torrent-repository/src/statistics/event/handler.rs +++ b/packages/torrent-repository/src/statistics/event/handler.rs @@ -36,7 +36,10 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: // todo: update metrics tracing::debug!("Peer added {announcement:?}"); } - Event::PeerRemoved { socket_addr, peer_id } => { + Event::PeerRemoved { + peer_addr: socket_addr, + peer_id, + } => { // todo: update metrics tracing::debug!("Peer removed: socket address {socket_addr:?}, peer ID: {peer_id:?}"); } diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index d1918bd24..32785cada 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -143,7 +143,7 @@ impl Swarm { if let Some(event_sender) = self.event_sender.as_deref() { event_sender .send(Event::PeerRemoved { - socket_addr: old_peer.peer_addr, + peer_addr: old_peer.peer_addr, peer_id: old_peer.peer_id, }) .await; @@ -155,10 +155,11 @@ impl Swarm { } } - pub fn remove_inactive(&mut self, current_cutoff: DurationSinceUnixEpoch) -> u64 { - let mut inactive_peers_removed = 0; + pub async fn remove_inactive(&mut self, current_cutoff: DurationSinceUnixEpoch) -> usize { + let mut number_of_peers_removed = 0; + let mut removed_peers = Vec::new(); - self.peers.retain(|_, peer| { + self.peers.retain(|_key, peer| { let is_active = peer::ReadInfo::get_updated(peer) > current_cutoff; if !is_active { @@ -169,13 +170,30 @@ impl Swarm { self.metadata.incomplete -= 1; } - inactive_peers_removed += 1; + number_of_peers_removed += 1; + + if let Some(_event_sender) = self.event_sender.as_deref() { + // Events can not be trigger here because retain does not allow + // async closures. + removed_peers.push((peer.peer_addr, peer.peer_id)); + } } is_active }); - inactive_peers_removed + if let Some(event_sender) = self.event_sender.as_deref() { + for (peer_addr, peer_id) in &removed_peers { + event_sender + .send(Event::PeerRemoved { + peer_addr: *peer_addr, + peer_id: *peer_id, + }) + .await; + } + } + + number_of_peers_removed } #[must_use] @@ -431,7 +449,7 @@ mod tests { swarm.upsert_peer(peer.into(), &mut downloads_increased).await; // Remove peers not updated since one second after inserting the peer - swarm.remove_inactive(last_update_time + one_second); + swarm.remove_inactive(last_update_time + one_second).await; assert_eq!(swarm.len(), 0); } @@ -448,7 +466,7 @@ mod tests { swarm.upsert_peer(peer.into(), &mut downloads_increased).await; // Remove peers not updated since one second before inserting the peer. - swarm.remove_inactive(last_update_time - one_second); + swarm.remove_inactive(last_update_time - one_second).await; assert_eq!(swarm.len(), 1); } @@ -753,7 +771,7 @@ mod tests { let leechers = swarm.metadata().leechers(); - swarm.remove_inactive(leecher.updated + Duration::from_secs(1)); + swarm.remove_inactive(leecher.updated + Duration::from_secs(1)).await; assert_eq!(swarm.metadata().leechers(), leechers - 1); } @@ -769,7 +787,7 @@ mod tests { let seeders = swarm.metadata().seeders(); - swarm.remove_inactive(seeder.updated + Duration::from_secs(1)); + swarm.remove_inactive(seeder.updated + Duration::from_secs(1)).await; assert_eq!(swarm.metadata().seeders(), seeders - 1); } diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 41123fd50..c74fec3ea 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -259,7 +259,7 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for any /// swarm handle. - pub async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> Result { + pub async fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> Result { tracing::info!( "Removing inactive peers since: {:?} ...", convert_from_timestamp_to_datetime_utc(current_cutoff) @@ -269,7 +269,7 @@ impl Swarms { for swarm_handle in &self.swarms { let mut swarm = swarm_handle.value().lock().await; - let removed = swarm.remove_inactive(current_cutoff); + let removed = swarm.remove_inactive(current_cutoff).await; inactive_peers_removed += removed; } diff --git a/packages/torrent-repository/tests/swarm/mod.rs b/packages/torrent-repository/tests/swarm/mod.rs index 1f5d0b737..f7ae4b439 100644 --- a/packages/torrent-repository/tests/swarm/mod.rs +++ b/packages/torrent-repository/tests/swarm/mod.rs @@ -390,7 +390,7 @@ async fn it_should_remove_inactive_peers_beyond_cutoff(#[values(swarm())] mut sw assert_eq!(swarm.len(), peers.len() + 1); let current_cutoff = CurrentClock::now_sub(&TIMEOUT).unwrap_or_default(); - swarm.remove_inactive(current_cutoff); + swarm.remove_inactive(current_cutoff).await; assert_eq!(swarm.len(), peers.len()); } From 269d27398975df921a846770e58b4d0a5bfde256 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 13 May 2025 20:14:31 +0100 Subject: [PATCH 1098/1297] refactor: [#1358] rename metric From `TORRENT_REPOSITORY_RUNTIME_TORRENTS_DOWNLOADS_TOTAL` to `TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL`. None of the metrics in the `torrent-repositry` package will be persisted. We can use the `persitent` sufix for metrics in other packages to avoid conflicts. It's planned to use the same metric in the `tracker-core` package but with the historial persited value. --- packages/torrent-repository/src/statistics/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/torrent-repository/src/statistics/mod.rs b/packages/torrent-repository/src/statistics/mod.rs index f1507b7bb..941d619e9 100644 --- a/packages/torrent-repository/src/statistics/mod.rs +++ b/packages/torrent-repository/src/statistics/mod.rs @@ -8,7 +8,7 @@ use torrust_tracker_metrics::metric_name; use torrust_tracker_metrics::unit::Unit; const TORRENT_REPOSITORY_TORRENTS_TOTAL: &str = "torrent_repository_torrents_total"; -const TORRENT_REPOSITORY_RUNTIME_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_runtime_torrents_downloads_total"; +const TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_torrents_downloads_total"; #[must_use] pub fn describe_metrics() -> Metrics { @@ -21,7 +21,7 @@ pub fn describe_metrics() -> Metrics { ); metrics.metric_collection.describe_counter( - &metric_name!(TORRENT_REPOSITORY_RUNTIME_TORRENTS_DOWNLOADS_TOTAL), + &metric_name!(TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL), Some(Unit::Count), Some(&MetricDescription::new( "The total number of torrent downloads since the tracker process started.", From 01a9970256c1c4f76ee9efb1bfb5faa886c7fd3d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 14 May 2025 07:40:22 +0100 Subject: [PATCH 1099/1297] feat: [#1358] new metric in torrent-repository: total number of peers You can tested it manually with: ``` cargo run -p torrust-tracker-client --bin udp_tracker_client announce udp://127.0.0.1:6969 443c7602b4fde83d1154d6d9da48808418b181b6 | jq curl -s "http://localhost:1212/api/v1/metrics?token=MyAccessToken&format=prometheus" | grep torrent_repository_peers_total Finished `dev` profile [optimized + debuginfo] target(s) in 0.10s Running `target/debug/udp_tracker_client announce 'udp://127.0.0.1:6969' 443c7602b4fde83d1154d6d9da48808418b181b6` { "AnnounceIpv4": { "transaction_id": -888840697, "announce_interval": 120, "leechers": 0, "seeders": 1, "peers": [] } } torrent_repository_peers_total{peer_role="seeder"} 1 ``` --- packages/torrent-repository/src/event.rs | 10 ++-- .../src/statistics/event/handler.rs | 51 ++++++++++++++----- .../torrent-repository/src/statistics/mod.rs | 16 ++++++ packages/torrent-repository/src/swarm.rs | 24 ++------- 4 files changed, 61 insertions(+), 40 deletions(-) diff --git a/packages/torrent-repository/src/event.rs b/packages/torrent-repository/src/event.rs index 1184714ae..fecb8cd1d 100644 --- a/packages/torrent-repository/src/event.rs +++ b/packages/torrent-repository/src/event.rs @@ -1,8 +1,5 @@ -use std::net::SocketAddr; - -use aquatic_udp_protocol::PeerId; use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::peer::PeerAnnouncement; +use torrust_tracker_primitives::peer::{Peer, PeerAnnouncement}; #[derive(Debug, PartialEq, Eq, Clone)] pub enum Event { @@ -14,11 +11,10 @@ pub enum Event { info_hash: InfoHash, }, PeerAdded { - announcement: PeerAnnouncement, + peer: Peer, }, PeerRemoved { - peer_addr: SocketAddr, - peer_id: PeerId, + peer: Peer, }, } diff --git a/packages/torrent-repository/src/statistics/event/handler.rs b/packages/torrent-repository/src/statistics/event/handler.rs index 8022102d9..e869e7c1a 100644 --- a/packages/torrent-repository/src/statistics/event/handler.rs +++ b/packages/torrent-repository/src/statistics/event/handler.rs @@ -1,17 +1,17 @@ use std::sync::Arc; -use torrust_tracker_metrics::label::LabelSet; -use torrust_tracker_metrics::metric_name; +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::{label_name, metric_name}; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; use crate::statistics::repository::Repository; -use crate::statistics::TORRENT_REPOSITORY_TORRENTS_TOTAL; +use crate::statistics::{TORRENT_REPOSITORY_PEERS_TOTAL, TORRENT_REPOSITORY_TORRENTS_TOTAL}; pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { match event { Event::TorrentAdded { info_hash, .. } => { - tracing::debug!("Torrent added {info_hash}"); + tracing::debug!(info_hash = ?info_hash, "Torrent added",); match stats_repository .increment_gauge(&metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), &LabelSet::default(), now) @@ -22,7 +22,7 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: }; } Event::TorrentRemoved { info_hash } => { - tracing::debug!("Torrent removed {info_hash}"); + tracing::debug!(info_hash = ?info_hash, "Torrent removed",); match stats_repository .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), &LabelSet::default(), now) @@ -32,16 +32,39 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: Err(err) => tracing::error!("Failed to decrement the gauge: {}", err), }; } - Event::PeerAdded { announcement } => { - // todo: update metrics - tracing::debug!("Peer added {announcement:?}"); + Event::PeerAdded { peer } => { + tracing::debug!(peer = ?peer, "Peer added", ); + + let label_set: LabelSet = if peer.is_seeder() { + (label_name!("peer_role"), LabelValue::new("seeder")).into() + } else { + (label_name!("peer_role"), LabelValue::new("leecher")).into() + }; + + match stats_repository + .increment_gauge(&metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increment the gauge: {}", err), + }; } - Event::PeerRemoved { - peer_addr: socket_addr, - peer_id, - } => { - // todo: update metrics - tracing::debug!("Peer removed: socket address {socket_addr:?}, peer ID: {peer_id:?}"); + Event::PeerRemoved { peer } => { + tracing::debug!(peer = ?peer, "Peer removed", ); + + let label_set: LabelSet = if peer.is_seeder() { + (label_name!("peer_role"), LabelValue::new("seeder")).into() + } else { + (label_name!("peer_role"), LabelValue::new("leecher")).into() + }; + + match stats_repository + .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to decrement the gauge: {}", err), + }; } } } diff --git a/packages/torrent-repository/src/statistics/mod.rs b/packages/torrent-repository/src/statistics/mod.rs index 941d619e9..4deaf19cb 100644 --- a/packages/torrent-repository/src/statistics/mod.rs +++ b/packages/torrent-repository/src/statistics/mod.rs @@ -7,13 +7,21 @@ use torrust_tracker_metrics::metric::description::MetricDescription; use torrust_tracker_metrics::metric_name; use torrust_tracker_metrics::unit::Unit; +// Torrent metrics + const TORRENT_REPOSITORY_TORRENTS_TOTAL: &str = "torrent_repository_torrents_total"; const TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_torrents_downloads_total"; +// Peers metrics + +const TORRENT_REPOSITORY_PEERS_TOTAL: &str = "torrent_repository_peers_total"; + #[must_use] pub fn describe_metrics() -> Metrics { let mut metrics = Metrics::default(); + // Torrent metrics + metrics.metric_collection.describe_gauge( &metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), Some(Unit::Count), @@ -28,5 +36,13 @@ pub fn describe_metrics() -> Metrics { )), ); + // Peers metrics + + metrics.metric_collection.describe_gauge( + &metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new("The total number of peers.")), + ); + metrics } diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 32785cada..9832d8b2a 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -117,11 +117,7 @@ impl Swarm { } if let Some(event_sender) = self.event_sender.as_deref() { - event_sender - .send(Event::PeerAdded { - announcement: *announcement, - }) - .await; + event_sender.send(Event::PeerAdded { peer: *announcement }).await; } None @@ -141,12 +137,7 @@ impl Swarm { } if let Some(event_sender) = self.event_sender.as_deref() { - event_sender - .send(Event::PeerRemoved { - peer_addr: old_peer.peer_addr, - peer_id: old_peer.peer_id, - }) - .await; + event_sender.send(Event::PeerRemoved { peer: *old_peer.clone() }).await; } Some(old_peer) @@ -175,7 +166,7 @@ impl Swarm { if let Some(_event_sender) = self.event_sender.as_deref() { // Events can not be trigger here because retain does not allow // async closures. - removed_peers.push((peer.peer_addr, peer.peer_id)); + removed_peers.push(*peer.clone()); } } @@ -183,13 +174,8 @@ impl Swarm { }); if let Some(event_sender) = self.event_sender.as_deref() { - for (peer_addr, peer_id) in &removed_peers { - event_sender - .send(Event::PeerRemoved { - peer_addr: *peer_addr, - peer_id: *peer_id, - }) - .await; + for peer in &removed_peers { + event_sender.send(Event::PeerRemoved { peer: *peer }).await; } } From daba8a07ae957c927a6d45591549a10b12a9a582 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 14 May 2025 12:13:38 +0100 Subject: [PATCH 1100/1297] feat: [#1358] new metric in torrent-repository: total number of downloads --- packages/primitives/src/peer.rs | 42 +++++++++++ packages/torrent-repository/Cargo.toml | 2 +- packages/torrent-repository/src/event.rs | 7 ++ .../src/statistics/event/handler.rs | 72 +++++++++++++++---- packages/torrent-repository/src/swarm.rs | 15 +++- 5 files changed, 122 insertions(+), 16 deletions(-) diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index bd753b220..316541ad6 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -27,6 +27,7 @@ use std::ops::{Deref, DerefMut}; use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use derive_more::Display; use serde::Serialize; use zerocopy::FromBytes as _; @@ -34,6 +35,24 @@ use crate::DurationSinceUnixEpoch; pub type PeerAnnouncement = Peer; +#[derive(Debug, Display, Serialize, Copy, Clone, PartialEq, Eq, Hash)] +#[serde(rename_all_fields = "lowercase")] +pub enum PeerRole { + Seeder, + Leecher, +} + +impl PeerRole { + /// Returns the opposite role: Seeder becomes Leecher, and vice versa. + #[must_use] + pub fn opposite(self) -> Self { + match self { + PeerRole::Seeder => PeerRole::Leecher, + PeerRole::Leecher => PeerRole::Seeder, + } + } +} + /// Peer struct used by the core `Tracker`. /// /// A sample peer: @@ -147,6 +166,7 @@ impl PartialOrd for Peer { pub trait ReadInfo { fn is_seeder(&self) -> bool; + fn is_leecher(&self) -> bool; fn get_event(&self) -> AnnounceEvent; fn get_id(&self) -> PeerId; fn get_updated(&self) -> DurationSinceUnixEpoch; @@ -158,6 +178,10 @@ impl ReadInfo for Peer { self.left.0.get() <= 0 && self.event != AnnounceEvent::Stopped } + fn is_leecher(&self) -> bool { + !self.is_seeder() + } + fn get_event(&self) -> AnnounceEvent { self.event } @@ -180,6 +204,10 @@ impl ReadInfo for Arc { self.left.0.get() <= 0 && self.event != AnnounceEvent::Stopped } + fn is_leecher(&self) -> bool { + !self.is_seeder() + } + fn get_event(&self) -> AnnounceEvent { self.event } @@ -203,6 +231,20 @@ impl Peer { self.left.0.get() <= 0 && self.event != AnnounceEvent::Stopped } + #[must_use] + pub fn is_leecher(&self) -> bool { + !self.is_seeder() + } + + #[must_use] + pub fn role(&self) -> PeerRole { + if self.is_seeder() { + PeerRole::Seeder + } else { + PeerRole::Leecher + } + } + pub fn ip(&mut self) -> IpAddr { self.peer_addr.ip() } diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 1c7cc09fe..26662b583 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -20,7 +20,7 @@ aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" crossbeam-skiplist = "0" futures = "0" -serde = "1.0.219" +serde = { version = "1.0.219", features = ["derive"] } thiserror = "2.0.12" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } diff --git a/packages/torrent-repository/src/event.rs b/packages/torrent-repository/src/event.rs index fecb8cd1d..69d35141f 100644 --- a/packages/torrent-repository/src/event.rs +++ b/packages/torrent-repository/src/event.rs @@ -16,6 +16,13 @@ pub enum Event { PeerRemoved { peer: Peer, }, + PeerUpdated { + old_peer: Peer, + new_peer: Peer, + }, + PeerDownloadCompleted { + peer: Peer, + }, } pub mod sender { diff --git a/packages/torrent-repository/src/statistics/event/handler.rs b/packages/torrent-repository/src/statistics/event/handler.rs index e869e7c1a..5bf4a2f84 100644 --- a/packages/torrent-repository/src/statistics/event/handler.rs +++ b/packages/torrent-repository/src/statistics/event/handler.rs @@ -2,11 +2,14 @@ use std::sync::Arc; use torrust_tracker_metrics::label::{LabelSet, LabelValue}; use torrust_tracker_metrics::{label_name, metric_name}; +use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; use crate::statistics::repository::Repository; -use crate::statistics::{TORRENT_REPOSITORY_PEERS_TOTAL, TORRENT_REPOSITORY_TORRENTS_TOTAL}; +use crate::statistics::{ + TORRENT_REPOSITORY_PEERS_TOTAL, TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL, TORRENT_REPOSITORY_TORRENTS_TOTAL, +}; pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { match event { @@ -35,14 +38,8 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: Event::PeerAdded { peer } => { tracing::debug!(peer = ?peer, "Peer added", ); - let label_set: LabelSet = if peer.is_seeder() { - (label_name!("peer_role"), LabelValue::new("seeder")).into() - } else { - (label_name!("peer_role"), LabelValue::new("leecher")).into() - }; - match stats_repository - .increment_gauge(&metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), &label_set, now) + .increment_gauge(&metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), &label_set_for_peer(&peer), now) .await { Ok(()) => {} @@ -52,19 +49,66 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: Event::PeerRemoved { peer } => { tracing::debug!(peer = ?peer, "Peer removed", ); - let label_set: LabelSet = if peer.is_seeder() { - (label_name!("peer_role"), LabelValue::new("seeder")).into() - } else { - (label_name!("peer_role"), LabelValue::new("leecher")).into() + match stats_repository + .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), &label_set_for_peer(&peer), now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to decrement the gauge: {}", err), }; + } + Event::PeerUpdated { old_peer, new_peer } => { + tracing::debug!(old_peer = ?old_peer, new_peer = ?new_peer, "Peer updated", ); + + if old_peer.role() != new_peer.role() { + match stats_repository + .increment_gauge( + &metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), + &(label_name!("peer_role"), LabelValue::new(&new_peer.role().to_string())).into(), + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increment the gauge: {}", err), + } + + match stats_repository + .decrement_gauge( + &metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), + &(label_name!("peer_role"), LabelValue::new(&old_peer.role().to_string())).into(), + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to decrement the gauge: {}", err), + }; + } + } + Event::PeerDownloadCompleted { peer } => { + tracing::debug!(peer = ?peer, "Peer download completed", ); match stats_repository - .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), &label_set, now) + .increment_counter( + &metric_name!(TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL), + &label_set_for_peer(&peer), + now, + ) .await { Ok(()) => {} - Err(err) => tracing::error!("Failed to decrement the gauge: {}", err), + Err(err) => tracing::error!("Failed to increment the gauge: {}", err), }; } } } + +/// Returns the label set to be included in the metrics for the given peer. +fn label_set_for_peer(peer: &Peer) -> LabelSet { + if peer.is_seeder() { + (label_name!("peer_role"), LabelValue::new("seeder")).into() + } else { + (label_name!("peer_role"), LabelValue::new("leecher")).into() + } +} diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 9832d8b2a..782726958 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -82,7 +82,7 @@ impl Swarm { if let Some(old_announce) = self.peers.insert(incoming_announce.peer_addr, incoming_announce) { // A peer has been updated in the swarm. - // Check if the peer has changed its from leecher to seeder or vice versa. + // Check if the peer has changed from leecher to seeder or vice versa. if old_announce.is_seeder() != is_now_seeder { if is_now_seeder { self.metadata.complete += 1; @@ -99,6 +99,19 @@ impl Swarm { *downloads_increased = true; } + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerUpdated { + old_peer: *old_announce, + new_peer: *announcement, + }) + .await; + + if *downloads_increased { + event_sender.send(Event::PeerDownloadCompleted { peer: *announcement }).await; + } + } + Some(old_announce) } else { // A new peer has been added to the swarm. From c706a1b30915f660ec09a3c28bc4a4a841536a5c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 14 May 2025 12:24:14 +0100 Subject: [PATCH 1101/1297] refactor: [#1358] move logs --- .../src/statistics/event/handler.rs | 60 +++++-------------- .../src/statistics/repository.rs | 15 +++++ 2 files changed, 31 insertions(+), 44 deletions(-) diff --git a/packages/torrent-repository/src/statistics/event/handler.rs b/packages/torrent-repository/src/statistics/event/handler.rs index 5bf4a2f84..90df19ab6 100644 --- a/packages/torrent-repository/src/statistics/event/handler.rs +++ b/packages/torrent-repository/src/statistics/event/handler.rs @@ -16,90 +16,62 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: Event::TorrentAdded { info_hash, .. } => { tracing::debug!(info_hash = ?info_hash, "Torrent added",); - match stats_repository + let _unused = stats_repository .increment_gauge(&metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), &LabelSet::default(), now) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increment the gauge: {}", err), - }; + .await; } Event::TorrentRemoved { info_hash } => { tracing::debug!(info_hash = ?info_hash, "Torrent removed",); - match stats_repository + let _unused = stats_repository .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), &LabelSet::default(), now) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to decrement the gauge: {}", err), - }; + .await; } Event::PeerAdded { peer } => { tracing::debug!(peer = ?peer, "Peer added", ); - match stats_repository + let _unused = stats_repository .increment_gauge(&metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), &label_set_for_peer(&peer), now) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increment the gauge: {}", err), - }; + .await; } Event::PeerRemoved { peer } => { tracing::debug!(peer = ?peer, "Peer removed", ); - match stats_repository + let _unused = stats_repository .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), &label_set_for_peer(&peer), now) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to decrement the gauge: {}", err), - }; + .await; } Event::PeerUpdated { old_peer, new_peer } => { tracing::debug!(old_peer = ?old_peer, new_peer = ?new_peer, "Peer updated", ); if old_peer.role() != new_peer.role() { - match stats_repository + let _unused = stats_repository .increment_gauge( &metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), - &(label_name!("peer_role"), LabelValue::new(&new_peer.role().to_string())).into(), + &label_set_for_peer(&new_peer), now, ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increment the gauge: {}", err), - } + .await; - match stats_repository + let _unused = stats_repository .decrement_gauge( &metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), - &(label_name!("peer_role"), LabelValue::new(&old_peer.role().to_string())).into(), + &label_set_for_peer(&old_peer), now, ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to decrement the gauge: {}", err), - }; + .await; } } Event::PeerDownloadCompleted { peer } => { tracing::debug!(peer = ?peer, "Peer download completed", ); - match stats_repository + let _unused = stats_repository .increment_counter( &metric_name!(TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL), &label_set_for_peer(&peer), now, ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increment the gauge: {}", err), - }; + .await; } } } diff --git a/packages/torrent-repository/src/statistics/repository.rs b/packages/torrent-repository/src/statistics/repository.rs index a8cb8549e..1e376faf7 100644 --- a/packages/torrent-repository/src/statistics/repository.rs +++ b/packages/torrent-repository/src/statistics/repository.rs @@ -49,6 +49,11 @@ impl Repository { drop(stats_lock); + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to increment the counter: {}", err), + } + result } @@ -68,6 +73,11 @@ impl Repository { drop(stats_lock); + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to increment the gauge: {}", err), + } + result } @@ -87,6 +97,11 @@ impl Repository { drop(stats_lock); + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to decrement the gauge: {}", err), + } + result } } From 60c00e8bd575285f5c47e0cf8518574b527b6db7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 14 May 2025 12:46:53 +0100 Subject: [PATCH 1102/1297] feat: [#1358] add info-hash to all torrent-repository events To know which swarm the event belongs to. --- packages/torrent-repository/src/event.rs | 4 + .../src/statistics/event/handler.rs | 20 ++-- packages/torrent-repository/src/swarm.rs | 106 +++++++++++------- packages/torrent-repository/src/swarms.rs | 11 +- .../torrent-repository/tests/swarm/mod.rs | 3 +- .../torrent-repository/tests/swarms/mod.rs | 22 ++-- 6 files changed, 104 insertions(+), 62 deletions(-) diff --git a/packages/torrent-repository/src/event.rs b/packages/torrent-repository/src/event.rs index 69d35141f..ac1c06637 100644 --- a/packages/torrent-repository/src/event.rs +++ b/packages/torrent-repository/src/event.rs @@ -11,16 +11,20 @@ pub enum Event { info_hash: InfoHash, }, PeerAdded { + info_hash: InfoHash, peer: Peer, }, PeerRemoved { + info_hash: InfoHash, peer: Peer, }, PeerUpdated { + info_hash: InfoHash, old_peer: Peer, new_peer: Peer, }, PeerDownloadCompleted { + info_hash: InfoHash, peer: Peer, }, } diff --git a/packages/torrent-repository/src/statistics/event/handler.rs b/packages/torrent-repository/src/statistics/event/handler.rs index 90df19ab6..d2783f9ba 100644 --- a/packages/torrent-repository/src/statistics/event/handler.rs +++ b/packages/torrent-repository/src/statistics/event/handler.rs @@ -27,22 +27,26 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), &LabelSet::default(), now) .await; } - Event::PeerAdded { peer } => { - tracing::debug!(peer = ?peer, "Peer added", ); + Event::PeerAdded { info_hash, peer } => { + tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer added", ); let _unused = stats_repository .increment_gauge(&metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), &label_set_for_peer(&peer), now) .await; } - Event::PeerRemoved { peer } => { - tracing::debug!(peer = ?peer, "Peer removed", ); + Event::PeerRemoved { info_hash, peer } => { + tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer removed", ); let _unused = stats_repository .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), &label_set_for_peer(&peer), now) .await; } - Event::PeerUpdated { old_peer, new_peer } => { - tracing::debug!(old_peer = ?old_peer, new_peer = ?new_peer, "Peer updated", ); + Event::PeerUpdated { + info_hash, + old_peer, + new_peer, + } => { + tracing::debug!(info_hash = ?info_hash, old_peer = ?old_peer, new_peer = ?new_peer, "Peer updated", ); if old_peer.role() != new_peer.role() { let _unused = stats_repository @@ -62,8 +66,8 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: .await; } } - Event::PeerDownloadCompleted { peer } => { - tracing::debug!(peer = ?peer, "Peer download completed", ); + Event::PeerDownloadCompleted { info_hash, peer } => { + tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer download completed", ); let _unused = stats_repository .increment_counter( diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 782726958..3fe0e27d7 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -7,6 +7,7 @@ use std::net::SocketAddr; use std::sync::Arc; use aquatic_udp_protocol::AnnounceEvent; +use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::peer::{self, Peer, PeerAnnouncement}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; @@ -15,8 +16,9 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::sender::Sender; use crate::event::Event; -#[derive(Clone, Default)] +#[derive(Clone)] pub struct Swarm { + info_hash: InfoHash, peers: BTreeMap>, metadata: SwarmMetadata, event_sender: Sender, @@ -49,8 +51,9 @@ impl Eq for Swarm {} impl Swarm { #[must_use] - pub fn new(downloaded: u32, event_sender: Sender) -> Self { + pub fn new(info_hash: &InfoHash, downloaded: u32, event_sender: Sender) -> Self { Self { + info_hash: *info_hash, peers: BTreeMap::new(), metadata: SwarmMetadata::new(downloaded, 0, 0), event_sender, @@ -102,13 +105,19 @@ impl Swarm { if let Some(event_sender) = self.event_sender.as_deref() { event_sender .send(Event::PeerUpdated { + info_hash: self.info_hash, old_peer: *old_announce, new_peer: *announcement, }) .await; if *downloads_increased { - event_sender.send(Event::PeerDownloadCompleted { peer: *announcement }).await; + event_sender + .send(Event::PeerDownloadCompleted { + info_hash: self.info_hash, + peer: *announcement, + }) + .await; } } @@ -130,7 +139,12 @@ impl Swarm { } if let Some(event_sender) = self.event_sender.as_deref() { - event_sender.send(Event::PeerAdded { peer: *announcement }).await; + event_sender + .send(Event::PeerAdded { + info_hash: self.info_hash, + peer: *announcement, + }) + .await; } None @@ -150,7 +164,12 @@ impl Swarm { } if let Some(event_sender) = self.event_sender.as_deref() { - event_sender.send(Event::PeerRemoved { peer: *old_peer.clone() }).await; + event_sender + .send(Event::PeerRemoved { + info_hash: self.info_hash, + peer: *old_peer.clone(), + }) + .await; } Some(old_peer) @@ -188,7 +207,12 @@ impl Swarm { if let Some(event_sender) = self.event_sender.as_deref() { for peer in &removed_peers { - event_sender.send(Event::PeerRemoved { peer: *peer }).await; + event_sender + .send(Event::PeerRemoved { + info_hash: self.info_hash, + peer: *peer, + }) + .await; } } @@ -302,24 +326,25 @@ mod tests { use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::swarm::Swarm; + use crate::tests::sample_info_hash; #[test] fn it_should_be_empty_when_no_peers_have_been_inserted() { - let swarm = Swarm::default(); + let swarm = Swarm::new(&sample_info_hash(), 0, None); assert!(swarm.is_empty()); } #[test] fn it_should_have_zero_length_when_no_peers_have_been_inserted() { - let swarm = Swarm::default(); + let swarm = Swarm::new(&sample_info_hash(), 0, None); assert_eq!(swarm.len(), 0); } #[tokio::test] async fn it_should_allow_inserting_a_new_peer() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); @@ -329,7 +354,7 @@ mod tests { #[tokio::test] async fn it_should_allow_updating_a_preexisting_peer() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); @@ -344,7 +369,7 @@ mod tests { #[tokio::test] async fn it_should_allow_getting_all_peers() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); @@ -356,7 +381,7 @@ mod tests { #[tokio::test] async fn it_should_allow_getting_one_peer_by_id() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); @@ -368,7 +393,7 @@ mod tests { #[tokio::test] async fn it_should_increase_the_number_of_peers_after_inserting_a_new_one() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); @@ -380,7 +405,7 @@ mod tests { #[tokio::test] async fn it_should_decrease_the_number_of_peers_after_removing_one() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); @@ -394,7 +419,7 @@ mod tests { #[tokio::test] async fn it_should_allow_removing_an_existing_peer() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let peer = PeerBuilder::default().build(); @@ -409,7 +434,7 @@ mod tests { #[tokio::test] async fn it_should_allow_removing_a_non_existing_peer() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let peer = PeerBuilder::default().build(); @@ -418,7 +443,7 @@ mod tests { #[tokio::test] async fn it_should_allow_getting_all_peers_excluding_peers_with_a_given_address() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let peer1 = PeerBuilder::default() @@ -438,7 +463,7 @@ mod tests { #[tokio::test] async fn it_should_remove_inactive_peers() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let one_second = DurationSinceUnixEpoch::new(1, 0); @@ -455,7 +480,7 @@ mod tests { #[tokio::test] async fn it_should_not_remove_active_peers() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let one_second = DurationSinceUnixEpoch::new(1, 0); @@ -475,20 +500,21 @@ mod tests { use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use crate::tests::sample_info_hash; use crate::Swarm; fn empty_swarm() -> Swarm { - Swarm::default() + Swarm::new(&sample_info_hash(), 0, None) } async fn not_empty_swarm() -> Swarm { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); swarm.upsert_peer(PeerBuilder::default().build().into(), &mut false).await; swarm } async fn not_empty_swarm_with_downloads() -> Swarm { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut peer = PeerBuilder::leecher().build(); let mut downloads_increased = false; @@ -571,7 +597,7 @@ mod tests { #[tokio::test] async fn it_should_allow_inserting_two_identical_peers_except_for_the_socket_address() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let peer1 = PeerBuilder::default() @@ -589,7 +615,7 @@ mod tests { #[tokio::test] async fn it_should_not_allow_inserting_two_peers_with_different_peer_id_but_the_same_socket_address() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; // When that happens the peer ID will be changed in the swarm. @@ -612,7 +638,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_metadata() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); @@ -633,7 +659,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_number_of_seeders_in_the_list() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); @@ -649,7 +675,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_number_of_leechers_in_the_list() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); @@ -669,10 +695,11 @@ mod tests { use torrust_tracker_primitives::peer::fixture::PeerBuilder; use crate::swarm::Swarm; + use crate::tests::sample_info_hash; #[tokio::test] async fn it_should_increase_the_number_of_leechers_if_the_new_peer_is_a_leecher_() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let leechers = swarm.metadata().leechers(); @@ -686,7 +713,7 @@ mod tests { #[tokio::test] async fn it_should_increase_the_number_of_seeders_if_the_new_peer_is_a_seeder() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let seeders = swarm.metadata().seeders(); @@ -701,7 +728,7 @@ mod tests { #[tokio::test] async fn it_should_not_increasing_the_number_of_downloads_if_the_new_peer_has_completed_downloading_as_it_was_not_previously_known( ) { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let downloads = swarm.metadata().downloads(); @@ -718,10 +745,11 @@ mod tests { use torrust_tracker_primitives::peer::fixture::PeerBuilder; use crate::swarm::Swarm; + use crate::tests::sample_info_hash; #[tokio::test] async fn it_should_decrease_the_number_of_leechers_if_the_removed_peer_was_a_leecher() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let leecher = PeerBuilder::leecher().build(); @@ -737,7 +765,7 @@ mod tests { #[tokio::test] async fn it_should_decrease_the_number_of_seeders_if_the_removed_peer_was_a_seeder() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); @@ -758,10 +786,11 @@ mod tests { use torrust_tracker_primitives::peer::fixture::PeerBuilder; use crate::swarm::Swarm; + use crate::tests::sample_info_hash; #[tokio::test] async fn it_should_decrease_the_number_of_leechers_when_a_removed_peer_is_a_leecher() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let leecher = PeerBuilder::leecher().build(); @@ -777,7 +806,7 @@ mod tests { #[tokio::test] async fn it_should_decrease_the_number_of_seeders_when_the_removed_peer_is_a_seeder() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); @@ -797,10 +826,11 @@ mod tests { use torrust_tracker_primitives::peer::fixture::PeerBuilder; use crate::swarm::Swarm; + use crate::tests::sample_info_hash; #[tokio::test] async fn it_should_increase_seeders_and_decreasing_leechers_when_the_peer_changes_from_leecher_to_seeder_() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let mut peer = PeerBuilder::leecher().build(); @@ -820,7 +850,7 @@ mod tests { #[tokio::test] async fn it_should_increase_leechers_and_decreasing_seeders_when_the_peer_changes_from_seeder_to_leecher() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let mut peer = PeerBuilder::seeder().build(); @@ -840,7 +870,7 @@ mod tests { #[tokio::test] async fn it_should_increase_the_number_of_downloads_when_the_peer_announces_completed_downloading() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let mut peer = PeerBuilder::leecher().build(); @@ -858,7 +888,7 @@ mod tests { #[tokio::test] async fn it_should_not_increasing_the_number_of_downloads_when_the_peer_announces_completed_downloading_twice_() { - let mut swarm = Swarm::default(); + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; let mut peer = PeerBuilder::leecher().build(); diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index c74fec3ea..3200d77ff 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -58,11 +58,10 @@ impl Swarms { ) -> Result { let swarm_handle = match self.swarms.get(info_hash) { None => { - let new_swarm_handle = if let Some(number_of_downloads) = opt_persistent_torrent { - SwarmHandle::new(Swarm::new(number_of_downloads, self.event_sender.clone()).into()) - } else { - SwarmHandle::default() - }; + let number_of_downloads = opt_persistent_torrent.unwrap_or_default(); + + let new_swarm_handle = + SwarmHandle::new(Swarm::new(info_hash, number_of_downloads, self.event_sender.clone()).into()); let new_swarm_handle = self.swarms.get_or_insert(*info_hash, new_swarm_handle); @@ -330,7 +329,7 @@ impl Swarms { continue; } - let entry = SwarmHandle::new(Swarm::new(*completed, self.event_sender.clone()).into()); + let entry = SwarmHandle::new(Swarm::new(info_hash, *completed, self.event_sender.clone()).into()); // Since SkipMap is lock-free the torrent could have been inserted // after checking if it exists. diff --git a/packages/torrent-repository/tests/swarm/mod.rs b/packages/torrent-repository/tests/swarm/mod.rs index f7ae4b439..cb4009ba9 100644 --- a/packages/torrent-repository/tests/swarm/mod.rs +++ b/packages/torrent-repository/tests/swarm/mod.rs @@ -3,6 +3,7 @@ use std::ops::Sub; use std::time::Duration; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; +use bittorrent_primitives::info_hash::InfoHash; use rstest::{fixture, rstest}; use torrust_tracker_clock::clock::stopped::Stopped as _; use torrust_tracker_clock::clock::{self, Time as _}; @@ -16,7 +17,7 @@ use crate::CurrentClock; #[fixture] fn swarm() -> Swarm { - Swarm::default() + Swarm::new(&InfoHash::default(), 0, None) } #[fixture] diff --git a/packages/torrent-repository/tests/swarms/mod.rs b/packages/torrent-repository/tests/swarms/mod.rs index d8ee354c8..780d6cd4c 100644 --- a/packages/torrent-repository/tests/swarms/mod.rs +++ b/packages/torrent-repository/tests/swarms/mod.rs @@ -14,6 +14,10 @@ use torrust_tracker_torrent_repository::Swarms; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; +fn swarm() -> Swarm { + Swarm::new(&InfoHash::default(), 0, None) +} + #[fixture] fn swarms() -> Swarms { Swarms::default() @@ -28,26 +32,26 @@ fn empty() -> Entries { #[fixture] fn default() -> Entries { - vec![(InfoHash::default(), Swarm::default())] + vec![(InfoHash::default(), swarm())] } #[fixture] async fn started() -> Entries { - let mut swarm = Swarm::default(); + let mut swarm = swarm(); swarm.handle_announcement(&a_started_peer(1)).await; vec![(InfoHash::default(), swarm)] } #[fixture] async fn completed() -> Entries { - let mut swarm = Swarm::default(); + let mut swarm = swarm(); swarm.handle_announcement(&a_completed_peer(2)).await; vec![(InfoHash::default(), swarm)] } #[fixture] async fn downloaded() -> Entries { - let mut swarm = Swarm::default(); + let mut swarm = swarm(); let mut peer = a_started_peer(3); swarm.handle_announcement(&peer).await; peer.event = AnnounceEvent::Completed; @@ -58,17 +62,17 @@ async fn downloaded() -> Entries { #[fixture] async fn three() -> Entries { - let mut started = Swarm::default(); + let mut started = swarm(); let started_h = &mut DefaultHasher::default(); started.handle_announcement(&a_started_peer(1)).await; started.hash(started_h); - let mut completed = Swarm::default(); + let mut completed = swarm(); let completed_h = &mut DefaultHasher::default(); completed.handle_announcement(&a_completed_peer(2)).await; completed.hash(completed_h); - let mut downloaded = Swarm::default(); + let mut downloaded = swarm(); let downloaded_h = &mut DefaultHasher::default(); let mut downloaded_peer = a_started_peer(3); downloaded.handle_announcement(&downloaded_peer).await; @@ -89,7 +93,7 @@ async fn many_out_of_order() -> Entries { let mut entries: HashSet<(InfoHash, Swarm)> = HashSet::default(); for i in 0..408 { - let mut entry = Swarm::default(); + let mut entry = swarm(); entry.handle_announcement(&a_started_peer(i)).await; entries.insert((InfoHash::from(&i), entry)); @@ -104,7 +108,7 @@ async fn many_hashed_in_order() -> Entries { let mut entries: BTreeMap = BTreeMap::default(); for i in 0..408 { - let mut entry = Swarm::default(); + let mut entry = swarm(); entry.handle_announcement(&a_started_peer(i)).await; let hash: &mut DefaultHasher = &mut DefaultHasher::default(); From dfba00c7c2fe641e486d2fbeb023cd099db3e567 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 14 May 2025 13:15:14 +0100 Subject: [PATCH 1103/1297] feat: [#1358] allow disabling the event sender in the torrent-repository pkg --- .../src/environment.rs | 4 +- .../axum-http-tracker-server/src/server.rs | 6 ++- .../src/v1/handlers/announce.rs | 2 +- .../src/v1/handlers/scrape.rs | 2 +- .../src/environment.rs | 4 +- packages/events/src/bus.rs | 46 ++++++++++++++----- .../http-tracker-core/benches/helpers/util.rs | 2 +- packages/http-tracker-core/src/container.rs | 6 ++- .../src/services/announce.rs | 2 +- .../http-tracker-core/src/services/scrape.rs | 6 ++- .../src/statistics/services.rs | 2 +- .../rest-tracker-api-core/src/container.rs | 4 +- .../src/statistics/services.rs | 2 +- packages/torrent-repository/src/container.rs | 7 +-- .../udp-tracker-core/benches/helpers/sync.rs | 3 +- packages/udp-tracker-core/src/container.rs | 6 ++- .../udp-tracker-core/src/services/connect.rs | 7 +-- packages/udp-tracker-server/src/container.rs | 2 +- .../udp-tracker-server/src/environment.rs | 4 +- .../src/handlers/announce.rs | 14 ++++-- .../src/handlers/connect.rs | 22 ++++++--- .../udp-tracker-server/src/handlers/mod.rs | 8 +++- .../udp-tracker-server/src/handlers/scrape.rs | 3 +- src/container.rs | 4 +- 24 files changed, 118 insertions(+), 50 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index 078bda9e5..10dada2db 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -144,7 +144,9 @@ impl EnvContainer { .expect("missing HTTP tracker configuration"); let http_tracker_config = Arc::new(http_tracker_config[0].clone()); - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + configuration.core.tracker_usage_statistics.into(), + )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( &core_config, diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 3904449fa..f7d1ed7ea 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -280,7 +280,7 @@ mod tests { let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); let http_stats_event_bus = Arc::new(EventBus::new( - configuration.core.tracker_usage_statistics, + configuration.core.tracker_usage_statistics.into(), http_core_broadcaster.clone(), )); @@ -290,7 +290,9 @@ mod tests { let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); } - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + configuration.core.tracker_usage_statistics.into(), + )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( &core_config, diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 7489211a9..7d7a0b386 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -168,7 +168,7 @@ mod tests { let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); let http_stats_event_bus = Arc::new(EventBus::new( - config.core.tracker_usage_statistics, + config.core.tracker_usage_statistics.into(), http_core_broadcaster.clone(), )); diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index 330e7c13e..8decfe95c 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -139,7 +139,7 @@ mod tests { let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); let http_stats_event_bus = Arc::new(EventBus::new( - config.core.tracker_usage_statistics, + config.core.tracker_usage_statistics.into(), http_core_broadcaster.clone(), )); diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index e4a83d15d..92ca5a2d1 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -173,7 +173,9 @@ impl EnvContainer { .clone(), ); - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( &core_config, diff --git a/packages/events/src/bus.rs b/packages/events/src/bus.rs index d53f29b8d..b42fb4fc5 100644 --- a/packages/events/src/bus.rs +++ b/packages/events/src/bus.rs @@ -3,36 +3,60 @@ use std::sync::Arc; use crate::broadcaster::Broadcaster; use crate::{receiver, sender}; +#[derive(Clone, Debug)] +pub enum SenderStatus { + Enabled, + Disabled, +} + +impl From for SenderStatus { + fn from(enabled: bool) -> Self { + if enabled { + Self::Enabled + } else { + Self::Disabled + } + } +} + +impl From for bool { + fn from(sender_status: SenderStatus) -> Self { + match sender_status { + SenderStatus::Enabled => true, + SenderStatus::Disabled => false, + } + } +} + #[derive(Clone, Debug)] pub struct EventBus { - pub enable_sender: bool, + pub sender_status: SenderStatus, pub broadcaster: Broadcaster, } impl Default for EventBus { fn default() -> Self { - let enable_sender = true; + let sender_status = SenderStatus::Enabled; let broadcaster = Broadcaster::::default(); - Self::new(enable_sender, broadcaster) + Self::new(sender_status, broadcaster) } } impl EventBus { #[must_use] - pub fn new(enable_sender: bool, broadcaster: Broadcaster) -> Self { + pub fn new(sender_status: SenderStatus, broadcaster: Broadcaster) -> Self { Self { - enable_sender, + sender_status, broadcaster, } } #[must_use] pub fn sender(&self) -> Option>> { - if self.enable_sender { - Some(Arc::new(self.broadcaster.clone())) - } else { - None + match self.sender_status { + SenderStatus::Enabled => Some(Arc::new(self.broadcaster.clone())), + SenderStatus::Disabled => None, } } @@ -50,14 +74,14 @@ mod tests { #[tokio::test] async fn it_should_provide_an_event_sender_when_enabled() { - let bus = EventBus::::new(true, Broadcaster::default()); + let bus = EventBus::::new(SenderStatus::Enabled, Broadcaster::default()); assert!(bus.sender().is_some()); } #[tokio::test] async fn it_should_not_provide_event_sender_when_disabled() { - let bus = EventBus::::new(false, Broadcaster::default()); + let bus = EventBus::::new(SenderStatus::Disabled, Broadcaster::default()); assert!(bus.sender().is_none()); } diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 7ee91a2c4..cfb3f745f 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -62,7 +62,7 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); let http_stats_event_bus = Arc::new(EventBus::new( - config.core.tracker_usage_statistics, + config.core.tracker_usage_statistics.into(), http_core_broadcaster.clone(), )); diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 922273610..f063c0061 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -27,7 +27,9 @@ pub struct HttpTrackerCoreContainer { impl HttpTrackerCoreContainer { #[must_use] pub fn initialize(core_config: &Arc, http_tracker_config: &Arc) -> Arc { - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( core_config, @@ -80,7 +82,7 @@ impl HttpTrackerCoreServices { let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); let http_stats_event_bus = Arc::new(EventBus::new( - tracker_core_container.core_config.tracker_usage_statistics, + tracker_core_container.core_config.tracker_usage_statistics.into(), http_core_broadcaster.clone(), )); diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index e0f387273..9f39a04e4 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -256,7 +256,7 @@ mod tests { let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); let http_stats_event_bus = Arc::new(EventBus::new( - config.core.tracker_usage_statistics, + config.core.tracker_usage_statistics.into(), http_core_broadcaster.clone(), )); diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 70e30099c..3da1aa88f 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -255,6 +255,7 @@ mod tests { use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ClientIpSources, RemoteClientAddr, ResolvedIp}; use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; + use torrust_tracker_events::bus::SenderStatus; use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; @@ -276,7 +277,7 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); - let http_stats_event_bus = Arc::new(EventBus::new(false, http_core_broadcaster.clone())); + let http_stats_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, http_core_broadcaster.clone())); let http_stats_event_sender = http_stats_event_bus.sender(); @@ -446,6 +447,7 @@ mod tests { use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ClientIpSources, RemoteClientAddr, ResolvedIp}; use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; + use torrust_tracker_events::bus::SenderStatus; use torrust_tracker_primitives::core::ScrapeData; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_test_helpers::configuration; @@ -468,7 +470,7 @@ mod tests { // HTTP core stats let http_core_broadcaster = Broadcaster::default(); - let http_stats_event_bus = Arc::new(EventBus::new(false, http_core_broadcaster.clone())); + let http_stats_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, http_core_broadcaster.clone())); let http_stats_event_sender = http_stats_event_bus.sender(); diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index 3c8a4fa43..af1e30524 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -96,7 +96,7 @@ mod tests { let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); let http_stats_event_bus = Arc::new(EventBus::new( - config.core.tracker_usage_statistics, + config.core.tracker_usage_statistics.into(), http_core_broadcaster.clone(), )); diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs index e9a622e04..1c4a08e26 100644 --- a/packages/rest-tracker-api-core/src/container.rs +++ b/packages/rest-tracker-api-core/src/container.rs @@ -36,7 +36,9 @@ impl TrackerHttpApiCoreContainer { udp_tracker_config: &Arc, http_api_config: &Arc, ) -> Arc { - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( core_config, diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index aad31a323..d05a35981 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -160,7 +160,7 @@ mod tests { let http_core_broadcaster = Broadcaster::default(); let http_stats_repository = Arc::new(Repository::new()); let http_stats_event_bus = Arc::new(EventBus::new( - config.core.tracker_usage_statistics, + config.core.tracker_usage_statistics.into(), http_core_broadcaster.clone(), )); diff --git a/packages/torrent-repository/src/container.rs b/packages/torrent-repository/src/container.rs index 50a6b8b9c..d185180b1 100644 --- a/packages/torrent-repository/src/container.rs +++ b/packages/torrent-repository/src/container.rs @@ -1,5 +1,7 @@ use std::sync::Arc; +use torrust_tracker_events::bus::SenderStatus; + use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::{self}; @@ -15,13 +17,12 @@ pub struct TorrentRepositoryContainer { impl TorrentRepositoryContainer { #[must_use] - pub fn initialize() -> Self { + pub fn initialize(sender_status: SenderStatus) -> Self { // Torrent repository stats let broadcaster = Broadcaster::default(); let stats_repository = Arc::new(Repository::new()); - // todo: add a config option to enable/disable stats for this package - let event_bus = Arc::new(EventBus::new(true, broadcaster.clone())); + let event_bus = Arc::new(EventBus::new(sender_status, broadcaster.clone())); let stats_event_sender = event_bus.sender(); diff --git a/packages/udp-tracker-core/benches/helpers/sync.rs b/packages/udp-tracker-core/benches/helpers/sync.rs index 1814a865e..e8ec1ce03 100644 --- a/packages/udp-tracker-core/benches/helpers/sync.rs +++ b/packages/udp-tracker-core/benches/helpers/sync.rs @@ -5,6 +5,7 @@ use std::time::{Duration, Instant}; use bittorrent_udp_tracker_core::event::bus::EventBus; use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::connect::ConnectService; +use torrust_tracker_events::bus::SenderStatus; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::helpers::utils::{sample_ipv4_remote_addr, sample_issue_time}; @@ -16,7 +17,7 @@ pub async fn connect_once(samples: u64) -> Duration { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = event_bus.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index 2b6567ec0..07a8a09ef 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -32,7 +32,9 @@ pub struct UdpTrackerCoreContainer { impl UdpTrackerCoreContainer { #[must_use] pub fn initialize(core_config: &Arc, udp_tracker_config: &Arc) -> Arc { - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( core_config, @@ -91,7 +93,7 @@ impl UdpTrackerCoreServices { let udp_core_broadcaster = Broadcaster::default(); let udp_core_stats_repository = Arc::new(Repository::new()); let event_bus = Arc::new(EventBus::new( - tracker_core_container.core_config.tracker_usage_statistics, + tracker_core_container.core_config.tracker_usage_statistics.into(), udp_core_broadcaster.clone(), )); diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index 18c9fd0ba..6ba36f274 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -61,6 +61,7 @@ mod tests { use std::sync::Arc; use mockall::predicate::eq; + use torrust_tracker_events::bus::SenderStatus; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::connection_cookie::make; @@ -79,7 +80,7 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = event_bus.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -100,7 +101,7 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = event_bus.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); @@ -122,7 +123,7 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = event_bus.sender(); let connect_service = Arc::new(ConnectService::new(udp_core_stats_event_sender)); diff --git a/packages/udp-tracker-server/src/container.rs b/packages/udp-tracker-server/src/container.rs index a0bc8f35b..365db4ca7 100644 --- a/packages/udp-tracker-server/src/container.rs +++ b/packages/udp-tracker-server/src/container.rs @@ -39,7 +39,7 @@ impl UdpTrackerServerServices { let udp_server_broadcaster = Broadcaster::default(); let udp_server_stats_repository = Arc::new(Repository::new()); let udp_server_stats_event_bus = Arc::new(EventBus::new( - core_config.tracker_usage_statistics, + core_config.tracker_usage_statistics.into(), udp_server_broadcaster.clone(), )); diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 6dae3d860..f92d5dd29 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -175,7 +175,9 @@ impl EnvContainer { let udp_tracker_configurations = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( &core_config, diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 86e7888f2..65b521f27 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -206,6 +206,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use mockall::predicate::eq; + use torrust_tracker_events::bus::SenderStatus; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{ConnectionContext, Event, UdpRequestKind}; @@ -378,7 +379,10 @@ mod tests { core_udp_tracker_services: Arc, ) -> Response { let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let event_bus = Arc::new(crate::event::bus::EventBus::new(false, udp_server_broadcaster.clone())); + let event_bus = Arc::new(crate::event::bus::EventBus::new( + SenderStatus::Disabled, + udp_server_broadcaster.clone(), + )); let udp_server_stats_event_sender = event_bus.sender(); @@ -542,6 +546,7 @@ mod tests { use bittorrent_udp_tracker_core::services::announce::AnnounceService; use mockall::predicate::eq; use torrust_tracker_configuration::Core; + use torrust_tracker_events::bus::SenderStatus; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{ConnectionContext, Event, UdpRequestKind}; @@ -718,11 +723,14 @@ mod tests { whitelist_authorization: Arc, ) -> Response { let udp_core_broadcaster = Broadcaster::default(); - let core_event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let core_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_event_bus = Arc::new(crate::event::bus::EventBus::new(false, udp_server_broadcaster.clone())); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new( + SenderStatus::Disabled, + udp_server_broadcaster.clone(), + )); let udp_server_stats_event_sender = server_event_bus.sender(); diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 1244a6a3b..961189945 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -63,6 +63,7 @@ mod tests { use bittorrent_udp_tracker_core::event::sender::Broadcaster; use bittorrent_udp_tracker_core::services::connect::ConnectService; use mockall::predicate::eq; + use torrust_tracker_events::bus::SenderStatus; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{ConnectionContext, Event, UdpRequestKind}; @@ -84,11 +85,14 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let core_event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let core_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_event_bus = Arc::new(crate::event::bus::EventBus::new(false, udp_server_broadcaster.clone())); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new( + SenderStatus::Disabled, + udp_server_broadcaster.clone(), + )); let udp_server_stats_event_sender = server_event_bus.sender(); @@ -123,11 +127,14 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let core_event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let core_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_event_bus = Arc::new(crate::event::bus::EventBus::new(false, udp_server_broadcaster.clone())); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new( + SenderStatus::Disabled, + udp_server_broadcaster.clone(), + )); let udp_server_stats_event_sender = server_event_bus.sender(); @@ -162,12 +169,15 @@ mod tests { let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); let udp_core_broadcaster = Broadcaster::default(); - let core_event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let core_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_event_bus = Arc::new(crate::event::bus::EventBus::new(false, udp_server_broadcaster.clone())); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new( + SenderStatus::Disabled, + udp_server_broadcaster.clone(), + )); let udp_server_stats_event_sender = server_event_bus.sender(); diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index d39ad0972..ca834c006 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -227,6 +227,7 @@ pub(crate) mod tests { use mockall::mock; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{Configuration, Core}; + use torrust_tracker_events::bus::SenderStatus; use torrust_tracker_events::sender::SendError; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; @@ -287,11 +288,14 @@ pub(crate) mod tests { let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); let udp_core_broadcaster = Broadcaster::default(); - let core_event_bus = Arc::new(EventBus::new(false, udp_core_broadcaster.clone())); + let core_event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_core_broadcaster.clone())); let udp_core_stats_event_sender = core_event_bus.sender(); let udp_server_broadcaster = crate::event::sender::Broadcaster::default(); - let server_event_bus = Arc::new(crate::event::bus::EventBus::new(false, udp_server_broadcaster.clone())); + let server_event_bus = Arc::new(crate::event::bus::EventBus::new( + SenderStatus::Disabled, + udp_server_broadcaster.clone(), + )); let udp_server_stats_event_sender = server_event_bus.sender(); diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 34d5a5ce2..e35e118b4 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -92,6 +92,7 @@ mod tests { }; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use torrust_tracker_events::bus::SenderStatus; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::bus::EventBus; @@ -183,7 +184,7 @@ mod tests { core_udp_tracker_services: Arc, ) -> Response { let udp_server_broadcaster = Broadcaster::default(); - let event_bus = Arc::new(EventBus::new(false, udp_server_broadcaster.clone())); + let event_bus = Arc::new(EventBus::new(SenderStatus::Disabled, udp_server_broadcaster.clone())); let udp_server_stats_event_sender = event_bus.sender(); diff --git a/src/container.rs b/src/container.rs index 273425fc1..98c455780 100644 --- a/src/container.rs +++ b/src/container.rs @@ -60,7 +60,9 @@ impl AppContainer { // Torrent Repository - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize()); + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); // Core From 8ee258eee3f16aeceb6166185b71325263dd0ff8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 14 May 2025 14:11:37 +0100 Subject: [PATCH 1104/1297] refactor: [#1358] use the new field info-hash as ID for the Swarm (Hash,PartialEq) --- packages/torrent-repository/src/swarm.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 3fe0e27d7..2ad216a61 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -36,14 +36,13 @@ impl Debug for Swarm { impl Hash for Swarm { fn hash(&self, state: &mut H) { - self.peers.hash(state); - self.metadata.hash(state); + self.info_hash.hash(state); } } impl PartialEq for Swarm { fn eq(&self, other: &Self) -> bool { - self.peers == other.peers && self.metadata == other.metadata + self.info_hash == other.info_hash } } From c9a893c876546562c484131acba77034249b5008 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 14 May 2025 14:12:01 +0100 Subject: [PATCH 1105/1297] refactor: [#1358] rename metrics for clarity There are two concepts: - Unique peers: phisical client with different socket address. - Peer connections: a client (peer) can particiapte in multiple swarms. Current metrics count the second, meaning the peer would be counted doubled if it particiaptes in two swarms. --- .../src/statistics/event/handler.rs | 18 +++++++++++++----- .../torrent-repository/src/statistics/mod.rs | 17 +++++++++++++---- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/packages/torrent-repository/src/statistics/event/handler.rs b/packages/torrent-repository/src/statistics/event/handler.rs index d2783f9ba..2fd7271cc 100644 --- a/packages/torrent-repository/src/statistics/event/handler.rs +++ b/packages/torrent-repository/src/statistics/event/handler.rs @@ -8,7 +8,7 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; use crate::statistics::repository::Repository; use crate::statistics::{ - TORRENT_REPOSITORY_PEERS_TOTAL, TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL, TORRENT_REPOSITORY_TORRENTS_TOTAL, + TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL, TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL, TORRENT_REPOSITORY_TORRENTS_TOTAL, }; pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { @@ -31,14 +31,22 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer added", ); let _unused = stats_repository - .increment_gauge(&metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), &label_set_for_peer(&peer), now) + .increment_gauge( + &metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), + &label_set_for_peer(&peer), + now, + ) .await; } Event::PeerRemoved { info_hash, peer } => { tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer removed", ); let _unused = stats_repository - .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), &label_set_for_peer(&peer), now) + .decrement_gauge( + &metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), + &label_set_for_peer(&peer), + now, + ) .await; } Event::PeerUpdated { @@ -51,7 +59,7 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: if old_peer.role() != new_peer.role() { let _unused = stats_repository .increment_gauge( - &metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), + &metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), &label_set_for_peer(&new_peer), now, ) @@ -59,7 +67,7 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: let _unused = stats_repository .decrement_gauge( - &metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), + &metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), &label_set_for_peer(&old_peer), now, ) diff --git a/packages/torrent-repository/src/statistics/mod.rs b/packages/torrent-repository/src/statistics/mod.rs index 4deaf19cb..18dcf83ea 100644 --- a/packages/torrent-repository/src/statistics/mod.rs +++ b/packages/torrent-repository/src/statistics/mod.rs @@ -14,7 +14,8 @@ const TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_to // Peers metrics -const TORRENT_REPOSITORY_PEERS_TOTAL: &str = "torrent_repository_peers_total"; +const TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL: &str = "torrent_repository_peer_connections_total"; +const TORRENT_REPOSITORY_UNIQUE_PEERS_TOTAL: &str = "torrent_repository_unique_peers_total"; // todo: not implemented yet #[must_use] pub fn describe_metrics() -> Metrics { @@ -32,16 +33,24 @@ pub fn describe_metrics() -> Metrics { &metric_name!(TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL), Some(Unit::Count), Some(&MetricDescription::new( - "The total number of torrent downloads since the tracker process started.", + "The total number of torrent downloads (since the tracker process started).", )), ); // Peers metrics metrics.metric_collection.describe_gauge( - &metric_name!(TORRENT_REPOSITORY_PEERS_TOTAL), + &metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("The total number of peers.")), + Some(&MetricDescription::new( + "The total number of peer connections (one connection per torrent).", + )), + ); + + metrics.metric_collection.describe_gauge( + &metric_name!(TORRENT_REPOSITORY_UNIQUE_PEERS_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new("The total number of unique peers.")), ); metrics From 0e38707fda29f54ae8cad8e2d19b737c97d77843 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 14 May 2025 15:43:01 +0100 Subject: [PATCH 1106/1297] fix: [#1358] revert Hash impl for Swarm To fix broken tests. This implementation will kept for now. I think it's only used for testing and I'm planning to remvoe all integration tests becuase now web have unit tests covering the same functionality. --- packages/torrent-repository/src/swarm.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 2ad216a61..3fe0e27d7 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -36,13 +36,14 @@ impl Debug for Swarm { impl Hash for Swarm { fn hash(&self, state: &mut H) { - self.info_hash.hash(state); + self.peers.hash(state); + self.metadata.hash(state); } } impl PartialEq for Swarm { fn eq(&self, other: &Self) -> bool { - self.info_hash == other.info_hash + self.peers == other.peers && self.metadata == other.metadata } } From 3d7e6ff04ab94f576b8aedd6663756243c6f3e55 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 14 May 2025 17:03:02 +0100 Subject: [PATCH 1107/1297] test: [#1358] add tests to torrust_tracker_torrent_repository::swarm::Swarm --- Cargo.lock | 1 + packages/primitives/src/peer.rs | 18 +++ packages/torrent-repository/Cargo.toml | 1 + packages/torrent-repository/src/event.rs | 20 +++ packages/torrent-repository/src/swarm.rs | 189 +++++++++++++++++++++++ 5 files changed, 229 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index ddf163cc6..75a272292 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4858,6 +4858,7 @@ dependencies = [ "criterion", "crossbeam-skiplist", "futures", + "mockall", "rand 0.9.1", "rstest", "serde", diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index 316541ad6..cd4531b09 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -252,6 +252,18 @@ impl Peer { pub fn change_ip(&mut self, new_ip: &IpAddr) { self.peer_addr = SocketAddr::new(*new_ip, self.peer_addr.port()); } + + pub fn mark_as_completed(&mut self) { + self.event = AnnounceEvent::Completed; + } + + #[must_use] + pub fn into_completed(self) -> Self { + Self { + event: AnnounceEvent::Completed, + ..self + } + } } use std::panic::Location; @@ -520,6 +532,12 @@ pub mod fixture { self } + #[must_use] + pub fn with_event(mut self, event: AnnounceEvent) -> Self { + self.peer.event = event; + self + } + #[allow(dead_code)] #[must_use] pub fn build(self) -> Peer { diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 26662b583..98ae5817d 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -33,6 +33,7 @@ tracing = "0" [dev-dependencies] async-std = { version = "1", features = ["attributes", "tokio1"] } criterion = { version = "0", features = ["async_tokio"] } +mockall = "0" rand = "0" rstest = "0" torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } diff --git a/packages/torrent-repository/src/event.rs b/packages/torrent-repository/src/event.rs index ac1c06637..9709da19a 100644 --- a/packages/torrent-repository/src/event.rs +++ b/packages/torrent-repository/src/event.rs @@ -36,6 +36,26 @@ pub mod sender { pub type Sender = Option>>; pub type Broadcaster = torrust_tracker_events::broadcaster::Broadcaster; + + #[cfg(test)] + pub mod tests { + + use futures::future::BoxFuture; + use mockall::mock; + use torrust_tracker_events::sender::{SendError, Sender}; + + use crate::event::Event; + + mock! { + pub EventSender {} + + impl Sender for EventSender { + type Event = Event; + + fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; + } + } + } } pub mod receiver { diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 3fe0e27d7..473703e89 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -328,6 +328,16 @@ mod tests { use crate::swarm::Swarm; use crate::tests::sample_info_hash; + #[test] + fn it_should_allow_debugging() { + let swarm = Swarm::new(&sample_info_hash(), 0, None); + + assert_eq!( + format!("{swarm:?}"), + "Swarm { peers: {}, metadata: SwarmMetadata { downloaded: 0, complete: 0, incomplete: 0 } }" + ); + } + #[test] fn it_should_be_empty_when_no_peers_have_been_inserted() { let swarm = Swarm::new(&sample_info_hash(), 0, None); @@ -689,6 +699,12 @@ mod tests { assert_eq!(leechers, 1); } + #[tokio::test] + async fn it_should_be_a_peerless_swarm_when_it_does_not_contain_any_peers() { + let swarm = Swarm::new(&sample_info_hash(), 0, None); + assert!(swarm.is_peerless()); + } + mod updating_the_swarm_metadata { mod when_a_new_peer_is_added { @@ -907,4 +923,177 @@ mod tests { } } } + + mod triggering_events { + + use std::future; + use std::sync::Arc; + + use aquatic_udp_protocol::AnnounceEvent::Started; + use mockall::predicate::eq; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::event::sender::tests::MockEventSender; + use crate::event::Event; + use crate::swarm::Swarm; + use crate::tests::sample_info_hash; + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_new_peer_is_added() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().build(); + + let mut event_sender_mock = MockEventSender::new(); + + event_sender_mock + .expect_send() + .with(eq(Event::PeerAdded { info_hash, peer })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + + let mut swarm = Swarm::new(&sample_info_hash(), 0, Some(Arc::new(event_sender_mock))); + + let mut downloads_increased = false; + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + } + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_peer_is_directly_removed() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().build(); + + let mut event_sender_mock = MockEventSender::new(); + + event_sender_mock + .expect_send() + .with(eq(Event::PeerAdded { info_hash, peer })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + + event_sender_mock + .expect_send() + .with(eq(Event::PeerRemoved { info_hash, peer })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + + let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); + + // Insert the peer + let mut downloads_increased = false; + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + + swarm.remove(&peer).await; + } + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_peer_is_removed_due_to_inactivity() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().build(); + + let mut event_sender_mock = MockEventSender::new(); + + event_sender_mock + .expect_send() + .with(eq(Event::PeerAdded { info_hash, peer })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + + event_sender_mock + .expect_send() + .with(eq(Event::PeerRemoved { info_hash, peer })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + + let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); + + // Insert the peer + let mut downloads_increased = false; + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + + // Peers not updated after this time will be removed + let current_cutoff = peer.updated + DurationSinceUnixEpoch::from_secs(1); + + swarm.remove_inactive(current_cutoff).await; + } + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_peer_is_updated() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().with_event(Started).build(); + + let mut event_sender_mock = MockEventSender::new(); + + event_sender_mock + .expect_send() + .with(eq(Event::PeerAdded { info_hash, peer })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + + event_sender_mock + .expect_send() + .with(eq(Event::PeerUpdated { + info_hash, + old_peer: peer, + new_peer: peer, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + + let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); + + // Insert the peer + let mut downloads_increased = false; + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + + // Update the peer + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + } + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_peer_completes_a_download() { + let info_hash = sample_info_hash(); + let started_peer = PeerBuilder::leecher().with_event(Started).build(); + let completed_peer = started_peer.into_completed(); + + let mut event_sender_mock = MockEventSender::new(); + + event_sender_mock + .expect_send() + .with(eq(Event::PeerAdded { + info_hash, + peer: started_peer, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + + event_sender_mock + .expect_send() + .with(eq(Event::PeerUpdated { + info_hash, + old_peer: started_peer, + new_peer: completed_peer, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + + event_sender_mock + .expect_send() + .with(eq(Event::PeerDownloadCompleted { + info_hash, + peer: completed_peer, + })) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + + let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); + + // Insert the peer + let mut downloads_increased = false; + swarm.upsert_peer(started_peer.into(), &mut downloads_increased).await; + + // Announce as completed + swarm.upsert_peer(completed_peer.into(), &mut downloads_increased).await; + } + } } From f71211fedc91477058064150398b265705f6fdf0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 14 May 2025 17:53:02 +0100 Subject: [PATCH 1108/1297] test: [#1358] add tests to torrust_tracker_torrent_repository::swarms::Swarms --- packages/torrent-repository/src/event.rs | 16 +- packages/torrent-repository/src/swarm.rs | 2 +- packages/torrent-repository/src/swarms.rs | 247 +++++++++++++++++++++- 3 files changed, 259 insertions(+), 6 deletions(-) diff --git a/packages/torrent-repository/src/event.rs b/packages/torrent-repository/src/event.rs index 9709da19a..da086f89e 100644 --- a/packages/torrent-repository/src/event.rs +++ b/packages/torrent-repository/src/event.rs @@ -40,8 +40,9 @@ pub mod sender { #[cfg(test)] pub mod tests { - use futures::future::BoxFuture; + use futures::future::{self, BoxFuture}; use mockall::mock; + use mockall::predicate::eq; use torrust_tracker_events::sender::{SendError, Sender}; use crate::event::Event; @@ -55,6 +56,19 @@ pub mod sender { fn send(&self, event: Event) -> BoxFuture<'static,Option > > > ; } } + + pub fn expect_event(mock: &mut MockEventSender, event: Event) { + mock.expect_send() + .with(eq(event)) + .times(1) + .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + } + + pub fn expect_event_sequence(mock: &mut MockEventSender, event: Vec) { + for e in event { + expect_event(mock, e); + } + } } } diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 473703e89..160636906 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -647,7 +647,7 @@ mod tests { } #[tokio::test] - async fn it_should_return_the_metadata() { + async fn it_should_return_the_swarm_metadata() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut downloads_increased = false; diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 3200d77ff..8b8327778 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -440,8 +440,13 @@ mod tests { mod the_swarm_repository { + use std::sync::Arc; + use aquatic_udp_protocol::PeerId; + use crate::swarms::Swarms; + use crate::tests::{sample_info_hash, sample_peer}; + /// It generates a peer id from a number where the number is the last /// part of the peer ID. For example, for `12` it returns /// `-qB00000000000000012`. @@ -462,14 +467,50 @@ mod tests { // The `TorrentRepository` has these responsibilities: // - To maintain the peer lists for each torrent. - // - To maintain the the torrent entries, which contains all the info about the - // torrents, including the peer lists. - // - To return the torrent entries. + // - To maintain the the torrent entries, which contains all the info + // about the torrents, including the peer lists. + // - To return the torrent entries (swarm handles). // - To return the peer lists for a given torrent. // - To return the torrent metrics. // - To return the swarm metadata for a given torrent. // - To handle the persistence of the torrent entries. + #[tokio::test] + async fn it_should_return_zero_length_when_it_has_no_swarms() { + let swarms = Arc::new(Swarms::default()); + assert_eq!(swarms.len(), 0); + } + + #[tokio::test] + async fn it_should_return_the_length_when_it_has_swarms() { + let swarms = Arc::new(Swarms::default()); + let info_hash = sample_info_hash(); + let peer = sample_peer(); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + assert_eq!(swarms.len(), 1); + } + + #[tokio::test] + async fn it_should_be_empty_when_it_has_no_swarms() { + let swarms = Arc::new(Swarms::default()); + assert!(swarms.is_empty()); + + let info_hash = sample_info_hash(); + let peer = sample_peer(); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + assert!(!swarms.is_empty()); + } + + #[tokio::test] + async fn it_should_not_be_empty_when_it_has_at_least_one_swarm() { + let swarms = Arc::new(Swarms::default()); + let info_hash = sample_info_hash(); + let peer = sample_peer(); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + assert!(!swarms.is_empty()); + } + mod maintaining_the_peer_lists { use std::sync::Arc; @@ -1054,6 +1095,59 @@ mod tests { "{result_a:?} {result_b:?}" ); } + + mod it_should_count_peerless_torrents { + use std::sync::Arc; + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::swarms::Swarms; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn no_peerless_torrents() { + let swarms = Arc::new(Swarms::default()); + assert_eq!(swarms.count_peerless_torrents().await.unwrap(), 0); + } + + #[tokio::test] + async fn one_peerless_torrents() { + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + let swarms = Arc::new(Swarms::default()); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + let current_cutoff = peer.updated + DurationSinceUnixEpoch::from_secs(1); + swarms.remove_inactive_peers(current_cutoff).await.unwrap(); + + assert_eq!(swarms.count_peerless_torrents().await.unwrap(), 1); + } + } + + mod it_should_count_peers { + use std::sync::Arc; + + use crate::swarms::Swarms; + use crate::tests::{sample_info_hash, sample_peer}; + + #[tokio::test] + async fn no_peers() { + let swarms = Arc::new(Swarms::default()); + assert_eq!(swarms.count_peers().await.unwrap(), 0); + } + + #[tokio::test] + async fn one_peer() { + let info_hash = sample_info_hash(); + let peer = sample_peer(); + + let swarms = Arc::new(Swarms::default()); + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + assert_eq!(swarms.count_peers().await.unwrap(), 1); + } + } } mod returning_swarm_metadata { @@ -1102,7 +1196,7 @@ mod tests { use torrust_tracker_primitives::PersistentTorrents; use crate::swarms::Swarms; - use crate::tests::sample_info_hash; + use crate::tests::{leecher, sample_info_hash}; #[tokio::test] async fn it_should_allow_importing_persisted_torrent_entries() { @@ -1121,6 +1215,151 @@ mod tests { // Only the number of downloads is persisted. assert_eq!(swarm_metadata.downloaded, 1); } + + #[tokio::test] + async fn it_should_allow_overwriting_a_previously_imported_persisted_torrent() { + // code-review: do we want to allow this? + + let swarms = Arc::new(Swarms::default()); + + let infohash = sample_info_hash(); + + let mut persistent_torrents = PersistentTorrents::default(); + + persistent_torrents.insert(infohash, 1); + persistent_torrents.insert(infohash, 2); + + swarms.import_persistent(&persistent_torrents); + + let swarm_metadata = swarms.get_swarm_metadata_or_default(&infohash).await.unwrap(); + + // It takes the last value + assert_eq!(swarm_metadata.downloaded, 2); + } + + #[tokio::test] + async fn it_should_now_allow_importing_a_persisted_torrent_if_it_already_exists() { + let swarms = Arc::new(Swarms::default()); + + let infohash = sample_info_hash(); + + // Insert a new the torrent entry + swarms.handle_announcement(&infohash, &leecher(), None).await.unwrap(); + let initial_number_of_downloads = swarms.get_swarm_metadata_or_default(&infohash).await.unwrap().downloaded; + + // Try to import the torrent entry + let new_number_of_downloads = initial_number_of_downloads + 1; + let mut persistent_torrents = PersistentTorrents::default(); + persistent_torrents.insert(infohash, new_number_of_downloads); + swarms.import_persistent(&persistent_torrents); + + // The number of downloads should not be changed + assert_eq!( + swarms.get_swarm_metadata_or_default(&infohash).await.unwrap().downloaded, + initial_number_of_downloads + ); + } + } + } + + mod triggering_events { + + use std::sync::Arc; + + use torrust_tracker_primitives::peer::fixture::PeerBuilder; + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::event::sender::tests::{expect_event_sequence, MockEventSender}; + use crate::event::Event; + use crate::swarms::Swarms; + use crate::tests::sample_info_hash; + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_new_torrent_is_added() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().build(); + + let mut event_sender_mock = MockEventSender::new(); + + expect_event_sequence( + &mut event_sender_mock, + vec![ + Event::TorrentAdded { + info_hash, + announcement: peer, + }, + Event::PeerAdded { info_hash, peer }, + ], + ); + + let swarms = Swarms::new(Some(Arc::new(event_sender_mock))); + + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + } + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_torrent_is_directly_removed() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().build(); + + let mut event_sender_mock = MockEventSender::new(); + + expect_event_sequence( + &mut event_sender_mock, + vec![ + Event::TorrentAdded { + info_hash, + announcement: peer, + }, + Event::PeerAdded { info_hash, peer }, + Event::TorrentRemoved { info_hash }, + ], + ); + + let swarms = Swarms::new(Some(Arc::new(event_sender_mock))); + + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + swarms.remove(&info_hash).await.unwrap(); + } + + #[tokio::test] + async fn it_should_trigger_an_event_when_a_peerless_torrent_is_removed() { + let info_hash = sample_info_hash(); + let peer = PeerBuilder::leecher().build(); + + let mut event_sender_mock = MockEventSender::new(); + + expect_event_sequence( + &mut event_sender_mock, + vec![ + Event::TorrentAdded { + info_hash, + announcement: peer, + }, + Event::PeerAdded { info_hash, peer }, + Event::PeerRemoved { info_hash, peer }, + Event::TorrentRemoved { info_hash }, + ], + ); + + let swarms = Swarms::new(Some(Arc::new(event_sender_mock))); + + // Add the new torrent + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + // Remove the peer + let current_cutoff = peer.updated + DurationSinceUnixEpoch::from_secs(1); + swarms.remove_inactive_peers(current_cutoff).await.unwrap(); + + // Remove peerless torrents + + let tracker_policy = torrust_tracker_configuration::TrackerPolicy { + remove_peerless_torrents: true, + ..Default::default() + }; + + swarms.remove_peerless_torrents(&tracker_policy).await.unwrap(); } } } From b13797e768ea79fd071a47dd6cbb710f11a22a21 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 14 May 2025 19:33:26 +0100 Subject: [PATCH 1109/1297] test: [#1358] add tests for events in torrent-repository pkg --- packages/primitives/src/peer.rs | 46 ++- packages/torrent-repository/src/event.rs | 26 ++ .../src/statistics/event/handler.rs | 336 ++++++++++++++++++ 3 files changed, 406 insertions(+), 2 deletions(-) diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index cd4531b09..20ddd3074 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -22,12 +22,13 @@ //! }; //! ``` +use std::fmt; use std::net::{IpAddr, SocketAddr}; use std::ops::{Deref, DerefMut}; +use std::str::FromStr; use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; -use derive_more::Display; use serde::Serialize; use zerocopy::FromBytes as _; @@ -35,7 +36,7 @@ use crate::DurationSinceUnixEpoch; pub type PeerAnnouncement = Peer; -#[derive(Debug, Display, Serialize, Copy, Clone, PartialEq, Eq, Hash)] +#[derive(Debug, Serialize, Copy, Clone, PartialEq, Eq, Hash)] #[serde(rename_all_fields = "lowercase")] pub enum PeerRole { Seeder, @@ -53,6 +54,39 @@ impl PeerRole { } } +impl fmt::Display for PeerRole { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PeerRole::Seeder => write!(f, "seeder"), + PeerRole::Leecher => write!(f, "leecher"), + } + } +} + +impl FromStr for PeerRole { + type Err = ParsePeerRoleError; + + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + "seeder" => Ok(PeerRole::Seeder), + "leecher" => Ok(PeerRole::Leecher), + _ => Err(ParsePeerRoleError::InvalidPeerRole { + location: Location::caller(), + raw_param: s.to_string(), + }), + } + } +} + +#[derive(Error, Debug)] +pub enum ParsePeerRoleError { + #[error("invalid param {raw_param} in {location}")] + InvalidPeerRole { + location: &'static Location<'static>, + raw_param: String, + }, +} + /// Peer struct used by the core `Tracker`. /// /// A sample peer: @@ -264,6 +298,14 @@ impl Peer { ..self } } + + #[must_use] + pub fn into_seeder(self) -> Self { + Self { + left: NumberOfBytes::new(0), + ..self + } + } } use std::panic::Location; diff --git a/packages/torrent-repository/src/event.rs b/packages/torrent-repository/src/event.rs index da086f89e..65a65ce8c 100644 --- a/packages/torrent-repository/src/event.rs +++ b/packages/torrent-repository/src/event.rs @@ -83,3 +83,29 @@ pub mod bus { pub type EventBus = torrust_tracker_events::bus::EventBus; } + +#[cfg(test)] +pub mod test { + + use torrust_tracker_primitives::peer::Peer; + + use super::Event; + use crate::tests::sample_info_hash; + + #[test] + fn events_should_be_comparable() { + let info_hash = sample_info_hash(); + + let event1 = Event::TorrentAdded { + info_hash, + announcement: Peer::default(), + }; + + let event2 = Event::TorrentRemoved { info_hash }; + + let event1_clone = event1.clone(); + + assert!(event1 == event1_clone); + assert!(event1 != event2); + } +} diff --git a/packages/torrent-repository/src/statistics/event/handler.rs b/packages/torrent-repository/src/statistics/event/handler.rs index 2fd7271cc..2b61839b8 100644 --- a/packages/torrent-repository/src/statistics/event/handler.rs +++ b/packages/torrent-repository/src/statistics/event/handler.rs @@ -13,6 +13,7 @@ use crate::statistics::{ pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { match event { + // Torrent events Event::TorrentAdded { info_hash, .. } => { tracing::debug!(info_hash = ?info_hash, "Torrent added",); @@ -27,6 +28,8 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), &LabelSet::default(), now) .await; } + + // Peer events Event::PeerAdded { info_hash, peer } => { tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer added", ); @@ -96,3 +99,336 @@ fn label_set_for_peer(peer: &Peer) -> LabelSet { (label_name!("peer_role"), LabelValue::new("leecher")).into() } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use aquatic_udp_protocol::NumberOfBytes; + use torrust_tracker_metrics::label::LabelSet; + use torrust_tracker_metrics::metric::MetricName; + use torrust_tracker_primitives::peer::{Peer, PeerRole}; + + use crate::statistics::repository::Repository; + use crate::tests::{leecher, seeder}; + + fn make_peer(role: PeerRole) -> Peer { + match role { + PeerRole::Seeder => seeder(), + PeerRole::Leecher => leecher(), + } + } + + // It returns a peer with the opposite role of the given peer. + fn make_opposite_role_peer(peer: &Peer) -> Peer { + let mut opposite_role_peer = *peer; + + match peer.role() { + PeerRole::Seeder => { + opposite_role_peer.left = NumberOfBytes::new(1); + } + PeerRole::Leecher => { + opposite_role_peer.left = NumberOfBytes::new(0); + } + } + + opposite_role_peer + } + + async fn expect_counter_metric_to_be( + stats_repository: &Arc, + metric_name: &MetricName, + label_set: &LabelSet, + expected_value: u64, + ) { + let value = get_counter_metric(stats_repository, metric_name, label_set).await; + assert_eq!(value.to_string(), expected_value.to_string()); + } + + async fn get_counter_metric(stats_repository: &Arc, metric_name: &MetricName, label_set: &LabelSet) -> u64 { + stats_repository + .get_metrics() + .await + .metric_collection + .get_counter_value(metric_name, label_set) + .unwrap_or_else(|| panic!("Failed to get counter value for metric name '{metric_name}' and label set '{label_set}'")) + .value() + } + + async fn expect_gauge_metric_to_be( + stats_repository: &Arc, + metric_name: &MetricName, + label_set: &LabelSet, + expected_value: f64, + ) { + let value = get_gauge_metric(stats_repository, metric_name, label_set).await; + assert_eq!(value.to_string(), expected_value.to_string()); + } + + async fn get_gauge_metric(stats_repository: &Arc, metric_name: &MetricName, label_set: &LabelSet) -> f64 { + stats_repository + .get_metrics() + .await + .metric_collection + .get_gauge_value(metric_name, label_set) + .unwrap_or_else(|| panic!("Failed to get gauge value for metric name '{metric_name}' and label set '{label_set}'")) + .value() + } + + mod for_torrent_metrics { + + use std::sync::Arc; + + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self, Time}; + use torrust_tracker_metrics::label::LabelSet; + use torrust_tracker_metrics::metric_name; + + use crate::event::Event; + use crate::statistics::event::handler::handle_event; + use crate::statistics::event::handler::tests::expect_gauge_metric_to_be; + use crate::statistics::repository::Repository; + use crate::statistics::TORRENT_REPOSITORY_TORRENTS_TOTAL; + use crate::tests::{sample_info_hash, sample_peer}; + use crate::CurrentClock; + + #[tokio::test] + async fn it_should_increment_the_number_of_torrents_when_a_torrent_added_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + handle_event( + Event::TorrentAdded { + info_hash: sample_info_hash(), + announcement: sample_peer(), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_gauge_metric_to_be( + &stats_repository, + &metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), + &LabelSet::default(), + 1.0, + ) + .await; + } + + #[tokio::test] + async fn it_should_decrement_the_number_of_torrents_when_a_torrent_removed_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + let metric_name = metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL); + let label_set = LabelSet::default(); + + // Increment the gauge first to simulate a torrent being added. + stats_repository + .increment_gauge(&metric_name, &label_set, CurrentClock::now()) + .await + .unwrap(); + + handle_event( + Event::TorrentRemoved { + info_hash: sample_info_hash(), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_gauge_metric_to_be(&stats_repository, &metric_name, &label_set, 0.0).await; + } + } + + mod for_peer_metrics { + + mod peer_connections_total { + + use std::sync::Arc; + + use rstest::rstest; + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self, Time}; + use torrust_tracker_metrics::label::LabelValue; + use torrust_tracker_metrics::{label_name, metric_name}; + use torrust_tracker_primitives::peer::PeerRole; + + use crate::event::Event; + use crate::statistics::event::handler::handle_event; + use crate::statistics::event::handler::tests::{ + expect_gauge_metric_to_be, get_gauge_metric, make_opposite_role_peer, make_peer, + }; + use crate::statistics::repository::Repository; + use crate::statistics::TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL; + use crate::tests::sample_info_hash; + use crate::CurrentClock; + + #[rstest] + #[case("seeder")] + #[case("leecher")] + #[tokio::test] + async fn it_should_increment_the_number_of_peer_connections_when_a_peer_added_event_is_received( + #[case] role: PeerRole, + ) { + clock::Stopped::local_set_to_unix_epoch(); + + let peer = make_peer(role); + + let stats_repository = Arc::new(Repository::new()); + let metric_name = metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL); + let label_set = (label_name!("peer_role"), LabelValue::new(&role.to_string())).into(); + + handle_event( + Event::PeerAdded { + info_hash: sample_info_hash(), + peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_gauge_metric_to_be(&stats_repository, &metric_name, &label_set, 1.0).await; + } + + #[rstest] + #[case("seeder")] + #[case("leecher")] + #[tokio::test] + async fn it_should_decrement_the_number_of_peer_connections_when_a_peer_removed_event_is_received( + #[case] role: PeerRole, + ) { + clock::Stopped::local_set_to_unix_epoch(); + + let peer = make_peer(role); + + let stats_repository = Arc::new(Repository::new()); + + let metric_name = metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL); + let label_set = (label_name!("peer_role"), LabelValue::new(&role.to_string())).into(); + + // Increment the gauge first to simulate a peer being added. + stats_repository + .increment_gauge(&metric_name, &label_set, CurrentClock::now()) + .await + .unwrap(); + + handle_event( + Event::PeerRemoved { + info_hash: sample_info_hash(), + peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_gauge_metric_to_be(&stats_repository, &metric_name, &label_set, 0.0).await; + } + + #[rstest] + #[case("seeder")] + #[case("leecher")] + #[tokio::test] + async fn it_should_adjust_the_number_of_seeders_and_leechers_when_a_peer_updated_event_is_received_and_the_peer_changed_its_role( + #[case] old_role: PeerRole, + ) { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + let old_peer = make_peer(old_role); + let new_peer = make_opposite_role_peer(&old_peer); + + let metric_name = metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL); + let old_role_label_set = (label_name!("peer_role"), LabelValue::new(&old_peer.role().to_string())).into(); + let new_role_label_set = (label_name!("peer_role"), LabelValue::new(&new_peer.role().to_string())).into(); + + // Increment the gauge first by simulating a peer was added. + handle_event( + Event::PeerAdded { + info_hash: sample_info_hash(), + peer: old_peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + let old_role_total = get_gauge_metric(&stats_repository, &metric_name, &old_role_label_set).await; + let new_role_total = 0.0; + + // The peer's role has changed, so we need to increment the new + // role and decrement the old one. + handle_event( + Event::PeerUpdated { + info_hash: sample_info_hash(), + old_peer, + new_peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + // The peer's role has changed, so the new role has incremented. + expect_gauge_metric_to_be(&stats_repository, &metric_name, &new_role_label_set, new_role_total + 1.0).await; + + // And the old role has decremented. + expect_gauge_metric_to_be(&stats_repository, &metric_name, &old_role_label_set, old_role_total - 1.0).await; + } + } + + mod torrent_downloads_total { + + use std::sync::Arc; + + use rstest::rstest; + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self, Time}; + use torrust_tracker_metrics::label::LabelValue; + use torrust_tracker_metrics::{label_name, metric_name}; + use torrust_tracker_primitives::peer::PeerRole; + + use crate::event::Event; + use crate::statistics::event::handler::handle_event; + use crate::statistics::event::handler::tests::{expect_counter_metric_to_be, make_peer}; + use crate::statistics::repository::Repository; + use crate::statistics::TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL; + use crate::tests::sample_info_hash; + use crate::CurrentClock; + + #[rstest] + #[case("seeder")] + #[case("leecher")] + #[tokio::test] + async fn it_should_increment_the_number_of_downloads_when_a_peer_downloaded_event_is_received( + #[case] role: PeerRole, + ) { + clock::Stopped::local_set_to_unix_epoch(); + + let peer = make_peer(role); + + let stats_repository = Arc::new(Repository::new()); + let metric_name = metric_name!(TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL); + let label_set = (label_name!("peer_role"), LabelValue::new(&role.to_string())).into(); + + handle_event( + Event::PeerDownloadCompleted { + info_hash: sample_info_hash(), + peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_counter_metric_to_be(&stats_repository, &metric_name, &label_set, 1).await; + } + } + } +} From 47d1eab5a7328b8a524d9bbcabc3b3bc4ddce6b5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 15 May 2025 19:09:43 +0100 Subject: [PATCH 1110/1297] refactor: [#1358] Swarm tests to use new mock helpers --- packages/torrent-repository/src/swarm.rs | 111 ++++++++--------------- 1 file changed, 39 insertions(+), 72 deletions(-) diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 160636906..3277cad8d 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -926,15 +926,13 @@ mod tests { mod triggering_events { - use std::future; use std::sync::Arc; use aquatic_udp_protocol::AnnounceEvent::Started; - use mockall::predicate::eq; use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::event::sender::tests::MockEventSender; + use crate::event::sender::tests::{expect_event_sequence, MockEventSender}; use crate::event::Event; use crate::swarm::Swarm; use crate::tests::sample_info_hash; @@ -946,11 +944,7 @@ mod tests { let mut event_sender_mock = MockEventSender::new(); - event_sender_mock - .expect_send() - .with(eq(Event::PeerAdded { info_hash, peer })) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + expect_event_sequence(&mut event_sender_mock, vec![Event::PeerAdded { info_hash, peer }]); let mut swarm = Swarm::new(&sample_info_hash(), 0, Some(Arc::new(event_sender_mock))); @@ -965,17 +959,10 @@ mod tests { let mut event_sender_mock = MockEventSender::new(); - event_sender_mock - .expect_send() - .with(eq(Event::PeerAdded { info_hash, peer })) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - - event_sender_mock - .expect_send() - .with(eq(Event::PeerRemoved { info_hash, peer })) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + expect_event_sequence( + &mut event_sender_mock, + vec![Event::PeerAdded { info_hash, peer }, Event::PeerRemoved { info_hash, peer }], + ); let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); @@ -993,17 +980,10 @@ mod tests { let mut event_sender_mock = MockEventSender::new(); - event_sender_mock - .expect_send() - .with(eq(Event::PeerAdded { info_hash, peer })) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - - event_sender_mock - .expect_send() - .with(eq(Event::PeerRemoved { info_hash, peer })) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + expect_event_sequence( + &mut event_sender_mock, + vec![Event::PeerAdded { info_hash, peer }, Event::PeerRemoved { info_hash, peer }], + ); let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); @@ -1024,21 +1004,17 @@ mod tests { let mut event_sender_mock = MockEventSender::new(); - event_sender_mock - .expect_send() - .with(eq(Event::PeerAdded { info_hash, peer })) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - - event_sender_mock - .expect_send() - .with(eq(Event::PeerUpdated { - info_hash, - old_peer: peer, - new_peer: peer, - })) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + expect_event_sequence( + &mut event_sender_mock, + vec![ + Event::PeerAdded { info_hash, peer }, + Event::PeerUpdated { + info_hash, + old_peer: peer, + new_peer: peer, + }, + ], + ); let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); @@ -1058,33 +1034,24 @@ mod tests { let mut event_sender_mock = MockEventSender::new(); - event_sender_mock - .expect_send() - .with(eq(Event::PeerAdded { - info_hash, - peer: started_peer, - })) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - - event_sender_mock - .expect_send() - .with(eq(Event::PeerUpdated { - info_hash, - old_peer: started_peer, - new_peer: completed_peer, - })) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(1))))); - - event_sender_mock - .expect_send() - .with(eq(Event::PeerDownloadCompleted { - info_hash, - peer: completed_peer, - })) - .times(1) - .returning(|_| Box::pin(future::ready(Some(Ok(1))))); + expect_event_sequence( + &mut event_sender_mock, + vec![ + Event::PeerAdded { + info_hash, + peer: started_peer, + }, + Event::PeerUpdated { + info_hash, + old_peer: started_peer, + new_peer: completed_peer, + }, + Event::PeerDownloadCompleted { + info_hash, + peer: completed_peer, + }, + ], + ); let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); From b3b0b71396bebb0916a47f4833313b473260f59d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 15 May 2025 21:51:44 +0100 Subject: [PATCH 1111/1297] refactor: [#1358] Swarm, cleaning upsert_peer method --- packages/primitives/src/peer.rs | 5 + packages/torrent-repository/src/swarm.rs | 111 +++++++++++++---------- 2 files changed, 67 insertions(+), 49 deletions(-) diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index 20ddd3074..57ca3909d 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -270,6 +270,11 @@ impl Peer { !self.is_seeder() } + #[must_use] + pub fn is_completed(&self) -> bool { + self.event == AnnounceEvent::Completed + } + #[must_use] pub fn role(&self) -> PeerRole { if self.is_seeder() { diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 3277cad8d..d01f79fe8 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -73,21 +73,39 @@ impl Swarm { downloads_increased } - pub async fn upsert_peer( + async fn upsert_peer( &mut self, incoming_announce: Arc, downloads_increased: &mut bool, ) -> Option> { - let is_now_seeder = incoming_announce.is_seeder(); - let has_completed = incoming_announce.event == AnnounceEvent::Completed; let announcement = incoming_announce.clone(); - if let Some(old_announce) = self.peers.insert(incoming_announce.peer_addr, incoming_announce) { - // A peer has been updated in the swarm. + if let Some(previous_announce) = self.peers.insert(incoming_announce.peer_addr, incoming_announce) { + *downloads_increased = self.update_metadata(Some(&previous_announce), &announcement); - // Check if the peer has changed from leecher to seeder or vice versa. - if old_announce.is_seeder() != is_now_seeder { - if is_now_seeder { + self.trigger_peer_updated_event(&previous_announce, &announcement, *downloads_increased) + .await; + + Some(previous_announce) + } else { + *downloads_increased = self.update_metadata(None, &announcement); + + self.trigger_peer_added_event(&announcement).await; + + None + } + } + + fn update_metadata( + &mut self, + opt_previous_announce: Option<&Arc>, + new_announce: &Arc, + ) -> bool { + let mut downloads_increased = false; + + if let Some(previous_announce) = opt_previous_announce { + if previous_announce.role() != new_announce.role() { + if new_announce.is_seeder() { self.metadata.complete += 1; self.metadata.incomplete -= 1; } else { @@ -96,58 +114,53 @@ impl Swarm { } } - // Check if the peer has completed downloading the torrent. - if has_completed && old_announce.event != AnnounceEvent::Completed { + if new_announce.is_completed() && !previous_announce.is_completed() { self.metadata.downloaded += 1; - *downloads_increased = true; + downloads_increased = true; } - - if let Some(event_sender) = self.event_sender.as_deref() { - event_sender - .send(Event::PeerUpdated { - info_hash: self.info_hash, - old_peer: *old_announce, - new_peer: *announcement, - }) - .await; - - if *downloads_increased { - event_sender - .send(Event::PeerDownloadCompleted { - info_hash: self.info_hash, - peer: *announcement, - }) - .await; - } - } - - Some(old_announce) + } else if new_announce.is_seeder() { + self.metadata.complete += 1; } else { - // A new peer has been added to the swarm. - - // Check if the peer is a seeder or a leecher. - if is_now_seeder { - self.metadata.complete += 1; - } else { - self.metadata.incomplete += 1; - } + self.metadata.incomplete += 1; + } - // Check if the peer has completed downloading the torrent. - if has_completed { - // Don't increment `downloaded` here: we only count transitions - // from a known peer - } + downloads_increased + } - if let Some(event_sender) = self.event_sender.as_deref() { + async fn trigger_peer_updated_event( + &self, + old_announce: &Arc, + new_announce: &Arc, + downloads_increased: bool, + ) { + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerUpdated { + info_hash: self.info_hash, + old_peer: *old_announce.clone(), + new_peer: *new_announce.clone(), + }) + .await; + + if downloads_increased { event_sender - .send(Event::PeerAdded { + .send(Event::PeerDownloadCompleted { info_hash: self.info_hash, - peer: *announcement, + peer: *new_announce.clone(), }) .await; } + } + } - None + async fn trigger_peer_added_event(&self, announcement: &Arc) { + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerAdded { + info_hash: self.info_hash, + peer: *announcement.clone(), + }) + .await; } } From d154b2aa045063c807deb0a6a88fad55297e46b4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 16 May 2025 08:51:09 +0100 Subject: [PATCH 1112/1297] refactor: [#1358] clean Swarm type --- packages/torrent-repository/src/swarm.rs | 308 +++++++++++------------ 1 file changed, 148 insertions(+), 160 deletions(-) diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index d01f79fe8..8cf2982e6 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -67,169 +67,20 @@ impl Swarm { AnnounceEvent::Started | AnnounceEvent::None | AnnounceEvent::Completed => { self.upsert_peer(Arc::new(*incoming_announce), &mut downloads_increased).await } - AnnounceEvent::Stopped => self.remove(incoming_announce).await, + AnnounceEvent::Stopped => self.remove_peer(&incoming_announce.peer_addr).await, }; downloads_increased } - async fn upsert_peer( - &mut self, - incoming_announce: Arc, - downloads_increased: &mut bool, - ) -> Option> { - let announcement = incoming_announce.clone(); - - if let Some(previous_announce) = self.peers.insert(incoming_announce.peer_addr, incoming_announce) { - *downloads_increased = self.update_metadata(Some(&previous_announce), &announcement); - - self.trigger_peer_updated_event(&previous_announce, &announcement, *downloads_increased) - .await; - - Some(previous_announce) - } else { - *downloads_increased = self.update_metadata(None, &announcement); - - self.trigger_peer_added_event(&announcement).await; - - None - } - } - - fn update_metadata( - &mut self, - opt_previous_announce: Option<&Arc>, - new_announce: &Arc, - ) -> bool { - let mut downloads_increased = false; - - if let Some(previous_announce) = opt_previous_announce { - if previous_announce.role() != new_announce.role() { - if new_announce.is_seeder() { - self.metadata.complete += 1; - self.metadata.incomplete -= 1; - } else { - self.metadata.complete -= 1; - self.metadata.incomplete += 1; - } - } - - if new_announce.is_completed() && !previous_announce.is_completed() { - self.metadata.downloaded += 1; - downloads_increased = true; - } - } else if new_announce.is_seeder() { - self.metadata.complete += 1; - } else { - self.metadata.incomplete += 1; - } - - downloads_increased - } - - async fn trigger_peer_updated_event( - &self, - old_announce: &Arc, - new_announce: &Arc, - downloads_increased: bool, - ) { - if let Some(event_sender) = self.event_sender.as_deref() { - event_sender - .send(Event::PeerUpdated { - info_hash: self.info_hash, - old_peer: *old_announce.clone(), - new_peer: *new_announce.clone(), - }) - .await; - - if downloads_increased { - event_sender - .send(Event::PeerDownloadCompleted { - info_hash: self.info_hash, - peer: *new_announce.clone(), - }) - .await; - } - } - } - - async fn trigger_peer_added_event(&self, announcement: &Arc) { - if let Some(event_sender) = self.event_sender.as_deref() { - event_sender - .send(Event::PeerAdded { - info_hash: self.info_hash, - peer: *announcement.clone(), - }) - .await; - } - } - - pub async fn remove(&mut self, peer_to_remove: &Peer) -> Option> { - match self.peers.remove(&peer_to_remove.peer_addr) { - Some(old_peer) => { - // A peer has been removed from the swarm. - - // Check if the peer was a seeder or a leecher. - if old_peer.is_seeder() { - self.metadata.complete -= 1; - } else { - self.metadata.incomplete -= 1; - } - - if let Some(event_sender) = self.event_sender.as_deref() { - event_sender - .send(Event::PeerRemoved { - info_hash: self.info_hash, - peer: *old_peer.clone(), - }) - .await; - } - - Some(old_peer) - } - None => None, - } - } - pub async fn remove_inactive(&mut self, current_cutoff: DurationSinceUnixEpoch) -> usize { - let mut number_of_peers_removed = 0; - let mut removed_peers = Vec::new(); - - self.peers.retain(|_key, peer| { - let is_active = peer::ReadInfo::get_updated(peer) > current_cutoff; - - if !is_active { - // Update the metadata when removing a peer. - if peer.is_seeder() { - self.metadata.complete -= 1; - } else { - self.metadata.incomplete -= 1; - } - - number_of_peers_removed += 1; - - if let Some(_event_sender) = self.event_sender.as_deref() { - // Events can not be trigger here because retain does not allow - // async closures. - removed_peers.push(*peer.clone()); - } - } + let peers_to_remove = self.inactive_peers(current_cutoff); - is_active - }); - - if let Some(event_sender) = self.event_sender.as_deref() { - for peer in &removed_peers { - event_sender - .send(Event::PeerRemoved { - info_hash: self.info_hash, - peer: *peer, - }) - .await; - } + for peer_addr in &peers_to_remove { + self.remove_peer(peer_addr).await; } - number_of_peers_removed + peers_to_remove.len() } #[must_use] @@ -316,6 +167,57 @@ impl Swarm { !self.should_be_removed(policy) } + async fn upsert_peer( + &mut self, + incoming_announce: Arc, + downloads_increased: &mut bool, + ) -> Option> { + let announcement = incoming_announce.clone(); + + if let Some(previous_announce) = self.peers.insert(incoming_announce.peer_addr, incoming_announce) { + *downloads_increased = self.update_metadata_on_update(&previous_announce, &announcement); + + self.trigger_peer_updated_event(&previous_announce, &announcement).await; + + if *downloads_increased { + self.trigger_peer_download_completed_event(&announcement).await; + } + + Some(previous_announce) + } else { + *downloads_increased = false; + + self.update_metadata_on_insert(&announcement); + + self.trigger_peer_added_event(&announcement).await; + + None + } + } + + async fn remove_peer(&mut self, peer_addr: &SocketAddr) -> Option> { + if let Some(old_peer) = self.peers.remove(peer_addr) { + self.update_metadata_on_removal(&old_peer); + + self.trigger_peer_removed_event(&old_peer).await; + + Some(old_peer) + } else { + None + } + } + + #[must_use] + fn inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> Vec { + self.peers + .iter() + .filter(|(_, peer)| peer::ReadInfo::get_updated(&**peer) <= current_cutoff) + .map(|(addr, _)| *addr) + .collect() + } + + /// Returns true if the swarm should be removed according to the retention + /// policy. fn should_be_removed(&self, policy: &TrackerPolicy) -> bool { // If the policy is to remove peerless torrents and the swarm is empty (no peers), (policy.remove_peerless_torrents && self.is_empty()) @@ -325,6 +227,92 @@ impl Swarm { // See https://github.com/torrust/torrust-tracker/issues/1502) && !(policy.persistent_torrent_completed_stat && self.metadata().downloaded > 0) } + + fn update_metadata_on_insert(&mut self, added_peer: &Arc) { + if added_peer.is_seeder() { + self.metadata.complete += 1; + } else { + self.metadata.incomplete += 1; + } + } + + fn update_metadata_on_removal(&mut self, removed_peer: &Arc) { + if removed_peer.is_seeder() { + self.metadata.complete -= 1; + } else { + self.metadata.incomplete -= 1; + } + } + + fn update_metadata_on_update( + &mut self, + previous_announce: &Arc, + new_announce: &Arc, + ) -> bool { + let mut downloads_increased = false; + + if previous_announce.role() != new_announce.role() { + if new_announce.is_seeder() { + self.metadata.complete += 1; + self.metadata.incomplete -= 1; + } else { + self.metadata.complete -= 1; + self.metadata.incomplete += 1; + } + } + + if new_announce.is_completed() && !previous_announce.is_completed() { + self.metadata.downloaded += 1; + downloads_increased = true; + } + + downloads_increased + } + + async fn trigger_peer_added_event(&self, announcement: &Arc) { + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerAdded { + info_hash: self.info_hash, + peer: *announcement.clone(), + }) + .await; + } + } + + async fn trigger_peer_removed_event(&self, old_peer: &Arc) { + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerRemoved { + info_hash: self.info_hash, + peer: *old_peer.clone(), + }) + .await; + } + } + + async fn trigger_peer_updated_event(&self, old_announce: &Arc, new_announce: &Arc) { + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerUpdated { + info_hash: self.info_hash, + old_peer: *old_announce.clone(), + new_peer: *new_announce.clone(), + }) + .await; + } + } + + async fn trigger_peer_download_completed_event(&self, new_announce: &Arc) { + if let Some(event_sender) = self.event_sender.as_deref() { + event_sender + .send(Event::PeerDownloadCompleted { + info_hash: self.info_hash, + peer: *new_announce.clone(), + }) + .await; + } + } } #[cfg(test)] @@ -435,7 +423,7 @@ mod tests { swarm.upsert_peer(peer.into(), &mut downloads_increased).await; - swarm.remove(&peer).await; + swarm.remove_peer(&peer.peer_addr).await; assert!(swarm.is_empty()); } @@ -449,7 +437,7 @@ mod tests { swarm.upsert_peer(peer.into(), &mut downloads_increased).await; - let old = swarm.remove(&peer).await; + let old = swarm.remove_peer(&peer.peer_addr).await; assert_eq!(old, Some(Arc::new(peer))); assert_eq!(swarm.get(&peer.peer_addr), None); @@ -461,7 +449,7 @@ mod tests { let peer = PeerBuilder::default().build(); - assert_eq!(swarm.remove(&peer).await, None); + assert_eq!(swarm.remove_peer(&peer.peer_addr).await, None); } #[tokio::test] @@ -787,7 +775,7 @@ mod tests { let leechers = swarm.metadata().leechers(); - swarm.remove(&leecher).await; + swarm.remove_peer(&leecher.peer_addr).await; assert_eq!(swarm.metadata().leechers(), leechers - 1); } @@ -803,7 +791,7 @@ mod tests { let seeders = swarm.metadata().seeders(); - swarm.remove(&seeder).await; + swarm.remove_peer(&seeder.peer_addr).await; assert_eq!(swarm.metadata().seeders(), seeders - 1); } @@ -983,7 +971,7 @@ mod tests { let mut downloads_increased = false; swarm.upsert_peer(peer.into(), &mut downloads_increased).await; - swarm.remove(&peer).await; + swarm.remove_peer(&peer.peer_addr).await; } #[tokio::test] From 52ac171063270edfb9b63549ae848157acd258da Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 16 May 2025 10:12:18 +0100 Subject: [PATCH 1113/1297] chore(deps): update dependencies ```output cargo update Updating crates.io index Locking 32 packages to latest compatible versions Updating bitflags v2.9.0 -> v2.9.1 Updating cc v1.2.21 -> v1.2.22 Updating clap v4.5.37 -> v4.5.38 Updating clap_builder v4.5.37 -> v4.5.38 Updating errno v0.3.11 -> v0.3.12 Updating getrandom v0.3.2 -> v0.3.3 Updating icu_collections v1.5.0 -> v2.0.0 Adding icu_locale_core v2.0.0 Removing icu_locid v1.5.0 Removing icu_locid_transform v1.5.0 Removing icu_locid_transform_data v1.5.1 Updating icu_normalizer v1.5.0 -> v2.0.0 Updating icu_normalizer_data v1.5.1 -> v2.0.0 Updating icu_properties v1.5.1 -> v2.0.0 Updating icu_properties_data v1.5.1 -> v2.0.0 Updating icu_provider v1.5.0 -> v2.0.0 Removing icu_provider_macros v1.5.0 Updating idna_adapter v1.2.0 -> v1.2.1 Updating libloading v0.8.6 -> v0.8.7 Updating litemap v0.7.5 -> v0.8.0 Updating multimap v0.10.0 -> v0.10.1 Updating owo-colors v4.2.0 -> v4.2.1 Adding potential_utf v0.1.2 Updating rustls-webpki v0.103.2 -> v0.103.3 Updating tempfile v3.19.1 -> v3.20.0 Updating tinystr v0.7.6 -> v0.8.1 Updating tower-http v0.6.2 -> v0.6.4 Removing utf16_iter v1.0.5 Updating windows-core v0.61.0 -> v0.61.1 Updating windows-result v0.3.2 -> v0.3.3 Updating windows-strings v0.4.0 -> v0.4.1 Removing write16 v1.0.0 Updating writeable v0.5.5 -> v0.6.1 Updating yoke v0.7.5 -> v0.8.0 Updating yoke-derive v0.7.5 -> v0.8.0 Adding zerotrie v0.2.2 Updating zerovec v0.10.4 -> v0.11.2 Updating zerovec-derive v0.10.3 -> v0.11.1 ``` --- Cargo.lock | 236 ++++++++++++++++++++++++----------------------------- 1 file changed, 106 insertions(+), 130 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 75a272292..ab898e327 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -541,7 +541,7 @@ version = "0.71.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.9.1", "cexpr", "clang-sys", "itertools 0.13.0", @@ -567,9 +567,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.9.0" +version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" +checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" [[package]] name = "bittorrent-http-tracker-core" @@ -957,9 +957,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.21" +version = "1.2.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8691782945451c1c383942c4874dbe63814f61cb57ef773cda2972682b7bb3c0" +checksum = "32db95edf998450acc7881c932f94cd9b05c87b4b2599e8bab064753da4acfd1" dependencies = [ "jobserver", "libc", @@ -1050,9 +1050,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.37" +version = "4.5.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eccb054f56cbd38340b380d4a8e69ef1f02f1af43db2f0cc817a4774d80ae071" +checksum = "ed93b9805f8ba930df42c2590f05453d5ec36cbb85d018868a5b24d31f6ac000" dependencies = [ "clap_builder", "clap_derive", @@ -1060,9 +1060,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.37" +version = "4.5.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efd9466fac8543255d3b1fcad4762c5e116ffe808c8a3043d4263cd4fd4862a2" +checksum = "379026ff283facf611b0ea629334361c4211d1b12ee01024eec1591133b04120" dependencies = [ "anstream", "anstyle", @@ -1457,9 +1457,9 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" -version = "0.3.11" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e" +checksum = "cea14ef9355e3beab063703aa9dab15afd25f0667c341310c1e5274bb1d0da18" dependencies = [ "libc", "windows-sys 0.59.0", @@ -1825,9 +1825,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" +checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ "cfg-if", "libc", @@ -2138,21 +2138,22 @@ dependencies = [ [[package]] name = "icu_collections" -version = "1.5.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526" +checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47" dependencies = [ "displaydoc", + "potential_utf", "yoke", "zerofrom", "zerovec", ] [[package]] -name = "icu_locid" -version = "1.5.0" +name = "icu_locale_core" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637" +checksum = "0cde2700ccaed3872079a65fb1a78f6c0a36c91570f28755dda67bc8f7d9f00a" dependencies = [ "displaydoc", "litemap", @@ -2161,31 +2162,11 @@ dependencies = [ "zerovec", ] -[[package]] -name = "icu_locid_transform" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e" -dependencies = [ - "displaydoc", - "icu_locid", - "icu_locid_transform_data", - "icu_provider", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_locid_transform_data" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7515e6d781098bf9f7205ab3fc7e9709d34554ae0b21ddbcb5febfa4bc7df11d" - [[package]] name = "icu_normalizer" -version = "1.5.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f" +checksum = "436880e8e18df4d7bbc06d58432329d6458cc84531f7ac5f024e93deadb37979" dependencies = [ "displaydoc", "icu_collections", @@ -2193,67 +2174,54 @@ dependencies = [ "icu_properties", "icu_provider", "smallvec", - "utf16_iter", - "utf8_iter", - "write16", "zerovec", ] [[package]] name = "icu_normalizer_data" -version = "1.5.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e8338228bdc8ab83303f16b797e177953730f601a96c25d10cb3ab0daa0cb7" +checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3" [[package]] name = "icu_properties" -version = "1.5.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93d6020766cfc6302c15dbbc9c8778c37e62c14427cb7f6e601d849e092aeef5" +checksum = "2549ca8c7241c82f59c80ba2a6f415d931c5b58d24fb8412caa1a1f02c49139a" dependencies = [ "displaydoc", "icu_collections", - "icu_locid_transform", + "icu_locale_core", "icu_properties_data", "icu_provider", - "tinystr", + "potential_utf", + "zerotrie", "zerovec", ] [[package]] name = "icu_properties_data" -version = "1.5.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85fb8799753b75aee8d2a21d7c14d9f38921b54b3dbda10f5a3c7a7b82dba5e2" +checksum = "8197e866e47b68f8f7d95249e172903bec06004b18b2937f1095d40a0c57de04" [[package]] name = "icu_provider" -version = "1.5.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9" +checksum = "03c80da27b5f4187909049ee2d72f276f0d9f99a42c306bd0131ecfe04d8e5af" dependencies = [ "displaydoc", - "icu_locid", - "icu_provider_macros", + "icu_locale_core", "stable_deref_trait", "tinystr", "writeable", "yoke", "zerofrom", + "zerotrie", "zerovec", ] -[[package]] -name = "icu_provider_macros" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.101", -] - [[package]] name = "ident_case" version = "1.0.1" @@ -2273,9 +2241,9 @@ dependencies = [ [[package]] name = "idna_adapter" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daca1df1c957320b2cf139ac61e7bd64fed304c5040df000a745aa1de3b4ef71" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" dependencies = [ "icu_normalizer", "icu_properties", @@ -2386,7 +2354,7 @@ version = "0.1.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38f262f097c174adebe41eb73d66ae9c06b2844fb0da69969647bbddd9b0538a" dependencies = [ - "getrandom 0.3.2", + "getrandom 0.3.3", "libc", ] @@ -2423,12 +2391,12 @@ checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" [[package]] name = "libloading" -version = "0.8.6" +version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" +checksum = "6a793df0d7afeac54f95b471d3af7f0d4fb975699f972341a4b76988d49cdf0c" dependencies = [ "cfg-if", - "windows-targets 0.52.6", + "windows-targets 0.53.0", ] [[package]] @@ -2443,7 +2411,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.9.1", "libc", "redox_syscall 0.5.12", ] @@ -2484,9 +2452,9 @@ checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" [[package]] name = "litemap" -version = "0.7.5" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23fb14cb19457329c82206317a5663005a4d404783dc74f4252769b0d5f42856" +checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956" [[package]] name = "local-ip-address" @@ -2630,9 +2598,9 @@ dependencies = [ [[package]] name = "multimap" -version = "0.10.0" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "defc4c55412d89136f966bbb339008b474350e5e6e78d2714439c386b3137a03" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" dependencies = [ "serde", ] @@ -2689,7 +2657,7 @@ dependencies = [ "base64 0.21.7", "bigdecimal", "bindgen", - "bitflags 2.9.0", + "bitflags 2.9.1", "bitvec", "btoi", "byteorder", @@ -2857,7 +2825,7 @@ version = "0.10.72" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fedfea7d58a1f73118430a55da6a286e7b044961736ce96a16a17068ea25e5da" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.9.1", "cfg-if", "foreign-types", "libc", @@ -2903,9 +2871,9 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" [[package]] name = "owo-colors" -version = "4.2.0" +version = "4.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1036865bb9422d3300cf723f657c2851d0e9ab12567854b1f4eba3d77decf564" +checksum = "26995317201fa17f3656c36716aed4a7c81743a9634ac4c99c0eeda495db0cec" [[package]] name = "parking" @@ -3125,6 +3093,15 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "potential_utf" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5a7c30837279ca13e7c867e9e40053bc68740f988cb07f7ca6df43cc734b585" +dependencies = [ + "zerovec", +] + [[package]] name = "powerfmt" version = "0.2.0" @@ -3369,7 +3346,7 @@ version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ - "getrandom 0.3.2", + "getrandom 0.3.3", ] [[package]] @@ -3407,7 +3384,7 @@ version = "0.5.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "928fca9cf2aa042393a8325b9ead81d2f0df4cb12e1e24cef072922ccd99c5af" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.9.1", ] [[package]] @@ -3588,7 +3565,7 @@ version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a22715a5d6deef63c637207afbe68d0c72c3f8d0022d7cf9714c442d6157606b" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.9.1", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -3639,7 +3616,7 @@ version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.9.1", "errno", "libc", "linux-raw-sys 0.4.15", @@ -3652,7 +3629,7 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.9.1", "errno", "libc", "linux-raw-sys 0.9.4", @@ -3705,9 +3682,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.2" +version = "0.103.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7149975849f1abb3832b246010ef62ccc80d3a76169517ada7188252b9cfb437" +checksum = "e4a72fe2bcf7a6ac6fd7d0b9e5cb68aeb7d4c0a0271730218b3e92d43b4eb435" dependencies = [ "ring", "rustls-pki-types", @@ -3777,7 +3754,7 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.9.1", "core-foundation 0.9.4", "core-foundation-sys", "libc", @@ -3790,7 +3767,7 @@ version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "271720403f46ca04f7ba6f55d438f8bd878d6b8ca0a1046e8228c4145bcbb316" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.9.1", "core-foundation 0.10.0", "core-foundation-sys", "libc", @@ -4159,7 +4136,7 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.9.1", "core-foundation 0.9.4", "system-configuration-sys", ] @@ -4199,12 +4176,12 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.19.1" +version = "3.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7437ac7763b9b123ccf33c338a5cc1bac6f69b45a136c19bdd8a65e3916435bf" +checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1" dependencies = [ "fastrand", - "getrandom 0.3.2", + "getrandom 0.3.3", "once_cell", "rustix 1.0.7", "windows-sys 0.59.0", @@ -4357,9 +4334,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.7.6" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" +checksum = "5d4f6d1145dcb577acf783d4e601bc1d76a13337bb54e6233add580b07344c8b" dependencies = [ "displaydoc", "zerovec", @@ -4945,12 +4922,12 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.2" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "403fa3b783d4b626a8ad51d766ab03cb6d2dbfc46b1c5d4448395e6628dc9697" +checksum = "0fdb0c213ca27a9f57ab69ddb290fd80d970922355b83ae380b395d3986b8a2e" dependencies = [ "async-compression", - "bitflags 2.9.0", + "bitflags 2.9.1", "bytes", "futures-core", "http", @@ -5127,12 +5104,6 @@ dependencies = [ "serde", ] -[[package]] -name = "utf16_iter" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" - [[package]] name = "utf8_iter" version = "1.0.4" @@ -5151,7 +5122,7 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9" dependencies = [ - "getrandom 0.3.2", + "getrandom 0.3.3", "rand 0.9.1", ] @@ -5327,15 +5298,15 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-core" -version = "0.61.0" +version = "0.61.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4763c1de310c86d75a878046489e2e5ba02c649d185f21c67d4cf8a56d098980" +checksum = "46ec44dc15085cea82cf9c78f85a9114c463a369786585ad2882d1ff0b0acf40" dependencies = [ "windows-implement", "windows-interface", "windows-link", "windows-result", - "windows-strings 0.4.0", + "windows-strings 0.4.1", ] [[package]] @@ -5379,9 +5350,9 @@ dependencies = [ [[package]] name = "windows-result" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c64fd11a4fd95df68efcfee5f44a294fe71b8bc6a91993e2791938abcc712252" +checksum = "4b895b5356fc36103d0f64dd1e94dfa7ac5633f1c9dd6e80fe9ec4adef69e09d" dependencies = [ "windows-link", ] @@ -5397,9 +5368,9 @@ dependencies = [ [[package]] name = "windows-strings" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2ba9642430ee452d5a7aa78d72907ebe8cfda358e8cb7918a2050581322f97" +checksum = "2a7ab927b2637c19b3dbe0965e75d8f2d30bdd697a1516191cad2ec4df8fb28a" dependencies = [ "windows-link", ] @@ -5565,20 +5536,14 @@ version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ - "bitflags 2.9.0", + "bitflags 2.9.1", ] -[[package]] -name = "write16" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" - [[package]] name = "writeable" -version = "0.5.5" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" +checksum = "ea2f10b9bb0928dfb1b42b65e1f9e36f7f54dbdf08457afefb38afcdec4fa2bb" [[package]] name = "wyz" @@ -5607,9 +5572,9 @@ checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" [[package]] name = "yoke" -version = "0.7.5" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "120e6aef9aa629e3d4f52dc8cc43a015c7724194c97dfaf45180d2daf2b77f40" +checksum = "5f41bb01b8226ef4bfd589436a297c53d118f65921786300e427be8d487695cc" dependencies = [ "serde", "stable_deref_trait", @@ -5619,9 +5584,9 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.7.5" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" +checksum = "38da3c9736e16c5d3c8c597a9aaa5d1fa565d0532ae05e27c24aa62fb32c0ab6" dependencies = [ "proc-macro2", "quote", @@ -5697,11 +5662,22 @@ version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" +[[package]] +name = "zerotrie" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36f0bbd478583f79edad978b407914f61b2972f5af6fa089686016be8f9af595" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + [[package]] name = "zerovec" -version = "0.10.4" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa2b893d79df23bfb12d5461018d408ea19dfafe76c2c7ef6d4eba614f8ff079" +checksum = "4a05eb080e015ba39cc9e23bbe5e7fb04d5fb040350f99f34e338d5fdd294428" dependencies = [ "yoke", "zerofrom", @@ -5710,9 +5686,9 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.10.3" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" +checksum = "5b96237efa0c878c64bd89c436f661be4e46b2f3eff1ebb976f7ef2321d2f58f" dependencies = [ "proc-macro2", "quote", From 8d3b948ec3218e09f5187674866b969b5ef73af3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 16 May 2025 13:13:37 +0100 Subject: [PATCH 1114/1297] tests: [#1504] remove integration tests from torrent-repository pacakge All features are now covered by unit tests. --- .../torrent-repository/tests/common/mod.rs | 1 - .../tests/common/torrent_peer_builder.rs | 106 ---- .../torrent-repository/tests/integration.rs | 22 - .../torrent-repository/tests/swarm/mod.rs | 397 ------------- .../torrent-repository/tests/swarms/mod.rs | 524 ------------------ 5 files changed, 1050 deletions(-) delete mode 100644 packages/torrent-repository/tests/common/mod.rs delete mode 100644 packages/torrent-repository/tests/common/torrent_peer_builder.rs delete mode 100644 packages/torrent-repository/tests/integration.rs delete mode 100644 packages/torrent-repository/tests/swarm/mod.rs delete mode 100644 packages/torrent-repository/tests/swarms/mod.rs diff --git a/packages/torrent-repository/tests/common/mod.rs b/packages/torrent-repository/tests/common/mod.rs deleted file mode 100644 index c77ca2769..000000000 --- a/packages/torrent-repository/tests/common/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod torrent_peer_builder; diff --git a/packages/torrent-repository/tests/common/torrent_peer_builder.rs b/packages/torrent-repository/tests/common/torrent_peer_builder.rs deleted file mode 100644 index 0c065e670..000000000 --- a/packages/torrent-repository/tests/common/torrent_peer_builder.rs +++ /dev/null @@ -1,106 +0,0 @@ -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; -use torrust_tracker_clock::clock::Time; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; - -use crate::CurrentClock; - -#[derive(Debug, Default)] -struct TorrentPeerBuilder { - peer: peer::Peer, -} - -#[allow(dead_code)] -impl TorrentPeerBuilder { - #[must_use] - fn new() -> Self { - Self { - peer: peer::Peer { - updated: CurrentClock::now(), - ..Default::default() - }, - } - } - - #[must_use] - fn with_event_completed(mut self) -> Self { - self.peer.event = AnnounceEvent::Completed; - self - } - - #[must_use] - fn with_event_started(mut self) -> Self { - self.peer.event = AnnounceEvent::Started; - self - } - - #[must_use] - fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { - self.peer.peer_addr = peer_addr; - self - } - - #[must_use] - fn with_peer_id(mut self, peer_id: PeerId) -> Self { - self.peer.peer_id = peer_id; - self - } - - #[must_use] - fn with_number_of_bytes_left(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes::new(left); - self - } - - #[must_use] - fn updated_at(mut self, updated: DurationSinceUnixEpoch) -> Self { - self.peer.updated = updated; - self - } - - #[must_use] - fn into(self) -> peer::Peer { - self.peer - } -} - -/// A torrent seeder is a peer with 0 bytes left to download which -/// has not announced it has stopped -#[allow(clippy::cast_sign_loss)] -#[allow(clippy::cast_possible_truncation)] -#[must_use] -pub fn a_completed_peer(id: i32) -> peer::Peer { - let peer_id = peer::Id::new(id); - let peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), id as u16); - - TorrentPeerBuilder::new() - .with_number_of_bytes_left(0) - .with_event_completed() - .with_peer_id(*peer_id) - .with_peer_address(peer_addr) - .into() -} - -/// A torrent leecher is a peer that is not a seeder. -/// Leecher: left > 0 OR event = Stopped -/// -/// # Panics -/// -/// This function panics if proved id can't be converted into a valid socket address port. -/// -/// The `id` argument is used to identify the peer in both the `peer_id` and the `peer_addr`. -#[allow(clippy::cast_sign_loss)] -#[allow(clippy::cast_possible_truncation)] -#[must_use] -pub fn a_started_peer(id: i32) -> peer::Peer { - let peer_id = peer::Id::new(id); - let peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), id as u16); - - TorrentPeerBuilder::new() - .with_number_of_bytes_left(1) - .with_event_started() - .with_peer_id(*peer_id) - .with_peer_address(peer_addr) - .into() -} diff --git a/packages/torrent-repository/tests/integration.rs b/packages/torrent-repository/tests/integration.rs deleted file mode 100644 index b3e057075..000000000 --- a/packages/torrent-repository/tests/integration.rs +++ /dev/null @@ -1,22 +0,0 @@ -//! Integration tests. -//! -//! ```text -//! cargo test --test integration -//! ``` - -use torrust_tracker_clock::clock; - -pub mod common; -mod swarm; -mod swarms; - -/// This code needs to be copied into each crate. -/// Working version, for production. -#[cfg(not(test))] -#[allow(dead_code)] -pub(crate) type CurrentClock = clock::Working; - -/// Stopped version, for testing. -#[cfg(test)] -#[allow(dead_code)] -pub(crate) type CurrentClock = clock::Stopped; diff --git a/packages/torrent-repository/tests/swarm/mod.rs b/packages/torrent-repository/tests/swarm/mod.rs deleted file mode 100644 index cb4009ba9..000000000 --- a/packages/torrent-repository/tests/swarm/mod.rs +++ /dev/null @@ -1,397 +0,0 @@ -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use std::ops::Sub; -use std::time::Duration; - -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; -use bittorrent_primitives::info_hash::InfoHash; -use rstest::{fixture, rstest}; -use torrust_tracker_clock::clock::stopped::Stopped as _; -use torrust_tracker_clock::clock::{self, Time as _}; -use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; -use torrust_tracker_primitives::peer; -use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_torrent_repository::Swarm; - -use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; -use crate::CurrentClock; - -#[fixture] -fn swarm() -> Swarm { - Swarm::new(&InfoHash::default(), 0, None) -} - -#[fixture] -fn policy_none() -> TrackerPolicy { - TrackerPolicy::new(0, false, false) -} - -#[fixture] -fn policy_persist() -> TrackerPolicy { - TrackerPolicy::new(0, true, false) -} - -#[fixture] -fn policy_remove() -> TrackerPolicy { - TrackerPolicy::new(0, false, true) -} - -#[fixture] -fn policy_remove_persist() -> TrackerPolicy { - TrackerPolicy::new(0, true, true) -} - -pub enum Makes { - Empty, - Started, - Completed, - Downloaded, - Three, -} - -async fn make(swarm: &mut Swarm, makes: &Makes) -> Vec { - match makes { - Makes::Empty => vec![], - Makes::Started => { - let peer = a_started_peer(1); - swarm.handle_announcement(&peer).await; - vec![peer] - } - Makes::Completed => { - let peer = a_completed_peer(2); - swarm.handle_announcement(&peer).await; - vec![peer] - } - Makes::Downloaded => { - let mut peer = a_started_peer(3); - swarm.handle_announcement(&peer).await; - peer.event = AnnounceEvent::Completed; - peer.left = NumberOfBytes::new(0); - swarm.handle_announcement(&peer).await; - vec![peer] - } - Makes::Three => { - let peer_1 = a_started_peer(1); - swarm.handle_announcement(&peer_1).await; - - let peer_2 = a_completed_peer(2); - swarm.handle_announcement(&peer_2).await; - - let mut peer_3 = a_started_peer(3); - swarm.handle_announcement(&peer_3).await; - peer_3.event = AnnounceEvent::Completed; - peer_3.left = NumberOfBytes::new(0); - swarm.handle_announcement(&peer_3).await; - vec![peer_1, peer_2, peer_3] - } - } -} - -#[rstest] -#[case::empty(&Makes::Empty)] -#[tokio::test] -async fn it_should_be_empty_by_default(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - make(&mut swarm, makes).await; - - assert_eq!(swarm.len(), 0); -} - -#[rstest] -#[case::empty(&Makes::Empty)] -#[case::started(&Makes::Started)] -#[case::completed(&Makes::Completed)] -#[case::downloaded(&Makes::Downloaded)] -#[case::three(&Makes::Three)] -#[tokio::test] -async fn it_should_check_if_entry_should_be_retained_based_on_the_tracker_policy( - #[values(swarm())] mut swarm: Swarm, - #[case] makes: &Makes, - #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, -) { - make(&mut swarm, makes).await; - - let has_peers = !swarm.is_empty(); - let has_downloads = swarm.metadata().downloaded != 0; - - match (policy.remove_peerless_torrents, policy.persistent_torrent_completed_stat) { - // remove torrents without peers, and keep completed download stats - (true, true) => match (has_peers, has_downloads) { - // no peers, but has downloads - // peers, with or without downloads - (false, true) | (true, true | false) => assert!(swarm.meets_retaining_policy(&policy)), - // no peers and no downloads - (false, false) => assert!(!swarm.meets_retaining_policy(&policy)), - }, - // remove torrents without peers and drop completed download stats - (true, false) => match (has_peers, has_downloads) { - // peers, with or without downloads - (true, true | false) => assert!(swarm.meets_retaining_policy(&policy)), - // no peers and with or without downloads - (false, true | false) => assert!(!swarm.meets_retaining_policy(&policy)), - }, - // keep torrents without peers, but keep or drop completed download stats - (false, true | false) => assert!(swarm.meets_retaining_policy(&policy)), - } -} - -#[rstest] -#[case::empty(&Makes::Empty)] -#[case::started(&Makes::Started)] -#[case::completed(&Makes::Completed)] -#[case::downloaded(&Makes::Downloaded)] -#[case::three(&Makes::Three)] -#[tokio::test] -async fn it_should_get_peers_for_torrent_entry(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - let peers = make(&mut swarm, makes).await; - - let torrent_peers = swarm.peers(None); - - assert_eq!(torrent_peers.len(), peers.len()); - - for peer in torrent_peers { - assert!(peers.contains(&peer)); - } -} - -#[rstest] -#[case::empty(&Makes::Empty)] -#[case::started(&Makes::Started)] -#[case::completed(&Makes::Completed)] -#[case::downloaded(&Makes::Downloaded)] -#[case::three(&Makes::Three)] -#[tokio::test] -async fn it_should_update_a_peer(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - make(&mut swarm, makes).await; - - // Make and insert a new peer. - let mut peer = a_started_peer(-1); - swarm.handle_announcement(&peer).await; - - // Get the Inserted Peer by Id. - let peers = swarm.peers(None); - let original = peers - .iter() - .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) - .expect("it should find peer by id"); - - assert_eq!(original.event, AnnounceEvent::Started, "it should be as created"); - - // Announce "Completed" torrent download event. - peer.event = AnnounceEvent::Completed; - swarm.handle_announcement(&peer).await; - - // Get the Updated Peer by Id. - let peers = swarm.peers(None); - let updated = peers - .iter() - .find(|p| peer::ReadInfo::get_id(*p) == peer::ReadInfo::get_id(&peer)) - .expect("it should find peer by id"); - - assert_eq!(updated.event, AnnounceEvent::Completed, "it should be updated"); -} - -#[rstest] -#[case::empty(&Makes::Empty)] -#[case::started(&Makes::Started)] -#[case::completed(&Makes::Completed)] -#[case::downloaded(&Makes::Downloaded)] -#[case::three(&Makes::Three)] -#[tokio::test] -async fn it_should_remove_a_peer_upon_stopped_announcement(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - use torrust_tracker_primitives::peer::ReadInfo as _; - - make(&mut swarm, makes).await; - - let mut peer = a_started_peer(-1); - - swarm.handle_announcement(&peer).await; - - // The started peer should be inserted. - let peers = swarm.peers(None); - let original = peers - .iter() - .find(|p| p.get_id() == peer.get_id()) - .expect("it should find peer by id"); - - assert_eq!(original.event, AnnounceEvent::Started); - - // Change peer to "Stopped" and insert. - peer.event = AnnounceEvent::Stopped; - swarm.handle_announcement(&peer).await; - - // It should be removed now. - let peers = swarm.peers(None); - - assert_eq!( - peers.iter().find(|p| p.get_id() == peer.get_id()), - None, - "it should be removed" - ); -} - -#[rstest] -#[case::started(&Makes::Started)] -#[case::completed(&Makes::Completed)] -#[case::downloaded(&Makes::Downloaded)] -#[case::three(&Makes::Three)] -#[tokio::test] -async fn it_should_handle_a_peer_completed_announcement_and_update_the_downloaded_statistic( - #[values(swarm())] mut torrent: Swarm, - #[case] makes: &Makes, -) { - make(&mut torrent, makes).await; - let downloaded = torrent.metadata().downloaded; - - let peers = torrent.peers(None); - let mut peer = **peers.first().expect("there should be a peer"); - - let is_already_completed = peer.event == AnnounceEvent::Completed; - - // Announce "Completed" torrent download event. - peer.event = AnnounceEvent::Completed; - - torrent.handle_announcement(&peer).await; - let stats = torrent.metadata(); - - if is_already_completed { - assert_eq!(stats.downloaded, downloaded); - } else { - assert_eq!(stats.downloaded, downloaded + 1); - } -} - -#[rstest] -#[case::started(&Makes::Started)] -#[case::completed(&Makes::Completed)] -#[case::downloaded(&Makes::Downloaded)] -#[case::three(&Makes::Three)] -#[tokio::test] -async fn it_should_update_a_peer_as_a_seeder(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - let peers = make(&mut swarm, makes).await; - let completed = u32::try_from(peers.iter().filter(|p| p.is_seeder()).count()).expect("it_should_not_be_so_many"); - - let peers = swarm.peers(None); - let mut peer = **peers.first().expect("there should be a peer"); - - let is_already_non_left = peer.left == NumberOfBytes::new(0); - - // Set Bytes Left to Zero - peer.left = NumberOfBytes::new(0); - swarm.handle_announcement(&peer).await; - let stats = swarm.metadata(); - - if is_already_non_left { - // it was already complete - assert_eq!(stats.complete, completed); - } else { - // now it is complete - assert_eq!(stats.complete, completed + 1); - } -} - -#[rstest] -#[case::started(&Makes::Started)] -#[case::completed(&Makes::Completed)] -#[case::downloaded(&Makes::Downloaded)] -#[case::three(&Makes::Three)] -#[tokio::test] -async fn it_should_update_a_peer_as_incomplete(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - let peers = make(&mut swarm, makes).await; - let incomplete = u32::try_from(peers.iter().filter(|p| !p.is_seeder()).count()).expect("it should not be so many"); - - let peers = swarm.peers(None); - let mut peer = **peers.first().expect("there should be a peer"); - - let completed_already = peer.left == NumberOfBytes::new(0); - - // Set Bytes Left to no Zero - peer.left = NumberOfBytes::new(1); - swarm.handle_announcement(&peer).await; - let stats = swarm.metadata(); - - if completed_already { - // now it is incomplete - assert_eq!(stats.incomplete, incomplete + 1); - } else { - // was already incomplete - assert_eq!(stats.incomplete, incomplete); - } -} - -#[rstest] -#[case::started(&Makes::Started)] -#[case::completed(&Makes::Completed)] -#[case::downloaded(&Makes::Downloaded)] -#[case::three(&Makes::Three)] -#[tokio::test] -async fn it_should_get_peers_excluding_the_client_socket(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - make(&mut swarm, makes).await; - - let peers = swarm.peers(None); - let mut peer = **peers.first().expect("there should be a peer"); - - let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8081); - - // for this test, we should not already use this socket. - assert_ne!(peer.peer_addr, socket); - - // it should get the peer as it dose not share the socket. - assert!(swarm.peers_excluding(&socket, None).contains(&peer.into())); - - // set the address to the socket. - peer.peer_addr = socket; - swarm.handle_announcement(&peer).await; // Add peer - - // It should not include the peer that has the same socket. - assert!(!swarm.peers_excluding(&socket, None).contains(&peer.into())); -} - -#[rstest] -#[case::empty(&Makes::Empty)] -#[case::started(&Makes::Started)] -#[case::completed(&Makes::Completed)] -#[case::downloaded(&Makes::Downloaded)] -#[case::three(&Makes::Three)] -#[tokio::test] -async fn it_should_limit_the_number_of_peers_returned(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - make(&mut swarm, makes).await; - - // We add one more peer than the scrape limit - for peer_number in 1..=74 + 1 { - let peer = a_started_peer(peer_number); - swarm.handle_announcement(&peer).await; - } - - let peers = swarm.peers(Some(TORRENT_PEERS_LIMIT)); - - assert_eq!(peers.len(), 74); -} - -#[rstest] -#[case::empty(&Makes::Empty)] -#[case::started(&Makes::Started)] -#[case::completed(&Makes::Completed)] -#[case::downloaded(&Makes::Downloaded)] -#[case::three(&Makes::Three)] -#[tokio::test] -async fn it_should_remove_inactive_peers_beyond_cutoff(#[values(swarm())] mut swarm: Swarm, #[case] makes: &Makes) { - const TIMEOUT: Duration = Duration::from_secs(120); - const EXPIRE: Duration = Duration::from_secs(121); - - let peers = make(&mut swarm, makes).await; - - let mut peer = a_completed_peer(-1); - - let now = clock::Working::now(); - clock::Stopped::local_set(&now); - - peer.updated = now.sub(EXPIRE); - - swarm.handle_announcement(&peer).await; - - assert_eq!(swarm.len(), peers.len() + 1); - - let current_cutoff = CurrentClock::now_sub(&TIMEOUT).unwrap_or_default(); - swarm.remove_inactive(current_cutoff).await; - - assert_eq!(swarm.len(), peers.len()); -} diff --git a/packages/torrent-repository/tests/swarms/mod.rs b/packages/torrent-repository/tests/swarms/mod.rs deleted file mode 100644 index 780d6cd4c..000000000 --- a/packages/torrent-repository/tests/swarms/mod.rs +++ /dev/null @@ -1,524 +0,0 @@ -use std::collections::{BTreeMap, HashSet}; -use std::hash::{DefaultHasher, Hash, Hasher}; - -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; -use bittorrent_primitives::info_hash::InfoHash; -use futures::future::join_all; -use rstest::{fixture, rstest}; -use torrust_tracker_configuration::TrackerPolicy; -use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::PersistentTorrents; -use torrust_tracker_torrent_repository::swarm::Swarm; -use torrust_tracker_torrent_repository::Swarms; - -use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; - -fn swarm() -> Swarm { - Swarm::new(&InfoHash::default(), 0, None) -} - -#[fixture] -fn swarms() -> Swarms { - Swarms::default() -} - -type Entries = Vec<(InfoHash, Swarm)>; - -#[fixture] -fn empty() -> Entries { - vec![] -} - -#[fixture] -fn default() -> Entries { - vec![(InfoHash::default(), swarm())] -} - -#[fixture] -async fn started() -> Entries { - let mut swarm = swarm(); - swarm.handle_announcement(&a_started_peer(1)).await; - vec![(InfoHash::default(), swarm)] -} - -#[fixture] -async fn completed() -> Entries { - let mut swarm = swarm(); - swarm.handle_announcement(&a_completed_peer(2)).await; - vec![(InfoHash::default(), swarm)] -} - -#[fixture] -async fn downloaded() -> Entries { - let mut swarm = swarm(); - let mut peer = a_started_peer(3); - swarm.handle_announcement(&peer).await; - peer.event = AnnounceEvent::Completed; - peer.left = NumberOfBytes::new(0); - swarm.handle_announcement(&peer).await; - vec![(InfoHash::default(), swarm)] -} - -#[fixture] -async fn three() -> Entries { - let mut started = swarm(); - let started_h = &mut DefaultHasher::default(); - started.handle_announcement(&a_started_peer(1)).await; - started.hash(started_h); - - let mut completed = swarm(); - let completed_h = &mut DefaultHasher::default(); - completed.handle_announcement(&a_completed_peer(2)).await; - completed.hash(completed_h); - - let mut downloaded = swarm(); - let downloaded_h = &mut DefaultHasher::default(); - let mut downloaded_peer = a_started_peer(3); - downloaded.handle_announcement(&downloaded_peer).await; - downloaded_peer.event = AnnounceEvent::Completed; - downloaded_peer.left = NumberOfBytes::new(0); - downloaded.handle_announcement(&downloaded_peer).await; - downloaded.hash(downloaded_h); - - vec![ - (InfoHash::from(&started_h.clone()), started), - (InfoHash::from(&completed_h.clone()), completed), - (InfoHash::from(&downloaded_h.clone()), downloaded), - ] -} - -#[fixture] -async fn many_out_of_order() -> Entries { - let mut entries: HashSet<(InfoHash, Swarm)> = HashSet::default(); - - for i in 0..408 { - let mut entry = swarm(); - entry.handle_announcement(&a_started_peer(i)).await; - - entries.insert((InfoHash::from(&i), entry)); - } - - // we keep the random order from the hashed set for the vector. - entries.iter().map(|(i, e)| (*i, e.clone())).collect() -} - -#[fixture] -async fn many_hashed_in_order() -> Entries { - let mut entries: BTreeMap = BTreeMap::default(); - - for i in 0..408 { - let mut entry = swarm(); - entry.handle_announcement(&a_started_peer(i)).await; - - let hash: &mut DefaultHasher = &mut DefaultHasher::default(); - hash.write_i32(i); - - entries.insert(InfoHash::from(&hash.clone()), entry); - } - - // We return the entries in-order from from the b-tree map. - entries.iter().map(|(i, e)| (*i, e.clone())).collect() -} - -#[fixture] -fn persistent_empty() -> PersistentTorrents { - PersistentTorrents::default() -} - -#[fixture] -fn persistent_single() -> PersistentTorrents { - let hash = &mut DefaultHasher::default(); - - hash.write_u8(1); - let t = [(InfoHash::from(&hash.clone()), 0_u32)]; - - t.iter().copied().collect() -} - -#[fixture] -fn persistent_three() -> PersistentTorrents { - let hash = &mut DefaultHasher::default(); - - hash.write_u8(1); - let info_1 = InfoHash::from(&hash.clone()); - hash.write_u8(2); - let info_2 = InfoHash::from(&hash.clone()); - hash.write_u8(3); - let info_3 = InfoHash::from(&hash.clone()); - - let t = [(info_1, 1_u32), (info_2, 2_u32), (info_3, 3_u32)]; - - t.iter().copied().collect() -} - -fn make(swarms: &Swarms, entries: &Entries) { - for (info_hash, swarm) in entries { - swarms.insert(info_hash, swarm.clone()); - } -} - -#[fixture] -fn paginated_limit_zero() -> Pagination { - Pagination::new(0, 0) -} - -#[fixture] -fn paginated_limit_one() -> Pagination { - Pagination::new(0, 1) -} - -#[fixture] -fn paginated_limit_one_offset_one() -> Pagination { - Pagination::new(1, 1) -} - -#[fixture] -fn policy_none() -> TrackerPolicy { - TrackerPolicy::new(0, false, false) -} - -#[fixture] -fn policy_persist() -> TrackerPolicy { - TrackerPolicy::new(0, true, false) -} - -#[fixture] -fn policy_remove() -> TrackerPolicy { - TrackerPolicy::new(0, false, true) -} - -#[fixture] -fn policy_remove_persist() -> TrackerPolicy { - TrackerPolicy::new(0, true, true) -} - -#[rstest] -#[case::empty(empty())] -#[case::default(default())] -#[case::started(started().await)] -#[case::completed(completed().await)] -#[case::downloaded(downloaded().await)] -#[case::three(three().await)] -#[case::out_of_order(many_out_of_order().await)] -#[case::in_order(many_hashed_in_order().await)] -#[tokio::test] -async fn it_should_get_a_torrent_entry(#[values(swarms())] repo: Swarms, #[case] entries: Entries) { - make(&repo, &entries); - - if let Some((info_hash, swarm)) = entries.first() { - assert_eq!(Some(repo.get(info_hash).unwrap().lock().await.clone()), Some(swarm.clone())); - } else { - assert!(repo.get(&InfoHash::default()).is_none()); - } -} - -#[rstest] -#[case::empty(empty())] -#[case::default(default())] -#[case::started(started().await)] -#[case::completed(completed().await)] -#[case::downloaded(downloaded().await)] -#[case::three(three().await)] -#[case::out_of_order(many_out_of_order().await)] -#[case::in_order(many_hashed_in_order().await)] -#[tokio::test] -async fn it_should_get_paginated_entries_in_a_stable_or_sorted_order( - #[values(swarms())] repo: Swarms, - #[case] entries: Entries, - #[future] many_out_of_order: Entries, -) { - make(&repo, &entries); - - let entries_a = repo.get_paginated(None).iter().map(|(i, _)| *i).collect::>(); - - make(&repo, &many_out_of_order.await); - - let entries_b = repo.get_paginated(None).iter().map(|(i, _)| *i).collect::>(); - - let is_equal = entries_b.iter().take(entries_a.len()).copied().collect::>() == entries_a; - - let is_sorted = entries_b.windows(2).all(|w| w[0] <= w[1]); - - assert!( - is_equal || is_sorted, - "The order is unstable: {is_equal}, or is sorted {is_sorted}." - ); -} - -#[rstest] -#[case::empty(empty())] -#[case::default(default())] -#[case::started(started().await)] -#[case::completed(completed().await)] -#[case::downloaded(downloaded().await)] -#[case::three(three().await)] -#[case::out_of_order(many_out_of_order().await)] -#[case::in_order(many_hashed_in_order().await)] -#[tokio::test] -async fn it_should_get_paginated( - #[values(swarms())] repo: Swarms, - #[case] entries: Entries, - #[values(paginated_limit_zero(), paginated_limit_one(), paginated_limit_one_offset_one())] paginated: Pagination, -) { - make(&repo, &entries); - - let mut info_hashes = repo.get_paginated(None).iter().map(|(i, _)| *i).collect::>(); - info_hashes.sort(); - - match paginated { - // it should return empty if limit is zero. - Pagination { limit: 0, .. } => { - let page = repo.get_paginated(Some(&paginated)); - - let futures = page.iter().map(|(i, swarm_handle)| { - let i = *i; - let swarm_handle = swarm_handle.clone(); - async move { (i, swarm_handle.lock().await.clone()) } - }); - - let swarms: Vec<(InfoHash, Swarm)> = join_all(futures).await; - - assert_eq!(swarms, vec![]); - } - - // it should return a single entry if the limit is one. - Pagination { limit: 1, offset: 0 } => { - if info_hashes.is_empty() { - assert_eq!(repo.get_paginated(Some(&paginated)).len(), 0); - } else { - let page = repo.get_paginated(Some(&paginated)); - assert_eq!(page.len(), 1); - assert_eq!(page.first().map(|(i, _)| i), info_hashes.first()); - } - } - - // it should return only the second entry if both the limit and the offset are one. - Pagination { limit: 1, offset: 1 } => { - if info_hashes.len() > 1 { - let page = repo.get_paginated(Some(&paginated)); - assert_eq!(page.len(), 1); - assert_eq!(page[0].0, info_hashes[1]); - } - } - - _ => {} - } -} - -#[rstest] -#[case::empty(empty())] -#[case::default(default())] -#[case::started(started().await)] -#[case::completed(completed().await)] -#[case::downloaded(downloaded().await)] -#[case::three(three().await)] -#[case::out_of_order(many_out_of_order().await)] -#[case::in_order(many_hashed_in_order().await)] -#[tokio::test] -async fn it_should_get_metrics(#[values(swarms())] swarms: Swarms, #[case] entries: Entries) { - use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; - - make(&swarms, &entries); - - let mut metrics = AggregateSwarmMetadata::default(); - - for (_, torrent) in entries { - let stats = torrent.metadata(); - - metrics.total_torrents += 1; - metrics.total_incomplete += u64::from(stats.incomplete); - metrics.total_complete += u64::from(stats.complete); - metrics.total_downloaded += u64::from(stats.downloaded); - } - - assert_eq!(swarms.get_aggregate_swarm_metadata().await.unwrap(), metrics); -} - -#[rstest] -#[case::empty(empty())] -#[case::default(default())] -#[case::started(started().await)] -#[case::completed(completed().await)] -#[case::downloaded(downloaded().await)] -#[case::three(three().await)] -#[case::out_of_order(many_out_of_order().await)] -#[case::in_order(many_hashed_in_order().await)] -#[tokio::test] -async fn it_should_import_persistent_torrents( - #[values(swarms())] swarms: Swarms, - #[case] entries: Entries, - #[values(persistent_empty(), persistent_single(), persistent_three())] persistent_torrents: PersistentTorrents, -) { - make(&swarms, &entries); - - let mut downloaded = swarms.get_aggregate_swarm_metadata().await.unwrap().total_downloaded; - persistent_torrents.iter().for_each(|(_, d)| downloaded += u64::from(*d)); - - swarms.import_persistent(&persistent_torrents); - - assert_eq!( - swarms.get_aggregate_swarm_metadata().await.unwrap().total_downloaded, - downloaded - ); - - for (entry, _) in persistent_torrents { - assert!(swarms.get(&entry).is_some()); - } -} - -#[rstest] -#[case::empty(empty())] -#[case::default(default())] -#[case::started(started().await)] -#[case::completed(completed().await)] -#[case::downloaded(downloaded().await)] -#[case::three(three().await)] -#[case::out_of_order(many_out_of_order().await)] -#[case::in_order(many_hashed_in_order().await)] -#[tokio::test] -async fn it_should_remove_an_entry(#[values(swarms())] swarms: Swarms, #[case] entries: Entries) { - make(&swarms, &entries); - - for (info_hash, torrent) in entries { - assert_eq!( - Some(swarms.get(&info_hash).unwrap().lock().await.clone()), - Some(torrent.clone()) - ); - assert_eq!( - Some(swarms.remove(&info_hash).await.unwrap().lock().await.clone()), - Some(torrent) - ); - - assert!(swarms.get(&info_hash).is_none()); - assert!(swarms.remove(&info_hash).await.is_none()); - } - - assert_eq!(swarms.get_aggregate_swarm_metadata().await.unwrap().total_torrents, 0); -} - -#[rstest] -#[case::empty(empty())] -#[case::default(default())] -#[case::started(started().await)] -#[case::completed(completed().await)] -#[case::downloaded(downloaded().await)] -#[case::three(three().await)] -#[case::out_of_order(many_out_of_order().await)] -#[case::in_order(many_hashed_in_order().await)] -#[tokio::test] -async fn it_should_remove_inactive_peers(#[values(swarms())] swarms: Swarms, #[case] entries: Entries) { - use std::ops::Sub as _; - use std::time::Duration; - - use torrust_tracker_clock::clock::stopped::Stopped as _; - use torrust_tracker_clock::clock::{self, Time as _}; - use torrust_tracker_primitives::peer; - - use crate::CurrentClock; - - const TIMEOUT: Duration = Duration::from_secs(120); - const EXPIRE: Duration = Duration::from_secs(121); - - make(&swarms, &entries); - - let info_hash: InfoHash; - let mut peer: peer::Peer; - - // Generate a new infohash and peer. - { - let hash = &mut DefaultHasher::default(); - hash.write_u8(255); - info_hash = InfoHash::from(&hash.clone()); - peer = a_completed_peer(-1); - } - - // Set the last updated time of the peer to be 121 seconds ago. - { - let now = clock::Working::now(); - clock::Stopped::local_set(&now); - - peer.updated = now.sub(EXPIRE); - } - - // Insert the infohash and peer into the repository - // and verify there is an extra torrent entry. - { - swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); - assert_eq!( - swarms.get_aggregate_swarm_metadata().await.unwrap().total_torrents, - entries.len() as u64 + 1 - ); - } - - // Insert the infohash and peer into the repository - // and verify the swarm metadata was updated. - { - swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); - let stats = swarms.get_swarm_metadata(&info_hash).await.unwrap(); - assert_eq!( - stats, - Some(SwarmMetadata { - downloaded: 0, - complete: 1, - incomplete: 0 - }) - ); - } - - // Verify that this new peer was inserted into the repository. - { - let lock_tracked_torrent = swarms.get(&info_hash).expect("it_should_get_some"); - let entry = lock_tracked_torrent.lock().await; - assert!(entry.peers(None).contains(&peer.into())); - } - - // Remove peers that have not been updated since the timeout (120 seconds ago). - { - swarms - .remove_inactive_peers(CurrentClock::now_sub(&TIMEOUT).expect("it should get a time passed")) - .await - .unwrap(); - } - - // Verify that the this peer was removed from the repository. - { - let lock_tracked_torrent = swarms.get(&info_hash).expect("it_should_get_some"); - let entry = lock_tracked_torrent.lock().await; - assert!(!entry.peers(None).contains(&peer.into())); - } -} - -#[rstest] -#[case::empty(empty())] -#[case::default(default())] -#[case::started(started().await)] -#[case::completed(completed().await)] -#[case::downloaded(downloaded().await)] -#[case::three(three().await)] -#[case::out_of_order(many_out_of_order().await)] -#[case::in_order(many_hashed_in_order().await)] -#[tokio::test] -async fn it_should_remove_peerless_torrents( - #[values(swarms())] swarms: Swarms, - #[case] entries: Entries, - #[values(policy_none(), policy_persist(), policy_remove(), policy_remove_persist())] policy: TrackerPolicy, -) { - make(&swarms, &entries); - - swarms.remove_peerless_torrents(&policy).await.unwrap(); - - let paginated = swarms.get_paginated(None); // ← store the result in a named variable - - let futures = paginated.iter().map(|(i, swarm_handle)| { - let i = *i; - let swarm_handle = swarm_handle.clone(); - async move { (i, swarm_handle.lock().await.clone()) } - }); - - let torrents: Vec<(InfoHash, Swarm)> = join_all(futures).await; - - for (_, entry) in torrents { - assert!(entry.meets_retaining_policy(&policy)); - } -} From c2dabb2fcc5a4bddacfc21c68f0e626a547c82af Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 16 May 2025 13:15:24 +0100 Subject: [PATCH 1115/1297] chore: [#1504] remove uneeded fn attribute --- packages/torrent-repository/src/swarms.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 8b8327778..ac2490853 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -49,7 +49,6 @@ impl Swarms { /// # Errors /// /// This function panics if the lock for the swarm handle cannot be acquired. - #[allow(clippy::await_holding_lock)] pub async fn handle_announcement( &self, info_hash: &InfoHash, From 1472c8e99ac145ec03140f719e08786e750892ca Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 16 May 2025 13:17:54 +0100 Subject: [PATCH 1116/1297] refactor: [#1504] remove unneded trait implementationis for Swarm --- packages/torrent-repository/src/swarm.rs | 37 ------------------------ 1 file changed, 37 deletions(-) diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 8cf2982e6..f25304979 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -1,8 +1,6 @@ //! A swarm is a collection of peers that are all trying to download the same //! torrent. use std::collections::BTreeMap; -use std::fmt::Debug; -use std::hash::{Hash, Hasher}; use std::net::SocketAddr; use std::sync::Arc; @@ -24,31 +22,6 @@ pub struct Swarm { event_sender: Sender, } -#[allow(clippy::missing_fields_in_debug)] -impl Debug for Swarm { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Swarm") - .field("peers", &self.peers) - .field("metadata", &self.metadata) - .finish() - } -} - -impl Hash for Swarm { - fn hash(&self, state: &mut H) { - self.peers.hash(state); - self.metadata.hash(state); - } -} - -impl PartialEq for Swarm { - fn eq(&self, other: &Self) -> bool { - self.peers == other.peers && self.metadata == other.metadata - } -} - -impl Eq for Swarm {} - impl Swarm { #[must_use] pub fn new(info_hash: &InfoHash, downloaded: u32, event_sender: Sender) -> Self { @@ -329,16 +302,6 @@ mod tests { use crate::swarm::Swarm; use crate::tests::sample_info_hash; - #[test] - fn it_should_allow_debugging() { - let swarm = Swarm::new(&sample_info_hash(), 0, None); - - assert_eq!( - format!("{swarm:?}"), - "Swarm { peers: {}, metadata: SwarmMetadata { downloaded: 0, complete: 0, incomplete: 0 } }" - ); - } - #[test] fn it_should_be_empty_when_no_peers_have_been_inserted() { let swarm = Swarm::new(&sample_info_hash(), 0, None); From 85d9d3562bfaca3295f0cf2c3e879e061e7169ac Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 19 May 2025 10:48:31 +0100 Subject: [PATCH 1117/1297] refactor: [#1493] remove duplicate code for Peer buidler --- .../tests/server/v1/contract.rs | 14 ++-- packages/primitives/src/peer.rs | 33 ++++++-- .../tests/common/torrent_peer_builder.rs | 80 ++----------------- .../src/handlers/announce.rs | 27 ++++--- .../udp-tracker-server/src/handlers/mod.rs | 51 +----------- .../udp-tracker-server/src/handlers/scrape.rs | 9 ++- 6 files changed, 61 insertions(+), 153 deletions(-) diff --git a/packages/axum-http-tracker-server/tests/server/v1/contract.rs b/packages/axum-http-tracker-server/tests/server/v1/contract.rs index d864ba67c..d9ac2e1e1 100644 --- a/packages/axum-http-tracker-server/tests/server/v1/contract.rs +++ b/packages/axum-http-tracker-server/tests/server/v1/contract.rs @@ -1012,7 +1012,7 @@ mod for_all_config_modes { &info_hash, &PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) + .with_bytes_left_to_download(1) .build(), ) .await; @@ -1053,7 +1053,7 @@ mod for_all_config_modes { &info_hash, &PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) - .with_no_bytes_pending_to_download() + .with_no_bytes_left_to_download() .build(), ) .await; @@ -1286,7 +1286,7 @@ mod configured_as_whitelisted { &info_hash, &PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) + .with_bytes_left_to_download(1) .build(), ) .await; @@ -1323,7 +1323,7 @@ mod configured_as_whitelisted { &info_hash, &PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) + .with_bytes_left_to_download(1) .build(), ) .await; @@ -1500,7 +1500,7 @@ mod configured_as_private { &info_hash, &PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) + .with_bytes_left_to_download(1) .build(), ) .await; @@ -1532,7 +1532,7 @@ mod configured_as_private { &info_hash, &PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) + .with_bytes_left_to_download(1) .build(), ) .await; @@ -1584,7 +1584,7 @@ mod configured_as_private { &info_hash, &PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) - .with_bytes_pending_to_download(1) + .with_bytes_left_to_download(1) .build(), ) .await; diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index 57ca3909d..c271ee5d6 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -558,21 +558,30 @@ pub mod fixture { self } - #[allow(dead_code)] #[must_use] - pub fn with_bytes_pending_to_download(mut self, left: i64) -> Self { + pub fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { + self.peer.peer_addr = peer_addr; + self + } + + #[must_use] + pub fn updated_on(mut self, updated: DurationSinceUnixEpoch) -> Self { + self.peer.updated = updated; + self + } + + #[must_use] + pub fn with_bytes_left_to_download(mut self, left: i64) -> Self { self.peer.left = NumberOfBytes::new(left); self } - #[allow(dead_code)] #[must_use] - pub fn with_no_bytes_pending_to_download(mut self) -> Self { + pub fn with_no_bytes_left_to_download(mut self) -> Self { self.peer.left = NumberOfBytes::new(0); self } - #[allow(dead_code)] #[must_use] pub fn last_updated_on(mut self, updated: DurationSinceUnixEpoch) -> Self { self.peer.updated = updated; @@ -585,13 +594,23 @@ pub mod fixture { self } - #[allow(dead_code)] + #[must_use] + pub fn with_event_started(mut self) -> Self { + self.peer.event = AnnounceEvent::Started; + self + } + + #[must_use] + pub fn with_event_completed(mut self) -> Self { + self.peer.event = AnnounceEvent::Completed; + self + } + #[must_use] pub fn build(self) -> Peer { self.into() } - #[allow(dead_code)] #[must_use] pub fn into(self) -> Peer { self.peer diff --git a/packages/torrent-repository-benchmarking/tests/common/torrent_peer_builder.rs b/packages/torrent-repository-benchmarking/tests/common/torrent_peer_builder.rs index 33120180d..48aa981cd 100644 --- a/packages/torrent-repository-benchmarking/tests/common/torrent_peer_builder.rs +++ b/packages/torrent-repository-benchmarking/tests/common/torrent_peer_builder.rs @@ -1,79 +1,15 @@ -use std::net::SocketAddr; - -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; -use torrust_tracker_clock::clock::Time; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; - -use crate::CurrentClock; - -#[derive(Debug, Default)] -struct TorrentPeerBuilder { - peer: peer::Peer, -} - -#[allow(dead_code)] -impl TorrentPeerBuilder { - #[must_use] - fn new() -> Self { - Self { - peer: peer::Peer { - updated: CurrentClock::now(), - ..Default::default() - }, - } - } - - #[must_use] - fn with_event_completed(mut self) -> Self { - self.peer.event = AnnounceEvent::Completed; - self - } - - #[must_use] - fn with_event_started(mut self) -> Self { - self.peer.event = AnnounceEvent::Started; - self - } - - #[must_use] - fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { - self.peer.peer_addr = peer_addr; - self - } - - #[must_use] - fn with_peer_id(mut self, peer_id: PeerId) -> Self { - self.peer.peer_id = peer_id; - self - } - - #[must_use] - fn with_number_of_bytes_left(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes::new(left); - self - } - - #[must_use] - fn updated_at(mut self, updated: DurationSinceUnixEpoch) -> Self { - self.peer.updated = updated; - self - } - - #[must_use] - fn into(self) -> peer::Peer { - self.peer - } -} +use torrust_tracker_primitives::peer::fixture::PeerBuilder; +use torrust_tracker_primitives::peer::{self}; /// A torrent seeder is a peer with 0 bytes left to download which /// has not announced it has stopped #[must_use] pub fn a_completed_peer(id: i32) -> peer::Peer { let peer_id = peer::Id::new(id); - TorrentPeerBuilder::new() - .with_number_of_bytes_left(0) + PeerBuilder::default() + .with_bytes_left_to_download(0) .with_event_completed() - .with_peer_id(*peer_id) + .with_peer_id(&peer_id) .into() } @@ -82,9 +18,9 @@ pub fn a_completed_peer(id: i32) -> peer::Peer { #[must_use] pub fn a_started_peer(id: i32) -> peer::Peer { let peer_id = peer::Id::new(id); - TorrentPeerBuilder::new() - .with_number_of_bytes_left(1) + PeerBuilder::default() + .with_bytes_left_to_download(1) .with_event_started() - .with_peer_id(*peer_id) + .with_peer_id(&peer_id) .into() } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 65b521f27..567f43740 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -207,6 +207,7 @@ mod tests { use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use mockall::predicate::eq; use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{ConnectionContext, Event, UdpRequestKind}; @@ -216,7 +217,6 @@ mod tests { initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_socket_address, sample_issue_time, CoreTrackerServices, CoreUdpTrackerServices, MockUdpServerStatsEventSender, - TorrentPeerBuilder, }; #[tokio::test] @@ -258,8 +258,8 @@ mod tests { .get_torrent_peers(&info_hash.0.into()) .await; - let expected_peer = TorrentPeerBuilder::new() - .with_peer_id(peer_id) + let expected_peer = PeerBuilder::default() + .with_peer_id(&peer_id) .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip), client_port)) .updated_on(peers[0].updated) .into(); @@ -364,8 +364,8 @@ mod tests { let client_port = 8080; let peer_id = AquaticPeerId([255u8; 20]); - let peer_using_ipv6 = TorrentPeerBuilder::new() - .with_peer_id(peer_id) + let peer_using_ipv6 = PeerBuilder::default() + .with_peer_id(&peer_id) .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); @@ -466,13 +466,13 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::handlers::handle_announce; use crate::handlers::tests::{ initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_issue_time, - TorrentPeerBuilder, }; #[tokio::test] @@ -516,8 +516,8 @@ mod tests { let external_ip_in_tracker_configuration = core_tracker_services.core_config.net.external_ip.unwrap(); - let expected_peer = TorrentPeerBuilder::new() - .with_peer_id(peer_id) + let expected_peer = PeerBuilder::default() + .with_peer_id(&peer_id) .with_peer_address(SocketAddr::new(external_ip_in_tracker_configuration, client_port)) .updated_on(peers[0].updated) .into(); @@ -547,6 +547,7 @@ mod tests { use mockall::predicate::eq; use torrust_tracker_configuration::Core; use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{ConnectionContext, Event, UdpRequestKind}; @@ -555,7 +556,7 @@ mod tests { use crate::handlers::tests::{ initialize_core_tracker_services_for_default_tracker_configuration, initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv6_remote_addr, - sample_issue_time, MockUdpServerStatsEventSender, TorrentPeerBuilder, + sample_issue_time, MockUdpServerStatsEventSender, }; #[tokio::test] @@ -598,8 +599,8 @@ mod tests { .get_torrent_peers(&info_hash.0.into()) .await; - let expected_peer = TorrentPeerBuilder::new() - .with_peer_id(peer_id) + let expected_peer = PeerBuilder::default() + .with_peer_id(&peer_id) .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .updated_on(peers[0].updated) .into(); @@ -707,8 +708,8 @@ mod tests { let client_port = 8080; let peer_id = AquaticPeerId([255u8; 20]); - let peer_using_ipv4 = TorrentPeerBuilder::new() - .with_peer_id(peer_id) + let peer_using_ipv4 = PeerBuilder::default() + .with_peer_id(&peer_id) .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) .into(); diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index ca834c006..831073333 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -208,7 +208,6 @@ pub(crate) mod tests { use std::ops::Range; use std::sync::Arc; - use aquatic_udp_protocol::{NumberOfBytes, PeerId}; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; @@ -225,14 +224,12 @@ pub(crate) mod tests { use bittorrent_udp_tracker_core::{self, event as core_event}; use futures::future::BoxFuture; use mockall::mock; - use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_events::bus::SenderStatus; use torrust_tracker_events::sender::SendError; - use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch}; use torrust_tracker_test_helpers::configuration; - use crate::{event as server_event, CurrentClock}; + use crate::event as server_event; pub(crate) struct CoreTrackerServices { pub core_config: Arc, @@ -360,52 +357,6 @@ pub(crate) mod tests { sample_issue_time() - 10.0..sample_issue_time() + 10.0 } - #[derive(Debug, Default)] - pub(crate) struct TorrentPeerBuilder { - peer: peer::Peer, - } - - impl TorrentPeerBuilder { - #[must_use] - pub fn new() -> Self { - Self { - peer: peer::Peer { - updated: CurrentClock::now(), - ..Default::default() - }, - } - } - - #[must_use] - pub fn with_peer_address(mut self, peer_addr: SocketAddr) -> Self { - self.peer.peer_addr = peer_addr; - self - } - - #[must_use] - pub fn with_peer_id(mut self, peer_id: PeerId) -> Self { - self.peer.peer_id = peer_id; - self - } - - #[must_use] - pub fn with_number_of_bytes_left(mut self, left: i64) -> Self { - self.peer.left = NumberOfBytes::new(left); - self - } - - #[must_use] - pub fn updated_on(mut self, updated: DurationSinceUnixEpoch) -> Self { - self.peer.updated = updated; - self - } - - #[must_use] - pub fn into(self) -> peer::Peer { - self.peer - } - } - pub(crate) struct TrackerConfigurationBuilder { configuration: Configuration, } diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index e35e118b4..a9462e0f9 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -93,6 +93,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::bus::EventBus; @@ -100,7 +101,7 @@ mod tests { use crate::handlers::handle_scrape; use crate::handlers::tests::{ initialize_core_tracker_services_for_public_tracker, sample_cookie_valid_range, sample_ipv4_remote_addr, - sample_issue_time, CoreTrackerServices, CoreUdpTrackerServices, TorrentPeerBuilder, + sample_issue_time, CoreTrackerServices, CoreUdpTrackerServices, }; fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { @@ -158,10 +159,10 @@ mod tests { ) { let peer_id = PeerId([255u8; 20]); - let peer = TorrentPeerBuilder::new() - .with_peer_id(peer_id) + let peer = PeerBuilder::default() + .with_peer_id(&peer_id) .with_peer_address(*remote_addr) - .with_number_of_bytes_left(0) + .with_bytes_left_to_download(0) .into(); let _number_of_downloads_increased = in_memory_torrent_repository From b11af88ee3981faa92d26f64b6216d56ec1ff473 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 19 May 2025 17:51:21 +0100 Subject: [PATCH 1118/1297] feat: [#1522] add events metrics in torrent-repository These new metrics just count the number of times events have ocurred. --- .../src/statistics/event/handler.rs | 206 ++++++++++++++++-- .../torrent-repository/src/statistics/mod.rs | 41 +++- 2 files changed, 229 insertions(+), 18 deletions(-) diff --git a/packages/torrent-repository/src/statistics/event/handler.rs b/packages/torrent-repository/src/statistics/event/handler.rs index 2b61839b8..f8d350a80 100644 --- a/packages/torrent-repository/src/statistics/event/handler.rs +++ b/packages/torrent-repository/src/statistics/event/handler.rs @@ -8,7 +8,9 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; use crate::statistics::repository::Repository; use crate::statistics::{ - TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL, TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL, TORRENT_REPOSITORY_TORRENTS_TOTAL, + TORRENT_REPOSITORY_PEERS_ADDED_TOTAL, TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL, TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL, + TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL, TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL, + TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL, TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL, TORRENT_REPOSITORY_TORRENTS_TOTAL, }; pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { @@ -20,6 +22,14 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: let _unused = stats_repository .increment_gauge(&metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), &LabelSet::default(), now) .await; + + let _unused = stats_repository + .increment_counter( + &metric_name!(TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL), + &LabelSet::default(), + now, + ) + .await; } Event::TorrentRemoved { info_hash } => { tracing::debug!(info_hash = ?info_hash, "Torrent removed",); @@ -27,29 +37,41 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: let _unused = stats_repository .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), &LabelSet::default(), now) .await; + + let _unused = stats_repository + .increment_counter( + &metric_name!(TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL), + &LabelSet::default(), + now, + ) + .await; } // Peer events Event::PeerAdded { info_hash, peer } => { tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer added", ); + let label_set = label_set_for_peer(&peer); + let _unused = stats_repository - .increment_gauge( - &metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), - &label_set_for_peer(&peer), - now, - ) + .increment_gauge(&metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), &label_set, now) + .await; + + let _unused = stats_repository + .increment_counter(&metric_name!(TORRENT_REPOSITORY_PEERS_ADDED_TOTAL), &label_set, now) .await; } Event::PeerRemoved { info_hash, peer } => { tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer removed", ); + let label_set = label_set_for_peer(&peer); + let _unused = stats_repository - .decrement_gauge( - &metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), - &label_set_for_peer(&peer), - now, - ) + .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), &label_set, now) + .await; + + let _unused = stats_repository + .increment_counter(&metric_name!(TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL), &label_set, now) .await; } Event::PeerUpdated { @@ -76,6 +98,12 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: ) .await; } + + let label_set = label_set_for_peer(&new_peer); + + let _unused = stats_repository + .increment_counter(&metric_name!(TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL), &label_set, now) + .await; } Event::PeerDownloadCompleted { info_hash, peer } => { tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer download completed", ); @@ -92,7 +120,7 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: } /// Returns the label set to be included in the metrics for the given peer. -fn label_set_for_peer(peer: &Peer) -> LabelSet { +pub(crate) fn label_set_for_peer(peer: &Peer) -> LabelSet { if peer.is_seeder() { (label_name!("peer_role"), LabelValue::new("seeder")).into() } else { @@ -135,7 +163,7 @@ mod tests { opposite_role_peer } - async fn expect_counter_metric_to_be( + pub async fn expect_counter_metric_to_be( stats_repository: &Arc, metric_name: &MetricName, label_set: &LabelSet, @@ -186,9 +214,11 @@ mod tests { use crate::event::Event; use crate::statistics::event::handler::handle_event; - use crate::statistics::event::handler::tests::expect_gauge_metric_to_be; + use crate::statistics::event::handler::tests::{expect_counter_metric_to_be, expect_gauge_metric_to_be}; use crate::statistics::repository::Repository; - use crate::statistics::TORRENT_REPOSITORY_TORRENTS_TOTAL; + use crate::statistics::{ + TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL, TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL, TORRENT_REPOSITORY_TORRENTS_TOTAL, + }; use crate::tests::{sample_info_hash, sample_peer}; use crate::CurrentClock; @@ -242,9 +272,73 @@ mod tests { expect_gauge_metric_to_be(&stats_repository, &metric_name, &label_set, 0.0).await; } + + #[tokio::test] + async fn it_should_increment_the_number_of_torrents_added_when_a_torrent_added_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + handle_event( + Event::TorrentAdded { + info_hash: sample_info_hash(), + announcement: sample_peer(), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_counter_metric_to_be( + &stats_repository, + &metric_name!(TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL), + &LabelSet::default(), + 1, + ) + .await; + } + + #[tokio::test] + async fn it_should_increment_the_number_of_torrents_removed_when_a_torrent_removed_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + handle_event( + Event::TorrentRemoved { + info_hash: sample_info_hash(), + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_counter_metric_to_be( + &stats_repository, + &metric_name!(TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL), + &LabelSet::default(), + 1, + ) + .await; + } } mod for_peer_metrics { + use std::sync::Arc; + + use torrust_tracker_clock::clock::stopped::Stopped; + use torrust_tracker_clock::clock::{self, Time}; + use torrust_tracker_metrics::metric_name; + + use crate::event::Event; + use crate::statistics::event::handler::tests::expect_counter_metric_to_be; + use crate::statistics::event::handler::{handle_event, label_set_for_peer}; + use crate::statistics::repository::Repository; + use crate::statistics::{ + TORRENT_REPOSITORY_PEERS_ADDED_TOTAL, TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL, TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL, + }; + use crate::tests::{sample_info_hash, sample_peer}; + use crate::CurrentClock; mod peer_connections_total { @@ -383,6 +477,88 @@ mod tests { } } + #[tokio::test] + async fn it_should_increment_the_number_of_peers_added_when_a_peer_added_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + let peer = sample_peer(); + + handle_event( + Event::PeerAdded { + info_hash: sample_info_hash(), + peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_counter_metric_to_be( + &stats_repository, + &metric_name!(TORRENT_REPOSITORY_PEERS_ADDED_TOTAL), + &label_set_for_peer(&peer), + 1, + ) + .await; + } + + #[tokio::test] + async fn it_should_increment_the_number_of_peers_removed_when_a_peer_removed_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + let peer = sample_peer(); + + handle_event( + Event::PeerRemoved { + info_hash: sample_info_hash(), + peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_counter_metric_to_be( + &stats_repository, + &metric_name!(TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL), + &label_set_for_peer(&peer), + 1, + ) + .await; + } + + #[tokio::test] + async fn it_should_increment_the_number_of_peers_updated_when_a_peer_updated_event_is_received() { + clock::Stopped::local_set_to_unix_epoch(); + + let stats_repository = Arc::new(Repository::new()); + + let new_peer = sample_peer(); + + handle_event( + Event::PeerUpdated { + info_hash: sample_info_hash(), + old_peer: sample_peer(), + new_peer, + }, + &stats_repository, + CurrentClock::now(), + ) + .await; + + expect_counter_metric_to_be( + &stats_repository, + &metric_name!(TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL), + &label_set_for_peer(&new_peer), + 1, + ) + .await; + } + mod torrent_downloads_total { use std::sync::Arc; diff --git a/packages/torrent-repository/src/statistics/mod.rs b/packages/torrent-repository/src/statistics/mod.rs index 18dcf83ea..7d3ad85ce 100644 --- a/packages/torrent-repository/src/statistics/mod.rs +++ b/packages/torrent-repository/src/statistics/mod.rs @@ -9,11 +9,18 @@ use torrust_tracker_metrics::unit::Unit; // Torrent metrics +const TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL: &str = "torrent_repository_torrents_added_total"; +const TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL: &str = "torrent_repository_torrents_removed_total"; + const TORRENT_REPOSITORY_TORRENTS_TOTAL: &str = "torrent_repository_torrents_total"; const TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_torrents_downloads_total"; // Peers metrics +const TORRENT_REPOSITORY_PEERS_ADDED_TOTAL: &str = "torrent_repository_peers_added_total"; +const TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL: &str = "torrent_repository_peers_removed_total"; +const TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL: &str = "torrent_repository_peers_updated_total"; + const TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL: &str = "torrent_repository_peer_connections_total"; const TORRENT_REPOSITORY_UNIQUE_PEERS_TOTAL: &str = "torrent_repository_unique_peers_total"; // todo: not implemented yet @@ -23,6 +30,18 @@ pub fn describe_metrics() -> Metrics { // Torrent metrics + metrics.metric_collection.describe_counter( + &metric_name!(TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new("The total number of torrents added.")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new("The total number of torrents removed.")), + ); + metrics.metric_collection.describe_gauge( &metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), Some(Unit::Count), @@ -32,13 +51,29 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_counter( &metric_name!(TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new( - "The total number of torrent downloads (since the tracker process started).", - )), + Some(&MetricDescription::new("The total number of torrent downloads.")), ); // Peers metrics + metrics.metric_collection.describe_counter( + &metric_name!(TORRENT_REPOSITORY_PEERS_ADDED_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new("The total number of peers added.")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new("The total number of peers removed.")), + ); + + metrics.metric_collection.describe_counter( + &metric_name!(TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new("The total number of peers updated.")), + ); + metrics.metric_collection.describe_gauge( &metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), Some(Unit::Count), From 260f7ffbe557d84ae400f152c4fc3c9980eb4b27 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 20 May 2025 12:07:45 +0100 Subject: [PATCH 1119/1297] feat: [#1523] add new metric: number of inactive peers The metric is added to the `torrent-repository` package. The metric in Prometheus format: ``` torrent_repository_peers_inactive_total{} 0 ``` It was not included as a new label in the number of peers because it can't be calculated from current events. New inactivity events could have been added but the solution was much more complex than this and having two metrics counting peers is not so bad. The discarded alternative was addinga new label por satte (`active`, `inactive`). --- Cargo.lock | 1 + packages/torrent-repository/Cargo.toml | 1 + .../torrent-repository/src/statistics/mod.rs | 8 +++ .../src/statistics/peers_inactivity_update.rs | 72 +++++++++++++++++++ .../src/statistics/repository.rs | 25 +++++++ packages/torrent-repository/src/swarm.rs | 24 +++++++ packages/torrent-repository/src/swarms.rs | 28 ++++++++ packages/tracker-core/src/torrent/manager.rs | 10 ++- src/app.rs | 19 ++++- src/bootstrap/jobs/mod.rs | 1 + src/bootstrap/jobs/peers_inactivity_update.rs | 27 +++++++ 11 files changed, 211 insertions(+), 5 deletions(-) create mode 100644 packages/torrent-repository/src/statistics/peers_inactivity_update.rs create mode 100644 src/bootstrap/jobs/peers_inactivity_update.rs diff --git a/Cargo.lock b/Cargo.lock index ab898e327..6e4ab415f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4832,6 +4832,7 @@ dependencies = [ "aquatic_udp_protocol", "async-std", "bittorrent-primitives", + "chrono", "criterion", "crossbeam-skiplist", "futures", diff --git a/packages/torrent-repository/Cargo.toml b/packages/torrent-repository/Cargo.toml index 98ae5817d..510a59e9d 100644 --- a/packages/torrent-repository/Cargo.toml +++ b/packages/torrent-repository/Cargo.toml @@ -18,6 +18,7 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" +chrono = { version = "0", default-features = false, features = ["clock"] } crossbeam-skiplist = "0" futures = "0" serde = { version = "1.0.219", features = ["derive"] } diff --git a/packages/torrent-repository/src/statistics/mod.rs b/packages/torrent-repository/src/statistics/mod.rs index 7d3ad85ce..0f8a839ca 100644 --- a/packages/torrent-repository/src/statistics/mod.rs +++ b/packages/torrent-repository/src/statistics/mod.rs @@ -1,5 +1,6 @@ pub mod event; pub mod metrics; +pub mod peers_inactivity_update; pub mod repository; use metrics::Metrics; @@ -23,6 +24,7 @@ const TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL: &str = "torrent_repository_peers_u const TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL: &str = "torrent_repository_peer_connections_total"; const TORRENT_REPOSITORY_UNIQUE_PEERS_TOTAL: &str = "torrent_repository_unique_peers_total"; // todo: not implemented yet +const TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL: &str = "torrent_repository_peers_inactive_total"; #[must_use] pub fn describe_metrics() -> Metrics { @@ -88,5 +90,11 @@ pub fn describe_metrics() -> Metrics { Some(&MetricDescription::new("The total number of unique peers.")), ); + metrics.metric_collection.describe_gauge( + &metric_name!(TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new("The total number of inactive peers.")), + ); + metrics } diff --git a/packages/torrent-repository/src/statistics/peers_inactivity_update.rs b/packages/torrent-repository/src/statistics/peers_inactivity_update.rs new file mode 100644 index 000000000..e388173a1 --- /dev/null +++ b/packages/torrent-repository/src/statistics/peers_inactivity_update.rs @@ -0,0 +1,72 @@ +//! Job that runs a task on intervals to update peers' inactivity metrics. +use std::sync::Arc; + +use chrono::Utc; +use tokio::task::JoinHandle; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use tracing::instrument; + +use super::repository::Repository; +use crate::statistics::TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL; +use crate::{CurrentClock, Swarms}; + +#[must_use] +#[instrument(skip(swarms, stats_repository))] +pub fn start_job( + swarms: &Arc, + stats_repository: &Arc, + inactivity_cutoff: DurationSinceUnixEpoch, +) -> JoinHandle<()> { + let weak_swarms = std::sync::Arc::downgrade(swarms); + let weak_stats_repository = std::sync::Arc::downgrade(stats_repository); + + let interval_in_secs = 15; // todo: make this configurable + + tokio::spawn(async move { + let interval = std::time::Duration::from_secs(interval_in_secs); + let mut interval = tokio::time::interval(interval); + interval.tick().await; + + loop { + tokio::select! { + _ = tokio::signal::ctrl_c() => { + tracing::info!("Stopping peers inactivity metrics update job ..."); + break; + } + _ = interval.tick() => { + if let (Some(swarms), Some(stats_repository)) = (weak_swarms.upgrade(), weak_stats_repository.upgrade()) { + let start_time = Utc::now().time(); + + tracing::debug!("Updating peers inactivity metrics (executed every {} secs) ...", interval_in_secs); + + let inactive_peers_total = swarms.count_inactive_peers(inactivity_cutoff).await; + + tracing::info!(inactive_peers_total = inactive_peers_total); + + #[allow(clippy::cast_precision_loss)] + let inactive_peers_total = inactive_peers_total as f64; + + let _unused = stats_repository + .set_gauge( + &metric_name!(TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL), + &LabelSet::default(), + inactive_peers_total, + CurrentClock::now(), + ) + .await; + + tracing::debug!( + "Peers inactivity metrics updated in {} ms", + (Utc::now().time() - start_time).num_milliseconds() + ); + } else { + break; + } + } + } + } + }) +} diff --git a/packages/torrent-repository/src/statistics/repository.rs b/packages/torrent-repository/src/statistics/repository.rs index 1e376faf7..fe1292d00 100644 --- a/packages/torrent-repository/src/statistics/repository.rs +++ b/packages/torrent-repository/src/statistics/repository.rs @@ -57,6 +57,31 @@ impl Repository { result } + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// set the gauge. + pub async fn set_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.set_gauge(metric_name, labels, value, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to set the gauge: {}", err), + } + + result + } + /// # Errors /// /// This function will return an error if the metric collection fails to diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index f25304979..d7a1ede87 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -118,6 +118,14 @@ impl Swarm { (seeders, leechers) } + #[must_use] + pub fn count_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> usize { + self.peers + .iter() + .filter(|(_, peer)| peer::ReadInfo::get_updated(&**peer) <= current_cutoff) + .count() + } + #[must_use] pub fn len(&self) -> usize { self.peers.len() @@ -435,6 +443,22 @@ mod tests { assert_eq!(swarm.peers_excluding(&peer2.peer_addr, None), [Arc::new(peer1)]); } + #[tokio::test] + async fn it_should_count_inactive_peers() { + let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut downloads_increased = false; + let one_second = DurationSinceUnixEpoch::new(1, 0); + + // Insert the peer + let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); + let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); + swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + + let inactive_peers_total = swarm.count_inactive_peers(last_update_time + one_second); + + assert_eq!(inactive_peers_total, 1); + } + #[tokio::test] async fn it_should_remove_inactive_peers() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index ac2490853..811bf6a50 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -248,6 +248,18 @@ impl Swarms { } } + /// Counts the number of inactive peers across all torrents. + pub async fn count_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> usize { + let mut inactive_peers_total = 0; + + for swarm_handle in &self.swarms { + let swarm = swarm_handle.value().lock().await; + inactive_peers_total += swarm.count_inactive_peers(current_cutoff); + } + + inactive_peers_total + } + /// Removes inactive peers from all torrent entries. /// /// A peer is considered inactive if its last update timestamp is older than @@ -705,6 +717,22 @@ mod tests { assert!(swarms.get(&info_hash).is_none()); } + #[tokio::test] + async fn it_should_count_inactive_peers() { + let swarms = Arc::new(Swarms::default()); + + let info_hash = sample_info_hash(); + let mut peer = sample_peer(); + peer.updated = DurationSinceUnixEpoch::new(0, 0); + + swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); + + // Cut off time is 1 second after the peer was updated + let inactive_peers_total = swarms.count_inactive_peers(peer.updated.add(Duration::from_secs(1))).await; + + assert_eq!(inactive_peers_total, 1); + } + #[tokio::test] async fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { let swarms = Arc::new(Swarms::default()); diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index bc193bd4f..bf73f7e8b 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -4,6 +4,7 @@ use std::time::Duration; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Core; +use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::repository::in_memory::InMemoryTorrentRepository; use super::repository::persisted::DatabasePersistentTorrentRepository; @@ -103,10 +104,13 @@ impl TorrentsManager { } async fn remove_inactive_peers(&self) { - let current_cutoff = CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout))) - .unwrap_or_default(); + self.in_memory_torrent_repository + .remove_inactive_peers(self.current_cutoff()) + .await; + } - self.in_memory_torrent_repository.remove_inactive_peers(current_cutoff).await; + fn current_cutoff(&self) -> DurationSinceUnixEpoch { + CurrentClock::now_sub(&Duration::from_secs(u64::from(self.config.tracker_policy.max_peer_timeout))).unwrap_or_default() } async fn remove_peerless_torrents(&self) { diff --git a/src/app.rs b/src/app.rs index ca8b7a5c3..1c2d9387e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -27,7 +27,9 @@ use torrust_tracker_configuration::{Configuration, HttpTracker, UdpTracker}; use tracing::instrument; use crate::bootstrap::jobs::manager::JobManager; -use crate::bootstrap::jobs::{self, health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker}; +use crate::bootstrap::jobs::{ + self, health_check_api, http_tracker, peers_inactivity_update, torrent_cleanup, tracker_apis, udp_tracker, +}; use crate::bootstrap::{self}; use crate::container::AppContainer; @@ -79,8 +81,11 @@ async fn start_jobs(config: &Configuration, app_container: &Arc) - start_the_udp_instances(config, app_container, &mut job_manager).await; start_the_http_instances(config, app_container, &mut job_manager).await; - start_the_http_api(config, app_container, &mut job_manager).await; + start_torrent_cleanup(config, app_container, &mut job_manager); + start_peers_inactivity_update(config, app_container, &mut job_manager); + + start_the_http_api(config, app_container, &mut job_manager).await; start_health_check_api(config, app_container, &mut job_manager).await; job_manager @@ -260,6 +265,16 @@ fn start_torrent_cleanup(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + if config.core.tracker_usage_statistics { + let handle = peers_inactivity_update::start_job(config, app_container); + + job_manager.push("peers_inactivity_update", handle); + } else { + tracing::info!("Peers inactivity update job is disabled."); + } +} + async fn start_health_check_api(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { let handle = health_check_api::start_job(&config.health_check_api, app_container.registar.entries()).await; diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index b311c6da6..f593ce808 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -10,6 +10,7 @@ pub mod health_check_api; pub mod http_tracker; pub mod http_tracker_core; pub mod manager; +pub mod peers_inactivity_update; pub mod torrent_cleanup; pub mod torrent_repository; pub mod tracker_apis; diff --git a/src/bootstrap/jobs/peers_inactivity_update.rs b/src/bootstrap/jobs/peers_inactivity_update.rs new file mode 100644 index 000000000..e7939720c --- /dev/null +++ b/src/bootstrap/jobs/peers_inactivity_update.rs @@ -0,0 +1,27 @@ +//! Job that runs a task on intervals to update peers' inactivity metrics. +use std::sync::Arc; +use std::time::Duration; + +use tokio::task::JoinHandle; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_configuration::Configuration; + +use crate::container::AppContainer; +use crate::CurrentClock; + +#[must_use] +pub fn start_job(config: &Configuration, app_container: &Arc) -> JoinHandle<()> { + torrust_tracker_torrent_repository::statistics::peers_inactivity_update::start_job( + &app_container.torrent_repository_container.swarms.clone(), + &app_container.torrent_repository_container.stats_repository.clone(), + peer_inactivity_cutoff_timestamp(config.core.tracker_policy.max_peer_timeout), + ) +} + +/// Returns the timestamp of the cutoff for inactive peers. +/// +/// Peers that has not been updated for more than `max_peer_timeout` seconds are +/// considered inactive. +fn peer_inactivity_cutoff_timestamp(max_peer_timeout: u32) -> Duration { + CurrentClock::now_sub(&Duration::from_secs(u64::from(max_peer_timeout))).unwrap_or_default() +} From 677deacdc419526122eff62973f2685ac976a5eb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 21 May 2025 12:34:12 +0100 Subject: [PATCH 1120/1297] feat: [#1523] add new metric: number of inactive torrents --- .../statistics/activity_metrics_updater.rs | 104 ++++++++++++++++++ .../torrent-repository/src/statistics/mod.rs | 9 +- .../src/statistics/peers_inactivity_update.rs | 72 ------------ packages/torrent-repository/src/swarm.rs | 35 ++++++ packages/torrent-repository/src/swarms.rs | 51 +++++++++ src/app.rs | 4 +- ..._update.rs => activity_metrics_updater.rs} | 4 +- src/bootstrap/jobs/mod.rs | 2 +- 8 files changed, 203 insertions(+), 78 deletions(-) create mode 100644 packages/torrent-repository/src/statistics/activity_metrics_updater.rs delete mode 100644 packages/torrent-repository/src/statistics/peers_inactivity_update.rs rename src/bootstrap/jobs/{peers_inactivity_update.rs => activity_metrics_updater.rs} (84%) diff --git a/packages/torrent-repository/src/statistics/activity_metrics_updater.rs b/packages/torrent-repository/src/statistics/activity_metrics_updater.rs new file mode 100644 index 000000000..2dfa5fb4e --- /dev/null +++ b/packages/torrent-repository/src/statistics/activity_metrics_updater.rs @@ -0,0 +1,104 @@ +//! Job that runs a task on intervals to update peers' activity metrics. +use std::sync::Arc; + +use chrono::Utc; +use tokio::task::JoinHandle; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use tracing::instrument; + +use super::repository::Repository; +use crate::statistics::{TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL, TORRENT_REPOSITORY_TORRENTS_INACTIVE_TOTAL}; +use crate::{CurrentClock, Swarms}; + +#[must_use] +#[instrument(skip(swarms, stats_repository))] +pub fn start_job( + swarms: &Arc, + stats_repository: &Arc, + inactivity_cutoff: DurationSinceUnixEpoch, +) -> JoinHandle<()> { + let weak_swarms = std::sync::Arc::downgrade(swarms); + let weak_stats_repository = std::sync::Arc::downgrade(stats_repository); + + let interval_in_secs = 15; // todo: make this configurable + + tokio::spawn(async move { + let interval = std::time::Duration::from_secs(interval_in_secs); + let mut interval = tokio::time::interval(interval); + interval.tick().await; + + loop { + tokio::select! { + _ = tokio::signal::ctrl_c() => { + tracing::info!("Stopping peers activity metrics update job (ctrl-c signal received) ..."); + break; + } + _ = interval.tick() => { + if let (Some(swarms), Some(stats_repository)) = (weak_swarms.upgrade(), weak_stats_repository.upgrade()) { + update_activity_metrics(interval_in_secs, &swarms, &stats_repository, inactivity_cutoff).await; + } else { + tracing::info!("Stopping peers activity metrics update job (can't upgrade weak pointers) ..."); + break; + } + } + } + } + }) +} + +async fn update_activity_metrics( + interval_in_secs: u64, + swarms: &Arc, + stats_repository: &Arc, + inactivity_cutoff: DurationSinceUnixEpoch, +) { + let start_time = Utc::now().time(); + + tracing::debug!( + "Updating peers and torrents activity metrics (executed every {} secs) ...", + interval_in_secs + ); + + let activity_metadata = swarms.get_activity_metadata(inactivity_cutoff).await; + + activity_metadata.log(); + + update_inactive_peers_total(stats_repository, activity_metadata.inactive_peers_total).await; + update_inactive_torrents_total(stats_repository, activity_metadata.inactive_torrents_total).await; + + tracing::debug!( + "Peers and torrents activity metrics updated in {} ms", + (Utc::now().time() - start_time).num_milliseconds() + ); +} + +async fn update_inactive_peers_total(stats_repository: &Arc, inactive_peers_total: usize) { + #[allow(clippy::cast_precision_loss)] + let inactive_peers_total = inactive_peers_total as f64; + + let _unused = stats_repository + .set_gauge( + &metric_name!(TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL), + &LabelSet::default(), + inactive_peers_total, + CurrentClock::now(), + ) + .await; +} + +async fn update_inactive_torrents_total(stats_repository: &Arc, inactive_torrents_total: usize) { + #[allow(clippy::cast_precision_loss)] + let inactive_torrents_total = inactive_torrents_total as f64; + + let _unused = stats_repository + .set_gauge( + &metric_name!(TORRENT_REPOSITORY_TORRENTS_INACTIVE_TOTAL), + &LabelSet::default(), + inactive_torrents_total, + CurrentClock::now(), + ) + .await; +} diff --git a/packages/torrent-repository/src/statistics/mod.rs b/packages/torrent-repository/src/statistics/mod.rs index 0f8a839ca..cfc252e34 100644 --- a/packages/torrent-repository/src/statistics/mod.rs +++ b/packages/torrent-repository/src/statistics/mod.rs @@ -1,6 +1,6 @@ +pub mod activity_metrics_updater; pub mod event; pub mod metrics; -pub mod peers_inactivity_update; pub mod repository; use metrics::Metrics; @@ -15,6 +15,7 @@ const TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL: &str = "torrent_repository_torr const TORRENT_REPOSITORY_TORRENTS_TOTAL: &str = "torrent_repository_torrents_total"; const TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_torrents_downloads_total"; +const TORRENT_REPOSITORY_TORRENTS_INACTIVE_TOTAL: &str = "torrent_repository_torrents_inactive_total"; // Peers metrics @@ -56,6 +57,12 @@ pub fn describe_metrics() -> Metrics { Some(&MetricDescription::new("The total number of torrent downloads.")), ); + metrics.metric_collection.describe_gauge( + &metric_name!(TORRENT_REPOSITORY_TORRENTS_INACTIVE_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new("The total number of inactive torrents.")), + ); + // Peers metrics metrics.metric_collection.describe_counter( diff --git a/packages/torrent-repository/src/statistics/peers_inactivity_update.rs b/packages/torrent-repository/src/statistics/peers_inactivity_update.rs deleted file mode 100644 index e388173a1..000000000 --- a/packages/torrent-repository/src/statistics/peers_inactivity_update.rs +++ /dev/null @@ -1,72 +0,0 @@ -//! Job that runs a task on intervals to update peers' inactivity metrics. -use std::sync::Arc; - -use chrono::Utc; -use tokio::task::JoinHandle; -use torrust_tracker_clock::clock::Time; -use torrust_tracker_metrics::label::LabelSet; -use torrust_tracker_metrics::metric_name; -use torrust_tracker_primitives::DurationSinceUnixEpoch; -use tracing::instrument; - -use super::repository::Repository; -use crate::statistics::TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL; -use crate::{CurrentClock, Swarms}; - -#[must_use] -#[instrument(skip(swarms, stats_repository))] -pub fn start_job( - swarms: &Arc, - stats_repository: &Arc, - inactivity_cutoff: DurationSinceUnixEpoch, -) -> JoinHandle<()> { - let weak_swarms = std::sync::Arc::downgrade(swarms); - let weak_stats_repository = std::sync::Arc::downgrade(stats_repository); - - let interval_in_secs = 15; // todo: make this configurable - - tokio::spawn(async move { - let interval = std::time::Duration::from_secs(interval_in_secs); - let mut interval = tokio::time::interval(interval); - interval.tick().await; - - loop { - tokio::select! { - _ = tokio::signal::ctrl_c() => { - tracing::info!("Stopping peers inactivity metrics update job ..."); - break; - } - _ = interval.tick() => { - if let (Some(swarms), Some(stats_repository)) = (weak_swarms.upgrade(), weak_stats_repository.upgrade()) { - let start_time = Utc::now().time(); - - tracing::debug!("Updating peers inactivity metrics (executed every {} secs) ...", interval_in_secs); - - let inactive_peers_total = swarms.count_inactive_peers(inactivity_cutoff).await; - - tracing::info!(inactive_peers_total = inactive_peers_total); - - #[allow(clippy::cast_precision_loss)] - let inactive_peers_total = inactive_peers_total as f64; - - let _unused = stats_repository - .set_gauge( - &metric_name!(TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL), - &LabelSet::default(), - inactive_peers_total, - CurrentClock::now(), - ) - .await; - - tracing::debug!( - "Peers inactivity metrics updated in {} ms", - (Utc::now().time() - start_time).num_milliseconds() - ); - } else { - break; - } - } - } - } - }) -} diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index d7a1ede87..b9076289b 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -126,6 +126,17 @@ impl Swarm { .count() } + #[must_use] + pub fn get_activity_metadata(&self, current_cutoff: DurationSinceUnixEpoch) -> ActivityMetadata { + let inactive_peers_total = self.count_inactive_peers(current_cutoff); + + let active_peers_total = self.len() - inactive_peers_total; + + let is_active = active_peers_total > 0; + + ActivityMetadata::new(is_active, active_peers_total, inactive_peers_total) + } + #[must_use] pub fn len(&self) -> usize { self.peers.len() @@ -296,6 +307,30 @@ impl Swarm { } } +#[derive(Clone)] +pub struct ActivityMetadata { + /// Indicates if the swarm is active. It's inactive if there are no active + /// peers. + pub is_active: bool, + + /// The number of active peers in the swarm. + pub active_peers_total: usize, + + /// The number of inactive peers in the swarm. + pub inactive_peers_total: usize, +} + +impl ActivityMetadata { + #[must_use] + pub fn new(is_active: bool, active_peers_total: usize, inactive_peers_total: usize) -> Self { + Self { + is_active, + active_peers_total, + inactive_peers_total, + } + } +} + #[cfg(test)] mod tests { diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 811bf6a50..36f83070d 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -248,6 +248,32 @@ impl Swarms { } } + pub async fn get_activity_metadata(&self, current_cutoff: DurationSinceUnixEpoch) -> AggregateActivityMetadata { + let mut active_peers_total = 0; + let mut inactive_peers_total = 0; + let mut active_torrents_total = 0; + + for swarm_handle in &self.swarms { + let swarm = swarm_handle.value().lock().await; + + let activity_metadata = swarm.get_activity_metadata(current_cutoff); + + if activity_metadata.is_active { + active_torrents_total += 1; + } + + active_peers_total += activity_metadata.active_peers_total; + inactive_peers_total += activity_metadata.inactive_peers_total; + } + + AggregateActivityMetadata { + active_peers_total, + inactive_peers_total, + active_torrents_total, + inactive_torrents_total: self.len() - active_torrents_total, + } + } + /// Counts the number of inactive peers across all torrents. pub async fn count_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> usize { let mut inactive_peers_total = 0; @@ -446,6 +472,31 @@ impl Swarms { #[derive(thiserror::Error, Debug, Clone)] pub enum Error {} +#[derive(Clone, Debug, Default)] +pub struct AggregateActivityMetadata { + /// The number of active peers in all swarms. + pub active_peers_total: usize, + + /// The number of inactive peers in all swarms. + pub inactive_peers_total: usize, + + /// The number of active torrents. + pub active_torrents_total: usize, + + /// The number of inactive torrents. + pub inactive_torrents_total: usize, +} + +impl AggregateActivityMetadata { + pub fn log(&self) { + tracing::info!( + active_peers_total = self.active_peers_total, + inactive_peers_total = self.inactive_peers_total, + active_torrents_total = self.active_torrents_total, + inactive_torrents_total = self.inactive_torrents_total + ); + } +} #[cfg(test)] mod tests { diff --git a/src/app.rs b/src/app.rs index 1c2d9387e..5180e4583 100644 --- a/src/app.rs +++ b/src/app.rs @@ -28,7 +28,7 @@ use tracing::instrument; use crate::bootstrap::jobs::manager::JobManager; use crate::bootstrap::jobs::{ - self, health_check_api, http_tracker, peers_inactivity_update, torrent_cleanup, tracker_apis, udp_tracker, + self, activity_metrics_updater, health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker, }; use crate::bootstrap::{self}; use crate::container::AppContainer; @@ -267,7 +267,7 @@ fn start_torrent_cleanup(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { if config.core.tracker_usage_statistics { - let handle = peers_inactivity_update::start_job(config, app_container); + let handle = activity_metrics_updater::start_job(config, app_container); job_manager.push("peers_inactivity_update", handle); } else { diff --git a/src/bootstrap/jobs/peers_inactivity_update.rs b/src/bootstrap/jobs/activity_metrics_updater.rs similarity index 84% rename from src/bootstrap/jobs/peers_inactivity_update.rs rename to src/bootstrap/jobs/activity_metrics_updater.rs index e7939720c..7411c05cf 100644 --- a/src/bootstrap/jobs/peers_inactivity_update.rs +++ b/src/bootstrap/jobs/activity_metrics_updater.rs @@ -1,4 +1,4 @@ -//! Job that runs a task on intervals to update peers' inactivity metrics. +//! Job that runs a task on intervals to update peers' activity metrics. use std::sync::Arc; use std::time::Duration; @@ -11,7 +11,7 @@ use crate::CurrentClock; #[must_use] pub fn start_job(config: &Configuration, app_container: &Arc) -> JoinHandle<()> { - torrust_tracker_torrent_repository::statistics::peers_inactivity_update::start_job( + torrust_tracker_torrent_repository::statistics::activity_metrics_updater::start_job( &app_container.torrent_repository_container.swarms.clone(), &app_container.torrent_repository_container.stats_repository.clone(), peer_inactivity_cutoff_timestamp(config.core.tracker_policy.max_peer_timeout), diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index f593ce808..c8d7a8598 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -6,11 +6,11 @@ //! 2. Launch all the application services as concurrent jobs. //! //! This modules contains all the functions needed to start those jobs. +pub mod activity_metrics_updater; pub mod health_check_api; pub mod http_tracker; pub mod http_tracker_core; pub mod manager; -pub mod peers_inactivity_update; pub mod torrent_cleanup; pub mod torrent_repository; pub mod tracker_apis; From 3a23a38b38c059311b5213e8e6055ac809d6f648 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 21 May 2025 16:56:39 +0100 Subject: [PATCH 1121/1297] fix: tracing message --- src/bootstrap/jobs/torrent_repository.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bootstrap/jobs/torrent_repository.rs b/src/bootstrap/jobs/torrent_repository.rs index 2125de554..ea0d215ee 100644 --- a/src/bootstrap/jobs/torrent_repository.rs +++ b/src/bootstrap/jobs/torrent_repository.rs @@ -14,7 +14,7 @@ pub fn start_event_listener(config: &Configuration, app_container: &Arc Date: Wed, 21 May 2025 17:11:52 +0100 Subject: [PATCH 1122/1297] feat: [#1524] listens to torrent-repository events in the tracker-core pkg This will enable udpating stats (number of torrent downloads per torrent) from the event handler (persisting in the DB). And after that, I will enable adding lebeled metrics. --- Cargo.lock | 1 + packages/tracker-core/Cargo.toml | 1 + packages/tracker-core/src/lib.rs | 3 ++ .../src/statistics/event/handler.rs | 32 ++++++++++++ .../src/statistics/event/listener.rs | 52 +++++++++++++++++++ .../tracker-core/src/statistics/event/mod.rs | 2 + packages/tracker-core/src/statistics/mod.rs | 1 + src/app.rs | 9 ++++ src/bootstrap/jobs/mod.rs | 1 + src/bootstrap/jobs/tracker_core.rs | 21 ++++++++ 10 files changed, 123 insertions(+) create mode 100644 packages/tracker-core/src/statistics/event/handler.rs create mode 100644 packages/tracker-core/src/statistics/event/listener.rs create mode 100644 packages/tracker-core/src/statistics/event/mod.rs create mode 100644 packages/tracker-core/src/statistics/mod.rs create mode 100644 src/bootstrap/jobs/tracker_core.rs diff --git a/Cargo.lock b/Cargo.lock index 6e4ab415f..5415149e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -676,6 +676,7 @@ dependencies = [ "torrust-rest-tracker-api-client", "torrust-tracker-clock", "torrust-tracker-configuration", + "torrust-tracker-events", "torrust-tracker-located-error", "torrust-tracker-primitives", "torrust-tracker-test-helpers", diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index ac1cee88d..3c89505b2 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -29,6 +29,7 @@ thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } +torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index 82ebac3c6..dacf41383 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -124,6 +124,7 @@ pub mod container; pub mod databases; pub mod error; pub mod scrape_handler; +pub mod statistics; pub mod torrent; pub mod whitelist; @@ -156,6 +157,8 @@ pub(crate) type CurrentClock = clock::Working; #[allow(dead_code)] pub(crate) type CurrentClock = clock::Stopped; +pub const TRACKER_CORE_LOG_TARGET: &str = "TRACKER_CORE"; + #[cfg(test)] mod tests { mod the_tracker { diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs new file mode 100644 index 000000000..bdd4d414b --- /dev/null +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -0,0 +1,32 @@ +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use torrust_tracker_torrent_repository::event::Event; + +pub async fn handle_event(event: Event, _now: DurationSinceUnixEpoch) { + match event { + // Torrent events + Event::TorrentAdded { info_hash, .. } => { + tracing::debug!(info_hash = ?info_hash, "Torrent added",); + } + Event::TorrentRemoved { info_hash } => { + tracing::debug!(info_hash = ?info_hash, "Torrent removed",); + } + + // Peer events + Event::PeerAdded { info_hash, peer } => { + tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer added", ); + } + Event::PeerRemoved { info_hash, peer } => { + tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer removed", ); + } + Event::PeerUpdated { + info_hash, + old_peer, + new_peer, + } => { + tracing::debug!(info_hash = ?info_hash, old_peer = ?old_peer, new_peer = ?new_peer, "Peer updated"); + } + Event::PeerDownloadCompleted { info_hash, peer } => { + tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer download completed", ); + } + } +} diff --git a/packages/tracker-core/src/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs new file mode 100644 index 000000000..2fe068b76 --- /dev/null +++ b/packages/tracker-core/src/statistics/event/listener.rs @@ -0,0 +1,52 @@ +use tokio::task::JoinHandle; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_events::receiver::RecvError; +use torrust_tracker_torrent_repository::event::receiver::Receiver; + +use super::handler::handle_event; +use crate::{CurrentClock, TRACKER_CORE_LOG_TARGET}; + +#[must_use] +pub fn run_event_listener(receiver: Receiver) -> JoinHandle<()> { + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Starting torrent repository event listener"); + + tokio::spawn(async move { + dispatch_events(receiver).await; + + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Torrent repository listener finished"); + }) +} + +async fn dispatch_events(mut receiver: Receiver) { + let shutdown_signal = tokio::signal::ctrl_c(); + + tokio::pin!(shutdown_signal); + + loop { + tokio::select! { + biased; + + _ = &mut shutdown_signal => { + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Received Ctrl+C, shutting down torrent repository event listener"); + break; + } + + result = receiver.recv() => { + match result { + Ok(event) => handle_event(event, CurrentClock::now()).await, + Err(e) => { + match e { + RecvError::Closed => { + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Torrent repository event receiver closed"); + break; + } + RecvError::Lagged(n) => { + tracing::warn!(target: TRACKER_CORE_LOG_TARGET, "Torrent repository event receiver lagged by {} events", n); + } + } + } + } + } + } + } +} diff --git a/packages/tracker-core/src/statistics/event/mod.rs b/packages/tracker-core/src/statistics/event/mod.rs new file mode 100644 index 000000000..dae683398 --- /dev/null +++ b/packages/tracker-core/src/statistics/event/mod.rs @@ -0,0 +1,2 @@ +pub mod handler; +pub mod listener; diff --git a/packages/tracker-core/src/statistics/mod.rs b/packages/tracker-core/src/statistics/mod.rs new file mode 100644 index 000000000..53f112654 --- /dev/null +++ b/packages/tracker-core/src/statistics/mod.rs @@ -0,0 +1 @@ +pub mod event; diff --git a/src/app.rs b/src/app.rs index 5180e4583..3b6abb86f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -75,6 +75,7 @@ async fn start_jobs(config: &Configuration, app_container: &Arc) - let mut job_manager = JobManager::new(); start_torrent_repository_event_listener(config, app_container, &mut job_manager); + start_tracker_core_event_listener(config, app_container, &mut job_manager); start_http_core_event_listener(config, app_container, &mut job_manager); start_udp_core_event_listener(config, app_container, &mut job_manager); start_udp_server_event_listener(config, app_container, &mut job_manager); @@ -145,6 +146,14 @@ fn start_torrent_repository_event_listener( } } +fn start_tracker_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { + let opt_handle = jobs::tracker_core::start_event_listener(config, app_container); + + if let Some(handle) = opt_handle { + job_manager.push("tracker_core_event_listener", handle); + } +} + fn start_http_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { let opt_handle = jobs::http_tracker_core::start_event_listener(config, app_container); diff --git a/src/bootstrap/jobs/mod.rs b/src/bootstrap/jobs/mod.rs index c8d7a8598..0e9c912af 100644 --- a/src/bootstrap/jobs/mod.rs +++ b/src/bootstrap/jobs/mod.rs @@ -14,6 +14,7 @@ pub mod manager; pub mod torrent_cleanup; pub mod torrent_repository; pub mod tracker_apis; +pub mod tracker_core; pub mod udp_tracker; pub mod udp_tracker_core; pub mod udp_tracker_server; diff --git a/src/bootstrap/jobs/tracker_core.rs b/src/bootstrap/jobs/tracker_core.rs new file mode 100644 index 000000000..28eb745c2 --- /dev/null +++ b/src/bootstrap/jobs/tracker_core.rs @@ -0,0 +1,21 @@ +use std::sync::Arc; + +use tokio::task::JoinHandle; +use torrust_tracker_configuration::Configuration; + +use crate::container::AppContainer; + +pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { + // todo: enable this when labeled metrics are implemented. + //if config.core.tracker_usage_statistics || config.core.tracker_policy.persistent_torrent_completed_stat { + if config.core.tracker_policy.persistent_torrent_completed_stat { + let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( + app_container.torrent_repository_container.event_bus.receiver(), + ); + + Some(job) + } else { + tracing::info!("Tracker core event listener job is disabled."); + None + } +} From 896875738f62b863bb87f27558f0e2344703110a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 21 May 2025 17:26:05 +0100 Subject: [PATCH 1123/1297] refactor: extract method JobManger::push_opt --- src/app.rs | 45 ++++++++++++++++------------------- src/bootstrap/jobs/manager.rs | 6 +++++ 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/src/app.rs b/src/app.rs index 3b6abb86f..5037ad761 100644 --- a/src/app.rs +++ b/src/app.rs @@ -139,43 +139,38 @@ fn start_torrent_repository_event_listener( app_container: &Arc, job_manager: &mut JobManager, ) { - let opt_handle = jobs::torrent_repository::start_event_listener(config, app_container); - - if let Some(handle) = opt_handle { - job_manager.push("torrent_repository_event_listener", handle); - } + job_manager.push_opt( + "torrent_repository_event_listener", + jobs::torrent_repository::start_event_listener(config, app_container), + ); } fn start_tracker_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { - let opt_handle = jobs::tracker_core::start_event_listener(config, app_container); - - if let Some(handle) = opt_handle { - job_manager.push("tracker_core_event_listener", handle); - } + job_manager.push_opt( + "tracker_core_event_listener", + jobs::tracker_core::start_event_listener(config, app_container), + ); } fn start_http_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { - let opt_handle = jobs::http_tracker_core::start_event_listener(config, app_container); - - if let Some(handle) = opt_handle { - job_manager.push("http_core_event_listener", handle); - } + job_manager.push_opt( + "http_core_event_listener", + jobs::http_tracker_core::start_event_listener(config, app_container), + ); } fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { - let opt_handle = jobs::udp_tracker_core::start_event_listener(config, app_container); - - if let Some(handle) = opt_handle { - job_manager.push("udp_core_event_listener", handle); - } + job_manager.push_opt( + "udp_core_event_listener", + jobs::udp_tracker_core::start_event_listener(config, app_container), + ); } fn start_udp_server_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { - let opt_handle = jobs::udp_tracker_server::start_event_listener(config, app_container); - - if let Some(handle) = opt_handle { - job_manager.push("udp_server_event_listener", handle); - } + job_manager.push_opt( + "udp_server_event_listener", + jobs::udp_tracker_server::start_event_listener(config, app_container), + ); } async fn start_the_udp_instances(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { diff --git a/src/bootstrap/jobs/manager.rs b/src/bootstrap/jobs/manager.rs index 5beab3224..53733844b 100644 --- a/src/bootstrap/jobs/manager.rs +++ b/src/bootstrap/jobs/manager.rs @@ -36,6 +36,12 @@ impl JobManager { self.jobs.push(Job::new(name, handle)); } + pub fn push_opt>(&mut self, name: N, handle: Option>) { + if let Some(handle) = handle { + self.push(name, handle); + } + } + /// Waits sequentially for all jobs to complete, with a graceful timeout per /// job. pub async fn wait_for_all(mut self, grace_period: Duration) { From e90585af80fc7a153708731ef1d5488da4e549d6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 21 May 2025 18:16:39 +0100 Subject: [PATCH 1124/1297] refactor: [#1524] move total downloads udpate from announce command to event handler --- packages/tracker-core/src/announce_handler.rs | 11 ++++++----- .../src/statistics/event/handler.rs | 19 ++++++++++++++++++- .../src/statistics/event/listener.rs | 16 ++++++++++++---- src/bootstrap/jobs/tracker_core.rs | 1 + 4 files changed, 37 insertions(+), 10 deletions(-) diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index a2e8db743..61e5de125 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -163,6 +163,11 @@ impl AnnounceHandler { ) -> Result { self.whitelist_authorization.authorize(info_hash).await?; + // This will be removed in the future. + // See https://github.com/torrust/torrust-tracker/issues/1502 + // There will be a persisted metric for counting the total number of + // downloads across all torrents. The in-memory metric will count only + // the number of downloads during the current tracker uptime. let opt_persistent_torrent = if self.config.tracker_policy.persistent_torrent_completed_stat { self.db_torrent_repository.load(info_hash)? } else { @@ -171,15 +176,11 @@ impl AnnounceHandler { peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); - let number_of_downloads_increased = self + let _number_of_downloads_increased = self .in_memory_torrent_repository .upsert_peer(info_hash, peer, opt_persistent_torrent) .await; - if self.config.tracker_policy.persistent_torrent_completed_stat && number_of_downloads_increased { - self.db_torrent_repository.increase_number_of_downloads(info_hash)?; - } - Ok(self.build_announce_data(info_hash, peer, peers_wanted).await) } diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs index bdd4d414b..7b6ce83b7 100644 --- a/packages/tracker-core/src/statistics/event/handler.rs +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -1,7 +1,15 @@ +use std::sync::Arc; + use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_torrent_repository::event::Event; -pub async fn handle_event(event: Event, _now: DurationSinceUnixEpoch) { +use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; + +pub async fn handle_event( + event: Event, + db_torrent_repository: &Arc, + _now: DurationSinceUnixEpoch, +) { match event { // Torrent events Event::TorrentAdded { info_hash, .. } => { @@ -27,6 +35,15 @@ pub async fn handle_event(event: Event, _now: DurationSinceUnixEpoch) { } Event::PeerDownloadCompleted { info_hash, peer } => { tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer download completed", ); + + match db_torrent_repository.increase_number_of_downloads(&info_hash) { + Ok(()) => { + tracing::debug!(info_hash = ?info_hash, "Number of downloads increased"); + } + Err(err) => { + tracing::error!(info_hash = ?info_hash, error = ?err, "Failed to increase number of downloads"); + } + } } } } diff --git a/packages/tracker-core/src/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs index 2fe068b76..e04675092 100644 --- a/packages/tracker-core/src/statistics/event/listener.rs +++ b/packages/tracker-core/src/statistics/event/listener.rs @@ -1,23 +1,31 @@ +use std::sync::Arc; + use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; use torrust_tracker_events::receiver::RecvError; use torrust_tracker_torrent_repository::event::receiver::Receiver; use super::handler::handle_event; +use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; use crate::{CurrentClock, TRACKER_CORE_LOG_TARGET}; #[must_use] -pub fn run_event_listener(receiver: Receiver) -> JoinHandle<()> { +pub fn run_event_listener( + receiver: Receiver, + db_torrent_repository: &Arc, +) -> JoinHandle<()> { + let db_torrent_repository: Arc = db_torrent_repository.clone(); + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Starting torrent repository event listener"); tokio::spawn(async move { - dispatch_events(receiver).await; + dispatch_events(receiver, db_torrent_repository).await; tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Torrent repository listener finished"); }) } -async fn dispatch_events(mut receiver: Receiver) { +async fn dispatch_events(mut receiver: Receiver, db_torrent_repository: Arc) { let shutdown_signal = tokio::signal::ctrl_c(); tokio::pin!(shutdown_signal); @@ -33,7 +41,7 @@ async fn dispatch_events(mut receiver: Receiver) { result = receiver.recv() => { match result { - Ok(event) => handle_event(event, CurrentClock::now()).await, + Ok(event) => handle_event(event, &db_torrent_repository, CurrentClock::now()).await, Err(e) => { match e { RecvError::Closed => { diff --git a/src/bootstrap/jobs/tracker_core.rs b/src/bootstrap/jobs/tracker_core.rs index 28eb745c2..bb879db6b 100644 --- a/src/bootstrap/jobs/tracker_core.rs +++ b/src/bootstrap/jobs/tracker_core.rs @@ -11,6 +11,7 @@ pub fn start_event_listener(config: &Configuration, app_container: &Arc Date: Mon, 26 May 2025 09:45:42 +0100 Subject: [PATCH 1125/1297] refactor: [#1524] remove duplciate code for tracker core container --- packages/tracker-core/tests/integration.rs | 49 ++++------------------ 1 file changed, 7 insertions(+), 42 deletions(-) diff --git a/packages/tracker-core/tests/integration.rs b/packages/tracker-core/tests/integration.rs index 5aaded10a..282dcade5 100644 --- a/packages/tracker-core/tests/integration.rs +++ b/packages/tracker-core/tests/integration.rs @@ -4,17 +4,13 @@ use std::sync::Arc; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; -use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; -use bittorrent_tracker_core::databases::setup::initialize_database; -use bittorrent_tracker_core::scrape_handler::ScrapeHandler; -use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; -use bittorrent_tracker_core::whitelist; -use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; +use bittorrent_tracker_core::announce_handler::PeersWanted; +use bittorrent_tracker_core::container::TrackerCoreContainer; use torrust_tracker_configuration::Core; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; +use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; /// # Panics /// @@ -59,41 +55,13 @@ fn remote_client_ip() -> IpAddr { IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) } -struct Container { - pub announce_handler: Arc, - pub scrape_handler: Arc, -} - -impl Container { - pub fn initialize(config: &Core) -> Self { - let database = initialize_database(config); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(whitelist::authorization::WhitelistAuthorization::new( - config, - &in_memory_whitelist.clone(), - )); - let announce_handler = Arc::new(AnnounceHandler::new( - config, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); - - Self { - announce_handler, - scrape_handler, - } - } -} - #[tokio::test] async fn test_announce_and_scrape_requests() { - let config = ephemeral_configuration(); + let config = Arc::new(ephemeral_configuration()); + + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize(config.tracker_usage_statistics.into())); - let container = Container::initialize(&config); + let container = TrackerCoreContainer::initialize_from(&config, &torrent_repository_container); let info_hash = sample_info_hash(); @@ -130,6 +98,3 @@ async fn test_announce_and_scrape_requests() { assert!(scrape_data.files.contains_key(&info_hash)); } - -#[test] -fn test_scrape_request() {} From b05bccdccc90ed73f63ac9f9c61fcbfaa75f7bbf Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 26 May 2025 10:02:49 +0100 Subject: [PATCH 1126/1297] refactor: [#1524] integration tests in tracker-core --- packages/tracker-core/tests/integration.rs | 58 +++++++++++++++------- 1 file changed, 39 insertions(+), 19 deletions(-) diff --git a/packages/tracker-core/tests/integration.rs b/packages/tracker-core/tests/integration.rs index 282dcade5..f59b9d185 100644 --- a/packages/tracker-core/tests/integration.rs +++ b/packages/tracker-core/tests/integration.rs @@ -7,6 +7,7 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::PeersWanted; use bittorrent_tracker_core::container::TrackerCoreContainer; use torrust_tracker_configuration::Core; +use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; @@ -55,44 +56,63 @@ fn remote_client_ip() -> IpAddr { IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) } -#[tokio::test] -async fn test_announce_and_scrape_requests() { +fn initialize() -> (Arc, Arc, InfoHash, Peer) { let config = Arc::new(ephemeral_configuration()); let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize(config.tracker_usage_statistics.into())); - let container = TrackerCoreContainer::initialize_from(&config, &torrent_repository_container); + let container = Arc::new(TrackerCoreContainer::initialize_from(&config, &torrent_repository_container)); let info_hash = sample_info_hash(); - let mut peer = sample_peer(); + let peer = sample_peer(); - // Announce + (config, container, info_hash, peer) +} - // First announce: download started +async fn announce_peer_started(container: &Arc, peer: &mut Peer, info_hash: &InfoHash) -> AnnounceData { peer.event = AnnounceEvent::Started; - let announce_data = container + + container .announce_handler - .announce(&info_hash, &mut peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible) + .announce(info_hash, peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible) .await - .unwrap(); - - // NOTICE: you don't get back the peer making the request. - assert_eq!(announce_data.peers.len(), 0); - assert_eq!(announce_data.stats.downloaded, 0); + .unwrap() +} - // Second announce: download completed +async fn _announce_peer_completed(container: &Arc, peer: &mut Peer, info_hash: &InfoHash) -> AnnounceData { peer.event = AnnounceEvent::Completed; - let announce_data = container + + container .announce_handler - .announce(&info_hash, &mut peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible) + .announce(info_hash, peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible) .await - .unwrap(); + .unwrap() +} + +#[tokio::test] +async fn it_should_handle_the_announce_request() { + let (_config, container, info_hash, mut peer) = initialize(); + + let announce_data = announce_peer_started(&container, &mut peer, &info_hash).await; + + assert_eq!(announce_data, AnnounceData::default()); +} + +#[tokio::test] +async fn it_should_not_return_the_peer_making_the_announce_request() { + let (_config, container, info_hash, mut peer) = initialize(); + + let announce_data = announce_peer_started(&container, &mut peer, &info_hash).await; assert_eq!(announce_data.peers.len(), 0); - assert_eq!(announce_data.stats.downloaded, 1); +} + +#[tokio::test] +async fn it_should_handle_the_scrape_request() { + let (_config, container, info_hash, mut peer) = initialize(); - // Scrape + let _announce_data = announce_peer_started(&container, &mut peer, &info_hash).await; let scrape_data = container.scrape_handler.scrape(&vec![info_hash]).await.unwrap(); From ab2f52dd3781d58d56d997b42e185c2f102feafc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 26 May 2025 12:54:12 +0100 Subject: [PATCH 1127/1297] fix: [#1524] test (move to integration test) --- packages/tracker-core/src/announce_handler.rs | 77 ----------- packages/tracker-core/src/torrent/manager.rs | 2 + .../src/torrent/repository/in_memory.rs | 19 --- packages/tracker-core/tests/integration.rs | 121 +++++++++++++++--- 4 files changed, 106 insertions(+), 113 deletions(-) diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 61e5de125..0a3fef045 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -594,83 +594,6 @@ mod tests { } } - mod handling_torrent_persistence { - - use std::sync::Arc; - - use aquatic_udp_protocol::AnnounceEvent; - use torrust_tracker_test_helpers::configuration; - use torrust_tracker_torrent_repository::Swarms; - - use crate::announce_handler::tests::the_announce_handler::peer_ip; - use crate::announce_handler::{AnnounceHandler, PeersWanted}; - use crate::databases::setup::initialize_database; - use crate::test_helpers::tests::{sample_info_hash, sample_peer}; - use crate::torrent::manager::TorrentsManager; - use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; - use crate::whitelist::authorization::WhitelistAuthorization; - use crate::whitelist::repository::in_memory::InMemoryWhitelist; - - #[tokio::test] - async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { - let mut config = configuration::ephemeral_public(); - - config.core.tracker_policy.persistent_torrent_completed_stat = true; - - let database = initialize_database(&config.core); - let swarms = Arc::new(Swarms::default()); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new(swarms)); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); - let torrents_manager = Arc::new(TorrentsManager::new( - &config.core, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); - let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); - let announce_handler = Arc::new(AnnounceHandler::new( - &config.core, - &whitelist_authorization, - &in_memory_torrent_repository, - &db_torrent_repository, - )); - - let info_hash = sample_info_hash(); - - let mut peer = sample_peer(); - - peer.event = AnnounceEvent::Started; - let announce_data = announce_handler - .announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) - .await - .unwrap(); - assert_eq!(announce_data.stats.downloaded, 0); - - peer.event = AnnounceEvent::Completed; - let announce_data = announce_handler - .announce(&info_hash, &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) - .await - .unwrap(); - assert_eq!(announce_data.stats.downloaded, 1); - - // Remove the newly updated torrent from memory - let _unused = in_memory_torrent_repository.remove(&info_hash).await; - - torrents_manager.load_torrents_from_database().unwrap(); - - let torrent_entry = in_memory_torrent_repository - .get(&info_hash) - .expect("it should be able to get entry"); - - // It persists the number of completed peers. - assert_eq!(torrent_entry.lock().await.metadata().downloaded, 1); - - // It does not persist the peers - assert!(torrent_entry.lock().await.is_empty()); - } - } - mod should_allow_the_client_peers_to_specified_the_number_of_peers_wanted { use torrust_tracker_configuration::TORRENT_PEERS_LIMIT; diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index bf73f7e8b..f463eee98 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -74,6 +74,8 @@ impl TorrentsManager { pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { let persistent_torrents = self.db_torrent_repository.load_all()?; + println!("Loaded {} persistent torrents from the database", persistent_torrents.len()); + self.in_memory_torrent_repository.import_persistent(&persistent_torrents); Ok(()) diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 311480306..bf8d083f8 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -61,25 +61,6 @@ impl InMemoryTorrentRepository { .expect("Failed to upsert the peer in swarms") } - /// Removes a torrent entry from the repository. - /// - /// This method is only available in tests. It removes the torrent entry - /// associated with the given info hash and returns the removed entry if it - /// existed. - /// - /// # Arguments - /// - /// * `key` - The info hash of the torrent to remove. - /// - /// # Returns - /// - /// An `Option` containing the removed torrent entry if it existed. - #[cfg(test)] - #[must_use] - pub(crate) async fn remove(&self, key: &InfoHash) -> Option { - self.swarms.remove(key).await - } - /// Removes inactive peers from all torrent entries. /// /// A peer is considered inactive if its last update timestamp is older than diff --git a/packages/tracker-core/tests/integration.rs b/packages/tracker-core/tests/integration.rs index f59b9d185..7af0ec4fa 100644 --- a/packages/tracker-core/tests/integration.rs +++ b/packages/tracker-core/tests/integration.rs @@ -6,12 +6,15 @@ use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::PeersWanted; use bittorrent_tracker_core::container::TrackerCoreContainer; -use torrust_tracker_configuration::Core; +use tokio::task::yield_now; +use torrust_tracker_configuration::{AnnouncePolicy, Core}; use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; +use torrust_tracker_torrent_repository::Swarms; /// # Panics /// @@ -56,52 +59,114 @@ fn remote_client_ip() -> IpAddr { IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) } -fn initialize() -> (Arc, Arc, InfoHash, Peer) { - let config = Arc::new(ephemeral_configuration()); - - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize(config.tracker_usage_statistics.into())); - - let container = Arc::new(TrackerCoreContainer::initialize_from(&config, &torrent_repository_container)); +async fn initialize_test_env(core_config: Core) -> (Arc, Arc, Arc, InfoHash, Peer) { + let config = Arc::new(core_config); let info_hash = sample_info_hash(); let peer = sample_peer(); - (config, container, info_hash, peer) + let (container, swarms) = start(&config).await; + + (config, container, swarms, info_hash, peer) +} + +async fn start(core_config: &Arc) -> (Arc, Arc) { + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); + + let container = Arc::new(TrackerCoreContainer::initialize_from( + core_config, + &torrent_repository_container, + )); + + let mut jobs = vec![]; + + let job = torrust_tracker_torrent_repository::statistics::event::listener::run_event_listener( + torrent_repository_container.event_bus.receiver(), + &torrent_repository_container.stats_repository, + ); + + jobs.push(job); + + let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( + torrent_repository_container.event_bus.receiver(), + &container.db_torrent_repository, + ); + + jobs.push(job); + + // Give the event listeners some time to start + // todo: they should notify when they are ready + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + + (container, torrent_repository_container.swarms.clone()) } async fn announce_peer_started(container: &Arc, peer: &mut Peer, info_hash: &InfoHash) -> AnnounceData { peer.event = AnnounceEvent::Started; - container + let announce_data = container .announce_handler .announce(info_hash, peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible) .await - .unwrap() + .unwrap(); + + // Give time to the event listeners to process the event + yield_now().await; + + announce_data } -async fn _announce_peer_completed(container: &Arc, peer: &mut Peer, info_hash: &InfoHash) -> AnnounceData { +async fn announce_peer_completed(container: &Arc, peer: &mut Peer, info_hash: &InfoHash) -> AnnounceData { peer.event = AnnounceEvent::Completed; - container + let announce_data = container .announce_handler .announce(info_hash, peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible) .await - .unwrap() + .unwrap(); + + // Give time to the event listeners to process the event + yield_now().await; + + announce_data +} + +async fn increase_number_of_downloads(container: &Arc, peer: &mut Peer, info_hash: &InfoHash) { + let _announce_data = announce_peer_started(container, peer, info_hash).await; + let announce_data = announce_peer_completed(container, peer, info_hash).await; + + assert_eq!(announce_data.stats.downloads(), 1); } #[tokio::test] async fn it_should_handle_the_announce_request() { - let (_config, container, info_hash, mut peer) = initialize(); + let (_config, container, _swarms, info_hash, mut peer) = initialize_test_env(ephemeral_configuration()).await; let announce_data = announce_peer_started(&container, &mut peer, &info_hash).await; - assert_eq!(announce_data, AnnounceData::default()); + assert_eq!( + announce_data, + AnnounceData { + peers: vec![], + stats: SwarmMetadata { + downloaded: 0, + complete: 1, + incomplete: 0 + }, + policy: AnnouncePolicy { + interval: 120, + interval_min: 120 + } + } + ); } #[tokio::test] async fn it_should_not_return_the_peer_making_the_announce_request() { - let (_config, container, info_hash, mut peer) = initialize(); + let (_config, container, _swarms, info_hash, mut peer) = initialize_test_env(ephemeral_configuration()).await; let announce_data = announce_peer_started(&container, &mut peer, &info_hash).await; @@ -110,7 +175,7 @@ async fn it_should_not_return_the_peer_making_the_announce_request() { #[tokio::test] async fn it_should_handle_the_scrape_request() { - let (_config, container, info_hash, mut peer) = initialize(); + let (_config, container, _swarms, info_hash, mut peer) = initialize_test_env(ephemeral_configuration()).await; let _announce_data = announce_peer_started(&container, &mut peer, &info_hash).await; @@ -118,3 +183,25 @@ async fn it_should_handle_the_scrape_request() { assert!(scrape_data.files.contains_key(&info_hash)); } + +#[tokio::test] +async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { + let mut core_config = ephemeral_configuration(); + core_config.tracker_policy.persistent_torrent_completed_stat = true; + + let (_config, container, swarms, info_hash, mut peer) = initialize_test_env(core_config).await; + + increase_number_of_downloads(&container, &mut peer, &info_hash).await; + + assert!(swarms.get_swarm_metadata(&info_hash).await.unwrap().unwrap().downloads() == 1); + + swarms.remove(&info_hash).await.unwrap(); + + // Make sure the swarm metadata is removed + assert!(swarms.get_swarm_metadata(&info_hash).await.unwrap().is_none()); + + // Load torrents from the database to ensure the completed stats are persisted + container.torrents_manager.load_torrents_from_database().unwrap(); + + assert!(swarms.get_swarm_metadata(&info_hash).await.unwrap().unwrap().downloads() == 1); +} From 28603fe1d877ab26076ff3e9c10a246e26122fab Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 26 May 2025 13:38:26 +0100 Subject: [PATCH 1128/1297] refactor: [#1524] extract TestEnv for integration tests in tracker-core --- .../tracker-core/tests/common/fixtures.rs | 52 +++++ packages/tracker-core/tests/common/mod.rs | 2 + .../tracker-core/tests/common/test_env.rs | 137 +++++++++++++ packages/tracker-core/tests/integration.rs | 191 ++++-------------- 4 files changed, 227 insertions(+), 155 deletions(-) create mode 100644 packages/tracker-core/tests/common/fixtures.rs create mode 100644 packages/tracker-core/tests/common/mod.rs create mode 100644 packages/tracker-core/tests/common/test_env.rs diff --git a/packages/tracker-core/tests/common/fixtures.rs b/packages/tracker-core/tests/common/fixtures.rs new file mode 100644 index 000000000..ea9c93a65 --- /dev/null +++ b/packages/tracker-core/tests/common/fixtures.rs @@ -0,0 +1,52 @@ +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::str::FromStr; + +use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; +use bittorrent_primitives::info_hash::InfoHash; +use torrust_tracker_configuration::Core; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::DurationSinceUnixEpoch; +use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; + +/// # Panics +/// +/// Will panic if the temporary file path is not a valid UTF-8 string. +#[must_use] +pub fn ephemeral_configuration() -> Core { + let mut config = Core::default(); + + let temp_file = ephemeral_sqlite_database(); + temp_file.to_str().unwrap().clone_into(&mut config.database.path); + + config +} + +/// # Panics +/// +/// Will panic if the string representation of the info hash is not a valid infohash. +#[must_use] +pub fn sample_info_hash() -> InfoHash { + "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 + .parse::() + .expect("String should be a valid info hash") +} + +/// Sample peer whose state is not relevant for the tests. +#[must_use] +pub fn sample_peer() -> Peer { + Peer { + peer_id: PeerId(*b"-qB00000000000000000"), + peer_addr: SocketAddr::new(remote_client_ip(), 8080), + updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), + uploaded: NumberOfBytes::new(0), + downloaded: NumberOfBytes::new(0), + left: NumberOfBytes::new(0), // No bytes left to download + event: AnnounceEvent::Completed, + } +} + +// The client peer IP. +#[must_use] +pub fn remote_client_ip() -> IpAddr { + IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) +} diff --git a/packages/tracker-core/tests/common/mod.rs b/packages/tracker-core/tests/common/mod.rs new file mode 100644 index 000000000..414e9d7b5 --- /dev/null +++ b/packages/tracker-core/tests/common/mod.rs @@ -0,0 +1,2 @@ +pub mod fixtures; +pub mod test_env; diff --git a/packages/tracker-core/tests/common/test_env.rs b/packages/tracker-core/tests/common/test_env.rs new file mode 100644 index 000000000..8a443d8f0 --- /dev/null +++ b/packages/tracker-core/tests/common/test_env.rs @@ -0,0 +1,137 @@ +use std::net::IpAddr; +use std::sync::Arc; + +use aquatic_udp_protocol::AnnounceEvent; +use bittorrent_primitives::info_hash::InfoHash; +use bittorrent_tracker_core::announce_handler::PeersWanted; +use bittorrent_tracker_core::container::TrackerCoreContainer; +use tokio::task::yield_now; +use torrust_tracker_configuration::Core; +use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; +use torrust_tracker_primitives::peer::Peer; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; + +pub struct TestEnv { + pub torrent_repository_container: Arc, + pub tracker_core_container: Arc, +} + +impl TestEnv { + #[must_use] + pub async fn started(core_config: Core) -> Self { + let test_env = TestEnv::new(core_config); + test_env.start().await; + test_env + } + + #[must_use] + pub fn new(core_config: Core) -> Self { + let core_config = Arc::new(core_config); + + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + core_config.tracker_usage_statistics.into(), + )); + + let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( + &core_config, + &torrent_repository_container, + )); + + Self { + torrent_repository_container, + tracker_core_container, + } + } + + pub async fn start(&self) { + let mut jobs = vec![]; + + let job = torrust_tracker_torrent_repository::statistics::event::listener::run_event_listener( + self.torrent_repository_container.event_bus.receiver(), + &self.torrent_repository_container.stats_repository, + ); + + jobs.push(job); + + let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( + self.torrent_repository_container.event_bus.receiver(), + &self.tracker_core_container.db_torrent_repository, + ); + + jobs.push(job); + + // Give the event listeners some time to start + // todo: they should notify when they are ready + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + + pub async fn announce_peer_started( + &mut self, + mut peer: Peer, + remote_client_ip: &IpAddr, + info_hash: &InfoHash, + ) -> AnnounceData { + peer.event = AnnounceEvent::Started; + + let announce_data = self + .tracker_core_container + .announce_handler + .announce(info_hash, &mut peer, remote_client_ip, &PeersWanted::AsManyAsPossible) + .await + .unwrap(); + + // Give time to the event listeners to process the event + yield_now().await; + + announce_data + } + + pub async fn announce_peer_completed( + &mut self, + mut peer: Peer, + remote_client_ip: &IpAddr, + info_hash: &InfoHash, + ) -> AnnounceData { + peer.event = AnnounceEvent::Completed; + + let announce_data = self + .tracker_core_container + .announce_handler + .announce(info_hash, &mut peer, remote_client_ip, &PeersWanted::AsManyAsPossible) + .await + .unwrap(); + + // Give time to the event listeners to process the event + yield_now().await; + + announce_data + } + + pub async fn scrape(&self, info_hash: &InfoHash) -> ScrapeData { + self.tracker_core_container + .scrape_handler + .scrape(&vec![*info_hash]) + .await + .unwrap() + } + + pub async fn increase_number_of_downloads(&mut self, peer: Peer, remote_client_ip: &IpAddr, info_hash: &InfoHash) { + let _announce_data = self.announce_peer_started(peer, remote_client_ip, info_hash).await; + let announce_data = self.announce_peer_completed(peer, remote_client_ip, info_hash).await; + + assert_eq!(announce_data.stats.downloads(), 1); + } + + pub async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { + self.torrent_repository_container + .swarms + .get_swarm_metadata(info_hash) + .await + .unwrap() + } + + pub async fn remove_swarm(&self, info_hash: &InfoHash) { + self.torrent_repository_container.swarms.remove(info_hash).await.unwrap(); + } +} diff --git a/packages/tracker-core/tests/integration.rs b/packages/tracker-core/tests/integration.rs index 7af0ec4fa..d24acf67b 100644 --- a/packages/tracker-core/tests/integration.rs +++ b/packages/tracker-core/tests/integration.rs @@ -1,151 +1,18 @@ -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use std::str::FromStr; -use std::sync::Arc; - -use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; -use bittorrent_primitives::info_hash::InfoHash; -use bittorrent_tracker_core::announce_handler::PeersWanted; -use bittorrent_tracker_core::container::TrackerCoreContainer; -use tokio::task::yield_now; -use torrust_tracker_configuration::{AnnouncePolicy, Core}; +mod common; + +use common::fixtures::{ephemeral_configuration, remote_client_ip, sample_info_hash, sample_peer}; +use common::test_env::TestEnv; +use torrust_tracker_configuration::AnnouncePolicy; use torrust_tracker_primitives::core::AnnounceData; -use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::DurationSinceUnixEpoch; -use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; -use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; -use torrust_tracker_torrent_repository::Swarms; - -/// # Panics -/// -/// Will panic if the temporary file path is not a valid UTF-8 string. -#[must_use] -pub fn ephemeral_configuration() -> Core { - let mut config = Core::default(); - - let temp_file = ephemeral_sqlite_database(); - temp_file.to_str().unwrap().clone_into(&mut config.database.path); - - config -} - -/// # Panics -/// -/// Will panic if the string representation of the info hash is not a valid infohash. -#[must_use] -pub fn sample_info_hash() -> InfoHash { - "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0" // DevSkim: ignore DS173237 - .parse::() - .expect("String should be a valid info hash") -} - -/// Sample peer whose state is not relevant for the tests. -#[must_use] -pub fn sample_peer() -> Peer { - Peer { - peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(remote_client_ip(), 8080), - updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), - uploaded: NumberOfBytes::new(0), - downloaded: NumberOfBytes::new(0), - left: NumberOfBytes::new(0), // No bytes left to download - event: AnnounceEvent::Completed, - } -} - -// The client peer IP. -#[must_use] -fn remote_client_ip() -> IpAddr { - IpAddr::V4(Ipv4Addr::from_str("126.0.0.1").unwrap()) -} - -async fn initialize_test_env(core_config: Core) -> (Arc, Arc, Arc, InfoHash, Peer) { - let config = Arc::new(core_config); - - let info_hash = sample_info_hash(); - - let peer = sample_peer(); - - let (container, swarms) = start(&config).await; - - (config, container, swarms, info_hash, peer) -} - -async fn start(core_config: &Arc) -> (Arc, Arc) { - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( - core_config.tracker_usage_statistics.into(), - )); - - let container = Arc::new(TrackerCoreContainer::initialize_from( - core_config, - &torrent_repository_container, - )); - - let mut jobs = vec![]; - - let job = torrust_tracker_torrent_repository::statistics::event::listener::run_event_listener( - torrent_repository_container.event_bus.receiver(), - &torrent_repository_container.stats_repository, - ); - - jobs.push(job); - - let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( - torrent_repository_container.event_bus.receiver(), - &container.db_torrent_repository, - ); - - jobs.push(job); - - // Give the event listeners some time to start - // todo: they should notify when they are ready - tokio::time::sleep(std::time::Duration::from_millis(100)).await; - - (container, torrent_repository_container.swarms.clone()) -} - -async fn announce_peer_started(container: &Arc, peer: &mut Peer, info_hash: &InfoHash) -> AnnounceData { - peer.event = AnnounceEvent::Started; - - let announce_data = container - .announce_handler - .announce(info_hash, peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible) - .await - .unwrap(); - - // Give time to the event listeners to process the event - yield_now().await; - - announce_data -} - -async fn announce_peer_completed(container: &Arc, peer: &mut Peer, info_hash: &InfoHash) -> AnnounceData { - peer.event = AnnounceEvent::Completed; - - let announce_data = container - .announce_handler - .announce(info_hash, peer, &remote_client_ip(), &PeersWanted::AsManyAsPossible) - .await - .unwrap(); - - // Give time to the event listeners to process the event - yield_now().await; - - announce_data -} - -async fn increase_number_of_downloads(container: &Arc, peer: &mut Peer, info_hash: &InfoHash) { - let _announce_data = announce_peer_started(container, peer, info_hash).await; - let announce_data = announce_peer_completed(container, peer, info_hash).await; - - assert_eq!(announce_data.stats.downloads(), 1); -} #[tokio::test] async fn it_should_handle_the_announce_request() { - let (_config, container, _swarms, info_hash, mut peer) = initialize_test_env(ephemeral_configuration()).await; + let mut test_env = TestEnv::started(ephemeral_configuration()).await; - let announce_data = announce_peer_started(&container, &mut peer, &info_hash).await; + let announce_data = test_env + .announce_peer_started(sample_peer(), &remote_client_ip(), &sample_info_hash()) + .await; assert_eq!( announce_data, @@ -166,20 +33,26 @@ async fn it_should_handle_the_announce_request() { #[tokio::test] async fn it_should_not_return_the_peer_making_the_announce_request() { - let (_config, container, _swarms, info_hash, mut peer) = initialize_test_env(ephemeral_configuration()).await; + let mut test_env = TestEnv::started(ephemeral_configuration()).await; - let announce_data = announce_peer_started(&container, &mut peer, &info_hash).await; + let announce_data = test_env + .announce_peer_started(sample_peer(), &remote_client_ip(), &sample_info_hash()) + .await; assert_eq!(announce_data.peers.len(), 0); } #[tokio::test] async fn it_should_handle_the_scrape_request() { - let (_config, container, _swarms, info_hash, mut peer) = initialize_test_env(ephemeral_configuration()).await; + let mut test_env = TestEnv::started(ephemeral_configuration()).await; - let _announce_data = announce_peer_started(&container, &mut peer, &info_hash).await; + let info_hash = sample_info_hash(); + + let _announce_data = test_env + .announce_peer_started(sample_peer(), &remote_client_ip(), &info_hash) + .await; - let scrape_data = container.scrape_handler.scrape(&vec![info_hash]).await.unwrap(); + let scrape_data = test_env.scrape(&info_hash).await; assert!(scrape_data.files.contains_key(&info_hash)); } @@ -189,19 +62,27 @@ async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_t let mut core_config = ephemeral_configuration(); core_config.tracker_policy.persistent_torrent_completed_stat = true; - let (_config, container, swarms, info_hash, mut peer) = initialize_test_env(core_config).await; + let mut test_env = TestEnv::started(core_config).await; - increase_number_of_downloads(&container, &mut peer, &info_hash).await; + let info_hash = sample_info_hash(); - assert!(swarms.get_swarm_metadata(&info_hash).await.unwrap().unwrap().downloads() == 1); + test_env + .increase_number_of_downloads(sample_peer(), &remote_client_ip(), &info_hash) + .await; - swarms.remove(&info_hash).await.unwrap(); + assert!(test_env.get_swarm_metadata(&info_hash).await.unwrap().downloads() == 1); - // Make sure the swarm metadata is removed - assert!(swarms.get_swarm_metadata(&info_hash).await.unwrap().is_none()); + test_env.remove_swarm(&info_hash).await; + + // Ensure the swarm metadata is removed + assert!(test_env.get_swarm_metadata(&info_hash).await.is_none()); // Load torrents from the database to ensure the completed stats are persisted - container.torrents_manager.load_torrents_from_database().unwrap(); + test_env + .tracker_core_container + .torrents_manager + .load_torrents_from_database() + .unwrap(); - assert!(swarms.get_swarm_metadata(&info_hash).await.unwrap().unwrap().downloads() == 1); + assert!(test_env.get_swarm_metadata(&info_hash).await.unwrap().downloads() == 1); } From 8c3154953f80a221de63366bd10cc7111a71f126 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 26 May 2025 13:47:40 +0100 Subject: [PATCH 1129/1297] refactor: [#1524] rename methods --- .../src/environment.rs | 2 +- .../src/environment.rs | 2 +- .../src/services/announce.rs | 2 +- .../http-tracker-core/src/services/scrape.rs | 6 ++--- packages/tracker-core/src/announce_handler.rs | 24 +++++++++---------- packages/tracker-core/src/lib.rs | 8 +++---- packages/tracker-core/src/scrape_handler.rs | 6 ++--- packages/tracker-core/src/torrent/manager.rs | 4 ++-- .../src/torrent/repository/in_memory.rs | 2 +- packages/tracker-core/src/torrent/services.rs | 18 +++++++------- .../tracker-core/tests/common/test_env.rs | 6 ++--- .../udp-tracker-core/src/services/announce.rs | 2 +- .../udp-tracker-core/src/services/scrape.rs | 2 +- .../udp-tracker-server/src/environment.rs | 2 +- .../src/handlers/announce.rs | 4 ++-- .../udp-tracker-server/src/handlers/scrape.rs | 2 +- 16 files changed, 46 insertions(+), 46 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index 10dada2db..59605d781 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -29,7 +29,7 @@ impl Environment { self.container .tracker_core_container .in_memory_torrent_repository - .upsert_peer(info_hash, peer, None) + .handle_announcement(info_hash, peer, None) .await } } diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index 92ca5a2d1..3c7ff564d 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -37,7 +37,7 @@ where self.container .tracker_core_container .in_memory_torrent_repository - .upsert_peer(info_hash, peer, None) + .handle_announcement(info_hash, peer, None) .await } } diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 9f39a04e4..0ad5ed143 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -87,7 +87,7 @@ impl AnnounceService { let announce_data = self .announce_handler - .announce( + .handle_announcement( &announce_request.info_hash, &mut peer, &remote_client_addr.ip(), diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 3da1aa88f..f22f2f632 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -78,7 +78,7 @@ impl ScrapeService { let scrape_data = if self.authentication_is_required() && !self.is_authenticated(maybe_key).await { ScrapeData::zeroed(&scrape_request.info_hashes) } else { - self.scrape_handler.scrape(&scrape_request.info_hashes).await? + self.scrape_handler.handle_scrape(&scrape_request.info_hashes).await? }; let remote_client_addr = resolve_remote_client_addr(&self.core_config.net.on_reverse_proxy.into(), client_ip_sources)?; @@ -291,7 +291,7 @@ mod tests { let original_peer_ip = peer.ip(); container .announce_handler - .announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible) + .handle_announcement(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible) .await .unwrap(); @@ -482,7 +482,7 @@ mod tests { let original_peer_ip = peer.ip(); container .announce_handler - .announce(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible) + .handle_announcement(&info_hash, &mut peer, &original_peer_ip, &PeersWanted::AsManyAsPossible) .await .unwrap(); diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 0a3fef045..7d37ec9ed 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -154,7 +154,7 @@ impl AnnounceHandler { /// /// Returns an error if the tracker is running in `listed` mode and the /// torrent is not whitelisted. - pub async fn announce( + pub async fn handle_announcement( &self, info_hash: &InfoHash, peer: &mut peer::Peer, @@ -178,7 +178,7 @@ impl AnnounceHandler { let _number_of_downloads_increased = self .in_memory_torrent_repository - .upsert_peer(info_hash, peer, opt_persistent_torrent) + .handle_announcement(info_hash, peer, opt_persistent_torrent) .await; Ok(self.build_announce_data(info_hash, peer, peers_wanted).await) @@ -456,7 +456,7 @@ mod tests { let mut peer = sample_peer(); let announce_data = announce_handler - .announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .handle_announcement(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) .await .unwrap(); @@ -469,7 +469,7 @@ mod tests { let mut previously_announced_peer = sample_peer_1(); announce_handler - .announce( + .handle_announcement( &sample_info_hash(), &mut previously_announced_peer, &peer_ip(), @@ -480,7 +480,7 @@ mod tests { let mut peer = sample_peer_2(); let announce_data = announce_handler - .announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .handle_announcement(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) .await .unwrap(); @@ -493,7 +493,7 @@ mod tests { let mut previously_announced_peer_1 = sample_peer_1(); announce_handler - .announce( + .handle_announcement( &sample_info_hash(), &mut previously_announced_peer_1, &peer_ip(), @@ -504,7 +504,7 @@ mod tests { let mut previously_announced_peer_2 = sample_peer_2(); announce_handler - .announce( + .handle_announcement( &sample_info_hash(), &mut previously_announced_peer_2, &peer_ip(), @@ -515,7 +515,7 @@ mod tests { let mut peer = sample_peer_3(); let announce_data = announce_handler - .announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::only(1)) + .handle_announcement(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::only(1)) .await .unwrap(); @@ -540,7 +540,7 @@ mod tests { let mut peer = seeder(); let announce_data = announce_handler - .announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .handle_announcement(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) .await .unwrap(); @@ -554,7 +554,7 @@ mod tests { let mut peer = leecher(); let announce_data = announce_handler - .announce(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) + .handle_announcement(&sample_info_hash(), &mut peer, &peer_ip(), &PeersWanted::AsManyAsPossible) .await .unwrap(); @@ -568,7 +568,7 @@ mod tests { // We have to announce with "started" event because peer does not count if peer was not previously known let mut started_peer = started_peer(); announce_handler - .announce( + .handle_announcement( &sample_info_hash(), &mut started_peer, &peer_ip(), @@ -579,7 +579,7 @@ mod tests { let mut completed_peer = completed_peer(); let announce_data = announce_handler - .announce( + .handle_announcement( &sample_info_hash(), &mut completed_peer, &peer_ip(), diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index dacf41383..5167abf51 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -203,7 +203,7 @@ mod tests { // Announce a "complete" peer for the torrent let mut complete_peer = complete_peer(); announce_handler - .announce( + .handle_announcement( &info_hash, &mut complete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 10)), @@ -215,7 +215,7 @@ mod tests { // Announce an "incomplete" peer for the torrent let mut incomplete_peer = incomplete_peer(); announce_handler - .announce( + .handle_announcement( &info_hash, &mut incomplete_peer, &IpAddr::V4(Ipv4Addr::new(126, 0, 0, 11)), @@ -225,7 +225,7 @@ mod tests { .unwrap(); // Scrape - let scrape_data = scrape_handler.scrape(&vec![info_hash]).await.unwrap(); + let scrape_data = scrape_handler.handle_scrape(&vec![info_hash]).await.unwrap(); // The expected swarm metadata for the torrent let mut expected_scrape_data = ScrapeData::empty(); @@ -259,7 +259,7 @@ mod tests { let non_whitelisted_info_hash = "3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap(); // DevSkim: ignore DS173237 - let scrape_data = scrape_handler.scrape(&vec![non_whitelisted_info_hash]).await.unwrap(); + let scrape_data = scrape_handler.handle_scrape(&vec![non_whitelisted_info_hash]).await.unwrap(); // The expected zeroed swarm metadata for the file let mut expected_scrape_data = ScrapeData::empty(); diff --git a/packages/tracker-core/src/scrape_handler.rs b/packages/tracker-core/src/scrape_handler.rs index 443d989a6..9c94a4e50 100644 --- a/packages/tracker-core/src/scrape_handler.rs +++ b/packages/tracker-core/src/scrape_handler.rs @@ -107,7 +107,7 @@ impl ScrapeHandler { /// # BEP Reference: /// /// [BEP 48: Scrape Protocol](https://www.bittorrent.org/beps/bep_0048.html) - pub async fn scrape(&self, info_hashes: &Vec) -> Result { + pub async fn handle_scrape(&self, info_hashes: &Vec) -> Result { let mut scrape_data = ScrapeData::empty(); for info_hash in info_hashes { @@ -158,7 +158,7 @@ mod tests { let info_hashes = vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::().unwrap()]; // DevSkim: ignore DS173237 - let scrape_data = scrape_handler.scrape(&info_hashes).await.unwrap(); + let scrape_data = scrape_handler.handle_scrape(&info_hashes).await.unwrap(); let mut expected_scrape_data = ScrapeData::empty(); @@ -176,7 +176,7 @@ mod tests { "99c82bb73505a3c0b453f9fa0e881d6e5a32a0c1".parse::().unwrap(), // DevSkim: ignore DS173237 ]; - let scrape_data = scrape_handler.scrape(&info_hashes).await.unwrap(); + let scrape_data = scrape_handler.handle_scrape(&info_hashes).await.unwrap(); let mut expected_scrape_data = ScrapeData::empty(); expected_scrape_data.add_file_with_zeroed_metadata(&info_hashes[0]); diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index f463eee98..171d554a8 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -241,7 +241,7 @@ mod tests { peer.updated = DurationSinceUnixEpoch::new(0, 0); let _number_of_downloads_increased = services .in_memory_torrent_repository - .upsert_peer(&infohash, &peer, None) + .handle_announcement(&infohash, &peer, None) .await; // Simulate the time has passed 1 second more than the max peer timeout. @@ -259,7 +259,7 @@ mod tests { // Add a peer to the torrent let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = in_memory_torrent_repository.upsert_peer(infohash, &peer, None).await; + let _number_of_downloads_increased = in_memory_torrent_repository.handle_announcement(infohash, &peer, None).await; // Remove the peer. The torrent is now peerless. in_memory_torrent_repository diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index bf8d083f8..bf63ef8d4 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -49,7 +49,7 @@ impl InMemoryTorrentRepository { /// /// This function panics if the underling swarms return an error. #[must_use] - pub async fn upsert_peer( + pub async fn handle_announcement( &self, info_hash: &InfoHash, peer: &peer::Peer, diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index 97694a80f..16db7b635 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -252,7 +252,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); let _number_of_downloads_increased = in_memory_torrent_repository - .upsert_peer(&info_hash, &sample_peer(), None) + .handle_announcement(&info_hash, &sample_peer(), None) .await; let torrent_info = get_torrent_info(&in_memory_torrent_repository, &info_hash).await.unwrap(); @@ -298,7 +298,7 @@ mod tests { let info_hash = InfoHash::from_str(&hash).unwrap(); let _number_of_downloads_increased = in_memory_torrent_repository - .upsert_peer(&info_hash, &sample_peer(), None) + .handle_announcement(&info_hash, &sample_peer(), None) .await; let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())).await; @@ -325,10 +325,10 @@ mod tests { let info_hash2 = InfoHash::from_str(&hash2).unwrap(); let _number_of_downloads_increased = in_memory_torrent_repository - .upsert_peer(&info_hash1, &sample_peer(), None) + .handle_announcement(&info_hash1, &sample_peer(), None) .await; let _number_of_downloads_increased = in_memory_torrent_repository - .upsert_peer(&info_hash2, &sample_peer(), None) + .handle_announcement(&info_hash2, &sample_peer(), None) .await; let offset = 0; @@ -350,10 +350,10 @@ mod tests { let info_hash2 = InfoHash::from_str(&hash2).unwrap(); let _number_of_downloads_increased = in_memory_torrent_repository - .upsert_peer(&info_hash1, &sample_peer(), None) + .handle_announcement(&info_hash1, &sample_peer(), None) .await; let _number_of_downloads_increased = in_memory_torrent_repository - .upsert_peer(&info_hash2, &sample_peer(), None) + .handle_announcement(&info_hash2, &sample_peer(), None) .await; let offset = 1; @@ -380,13 +380,13 @@ mod tests { let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash1 = InfoHash::from_str(&hash1).unwrap(); let _number_of_downloads_increased = in_memory_torrent_repository - .upsert_peer(&info_hash1, &sample_peer(), None) + .handle_announcement(&info_hash1, &sample_peer(), None) .await; let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); let _number_of_downloads_increased = in_memory_torrent_repository - .upsert_peer(&info_hash2, &sample_peer(), None) + .handle_announcement(&info_hash2, &sample_peer(), None) .await; let torrents = get_torrents_page(&in_memory_torrent_repository, Some(&Pagination::default())).await; @@ -436,7 +436,7 @@ mod tests { let info_hash = sample_info_hash(); let _ = in_memory_torrent_repository - .upsert_peer(&info_hash, &sample_peer(), None) + .handle_announcement(&info_hash, &sample_peer(), None) .await; let torrent_info = get_torrents(&in_memory_torrent_repository, &[info_hash]).await; diff --git a/packages/tracker-core/tests/common/test_env.rs b/packages/tracker-core/tests/common/test_env.rs index 8a443d8f0..d4462e3f6 100644 --- a/packages/tracker-core/tests/common/test_env.rs +++ b/packages/tracker-core/tests/common/test_env.rs @@ -77,7 +77,7 @@ impl TestEnv { let announce_data = self .tracker_core_container .announce_handler - .announce(info_hash, &mut peer, remote_client_ip, &PeersWanted::AsManyAsPossible) + .handle_announcement(info_hash, &mut peer, remote_client_ip, &PeersWanted::AsManyAsPossible) .await .unwrap(); @@ -98,7 +98,7 @@ impl TestEnv { let announce_data = self .tracker_core_container .announce_handler - .announce(info_hash, &mut peer, remote_client_ip, &PeersWanted::AsManyAsPossible) + .handle_announcement(info_hash, &mut peer, remote_client_ip, &PeersWanted::AsManyAsPossible) .await .unwrap(); @@ -111,7 +111,7 @@ impl TestEnv { pub async fn scrape(&self, info_hash: &InfoHash) -> ScrapeData { self.tracker_core_container .scrape_handler - .scrape(&vec![*info_hash]) + .handle_scrape(&vec![*info_hash]) .await .unwrap() } diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index 6ea237d84..a69e91d8a 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -78,7 +78,7 @@ impl AnnounceService { let announce_data = self .announce_handler - .announce(&info_hash, &mut peer, &remote_client_ip, &peers_wanted) + .handle_announcement(&info_hash, &mut peer, &remote_client_ip, &peers_wanted) .await?; self.send_event(info_hash, peer, client_socket_addr, server_service_binding) diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index b42004f63..8551351fb 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -56,7 +56,7 @@ impl ScrapeService { let scrape_data = self .scrape_handler - .scrape(&Self::convert_from_aquatic(&request.info_hashes)) + .handle_scrape(&Self::convert_from_aquatic(&request.info_hashes)) .await?; self.send_event(client_socket_addr, server_service_binding).await; diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index f92d5dd29..c4e0ce96f 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -39,7 +39,7 @@ where .container .tracker_core_container .in_memory_torrent_repository - .upsert_peer(info_hash, peer, None) + .handle_announcement(info_hash, peer, None) .await; } } diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 567f43740..edc36ebc8 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -370,7 +370,7 @@ mod tests { .into(); let _number_of_downloads_increased = in_memory_torrent_repository - .upsert_peer(&info_hash.0.into(), &peer_using_ipv6, None) + .handle_announcement(&info_hash.0.into(), &peer_using_ipv6, None) .await; } @@ -714,7 +714,7 @@ mod tests { .into(); let _number_of_downloads_increased = in_memory_torrent_repository - .upsert_peer(&info_hash.0.into(), &peer_using_ipv4, None) + .handle_announcement(&info_hash.0.into(), &peer_using_ipv4, None) .await; } diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index a9462e0f9..183d78b70 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -166,7 +166,7 @@ mod tests { .into(); let _number_of_downloads_increased = in_memory_torrent_repository - .upsert_peer(&info_hash.0.into(), &peer, None) + .handle_announcement(&info_hash.0.into(), &peer, None) .await; } From 67d177b6d4af24608d6be5a80ed10434242c4cd4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 26 May 2025 15:47:18 +0100 Subject: [PATCH 1130/1297] refactor: [#1524] command/query separation The returned value is not needed anymore. Secondary action (increase metrics) is done in the event listeners. --- .../src/environment.rs | 4 +- .../src/environment.rs | 4 +- packages/torrent-repository/src/swarm.rs | 157 +++++++----------- packages/torrent-repository/src/swarms.rs | 6 +- packages/tracker-core/src/announce_handler.rs | 3 +- packages/tracker-core/src/torrent/manager.rs | 4 +- .../src/torrent/repository/in_memory.rs | 5 +- packages/tracker-core/src/torrent/services.rs | 18 +- .../udp-tracker-server/src/environment.rs | 3 +- .../src/handlers/announce.rs | 4 +- .../udp-tracker-server/src/handlers/scrape.rs | 2 +- 11 files changed, 82 insertions(+), 128 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index 59605d781..0c1431db5 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -25,12 +25,12 @@ pub struct Environment { impl Environment { /// Add a torrent to the tracker - pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { self.container .tracker_core_container .in_memory_torrent_repository .handle_announcement(info_hash, peer, None) - .await + .await; } } diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index 3c7ff564d..be93a8723 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -33,12 +33,12 @@ where S: std::fmt::Debug + std::fmt::Display, { /// Add a torrent to the tracker - pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) -> bool { + pub async fn add_torrent_peer(&self, info_hash: &InfoHash, peer: &peer::Peer) { self.container .tracker_core_container .in_memory_torrent_repository .handle_announcement(info_hash, peer, None) - .await + .await; } } diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index b9076289b..84e1f2da4 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -33,17 +33,13 @@ impl Swarm { } } - pub async fn handle_announcement(&mut self, incoming_announce: &PeerAnnouncement) -> bool { - let mut downloads_increased: bool = false; - + pub async fn handle_announcement(&mut self, incoming_announce: &PeerAnnouncement) { let _previous_peer = match peer::ReadInfo::get_event(incoming_announce) { AnnounceEvent::Started | AnnounceEvent::None | AnnounceEvent::Completed => { - self.upsert_peer(Arc::new(*incoming_announce), &mut downloads_increased).await + self.upsert_peer(Arc::new(*incoming_announce)).await } AnnounceEvent::Stopped => self.remove_peer(&incoming_announce.peer_addr).await, }; - - downloads_increased } pub async fn remove_inactive(&mut self, current_cutoff: DurationSinceUnixEpoch) -> usize { @@ -159,26 +155,20 @@ impl Swarm { !self.should_be_removed(policy) } - async fn upsert_peer( - &mut self, - incoming_announce: Arc, - downloads_increased: &mut bool, - ) -> Option> { + async fn upsert_peer(&mut self, incoming_announce: Arc) -> Option> { let announcement = incoming_announce.clone(); if let Some(previous_announce) = self.peers.insert(incoming_announce.peer_addr, incoming_announce) { - *downloads_increased = self.update_metadata_on_update(&previous_announce, &announcement); + let downloads_increased = self.update_metadata_on_update(&previous_announce, &announcement); self.trigger_peer_updated_event(&previous_announce, &announcement).await; - if *downloads_increased { + if downloads_increased { self.trigger_peer_download_completed_event(&announcement).await; } Some(previous_announce) } else { - *downloads_increased = false; - self.update_metadata_on_insert(&announcement); self.trigger_peer_added_event(&announcement).await; @@ -362,36 +352,30 @@ mod tests { #[tokio::test] async fn it_should_allow_inserting_a_new_peer() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - assert_eq!(swarm.upsert_peer(peer.into(), &mut downloads_increased).await, None); + assert_eq!(swarm.upsert_peer(peer.into()).await, None); } #[tokio::test] async fn it_should_allow_updating_a_preexisting_peer() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; - assert_eq!( - swarm.upsert_peer(peer.into(), &mut downloads_increased).await, - Some(Arc::new(peer)) - ); + assert_eq!(swarm.upsert_peer(peer.into()).await, Some(Arc::new(peer))); } #[tokio::test] async fn it_should_allow_getting_all_peers() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; assert_eq!(swarm.peers(None), [Arc::new(peer)]); } @@ -399,11 +383,10 @@ mod tests { #[tokio::test] async fn it_should_allow_getting_one_peer_by_id() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; assert_eq!(swarm.get(&peer.peer_addr), Some(Arc::new(peer)).as_ref()); } @@ -411,11 +394,10 @@ mod tests { #[tokio::test] async fn it_should_increase_the_number_of_peers_after_inserting_a_new_one() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; assert_eq!(swarm.len(), 1); } @@ -423,11 +405,10 @@ mod tests { #[tokio::test] async fn it_should_decrease_the_number_of_peers_after_removing_one() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; swarm.remove_peer(&peer.peer_addr).await; @@ -437,11 +418,10 @@ mod tests { #[tokio::test] async fn it_should_allow_removing_an_existing_peer() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let peer = PeerBuilder::default().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; let old = swarm.remove_peer(&peer.peer_addr).await; @@ -461,19 +441,18 @@ mod tests { #[tokio::test] async fn it_should_allow_getting_all_peers_excluding_peers_with_a_given_address() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let peer1 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.upsert_peer(peer1.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer1.into()).await; let peer2 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) .build(); - swarm.upsert_peer(peer2.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer2.into()).await; assert_eq!(swarm.peers_excluding(&peer2.peer_addr, None), [Arc::new(peer1)]); } @@ -481,13 +460,13 @@ mod tests { #[tokio::test] async fn it_should_count_inactive_peers() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; + let one_second = DurationSinceUnixEpoch::new(1, 0); // Insert the peer let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; let inactive_peers_total = swarm.count_inactive_peers(last_update_time + one_second); @@ -497,13 +476,13 @@ mod tests { #[tokio::test] async fn it_should_remove_inactive_peers() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; + let one_second = DurationSinceUnixEpoch::new(1, 0); // Insert the peer let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; // Remove peers not updated since one second after inserting the peer swarm.remove_inactive(last_update_time + one_second).await; @@ -514,13 +493,13 @@ mod tests { #[tokio::test] async fn it_should_not_remove_active_peers() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; + let one_second = DurationSinceUnixEpoch::new(1, 0); // Insert the peer let last_update_time = DurationSinceUnixEpoch::new(1_669_397_478_934, 0); let peer = PeerBuilder::default().last_updated_on(last_update_time).build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; // Remove peers not updated since one second before inserting the peer. swarm.remove_inactive(last_update_time - one_second).await; @@ -542,7 +521,7 @@ mod tests { async fn not_empty_swarm() -> Swarm { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - swarm.upsert_peer(PeerBuilder::default().build().into(), &mut false).await; + swarm.upsert_peer(PeerBuilder::default().build().into()).await; swarm } @@ -550,13 +529,12 @@ mod tests { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); let mut peer = PeerBuilder::leecher().build(); - let mut downloads_increased = false; - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; assert!(swarm.metadata().downloads() > 0); @@ -631,17 +609,16 @@ mod tests { #[tokio::test] async fn it_should_allow_inserting_two_identical_peers_except_for_the_socket_address() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let peer1 = PeerBuilder::default() .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.upsert_peer(peer1.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer1.into()).await; let peer2 = PeerBuilder::default() .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)), 6969)) .build(); - swarm.upsert_peer(peer2.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer2.into()).await; assert_eq!(swarm.len(), 2); } @@ -649,7 +626,6 @@ mod tests { #[tokio::test] async fn it_should_not_allow_inserting_two_peers_with_different_peer_id_but_the_same_socket_address() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; // When that happens the peer ID will be changed in the swarm. // In practice, it's like if the peer had changed its ID. @@ -658,13 +634,13 @@ mod tests { .with_peer_id(&PeerId(*b"-qB00000000000000001")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.upsert_peer(peer1.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer1.into()).await; let peer2 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000002")) .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) .build(); - swarm.upsert_peer(peer2.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer2.into()).await; assert_eq!(swarm.len(), 1); } @@ -672,13 +648,12 @@ mod tests { #[tokio::test] async fn it_should_return_the_swarm_metadata() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; - swarm.upsert_peer(leecher.into(), &mut downloads_increased).await; + swarm.upsert_peer(seeder.into()).await; + swarm.upsert_peer(leecher.into()).await; assert_eq!( swarm.metadata(), @@ -693,13 +668,12 @@ mod tests { #[tokio::test] async fn it_should_return_the_number_of_seeders_in_the_list() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; - swarm.upsert_peer(leecher.into(), &mut downloads_increased).await; + swarm.upsert_peer(seeder.into()).await; + swarm.upsert_peer(leecher.into()).await; let (seeders, _leechers) = swarm.seeders_and_leechers(); @@ -709,13 +683,12 @@ mod tests { #[tokio::test] async fn it_should_return_the_number_of_leechers_in_the_list() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; - swarm.upsert_peer(leecher.into(), &mut downloads_increased).await; + swarm.upsert_peer(seeder.into()).await; + swarm.upsert_peer(leecher.into()).await; let (_seeders, leechers) = swarm.seeders_and_leechers(); @@ -739,13 +712,12 @@ mod tests { #[tokio::test] async fn it_should_increase_the_number_of_leechers_if_the_new_peer_is_a_leecher_() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let leechers = swarm.metadata().leechers(); let leecher = PeerBuilder::leecher().build(); - swarm.upsert_peer(leecher.into(), &mut downloads_increased).await; + swarm.upsert_peer(leecher.into()).await; assert_eq!(swarm.metadata().leechers(), leechers + 1); } @@ -753,13 +725,12 @@ mod tests { #[tokio::test] async fn it_should_increase_the_number_of_seeders_if_the_new_peer_is_a_seeder() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let seeders = swarm.metadata().seeders(); let seeder = PeerBuilder::seeder().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; + swarm.upsert_peer(seeder.into()).await; assert_eq!(swarm.metadata().seeders(), seeders + 1); } @@ -768,13 +739,12 @@ mod tests { async fn it_should_not_increasing_the_number_of_downloads_if_the_new_peer_has_completed_downloading_as_it_was_not_previously_known( ) { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let downloads = swarm.metadata().downloads(); let seeder = PeerBuilder::seeder().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; + swarm.upsert_peer(seeder.into()).await; assert_eq!(swarm.metadata().downloads(), downloads); } @@ -789,11 +759,10 @@ mod tests { #[tokio::test] async fn it_should_decrease_the_number_of_leechers_if_the_removed_peer_was_a_leecher() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let leecher = PeerBuilder::leecher().build(); - swarm.upsert_peer(leecher.into(), &mut downloads_increased).await; + swarm.upsert_peer(leecher.into()).await; let leechers = swarm.metadata().leechers(); @@ -805,11 +774,10 @@ mod tests { #[tokio::test] async fn it_should_decrease_the_number_of_seeders_if_the_removed_peer_was_a_seeder() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; + swarm.upsert_peer(seeder.into()).await; let seeders = swarm.metadata().seeders(); @@ -830,11 +798,10 @@ mod tests { #[tokio::test] async fn it_should_decrease_the_number_of_leechers_when_a_removed_peer_is_a_leecher() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let leecher = PeerBuilder::leecher().build(); - swarm.upsert_peer(leecher.into(), &mut downloads_increased).await; + swarm.upsert_peer(leecher.into()).await; let leechers = swarm.metadata().leechers(); @@ -846,11 +813,10 @@ mod tests { #[tokio::test] async fn it_should_decrease_the_number_of_seeders_when_the_removed_peer_is_a_seeder() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let seeder = PeerBuilder::seeder().build(); - swarm.upsert_peer(seeder.into(), &mut downloads_increased).await; + swarm.upsert_peer(seeder.into()).await; let seeders = swarm.metadata().seeders(); @@ -870,18 +836,17 @@ mod tests { #[tokio::test] async fn it_should_increase_seeders_and_decreasing_leechers_when_the_peer_changes_from_leecher_to_seeder_() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let mut peer = PeerBuilder::leecher().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; let leechers = swarm.metadata().leechers(); let seeders = swarm.metadata().seeders(); peer.left = NumberOfBytes::new(0); // Convert to seeder - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; assert_eq!(swarm.metadata().seeders(), seeders + 1); assert_eq!(swarm.metadata().leechers(), leechers - 1); @@ -890,18 +855,17 @@ mod tests { #[tokio::test] async fn it_should_increase_leechers_and_decreasing_seeders_when_the_peer_changes_from_seeder_to_leecher() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let mut peer = PeerBuilder::seeder().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; let leechers = swarm.metadata().leechers(); let seeders = swarm.metadata().seeders(); peer.left = NumberOfBytes::new(10); // Convert to leecher - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; assert_eq!(swarm.metadata().leechers(), leechers + 1); assert_eq!(swarm.metadata().seeders(), seeders - 1); @@ -910,17 +874,16 @@ mod tests { #[tokio::test] async fn it_should_increase_the_number_of_downloads_when_the_peer_announces_completed_downloading() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let mut peer = PeerBuilder::leecher().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; let downloads = swarm.metadata().downloads(); peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; assert_eq!(swarm.metadata().downloads(), downloads + 1); } @@ -928,19 +891,18 @@ mod tests { #[tokio::test] async fn it_should_not_increasing_the_number_of_downloads_when_the_peer_announces_completed_downloading_twice_() { let mut swarm = Swarm::new(&sample_info_hash(), 0, None); - let mut downloads_increased = false; let mut peer = PeerBuilder::leecher().build(); - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; let downloads = swarm.metadata().downloads(); peer.event = aquatic_udp_protocol::AnnounceEvent::Completed; - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; assert_eq!(swarm.metadata().downloads(), downloads + 1); } @@ -971,8 +933,7 @@ mod tests { let mut swarm = Swarm::new(&sample_info_hash(), 0, Some(Arc::new(event_sender_mock))); - let mut downloads_increased = false; - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; } #[tokio::test] @@ -990,8 +951,7 @@ mod tests { let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); // Insert the peer - let mut downloads_increased = false; - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; swarm.remove_peer(&peer.peer_addr).await; } @@ -1011,8 +971,7 @@ mod tests { let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); // Insert the peer - let mut downloads_increased = false; - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; // Peers not updated after this time will be removed let current_cutoff = peer.updated + DurationSinceUnixEpoch::from_secs(1); @@ -1042,11 +1001,10 @@ mod tests { let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); // Insert the peer - let mut downloads_increased = false; - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; // Update the peer - swarm.upsert_peer(peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(peer.into()).await; } #[tokio::test] @@ -1079,11 +1037,10 @@ mod tests { let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); // Insert the peer - let mut downloads_increased = false; - swarm.upsert_peer(started_peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(started_peer.into()).await; // Announce as completed - swarm.upsert_peer(completed_peer.into(), &mut downloads_increased).await; + swarm.upsert_peer(completed_peer.into()).await; } } } diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 36f83070d..1504ac1f4 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -54,7 +54,7 @@ impl Swarms { info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option, - ) -> Result { + ) -> Result<(), Error> { let swarm_handle = match self.swarms.get(info_hash) { None => { let number_of_downloads = opt_persistent_torrent.unwrap_or_default(); @@ -80,9 +80,9 @@ impl Swarms { let mut swarm = swarm_handle.value().lock().await; - let downloads_increased = swarm.handle_announcement(peer).await; + swarm.handle_announcement(peer).await; - Ok(downloads_increased) + Ok(()) } /// Inserts a new swarm. Only used for testing purposes. diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 7d37ec9ed..ffd244f2a 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -176,8 +176,7 @@ impl AnnounceHandler { peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); - let _number_of_downloads_increased = self - .in_memory_torrent_repository + self.in_memory_torrent_repository .handle_announcement(info_hash, peer, opt_persistent_torrent) .await; diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index 171d554a8..d9997c4ad 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -239,7 +239,7 @@ mod tests { // Add a peer to the torrent let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = services + services .in_memory_torrent_repository .handle_announcement(&infohash, &peer, None) .await; @@ -259,7 +259,7 @@ mod tests { // Add a peer to the torrent let mut peer = sample_peer(); peer.updated = DurationSinceUnixEpoch::new(0, 0); - let _number_of_downloads_increased = in_memory_torrent_repository.handle_announcement(infohash, &peer, None).await; + in_memory_torrent_repository.handle_announcement(infohash, &peer, None).await; // Remove the peer. The torrent is now peerless. in_memory_torrent_repository diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index bf63ef8d4..5c8a335b6 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -48,17 +48,16 @@ impl InMemoryTorrentRepository { /// # Panics /// /// This function panics if the underling swarms return an error. - #[must_use] pub async fn handle_announcement( &self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option, - ) -> bool { + ) { self.swarms .handle_announcement(info_hash, peer, opt_persistent_torrent) .await - .expect("Failed to upsert the peer in swarms") + .expect("Failed to upsert the peer in swarms"); } /// Removes inactive peers from all torrent entries. diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index 16db7b635..2ae51fc78 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -251,7 +251,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository + in_memory_torrent_repository .handle_announcement(&info_hash, &sample_peer(), None) .await; @@ -297,7 +297,7 @@ mod tests { let hash = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash = InfoHash::from_str(&hash).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository + in_memory_torrent_repository .handle_announcement(&info_hash, &sample_peer(), None) .await; @@ -324,10 +324,10 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository + in_memory_torrent_repository .handle_announcement(&info_hash1, &sample_peer(), None) .await; - let _number_of_downloads_increased = in_memory_torrent_repository + in_memory_torrent_repository .handle_announcement(&info_hash2, &sample_peer(), None) .await; @@ -349,10 +349,10 @@ mod tests { let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository + in_memory_torrent_repository .handle_announcement(&info_hash1, &sample_peer(), None) .await; - let _number_of_downloads_increased = in_memory_torrent_repository + in_memory_torrent_repository .handle_announcement(&info_hash2, &sample_peer(), None) .await; @@ -379,13 +379,13 @@ mod tests { let hash1 = "9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d".to_owned(); // DevSkim: ignore DS173237 let info_hash1 = InfoHash::from_str(&hash1).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository + in_memory_torrent_repository .handle_announcement(&info_hash1, &sample_peer(), None) .await; let hash2 = "03840548643af2a7b63a9f5cbca348bc7150ca3a".to_owned(); // DevSkim: ignore DS173237 let info_hash2 = InfoHash::from_str(&hash2).unwrap(); - let _number_of_downloads_increased = in_memory_torrent_repository + in_memory_torrent_repository .handle_announcement(&info_hash2, &sample_peer(), None) .await; @@ -435,7 +435,7 @@ mod tests { let info_hash = sample_info_hash(); - let _ = in_memory_torrent_repository + in_memory_torrent_repository .handle_announcement(&info_hash, &sample_peer(), None) .await; diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index c4e0ce96f..94a166e4e 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -35,8 +35,7 @@ where /// Add a torrent to the tracker #[allow(dead_code)] pub async fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { - let _number_of_downloads_increased = self - .container + self.container .tracker_core_container .in_memory_torrent_repository .handle_announcement(info_hash, peer, None) diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index edc36ebc8..e2ca6821e 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -369,7 +369,7 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V6(client_ip_v6), client_port)) .into(); - let _number_of_downloads_increased = in_memory_torrent_repository + in_memory_torrent_repository .handle_announcement(&info_hash.0.into(), &peer_using_ipv6, None) .await; } @@ -713,7 +713,7 @@ mod tests { .with_peer_address(SocketAddr::new(IpAddr::V4(client_ip_v4), client_port)) .into(); - let _number_of_downloads_increased = in_memory_torrent_repository + in_memory_torrent_repository .handle_announcement(&info_hash.0.into(), &peer_using_ipv4, None) .await; } diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 183d78b70..8bac05c1e 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -165,7 +165,7 @@ mod tests { .with_bytes_left_to_download(0) .into(); - let _number_of_downloads_increased = in_memory_torrent_repository + in_memory_torrent_repository .handle_announcement(&info_hash.0.into(), &peer, None) .await; } From 21752709a3703f9e791510ccea97bbcbd495bb1d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 26 May 2025 18:39:20 +0100 Subject: [PATCH 1131/1297] feat: [#1535] scaffolding for tracker-core metrics New metric added: ``` tracker_core_persistent_torrents_downloads_total{} 1 ``` However, it's not persisted yet. TODO: - Persist into the database when updated. - Load from database when the tracker starts. --- Cargo.lock | 1 + .../src/v1/context/stats/handlers.rs | 2 + .../src/v1/context/stats/routes.rs | 2 + .../src/statistics/services.rs | 5 + .../src/http/client/requests/announce.rs | 8 +- packages/tracker-core/Cargo.toml | 1 + packages/tracker-core/src/container.rs | 6 +- .../src/statistics/event/handler.rs | 21 ++- .../src/statistics/event/listener.rs | 13 +- .../tracker-core/src/statistics/metrics.rs | 63 +++++++++ packages/tracker-core/src/statistics/mod.rs | 26 ++++ .../tracker-core/src/statistics/repository.rs | 132 ++++++++++++++++++ .../tracker-core/tests/common/test_env.rs | 1 + .../config/tracker.development.sqlite3.toml | 4 +- src/bootstrap/jobs/tracker_core.rs | 5 +- 15 files changed, 276 insertions(+), 14 deletions(-) create mode 100644 packages/tracker-core/src/statistics/metrics.rs create mode 100644 packages/tracker-core/src/statistics/repository.rs diff --git a/Cargo.lock b/Cargo.lock index 5415149e8..96de11cb2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -678,6 +678,7 @@ dependencies = [ "torrust-tracker-configuration", "torrust-tracker-events", "torrust-tracker-located-error", + "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", "torrust-tracker-torrent-repository", diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs index 552958d74..3a353f1fc 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs @@ -70,6 +70,7 @@ pub async fn get_metrics_handler( Arc, Arc>, Arc, + Arc, Arc, Arc, Arc, @@ -83,6 +84,7 @@ pub async fn get_metrics_handler( state.3.clone(), state.4.clone(), state.5.clone(), + state.6.clone(), ) .await; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs index 3eeaa8bf4..f6c661130 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs @@ -28,7 +28,9 @@ pub fn add(prefix: &str, router: Router, http_api_container: &Arc, ban_service: Arc>, swarms_stats_repository: Arc, + tracker_core_stats_repository: Arc, http_stats_repository: Arc, udp_stats_repository: Arc, udp_server_stats_repository: Arc, @@ -102,6 +103,7 @@ pub async fn get_labeled_metrics( let _udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); let swarms_stats = swarms_stats_repository.get_metrics().await; + let tracker_core_stats = tracker_core_stats_repository.get_metrics().await; let http_stats = http_stats_repository.get_stats().await; let udp_stats_repository = udp_stats_repository.get_stats().await; let udp_server_stats = udp_server_stats_repository.get_stats().await; @@ -112,6 +114,9 @@ pub async fn get_labeled_metrics( metrics .merge(&swarms_stats.metric_collection) .expect("msg: failed to merge torrent repository metrics"); + metrics + .merge(&tracker_core_stats.metric_collection) + .expect("msg: failed to merge tracker core metrics"); metrics .merge(&http_stats.metric_collection) .expect("msg: failed to merge HTTP core metrics"); diff --git a/packages/tracker-client/src/http/client/requests/announce.rs b/packages/tracker-client/src/http/client/requests/announce.rs index 7d20fbba8..29b5d1221 100644 --- a/packages/tracker-client/src/http/client/requests/announce.rs +++ b/packages/tracker-client/src/http/client/requests/announce.rs @@ -53,16 +53,16 @@ pub type BaseTenASCII = u64; pub type PortNumber = u16; pub enum Event { - //Started, - //Stopped, + Started, + Stopped, Completed, } impl fmt::Display for Event { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - //Event::Started => write!(f, "started"), - //Event::Stopped => write!(f, "stopped"), + Event::Started => write!(f, "started"), + Event::Stopped => write!(f, "stopped"), Event::Completed => write!(f, "completed"), } } diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index 3c89505b2..a2d08dfa0 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -31,6 +31,7 @@ torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } +torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } tracing = "0" diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs index f4fb272de..ed56fb106 100644 --- a/packages/tracker-core/src/container.rs +++ b/packages/tracker-core/src/container.rs @@ -14,11 +14,11 @@ use crate::scrape_handler::ScrapeHandler; use crate::torrent::manager::TorrentsManager; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; -use crate::whitelist; use crate::whitelist::authorization::WhitelistAuthorization; use crate::whitelist::manager::WhitelistManager; use crate::whitelist::repository::in_memory::InMemoryWhitelist; use crate::whitelist::setup::initialize_whitelist_manager; +use crate::{statistics, whitelist}; pub struct TrackerCoreContainer { pub core_config: Arc, @@ -33,6 +33,7 @@ pub struct TrackerCoreContainer { pub in_memory_torrent_repository: Arc, pub db_torrent_repository: Arc, pub torrents_manager: Arc, + pub stats_repository: Arc, } impl TrackerCoreContainer { @@ -58,6 +59,8 @@ impl TrackerCoreContainer { &db_torrent_repository, )); + let stats_repository = Arc::new(statistics::repository::Repository::new()); + let announce_handler = Arc::new(AnnounceHandler::new( core_config, &whitelist_authorization, @@ -80,6 +83,7 @@ impl TrackerCoreContainer { in_memory_torrent_repository, db_torrent_repository, torrents_manager, + stats_repository, } } } diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs index 7b6ce83b7..ac6d0639e 100644 --- a/packages/tracker-core/src/statistics/event/handler.rs +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -1,14 +1,19 @@ use std::sync::Arc; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_torrent_repository::event::Event; +use crate::statistics::repository::Repository; +use crate::statistics::TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL; use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; pub async fn handle_event( event: Event, + stats_repository: &Arc, db_torrent_repository: &Arc, - _now: DurationSinceUnixEpoch, + now: DurationSinceUnixEpoch, ) { match event { // Torrent events @@ -36,6 +41,7 @@ pub async fn handle_event( Event::PeerDownloadCompleted { info_hash, peer } => { tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer download completed", ); + // Increment the number of downloads for the torrent match db_torrent_repository.increase_number_of_downloads(&info_hash) { Ok(()) => { tracing::debug!(info_hash = ?info_hash, "Number of downloads increased"); @@ -44,6 +50,19 @@ pub async fn handle_event( tracing::error!(info_hash = ?info_hash, error = ?err, "Failed to increase number of downloads"); } } + + // Increment the number of downloads for all the torrents + let _unused = stats_repository + .increment_counter( + &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), + &LabelSet::default(), + now, + ) + .await; + + // todo: + // - Persist the metric into the database. + // - Load the metric from the database. } } } diff --git a/packages/tracker-core/src/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs index e04675092..f85b2b7a0 100644 --- a/packages/tracker-core/src/statistics/event/listener.rs +++ b/packages/tracker-core/src/statistics/event/listener.rs @@ -6,26 +6,33 @@ use torrust_tracker_events::receiver::RecvError; use torrust_tracker_torrent_repository::event::receiver::Receiver; use super::handler::handle_event; +use crate::statistics::repository::Repository; use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; use crate::{CurrentClock, TRACKER_CORE_LOG_TARGET}; #[must_use] pub fn run_event_listener( receiver: Receiver, + repository: &Arc, db_torrent_repository: &Arc, ) -> JoinHandle<()> { + let stats_repository = repository.clone(); let db_torrent_repository: Arc = db_torrent_repository.clone(); tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Starting torrent repository event listener"); tokio::spawn(async move { - dispatch_events(receiver, db_torrent_repository).await; + dispatch_events(receiver, stats_repository, db_torrent_repository).await; tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Torrent repository listener finished"); }) } -async fn dispatch_events(mut receiver: Receiver, db_torrent_repository: Arc) { +async fn dispatch_events( + mut receiver: Receiver, + stats_repository: Arc, + db_torrent_repository: Arc, +) { let shutdown_signal = tokio::signal::ctrl_c(); tokio::pin!(shutdown_signal); @@ -41,7 +48,7 @@ async fn dispatch_events(mut receiver: Receiver, db_torrent_repository: Arc { match result { - Ok(event) => handle_event(event, &db_torrent_repository, CurrentClock::now()).await, + Ok(event) => handle_event(event, &stats_repository, &db_torrent_repository, CurrentClock::now()).await, Err(e) => { match e { RecvError::Closed => { diff --git a/packages/tracker-core/src/statistics/metrics.rs b/packages/tracker-core/src/statistics/metrics.rs new file mode 100644 index 000000000..f8ab3f9d9 --- /dev/null +++ b/packages/tracker-core/src/statistics/metrics.rs @@ -0,0 +1,63 @@ +use serde::Serialize; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +/// Metrics collected by the torrent repository. +#[derive(Debug, Clone, PartialEq, Default, Serialize)] +pub struct Metrics { + /// A collection of metrics. + pub metric_collection: MetricCollection, +} + +impl Metrics { + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increment_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increase_counter(metric_name, labels, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn set_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_gauge(metric_name, labels, value, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increment_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increment_gauge(metric_name, labels, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn decrement_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.decrement_gauge(metric_name, labels, now) + } +} diff --git a/packages/tracker-core/src/statistics/mod.rs b/packages/tracker-core/src/statistics/mod.rs index 53f112654..1cd9aac6b 100644 --- a/packages/tracker-core/src/statistics/mod.rs +++ b/packages/tracker-core/src/statistics/mod.rs @@ -1 +1,27 @@ pub mod event; +pub mod metrics; +pub mod repository; + +use metrics::Metrics; +use torrust_tracker_metrics::metric::description::MetricDescription; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_metrics::unit::Unit; + +// Torrent metrics + +const TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL: &str = "tracker_core_persistent_torrents_downloads_total"; + +#[must_use] +pub fn describe_metrics() -> Metrics { + let mut metrics = Metrics::default(); + + // Torrent metrics + + metrics.metric_collection.describe_counter( + &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new("The total number of torrent downloads (persisted).")), + ); + + metrics +} diff --git a/packages/tracker-core/src/statistics/repository.rs b/packages/tracker-core/src/statistics/repository.rs new file mode 100644 index 000000000..fe1292d00 --- /dev/null +++ b/packages/tracker-core/src/statistics/repository.rs @@ -0,0 +1,132 @@ +use std::sync::Arc; + +use tokio::sync::{RwLock, RwLockReadGuard}; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::Error; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::describe_metrics; +use super::metrics::Metrics; + +/// A repository for the torrent repository metrics. +#[derive(Clone)] +pub struct Repository { + pub stats: Arc>, +} + +impl Default for Repository { + fn default() -> Self { + Self::new() + } +} + +impl Repository { + #[must_use] + pub fn new() -> Self { + let stats = Arc::new(RwLock::new(describe_metrics())); + + Self { stats } + } + + pub async fn get_metrics(&self) -> RwLockReadGuard<'_, Metrics> { + self.stats.read().await + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increment the counter. + pub async fn increment_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.increment_counter(metric_name, labels, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to increment the counter: {}", err), + } + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// set the gauge. + pub async fn set_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.set_gauge(metric_name, labels, value, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to set the gauge: {}", err), + } + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increment the gauge. + pub async fn increment_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.increment_gauge(metric_name, labels, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to increment the gauge: {}", err), + } + + result + } + + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// decrement the gauge. + pub async fn decrement_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.decrement_gauge(metric_name, labels, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to decrement the gauge: {}", err), + } + + result + } +} diff --git a/packages/tracker-core/tests/common/test_env.rs b/packages/tracker-core/tests/common/test_env.rs index d4462e3f6..0be8bd4c6 100644 --- a/packages/tracker-core/tests/common/test_env.rs +++ b/packages/tracker-core/tests/common/test_env.rs @@ -56,6 +56,7 @@ impl TestEnv { let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( self.torrent_repository_container.event_bus.receiver(), + &self.tracker_core_container.stats_repository, &self.tracker_core_container.db_torrent_repository, ); diff --git a/share/default/config/tracker.development.sqlite3.toml b/share/default/config/tracker.development.sqlite3.toml index 89d700132..17a73a1d2 100644 --- a/share/default/config/tracker.development.sqlite3.toml +++ b/share/default/config/tracker.development.sqlite3.toml @@ -7,12 +7,12 @@ schema_version = "2.0.0" threshold = "info" [core] -inactive_peer_cleanup_interval = 60 +inactive_peer_cleanup_interval = 120 listed = false private = false [core.tracker_policy] -max_peer_timeout = 30 +max_peer_timeout = 60 persistent_torrent_completed_stat = true remove_peerless_torrents = true diff --git a/src/bootstrap/jobs/tracker_core.rs b/src/bootstrap/jobs/tracker_core.rs index bb879db6b..37c53b9e4 100644 --- a/src/bootstrap/jobs/tracker_core.rs +++ b/src/bootstrap/jobs/tracker_core.rs @@ -6,11 +6,10 @@ use torrust_tracker_configuration::Configuration; use crate::container::AppContainer; pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { - // todo: enable this when labeled metrics are implemented. - //if config.core.tracker_usage_statistics || config.core.tracker_policy.persistent_torrent_completed_stat { - if config.core.tracker_policy.persistent_torrent_completed_stat { + if config.core.tracker_usage_statistics || config.core.tracker_policy.persistent_torrent_completed_stat { let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( app_container.torrent_repository_container.event_bus.receiver(), + &app_container.tracker_core_container.stats_repository, &app_container.tracker_core_container.db_torrent_repository, ); From 6f11534d49742a8b6654fe9450b683c2bd49e9a9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 May 2025 10:37:27 +0100 Subject: [PATCH 1132/1297] feat: [#1539] add method to Database trait to persis global downloads counter It does not use the new methods in production yet. --- ...3000_torrust_tracker_create_all_tables.sql | 1 + ...er_new_torrent_aggregate_metrics_table.sql | 6 ++ ...3000_torrust_tracker_create_all_tables.sql | 1 + ...er_new_torrent_aggregate_metrics_table.sql | 6 ++ .../tracker-core/src/databases/driver/mod.rs | 44 ++++++++++++ .../src/databases/driver/mysql.rs | 57 +++++++++++++++- .../src/databases/driver/sqlite.rs | 68 ++++++++++++++++++- packages/tracker-core/src/databases/mod.rs | 34 +++++++++- 8 files changed, 214 insertions(+), 3 deletions(-) create mode 100644 packages/tracker-core/migrations/mysql/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql create mode 100644 packages/tracker-core/migrations/sqlite/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql diff --git a/packages/tracker-core/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql b/packages/tracker-core/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql index 407ae4dd1..ab160bd75 100644 --- a/packages/tracker-core/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql +++ b/packages/tracker-core/migrations/mysql/20240730183000_torrust_tracker_create_all_tables.sql @@ -4,6 +4,7 @@ CREATE TABLE info_hash VARCHAR(40) NOT NULL UNIQUE ); +# todo: rename to `torrent_metrics` CREATE TABLE IF NOT EXISTS torrents ( id integer PRIMARY KEY AUTO_INCREMENT, diff --git a/packages/tracker-core/migrations/mysql/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql b/packages/tracker-core/migrations/mysql/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql new file mode 100644 index 000000000..36f940cc3 --- /dev/null +++ b/packages/tracker-core/migrations/mysql/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql @@ -0,0 +1,6 @@ +CREATE TABLE + IF NOT EXISTS torrent_aggregate_metrics ( + id integer PRIMARY KEY AUTO_INCREMENT, + metric_name VARCHAR(50) NOT NULL UNIQUE, + value INTEGER DEFAULT 0 NOT NULL + ); \ No newline at end of file diff --git a/packages/tracker-core/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql b/packages/tracker-core/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql index bd451bf8b..c5bcad926 100644 --- a/packages/tracker-core/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql +++ b/packages/tracker-core/migrations/sqlite/20240730183000_torrust_tracker_create_all_tables.sql @@ -4,6 +4,7 @@ CREATE TABLE info_hash TEXT NOT NULL UNIQUE ); +# todo: rename to `torrent_metrics` CREATE TABLE IF NOT EXISTS torrents ( id INTEGER PRIMARY KEY AUTOINCREMENT, diff --git a/packages/tracker-core/migrations/sqlite/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql b/packages/tracker-core/migrations/sqlite/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql new file mode 100644 index 000000000..34166903c --- /dev/null +++ b/packages/tracker-core/migrations/sqlite/20250527093000_torrust_tracker_new_torrent_aggregate_metrics_table.sql @@ -0,0 +1,6 @@ +CREATE TABLE + IF NOT EXISTS torrent_aggregate_metrics ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + metric_name TEXT NOT NULL UNIQUE, + value INTEGER DEFAULT 0 NOT NULL + ); \ No newline at end of file diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index 2cedab2d7..e8f0ecbfb 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -6,6 +6,9 @@ use sqlite::Sqlite; use super::error::Error; use super::Database; +/// Metric name in DB for the total number of downloads across all torrents. +const TORRENTS_DOWNLOADS_TOTAL: &str = "torrents_downloads_total"; + /// The database management system used by the tracker. /// /// Refer to: @@ -97,9 +100,14 @@ pub(crate) mod tests { // Persistent torrents (stats) + // Torrent metrics handling_torrent_persistence::it_should_save_and_load_persistent_torrents(driver); handling_torrent_persistence::it_should_load_all_persistent_torrents(driver); handling_torrent_persistence::it_should_increase_the_number_of_downloads_for_a_given_torrent(driver); + // Aggregate metrics for all torrents + handling_torrent_persistence::it_should_save_and_load_the_global_number_of_downloads(driver); + handling_torrent_persistence::it_should_load_the_global_number_of_downloads(driver); + handling_torrent_persistence::it_should_increase_the_global_number_of_downloads(driver); // Authentication keys (for private trackers) @@ -154,6 +162,8 @@ pub(crate) mod tests { use crate::databases::Database; use crate::test_helpers::tests::sample_info_hash; + // Metrics per torrent + pub fn it_should_save_and_load_persistent_torrents(driver: &Arc>) { let infohash = sample_info_hash(); @@ -192,6 +202,40 @@ pub(crate) mod tests { assert_eq!(number_of_downloads, 2); } + + // Aggregate metrics for all torrents + + pub fn it_should_save_and_load_the_global_number_of_downloads(driver: &Arc>) { + let number_of_downloads = 1; + + driver.save_global_number_of_downloads(number_of_downloads).unwrap(); + + let number_of_downloads = driver.load_global_number_of_downloads().unwrap().unwrap(); + + assert_eq!(number_of_downloads, 1); + } + + pub fn it_should_load_the_global_number_of_downloads(driver: &Arc>) { + let number_of_downloads = 1; + + driver.save_global_number_of_downloads(number_of_downloads).unwrap(); + + let number_of_downloads = driver.load_global_number_of_downloads().unwrap().unwrap(); + + assert_eq!(number_of_downloads, 1); + } + + pub fn it_should_increase_the_global_number_of_downloads(driver: &Arc>) { + let number_of_downloads = 1; + + driver.save_global_number_of_downloads(number_of_downloads).unwrap(); + + driver.increase_global_number_of_downloads().unwrap(); + + let number_of_downloads = driver.load_global_number_of_downloads().unwrap().unwrap(); + + assert_eq!(number_of_downloads, 2); + } } mod handling_authentication_keys { diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index d07f061c2..bfbc47ebd 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -15,7 +15,7 @@ use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MySqlConnectionManager; use torrust_tracker_primitives::{PersistentTorrent, PersistentTorrents}; -use super::{Database, Driver, Error}; +use super::{Database, Driver, Error, TORRENTS_DOWNLOADS_TOTAL}; use crate::authentication::key::AUTH_KEY_LENGTH; use crate::authentication::{self, Key}; @@ -46,6 +46,27 @@ impl Mysql { Ok(Self { pool }) } + + fn load_torrent_aggregate_metric(&self, metric_name: &str) -> Result, Error> { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let query = conn.exec_first::( + "SELECT value FROM torrent_aggregate_metrics WHERE metric_name = :metric_name", + params! { "metric_name" => metric_name }, + ); + + let persistent_torrent = query?; + + Ok(persistent_torrent) + } + + fn save_torrent_aggregate_metric(&self, metric_name: &str, completed: PersistentTorrent) -> Result<(), Error> { + const COMMAND : &str = "INSERT INTO torrent_aggregate_metrics (metric_name, value) VALUES (:metric_name, :completed) ON DUPLICATE KEY UPDATE value = VALUES(value)"; + + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + Ok(conn.exec_drop(COMMAND, params! { metric_name, completed })?) + } } impl Database for Mysql { @@ -66,6 +87,14 @@ impl Database for Mysql { );" .to_string(); + let create_torrent_aggregate_metrics_table = " + CREATE TABLE IF NOT EXISTS torrent_aggregate_metrics ( + id integer PRIMARY KEY AUTO_INCREMENT, + metric_name VARCHAR(50) NOT NULL UNIQUE, + value INTEGER DEFAULT 0 NOT NULL + );" + .to_string(); + let create_keys_table = format!( " CREATE TABLE IF NOT EXISTS `keys` ( @@ -82,6 +111,8 @@ impl Database for Mysql { conn.query_drop(&create_torrents_table) .expect("Could not create torrents table."); + conn.query_drop(&create_torrent_aggregate_metrics_table) + .expect("Could not create create_torrent_aggregate_metrics_table table."); conn.query_drop(&create_keys_table).expect("Could not create keys table."); conn.query_drop(&create_whitelist_table) .expect("Could not create whitelist table."); @@ -168,6 +199,30 @@ impl Database for Mysql { Ok(()) } + /// Refer to [`databases::Database::load_global_number_of_downloads`](crate::core::databases::Database::load_global_number_of_downloads). + fn load_global_number_of_downloads(&self) -> Result, Error> { + self.load_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL) + } + + /// Refer to [`databases::Database::save_global_number_of_downloads`](crate::core::databases::Database::save_global_number_of_downloads). + fn save_global_number_of_downloads(&self, downloaded: PersistentTorrent) -> Result<(), Error> { + self.save_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL, downloaded) + } + + /// Refer to [`databases::Database::increase_global_number_of_downloads`](crate::core::databases::Database::increase_global_number_of_downloads). + fn increase_global_number_of_downloads(&self) -> Result<(), Error> { + let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let metric_name = TORRENTS_DOWNLOADS_TOTAL; + + conn.exec_drop( + "UPDATE torrent_aggregate_metrics SET value = value + 1 WHERE metric_name = :metric_name", + params! { metric_name }, + )?; + + Ok(()) + } + /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). fn load_keys(&self) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs index d36f24f8b..91e969233 100644 --- a/packages/tracker-core/src/databases/driver/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -15,7 +15,7 @@ use r2d2_sqlite::rusqlite::types::Null; use r2d2_sqlite::SqliteConnectionManager; use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; -use super::{Database, Driver, Error}; +use super::{Database, Driver, Error, TORRENTS_DOWNLOADS_TOTAL}; use crate::authentication::{self, Key}; const DRIVER: Driver = Driver::Sqlite3; @@ -49,6 +49,39 @@ impl Sqlite { Ok(Self { pool }) } + + fn load_torrent_aggregate_metric(&self, metric_name: &str) -> Result, Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let mut stmt = conn.prepare("SELECT value FROM torrent_aggregate_metrics WHERE metric_name = ?")?; + + let mut rows = stmt.query([metric_name])?; + + let persistent_torrent = rows.next()?; + + Ok(persistent_torrent.map(|f| { + let value: i64 = f.get(0).unwrap(); + u32::try_from(value).unwrap() + })) + } + + fn save_torrent_aggregate_metric(&self, metric_name: &str, completed: PersistentTorrent) -> Result<(), Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let insert = conn.execute( + "INSERT INTO torrent_aggregate_metrics (metric_name, value) VALUES (?1, ?2) ON CONFLICT(metric_name) DO UPDATE SET value = ?2", + [metric_name.to_string(), completed.to_string()], + )?; + + if insert == 0 { + Err(Error::InsertFailed { + location: Location::caller(), + driver: DRIVER, + }) + } else { + Ok(()) + } + } } impl Database for Sqlite { @@ -69,6 +102,14 @@ impl Database for Sqlite { );" .to_string(); + let create_torrent_aggregate_metrics_table = " + CREATE TABLE IF NOT EXISTS torrent_aggregate_metrics ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + metric_name TEXT NOT NULL UNIQUE, + value INTEGER DEFAULT 0 NOT NULL + );" + .to_string(); + let create_keys_table = " CREATE TABLE IF NOT EXISTS keys ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -82,6 +123,7 @@ impl Database for Sqlite { conn.execute(&create_whitelist_table, [])?; conn.execute(&create_keys_table, [])?; conn.execute(&create_torrents_table, [])?; + conn.execute(&create_torrent_aggregate_metrics_table, [])?; Ok(()) } @@ -172,6 +214,30 @@ impl Database for Sqlite { Ok(()) } + /// Refer to [`databases::Database::load_global_number_of_downloads`](crate::core::databases::Database::load_global_number_of_downloads). + fn load_global_number_of_downloads(&self) -> Result, Error> { + self.load_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL) + } + + /// Refer to [`databases::Database::save_global_number_of_downloads`](crate::core::databases::Database::save_global_number_of_downloads). + fn save_global_number_of_downloads(&self, downloaded: PersistentTorrent) -> Result<(), Error> { + self.save_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL, downloaded) + } + + /// Refer to [`databases::Database::increase_global_number_of_downloads`](crate::core::databases::Database::increase_global_number_of_downloads). + fn increase_global_number_of_downloads(&self) -> Result<(), Error> { + let conn = self.pool.get().map_err(|e| (e, DRIVER))?; + + let metric_name = TORRENTS_DOWNLOADS_TOTAL; + + let _ = conn.execute( + "UPDATE torrent_aggregate_metrics SET value = value + 1 WHERE metric_name = ?", + [metric_name], + )?; + + Ok(()) + } + /// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys). fn load_keys(&self) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs index 2703ab8bf..a9d6b2a22 100644 --- a/packages/tracker-core/src/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -131,16 +131,48 @@ pub trait Database: Sync + Send { /// It does not create a new entry if the torrent is not found and it does /// not return an error. /// + /// # Context: Torrent Metrics + /// + /// # Arguments + /// + /// * `info_hash` - A reference to the torrent's info hash. + /// + /// # Errors + /// + /// Returns an [`Error`] if the query failed. + fn increase_number_of_downloads(&self, info_hash: &InfoHash) -> Result<(), Error>; + + /// Loads the total number of downloads for all torrents from the database. + /// + /// # Context: Torrent Metrics + /// + /// # Errors + /// + /// Returns an [`Error`] if the total downloads cannot be loaded. + fn load_global_number_of_downloads(&self) -> Result, Error>; + + /// Saves the total number of downloads for all torrents into the database. + /// + /// # Context: Torrent Metrics + /// /// # Arguments /// /// * `info_hash` - A reference to the torrent's info hash. + /// * `downloaded` - The number of times the torrent has been downloaded. + /// + /// # Errors + /// + /// Returns an [`Error`] if the total downloads cannot be saved. + fn save_global_number_of_downloads(&self, downloaded: PersistentTorrent) -> Result<(), Error>; + + /// Increases the total number of downloads for all torrents. /// /// # Context: Torrent Metrics /// /// # Errors /// /// Returns an [`Error`] if the query failed. - fn increase_number_of_downloads(&self, info_hash: &InfoHash) -> Result<(), Error>; + fn increase_global_number_of_downloads(&self) -> Result<(), Error>; // Whitelist From 9301e587ab8f4d565c19418ebb46a4340a1fcc9f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 May 2025 10:57:20 +0100 Subject: [PATCH 1133/1297] feat: [#1539] save global downloads counter in DB The total number of dowloads (for all torrents) is saved in the DB, but not loaded yet. todo: load the initial value when the tracker starts. --- .../src/statistics/event/handler.rs | 34 +++++++++++-------- .../src/torrent/repository/persisted.rs | 16 +++++++++ 2 files changed, 36 insertions(+), 14 deletions(-) diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs index ac6d0639e..e394641b8 100644 --- a/packages/tracker-core/src/statistics/event/handler.rs +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -41,17 +41,7 @@ pub async fn handle_event( Event::PeerDownloadCompleted { info_hash, peer } => { tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer download completed", ); - // Increment the number of downloads for the torrent - match db_torrent_repository.increase_number_of_downloads(&info_hash) { - Ok(()) => { - tracing::debug!(info_hash = ?info_hash, "Number of downloads increased"); - } - Err(err) => { - tracing::error!(info_hash = ?info_hash, error = ?err, "Failed to increase number of downloads"); - } - } - - // Increment the number of downloads for all the torrents + // Increment the number of downloads for all the torrents in memory let _unused = stats_repository .increment_counter( &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), @@ -60,9 +50,25 @@ pub async fn handle_event( ) .await; - // todo: - // - Persist the metric into the database. - // - Load the metric from the database. + // Increment the number of downloads for the torrent in the database + match db_torrent_repository.increase_number_of_downloads(&info_hash) { + Ok(()) => { + tracing::debug!(info_hash = ?info_hash, "Number of torrent downloads increased"); + } + Err(err) => { + tracing::error!(info_hash = ?info_hash, error = ?err, "Failed to increase number of downloads for the torrent"); + } + } + + // Increment the global number of downloads (for all torrents) in the database + match db_torrent_repository.increase_global_number_of_downloads() { + Ok(()) => { + tracing::debug!("Global number of downloads increased"); + } + Err(err) => { + tracing::error!(error = ?err, "Failed to increase global number of downloads"); + } + } } } } diff --git a/packages/tracker-core/src/torrent/repository/persisted.rs b/packages/tracker-core/src/torrent/repository/persisted.rs index dec571baf..62e3244ba 100644 --- a/packages/tracker-core/src/torrent/repository/persisted.rs +++ b/packages/tracker-core/src/torrent/repository/persisted.rs @@ -67,6 +67,22 @@ impl DatabasePersistentTorrentRepository { } } + /// Increases the global number of downloads for all torrent. + /// + /// If the metric is not found, it creates it. + /// + /// # Errors + /// + /// Returns an [`Error`] if the database operation fails. + pub(crate) fn increase_global_number_of_downloads(&self) -> Result<(), Error> { + let torrent = self.database.load_global_number_of_downloads()?; + + match torrent { + Some(_number_of_downloads) => self.database.increase_global_number_of_downloads(), + None => self.database.save_global_number_of_downloads(1), + } + } + /// Loads all persistent torrent metrics from the database. /// /// This function retrieves the torrent metrics (e.g., download counts) from the persistent store From c07f3667572b9c70c72f281aabe0a2f13cebcdc3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 May 2025 12:05:20 +0100 Subject: [PATCH 1134/1297] feat: [#1539] load global downloads counter from DB When the tracker starts. --- packages/metrics/src/counter.rs | 11 ++++ packages/metrics/src/metric/mod.rs | 4 ++ packages/metrics/src/metric_collection.rs | 43 +++++++++++++- packages/metrics/src/sample.rs | 5 ++ packages/metrics/src/sample_collection.rs | 9 +++ .../tracker-core/src/statistics/metrics.rs | 13 +++++ packages/tracker-core/src/statistics/mod.rs | 1 + .../src/statistics/persisted_metrics.rs | 57 +++++++++++++++++++ .../tracker-core/src/statistics/repository.rs | 25 ++++++++ .../src/torrent/repository/persisted.rs | 45 +++++++++------ packages/tracker-core/tests/integration.rs | 2 +- src/app.rs | 17 ++++++ 12 files changed, 214 insertions(+), 18 deletions(-) create mode 100644 packages/tracker-core/src/statistics/persisted_metrics.rs diff --git a/packages/metrics/src/counter.rs b/packages/metrics/src/counter.rs index 3a816c75b..ac6d21836 100644 --- a/packages/metrics/src/counter.rs +++ b/packages/metrics/src/counter.rs @@ -20,6 +20,10 @@ impl Counter { pub fn increment(&mut self, value: u64) { self.0 += value; } + + pub fn absolute(&mut self, value: u64) { + self.0 = value; + } } impl From for Counter { @@ -73,6 +77,13 @@ mod tests { assert_eq!(counter.value(), 3); } + #[test] + fn it_could_set_to_an_absolute_value() { + let mut counter = Counter::new(0); + counter.absolute(1); + assert_eq!(counter.value(), 1); + } + #[test] fn it_serializes_to_prometheus() { let counter = Counter::new(42); diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index 05779f09f..2118637b8 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -55,6 +55,10 @@ impl Metric { pub fn increment(&mut self, label_set: &LabelSet, time: DurationSinceUnixEpoch) { self.sample_collection.increment(label_set, time); } + + pub fn absolute(&mut self, label_set: &LabelSet, value: u64, time: DurationSinceUnixEpoch) { + self.sample_collection.absolute(label_set, value, time); + } } impl Metric { diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index 83b08f178..824397000 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -72,6 +72,8 @@ impl MetricCollection { self.counters.get_value(name, label_set) } + /// Increases the counter for the given metric name and labels. + /// /// # Errors /// /// Return an error if a metrics of a different type with the same name @@ -93,6 +95,30 @@ impl MetricCollection { Ok(()) } + /// Sets the counter for the given metric name and labels. + /// + /// # Errors + /// + /// Return an error if a metrics of a different type with the same name + /// already exists. + pub fn set_counter( + &mut self, + name: &MetricName, + label_set: &LabelSet, + value: u64, + time: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + if self.gauges.metrics.contains_key(name) { + return Err(Error::MetricNameCollisionAdding { + metric_name: name.clone(), + }); + } + + self.counters.absolute(name, label_set, value, time); + + Ok(()) + } + pub fn ensure_counter_exists(&mut self, name: &MetricName) { self.counters.ensure_metric_exists(name); } @@ -361,7 +387,7 @@ impl MetricKindCollection { /// /// # Panics /// - /// Panics if the metric does not exist and it could not be created. + /// Panics if the metric does not exist. pub fn increment(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { self.ensure_metric_exists(name); @@ -370,6 +396,21 @@ impl MetricKindCollection { metric.increment(label_set, time); } + /// Sets the counter to an absolute value for the given metric name and labels. + /// + /// If the metric name does not exist, it will be created. + /// + /// # Panics + /// + /// Panics if the metric does not exist. + pub fn absolute(&mut self, name: &MetricName, label_set: &LabelSet, value: u64, time: DurationSinceUnixEpoch) { + self.ensure_metric_exists(name); + + let metric = self.metrics.get_mut(name).expect("Counter metric should exist"); + + metric.absolute(label_set, value, time); + } + #[must_use] pub fn get_value(&self, name: &MetricName, label_set: &LabelSet) -> Option { self.metrics diff --git a/packages/metrics/src/sample.rs b/packages/metrics/src/sample.rs index 4621c9906..ad4dff00e 100644 --- a/packages/metrics/src/sample.rs +++ b/packages/metrics/src/sample.rs @@ -122,6 +122,11 @@ impl Measurement { self.value.increment(1); self.set_recorded_at(time); } + + pub fn absolute(&mut self, value: u64, time: DurationSinceUnixEpoch) { + self.value.absolute(value); + self.set_recorded_at(time); + } } impl Measurement { diff --git a/packages/metrics/src/sample_collection.rs b/packages/metrics/src/sample_collection.rs index ea6b4d4af..e815f26ec 100644 --- a/packages/metrics/src/sample_collection.rs +++ b/packages/metrics/src/sample_collection.rs @@ -79,6 +79,15 @@ impl SampleCollection { sample.increment(time); } + + pub fn absolute(&mut self, label_set: &LabelSet, value: u64, time: DurationSinceUnixEpoch) { + let sample = self + .samples + .entry(label_set.clone()) + .or_insert_with(|| Measurement::new(Counter::default(), time)); + + sample.absolute(value, time); + } } impl SampleCollection { diff --git a/packages/tracker-core/src/statistics/metrics.rs b/packages/tracker-core/src/statistics/metrics.rs index f8ab3f9d9..02cc51499 100644 --- a/packages/tracker-core/src/statistics/metrics.rs +++ b/packages/tracker-core/src/statistics/metrics.rs @@ -24,6 +24,19 @@ impl Metrics { self.metric_collection.increase_counter(metric_name, labels, now) } + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn set_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: u64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_counter(metric_name, labels, value, now) + } + /// # Errors /// /// Returns an error if the metric does not exist and it cannot be created. diff --git a/packages/tracker-core/src/statistics/mod.rs b/packages/tracker-core/src/statistics/mod.rs index 1cd9aac6b..89d6b79d5 100644 --- a/packages/tracker-core/src/statistics/mod.rs +++ b/packages/tracker-core/src/statistics/mod.rs @@ -1,5 +1,6 @@ pub mod event; pub mod metrics; +pub mod persisted_metrics; pub mod repository; use metrics::Metrics; diff --git a/packages/tracker-core/src/statistics/persisted_metrics.rs b/packages/tracker-core/src/statistics/persisted_metrics.rs new file mode 100644 index 000000000..4d53236a5 --- /dev/null +++ b/packages/tracker-core/src/statistics/persisted_metrics.rs @@ -0,0 +1,57 @@ +use std::sync::Arc; + +use thiserror::Error; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::{metric_collection, metric_name}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use super::repository::Repository; +use super::TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL; +use crate::databases; +use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; + +/// Loads persisted metrics from the database and sets them in the stats repository. +/// +/// # Errors +/// +/// This function will return an error if the database query fails or if the +/// metric collection fails to set the initial metric values. +pub async fn load_persisted_metrics( + stats_repository: &Arc, + db_torrent_repository: &Arc, + now: DurationSinceUnixEpoch, +) -> Result<(), Error> { + if let Some(downloads) = db_torrent_repository.load_global_number_of_downloads()? { + stats_repository + .set_counter( + &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), + &LabelSet::default(), + u64::from(downloads), + now, + ) + .await?; + } + + Ok(()) +} + +#[derive(Error, Debug, Clone)] +pub enum Error { + #[error("Database error: {err}")] + DatabaseError { err: databases::error::Error }, + + #[error("Metrics error: {err}")] + MetricsError { err: metric_collection::Error }, +} + +impl From for Error { + fn from(err: databases::error::Error) -> Self { + Self::DatabaseError { err } + } +} + +impl From for Error { + fn from(err: metric_collection::Error) -> Self { + Self::MetricsError { err } + } +} diff --git a/packages/tracker-core/src/statistics/repository.rs b/packages/tracker-core/src/statistics/repository.rs index fe1292d00..dd0ebebe7 100644 --- a/packages/tracker-core/src/statistics/repository.rs +++ b/packages/tracker-core/src/statistics/repository.rs @@ -57,6 +57,31 @@ impl Repository { result } + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increment the counter. + pub async fn set_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + value: u64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + let mut stats_lock = self.stats.write().await; + + let result = stats_lock.set_counter(metric_name, labels, value, now); + + drop(stats_lock); + + match result { + Ok(()) => {} + Err(ref err) => tracing::error!("Failed to set the counter: {}", err), + } + + result + } + /// # Errors /// /// This function will return an error if the metric collection fails to diff --git a/packages/tracker-core/src/torrent/repository/persisted.rs b/packages/tracker-core/src/torrent/repository/persisted.rs index 62e3244ba..1818065fd 100644 --- a/packages/tracker-core/src/torrent/repository/persisted.rs +++ b/packages/tracker-core/src/torrent/repository/persisted.rs @@ -47,6 +47,8 @@ impl DatabasePersistentTorrentRepository { } } + // Single Torrent Metrics + /// Increases the number of downloads for a given torrent. /// /// If the torrent is not found, it creates a new entry. @@ -67,22 +69,6 @@ impl DatabasePersistentTorrentRepository { } } - /// Increases the global number of downloads for all torrent. - /// - /// If the metric is not found, it creates it. - /// - /// # Errors - /// - /// Returns an [`Error`] if the database operation fails. - pub(crate) fn increase_global_number_of_downloads(&self) -> Result<(), Error> { - let torrent = self.database.load_global_number_of_downloads()?; - - match torrent { - Some(_number_of_downloads) => self.database.increase_global_number_of_downloads(), - None => self.database.save_global_number_of_downloads(1), - } - } - /// Loads all persistent torrent metrics from the database. /// /// This function retrieves the torrent metrics (e.g., download counts) from the persistent store @@ -123,6 +109,33 @@ impl DatabasePersistentTorrentRepository { pub(crate) fn save(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error> { self.database.save_persistent_torrent(info_hash, downloaded) } + + // Aggregate Metrics + + /// Increases the global number of downloads for all torrent. + /// + /// If the metric is not found, it creates it. + /// + /// # Errors + /// + /// Returns an [`Error`] if the database operation fails. + pub(crate) fn increase_global_number_of_downloads(&self) -> Result<(), Error> { + let torrent = self.database.load_global_number_of_downloads()?; + + match torrent { + Some(_number_of_downloads) => self.database.increase_global_number_of_downloads(), + None => self.database.save_global_number_of_downloads(1), + } + } + + /// Loads the global number of downloads for all torrents from the database. + /// + /// # Errors + /// + /// Returns an [`Error`] if the underlying database query fails. + pub(crate) fn load_global_number_of_downloads(&self) -> Result, Error> { + self.database.load_global_number_of_downloads() + } } #[cfg(test)] diff --git a/packages/tracker-core/tests/integration.rs b/packages/tracker-core/tests/integration.rs index d24acf67b..986bdaaf3 100644 --- a/packages/tracker-core/tests/integration.rs +++ b/packages/tracker-core/tests/integration.rs @@ -58,7 +58,7 @@ async fn it_should_handle_the_scrape_request() { } #[tokio::test] -async fn it_should_persist_the_number_of_completed_peers_for_all_torrents_into_the_database() { +async fn it_should_persist_the_number_of_completed_peers_for_each_torrent_into_the_database() { let mut core_config = ephemeral_configuration(); core_config.tracker_policy.persistent_torrent_completed_stat = true; diff --git a/src/app.rs b/src/app.rs index 5037ad761..571e034f5 100644 --- a/src/app.rs +++ b/src/app.rs @@ -23,6 +23,7 @@ //! - Tracker REST API: the tracker API can be enabled/disabled. use std::sync::Arc; +use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{Configuration, HttpTracker, UdpTracker}; use tracing::instrument; @@ -32,6 +33,7 @@ use crate::bootstrap::jobs::{ }; use crate::bootstrap::{self}; use crate::container::AppContainer; +use crate::CurrentClock; pub async fn run() -> (Arc, JobManager) { let (config, app_container) = bootstrap::app::setup(); @@ -63,6 +65,8 @@ pub async fn start(config: &Configuration, app_container: &Arc) -> async fn load_data_from_database(config: &Configuration, app_container: &Arc) { load_peer_keys(config, app_container).await; load_whitelisted_torrents(config, app_container).await; + load_torrent_metrics(config, app_container).await; + // todo: disabled because of performance issues. // The tracker demo has a lot of torrents and loading them all at once is not // efficient. We also load them on demand but the total number of downloads @@ -134,6 +138,19 @@ fn load_torrents_from_database(config: &Configuration, app_container: &Arc) { + if config.core.tracker_policy.persistent_torrent_completed_stat { + bittorrent_tracker_core::statistics::persisted_metrics::load_persisted_metrics( + &app_container.tracker_core_container.stats_repository, + &app_container.tracker_core_container.db_torrent_repository, + CurrentClock::now(), + ) + .await + .expect("Could not load persisted metrics from database."); + } +} + fn start_torrent_repository_event_listener( config: &Configuration, app_container: &Arc, From 2c9311bf2240cbc56ccbb3ec5dfee954d666a13e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 May 2025 12:54:35 +0100 Subject: [PATCH 1135/1297] test: [#1539] add integration test for persisted downloads counter --- .../tracker-core/tests/common/test_env.rs | 31 +++++++++++++++++++ packages/tracker-core/tests/integration.rs | 25 +++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/packages/tracker-core/tests/common/test_env.rs b/packages/tracker-core/tests/common/test_env.rs index 0be8bd4c6..4e14e9bd8 100644 --- a/packages/tracker-core/tests/common/test_env.rs +++ b/packages/tracker-core/tests/common/test_env.rs @@ -5,11 +5,15 @@ use aquatic_udp_protocol::AnnounceEvent; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::PeersWanted; use bittorrent_tracker_core::container::TrackerCoreContainer; +use bittorrent_tracker_core::statistics::persisted_metrics::load_persisted_metrics; use tokio::task::yield_now; use torrust_tracker_configuration::Core; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric::MetricName; use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; +use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; pub struct TestEnv { @@ -45,6 +49,22 @@ impl TestEnv { } pub async fn start(&self) { + let now = DurationSinceUnixEpoch::from_secs(0); + self.load_persisted_metrics(now).await; + self.run_jobs().await; + } + + async fn load_persisted_metrics(&self, now: DurationSinceUnixEpoch) { + load_persisted_metrics( + &self.tracker_core_container.stats_repository, + &self.tracker_core_container.db_torrent_repository, + now, + ) + .await + .unwrap(); + } + + async fn run_jobs(&self) { let mut jobs = vec![]; let job = torrust_tracker_torrent_repository::statistics::event::listener::run_event_listener( @@ -135,4 +155,15 @@ impl TestEnv { pub async fn remove_swarm(&self, info_hash: &InfoHash) { self.torrent_repository_container.swarms.remove(info_hash).await.unwrap(); } + + pub async fn get_counter_value(&self, metric_name: &str) -> u64 { + self.tracker_core_container + .stats_repository + .get_metrics() + .await + .metric_collection + .get_counter_value(&MetricName::new(metric_name), &LabelSet::default()) + .unwrap() + .value() + } } diff --git a/packages/tracker-core/tests/integration.rs b/packages/tracker-core/tests/integration.rs index 986bdaaf3..b170aaebd 100644 --- a/packages/tracker-core/tests/integration.rs +++ b/packages/tracker-core/tests/integration.rs @@ -86,3 +86,28 @@ async fn it_should_persist_the_number_of_completed_peers_for_each_torrent_into_t assert!(test_env.get_swarm_metadata(&info_hash).await.unwrap().downloads() == 1); } + +#[tokio::test] +async fn it_should_persist_the_global_number_of_completed_peers_into_the_database() { + let mut core_config = ephemeral_configuration(); + + core_config.tracker_policy.persistent_torrent_completed_stat = true; + + let mut test_env = TestEnv::started(core_config.clone()).await; + + test_env + .increase_number_of_downloads(sample_peer(), &remote_client_ip(), &sample_info_hash()) + .await; + + // We run a new instance of the test environment to simulate a restart. + // The new instance uses the same underlying database. + + let new_test_env = TestEnv::started(core_config).await; + + assert_eq!( + new_test_env + .get_counter_value("tracker_core_persistent_torrents_downloads_total") + .await, + 1 + ); +} From 4febda494e036f772e2c473a784acf0d254d026c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 May 2025 13:17:57 +0100 Subject: [PATCH 1136/1297] fic: [#1539] persisten metrics should be enabled by config --- .../src/statistics/event/handler.rs | 33 ++++++++++--------- .../src/statistics/event/listener.rs | 17 ++++++++-- .../tracker-core/tests/common/test_env.rs | 4 +++ src/bootstrap/jobs/tracker_core.rs | 5 +++ 4 files changed, 42 insertions(+), 17 deletions(-) diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs index e394641b8..4002053e2 100644 --- a/packages/tracker-core/src/statistics/event/handler.rs +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -13,6 +13,7 @@ pub async fn handle_event( event: Event, stats_repository: &Arc, db_torrent_repository: &Arc, + persistent_torrent_completed_stat: bool, now: DurationSinceUnixEpoch, ) { match event { @@ -50,23 +51,25 @@ pub async fn handle_event( ) .await; - // Increment the number of downloads for the torrent in the database - match db_torrent_repository.increase_number_of_downloads(&info_hash) { - Ok(()) => { - tracing::debug!(info_hash = ?info_hash, "Number of torrent downloads increased"); + if persistent_torrent_completed_stat { + // Increment the number of downloads for the torrent in the database + match db_torrent_repository.increase_number_of_downloads(&info_hash) { + Ok(()) => { + tracing::debug!(info_hash = ?info_hash, "Number of torrent downloads increased"); + } + Err(err) => { + tracing::error!(info_hash = ?info_hash, error = ?err, "Failed to increase number of downloads for the torrent"); + } } - Err(err) => { - tracing::error!(info_hash = ?info_hash, error = ?err, "Failed to increase number of downloads for the torrent"); - } - } - // Increment the global number of downloads (for all torrents) in the database - match db_torrent_repository.increase_global_number_of_downloads() { - Ok(()) => { - tracing::debug!("Global number of downloads increased"); - } - Err(err) => { - tracing::error!(error = ?err, "Failed to increase global number of downloads"); + // Increment the global number of downloads (for all torrents) in the database + match db_torrent_repository.increase_global_number_of_downloads() { + Ok(()) => { + tracing::debug!("Global number of downloads increased"); + } + Err(err) => { + tracing::error!(error = ?err, "Failed to increase global number of downloads"); + } } } } diff --git a/packages/tracker-core/src/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs index f85b2b7a0..cf6d35d6e 100644 --- a/packages/tracker-core/src/statistics/event/listener.rs +++ b/packages/tracker-core/src/statistics/event/listener.rs @@ -15,6 +15,7 @@ pub fn run_event_listener( receiver: Receiver, repository: &Arc, db_torrent_repository: &Arc, + persistent_torrent_completed_stat: bool, ) -> JoinHandle<()> { let stats_repository = repository.clone(); let db_torrent_repository: Arc = db_torrent_repository.clone(); @@ -22,7 +23,13 @@ pub fn run_event_listener( tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Starting torrent repository event listener"); tokio::spawn(async move { - dispatch_events(receiver, stats_repository, db_torrent_repository).await; + dispatch_events( + receiver, + stats_repository, + db_torrent_repository, + persistent_torrent_completed_stat, + ) + .await; tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Torrent repository listener finished"); }) @@ -32,6 +39,7 @@ async fn dispatch_events( mut receiver: Receiver, stats_repository: Arc, db_torrent_repository: Arc, + persistent_torrent_completed_stat: bool, ) { let shutdown_signal = tokio::signal::ctrl_c(); @@ -48,7 +56,12 @@ async fn dispatch_events( result = receiver.recv() => { match result { - Ok(event) => handle_event(event, &stats_repository, &db_torrent_repository, CurrentClock::now()).await, + Ok(event) => handle_event( + event, + &stats_repository, + &db_torrent_repository, + persistent_torrent_completed_stat, + CurrentClock::now()).await, Err(e) => { match e { RecvError::Closed => { diff --git a/packages/tracker-core/tests/common/test_env.rs b/packages/tracker-core/tests/common/test_env.rs index 4e14e9bd8..11a4d400a 100644 --- a/packages/tracker-core/tests/common/test_env.rs +++ b/packages/tracker-core/tests/common/test_env.rs @@ -78,6 +78,10 @@ impl TestEnv { self.torrent_repository_container.event_bus.receiver(), &self.tracker_core_container.stats_repository, &self.tracker_core_container.db_torrent_repository, + self.tracker_core_container + .core_config + .tracker_policy + .persistent_torrent_completed_stat, ); jobs.push(job); diff --git a/src/bootstrap/jobs/tracker_core.rs b/src/bootstrap/jobs/tracker_core.rs index 37c53b9e4..161e69aad 100644 --- a/src/bootstrap/jobs/tracker_core.rs +++ b/src/bootstrap/jobs/tracker_core.rs @@ -11,6 +11,11 @@ pub fn start_event_listener(config: &Configuration, app_container: &Arc Date: Tue, 27 May 2025 14:36:23 +0100 Subject: [PATCH 1137/1297] refactor: [#1541] rename DatabasePersistentTorrentRepository to DatabaseDownloadsMetricRepository --- .../src/v1/handlers/announce.rs | 4 ++-- packages/http-tracker-core/benches/helpers/util.rs | 4 ++-- packages/http-tracker-core/src/services/announce.rs | 4 ++-- packages/http-tracker-core/src/services/scrape.rs | 4 ++-- packages/tracker-core/src/announce_handler.rs | 6 +++--- packages/tracker-core/src/container.rs | 6 +++--- .../tracker-core/src/statistics/event/handler.rs | 4 ++-- .../tracker-core/src/statistics/event/listener.rs | 8 ++++---- .../tracker-core/src/statistics/persisted_metrics.rs | 4 ++-- packages/tracker-core/src/test_helpers.rs | 4 ++-- packages/tracker-core/src/torrent/manager.rs | 12 ++++++------ .../tracker-core/src/torrent/repository/persisted.rs | 12 ++++++------ packages/udp-tracker-server/src/handlers/announce.rs | 4 ++-- packages/udp-tracker-server/src/handlers/mod.rs | 4 ++-- 14 files changed, 40 insertions(+), 40 deletions(-) diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 7d7a0b386..c195b5a1f 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -120,7 +120,7 @@ mod tests { use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::Configuration; @@ -156,7 +156,7 @@ mod tests { let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository)); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &whitelist_authorization, diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index cfb3f745f..bf870b39c 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -15,7 +15,7 @@ use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemor use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use bittorrent_tracker_core::torrent::repository::persisted::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; @@ -45,7 +45,7 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( let core_config = Arc::new(config.core.clone()); let database = initialize_database(&config.core); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 0ad5ed143..36dd58193 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -213,7 +213,7 @@ mod tests { use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::{Configuration, Core}; @@ -239,7 +239,7 @@ mod tests { let core_config = Arc::new(config.core.clone()); let database = initialize_database(&config.core); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index f22f2f632..e98c1b2c4 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -177,7 +177,7 @@ mod tests { use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; @@ -200,7 +200,7 @@ mod tests { let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository)); diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index ffd244f2a..5c79e32bf 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -99,7 +99,7 @@ use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; use super::torrent::repository::in_memory::InMemoryTorrentRepository; -use super::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use super::torrent::repository::persisted::DatabaseDownloadsMetricRepository; use crate::error::AnnounceError; use crate::whitelist::authorization::WhitelistAuthorization; @@ -115,7 +115,7 @@ pub struct AnnounceHandler { in_memory_torrent_repository: Arc, /// Repository for persistent torrent data (database). - db_torrent_repository: Arc, + db_torrent_repository: Arc, } impl AnnounceHandler { @@ -125,7 +125,7 @@ impl AnnounceHandler { config: &Core, whitelist_authorization: &Arc, in_memory_torrent_repository: &Arc, - db_torrent_repository: &Arc, + db_torrent_repository: &Arc, ) -> Self { Self { whitelist_authorization: whitelist_authorization.clone(), diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs index ed56fb106..8c6f360eb 100644 --- a/packages/tracker-core/src/container.rs +++ b/packages/tracker-core/src/container.rs @@ -13,7 +13,7 @@ use crate::databases::Database; use crate::scrape_handler::ScrapeHandler; use crate::torrent::manager::TorrentsManager; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use crate::torrent::repository::persisted::DatabaseDownloadsMetricRepository; use crate::whitelist::authorization::WhitelistAuthorization; use crate::whitelist::manager::WhitelistManager; use crate::whitelist::repository::in_memory::InMemoryWhitelist; @@ -31,7 +31,7 @@ pub struct TrackerCoreContainer { pub whitelist_authorization: Arc, pub whitelist_manager: Arc, pub in_memory_torrent_repository: Arc, - pub db_torrent_repository: Arc, + pub db_torrent_repository: Arc, pub torrents_manager: Arc, pub stats_repository: Arc, } @@ -51,7 +51,7 @@ impl TrackerCoreContainer { &in_memory_key_repository.clone(), )); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new(torrent_repository_container.swarms.clone())); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let torrents_manager = Arc::new(TorrentsManager::new( core_config, diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs index 4002053e2..028e7bc46 100644 --- a/packages/tracker-core/src/statistics/event/handler.rs +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -7,12 +7,12 @@ use torrust_tracker_torrent_repository::event::Event; use crate::statistics::repository::Repository; use crate::statistics::TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL; -use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use crate::torrent::repository::persisted::DatabaseDownloadsMetricRepository; pub async fn handle_event( event: Event, stats_repository: &Arc, - db_torrent_repository: &Arc, + db_torrent_repository: &Arc, persistent_torrent_completed_stat: bool, now: DurationSinceUnixEpoch, ) { diff --git a/packages/tracker-core/src/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs index cf6d35d6e..63c75e2f6 100644 --- a/packages/tracker-core/src/statistics/event/listener.rs +++ b/packages/tracker-core/src/statistics/event/listener.rs @@ -7,18 +7,18 @@ use torrust_tracker_torrent_repository::event::receiver::Receiver; use super::handler::handle_event; use crate::statistics::repository::Repository; -use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use crate::torrent::repository::persisted::DatabaseDownloadsMetricRepository; use crate::{CurrentClock, TRACKER_CORE_LOG_TARGET}; #[must_use] pub fn run_event_listener( receiver: Receiver, repository: &Arc, - db_torrent_repository: &Arc, + db_torrent_repository: &Arc, persistent_torrent_completed_stat: bool, ) -> JoinHandle<()> { let stats_repository = repository.clone(); - let db_torrent_repository: Arc = db_torrent_repository.clone(); + let db_torrent_repository: Arc = db_torrent_repository.clone(); tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Starting torrent repository event listener"); @@ -38,7 +38,7 @@ pub fn run_event_listener( async fn dispatch_events( mut receiver: Receiver, stats_repository: Arc, - db_torrent_repository: Arc, + db_torrent_repository: Arc, persistent_torrent_completed_stat: bool, ) { let shutdown_signal = tokio::signal::ctrl_c(); diff --git a/packages/tracker-core/src/statistics/persisted_metrics.rs b/packages/tracker-core/src/statistics/persisted_metrics.rs index 4d53236a5..73c52884e 100644 --- a/packages/tracker-core/src/statistics/persisted_metrics.rs +++ b/packages/tracker-core/src/statistics/persisted_metrics.rs @@ -8,7 +8,7 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::repository::Repository; use super::TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL; use crate::databases; -use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; +use crate::torrent::repository::persisted::DatabaseDownloadsMetricRepository; /// Loads persisted metrics from the database and sets them in the stats repository. /// @@ -18,7 +18,7 @@ use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; /// metric collection fails to set the initial metric values. pub async fn load_persisted_metrics( stats_repository: &Arc, - db_torrent_repository: &Arc, + db_torrent_repository: &Arc, now: DurationSinceUnixEpoch, ) -> Result<(), Error> { if let Some(downloads) = db_torrent_repository.load_global_number_of_downloads()? { diff --git a/packages/tracker-core/src/test_helpers.rs b/packages/tracker-core/src/test_helpers.rs index 04fe4133b..540381c75 100644 --- a/packages/tracker-core/src/test_helpers.rs +++ b/packages/tracker-core/src/test_helpers.rs @@ -20,7 +20,7 @@ pub(crate) mod tests { use crate::databases::setup::initialize_database; use crate::scrape_handler::ScrapeHandler; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use crate::torrent::repository::persisted::DatabaseDownloadsMetricRepository; use crate::whitelist::repository::in_memory::InMemoryWhitelist; use crate::whitelist::{self}; @@ -137,7 +137,7 @@ pub(crate) mod tests { &in_memory_whitelist.clone(), )); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index d9997c4ad..dfcdaf38c 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -7,7 +7,7 @@ use torrust_tracker_configuration::Core; use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::repository::in_memory::InMemoryTorrentRepository; -use super::repository::persisted::DatabasePersistentTorrentRepository; +use super::repository::persisted::DatabaseDownloadsMetricRepository; use crate::{databases, CurrentClock}; /// The `TorrentsManager` is responsible for managing torrent entries by @@ -31,7 +31,7 @@ pub struct TorrentsManager { /// The persistent torrents repository. #[allow(dead_code)] - db_torrent_repository: Arc, + db_torrent_repository: Arc, } impl TorrentsManager { @@ -52,7 +52,7 @@ impl TorrentsManager { pub fn new( config: &Core, in_memory_torrent_repository: &Arc, - db_torrent_repository: &Arc, + db_torrent_repository: &Arc, ) -> Self { Self { config: config.clone(), @@ -153,7 +153,7 @@ mod tests { use torrust_tracker_configuration::Core; use torrust_tracker_torrent_repository::Swarms; - use super::{DatabasePersistentTorrentRepository, TorrentsManager}; + use super::{DatabaseDownloadsMetricRepository, TorrentsManager}; use crate::databases::setup::initialize_database; use crate::test_helpers::tests::{ephemeral_configuration, sample_info_hash}; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; @@ -161,7 +161,7 @@ mod tests { struct TorrentsManagerDeps { config: Arc, in_memory_torrent_repository: Arc, - database_persistent_torrent_repository: Arc, + database_persistent_torrent_repository: Arc, } fn initialize_torrents_manager() -> (Arc, Arc) { @@ -173,7 +173,7 @@ mod tests { let swarms = Arc::new(Swarms::default()); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new(swarms)); let database = initialize_database(&config); - let database_persistent_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let database_persistent_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let torrents_manager = Arc::new(TorrentsManager::new( &config, diff --git a/packages/tracker-core/src/torrent/repository/persisted.rs b/packages/tracker-core/src/torrent/repository/persisted.rs index 1818065fd..d6c6ce263 100644 --- a/packages/tracker-core/src/torrent/repository/persisted.rs +++ b/packages/tracker-core/src/torrent/repository/persisted.rs @@ -19,7 +19,7 @@ use crate::databases::Database; /// /// Not all in-memory torrent data is persisted; only the aggregate metrics are /// stored. -pub struct DatabasePersistentTorrentRepository { +pub struct DatabaseDownloadsMetricRepository { /// A shared reference to the database driver implementation. /// /// The driver must implement the [`Database`] trait. This allows for @@ -28,7 +28,7 @@ pub struct DatabasePersistentTorrentRepository { database: Arc>, } -impl DatabasePersistentTorrentRepository { +impl DatabaseDownloadsMetricRepository { /// Creates a new instance of `DatabasePersistentTorrentRepository`. /// /// # Arguments @@ -41,7 +41,7 @@ impl DatabasePersistentTorrentRepository { /// A new `DatabasePersistentTorrentRepository` instance with a cloned /// reference to the provided database. #[must_use] - pub fn new(database: &Arc>) -> DatabasePersistentTorrentRepository { + pub fn new(database: &Arc>) -> DatabaseDownloadsMetricRepository { Self { database: database.clone(), } @@ -143,14 +143,14 @@ mod tests { use torrust_tracker_primitives::PersistentTorrents; - use super::DatabasePersistentTorrentRepository; + use super::DatabaseDownloadsMetricRepository; use crate::databases::setup::initialize_database; use crate::test_helpers::tests::{ephemeral_configuration, sample_info_hash, sample_info_hash_one, sample_info_hash_two}; - fn initialize_db_persistent_torrent_repository() -> DatabasePersistentTorrentRepository { + fn initialize_db_persistent_torrent_repository() -> DatabaseDownloadsMetricRepository { let config = ephemeral_configuration(); let database = initialize_database(&config); - DatabasePersistentTorrentRepository::new(&database) + DatabaseDownloadsMetricRepository::new(&database) } #[test] diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index e2ca6821e..60788ab9c 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -836,7 +836,7 @@ mod tests { use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; @@ -885,7 +885,7 @@ mod tests { let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 831073333..eb51e6d01 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -212,7 +212,7 @@ pub(crate) mod tests { use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabasePersistentTorrentRepository; + use bittorrent_tracker_core::torrent::repository::persisted::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; @@ -275,7 +275,7 @@ pub(crate) mod tests { let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabasePersistentTorrentRepository::new(&database)); + let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &whitelist_authorization, From 99adbdee9dfe7bf9846bfebeacbf0036193385bc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 May 2025 14:41:48 +0100 Subject: [PATCH 1138/1297] refactor: [#1541] rename symbol db_torrent_repository to db_downloads_metric_repository --- .../src/v1/handlers/announce.rs | 4 ++-- packages/http-tracker-core/benches/helpers/util.rs | 4 ++-- packages/http-tracker-core/src/services/announce.rs | 4 ++-- packages/http-tracker-core/src/services/scrape.rs | 4 ++-- packages/tracker-core/src/announce_handler.rs | 8 ++++---- packages/tracker-core/src/container.rs | 10 +++++----- packages/tracker-core/src/statistics/event/handler.rs | 6 +++--- packages/tracker-core/src/statistics/event/listener.rs | 10 +++++----- .../tracker-core/src/statistics/persisted_metrics.rs | 4 ++-- packages/tracker-core/src/test_helpers.rs | 4 ++-- packages/tracker-core/src/torrent/manager.rs | 10 +++++----- packages/tracker-core/tests/common/test_env.rs | 4 ++-- packages/udp-tracker-server/src/handlers/announce.rs | 4 ++-- packages/udp-tracker-server/src/handlers/mod.rs | 4 ++-- src/app.rs | 2 +- src/bootstrap/jobs/tracker_core.rs | 2 +- 16 files changed, 42 insertions(+), 42 deletions(-) diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index c195b5a1f..108ebb33f 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -156,12 +156,12 @@ mod tests { let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository)); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &whitelist_authorization, &in_memory_torrent_repository, - &db_torrent_repository, + &db_downloads_metric_repository, )); // HTTP core stats diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index bf870b39c..06c20543e 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -45,7 +45,7 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( let core_config = Arc::new(config.core.clone()); let database = initialize_database(&config.core); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); @@ -55,7 +55,7 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( &config.core, &whitelist_authorization, &in_memory_torrent_repository, - &db_torrent_repository, + &db_downloads_metric_repository, )); // HTTP core stats diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 36dd58193..7831324f0 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -239,7 +239,7 @@ mod tests { let core_config = Arc::new(config.core.clone()); let database = initialize_database(&config.core); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); @@ -249,7 +249,7 @@ mod tests { &config.core, &whitelist_authorization, &in_memory_torrent_repository, - &db_torrent_repository, + &db_downloads_metric_repository, )); // HTTP core stats diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index e98c1b2c4..0261626a9 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -200,7 +200,7 @@ mod tests { let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default()); let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository)); @@ -208,7 +208,7 @@ mod tests { &config.core, &whitelist_authorization, &in_memory_torrent_repository, - &db_torrent_repository, + &db_downloads_metric_repository, )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 5c79e32bf..847ddd1af 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -115,7 +115,7 @@ pub struct AnnounceHandler { in_memory_torrent_repository: Arc, /// Repository for persistent torrent data (database). - db_torrent_repository: Arc, + db_downloads_metric_repository: Arc, } impl AnnounceHandler { @@ -125,13 +125,13 @@ impl AnnounceHandler { config: &Core, whitelist_authorization: &Arc, in_memory_torrent_repository: &Arc, - db_torrent_repository: &Arc, + db_downloads_metric_repository: &Arc, ) -> Self { Self { whitelist_authorization: whitelist_authorization.clone(), config: config.clone(), in_memory_torrent_repository: in_memory_torrent_repository.clone(), - db_torrent_repository: db_torrent_repository.clone(), + db_downloads_metric_repository: db_downloads_metric_repository.clone(), } } @@ -169,7 +169,7 @@ impl AnnounceHandler { // downloads across all torrents. The in-memory metric will count only // the number of downloads during the current tracker uptime. let opt_persistent_torrent = if self.config.tracker_policy.persistent_torrent_completed_stat { - self.db_torrent_repository.load(info_hash)? + self.db_downloads_metric_repository.load(info_hash)? } else { None }; diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs index 8c6f360eb..4dd795e7a 100644 --- a/packages/tracker-core/src/container.rs +++ b/packages/tracker-core/src/container.rs @@ -31,7 +31,7 @@ pub struct TrackerCoreContainer { pub whitelist_authorization: Arc, pub whitelist_manager: Arc, pub in_memory_torrent_repository: Arc, - pub db_torrent_repository: Arc, + pub db_downloads_metric_repository: Arc, pub torrents_manager: Arc, pub stats_repository: Arc, } @@ -51,12 +51,12 @@ impl TrackerCoreContainer { &in_memory_key_repository.clone(), )); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new(torrent_repository_container.swarms.clone())); - let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let torrents_manager = Arc::new(TorrentsManager::new( core_config, &in_memory_torrent_repository, - &db_torrent_repository, + &db_downloads_metric_repository, )); let stats_repository = Arc::new(statistics::repository::Repository::new()); @@ -65,7 +65,7 @@ impl TrackerCoreContainer { core_config, &whitelist_authorization, &in_memory_torrent_repository, - &db_torrent_repository, + &db_downloads_metric_repository, )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); @@ -81,7 +81,7 @@ impl TrackerCoreContainer { whitelist_authorization, whitelist_manager, in_memory_torrent_repository, - db_torrent_repository, + db_downloads_metric_repository, torrents_manager, stats_repository, } diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs index 028e7bc46..82c56abce 100644 --- a/packages/tracker-core/src/statistics/event/handler.rs +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -12,7 +12,7 @@ use crate::torrent::repository::persisted::DatabaseDownloadsMetricRepository; pub async fn handle_event( event: Event, stats_repository: &Arc, - db_torrent_repository: &Arc, + db_downloads_metric_repository: &Arc, persistent_torrent_completed_stat: bool, now: DurationSinceUnixEpoch, ) { @@ -53,7 +53,7 @@ pub async fn handle_event( if persistent_torrent_completed_stat { // Increment the number of downloads for the torrent in the database - match db_torrent_repository.increase_number_of_downloads(&info_hash) { + match db_downloads_metric_repository.increase_number_of_downloads(&info_hash) { Ok(()) => { tracing::debug!(info_hash = ?info_hash, "Number of torrent downloads increased"); } @@ -63,7 +63,7 @@ pub async fn handle_event( } // Increment the global number of downloads (for all torrents) in the database - match db_torrent_repository.increase_global_number_of_downloads() { + match db_downloads_metric_repository.increase_global_number_of_downloads() { Ok(()) => { tracing::debug!("Global number of downloads increased"); } diff --git a/packages/tracker-core/src/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs index 63c75e2f6..f0d8cb7f1 100644 --- a/packages/tracker-core/src/statistics/event/listener.rs +++ b/packages/tracker-core/src/statistics/event/listener.rs @@ -14,11 +14,11 @@ use crate::{CurrentClock, TRACKER_CORE_LOG_TARGET}; pub fn run_event_listener( receiver: Receiver, repository: &Arc, - db_torrent_repository: &Arc, + db_downloads_metric_repository: &Arc, persistent_torrent_completed_stat: bool, ) -> JoinHandle<()> { let stats_repository = repository.clone(); - let db_torrent_repository: Arc = db_torrent_repository.clone(); + let db_downloads_metric_repository: Arc = db_downloads_metric_repository.clone(); tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Starting torrent repository event listener"); @@ -26,7 +26,7 @@ pub fn run_event_listener( dispatch_events( receiver, stats_repository, - db_torrent_repository, + db_downloads_metric_repository, persistent_torrent_completed_stat, ) .await; @@ -38,7 +38,7 @@ pub fn run_event_listener( async fn dispatch_events( mut receiver: Receiver, stats_repository: Arc, - db_torrent_repository: Arc, + db_downloads_metric_repository: Arc, persistent_torrent_completed_stat: bool, ) { let shutdown_signal = tokio::signal::ctrl_c(); @@ -59,7 +59,7 @@ async fn dispatch_events( Ok(event) => handle_event( event, &stats_repository, - &db_torrent_repository, + &db_downloads_metric_repository, persistent_torrent_completed_stat, CurrentClock::now()).await, Err(e) => { diff --git a/packages/tracker-core/src/statistics/persisted_metrics.rs b/packages/tracker-core/src/statistics/persisted_metrics.rs index 73c52884e..55ec91b10 100644 --- a/packages/tracker-core/src/statistics/persisted_metrics.rs +++ b/packages/tracker-core/src/statistics/persisted_metrics.rs @@ -18,10 +18,10 @@ use crate::torrent::repository::persisted::DatabaseDownloadsMetricRepository; /// metric collection fails to set the initial metric values. pub async fn load_persisted_metrics( stats_repository: &Arc, - db_torrent_repository: &Arc, + db_downloads_metric_repository: &Arc, now: DurationSinceUnixEpoch, ) -> Result<(), Error> { - if let Some(downloads) = db_torrent_repository.load_global_number_of_downloads()? { + if let Some(downloads) = db_downloads_metric_repository.load_global_number_of_downloads()? { stats_repository .set_counter( &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), diff --git a/packages/tracker-core/src/test_helpers.rs b/packages/tracker-core/src/test_helpers.rs index 540381c75..f8b79e4db 100644 --- a/packages/tracker-core/src/test_helpers.rs +++ b/packages/tracker-core/src/test_helpers.rs @@ -137,13 +137,13 @@ pub(crate) mod tests { &in_memory_whitelist.clone(), )); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &whitelist_authorization, &in_memory_torrent_repository, - &db_torrent_repository, + &db_downloads_metric_repository, )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index dfcdaf38c..e18e19ce0 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -31,7 +31,7 @@ pub struct TorrentsManager { /// The persistent torrents repository. #[allow(dead_code)] - db_torrent_repository: Arc, + db_downloads_metric_repository: Arc, } impl TorrentsManager { @@ -42,7 +42,7 @@ impl TorrentsManager { /// * `config` - A reference to the tracker configuration. /// * `in_memory_torrent_repository` - A shared reference to the in-memory /// repository of torrents. - /// * `db_torrent_repository` - A shared reference to the persistent + /// * `db_downloads_metric_repository` - A shared reference to the persistent /// repository for torrent metrics. /// /// # Returns @@ -52,12 +52,12 @@ impl TorrentsManager { pub fn new( config: &Core, in_memory_torrent_repository: &Arc, - db_torrent_repository: &Arc, + db_downloads_metric_repository: &Arc, ) -> Self { Self { config: config.clone(), in_memory_torrent_repository: in_memory_torrent_repository.clone(), - db_torrent_repository: db_torrent_repository.clone(), + db_downloads_metric_repository: db_downloads_metric_repository.clone(), } } @@ -72,7 +72,7 @@ impl TorrentsManager { /// Returns a `databases::error::Error` if unable to load the persistent /// torrent data. pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { - let persistent_torrents = self.db_torrent_repository.load_all()?; + let persistent_torrents = self.db_downloads_metric_repository.load_all()?; println!("Loaded {} persistent torrents from the database", persistent_torrents.len()); diff --git a/packages/tracker-core/tests/common/test_env.rs b/packages/tracker-core/tests/common/test_env.rs index 11a4d400a..88b363234 100644 --- a/packages/tracker-core/tests/common/test_env.rs +++ b/packages/tracker-core/tests/common/test_env.rs @@ -57,7 +57,7 @@ impl TestEnv { async fn load_persisted_metrics(&self, now: DurationSinceUnixEpoch) { load_persisted_metrics( &self.tracker_core_container.stats_repository, - &self.tracker_core_container.db_torrent_repository, + &self.tracker_core_container.db_downloads_metric_repository, now, ) .await @@ -77,7 +77,7 @@ impl TestEnv { let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( self.torrent_repository_container.event_bus.receiver(), &self.tracker_core_container.stats_repository, - &self.tracker_core_container.db_torrent_repository, + &self.tracker_core_container.db_downloads_metric_repository, self.tracker_core_container .core_config .tracker_policy diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 60788ab9c..38e136a12 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -885,7 +885,7 @@ mod tests { let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock @@ -923,7 +923,7 @@ mod tests { &config.core, &whitelist_authorization, &in_memory_torrent_repository, - &db_torrent_repository, + &db_downloads_metric_repository, )); let request = AnnounceRequestBuilder::default() diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index eb51e6d01..9bbebd56e 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -275,12 +275,12 @@ pub(crate) mod tests { let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let db_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let announce_handler = Arc::new(AnnounceHandler::new( &config.core, &whitelist_authorization, &in_memory_torrent_repository, - &db_torrent_repository, + &db_downloads_metric_repository, )); let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository)); diff --git a/src/app.rs b/src/app.rs index 571e034f5..ac51239fc 100644 --- a/src/app.rs +++ b/src/app.rs @@ -143,7 +143,7 @@ async fn load_torrent_metrics(config: &Configuration, app_container: &Arc Date: Tue, 27 May 2025 14:45:40 +0100 Subject: [PATCH 1139/1297] refactor: [#1541] create folder for mod More submods will be included inside. --- packages/tracker-core/src/statistics/mod.rs | 2 +- .../src/statistics/{persisted_metrics.rs => persisted/mod.rs} | 0 packages/tracker-core/tests/common/test_env.rs | 2 +- src/app.rs | 2 +- 4 files changed, 3 insertions(+), 3 deletions(-) rename packages/tracker-core/src/statistics/{persisted_metrics.rs => persisted/mod.rs} (100%) diff --git a/packages/tracker-core/src/statistics/mod.rs b/packages/tracker-core/src/statistics/mod.rs index 89d6b79d5..ff8187379 100644 --- a/packages/tracker-core/src/statistics/mod.rs +++ b/packages/tracker-core/src/statistics/mod.rs @@ -1,6 +1,6 @@ pub mod event; pub mod metrics; -pub mod persisted_metrics; +pub mod persisted; pub mod repository; use metrics::Metrics; diff --git a/packages/tracker-core/src/statistics/persisted_metrics.rs b/packages/tracker-core/src/statistics/persisted/mod.rs similarity index 100% rename from packages/tracker-core/src/statistics/persisted_metrics.rs rename to packages/tracker-core/src/statistics/persisted/mod.rs diff --git a/packages/tracker-core/tests/common/test_env.rs b/packages/tracker-core/tests/common/test_env.rs index 88b363234..2aafbbbad 100644 --- a/packages/tracker-core/tests/common/test_env.rs +++ b/packages/tracker-core/tests/common/test_env.rs @@ -5,7 +5,7 @@ use aquatic_udp_protocol::AnnounceEvent; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::PeersWanted; use bittorrent_tracker_core::container::TrackerCoreContainer; -use bittorrent_tracker_core::statistics::persisted_metrics::load_persisted_metrics; +use bittorrent_tracker_core::statistics::persisted::load_persisted_metrics; use tokio::task::yield_now; use torrust_tracker_configuration::Core; use torrust_tracker_metrics::label::LabelSet; diff --git a/src/app.rs b/src/app.rs index ac51239fc..c31281829 100644 --- a/src/app.rs +++ b/src/app.rs @@ -141,7 +141,7 @@ fn load_torrents_from_database(config: &Configuration, app_container: &Arc) { if config.core.tracker_policy.persistent_torrent_completed_stat { - bittorrent_tracker_core::statistics::persisted_metrics::load_persisted_metrics( + bittorrent_tracker_core::statistics::persisted::load_persisted_metrics( &app_container.tracker_core_container.stats_repository, &app_container.tracker_core_container.db_downloads_metric_repository, CurrentClock::now(), From fdbea0aa85dcef20561e7e363232eea00e3d4f6b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 May 2025 14:47:32 +0100 Subject: [PATCH 1140/1297] refactor: [#1541] rename mod --- packages/axum-http-tracker-server/src/v1/handlers/announce.rs | 2 +- packages/http-tracker-core/benches/helpers/util.rs | 2 +- packages/http-tracker-core/src/services/announce.rs | 2 +- packages/http-tracker-core/src/services/scrape.rs | 2 +- packages/tracker-core/src/announce_handler.rs | 2 +- packages/tracker-core/src/container.rs | 2 +- packages/tracker-core/src/statistics/event/handler.rs | 2 +- packages/tracker-core/src/statistics/event/listener.rs | 2 +- packages/tracker-core/src/statistics/persisted/mod.rs | 2 +- packages/tracker-core/src/test_helpers.rs | 2 +- packages/tracker-core/src/torrent/manager.rs | 2 +- .../src/torrent/repository/{persisted.rs => downloads.rs} | 0 packages/tracker-core/src/torrent/repository/mod.rs | 2 +- packages/udp-tracker-server/src/handlers/announce.rs | 2 +- packages/udp-tracker-server/src/handlers/mod.rs | 2 +- 15 files changed, 14 insertions(+), 14 deletions(-) rename packages/tracker-core/src/torrent/repository/{persisted.rs => downloads.rs} (100%) diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 108ebb33f..68e0825f4 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -120,7 +120,7 @@ mod tests { use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabaseDownloadsMetricRepository; + use bittorrent_tracker_core::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::Configuration; diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 06c20543e..2798203ae 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -15,7 +15,7 @@ use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemor use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_tracker_core::torrent::repository::persisted::DatabaseDownloadsMetricRepository; +use bittorrent_tracker_core::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 7831324f0..7f3e553e4 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -213,7 +213,7 @@ mod tests { use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabaseDownloadsMetricRepository; + use bittorrent_tracker_core::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::{Configuration, Core}; diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 0261626a9..f10f00732 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -177,7 +177,7 @@ mod tests { use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabaseDownloadsMetricRepository; + use bittorrent_tracker_core::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 847ddd1af..9a1c92efa 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -99,7 +99,7 @@ use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; use super::torrent::repository::in_memory::InMemoryTorrentRepository; -use super::torrent::repository::persisted::DatabaseDownloadsMetricRepository; +use super::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use crate::error::AnnounceError; use crate::whitelist::authorization::WhitelistAuthorization; diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs index 4dd795e7a..b2bcdebb3 100644 --- a/packages/tracker-core/src/container.rs +++ b/packages/tracker-core/src/container.rs @@ -13,7 +13,7 @@ use crate::databases::Database; use crate::scrape_handler::ScrapeHandler; use crate::torrent::manager::TorrentsManager; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::torrent::repository::persisted::DatabaseDownloadsMetricRepository; +use crate::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use crate::whitelist::authorization::WhitelistAuthorization; use crate::whitelist::manager::WhitelistManager; use crate::whitelist::repository::in_memory::InMemoryWhitelist; diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs index 82c56abce..028f32030 100644 --- a/packages/tracker-core/src/statistics/event/handler.rs +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -7,7 +7,7 @@ use torrust_tracker_torrent_repository::event::Event; use crate::statistics::repository::Repository; use crate::statistics::TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL; -use crate::torrent::repository::persisted::DatabaseDownloadsMetricRepository; +use crate::torrent::repository::downloads::DatabaseDownloadsMetricRepository; pub async fn handle_event( event: Event, diff --git a/packages/tracker-core/src/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs index f0d8cb7f1..23b6e648a 100644 --- a/packages/tracker-core/src/statistics/event/listener.rs +++ b/packages/tracker-core/src/statistics/event/listener.rs @@ -7,7 +7,7 @@ use torrust_tracker_torrent_repository::event::receiver::Receiver; use super::handler::handle_event; use crate::statistics::repository::Repository; -use crate::torrent::repository::persisted::DatabaseDownloadsMetricRepository; +use crate::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use crate::{CurrentClock, TRACKER_CORE_LOG_TARGET}; #[must_use] diff --git a/packages/tracker-core/src/statistics/persisted/mod.rs b/packages/tracker-core/src/statistics/persisted/mod.rs index 55ec91b10..4475f9647 100644 --- a/packages/tracker-core/src/statistics/persisted/mod.rs +++ b/packages/tracker-core/src/statistics/persisted/mod.rs @@ -8,7 +8,7 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::repository::Repository; use super::TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL; use crate::databases; -use crate::torrent::repository::persisted::DatabaseDownloadsMetricRepository; +use crate::torrent::repository::downloads::DatabaseDownloadsMetricRepository; /// Loads persisted metrics from the database and sets them in the stats repository. /// diff --git a/packages/tracker-core/src/test_helpers.rs b/packages/tracker-core/src/test_helpers.rs index f8b79e4db..c10d3dd3e 100644 --- a/packages/tracker-core/src/test_helpers.rs +++ b/packages/tracker-core/src/test_helpers.rs @@ -20,7 +20,7 @@ pub(crate) mod tests { use crate::databases::setup::initialize_database; use crate::scrape_handler::ScrapeHandler; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::torrent::repository::persisted::DatabaseDownloadsMetricRepository; + use crate::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use crate::whitelist::repository::in_memory::InMemoryWhitelist; use crate::whitelist::{self}; diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index e18e19ce0..f86e9442e 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -7,7 +7,7 @@ use torrust_tracker_configuration::Core; use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::repository::in_memory::InMemoryTorrentRepository; -use super::repository::persisted::DatabaseDownloadsMetricRepository; +use super::repository::downloads::DatabaseDownloadsMetricRepository; use crate::{databases, CurrentClock}; /// The `TorrentsManager` is responsible for managing torrent entries by diff --git a/packages/tracker-core/src/torrent/repository/persisted.rs b/packages/tracker-core/src/torrent/repository/downloads.rs similarity index 100% rename from packages/tracker-core/src/torrent/repository/persisted.rs rename to packages/tracker-core/src/torrent/repository/downloads.rs diff --git a/packages/tracker-core/src/torrent/repository/mod.rs b/packages/tracker-core/src/torrent/repository/mod.rs index ae789e5e9..fd0382025 100644 --- a/packages/tracker-core/src/torrent/repository/mod.rs +++ b/packages/tracker-core/src/torrent/repository/mod.rs @@ -1,3 +1,3 @@ //! Torrent repository implementations. pub mod in_memory; -pub mod persisted; +pub mod downloads; diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 38e136a12..555d047d0 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -836,7 +836,7 @@ mod tests { use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabaseDownloadsMetricRepository; + use bittorrent_tracker_core::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 9bbebd56e..3957f63c3 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -212,7 +212,7 @@ pub(crate) mod tests { use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::persisted::DatabaseDownloadsMetricRepository; + use bittorrent_tracker_core::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; From 7e27d31bcfff7b5653adc6df99e9b87caf8eed59 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 May 2025 14:52:30 +0100 Subject: [PATCH 1141/1297] refactor: [#1541] move mod --- packages/axum-http-tracker-server/src/v1/handlers/announce.rs | 2 +- packages/http-tracker-core/benches/helpers/util.rs | 2 +- packages/http-tracker-core/src/services/announce.rs | 2 +- packages/http-tracker-core/src/services/scrape.rs | 2 +- packages/tracker-core/src/announce_handler.rs | 2 +- packages/tracker-core/src/container.rs | 2 +- packages/tracker-core/src/statistics/event/handler.rs | 2 +- packages/tracker-core/src/statistics/event/listener.rs | 2 +- .../{torrent/repository => statistics/persisted}/downloads.rs | 0 packages/tracker-core/src/statistics/persisted/mod.rs | 4 +++- packages/tracker-core/src/test_helpers.rs | 2 +- packages/tracker-core/src/torrent/manager.rs | 2 +- packages/tracker-core/src/torrent/repository/mod.rs | 1 - packages/udp-tracker-server/src/handlers/announce.rs | 2 +- packages/udp-tracker-server/src/handlers/mod.rs | 2 +- 15 files changed, 15 insertions(+), 14 deletions(-) rename packages/tracker-core/src/{torrent/repository => statistics/persisted}/downloads.rs (100%) diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 68e0825f4..16ff83f81 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -119,8 +119,8 @@ mod tests { use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::Configuration; diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 2798203ae..414d3b40e 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -14,8 +14,8 @@ use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::setup::initialize_database; +use bittorrent_tracker_core::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_tracker_core::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 7f3e553e4..23d589bce 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -212,8 +212,8 @@ mod tests { use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository; use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use torrust_tracker_configuration::{Configuration, Core}; diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index f10f00732..1445ffcfe 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -176,8 +176,8 @@ mod tests { use bittorrent_tracker_core::authentication::service::AuthenticationService; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; + use bittorrent_tracker_core::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 9a1c92efa..501993ad5 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -99,8 +99,8 @@ use torrust_tracker_primitives::core::AnnounceData; use torrust_tracker_primitives::peer; use super::torrent::repository::in_memory::InMemoryTorrentRepository; -use super::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use crate::error::AnnounceError; +use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use crate::whitelist::authorization::WhitelistAuthorization; /// Handles `announce` requests from `BitTorrent` clients. diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs index b2bcdebb3..02af67118 100644 --- a/packages/tracker-core/src/container.rs +++ b/packages/tracker-core/src/container.rs @@ -11,9 +11,9 @@ use crate::authentication::service::AuthenticationService; use crate::databases::setup::initialize_database; use crate::databases::Database; use crate::scrape_handler::ScrapeHandler; +use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use crate::torrent::manager::TorrentsManager; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; -use crate::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use crate::whitelist::authorization::WhitelistAuthorization; use crate::whitelist::manager::WhitelistManager; use crate::whitelist::repository::in_memory::InMemoryWhitelist; diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs index 028f32030..0001b43ce 100644 --- a/packages/tracker-core/src/statistics/event/handler.rs +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -5,9 +5,9 @@ use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_torrent_repository::event::Event; +use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use crate::statistics::repository::Repository; use crate::statistics::TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL; -use crate::torrent::repository::downloads::DatabaseDownloadsMetricRepository; pub async fn handle_event( event: Event, diff --git a/packages/tracker-core/src/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs index 23b6e648a..2702aa858 100644 --- a/packages/tracker-core/src/statistics/event/listener.rs +++ b/packages/tracker-core/src/statistics/event/listener.rs @@ -6,8 +6,8 @@ use torrust_tracker_events::receiver::RecvError; use torrust_tracker_torrent_repository::event::receiver::Receiver; use super::handler::handle_event; +use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use crate::statistics::repository::Repository; -use crate::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use crate::{CurrentClock, TRACKER_CORE_LOG_TARGET}; #[must_use] diff --git a/packages/tracker-core/src/torrent/repository/downloads.rs b/packages/tracker-core/src/statistics/persisted/downloads.rs similarity index 100% rename from packages/tracker-core/src/torrent/repository/downloads.rs rename to packages/tracker-core/src/statistics/persisted/downloads.rs diff --git a/packages/tracker-core/src/statistics/persisted/mod.rs b/packages/tracker-core/src/statistics/persisted/mod.rs index 4475f9647..f675b4ebc 100644 --- a/packages/tracker-core/src/statistics/persisted/mod.rs +++ b/packages/tracker-core/src/statistics/persisted/mod.rs @@ -1,3 +1,5 @@ +pub mod downloads; + use std::sync::Arc; use thiserror::Error; @@ -8,7 +10,7 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::repository::Repository; use super::TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL; use crate::databases; -use crate::torrent::repository::downloads::DatabaseDownloadsMetricRepository; +use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; /// Loads persisted metrics from the database and sets them in the stats repository. /// diff --git a/packages/tracker-core/src/test_helpers.rs b/packages/tracker-core/src/test_helpers.rs index c10d3dd3e..62649cd22 100644 --- a/packages/tracker-core/src/test_helpers.rs +++ b/packages/tracker-core/src/test_helpers.rs @@ -19,8 +19,8 @@ pub(crate) mod tests { use crate::announce_handler::AnnounceHandler; use crate::databases::setup::initialize_database; use crate::scrape_handler::ScrapeHandler; + use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use crate::torrent::repository::in_memory::InMemoryTorrentRepository; - use crate::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use crate::whitelist::repository::in_memory::InMemoryWhitelist; use crate::whitelist::{self}; diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index f86e9442e..b7c6d5117 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -7,7 +7,7 @@ use torrust_tracker_configuration::Core; use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::repository::in_memory::InMemoryTorrentRepository; -use super::repository::downloads::DatabaseDownloadsMetricRepository; +use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use crate::{databases, CurrentClock}; /// The `TorrentsManager` is responsible for managing torrent entries by diff --git a/packages/tracker-core/src/torrent/repository/mod.rs b/packages/tracker-core/src/torrent/repository/mod.rs index fd0382025..d8325dec5 100644 --- a/packages/tracker-core/src/torrent/repository/mod.rs +++ b/packages/tracker-core/src/torrent/repository/mod.rs @@ -1,3 +1,2 @@ //! Torrent repository implementations. pub mod in_memory; -pub mod downloads; diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 555d047d0..2fc3f6e63 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -835,8 +835,8 @@ mod tests { use aquatic_udp_protocol::{InfoHash as AquaticInfoHash, PeerId as AquaticPeerId}; use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::databases::setup::initialize_database; + use bittorrent_tracker_core::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use bittorrent_udp_tracker_core::connection_cookie::{gen_remote_fingerprint, make}; diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 3957f63c3..df550ab72 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -211,8 +211,8 @@ pub(crate) mod tests { use bittorrent_tracker_core::announce_handler::AnnounceHandler; use bittorrent_tracker_core::databases::setup::initialize_database; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; + use bittorrent_tracker_core::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::torrent::repository::downloads::DatabaseDownloadsMetricRepository; use bittorrent_tracker_core::whitelist; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; From 0508a6a11e6050715a712005384c65659bfecf4e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 May 2025 15:04:51 +0100 Subject: [PATCH 1142/1297] refactor: [#1541] rename methods --- packages/tracker-core/src/announce_handler.rs | 2 +- .../tracker-core/src/databases/driver/mod.rs | 28 +++++------ .../src/databases/driver/mysql.rs | 14 +++--- .../src/databases/driver/sqlite.rs | 14 +++--- packages/tracker-core/src/databases/mod.rs | 14 +++--- .../src/statistics/event/handler.rs | 4 +- .../src/statistics/persisted/downloads.rs | 46 +++++++++---------- .../src/statistics/persisted/mod.rs | 2 +- packages/tracker-core/src/torrent/manager.rs | 12 ++--- 9 files changed, 68 insertions(+), 68 deletions(-) diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index 501993ad5..a6614361a 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -169,7 +169,7 @@ impl AnnounceHandler { // downloads across all torrents. The in-memory metric will count only // the number of downloads during the current tracker uptime. let opt_persistent_torrent = if self.config.tracker_policy.persistent_torrent_completed_stat { - self.db_downloads_metric_repository.load(info_hash)? + self.db_downloads_metric_repository.load_torrent_downloads(info_hash)? } else { None }; diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index e8f0ecbfb..6c849bb70 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -169,9 +169,9 @@ pub(crate) mod tests { let number_of_downloads = 1; - driver.save_persistent_torrent(&infohash, number_of_downloads).unwrap(); + driver.save_torrent_downloads(&infohash, number_of_downloads).unwrap(); - let number_of_downloads = driver.load_persistent_torrent(&infohash).unwrap().unwrap(); + let number_of_downloads = driver.load_torrent_downloads(&infohash).unwrap().unwrap(); assert_eq!(number_of_downloads, 1); } @@ -181,9 +181,9 @@ pub(crate) mod tests { let number_of_downloads = 1; - driver.save_persistent_torrent(&infohash, number_of_downloads).unwrap(); + driver.save_torrent_downloads(&infohash, number_of_downloads).unwrap(); - let torrents = driver.load_persistent_torrents().unwrap(); + let torrents = driver.load_all_torrents_downloads().unwrap(); assert_eq!(torrents.len(), 1); assert_eq!(torrents.get(&infohash), Some(number_of_downloads).as_ref()); @@ -194,11 +194,11 @@ pub(crate) mod tests { let number_of_downloads = 1; - driver.save_persistent_torrent(&infohash, number_of_downloads).unwrap(); + driver.save_torrent_downloads(&infohash, number_of_downloads).unwrap(); - driver.increase_number_of_downloads(&infohash).unwrap(); + driver.increase_downloads_for_torrent(&infohash).unwrap(); - let number_of_downloads = driver.load_persistent_torrent(&infohash).unwrap().unwrap(); + let number_of_downloads = driver.load_torrent_downloads(&infohash).unwrap().unwrap(); assert_eq!(number_of_downloads, 2); } @@ -208,9 +208,9 @@ pub(crate) mod tests { pub fn it_should_save_and_load_the_global_number_of_downloads(driver: &Arc>) { let number_of_downloads = 1; - driver.save_global_number_of_downloads(number_of_downloads).unwrap(); + driver.save_global_downloads(number_of_downloads).unwrap(); - let number_of_downloads = driver.load_global_number_of_downloads().unwrap().unwrap(); + let number_of_downloads = driver.load_global_downloads().unwrap().unwrap(); assert_eq!(number_of_downloads, 1); } @@ -218,9 +218,9 @@ pub(crate) mod tests { pub fn it_should_load_the_global_number_of_downloads(driver: &Arc>) { let number_of_downloads = 1; - driver.save_global_number_of_downloads(number_of_downloads).unwrap(); + driver.save_global_downloads(number_of_downloads).unwrap(); - let number_of_downloads = driver.load_global_number_of_downloads().unwrap().unwrap(); + let number_of_downloads = driver.load_global_downloads().unwrap().unwrap(); assert_eq!(number_of_downloads, 1); } @@ -228,11 +228,11 @@ pub(crate) mod tests { pub fn it_should_increase_the_global_number_of_downloads(driver: &Arc>) { let number_of_downloads = 1; - driver.save_global_number_of_downloads(number_of_downloads).unwrap(); + driver.save_global_downloads(number_of_downloads).unwrap(); - driver.increase_global_number_of_downloads().unwrap(); + driver.increase_global_downloads().unwrap(); - let number_of_downloads = driver.load_global_number_of_downloads().unwrap().unwrap(); + let number_of_downloads = driver.load_global_downloads().unwrap().unwrap(); assert_eq!(number_of_downloads, 2); } diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index bfbc47ebd..ce76ce563 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -146,7 +146,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::load_persistent_torrents`](crate::core::databases::Database::load_persistent_torrents). - fn load_persistent_torrents(&self) -> Result { + fn load_all_torrents_downloads(&self) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let torrents = conn.query_map( @@ -161,7 +161,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::load_persistent_torrent`](crate::core::databases::Database::load_persistent_torrent). - fn load_persistent_torrent(&self, info_hash: &InfoHash) -> Result, Error> { + fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let query = conn.exec_first::( @@ -175,7 +175,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::save_persistent_torrent`](crate::core::databases::Database::save_persistent_torrent). - fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { + fn save_torrent_downloads(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { const COMMAND : &str = "INSERT INTO torrents (info_hash, completed) VALUES (:info_hash_str, :completed) ON DUPLICATE KEY UPDATE completed = VALUES(completed)"; let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -186,7 +186,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::increase_number_of_downloads`](crate::core::databases::Database::increase_number_of_downloads). - fn increase_number_of_downloads(&self, info_hash: &InfoHash) -> Result<(), Error> { + fn increase_downloads_for_torrent(&self, info_hash: &InfoHash) -> Result<(), Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let info_hash_str = info_hash.to_string(); @@ -200,17 +200,17 @@ impl Database for Mysql { } /// Refer to [`databases::Database::load_global_number_of_downloads`](crate::core::databases::Database::load_global_number_of_downloads). - fn load_global_number_of_downloads(&self) -> Result, Error> { + fn load_global_downloads(&self) -> Result, Error> { self.load_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL) } /// Refer to [`databases::Database::save_global_number_of_downloads`](crate::core::databases::Database::save_global_number_of_downloads). - fn save_global_number_of_downloads(&self, downloaded: PersistentTorrent) -> Result<(), Error> { + fn save_global_downloads(&self, downloaded: PersistentTorrent) -> Result<(), Error> { self.save_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL, downloaded) } /// Refer to [`databases::Database::increase_global_number_of_downloads`](crate::core::databases::Database::increase_global_number_of_downloads). - fn increase_global_number_of_downloads(&self) -> Result<(), Error> { + fn increase_global_downloads(&self) -> Result<(), Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let metric_name = TORRENTS_DOWNLOADS_TOTAL; diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs index 91e969233..794f65a4c 100644 --- a/packages/tracker-core/src/databases/driver/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -152,7 +152,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::load_persistent_torrents`](crate::core::databases::Database::load_persistent_torrents). - fn load_persistent_torrents(&self) -> Result { + fn load_all_torrents_downloads(&self) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT info_hash, completed FROM torrents")?; @@ -168,7 +168,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::load_persistent_torrent`](crate::core::databases::Database::load_persistent_torrent). - fn load_persistent_torrent(&self, info_hash: &InfoHash) -> Result, Error> { + fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT completed FROM torrents WHERE info_hash = ?")?; @@ -184,7 +184,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::save_persistent_torrent`](crate::core::databases::Database::save_persistent_torrent). - fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { + fn save_torrent_downloads(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let insert = conn.execute( @@ -203,7 +203,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::increase_number_of_downloads`](crate::core::databases::Database::increase_number_of_downloads). - fn increase_number_of_downloads(&self, info_hash: &InfoHash) -> Result<(), Error> { + fn increase_downloads_for_torrent(&self, info_hash: &InfoHash) -> Result<(), Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let _ = conn.execute( @@ -215,17 +215,17 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::load_global_number_of_downloads`](crate::core::databases::Database::load_global_number_of_downloads). - fn load_global_number_of_downloads(&self) -> Result, Error> { + fn load_global_downloads(&self) -> Result, Error> { self.load_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL) } /// Refer to [`databases::Database::save_global_number_of_downloads`](crate::core::databases::Database::save_global_number_of_downloads). - fn save_global_number_of_downloads(&self, downloaded: PersistentTorrent) -> Result<(), Error> { + fn save_global_downloads(&self, downloaded: PersistentTorrent) -> Result<(), Error> { self.save_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL, downloaded) } /// Refer to [`databases::Database::increase_global_number_of_downloads`](crate::core::databases::Database::increase_global_number_of_downloads). - fn increase_global_number_of_downloads(&self) -> Result<(), Error> { + fn increase_global_downloads(&self) -> Result<(), Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let metric_name = TORRENTS_DOWNLOADS_TOTAL; diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs index a9d6b2a22..b637219ad 100644 --- a/packages/tracker-core/src/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -101,7 +101,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Returns an [`Error`] if the metrics cannot be loaded. - fn load_persistent_torrents(&self) -> Result; + fn load_all_torrents_downloads(&self) -> Result; /// Loads torrent metrics data from the database for one torrent. /// @@ -110,7 +110,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Returns an [`Error`] if the metrics cannot be loaded. - fn load_persistent_torrent(&self, info_hash: &InfoHash) -> Result, Error>; + fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error>; /// Saves torrent metrics data into the database. /// @@ -124,7 +124,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Returns an [`Error`] if the metrics cannot be saved. - fn save_persistent_torrent(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error>; + fn save_torrent_downloads(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error>; /// Increases the number of downloads for a given torrent. /// @@ -140,7 +140,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Returns an [`Error`] if the query failed. - fn increase_number_of_downloads(&self, info_hash: &InfoHash) -> Result<(), Error>; + fn increase_downloads_for_torrent(&self, info_hash: &InfoHash) -> Result<(), Error>; /// Loads the total number of downloads for all torrents from the database. /// @@ -149,7 +149,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Returns an [`Error`] if the total downloads cannot be loaded. - fn load_global_number_of_downloads(&self) -> Result, Error>; + fn load_global_downloads(&self) -> Result, Error>; /// Saves the total number of downloads for all torrents into the database. /// @@ -163,7 +163,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Returns an [`Error`] if the total downloads cannot be saved. - fn save_global_number_of_downloads(&self, downloaded: PersistentTorrent) -> Result<(), Error>; + fn save_global_downloads(&self, downloaded: PersistentTorrent) -> Result<(), Error>; /// Increases the total number of downloads for all torrents. /// @@ -172,7 +172,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Returns an [`Error`] if the query failed. - fn increase_global_number_of_downloads(&self) -> Result<(), Error>; + fn increase_global_downloads(&self) -> Result<(), Error>; // Whitelist diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs index 0001b43ce..0909dc184 100644 --- a/packages/tracker-core/src/statistics/event/handler.rs +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -53,7 +53,7 @@ pub async fn handle_event( if persistent_torrent_completed_stat { // Increment the number of downloads for the torrent in the database - match db_downloads_metric_repository.increase_number_of_downloads(&info_hash) { + match db_downloads_metric_repository.increase_downloads_for_torrent(&info_hash) { Ok(()) => { tracing::debug!(info_hash = ?info_hash, "Number of torrent downloads increased"); } @@ -63,7 +63,7 @@ pub async fn handle_event( } // Increment the global number of downloads (for all torrents) in the database - match db_downloads_metric_repository.increase_global_number_of_downloads() { + match db_downloads_metric_repository.increase_global_downloads() { Ok(()) => { tracing::debug!("Global number of downloads increased"); } diff --git a/packages/tracker-core/src/statistics/persisted/downloads.rs b/packages/tracker-core/src/statistics/persisted/downloads.rs index d6c6ce263..7edaf73d8 100644 --- a/packages/tracker-core/src/statistics/persisted/downloads.rs +++ b/packages/tracker-core/src/statistics/persisted/downloads.rs @@ -60,12 +60,12 @@ impl DatabaseDownloadsMetricRepository { /// # Errors /// /// Returns an [`Error`] if the database operation fails. - pub(crate) fn increase_number_of_downloads(&self, info_hash: &InfoHash) -> Result<(), Error> { - let torrent = self.load(info_hash)?; + pub(crate) fn increase_downloads_for_torrent(&self, info_hash: &InfoHash) -> Result<(), Error> { + let torrent = self.load_torrent_downloads(info_hash)?; match torrent { - Some(_number_of_downloads) => self.database.increase_number_of_downloads(info_hash), - None => self.save(info_hash, 1), + Some(_number_of_downloads) => self.database.increase_downloads_for_torrent(info_hash), + None => self.save_torrent_downloads(info_hash, 1), } } @@ -77,8 +77,8 @@ impl DatabaseDownloadsMetricRepository { /// # Errors /// /// Returns an [`Error`] if the underlying database query fails. - pub(crate) fn load_all(&self) -> Result { - self.database.load_persistent_torrents() + pub(crate) fn load_all_torrents_downloads(&self) -> Result { + self.database.load_all_torrents_downloads() } /// Loads one persistent torrent metrics from the database. @@ -89,8 +89,8 @@ impl DatabaseDownloadsMetricRepository { /// # Errors /// /// Returns an [`Error`] if the underlying database query fails. - pub(crate) fn load(&self, info_hash: &InfoHash) -> Result, Error> { - self.database.load_persistent_torrent(info_hash) + pub(crate) fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error> { + self.database.load_torrent_downloads(info_hash) } /// Saves the persistent torrent metric into the database. @@ -106,8 +106,8 @@ impl DatabaseDownloadsMetricRepository { /// # Errors /// /// Returns an [`Error`] if the database operation fails. - pub(crate) fn save(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error> { - self.database.save_persistent_torrent(info_hash, downloaded) + pub(crate) fn save_torrent_downloads(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error> { + self.database.save_torrent_downloads(info_hash, downloaded) } // Aggregate Metrics @@ -119,12 +119,12 @@ impl DatabaseDownloadsMetricRepository { /// # Errors /// /// Returns an [`Error`] if the database operation fails. - pub(crate) fn increase_global_number_of_downloads(&self) -> Result<(), Error> { - let torrent = self.database.load_global_number_of_downloads()?; + pub(crate) fn increase_global_downloads(&self) -> Result<(), Error> { + let torrent = self.database.load_global_downloads()?; match torrent { - Some(_number_of_downloads) => self.database.increase_global_number_of_downloads(), - None => self.database.save_global_number_of_downloads(1), + Some(_number_of_downloads) => self.database.increase_global_downloads(), + None => self.database.save_global_downloads(1), } } @@ -133,8 +133,8 @@ impl DatabaseDownloadsMetricRepository { /// # Errors /// /// Returns an [`Error`] if the underlying database query fails. - pub(crate) fn load_global_number_of_downloads(&self) -> Result, Error> { - self.database.load_global_number_of_downloads() + pub(crate) fn load_global_downloads(&self) -> Result, Error> { + self.database.load_global_downloads() } } @@ -159,9 +159,9 @@ mod tests { let infohash = sample_info_hash(); - repository.save(&infohash, 1).unwrap(); + repository.save_torrent_downloads(&infohash, 1).unwrap(); - let torrents = repository.load_all().unwrap(); + let torrents = repository.load_all_torrents_downloads().unwrap(); assert_eq!(torrents.get(&infohash), Some(1).as_ref()); } @@ -172,9 +172,9 @@ mod tests { let infohash = sample_info_hash(); - repository.increase_number_of_downloads(&infohash).unwrap(); + repository.increase_downloads_for_torrent(&infohash).unwrap(); - let torrents = repository.load_all().unwrap(); + let torrents = repository.load_all_torrents_downloads().unwrap(); assert_eq!(torrents.get(&infohash), Some(1).as_ref()); } @@ -186,10 +186,10 @@ mod tests { let infohash_one = sample_info_hash_one(); let infohash_two = sample_info_hash_two(); - repository.save(&infohash_one, 1).unwrap(); - repository.save(&infohash_two, 2).unwrap(); + repository.save_torrent_downloads(&infohash_one, 1).unwrap(); + repository.save_torrent_downloads(&infohash_two, 2).unwrap(); - let torrents = repository.load_all().unwrap(); + let torrents = repository.load_all_torrents_downloads().unwrap(); let mut expected_torrents = PersistentTorrents::new(); expected_torrents.insert(infohash_one, 1); diff --git a/packages/tracker-core/src/statistics/persisted/mod.rs b/packages/tracker-core/src/statistics/persisted/mod.rs index f675b4ebc..86c28370d 100644 --- a/packages/tracker-core/src/statistics/persisted/mod.rs +++ b/packages/tracker-core/src/statistics/persisted/mod.rs @@ -23,7 +23,7 @@ pub async fn load_persisted_metrics( db_downloads_metric_repository: &Arc, now: DurationSinceUnixEpoch, ) -> Result<(), Error> { - if let Some(downloads) = db_downloads_metric_repository.load_global_number_of_downloads()? { + if let Some(downloads) = db_downloads_metric_repository.load_global_downloads()? { stats_repository .set_counter( &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index b7c6d5117..766fa5c4a 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -29,8 +29,7 @@ pub struct TorrentsManager { /// The in-memory torrents repository. in_memory_torrent_repository: Arc, - /// The persistent torrents repository. - #[allow(dead_code)] + /// The download metrics repository. db_downloads_metric_repository: Arc, } @@ -72,9 +71,7 @@ impl TorrentsManager { /// Returns a `databases::error::Error` if unable to load the persistent /// torrent data. pub fn load_torrents_from_database(&self) -> Result<(), databases::error::Error> { - let persistent_torrents = self.db_downloads_metric_repository.load_all()?; - - println!("Loaded {} persistent torrents from the database", persistent_torrents.len()); + let persistent_torrents = self.db_downloads_metric_repository.load_all_torrents_downloads()?; self.in_memory_torrent_repository.import_persistent(&persistent_torrents); @@ -197,7 +194,10 @@ mod tests { let infohash = sample_info_hash(); - services.database_persistent_torrent_repository.save(&infohash, 1).unwrap(); + services + .database_persistent_torrent_repository + .save_torrent_downloads(&infohash, 1) + .unwrap(); torrents_manager.load_torrents_from_database().unwrap(); From a5a80b5de923957eaee81c474110ea443b2cd5a6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 May 2025 15:09:40 +0100 Subject: [PATCH 1143/1297] refactor: [#1541] rename type alias PersistentTorrent to NumberOfDownloads --- packages/primitives/src/lib.rs | 4 ++-- .../src/repository/dash_map_mutex_std.rs | 4 ++-- .../src/repository/mod.rs | 6 +++--- .../src/repository/rw_lock_std.rs | 4 ++-- .../src/repository/rw_lock_std_mutex_std.rs | 4 ++-- .../src/repository/rw_lock_std_mutex_tokio.rs | 4 ++-- .../src/repository/rw_lock_tokio.rs | 4 ++-- .../src/repository/rw_lock_tokio_mutex_std.rs | 4 ++-- .../src/repository/rw_lock_tokio_mutex_tokio.rs | 4 ++-- .../src/repository/skip_map_mutex_std.rs | 8 ++++---- .../tests/common/repo.rs | 4 ++-- packages/torrent-repository/src/swarms.rs | 4 ++-- packages/tracker-core/src/databases/driver/mysql.rs | 12 ++++++------ packages/tracker-core/src/databases/driver/sqlite.rs | 12 ++++++------ packages/tracker-core/src/databases/mod.rs | 8 ++++---- .../src/statistics/persisted/downloads.rs | 6 +++--- .../tracker-core/src/torrent/repository/in_memory.rs | 4 ++-- 17 files changed, 48 insertions(+), 48 deletions(-) diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index c901e5276..b04991eb8 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -18,5 +18,5 @@ use bittorrent_primitives::info_hash::InfoHash; /// Duration since the Unix Epoch. pub type DurationSinceUnixEpoch = Duration; -pub type PersistentTorrent = u32; -pub type PersistentTorrents = BTreeMap; +pub type NumberOfDownloads = u32; +pub type PersistentTorrents = BTreeMap; diff --git a/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs index d4a84caa0..c0ef455d4 100644 --- a/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs @@ -5,7 +5,7 @@ use dashmap::DashMap; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -22,7 +22,7 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { // todo: load persistent torrent data if provided if let Some(entry) = self.torrents.get(info_hash) { diff --git a/packages/torrent-repository-benchmarking/src/repository/mod.rs b/packages/torrent-repository-benchmarking/src/repository/mod.rs index 9284ff6e6..2ad7a3927 100644 --- a/packages/torrent-repository-benchmarking/src/repository/mod.rs +++ b/packages/torrent-repository-benchmarking/src/repository/mod.rs @@ -2,7 +2,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; pub mod dash_map_mutex_std; pub mod rw_lock_std; @@ -23,7 +23,7 @@ pub trait Repository: Debug + Default + Sized + 'static { fn remove(&self, key: &InfoHash) -> Option; fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); fn remove_peerless_torrents(&self, policy: &TrackerPolicy); - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool; + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool; fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option; } @@ -40,7 +40,7 @@ pub trait RepositoryAsync: Debug + Default + Sized + 'static { &self, info_hash: &InfoHash, peer: &peer::Peer, - opt_persistent_torrent: Option, + opt_persistent_torrent: Option, ) -> impl std::future::Future + Send; fn get_swarm_metadata(&self, info_hash: &InfoHash) -> impl std::future::Future> + Send; } diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs index d190718af..c0e4d5cf5 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs @@ -2,7 +2,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -45,7 +45,7 @@ impl Repository for TorrentsRwLockStd where EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { // todo: load persistent torrent data if provided let mut db = self.get_torrents_mut(); diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs index 1764b94e8..30aabc799 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs @@ -4,7 +4,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -32,7 +32,7 @@ where EntryMutexStd: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { // todo: load persistent torrent data if provided let maybe_entry = self.get_torrents().get(info_hash).cloned(); diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs index 116c1ff87..f56322654 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs @@ -8,7 +8,7 @@ use futures::{Future, FutureExt}; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; @@ -40,7 +40,7 @@ where &self, info_hash: &InfoHash, peer: &peer::Peer, - _opt_persistent_torrent: Option, + _opt_persistent_torrent: Option, ) -> bool { // todo: load persistent torrent data if provided diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs index 53838023d..091ff303d 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs @@ -2,7 +2,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; @@ -50,7 +50,7 @@ where &self, info_hash: &InfoHash, peer: &peer::Peer, - _opt_persistent_torrent: Option, + _opt_persistent_torrent: Option, ) -> bool { // todo: load persistent torrent data if provided diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs index eb7e300fd..542ad7f0a 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs @@ -4,7 +4,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; @@ -38,7 +38,7 @@ where &self, info_hash: &InfoHash, peer: &peer::Peer, - _opt_persistent_torrent: Option, + _opt_persistent_torrent: Option, ) -> bool { // todo: load persistent torrent data if provided diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs index c8ebaf4d6..2551972b3 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -4,7 +4,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; @@ -38,7 +38,7 @@ where &self, info_hash: &InfoHash, peer: &peer::Peer, - _opt_persistent_torrent: Option, + _opt_persistent_torrent: Option, ) -> bool { // todo: load persistent torrent data if provided diff --git a/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs index 8a15a9442..7d141facb 100644 --- a/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs @@ -5,7 +5,7 @@ use crossbeam_skiplist::SkipMap; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -38,7 +38,7 @@ where /// /// Returns `true` if the number of downloads was increased because the peer /// completed the download. - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, opt_persistent_torrent: Option) -> bool { if let Some(existing_entry) = self.torrents.get(info_hash) { existing_entry.value().upsert_peer(peer) } else { @@ -146,7 +146,7 @@ where EntryRwLockParkingLot: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { // todo: load persistent torrent data if provided let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); @@ -239,7 +239,7 @@ where EntryMutexParkingLot: EntrySync, EntrySingle: Entry, { - fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { + fn upsert_peer(&self, info_hash: &InfoHash, peer: &peer::Peer, _opt_persistent_torrent: Option) -> bool { // todo: load persistent torrent data if provided let entry = self.torrents.get_or_insert(*info_hash, Arc::default()); diff --git a/packages/torrent-repository-benchmarking/tests/common/repo.rs b/packages/torrent-repository-benchmarking/tests/common/repo.rs index 6c5c6ff77..3371e3c64 100644 --- a/packages/torrent-repository-benchmarking/tests/common/repo.rs +++ b/packages/torrent-repository-benchmarking/tests/common/repo.rs @@ -2,7 +2,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; use torrust_tracker_torrent_repository_benchmarking::repository::{Repository as _, RepositoryAsync as _}; use torrust_tracker_torrent_repository_benchmarking::{ EntrySingle, TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, @@ -29,7 +29,7 @@ impl Repo { &self, info_hash: &InfoHash, peer: &peer::Peer, - opt_persistent_torrent: Option, + opt_persistent_torrent: Option, ) -> bool { match self { Repo::RwLockStd(repo) => repo.upsert_peer(info_hash, peer, opt_persistent_torrent), diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 1504ac1f4..9c1f3d9b2 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -7,7 +7,7 @@ use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; use crate::event::sender::Sender; use crate::event::Event; @@ -53,7 +53,7 @@ impl Swarms { &self, info_hash: &InfoHash, peer: &peer::Peer, - opt_persistent_torrent: Option, + opt_persistent_torrent: Option, ) -> Result<(), Error> { let swarm_handle = match self.swarms.get(info_hash) { None => { diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index ce76ce563..a5dfc50e5 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -13,7 +13,7 @@ use r2d2::Pool; use r2d2_mysql::mysql::prelude::Queryable; use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MySqlConnectionManager; -use torrust_tracker_primitives::{PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{NumberOfDownloads, PersistentTorrents}; use super::{Database, Driver, Error, TORRENTS_DOWNLOADS_TOTAL}; use crate::authentication::key::AUTH_KEY_LENGTH; @@ -47,7 +47,7 @@ impl Mysql { Ok(Self { pool }) } - fn load_torrent_aggregate_metric(&self, metric_name: &str) -> Result, Error> { + fn load_torrent_aggregate_metric(&self, metric_name: &str) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let query = conn.exec_first::( @@ -60,7 +60,7 @@ impl Mysql { Ok(persistent_torrent) } - fn save_torrent_aggregate_metric(&self, metric_name: &str, completed: PersistentTorrent) -> Result<(), Error> { + fn save_torrent_aggregate_metric(&self, metric_name: &str, completed: NumberOfDownloads) -> Result<(), Error> { const COMMAND : &str = "INSERT INTO torrent_aggregate_metrics (metric_name, value) VALUES (:metric_name, :completed) ON DUPLICATE KEY UPDATE value = VALUES(value)"; let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; @@ -161,7 +161,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::load_persistent_torrent`](crate::core::databases::Database::load_persistent_torrent). - fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error> { + fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error> { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let query = conn.exec_first::( @@ -200,12 +200,12 @@ impl Database for Mysql { } /// Refer to [`databases::Database::load_global_number_of_downloads`](crate::core::databases::Database::load_global_number_of_downloads). - fn load_global_downloads(&self) -> Result, Error> { + fn load_global_downloads(&self) -> Result, Error> { self.load_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL) } /// Refer to [`databases::Database::save_global_number_of_downloads`](crate::core::databases::Database::save_global_number_of_downloads). - fn save_global_downloads(&self, downloaded: PersistentTorrent) -> Result<(), Error> { + fn save_global_downloads(&self, downloaded: NumberOfDownloads) -> Result<(), Error> { self.save_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL, downloaded) } diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs index 794f65a4c..d4b6a82c6 100644 --- a/packages/tracker-core/src/databases/driver/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -13,7 +13,7 @@ use r2d2::Pool; use r2d2_sqlite::rusqlite::params; use r2d2_sqlite::rusqlite::types::Null; use r2d2_sqlite::SqliteConnectionManager; -use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; use super::{Database, Driver, Error, TORRENTS_DOWNLOADS_TOTAL}; use crate::authentication::{self, Key}; @@ -50,7 +50,7 @@ impl Sqlite { Ok(Self { pool }) } - fn load_torrent_aggregate_metric(&self, metric_name: &str) -> Result, Error> { + fn load_torrent_aggregate_metric(&self, metric_name: &str) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT value FROM torrent_aggregate_metrics WHERE metric_name = ?")?; @@ -65,7 +65,7 @@ impl Sqlite { })) } - fn save_torrent_aggregate_metric(&self, metric_name: &str, completed: PersistentTorrent) -> Result<(), Error> { + fn save_torrent_aggregate_metric(&self, metric_name: &str, completed: NumberOfDownloads) -> Result<(), Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let insert = conn.execute( @@ -168,7 +168,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::load_persistent_torrent`](crate::core::databases::Database::load_persistent_torrent). - fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error> { + fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error> { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT completed FROM torrents WHERE info_hash = ?")?; @@ -215,12 +215,12 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::load_global_number_of_downloads`](crate::core::databases::Database::load_global_number_of_downloads). - fn load_global_downloads(&self) -> Result, Error> { + fn load_global_downloads(&self) -> Result, Error> { self.load_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL) } /// Refer to [`databases::Database::save_global_number_of_downloads`](crate::core::databases::Database::save_global_number_of_downloads). - fn save_global_downloads(&self, downloaded: PersistentTorrent) -> Result<(), Error> { + fn save_global_downloads(&self, downloaded: NumberOfDownloads) -> Result<(), Error> { self.save_torrent_aggregate_metric(TORRENTS_DOWNLOADS_TOTAL, downloaded) } diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs index b637219ad..6147873f6 100644 --- a/packages/tracker-core/src/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -52,7 +52,7 @@ pub mod setup; use bittorrent_primitives::info_hash::InfoHash; use mockall::automock; -use torrust_tracker_primitives::{PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{NumberOfDownloads, PersistentTorrents}; use self::error::Error; use crate::authentication::{self, Key}; @@ -110,7 +110,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Returns an [`Error`] if the metrics cannot be loaded. - fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error>; + fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error>; /// Saves torrent metrics data into the database. /// @@ -149,7 +149,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Returns an [`Error`] if the total downloads cannot be loaded. - fn load_global_downloads(&self) -> Result, Error>; + fn load_global_downloads(&self) -> Result, Error>; /// Saves the total number of downloads for all torrents into the database. /// @@ -163,7 +163,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Returns an [`Error`] if the total downloads cannot be saved. - fn save_global_downloads(&self, downloaded: PersistentTorrent) -> Result<(), Error>; + fn save_global_downloads(&self, downloaded: NumberOfDownloads) -> Result<(), Error>; /// Increases the total number of downloads for all torrents. /// diff --git a/packages/tracker-core/src/statistics/persisted/downloads.rs b/packages/tracker-core/src/statistics/persisted/downloads.rs index 7edaf73d8..2e2ae3926 100644 --- a/packages/tracker-core/src/statistics/persisted/downloads.rs +++ b/packages/tracker-core/src/statistics/persisted/downloads.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::{PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{NumberOfDownloads, PersistentTorrents}; use crate::databases::error::Error; use crate::databases::Database; @@ -89,7 +89,7 @@ impl DatabaseDownloadsMetricRepository { /// # Errors /// /// Returns an [`Error`] if the underlying database query fails. - pub(crate) fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error> { + pub(crate) fn load_torrent_downloads(&self, info_hash: &InfoHash) -> Result, Error> { self.database.load_torrent_downloads(info_hash) } @@ -133,7 +133,7 @@ impl DatabaseDownloadsMetricRepository { /// # Errors /// /// Returns an [`Error`] if the underlying database query fails. - pub(crate) fn load_global_downloads(&self) -> Result, Error> { + pub(crate) fn load_global_downloads(&self) -> Result, Error> { self.database.load_global_downloads() } } diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 5c8a335b6..e44bd774f 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -6,7 +6,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; use torrust_tracker_torrent_repository::{SwarmHandle, Swarms}; /// In-memory repository for torrent entries. @@ -52,7 +52,7 @@ impl InMemoryTorrentRepository { &self, info_hash: &InfoHash, peer: &peer::Peer, - opt_persistent_torrent: Option, + opt_persistent_torrent: Option, ) { self.swarms .handle_announcement(info_hash, peer, opt_persistent_torrent) From bcf2338b04b5953dd75f2072365baa0dacff6b16 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 May 2025 15:12:26 +0100 Subject: [PATCH 1144/1297] refactor: [#1541] rename type alias PersistentTorrents to NumberOfDownloadsBTreeMap --- packages/primitives/src/lib.rs | 2 +- .../src/repository/dash_map_mutex_std.rs | 4 ++-- .../src/repository/mod.rs | 6 +++--- .../src/repository/rw_lock_std.rs | 4 ++-- .../src/repository/rw_lock_std_mutex_std.rs | 4 ++-- .../src/repository/rw_lock_std_mutex_tokio.rs | 4 ++-- .../src/repository/rw_lock_tokio.rs | 4 ++-- .../src/repository/rw_lock_tokio_mutex_std.rs | 4 ++-- .../src/repository/rw_lock_tokio_mutex_tokio.rs | 4 ++-- .../src/repository/skip_map_mutex_std.rs | 8 ++++---- .../tests/common/repo.rs | 4 ++-- .../tests/repository/mod.rs | 12 ++++++------ packages/torrent-repository/src/swarms.rs | 12 ++++++------ packages/tracker-core/src/databases/driver/mysql.rs | 4 ++-- packages/tracker-core/src/databases/driver/sqlite.rs | 4 ++-- packages/tracker-core/src/databases/mod.rs | 4 ++-- .../src/statistics/persisted/downloads.rs | 8 ++++---- .../tracker-core/src/torrent/repository/in_memory.rs | 4 ++-- 18 files changed, 48 insertions(+), 48 deletions(-) diff --git a/packages/primitives/src/lib.rs b/packages/primitives/src/lib.rs index b04991eb8..ec2edda97 100644 --- a/packages/primitives/src/lib.rs +++ b/packages/primitives/src/lib.rs @@ -19,4 +19,4 @@ use bittorrent_primitives::info_hash::InfoHash; pub type DurationSinceUnixEpoch = Duration; pub type NumberOfDownloads = u32; -pub type PersistentTorrents = BTreeMap; +pub type NumberOfDownloadsBTreeMap = BTreeMap; diff --git a/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs index c0ef455d4..192777b32 100644 --- a/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs @@ -5,7 +5,7 @@ use dashmap::DashMap; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -77,7 +77,7 @@ where } } - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { for (info_hash, completed) in persistent_torrents { if self.torrents.contains_key(info_hash) { continue; diff --git a/packages/torrent-repository-benchmarking/src/repository/mod.rs b/packages/torrent-repository-benchmarking/src/repository/mod.rs index 2ad7a3927..890088ea7 100644 --- a/packages/torrent-repository-benchmarking/src/repository/mod.rs +++ b/packages/torrent-repository-benchmarking/src/repository/mod.rs @@ -2,7 +2,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; pub mod dash_map_mutex_std; pub mod rw_lock_std; @@ -19,7 +19,7 @@ pub trait Repository: Debug + Default + Sized + 'static { fn get(&self, key: &InfoHash) -> Option; fn get_metrics(&self) -> AggregateSwarmMetadata; fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, T)>; - fn import_persistent(&self, persistent_torrents: &PersistentTorrents); + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap); fn remove(&self, key: &InfoHash) -> Option; fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch); fn remove_peerless_torrents(&self, policy: &TrackerPolicy); @@ -32,7 +32,7 @@ pub trait RepositoryAsync: Debug + Default + Sized + 'static { fn get(&self, key: &InfoHash) -> impl std::future::Future> + Send; fn get_metrics(&self) -> impl std::future::Future + Send; fn get_paginated(&self, pagination: Option<&Pagination>) -> impl std::future::Future> + Send; - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) -> impl std::future::Future + Send; + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) -> impl std::future::Future + Send; fn remove(&self, key: &InfoHash) -> impl std::future::Future> + Send; fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) -> impl std::future::Future + Send; fn remove_peerless_torrents(&self, policy: &TrackerPolicy) -> impl std::future::Future + Send; diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs index c0e4d5cf5..074725674 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs @@ -2,7 +2,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -92,7 +92,7 @@ where } } - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { let mut torrents = self.get_torrents_mut(); for (info_hash, downloaded) in persistent_torrents { diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs index 30aabc799..9577a42e1 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs @@ -4,7 +4,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -87,7 +87,7 @@ where } } - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { let mut torrents = self.get_torrents_mut(); for (info_hash, completed) in persistent_torrents { diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs index f56322654..73cb64a08 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs @@ -8,7 +8,7 @@ use futures::{Future, FutureExt}; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; @@ -101,7 +101,7 @@ where metrics } - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + async fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { let mut db = self.get_torrents_mut(); for (info_hash, completed) in persistent_torrents { diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs index 091ff303d..9d7d591fc 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs @@ -2,7 +2,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; @@ -98,7 +98,7 @@ where metrics } - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + async fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { let mut torrents = self.get_torrents_mut().await; for (info_hash, completed) in persistent_torrents { diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs index 542ad7f0a..6ad7ade98 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs @@ -4,7 +4,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; @@ -92,7 +92,7 @@ where metrics } - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + async fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { let mut torrents = self.get_torrents_mut().await; for (info_hash, completed) in persistent_torrents { diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs index 2551972b3..6ce6c3f58 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -4,7 +4,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; @@ -95,7 +95,7 @@ where metrics } - async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + async fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { let mut db = self.get_torrents_mut().await; for (info_hash, completed) in persistent_torrents { diff --git a/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs index 7d141facb..81fc1c05a 100644 --- a/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs @@ -5,7 +5,7 @@ use crossbeam_skiplist::SkipMap; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -100,7 +100,7 @@ where } } - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { for (info_hash, completed) in persistent_torrents { if self.torrents.contains_key(info_hash) { continue; @@ -193,7 +193,7 @@ where } } - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { for (info_hash, completed) in persistent_torrents { if self.torrents.contains_key(info_hash) { continue; @@ -286,7 +286,7 @@ where } } - fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { for (info_hash, completed) in persistent_torrents { if self.torrents.contains_key(info_hash) { continue; diff --git a/packages/torrent-repository-benchmarking/tests/common/repo.rs b/packages/torrent-repository-benchmarking/tests/common/repo.rs index 3371e3c64..e5037d641 100644 --- a/packages/torrent-repository-benchmarking/tests/common/repo.rs +++ b/packages/torrent-repository-benchmarking/tests/common/repo.rs @@ -2,7 +2,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use torrust_tracker_torrent_repository_benchmarking::repository::{Repository as _, RepositoryAsync as _}; use torrust_tracker_torrent_repository_benchmarking::{ EntrySingle, TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, @@ -144,7 +144,7 @@ impl Repo { } } - pub(crate) async fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + pub(crate) async fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { match self { Repo::RwLockStd(repo) => repo.import_persistent(persistent_torrents), Repo::RwLockStdMutexStd(repo) => repo.import_persistent(persistent_torrents), diff --git a/packages/torrent-repository-benchmarking/tests/repository/mod.rs b/packages/torrent-repository-benchmarking/tests/repository/mod.rs index 6973f38bd..141faa8a9 100644 --- a/packages/torrent-repository-benchmarking/tests/repository/mod.rs +++ b/packages/torrent-repository-benchmarking/tests/repository/mod.rs @@ -7,7 +7,7 @@ use rstest::{fixture, rstest}; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; -use torrust_tracker_primitives::PersistentTorrents; +use torrust_tracker_primitives::NumberOfDownloadsBTreeMap; use torrust_tracker_torrent_repository_benchmarking::entry::Entry as _; use torrust_tracker_torrent_repository_benchmarking::repository::dash_map_mutex_std::XacrimonDashMap; use torrust_tracker_torrent_repository_benchmarking::repository::rw_lock_std::RwLockStd; @@ -167,12 +167,12 @@ fn many_hashed_in_order() -> Entries { } #[fixture] -fn persistent_empty() -> PersistentTorrents { - PersistentTorrents::default() +fn persistent_empty() -> NumberOfDownloadsBTreeMap { + NumberOfDownloadsBTreeMap::default() } #[fixture] -fn persistent_single() -> PersistentTorrents { +fn persistent_single() -> NumberOfDownloadsBTreeMap { let hash = &mut DefaultHasher::default(); hash.write_u8(1); @@ -182,7 +182,7 @@ fn persistent_single() -> PersistentTorrents { } #[fixture] -fn persistent_three() -> PersistentTorrents { +fn persistent_three() -> NumberOfDownloadsBTreeMap { let hash = &mut DefaultHasher::default(); hash.write_u8(1); @@ -445,7 +445,7 @@ async fn it_should_import_persistent_torrents( )] repo: Repo, #[case] entries: Entries, - #[values(persistent_empty(), persistent_single(), persistent_three())] persistent_torrents: PersistentTorrents, + #[values(persistent_empty(), persistent_single(), persistent_three())] persistent_torrents: NumberOfDownloadsBTreeMap, ) { make(&repo, &entries).await; diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index 9c1f3d9b2..ba8a80a62 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -7,7 +7,7 @@ use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use crate::event::sender::Sender; use crate::event::Event; @@ -356,7 +356,7 @@ impl Swarms { /// This method takes a set of persisted torrent entries (e.g., from a /// database) and imports them into the in-memory repository for immediate /// access. - pub fn import_persistent(&self, persistent_torrents: &PersistentTorrents) -> u64 { + pub fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) -> u64 { tracing::info!("Importing persisted info about torrents ..."); let mut torrents_imported = 0; @@ -1271,7 +1271,7 @@ mod tests { use std::sync::Arc; - use torrust_tracker_primitives::PersistentTorrents; + use torrust_tracker_primitives::NumberOfDownloadsBTreeMap; use crate::swarms::Swarms; use crate::tests::{leecher, sample_info_hash}; @@ -1282,7 +1282,7 @@ mod tests { let infohash = sample_info_hash(); - let mut persistent_torrents = PersistentTorrents::default(); + let mut persistent_torrents = NumberOfDownloadsBTreeMap::default(); persistent_torrents.insert(infohash, 1); @@ -1302,7 +1302,7 @@ mod tests { let infohash = sample_info_hash(); - let mut persistent_torrents = PersistentTorrents::default(); + let mut persistent_torrents = NumberOfDownloadsBTreeMap::default(); persistent_torrents.insert(infohash, 1); persistent_torrents.insert(infohash, 2); @@ -1327,7 +1327,7 @@ mod tests { // Try to import the torrent entry let new_number_of_downloads = initial_number_of_downloads + 1; - let mut persistent_torrents = PersistentTorrents::default(); + let mut persistent_torrents = NumberOfDownloadsBTreeMap::default(); persistent_torrents.insert(infohash, new_number_of_downloads); swarms.import_persistent(&persistent_torrents); diff --git a/packages/tracker-core/src/databases/driver/mysql.rs b/packages/tracker-core/src/databases/driver/mysql.rs index a5dfc50e5..da2f86ce8 100644 --- a/packages/tracker-core/src/databases/driver/mysql.rs +++ b/packages/tracker-core/src/databases/driver/mysql.rs @@ -13,7 +13,7 @@ use r2d2::Pool; use r2d2_mysql::mysql::prelude::Queryable; use r2d2_mysql::mysql::{params, Opts, OptsBuilder}; use r2d2_mysql::MySqlConnectionManager; -use torrust_tracker_primitives::{NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::{Database, Driver, Error, TORRENTS_DOWNLOADS_TOTAL}; use crate::authentication::key::AUTH_KEY_LENGTH; @@ -146,7 +146,7 @@ impl Database for Mysql { } /// Refer to [`databases::Database::load_persistent_torrents`](crate::core::databases::Database::load_persistent_torrents). - fn load_all_torrents_downloads(&self) -> Result { + fn load_all_torrents_downloads(&self) -> Result { let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?; let torrents = conn.query_map( diff --git a/packages/tracker-core/src/databases/driver/sqlite.rs b/packages/tracker-core/src/databases/driver/sqlite.rs index d4b6a82c6..d08351aa8 100644 --- a/packages/tracker-core/src/databases/driver/sqlite.rs +++ b/packages/tracker-core/src/databases/driver/sqlite.rs @@ -13,7 +13,7 @@ use r2d2::Pool; use r2d2_sqlite::rusqlite::params; use r2d2_sqlite::rusqlite::types::Null; use r2d2_sqlite::SqliteConnectionManager; -use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::{Database, Driver, Error, TORRENTS_DOWNLOADS_TOTAL}; use crate::authentication::{self, Key}; @@ -152,7 +152,7 @@ impl Database for Sqlite { } /// Refer to [`databases::Database::load_persistent_torrents`](crate::core::databases::Database::load_persistent_torrents). - fn load_all_torrents_downloads(&self) -> Result { + fn load_all_torrents_downloads(&self) -> Result { let conn = self.pool.get().map_err(|e| (e, DRIVER))?; let mut stmt = conn.prepare("SELECT info_hash, completed FROM torrents")?; diff --git a/packages/tracker-core/src/databases/mod.rs b/packages/tracker-core/src/databases/mod.rs index 6147873f6..c9d89769a 100644 --- a/packages/tracker-core/src/databases/mod.rs +++ b/packages/tracker-core/src/databases/mod.rs @@ -52,7 +52,7 @@ pub mod setup; use bittorrent_primitives::info_hash::InfoHash; use mockall::automock; -use torrust_tracker_primitives::{NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{NumberOfDownloads, NumberOfDownloadsBTreeMap}; use self::error::Error; use crate::authentication::{self, Key}; @@ -101,7 +101,7 @@ pub trait Database: Sync + Send { /// # Errors /// /// Returns an [`Error`] if the metrics cannot be loaded. - fn load_all_torrents_downloads(&self) -> Result; + fn load_all_torrents_downloads(&self) -> Result; /// Loads torrent metrics data from the database for one torrent. /// diff --git a/packages/tracker-core/src/statistics/persisted/downloads.rs b/packages/tracker-core/src/statistics/persisted/downloads.rs index 2e2ae3926..4d3bdf9a3 100644 --- a/packages/tracker-core/src/statistics/persisted/downloads.rs +++ b/packages/tracker-core/src/statistics/persisted/downloads.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::{NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{NumberOfDownloads, NumberOfDownloadsBTreeMap}; use crate::databases::error::Error; use crate::databases::Database; @@ -77,7 +77,7 @@ impl DatabaseDownloadsMetricRepository { /// # Errors /// /// Returns an [`Error`] if the underlying database query fails. - pub(crate) fn load_all_torrents_downloads(&self) -> Result { + pub(crate) fn load_all_torrents_downloads(&self) -> Result { self.database.load_all_torrents_downloads() } @@ -141,7 +141,7 @@ impl DatabaseDownloadsMetricRepository { #[cfg(test)] mod tests { - use torrust_tracker_primitives::PersistentTorrents; + use torrust_tracker_primitives::NumberOfDownloadsBTreeMap; use super::DatabaseDownloadsMetricRepository; use crate::databases::setup::initialize_database; @@ -191,7 +191,7 @@ mod tests { let torrents = repository.load_all_torrents_downloads().unwrap(); - let mut expected_torrents = PersistentTorrents::new(); + let mut expected_torrents = NumberOfDownloadsBTreeMap::new(); expected_torrents.insert(infohash_one, 1); expected_torrents.insert(infohash_two, 2); diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index e44bd774f..164f46c69 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -6,7 +6,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, PersistentTorrents}; +use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use torrust_tracker_torrent_repository::{SwarmHandle, Swarms}; /// In-memory repository for torrent entries. @@ -264,7 +264,7 @@ impl InMemoryTorrentRepository { /// # Arguments /// /// * `persistent_torrents` - A reference to the persisted torrent data. - pub fn import_persistent(&self, persistent_torrents: &PersistentTorrents) { + pub fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { self.swarms.import_persistent(persistent_torrents); } } From bd6e06acaaebffad76a69249a5faa3402db501a7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 27 May 2025 15:14:09 +0100 Subject: [PATCH 1145/1297] refactor: [#1541] remove unused code --- src/app.rs | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/src/app.rs b/src/app.rs index c31281829..ccc2e8bcb 100644 --- a/src/app.rs +++ b/src/app.rs @@ -66,13 +66,6 @@ async fn load_data_from_database(config: &Configuration, app_container: &Arc) -> JobManager { @@ -127,18 +120,6 @@ async fn load_whitelisted_torrents(config: &Configuration, app_container: &Arc) { - if config.core.tracker_policy.persistent_torrent_completed_stat { - app_container - .tracker_core_container - .torrents_manager - .load_torrents_from_database() - .expect("Could not load torrents from database."); - } -} - -#[allow(dead_code)] async fn load_torrent_metrics(config: &Configuration, app_container: &Arc) { if config.core.tracker_policy.persistent_torrent_completed_stat { bittorrent_tracker_core::statistics::persisted::load_persisted_metrics( From 3d6fc651d2cb515a3147264554f0db6f4c7ace12 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 28 May 2025 08:14:01 +0100 Subject: [PATCH 1146/1297] refactor: [#1543] rename AggregateSwarmMetadata to AggregateActiveSwarmMetadata Aggregate values are only for active swarms. For example, it does not count downloads for torrents that are not currently active. --- .../src/v1/context/stats/resources.rs | 4 ++-- .../src/statistics/services.rs | 8 ++++---- packages/primitives/src/swarm_metadata.rs | 13 ++++++------- .../src/statistics/services.rs | 8 ++++---- .../src/repository/dash_map_mutex_std.rs | 6 +++--- .../src/repository/mod.rs | 6 +++--- .../src/repository/rw_lock_std.rs | 6 +++--- .../src/repository/rw_lock_std_mutex_std.rs | 6 +++--- .../src/repository/rw_lock_std_mutex_tokio.rs | 6 +++--- .../src/repository/rw_lock_tokio.rs | 6 +++--- .../src/repository/rw_lock_tokio_mutex_std.rs | 6 +++--- .../repository/rw_lock_tokio_mutex_tokio.rs | 6 +++--- .../src/repository/skip_map_mutex_std.rs | 14 +++++++------- .../tests/common/repo.rs | 4 ++-- .../tests/repository/mod.rs | 4 ++-- packages/torrent-repository/src/swarms.rs | 18 +++++++++--------- .../src/torrent/repository/in_memory.rs | 4 ++-- .../src/statistics/services.rs | 8 ++++---- .../src/statistics/services.rs | 8 ++++---- 19 files changed, 70 insertions(+), 71 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs index 8fcfd1be0..8b6d639c8 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs @@ -136,7 +136,7 @@ impl From for LabeledStats { mod tests { use torrust_rest_tracker_api_core::statistics::metrics::Metrics; use torrust_rest_tracker_api_core::statistics::services::TrackerMetrics; - use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; + use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use super::Stats; @@ -145,7 +145,7 @@ mod tests { fn stats_resource_should_be_converted_from_tracker_metrics() { assert_eq!( Stats::from(TrackerMetrics { - torrents_metrics: AggregateSwarmMetadata { + torrents_metrics: AggregateActiveSwarmMetadata { total_complete: 1, total_downloaded: 2, total_incomplete: 3, diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index af1e30524..dbc096030 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -23,7 +23,7 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; +use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use crate::statistics::metrics::Metrics; use crate::statistics::repository::Repository; @@ -34,7 +34,7 @@ pub struct TrackerMetrics { /// Domain level metrics. /// /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: AggregateSwarmMetadata, + pub torrents_metrics: AggregateActiveSwarmMetadata, /// Application level metrics. Usage statistics/metrics. /// @@ -72,7 +72,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self}; use torrust_tracker_configuration::Configuration; - use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; + use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use torrust_tracker_test_helpers::configuration; use crate::event::bus::EventBus; @@ -109,7 +109,7 @@ mod tests { assert_eq!( tracker_metrics, TrackerMetrics { - torrents_metrics: AggregateSwarmMetadata::default(), + torrents_metrics: AggregateActiveSwarmMetadata::default(), protocol_metrics: describe_metrics(), } ); diff --git a/packages/primitives/src/swarm_metadata.rs b/packages/primitives/src/swarm_metadata.rs index a70298d71..57ba816d3 100644 --- a/packages/primitives/src/swarm_metadata.rs +++ b/packages/primitives/src/swarm_metadata.rs @@ -46,24 +46,23 @@ impl SwarmMetadata { /// Structure that holds aggregate swarm metadata. /// -/// Metrics are aggregate values for all torrents. +/// Metrics are aggregate values for all active torrents/swarms. #[derive(Copy, Clone, Debug, PartialEq, Default)] -pub struct AggregateSwarmMetadata { - /// Total number of peers that have ever completed downloading for all - /// torrents. +pub struct AggregateActiveSwarmMetadata { + /// Total number of peers that have ever completed downloading. pub total_downloaded: u64, - /// Total number of seeders for all torrents. + /// Total number of seeders. pub total_complete: u64, - /// Total number of leechers for all torrents. + /// Total number of leechers. pub total_incomplete: u64, /// Total number of torrents. pub total_torrents: u64, } -impl AddAssign for AggregateSwarmMetadata { +impl AddAssign for AggregateActiveSwarmMetadata { fn add_assign(&mut self, rhs: Self) { self.total_complete += rhs.total_complete; self.total_downloaded += rhs.total_downloaded; diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 8fb29e7bd..4a471a3ef 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -5,7 +5,7 @@ use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self}; use tokio::sync::RwLock; use torrust_tracker_metrics::metric_collection::MetricCollection; -use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; +use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use torrust_udp_tracker_server::statistics as udp_server_statistics; use crate::statistics::metrics::Metrics; @@ -16,7 +16,7 @@ pub struct TrackerMetrics { /// Domain level metrics. /// /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: AggregateSwarmMetadata, + pub torrents_metrics: AggregateActiveSwarmMetadata, /// Application level metrics. Usage statistics/metrics. /// @@ -144,7 +144,7 @@ mod tests { use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use tokio::sync::RwLock; use torrust_tracker_configuration::Configuration; - use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; + use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use torrust_tracker_test_helpers::configuration; use crate::statistics::metrics::Metrics; @@ -187,7 +187,7 @@ mod tests { assert_eq!( tracker_metrics, TrackerMetrics { - torrents_metrics: AggregateSwarmMetadata::default(), + torrents_metrics: AggregateActiveSwarmMetadata::default(), protocol_metrics: Metrics::default(), } ); diff --git a/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs index 192777b32..fec94b4a5 100644 --- a/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/dash_map_mutex_std.rs @@ -4,7 +4,7 @@ use bittorrent_primitives::info_hash::InfoHash; use dashmap::DashMap; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::Repository; @@ -46,8 +46,8 @@ where maybe_entry.map(|entry| entry.clone()) } - fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); + fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); for entry in &self.torrents { let stats = entry.value().lock().expect("it should get a lock").get_swarm_metadata(); diff --git a/packages/torrent-repository-benchmarking/src/repository/mod.rs b/packages/torrent-repository-benchmarking/src/repository/mod.rs index 890088ea7..cf58838a1 100644 --- a/packages/torrent-repository-benchmarking/src/repository/mod.rs +++ b/packages/torrent-repository-benchmarking/src/repository/mod.rs @@ -1,7 +1,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; pub mod dash_map_mutex_std; @@ -17,7 +17,7 @@ use std::fmt::Debug; pub trait Repository: Debug + Default + Sized + 'static { fn get(&self, key: &InfoHash) -> Option; - fn get_metrics(&self) -> AggregateSwarmMetadata; + fn get_metrics(&self) -> AggregateActiveSwarmMetadata; fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, T)>; fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap); fn remove(&self, key: &InfoHash) -> Option; @@ -30,7 +30,7 @@ pub trait Repository: Debug + Default + Sized + 'static { #[allow(clippy::module_name_repetitions)] pub trait RepositoryAsync: Debug + Default + Sized + 'static { fn get(&self, key: &InfoHash) -> impl std::future::Future> + Send; - fn get_metrics(&self) -> impl std::future::Future + Send; + fn get_metrics(&self) -> impl std::future::Future + Send; fn get_paginated(&self, pagination: Option<&Pagination>) -> impl std::future::Future> + Send; fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) -> impl std::future::Future + Send; fn remove(&self, key: &InfoHash) -> impl std::future::Future> + Send; diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs index 074725674..5000579dd 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs @@ -1,7 +1,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::Repository; @@ -64,8 +64,8 @@ where db.get(key).cloned() } - fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); + fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); for entry in self.get_torrents().values() { let stats = entry.get_swarm_metadata(); diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs index 9577a42e1..085256ff1 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_std.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::Repository; @@ -59,8 +59,8 @@ where db.get(key).cloned() } - fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); + fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); for entry in self.get_torrents().values() { let stats = entry.lock().expect("it should get a lock").get_swarm_metadata(); diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs index 73cb64a08..9fd451149 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std_mutex_tokio.rs @@ -7,7 +7,7 @@ use futures::future::join_all; use futures::{Future, FutureExt}; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::RepositoryAsync; @@ -85,8 +85,8 @@ where } } - async fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); + async fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); let entries: Vec<_> = self.get_torrents().values().cloned().collect(); diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs index 9d7d591fc..e85200aeb 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs @@ -1,7 +1,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::RepositoryAsync; @@ -84,8 +84,8 @@ where } } - async fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); + async fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); for entry in self.get_torrents().await.values() { let stats = entry.get_swarm_metadata(); diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs index 6ad7ade98..8d6584713 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_std.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::RepositoryAsync; @@ -78,8 +78,8 @@ where } } - async fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); + async fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); for entry in self.get_torrents().await.values() { let stats = entry.get_swarm_metadata(); diff --git a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs index 6ce6c3f58..c8f499e03 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio_mutex_tokio.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::RepositoryAsync; @@ -81,8 +81,8 @@ where } } - async fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); + async fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); for entry in self.get_torrents().await.values() { let stats = entry.get_swarm_metadata().await; diff --git a/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs b/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs index 81fc1c05a..0432b13d0 100644 --- a/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/skip_map_mutex_std.rs @@ -4,7 +4,7 @@ use bittorrent_primitives::info_hash::InfoHash; use crossbeam_skiplist::SkipMap; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use super::Repository; @@ -69,8 +69,8 @@ where maybe_entry.map(|entry| entry.value().clone()) } - fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); + fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); for entry in &self.torrents { let stats = entry.value().lock().expect("it should get a lock").get_swarm_metadata(); @@ -162,8 +162,8 @@ where maybe_entry.map(|entry| entry.value().clone()) } - fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); + fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); for entry in &self.torrents { let stats = entry.value().read().get_swarm_metadata(); @@ -255,8 +255,8 @@ where maybe_entry.map(|entry| entry.value().clone()) } - fn get_metrics(&self) -> AggregateSwarmMetadata { - let mut metrics = AggregateSwarmMetadata::default(); + fn get_metrics(&self) -> AggregateActiveSwarmMetadata { + let mut metrics = AggregateActiveSwarmMetadata::default(); for entry in &self.torrents { let stats = entry.value().lock().get_swarm_metadata(); diff --git a/packages/torrent-repository-benchmarking/tests/common/repo.rs b/packages/torrent-repository-benchmarking/tests/common/repo.rs index e5037d641..2987240ef 100644 --- a/packages/torrent-repository-benchmarking/tests/common/repo.rs +++ b/packages/torrent-repository-benchmarking/tests/common/repo.rs @@ -1,7 +1,7 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use torrust_tracker_torrent_repository_benchmarking::repository::{Repository as _, RepositoryAsync as _}; use torrust_tracker_torrent_repository_benchmarking::{ @@ -75,7 +75,7 @@ impl Repo { } } - pub(crate) async fn get_metrics(&self) -> AggregateSwarmMetadata { + pub(crate) async fn get_metrics(&self) -> AggregateActiveSwarmMetadata { match self { Repo::RwLockStd(repo) => repo.get_metrics(), Repo::RwLockStdMutexStd(repo) => repo.get_metrics(), diff --git a/packages/torrent-repository-benchmarking/tests/repository/mod.rs b/packages/torrent-repository-benchmarking/tests/repository/mod.rs index 141faa8a9..e555654ca 100644 --- a/packages/torrent-repository-benchmarking/tests/repository/mod.rs +++ b/packages/torrent-repository-benchmarking/tests/repository/mod.rs @@ -402,11 +402,11 @@ async fn it_should_get_metrics( repo: Repo, #[case] entries: Entries, ) { - use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; + use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; make(&repo, &entries).await; - let mut metrics = AggregateSwarmMetadata::default(); + let mut metrics = AggregateActiveSwarmMetadata::default(); for (_, torrent) in entries { let stats = torrent.get_swarm_metadata(); diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index ba8a80a62..f0b3233b6 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -6,7 +6,7 @@ use tokio::sync::Mutex; use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use crate::event::sender::Sender; @@ -394,8 +394,8 @@ impl Swarms { /// /// This function returns an error if it fails to acquire the lock for any /// swarm handle. - pub async fn get_aggregate_swarm_metadata(&self) -> Result { - let mut metrics = AggregateSwarmMetadata::default(); + pub async fn get_aggregate_swarm_metadata(&self) -> Result { + let mut metrics = AggregateActiveSwarmMetadata::default(); for swarm_handle in &self.swarms { let swarm = swarm_handle.value().lock().await; @@ -1055,7 +1055,7 @@ mod tests { use std::sync::Arc; use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; - use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; + use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use crate::swarms::Swarms; use crate::tests::{complete_peer, leecher, sample_info_hash, seeder}; @@ -1070,7 +1070,7 @@ mod tests { assert_eq!( aggregate_swarm_metadata, - AggregateSwarmMetadata { + AggregateActiveSwarmMetadata { total_complete: 0, total_downloaded: 0, total_incomplete: 0, @@ -1092,7 +1092,7 @@ mod tests { assert_eq!( aggregate_swarm_metadata, - AggregateSwarmMetadata { + AggregateActiveSwarmMetadata { total_complete: 0, total_downloaded: 0, total_incomplete: 1, @@ -1114,7 +1114,7 @@ mod tests { assert_eq!( aggregate_swarm_metadata, - AggregateSwarmMetadata { + AggregateActiveSwarmMetadata { total_complete: 1, total_downloaded: 0, total_incomplete: 0, @@ -1136,7 +1136,7 @@ mod tests { assert_eq!( aggregate_swarm_metadata, - AggregateSwarmMetadata { + AggregateActiveSwarmMetadata { total_complete: 1, total_downloaded: 0, total_incomplete: 0, @@ -1164,7 +1164,7 @@ mod tests { assert_eq!( (aggregate_swarm_metadata), - (AggregateSwarmMetadata { + (AggregateActiveSwarmMetadata { total_complete: 0, total_downloaded: 0, total_incomplete: 1_000_000, diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 164f46c69..ffd885c4f 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; -use torrust_tracker_primitives::swarm_metadata::{AggregateSwarmMetadata, SwarmMetadata}; +use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; use torrust_tracker_torrent_repository::{SwarmHandle, Swarms}; @@ -226,7 +226,7 @@ impl InMemoryTorrentRepository { /// /// This function panics if the underling swarms return an error. #[must_use] - pub async fn get_aggregate_swarm_metadata(&self) -> AggregateSwarmMetadata { + pub async fn get_aggregate_swarm_metadata(&self) -> AggregateActiveSwarmMetadata { self.swarms .get_aggregate_swarm_metadata() .await diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index 20ba2ea7f..24d25a25c 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -39,7 +39,7 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; +use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use crate::statistics::metrics::Metrics; use crate::statistics::repository::Repository; @@ -50,7 +50,7 @@ pub struct TrackerMetrics { /// Domain level metrics. /// /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: AggregateSwarmMetadata, + pub torrents_metrics: AggregateActiveSwarmMetadata, /// Application level metrics. Usage statistics/metrics. /// @@ -89,7 +89,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self}; - use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; + use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use crate::statistics::describe_metrics; use crate::statistics::repository::Repository; @@ -106,7 +106,7 @@ mod tests { assert_eq!( tracker_metrics, TrackerMetrics { - torrents_metrics: AggregateSwarmMetadata::default(), + torrents_metrics: AggregateActiveSwarmMetadata::default(), protocol_metrics: describe_metrics(), } ); diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index c8b24a744..e6e5a28f3 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -41,7 +41,7 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::services::banning::BanService; use tokio::sync::RwLock; -use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; +use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use crate::statistics::metrics::Metrics; use crate::statistics::repository::Repository; @@ -52,7 +52,7 @@ pub struct TrackerMetrics { /// Domain level metrics. /// /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: AggregateSwarmMetadata, + pub torrents_metrics: AggregateActiveSwarmMetadata, /// Application level metrics. Usage statistics/metrics. /// @@ -109,7 +109,7 @@ mod tests { use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use tokio::sync::RwLock; - use torrust_tracker_primitives::swarm_metadata::AggregateSwarmMetadata; + use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use crate::statistics::describe_metrics; use crate::statistics::repository::Repository; @@ -132,7 +132,7 @@ mod tests { assert_eq!( tracker_metrics, TrackerMetrics { - torrents_metrics: AggregateSwarmMetadata::default(), + torrents_metrics: AggregateActiveSwarmMetadata::default(), protocol_metrics: describe_metrics(), } ); From e1076142feea8062691da139f9b7ff38be59491f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 28 May 2025 08:19:12 +0100 Subject: [PATCH 1147/1297] chore: [#1543] remove comment on tracker-core handle_announcement We need to load the number of downloads for the torrent before adding it to the active swarms becuase the scrape response includes the number of downloads, and that number should included all downloads ever. --- packages/tracker-core/src/announce_handler.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index a6614361a..f74c135e3 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -163,11 +163,6 @@ impl AnnounceHandler { ) -> Result { self.whitelist_authorization.authorize(info_hash).await?; - // This will be removed in the future. - // See https://github.com/torrust/torrust-tracker/issues/1502 - // There will be a persisted metric for counting the total number of - // downloads across all torrents. The in-memory metric will count only - // the number of downloads during the current tracker uptime. let opt_persistent_torrent = if self.config.tracker_policy.persistent_torrent_completed_stat { self.db_downloads_metric_repository.load_torrent_downloads(info_hash)? } else { From 762bf6905477866ae2cf2a676255050d7a522d7f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 28 May 2025 08:39:17 +0100 Subject: [PATCH 1148/1297] refactor: [#1543] Optimization: Don't load number of downloads from DB if not needed --- packages/torrent-repository/src/swarms.rs | 4 ++++ packages/tracker-core/src/announce_handler.rs | 24 ++++++++++++------- .../src/torrent/repository/in_memory.rs | 6 +++++ 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/packages/torrent-repository/src/swarms.rs b/packages/torrent-repository/src/swarms.rs index f0b3233b6..8e7bc24de 100644 --- a/packages/torrent-repository/src/swarms.rs +++ b/packages/torrent-repository/src/swarms.rs @@ -467,6 +467,10 @@ impl Swarms { pub fn is_empty(&self) -> bool { self.swarms.is_empty() } + + pub fn contains(&self, key: &InfoHash) -> bool { + self.swarms.contains_key(key) + } } #[derive(thiserror::Error, Debug, Clone)] diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index f74c135e3..0b6bffd31 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -96,9 +96,10 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::{Core, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::core::AnnounceData; -use torrust_tracker_primitives::peer; +use torrust_tracker_primitives::{peer, NumberOfDownloads}; use super::torrent::repository::in_memory::InMemoryTorrentRepository; +use crate::databases; use crate::error::AnnounceError; use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use crate::whitelist::authorization::WhitelistAuthorization; @@ -163,21 +164,28 @@ impl AnnounceHandler { ) -> Result { self.whitelist_authorization.authorize(info_hash).await?; - let opt_persistent_torrent = if self.config.tracker_policy.persistent_torrent_completed_stat { - self.db_downloads_metric_repository.load_torrent_downloads(info_hash)? - } else { - None - }; - peer.change_ip(&assign_ip_address_to_peer(remote_client_ip, self.config.net.external_ip)); self.in_memory_torrent_repository - .handle_announcement(info_hash, peer, opt_persistent_torrent) + .handle_announcement(info_hash, peer, self.load_downloads_metric_if_needed(info_hash)?) .await; Ok(self.build_announce_data(info_hash, peer, peers_wanted).await) } + /// Loads the number of downloads for a torrent if needed. + fn load_downloads_metric_if_needed( + &self, + info_hash: &InfoHash, + ) -> Result, databases::error::Error> { + if self.config.tracker_policy.persistent_torrent_completed_stat && !self.in_memory_torrent_repository.contains(info_hash) + { + Ok(self.db_downloads_metric_repository.load_torrent_downloads(info_hash)?) + } else { + Ok(None) + } + } + /// Builds the announce data for the peer making the request. async fn build_announce_data(&self, info_hash: &InfoHash, peer: &peer::Peer, peers_wanted: &PeersWanted) -> AnnounceData { let peers = self diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index ffd885c4f..cc873726d 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -267,4 +267,10 @@ impl InMemoryTorrentRepository { pub fn import_persistent(&self, persistent_torrents: &NumberOfDownloadsBTreeMap) { self.swarms.import_persistent(persistent_torrents); } + + /// Checks if the repository contains a torrent entry for the given infohash. + #[must_use] + pub fn contains(&self, info_hash: &InfoHash) -> bool { + self.swarms.contains(info_hash) + } } From 02c33f6972eef36058afee9f0ee7180b51b5d072 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 28 May 2025 11:34:42 +0100 Subject: [PATCH 1149/1297] fix: [#1543] the downloads counter values returned in the API It now returns the persisted value when available (stats persistence enabled). --- Cargo.lock | 1 + .../src/v1/context/stats/handlers.rs | 15 ++++- .../src/v1/context/stats/routes.rs | 3 + packages/rest-tracker-api-core/Cargo.toml | 1 + .../src/statistics/services.rs | 56 +++++++++++++++++-- .../torrent-repository/src/statistics/mod.rs | 2 +- packages/tracker-core/src/statistics/mod.rs | 2 +- 7 files changed, 73 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 96de11cb2..009b1e458 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4646,6 +4646,7 @@ dependencies = [ "bittorrent-udp-tracker-core", "tokio", "torrust-tracker-configuration", + "torrust-tracker-events", "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-test-helpers", diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs index 3a353f1fc..463c81ac8 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs @@ -10,6 +10,7 @@ use bittorrent_udp_tracker_core::services::banning::BanService; use serde::Deserialize; use tokio::sync::RwLock; use torrust_rest_tracker_api_core::statistics::services::{get_labeled_metrics, get_metrics}; +use torrust_tracker_configuration::Core; use super::responses::{labeled_metrics_response, labeled_stats_response, metrics_response, stats_response}; @@ -40,14 +41,26 @@ pub struct QueryParams { #[allow(clippy::type_complexity)] pub async fn get_stats_handler( State(state): State<( + Arc, Arc, Arc>, + Arc, + Arc, Arc, Arc, )>, params: Query, ) -> Response { - let metrics = get_metrics(state.0.clone(), state.1.clone(), state.2.clone(), state.3.clone()).await; + let metrics = get_metrics( + state.0.clone(), + state.1.clone(), + state.2.clone(), + state.3.clone(), + state.4.clone(), + state.5.clone(), + state.6.clone(), + ) + .await; match params.0.format { Some(format) => match format { diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs index f6c661130..3be266d3a 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs @@ -17,8 +17,11 @@ pub fn add(prefix: &str, router: Router, http_api_container: &Arc, in_memory_torrent_repository: Arc, ban_service: Arc>, + torrent_repository_stats_repository: Arc, + tracker_core_stats_repository: Arc, http_stats_repository: Arc, udp_server_stats_repository: Arc, ) -> TrackerMetrics { - let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; + let aggregate_active_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); let http_stats = http_stats_repository.get_stats().await; let udp_server_stats = udp_server_stats_repository.get_stats().await; + let total_downloaded = if core_config.tracker_policy.persistent_torrent_completed_stat { + let metrics = tracker_core_stats_repository.get_metrics().await; + + let downloads = metrics.metric_collection.get_counter_value( + &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), + &LabelSet::default(), + ); + + if let Some(downloads) = downloads { + downloads.value() + } else { + 0 + } + } else { + let metrics = torrent_repository_stats_repository.get_metrics().await; + + let downloads = metrics.metric_collection.get_counter_value( + &metric_name!(TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL), + &LabelSet::default(), + ); + + if let Some(downloads) = downloads { + downloads.value() + } else { + 0 + } + }; + + let mut torrents_metrics = aggregate_active_swarm_metadata; + torrents_metrics.total_downloaded = total_downloaded; + // For backward compatibility we keep the `tcp4_connections_handled` and // `tcp6_connections_handled` metrics. They don't make sense for the HTTP // tracker, but we keep them for now. In new major versions we should remove @@ -138,14 +177,16 @@ mod tests { use bittorrent_http_tracker_core::event::sender::Broadcaster; use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; use bittorrent_http_tracker_core::statistics::repository::Repository; - use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; + use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_tracker_core::{self}; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use tokio::sync::RwLock; use torrust_tracker_configuration::Configuration; + use torrust_tracker_events::bus::SenderStatus; use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use torrust_tracker_test_helpers::configuration; + use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; use crate::statistics::metrics::Metrics; use crate::statistics::services::{get_metrics, TrackerMetrics}; @@ -157,8 +198,12 @@ mod tests { #[tokio::test] async fn the_statistics_service_should_return_the_tracker_metrics() { let config = tracker_configuration(); + let core_config = Arc::new(config.core.clone()); + + let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize(SenderStatus::Enabled)); + + let tracker_core_container = TrackerCoreContainer::initialize_from(&core_config, &torrent_repository_container.clone()); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); // HTTP core stats @@ -177,8 +222,11 @@ mod tests { let udp_server_stats_repository = Arc::new(torrust_udp_tracker_server::statistics::repository::Repository::new()); let tracker_metrics = get_metrics( - in_memory_torrent_repository.clone(), + core_config, + tracker_core_container.in_memory_torrent_repository.clone(), ban_service.clone(), + torrent_repository_container.stats_repository.clone(), + tracker_core_container.stats_repository.clone(), http_stats_repository.clone(), udp_server_stats_repository.clone(), ) diff --git a/packages/torrent-repository/src/statistics/mod.rs b/packages/torrent-repository/src/statistics/mod.rs index cfc252e34..ab5eb3f09 100644 --- a/packages/torrent-repository/src/statistics/mod.rs +++ b/packages/torrent-repository/src/statistics/mod.rs @@ -14,7 +14,7 @@ const TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL: &str = "torrent_repository_torren const TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL: &str = "torrent_repository_torrents_removed_total"; const TORRENT_REPOSITORY_TORRENTS_TOTAL: &str = "torrent_repository_torrents_total"; -const TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_torrents_downloads_total"; +pub const TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_torrents_downloads_total"; const TORRENT_REPOSITORY_TORRENTS_INACTIVE_TOTAL: &str = "torrent_repository_torrents_inactive_total"; // Peers metrics diff --git a/packages/tracker-core/src/statistics/mod.rs b/packages/tracker-core/src/statistics/mod.rs index ff8187379..0c421863f 100644 --- a/packages/tracker-core/src/statistics/mod.rs +++ b/packages/tracker-core/src/statistics/mod.rs @@ -10,7 +10,7 @@ use torrust_tracker_metrics::unit::Unit; // Torrent metrics -const TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL: &str = "tracker_core_persistent_torrents_downloads_total"; +pub const TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL: &str = "tracker_core_persistent_torrents_downloads_total"; #[must_use] pub fn describe_metrics() -> Metrics { From 8d3a6fe9c3ef05a914ac51437260191a7b3c4e47 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 28 May 2025 11:48:02 +0100 Subject: [PATCH 1150/1297] refactor: [#1543] extract methods --- .../src/v1/context/stats/resources.rs | 5 +- .../src/statistics/metrics.rs | 31 ++++- .../src/statistics/services.rs | 109 +++++++++++------- 3 files changed, 98 insertions(+), 47 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs index 8b6d639c8..08f83026f 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs @@ -134,9 +134,8 @@ impl From for LabeledStats { #[cfg(test)] mod tests { - use torrust_rest_tracker_api_core::statistics::metrics::Metrics; + use torrust_rest_tracker_api_core::statistics::metrics::{Metrics, TorrentsMetrics}; use torrust_rest_tracker_api_core::statistics::services::TrackerMetrics; - use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use super::Stats; @@ -145,7 +144,7 @@ mod tests { fn stats_resource_should_be_converted_from_tracker_metrics() { assert_eq!( Stats::from(TrackerMetrics { - torrents_metrics: AggregateActiveSwarmMetadata { + torrents_metrics: TorrentsMetrics { total_complete: 1, total_downloaded: 2, total_incomplete: 3, diff --git a/packages/rest-tracker-api-core/src/statistics/metrics.rs b/packages/rest-tracker-api-core/src/statistics/metrics.rs index 7e41cf713..ca556becf 100644 --- a/packages/rest-tracker-api-core/src/statistics/metrics.rs +++ b/packages/rest-tracker-api-core/src/statistics/metrics.rs @@ -1,4 +1,33 @@ -/// Metrics collected by the tracker. +use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; + +/// Metrics collected by the tracker at the swarm layer. +#[derive(Copy, Clone, Debug, PartialEq, Default)] +pub struct TorrentsMetrics { + /// Total number of peers that have ever completed downloading. + pub total_downloaded: u64, + + /// Total number of seeders. + pub total_complete: u64, + + /// Total number of leechers. + pub total_incomplete: u64, + + /// Total number of torrents. + pub total_torrents: u64, +} + +impl From for TorrentsMetrics { + fn from(value: AggregateActiveSwarmMetadata) -> Self { + Self { + total_downloaded: value.total_downloaded, + total_complete: value.total_complete, + total_incomplete: value.total_incomplete, + total_torrents: value.total_torrents, + } + } +} + +/// Metrics collected by the tracker at the delivery layer. /// /// - Number of connections handled /// - Number of `announce` requests handled diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index cc02f61e6..a899cb961 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -9,10 +9,10 @@ use torrust_tracker_configuration::Core; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric_collection::MetricCollection; use torrust_tracker_metrics::metric_name; -use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use torrust_tracker_torrent_repository::statistics::TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL; use torrust_udp_tracker_server::statistics as udp_server_statistics; +use super::metrics::TorrentsMetrics; use crate::statistics::metrics::Metrics; /// All the metrics collected by the tracker. @@ -21,7 +21,7 @@ pub struct TrackerMetrics { /// Domain level metrics. /// /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: AggregateActiveSwarmMetadata, + pub torrents_metrics: TorrentsMetrics, /// Application level metrics. Usage statistics/metrics. /// @@ -30,7 +30,6 @@ pub struct TrackerMetrics { } /// It returns all the [`TrackerMetrics`] -#[allow(deprecated)] pub async fn get_metrics( core_config: Arc, in_memory_torrent_repository: Arc, @@ -40,10 +39,25 @@ pub async fn get_metrics( http_stats_repository: Arc, udp_server_stats_repository: Arc, ) -> TrackerMetrics { + TrackerMetrics { + torrents_metrics: get_torrents_metrics( + core_config, + in_memory_torrent_repository, + torrent_repository_stats_repository, + tracker_core_stats_repository, + ) + .await, + protocol_metrics: get_protocol_metrics(ban_service, http_stats_repository, udp_server_stats_repository).await, + } +} + +async fn get_torrents_metrics( + core_config: Arc, + in_memory_torrent_repository: Arc, + torrent_repository_stats_repository: Arc, + tracker_core_stats_repository: Arc, +) -> TorrentsMetrics { let aggregate_active_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; - let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); - let http_stats = http_stats_repository.get_stats().await; - let udp_server_stats = udp_server_stats_repository.get_stats().await; let total_downloaded = if core_config.tracker_policy.persistent_torrent_completed_stat { let metrics = tracker_core_stats_repository.get_metrics().await; @@ -73,47 +87,57 @@ pub async fn get_metrics( } }; - let mut torrents_metrics = aggregate_active_swarm_metadata; + let mut torrents_metrics: TorrentsMetrics = aggregate_active_swarm_metadata.into(); torrents_metrics.total_downloaded = total_downloaded; + torrents_metrics +} + +#[allow(deprecated)] +async fn get_protocol_metrics( + ban_service: Arc>, + http_stats_repository: Arc, + udp_server_stats_repository: Arc, +) -> Metrics { + let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); + let http_stats = http_stats_repository.get_stats().await; + let udp_server_stats = udp_server_stats_repository.get_stats().await; + // For backward compatibility we keep the `tcp4_connections_handled` and // `tcp6_connections_handled` metrics. They don't make sense for the HTTP // tracker, but we keep them for now. In new major versions we should remove // them. - TrackerMetrics { - torrents_metrics, - protocol_metrics: Metrics { - // TCPv4 - tcp4_connections_handled: http_stats.tcp4_announces_handled + http_stats.tcp4_scrapes_handled, - tcp4_announces_handled: http_stats.tcp4_announces_handled, - tcp4_scrapes_handled: http_stats.tcp4_scrapes_handled, - // TCPv6 - tcp6_connections_handled: http_stats.tcp6_announces_handled + http_stats.tcp6_scrapes_handled, - tcp6_announces_handled: http_stats.tcp6_announces_handled, - tcp6_scrapes_handled: http_stats.tcp6_scrapes_handled, - // UDP - udp_requests_aborted: udp_server_stats.udp_requests_aborted, - udp_requests_banned: udp_server_stats.udp_requests_banned, - udp_banned_ips_total: udp_banned_ips_total as u64, - udp_avg_connect_processing_time_ns: udp_server_stats.udp_avg_connect_processing_time_ns, - udp_avg_announce_processing_time_ns: udp_server_stats.udp_avg_announce_processing_time_ns, - udp_avg_scrape_processing_time_ns: udp_server_stats.udp_avg_scrape_processing_time_ns, - // UDPv4 - udp4_requests: udp_server_stats.udp4_requests, - udp4_connections_handled: udp_server_stats.udp4_connections_handled, - udp4_announces_handled: udp_server_stats.udp4_announces_handled, - udp4_scrapes_handled: udp_server_stats.udp4_scrapes_handled, - udp4_responses: udp_server_stats.udp4_responses, - udp4_errors_handled: udp_server_stats.udp4_errors_handled, - // UDPv6 - udp6_requests: udp_server_stats.udp6_requests, - udp6_connections_handled: udp_server_stats.udp6_connections_handled, - udp6_announces_handled: udp_server_stats.udp6_announces_handled, - udp6_scrapes_handled: udp_server_stats.udp6_scrapes_handled, - udp6_responses: udp_server_stats.udp6_responses, - udp6_errors_handled: udp_server_stats.udp6_errors_handled, - }, + Metrics { + // TCPv4 + tcp4_connections_handled: http_stats.tcp4_announces_handled + http_stats.tcp4_scrapes_handled, + tcp4_announces_handled: http_stats.tcp4_announces_handled, + tcp4_scrapes_handled: http_stats.tcp4_scrapes_handled, + // TCPv6 + tcp6_connections_handled: http_stats.tcp6_announces_handled + http_stats.tcp6_scrapes_handled, + tcp6_announces_handled: http_stats.tcp6_announces_handled, + tcp6_scrapes_handled: http_stats.tcp6_scrapes_handled, + // UDP + udp_requests_aborted: udp_server_stats.udp_requests_aborted, + udp_requests_banned: udp_server_stats.udp_requests_banned, + udp_banned_ips_total: udp_banned_ips_total as u64, + udp_avg_connect_processing_time_ns: udp_server_stats.udp_avg_connect_processing_time_ns, + udp_avg_announce_processing_time_ns: udp_server_stats.udp_avg_announce_processing_time_ns, + udp_avg_scrape_processing_time_ns: udp_server_stats.udp_avg_scrape_processing_time_ns, + // UDPv4 + udp4_requests: udp_server_stats.udp4_requests, + udp4_connections_handled: udp_server_stats.udp4_connections_handled, + udp4_announces_handled: udp_server_stats.udp4_announces_handled, + udp4_scrapes_handled: udp_server_stats.udp4_scrapes_handled, + udp4_responses: udp_server_stats.udp4_responses, + udp4_errors_handled: udp_server_stats.udp4_errors_handled, + // UDPv6 + udp6_requests: udp_server_stats.udp6_requests, + udp6_connections_handled: udp_server_stats.udp6_connections_handled, + udp6_announces_handled: udp_server_stats.udp6_announces_handled, + udp6_scrapes_handled: udp_server_stats.udp6_scrapes_handled, + udp6_responses: udp_server_stats.udp6_responses, + udp6_errors_handled: udp_server_stats.udp6_errors_handled, } } @@ -184,11 +208,10 @@ mod tests { use tokio::sync::RwLock; use torrust_tracker_configuration::Configuration; use torrust_tracker_events::bus::SenderStatus; - use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use torrust_tracker_test_helpers::configuration; use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; - use crate::statistics::metrics::Metrics; + use crate::statistics::metrics::{Metrics, TorrentsMetrics}; use crate::statistics::services::{get_metrics, TrackerMetrics}; pub fn tracker_configuration() -> Configuration { @@ -235,7 +258,7 @@ mod tests { assert_eq!( tracker_metrics, TrackerMetrics { - torrents_metrics: AggregateActiveSwarmMetadata::default(), + torrents_metrics: TorrentsMetrics::default(), protocol_metrics: Metrics::default(), } ); From b0e744390603b94a00232f1e8d72e61010c2a24a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 28 May 2025 12:08:05 +0100 Subject: [PATCH 1151/1297] fix: [#1543] return always in API the downloads number from tracker-core The tracker-core always has the metric alhoutght it can be persisted or not. When it's not persisted, it contains the number of downloads during the session. On the other hand, the `torrent-repository` metri uses labels, so you have to sum all values for all labels to get the total. ``` torrent_repository_torrents_downloads_total{peer_role="seeder"} 1 tracker_core_persistent_torrents_downloads_total{} 1 ``` --- .../src/v1/context/stats/handlers.rs | 5 -- .../src/v1/context/stats/routes.rs | 2 - .../src/statistics/services.rs | 51 ++----------------- .../torrent-repository/src/statistics/mod.rs | 2 +- .../src/http/client/requests/announce.rs | 2 +- packages/tracker-core/src/statistics/mod.rs | 2 +- .../tracker-core/src/statistics/repository.rs | 21 +++++++- 7 files changed, 26 insertions(+), 59 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs index 463c81ac8..47bb5ad16 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs @@ -10,7 +10,6 @@ use bittorrent_udp_tracker_core::services::banning::BanService; use serde::Deserialize; use tokio::sync::RwLock; use torrust_rest_tracker_api_core::statistics::services::{get_labeled_metrics, get_metrics}; -use torrust_tracker_configuration::Core; use super::responses::{labeled_metrics_response, labeled_stats_response, metrics_response, stats_response}; @@ -41,10 +40,8 @@ pub struct QueryParams { #[allow(clippy::type_complexity)] pub async fn get_stats_handler( State(state): State<( - Arc, Arc, Arc>, - Arc, Arc, Arc, Arc, @@ -57,8 +54,6 @@ pub async fn get_stats_handler( state.2.clone(), state.3.clone(), state.4.clone(), - state.5.clone(), - state.6.clone(), ) .await; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs index 3be266d3a..a573b764a 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs @@ -17,10 +17,8 @@ pub fn add(prefix: &str, router: Router, http_api_container: &Arc, in_memory_torrent_repository: Arc, ban_service: Arc>, - torrent_repository_stats_repository: Arc, tracker_core_stats_repository: Arc, http_stats_repository: Arc, udp_server_stats_repository: Arc, ) -> TrackerMetrics { TrackerMetrics { - torrents_metrics: get_torrents_metrics( - core_config, - in_memory_torrent_repository, - torrent_repository_stats_repository, - tracker_core_stats_repository, - ) - .await, + torrents_metrics: get_torrents_metrics(in_memory_torrent_repository, tracker_core_stats_repository).await, protocol_metrics: get_protocol_metrics(ban_service, http_stats_repository, udp_server_stats_repository).await, } } async fn get_torrents_metrics( - core_config: Arc, in_memory_torrent_repository: Arc, - torrent_repository_stats_repository: Arc, + tracker_core_stats_repository: Arc, ) -> TorrentsMetrics { let aggregate_active_swarm_metadata = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; - let total_downloaded = if core_config.tracker_policy.persistent_torrent_completed_stat { - let metrics = tracker_core_stats_repository.get_metrics().await; - - let downloads = metrics.metric_collection.get_counter_value( - &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), - &LabelSet::default(), - ); - - if let Some(downloads) = downloads { - downloads.value() - } else { - 0 - } - } else { - let metrics = torrent_repository_stats_repository.get_metrics().await; - - let downloads = metrics.metric_collection.get_counter_value( - &metric_name!(TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL), - &LabelSet::default(), - ); - - if let Some(downloads) = downloads { - downloads.value() - } else { - 0 - } - }; - let mut torrents_metrics: TorrentsMetrics = aggregate_active_swarm_metadata.into(); - torrents_metrics.total_downloaded = total_downloaded; + torrents_metrics.total_downloaded = tracker_core_stats_repository.get_torrents_downloads_total().await; torrents_metrics } @@ -152,7 +110,6 @@ pub struct TrackerLabeledMetrics { /// /// Will panic if the metrics cannot be merged. This could happen if the /// packages are producing duplicate metric names, for example. -#[allow(deprecated)] pub async fn get_labeled_metrics( in_memory_torrent_repository: Arc, ban_service: Arc>, @@ -245,10 +202,8 @@ mod tests { let udp_server_stats_repository = Arc::new(torrust_udp_tracker_server::statistics::repository::Repository::new()); let tracker_metrics = get_metrics( - core_config, tracker_core_container.in_memory_torrent_repository.clone(), ban_service.clone(), - torrent_repository_container.stats_repository.clone(), tracker_core_container.stats_repository.clone(), http_stats_repository.clone(), udp_server_stats_repository.clone(), diff --git a/packages/torrent-repository/src/statistics/mod.rs b/packages/torrent-repository/src/statistics/mod.rs index ab5eb3f09..cfc252e34 100644 --- a/packages/torrent-repository/src/statistics/mod.rs +++ b/packages/torrent-repository/src/statistics/mod.rs @@ -14,7 +14,7 @@ const TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL: &str = "torrent_repository_torren const TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL: &str = "torrent_repository_torrents_removed_total"; const TORRENT_REPOSITORY_TORRENTS_TOTAL: &str = "torrent_repository_torrents_total"; -pub const TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_torrents_downloads_total"; +const TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_torrents_downloads_total"; const TORRENT_REPOSITORY_TORRENTS_INACTIVE_TOTAL: &str = "torrent_repository_torrents_inactive_total"; // Peers metrics diff --git a/packages/tracker-client/src/http/client/requests/announce.rs b/packages/tracker-client/src/http/client/requests/announce.rs index 29b5d1221..87bdbad52 100644 --- a/packages/tracker-client/src/http/client/requests/announce.rs +++ b/packages/tracker-client/src/http/client/requests/announce.rs @@ -102,7 +102,7 @@ impl QueryBuilder { peer_id: PeerId(*b"-qB00000000000000001").0, port: 17548, left: 0, - event: Some(Event::Completed), + event: Some(Event::Started), compact: Some(Compact::NotAccepted), }; Self { diff --git a/packages/tracker-core/src/statistics/mod.rs b/packages/tracker-core/src/statistics/mod.rs index 0c421863f..ff8187379 100644 --- a/packages/tracker-core/src/statistics/mod.rs +++ b/packages/tracker-core/src/statistics/mod.rs @@ -10,7 +10,7 @@ use torrust_tracker_metrics::unit::Unit; // Torrent metrics -pub const TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL: &str = "tracker_core_persistent_torrents_downloads_total"; +const TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL: &str = "tracker_core_persistent_torrents_downloads_total"; #[must_use] pub fn describe_metrics() -> Metrics { diff --git a/packages/tracker-core/src/statistics/repository.rs b/packages/tracker-core/src/statistics/repository.rs index dd0ebebe7..21b1da7f2 100644 --- a/packages/tracker-core/src/statistics/repository.rs +++ b/packages/tracker-core/src/statistics/repository.rs @@ -4,10 +4,11 @@ use tokio::sync::{RwLock, RwLockReadGuard}; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; use torrust_tracker_metrics::metric_collection::Error; +use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use super::describe_metrics; use super::metrics::Metrics; +use super::{describe_metrics, TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL}; /// A repository for the torrent repository metrics. #[derive(Clone)] @@ -154,4 +155,22 @@ impl Repository { result } + + /// Get the total number of torrent downloads. + /// + /// The value is persisted in database if persistence for downloads metrics is enabled. + pub async fn get_torrents_downloads_total(&self) -> u64 { + let metrics = self.get_metrics().await; + + let downloads = metrics.metric_collection.get_counter_value( + &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), + &LabelSet::default(), + ); + + if let Some(downloads) = downloads { + downloads.value() + } else { + 0 + } + } } From 43c71793aaba1feba5d246c42db703b443721e60 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 28 May 2025 12:15:26 +0100 Subject: [PATCH 1152/1297] refactor: [#1543] rename Metrics to ProtocolMetrics --- .../src/v1/context/stats/resources.rs | 4 ++-- .../rest-tracker-api-core/src/statistics/metrics.rs | 2 +- .../rest-tracker-api-core/src/statistics/services.rs | 12 ++++++------ 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs index 08f83026f..ece50383b 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/resources.rs @@ -134,7 +134,7 @@ impl From for LabeledStats { #[cfg(test)] mod tests { - use torrust_rest_tracker_api_core::statistics::metrics::{Metrics, TorrentsMetrics}; + use torrust_rest_tracker_api_core::statistics::metrics::{ProtocolMetrics, TorrentsMetrics}; use torrust_rest_tracker_api_core::statistics::services::TrackerMetrics; use super::Stats; @@ -150,7 +150,7 @@ mod tests { total_incomplete: 3, total_torrents: 4 }, - protocol_metrics: Metrics { + protocol_metrics: ProtocolMetrics { // TCP tcp4_connections_handled: 5, tcp4_announces_handled: 6, diff --git a/packages/rest-tracker-api-core/src/statistics/metrics.rs b/packages/rest-tracker-api-core/src/statistics/metrics.rs index ca556becf..ecdecd130 100644 --- a/packages/rest-tracker-api-core/src/statistics/metrics.rs +++ b/packages/rest-tracker-api-core/src/statistics/metrics.rs @@ -36,7 +36,7 @@ impl From for TorrentsMetrics { /// These metrics are collected for each connection type: UDP and HTTP /// and also for each IP version used by the peers: IPv4 and IPv6. #[derive(Debug, PartialEq, Default)] -pub struct Metrics { +pub struct ProtocolMetrics { /// Total number of TCP (HTTP tracker) connections from IPv4 peers. /// Since the HTTP tracker spec does not require a handshake, this metric /// increases for every HTTP request. diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index d5b68c274..9a2eb3667 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -8,7 +8,7 @@ use torrust_tracker_metrics::metric_collection::MetricCollection; use torrust_udp_tracker_server::statistics as udp_server_statistics; use super::metrics::TorrentsMetrics; -use crate::statistics::metrics::Metrics; +use crate::statistics::metrics::ProtocolMetrics; /// All the metrics collected by the tracker. #[derive(Debug, PartialEq)] @@ -21,7 +21,7 @@ pub struct TrackerMetrics { /// Application level metrics. Usage statistics/metrics. /// /// Metrics about how the tracker is been used (number of udp announce requests, number of http scrape requests, etcetera) - pub protocol_metrics: Metrics, + pub protocol_metrics: ProtocolMetrics, } /// It returns all the [`TrackerMetrics`] @@ -56,7 +56,7 @@ async fn get_protocol_metrics( ban_service: Arc>, http_stats_repository: Arc, udp_server_stats_repository: Arc, -) -> Metrics { +) -> ProtocolMetrics { let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); let http_stats = http_stats_repository.get_stats().await; let udp_server_stats = udp_server_stats_repository.get_stats().await; @@ -66,7 +66,7 @@ async fn get_protocol_metrics( // tracker, but we keep them for now. In new major versions we should remove // them. - Metrics { + ProtocolMetrics { // TCPv4 tcp4_connections_handled: http_stats.tcp4_announces_handled + http_stats.tcp4_scrapes_handled, tcp4_announces_handled: http_stats.tcp4_announces_handled, @@ -168,7 +168,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; - use crate::statistics::metrics::{Metrics, TorrentsMetrics}; + use crate::statistics::metrics::{ProtocolMetrics, TorrentsMetrics}; use crate::statistics::services::{get_metrics, TrackerMetrics}; pub fn tracker_configuration() -> Configuration { @@ -214,7 +214,7 @@ mod tests { tracker_metrics, TrackerMetrics { torrents_metrics: TorrentsMetrics::default(), - protocol_metrics: Metrics::default(), + protocol_metrics: ProtocolMetrics::default(), } ); } From 92242f8b54e7b0091b053a3ab8c110638b51a7a5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 28 May 2025 12:21:08 +0100 Subject: [PATCH 1153/1297] fix: [#1543] Remove peerless torrents when it's enabled in the tracker policy There were not being removed when stats was enabled becuase the tracker was counting downloads only from the active swarms. Now the API exposed metric (global downldoads) is not taken from the in-memory data structrure unless stats persistence is disabled. In that case, the global total would be per session (since the tracker started), and reset when the tracker restarts. --- packages/torrent-repository/src/swarm.rs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/packages/torrent-repository/src/swarm.rs b/packages/torrent-repository/src/swarm.rs index 84e1f2da4..362fc6153 100644 --- a/packages/torrent-repository/src/swarm.rs +++ b/packages/torrent-repository/src/swarm.rs @@ -201,13 +201,7 @@ impl Swarm { /// Returns true if the swarm should be removed according to the retention /// policy. fn should_be_removed(&self, policy: &TrackerPolicy) -> bool { - // If the policy is to remove peerless torrents and the swarm is empty (no peers), - (policy.remove_peerless_torrents && self.is_empty()) - // but not when the policy is to persist torrent stats and the - // torrent has been downloaded at least once. - // (because the only way to store the counter is to keep the swarm in memory. - // See https://github.com/torrust/torrust-tracker/issues/1502) - && !(policy.persistent_torrent_completed_stat && self.metadata().downloaded > 0) + policy.remove_peerless_torrents && self.is_empty() } fn update_metadata_on_insert(&mut self, added_peer: &Arc) { From 55149bcf97ad261e0ef36334520ce4cc73082ecc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 29 May 2025 10:16:12 +0100 Subject: [PATCH 1154/1297] refactor: [#1519] rename dir torrent-repository --- Cargo.toml | 2 +- packages/axum-http-tracker-server/Cargo.toml | 2 +- packages/axum-rest-tracker-api-server/Cargo.toml | 2 +- packages/http-tracker-core/Cargo.toml | 2 +- packages/rest-tracker-api-core/Cargo.toml | 2 +- .../.gitignore | 0 .../Cargo.toml | 0 .../README.md | 0 .../src/container.rs | 0 .../src/event.rs | 0 .../src/lib.rs | 0 .../src/statistics/activity_metrics_updater.rs | 0 .../src/statistics/event/handler.rs | 0 .../src/statistics/event/listener.rs | 0 .../src/statistics/event/mod.rs | 0 .../src/statistics/metrics.rs | 0 .../src/statistics/mod.rs | 0 .../src/statistics/repository.rs | 0 .../src/swarm.rs | 0 .../src/swarms.rs | 0 packages/torrent-repository-benchmarking/README.md | 2 +- packages/tracker-core/Cargo.toml | 2 +- packages/udp-tracker-core/Cargo.toml | 2 +- packages/udp-tracker-server/Cargo.toml | 2 +- 24 files changed, 9 insertions(+), 9 deletions(-) rename packages/{torrent-repository => swarm-coordination-registry}/.gitignore (100%) rename packages/{torrent-repository => swarm-coordination-registry}/Cargo.toml (100%) rename packages/{torrent-repository => swarm-coordination-registry}/README.md (100%) rename packages/{torrent-repository => swarm-coordination-registry}/src/container.rs (100%) rename packages/{torrent-repository => swarm-coordination-registry}/src/event.rs (100%) rename packages/{torrent-repository => swarm-coordination-registry}/src/lib.rs (100%) rename packages/{torrent-repository => swarm-coordination-registry}/src/statistics/activity_metrics_updater.rs (100%) rename packages/{torrent-repository => swarm-coordination-registry}/src/statistics/event/handler.rs (100%) rename packages/{torrent-repository => swarm-coordination-registry}/src/statistics/event/listener.rs (100%) rename packages/{torrent-repository => swarm-coordination-registry}/src/statistics/event/mod.rs (100%) rename packages/{torrent-repository => swarm-coordination-registry}/src/statistics/metrics.rs (100%) rename packages/{torrent-repository => swarm-coordination-registry}/src/statistics/mod.rs (100%) rename packages/{torrent-repository => swarm-coordination-registry}/src/statistics/repository.rs (100%) rename packages/{torrent-repository => swarm-coordination-registry}/src/swarm.rs (100%) rename packages/{torrent-repository => swarm-coordination-registry}/src/swarms.rs (100%) diff --git a/Cargo.toml b/Cargo.toml index 219701d03..3e6e3e073 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,7 +55,7 @@ torrust-rest-tracker-api-core = { version = "3.0.0-develop", path = "packages/re torrust-server-lib = { version = "3.0.0-develop", path = "packages/server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "packages/torrent-repository" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "packages/swarm-coordination-registry" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "packages/udp-tracker-server" } tracing = "0" tracing-subscriber = { version = "0", features = ["json"] } diff --git a/packages/axum-http-tracker-server/Cargo.toml b/packages/axum-http-tracker-server/Cargo.toml index 81831a614..51283ee01 100644 --- a/packages/axum-http-tracker-server/Cargo.toml +++ b/packages/axum-http-tracker-server/Cargo.toml @@ -33,7 +33,7 @@ torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" diff --git a/packages/axum-rest-tracker-api-server/Cargo.toml b/packages/axum-rest-tracker-api-server/Cargo.toml index 296f77d61..558dbf6c1 100644 --- a/packages/axum-rest-tracker-api-server/Cargo.toml +++ b/packages/axum-rest-tracker-api-server/Cargo.toml @@ -39,7 +39,7 @@ torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } diff --git a/packages/http-tracker-core/Cargo.toml b/packages/http-tracker-core/Cargo.toml index 37b540e39..008aa92c6 100644 --- a/packages/http-tracker-core/Cargo.toml +++ b/packages/http-tracker-core/Cargo.toml @@ -28,7 +28,7 @@ torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configur torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } tracing = "0" [dev-dependencies] diff --git a/packages/rest-tracker-api-core/Cargo.toml b/packages/rest-tracker-api-core/Cargo.toml index 8cfe601b2..9a086ad19 100644 --- a/packages/rest-tracker-api-core/Cargo.toml +++ b/packages/rest-tracker-api-core/Cargo.toml @@ -21,7 +21,7 @@ tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } [dev-dependencies] diff --git a/packages/torrent-repository/.gitignore b/packages/swarm-coordination-registry/.gitignore similarity index 100% rename from packages/torrent-repository/.gitignore rename to packages/swarm-coordination-registry/.gitignore diff --git a/packages/torrent-repository/Cargo.toml b/packages/swarm-coordination-registry/Cargo.toml similarity index 100% rename from packages/torrent-repository/Cargo.toml rename to packages/swarm-coordination-registry/Cargo.toml diff --git a/packages/torrent-repository/README.md b/packages/swarm-coordination-registry/README.md similarity index 100% rename from packages/torrent-repository/README.md rename to packages/swarm-coordination-registry/README.md diff --git a/packages/torrent-repository/src/container.rs b/packages/swarm-coordination-registry/src/container.rs similarity index 100% rename from packages/torrent-repository/src/container.rs rename to packages/swarm-coordination-registry/src/container.rs diff --git a/packages/torrent-repository/src/event.rs b/packages/swarm-coordination-registry/src/event.rs similarity index 100% rename from packages/torrent-repository/src/event.rs rename to packages/swarm-coordination-registry/src/event.rs diff --git a/packages/torrent-repository/src/lib.rs b/packages/swarm-coordination-registry/src/lib.rs similarity index 100% rename from packages/torrent-repository/src/lib.rs rename to packages/swarm-coordination-registry/src/lib.rs diff --git a/packages/torrent-repository/src/statistics/activity_metrics_updater.rs b/packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs similarity index 100% rename from packages/torrent-repository/src/statistics/activity_metrics_updater.rs rename to packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs diff --git a/packages/torrent-repository/src/statistics/event/handler.rs b/packages/swarm-coordination-registry/src/statistics/event/handler.rs similarity index 100% rename from packages/torrent-repository/src/statistics/event/handler.rs rename to packages/swarm-coordination-registry/src/statistics/event/handler.rs diff --git a/packages/torrent-repository/src/statistics/event/listener.rs b/packages/swarm-coordination-registry/src/statistics/event/listener.rs similarity index 100% rename from packages/torrent-repository/src/statistics/event/listener.rs rename to packages/swarm-coordination-registry/src/statistics/event/listener.rs diff --git a/packages/torrent-repository/src/statistics/event/mod.rs b/packages/swarm-coordination-registry/src/statistics/event/mod.rs similarity index 100% rename from packages/torrent-repository/src/statistics/event/mod.rs rename to packages/swarm-coordination-registry/src/statistics/event/mod.rs diff --git a/packages/torrent-repository/src/statistics/metrics.rs b/packages/swarm-coordination-registry/src/statistics/metrics.rs similarity index 100% rename from packages/torrent-repository/src/statistics/metrics.rs rename to packages/swarm-coordination-registry/src/statistics/metrics.rs diff --git a/packages/torrent-repository/src/statistics/mod.rs b/packages/swarm-coordination-registry/src/statistics/mod.rs similarity index 100% rename from packages/torrent-repository/src/statistics/mod.rs rename to packages/swarm-coordination-registry/src/statistics/mod.rs diff --git a/packages/torrent-repository/src/statistics/repository.rs b/packages/swarm-coordination-registry/src/statistics/repository.rs similarity index 100% rename from packages/torrent-repository/src/statistics/repository.rs rename to packages/swarm-coordination-registry/src/statistics/repository.rs diff --git a/packages/torrent-repository/src/swarm.rs b/packages/swarm-coordination-registry/src/swarm.rs similarity index 100% rename from packages/torrent-repository/src/swarm.rs rename to packages/swarm-coordination-registry/src/swarm.rs diff --git a/packages/torrent-repository/src/swarms.rs b/packages/swarm-coordination-registry/src/swarms.rs similarity index 100% rename from packages/torrent-repository/src/swarms.rs rename to packages/swarm-coordination-registry/src/swarms.rs diff --git a/packages/torrent-repository-benchmarking/README.md b/packages/torrent-repository-benchmarking/README.md index f248ca0da..a0556a58f 100644 --- a/packages/torrent-repository-benchmarking/README.md +++ b/packages/torrent-repository-benchmarking/README.md @@ -1,4 +1,4 @@ -# Torrust Tracker Torrent Repository Benchmarking +# Torrust Tracker Swarm Coordination Registry Benchmarking A library to runt benchmarking for different implementations of a repository of torrents files and their peers. Torrent repositories are used by the [Torrust Tracker](https://github.com/torrust/torrust-tracker). diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index a2d08dfa0..8c9bf7769 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -33,7 +33,7 @@ torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } tracing = "0" [dev-dependencies] diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml index 9a27ec826..2933a7e70 100644 --- a/packages/udp-tracker-core/Cargo.toml +++ b/packages/udp-tracker-core/Cargo.toml @@ -33,7 +33,7 @@ torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configur torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } tracing = "0" zerocopy = "0.7" diff --git a/packages/udp-tracker-server/Cargo.toml b/packages/udp-tracker-server/Cargo.toml index a0c129acb..396dc0805 100644 --- a/packages/udp-tracker-server/Cargo.toml +++ b/packages/udp-tracker-server/Cargo.toml @@ -33,7 +33,7 @@ torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../torrent-repository" } +torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } tracing = "0" url = { version = "2", features = ["serde"] } uuid = { version = "1", features = ["v4"] } From 2b7a25163a6a0d21aa0defe9e2999be1c5105ae0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 29 May 2025 10:42:57 +0100 Subject: [PATCH 1155/1297] refactor: [#1519] rename crate torrust-tracker-torrent-repository to torrust-tracker-swarm-coordination-registry --- .github/workflows/deployment.yaml | 2 +- Cargo.lock | 40 +++++++++---------- Cargo.toml | 2 +- packages/axum-http-tracker-server/Cargo.toml | 2 +- .../src/environment.rs | 2 +- .../axum-http-tracker-server/src/server.rs | 2 +- .../axum-rest-tracker-api-server/Cargo.toml | 2 +- .../src/environment.rs | 2 +- .../src/v1/context/stats/handlers.rs | 2 +- packages/http-tracker-core/Cargo.toml | 2 +- packages/http-tracker-core/src/container.rs | 2 +- packages/rest-tracker-api-core/Cargo.toml | 2 +- .../rest-tracker-api-core/src/container.rs | 2 +- .../src/statistics/services.rs | 4 +- .../swarm-coordination-registry/Cargo.toml | 2 +- packages/tracker-core/Cargo.toml | 2 +- packages/tracker-core/src/container.rs | 2 +- .../src/statistics/event/handler.rs | 2 +- .../src/statistics/event/listener.rs | 2 +- packages/tracker-core/src/torrent/manager.rs | 2 +- .../src/torrent/repository/in_memory.rs | 2 +- .../tracker-core/tests/common/test_env.rs | 6 +-- packages/udp-tracker-core/Cargo.toml | 2 +- packages/udp-tracker-core/src/container.rs | 2 +- packages/udp-tracker-server/Cargo.toml | 2 +- .../udp-tracker-server/src/environment.rs | 2 +- .../jobs/activity_metrics_updater.rs | 2 +- src/bootstrap/jobs/torrent_repository.rs | 2 +- src/container.rs | 2 +- 29 files changed, 50 insertions(+), 52 deletions(-) diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index d62b4bbcc..4e8fd579b 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -77,7 +77,7 @@ jobs: cargo publish -p torrust-tracker-located-error cargo publish -p torrust-tracker-metrics cargo publish -p torrust-tracker-primitives + cargo publish -p torrust-tracker-swarm-coordination-registry cargo publish -p torrust-tracker-test-helpers cargo publish -p torrust-tracker-torrent-benchmarking - cargo publish -p torrust-tracker-torrent-repository cargo publish -p torrust-udp-tracker-server diff --git a/Cargo.lock b/Cargo.lock index 009b1e458..ecf178a59 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -592,8 +592,8 @@ dependencies = [ "torrust-tracker-events", "torrust-tracker-metrics", "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", "torrust-tracker-test-helpers", - "torrust-tracker-torrent-repository", "tracing", ] @@ -680,8 +680,8 @@ dependencies = [ "torrust-tracker-located-error", "torrust-tracker-metrics", "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", "torrust-tracker-test-helpers", - "torrust-tracker-torrent-repository", "tracing", "url", ] @@ -710,8 +710,8 @@ dependencies = [ "torrust-tracker-events", "torrust-tracker-metrics", "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", "torrust-tracker-test-helpers", - "torrust-tracker-torrent-repository", "tracing", "zerocopy 0.7.35", ] @@ -4555,8 +4555,8 @@ dependencies = [ "torrust-tracker-configuration", "torrust-tracker-events", "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", "torrust-tracker-test-helpers", - "torrust-tracker-torrent-repository", "tower", "tower-http", "tracing", @@ -4595,8 +4595,8 @@ dependencies = [ "torrust-tracker-configuration", "torrust-tracker-metrics", "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", "torrust-tracker-test-helpers", - "torrust-tracker-torrent-repository", "torrust-udp-tracker-server", "tower", "tower-http", @@ -4649,8 +4649,8 @@ dependencies = [ "torrust-tracker-events", "torrust-tracker-metrics", "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", "torrust-tracker-test-helpers", - "torrust-tracker-torrent-repository", "torrust-udp-tracker-server", ] @@ -4697,8 +4697,8 @@ dependencies = [ "torrust-server-lib", "torrust-tracker-clock", "torrust-tracker-configuration", + "torrust-tracker-swarm-coordination-registry", "torrust-tracker-test-helpers", - "torrust-tracker-torrent-repository", "torrust-udp-tracker-server", "tracing", "tracing-subscriber", @@ -4819,17 +4819,7 @@ dependencies = [ ] [[package]] -name = "torrust-tracker-test-helpers" -version = "3.0.0-develop" -dependencies = [ - "rand 0.9.1", - "torrust-tracker-configuration", - "tracing", - "tracing-subscriber", -] - -[[package]] -name = "torrust-tracker-torrent-repository" +name = "torrust-tracker-swarm-coordination-registry" version = "3.0.0-develop" dependencies = [ "aquatic_udp_protocol", @@ -4840,7 +4830,7 @@ dependencies = [ "crossbeam-skiplist", "futures", "mockall", - "rand 0.9.1", + "rand 0.8.5", "rstest", "serde", "thiserror 2.0.12", @@ -4854,6 +4844,16 @@ dependencies = [ "tracing", ] +[[package]] +name = "torrust-tracker-test-helpers" +version = "3.0.0-develop" +dependencies = [ + "rand 0.9.1", + "torrust-tracker-configuration", + "tracing", + "tracing-subscriber", +] + [[package]] name = "torrust-tracker-torrent-repository-benchmarking" version = "3.0.0-develop" @@ -4900,8 +4900,8 @@ dependencies = [ "torrust-tracker-located-error", "torrust-tracker-metrics", "torrust-tracker-primitives", + "torrust-tracker-swarm-coordination-registry", "torrust-tracker-test-helpers", - "torrust-tracker-torrent-repository", "tracing", "url", "uuid", diff --git a/Cargo.toml b/Cargo.toml index 3e6e3e073..976176155 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,7 +55,7 @@ torrust-rest-tracker-api-core = { version = "3.0.0-develop", path = "packages/re torrust-server-lib = { version = "3.0.0-develop", path = "packages/server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "packages/clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/configuration" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "packages/swarm-coordination-registry" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "packages/swarm-coordination-registry" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "packages/udp-tracker-server" } tracing = "0" tracing-subscriber = { version = "0", features = ["json"] } diff --git a/packages/axum-http-tracker-server/Cargo.toml b/packages/axum-http-tracker-server/Cargo.toml index 51283ee01..fa195489c 100644 --- a/packages/axum-http-tracker-server/Cargo.toml +++ b/packages/axum-http-tracker-server/Cargo.toml @@ -33,7 +33,7 @@ torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } tracing = "0" diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index 0c1431db5..54c6b7767 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -10,7 +10,7 @@ use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_primitives::peer; -use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; use crate::server::{HttpServer, Launcher, Running, Stopped}; diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index f7d1ed7ea..b8ece8086 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -259,8 +259,8 @@ mod tests { use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; + use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; use crate::server::{HttpServer, Launcher}; diff --git a/packages/axum-rest-tracker-api-server/Cargo.toml b/packages/axum-rest-tracker-api-server/Cargo.toml index 558dbf6c1..9493b8693 100644 --- a/packages/axum-rest-tracker-api-server/Cargo.toml +++ b/packages/axum-rest-tracker-api-server/Cargo.toml @@ -39,7 +39,7 @@ torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } tower = { version = "0", features = ["timeout"] } tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index be93a8723..6be4cc53c 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -12,7 +12,7 @@ use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_primitives::peer; -use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use crate::server::{ApiServer, Launcher, Running, Stopped}; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs index 47bb5ad16..b907b861a 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs @@ -77,7 +77,7 @@ pub async fn get_metrics_handler( State(state): State<( Arc, Arc>, - Arc, + Arc, Arc, Arc, Arc, diff --git a/packages/http-tracker-core/Cargo.toml b/packages/http-tracker-core/Cargo.toml index 008aa92c6..45af59baa 100644 --- a/packages/http-tracker-core/Cargo.toml +++ b/packages/http-tracker-core/Cargo.toml @@ -28,7 +28,7 @@ torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configur torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } tracing = "0" [dev-dependencies] diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index f063c0061..35f75e1fe 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use bittorrent_tracker_core::container::TrackerCoreContainer; use torrust_tracker_configuration::{Core, HttpTracker}; -use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; diff --git a/packages/rest-tracker-api-core/Cargo.toml b/packages/rest-tracker-api-core/Cargo.toml index 9a086ad19..cc8eda903 100644 --- a/packages/rest-tracker-api-core/Cargo.toml +++ b/packages/rest-tracker-api-core/Cargo.toml @@ -21,7 +21,7 @@ tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } [dev-dependencies] diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs index 1c4a08e26..f76c2ece3 100644 --- a/packages/rest-tracker-api-core/src/container.rs +++ b/packages/rest-tracker-api-core/src/container.rs @@ -7,7 +7,7 @@ use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self}; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; -use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; pub struct TrackerHttpApiCoreContainer { diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 9a2eb3667..56536a02f 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -113,7 +113,7 @@ pub struct TrackerLabeledMetrics { pub async fn get_labeled_metrics( in_memory_torrent_repository: Arc, ban_service: Arc>, - swarms_stats_repository: Arc, + swarms_stats_repository: Arc, tracker_core_stats_repository: Arc, http_stats_repository: Arc, udp_stats_repository: Arc, @@ -165,8 +165,8 @@ mod tests { use tokio::sync::RwLock; use torrust_tracker_configuration::Configuration; use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; use torrust_tracker_test_helpers::configuration; - use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; use crate::statistics::metrics::{ProtocolMetrics, TorrentsMetrics}; use crate::statistics::services::{get_metrics, TrackerMetrics}; diff --git a/packages/swarm-coordination-registry/Cargo.toml b/packages/swarm-coordination-registry/Cargo.toml index 510a59e9d..074562a47 100644 --- a/packages/swarm-coordination-registry/Cargo.toml +++ b/packages/swarm-coordination-registry/Cargo.toml @@ -1,7 +1,7 @@ [package] description = "A library that provides a repository of torrents files and their peers." keywords = ["library", "repository", "torrents"] -name = "torrust-tracker-torrent-repository" +name = "torrust-tracker-swarm-coordination-registry" readme = "README.md" authors.workspace = true diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index 8c9bf7769..f04a3b89b 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -33,7 +33,7 @@ torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } tracing = "0" [dev-dependencies] diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs index 02af67118..949761553 100644 --- a/packages/tracker-core/src/container.rs +++ b/packages/tracker-core/src/container.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use torrust_tracker_configuration::Core; -use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; use crate::announce_handler::AnnounceHandler; use crate::authentication::handler::KeysHandler; diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs index 0909dc184..9a5182f25 100644 --- a/packages/tracker-core/src/statistics/event/handler.rs +++ b/packages/tracker-core/src/statistics/event/handler.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use torrust_tracker_torrent_repository::event::Event; +use torrust_tracker_swarm_coordination_registry::event::Event; use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use crate::statistics::repository::Repository; diff --git a/packages/tracker-core/src/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs index 2702aa858..d3beaf41f 100644 --- a/packages/tracker-core/src/statistics/event/listener.rs +++ b/packages/tracker-core/src/statistics/event/listener.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; use torrust_tracker_events::receiver::RecvError; -use torrust_tracker_torrent_repository::event::receiver::Receiver; +use torrust_tracker_swarm_coordination_registry::event::receiver::Receiver; use super::handler::handle_event; use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index 766fa5c4a..cbdf01193 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -148,7 +148,7 @@ mod tests { use std::sync::Arc; use torrust_tracker_configuration::Core; - use torrust_tracker_torrent_repository::Swarms; + use torrust_tracker_swarm_coordination_registry::Swarms; use super::{DatabaseDownloadsMetricRepository, TorrentsManager}; use crate::databases::setup::initialize_database; diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index cc873726d..47b34ad26 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -7,7 +7,7 @@ use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; -use torrust_tracker_torrent_repository::{SwarmHandle, Swarms}; +use torrust_tracker_swarm_coordination_registry::{SwarmHandle, Swarms}; /// In-memory repository for torrent entries. /// diff --git a/packages/tracker-core/tests/common/test_env.rs b/packages/tracker-core/tests/common/test_env.rs index 2aafbbbad..64bdcaad8 100644 --- a/packages/tracker-core/tests/common/test_env.rs +++ b/packages/tracker-core/tests/common/test_env.rs @@ -14,7 +14,7 @@ use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; pub struct TestEnv { pub torrent_repository_container: Arc, @@ -67,11 +67,10 @@ impl TestEnv { async fn run_jobs(&self) { let mut jobs = vec![]; - let job = torrust_tracker_torrent_repository::statistics::event::listener::run_event_listener( + let job = torrust_tracker_swarm_coordination_registry::statistics::event::listener::run_event_listener( self.torrent_repository_container.event_bus.receiver(), &self.torrent_repository_container.stats_repository, ); - jobs.push(job); let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( @@ -83,7 +82,6 @@ impl TestEnv { .tracker_policy .persistent_torrent_completed_stat, ); - jobs.push(job); // Give the event listeners some time to start diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml index 2933a7e70..290c5fbfd 100644 --- a/packages/udp-tracker-core/Cargo.toml +++ b/packages/udp-tracker-core/Cargo.toml @@ -33,7 +33,7 @@ torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configur torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } tracing = "0" zerocopy = "0.7" diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index 07a8a09ef..c4be395fc 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use bittorrent_tracker_core::container::TrackerCoreContainer; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, UdpTracker}; -use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; diff --git a/packages/udp-tracker-server/Cargo.toml b/packages/udp-tracker-server/Cargo.toml index 396dc0805..72fa520ba 100644 --- a/packages/udp-tracker-server/Cargo.toml +++ b/packages/udp-tracker-server/Cargo.toml @@ -33,7 +33,7 @@ torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -torrust-tracker-torrent-repository = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } +torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } tracing = "0" url = { version = "2", features = ["serde"] } uuid = { version = "1", features = ["v4"] } diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 94a166e4e..3f479a02d 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -8,7 +8,7 @@ use tokio::task::JoinHandle; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_primitives::peer; -use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; use crate::container::UdpTrackerServerContainer; use crate::server::spawner::Spawner; diff --git a/src/bootstrap/jobs/activity_metrics_updater.rs b/src/bootstrap/jobs/activity_metrics_updater.rs index 7411c05cf..9813fed65 100644 --- a/src/bootstrap/jobs/activity_metrics_updater.rs +++ b/src/bootstrap/jobs/activity_metrics_updater.rs @@ -11,7 +11,7 @@ use crate::CurrentClock; #[must_use] pub fn start_job(config: &Configuration, app_container: &Arc) -> JoinHandle<()> { - torrust_tracker_torrent_repository::statistics::activity_metrics_updater::start_job( + torrust_tracker_swarm_coordination_registry::statistics::activity_metrics_updater::start_job( &app_container.torrent_repository_container.swarms.clone(), &app_container.torrent_repository_container.stats_repository.clone(), peer_inactivity_cutoff_timestamp(config.core.tracker_policy.max_peer_timeout), diff --git a/src/bootstrap/jobs/torrent_repository.rs b/src/bootstrap/jobs/torrent_repository.rs index ea0d215ee..c64917ea6 100644 --- a/src/bootstrap/jobs/torrent_repository.rs +++ b/src/bootstrap/jobs/torrent_repository.rs @@ -7,7 +7,7 @@ use crate::container::AppContainer; pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { if config.core.tracker_usage_statistics { - let job = torrust_tracker_torrent_repository::statistics::event::listener::run_event_listener( + let job = torrust_tracker_swarm_coordination_registry::statistics::event::listener::run_event_listener( app_container.torrent_repository_container.event_bus.receiver(), &app_container.torrent_repository_container.stats_repository, ); diff --git a/src/container.rs b/src/container.rs index 98c455780..bb5873fb2 100644 --- a/src/container.rs +++ b/src/container.rs @@ -9,7 +9,7 @@ use bittorrent_udp_tracker_core::{self}; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{Configuration, HttpApi}; -use torrust_tracker_torrent_repository::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use tracing::instrument; From 2768306a8b5db288f27dedac6ce59a11efc61bcb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 29 May 2025 10:50:56 +0100 Subject: [PATCH 1156/1297] refactor: [#1519] rename Swarm to Coordinator --- .../swarm-coordination-registry/src/lib.rs | 4 +- .../swarm-coordination-registry/src/swarm.rs | 102 +++++++++--------- .../swarm-coordination-registry/src/swarms.rs | 12 +-- 3 files changed, 59 insertions(+), 59 deletions(-) diff --git a/packages/swarm-coordination-registry/src/lib.rs b/packages/swarm-coordination-registry/src/lib.rs index 3adf2f18d..c93f553fa 100644 --- a/packages/swarm-coordination-registry/src/lib.rs +++ b/packages/swarm-coordination-registry/src/lib.rs @@ -10,8 +10,8 @@ use tokio::sync::Mutex; use torrust_tracker_clock::clock; pub type Swarms = swarms::Swarms; -pub type SwarmHandle = Arc>; -pub type Swarm = swarm::Swarm; +pub type SwarmHandle = Arc>; +pub type Coordinator = swarm::Coordinator; /// Working version, for production. #[cfg(not(test))] diff --git a/packages/swarm-coordination-registry/src/swarm.rs b/packages/swarm-coordination-registry/src/swarm.rs index 362fc6153..81e454d8b 100644 --- a/packages/swarm-coordination-registry/src/swarm.rs +++ b/packages/swarm-coordination-registry/src/swarm.rs @@ -15,14 +15,14 @@ use crate::event::sender::Sender; use crate::event::Event; #[derive(Clone)] -pub struct Swarm { +pub struct Coordinator { info_hash: InfoHash, peers: BTreeMap>, metadata: SwarmMetadata, event_sender: Sender, } -impl Swarm { +impl Coordinator { #[must_use] pub fn new(info_hash: &InfoHash, downloaded: u32, event_sender: Sender) -> Self { Self { @@ -326,26 +326,26 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::swarm::Swarm; + use crate::swarm::Coordinator; use crate::tests::sample_info_hash; #[test] fn it_should_be_empty_when_no_peers_have_been_inserted() { - let swarm = Swarm::new(&sample_info_hash(), 0, None); + let swarm = Coordinator::new(&sample_info_hash(), 0, None); assert!(swarm.is_empty()); } #[test] fn it_should_have_zero_length_when_no_peers_have_been_inserted() { - let swarm = Swarm::new(&sample_info_hash(), 0, None); + let swarm = Coordinator::new(&sample_info_hash(), 0, None); assert_eq!(swarm.len(), 0); } #[tokio::test] async fn it_should_allow_inserting_a_new_peer() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let peer = PeerBuilder::default().build(); @@ -354,7 +354,7 @@ mod tests { #[tokio::test] async fn it_should_allow_updating_a_preexisting_peer() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let peer = PeerBuilder::default().build(); @@ -365,7 +365,7 @@ mod tests { #[tokio::test] async fn it_should_allow_getting_all_peers() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let peer = PeerBuilder::default().build(); @@ -376,7 +376,7 @@ mod tests { #[tokio::test] async fn it_should_allow_getting_one_peer_by_id() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let peer = PeerBuilder::default().build(); @@ -387,7 +387,7 @@ mod tests { #[tokio::test] async fn it_should_increase_the_number_of_peers_after_inserting_a_new_one() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let peer = PeerBuilder::default().build(); @@ -398,7 +398,7 @@ mod tests { #[tokio::test] async fn it_should_decrease_the_number_of_peers_after_removing_one() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let peer = PeerBuilder::default().build(); @@ -411,7 +411,7 @@ mod tests { #[tokio::test] async fn it_should_allow_removing_an_existing_peer() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let peer = PeerBuilder::default().build(); @@ -425,7 +425,7 @@ mod tests { #[tokio::test] async fn it_should_allow_removing_a_non_existing_peer() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let peer = PeerBuilder::default().build(); @@ -434,7 +434,7 @@ mod tests { #[tokio::test] async fn it_should_allow_getting_all_peers_excluding_peers_with_a_given_address() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let peer1 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) @@ -453,7 +453,7 @@ mod tests { #[tokio::test] async fn it_should_count_inactive_peers() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let one_second = DurationSinceUnixEpoch::new(1, 0); @@ -469,7 +469,7 @@ mod tests { #[tokio::test] async fn it_should_remove_inactive_peers() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let one_second = DurationSinceUnixEpoch::new(1, 0); @@ -486,7 +486,7 @@ mod tests { #[tokio::test] async fn it_should_not_remove_active_peers() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let one_second = DurationSinceUnixEpoch::new(1, 0); @@ -507,20 +507,20 @@ mod tests { use torrust_tracker_primitives::peer::fixture::PeerBuilder; use crate::tests::sample_info_hash; - use crate::Swarm; + use crate::Coordinator; - fn empty_swarm() -> Swarm { - Swarm::new(&sample_info_hash(), 0, None) + fn empty_swarm() -> Coordinator { + Coordinator::new(&sample_info_hash(), 0, None) } - async fn not_empty_swarm() -> Swarm { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + async fn not_empty_swarm() -> Coordinator { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); swarm.upsert_peer(PeerBuilder::default().build().into()).await; swarm } - async fn not_empty_swarm_with_downloads() -> Swarm { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + async fn not_empty_swarm_with_downloads() -> Coordinator { + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let mut peer = PeerBuilder::leecher().build(); @@ -602,7 +602,7 @@ mod tests { #[tokio::test] async fn it_should_allow_inserting_two_identical_peers_except_for_the_socket_address() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let peer1 = PeerBuilder::default() .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) @@ -619,7 +619,7 @@ mod tests { #[tokio::test] async fn it_should_not_allow_inserting_two_peers_with_different_peer_id_but_the_same_socket_address() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); // When that happens the peer ID will be changed in the swarm. // In practice, it's like if the peer had changed its ID. @@ -641,7 +641,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_swarm_metadata() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); @@ -661,7 +661,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_number_of_seeders_in_the_list() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); @@ -676,7 +676,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_number_of_leechers_in_the_list() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let seeder = PeerBuilder::seeder().build(); let leecher = PeerBuilder::leecher().build(); @@ -691,7 +691,7 @@ mod tests { #[tokio::test] async fn it_should_be_a_peerless_swarm_when_it_does_not_contain_any_peers() { - let swarm = Swarm::new(&sample_info_hash(), 0, None); + let swarm = Coordinator::new(&sample_info_hash(), 0, None); assert!(swarm.is_peerless()); } @@ -700,12 +700,12 @@ mod tests { mod when_a_new_peer_is_added { use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::swarm::Swarm; + use crate::swarm::Coordinator; use crate::tests::sample_info_hash; #[tokio::test] async fn it_should_increase_the_number_of_leechers_if_the_new_peer_is_a_leecher_() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let leechers = swarm.metadata().leechers(); @@ -718,7 +718,7 @@ mod tests { #[tokio::test] async fn it_should_increase_the_number_of_seeders_if_the_new_peer_is_a_seeder() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let seeders = swarm.metadata().seeders(); @@ -732,7 +732,7 @@ mod tests { #[tokio::test] async fn it_should_not_increasing_the_number_of_downloads_if_the_new_peer_has_completed_downloading_as_it_was_not_previously_known( ) { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let downloads = swarm.metadata().downloads(); @@ -747,12 +747,12 @@ mod tests { mod when_a_peer_is_removed { use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::swarm::Swarm; + use crate::swarm::Coordinator; use crate::tests::sample_info_hash; #[tokio::test] async fn it_should_decrease_the_number_of_leechers_if_the_removed_peer_was_a_leecher() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let leecher = PeerBuilder::leecher().build(); @@ -767,7 +767,7 @@ mod tests { #[tokio::test] async fn it_should_decrease_the_number_of_seeders_if_the_removed_peer_was_a_seeder() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let seeder = PeerBuilder::seeder().build(); @@ -786,12 +786,12 @@ mod tests { use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::swarm::Swarm; + use crate::swarm::Coordinator; use crate::tests::sample_info_hash; #[tokio::test] async fn it_should_decrease_the_number_of_leechers_when_a_removed_peer_is_a_leecher() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let leecher = PeerBuilder::leecher().build(); @@ -806,7 +806,7 @@ mod tests { #[tokio::test] async fn it_should_decrease_the_number_of_seeders_when_the_removed_peer_is_a_seeder() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let seeder = PeerBuilder::seeder().build(); @@ -824,12 +824,12 @@ mod tests { use aquatic_udp_protocol::NumberOfBytes; use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::swarm::Swarm; + use crate::swarm::Coordinator; use crate::tests::sample_info_hash; #[tokio::test] async fn it_should_increase_seeders_and_decreasing_leechers_when_the_peer_changes_from_leecher_to_seeder_() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let mut peer = PeerBuilder::leecher().build(); @@ -848,7 +848,7 @@ mod tests { #[tokio::test] async fn it_should_increase_leechers_and_decreasing_seeders_when_the_peer_changes_from_seeder_to_leecher() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let mut peer = PeerBuilder::seeder().build(); @@ -867,7 +867,7 @@ mod tests { #[tokio::test] async fn it_should_increase_the_number_of_downloads_when_the_peer_announces_completed_downloading() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let mut peer = PeerBuilder::leecher().build(); @@ -884,7 +884,7 @@ mod tests { #[tokio::test] async fn it_should_not_increasing_the_number_of_downloads_when_the_peer_announces_completed_downloading_twice_() { - let mut swarm = Swarm::new(&sample_info_hash(), 0, None); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let mut peer = PeerBuilder::leecher().build(); @@ -913,7 +913,7 @@ mod tests { use crate::event::sender::tests::{expect_event_sequence, MockEventSender}; use crate::event::Event; - use crate::swarm::Swarm; + use crate::swarm::Coordinator; use crate::tests::sample_info_hash; #[tokio::test] @@ -925,7 +925,7 @@ mod tests { expect_event_sequence(&mut event_sender_mock, vec![Event::PeerAdded { info_hash, peer }]); - let mut swarm = Swarm::new(&sample_info_hash(), 0, Some(Arc::new(event_sender_mock))); + let mut swarm = Coordinator::new(&sample_info_hash(), 0, Some(Arc::new(event_sender_mock))); swarm.upsert_peer(peer.into()).await; } @@ -942,7 +942,7 @@ mod tests { vec![Event::PeerAdded { info_hash, peer }, Event::PeerRemoved { info_hash, peer }], ); - let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); + let mut swarm = Coordinator::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); // Insert the peer swarm.upsert_peer(peer.into()).await; @@ -962,7 +962,7 @@ mod tests { vec![Event::PeerAdded { info_hash, peer }, Event::PeerRemoved { info_hash, peer }], ); - let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); + let mut swarm = Coordinator::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); // Insert the peer swarm.upsert_peer(peer.into()).await; @@ -992,7 +992,7 @@ mod tests { ], ); - let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); + let mut swarm = Coordinator::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); // Insert the peer swarm.upsert_peer(peer.into()).await; @@ -1028,7 +1028,7 @@ mod tests { ], ); - let mut swarm = Swarm::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); + let mut swarm = Coordinator::new(&info_hash, 0, Some(Arc::new(event_sender_mock))); // Insert the peer swarm.upsert_peer(started_peer.into()).await; diff --git a/packages/swarm-coordination-registry/src/swarms.rs b/packages/swarm-coordination-registry/src/swarms.rs index 8e7bc24de..12fe2190d 100644 --- a/packages/swarm-coordination-registry/src/swarms.rs +++ b/packages/swarm-coordination-registry/src/swarms.rs @@ -11,7 +11,7 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads use crate::event::sender::Sender; use crate::event::Event; -use crate::swarm::Swarm; +use crate::swarm::Coordinator; use crate::SwarmHandle; #[derive(Default)] @@ -60,7 +60,7 @@ impl Swarms { let number_of_downloads = opt_persistent_torrent.unwrap_or_default(); let new_swarm_handle = - SwarmHandle::new(Swarm::new(info_hash, number_of_downloads, self.event_sender.clone()).into()); + SwarmHandle::new(Coordinator::new(info_hash, number_of_downloads, self.event_sender.clone()).into()); let new_swarm_handle = self.swarms.get_or_insert(*info_hash, new_swarm_handle); @@ -86,7 +86,7 @@ impl Swarms { } /// Inserts a new swarm. Only used for testing purposes. - pub fn insert(&self, info_hash: &InfoHash, swarm: Swarm) { + pub fn insert(&self, info_hash: &InfoHash, swarm: Coordinator) { // code-review: swarms builder? or constructor from vec? // It's only used for testing purposes. It allows to pre-define the // initial state of the swarm without having to go through the upsert @@ -366,7 +366,7 @@ impl Swarms { continue; } - let entry = SwarmHandle::new(Swarm::new(info_hash, *completed, self.event_sender.clone()).into()); + let entry = SwarmHandle::new(Coordinator::new(info_hash, *completed, self.event_sender.clone()).into()); // Since SkipMap is lock-free the torrent could have been inserted // after checking if it exists. @@ -853,7 +853,7 @@ mod tests { use crate::swarms::Swarms; use crate::tests::{sample_info_hash, sample_peer}; - use crate::{Swarm, SwarmHandle}; + use crate::{Coordinator, SwarmHandle}; /// `TorrentEntry` data is not directly accessible. It's only /// accessible through the trait methods. We need this temporary @@ -871,7 +871,7 @@ mod tests { } #[allow(clippy::from_over_into)] - impl Into for Swarm { + impl Into for Coordinator { fn into(self) -> TorrentEntryInfo { let torrent_entry_info = TorrentEntryInfo { swarm_metadata: self.metadata(), From ba37801d3c62b2b2c4ad1df1785609e6543d7d61 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 29 May 2025 10:55:08 +0100 Subject: [PATCH 1157/1297] refactor: [#1519] rename Swarms to Registry --- .../swarm-coordination-registry/src/lib.rs | 2 +- .../swarm-coordination-registry/src/swarms.rs | 110 +++++++++--------- 2 files changed, 56 insertions(+), 56 deletions(-) diff --git a/packages/swarm-coordination-registry/src/lib.rs b/packages/swarm-coordination-registry/src/lib.rs index c93f553fa..f3926331a 100644 --- a/packages/swarm-coordination-registry/src/lib.rs +++ b/packages/swarm-coordination-registry/src/lib.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use tokio::sync::Mutex; use torrust_tracker_clock::clock; -pub type Swarms = swarms::Swarms; +pub type Swarms = swarms::Registry; pub type SwarmHandle = Arc>; pub type Coordinator = swarm::Coordinator; diff --git a/packages/swarm-coordination-registry/src/swarms.rs b/packages/swarm-coordination-registry/src/swarms.rs index 12fe2190d..c14cb66b7 100644 --- a/packages/swarm-coordination-registry/src/swarms.rs +++ b/packages/swarm-coordination-registry/src/swarms.rs @@ -15,12 +15,12 @@ use crate::swarm::Coordinator; use crate::SwarmHandle; #[derive(Default)] -pub struct Swarms { +pub struct Registry { swarms: SkipMap, event_sender: Sender, } -impl Swarms { +impl Registry { #[must_use] pub fn new(event_sender: Sender) -> Self { Self { @@ -510,7 +510,7 @@ mod tests { use aquatic_udp_protocol::PeerId; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{sample_info_hash, sample_peer}; /// It generates a peer id from a number where the number is the last @@ -543,13 +543,13 @@ mod tests { #[tokio::test] async fn it_should_return_zero_length_when_it_has_no_swarms() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); assert_eq!(swarms.len(), 0); } #[tokio::test] async fn it_should_return_the_length_when_it_has_swarms() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); @@ -558,7 +558,7 @@ mod tests { #[tokio::test] async fn it_should_be_empty_when_it_has_no_swarms() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); assert!(swarms.is_empty()); let info_hash = sample_info_hash(); @@ -569,7 +569,7 @@ mod tests { #[tokio::test] async fn it_should_not_be_empty_when_it_has_at_least_one_swarm() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); @@ -581,12 +581,12 @@ mod tests { use std::sync::Arc; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] async fn it_should_add_the_first_peer_to_the_torrent_peer_list() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); @@ -597,7 +597,7 @@ mod tests { #[tokio::test] async fn it_should_allow_adding_the_same_peer_twice_to_the_torrent_peer_list() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); @@ -618,12 +618,12 @@ mod tests { use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::swarms::tests::the_swarm_repository::numeric_peer_id; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); @@ -637,7 +637,7 @@ mod tests { #[tokio::test] async fn it_should_return_an_empty_list_or_peers_for_a_non_existing_torrent() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let peers = swarms.get_swarm_peers(&sample_info_hash(), 74).await.unwrap(); @@ -646,7 +646,7 @@ mod tests { #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); @@ -680,12 +680,12 @@ mod tests { use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::swarms::tests::the_swarm_repository::numeric_peer_id; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] async fn it_should_return_an_empty_peer_list_for_a_non_existing_torrent() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let peers = swarms .get_peers_peers_excluding(&sample_info_hash(), &sample_peer(), TORRENT_PEERS_LIMIT) @@ -697,7 +697,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_peers_for_a_given_torrent_excluding_a_given_peer() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); @@ -714,7 +714,7 @@ mod tests { #[tokio::test] async fn it_should_return_74_peers_at_the_most_for_a_given_torrent_when_it_filters_out_a_given_peer() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); @@ -757,12 +757,12 @@ mod tests { use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] async fn it_should_remove_a_torrent_entry() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); swarms.handle_announcement(&info_hash, &sample_peer(), None).await.unwrap(); @@ -774,7 +774,7 @@ mod tests { #[tokio::test] async fn it_should_count_inactive_peers() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); let mut peer = sample_peer(); @@ -790,7 +790,7 @@ mod tests { #[tokio::test] async fn it_should_remove_peers_that_have_not_been_updated_after_a_cutoff_time() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); let mut peer = sample_peer(); @@ -811,8 +811,8 @@ mod tests { .contains(&Arc::new(peer))); } - async fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { - let swarms = Arc::new(Swarms::default()); + async fn initialize_repository_with_one_torrent_without_peers(info_hash: &InfoHash) -> Arc { + let swarms = Arc::new(Registry::default()); // Insert a sample peer for the torrent to force adding the torrent entry let mut peer = sample_peer(); @@ -851,7 +851,7 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{sample_info_hash, sample_peer}; use crate::{Coordinator, SwarmHandle}; @@ -884,7 +884,7 @@ mod tests { #[tokio::test] async fn it_should_return_one_torrent_entry_by_infohash() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); @@ -915,12 +915,12 @@ mod tests { use crate::swarms::tests::the_swarm_repository::returning_torrent_entries::{ torrent_entry_info, TorrentEntryInfo, }; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] async fn without_pagination() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let info_hash = sample_info_hash(); let peer = sample_peer(); @@ -955,7 +955,7 @@ mod tests { use crate::swarms::tests::the_swarm_repository::returning_torrent_entries::{ torrent_entry_info, TorrentEntryInfo, }; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{ sample_info_hash_alphabetically_ordered_after_sample_info_hash_one, sample_info_hash_one, sample_peer_one, sample_peer_two, @@ -963,7 +963,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_first_page() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); // Insert one torrent entry let info_hash_one = sample_info_hash_one(); @@ -998,7 +998,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_second_page() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); // Insert one torrent entry let info_hash_one = sample_info_hash_one(); @@ -1033,7 +1033,7 @@ mod tests { #[tokio::test] async fn it_should_allow_changing_the_page_size() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); // Insert one torrent entry let info_hash_one = sample_info_hash_one(); @@ -1061,14 +1061,14 @@ mod tests { use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{complete_peer, leecher, sample_info_hash, seeder}; // todo: refactor to use test parametrization #[tokio::test] async fn it_should_get_empty_aggregate_swarm_metadata_when_there_are_no_torrents() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let aggregate_swarm_metadata = swarms.get_aggregate_swarm_metadata().await.unwrap(); @@ -1085,7 +1085,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_leecher() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); swarms .handle_announcement(&sample_info_hash(), &leecher(), None) @@ -1107,7 +1107,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_seeder() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); swarms .handle_announcement(&sample_info_hash(), &seeder(), None) @@ -1129,7 +1129,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_is_a_completed_peer() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); swarms .handle_announcement(&sample_info_hash(), &complete_peer(), None) @@ -1151,7 +1151,7 @@ mod tests { #[tokio::test] async fn it_should_return_the_aggregate_swarm_metadata_when_there_are_multiple_torrents() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let start_time = std::time::Instant::now(); for i in 0..1_000_000 { @@ -1183,12 +1183,12 @@ mod tests { use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] async fn no_peerless_torrents() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); assert_eq!(swarms.count_peerless_torrents().await.unwrap(), 0); } @@ -1197,7 +1197,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); let current_cutoff = peer.updated + DurationSinceUnixEpoch::from_secs(1); @@ -1210,12 +1210,12 @@ mod tests { mod it_should_count_peers { use std::sync::Arc; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] async fn no_peers() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); assert_eq!(swarms.count_peers().await.unwrap(), 0); } @@ -1224,7 +1224,7 @@ mod tests { let info_hash = sample_info_hash(); let peer = sample_peer(); - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); assert_eq!(swarms.count_peers().await.unwrap(), 1); @@ -1238,12 +1238,12 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{leecher, sample_info_hash}; #[tokio::test] async fn it_should_get_swarm_metadata_for_an_existing_torrent() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let infohash = sample_info_hash(); @@ -1263,7 +1263,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_for_a_non_existing_torrent() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let swarm_metadata = swarms.get_swarm_metadata_or_default(&sample_info_hash()).await.unwrap(); @@ -1277,12 +1277,12 @@ mod tests { use torrust_tracker_primitives::NumberOfDownloadsBTreeMap; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::{leecher, sample_info_hash}; #[tokio::test] async fn it_should_allow_importing_persisted_torrent_entries() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let infohash = sample_info_hash(); @@ -1302,7 +1302,7 @@ mod tests { async fn it_should_allow_overwriting_a_previously_imported_persisted_torrent() { // code-review: do we want to allow this? - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let infohash = sample_info_hash(); @@ -1321,7 +1321,7 @@ mod tests { #[tokio::test] async fn it_should_now_allow_importing_a_persisted_torrent_if_it_already_exists() { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let infohash = sample_info_hash(); @@ -1353,7 +1353,7 @@ mod tests { use crate::event::sender::tests::{expect_event_sequence, MockEventSender}; use crate::event::Event; - use crate::swarms::Swarms; + use crate::swarms::Registry; use crate::tests::sample_info_hash; #[tokio::test] @@ -1374,7 +1374,7 @@ mod tests { ], ); - let swarms = Swarms::new(Some(Arc::new(event_sender_mock))); + let swarms = Registry::new(Some(Arc::new(event_sender_mock))); swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); } @@ -1398,7 +1398,7 @@ mod tests { ], ); - let swarms = Swarms::new(Some(Arc::new(event_sender_mock))); + let swarms = Registry::new(Some(Arc::new(event_sender_mock))); swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); @@ -1425,7 +1425,7 @@ mod tests { ], ); - let swarms = Swarms::new(Some(Arc::new(event_sender_mock))); + let swarms = Registry::new(Some(Arc::new(event_sender_mock))); // Add the new torrent swarms.handle_announcement(&info_hash, &peer, None).await.unwrap(); From 63f04e57ffbf27644692fd0fb4b7527415188f4c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 29 May 2025 11:04:27 +0100 Subject: [PATCH 1158/1297] refactor: [#1519] extract mod coordinator --- packages/swarm-coordination-registry/src/lib.rs | 2 +- .../src/{swarm.rs => swarm/coordinator.rs} | 16 ++++++++-------- .../swarm-coordination-registry/src/swarm/mod.rs | 1 + .../swarm-coordination-registry/src/swarms.rs | 2 +- 4 files changed, 11 insertions(+), 10 deletions(-) rename packages/swarm-coordination-registry/src/{swarm.rs => swarm/coordinator.rs} (98%) create mode 100644 packages/swarm-coordination-registry/src/swarm/mod.rs diff --git a/packages/swarm-coordination-registry/src/lib.rs b/packages/swarm-coordination-registry/src/lib.rs index f3926331a..2e591f41c 100644 --- a/packages/swarm-coordination-registry/src/lib.rs +++ b/packages/swarm-coordination-registry/src/lib.rs @@ -11,7 +11,7 @@ use torrust_tracker_clock::clock; pub type Swarms = swarms::Registry; pub type SwarmHandle = Arc>; -pub type Coordinator = swarm::Coordinator; +pub type Coordinator = swarm::coordinator::Coordinator; /// Working version, for production. #[cfg(not(test))] diff --git a/packages/swarm-coordination-registry/src/swarm.rs b/packages/swarm-coordination-registry/src/swarm/coordinator.rs similarity index 98% rename from packages/swarm-coordination-registry/src/swarm.rs rename to packages/swarm-coordination-registry/src/swarm/coordinator.rs index 81e454d8b..1ddf3e60b 100644 --- a/packages/swarm-coordination-registry/src/swarm.rs +++ b/packages/swarm-coordination-registry/src/swarm/coordinator.rs @@ -326,7 +326,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::swarm::Coordinator; + use crate::swarm::coordinator::Coordinator; use crate::tests::sample_info_hash; #[test] @@ -553,7 +553,7 @@ mod tests { use torrust_tracker_configuration::TrackerPolicy; - use crate::swarm::tests::for_retaining_policy::{ + use crate::swarm::coordinator::tests::for_retaining_policy::{ empty_swarm, not_empty_swarm, not_empty_swarm_with_downloads, remove_peerless_torrents_policy, }; @@ -582,7 +582,7 @@ mod tests { mod when_removing_peerless_torrents_is_disabled { - use crate::swarm::tests::for_retaining_policy::{ + use crate::swarm::coordinator::tests::for_retaining_policy::{ don_not_remove_peerless_torrents_policy, empty_swarm, not_empty_swarm, }; @@ -700,7 +700,7 @@ mod tests { mod when_a_new_peer_is_added { use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::swarm::Coordinator; + use crate::swarm::coordinator::Coordinator; use crate::tests::sample_info_hash; #[tokio::test] @@ -747,7 +747,7 @@ mod tests { mod when_a_peer_is_removed { use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::swarm::Coordinator; + use crate::swarm::coordinator::Coordinator; use crate::tests::sample_info_hash; #[tokio::test] @@ -786,7 +786,7 @@ mod tests { use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::swarm::Coordinator; + use crate::swarm::coordinator::Coordinator; use crate::tests::sample_info_hash; #[tokio::test] @@ -824,7 +824,7 @@ mod tests { use aquatic_udp_protocol::NumberOfBytes; use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::swarm::Coordinator; + use crate::swarm::coordinator::Coordinator; use crate::tests::sample_info_hash; #[tokio::test] @@ -913,7 +913,7 @@ mod tests { use crate::event::sender::tests::{expect_event_sequence, MockEventSender}; use crate::event::Event; - use crate::swarm::Coordinator; + use crate::swarm::coordinator::Coordinator; use crate::tests::sample_info_hash; #[tokio::test] diff --git a/packages/swarm-coordination-registry/src/swarm/mod.rs b/packages/swarm-coordination-registry/src/swarm/mod.rs new file mode 100644 index 000000000..115b2c7c9 --- /dev/null +++ b/packages/swarm-coordination-registry/src/swarm/mod.rs @@ -0,0 +1 @@ +pub mod coordinator; diff --git a/packages/swarm-coordination-registry/src/swarms.rs b/packages/swarm-coordination-registry/src/swarms.rs index c14cb66b7..158cc88c7 100644 --- a/packages/swarm-coordination-registry/src/swarms.rs +++ b/packages/swarm-coordination-registry/src/swarms.rs @@ -11,7 +11,7 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads use crate::event::sender::Sender; use crate::event::Event; -use crate::swarm::Coordinator; +use crate::swarm::coordinator::Coordinator; use crate::SwarmHandle; #[derive(Default)] From cfc5b342180ccfa5e2388403ede3d7a33ac35af3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 29 May 2025 11:05:25 +0100 Subject: [PATCH 1159/1297] refactor: [#1519] rename mod swarms to resgistry --- .../swarm-coordination-registry/src/lib.rs | 4 +-- .../src/{swarms.rs => registry.rs} | 36 +++++++++---------- 2 files changed, 20 insertions(+), 20 deletions(-) rename packages/swarm-coordination-registry/src/{swarms.rs => registry.rs} (98%) diff --git a/packages/swarm-coordination-registry/src/lib.rs b/packages/swarm-coordination-registry/src/lib.rs index 2e591f41c..82a29b867 100644 --- a/packages/swarm-coordination-registry/src/lib.rs +++ b/packages/swarm-coordination-registry/src/lib.rs @@ -2,14 +2,14 @@ pub mod container; pub mod event; pub mod statistics; pub mod swarm; -pub mod swarms; +pub mod registry; use std::sync::Arc; use tokio::sync::Mutex; use torrust_tracker_clock::clock; -pub type Swarms = swarms::Registry; +pub type Swarms = registry::Registry; pub type SwarmHandle = Arc>; pub type Coordinator = swarm::coordinator::Coordinator; diff --git a/packages/swarm-coordination-registry/src/swarms.rs b/packages/swarm-coordination-registry/src/registry.rs similarity index 98% rename from packages/swarm-coordination-registry/src/swarms.rs rename to packages/swarm-coordination-registry/src/registry.rs index 158cc88c7..970b664ec 100644 --- a/packages/swarm-coordination-registry/src/swarms.rs +++ b/packages/swarm-coordination-registry/src/registry.rs @@ -510,7 +510,7 @@ mod tests { use aquatic_udp_protocol::PeerId; - use crate::swarms::Registry; + use crate::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; /// It generates a peer id from a number where the number is the last @@ -581,7 +581,7 @@ mod tests { use std::sync::Arc; - use crate::swarms::Registry; + use crate::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -617,8 +617,8 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::swarms::tests::the_swarm_repository::numeric_peer_id; - use crate::swarms::Registry; + use crate::registry::tests::the_swarm_repository::numeric_peer_id; + use crate::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -679,8 +679,8 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::swarms::tests::the_swarm_repository::numeric_peer_id; - use crate::swarms::Registry; + use crate::registry::tests::the_swarm_repository::numeric_peer_id; + use crate::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -757,7 +757,7 @@ mod tests { use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::swarms::Registry; + use crate::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -851,7 +851,7 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::swarms::Registry; + use crate::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; use crate::{Coordinator, SwarmHandle}; @@ -912,10 +912,10 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::swarms::tests::the_swarm_repository::returning_torrent_entries::{ + use crate::registry::tests::the_swarm_repository::returning_torrent_entries::{ torrent_entry_info, TorrentEntryInfo, }; - use crate::swarms::Registry; + use crate::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -952,10 +952,10 @@ mod tests { use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::swarms::tests::the_swarm_repository::returning_torrent_entries::{ + use crate::registry::tests::the_swarm_repository::returning_torrent_entries::{ torrent_entry_info, TorrentEntryInfo, }; - use crate::swarms::Registry; + use crate::registry::Registry; use crate::tests::{ sample_info_hash_alphabetically_ordered_after_sample_info_hash_one, sample_info_hash_one, sample_peer_one, sample_peer_two, @@ -1061,7 +1061,7 @@ mod tests { use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; - use crate::swarms::Registry; + use crate::registry::Registry; use crate::tests::{complete_peer, leecher, sample_info_hash, seeder}; // todo: refactor to use test parametrization @@ -1183,7 +1183,7 @@ mod tests { use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::swarms::Registry; + use crate::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -1210,7 +1210,7 @@ mod tests { mod it_should_count_peers { use std::sync::Arc; - use crate::swarms::Registry; + use crate::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -1238,7 +1238,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::swarms::Registry; + use crate::registry::Registry; use crate::tests::{leecher, sample_info_hash}; #[tokio::test] @@ -1277,7 +1277,7 @@ mod tests { use torrust_tracker_primitives::NumberOfDownloadsBTreeMap; - use crate::swarms::Registry; + use crate::registry::Registry; use crate::tests::{leecher, sample_info_hash}; #[tokio::test] @@ -1353,7 +1353,7 @@ mod tests { use crate::event::sender::tests::{expect_event_sequence, MockEventSender}; use crate::event::Event; - use crate::swarms::Registry; + use crate::registry::Registry; use crate::tests::sample_info_hash; #[tokio::test] From 9146681a798ce22df46e069e4ea357e6c18ce8b7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 29 May 2025 11:08:21 +0100 Subject: [PATCH 1160/1297] refactor: [#1519] move mod registry --- .../swarm-coordination-registry/src/lib.rs | 3 +- .../src/swarm/mod.rs | 1 + .../src/{ => swarm}/registry.rs | 36 +++++++++---------- 3 files changed, 20 insertions(+), 20 deletions(-) rename packages/swarm-coordination-registry/src/{ => swarm}/registry.rs (97%) diff --git a/packages/swarm-coordination-registry/src/lib.rs b/packages/swarm-coordination-registry/src/lib.rs index 82a29b867..bbeb5e924 100644 --- a/packages/swarm-coordination-registry/src/lib.rs +++ b/packages/swarm-coordination-registry/src/lib.rs @@ -2,14 +2,13 @@ pub mod container; pub mod event; pub mod statistics; pub mod swarm; -pub mod registry; use std::sync::Arc; use tokio::sync::Mutex; use torrust_tracker_clock::clock; -pub type Swarms = registry::Registry; +pub type Swarms = swarm::registry::Registry; pub type SwarmHandle = Arc>; pub type Coordinator = swarm::coordinator::Coordinator; diff --git a/packages/swarm-coordination-registry/src/swarm/mod.rs b/packages/swarm-coordination-registry/src/swarm/mod.rs index 115b2c7c9..925ae4948 100644 --- a/packages/swarm-coordination-registry/src/swarm/mod.rs +++ b/packages/swarm-coordination-registry/src/swarm/mod.rs @@ -1 +1,2 @@ pub mod coordinator; +pub mod registry; diff --git a/packages/swarm-coordination-registry/src/registry.rs b/packages/swarm-coordination-registry/src/swarm/registry.rs similarity index 97% rename from packages/swarm-coordination-registry/src/registry.rs rename to packages/swarm-coordination-registry/src/swarm/registry.rs index 970b664ec..30652537b 100644 --- a/packages/swarm-coordination-registry/src/registry.rs +++ b/packages/swarm-coordination-registry/src/swarm/registry.rs @@ -510,7 +510,7 @@ mod tests { use aquatic_udp_protocol::PeerId; - use crate::registry::Registry; + use crate::swarm::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; /// It generates a peer id from a number where the number is the last @@ -581,7 +581,7 @@ mod tests { use std::sync::Arc; - use crate::registry::Registry; + use crate::swarm::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -617,8 +617,8 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::registry::tests::the_swarm_repository::numeric_peer_id; - use crate::registry::Registry; + use crate::swarm::registry::tests::the_swarm_repository::numeric_peer_id; + use crate::swarm::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -679,8 +679,8 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::registry::tests::the_swarm_repository::numeric_peer_id; - use crate::registry::Registry; + use crate::swarm::registry::tests::the_swarm_repository::numeric_peer_id; + use crate::swarm::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -757,7 +757,7 @@ mod tests { use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::registry::Registry; + use crate::swarm::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -851,7 +851,7 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::registry::Registry; + use crate::swarm::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; use crate::{Coordinator, SwarmHandle}; @@ -912,10 +912,10 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::registry::tests::the_swarm_repository::returning_torrent_entries::{ + use crate::swarm::registry::tests::the_swarm_repository::returning_torrent_entries::{ torrent_entry_info, TorrentEntryInfo, }; - use crate::registry::Registry; + use crate::swarm::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -952,10 +952,10 @@ mod tests { use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::registry::tests::the_swarm_repository::returning_torrent_entries::{ + use crate::swarm::registry::tests::the_swarm_repository::returning_torrent_entries::{ torrent_entry_info, TorrentEntryInfo, }; - use crate::registry::Registry; + use crate::swarm::registry::Registry; use crate::tests::{ sample_info_hash_alphabetically_ordered_after_sample_info_hash_one, sample_info_hash_one, sample_peer_one, sample_peer_two, @@ -1061,7 +1061,7 @@ mod tests { use bittorrent_primitives::info_hash::fixture::gen_seeded_infohash; use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; - use crate::registry::Registry; + use crate::swarm::registry::Registry; use crate::tests::{complete_peer, leecher, sample_info_hash, seeder}; // todo: refactor to use test parametrization @@ -1183,7 +1183,7 @@ mod tests { use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::registry::Registry; + use crate::swarm::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -1210,7 +1210,7 @@ mod tests { mod it_should_count_peers { use std::sync::Arc; - use crate::registry::Registry; + use crate::swarm::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -1238,7 +1238,7 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use crate::registry::Registry; + use crate::swarm::registry::Registry; use crate::tests::{leecher, sample_info_hash}; #[tokio::test] @@ -1277,7 +1277,7 @@ mod tests { use torrust_tracker_primitives::NumberOfDownloadsBTreeMap; - use crate::registry::Registry; + use crate::swarm::registry::Registry; use crate::tests::{leecher, sample_info_hash}; #[tokio::test] @@ -1353,7 +1353,7 @@ mod tests { use crate::event::sender::tests::{expect_event_sequence, MockEventSender}; use crate::event::Event; - use crate::registry::Registry; + use crate::swarm::registry::Registry; use crate::tests::sample_info_hash; #[tokio::test] From 290c9eb491373ada84e9b3b2baa9bb596cbaffcc Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 29 May 2025 11:09:02 +0100 Subject: [PATCH 1161/1297] refactor: [#1519] rename Swarms to Registry --- packages/swarm-coordination-registry/src/container.rs | 6 +++--- packages/swarm-coordination-registry/src/lib.rs | 2 +- .../src/statistics/activity_metrics_updater.rs | 6 +++--- packages/tracker-core/src/torrent/manager.rs | 4 ++-- packages/tracker-core/src/torrent/repository/in_memory.rs | 6 +++--- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/packages/swarm-coordination-registry/src/container.rs b/packages/swarm-coordination-registry/src/container.rs index d185180b1..1b56b3d4b 100644 --- a/packages/swarm-coordination-registry/src/container.rs +++ b/packages/swarm-coordination-registry/src/container.rs @@ -6,10 +6,10 @@ use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::{self}; use crate::statistics::repository::Repository; -use crate::{statistics, Swarms}; +use crate::{statistics, Registry}; pub struct TorrentRepositoryContainer { - pub swarms: Arc, + pub swarms: Arc, pub event_bus: Arc, pub stats_event_sender: event::sender::Sender, pub stats_repository: Arc, @@ -26,7 +26,7 @@ impl TorrentRepositoryContainer { let stats_event_sender = event_bus.sender(); - let swarms = Arc::new(Swarms::new(stats_event_sender.clone())); + let swarms = Arc::new(Registry::new(stats_event_sender.clone())); Self { swarms, diff --git a/packages/swarm-coordination-registry/src/lib.rs b/packages/swarm-coordination-registry/src/lib.rs index bbeb5e924..0382c14fa 100644 --- a/packages/swarm-coordination-registry/src/lib.rs +++ b/packages/swarm-coordination-registry/src/lib.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use tokio::sync::Mutex; use torrust_tracker_clock::clock; -pub type Swarms = swarm::registry::Registry; +pub type Registry = swarm::registry::Registry; pub type SwarmHandle = Arc>; pub type Coordinator = swarm::coordinator::Coordinator; diff --git a/packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs b/packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs index 2dfa5fb4e..016e230ec 100644 --- a/packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs +++ b/packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs @@ -11,12 +11,12 @@ use tracing::instrument; use super::repository::Repository; use crate::statistics::{TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL, TORRENT_REPOSITORY_TORRENTS_INACTIVE_TOTAL}; -use crate::{CurrentClock, Swarms}; +use crate::{CurrentClock, Registry}; #[must_use] #[instrument(skip(swarms, stats_repository))] pub fn start_job( - swarms: &Arc, + swarms: &Arc, stats_repository: &Arc, inactivity_cutoff: DurationSinceUnixEpoch, ) -> JoinHandle<()> { @@ -51,7 +51,7 @@ pub fn start_job( async fn update_activity_metrics( interval_in_secs: u64, - swarms: &Arc, + swarms: &Arc, stats_repository: &Arc, inactivity_cutoff: DurationSinceUnixEpoch, ) { diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index cbdf01193..5acc27980 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -148,7 +148,7 @@ mod tests { use std::sync::Arc; use torrust_tracker_configuration::Core; - use torrust_tracker_swarm_coordination_registry::Swarms; + use torrust_tracker_swarm_coordination_registry::Registry; use super::{DatabaseDownloadsMetricRepository, TorrentsManager}; use crate::databases::setup::initialize_database; @@ -167,7 +167,7 @@ mod tests { } fn initialize_torrents_manager_with(config: Core) -> (Arc, Arc) { - let swarms = Arc::new(Swarms::default()); + let swarms = Arc::new(Registry::default()); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new(swarms)); let database = initialize_database(&config); let database_persistent_torrent_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index 47b34ad26..ead05a32d 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -7,7 +7,7 @@ use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; -use torrust_tracker_swarm_coordination_registry::{SwarmHandle, Swarms}; +use torrust_tracker_swarm_coordination_registry::{Registry, SwarmHandle}; /// In-memory repository for torrent entries. /// @@ -21,12 +21,12 @@ use torrust_tracker_swarm_coordination_registry::{SwarmHandle, Swarms}; #[derive(Default)] pub struct InMemoryTorrentRepository { /// The underlying in-memory data structure that stores swarms data. - swarms: Arc, + swarms: Arc, } impl InMemoryTorrentRepository { #[must_use] - pub fn new(swarms: Arc) -> Self { + pub fn new(swarms: Arc) -> Self { Self { swarms } } From bbe974de3537246dad431826fd3dc8764dd44375 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 29 May 2025 11:11:23 +0100 Subject: [PATCH 1162/1297] refactor: [#1519] rename SwarmHandle to CoordinatorHandle --- .../swarm-coordination-registry/src/lib.rs | 2 +- .../src/swarm/registry.rs | 18 +++++++++--------- .../src/torrent/repository/in_memory.rs | 6 +++--- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/packages/swarm-coordination-registry/src/lib.rs b/packages/swarm-coordination-registry/src/lib.rs index 0382c14fa..fc7996817 100644 --- a/packages/swarm-coordination-registry/src/lib.rs +++ b/packages/swarm-coordination-registry/src/lib.rs @@ -9,7 +9,7 @@ use tokio::sync::Mutex; use torrust_tracker_clock::clock; pub type Registry = swarm::registry::Registry; -pub type SwarmHandle = Arc>; +pub type CoordinatorHandle = Arc>; pub type Coordinator = swarm::coordinator::Coordinator; /// Working version, for production. diff --git a/packages/swarm-coordination-registry/src/swarm/registry.rs b/packages/swarm-coordination-registry/src/swarm/registry.rs index 30652537b..c8e98f307 100644 --- a/packages/swarm-coordination-registry/src/swarm/registry.rs +++ b/packages/swarm-coordination-registry/src/swarm/registry.rs @@ -12,11 +12,11 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads use crate::event::sender::Sender; use crate::event::Event; use crate::swarm::coordinator::Coordinator; -use crate::SwarmHandle; +use crate::CoordinatorHandle; #[derive(Default)] pub struct Registry { - swarms: SkipMap, + swarms: SkipMap, event_sender: Sender, } @@ -60,7 +60,7 @@ impl Registry { let number_of_downloads = opt_persistent_torrent.unwrap_or_default(); let new_swarm_handle = - SwarmHandle::new(Coordinator::new(info_hash, number_of_downloads, self.event_sender.clone()).into()); + CoordinatorHandle::new(Coordinator::new(info_hash, number_of_downloads, self.event_sender.clone()).into()); let new_swarm_handle = self.swarms.get_or_insert(*info_hash, new_swarm_handle); @@ -107,7 +107,7 @@ impl Registry { /// /// An `Option` containing the removed torrent entry if it existed. #[must_use] - pub async fn remove(&self, key: &InfoHash) -> Option { + pub async fn remove(&self, key: &InfoHash) -> Option { let swarm_handle = self.swarms.remove(key).map(|entry| entry.value().clone()); if let Some(event_sender) = self.event_sender.as_deref() { @@ -123,7 +123,7 @@ impl Registry { /// /// An `Option` containing the tracked torrent handle if found. #[must_use] - pub fn get(&self, key: &InfoHash) -> Option { + pub fn get(&self, key: &InfoHash) -> Option { let maybe_entry = self.swarms.get(key); maybe_entry.map(|entry| entry.value().clone()) } @@ -138,7 +138,7 @@ impl Registry { /// /// A vector of `(InfoHash, TorrentEntry)` tuples. #[must_use] - pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, SwarmHandle)> { + pub fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, CoordinatorHandle)> { match pagination { Some(pagination) => self .swarms @@ -366,7 +366,7 @@ impl Registry { continue; } - let entry = SwarmHandle::new(Coordinator::new(info_hash, *completed, self.event_sender.clone()).into()); + let entry = CoordinatorHandle::new(Coordinator::new(info_hash, *completed, self.event_sender.clone()).into()); // Since SkipMap is lock-free the torrent could have been inserted // after checking if it exists. @@ -853,7 +853,7 @@ mod tests { use crate::swarm::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; - use crate::{Coordinator, SwarmHandle}; + use crate::{Coordinator, CoordinatorHandle}; /// `TorrentEntry` data is not directly accessible. It's only /// accessible through the trait methods. We need this temporary @@ -865,7 +865,7 @@ mod tests { number_of_peers: usize, } - async fn torrent_entry_info(swarm_handle: SwarmHandle) -> TorrentEntryInfo { + async fn torrent_entry_info(swarm_handle: CoordinatorHandle) -> TorrentEntryInfo { let torrent_guard = swarm_handle.lock().await; torrent_guard.clone().into() } diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index ead05a32d..e50a82933 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -7,7 +7,7 @@ use torrust_tracker_configuration::{TrackerPolicy, TORRENT_PEERS_LIMIT}; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::{AggregateActiveSwarmMetadata, SwarmMetadata}; use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; -use torrust_tracker_swarm_coordination_registry::{Registry, SwarmHandle}; +use torrust_tracker_swarm_coordination_registry::{CoordinatorHandle, Registry}; /// In-memory repository for torrent entries. /// @@ -110,7 +110,7 @@ impl InMemoryTorrentRepository { /// /// An `Option` containing the torrent entry if found. #[must_use] - pub(crate) fn get(&self, key: &InfoHash) -> Option { + pub(crate) fn get(&self, key: &InfoHash) -> Option { self.swarms.get(key) } @@ -128,7 +128,7 @@ impl InMemoryTorrentRepository { /// /// A vector of `(InfoHash, TorrentEntry)` tuples. #[must_use] - pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, SwarmHandle)> { + pub(crate) fn get_paginated(&self, pagination: Option<&Pagination>) -> Vec<(InfoHash, CoordinatorHandle)> { self.swarms.get_paginated(pagination) } From 00b9bf998269dec2e64b512fd07a0b4296985166 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 08:00:23 +0100 Subject: [PATCH 1163/1297] chore(deps): update dependencies ```output cargo update Updating crates.io index Locking 33 packages to latest compatible versions Updating anstyle-wincon v3.0.7 -> v3.0.8 Updating async-io v2.4.0 -> v2.4.1 Updating cc v1.2.22 -> v1.2.25 Updating clap v4.5.38 -> v4.5.39 Updating clap_builder v4.5.38 -> v4.5.39 Updating core-foundation v0.10.0 -> v0.10.1 Adding criterion v0.6.0 Removing hermit-abi v0.4.0 Updating hyper-rustls v0.27.5 -> v0.27.6 Updating hyper-util v0.1.11 -> v0.1.13 Updating icu_properties v2.0.0 -> v2.0.1 Updating icu_properties_data v2.0.0 -> v2.0.1 Adding iri-string v0.7.8 Updating libloading v0.8.7 -> v0.8.8 Updating libsqlite3-sys v0.33.0 -> v0.34.0 Removing linux-raw-sys v0.4.15 Updating lock_api v0.4.12 -> v0.4.13 Updating mio v1.0.3 -> v1.0.4 Adding once_cell_polyfill v1.70.1 Updating openssl v0.10.72 -> v0.10.73 Updating openssl-sys v0.9.108 -> v0.9.109 Updating parking_lot v0.12.3 -> v0.12.4 Updating parking_lot_core v0.9.10 -> v0.9.11 Updating polling v3.7.4 -> v3.8.0 Updating r2d2_sqlite v0.28.0 -> v0.29.0 Updating reqwest v0.12.15 -> v0.12.18 Updating rusqlite v0.35.0 -> v0.36.0 Removing rustix v0.38.44 Updating rustversion v1.0.20 -> v1.0.21 Updating socket2 v0.5.9 -> v0.5.10 Updating tokio v1.45.0 -> v1.45.1 Updating tower-http v0.6.4 -> v0.6.5 Updating uuid v1.16.0 -> v1.17.0 Updating windows-core v0.61.1 -> v0.61.2 Updating windows-result v0.3.3 -> v0.3.4 Updating windows-strings v0.4.1 -> v0.4.2 ``` --- Cargo.lock | 239 +++++++++++++++++++++++++++++------------------------ 1 file changed, 131 insertions(+), 108 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ecf178a59..35040f516 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -120,12 +120,12 @@ dependencies = [ [[package]] name = "anstyle-wincon" -version = "3.0.7" +version = "3.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e" +checksum = "6680de5231bd6ee4c6191b8a1325daa282b415391ec9d3a37bd34f2060dc73fa" dependencies = [ "anstyle", - "once_cell", + "once_cell_polyfill", "windows-sys 0.59.0", ] @@ -263,9 +263,9 @@ dependencies = [ [[package]] name = "async-io" -version = "2.4.0" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a2b323ccce0a1d90b449fd71f2a06ca7faa7c54c2751f06c9bd851fc061059" +checksum = "1237c0ae75a0f3765f58910ff9cdd0a12eeb39ab2f4c7de23262f337f0aacbb3" dependencies = [ "async-lock", "cfg-if", @@ -274,7 +274,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 0.38.44", + "rustix", "slab", "tracing", "windows-sys 0.59.0", @@ -579,7 +579,7 @@ dependencies = [ "bittorrent-http-tracker-protocol", "bittorrent-primitives", "bittorrent-tracker-core", - "criterion", + "criterion 0.5.1", "formatjson", "futures", "mockall", @@ -697,7 +697,7 @@ dependencies = [ "bloom", "blowfish", "cipher", - "criterion", + "criterion 0.5.1", "futures", "lazy_static", "mockall", @@ -959,9 +959,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.22" +version = "1.2.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32db95edf998450acc7881c932f94cd9b05c87b4b2599e8bab064753da4acfd1" +checksum = "d0fc897dc1e865cc67c0e05a836d9d3f1df3cbe442aa4a9473b18e12624a4951" dependencies = [ "jobserver", "libc", @@ -1052,9 +1052,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.38" +version = "4.5.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed93b9805f8ba930df42c2590f05453d5ec36cbb85d018868a5b24d31f6ac000" +checksum = "fd60e63e9be68e5fb56422e397cf9baddded06dae1d2e523401542383bc72a9f" dependencies = [ "clap_builder", "clap_derive", @@ -1062,9 +1062,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.38" +version = "4.5.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "379026ff283facf611b0ea629334361c4211d1b12ee01024eec1591133b04120" +checksum = "89cc6392a1f72bbeb820d71f32108f61fdaf18bc526e1d23954168a67759ef51" dependencies = [ "anstream", "anstyle", @@ -1139,9 +1139,9 @@ dependencies = [ [[package]] name = "core-foundation" -version = "0.10.0" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b55271e5c8c478ad3f38ad24ef34923091e0548492a266d19b3c0b4d82574c63" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" dependencies = [ "core-foundation-sys", "libc", @@ -1199,6 +1199,30 @@ dependencies = [ "walkdir", ] +[[package]] +name = "criterion" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bf7af66b0989381bd0be551bd7cc91912a655a58c6918420c9527b1fd8b4679" +dependencies = [ + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot", + "itertools 0.13.0", + "num-traits", + "oorandom", + "plotters", + "rayon", + "regex", + "serde", + "serde_json", + "tinytemplate", + "tokio", + "walkdir", +] + [[package]] name = "criterion-plot" version = "0.5.0" @@ -1931,12 +1955,6 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" -[[package]] -name = "hermit-abi" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" - [[package]] name = "hermit-abi" version = "0.5.1" @@ -2048,11 +2066,10 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.5" +version = "0.27.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d191583f3da1305256f22463b9bb0471acad48a4e534a5218b9963e9c1f59b2" +checksum = "03a01595e11bdcec50946522c32dde3fc6914743000a68b93000965f2f02406d" dependencies = [ - "futures-util", "http", "hyper", "hyper-util", @@ -2081,22 +2098,28 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.11" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "497bbc33a26fdd4af9ed9c70d63f61cf56a938375fbb32df34db9b1cd6d643f2" +checksum = "b1c293b6b3d21eca78250dc7dbebd6b9210ec5530e038cbfe0661b5c47ab06e8" dependencies = [ + "base64 0.22.1", "bytes", "futures-channel", + "futures-core", "futures-util", "http", "http-body", "hyper", + "ipnet", "libc", + "percent-encoding", "pin-project-lite", "socket2", + "system-configuration", "tokio", "tower-service", "tracing", + "windows-registry", ] [[package]] @@ -2187,9 +2210,9 @@ checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3" [[package]] name = "icu_properties" -version = "2.0.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2549ca8c7241c82f59c80ba2a6f415d931c5b58d24fb8412caa1a1f02c49139a" +checksum = "016c619c1eeb94efb86809b015c58f479963de65bdb6253345c1a1276f22e32b" dependencies = [ "displaydoc", "icu_collections", @@ -2203,9 +2226,9 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.0.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8197e866e47b68f8f7d95249e172903bec06004b18b2937f1095d40a0c57de04" +checksum = "298459143998310acd25ffe6810ed544932242d3f07083eee1084d83a71bd632" [[package]] name = "icu_provider" @@ -2303,13 +2326,23 @@ version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" +[[package]] +name = "iri-string" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "is-terminal" version = "0.4.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" dependencies = [ - "hermit-abi 0.5.1", + "hermit-abi", "libc", "windows-sys 0.59.0", ] @@ -2393,9 +2426,9 @@ checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" [[package]] name = "libloading" -version = "0.8.7" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a793df0d7afeac54f95b471d3af7f0d4fb975699f972341a4b76988d49cdf0c" +checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667" dependencies = [ "cfg-if", "windows-targets 0.53.0", @@ -2420,9 +2453,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.33.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "947e6816f7825b2b45027c2c32e7085da9934defa535de4a6a46b10a4d5257fa" +checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15" dependencies = [ "cc", "pkg-config", @@ -2440,12 +2473,6 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "linux-raw-sys" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" - [[package]] name = "linux-raw-sys" version = "0.9.4" @@ -2472,9 +2499,9 @@ dependencies = [ [[package]] name = "lock_api" -version = "0.4.12" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765" dependencies = [ "autocfg", "scopeguard", @@ -2563,13 +2590,13 @@ dependencies = [ [[package]] name = "mio" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" +checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c" dependencies = [ "libc", "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -2815,6 +2842,12 @@ version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +[[package]] +name = "once_cell_polyfill" +version = "1.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad" + [[package]] name = "oorandom" version = "11.1.5" @@ -2823,9 +2856,9 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "openssl" -version = "0.10.72" +version = "0.10.73" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fedfea7d58a1f73118430a55da6a286e7b044961736ce96a16a17068ea25e5da" +checksum = "8505734d46c8ab1e19a1dce3aef597ad87dcb4c37e7188231769bd6bd51cebf8" dependencies = [ "bitflags 2.9.1", "cfg-if", @@ -2855,9 +2888,9 @@ checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" [[package]] name = "openssl-sys" -version = "0.9.108" +version = "0.9.109" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e145e1651e858e820e4860f7b9c5e169bc1d8ce1c86043be79fa7b7634821847" +checksum = "90096e2e47630d78b7d1c20952dc621f957103f8bc2c8359ec81290d75238571" dependencies = [ "cc", "libc", @@ -2885,9 +2918,9 @@ checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" [[package]] name = "parking_lot" -version = "0.12.3" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13" dependencies = [ "lock_api", "parking_lot_core", @@ -2895,9 +2928,9 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.10" +version = "0.9.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5" dependencies = [ "cfg-if", "libc", @@ -3067,15 +3100,15 @@ dependencies = [ [[package]] name = "polling" -version = "3.7.4" +version = "3.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a604568c3202727d1507653cb121dbd627a58684eb09a820fd746bee38b4442f" +checksum = "b53a684391ad002dd6a596ceb6c74fd004fdce75f4be2e3f615068abbea5fd50" dependencies = [ "cfg-if", "concurrent-queue", - "hermit-abi 0.4.0", + "hermit-abi", "pin-project-lite", - "rustix 0.38.44", + "rustix", "tracing", "windows-sys 0.59.0", ] @@ -3277,9 +3310,9 @@ dependencies = [ [[package]] name = "r2d2_sqlite" -version = "0.28.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8998443b32daee2ad6f528afb19ad77c4a8acc4d8d55b3e5072ed42862fe261a" +checksum = "35006423374afbd4b270acddcbf1e28e60f6bdaaad10c2888b8fd2fba035213c" dependencies = [ "r2d2", "rusqlite", @@ -3435,15 +3468,14 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.15" +version = "0.12.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d19c46a6fdd48bc4dab94b6103fccc55d34c67cc0ad04653aad4ea2a07cd7bbb" +checksum = "e98ff6b0dbbe4d5a37318f433d4fc82babd21631f194d370409ceb2e40b2f0b5" dependencies = [ "base64 0.22.1", "bytes", "encoding_rs", "futures-core", - "futures-util", "h2", "http", "http-body", @@ -3460,21 +3492,20 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", - "rustls-pemfile", + "rustls-pki-types", "serde", "serde_json", "serde_urlencoded", "sync_wrapper", - "system-configuration", "tokio", "tokio-native-tls", "tower", + "tower-http", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "windows-registry", ] [[package]] @@ -3563,9 +3594,9 @@ dependencies = [ [[package]] name = "rusqlite" -version = "0.35.0" +version = "0.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a22715a5d6deef63c637207afbe68d0c72c3f8d0022d7cf9714c442d6157606b" +checksum = "3de23c3319433716cf134eed225fe9986bc24f63bed9be9f20c329029e672dc7" dependencies = [ "bitflags 2.9.1", "fallible-iterator", @@ -3612,19 +3643,6 @@ dependencies = [ "semver", ] -[[package]] -name = "rustix" -version = "0.38.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" -dependencies = [ - "bitflags 2.9.1", - "errno", - "libc", - "linux-raw-sys 0.4.15", - "windows-sys 0.59.0", -] - [[package]] name = "rustix" version = "1.0.7" @@ -3634,7 +3652,7 @@ dependencies = [ "bitflags 2.9.1", "errno", "libc", - "linux-raw-sys 0.9.4", + "linux-raw-sys", "windows-sys 0.59.0", ] @@ -3695,9 +3713,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.20" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2" +checksum = "8a0d197bd2c9dc6e53b84da9556a69ba4cdfab8619eb41a8bd1cc2027a0f6b1d" [[package]] name = "ryu" @@ -3770,7 +3788,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "271720403f46ca04f7ba6f55d438f8bd878d6b8ca0a1046e8228c4145bcbb316" dependencies = [ "bitflags 2.9.1", - "core-foundation 0.10.0", + "core-foundation 0.10.1", "core-foundation-sys", "libc", "security-framework-sys", @@ -4004,9 +4022,9 @@ checksum = "8917285742e9f3e1683f0a9c4e6b57960b7314d0b08d30d1ecd426713ee2eee9" [[package]] name = "socket2" -version = "0.5.9" +version = "0.5.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f5fd57c80058a56cf5c777ab8a126398ece8e442983605d280a44ce79d0edef" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" dependencies = [ "libc", "windows-sys 0.52.0", @@ -4185,7 +4203,7 @@ dependencies = [ "fastrand", "getrandom 0.3.3", "once_cell", - "rustix 1.0.7", + "rustix", "windows-sys 0.59.0", ] @@ -4204,7 +4222,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45c6481c4829e4cc63825e62c49186a34538b7b2750b73b266581ffb612fb5ed" dependencies = [ - "rustix 1.0.7", + "rustix", "windows-sys 0.59.0", ] @@ -4371,9 +4389,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.45.0" +version = "1.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2513ca694ef9ede0fb23fe71a4ee4107cb102b9dc1930f6d0fd77aae068ae165" +checksum = "75ef51a33ef1da925cea3e4eb122833cb377c61439ca401b770f54902b806779" dependencies = [ "backtrace", "bytes", @@ -4762,7 +4780,7 @@ dependencies = [ name = "torrust-tracker-contrib-bencode" version = "3.0.0-develop" dependencies = [ - "criterion", + "criterion 0.6.0", "thiserror 2.0.12", ] @@ -4826,11 +4844,11 @@ dependencies = [ "async-std", "bittorrent-primitives", "chrono", - "criterion", + "criterion 0.6.0", "crossbeam-skiplist", "futures", "mockall", - "rand 0.8.5", + "rand 0.9.1", "rstest", "serde", "thiserror 2.0.12", @@ -4861,7 +4879,7 @@ dependencies = [ "aquatic_udp_protocol", "async-std", "bittorrent-primitives", - "criterion", + "criterion 0.6.0", "crossbeam-skiplist", "dashmap", "futures", @@ -4926,19 +4944,22 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fdb0c213ca27a9f57ab69ddb290fd80d970922355b83ae380b395d3986b8a2e" +checksum = "5cc2d9e086a412a451384326f521c8123a99a466b329941a9403696bff9b0da2" dependencies = [ "async-compression", "bitflags 2.9.1", "bytes", "futures-core", + "futures-util", "http", "http-body", + "iri-string", "pin-project-lite", "tokio", "tokio-util", + "tower", "tower-layer", "tower-service", "tracing", @@ -5122,12 +5143,14 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.16.0" +version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9" +checksum = "3cf4199d1e5d15ddd86a694e4d0dffa9c323ce759fea589f00fef9d81cc1931d" dependencies = [ "getrandom 0.3.3", + "js-sys", "rand 0.9.1", + "wasm-bindgen", ] [[package]] @@ -5302,15 +5325,15 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-core" -version = "0.61.1" +version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46ec44dc15085cea82cf9c78f85a9114c463a369786585ad2882d1ff0b0acf40" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" dependencies = [ "windows-implement", "windows-interface", "windows-link", "windows-result", - "windows-strings 0.4.1", + "windows-strings 0.4.2", ] [[package]] @@ -5354,9 +5377,9 @@ dependencies = [ [[package]] name = "windows-result" -version = "0.3.3" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b895b5356fc36103d0f64dd1e94dfa7ac5633f1c9dd6e80fe9ec4adef69e09d" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" dependencies = [ "windows-link", ] @@ -5372,9 +5395,9 @@ dependencies = [ [[package]] name = "windows-strings" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a7ab927b2637c19b3dbe0965e75d8f2d30bdd697a1516191cad2ec4df8fb28a" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" dependencies = [ "windows-link", ] @@ -5565,7 +5588,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d65cbf2f12c15564212d48f4e3dfb87923d25d611f2aed18f4cb23f0413d89e" dependencies = [ "libc", - "rustix 1.0.7", + "rustix", ] [[package]] From caa03cc88a912d8ef2c8041aba5b3eb2ddf6ed95 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 10:47:51 +0100 Subject: [PATCH 1164/1297] fix: deprecated function criterion::black_box --- contrib/bencode/benches/bencode_benchmark.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/contrib/bencode/benches/bencode_benchmark.rs b/contrib/bencode/benches/bencode_benchmark.rs index b79bb0999..b22b286a5 100644 --- a/contrib/bencode/benches/bencode_benchmark.rs +++ b/contrib/bencode/benches/bencode_benchmark.rs @@ -1,4 +1,6 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use std::hint::black_box; + +use criterion::{criterion_group, criterion_main, Criterion}; use torrust_tracker_contrib_bencode::{BDecodeOpt, BencodeRef}; const B_NESTED_LISTS: &[u8; 100] = From 9c3c9109f575b221749f6baff0c9909197d46650 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 10:50:19 +0100 Subject: [PATCH 1165/1297] chore: add GitHhub MCP server config --- .vscode/mcp.json | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 .vscode/mcp.json diff --git a/.vscode/mcp.json b/.vscode/mcp.json new file mode 100644 index 000000000..506a52259 --- /dev/null +++ b/.vscode/mcp.json @@ -0,0 +1,26 @@ +{ + "inputs": [ + { + "type": "promptString", + "id": "github_token", + "description": "GitHub Personal Access Token", + "password": true + } + ], + "servers": { + "github": { + "command": "docker", + "args": [ + "run", + "-i", + "--rm", + "-e", + "GITHUB_PERSONAL_ACCESS_TOKEN", + "ghcr.io/github/github-mcp-server" + ], + "env": { + "GITHUB_PERSONAL_ACCESS_TOKEN": "${input:github_token}" + } + } + } +} \ No newline at end of file From db1c9b066d3bb5e0458f7d03dbdf6c2a6b251303 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 11:53:06 +0100 Subject: [PATCH 1166/1297] fix: test after updating dependencies --- .../tests/server/contract.rs | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/packages/axum-health-check-api-server/tests/server/contract.rs b/packages/axum-health-check-api-server/tests/server/contract.rs index 0e0d26b83..1d1ba3539 100644 --- a/packages/axum-health-check-api-server/tests/server/contract.rs +++ b/packages/axum-health-check-api-server/tests/server/contract.rs @@ -119,11 +119,8 @@ mod api { assert_eq!(details.binding, binding); assert!( - details - .result - .as_ref() - .is_err_and(|e| e.contains("error sending request for url")), - "Expected to contain, \"error sending request for url\", but have message \"{:?}\".", + details.result.as_ref().is_err_and(|e| e.contains("error sending request")), + "Expected to contain, \"error sending request\", but have message \"{:?}\".", details.result ); assert_eq!( @@ -226,11 +223,8 @@ mod http { assert_eq!(details.binding, binding); assert!( - details - .result - .as_ref() - .is_err_and(|e| e.contains("error sending request for url")), - "Expected to contain, \"error sending request for url\", but have message \"{:?}\".", + details.result.as_ref().is_err_and(|e| e.contains("error sending request")), + "Expected to contain, \"error sending request\", but have message \"{:?}\".", details.result ); assert_eq!( From 52b9660eeb6172fc4a03285751d9fe201eaca7a4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 13:49:09 +0100 Subject: [PATCH 1167/1297] feat: [#1456] wrapper over aquatic RequestParseError to make it sendable The error will be included in the UdpError event ans sent via tokio channel. --- packages/udp-tracker-server/src/error.rs | 34 +++++++++++++++++-- .../udp-tracker-server/src/handlers/error.rs | 20 +++-------- 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/packages/udp-tracker-server/src/error.rs b/packages/udp-tracker-server/src/error.rs index 93caf6853..6a63a4c9a 100644 --- a/packages/udp-tracker-server/src/error.rs +++ b/packages/udp-tracker-server/src/error.rs @@ -1,7 +1,7 @@ //! Error types for the UDP server. use std::panic::Location; -use aquatic_udp_protocol::{ConnectionId, RequestParseError}; +use aquatic_udp_protocol::{ConnectionId, RequestParseError, TransactionId}; use bittorrent_udp_tracker_core::services::announce::UdpAnnounceError; use bittorrent_udp_tracker_core::services::scrape::UdpScrapeError; use derive_more::derive::Display; @@ -17,7 +17,7 @@ pub struct ConnectionCookie(pub ConnectionId); pub enum Error { /// Error returned when the request is invalid. #[error("error when phrasing request: {request_parse_error:?}")] - RequestParseError { request_parse_error: RequestParseError }, + RequestParseError { request_parse_error: SendableRequestParseError }, /// Error returned when the domain tracker returns an announce error. #[error("tracker announce error: {source}")] @@ -47,7 +47,9 @@ pub enum Error { impl From for Error { fn from(request_parse_error: RequestParseError) -> Self { - Self::RequestParseError { request_parse_error } + Self::RequestParseError { + request_parse_error: request_parse_error.into(), + } } } @@ -66,3 +68,29 @@ impl From for Error { } } } + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct SendableRequestParseError { + pub message: String, + pub opt_connection_id: Option, + pub opt_transaction_id: Option, +} + +impl From for SendableRequestParseError { + fn from(request_parse_error: RequestParseError) -> Self { + let (message, opt_connection_id, opt_transaction_id) = match request_parse_error { + RequestParseError::Sendable { + connection_id, + transaction_id, + err, + } => ((*err).to_string(), Some(connection_id), Some(transaction_id)), + RequestParseError::Unsendable { err } => (err.to_string(), None, None), + }; + + Self { + message, + opt_connection_id, + opt_transaction_id, + } + } +} diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index 6259e26ca..7b477d84f 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -2,8 +2,7 @@ use std::net::SocketAddr; use std::ops::Range; -use aquatic_udp_protocol::{ErrorResponse, RequestParseError, Response, TransactionId}; -use bittorrent_udp_tracker_core::connection_cookie::{check, gen_remote_fingerprint}; +use aquatic_udp_protocol::{ErrorResponse, Response, TransactionId}; use bittorrent_udp_tracker_core::{self, UDP_TRACKER_LOG_TARGET}; use torrust_tracker_primitives::service_binding::ServiceBinding; use tracing::{instrument, Level}; @@ -40,25 +39,14 @@ pub async fn handle_error( } let e = if let Error::RequestParseError { request_parse_error } = e { - match request_parse_error { - RequestParseError::Sendable { - connection_id, - transaction_id, - err, - } => { - if let Err(e) = check(connection_id, gen_remote_fingerprint(&client_socket_addr), cookie_valid_range) { - (e.to_string(), Some(*transaction_id)) - } else { - ((*err).to_string(), Some(*transaction_id)) - } - } - RequestParseError::Unsendable { err } => (err.to_string(), transaction_id), - } + (request_parse_error.message.clone(), transaction_id) } else { (e.to_string(), transaction_id) }; if e.1.is_some() { + // code-review: why we trigger an event only if transaction_id is present? + if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { udp_server_stats_event_sender .send(Event::UdpError { From 8f3c22aaa3bbdb643545af72c48e27499f3a283c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 16:29:27 +0100 Subject: [PATCH 1168/1297] feat: [#1456] expose error kind in the UdpError event Not exposing the original complex error type becuase: - It's too complex. - It forces all errors to be "Sent", "PartialEq". - It would expose a lot of internals. --- packages/tracker-core/src/error.rs | 2 +- .../udp-tracker-core/src/connection_cookie.rs | 2 +- packages/udp-tracker-server/src/error.rs | 13 +++++- packages/udp-tracker-server/src/event.rs | 45 ++++++++++++++++++- .../udp-tracker-server/src/handlers/error.rs | 11 ++--- .../src/statistics/event/handler.rs | 6 ++- 6 files changed, 68 insertions(+), 11 deletions(-) diff --git a/packages/tracker-core/src/error.rs b/packages/tracker-core/src/error.rs index 4a35e9a0b..866aa64c5 100644 --- a/packages/tracker-core/src/error.rs +++ b/packages/tracker-core/src/error.rs @@ -84,7 +84,7 @@ pub enum ScrapeError { /// /// This error is returned when an operation involves a torrent that is not /// present in the whitelist. -#[derive(thiserror::Error, Debug, Clone)] +#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)] pub enum WhitelistError { /// Indicates that the torrent identified by `info_hash` is not whitelisted. #[error("The torrent: {info_hash}, is not whitelisted, {location}")] diff --git a/packages/udp-tracker-core/src/connection_cookie.rs b/packages/udp-tracker-core/src/connection_cookie.rs index 31c116400..ce255705f 100644 --- a/packages/udp-tracker-core/src/connection_cookie.rs +++ b/packages/udp-tracker-core/src/connection_cookie.rs @@ -86,7 +86,7 @@ use zerocopy::AsBytes; use crate::crypto::keys::CipherArrayBlowfish; /// Error returned when there was an error with the connection cookie. -#[derive(Error, Debug, Clone)] +#[derive(Error, Debug, Clone, PartialEq)] pub enum ConnectionCookieError { #[error("cookie value is not normal: {not_normal_value}")] ValueNotNormal { not_normal_value: f64 }, diff --git a/packages/udp-tracker-server/src/error.rs b/packages/udp-tracker-server/src/error.rs index 6a63a4c9a..d45b96569 100644 --- a/packages/udp-tracker-server/src/error.rs +++ b/packages/udp-tracker-server/src/error.rs @@ -1,4 +1,5 @@ //! Error types for the UDP server. +use std::fmt::Display; use std::panic::Location; use aquatic_udp_protocol::{ConnectionId, RequestParseError, TransactionId}; @@ -13,7 +14,7 @@ use torrust_tracker_located_error::LocatedError; pub struct ConnectionCookie(pub ConnectionId); /// Error returned by the UDP server. -#[derive(Error, Debug)] +#[derive(Error, Debug, Clone)] pub enum Error { /// Error returned when the request is invalid. #[error("error when phrasing request: {request_parse_error:?}")] @@ -76,6 +77,16 @@ pub struct SendableRequestParseError { pub opt_transaction_id: Option, } +impl Display for SendableRequestParseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "SendableRequestParseError: message: {}, connection_id: {:?}, transaction_id: {:?}", + self.message, self.opt_connection_id, self.opt_transaction_id + ) + } +} + impl From for SendableRequestParseError { fn from(request_parse_error: RequestParseError) -> Self { let (message, opt_connection_id, opt_transaction_id) = match request_parse_error { diff --git a/packages/udp-tracker-server/src/event.rs b/packages/udp-tracker-server/src/event.rs index 8aabd7ffb..4d3646563 100644 --- a/packages/udp-tracker-server/src/event.rs +++ b/packages/udp-tracker-server/src/event.rs @@ -2,12 +2,17 @@ use std::fmt; use std::net::SocketAddr; use std::time::Duration; +use bittorrent_tracker_core::error::{AnnounceError, ScrapeError}; +use bittorrent_udp_tracker_core::services::announce::UdpAnnounceError; +use bittorrent_udp_tracker_core::services::scrape::UdpScrapeError; use torrust_tracker_metrics::label::{LabelSet, LabelValue}; use torrust_tracker_metrics::label_name; use torrust_tracker_primitives::service_binding::ServiceBinding; +use crate::error::Error; + /// A UDP server event. -#[derive(Debug, PartialEq, Eq, Clone)] +#[derive(Debug, Clone, PartialEq)] pub enum Event { UdpRequestReceived { context: ConnectionContext, @@ -30,6 +35,7 @@ pub enum Event { UdpError { context: ConnectionContext, kind: Option, + error: ErrorKind, }, } @@ -109,6 +115,43 @@ impl From for LabelSet { } } +#[derive(Debug, Clone, PartialEq)] +pub enum ErrorKind { + RequestParse(String), + ConnectionCookie(String), + Whitelist(String), + Database(String), + InternalServer(String), + BadRequest(String), + TrackerAuthentication(String), +} + +impl From for ErrorKind { + fn from(error: Error) -> Self { + match error { + Error::RequestParseError { request_parse_error } => Self::RequestParse(request_parse_error.to_string()), + Error::UdpAnnounceError { source } => match source { + UdpAnnounceError::ConnectionCookieError { source } => Self::ConnectionCookie(source.to_string()), + UdpAnnounceError::TrackerCoreAnnounceError { source } => match source { + AnnounceError::Whitelist(whitelist_error) => Self::Whitelist(whitelist_error.to_string()), + AnnounceError::Database(error) => Self::Database(error.to_string()), + }, + UdpAnnounceError::TrackerCoreWhitelistError { source } => Self::Whitelist(source.to_string()), + }, + Error::UdpScrapeError { source } => match source { + UdpScrapeError::ConnectionCookieError { source } => Self::ConnectionCookie(source.to_string()), + UdpScrapeError::TrackerCoreScrapeError { source } => match source { + ScrapeError::Whitelist(whitelist_error) => Self::Whitelist(whitelist_error.to_string()), + }, + UdpScrapeError::TrackerCoreWhitelistError { source } => Self::Whitelist(source.to_string()), + }, + Error::InternalServer { location: _, message } => Self::InternalServer(message.to_string()), + Error::BadRequest { source } => Self::BadRequest(source.to_string()), + Error::TrackerAuthenticationRequired { location } => Self::TrackerAuthentication(location.to_string()), + } + } +} + pub mod sender { use std::sync::Arc; diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index 7b477d84f..54163aca5 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -21,7 +21,7 @@ pub async fn handle_error( request_id: Uuid, opt_udp_server_stats_event_sender: &crate::event::sender::Sender, cookie_valid_range: Range, - e: &Error, + error: &Error, transaction_id: Option, ) -> Response { tracing::trace!("handle error"); @@ -31,17 +31,17 @@ pub async fn handle_error( match transaction_id { Some(transaction_id) => { let transaction_id = transaction_id.0.to_string(); - tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %e, %client_socket_addr, %server_socket_addr, %request_id, %transaction_id, "response error"); + tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %error, %client_socket_addr, %server_socket_addr, %request_id, %transaction_id, "response error"); } None => { - tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %e, %client_socket_addr, %server_socket_addr, %request_id, "response error"); + tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %error, %client_socket_addr, %server_socket_addr, %request_id, "response error"); } } - let e = if let Error::RequestParseError { request_parse_error } = e { + let e = if let Error::RequestParseError { request_parse_error } = error { (request_parse_error.message.clone(), transaction_id) } else { - (e.to_string(), transaction_id) + (error.to_string(), transaction_id) }; if e.1.is_some() { @@ -52,6 +52,7 @@ pub async fn handle_error( .send(Event::UdpError { context: ConnectionContext::new(client_socket_addr, server_service_binding), kind: req_kind, + error: error.clone().into(), }) .await; } diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 1e1502339..b231d8336 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -232,7 +232,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura Err(err) => tracing::error!("Failed to increase the counter: {}", err), }; } - Event::UdpError { context, kind } => { + Event::UdpError { context, kind, error: _ } => { // Global fixed metrics match context.client_socket_addr().ip() { std::net::IpAddr::V4(_) => { @@ -271,7 +271,7 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; - use crate::event::{ConnectionContext, Event, UdpRequestKind}; + use crate::event::{ConnectionContext, ErrorKind, Event, UdpRequestKind}; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; use crate::CurrentClock; @@ -518,6 +518,7 @@ mod tests { .unwrap(), ), kind: None, + error: ErrorKind::RequestParse("Invalid request format".to_string()), }, &stats_repository, CurrentClock::now(), @@ -650,6 +651,7 @@ mod tests { .unwrap(), ), kind: None, + error: ErrorKind::RequestParse("Invalid request format".to_string()), }, &stats_repository, CurrentClock::now(), From d7902f1d670bf4411303fa3934e0a4ce595a20ef Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 16:36:50 +0100 Subject: [PATCH 1169/1297] refactor: [#1456] remove unused enum variant in udp server error --- Cargo.lock | 1 - packages/udp-tracker-server/Cargo.toml | 1 - packages/udp-tracker-server/src/error.rs | 7 ------- packages/udp-tracker-server/src/event.rs | 1 - packages/udp-tracker-server/src/handlers/mod.rs | 1 + 5 files changed, 1 insertion(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 35040f516..feb749d3f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4915,7 +4915,6 @@ dependencies = [ "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-events", - "torrust-tracker-located-error", "torrust-tracker-metrics", "torrust-tracker-primitives", "torrust-tracker-swarm-coordination-registry", diff --git a/packages/udp-tracker-server/Cargo.toml b/packages/udp-tracker-server/Cargo.toml index 72fa520ba..c0bc94ce3 100644 --- a/packages/udp-tracker-server/Cargo.toml +++ b/packages/udp-tracker-server/Cargo.toml @@ -30,7 +30,6 @@ torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } -torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } diff --git a/packages/udp-tracker-server/src/error.rs b/packages/udp-tracker-server/src/error.rs index d45b96569..aecf960b8 100644 --- a/packages/udp-tracker-server/src/error.rs +++ b/packages/udp-tracker-server/src/error.rs @@ -7,7 +7,6 @@ use bittorrent_udp_tracker_core::services::announce::UdpAnnounceError; use bittorrent_udp_tracker_core::services::scrape::UdpScrapeError; use derive_more::derive::Display; use thiserror::Error; -use torrust_tracker_located_error::LocatedError; #[derive(Display, Debug)] #[display(":?")] @@ -35,12 +34,6 @@ pub enum Error { message: String, }, - /// Error returned when the request is invalid. - #[error("bad request: {source}")] - BadRequest { - source: LocatedError<'static, dyn std::error::Error + Send + Sync>, - }, - /// Error returned when tracker requires authentication. #[error("domain tracker requires authentication but is not supported in current UDP implementation. Location: {location}")] TrackerAuthenticationRequired { location: &'static Location<'static> }, diff --git a/packages/udp-tracker-server/src/event.rs b/packages/udp-tracker-server/src/event.rs index 4d3646563..e320ceb8a 100644 --- a/packages/udp-tracker-server/src/event.rs +++ b/packages/udp-tracker-server/src/event.rs @@ -146,7 +146,6 @@ impl From for ErrorKind { UdpScrapeError::TrackerCoreWhitelistError { source } => Self::Whitelist(source.to_string()), }, Error::InternalServer { location: _, message } => Self::InternalServer(message.to_string()), - Error::BadRequest { source } => Self::BadRequest(source.to_string()), Error::TrackerAuthenticationRequired { location } => Self::TrackerAuthentication(location.to_string()), } } diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index df550ab72..6785bd293 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -109,6 +109,7 @@ pub(crate) async fn handle_packet( } }, Err(e) => { + // The request payload could not be parsed, so we handle it as an error. let response = handle_error( None, udp_request.from, From 0108c26b6db35d11522589cb20ce62904a97c059 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 16:54:40 +0100 Subject: [PATCH 1170/1297] fix: test. Error message changed --- packages/udp-tracker-server/src/error.rs | 2 +- packages/udp-tracker-server/tests/server/contract.rs | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/udp-tracker-server/src/error.rs b/packages/udp-tracker-server/src/error.rs index aecf960b8..697cc5cab 100644 --- a/packages/udp-tracker-server/src/error.rs +++ b/packages/udp-tracker-server/src/error.rs @@ -16,7 +16,7 @@ pub struct ConnectionCookie(pub ConnectionId); #[derive(Error, Debug, Clone)] pub enum Error { /// Error returned when the request is invalid. - #[error("error when phrasing request: {request_parse_error:?}")] + #[error("error parsing request: {request_parse_error:?}")] RequestParseError { request_parse_error: SendableRequestParseError }, /// Error returned when the domain tracker returns an announce error. diff --git a/packages/udp-tracker-server/tests/server/contract.rs b/packages/udp-tracker-server/tests/server/contract.rs index 860fd1f0b..04ad0f39d 100644 --- a/packages/udp-tracker-server/tests/server/contract.rs +++ b/packages/udp-tracker-server/tests/server/contract.rs @@ -59,7 +59,9 @@ async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_req let response = Response::parse_bytes(&response, true).unwrap(); - assert_eq!(get_error_response_message(&response).unwrap(), "Protocol identifier missing"); + assert!(get_error_response_message(&response) + .unwrap() + .contains("Protocol identifier missing")); env.stop().await; } From f485501f8e7705fe886932d5889b79c8eafb9057 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 16:55:24 +0100 Subject: [PATCH 1171/1297] refactor: [#1456 clean code --- .../udp-tracker-server/src/handlers/error.rs | 16 +++++----------- packages/udp-tracker-server/src/handlers/mod.rs | 9 ++++++++- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index 54163aca5..4ebe24075 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -22,13 +22,13 @@ pub async fn handle_error( opt_udp_server_stats_event_sender: &crate::event::sender::Sender, cookie_valid_range: Range, error: &Error, - transaction_id: Option, + opt_transaction_id: Option, ) -> Response { tracing::trace!("handle error"); let server_socket_addr = server_service_binding.bind_address(); - match transaction_id { + match opt_transaction_id { Some(transaction_id) => { let transaction_id = transaction_id.0.to_string(); tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %error, %client_socket_addr, %server_socket_addr, %request_id, %transaction_id, "response error"); @@ -38,13 +38,7 @@ pub async fn handle_error( } } - let e = if let Error::RequestParseError { request_parse_error } = error { - (request_parse_error.message.clone(), transaction_id) - } else { - (error.to_string(), transaction_id) - }; - - if e.1.is_some() { + if opt_transaction_id.is_some() { // code-review: why we trigger an event only if transaction_id is present? if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { @@ -59,7 +53,7 @@ pub async fn handle_error( } Response::from(ErrorResponse { - transaction_id: e.1.unwrap_or(TransactionId(I32::new(0))), - message: e.0.into(), + transaction_id: opt_transaction_id.unwrap_or(TransactionId(I32::new(0))), + message: error.to_string().into(), }) } diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 6785bd293..69c62a638 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -110,6 +110,13 @@ pub(crate) async fn handle_packet( }, Err(e) => { // The request payload could not be parsed, so we handle it as an error. + + let opt_transaction_id = if let Error::RequestParseError { request_parse_error } = e.clone() { + request_parse_error.opt_transaction_id + } else { + None + }; + let response = handle_error( None, udp_request.from, @@ -118,7 +125,7 @@ pub(crate) async fn handle_packet( &udp_tracker_server_container.stats_event_sender, cookie_time_values.valid_range.clone(), &e, - None, + opt_transaction_id, ) .await; From 525ab738d485a15175a8924520d88f66515f927a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 17:04:25 +0100 Subject: [PATCH 1172/1297] refactor: [#1456] extract methods --- .../udp-tracker-server/src/handlers/error.rs | 41 ++++++++++++++++--- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index 4ebe24075..af530efd6 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -28,6 +28,32 @@ pub async fn handle_error( let server_socket_addr = server_service_binding.bind_address(); + log_error(error, client_socket_addr, server_socket_addr, opt_transaction_id, request_id); + + trigger_udp_error_event( + error.clone(), + client_socket_addr, + server_service_binding, + opt_transaction_id, + opt_udp_server_stats_event_sender, + req_kind, + ) + .await; + + Response::from(ErrorResponse { + transaction_id: opt_transaction_id.unwrap_or(TransactionId(I32::new(0))), + message: error.to_string().into(), + }) +} + +fn log_error( + error: &Error, + client_socket_addr: SocketAddr, + server_socket_addr: SocketAddr, + opt_transaction_id: Option, + + request_id: Uuid, +) { match opt_transaction_id { Some(transaction_id) => { let transaction_id = transaction_id.0.to_string(); @@ -37,7 +63,17 @@ pub async fn handle_error( tracing::error!(target: UDP_TRACKER_LOG_TARGET, error = %error, %client_socket_addr, %server_socket_addr, %request_id, "response error"); } } +} + +async fn trigger_udp_error_event( + error: Error, + client_socket_addr: SocketAddr, + server_service_binding: ServiceBinding, + opt_transaction_id: Option, + opt_udp_server_stats_event_sender: &crate::event::sender::Sender, + req_kind: Option, +) { if opt_transaction_id.is_some() { // code-review: why we trigger an event only if transaction_id is present? @@ -51,9 +87,4 @@ pub async fn handle_error( .await; } } - - Response::from(ErrorResponse { - transaction_id: opt_transaction_id.unwrap_or(TransactionId(I32::new(0))), - message: error.to_string().into(), - }) } From ad1b19a366573dd24f35c3d6250758ee082ba9f6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 17:09:45 +0100 Subject: [PATCH 1173/1297] feat: trigger UDP error event when there is no transaction ID too --- .../udp-tracker-server/src/handlers/error.rs | 28 +++++++------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index af530efd6..7fb4141b2 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -31,10 +31,9 @@ pub async fn handle_error( log_error(error, client_socket_addr, server_socket_addr, opt_transaction_id, request_id); trigger_udp_error_event( - error.clone(), + error, client_socket_addr, server_service_binding, - opt_transaction_id, opt_udp_server_stats_event_sender, req_kind, ) @@ -51,7 +50,6 @@ fn log_error( client_socket_addr: SocketAddr, server_socket_addr: SocketAddr, opt_transaction_id: Option, - request_id: Uuid, ) { match opt_transaction_id { @@ -66,25 +64,19 @@ fn log_error( } async fn trigger_udp_error_event( - error: Error, + error: &Error, client_socket_addr: SocketAddr, server_service_binding: ServiceBinding, - opt_transaction_id: Option, - opt_udp_server_stats_event_sender: &crate::event::sender::Sender, req_kind: Option, ) { - if opt_transaction_id.is_some() { - // code-review: why we trigger an event only if transaction_id is present? - - if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { - udp_server_stats_event_sender - .send(Event::UdpError { - context: ConnectionContext::new(client_socket_addr, server_service_binding), - kind: req_kind, - error: error.clone().into(), - }) - .await; - } + if let Some(udp_server_stats_event_sender) = opt_udp_server_stats_event_sender.as_deref() { + udp_server_stats_event_sender + .send(Event::UdpError { + context: ConnectionContext::new(client_socket_addr, server_service_binding), + kind: req_kind, + error: error.clone().into(), + }) + .await; } } From 21bea5b4bf30f3c220b443fed839521df50f453c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 17:35:17 +0100 Subject: [PATCH 1174/1297] refactor: [#1456] increase ban counters asyncronously --- .../udp-tracker-server/src/environment.rs | 1 + .../udp-tracker-server/src/handlers/mod.rs | 10 ---- .../src/statistics/event/handler.rs | 54 +++++++++++++++++-- .../src/statistics/event/listener.rs | 17 ++++-- src/bootstrap/jobs/udp_tracker_server.rs | 1 + 5 files changed, 65 insertions(+), 18 deletions(-) diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 3f479a02d..268259f1b 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -82,6 +82,7 @@ impl Environment { let udp_server_event_listener_job = Some(crate::statistics::event::listener::run_event_listener( self.container.udp_tracker_server_container.event_bus.receiver(), &self.container.udp_tracker_server_container.stats_repository, + &self.container.udp_tracker_core_container.ban_service, )); // Start the UDP tracker server diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 69c62a638..0bd455701 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -13,7 +13,6 @@ use announce::handle_announce; use aquatic_udp_protocol::{Request, Response, TransactionId}; use bittorrent_tracker_core::MAX_SCRAPE_TORRENTS; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; -use bittorrent_udp_tracker_core::services::announce::UdpAnnounceError; use connect::handle_connect; use error::handle_error; use scrape::handle_scrape; @@ -84,15 +83,6 @@ pub(crate) async fn handle_packet( { Ok((response, req_kid)) => return (response, Some(req_kid)), Err((error, transaction_id, req_kind)) => { - if let Error::UdpAnnounceError { - source: UdpAnnounceError::ConnectionCookieError { .. }, - } = error - { - // code-review: should we include `RequestParseError` and `BadRequest`? - let mut ban_service = udp_tracker_core_container.ban_service.write().await; - ban_service.increase_counter(&udp_request.from.ip()); - } - let response = handle_error( Some(req_kind.clone()), udp_request.from, diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index b231d8336..394850844 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -1,8 +1,12 @@ +use std::sync::Arc; + +use bittorrent_udp_tracker_core::services::banning::BanService; +use tokio::sync::RwLock; use torrust_tracker_metrics::label::{LabelSet, LabelValue}; use torrust_tracker_metrics::{label_name, metric_name}; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use crate::event::{Event, UdpRequestKind, UdpResponseKind}; +use crate::event::{ErrorKind, Event, UdpRequestKind, UdpResponseKind}; use crate::statistics::repository::Repository; use crate::statistics::{ UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, @@ -16,7 +20,12 @@ use crate::statistics::{ /// This function panics if the client IP version does not match the expected /// version. #[allow(clippy::too_many_lines)] -pub async fn handle_event(event: Event, stats_repository: &Repository, now: DurationSinceUnixEpoch) { +pub async fn handle_event( + event: Event, + stats_repository: &Repository, + ban_service: &Arc>, + now: DurationSinceUnixEpoch, +) { match event { Event::UdpRequestAborted { context } => { // Global fixed metrics @@ -232,7 +241,14 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura Err(err) => tracing::error!("Failed to increase the counter: {}", err), }; } - Event::UdpError { context, kind, error: _ } => { + Event::UdpError { context, kind, error } => { + // Increase the number of errors + // code-review: should we ban IP due to other errors too? + if let ErrorKind::ConnectionCookie(_msg) = error { + let mut ban_service = ban_service.write().await; + ban_service.increase_counter(&context.client_socket_addr().ip()); + } + // Global fixed metrics match context.client_socket_addr().ip() { std::net::IpAddr::V4(_) => { @@ -267,7 +283,9 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + use bittorrent_udp_tracker_core::services::banning::BanService; use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -279,6 +297,7 @@ mod tests { #[tokio::test] async fn should_increase_the_number_of_aborted_requests_when_it_receives_a_udp_request_aborted_event() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAborted { @@ -292,6 +311,7 @@ mod tests { ), }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -304,6 +324,7 @@ mod tests { #[tokio::test] async fn should_increase_the_number_of_banned_requests_when_it_receives_a_udp_request_banned_event() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestBanned { @@ -317,6 +338,7 @@ mod tests { ), }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -329,6 +351,7 @@ mod tests { #[tokio::test] async fn should_increase_the_number_of_incoming_requests_when_it_receives_a_udp4_incoming_request_event() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestReceived { @@ -342,6 +365,7 @@ mod tests { ), }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -354,6 +378,7 @@ mod tests { #[tokio::test] async fn should_increase_the_udp_abort_counter_when_it_receives_a_udp_abort_event() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAborted { @@ -367,6 +392,7 @@ mod tests { ), }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -376,6 +402,7 @@ mod tests { #[tokio::test] async fn should_increase_the_udp_ban_counter_when_it_receives_a_udp_banned_event() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestBanned { @@ -389,6 +416,7 @@ mod tests { ), }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -399,6 +427,7 @@ mod tests { #[tokio::test] async fn should_increase_the_udp4_connect_requests_counter_when_it_receives_a_udp4_request_event_of_connect_kind() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAccepted { @@ -413,6 +442,7 @@ mod tests { kind: crate::event::UdpRequestKind::Connect, }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -425,6 +455,7 @@ mod tests { #[tokio::test] async fn should_increase_the_udp4_announce_requests_counter_when_it_receives_a_udp4_request_event_of_announce_kind() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAccepted { @@ -439,6 +470,7 @@ mod tests { kind: crate::event::UdpRequestKind::Announce, }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -451,6 +483,7 @@ mod tests { #[tokio::test] async fn should_increase_the_udp4_scrape_requests_counter_when_it_receives_a_udp4_request_event_of_scrape_kind() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAccepted { @@ -465,6 +498,7 @@ mod tests { kind: crate::event::UdpRequestKind::Scrape, }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -477,6 +511,7 @@ mod tests { #[tokio::test] async fn should_increase_the_udp4_responses_counter_when_it_receives_a_udp4_response_event() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpResponseSent { @@ -494,6 +529,7 @@ mod tests { req_processing_time: std::time::Duration::from_secs(1), }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -506,6 +542,7 @@ mod tests { #[tokio::test] async fn should_increase_the_udp4_errors_counter_when_it_receives_a_udp4_error_event() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpError { @@ -521,6 +558,7 @@ mod tests { error: ErrorKind::RequestParse("Invalid request format".to_string()), }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -533,6 +571,7 @@ mod tests { #[tokio::test] async fn should_increase_the_udp6_connect_requests_counter_when_it_receives_a_udp6_request_event_of_connect_kind() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAccepted { @@ -547,6 +586,7 @@ mod tests { kind: crate::event::UdpRequestKind::Connect, }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -559,6 +599,7 @@ mod tests { #[tokio::test] async fn should_increase_the_udp6_announce_requests_counter_when_it_receives_a_udp6_request_event_of_announce_kind() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAccepted { @@ -573,6 +614,7 @@ mod tests { kind: crate::event::UdpRequestKind::Announce, }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -585,6 +627,7 @@ mod tests { #[tokio::test] async fn should_increase_the_udp6_scrape_requests_counter_when_it_receives_a_udp6_request_event_of_scrape_kind() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAccepted { @@ -599,6 +642,7 @@ mod tests { kind: crate::event::UdpRequestKind::Scrape, }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -611,6 +655,7 @@ mod tests { #[tokio::test] async fn should_increase_the_udp6_response_counter_when_it_receives_a_udp6_response_event() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpResponseSent { @@ -628,6 +673,7 @@ mod tests { req_processing_time: std::time::Duration::from_secs(1), }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; @@ -639,6 +685,7 @@ mod tests { #[tokio::test] async fn should_increase_the_udp6_errors_counter_when_it_receives_a_udp6_error_event() { let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpError { @@ -654,6 +701,7 @@ mod tests { error: ErrorKind::RequestParse("Invalid request format".to_string()), }, &stats_repository, + &ban_service, CurrentClock::now(), ) .await; diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index d805cc87f..e6c9a85ce 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -1,6 +1,8 @@ use std::sync::Arc; +use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; +use tokio::sync::RwLock; use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; use torrust_tracker_events::receiver::RecvError; @@ -11,19 +13,24 @@ use crate::statistics::repository::Repository; use crate::CurrentClock; #[must_use] -pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { - let stats_repository = repository.clone(); +pub fn run_event_listener( + receiver: Receiver, + repository: &Arc, + ban_service: &Arc>, +) -> JoinHandle<()> { + let repository_clone = repository.clone(); + let ban_service_clone = ban_service.clone(); tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker server event listener"); tokio::spawn(async move { - dispatch_events(receiver, stats_repository).await; + dispatch_events(receiver, repository_clone, ban_service_clone).await; tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker server event listener finished"); }) } -async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { +async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc, ban_service: Arc>) { let shutdown_signal = tokio::signal::ctrl_c(); tokio::pin!(shutdown_signal); @@ -38,7 +45,7 @@ async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc { match result { - Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, + Ok(event) => handle_event(event, &stats_repository, &ban_service, CurrentClock::now()).await, Err(e) => { match e { RecvError::Closed => { diff --git a/src/bootstrap/jobs/udp_tracker_server.rs b/src/bootstrap/jobs/udp_tracker_server.rs index 42ac2d03e..8a4c2a273 100644 --- a/src/bootstrap/jobs/udp_tracker_server.rs +++ b/src/bootstrap/jobs/udp_tracker_server.rs @@ -10,6 +10,7 @@ pub fn start_event_listener(config: &Configuration, app_container: &Arc Date: Mon, 2 Jun 2025 17:49:41 +0100 Subject: [PATCH 1175/1297] refactor: rename UDP tracker server error variants --- packages/udp-tracker-server/src/error.rs | 16 ++++++++-------- packages/udp-tracker-server/src/event.rs | 10 +++++----- packages/udp-tracker-server/src/handlers/mod.rs | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/packages/udp-tracker-server/src/error.rs b/packages/udp-tracker-server/src/error.rs index 697cc5cab..d260ebfd4 100644 --- a/packages/udp-tracker-server/src/error.rs +++ b/packages/udp-tracker-server/src/error.rs @@ -17,31 +17,31 @@ pub struct ConnectionCookie(pub ConnectionId); pub enum Error { /// Error returned when the request is invalid. #[error("error parsing request: {request_parse_error:?}")] - RequestParseError { request_parse_error: SendableRequestParseError }, + InvalidRequest { request_parse_error: SendableRequestParseError }, /// Error returned when the domain tracker returns an announce error. #[error("tracker announce error: {source}")] - UdpAnnounceError { source: UdpAnnounceError }, + AnnounceFailed { source: UdpAnnounceError }, /// Error returned when the domain tracker returns an scrape error. #[error("tracker scrape error: {source}")] - UdpScrapeError { source: UdpScrapeError }, + ScrapeFailed { source: UdpScrapeError }, /// Error returned from a third-party library (`aquatic_udp_protocol`). #[error("internal server error: {message}, {location}")] - InternalServer { + Internal { location: &'static Location<'static>, message: String, }, /// Error returned when tracker requires authentication. #[error("domain tracker requires authentication but is not supported in current UDP implementation. Location: {location}")] - TrackerAuthenticationRequired { location: &'static Location<'static> }, + AuthRequired { location: &'static Location<'static> }, } impl From for Error { fn from(request_parse_error: RequestParseError) -> Self { - Self::RequestParseError { + Self::InvalidRequest { request_parse_error: request_parse_error.into(), } } @@ -49,7 +49,7 @@ impl From for Error { impl From for Error { fn from(udp_announce_error: UdpAnnounceError) -> Self { - Self::UdpAnnounceError { + Self::AnnounceFailed { source: udp_announce_error, } } @@ -57,7 +57,7 @@ impl From for Error { impl From for Error { fn from(udp_scrape_error: UdpScrapeError) -> Self { - Self::UdpScrapeError { + Self::ScrapeFailed { source: udp_scrape_error, } } diff --git a/packages/udp-tracker-server/src/event.rs b/packages/udp-tracker-server/src/event.rs index e320ceb8a..4fa29940e 100644 --- a/packages/udp-tracker-server/src/event.rs +++ b/packages/udp-tracker-server/src/event.rs @@ -129,8 +129,8 @@ pub enum ErrorKind { impl From for ErrorKind { fn from(error: Error) -> Self { match error { - Error::RequestParseError { request_parse_error } => Self::RequestParse(request_parse_error.to_string()), - Error::UdpAnnounceError { source } => match source { + Error::InvalidRequest { request_parse_error } => Self::RequestParse(request_parse_error.to_string()), + Error::AnnounceFailed { source } => match source { UdpAnnounceError::ConnectionCookieError { source } => Self::ConnectionCookie(source.to_string()), UdpAnnounceError::TrackerCoreAnnounceError { source } => match source { AnnounceError::Whitelist(whitelist_error) => Self::Whitelist(whitelist_error.to_string()), @@ -138,15 +138,15 @@ impl From for ErrorKind { }, UdpAnnounceError::TrackerCoreWhitelistError { source } => Self::Whitelist(source.to_string()), }, - Error::UdpScrapeError { source } => match source { + Error::ScrapeFailed { source } => match source { UdpScrapeError::ConnectionCookieError { source } => Self::ConnectionCookie(source.to_string()), UdpScrapeError::TrackerCoreScrapeError { source } => match source { ScrapeError::Whitelist(whitelist_error) => Self::Whitelist(whitelist_error.to_string()), }, UdpScrapeError::TrackerCoreWhitelistError { source } => Self::Whitelist(source.to_string()), }, - Error::InternalServer { location: _, message } => Self::InternalServer(message.to_string()), - Error::TrackerAuthenticationRequired { location } => Self::TrackerAuthentication(location.to_string()), + Error::Internal { location: _, message } => Self::InternalServer(message.to_string()), + Error::AuthRequired { location } => Self::TrackerAuthentication(location.to_string()), } } } diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 0bd455701..c1125b97f 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -101,7 +101,7 @@ pub(crate) async fn handle_packet( Err(e) => { // The request payload could not be parsed, so we handle it as an error. - let opt_transaction_id = if let Error::RequestParseError { request_parse_error } = e.clone() { + let opt_transaction_id = if let Error::InvalidRequest { request_parse_error } = e.clone() { request_parse_error.opt_transaction_id } else { None From 89ac87cbc1c26fd93e6a019faeb10161f9f6e058 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 18:03:25 +0100 Subject: [PATCH 1176/1297] refactor: [#1551] extract methods in udp event handler" --- .../src/statistics/event/handler.rs | 482 +++++++++--------- 1 file changed, 254 insertions(+), 228 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs index 394850844..a1e9007e9 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler.rs @@ -6,7 +6,7 @@ use torrust_tracker_metrics::label::{LabelSet, LabelValue}; use torrust_tracker_metrics::{label_name, metric_name}; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use crate::event::{ErrorKind, Event, UdpRequestKind, UdpResponseKind}; +use crate::event::{ConnectionContext, ErrorKind, Event, UdpRequestKind, UdpResponseKind}; use crate::statistics::repository::Repository; use crate::statistics::{ UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, @@ -15,10 +15,6 @@ use crate::statistics::{ UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL, }; -/// # Panics -/// -/// This function panics if the client IP version does not match the expected -/// version. #[allow(clippy::too_many_lines)] pub async fn handle_event( event: Event, @@ -28,256 +24,286 @@ pub async fn handle_event( ) { match event { Event::UdpRequestAborted { context } => { - // Global fixed metrics - stats_repository.increase_udp_requests_aborted().await; - - // Extendable metrics - match stats_repository - .increase_counter( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), - &LabelSet::from(context), - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + handle_udp_request_aborted_event(context, stats_repository, now).await; } Event::UdpRequestBanned { context } => { - // Global fixed metrics - stats_repository.increase_udp_requests_banned().await; - - // Extendable metrics - match stats_repository - .increase_counter( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), - &LabelSet::from(context), - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + handle_udp_request_banned_event(context, stats_repository, now).await; } Event::UdpRequestReceived { context } => { - // Global fixed metrics - match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_requests().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_requests().await; - } - } - - // Extendable metrics - match stats_repository - .increase_counter( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), - &LabelSet::from(context), - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + handle_udp_request_received_event(context, stats_repository, now).await; } Event::UdpRequestAccepted { context, kind } => { - // Global fixed metrics - match kind { - UdpRequestKind::Connect => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_connections().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_connections().await; - } - }, - UdpRequestKind::Announce => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_announces().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_announces().await; - } - }, - UdpRequestKind::Scrape => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_scrapes().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_scrapes().await; - } - }, - } - - // Extendable metrics - - let mut label_set = LabelSet::from(context); - - label_set.upsert(label_name!("request_kind"), LabelValue::new(&kind.to_string())); - - match stats_repository - .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &label_set, now) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + handle_udp_request_accepted_event(context, kind, stats_repository, now).await; } Event::UdpResponseSent { context, kind, req_processing_time, } => { - // Global fixed metrics - match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_responses().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_responses().await; - } - } + handle_udp_response_sent_event(context, kind, req_processing_time, stats_repository, now).await; + } + Event::UdpError { context, kind, error } => { + handle_udp_error_event(context, kind, error, stats_repository, ban_service, now).await; + } + } - let (result_label_value, kind_label_value) = match kind { - UdpResponseKind::Ok { req_kind } => match req_kind { - UdpRequestKind::Connect => { - let new_avg = stats_repository - .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) - .await; - - // Extendable metrics - - let mut label_set = LabelSet::from(context.clone()); - label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); - - match stats_repository - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &label_set, - new_avg, - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to set gauge: {}", err), - } - - (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Connect.to_string())) - } - UdpRequestKind::Announce => { - let new_avg = stats_repository - .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) - .await; - - // Extendable metrics - - let mut label_set = LabelSet::from(context.clone()); - label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); - - match stats_repository - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &label_set, - new_avg, - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to set gauge: {}", err), - } - - (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Announce.to_string())) - } - UdpRequestKind::Scrape => { - let new_avg = stats_repository - .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) - .await; - - // Extendable metrics - - let mut label_set = LabelSet::from(context.clone()); - label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); - - match stats_repository - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &label_set, - new_avg, - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to set gauge: {}", err), - } - - (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Scrape.to_string())) - } - }, - UdpResponseKind::Error { opt_req_kind: _ } => (LabelValue::new("error"), LabelValue::ignore()), - }; + tracing::debug!("stats: {:?}", stats_repository.get_stats().await); +} - // Extendable metrics +async fn handle_udp_request_aborted_event( + context: ConnectionContext, + stats_repository: &Repository, + now: DurationSinceUnixEpoch, +) { + // Global fixed metrics + stats_repository.increase_udp_requests_aborted().await; + + // Extendable metrics + match stats_repository + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), + &LabelSet::from(context), + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} - let mut label_set = LabelSet::from(context); +async fn handle_udp_request_banned_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { + // Global fixed metrics + stats_repository.increase_udp_requests_banned().await; - if result_label_value == LabelValue::new("ok") { - label_set.upsert(label_name!("request_kind"), kind_label_value); - } - label_set.upsert(label_name!("result"), result_label_value); - - match stats_repository - .increase_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &label_set, now) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + // Extendable metrics + match stats_repository + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), + &LabelSet::from(context), + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +async fn handle_udp_request_received_event( + context: ConnectionContext, + stats_repository: &Repository, + now: DurationSinceUnixEpoch, +) { + // Global fixed metrics + match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_requests().await; } - Event::UdpError { context, kind, error } => { - // Increase the number of errors - // code-review: should we ban IP due to other errors too? - if let ErrorKind::ConnectionCookie(_msg) = error { - let mut ban_service = ban_service.write().await; - ban_service.increase_counter(&context.client_socket_addr().ip()); - } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_requests().await; + } + } - // Global fixed metrics - match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_errors().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_errors().await; - } + // Extendable metrics + match stats_repository + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), + &LabelSet::from(context), + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +async fn handle_udp_request_accepted_event( + context: ConnectionContext, + kind: UdpRequestKind, + stats_repository: &Repository, + now: DurationSinceUnixEpoch, +) { + // Global fixed metrics + match kind { + UdpRequestKind::Connect => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_connections().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_connections().await; + } + }, + UdpRequestKind::Announce => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_announces().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_announces().await; + } + }, + UdpRequestKind::Scrape => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_scrapes().await; } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_scrapes().await; + } + }, + } - // Extendable metrics + // Extendable metrics + let mut label_set = LabelSet::from(context); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&kind.to_string())); + match stats_repository + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} - let mut label_set = LabelSet::from(context); +/// # Panics +/// +/// This function panics if the client IP version does not match the expected +/// version. +async fn handle_udp_response_sent_event( + context: ConnectionContext, + kind: UdpResponseKind, + req_processing_time: std::time::Duration, + stats_repository: &Repository, + now: DurationSinceUnixEpoch, +) { + // Global fixed metrics + match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_responses().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_responses().await; + } + } - if let Some(kind) = kind { - label_set.upsert(label_name!("request_kind"), kind.to_string().into()); + let (result_label_value, kind_label_value) = match kind { + UdpResponseKind::Ok { req_kind } => match req_kind { + UdpRequestKind::Connect => { + let new_avg = stats_repository + .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) + .await; + let mut label_set = LabelSet::from(context.clone()); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); + match stats_repository + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &label_set, + new_avg, + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Connect.to_string())) } + UdpRequestKind::Announce => { + let new_avg = stats_repository + .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) + .await; + let mut label_set = LabelSet::from(context.clone()); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); + match stats_repository + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &label_set, + new_avg, + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Announce.to_string())) + } + UdpRequestKind::Scrape => { + let new_avg = stats_repository + .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) + .await; + let mut label_set = LabelSet::from(context.clone()); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); + match stats_repository + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &label_set, + new_avg, + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Scrape.to_string())) + } + }, + UdpResponseKind::Error { opt_req_kind: _ } => (LabelValue::new("error"), LabelValue::ignore()), + }; + + // Extendable metrics + let mut label_set = LabelSet::from(context); + if result_label_value == LabelValue::new("ok") { + label_set.upsert(label_name!("request_kind"), kind_label_value); + } + label_set.upsert(label_name!("result"), result_label_value); + match stats_repository + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +async fn handle_udp_error_event( + context: ConnectionContext, + kind: Option, + error: ErrorKind, + stats_repository: &Repository, + ban_service: &Arc>, + now: DurationSinceUnixEpoch, +) { + // Increase the number of errors + // code-review: should we ban IP due to other errors too? + if let ErrorKind::ConnectionCookie(_msg) = error { + let mut ban_service = ban_service.write().await; + ban_service.increase_counter(&context.client_socket_addr().ip()); + } - match stats_repository - .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &label_set, now) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + // Global fixed metrics + match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_errors().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_errors().await; } } - tracing::debug!("stats: {:?}", stats_repository.get_stats().await); + // Extendable metrics + let mut label_set = LabelSet::from(context); + if let Some(kind) = kind { + label_set.upsert(label_name!("request_kind"), kind.to_string().into()); + } + match stats_repository + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; } #[cfg(test)] From a8f3a973c661815b7721d87cc24b828915d0deec Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 2 Jun 2025 18:47:46 +0100 Subject: [PATCH 1177/1297] refactor: [#1551] extract event handler for each udp event --- .../src/statistics/event/handler.rs | 739 ------------------ .../src/statistics/event/handler/error.rs | 95 +++ .../src/statistics/event/handler/mod.rs | 49 ++ .../event/handler/request_aborted.rs | 92 +++ .../event/handler/request_accepted.rs | 236 ++++++ .../event/handler/request_banned.rs | 92 +++ .../event/handler/request_received.rs | 74 ++ .../statistics/event/handler/response_sent.rs | 182 +++++ 8 files changed, 820 insertions(+), 739 deletions(-) delete mode 100644 packages/udp-tracker-server/src/statistics/event/handler.rs create mode 100644 packages/udp-tracker-server/src/statistics/event/handler/error.rs create mode 100644 packages/udp-tracker-server/src/statistics/event/handler/mod.rs create mode 100644 packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs create mode 100644 packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs create mode 100644 packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs create mode 100644 packages/udp-tracker-server/src/statistics/event/handler/request_received.rs create mode 100644 packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs diff --git a/packages/udp-tracker-server/src/statistics/event/handler.rs b/packages/udp-tracker-server/src/statistics/event/handler.rs deleted file mode 100644 index a1e9007e9..000000000 --- a/packages/udp-tracker-server/src/statistics/event/handler.rs +++ /dev/null @@ -1,739 +0,0 @@ -use std::sync::Arc; - -use bittorrent_udp_tracker_core::services::banning::BanService; -use tokio::sync::RwLock; -use torrust_tracker_metrics::label::{LabelSet, LabelValue}; -use torrust_tracker_metrics::{label_name, metric_name}; -use torrust_tracker_primitives::DurationSinceUnixEpoch; - -use crate::event::{ConnectionContext, ErrorKind, Event, UdpRequestKind, UdpResponseKind}; -use crate::statistics::repository::Repository; -use crate::statistics::{ - UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, - UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL, - UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL, - UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL, -}; - -#[allow(clippy::too_many_lines)] -pub async fn handle_event( - event: Event, - stats_repository: &Repository, - ban_service: &Arc>, - now: DurationSinceUnixEpoch, -) { - match event { - Event::UdpRequestAborted { context } => { - handle_udp_request_aborted_event(context, stats_repository, now).await; - } - Event::UdpRequestBanned { context } => { - handle_udp_request_banned_event(context, stats_repository, now).await; - } - Event::UdpRequestReceived { context } => { - handle_udp_request_received_event(context, stats_repository, now).await; - } - Event::UdpRequestAccepted { context, kind } => { - handle_udp_request_accepted_event(context, kind, stats_repository, now).await; - } - Event::UdpResponseSent { - context, - kind, - req_processing_time, - } => { - handle_udp_response_sent_event(context, kind, req_processing_time, stats_repository, now).await; - } - Event::UdpError { context, kind, error } => { - handle_udp_error_event(context, kind, error, stats_repository, ban_service, now).await; - } - } - - tracing::debug!("stats: {:?}", stats_repository.get_stats().await); -} - -async fn handle_udp_request_aborted_event( - context: ConnectionContext, - stats_repository: &Repository, - now: DurationSinceUnixEpoch, -) { - // Global fixed metrics - stats_repository.increase_udp_requests_aborted().await; - - // Extendable metrics - match stats_repository - .increase_counter( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), - &LabelSet::from(context), - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; -} - -async fn handle_udp_request_banned_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { - // Global fixed metrics - stats_repository.increase_udp_requests_banned().await; - - // Extendable metrics - match stats_repository - .increase_counter( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), - &LabelSet::from(context), - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; -} - -async fn handle_udp_request_received_event( - context: ConnectionContext, - stats_repository: &Repository, - now: DurationSinceUnixEpoch, -) { - // Global fixed metrics - match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_requests().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_requests().await; - } - } - - // Extendable metrics - match stats_repository - .increase_counter( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), - &LabelSet::from(context), - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; -} - -async fn handle_udp_request_accepted_event( - context: ConnectionContext, - kind: UdpRequestKind, - stats_repository: &Repository, - now: DurationSinceUnixEpoch, -) { - // Global fixed metrics - match kind { - UdpRequestKind::Connect => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_connections().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_connections().await; - } - }, - UdpRequestKind::Announce => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_announces().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_announces().await; - } - }, - UdpRequestKind::Scrape => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_scrapes().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_scrapes().await; - } - }, - } - - // Extendable metrics - let mut label_set = LabelSet::from(context); - label_set.upsert(label_name!("request_kind"), LabelValue::new(&kind.to_string())); - match stats_repository - .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &label_set, now) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; -} - -/// # Panics -/// -/// This function panics if the client IP version does not match the expected -/// version. -async fn handle_udp_response_sent_event( - context: ConnectionContext, - kind: UdpResponseKind, - req_processing_time: std::time::Duration, - stats_repository: &Repository, - now: DurationSinceUnixEpoch, -) { - // Global fixed metrics - match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_responses().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_responses().await; - } - } - - let (result_label_value, kind_label_value) = match kind { - UdpResponseKind::Ok { req_kind } => match req_kind { - UdpRequestKind::Connect => { - let new_avg = stats_repository - .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) - .await; - let mut label_set = LabelSet::from(context.clone()); - label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); - match stats_repository - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &label_set, - new_avg, - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to set gauge: {}", err), - } - (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Connect.to_string())) - } - UdpRequestKind::Announce => { - let new_avg = stats_repository - .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) - .await; - let mut label_set = LabelSet::from(context.clone()); - label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); - match stats_repository - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &label_set, - new_avg, - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to set gauge: {}", err), - } - (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Announce.to_string())) - } - UdpRequestKind::Scrape => { - let new_avg = stats_repository - .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) - .await; - let mut label_set = LabelSet::from(context.clone()); - label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); - match stats_repository - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &label_set, - new_avg, - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to set gauge: {}", err), - } - (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Scrape.to_string())) - } - }, - UdpResponseKind::Error { opt_req_kind: _ } => (LabelValue::new("error"), LabelValue::ignore()), - }; - - // Extendable metrics - let mut label_set = LabelSet::from(context); - if result_label_value == LabelValue::new("ok") { - label_set.upsert(label_name!("request_kind"), kind_label_value); - } - label_set.upsert(label_name!("result"), result_label_value); - match stats_repository - .increase_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &label_set, now) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; -} - -async fn handle_udp_error_event( - context: ConnectionContext, - kind: Option, - error: ErrorKind, - stats_repository: &Repository, - ban_service: &Arc>, - now: DurationSinceUnixEpoch, -) { - // Increase the number of errors - // code-review: should we ban IP due to other errors too? - if let ErrorKind::ConnectionCookie(_msg) = error { - let mut ban_service = ban_service.write().await; - ban_service.increase_counter(&context.client_socket_addr().ip()); - } - - // Global fixed metrics - match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_errors().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_errors().await; - } - } - - // Extendable metrics - let mut label_set = LabelSet::from(context); - if let Some(kind) = kind { - label_set.upsert(label_name!("request_kind"), kind.to_string().into()); - } - match stats_repository - .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &label_set, now) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; -} - -#[cfg(test)] -mod tests { - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use std::sync::Arc; - - use bittorrent_udp_tracker_core::services::banning::BanService; - use torrust_tracker_clock::clock::Time; - use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; - - use crate::event::{ConnectionContext, ErrorKind, Event, UdpRequestKind}; - use crate::statistics::event::handler::handle_event; - use crate::statistics::repository::Repository; - use crate::CurrentClock; - - #[tokio::test] - async fn should_increase_the_number_of_aborted_requests_when_it_receives_a_udp_request_aborted_event() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpRequestAborted { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp_requests_aborted, 1); - } - - #[tokio::test] - async fn should_increase_the_number_of_banned_requests_when_it_receives_a_udp_request_banned_event() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpRequestBanned { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp_requests_banned, 1); - } - - #[tokio::test] - async fn should_increase_the_number_of_incoming_requests_when_it_receives_a_udp4_incoming_request_event() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpRequestReceived { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_requests, 1); - } - - #[tokio::test] - async fn should_increase_the_udp_abort_counter_when_it_receives_a_udp_abort_event() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpRequestAborted { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp_requests_aborted, 1); - } - #[tokio::test] - async fn should_increase_the_udp_ban_counter_when_it_receives_a_udp_banned_event() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpRequestBanned { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp_requests_banned, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_connect_requests_counter_when_it_receives_a_udp4_request_event_of_connect_kind() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpRequestAccepted { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - kind: crate::event::UdpRequestKind::Connect, - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_announce_requests_counter_when_it_receives_a_udp4_request_event_of_announce_kind() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpRequestAccepted { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - kind: crate::event::UdpRequestKind::Announce, - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_scrape_requests_counter_when_it_receives_a_udp4_request_event_of_scrape_kind() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpRequestAccepted { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - kind: crate::event::UdpRequestKind::Scrape, - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_scrapes_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_responses_counter_when_it_receives_a_udp4_response_event() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpResponseSent { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - kind: crate::event::UdpResponseKind::Ok { - req_kind: UdpRequestKind::Announce, - }, - req_processing_time: std::time::Duration::from_secs(1), - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_responses, 1); - } - - #[tokio::test] - async fn should_increase_the_udp4_errors_counter_when_it_receives_a_udp4_error_event() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpError { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - kind: None, - error: ErrorKind::RequestParse("Invalid request format".to_string()), - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp4_errors_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_connect_requests_counter_when_it_receives_a_udp6_request_event_of_connect_kind() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpRequestAccepted { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - kind: crate::event::UdpRequestKind::Connect, - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_connections_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_announce_requests_counter_when_it_receives_a_udp6_request_event_of_announce_kind() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpRequestAccepted { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - kind: crate::event::UdpRequestKind::Announce, - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_announces_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_scrape_requests_counter_when_it_receives_a_udp6_request_event_of_scrape_kind() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpRequestAccepted { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - kind: crate::event::UdpRequestKind::Scrape, - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_scrapes_handled, 1); - } - - #[tokio::test] - async fn should_increase_the_udp6_response_counter_when_it_receives_a_udp6_response_event() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpResponseSent { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - kind: crate::event::UdpResponseKind::Ok { - req_kind: UdpRequestKind::Announce, - }, - req_processing_time: std::time::Duration::from_secs(1), - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_responses, 1); - } - #[tokio::test] - async fn should_increase_the_udp6_errors_counter_when_it_receives_a_udp6_error_event() { - let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); - - handle_event( - Event::UdpError { - context: ConnectionContext::new( - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), - ServiceBinding::new( - Protocol::UDP, - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), - ) - .unwrap(), - ), - kind: None, - error: ErrorKind::RequestParse("Invalid request format".to_string()), - }, - &stats_repository, - &ban_service, - CurrentClock::now(), - ) - .await; - - let stats = stats_repository.get_stats().await; - - assert_eq!(stats.udp6_errors_handled, 1); - } -} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/error.rs b/packages/udp-tracker-server/src/statistics/event/handler/error.rs new file mode 100644 index 000000000..e1023a56b --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/error.rs @@ -0,0 +1,95 @@ +use std::sync::Arc; + +use bittorrent_udp_tracker_core::services::banning::BanService; +use tokio::sync::RwLock; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::{label_name, metric_name}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::{ConnectionContext, ErrorKind, UdpRequestKind}; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_SERVER_ERRORS_TOTAL; + +pub async fn handle_event( + context: ConnectionContext, + kind: Option, + error: ErrorKind, + stats_repository: &Repository, + ban_service: &Arc>, + now: DurationSinceUnixEpoch, +) { + // Increase the number of errors + // code-review: should we ban IP due to other errors too? + if let ErrorKind::ConnectionCookie(_msg) = error { + let mut ban_service = ban_service.write().await; + ban_service.increase_counter(&context.client_socket_addr().ip()); + } + + // Global fixed metrics + match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_errors().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_errors().await; + } + } + + // Extendable metrics + let mut label_set = LabelSet::from(context); + if let Some(kind) = kind { + label_set.upsert(label_name!("request_kind"), kind.to_string().into()); + } + match stats_repository + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use bittorrent_udp_tracker_core::services::banning::BanService; + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::statistics::event::handler::error::ErrorKind; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_udp4_errors_counter_when_it_receives_a_udp4_error_event() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpError { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: None, + error: ErrorKind::RequestParse("Invalid request format".to_string()), + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_errors_handled, 1); + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/mod.rs b/packages/udp-tracker-server/src/statistics/event/handler/mod.rs new file mode 100644 index 000000000..c8ac864a3 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/mod.rs @@ -0,0 +1,49 @@ +mod error; +mod request_aborted; +mod request_accepted; +mod request_banned; +mod request_received; +mod response_sent; + +use std::sync::Arc; + +use bittorrent_udp_tracker_core::services::banning::BanService; +use tokio::sync::RwLock; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::Event; +use crate::statistics::repository::Repository; + +pub async fn handle_event( + event: Event, + stats_repository: &Repository, + ban_service: &Arc>, + now: DurationSinceUnixEpoch, +) { + match event { + Event::UdpRequestAborted { context } => { + request_aborted::handle_event(context, stats_repository, now).await; + } + Event::UdpRequestBanned { context } => { + request_banned::handle_event(context, stats_repository, now).await; + } + Event::UdpRequestReceived { context } => { + request_received::handle_event(context, stats_repository, now).await; + } + Event::UdpRequestAccepted { context, kind } => { + request_accepted::handle_event(context, kind, stats_repository, now).await; + } + Event::UdpResponseSent { + context, + kind, + req_processing_time, + } => { + response_sent::handle_event(context, kind, req_processing_time, stats_repository, now).await; + } + Event::UdpError { context, kind, error } => { + error::handle_event(context, kind, error, stats_repository, ban_service, now).await; + } + } + + tracing::debug!("stats: {:?}", stats_repository.get_stats().await); +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs new file mode 100644 index 000000000..270ec2a45 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs @@ -0,0 +1,92 @@ +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::ConnectionContext; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL; + +pub async fn handle_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { + // Global fixed metrics + stats_repository.increase_udp_requests_aborted().await; + + // Extendable metrics + match stats_repository + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), + &LabelSet::from(context), + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use bittorrent_udp_tracker_core::services::banning::BanService; + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_number_of_aborted_requests_when_it_receives_a_udp_request_aborted_event() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpRequestAborted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp_requests_aborted, 1); + } + + #[tokio::test] + async fn should_increase_the_udp_abort_counter_when_it_receives_a_udp_abort_event() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpRequestAborted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + let stats = stats_repository.get_stats().await; + assert_eq!(stats.udp_requests_aborted, 1); + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs new file mode 100644 index 000000000..25c1311e5 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs @@ -0,0 +1,236 @@ +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::{label_name, metric_name}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::{ConnectionContext, UdpRequestKind}; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL; + +pub async fn handle_event( + context: ConnectionContext, + kind: UdpRequestKind, + stats_repository: &Repository, + now: DurationSinceUnixEpoch, +) { + // Global fixed metrics + match kind { + UdpRequestKind::Connect => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_connections().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_connections().await; + } + }, + UdpRequestKind::Announce => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_announces().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_announces().await; + } + }, + UdpRequestKind::Scrape => match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_scrapes().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_scrapes().await; + } + }, + } + + // Extendable metrics + let mut label_set = LabelSet::from(context); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&kind.to_string())); + match stats_repository + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + + use bittorrent_udp_tracker_core::services::banning::BanService; + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_udp4_connect_requests_counter_when_it_receives_a_udp4_request_event_of_connect_kind() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpRequestAccepted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpRequestKind::Connect, + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_announce_requests_counter_when_it_receives_a_udp4_request_event_of_announce_kind() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpRequestAccepted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpRequestKind::Announce, + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_announces_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp4_scrape_requests_counter_when_it_receives_a_udp4_request_event_of_scrape_kind() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpRequestAccepted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpRequestKind::Scrape, + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_scrapes_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_connect_requests_counter_when_it_receives_a_udp6_request_event_of_connect_kind() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpRequestAccepted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpRequestKind::Connect, + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_connections_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_announce_requests_counter_when_it_receives_a_udp6_request_event_of_announce_kind() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpRequestAccepted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpRequestKind::Announce, + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_announces_handled, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_scrape_requests_counter_when_it_receives_a_udp6_request_event_of_scrape_kind() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpRequestAccepted { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpRequestKind::Scrape, + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_scrapes_handled, 1); + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs new file mode 100644 index 000000000..74641574a --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs @@ -0,0 +1,92 @@ +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::ConnectionContext; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL; + +pub async fn handle_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { + // Global fixed metrics + stats_repository.increase_udp_requests_banned().await; + + // Extendable metrics + match stats_repository + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), + &LabelSet::from(context), + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use bittorrent_udp_tracker_core::services::banning::BanService; + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_number_of_banned_requests_when_it_receives_a_udp_request_banned_event() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpRequestBanned { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp_requests_banned, 1); + } + + #[tokio::test] + async fn should_increase_the_udp_ban_counter_when_it_receives_a_udp_banned_event() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpRequestBanned { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + let stats = stats_repository.get_stats().await; + assert_eq!(stats.udp_requests_banned, 1); + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs new file mode 100644 index 000000000..8333258c2 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs @@ -0,0 +1,74 @@ +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::ConnectionContext; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL; + +pub async fn handle_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { + // Global fixed metrics + match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_requests().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_requests().await; + } + } + + // Extendable metrics + match stats_repository + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), + &LabelSet::from(context), + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use std::sync::Arc; + + use bittorrent_udp_tracker_core::services::banning::BanService; + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event}; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_number_of_incoming_requests_when_it_receives_a_udp4_incoming_request_event() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpRequestReceived { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_requests, 1); + } +} diff --git a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs new file mode 100644 index 000000000..a69184e08 --- /dev/null +++ b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs @@ -0,0 +1,182 @@ +use torrust_tracker_metrics::label::{LabelSet, LabelValue}; +use torrust_tracker_metrics::{label_name, metric_name}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::{ConnectionContext, UdpRequestKind, UdpResponseKind}; +use crate::statistics::repository::Repository; +use crate::statistics::{UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL}; + +pub async fn handle_event( + context: ConnectionContext, + kind: UdpResponseKind, + req_processing_time: std::time::Duration, + stats_repository: &Repository, + now: DurationSinceUnixEpoch, +) { + // Global fixed metrics + match context.client_socket_addr().ip() { + std::net::IpAddr::V4(_) => { + stats_repository.increase_udp4_responses().await; + } + std::net::IpAddr::V6(_) => { + stats_repository.increase_udp6_responses().await; + } + } + + let (result_label_value, kind_label_value) = match kind { + UdpResponseKind::Ok { req_kind } => match req_kind { + UdpRequestKind::Connect => { + let new_avg = stats_repository + .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) + .await; + let mut label_set = LabelSet::from(context.clone()); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); + match stats_repository + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &label_set, + new_avg, + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Connect.to_string())) + } + UdpRequestKind::Announce => { + let new_avg = stats_repository + .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) + .await; + let mut label_set = LabelSet::from(context.clone()); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); + match stats_repository + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &label_set, + new_avg, + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Announce.to_string())) + } + UdpRequestKind::Scrape => { + let new_avg = stats_repository + .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) + .await; + let mut label_set = LabelSet::from(context.clone()); + label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); + match stats_repository + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &label_set, + new_avg, + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Scrape.to_string())) + } + }, + UdpResponseKind::Error { opt_req_kind: _ } => (LabelValue::new("error"), LabelValue::ignore()), + }; + + // Extendable metrics + let mut label_set = LabelSet::from(context); + if result_label_value == LabelValue::new("ok") { + label_set.upsert(label_name!("request_kind"), kind_label_value); + } + label_set.upsert(label_name!("result"), result_label_value); + match stats_repository + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::sync::Arc; + + use bittorrent_udp_tracker_core::services::banning::BanService; + use torrust_tracker_clock::clock::Time; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + + use crate::event::{ConnectionContext, Event, UdpRequestKind}; + use crate::statistics::event::handler::handle_event; + use crate::statistics::repository::Repository; + use crate::CurrentClock; + + #[tokio::test] + async fn should_increase_the_udp4_responses_counter_when_it_receives_a_udp4_response_event() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpResponseSent { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpResponseKind::Ok { + req_kind: UdpRequestKind::Announce, + }, + req_processing_time: std::time::Duration::from_secs(1), + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp4_responses, 1); + } + + #[tokio::test] + async fn should_increase_the_udp6_response_counter_when_it_receives_a_udp6_response_event() { + let stats_repository = Repository::new(); + let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); + + handle_event( + Event::UdpResponseSent { + context: ConnectionContext::new( + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 195)), 8080), + ServiceBinding::new( + Protocol::UDP, + SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969), + ) + .unwrap(), + ), + kind: crate::event::UdpResponseKind::Ok { + req_kind: UdpRequestKind::Announce, + }, + req_processing_time: std::time::Duration::from_secs(1), + }, + &stats_repository, + &ban_service, + CurrentClock::now(), + ) + .await; + + let stats = stats_repository.get_stats().await; + + assert_eq!(stats.udp6_responses, 1); + } +} From d9f4c13fa860b835dc2299f9d2688a9467faef73 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 4 Jun 2025 10:22:14 +0100 Subject: [PATCH 1178/1297] refactor: [#1556] extract functions --- .../src/statistics/event/handler/error.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/event/handler/error.rs b/packages/udp-tracker-server/src/statistics/event/handler/error.rs index e1023a56b..5cd57e12b 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/error.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/error.rs @@ -18,14 +18,17 @@ pub async fn handle_event( ban_service: &Arc>, now: DurationSinceUnixEpoch, ) { - // Increase the number of errors - // code-review: should we ban IP due to other errors too? if let ErrorKind::ConnectionCookie(_msg) = error { let mut ban_service = ban_service.write().await; ban_service.increase_counter(&context.client_socket_addr().ip()); } - // Global fixed metrics + update_global_fixed_metrics(&context, stats_repository).await; + + update_extendable_metrics(&context, kind, stats_repository, now).await; +} + +async fn update_global_fixed_metrics(context: &ConnectionContext, stats_repository: &Repository) { match context.client_socket_addr().ip() { std::net::IpAddr::V4(_) => { stats_repository.increase_udp4_errors().await; @@ -34,9 +37,15 @@ pub async fn handle_event( stats_repository.increase_udp6_errors().await; } } +} - // Extendable metrics - let mut label_set = LabelSet::from(context); +async fn update_extendable_metrics( + context: &ConnectionContext, + kind: Option, + stats_repository: &Repository, + now: DurationSinceUnixEpoch, +) { + let mut label_set = LabelSet::from(context.clone()); if let Some(kind) = kind { label_set.upsert(label_name!("request_kind"), kind.to_string().into()); } From 7e616d71afe16e82968e56185df45ee695588e8a Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 4 Jun 2025 12:12:05 +0100 Subject: [PATCH 1179/1297] feat: [#1556] add a new metric to count connection ID errors per clietn software The new metric in Prometheous format: ``` udp_tracker_server_connection_id_errors_total{client_software_name="Transmission",client_software_version="0.12"} 2 ``` --- cSpell.json | 1 + packages/udp-tracker-server/src/event.rs | 15 ++- .../src/handlers/announce.rs | 55 +++++---- .../udp-tracker-server/src/handlers/mod.rs | 2 +- .../src/server/processor.rs | 17 ++- .../src/statistics/event/handler/error.rs | 105 ++++++++++++++---- .../event/handler/request_accepted.rs | 11 +- .../statistics/event/handler/response_sent.rs | 17 ++- .../udp-tracker-server/src/statistics/mod.rs | 7 ++ 9 files changed, 168 insertions(+), 62 deletions(-) diff --git a/cSpell.json b/cSpell.json index e384a08d9..fcbf53f1f 100644 --- a/cSpell.json +++ b/cSpell.json @@ -127,6 +127,7 @@ "proto", "Quickstart", "Radeon", + "Rakshasa", "Rasterbar", "realpath", "reannounce", diff --git a/packages/udp-tracker-server/src/event.rs b/packages/udp-tracker-server/src/event.rs index 4fa29940e..152545e6a 100644 --- a/packages/udp-tracker-server/src/event.rs +++ b/packages/udp-tracker-server/src/event.rs @@ -2,6 +2,7 @@ use std::fmt; use std::net::SocketAddr; use std::time::Duration; +use aquatic_udp_protocol::AnnounceRequest; use bittorrent_tracker_core::error::{AnnounceError, ScrapeError}; use bittorrent_udp_tracker_core::services::announce::UdpAnnounceError; use bittorrent_udp_tracker_core::services::scrape::UdpScrapeError; @@ -42,15 +43,25 @@ pub enum Event { #[derive(Debug, PartialEq, Eq, Clone)] pub enum UdpRequestKind { Connect, - Announce, + Announce { announce_request: AnnounceRequest }, Scrape, } +impl From for LabelValue { + fn from(kind: UdpRequestKind) -> Self { + match kind { + UdpRequestKind::Connect => LabelValue::new("connect"), + UdpRequestKind::Announce { .. } => LabelValue::new("announce"), + UdpRequestKind::Scrape => LabelValue::new("scrape"), + } + } +} + impl fmt::Display for UdpRequestKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let proto_str = match self { UdpRequestKind::Connect => "connect", - UdpRequestKind::Announce => "announce", + UdpRequestKind::Announce { .. } => "announce", UdpRequestKind::Scrape => "scrape", }; write!(f, "{proto_str}") diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 2fc3f6e63..901a1434a 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -44,7 +44,9 @@ pub async fn handle_announce( udp_server_stats_event_sender .send(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), - kind: UdpRequestKind::Announce, + kind: UdpRequestKind::Announce { + announce_request: *request, + }, }) .await; } @@ -52,7 +54,15 @@ pub async fn handle_announce( let announce_data = announce_service .handle_announce(client_socket_addr, server_service_binding, request, cookie_valid_range) .await - .map_err(|e| (e.into(), request.transaction_id, UdpRequestKind::Announce))?; + .map_err(|e| { + ( + e.into(), + request.transaction_id, + UdpRequestKind::Announce { + announce_request: *request, + }, + ) + })?; Ok(build_response(client_socket_addr, request, core_config, &announce_data)) } @@ -118,9 +128,9 @@ fn build_response( } #[cfg(test)] -mod tests { +pub(crate) mod tests { - mod announce_request { + pub mod announce_request { use std::net::Ipv4Addr; use std::num::NonZeroU16; @@ -133,7 +143,7 @@ mod tests { use crate::handlers::tests::{sample_ipv4_remote_addr_fingerprint, sample_issue_time}; - struct AnnounceRequestBuilder { + pub struct AnnounceRequestBuilder { request: AnnounceRequest, } @@ -431,13 +441,14 @@ mod tests { let client_socket_addr = sample_ipv4_socket_address(); let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + let announce_request = AnnounceRequestBuilder::default().into(); let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send() .with(eq(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), - kind: UdpRequestKind::Announce, + kind: UdpRequestKind::Announce { announce_request }, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -451,7 +462,7 @@ mod tests { &core_udp_tracker_services.announce_service, client_socket_addr, server_service_binding, - &AnnounceRequestBuilder::default().into(), + &announce_request, &core_tracker_services.core_config, &udp_server_stats_event_sender, sample_cookie_valid_range(), @@ -795,12 +806,16 @@ mod tests { let server_socket_addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 203, 0, 113, 196)), 6969); let server_service_binding = ServiceBinding::new(Protocol::UDP, server_socket_addr).unwrap(); + let announce_request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .into(); + let mut udp_server_stats_event_sender_mock = MockUdpServerStatsEventSender::new(); udp_server_stats_event_sender_mock .expect_send() .with(eq(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding.clone()), - kind: UdpRequestKind::Announce, + kind: UdpRequestKind::Announce { announce_request }, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -810,10 +825,6 @@ mod tests { let (core_tracker_services, core_udp_tracker_services, _server_udp_tracker_services) = initialize_core_tracker_services_for_default_tracker_configuration(); - let announce_request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) - .into(); - handle_announce( &core_udp_tracker_services.announce_service, client_socket_addr, @@ -887,6 +898,14 @@ mod tests { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); + let request = AnnounceRequestBuilder::default() + .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) + .with_info_hash(info_hash) + .with_peer_id(peer_id) + .with_ip_address(client_ip_v4) + .with_port(client_port) + .into(); + let mut udp_core_stats_event_sender_mock = MockUdpCoreStatsEventSender::new(); udp_core_stats_event_sender_mock .expect_send() @@ -912,7 +931,9 @@ mod tests { .expect_send() .with(eq(Event::UdpRequestAccepted { context: ConnectionContext::new(client_socket_addr, server_service_binding_clone.clone()), - kind: UdpRequestKind::Announce, + kind: UdpRequestKind::Announce { + announce_request: request, + }, })) .times(1) .returning(|_| Box::pin(future::ready(Some(Ok(1))))); @@ -926,14 +947,6 @@ mod tests { &db_downloads_metric_repository, )); - let request = AnnounceRequestBuilder::default() - .with_connection_id(make(gen_remote_fingerprint(&client_socket_addr), sample_issue_time()).unwrap()) - .with_info_hash(info_hash) - .with_peer_id(peer_id) - .with_ip_address(client_ip_v4) - .with_port(client_port) - .into(); - let core_config = Arc::new(config.core.clone()); let announce_service = Arc::new(AnnounceService::new( diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index c1125b97f..3c8204bf5 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -177,7 +177,7 @@ pub async fn handle_request( ) .await { - Ok(response) => Ok((response, UdpRequestKind::Announce)), + Ok(response) => Ok((response, UdpRequestKind::Announce { announce_request })), Err(err) => Err(err), } } diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs index 6b877f85b..dd6ba633d 100644 --- a/packages/udp-tracker-server/src/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -87,16 +87,15 @@ impl Processor { }; let udp_response_kind = match &response { - Response::Connect(_) => event::UdpResponseKind::Ok { - req_kind: event::UdpRequestKind::Connect, - }, - Response::AnnounceIpv4(_) | Response::AnnounceIpv6(_) => event::UdpResponseKind::Ok { - req_kind: event::UdpRequestKind::Announce, - }, - Response::Scrape(_) => event::UdpResponseKind::Ok { - req_kind: event::UdpRequestKind::Scrape, - }, Response::Error(_e) => event::UdpResponseKind::Error { opt_req_kind: None }, + _ => { + if let Some(req_kind) = opt_req_kind { + event::UdpResponseKind::Ok { req_kind } + } else { + // code-review: this case should never happen. + event::UdpResponseKind::Error { opt_req_kind } + } + } }; let mut writer = Cursor::new(Vec::with_capacity(200)); diff --git a/packages/udp-tracker-server/src/statistics/event/handler/error.rs b/packages/udp-tracker-server/src/statistics/event/handler/error.rs index 5cd57e12b..7327386a3 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/error.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/error.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use aquatic_udp_protocol::PeerClient; use bittorrent_udp_tracker_core::services::banning::BanService; use tokio::sync::RwLock; use torrust_tracker_metrics::label::LabelSet; @@ -8,54 +9,118 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::{ConnectionContext, ErrorKind, UdpRequestKind}; use crate::statistics::repository::Repository; -use crate::statistics::UDP_TRACKER_SERVER_ERRORS_TOTAL; +use crate::statistics::{UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL, UDP_TRACKER_SERVER_ERRORS_TOTAL}; pub async fn handle_event( - context: ConnectionContext, - kind: Option, - error: ErrorKind, - stats_repository: &Repository, + connection_context: ConnectionContext, + opt_udp_request_kind: Option, + error_kind: ErrorKind, + repository: &Repository, ban_service: &Arc>, now: DurationSinceUnixEpoch, ) { - if let ErrorKind::ConnectionCookie(_msg) = error { + if let ErrorKind::ConnectionCookie(_msg) = error_kind.clone() { let mut ban_service = ban_service.write().await; - ban_service.increase_counter(&context.client_socket_addr().ip()); + ban_service.increase_counter(&connection_context.client_socket_addr().ip()); } - update_global_fixed_metrics(&context, stats_repository).await; + update_global_fixed_metrics(&connection_context, repository).await; - update_extendable_metrics(&context, kind, stats_repository, now).await; + update_extendable_metrics(&connection_context, opt_udp_request_kind, error_kind, repository, now).await; } -async fn update_global_fixed_metrics(context: &ConnectionContext, stats_repository: &Repository) { - match context.client_socket_addr().ip() { +async fn update_global_fixed_metrics(connection_context: &ConnectionContext, repository: &Repository) { + match connection_context.client_socket_addr().ip() { std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_errors().await; + repository.increase_udp4_errors().await; } std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_errors().await; + repository.increase_udp6_errors().await; } } } async fn update_extendable_metrics( - context: &ConnectionContext, - kind: Option, - stats_repository: &Repository, + connection_context: &ConnectionContext, + opt_udp_request_kind: Option, + error_kind: ErrorKind, + repository: &Repository, now: DurationSinceUnixEpoch, ) { - let mut label_set = LabelSet::from(context.clone()); - if let Some(kind) = kind { + update_all_errors_counter(connection_context, opt_udp_request_kind.clone(), repository, now).await; + update_connection_id_errors_counter(opt_udp_request_kind, error_kind, repository, now).await; +} + +async fn update_all_errors_counter( + connection_context: &ConnectionContext, + opt_udp_request_kind: Option, + repository: &Repository, + now: DurationSinceUnixEpoch, +) { + let mut label_set = LabelSet::from(connection_context.clone()); + + if let Some(kind) = opt_udp_request_kind.clone() { label_set.upsert(label_name!("request_kind"), kind.to_string().into()); } - match stats_repository + + match repository .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &label_set, now) .await { Ok(()) => {} Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + } +} + +async fn update_connection_id_errors_counter( + opt_udp_request_kind: Option, + error_kind: ErrorKind, + repository: &Repository, + now: DurationSinceUnixEpoch, +) { + if let ErrorKind::ConnectionCookie(_) = error_kind { + if let Some(UdpRequestKind::Announce { announce_request }) = opt_udp_request_kind { + let (client_software_name, client_software_version) = extract_name_and_version(&announce_request.peer_id.client()); + + let label_set = LabelSet::from([ + (label_name!("client_software_name"), client_software_name.into()), + (label_name!("client_software_version"), client_software_version.into()), + ]); + + match repository + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL), &label_set, now) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), + }; + } + } +} + +fn extract_name_and_version(peer_client: &PeerClient) -> (String, String) { + match peer_client { + PeerClient::BitTorrent(compact_string) => ("BitTorrent".to_string(), compact_string.as_str().to_owned()), + PeerClient::Deluge(compact_string) => ("Deluge".to_string(), compact_string.as_str().to_owned()), + PeerClient::LibTorrentRakshasa(compact_string) => ("lt (rakshasa)".to_string(), compact_string.as_str().to_owned()), + PeerClient::LibTorrentRasterbar(compact_string) => ("lt (rasterbar)".to_string(), compact_string.as_str().to_owned()), + PeerClient::QBitTorrent(compact_string) => ("QBitTorrent".to_string(), compact_string.as_str().to_owned()), + PeerClient::Transmission(compact_string) => ("Transmission".to_string(), compact_string.as_str().to_owned()), + PeerClient::UTorrent(compact_string) => ("µTorrent".to_string(), compact_string.as_str().to_owned()), + PeerClient::UTorrentEmbedded(compact_string) => ("µTorrent Emb.".to_string(), compact_string.as_str().to_owned()), + PeerClient::UTorrentMac(compact_string) => ("µTorrent Mac".to_string(), compact_string.as_str().to_owned()), + PeerClient::UTorrentWeb(compact_string) => ("µTorrent Web".to_string(), compact_string.as_str().to_owned()), + PeerClient::Vuze(compact_string) => ("Vuze".to_string(), compact_string.as_str().to_owned()), + PeerClient::WebTorrent(compact_string) => ("WebTorrent".to_string(), compact_string.as_str().to_owned()), + PeerClient::WebTorrentDesktop(compact_string) => ("WebTorrent Desktop".to_string(), compact_string.as_str().to_owned()), + PeerClient::Mainline(compact_string) => ("Mainline".to_string(), compact_string.as_str().to_owned()), + PeerClient::OtherWithPrefixAndVersion { prefix, version } => { + (format!("Other ({})", prefix.as_str()), version.as_str().to_owned()) + } + PeerClient::OtherWithPrefix(compact_string) => (format!("Other ({compact_string})"), String::new()), + PeerClient::Other => ("Other".to_string(), String::new()), + _ => ("Unknown".to_string(), String::new()), + } } #[cfg(test)] diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs index 25c1311e5..0007a18b0 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs @@ -22,7 +22,7 @@ pub async fn handle_event( stats_repository.increase_udp6_connections().await; } }, - UdpRequestKind::Announce => match context.client_socket_addr().ip() { + UdpRequestKind::Announce { .. } => match context.client_socket_addr().ip() { std::net::IpAddr::V4(_) => { stats_repository.increase_udp4_announces().await; } @@ -62,6 +62,7 @@ mod tests { use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use crate::event::{ConnectionContext, Event}; + use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; use crate::CurrentClock; @@ -109,7 +110,9 @@ mod tests { ) .unwrap(), ), - kind: crate::event::UdpRequestKind::Announce, + kind: crate::event::UdpRequestKind::Announce { + announce_request: AnnounceRequestBuilder::default().into(), + }, }, &stats_repository, &ban_service, @@ -193,7 +196,9 @@ mod tests { ) .unwrap(), ), - kind: crate::event::UdpRequestKind::Announce, + kind: crate::event::UdpRequestKind::Announce { + announce_request: AnnounceRequestBuilder::default().into(), + }, }, &stats_repository, &ban_service, diff --git a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs index a69184e08..0038ac5f9 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs @@ -43,9 +43,9 @@ pub async fn handle_event( Ok(()) => {} Err(err) => tracing::error!("Failed to set gauge: {}", err), } - (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Connect.to_string())) + (LabelValue::new("ok"), UdpRequestKind::Connect.into()) } - UdpRequestKind::Announce => { + UdpRequestKind::Announce { announce_request } => { let new_avg = stats_repository .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) .await; @@ -63,7 +63,7 @@ pub async fn handle_event( Ok(()) => {} Err(err) => tracing::error!("Failed to set gauge: {}", err), } - (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Announce.to_string())) + (LabelValue::new("ok"), UdpRequestKind::Announce { announce_request }.into()) } UdpRequestKind::Scrape => { let new_avg = stats_repository @@ -113,7 +113,8 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; - use crate::event::{ConnectionContext, Event, UdpRequestKind}; + use crate::event::{ConnectionContext, Event}; + use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::statistics::event::handler::handle_event; use crate::statistics::repository::Repository; use crate::CurrentClock; @@ -134,7 +135,9 @@ mod tests { .unwrap(), ), kind: crate::event::UdpResponseKind::Ok { - req_kind: UdpRequestKind::Announce, + req_kind: crate::event::UdpRequestKind::Announce { + announce_request: AnnounceRequestBuilder::default().into(), + }, }, req_processing_time: std::time::Duration::from_secs(1), }, @@ -165,7 +168,9 @@ mod tests { .unwrap(), ), kind: crate::event::UdpResponseKind::Ok { - req_kind: UdpRequestKind::Announce, + req_kind: crate::event::UdpRequestKind::Announce { + announce_request: AnnounceRequestBuilder::default().into(), + }, }, req_processing_time: std::time::Duration::from_secs(1), }, diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index 8f6e9becf..5c30a9abc 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -10,6 +10,7 @@ use torrust_tracker_metrics::unit::Unit; const UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL: &str = "udp_tracker_server_requests_aborted_total"; const UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL: &str = "udp_tracker_server_requests_banned_total"; +const UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL: &str = "udp_tracker_server_connection_id_errors_total"; const UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL: &str = "udp_tracker_server_requests_received_total"; const UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL: &str = "udp_tracker_server_requests_accepted_total"; const UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL: &str = "udp_tracker_server_responses_sent_total"; @@ -32,6 +33,12 @@ pub fn describe_metrics() -> Metrics { Some(&MetricDescription::new("Total number of UDP requests banned")), ); + metrics.metric_collection.describe_counter( + &metric_name!(UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL), + Some(Unit::Count), + Some(&MetricDescription::new("Total number of requests with connection ID errors")), + ); + metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), From d4c43bd3a5bc75704d8b8a5b4641f273968aceb4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 4 Jun 2025 18:46:23 +0100 Subject: [PATCH 1180/1297] feat: [#1375] add new metric label server_binding_address_type - Label name: `server_binding_address_type` - Label values: `plain`, `v4_mapped_v6` Usage example in Prometheous format: ``` udp_tracker_server_requests_accepted_total{request_kind="connect",server_binding_address_type="plain",server_binding_ip="0.0.0.0",server_binding_port="6969",server_binding_protocol="udp"} 1 ``` Example of IPv4-mapped-IPv6 IP: `[::ffff:192.0.2.33]` --- packages/http-tracker-core/src/event.rs | 4 ++ packages/primitives/src/service_binding.rs | 68 +++++++++++++++++++++- packages/udp-tracker-core/src/event.rs | 4 ++ packages/udp-tracker-server/src/event.rs | 4 ++ 4 files changed, 79 insertions(+), 1 deletion(-) diff --git a/packages/http-tracker-core/src/event.rs b/packages/http-tracker-core/src/event.rs index 681f4bbfe..cf969b4ff 100644 --- a/packages/http-tracker-core/src/event.rs +++ b/packages/http-tracker-core/src/event.rs @@ -86,6 +86,10 @@ impl From for LabelSet { label_name!("server_binding_ip"), LabelValue::new(&connection_context.server.service_binding.bind_address().ip().to_string()), ), + ( + label_name!("server_binding_address_type"), + LabelValue::new(&connection_context.server.service_binding.bind_address_type().to_string()), + ), ( label_name!("server_binding_port"), LabelValue::new(&connection_context.server.service_binding.bind_address().port().to_string()), diff --git a/packages/primitives/src/service_binding.rs b/packages/primitives/src/service_binding.rs index 30eb1aa9e..d5055130e 100644 --- a/packages/primitives/src/service_binding.rs +++ b/packages/primitives/src/service_binding.rs @@ -4,6 +4,8 @@ use std::net::SocketAddr; use serde::{Deserialize, Serialize}; use url::Url; +const DUAL_STACK_IP_V4_MAPPED_V6_PREFIX: &str = "::ffff:"; + /// Represents the supported network protocols. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] pub enum Protocol { @@ -23,6 +25,29 @@ impl fmt::Display for Protocol { } } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub enum AddressType { + /// Represents a plain IPv4 or IPv6 address. + Plain, + + /// Represents an IPv6 address that is a mapped IPv4 address. + /// + /// This is used for IPv6 addresses that represent an IPv4 address in a dual-stack network. + /// + /// For example: `[::ffff:192.0.2.33]` + V4MappedV6, +} + +impl fmt::Display for AddressType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let addr_type_str = match self { + Self::Plain => "plain", + Self::V4MappedV6 => "v4_mapped_v6", + }; + write!(f, "{addr_type_str}") + } +} + #[derive(thiserror::Error, Debug, Clone)] pub enum Error { #[error("The port number cannot be zero. It must be an assigned valid port.")] @@ -94,6 +119,15 @@ impl ServiceBinding { self.bind_address } + #[must_use] + pub fn bind_address_type(&self) -> AddressType { + if self.is_v4_mapped_v6() { + return AddressType::V4MappedV6; + } + + AddressType::Plain + } + /// # Panics /// /// It never panics because the URL is always valid. @@ -102,6 +136,15 @@ impl ServiceBinding { Url::parse(&format!("{}://{}", self.protocol, self.bind_address)) .expect("Service binding can always be parsed into a URL") } + + fn is_v4_mapped_v6(&self) -> bool { + self.bind_address.ip().is_ipv6() + && self + .bind_address + .ip() + .to_string() + .starts_with(DUAL_STACK_IP_V4_MAPPED_V6_PREFIX) + } } impl From for Url { @@ -126,7 +169,7 @@ mod tests { use rstest::rstest; use url::Url; - use crate::service_binding::{Error, Protocol, ServiceBinding}; + use crate::service_binding::{AddressType, Error, Protocol, ServiceBinding}; #[rstest] #[case("wildcard_ip", Protocol::UDP, SocketAddr::from_str("0.0.0.0:6969").unwrap())] @@ -156,6 +199,29 @@ mod tests { ); } + #[test] + fn should_return_the_bind_address_plain_type_for_ipv4_ips() { + let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap(); + + assert_eq!(service_binding.bind_address_type(), AddressType::Plain); + } + + #[test] + fn should_return_the_bind_address_plain_type_for_ipv6_ips() { + let service_binding = + ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("[0:0:0:0:0:0:0:1]:6969").unwrap()).unwrap(); + + assert_eq!(service_binding.bind_address_type(), AddressType::Plain); + } + + #[test] + fn should_return_the_bind_address_v4_mapped_v7_type_for_ipv4_ips_mapped_to_ipv6() { + let service_binding = + ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("[::ffff:192.0.2.33]:6969").unwrap()).unwrap(); + + assert_eq!(service_binding.bind_address_type(), AddressType::V4MappedV6); + } + #[test] fn should_return_the_corresponding_url() { let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap(); diff --git a/packages/udp-tracker-core/src/event.rs b/packages/udp-tracker-core/src/event.rs index 14a4dbfb3..e9264653e 100644 --- a/packages/udp-tracker-core/src/event.rs +++ b/packages/udp-tracker-core/src/event.rs @@ -59,6 +59,10 @@ impl From for LabelSet { label_name!("server_binding_ip"), LabelValue::new(&connection_context.server_service_binding.bind_address().ip().to_string()), ), + ( + label_name!("server_binding_address_type"), + LabelValue::new(&connection_context.server_service_binding.bind_address_type().to_string()), + ), ( label_name!("server_binding_port"), LabelValue::new(&connection_context.server_service_binding.bind_address().port().to_string()), diff --git a/packages/udp-tracker-server/src/event.rs b/packages/udp-tracker-server/src/event.rs index 152545e6a..09fc139cb 100644 --- a/packages/udp-tracker-server/src/event.rs +++ b/packages/udp-tracker-server/src/event.rs @@ -118,6 +118,10 @@ impl From for LabelSet { label_name!("server_binding_ip"), LabelValue::new(&connection_context.server_service_binding.bind_address().ip().to_string()), ), + ( + label_name!("server_binding_address_type"), + LabelValue::new(&connection_context.server_service_binding.bind_address_type().to_string()), + ), ( label_name!("server_binding_port"), LabelValue::new(&connection_context.server_service_binding.bind_address().port().to_string()), From 552697b452219100f345bc2696fb760f8f68fd15 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 5 Jun 2025 12:06:24 +0100 Subject: [PATCH 1181/1297] feat!: [#1514] rename ffield kind to type in JSON metrics "kind" has been renamed to "type" to follow Prometheus name. ```json { "type": "counter", "name": "http_tracker_core_requests_received_total", "samples": [] } ``` --- packages/metrics/src/metric_collection.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index 824397000..4038497d1 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -234,7 +234,7 @@ impl Serialize for MetricCollection { S: Serializer, { #[derive(Serialize)] - #[serde(tag = "kind", rename_all = "lowercase")] + #[serde(tag = "type", rename_all = "lowercase")] enum SerializableMetric<'a> { Counter(&'a Metric), Gauge(&'a Metric), @@ -260,7 +260,7 @@ impl<'de> Deserialize<'de> for MetricCollection { D: Deserializer<'de>, { #[derive(Deserialize)] - #[serde(tag = "kind", rename_all = "lowercase")] + #[serde(tag = "type", rename_all = "lowercase")] enum MetricPayload { Counter(Metric), Gauge(Metric), @@ -540,7 +540,7 @@ mod tests { r#" [ { - "kind":"counter", + "type":"counter", "name":"http_tracker_core_announce_requests_received_total", "samples":[ { @@ -564,7 +564,7 @@ mod tests { ] }, { - "kind":"gauge", + "type":"gauge", "name":"udp_tracker_server_performance_avg_announce_processing_time_ns", "samples":[ { From 2ee3111deebc2970784b65a73d5551d38ec6ec77 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 5 Jun 2025 12:49:09 +0100 Subject: [PATCH 1182/1297] refactor: [#1514] ensure_metric_exists method to pass the whole metric This will allow to inject also the metric unit and description. --- packages/metrics/src/metric/mod.rs | 11 ++++ packages/metrics/src/metric_collection.rs | 64 ++++++++++++++--------- 2 files changed, 51 insertions(+), 24 deletions(-) diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index 2118637b8..14704925c 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -30,6 +30,17 @@ impl Metric { } } + /// # Panics + /// + /// This function will panic if the empty sample collection cannot be created. + #[must_use] + pub fn without_samples(name: MetricName) -> Self { + Self { + name, + sample_collection: SampleCollection::new(vec![]).expect("Empty sample collection creation should not fail"), + } + } + #[must_use] pub fn name(&self) -> &MetricName { &self.name diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index 4038497d1..d10bcfd7c 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -10,7 +10,6 @@ use super::label::LabelSet; use super::metric::{Metric, MetricName}; use super::prometheus::PrometheusSerializable; use crate::metric::description::MetricDescription; -use crate::sample_collection::SampleCollection; use crate::unit::Unit; use crate::METRICS_TARGET; @@ -59,7 +58,10 @@ impl MetricCollection { pub fn describe_counter(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option<&MetricDescription>) { tracing::info!(target: METRICS_TARGET, type = "counter", name = name.to_string(), unit = ?opt_unit, description = ?opt_description); - self.counters.ensure_metric_exists(name); + + let metric = Metric::::without_samples(name.clone()); + + self.counters.ensure_metric_exists(metric); } #[must_use] @@ -120,14 +122,19 @@ impl MetricCollection { } pub fn ensure_counter_exists(&mut self, name: &MetricName) { - self.counters.ensure_metric_exists(name); + let metric = Metric::::without_samples(name.clone()); + + self.counters.ensure_metric_exists(metric); } // Gauge-specific methods pub fn describe_gauge(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option<&MetricDescription>) { tracing::info!(target: METRICS_TARGET, type = "gauge", name = name.to_string(), unit = ?opt_unit, description = ?opt_description); - self.gauges.ensure_metric_exists(name); + + let metric = Metric::::without_samples(name.clone()); + + self.gauges.ensure_metric_exists(metric); } #[must_use] @@ -205,7 +212,9 @@ impl MetricCollection { } pub fn ensure_gauge_exists(&mut self, name: &MetricName) { - self.gauges.ensure_metric_exists(name); + let metric = Metric::::without_samples(name.clone()); + + self.gauges.ensure_metric_exists(metric); } } @@ -336,18 +345,9 @@ impl MetricKindCollection { self.metrics.keys() } - /// # Panics - /// - /// It should not panic as long as empty sample collections are allowed. - pub fn ensure_metric_exists(&mut self, name: &MetricName) { - if !self.metrics.contains_key(name) { - self.metrics.insert( - name.clone(), - Metric::new( - name.clone(), - SampleCollection::new(vec![]).expect("Empty sample collection creation should not fail"), - ), - ); + pub fn ensure_metric_exists(&mut self, metric: Metric) { + if !self.metrics.contains_key(metric.name()) { + self.metrics.insert(metric.name().clone(), metric); } } } @@ -389,7 +389,9 @@ impl MetricKindCollection { /// /// Panics if the metric does not exist. pub fn increment(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { - self.ensure_metric_exists(name); + let metric = Metric::::without_samples(name.clone()); + + self.ensure_metric_exists(metric); let metric = self.metrics.get_mut(name).expect("Counter metric should exist"); @@ -404,7 +406,9 @@ impl MetricKindCollection { /// /// Panics if the metric does not exist. pub fn absolute(&mut self, name: &MetricName, label_set: &LabelSet, value: u64, time: DurationSinceUnixEpoch) { - self.ensure_metric_exists(name); + let metric = Metric::::without_samples(name.clone()); + + self.ensure_metric_exists(metric); let metric = self.metrics.get_mut(name).expect("Counter metric should exist"); @@ -429,7 +433,9 @@ impl MetricKindCollection { /// /// Panics if the metric does not exist and it could not be created. pub fn set(&mut self, name: &MetricName, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { - self.ensure_metric_exists(name); + let metric = Metric::::without_samples(name.clone()); + + self.ensure_metric_exists(metric); let metric = self.metrics.get_mut(name).expect("Gauge metric should exist"); @@ -444,7 +450,9 @@ impl MetricKindCollection { /// /// Panics if the metric does not exist and it could not be created. pub fn increment(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { - self.ensure_metric_exists(name); + let metric = Metric::::without_samples(name.clone()); + + self.ensure_metric_exists(metric); let metric = self.metrics.get_mut(name).expect("Gauge metric should exist"); @@ -459,7 +467,9 @@ impl MetricKindCollection { /// /// Panics if the metric does not exist and it could not be created. pub fn decrement(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { - self.ensure_metric_exists(name); + let metric = Metric::::without_samples(name.clone()); + + self.ensure_metric_exists(metric); let metric = self.metrics.get_mut(name).expect("Gauge metric should exist"); @@ -483,6 +493,7 @@ mod tests { use super::*; use crate::label::LabelValue; use crate::sample::Sample; + use crate::sample_collection::SampleCollection; use crate::tests::{format_prometheus_output, sort_lines}; use crate::{label_name, metric_name}; @@ -731,8 +742,11 @@ mod tests { let mut counters = MetricKindCollection::default(); let mut gauges = MetricKindCollection::default(); - counters.ensure_metric_exists(&metric_name!("test_counter")); - gauges.ensure_metric_exists(&metric_name!("test_gauge")); + let counter = Metric::::without_samples(metric_name!("test_counter")); + counters.ensure_metric_exists(counter); + + let gauge = Metric::::without_samples(metric_name!("test_gauge")); + gauges.ensure_metric_exists(gauge); let metric_collection = MetricCollection::new(counters, gauges).unwrap(); @@ -748,6 +762,7 @@ mod tests { use super::*; use crate::label::LabelValue; use crate::sample::Sample; + use crate::sample_collection::SampleCollection; #[test] fn it_should_increase_a_preexistent_counter() { @@ -845,6 +860,7 @@ mod tests { use super::*; use crate::label::LabelValue; use crate::sample::Sample; + use crate::sample_collection::SampleCollection; #[test] fn it_should_set_a_preexistent_gauge() { From 031bf65fe7b89ca85409a9c156017df100d48c2e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 5 Jun 2025 12:52:31 +0100 Subject: [PATCH 1183/1297] refactor: [#1514] remove unused code --- packages/metrics/src/metric_collection.rs | 32 ----------------------- 1 file changed, 32 deletions(-) diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index d10bcfd7c..b9e397e5b 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -121,12 +121,6 @@ impl MetricCollection { Ok(()) } - pub fn ensure_counter_exists(&mut self, name: &MetricName) { - let metric = Metric::::without_samples(name.clone()); - - self.counters.ensure_metric_exists(metric); - } - // Gauge-specific methods pub fn describe_gauge(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option<&MetricDescription>) { @@ -210,12 +204,6 @@ impl MetricCollection { Ok(()) } - - pub fn ensure_gauge_exists(&mut self, name: &MetricName) { - let metric = Metric::::without_samples(name.clone()); - - self.gauges.ensure_metric_exists(metric); - } } #[derive(thiserror::Error, Debug, Clone)] @@ -813,16 +801,6 @@ mod tests { ); } - #[test] - fn it_should_allow_making_sure_a_counter_exists_without_increasing_it() { - let mut metric_collection = - MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); - - metric_collection.ensure_counter_exists(&metric_name!("test_counter")); - - assert!(metric_collection.contains_counter(&metric_name!("test_counter"))); - } - #[test] fn it_should_allow_describing_a_counter_before_using_it() { let mut metric_collection = @@ -905,16 +883,6 @@ mod tests { ); } - #[test] - fn it_should_allow_making_sure_a_gauge_exists_without_setting_it() { - let mut metric_collection = - MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); - - metric_collection.ensure_gauge_exists(&metric_name!("test_gauge")); - - assert!(metric_collection.contains_gauge(&metric_name!("test_gauge"))); - } - #[test] fn it_should_allow_describing_a_gauge_before_using_it() { let mut metric_collection = From 458497b6460e9069d4e7fdaf27da43864cf0ed2e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 5 Jun 2025 16:04:22 +0100 Subject: [PATCH 1184/1297] feat: [#1514] add unit and description to metrics It's also shown in the JSON export format. ```json { "metrics": [ { "type": "counter", "name": "torrent_repository_torrents_downloads_total", "unit": "count", "description": "The total number of torrent downloads.", "samples": [] } } ``` todo: show them in the Prometheus export format. --- .../http-tracker-core/src/statistics/mod.rs | 2 +- packages/metrics/src/metric/mod.rs | 35 ++++++-- packages/metrics/src/metric_collection.rs | 89 +++++++++++++------ packages/metrics/src/unit.rs | 6 +- .../src/statistics/mod.rs | 22 ++--- packages/tracker-core/src/statistics/mod.rs | 2 +- .../udp-tracker-core/src/statistics/mod.rs | 2 +- .../udp-tracker-server/src/statistics/mod.rs | 16 ++-- 8 files changed, 116 insertions(+), 58 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs index f949babbd..7181632aa 100644 --- a/packages/http-tracker-core/src/statistics/mod.rs +++ b/packages/http-tracker-core/src/statistics/mod.rs @@ -17,7 +17,7 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_counter( &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("Total number of HTTP requests received")), + Some(MetricDescription::new("Total number of HTTP requests received")), ); metrics diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index 14704925c..eff2c7a5f 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -9,7 +9,9 @@ use super::label::LabelSet; use super::prometheus::PrometheusSerializable; use super::sample_collection::SampleCollection; use crate::gauge::Gauge; +use crate::metric::description::MetricDescription; use crate::sample::Measurement; +use crate::unit::Unit; pub type MetricName = name::MetricName; @@ -17,15 +19,28 @@ pub type MetricName = name::MetricName; pub struct Metric { name: MetricName, + #[serde(rename = "unit")] + opt_unit: Option, + + #[serde(rename = "description")] + opt_description: Option, + #[serde(rename = "samples")] sample_collection: SampleCollection, } impl Metric { #[must_use] - pub fn new(name: MetricName, samples: SampleCollection) -> Self { + pub fn new( + name: MetricName, + opt_unit: Option, + opt_description: Option, + samples: SampleCollection, + ) -> Self { Self { name, + opt_unit, + opt_description, sample_collection: samples, } } @@ -34,9 +49,11 @@ impl Metric { /// /// This function will panic if the empty sample collection cannot be created. #[must_use] - pub fn without_samples(name: MetricName) -> Self { + pub fn new_empty_with_name(name: MetricName) -> Self { Self { name, + opt_unit: None, + opt_description: None, sample_collection: SampleCollection::new(vec![]).expect("Empty sample collection creation should not fail"), } } @@ -119,7 +136,7 @@ mod tests { let samples = SampleCollection::::default(); - let metric = Metric::::new(name.clone(), samples); + let metric = Metric::::new(name.clone(), None, None, samples); assert!(metric.is_empty()); } @@ -133,7 +150,7 @@ mod tests { let samples = SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set.clone())]).unwrap(); - Metric::::new(name.clone(), samples) + Metric::::new(name.clone(), None, None, samples) } #[test] @@ -147,7 +164,7 @@ mod tests { let samples = SampleCollection::::default(); - let metric = Metric::::new(name.clone(), samples); + let metric = Metric::::new(name.clone(), None, None, samples); assert_eq!(metric.number_of_samples(), 0); } @@ -166,7 +183,7 @@ mod tests { let samples = SampleCollection::::default(); - let _metric = Metric::::new(name, samples); + let _metric = Metric::::new(name, None, None, samples); } #[test] @@ -179,7 +196,7 @@ mod tests { let samples = SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set.clone())]).unwrap(); - let metric = Metric::::new(name.clone(), samples); + let metric = Metric::::new(name.clone(), None, None, samples); assert_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1); } @@ -200,7 +217,7 @@ mod tests { let samples = SampleCollection::::default(); - let _metric = Metric::::new(name, samples); + let _metric = Metric::::new(name, None, None, samples); } #[test] @@ -213,7 +230,7 @@ mod tests { let samples = SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set.clone())]).unwrap(); - let metric = Metric::::new(name.clone(), samples); + let metric = Metric::::new(name.clone(), None, None, samples); assert_relative_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1.0); } diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index b9e397e5b..59c0448af 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -10,6 +10,7 @@ use super::label::LabelSet; use super::metric::{Metric, MetricName}; use super::prometheus::PrometheusSerializable; use crate::metric::description::MetricDescription; +use crate::sample_collection::SampleCollection; use crate::unit::Unit; use crate::METRICS_TARGET; @@ -56,12 +57,12 @@ impl MetricCollection { // Counter-specific methods - pub fn describe_counter(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option<&MetricDescription>) { + pub fn describe_counter(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option) { tracing::info!(target: METRICS_TARGET, type = "counter", name = name.to_string(), unit = ?opt_unit, description = ?opt_description); - let metric = Metric::::without_samples(name.clone()); + let metric = Metric::::new(name.clone(), opt_unit, opt_description, SampleCollection::default()); - self.counters.ensure_metric_exists(metric); + self.counters.insert(metric); } #[must_use] @@ -123,12 +124,12 @@ impl MetricCollection { // Gauge-specific methods - pub fn describe_gauge(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option<&MetricDescription>) { + pub fn describe_gauge(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option) { tracing::info!(target: METRICS_TARGET, type = "gauge", name = name.to_string(), unit = ?opt_unit, description = ?opt_description); - let metric = Metric::::without_samples(name.clone()); + let metric = Metric::::new(name.clone(), opt_unit, opt_description, SampleCollection::default()); - self.gauges.ensure_metric_exists(metric); + self.gauges.insert(metric); } #[must_use] @@ -333,11 +334,15 @@ impl MetricKindCollection { self.metrics.keys() } - pub fn ensure_metric_exists(&mut self, metric: Metric) { + pub fn insert_if_absent(&mut self, metric: Metric) { if !self.metrics.contains_key(metric.name()) { - self.metrics.insert(metric.name().clone(), metric); + self.insert(metric); } } + + pub fn insert(&mut self, metric: Metric) { + self.metrics.insert(metric.name().clone(), metric); + } } impl MetricKindCollection { @@ -377,9 +382,9 @@ impl MetricKindCollection { /// /// Panics if the metric does not exist. pub fn increment(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { - let metric = Metric::::without_samples(name.clone()); + let metric = Metric::::new_empty_with_name(name.clone()); - self.ensure_metric_exists(metric); + self.insert_if_absent(metric); let metric = self.metrics.get_mut(name).expect("Counter metric should exist"); @@ -394,9 +399,9 @@ impl MetricKindCollection { /// /// Panics if the metric does not exist. pub fn absolute(&mut self, name: &MetricName, label_set: &LabelSet, value: u64, time: DurationSinceUnixEpoch) { - let metric = Metric::::without_samples(name.clone()); + let metric = Metric::::new_empty_with_name(name.clone()); - self.ensure_metric_exists(metric); + self.insert_if_absent(metric); let metric = self.metrics.get_mut(name).expect("Counter metric should exist"); @@ -421,9 +426,9 @@ impl MetricKindCollection { /// /// Panics if the metric does not exist and it could not be created. pub fn set(&mut self, name: &MetricName, label_set: &LabelSet, value: f64, time: DurationSinceUnixEpoch) { - let metric = Metric::::without_samples(name.clone()); + let metric = Metric::::new_empty_with_name(name.clone()); - self.ensure_metric_exists(metric); + self.insert_if_absent(metric); let metric = self.metrics.get_mut(name).expect("Gauge metric should exist"); @@ -438,9 +443,9 @@ impl MetricKindCollection { /// /// Panics if the metric does not exist and it could not be created. pub fn increment(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { - let metric = Metric::::without_samples(name.clone()); + let metric = Metric::::new_empty_with_name(name.clone()); - self.ensure_metric_exists(metric); + self.insert_if_absent(metric); let metric = self.metrics.get_mut(name).expect("Gauge metric should exist"); @@ -455,9 +460,9 @@ impl MetricKindCollection { /// /// Panics if the metric does not exist and it could not be created. pub fn decrement(&mut self, name: &MetricName, label_set: &LabelSet, time: DurationSinceUnixEpoch) { - let metric = Metric::::without_samples(name.clone()); + let metric = Metric::::new_empty_with_name(name.clone()); - self.ensure_metric_exists(metric); + self.insert_if_absent(metric); let metric = self.metrics.get_mut(name).expect("Gauge metric should exist"); @@ -523,11 +528,15 @@ mod tests { MetricCollection::new( MetricKindCollection::new(vec![Metric::new( metric_name!("http_tracker_core_announce_requests_received_total"), + None, + None, SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set_1.clone())]).unwrap(), )]) .unwrap(), MetricKindCollection::new(vec![Metric::new( metric_name!("udp_tracker_server_performance_avg_announce_processing_time_ns"), + None, + None, SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set_1.clone())]).unwrap(), )]) .unwrap(), @@ -541,6 +550,8 @@ mod tests { { "type":"counter", "name":"http_tracker_core_announce_requests_received_total", + "unit": null, + "description": null, "samples":[ { "value":1, @@ -565,6 +576,8 @@ mod tests { { "type":"gauge", "name":"udp_tracker_server_performance_avg_announce_processing_time_ns", + "unit": null, + "description": null, "samples":[ { "value":1.0, @@ -603,10 +616,20 @@ mod tests { #[test] fn it_should_not_allow_duplicate_names_across_types() { - let counters = - MetricKindCollection::new(vec![Metric::new(metric_name!("test_metric"), SampleCollection::default())]).unwrap(); - let gauges = - MetricKindCollection::new(vec![Metric::new(metric_name!("test_metric"), SampleCollection::default())]).unwrap(); + let counters = MetricKindCollection::new(vec![Metric::new( + metric_name!("test_metric"), + None, + None, + SampleCollection::default(), + )]) + .unwrap(); + let gauges = MetricKindCollection::new(vec![Metric::new( + metric_name!("test_metric"), + None, + None, + SampleCollection::default(), + )]) + .unwrap(); assert!(MetricCollection::new(counters, gauges).is_err()); } @@ -699,6 +722,8 @@ mod tests { let metric_collection = MetricCollection::new( MetricKindCollection::new(vec![Metric::new( metric_name!("http_tracker_core_announce_requests_received_total"), + None, + None, SampleCollection::new(vec![ Sample::new(Counter::new(1), time, label_set_1.clone()), Sample::new(Counter::new(2), time, label_set_2.clone()), @@ -730,11 +755,11 @@ mod tests { let mut counters = MetricKindCollection::default(); let mut gauges = MetricKindCollection::default(); - let counter = Metric::::without_samples(metric_name!("test_counter")); - counters.ensure_metric_exists(counter); + let counter = Metric::::new_empty_with_name(metric_name!("test_counter")); + counters.insert_if_absent(counter); - let gauge = Metric::::without_samples(metric_name!("test_gauge")); - gauges.ensure_metric_exists(gauge); + let gauge = Metric::::new_empty_with_name(metric_name!("test_gauge")); + gauges.insert_if_absent(gauge); let metric_collection = MetricCollection::new(counters, gauges).unwrap(); @@ -760,6 +785,8 @@ mod tests { let mut metric_collection = MetricCollection::new( MetricKindCollection::new(vec![Metric::new( metric_name!("test_counter"), + None, + None, SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(), )]) .unwrap(), @@ -819,10 +846,14 @@ mod tests { let result = MetricKindCollection::new(vec![ Metric::new( metric_name!("test_counter"), + None, + None, SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(), ), Metric::new( metric_name!("test_counter"), + None, + None, SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(), ), ]); @@ -849,6 +880,8 @@ mod tests { MetricKindCollection::default(), MetricKindCollection::new(vec![Metric::new( metric_name!("test_gauge"), + None, + None, SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(), )]) .unwrap(), @@ -901,10 +934,14 @@ mod tests { let result = MetricKindCollection::new(vec![ Metric::new( metric_name!("test_gauge"), + None, + None, SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(), ), Metric::new( metric_name!("test_gauge"), + None, + None, SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(), ), ]); diff --git a/packages/metrics/src/unit.rs b/packages/metrics/src/unit.rs index f7a528bed..43b42bf79 100644 --- a/packages/metrics/src/unit.rs +++ b/packages/metrics/src/unit.rs @@ -4,7 +4,11 @@ //! The `Unit` enum is used to specify the unit of measurement for metrics. //! //! They were copied from the `metrics` crate, to allow future compatibility. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] pub enum Unit { Count, Percent, diff --git a/packages/swarm-coordination-registry/src/statistics/mod.rs b/packages/swarm-coordination-registry/src/statistics/mod.rs index cfc252e34..6505a2db2 100644 --- a/packages/swarm-coordination-registry/src/statistics/mod.rs +++ b/packages/swarm-coordination-registry/src/statistics/mod.rs @@ -36,31 +36,31 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_counter( &metric_name!(TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("The total number of torrents added.")), + Some(MetricDescription::new("The total number of torrents added.")), ); metrics.metric_collection.describe_counter( &metric_name!(TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("The total number of torrents removed.")), + Some(MetricDescription::new("The total number of torrents removed.")), ); metrics.metric_collection.describe_gauge( &metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("The total number of torrents.")), + Some(MetricDescription::new("The total number of torrents.")), ); metrics.metric_collection.describe_counter( &metric_name!(TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("The total number of torrent downloads.")), + Some(MetricDescription::new("The total number of torrent downloads.")), ); metrics.metric_collection.describe_gauge( &metric_name!(TORRENT_REPOSITORY_TORRENTS_INACTIVE_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("The total number of inactive torrents.")), + Some(MetricDescription::new("The total number of inactive torrents.")), ); // Peers metrics @@ -68,25 +68,25 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_counter( &metric_name!(TORRENT_REPOSITORY_PEERS_ADDED_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("The total number of peers added.")), + Some(MetricDescription::new("The total number of peers added.")), ); metrics.metric_collection.describe_counter( &metric_name!(TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("The total number of peers removed.")), + Some(MetricDescription::new("The total number of peers removed.")), ); metrics.metric_collection.describe_counter( &metric_name!(TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("The total number of peers updated.")), + Some(MetricDescription::new("The total number of peers updated.")), ); metrics.metric_collection.describe_gauge( &metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new( + Some(MetricDescription::new( "The total number of peer connections (one connection per torrent).", )), ); @@ -94,13 +94,13 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_gauge( &metric_name!(TORRENT_REPOSITORY_UNIQUE_PEERS_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("The total number of unique peers.")), + Some(MetricDescription::new("The total number of unique peers.")), ); metrics.metric_collection.describe_gauge( &metric_name!(TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("The total number of inactive peers.")), + Some(MetricDescription::new("The total number of inactive peers.")), ); metrics diff --git a/packages/tracker-core/src/statistics/mod.rs b/packages/tracker-core/src/statistics/mod.rs index ff8187379..fdb8e8fd4 100644 --- a/packages/tracker-core/src/statistics/mod.rs +++ b/packages/tracker-core/src/statistics/mod.rs @@ -21,7 +21,7 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_counter( &metric_name!(TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("The total number of torrent downloads (persisted).")), + Some(MetricDescription::new("The total number of torrent downloads (persisted).")), ); metrics diff --git a/packages/udp-tracker-core/src/statistics/mod.rs b/packages/udp-tracker-core/src/statistics/mod.rs index 9eb85d7f1..fec76069e 100644 --- a/packages/udp-tracker-core/src/statistics/mod.rs +++ b/packages/udp-tracker-core/src/statistics/mod.rs @@ -17,7 +17,7 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("Total number of UDP requests received")), + Some(MetricDescription::new("Total number of UDP requests received")), ); metrics diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index 5c30a9abc..a7da2dc63 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -24,49 +24,49 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("Total number of UDP requests aborted")), + Some(MetricDescription::new("Total number of UDP requests aborted")), ); metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("Total number of UDP requests banned")), + Some(MetricDescription::new("Total number of UDP requests banned")), ); metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("Total number of requests with connection ID errors")), + Some(MetricDescription::new("Total number of requests with connection ID errors")), ); metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("Total number of UDP requests received")), + Some(MetricDescription::new("Total number of UDP requests received")), ); metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("Total number of UDP requests accepted")), + Some(MetricDescription::new("Total number of UDP requests accepted")), ); metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("Total number of UDP responses sent")), + Some(MetricDescription::new("Total number of UDP responses sent")), ); metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), Some(Unit::Count), - Some(&MetricDescription::new("Total number of errors processing UDP requests")), + Some(MetricDescription::new("Total number of errors processing UDP requests")), ); metrics.metric_collection.describe_gauge( &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), Some(Unit::Nanoseconds), - Some(&MetricDescription::new( + Some(MetricDescription::new( "Average time to process a UDP connect request in nanoseconds", )), ); From 842739ff95d33f1b47afc9b71459b3f8671ed175 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 6 Jun 2025 11:18:02 +0100 Subject: [PATCH 1185/1297] feat: [#1514] add HELP and TYPE to prometehous metric export --- packages/metrics/src/metric/mod.rs | 44 +++++++++++++++++++++-- packages/metrics/src/metric_collection.rs | 4 +++ 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index eff2c7a5f..08f7dd485 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -103,18 +103,56 @@ impl Metric { } } -impl PrometheusSerializable for Metric { +impl PrometheusSerializable for Metric { fn to_prometheus(&self) -> String { let samples: Vec = self .sample_collection .iter() .map(|(label_set, sample)| { - format!( + let help = if let Some(description) = &self.opt_description { + format!("# HELP {description}\n") + } else { + String::new() + }; + + let kind = format!("# TYPE {} counter\n", self.name.to_prometheus()); + + let metric = format!( "{}{} {}", self.name.to_prometheus(), label_set.to_prometheus(), sample.value().to_prometheus() - ) + ); + + format!("{help}{kind}{metric}") + }) + .collect(); + samples.join("\n") + } +} + +impl PrometheusSerializable for Metric { + fn to_prometheus(&self) -> String { + let samples: Vec = self + .sample_collection + .iter() + .map(|(label_set, sample)| { + let help = if let Some(description) = &self.opt_description { + format!("# HELP {description}\n") + } else { + String::new() + }; + + let kind = format!("# TYPE {} gauge\n", self.name.to_prometheus()); + + let metric = format!( + "{}{} {}", + self.name.to_prometheus(), + label_set.to_prometheus(), + sample.value().to_prometheus() + ); + + format!("{help}{kind}{metric}") }) .collect(); samples.join("\n") diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index 59c0448af..23b7609f6 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -607,7 +607,9 @@ mod tests { fn prometheus() -> String { format_prometheus_output( r#" + # TYPE http_tracker_core_announce_requests_received_total counter http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 + # TYPE udp_tracker_server_performance_avg_announce_processing_time_ns gauge udp_tracker_server_performance_avg_announce_processing_time_ns{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 "#, ) @@ -739,7 +741,9 @@ mod tests { let expected_prometheus_output = format_prometheus_output( r#" + # TYPE http_tracker_core_announce_requests_received_total counter http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7171",server_binding_protocol="http"} 2 + # TYPE http_tracker_core_announce_requests_received_total counter http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 "#, ); From ed1322b7a8be7cf039d01aaab112eefe01e55ba0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 6 Jun 2025 11:25:48 +0100 Subject: [PATCH 1186/1297] refactor: [#1514] reorganize SampleCollection tests --- packages/metrics/src/sample_collection.rs | 90 +++++++++++++---------- 1 file changed, 53 insertions(+), 37 deletions(-) diff --git a/packages/metrics/src/sample_collection.rs b/packages/metrics/src/sample_collection.rs index e815f26ec..a87aacb63 100644 --- a/packages/metrics/src/sample_collection.rs +++ b/packages/metrics/src/sample_collection.rs @@ -168,10 +168,8 @@ mod tests { use crate::counter::Counter; use crate::label::LabelSet; - use crate::prometheus::PrometheusSerializable; use crate::sample::Sample; use crate::sample_collection::SampleCollection; - use crate::tests::format_prometheus_output; fn sample_update_time() -> DurationSinceUnixEpoch { DurationSinceUnixEpoch::from_secs(1_743_552_000) @@ -242,56 +240,74 @@ mod tests { assert!(!collection.is_empty()); } - #[test] - fn it_should_be_serializable_and_deserializable_for_json_format() { - let sample = Sample::new(Counter::default(), sample_update_time(), LabelSet::default()); - let collection = SampleCollection::new(vec![sample]).unwrap(); + mod json_serialization { + use crate::counter::Counter; + use crate::label::LabelSet; + use crate::sample::Sample; + use crate::sample_collection::tests::sample_update_time; + use crate::sample_collection::SampleCollection; - let serialized = serde_json::to_string(&collection).unwrap(); - let deserialized: SampleCollection = serde_json::from_str(&serialized).unwrap(); + #[test] + fn it_should_be_serializable_and_deserializable_for_json_format() { + let sample = Sample::new(Counter::default(), sample_update_time(), LabelSet::default()); + let collection = SampleCollection::new(vec![sample]).unwrap(); - assert_eq!(deserialized, collection); - } + let serialized = serde_json::to_string(&collection).unwrap(); + let deserialized: SampleCollection = serde_json::from_str(&serialized).unwrap(); - #[test] - fn it_should_fail_deserializing_from_json_with_duplicate_label_sets() { - let samples = vec![ - Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), - Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), - ]; + assert_eq!(deserialized, collection); + } - let serialized = serde_json::to_string(&samples).unwrap(); + #[test] + fn it_should_fail_deserializing_from_json_with_duplicate_label_sets() { + let samples = vec![ + Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), + Sample::new(Counter::default(), sample_update_time(), LabelSet::default()), + ]; - let result: Result, _> = serde_json::from_str(&serialized); + let serialized = serde_json::to_string(&samples).unwrap(); - assert!(result.is_err()); + let result: Result, _> = serde_json::from_str(&serialized); + + assert!(result.is_err()); + } } - #[test] - fn it_should_be_exportable_to_prometheus_format_when_empty() { - let sample = Sample::new(Counter::default(), sample_update_time(), LabelSet::default()); - let collection = SampleCollection::new(vec![sample]).unwrap(); + mod prometheus_serialization { + use crate::counter::Counter; + use crate::label::LabelSet; + use crate::prometheus::PrometheusSerializable; + use crate::sample::Sample; + use crate::sample_collection::tests::sample_update_time; + use crate::sample_collection::SampleCollection; + use crate::tests::format_prometheus_output; - let prometheus_output = collection.to_prometheus(); + #[test] + fn it_should_be_exportable_to_prometheus_format_when_empty() { + let sample = Sample::new(Counter::default(), sample_update_time(), LabelSet::default()); + let collection = SampleCollection::new(vec![sample]).unwrap(); - assert!(!prometheus_output.is_empty()); - } + let prometheus_output = collection.to_prometheus(); - #[test] - fn it_should_be_exportable_to_prometheus_format() { - let sample = Sample::new( - Counter::new(1), - sample_update_time(), - LabelSet::from(vec![("labe_name_1", "label value value 1")]), - ); + assert!(!prometheus_output.is_empty()); + } - let collection = SampleCollection::new(vec![sample]).unwrap(); + #[test] + fn it_should_be_exportable_to_prometheus_format() { + let sample = Sample::new( + Counter::new(1), + sample_update_time(), + LabelSet::from(vec![("labe_name_1", "label value value 1")]), + ); - let prometheus_output = collection.to_prometheus(); + let collection = SampleCollection::new(vec![sample]).unwrap(); - let expected_prometheus_output = format_prometheus_output("{labe_name_1=\"label value value 1\"} 1"); + let prometheus_output = collection.to_prometheus(); - assert_eq!(prometheus_output, expected_prometheus_output); + let expected_prometheus_output = format_prometheus_output("{labe_name_1=\"label value value 1\"} 1"); + + assert_eq!(prometheus_output, expected_prometheus_output); + } } #[cfg(test)] From a89406daad7c308639635fa234d39b27ec41085b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 6 Jun 2025 12:49:34 +0100 Subject: [PATCH 1187/1297] refactor: [#1514] remove duplicate code in Metric type --- packages/metrics/src/metric/mod.rs | 117 ++++++++++++++++++++--------- 1 file changed, 83 insertions(+), 34 deletions(-) diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index 08f7dd485..a97621da8 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -103,28 +103,92 @@ impl Metric { } } +/// `PrometheusMetricSample` is a wrapper around types that provides methods to +/// convert the metric and its measurement into a Prometheus-compatible format. +/// +/// In Prometheus, a metric is a time series that consists of a name, a set of +/// labels, and a value. The sample value needs data from the `Metric` and +/// `Measurement` structs, as well as the `LabelSet` that defines the labels for +/// the metric. +struct PrometheusMetricSample<'a, T> { + metric: &'a Metric, + measurement: &'a Measurement, + label_set: &'a LabelSet, +} + +enum PrometheusType { + Counter, + Gauge, +} + +impl PrometheusSerializable for PrometheusType { + fn to_prometheus(&self) -> String { + match self { + PrometheusType::Counter => "counter".to_string(), + PrometheusType::Gauge => "gauge".to_string(), + } + } +} + +impl PrometheusMetricSample<'_, T> { + fn to_prometheus(&self, prometheus_type: &PrometheusType) -> String { + format!( + "{}{}{}", + self.help_line(), + self.type_line(prometheus_type), + self.metric_line() + ) + } + + fn help_line(&self) -> String { + if let Some(description) = &self.metric.opt_description { + format!("# HELP {description}\n") + } else { + String::new() + } + } + + fn type_line(&self, kind: &PrometheusType) -> String { + format!("# TYPE {} {}\n", self.metric.name().to_prometheus(), kind.to_prometheus()) + } + + fn metric_line(&self) -> String { + format!( + "{}{} {}", + self.metric.name.to_prometheus(), + self.label_set.to_prometheus(), + self.measurement.value().to_prometheus() + ) + } +} + +impl<'a> PrometheusMetricSample<'a, Counter> { + pub fn new(metric: &'a Metric, measurement: &'a Measurement, label_set: &'a LabelSet) -> Self { + Self { + metric, + measurement, + label_set, + } + } +} + +impl<'a> PrometheusMetricSample<'a, Gauge> { + pub fn new(metric: &'a Metric, measurement: &'a Measurement, label_set: &'a LabelSet) -> Self { + Self { + metric, + measurement, + label_set, + } + } +} + impl PrometheusSerializable for Metric { fn to_prometheus(&self) -> String { let samples: Vec = self .sample_collection .iter() - .map(|(label_set, sample)| { - let help = if let Some(description) = &self.opt_description { - format!("# HELP {description}\n") - } else { - String::new() - }; - - let kind = format!("# TYPE {} counter\n", self.name.to_prometheus()); - - let metric = format!( - "{}{} {}", - self.name.to_prometheus(), - label_set.to_prometheus(), - sample.value().to_prometheus() - ); - - format!("{help}{kind}{metric}") + .map(|(label_set, measurement)| { + PrometheusMetricSample::::new(self, measurement, label_set).to_prometheus(&PrometheusType::Counter) }) .collect(); samples.join("\n") @@ -136,23 +200,8 @@ impl PrometheusSerializable for Metric { let samples: Vec = self .sample_collection .iter() - .map(|(label_set, sample)| { - let help = if let Some(description) = &self.opt_description { - format!("# HELP {description}\n") - } else { - String::new() - }; - - let kind = format!("# TYPE {} gauge\n", self.name.to_prometheus()); - - let metric = format!( - "{}{} {}", - self.name.to_prometheus(), - label_set.to_prometheus(), - sample.value().to_prometheus() - ); - - format!("{help}{kind}{metric}") + .map(|(label_set, measurement)| { + PrometheusMetricSample::::new(self, measurement, label_set).to_prometheus(&PrometheusType::Gauge) }) .collect(); samples.join("\n") From 748e6a50e6f18324d2587eddb3fc43f626fb3876 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 6 Jun 2025 15:41:07 +0100 Subject: [PATCH 1188/1297] test: [#1514] add tests to metrics package --- packages/metrics/src/label/set.rs | 200 +++++++++++++++++++++------- packages/metrics/src/label/value.rs | 59 ++++++++ 2 files changed, 211 insertions(+), 48 deletions(-) diff --git a/packages/metrics/src/label/set.rs b/packages/metrics/src/label/set.rs index 2b6334fc7..1c2c3e27e 100644 --- a/packages/metrics/src/label/set.rs +++ b/packages/metrics/src/label/set.rs @@ -175,6 +175,7 @@ impl PrometheusSerializable for LabelSet { mod tests { use std::collections::BTreeMap; + use std::hash::{DefaultHasher, Hash}; use pretty_assertions::assert_eq; @@ -195,54 +196,6 @@ mod tests { ] } - #[test] - fn it_should_allow_instantiation_from_an_array_of_label_pairs() { - let label_set: LabelSet = sample_array_of_label_pairs().into(); - - assert_eq!( - label_set, - LabelSet { - items: BTreeMap::from(sample_array_of_label_pairs()) - } - ); - } - - #[test] - fn it_should_allow_instantiation_from_a_vec_of_label_pairs() { - let label_set: LabelSet = sample_vec_of_label_pairs().into(); - - assert_eq!( - label_set, - LabelSet { - items: BTreeMap::from(sample_array_of_label_pairs()) - } - ); - } - - #[test] - fn it_should_allow_instantiation_from_a_b_tree_map() { - let label_set: LabelSet = BTreeMap::from(sample_array_of_label_pairs()).into(); - - assert_eq!( - label_set, - LabelSet { - items: BTreeMap::from(sample_array_of_label_pairs()) - } - ); - } - - #[test] - fn it_should_allow_instantiation_from_a_label_pair() { - let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); - - assert_eq!( - label_set, - LabelSet { - items: BTreeMap::from([(label_name!("label_name"), LabelValue::new("value"))]) - } - ); - } - #[test] fn it_should_allow_inserting_a_new_label_pair() { let mut label_set = LabelSet::default(); @@ -338,4 +291,155 @@ mod tests { assert_eq!(label_set.to_string(), r#"{label_name="label value"}"#); } + + #[test] + fn it_should_allow_instantiation_from_an_array_of_label_pairs() { + let label_set: LabelSet = sample_array_of_label_pairs().into(); + + assert_eq!( + label_set, + LabelSet { + items: BTreeMap::from(sample_array_of_label_pairs()) + } + ); + } + + #[test] + fn it_should_allow_instantiation_from_a_vec_of_label_pairs() { + let label_set: LabelSet = sample_vec_of_label_pairs().into(); + + assert_eq!( + label_set, + LabelSet { + items: BTreeMap::from(sample_array_of_label_pairs()) + } + ); + } + + #[test] + fn it_should_allow_instantiation_from_a_b_tree_map() { + let label_set: LabelSet = BTreeMap::from(sample_array_of_label_pairs()).into(); + + assert_eq!( + label_set, + LabelSet { + items: BTreeMap::from(sample_array_of_label_pairs()) + } + ); + } + + #[test] + fn it_should_allow_instantiation_from_a_label_pair() { + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + assert_eq!( + label_set, + LabelSet { + items: BTreeMap::from([(label_name!("label_name"), LabelValue::new("value"))]) + } + ); + } + + #[test] + fn it_should_allow_instantiation_from_vec_of_str_tuples() { + let label_set: LabelSet = vec![("foo", "bar"), ("baz", "qux")].into(); + + let mut expected = BTreeMap::new(); + expected.insert(LabelName::new("foo"), LabelValue::new("bar")); + expected.insert(LabelName::new("baz"), LabelValue::new("qux")); + + assert_eq!(label_set, LabelSet { items: expected }); + } + + #[test] + fn it_should_allow_instantiation_from_vec_of_string_tuples() { + let label_set: LabelSet = vec![("foo".to_string(), "bar".to_string()), ("baz".to_string(), "qux".to_string())].into(); + + let mut expected = BTreeMap::new(); + expected.insert(LabelName::new("foo"), LabelValue::new("bar")); + expected.insert(LabelName::new("baz"), LabelValue::new("qux")); + + assert_eq!(label_set, LabelSet { items: expected }); + } + + #[test] + fn it_should_allow_instantiation_from_vec_of_serialized_label() { + use super::SerializedLabel; + let label_set: LabelSet = vec![ + SerializedLabel { + name: LabelName::new("foo"), + value: LabelValue::new("bar"), + }, + SerializedLabel { + name: LabelName::new("baz"), + value: LabelValue::new("qux"), + }, + ] + .into(); + + let mut expected = BTreeMap::new(); + expected.insert(LabelName::new("foo"), LabelValue::new("bar")); + expected.insert(LabelName::new("baz"), LabelValue::new("qux")); + + assert_eq!(label_set, LabelSet { items: expected }); + } + + #[test] + fn it_should_allow_instantiation_from_array_of_string_tuples() { + let arr: [(String, String); 2] = [("foo".to_string(), "bar".to_string()), ("baz".to_string(), "qux".to_string())]; + let label_set: LabelSet = arr.into(); + + let mut expected = BTreeMap::new(); + + expected.insert(LabelName::new("foo"), LabelValue::new("bar")); + expected.insert(LabelName::new("baz"), LabelValue::new("qux")); + + assert_eq!(label_set, LabelSet { items: expected }); + } + + #[test] + fn it_should_allow_instantiation_from_array_of_str_tuples() { + let arr: [(&str, &str); 2] = [("foo", "bar"), ("baz", "qux")]; + let label_set: LabelSet = arr.into(); + + let mut expected = BTreeMap::new(); + + expected.insert(LabelName::new("foo"), LabelValue::new("bar")); + expected.insert(LabelName::new("baz"), LabelValue::new("qux")); + + assert_eq!(label_set, LabelSet { items: expected }); + } + + #[test] + fn it_should_be_comparable() { + let a: LabelSet = (label_name!("x"), LabelValue::new("1")).into(); + let b: LabelSet = (label_name!("x"), LabelValue::new("1")).into(); + let c: LabelSet = (label_name!("y"), LabelValue::new("2")).into(); + + assert_eq!(a, b); + assert_ne!(a, c); + } + + #[test] + fn it_should_be_allow_ordering() { + let a: LabelSet = (label_name!("x"), LabelValue::new("1")).into(); + let b: LabelSet = (label_name!("y"), LabelValue::new("2")).into(); + + assert!(a < b); + } + + #[test] + fn it_should_be_hashable() { + let a: LabelSet = (label_name!("x"), LabelValue::new("1")).into(); + + let mut hasher = DefaultHasher::new(); + + a.hash(&mut hasher); + } + + #[test] + fn it_should_implement_clone() { + let a: LabelSet = (label_name!("x"), LabelValue::new("1")).into(); + let _unused = a.clone(); + } } diff --git a/packages/metrics/src/label/value.rs b/packages/metrics/src/label/value.rs index ffdbce333..4f25844a8 100644 --- a/packages/metrics/src/label/value.rs +++ b/packages/metrics/src/label/value.rs @@ -33,6 +33,9 @@ impl From for LabelValue { #[cfg(test)] mod tests { + use std::collections::hash_map::DefaultHasher; + use std::hash::Hash; + use crate::label::value::LabelValue; use crate::prometheus::PrometheusSerializable; @@ -41,4 +44,60 @@ mod tests { let label_value = LabelValue::new("value"); assert_eq!(label_value.to_prometheus(), "value"); } + + #[test] + fn it_could_be_initialized_from_str() { + let lv = LabelValue::new("abc"); + assert_eq!(lv.0, "abc"); + } + + #[test] + fn it_should_allow_to_create_an_ignored_label_value() { + let lv = LabelValue::ignore(); + assert_eq!(lv.0, ""); + } + + #[test] + fn it_should_be_converted_from_string() { + let s = String::from("foo"); + let lv: LabelValue = s.clone().into(); + assert_eq!(lv.0, s); + } + + #[test] + fn it_should_be_comparable() { + let a = LabelValue::new("x"); + let b = LabelValue::new("x"); + let c = LabelValue::new("y"); + + assert_eq!(a, b); + assert_ne!(a, c); + } + + #[test] + fn it_should_be_allow_ordering() { + let a = LabelValue::new("x"); + let b = LabelValue::new("y"); + + assert!(a < b); + } + + #[test] + fn it_should_be_hashable() { + let a = LabelValue::new("x"); + let mut hasher = DefaultHasher::new(); + a.hash(&mut hasher); + } + + #[test] + fn it_should_implement_clone() { + let a = LabelValue::new("x"); + let _unused = a.clone(); + } + + #[test] + fn it_should_implement_display() { + let a = LabelValue::new("x"); + assert_eq!(format!("{a}"), "x"); + } } From 642d7742ea44dfd65db0ce840dc33053c0ce53dd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 6 Jun 2025 16:15:11 +0100 Subject: [PATCH 1189/1297] fix: [#1514] HELP line in Prometheus export must contain metric name Format for each metric sample: {label_set} Exmaple: ``` udp_tracker_server_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="6868",server_binding_protocol="udp"} 36661 ``` See https://prometheus.io/docs/instrumenting/exposition_formats/#comments-help-text-and-type-information --- packages/metrics/src/metric/description.rs | 13 +++++++++++++ packages/metrics/src/metric/mod.rs | 12 +++++++++++- packages/metrics/src/metric_collection.rs | 10 ++++++---- 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/packages/metrics/src/metric/description.rs b/packages/metrics/src/metric/description.rs index 8a50dee90..6a0ca3432 100644 --- a/packages/metrics/src/metric/description.rs +++ b/packages/metrics/src/metric/description.rs @@ -1,6 +1,8 @@ use derive_more::Display; use serde::{Deserialize, Serialize}; +use crate::prometheus::PrometheusSerializable; + #[derive(Debug, Display, Clone, Eq, PartialEq, Default, Deserialize, Serialize, Hash, Ord, PartialOrd)] pub struct MetricDescription(String); @@ -11,6 +13,11 @@ impl MetricDescription { } } +impl PrometheusSerializable for MetricDescription { + fn to_prometheus(&self) -> String { + self.0.clone() + } +} #[cfg(test)] mod tests { use super::*; @@ -21,6 +28,12 @@ mod tests { assert_eq!(metric.0, "Metric description"); } + #[test] + fn it_serializes_to_prometheus() { + let label_value = MetricDescription::new("name"); + assert_eq!(label_value.to_prometheus(), "name"); + } + #[test] fn it_should_be_displayed() { let metric = MetricDescription::new("Metric description"); diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index a97621da8..f3278d98c 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -133,6 +133,10 @@ impl PrometheusSerializable for PrometheusType { impl PrometheusMetricSample<'_, T> { fn to_prometheus(&self, prometheus_type: &PrometheusType) -> String { format!( + // Format: + // # HELP + // # TYPE + // {label_set} "{}{}{}", self.help_line(), self.type_line(prometheus_type), @@ -142,7 +146,12 @@ impl PrometheusMetricSample<'_, T> { fn help_line(&self) -> String { if let Some(description) = &self.metric.opt_description { - format!("# HELP {description}\n") + format!( + // Format: # HELP + "# HELP {} {}\n", + self.metric.name().to_prometheus(), + description.to_prometheus() + ) } else { String::new() } @@ -154,6 +163,7 @@ impl PrometheusMetricSample<'_, T> { fn metric_line(&self) -> String { format!( + // Format: {label_set} "{}{} {}", self.metric.name.to_prometheus(), self.label_set.to_prometheus(), diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index 23b7609f6..122895478 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -529,14 +529,14 @@ mod tests { MetricKindCollection::new(vec![Metric::new( metric_name!("http_tracker_core_announce_requests_received_total"), None, - None, + Some(MetricDescription::new("The number of announce requests received.")), SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set_1.clone())]).unwrap(), )]) .unwrap(), MetricKindCollection::new(vec![Metric::new( metric_name!("udp_tracker_server_performance_avg_announce_processing_time_ns"), None, - None, + Some(MetricDescription::new("The average announce processing time in nanoseconds.")), SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set_1.clone())]).unwrap(), )]) .unwrap(), @@ -551,7 +551,7 @@ mod tests { "type":"counter", "name":"http_tracker_core_announce_requests_received_total", "unit": null, - "description": null, + "description": "The number of announce requests received.", "samples":[ { "value":1, @@ -577,7 +577,7 @@ mod tests { "type":"gauge", "name":"udp_tracker_server_performance_avg_announce_processing_time_ns", "unit": null, - "description": null, + "description": "The average announce processing time in nanoseconds.", "samples":[ { "value":1.0, @@ -607,8 +607,10 @@ mod tests { fn prometheus() -> String { format_prometheus_output( r#" + # HELP http_tracker_core_announce_requests_received_total The number of announce requests received. # TYPE http_tracker_core_announce_requests_received_total counter http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 + # HELP udp_tracker_server_performance_avg_announce_processing_time_ns The average announce processing time in nanoseconds. # TYPE udp_tracker_server_performance_avg_announce_processing_time_ns gauge udp_tracker_server_performance_avg_announce_processing_time_ns{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 "#, From 376f242166725f682c4b80502535b27b88fcb52c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 6 Jun 2025 16:31:07 +0100 Subject: [PATCH 1190/1297] test: [#1514] add tests to metrics package --- packages/metrics/src/metric/mod.rs | 51 +++++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 8 deletions(-) diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index f3278d98c..6f254023f 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -286,14 +286,25 @@ mod tests { #[test] fn it_should_allow_incrementing_a_sample() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); - let name = metric_name!("test_metric"); - let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); + let samples = SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(); + let mut metric = Metric::::new(name.clone(), None, None, samples); - let samples = SampleCollection::new(vec![Sample::new(Counter::new(1), time, label_set.clone())]).unwrap(); + metric.increment(&label_set, time); - let metric = Metric::::new(name.clone(), None, None, samples); + assert_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1); + } + + #[test] + fn it_should_allow_setting_to_an_absolute_value() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let name = metric_name!("test_metric"); + let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); + let samples = SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(); + let mut metric = Metric::::new(name.clone(), None, None, samples); + + metric.absolute(&label_set, 1, time); assert_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1); } @@ -318,16 +329,40 @@ mod tests { } #[test] - fn it_should_allow_setting_a_sample() { + fn it_should_allow_incrementing_a_sample() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); - let name = metric_name!("test_metric"); - let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); + let samples = SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(); + let mut metric = Metric::::new(name.clone(), None, None, samples); + metric.increment(&label_set, time); + + assert_relative_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1.0); + } + + #[test] + fn it_should_allow_decrement_a_sample() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let name = metric_name!("test_metric"); + let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); let samples = SampleCollection::new(vec![Sample::new(Gauge::new(1.0), time, label_set.clone())]).unwrap(); + let mut metric = Metric::::new(name.clone(), None, None, samples); - let metric = Metric::::new(name.clone(), None, None, samples); + metric.decrement(&label_set, time); + + assert_relative_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 0.0); + } + + #[test] + fn it_should_allow_setting_a_sample() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let name = metric_name!("test_metric"); + let label_set: LabelSet = [(label_name!("server_binding_protocol"), LabelValue::new("http"))].into(); + let samples = SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(); + let mut metric = Metric::::new(name.clone(), None, None, samples); + + metric.set(&label_set, 1.0, time); assert_relative_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1.0); } From 507b48035daac72b6ae5c22394fc7198fe3fee02 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 6 Jun 2025 17:01:43 +0100 Subject: [PATCH 1191/1297] fix: [#1514] bug. Don't allow merge metric collections with the same metrin name It was not possible to merge counters or gauges if the metric names was duplicate but possible when the metric name was duplciate across types. For example, the target collection (the one is mutated) contains a counter with a name that is being used in the source collection (the wan we get metric from) for a gauge metric. --- packages/metrics/src/metric_collection.rs | 82 +++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index 122895478..c7dfbba7a 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -50,11 +50,33 @@ impl MetricCollection { /// /// Returns an error if a metric name already exists in the current collection. pub fn merge(&mut self, other: &Self) -> Result<(), Error> { + self.check_cross_type_collision(other)?; self.counters.merge(&other.counters)?; self.gauges.merge(&other.gauges)?; Ok(()) } + /// Returns a set of all metric names in this collection. + fn collect_names(&self) -> HashSet { + self.counters.names().chain(self.gauges.names()).cloned().collect() + } + + /// Checks for name collisions between this collection and another one. + fn check_cross_type_collision(&self, other: &Self) -> Result<(), Error> { + let self_names: HashSet<_> = self.collect_names(); + let other_names: HashSet<_> = other.collect_names(); + + let cross_type_collisions = self_names.intersection(&other_names).next(); + + if let Some(name) = cross_type_collisions { + return Err(Error::MetricNameCollisionInMerge { + metric_name: (*name).clone(), + }); + } + + Ok(()) + } + // Counter-specific methods pub fn describe_counter(&mut self, name: &MetricName, opt_unit: Option, opt_description: Option) { @@ -774,6 +796,66 @@ mod tests { assert_eq!(prometheus_output, ""); } + #[test] + fn it_should_allow_merging_metric_collections() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection1 = MetricCollection::default(); + collection1 + .increase_counter(&metric_name!("test_counter"), &label_set, time) + .unwrap(); + + let mut collection2 = MetricCollection::default(); + collection2 + .set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time) + .unwrap(); + + collection1.merge(&collection2).unwrap(); + + assert!(collection1.contains_counter(&metric_name!("test_counter"))); + assert!(collection1.contains_gauge(&metric_name!("test_gauge"))); + } + + #[test] + fn it_should_not_allow_merging_metric_collections_with_name_collisions_for_the_same_metric_types() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection1 = MetricCollection::default(); + collection1 + .increase_counter(&metric_name!("test_metric"), &label_set, time) + .unwrap(); + + let mut collection2 = MetricCollection::default(); + collection2 + .increase_counter(&metric_name!("test_metric"), &label_set, time) + .unwrap(); + let result = collection1.merge(&collection2); + + assert!(result.is_err()); + } + + #[test] + fn it_should_not_allow_merging_metric_collections_with_name_collisions_for_different_metric_types() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection1 = MetricCollection::default(); + collection1 + .increase_counter(&metric_name!("test_metric"), &label_set, time) + .unwrap(); + + let mut collection2 = MetricCollection::default(); + collection2 + .set_gauge(&metric_name!("test_metric"), &label_set, 1.0, time) + .unwrap(); + + let result = collection1.merge(&collection2); + + assert!(result.is_err()); + } + mod for_counters { use pretty_assertions::assert_eq; From bb2392dda0f2f7339544a3227a2d1adca008f156 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 6 Jun 2025 17:16:48 +0100 Subject: [PATCH 1192/1297] test: [#1514] add tests to metrics package --- packages/metrics/src/metric_collection.rs | 233 ++++++++++++++++++---- 1 file changed, 194 insertions(+), 39 deletions(-) diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index c7dfbba7a..c53d02bcf 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -374,17 +374,18 @@ impl MetricKindCollection { /// /// Returns an error if a metric name already exists in the current collection. pub fn merge(&mut self, other: &Self) -> Result<(), Error> { - // Check for name collisions - for metric_name in other.metrics.keys() { - if self.metrics.contains_key(metric_name) { - return Err(Error::MetricNameCollisionInMerge { - metric_name: metric_name.clone(), - }); - } - } + self.check_for_name_collision(other)?; for (metric_name, metric) in &other.metrics { - if self.metrics.insert(metric_name.clone(), metric.clone()).is_some() { + self.metrics.insert(metric_name.clone(), metric.clone()); + } + + Ok(()) + } + + fn check_for_name_collision(&self, other: &Self) -> Result<(), Error> { + for metric_name in other.metrics.keys() { + if self.metrics.contains_key(metric_name) { return Err(Error::MetricNameCollisionInMerge { metric_name: metric_name.clone(), }); @@ -856,6 +857,38 @@ mod tests { assert!(result.is_err()); } + fn collection_with_one_counter(metric_name: &MetricName, label_set: &LabelSet, counter: Counter) -> MetricCollection { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + MetricCollection::new( + MetricKindCollection::new(vec![Metric::new( + metric_name.clone(), + None, + None, + SampleCollection::new(vec![Sample::new(counter, time, label_set.clone())]).unwrap(), + )]) + .unwrap(), + MetricKindCollection::default(), + ) + .unwrap() + } + + fn collection_with_one_gauge(metric_name: &MetricName, label_set: &LabelSet, gauge: Gauge) -> MetricCollection { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + + MetricCollection::new( + MetricKindCollection::default(), + MetricKindCollection::new(vec![Metric::new( + metric_name.clone(), + None, + None, + SampleCollection::new(vec![Sample::new(gauge, time, label_set.clone())]).unwrap(), + )]) + .unwrap(), + ) + .unwrap() + } + mod for_counters { use pretty_assertions::assert_eq; @@ -866,32 +899,54 @@ mod tests { use crate::sample_collection::SampleCollection; #[test] - fn it_should_increase_a_preexistent_counter() { + fn it_should_allow_setting_to_an_absolute_value() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_counter"); let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); - let mut metric_collection = MetricCollection::new( - MetricKindCollection::new(vec![Metric::new( - metric_name!("test_counter"), - None, - None, - SampleCollection::new(vec![Sample::new(Counter::new(0), time, label_set.clone())]).unwrap(), - )]) - .unwrap(), - MetricKindCollection::default(), - ) - .unwrap(); + let mut collection = collection_with_one_counter(&metric_name, &label_set, Counter::new(0)); - metric_collection - .increase_counter(&metric_name!("test_counter"), &label_set, time) + collection + .set_counter(&metric_name!("test_counter"), &label_set, 1, time) .unwrap(); - metric_collection + + assert_eq!( + collection.get_counter_value(&metric_name!("test_counter"), &label_set), + Some(Counter::new(1)) + ); + } + + #[test] + fn it_should_fail_setting_to_an_absolute_value_if_a_gauge_with_the_same_name_exists() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_counter"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_gauge(&metric_name, &label_set, Gauge::new(0.0)); + + let result = collection.set_counter(&metric_name!("test_counter"), &label_set, 1, time); + + assert!( + result.is_err() + && matches!(result, Err(Error::MetricNameCollisionAdding { metric_name }) if metric_name == metric_name!("test_counter")) + ); + } + + #[test] + fn it_should_increase_a_preexistent_counter() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_counter"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_counter(&metric_name, &label_set, Counter::new(0)); + + collection .increase_counter(&metric_name!("test_counter"), &label_set, time) .unwrap(); assert_eq!( - metric_collection.get_counter_value(&metric_name!("test_counter"), &label_set), - Some(Counter::new(2)) + collection.get_counter_value(&metric_name!("test_counter"), &label_set), + Some(Counter::new(1)) ); } @@ -962,30 +1017,89 @@ mod tests { #[test] fn it_should_set_a_preexistent_gauge() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_gauge"); let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); - let mut metric_collection = MetricCollection::new( - MetricKindCollection::default(), - MetricKindCollection::new(vec![Metric::new( - metric_name!("test_gauge"), - None, - None, - SampleCollection::new(vec![Sample::new(Gauge::new(0.0), time, label_set.clone())]).unwrap(), - )]) - .unwrap(), - ) - .unwrap(); + let mut collection = collection_with_one_gauge(&metric_name, &label_set, Gauge::new(0.0)); - metric_collection + collection .set_gauge(&metric_name!("test_gauge"), &label_set, 1.0, time) .unwrap(); assert_eq!( - metric_collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), + collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), Some(Gauge::new(1.0)) ); } + #[test] + fn it_should_allow_incrementing_a_gauge() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_gauge"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_gauge(&metric_name, &label_set, Gauge::new(0.0)); + + collection + .increment_gauge(&metric_name!("test_gauge"), &label_set, time) + .unwrap(); + + assert_eq!( + collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), + Some(Gauge::new(1.0)) + ); + } + + #[test] + fn it_should_fail_incrementing_a_gauge_if_it_exists_a_counter_with_the_same_name() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_gauge"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_counter(&metric_name, &label_set, Counter::new(0)); + + let result = collection.increment_gauge(&metric_name!("test_gauge"), &label_set, time); + + assert!( + result.is_err() + && matches!(result, Err(Error::MetricNameCollisionAdding { metric_name }) if metric_name == metric_name!("test_gauge")) + ); + } + + #[test] + fn it_should_allow_decrementing_a_gauge() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_gauge"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_gauge(&metric_name, &label_set, Gauge::new(1.0)); + + collection + .decrement_gauge(&metric_name!("test_gauge"), &label_set, time) + .unwrap(); + + assert_eq!( + collection.get_gauge_value(&metric_name!("test_gauge"), &label_set), + Some(Gauge::new(0.0)) + ); + } + + #[test] + fn it_should_fail_decrementing_a_gauge_if_it_exists_a_counter_with_the_same_name() { + let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); + let metric_name = metric_name!("test_gauge"); + let label_set: LabelSet = (label_name!("label_name"), LabelValue::new("value")).into(); + + let mut collection = collection_with_one_counter(&metric_name, &label_set, Counter::new(0)); + + let result = collection.decrement_gauge(&metric_name!("test_gauge"), &label_set, time); + + assert!( + result.is_err() + && matches!(result, Err(Error::MetricNameCollisionAdding { metric_name }) if metric_name == metric_name!("test_gauge")) + ); + } + #[test] fn it_should_automatically_create_a_gauge_when_setting_if_it_does_not_exist() { let time = DurationSinceUnixEpoch::from_secs(1_743_552_000); @@ -1037,4 +1151,45 @@ mod tests { assert!(result.is_err()); } } + + mod metric_kind_collection { + + use crate::counter::Counter; + use crate::gauge::Gauge; + use crate::metric::Metric; + use crate::metric_collection::{Error, MetricKindCollection}; + use crate::metric_name; + + #[test] + fn it_should_not_allow_merging_counter_metric_collections_with_name_collisions() { + let mut collection1 = MetricKindCollection::::default(); + collection1.insert(Metric::::new_empty_with_name(metric_name!("test_metric"))); + + let mut collection2 = MetricKindCollection::::default(); + collection2.insert(Metric::::new_empty_with_name(metric_name!("test_metric"))); + + let result = collection1.merge(&collection2); + + assert!( + result.is_err() + && matches!(result, Err(Error::MetricNameCollisionInMerge { metric_name }) if metric_name == metric_name!("test_metric")) + ); + } + + #[test] + fn it_should_not_allow_merging_gauge_metric_collections_with_name_collisions() { + let mut collection1 = MetricKindCollection::::default(); + collection1.insert(Metric::::new_empty_with_name(metric_name!("test_metric"))); + + let mut collection2 = MetricKindCollection::::default(); + collection2.insert(Metric::::new_empty_with_name(metric_name!("test_metric"))); + + let result = collection1.merge(&collection2); + + assert!( + result.is_err() + && matches!(result, Err(Error::MetricNameCollisionInMerge { metric_name }) if metric_name == metric_name!("test_metric")) + ); + } + } } From 45bc807c366ee1dd4522ac9cfdb00f45d8eeb606 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 9 Jun 2025 12:59:55 +0100 Subject: [PATCH 1193/1297] refactor: [#1534] rename TORRENT_REPOSITORY_LOG_TARGET to SWARM_COORDINATION_REGISTRY_LOG_TARGET --- packages/swarm-coordination-registry/src/lib.rs | 2 +- .../src/statistics/event/listener.rs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/swarm-coordination-registry/src/lib.rs b/packages/swarm-coordination-registry/src/lib.rs index fc7996817..eb2721a0c 100644 --- a/packages/swarm-coordination-registry/src/lib.rs +++ b/packages/swarm-coordination-registry/src/lib.rs @@ -22,7 +22,7 @@ pub(crate) type CurrentClock = clock::Working; #[allow(dead_code)] pub(crate) type CurrentClock = clock::Stopped; -pub const TORRENT_REPOSITORY_LOG_TARGET: &str = "TORRENT_REPOSITORY"; +pub const SWARM_COORDINATION_REGISTRY_LOG_TARGET: &str = "SWARM_COORDINATION_REGISTRY"; #[cfg(test)] pub(crate) mod tests { diff --git a/packages/swarm-coordination-registry/src/statistics/event/listener.rs b/packages/swarm-coordination-registry/src/statistics/event/listener.rs index f3b534332..9ff707818 100644 --- a/packages/swarm-coordination-registry/src/statistics/event/listener.rs +++ b/packages/swarm-coordination-registry/src/statistics/event/listener.rs @@ -7,18 +7,18 @@ use torrust_tracker_events::receiver::RecvError; use super::handler::handle_event; use crate::event::receiver::Receiver; use crate::statistics::repository::Repository; -use crate::{CurrentClock, TORRENT_REPOSITORY_LOG_TARGET}; +use crate::{CurrentClock, SWARM_COORDINATION_REGISTRY_LOG_TARGET}; #[must_use] pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { let stats_repository = repository.clone(); - tracing::info!(target: TORRENT_REPOSITORY_LOG_TARGET, "Starting torrent repository event listener"); + tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Starting torrent repository event listener"); tokio::spawn(async move { dispatch_events(receiver, stats_repository).await; - tracing::info!(target: TORRENT_REPOSITORY_LOG_TARGET, "Torrent repository listener finished"); + tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Torrent repository listener finished"); }) } @@ -32,7 +32,7 @@ async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc { - tracing::info!(target: TORRENT_REPOSITORY_LOG_TARGET, "Received Ctrl+C, shutting down torrent repository event listener."); + tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Received Ctrl+C, shutting down torrent repository event listener."); break; } @@ -42,11 +42,11 @@ async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc { match e { RecvError::Closed => { - tracing::info!(target: TORRENT_REPOSITORY_LOG_TARGET, "Torrent repository event receiver closed."); + tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Torrent repository event receiver closed."); break; } RecvError::Lagged(n) => { - tracing::warn!(target: TORRENT_REPOSITORY_LOG_TARGET, "Torrent repository event receiver lagged by {} events.", n); + tracing::warn!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Torrent repository event receiver lagged by {} events.", n); } } } From c67f27a7f071708cf4739fd7ae3cbff3e946464f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 9 Jun 2025 13:05:03 +0100 Subject: [PATCH 1194/1297] refactor: [#1534] Rename torrent_repository_ prefix to swarm_coordination_registry_ --- .../statistics/activity_metrics_updater.rs | 6 +- .../src/statistics/event/handler.rs | 88 ++++++++++++------- .../src/statistics/mod.rs | 44 +++++----- 3 files changed, 83 insertions(+), 55 deletions(-) diff --git a/packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs b/packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs index 016e230ec..cf814e810 100644 --- a/packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs +++ b/packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs @@ -10,7 +10,7 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use tracing::instrument; use super::repository::Repository; -use crate::statistics::{TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL, TORRENT_REPOSITORY_TORRENTS_INACTIVE_TOTAL}; +use crate::statistics::{SWARM_COORDINATION_REGISTRY_PEERS_INACTIVE_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_INACTIVE_TOTAL}; use crate::{CurrentClock, Registry}; #[must_use] @@ -81,7 +81,7 @@ async fn update_inactive_peers_total(stats_repository: &Arc, inactiv let _unused = stats_repository .set_gauge( - &metric_name!(TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_INACTIVE_TOTAL), &LabelSet::default(), inactive_peers_total, CurrentClock::now(), @@ -95,7 +95,7 @@ async fn update_inactive_torrents_total(stats_repository: &Arc, inac let _unused = stats_repository .set_gauge( - &metric_name!(TORRENT_REPOSITORY_TORRENTS_INACTIVE_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_INACTIVE_TOTAL), &LabelSet::default(), inactive_torrents_total, CurrentClock::now(), diff --git a/packages/swarm-coordination-registry/src/statistics/event/handler.rs b/packages/swarm-coordination-registry/src/statistics/event/handler.rs index f8d350a80..17b012086 100644 --- a/packages/swarm-coordination-registry/src/statistics/event/handler.rs +++ b/packages/swarm-coordination-registry/src/statistics/event/handler.rs @@ -8,11 +8,13 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; use crate::statistics::repository::Repository; use crate::statistics::{ - TORRENT_REPOSITORY_PEERS_ADDED_TOTAL, TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL, TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL, - TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL, TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL, - TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL, TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL, TORRENT_REPOSITORY_TORRENTS_TOTAL, + SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL, SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL, + SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL, SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL, + SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL, + SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL, }; +#[allow(clippy::too_many_lines)] pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { match event { // Torrent events @@ -20,12 +22,16 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: tracing::debug!(info_hash = ?info_hash, "Torrent added",); let _unused = stats_repository - .increment_gauge(&metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), &LabelSet::default(), now) + .increment_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL), + &LabelSet::default(), + now, + ) .await; let _unused = stats_repository .increment_counter( - &metric_name!(TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL), &LabelSet::default(), now, ) @@ -35,12 +41,16 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: tracing::debug!(info_hash = ?info_hash, "Torrent removed",); let _unused = stats_repository - .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), &LabelSet::default(), now) + .decrement_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL), + &LabelSet::default(), + now, + ) .await; let _unused = stats_repository .increment_counter( - &metric_name!(TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL), &LabelSet::default(), now, ) @@ -54,11 +64,15 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: let label_set = label_set_for_peer(&peer); let _unused = stats_repository - .increment_gauge(&metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), &label_set, now) + .increment_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL), + &label_set, + now, + ) .await; let _unused = stats_repository - .increment_counter(&metric_name!(TORRENT_REPOSITORY_PEERS_ADDED_TOTAL), &label_set, now) + .increment_counter(&metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL), &label_set, now) .await; } Event::PeerRemoved { info_hash, peer } => { @@ -67,11 +81,19 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: let label_set = label_set_for_peer(&peer); let _unused = stats_repository - .decrement_gauge(&metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), &label_set, now) + .decrement_gauge( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL), + &label_set, + now, + ) .await; let _unused = stats_repository - .increment_counter(&metric_name!(TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL), &label_set, now) + .increment_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL), + &label_set, + now, + ) .await; } Event::PeerUpdated { @@ -84,7 +106,7 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: if old_peer.role() != new_peer.role() { let _unused = stats_repository .increment_gauge( - &metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL), &label_set_for_peer(&new_peer), now, ) @@ -92,7 +114,7 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: let _unused = stats_repository .decrement_gauge( - &metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL), &label_set_for_peer(&old_peer), now, ) @@ -102,7 +124,11 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: let label_set = label_set_for_peer(&new_peer); let _unused = stats_repository - .increment_counter(&metric_name!(TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL), &label_set, now) + .increment_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL), + &label_set, + now, + ) .await; } Event::PeerDownloadCompleted { info_hash, peer } => { @@ -110,7 +136,7 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: let _unused = stats_repository .increment_counter( - &metric_name!(TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL), &label_set_for_peer(&peer), now, ) @@ -217,7 +243,8 @@ mod tests { use crate::statistics::event::handler::tests::{expect_counter_metric_to_be, expect_gauge_metric_to_be}; use crate::statistics::repository::Repository; use crate::statistics::{ - TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL, TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL, TORRENT_REPOSITORY_TORRENTS_TOTAL, + SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL, + SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL, }; use crate::tests::{sample_info_hash, sample_peer}; use crate::CurrentClock; @@ -240,7 +267,7 @@ mod tests { expect_gauge_metric_to_be( &stats_repository, - &metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL), &LabelSet::default(), 1.0, ) @@ -252,7 +279,7 @@ mod tests { clock::Stopped::local_set_to_unix_epoch(); let stats_repository = Arc::new(Repository::new()); - let metric_name = metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL); + let metric_name = metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL); let label_set = LabelSet::default(); // Increment the gauge first to simulate a torrent being added. @@ -291,7 +318,7 @@ mod tests { expect_counter_metric_to_be( &stats_repository, - &metric_name!(TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL), &LabelSet::default(), 1, ) @@ -315,7 +342,7 @@ mod tests { expect_counter_metric_to_be( &stats_repository, - &metric_name!(TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL), &LabelSet::default(), 1, ) @@ -335,7 +362,8 @@ mod tests { use crate::statistics::event::handler::{handle_event, label_set_for_peer}; use crate::statistics::repository::Repository; use crate::statistics::{ - TORRENT_REPOSITORY_PEERS_ADDED_TOTAL, TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL, TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL, + SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL, SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL, + SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL, }; use crate::tests::{sample_info_hash, sample_peer}; use crate::CurrentClock; @@ -357,7 +385,7 @@ mod tests { expect_gauge_metric_to_be, get_gauge_metric, make_opposite_role_peer, make_peer, }; use crate::statistics::repository::Repository; - use crate::statistics::TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL; + use crate::statistics::SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL; use crate::tests::sample_info_hash; use crate::CurrentClock; @@ -373,7 +401,7 @@ mod tests { let peer = make_peer(role); let stats_repository = Arc::new(Repository::new()); - let metric_name = metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL); + let metric_name = metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL); let label_set = (label_name!("peer_role"), LabelValue::new(&role.to_string())).into(); handle_event( @@ -402,7 +430,7 @@ mod tests { let stats_repository = Arc::new(Repository::new()); - let metric_name = metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL); + let metric_name = metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL); let label_set = (label_name!("peer_role"), LabelValue::new(&role.to_string())).into(); // Increment the gauge first to simulate a peer being added. @@ -438,7 +466,7 @@ mod tests { let old_peer = make_peer(old_role); let new_peer = make_opposite_role_peer(&old_peer); - let metric_name = metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL); + let metric_name = metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL); let old_role_label_set = (label_name!("peer_role"), LabelValue::new(&old_peer.role().to_string())).into(); let new_role_label_set = (label_name!("peer_role"), LabelValue::new(&new_peer.role().to_string())).into(); @@ -497,7 +525,7 @@ mod tests { expect_counter_metric_to_be( &stats_repository, - &metric_name!(TORRENT_REPOSITORY_PEERS_ADDED_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL), &label_set_for_peer(&peer), 1, ) @@ -524,7 +552,7 @@ mod tests { expect_counter_metric_to_be( &stats_repository, - &metric_name!(TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL), &label_set_for_peer(&peer), 1, ) @@ -552,7 +580,7 @@ mod tests { expect_counter_metric_to_be( &stats_repository, - &metric_name!(TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL), &label_set_for_peer(&new_peer), 1, ) @@ -574,7 +602,7 @@ mod tests { use crate::statistics::event::handler::handle_event; use crate::statistics::event::handler::tests::{expect_counter_metric_to_be, make_peer}; use crate::statistics::repository::Repository; - use crate::statistics::TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL; + use crate::statistics::SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL; use crate::tests::sample_info_hash; use crate::CurrentClock; @@ -590,7 +618,7 @@ mod tests { let peer = make_peer(role); let stats_repository = Arc::new(Repository::new()); - let metric_name = metric_name!(TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL); + let metric_name = metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL); let label_set = (label_name!("peer_role"), LabelValue::new(&role.to_string())).into(); handle_event( diff --git a/packages/swarm-coordination-registry/src/statistics/mod.rs b/packages/swarm-coordination-registry/src/statistics/mod.rs index 6505a2db2..5b9b7f376 100644 --- a/packages/swarm-coordination-registry/src/statistics/mod.rs +++ b/packages/swarm-coordination-registry/src/statistics/mod.rs @@ -10,22 +10,22 @@ use torrust_tracker_metrics::unit::Unit; // Torrent metrics -const TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL: &str = "torrent_repository_torrents_added_total"; -const TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL: &str = "torrent_repository_torrents_removed_total"; +const SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL: &str = "swarm_coordination_registry_torrents_added_total"; +const SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL: &str = "swarm_coordination_registry_torrents_removed_total"; -const TORRENT_REPOSITORY_TORRENTS_TOTAL: &str = "torrent_repository_torrents_total"; -const TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL: &str = "torrent_repository_torrents_downloads_total"; -const TORRENT_REPOSITORY_TORRENTS_INACTIVE_TOTAL: &str = "torrent_repository_torrents_inactive_total"; +const SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL: &str = "swarm_coordination_registry_torrents_total"; +const SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL: &str = "swarm_coordination_registry_torrents_downloads_total"; +const SWARM_COORDINATION_REGISTRY_TORRENTS_INACTIVE_TOTAL: &str = "swarm_coordination_registry_torrents_inactive_total"; // Peers metrics -const TORRENT_REPOSITORY_PEERS_ADDED_TOTAL: &str = "torrent_repository_peers_added_total"; -const TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL: &str = "torrent_repository_peers_removed_total"; -const TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL: &str = "torrent_repository_peers_updated_total"; +const SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL: &str = "swarm_coordination_registry_peers_added_total"; +const SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL: &str = "swarm_coordination_registry_peers_removed_total"; +const SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL: &str = "swarm_coordination_registry_peers_updated_total"; -const TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL: &str = "torrent_repository_peer_connections_total"; -const TORRENT_REPOSITORY_UNIQUE_PEERS_TOTAL: &str = "torrent_repository_unique_peers_total"; // todo: not implemented yet -const TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL: &str = "torrent_repository_peers_inactive_total"; +const SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL: &str = "swarm_coordination_registry_peer_connections_total"; +const SWARM_COORDINATION_REGISTRY_UNIQUE_PEERS_TOTAL: &str = "swarm_coordination_registry_unique_peers_total"; // todo: not implemented yet +const SWARM_COORDINATION_REGISTRY_PEERS_INACTIVE_TOTAL: &str = "swarm_coordination_registry_peers_inactive_total"; #[must_use] pub fn describe_metrics() -> Metrics { @@ -34,31 +34,31 @@ pub fn describe_metrics() -> Metrics { // Torrent metrics metrics.metric_collection.describe_counter( - &metric_name!(TORRENT_REPOSITORY_TORRENTS_ADDED_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("The total number of torrents added.")), ); metrics.metric_collection.describe_counter( - &metric_name!(TORRENT_REPOSITORY_TORRENTS_REMOVED_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("The total number of torrents removed.")), ); metrics.metric_collection.describe_gauge( - &metric_name!(TORRENT_REPOSITORY_TORRENTS_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL), Some(Unit::Count), Some(MetricDescription::new("The total number of torrents.")), ); metrics.metric_collection.describe_counter( - &metric_name!(TORRENT_REPOSITORY_TORRENTS_DOWNLOADS_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL), Some(Unit::Count), Some(MetricDescription::new("The total number of torrent downloads.")), ); metrics.metric_collection.describe_gauge( - &metric_name!(TORRENT_REPOSITORY_TORRENTS_INACTIVE_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_INACTIVE_TOTAL), Some(Unit::Count), Some(MetricDescription::new("The total number of inactive torrents.")), ); @@ -66,25 +66,25 @@ pub fn describe_metrics() -> Metrics { // Peers metrics metrics.metric_collection.describe_counter( - &metric_name!(TORRENT_REPOSITORY_PEERS_ADDED_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("The total number of peers added.")), ); metrics.metric_collection.describe_counter( - &metric_name!(TORRENT_REPOSITORY_PEERS_REMOVED_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("The total number of peers removed.")), ); metrics.metric_collection.describe_counter( - &metric_name!(TORRENT_REPOSITORY_PEERS_UPDATED_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL), Some(Unit::Count), Some(MetricDescription::new("The total number of peers updated.")), ); metrics.metric_collection.describe_gauge( - &metric_name!(TORRENT_REPOSITORY_PEER_CONNECTIONS_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL), Some(Unit::Count), Some(MetricDescription::new( "The total number of peer connections (one connection per torrent).", @@ -92,13 +92,13 @@ pub fn describe_metrics() -> Metrics { ); metrics.metric_collection.describe_gauge( - &metric_name!(TORRENT_REPOSITORY_UNIQUE_PEERS_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_UNIQUE_PEERS_TOTAL), Some(Unit::Count), Some(MetricDescription::new("The total number of unique peers.")), ); metrics.metric_collection.describe_gauge( - &metric_name!(TORRENT_REPOSITORY_PEERS_INACTIVE_TOTAL), + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_INACTIVE_TOTAL), Some(Unit::Count), Some(MetricDescription::new("The total number of inactive peers.")), ); From c26315aea7c837ff0c523b5979600aa8f00d93bf Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 9 Jun 2025 13:06:36 +0100 Subject: [PATCH 1195/1297] refactor: [#1534] Rename TorrentRepositoryContainer type to SwarmCoordinationRegistryContainer --- packages/axum-http-tracker-server/src/environment.rs | 4 ++-- packages/axum-http-tracker-server/src/server.rs | 4 ++-- packages/axum-rest-tracker-api-server/src/environment.rs | 4 ++-- packages/http-tracker-core/src/container.rs | 4 ++-- packages/rest-tracker-api-core/src/container.rs | 8 ++++---- packages/rest-tracker-api-core/src/statistics/services.rs | 4 ++-- packages/swarm-coordination-registry/src/container.rs | 4 ++-- packages/tracker-core/src/container.rs | 7 +++++-- packages/tracker-core/tests/common/test_env.rs | 6 +++--- packages/udp-tracker-core/src/container.rs | 4 ++-- packages/udp-tracker-server/src/environment.rs | 4 ++-- src/container.rs | 6 +++--- 12 files changed, 31 insertions(+), 28 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index 54c6b7767..ccc54b9cc 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -10,7 +10,7 @@ use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_primitives::peer; -use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use crate::server::{HttpServer, Launcher, Running, Stopped}; @@ -144,7 +144,7 @@ impl EnvContainer { .expect("missing HTTP tracker configuration"); let http_tracker_config = Arc::new(http_tracker_config[0].clone()); - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( configuration.core.tracker_usage_statistics.into(), )); diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index b8ece8086..99ba4be51 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -259,7 +259,7 @@ mod tests { use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; - use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; + use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::server::{HttpServer, Launcher}; @@ -290,7 +290,7 @@ mod tests { let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); } - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( configuration.core.tracker_usage_statistics.into(), )); diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index 6be4cc53c..fc6ee112e 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -12,7 +12,7 @@ use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; use torrust_tracker_primitives::peer; -use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use crate::server::{ApiServer, Launcher, Running, Stopped}; @@ -173,7 +173,7 @@ impl EnvContainer { .clone(), ); - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); diff --git a/packages/http-tracker-core/src/container.rs b/packages/http-tracker-core/src/container.rs index 35f75e1fe..f573740a7 100644 --- a/packages/http-tracker-core/src/container.rs +++ b/packages/http-tracker-core/src/container.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use bittorrent_tracker_core::container::TrackerCoreContainer; use torrust_tracker_configuration::{Core, HttpTracker}; -use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; @@ -27,7 +27,7 @@ pub struct HttpTrackerCoreContainer { impl HttpTrackerCoreContainer { #[must_use] pub fn initialize(core_config: &Arc, http_tracker_config: &Arc) -> Arc { - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs index f76c2ece3..238e76801 100644 --- a/packages/rest-tracker-api-core/src/container.rs +++ b/packages/rest-tracker-api-core/src/container.rs @@ -7,14 +7,14 @@ use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self}; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, HttpApi, HttpTracker, UdpTracker}; -use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; pub struct TrackerHttpApiCoreContainer { pub http_api_config: Arc, // Torrent repository - pub torrent_repository_container: Arc, + pub torrent_repository_container: Arc, // Tracker core pub tracker_core_container: Arc, @@ -36,7 +36,7 @@ impl TrackerHttpApiCoreContainer { udp_tracker_config: &Arc, http_api_config: &Arc, ) -> Arc { - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); @@ -65,7 +65,7 @@ impl TrackerHttpApiCoreContainer { #[must_use] pub fn initialize_from( - torrent_repository_container: &Arc, + torrent_repository_container: &Arc, tracker_core_container: &Arc, http_tracker_core_container: &Arc, udp_tracker_core_container: &Arc, diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 56536a02f..1467517d9 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -165,7 +165,7 @@ mod tests { use tokio::sync::RwLock; use torrust_tracker_configuration::Configuration; use torrust_tracker_events::bus::SenderStatus; - use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; + use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use torrust_tracker_test_helpers::configuration; use crate::statistics::metrics::{ProtocolMetrics, TorrentsMetrics}; @@ -180,7 +180,7 @@ mod tests { let config = tracker_configuration(); let core_config = Arc::new(config.core.clone()); - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize(SenderStatus::Enabled)); + let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize(SenderStatus::Enabled)); let tracker_core_container = TrackerCoreContainer::initialize_from(&core_config, &torrent_repository_container.clone()); diff --git a/packages/swarm-coordination-registry/src/container.rs b/packages/swarm-coordination-registry/src/container.rs index 1b56b3d4b..1a243f967 100644 --- a/packages/swarm-coordination-registry/src/container.rs +++ b/packages/swarm-coordination-registry/src/container.rs @@ -8,14 +8,14 @@ use crate::event::{self}; use crate::statistics::repository::Repository; use crate::{statistics, Registry}; -pub struct TorrentRepositoryContainer { +pub struct SwarmCoordinationRegistryContainer { pub swarms: Arc, pub event_bus: Arc, pub stats_event_sender: event::sender::Sender, pub stats_repository: Arc, } -impl TorrentRepositoryContainer { +impl SwarmCoordinationRegistryContainer { #[must_use] pub fn initialize(sender_status: SenderStatus) -> Self { // Torrent repository stats diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs index 949761553..8d776a3e6 100644 --- a/packages/tracker-core/src/container.rs +++ b/packages/tracker-core/src/container.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use torrust_tracker_configuration::Core; -use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use crate::announce_handler::AnnounceHandler; use crate::authentication::handler::KeysHandler; @@ -38,7 +38,10 @@ pub struct TrackerCoreContainer { impl TrackerCoreContainer { #[must_use] - pub fn initialize_from(core_config: &Arc, torrent_repository_container: &Arc) -> Self { + pub fn initialize_from( + core_config: &Arc, + torrent_repository_container: &Arc, + ) -> Self { let database = initialize_database(core_config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(core_config, &in_memory_whitelist.clone())); diff --git a/packages/tracker-core/tests/common/test_env.rs b/packages/tracker-core/tests/common/test_env.rs index 64bdcaad8..0c1ea8524 100644 --- a/packages/tracker-core/tests/common/test_env.rs +++ b/packages/tracker-core/tests/common/test_env.rs @@ -14,10 +14,10 @@ use torrust_tracker_primitives::core::{AnnounceData, ScrapeData}; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; pub struct TestEnv { - pub torrent_repository_container: Arc, + pub torrent_repository_container: Arc, pub tracker_core_container: Arc, } @@ -33,7 +33,7 @@ impl TestEnv { pub fn new(core_config: Core) -> Self { let core_config = Arc::new(core_config); - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index c4be395fc..a6e45268f 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use bittorrent_tracker_core::container::TrackerCoreContainer; use tokio::sync::RwLock; use torrust_tracker_configuration::{Core, UdpTracker}; -use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; @@ -32,7 +32,7 @@ pub struct UdpTrackerCoreContainer { impl UdpTrackerCoreContainer { #[must_use] pub fn initialize(core_config: &Arc, udp_tracker_config: &Arc) -> Arc { - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 268259f1b..d12a1b011 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -8,7 +8,7 @@ use tokio::task::JoinHandle; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_primitives::peer; -use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use crate::container::UdpTrackerServerContainer; use crate::server::spawner::Spawner; @@ -175,7 +175,7 @@ impl EnvContainer { let udp_tracker_configurations = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); diff --git a/src/container.rs b/src/container.rs index bb5873fb2..0f73bda6b 100644 --- a/src/container.rs +++ b/src/container.rs @@ -9,7 +9,7 @@ use bittorrent_udp_tracker_core::{self}; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{Configuration, HttpApi}; -use torrust_tracker_swarm_coordination_registry::container::TorrentRepositoryContainer; +use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; use tracing::instrument; @@ -30,7 +30,7 @@ pub struct AppContainer { pub registar: Arc, // Torrent Repository - pub torrent_repository_container: Arc, + pub torrent_repository_container: Arc, // Core pub tracker_core_container: Arc, @@ -60,7 +60,7 @@ impl AppContainer { // Torrent Repository - let torrent_repository_container = Arc::new(TorrentRepositoryContainer::initialize( + let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); From b09e79c5983952ece3f94e6c689f62737bf1fd86 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 9 Jun 2025 13:11:56 +0100 Subject: [PATCH 1196/1297] refactor: [#1534] Rename torrent_repository_container to swarm_coordination_registry_container --- .../src/environment.rs | 4 ++-- .../axum-http-tracker-server/src/server.rs | 4 ++-- .../src/environment.rs | 6 ++--- .../src/v1/context/stats/routes.rs | 5 ++++- packages/http-tracker-core/src/container.rs | 4 ++-- .../rest-tracker-api-core/src/container.rs | 12 +++++----- .../src/statistics/services.rs | 6 +++-- packages/tracker-core/src/container.rs | 6 +++-- .../tracker-core/tests/common/test_env.rs | 22 +++++++++++-------- packages/udp-tracker-core/src/container.rs | 4 ++-- .../udp-tracker-server/src/environment.rs | 4 ++-- .../jobs/activity_metrics_updater.rs | 4 ++-- src/bootstrap/jobs/torrent_repository.rs | 4 ++-- src/bootstrap/jobs/tracker_core.rs | 2 +- src/container.rs | 10 ++++----- 15 files changed, 54 insertions(+), 43 deletions(-) diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index ccc54b9cc..6e58c2cac 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -144,13 +144,13 @@ impl EnvContainer { .expect("missing HTTP tracker configuration"); let http_tracker_config = Arc::new(http_tracker_config[0].clone()); - let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( configuration.core.tracker_usage_statistics.into(), )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( &core_config, - &torrent_repository_container, + &swarm_coordination_registry_container, )); let http_tracker_container = diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 99ba4be51..1775a3d72 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -290,13 +290,13 @@ mod tests { let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); } - let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( configuration.core.tracker_usage_statistics.into(), )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( &core_config, - &torrent_repository_container, + &swarm_coordination_registry_container, )); let announce_service = Arc::new(AnnounceService::new( diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index fc6ee112e..cddb45277 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -173,13 +173,13 @@ impl EnvContainer { .clone(), ); - let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( &core_config, - &torrent_repository_container, + &swarm_coordination_registry_container, )); let http_tracker_core_container = @@ -191,7 +191,7 @@ impl EnvContainer { let udp_tracker_server_container = UdpTrackerServerContainer::initialize(&core_config); let tracker_http_api_core_container = TrackerHttpApiCoreContainer::initialize_from( - &torrent_repository_container, + &swarm_coordination_registry_container, &tracker_core_container, &http_tracker_core_container, &udp_tracker_core_container, diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs index a573b764a..c2a1466e0 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs @@ -30,7 +30,10 @@ pub fn add(prefix: &str, router: Router, http_api_container: &Arc, http_tracker_config: &Arc) -> Arc { - let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( core_config, - &torrent_repository_container, + &swarm_coordination_registry_container, )); Self::initialize_from_tracker_core(&tracker_core_container, http_tracker_config) diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs index 238e76801..93655b2ba 100644 --- a/packages/rest-tracker-api-core/src/container.rs +++ b/packages/rest-tracker-api-core/src/container.rs @@ -14,7 +14,7 @@ pub struct TrackerHttpApiCoreContainer { pub http_api_config: Arc, // Torrent repository - pub torrent_repository_container: Arc, + pub swarm_coordination_registry_container: Arc, // Tracker core pub tracker_core_container: Arc, @@ -36,13 +36,13 @@ impl TrackerHttpApiCoreContainer { udp_tracker_config: &Arc, http_api_config: &Arc, ) -> Arc { - let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( core_config, - &torrent_repository_container, + &swarm_coordination_registry_container, )); let http_tracker_core_container = @@ -54,7 +54,7 @@ impl TrackerHttpApiCoreContainer { let udp_tracker_server_container = UdpTrackerServerContainer::initialize(core_config); Self::initialize_from( - &torrent_repository_container, + &swarm_coordination_registry_container, &tracker_core_container, &http_tracker_core_container, &udp_tracker_core_container, @@ -65,7 +65,7 @@ impl TrackerHttpApiCoreContainer { #[must_use] pub fn initialize_from( - torrent_repository_container: &Arc, + swarm_coordination_registry_container: &Arc, tracker_core_container: &Arc, http_tracker_core_container: &Arc, udp_tracker_core_container: &Arc, @@ -76,7 +76,7 @@ impl TrackerHttpApiCoreContainer { http_api_config: http_api_config.clone(), // Torrent repository - torrent_repository_container: torrent_repository_container.clone(), + swarm_coordination_registry_container: swarm_coordination_registry_container.clone(), // Tracker core tracker_core_container: tracker_core_container.clone(), diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 1467517d9..6474df0d7 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -180,9 +180,11 @@ mod tests { let config = tracker_configuration(); let core_config = Arc::new(config.core.clone()); - let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize(SenderStatus::Enabled)); + let swarm_coordination_registry_container = + Arc::new(SwarmCoordinationRegistryContainer::initialize(SenderStatus::Enabled)); - let tracker_core_container = TrackerCoreContainer::initialize_from(&core_config, &torrent_repository_container.clone()); + let tracker_core_container = + TrackerCoreContainer::initialize_from(&core_config, &swarm_coordination_registry_container.clone()); let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs index 8d776a3e6..93b8efd7e 100644 --- a/packages/tracker-core/src/container.rs +++ b/packages/tracker-core/src/container.rs @@ -40,7 +40,7 @@ impl TrackerCoreContainer { #[must_use] pub fn initialize_from( core_config: &Arc, - torrent_repository_container: &Arc, + swarm_coordination_registry_container: &Arc, ) -> Self { let database = initialize_database(core_config); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -53,7 +53,9 @@ impl TrackerCoreContainer { &db_key_repository.clone(), &in_memory_key_repository.clone(), )); - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new(torrent_repository_container.swarms.clone())); + let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::new( + swarm_coordination_registry_container.swarms.clone(), + )); let db_downloads_metric_repository = Arc::new(DatabaseDownloadsMetricRepository::new(&database)); let torrents_manager = Arc::new(TorrentsManager::new( diff --git a/packages/tracker-core/tests/common/test_env.rs b/packages/tracker-core/tests/common/test_env.rs index 0c1ea8524..d3bc9652a 100644 --- a/packages/tracker-core/tests/common/test_env.rs +++ b/packages/tracker-core/tests/common/test_env.rs @@ -17,7 +17,7 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; pub struct TestEnv { - pub torrent_repository_container: Arc, + pub swarm_coordination_registry_container: Arc, pub tracker_core_container: Arc, } @@ -33,17 +33,17 @@ impl TestEnv { pub fn new(core_config: Core) -> Self { let core_config = Arc::new(core_config); - let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( &core_config, - &torrent_repository_container, + &swarm_coordination_registry_container, )); Self { - torrent_repository_container, + swarm_coordination_registry_container, tracker_core_container, } } @@ -68,13 +68,13 @@ impl TestEnv { let mut jobs = vec![]; let job = torrust_tracker_swarm_coordination_registry::statistics::event::listener::run_event_listener( - self.torrent_repository_container.event_bus.receiver(), - &self.torrent_repository_container.stats_repository, + self.swarm_coordination_registry_container.event_bus.receiver(), + &self.swarm_coordination_registry_container.stats_repository, ); jobs.push(job); let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( - self.torrent_repository_container.event_bus.receiver(), + self.swarm_coordination_registry_container.event_bus.receiver(), &self.tracker_core_container.stats_repository, &self.tracker_core_container.db_downloads_metric_repository, self.tracker_core_container @@ -147,7 +147,7 @@ impl TestEnv { } pub async fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option { - self.torrent_repository_container + self.swarm_coordination_registry_container .swarms .get_swarm_metadata(info_hash) .await @@ -155,7 +155,11 @@ impl TestEnv { } pub async fn remove_swarm(&self, info_hash: &InfoHash) { - self.torrent_repository_container.swarms.remove(info_hash).await.unwrap(); + self.swarm_coordination_registry_container + .swarms + .remove(info_hash) + .await + .unwrap(); } pub async fn get_counter_value(&self, metric_name: &str) -> u64 { diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index a6e45268f..1d8b1d71c 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -32,13 +32,13 @@ pub struct UdpTrackerCoreContainer { impl UdpTrackerCoreContainer { #[must_use] pub fn initialize(core_config: &Arc, udp_tracker_config: &Arc) -> Arc { - let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( core_config, - &torrent_repository_container, + &swarm_coordination_registry_container, )); Self::initialize_from_tracker_core(&tracker_core_container, udp_tracker_config) diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index d12a1b011..f48b3a7c1 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -175,13 +175,13 @@ impl EnvContainer { let udp_tracker_configurations = configuration.udp_trackers.clone().expect("missing UDP tracker configuration"); let udp_tracker_config = Arc::new(udp_tracker_configurations[0].clone()); - let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( &core_config, - &torrent_repository_container, + &swarm_coordination_registry_container, )); let udp_tracker_core_container = diff --git a/src/bootstrap/jobs/activity_metrics_updater.rs b/src/bootstrap/jobs/activity_metrics_updater.rs index 9813fed65..9bbdc3f9b 100644 --- a/src/bootstrap/jobs/activity_metrics_updater.rs +++ b/src/bootstrap/jobs/activity_metrics_updater.rs @@ -12,8 +12,8 @@ use crate::CurrentClock; #[must_use] pub fn start_job(config: &Configuration, app_container: &Arc) -> JoinHandle<()> { torrust_tracker_swarm_coordination_registry::statistics::activity_metrics_updater::start_job( - &app_container.torrent_repository_container.swarms.clone(), - &app_container.torrent_repository_container.stats_repository.clone(), + &app_container.swarm_coordination_registry_container.swarms.clone(), + &app_container.swarm_coordination_registry_container.stats_repository.clone(), peer_inactivity_cutoff_timestamp(config.core.tracker_policy.max_peer_timeout), ) } diff --git a/src/bootstrap/jobs/torrent_repository.rs b/src/bootstrap/jobs/torrent_repository.rs index c64917ea6..44ffdf53b 100644 --- a/src/bootstrap/jobs/torrent_repository.rs +++ b/src/bootstrap/jobs/torrent_repository.rs @@ -8,8 +8,8 @@ use crate::container::AppContainer; pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { if config.core.tracker_usage_statistics { let job = torrust_tracker_swarm_coordination_registry::statistics::event::listener::run_event_listener( - app_container.torrent_repository_container.event_bus.receiver(), - &app_container.torrent_repository_container.stats_repository, + app_container.swarm_coordination_registry_container.event_bus.receiver(), + &app_container.swarm_coordination_registry_container.stats_repository, ); Some(job) diff --git a/src/bootstrap/jobs/tracker_core.rs b/src/bootstrap/jobs/tracker_core.rs index fd5cacbda..f2fc25ef3 100644 --- a/src/bootstrap/jobs/tracker_core.rs +++ b/src/bootstrap/jobs/tracker_core.rs @@ -8,7 +8,7 @@ use crate::container::AppContainer; pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { if config.core.tracker_usage_statistics || config.core.tracker_policy.persistent_torrent_completed_stat { let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( - app_container.torrent_repository_container.event_bus.receiver(), + app_container.swarm_coordination_registry_container.event_bus.receiver(), &app_container.tracker_core_container.stats_repository, &app_container.tracker_core_container.db_downloads_metric_repository, app_container diff --git a/src/container.rs b/src/container.rs index 0f73bda6b..461a5b36a 100644 --- a/src/container.rs +++ b/src/container.rs @@ -30,7 +30,7 @@ pub struct AppContainer { pub registar: Arc, // Torrent Repository - pub torrent_repository_container: Arc, + pub swarm_coordination_registry_container: Arc, // Core pub tracker_core_container: Arc, @@ -60,7 +60,7 @@ impl AppContainer { // Torrent Repository - let torrent_repository_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( + let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), )); @@ -68,7 +68,7 @@ impl AppContainer { let tracker_core_container = Arc::new(TrackerCoreContainer::initialize_from( &core_config, - &torrent_repository_container, + &swarm_coordination_registry_container, )); // HTTP @@ -98,7 +98,7 @@ impl AppContainer { registar, // Torrent Repository - torrent_repository_container, + swarm_coordination_registry_container, // Core tracker_core_container, @@ -146,7 +146,7 @@ impl AppContainer { TrackerHttpApiCoreContainer { http_api_config: http_api_config.clone(), - torrent_repository_container: self.torrent_repository_container.clone(), + swarm_coordination_registry_container: self.swarm_coordination_registry_container.clone(), tracker_core_container: self.tracker_core_container.clone(), From 8da42e4333d015ff5927da10807f7c67fa399ece Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 9 Jun 2025 13:13:48 +0100 Subject: [PATCH 1197/1297] refactor: [#1534] Rename torrent_repository_event_listener to swarm_coordination_registry_event_listener --- src/app.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app.rs b/src/app.rs index ccc2e8bcb..5050c1dd1 100644 --- a/src/app.rs +++ b/src/app.rs @@ -71,7 +71,7 @@ async fn load_data_from_database(config: &Configuration, app_container: &Arc) -> JobManager { let mut job_manager = JobManager::new(); - start_torrent_repository_event_listener(config, app_container, &mut job_manager); + start_swarm_coordination_registry_event_listener(config, app_container, &mut job_manager); start_tracker_core_event_listener(config, app_container, &mut job_manager); start_http_core_event_listener(config, app_container, &mut job_manager); start_udp_core_event_listener(config, app_container, &mut job_manager); @@ -132,13 +132,13 @@ async fn load_torrent_metrics(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager, ) { job_manager.push_opt( - "torrent_repository_event_listener", + "swarm_coordination_registry_event_listener", jobs::torrent_repository::start_event_listener(config, app_container), ); } From b2feb7b3150f0314cace37b7f08a926a2eb63298 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 9 Jun 2025 13:15:40 +0100 Subject: [PATCH 1198/1297] docs: [#1534] Update comments after rename --- packages/rest-tracker-api-core/src/container.rs | 4 ++-- packages/swarm-coordination-registry/src/container.rs | 2 +- packages/tracker-core/src/statistics/persisted/downloads.rs | 2 +- src/container.rs | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/rest-tracker-api-core/src/container.rs b/packages/rest-tracker-api-core/src/container.rs index 93655b2ba..bcc5a0186 100644 --- a/packages/rest-tracker-api-core/src/container.rs +++ b/packages/rest-tracker-api-core/src/container.rs @@ -13,7 +13,7 @@ use torrust_udp_tracker_server::container::UdpTrackerServerContainer; pub struct TrackerHttpApiCoreContainer { pub http_api_config: Arc, - // Torrent repository + // Swarm Coordination Registry Container pub swarm_coordination_registry_container: Arc, // Tracker core @@ -75,7 +75,7 @@ impl TrackerHttpApiCoreContainer { Arc::new(TrackerHttpApiCoreContainer { http_api_config: http_api_config.clone(), - // Torrent repository + // Swarm Coordination Registry Container swarm_coordination_registry_container: swarm_coordination_registry_container.clone(), // Tracker core diff --git a/packages/swarm-coordination-registry/src/container.rs b/packages/swarm-coordination-registry/src/container.rs index 1a243f967..718e3ee52 100644 --- a/packages/swarm-coordination-registry/src/container.rs +++ b/packages/swarm-coordination-registry/src/container.rs @@ -18,7 +18,7 @@ pub struct SwarmCoordinationRegistryContainer { impl SwarmCoordinationRegistryContainer { #[must_use] pub fn initialize(sender_status: SenderStatus) -> Self { - // Torrent repository stats + // // Swarm Coordination Registry Container stats let broadcaster = Broadcaster::default(); let stats_repository = Arc::new(Repository::new()); diff --git a/packages/tracker-core/src/statistics/persisted/downloads.rs b/packages/tracker-core/src/statistics/persisted/downloads.rs index 4d3bdf9a3..6248bdc73 100644 --- a/packages/tracker-core/src/statistics/persisted/downloads.rs +++ b/packages/tracker-core/src/statistics/persisted/downloads.rs @@ -7,7 +7,7 @@ use torrust_tracker_primitives::{NumberOfDownloads, NumberOfDownloadsBTreeMap}; use crate::databases::error::Error; use crate::databases::Database; -/// Torrent repository implementation that persists torrent metrics in a database. +/// It persists torrent metrics in a database. /// /// This repository persists only a subset of the torrent data: the torrent /// metrics, specifically the number of downloads (or completed counts) for each diff --git a/src/container.rs b/src/container.rs index 461a5b36a..7112a54e8 100644 --- a/src/container.rs +++ b/src/container.rs @@ -29,7 +29,7 @@ pub struct AppContainer { // Registar pub registar: Arc, - // Torrent Repository + // Swarm Coordination Registry Container pub swarm_coordination_registry_container: Arc, // Core @@ -58,7 +58,7 @@ impl AppContainer { let registar = Arc::new(Registar::default()); - // Torrent Repository + // Swarm Coordination Registry Container let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( core_config.tracker_usage_statistics.into(), @@ -97,7 +97,7 @@ impl AppContainer { // Registar registar, - // Torrent Repository + // Swarm Coordination Registry Container swarm_coordination_registry_container, // Core From 7be03663946dcbcf2f1ee28d62b1c8d30741cd42 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 9 Jun 2025 13:42:39 +0100 Subject: [PATCH 1199/1297] feat: [#1534] add new metric to count peers reverting state from complete to any other state The metric is: ``` swarm_coordination_registry_peers_completed_state_reverted_total 1 ``` --- .../src/statistics/event/handler.rs | 27 +++++++++++++++---- .../src/statistics/mod.rs | 10 +++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/packages/swarm-coordination-registry/src/statistics/event/handler.rs b/packages/swarm-coordination-registry/src/statistics/event/handler.rs index 17b012086..1d3f8f32c 100644 --- a/packages/swarm-coordination-registry/src/statistics/event/handler.rs +++ b/packages/swarm-coordination-registry/src/statistics/event/handler.rs @@ -8,10 +8,11 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; use crate::statistics::repository::Repository; use crate::statistics::{ - SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL, SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL, - SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL, SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL, - SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL, - SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL, + SWARM_COORDINATION_REGISTRY_PEERS_ADDED_TOTAL, SWARM_COORDINATION_REGISTRY_PEERS_COMPLETED_STATE_REVERTED_TOTAL, + SWARM_COORDINATION_REGISTRY_PEERS_REMOVED_TOTAL, SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL, + SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_ADDED_TOTAL, + SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL, + SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL, }; #[allow(clippy::too_many_lines)] @@ -103,6 +104,8 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: } => { tracing::debug!(info_hash = ?info_hash, old_peer = ?old_peer, new_peer = ?new_peer, "Peer updated", ); + // If the peer's role has changed, we need to adjust the number of + // connections if old_peer.role() != new_peer.role() { let _unused = stats_repository .increment_gauge( @@ -121,6 +124,20 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: .await; } + // If the peer reverted from a completed state to any other state, + // we need to increment the counter for reverted completed. + if old_peer.is_completed() && !new_peer.is_completed() { + let _unused = stats_repository + .increment_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_COMPLETED_STATE_REVERTED_TOTAL), + &LabelSet::default(), + now, + ) + .await; + } + + // Regardless of the role change, we still need to increment the + // counter for updated peers. let label_set = label_set_for_peer(&new_peer); let _unused = stats_repository @@ -134,7 +151,7 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: Event::PeerDownloadCompleted { info_hash, peer } => { tracing::debug!(info_hash = ?info_hash, peer = ?peer, "Peer download completed", ); - let _unused = stats_repository + let _unused: Result<(), torrust_tracker_metrics::metric_collection::Error> = stats_repository .increment_counter( &metric_name!(SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL), &label_set_for_peer(&peer), diff --git a/packages/swarm-coordination-registry/src/statistics/mod.rs b/packages/swarm-coordination-registry/src/statistics/mod.rs index 5b9b7f376..a4bf4c018 100644 --- a/packages/swarm-coordination-registry/src/statistics/mod.rs +++ b/packages/swarm-coordination-registry/src/statistics/mod.rs @@ -26,6 +26,8 @@ const SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL: &str = "swarm_coordinatio const SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL: &str = "swarm_coordination_registry_peer_connections_total"; const SWARM_COORDINATION_REGISTRY_UNIQUE_PEERS_TOTAL: &str = "swarm_coordination_registry_unique_peers_total"; // todo: not implemented yet const SWARM_COORDINATION_REGISTRY_PEERS_INACTIVE_TOTAL: &str = "swarm_coordination_registry_peers_inactive_total"; +const SWARM_COORDINATION_REGISTRY_PEERS_COMPLETED_STATE_REVERTED_TOTAL: &str = + "swarm_coordination_registry_peers_completed_state_reverted_total"; #[must_use] pub fn describe_metrics() -> Metrics { @@ -103,5 +105,13 @@ pub fn describe_metrics() -> Metrics { Some(MetricDescription::new("The total number of inactive peers.")), ); + metrics.metric_collection.describe_counter( + &metric_name!(SWARM_COORDINATION_REGISTRY_PEERS_COMPLETED_STATE_REVERTED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new( + "The total number of peers whose completed state was reverted.", + )), + ); + metrics } From d81e59e2e11787ea99fa123091154a524c85f8eb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 9 Jun 2025 17:27:03 +0100 Subject: [PATCH 1200/1297] fix: [#1565] ban service should work with stats disabled --- .../src/banning/event/handler.rs | 19 ++++++ .../src/banning/event/listener.rs | 58 +++++++++++++++++++ .../src/banning/event/mod.rs | 2 + .../udp-tracker-server/src/banning/mod.rs | 1 + .../udp-tracker-server/src/environment.rs | 51 ++++++++-------- packages/udp-tracker-server/src/lib.rs | 1 + .../src/statistics/event/handler/error.rs | 15 ----- .../src/statistics/event/handler/mod.rs | 13 +---- .../event/handler/request_aborted.rs | 6 -- .../event/handler/request_accepted.rs | 14 ----- .../event/handler/request_banned.rs | 6 -- .../event/handler/request_received.rs | 4 -- .../statistics/event/handler/response_sent.rs | 6 -- .../src/statistics/event/listener.rs | 15 ++--- src/app.rs | 20 +++++-- src/bootstrap/jobs/udp_tracker_server.rs | 11 +++- 16 files changed, 137 insertions(+), 105 deletions(-) create mode 100644 packages/udp-tracker-server/src/banning/event/handler.rs create mode 100644 packages/udp-tracker-server/src/banning/event/listener.rs create mode 100644 packages/udp-tracker-server/src/banning/event/mod.rs create mode 100644 packages/udp-tracker-server/src/banning/mod.rs diff --git a/packages/udp-tracker-server/src/banning/event/handler.rs b/packages/udp-tracker-server/src/banning/event/handler.rs new file mode 100644 index 000000000..2d77d0979 --- /dev/null +++ b/packages/udp-tracker-server/src/banning/event/handler.rs @@ -0,0 +1,19 @@ +use std::sync::Arc; + +use bittorrent_udp_tracker_core::services::banning::BanService; +use tokio::sync::RwLock; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +use crate::event::{ErrorKind, Event}; + +pub async fn handle_event(event: Event, ban_service: &Arc>, _now: DurationSinceUnixEpoch) { + if let Event::UdpError { + context, + kind: _, + error: ErrorKind::ConnectionCookie(_msg), + } = event + { + let mut ban_service = ban_service.write().await; + ban_service.increase_counter(&context.client_socket_addr().ip()); + } +} diff --git a/packages/udp-tracker-server/src/banning/event/listener.rs b/packages/udp-tracker-server/src/banning/event/listener.rs new file mode 100644 index 000000000..ee1a4366f --- /dev/null +++ b/packages/udp-tracker-server/src/banning/event/listener.rs @@ -0,0 +1,58 @@ +use std::sync::Arc; + +use bittorrent_udp_tracker_core::services::banning::BanService; +use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; +use tokio::sync::RwLock; +use tokio::task::JoinHandle; +use torrust_tracker_clock::clock::Time; +use torrust_tracker_events::receiver::RecvError; + +use super::handler::handle_event; +use crate::event::receiver::Receiver; +use crate::CurrentClock; + +#[must_use] +pub fn run_event_listener(receiver: Receiver, ban_service: &Arc>) -> JoinHandle<()> { + let ban_service_clone = ban_service.clone(); + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker server event listener (banning)"); + + tokio::spawn(async move { + dispatch_events(receiver, ban_service_clone).await; + + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker server event listener (banning) finished"); + }) +} + +async fn dispatch_events(mut receiver: Receiver, ban_service: Arc>) { + let shutdown_signal = tokio::signal::ctrl_c(); + tokio::pin!(shutdown_signal); + + loop { + tokio::select! { + biased; + + _ = &mut shutdown_signal => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Received Ctrl+C, shutting down UDP tracker server event listener (banning)"); + break; + } + + result = receiver.recv() => { + match result { + Ok(event) => handle_event(event, &ban_service, CurrentClock::now()).await, + Err(e) => { + match e { + RecvError::Closed => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp server receiver (banning) closed."); + break; + } + RecvError::Lagged(n) => { + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp server receiver (banning) lagged by {} events.", n); + } + } + } + } + } + } + } +} diff --git a/packages/udp-tracker-server/src/banning/event/mod.rs b/packages/udp-tracker-server/src/banning/event/mod.rs new file mode 100644 index 000000000..dae683398 --- /dev/null +++ b/packages/udp-tracker-server/src/banning/event/mod.rs @@ -0,0 +1,2 @@ +pub mod handler; +pub mod listener; diff --git a/packages/udp-tracker-server/src/banning/mod.rs b/packages/udp-tracker-server/src/banning/mod.rs new file mode 100644 index 000000000..53f112654 --- /dev/null +++ b/packages/udp-tracker-server/src/banning/mod.rs @@ -0,0 +1 @@ +pub mod event; diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index f48b3a7c1..6c03cc75f 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -1,13 +1,11 @@ use std::net::SocketAddr; use std::sync::Arc; -use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use tokio::task::JoinHandle; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; -use torrust_tracker_primitives::peer; use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use crate::container::UdpTrackerServerContainer; @@ -25,22 +23,8 @@ where pub registar: Registar, pub server: Server, pub udp_core_event_listener_job: Option>, - pub udp_server_event_listener_job: Option>, -} - -impl Environment -where - S: std::fmt::Debug + std::fmt::Display, -{ - /// Add a torrent to the tracker - #[allow(dead_code)] - pub async fn add_torrent(&self, info_hash: &InfoHash, peer: &peer::Peer) { - self.container - .tracker_core_container - .in_memory_torrent_repository - .handle_announcement(info_hash, peer, None) - .await; - } + pub udp_server_stats_event_listener_job: Option>, + pub udp_server_banning_event_listener_job: Option>, } impl Environment { @@ -60,7 +44,8 @@ impl Environment { registar: Registar::default(), server, udp_core_event_listener_job: None, - udp_server_event_listener_job: None, + udp_server_stats_event_listener_job: None, + udp_server_banning_event_listener_job: None, } } @@ -78,10 +63,15 @@ impl Environment { &self.container.udp_tracker_core_container.stats_repository, )); - // Start the UDP tracker server event listener - let udp_server_event_listener_job = Some(crate::statistics::event::listener::run_event_listener( + // Start the UDP tracker server event listener (statistics) + let udp_server_stats_event_listener_job = Some(crate::statistics::event::listener::run_event_listener( self.container.udp_tracker_server_container.event_bus.receiver(), &self.container.udp_tracker_server_container.stats_repository, + )); + + // Start the UDP tracker server event listener (banning) + let udp_server_banning_event_listener_job = Some(crate::banning::event::listener::run_event_listener( + self.container.udp_tracker_server_container.event_bus.receiver(), &self.container.udp_tracker_core_container.ban_service, )); @@ -102,7 +92,8 @@ impl Environment { registar: self.registar.clone(), server, udp_core_event_listener_job, - udp_server_event_listener_job, + udp_server_stats_event_listener_job, + udp_server_banning_event_listener_job, } } } @@ -131,11 +122,18 @@ impl Environment { udp_core_event_listener_job.abort(); } - // Stop the UDP tracker server event listener - if let Some(udp_server_event_listener_job) = self.udp_server_event_listener_job { + // Stop the UDP tracker server event listener (statistics) + if let Some(udp_server_stats_event_listener_job) = self.udp_server_stats_event_listener_job { + // todo: send a message to the event listener to stop and wait for + // it to finish + udp_server_stats_event_listener_job.abort(); + } + + // Stop the UDP tracker server event listener (banning) + if let Some(udp_server_banning_event_listener_job) = self.udp_server_banning_event_listener_job { // todo: send a message to the event listener to stop and wait for // it to finish - udp_server_event_listener_job.abort(); + udp_server_banning_event_listener_job.abort(); } // Stop the UDP tracker server @@ -149,7 +147,8 @@ impl Environment { registar: Registar::default(), server, udp_core_event_listener_job: None, - udp_server_event_listener_job: None, + udp_server_stats_event_listener_job: None, + udp_server_banning_event_listener_job: None, } } diff --git a/packages/udp-tracker-server/src/lib.rs b/packages/udp-tracker-server/src/lib.rs index 996c41917..58a3830e1 100644 --- a/packages/udp-tracker-server/src/lib.rs +++ b/packages/udp-tracker-server/src/lib.rs @@ -634,6 +634,7 @@ //! documentation by [Arvid Norberg](https://github.com/arvidn) was very //! supportive in the development of this documentation. Some descriptions were //! taken from the [libtorrent](https://www.rasterbar.com/products/libtorrent/udp_tracker_protocol.html). +pub mod banning; pub mod container; pub mod environment; pub mod error; diff --git a/packages/udp-tracker-server/src/statistics/event/handler/error.rs b/packages/udp-tracker-server/src/statistics/event/handler/error.rs index 7327386a3..7bde032fe 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/error.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/error.rs @@ -1,8 +1,4 @@ -use std::sync::Arc; - use aquatic_udp_protocol::PeerClient; -use bittorrent_udp_tracker_core::services::banning::BanService; -use tokio::sync::RwLock; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::{label_name, metric_name}; use torrust_tracker_primitives::DurationSinceUnixEpoch; @@ -16,16 +12,9 @@ pub async fn handle_event( opt_udp_request_kind: Option, error_kind: ErrorKind, repository: &Repository, - ban_service: &Arc>, now: DurationSinceUnixEpoch, ) { - if let ErrorKind::ConnectionCookie(_msg) = error_kind.clone() { - let mut ban_service = ban_service.write().await; - ban_service.increase_counter(&connection_context.client_socket_addr().ip()); - } - update_global_fixed_metrics(&connection_context, repository).await; - update_extendable_metrics(&connection_context, opt_udp_request_kind, error_kind, repository, now).await; } @@ -126,9 +115,7 @@ fn extract_name_and_version(peer_client: &PeerClient) -> (String, String) { #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; - use bittorrent_udp_tracker_core::services::banning::BanService; use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -141,7 +128,6 @@ mod tests { #[tokio::test] async fn should_increase_the_udp4_errors_counter_when_it_receives_a_udp4_error_event() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpError { @@ -157,7 +143,6 @@ mod tests { error: ErrorKind::RequestParse("Invalid request format".to_string()), }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; diff --git a/packages/udp-tracker-server/src/statistics/event/handler/mod.rs b/packages/udp-tracker-server/src/statistics/event/handler/mod.rs index c8ac864a3..9e7f5cd47 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/mod.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/mod.rs @@ -5,21 +5,12 @@ mod request_banned; mod request_received; mod response_sent; -use std::sync::Arc; - -use bittorrent_udp_tracker_core::services::banning::BanService; -use tokio::sync::RwLock; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::Event; use crate::statistics::repository::Repository; -pub async fn handle_event( - event: Event, - stats_repository: &Repository, - ban_service: &Arc>, - now: DurationSinceUnixEpoch, -) { +pub async fn handle_event(event: Event, stats_repository: &Repository, now: DurationSinceUnixEpoch) { match event { Event::UdpRequestAborted { context } => { request_aborted::handle_event(context, stats_repository, now).await; @@ -41,7 +32,7 @@ pub async fn handle_event( response_sent::handle_event(context, kind, req_processing_time, stats_repository, now).await; } Event::UdpError { context, kind, error } => { - error::handle_event(context, kind, error, stats_repository, ban_service, now).await; + error::handle_event(context, kind, error, stats_repository, now).await; } } diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs index 270ec2a45..fc701df75 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs @@ -27,9 +27,7 @@ pub async fn handle_event(context: ConnectionContext, stats_repository: &Reposit #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; - use bittorrent_udp_tracker_core::services::banning::BanService; use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -41,7 +39,6 @@ mod tests { #[tokio::test] async fn should_increase_the_number_of_aborted_requests_when_it_receives_a_udp_request_aborted_event() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAborted { @@ -55,7 +52,6 @@ mod tests { ), }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; @@ -68,7 +64,6 @@ mod tests { #[tokio::test] async fn should_increase_the_udp_abort_counter_when_it_receives_a_udp_abort_event() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAborted { @@ -82,7 +77,6 @@ mod tests { ), }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs index 0007a18b0..b296f8ec9 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs @@ -55,9 +55,7 @@ pub async fn handle_event( #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use std::sync::Arc; - use bittorrent_udp_tracker_core::services::banning::BanService; use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -70,7 +68,6 @@ mod tests { #[tokio::test] async fn should_increase_the_udp4_connect_requests_counter_when_it_receives_a_udp4_request_event_of_connect_kind() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAccepted { @@ -85,7 +82,6 @@ mod tests { kind: crate::event::UdpRequestKind::Connect, }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; @@ -98,7 +94,6 @@ mod tests { #[tokio::test] async fn should_increase_the_udp4_announce_requests_counter_when_it_receives_a_udp4_request_event_of_announce_kind() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAccepted { @@ -115,7 +110,6 @@ mod tests { }, }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; @@ -128,7 +122,6 @@ mod tests { #[tokio::test] async fn should_increase_the_udp4_scrape_requests_counter_when_it_receives_a_udp4_request_event_of_scrape_kind() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAccepted { @@ -143,7 +136,6 @@ mod tests { kind: crate::event::UdpRequestKind::Scrape, }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; @@ -156,7 +148,6 @@ mod tests { #[tokio::test] async fn should_increase_the_udp6_connect_requests_counter_when_it_receives_a_udp6_request_event_of_connect_kind() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAccepted { @@ -171,7 +162,6 @@ mod tests { kind: crate::event::UdpRequestKind::Connect, }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; @@ -184,7 +174,6 @@ mod tests { #[tokio::test] async fn should_increase_the_udp6_announce_requests_counter_when_it_receives_a_udp6_request_event_of_announce_kind() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAccepted { @@ -201,7 +190,6 @@ mod tests { }, }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; @@ -214,7 +202,6 @@ mod tests { #[tokio::test] async fn should_increase_the_udp6_scrape_requests_counter_when_it_receives_a_udp6_request_event_of_scrape_kind() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestAccepted { @@ -229,7 +216,6 @@ mod tests { kind: crate::event::UdpRequestKind::Scrape, }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs index 74641574a..ce6e179a3 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs @@ -27,9 +27,7 @@ pub async fn handle_event(context: ConnectionContext, stats_repository: &Reposit #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; - use bittorrent_udp_tracker_core::services::banning::BanService; use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -41,7 +39,6 @@ mod tests { #[tokio::test] async fn should_increase_the_number_of_banned_requests_when_it_receives_a_udp_request_banned_event() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestBanned { @@ -55,7 +52,6 @@ mod tests { ), }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; @@ -68,7 +64,6 @@ mod tests { #[tokio::test] async fn should_increase_the_udp_ban_counter_when_it_receives_a_udp_banned_event() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestBanned { @@ -82,7 +77,6 @@ mod tests { ), }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs index 8333258c2..89f306f6a 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs @@ -34,9 +34,7 @@ pub async fn handle_event(context: ConnectionContext, stats_repository: &Reposit #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use std::sync::Arc; - use bittorrent_udp_tracker_core::services::banning::BanService; use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -48,7 +46,6 @@ mod tests { #[tokio::test] async fn should_increase_the_number_of_incoming_requests_when_it_receives_a_udp4_incoming_request_event() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpRequestReceived { @@ -62,7 +59,6 @@ mod tests { ), }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; diff --git a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs index 0038ac5f9..4e167a10e 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs @@ -107,9 +107,7 @@ pub async fn handle_event( #[cfg(test)] mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use std::sync::Arc; - use bittorrent_udp_tracker_core::services::banning::BanService; use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; @@ -122,7 +120,6 @@ mod tests { #[tokio::test] async fn should_increase_the_udp4_responses_counter_when_it_receives_a_udp4_response_event() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpResponseSent { @@ -142,7 +139,6 @@ mod tests { req_processing_time: std::time::Duration::from_secs(1), }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; @@ -155,7 +151,6 @@ mod tests { #[tokio::test] async fn should_increase_the_udp6_response_counter_when_it_receives_a_udp6_response_event() { let stats_repository = Repository::new(); - let ban_service = Arc::new(tokio::sync::RwLock::new(BanService::new(1))); handle_event( Event::UdpResponseSent { @@ -175,7 +170,6 @@ mod tests { req_processing_time: std::time::Duration::from_secs(1), }, &stats_repository, - &ban_service, CurrentClock::now(), ) .await; diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index e6c9a85ce..ae659c15e 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -1,8 +1,6 @@ use std::sync::Arc; -use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; -use tokio::sync::RwLock; use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; use torrust_tracker_events::receiver::RecvError; @@ -13,24 +11,19 @@ use crate::statistics::repository::Repository; use crate::CurrentClock; #[must_use] -pub fn run_event_listener( - receiver: Receiver, - repository: &Arc, - ban_service: &Arc>, -) -> JoinHandle<()> { +pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { let repository_clone = repository.clone(); - let ban_service_clone = ban_service.clone(); tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker server event listener"); tokio::spawn(async move { - dispatch_events(receiver, repository_clone, ban_service_clone).await; + dispatch_events(receiver, repository_clone).await; tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker server event listener finished"); }) } -async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc, ban_service: Arc>) { +async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { let shutdown_signal = tokio::signal::ctrl_c(); tokio::pin!(shutdown_signal); @@ -45,7 +38,7 @@ async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc { match result { - Ok(event) => handle_event(event, &stats_repository, &ban_service, CurrentClock::now()).await, + Ok(event) => handle_event(event, &stats_repository, CurrentClock::now()).await, Err(e) => { match e { RecvError::Closed => { diff --git a/src/app.rs b/src/app.rs index 5050c1dd1..58d758d7f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -75,7 +75,8 @@ async fn start_jobs(config: &Configuration, app_container: &Arc) - start_tracker_core_event_listener(config, app_container, &mut job_manager); start_http_core_event_listener(config, app_container, &mut job_manager); start_udp_core_event_listener(config, app_container, &mut job_manager); - start_udp_server_event_listener(config, app_container, &mut job_manager); + start_udp_server_stats_event_listener(config, app_container, &mut job_manager); + start_udp_server_banning_event_listener(app_container, &mut job_manager); start_the_udp_instances(config, app_container, &mut job_manager).await; start_the_http_instances(config, app_container, &mut job_manager).await; @@ -164,10 +165,21 @@ fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { +fn start_udp_server_stats_event_listener( + config: &Configuration, + app_container: &Arc, + job_manager: &mut JobManager, +) { job_manager.push_opt( - "udp_server_event_listener", - jobs::udp_tracker_server::start_event_listener(config, app_container), + "udp_server_stats_event_listener", + jobs::udp_tracker_server::start_stats_event_listener(config, app_container), + ); +} + +fn start_udp_server_banning_event_listener(app_container: &Arc, job_manager: &mut JobManager) { + job_manager.push( + "udp_server_banning_event_listener", + jobs::udp_tracker_server::start_banning_event_listener(app_container), ); } diff --git a/src/bootstrap/jobs/udp_tracker_server.rs b/src/bootstrap/jobs/udp_tracker_server.rs index 8a4c2a273..0910fdaf5 100644 --- a/src/bootstrap/jobs/udp_tracker_server.rs +++ b/src/bootstrap/jobs/udp_tracker_server.rs @@ -5,12 +5,11 @@ use torrust_tracker_configuration::Configuration; use crate::container::AppContainer; -pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { +pub fn start_stats_event_listener(config: &Configuration, app_container: &Arc) -> Option> { if config.core.tracker_usage_statistics { let job = torrust_udp_tracker_server::statistics::event::listener::run_event_listener( app_container.udp_tracker_server_container.event_bus.receiver(), &app_container.udp_tracker_server_container.stats_repository, - &app_container.udp_tracker_core_services.ban_service, ); Some(job) } else { @@ -18,3 +17,11 @@ pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> JoinHandle<()> { + torrust_udp_tracker_server::banning::event::listener::run_event_listener( + app_container.udp_tracker_server_container.event_bus.receiver(), + &app_container.udp_tracker_core_services.ban_service, + ) +} From f7b80ed937fd98e6c31f47e87fd005990bbf25a4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 10 Jun 2025 13:50:26 +0100 Subject: [PATCH 1201/1297] feat: [#1570] add new metric for banned IPs total --- .../src/banning/event/handler.rs | 30 ++++++++++++++++++- .../src/banning/event/listener.rs | 14 ++++++--- .../udp-tracker-server/src/environment.rs | 1 + .../udp-tracker-server/src/statistics/mod.rs | 7 +++++ src/bootstrap/jobs/udp_tracker_server.rs | 1 + 5 files changed, 48 insertions(+), 5 deletions(-) diff --git a/packages/udp-tracker-server/src/banning/event/handler.rs b/packages/udp-tracker-server/src/banning/event/handler.rs index 2d77d0979..4876323a8 100644 --- a/packages/udp-tracker-server/src/banning/event/handler.rs +++ b/packages/udp-tracker-server/src/banning/event/handler.rs @@ -2,11 +2,20 @@ use std::sync::Arc; use bittorrent_udp_tracker_core::services::banning::BanService; use tokio::sync::RwLock; +use torrust_tracker_metrics::label::LabelSet; +use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::{ErrorKind, Event}; +use crate::statistics::repository::Repository; +use crate::statistics::UDP_TRACKER_SERVER_IPS_BANNED_TOTAL; -pub async fn handle_event(event: Event, ban_service: &Arc>, _now: DurationSinceUnixEpoch) { +pub async fn handle_event( + event: Event, + ban_service: &Arc>, + repository: &Repository, + now: DurationSinceUnixEpoch, +) { if let Event::UdpError { context, kind: _, @@ -14,6 +23,25 @@ pub async fn handle_event(event: Event, ban_service: &Arc>, _ } = event { let mut ban_service = ban_service.write().await; + ban_service.increase_counter(&context.client_socket_addr().ip()); + + update_metric_for_banned_ips_total(repository, ban_service.get_banned_ips_total(), now).await; + } +} + +#[allow(clippy::cast_precision_loss)] +async fn update_metric_for_banned_ips_total(repository: &Repository, ips_banned_total: usize, now: DurationSinceUnixEpoch) { + match repository + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), + &LabelSet::default(), + ips_banned_total as f64, + now, + ) + .await + { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increase the counter: {}", err), } } diff --git a/packages/udp-tracker-server/src/banning/event/listener.rs b/packages/udp-tracker-server/src/banning/event/listener.rs index ee1a4366f..fee3395fa 100644 --- a/packages/udp-tracker-server/src/banning/event/listener.rs +++ b/packages/udp-tracker-server/src/banning/event/listener.rs @@ -9,22 +9,28 @@ use torrust_tracker_events::receiver::RecvError; use super::handler::handle_event; use crate::event::receiver::Receiver; +use crate::statistics::repository::Repository; use crate::CurrentClock; #[must_use] -pub fn run_event_listener(receiver: Receiver, ban_service: &Arc>) -> JoinHandle<()> { +pub fn run_event_listener( + receiver: Receiver, + ban_service: &Arc>, + repository: &Arc, +) -> JoinHandle<()> { let ban_service_clone = ban_service.clone(); + let repository_clone = repository.clone(); tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker server event listener (banning)"); tokio::spawn(async move { - dispatch_events(receiver, ban_service_clone).await; + dispatch_events(receiver, ban_service_clone, repository_clone).await; tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker server event listener (banning) finished"); }) } -async fn dispatch_events(mut receiver: Receiver, ban_service: Arc>) { +async fn dispatch_events(mut receiver: Receiver, ban_service: Arc>, repository: Arc) { let shutdown_signal = tokio::signal::ctrl_c(); tokio::pin!(shutdown_signal); @@ -39,7 +45,7 @@ async fn dispatch_events(mut receiver: Receiver, ban_service: Arc { match result { - Ok(event) => handle_event(event, &ban_service, CurrentClock::now()).await, + Ok(event) => handle_event(event, &ban_service, &repository, CurrentClock::now()).await, Err(e) => { match e { RecvError::Closed => { diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 6c03cc75f..61b1cba63 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -73,6 +73,7 @@ impl Environment { let udp_server_banning_event_listener_job = Some(crate::banning::event::listener::run_event_listener( self.container.udp_tracker_server_container.event_bus.receiver(), &self.container.udp_tracker_core_container.ban_service, + &self.container.udp_tracker_server_container.stats_repository, )); // Start the UDP tracker server diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index a7da2dc63..ebb3df0bf 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -10,6 +10,7 @@ use torrust_tracker_metrics::unit::Unit; const UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL: &str = "udp_tracker_server_requests_aborted_total"; const UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL: &str = "udp_tracker_server_requests_banned_total"; +pub(crate) const UDP_TRACKER_SERVER_IPS_BANNED_TOTAL: &str = "udp_tracker_server_ips_banned_total"; const UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL: &str = "udp_tracker_server_connection_id_errors_total"; const UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL: &str = "udp_tracker_server_requests_received_total"; const UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL: &str = "udp_tracker_server_requests_accepted_total"; @@ -33,6 +34,12 @@ pub fn describe_metrics() -> Metrics { Some(MetricDescription::new("Total number of UDP requests banned")), ); + metrics.metric_collection.describe_gauge( + &metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new("Total number of IPs banned from UDP requests")), + ); + metrics.metric_collection.describe_counter( &metric_name!(UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL), Some(Unit::Count), diff --git a/src/bootstrap/jobs/udp_tracker_server.rs b/src/bootstrap/jobs/udp_tracker_server.rs index 0910fdaf5..3e8a7aaa8 100644 --- a/src/bootstrap/jobs/udp_tracker_server.rs +++ b/src/bootstrap/jobs/udp_tracker_server.rs @@ -23,5 +23,6 @@ pub fn start_banning_event_listener(app_container: &Arc) -> JoinHa torrust_udp_tracker_server::banning::event::listener::run_event_listener( app_container.udp_tracker_server_container.event_bus.receiver(), &app_container.udp_tracker_core_services.ban_service, + &app_container.udp_tracker_server_container.stats_repository, ) } From 12d69179a8c8a2d240d7860ffe2e84afc4082d62 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 10 Jun 2025 15:42:55 +0100 Subject: [PATCH 1202/1297] feat: [#1571] increase broadcaster channel capacity to 65536 --- packages/events/src/broadcaster.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/events/src/broadcaster.rs b/packages/events/src/broadcaster.rs index d0a511cd4..79c83df8a 100644 --- a/packages/events/src/broadcaster.rs +++ b/packages/events/src/broadcaster.rs @@ -5,7 +5,7 @@ use tokio::sync::broadcast::{self}; use crate::receiver::{Receiver, RecvError}; use crate::sender::{SendError, Sender}; -const CHANNEL_CAPACITY: usize = 32768; +const CHANNEL_CAPACITY: usize = 65536; /// An event sender and receiver implementation using a broadcast channel. #[derive(Clone, Debug)] From 02433cbe809d72e066b1bd3c3461e4349a201c67 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 10 Jun 2025 18:56:26 +0100 Subject: [PATCH 1203/1297] fix: [#1569] Prometheus txt export format. Only one HELP and TYPE header per metric Current format: ``` # HELP udp_tracker_server_connection_id_errors_total Total number of requests with connection ID errors # TYPE udp_tracker_server_connection_id_errors_total counter udp_tracker_server_connection_id_errors_total{client_software_name="Other (BC)",client_software_version="0087"} 4 # HELP udp_tracker_server_connection_id_errors_total Total number of requests with connection ID errors # TYPE udp_tracker_server_connection_id_errors_total counter udp_tracker_server_connection_id_errors_total{client_software_name="Other (FD66)",client_software_version=""} 1 # HELP udp_tracker_server_connection_id_errors_total Total number of requests with connection ID errors # TYPE udp_tracker_server_connection_id_errors_total counter udp_tracker_server_connection_id_errors_total{client_software_name="Other (SP)",client_software_version="3605"} 631 # HELP udp_tracker_server_connection_id_errors_total Total number of requests with connection ID errors # TYPE udp_tracker_server_connection_id_errors_total counter udp_tracker_server_connection_id_errors_total{client_software_name="Other (TIX0325)",client_software_version=""} 14 # HELP udp_tracker_server_connection_id_errors_total Total number of requests with connection ID errors # TYPE udp_tracker_server_connection_id_errors_total counter udp_tracker_server_connection_id_errors_total{client_software_name="Other (BC)",client_software_version="0202"} 6754 # HELP udp_tracker_server_connection_id_errors_total Total number of requests with connection ID errors # TYPE udp_tracker_server_connection_id_errors_total counter udp_tracker_server_connection_id_errors_total{client_software_name="Other (XF)",client_software_version="9400"} 1 # HELP udp_tracker_server_connection_id_errors_total Total number of requests with connection ID errors # TYPE udp_tracker_server_connection_id_errors_total counter udp_tracker_server_connection_id_errors_total{client_software_name="Other (BC)",client_software_version="0090"} 7 # HELP udp_tracker_server_connection_id_errors_total Total number of requests with connection ID errors # TYPE udp_tracker_server_connection_id_errors_total counter udp_tracker_server_connection_id_errors_total{client_software_name="Transmission",client_software_version="2.32"} 1 # HELP udp_tracker_server_connection_id_errors_total Total number of requests with connection ID errors # TYPE udp_tracker_server_connection_id_errors_total counter udp_tracker_server_connection_id_errors_total{client_software_name="Other (61-b39e)",client_software_version=""} 1 ``` Expected format: ``` # HELP udp_tracker_server_connection_id_errors_total Total number of requests with connection ID errors # TYPE udp_tracker_server_connection_id_errors_total counter udp_tracker_server_connection_id_errors_total{client_software_name="Other (BC)",client_software_version="0087"} 4 udp_tracker_server_connection_id_errors_total{client_software_name="Other (FD66)",client_software_version=""} 1 udp_tracker_server_connection_id_errors_total{client_software_name="Other (SP)",client_software_version="3605"} 631 udp_tracker_server_connection_id_errors_total{client_software_name="Other (TIX0325)",client_software_version=""} 14 udp_tracker_server_connection_id_errors_total{client_software_name="Other (BC)",client_software_version="0202"} 6754 udp_tracker_server_connection_id_errors_total{client_software_name="Other (XF)",client_software_version="9400"} 1 udp_tracker_server_connection_id_errors_total{client_software_name="Other (BC)",client_software_version="0090"} 7 udp_tracker_server_connection_id_errors_total{client_software_name="Transmission",client_software_version="2.32"} 1 udp_tracker_server_connection_id_errors_total{client_software_name="Other (61-b39e)",client_software_version=""} 1 ``` A line break after each metric has also been added to improve readability. --- packages/metrics/src/label/set.rs | 8 ++ packages/metrics/src/lib.rs | 6 +- packages/metrics/src/metric/mod.rs | 102 ++++++---------------- packages/metrics/src/metric_collection.rs | 31 ++++--- packages/metrics/src/sample.rs | 6 +- packages/metrics/src/sample_collection.rs | 6 +- 6 files changed, 64 insertions(+), 95 deletions(-) diff --git a/packages/metrics/src/label/set.rs b/packages/metrics/src/label/set.rs index 1c2c3e27e..cab457f42 100644 --- a/packages/metrics/src/label/set.rs +++ b/packages/metrics/src/label/set.rs @@ -16,6 +16,10 @@ impl LabelSet { pub fn upsert(&mut self, key: LabelName, value: LabelValue) { self.items.insert(key, value); } + + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } } impl Display for LabelSet { @@ -157,6 +161,10 @@ impl<'de> Deserialize<'de> for LabelSet { impl PrometheusSerializable for LabelSet { fn to_prometheus(&self) -> String { + if self.is_empty() { + return String::new(); + } + let items = self.items.iter().fold(String::new(), |mut output, label_pair| { if !output.is_empty() { output.push(','); diff --git a/packages/metrics/src/lib.rs b/packages/metrics/src/lib.rs index 95d70bf6c..997cd3c8c 100644 --- a/packages/metrics/src/lib.rs +++ b/packages/metrics/src/lib.rs @@ -12,12 +12,12 @@ pub const METRICS_TARGET: &str = "METRICS"; #[cfg(test)] mod tests { - /// It removes leading and trailing whitespace from each line, and empty lines. + /// It removes leading and trailing whitespace from each line. pub fn format_prometheus_output(output: &str) -> String { output .lines() - .map(str::trim) - .filter(|line| !line.is_empty()) + .map(str::trim_start) + .map(str::trim_end) .collect::>() .join("\n") } diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index 6f254023f..df743c519 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -103,19 +103,6 @@ impl Metric { } } -/// `PrometheusMetricSample` is a wrapper around types that provides methods to -/// convert the metric and its measurement into a Prometheus-compatible format. -/// -/// In Prometheus, a metric is a time series that consists of a name, a set of -/// labels, and a value. The sample value needs data from the `Metric` and -/// `Measurement` structs, as well as the `LabelSet` that defines the labels for -/// the metric. -struct PrometheusMetricSample<'a, T> { - metric: &'a Metric, - measurement: &'a Measurement, - label_set: &'a LabelSet, -} - enum PrometheusType { Counter, Gauge, @@ -130,91 +117,58 @@ impl PrometheusSerializable for PrometheusType { } } -impl PrometheusMetricSample<'_, T> { - fn to_prometheus(&self, prometheus_type: &PrometheusType) -> String { - format!( - // Format: - // # HELP - // # TYPE - // {label_set} - "{}{}{}", - self.help_line(), - self.type_line(prometheus_type), - self.metric_line() - ) - } - - fn help_line(&self) -> String { - if let Some(description) = &self.metric.opt_description { - format!( - // Format: # HELP - "# HELP {} {}\n", - self.metric.name().to_prometheus(), - description.to_prometheus() - ) +impl Metric { + #[must_use] + fn prometheus_help_line(&self) -> String { + if let Some(description) = &self.opt_description { + format!("# HELP {} {}", self.name.to_prometheus(), description.to_prometheus()) } else { String::new() } } - fn type_line(&self, kind: &PrometheusType) -> String { - format!("# TYPE {} {}\n", self.metric.name().to_prometheus(), kind.to_prometheus()) + #[must_use] + fn prometheus_type_line(&self, prometheus_type: &PrometheusType) -> String { + format!("# TYPE {} {}", self.name.to_prometheus(), prometheus_type.to_prometheus()) } - fn metric_line(&self) -> String { + #[must_use] + fn prometheus_sample_line(&self, label_set: &LabelSet, measurement: &Measurement) -> String { format!( - // Format: {label_set} "{}{} {}", - self.metric.name.to_prometheus(), - self.label_set.to_prometheus(), - self.measurement.value().to_prometheus() + self.name.to_prometheus(), + label_set.to_prometheus(), + measurement.to_prometheus() ) } -} -impl<'a> PrometheusMetricSample<'a, Counter> { - pub fn new(metric: &'a Metric, measurement: &'a Measurement, label_set: &'a LabelSet) -> Self { - Self { - metric, - measurement, - label_set, - } + #[must_use] + fn prometheus_samples(&self) -> String { + self.sample_collection + .iter() + .map(|(label_set, measurement)| self.prometheus_sample_line(label_set, measurement)) + .collect::>() + .join("\n") } -} -impl<'a> PrometheusMetricSample<'a, Gauge> { - pub fn new(metric: &'a Metric, measurement: &'a Measurement, label_set: &'a LabelSet) -> Self { - Self { - metric, - measurement, - label_set, - } + fn to_prometheus(&self, prometheus_type: &PrometheusType) -> String { + let help_line = self.prometheus_help_line(); + let type_line = self.prometheus_type_line(prometheus_type); + let samples = self.prometheus_samples(); + + format!("{help_line}\n{type_line}\n{samples}") } } impl PrometheusSerializable for Metric { fn to_prometheus(&self) -> String { - let samples: Vec = self - .sample_collection - .iter() - .map(|(label_set, measurement)| { - PrometheusMetricSample::::new(self, measurement, label_set).to_prometheus(&PrometheusType::Counter) - }) - .collect(); - samples.join("\n") + self.to_prometheus(&PrometheusType::Counter) } } impl PrometheusSerializable for Metric { fn to_prometheus(&self) -> String { - let samples: Vec = self - .sample_collection - .iter() - .map(|(label_set, measurement)| { - PrometheusMetricSample::::new(self, measurement, label_set).to_prometheus(&PrometheusType::Gauge) - }) - .collect(); - samples.join("\n") + self.to_prometheus(&PrometheusType::Gauge) } } diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection.rs index c53d02bcf..ff932caae 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection.rs @@ -322,7 +322,7 @@ impl PrometheusSerializable for MetricCollection { .map(Metric::::to_prometheus), ) .collect::>() - .join("\n") + .join("\n\n") } } @@ -629,14 +629,14 @@ mod tests { fn prometheus() -> String { format_prometheus_output( - r#" - # HELP http_tracker_core_announce_requests_received_total The number of announce requests received. - # TYPE http_tracker_core_announce_requests_received_total counter - http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 - # HELP udp_tracker_server_performance_avg_announce_processing_time_ns The average announce processing time in nanoseconds. - # TYPE udp_tracker_server_performance_avg_announce_processing_time_ns gauge - udp_tracker_server_performance_avg_announce_processing_time_ns{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 - "#, + r#"# HELP http_tracker_core_announce_requests_received_total The number of announce requests received. +# TYPE http_tracker_core_announce_requests_received_total counter +http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 + +# HELP udp_tracker_server_performance_avg_announce_processing_time_ns The average announce processing time in nanoseconds. +# TYPE udp_tracker_server_performance_avg_announce_processing_time_ns gauge +udp_tracker_server_performance_avg_announce_processing_time_ns{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 +"#, ) } } @@ -750,7 +750,7 @@ mod tests { MetricKindCollection::new(vec![Metric::new( metric_name!("http_tracker_core_announce_requests_received_total"), None, - None, + Some(MetricDescription::new("The number of announce requests received.")), SampleCollection::new(vec![ Sample::new(Counter::new(1), time, label_set_1.clone()), Sample::new(Counter::new(2), time, label_set_2.clone()), @@ -765,12 +765,11 @@ mod tests { let prometheus_output = metric_collection.to_prometheus(); let expected_prometheus_output = format_prometheus_output( - r#" - # TYPE http_tracker_core_announce_requests_received_total counter - http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7171",server_binding_protocol="http"} 2 - # TYPE http_tracker_core_announce_requests_received_total counter - http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 - "#, + r#"# HELP http_tracker_core_announce_requests_received_total The number of announce requests received. +# TYPE http_tracker_core_announce_requests_received_total counter +http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7070",server_binding_protocol="http"} 1 +http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",server_binding_port="7171",server_binding_protocol="http"} 2 +"#, ); // code-review: samples are not serialized in the same order as they are created. diff --git a/packages/metrics/src/sample.rs b/packages/metrics/src/sample.rs index ad4dff00e..b9cd6c312 100644 --- a/packages/metrics/src/sample.rs +++ b/packages/metrics/src/sample.rs @@ -50,7 +50,11 @@ impl Sample { impl PrometheusSerializable for Sample { fn to_prometheus(&self) -> String { - format!("{} {}", self.label_set.to_prometheus(), self.measurement.to_prometheus()) + if self.label_set.is_empty() { + format!(" {}", self.measurement.to_prometheus()) + } else { + format!("{} {}", self.label_set.to_prometheus(), self.measurement.to_prometheus()) + } } } diff --git a/packages/metrics/src/sample_collection.rs b/packages/metrics/src/sample_collection.rs index a87aacb63..ef88b27dd 100644 --- a/packages/metrics/src/sample_collection.rs +++ b/packages/metrics/src/sample_collection.rs @@ -155,7 +155,11 @@ impl PrometheusSerializable for SampleCollection { let mut output = String::new(); for (label_set, sample_data) in &self.samples { - let _ = write!(output, "{} {}", label_set.to_prometheus(), sample_data.to_prometheus()); + if label_set.is_empty() { + let _ = write!(output, "{}", sample_data.to_prometheus()); + } else { + let _ = write!(output, "{} {}", label_set.to_prometheus(), sample_data.to_prometheus()); + } } output From 9b254ce7082899a6995760f7403fb6d7efbad324 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 10 Jun 2025 21:40:12 +0100 Subject: [PATCH 1204/1297] chore(deps): update dependencies ``` cargo update Updating crates.io index Locking 41 packages to latest compatible versions Updating adler2 v2.0.0 -> v2.0.1 Updating anstream v0.6.18 -> v0.6.19 Updating anstyle v1.0.10 -> v1.0.11 Updating anstyle-parse v0.2.6 -> v0.2.7 Updating anstyle-query v1.1.2 -> v1.1.3 Updating anstyle-wincon v3.0.8 -> v3.0.9 Updating async-compression v0.4.23 -> v0.4.24 Updating bindgen v0.71.1 -> v0.72.0 Updating bumpalo v3.17.0 -> v3.18.1 Updating bytemuck v1.23.0 -> v1.23.1 Updating camino v1.1.9 -> v1.1.10 Updating cc v1.2.25 -> v1.2.26 Updating cfg-if v1.0.0 -> v1.0.1 Updating clap v4.5.39 -> v4.5.40 Updating clap_builder v4.5.39 -> v4.5.40 Updating clap_derive v4.5.32 -> v4.5.40 Updating clap_lex v0.7.4 -> v0.7.5 Updating colorchoice v1.0.3 -> v1.0.4 Updating flate2 v1.1.1 -> v1.1.2 Updating fs-err v3.1.0 -> v3.1.1 Updating hashbrown v0.15.3 -> v0.15.4 Updating hyper-rustls v0.27.6 -> v0.27.7 Updating hyper-util v0.1.13 -> v0.1.14 Updating miniz_oxide v0.8.8 -> v0.8.9 Updating portable-atomic v1.11.0 -> v1.11.1 Updating reqwest v0.12.18 -> v0.12.20 Updating rustc-demangle v0.1.24 -> v0.1.25 Updating serde_spanned v0.6.8 -> v0.6.9 Updating smallvec v1.15.0 -> v1.15.1 Updating syn v2.0.101 -> v2.0.102 Updating toml v0.8.22 -> v0.8.23 Updating toml_datetime v0.6.9 -> v0.6.11 Updating toml_edit v0.22.26 -> v0.22.27 Updating toml_write v0.1.1 -> v0.1.2 Updating tower-http v0.6.5 -> v0.6.6 Updating tracing-attributes v0.1.28 -> v0.1.29 Updating tracing-core v0.1.33 -> v0.1.34 Updating unicode-width v0.2.0 -> v0.2.1 Updating wasi v0.11.0+wasi-snapshot-preview1 -> v0.11.1+wasi-snapshot-preview1 Updating windows-registry v0.4.0 -> v0.5.2 Removing windows-strings v0.3.1 Updating winnow v0.7.10 -> v0.7.11 ``` --- Cargo.lock | 277 +++++++++++++++++++++++++---------------------------- 1 file changed, 133 insertions(+), 144 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index feb749d3f..269f7a3a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13,9 +13,9 @@ dependencies = [ [[package]] name = "adler2" -version = "2.0.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "ahash" @@ -81,9 +81,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.18" +version = "0.6.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" +checksum = "301af1932e46185686725e0fad2f8f2aa7da69dd70bf6ecc44d6b703844a3933" dependencies = [ "anstyle", "anstyle-parse", @@ -96,33 +96,33 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" +checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" [[package]] name = "anstyle-parse" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" +checksum = "6c8bdeb6047d8983be085bab0ba1472e6dc604e7041dbf6fcd5e71523014fae9" dependencies = [ "windows-sys 0.59.0", ] [[package]] name = "anstyle-wincon" -version = "3.0.8" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6680de5231bd6ee4c6191b8a1325daa282b415391ec9d3a37bd34f2060dc73fa" +checksum = "403f75924867bb1033c59fbf0797484329750cfbe3c4325cd33127941fabc882" dependencies = [ "anstyle", "once_cell_polyfill", @@ -217,9 +217,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.23" +version = "0.4.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b37fc50485c4f3f736a4fb14199f6d5f5ba008d7f28fe710306c92780f004c07" +checksum = "d615619615a650c571269c00dca41db04b9210037fa76ed8239f70404ab56985" dependencies = [ "brotli", "flate2", @@ -332,7 +332,7 @@ checksum = "e539d3fca749fcee5236ab05e93a52867dd549cc157c8cb7f99595f3cedffdb5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -455,7 +455,7 @@ checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -537,9 +537,9 @@ checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" [[package]] name = "bindgen" -version = "0.71.1" +version = "0.72.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3" +checksum = "4f72209734318d0b619a5e0f5129918b848c416e122a3c4ce054e03cb87b726f" dependencies = [ "bitflags 2.9.1", "cexpr", @@ -550,7 +550,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -848,7 +848,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -889,9 +889,9 @@ checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" [[package]] name = "bumpalo" -version = "3.17.0" +version = "3.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" +checksum = "793db76d6187cd04dff33004d8e6c9cc4e05cd330500379d2394209271b4aeee" [[package]] name = "bytecheck" @@ -917,9 +917,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.23.0" +version = "1.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9134a6ef01ce4b366b50689c94f82c14bc72bc5d0386829828a2e2752ef7958c" +checksum = "5c76a5792e44e4abe34d3abf15636779261d45a7450612059293d1d2cfc63422" [[package]] name = "byteorder" @@ -935,9 +935,9 @@ checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" [[package]] name = "camino" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b96ec4966b5813e2c0507c1f86115c8c5abaadc3980879c3424042a02fd1ad3" +checksum = "0da45bc31171d8d6960122e222a67740df867c1dd53b4d51caa297084c185cab" dependencies = [ "serde", ] @@ -959,9 +959,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.25" +version = "1.2.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0fc897dc1e865cc67c0e05a836d9d3f1df3cbe442aa4a9473b18e12624a4951" +checksum = "956a5e21988b87f372569b66183b78babf23ebc2e744b733e4350a752c4dafac" dependencies = [ "jobserver", "libc", @@ -979,9 +979,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268" [[package]] name = "cfg_aliases" @@ -1052,9 +1052,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.39" +version = "4.5.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd60e63e9be68e5fb56422e397cf9baddded06dae1d2e523401542383bc72a9f" +checksum = "40b6887a1d8685cebccf115538db5c0efe625ccac9696ad45c409d96566e910f" dependencies = [ "clap_builder", "clap_derive", @@ -1062,9 +1062,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.39" +version = "4.5.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89cc6392a1f72bbeb820d71f32108f61fdaf18bc526e1d23954168a67759ef51" +checksum = "e0c66c08ce9f0c698cbce5c0279d0bb6ac936d8674174fe48f736533b964f59e" dependencies = [ "anstream", "anstyle", @@ -1074,21 +1074,21 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.32" +version = "4.5.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09176aae279615badda0765c0c0b3f6ed53f4709118af73cf4655d85d1530cd7" +checksum = "d2c7947ae4cc3d851207c1adb5b5e260ff0cca11446b1d6d1423788e442257ce" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] name = "clap_lex" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" +checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" [[package]] name = "cmake" @@ -1101,9 +1101,9 @@ dependencies = [ [[package]] name = "colorchoice" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" [[package]] name = "compact_str" @@ -1336,7 +1336,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -1347,7 +1347,7 @@ checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ "darling_core", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -1391,7 +1391,7 @@ checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", "unicode-xid", ] @@ -1403,7 +1403,7 @@ checksum = "ccfae181bab5ab6c5478b2ccb69e4c68a02f8c3ec72f6616bfec9dbc599d2ee0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -1430,7 +1430,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -1577,9 +1577,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.1.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ced92e76e966ca2fd84c8f7aa01a4aea65b0eb6648d72f7c8f3e2764a67fece" +checksum = "4a3d7db9596fecd151c5f638c0ee5d5bd487b6e0ea232e5dc96d5250f6f94b1d" dependencies = [ "crc32fast", "libz-sys", @@ -1677,7 +1677,7 @@ checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -1689,7 +1689,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -1701,14 +1701,14 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] name = "fs-err" -version = "3.1.0" +version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f89bda4c2a21204059a977ed3bfe746677dfd137b83c339e702b0ac91d482aa" +checksum = "88d7be93788013f265201256d58f04936a8079ad5dc898743aa20525f503b683" dependencies = [ "autocfg", "tokio", @@ -1789,7 +1789,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -1846,7 +1846,7 @@ checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi 0.11.1+wasi-snapshot-preview1", ] [[package]] @@ -1931,9 +1931,9 @@ checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" [[package]] name = "hashbrown" -version = "0.15.3" +version = "0.15.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84b26c544d002229e640969970a2e74021aadf6e2f96372b9c58eff97de08eb3" +checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5" dependencies = [ "allocator-api2", "equivalent", @@ -1946,7 +1946,7 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" dependencies = [ - "hashbrown 0.15.3", + "hashbrown 0.15.4", ] [[package]] @@ -2066,9 +2066,9 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.6" +version = "0.27.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03a01595e11bdcec50946522c32dde3fc6914743000a68b93000965f2f02406d" +checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" dependencies = [ "http", "hyper", @@ -2098,9 +2098,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.13" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1c293b6b3d21eca78250dc7dbebd6b9210ec5530e038cbfe0661b5c47ab06e8" +checksum = "dc2fdfdbff08affe55bb779f33b053aa1fe5dd5b54c257343c17edfa55711bdb" dependencies = [ "base64 0.22.1", "bytes", @@ -2292,7 +2292,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e" dependencies = [ "equivalent", - "hashbrown 0.15.3", + "hashbrown 0.15.4", "serde", ] @@ -2522,7 +2522,7 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" dependencies = [ - "hashbrown 0.15.3", + "hashbrown 0.15.4", ] [[package]] @@ -2564,7 +2564,7 @@ checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -2581,9 +2581,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be647b768db090acb35d5ec5db2b0e1f1de11133ca123b9eacf5137868f892a" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", ] @@ -2595,7 +2595,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c" dependencies = [ "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi 0.11.1+wasi-snapshot-preview1", "windows-sys 0.59.0", ] @@ -2622,7 +2622,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -2672,7 +2672,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", "termcolor", "thiserror 1.0.69", ] @@ -2877,7 +2877,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -2961,7 +2961,7 @@ dependencies = [ "regex", "regex-syntax", "structmeta", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -2984,7 +2984,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -3115,9 +3115,9 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.11.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e" +checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" [[package]] name = "portable-atomic-util" @@ -3216,7 +3216,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -3236,7 +3236,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", "version_check", "yansi", ] @@ -3468,9 +3468,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.18" +version = "0.12.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e98ff6b0dbbe4d5a37318f433d4fc82babd21631f194d370409ceb2e40b2f0b5" +checksum = "eabf4c97d9130e2bf606614eb937e86edac8292eaa6f422f995d7e8de1eb1813" dependencies = [ "base64 0.22.1", "bytes", @@ -3484,12 +3484,10 @@ dependencies = [ "hyper-rustls", "hyper-tls", "hyper-util", - "ipnet", "js-sys", "log", "mime", "native-tls", - "once_cell", "percent-encoding", "pin-project-lite", "rustls-pki-types", @@ -3588,7 +3586,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.101", + "syn 2.0.102", "unicode-ident", ] @@ -3624,9 +3622,9 @@ dependencies = [ [[package]] name = "rustc-demangle" -version = "0.1.24" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" +checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f" [[package]] name = "rustc-hash" @@ -3846,7 +3844,7 @@ checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -3893,14 +3891,14 @@ checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] name = "serde_spanned" -version = "0.6.8" +version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" dependencies = [ "serde", ] @@ -3944,7 +3942,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -4016,9 +4014,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.15.0" +version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8917285742e9f3e1683f0a9c4e6b57960b7314d0b08d30d1ecd426713ee2eee9" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] name = "socket2" @@ -4057,7 +4055,7 @@ dependencies = [ "proc-macro2", "quote", "structmeta-derive", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -4068,7 +4066,7 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -4121,9 +4119,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.101" +version = "2.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf" +checksum = "f6397daf94fa90f058bd0fd88429dd9e5738999cca8d701813c80723add80462" dependencies = [ "proc-macro2", "quote", @@ -4147,7 +4145,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -4268,7 +4266,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057" dependencies = [ "unicode-linebreak", - "unicode-width 0.2.0", + "unicode-width 0.2.1", ] [[package]] @@ -4297,7 +4295,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -4308,7 +4306,7 @@ checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -4412,7 +4410,7 @@ checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -4476,9 +4474,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.22" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05ae329d1f08c4d17a59bed7ff5b5a769d062e64a62d34a3261b219e62cd5aae" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" dependencies = [ "serde", "serde_spanned", @@ -4488,18 +4486,18 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.6.9" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3da5db5a963e24bc68be8b17b6fa82814bb22ee8660f192bb182771d498f09a3" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.22.26" +version = "0.22.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "310068873db2c5b3e7659d2cc35d21855dbafa50d1ce336397c666e3cb08137e" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ "indexmap 2.9.0", "serde", @@ -4511,9 +4509,9 @@ dependencies = [ [[package]] name = "toml_write" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfb942dfe1d8e29a7ee7fcbde5bd2b9a25fb89aa70caea2eba3bee836ff41076" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" [[package]] name = "torrust-axum-health-check-api-server" @@ -4943,9 +4941,9 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.5" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc2d9e086a412a451384326f521c8123a99a466b329941a9403696bff9b0da2" +checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2" dependencies = [ "async-compression", "bitflags 2.9.1", @@ -4991,20 +4989,20 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.28" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" +checksum = "1b1ffbcf9c6f6b99d386e7444eb608ba646ae452a36b39737deb9663b610f662" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] name = "tracing-core" -version = "0.1.33" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" +checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" dependencies = [ "once_cell", "valuable", @@ -5100,9 +5098,9 @@ checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "unicode-width" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" +checksum = "4a1a07cc7db3810833284e8d372ccdc6da29741639ecc70c9ec107df0fa6154c" [[package]] name = "unicode-xid" @@ -5197,9 +5195,9 @@ dependencies = [ [[package]] name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" +version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasi" @@ -5232,7 +5230,7 @@ dependencies = [ "log", "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", "wasm-bindgen-shared", ] @@ -5267,7 +5265,7 @@ checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -5332,7 +5330,7 @@ dependencies = [ "windows-interface", "windows-link", "windows-result", - "windows-strings 0.4.2", + "windows-strings", ] [[package]] @@ -5343,7 +5341,7 @@ checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -5354,7 +5352,7 @@ checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -5365,13 +5363,13 @@ checksum = "76840935b766e1b0a05c0066835fb9ec80071d4c09a16f6bd5f7e655e3c14c38" [[package]] name = "windows-registry" -version = "0.4.0" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4286ad90ddb45071efd1a66dfa43eb02dd0dfbae1545ad6cc3c51cf34d7e8ba3" +checksum = "b3bab093bdd303a1240bb99b8aba8ea8a69ee19d34c9e2ef9594e708a4878820" dependencies = [ + "windows-link", "windows-result", - "windows-strings 0.3.1", - "windows-targets 0.53.0", + "windows-strings", ] [[package]] @@ -5383,15 +5381,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-strings" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87fa48cc5d406560701792be122a10132491cff9d0aeb23583cc2dcafc847319" -dependencies = [ - "windows-link", -] - [[package]] name = "windows-strings" version = "0.4.2" @@ -5549,9 +5538,9 @@ checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" [[package]] name = "winnow" -version = "0.7.10" +version = "0.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06928c8748d81b05c9be96aad92e1b6ff01833332f281e8cfca3be4b35fc9ec" +checksum = "74c7b26e3480b707944fc872477815d29a8e429d2f93a1ce000f5fa84a15cbcd" dependencies = [ "memchr", ] @@ -5616,7 +5605,7 @@ checksum = "38da3c9736e16c5d3c8c597a9aaa5d1fa565d0532ae05e27c24aa62fb32c0ab6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", "synstructure", ] @@ -5647,7 +5636,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -5658,7 +5647,7 @@ checksum = "28a6e20d751156648aa063f3800b706ee209a32c0b4d9f24be3d980b01be55ef" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] @@ -5678,7 +5667,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", "synstructure", ] @@ -5718,7 +5707,7 @@ checksum = "5b96237efa0c878c64bd89c436f661be4e46b2f3eff1ebb976f7ef2321d2f58f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.101", + "syn 2.0.102", ] [[package]] From 7e722c06f17603c9d049692f49eca4e1693b7cf7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 10 Jun 2025 21:57:08 +0100 Subject: [PATCH 1205/1297] fix: clippy errors --- packages/axum-http-tracker-server/src/server.rs | 6 +++--- packages/axum-http-tracker-server/src/v1/routes.rs | 2 +- packages/axum-rest-tracker-api-server/src/routes.rs | 4 ++-- packages/axum-rest-tracker-api-server/src/server.rs | 4 ++-- .../torrent-repository-benchmarking/tests/repository/mod.rs | 4 +++- packages/udp-tracker-server/src/handlers/mod.rs | 2 +- 6 files changed, 12 insertions(+), 10 deletions(-) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 1775a3d72..ba0dd8c6e 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -47,7 +47,7 @@ impl Launcher { #[instrument(skip(self, http_tracker_container, tx_start, rx_halt))] fn start( &self, - http_tracker_container: Arc, + http_tracker_container: &Arc, tx_start: Sender, rx_halt: Receiver, ) -> BoxFuture<'static, ()> { @@ -69,7 +69,7 @@ impl Launcher { tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting on: {protocol}://{address}"); - let app = router(http_tracker_container, service_binding.clone()); + let app = router(http_tracker_container, &service_binding); let running = Box::pin(async { match tls { @@ -176,7 +176,7 @@ impl HttpServer { let launcher = self.state.launcher; let task = tokio::spawn(async move { - let server = launcher.start(http_tracker_container, tx_start, rx_halt); + let server = launcher.start(&http_tracker_container, tx_start, rx_halt); server.await; diff --git a/packages/axum-http-tracker-server/src/v1/routes.rs b/packages/axum-http-tracker-server/src/v1/routes.rs index 3fe467a0d..df395cd9a 100644 --- a/packages/axum-http-tracker-server/src/v1/routes.rs +++ b/packages/axum-http-tracker-server/src/v1/routes.rs @@ -31,7 +31,7 @@ use crate::HTTP_TRACKER_LOG_TARGET; /// > **NOTICE**: it's added a layer to get the client IP from the connection /// > info. The tracker could use the connection info to get the client IP. #[instrument(skip(http_tracker_container, server_service_binding))] -pub fn router(http_tracker_container: Arc, server_service_binding: ServiceBinding) -> Router { +pub fn router(http_tracker_container: &Arc, server_service_binding: &ServiceBinding) -> Router { let server_socket_addr = server_service_binding.bind_address(); Router::new() diff --git a/packages/axum-rest-tracker-api-server/src/routes.rs b/packages/axum-rest-tracker-api-server/src/routes.rs index c18451c89..78b7818d9 100644 --- a/packages/axum-rest-tracker-api-server/src/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/routes.rs @@ -36,7 +36,7 @@ use crate::API_LOG_TARGET; /// Add all API routes to the router. #[instrument(skip(http_api_container, access_tokens))] pub fn router( - http_api_container: Arc, + http_api_container: &Arc, access_tokens: Arc, server_socket_addr: SocketAddr, ) -> Router { @@ -44,7 +44,7 @@ pub fn router( let api_url_prefix = "/api"; - let router = v1::routes::add(api_url_prefix, router, &http_api_container); + let router = v1::routes::add(api_url_prefix, router, http_api_container); let state = State { access_tokens }; diff --git a/packages/axum-rest-tracker-api-server/src/server.rs b/packages/axum-rest-tracker-api-server/src/server.rs index 04c51d8fb..b358345fb 100644 --- a/packages/axum-rest-tracker-api-server/src/server.rs +++ b/packages/axum-rest-tracker-api-server/src/server.rs @@ -140,7 +140,7 @@ impl ApiServer { let task = tokio::spawn(async move { tracing::debug!(target: API_LOG_TARGET, "Starting with launcher in spawned task ..."); - let _task = launcher.start(http_api_container, access_tokens, tx_start, rx_halt).await; + let _task = launcher.start(&http_api_container, access_tokens, tx_start, rx_halt).await; tracing::debug!(target: API_LOG_TARGET, "Started with launcher in spawned task"); @@ -241,7 +241,7 @@ impl Launcher { #[instrument(skip(self, http_api_container, access_tokens, tx_start, rx_halt))] pub fn start( &self, - http_api_container: Arc, + http_api_container: &Arc, access_tokens: Arc, tx_start: Sender, rx_halt: Receiver, diff --git a/packages/torrent-repository-benchmarking/tests/repository/mod.rs b/packages/torrent-repository-benchmarking/tests/repository/mod.rs index e555654ca..c3589ce68 100644 --- a/packages/torrent-repository-benchmarking/tests/repository/mod.rs +++ b/packages/torrent-repository-benchmarking/tests/repository/mod.rs @@ -450,7 +450,9 @@ async fn it_should_import_persistent_torrents( make(&repo, &entries).await; let mut downloaded = repo.get_metrics().await.total_downloaded; - persistent_torrents.iter().for_each(|(_, d)| downloaded += u64::from(*d)); + for d in persistent_torrents.values() { + downloaded += u64::from(*d); + } repo.import_persistent(&persistent_torrents).await; diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 3c8204bf5..43c5bc4d5 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -28,7 +28,7 @@ use crate::event::UdpRequestKind; use crate::CurrentClock; #[derive(Debug, Clone, PartialEq)] -pub(super) struct CookieTimeValues { +pub struct CookieTimeValues { pub(super) issue_time: f64, pub(super) valid_range: Range, } From 64be8472feffb8217cdd7ce505510b4d234d5981 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 11 Jun 2025 14:16:02 +0100 Subject: [PATCH 1206/1297] feat: [#1446] add aggregate function sum to metric collection It allows sum metric samples matching a given criteria. The criteria is a label set. Sample values are added if they contain all the label name/value pairs specified in the criteria. For example, given these metric's samples in Prometheus export text format: ``` udp_tracker_server_requests_accepted_total{request_kind="scrape",server_binding_address_type="plain",server_binding_ip="0.0.0.0",server_binding_port="6969",server_binding_protocol="udp"} 213118 udp_tracker_server_requests_accepted_total{request_kind="announce",server_binding_address_type="plain",server_binding_ip="0.0.0.0",server_binding_port="6969",server_binding_protocol="udp"} 16460553 udp_tracker_server_requests_accepted_total{request_kind="connect",server_binding_address_type="plain",server_binding_ip="0.0.0.0",server_binding_port="6868",server_binding_protocol="udp"} 617 udp_tracker_server_requests_accepted_total{request_kind="connect",server_binding_address_type="plain",server_binding_ip="0.0.0.0",server_binding_port="6969",server_binding_protocol="udp"} 17148137 ``` And the criteria: it should contain the label `request_kind` with the value `connect`. It should return: 617 + 17148137 = 17148754 --- .../src/statistics/metrics.rs | 2 +- packages/metrics/src/aggregate.rs | 28 ++ packages/metrics/src/counter.rs | 18 ++ packages/metrics/src/gauge.rs | 11 + packages/metrics/src/label/set.rs | 21 ++ packages/metrics/src/lib.rs | 1 + packages/metrics/src/metric/aggregate/mod.rs | 1 + packages/metrics/src/metric/aggregate/sum.rs | 283 ++++++++++++++++++ packages/metrics/src/metric/mod.rs | 1 + .../src/metric_collection/aggregate.rs | 112 +++++++ .../mod.rs} | 22 +- .../src/statistics/metrics.rs | 2 +- .../tracker-core/src/statistics/metrics.rs | 2 +- .../src/statistics/metrics.rs | 2 +- .../src/statistics/metrics.rs | 2 +- 15 files changed, 493 insertions(+), 15 deletions(-) create mode 100644 packages/metrics/src/aggregate.rs create mode 100644 packages/metrics/src/metric/aggregate/mod.rs create mode 100644 packages/metrics/src/metric/aggregate/sum.rs create mode 100644 packages/metrics/src/metric_collection/aggregate.rs rename packages/metrics/src/{metric_collection.rs => metric_collection/mod.rs} (98%) diff --git a/packages/http-tracker-core/src/statistics/metrics.rs b/packages/http-tracker-core/src/statistics/metrics.rs index bf053b04e..650194d43 100644 --- a/packages/http-tracker-core/src/statistics/metrics.rs +++ b/packages/http-tracker-core/src/statistics/metrics.rs @@ -33,7 +33,7 @@ impl Metrics { labels: &LabelSet, now: DurationSinceUnixEpoch, ) -> Result<(), Error> { - self.metric_collection.increase_counter(metric_name, labels, now) + self.metric_collection.increment_counter(metric_name, labels, now) } /// # Errors diff --git a/packages/metrics/src/aggregate.rs b/packages/metrics/src/aggregate.rs new file mode 100644 index 000000000..875360cd9 --- /dev/null +++ b/packages/metrics/src/aggregate.rs @@ -0,0 +1,28 @@ +use derive_more::Display; + +#[derive(Debug, Display, Clone, Copy, PartialEq)] +pub struct AggregateValue(f64); + +impl AggregateValue { + #[must_use] + pub fn new(value: f64) -> Self { + Self(value) + } + + #[must_use] + pub fn value(&self) -> f64 { + self.0 + } +} + +impl From for AggregateValue { + fn from(value: f64) -> Self { + Self(value) + } +} + +impl From for f64 { + fn from(value: AggregateValue) -> Self { + value.0 + } +} diff --git a/packages/metrics/src/counter.rs b/packages/metrics/src/counter.rs index ac6d21836..3148ab4c3 100644 --- a/packages/metrics/src/counter.rs +++ b/packages/metrics/src/counter.rs @@ -17,6 +17,11 @@ impl Counter { self.0 } + #[must_use] + pub fn primitive(&self) -> u64 { + self.value() + } + pub fn increment(&mut self, value: u64) { self.0 += value; } @@ -26,12 +31,25 @@ impl Counter { } } +impl From for Counter { + fn from(value: u32) -> Self { + Self(u64::from(value)) + } +} + impl From for Counter { fn from(value: u64) -> Self { Self(value) } } +impl From for Counter { + fn from(value: i32) -> Self { + #[allow(clippy::cast_sign_loss)] + Self(value as u64) + } +} + impl From for u64 { fn from(counter: Counter) -> Self { counter.value() diff --git a/packages/metrics/src/gauge.rs b/packages/metrics/src/gauge.rs index 3f6089955..a2ef8135f 100644 --- a/packages/metrics/src/gauge.rs +++ b/packages/metrics/src/gauge.rs @@ -17,6 +17,11 @@ impl Gauge { self.0 } + #[must_use] + pub fn primitive(&self) -> f64 { + self.value() + } + pub fn set(&mut self, value: f64) { self.0 = value; } @@ -30,6 +35,12 @@ impl Gauge { } } +impl From for Gauge { + fn from(value: f32) -> Self { + Self(f64::from(value)) + } +} + impl From for Gauge { fn from(value: f64) -> Self { Self(value) diff --git a/packages/metrics/src/label/set.rs b/packages/metrics/src/label/set.rs index cab457f42..673f330c1 100644 --- a/packages/metrics/src/label/set.rs +++ b/packages/metrics/src/label/set.rs @@ -1,3 +1,4 @@ +use std::collections::btree_map::Iter; use std::collections::BTreeMap; use std::fmt::Display; @@ -12,6 +13,11 @@ pub struct LabelSet { } impl LabelSet { + #[must_use] + pub fn empty() -> Self { + Self { items: BTreeMap::new() } + } + /// Insert a new label pair or update the value of an existing label. pub fn upsert(&mut self, key: LabelName, value: LabelValue) { self.items.insert(key, value); @@ -20,6 +26,21 @@ impl LabelSet { pub fn is_empty(&self) -> bool { self.items.is_empty() } + + pub fn contains_pair(&self, name: &LabelName, value: &LabelValue) -> bool { + match self.items.get(name) { + Some(existing_value) => existing_value == value, + None => false, + } + } + + pub fn matches(&self, criteria: &LabelSet) -> bool { + criteria.iter().all(|(key, value)| self.contains_pair(key, value)) + } + + pub fn iter(&self) -> Iter<'_, LabelName, LabelValue> { + self.items.iter() + } } impl Display for LabelSet { diff --git a/packages/metrics/src/lib.rs b/packages/metrics/src/lib.rs index 997cd3c8c..c53e9dd02 100644 --- a/packages/metrics/src/lib.rs +++ b/packages/metrics/src/lib.rs @@ -1,3 +1,4 @@ +pub mod aggregate; pub mod counter; pub mod gauge; pub mod label; diff --git a/packages/metrics/src/metric/aggregate/mod.rs b/packages/metrics/src/metric/aggregate/mod.rs new file mode 100644 index 000000000..dce785d95 --- /dev/null +++ b/packages/metrics/src/metric/aggregate/mod.rs @@ -0,0 +1 @@ +pub mod sum; diff --git a/packages/metrics/src/metric/aggregate/sum.rs b/packages/metrics/src/metric/aggregate/sum.rs new file mode 100644 index 000000000..f08ea7d55 --- /dev/null +++ b/packages/metrics/src/metric/aggregate/sum.rs @@ -0,0 +1,283 @@ +use crate::aggregate::AggregateValue; +use crate::counter::Counter; +use crate::gauge::Gauge; +use crate::label::LabelSet; +use crate::metric::Metric; + +pub trait Sum { + fn sum(&self, label_set_criteria: &LabelSet) -> AggregateValue; +} + +impl Sum for Metric { + #[allow(clippy::cast_precision_loss)] + fn sum(&self, label_set_criteria: &LabelSet) -> AggregateValue { + let sum: f64 = self + .sample_collection + .iter() + .filter(|(label_set, _measurement)| label_set.matches(label_set_criteria)) + .map(|(_label_set, measurement)| measurement.value().primitive() as f64) + .sum(); + + sum.into() + } +} + +impl Sum for Metric { + fn sum(&self, label_set_criteria: &LabelSet) -> AggregateValue { + let sum: f64 = self + .sample_collection + .iter() + .filter(|(label_set, _measurement)| label_set.matches(label_set_criteria)) + .map(|(_label_set, measurement)| measurement.value().primitive()) + .sum(); + + sum.into() + } +} + +#[cfg(test)] +mod tests { + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::aggregate::AggregateValue; + use crate::counter::Counter; + use crate::gauge::Gauge; + use crate::label::LabelSet; + use crate::metric::aggregate::sum::Sum; + use crate::metric::{Metric, MetricName}; + use crate::metric_name; + use crate::sample::Sample; + use crate::sample_collection::SampleCollection; + + struct MetricBuilder { + sample_time: DurationSinceUnixEpoch, + name: MetricName, + samples: Vec>, + } + + impl Default for MetricBuilder { + fn default() -> Self { + Self { + sample_time: DurationSinceUnixEpoch::from_secs(1_743_552_000), + name: metric_name!("test_metric"), + samples: vec![], + } + } + } + + impl MetricBuilder { + fn with_sample(mut self, value: T, label_set: &LabelSet) -> Self { + let sample = Sample::new(value, self.sample_time, label_set.clone()); + self.samples.push(sample); + self + } + + fn build(self) -> Metric { + Metric::new( + self.name, + None, + None, + SampleCollection::new(self.samples).expect("invalid samples"), + ) + } + } + + fn counter_cases() -> Vec<(Metric, LabelSet, AggregateValue)> { + // (metric, label set criteria, expected_aggregate_value) + vec![ + // Metric with one sample without label set + ( + MetricBuilder::default().with_sample(1.into(), &LabelSet::empty()).build(), + LabelSet::empty(), + 1.0.into(), + ), + // Metric with one sample with a label set + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0.into(), + ), + // Metric with two samples, different label sets, sum all + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value")].into()) + .with_sample(2.into(), &[("l2", "l2_value")].into()) + .build(), + LabelSet::empty(), + 3.0.into(), + ), + // Metric with two samples, different label sets, sum one + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value")].into()) + .with_sample(2.into(), &[("l2", "l2_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0.into(), + ), + // Metric with two samples, same label key, different label values, sum by key + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(2.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 3.0.into(), + ), + // Metric with two samples, different label values, sum by subkey + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(2.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .build(), + [("la", "la_value")].into(), + 1.0.into(), + ), + // Edge: Metric with no samples at all + (MetricBuilder::default().build(), LabelSet::empty(), 0.0.into()), + // Edge: Metric with samples but no matching labels + ( + MetricBuilder::default() + .with_sample(5.into(), &[("foo", "bar")].into()) + .build(), + [("not", "present")].into(), + 0.0.into(), + ), + // Edge: Metric with zero value + ( + MetricBuilder::default() + .with_sample(0.into(), &[("l3", "l3_value")].into()) + .build(), + [("l3", "l3_value")].into(), + 0.0.into(), + ), + // Edge: Metric with a very large value + ( + MetricBuilder::default() + .with_sample(u64::MAX.into(), &LabelSet::empty()) + .build(), + LabelSet::empty(), + #[allow(clippy::cast_precision_loss)] + (u64::MAX as f64).into(), + ), + ] + } + + fn gauge_cases() -> Vec<(Metric, LabelSet, AggregateValue)> { + // (metric, label set criteria, expected_aggregate_value) + vec![ + // Metric with one sample without label set + ( + MetricBuilder::default().with_sample(1.0.into(), &LabelSet::empty()).build(), + LabelSet::empty(), + 1.0.into(), + ), + // Metric with one sample with a label set + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0.into(), + ), + // Metric with two samples, different label sets, sum all + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value")].into()) + .with_sample(2.0.into(), &[("l2", "l2_value")].into()) + .build(), + LabelSet::empty(), + 3.0.into(), + ), + // Metric with two samples, different label sets, sum one + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value")].into()) + .with_sample(2.0.into(), &[("l2", "l2_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0.into(), + ), + // Metric with two samples, same label key, different label values, sum by key + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(2.0.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 3.0.into(), + ), + // Metric with two samples, different label values, sum by subkey + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(2.0.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .build(), + [("la", "la_value")].into(), + 1.0.into(), + ), + // Edge: Metric with no samples at all + (MetricBuilder::default().build(), LabelSet::empty(), 0.0.into()), + // Edge: Metric with samples but no matching labels + ( + MetricBuilder::default() + .with_sample(5.0.into(), &[("foo", "bar")].into()) + .build(), + [("not", "present")].into(), + 0.0.into(), + ), + // Edge: Metric with zero value + ( + MetricBuilder::default() + .with_sample(0.0.into(), &[("l3", "l3_value")].into()) + .build(), + [("l3", "l3_value")].into(), + 0.0.into(), + ), + // Edge: Metric with negative values + ( + MetricBuilder::default() + .with_sample((-2.0).into(), &[("l4", "l4_value")].into()) + .with_sample(3.0.into(), &[("l5", "l5_value")].into()) + .build(), + LabelSet::empty(), + 1.0.into(), + ), + // Edge: Metric with a very large value + ( + MetricBuilder::default() + .with_sample(f64::MAX.into(), &LabelSet::empty()) + .build(), + LabelSet::empty(), + f64::MAX.into(), + ), + ] + } + + #[test] + fn test_counter_cases() { + for (idx, (metric, criteria, expected_value)) in counter_cases().iter().enumerate() { + let sum = metric.sum(criteria); + + assert_eq!( + sum, *expected_value, + "at case {idx}, expected sum to be {expected_value}, got {sum}" + ); + } + } + + #[test] + fn test_gauge_cases() { + for (idx, (metric, criteria, expected_value)) in gauge_cases().iter().enumerate() { + let sum = metric.sum(criteria); + + assert_eq!( + sum, *expected_value, + "at case {idx}, expected sum to be {expected_value}, got {sum}" + ); + } + } +} diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index df743c519..8ee24493a 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -1,3 +1,4 @@ +pub mod aggregate; pub mod description; pub mod name; diff --git a/packages/metrics/src/metric_collection/aggregate.rs b/packages/metrics/src/metric_collection/aggregate.rs new file mode 100644 index 000000000..7fd744d92 --- /dev/null +++ b/packages/metrics/src/metric_collection/aggregate.rs @@ -0,0 +1,112 @@ +use crate::aggregate::AggregateValue; +use crate::counter::Counter; +use crate::gauge::Gauge; +use crate::label::LabelSet; +use crate::metric::aggregate::sum::Sum as MetricSumTrait; +use crate::metric::MetricName; +use crate::metric_collection::{MetricCollection, MetricKindCollection}; + +pub trait Sum { + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option; +} + +impl Sum for MetricCollection { + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + if let Some(value) = self.counters.sum(metric_name, label_set_criteria) { + return Some(value); + } + + self.gauges.sum(metric_name, label_set_criteria) + } +} + +impl Sum for MetricKindCollection { + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + self.metrics.get(metric_name).map(|metric| metric.sum(label_set_criteria)) + } +} + +impl Sum for MetricKindCollection { + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + self.metrics.get(metric_name).map(|metric| metric.sum(label_set_criteria)) + } +} + +#[cfg(test)] +mod tests { + + mod it_should_allow_summing_all_metric_samples_containing_some_given_labels { + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::label::LabelValue; + use crate::label_name; + use crate::metric_collection::aggregate::Sum; + + #[test] + fn type_counter_with_two_samples() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let metric_name = metric_name!("test_counter"); + + let mut collection = MetricCollection::default(); + + collection + .increment_counter( + &metric_name!("test_counter"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + collection + .increment_counter( + &metric_name!("test_counter"), + &(label_name!("label_2"), LabelValue::new("value_2")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + assert_eq!(collection.sum(&metric_name, &LabelSet::empty()), Some(2.0.into())); + assert_eq!( + collection.sum(&metric_name, &(label_name!("label_1"), LabelValue::new("value_1")).into()), + Some(1.0.into()) + ); + } + + #[test] + fn type_gauge_with_two_samples() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let metric_name = metric_name!("test_gauge"); + + let mut collection = MetricCollection::default(); + + collection + .increment_gauge( + &metric_name!("test_gauge"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + collection + .increment_gauge( + &metric_name!("test_gauge"), + &(label_name!("label_2"), LabelValue::new("value_2")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + assert_eq!(collection.sum(&metric_name, &LabelSet::empty()), Some(2.0.into())); + assert_eq!( + collection.sum(&metric_name, &(label_name!("label_1"), LabelValue::new("value_1")).into()), + Some(1.0.into()) + ); + } + } +} diff --git a/packages/metrics/src/metric_collection.rs b/packages/metrics/src/metric_collection/mod.rs similarity index 98% rename from packages/metrics/src/metric_collection.rs rename to packages/metrics/src/metric_collection/mod.rs index ff932caae..e183236aa 100644 --- a/packages/metrics/src/metric_collection.rs +++ b/packages/metrics/src/metric_collection/mod.rs @@ -1,3 +1,5 @@ +pub mod aggregate; + use std::collections::{HashMap, HashSet}; use serde::ser::{SerializeSeq, Serializer}; @@ -103,7 +105,7 @@ impl MetricCollection { /// /// Return an error if a metrics of a different type with the same name /// already exists. - pub fn increase_counter( + pub fn increment_counter( &mut self, name: &MetricName, label_set: &LabelSet, @@ -669,7 +671,7 @@ udp_tracker_server_performance_avg_announce_processing_time_ns{server_binding_ip // First create a counter collection - .increase_counter(&metric_name!("test_metric"), &label_set, time) + .increment_counter(&metric_name!("test_metric"), &label_set, time) .unwrap(); // Then try to create a gauge with the same name @@ -690,7 +692,7 @@ udp_tracker_server_performance_avg_announce_processing_time_ns{server_binding_ip .unwrap(); // Then try to create a counter with the same name - let result = collection.increase_counter(&metric_name!("test_metric"), &label_set, time); + let result = collection.increment_counter(&metric_name!("test_metric"), &label_set, time); assert!(result.is_err()); } @@ -803,7 +805,7 @@ http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",s let mut collection1 = MetricCollection::default(); collection1 - .increase_counter(&metric_name!("test_counter"), &label_set, time) + .increment_counter(&metric_name!("test_counter"), &label_set, time) .unwrap(); let mut collection2 = MetricCollection::default(); @@ -824,12 +826,12 @@ http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",s let mut collection1 = MetricCollection::default(); collection1 - .increase_counter(&metric_name!("test_metric"), &label_set, time) + .increment_counter(&metric_name!("test_metric"), &label_set, time) .unwrap(); let mut collection2 = MetricCollection::default(); collection2 - .increase_counter(&metric_name!("test_metric"), &label_set, time) + .increment_counter(&metric_name!("test_metric"), &label_set, time) .unwrap(); let result = collection1.merge(&collection2); @@ -843,7 +845,7 @@ http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",s let mut collection1 = MetricCollection::default(); collection1 - .increase_counter(&metric_name!("test_metric"), &label_set, time) + .increment_counter(&metric_name!("test_metric"), &label_set, time) .unwrap(); let mut collection2 = MetricCollection::default(); @@ -940,7 +942,7 @@ http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",s let mut collection = collection_with_one_counter(&metric_name, &label_set, Counter::new(0)); collection - .increase_counter(&metric_name!("test_counter"), &label_set, time) + .increment_counter(&metric_name!("test_counter"), &label_set, time) .unwrap(); assert_eq!( @@ -958,10 +960,10 @@ http_tracker_core_announce_requests_received_total{server_binding_ip="0.0.0.0",s MetricCollection::new(MetricKindCollection::default(), MetricKindCollection::default()).unwrap(); metric_collection - .increase_counter(&metric_name!("test_counter"), &label_set, time) + .increment_counter(&metric_name!("test_counter"), &label_set, time) .unwrap(); metric_collection - .increase_counter(&metric_name!("test_counter"), &label_set, time) + .increment_counter(&metric_name!("test_counter"), &label_set, time) .unwrap(); assert_eq!( diff --git a/packages/swarm-coordination-registry/src/statistics/metrics.rs b/packages/swarm-coordination-registry/src/statistics/metrics.rs index f8ab3f9d9..d62a1ba6e 100644 --- a/packages/swarm-coordination-registry/src/statistics/metrics.rs +++ b/packages/swarm-coordination-registry/src/statistics/metrics.rs @@ -21,7 +21,7 @@ impl Metrics { labels: &LabelSet, now: DurationSinceUnixEpoch, ) -> Result<(), Error> { - self.metric_collection.increase_counter(metric_name, labels, now) + self.metric_collection.increment_counter(metric_name, labels, now) } /// # Errors diff --git a/packages/tracker-core/src/statistics/metrics.rs b/packages/tracker-core/src/statistics/metrics.rs index 02cc51499..a5caaf1cf 100644 --- a/packages/tracker-core/src/statistics/metrics.rs +++ b/packages/tracker-core/src/statistics/metrics.rs @@ -21,7 +21,7 @@ impl Metrics { labels: &LabelSet, now: DurationSinceUnixEpoch, ) -> Result<(), Error> { - self.metric_collection.increase_counter(metric_name, labels, now) + self.metric_collection.increment_counter(metric_name, labels, now) } /// # Errors diff --git a/packages/udp-tracker-core/src/statistics/metrics.rs b/packages/udp-tracker-core/src/statistics/metrics.rs index 94aa7d08f..e6ff8d5f6 100644 --- a/packages/udp-tracker-core/src/statistics/metrics.rs +++ b/packages/udp-tracker-core/src/statistics/metrics.rs @@ -47,7 +47,7 @@ impl Metrics { labels: &LabelSet, now: DurationSinceUnixEpoch, ) -> Result<(), Error> { - self.metric_collection.increase_counter(metric_name, labels, now) + self.metric_collection.increment_counter(metric_name, labels, now) } /// # Errors diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index 7b18f6418..ac6250872 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -78,7 +78,7 @@ impl Metrics { labels: &LabelSet, now: DurationSinceUnixEpoch, ) -> Result<(), Error> { - self.metric_collection.increase_counter(metric_name, labels, now) + self.metric_collection.increment_counter(metric_name, labels, now) } /// # Errors From 4da4f8351c1e616421bf0e8b5b83b1926fe34cd4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 12 Jun 2025 08:49:47 +0100 Subject: [PATCH 1207/1297] refactor: [#1446] rename vars --- packages/metrics/src/label/set.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/metrics/src/label/set.rs b/packages/metrics/src/label/set.rs index 673f330c1..542f5d2e6 100644 --- a/packages/metrics/src/label/set.rs +++ b/packages/metrics/src/label/set.rs @@ -19,8 +19,8 @@ impl LabelSet { } /// Insert a new label pair or update the value of an existing label. - pub fn upsert(&mut self, key: LabelName, value: LabelValue) { - self.items.insert(key, value); + pub fn upsert(&mut self, name: LabelName, value: LabelValue) { + self.items.insert(name, value); } pub fn is_empty(&self) -> bool { @@ -35,7 +35,7 @@ impl LabelSet { } pub fn matches(&self, criteria: &LabelSet) -> bool { - criteria.iter().all(|(key, value)| self.contains_pair(key, value)) + criteria.iter().all(|(name, value)| self.contains_pair(name, value)) } pub fn iter(&self) -> Iter<'_, LabelName, LabelValue> { @@ -48,7 +48,7 @@ impl Display for LabelSet { let items = self .items .iter() - .map(|(key, value)| format!("{key}=\"{value}\"")) + .map(|(name, value)| format!("{name}=\"{value}\"")) .collect::>() .join(","); @@ -90,8 +90,8 @@ impl From> for LabelSet { fn from(vec: Vec) -> Self { let mut items = BTreeMap::new(); - for (key, value) in vec { - items.insert(key, value); + for (name, value) in vec { + items.insert(name, value); } Self { items } @@ -160,8 +160,8 @@ impl Serialize for LabelSet { { self.items .iter() - .map(|(key, value)| SerializedLabel { - name: key.clone(), + .map(|(name, value)| SerializedLabel { + name: name.clone(), value: value.clone(), }) .collect::>() From 0d134396e53c9fe75becaad8f03072a0e53d3a22 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 12 Jun 2025 09:50:24 +0100 Subject: [PATCH 1208/1297] test: [#1446] add more tests to metrics package --- packages/metrics/.gitignore | 2 +- packages/metrics/README.md | 22 +++ packages/metrics/cSpell.json | 19 +++ packages/metrics/src/aggregate.rs | 115 ++++++++++++++++ packages/metrics/src/counter.rs | 156 ++++++++++++++++++++++ packages/metrics/src/gauge.rs | 124 +++++++++++++++++ packages/metrics/src/label/set.rs | 112 +++++++++++++++- packages/metrics/src/metric/mod.rs | 29 ++++ packages/metrics/src/sample.rs | 18 +++ packages/metrics/src/sample_collection.rs | 50 +++++++ 10 files changed, 645 insertions(+), 2 deletions(-) create mode 100644 packages/metrics/cSpell.json diff --git a/packages/metrics/.gitignore b/packages/metrics/.gitignore index 0b1372e5c..6350e9868 100644 --- a/packages/metrics/.gitignore +++ b/packages/metrics/.gitignore @@ -1 +1 @@ -./.coverage +.coverage diff --git a/packages/metrics/README.md b/packages/metrics/README.md index 627640eec..885d6fa45 100644 --- a/packages/metrics/README.md +++ b/packages/metrics/README.md @@ -6,6 +6,28 @@ A library with the metrics types used by the [Torrust Tracker](https://github.co [Crate documentation](https://docs.rs/torrust-tracker-metrics). +## Testing + +Run coverage report: + +```console +cargo llvm-cov --package torrust-tracker-metrics +``` + +Generate LCOV report with `llvm-cov` (for Visual Studio Code extension): + +```console +mkdir -p ./.coverage +cargo llvm-cov --package torrust-tracker-metrics --lcov --output-path=./.coverage/lcov.info +``` + +Generate HTML report with `llvm-cov`: + +```console +mkdir -p ./.coverage +cargo llvm-cov --package torrust-tracker-metrics --html --output-dir ./.coverage +``` + ## Acknowledgements We copied some parts like units or function names and signatures from the crate [metrics](https://crates.io/crates/metrics) because we wanted to make it compatible as much as possible with it. In the future, we may consider using the `metrics` crate directly instead of maintaining our own version. diff --git a/packages/metrics/cSpell.json b/packages/metrics/cSpell.json new file mode 100644 index 000000000..1a2c13d2e --- /dev/null +++ b/packages/metrics/cSpell.json @@ -0,0 +1,19 @@ +{ + "words": [ + "cloneable", + "formatjson", + "Gibibytes", + "Kibibytes", + "Mebibytes", + "ñaca", + "rstest", + "subsec", + "Tebibytes", + "thiserror" + ], + "enableFiletypes": [ + "dockerfile", + "shellscript", + "toml" + ] +} diff --git a/packages/metrics/src/aggregate.rs b/packages/metrics/src/aggregate.rs index 875360cd9..e480be396 100644 --- a/packages/metrics/src/aggregate.rs +++ b/packages/metrics/src/aggregate.rs @@ -26,3 +26,118 @@ impl From for f64 { value.0 } } + +#[cfg(test)] +mod tests { + use approx::assert_relative_eq; + + use super::*; + + #[test] + fn it_should_be_created_with_new() { + let value = AggregateValue::new(42.5); + assert_relative_eq!(value.value(), 42.5); + } + + #[test] + fn it_should_return_the_inner_value() { + let value = AggregateValue::new(123.456); + assert_relative_eq!(value.value(), 123.456); + } + + #[test] + fn it_should_handle_zero_value() { + let value = AggregateValue::new(0.0); + assert_relative_eq!(value.value(), 0.0); + } + + #[test] + fn it_should_handle_negative_values() { + let value = AggregateValue::new(-42.5); + assert_relative_eq!(value.value(), -42.5); + } + + #[test] + fn it_should_handle_infinity() { + let value = AggregateValue::new(f64::INFINITY); + assert_relative_eq!(value.value(), f64::INFINITY); + } + + #[test] + fn it_should_handle_nan() { + let value = AggregateValue::new(f64::NAN); + assert!(value.value().is_nan()); + } + + #[test] + fn it_should_be_created_from_f64() { + let value: AggregateValue = 42.5.into(); + assert_relative_eq!(value.value(), 42.5); + } + + #[test] + fn it_should_convert_to_f64() { + let value = AggregateValue::new(42.5); + let f64_value: f64 = value.into(); + assert_relative_eq!(f64_value, 42.5); + } + + #[test] + fn it_should_be_displayable() { + let value = AggregateValue::new(42.5); + assert_eq!(value.to_string(), "42.5"); + } + + #[test] + fn it_should_be_debuggable() { + let value = AggregateValue::new(42.5); + let debug_string = format!("{value:?}"); + assert_eq!(debug_string, "AggregateValue(42.5)"); + } + + #[test] + fn it_should_be_cloneable() { + let value = AggregateValue::new(42.5); + let cloned_value = value; + assert_eq!(value, cloned_value); + } + + #[test] + fn it_should_be_copyable() { + let value = AggregateValue::new(42.5); + let copied_value = value; + assert_eq!(value, copied_value); + } + + #[test] + fn it_should_support_equality_comparison() { + let value1 = AggregateValue::new(42.5); + let value2 = AggregateValue::new(42.5); + let value3 = AggregateValue::new(43.0); + + assert_eq!(value1, value2); + assert_ne!(value1, value3); + } + + #[test] + fn it_should_handle_special_float_values_in_equality() { + let nan1 = AggregateValue::new(f64::NAN); + let nan2 = AggregateValue::new(f64::NAN); + let infinity = AggregateValue::new(f64::INFINITY); + let neg_infinity = AggregateValue::new(f64::NEG_INFINITY); + + // NaN is not equal to itself in IEEE 754 + assert_ne!(nan1, nan2); + assert_eq!(infinity, AggregateValue::new(f64::INFINITY)); + assert_eq!(neg_infinity, AggregateValue::new(f64::NEG_INFINITY)); + assert_ne!(infinity, neg_infinity); + } + + #[test] + fn it_should_handle_conversion_roundtrip() { + let original_value = 42.5; + let aggregate_value = AggregateValue::from(original_value); + let converted_back: f64 = aggregate_value.into(); + assert_relative_eq!(original_value, converted_back); + } +} diff --git a/packages/metrics/src/counter.rs b/packages/metrics/src/counter.rs index 3148ab4c3..0e2002181 100644 --- a/packages/metrics/src/counter.rs +++ b/packages/metrics/src/counter.rs @@ -107,4 +107,160 @@ mod tests { let counter = Counter::new(42); assert_eq!(counter.to_prometheus(), "42"); } + + #[test] + fn it_could_be_converted_from_u32() { + let counter: Counter = 42u32.into(); + assert_eq!(counter.value(), 42); + } + + #[test] + fn it_could_be_converted_from_i32() { + let counter: Counter = 42i32.into(); + assert_eq!(counter.value(), 42); + } + + #[test] + fn it_should_return_primitive_value() { + let counter = Counter::new(123); + assert_eq!(counter.primitive(), 123); + } + + #[test] + fn it_should_handle_zero_value() { + let counter = Counter::new(0); + assert_eq!(counter.value(), 0); + assert_eq!(counter.primitive(), 0); + } + + #[test] + fn it_should_handle_large_values() { + let counter = Counter::new(u64::MAX); + assert_eq!(counter.value(), u64::MAX); + } + + #[test] + fn it_should_handle_u32_max_conversion() { + let counter: Counter = u32::MAX.into(); + assert_eq!(counter.value(), u64::from(u32::MAX)); + } + + #[test] + fn it_should_handle_i32_max_conversion() { + let counter: Counter = i32::MAX.into(); + assert_eq!(counter.value(), i32::MAX as u64); + } + + #[test] + fn it_should_handle_negative_i32_conversion() { + let counter: Counter = (-42i32).into(); + #[allow(clippy::cast_sign_loss)] + let expected = (-42i32) as u64; + assert_eq!(counter.value(), expected); + } + + #[test] + fn it_should_handle_i32_min_conversion() { + let counter: Counter = i32::MIN.into(); + #[allow(clippy::cast_sign_loss)] + let expected = i32::MIN as u64; + assert_eq!(counter.value(), expected); + } + + #[test] + fn it_should_handle_large_increments() { + let mut counter = Counter::new(100); + counter.increment(1000); + assert_eq!(counter.value(), 1100); + + counter.increment(u64::MAX - 1100); + assert_eq!(counter.value(), u64::MAX); + } + + #[test] + fn it_should_support_multiple_absolute_operations() { + let mut counter = Counter::new(0); + + counter.absolute(100); + assert_eq!(counter.value(), 100); + + counter.absolute(50); + assert_eq!(counter.value(), 50); + + counter.absolute(0); + assert_eq!(counter.value(), 0); + } + + #[test] + fn it_should_be_displayable() { + let counter = Counter::new(42); + assert_eq!(counter.to_string(), "42"); + + let counter = Counter::new(0); + assert_eq!(counter.to_string(), "0"); + } + + #[test] + fn it_should_be_debuggable() { + let counter = Counter::new(42); + let debug_string = format!("{counter:?}"); + assert_eq!(debug_string, "Counter(42)"); + } + + #[test] + fn it_should_be_cloneable() { + let counter = Counter::new(42); + let cloned_counter = counter.clone(); + assert_eq!(counter, cloned_counter); + assert_eq!(counter.value(), cloned_counter.value()); + } + + #[test] + fn it_should_support_equality_comparison() { + let counter1 = Counter::new(42); + let counter2 = Counter::new(42); + let counter3 = Counter::new(43); + + assert_eq!(counter1, counter2); + assert_ne!(counter1, counter3); + } + + #[test] + fn it_should_have_default_value() { + let counter = Counter::default(); + assert_eq!(counter.value(), 0); + } + + #[test] + fn it_should_handle_conversion_roundtrip() { + let original_value = 12345u64; + let counter = Counter::from(original_value); + let converted_back: u64 = counter.into(); + assert_eq!(original_value, converted_back); + } + + #[test] + fn it_should_handle_u32_conversion_roundtrip() { + let original_value = 12345u32; + let counter = Counter::from(original_value); + assert_eq!(counter.value(), u64::from(original_value)); + } + + #[test] + fn it_should_handle_i32_conversion_roundtrip() { + let original_value = 12345i32; + let counter = Counter::from(original_value); + #[allow(clippy::cast_sign_loss)] + let expected = original_value as u64; + assert_eq!(counter.value(), expected); + } + + #[test] + fn it_should_serialize_large_values_to_prometheus() { + let counter = Counter::new(u64::MAX); + assert_eq!(counter.to_prometheus(), u64::MAX.to_string()); + + let counter = Counter::new(0); + assert_eq!(counter.to_prometheus(), "0"); + } } diff --git a/packages/metrics/src/gauge.rs b/packages/metrics/src/gauge.rs index a2ef8135f..d0883715b 100644 --- a/packages/metrics/src/gauge.rs +++ b/packages/metrics/src/gauge.rs @@ -113,4 +113,128 @@ mod tests { let counter = Gauge::new(42.1); assert_eq!(counter.to_prometheus(), "42.1"); } + + #[test] + fn it_could_be_converted_from_f32() { + let gauge: Gauge = 42.5f32.into(); + assert_relative_eq!(gauge.value(), 42.5); + } + + #[test] + fn it_should_return_primitive_value() { + let gauge = Gauge::new(123.456); + assert_relative_eq!(gauge.primitive(), 123.456); + } + + #[test] + fn it_should_handle_zero_value() { + let gauge = Gauge::new(0.0); + assert_relative_eq!(gauge.value(), 0.0); + assert_relative_eq!(gauge.primitive(), 0.0); + } + + #[test] + fn it_should_handle_negative_values() { + let gauge = Gauge::new(-42.5); + assert_relative_eq!(gauge.value(), -42.5); + } + + #[test] + fn it_should_handle_large_values() { + let gauge = Gauge::new(f64::MAX); + assert_relative_eq!(gauge.value(), f64::MAX); + } + + #[test] + fn it_should_handle_infinity() { + let gauge = Gauge::new(f64::INFINITY); + assert_relative_eq!(gauge.value(), f64::INFINITY); + } + + #[test] + fn it_should_handle_nan() { + let gauge = Gauge::new(f64::NAN); + assert!(gauge.value().is_nan()); + } + + #[test] + fn it_should_be_displayable() { + let gauge = Gauge::new(42.5); + assert_eq!(gauge.to_string(), "42.5"); + + let gauge = Gauge::new(0.0); + assert_eq!(gauge.to_string(), "0"); + } + + #[test] + fn it_should_be_debuggable() { + let gauge = Gauge::new(42.5); + let debug_string = format!("{gauge:?}"); + assert_eq!(debug_string, "Gauge(42.5)"); + } + + #[test] + fn it_should_be_cloneable() { + let gauge = Gauge::new(42.5); + let cloned_gauge = gauge.clone(); + assert_eq!(gauge, cloned_gauge); + assert_relative_eq!(gauge.value(), cloned_gauge.value()); + } + + #[test] + fn it_should_support_equality_comparison() { + let gauge1 = Gauge::new(42.5); + let gauge2 = Gauge::new(42.5); + let gauge3 = Gauge::new(43.0); + + assert_eq!(gauge1, gauge2); + assert_ne!(gauge1, gauge3); + } + + #[test] + fn it_should_have_default_value() { + let gauge = Gauge::default(); + assert_relative_eq!(gauge.value(), 0.0); + } + + #[test] + fn it_should_handle_conversion_roundtrip() { + let original_value = 12345.678; + let gauge = Gauge::from(original_value); + let converted_back: f64 = gauge.into(); + assert_relative_eq!(original_value, converted_back); + } + + #[test] + fn it_should_handle_f32_conversion_roundtrip() { + let original_value = 12345.5f32; + let gauge = Gauge::from(original_value); + assert_relative_eq!(gauge.value(), f64::from(original_value)); + } + + #[test] + fn it_should_handle_multiple_operations() { + let mut gauge = Gauge::new(100.0); + + gauge.increment(50.0); + assert_relative_eq!(gauge.value(), 150.0); + + gauge.decrement(25.0); + assert_relative_eq!(gauge.value(), 125.0); + + gauge.set(200.0); + assert_relative_eq!(gauge.value(), 200.0); + } + + #[test] + fn it_should_serialize_special_values_to_prometheus() { + let gauge = Gauge::new(f64::INFINITY); + assert_eq!(gauge.to_prometheus(), "inf"); + + let gauge = Gauge::new(f64::NEG_INFINITY); + assert_eq!(gauge.to_prometheus(), "-inf"); + + let gauge = Gauge::new(f64::NAN); + assert_eq!(gauge.to_prometheus(), "NaN"); + } } diff --git a/packages/metrics/src/label/set.rs b/packages/metrics/src/label/set.rs index 542f5d2e6..46256e4d5 100644 --- a/packages/metrics/src/label/set.rs +++ b/packages/metrics/src/label/set.rs @@ -297,10 +297,18 @@ mod tests { #[test] fn it_should_allow_serializing_to_prometheus_format() { let label_set = LabelSet::from((label_name!("label_name"), LabelValue::new("label value"))); - assert_eq!(label_set.to_prometheus(), r#"{label_name="label value"}"#); } + #[test] + fn it_should_handle_prometheus_format_with_special_characters() { + let label_set: LabelSet = vec![("label_with_underscores", "value_with_underscores")].into(); + assert_eq!( + label_set.to_prometheus(), + r#"{label_with_underscores="value_with_underscores"}"# + ); + } + #[test] fn it_should_alphabetically_order_labels_in_prometheus_format() { let label_set = LabelSet::from([ @@ -471,4 +479,106 @@ mod tests { let a: LabelSet = (label_name!("x"), LabelValue::new("1")).into(); let _unused = a.clone(); } + + #[test] + fn it_should_check_if_empty() { + let empty_set = LabelSet::empty(); + assert!(empty_set.is_empty()); + } + + #[test] + fn it_should_check_if_non_empty() { + let non_empty_set: LabelSet = (label_name!("label"), LabelValue::new("value")).into(); + assert!(!non_empty_set.is_empty()); + } + + #[test] + fn it_should_create_an_empty_label_set() { + let empty_set = LabelSet::empty(); + assert!(empty_set.is_empty()); + } + + #[test] + fn it_should_check_if_contains_specific_label_pair() { + let label_set: LabelSet = vec![("service", "tracker"), ("protocol", "http")].into(); + + // Test existing pair + assert!(label_set.contains_pair(&LabelName::new("service"), &LabelValue::new("tracker"))); + assert!(label_set.contains_pair(&LabelName::new("protocol"), &LabelValue::new("http"))); + + // Test non-existing name + assert!(!label_set.contains_pair(&LabelName::new("missing"), &LabelValue::new("value"))); + + // Test existing name with wrong value + assert!(!label_set.contains_pair(&LabelName::new("service"), &LabelValue::new("wrong"))); + } + + #[test] + fn it_should_match_against_criteria() { + let label_set: LabelSet = vec![("service", "tracker"), ("protocol", "http"), ("version", "v1")].into(); + + // Empty criteria should match any label set + assert!(label_set.matches(&LabelSet::empty())); + + // Single matching criterion + let single_criteria: LabelSet = vec![("service", "tracker")].into(); + assert!(label_set.matches(&single_criteria)); + + // Multiple matching criteria + let multiple_criteria: LabelSet = vec![("service", "tracker"), ("protocol", "http")].into(); + assert!(label_set.matches(&multiple_criteria)); + + // Non-matching criterion + let non_matching: LabelSet = vec![("service", "wrong")].into(); + assert!(!label_set.matches(&non_matching)); + + // Partially matching criteria (one matches, one doesn't) + let partial_matching: LabelSet = vec![("service", "tracker"), ("missing", "value")].into(); + assert!(!label_set.matches(&partial_matching)); + + // Criteria with label not in original set + let missing_label: LabelSet = vec![("missing_label", "value")].into(); + assert!(!label_set.matches(&missing_label)); + } + + #[test] + fn it_should_allow_iteration_over_label_pairs() { + let label_set: LabelSet = vec![("service", "tracker"), ("protocol", "http")].into(); + + let mut count = 0; + + for (name, value) in label_set.iter() { + count += 1; + // Verify we can access name and value + assert!(!name.to_string().is_empty()); + assert!(!value.to_string().is_empty()); + } + + assert_eq!(count, 2); + } + + #[test] + fn it_should_display_empty_label_set() { + let empty_set = LabelSet::empty(); + assert_eq!(empty_set.to_string(), "{}"); + } + + #[test] + fn it_should_serialize_empty_label_set_to_prometheus_format() { + let empty_set = LabelSet::empty(); + assert_eq!(empty_set.to_prometheus(), ""); + } + + #[test] + fn it_should_maintain_order_in_iteration() { + let label_set: LabelSet = vec![("z_label", "z_value"), ("a_label", "a_value"), ("m_label", "m_value")].into(); + + let mut labels: Vec = vec![]; + for (name, _) in label_set.iter() { + labels.push(name.to_string()); + } + + // Should be in alphabetical order + assert_eq!(labels, vec!["a_label", "m_label", "z_label"]); + } } diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index 8ee24493a..d1aa01b94 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -322,4 +322,33 @@ mod tests { assert_relative_eq!(metric.get_sample_data(&label_set).unwrap().value().value(), 1.0); } } + + mod for_prometheus_serialization { + use super::super::*; + use crate::counter::Counter; + use crate::metric_name; + + #[test] + fn it_should_return_empty_string_for_prometheus_help_line_when_description_is_none() { + let name = metric_name!("test_metric"); + let samples = SampleCollection::::default(); + let metric = Metric::::new(name, None, None, samples); + + let help_line = metric.prometheus_help_line(); + + assert_eq!(help_line, String::new()); + } + + #[test] + fn it_should_return_formatted_help_line_for_prometheus_when_description_is_some() { + let name = metric_name!("test_metric"); + let description = MetricDescription::new("This is a test metric description"); + let samples = SampleCollection::::default(); + let metric = Metric::::new(name, None, Some(description), samples); + + let help_line = metric.prometheus_help_line(); + + assert_eq!(help_line, "# HELP test_metric This is a test metric description"); + } + } } diff --git a/packages/metrics/src/sample.rs b/packages/metrics/src/sample.rs index b9cd6c312..63f46b9b8 100644 --- a/packages/metrics/src/sample.rs +++ b/packages/metrics/src/sample.rs @@ -279,6 +279,15 @@ mod tests { assert_eq!(sample.to_prometheus(), r#"{label_name="label_value",method="GET"} 42"#); } + + #[test] + fn it_should_allow_exporting_to_prometheus_format_with_empty_label_set() { + let counter = Counter::new(42); + + let sample = Sample::new(counter, DurationSinceUnixEpoch::default(), LabelSet::default()); + + assert_eq!(sample.to_prometheus(), " 42"); + } } mod for_gauge_type_sample { use torrust_tracker_primitives::DurationSinceUnixEpoch; @@ -347,6 +356,15 @@ mod tests { assert_eq!(sample.to_prometheus(), r#"{label_name="label_value",method="GET"} 42"#); } + + #[test] + fn it_should_allow_exporting_to_prometheus_format_with_empty_label_set() { + let gauge = Gauge::new(42.0); + + let sample = Sample::new(gauge, DurationSinceUnixEpoch::default(), LabelSet::default()); + + assert_eq!(sample.to_prometheus(), " 42"); + } } mod serialization_to_json { diff --git a/packages/metrics/src/sample_collection.rs b/packages/metrics/src/sample_collection.rs index ef88b27dd..e520d7310 100644 --- a/packages/metrics/src/sample_collection.rs +++ b/packages/metrics/src/sample_collection.rs @@ -386,6 +386,56 @@ mod tests { assert_eq!(collection.get(&label2).unwrap().value(), &Counter::new(1)); assert_eq!(collection.len(), 2); } + + #[test] + fn it_should_allow_setting_absolute_value_for_a_counter() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::::default(); + + // Set absolute value for a non-existent label + collection.absolute(&label_set, 42, sample_update_time()); + + // Verify the label exists and has the absolute value + assert!(collection.get(&label_set).is_some()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Counter::new(42)); + } + + #[test] + fn it_should_allow_setting_absolute_value_for_existing_counter() { + let label_set = LabelSet::default(); + let mut collection = SampleCollection::::default(); + + // Initialize the sample with increment + collection.increment(&label_set, sample_update_time()); + + // Verify initial state + let sample = collection.get(&label_set).unwrap(); + assert_eq!(sample.value(), &Counter::new(1)); + + // Set absolute value + collection.absolute(&label_set, 100, sample_update_time()); + let sample = collection.get(&label_set).unwrap(); + assert_eq!(*sample.value(), Counter::new(100)); + } + + #[test] + fn it_should_update_time_when_setting_absolute_value() { + let label_set = LabelSet::default(); + let initial_time = sample_update_time(); + let mut collection = SampleCollection::::default(); + + // Set absolute value with initial time + collection.absolute(&label_set, 50, initial_time); + + // Set absolute value with a new time + let new_time = initial_time.add(DurationSinceUnixEpoch::from_secs(1)); + collection.absolute(&label_set, 75, new_time); + + let sample = collection.get(&label_set).unwrap(); + assert_eq!(sample.recorded_at(), new_time); + assert_eq!(*sample.value(), Counter::new(75)); + } } #[cfg(test)] From 476ece46e7b3b67d01e8fc2031aa0e9faf3578af Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 13 Jun 2025 10:52:53 +0100 Subject: [PATCH 1209/1297] refactor: [#1446] WIP. Calculate global metrics from labeled metrics We need to add a new label to make it easier to fileter by the server IP family: IPV4 or IPv6. --- Cargo.lock | 1 + .../src/statistics/event/handler.rs | 14 ++- .../http-tracker-core/src/statistics/mod.rs | 2 +- packages/metrics/src/aggregate.rs | 2 +- packages/rest-tracker-api-core/Cargo.toml | 1 + .../src/statistics/services.rs | 117 +++++++++++++++++- .../event/handler/request_accepted.rs | 4 +- .../udp-tracker-server/src/statistics/mod.rs | 2 +- 8 files changed, 135 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 269f7a3a2..6f8215bbf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4668,6 +4668,7 @@ dependencies = [ "torrust-tracker-swarm-coordination-registry", "torrust-tracker-test-helpers", "torrust-udp-tracker-server", + "tracing", ] [[package]] diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index f5506f6e3..dcb814eef 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -32,7 +32,12 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: .increase_counter(&metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) .await { - Ok(()) => {} + Ok(()) => { + tracing::debug!( + "Successfully increased the counter for HTTP announce requests received: {}", + label_set + ); + } Err(err) => tracing::error!("Failed to increase the counter: {}", err), }; } @@ -57,7 +62,12 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: .increase_counter(&metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &label_set, now) .await { - Ok(()) => {} + Ok(()) => { + tracing::debug!( + "Successfully increased the counter for HTTP scrape requests received: {}", + label_set + ); + } Err(err) => tracing::error!("Failed to increase the counter: {}", err), }; } diff --git a/packages/http-tracker-core/src/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs index 7181632aa..b8ca865fa 100644 --- a/packages/http-tracker-core/src/statistics/mod.rs +++ b/packages/http-tracker-core/src/statistics/mod.rs @@ -8,7 +8,7 @@ use torrust_tracker_metrics::metric::description::MetricDescription; use torrust_tracker_metrics::metric_name; use torrust_tracker_metrics::unit::Unit; -const HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL: &str = "http_tracker_core_requests_received_total"; +pub const HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL: &str = "http_tracker_core_requests_received_total"; #[must_use] pub fn describe_metrics() -> Metrics { diff --git a/packages/metrics/src/aggregate.rs b/packages/metrics/src/aggregate.rs index e480be396..39b760fca 100644 --- a/packages/metrics/src/aggregate.rs +++ b/packages/metrics/src/aggregate.rs @@ -1,6 +1,6 @@ use derive_more::Display; -#[derive(Debug, Display, Clone, Copy, PartialEq)] +#[derive(Debug, Display, Clone, Copy, PartialEq, Default)] pub struct AggregateValue(f64); impl AggregateValue { diff --git a/packages/rest-tracker-api-core/Cargo.toml b/packages/rest-tracker-api-core/Cargo.toml index cc8eda903..d9e396960 100644 --- a/packages/rest-tracker-api-core/Cargo.toml +++ b/packages/rest-tracker-api-core/Cargo.toml @@ -23,6 +23,7 @@ torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } +tracing = "0" [dev-dependencies] torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 6474df0d7..3cfd6653e 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -1,11 +1,14 @@ use std::sync::Arc; +use bittorrent_http_tracker_core::statistics::HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self}; use tokio::sync::RwLock; +use torrust_tracker_metrics::metric_collection::aggregate::Sum; use torrust_tracker_metrics::metric_collection::MetricCollection; -use torrust_udp_tracker_server::statistics as udp_server_statistics; +use torrust_tracker_metrics::metric_name; +use torrust_udp_tracker_server::statistics::{self as udp_server_statistics, UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL}; use super::metrics::TorrentsMetrics; use crate::statistics::metrics::ProtocolMetrics; @@ -32,9 +35,38 @@ pub async fn get_metrics( http_stats_repository: Arc, udp_server_stats_repository: Arc, ) -> TrackerMetrics { + let protocol_metrics_from_global_metrics = get_protocol_metrics( + ban_service.clone(), + http_stats_repository.clone(), + udp_server_stats_repository.clone(), + ) + .await; + + let protocol_metrics_from_labeled_metrics = get_protocol_metrics_from_labeled_metrics( + ban_service.clone(), + http_stats_repository.clone(), + udp_server_stats_repository.clone(), + ) + .await; + + // todo: + // We keep both metrics until we deploy to production and we can + // ensure that the protocol metrics from labeled metrics are correct. + // After that we can remove the `get_protocol_metrics` function and + // use only the `get_protocol_metrics_from_labeled_metrics` function. + // And also remove the code in repositories to generate the global metrics. + let protocol_metrics = if protocol_metrics_from_global_metrics == protocol_metrics_from_labeled_metrics { + protocol_metrics_from_labeled_metrics + } else { + // tracing::warn!("The protocol metrics from global metrics and labeled metrics are different"); + // tracing::warn!("Global metrics: {:?}", protocol_metrics_from_global_metrics); + // tracing::warn!("Labeled metrics: {:?}", protocol_metrics_from_labeled_metrics); + protocol_metrics_from_global_metrics + }; + TrackerMetrics { torrents_metrics: get_torrents_metrics(in_memory_torrent_repository, tracker_core_stats_repository).await, - protocol_metrics: get_protocol_metrics(ban_service, http_stats_repository, udp_server_stats_repository).await, + protocol_metrics, } } @@ -99,6 +131,87 @@ async fn get_protocol_metrics( } } +#[allow(deprecated)] +async fn get_protocol_metrics_from_labeled_metrics( + ban_service: Arc>, + http_stats_repository: Arc, + udp_server_stats_repository: Arc, +) -> ProtocolMetrics { + let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); + let http_stats = http_stats_repository.get_stats().await; + let udp_server_stats = udp_server_stats_repository.get_stats().await; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let tcp4_announces_handled = http_stats + .metric_collection + .sum( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("request_kind", "announce")].into(), // todo: add label for `server_binding_ip_family` with value `inet` (inet/inet6) + ) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp4_announces_handled = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("request_kind", "announce")].into(), // todo: add label for `server_binding_ip_family` with value `inet` (inet/inet6) + ) + .unwrap_or_default() + .value() as u64; + + /* + + todo: + + - Add a label for `server_binding_ip_family` with value `inet` (inet/inet6) + to all metrics containing an IP address. This will allow us to distinguish + between IPv4 and IPv6 metrics. + - Continue replacing the other metrics with the labeled metrics. + + */ + + // For backward compatibility we keep the `tcp4_connections_handled` and + // `tcp6_connections_handled` metrics. They don't make sense for the HTTP + // tracker, but we keep them for now. In new major versions we should remove + // them. + + ProtocolMetrics { + // TCPv4 + tcp4_connections_handled: tcp4_announces_handled + http_stats.tcp4_scrapes_handled, + tcp4_announces_handled, + tcp4_scrapes_handled: http_stats.tcp4_scrapes_handled, + // TCPv6 + tcp6_connections_handled: http_stats.tcp6_announces_handled + http_stats.tcp6_scrapes_handled, + tcp6_announces_handled: http_stats.tcp6_announces_handled, + tcp6_scrapes_handled: http_stats.tcp6_scrapes_handled, + // UDP + udp_requests_aborted: udp_server_stats.udp_requests_aborted, + udp_requests_banned: udp_server_stats.udp_requests_banned, + udp_banned_ips_total: udp_banned_ips_total as u64, + udp_avg_connect_processing_time_ns: udp_server_stats.udp_avg_connect_processing_time_ns, + udp_avg_announce_processing_time_ns: udp_server_stats.udp_avg_announce_processing_time_ns, + udp_avg_scrape_processing_time_ns: udp_server_stats.udp_avg_scrape_processing_time_ns, + // UDPv4 + udp4_requests: udp_server_stats.udp4_requests, + udp4_connections_handled: udp_server_stats.udp4_connections_handled, + udp4_announces_handled, + udp4_scrapes_handled: udp_server_stats.udp4_scrapes_handled, + udp4_responses: udp_server_stats.udp4_responses, + udp4_errors_handled: udp_server_stats.udp4_errors_handled, + // UDPv6 + udp6_requests: udp_server_stats.udp6_requests, + udp6_connections_handled: udp_server_stats.udp6_connections_handled, + udp6_announces_handled: udp_server_stats.udp6_announces_handled, + udp6_scrapes_handled: udp_server_stats.udp6_scrapes_handled, + udp6_responses: udp_server_stats.udp6_responses, + udp6_errors_handled: udp_server_stats.udp6_errors_handled, + } +} + #[derive(Debug, PartialEq)] pub struct TrackerLabeledMetrics { pub metrics: MetricCollection, diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs index b296f8ec9..37b668227 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs @@ -47,7 +47,9 @@ pub async fn handle_event( .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &label_set, now) .await { - Ok(()) => {} + Ok(()) => { + tracing::debug!("Successfully increased the counter for UDP requests accepted: {}", label_set); + } Err(err) => tracing::error!("Failed to increase the counter: {}", err), }; } diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index ebb3df0bf..3a25fd51d 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -13,7 +13,7 @@ const UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL: &str = "udp_tracker_server_reque pub(crate) const UDP_TRACKER_SERVER_IPS_BANNED_TOTAL: &str = "udp_tracker_server_ips_banned_total"; const UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL: &str = "udp_tracker_server_connection_id_errors_total"; const UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL: &str = "udp_tracker_server_requests_received_total"; -const UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL: &str = "udp_tracker_server_requests_accepted_total"; +pub const UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL: &str = "udp_tracker_server_requests_accepted_total"; const UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL: &str = "udp_tracker_server_responses_sent_total"; const UDP_TRACKER_SERVER_ERRORS_TOTAL: &str = "udp_tracker_server_errors_total"; const UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS: &str = "udp_tracker_server_performance_avg_processing_time_ns"; From 1376a7cb20166140c081c2bbf26443043bd1eb77 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 13 Jun 2025 11:02:35 +0100 Subject: [PATCH 1210/1297] refactor: [#1446] rename AddressType to IpType Address might be a socket address. --- packages/http-tracker-core/src/event.rs | 4 ++-- packages/primitives/src/service_binding.rs | 18 +++++++++--------- packages/udp-tracker-core/src/event.rs | 4 ++-- packages/udp-tracker-server/src/event.rs | 4 ++-- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/packages/http-tracker-core/src/event.rs b/packages/http-tracker-core/src/event.rs index cf969b4ff..e3d37569d 100644 --- a/packages/http-tracker-core/src/event.rs +++ b/packages/http-tracker-core/src/event.rs @@ -87,8 +87,8 @@ impl From for LabelSet { LabelValue::new(&connection_context.server.service_binding.bind_address().ip().to_string()), ), ( - label_name!("server_binding_address_type"), - LabelValue::new(&connection_context.server.service_binding.bind_address_type().to_string()), + label_name!("server_binding_address_ip_type"), + LabelValue::new(&connection_context.server.service_binding.bind_address_ip_type().to_string()), ), ( label_name!("server_binding_port"), diff --git a/packages/primitives/src/service_binding.rs b/packages/primitives/src/service_binding.rs index d5055130e..72d5e7f2e 100644 --- a/packages/primitives/src/service_binding.rs +++ b/packages/primitives/src/service_binding.rs @@ -26,7 +26,7 @@ impl fmt::Display for Protocol { } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] -pub enum AddressType { +pub enum IpType { /// Represents a plain IPv4 or IPv6 address. Plain, @@ -38,7 +38,7 @@ pub enum AddressType { V4MappedV6, } -impl fmt::Display for AddressType { +impl fmt::Display for IpType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let addr_type_str = match self { Self::Plain => "plain", @@ -120,12 +120,12 @@ impl ServiceBinding { } #[must_use] - pub fn bind_address_type(&self) -> AddressType { + pub fn bind_address_ip_type(&self) -> IpType { if self.is_v4_mapped_v6() { - return AddressType::V4MappedV6; + return IpType::V4MappedV6; } - AddressType::Plain + IpType::Plain } /// # Panics @@ -169,7 +169,7 @@ mod tests { use rstest::rstest; use url::Url; - use crate::service_binding::{AddressType, Error, Protocol, ServiceBinding}; + use crate::service_binding::{Error, IpType, Protocol, ServiceBinding}; #[rstest] #[case("wildcard_ip", Protocol::UDP, SocketAddr::from_str("0.0.0.0:6969").unwrap())] @@ -203,7 +203,7 @@ mod tests { fn should_return_the_bind_address_plain_type_for_ipv4_ips() { let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("127.0.0.1:6969").unwrap()).unwrap(); - assert_eq!(service_binding.bind_address_type(), AddressType::Plain); + assert_eq!(service_binding.bind_address_ip_type(), IpType::Plain); } #[test] @@ -211,7 +211,7 @@ mod tests { let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("[0:0:0:0:0:0:0:1]:6969").unwrap()).unwrap(); - assert_eq!(service_binding.bind_address_type(), AddressType::Plain); + assert_eq!(service_binding.bind_address_ip_type(), IpType::Plain); } #[test] @@ -219,7 +219,7 @@ mod tests { let service_binding = ServiceBinding::new(Protocol::UDP, SocketAddr::from_str("[::ffff:192.0.2.33]:6969").unwrap()).unwrap(); - assert_eq!(service_binding.bind_address_type(), AddressType::V4MappedV6); + assert_eq!(service_binding.bind_address_ip_type(), IpType::V4MappedV6); } #[test] diff --git a/packages/udp-tracker-core/src/event.rs b/packages/udp-tracker-core/src/event.rs index e9264653e..d354d3e7e 100644 --- a/packages/udp-tracker-core/src/event.rs +++ b/packages/udp-tracker-core/src/event.rs @@ -60,8 +60,8 @@ impl From for LabelSet { LabelValue::new(&connection_context.server_service_binding.bind_address().ip().to_string()), ), ( - label_name!("server_binding_address_type"), - LabelValue::new(&connection_context.server_service_binding.bind_address_type().to_string()), + label_name!("server_binding_address_ip_type"), + LabelValue::new(&connection_context.server_service_binding.bind_address_ip_type().to_string()), ), ( label_name!("server_binding_port"), diff --git a/packages/udp-tracker-server/src/event.rs b/packages/udp-tracker-server/src/event.rs index 09fc139cb..c3e736a53 100644 --- a/packages/udp-tracker-server/src/event.rs +++ b/packages/udp-tracker-server/src/event.rs @@ -119,8 +119,8 @@ impl From for LabelSet { LabelValue::new(&connection_context.server_service_binding.bind_address().ip().to_string()), ), ( - label_name!("server_binding_address_type"), - LabelValue::new(&connection_context.server_service_binding.bind_address_type().to_string()), + label_name!("server_binding_address_ip_type"), + LabelValue::new(&connection_context.server_service_binding.bind_address_ip_type().to_string()), ), ( label_name!("server_binding_port"), From 96bae36c5b9bae301f9567bc339a43b7ee80219c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 13 Jun 2025 11:19:02 +0100 Subject: [PATCH 1211/1297] feat: [#1446] add new metric label server_binding_address_ip_type Example: ``` udp_tracker_core_requests_received_total{request_kind="connect",server_binding_address_ip_family="inet",server_binding_address_ip_type="plain",server_binding_ip="0.0.0.0",server_binding_port="6969",server_binding_protocol="udp"} 1 ``` It's needed to easily filter metric samples to calculate aggregate values for a given IP family (IPv4 or IPv6). --- packages/http-tracker-core/src/event.rs | 4 ++ packages/primitives/src/service_binding.rs | 43 ++++++++++++++++++++-- packages/udp-tracker-core/src/event.rs | 4 ++ packages/udp-tracker-server/src/event.rs | 4 ++ 4 files changed, 52 insertions(+), 3 deletions(-) diff --git a/packages/http-tracker-core/src/event.rs b/packages/http-tracker-core/src/event.rs index e3d37569d..5af88c927 100644 --- a/packages/http-tracker-core/src/event.rs +++ b/packages/http-tracker-core/src/event.rs @@ -90,6 +90,10 @@ impl From for LabelSet { label_name!("server_binding_address_ip_type"), LabelValue::new(&connection_context.server.service_binding.bind_address_ip_type().to_string()), ), + ( + label_name!("server_binding_address_ip_family"), + LabelValue::new(&connection_context.server.service_binding.bind_address_ip_family().to_string()), + ), ( label_name!("server_binding_port"), LabelValue::new(&connection_context.server.service_binding.bind_address().port().to_string()), diff --git a/packages/primitives/src/service_binding.rs b/packages/primitives/src/service_binding.rs index 72d5e7f2e..74ff58e66 100644 --- a/packages/primitives/src/service_binding.rs +++ b/packages/primitives/src/service_binding.rs @@ -1,5 +1,5 @@ use std::fmt; -use std::net::SocketAddr; +use std::net::{IpAddr, SocketAddr}; use serde::{Deserialize, Serialize}; use url::Url; @@ -40,11 +40,43 @@ pub enum IpType { impl fmt::Display for IpType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let addr_type_str = match self { + let ip_type_str = match self { Self::Plain => "plain", Self::V4MappedV6 => "v4_mapped_v6", }; - write!(f, "{addr_type_str}") + write!(f, "{ip_type_str}") + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub enum IpFamily { + // IPv4 + Inet, + // IPv6 + Inet6, +} + +impl fmt::Display for IpFamily { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let ip_family_str = match self { + Self::Inet => "inet", + Self::Inet6 => "inet6", + }; + write!(f, "{ip_family_str}") + } +} + +impl From for IpFamily { + fn from(ip: IpAddr) -> Self { + if ip.is_ipv4() { + return IpFamily::Inet; + } + + if ip.is_ipv6() { + return IpFamily::Inet6; + } + + panic!("Unsupported IP address type: {ip}"); } } @@ -128,6 +160,11 @@ impl ServiceBinding { IpType::Plain } + #[must_use] + pub fn bind_address_ip_family(&self) -> IpFamily { + self.bind_address.ip().into() + } + /// # Panics /// /// It never panics because the URL is always valid. diff --git a/packages/udp-tracker-core/src/event.rs b/packages/udp-tracker-core/src/event.rs index d354d3e7e..761b809d8 100644 --- a/packages/udp-tracker-core/src/event.rs +++ b/packages/udp-tracker-core/src/event.rs @@ -63,6 +63,10 @@ impl From for LabelSet { label_name!("server_binding_address_ip_type"), LabelValue::new(&connection_context.server_service_binding.bind_address_ip_type().to_string()), ), + ( + label_name!("server_binding_address_ip_family"), + LabelValue::new(&connection_context.server_service_binding.bind_address_ip_family().to_string()), + ), ( label_name!("server_binding_port"), LabelValue::new(&connection_context.server_service_binding.bind_address().port().to_string()), diff --git a/packages/udp-tracker-server/src/event.rs b/packages/udp-tracker-server/src/event.rs index c3e736a53..5588a2b33 100644 --- a/packages/udp-tracker-server/src/event.rs +++ b/packages/udp-tracker-server/src/event.rs @@ -122,6 +122,10 @@ impl From for LabelSet { label_name!("server_binding_address_ip_type"), LabelValue::new(&connection_context.server_service_binding.bind_address_ip_type().to_string()), ), + ( + label_name!("server_binding_address_ip_family"), + LabelValue::new(&connection_context.server_service_binding.bind_address_ip_family().to_string()), + ), ( label_name!("server_binding_port"), LabelValue::new(&connection_context.server_service_binding.bind_address().port().to_string()), From 3f5216e382e40f2e65e8ca5d2ce40eb7ba4753aa Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 13 Jun 2025 11:21:05 +0100 Subject: [PATCH 1212/1297] fix: [#1446] clippy error --- packages/rest-tracker-api-core/src/statistics/services.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 3cfd6653e..4ffecb690 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -164,14 +164,14 @@ async fn get_protocol_metrics_from_labeled_metrics( .value() as u64; /* - + todo: - Add a label for `server_binding_ip_family` with value `inet` (inet/inet6) - to all metrics containing an IP address. This will allow us to distinguish + to all metrics containing an IP address. This will allow us to distinguish between IPv4 and IPv6 metrics. - Continue replacing the other metrics with the labeled metrics. - + */ // For backward compatibility we keep the `tcp4_connections_handled` and From dcfb5d5d207b9fad0aceba9aa85c4497923cb33c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 13 Jun 2025 11:51:53 +0100 Subject: [PATCH 1213/1297] refactor: [#1446] Calculate global metrics from labeled metrics --- .../src/statistics/services.rs | 309 +++++++++++++++--- .../udp-tracker-server/src/statistics/mod.rs | 16 +- 2 files changed, 274 insertions(+), 51 deletions(-) diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 4ffecb690..66bacbb06 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -5,10 +5,16 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self}; use tokio::sync::RwLock; +use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric_collection::aggregate::Sum; use torrust_tracker_metrics::metric_collection::MetricCollection; use torrust_tracker_metrics::metric_name; -use torrust_udp_tracker_server::statistics::{self as udp_server_statistics, UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL}; +use torrust_udp_tracker_server::statistics::{ + self as udp_server_statistics, UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_IPS_BANNED_TOTAL, + UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL, + UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL, + UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL, UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL, +}; use super::metrics::TorrentsMetrics; use crate::statistics::metrics::ProtocolMetrics; @@ -42,12 +48,8 @@ pub async fn get_metrics( ) .await; - let protocol_metrics_from_labeled_metrics = get_protocol_metrics_from_labeled_metrics( - ban_service.clone(), - http_stats_repository.clone(), - udp_server_stats_repository.clone(), - ) - .await; + let protocol_metrics_from_labeled_metrics = + get_protocol_metrics_from_labeled_metrics(http_stats_repository.clone(), udp_server_stats_repository.clone()).await; // todo: // We keep both metrics until we deploy to production and we can @@ -58,9 +60,9 @@ pub async fn get_metrics( let protocol_metrics = if protocol_metrics_from_global_metrics == protocol_metrics_from_labeled_metrics { protocol_metrics_from_labeled_metrics } else { - // tracing::warn!("The protocol metrics from global metrics and labeled metrics are different"); - // tracing::warn!("Global metrics: {:?}", protocol_metrics_from_global_metrics); - // tracing::warn!("Labeled metrics: {:?}", protocol_metrics_from_labeled_metrics); + tracing::warn!("The protocol metrics from global metrics and labeled metrics are different"); + tracing::warn!("Global metrics: {:?}", protocol_metrics_from_global_metrics); + tracing::warn!("Labeled metrics: {:?}", protocol_metrics_from_labeled_metrics); protocol_metrics_from_global_metrics }; @@ -132,22 +134,153 @@ async fn get_protocol_metrics( } #[allow(deprecated)] +#[allow(clippy::too_many_lines)] async fn get_protocol_metrics_from_labeled_metrics( - ban_service: Arc>, http_stats_repository: Arc, udp_server_stats_repository: Arc, ) -> ProtocolMetrics { - let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); let http_stats = http_stats_repository.get_stats().await; let udp_server_stats = udp_server_stats_repository.get_stats().await; + /* + + todo: We have to delete the global metrics from Metric types: + + - bittorrent_http_tracker_core::statistics::metrics::Metrics + - bittorrent_udp_tracker_core::statistics::metrics::Metrics + - torrust_udp_tracker_server::statistics::metrics::Metrics + + Internally only the labeled metrics should be used. + + */ + + // TCPv4 + #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] let tcp4_announces_handled = http_stats .metric_collection .sum( &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), - &[("request_kind", "announce")].into(), // todo: add label for `server_binding_ip_family` with value `inet` (inet/inet6) + &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let tcp4_scrapes_handled = http_stats + .metric_collection + .sum( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() + .value() as u64; + + // TCPv6 + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let tcp6_announces_handled = http_stats + .metric_collection + .sum( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let tcp6_scrapes_handled = http_stats + .metric_collection + .sum( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() + .value() as u64; + + // UDP + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp_requests_aborted = udp_server_stats + .metric_collection + .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &LabelSet::empty()) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp_requests_banned = udp_server_stats + .metric_collection + .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), &LabelSet::empty()) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp_banned_ips_total = udp_server_stats + .metric_collection + .sum(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &LabelSet::empty()) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp_avg_connect_processing_time_ns = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "connect")].into(), + ) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp_avg_announce_processing_time_ns = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "announce")].into(), + ) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp_avg_scrape_processing_time_ns = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "scrape")].into(), + ) + .unwrap_or_default() + .value() as u64; + + // UDPv4 + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp4_requests = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet")].into(), + ) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp4_connections_handled = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "connect")].into(), ) .unwrap_or_default() .value() as u64; @@ -158,21 +291,111 @@ async fn get_protocol_metrics_from_labeled_metrics( .metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), - &[("request_kind", "announce")].into(), // todo: add label for `server_binding_ip_family` with value `inet` (inet/inet6) + &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), ) .unwrap_or_default() .value() as u64; - /* + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp4_scrapes_handled = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp4_responses = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), + &[("server_binding_address_ip_family", "inet")].into(), + ) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp4_errors_handled = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), + &[("server_binding_address_ip_family", "inet")].into(), + ) + .unwrap_or_default() + .value() as u64; - todo: + // UDPv6 - - Add a label for `server_binding_ip_family` with value `inet` (inet/inet6) - to all metrics containing an IP address. This will allow us to distinguish - between IPv4 and IPv6 metrics. - - Continue replacing the other metrics with the labeled metrics. + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp6_requests = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6")].into(), + ) + .unwrap_or_default() + .value() as u64; - */ + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp6_connections_handled = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")].into(), + ) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp6_announces_handled = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp6_scrapes_handled = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp6_responses = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), + &[("server_binding_address_ip_family", "inet6")].into(), + ) + .unwrap_or_default() + .value() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp6_errors_handled = udp_server_stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), + &[("server_binding_address_ip_family", "inet6")].into(), + ) + .unwrap_or_default() + .value() as u64; // For backward compatibility we keep the `tcp4_connections_handled` and // `tcp6_connections_handled` metrics. They don't make sense for the HTTP @@ -181,34 +404,34 @@ async fn get_protocol_metrics_from_labeled_metrics( ProtocolMetrics { // TCPv4 - tcp4_connections_handled: tcp4_announces_handled + http_stats.tcp4_scrapes_handled, + tcp4_connections_handled: tcp4_announces_handled + tcp4_scrapes_handled, tcp4_announces_handled, - tcp4_scrapes_handled: http_stats.tcp4_scrapes_handled, + tcp4_scrapes_handled, // TCPv6 - tcp6_connections_handled: http_stats.tcp6_announces_handled + http_stats.tcp6_scrapes_handled, - tcp6_announces_handled: http_stats.tcp6_announces_handled, - tcp6_scrapes_handled: http_stats.tcp6_scrapes_handled, + tcp6_connections_handled: tcp6_announces_handled + tcp6_scrapes_handled, + tcp6_announces_handled, + tcp6_scrapes_handled, // UDP - udp_requests_aborted: udp_server_stats.udp_requests_aborted, - udp_requests_banned: udp_server_stats.udp_requests_banned, - udp_banned_ips_total: udp_banned_ips_total as u64, - udp_avg_connect_processing_time_ns: udp_server_stats.udp_avg_connect_processing_time_ns, - udp_avg_announce_processing_time_ns: udp_server_stats.udp_avg_announce_processing_time_ns, - udp_avg_scrape_processing_time_ns: udp_server_stats.udp_avg_scrape_processing_time_ns, + udp_requests_aborted, + udp_requests_banned, + udp_banned_ips_total, + udp_avg_connect_processing_time_ns, + udp_avg_announce_processing_time_ns, + udp_avg_scrape_processing_time_ns, // UDPv4 - udp4_requests: udp_server_stats.udp4_requests, - udp4_connections_handled: udp_server_stats.udp4_connections_handled, + udp4_requests, + udp4_connections_handled, udp4_announces_handled, - udp4_scrapes_handled: udp_server_stats.udp4_scrapes_handled, - udp4_responses: udp_server_stats.udp4_responses, - udp4_errors_handled: udp_server_stats.udp4_errors_handled, + udp4_scrapes_handled, + udp4_responses, + udp4_errors_handled, // UDPv6 - udp6_requests: udp_server_stats.udp6_requests, - udp6_connections_handled: udp_server_stats.udp6_connections_handled, - udp6_announces_handled: udp_server_stats.udp6_announces_handled, - udp6_scrapes_handled: udp_server_stats.udp6_scrapes_handled, - udp6_responses: udp_server_stats.udp6_responses, - udp6_errors_handled: udp_server_stats.udp6_errors_handled, + udp6_requests, + udp6_connections_handled, + udp6_announces_handled, + udp6_scrapes_handled, + udp6_responses, + udp6_errors_handled, } } diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index 3a25fd51d..b42a73f27 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -8,15 +8,15 @@ use torrust_tracker_metrics::metric::description::MetricDescription; use torrust_tracker_metrics::metric_name; use torrust_tracker_metrics::unit::Unit; -const UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL: &str = "udp_tracker_server_requests_aborted_total"; -const UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL: &str = "udp_tracker_server_requests_banned_total"; -pub(crate) const UDP_TRACKER_SERVER_IPS_BANNED_TOTAL: &str = "udp_tracker_server_ips_banned_total"; -const UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL: &str = "udp_tracker_server_connection_id_errors_total"; -const UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL: &str = "udp_tracker_server_requests_received_total"; +pub const UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL: &str = "udp_tracker_server_requests_aborted_total"; +pub const UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL: &str = "udp_tracker_server_requests_banned_total"; +pub const UDP_TRACKER_SERVER_IPS_BANNED_TOTAL: &str = "udp_tracker_server_ips_banned_total"; +pub const UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL: &str = "udp_tracker_server_connection_id_errors_total"; +pub const UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL: &str = "udp_tracker_server_requests_received_total"; pub const UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL: &str = "udp_tracker_server_requests_accepted_total"; -const UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL: &str = "udp_tracker_server_responses_sent_total"; -const UDP_TRACKER_SERVER_ERRORS_TOTAL: &str = "udp_tracker_server_errors_total"; -const UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS: &str = "udp_tracker_server_performance_avg_processing_time_ns"; +pub const UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL: &str = "udp_tracker_server_responses_sent_total"; +pub const UDP_TRACKER_SERVER_ERRORS_TOTAL: &str = "udp_tracker_server_errors_total"; +pub const UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS: &str = "udp_tracker_server_performance_avg_processing_time_ns"; #[must_use] pub fn describe_metrics() -> Metrics { From 15b802526a8741b021db5968af1b3502ad5a5986 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 16 Jun 2025 11:31:27 +0100 Subject: [PATCH 1214/1297] docs: [#1579] add tracker demo section to README --- README.md | 22 +++++++++++++++++- .../torrust-tracker-grafana-dashboard.png | Bin 0 -> 259670 bytes 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 docs/media/demo/torrust-tracker-grafana-dashboard.png diff --git a/README.md b/README.md index 33fc4a028..bb102355b 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,24 @@ - [x] Support [newTrackon][newtrackon] checks. - [x] Persistent `SQLite3` or `MySQL` Databases. +## Tracker Demo + +Experience the **Torrust Tracker** in action with our comprehensive demo environment! The [Torrust Demo][torrust-demo] repository provides a complete setup showcasing the tracker's capabilities in a real-world scenario. + +The demo takes full advantage of the tracker's powerful metrics system and seamless integration with [Prometheus][prometheus]. This allows you to monitor tracker performance, peer statistics, and system health in real-time. You can build sophisticated Grafana dashboards to visualize all aspects of your tracker's operation. + +![Sample Grafana Dashboard](./docs/media/demo/torrust-tracker-grafana-dashboard.png) + +**Demo Features:** + +- Complete Docker Compose setup. +- Pre-configured Prometheus metrics collection. +- Sample Grafana dashboards for monitoring. +- Real-time tracker statistics and performance metrics. +- Easy deployment for testing and evaluation. + +Visit the [Torrust Demo repository][torrust-demo] to get started with your own tracker instance and explore the monitoring capabilities. + ## Roadmap Core: @@ -49,7 +67,7 @@ Utils: Others: -- [ ] Support for Windows. +- [ ] Intensive testing for Windows. - [ ] Docker images for other architectures. @@ -274,3 +292,5 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [Naim A.]: https://github.com/naim94a/udpt [greatest-ape]: https://github.com/greatest-ape/aquatic [Power2All]: https://github.com/power2all +[torrust-demo]: https://github.com/torrust/torrust-demo +[prometheus]: https://prometheus.io/ diff --git a/docs/media/demo/torrust-tracker-grafana-dashboard.png b/docs/media/demo/torrust-tracker-grafana-dashboard.png new file mode 100644 index 0000000000000000000000000000000000000000..090932a8c47b5fba171bab7887f7368e70b94e7c GIT binary patch literal 259670 zcmeFYcTiK|*De|xic(ahC{3jbA~hf-ph)imq4(ZVdPhY-y3#vH3rQeI2_-Z&0@8bc zP$JR^ozUCee!qLpcjlhI?#!M0*V!`+WM_xH-}SEYtmj#Y($Y|*y!qfJ2n3>3R+7^O zfo^nzKvz3&kO60~tykQDUza?!6=gxFKBg7m#Z_zNS6Y`SL6@=}C51qshahFSm%4u0 zYt#M~x_b>5+x<2|Nosag>Z!`IvZ6ofUKl>5i?({r!&hzvb)&_M%Om+}Rp{ZhH9Wd8 zV=B%_S9#+!x=QVPDlrQx#XCtVwy$xw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K<()-%HIKTi&%) zy&9&cVNv4*BOYg!!&HEJ03l(yMq67H)PM))5{z4x+YKBKOj&7f zfXOTU8td$Ry%%q|y$?yt{E=0~Jxd^1F}-fgS)HjqvdTHAvs6jOQ&Urm9oPo^0goSe zfqaTrdY&X5?gzsw5a32vH$fy!Lw?d8g(@Nl-3t9nW# zT$oM#z@QGdSLYI}c^*}*pKBj~Cs|a_A+hdJz(Th~_*ulKkw*|5g6*86G2;-+uqCDX zLlX#A8N1oK$L3s!iHy8oG+}?HKiqn&mJDowcZi63Kg021d{5h~xVWbLo;$K%g1}&b z!khWBPK7VZy?QsQuKZigi!*kXy#wP7Q}&O)&jE7!z@o=D9Od*%iq%~fT-=NPH))*S z__^(rrFz=?`>cWSoW|y-zJM3YUo#TvbpnNqI)MDw)B-R;AP~SF@qh#_plyv8AnND7G4`;n%ESF(r zvALaH=;hhnNA$AQshl7{00tD7y{v@j(9)60`8V)@^EsnXjBY_Dw|z4 z_eE^1WCSu>e{Q-`%mTJX%v-=9q-GYB% zwA^y_s&QO5m|fEUy#2rZFem;0g{l4Lnd<+B2*3Zog^8)z(#LQ=5K0Mt`yVf=+Nx14 zut$bDQjnd|5WZkir1y=+0KbOA3kq!BhxwL`)L2HUI(}mp|1b9x`sdTLTME!mIruNH zFJ}MK2}OU@GG)qty|WhjzX;(l_5S-U8qt5K5&7fi|8ldh|0i#G31hzh{cho;#1sU) Nl;l)pOQl~2{5PVGW#j+= literal 0 HcmV?d00001 From 4cb56482ae0f866c1bc688d14bf45057e329cda5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 16 Jun 2025 11:55:48 +0100 Subject: [PATCH 1215/1297] fix: [#1579] clippy errors --- .../src/console/clients/checker/checks/udp.rs | 8 +++---- .../src/console/clients/udp/checker.rs | 2 +- .../src/v1/handlers/announce.rs | 10 ++++----- .../src/v1/handlers/scrape.rs | 10 ++++----- .../tests/server/v1/contract.rs | 2 +- .../src/v2_0_0/health_check_api.rs | 2 +- .../configuration/src/v2_0_0/http_tracker.rs | 2 +- packages/configuration/src/v2_0_0/mod.rs | 5 +---- packages/configuration/src/v2_0_0/network.rs | 2 +- .../configuration/src/v2_0_0/tracker_api.rs | 2 +- .../configuration/src/v2_0_0/udp_tracker.rs | 2 +- .../http-tracker-core/benches/helpers/sync.rs | 2 +- packages/http-tracker-core/src/event.rs | 6 ++--- .../src/services/announce.rs | 16 +++++++------- .../http-tracker-core/src/services/scrape.rs | 22 +++++++++---------- .../src/statistics/event/handler.rs | 8 +++---- packages/primitives/src/peer.rs | 6 ++--- packages/primitives/src/service_binding.rs | 2 +- .../src/swarm/coordinator.rs | 8 +++---- packages/test-helpers/src/configuration.rs | 10 ++++----- .../benches/helpers/utils.rs | 2 +- .../src/entry/peer_list.rs | 2 +- .../tests/entry/mod.rs | 2 +- .../udp-tracker-core/benches/helpers/utils.rs | 2 +- packages/udp-tracker-core/src/services/mod.rs | 4 ++-- .../src/handlers/announce.rs | 6 ++--- .../udp-tracker-server/src/handlers/mod.rs | 4 ++-- .../tests/server/contract.rs | 2 +- 28 files changed, 73 insertions(+), 78 deletions(-) diff --git a/console/tracker-client/src/console/clients/checker/checks/udp.rs b/console/tracker-client/src/console/clients/checker/checks/udp.rs index b4edb2e2c..20394d55a 100644 --- a/console/tracker-client/src/console/clients/checker/checks/udp.rs +++ b/console/tracker-client/src/console/clients/checker/checks/udp.rs @@ -117,8 +117,8 @@ mod tests { let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); assert!( - socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) - || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) + socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080) + || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 8080) ); } @@ -127,8 +127,8 @@ mod tests { let socket_addr = resolve_socket_addr(&Url::parse("udp://localhost:8080").unwrap()); assert!( - socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) - || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) + socket_addr == SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080) + || socket_addr == SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 8080) ); } } diff --git a/console/tracker-client/src/console/clients/udp/checker.rs b/console/tracker-client/src/console/clients/udp/checker.rs index bf6b49782..ded5c107e 100644 --- a/console/tracker-client/src/console/clients/udp/checker.rs +++ b/console/tracker-client/src/console/clients/udp/checker.rs @@ -116,7 +116,7 @@ impl Client { bytes_uploaded: NumberOfBytes(0i64.into()), bytes_left: NumberOfBytes(0i64.into()), event: AnnounceEvent::Started.into(), - ip_address: Ipv4Addr::new(0, 0, 0, 0).into(), + ip_address: Ipv4Addr::UNSPECIFIED.into(), key: PeerKey::new(0i32), peers_wanted: NumberOfPeers(1i32.into()), port: Port::new(port), diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index 16ff83f81..e21a485cf 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -234,7 +234,7 @@ mod tests { async fn it_should_fail_when_the_authentication_key_is_missing() { let http_core_tracker_services = initialize_private_tracker(); - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let maybe_key = None; @@ -265,7 +265,7 @@ mod tests { let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap(); - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let maybe_key = Some(unregistered_key); @@ -308,7 +308,7 @@ mod tests { let announce_request = sample_announce_request(); - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let response = handle_announce( @@ -356,7 +356,7 @@ mod tests { connection_info_socket_address: None, }; - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let response = handle_announce( @@ -401,7 +401,7 @@ mod tests { connection_info_socket_address: None, }; - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let response = handle_announce( diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index 8decfe95c..b48d6e036 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -192,7 +192,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() { - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let (core_tracker_services, core_http_tracker_services) = initialize_private_tracker(); @@ -224,7 +224,7 @@ mod tests { #[tokio::test] async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() { - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let (core_tracker_services, core_http_tracker_services) = initialize_private_tracker(); @@ -272,7 +272,7 @@ mod tests { let scrape_request = sample_scrape_request(); - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = ScrapeService::new( @@ -314,7 +314,7 @@ mod tests { connection_info_socket_address: None, }; - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = ScrapeService::new( @@ -361,7 +361,7 @@ mod tests { connection_info_socket_address: None, }; - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = ScrapeService::new( diff --git a/packages/axum-http-tracker-server/tests/server/v1/contract.rs b/packages/axum-http-tracker-server/tests/server/v1/contract.rs index d9ac2e1e1..dd80e6b59 100644 --- a/packages/axum-http-tracker-server/tests/server/v1/contract.rs +++ b/packages/axum-http-tracker-server/tests/server/v1/contract.rs @@ -748,7 +748,7 @@ mod for_all_config_modes { Client::new(*env.bind_address()) .announce( &QueryBuilder::default() - .with_peer_addr(&IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1))) + .with_peer_addr(&IpAddr::V6(Ipv6Addr::LOCALHOST)) .query(), ) .await; diff --git a/packages/configuration/src/v2_0_0/health_check_api.rs b/packages/configuration/src/v2_0_0/health_check_api.rs index 61178fa80..368f26c42 100644 --- a/packages/configuration/src/v2_0_0/health_check_api.rs +++ b/packages/configuration/src/v2_0_0/health_check_api.rs @@ -25,6 +25,6 @@ impl Default for HealthCheckApi { impl HealthCheckApi { fn default_bind_address() -> SocketAddr { - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1313) + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1313) } } diff --git a/packages/configuration/src/v2_0_0/http_tracker.rs b/packages/configuration/src/v2_0_0/http_tracker.rs index b3b21bda8..ae00257d8 100644 --- a/packages/configuration/src/v2_0_0/http_tracker.rs +++ b/packages/configuration/src/v2_0_0/http_tracker.rs @@ -37,7 +37,7 @@ impl Default for HttpTracker { impl HttpTracker { fn default_bind_address() -> SocketAddr { - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 7070) + SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 7070) } fn default_tsl_config() -> Option { diff --git a/packages/configuration/src/v2_0_0/mod.rs b/packages/configuration/src/v2_0_0/mod.rs index fd742d8d2..8391ba0e1 100644 --- a/packages/configuration/src/v2_0_0/mod.rs +++ b/packages/configuration/src/v2_0_0/mod.rs @@ -492,10 +492,7 @@ mod tests { fn configuration_should_contain_the_external_ip() { let configuration = Configuration::default(); - assert_eq!( - configuration.core.net.external_ip, - Some(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))) - ); + assert_eq!(configuration.core.net.external_ip, Some(IpAddr::V4(Ipv4Addr::UNSPECIFIED))); } #[test] diff --git a/packages/configuration/src/v2_0_0/network.rs b/packages/configuration/src/v2_0_0/network.rs index 8e53d419c..7a4668727 100644 --- a/packages/configuration/src/v2_0_0/network.rs +++ b/packages/configuration/src/v2_0_0/network.rs @@ -32,7 +32,7 @@ impl Default for Network { impl Network { #[allow(clippy::unnecessary_wraps)] fn default_external_ip() -> Option { - Some(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))) + Some(IpAddr::V4(Ipv4Addr::UNSPECIFIED)) } fn default_on_reverse_proxy() -> bool { diff --git a/packages/configuration/src/v2_0_0/tracker_api.rs b/packages/configuration/src/v2_0_0/tracker_api.rs index 2da21758b..9433c8c8c 100644 --- a/packages/configuration/src/v2_0_0/tracker_api.rs +++ b/packages/configuration/src/v2_0_0/tracker_api.rs @@ -43,7 +43,7 @@ impl Default for HttpApi { impl HttpApi { fn default_bind_address() -> SocketAddr { - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1212) + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 1212) } #[allow(clippy::unnecessary_wraps)] diff --git a/packages/configuration/src/v2_0_0/udp_tracker.rs b/packages/configuration/src/v2_0_0/udp_tracker.rs index 9918bc1fa..133018e86 100644 --- a/packages/configuration/src/v2_0_0/udp_tracker.rs +++ b/packages/configuration/src/v2_0_0/udp_tracker.rs @@ -33,7 +33,7 @@ impl Default for UdpTracker { impl UdpTracker { fn default_bind_address() -> SocketAddr { - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 6969) + SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 6969) } fn default_cookie_lifetime() -> Duration { diff --git a/packages/http-tracker-core/benches/helpers/sync.rs b/packages/http-tracker-core/benches/helpers/sync.rs index e0f022108..dbf0dac83 100644 --- a/packages/http-tracker-core/benches/helpers/sync.rs +++ b/packages/http-tracker-core/benches/helpers/sync.rs @@ -22,7 +22,7 @@ pub async fn return_announce_data_once(samples: u64) -> Duration { core_http_tracker_services.http_stats_event_sender.clone(), ); - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let start = Instant::now(); diff --git a/packages/http-tracker-core/src/event.rs b/packages/http-tracker-core/src/event.rs index 5af88c927..2a4734bfd 100644 --- a/packages/http-tracker-core/src/event.rs +++ b/packages/http-tracker-core/src/event.rs @@ -174,13 +174,13 @@ pub mod test { use crate::event::{ConnectionContext, Event}; - let remote_client_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); + let remote_client_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); let info_hash = sample_info_hash(); let event1 = Event::TcpAnnounce { connection: ConnectionContext::new( RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), - ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), ), info_hash, announcement: Peer::default(), @@ -192,7 +192,7 @@ pub mod test { ResolvedIp::FromSocketAddr(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2))), Some(8080), ), - ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), ), info_hash, announcement: Peer::default(), diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 23d589bce..8d12da713 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -349,7 +349,7 @@ mod tests { let (announce_request, client_ip_sources) = sample_announce_request_for_peer(peer); - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let announce_service = AnnounceService::new( @@ -380,7 +380,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_4_announce_event_when_the_peer_uses_ipv4() { - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let peer = sample_peer_using_ipv4(); let remote_client_ip = IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1)); @@ -442,7 +442,7 @@ mod tests { } fn peer_with_the_ipv4_loopback_ip() -> peer::Peer { - let loopback_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); + let loopback_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); let mut peer = sample_peer(); peer.peer_addr = SocketAddr::new(loopback_ip, 8080); peer @@ -453,10 +453,10 @@ mod tests { { // Tracker changes the peer IP to the tracker external IP when the peer is using the loopback IP. - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let peer = peer_with_the_ipv4_loopback_ip(); - let remote_client_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); + let remote_client_ip = IpAddr::V4(Ipv4Addr::LOCALHOST); let server_service_binding_clone = server_service_binding.clone(); let peer_copy = peer; @@ -466,7 +466,7 @@ mod tests { .expect_send() .with(predicate::function(move |event| { let mut announced_peer = peer_copy; - announced_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); + announced_peer.peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080); let mut peer_announcement = peer; peer_announcement.peer_addr = SocketAddr::new( @@ -514,7 +514,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_announce_event_when_the_peer_uses_ipv6_even_if_the_tracker_changes_the_peer_ip_to_ipv4() { - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let peer = sample_peer_using_ipv6(); let remote_client_ip = IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)); @@ -550,7 +550,7 @@ mod tests { core_http_tracker_services.http_stats_event_sender.clone(), ); - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let _announce_data = announce_service diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 1445ffcfe..4587bc90a 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -304,7 +304,7 @@ mod tests { connection_info_socket_address: Some(SocketAddr::new(original_peer_ip, 8080)), }; - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = Arc::new(ScrapeService::new( @@ -345,8 +345,7 @@ mod tests { ResolvedIp::FromSocketAddr(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1))), Some(8080), ), - ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)) - .unwrap(), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), ), })) .times(1) @@ -366,7 +365,7 @@ mod tests { connection_info_socket_address: Some(SocketAddr::new(peer_ip, 8080)), }; - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = Arc::new(ScrapeService::new( @@ -384,7 +383,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let config = configuration::ephemeral(); @@ -420,7 +419,7 @@ mod tests { connection_info_socket_address: Some(SocketAddr::new(peer_ip, 8080)), }; - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = Arc::new(ScrapeService::new( @@ -495,7 +494,7 @@ mod tests { connection_info_socket_address: Some(SocketAddr::new(original_peer_ip, 8080)), }; - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = Arc::new(ScrapeService::new( @@ -530,8 +529,7 @@ mod tests { ResolvedIp::FromSocketAddr(IpAddr::V4(Ipv4Addr::new(126, 0, 0, 1))), Some(8080), ), - ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)) - .unwrap(), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), ), })) .times(1) @@ -549,7 +547,7 @@ mod tests { connection_info_socket_address: Some(SocketAddr::new(peer_ip, 8080)), }; - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = Arc::new(ScrapeService::new( @@ -567,7 +565,7 @@ mod tests { #[tokio::test] async fn it_should_send_the_tcp_6_scrape_event_when_the_peer_uses_ipv6() { - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let config = configuration::ephemeral(); @@ -603,7 +601,7 @@ mod tests { connection_info_socket_address: Some(SocketAddr::new(peer_ip, 8080)), }; - let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070); + let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070); let server_service_binding = ServiceBinding::new(Protocol::HTTP, server_socket_addr).unwrap(); let scrape_service = Arc::new(ScrapeService::new( diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index dcb814eef..78ef24e02 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -101,7 +101,7 @@ mod tests { Event::TcpAnnounce { connection: ConnectionContext::new( RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), - ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), ), info_hash: sample_info_hash(), announcement: peer, @@ -127,7 +127,7 @@ mod tests { ResolvedIp::FromSocketAddr(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2))), Some(8080), ), - ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), ), }, &stats_repository, @@ -150,7 +150,7 @@ mod tests { Event::TcpAnnounce { connection: ConnectionContext::new( RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), - ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), ), info_hash: sample_info_hash(), announcement: peer, @@ -178,7 +178,7 @@ mod tests { ))), Some(8080), ), - ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), ), }, &stats_repository, diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index c271ee5d6..ef47f28f8 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -194,7 +194,7 @@ impl Ord for Peer { impl PartialOrd for Peer { fn partial_cmp(&self, other: &Self) -> Option { - Some(self.peer_id.cmp(&other.peer_id)) + Some(self.cmp(other)) } } @@ -517,7 +517,7 @@ pub mod fixture { pub fn seeder() -> Self { let peer = Peer { peer_id: PeerId(*b"-qB00000000000000001"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), downloaded: NumberOfBytes::new(0), @@ -621,7 +621,7 @@ pub mod fixture { fn default() -> Self { Self { peer_id: PeerId(*b"-qB00000000000000000"), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080), updated: DurationSinceUnixEpoch::new(1_669_397_478_934, 0), uploaded: NumberOfBytes::new(0), downloaded: NumberOfBytes::new(0), diff --git a/packages/primitives/src/service_binding.rs b/packages/primitives/src/service_binding.rs index 74ff58e66..c1ec308c8 100644 --- a/packages/primitives/src/service_binding.rs +++ b/packages/primitives/src/service_binding.rs @@ -115,7 +115,7 @@ pub enum Error { /// use std::net::{IpAddr, Ipv4Addr, SocketAddr}; /// use torrust_tracker_primitives::service_binding::{ServiceBinding, Protocol}; /// -/// let service_binding = ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070)).unwrap(); +/// let service_binding = ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(); /// /// assert_eq!(service_binding.url().to_string(), "http://127.0.0.1:7070/".to_string()); /// ``` diff --git a/packages/swarm-coordination-registry/src/swarm/coordinator.rs b/packages/swarm-coordination-registry/src/swarm/coordinator.rs index 1ddf3e60b..f4e94c62c 100644 --- a/packages/swarm-coordination-registry/src/swarm/coordinator.rs +++ b/packages/swarm-coordination-registry/src/swarm/coordinator.rs @@ -438,7 +438,7 @@ mod tests { let peer1 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) - .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 6969)) .build(); swarm.upsert_peer(peer1.into()).await; @@ -605,7 +605,7 @@ mod tests { let mut swarm = Coordinator::new(&sample_info_hash(), 0, None); let peer1 = PeerBuilder::default() - .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 6969)) .build(); swarm.upsert_peer(peer1.into()).await; @@ -626,13 +626,13 @@ mod tests { let peer1 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) - .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 6969)) .build(); swarm.upsert_peer(peer1.into()).await; let peer2 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000002")) - .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 6969)) .build(); swarm.upsert_peer(peer2.into()).await; diff --git a/packages/test-helpers/src/configuration.rs b/packages/test-helpers/src/configuration.rs index 986981b1f..ffe3af3b2 100644 --- a/packages/test-helpers/src/configuration.rs +++ b/packages/test-helpers/src/configuration.rs @@ -40,7 +40,7 @@ pub fn ephemeral() -> Configuration { // Ephemeral socket address for API let api_port = 0u16; let mut http_api = HttpApi { - bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), api_port), + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), api_port), ..Default::default() }; http_api.add_token("admin", "MyAccessToken"); @@ -48,12 +48,12 @@ pub fn ephemeral() -> Configuration { // Ephemeral socket address for Health Check API let health_check_api_port = 0u16; - config.health_check_api.bind_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), health_check_api_port); + config.health_check_api.bind_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), health_check_api_port); // Ephemeral socket address for UDP tracker let udp_port = 0u16; config.udp_trackers = Some(vec![UdpTracker { - bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), udp_port), + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), udp_port), cookie_lifetime: Duration::from_secs(120), tracker_usage_statistics: true, }]); @@ -61,7 +61,7 @@ pub fn ephemeral() -> Configuration { // Ephemeral socket address for HTTP tracker let http_port = 0u16; config.http_trackers = Some(vec![HttpTracker { - bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), http_port), + bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), http_port), tsl_config: None, tracker_usage_statistics: true, }]); @@ -156,7 +156,7 @@ pub fn ephemeral_with_external_ip(ip: IpAddr) -> Configuration { pub fn ephemeral_ipv6() -> Configuration { let mut cfg = ephemeral(); - let ipv6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), 0); + let ipv6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0); if let Some(ref mut http_api) = cfg.http_api { http_api.bind_address.clone_from(&ipv6); diff --git a/packages/torrent-repository-benchmarking/benches/helpers/utils.rs b/packages/torrent-repository-benchmarking/benches/helpers/utils.rs index 51b09ec0f..16ba0bf7f 100644 --- a/packages/torrent-repository-benchmarking/benches/helpers/utils.rs +++ b/packages/torrent-repository-benchmarking/benches/helpers/utils.rs @@ -9,7 +9,7 @@ use zerocopy::I64; pub const DEFAULT_PEER: Peer = Peer { peer_id: PeerId([0; 20]), - peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080), + peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080), updated: DurationSinceUnixEpoch::from_secs(0), uploaded: NumberOfBytes(I64::ZERO), downloaded: NumberOfBytes(I64::ZERO), diff --git a/packages/torrent-repository-benchmarking/src/entry/peer_list.rs b/packages/torrent-repository-benchmarking/src/entry/peer_list.rs index 33270cf27..54a560994 100644 --- a/packages/torrent-repository-benchmarking/src/entry/peer_list.rs +++ b/packages/torrent-repository-benchmarking/src/entry/peer_list.rs @@ -195,7 +195,7 @@ mod tests { let peer1 = PeerBuilder::default() .with_peer_id(&PeerId(*b"-qB00000000000000001")) - .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 6969)) + .with_peer_addr(&SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 6969)) .build(); peer_list.upsert(peer1.into()); diff --git a/packages/torrent-repository-benchmarking/tests/entry/mod.rs b/packages/torrent-repository-benchmarking/tests/entry/mod.rs index b46c05415..5cbb3b19c 100644 --- a/packages/torrent-repository-benchmarking/tests/entry/mod.rs +++ b/packages/torrent-repository-benchmarking/tests/entry/mod.rs @@ -368,7 +368,7 @@ async fn it_should_get_peers_excluding_the_client_socket( let peers = torrent.get_peers(None).await; let mut peer = **peers.first().expect("there should be a peer"); - let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8081); + let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8081); // for this test, we should not already use this socket. assert_ne!(peer.peer_addr, socket); diff --git a/packages/udp-tracker-core/benches/helpers/utils.rs b/packages/udp-tracker-core/benches/helpers/utils.rs index f04805001..1423d4bcd 100644 --- a/packages/udp-tracker-core/benches/helpers/utils.rs +++ b/packages/udp-tracker-core/benches/helpers/utils.rs @@ -10,7 +10,7 @@ pub(crate) fn sample_ipv4_remote_addr() -> SocketAddr { } pub(crate) fn sample_ipv4_socket_address() -> SocketAddr { - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080) } pub(crate) fn sample_issue_time() -> f64 { diff --git a/packages/udp-tracker-core/src/services/mod.rs b/packages/udp-tracker-core/src/services/mod.rs index 64e357b1c..56882e68f 100644 --- a/packages/udp-tracker-core/src/services/mod.rs +++ b/packages/udp-tracker-core/src/services/mod.rs @@ -32,11 +32,11 @@ pub(crate) mod tests { } pub(crate) fn sample_ipv4_socket_address() -> SocketAddr { - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080) } fn sample_ipv6_socket_address() -> SocketAddr { - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) + SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 8080) } pub(crate) fn sample_issue_time() -> f64 { diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 901a1434a..ea19611ce 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -491,7 +491,7 @@ pub(crate) mod tests { let (core_tracker_services, core_udp_tracker_services, server_udp_tracker_services) = initialize_core_tracker_services_for_public_tracker(); - let client_ip = Ipv4Addr::new(127, 0, 0, 1); + let client_ip = Ipv4Addr::LOCALHOST; let client_port = 8080; let info_hash = AquaticInfoHash([0u8; 20]); let peer_id = AquaticPeerId([255u8; 20]); @@ -869,8 +869,8 @@ pub(crate) mod tests { async fn the_peer_ip_should_be_changed_to_the_external_ip_in_the_tracker_configuration() { let config = Arc::new(TrackerConfigurationBuilder::default().with_external_ip("::126.0.0.1").into()); - let loopback_ipv4 = Ipv4Addr::new(127, 0, 0, 1); - let loopback_ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); + let loopback_ipv4 = Ipv4Addr::LOCALHOST; + let loopback_ipv6 = Ipv6Addr::LOCALHOST; let client_ip_v4 = loopback_ipv4; let client_ip_v6 = loopback_ipv6; diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 43c5bc4d5..add576a89 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -340,11 +340,11 @@ pub(crate) mod tests { } pub(crate) fn sample_ipv4_socket_address() -> SocketAddr { - SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080) + SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080) } fn sample_ipv6_socket_address() -> SocketAddr { - SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), 8080) + SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 8080) } pub(crate) fn sample_issue_time() -> f64 { diff --git a/packages/udp-tracker-server/tests/server/contract.rs b/packages/udp-tracker-server/tests/server/contract.rs index 04ad0f39d..0d9540289 100644 --- a/packages/udp-tracker-server/tests/server/contract.rs +++ b/packages/udp-tracker-server/tests/server/contract.rs @@ -167,7 +167,7 @@ mod receiving_an_announce_request { bytes_uploaded: NumberOfBytes(0i64.into()), bytes_left: NumberOfBytes(0i64.into()), event: AnnounceEvent::Started.into(), - ip_address: Ipv4Addr::new(0, 0, 0, 0).into(), + ip_address: Ipv4Addr::UNSPECIFIED.into(), key: PeerKey::new(0i32), peers_wanted: NumberOfPeers(1i32.into()), port: Port(port.into()), From 42850f3031ea4cf0d4c99f780ffcba402da369c3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 16 Jun 2025 16:10:36 +0100 Subject: [PATCH 1216/1297] refactor: [#1581] extract methods --- .../src/statistics/metrics.rs | 62 +++++++++++++++++++ .../src/statistics/services.rs | 47 ++------------ 2 files changed, 66 insertions(+), 43 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/metrics.rs b/packages/http-tracker-core/src/statistics/metrics.rs index 650194d43..5e6d70831 100644 --- a/packages/http-tracker-core/src/statistics/metrics.rs +++ b/packages/http-tracker-core/src/statistics/metrics.rs @@ -1,9 +1,13 @@ use serde::Serialize; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::aggregate::Sum; use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; +use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; +use crate::statistics::HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; + /// Metrics collected by the tracker. #[derive(Debug, Clone, PartialEq, Default, Serialize)] pub struct Metrics { @@ -49,3 +53,61 @@ impl Metrics { self.metric_collection.set_gauge(metric_name, labels, value, now) } } + +impl Metrics { + /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn tcp4_announces_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() + .value() as u64 + } + + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn tcp4_scrapes_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() + .value() as u64 + } + + /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn tcp6_announces_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() + .value() as u64 + } + + /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn tcp6_scrapes_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() + .value() as u64 + } +} diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 66bacbb06..77c04fef2 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -1,6 +1,5 @@ use std::sync::Arc; -use bittorrent_http_tracker_core::statistics::HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self}; @@ -156,51 +155,13 @@ async fn get_protocol_metrics_from_labeled_metrics( // TCPv4 - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let tcp4_announces_handled = http_stats - .metric_collection - .sum( - &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), - &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let tcp4_scrapes_handled = http_stats - .metric_collection - .sum( - &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), - &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), - ) - .unwrap_or_default() - .value() as u64; + let tcp4_announces_handled = http_stats.tcp4_announces_handled(); + let tcp4_scrapes_handled = http_stats.tcp4_scrapes_handled(); // TCPv6 - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let tcp6_announces_handled = http_stats - .metric_collection - .sum( - &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), - &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let tcp6_scrapes_handled = http_stats - .metric_collection - .sum( - &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), - &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), - ) - .unwrap_or_default() - .value() as u64; + let tcp6_announces_handled = http_stats.tcp6_announces_handled(); + let tcp6_scrapes_handled = http_stats.tcp6_scrapes_handled(); // UDP From 44c184816bb57559fa6b396e734197a459f87ec5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 16 Jun 2025 16:19:41 +0100 Subject: [PATCH 1217/1297] refactor: [#1581] remove non-labeled metrics in http-tracker-core pkg We only used labeled metric internally, althougth the APi exposes global aggregate metrics (without labels. They are calculated from the labeled metrics. --- .../tests/server/v1/contract.rs | 10 +++--- .../src/statistics/event/handler.rs | 35 +++---------------- .../src/statistics/metrics.rs | 12 ------- .../src/statistics/repository.rs | 24 ------------- .../src/statistics/services.rs | 7 ---- .../src/statistics/services.rs | 12 +++---- 6 files changed, 15 insertions(+), 85 deletions(-) diff --git a/packages/axum-http-tracker-server/tests/server/v1/contract.rs b/packages/axum-http-tracker-server/tests/server/v1/contract.rs index dd80e6b59..85792f922 100644 --- a/packages/axum-http-tracker-server/tests/server/v1/contract.rs +++ b/packages/axum-http-tracker-server/tests/server/v1/contract.rs @@ -704,7 +704,7 @@ mod for_all_config_modes { let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; - assert_eq!(stats.tcp4_announces_handled, 1); + assert_eq!(stats.tcp4_announces_handled(), 1); drop(stats); @@ -730,7 +730,7 @@ mod for_all_config_modes { let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; - assert_eq!(stats.tcp6_announces_handled, 1); + assert_eq!(stats.tcp6_announces_handled(), 1); drop(stats); @@ -755,7 +755,7 @@ mod for_all_config_modes { let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; - assert_eq!(stats.tcp6_announces_handled, 0); + assert_eq!(stats.tcp6_announces_handled(), 0); drop(stats); @@ -1149,7 +1149,7 @@ mod for_all_config_modes { let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; - assert_eq!(stats.tcp4_scrapes_handled, 1); + assert_eq!(stats.tcp4_scrapes_handled(), 1); drop(stats); @@ -1181,7 +1181,7 @@ mod for_all_config_modes { let stats = env.container.http_tracker_core_container.stats_repository.get_stats().await; - assert_eq!(stats.tcp6_scrapes_handled, 1); + assert_eq!(stats.tcp6_scrapes_handled(), 1); drop(stats); diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index 78ef24e02..a1d8d5fc2 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -1,4 +1,3 @@ -use std::net::IpAddr; use std::sync::Arc; use torrust_tracker_metrics::label::{LabelSet, LabelValue}; @@ -12,19 +11,6 @@ use crate::statistics::HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { match event { Event::TcpAnnounce { connection, .. } => { - // Global fixed metrics - - match connection.client_ip_addr() { - IpAddr::V4(_) => { - stats_repository.increase_tcp4_announces().await; - } - IpAddr::V6(_) => { - stats_repository.increase_tcp6_announces().await; - } - } - - // Extendable metrics - let mut label_set = LabelSet::from(connection); label_set.upsert(label_name!("request_kind"), LabelValue::new("announce")); @@ -42,19 +28,6 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: }; } Event::TcpScrape { connection } => { - // Global fixed metrics - - match connection.client_ip_addr() { - IpAddr::V4(_) => { - stats_repository.increase_tcp4_scrapes().await; - } - IpAddr::V6(_) => { - stats_repository.increase_tcp6_scrapes().await; - } - } - - // Extendable metrics - let mut label_set = LabelSet::from(connection); label_set.upsert(label_name!("request_kind"), LabelValue::new("scrape")); @@ -113,7 +86,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.tcp4_announces_handled, 1); + assert_eq!(stats.tcp4_announces_handled(), 1); } #[tokio::test] @@ -137,7 +110,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.tcp4_scrapes_handled, 1); + assert_eq!(stats.tcp4_scrapes_handled(), 1); } #[tokio::test] @@ -162,7 +135,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.tcp6_announces_handled, 1); + assert_eq!(stats.tcp6_announces_handled(), 1); } #[tokio::test] @@ -188,6 +161,6 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.tcp6_scrapes_handled, 1); + assert_eq!(stats.tcp6_scrapes_handled(), 1); } } diff --git a/packages/http-tracker-core/src/statistics/metrics.rs b/packages/http-tracker-core/src/statistics/metrics.rs index 5e6d70831..05acea937 100644 --- a/packages/http-tracker-core/src/statistics/metrics.rs +++ b/packages/http-tracker-core/src/statistics/metrics.rs @@ -11,18 +11,6 @@ use crate::statistics::HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; /// Metrics collected by the tracker. #[derive(Debug, Clone, PartialEq, Default, Serialize)] pub struct Metrics { - /// Total number of TCP (HTTP tracker) `announce` requests from IPv4 peers. - pub tcp4_announces_handled: u64, - - /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. - pub tcp4_scrapes_handled: u64, - - /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. - pub tcp6_announces_handled: u64, - - /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. - pub tcp6_scrapes_handled: u64, - /// A collection of metrics. pub metric_collection: MetricCollection, } diff --git a/packages/http-tracker-core/src/statistics/repository.rs b/packages/http-tracker-core/src/statistics/repository.rs index d5e718821..ea027f5c6 100644 --- a/packages/http-tracker-core/src/statistics/repository.rs +++ b/packages/http-tracker-core/src/statistics/repository.rs @@ -33,30 +33,6 @@ impl Repository { self.stats.read().await } - pub async fn increase_tcp4_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp4_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp4_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp4_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp6_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp6_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_tcp6_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.tcp6_scrapes_handled += 1; - drop(stats_lock); - } - /// # Errors /// /// This function will return an error if the metric collection fails to diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs index dbc096030..b53d6f12e 100644 --- a/packages/http-tracker-core/src/statistics/services.rs +++ b/packages/http-tracker-core/src/statistics/services.rs @@ -53,13 +53,6 @@ pub async fn get_metrics( TrackerMetrics { torrents_metrics, protocol_metrics: Metrics { - // TCPv4 - tcp4_announces_handled: stats.tcp4_announces_handled, - tcp4_scrapes_handled: stats.tcp4_scrapes_handled, - // TCPv6 - tcp6_announces_handled: stats.tcp6_announces_handled, - tcp6_scrapes_handled: stats.tcp6_scrapes_handled, - // Samples metric_collection: stats.metric_collection.clone(), }, } diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 77c04fef2..60c4a8ebd 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -101,13 +101,13 @@ async fn get_protocol_metrics( ProtocolMetrics { // TCPv4 - tcp4_connections_handled: http_stats.tcp4_announces_handled + http_stats.tcp4_scrapes_handled, - tcp4_announces_handled: http_stats.tcp4_announces_handled, - tcp4_scrapes_handled: http_stats.tcp4_scrapes_handled, + tcp4_connections_handled: http_stats.tcp4_announces_handled() + http_stats.tcp4_scrapes_handled(), + tcp4_announces_handled: http_stats.tcp4_announces_handled(), + tcp4_scrapes_handled: http_stats.tcp4_scrapes_handled(), // TCPv6 - tcp6_connections_handled: http_stats.tcp6_announces_handled + http_stats.tcp6_scrapes_handled, - tcp6_announces_handled: http_stats.tcp6_announces_handled, - tcp6_scrapes_handled: http_stats.tcp6_scrapes_handled, + tcp6_connections_handled: http_stats.tcp6_announces_handled() + http_stats.tcp6_scrapes_handled(), + tcp6_announces_handled: http_stats.tcp6_announces_handled(), + tcp6_scrapes_handled: http_stats.tcp6_scrapes_handled(), // UDP udp_requests_aborted: udp_server_stats.udp_requests_aborted, udp_requests_banned: udp_server_stats.udp_requests_banned, From a5c5a890a5af81ce1e01a978759ee42432d8490e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 16 Jun 2025 16:24:13 +0100 Subject: [PATCH 1218/1297] refactor: [#1581] remove unused code --- .../http-tracker-core/src/statistics/mod.rs | 1 - .../src/statistics/services.rs | 110 ------------------ 2 files changed, 111 deletions(-) delete mode 100644 packages/http-tracker-core/src/statistics/services.rs diff --git a/packages/http-tracker-core/src/statistics/mod.rs b/packages/http-tracker-core/src/statistics/mod.rs index b8ca865fa..3ae355471 100644 --- a/packages/http-tracker-core/src/statistics/mod.rs +++ b/packages/http-tracker-core/src/statistics/mod.rs @@ -1,7 +1,6 @@ pub mod event; pub mod metrics; pub mod repository; -pub mod services; use metrics::Metrics; use torrust_tracker_metrics::metric::description::MetricDescription; diff --git a/packages/http-tracker-core/src/statistics/services.rs b/packages/http-tracker-core/src/statistics/services.rs deleted file mode 100644 index b53d6f12e..000000000 --- a/packages/http-tracker-core/src/statistics/services.rs +++ /dev/null @@ -1,110 +0,0 @@ -//! Statistics services. -//! -//! It includes: -//! -//! - A [`factory`](crate::statistics::setup::factory) function to build the structs needed to collect the tracker metrics. -//! - A [`get_metrics`] service to get the tracker [`metrics`](crate::statistics::metrics::Metrics). -//! -//! Tracker metrics are collected using a Publisher-Subscribe pattern. -//! -//! The factory function builds two structs: -//! -//! - An statistics event [`Sender`](torrust_tracker_events::sender::Sender) -//! - An statistics [`Repository`] -//! -//! ```text -//! let (stats_event_sender, stats_repository) = factory(tracker_usage_statistics); -//! ``` -//! -//! The statistics repository is responsible for storing the metrics in memory. -//! The statistics event sender allows sending events related to metrics. -//! There is an event listener that is receiving all the events and processing them with an event handler. -//! Then, the event handler updates the metrics depending on the received event. -use std::sync::Arc; - -use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; - -use crate::statistics::metrics::Metrics; -use crate::statistics::repository::Repository; - -/// All the metrics collected by the tracker. -#[derive(Debug, PartialEq)] -pub struct TrackerMetrics { - /// Domain level metrics. - /// - /// General metrics for all torrents (number of seeders, leechers, etcetera) - pub torrents_metrics: AggregateActiveSwarmMetadata, - - /// Application level metrics. Usage statistics/metrics. - /// - /// Metrics about how the tracker is been used (number of number of http scrape requests, etcetera) - pub protocol_metrics: Metrics, -} - -/// It returns all the [`TrackerMetrics`] -pub async fn get_metrics( - in_memory_torrent_repository: Arc, - stats_repository: Arc, -) -> TrackerMetrics { - let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; - let stats = stats_repository.get_stats().await; - - TrackerMetrics { - torrents_metrics, - protocol_metrics: Metrics { - metric_collection: stats.metric_collection.clone(), - }, - } -} - -#[cfg(test)] -mod tests { - use std::sync::Arc; - - use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; - use bittorrent_tracker_core::{self}; - use torrust_tracker_configuration::Configuration; - use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; - use torrust_tracker_test_helpers::configuration; - - use crate::event::bus::EventBus; - use crate::event::sender::Broadcaster; - use crate::statistics::describe_metrics; - use crate::statistics::event::listener::run_event_listener; - use crate::statistics::repository::Repository; - use crate::statistics::services::{get_metrics, TrackerMetrics}; - - pub fn tracker_configuration() -> Configuration { - configuration::ephemeral() - } - - #[tokio::test] - async fn the_statistics_service_should_return_the_tracker_metrics() { - let config = tracker_configuration(); - - let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - - // HTTP core stats - let http_core_broadcaster = Broadcaster::default(); - let http_stats_repository = Arc::new(Repository::new()); - let http_stats_event_bus = Arc::new(EventBus::new( - config.core.tracker_usage_statistics.into(), - http_core_broadcaster.clone(), - )); - - if config.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); - } - - let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), http_stats_repository).await; - - assert_eq!( - tracker_metrics, - TrackerMetrics { - torrents_metrics: AggregateActiveSwarmMetadata::default(), - protocol_metrics: describe_metrics(), - } - ); - } -} From 0284bef1eaf87dfa0884baca89f869672574d8f6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 16 Jun 2025 16:40:44 +0100 Subject: [PATCH 1219/1297] refactor: [#1581] remove non-labeled metrics in udp-tracker-core pkg --- .../src/statistics/event/handler.rs | 51 +------- .../src/statistics/metrics.rs | 116 ++++++++++++++---- .../src/statistics/repository.rs | 36 ------ .../src/statistics/services.rs | 9 -- 4 files changed, 96 insertions(+), 116 deletions(-) diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index 039b6b0d5..e5d2b87a7 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -12,19 +12,6 @@ use crate::statistics::UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; pub async fn handle_event(event: Event, stats_repository: &Repository, now: DurationSinceUnixEpoch) { match event { Event::UdpConnect { connection: context } => { - // Global fixed metrics - - match context.client_socket_addr.ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_connections().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_connections().await; - } - } - - // Extendable metrics - let mut label_set = LabelSet::from(context); label_set.upsert(label_name!("request_kind"), LabelValue::new("connect")); @@ -37,19 +24,6 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura }; } Event::UdpAnnounce { connection: context, .. } => { - // Global fixed metrics - - match context.client_socket_addr.ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_announces().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_announces().await; - } - } - - // Extendable metrics - let mut label_set = LabelSet::from(context); label_set.upsert(label_name!("request_kind"), LabelValue::new("announce")); @@ -62,19 +36,6 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura }; } Event::UdpScrape { connection: context } => { - // Global fixed metrics - - match context.client_socket_addr.ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_scrapes().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_scrapes().await; - } - } - - // Extendable metrics - let mut label_set = LabelSet::from(context); label_set.upsert(label_name!("request_kind"), LabelValue::new("scrape")); @@ -127,7 +88,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_connections_handled, 1); + assert_eq!(stats.udp4_connections_handled(), 1); } #[tokio::test] @@ -154,7 +115,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_announces_handled, 1); + assert_eq!(stats.udp4_announces_handled(), 1); } #[tokio::test] @@ -179,7 +140,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_scrapes_handled, 1); + assert_eq!(stats.udp4_scrapes_handled(), 1); } #[tokio::test] @@ -204,7 +165,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp6_connections_handled, 1); + assert_eq!(stats.udp6_connections_handled(), 1); } #[tokio::test] @@ -231,7 +192,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp6_announces_handled, 1); + assert_eq!(stats.udp6_announces_handled(), 1); } #[tokio::test] @@ -256,6 +217,6 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp6_scrapes_handled, 1); + assert_eq!(stats.udp6_scrapes_handled(), 1); } } diff --git a/packages/udp-tracker-core/src/statistics/metrics.rs b/packages/udp-tracker-core/src/statistics/metrics.rs index e6ff8d5f6..57838c66f 100644 --- a/packages/udp-tracker-core/src/statistics/metrics.rs +++ b/packages/udp-tracker-core/src/statistics/metrics.rs @@ -1,37 +1,15 @@ use serde::Serialize; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::aggregate::Sum; use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; +use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; -/// Metrics collected by the tracker. -/// -/// - Number of connections handled -/// - Number of `announce` requests handled -/// - Number of `scrape` request handled -/// -/// These metrics are collected for each connection type: UDP and HTTP -/// and also for each IP version used by the peers: IPv4 and IPv6. +use crate::statistics::UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; + #[derive(Debug, PartialEq, Default, Serialize)] pub struct Metrics { - /// Total number of UDP (UDP tracker) connections from IPv4 peers. - pub udp4_connections_handled: u64, - - /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. - pub udp4_announces_handled: u64, - - /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. - pub udp4_scrapes_handled: u64, - - /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. - pub udp6_connections_handled: u64, - - /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. - pub udp6_announces_handled: u64, - - /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. - pub udp6_scrapes_handled: u64, - /// A collection of metrics. pub metric_collection: MetricCollection, } @@ -64,3 +42,89 @@ impl Metrics { self.metric_collection.set_gauge(metric_name, labels, value, now) } } + +impl Metrics { + /// Total number of UDP (UDP tracker) connections from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_connections_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "connect")].into(), + ) + .unwrap_or_default() + .value() as u64 + } + + /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_announces_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() + .value() as u64 + } + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_scrapes_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() + .value() as u64 + } + + /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_connections_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")].into(), + ) + .unwrap_or_default() + .value() as u64 + } + + /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_announces_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() + .value() as u64 + } + + /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_scrapes_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() + .value() as u64 + } +} diff --git a/packages/udp-tracker-core/src/statistics/repository.rs b/packages/udp-tracker-core/src/statistics/repository.rs index c68fa14f7..ceee0e369 100644 --- a/packages/udp-tracker-core/src/statistics/repository.rs +++ b/packages/udp-tracker-core/src/statistics/repository.rs @@ -33,42 +33,6 @@ impl Repository { self.stats.read().await } - pub async fn increase_udp4_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp4_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_scrapes_handled += 1; - drop(stats_lock); - } - /// # Errors /// /// This function will return an error if the metric collection fails to diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index 24d25a25c..18a80bad1 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -69,15 +69,6 @@ pub async fn get_metrics( TrackerMetrics { torrents_metrics, protocol_metrics: Metrics { - // UDPv4 - udp4_connections_handled: stats.udp4_connections_handled, - udp4_announces_handled: stats.udp4_announces_handled, - udp4_scrapes_handled: stats.udp4_scrapes_handled, - // UDPv6 - udp6_connections_handled: stats.udp6_connections_handled, - udp6_announces_handled: stats.udp6_announces_handled, - udp6_scrapes_handled: stats.udp6_scrapes_handled, - // Extendable metrics metric_collection: stats.metric_collection.clone(), }, } From f008a0a618cbbf221c6442fb32623b23157bb403 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 16 Jun 2025 16:50:26 +0100 Subject: [PATCH 1220/1297] fix: test for request counters in http-tracker-core The IP faimly related to the counter (inet or inet6) dependos on the server binding IP. If the server is listening on a inet6 IP, then inet6 lreated counters should be increased. --- packages/http-tracker-core/src/statistics/event/handler.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index a1d8d5fc2..37c7a26b5 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -123,7 +123,7 @@ mod tests { Event::TcpAnnounce { connection: ConnectionContext::new( RemoteClientAddr::new(ResolvedIp::FromSocketAddr(remote_client_ip), Some(8080)), - ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 7070)).unwrap(), ), info_hash: sample_info_hash(), announcement: peer, @@ -151,7 +151,7 @@ mod tests { ))), Some(8080), ), - ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 7070)).unwrap(), + ServiceBinding::new(Protocol::HTTP, SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), 7070)).unwrap(), ), }, &stats_repository, From 6183eba1a2bf42e7198350f2b205e76a682d9d52 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 16 Jun 2025 17:19:53 +0100 Subject: [PATCH 1221/1297] refactor: [#1581] remove non-labeled metrics in udp-tracker-server pkg --- .../src/statistics/services.rs | 248 +++------------ .../src/statistics/event/handler/error.rs | 14 +- .../event/handler/request_aborted.rs | 8 +- .../event/handler/request_accepted.rs | 41 +-- .../event/handler/request_banned.rs | 8 +- .../event/handler/request_received.rs | 13 +- .../statistics/event/handler/response_sent.rs | 14 +- .../src/statistics/metrics.rs | 294 +++++++++++++++--- .../src/statistics/repository.rs | 158 ++-------- .../src/statistics/services.rs | 37 +-- .../tests/server/contract.rs | 4 +- 11 files changed, 334 insertions(+), 505 deletions(-) diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 60c4a8ebd..e30febf00 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -4,16 +4,8 @@ use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepo use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::{self}; use tokio::sync::RwLock; -use torrust_tracker_metrics::label::LabelSet; -use torrust_tracker_metrics::metric_collection::aggregate::Sum; use torrust_tracker_metrics::metric_collection::MetricCollection; -use torrust_tracker_metrics::metric_name; -use torrust_udp_tracker_server::statistics::{ - self as udp_server_statistics, UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_IPS_BANNED_TOTAL, - UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL, - UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL, - UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL, UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL, -}; +use torrust_udp_tracker_server::statistics::{self as udp_server_statistics}; use super::metrics::TorrentsMetrics; use crate::statistics::metrics::ProtocolMetrics; @@ -109,26 +101,26 @@ async fn get_protocol_metrics( tcp6_announces_handled: http_stats.tcp6_announces_handled(), tcp6_scrapes_handled: http_stats.tcp6_scrapes_handled(), // UDP - udp_requests_aborted: udp_server_stats.udp_requests_aborted, - udp_requests_banned: udp_server_stats.udp_requests_banned, + udp_requests_aborted: udp_server_stats.udp_requests_aborted(), + udp_requests_banned: udp_server_stats.udp_requests_banned(), udp_banned_ips_total: udp_banned_ips_total as u64, - udp_avg_connect_processing_time_ns: udp_server_stats.udp_avg_connect_processing_time_ns, - udp_avg_announce_processing_time_ns: udp_server_stats.udp_avg_announce_processing_time_ns, - udp_avg_scrape_processing_time_ns: udp_server_stats.udp_avg_scrape_processing_time_ns, + udp_avg_connect_processing_time_ns: udp_server_stats.udp_avg_connect_processing_time_ns(), + udp_avg_announce_processing_time_ns: udp_server_stats.udp_avg_announce_processing_time_ns(), + udp_avg_scrape_processing_time_ns: udp_server_stats.udp_avg_scrape_processing_time_ns(), // UDPv4 - udp4_requests: udp_server_stats.udp4_requests, - udp4_connections_handled: udp_server_stats.udp4_connections_handled, - udp4_announces_handled: udp_server_stats.udp4_announces_handled, - udp4_scrapes_handled: udp_server_stats.udp4_scrapes_handled, - udp4_responses: udp_server_stats.udp4_responses, - udp4_errors_handled: udp_server_stats.udp4_errors_handled, + udp4_requests: udp_server_stats.udp4_requests(), + udp4_connections_handled: udp_server_stats.udp4_connections_handled(), + udp4_announces_handled: udp_server_stats.udp4_announces_handled(), + udp4_scrapes_handled: udp_server_stats.udp4_scrapes_handled(), + udp4_responses: udp_server_stats.udp4_responses(), + udp4_errors_handled: udp_server_stats.udp4_errors_handled(), // UDPv6 - udp6_requests: udp_server_stats.udp6_requests, - udp6_connections_handled: udp_server_stats.udp6_connections_handled, - udp6_announces_handled: udp_server_stats.udp6_announces_handled, - udp6_scrapes_handled: udp_server_stats.udp6_scrapes_handled, - udp6_responses: udp_server_stats.udp6_responses, - udp6_errors_handled: udp_server_stats.udp6_errors_handled, + udp6_requests: udp_server_stats.udp6_requests(), + udp6_connections_handled: udp_server_stats.udp6_connections_handled(), + udp6_announces_handled: udp_server_stats.udp6_announces_handled(), + udp6_scrapes_handled: udp_server_stats.udp6_scrapes_handled(), + udp6_responses: udp_server_stats.udp6_responses(), + udp6_errors_handled: udp_server_stats.udp6_errors_handled(), } } @@ -165,198 +157,30 @@ async fn get_protocol_metrics_from_labeled_metrics( // UDP - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp_requests_aborted = udp_server_stats - .metric_collection - .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &LabelSet::empty()) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp_requests_banned = udp_server_stats - .metric_collection - .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), &LabelSet::empty()) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp_banned_ips_total = udp_server_stats - .metric_collection - .sum(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &LabelSet::empty()) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp_avg_connect_processing_time_ns = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &[("request_kind", "connect")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp_avg_announce_processing_time_ns = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &[("request_kind", "announce")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp_avg_scrape_processing_time_ns = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &[("request_kind", "scrape")].into(), - ) - .unwrap_or_default() - .value() as u64; + let udp_requests_aborted = udp_server_stats.udp_requests_aborted(); + let udp_requests_banned = udp_server_stats.udp_requests_banned(); + let udp_banned_ips_total = udp_server_stats.udp_banned_ips_total(); + let udp_avg_connect_processing_time_ns = udp_server_stats.udp_avg_connect_processing_time_ns(); + let udp_avg_announce_processing_time_ns = udp_server_stats.udp_avg_announce_processing_time_ns(); + let udp_avg_scrape_processing_time_ns = udp_server_stats.udp_avg_scrape_processing_time_ns(); // UDPv4 - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp4_requests = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), - &[("server_binding_address_ip_family", "inet")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp4_connections_handled = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), - &[("server_binding_address_ip_family", "inet"), ("request_kind", "connect")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp4_announces_handled = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), - &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp4_scrapes_handled = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), - &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp4_responses = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), - &[("server_binding_address_ip_family", "inet")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp4_errors_handled = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), - &[("server_binding_address_ip_family", "inet")].into(), - ) - .unwrap_or_default() - .value() as u64; + let udp4_requests = udp_server_stats.udp4_requests(); + let udp4_connections_handled = udp_server_stats.udp4_connections_handled(); + let udp4_announces_handled = udp_server_stats.udp4_announces_handled(); + let udp4_scrapes_handled = udp_server_stats.udp4_scrapes_handled(); + let udp4_responses = udp_server_stats.udp4_responses(); + let udp4_errors_handled = udp_server_stats.udp4_errors_handled(); // UDPv6 - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp6_requests = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), - &[("server_binding_address_ip_family", "inet6")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp6_connections_handled = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), - &[("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp6_announces_handled = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), - &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp6_scrapes_handled = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), - &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp6_responses = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), - &[("server_binding_address_ip_family", "inet6")].into(), - ) - .unwrap_or_default() - .value() as u64; - - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let udp6_errors_handled = udp_server_stats - .metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), - &[("server_binding_address_ip_family", "inet6")].into(), - ) - .unwrap_or_default() - .value() as u64; + let udp6_requests = udp_server_stats.udp6_requests(); + let udp6_connections_handled = udp_server_stats.udp6_connections_handled(); + let udp6_announces_handled = udp_server_stats.udp6_announces_handled(); + let udp6_scrapes_handled = udp_server_stats.udp6_scrapes_handled(); + let udp6_responses = udp_server_stats.udp6_responses(); + let udp6_errors_handled = udp_server_stats.udp6_errors_handled(); // For backward compatibility we keep the `tcp4_connections_handled` and // `tcp6_connections_handled` metrics. They don't make sense for the HTTP diff --git a/packages/udp-tracker-server/src/statistics/event/handler/error.rs b/packages/udp-tracker-server/src/statistics/event/handler/error.rs index 7bde032fe..d83a0584d 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/error.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/error.rs @@ -14,21 +14,9 @@ pub async fn handle_event( repository: &Repository, now: DurationSinceUnixEpoch, ) { - update_global_fixed_metrics(&connection_context, repository).await; update_extendable_metrics(&connection_context, opt_udp_request_kind, error_kind, repository, now).await; } -async fn update_global_fixed_metrics(connection_context: &ConnectionContext, repository: &Repository) { - match connection_context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - repository.increase_udp4_errors().await; - } - std::net::IpAddr::V6(_) => { - repository.increase_udp6_errors().await; - } - } -} - async fn update_extendable_metrics( connection_context: &ConnectionContext, opt_udp_request_kind: Option, @@ -149,6 +137,6 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_errors_handled, 1); + assert_eq!(stats.udp4_errors_handled(), 1); } } diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs index fc701df75..19e410d5e 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs @@ -7,10 +7,6 @@ use crate::statistics::repository::Repository; use crate::statistics::UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL; pub async fn handle_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { - // Global fixed metrics - stats_repository.increase_udp_requests_aborted().await; - - // Extendable metrics match stats_repository .increase_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), @@ -58,7 +54,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp_requests_aborted, 1); + assert_eq!(stats.udp_requests_aborted(), 1); } #[tokio::test] @@ -81,6 +77,6 @@ mod tests { ) .await; let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp_requests_aborted, 1); + assert_eq!(stats.udp_requests_aborted(), 1); } } diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs index 37b668227..af92636df 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs @@ -12,35 +12,6 @@ pub async fn handle_event( stats_repository: &Repository, now: DurationSinceUnixEpoch, ) { - // Global fixed metrics - match kind { - UdpRequestKind::Connect => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_connections().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_connections().await; - } - }, - UdpRequestKind::Announce { .. } => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_announces().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_announces().await; - } - }, - UdpRequestKind::Scrape => match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_scrapes().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_scrapes().await; - } - }, - } - - // Extendable metrics let mut label_set = LabelSet::from(context); label_set.upsert(label_name!("request_kind"), LabelValue::new(&kind.to_string())); match stats_repository @@ -90,7 +61,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_connections_handled, 1); + assert_eq!(stats.udp4_connections_handled(), 1); } #[tokio::test] @@ -118,7 +89,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_announces_handled, 1); + assert_eq!(stats.udp4_announces_handled(), 1); } #[tokio::test] @@ -144,7 +115,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_scrapes_handled, 1); + assert_eq!(stats.udp4_scrapes_handled(), 1); } #[tokio::test] @@ -170,7 +141,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp6_connections_handled, 1); + assert_eq!(stats.udp6_connections_handled(), 1); } #[tokio::test] @@ -198,7 +169,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp6_announces_handled, 1); + assert_eq!(stats.udp6_announces_handled(), 1); } #[tokio::test] @@ -224,6 +195,6 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp6_scrapes_handled, 1); + assert_eq!(stats.udp6_scrapes_handled(), 1); } } diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs index ce6e179a3..8badfa137 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs @@ -7,10 +7,6 @@ use crate::statistics::repository::Repository; use crate::statistics::UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL; pub async fn handle_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { - // Global fixed metrics - stats_repository.increase_udp_requests_banned().await; - - // Extendable metrics match stats_repository .increase_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), @@ -58,7 +54,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp_requests_banned, 1); + assert_eq!(stats.udp_requests_banned(), 1); } #[tokio::test] @@ -81,6 +77,6 @@ mod tests { ) .await; let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp_requests_banned, 1); + assert_eq!(stats.udp_requests_banned(), 1); } } diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs index 89f306f6a..eced5a215 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs @@ -7,17 +7,6 @@ use crate::statistics::repository::Repository; use crate::statistics::UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL; pub async fn handle_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { - // Global fixed metrics - match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_requests().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_requests().await; - } - } - - // Extendable metrics match stats_repository .increase_counter( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), @@ -65,6 +54,6 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_requests, 1); + assert_eq!(stats.udp4_requests(), 1); } } diff --git a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs index 4e167a10e..7e05e483b 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs @@ -13,16 +13,6 @@ pub async fn handle_event( stats_repository: &Repository, now: DurationSinceUnixEpoch, ) { - // Global fixed metrics - match context.client_socket_addr().ip() { - std::net::IpAddr::V4(_) => { - stats_repository.increase_udp4_responses().await; - } - std::net::IpAddr::V6(_) => { - stats_repository.increase_udp6_responses().await; - } - } - let (result_label_value, kind_label_value) = match kind { UdpResponseKind::Ok { req_kind } => match req_kind { UdpRequestKind::Connect => { @@ -145,7 +135,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_responses, 1); + assert_eq!(stats.udp4_responses(), 1); } #[tokio::test] @@ -176,6 +166,6 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp6_responses, 1); + assert_eq!(stats.udp6_responses(), 1); } } diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index ac6250872..8eba248d2 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -1,96 +1,296 @@ use serde::Serialize; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::aggregate::Sum; use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; +use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; +use crate::statistics::{ + UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_IPS_BANNED_TOTAL, UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, + UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL, + UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL, + UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL, +}; + /// Metrics collected by the UDP tracker server. #[derive(Debug, PartialEq, Default, Serialize)] pub struct Metrics { + /// A collection of metrics. + pub metric_collection: MetricCollection, +} + +impl Metrics { + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn increase_counter( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.increment_counter(metric_name, labels, now) + } + + /// # Errors + /// + /// Returns an error if the metric does not exist and it cannot be created. + pub fn set_gauge( + &mut self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { + self.metric_collection.set_gauge(metric_name, labels, value, now) + } +} + +impl Metrics { // UDP /// Total number of UDP (UDP tracker) requests aborted. - pub udp_requests_aborted: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_requests_aborted(&self) -> u64 { + self.metric_collection + .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &LabelSet::empty()) + .unwrap_or_default() + .value() as u64 + } /// Total number of UDP (UDP tracker) requests banned. - pub udp_requests_banned: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_requests_banned(&self) -> u64 { + self.metric_collection + .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), &LabelSet::empty()) + .unwrap_or_default() + .value() as u64 + } /// Total number of banned IPs. - pub udp_banned_ips_total: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_banned_ips_total(&self) -> u64 { + self.metric_collection + .sum(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &LabelSet::empty()) + .unwrap_or_default() + .value() as u64 + } /// Average rounded time spent processing UDP connect requests. - pub udp_avg_connect_processing_time_ns: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_avg_connect_processing_time_ns(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "connect")].into(), + ) + .unwrap_or_default() + .value() as u64 + } /// Average rounded time spent processing UDP announce requests. - pub udp_avg_announce_processing_time_ns: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_avg_announce_processing_time_ns(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "announce")].into(), + ) + .unwrap_or_default() + .value() as u64 + } /// Average rounded time spent processing UDP scrape requests. - pub udp_avg_scrape_processing_time_ns: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_avg_scrape_processing_time_ns(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "scrape")].into(), + ) + .unwrap_or_default() + .value() as u64 + } // UDPv4 /// Total number of UDP (UDP tracker) requests from IPv4 peers. - pub udp4_requests: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_requests(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet")].into(), + ) + .unwrap_or_default() + .value() as u64 + } /// Total number of UDP (UDP tracker) connections from IPv4 peers. - pub udp4_connections_handled: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_connections_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "connect")].into(), + ) + .unwrap_or_default() + .value() as u64 + } /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. - pub udp4_announces_handled: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_announces_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() + .value() as u64 + } /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. - pub udp4_scrapes_handled: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_scrapes_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() + .value() as u64 + } /// Total number of UDP (UDP tracker) responses from IPv4 peers. - pub udp4_responses: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_responses(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), + &[("server_binding_address_ip_family", "inet")].into(), + ) + .unwrap_or_default() + .value() as u64 + } /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. - pub udp4_errors_handled: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp4_errors_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), + &[("server_binding_address_ip_family", "inet")].into(), + ) + .unwrap_or_default() + .value() as u64 + } // UDPv6 /// Total number of UDP (UDP tracker) requests from IPv6 peers. - pub udp6_requests: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_requests(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), + &[("server_binding_address_ip_family", "inet6")].into(), + ) + .unwrap_or_default() + .value() as u64 + } /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. - pub udp6_connections_handled: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_connections_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")].into(), + ) + .unwrap_or_default() + .value() as u64 + } /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. - pub udp6_announces_handled: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_announces_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), + ) + .unwrap_or_default() + .value() as u64 + } /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. - pub udp6_scrapes_handled: u64, + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_scrapes_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), + ) + .unwrap_or_default() + .value() as u64 + } /// Total number of UDP (UDP tracker) responses from IPv6 peers. - pub udp6_responses: u64, - - /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. - pub udp6_errors_handled: u64, - - /// A collection of metrics. - pub metric_collection: MetricCollection, -} - -impl Metrics { - /// # Errors - /// - /// Returns an error if the metric does not exist and it cannot be created. - pub fn increase_counter( - &mut self, - metric_name: &MetricName, - labels: &LabelSet, - now: DurationSinceUnixEpoch, - ) -> Result<(), Error> { - self.metric_collection.increment_counter(metric_name, labels, now) + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_responses(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), + &[("server_binding_address_ip_family", "inet6")].into(), + ) + .unwrap_or_default() + .value() as u64 } - /// # Errors - /// - /// Returns an error if the metric does not exist and it cannot be created. - pub fn set_gauge( - &mut self, - metric_name: &MetricName, - labels: &LabelSet, - value: f64, - now: DurationSinceUnixEpoch, - ) -> Result<(), Error> { - self.metric_collection.set_gauge(metric_name, labels, value, now) + /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp6_errors_handled(&self) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), + &[("server_binding_address_ip_family", "inet6")].into(), + ) + .unwrap_or_default() + .value() as u64 } } diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index 1a1db89c7..1851b78a8 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -34,70 +34,59 @@ impl Repository { self.stats.read().await } - pub async fn increase_udp_requests_aborted(&self) { + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increase the counter. + pub async fn increase_counter( + &self, + metric_name: &MetricName, + labels: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { let mut stats_lock = self.stats.write().await; - stats_lock.udp_requests_aborted += 1; - drop(stats_lock); - } - pub async fn increase_udp_requests_banned(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp_requests_banned += 1; - drop(stats_lock); - } + let result = stats_lock.increase_counter(metric_name, labels, now); - pub async fn increase_udp4_requests(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_requests += 1; drop(stats_lock); - } - pub async fn increase_udp4_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_connections_handled += 1; - drop(stats_lock); + result } - pub async fn increase_udp4_announces(&self) { + /// # Errors + /// + /// This function will return an error if the metric collection fails to + /// increase the counter. + pub async fn set_gauge( + &self, + metric_name: &MetricName, + labels: &LabelSet, + value: f64, + now: DurationSinceUnixEpoch, + ) -> Result<(), Error> { let mut stats_lock = self.stats.write().await; - stats_lock.udp4_announces_handled += 1; - drop(stats_lock); - } - pub async fn increase_udp4_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_scrapes_handled += 1; - drop(stats_lock); - } + let result = stats_lock.set_gauge(metric_name, labels, value, now); - pub async fn increase_udp4_responses(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_responses += 1; drop(stats_lock); - } - pub async fn increase_udp4_errors(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp4_errors_handled += 1; - drop(stats_lock); + result } #[allow(clippy::cast_precision_loss)] #[allow(clippy::cast_possible_truncation)] #[allow(clippy::cast_sign_loss)] pub async fn recalculate_udp_avg_connect_processing_time_ns(&self, req_processing_time: Duration) -> f64 { - let mut stats_lock = self.stats.write().await; + let stats_lock = self.stats.write().await; let req_processing_time = req_processing_time.as_nanos() as f64; - let udp_connections_handled = (stats_lock.udp4_connections_handled + stats_lock.udp6_connections_handled) as f64; + let udp_connections_handled = (stats_lock.udp4_connections_handled() + stats_lock.udp6_connections_handled()) as f64; - let previous_avg = stats_lock.udp_avg_connect_processing_time_ns; + let previous_avg = stats_lock.udp_avg_connect_processing_time_ns(); // Moving average: https://en.wikipedia.org/wiki/Moving_average let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_connections_handled; - stats_lock.udp_avg_connect_processing_time_ns = new_avg.ceil() as u64; - drop(stats_lock); new_avg @@ -107,19 +96,17 @@ impl Repository { #[allow(clippy::cast_possible_truncation)] #[allow(clippy::cast_sign_loss)] pub async fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) -> f64 { - let mut stats_lock = self.stats.write().await; + let stats_lock = self.stats.write().await; let req_processing_time = req_processing_time.as_nanos() as f64; - let udp_announces_handled = (stats_lock.udp4_announces_handled + stats_lock.udp6_announces_handled) as f64; + let udp_announces_handled = (stats_lock.udp4_announces_handled() + stats_lock.udp6_announces_handled()) as f64; - let previous_avg = stats_lock.udp_avg_announce_processing_time_ns; + let previous_avg = stats_lock.udp_avg_announce_processing_time_ns(); // Moving average: https://en.wikipedia.org/wiki/Moving_average let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_announces_handled; - stats_lock.udp_avg_announce_processing_time_ns = new_avg.ceil() as u64; - drop(stats_lock); new_avg @@ -129,95 +116,18 @@ impl Repository { #[allow(clippy::cast_possible_truncation)] #[allow(clippy::cast_sign_loss)] pub async fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) -> f64 { - let mut stats_lock = self.stats.write().await; + let stats_lock = self.stats.write().await; let req_processing_time = req_processing_time.as_nanos() as f64; - let udp_scrapes_handled = (stats_lock.udp4_scrapes_handled + stats_lock.udp6_scrapes_handled) as f64; + let udp_scrapes_handled = (stats_lock.udp4_scrapes_handled() + stats_lock.udp6_scrapes_handled()) as f64; - let previous_avg = stats_lock.udp_avg_scrape_processing_time_ns; + let previous_avg = stats_lock.udp_avg_scrape_processing_time_ns(); // Moving average: https://en.wikipedia.org/wiki/Moving_average let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_scrapes_handled; - stats_lock.udp_avg_scrape_processing_time_ns = new_avg.ceil() as u64; - drop(stats_lock); new_avg } - - pub async fn increase_udp6_requests(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_requests += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_connections(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_connections_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_announces(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_announces_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_scrapes(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_scrapes_handled += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_responses(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_responses += 1; - drop(stats_lock); - } - - pub async fn increase_udp6_errors(&self) { - let mut stats_lock = self.stats.write().await; - stats_lock.udp6_errors_handled += 1; - drop(stats_lock); - } - - /// # Errors - /// - /// This function will return an error if the metric collection fails to - /// increase the counter. - pub async fn increase_counter( - &self, - metric_name: &MetricName, - labels: &LabelSet, - now: DurationSinceUnixEpoch, - ) -> Result<(), Error> { - let mut stats_lock = self.stats.write().await; - - let result = stats_lock.increase_counter(metric_name, labels, now); - - drop(stats_lock); - - result - } - - /// # Errors - /// - /// This function will return an error if the metric collection fails to - /// increase the counter. - pub async fn set_gauge( - &self, - metric_name: &MetricName, - labels: &LabelSet, - value: f64, - now: DurationSinceUnixEpoch, - ) -> Result<(), Error> { - let mut stats_lock = self.stats.write().await; - - let result = stats_lock.set_gauge(metric_name, labels, value, now); - - drop(stats_lock); - - result - } } diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index e6e5a28f3..0eac01270 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -39,8 +39,6 @@ use std::sync::Arc; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; -use bittorrent_udp_tracker_core::services::banning::BanService; -use tokio::sync::RwLock; use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use crate::statistics::metrics::Metrics; @@ -63,38 +61,14 @@ pub struct TrackerMetrics { /// It returns all the [`TrackerMetrics`] pub async fn get_metrics( in_memory_torrent_repository: Arc, - ban_service: Arc>, stats_repository: Arc, ) -> TrackerMetrics { let torrents_metrics = in_memory_torrent_repository.get_aggregate_swarm_metadata().await; let stats = stats_repository.get_stats().await; - let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); TrackerMetrics { torrents_metrics, protocol_metrics: Metrics { - // UDP - udp_requests_aborted: stats.udp_requests_aborted, - udp_requests_banned: stats.udp_requests_banned, - udp_banned_ips_total: udp_banned_ips_total as u64, - udp_avg_connect_processing_time_ns: stats.udp_avg_connect_processing_time_ns, - udp_avg_announce_processing_time_ns: stats.udp_avg_announce_processing_time_ns, - udp_avg_scrape_processing_time_ns: stats.udp_avg_scrape_processing_time_ns, - // UDPv4 - udp4_requests: stats.udp4_requests, - udp4_connections_handled: stats.udp4_connections_handled, - udp4_announces_handled: stats.udp4_announces_handled, - udp4_scrapes_handled: stats.udp4_scrapes_handled, - udp4_responses: stats.udp4_responses, - udp4_errors_handled: stats.udp4_errors_handled, - // UDPv6 - udp6_requests: stats.udp6_requests, - udp6_connections_handled: stats.udp6_connections_handled, - udp6_announces_handled: stats.udp6_announces_handled, - udp6_scrapes_handled: stats.udp6_scrapes_handled, - udp6_responses: stats.udp6_responses, - udp6_errors_handled: stats.udp6_errors_handled, - // Extendable metrics metric_collection: stats.metric_collection.clone(), }, } @@ -106,9 +80,6 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::{self}; - use bittorrent_udp_tracker_core::services::banning::BanService; - use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; - use tokio::sync::RwLock; use torrust_tracker_primitives::swarm_metadata::AggregateActiveSwarmMetadata; use crate::statistics::describe_metrics; @@ -118,16 +89,10 @@ mod tests { #[tokio::test] async fn the_statistics_service_should_return_the_tracker_metrics() { let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); let stats_repository = Arc::new(Repository::new()); - let tracker_metrics = get_metrics( - in_memory_torrent_repository.clone(), - ban_service.clone(), - stats_repository.clone(), - ) - .await; + let tracker_metrics = get_metrics(in_memory_torrent_repository.clone(), stats_repository.clone()).await; assert_eq!( tracker_metrics, diff --git a/packages/udp-tracker-server/tests/server/contract.rs b/packages/udp-tracker-server/tests/server/contract.rs index 0d9540289..2745f3407 100644 --- a/packages/udp-tracker-server/tests/server/contract.rs +++ b/packages/udp-tracker-server/tests/server/contract.rs @@ -273,7 +273,7 @@ mod receiving_an_announce_request { .stats_repository .get_stats() .await - .udp_requests_banned; + .udp_requests_banned(); // This should return a timeout error match client.send(announce_request.into()).await { @@ -289,7 +289,7 @@ mod receiving_an_announce_request { .stats_repository .get_stats() .await - .udp_requests_banned; + .udp_requests_banned(); let udp_banned_ips_total_after = ban_service.read().await.get_banned_ips_total(); // UDP counter for banned requests should be increased by 1 From a5524825452e82a37c25462fd101d6d2023a36bb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 16 Jun 2025 17:28:22 +0100 Subject: [PATCH 1222/1297] refactor: [#1581] finished. Global metrics in API loaded from labeled metrics --- Cargo.lock | 1 - .../src/v1/context/stats/handlers.rs | 10 +-- .../src/v1/context/stats/routes.rs | 1 - packages/rest-tracker-api-core/Cargo.toml | 1 - .../src/statistics/services.rs | 81 +------------------ 5 files changed, 4 insertions(+), 90 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6f8215bbf..269f7a3a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4668,7 +4668,6 @@ dependencies = [ "torrust-tracker-swarm-coordination-registry", "torrust-tracker-test-helpers", "torrust-udp-tracker-server", - "tracing", ] [[package]] diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs index b907b861a..1b1f670a0 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/handlers.rs @@ -41,21 +41,13 @@ pub struct QueryParams { pub async fn get_stats_handler( State(state): State<( Arc, - Arc>, Arc, Arc, Arc, )>, params: Query, ) -> Response { - let metrics = get_metrics( - state.0.clone(), - state.1.clone(), - state.2.clone(), - state.3.clone(), - state.4.clone(), - ) - .await; + let metrics = get_metrics(state.0.clone(), state.1.clone(), state.2.clone(), state.3.clone()).await; match params.0.format { Some(format) => match format { diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs index c2a1466e0..2bf3776fd 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/stats/routes.rs @@ -18,7 +18,6 @@ pub fn add(prefix: &str, router: Router, http_api_container: &Arc, - ban_service: Arc>, tracker_core_stats_repository: Arc, http_stats_repository: Arc, udp_server_stats_repository: Arc, ) -> TrackerMetrics { - let protocol_metrics_from_global_metrics = get_protocol_metrics( - ban_service.clone(), - http_stats_repository.clone(), - udp_server_stats_repository.clone(), - ) - .await; - - let protocol_metrics_from_labeled_metrics = - get_protocol_metrics_from_labeled_metrics(http_stats_repository.clone(), udp_server_stats_repository.clone()).await; - - // todo: - // We keep both metrics until we deploy to production and we can - // ensure that the protocol metrics from labeled metrics are correct. - // After that we can remove the `get_protocol_metrics` function and - // use only the `get_protocol_metrics_from_labeled_metrics` function. - // And also remove the code in repositories to generate the global metrics. - let protocol_metrics = if protocol_metrics_from_global_metrics == protocol_metrics_from_labeled_metrics { - protocol_metrics_from_labeled_metrics - } else { - tracing::warn!("The protocol metrics from global metrics and labeled metrics are different"); - tracing::warn!("Global metrics: {:?}", protocol_metrics_from_global_metrics); - tracing::warn!("Labeled metrics: {:?}", protocol_metrics_from_labeled_metrics); - protocol_metrics_from_global_metrics - }; - TrackerMetrics { torrents_metrics: get_torrents_metrics(in_memory_torrent_repository, tracker_core_stats_repository).await, - protocol_metrics, + protocol_metrics: get_protocol_metrics(http_stats_repository.clone(), udp_server_stats_repository.clone()).await, } } @@ -76,57 +50,9 @@ async fn get_torrents_metrics( torrents_metrics } -#[allow(deprecated)] -async fn get_protocol_metrics( - ban_service: Arc>, - http_stats_repository: Arc, - udp_server_stats_repository: Arc, -) -> ProtocolMetrics { - let udp_banned_ips_total = ban_service.read().await.get_banned_ips_total(); - let http_stats = http_stats_repository.get_stats().await; - let udp_server_stats = udp_server_stats_repository.get_stats().await; - - // For backward compatibility we keep the `tcp4_connections_handled` and - // `tcp6_connections_handled` metrics. They don't make sense for the HTTP - // tracker, but we keep them for now. In new major versions we should remove - // them. - - ProtocolMetrics { - // TCPv4 - tcp4_connections_handled: http_stats.tcp4_announces_handled() + http_stats.tcp4_scrapes_handled(), - tcp4_announces_handled: http_stats.tcp4_announces_handled(), - tcp4_scrapes_handled: http_stats.tcp4_scrapes_handled(), - // TCPv6 - tcp6_connections_handled: http_stats.tcp6_announces_handled() + http_stats.tcp6_scrapes_handled(), - tcp6_announces_handled: http_stats.tcp6_announces_handled(), - tcp6_scrapes_handled: http_stats.tcp6_scrapes_handled(), - // UDP - udp_requests_aborted: udp_server_stats.udp_requests_aborted(), - udp_requests_banned: udp_server_stats.udp_requests_banned(), - udp_banned_ips_total: udp_banned_ips_total as u64, - udp_avg_connect_processing_time_ns: udp_server_stats.udp_avg_connect_processing_time_ns(), - udp_avg_announce_processing_time_ns: udp_server_stats.udp_avg_announce_processing_time_ns(), - udp_avg_scrape_processing_time_ns: udp_server_stats.udp_avg_scrape_processing_time_ns(), - // UDPv4 - udp4_requests: udp_server_stats.udp4_requests(), - udp4_connections_handled: udp_server_stats.udp4_connections_handled(), - udp4_announces_handled: udp_server_stats.udp4_announces_handled(), - udp4_scrapes_handled: udp_server_stats.udp4_scrapes_handled(), - udp4_responses: udp_server_stats.udp4_responses(), - udp4_errors_handled: udp_server_stats.udp4_errors_handled(), - // UDPv6 - udp6_requests: udp_server_stats.udp6_requests(), - udp6_connections_handled: udp_server_stats.udp6_connections_handled(), - udp6_announces_handled: udp_server_stats.udp6_announces_handled(), - udp6_scrapes_handled: udp_server_stats.udp6_scrapes_handled(), - udp6_responses: udp_server_stats.udp6_responses(), - udp6_errors_handled: udp_server_stats.udp6_errors_handled(), - } -} - #[allow(deprecated)] #[allow(clippy::too_many_lines)] -async fn get_protocol_metrics_from_labeled_metrics( +async fn get_protocol_metrics( http_stats_repository: Arc, udp_server_stats_repository: Arc, ) -> ProtocolMetrics { @@ -307,7 +233,7 @@ mod tests { let tracker_core_container = TrackerCoreContainer::initialize_from(&core_config, &swarm_coordination_registry_container.clone()); - let ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); + let _ban_service = Arc::new(RwLock::new(BanService::new(MAX_CONNECTION_ID_ERRORS_PER_IP))); // HTTP core stats let http_core_broadcaster = Broadcaster::default(); @@ -326,7 +252,6 @@ mod tests { let tracker_metrics = get_metrics( tracker_core_container.in_memory_torrent_repository.clone(), - ban_service.clone(), tracker_core_container.stats_repository.clone(), http_stats_repository.clone(), udp_server_stats_repository.clone(), From 0d9f88337a5117fba523e7f2cb84a70d46af9444 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 17 Jun 2025 08:06:25 +0100 Subject: [PATCH 1223/1297] refactor(metrics): [#1580] convert Sum trait to use associated types for mathematically correct return types - Replace AggregateValue return type with associated Output type in Sum trait - Counter metrics now return u64 (preserving integer precision) - Gauge metrics now return f64 (avoiding unnecessary wrapper type) - Update all test cases to expect primitive types instead of AggregateValue - Convert primitive results to AggregateValue at collection level for backward compatibility - Use proper floating-point comparison in gauge tests with epsilon tolerance This change ensures each aggregate function returns the mathematically appropriate type while maintaining API compatibility for metric collections. --- packages/metrics/src/metric/aggregate/sum.rs | 81 +++++++++---------- .../src/metric_collection/aggregate.rs | 11 ++- 2 files changed, 47 insertions(+), 45 deletions(-) diff --git a/packages/metrics/src/metric/aggregate/sum.rs b/packages/metrics/src/metric/aggregate/sum.rs index f08ea7d55..30c2819b7 100644 --- a/packages/metrics/src/metric/aggregate/sum.rs +++ b/packages/metrics/src/metric/aggregate/sum.rs @@ -1,37 +1,34 @@ -use crate::aggregate::AggregateValue; use crate::counter::Counter; use crate::gauge::Gauge; use crate::label::LabelSet; use crate::metric::Metric; pub trait Sum { - fn sum(&self, label_set_criteria: &LabelSet) -> AggregateValue; + type Output; + fn sum(&self, label_set_criteria: &LabelSet) -> Self::Output; } impl Sum for Metric { - #[allow(clippy::cast_precision_loss)] - fn sum(&self, label_set_criteria: &LabelSet) -> AggregateValue { - let sum: f64 = self - .sample_collection + type Output = u64; + + fn sum(&self, label_set_criteria: &LabelSet) -> Self::Output { + self.sample_collection .iter() .filter(|(label_set, _measurement)| label_set.matches(label_set_criteria)) - .map(|(_label_set, measurement)| measurement.value().primitive() as f64) - .sum(); - - sum.into() + .map(|(_label_set, measurement)| measurement.value().primitive()) + .sum() } } impl Sum for Metric { - fn sum(&self, label_set_criteria: &LabelSet) -> AggregateValue { - let sum: f64 = self - .sample_collection + type Output = f64; + + fn sum(&self, label_set_criteria: &LabelSet) -> Self::Output { + self.sample_collection .iter() .filter(|(label_set, _measurement)| label_set.matches(label_set_criteria)) .map(|(_label_set, measurement)| measurement.value().primitive()) - .sum(); - - sum.into() + .sum() } } @@ -40,7 +37,6 @@ mod tests { use torrust_tracker_primitives::DurationSinceUnixEpoch; - use crate::aggregate::AggregateValue; use crate::counter::Counter; use crate::gauge::Gauge; use crate::label::LabelSet; @@ -83,14 +79,14 @@ mod tests { } } - fn counter_cases() -> Vec<(Metric, LabelSet, AggregateValue)> { + fn counter_cases() -> Vec<(Metric, LabelSet, u64)> { // (metric, label set criteria, expected_aggregate_value) vec![ // Metric with one sample without label set ( MetricBuilder::default().with_sample(1.into(), &LabelSet::empty()).build(), LabelSet::empty(), - 1.0.into(), + 1, ), // Metric with one sample with a label set ( @@ -98,7 +94,7 @@ mod tests { .with_sample(1.into(), &[("l1", "l1_value")].into()) .build(), [("l1", "l1_value")].into(), - 1.0.into(), + 1, ), // Metric with two samples, different label sets, sum all ( @@ -107,7 +103,7 @@ mod tests { .with_sample(2.into(), &[("l2", "l2_value")].into()) .build(), LabelSet::empty(), - 3.0.into(), + 3, ), // Metric with two samples, different label sets, sum one ( @@ -116,7 +112,7 @@ mod tests { .with_sample(2.into(), &[("l2", "l2_value")].into()) .build(), [("l1", "l1_value")].into(), - 1.0.into(), + 1, ), // Metric with two samples, same label key, different label values, sum by key ( @@ -125,7 +121,7 @@ mod tests { .with_sample(2.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) .build(), [("l1", "l1_value")].into(), - 3.0.into(), + 3, ), // Metric with two samples, different label values, sum by subkey ( @@ -134,17 +130,17 @@ mod tests { .with_sample(2.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) .build(), [("la", "la_value")].into(), - 1.0.into(), + 1, ), // Edge: Metric with no samples at all - (MetricBuilder::default().build(), LabelSet::empty(), 0.0.into()), + (MetricBuilder::default().build(), LabelSet::empty(), 0), // Edge: Metric with samples but no matching labels ( MetricBuilder::default() .with_sample(5.into(), &[("foo", "bar")].into()) .build(), [("not", "present")].into(), - 0.0.into(), + 0, ), // Edge: Metric with zero value ( @@ -152,7 +148,7 @@ mod tests { .with_sample(0.into(), &[("l3", "l3_value")].into()) .build(), [("l3", "l3_value")].into(), - 0.0.into(), + 0, ), // Edge: Metric with a very large value ( @@ -160,20 +156,19 @@ mod tests { .with_sample(u64::MAX.into(), &LabelSet::empty()) .build(), LabelSet::empty(), - #[allow(clippy::cast_precision_loss)] - (u64::MAX as f64).into(), + u64::MAX, ), ] } - fn gauge_cases() -> Vec<(Metric, LabelSet, AggregateValue)> { + fn gauge_cases() -> Vec<(Metric, LabelSet, f64)> { // (metric, label set criteria, expected_aggregate_value) vec![ // Metric with one sample without label set ( MetricBuilder::default().with_sample(1.0.into(), &LabelSet::empty()).build(), LabelSet::empty(), - 1.0.into(), + 1.0, ), // Metric with one sample with a label set ( @@ -181,7 +176,7 @@ mod tests { .with_sample(1.0.into(), &[("l1", "l1_value")].into()) .build(), [("l1", "l1_value")].into(), - 1.0.into(), + 1.0, ), // Metric with two samples, different label sets, sum all ( @@ -190,7 +185,7 @@ mod tests { .with_sample(2.0.into(), &[("l2", "l2_value")].into()) .build(), LabelSet::empty(), - 3.0.into(), + 3.0, ), // Metric with two samples, different label sets, sum one ( @@ -199,7 +194,7 @@ mod tests { .with_sample(2.0.into(), &[("l2", "l2_value")].into()) .build(), [("l1", "l1_value")].into(), - 1.0.into(), + 1.0, ), // Metric with two samples, same label key, different label values, sum by key ( @@ -208,7 +203,7 @@ mod tests { .with_sample(2.0.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) .build(), [("l1", "l1_value")].into(), - 3.0.into(), + 3.0, ), // Metric with two samples, different label values, sum by subkey ( @@ -217,17 +212,17 @@ mod tests { .with_sample(2.0.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) .build(), [("la", "la_value")].into(), - 1.0.into(), + 1.0, ), // Edge: Metric with no samples at all - (MetricBuilder::default().build(), LabelSet::empty(), 0.0.into()), + (MetricBuilder::default().build(), LabelSet::empty(), 0.0), // Edge: Metric with samples but no matching labels ( MetricBuilder::default() .with_sample(5.0.into(), &[("foo", "bar")].into()) .build(), [("not", "present")].into(), - 0.0.into(), + 0.0, ), // Edge: Metric with zero value ( @@ -235,7 +230,7 @@ mod tests { .with_sample(0.0.into(), &[("l3", "l3_value")].into()) .build(), [("l3", "l3_value")].into(), - 0.0.into(), + 0.0, ), // Edge: Metric with negative values ( @@ -244,7 +239,7 @@ mod tests { .with_sample(3.0.into(), &[("l5", "l5_value")].into()) .build(), LabelSet::empty(), - 1.0.into(), + 1.0, ), // Edge: Metric with a very large value ( @@ -252,7 +247,7 @@ mod tests { .with_sample(f64::MAX.into(), &LabelSet::empty()) .build(), LabelSet::empty(), - f64::MAX.into(), + f64::MAX, ), ] } @@ -274,8 +269,8 @@ mod tests { for (idx, (metric, criteria, expected_value)) in gauge_cases().iter().enumerate() { let sum = metric.sum(criteria); - assert_eq!( - sum, *expected_value, + assert!( + (sum - expected_value).abs() <= f64::EPSILON, "at case {idx}, expected sum to be {expected_value}, got {sum}" ); } diff --git a/packages/metrics/src/metric_collection/aggregate.rs b/packages/metrics/src/metric_collection/aggregate.rs index 7fd744d92..a1afa30da 100644 --- a/packages/metrics/src/metric_collection/aggregate.rs +++ b/packages/metrics/src/metric_collection/aggregate.rs @@ -22,13 +22,20 @@ impl Sum for MetricCollection { impl Sum for MetricKindCollection { fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { - self.metrics.get(metric_name).map(|metric| metric.sum(label_set_criteria)) + self.metrics.get(metric_name).map(|metric| { + let sum: u64 = metric.sum(label_set_criteria); + #[allow(clippy::cast_precision_loss)] + AggregateValue::new(sum as f64) + }) } } impl Sum for MetricKindCollection { fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { - self.metrics.get(metric_name).map(|metric| metric.sum(label_set_criteria)) + self.metrics.get(metric_name).map(|metric| { + let sum: f64 = metric.sum(label_set_criteria); + AggregateValue::new(sum) + }) } } From db6b491edc2ecf219a88fa6b85c9e6de100520e1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 17 Jun 2025 08:14:12 +0100 Subject: [PATCH 1224/1297] refactor(metrics): [#1580] add associated types to collection-level Sum trait - Convert collection Sum trait from fixed return type to associated Output type - MetricKindCollection now returns Option preserving integer precision - MetricKindCollection now returns Option for direct float access - MetricCollection maintains Option for backward compatibility - Simplify implementation by directly delegating to metric-level sum methods - Remove intermediate conversions in metric kind collections This completes the associated types pattern across both metric-level and collection-level Sum traits, allowing each implementation to return the most mathematically appropriate type while maintaining API compatibility. --- .../src/metric_collection/aggregate.rs | 35 +++++++++++-------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/packages/metrics/src/metric_collection/aggregate.rs b/packages/metrics/src/metric_collection/aggregate.rs index a1afa30da..8bda278d4 100644 --- a/packages/metrics/src/metric_collection/aggregate.rs +++ b/packages/metrics/src/metric_collection/aggregate.rs @@ -7,35 +7,40 @@ use crate::metric::MetricName; use crate::metric_collection::{MetricCollection, MetricKindCollection}; pub trait Sum { - fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option; + type Output; + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Self::Output; } impl Sum for MetricCollection { - fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + type Output = Option; + + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Self::Output { if let Some(value) = self.counters.sum(metric_name, label_set_criteria) { - return Some(value); + #[allow(clippy::cast_precision_loss)] + return Some(AggregateValue::new(value as f64)); + } + + if let Some(value) = self.gauges.sum(metric_name, label_set_criteria) { + return Some(AggregateValue::new(value)); } - self.gauges.sum(metric_name, label_set_criteria) + None } } impl Sum for MetricKindCollection { - fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { - self.metrics.get(metric_name).map(|metric| { - let sum: u64 = metric.sum(label_set_criteria); - #[allow(clippy::cast_precision_loss)] - AggregateValue::new(sum as f64) - }) + type Output = Option; + + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Self::Output { + self.metrics.get(metric_name).map(|metric| metric.sum(label_set_criteria)) } } impl Sum for MetricKindCollection { - fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { - self.metrics.get(metric_name).map(|metric| { - let sum: f64 = metric.sum(label_set_criteria); - AggregateValue::new(sum) - }) + type Output = Option; + + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Self::Output { + self.metrics.get(metric_name).map(|metric| metric.sum(label_set_criteria)) } } From 00ac210a90258afc2e5ee06368bb90e9a045731d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 17 Jun 2025 08:40:03 +0100 Subject: [PATCH 1225/1297] refactor(metrics): [#1580] remove AggregateValue wrapper, return primitive types from aggregates - Remove AggregateValue struct and its entire module from metrics package - Simplify Sum trait in metric collections to return Option directly - Update MetricKindCollection implementations to cast counter values to f64 - Remove AggregateValue dependencies from http-tracker-core, udp-tracker-core, and udp-tracker-server - Eliminate unnecessary wrapper overhead in aggregate operations - Maintain backward compatibility by converting all aggregate results to f64 This change completes the metrics package refactoring by removing the generic AggregateValue wrapper that added no value when aggregate functions can return mathematically appropriate primitive types directly. --- .../src/statistics/metrics.rs | 12 +- packages/metrics/src/aggregate.rs | 143 ------------------ packages/metrics/src/lib.rs | 1 - .../src/metric_collection/aggregate.rs | 34 ++--- .../src/statistics/metrics.rs | 18 +-- .../src/statistics/metrics.rs | 54 +++---- 6 files changed, 42 insertions(+), 220 deletions(-) delete mode 100644 packages/metrics/src/aggregate.rs diff --git a/packages/http-tracker-core/src/statistics/metrics.rs b/packages/http-tracker-core/src/statistics/metrics.rs index 05acea937..6aede8359 100644 --- a/packages/http-tracker-core/src/statistics/metrics.rs +++ b/packages/http-tracker-core/src/statistics/metrics.rs @@ -53,8 +53,7 @@ impl Metrics { &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of TCP (HTTP tracker) `scrape` requests from IPv4 peers. @@ -67,8 +66,7 @@ impl Metrics { &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of TCP (HTTP tracker) `announce` requests from IPv6 peers. @@ -81,8 +79,7 @@ impl Metrics { &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of TCP (HTTP tracker) `scrape` requests from IPv6 peers. @@ -95,7 +92,6 @@ impl Metrics { &metric_name!(HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } } diff --git a/packages/metrics/src/aggregate.rs b/packages/metrics/src/aggregate.rs deleted file mode 100644 index 39b760fca..000000000 --- a/packages/metrics/src/aggregate.rs +++ /dev/null @@ -1,143 +0,0 @@ -use derive_more::Display; - -#[derive(Debug, Display, Clone, Copy, PartialEq, Default)] -pub struct AggregateValue(f64); - -impl AggregateValue { - #[must_use] - pub fn new(value: f64) -> Self { - Self(value) - } - - #[must_use] - pub fn value(&self) -> f64 { - self.0 - } -} - -impl From for AggregateValue { - fn from(value: f64) -> Self { - Self(value) - } -} - -impl From for f64 { - fn from(value: AggregateValue) -> Self { - value.0 - } -} - -#[cfg(test)] -mod tests { - use approx::assert_relative_eq; - - use super::*; - - #[test] - fn it_should_be_created_with_new() { - let value = AggregateValue::new(42.5); - assert_relative_eq!(value.value(), 42.5); - } - - #[test] - fn it_should_return_the_inner_value() { - let value = AggregateValue::new(123.456); - assert_relative_eq!(value.value(), 123.456); - } - - #[test] - fn it_should_handle_zero_value() { - let value = AggregateValue::new(0.0); - assert_relative_eq!(value.value(), 0.0); - } - - #[test] - fn it_should_handle_negative_values() { - let value = AggregateValue::new(-42.5); - assert_relative_eq!(value.value(), -42.5); - } - - #[test] - fn it_should_handle_infinity() { - let value = AggregateValue::new(f64::INFINITY); - assert_relative_eq!(value.value(), f64::INFINITY); - } - - #[test] - fn it_should_handle_nan() { - let value = AggregateValue::new(f64::NAN); - assert!(value.value().is_nan()); - } - - #[test] - fn it_should_be_created_from_f64() { - let value: AggregateValue = 42.5.into(); - assert_relative_eq!(value.value(), 42.5); - } - - #[test] - fn it_should_convert_to_f64() { - let value = AggregateValue::new(42.5); - let f64_value: f64 = value.into(); - assert_relative_eq!(f64_value, 42.5); - } - - #[test] - fn it_should_be_displayable() { - let value = AggregateValue::new(42.5); - assert_eq!(value.to_string(), "42.5"); - } - - #[test] - fn it_should_be_debuggable() { - let value = AggregateValue::new(42.5); - let debug_string = format!("{value:?}"); - assert_eq!(debug_string, "AggregateValue(42.5)"); - } - - #[test] - fn it_should_be_cloneable() { - let value = AggregateValue::new(42.5); - let cloned_value = value; - assert_eq!(value, cloned_value); - } - - #[test] - fn it_should_be_copyable() { - let value = AggregateValue::new(42.5); - let copied_value = value; - assert_eq!(value, copied_value); - } - - #[test] - fn it_should_support_equality_comparison() { - let value1 = AggregateValue::new(42.5); - let value2 = AggregateValue::new(42.5); - let value3 = AggregateValue::new(43.0); - - assert_eq!(value1, value2); - assert_ne!(value1, value3); - } - - #[test] - fn it_should_handle_special_float_values_in_equality() { - let nan1 = AggregateValue::new(f64::NAN); - let nan2 = AggregateValue::new(f64::NAN); - let infinity = AggregateValue::new(f64::INFINITY); - let neg_infinity = AggregateValue::new(f64::NEG_INFINITY); - - // NaN is not equal to itself in IEEE 754 - assert_ne!(nan1, nan2); - assert_eq!(infinity, AggregateValue::new(f64::INFINITY)); - assert_eq!(neg_infinity, AggregateValue::new(f64::NEG_INFINITY)); - assert_ne!(infinity, neg_infinity); - } - - #[test] - fn it_should_handle_conversion_roundtrip() { - let original_value = 42.5; - let aggregate_value = AggregateValue::from(original_value); - let converted_back: f64 = aggregate_value.into(); - assert_relative_eq!(original_value, converted_back); - } -} diff --git a/packages/metrics/src/lib.rs b/packages/metrics/src/lib.rs index c53e9dd02..997cd3c8c 100644 --- a/packages/metrics/src/lib.rs +++ b/packages/metrics/src/lib.rs @@ -1,4 +1,3 @@ -pub mod aggregate; pub mod counter; pub mod gauge; pub mod label; diff --git a/packages/metrics/src/metric_collection/aggregate.rs b/packages/metrics/src/metric_collection/aggregate.rs index 8bda278d4..62b2ca498 100644 --- a/packages/metrics/src/metric_collection/aggregate.rs +++ b/packages/metrics/src/metric_collection/aggregate.rs @@ -1,4 +1,3 @@ -use crate::aggregate::AggregateValue; use crate::counter::Counter; use crate::gauge::Gauge; use crate::label::LabelSet; @@ -7,21 +6,17 @@ use crate::metric::MetricName; use crate::metric_collection::{MetricCollection, MetricKindCollection}; pub trait Sum { - type Output; - fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Self::Output; + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option; } impl Sum for MetricCollection { - type Output = Option; - - fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Self::Output { + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { if let Some(value) = self.counters.sum(metric_name, label_set_criteria) { - #[allow(clippy::cast_precision_loss)] - return Some(AggregateValue::new(value as f64)); + return Some(value); } if let Some(value) = self.gauges.sum(metric_name, label_set_criteria) { - return Some(AggregateValue::new(value)); + return Some(value); } None @@ -29,17 +24,16 @@ impl Sum for MetricCollection { } impl Sum for MetricKindCollection { - type Output = Option; - - fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Self::Output { - self.metrics.get(metric_name).map(|metric| metric.sum(label_set_criteria)) + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + #[allow(clippy::cast_precision_loss)] + self.metrics + .get(metric_name) + .map(|metric| metric.sum(label_set_criteria) as f64) } } impl Sum for MetricKindCollection { - type Output = Option; - - fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Self::Output { + fn sum(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { self.metrics.get(metric_name).map(|metric| metric.sum(label_set_criteria)) } } @@ -81,10 +75,10 @@ mod tests { ) .unwrap(); - assert_eq!(collection.sum(&metric_name, &LabelSet::empty()), Some(2.0.into())); + assert_eq!(collection.sum(&metric_name, &LabelSet::empty()), Some(2.0)); assert_eq!( collection.sum(&metric_name, &(label_name!("label_1"), LabelValue::new("value_1")).into()), - Some(1.0.into()) + Some(1.0) ); } @@ -114,10 +108,10 @@ mod tests { ) .unwrap(); - assert_eq!(collection.sum(&metric_name, &LabelSet::empty()), Some(2.0.into())); + assert_eq!(collection.sum(&metric_name, &LabelSet::empty()), Some(2.0)); assert_eq!( collection.sum(&metric_name, &(label_name!("label_1"), LabelValue::new("value_1")).into()), - Some(1.0.into()) + Some(1.0) ); } } diff --git a/packages/udp-tracker-core/src/statistics/metrics.rs b/packages/udp-tracker-core/src/statistics/metrics.rs index 57838c66f..db83c1c1d 100644 --- a/packages/udp-tracker-core/src/statistics/metrics.rs +++ b/packages/udp-tracker-core/src/statistics/metrics.rs @@ -54,8 +54,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &[("server_binding_address_ip_family", "inet"), ("request_kind", "connect")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. @@ -68,8 +67,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. @@ -82,8 +80,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. @@ -96,8 +93,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &[("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. @@ -110,8 +106,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. @@ -124,7 +119,6 @@ impl Metrics { &metric_name!(UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL), &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } } diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index 8eba248d2..d3f273665 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -56,8 +56,7 @@ impl Metrics { pub fn udp_requests_aborted(&self) -> u64 { self.metric_collection .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &LabelSet::empty()) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) requests banned. @@ -67,8 +66,7 @@ impl Metrics { pub fn udp_requests_banned(&self) -> u64 { self.metric_collection .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), &LabelSet::empty()) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of banned IPs. @@ -78,8 +76,7 @@ impl Metrics { pub fn udp_banned_ips_total(&self) -> u64 { self.metric_collection .sum(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &LabelSet::empty()) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Average rounded time spent processing UDP connect requests. @@ -92,8 +89,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), &[("request_kind", "connect")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Average rounded time spent processing UDP announce requests. @@ -106,8 +102,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), &[("request_kind", "announce")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Average rounded time spent processing UDP scrape requests. @@ -120,8 +115,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), &[("request_kind", "scrape")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } // UDPv4 @@ -135,8 +129,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &[("server_binding_address_ip_family", "inet")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) connections from IPv4 peers. @@ -149,8 +142,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &[("server_binding_address_ip_family", "inet"), ("request_kind", "connect")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) `announce` requests from IPv4 peers. @@ -163,8 +155,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &[("server_binding_address_ip_family", "inet"), ("request_kind", "announce")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) `scrape` requests from IPv4 peers. @@ -177,8 +168,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &[("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) responses from IPv4 peers. @@ -191,8 +181,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &[("server_binding_address_ip_family", "inet")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) `error` requests from IPv4 peers. @@ -205,8 +194,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &[("server_binding_address_ip_family", "inet")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } // UDPv6 @@ -220,8 +208,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &[("server_binding_address_ip_family", "inet6")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) `connection` requests from IPv6 peers. @@ -234,8 +221,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &[("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) `announce` requests from IPv6 peers. @@ -248,8 +234,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &[("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) `scrape` requests from IPv6 peers. @@ -262,8 +247,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &[("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) responses from IPv6 peers. @@ -276,8 +260,7 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &[("server_binding_address_ip_family", "inet6")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } /// Total number of UDP (UDP tracker) `error` requests from IPv6 peers. @@ -290,7 +273,6 @@ impl Metrics { &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &[("server_binding_address_ip_family", "inet6")].into(), ) - .unwrap_or_default() - .value() as u64 + .unwrap_or_default() as u64 } } From dfd950d715f253ff4740b518564f62ec35977bdb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 17 Jun 2025 08:55:50 +0100 Subject: [PATCH 1226/1297] refactor(metrics): [#1580] reorganize metric collection aggregates into submodules - Move metric_collection/aggregate.rs to aggregate/sum.rs submodule - Create proper module structure for aggregate operations - Update import paths in http-tracker-core, udp-tracker-core, and udp-tracker-server - Change imports from `aggregate::Sum` to `aggregate::sum::Sum` - Maintain the same Sum trait functionality with cleaner module organization This reorganization prepares for potential future aggregate operations beyond just sum while keeping the existing Sum trait API intact. --- packages/http-tracker-core/src/statistics/metrics.rs | 2 +- packages/metrics/src/metric_collection/aggregate/mod.rs | 1 + .../src/metric_collection/{aggregate.rs => aggregate/sum.rs} | 2 +- packages/udp-tracker-core/src/statistics/metrics.rs | 2 +- packages/udp-tracker-server/src/statistics/metrics.rs | 2 +- 5 files changed, 5 insertions(+), 4 deletions(-) create mode 100644 packages/metrics/src/metric_collection/aggregate/mod.rs rename packages/metrics/src/metric_collection/{aggregate.rs => aggregate/sum.rs} (98%) diff --git a/packages/http-tracker-core/src/statistics/metrics.rs b/packages/http-tracker-core/src/statistics/metrics.rs index 6aede8359..00d09b803 100644 --- a/packages/http-tracker-core/src/statistics/metrics.rs +++ b/packages/http-tracker-core/src/statistics/metrics.rs @@ -1,7 +1,7 @@ use serde::Serialize; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; -use torrust_tracker_metrics::metric_collection::aggregate::Sum; +use torrust_tracker_metrics::metric_collection::aggregate::sum::Sum; use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; diff --git a/packages/metrics/src/metric_collection/aggregate/mod.rs b/packages/metrics/src/metric_collection/aggregate/mod.rs new file mode 100644 index 000000000..dce785d95 --- /dev/null +++ b/packages/metrics/src/metric_collection/aggregate/mod.rs @@ -0,0 +1 @@ +pub mod sum; diff --git a/packages/metrics/src/metric_collection/aggregate.rs b/packages/metrics/src/metric_collection/aggregate/sum.rs similarity index 98% rename from packages/metrics/src/metric_collection/aggregate.rs rename to packages/metrics/src/metric_collection/aggregate/sum.rs index 62b2ca498..3285fa8f1 100644 --- a/packages/metrics/src/metric_collection/aggregate.rs +++ b/packages/metrics/src/metric_collection/aggregate/sum.rs @@ -47,7 +47,7 @@ mod tests { use crate::label::LabelValue; use crate::label_name; - use crate::metric_collection::aggregate::Sum; + use crate::metric_collection::aggregate::sum::Sum; #[test] fn type_counter_with_two_samples() { diff --git a/packages/udp-tracker-core/src/statistics/metrics.rs b/packages/udp-tracker-core/src/statistics/metrics.rs index db83c1c1d..98906a596 100644 --- a/packages/udp-tracker-core/src/statistics/metrics.rs +++ b/packages/udp-tracker-core/src/statistics/metrics.rs @@ -1,7 +1,7 @@ use serde::Serialize; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; -use torrust_tracker_metrics::metric_collection::aggregate::Sum; +use torrust_tracker_metrics::metric_collection::aggregate::sum::Sum; use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index d3f273665..c50966bc6 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -1,7 +1,7 @@ use serde::Serialize; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; -use torrust_tracker_metrics::metric_collection::aggregate::Sum; +use torrust_tracker_metrics::metric_collection::aggregate::sum::Sum; use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; From 7df7d367d8da85122e0423e3521065ec602ee748 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 17 Jun 2025 09:06:19 +0100 Subject: [PATCH 1227/1297] docs(metrics): enhance README with comprehensive documentation and examples - Add detailed overview and key features section - Include quick start guide with practical usage examples - Document architecture with core components and type system - Add comprehensive development guide with building, testing, and coverage - Include performance considerations and compatibility notes - Add contributing guidelines and related projects - Transform from basic description to full developer documentation - Update cSpell.json with new technical terms (println, serde) This provides much better onboarding for developers and users of the metrics library. --- packages/metrics/README.md | 185 +++++++++++++++++++++++++++++++++-- packages/metrics/cSpell.json | 2 + 2 files changed, 177 insertions(+), 10 deletions(-) diff --git a/packages/metrics/README.md b/packages/metrics/README.md index 885d6fa45..9f3883fba 100644 --- a/packages/metrics/README.md +++ b/packages/metrics/README.md @@ -1,37 +1,202 @@ # Torrust Tracker Metrics -A library with the metrics types used by the [Torrust Tracker](https://github.com/torrust/torrust-tracker) packages. +A comprehensive metrics library providing type-safe metric collection, aggregation, and Prometheus export functionality for the [Torrust Tracker](https://github.com/torrust/torrust-tracker) ecosystem. + +## Overview + +This library offers a robust metrics system designed specifically for tracking and monitoring BitTorrent tracker performance. It provides type-safe metric collection with support for labels, time-series data, and multiple export formats including Prometheus. + +## Key Features + +- **Type-Safe Metrics**: Strongly typed `Counter` and `Gauge` metrics with compile-time guarantees +- **Label Support**: Rich labeling system for multi-dimensional metrics +- **Time-Series Data**: Built-in support for timestamped samples +- **Prometheus Export**: Native Prometheus format serialization +- **Aggregation Functions**: Sum operations with mathematically appropriate return types +- **JSON Serialization**: Full serde support for all metric types +- **Memory Efficient**: Optimized data structures for high-performance scenarios + +## Quick Start + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +torrust-tracker-metrics = "3.0.0" +``` + +### Basic Usage + +```rust +use torrust_tracker_metrics::{ + metric_collection::MetricCollection, + label::{LabelSet, LabelValue}, + metric_name, label_name, +}; +use torrust_tracker_primitives::DurationSinceUnixEpoch; + +// Create a metric collection +let mut metrics = MetricCollection::default(); + +// Define labels +let labels: LabelSet = [ + (label_name!("server"), LabelValue::new("tracker-01")), + (label_name!("protocol"), LabelValue::new("http")), +].into(); + +// Record metrics +let time = DurationSinceUnixEpoch::from_secs(1234567890); +metrics.increment_counter( + &metric_name!("requests_total"), + &labels, + time, +)?; + +metrics.set_gauge( + &metric_name!("active_connections"), + &labels, + 42.0, + time, +)?; + +// Export to Prometheus format +let prometheus_output = metrics.to_prometheus(); +println!("{}", prometheus_output); +``` + +### Metric Aggregation + +```rust +use torrust_tracker_metrics::metric_collection::aggregate::Sum; + +// Sum all counter values matching specific labels +let total_requests = metrics.sum( + &metric_name!("requests_total"), + &[("server", "tracker-01")].into(), +); + +println!("Total requests: {:?}", total_requests); +``` + +## Architecture + +### Core Components + +- **`Counter`**: Monotonically increasing integer values (u64) +- **`Gauge`**: Arbitrary floating-point values that can increase or decrease (f64) +- **`Metric`**: Generic metric container with metadata (name, description, unit) +- **`MetricCollection`**: Type-safe collection managing both counters and gauges +- **`LabelSet`**: Key-value pairs for metric dimensionality +- **`Sample`**: Timestamped metric values with associated labels + +### Type System + +The library uses Rust's type system to ensure metric safety: + +```rust +// Counter operations return u64 +let counter_sum: Option = counter_collection.sum(&name, &labels); + +// Gauge operations return f64 +let gauge_sum: Option = gauge_collection.sum(&name, &labels); + +// Mixed collections convert to f64 for compatibility +let mixed_sum: Option = metric_collection.sum(&name, &labels); +``` + +### Module Structure + +```output +src/ +├── counter.rs # Counter metric type +├── gauge.rs # Gauge metric type +├── metric/ # Generic metric container +│ ├── mod.rs +│ ├── name.rs # Metric naming +│ ├── description.rs # Metric descriptions +│ └── aggregate/ # Metric-level aggregations +├── metric_collection/ # Collection management +│ ├── mod.rs +│ └── aggregate/ # Collection-level aggregations +├── label/ # Label system +│ ├── name.rs # Label names +│ ├── value.rs # Label values +│ └── set.rs # Label collections +├── sample.rs # Timestamped values +├── sample_collection.rs # Sample management +├── prometheus.rs # Prometheus export +└── unit.rs # Measurement units +``` ## Documentation -[Crate documentation](https://docs.rs/torrust-tracker-metrics). +- [Crate documentation](https://docs.rs/torrust-tracker-metrics) +- [API Reference](https://docs.rs/torrust-tracker-metrics/latest/torrust_tracker_metrics/) + +## Development -## Testing +### Code Coverage -Run coverage report: +Run basic coverage report: ```console cargo llvm-cov --package torrust-tracker-metrics ``` -Generate LCOV report with `llvm-cov` (for Visual Studio Code extension): +Generate LCOV report (for IDE integration): ```console mkdir -p ./.coverage -cargo llvm-cov --package torrust-tracker-metrics --lcov --output-path=./.coverage/lcov.info +cargo llvm-cov --package torrust-tracker-metrics --lcov --output-path=./.coverage/lcov.info ``` -Generate HTML report with `llvm-cov`: +Generate detailed HTML coverage report: + +Generate detailed HTML coverage report: ```console mkdir -p ./.coverage -cargo llvm-cov --package torrust-tracker-metrics --html --output-dir ./.coverage +cargo llvm-cov --package torrust-tracker-metrics --html --output-dir ./.coverage ``` +Open the coverage report in your browser: + +```console +open ./.coverage/index.html # macOS +xdg-open ./.coverage/index.html # Linux +``` + +## Performance Considerations + +- **Memory Usage**: Metrics are stored in-memory with efficient HashMap-based collections +- **Label Cardinality**: Be mindful of label combinations as they create separate time series +- **Aggregation**: Sum operations are optimized for both single-type and mixed collections + +## Compatibility + +This library is designed to be compatible with the standard Rust [metrics](https://crates.io/crates/metrics) crate ecosystem where possible. + +## Contributing + +We welcome contributions! Please see the main [Torrust Tracker repository](https://github.com/torrust/torrust-tracker) for contribution guidelines. + +### Reporting Issues + +- [Bug Reports](https://github.com/torrust/torrust-tracker/issues/new?template=bug_report.md) +- [Feature Requests](https://github.com/torrust/torrust-tracker/issues/new?template=feature_request.md) + ## Acknowledgements -We copied some parts like units or function names and signatures from the crate [metrics](https://crates.io/crates/metrics) because we wanted to make it compatible as much as possible with it. In the future, we may consider using the `metrics` crate directly instead of maintaining our own version. +This library draws inspiration from the Rust [metrics](https://crates.io/crates/metrics) crate, incorporating compatible APIs and naming conventions where possible. We may consider migrating to the standard metrics crate in future versions while maintaining our specialized functionality. + +Special thanks to the Rust metrics ecosystem contributors for establishing excellent patterns for metrics collection and export. ## License -The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). +This project is licensed under the [GNU AFFERO GENERAL PUBLIC LICENSE v3.0](./LICENSE). + +## Related Projects + +- [Torrust Tracker](https://github.com/torrust/torrust-tracker) - The main BitTorrent tracker +- [metrics](https://crates.io/crates/metrics) - Standard Rust metrics facade +- [prometheus](https://crates.io/crates/prometheus) - Prometheus client library diff --git a/packages/metrics/cSpell.json b/packages/metrics/cSpell.json index 1a2c13d2e..f04cce9e3 100644 --- a/packages/metrics/cSpell.json +++ b/packages/metrics/cSpell.json @@ -6,7 +6,9 @@ "Kibibytes", "Mebibytes", "ñaca", + "println", "rstest", + "serde", "subsec", "Tebibytes", "thiserror" From d2e75e3f78f367e5f2829bbe5adfedc549fb24f5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 17 Jun 2025 10:57:11 +0100 Subject: [PATCH 1228/1297] refactor: [#1405] gracefull shutdown for listeners Events listeners listen for the cancelation request instead of directly for the CRTR+c signal. This will allow implementing centralized policies for shutdown and alternative conditions. --- Cargo.lock | 8 +++++ Cargo.toml | 1 + packages/axum-http-tracker-server/Cargo.toml | 1 + .../src/environment.rs | 6 ++++ .../axum-http-tracker-server/src/server.rs | 5 +++- .../src/v1/handlers/announce.rs | 6 +++- .../src/v1/handlers/scrape.rs | 5 +++- packages/events/src/shutdown.rs | 0 packages/http-tracker-core/Cargo.toml | 1 + .../http-tracker-core/benches/helpers/util.rs | 5 +++- .../src/services/announce.rs | 5 +++- .../src/statistics/event/listener.rs | 23 +++++++------- packages/rest-tracker-api-core/Cargo.toml | 1 + .../src/statistics/services.rs | 5 +++- .../swarm-coordination-registry/Cargo.toml | 1 + .../src/statistics/event/listener.rs | 27 +++++++++-------- packages/tracker-core/Cargo.toml | 1 + .../src/statistics/event/listener.rs | 20 ++++++------- .../tracker-core/tests/common/test_env.rs | 5 ++++ packages/udp-tracker-core/Cargo.toml | 1 + .../src/statistics/event/listener.rs | 22 +++++++------- packages/udp-tracker-server/Cargo.toml | 1 + .../src/banning/event/listener.rs | 22 ++++++++------ .../udp-tracker-server/src/environment.rs | 9 ++++++ .../src/statistics/event/listener.rs | 22 +++++++------- src/app.rs | 12 ++++---- src/bootstrap/jobs/http_tracker_core.rs | 8 ++++- src/bootstrap/jobs/manager.rs | 30 +++++++++++++++++-- src/bootstrap/jobs/torrent_repository.rs | 8 ++++- src/bootstrap/jobs/tracker_core.rs | 8 ++++- src/bootstrap/jobs/udp_tracker_core.rs | 8 ++++- src/bootstrap/jobs/udp_tracker_server.rs | 11 +++++-- src/main.rs | 2 ++ 33 files changed, 206 insertions(+), 84 deletions(-) create mode 100644 packages/events/src/shutdown.rs diff --git a/Cargo.lock b/Cargo.lock index 269f7a3a2..b523c8b60 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -587,6 +587,7 @@ dependencies = [ "serde_json", "thiserror 2.0.12", "tokio", + "tokio-util", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-events", @@ -673,6 +674,7 @@ dependencies = [ "testcontainers", "thiserror 2.0.12", "tokio", + "tokio-util", "torrust-rest-tracker-api-client", "torrust-tracker-clock", "torrust-tracker-configuration", @@ -705,6 +707,7 @@ dependencies = [ "serde", "thiserror 2.0.12", "tokio", + "tokio-util", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-events", @@ -4565,6 +4568,7 @@ dependencies = [ "serde_bytes", "serde_repr", "tokio", + "tokio-util", "torrust-axum-server", "torrust-server-lib", "torrust-tracker-clock", @@ -4661,6 +4665,7 @@ dependencies = [ "bittorrent-tracker-core", "bittorrent-udp-tracker-core", "tokio", + "tokio-util", "torrust-tracker-configuration", "torrust-tracker-events", "torrust-tracker-metrics", @@ -4704,6 +4709,7 @@ dependencies = [ "serde_json", "thiserror 2.0.12", "tokio", + "tokio-util", "torrust-axum-health-check-api-server", "torrust-axum-http-tracker-server", "torrust-axum-rest-tracker-api-server", @@ -4851,6 +4857,7 @@ dependencies = [ "serde", "thiserror 2.0.12", "tokio", + "tokio-util", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-events", @@ -4909,6 +4916,7 @@ dependencies = [ "serde", "thiserror 2.0.12", "tokio", + "tokio-util", "torrust-server-lib", "torrust-tracker-clock", "torrust-tracker-configuration", diff --git a/Cargo.toml b/Cargo.toml index 976176155..dbc39bdf8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,6 +47,7 @@ serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } thiserror = "2.0.12" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio-util = "0.7.15" torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "packages/axum-health-check-api-server" } torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "packages/axum-http-tracker-server" } torrust-axum-rest-tracker-api-server = { version = "3.0.0-develop", path = "packages/axum-rest-tracker-api-server" } diff --git a/packages/axum-http-tracker-server/Cargo.toml b/packages/axum-http-tracker-server/Cargo.toml index fa195489c..eb2c2cad3 100644 --- a/packages/axum-http-tracker-server/Cargo.toml +++ b/packages/axum-http-tracker-server/Cargo.toml @@ -28,6 +28,7 @@ hyper = "1" reqwest = { version = "0", features = ["json"] } serde = { version = "1", features = ["derive"] } tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio-util = "0.7.15" torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index 6e58c2cac..616973a0f 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -6,6 +6,7 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::container::TrackerCoreContainer; use futures::executor::block_on; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; @@ -21,6 +22,7 @@ pub struct Environment { pub registar: Registar, pub server: HttpServer, pub event_listener_job: Option>, + pub cancellation_token: CancellationToken, } impl Environment { @@ -59,6 +61,7 @@ impl Environment { registar: Registar::default(), server, event_listener_job: None, + cancellation_token: CancellationToken::new(), } } @@ -72,6 +75,7 @@ impl Environment { // Start the event listener let event_listener_job = run_event_listener( self.container.http_tracker_core_container.event_bus.receiver(), + self.cancellation_token.clone(), &self.container.http_tracker_core_container.stats_repository, ); @@ -87,6 +91,7 @@ impl Environment { registar: self.registar.clone(), server, event_listener_job: Some(event_listener_job), + cancellation_token: self.cancellation_token, } } } @@ -117,6 +122,7 @@ impl Environment { registar: Registar::default(), server, event_listener_job: None, + cancellation_token: self.cancellation_token, } } diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index ba0dd8c6e..2b43be0a9 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -256,6 +256,7 @@ mod tests { use bittorrent_http_tracker_core::statistics::event::listener::run_event_listener; use bittorrent_http_tracker_core::statistics::repository::Repository; use bittorrent_tracker_core::container::TrackerCoreContainer; + use tokio_util::sync::CancellationToken; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration}; @@ -265,6 +266,8 @@ mod tests { use crate::server::{HttpServer, Launcher}; pub fn initialize_container(configuration: &Configuration) -> HttpTrackerCoreContainer { + let cancellation_token = CancellationToken::new(); + let core_config = Arc::new(configuration.core.clone()); let http_trackers = configuration @@ -287,7 +290,7 @@ mod tests { let http_stats_event_sender = http_stats_event_bus.sender(); if configuration.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), cancellation_token, &http_stats_repository); } let swarm_coordination_registry_container = Arc::new(SwarmCoordinationRegistryContainer::initialize( diff --git a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs index e21a485cf..ce718cd30 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -123,6 +123,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::Configuration; use torrust_tracker_test_helpers::configuration; @@ -149,6 +150,9 @@ mod tests { } fn initialize_core_tracker_services(config: &Configuration) -> CoreHttpTrackerServices { + let cancellation_token = CancellationToken::new(); + + // Initialize the core tracker services with the provided configuration. let core_config = Arc::new(config.core.clone()); let database = initialize_database(&config.core); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); @@ -175,7 +179,7 @@ mod tests { let http_stats_event_sender = http_stats_event_bus.sender(); if config.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), cancellation_token, &http_stats_repository); } let announce_service = Arc::new(AnnounceService::new( diff --git a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs index b48d6e036..bdd4378f3 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -97,6 +97,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_test_helpers::configuration; @@ -127,6 +128,8 @@ mod tests { } fn initialize_core_tracker_services(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) { + let cancellation_token = CancellationToken::new(); + let core_config = Arc::new(config.core.clone()); let in_memory_whitelist = Arc::new(InMemoryWhitelist::default()); let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone())); @@ -146,7 +149,7 @@ mod tests { let http_stats_event_sender = http_stats_event_bus.sender(); if config.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), cancellation_token, &http_stats_repository); } ( diff --git a/packages/events/src/shutdown.rs b/packages/events/src/shutdown.rs new file mode 100644 index 000000000..e69de29bb diff --git a/packages/http-tracker-core/Cargo.toml b/packages/http-tracker-core/Cargo.toml index 45af59baa..04a6c96b6 100644 --- a/packages/http-tracker-core/Cargo.toml +++ b/packages/http-tracker-core/Cargo.toml @@ -23,6 +23,7 @@ futures = "0" serde = "1.0.219" thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio-util = "0.7.15" torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index 414d3b40e..028d7c535 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -20,6 +20,7 @@ use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; use futures::future::BoxFuture; use mockall::mock; +use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_events::sender::SendError; use torrust_tracker_primitives::peer::Peer; @@ -42,6 +43,8 @@ pub fn initialize_core_tracker_services() -> (CoreTrackerServices, CoreHttpTrack } pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) { + let cancellation_token = CancellationToken::new(); + let core_config = Arc::new(config.core.clone()); let database = initialize_database(&config.core); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); @@ -69,7 +72,7 @@ pub fn initialize_core_tracker_services_with_config(config: &Configuration) -> ( let http_stats_event_sender = http_stats_event_bus.sender(); if config.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), cancellation_token, &http_stats_repository); } ( diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 8d12da713..08ac93f68 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -216,6 +216,7 @@ mod tests { use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization; use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist; + use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_primitives::peer::Peer; use torrust_tracker_test_helpers::configuration; @@ -236,6 +237,8 @@ mod tests { } fn initialize_core_tracker_services_with_config(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) { + let cancellation_token = CancellationToken::new(); + let core_config = Arc::new(config.core.clone()); let database = initialize_database(&config.core); let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default()); @@ -263,7 +266,7 @@ mod tests { let http_stats_event_sender = http_stats_event_bus.sender(); if config.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), cancellation_token, &http_stats_repository); } ( diff --git a/packages/http-tracker-core/src/statistics/event/listener.rs b/packages/http-tracker-core/src/statistics/event/listener.rs index 6730d4c70..ff2937a59 100644 --- a/packages/http-tracker-core/src/statistics/event/listener.rs +++ b/packages/http-tracker-core/src/statistics/event/listener.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_tracker_clock::clock::Time; use torrust_tracker_events::receiver::RecvError; @@ -10,29 +11,29 @@ use crate::statistics::repository::Repository; use crate::{CurrentClock, HTTP_TRACKER_LOG_TARGET}; #[must_use] -pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { +pub fn run_event_listener( + receiver: Receiver, + cancellation_token: CancellationToken, + repository: &Arc, +) -> JoinHandle<()> { let stats_repository = repository.clone(); tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Starting HTTP tracker core event listener"); tokio::spawn(async move { - dispatch_events(receiver, stats_repository).await; + dispatch_events(receiver, cancellation_token, stats_repository).await; tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "HTTP tracker core event listener finished"); }) } -async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { - let shutdown_signal = tokio::signal::ctrl_c(); - - tokio::pin!(shutdown_signal); - +async fn dispatch_events(mut receiver: Receiver, cancellation_token: CancellationToken, stats_repository: Arc) { loop { tokio::select! { biased; - _ = &mut shutdown_signal => { - tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Received Ctrl+C, shutting down HTTP tracker core event listener."); + () = cancellation_token.cancelled() => { + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Received cancellation request, shutting down HTTP tracker core event listener."); break; } @@ -42,11 +43,11 @@ async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc { match e { RecvError::Closed => { - tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Http core statistics receiver closed."); + tracing::info!(target: HTTP_TRACKER_LOG_TARGET, "Http tracker core statistics receiver closed."); break; } RecvError::Lagged(n) => { - tracing::warn!(target: HTTP_TRACKER_LOG_TARGET, "Http core statistics receiver lagged by {} events.", n); + tracing::warn!(target: HTTP_TRACKER_LOG_TARGET, "Http tracker core statistics receiver lagged by {} events.", n); } } } diff --git a/packages/rest-tracker-api-core/Cargo.toml b/packages/rest-tracker-api-core/Cargo.toml index cc8eda903..be6d493d7 100644 --- a/packages/rest-tracker-api-core/Cargo.toml +++ b/packages/rest-tracker-api-core/Cargo.toml @@ -18,6 +18,7 @@ bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "../http-trac bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "../udp-tracker-core" } tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio-util = "0.7.15" torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index 44c82bfea..a8132d4fd 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -210,6 +210,7 @@ mod tests { use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::MAX_CONNECTION_ID_ERRORS_PER_IP; use tokio::sync::RwLock; + use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::Configuration; use torrust_tracker_events::bus::SenderStatus; use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; @@ -224,6 +225,8 @@ mod tests { #[tokio::test] async fn the_statistics_service_should_return_the_tracker_metrics() { + let cancellation_token = CancellationToken::new(); + let config = tracker_configuration(); let core_config = Arc::new(config.core.clone()); @@ -244,7 +247,7 @@ mod tests { )); if config.core.tracker_usage_statistics { - let _unused = run_event_listener(http_stats_event_bus.receiver(), &http_stats_repository); + let _unused = run_event_listener(http_stats_event_bus.receiver(), cancellation_token, &http_stats_repository); } // UDP server stats diff --git a/packages/swarm-coordination-registry/Cargo.toml b/packages/swarm-coordination-registry/Cargo.toml index 074562a47..45359ad81 100644 --- a/packages/swarm-coordination-registry/Cargo.toml +++ b/packages/swarm-coordination-registry/Cargo.toml @@ -24,6 +24,7 @@ futures = "0" serde = { version = "1.0.219", features = ["derive"] } thiserror = "2.0.12" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio-util = "0.7.15" torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } diff --git a/packages/swarm-coordination-registry/src/statistics/event/listener.rs b/packages/swarm-coordination-registry/src/statistics/event/listener.rs index 9ff707818..b578d1284 100644 --- a/packages/swarm-coordination-registry/src/statistics/event/listener.rs +++ b/packages/swarm-coordination-registry/src/statistics/event/listener.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_tracker_clock::clock::Time; use torrust_tracker_events::receiver::RecvError; @@ -10,29 +11,29 @@ use crate::statistics::repository::Repository; use crate::{CurrentClock, SWARM_COORDINATION_REGISTRY_LOG_TARGET}; #[must_use] -pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { +pub fn run_event_listener( + receiver: Receiver, + cancellation_token: CancellationToken, + repository: &Arc, +) -> JoinHandle<()> { let stats_repository = repository.clone(); - tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Starting torrent repository event listener"); + tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Starting swarm coordination registry event listener"); tokio::spawn(async move { - dispatch_events(receiver, stats_repository).await; + dispatch_events(receiver, cancellation_token, stats_repository).await; - tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Torrent repository listener finished"); + tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Swarm coordination registry listener finished"); }) } -async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { - let shutdown_signal = tokio::signal::ctrl_c(); - - tokio::pin!(shutdown_signal); - +async fn dispatch_events(mut receiver: Receiver, cancellation_token: CancellationToken, stats_repository: Arc) { loop { tokio::select! { biased; - _ = &mut shutdown_signal => { - tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Received Ctrl+C, shutting down torrent repository event listener."); + () = cancellation_token.cancelled() => { + tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Received cancellation request, shutting down swarm coordination registry event listener."); break; } @@ -42,11 +43,11 @@ async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc { match e { RecvError::Closed => { - tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Torrent repository event receiver closed."); + tracing::info!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Swarm coordination registry event receiver closed."); break; } RecvError::Lagged(n) => { - tracing::warn!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Torrent repository event receiver lagged by {} events.", n); + tracing::warn!(target: SWARM_COORDINATION_REGISTRY_LOG_TARGET, "Swarm coordination registry event receiver lagged by {} events.", n); } } } diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index f04a3b89b..dfc83e58e 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -27,6 +27,7 @@ serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order"] } thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio-util = "0.7.15" torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } diff --git a/packages/tracker-core/src/statistics/event/listener.rs b/packages/tracker-core/src/statistics/event/listener.rs index d3beaf41f..8d2d74c71 100644 --- a/packages/tracker-core/src/statistics/event/listener.rs +++ b/packages/tracker-core/src/statistics/event/listener.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_tracker_clock::clock::Time; use torrust_tracker_events::receiver::RecvError; use torrust_tracker_swarm_coordination_registry::event::receiver::Receiver; @@ -13,6 +14,7 @@ use crate::{CurrentClock, TRACKER_CORE_LOG_TARGET}; #[must_use] pub fn run_event_listener( receiver: Receiver, + cancellation_token: CancellationToken, repository: &Arc, db_downloads_metric_repository: &Arc, persistent_torrent_completed_stat: bool, @@ -20,37 +22,35 @@ pub fn run_event_listener( let stats_repository = repository.clone(); let db_downloads_metric_repository: Arc = db_downloads_metric_repository.clone(); - tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Starting torrent repository event listener"); + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Starting tracker core event listener"); tokio::spawn(async move { dispatch_events( receiver, + cancellation_token, stats_repository, db_downloads_metric_repository, persistent_torrent_completed_stat, ) .await; - tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Torrent repository listener finished"); + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Tracker core listener finished"); }) } async fn dispatch_events( mut receiver: Receiver, + cancellation_token: CancellationToken, stats_repository: Arc, db_downloads_metric_repository: Arc, persistent_torrent_completed_stat: bool, ) { - let shutdown_signal = tokio::signal::ctrl_c(); - - tokio::pin!(shutdown_signal); - loop { tokio::select! { biased; - _ = &mut shutdown_signal => { - tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Received Ctrl+C, shutting down torrent repository event listener"); + () = cancellation_token.cancelled() => { + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Received cancellation request, shutting down tracker core event listener."); break; } @@ -65,11 +65,11 @@ async fn dispatch_events( Err(e) => { match e { RecvError::Closed => { - tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Torrent repository event receiver closed"); + tracing::info!(target: TRACKER_CORE_LOG_TARGET, "Tracker core event receiver closed"); break; } RecvError::Lagged(n) => { - tracing::warn!(target: TRACKER_CORE_LOG_TARGET, "Torrent repository event receiver lagged by {} events", n); + tracing::warn!(target: TRACKER_CORE_LOG_TARGET, "Tracker core event receiver lagged by {} events", n); } } } diff --git a/packages/tracker-core/tests/common/test_env.rs b/packages/tracker-core/tests/common/test_env.rs index d3bc9652a..3fe0464fe 100644 --- a/packages/tracker-core/tests/common/test_env.rs +++ b/packages/tracker-core/tests/common/test_env.rs @@ -7,6 +7,7 @@ use bittorrent_tracker_core::announce_handler::PeersWanted; use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_tracker_core::statistics::persisted::load_persisted_metrics; use tokio::task::yield_now; +use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::Core; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; @@ -66,15 +67,19 @@ impl TestEnv { async fn run_jobs(&self) { let mut jobs = vec![]; + let cancellation_token = CancellationToken::new(); let job = torrust_tracker_swarm_coordination_registry::statistics::event::listener::run_event_listener( self.swarm_coordination_registry_container.event_bus.receiver(), + cancellation_token.clone(), &self.swarm_coordination_registry_container.stats_repository, ); + jobs.push(job); let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( self.swarm_coordination_registry_container.event_bus.receiver(), + cancellation_token.clone(), &self.tracker_core_container.stats_repository, &self.tracker_core_container.db_downloads_metric_repository, self.tracker_core_container diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml index 290c5fbfd..b3007eb80 100644 --- a/packages/udp-tracker-core/Cargo.toml +++ b/packages/udp-tracker-core/Cargo.toml @@ -28,6 +28,7 @@ rand = "0" serde = "1.0.219" thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync", "time"] } +tokio-util = "0.7.15" torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } diff --git a/packages/udp-tracker-core/src/statistics/event/listener.rs b/packages/udp-tracker-core/src/statistics/event/listener.rs index 9b6f2e574..b11bcce85 100644 --- a/packages/udp-tracker-core/src/statistics/event/listener.rs +++ b/packages/udp-tracker-core/src/statistics/event/listener.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_tracker_clock::clock::Time; use torrust_tracker_events::receiver::RecvError; @@ -10,28 +11,29 @@ use crate::statistics::repository::Repository; use crate::{CurrentClock, UDP_TRACKER_LOG_TARGET}; #[must_use] -pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { +pub fn run_event_listener( + receiver: Receiver, + cancellation_token: CancellationToken, + repository: &Arc, +) -> JoinHandle<()> { let stats_repository = repository.clone(); tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker core event listener"); tokio::spawn(async move { - dispatch_events(receiver, stats_repository).await; + dispatch_events(receiver, cancellation_token, stats_repository).await; tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker core event listener finished"); }) } -async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { - let shutdown_signal = tokio::signal::ctrl_c(); - tokio::pin!(shutdown_signal); - +async fn dispatch_events(mut receiver: Receiver, cancellation_token: CancellationToken, stats_repository: Arc) { loop { tokio::select! { biased; - _ = &mut shutdown_signal => { - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Received Ctrl+C, shutting down UDP tracker core event listener."); + () = cancellation_token.cancelled() => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Received cancellation request, shutting down UDP tracker core event listener."); break; } @@ -41,11 +43,11 @@ async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc { match e { RecvError::Closed => { - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp core statistics receiver closed."); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp tracker core statistics receiver closed."); break; } RecvError::Lagged(n) => { - tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp core statistics receiver lagged by {} events.", n); + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp tracker core statistics receiver lagged by {} events.", n); } } } diff --git a/packages/udp-tracker-server/Cargo.toml b/packages/udp-tracker-server/Cargo.toml index c0bc94ce3..160fe58f9 100644 --- a/packages/udp-tracker-server/Cargo.toml +++ b/packages/udp-tracker-server/Cargo.toml @@ -26,6 +26,7 @@ ringbuf = "0" serde = "1.0.219" thiserror = "2" tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio-util = "0.7.15" torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } diff --git a/packages/udp-tracker-server/src/banning/event/listener.rs b/packages/udp-tracker-server/src/banning/event/listener.rs index fee3395fa..0d579f912 100644 --- a/packages/udp-tracker-server/src/banning/event/listener.rs +++ b/packages/udp-tracker-server/src/banning/event/listener.rs @@ -4,6 +4,7 @@ use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use tokio::sync::RwLock; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_tracker_clock::clock::Time; use torrust_tracker_events::receiver::RecvError; @@ -15,6 +16,7 @@ use crate::CurrentClock; #[must_use] pub fn run_event_listener( receiver: Receiver, + cancellation_token: CancellationToken, ban_service: &Arc>, repository: &Arc, ) -> JoinHandle<()> { @@ -24,22 +26,24 @@ pub fn run_event_listener( tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker server event listener (banning)"); tokio::spawn(async move { - dispatch_events(receiver, ban_service_clone, repository_clone).await; + dispatch_events(receiver, cancellation_token, ban_service_clone, repository_clone).await; tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker server event listener (banning) finished"); }) } -async fn dispatch_events(mut receiver: Receiver, ban_service: Arc>, repository: Arc) { - let shutdown_signal = tokio::signal::ctrl_c(); - tokio::pin!(shutdown_signal); - +async fn dispatch_events( + mut receiver: Receiver, + cancellation_token: CancellationToken, + ban_service: Arc>, + repository: Arc, +) { loop { tokio::select! { biased; - _ = &mut shutdown_signal => { - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Received Ctrl+C, shutting down UDP tracker server event listener (banning)"); + () = cancellation_token.cancelled() => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Received cancellation request, shutting down UDP tracker server event listener."); break; } @@ -49,11 +53,11 @@ async fn dispatch_events(mut receiver: Receiver, ban_service: Arc { match e { RecvError::Closed => { - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp server receiver (banning) closed."); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp tracker server receiver (banning) closed."); break; } RecvError::Lagged(n) => { - tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp server receiver (banning) lagged by {} events.", n); + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp tracker server receiver (banning) lagged by {} events.", n); } } } diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 61b1cba63..13e18ba9b 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use bittorrent_tracker_core::container::TrackerCoreContainer; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_server_lib::registar::Registar; use torrust_tracker_configuration::{logging, Configuration, DEFAULT_TIMEOUT}; use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; @@ -25,6 +26,7 @@ where pub udp_core_event_listener_job: Option>, pub udp_server_stats_event_listener_job: Option>, pub udp_server_banning_event_listener_job: Option>, + pub cancellation_token: CancellationToken, } impl Environment { @@ -46,6 +48,7 @@ impl Environment { udp_core_event_listener_job: None, udp_server_stats_event_listener_job: None, udp_server_banning_event_listener_job: None, + cancellation_token: CancellationToken::new(), } } @@ -57,21 +60,25 @@ impl Environment { #[allow(dead_code)] pub async fn start(self) -> Environment { let cookie_lifetime = self.container.udp_tracker_core_container.udp_tracker_config.cookie_lifetime; + // Start the UDP tracker core event listener let udp_core_event_listener_job = Some(bittorrent_udp_tracker_core::statistics::event::listener::run_event_listener( self.container.udp_tracker_core_container.event_bus.receiver(), + self.cancellation_token.clone(), &self.container.udp_tracker_core_container.stats_repository, )); // Start the UDP tracker server event listener (statistics) let udp_server_stats_event_listener_job = Some(crate::statistics::event::listener::run_event_listener( self.container.udp_tracker_server_container.event_bus.receiver(), + self.cancellation_token.clone(), &self.container.udp_tracker_server_container.stats_repository, )); // Start the UDP tracker server event listener (banning) let udp_server_banning_event_listener_job = Some(crate::banning::event::listener::run_event_listener( self.container.udp_tracker_server_container.event_bus.receiver(), + self.cancellation_token.clone(), &self.container.udp_tracker_core_container.ban_service, &self.container.udp_tracker_server_container.stats_repository, )); @@ -95,6 +102,7 @@ impl Environment { udp_core_event_listener_job, udp_server_stats_event_listener_job, udp_server_banning_event_listener_job, + cancellation_token: self.cancellation_token, } } } @@ -150,6 +158,7 @@ impl Environment { udp_core_event_listener_job: None, udp_server_stats_event_listener_job: None, udp_server_banning_event_listener_job: None, + cancellation_token: self.cancellation_token, } } diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index ae659c15e..caaf5a2bc 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_tracker_clock::clock::Time; use torrust_tracker_events::receiver::RecvError; @@ -11,28 +12,29 @@ use crate::statistics::repository::Repository; use crate::CurrentClock; #[must_use] -pub fn run_event_listener(receiver: Receiver, repository: &Arc) -> JoinHandle<()> { +pub fn run_event_listener( + receiver: Receiver, + cancellation_token: CancellationToken, + repository: &Arc, +) -> JoinHandle<()> { let repository_clone = repository.clone(); tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Starting UDP tracker server event listener"); tokio::spawn(async move { - dispatch_events(receiver, repository_clone).await; + dispatch_events(receiver, cancellation_token, repository_clone).await; tracing::info!(target: UDP_TRACKER_LOG_TARGET, "UDP tracker server event listener finished"); }) } -async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc) { - let shutdown_signal = tokio::signal::ctrl_c(); - tokio::pin!(shutdown_signal); - +async fn dispatch_events(mut receiver: Receiver, cancellation_token: CancellationToken, stats_repository: Arc) { loop { tokio::select! { biased; - _ = &mut shutdown_signal => { - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Received Ctrl+C, shutting down UDP tracker server event listener."); + () = cancellation_token.cancelled() => { + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Received cancellation request, shutting down UDP tracker server event listener."); break; } @@ -42,11 +44,11 @@ async fn dispatch_events(mut receiver: Receiver, stats_repository: Arc { match e { RecvError::Closed => { - tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp server statistics receiver closed."); + tracing::info!(target: UDP_TRACKER_LOG_TARGET, "Udp tracker server statistics receiver closed."); break; } RecvError::Lagged(n) => { - tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp server statistics receiver lagged by {} events.", n); + tracing::warn!(target: UDP_TRACKER_LOG_TARGET, "Udp tracker server statistics receiver lagged by {} events.", n); } } } diff --git a/src/app.rs b/src/app.rs index 58d758d7f..2149a6d4c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -140,28 +140,28 @@ fn start_swarm_coordination_registry_event_listener( ) { job_manager.push_opt( "swarm_coordination_registry_event_listener", - jobs::torrent_repository::start_event_listener(config, app_container), + jobs::torrent_repository::start_event_listener(config, app_container, job_manager.new_cancellation_token()), ); } fn start_tracker_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { job_manager.push_opt( "tracker_core_event_listener", - jobs::tracker_core::start_event_listener(config, app_container), + jobs::tracker_core::start_event_listener(config, app_container, job_manager.new_cancellation_token()), ); } fn start_http_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { job_manager.push_opt( "http_core_event_listener", - jobs::http_tracker_core::start_event_listener(config, app_container), + jobs::http_tracker_core::start_event_listener(config, app_container, job_manager.new_cancellation_token()), ); } fn start_udp_core_event_listener(config: &Configuration, app_container: &Arc, job_manager: &mut JobManager) { job_manager.push_opt( "udp_core_event_listener", - jobs::udp_tracker_core::start_event_listener(config, app_container), + jobs::udp_tracker_core::start_event_listener(config, app_container, job_manager.new_cancellation_token()), ); } @@ -172,14 +172,14 @@ fn start_udp_server_stats_event_listener( ) { job_manager.push_opt( "udp_server_stats_event_listener", - jobs::udp_tracker_server::start_stats_event_listener(config, app_container), + jobs::udp_tracker_server::start_stats_event_listener(config, app_container, job_manager.new_cancellation_token()), ); } fn start_udp_server_banning_event_listener(app_container: &Arc, job_manager: &mut JobManager) { job_manager.push( "udp_server_banning_event_listener", - jobs::udp_tracker_server::start_banning_event_listener(app_container), + jobs::udp_tracker_server::start_banning_event_listener(app_container, job_manager.new_cancellation_token()), ); } diff --git a/src/bootstrap/jobs/http_tracker_core.rs b/src/bootstrap/jobs/http_tracker_core.rs index 952c80b40..ab71b9a0f 100644 --- a/src/bootstrap/jobs/http_tracker_core.rs +++ b/src/bootstrap/jobs/http_tracker_core.rs @@ -1,14 +1,20 @@ use std::sync::Arc; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::Configuration; use crate::container::AppContainer; -pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { +pub fn start_event_listener( + config: &Configuration, + app_container: &Arc, + cancellation_token: CancellationToken, +) -> Option> { if config.core.tracker_usage_statistics { let job = bittorrent_http_tracker_core::statistics::event::listener::run_event_listener( app_container.http_tracker_core_services.event_bus.receiver(), + cancellation_token, &app_container.http_tracker_core_services.stats_repository, ); diff --git a/src/bootstrap/jobs/manager.rs b/src/bootstrap/jobs/manager.rs index 53733844b..565cd7b73 100644 --- a/src/bootstrap/jobs/manager.rs +++ b/src/bootstrap/jobs/manager.rs @@ -2,13 +2,14 @@ use std::time::Duration; use tokio::task::JoinHandle; use tokio::time::timeout; +use tokio_util::sync::CancellationToken; use tracing::{info, warn}; /// Represents a named background job. #[derive(Debug)] pub struct Job { - pub name: String, - pub handle: JoinHandle<()>, + name: String, + handle: JoinHandle<()>, } impl Job { @@ -24,12 +25,16 @@ impl Job { #[derive(Debug, Default)] pub struct JobManager { jobs: Vec, + cancellation_token: CancellationToken, } impl JobManager { #[must_use] pub fn new() -> Self { - Self { jobs: Vec::new() } + Self { + jobs: Vec::new(), + cancellation_token: CancellationToken::new(), + } } pub fn push>(&mut self, name: N, handle: JoinHandle<()>) { @@ -42,6 +47,25 @@ impl JobManager { } } + #[must_use] + pub fn new_cancellation_token(&self) -> CancellationToken { + self.cancellation_token.clone() + } + + /// Cancels all jobs using the shared cancellation token. + /// + /// Notice that this does not cancel the jobs immediately, but rather + /// signals them to stop. The jobs themselves must handle the cancellation + /// token appropriately. + /// + /// Notice jobs might be pushed into the manager without a cancellation + /// token, so this method will not cancel those jobs. Some tasks might + /// decide to listen for CTRL+c signal directly, or implement their own + /// cancellation logic. + pub fn cancel(&self) { + self.cancellation_token.cancel(); + } + /// Waits sequentially for all jobs to complete, with a graceful timeout per /// job. pub async fn wait_for_all(mut self, grace_period: Duration) { diff --git a/src/bootstrap/jobs/torrent_repository.rs b/src/bootstrap/jobs/torrent_repository.rs index 44ffdf53b..e49323735 100644 --- a/src/bootstrap/jobs/torrent_repository.rs +++ b/src/bootstrap/jobs/torrent_repository.rs @@ -1,14 +1,20 @@ use std::sync::Arc; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::Configuration; use crate::container::AppContainer; -pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { +pub fn start_event_listener( + config: &Configuration, + app_container: &Arc, + cancellation_token: CancellationToken, +) -> Option> { if config.core.tracker_usage_statistics { let job = torrust_tracker_swarm_coordination_registry::statistics::event::listener::run_event_listener( app_container.swarm_coordination_registry_container.event_bus.receiver(), + cancellation_token, &app_container.swarm_coordination_registry_container.stats_repository, ); diff --git a/src/bootstrap/jobs/tracker_core.rs b/src/bootstrap/jobs/tracker_core.rs index f2fc25ef3..d881f4cd2 100644 --- a/src/bootstrap/jobs/tracker_core.rs +++ b/src/bootstrap/jobs/tracker_core.rs @@ -1,14 +1,20 @@ use std::sync::Arc; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::Configuration; use crate::container::AppContainer; -pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { +pub fn start_event_listener( + config: &Configuration, + app_container: &Arc, + cancellation_token: CancellationToken, +) -> Option> { if config.core.tracker_usage_statistics || config.core.tracker_policy.persistent_torrent_completed_stat { let job = bittorrent_tracker_core::statistics::event::listener::run_event_listener( app_container.swarm_coordination_registry_container.event_bus.receiver(), + cancellation_token, &app_container.tracker_core_container.stats_repository, &app_container.tracker_core_container.db_downloads_metric_repository, app_container diff --git a/src/bootstrap/jobs/udp_tracker_core.rs b/src/bootstrap/jobs/udp_tracker_core.rs index 689fa8301..dd7e8c165 100644 --- a/src/bootstrap/jobs/udp_tracker_core.rs +++ b/src/bootstrap/jobs/udp_tracker_core.rs @@ -1,14 +1,20 @@ use std::sync::Arc; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::Configuration; use crate::container::AppContainer; -pub fn start_event_listener(config: &Configuration, app_container: &Arc) -> Option> { +pub fn start_event_listener( + config: &Configuration, + app_container: &Arc, + cancellation_token: CancellationToken, +) -> Option> { if config.core.tracker_usage_statistics { let job = bittorrent_udp_tracker_core::statistics::event::listener::run_event_listener( app_container.udp_tracker_core_services.event_bus.receiver(), + cancellation_token, &app_container.udp_tracker_core_services.stats_repository, ); Some(job) diff --git a/src/bootstrap/jobs/udp_tracker_server.rs b/src/bootstrap/jobs/udp_tracker_server.rs index 3e8a7aaa8..fc6df9c16 100644 --- a/src/bootstrap/jobs/udp_tracker_server.rs +++ b/src/bootstrap/jobs/udp_tracker_server.rs @@ -1,14 +1,20 @@ use std::sync::Arc; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::Configuration; use crate::container::AppContainer; -pub fn start_stats_event_listener(config: &Configuration, app_container: &Arc) -> Option> { +pub fn start_stats_event_listener( + config: &Configuration, + app_container: &Arc, + cancellation_token: CancellationToken, +) -> Option> { if config.core.tracker_usage_statistics { let job = torrust_udp_tracker_server::statistics::event::listener::run_event_listener( app_container.udp_tracker_server_container.event_bus.receiver(), + cancellation_token, &app_container.udp_tracker_server_container.stats_repository, ); Some(job) @@ -19,9 +25,10 @@ pub fn start_stats_event_listener(config: &Configuration, app_container: &Arc) -> JoinHandle<()> { +pub fn start_banning_event_listener(app_container: &Arc, cancellation_token: CancellationToken) -> JoinHandle<()> { torrust_udp_tracker_server::banning::event::listener::run_event_listener( app_container.udp_tracker_server_container.event_bus.receiver(), + cancellation_token, &app_container.udp_tracker_core_services.ban_service, &app_container.udp_tracker_server_container.stats_repository, ) diff --git a/src/main.rs b/src/main.rs index a49c3aeba..7012ecaa7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,6 +10,8 @@ async fn main() { _ = tokio::signal::ctrl_c() => { tracing::info!("Torrust tracker shutting down ..."); + jobs.cancel(); + jobs.wait_for_all(Duration::from_secs(10)).await; tracing::info!("Torrust tracker successfully shutdown."); From f7ab993e96a050ddbbd1dd8467bb5bd1ef8c411d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 17 Jun 2025 19:41:33 +0100 Subject: [PATCH 1229/1297] refactor: [#1589] add logs for debugging --- .../src/statistics/repository.rs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index 1851b78a8..fa85610a0 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -89,6 +89,14 @@ impl Repository { drop(stats_lock); + tracing::debug!( + "Recalculated UDP average connect processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_connections_handled: {})", + new_avg, + previous_avg, + req_processing_time, + udp_connections_handled + ); + new_avg } @@ -109,6 +117,14 @@ impl Repository { drop(stats_lock); + tracing::debug!( + "Recalculated UDP average announce processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_announces_handled: {})", + new_avg, + previous_avg, + req_processing_time, + udp_announces_handled + ); + new_avg } @@ -128,6 +144,14 @@ impl Repository { drop(stats_lock); + tracing::debug!( + "Recalculated UDP average scrape processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_scrapes_handled: {})", + new_avg, + previous_avg, + req_processing_time, + udp_scrapes_handled + ); + new_avg } } From 5fc255fa849ad88e977f10e45640176bfd134d26 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 18 Jun 2025 11:07:53 +0100 Subject: [PATCH 1230/1297] tests(udp-tracker-server): [#1589] add unit tests to statistics::repository::Repository --- cSpell.json | 1 + .../src/statistics/repository.rs | 512 ++++++++++++++++++ 2 files changed, 513 insertions(+) diff --git a/cSpell.json b/cSpell.json index fcbf53f1f..647dd24a2 100644 --- a/cSpell.json +++ b/cSpell.json @@ -34,6 +34,7 @@ "chrono", "ciphertext", "clippy", + "cloneable", "codecov", "codegen", "completei", diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index fa85610a0..eb0951614 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -155,3 +155,515 @@ impl Repository { new_avg } } + +#[cfg(test)] +mod tests { + use core::f64; + use std::time::Duration; + + use torrust_tracker_clock::clock::Time; + use torrust_tracker_metrics::metric_name; + + use super::*; + use crate::statistics::*; + use crate::CurrentClock; + + #[test] + fn it_should_implement_default() { + let repo = Repository::default(); + assert!(!std::ptr::eq(&repo.stats, &Repository::new().stats)); + } + + #[test] + fn it_should_be_cloneable() { + let repo = Repository::new(); + let cloned_repo = repo.clone(); + assert!(!std::ptr::eq(&repo.stats, &cloned_repo.stats)); + } + + #[tokio::test] + async fn it_should_be_initialized_with_described_metrics() { + let repo = Repository::new(); + let stats = repo.get_stats().await; + + // Check that the described metrics are present + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL))); + assert!(stats + .metric_collection + .contains_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_CONNECTION_ID_ERRORS_TOTAL))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL))); + assert!(stats + .metric_collection + .contains_gauge(&metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS))); + } + + #[tokio::test] + async fn it_should_return_a_read_guard_to_metrics() { + let repo = Repository::new(); + let stats = repo.get_stats().await; + + // Should be able to read metrics through the guard + assert_eq!(stats.udp_requests_aborted(), 0); + assert_eq!(stats.udp_requests_banned(), 0); + } + + #[tokio::test] + async fn it_should_allow_increasing_a_counter_metric_successfully() { + let repo = Repository::new(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Increase a counter metric + let result = repo + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now) + .await; + + assert!(result.is_ok()); + + // Verify the counter was incremented + let stats = repo.get_stats().await; + assert_eq!(stats.udp_requests_aborted(), 1); + } + + #[tokio::test] + async fn it_should_allow_increasing_a_counter_multiple_times() { + let repo = Repository::new(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Increase counter multiple times + for _ in 0..5 { + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now) + .await + .unwrap(); + } + + // Verify the counter was incremented correctly + let stats = repo.get_stats().await; + assert_eq!(stats.udp_requests_aborted(), 5); + } + + #[tokio::test] + async fn it_should_allow_increasing_a_counter_with_different_labels() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + let labels_ipv4 = LabelSet::from([("server_binding_address_ip_family", "inet")]); + let labels_ipv6 = LabelSet::from([("server_binding_address_ip_family", "inet6")]); + + // Increase counters with different labels + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels_ipv4, now) + .await + .unwrap(); + + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels_ipv6, now) + .await + .unwrap(); + + // Verify both labeled metrics + let stats = repo.get_stats().await; + assert_eq!(stats.udp4_requests(), 1); + assert_eq!(stats.udp6_requests(), 1); + } + + #[tokio::test] + async fn it_should_set_a_gauge_metric_successfully() { + let repo = Repository::new(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Set a gauge metric + let result = repo + .set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 42.0, now) + .await; + + assert!(result.is_ok()); + + // Verify the gauge was set + let stats = repo.get_stats().await; + assert_eq!(stats.udp_banned_ips_total(), 42); + } + + #[tokio::test] + async fn it_should_overwrite_previous_value_when_setting_a_gauge_with_a_previous_value() { + let repo = Repository::new(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Set gauge to initial value + repo.set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 10.0, now) + .await + .unwrap(); + + // Overwrite with new value + repo.set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 25.0, now) + .await + .unwrap(); + + // Verify the gauge has the new value + let stats = repo.get_stats().await; + assert_eq!(stats.udp_banned_ips_total(), 25); + } + + #[tokio::test] + async fn it_should_allow_setting_a_gauge_with_different_labels() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + let labels_connect = LabelSet::from([("request_kind", "connect")]); + let labels_announce = LabelSet::from([("request_kind", "announce")]); + + // Set gauges with different labels + repo.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels_connect, + 1000.0, + now, + ) + .await + .unwrap(); + + repo.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels_announce, + 2000.0, + now, + ) + .await + .unwrap(); + + // Verify both labeled metrics + let stats = repo.get_stats().await; + assert_eq!(stats.udp_avg_connect_processing_time_ns(), 1000); + assert_eq!(stats.udp_avg_announce_processing_time_ns(), 2000); + } + + #[tokio::test] + async fn it_should_recalculate_the_udp_average_connect_processing_time_in_nanoseconds_using_moving_average() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Set up initial connections handled + let ipv4_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "connect")]); + let ipv6_labels = LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")]); + + // Simulate 2 IPv4 and 1 IPv6 connections + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv4_labels, now) + .await + .unwrap(); + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv4_labels, now) + .await + .unwrap(); + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv6_labels, now) + .await + .unwrap(); + + // Set initial average to 1000ns + let connect_labels = LabelSet::from([("request_kind", "connect")]); + repo.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &connect_labels, + 1000.0, + now, + ) + .await + .unwrap(); + + // Calculate new average with processing time of 2000ns + let processing_time = Duration::from_nanos(2000); + let new_avg = repo.recalculate_udp_avg_connect_processing_time_ns(processing_time).await; + + // Moving average: previous_avg + (new_value - previous_avg) / total_connections + // 1000 + (2000 - 1000) / 3 = 1000 + 333.33 = 1333.33 + let expected_avg = 1000.0 + (2000.0 - 1000.0) / 3.0; + assert!( + (new_avg - expected_avg).abs() < 0.01, + "Expected {expected_avg}, got {new_avg}" + ); + } + + #[tokio::test] + async fn it_should_recalculate_the_udp_average_announce_processing_time_in_nanoseconds_using_moving_average() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Set up initial announces handled + let ipv4_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "announce")]); + let ipv6_labels = LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")]); + + // Simulate 3 IPv4 and 2 IPv6 announces + for _ in 0..3 { + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv4_labels, now) + .await + .unwrap(); + } + for _ in 0..2 { + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv6_labels, now) + .await + .unwrap(); + } + + // Set initial average to 500ns + let announce_labels = LabelSet::from([("request_kind", "announce")]); + repo.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &announce_labels, + 500.0, + now, + ) + .await + .unwrap(); + + // Calculate new average with processing time of 1500ns + let processing_time = Duration::from_nanos(1500); + let new_avg = repo.recalculate_udp_avg_announce_processing_time_ns(processing_time).await; + + // Moving average: previous_avg + (new_value - previous_avg) / total_announces + // 500 + (1500 - 500) / 5 = 500 + 200 = 700 + let expected_avg = 500.0 + (1500.0 - 500.0) / 5.0; + assert!( + (new_avg - expected_avg).abs() < 0.01, + "Expected {expected_avg}, got {new_avg}" + ); + } + + #[tokio::test] + async fn it_should_recalculate_the_udp_average_scrape_processing_time_in_nanoseconds_using_moving_average() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Set up initial scrapes handled + let ipv4_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")]); + + // Simulate 4 IPv4 scrapes + for _ in 0..4 { + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv4_labels, now) + .await + .unwrap(); + } + + // Set initial average to 800ns + let scrape_labels = LabelSet::from([("request_kind", "scrape")]); + repo.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &scrape_labels, + 800.0, + now, + ) + .await + .unwrap(); + + // Calculate new average with processing time of 1200ns + let processing_time = Duration::from_nanos(1200); + let new_avg = repo.recalculate_udp_avg_scrape_processing_time_ns(processing_time).await; + + // Moving average: previous_avg + (new_value - previous_avg) / total_scrapes + // 800 + (1200 - 800) / 4 = 800 + 100 = 900 + let expected_avg = 800.0 + (1200.0 - 800.0) / 4.0; + assert!( + (new_avg - expected_avg).abs() < 0.01, + "Expected {expected_avg}, got {new_avg}" + ); + } + + #[tokio::test] + async fn recalculate_average_methods_should_handle_zero_connections_gracefully() { + let repo = Repository::new(); + + // Test with zero connections (should not panic, should handle division by zero) + let processing_time = Duration::from_nanos(1000); + + let connect_avg = repo.recalculate_udp_avg_connect_processing_time_ns(processing_time).await; + let announce_avg = repo.recalculate_udp_avg_announce_processing_time_ns(processing_time).await; + let scrape_avg = repo.recalculate_udp_avg_scrape_processing_time_ns(processing_time).await; + + // With 0 total connections, the formula becomes 0 + (1000 - 0) / 0 + // This should handle the division by zero case gracefully + assert!(connect_avg.is_infinite() || connect_avg.is_nan()); + assert!(announce_avg.is_infinite() || announce_avg.is_nan()); + assert!(scrape_avg.is_infinite() || scrape_avg.is_nan()); + } + + #[tokio::test] + async fn it_should_handle_concurrent_access() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Spawn multiple concurrent tasks + let mut handles = vec![]; + + for i in 0..10 { + let repo_clone = repo.clone(); + let handle = tokio::spawn(async move { + for _ in 0..5 { + repo_clone + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), + &LabelSet::empty(), + now, + ) + .await + .unwrap(); + } + i + }); + handles.push(handle); + } + + // Wait for all tasks to complete + for handle in handles { + handle.await.unwrap(); + } + + // Verify all increments were properly recorded + let stats = repo.get_stats().await; + assert_eq!(stats.udp_requests_aborted(), 50); // 10 tasks * 5 increments each + } + + #[tokio::test] + async fn it_should_handle_large_processing_times() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Set up a connection + let ipv4_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "connect")]); + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv4_labels, now) + .await + .unwrap(); + + // Test with very large processing time + let large_duration = Duration::from_secs(1); // 1 second = 1,000,000,000 ns + let new_avg = repo.recalculate_udp_avg_connect_processing_time_ns(large_duration).await; + + // Should handle large numbers without overflow + assert!(new_avg > 0.0); + assert!(new_avg.is_finite()); + } + + #[tokio::test] + async fn it_should_maintain_consistency_across_operations() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Perform a series of operations + repo.increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), + &LabelSet::empty(), + now, + ) + .await + .unwrap(); + + repo.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), + &LabelSet::empty(), + 10.0, + now, + ) + .await + .unwrap(); + + repo.increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), + &LabelSet::empty(), + now, + ) + .await + .unwrap(); + + // Check final state + let stats = repo.get_stats().await; + assert_eq!(stats.udp_requests_aborted(), 1); + assert_eq!(stats.udp_banned_ips_total(), 10); + assert_eq!(stats.udp_requests_banned(), 1); + } + + #[tokio::test] + async fn it_should_handle_error_cases_gracefully() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Test with invalid metric name (this should still work as metrics are created dynamically) + let result = repo + .increase_counter(&metric_name!("non_existent_metric"), &LabelSet::empty(), now) + .await; + + // Should succeed as metrics are created on demand + assert!(result.is_ok()); + + // Test with NaN value for gauge + let result = repo + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), + &LabelSet::empty(), + f64::NAN, + now, + ) + .await; + + // Should handle NaN values + assert!(result.is_ok()); + } + + #[tokio::test] + async fn it_should_handle_moving_average_calculation_before_any_connections_are_recorded() { + let repo = Repository::new(); + let now = CurrentClock::now(); + + // This test checks the behavior of `recalculate_udp_avg_connect_processing_time_ns`` + // when no connections have been recorded yet. The first call should + // handle division by zero gracefully and return an infinite average, + // which is the current behavior. + + // todo: the first average should be 2000ns, not infinity. + // This is because the first connection is not counted in the average + // calculation if the counter is increased after calculating the average. + // The problem is that we count requests when they are accepted, not + // when they are processed. And we calculate the average when the + // response is sent. + + // First calculation: no connections recorded yet, should result in infinity + let processing_time_1 = Duration::from_nanos(2000); + let avg_1 = repo.recalculate_udp_avg_connect_processing_time_ns(processing_time_1).await; + + // Division by zero: 1000 + (2000 - 1000) / 0 = infinity + assert!( + avg_1.is_infinite(), + "First calculation should be infinite due to division by zero" + ); + + // Now add one connection and try again + let ipv4_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "connect")]); + repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv4_labels, now) + .await + .unwrap(); + + // Second calculation: 1 connection, but previous average is infinity + let processing_time_2 = Duration::from_nanos(3000); + let avg_2 = repo.recalculate_udp_avg_connect_processing_time_ns(processing_time_2).await; + + assert!( + (avg_2 - 3000.0).abs() < f64::EPSILON, + "Second calculation should be 3000ns, but got {avg_2}" + ); + } +} From 7e9d9827f1933d2774cce03eb59b47632214a8d2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 18 Jun 2025 12:15:01 +0100 Subject: [PATCH 1231/1297] fix(udt-tracker-server): metric description --- packages/udp-tracker-server/src/statistics/mod.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index b42a73f27..768722ba3 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -73,9 +73,7 @@ pub fn describe_metrics() -> Metrics { metrics.metric_collection.describe_gauge( &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), Some(Unit::Nanoseconds), - Some(MetricDescription::new( - "Average time to process a UDP connect request in nanoseconds", - )), + Some(MetricDescription::new("Average time to process a UDP request in nanoseconds")), ); metrics From bf9d16a83ec48d2b60074fdc97b93f7c58bb5944 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 18 Jun 2025 12:33:52 +0100 Subject: [PATCH 1232/1297] tests(udp-tracker-server): [#1589] add unit tests to statistics::metrics::Metrics --- cSpell.json | 1 + .../src/statistics/metrics.rs | 781 ++++++++++++++++++ 2 files changed, 782 insertions(+) diff --git a/cSpell.json b/cSpell.json index 647dd24a2..76939c199 100644 --- a/cSpell.json +++ b/cSpell.json @@ -175,6 +175,7 @@ "trackerid", "Trackon", "typenum", + "udpv", "Unamed", "underflows", "Unsendable", diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index c50966bc6..3c162ff02 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -276,3 +276,784 @@ impl Metrics { .unwrap_or_default() as u64 } } + +#[cfg(test)] +mod tests { + use torrust_tracker_clock::clock::Time; + use torrust_tracker_metrics::metric_name; + + use super::*; + use crate::statistics::{ + UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_IPS_BANNED_TOTAL, + UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL, + UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL, + UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL, UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL, + }; + use crate::CurrentClock; + + #[test] + fn it_should_implement_default() { + let metrics = Metrics::default(); + // MetricCollection starts with empty collections + assert_eq!(metrics, Metrics::default()); + } + + #[test] + fn it_should_implement_debug() { + let metrics = Metrics::default(); + let debug_string = format!("{metrics:?}"); + assert!(debug_string.contains("Metrics")); + assert!(debug_string.contains("metric_collection")); + } + + #[test] + fn it_should_implement_partial_eq() { + let metrics1 = Metrics::default(); + let metrics2 = Metrics::default(); + assert_eq!(metrics1, metrics2); + } + + #[test] + fn it_should_increase_counter_metric() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + let result = metrics.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now); + + assert!(result.is_ok()); + } + + #[test] + fn it_should_increase_counter_metric_with_labels() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet")]); + + let result = metrics.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels, now); + + assert!(result.is_ok()); + } + + #[test] + fn it_should_set_gauge_metric() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + let result = metrics.set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 42.0, now); + + assert!(result.is_ok()); + } + + #[test] + fn it_should_set_gauge_metric_with_labels() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("request_kind", "connect")]); + + let result = metrics.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels, + 1000.0, + now, + ); + + assert!(result.is_ok()); + } + + mod udp_general_metrics { + use super::*; + + #[test] + fn it_should_return_zero_for_udp_requests_aborted_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_requests_aborted(), 0); + } + + #[test] + fn it_should_return_sum_of_udp_requests_aborted() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now) + .unwrap(); + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now) + .unwrap(); + + assert_eq!(metrics.udp_requests_aborted(), 2); + } + + #[test] + fn it_should_return_zero_for_udp_requests_banned_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_requests_banned(), 0); + } + + #[test] + fn it_should_return_sum_of_udp_requests_banned() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + for _ in 0..3 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp_requests_banned(), 3); + } + + #[test] + fn it_should_return_zero_for_udp_banned_ips_total_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_banned_ips_total(), 0); + } + + #[test] + fn it_should_return_gauge_value_for_udp_banned_ips_total() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + metrics + .set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 10.0, now) + .unwrap(); + + assert_eq!(metrics.udp_banned_ips_total(), 10); + } + } + + mod udp_performance_metrics { + use super::*; + + #[test] + fn it_should_return_zero_for_udp_avg_connect_processing_time_ns_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_avg_connect_processing_time_ns(), 0); + } + + #[test] + fn it_should_return_gauge_value_for_udp_avg_connect_processing_time_ns() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("request_kind", "connect")]); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels, + 1500.0, + now, + ) + .unwrap(); + + assert_eq!(metrics.udp_avg_connect_processing_time_ns(), 1500); + } + + #[test] + fn it_should_return_zero_for_udp_avg_announce_processing_time_ns_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_avg_announce_processing_time_ns(), 0); + } + + #[test] + fn it_should_return_gauge_value_for_udp_avg_announce_processing_time_ns() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("request_kind", "announce")]); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels, + 2500.0, + now, + ) + .unwrap(); + + assert_eq!(metrics.udp_avg_announce_processing_time_ns(), 2500); + } + + #[test] + fn it_should_return_zero_for_udp_avg_scrape_processing_time_ns_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_avg_scrape_processing_time_ns(), 0); + } + + #[test] + fn it_should_return_gauge_value_for_udp_avg_scrape_processing_time_ns() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("request_kind", "scrape")]); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels, + 3500.0, + now, + ) + .unwrap(); + + assert_eq!(metrics.udp_avg_scrape_processing_time_ns(), 3500); + } + } + + mod udpv4_metrics { + use super::*; + + #[test] + fn it_should_return_zero_for_udp4_requests_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp4_requests(), 0); + } + + #[test] + fn it_should_return_sum_of_udp4_requests() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet")]); + + for _ in 0..5 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_requests(), 5); + } + + #[test] + fn it_should_return_zero_for_udp4_connections_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp4_connections_handled(), 0); + } + + #[test] + fn it_should_return_sum_of_udp4_connections_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "connect")]); + + for _ in 0..3 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_connections_handled(), 3); + } + + #[test] + fn it_should_return_zero_for_udp4_announces_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp4_announces_handled(), 0); + } + + #[test] + fn it_should_return_sum_of_udp4_announces_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "announce")]); + + for _ in 0..7 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_announces_handled(), 7); + } + + #[test] + fn it_should_return_zero_for_udp4_scrapes_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp4_scrapes_handled(), 0); + } + + #[test] + fn it_should_return_sum_of_udp4_scrapes_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")]); + + for _ in 0..4 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_scrapes_handled(), 4); + } + + #[test] + fn it_should_return_zero_for_udp4_responses_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp4_responses(), 0); + } + + #[test] + fn it_should_return_sum_of_udp4_responses() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet")]); + + for _ in 0..6 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_responses(), 6); + } + + #[test] + fn it_should_return_zero_for_udp4_errors_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp4_errors_handled(), 0); + } + + #[test] + fn it_should_return_sum_of_udp4_errors_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet")]); + + for _ in 0..2 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_errors_handled(), 2); + } + } + + mod udpv6_metrics { + use super::*; + + #[test] + fn it_should_return_zero_for_udp6_requests_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp6_requests(), 0); + } + + #[test] + fn it_should_return_sum_of_udp6_requests() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet6")]); + + for _ in 0..8 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp6_requests(), 8); + } + + #[test] + fn it_should_return_zero_for_udp6_connections_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp6_connections_handled(), 0); + } + + #[test] + fn it_should_return_sum_of_udp6_connections_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")]); + + for _ in 0..4 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp6_connections_handled(), 4); + } + + #[test] + fn it_should_return_zero_for_udp6_announces_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp6_announces_handled(), 0); + } + + #[test] + fn it_should_return_sum_of_udp6_announces_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")]); + + for _ in 0..9 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp6_announces_handled(), 9); + } + + #[test] + fn it_should_return_zero_for_udp6_scrapes_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp6_scrapes_handled(), 0); + } + + #[test] + fn it_should_return_sum_of_udp6_scrapes_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "scrape")]); + + for _ in 0..6 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp6_scrapes_handled(), 6); + } + + #[test] + fn it_should_return_zero_for_udp6_responses_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp6_responses(), 0); + } + + #[test] + fn it_should_return_sum_of_udp6_responses() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet6")]); + + for _ in 0..11 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp6_responses(), 11); + } + + #[test] + fn it_should_return_zero_for_udp6_errors_handled_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp6_errors_handled(), 0); + } + + #[test] + fn it_should_return_sum_of_udp6_errors_handled() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("server_binding_address_ip_family", "inet6")]); + + for _ in 0..3 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp6_errors_handled(), 3); + } + } + + mod combined_metrics { + use super::*; + + #[test] + fn it_should_distinguish_between_ipv4_and_ipv6_metrics() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + + let ipv4_labels = LabelSet::from([("server_binding_address_ip_family", "inet")]); + let ipv6_labels = LabelSet::from([("server_binding_address_ip_family", "inet6")]); + + // Add different counts for IPv4 and IPv6 + for _ in 0..3 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &ipv4_labels, now) + .unwrap(); + } + + for _ in 0..7 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &ipv6_labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_requests(), 3); + assert_eq!(metrics.udp6_requests(), 7); + } + + #[test] + fn it_should_distinguish_between_different_request_kinds() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + + let connect_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "connect")]); + let announce_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "announce")]); + let scrape_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")]); + + // Add different counts for different request kinds + for _ in 0..2 { + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &connect_labels, + now, + ) + .unwrap(); + } + + for _ in 0..5 { + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &announce_labels, + now, + ) + .unwrap(); + } + + for _ in 0..1 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &scrape_labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp4_connections_handled(), 2); + assert_eq!(metrics.udp4_announces_handled(), 5); + assert_eq!(metrics.udp4_scrapes_handled(), 1); + } + + #[test] + fn it_should_handle_mixed_ipv4_and_ipv6_for_different_request_kinds() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + + let ipv4_connect_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "connect")]); + let ipv6_connect_labels = + LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")]); + let ipv4_announce_labels = + LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "announce")]); + let ipv6_announce_labels = + LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")]); + + // Add mixed IPv4/IPv6 counts + for _ in 0..3 { + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &ipv4_connect_labels, + now, + ) + .unwrap(); + } + + for _ in 0..2 { + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &ipv6_connect_labels, + now, + ) + .unwrap(); + } + + for _ in 0..4 { + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &ipv4_announce_labels, + now, + ) + .unwrap(); + } + + for _ in 0..6 { + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), + &ipv6_announce_labels, + now, + ) + .unwrap(); + } + + assert_eq!(metrics.udp4_connections_handled(), 3); + assert_eq!(metrics.udp6_connections_handled(), 2); + assert_eq!(metrics.udp4_announces_handled(), 4); + assert_eq!(metrics.udp6_announces_handled(), 6); + } + } + + mod edge_cases { + use super::*; + + #[test] + fn it_should_handle_large_counter_values() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Add a large number of increments + for _ in 0..1000 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now) + .unwrap(); + } + + assert_eq!(metrics.udp_requests_aborted(), 1000); + } + + #[test] + fn it_should_handle_large_gauge_values() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Set a large gauge value + metrics + .set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 999_999.0, now) + .unwrap(); + + assert_eq!(metrics.udp_banned_ips_total(), 999_999); + } + + #[test] + fn it_should_handle_zero_gauge_values() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + metrics + .set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 0.0, now) + .unwrap(); + + assert_eq!(metrics.udp_banned_ips_total(), 0); + } + + #[test] + fn it_should_handle_fractional_gauge_values_with_truncation() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("request_kind", "connect")]); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels, + 1234.567, + now, + ) + .unwrap(); + + // Should truncate to 1234 + assert_eq!(metrics.udp_avg_connect_processing_time_ns(), 1234); + } + + #[test] + fn it_should_overwrite_gauge_values_when_set_multiple_times() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // Set initial value + metrics + .set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 50.0, now) + .unwrap(); + + assert_eq!(metrics.udp_banned_ips_total(), 50); + + // Overwrite with new value + metrics + .set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 75.0, now) + .unwrap(); + + assert_eq!(metrics.udp_banned_ips_total(), 75); + } + + #[test] + fn it_should_handle_empty_label_sets() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let empty_labels = LabelSet::empty(); + + let result = metrics.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &empty_labels, now); + + assert!(result.is_ok()); + assert_eq!(metrics.udp_requests_aborted(), 1); + } + + #[test] + fn it_should_handle_multiple_labels_on_same_metric() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + + let labels1 = LabelSet::from([("server_binding_address_ip_family", "inet")]); + let labels2 = LabelSet::from([("server_binding_address_ip_family", "inet6")]); + + // Add to same metric with different labels + for _ in 0..3 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels1, now) + .unwrap(); + } + + for _ in 0..5 { + metrics + .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), &labels2, now) + .unwrap(); + } + + // Should return labeled sums correctly + assert_eq!(metrics.udp4_requests(), 3); + assert_eq!(metrics.udp6_requests(), 5); + } + } + + mod error_handling { + use super::*; + + #[test] + fn it_should_return_ok_result_for_valid_counter_operations() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + let result = metrics.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now); + + assert!(result.is_ok()); + } + + #[test] + fn it_should_return_ok_result_for_valid_gauge_operations() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + let result = metrics.set_gauge(&metric_name!(UDP_TRACKER_SERVER_IPS_BANNED_TOTAL), &labels, 42.0, now); + + assert!(result.is_ok()); + } + + #[test] + fn it_should_handle_unknown_metric_names_gracefully() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::empty(); + + // This should still work as metrics are created on demand + let result = metrics.increase_counter(&metric_name!("unknown_metric"), &labels, now); + + assert!(result.is_ok()); + } + } +} From 520fd8b6deb9d7ec5cc943ca622267565af304dd Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 18 Jun 2025 20:04:50 +0100 Subject: [PATCH 1233/1297] chore: [#1589] add debug logs for avg processing time metric update --- .../src/statistics/event/handler/response_sent.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs index 7e05e483b..e76d67a4e 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs @@ -19,6 +19,9 @@ pub async fn handle_event( let new_avg = stats_repository .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) .await; + + tracing::debug!("Updating average processing time metric for connect requests: {} ns", new_avg); + let mut label_set = LabelSet::from(context.clone()); label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); match stats_repository @@ -39,6 +42,12 @@ pub async fn handle_event( let new_avg = stats_repository .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) .await; + + tracing::debug!( + "Updating average processing time metric for announce requests: {} ns", + new_avg + ); + let mut label_set = LabelSet::from(context.clone()); label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); match stats_repository @@ -59,6 +68,9 @@ pub async fn handle_event( let new_avg = stats_repository .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) .await; + + tracing::debug!("Updating average processing time metric for scrape requests: {} ns", new_avg); + let mut label_set = LabelSet::from(context.clone()); label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); match stats_repository From e6c05b6886e241dbf6f2472d41b2c0cc47739756 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 19 Jun 2025 10:30:54 +0100 Subject: [PATCH 1234/1297] refactor(udp-tracker-server): [#1589] move average processing time calculation from Repository to Metrics --- .../src/statistics/metrics.rs | 67 +++++++++++++++++++ .../src/statistics/repository.rs | 58 +--------------- 2 files changed, 70 insertions(+), 55 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index 3c162ff02..e0ca0aaaf 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -1,3 +1,5 @@ +use std::time::Duration; + use serde::Serialize; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; @@ -48,6 +50,71 @@ impl Metrics { } impl Metrics { + #[allow(clippy::cast_precision_loss)] + pub fn recalculate_udp_avg_connect_processing_time_ns(&self, req_processing_time: Duration) -> f64 { + let req_processing_time = req_processing_time.as_nanos() as f64; + let udp_connections_handled = (self.udp4_connections_handled() + self.udp6_connections_handled()) as f64; + + let previous_avg = self.udp_avg_connect_processing_time_ns(); + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_connections_handled; + + tracing::debug!( + "Recalculated UDP average connect processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_connections_handled: {})", + new_avg, + previous_avg, + req_processing_time, + udp_connections_handled + ); + + new_avg + } + + #[allow(clippy::cast_precision_loss)] + pub fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) -> f64 { + let req_processing_time = req_processing_time.as_nanos() as f64; + + let udp_announces_handled = (self.udp4_announces_handled() + self.udp6_announces_handled()) as f64; + + let previous_avg = self.udp_avg_announce_processing_time_ns(); + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_announces_handled; + + tracing::debug!( + "Recalculated UDP average announce processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_announces_handled: {})", + new_avg, + previous_avg, + req_processing_time, + udp_announces_handled + ); + + new_avg + } + + #[allow(clippy::cast_precision_loss)] + pub fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) -> f64 { + let req_processing_time = req_processing_time.as_nanos() as f64; + + let udp_scrapes_handled = (self.udp4_scrapes_handled() + self.udp6_scrapes_handled()) as f64; + + let previous_avg = self.udp_avg_scrape_processing_time_ns(); + + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_scrapes_handled; + + tracing::debug!( + "Recalculated UDP average scrape processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_scrapes_handled: {})", + new_avg, + previous_avg, + req_processing_time, + udp_scrapes_handled + ); + + new_avg + } + // UDP /// Total number of UDP (UDP tracker) requests aborted. #[must_use] diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index eb0951614..2d081767e 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -73,85 +73,33 @@ impl Repository { result } - #[allow(clippy::cast_precision_loss)] - #[allow(clippy::cast_possible_truncation)] - #[allow(clippy::cast_sign_loss)] pub async fn recalculate_udp_avg_connect_processing_time_ns(&self, req_processing_time: Duration) -> f64 { let stats_lock = self.stats.write().await; - let req_processing_time = req_processing_time.as_nanos() as f64; - let udp_connections_handled = (stats_lock.udp4_connections_handled() + stats_lock.udp6_connections_handled()) as f64; - - let previous_avg = stats_lock.udp_avg_connect_processing_time_ns(); - - // Moving average: https://en.wikipedia.org/wiki/Moving_average - let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_connections_handled; + let new_avg = stats_lock.recalculate_udp_avg_connect_processing_time_ns(req_processing_time); drop(stats_lock); - tracing::debug!( - "Recalculated UDP average connect processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_connections_handled: {})", - new_avg, - previous_avg, - req_processing_time, - udp_connections_handled - ); - new_avg } - #[allow(clippy::cast_precision_loss)] - #[allow(clippy::cast_possible_truncation)] - #[allow(clippy::cast_sign_loss)] pub async fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) -> f64 { let stats_lock = self.stats.write().await; - let req_processing_time = req_processing_time.as_nanos() as f64; - - let udp_announces_handled = (stats_lock.udp4_announces_handled() + stats_lock.udp6_announces_handled()) as f64; - - let previous_avg = stats_lock.udp_avg_announce_processing_time_ns(); - - // Moving average: https://en.wikipedia.org/wiki/Moving_average - let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_announces_handled; + let new_avg = stats_lock.recalculate_udp_avg_announce_processing_time_ns(req_processing_time); drop(stats_lock); - tracing::debug!( - "Recalculated UDP average announce processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_announces_handled: {})", - new_avg, - previous_avg, - req_processing_time, - udp_announces_handled - ); - new_avg } - #[allow(clippy::cast_precision_loss)] - #[allow(clippy::cast_possible_truncation)] - #[allow(clippy::cast_sign_loss)] pub async fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) -> f64 { let stats_lock = self.stats.write().await; - let req_processing_time = req_processing_time.as_nanos() as f64; - let udp_scrapes_handled = (stats_lock.udp4_scrapes_handled() + stats_lock.udp6_scrapes_handled()) as f64; - - let previous_avg = stats_lock.udp_avg_scrape_processing_time_ns(); - - // Moving average: https://en.wikipedia.org/wiki/Moving_average - let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_scrapes_handled; + let new_avg = stats_lock.recalculate_udp_avg_scrape_processing_time_ns(req_processing_time); drop(stats_lock); - tracing::debug!( - "Recalculated UDP average scrape processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_scrapes_handled: {})", - new_avg, - previous_avg, - req_processing_time, - udp_scrapes_handled - ); - new_avg } } From d50948ea1a5a311605adba930d464c3334835df1 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 19 Jun 2025 11:19:57 +0100 Subject: [PATCH 1235/1297] refactor: [#1598] make recalculate udp avg connect processing time metric and update atomic It also fixes a division by zero bug when the metrics is updated before the counter for number of conenctions has been increased. It only avoid the division by zero. I will propoerly fixed with independent request counter for the moving average calculation. --- .../statistics/event/handler/response_sent.rs | 23 ++------ .../src/statistics/metrics.rs | 31 +++++++++-- .../src/statistics/repository.rs | 53 ++++++++++++++----- 3 files changed, 73 insertions(+), 34 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs index e76d67a4e..7b271f872 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs @@ -16,26 +16,13 @@ pub async fn handle_event( let (result_label_value, kind_label_value) = match kind { UdpResponseKind::Ok { req_kind } => match req_kind { UdpRequestKind::Connect => { - let new_avg = stats_repository - .recalculate_udp_avg_connect_processing_time_ns(req_processing_time) - .await; - - tracing::debug!("Updating average processing time metric for connect requests: {} ns", new_avg); - let mut label_set = LabelSet::from(context.clone()); label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); - match stats_repository - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &label_set, - new_avg, - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to set gauge: {}", err), - } + + let _new_avg = stats_repository + .recalculate_udp_avg_connect_processing_time_ns(req_processing_time, &label_set, now) + .await; + (LabelValue::new("ok"), UdpRequestKind::Connect.into()) } UdpRequestKind::Announce { announce_request } => { diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index e0ca0aaaf..61902dbba 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -51,14 +51,23 @@ impl Metrics { impl Metrics { #[allow(clippy::cast_precision_loss)] - pub fn recalculate_udp_avg_connect_processing_time_ns(&self, req_processing_time: Duration) -> f64 { + pub fn recalculate_udp_avg_connect_processing_time_ns( + &mut self, + req_processing_time: Duration, + label_set: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> f64 { let req_processing_time = req_processing_time.as_nanos() as f64; let udp_connections_handled = (self.udp4_connections_handled() + self.udp6_connections_handled()) as f64; let previous_avg = self.udp_avg_connect_processing_time_ns(); - // Moving average: https://en.wikipedia.org/wiki/Moving_average - let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_connections_handled; + let new_avg = if udp_connections_handled == 0.0 { + req_processing_time + } else { + // Moving average: https://en.wikipedia.org/wiki/Moving_average + previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_connections_handled + }; tracing::debug!( "Recalculated UDP average connect processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_connections_handled: {})", @@ -68,9 +77,25 @@ impl Metrics { udp_connections_handled ); + self.update_udp_avg_connect_processing_time_ns(new_avg, label_set, now); + new_avg } + fn update_udp_avg_connect_processing_time_ns(&mut self, new_avg: f64, label_set: &LabelSet, now: DurationSinceUnixEpoch) { + tracing::debug!("Updating average processing time metric for connect requests: {} ns", new_avg); + + match self.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + label_set, + new_avg, + now, + ) { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } + } + #[allow(clippy::cast_precision_loss)] pub fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) -> f64 { let req_processing_time = req_processing_time.as_nanos() as f64; diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index 2d081767e..cb6979a83 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -73,10 +73,15 @@ impl Repository { result } - pub async fn recalculate_udp_avg_connect_processing_time_ns(&self, req_processing_time: Duration) -> f64 { - let stats_lock = self.stats.write().await; + pub async fn recalculate_udp_avg_connect_processing_time_ns( + &self, + req_processing_time: Duration, + label_set: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> f64 { + let mut stats_lock = self.stats.write().await; - let new_avg = stats_lock.recalculate_udp_avg_connect_processing_time_ns(req_processing_time); + let new_avg = stats_lock.recalculate_udp_avg_connect_processing_time_ns(req_processing_time, label_set, now); drop(stats_lock); @@ -338,7 +343,9 @@ mod tests { // Calculate new average with processing time of 2000ns let processing_time = Duration::from_nanos(2000); - let new_avg = repo.recalculate_udp_avg_connect_processing_time_ns(processing_time).await; + let new_avg = repo + .recalculate_udp_avg_connect_processing_time_ns(processing_time, &connect_labels, now) + .await; // Moving average: previous_avg + (new_value - previous_avg) / total_connections // 1000 + (2000 - 1000) / 3 = 1000 + 333.33 = 1333.33 @@ -436,17 +443,25 @@ mod tests { #[tokio::test] async fn recalculate_average_methods_should_handle_zero_connections_gracefully() { let repo = Repository::new(); + let now = CurrentClock::now(); // Test with zero connections (should not panic, should handle division by zero) let processing_time = Duration::from_nanos(1000); - let connect_avg = repo.recalculate_udp_avg_connect_processing_time_ns(processing_time).await; + let connect_labels = LabelSet::from([("request_kind", "connect")]); + let connect_avg = repo + .recalculate_udp_avg_connect_processing_time_ns(processing_time, &connect_labels, now) + .await; + + let _announce_labels = LabelSet::from([("request_kind", "announce")]); let announce_avg = repo.recalculate_udp_avg_announce_processing_time_ns(processing_time).await; + + let _scrape_labels = LabelSet::from([("request_kind", "scrape")]); let scrape_avg = repo.recalculate_udp_avg_scrape_processing_time_ns(processing_time).await; // With 0 total connections, the formula becomes 0 + (1000 - 0) / 0 // This should handle the division by zero case gracefully - assert!(connect_avg.is_infinite() || connect_avg.is_nan()); + assert!((connect_avg - 1000.0).abs() < f64::EPSILON); assert!(announce_avg.is_infinite() || announce_avg.is_nan()); assert!(scrape_avg.is_infinite() || scrape_avg.is_nan()); } @@ -500,7 +515,10 @@ mod tests { // Test with very large processing time let large_duration = Duration::from_secs(1); // 1 second = 1,000,000,000 ns - let new_avg = repo.recalculate_udp_avg_connect_processing_time_ns(large_duration).await; + let connect_labels = LabelSet::from([("request_kind", "connect")]); + let new_avg = repo + .recalculate_udp_avg_connect_processing_time_ns(large_duration, &connect_labels, now) + .await; // Should handle large numbers without overflow assert!(new_avg > 0.0); @@ -575,6 +593,7 @@ mod tests { #[tokio::test] async fn it_should_handle_moving_average_calculation_before_any_connections_are_recorded() { let repo = Repository::new(); + let connect_labels = LabelSet::from([("request_kind", "connect")]); let now = CurrentClock::now(); // This test checks the behavior of `recalculate_udp_avg_connect_processing_time_ns`` @@ -591,12 +610,13 @@ mod tests { // First calculation: no connections recorded yet, should result in infinity let processing_time_1 = Duration::from_nanos(2000); - let avg_1 = repo.recalculate_udp_avg_connect_processing_time_ns(processing_time_1).await; + let avg_1 = repo + .recalculate_udp_avg_connect_processing_time_ns(processing_time_1, &connect_labels, now) + .await; - // Division by zero: 1000 + (2000 - 1000) / 0 = infinity assert!( - avg_1.is_infinite(), - "First calculation should be infinite due to division by zero" + (avg_1 - 2000.0).abs() < f64::EPSILON, + "First calculation should be 2000, but got {avg_1}" ); // Now add one connection and try again @@ -605,10 +625,17 @@ mod tests { .await .unwrap(); - // Second calculation: 1 connection, but previous average is infinity + // Second calculation: 1 connection let processing_time_2 = Duration::from_nanos(3000); - let avg_2 = repo.recalculate_udp_avg_connect_processing_time_ns(processing_time_2).await; + let connect_labels = LabelSet::from([("request_kind", "connect")]); + let avg_2 = repo + .recalculate_udp_avg_connect_processing_time_ns(processing_time_2, &connect_labels, now) + .await; + // There is one connection, so the average should be: + // 2000 + (3000 - 2000) / 1 = 2000 + 1000 = 3000 + // This is because one connection is not counted yet in the average calculation, + // so the average is simply the processing time of the second connection. assert!( (avg_2 - 3000.0).abs() < f64::EPSILON, "Second calculation should be 3000ns, but got {avg_2}" From 59fbb39974fe731d5b6bc8dc50cee29816058780 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 19 Jun 2025 11:32:50 +0100 Subject: [PATCH 1236/1297] refactor: [#1598] make recalculate udp avg announce processing time metric and update atomic It also fixes a division by zero bug when the metrics is updated before the counter for number of conenctions has been increased. It only avoid the division by zero. I will propoerly fixed with independent request counter for the moving average calculation. --- .../statistics/event/handler/response_sent.rs | 26 ++-------- .../src/statistics/metrics.rs | 51 ++++++++++++------- .../src/statistics/repository.rs | 23 ++++++--- 3 files changed, 54 insertions(+), 46 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs index 7b271f872..3258a7023 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs @@ -26,29 +26,13 @@ pub async fn handle_event( (LabelValue::new("ok"), UdpRequestKind::Connect.into()) } UdpRequestKind::Announce { announce_request } => { - let new_avg = stats_repository - .recalculate_udp_avg_announce_processing_time_ns(req_processing_time) - .await; - - tracing::debug!( - "Updating average processing time metric for announce requests: {} ns", - new_avg - ); - let mut label_set = LabelSet::from(context.clone()); label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); - match stats_repository - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &label_set, - new_avg, - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to set gauge: {}", err), - } + + let _new_avg = stats_repository + .recalculate_udp_avg_announce_processing_time_ns(req_processing_time, &label_set, now) + .await; + (LabelValue::new("ok"), UdpRequestKind::Announce { announce_request }.into()) } UdpRequestKind::Scrape => { diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index 61902dbba..cef1c2824 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -77,35 +77,30 @@ impl Metrics { udp_connections_handled ); - self.update_udp_avg_connect_processing_time_ns(new_avg, label_set, now); + self.update_udp_avg_processing_time_ns(new_avg, label_set, now); new_avg } - fn update_udp_avg_connect_processing_time_ns(&mut self, new_avg: f64, label_set: &LabelSet, now: DurationSinceUnixEpoch) { - tracing::debug!("Updating average processing time metric for connect requests: {} ns", new_avg); - - match self.set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - label_set, - new_avg, - now, - ) { - Ok(()) => {} - Err(err) => tracing::error!("Failed to set gauge: {}", err), - } - } - #[allow(clippy::cast_precision_loss)] - pub fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) -> f64 { + pub fn recalculate_udp_avg_announce_processing_time_ns( + &mut self, + req_processing_time: Duration, + label_set: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> f64 { let req_processing_time = req_processing_time.as_nanos() as f64; let udp_announces_handled = (self.udp4_announces_handled() + self.udp6_announces_handled()) as f64; let previous_avg = self.udp_avg_announce_processing_time_ns(); - // Moving average: https://en.wikipedia.org/wiki/Moving_average - let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_announces_handled; + let new_avg = if udp_announces_handled == 0.0 { + req_processing_time + } else { + // Moving average: https://en.wikipedia.org/wiki/Moving_average + previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_announces_handled + }; tracing::debug!( "Recalculated UDP average announce processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_announces_handled: {})", @@ -115,9 +110,29 @@ impl Metrics { udp_announces_handled ); + self.update_udp_avg_processing_time_ns(new_avg, label_set, now); + new_avg } + fn update_udp_avg_processing_time_ns(&mut self, new_avg: f64, label_set: &LabelSet, now: DurationSinceUnixEpoch) { + tracing::debug!( + "Updating average processing time metric to {} ns for label set {}", + new_avg, + label_set, + ); + + match self.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + label_set, + new_avg, + now, + ) { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } + } + #[allow(clippy::cast_precision_loss)] pub fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) -> f64 { let req_processing_time = req_processing_time.as_nanos() as f64; diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index cb6979a83..024ff4535 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -88,10 +88,15 @@ impl Repository { new_avg } - pub async fn recalculate_udp_avg_announce_processing_time_ns(&self, req_processing_time: Duration) -> f64 { - let stats_lock = self.stats.write().await; + pub async fn recalculate_udp_avg_announce_processing_time_ns( + &self, + req_processing_time: Duration, + label_set: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> f64 { + let mut stats_lock = self.stats.write().await; - let new_avg = stats_lock.recalculate_udp_avg_announce_processing_time_ns(req_processing_time); + let new_avg = stats_lock.recalculate_udp_avg_announce_processing_time_ns(req_processing_time, label_set, now); drop(stats_lock); @@ -390,7 +395,9 @@ mod tests { // Calculate new average with processing time of 1500ns let processing_time = Duration::from_nanos(1500); - let new_avg = repo.recalculate_udp_avg_announce_processing_time_ns(processing_time).await; + let new_avg = repo + .recalculate_udp_avg_announce_processing_time_ns(processing_time, &announce_labels, now) + .await; // Moving average: previous_avg + (new_value - previous_avg) / total_announces // 500 + (1500 - 500) / 5 = 500 + 200 = 700 @@ -453,8 +460,10 @@ mod tests { .recalculate_udp_avg_connect_processing_time_ns(processing_time, &connect_labels, now) .await; - let _announce_labels = LabelSet::from([("request_kind", "announce")]); - let announce_avg = repo.recalculate_udp_avg_announce_processing_time_ns(processing_time).await; + let announce_labels = LabelSet::from([("request_kind", "announce")]); + let announce_avg = repo + .recalculate_udp_avg_announce_processing_time_ns(processing_time, &announce_labels, now) + .await; let _scrape_labels = LabelSet::from([("request_kind", "scrape")]); let scrape_avg = repo.recalculate_udp_avg_scrape_processing_time_ns(processing_time).await; @@ -462,7 +471,7 @@ mod tests { // With 0 total connections, the formula becomes 0 + (1000 - 0) / 0 // This should handle the division by zero case gracefully assert!((connect_avg - 1000.0).abs() < f64::EPSILON); - assert!(announce_avg.is_infinite() || announce_avg.is_nan()); + assert!((announce_avg - 1000.0).abs() < f64::EPSILON); assert!(scrape_avg.is_infinite() || scrape_avg.is_nan()); } From 47c294987725dba83363460c68222f914efcb698 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 19 Jun 2025 12:05:58 +0100 Subject: [PATCH 1237/1297] refactor: [#1598] make recalculate udp avg scrape processing time metric and update atomic It also fixes a division by zero bug when the metrics is updated before the counter for number of conenctions has been increased. It only avoid the division by zero. I will propoerly fixed with independent request counter for the moving average calculation. --- .../statistics/event/handler/response_sent.rs | 27 +++------- .../src/statistics/metrics.rs | 53 +++++++++++-------- .../src/statistics/repository.rs | 23 +++++--- 3 files changed, 55 insertions(+), 48 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs index 3258a7023..7594d16f2 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs @@ -4,7 +4,7 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::event::{ConnectionContext, UdpRequestKind, UdpResponseKind}; use crate::statistics::repository::Repository; -use crate::statistics::{UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL}; +use crate::statistics::UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL; pub async fn handle_event( context: ConnectionContext, @@ -36,33 +36,20 @@ pub async fn handle_event( (LabelValue::new("ok"), UdpRequestKind::Announce { announce_request }.into()) } UdpRequestKind::Scrape => { - let new_avg = stats_repository - .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time) - .await; - - tracing::debug!("Updating average processing time metric for scrape requests: {} ns", new_avg); - let mut label_set = LabelSet::from(context.clone()); label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); - match stats_repository - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &label_set, - new_avg, - now, - ) - .await - { - Ok(()) => {} - Err(err) => tracing::error!("Failed to set gauge: {}", err), - } + + let _new_avg = stats_repository + .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time, &label_set, now) + .await; + (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Scrape.to_string())) } }, UdpResponseKind::Error { opt_req_kind: _ } => (LabelValue::new("error"), LabelValue::ignore()), }; - // Extendable metrics + // Increase the number of responses sent let mut label_set = LabelSet::from(context); if result_label_value == LabelValue::new("ok") { label_set.upsert(label_name!("request_kind"), kind_label_value); diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index cef1c2824..eedd1a02f 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -115,34 +115,25 @@ impl Metrics { new_avg } - fn update_udp_avg_processing_time_ns(&mut self, new_avg: f64, label_set: &LabelSet, now: DurationSinceUnixEpoch) { - tracing::debug!( - "Updating average processing time metric to {} ns for label set {}", - new_avg, - label_set, - ); - - match self.set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - label_set, - new_avg, - now, - ) { - Ok(()) => {} - Err(err) => tracing::error!("Failed to set gauge: {}", err), - } - } - #[allow(clippy::cast_precision_loss)] - pub fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) -> f64 { + pub fn recalculate_udp_avg_scrape_processing_time_ns( + &mut self, + req_processing_time: Duration, + label_set: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> f64 { let req_processing_time = req_processing_time.as_nanos() as f64; let udp_scrapes_handled = (self.udp4_scrapes_handled() + self.udp6_scrapes_handled()) as f64; let previous_avg = self.udp_avg_scrape_processing_time_ns(); - // Moving average: https://en.wikipedia.org/wiki/Moving_average - let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_scrapes_handled; + let new_avg = if udp_scrapes_handled == 0.0 { + req_processing_time + } else { + // Moving average: https://en.wikipedia.org/wiki/Moving_average + previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_scrapes_handled + }; tracing::debug!( "Recalculated UDP average scrape processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_scrapes_handled: {})", @@ -152,9 +143,29 @@ impl Metrics { udp_scrapes_handled ); + self.update_udp_avg_processing_time_ns(new_avg, label_set, now); + new_avg } + fn update_udp_avg_processing_time_ns(&mut self, new_avg: f64, label_set: &LabelSet, now: DurationSinceUnixEpoch) { + tracing::debug!( + "Updating average processing time metric to {} ns for label set {}", + new_avg, + label_set, + ); + + match self.set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + label_set, + new_avg, + now, + ) { + Ok(()) => {} + Err(err) => tracing::error!("Failed to set gauge: {}", err), + } + } + // UDP /// Total number of UDP (UDP tracker) requests aborted. #[must_use] diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index 024ff4535..c9b3d0548 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -103,10 +103,15 @@ impl Repository { new_avg } - pub async fn recalculate_udp_avg_scrape_processing_time_ns(&self, req_processing_time: Duration) -> f64 { - let stats_lock = self.stats.write().await; + pub async fn recalculate_udp_avg_scrape_processing_time_ns( + &self, + req_processing_time: Duration, + label_set: &LabelSet, + now: DurationSinceUnixEpoch, + ) -> f64 { + let mut stats_lock = self.stats.write().await; - let new_avg = stats_lock.recalculate_udp_avg_scrape_processing_time_ns(req_processing_time); + let new_avg = stats_lock.recalculate_udp_avg_scrape_processing_time_ns(req_processing_time, label_set, now); drop(stats_lock); @@ -436,7 +441,9 @@ mod tests { // Calculate new average with processing time of 1200ns let processing_time = Duration::from_nanos(1200); - let new_avg = repo.recalculate_udp_avg_scrape_processing_time_ns(processing_time).await; + let new_avg = repo + .recalculate_udp_avg_scrape_processing_time_ns(processing_time, &scrape_labels, now) + .await; // Moving average: previous_avg + (new_value - previous_avg) / total_scrapes // 800 + (1200 - 800) / 4 = 800 + 100 = 900 @@ -465,14 +472,16 @@ mod tests { .recalculate_udp_avg_announce_processing_time_ns(processing_time, &announce_labels, now) .await; - let _scrape_labels = LabelSet::from([("request_kind", "scrape")]); - let scrape_avg = repo.recalculate_udp_avg_scrape_processing_time_ns(processing_time).await; + let scrape_labels = LabelSet::from([("request_kind", "scrape")]); + let scrape_avg = repo + .recalculate_udp_avg_scrape_processing_time_ns(processing_time, &scrape_labels, now) + .await; // With 0 total connections, the formula becomes 0 + (1000 - 0) / 0 // This should handle the division by zero case gracefully assert!((connect_avg - 1000.0).abs() < f64::EPSILON); assert!((announce_avg - 1000.0).abs() < f64::EPSILON); - assert!(scrape_avg.is_infinite() || scrape_avg.is_nan()); + assert!((scrape_avg - 1000.0).abs() < f64::EPSILON); } #[tokio::test] From 1c13b12c7cf6c4f109cebea8e8c85ccebb1f99c6 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 19 Jun 2025 12:27:16 +0100 Subject: [PATCH 1238/1297] fix: [#1589] partially. Moving average calculated for each time series We can't count the total number of UDP requests while calculating the moving average but updating it only for a concrete label set (time series). Averages are calculate for each label set. They could be aggregated by caclulating the average for all time series. --- .../src/statistics/metrics.rs | 52 +++++++++++++------ 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index eedd1a02f..8e32c1f4c 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -58,15 +58,16 @@ impl Metrics { now: DurationSinceUnixEpoch, ) -> f64 { let req_processing_time = req_processing_time.as_nanos() as f64; - let udp_connections_handled = (self.udp4_connections_handled() + self.udp6_connections_handled()) as f64; - let previous_avg = self.udp_avg_connect_processing_time_ns(); + let request_accepted_total = self.udp_request_accepted(label_set) as f64; - let new_avg = if udp_connections_handled == 0.0 { + let previous_avg = self.udp_avg_processing_time_ns(label_set); + + let new_avg = if request_accepted_total == 0.0 { req_processing_time } else { // Moving average: https://en.wikipedia.org/wiki/Moving_average - previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_connections_handled + previous_avg as f64 + (req_processing_time - previous_avg as f64) / request_accepted_total }; tracing::debug!( @@ -74,7 +75,7 @@ impl Metrics { new_avg, previous_avg, req_processing_time, - udp_connections_handled + request_accepted_total ); self.update_udp_avg_processing_time_ns(new_avg, label_set, now); @@ -91,15 +92,15 @@ impl Metrics { ) -> f64 { let req_processing_time = req_processing_time.as_nanos() as f64; - let udp_announces_handled = (self.udp4_announces_handled() + self.udp6_announces_handled()) as f64; + let request_accepted_total = self.udp_request_accepted(label_set) as f64; - let previous_avg = self.udp_avg_announce_processing_time_ns(); + let previous_avg = self.udp_avg_processing_time_ns(label_set); - let new_avg = if udp_announces_handled == 0.0 { + let new_avg = if request_accepted_total == 0.0 { req_processing_time } else { // Moving average: https://en.wikipedia.org/wiki/Moving_average - previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_announces_handled + previous_avg as f64 + (req_processing_time - previous_avg as f64) / request_accepted_total }; tracing::debug!( @@ -107,7 +108,7 @@ impl Metrics { new_avg, previous_avg, req_processing_time, - udp_announces_handled + request_accepted_total ); self.update_udp_avg_processing_time_ns(new_avg, label_set, now); @@ -124,15 +125,15 @@ impl Metrics { ) -> f64 { let req_processing_time = req_processing_time.as_nanos() as f64; - let udp_scrapes_handled = (self.udp4_scrapes_handled() + self.udp6_scrapes_handled()) as f64; + let request_accepted_total = self.udp_request_accepted(label_set) as f64; - let previous_avg = self.udp_avg_scrape_processing_time_ns(); + let previous_avg = self.udp_avg_processing_time_ns(label_set); - let new_avg = if udp_scrapes_handled == 0.0 { + let new_avg = if request_accepted_total == 0.0 { req_processing_time } else { // Moving average: https://en.wikipedia.org/wiki/Moving_average - previous_avg as f64 + (req_processing_time - previous_avg as f64) / udp_scrapes_handled + previous_avg as f64 + (req_processing_time - previous_avg as f64) / request_accepted_total }; tracing::debug!( @@ -140,7 +141,7 @@ impl Metrics { new_avg, previous_avg, req_processing_time, - udp_scrapes_handled + request_accepted_total ); self.update_udp_avg_processing_time_ns(new_avg, label_set, now); @@ -148,6 +149,27 @@ impl Metrics { new_avg } + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_avg_processing_time_ns(&self, label_set: &LabelSet) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + label_set, + ) + .unwrap_or_default() as u64 + } + + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_request_accepted(&self, label_set: &LabelSet) -> u64 { + self.metric_collection + .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), label_set) + .unwrap_or_default() as u64 + } + fn update_udp_avg_processing_time_ns(&mut self, new_avg: f64, label_set: &LabelSet, now: DurationSinceUnixEpoch) { tracing::debug!( "Updating average processing time metric to {} ns for label set {}", From 164de924999367b6fb714c2ecea38da7ad99b0fb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 19 Jun 2025 13:59:55 +0100 Subject: [PATCH 1239/1297] refactor: [#1589] remvoe duplicate code --- .../statistics/event/handler/response_sent.rs | 6 +- .../src/statistics/metrics.rs | 71 +------------------ .../src/statistics/repository.rs | 52 +++----------- 3 files changed, 17 insertions(+), 112 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs index 7594d16f2..34093f511 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs @@ -20,7 +20,7 @@ pub async fn handle_event( label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); let _new_avg = stats_repository - .recalculate_udp_avg_connect_processing_time_ns(req_processing_time, &label_set, now) + .recalculate_udp_avg_processing_time_ns(req_processing_time, &label_set, now) .await; (LabelValue::new("ok"), UdpRequestKind::Connect.into()) @@ -30,7 +30,7 @@ pub async fn handle_event( label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); let _new_avg = stats_repository - .recalculate_udp_avg_announce_processing_time_ns(req_processing_time, &label_set, now) + .recalculate_udp_avg_processing_time_ns(req_processing_time, &label_set, now) .await; (LabelValue::new("ok"), UdpRequestKind::Announce { announce_request }.into()) @@ -40,7 +40,7 @@ pub async fn handle_event( label_set.upsert(label_name!("request_kind"), LabelValue::new(&req_kind.to_string())); let _new_avg = stats_repository - .recalculate_udp_avg_scrape_processing_time_ns(req_processing_time, &label_set, now) + .recalculate_udp_avg_processing_time_ns(req_processing_time, &label_set, now) .await; (LabelValue::new("ok"), LabelValue::new(&UdpRequestKind::Scrape.to_string())) diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index 8e32c1f4c..bfed16c47 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -51,7 +51,7 @@ impl Metrics { impl Metrics { #[allow(clippy::cast_precision_loss)] - pub fn recalculate_udp_avg_connect_processing_time_ns( + pub fn recalculate_udp_avg_processing_time_ns( &mut self, req_processing_time: Duration, label_set: &LabelSet, @@ -71,73 +71,8 @@ impl Metrics { }; tracing::debug!( - "Recalculated UDP average connect processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_connections_handled: {})", - new_avg, - previous_avg, - req_processing_time, - request_accepted_total - ); - - self.update_udp_avg_processing_time_ns(new_avg, label_set, now); - - new_avg - } - - #[allow(clippy::cast_precision_loss)] - pub fn recalculate_udp_avg_announce_processing_time_ns( - &mut self, - req_processing_time: Duration, - label_set: &LabelSet, - now: DurationSinceUnixEpoch, - ) -> f64 { - let req_processing_time = req_processing_time.as_nanos() as f64; - - let request_accepted_total = self.udp_request_accepted(label_set) as f64; - - let previous_avg = self.udp_avg_processing_time_ns(label_set); - - let new_avg = if request_accepted_total == 0.0 { - req_processing_time - } else { - // Moving average: https://en.wikipedia.org/wiki/Moving_average - previous_avg as f64 + (req_processing_time - previous_avg as f64) / request_accepted_total - }; - - tracing::debug!( - "Recalculated UDP average announce processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_announces_handled: {})", - new_avg, - previous_avg, - req_processing_time, - request_accepted_total - ); - - self.update_udp_avg_processing_time_ns(new_avg, label_set, now); - - new_avg - } - - #[allow(clippy::cast_precision_loss)] - pub fn recalculate_udp_avg_scrape_processing_time_ns( - &mut self, - req_processing_time: Duration, - label_set: &LabelSet, - now: DurationSinceUnixEpoch, - ) -> f64 { - let req_processing_time = req_processing_time.as_nanos() as f64; - - let request_accepted_total = self.udp_request_accepted(label_set) as f64; - - let previous_avg = self.udp_avg_processing_time_ns(label_set); - - let new_avg = if request_accepted_total == 0.0 { - req_processing_time - } else { - // Moving average: https://en.wikipedia.org/wiki/Moving_average - previous_avg as f64 + (req_processing_time - previous_avg as f64) / request_accepted_total - }; - - tracing::debug!( - "Recalculated UDP average scrape processing time: {} ns (previous: {} ns, req_processing_time: {} ns, udp_scrapes_handled: {})", + "Recalculated UDP average processing time for labels {}: {} ns (previous: {} ns, req_processing_time: {} ns, request_accepted_total: {})", + label_set, new_avg, previous_avg, req_processing_time, diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index c9b3d0548..6695bbfbc 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -73,7 +73,7 @@ impl Repository { result } - pub async fn recalculate_udp_avg_connect_processing_time_ns( + pub async fn recalculate_udp_avg_processing_time_ns( &self, req_processing_time: Duration, label_set: &LabelSet, @@ -81,37 +81,7 @@ impl Repository { ) -> f64 { let mut stats_lock = self.stats.write().await; - let new_avg = stats_lock.recalculate_udp_avg_connect_processing_time_ns(req_processing_time, label_set, now); - - drop(stats_lock); - - new_avg - } - - pub async fn recalculate_udp_avg_announce_processing_time_ns( - &self, - req_processing_time: Duration, - label_set: &LabelSet, - now: DurationSinceUnixEpoch, - ) -> f64 { - let mut stats_lock = self.stats.write().await; - - let new_avg = stats_lock.recalculate_udp_avg_announce_processing_time_ns(req_processing_time, label_set, now); - - drop(stats_lock); - - new_avg - } - - pub async fn recalculate_udp_avg_scrape_processing_time_ns( - &self, - req_processing_time: Duration, - label_set: &LabelSet, - now: DurationSinceUnixEpoch, - ) -> f64 { - let mut stats_lock = self.stats.write().await; - - let new_avg = stats_lock.recalculate_udp_avg_scrape_processing_time_ns(req_processing_time, label_set, now); + let new_avg = stats_lock.recalculate_udp_avg_processing_time_ns(req_processing_time, label_set, now); drop(stats_lock); @@ -354,7 +324,7 @@ mod tests { // Calculate new average with processing time of 2000ns let processing_time = Duration::from_nanos(2000); let new_avg = repo - .recalculate_udp_avg_connect_processing_time_ns(processing_time, &connect_labels, now) + .recalculate_udp_avg_processing_time_ns(processing_time, &connect_labels, now) .await; // Moving average: previous_avg + (new_value - previous_avg) / total_connections @@ -401,7 +371,7 @@ mod tests { // Calculate new average with processing time of 1500ns let processing_time = Duration::from_nanos(1500); let new_avg = repo - .recalculate_udp_avg_announce_processing_time_ns(processing_time, &announce_labels, now) + .recalculate_udp_avg_processing_time_ns(processing_time, &announce_labels, now) .await; // Moving average: previous_avg + (new_value - previous_avg) / total_announces @@ -442,7 +412,7 @@ mod tests { // Calculate new average with processing time of 1200ns let processing_time = Duration::from_nanos(1200); let new_avg = repo - .recalculate_udp_avg_scrape_processing_time_ns(processing_time, &scrape_labels, now) + .recalculate_udp_avg_processing_time_ns(processing_time, &scrape_labels, now) .await; // Moving average: previous_avg + (new_value - previous_avg) / total_scrapes @@ -464,17 +434,17 @@ mod tests { let connect_labels = LabelSet::from([("request_kind", "connect")]); let connect_avg = repo - .recalculate_udp_avg_connect_processing_time_ns(processing_time, &connect_labels, now) + .recalculate_udp_avg_processing_time_ns(processing_time, &connect_labels, now) .await; let announce_labels = LabelSet::from([("request_kind", "announce")]); let announce_avg = repo - .recalculate_udp_avg_announce_processing_time_ns(processing_time, &announce_labels, now) + .recalculate_udp_avg_processing_time_ns(processing_time, &announce_labels, now) .await; let scrape_labels = LabelSet::from([("request_kind", "scrape")]); let scrape_avg = repo - .recalculate_udp_avg_scrape_processing_time_ns(processing_time, &scrape_labels, now) + .recalculate_udp_avg_processing_time_ns(processing_time, &scrape_labels, now) .await; // With 0 total connections, the formula becomes 0 + (1000 - 0) / 0 @@ -535,7 +505,7 @@ mod tests { let large_duration = Duration::from_secs(1); // 1 second = 1,000,000,000 ns let connect_labels = LabelSet::from([("request_kind", "connect")]); let new_avg = repo - .recalculate_udp_avg_connect_processing_time_ns(large_duration, &connect_labels, now) + .recalculate_udp_avg_processing_time_ns(large_duration, &connect_labels, now) .await; // Should handle large numbers without overflow @@ -629,7 +599,7 @@ mod tests { // First calculation: no connections recorded yet, should result in infinity let processing_time_1 = Duration::from_nanos(2000); let avg_1 = repo - .recalculate_udp_avg_connect_processing_time_ns(processing_time_1, &connect_labels, now) + .recalculate_udp_avg_processing_time_ns(processing_time_1, &connect_labels, now) .await; assert!( @@ -647,7 +617,7 @@ mod tests { let processing_time_2 = Duration::from_nanos(3000); let connect_labels = LabelSet::from([("request_kind", "connect")]); let avg_2 = repo - .recalculate_udp_avg_connect_processing_time_ns(processing_time_2, &connect_labels, now) + .recalculate_udp_avg_processing_time_ns(processing_time_2, &connect_labels, now) .await; // There is one connection, so the average should be: From ed5f1e69de7fc05a87250614425b562fb7db67b9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Thu, 19 Jun 2025 22:28:30 +0100 Subject: [PATCH 1240/1297] fix: [#1589] add dedicated metric for UDP request processing in moving average calculation Add a new metric `UDP_TRACKER_SERVER_PERFORMANCE_PROCESSED_REQUESTS_TOTAL` to track requests processed specifically for performance metrics, eliminating race conditions in the moving average calculation. **Changes:** - Add new metric constant `UDP_TRACKER_SERVER_PERFORMANCE_PROCESSED_REQUESTS_TOTAL` - Update `recalculate_udp_avg_processing_time_ns()` to use dedicated counter instead of accepted requests total - Add `udp_processed_requests_total()` method to retrieve the new metric value - Add `increment_udp_processed_requests_total()` helper method - Update metric descriptions to include the new counter **Problem Fixed:** Previously, the moving average calculation used the accepted requests counter that could be updated independently, causing race conditions where the same request count was used for multiple calculations. The new implementation increments its own dedicated counter atomically during the calculation, ensuring consistency. **Behavior Change:** The counter now starts at 0 and gets incremented to 1 on the first calculation call, then uses proper moving average formula for subsequent calls. This eliminates division by zero issues and provides more accurate moving averages. **Tests Updated:** Updated repository tests to reflect the new atomic behavior where the processed requests counter is managed specifically for moving average calculations. Fixes race conditions in UDP request processing time metrics while maintaining backward compatibility of all public APIs. --- .../src/statistics/metrics.rs | 78 ++++++++++--- .../udp-tracker-server/src/statistics/mod.rs | 10 ++ .../src/statistics/repository.rs | 106 +++++------------- 3 files changed, 103 insertions(+), 91 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index bfed16c47..e7653815f 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -9,7 +9,8 @@ use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::statistics::{ - UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_IPS_BANNED_TOTAL, UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, + UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_IPS_BANNED_TOTAL, + UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL, UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL, UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL, @@ -57,26 +58,22 @@ impl Metrics { label_set: &LabelSet, now: DurationSinceUnixEpoch, ) -> f64 { - let req_processing_time = req_processing_time.as_nanos() as f64; - - let request_accepted_total = self.udp_request_accepted(label_set) as f64; + self.increment_udp_processed_requests_total(label_set, now); + let processed_requests_total = self.udp_processed_requests_total(label_set) as f64; let previous_avg = self.udp_avg_processing_time_ns(label_set); + let req_processing_time = req_processing_time.as_nanos() as f64; - let new_avg = if request_accepted_total == 0.0 { - req_processing_time - } else { - // Moving average: https://en.wikipedia.org/wiki/Moving_average - previous_avg as f64 + (req_processing_time - previous_avg as f64) / request_accepted_total - }; + // Moving average: https://en.wikipedia.org/wiki/Moving_average + let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / processed_requests_total; tracing::debug!( - "Recalculated UDP average processing time for labels {}: {} ns (previous: {} ns, req_processing_time: {} ns, request_accepted_total: {})", + "Recalculated UDP average processing time for labels {}: {} ns (previous: {} ns, req_processing_time: {} ns, request_processed_total: {})", label_set, new_avg, previous_avg, req_processing_time, - request_accepted_total + processed_requests_total ); self.update_udp_avg_processing_time_ns(new_avg, label_set, now); @@ -105,6 +102,18 @@ impl Metrics { .unwrap_or_default() as u64 } + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_processed_requests_total(&self, label_set: &LabelSet) -> u64 { + self.metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), + label_set, + ) + .unwrap_or_default() as u64 + } + fn update_udp_avg_processing_time_ns(&mut self, new_avg: f64, label_set: &LabelSet, now: DurationSinceUnixEpoch) { tracing::debug!( "Updating average processing time metric to {} ns for label set {}", @@ -123,6 +132,19 @@ impl Metrics { } } + fn increment_udp_processed_requests_total(&mut self, label_set: &LabelSet, now: DurationSinceUnixEpoch) { + tracing::debug!("Incrementing processed requests total for label set {}", label_set,); + + match self.increase_counter( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), + label_set, + now, + ) { + Ok(()) => {} + Err(err) => tracing::error!("Failed to increment counter: {}", err), + } + } + // UDP /// Total number of UDP (UDP tracker) requests aborted. #[must_use] @@ -360,9 +382,10 @@ mod tests { use super::*; use crate::statistics::{ UDP_TRACKER_SERVER_ERRORS_TOTAL, UDP_TRACKER_SERVER_IPS_BANNED_TOTAL, - UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL, - UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL, - UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL, UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL, + UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL, UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS, + UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL, + UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL, UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL, + UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL, }; use crate::CurrentClock; @@ -437,6 +460,31 @@ mod tests { assert!(result.is_ok()); } + #[test] + fn it_should_return_zero_for_udp_processed_requests_total_when_no_data() { + let metrics = Metrics::default(); + let labels = LabelSet::from([("request_kind", "connect")]); + assert_eq!(metrics.udp_processed_requests_total(&labels), 0); + } + + #[test] + fn it_should_increment_processed_requests_total() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("request_kind", "connect")]); + + // Directly increment the counter using the public method + metrics + .increase_counter( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), + &labels, + now, + ) + .unwrap(); + + assert_eq!(metrics.udp_processed_requests_total(&labels), 1); + } + mod udp_general_metrics { use super::*; diff --git a/packages/udp-tracker-server/src/statistics/mod.rs b/packages/udp-tracker-server/src/statistics/mod.rs index 768722ba3..6bd35b9a1 100644 --- a/packages/udp-tracker-server/src/statistics/mod.rs +++ b/packages/udp-tracker-server/src/statistics/mod.rs @@ -17,6 +17,8 @@ pub const UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL: &str = "udp_tracker_server pub const UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL: &str = "udp_tracker_server_responses_sent_total"; pub const UDP_TRACKER_SERVER_ERRORS_TOTAL: &str = "udp_tracker_server_errors_total"; pub const UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS: &str = "udp_tracker_server_performance_avg_processing_time_ns"; +pub const UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL: &str = + "udp_tracker_server_performance_avg_processed_requests_total"; #[must_use] pub fn describe_metrics() -> Metrics { @@ -76,5 +78,13 @@ pub fn describe_metrics() -> Metrics { Some(MetricDescription::new("Average time to process a UDP request in nanoseconds")), ); + metrics.metric_collection.describe_counter( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), + Some(Unit::Count), + Some(MetricDescription::new( + "Total number of UDP requests processed for the average performance metrics", + )), + ); + metrics } diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index 6695bbfbc..1ab2cc6a7 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -295,21 +295,6 @@ mod tests { let repo = Repository::new(); let now = CurrentClock::now(); - // Set up initial connections handled - let ipv4_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "connect")]); - let ipv6_labels = LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "connect")]); - - // Simulate 2 IPv4 and 1 IPv6 connections - repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv4_labels, now) - .await - .unwrap(); - repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv4_labels, now) - .await - .unwrap(); - repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv6_labels, now) - .await - .unwrap(); - // Set initial average to 1000ns let connect_labels = LabelSet::from([("request_kind", "connect")]); repo.set_gauge( @@ -322,14 +307,16 @@ mod tests { .unwrap(); // Calculate new average with processing time of 2000ns + // This will increment the processed requests counter from 0 to 1 let processing_time = Duration::from_nanos(2000); let new_avg = repo .recalculate_udp_avg_processing_time_ns(processing_time, &connect_labels, now) .await; - // Moving average: previous_avg + (new_value - previous_avg) / total_connections - // 1000 + (2000 - 1000) / 3 = 1000 + 333.33 = 1333.33 - let expected_avg = 1000.0 + (2000.0 - 1000.0) / 3.0; + // Moving average: previous_avg + (new_value - previous_avg) / processed_requests_total + // With processed_requests_total = 1 (incremented during the call): + // 1000 + (2000 - 1000) / 1 = 1000 + 1000 = 2000 + let expected_avg = 1000.0 + (2000.0 - 1000.0) / 1.0; assert!( (new_avg - expected_avg).abs() < 0.01, "Expected {expected_avg}, got {new_avg}" @@ -341,22 +328,6 @@ mod tests { let repo = Repository::new(); let now = CurrentClock::now(); - // Set up initial announces handled - let ipv4_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "announce")]); - let ipv6_labels = LabelSet::from([("server_binding_address_ip_family", "inet6"), ("request_kind", "announce")]); - - // Simulate 3 IPv4 and 2 IPv6 announces - for _ in 0..3 { - repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv4_labels, now) - .await - .unwrap(); - } - for _ in 0..2 { - repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv6_labels, now) - .await - .unwrap(); - } - // Set initial average to 500ns let announce_labels = LabelSet::from([("request_kind", "announce")]); repo.set_gauge( @@ -369,14 +340,16 @@ mod tests { .unwrap(); // Calculate new average with processing time of 1500ns + // This will increment the processed requests counter from 0 to 1 let processing_time = Duration::from_nanos(1500); let new_avg = repo .recalculate_udp_avg_processing_time_ns(processing_time, &announce_labels, now) .await; - // Moving average: previous_avg + (new_value - previous_avg) / total_announces - // 500 + (1500 - 500) / 5 = 500 + 200 = 700 - let expected_avg = 500.0 + (1500.0 - 500.0) / 5.0; + // Moving average: previous_avg + (new_value - previous_avg) / processed_requests_total + // With processed_requests_total = 1 (incremented during the call): + // 500 + (1500 - 500) / 1 = 500 + 1000 = 1500 + let expected_avg = 500.0 + (1500.0 - 500.0) / 1.0; assert!( (new_avg - expected_avg).abs() < 0.01, "Expected {expected_avg}, got {new_avg}" @@ -388,16 +361,6 @@ mod tests { let repo = Repository::new(); let now = CurrentClock::now(); - // Set up initial scrapes handled - let ipv4_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "scrape")]); - - // Simulate 4 IPv4 scrapes - for _ in 0..4 { - repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv4_labels, now) - .await - .unwrap(); - } - // Set initial average to 800ns let scrape_labels = LabelSet::from([("request_kind", "scrape")]); repo.set_gauge( @@ -410,14 +373,16 @@ mod tests { .unwrap(); // Calculate new average with processing time of 1200ns + // This will increment the processed requests counter from 0 to 1 let processing_time = Duration::from_nanos(1200); let new_avg = repo .recalculate_udp_avg_processing_time_ns(processing_time, &scrape_labels, now) .await; - // Moving average: previous_avg + (new_value - previous_avg) / total_scrapes - // 800 + (1200 - 800) / 4 = 800 + 100 = 900 - let expected_avg = 800.0 + (1200.0 - 800.0) / 4.0; + // Moving average: previous_avg + (new_value - previous_avg) / processed_requests_total + // With processed_requests_total = 1 (incremented during the call): + // 800 + (1200 - 800) / 1 = 800 + 400 = 1200 + let expected_avg = 800.0 + (1200.0 - 800.0) / 1.0; assert!( (new_avg - expected_avg).abs() < 0.01, "Expected {expected_avg}, got {new_avg}" @@ -584,49 +549,38 @@ mod tests { let connect_labels = LabelSet::from([("request_kind", "connect")]); let now = CurrentClock::now(); - // This test checks the behavior of `recalculate_udp_avg_connect_processing_time_ns`` - // when no connections have been recorded yet. The first call should - // handle division by zero gracefully and return an infinite average, - // which is the current behavior. + // This test checks the behavior of `recalculate_udp_avg_processing_time_ns` + // when no processed requests have been recorded yet. The first call should + // handle division by zero gracefully and set the first average to the + // processing time of the first request. - // todo: the first average should be 2000ns, not infinity. - // This is because the first connection is not counted in the average - // calculation if the counter is increased after calculating the average. - // The problem is that we count requests when they are accepted, not - // when they are processed. And we calculate the average when the - // response is sent. - - // First calculation: no connections recorded yet, should result in infinity + // First calculation: no processed requests recorded yet let processing_time_1 = Duration::from_nanos(2000); let avg_1 = repo .recalculate_udp_avg_processing_time_ns(processing_time_1, &connect_labels, now) .await; + // The first average should be the first processing time since processed_requests_total is 0 + // When processed_requests_total == 0.0, new_avg = req_processing_time assert!( (avg_1 - 2000.0).abs() < f64::EPSILON, "First calculation should be 2000, but got {avg_1}" ); - // Now add one connection and try again - let ipv4_labels = LabelSet::from([("server_binding_address_ip_family", "inet"), ("request_kind", "connect")]); - repo.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), &ipv4_labels, now) - .await - .unwrap(); - - // Second calculation: 1 connection + // Second calculation: now we have one processed request (incremented during first call) let processing_time_2 = Duration::from_nanos(3000); - let connect_labels = LabelSet::from([("request_kind", "connect")]); let avg_2 = repo .recalculate_udp_avg_processing_time_ns(processing_time_2, &connect_labels, now) .await; - // There is one connection, so the average should be: - // 2000 + (3000 - 2000) / 1 = 2000 + 1000 = 3000 - // This is because one connection is not counted yet in the average calculation, - // so the average is simply the processing time of the second connection. + // Moving average calculation: previous_avg + (new_value - previous_avg) / processed_requests_total + // After first call: processed_requests_total = 1, avg = 2000 + // During second call: processed_requests_total incremented to 2 + // new_avg = 2000 + (3000 - 2000) / 2 = 2000 + 500 = 2500 + let expected_avg_2 = 2000.0 + (3000.0 - 2000.0) / 2.0; assert!( - (avg_2 - 3000.0).abs() < f64::EPSILON, - "Second calculation should be 3000ns, but got {avg_2}" + (avg_2 - expected_avg_2).abs() < f64::EPSILON, + "Second calculation should be {expected_avg_2}ns, but got {avg_2}" ); } } From 384b887fa2790413cd189c169c047f5ceebcbe4c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 20 Jun 2025 07:57:48 +0100 Subject: [PATCH 1241/1297] feat(metrics): [#1589] add Avg (average) aggregate function Implements a new aggregate function for calculating averages of metric samples that match specific label criteria, complementing the existing Sum aggregation. - **metrics/src/metric/aggregate/avg.rs**: New metric-level average trait and implementations - `Avg` trait with `avg()` method for calculating averages - Implementation for `Metric` returning `f64` - Implementation for `Metric` returning `f64` - Comprehensive unit tests with edge cases (empty samples, large values, etc.) - **metrics/src/metric_collection/aggregate/avg.rs**: New collection-level average trait - `Avg` trait for `MetricCollection` and `MetricKindCollection` - Delegates to metric-level implementations - Handles mixed counter/gauge collections by trying counters first, then gauges - Returns `None` for non-existent metrics - Comprehensive test suite covering various scenarios - **metrics/src/metric/aggregate/mod.rs**: Export new `avg` module - **metrics/src/metric_collection/aggregate/mod.rs**: Export new `avg` module - **metrics/README.md**: Add example usage of the new `Avg` trait in the aggregation section - **Type Safety**: Returns appropriate types (`f64` for both counters and gauges) - **Label Filtering**: Supports filtering samples by label criteria like existing `Sum` - **Edge Case Handling**: Returns `0.0` for empty sample sets - **Performance**: Uses iterator chains for efficient sample processing - **Comprehensive Testing**: 205 tests pass including new avg functionality ```rust use torrust_tracker_metrics::metric_collection::aggregate::Avg; // Calculate average of all matching samples let avg_value = metrics.avg(&metric_name, &label_criteria); ``` The implementation follows the same patterns as the existing `Sum` aggregate function, ensuring consistency in the codebase and maintaining the same level of type safety and performance characteristics. --- packages/metrics/README.md | 10 +- packages/metrics/src/metric/aggregate/avg.rs | 307 ++++++++++++++++++ packages/metrics/src/metric/aggregate/mod.rs | 1 + .../src/metric_collection/aggregate/avg.rs | 214 ++++++++++++ .../src/metric_collection/aggregate/mod.rs | 1 + 5 files changed, 532 insertions(+), 1 deletion(-) create mode 100644 packages/metrics/src/metric/aggregate/avg.rs create mode 100644 packages/metrics/src/metric_collection/aggregate/avg.rs diff --git a/packages/metrics/README.md b/packages/metrics/README.md index 9f3883fba..3d1d94c5f 100644 --- a/packages/metrics/README.md +++ b/packages/metrics/README.md @@ -67,7 +67,7 @@ println!("{}", prometheus_output); ### Metric Aggregation ```rust -use torrust_tracker_metrics::metric_collection::aggregate::Sum; +use torrust_tracker_metrics::metric_collection::aggregate::{Sum, Avg}; // Sum all counter values matching specific labels let total_requests = metrics.sum( @@ -76,6 +76,14 @@ let total_requests = metrics.sum( ); println!("Total requests: {:?}", total_requests); + +// Calculate average of gauge values matching specific labels +let avg_response_time = metrics.avg( + &metric_name!("response_time_seconds"), + &[("endpoint", "/announce")].into(), +); + +println!("Average response time: {:?}", avg_response_time); ``` ## Architecture diff --git a/packages/metrics/src/metric/aggregate/avg.rs b/packages/metrics/src/metric/aggregate/avg.rs new file mode 100644 index 000000000..e1882ea68 --- /dev/null +++ b/packages/metrics/src/metric/aggregate/avg.rs @@ -0,0 +1,307 @@ +use crate::counter::Counter; +use crate::gauge::Gauge; +use crate::label::LabelSet; +use crate::metric::Metric; + +pub trait Avg { + type Output; + fn avg(&self, label_set_criteria: &LabelSet) -> Self::Output; +} + +impl Avg for Metric { + type Output = f64; + + fn avg(&self, label_set_criteria: &LabelSet) -> Self::Output { + let matching_samples: Vec<_> = self + .sample_collection + .iter() + .filter(|(label_set, _measurement)| label_set.matches(label_set_criteria)) + .collect(); + + if matching_samples.is_empty() { + return 0.0; + } + + let sum: u64 = matching_samples + .iter() + .map(|(_label_set, measurement)| measurement.value().primitive()) + .sum(); + + #[allow(clippy::cast_precision_loss)] + (sum as f64 / matching_samples.len() as f64) + } +} + +impl Avg for Metric { + type Output = f64; + + fn avg(&self, label_set_criteria: &LabelSet) -> Self::Output { + let matching_samples: Vec<_> = self + .sample_collection + .iter() + .filter(|(label_set, _measurement)| label_set.matches(label_set_criteria)) + .collect(); + + if matching_samples.is_empty() { + return 0.0; + } + + let sum: f64 = matching_samples + .iter() + .map(|(_label_set, measurement)| measurement.value().primitive()) + .sum(); + + #[allow(clippy::cast_precision_loss)] + (sum / matching_samples.len() as f64) + } +} + +#[cfg(test)] +mod tests { + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::counter::Counter; + use crate::gauge::Gauge; + use crate::label::LabelSet; + use crate::metric::aggregate::avg::Avg; + use crate::metric::{Metric, MetricName}; + use crate::metric_name; + use crate::sample::Sample; + use crate::sample_collection::SampleCollection; + + struct MetricBuilder { + sample_time: DurationSinceUnixEpoch, + name: MetricName, + samples: Vec>, + } + + impl Default for MetricBuilder { + fn default() -> Self { + Self { + sample_time: DurationSinceUnixEpoch::from_secs(1_743_552_000), + name: metric_name!("test_metric"), + samples: vec![], + } + } + } + + impl MetricBuilder { + fn with_sample(mut self, value: T, label_set: &LabelSet) -> Self { + let sample = Sample::new(value, self.sample_time, label_set.clone()); + self.samples.push(sample); + self + } + + fn build(self) -> Metric { + Metric::new( + self.name, + None, + None, + SampleCollection::new(self.samples).expect("invalid samples"), + ) + } + } + + fn counter_cases() -> Vec<(Metric, LabelSet, f64)> { + // (metric, label set criteria, expected_average_value) + vec![ + // Metric with one sample without label set + ( + MetricBuilder::default().with_sample(1.into(), &LabelSet::empty()).build(), + LabelSet::empty(), + 1.0, + ), + // Metric with one sample with a label set + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0, + ), + // Metric with two samples, different label sets, average all + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value")].into()) + .with_sample(3.into(), &[("l2", "l2_value")].into()) + .build(), + LabelSet::empty(), + 2.0, // (1 + 3) / 2 = 2.0 + ), + // Metric with two samples, different label sets, average one + ( + MetricBuilder::default() + .with_sample(1.into(), &[("l1", "l1_value")].into()) + .with_sample(2.into(), &[("l2", "l2_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0, + ), + // Metric with three samples, same label key, different label values, average by key + ( + MetricBuilder::default() + .with_sample(2.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(4.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .with_sample(6.into(), &[("l1", "l1_value"), ("lc", "lc_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 4.0, // (2 + 4 + 6) / 3 = 4.0 + ), + // Metric with two samples, different label values, average by subkey + ( + MetricBuilder::default() + .with_sample(5.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(7.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .build(), + [("la", "la_value")].into(), + 5.0, + ), + // Edge: Metric with no samples at all + (MetricBuilder::default().build(), LabelSet::empty(), 0.0), + // Edge: Metric with samples but no matching labels + ( + MetricBuilder::default() + .with_sample(5.into(), &[("foo", "bar")].into()) + .build(), + [("not", "present")].into(), + 0.0, + ), + // Edge: Metric with zero value + ( + MetricBuilder::default() + .with_sample(0.into(), &[("l3", "l3_value")].into()) + .build(), + [("l3", "l3_value")].into(), + 0.0, + ), + // Edge: Metric with a very large value + ( + MetricBuilder::default() + .with_sample((u64::MAX / 2).into(), &[("edge", "large1")].into()) + .with_sample((u64::MAX / 2).into(), &[("edge", "large2")].into()) + .build(), + LabelSet::empty(), + #[allow(clippy::cast_precision_loss)] + (u64::MAX as f64 / 2.0), // Average of (max/2) and (max/2) + ), + ] + } + + fn gauge_cases() -> Vec<(Metric, LabelSet, f64)> { + // (metric, label set criteria, expected_average_value) + vec![ + // Metric with one sample without label set + ( + MetricBuilder::default().with_sample(1.0.into(), &LabelSet::empty()).build(), + LabelSet::empty(), + 1.0, + ), + // Metric with one sample with a label set + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0, + ), + // Metric with two samples, different label sets, average all + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value")].into()) + .with_sample(3.0.into(), &[("l2", "l2_value")].into()) + .build(), + LabelSet::empty(), + 2.0, // (1.0 + 3.0) / 2 = 2.0 + ), + // Metric with two samples, different label sets, average one + ( + MetricBuilder::default() + .with_sample(1.0.into(), &[("l1", "l1_value")].into()) + .with_sample(2.0.into(), &[("l2", "l2_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 1.0, + ), + // Metric with three samples, same label key, different label values, average by key + ( + MetricBuilder::default() + .with_sample(2.0.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(4.0.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .with_sample(6.0.into(), &[("l1", "l1_value"), ("lc", "lc_value")].into()) + .build(), + [("l1", "l1_value")].into(), + 4.0, // (2.0 + 4.0 + 6.0) / 3 = 4.0 + ), + // Metric with two samples, different label values, average by subkey + ( + MetricBuilder::default() + .with_sample(5.0.into(), &[("l1", "l1_value"), ("la", "la_value")].into()) + .with_sample(7.0.into(), &[("l1", "l1_value"), ("lb", "lb_value")].into()) + .build(), + [("la", "la_value")].into(), + 5.0, + ), + // Edge: Metric with no samples at all + (MetricBuilder::default().build(), LabelSet::empty(), 0.0), + // Edge: Metric with samples but no matching labels + ( + MetricBuilder::default() + .with_sample(5.0.into(), &[("foo", "bar")].into()) + .build(), + [("not", "present")].into(), + 0.0, + ), + // Edge: Metric with zero value + ( + MetricBuilder::default() + .with_sample(0.0.into(), &[("l3", "l3_value")].into()) + .build(), + [("l3", "l3_value")].into(), + 0.0, + ), + // Edge: Metric with negative values + ( + MetricBuilder::default() + .with_sample((-2.0).into(), &[("l4", "l4_value")].into()) + .with_sample(4.0.into(), &[("l5", "l5_value")].into()) + .build(), + LabelSet::empty(), + 1.0, // (-2.0 + 4.0) / 2 = 1.0 + ), + // Edge: Metric with decimal values + ( + MetricBuilder::default() + .with_sample(1.5.into(), &[("l6", "l6_value")].into()) + .with_sample(2.5.into(), &[("l7", "l7_value")].into()) + .build(), + LabelSet::empty(), + 2.0, // (1.5 + 2.5) / 2 = 2.0 + ), + ] + } + + #[test] + fn test_counter_cases() { + for (idx, (metric, criteria, expected_value)) in counter_cases().iter().enumerate() { + let avg = metric.avg(criteria); + + assert!( + (avg - expected_value).abs() <= f64::EPSILON, + "at case {idx}, expected avg to be {expected_value}, got {avg}" + ); + } + } + + #[test] + fn test_gauge_cases() { + for (idx, (metric, criteria, expected_value)) in gauge_cases().iter().enumerate() { + let avg = metric.avg(criteria); + + assert!( + (avg - expected_value).abs() <= f64::EPSILON, + "at case {idx}, expected avg to be {expected_value}, got {avg}" + ); + } + } +} diff --git a/packages/metrics/src/metric/aggregate/mod.rs b/packages/metrics/src/metric/aggregate/mod.rs index dce785d95..1224a1f52 100644 --- a/packages/metrics/src/metric/aggregate/mod.rs +++ b/packages/metrics/src/metric/aggregate/mod.rs @@ -1 +1,2 @@ +pub mod avg; pub mod sum; diff --git a/packages/metrics/src/metric_collection/aggregate/avg.rs b/packages/metrics/src/metric_collection/aggregate/avg.rs new file mode 100644 index 000000000..936754fc4 --- /dev/null +++ b/packages/metrics/src/metric_collection/aggregate/avg.rs @@ -0,0 +1,214 @@ +use crate::counter::Counter; +use crate::gauge::Gauge; +use crate::label::LabelSet; +use crate::metric::aggregate::avg::Avg as MetricAvgTrait; +use crate::metric::MetricName; +use crate::metric_collection::{MetricCollection, MetricKindCollection}; + +pub trait Avg { + fn avg(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option; +} + +impl Avg for MetricCollection { + fn avg(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + if let Some(value) = self.counters.avg(metric_name, label_set_criteria) { + return Some(value); + } + + if let Some(value) = self.gauges.avg(metric_name, label_set_criteria) { + return Some(value); + } + + None + } +} + +impl Avg for MetricKindCollection { + fn avg(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + self.metrics + .get(metric_name) + .map(|metric| metric.avg(label_set_criteria)) + } +} + +impl Avg for MetricKindCollection { + fn avg(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { + self.metrics.get(metric_name).map(|metric| metric.avg(label_set_criteria)) + } +} + +#[cfg(test)] +mod tests { + + mod it_should_allow_averaging_all_metric_samples_containing_some_given_labels { + + use torrust_tracker_primitives::DurationSinceUnixEpoch; + + use crate::label::LabelValue; + use crate::label_name; + use crate::metric_collection::aggregate::avg::Avg; + + #[test] + fn type_counter_with_two_samples() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let metric_name = metric_name!("test_counter"); + + let mut collection = MetricCollection::default(); + + collection + .increment_counter( + &metric_name!("test_counter"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + collection + .increment_counter( + &metric_name!("test_counter"), + &(label_name!("label_2"), LabelValue::new("value_2")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + // Two samples with value 1 each, average should be 1.0 + assert_eq!(collection.avg(&metric_name, &LabelSet::empty()), Some(1.0)); + assert_eq!( + collection.avg(&metric_name, &(label_name!("label_1"), LabelValue::new("value_1")).into()), + Some(1.0) + ); + } + + #[test] + fn type_counter_with_different_values() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let metric_name = metric_name!("test_counter"); + + let mut collection = MetricCollection::default(); + + // First increment: value goes from 0 to 1 + collection + .increment_counter( + &metric_name!("test_counter"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + // Second increment on the same label: value goes from 1 to 2 + collection + .increment_counter( + &metric_name!("test_counter"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + DurationSinceUnixEpoch::from_secs(2), + ) + .unwrap(); + + // Create another counter with a different value + collection + .set_counter( + &metric_name!("test_counter"), + &(label_name!("label_2"), LabelValue::new("value_2")).into(), + 4, + DurationSinceUnixEpoch::from_secs(3), + ) + .unwrap(); + + // Average of 2 and 4 should be 3.0 + assert_eq!(collection.avg(&metric_name, &LabelSet::empty()), Some(3.0)); + assert_eq!( + collection.avg(&metric_name, &(label_name!("label_1"), LabelValue::new("value_1")).into()), + Some(2.0) + ); + assert_eq!( + collection.avg(&metric_name, &(label_name!("label_2"), LabelValue::new("value_2")).into()), + Some(4.0) + ); + } + + #[test] + fn type_gauge_with_two_samples() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let metric_name = metric_name!("test_gauge"); + + let mut collection = MetricCollection::default(); + + collection + .set_gauge( + &metric_name!("test_gauge"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + 2.0, + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + collection + .set_gauge( + &metric_name!("test_gauge"), + &(label_name!("label_2"), LabelValue::new("value_2")).into(), + 4.0, + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + // Average of 2.0 and 4.0 should be 3.0 + assert_eq!(collection.avg(&metric_name, &LabelSet::empty()), Some(3.0)); + assert_eq!( + collection.avg(&metric_name, &(label_name!("label_1"), LabelValue::new("value_1")).into()), + Some(2.0) + ); + } + + #[test] + fn type_gauge_with_negative_values() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let metric_name = metric_name!("test_gauge"); + + let mut collection = MetricCollection::default(); + + collection + .set_gauge( + &metric_name!("test_gauge"), + &(label_name!("label_1"), LabelValue::new("value_1")).into(), + -2.0, + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + collection + .set_gauge( + &metric_name!("test_gauge"), + &(label_name!("label_2"), LabelValue::new("value_2")).into(), + 6.0, + DurationSinceUnixEpoch::from_secs(1), + ) + .unwrap(); + + // Average of -2.0 and 6.0 should be 2.0 + assert_eq!(collection.avg(&metric_name, &LabelSet::empty()), Some(2.0)); + } + + #[test] + fn nonexistent_metric() { + use crate::label::LabelSet; + use crate::metric_collection::MetricCollection; + use crate::metric_name; + + let collection = MetricCollection::default(); + + assert_eq!(collection.avg(&metric_name!("nonexistent"), &LabelSet::empty()), None); + } + } +} diff --git a/packages/metrics/src/metric_collection/aggregate/mod.rs b/packages/metrics/src/metric_collection/aggregate/mod.rs index dce785d95..1224a1f52 100644 --- a/packages/metrics/src/metric_collection/aggregate/mod.rs +++ b/packages/metrics/src/metric_collection/aggregate/mod.rs @@ -1 +1,2 @@ +pub mod avg; pub mod sum; From 8fbcf9024a39af498162a522ecbd107d01f239a4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 20 Jun 2025 08:30:27 +0100 Subject: [PATCH 1242/1297] refactor(metrics): extract collect_matching_samples to Metric impl Improve AI-generated code. Moves the collect_matching_samples helper method from individual aggregate implementations to the generic Metric implementation, making it reusable across all aggregate functions. - Add collect_matching_samples method to Metric for filtering samples by label criteria - Remove code duplication between Sum and Avg aggregate implementations - Improve code organization by centralizing sample collection logic - Maintain backward compatibility and all existing functionality This refactoring improves maintainability by providing a single, well-tested implementation of sample filtering that can be used by current and future aggregate functions. --- packages/metrics/src/metric/aggregate/avg.rs | 23 +++++--------------- packages/metrics/src/metric/mod.rs | 11 ++++++++++ 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/packages/metrics/src/metric/aggregate/avg.rs b/packages/metrics/src/metric/aggregate/avg.rs index e1882ea68..95628450b 100644 --- a/packages/metrics/src/metric/aggregate/avg.rs +++ b/packages/metrics/src/metric/aggregate/avg.rs @@ -1,6 +1,7 @@ use crate::counter::Counter; use crate::gauge::Gauge; use crate::label::LabelSet; +use crate::metric::aggregate::sum::Sum; use crate::metric::Metric; pub trait Avg { @@ -12,20 +13,13 @@ impl Avg for Metric { type Output = f64; fn avg(&self, label_set_criteria: &LabelSet) -> Self::Output { - let matching_samples: Vec<_> = self - .sample_collection - .iter() - .filter(|(label_set, _measurement)| label_set.matches(label_set_criteria)) - .collect(); + let matching_samples = self.collect_matching_samples(label_set_criteria); if matching_samples.is_empty() { return 0.0; } - let sum: u64 = matching_samples - .iter() - .map(|(_label_set, measurement)| measurement.value().primitive()) - .sum(); + let sum = self.sum(label_set_criteria); #[allow(clippy::cast_precision_loss)] (sum as f64 / matching_samples.len() as f64) @@ -36,20 +30,13 @@ impl Avg for Metric { type Output = f64; fn avg(&self, label_set_criteria: &LabelSet) -> Self::Output { - let matching_samples: Vec<_> = self - .sample_collection - .iter() - .filter(|(label_set, _measurement)| label_set.matches(label_set_criteria)) - .collect(); + let matching_samples = self.collect_matching_samples(label_set_criteria); if matching_samples.is_empty() { return 0.0; } - let sum: f64 = matching_samples - .iter() - .map(|(_label_set, measurement)| measurement.value().primitive()) - .sum(); + let sum = self.sum(label_set_criteria); #[allow(clippy::cast_precision_loss)] (sum / matching_samples.len() as f64) diff --git a/packages/metrics/src/metric/mod.rs b/packages/metrics/src/metric/mod.rs index d1aa01b94..6bc1a6075 100644 --- a/packages/metrics/src/metric/mod.rs +++ b/packages/metrics/src/metric/mod.rs @@ -78,6 +78,17 @@ impl Metric { pub fn is_empty(&self) -> bool { self.sample_collection.is_empty() } + + #[must_use] + pub fn collect_matching_samples( + &self, + label_set_criteria: &LabelSet, + ) -> Vec<(&crate::label::LabelSet, &crate::sample::Measurement)> { + self.sample_collection + .iter() + .filter(|(label_set, _measurement)| label_set.matches(label_set_criteria)) + .collect() + } } impl Metric { From f402b0250b846dfb62c8d8cb48ec5b175693f350 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 20 Jun 2025 08:32:43 +0100 Subject: [PATCH 1243/1297] chore: remove deprecated comment --- .../rest-tracker-api-core/src/statistics/services.rs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index a8132d4fd..af79c5ce7 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -59,18 +59,6 @@ async fn get_protocol_metrics( let http_stats = http_stats_repository.get_stats().await; let udp_server_stats = udp_server_stats_repository.get_stats().await; - /* - - todo: We have to delete the global metrics from Metric types: - - - bittorrent_http_tracker_core::statistics::metrics::Metrics - - bittorrent_udp_tracker_core::statistics::metrics::Metrics - - torrust_udp_tracker_server::statistics::metrics::Metrics - - Internally only the labeled metrics should be used. - - */ - // TCPv4 let tcp4_announces_handled = http_stats.tcp4_announces_handled(); From caa69ae91356584e193b11485548fb935bb4f2d3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 20 Jun 2025 08:33:43 +0100 Subject: [PATCH 1244/1297] test: [#1589] remove uneeded test Division by zero issues was solved. It can't happen now becuase we increase the counter at the beggining of the function. ```rust #[allow(clippy::cast_precision_loss)] pub fn recalculate_udp_avg_processing_time_ns( &mut self, req_processing_time: Duration, label_set: &LabelSet, now: DurationSinceUnixEpoch, ) -> f64 { self.increment_udp_processed_requests_total(label_set, now); let processed_requests_total = self.udp_processed_requests_total(label_set) as f64; let previous_avg = self.udp_avg_processing_time_ns(label_set); let req_processing_time = req_processing_time.as_nanos() as f64; // Moving average: https://en.wikipedia.org/wiki/Moving_average let new_avg = previous_avg as f64 + (req_processing_time - previous_avg as f64) / processed_requests_total; tracing::debug!( "Recalculated UDP average processing time for labels {}: {} ns (previous: {} ns, req_processing_time: {} ns, request_processed_total: {})", label_set, new_avg, previous_avg, req_processing_time, processed_requests_total ); self.update_udp_avg_processing_time_ns(new_avg, label_set, now); new_avg } ``` --- .../src/statistics/repository.rs | 41 ------------------- 1 file changed, 41 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index 1ab2cc6a7..85e3bbe64 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -542,45 +542,4 @@ mod tests { // Should handle NaN values assert!(result.is_ok()); } - - #[tokio::test] - async fn it_should_handle_moving_average_calculation_before_any_connections_are_recorded() { - let repo = Repository::new(); - let connect_labels = LabelSet::from([("request_kind", "connect")]); - let now = CurrentClock::now(); - - // This test checks the behavior of `recalculate_udp_avg_processing_time_ns` - // when no processed requests have been recorded yet. The first call should - // handle division by zero gracefully and set the first average to the - // processing time of the first request. - - // First calculation: no processed requests recorded yet - let processing_time_1 = Duration::from_nanos(2000); - let avg_1 = repo - .recalculate_udp_avg_processing_time_ns(processing_time_1, &connect_labels, now) - .await; - - // The first average should be the first processing time since processed_requests_total is 0 - // When processed_requests_total == 0.0, new_avg = req_processing_time - assert!( - (avg_1 - 2000.0).abs() < f64::EPSILON, - "First calculation should be 2000, but got {avg_1}" - ); - - // Second calculation: now we have one processed request (incremented during first call) - let processing_time_2 = Duration::from_nanos(3000); - let avg_2 = repo - .recalculate_udp_avg_processing_time_ns(processing_time_2, &connect_labels, now) - .await; - - // Moving average calculation: previous_avg + (new_value - previous_avg) / processed_requests_total - // After first call: processed_requests_total = 1, avg = 2000 - // During second call: processed_requests_total incremented to 2 - // new_avg = 2000 + (3000 - 2000) / 2 = 2000 + 500 = 2500 - let expected_avg_2 = 2000.0 + (3000.0 - 2000.0) / 2.0; - assert!( - (avg_2 - expected_avg_2).abs() < f64::EPSILON, - "Second calculation should be {expected_avg_2}ns, but got {avg_2}" - ); - } } From ba3d8a914e3dabe7c17c24e2a1258a35fa87199e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 20 Jun 2025 10:10:21 +0100 Subject: [PATCH 1245/1297] fix: format --- packages/metrics/src/metric_collection/aggregate/avg.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/metrics/src/metric_collection/aggregate/avg.rs b/packages/metrics/src/metric_collection/aggregate/avg.rs index 936754fc4..0aef4e325 100644 --- a/packages/metrics/src/metric_collection/aggregate/avg.rs +++ b/packages/metrics/src/metric_collection/aggregate/avg.rs @@ -25,9 +25,7 @@ impl Avg for MetricCollection { impl Avg for MetricKindCollection { fn avg(&self, metric_name: &MetricName, label_set_criteria: &LabelSet) -> Option { - self.metrics - .get(metric_name) - .map(|metric| metric.avg(label_set_criteria)) + self.metrics.get(metric_name).map(|metric| metric.avg(label_set_criteria)) } } From cd57f7a78f423d9ae409fd3aa63f7fc7a517375d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 20 Jun 2025 10:23:58 +0100 Subject: [PATCH 1246/1297] fix: [#1589] use average aggregation for UDP processing time metrics When calculating aggregated values for processing time metrics across multiple servers, we need to use the average (.avg()) instead of sum (.sum()) because the metric samples are already averages per server. Using sum() on pre-averaged values would produce incorrect results, as it would add up the averages rather than computing the true average across all servers. Changes: - Add new *_averaged() methods that use .avg() for proper aggregation - Update services.rs to use the corrected averaging methods - Import Avg trait for metric collection averaging functionality Fixes incorrect metric aggregation for: - udp_avg_connect_processing_time_ns - udp_avg_announce_processing_time_ns - udp_avg_scrape_processing_time_ns" --- .../src/statistics/services.rs | 6 +- .../src/statistics/metrics.rs | 267 ++++++++++++++++++ 2 files changed, 270 insertions(+), 3 deletions(-) diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index af79c5ce7..a1edae46a 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -74,9 +74,9 @@ async fn get_protocol_metrics( let udp_requests_aborted = udp_server_stats.udp_requests_aborted(); let udp_requests_banned = udp_server_stats.udp_requests_banned(); let udp_banned_ips_total = udp_server_stats.udp_banned_ips_total(); - let udp_avg_connect_processing_time_ns = udp_server_stats.udp_avg_connect_processing_time_ns(); - let udp_avg_announce_processing_time_ns = udp_server_stats.udp_avg_announce_processing_time_ns(); - let udp_avg_scrape_processing_time_ns = udp_server_stats.udp_avg_scrape_processing_time_ns(); + let udp_avg_connect_processing_time_ns = udp_server_stats.udp_avg_connect_processing_time_ns_averaged(); + let udp_avg_announce_processing_time_ns = udp_server_stats.udp_avg_announce_processing_time_ns_averaged(); + let udp_avg_scrape_processing_time_ns = udp_server_stats.udp_avg_scrape_processing_time_ns_averaged(); // UDPv4 diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index e7653815f..ac9540f8e 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -3,6 +3,7 @@ use std::time::Duration; use serde::Serialize; use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; +use torrust_tracker_metrics::metric_collection::aggregate::avg::Avg; use torrust_tracker_metrics::metric_collection::aggregate::sum::Sum; use torrust_tracker_metrics::metric_collection::{Error, MetricCollection}; use torrust_tracker_metrics::metric_name; @@ -215,6 +216,48 @@ impl Metrics { .unwrap_or_default() as u64 } + /// Average processing time for UDP connect requests across all servers (in nanoseconds). + /// This calculates the average of all gauge samples for connect requests. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_avg_connect_processing_time_ns_averaged(&self) -> u64 { + self.metric_collection + .avg( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "connect")].into(), + ) + .unwrap_or(0.0) as u64 + } + + /// Average processing time for UDP announce requests across all servers (in nanoseconds). + /// This calculates the average of all gauge samples for announce requests. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_avg_announce_processing_time_ns_averaged(&self) -> u64 { + self.metric_collection + .avg( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "announce")].into(), + ) + .unwrap_or(0.0) as u64 + } + + /// Average processing time for UDP scrape requests across all servers (in nanoseconds). + /// This calculates the average of all gauge samples for scrape requests. + #[must_use] + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + pub fn udp_avg_scrape_processing_time_ns_averaged(&self) -> u64 { + self.metric_collection + .avg( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "scrape")].into(), + ) + .unwrap_or(0.0) as u64 + } + // UDPv4 /// Total number of UDP (UDP tracker) requests from IPv4 peers. #[must_use] @@ -1179,4 +1222,228 @@ mod tests { assert!(result.is_ok()); } } + + mod averaged_processing_time_metrics { + use super::*; + + #[test] + fn it_should_return_zero_for_udp_avg_connect_processing_time_ns_averaged_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_avg_connect_processing_time_ns_averaged(), 0); + } + + #[test] + fn it_should_return_averaged_value_for_udp_avg_connect_processing_time_ns_averaged() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels1 = LabelSet::from([("request_kind", "connect"), ("server_id", "server1")]); + let labels2 = LabelSet::from([("request_kind", "connect"), ("server_id", "server2")]); + + // Set different gauge values for connect requests from different servers + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels1, + 1000.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels2, + 2000.0, + now, + ) + .unwrap(); + + // Should return the average: (1000 + 2000) / 2 = 1500 + assert_eq!(metrics.udp_avg_connect_processing_time_ns_averaged(), 1500); + } + + #[test] + fn it_should_return_zero_for_udp_avg_announce_processing_time_ns_averaged_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_avg_announce_processing_time_ns_averaged(), 0); + } + + #[test] + fn it_should_return_averaged_value_for_udp_avg_announce_processing_time_ns_averaged() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels1 = LabelSet::from([("request_kind", "announce"), ("server_id", "server1")]); + let labels2 = LabelSet::from([("request_kind", "announce"), ("server_id", "server2")]); + let labels3 = LabelSet::from([("request_kind", "announce"), ("server_id", "server3")]); + + // Set different gauge values for announce requests from different servers + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels1, + 1500.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels2, + 2500.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels3, + 3000.0, + now, + ) + .unwrap(); + + // Should return the average: (1500 + 2500 + 3000) / 3 = 2333 (truncated) + assert_eq!(metrics.udp_avg_announce_processing_time_ns_averaged(), 2333); + } + + #[test] + fn it_should_return_zero_for_udp_avg_scrape_processing_time_ns_averaged_when_no_data() { + let metrics = Metrics::default(); + assert_eq!(metrics.udp_avg_scrape_processing_time_ns_averaged(), 0); + } + + #[test] + fn it_should_return_averaged_value_for_udp_avg_scrape_processing_time_ns_averaged() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels1 = LabelSet::from([("request_kind", "scrape"), ("server_id", "server1")]); + let labels2 = LabelSet::from([("request_kind", "scrape"), ("server_id", "server2")]); + + // Set different gauge values for scrape requests from different servers + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels1, + 500.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels2, + 1500.0, + now, + ) + .unwrap(); + + // Should return the average: (500 + 1500) / 2 = 1000 + assert_eq!(metrics.udp_avg_scrape_processing_time_ns_averaged(), 1000); + } + + #[test] + fn it_should_handle_fractional_averages_with_truncation() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels1 = LabelSet::from([("request_kind", "connect"), ("server_id", "server1")]); + let labels2 = LabelSet::from([("request_kind", "connect"), ("server_id", "server2")]); + let labels3 = LabelSet::from([("request_kind", "connect"), ("server_id", "server3")]); + + // Set values that will result in a fractional average + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels1, + 1000.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels2, + 1001.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels3, + 1001.0, + now, + ) + .unwrap(); + + // Should return the average: (1000 + 1001 + 1001) / 3 = 1000.666... → 1000 (truncated) + assert_eq!(metrics.udp_avg_connect_processing_time_ns_averaged(), 1000); + } + + #[test] + fn it_should_only_average_matching_request_kinds() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + + // Set values for different request kinds with the same server_id + let connect_labels = LabelSet::from([("request_kind", "connect"), ("server_id", "server1")]); + let announce_labels = LabelSet::from([("request_kind", "announce"), ("server_id", "server1")]); + let scrape_labels = LabelSet::from([("request_kind", "scrape"), ("server_id", "server1")]); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &connect_labels, + 1000.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &announce_labels, + 2000.0, + now, + ) + .unwrap(); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &scrape_labels, + 3000.0, + now, + ) + .unwrap(); + + // Each function should only return the value for its specific request kind + assert_eq!(metrics.udp_avg_connect_processing_time_ns_averaged(), 1000); + assert_eq!(metrics.udp_avg_announce_processing_time_ns_averaged(), 2000); + assert_eq!(metrics.udp_avg_scrape_processing_time_ns_averaged(), 3000); + } + + #[test] + fn it_should_handle_single_server_averaged_metrics() { + let mut metrics = Metrics::default(); + let now = CurrentClock::now(); + let labels = LabelSet::from([("request_kind", "connect"), ("server_id", "single_server")]); + + metrics + .set_gauge( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &labels, + 1234.0, + now, + ) + .unwrap(); + + // With only one server, the average should be the same as the single value + assert_eq!(metrics.udp_avg_connect_processing_time_ns_averaged(), 1234); + } + } } From 4c082faefe1ae5932cca4a7f44b0619a14a50a11 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 20 Jun 2025 10:43:01 +0100 Subject: [PATCH 1247/1297] refactor: [#1589] make methods private --- packages/udp-tracker-server/src/statistics/metrics.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index ac9540f8e..178855377 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -85,7 +85,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp_avg_processing_time_ns(&self, label_set: &LabelSet) -> u64 { + fn udp_avg_processing_time_ns(&self, label_set: &LabelSet) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), @@ -106,7 +106,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp_processed_requests_total(&self, label_set: &LabelSet) -> u64 { + fn udp_processed_requests_total(&self, label_set: &LabelSet) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), From a9acca5e73d6897c671117eae63c7e28f3e1629b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 20 Jun 2025 11:24:54 +0100 Subject: [PATCH 1248/1297] refactor: [#1589] rename methods and remove unused code --- .../src/statistics/services.rs | 28 +- .../src/statistics/event/handler/error.rs | 2 +- .../event/handler/request_aborted.rs | 4 +- .../event/handler/request_accepted.rs | 12 +- .../event/handler/request_banned.rs | 4 +- .../event/handler/request_received.rs | 2 +- .../statistics/event/handler/response_sent.rs | 4 +- .../src/statistics/metrics.rs | 246 ++++-------------- .../src/statistics/repository.rs | 44 +++- .../tests/server/contract.rs | 4 +- 10 files changed, 119 insertions(+), 231 deletions(-) diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index a1edae46a..f87cb8c76 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -71,8 +71,8 @@ async fn get_protocol_metrics( // UDP - let udp_requests_aborted = udp_server_stats.udp_requests_aborted(); - let udp_requests_banned = udp_server_stats.udp_requests_banned(); + let udp_requests_aborted = udp_server_stats.udp_requests_aborted_total(); + let udp_requests_banned = udp_server_stats.udp_requests_banned_total(); let udp_banned_ips_total = udp_server_stats.udp_banned_ips_total(); let udp_avg_connect_processing_time_ns = udp_server_stats.udp_avg_connect_processing_time_ns_averaged(); let udp_avg_announce_processing_time_ns = udp_server_stats.udp_avg_announce_processing_time_ns_averaged(); @@ -80,21 +80,21 @@ async fn get_protocol_metrics( // UDPv4 - let udp4_requests = udp_server_stats.udp4_requests(); - let udp4_connections_handled = udp_server_stats.udp4_connections_handled(); - let udp4_announces_handled = udp_server_stats.udp4_announces_handled(); - let udp4_scrapes_handled = udp_server_stats.udp4_scrapes_handled(); - let udp4_responses = udp_server_stats.udp4_responses(); - let udp4_errors_handled = udp_server_stats.udp4_errors_handled(); + let udp4_requests = udp_server_stats.udp4_requests_received_total(); + let udp4_connections_handled = udp_server_stats.udp4_connect_requests_accepted_total(); + let udp4_announces_handled = udp_server_stats.udp4_announce_requests_accepted_total(); + let udp4_scrapes_handled = udp_server_stats.udp4_scrape_requests_accepted_total(); + let udp4_responses = udp_server_stats.udp4_responses_sent_total(); + let udp4_errors_handled = udp_server_stats.udp4_errors_total(); // UDPv6 - let udp6_requests = udp_server_stats.udp6_requests(); - let udp6_connections_handled = udp_server_stats.udp6_connections_handled(); - let udp6_announces_handled = udp_server_stats.udp6_announces_handled(); - let udp6_scrapes_handled = udp_server_stats.udp6_scrapes_handled(); - let udp6_responses = udp_server_stats.udp6_responses(); - let udp6_errors_handled = udp_server_stats.udp6_errors_handled(); + let udp6_requests = udp_server_stats.udp6_requests_received_total(); + let udp6_connections_handled = udp_server_stats.udp6_connect_requests_accepted_total(); + let udp6_announces_handled = udp_server_stats.udp6_announce_requests_accepted_total(); + let udp6_scrapes_handled = udp_server_stats.udp6_scrape_requests_accepted_total(); + let udp6_responses = udp_server_stats.udp6_responses_sent_total(); + let udp6_errors_handled = udp_server_stats.udp6_errors_total(); // For backward compatibility we keep the `tcp4_connections_handled` and // `tcp6_connections_handled` metrics. They don't make sense for the HTTP diff --git a/packages/udp-tracker-server/src/statistics/event/handler/error.rs b/packages/udp-tracker-server/src/statistics/event/handler/error.rs index d83a0584d..63e480ca5 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/error.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/error.rs @@ -137,6 +137,6 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_errors_handled(), 1); + assert_eq!(stats.udp4_errors_total(), 1); } } diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs index 19e410d5e..f340fe51a 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_aborted.rs @@ -54,7 +54,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp_requests_aborted(), 1); + assert_eq!(stats.udp_requests_aborted_total(), 1); } #[tokio::test] @@ -77,6 +77,6 @@ mod tests { ) .await; let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp_requests_aborted(), 1); + assert_eq!(stats.udp_requests_aborted_total(), 1); } } diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs index af92636df..33971926e 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_accepted.rs @@ -61,7 +61,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_connections_handled(), 1); + assert_eq!(stats.udp4_connect_requests_accepted_total(), 1); } #[tokio::test] @@ -89,7 +89,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_announces_handled(), 1); + assert_eq!(stats.udp4_announce_requests_accepted_total(), 1); } #[tokio::test] @@ -115,7 +115,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_scrapes_handled(), 1); + assert_eq!(stats.udp4_scrape_requests_accepted_total(), 1); } #[tokio::test] @@ -141,7 +141,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp6_connections_handled(), 1); + assert_eq!(stats.udp6_connect_requests_accepted_total(), 1); } #[tokio::test] @@ -169,7 +169,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp6_announces_handled(), 1); + assert_eq!(stats.udp6_announce_requests_accepted_total(), 1); } #[tokio::test] @@ -195,6 +195,6 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp6_scrapes_handled(), 1); + assert_eq!(stats.udp6_scrape_requests_accepted_total(), 1); } } diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs index 8badfa137..10f6cad88 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_banned.rs @@ -54,7 +54,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp_requests_banned(), 1); + assert_eq!(stats.udp_requests_banned_total(), 1); } #[tokio::test] @@ -77,6 +77,6 @@ mod tests { ) .await; let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp_requests_banned(), 1); + assert_eq!(stats.udp_requests_banned_total(), 1); } } diff --git a/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs b/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs index eced5a215..148b9d8da 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/request_received.rs @@ -54,6 +54,6 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_requests(), 1); + assert_eq!(stats.udp4_requests_received_total(), 1); } } diff --git a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs index 34093f511..b1a046b5b 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/response_sent.rs @@ -105,7 +105,7 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp4_responses(), 1); + assert_eq!(stats.udp4_responses_sent_total(), 1); } #[tokio::test] @@ -136,6 +136,6 @@ mod tests { let stats = stats_repository.get_stats().await; - assert_eq!(stats.udp6_responses(), 1); + assert_eq!(stats.udp6_responses_sent_total(), 1); } } diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index 178855377..e167dc5ae 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -97,7 +97,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp_request_accepted(&self, label_set: &LabelSet) -> u64 { + pub fn udp_request_accepted_total(&self, label_set: &LabelSet) -> u64 { self.metric_collection .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), label_set) .unwrap_or_default() as u64 @@ -151,7 +151,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp_requests_aborted(&self) -> u64 { + pub fn udp_requests_aborted_total(&self) -> u64 { self.metric_collection .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &LabelSet::empty()) .unwrap_or_default() as u64 @@ -161,7 +161,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp_requests_banned(&self) -> u64 { + pub fn udp_requests_banned_total(&self) -> u64 { self.metric_collection .sum(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_BANNED_TOTAL), &LabelSet::empty()) .unwrap_or_default() as u64 @@ -177,45 +177,6 @@ impl Metrics { .unwrap_or_default() as u64 } - /// Average rounded time spent processing UDP connect requests. - #[must_use] - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - pub fn udp_avg_connect_processing_time_ns(&self) -> u64 { - self.metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &[("request_kind", "connect")].into(), - ) - .unwrap_or_default() as u64 - } - - /// Average rounded time spent processing UDP announce requests. - #[must_use] - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - pub fn udp_avg_announce_processing_time_ns(&self) -> u64 { - self.metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &[("request_kind", "announce")].into(), - ) - .unwrap_or_default() as u64 - } - - /// Average rounded time spent processing UDP scrape requests. - #[must_use] - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - pub fn udp_avg_scrape_processing_time_ns(&self) -> u64 { - self.metric_collection - .sum( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &[("request_kind", "scrape")].into(), - ) - .unwrap_or_default() as u64 - } - /// Average processing time for UDP connect requests across all servers (in nanoseconds). /// This calculates the average of all gauge samples for connect requests. #[must_use] @@ -263,7 +224,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp4_requests(&self) -> u64 { + pub fn udp4_requests_received_total(&self) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), @@ -276,7 +237,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp4_connections_handled(&self) -> u64 { + pub fn udp4_connect_requests_accepted_total(&self) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), @@ -289,7 +250,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp4_announces_handled(&self) -> u64 { + pub fn udp4_announce_requests_accepted_total(&self) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), @@ -302,7 +263,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp4_scrapes_handled(&self) -> u64 { + pub fn udp4_scrape_requests_accepted_total(&self) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), @@ -315,7 +276,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp4_responses(&self) -> u64 { + pub fn udp4_responses_sent_total(&self) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), @@ -328,7 +289,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp4_errors_handled(&self) -> u64 { + pub fn udp4_errors_total(&self) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), @@ -342,7 +303,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp6_requests(&self) -> u64 { + pub fn udp6_requests_received_total(&self) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_RECEIVED_TOTAL), @@ -355,7 +316,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp6_connections_handled(&self) -> u64 { + pub fn udp6_connect_requests_accepted_total(&self) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), @@ -368,7 +329,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp6_announces_handled(&self) -> u64 { + pub fn udp6_announce_requests_accepted_total(&self) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), @@ -381,7 +342,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp6_scrapes_handled(&self) -> u64 { + pub fn udp6_scrape_requests_accepted_total(&self) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_REQUESTS_ACCEPTED_TOTAL), @@ -394,7 +355,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp6_responses(&self) -> u64 { + pub fn udp6_responses_sent_total(&self) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_RESPONSES_SENT_TOTAL), @@ -407,7 +368,7 @@ impl Metrics { #[must_use] #[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_possible_truncation)] - pub fn udp6_errors_handled(&self) -> u64 { + pub fn udp6_errors_total(&self) -> u64 { self.metric_collection .sum( &metric_name!(UDP_TRACKER_SERVER_ERRORS_TOTAL), @@ -534,7 +495,7 @@ mod tests { #[test] fn it_should_return_zero_for_udp_requests_aborted_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp_requests_aborted(), 0); + assert_eq!(metrics.udp_requests_aborted_total(), 0); } #[test] @@ -550,13 +511,13 @@ mod tests { .increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &labels, now) .unwrap(); - assert_eq!(metrics.udp_requests_aborted(), 2); + assert_eq!(metrics.udp_requests_aborted_total(), 2); } #[test] fn it_should_return_zero_for_udp_requests_banned_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp_requests_banned(), 0); + assert_eq!(metrics.udp_requests_banned_total(), 0); } #[test] @@ -571,7 +532,7 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp_requests_banned(), 3); + assert_eq!(metrics.udp_requests_banned_total(), 3); } #[test] @@ -594,89 +555,13 @@ mod tests { } } - mod udp_performance_metrics { - use super::*; - - #[test] - fn it_should_return_zero_for_udp_avg_connect_processing_time_ns_when_no_data() { - let metrics = Metrics::default(); - assert_eq!(metrics.udp_avg_connect_processing_time_ns(), 0); - } - - #[test] - fn it_should_return_gauge_value_for_udp_avg_connect_processing_time_ns() { - let mut metrics = Metrics::default(); - let now = CurrentClock::now(); - let labels = LabelSet::from([("request_kind", "connect")]); - - metrics - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &labels, - 1500.0, - now, - ) - .unwrap(); - - assert_eq!(metrics.udp_avg_connect_processing_time_ns(), 1500); - } - - #[test] - fn it_should_return_zero_for_udp_avg_announce_processing_time_ns_when_no_data() { - let metrics = Metrics::default(); - assert_eq!(metrics.udp_avg_announce_processing_time_ns(), 0); - } - - #[test] - fn it_should_return_gauge_value_for_udp_avg_announce_processing_time_ns() { - let mut metrics = Metrics::default(); - let now = CurrentClock::now(); - let labels = LabelSet::from([("request_kind", "announce")]); - - metrics - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &labels, - 2500.0, - now, - ) - .unwrap(); - - assert_eq!(metrics.udp_avg_announce_processing_time_ns(), 2500); - } - - #[test] - fn it_should_return_zero_for_udp_avg_scrape_processing_time_ns_when_no_data() { - let metrics = Metrics::default(); - assert_eq!(metrics.udp_avg_scrape_processing_time_ns(), 0); - } - - #[test] - fn it_should_return_gauge_value_for_udp_avg_scrape_processing_time_ns() { - let mut metrics = Metrics::default(); - let now = CurrentClock::now(); - let labels = LabelSet::from([("request_kind", "scrape")]); - - metrics - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &labels, - 3500.0, - now, - ) - .unwrap(); - - assert_eq!(metrics.udp_avg_scrape_processing_time_ns(), 3500); - } - } - mod udpv4_metrics { use super::*; #[test] fn it_should_return_zero_for_udp4_requests_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp4_requests(), 0); + assert_eq!(metrics.udp4_requests_received_total(), 0); } #[test] @@ -691,13 +576,13 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp4_requests(), 5); + assert_eq!(metrics.udp4_requests_received_total(), 5); } #[test] fn it_should_return_zero_for_udp4_connections_handled_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp4_connections_handled(), 0); + assert_eq!(metrics.udp4_connect_requests_accepted_total(), 0); } #[test] @@ -712,13 +597,13 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp4_connections_handled(), 3); + assert_eq!(metrics.udp4_connect_requests_accepted_total(), 3); } #[test] fn it_should_return_zero_for_udp4_announces_handled_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp4_announces_handled(), 0); + assert_eq!(metrics.udp4_announce_requests_accepted_total(), 0); } #[test] @@ -733,13 +618,13 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp4_announces_handled(), 7); + assert_eq!(metrics.udp4_announce_requests_accepted_total(), 7); } #[test] fn it_should_return_zero_for_udp4_scrapes_handled_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp4_scrapes_handled(), 0); + assert_eq!(metrics.udp4_scrape_requests_accepted_total(), 0); } #[test] @@ -754,13 +639,13 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp4_scrapes_handled(), 4); + assert_eq!(metrics.udp4_scrape_requests_accepted_total(), 4); } #[test] fn it_should_return_zero_for_udp4_responses_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp4_responses(), 0); + assert_eq!(metrics.udp4_responses_sent_total(), 0); } #[test] @@ -775,13 +660,13 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp4_responses(), 6); + assert_eq!(metrics.udp4_responses_sent_total(), 6); } #[test] fn it_should_return_zero_for_udp4_errors_handled_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp4_errors_handled(), 0); + assert_eq!(metrics.udp4_errors_total(), 0); } #[test] @@ -796,7 +681,7 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp4_errors_handled(), 2); + assert_eq!(metrics.udp4_errors_total(), 2); } } @@ -806,7 +691,7 @@ mod tests { #[test] fn it_should_return_zero_for_udp6_requests_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp6_requests(), 0); + assert_eq!(metrics.udp6_requests_received_total(), 0); } #[test] @@ -821,13 +706,13 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp6_requests(), 8); + assert_eq!(metrics.udp6_requests_received_total(), 8); } #[test] fn it_should_return_zero_for_udp6_connections_handled_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp6_connections_handled(), 0); + assert_eq!(metrics.udp6_connect_requests_accepted_total(), 0); } #[test] @@ -842,13 +727,13 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp6_connections_handled(), 4); + assert_eq!(metrics.udp6_connect_requests_accepted_total(), 4); } #[test] fn it_should_return_zero_for_udp6_announces_handled_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp6_announces_handled(), 0); + assert_eq!(metrics.udp6_announce_requests_accepted_total(), 0); } #[test] @@ -863,13 +748,13 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp6_announces_handled(), 9); + assert_eq!(metrics.udp6_announce_requests_accepted_total(), 9); } #[test] fn it_should_return_zero_for_udp6_scrapes_handled_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp6_scrapes_handled(), 0); + assert_eq!(metrics.udp6_scrape_requests_accepted_total(), 0); } #[test] @@ -884,13 +769,13 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp6_scrapes_handled(), 6); + assert_eq!(metrics.udp6_scrape_requests_accepted_total(), 6); } #[test] fn it_should_return_zero_for_udp6_responses_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp6_responses(), 0); + assert_eq!(metrics.udp6_responses_sent_total(), 0); } #[test] @@ -905,13 +790,13 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp6_responses(), 11); + assert_eq!(metrics.udp6_responses_sent_total(), 11); } #[test] fn it_should_return_zero_for_udp6_errors_handled_when_no_data() { let metrics = Metrics::default(); - assert_eq!(metrics.udp6_errors_handled(), 0); + assert_eq!(metrics.udp6_errors_total(), 0); } #[test] @@ -926,7 +811,7 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp6_errors_handled(), 3); + assert_eq!(metrics.udp6_errors_total(), 3); } } @@ -954,8 +839,8 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp4_requests(), 3); - assert_eq!(metrics.udp6_requests(), 7); + assert_eq!(metrics.udp4_requests_received_total(), 3); + assert_eq!(metrics.udp6_requests_received_total(), 7); } #[test] @@ -994,9 +879,9 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp4_connections_handled(), 2); - assert_eq!(metrics.udp4_announces_handled(), 5); - assert_eq!(metrics.udp4_scrapes_handled(), 1); + assert_eq!(metrics.udp4_connect_requests_accepted_total(), 2); + assert_eq!(metrics.udp4_announce_requests_accepted_total(), 5); + assert_eq!(metrics.udp4_scrape_requests_accepted_total(), 1); } #[test] @@ -1053,10 +938,10 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp4_connections_handled(), 3); - assert_eq!(metrics.udp6_connections_handled(), 2); - assert_eq!(metrics.udp4_announces_handled(), 4); - assert_eq!(metrics.udp6_announces_handled(), 6); + assert_eq!(metrics.udp4_connect_requests_accepted_total(), 3); + assert_eq!(metrics.udp6_connect_requests_accepted_total(), 2); + assert_eq!(metrics.udp4_announce_requests_accepted_total(), 4); + assert_eq!(metrics.udp6_announce_requests_accepted_total(), 6); } } @@ -1076,7 +961,7 @@ mod tests { .unwrap(); } - assert_eq!(metrics.udp_requests_aborted(), 1000); + assert_eq!(metrics.udp_requests_aborted_total(), 1000); } #[test] @@ -1106,25 +991,6 @@ mod tests { assert_eq!(metrics.udp_banned_ips_total(), 0); } - #[test] - fn it_should_handle_fractional_gauge_values_with_truncation() { - let mut metrics = Metrics::default(); - let now = CurrentClock::now(); - let labels = LabelSet::from([("request_kind", "connect")]); - - metrics - .set_gauge( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &labels, - 1234.567, - now, - ) - .unwrap(); - - // Should truncate to 1234 - assert_eq!(metrics.udp_avg_connect_processing_time_ns(), 1234); - } - #[test] fn it_should_overwrite_gauge_values_when_set_multiple_times() { let mut metrics = Metrics::default(); @@ -1155,7 +1021,7 @@ mod tests { let result = metrics.increase_counter(&metric_name!(UDP_TRACKER_SERVER_REQUESTS_ABORTED_TOTAL), &empty_labels, now); assert!(result.is_ok()); - assert_eq!(metrics.udp_requests_aborted(), 1); + assert_eq!(metrics.udp_requests_aborted_total(), 1); } #[test] @@ -1180,8 +1046,8 @@ mod tests { } // Should return labeled sums correctly - assert_eq!(metrics.udp4_requests(), 3); - assert_eq!(metrics.udp6_requests(), 5); + assert_eq!(metrics.udp4_requests_received_total(), 3); + assert_eq!(metrics.udp6_requests_received_total(), 5); } } diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index 85e3bbe64..7a1c5fa4a 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -95,6 +95,7 @@ mod tests { use std::time::Duration; use torrust_tracker_clock::clock::Time; + use torrust_tracker_metrics::metric_collection::aggregate::sum::Sum; use torrust_tracker_metrics::metric_name; use super::*; @@ -155,8 +156,8 @@ mod tests { let stats = repo.get_stats().await; // Should be able to read metrics through the guard - assert_eq!(stats.udp_requests_aborted(), 0); - assert_eq!(stats.udp_requests_banned(), 0); + assert_eq!(stats.udp_requests_aborted_total(), 0); + assert_eq!(stats.udp_requests_banned_total(), 0); } #[tokio::test] @@ -174,7 +175,7 @@ mod tests { // Verify the counter was incremented let stats = repo.get_stats().await; - assert_eq!(stats.udp_requests_aborted(), 1); + assert_eq!(stats.udp_requests_aborted_total(), 1); } #[tokio::test] @@ -192,7 +193,7 @@ mod tests { // Verify the counter was incremented correctly let stats = repo.get_stats().await; - assert_eq!(stats.udp_requests_aborted(), 5); + assert_eq!(stats.udp_requests_aborted_total(), 5); } #[tokio::test] @@ -214,8 +215,8 @@ mod tests { // Verify both labeled metrics let stats = repo.get_stats().await; - assert_eq!(stats.udp4_requests(), 1); - assert_eq!(stats.udp6_requests(), 1); + assert_eq!(stats.udp4_requests_received_total(), 1); + assert_eq!(stats.udp6_requests_received_total(), 1); } #[tokio::test] @@ -286,8 +287,29 @@ mod tests { // Verify both labeled metrics let stats = repo.get_stats().await; - assert_eq!(stats.udp_avg_connect_processing_time_ns(), 1000); - assert_eq!(stats.udp_avg_announce_processing_time_ns(), 2000); + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp_avg_connect_processing_time_ns = stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "connect")].into(), + ) + .unwrap_or_default() as u64; + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let udp_avg_announce_processing_time_ns = stats + .metric_collection + .sum( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &[("request_kind", "announce")].into(), + ) + .unwrap_or_default() as u64; + + assert_eq!(udp_avg_connect_processing_time_ns, 1000); + assert_eq!(udp_avg_announce_processing_time_ns, 2000); } #[tokio::test] @@ -452,7 +474,7 @@ mod tests { // Verify all increments were properly recorded let stats = repo.get_stats().await; - assert_eq!(stats.udp_requests_aborted(), 50); // 10 tasks * 5 increments each + assert_eq!(stats.udp_requests_aborted_total(), 50); // 10 tasks * 5 increments each } #[tokio::test] @@ -511,9 +533,9 @@ mod tests { // Check final state let stats = repo.get_stats().await; - assert_eq!(stats.udp_requests_aborted(), 1); + assert_eq!(stats.udp_requests_aborted_total(), 1); assert_eq!(stats.udp_banned_ips_total(), 10); - assert_eq!(stats.udp_requests_banned(), 1); + assert_eq!(stats.udp_requests_banned_total(), 1); } #[tokio::test] diff --git a/packages/udp-tracker-server/tests/server/contract.rs b/packages/udp-tracker-server/tests/server/contract.rs index 2745f3407..da08bc177 100644 --- a/packages/udp-tracker-server/tests/server/contract.rs +++ b/packages/udp-tracker-server/tests/server/contract.rs @@ -273,7 +273,7 @@ mod receiving_an_announce_request { .stats_repository .get_stats() .await - .udp_requests_banned(); + .udp_requests_banned_total(); // This should return a timeout error match client.send(announce_request.into()).await { @@ -289,7 +289,7 @@ mod receiving_an_announce_request { .stats_repository .get_stats() .await - .udp_requests_banned(); + .udp_requests_banned_total(); let udp_banned_ips_total_after = ban_service.read().await.get_banned_ips_total(); // UDP counter for banned requests should be increased by 1 From dc8d4a9b9874b03a7724b17d0494e84430d95d45 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 20 Jun 2025 16:23:07 +0100 Subject: [PATCH 1249/1297] test: [#1589] add race condition test for UDP performance metrics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a comprehensive unit test to validate thread safety when updating UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS metrics under concurrent load. The test: - Spawns 200 concurrent tasks (100 per server) simulating two UDP servers - Server 1: cycles through [1000, 2000, 3000, 4000, 5000] ns processing times - Server 2: cycles through [2000, 3000, 4000, 5000, 6000] ns processing times - Validates request counts, average calculations, and metric relationships - Uses tolerance-based assertions (±50ns) to account for moving average calculation variations in concurrent environments - Ensures thread safety and mathematical correctness of the metrics system This test helps ensure the UDP tracker server's metrics collection remains accurate and thread-safe under high-concurrency scenarios. --- .../src/statistics/repository.rs | 202 ++++++++++++++++++ 1 file changed, 202 insertions(+) diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index 7a1c5fa4a..b80b8ba09 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -564,4 +564,206 @@ mod tests { // Should handle NaN values assert!(result.is_ok()); } + + #[tokio::test] + #[allow(clippy::too_many_lines)] + async fn it_should_handle_race_conditions_when_updating_udp_performance_metrics_in_parallel() { + // Number of concurrent requests per server + const REQUESTS_PER_SERVER: usize = 100; + + let repo = Repository::new(); + let now = CurrentClock::now(); + + // Define labels for two different UDP servers + let server1_labels = LabelSet::from([ + ("request_kind", "connect"), + ("server_binding_address_ip_family", "inet"), + ("server_port", "6868"), + ]); + let server2_labels = LabelSet::from([ + ("request_kind", "connect"), + ("server_binding_address_ip_family", "inet"), + ("server_port", "6969"), + ]); + + let mut handles = vec![]; + + // Spawn tasks for server 1 + for i in 0..REQUESTS_PER_SERVER { + let repo_clone = repo.clone(); + let labels = server1_labels.clone(); + let handle = tokio::spawn(async move { + // Simulate varying processing times (1000ns to 5000ns) + let processing_time_ns = 1000 + (i % 5) * 1000; + let processing_time = Duration::from_nanos(processing_time_ns as u64); + + repo_clone + .recalculate_udp_avg_processing_time_ns(processing_time, &labels, now) + .await + }); + handles.push(handle); + } + + // Spawn tasks for server 2 + for i in 0..REQUESTS_PER_SERVER { + let repo_clone = repo.clone(); + let labels = server2_labels.clone(); + let handle = tokio::spawn(async move { + // Simulate different processing times (2000ns to 6000ns) + let processing_time_ns = 2000 + (i % 5) * 1000; + let processing_time = Duration::from_nanos(processing_time_ns as u64); + + repo_clone + .recalculate_udp_avg_processing_time_ns(processing_time, &labels, now) + .await + }); + handles.push(handle); + } + + // Collect all the results + let mut server1_results = Vec::new(); + let mut server2_results = Vec::new(); + + for (i, handle) in handles.into_iter().enumerate() { + let result = handle.await.unwrap(); + if i < REQUESTS_PER_SERVER { + server1_results.push(result); + } else { + server2_results.push(result); + } + } + + // Verify that all tasks completed successfully + assert_eq!(server1_results.len(), REQUESTS_PER_SERVER); + assert_eq!(server2_results.len(), REQUESTS_PER_SERVER); + + // Verify that all results are finite and positive + for result in &server1_results { + assert!(result.is_finite(), "Server 1 result should be finite: {result}"); + assert!(*result > 0.0, "Server 1 result should be positive: {result}"); + } + + for result in &server2_results { + assert!(result.is_finite(), "Server 2 result should be finite: {result}"); + assert!(*result > 0.0, "Server 2 result should be positive: {result}"); + } + + // Get final stats and verify metrics integrity + let stats = repo.get_stats().await; + + // Verify that the processed requests counters are correct for each server + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let server1_processed = stats + .metric_collection + .get_counter_value( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), + &server1_labels, + ) + .unwrap() + .value(); + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let server2_processed = stats + .metric_collection + .get_counter_value( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), + &server2_labels, + ) + .unwrap() + .value(); + + assert_eq!( + server1_processed, REQUESTS_PER_SERVER as u64, + "Server 1 should have processed {REQUESTS_PER_SERVER} requests", + ); + assert_eq!( + server2_processed, REQUESTS_PER_SERVER as u64, + "Server 2 should have processed {REQUESTS_PER_SERVER} requests", + ); + + // Verify that the final average processing times are reasonable + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let server1_final_avg = stats + .metric_collection + .get_gauge_value( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &server1_labels, + ) + .unwrap() + .value(); + + #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_possible_truncation)] + let server2_final_avg = stats + .metric_collection + .get_gauge_value( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), + &server2_labels, + ) + .unwrap() + .value(); + + // Server 1: 100 requests cycling through [1000, 2000, 3000, 4000, 5000] ns + // Expected average: (20×1000 + 20×2000 + 20×3000 + 20×4000 + 20×5000) / 100 = 3000 ns + // Note: Moving average with concurrent updates may have small deviations due to order dependency + assert!( + (server1_final_avg - 3000.0).abs() < 50.0, + "Server 1 final average should be close to 3000ns (±50ns), got {server1_final_avg}ns" + ); + + // Server 2: 100 requests cycling through [2000, 3000, 4000, 5000, 6000] ns + // Expected average: (20×2000 + 20×3000 + 20×4000 + 20×5000 + 20×6000) / 100 = 4000 ns + // Note: Moving average with concurrent updates may have small deviations due to order dependency + assert!( + (server2_final_avg - 4000.0).abs() < 50.0, + "Server 2 final average should be close to 4000ns (±50ns), got {server2_final_avg}ns" + ); + + // Verify that the two servers have different averages (they should since they have different processing time ranges) + assert!( + (server1_final_avg - server2_final_avg).abs() > 950.0, + "Server 1 and Server 2 should have different average processing times" + ); + + // Server 2 should generally have higher averages since its processing times are higher + assert!( + server2_final_avg > server1_final_avg, + "Server 2 average ({server2_final_avg}) should be higher than Server 1 average ({server1_final_avg})" + ); + + // Verify that the moving average calculation maintains consistency + // The last result for each server should match the final stored average + let server1_last_result = server1_results.last().copied().unwrap(); + let server2_last_result = server2_results.last().copied().unwrap(); + + // Note: Due to race conditions, the last result might not exactly match the final stored average + // but it should be in a reasonable range. We'll check that they're in the same ballpark. + let server1_diff = (server1_last_result - server1_final_avg).abs(); + let server2_diff = (server2_last_result - server2_final_avg).abs(); + + assert!( + server1_diff <= 0.0, + "Server 1 last result ({server1_last_result}) should be equal to final average ({server1_final_avg}), diff: {server1_diff}", + ); + + assert!( + server2_diff <= 0.0, + "Server 2 last result ({server2_last_result}) should be equal to final average ({server2_final_avg}), diff: {server2_diff}", + ); + + // Verify that the metric collection contains the expected metrics for both servers + assert!(stats + .metric_collection + .contains_gauge(&metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL))); + + println!( + "Race condition test completed successfully:\n Server 1: {server1_processed} requests, final avg: {server1_final_avg}ns\n Server 2: {server2_processed} requests, final avg: {server2_final_avg}ns" + ); + } } From b423bf61ee13562ef642e3b4da01868246dfeec5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 20 Jun 2025 17:50:15 +0100 Subject: [PATCH 1250/1297] refactor: [#1589] improve readability of UDP performance metrics race condition test Restructures the race condition test to follow clear Arrange-Act-Assert pattern and eliminates code duplication through helper function extraction. The test maintains identical functionality while being more maintainable, readable, and following DRY principles. All 200 concurrent tasks still validate thread safety and mathematical correctness of the metrics system. --- .../src/statistics/repository.rs | 346 +++++++++--------- 1 file changed, 176 insertions(+), 170 deletions(-) diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index b80b8ba09..94a86e3ab 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -565,205 +565,211 @@ mod tests { assert!(result.is_ok()); } - #[tokio::test] - #[allow(clippy::too_many_lines)] - async fn it_should_handle_race_conditions_when_updating_udp_performance_metrics_in_parallel() { - // Number of concurrent requests per server - const REQUESTS_PER_SERVER: usize = 100; + mod race_conditions { - let repo = Repository::new(); - let now = CurrentClock::now(); + use core::f64; + use std::time::Duration; - // Define labels for two different UDP servers - let server1_labels = LabelSet::from([ - ("request_kind", "connect"), - ("server_binding_address_ip_family", "inet"), - ("server_port", "6868"), - ]); - let server2_labels = LabelSet::from([ - ("request_kind", "connect"), - ("server_binding_address_ip_family", "inet"), - ("server_port", "6969"), - ]); + use tokio::task::JoinHandle; + use torrust_tracker_clock::clock::Time; + use torrust_tracker_metrics::metric_name; - let mut handles = vec![]; + use super::*; + use crate::CurrentClock; - // Spawn tasks for server 1 - for i in 0..REQUESTS_PER_SERVER { - let repo_clone = repo.clone(); - let labels = server1_labels.clone(); - let handle = tokio::spawn(async move { - // Simulate varying processing times (1000ns to 5000ns) - let processing_time_ns = 1000 + (i % 5) * 1000; - let processing_time = Duration::from_nanos(processing_time_ns as u64); + #[tokio::test] + async fn it_should_handle_race_conditions_when_updating_udp_performance_metrics_in_parallel() { + const REQUESTS_PER_SERVER: usize = 100; - repo_clone - .recalculate_udp_avg_processing_time_ns(processing_time, &labels, now) - .await - }); - handles.push(handle); - } + // ** Set up test data and environment ** - // Spawn tasks for server 2 - for i in 0..REQUESTS_PER_SERVER { - let repo_clone = repo.clone(); - let labels = server2_labels.clone(); - let handle = tokio::spawn(async move { - // Simulate different processing times (2000ns to 6000ns) - let processing_time_ns = 2000 + (i % 5) * 1000; - let processing_time = Duration::from_nanos(processing_time_ns as u64); + let repo = Repository::new(); + let now = CurrentClock::now(); - repo_clone - .recalculate_udp_avg_processing_time_ns(processing_time, &labels, now) - .await - }); - handles.push(handle); - } + let server1_labels = create_server_metric_labels("6868"); + let server2_labels = create_server_metric_labels("6969"); - // Collect all the results - let mut server1_results = Vec::new(); - let mut server2_results = Vec::new(); + // ** Execute concurrent metric updates ** - for (i, handle) in handles.into_iter().enumerate() { - let result = handle.await.unwrap(); - if i < REQUESTS_PER_SERVER { - server1_results.push(result); - } else { - server2_results.push(result); - } - } + // Spawn concurrent tasks for server 1 with processing times [1000, 2000, 3000, 4000, 5000] ns + let server1_handles = spawn_server_tasks(&repo, &server1_labels, 1000, now, REQUESTS_PER_SERVER); - // Verify that all tasks completed successfully - assert_eq!(server1_results.len(), REQUESTS_PER_SERVER); - assert_eq!(server2_results.len(), REQUESTS_PER_SERVER); + // Spawn concurrent tasks for server 2 with processing times [2000, 3000, 4000, 5000, 6000] ns + let server2_handles = spawn_server_tasks(&repo, &server2_labels, 2000, now, REQUESTS_PER_SERVER); - // Verify that all results are finite and positive - for result in &server1_results { - assert!(result.is_finite(), "Server 1 result should be finite: {result}"); - assert!(*result > 0.0, "Server 1 result should be positive: {result}"); - } + // Wait for both servers' results + let (server1_results, server2_results) = tokio::join!( + collect_concurrent_task_results(server1_handles), + collect_concurrent_task_results(server2_handles) + ); + + // ** Verify results and metrics ** + + // Verify correctness of concurrent operations + assert_server_results_are_valid(&server1_results, "Server 1", REQUESTS_PER_SERVER); + assert_server_results_are_valid(&server2_results, "Server 2", REQUESTS_PER_SERVER); + + let stats = repo.get_stats().await; - for result in &server2_results { - assert!(result.is_finite(), "Server 2 result should be finite: {result}"); - assert!(*result > 0.0, "Server 2 result should be positive: {result}"); + // Verify each server's metrics individually + let server1_avg = assert_server_metrics_are_correct(&stats, &server1_labels, "Server 1", REQUESTS_PER_SERVER, 3000.0); + let server2_avg = assert_server_metrics_are_correct(&stats, &server2_labels, "Server 2", REQUESTS_PER_SERVER, 4000.0); + + // Verify relationship between servers + assert_server_metrics_relationship(server1_avg, server2_avg); + + // Verify each server's result consistency individually + assert_server_result_matches_stored_average(&server1_results, &stats, &server1_labels, "Server 1"); + assert_server_result_matches_stored_average(&server2_results, &stats, &server2_labels, "Server 2"); + + // Verify metric collection integrity + assert_metric_collection_integrity(&stats); } - // Get final stats and verify metrics integrity - let stats = repo.get_stats().await; + // Test helper functions to hide implementation details - // Verify that the processed requests counters are correct for each server - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let server1_processed = stats - .metric_collection - .get_counter_value( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), - &server1_labels, - ) - .unwrap() - .value(); + fn create_server_metric_labels(port: &str) -> LabelSet { + LabelSet::from([ + ("request_kind", "connect"), + ("server_binding_address_ip_family", "inet"), + ("server_port", port), + ]) + } - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let server2_processed = stats - .metric_collection - .get_counter_value( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), - &server2_labels, - ) - .unwrap() - .value(); + fn spawn_server_tasks( + repo: &Repository, + labels: &LabelSet, + base_processing_time_ns: usize, + now: DurationSinceUnixEpoch, + requests_per_server: usize, + ) -> Vec> { + let mut handles = vec![]; + + for i in 0..requests_per_server { + let repo_clone = repo.clone(); + let labels_clone = labels.clone(); + let handle = tokio::spawn(async move { + let processing_time_ns = base_processing_time_ns + (i % 5) * 1000; + let processing_time = Duration::from_nanos(processing_time_ns as u64); + repo_clone + .recalculate_udp_avg_processing_time_ns(processing_time, &labels_clone, now) + .await + }); + handles.push(handle); + } - assert_eq!( - server1_processed, REQUESTS_PER_SERVER as u64, - "Server 1 should have processed {REQUESTS_PER_SERVER} requests", - ); - assert_eq!( - server2_processed, REQUESTS_PER_SERVER as u64, - "Server 2 should have processed {REQUESTS_PER_SERVER} requests", - ); + handles + } - // Verify that the final average processing times are reasonable - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let server1_final_avg = stats - .metric_collection - .get_gauge_value( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &server1_labels, - ) - .unwrap() - .value(); + async fn collect_concurrent_task_results(handles: Vec>) -> Vec { + let mut server_results = Vec::new(); - #[allow(clippy::cast_sign_loss)] - #[allow(clippy::cast_possible_truncation)] - let server2_final_avg = stats - .metric_collection - .get_gauge_value( - &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), - &server2_labels, - ) - .unwrap() - .value(); + for handle in handles { + let result = handle.await.unwrap(); + server_results.push(result); + } - // Server 1: 100 requests cycling through [1000, 2000, 3000, 4000, 5000] ns - // Expected average: (20×1000 + 20×2000 + 20×3000 + 20×4000 + 20×5000) / 100 = 3000 ns - // Note: Moving average with concurrent updates may have small deviations due to order dependency - assert!( - (server1_final_avg - 3000.0).abs() < 50.0, - "Server 1 final average should be close to 3000ns (±50ns), got {server1_final_avg}ns" - ); + server_results + } - // Server 2: 100 requests cycling through [2000, 3000, 4000, 5000, 6000] ns - // Expected average: (20×2000 + 20×3000 + 20×4000 + 20×5000 + 20×6000) / 100 = 4000 ns - // Note: Moving average with concurrent updates may have small deviations due to order dependency - assert!( - (server2_final_avg - 4000.0).abs() < 50.0, - "Server 2 final average should be close to 4000ns (±50ns), got {server2_final_avg}ns" - ); + fn assert_server_results_are_valid(results: &[f64], server_name: &str, expected_count: usize) { + // Verify all tasks completed + assert_eq!( + results.len(), + expected_count, + "{server_name} should have {expected_count} results" + ); + + // Verify all results are valid numbers + for result in results { + assert!(result.is_finite(), "{server_name} result should be finite: {result}"); + assert!(*result > 0.0, "{server_name} result should be positive: {result}"); + } + } - // Verify that the two servers have different averages (they should since they have different processing time ranges) - assert!( - (server1_final_avg - server2_final_avg).abs() > 950.0, - "Server 1 and Server 2 should have different average processing times" - ); + fn assert_server_metrics_are_correct( + stats: &Metrics, + labels: &LabelSet, + server_name: &str, + expected_request_count: usize, + expected_avg_ns: f64, + ) -> f64 { + // Verify request count + let processed_requests = get_processed_requests_count(stats, labels); + assert_eq!( + processed_requests, expected_request_count as u64, + "{server_name} should have processed {expected_request_count} requests" + ); + + // Verify average processing time is within expected range + let avg_processing_time = get_average_processing_time(stats, labels); + assert!( + (avg_processing_time - expected_avg_ns).abs() < 50.0, + "{server_name} average should be ~{expected_avg_ns}ns (±50ns), got {avg_processing_time}ns" + ); + + avg_processing_time + } - // Server 2 should generally have higher averages since its processing times are higher - assert!( - server2_final_avg > server1_final_avg, - "Server 2 average ({server2_final_avg}) should be higher than Server 1 average ({server1_final_avg})" - ); + fn assert_server_metrics_relationship(server1_avg: f64, server2_avg: f64) { + const MIN_DIFFERENCE_NS: f64 = 950.0; - // Verify that the moving average calculation maintains consistency - // The last result for each server should match the final stored average - let server1_last_result = server1_results.last().copied().unwrap(); - let server2_last_result = server2_results.last().copied().unwrap(); + assert_averages_are_significantly_different(server1_avg, server2_avg, MIN_DIFFERENCE_NS); + assert_server_ordering_is_correct(server1_avg, server2_avg); + } - // Note: Due to race conditions, the last result might not exactly match the final stored average - // but it should be in a reasonable range. We'll check that they're in the same ballpark. - let server1_diff = (server1_last_result - server1_final_avg).abs(); - let server2_diff = (server2_last_result - server2_final_avg).abs(); + fn assert_averages_are_significantly_different(avg1: f64, avg2: f64, min_difference: f64) { + let difference = (avg1 - avg2).abs(); + assert!( + difference > min_difference, + "Server averages should differ by more than {min_difference}ns, but difference was {difference}ns" + ); + } - assert!( - server1_diff <= 0.0, - "Server 1 last result ({server1_last_result}) should be equal to final average ({server1_final_avg}), diff: {server1_diff}", + fn assert_server_ordering_is_correct(server1_avg: f64, server2_avg: f64) { + // Server 2 should have higher average since it has higher processing times [2000-6000] vs [1000-5000] + assert!( + server2_avg > server1_avg, + "Server 2 average ({server2_avg}ns) should be higher than Server 1 ({server1_avg}ns) due to higher processing time ranges" ); + } - assert!( - server2_diff <= 0.0, - "Server 2 last result ({server2_last_result}) should be equal to final average ({server2_final_avg}), diff: {server2_diff}", - ); + fn assert_server_result_matches_stored_average(results: &[f64], stats: &Metrics, labels: &LabelSet, server_name: &str) { + let final_avg = get_average_processing_time(stats, labels); + let last_result = results.last().copied().unwrap(); - // Verify that the metric collection contains the expected metrics for both servers - assert!(stats - .metric_collection - .contains_gauge(&metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS))); - assert!(stats - .metric_collection - .contains_counter(&metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL))); + assert!( + (last_result - final_avg).abs() <= f64::EPSILON, + "{server_name} last result ({last_result}) should match final average ({final_avg}) exactly" + ); + } - println!( - "Race condition test completed successfully:\n Server 1: {server1_processed} requests, final avg: {server1_final_avg}ns\n Server 2: {server2_processed} requests, final avg: {server2_final_avg}ns" - ); + fn assert_metric_collection_integrity(stats: &Metrics) { + assert!(stats + .metric_collection + .contains_gauge(&metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS))); + assert!(stats + .metric_collection + .contains_counter(&metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL))); + } + + fn get_processed_requests_count(stats: &Metrics, labels: &LabelSet) -> u64 { + stats + .metric_collection + .get_counter_value( + &metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSED_REQUESTS_TOTAL), + labels, + ) + .unwrap() + .value() + } + + fn get_average_processing_time(stats: &Metrics, labels: &LabelSet) -> f64 { + stats + .metric_collection + .get_gauge_value(&metric_name!(UDP_TRACKER_SERVER_PERFORMANCE_AVG_PROCESSING_TIME_NS), labels) + .unwrap() + .value() + } } } From 364c6077bd9a4eae3200c3665ac5b7fc472dba9c Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Dec 2025 12:42:58 +0000 Subject: [PATCH 1251/1297] fix: clippy errors --- .../src/console/clients/checker/checks/udp.rs | 1 + packages/http-protocol/src/v1/query.rs | 2 +- packages/http-tracker-core/src/services/announce.rs | 8 -------- .../swarm-coordination-registry/src/swarm/coordinator.rs | 2 +- .../src/entry/peer_list.rs | 2 +- packages/tracker-core/src/torrent/services.rs | 2 +- packages/udp-tracker-server/src/event.rs | 2 +- packages/udp-tracker-server/tests/server/contract.rs | 2 +- src/console/ci/e2e/docker.rs | 2 +- src/console/ci/e2e/runner.rs | 2 +- 10 files changed, 9 insertions(+), 16 deletions(-) diff --git a/console/tracker-client/src/console/clients/checker/checks/udp.rs b/console/tracker-client/src/console/clients/checker/checks/udp.rs index 20394d55a..611afafc4 100644 --- a/console/tracker-client/src/console/clients/checker/checks/udp.rs +++ b/console/tracker-client/src/console/clients/checker/checks/udp.rs @@ -29,6 +29,7 @@ pub async fn run(udp_trackers: Vec, timeout: Duration) -> Vec for ErrorKind { }, UdpScrapeError::TrackerCoreWhitelistError { source } => Self::Whitelist(source.to_string()), }, - Error::Internal { location: _, message } => Self::InternalServer(message.to_string()), + Error::Internal { location: _, message } => Self::InternalServer(message.clone()), Error::AuthRequired { location } => Self::TrackerAuthentication(location.to_string()), } } diff --git a/packages/udp-tracker-server/tests/server/contract.rs b/packages/udp-tracker-server/tests/server/contract.rs index da08bc177..e9691c879 100644 --- a/packages/udp-tracker-server/tests/server/contract.rs +++ b/packages/udp-tracker-server/tests/server/contract.rs @@ -251,7 +251,7 @@ mod receiving_an_announce_request { let transaction_id = tx_id.0.to_string(); assert!( - logs_contains_a_line_with(&["ERROR", "UDP TRACKER", &transaction_id.to_string()]), + logs_contains_a_line_with(&["ERROR", "UDP TRACKER", &transaction_id]), "Expected logs to contain: ERROR ... UDP TRACKER ... transaction_id={transaction_id}" ); } diff --git a/src/console/ci/e2e/docker.rs b/src/console/ci/e2e/docker.rs index ce2b1aa99..89d258d2c 100644 --- a/src/console/ci/e2e/docker.rs +++ b/src/console/ci/e2e/docker.rs @@ -82,7 +82,7 @@ impl Docker { let mut port_args: Vec = vec![]; for port in &options.ports { port_args.push("--publish".to_string()); - port_args.push(port.to_string()); + port_args.push(port.clone()); } let args = [initial_args, env_var_args, port_args, [image.to_string()].to_vec()].concat(); diff --git a/src/console/ci/e2e/runner.rs b/src/console/ci/e2e/runner.rs index 624878c70..6275c144b 100644 --- a/src/console/ci/e2e/runner.rs +++ b/src/console/ci/e2e/runner.rs @@ -77,7 +77,7 @@ pub fn run() -> anyhow::Result<()> { // Besides, if we don't use port 0 we should get the port numbers from the tracker configuration. // We could not use docker, but the intention was to create E2E tests including containerization. let options = RunOptions { - env_vars: vec![("TORRUST_TRACKER_CONFIG_TOML".to_string(), tracker_config.to_string())], + env_vars: vec![("TORRUST_TRACKER_CONFIG_TOML".to_string(), tracker_config.clone())], ports: vec![ "6969:6969/udp".to_string(), "7070:7070/tcp".to_string(), From 11721dce92bbf4cc42d389da098a157a1a053922 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 1 Dec 2025 12:43:42 +0000 Subject: [PATCH 1252/1297] chore(deps): udpate dependencies ``` $ cargo update Updating crates.io index Locking 264 packages to latest compatible versions Updating addr2line v0.24.2 -> v0.25.1 Updating aho-corasick v1.1.3 -> v1.1.4 Adding alloca v0.4.0 Removing android-tzdata v0.1.1 Updating anstream v0.6.19 -> v0.6.21 Updating anstyle v1.0.11 -> v1.0.13 Updating anstyle-query v1.1.3 -> v1.1.5 Updating anstyle-wincon v3.0.9 -> v3.0.11 Updating anyhow v1.0.98 -> v1.0.100 Adding astral-tokio-tar v0.5.6 Updating async-channel v2.3.1 -> v2.5.0 Updating async-compression v0.4.24 -> v0.4.34 Updating async-executor v1.13.2 -> v1.13.3 Updating async-io v2.4.1 -> v2.6.0 Updating async-lock v3.4.0 -> v3.4.1 Updating async-std v1.13.1 -> v1.13.2 Adding async-stream v0.3.6 Adding async-stream-impl v0.3.6 Updating async-trait v0.1.88 -> v0.1.89 Updating atomic v0.6.0 -> v0.6.1 Updating autocfg v1.4.0 -> v1.5.0 Updating axum v0.8.4 -> v0.8.7 Updating axum-core v0.5.2 -> v0.5.5 Updating axum-extra v0.10.1 -> v0.12.2 Updating axum-server v0.7.2 -> v0.7.3 Updating backtrace v0.3.75 -> v0.3.76 Updating bigdecimal v0.4.8 -> v0.4.9 Updating bindgen v0.72.0 -> v0.72.1 Removing bitflags v1.3.2 Removing bitflags v2.9.1 Adding bitflags v2.10.0 Updating blocking v1.6.1 -> v1.6.2 Updating bollard v0.18.1 -> v0.19.4 Adding bollard-buildkit-proto v0.7.0 Updating bollard-stubs v1.47.1-rc.27.3.1 -> v1.49.1-rc.28.4.0 Updating borsh v1.5.7 -> v1.6.0 Updating borsh-derive v1.5.7 -> v1.6.0 Updating brotli v8.0.1 -> v8.0.2 Updating bumpalo v3.18.1 -> v3.19.0 Updating bytemuck v1.23.1 -> v1.24.0 Updating bytes v1.10.1 -> v1.11.0 Updating camino v1.1.10 -> v1.1.12 (available: v1.2.1) Updating castaway v0.2.3 -> v0.2.4 Updating cc v1.2.26 -> v1.2.48 Updating cfg-if v1.0.1 -> v1.0.4 Updating chrono v0.4.41 -> v0.4.42 Updating clap v4.5.40 -> v4.5.53 Updating clap_builder v4.5.40 -> v4.5.53 Updating clap_derive v4.5.40 -> v4.5.49 Updating clap_lex v0.7.5 -> v0.7.6 Adding compression-codecs v0.4.33 Adding compression-core v0.4.31 Updating crc32fast v1.4.2 -> v1.5.0 Updating criterion v0.6.0 -> v0.8.0 Adding criterion-plot v0.8.0 Updating crunchy v0.2.3 -> v0.2.4 Updating crypto-common v0.1.6 -> v0.1.7 Adding darling v0.21.3 Adding darling_core v0.21.3 Adding darling_macro v0.21.3 Updating deranged v0.4.0 -> v0.5.5 Adding dyn-clone v1.0.20 Updating errno v0.3.12 -> v0.3.14 Updating etcetera v0.10.0 -> v0.11.0 Updating event-listener v5.4.0 -> v5.4.1 Adding ferroid v0.8.7 Updating filetime v0.2.25 -> v0.2.26 Adding find-msvc-tools v0.1.5 Updating flate2 v1.1.2 -> v1.1.5 Updating form_urlencoded v1.2.1 -> v1.2.2 Updating frunk v0.4.3 -> v0.4.4 Updating frunk_core v0.4.3 -> v0.4.4 Updating frunk_derives v0.4.3 -> v0.4.4 Updating frunk_proc_macro_helpers v0.1.3 -> v0.1.4 Updating frunk_proc_macros v0.1.3 -> v0.1.4 Updating fs-err v3.1.1 -> v3.2.0 Updating futures-lite v2.6.0 -> v2.6.1 Updating getrandom v0.3.3 -> v0.3.4 Updating gimli v0.31.1 -> v0.32.3 Updating glob v0.3.2 -> v0.3.3 Updating h2 v0.4.10 -> v0.4.12 Updating half v2.6.0 -> v2.7.1 Removing hashbrown v0.15.4 Adding hashbrown v0.15.5 Adding hashbrown v0.16.1 Updating hermit-abi v0.5.1 -> v0.5.2 Updating hex-literal v1.0.0 -> v1.1.0 Updating home v0.5.11 -> v0.5.12 Updating http v1.3.1 -> v1.4.0 Updating hyper v1.6.0 -> v1.8.1 Adding hyper-timeout v0.5.2 Updating hyper-util v0.1.14 -> v0.1.18 Updating iana-time-zone v0.1.63 -> v0.1.64 Updating icu_collections v2.0.0 -> v2.1.1 Updating icu_locale_core v2.0.0 -> v2.1.1 Updating icu_normalizer v2.0.0 -> v2.1.1 Updating icu_normalizer_data v2.0.0 -> v2.1.1 Updating icu_properties v2.0.1 -> v2.1.1 Updating icu_properties_data v2.0.1 -> v2.1.1 Updating icu_provider v2.0.0 -> v2.1.1 Updating idna v1.0.3 -> v1.1.0 Updating indexmap v2.9.0 -> v2.12.1 Updating iri-string v0.7.8 -> v0.7.9 Updating is-terminal v0.4.16 -> v0.4.17 Updating is_terminal_polyfill v1.70.1 -> v1.70.2 Adding itertools v0.14.0 Updating jobserver v0.1.33 -> v0.1.34 Updating js-sys v0.3.77 -> v0.3.83 Updating libc v0.2.172 -> v0.2.177 Updating libloading v0.8.8 -> v0.8.9 Updating libredox v0.1.3 -> v0.1.10 Updating libsqlite3-sys v0.34.0 -> v0.35.0 Updating libz-sys v1.1.22 -> v1.1.23 Updating linux-raw-sys v0.9.4 -> v0.11.0 Updating litemap v0.8.0 -> v0.8.1 Updating lock_api v0.4.13 -> v0.4.14 Updating log v0.4.27 -> v0.4.28 Updating memchr v2.7.4 -> v2.7.6 Updating mio v1.0.4 -> v1.1.0 Updating mockall v0.13.1 -> v0.14.0 Updating mockall_derive v0.13.1 -> v0.14.0 Updating nu-ansi-term v0.46.0 -> v0.50.3 Adding num v0.4.3 Adding num-complex v0.4.6 Adding num-iter v0.1.45 Adding num-rational v0.4.2 Updating object v0.36.7 -> v0.37.3 Updating once_cell_polyfill v1.70.1 -> v1.70.2 Updating openssl v0.10.73 -> v0.10.75 Updating openssl-sys v0.9.109 -> v0.9.111 Removing overload v0.1.1 Updating owo-colors v4.2.1 -> v4.2.3 Adding page_size v0.6.0 Updating parking_lot v0.12.4 -> v0.12.5 Updating parking_lot_core v0.9.11 -> v0.9.12 Updating pem v3.0.5 -> v3.0.6 Updating percent-encoding v2.3.1 -> v2.3.2 Adding pin-project v1.1.10 Adding pin-project-internal v1.1.10 Updating polling v3.8.0 -> v3.11.0 Updating potential_utf v0.1.2 -> v0.1.4 Updating proc-macro-crate v3.3.0 -> v3.4.0 Updating proc-macro2 v1.0.95 -> v1.0.103 Adding prost v0.14.2 Adding prost-derive v0.14.2 Adding prost-types v0.14.2 Updating quote v1.0.40 -> v1.0.42 Updating r-efi v5.2.0 -> v5.3.0 Updating r2d2_sqlite v0.29.0 -> v0.31.0 Updating rand v0.9.1 -> v0.9.2 Updating rayon v1.10.0 -> v1.11.0 Updating rayon-core v1.12.1 -> v1.13.0 Removing redox_syscall v0.3.5 Removing redox_syscall v0.5.12 Adding redox_syscall v0.5.18 Adding ref-cast v1.0.25 Adding ref-cast-impl v1.0.25 Updating regex v1.11.1 -> v1.12.2 Updating regex-automata v0.4.9 -> v0.4.13 Updating regex-syntax v0.8.5 -> v0.8.8 Updating reqwest v0.12.20 -> v0.12.24 Adding rstest v0.26.1 Adding rstest_macros v0.26.1 Updating rusqlite v0.36.0 -> v0.37.0 Updating rust_decimal v1.37.1 -> v1.39.0 Updating rustc-demangle v0.1.25 -> v0.1.26 Updating rustix v1.0.7 -> v1.1.2 Updating rustls v0.23.27 -> v0.23.35 Updating rustls-native-certs v0.8.1 -> v0.8.2 Updating rustls-pki-types v1.12.0 -> v1.13.1 Updating rustls-webpki v0.103.3 -> v0.103.8 Updating rustversion v1.0.21 -> v1.0.22 Updating schannel v0.1.27 -> v0.1.28 Adding schemars v0.9.0 Adding schemars v1.1.0 Updating security-framework v3.2.0 -> v3.5.1 Updating security-framework-sys v2.14.0 -> v2.15.0 Updating semver v1.0.26 -> v1.0.27 Updating serde v1.0.219 -> v1.0.228 Updating serde_bytes v0.11.17 -> v0.11.19 Adding serde_core v1.0.228 Updating serde_derive v1.0.219 -> v1.0.228 Updating serde_html_form v0.2.7 -> v0.2.8 Updating serde_json v1.0.140 -> v1.0.145 Updating serde_path_to_error v0.1.17 -> v0.1.20 Adding serde_spanned v1.0.3 Updating serde_with v3.12.0 -> v3.16.1 Updating serde_with_macros v3.12.0 -> v3.16.1 Updating signal-hook-registry v1.4.5 -> v1.4.7 Adding simd-adler32 v0.3.7 Updating slab v0.4.9 -> v0.4.11 Adding socket2 v0.6.1 Updating stable_deref_trait v1.2.0 -> v1.2.1 Updating syn v2.0.102 -> v2.0.111 Updating tempfile v3.20.0 -> v3.23.0 Updating terminal_size v0.4.2 -> v0.4.3 Updating testcontainers v0.24.0 -> v0.26.0 Updating thiserror v2.0.12 -> v2.0.17 Updating thiserror-impl v2.0.12 -> v2.0.17 Updating thread_local v1.1.8 -> v1.1.9 Updating time v0.3.41 -> v0.3.44 Updating time-core v0.1.4 -> v0.1.6 Updating time-macros v0.2.22 -> v0.2.24 Updating tinystr v0.8.1 -> v0.8.2 Updating tinyvec v1.9.0 -> v1.10.0 Updating tokio v1.45.1 -> v1.48.0 Updating tokio-macros v2.5.0 -> v2.6.0 Updating tokio-rustls v0.26.2 -> v0.26.4 Removing tokio-tar v0.3.1 Updating tokio-util v0.7.15 -> v0.7.17 Adding toml v0.9.8 Adding toml_datetime v0.7.3 Adding toml_edit v0.23.7 Adding toml_parser v1.0.4 Adding toml_writer v1.0.4 Adding tonic v0.14.2 Adding tonic-prost v0.14.2 Updating tower-http v0.6.6 -> v0.6.7 Updating tracing v0.1.41 -> v0.1.43 Updating tracing-attributes v0.1.29 -> v0.1.31 Updating tracing-core v0.1.34 -> v0.1.35 Updating tracing-subscriber v0.3.19 -> v0.3.22 Updating typenum v1.18.0 -> v1.19.0 Updating unicode-ident v1.0.18 -> v1.0.22 Updating unicode-width v0.2.1 -> v0.2.2 Adding ureq v3.1.4 Adding ureq-proto v0.5.3 Updating url v2.5.4 -> v2.5.7 Adding utf-8 v0.7.6 Updating uuid v1.17.0 -> v1.18.1 Updating value-bag v1.11.1 -> v1.12.0 Removing wasi v0.14.2+wasi-0.2.4 Adding wasip2 v1.0.1+wasi-0.2.4 Updating wasm-bindgen v0.2.100 -> v0.2.106 Removing wasm-bindgen-backend v0.2.100 Updating wasm-bindgen-futures v0.4.50 -> v0.4.56 Updating wasm-bindgen-macro v0.2.100 -> v0.2.106 Updating wasm-bindgen-macro-support v0.2.100 -> v0.2.106 Updating wasm-bindgen-shared v0.2.100 -> v0.2.106 Updating web-sys v0.3.77 -> v0.3.83 Adding web-time v1.1.0 Adding webpki-roots v1.0.4 Updating winapi-util v0.1.9 -> v0.1.11 Updating windows-core v0.61.2 -> v0.62.2 Updating windows-implement v0.60.0 -> v0.60.2 Updating windows-interface v0.59.1 -> v0.59.3 Updating windows-link v0.1.1 -> v0.2.1 Updating windows-registry v0.5.2 -> v0.6.1 Updating windows-result v0.3.4 -> v0.4.1 Updating windows-strings v0.4.2 -> v0.5.1 Adding windows-sys v0.60.2 Adding windows-sys v0.61.2 Updating windows-targets v0.53.0 -> v0.53.5 Updating windows_aarch64_gnullvm v0.53.0 -> v0.53.1 Updating windows_aarch64_msvc v0.53.0 -> v0.53.1 Updating windows_i686_gnu v0.53.0 -> v0.53.1 Updating windows_i686_gnullvm v0.53.0 -> v0.53.1 Updating windows_i686_msvc v0.53.0 -> v0.53.1 Updating windows_x86_64_gnu v0.53.0 -> v0.53.1 Updating windows_x86_64_gnullvm v0.53.0 -> v0.53.1 Updating windows_x86_64_msvc v0.53.0 -> v0.53.1 Updating winnow v0.7.11 -> v0.7.14 Adding wit-bindgen v0.46.0 Removing wit-bindgen-rt v0.39.0 Updating writeable v0.6.1 -> v0.6.2 Updating xattr v1.5.0 -> v1.6.1 Updating yoke v0.8.0 -> v0.8.1 Updating yoke-derive v0.8.0 -> v0.8.1 Updating zerocopy v0.8.25 -> v0.8.31 Updating zerocopy-derive v0.8.25 -> v0.8.31 Updating zeroize v1.8.1 -> v1.8.2 Updating zerotrie v0.2.2 -> v0.2.3 Updating zerovec v0.11.2 -> v0.11.5 Updating zerovec-derive v0.11.1 -> v0.11.2 Updating zstd-sys v2.0.15+zstd.1.5.7 -> v2.0.16+zstd.1.5.7 note: pass `--verbose` to see 6 unchanged dependencies behind latest ``` --- Cargo.lock | 1870 +++++++++++++++++++++++++++++++++------------------- 1 file changed, 1187 insertions(+), 683 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b523c8b60..62d10c72f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "addr2line" -version = "0.24.2" +version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" +checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" dependencies = [ "gimli", ] @@ -30,9 +30,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.1.3" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" dependencies = [ "memchr", ] @@ -53,16 +53,19 @@ dependencies = [ ] [[package]] -name = "allocator-api2" -version = "0.2.21" +name = "alloca" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4" +dependencies = [ + "cc", +] [[package]] -name = "android-tzdata" -version = "0.1.1" +name = "allocator-api2" +version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "android_system_properties" @@ -81,9 +84,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.19" +version = "0.6.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "301af1932e46185686725e0fad2f8f2aa7da69dd70bf6ecc44d6b703844a3933" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" dependencies = [ "anstyle", "anstyle-parse", @@ -96,9 +99,9 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.11" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" +checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" [[package]] name = "anstyle-parse" @@ -111,29 +114,29 @@ dependencies = [ [[package]] name = "anstyle-query" -version = "1.1.3" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c8bdeb6047d8983be085bab0ba1472e6dc604e7041dbf6fcd5e71523014fae9" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] name = "anstyle-wincon" -version = "3.0.9" +version = "3.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "403f75924867bb1033c59fbf0797484329750cfbe3c4325cd33127941fabc882" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] name = "anyhow" -version = "1.0.98" +version = "1.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487" +checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" [[package]] name = "approx" @@ -182,6 +185,22 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +[[package]] +name = "astral-tokio-tar" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec179a06c1769b1e42e1e2cbe74c7dcdb3d6383c838454d063eaac5bbb7ebbe5" +dependencies = [ + "filetime", + "futures-core", + "libc", + "portable-atomic", + "rustc-hash", + "tokio", + "tokio-stream", + "xattr", +] + [[package]] name = "async-attributes" version = "1.1.2" @@ -205,9 +224,9 @@ dependencies = [ [[package]] name = "async-channel" -version = "2.3.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89b47800b0be77592da0afd425cc03468052844aff33b84e33cc696f64e77b6a" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" dependencies = [ "concurrent-queue", "event-listener-strategy", @@ -217,25 +236,22 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.24" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d615619615a650c571269c00dca41db04b9210037fa76ed8239f70404ab56985" +checksum = "0e86f6d3dc9dc4352edeea6b8e499e13e3f5dc3b964d7ca5fd411415a3498473" dependencies = [ - "brotli", - "flate2", + "compression-codecs", + "compression-core", "futures-core", - "memchr", "pin-project-lite", "tokio", - "zstd", - "zstd-safe", ] [[package]] name = "async-executor" -version = "1.13.2" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb812ffb58524bdd10860d7d974e2f01cc0950c2438a74ee5ec2e2280c6c4ffa" +checksum = "497c00e0fd83a72a79a39fcbd8e3e2f055d6f6c7e025f3b3d91f4f8e76527fb8" dependencies = [ "async-task", "concurrent-queue", @@ -251,7 +267,7 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" dependencies = [ - "async-channel 2.3.1", + "async-channel 2.5.0", "async-executor", "async-io", "async-lock", @@ -263,11 +279,11 @@ dependencies = [ [[package]] name = "async-io" -version = "2.4.1" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1237c0ae75a0f3765f58910ff9cdd0a12eeb39ab2f4c7de23262f337f0aacbb3" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" dependencies = [ - "async-lock", + "autocfg", "cfg-if", "concurrent-queue", "futures-io", @@ -276,26 +292,25 @@ dependencies = [ "polling", "rustix", "slab", - "tracing", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] name = "async-lock" -version = "3.4.0" +version = "3.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" +checksum = "5fd03604047cee9b6ce9de9f70c6cd540a0520c813cbd49bae61f33ab80ed1dc" dependencies = [ - "event-listener 5.4.0", + "event-listener 5.4.1", "event-listener-strategy", "pin-project-lite", ] [[package]] name = "async-std" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "730294c1c08c2e0f85759590518f6333f0d5a0a766a27d519c1b244c3dfd8a24" +checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b" dependencies = [ "async-attributes", "async-channel 1.9.0", @@ -318,6 +333,28 @@ dependencies = [ "wasm-bindgen-futures", ] +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + [[package]] name = "async-task" version = "4.7.1" @@ -326,20 +363,20 @@ checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" [[package]] name = "async-trait" -version = "0.1.88" +version = "0.1.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e539d3fca749fcee5236ab05e93a52867dd549cc157c8cb7f99595f3cedffdb5" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "atomic" -version = "0.6.0" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d818003e740b63afc82337e3160717f4f63078720a810b7b903e70a5d1d2994" +checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" dependencies = [ "bytemuck", ] @@ -352,15 +389,15 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "axum" -version = "0.8.4" +version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5" +checksum = "5b098575ebe77cb6d14fc7f32749631a6e44edbef6b796f89b020e99ba20d425" dependencies = [ "axum-core", "axum-macros", @@ -378,8 +415,7 @@ dependencies = [ "mime", "percent-encoding", "pin-project-lite", - "rustversion", - "serde", + "serde_core", "serde_json", "serde_path_to_error", "serde_urlencoded", @@ -404,9 +440,9 @@ dependencies = [ [[package]] name = "axum-core" -version = "0.5.2" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68464cd0412f486726fb3373129ef5d2993f90c34bc2bc1c1e9943b2f4fc7ca6" +checksum = "59446ce19cd142f8833f856eb31f3eb097812d1479ab224f54d72428ca21ea22" dependencies = [ "bytes", "futures-core", @@ -415,7 +451,6 @@ dependencies = [ "http-body-util", "mime", "pin-project-lite", - "rustversion", "sync_wrapper", "tower-layer", "tower-service", @@ -424,27 +459,27 @@ dependencies = [ [[package]] name = "axum-extra" -version = "0.10.1" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45bf463831f5131b7d3c756525b305d40f1185b688565648a92e1392ca35713d" +checksum = "dbfe9f610fe4e99cf0cfcd03ccf8c63c28c616fe714d80475ef731f3b13dd21b" dependencies = [ "axum", "axum-core", "bytes", "form_urlencoded", + "futures-core", "futures-util", "http", "http-body", "http-body-util", "mime", "pin-project-lite", - "rustversion", - "serde", + "serde_core", "serde_html_form", "serde_path_to_error", - "tower", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -455,14 +490,14 @@ checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "axum-server" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "495c05f60d6df0093e8fb6e74aa5846a0ad06abaf96d76166283720bf740f8ab" +checksum = "c1ab4a3ec9ea8a657c72d99a03a824af695bd0fb5ec639ccbd9cd3543b41a5f9" dependencies = [ "arc-swap", "bytes", @@ -482,9 +517,9 @@ dependencies = [ [[package]] name = "backtrace" -version = "0.3.75" +version = "0.3.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6806a6321ec58106fea15becdad98371e28d92ccbc7c8f1b3b6dd724fe8f1002" +checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" dependencies = [ "addr2line", "cfg-if", @@ -492,7 +527,7 @@ dependencies = [ "miniz_oxide", "object", "rustc-demangle", - "windows-targets 0.52.6", + "windows-link", ] [[package]] @@ -518,9 +553,9 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "bigdecimal" -version = "0.4.8" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a22f228ab7a1b23027ccc6c350b72868017af7ea8356fbdf19f8d991c690013" +checksum = "560f42649de9fa436b73517378a147ec21f6c997a546581df4b4b31677828934" dependencies = [ "autocfg", "libm", @@ -537,11 +572,11 @@ checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" [[package]] name = "bindgen" -version = "0.72.0" +version = "0.72.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f72209734318d0b619a5e0f5129918b848c416e122a3c4ce054e03cb87b726f" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" dependencies = [ - "bitflags 2.9.1", + "bitflags", "cexpr", "clang-sys", "itertools 0.13.0", @@ -550,7 +585,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -561,15 +596,9 @@ checksum = "02b4ff8b16e6076c3e14220b39fbc1fabb6737522281a388998046859400895f" [[package]] name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.9.1" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" +checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" [[package]] name = "bittorrent-http-tracker-core" @@ -585,7 +614,7 @@ dependencies = [ "mockall", "serde", "serde_json", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "tokio-util", "torrust-tracker-clock", @@ -610,7 +639,7 @@ dependencies = [ "percent-encoding", "serde", "serde_bencode", - "thiserror 2.0.12", + "thiserror 2.0.17", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-contrib-bencode", @@ -646,7 +675,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_repr", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "torrust-tracker-configuration", "torrust-tracker-located-error", @@ -668,11 +697,11 @@ dependencies = [ "r2d2", "r2d2_mysql", "r2d2_sqlite", - "rand 0.9.1", + "rand 0.9.2", "serde", "serde_json", "testcontainers", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "tokio-util", "torrust-rest-tracker-api-client", @@ -703,9 +732,9 @@ dependencies = [ "futures", "lazy_static", "mockall", - "rand 0.9.1", + "rand 0.9.2", "serde", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "tokio-util", "torrust-tracker-clock", @@ -751,11 +780,11 @@ dependencies = [ [[package]] name = "blocking" -version = "1.6.1" +version = "1.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "703f41c54fc768e63e091340b424302bb1c29ef4aa0c7f10fe849dfb114d29ea" +checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21" dependencies = [ - "async-channel 2.3.1", + "async-channel 2.5.0", "async-task", "futures-io", "futures-lite", @@ -783,13 +812,17 @@ dependencies = [ [[package]] name = "bollard" -version = "0.18.1" +version = "0.19.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97ccca1260af6a459d75994ad5acc1651bcabcbdbc41467cc9786519ab854c30" +checksum = "87a52479c9237eb04047ddb94788c41ca0d26eaff8b697ecfbb4c32f7fdc3b1b" dependencies = [ + "async-stream", "base64 0.22.1", + "bitflags", + "bollard-buildkit-proto", "bollard-stubs", "bytes", + "chrono", "futures-core", "futures-util", "hex", @@ -802,7 +835,9 @@ dependencies = [ "hyper-util", "hyperlocal", "log", + "num", "pin-project-lite", + "rand 0.9.2", "rustls", "rustls-native-certs", "rustls-pemfile", @@ -812,30 +847,51 @@ dependencies = [ "serde_json", "serde_repr", "serde_urlencoded", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", + "tokio-stream", "tokio-util", + "tonic", "tower-service", "url", "winapi", ] +[[package]] +name = "bollard-buildkit-proto" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85a885520bf6249ab931a764ffdb87b0ceef48e6e7d807cfdb21b751e086e1ad" +dependencies = [ + "prost", + "prost-types", + "tonic", + "tonic-prost", + "ureq", +] + [[package]] name = "bollard-stubs" -version = "1.47.1-rc.27.3.1" +version = "1.49.1-rc.28.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f179cfbddb6e77a5472703d4b30436bff32929c0aa8a9008ecf23d1d3cdd0da" +checksum = "5731fe885755e92beff1950774068e0cae67ea6ec7587381536fca84f1779623" dependencies = [ + "base64 0.22.1", + "bollard-buildkit-proto", + "bytes", + "chrono", + "prost", "serde", + "serde_json", "serde_repr", "serde_with", ] [[package]] name = "borsh" -version = "1.5.7" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8646f98db542e39fc66e68a20b2144f6a732636df7c2354e74645faaa433ce" +checksum = "d1da5ab77c1437701eeff7c88d968729e7766172279eab0676857b3d63af7a6f" dependencies = [ "borsh-derive", "cfg_aliases", @@ -843,22 +899,22 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.5.7" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdd1d3c0c2f5833f22386f252fe8ed005c7f59fdcddeef025c01b4c3b9fd9ac3" +checksum = "0686c856aa6aac0c4498f936d7d6a02df690f614c03e4d906d1018062b5c5e2c" dependencies = [ "once_cell", "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "brotli" -version = "8.0.1" +version = "8.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9991eea70ea4f293524138648e41ee89b0b2b12ddef3b255effa43c8056e0e0d" +checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -892,9 +948,9 @@ checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" [[package]] name = "bumpalo" -version = "3.18.1" +version = "3.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "793db76d6187cd04dff33004d8e6c9cc4e05cd330500379d2394209271b4aeee" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" [[package]] name = "bytecheck" @@ -920,9 +976,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.23.1" +version = "1.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c76a5792e44e4abe34d3abf15636779261d45a7450612059293d1d2cfc63422" +checksum = "1fbdf580320f38b612e485521afda1ee26d10cc9884efaaa750d383e13e3c5f4" [[package]] name = "byteorder" @@ -932,15 +988,15 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.10.1" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" +checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3" [[package]] name = "camino" -version = "1.1.10" +version = "1.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0da45bc31171d8d6960122e222a67740df867c1dd53b4d51caa297084c185cab" +checksum = "dd0b03af37dad7a14518b7691d81acb0f8222604ad3d1b02f6b4bed5188c0cd5" dependencies = [ "serde", ] @@ -953,19 +1009,20 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "castaway" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0abae9be0aaf9ea96a3b1b8b1b55c602ca751eba1b1500220cea4ecbafe7c0d5" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" dependencies = [ "rustversion", ] [[package]] name = "cc" -version = "1.2.26" +version = "1.2.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "956a5e21988b87f372569b66183b78babf23ebc2e744b733e4350a752c4dafac" +checksum = "c481bdbf0ed3b892f6f806287d72acd515b352a4ec27a208489b8c1bc839633a" dependencies = [ + "find-msvc-tools", "jobserver", "libc", "shlex", @@ -982,9 +1039,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.1" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "cfg_aliases" @@ -994,11 +1051,10 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "chrono" -version = "0.4.41" +version = "0.4.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d" +checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2" dependencies = [ - "android-tzdata", "iana-time-zone", "num-traits", "serde", @@ -1055,9 +1111,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.40" +version = "4.5.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40b6887a1d8685cebccf115538db5c0efe625ccac9696ad45c409d96566e910f" +checksum = "c9e340e012a1bf4935f5282ed1436d1489548e8f72308207ea5df0e23d2d03f8" dependencies = [ "clap_builder", "clap_derive", @@ -1065,9 +1121,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.40" +version = "4.5.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0c66c08ce9f0c698cbce5c0279d0bb6ac936d8674174fe48f736533b964f59e" +checksum = "d76b5d13eaa18c901fd2f7fca939fefe3a0727a953561fefdf3b2922b8569d00" dependencies = [ "anstream", "anstyle", @@ -1077,21 +1133,21 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.40" +version = "4.5.49" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2c7947ae4cc3d851207c1adb5b5e260ff0cca11446b1d6d1423788e442257ce" +checksum = "2a0b5487afeab2deb2ff4e03a807ad1a03ac532ff5a2cee5d86884440c7f7671" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "clap_lex" -version = "0.7.5" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" +checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" [[package]] name = "cmake" @@ -1121,6 +1177,26 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "compression-codecs" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "302266479cb963552d11bd042013a58ef1adc56768016c8b82b4199488f2d4ad" +dependencies = [ + "brotli", + "compression-core", + "flate2", + "memchr", + "zstd", + "zstd-safe", +] + +[[package]] +name = "compression-core" +version = "0.4.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75984efb6ed102a0d42db99afb6c1948f0380d1d91808d5529916e6c08b49d8d" + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -1167,9 +1243,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.4.2" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" dependencies = [ "cfg-if", ] @@ -1184,7 +1260,7 @@ dependencies = [ "cast", "ciborium", "clap", - "criterion-plot", + "criterion-plot 0.5.0", "futures", "is-terminal", "itertools 0.10.5", @@ -1204,18 +1280,20 @@ dependencies = [ [[package]] name = "criterion" -version = "0.6.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bf7af66b0989381bd0be551bd7cc91912a655a58c6918420c9527b1fd8b4679" +checksum = "a0dfe5e9e71bdcf4e4954f7d14da74d1cdb92a3a07686452d1509652684b1aab" dependencies = [ + "alloca", "anes", "cast", "ciborium", "clap", - "criterion-plot", + "criterion-plot 0.8.0", "itertools 0.13.0", "num-traits", "oorandom", + "page_size", "plotters", "rayon", "regex", @@ -1236,6 +1314,16 @@ dependencies = [ "itertools 0.10.5", ] +[[package]] +name = "criterion-plot" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5de36c2bee19fba779808f92bf5d9b0fa5a40095c277aba10c458a12b35d21d6" +dependencies = [ + "cast", + "itertools 0.13.0", +] + [[package]] name = "crossbeam" version = "0.8.4" @@ -1304,15 +1392,15 @@ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "crunchy" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43da5946c66ffcc7745f48db692ffbb10a83bfe0afd96235c5c2a4fb23994929" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "crypto-common" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", "typenum", @@ -1324,8 +1412,18 @@ version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" dependencies = [ - "darling_core", - "darling_macro", + "darling_core 0.20.11", + "darling_macro 0.20.11", +] + +[[package]] +name = "darling" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" +dependencies = [ + "darling_core 0.21.3", + "darling_macro 0.21.3", ] [[package]] @@ -1339,7 +1437,21 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.102", + "syn 2.0.111", +] + +[[package]] +name = "darling_core" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.111", ] [[package]] @@ -1348,9 +1460,20 @@ version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ - "darling_core", + "darling_core 0.20.11", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "darling_macro" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" +dependencies = [ + "darling_core 0.21.3", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -1369,12 +1492,12 @@ dependencies = [ [[package]] name = "deranged" -version = "0.4.0" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c9e6a11ca8224451684bc0d7d5a7adbf8f2fd6887261a1cfc3c0432f9d4068e" +checksum = "ececcb659e7ba858fb4f10388c250a7252eb0a27373f1a72b8748afdd248e587" dependencies = [ "powerfmt", - "serde", + "serde_core", ] [[package]] @@ -1394,7 +1517,7 @@ checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", "unicode-xid", ] @@ -1406,7 +1529,7 @@ checksum = "ccfae181bab5ab6c5478b2ccb69e4c68a02f8c3ec72f6616bfec9dbc599d2ee0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -1433,7 +1556,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -1453,6 +1576,12 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "either" version = "1.15.0" @@ -1486,23 +1615,22 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" -version = "0.3.12" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cea14ef9355e3beab063703aa9dab15afd25f0667c341310c1e5274bb1d0da18" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] name = "etcetera" -version = "0.10.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26c7b13d0780cb82722fd59f6f57f925e143427e4a75313a6c77243bf5326ae6" +checksum = "de48cc4d1c1d97a20fd819def54b890cadde72ed3ad0c614822a0a433361be96" dependencies = [ "cfg-if", - "home", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -1513,9 +1641,9 @@ checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" [[package]] name = "event-listener" -version = "5.4.0" +version = "5.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3492acde4c3fc54c845eaab3eed8bd00c7a7d881f78bfc801e43a93dec1331ae" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" dependencies = [ "concurrent-queue", "parking", @@ -1528,7 +1656,7 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" dependencies = [ - "event-listener 5.4.0", + "event-listener 5.4.1", "pin-project-lite", ] @@ -1550,6 +1678,17 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" +[[package]] +name = "ferroid" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0e9414a6ae93ef993ce40a1e02944f13d4508e2bf6f1ced1580ce6910f08253" +dependencies = [ + "portable-atomic", + "rand 0.9.2", + "web-time", +] + [[package]] name = "figment" version = "0.10.19" @@ -1561,28 +1700,34 @@ dependencies = [ "pear", "serde", "tempfile", - "toml", + "toml 0.8.23", "uncased", "version_check", ] [[package]] name = "filetime" -version = "0.2.25" +version = "0.2.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35c0522e981e68cbfa8c3f978441a5f34b30b96e146b33cd3359176b50fe8586" +checksum = "bc0505cd1b6fa6580283f6bdf70a73fcf4aba1184038c90902b92b3dd0df63ed" dependencies = [ "cfg-if", "libc", "libredox", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] +[[package]] +name = "find-msvc-tools" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844" + [[package]] name = "flate2" -version = "1.1.2" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a3d7db9596fecd151c5f638c0ee5d5bd487b6e0ea232e5dc96d5250f6f94b1d" +checksum = "bfe33edd8e85a12a67454e37f8c75e730830d83e313556ab9ebf9ee7fbeb3bfb" dependencies = [ "crc32fast", "libz-sys", @@ -1618,9 +1763,9 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] name = "form_urlencoded" -version = "1.2.1" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" dependencies = [ "percent-encoding", ] @@ -1653,9 +1798,9 @@ checksum = "28dd6caf6059519a65843af8fe2a3ae298b14b80179855aeb4adc2c1934ee619" [[package]] name = "frunk" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "874b6a17738fc273ec753618bac60ddaeac48cb1d7684c3e7bd472e57a28b817" +checksum = "28aef0f9aa070bce60767c12ba9cb41efeaf1a2bc6427f87b7d83f11239a16d7" dependencies = [ "frunk_core", "frunk_derives", @@ -1665,53 +1810,53 @@ dependencies = [ [[package]] name = "frunk_core" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3529a07095650187788833d585c219761114005d5976185760cf794d265b6a5c" +checksum = "476eeaa382e3462b84da5d6ba3da97b5786823c2d0d3a0d04ef088d073da225c" dependencies = [ "serde", ] [[package]] name = "frunk_derives" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e99b8b3c28ae0e84b604c75f721c21dc77afb3706076af5e8216d15fd1deaae3" +checksum = "a0b4095fc99e1d858e5b8c7125d2638372ec85aa0fe6c807105cf10b0265ca6c" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "frunk_proc_macro_helpers" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05a956ef36c377977e512e227dcad20f68c2786ac7a54dacece3746046fea5ce" +checksum = "1952b802269f2db12ab7c0bd328d0ae8feaabf19f352a7b0af7bb0c5693abfce" dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "frunk_proc_macros" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67e86c2c9183662713fea27ea527aad20fb15fee635a71081ff91bf93df4dc51" +checksum = "3462f590fa236005bd7ca4847f81438bd6fe0febd4d04e11968d4c2e96437e78" dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "fs-err" -version = "3.1.1" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88d7be93788013f265201256d58f04936a8079ad5dc898743aa20525f503b683" +checksum = "62d91fd049c123429b018c47887d3f75a265540dd3c30ba9cb7bae9197edb03a" dependencies = [ "autocfg", "tokio", @@ -1773,9 +1918,9 @@ checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" [[package]] name = "futures-lite" -version = "2.6.0" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5edaec856126859abb19ed65f39e90fea3a9574b9707f13539acf4abf7eb532" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" dependencies = [ "fastrand", "futures-core", @@ -1792,7 +1937,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -1849,32 +1994,32 @@ checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "libc", - "wasi 0.11.1+wasi-snapshot-preview1", + "wasi", ] [[package]] name = "getrandom" -version = "0.3.3" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", "libc", "r-efi", - "wasi 0.14.2+wasi-0.2.4", + "wasip2", ] [[package]] name = "gimli" -version = "0.31.1" +version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" +checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" [[package]] name = "glob" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" [[package]] name = "gloo-timers" @@ -1890,9 +2035,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.10" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9421a676d1b147b16b82c9225157dc629087ef8ec4d5e2960f9437a90dac0a5" +checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" dependencies = [ "atomic-waker", "bytes", @@ -1900,7 +2045,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.9.0", + "indexmap 2.12.1", "slab", "tokio", "tokio-util", @@ -1909,12 +2054,13 @@ dependencies = [ [[package]] name = "half" -version = "2.6.0" +version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "459196ed295495a68f7d7fe1d84f6c4b7ff0e21fe3017b2f283c6fac3ad803c9" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "cfg-if", "crunchy", + "zerocopy 0.8.31", ] [[package]] @@ -1934,22 +2080,28 @@ checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" [[package]] name = "hashbrown" -version = "0.15.4" +version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ "allocator-api2", "equivalent", "foldhash", ] +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + [[package]] name = "hashlink" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" dependencies = [ - "hashbrown 0.15.4", + "hashbrown 0.15.5", ] [[package]] @@ -1960,9 +2112,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hermit-abi" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f154ce46856750ed433c8649605bf7ed2de3bc35fd9d2a9f30cddd873c80cb08" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" [[package]] name = "hex" @@ -1972,27 +2124,26 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "hex-literal" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcaaec4551594c969335c98c903c1397853d4198408ea609190f420500f6be71" +checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1" [[package]] name = "home" -version = "0.5.11" +version = "0.5.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] name = "http" -version = "1.3.1" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" dependencies = [ "bytes", - "fnv", "itoa", ] @@ -2033,13 +2184,14 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.6.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc2b571658e38e0c01b1fdca3bbbe93c00d3d71693ff2770043f8c29bc7d6f80" +checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" dependencies = [ + "atomic-waker", "bytes", "futures-channel", - "futures-util", + "futures-core", "h2", "http", "http-body", @@ -2047,6 +2199,7 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", + "pin-utils", "smallvec", "tokio", "want", @@ -2083,6 +2236,19 @@ dependencies = [ "tower-service", ] +[[package]] +name = "hyper-timeout" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" +dependencies = [ + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", +] + [[package]] name = "hyper-tls" version = "0.6.0" @@ -2101,9 +2267,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.14" +version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc2fdfdbff08affe55bb779f33b053aa1fe5dd5b54c257343c17edfa55711bdb" +checksum = "52e9a2a24dc5c6821e71a7030e1e14b7b632acac55c40e9d2e082c621261bb56" dependencies = [ "base64 0.22.1", "bytes", @@ -2117,7 +2283,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2", + "socket2 0.6.1", "system-configuration", "tokio", "tower-service", @@ -2142,9 +2308,9 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.63" +version = "0.1.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0c919e5debc312ad217002b8048a17b7d83f80703865bbfcfebb0458b0b27d8" +checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -2166,9 +2332,9 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.0.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" dependencies = [ "displaydoc", "potential_utf", @@ -2179,9 +2345,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.0.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cde2700ccaed3872079a65fb1a78f6c0a36c91570f28755dda67bc8f7d9f00a" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" dependencies = [ "displaydoc", "litemap", @@ -2192,11 +2358,10 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.0.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "436880e8e18df4d7bbc06d58432329d6458cc84531f7ac5f024e93deadb37979" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" dependencies = [ - "displaydoc", "icu_collections", "icu_normalizer_data", "icu_properties", @@ -2207,42 +2372,38 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.0.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" [[package]] name = "icu_properties" -version = "2.0.1" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "016c619c1eeb94efb86809b015c58f479963de65bdb6253345c1a1276f22e32b" +checksum = "e93fcd3157766c0c8da2f8cff6ce651a31f0810eaa1c51ec363ef790bbb5fb99" dependencies = [ - "displaydoc", "icu_collections", "icu_locale_core", "icu_properties_data", "icu_provider", - "potential_utf", "zerotrie", "zerovec", ] [[package]] name = "icu_properties_data" -version = "2.0.1" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "298459143998310acd25ffe6810ed544932242d3f07083eee1084d83a71bd632" +checksum = "02845b3647bb045f1100ecd6480ff52f34c35f82d9880e029d329c21d1054899" [[package]] name = "icu_provider" -version = "2.0.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03c80da27b5f4187909049ee2d72f276f0d9f99a42c306bd0131ecfe04d8e5af" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" dependencies = [ "displaydoc", "icu_locale_core", - "stable_deref_trait", - "tinystr", "writeable", "yoke", "zerofrom", @@ -2258,9 +2419,9 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "idna" -version = "1.0.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" dependencies = [ "idna_adapter", "smallvec", @@ -2290,13 +2451,14 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.9.0" +version = "2.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e" +checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2" dependencies = [ "equivalent", - "hashbrown 0.15.4", + "hashbrown 0.16.1", "serde", + "serde_core", ] [[package]] @@ -2331,9 +2493,9 @@ checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" [[package]] name = "iri-string" -version = "0.7.8" +version = "0.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2" +checksum = "4f867b9d1d896b67beb18518eda36fdb77a32ea590de864f1325b294a6d14397" dependencies = [ "memchr", "serde", @@ -2341,13 +2503,13 @@ dependencies = [ [[package]] name = "is-terminal" -version = "0.4.16" +version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9" +checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -2358,9 +2520,9 @@ checksum = "7655c9839580ee829dfacba1d1278c2b7883e50a277ff7541299489d6bdfdc45" [[package]] name = "is_terminal_polyfill" -version = "1.70.1" +version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "itertools" @@ -2381,26 +2543,35 @@ dependencies = [ ] [[package]] -name = "itoa" -version = "1.0.15" +name = "itertools" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "jobserver" -version = "0.1.33" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38f262f097c174adebe41eb73d66ae9c06b2844fb0da69969647bbddd9b0538a" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" dependencies = [ - "getrandom 0.3.3", + "getrandom 0.3.4", "libc", ] [[package]] name = "js-sys" -version = "0.3.77" +version = "0.3.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" +checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8" dependencies = [ "once_cell", "wasm-bindgen", @@ -2423,18 +2594,18 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.172" +version = "0.2.177" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" +checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" [[package]] name = "libloading" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" dependencies = [ "cfg-if", - "windows-targets 0.53.0", + "windows-link", ] [[package]] @@ -2445,20 +2616,20 @@ checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" [[package]] name = "libredox" -version = "0.1.3" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" +checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb" dependencies = [ - "bitflags 2.9.1", + "bitflags", "libc", - "redox_syscall 0.5.12", + "redox_syscall", ] [[package]] name = "libsqlite3-sys" -version = "0.34.0" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15" +checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f" dependencies = [ "cc", "pkg-config", @@ -2467,9 +2638,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.22" +version = "1.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b70e7a7df205e92a1a4cd9aaae7898dac0aa555503cc0a649494d0d60e7651d" +checksum = "15d118bbf3771060e7311cc7bb0545b01d08a8b4a7de949198dec1fa0ca1c0f7" dependencies = [ "cc", "pkg-config", @@ -2478,15 +2649,15 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.9.4" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" +checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" [[package]] name = "litemap" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956" +checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" [[package]] name = "local-ip-address" @@ -2496,25 +2667,24 @@ checksum = "656b3b27f8893f7bbf9485148ff9a65f019e3f33bd5cdc87c83cab16b3fd9ec8" dependencies = [ "libc", "neli", - "thiserror 2.0.12", + "thiserror 2.0.17", "windows-sys 0.59.0", ] [[package]] name = "lock_api" -version = "0.4.13" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" dependencies = [ - "autocfg", "scopeguard", ] [[package]] name = "log" -version = "0.4.27" +version = "0.4.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" +checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" dependencies = [ "value-bag", ] @@ -2525,7 +2695,7 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" dependencies = [ - "hashbrown 0.15.4", + "hashbrown 0.15.5", ] [[package]] @@ -2536,9 +2706,9 @@ checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" [[package]] name = "memchr" -version = "2.7.4" +version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" [[package]] name = "miette" @@ -2567,7 +2737,7 @@ checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -2589,24 +2759,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", + "simd-adler32", ] [[package]] name = "mio" -version = "1.0.4" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c" +checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873" dependencies = [ "libc", - "wasi 0.11.1+wasi-snapshot-preview1", - "windows-sys 0.59.0", + "wasi", + "windows-sys 0.61.2", ] [[package]] name = "mockall" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39a6bfcc6c8c7eed5ee98b9c3e33adc726054389233e201c95dab2d41a3839d2" +checksum = "f58d964098a5f9c6b63d0798e5372fd04708193510a7af313c22e9f29b7b620b" dependencies = [ "cfg-if", "downcast", @@ -2618,14 +2789,14 @@ dependencies = [ [[package]] name = "mockall_derive" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25ca3004c2efe9011bd4e461bd8256445052b9615405b4f7ea43fc8ca5c20898" +checksum = "ca41ce716dda6a9be188b385aa78ee5260fc25cd3802cb2a8afdc6afbe6b6dbf" dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -2657,7 +2828,7 @@ dependencies = [ "percent-encoding", "serde", "serde_json", - "socket2", + "socket2 0.5.10", "twox-hash", "url", ] @@ -2668,14 +2839,14 @@ version = "0.31.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63c3512cf11487168e0e9db7157801bf5273be13055a9cc95356dc9e0035e49c" dependencies = [ - "darling", + "darling 0.20.11", "heck", "num-bigint", "proc-macro-crate", "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", "termcolor", "thiserror 1.0.69", ] @@ -2689,7 +2860,7 @@ dependencies = [ "base64 0.21.7", "bigdecimal", "bindgen", - "bitflags 2.9.1", + "bitflags", "bitvec", "btoi", "byteorder", @@ -2788,12 +2959,25 @@ checksum = "e9e591e719385e6ebaeb5ce5d3887f7d5676fceca6411d1925ccc95745f3d6f7" [[package]] name = "nu-ansi-term" -version = "0.46.0" +version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "overload", - "winapi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", ] [[package]] @@ -2806,6 +2990,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + [[package]] name = "num-conv" version = "0.1.0" @@ -2821,6 +3014,28 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2832,9 +3047,9 @@ dependencies = [ [[package]] name = "object" -version = "0.36.7" +version = "0.37.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" +checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" dependencies = [ "memchr", ] @@ -2847,9 +3062,9 @@ checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] name = "once_cell_polyfill" -version = "1.70.1" +version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] name = "oorandom" @@ -2859,11 +3074,11 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "openssl" -version = "0.10.73" +version = "0.10.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8505734d46c8ab1e19a1dce3aef597ad87dcb4c37e7188231769bd6bd51cebf8" +checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328" dependencies = [ - "bitflags 2.9.1", + "bitflags", "cfg-if", "foreign-types", "libc", @@ -2880,7 +3095,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -2891,9 +3106,9 @@ checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" [[package]] name = "openssl-sys" -version = "0.9.109" +version = "0.9.111" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90096e2e47630d78b7d1c20952dc621f957103f8bc2c8359ec81290d75238571" +checksum = "82cab2d520aa75e3c58898289429321eb788c3106963d0dc886ec7a5f4adc321" dependencies = [ "cc", "libc", @@ -2902,16 +3117,20 @@ dependencies = [ ] [[package]] -name = "overload" -version = "0.1.1" +name = "owo-colors" +version = "4.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" +checksum = "9c6901729fa79e91a0913333229e9ca5dc725089d1c363b2f4b4760709dc4a52" [[package]] -name = "owo-colors" -version = "4.2.1" +name = "page_size" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26995317201fa17f3656c36716aed4a7c81743a9634ac4c99c0eeda495db0cec" +checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da" +dependencies = [ + "libc", + "winapi", +] [[package]] name = "parking" @@ -2921,9 +3140,9 @@ checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" [[package]] name = "parking_lot" -version = "0.12.4" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ "lock_api", "parking_lot_core", @@ -2931,15 +3150,15 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.11" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.12", + "redox_syscall", "smallvec", - "windows-targets 0.52.6", + "windows-link", ] [[package]] @@ -2964,7 +3183,7 @@ dependencies = [ "regex", "regex-syntax", "structmeta", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -2987,24 +3206,24 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "pem" -version = "3.0.5" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38af38e8470ac9dee3ce1bae1af9c1671fffc44ddfd8bd1d0a3445bf349a8ef3" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" dependencies = [ "base64 0.22.1", - "serde", + "serde_core", ] [[package]] name = "percent-encoding" -version = "2.3.1" +version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "phf" @@ -3044,6 +3263,26 @@ dependencies = [ "siphasher", ] +[[package]] +name = "pin-project" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + [[package]] name = "pin-project-lite" version = "0.2.16" @@ -3103,17 +3342,16 @@ dependencies = [ [[package]] name = "polling" -version = "3.8.0" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b53a684391ad002dd6a596ceb6c74fd004fdce75f4be2e3f615068abbea5fd50" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" dependencies = [ "cfg-if", "concurrent-queue", "hermit-abi", "pin-project-lite", "rustix", - "tracing", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -3133,9 +3371,9 @@ dependencies = [ [[package]] name = "potential_utf" -version = "0.1.2" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5a7c30837279ca13e7c867e9e40053bc68740f988cb07f7ca6df43cc734b585" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" dependencies = [ "zerovec", ] @@ -3152,7 +3390,7 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ - "zerocopy 0.8.25", + "zerocopy 0.8.31", ] [[package]] @@ -3193,11 +3431,11 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "3.3.0" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edce586971a4dfaa28950c6f18ed55e0406c1ab88bbce2c6f6293a7aaba73d35" +checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983" dependencies = [ - "toml_edit", + "toml_edit 0.23.7", ] [[package]] @@ -3219,14 +3457,14 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "proc-macro2" -version = "1.0.95" +version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" +checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" dependencies = [ "unicode-ident", ] @@ -3239,11 +3477,43 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", "version_check", "yansi", ] +[[package]] +name = "prost" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "101fec8d036f8d9d4a1e8ebf90d566d1d798f3b1aa379d2576a54a0d9acea5bd" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2d93e596a829ebe00afa41c3a056e6308d6b8a4c7d869edf184e2c91b1ba564" +dependencies = [ + "anyhow", + "itertools 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "prost-types" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5d7b7346e150de32340ae3390b8b3ffa37ad93ec31fb5dad86afe817619e4e7" +dependencies = [ + "prost", +] + [[package]] name = "ptr_meta" version = "0.1.4" @@ -3277,18 +3547,18 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.40" +version = "1.0.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f" dependencies = [ "proc-macro2", ] [[package]] name = "r-efi" -version = "5.2.0" +version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] name = "r2d2" @@ -3313,9 +3583,9 @@ dependencies = [ [[package]] name = "r2d2_sqlite" -version = "0.29.0" +version = "0.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35006423374afbd4b270acddcbf1e28e60f6bdaaad10c2888b8fd2fba035213c" +checksum = "63417e83dc891797eea3ad379f52a5986da4bca0d6ef28baf4d14034dd111b0c" dependencies = [ "r2d2", "rusqlite", @@ -3341,9 +3611,9 @@ dependencies = [ [[package]] name = "rand" -version = "0.9.1" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.3", @@ -3384,14 +3654,14 @@ version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ - "getrandom 0.3.3", + "getrandom 0.3.4", ] [[package]] name = "rayon" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" +checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" dependencies = [ "either", "rayon-core", @@ -3399,9 +3669,9 @@ dependencies = [ [[package]] name = "rayon-core" -version = "1.12.1" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" dependencies = [ "crossbeam-deque", "crossbeam-utils", @@ -3409,27 +3679,38 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.3.5" +version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 1.3.2", + "bitflags", ] [[package]] -name = "redox_syscall" -version = "0.5.12" +name = "ref-cast" +version = "1.0.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "928fca9cf2aa042393a8325b9ead81d2f0df4cb12e1e24cef072922ccd99c5af" +checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" dependencies = [ - "bitflags 2.9.1", + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", ] [[package]] name = "regex" -version = "1.11.1" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" +checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" dependencies = [ "aho-corasick", "memchr", @@ -3439,9 +3720,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.9" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" dependencies = [ "aho-corasick", "memchr", @@ -3450,9 +3731,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.5" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" +checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" [[package]] name = "relative-path" @@ -3471,9 +3752,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.20" +version = "0.12.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eabf4c97d9130e2bf606614eb937e86edac8292eaa6f422f995d7e8de1eb1813" +checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f" dependencies = [ "base64 0.22.1", "bytes", @@ -3571,10 +3852,21 @@ checksum = "6fc39292f8613e913f7df8fa892b8944ceb47c247b78e1b1ae2f09e019be789d" dependencies = [ "futures-timer", "futures-util", - "rstest_macros", + "rstest_macros 0.25.0", "rustc_version", ] +[[package]] +name = "rstest" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5a3193c063baaa2a95a33f03035c8a72b83d97a54916055ba22d35ed3839d49" +dependencies = [ + "futures-timer", + "futures-util", + "rstest_macros 0.26.1", +] + [[package]] name = "rstest_macros" version = "0.25.0" @@ -3589,17 +3881,35 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.102", + "syn 2.0.111", + "unicode-ident", +] + +[[package]] +name = "rstest_macros" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c845311f0ff7951c5506121a9ad75aec44d083c31583b2ea5a30bcb0b0abba0" +dependencies = [ + "cfg-if", + "glob", + "proc-macro-crate", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version", + "syn 2.0.111", "unicode-ident", ] [[package]] name = "rusqlite" -version = "0.36.0" +version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3de23c3319433716cf134eed225fe9986bc24f63bed9be9f20c329029e672dc7" +checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" dependencies = [ - "bitflags 2.9.1", + "bitflags", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -3609,9 +3919,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.37.1" +version = "1.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faa7de2ba56ac291bd90c6b9bece784a52ae1411f9506544b3eae36dd2356d50" +checksum = "35affe401787a9bd846712274d97654355d21b2a2c092a3139aabe31e9022282" dependencies = [ "arrayvec", "borsh", @@ -3625,9 +3935,9 @@ dependencies = [ [[package]] name = "rustc-demangle" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f" +checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" [[package]] name = "rustc-hash" @@ -3646,23 +3956,24 @@ dependencies = [ [[package]] name = "rustix" -version = "1.0.7" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266" +checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" dependencies = [ - "bitflags 2.9.1", + "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] name = "rustls" -version = "0.23.27" +version = "0.23.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "730944ca083c1c233a75c09f199e973ca499344a2b7ba9e755c457e86fb4a321" +checksum = "533f54bc6a7d4f647e46ad909549eda97bf5afc1585190ef692b4286b198bd8f" dependencies = [ + "log", "once_cell", "ring", "rustls-pki-types", @@ -3673,14 +3984,14 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcff2dd52b58a8d98a70243663a0d234c4e2b79235637849d15913394a247d3" +checksum = "9980d917ebb0c0536119ba501e90834767bffc3d60641457fd84a1f3fd337923" dependencies = [ "openssl-probe", "rustls-pki-types", "schannel", - "security-framework 3.2.0", + "security-framework 3.5.1", ] [[package]] @@ -3694,18 +4005,18 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.12.0" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "229a4a4c221013e7e1f1a043678c5cc39fe5171437c88fb47151a21e6f5b5c79" +checksum = "708c0f9d5f54ba0272468c1d306a52c495b31fa155e91bc25371e6df7996908c" dependencies = [ "zeroize", ] [[package]] name = "rustls-webpki" -version = "0.103.3" +version = "0.103.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4a72fe2bcf7a6ac6fd7d0b9e5cb68aeb7d4c0a0271730218b3e92d43b4eb435" +checksum = "2ffdfa2f5286e2247234e03f680868ac2815974dc39e00ea15adc445d0aafe52" dependencies = [ "ring", "rustls-pki-types", @@ -3714,9 +4025,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.21" +version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a0d197bd2c9dc6e53b84da9556a69ba4cdfab8619eb41a8bd1cc2027a0f6b1d" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "ryu" @@ -3741,11 +4052,11 @@ checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" [[package]] name = "schannel" -version = "0.1.27" +version = "0.1.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f29ebaa345f945cec9fbbc532eb307f0fdad8161f281b6369539c8d84876b3d" +checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -3757,6 +4068,30 @@ dependencies = [ "parking_lot", ] +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9558e172d4e8533736ba97870c4b2cd63f84b382a3d6eb063da41b91cce17289" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -3775,7 +4110,7 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" dependencies = [ - "bitflags 2.9.1", + "bitflags", "core-foundation 0.9.4", "core-foundation-sys", "libc", @@ -3784,11 +4119,11 @@ dependencies = [ [[package]] name = "security-framework" -version = "3.2.0" +version = "3.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "271720403f46ca04f7ba6f55d438f8bd878d6b8ca0a1046e8228c4145bcbb316" +checksum = "b3297343eaf830f66ede390ea39da1d462b6b0c1b000f420d0a83f898bbbe6ef" dependencies = [ - "bitflags 2.9.1", + "bitflags", "core-foundation 0.10.1", "core-foundation-sys", "libc", @@ -3797,9 +4132,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.14.0" +version = "2.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49db231d56a190491cb4aeda9527f1ad45345af50b0851622a7adb8c03b01c32" +checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0" dependencies = [ "core-foundation-sys", "libc", @@ -3807,16 +4142,17 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.26" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56e6fa9c48d24d85fb3de5ad847117517440f6beceb7798af16b4a87d616b8d0" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" [[package]] name = "serde" -version = "1.0.219" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ + "serde_core", "serde_derive", ] @@ -3832,58 +4168,70 @@ dependencies = [ [[package]] name = "serde_bytes" -version = "0.11.17" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8437fd221bde2d4ca316d61b90e337e9e702b3820b87d63caa9ba6c02bd06d96" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" dependencies = [ "serde", + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.219" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "serde_html_form" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d2de91cf02bbc07cde38891769ccd5d4f073d22a40683aa4bc7a95781aaa2c4" +checksum = "b2f2d7ff8a2140333718bb329f5c40fc5f0865b84c426183ce14c97d2ab8154f" dependencies = [ "form_urlencoded", - "indexmap 2.9.0", + "indexmap 2.12.1", "itoa", "ryu", - "serde", + "serde_core", ] [[package]] name = "serde_json" -version = "1.0.140" +version = "1.0.145" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" +checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" dependencies = [ - "indexmap 2.9.0", + "indexmap 2.12.1", "itoa", "memchr", "ryu", "serde", + "serde_core", ] [[package]] name = "serde_path_to_error" -version = "0.1.17" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59fab13f937fa393d08645bf3a84bdfe86e296747b506ada67bb15f10f218b2a" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" dependencies = [ "itoa", "serde", + "serde_core", ] [[package]] @@ -3894,7 +4242,7 @@ checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -3906,6 +4254,15 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_spanned" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e24345aa0fe688594e73770a5f6d1b216508b4f93484c0026d521acd30134392" +dependencies = [ + "serde_core", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -3920,17 +4277,18 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.12.0" +version = "3.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6b6f7f2fcb69f747921f79f3926bd1e203fce4fef62c268dd3abfb6d86029aa" +checksum = "4fa237f2807440d238e0364a218270b98f767a00d3dada77b1c53ae88940e2e7" dependencies = [ "base64 0.22.1", "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.9.0", - "serde", - "serde_derive", + "indexmap 2.12.1", + "schemars 0.9.0", + "schemars 1.1.0", + "serde_core", "serde_json", "serde_with_macros", "time", @@ -3938,14 +4296,14 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.12.0" +version = "3.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d00caa5193a3c8362ac2b73be6b9e768aa5a4b2f721d8f4b339600c3cb51f8e" +checksum = "52a8e3ca0ca629121f70ab50f95249e5a6f925cc0f6ffe8256c45b728875706c" dependencies = [ - "darling", + "darling 0.21.3", "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -3987,13 +4345,19 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "signal-hook-registry" -version = "1.4.5" +version = "1.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410" +checksum = "7664a098b8e616bdfcc2dc0e9ac44eb231eedf41db4e9fe95d8d32ec728dedad" dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" + [[package]] name = "simdutf8" version = "0.1.5" @@ -4008,12 +4372,9 @@ checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" [[package]] name = "slab" -version = "0.4.9" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" -dependencies = [ - "autocfg", -] +checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" [[package]] name = "smallvec" @@ -4031,11 +4392,21 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "socket2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881" +dependencies = [ + "libc", + "windows-sys 0.60.2", +] + [[package]] name = "stable_deref_trait" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "static_assertions" @@ -4058,7 +4429,7 @@ dependencies = [ "proc-macro2", "quote", "structmeta-derive", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -4069,7 +4440,7 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -4122,9 +4493,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.102" +version = "2.0.111" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6397daf94fa90f058bd0fd88429dd9e5738999cca8d701813c80723add80462" +checksum = "390cc9a294ab71bdb1aa2e99d13be9c753cd2d7bd6560c77118597410c4d2e87" dependencies = [ "proc-macro2", "quote", @@ -4148,7 +4519,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -4157,7 +4528,7 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" dependencies = [ - "bitflags 2.9.1", + "bitflags", "core-foundation 0.9.4", "system-configuration-sys", ] @@ -4197,15 +4568,15 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.20.0" +version = "3.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1" +checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16" dependencies = [ "fastrand", - "getrandom 0.3.3", + "getrandom 0.3.4", "once_cell", "rustix", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -4219,12 +4590,12 @@ dependencies = [ [[package]] name = "terminal_size" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45c6481c4829e4cc63825e62c49186a34538b7b2750b73b266581ffb612fb5ed" +checksum = "60b8cb979cb11c32ce1603f8137b22262a9d131aaa5c37b5678025f22b8becd0" dependencies = [ "rustix", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -4235,18 +4606,20 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "testcontainers" -version = "0.24.0" +version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23bb7577dca13ad86a78e8271ef5d322f37229ec83b8d98da6d996c588a1ddb1" +checksum = "a347cac4368ba4f1871743adb27dc14829024d26b1763572404726b0b9943eb8" dependencies = [ + "astral-tokio-tar", "async-trait", "bollard", - "bollard-stubs", "bytes", "docker_credential", "either", "etcetera", + "ferroid", "futures", + "itertools 0.14.0", "log", "memchr", "parse-display", @@ -4254,10 +4627,9 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "tokio-stream", - "tokio-tar", "tokio-util", "url", ] @@ -4269,7 +4641,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057" dependencies = [ "unicode-linebreak", - "unicode-width 0.2.1", + "unicode-width 0.2.2", ] [[package]] @@ -4283,11 +4655,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.12" +version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708" +checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" dependencies = [ - "thiserror-impl 2.0.12", + "thiserror-impl 2.0.17", ] [[package]] @@ -4298,35 +4670,34 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "thiserror-impl" -version = "2.0.12" +version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" +checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "thread_local" -version = "1.1.8" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" dependencies = [ "cfg-if", - "once_cell", ] [[package]] name = "time" -version = "0.3.41" +version = "0.3.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7619e19bc266e0f9c5e6686659d394bc57973859340060a69221e57dbc0c40" +checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d" dependencies = [ "deranged", "itoa", @@ -4339,15 +4710,15 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.4" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9e9a38711f559d9e3ce1cdb06dd7c5b8ea546bc90052da6d06bb76da74bb07c" +checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b" [[package]] name = "time-macros" -version = "0.2.22" +version = "0.2.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3526739392ec93fd8b359c8e98514cb3e8e021beb4e5f597b00a0221f8ed8a49" +checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3" dependencies = [ "num-conv", "time-core", @@ -4355,9 +4726,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d4f6d1145dcb577acf783d4e601bc1d76a13337bb54e6233add580b07344c8b" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" dependencies = [ "displaydoc", "zerovec", @@ -4375,9 +4746,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09b3661f17e86524eccd4371ab0429194e0d7c008abb45f7a7495b1719463c71" +checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" dependencies = [ "tinyvec_macros", ] @@ -4390,30 +4761,29 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.45.1" +version = "1.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75ef51a33ef1da925cea3e4eb122833cb377c61439ca401b770f54902b806779" +checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" dependencies = [ - "backtrace", "bytes", "libc", "mio", "pin-project-lite", "signal-hook-registry", - "socket2", + "socket2 0.6.1", "tokio-macros", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] name = "tokio-macros" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" +checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -4428,9 +4798,9 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.26.2" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e727b36a1a0e8b74c376ac2211e40c2c8af09fb4013c60d910495810f008e9b" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" dependencies = [ "rustls", "tokio", @@ -4447,26 +4817,11 @@ dependencies = [ "tokio", ] -[[package]] -name = "tokio-tar" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d5714c010ca3e5c27114c1cdeb9d14641ace49874aa5626d7149e47aedace75" -dependencies = [ - "filetime", - "futures-core", - "libc", - "redox_syscall 0.3.5", - "tokio", - "tokio-stream", - "xattr", -] - [[package]] name = "tokio-util" -version = "0.7.15" +version = "0.7.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66a539a9ad6d5d281510d5bd368c973d636c02dbf8a67300bfb6b950696ad7df" +checksum = "2efa149fe76073d6e8fd97ef4f4eca7b67f599660115591483572e406e165594" dependencies = [ "bytes", "futures-core", @@ -4482,9 +4837,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" dependencies = [ "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", + "toml_edit 0.22.27", +] + +[[package]] +name = "toml" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0dc8b1fb61449e27716ec0e1bdf0f6b8f3e8f6b05391e8497b8b6d7804ea6d8" +dependencies = [ + "indexmap 2.12.1", + "serde_core", + "serde_spanned 1.0.3", + "toml_datetime 0.7.3", + "toml_parser", + "toml_writer", + "winnow", ] [[package]] @@ -4496,26 +4866,102 @@ dependencies = [ "serde", ] +[[package]] +name = "toml_datetime" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2cdb639ebbc97961c51720f858597f7f24c4fc295327923af55b74c3c724533" +dependencies = [ + "serde_core", +] + [[package]] name = "toml_edit" version = "0.22.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ - "indexmap 2.9.0", + "indexmap 2.12.1", "serde", - "serde_spanned", - "toml_datetime", + "serde_spanned 0.6.9", + "toml_datetime 0.6.11", "toml_write", "winnow", ] +[[package]] +name = "toml_edit" +version = "0.23.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6485ef6d0d9b5d0ec17244ff7eb05310113c3f316f2d14200d4de56b3cb98f8d" +dependencies = [ + "indexmap 2.12.1", + "toml_datetime 0.7.3", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0cbe268d35bdb4bb5a56a2de88d0ad0eb70af5384a99d648cd4b3d04039800e" +dependencies = [ + "winnow", +] + [[package]] name = "toml_write" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" +[[package]] +name = "toml_writer" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8b2b54733674ad286d16267dcfc7a71ed5c776e4ac7aa3c3e2561f7c637bf2" + +[[package]] +name = "tonic" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb7613188ce9f7df5bfe185db26c5814347d110db17920415cf2fbcad85e7203" +dependencies = [ + "async-trait", + "axum", + "base64 0.22.1", + "bytes", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-timeout", + "hyper-util", + "percent-encoding", + "pin-project", + "socket2 0.6.1", + "sync_wrapper", + "tokio", + "tokio-stream", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tonic-prost" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66bd50ad6ce1252d87ef024b3d64fe4c3cf54a86fb9ef4c631fdd0ded7aeaa67" +dependencies = [ + "bytes", + "prost", + "tonic", +] + [[package]] name = "torrust-axum-health-check-api-server" version = "3.0.0-develop" @@ -4561,7 +5007,7 @@ dependencies = [ "hyper", "local-ip-address", "percent-encoding", - "rand 0.9.1", + "rand 0.9.2", "reqwest", "serde", "serde_bencode", @@ -4605,7 +5051,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "torrust-axum-server", "torrust-rest-tracker-api-client", @@ -4636,7 +5082,7 @@ dependencies = [ "hyper", "hyper-util", "pin-project-lite", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "torrust-server-lib", "torrust-tracker-configuration", @@ -4652,7 +5098,7 @@ dependencies = [ "hyper", "reqwest", "serde", - "thiserror 2.0.12", + "thiserror 2.0.17", "url", "uuid", ] @@ -4680,7 +5126,7 @@ name = "torrust-server-lib" version = "3.0.0-develop" dependencies = [ "derive_more", - "rstest", + "rstest 0.25.0", "tokio", "torrust-tracker-primitives", "tower-http", @@ -4702,12 +5148,12 @@ dependencies = [ "clap", "local-ip-address", "mockall", - "rand 0.9.1", + "rand 0.9.2", "regex", "reqwest", "serde", "serde_json", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "tokio-util", "torrust-axum-health-check-api-server", @@ -4743,7 +5189,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_json", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "torrust-tracker-configuration", "tracing", @@ -4771,8 +5217,8 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.12", - "toml", + "thiserror 2.0.17", + "toml 0.9.8", "torrust-tracker-located-error", "tracing", "tracing-subscriber", @@ -4784,8 +5230,8 @@ dependencies = [ name = "torrust-tracker-contrib-bencode" version = "3.0.0-develop" dependencies = [ - "criterion 0.6.0", - "thiserror 2.0.12", + "criterion 0.8.0", + "thiserror 2.0.17", ] [[package]] @@ -4801,7 +5247,7 @@ dependencies = [ name = "torrust-tracker-located-error" version = "3.0.0-develop" dependencies = [ - "thiserror 2.0.12", + "thiserror 2.0.17", "tracing", ] @@ -4814,10 +5260,10 @@ dependencies = [ "derive_more", "formatjson", "pretty_assertions", - "rstest", + "rstest 0.25.0", "serde", "serde_json", - "thiserror 2.0.12", + "thiserror 2.0.17", "torrust-tracker-primitives", "tracing", ] @@ -4830,11 +5276,11 @@ dependencies = [ "binascii", "bittorrent-primitives", "derive_more", - "rstest", + "rstest 0.25.0", "serde", "tdyne-peer-id", "tdyne-peer-id-registry", - "thiserror 2.0.12", + "thiserror 2.0.17", "torrust-tracker-configuration", "url", "zerocopy 0.7.35", @@ -4848,14 +5294,14 @@ dependencies = [ "async-std", "bittorrent-primitives", "chrono", - "criterion 0.6.0", + "criterion 0.8.0", "crossbeam-skiplist", "futures", "mockall", - "rand 0.9.1", - "rstest", + "rand 0.9.2", + "rstest 0.26.1", "serde", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "tokio-util", "torrust-tracker-clock", @@ -4871,7 +5317,7 @@ dependencies = [ name = "torrust-tracker-test-helpers" version = "3.0.0-develop" dependencies = [ - "rand 0.9.1", + "rand 0.9.2", "torrust-tracker-configuration", "tracing", "tracing-subscriber", @@ -4884,12 +5330,12 @@ dependencies = [ "aquatic_udp_protocol", "async-std", "bittorrent-primitives", - "criterion 0.6.0", + "criterion 0.8.0", "crossbeam-skiplist", "dashmap", "futures", "parking_lot", - "rstest", + "rstest 0.26.1", "tokio", "torrust-tracker-clock", "torrust-tracker-configuration", @@ -4911,10 +5357,10 @@ dependencies = [ "futures-util", "local-ip-address", "mockall", - "rand 0.9.1", + "rand 0.9.2", "ringbuf", "serde", - "thiserror 2.0.12", + "thiserror 2.0.17", "tokio", "tokio-util", "torrust-server-lib", @@ -4939,9 +5385,12 @@ checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" dependencies = [ "futures-core", "futures-util", + "indexmap 2.12.1", "pin-project-lite", + "slab", "sync_wrapper", "tokio", + "tokio-util", "tower-layer", "tower-service", "tracing", @@ -4949,12 +5398,12 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.6" +version = "0.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2" +checksum = "9cf146f99d442e8e68e585f5d798ccd3cad9a7835b917e09728880a862706456" dependencies = [ "async-compression", - "bitflags 2.9.1", + "bitflags", "bytes", "futures-core", "futures-util", @@ -4985,9 +5434,9 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tracing" -version = "0.1.41" +version = "0.1.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" +checksum = "2d15d90a0b5c19378952d479dc858407149d7bb45a14de0142f6c534b16fc647" dependencies = [ "log", "pin-project-lite", @@ -4997,20 +5446,20 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.29" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b1ffbcf9c6f6b99d386e7444eb608ba646ae452a36b39737deb9663b610f662" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "tracing-core" -version = "0.1.34" +version = "0.1.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" +checksum = "7a04e24fab5c89c6a36eb8558c9656f30d81de51dfa4d3b45f26b21d61fa0a6c" dependencies = [ "once_cell", "valuable", @@ -5039,9 +5488,9 @@ dependencies = [ [[package]] name = "tracing-subscriber" -version = "0.3.19" +version = "0.3.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008" +checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e" dependencies = [ "nu-ansi-term", "serde", @@ -5073,9 +5522,9 @@ dependencies = [ [[package]] name = "typenum" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" [[package]] name = "uncased" @@ -5088,9 +5537,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.18" +version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" +checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" [[package]] name = "unicode-linebreak" @@ -5106,9 +5555,9 @@ checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "unicode-width" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a1a07cc7db3810833284e8d372ccdc6da29741639ecc70c9ec107df0fa6154c" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" [[package]] name = "unicode-xid" @@ -5122,11 +5571,39 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" +[[package]] +name = "ureq" +version = "3.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d39cb1dbab692d82a977c0392ffac19e188bd9186a9f32806f0aaa859d75585a" +dependencies = [ + "base64 0.22.1", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf-8", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d81f9efa9df032be5934a46a068815a10a042b494b6a58cb0a1a97bb5467ed6f" +dependencies = [ + "base64 0.22.1", + "http", + "httparse", + "log", +] + [[package]] name = "url" -version = "2.5.4" +version = "2.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60" +checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" dependencies = [ "form_urlencoded", "idna", @@ -5134,6 +5611,12 @@ dependencies = [ "serde", ] +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -5148,13 +5631,13 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.17.0" +version = "1.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cf4199d1e5d15ddd86a694e4d0dffa9c323ce759fea589f00fef9d81cc1931d" +checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" dependencies = [ - "getrandom 0.3.3", + "getrandom 0.3.4", "js-sys", - "rand 0.9.1", + "rand 0.9.2", "wasm-bindgen", ] @@ -5166,9 +5649,9 @@ checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" [[package]] name = "value-bag" -version = "1.11.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "943ce29a8a743eb10d6082545d861b24f9d1b160b7d741e0f2cdf726bec909c5" +checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0" [[package]] name = "vcpkg" @@ -5208,45 +5691,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] -name = "wasi" -version = "0.14.2+wasi-0.2.4" +name = "wasip2" +version = "1.0.1+wasi-0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" dependencies = [ - "wit-bindgen-rt", + "wit-bindgen", ] [[package]] name = "wasm-bindgen" -version = "0.2.100" +version = "0.2.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" +checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" dependencies = [ "cfg-if", "once_cell", "rustversion", "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.100" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" -dependencies = [ - "bumpalo", - "log", - "proc-macro2", - "quote", - "syn 2.0.102", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.50" +version = "0.4.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61" +checksum = "836d9622d604feee9e5de25ac10e3ea5f2d65b41eac0d9ce72eb5deae707ce7c" dependencies = [ "cfg-if", "js-sys", @@ -5257,9 +5727,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.100" +version = "0.2.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" +checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -5267,36 +5737,55 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.100" +version = "0.2.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" +checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40" dependencies = [ + "bumpalo", "proc-macro2", "quote", - "syn 2.0.102", - "wasm-bindgen-backend", + "syn 2.0.111", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.100" +version = "0.2.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" +checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4" dependencies = [ "unicode-ident", ] [[package]] name = "web-sys" -version = "0.3.77" +version = "0.3.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b32828d774c412041098d182a8b38b16ea816958e07cf40eec2bc080ae137ac" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" dependencies = [ "js-sys", "wasm-bindgen", ] +[[package]] +name = "webpki-roots" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2878ef029c47c6e8cf779119f20fcf52bde7ad42a731b2a304bc221df17571e" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "winapi" version = "0.3.9" @@ -5315,11 +5804,11 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" -version = "0.1.9" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -5330,9 +5819,9 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-core" -version = "0.61.2" +version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ "windows-implement", "windows-interface", @@ -5343,37 +5832,37 @@ dependencies = [ [[package]] name = "windows-implement" -version = "0.60.0" +version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "windows-interface" -version = "0.59.1" +version = "0.59.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "windows-link" -version = "0.1.1" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76840935b766e1b0a05c0066835fb9ec80071d4c09a16f6bd5f7e655e3c14c38" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] name = "windows-registry" -version = "0.5.2" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3bab093bdd303a1240bb99b8aba8ea8a69ee19d34c9e2ef9594e708a4878820" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" dependencies = [ "windows-link", "windows-result", @@ -5382,18 +5871,18 @@ dependencies = [ [[package]] name = "windows-result" -version = "0.3.4" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ "windows-link", ] [[package]] name = "windows-strings" -version = "0.4.2" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ "windows-link", ] @@ -5416,6 +5905,24 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-targets" version = "0.52.6" @@ -5434,18 +5941,19 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.53.0" +version = "0.53.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e4c7e8ceaaf9cb7d7507c974735728ab453b67ef8f18febdd7c11fe59dca8b" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" dependencies = [ - "windows_aarch64_gnullvm 0.53.0", - "windows_aarch64_msvc 0.53.0", - "windows_i686_gnu 0.53.0", - "windows_i686_gnullvm 0.53.0", - "windows_i686_msvc 0.53.0", - "windows_x86_64_gnu 0.53.0", - "windows_x86_64_gnullvm 0.53.0", - "windows_x86_64_msvc 0.53.0", + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", ] [[package]] @@ -5456,9 +5964,9 @@ checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_gnullvm" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" [[package]] name = "windows_aarch64_msvc" @@ -5468,9 +5976,9 @@ checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_aarch64_msvc" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" [[package]] name = "windows_i686_gnu" @@ -5480,9 +5988,9 @@ checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnu" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" [[package]] name = "windows_i686_gnullvm" @@ -5492,9 +6000,9 @@ checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_gnullvm" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" [[package]] name = "windows_i686_msvc" @@ -5504,9 +6012,9 @@ checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_i686_msvc" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" [[package]] name = "windows_x86_64_gnu" @@ -5516,9 +6024,9 @@ checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnu" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" [[package]] name = "windows_x86_64_gnullvm" @@ -5528,9 +6036,9 @@ checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_gnullvm" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" [[package]] name = "windows_x86_64_msvc" @@ -5540,33 +6048,30 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "windows_x86_64_msvc" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" [[package]] name = "winnow" -version = "0.7.11" +version = "0.7.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74c7b26e3480b707944fc872477815d29a8e429d2f93a1ce000f5fa84a15cbcd" +checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829" dependencies = [ "memchr", ] [[package]] -name = "wit-bindgen-rt" -version = "0.39.0" +name = "wit-bindgen" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" -dependencies = [ - "bitflags 2.9.1", -] +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" [[package]] name = "writeable" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea2f10b9bb0928dfb1b42b65e1f9e36f7f54dbdf08457afefb38afcdec4fa2bb" +checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" [[package]] name = "wyz" @@ -5579,9 +6084,9 @@ dependencies = [ [[package]] name = "xattr" -version = "1.5.0" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d65cbf2f12c15564212d48f4e3dfb87923d25d611f2aed18f4cb23f0413d89e" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", "rustix", @@ -5595,11 +6100,10 @@ checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" [[package]] name = "yoke" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f41bb01b8226ef4bfd589436a297c53d118f65921786300e427be8d487695cc" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" dependencies = [ - "serde", "stable_deref_trait", "yoke-derive", "zerofrom", @@ -5607,13 +6111,13 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38da3c9736e16c5d3c8c597a9aaa5d1fa565d0532ae05e27c24aa62fb32c0ab6" +checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", "synstructure", ] @@ -5629,11 +6133,11 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.25" +version = "0.8.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1702d9583232ddb9174e01bb7c15a2ab8fb1bc6f227aa1233858c351a3ba0cb" +checksum = "fd74ec98b9250adb3ca554bdde269adf631549f51d8a8f8f0a10b50f1cb298c3" dependencies = [ - "zerocopy-derive 0.8.25", + "zerocopy-derive 0.8.31", ] [[package]] @@ -5644,18 +6148,18 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] name = "zerocopy-derive" -version = "0.8.25" +version = "0.8.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28a6e20d751156648aa063f3800b706ee209a32c0b4d9f24be3d980b01be55ef" +checksum = "d8a8d209fdf45cf5138cbb5a506f6b52522a25afccc534d1475dad8e31105c6a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -5675,21 +6179,21 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", "synstructure", ] [[package]] name = "zeroize" -version = "1.8.1" +version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" [[package]] name = "zerotrie" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36f0bbd478583f79edad978b407914f61b2972f5af6fa089686016be8f9af595" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" dependencies = [ "displaydoc", "yoke", @@ -5698,9 +6202,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.2" +version = "0.11.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a05eb080e015ba39cc9e23bbe5e7fb04d5fb040350f99f34e338d5fdd294428" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" dependencies = [ "yoke", "zerofrom", @@ -5709,13 +6213,13 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.1" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b96237efa0c878c64bd89c436f661be4e46b2f3eff1ebb976f7ef2321d2f58f" +checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.102", + "syn 2.0.111", ] [[package]] @@ -5738,9 +6242,9 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.0.15+zstd.1.5.7" +version = "2.0.16+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb81183ddd97d0c74cedf1d50d85c8d08c1b8b68ee863bdee9e706eedba1a237" +checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" dependencies = [ "cc", "pkg-config", From 00db8233574ccfc07f6de996da3fd9c3c3a19b67 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 2 Dec 2025 09:55:01 +0000 Subject: [PATCH 1253/1297] chore(deps): bump actions/checkout from 4 to 6 --- .github/workflows/container.yaml | 2 +- .github/workflows/coverage.yaml | 2 +- .github/workflows/deployment.yaml | 4 ++-- .github/workflows/generate_coverage_pr.yaml | 2 +- .github/workflows/labels.yaml | 2 +- .github/workflows/testing.yaml | 10 +++++----- .github/workflows/upload_coverage_pr.yaml | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index 9f51f3124..7416df71e 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -46,7 +46,7 @@ jobs: - id: checkout name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - id: compose name: Compose diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index e10c5ac66..2c8d63d6c 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -19,7 +19,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Install LLVM tools run: sudo apt-get update && sudo apt-get install -y llvm diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml index 4e8fd579b..b544d1da2 100644 --- a/.github/workflows/deployment.yaml +++ b/.github/workflows/deployment.yaml @@ -17,7 +17,7 @@ jobs: steps: - id: checkout name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - id: setup name: Setup Toolchain @@ -42,7 +42,7 @@ jobs: steps: - id: checkout name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - id: setup name: Setup Toolchain diff --git a/.github/workflows/generate_coverage_pr.yaml b/.github/workflows/generate_coverage_pr.yaml index d1b241b9d..8363376b2 100644 --- a/.github/workflows/generate_coverage_pr.yaml +++ b/.github/workflows/generate_coverage_pr.yaml @@ -19,7 +19,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Install LLVM tools run: sudo apt-get update && sudo apt-get install -y llvm diff --git a/.github/workflows/labels.yaml b/.github/workflows/labels.yaml index bb8283f30..a312c335f 100644 --- a/.github/workflows/labels.yaml +++ b/.github/workflows/labels.yaml @@ -25,7 +25,7 @@ jobs: steps: - id: checkout name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - id: sync name: Apply Labels from File diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 671864fc9..c9328d890 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -15,7 +15,7 @@ jobs: steps: - id: checkout name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - id: setup name: Setup Toolchain @@ -44,7 +44,7 @@ jobs: steps: - id: checkout name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - id: setup name: Setup Toolchain @@ -96,7 +96,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v6 - id: setup name: Setup Toolchain @@ -119,7 +119,7 @@ jobs: steps: - id: checkout name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - id: setup name: Setup Toolchain @@ -173,7 +173,7 @@ jobs: - id: checkout name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - id: test name: Run E2E Tests diff --git a/.github/workflows/upload_coverage_pr.yaml b/.github/workflows/upload_coverage_pr.yaml index 1ed2f7bcc..a2a3c82a6 100644 --- a/.github/workflows/upload_coverage_pr.yaml +++ b/.github/workflows/upload_coverage_pr.yaml @@ -96,7 +96,7 @@ jobs: echo "override_commit=$(> "$GITHUB_OUTPUT" - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: ref: ${{ steps.parse_previous_artifacts.outputs.override_commit || '' }} path: repo_root From 6757705ab631c4418eca9cb75b5bc24db1e84ee5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 2 Dec 2025 09:57:21 +0000 Subject: [PATCH 1254/1297] chore(deps): bump actions/upload-artifact from 4 to 5 --- .github/workflows/generate_coverage_pr.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/generate_coverage_pr.yaml b/.github/workflows/generate_coverage_pr.yaml index 8363376b2..6942e276f 100644 --- a/.github/workflows/generate_coverage_pr.yaml +++ b/.github/workflows/generate_coverage_pr.yaml @@ -59,13 +59,13 @@ jobs: # Triggered sub-workflow is not able to detect the original commit/PR which is available # in this workflow. - name: Store PR number - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: pr_number path: pr_number.txt - name: Store commit SHA - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: commit_sha path: commit_sha.txt @@ -74,7 +74,7 @@ jobs: # is executed by a different workflow `upload_coverage.yml`. The reason for this # split is because `on.pull_request` workflows don't have access to secrets. - name: Store coverage report in artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: codecov_report path: ./codecov.json From 46b245004abea6bbf16afdadadbf9baa617797a0 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 2 Dec 2025 09:57:29 +0000 Subject: [PATCH 1255/1297] chore(deps): bump actions/github-script from 7 to 8 --- .github/workflows/upload_coverage_pr.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/upload_coverage_pr.yaml b/.github/workflows/upload_coverage_pr.yaml index a2a3c82a6..8b0006a6d 100644 --- a/.github/workflows/upload_coverage_pr.yaml +++ b/.github/workflows/upload_coverage_pr.yaml @@ -22,7 +22,7 @@ jobs: steps: - name: "Download existing coverage report" id: prepare_report - uses: actions/github-script@v7 + uses: actions/github-script@v8 with: script: | var fs = require('fs'); From 6cb7cdd932385a160c8b2da76842909a2277b04b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 2 Dec 2025 10:03:07 +0000 Subject: [PATCH 1256/1297] chore(deps): update Cargo dependencies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tokio: 1.45.1 → 1.48.0 - reqwest: 0.12.20 → 0.12.24 - clap: 4.5.40 → 4.5.53 - tracing-subscriber: 0.3.19 → 0.3.22 - ringbuf: 0.4.4 → 0.4.8 - uuid: 1.18.1 → 1.19.0 - and other transitive dependencies Related dependabot PRs: - #1629 (tokio) - #1630 (reqwest) - #1623 (clap) - #1614 (tracing-subscriber) - #1604 (ringbuf) --- Cargo.lock | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 62d10c72f..952e1d8a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3484,9 +3484,9 @@ dependencies = [ [[package]] name = "prost" -version = "0.14.2" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "101fec8d036f8d9d4a1e8ebf90d566d1d798f3b1aa379d2576a54a0d9acea5bd" +checksum = "7231bd9b3d3d33c86b58adbac74b5ec0ad9f496b19d22801d773636feaa95f3d" dependencies = [ "bytes", "prost-derive", @@ -3494,9 +3494,9 @@ dependencies = [ [[package]] name = "prost-derive" -version = "0.14.2" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2d93e596a829ebe00afa41c3a056e6308d6b8a4c7d869edf184e2c91b1ba564" +checksum = "9120690fafc389a67ba3803df527d0ec9cbbc9cc45e4cc20b332996dfb672425" dependencies = [ "anyhow", "itertools 0.14.0", @@ -3507,9 +3507,9 @@ dependencies = [ [[package]] name = "prost-types" -version = "0.14.2" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5d7b7346e150de32340ae3390b8b3ffa37ad93ec31fb5dad86afe817619e4e7" +checksum = "b9b4db3d6da204ed77bb26ba83b6122a73aeb2e87e25fbf7ad2e84c4ccbf8f72" dependencies = [ "prost", ] @@ -5631,9 +5631,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.18.1" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" +checksum = "e2e054861b4bd027cd373e18e8d8d8e6548085000e41290d95ce0c373a654b4a" dependencies = [ "getrandom 0.3.4", "js-sys", From a2f9657ddb1d773d1067132dc0f7a2207b99c2c9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:26:22 +0000 Subject: [PATCH 1257/1297] chore(deps): update dependencies ``` cargo update Updating crates.io index Locking 49 packages to latest compatible versions Updating async-compression v0.4.34 -> v0.4.36 Updating async-lock v3.4.1 -> v3.4.2 Updating axum v0.8.7 -> v0.8.8 Updating axum-extra v0.12.2 -> v0.12.3 Updating axum-server v0.7.3 -> v0.8.0 Updating bumpalo v3.19.0 -> v3.19.1 Updating cc v1.2.48 -> v1.2.50 Updating cmake v0.1.54 -> v0.1.57 Updating compression-codecs v0.4.33 -> v0.4.35 Adding convert_case v0.10.0 Updating criterion v0.8.0 -> v0.8.1 Updating criterion-plot v0.8.0 -> v0.8.1 Adding derive_builder v0.20.2 Adding derive_builder_core v0.20.2 Adding derive_builder_macro v0.20.2 Updating derive_more v2.0.1 -> v2.1.0 Updating derive_more-impl v2.0.1 -> v2.1.0 Updating ferroid v0.8.7 -> v0.8.8 Updating fs-err v3.2.0 -> v3.2.1 Adding getset v0.1.6 Updating hyper-util v0.1.18 -> v0.1.19 Updating icu_properties v2.1.1 -> v2.1.2 Updating icu_properties_data v2.1.1 -> v2.1.2 Updating itoa v1.0.15 -> v1.0.16 Updating libc v0.2.177 -> v0.2.178 Updating libredox v0.1.10 -> v0.1.11 Updating local-ip-address v0.6.5 -> v0.6.8 Updating log v0.4.28 -> v0.4.29 Updating mio v1.1.0 -> v1.1.1 Updating neli v0.6.5 -> v0.7.3 Updating neli-proc-macros v0.1.4 -> v0.2.2 Updating portable-atomic v1.11.1 -> v1.12.0 Adding redox_syscall v0.6.0 Updating reqwest v0.12.24 -> v0.12.26 Updating rustls-pki-types v1.13.1 -> v1.13.2 Updating ryu v1.0.20 -> v1.0.21 Updating serde_spanned v1.0.3 -> v1.0.4 Updating simd-adler32 v0.3.7 -> v0.3.8 Updating supports-hyperlinks v3.1.0 -> v3.2.0 Updating testcontainers v0.26.0 -> v0.26.2 Updating toml v0.9.8 -> v0.9.10+spec-1.1.0 Updating toml_datetime v0.7.3 -> v0.7.5+spec-1.1.0 Updating toml_edit v0.23.7 -> v0.23.10+spec-1.0.0 Updating toml_parser v1.0.4 -> v1.0.6+spec-1.1.0 Updating toml_writer v1.0.4 -> v1.0.6+spec-1.1.0 Updating tower-http v0.6.7 -> v0.6.8 Updating tracing v0.1.43 -> v0.1.44 Updating tracing-core v0.1.35 -> v0.1.36 Adding unicode-segmentation v1.12.0 Removing windows-sys v0.59.0 note: pass `--verbose` to see 7 unchanged dependencies behind latest ``` --- Cargo.lock | 278 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 171 insertions(+), 107 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 952e1d8a6..da0910f48 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -236,9 +236,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.34" +version = "0.4.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e86f6d3dc9dc4352edeea6b8e499e13e3f5dc3b964d7ca5fd411415a3498473" +checksum = "98ec5f6c2f8bc326c994cb9e241cc257ddaba9afa8555a43cffbb5dd86efaa37" dependencies = [ "compression-codecs", "compression-core", @@ -297,9 +297,9 @@ dependencies = [ [[package]] name = "async-lock" -version = "3.4.1" +version = "3.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd03604047cee9b6ce9de9f70c6cd540a0520c813cbd49bae61f33ab80ed1dc" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" dependencies = [ "event-listener 5.4.1", "event-listener-strategy", @@ -395,9 +395,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "axum" -version = "0.8.7" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b098575ebe77cb6d14fc7f32749631a6e44edbef6b796f89b020e99ba20d425" +checksum = "8b52af3cb4058c895d37317bb27508dccc8e5f2d39454016b297bf4a400597b8" dependencies = [ "axum-core", "axum-macros", @@ -459,9 +459,9 @@ dependencies = [ [[package]] name = "axum-extra" -version = "0.12.2" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbfe9f610fe4e99cf0cfcd03ccf8c63c28c616fe714d80475ef731f3b13dd21b" +checksum = "6dfbd6109d91702d55fc56df06aae7ed85c465a7a451db6c0e54a4b9ca5983d1" dependencies = [ "axum", "axum-core", @@ -495,12 +495,13 @@ dependencies = [ [[package]] name = "axum-server" -version = "0.7.3" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1ab4a3ec9ea8a657c72d99a03a824af695bd0fb5ec639ccbd9cd3543b41a5f9" +checksum = "b1df331683d982a0b9492b38127151e6453639cd34926eb9c07d4cd8c6d22bfc" dependencies = [ "arc-swap", "bytes", + "either", "fs-err", "http", "http-body", @@ -508,7 +509,6 @@ dependencies = [ "hyper-util", "pin-project-lite", "rustls", - "rustls-pemfile", "rustls-pki-types", "tokio", "tokio-rustls", @@ -948,9 +948,9 @@ checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" [[package]] name = "bumpalo" -version = "3.19.0" +version = "3.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" +checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510" [[package]] name = "bytecheck" @@ -1018,9 +1018,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.48" +version = "1.2.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c481bdbf0ed3b892f6f806287d72acd515b352a4ec27a208489b8c1bc839633a" +checksum = "9f50d563227a1c37cc0a263f64eca3334388c01c5e4c4861a9def205c614383c" dependencies = [ "find-msvc-tools", "jobserver", @@ -1151,9 +1151,9 @@ checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" [[package]] name = "cmake" -version = "0.1.54" +version = "0.1.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7caa3f9de89ddbe2c607f4101924c5abec803763ae9534e4f4d7d8f84aa81f0" +checksum = "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d" dependencies = [ "cc", ] @@ -1179,9 +1179,9 @@ dependencies = [ [[package]] name = "compression-codecs" -version = "0.4.33" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "302266479cb963552d11bd042013a58ef1adc56768016c8b82b4199488f2d4ad" +checksum = "b0f7ac3e5b97fdce45e8922fb05cae2c37f7bbd63d30dd94821dacfd8f3f2bf2" dependencies = [ "brotli", "compression-core", @@ -1206,6 +1206,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -1280,16 +1289,16 @@ dependencies = [ [[package]] name = "criterion" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0dfe5e9e71bdcf4e4954f7d14da74d1cdb92a3a07686452d1509652684b1aab" +checksum = "4d883447757bb0ee46f233e9dc22eb84d93a9508c9b868687b274fc431d886bf" dependencies = [ "alloca", "anes", "cast", "ciborium", "clap", - "criterion-plot 0.8.0", + "criterion-plot 0.8.1", "itertools 0.13.0", "num-traits", "oorandom", @@ -1316,9 +1325,9 @@ dependencies = [ [[package]] name = "criterion-plot" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5de36c2bee19fba779808f92bf5d9b0fa5a40095c277aba10c458a12b35d21d6" +checksum = "ed943f81ea2faa8dcecbbfa50164acf95d555afec96a27871663b300e387b2e4" dependencies = [ "cast", "itertools 0.13.0", @@ -1500,23 +1509,56 @@ dependencies = [ "serde_core", ] +[[package]] +name = "derive_builder" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" +dependencies = [ + "derive_builder_macro", +] + +[[package]] +name = "derive_builder_core" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" +dependencies = [ + "darling 0.20.11", + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "derive_builder_macro" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" +dependencies = [ + "derive_builder_core", + "syn 2.0.111", +] + [[package]] name = "derive_more" -version = "2.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678" +checksum = "10b768e943bed7bf2cab53df09f4bc34bfd217cdb57d971e769874c9a6710618" dependencies = [ "derive_more-impl", ] [[package]] name = "derive_more-impl" -version = "2.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" +checksum = "6d286bfdaf75e988b4a78e013ecd79c581e06399ab53fbacd2d916c2f904f30b" dependencies = [ + "convert_case", "proc-macro2", "quote", + "rustc_version", "syn 2.0.111", "unicode-xid", ] @@ -1680,9 +1722,9 @@ checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "ferroid" -version = "0.8.7" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0e9414a6ae93ef993ce40a1e02944f13d4508e2bf6f1ced1580ce6910f08253" +checksum = "ce161062fb044bd629c2393590efd47cab8d0241faf15704ffb0d47b7b4e4a35" dependencies = [ "portable-atomic", "rand 0.9.2", @@ -1854,9 +1896,9 @@ dependencies = [ [[package]] name = "fs-err" -version = "3.2.0" +version = "3.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62d91fd049c123429b018c47887d3f75a265540dd3c30ba9cb7bae9197edb03a" +checksum = "824f08d01d0f496b3eca4f001a13cf17690a6ee930043d20817f547455fd98f8" dependencies = [ "autocfg", "tokio", @@ -2009,6 +2051,18 @@ dependencies = [ "wasip2", ] +[[package]] +name = "getset" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cf0fc11e47561d47397154977bc219f4cf809b2974facc3ccb3b89e2436f912" +dependencies = [ + "proc-macro-error2", + "proc-macro2", + "quote", + "syn 2.0.111", +] + [[package]] name = "gimli" version = "0.32.3" @@ -2267,9 +2321,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.18" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52e9a2a24dc5c6821e71a7030e1e14b7b632acac55c40e9d2e082c621261bb56" +checksum = "727805d60e7938b76b826a6ef209eb70eaa1812794f9424d4a4e2d740662df5f" dependencies = [ "base64 0.22.1", "bytes", @@ -2378,9 +2432,9 @@ checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" [[package]] name = "icu_properties" -version = "2.1.1" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e93fcd3157766c0c8da2f8cff6ce651a31f0810eaa1c51ec363ef790bbb5fb99" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" dependencies = [ "icu_collections", "icu_locale_core", @@ -2392,9 +2446,9 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.1.1" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02845b3647bb045f1100ecd6480ff52f34c35f82d9880e029d329c21d1054899" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" [[package]] name = "icu_provider" @@ -2553,9 +2607,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.15" +version = "1.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" +checksum = "7ee5b5339afb4c41626dde77b7a611bd4f2c202b897852b4bcf5d03eddc61010" [[package]] name = "jobserver" @@ -2594,9 +2648,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.177" +version = "0.2.178" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" +checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091" [[package]] name = "libloading" @@ -2616,13 +2670,13 @@ checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" [[package]] name = "libredox" -version = "0.1.10" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb" +checksum = "df15f6eac291ed1cf25865b1ee60399f57e7c227e7f51bdbd4c5270396a9ed50" dependencies = [ "bitflags", "libc", - "redox_syscall", + "redox_syscall 0.6.0", ] [[package]] @@ -2661,14 +2715,14 @@ checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" [[package]] name = "local-ip-address" -version = "0.6.5" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "656b3b27f8893f7bbf9485148ff9a65f019e3f33bd5cdc87c83cab16b3fd9ec8" +checksum = "0a60bf300a990b2d1ebdde4228e873e8e4da40d834adbf5265f3da1457ede652" dependencies = [ "libc", "neli", "thiserror 2.0.17", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -2682,9 +2736,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.28" +version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" dependencies = [ "value-bag", ] @@ -2764,9 +2818,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873" +checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" dependencies = [ "libc", "wasi", @@ -2918,27 +2972,31 @@ dependencies = [ [[package]] name = "neli" -version = "0.6.5" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93062a0dce6da2517ea35f301dfc88184ce18d3601ec786a727a87bf535deca9" +checksum = "e23bebbf3e157c402c4d5ee113233e5e0610cc27453b2f07eefce649c7365dcc" dependencies = [ + "bitflags", "byteorder", + "derive_builder", + "getset", "libc", "log", "neli-proc-macros", + "parking_lot", ] [[package]] name = "neli-proc-macros" -version = "0.1.4" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c8034b7fbb6f9455b2a96c19e6edf8dc9fc34c70449938d8ee3b4df363f61fe" +checksum = "05d8d08c6e98f20a62417478ebf7be8e1425ec9acecc6f63e22da633f6b71609" dependencies = [ "either", "proc-macro2", "quote", "serde", - "syn 1.0.109", + "syn 2.0.111", ] [[package]] @@ -3156,7 +3214,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall", + "redox_syscall 0.5.18", "smallvec", "windows-link", ] @@ -3356,9 +3414,9 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.11.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" +checksum = "f59e70c4aef1e55797c2e8fd94a4f2a973fc972cfde0e0b05f683667b0cd39dd" [[package]] name = "portable-atomic-util" @@ -3435,7 +3493,7 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983" dependencies = [ - "toml_edit 0.23.7", + "toml_edit 0.23.10+spec-1.0.0", ] [[package]] @@ -3686,6 +3744,15 @@ dependencies = [ "bitflags", ] +[[package]] +name = "redox_syscall" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec96166dafa0886eb81fe1c0a388bece180fbef2135f97c1e2cf8302e74b43b5" +dependencies = [ + "bitflags", +] + [[package]] name = "ref-cast" version = "1.0.25" @@ -3752,9 +3819,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.24" +version = "0.12.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f" +checksum = "3b4c14b2d9afca6a60277086b0cc6a6ae0b568f6f7916c943a8cdc79f8be240f" dependencies = [ "base64 0.22.1", "bytes", @@ -4005,9 +4072,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "708c0f9d5f54ba0272468c1d306a52c495b31fa155e91bc25371e6df7996908c" +checksum = "21e6f2ab2928ca4291b86736a8bd920a277a399bba1589409d72154ff87c1282" dependencies = [ "zeroize", ] @@ -4031,9 +4098,9 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "ryu" -version = "1.0.20" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" +checksum = "62049b2877bf12821e8f9ad256ee38fdc31db7387ec2d3b3f403024de2034aea" [[package]] name = "same-file" @@ -4256,9 +4323,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e24345aa0fe688594e73770a5f6d1b216508b4f93484c0026d521acd30134392" +checksum = "f8bbf91e5a4d6315eee45e704372590b30e260ee83af6639d64557f51b067776" dependencies = [ "serde_core", ] @@ -4354,9 +4421,9 @@ dependencies = [ [[package]] name = "simd-adler32" -version = "0.3.7" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" +checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" [[package]] name = "simdutf8" @@ -4470,9 +4537,9 @@ dependencies = [ [[package]] name = "supports-hyperlinks" -version = "3.1.0" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "804f44ed3c63152de6a9f90acbea1a110441de43006ea51bcce8f436196a288b" +checksum = "e396b6523b11ccb83120b115a0b7366de372751aa6edf19844dfb13a6af97e91" [[package]] name = "supports-unicode" @@ -4606,9 +4673,9 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "testcontainers" -version = "0.26.0" +version = "0.26.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a347cac4368ba4f1871743adb27dc14829024d26b1763572404726b0b9943eb8" +checksum = "1483605f58b2fff80d786eb56a0b6b4e8b1e5423fbc9ec2e3e562fa2040d6f27" dependencies = [ "astral-tokio-tar", "async-trait", @@ -4844,14 +4911,14 @@ dependencies = [ [[package]] name = "toml" -version = "0.9.8" +version = "0.9.10+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0dc8b1fb61449e27716ec0e1bdf0f6b8f3e8f6b05391e8497b8b6d7804ea6d8" +checksum = "0825052159284a1a8b4d6c0c86cbc801f2da5afd2b225fa548c72f2e74002f48" dependencies = [ "indexmap 2.12.1", "serde_core", - "serde_spanned 1.0.3", - "toml_datetime 0.7.3", + "serde_spanned 1.0.4", + "toml_datetime 0.7.5+spec-1.1.0", "toml_parser", "toml_writer", "winnow", @@ -4868,9 +4935,9 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.7.3" +version = "0.7.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2cdb639ebbc97961c51720f858597f7f24c4fc295327923af55b74c3c724533" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" dependencies = [ "serde_core", ] @@ -4891,21 +4958,21 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.23.7" +version = "0.23.10+spec-1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6485ef6d0d9b5d0ec17244ff7eb05310113c3f316f2d14200d4de56b3cb98f8d" +checksum = "84c8b9f757e028cee9fa244aea147aab2a9ec09d5325a9b01e0a49730c2b5269" dependencies = [ "indexmap 2.12.1", - "toml_datetime 0.7.3", + "toml_datetime 0.7.5+spec-1.1.0", "toml_parser", "winnow", ] [[package]] name = "toml_parser" -version = "1.0.4" +version = "1.0.6+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0cbe268d35bdb4bb5a56a2de88d0ad0eb70af5384a99d648cd4b3d04039800e" +checksum = "a3198b4b0a8e11f09dd03e133c0280504d0801269e9afa46362ffde1cbeebf44" dependencies = [ "winnow", ] @@ -4918,9 +4985,9 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" [[package]] name = "toml_writer" -version = "1.0.4" +version = "1.0.6+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df8b2b54733674ad286d16267dcfc7a71ed5c776e4ac7aa3c3e2561f7c637bf2" +checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607" [[package]] name = "tonic" @@ -5218,7 +5285,7 @@ dependencies = [ "serde_json", "serde_with", "thiserror 2.0.17", - "toml 0.9.8", + "toml 0.9.10+spec-1.1.0", "torrust-tracker-located-error", "tracing", "tracing-subscriber", @@ -5230,7 +5297,7 @@ dependencies = [ name = "torrust-tracker-contrib-bencode" version = "3.0.0-develop" dependencies = [ - "criterion 0.8.0", + "criterion 0.8.1", "thiserror 2.0.17", ] @@ -5294,7 +5361,7 @@ dependencies = [ "async-std", "bittorrent-primitives", "chrono", - "criterion 0.8.0", + "criterion 0.8.1", "crossbeam-skiplist", "futures", "mockall", @@ -5330,7 +5397,7 @@ dependencies = [ "aquatic_udp_protocol", "async-std", "bittorrent-primitives", - "criterion 0.8.0", + "criterion 0.8.1", "crossbeam-skiplist", "dashmap", "futures", @@ -5398,9 +5465,9 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.7" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf146f99d442e8e68e585f5d798ccd3cad9a7835b917e09728880a862706456" +checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" dependencies = [ "async-compression", "bitflags", @@ -5434,9 +5501,9 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tracing" -version = "0.1.43" +version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d15d90a0b5c19378952d479dc858407149d7bb45a14de0142f6c534b16fc647" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ "log", "pin-project-lite", @@ -5457,9 +5524,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.35" +version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a04e24fab5c89c6a36eb8558c9656f30d81de51dfa4d3b45f26b21d61fa0a6c" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", "valuable", @@ -5547,6 +5614,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" +[[package]] +name = "unicode-segmentation" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" + [[package]] name = "unicode-width" version = "0.1.14" @@ -5896,15 +5969,6 @@ dependencies = [ "windows-targets 0.52.6", ] -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets 0.52.6", -] - [[package]] name = "windows-sys" version = "0.60.2" From 4c16227bdaa03c236cc597b93dc49563224e0afe Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:35:13 +0000 Subject: [PATCH 1258/1297] fix: E0107 - missing generics for struct axum_server::Server in from_tcp_with_timeouts error[E0107]: missing generics for struct `axum_server::Server` --> packages/axum-server/src/custom_axum_server.rs:44:55 | 44 | pub fn from_tcp_with_timeouts(socket: TcpListener) -> Server { | ^^^^^^ expected at least 1 generic argument Added SocketAddr generic parameter to Server return type and Address trait bound to add_timeouts function. --- packages/axum-server/src/custom_axum_server.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/axum-server/src/custom_axum_server.rs b/packages/axum-server/src/custom_axum_server.rs index 5705ef24e..fccaf54dc 100644 --- a/packages/axum-server/src/custom_axum_server.rs +++ b/packages/axum-server/src/custom_axum_server.rs @@ -18,7 +18,7 @@ //! If you want to know more about Axum and timeouts see . use std::future::Ready; use std::io::ErrorKind; -use std::net::TcpListener; +use std::net::{SocketAddr, TcpListener}; use std::pin::Pin; use std::task::{Context, Poll}; use std::time::Duration; @@ -41,7 +41,7 @@ const HTTP2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(5); const HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(5); #[must_use] -pub fn from_tcp_with_timeouts(socket: TcpListener) -> Server { +pub fn from_tcp_with_timeouts(socket: TcpListener) -> Server { add_timeouts(axum_server::from_tcp(socket)) } @@ -50,7 +50,7 @@ pub fn from_tcp_rustls_with_timeouts(socket: TcpListener, tls: RustlsConfig) -> add_timeouts(axum_server::from_tcp_rustls(socket, tls)) } -fn add_timeouts(mut server: Server) -> Server { +fn add_timeouts(mut server: Server) -> Server { server.http_builder().http1().timer(TokioTimer::new()); server.http_builder().http2().timer(TokioTimer::new()); From 51452a8b2a7aee04822e90651179c2b0a8bb031f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:38:42 +0000 Subject: [PATCH 1259/1297] fix: E0277 and E0308 - RustlsAcceptor trait bounds and type mismatch in from_tcp_rustls_with_timeouts error[E0277]: the trait bound `RustlsAcceptor: Address` is not satisfied --> packages/axum-server/src/custom_axum_server.rs:49:81 | 49 | ... tls: RustlsConfig) -> Server { | ^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound error[E0308]: mismatched types --> packages/axum-server/src/custom_axum_server.rs:50:18 | 50 | add_timeouts(axum_server::from_tcp_rustls(socket, tls)) | ------------ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Server`, found `Result, ...>` Changed return type to Result, std::io::Error> and used map to apply add_timeouts to the Result value. --- packages/axum-server/src/custom_axum_server.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/axum-server/src/custom_axum_server.rs b/packages/axum-server/src/custom_axum_server.rs index fccaf54dc..39a2271d6 100644 --- a/packages/axum-server/src/custom_axum_server.rs +++ b/packages/axum-server/src/custom_axum_server.rs @@ -36,6 +36,8 @@ use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender}; use tokio::time::{Instant, Sleep}; use tower::Service; +type RustlsServerResult = Result, std::io::Error>; + const HTTP1_HEADER_READ_TIMEOUT: Duration = Duration::from_secs(5); const HTTP2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(5); const HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(5); @@ -46,8 +48,8 @@ pub fn from_tcp_with_timeouts(socket: TcpListener) -> Server { } #[must_use] -pub fn from_tcp_rustls_with_timeouts(socket: TcpListener, tls: RustlsConfig) -> Server { - add_timeouts(axum_server::from_tcp_rustls(socket, tls)) +pub fn from_tcp_rustls_with_timeouts(socket: TcpListener, tls: RustlsConfig) -> RustlsServerResult { + axum_server::from_tcp_rustls(socket, tls).map(add_timeouts) } fn add_timeouts(mut server: Server) -> Server { From 74d5c8b9f0520077e8ec3baf84423808f771a285 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:39:14 +0000 Subject: [PATCH 1260/1297] fix: E0308 - mismatched types, from_tcp returns Result in from_tcp_with_timeouts error[E0308]: mismatched types --> packages/axum-server/src/custom_axum_server.rs:47:18 | 47 | add_timeouts(axum_server::from_tcp(socket)) | ------------ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Server`, found `Result, Error>` Changed return type to Result, std::io::Error> and used map to apply add_timeouts to the Result value. --- packages/axum-server/src/custom_axum_server.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/axum-server/src/custom_axum_server.rs b/packages/axum-server/src/custom_axum_server.rs index 39a2271d6..b7f1d664e 100644 --- a/packages/axum-server/src/custom_axum_server.rs +++ b/packages/axum-server/src/custom_axum_server.rs @@ -37,14 +37,15 @@ use tokio::time::{Instant, Sleep}; use tower::Service; type RustlsServerResult = Result, std::io::Error>; +type ServerResult = Result, std::io::Error>; const HTTP1_HEADER_READ_TIMEOUT: Duration = Duration::from_secs(5); const HTTP2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(5); const HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(5); #[must_use] -pub fn from_tcp_with_timeouts(socket: TcpListener) -> Server { - add_timeouts(axum_server::from_tcp(socket)) +pub fn from_tcp_with_timeouts(socket: TcpListener) -> ServerResult { + axum_server::from_tcp(socket).map(add_timeouts) } #[must_use] From cd83cfd9491cc9369921d560467d5cbfec917d02 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:39:45 +0000 Subject: [PATCH 1261/1297] fix: E0631 - type mismatch in add_timeouts function arguments for acceptor type error[E0631]: type mismatch in function arguments --> packages/axum-server/src/custom_axum_server.rs:53:51 | 53 | axum_server::from_tcp_rustls(socket, tls).map(add_timeouts) | --- ^^^^^^^^^^^^ expected due to this | = note: expected function signature `fn(Server<_, RustlsAcceptor>) -> _` found function signature `fn(Server<_, DefaultAcceptor>) -> _` Made add_timeouts generic over both Address and Acceptor types to work with both DefaultAcceptor and RustlsAcceptor. --- packages/axum-server/src/custom_axum_server.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/axum-server/src/custom_axum_server.rs b/packages/axum-server/src/custom_axum_server.rs index b7f1d664e..e3567bad4 100644 --- a/packages/axum-server/src/custom_axum_server.rs +++ b/packages/axum-server/src/custom_axum_server.rs @@ -53,7 +53,7 @@ pub fn from_tcp_rustls_with_timeouts(socket: TcpListener, tls: RustlsConfig) -> axum_server::from_tcp_rustls(socket, tls).map(add_timeouts) } -fn add_timeouts(mut server: Server) -> Server { +fn add_timeouts(mut server: Server) -> Server { server.http_builder().http1().timer(TokioTimer::new()); server.http_builder().http2().timer(TokioTimer::new()); From 612f7f1f07e69ce3e0fdeb3c8b264f46917aa06e Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:40:10 +0000 Subject: [PATCH 1262/1297] fix: E0107 - missing generics for struct axum_server::Handle in signals.rs error[E0107]: missing generics for struct `axum_server::Handle` --> packages/axum-server/src/signals.rs:10:26 | 10 | handle: axum_server::Handle, | ^^^^^^ expected 1 generic argument Added SocketAddr generic parameter to Handle type in graceful_shutdown function signature. --- packages/axum-server/src/signals.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/axum-server/src/signals.rs b/packages/axum-server/src/signals.rs index 268ff79fa..360879e32 100644 --- a/packages/axum-server/src/signals.rs +++ b/packages/axum-server/src/signals.rs @@ -7,7 +7,7 @@ use tracing::instrument; #[instrument(skip(handle, rx_halt, message))] pub async fn graceful_shutdown( - handle: axum_server::Handle, + handle: axum_server::Handle, rx_halt: tokio::sync::oneshot::Receiver, message: String, address: SocketAddr, From 37793ce42e19ab922ad70948631d8f26ecad9213 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:41:05 +0000 Subject: [PATCH 1263/1297] fix: clippy::uninlined_format_args - variables can be used directly in format! string --> console/tracker-client/src/console/clients/udp/app.rs:178:24 | | __________________^ 179 | | ... "invalid address format: \`{}\`. Expected format is host:port", 180 | | ... tracker_socket_addr_str 181 | | ... )); | |_______^ --> console/tracker-client/src/console/clients/udp/app.rs:199:13 | 199 | ...rr(anyhow::anyhow!("DNS resolution failed for \`{}\`", tracker_socket_addr_str)) Changed format strings to use inline variable interpolation instead of positional arguments. --- console/tracker-client/src/console/clients/udp/app.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/console/tracker-client/src/console/clients/udp/app.rs b/console/tracker-client/src/console/clients/udp/app.rs index a2736c365..527f46e78 100644 --- a/console/tracker-client/src/console/clients/udp/app.rs +++ b/console/tracker-client/src/console/clients/udp/app.rs @@ -176,8 +176,7 @@ fn parse_socket_addr(tracker_socket_addr_str: &str) -> anyhow::Result anyhow::Result = resolved_addr.to_socket_addrs()?.collect(); if socket_addrs.is_empty() { - Err(anyhow::anyhow!("DNS resolution failed for `{}`", tracker_socket_addr_str)) + Err(anyhow::anyhow!("DNS resolution failed for `{tracker_socket_addr_str}`")) } else { Ok(socket_addrs[0]) } From f0678be9cf46a549ebd811800754f9b24b2dab7b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:41:49 +0000 Subject: [PATCH 1264/1297] fix: clippy::missing_errors_doc and clippy::double_must_use for from_tcp_with_timeouts error: docs for function returning `Result` missing `# Errors` section --> packages/axum-server/src/custom_axum_server.rs:47:1 | 47 | pub fn from_tcp_with_timeouts(socket: TcpListener) -> ServerResult { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: this function has a `#[must_use]` attribute with no message, but returns a type already marked as `#[must_use]` --> packages/axum-server/src/custom_axum_server.rs:47:1 | 47 | pub fn from_tcp_with_timeouts(socket: TcpListener) -> ServerResult { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Added documentation with Errors section and removed #[must_use] attribute since Result type already has it. --- packages/axum-server/src/custom_axum_server.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/axum-server/src/custom_axum_server.rs b/packages/axum-server/src/custom_axum_server.rs index e3567bad4..f332c9288 100644 --- a/packages/axum-server/src/custom_axum_server.rs +++ b/packages/axum-server/src/custom_axum_server.rs @@ -43,7 +43,11 @@ const HTTP1_HEADER_READ_TIMEOUT: Duration = Duration::from_secs(5); const HTTP2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(5); const HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(5); -#[must_use] +/// Creates an Axum server from a TCP listener with configured timeouts. +/// +/// # Errors +/// +/// Returns an error if the server cannot be created from the TCP socket. pub fn from_tcp_with_timeouts(socket: TcpListener) -> ServerResult { axum_server::from_tcp(socket).map(add_timeouts) } From ea001980306165b863393cc3b0ef1f28c0b61cf9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:42:12 +0000 Subject: [PATCH 1265/1297] fix: clippy::missing_errors_doc and clippy::double_must_use for from_tcp_rustls_with_timeouts error: docs for function returning `Result` missing `# Errors` section --> packages/axum-server/src/custom_axum_server.rs:52:1 | 52 | pub fn from_tcp_rustls_with_timeouts(socket: TcpListener, tls: RustlsConfig) -> RustlsServerResult { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: this function has a `#[must_use]` attribute with no message, but returns a type already marked as `#[must_use]` --> packages/axum-server/src/custom_axum_server.rs:52:1 | 52 | pub fn from_tcp_rustls_with_timeouts(socket: TcpListener, tls: RustlsConfig) -> RustlsServerResult { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Added documentation with Errors section and removed #[must_use] attribute since Result type already has it. --- packages/axum-server/src/custom_axum_server.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/axum-server/src/custom_axum_server.rs b/packages/axum-server/src/custom_axum_server.rs index f332c9288..0328198ec 100644 --- a/packages/axum-server/src/custom_axum_server.rs +++ b/packages/axum-server/src/custom_axum_server.rs @@ -52,7 +52,11 @@ pub fn from_tcp_with_timeouts(socket: TcpListener) -> ServerResult { axum_server::from_tcp(socket).map(add_timeouts) } -#[must_use] +/// Creates an Axum server from a TCP listener with TLS and configured timeouts. +/// +/// # Errors +/// +/// Returns an error if the server cannot be created from the TCP socket or if TLS configuration fails. pub fn from_tcp_rustls_with_timeouts(socket: TcpListener, tls: RustlsConfig) -> RustlsServerResult { axum_server::from_tcp_rustls(socket, tls).map(add_timeouts) } From a217bb924a427e281f8df91b7f0a299627293a78 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:43:28 +0000 Subject: [PATCH 1266/1297] fix: E0599 - no method named handle found for Result in health-check-api-server error[E0599]: no method named `handle` found for enum `std::result::Result` in the current scope --> packages/axum-health-check-api-server/src/server.rs:120:10 | 119 | let running = axum_server::from_tcp(socket) | ___________________- 120 | | .handle(handle) | |_________-^^^^^^ Added expect() to unwrap Result before calling handle() method since from_tcp now returns Result. --- packages/axum-health-check-api-server/src/server.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/axum-health-check-api-server/src/server.rs b/packages/axum-health-check-api-server/src/server.rs index 3eeb1b054..c261f6af8 100644 --- a/packages/axum-health-check-api-server/src/server.rs +++ b/packages/axum-health-check-api-server/src/server.rs @@ -117,6 +117,7 @@ pub fn start( )); let running = axum_server::from_tcp(socket) + .expect("Failed to create server from TCP socket") .handle(handle) .serve(router.into_make_service_with_connect_info::()); From 054843477e3c73d132b7ca71dee208e3bec65dd8 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:44:09 +0000 Subject: [PATCH 1267/1297] fix: E0599 and E0282 - no method named handle found for Result in axum-http-tracker-server error[E0599]: no method named `handle` found for enum `std::result::Result` in the current scope --> packages/axum-http-tracker-server/src/server.rs:77:22 | 76 | ... Some(tls) => custom_axum_server::from_tcp_rustls_with_timeouts(socket, tls) | ____________________- 77 | | ... .handle(handle) | |___________-^^^^^^ error[E0599]: no method named `handle` found for enum `std::result::Result` in the current scope --> packages/axum-http-tracker-server/src/server.rs:85:22 | 84 | None => custom_axum_server::from_tcp_with_timeouts(socket) | _________________________- 85 | | .handle(handle) | |_____________________-^^^^^^ Added expect() calls to unwrap Result before calling handle() method for both TLS and non-TLS cases. --- packages/axum-http-tracker-server/src/server.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 2b43be0a9..4b7c15de8 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -74,6 +74,7 @@ impl Launcher { let running = Box::pin(async { match tls { Some(tls) => custom_axum_server::from_tcp_rustls_with_timeouts(socket, tls) + .expect("Failed to create server from TCP socket with TLS") .handle(handle) // The TimeoutAcceptor is commented because TSL does not work with it. // See: https://github.com/torrust/torrust-index/issues/204#issuecomment-2115529214 @@ -82,6 +83,7 @@ impl Launcher { .await .expect("Axum server crashed."), None => custom_axum_server::from_tcp_with_timeouts(socket) + .expect("Failed to create server from TCP socket") .handle(handle) .acceptor(TimeoutAcceptor) .serve(app.into_make_service_with_connect_info::()) From 02e43394e2d30370ae8214b2d513c947773123b5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:45:06 +0000 Subject: [PATCH 1268/1297] fix: E0599 and E0282 - no method named handle found for Result in axum-rest-tracker-api-server error[E0599]: no method named `handle` found for enum `std::result::Result` in the current scope --> packages/axum-rest-tracker-api-server/src/server.rs:272:22 | 271 | ... Some(tls) => custom_axum_server::from_tcp_rustls_with_timeouts(socket, tls) | ____________________- 272 | | ... .handle(handle) | |___________-^^^^^^ error[E0599]: no method named `handle` found for enum `std::result::Result` in the current scope --> packages/axum-rest-tracker-api-server/src/server.rs:280:22 | 279 | None => custom_axum_server::from_tcp_with_timeouts(socket) | _________________________- 280 | | .handle(handle) | |_____________________-^^^^^^ Added expect() calls to unwrap Result before calling handle() method for both TLS and non-TLS cases. --- packages/axum-rest-tracker-api-server/src/server.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/axum-rest-tracker-api-server/src/server.rs b/packages/axum-rest-tracker-api-server/src/server.rs index b358345fb..a867ecfcf 100644 --- a/packages/axum-rest-tracker-api-server/src/server.rs +++ b/packages/axum-rest-tracker-api-server/src/server.rs @@ -269,6 +269,7 @@ impl Launcher { let running = Box::pin(async { match tls { Some(tls) => custom_axum_server::from_tcp_rustls_with_timeouts(socket, tls) + .expect("Failed to create server from TCP socket with TLS") .handle(handle) // The TimeoutAcceptor is commented because TSL does not work with it. // See: https://github.com/torrust/torrust-index/issues/204#issuecomment-2115529214 @@ -277,6 +278,7 @@ impl Launcher { .await .expect("Axum server for tracker API crashed."), None => custom_axum_server::from_tcp_with_timeouts(socket) + .expect("Failed to create server from TCP socket") .handle(handle) .acceptor(TimeoutAcceptor) .serve(router.into_make_service_with_connect_info::()) From a62eb146fae7de0edb671c65e99d108ca18db2e5 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 08:51:04 +0000 Subject: [PATCH 1269/1297] fix: runtime panic - Registering a blocking socket with tokio runtime is unsupported thread 'tokio-runtime-worker' panicked at /home/josecelano/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/axum-server-0.8.0/src/server.rs:70:30: Registering a blocking socket with the tokio runtime is unsupported. If you wish to do anyways, please add `--cfg tokio_allow_from_blocking_fd` to your RUSTFLAGS. See github.com/tokio-rs/tokio/issues/7172 for details. Set std::net::TcpListener instances to non-blocking mode using set_nonblocking(true) before passing them to axum-server to avoid runtime panics when registering with tokio runtime. This is required since axum-server 0.8.0 and tokio v1.44.0 which added debug assertions to prevent blocking sockets from being registered with the tokio runtime. --- packages/axum-health-check-api-server/src/server.rs | 3 +++ packages/axum-http-tracker-server/src/server.rs | 3 +++ packages/axum-rest-tracker-api-server/src/server.rs | 1 + 3 files changed, 7 insertions(+) diff --git a/packages/axum-health-check-api-server/src/server.rs b/packages/axum-health-check-api-server/src/server.rs index c261f6af8..a371f146e 100644 --- a/packages/axum-health-check-api-server/src/server.rs +++ b/packages/axum-health-check-api-server/src/server.rs @@ -101,6 +101,9 @@ pub fn start( .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid)); let socket = std::net::TcpListener::bind(bind_to).expect("Could not bind tcp_listener to address."); + socket + .set_nonblocking(true) + .expect("Failed to set socket to non-blocking mode"); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); let protocol = Protocol::HTTP; // The health check API only supports HTTP directly now. Use a reverse proxy for HTTPS. let service_binding = ServiceBinding::new(protocol.clone(), address).expect("Service binding creation failed"); diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 4b7c15de8..69f9cb72e 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -52,6 +52,9 @@ impl Launcher { rx_halt: Receiver, ) -> BoxFuture<'static, ()> { let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); + socket + .set_nonblocking(true) + .expect("Failed to set socket to non-blocking mode"); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); let handle = Handle::new(); diff --git a/packages/axum-rest-tracker-api-server/src/server.rs b/packages/axum-rest-tracker-api-server/src/server.rs index a867ecfcf..32c1051e1 100644 --- a/packages/axum-rest-tracker-api-server/src/server.rs +++ b/packages/axum-rest-tracker-api-server/src/server.rs @@ -247,6 +247,7 @@ impl Launcher { rx_halt: Receiver, ) -> BoxFuture<'static, ()> { let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); + socket.set_nonblocking(true).expect("Failed to set socket to non-blocking mode"); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); let router = router(http_api_container, access_tokens, address); From eccab24403fb95be99f3be3bd05875d2e2ac1916 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 09:07:47 +0000 Subject: [PATCH 1270/1297] style: apply cargo fmt formatting to axum-rest-tracker-api-server Format set_nonblocking call to use multi-line formatting per rustfmt conventions. --- packages/axum-rest-tracker-api-server/src/server.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/axum-rest-tracker-api-server/src/server.rs b/packages/axum-rest-tracker-api-server/src/server.rs index 32c1051e1..05adeae8a 100644 --- a/packages/axum-rest-tracker-api-server/src/server.rs +++ b/packages/axum-rest-tracker-api-server/src/server.rs @@ -247,7 +247,9 @@ impl Launcher { rx_halt: Receiver, ) -> BoxFuture<'static, ()> { let socket = std::net::TcpListener::bind(self.bind_to).expect("Could not bind tcp_listener to address."); - socket.set_nonblocking(true).expect("Failed to set socket to non-blocking mode"); + socket + .set_nonblocking(true) + .expect("Failed to set socket to non-blocking mode"); let address = socket.local_addr().expect("Could not get local_addr from tcp_listener."); let router = router(http_api_container, access_tokens, address); From 38ed4cbc074c7322ba6b898bf424ba935bb419e3 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 22 Dec 2025 16:38:41 +0000 Subject: [PATCH 1271/1297] chore(deps): update dependencies ``` cargo update Updating crates.io index Locking 4 packages to latest compatible versions Updating derive_more v2.1.0 -> v2.1.1 Updating derive_more-impl v2.1.0 -> v2.1.1 Updating reqwest v0.12.26 -> v0.12.27 Updating serde_json v1.0.145 -> v1.0.146 note: pass `--verbose` to see 7 unchanged dependencies behind latest ``` --- Cargo.lock | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index da0910f48..3bdf93e00 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1542,18 +1542,18 @@ dependencies = [ [[package]] name = "derive_more" -version = "2.1.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10b768e943bed7bf2cab53df09f4bc34bfd217cdb57d971e769874c9a6710618" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" dependencies = [ "derive_more-impl", ] [[package]] name = "derive_more-impl" -version = "2.1.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d286bfdaf75e988b4a78e013ecd79c581e06399ab53fbacd2d916c2f904f30b" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" dependencies = [ "convert_case", "proc-macro2", @@ -3819,9 +3819,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.26" +version = "0.12.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b4c14b2d9afca6a60277086b0cc6a6ae0b568f6f7916c943a8cdc79f8be240f" +checksum = "8e893f6bece5953520ddbb3f8f46f3ef36dd1fef4ee9b087c4b4a725fd5d10e4" dependencies = [ "base64 0.22.1", "bytes", @@ -4278,9 +4278,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.145" +version = "1.0.146" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" +checksum = "217ca874ae0207aac254aa02c957ded05585a90892cc8d87f9e5fa49669dadd8" dependencies = [ "indexmap 2.12.1", "itoa", From 767bb5c2ec9e3042ad28d0d36c7a8e1071385889 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 23 Dec 2025 08:58:13 +0000 Subject: [PATCH 1272/1297] fix: [#1628] upgrade to Debian 13 (Trixie) to resolve security vulnerabilities - Update base images from Debian 12 (bookworm) to Debian 13 (trixie) - Update builder: rust:bookworm -> rust:trixie - Update tester: rust:slim-bookworm -> rust:slim-trixie - Update GCC: gcc:bookworm -> gcc:trixie - Update runtime: gcr.io/distroless/cc-debian12:debug -> gcr.io/distroless/cc-debian13:debug This resolves all 5 security vulnerabilities (1 CRITICAL, 4 HIGH): - CVE-2019-1010022 (CRITICAL): glibc stack guard protection bypass - CVE-2018-20796 (HIGH): glibc uncontrolled recursion - CVE-2019-1010023 (HIGH): glibc ldd malicious ELF code execution - CVE-2019-9192 (HIGH): glibc uncontrolled recursion - CVE-2023-0286 (HIGH): OpenSSL X.400 address type confusion Trivy scan results: - Before: Total 5 (CRITICAL: 1, HIGH: 4) - After: Total 0 (CRITICAL: 0, HIGH: 0) Container tested and verified working with health checks passing. --- Containerfile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Containerfile b/Containerfile index 263053390..e926a5202 100644 --- a/Containerfile +++ b/Containerfile @@ -3,13 +3,13 @@ # Torrust Tracker ## Builder Image -FROM docker.io/library/rust:bookworm AS chef +FROM docker.io/library/rust:trixie AS chef WORKDIR /tmp RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash RUN cargo binstall --no-confirm cargo-chef cargo-nextest ## Tester Image -FROM docker.io/library/rust:slim-bookworm AS tester +FROM docker.io/library/rust:slim-trixie AS tester WORKDIR /tmp RUN apt-get update; apt-get install -y curl sqlite3; apt-get autoclean @@ -21,7 +21,7 @@ RUN mkdir -p /app/share/torrust/default/database/; \ sqlite3 /app/share/torrust/default/database/tracker.sqlite3.db "VACUUM;" ## Su Exe Compile -FROM docker.io/library/gcc:bookworm AS gcc +FROM docker.io/library/gcc:trixie AS gcc COPY ./contrib/dev-tools/su-exec/ /usr/local/src/su-exec/ RUN cc -Wall -Werror -g /usr/local/src/su-exec/su-exec.c -o /usr/local/bin/su-exec; chmod +x /usr/local/bin/su-exec @@ -91,7 +91,7 @@ RUN chown -R root:root /app; chmod -R u=rw,go=r,a+X /app; chmod -R a+x /app/bin ## Runtime -FROM gcr.io/distroless/cc-debian12:debug AS runtime +FROM gcr.io/distroless/cc-debian13:debug AS runtime RUN ["/busybox/cp", "-sp", "/busybox/sh","/busybox/cat","/busybox/ls","/busybox/env", "/bin/"] COPY --from=gcc --chmod=0555 /usr/local/bin/su-exec /bin/su-exec From 300be03c24aa769d55b8415d310c2e032cff59ce Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 23 Dec 2025 09:50:17 +0000 Subject: [PATCH 1273/1297] chore(deps): update dependencies ``` cargo update Updating crates.io index Locking 2 packages to latest compatible versions Updating reqwest v0.12.27 -> v0.12.28 Updating rustix v1.1.2 -> v1.1.3 note: pass `--verbose` to see 7 unchanged dependencies behind latest ``` --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3bdf93e00..d0478573b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3819,9 +3819,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.27" +version = "0.12.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e893f6bece5953520ddbb3f8f46f3ef36dd1fef4ee9b087c4b4a725fd5d10e4" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ "base64 0.22.1", "bytes", @@ -4023,9 +4023,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" +checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34" dependencies = [ "bitflags", "errno", From c9c027dfe96fbb4b5558f6519cb936d9ff9f5f1d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 23 Dec 2025 09:58:13 +0000 Subject: [PATCH 1274/1297] chore(deps): bump actions/upload-artifact from 5 to 6 Bumps actions/upload-artifact from 5 to 6. This update includes: - Node.js 24 runtime support - Requires Actions Runner version 2.327.1 or later - Fixes punycode deprecation warnings --- .github/workflows/generate_coverage_pr.yaml | 6 +++--- cSpell.json | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/generate_coverage_pr.yaml b/.github/workflows/generate_coverage_pr.yaml index 6942e276f..f762207cf 100644 --- a/.github/workflows/generate_coverage_pr.yaml +++ b/.github/workflows/generate_coverage_pr.yaml @@ -59,13 +59,13 @@ jobs: # Triggered sub-workflow is not able to detect the original commit/PR which is available # in this workflow. - name: Store PR number - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@v6 with: name: pr_number path: pr_number.txt - name: Store commit SHA - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@v6 with: name: commit_sha path: commit_sha.txt @@ -74,7 +74,7 @@ jobs: # is executed by a different workflow `upload_coverage.yml`. The reason for this # split is because `on.pull_request` workflows don't have access to secrets. - name: Store coverage report in artifacts - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@v6 with: name: codecov_report path: ./codecov.json diff --git a/cSpell.json b/cSpell.json index 76939c199..81421e050 100644 --- a/cSpell.json +++ b/cSpell.json @@ -32,6 +32,7 @@ "canonicalized", "certbot", "chrono", + "Cinstrument", "ciphertext", "clippy", "cloneable", From 8dde9c3e1b217ebd974670f5d309c590e6dba105 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 26 Jan 2026 12:41:33 +0000 Subject: [PATCH 1275/1297] chore(deps): update dependencies ``` cargo update Updating crates.io index Locking 109 packages to latest compatible versions Updating arc-swap v1.7.1 -> v1.8.0 Updating async-compression v0.4.36 -> v0.4.37 Adding aws-lc-rs v1.15.4 Adding aws-lc-sys v0.37.0 Updating axum-core v0.5.5 -> v0.5.6 Updating axum-extra v0.12.3 -> v0.12.5 Updating bigdecimal v0.4.9 -> v0.4.10 Updating cc v1.2.50 -> v1.2.54 Adding cesu8 v1.1.0 Updating chrono v0.4.42 -> v0.4.43 Updating clap v4.5.53 -> v4.5.54 Updating clap_builder v4.5.53 -> v4.5.54 Updating clap_lex v0.7.6 -> v0.7.7 Adding combine v4.6.7 Updating compression-codecs v0.4.35 -> v0.4.36 Adding dunce v1.0.5 Updating ferroid v0.8.8 -> v0.8.9 Updating filetime v0.2.26 -> v0.2.27 Updating find-msvc-tools v0.1.5 -> v0.1.8 Updating flate2 v1.1.5 -> v1.1.8 Adding foldhash v0.2.0 Updating fs-err v3.2.1 -> v3.2.2 Adding fs_extra v1.3.0 Updating getrandom v0.2.16 -> v0.2.17 Updating h2 v0.4.12 -> v0.4.13 Updating hashlink v0.10.0 -> v0.11.0 Removing hyper-tls v0.6.0 Updating indexmap v2.12.1 -> v2.13.0 Updating iri-string v0.7.9 -> v0.7.10 Updating itoa v1.0.16 -> v1.0.17 Adding jni v0.21.1 Adding jni-sys v0.3.0 Updating js-sys v0.3.83 -> v0.3.85 Updating libc v0.2.178 -> v0.2.180 Updating libm v0.2.15 -> v0.2.16 Updating libredox v0.1.11 -> v0.1.12 Updating libsqlite3-sys v0.35.0 -> v0.36.0 Updating local-ip-address v0.6.8 -> v0.6.9 Adding lru-slab v0.1.2 Updating num-conv v0.1.0 -> v0.2.0 Adding openssl-probe v0.2.1 Updating portable-atomic v1.12.0 -> v1.13.0 Updating proc-macro2 v1.0.103 -> v1.0.106 Updating prost v0.14.1 -> v0.14.3 Updating prost-derive v0.14.1 -> v0.14.3 Updating prost-types v0.14.1 -> v0.14.3 Adding quinn v0.11.9 Adding quinn-proto v0.11.13 Adding quinn-udp v0.5.14 Updating quote v1.0.42 -> v1.0.44 Updating r2d2_sqlite v0.31.0 -> v0.32.0 Updating rand_core v0.9.3 -> v0.9.5 Updating redox_syscall v0.6.0 -> v0.7.0 Updating reqwest v0.12.28 -> v0.13.1 Updating rkyv v0.7.45 -> v0.7.46 Updating rkyv_derive v0.7.45 -> v0.7.46 Adding rsqlite-vfs v0.1.0 Updating rusqlite v0.37.0 -> v0.38.0 Updating rust_decimal v1.39.0 -> v1.40.0 Updating rustc-demangle v0.1.26 -> v0.1.27 Updating rustls v0.23.35 -> v0.23.36 Updating rustls-native-certs v0.8.2 -> v0.8.3 Updating rustls-pki-types v1.13.2 -> v1.14.0 Adding rustls-platform-verifier v0.6.2 Adding rustls-platform-verifier-android v0.1.1 Updating rustls-webpki v0.103.8 -> v0.103.9 Updating ryu v1.0.21 -> v1.0.22 Updating schemars v1.1.0 -> v1.2.0 Updating serde_json v1.0.146 -> v1.0.149 Updating signal-hook-registry v1.4.7 -> v1.4.8 Updating socket2 v0.6.1 -> v0.6.2 Adding sqlite-wasm-rs v0.5.2 Updating subprocess v0.2.9 -> v0.2.13 Updating syn v2.0.111 -> v2.0.114 Updating tempfile v3.23.0 -> v3.24.0 Updating testcontainers v0.26.2 -> v0.26.3 Updating thiserror v2.0.17 -> v2.0.18 Updating thiserror-impl v2.0.17 -> v2.0.18 Updating time v0.3.44 -> v0.3.46 Updating time-core v0.1.6 -> v0.1.8 Updating time-macros v0.2.24 -> v0.2.26 Updating tokio v1.48.0 -> v1.49.0 Removing tokio-native-tls v0.3.1 Updating tokio-stream v0.1.17 -> v0.1.18 Updating tokio-util v0.7.17 -> v0.7.18 Updating toml v0.9.10+spec-1.1.0 -> v0.9.11+spec-1.1.0 Updating tower v0.5.2 -> v0.5.3 Updating url v2.5.7 -> v2.5.8 Updating uuid v1.19.0 -> v1.20.0 Updating wasip2 v1.0.1+wasi-0.2.4 -> v1.0.2+wasi-0.2.9 Updating wasm-bindgen v0.2.106 -> v0.2.108 Updating wasm-bindgen-futures v0.4.56 -> v0.4.58 Updating wasm-bindgen-macro v0.2.106 -> v0.2.108 Updating wasm-bindgen-macro-support v0.2.106 -> v0.2.108 Updating wasm-bindgen-shared v0.2.106 -> v0.2.108 Updating web-sys v0.3.83 -> v0.3.85 Adding webpki-root-certs v1.0.5 Updating webpki-roots v1.0.4 -> v1.0.5 Adding windows-sys v0.45.0 Adding windows-targets v0.42.2 Adding windows_aarch64_gnullvm v0.42.2 Adding windows_aarch64_msvc v0.42.2 Adding windows_i686_gnu v0.42.2 Adding windows_i686_msvc v0.42.2 Adding windows_x86_64_gnu v0.42.2 Adding windows_x86_64_gnullvm v0.42.2 Adding windows_x86_64_msvc v0.42.2 Updating wit-bindgen v0.46.0 -> v0.51.0 Updating zerocopy v0.8.31 -> v0.8.34 Updating zerocopy-derive v0.8.31 -> v0.8.34 Adding zmij v1.0.17 note: pass `--verbose` to see 7 unchanged dependencies behind latest ``` --- Cargo.lock | 850 +++++++++++++++++++++++++++++++++++------------------ 1 file changed, 557 insertions(+), 293 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d0478573b..146da3a18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,7 +23,7 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" dependencies = [ - "getrandom 0.2.16", + "getrandom 0.2.17", "once_cell", "version_check", ] @@ -175,9 +175,12 @@ dependencies = [ [[package]] name = "arc-swap" -version = "1.7.1" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457" +checksum = "51d03449bb8ca2cc2ef70869af31463d1ae5ccc8fa3e334b307203fbf815207e" +dependencies = [ + "rustversion", +] [[package]] name = "arrayvec" @@ -236,13 +239,12 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.36" +version = "0.4.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98ec5f6c2f8bc326c994cb9e241cc257ddaba9afa8555a43cffbb5dd86efaa37" +checksum = "d10e4f991a553474232bc0a31799f6d24b034a84c0971d80d2e2f78b2e576e40" dependencies = [ "compression-codecs", "compression-core", - "futures-core", "pin-project-lite", "tokio", ] @@ -352,7 +354,7 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -369,7 +371,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -393,6 +395,28 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +[[package]] +name = "aws-lc-rs" +version = "1.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b7b6141e96a8c160799cc2d5adecd5cbbe5054cb8c7c4af53da0f83bb7ad256" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c34dda4df7017c8db52132f0f8a2e0f8161649d15723ed63fc00c82d0f2081a" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", +] + [[package]] name = "axum" version = "0.8.8" @@ -440,9 +464,9 @@ dependencies = [ [[package]] name = "axum-core" -version = "0.5.5" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59446ce19cd142f8833f856eb31f3eb097812d1479ab224f54d72428ca21ea22" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" dependencies = [ "bytes", "futures-core", @@ -459,9 +483,9 @@ dependencies = [ [[package]] name = "axum-extra" -version = "0.12.3" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dfbd6109d91702d55fc56df06aae7ed85c465a7a451db6c0e54a4b9ca5983d1" +checksum = "fef252edff26ddba56bbcdf2ee3307b8129acb86f5749b68990c168a6fcc9c76" dependencies = [ "axum", "axum-core", @@ -490,7 +514,7 @@ checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -553,9 +577,9 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "bigdecimal" -version = "0.4.9" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "560f42649de9fa436b73517378a147ec21f6c997a546581df4b4b31677828934" +checksum = "4d6867f1565b3aad85681f1015055b087fcfd840d6aeee6eee7f2da317603695" dependencies = [ "autocfg", "libm", @@ -585,7 +609,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -614,7 +638,7 @@ dependencies = [ "mockall", "serde", "serde_json", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "tokio-util", "torrust-tracker-clock", @@ -639,7 +663,7 @@ dependencies = [ "percent-encoding", "serde", "serde_bencode", - "thiserror 2.0.17", + "thiserror 2.0.18", "torrust-tracker-clock", "torrust-tracker-configuration", "torrust-tracker-contrib-bencode", @@ -675,7 +699,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_repr", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "torrust-tracker-configuration", "torrust-tracker-located-error", @@ -701,7 +725,7 @@ dependencies = [ "serde", "serde_json", "testcontainers", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "tokio-util", "torrust-rest-tracker-api-client", @@ -734,7 +758,7 @@ dependencies = [ "mockall", "rand 0.9.2", "serde", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "tokio-util", "torrust-tracker-clock", @@ -847,7 +871,7 @@ dependencies = [ "serde_json", "serde_repr", "serde_urlencoded", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "tokio-stream", "tokio-util", @@ -907,7 +931,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -1018,9 +1042,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.50" +version = "1.2.54" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f50d563227a1c37cc0a263f64eca3334388c01c5e4c4861a9def205c614383c" +checksum = "6354c81bbfd62d9cfa9cb3c773c2b7b2a3a482d569de977fd0e961f6e7c00583" dependencies = [ "find-msvc-tools", "jobserver", @@ -1028,6 +1052,12 @@ dependencies = [ "shlex", ] +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + [[package]] name = "cexpr" version = "0.6.0" @@ -1051,9 +1081,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "chrono" -version = "0.4.42" +version = "0.4.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2" +checksum = "fac4744fb15ae8337dc853fee7fb3f4e48c0fbaa23d0afe49c447b4fab126118" dependencies = [ "iana-time-zone", "num-traits", @@ -1111,9 +1141,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.53" +version = "4.5.54" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9e340e012a1bf4935f5282ed1436d1489548e8f72308207ea5df0e23d2d03f8" +checksum = "c6e6ff9dcd79cff5cd969a17a545d79e84ab086e444102a591e288a8aa3ce394" dependencies = [ "clap_builder", "clap_derive", @@ -1121,9 +1151,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.53" +version = "4.5.54" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d76b5d13eaa18c901fd2f7fca939fefe3a0727a953561fefdf3b2922b8569d00" +checksum = "fa42cf4d2b7a41bc8f663a7cab4031ebafa1bf3875705bfaf8466dc60ab52c00" dependencies = [ "anstream", "anstyle", @@ -1140,14 +1170,14 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] name = "clap_lex" -version = "0.7.6" +version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" +checksum = "c3e64b0cc0439b12df2fa678eae89a1c56a529fd067a9115f7827f1fffd22b32" [[package]] name = "cmake" @@ -1164,6 +1194,16 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "compact_str" version = "0.7.1" @@ -1179,9 +1219,9 @@ dependencies = [ [[package]] name = "compression-codecs" -version = "0.4.35" +version = "0.4.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0f7ac3e5b97fdce45e8922fb05cae2c37f7bbd63d30dd94821dacfd8f3f2bf2" +checksum = "00828ba6fd27b45a448e57dbfe84f1029d4c9f26b368157e9a448a5f49a2ec2a" dependencies = [ "brotli", "compression-core", @@ -1446,7 +1486,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -1460,7 +1500,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -1471,7 +1511,7 @@ checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ "darling_core 0.20.11", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -1482,7 +1522,7 @@ checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" dependencies = [ "darling_core 0.21.3", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -1527,7 +1567,7 @@ dependencies = [ "darling 0.20.11", "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -1537,7 +1577,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" dependencies = [ "derive_builder_core", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -1559,7 +1599,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn 2.0.111", + "syn 2.0.114", "unicode-xid", ] @@ -1571,7 +1611,7 @@ checksum = "ccfae181bab5ab6c5478b2ccb69e4c68a02f8c3ec72f6616bfec9dbc599d2ee0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -1598,7 +1638,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -1618,6 +1658,12 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "dyn-clone" version = "1.0.20" @@ -1722,9 +1768,9 @@ checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "ferroid" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce161062fb044bd629c2393590efd47cab8d0241faf15704ffb0d47b7b4e4a35" +checksum = "bb330bbd4cb7a5b9f559427f06f98a4f853a137c8298f3bd3f8ca57663e21986" dependencies = [ "portable-atomic", "rand 0.9.2", @@ -1749,27 +1795,26 @@ dependencies = [ [[package]] name = "filetime" -version = "0.2.26" +version = "0.2.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc0505cd1b6fa6580283f6bdf70a73fcf4aba1184038c90902b92b3dd0df63ed" +checksum = "f98844151eee8917efc50bd9e8318cb963ae8b297431495d3f758616ea5c57db" dependencies = [ "cfg-if", "libc", "libredox", - "windows-sys 0.60.2", ] [[package]] name = "find-msvc-tools" -version = "0.1.5" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844" +checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db" [[package]] name = "flate2" -version = "1.1.5" +version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfe33edd8e85a12a67454e37f8c75e730830d83e313556ab9ebf9ee7fbeb3bfb" +checksum = "b375d6465b98090a5f25b1c7703f3859783755aa9a80433b36e0379a3ec2f369" dependencies = [ "crc32fast", "libz-sys", @@ -1788,6 +1833,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "foreign-types" version = "0.3.2" @@ -1867,7 +1918,7 @@ checksum = "a0b4095fc99e1d858e5b8c7125d2638372ec85aa0fe6c807105cf10b0265ca6c" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -1879,7 +1930,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -1891,19 +1942,25 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] name = "fs-err" -version = "3.2.1" +version = "3.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824f08d01d0f496b3eca4f001a13cf17690a6ee930043d20817f547455fd98f8" +checksum = "baf68cef89750956493a66a10f512b9e58d9db21f2a573c079c0bdf1207a54a7" dependencies = [ "autocfg", "tokio", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "funty" version = "2.0.0" @@ -1979,7 +2036,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -2030,13 +2087,15 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] @@ -2046,9 +2105,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi", "wasip2", + "wasm-bindgen", ] [[package]] @@ -2060,7 +2121,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -2089,9 +2150,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.12" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" +checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54" dependencies = [ "atomic-waker", "bytes", @@ -2099,7 +2160,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.12.1", + "indexmap 2.13.0", "slab", "tokio", "tokio-util", @@ -2114,7 +2175,7 @@ checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "cfg-if", "crunchy", - "zerocopy 0.8.31", + "zerocopy 0.8.34", ] [[package]] @@ -2140,7 +2201,7 @@ checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ "allocator-api2", "equivalent", - "foldhash", + "foldhash 0.1.5", ] [[package]] @@ -2148,14 +2209,17 @@ name = "hashbrown" version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash 0.2.0", +] [[package]] name = "hashlink" -version = "0.10.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +checksum = "ea0b22561a9c04a7cb1a302c013e0259cd3b4bb619f145b32f72b8b4bcbed230" dependencies = [ - "hashbrown 0.15.5", + "hashbrown 0.16.1", ] [[package]] @@ -2303,22 +2367,6 @@ dependencies = [ "tower-service", ] -[[package]] -name = "hyper-tls" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" -dependencies = [ - "bytes", - "http-body-util", - "hyper", - "hyper-util", - "native-tls", - "tokio", - "tokio-native-tls", - "tower-service", -] - [[package]] name = "hyper-util" version = "0.1.19" @@ -2337,7 +2385,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2 0.6.1", + "socket2 0.6.2", "system-configuration", "tokio", "tower-service", @@ -2505,9 +2553,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.12.1" +version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2" +checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" dependencies = [ "equivalent", "hashbrown 0.16.1", @@ -2547,9 +2595,9 @@ checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" [[package]] name = "iri-string" -version = "0.7.9" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f867b9d1d896b67beb18518eda36fdb77a32ea590de864f1325b294a6d14397" +checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a" dependencies = [ "memchr", "serde", @@ -2607,9 +2655,31 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.16" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni-sys" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ee5b5339afb4c41626dde77b7a611bd4f2c202b897852b4bcf5d03eddc61010" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" [[package]] name = "jobserver" @@ -2623,9 +2693,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.83" +version = "0.3.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8" +checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3" dependencies = [ "once_cell", "wasm-bindgen", @@ -2648,9 +2718,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.178" +version = "0.2.180" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091" +checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc" [[package]] name = "libloading" @@ -2664,26 +2734,26 @@ dependencies = [ [[package]] name = "libm" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.11" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df15f6eac291ed1cf25865b1ee60399f57e7c227e7f51bdbd4c5270396a9ed50" +checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616" dependencies = [ "bitflags", "libc", - "redox_syscall 0.6.0", + "redox_syscall 0.7.0", ] [[package]] name = "libsqlite3-sys" -version = "0.35.0" +version = "0.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f" +checksum = "95b4103cffefa72eb8428cb6b47d6627161e51c2739fc5e3b734584157bc642a" dependencies = [ "cc", "pkg-config", @@ -2715,13 +2785,12 @@ checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" [[package]] name = "local-ip-address" -version = "0.6.8" +version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a60bf300a990b2d1ebdde4228e873e8e4da40d834adbf5265f3da1457ede652" +checksum = "92488bc8a0f99ee9f23577bdd06526d49657df8bd70504c61f812337cdad01ab" dependencies = [ "libc", "neli", - "thiserror 2.0.17", "windows-sys 0.61.2", ] @@ -2752,6 +2821,12 @@ dependencies = [ "hashbrown 0.15.5", ] +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + [[package]] name = "matchit" version = "0.8.4" @@ -2791,7 +2866,7 @@ checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -2850,7 +2925,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -2900,7 +2975,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", "termcolor", "thiserror 1.0.69", ] @@ -2962,7 +3037,7 @@ dependencies = [ "libc", "log", "openssl", - "openssl-probe", + "openssl-probe 0.1.6", "openssl-sys", "schannel", "security-framework 2.11.1", @@ -2996,7 +3071,7 @@ dependencies = [ "proc-macro2", "quote", "serde", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -3059,9 +3134,9 @@ dependencies = [ [[package]] name = "num-conv" -version = "0.1.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" +checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050" [[package]] name = "num-integer" @@ -3153,7 +3228,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -3162,6 +3237,12 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + [[package]] name = "openssl-sys" version = "0.9.111" @@ -3241,7 +3322,7 @@ dependencies = [ "regex", "regex-syntax", "structmeta", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -3264,7 +3345,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -3338,7 +3419,7 @@ checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -3414,9 +3495,9 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f59e70c4aef1e55797c2e8fd94a4f2a973fc972cfde0e0b05f683667b0cd39dd" +checksum = "f89776e4d69bb58bc6993e99ffa1d11f228b839984854c7daeb5d37f87cbe950" [[package]] name = "portable-atomic-util" @@ -3448,7 +3529,7 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ - "zerocopy 0.8.31", + "zerocopy 0.8.34", ] [[package]] @@ -3515,14 +3596,14 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] name = "proc-macro2" -version = "1.0.103" +version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" dependencies = [ "unicode-ident", ] @@ -3535,16 +3616,16 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", "version_check", "yansi", ] [[package]] name = "prost" -version = "0.14.1" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7231bd9b3d3d33c86b58adbac74b5ec0ad9f496b19d22801d773636feaa95f3d" +checksum = "d2ea70524a2f82d518bce41317d0fae74151505651af45faf1ffbd6fd33f0568" dependencies = [ "bytes", "prost-derive", @@ -3552,22 +3633,22 @@ dependencies = [ [[package]] name = "prost-derive" -version = "0.14.1" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9120690fafc389a67ba3803df527d0ec9cbbc9cc45e4cc20b332996dfb672425" +checksum = "27c6023962132f4b30eb4c172c91ce92d933da334c59c23cddee82358ddafb0b" dependencies = [ "anyhow", "itertools 0.14.0", "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] name = "prost-types" -version = "0.14.1" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9b4db3d6da204ed77bb26ba83b6122a73aeb2e87e25fbf7ad2e84c4ccbf8f72" +checksum = "8991c4cbdb8bc5b11f0b074ffe286c30e523de90fee5ba8132f1399f23cb3dd7" dependencies = [ "prost", ] @@ -3603,11 +3684,67 @@ dependencies = [ "rand 0.8.5", ] +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2 0.6.2", + "thiserror 2.0.18", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand 0.9.2", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.18", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2 0.6.2", + "tracing", + "windows-sys 0.60.2", +] + [[package]] name = "quote" -version = "1.0.42" +version = "1.0.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f" +checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" dependencies = [ "proc-macro2", ] @@ -3641,9 +3778,9 @@ dependencies = [ [[package]] name = "r2d2_sqlite" -version = "0.31.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63417e83dc891797eea3ad379f52a5986da4bca0d6ef28baf4d14034dd111b0c" +checksum = "a2ebd03c29250cdf191da93a35118b4567c2ef0eacab54f65e058d6f4c9965f6" dependencies = [ "r2d2", "rusqlite", @@ -3674,7 +3811,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" dependencies = [ "rand_chacha 0.9.0", - "rand_core 0.9.3", + "rand_core 0.9.5", ] [[package]] @@ -3694,7 +3831,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core 0.9.3", + "rand_core 0.9.5", ] [[package]] @@ -3703,14 +3840,14 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom 0.2.16", + "getrandom 0.2.17", ] [[package]] name = "rand_core" -version = "0.9.3" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" dependencies = [ "getrandom 0.3.4", ] @@ -3746,9 +3883,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.6.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec96166dafa0886eb81fe1c0a388bece180fbef2135f97c1e2cf8302e74b43b5" +checksum = "49f3fe0889e69e2ae9e41f4d6c4c0181701d00e4697b356fb1f74173a5e0ee27" dependencies = [ "bitflags", ] @@ -3770,7 +3907,7 @@ checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -3819,9 +3956,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.28" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +checksum = "04e9018c9d814e5f30cc16a0f03271aeab3571e609612d9fe78c1aa8d11c2f62" dependencies = [ "base64 0.22.1", "bytes", @@ -3833,21 +3970,21 @@ dependencies = [ "http-body-util", "hyper", "hyper-rustls", - "hyper-tls", "hyper-util", "js-sys", "log", "mime", - "native-tls", "percent-encoding", "pin-project-lite", + "quinn", + "rustls", "rustls-pki-types", + "rustls-platform-verifier", "serde", "serde_json", - "serde_urlencoded", "sync_wrapper", "tokio", - "tokio-native-tls", + "tokio-rustls", "tower", "tower-http", "tower-service", @@ -3865,7 +4002,7 @@ checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" dependencies = [ "cc", "cfg-if", - "getrandom 0.2.16", + "getrandom 0.2.17", "libc", "untrusted", "windows-sys 0.52.0", @@ -3884,9 +4021,9 @@ dependencies = [ [[package]] name = "rkyv" -version = "0.7.45" +version = "0.7.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9008cd6385b9e161d8229e1f6549dd23c3d022f132a2ea37ac3a10ac4935779b" +checksum = "2297bf9c81a3f0dc96bc9521370b88f054168c29826a75e89c55ff196e7ed6a1" dependencies = [ "bitvec", "bytecheck", @@ -3902,15 +4039,25 @@ dependencies = [ [[package]] name = "rkyv_derive" -version = "0.7.45" +version = "0.7.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "503d1d27590a2b0a3a4ca4c94755aa2875657196ecbf401a42eff41d7de532c0" +checksum = "84d7b42d4b8d06048d3ac8db0eb31bcb942cbeb709f0b5f2b2ebde398d3038f5" dependencies = [ "proc-macro2", "quote", "syn 1.0.109", ] +[[package]] +name = "rsqlite-vfs" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8a1f2315036ef6b1fbacd1972e8ee7688030b0a2121edfc2a6550febd41574d" +dependencies = [ + "hashbrown 0.16.1", + "thiserror 2.0.18", +] + [[package]] name = "rstest" version = "0.25.0" @@ -3948,7 +4095,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.111", + "syn 2.0.114", "unicode-ident", ] @@ -3966,15 +4113,15 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.111", + "syn 2.0.114", "unicode-ident", ] [[package]] name = "rusqlite" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" +checksum = "f1c93dd1c9683b438c392c492109cb702b8090b2bfc8fed6f6e4eb4523f17af3" dependencies = [ "bitflags", "fallible-iterator", @@ -3982,13 +4129,14 @@ dependencies = [ "hashlink", "libsqlite3-sys", "smallvec", + "sqlite-wasm-rs", ] [[package]] name = "rust_decimal" -version = "1.39.0" +version = "1.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35affe401787a9bd846712274d97654355d21b2a2c092a3139aabe31e9022282" +checksum = "61f703d19852dbf87cbc513643fa81428361eb6940f1ac14fd58155d295a3eb0" dependencies = [ "arrayvec", "borsh", @@ -4002,9 +4150,9 @@ dependencies = [ [[package]] name = "rustc-demangle" -version = "0.1.26" +version = "0.1.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" +checksum = "b50b8869d9fc858ce7266cce0194bd74df58b9d0e3f6df3a9fc8eb470d95c09d" [[package]] name = "rustc-hash" @@ -4036,10 +4184,11 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.35" +version = "0.23.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "533f54bc6a7d4f647e46ad909549eda97bf5afc1585190ef692b4286b198bd8f" +checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b" dependencies = [ + "aws-lc-rs", "log", "once_cell", "ring", @@ -4051,11 +4200,11 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9980d917ebb0c0536119ba501e90834767bffc3d60641457fd84a1f3fd337923" +checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63" dependencies = [ - "openssl-probe", + "openssl-probe 0.2.1", "rustls-pki-types", "schannel", "security-framework 3.5.1", @@ -4072,19 +4221,48 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.13.2" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21e6f2ab2928ca4291b86736a8bd920a277a399bba1589409d72154ff87c1282" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" dependencies = [ + "web-time", "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework 3.5.1", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" + [[package]] name = "rustls-webpki" -version = "0.103.8" +version = "0.103.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ffdfa2f5286e2247234e03f680868ac2815974dc39e00ea15adc445d0aafe52" +checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53" dependencies = [ + "aws-lc-rs", "ring", "rustls-pki-types", "untrusted", @@ -4098,9 +4276,9 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "ryu" -version = "1.0.21" +version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62049b2877bf12821e8f9ad256ee38fdc31db7387ec2d3b3f403024de2034aea" +checksum = "a50f4cf475b65d88e057964e0e9bb1f0aa9bbb2036dc65c64596b42932536984" [[package]] name = "same-file" @@ -4149,9 +4327,9 @@ dependencies = [ [[package]] name = "schemars" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9558e172d4e8533736ba97870c4b2cd63f84b382a3d6eb063da41b91cce17289" +checksum = "54e910108742c57a770f492731f99be216a52fadd361b06c8fb59d74ccc267d2" dependencies = [ "dyn-clone", "ref-cast", @@ -4260,7 +4438,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -4270,7 +4448,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2f2d7ff8a2140333718bb329f5c40fc5f0865b84c426183ce14c97d2ab8154f" dependencies = [ "form_urlencoded", - "indexmap 2.12.1", + "indexmap 2.13.0", "itoa", "ryu", "serde_core", @@ -4278,16 +4456,16 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.146" +version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "217ca874ae0207aac254aa02c957ded05585a90892cc8d87f9e5fa49669dadd8" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" dependencies = [ - "indexmap 2.12.1", + "indexmap 2.13.0", "itoa", "memchr", - "ryu", "serde", "serde_core", + "zmij", ] [[package]] @@ -4309,7 +4487,7 @@ checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -4352,9 +4530,9 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.12.1", + "indexmap 2.13.0", "schemars 0.9.0", - "schemars 1.1.0", + "schemars 1.2.0", "serde_core", "serde_json", "serde_with_macros", @@ -4370,7 +4548,7 @@ dependencies = [ "darling 0.21.3", "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -4412,10 +4590,11 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "signal-hook-registry" -version = "1.4.7" +version = "1.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7664a098b8e616bdfcc2dc0e9ac44eb231eedf41db4e9fe95d8d32ec728dedad" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" dependencies = [ + "errno", "libc", ] @@ -4461,14 +4640,26 @@ dependencies = [ [[package]] name = "socket2" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881" +checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0" dependencies = [ "libc", "windows-sys 0.60.2", ] +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4206ed3a67690b9c29b77d728f6acc3ce78f16bf846d83c94f76400320181b" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -4496,7 +4687,7 @@ dependencies = [ "proc-macro2", "quote", "structmeta-derive", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -4507,14 +4698,14 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] name = "subprocess" -version = "0.2.9" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c2e86926081dda636c546d8c5e641661049d7562a68f5488be4a1f7f66f6086" +checksum = "f75238edb5be30a9ea3035b945eb9c319dde80e879411cdc9a8978e1ac822960" dependencies = [ "libc", "winapi", @@ -4560,9 +4751,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.111" +version = "2.0.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "390cc9a294ab71bdb1aa2e99d13be9c753cd2d7bd6560c77118597410c4d2e87" +checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a" dependencies = [ "proc-macro2", "quote", @@ -4586,7 +4777,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -4635,9 +4826,9 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.23.0" +version = "3.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16" +checksum = "655da9c7eb6305c55742045d5a8d2037996d61d8de95806335c7c86ce0f82e9c" dependencies = [ "fastrand", "getrandom 0.3.4", @@ -4673,9 +4864,9 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "testcontainers" -version = "0.26.2" +version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1483605f58b2fff80d786eb56a0b6b4e8b1e5423fbc9ec2e3e562fa2040d6f27" +checksum = "a81ec0158db5fbb9831e09d1813fe5ea9023a2b5e6e8e0a5fe67e2a820733629" dependencies = [ "astral-tokio-tar", "async-trait", @@ -4694,7 +4885,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "tokio-stream", "tokio-util", @@ -4722,11 +4913,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.17" +version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" dependencies = [ - "thiserror-impl 2.0.17", + "thiserror-impl 2.0.18", ] [[package]] @@ -4737,18 +4928,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] name = "thiserror-impl" -version = "2.0.17" +version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -4762,30 +4953,30 @@ dependencies = [ [[package]] name = "time" -version = "0.3.44" +version = "0.3.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d" +checksum = "9da98b7d9b7dad93488a84b8248efc35352b0b2657397d4167e7ad67e5d535e5" dependencies = [ "deranged", "itoa", "num-conv", "powerfmt", - "serde", + "serde_core", "time-core", "time-macros", ] [[package]] name = "time-core" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" [[package]] name = "time-macros" -version = "0.2.24" +version = "0.2.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3" +checksum = "78cc610bac2dcee56805c99642447d4c5dbde4d01f752ffea0199aee1f601dc4" dependencies = [ "num-conv", "time-core", @@ -4828,16 +5019,16 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.48.0" +version = "1.49.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" +checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86" dependencies = [ "bytes", "libc", "mio", "pin-project-lite", "signal-hook-registry", - "socket2 0.6.1", + "socket2 0.6.2", "tokio-macros", "windows-sys 0.61.2", ] @@ -4850,17 +5041,7 @@ checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", -] - -[[package]] -name = "tokio-native-tls" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" -dependencies = [ - "native-tls", - "tokio", + "syn 2.0.114", ] [[package]] @@ -4875,9 +5056,9 @@ dependencies = [ [[package]] name = "tokio-stream" -version = "0.1.17" +version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047" +checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" dependencies = [ "futures-core", "pin-project-lite", @@ -4886,9 +5067,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.17" +version = "0.7.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2efa149fe76073d6e8fd97ef4f4eca7b67f599660115591483572e406e165594" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" dependencies = [ "bytes", "futures-core", @@ -4911,11 +5092,11 @@ dependencies = [ [[package]] name = "toml" -version = "0.9.10+spec-1.1.0" +version = "0.9.11+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0825052159284a1a8b4d6c0c86cbc801f2da5afd2b225fa548c72f2e74002f48" +checksum = "f3afc9a848309fe1aaffaed6e1546a7a14de1f935dc9d89d32afd9a44bab7c46" dependencies = [ - "indexmap 2.12.1", + "indexmap 2.13.0", "serde_core", "serde_spanned 1.0.4", "toml_datetime 0.7.5+spec-1.1.0", @@ -4948,7 +5129,7 @@ version = "0.22.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ - "indexmap 2.12.1", + "indexmap 2.13.0", "serde", "serde_spanned 0.6.9", "toml_datetime 0.6.11", @@ -4962,7 +5143,7 @@ version = "0.23.10+spec-1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84c8b9f757e028cee9fa244aea147aab2a9ec09d5325a9b01e0a49730c2b5269" dependencies = [ - "indexmap 2.12.1", + "indexmap 2.13.0", "toml_datetime 0.7.5+spec-1.1.0", "toml_parser", "winnow", @@ -5008,7 +5189,7 @@ dependencies = [ "hyper-util", "percent-encoding", "pin-project", - "socket2 0.6.1", + "socket2 0.6.2", "sync_wrapper", "tokio", "tokio-stream", @@ -5118,7 +5299,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "torrust-axum-server", "torrust-rest-tracker-api-client", @@ -5149,7 +5330,7 @@ dependencies = [ "hyper", "hyper-util", "pin-project-lite", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "torrust-server-lib", "torrust-tracker-configuration", @@ -5165,7 +5346,7 @@ dependencies = [ "hyper", "reqwest", "serde", - "thiserror 2.0.17", + "thiserror 2.0.18", "url", "uuid", ] @@ -5220,7 +5401,7 @@ dependencies = [ "reqwest", "serde", "serde_json", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "tokio-util", "torrust-axum-health-check-api-server", @@ -5256,7 +5437,7 @@ dependencies = [ "serde_bencode", "serde_bytes", "serde_json", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "torrust-tracker-configuration", "tracing", @@ -5284,8 +5465,8 @@ dependencies = [ "serde", "serde_json", "serde_with", - "thiserror 2.0.17", - "toml 0.9.10+spec-1.1.0", + "thiserror 2.0.18", + "toml 0.9.11+spec-1.1.0", "torrust-tracker-located-error", "tracing", "tracing-subscriber", @@ -5298,7 +5479,7 @@ name = "torrust-tracker-contrib-bencode" version = "3.0.0-develop" dependencies = [ "criterion 0.8.1", - "thiserror 2.0.17", + "thiserror 2.0.18", ] [[package]] @@ -5314,7 +5495,7 @@ dependencies = [ name = "torrust-tracker-located-error" version = "3.0.0-develop" dependencies = [ - "thiserror 2.0.17", + "thiserror 2.0.18", "tracing", ] @@ -5330,7 +5511,7 @@ dependencies = [ "rstest 0.25.0", "serde", "serde_json", - "thiserror 2.0.17", + "thiserror 2.0.18", "torrust-tracker-primitives", "tracing", ] @@ -5347,7 +5528,7 @@ dependencies = [ "serde", "tdyne-peer-id", "tdyne-peer-id-registry", - "thiserror 2.0.17", + "thiserror 2.0.18", "torrust-tracker-configuration", "url", "zerocopy 0.7.35", @@ -5368,7 +5549,7 @@ dependencies = [ "rand 0.9.2", "rstest 0.26.1", "serde", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "tokio-util", "torrust-tracker-clock", @@ -5427,7 +5608,7 @@ dependencies = [ "rand 0.9.2", "ringbuf", "serde", - "thiserror 2.0.17", + "thiserror 2.0.18", "tokio", "tokio-util", "torrust-server-lib", @@ -5446,13 +5627,13 @@ dependencies = [ [[package]] name = "tower" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", - "indexmap 2.12.1", + "indexmap 2.13.0", "pin-project-lite", "slab", "sync_wrapper", @@ -5519,7 +5700,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -5674,14 +5855,15 @@ dependencies = [ [[package]] name = "url" -version = "2.5.7" +version = "2.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" dependencies = [ "form_urlencoded", "idna", "percent-encoding", "serde", + "serde_derive", ] [[package]] @@ -5704,9 +5886,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.19.0" +version = "1.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2e054861b4bd027cd373e18e8d8d8e6548085000e41290d95ce0c373a654b4a" +checksum = "ee48d38b119b0cd71fe4141b30f5ba9c7c5d9f4e7a3a8b4a674e4b6ef789976f" dependencies = [ "getrandom 0.3.4", "js-sys", @@ -5765,18 +5947,18 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasip2" -version = "1.0.1+wasi-0.2.4" +version = "1.0.2+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" dependencies = [ "wit-bindgen", ] [[package]] name = "wasm-bindgen" -version = "0.2.106" +version = "0.2.108" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" +checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566" dependencies = [ "cfg-if", "once_cell", @@ -5787,11 +5969,12 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.56" +version = "0.4.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836d9622d604feee9e5de25ac10e3ea5f2d65b41eac0d9ce72eb5deae707ce7c" +checksum = "70a6e77fd0ae8029c9ea0063f87c46fde723e7d887703d74ad2616d792e51e6f" dependencies = [ "cfg-if", + "futures-util", "js-sys", "once_cell", "wasm-bindgen", @@ -5800,9 +5983,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.106" +version = "0.2.108" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3" +checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -5810,31 +5993,31 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.106" +version = "0.2.108" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40" +checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.106" +version = "0.2.108" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4" +checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12" dependencies = [ "unicode-ident", ] [[package]] name = "web-sys" -version = "0.3.83" +version = "0.3.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b32828d774c412041098d182a8b38b16ea816958e07cf40eec2bc080ae137ac" +checksum = "312e32e551d92129218ea9a2452120f4aabc03529ef03e4d0d82fb2780608598" dependencies = [ "js-sys", "wasm-bindgen", @@ -5850,11 +6033,20 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36a29fc0408b113f68cf32637857ab740edfafdf460c326cd2afaa2d84cc05dc" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webpki-roots" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2878ef029c47c6e8cf779119f20fcf52bde7ad42a731b2a304bc221df17571e" +checksum = "12bed680863276c63889429bfd6cab3b99943659923822de1c8a39c49e4d722c" dependencies = [ "rustls-pki-types", ] @@ -5911,7 +6103,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -5922,7 +6114,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -5960,6 +6152,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + [[package]] name = "windows-sys" version = "0.52.0" @@ -5987,6 +6188,21 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + [[package]] name = "windows-targets" version = "0.52.6" @@ -6020,6 +6236,12 @@ dependencies = [ "windows_x86_64_msvc 0.53.1", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -6032,6 +6254,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" @@ -6044,6 +6272,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -6068,6 +6302,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + [[package]] name = "windows_i686_msvc" version = "0.52.6" @@ -6080,6 +6320,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" @@ -6092,6 +6338,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" @@ -6104,6 +6356,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -6127,9 +6385,9 @@ dependencies = [ [[package]] name = "wit-bindgen" -version = "0.46.0" +version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" [[package]] name = "writeable" @@ -6181,7 +6439,7 @@ checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", "synstructure", ] @@ -6197,11 +6455,11 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.31" +version = "0.8.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd74ec98b9250adb3ca554bdde269adf631549f51d8a8f8f0a10b50f1cb298c3" +checksum = "71ddd76bcebeed25db614f82bf31a9f4222d3fbba300e6fb6c00afa26cbd4d9d" dependencies = [ - "zerocopy-derive 0.8.31", + "zerocopy-derive 0.8.34", ] [[package]] @@ -6212,18 +6470,18 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] name = "zerocopy-derive" -version = "0.8.31" +version = "0.8.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8a8d209fdf45cf5138cbb5a506f6b52522a25afccc534d1475dad8e31105c6a" +checksum = "d8187381b52e32220d50b255276aa16a084ec0a9017a0ca2152a1f55c539758d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] [[package]] @@ -6243,7 +6501,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", "synstructure", ] @@ -6283,9 +6541,15 @@ checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.111", + "syn 2.0.114", ] +[[package]] +name = "zmij" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02aae0f83f69aafc94776e879363e9771d7ecbffe2c7fbb6c14c5e00dfe88439" + [[package]] name = "zstd" version = "0.13.3" From 457a020c704d3ec084c0df222c15ca00e1c83f82 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 26 Jan 2026 13:06:09 +0000 Subject: [PATCH 1276/1297] fix: enable reqwest query feature for API compatibility reqwest 0.13 made the feature optional and disabled by default. This commit adds the feature to the reqwest dependency in the rest-tracker-api-client package to restore query parameter functionality. --- Cargo.lock | 1 + packages/rest-tracker-api-client/Cargo.toml | 2 +- .../rest-tracker-api-client/src/v1/client.rs | 20 +++++++++---------- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 146da3a18..8916a6640 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3982,6 +3982,7 @@ dependencies = [ "rustls-platform-verifier", "serde", "serde_json", + "serde_urlencoded", "sync_wrapper", "tokio", "tokio-rustls", diff --git a/packages/rest-tracker-api-client/Cargo.toml b/packages/rest-tracker-api-client/Cargo.toml index cba580e18..c01b9c05a 100644 --- a/packages/rest-tracker-api-client/Cargo.toml +++ b/packages/rest-tracker-api-client/Cargo.toml @@ -16,7 +16,7 @@ version.workspace = true [dependencies] hyper = "1" -reqwest = { version = "0", features = ["json"] } +reqwest = { version = "0", features = ["json", "query"] } serde = { version = "1", features = ["derive"] } thiserror = "2" url = { version = "2", features = ["serde"] } diff --git a/packages/rest-tracker-api-client/src/v1/client.rs b/packages/rest-tracker-api-client/src/v1/client.rs index 3137b8b41..02a5b0d9c 100644 --- a/packages/rest-tracker-api-client/src/v1/client.rs +++ b/packages/rest-tracker-api-client/src/v1/client.rs @@ -204,22 +204,22 @@ impl Client { /// /// Will panic if the request can't be sent pub async fn get(path: Url, query: Option, headers: Option) -> Response { - let builder = reqwest::Client::builder() + let client = reqwest::Client::builder() .timeout(Duration::from_secs(DEFAULT_REQUEST_TIMEOUT_IN_SECS)) .build() .unwrap(); - let builder = match query { - Some(params) => builder.get(path).query(&ReqwestQuery::from(params)), - None => builder.get(path), - }; + let mut request_builder = client.get(path); - let builder = match headers { - Some(headers) => builder.headers(headers), - None => builder, - }; + if let Some(params) = query { + request_builder = request_builder.query(&ReqwestQuery::from(params)); + } + + if let Some(headers) = headers { + request_builder = request_builder.headers(headers); + } - builder.send().await.unwrap() + request_builder.send().await.unwrap() } /// Returns a `HeaderMap` with a request id header. From ac47c1b26a068cf371c35fe40660ccfb564f1de2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Mon, 26 Jan 2026 14:08:13 +0000 Subject: [PATCH 1277/1297] fix: suppress clippy warnings for large error types in config tests --- packages/configuration/src/v2_0_0/mod.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/configuration/src/v2_0_0/mod.rs b/packages/configuration/src/v2_0_0/mod.rs index 8391ba0e1..b3fbc881e 100644 --- a/packages/configuration/src/v2_0_0/mod.rs +++ b/packages/configuration/src/v2_0_0/mod.rs @@ -521,6 +521,7 @@ mod tests { } #[test] + #[allow(clippy::result_large_err)] fn configuration_should_use_the_default_values_when_only_the_mandatory_options_are_provided_by_the_user_via_toml_file() { figment::Jail::expect_with(|jail| { jail.create_file( @@ -552,6 +553,7 @@ mod tests { } #[test] + #[allow(clippy::result_large_err)] fn configuration_should_use_the_default_values_when_only_the_mandatory_options_are_provided_by_the_user_via_toml_content() { figment::Jail::expect_with(|_jail| { let config_toml = r#" @@ -581,6 +583,7 @@ mod tests { } #[test] + #[allow(clippy::result_large_err)] fn default_configuration_could_be_overwritten_from_a_single_env_var_with_toml_contents() { figment::Jail::expect_with(|_jail| { let config_toml = r#" @@ -613,6 +616,7 @@ mod tests { } #[test] + #[allow(clippy::result_large_err)] fn default_configuration_could_be_overwritten_from_a_toml_config_file() { figment::Jail::expect_with(|jail| { jail.create_file( @@ -646,6 +650,7 @@ mod tests { }); } + #[allow(clippy::result_large_err)] #[test] fn configuration_should_allow_to_overwrite_the_default_tracker_api_token_for_admin_with_an_env_var() { figment::Jail::expect_with(|jail| { From 046d5c982e34f7ace34e5e5355c8b72f540ad583 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 20 Feb 2026 11:08:46 +0000 Subject: [PATCH 1278/1297] chore(deps): update dependencies ``` cargo update Updating crates.io index Locking 98 packages to latest compatible versions Updating anyhow v1.0.100 -> v1.0.102 Updating arc-swap v1.8.0 -> v1.8.2 Updating async-compression v0.4.37 -> v0.4.40 Updating async-executor v1.13.3 -> v1.14.0 Updating aws-lc-rs v1.15.4 -> v1.16.0 Updating aws-lc-sys v0.37.0 -> v0.37.1 Updating bitflags v2.10.0 -> v2.11.0 Updating bollard v0.19.4 -> v0.20.1 Updating bollard-stubs v1.49.1-rc.28.4.0 -> v1.52.1-rc.29.1.3 Updating bumpalo v3.19.1 -> v3.20.2 Updating bytemuck v1.24.0 -> v1.25.0 Updating bytes v1.11.0 -> v1.11.1 Updating cc v1.2.54 -> v1.2.56 Adding chacha20 v0.10.0 Adding cipher v0.5.0 Updating clap v4.5.54 -> v4.5.60 Updating clap_builder v4.5.54 -> v4.5.60 Updating clap_derive v4.5.49 -> v4.5.55 Updating clap_lex v0.7.7 -> v1.0.0 Updating compression-codecs v0.4.36 -> v0.4.37 Adding cpufeatures v0.3.0 Updating criterion v0.8.1 -> v0.8.2 Updating criterion-plot v0.8.1 -> v0.8.2 Adding crypto-common v0.2.0 Updating deranged v0.5.5 -> v0.5.6 Adding env_filter v1.0.0 Updating env_logger v0.8.4 -> v0.11.9 Updating find-msvc-tools v0.1.8 -> v0.1.9 Updating flate2 v1.1.8 -> v1.1.9 Updating fs-err v3.2.2 -> v3.3.0 Updating futures v0.3.31 -> v0.3.32 Updating futures-channel v0.3.31 -> v0.3.32 Updating futures-core v0.3.31 -> v0.3.32 Updating futures-executor v0.3.31 -> v0.3.32 Updating futures-io v0.3.31 -> v0.3.32 Updating futures-macro v0.3.31 -> v0.3.32 Updating futures-sink v0.3.31 -> v0.3.32 Updating futures-task v0.3.31 -> v0.3.32 Updating futures-util v0.3.31 -> v0.3.32 Adding getrandom v0.4.1 Adding hybrid-array v0.4.7 Updating hyper-util v0.1.19 -> v0.1.20 Updating iana-time-zone v0.1.64 -> v0.1.65 Adding id-arena v2.3.0 Adding inout v0.2.2 Adding leb128fmt v0.1.0 Updating libc v0.2.180 -> v0.2.182 Updating local-ip-address v0.6.9 -> v0.6.10 Updating memchr v2.7.6 -> v2.8.0 Updating native-tls v0.2.14 -> v0.2.18 Updating neli v0.7.3 -> v0.7.4 Removing openssl-probe v0.1.6 Updating portable-atomic v1.13.0 -> v1.13.1 Updating portable-atomic-util v0.2.4 -> v0.2.5 Updating predicates v3.1.3 -> v3.1.4 Updating predicates-core v1.0.9 -> v1.0.10 Updating predicates-tree v1.0.12 -> v1.0.13 Adding prettyplease v0.2.37 Updating quickcheck v1.0.3 -> v1.1.0 Adding rand v0.10.0 Adding rand_core v0.10.0 Updating redox_syscall v0.7.0 -> v0.7.1 Updating regex v1.12.2 -> v1.12.3 Updating regex-automata v0.4.13 -> v0.4.14 Updating regex-syntax v0.8.8 -> v0.8.9 Updating reqwest v0.13.1 -> v0.13.2 Removing rustls-pemfile v2.2.0 Updating ryu v1.0.22 -> v1.0.23 Updating schemars v1.2.0 -> v1.2.1 Removing security-framework v2.11.1 Removing security-framework v3.5.1 Adding security-framework v3.7.0 Updating security-framework-sys v2.15.0 -> v2.17.0 Updating siphasher v1.0.1 -> v1.0.2 Updating slab v0.4.11 -> v0.4.12 Updating subprocess v0.2.13 -> v0.2.15 Updating syn v2.0.114 -> v2.0.117 Updating system-configuration v0.6.1 -> v0.7.0 Updating tempfile v3.24.0 -> v3.25.0 Updating testcontainers v0.26.3 -> v0.27.0 Updating time v0.3.46 -> v0.3.47 Updating time-macros v0.2.26 -> v0.2.27 Updating toml v0.9.11+spec-1.1.0 -> v0.9.12+spec-1.1.0 (available: v1.0.3+spec-1.1.0) Updating toml_parser v1.0.6+spec-1.1.0 -> v1.0.9+spec-1.1.0 Updating tonic v0.14.2 -> v0.14.5 Updating tonic-prost v0.14.2 -> v0.14.5 Updating unicode-ident v1.0.22 -> v1.0.24 Updating ureq v3.1.4 -> v3.2.0 Updating uuid v1.20.0 -> v1.21.0 Adding wasip3 v0.4.0+wasi-0.3.0-rc-2026-01-06 Adding wasm-encoder v0.244.0 Adding wasm-metadata v0.244.0 Adding wasmparser v0.244.0 Updating webpki-root-certs v1.0.5 -> v1.0.6 Removing webpki-roots v1.0.5 Adding wit-bindgen-core v0.51.0 Adding wit-bindgen-rust v0.51.0 Adding wit-bindgen-rust-macro v0.51.0 Adding wit-component v0.244.0 Adding wit-parser v0.244.0 Updating zerocopy v0.8.34 -> v0.8.39 Updating zerocopy-derive v0.8.34 -> v0.8.39 Updating zmij v1.0.17 -> v1.0.21 note: pass `--verbose` to see 7 unchanged dependencies behind latest ``` --- Cargo.lock | 767 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 485 insertions(+), 282 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8916a6640..e801b94cb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -134,9 +134,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.100" +version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" [[package]] name = "approx" @@ -175,9 +175,9 @@ dependencies = [ [[package]] name = "arc-swap" -version = "1.8.0" +version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d03449bb8ca2cc2ef70869af31463d1ae5ccc8fa3e334b307203fbf815207e" +checksum = "f9f3647c145568cec02c42054e07bdf9a5a698e15b466fb2341bfc393cd24aa5" dependencies = [ "rustversion", ] @@ -239,9 +239,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.37" +version = "0.4.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d10e4f991a553474232bc0a31799f6d24b034a84c0971d80d2e2f78b2e576e40" +checksum = "7d67d43201f4d20c78bcda740c142ca52482d81da80681533d33bf3f0596c8e2" dependencies = [ "compression-codecs", "compression-core", @@ -251,9 +251,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.13.3" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "497c00e0fd83a72a79a39fcbd8e3e2f055d6f6c7e025f3b3d91f4f8e76527fb8" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" dependencies = [ "async-task", "concurrent-queue", @@ -354,7 +354,7 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -371,7 +371,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -397,9 +397,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "aws-lc-rs" -version = "1.15.4" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b7b6141e96a8c160799cc2d5adecd5cbbe5054cb8c7c4af53da0f83bb7ad256" +checksum = "d9a7b350e3bb1767102698302bc37256cbd48422809984b98d292c40e2579aa9" dependencies = [ "aws-lc-sys", "zeroize", @@ -407,9 +407,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.37.0" +version = "0.37.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c34dda4df7017c8db52132f0f8a2e0f8161649d15723ed63fc00c82d0f2081a" +checksum = "b092fe214090261288111db7a2b2c2118e5a7f30dc2569f1732c4069a6840549" dependencies = [ "cc", "cmake", @@ -514,7 +514,7 @@ checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -609,7 +609,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -620,9 +620,9 @@ checksum = "02b4ff8b16e6076c3e14220b39fbc1fabb6737522281a388998046859400895f" [[package]] name = "bitflags" -version = "2.10.0" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" [[package]] name = "bittorrent-http-tracker-core" @@ -721,7 +721,7 @@ dependencies = [ "r2d2", "r2d2_mysql", "r2d2_sqlite", - "rand 0.9.2", + "rand 0.10.0", "serde", "serde_json", "testcontainers", @@ -751,12 +751,12 @@ dependencies = [ "bittorrent-udp-tracker-protocol", "bloom", "blowfish", - "cipher", + "cipher 0.5.0", "criterion 0.5.1", "futures", "lazy_static", "mockall", - "rand 0.9.2", + "rand 0.10.0", "serde", "thiserror 2.0.18", "tokio", @@ -831,14 +831,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7" dependencies = [ "byteorder", - "cipher", + "cipher 0.4.4", ] [[package]] name = "bollard" -version = "0.19.4" +version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87a52479c9237eb04047ddb94788c41ca0d26eaff8b697ecfbb4c32f7fdc3b1b" +checksum = "227aa051deec8d16bd9c34605e7aaf153f240e35483dd42f6f78903847934738" dependencies = [ "async-stream", "base64 0.22.1", @@ -846,7 +846,6 @@ dependencies = [ "bollard-buildkit-proto", "bollard-stubs", "bytes", - "chrono", "futures-core", "futures-util", "hex", @@ -864,14 +863,13 @@ dependencies = [ "rand 0.9.2", "rustls", "rustls-native-certs", - "rustls-pemfile", "rustls-pki-types", "serde", "serde_derive", "serde_json", - "serde_repr", "serde_urlencoded", "thiserror 2.0.18", + "time", "tokio", "tokio-stream", "tokio-util", @@ -896,19 +894,18 @@ dependencies = [ [[package]] name = "bollard-stubs" -version = "1.49.1-rc.28.4.0" +version = "1.52.1-rc.29.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5731fe885755e92beff1950774068e0cae67ea6ec7587381536fca84f1779623" +checksum = "0f0a8ca8799131c1837d1282c3f81f31e76ceb0ce426e04a7fe1ccee3287c066" dependencies = [ "base64 0.22.1", "bollard-buildkit-proto", "bytes", - "chrono", "prost", "serde", "serde_json", "serde_repr", - "serde_with", + "time", ] [[package]] @@ -931,7 +928,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -972,9 +969,9 @@ checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" [[package]] name = "bumpalo" -version = "3.19.1" +version = "3.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" [[package]] name = "bytecheck" @@ -1000,9 +997,9 @@ dependencies = [ [[package]] name = "bytemuck" -version = "1.24.0" +version = "1.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbdf580320f38b612e485521afda1ee26d10cc9884efaaa750d383e13e3c5f4" +checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" [[package]] name = "byteorder" @@ -1012,9 +1009,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.11.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" [[package]] name = "camino" @@ -1042,9 +1039,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.54" +version = "1.2.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6354c81bbfd62d9cfa9cb3c773c2b7b2a3a482d569de977fd0e961f6e7c00583" +checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2" dependencies = [ "find-msvc-tools", "jobserver", @@ -1079,6 +1076,17 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +[[package]] +name = "chacha20" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "rand_core 0.10.0", +] + [[package]] name = "chrono" version = "0.4.43" @@ -1124,8 +1132,18 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", - "inout", + "crypto-common 0.1.7", + "inout 0.1.4", +] + +[[package]] +name = "cipher" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64727038c8c5e2bb503a15b9f5b9df50a1da9a33e83e1f93067d914f2c6604a5" +dependencies = [ + "crypto-common 0.2.0", + "inout 0.2.2", ] [[package]] @@ -1141,9 +1159,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.54" +version = "4.5.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6e6ff9dcd79cff5cd969a17a545d79e84ab086e444102a591e288a8aa3ce394" +checksum = "2797f34da339ce31042b27d23607e051786132987f595b02ba4f6a6dffb7030a" dependencies = [ "clap_builder", "clap_derive", @@ -1151,9 +1169,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.54" +version = "4.5.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa42cf4d2b7a41bc8f663a7cab4031ebafa1bf3875705bfaf8466dc60ab52c00" +checksum = "24a241312cea5059b13574bb9b3861cabf758b879c15190b37b6d6fd63ab6876" dependencies = [ "anstream", "anstyle", @@ -1163,21 +1181,21 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.49" +version = "4.5.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a0b5487afeab2deb2ff4e03a807ad1a03ac532ff5a2cee5d86884440c7f7671" +checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] name = "clap_lex" -version = "0.7.7" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3e64b0cc0439b12df2fa678eae89a1c56a529fd067a9115f7827f1fffd22b32" +checksum = "3a822ea5bc7590f9d40f1ba12c0dc3c2760f3482c6984db1573ad11031420831" [[package]] name = "cmake" @@ -1219,9 +1237,9 @@ dependencies = [ [[package]] name = "compression-codecs" -version = "0.4.36" +version = "0.4.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00828ba6fd27b45a448e57dbfe84f1029d4c9f26b368157e9a448a5f49a2ec2a" +checksum = "eb7b51a7d9c967fc26773061ba86150f19c50c0d65c887cb1fbe295fd16619b7" dependencies = [ "brotli", "compression-core", @@ -1290,6 +1308,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.0" @@ -1329,16 +1356,16 @@ dependencies = [ [[package]] name = "criterion" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d883447757bb0ee46f233e9dc22eb84d93a9508c9b868687b274fc431d886bf" +checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3" dependencies = [ "alloca", "anes", "cast", "ciborium", "clap", - "criterion-plot 0.8.1", + "criterion-plot 0.8.2", "itertools 0.13.0", "num-traits", "oorandom", @@ -1365,9 +1392,9 @@ dependencies = [ [[package]] name = "criterion-plot" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed943f81ea2faa8dcecbbfa50164acf95d555afec96a27871663b300e387b2e4" +checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea" dependencies = [ "cast", "itertools 0.13.0", @@ -1455,6 +1482,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "211f05e03c7d03754740fd9e585de910a095d6b99f8bcfffdef8319fa02a8331" +dependencies = [ + "hybrid-array", +] + [[package]] name = "darling" version = "0.20.11" @@ -1486,7 +1522,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -1500,7 +1536,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -1511,7 +1547,7 @@ checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ "darling_core 0.20.11", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -1522,7 +1558,7 @@ checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" dependencies = [ "darling_core 0.21.3", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -1541,9 +1577,9 @@ dependencies = [ [[package]] name = "deranged" -version = "0.5.5" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ececcb659e7ba858fb4f10388c250a7252eb0a27373f1a72b8748afdd248e587" +checksum = "cc3dc5ad92c2e2d1c193bbbbdf2ea477cb81331de4f3103f267ca18368b988c4" dependencies = [ "powerfmt", "serde_core", @@ -1567,7 +1603,7 @@ dependencies = [ "darling 0.20.11", "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -1577,7 +1613,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" dependencies = [ "derive_builder_core", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -1599,7 +1635,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn 2.0.114", + "syn 2.0.117", "unicode-xid", ] @@ -1611,7 +1647,7 @@ checksum = "ccfae181bab5ab6c5478b2ccb69e4c68a02f8c3ec72f6616bfec9dbc599d2ee0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -1627,7 +1663,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", - "crypto-common", + "crypto-common 0.1.7", ] [[package]] @@ -1638,7 +1674,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -1686,15 +1722,25 @@ dependencies = [ ] [[package]] -name = "env_logger" -version = "0.8.4" +name = "env_filter" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3" +checksum = "7a1c3cc8e57274ec99de65301228b537f1e4eedc1b8e0f9411c6caac8ae7308f" dependencies = [ "log", "regex", ] +[[package]] +name = "env_logger" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2daee4ea451f429a58296525ddf28b45a3b64f1acf6587e2067437bb11e218d" +dependencies = [ + "env_filter", + "log", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -1806,15 +1852,15 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" [[package]] name = "flate2" -version = "1.1.8" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b375d6465b98090a5f25b1c7703f3859783755aa9a80433b36e0379a3ec2f369" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" dependencies = [ "crc32fast", "libz-sys", @@ -1918,7 +1964,7 @@ checksum = "a0b4095fc99e1d858e5b8c7125d2638372ec85aa0fe6c807105cf10b0265ca6c" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -1930,7 +1976,7 @@ dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -1942,14 +1988,14 @@ dependencies = [ "frunk_core", "frunk_proc_macro_helpers", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] name = "fs-err" -version = "3.2.2" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf68cef89750956493a66a10f512b9e58d9db21f2a573c079c0bdf1207a54a7" +checksum = "73fde052dbfc920003cfd2c8e2c6e6d4cc7c1091538c3a24226cec0665ab08c0" dependencies = [ "autocfg", "tokio", @@ -1969,9 +2015,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" [[package]] name = "futures" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" dependencies = [ "futures-channel", "futures-core", @@ -1984,9 +2030,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" dependencies = [ "futures-core", "futures-sink", @@ -1994,15 +2040,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" [[package]] name = "futures-executor" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" dependencies = [ "futures-core", "futures-task", @@ -2011,9 +2057,9 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" [[package]] name = "futures-lite" @@ -2030,26 +2076,26 @@ dependencies = [ [[package]] name = "futures-macro" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] name = "futures-sink" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" [[package]] name = "futures-task" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" [[package]] name = "futures-timer" @@ -2059,9 +2105,9 @@ checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" [[package]] name = "futures-util" -version = "0.3.31" +version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" dependencies = [ "futures-channel", "futures-core", @@ -2071,7 +2117,6 @@ dependencies = [ "futures-task", "memchr", "pin-project-lite", - "pin-utils", "slab", ] @@ -2112,6 +2157,20 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "getrandom" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core 0.10.0", + "wasip2", + "wasip3", +] + [[package]] name = "getset" version = "0.1.6" @@ -2121,7 +2180,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -2175,7 +2234,7 @@ checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "cfg-if", "crunchy", - "zerocopy 0.8.34", + "zerocopy 0.8.39", ] [[package]] @@ -2300,6 +2359,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b229d73f5803b562cc26e4da0396c8610a4ee209f4fac8fa4f8d709166dc45" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.8.1" @@ -2369,14 +2437,13 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.19" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "727805d60e7938b76b826a6ef209eb70eaa1812794f9424d4a4e2d740662df5f" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" dependencies = [ "base64 0.22.1", "bytes", "futures-channel", - "futures-core", "futures-util", "http", "http-body", @@ -2410,9 +2477,9 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.64" +version = "0.1.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -2513,6 +2580,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + [[package]] name = "ident_case" version = "1.0.1" @@ -2578,6 +2651,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "inout" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" +dependencies = [ + "hybrid-array", +] + [[package]] name = "io-enum" version = "1.2.0" @@ -2716,11 +2798,17 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + [[package]] name = "libc" -version = "0.2.180" +version = "0.2.182" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc" +checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" [[package]] name = "libloading" @@ -2746,7 +2834,7 @@ checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616" dependencies = [ "bitflags", "libc", - "redox_syscall 0.7.0", + "redox_syscall 0.7.1", ] [[package]] @@ -2785,9 +2873,9 @@ checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" [[package]] name = "local-ip-address" -version = "0.6.9" +version = "0.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92488bc8a0f99ee9f23577bdd06526d49657df8bd70504c61f812337cdad01ab" +checksum = "79ef8c257c92ade496781a32a581d43e3d512cf8ce714ecf04ea80f93ed0ff4a" dependencies = [ "libc", "neli", @@ -2835,9 +2923,9 @@ checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" [[package]] name = "memchr" -version = "2.7.6" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" [[package]] name = "miette" @@ -2866,7 +2954,7 @@ checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -2925,7 +3013,7 @@ dependencies = [ "cfg-if", "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -2975,7 +3063,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", "termcolor", "thiserror 1.0.69", ] @@ -3030,26 +3118,26 @@ dependencies = [ [[package]] name = "native-tls" -version = "0.2.14" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87de3442987e9dbec73158d5c715e7ad9072fda936bb03d19d7fa10e00520f0e" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" dependencies = [ "libc", "log", "openssl", - "openssl-probe 0.1.6", + "openssl-probe", "openssl-sys", "schannel", - "security-framework 2.11.1", + "security-framework", "security-framework-sys", "tempfile", ] [[package]] name = "neli" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e23bebbf3e157c402c4d5ee113233e5e0610cc27453b2f07eefce649c7365dcc" +checksum = "22f9786d56d972959e1408b6a93be6af13b9c1392036c5c1fafa08a1b0c6ee87" dependencies = [ "bitflags", "byteorder", @@ -3071,7 +3159,7 @@ dependencies = [ "proc-macro2", "quote", "serde", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -3228,15 +3316,9 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] -[[package]] -name = "openssl-probe" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" - [[package]] name = "openssl-probe" version = "0.2.1" @@ -3322,7 +3404,7 @@ dependencies = [ "regex", "regex-syntax", "structmeta", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -3345,7 +3427,7 @@ dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -3419,7 +3501,7 @@ checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -3495,15 +3577,15 @@ dependencies = [ [[package]] name = "portable-atomic" -version = "1.13.0" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f89776e4d69bb58bc6993e99ffa1d11f228b839984854c7daeb5d37f87cbe950" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" [[package]] name = "portable-atomic-util" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507" +checksum = "7a9db96d7fa8782dd8c15ce32ffe8680bbd1e978a43bf51a34d39483540495f5" dependencies = [ "portable-atomic", ] @@ -3529,14 +3611,14 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ - "zerocopy 0.8.34", + "zerocopy 0.8.39", ] [[package]] name = "predicates" -version = "3.1.3" +version = "3.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5d19ee57562043d37e82899fade9a22ebab7be9cef5026b07fda9cdd4293573" +checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" dependencies = [ "anstyle", "predicates-core", @@ -3544,15 +3626,15 @@ dependencies = [ [[package]] name = "predicates-core" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "727e462b119fe9c93fd0eb1429a5f7647394014cf3c04ab2c0350eeb09095ffa" +checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" [[package]] name = "predicates-tree" -version = "1.0.12" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72dd2d6d381dfb73a193c7fca536518d7caee39fc8503f74e7dc0be0531b425c" +checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" dependencies = [ "predicates-core", "termtree", @@ -3568,6 +3650,16 @@ dependencies = [ "yansi", ] +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.117", +] + [[package]] name = "proc-macro-crate" version = "3.4.0" @@ -3596,7 +3688,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -3616,7 +3708,7 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", "version_check", "yansi", ] @@ -3641,7 +3733,7 @@ dependencies = [ "itertools 0.14.0", "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -3675,13 +3767,13 @@ dependencies = [ [[package]] name = "quickcheck" -version = "1.0.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "588f6378e4dd99458b60ec275b4477add41ce4fa9f64dcba6f15adccb19b50d6" +checksum = "95c589f335db0f6aaa168a7cd27b1fc6920f5e1470c804f814d9cd6e62a0f70b" dependencies = [ "env_logger", "log", - "rand 0.8.5", + "rand 0.10.0", ] [[package]] @@ -3814,6 +3906,17 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc266eb313df6c5c09c1c7b1fbe2510961e5bcd3add930c1e31f7ed9da0feff8" +dependencies = [ + "chacha20", + "getrandom 0.4.1", + "rand_core 0.10.0", +] + [[package]] name = "rand_chacha" version = "0.3.1" @@ -3852,6 +3955,12 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c8d0fd677905edcbeedbf2edb6494d676f0e98d54d5cf9bda0b061cb8fb8aba" + [[package]] name = "rayon" version = "1.11.0" @@ -3883,9 +3992,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49f3fe0889e69e2ae9e41f4d6c4c0181701d00e4697b356fb1f74173a5e0ee27" +checksum = "35985aa610addc02e24fc232012c86fd11f14111180f902b67e2d5331f8ebf2b" dependencies = [ "bitflags", ] @@ -3907,14 +4016,14 @@ checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] name = "regex" -version = "1.12.2" +version = "1.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" dependencies = [ "aho-corasick", "memchr", @@ -3924,9 +4033,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.13" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" dependencies = [ "aho-corasick", "memchr", @@ -3935,9 +4044,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" +checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c" [[package]] name = "relative-path" @@ -3956,9 +4065,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.13.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04e9018c9d814e5f30cc16a0f03271aeab3571e609612d9fe78c1aa8d11c2f62" +checksum = "ab3f43e3283ab1488b624b44b0e988d0acea0b3214e694730a055cb6b2efa801" dependencies = [ "base64 0.22.1", "bytes", @@ -4096,7 +4205,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.114", + "syn 2.0.117", "unicode-ident", ] @@ -4114,7 +4223,7 @@ dependencies = [ "regex", "relative-path", "rustc_version", - "syn 2.0.114", + "syn 2.0.117", "unicode-ident", ] @@ -4205,19 +4314,10 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63" dependencies = [ - "openssl-probe 0.2.1", + "openssl-probe", "rustls-pki-types", "schannel", - "security-framework 3.5.1", -] - -[[package]] -name = "rustls-pemfile" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" -dependencies = [ - "rustls-pki-types", + "security-framework", ] [[package]] @@ -4245,7 +4345,7 @@ dependencies = [ "rustls-native-certs", "rustls-platform-verifier-android", "rustls-webpki", - "security-framework 3.5.1", + "security-framework", "security-framework-sys", "webpki-root-certs", "windows-sys 0.61.2", @@ -4277,9 +4377,9 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "ryu" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a50f4cf475b65d88e057964e0e9bb1f0aa9bbb2036dc65c64596b42932536984" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" [[package]] name = "same-file" @@ -4328,9 +4428,9 @@ dependencies = [ [[package]] name = "schemars" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54e910108742c57a770f492731f99be216a52fadd361b06c8fb59d74ccc267d2" +checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc" dependencies = [ "dyn-clone", "ref-cast", @@ -4352,22 +4452,9 @@ checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" [[package]] name = "security-framework" -version = "2.11.1" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" -dependencies = [ - "bitflags", - "core-foundation 0.9.4", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework" -version = "3.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3297343eaf830f66ede390ea39da1d462b6b0c1b000f420d0a83f898bbbe6ef" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ "bitflags", "core-foundation 0.10.1", @@ -4378,9 +4465,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.15.0" +version = "2.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc1f0cbffaac4852523ce30d8bd3c5cdc873501d96ff467ca09b6767bb8cd5c0" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" dependencies = [ "core-foundation-sys", "libc", @@ -4439,7 +4526,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -4488,7 +4575,7 @@ checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -4533,7 +4620,7 @@ dependencies = [ "indexmap 1.9.3", "indexmap 2.13.0", "schemars 0.9.0", - "schemars 1.2.0", + "schemars 1.2.1", "serde_core", "serde_json", "serde_with_macros", @@ -4549,7 +4636,7 @@ dependencies = [ "darling 0.21.3", "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -4559,7 +4646,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] @@ -4570,7 +4657,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] @@ -4613,15 +4700,15 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] name = "siphasher" -version = "1.0.1" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" +checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e" [[package]] name = "slab" -version = "0.4.11" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" @@ -4688,7 +4775,7 @@ dependencies = [ "proc-macro2", "quote", "structmeta-derive", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -4699,14 +4786,14 @@ checksum = "152a0b65a590ff6c3da95cabe2353ee04e6167c896b28e3b14478c2636c922fc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] name = "subprocess" -version = "0.2.13" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f75238edb5be30a9ea3035b945eb9c319dde80e879411cdc9a8978e1ac822960" +checksum = "2c56e8662b206b9892d7a5a3f2ecdbcb455d3d6b259111373b7e08b8055158a8" dependencies = [ "libc", "winapi", @@ -4752,9 +4839,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.114" +version = "2.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" dependencies = [ "proc-macro2", "quote", @@ -4778,14 +4865,14 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] name = "system-configuration" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" dependencies = [ "bitflags", "core-foundation 0.9.4", @@ -4827,12 +4914,12 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.24.0" +version = "3.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "655da9c7eb6305c55742045d5a8d2037996d61d8de95806335c7c86ce0f82e9c" +checksum = "0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.1", "once_cell", "rustix", "windows-sys 0.61.2", @@ -4865,9 +4952,9 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "testcontainers" -version = "0.26.3" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a81ec0158db5fbb9831e09d1813fe5ea9023a2b5e6e8e0a5fe67e2a820733629" +checksum = "c3fdcea723c64cc08dbc533b3761e345a15bf1222cbe6cb611de09b43f17a168" dependencies = [ "astral-tokio-tar", "async-trait", @@ -4878,6 +4965,7 @@ dependencies = [ "etcetera", "ferroid", "futures", + "http", "itertools 0.14.0", "log", "memchr", @@ -4929,7 +5017,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -4940,7 +5028,7 @@ checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -4954,9 +5042,9 @@ dependencies = [ [[package]] name = "time" -version = "0.3.46" +version = "0.3.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9da98b7d9b7dad93488a84b8248efc35352b0b2657397d4167e7ad67e5d535e5" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" dependencies = [ "deranged", "itoa", @@ -4975,9 +5063,9 @@ checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" [[package]] name = "time-macros" -version = "0.2.26" +version = "0.2.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78cc610bac2dcee56805c99642447d4c5dbde4d01f752ffea0199aee1f601dc4" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" dependencies = [ "num-conv", "time-core", @@ -5042,7 +5130,7 @@ checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -5093,9 +5181,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.9.11+spec-1.1.0" +version = "0.9.12+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3afc9a848309fe1aaffaed6e1546a7a14de1f935dc9d89d32afd9a44bab7c46" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" dependencies = [ "indexmap 2.13.0", "serde_core", @@ -5152,9 +5240,9 @@ dependencies = [ [[package]] name = "toml_parser" -version = "1.0.6+spec-1.1.0" +version = "1.0.9+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3198b4b0a8e11f09dd03e133c0280504d0801269e9afa46362ffde1cbeebf44" +checksum = "702d4415e08923e7e1ef96cd5727c0dfed80b4d2fa25db9647fe5eb6f7c5a4c4" dependencies = [ "winnow", ] @@ -5173,9 +5261,9 @@ checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607" [[package]] name = "tonic" -version = "0.14.2" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb7613188ce9f7df5bfe185db26c5814347d110db17920415cf2fbcad85e7203" +checksum = "fec7c61a0695dc1887c1b53952990f3ad2e3a31453e1f49f10e75424943a93ec" dependencies = [ "async-trait", "axum", @@ -5202,9 +5290,9 @@ dependencies = [ [[package]] name = "tonic-prost" -version = "0.14.2" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66bd50ad6ce1252d87ef024b3d64fe4c3cf54a86fb9ef4c631fdd0ded7aeaa67" +checksum = "a55376a0bbaa4975a3f10d009ad763d8f4108f067c7c2e74f3001fb49778d309" dependencies = [ "bytes", "prost", @@ -5256,7 +5344,7 @@ dependencies = [ "hyper", "local-ip-address", "percent-encoding", - "rand 0.9.2", + "rand 0.10.0", "reqwest", "serde", "serde_bencode", @@ -5397,7 +5485,7 @@ dependencies = [ "clap", "local-ip-address", "mockall", - "rand 0.9.2", + "rand 0.10.0", "regex", "reqwest", "serde", @@ -5467,7 +5555,7 @@ dependencies = [ "serde_json", "serde_with", "thiserror 2.0.18", - "toml 0.9.11+spec-1.1.0", + "toml 0.9.12+spec-1.1.0", "torrust-tracker-located-error", "tracing", "tracing-subscriber", @@ -5479,7 +5567,7 @@ dependencies = [ name = "torrust-tracker-contrib-bencode" version = "3.0.0-develop" dependencies = [ - "criterion 0.8.1", + "criterion 0.8.2", "thiserror 2.0.18", ] @@ -5543,11 +5631,11 @@ dependencies = [ "async-std", "bittorrent-primitives", "chrono", - "criterion 0.8.1", + "criterion 0.8.2", "crossbeam-skiplist", "futures", "mockall", - "rand 0.9.2", + "rand 0.10.0", "rstest 0.26.1", "serde", "thiserror 2.0.18", @@ -5566,7 +5654,7 @@ dependencies = [ name = "torrust-tracker-test-helpers" version = "3.0.0-develop" dependencies = [ - "rand 0.9.2", + "rand 0.10.0", "torrust-tracker-configuration", "tracing", "tracing-subscriber", @@ -5579,7 +5667,7 @@ dependencies = [ "aquatic_udp_protocol", "async-std", "bittorrent-primitives", - "criterion 0.8.1", + "criterion 0.8.2", "crossbeam-skiplist", "dashmap", "futures", @@ -5606,7 +5694,7 @@ dependencies = [ "futures-util", "local-ip-address", "mockall", - "rand 0.9.2", + "rand 0.10.0", "ringbuf", "serde", "thiserror 2.0.18", @@ -5701,7 +5789,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -5786,9 +5874,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.22" +version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "unicode-linebreak" @@ -5828,9 +5916,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "ureq" -version = "3.1.4" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d39cb1dbab692d82a977c0392ffac19e188bd9186a9f32806f0aaa859d75585a" +checksum = "fdc97a28575b85cfedf2a7e7d3cc64b3e11bd8ac766666318003abbacc7a21fc" dependencies = [ "base64 0.22.1", "log", @@ -5839,7 +5927,6 @@ dependencies = [ "rustls-pki-types", "ureq-proto", "utf-8", - "webpki-roots", ] [[package]] @@ -5887,11 +5974,11 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.20.0" +version = "1.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee48d38b119b0cd71fe4141b30f5ba9c7c5d9f4e7a3a8b4a674e4b6ef789976f" +checksum = "b672338555252d43fd2240c714dc444b8c6fb0a5c5335e65a07bba7742735ddb" dependencies = [ - "getrandom 0.3.4", + "getrandom 0.4.1", "js-sys", "rand 0.9.2", "wasm-bindgen", @@ -5955,6 +6042,15 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.108" @@ -6001,7 +6097,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", "wasm-bindgen-shared", ] @@ -6014,6 +6110,40 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap 2.13.0", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap 2.13.0", + "semver", +] + [[package]] name = "web-sys" version = "0.3.85" @@ -6036,18 +6166,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36a29fc0408b113f68cf32637857ab740edfafdf460c326cd2afaa2d84cc05dc" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "webpki-roots" -version = "1.0.5" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12bed680863276c63889429bfd6cab3b99943659923822de1c8a39c49e4d722c" +checksum = "804f18a4ac2676ffb4e8b5b5fa9ae38af06df08162314f96a68d2a363e21a8ca" dependencies = [ "rustls-pki-types", ] @@ -6104,7 +6225,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -6115,7 +6236,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -6389,6 +6510,88 @@ name = "wit-bindgen" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap 2.13.0", + "prettyplease", + "syn 2.0.117", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.117", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap 2.13.0", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap 2.13.0", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] [[package]] name = "writeable" @@ -6440,7 +6643,7 @@ checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", "synstructure", ] @@ -6456,11 +6659,11 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.34" +version = "0.8.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71ddd76bcebeed25db614f82bf31a9f4222d3fbba300e6fb6c00afa26cbd4d9d" +checksum = "db6d35d663eadb6c932438e763b262fe1a70987f9ae936e60158176d710cae4a" dependencies = [ - "zerocopy-derive 0.8.34", + "zerocopy-derive 0.8.39", ] [[package]] @@ -6471,18 +6674,18 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] name = "zerocopy-derive" -version = "0.8.34" +version = "0.8.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8187381b52e32220d50b255276aa16a084ec0a9017a0ca2152a1f55c539758d" +checksum = "4122cd3169e94605190e77839c9a40d40ed048d305bfdc146e7df40ab0f3e517" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] @@ -6502,7 +6705,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", "synstructure", ] @@ -6542,14 +6745,14 @@ checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" dependencies = [ "proc-macro2", "quote", - "syn 2.0.114", + "syn 2.0.117", ] [[package]] name = "zmij" -version = "1.0.17" +version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02aae0f83f69aafc94776e879363e9771d7ecbffe2c7fbb6c14c5e00dfe88439" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" [[package]] name = "zstd" From f737ace07747c99ef6d393d7cacdff4d7083532b Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Fri, 20 Feb 2026 11:58:56 +0000 Subject: [PATCH 1279/1297] fix: resolve compilation errors after dependency updates BREAKING CHANGE: cipher crate pinned to v0.4 for compatibility with blowfish - Replace Rng import with RngExt for sample_iter method in rand 0.10 - Pin cipher crate to v0.4 to match blowfish dependency constraints - Add explicit generic-array dependency to udp-tracker-core - Import GenericArray directly from generic_array crate - Update Keeper trait in crypto/keys.rs to use BlockEncrypt + BlockDecrypt bounds - Add BlockEncrypt and BlockDecrypt trait imports to connection_cookie.rs - Fix imports in: - packages/tracker-core/src/authentication/key/peer_key.rs - packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs - packages/udp-tracker-core/src/crypto/keys.rs - packages/test-helpers/src/random.rs - src/console/ci/e2e/tracker_container.rs --- Cargo.lock | 48 +++---------------- packages/test-helpers/src/random.rs | 2 +- .../src/authentication/key/peer_key.rs | 2 +- packages/tracker-core/src/test_helpers.rs | 2 +- packages/udp-tracker-core/Cargo.toml | 3 +- .../src/crypto/ephemeral_instance_keys.rs | 4 +- packages/udp-tracker-core/src/crypto/keys.rs | 4 +- src/console/ci/e2e/tracker_container.rs | 2 +- 8 files changed, 17 insertions(+), 50 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e801b94cb..c6b151951 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -751,9 +751,10 @@ dependencies = [ "bittorrent-udp-tracker-protocol", "bloom", "blowfish", - "cipher 0.5.0", + "cipher", "criterion 0.5.1", "futures", + "generic-array", "lazy_static", "mockall", "rand 0.10.0", @@ -831,7 +832,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7" dependencies = [ "byteorder", - "cipher 0.4.4", + "cipher", ] [[package]] @@ -1132,18 +1133,8 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common 0.1.7", - "inout 0.1.4", -] - -[[package]] -name = "cipher" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64727038c8c5e2bb503a15b9f5b9df50a1da9a33e83e1f93067d914f2c6604a5" -dependencies = [ - "crypto-common 0.2.0", - "inout 0.2.2", + "crypto-common", + "inout", ] [[package]] @@ -1482,15 +1473,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "crypto-common" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "211f05e03c7d03754740fd9e585de910a095d6b99f8bcfffdef8319fa02a8331" -dependencies = [ - "hybrid-array", -] - [[package]] name = "darling" version = "0.20.11" @@ -1663,7 +1645,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", - "crypto-common 0.1.7", + "crypto-common", ] [[package]] @@ -2359,15 +2341,6 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" -[[package]] -name = "hybrid-array" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1b229d73f5803b562cc26e4da0396c8610a4ee209f4fac8fa4f8d709166dc45" -dependencies = [ - "typenum", -] - [[package]] name = "hyper" version = "1.8.1" @@ -2651,15 +2624,6 @@ dependencies = [ "generic-array", ] -[[package]] -name = "inout" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" -dependencies = [ - "hybrid-array", -] - [[package]] name = "io-enum" version = "1.2.0" diff --git a/packages/test-helpers/src/random.rs b/packages/test-helpers/src/random.rs index f096d695c..62265dbd7 100644 --- a/packages/test-helpers/src/random.rs +++ b/packages/test-helpers/src/random.rs @@ -1,6 +1,6 @@ //! Random data generators for testing. use rand::distr::Alphanumeric; -use rand::{rng, Rng}; +use rand::{rng, RngExt}; /// Returns a random alphanumeric string of a certain size. /// diff --git a/packages/tracker-core/src/authentication/key/peer_key.rs b/packages/tracker-core/src/authentication/key/peer_key.rs index 41aba950b..ba648ad2f 100644 --- a/packages/tracker-core/src/authentication/key/peer_key.rs +++ b/packages/tracker-core/src/authentication/key/peer_key.rs @@ -13,7 +13,7 @@ use std::time::Duration; use derive_more::Display; use rand::distr::Alphanumeric; -use rand::{rng, Rng}; +use rand::{rng, RngExt}; use serde::{Deserialize, Serialize}; use thiserror::Error; use torrust_tracker_clock::conv::convert_from_timestamp_to_datetime_utc; diff --git a/packages/tracker-core/src/test_helpers.rs b/packages/tracker-core/src/test_helpers.rs index 62649cd22..bf21e6f94 100644 --- a/packages/tracker-core/src/test_helpers.rs +++ b/packages/tracker-core/src/test_helpers.rs @@ -7,7 +7,7 @@ pub(crate) mod tests { use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes, PeerId}; use bittorrent_primitives::info_hash::InfoHash; - use rand::Rng; + use rand::RngExt; use torrust_tracker_configuration::Configuration; #[cfg(test)] use torrust_tracker_configuration::Core; diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml index b3007eb80..aa12f898f 100644 --- a/packages/udp-tracker-core/Cargo.toml +++ b/packages/udp-tracker-core/Cargo.toml @@ -20,9 +20,10 @@ bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" bittorrent-udp-tracker-protocol = { version = "3.0.0-develop", path = "../udp-protocol" } bloom = "0.3.2" blowfish = "0" -cipher = "0" +cipher = "0.4" criterion = { version = "0.5.1", features = ["async_tokio"] } futures = "0" +generic-array = "0" lazy_static = "1" rand = "0" serde = "1.0.219" diff --git a/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs b/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs index 58ba70562..de40e4b1d 100644 --- a/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs +++ b/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs @@ -4,10 +4,10 @@ //! application starts and are not persisted anywhere. use blowfish::BlowfishLE; -use cipher::generic_array::GenericArray; use cipher::{BlockSizeUser, KeyInit}; +use generic_array::GenericArray; use rand::rngs::ThreadRng; -use rand::Rng; +use rand::RngExt; pub type Seed = [u8; 32]; pub type CipherBlowfish = BlowfishLE; diff --git a/packages/udp-tracker-core/src/crypto/keys.rs b/packages/udp-tracker-core/src/crypto/keys.rs index f9a3e361d..bb813b9dc 100644 --- a/packages/udp-tracker-core/src/crypto/keys.rs +++ b/packages/udp-tracker-core/src/crypto/keys.rs @@ -5,6 +5,8 @@ //! //! It also provides the logic for the cipher for encryption and decryption. +use cipher::{BlockDecrypt, BlockEncrypt}; + use self::detail_cipher::CURRENT_CIPHER; use self::detail_seed::CURRENT_SEED; pub use crate::crypto::ephemeral_instance_keys::CipherArrayBlowfish; @@ -13,7 +15,7 @@ use crate::crypto::ephemeral_instance_keys::{CipherBlowfish, Seed, RANDOM_CIPHER /// This trait is for structures that can keep and provide a seed. pub trait Keeper { type Seed: Sized + Default + AsMut<[u8]>; - type Cipher: cipher::BlockCipher; + type Cipher: BlockEncrypt + BlockDecrypt; /// It returns a reference to the seed that is keeping. fn get_seed() -> &'static Self::Seed; diff --git a/src/console/ci/e2e/tracker_container.rs b/src/console/ci/e2e/tracker_container.rs index a3845c103..1a7717a41 100644 --- a/src/console/ci/e2e/tracker_container.rs +++ b/src/console/ci/e2e/tracker_container.rs @@ -1,7 +1,7 @@ use std::time::Duration; use rand::distr::Alphanumeric; -use rand::Rng; +use rand::RngExt; use super::docker::{RunOptions, RunningContainer}; use super::logs_parser::RunningServices; From ed0937bfe450a306de84f90660683c7a7fb16f56 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 3 Mar 2026 07:55:53 +0000 Subject: [PATCH 1280/1297] chore(deps): update dependencies ``` cargo update Updating crates.io index Locking 35 packages to latest compatible versions Updating async-compression v0.4.40 -> v0.4.41 Updating aws-lc-rs v1.16.0 -> v1.16.1 Updating aws-lc-sys v0.37.1 -> v0.38.0 Updating chrono v0.4.43 -> v0.4.44 Updating deranged v0.5.6 -> v0.5.8 Updating derive_utils v0.15.0 -> v0.15.1 Updating io-enum v1.2.0 -> v1.2.1 Updating ipnet v2.11.0 -> v2.12.0 Updating js-sys v0.3.85 -> v0.3.91 Updating libredox v0.1.12 -> v0.1.14 Updating libz-sys v1.1.23 -> v1.1.24 Updating linux-raw-sys v0.11.0 -> v0.12.1 Updating owo-colors v4.2.3 -> v4.3.0 Updating pin-project v1.1.10 -> v1.1.11 Updating pin-project-internal v1.1.10 -> v1.1.11 Updating pin-project-lite v0.2.16 -> v0.2.17 Updating piper v0.2.4 -> v0.2.5 Adding plain v0.2.3 Updating redox_syscall v0.7.1 -> v0.7.3 Updating regex-syntax v0.8.9 -> v0.8.10 Updating rustix v1.1.3 -> v1.1.4 Updating rustls v0.23.36 -> v0.23.37 Updating serde_with v3.16.1 -> v3.17.0 Updating serde_with_macros v3.16.1 -> v3.17.0 Updating tempfile v3.25.0 -> v3.26.0 Updating testcontainers v0.27.0 -> v0.27.1 Updating tokio-macros v2.6.0 -> v2.6.1 Updating wasm-bindgen v0.2.108 -> v0.2.114 Updating wasm-bindgen-futures v0.4.58 -> v0.4.64 Updating wasm-bindgen-macro v0.2.108 -> v0.2.114 Updating wasm-bindgen-macro-support v0.2.108 -> v0.2.114 Updating wasm-bindgen-shared v0.2.108 -> v0.2.114 Updating web-sys v0.3.85 -> v0.3.91 Updating zerocopy v0.8.39 -> v0.8.40 Updating zerocopy-derive v0.8.39 -> v0.8.40 note: pass `--verbose` to see 9 unchanged dependencies behind latest ``` --- Cargo.lock | 151 ++++++++++++++++++++++++++++------------------------- 1 file changed, 79 insertions(+), 72 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c6b151951..6894e2bcd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -239,9 +239,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.40" +version = "0.4.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d67d43201f4d20c78bcda740c142ca52482d81da80681533d33bf3f0596c8e2" +checksum = "d0f9ee0f6e02ffd7ad5816e9464499fba7b3effd01123b515c41d1697c43dad1" dependencies = [ "compression-codecs", "compression-core", @@ -397,9 +397,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "aws-lc-rs" -version = "1.16.0" +version = "1.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9a7b350e3bb1767102698302bc37256cbd48422809984b98d292c40e2579aa9" +checksum = "94bffc006df10ac2a68c83692d734a465f8ee6c5b384d8545a636f81d858f4bf" dependencies = [ "aws-lc-sys", "zeroize", @@ -407,9 +407,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.37.1" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b092fe214090261288111db7a2b2c2118e5a7f30dc2569f1732c4069a6840549" +checksum = "4321e568ed89bb5a7d291a7f37997c2c0df89809d7b6d12062c81ddb54aa782e" dependencies = [ "cc", "cmake", @@ -1090,9 +1090,9 @@ dependencies = [ [[package]] name = "chrono" -version = "0.4.43" +version = "0.4.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fac4744fb15ae8337dc853fee7fb3f4e48c0fbaa23d0afe49c447b4fab126118" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" dependencies = [ "iana-time-zone", "num-traits", @@ -1559,9 +1559,9 @@ dependencies = [ [[package]] name = "deranged" -version = "0.5.6" +version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc3dc5ad92c2e2d1c193bbbbdf2ea477cb81331de4f3103f267ca18368b988c4" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" dependencies = [ "powerfmt", "serde_core", @@ -1623,9 +1623,9 @@ dependencies = [ [[package]] name = "derive_utils" -version = "0.15.0" +version = "0.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccfae181bab5ab6c5478b2ccb69e4c68a02f8c3ec72f6616bfec9dbc599d2ee0" +checksum = "362f47930db19fe7735f527e6595e4900316b893ebf6d48ad3d31be928d57dd6" dependencies = [ "proc-macro2", "quote", @@ -2216,7 +2216,7 @@ checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "cfg-if", "crunchy", - "zerocopy 0.8.39", + "zerocopy 0.8.40", ] [[package]] @@ -2626,18 +2626,18 @@ dependencies = [ [[package]] name = "io-enum" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d197db2f7ebf90507296df3aebaf65d69f5dce8559d8dbd82776a6cadab61bbf" +checksum = "7de9008599afe8527a8c9d70423437363b321649161e98473f433de802d76107" dependencies = [ "derive_utils", ] [[package]] name = "ipnet" -version = "2.11.0" +version = "2.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" [[package]] name = "iri-string" @@ -2739,9 +2739,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.85" +version = "0.3.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3" +checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c" dependencies = [ "once_cell", "wasm-bindgen", @@ -2792,13 +2792,14 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.12" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616" +checksum = "1744e39d1d6a9948f4f388969627434e31128196de472883b39f148769bfe30a" dependencies = [ "bitflags", "libc", - "redox_syscall 0.7.1", + "plain", + "redox_syscall 0.7.3", ] [[package]] @@ -2814,9 +2815,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.23" +version = "1.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15d118bbf3771060e7311cc7bb0545b01d08a8b4a7de949198dec1fa0ca1c0f7" +checksum = "4735e9cbde5aac84a5ce588f6b23a90b9b0b528f6c5a8db8a4aff300463a0839" dependencies = [ "cc", "pkg-config", @@ -2825,9 +2826,9 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.11.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litemap" @@ -3303,9 +3304,9 @@ dependencies = [ [[package]] name = "owo-colors" -version = "4.2.3" +version = "4.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c6901729fa79e91a0913333229e9ca5dc725089d1c363b2f4b4760709dc4a52" +checksum = "d211803b9b6b570f68772237e415a029d5a50c65d382910b879fb19d3271f94d" [[package]] name = "page_size" @@ -3450,18 +3451,18 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.10" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" +checksum = "f1749c7ed4bcaf4c3d0a3efc28538844fb29bcdd7d2b67b2be7e20ba861ff517" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.10" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" +checksum = "d9b20ed30f105399776b9c883e68e536ef602a16ae6f596d2c473591d6ad64c6" dependencies = [ "proc-macro2", "quote", @@ -3470,9 +3471,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "pin-utils" @@ -3482,9 +3483,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "piper" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" dependencies = [ "atomic-waker", "fastrand", @@ -3497,6 +3498,12 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + [[package]] name = "plotters" version = "0.3.7" @@ -3575,7 +3582,7 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ - "zerocopy 0.8.39", + "zerocopy 0.8.40", ] [[package]] @@ -3956,9 +3963,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.7.1" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35985aa610addc02e24fc232012c86fd11f14111180f902b67e2d5331f8ebf2b" +checksum = "6ce70a74e890531977d37e532c34d45e9055d2409ed08ddba14529471ed0be16" dependencies = [ "bitflags", ] @@ -4008,9 +4015,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.9" +version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" [[package]] name = "relative-path" @@ -4245,9 +4252,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.3" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ "bitflags", "errno", @@ -4258,9 +4265,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.36" +version = "0.23.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b" +checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4" dependencies = [ "aws-lc-rs", "log", @@ -4574,9 +4581,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.16.1" +version = "3.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fa237f2807440d238e0364a218270b98f767a00d3dada77b1c53ae88940e2e7" +checksum = "381b283ce7bc6b476d903296fb59d0d36633652b633b27f64db4fb46dcbfc3b9" dependencies = [ "base64 0.22.1", "chrono", @@ -4593,9 +4600,9 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.16.1" +version = "3.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52a8e3ca0ca629121f70ab50f95249e5a6f925cc0f6ffe8256c45b728875706c" +checksum = "a6d4e30573c8cb306ed6ab1dca8423eec9a463ea0e155f45399455e0368b27e0" dependencies = [ "darling 0.21.3", "proc-macro2", @@ -4878,9 +4885,9 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.25.0" +version = "3.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1" +checksum = "82a72c767771b47409d2345987fda8628641887d5466101319899796367354a0" dependencies = [ "fastrand", "getrandom 0.4.1", @@ -4916,9 +4923,9 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "testcontainers" -version = "0.27.0" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3fdcea723c64cc08dbc533b3761e345a15bf1222cbe6cb611de09b43f17a168" +checksum = "c1c0624faaa317c56d6d19136580be889677259caf5c897941c6f446b4655068" dependencies = [ "astral-tokio-tar", "async-trait", @@ -5088,9 +5095,9 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.6.0" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" +checksum = "5c55a2eff8b69ce66c84f85e1da1c233edc36ceb85a2058d11b0d6a3c7e7569c" dependencies = [ "proc-macro2", "quote", @@ -6017,9 +6024,9 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.108" +version = "0.2.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566" +checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e" dependencies = [ "cfg-if", "once_cell", @@ -6030,9 +6037,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.58" +version = "0.4.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70a6e77fd0ae8029c9ea0063f87c46fde723e7d887703d74ad2616d792e51e6f" +checksum = "e9c5522b3a28661442748e09d40924dfb9ca614b21c00d3fd135720e48b67db8" dependencies = [ "cfg-if", "futures-util", @@ -6044,9 +6051,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.108" +version = "0.2.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608" +checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -6054,9 +6061,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.108" +version = "0.2.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55" +checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3" dependencies = [ "bumpalo", "proc-macro2", @@ -6067,9 +6074,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.108" +version = "0.2.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12" +checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16" dependencies = [ "unicode-ident", ] @@ -6110,9 +6117,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.85" +version = "0.3.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "312e32e551d92129218ea9a2452120f4aabc03529ef03e4d0d82fb2780608598" +checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9" dependencies = [ "js-sys", "wasm-bindgen", @@ -6623,11 +6630,11 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.39" +version = "0.8.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db6d35d663eadb6c932438e763b262fe1a70987f9ae936e60158176d710cae4a" +checksum = "a789c6e490b576db9f7e6b6d661bcc9799f7c0ac8352f56ea20193b2681532e5" dependencies = [ - "zerocopy-derive 0.8.39", + "zerocopy-derive 0.8.40", ] [[package]] @@ -6643,9 +6650,9 @@ dependencies = [ [[package]] name = "zerocopy-derive" -version = "0.8.39" +version = "0.8.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4122cd3169e94605190e77839c9a40d40ed048d305bfdc146e7df40ab0f3e517" +checksum = "f65c489a7071a749c849713807783f70672b28094011623e200cb86dcb835953" dependencies = [ "proc-macro2", "quote", From 29edbb6d154f2230d7695d2bd47ca5084fbc53a4 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 3 Mar 2026 08:04:34 +0000 Subject: [PATCH 1281/1297] fix: collapse nested if into match arm guard in pagination test Resolves clippy::collapsible_match lint by moving the inner if condition into the match arm guard for the Pagination { limit: 1, offset: 1 } case. --- .../tests/repository/mod.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/packages/torrent-repository-benchmarking/tests/repository/mod.rs b/packages/torrent-repository-benchmarking/tests/repository/mod.rs index c3589ce68..ec7e68bae 100644 --- a/packages/torrent-repository-benchmarking/tests/repository/mod.rs +++ b/packages/torrent-repository-benchmarking/tests/repository/mod.rs @@ -364,12 +364,10 @@ async fn it_should_get_paginated( } // it should return the only the second entry if both the limit and the offset are one. - Pagination { limit: 1, offset: 1 } => { - if info_hashes.len() > 1 { - let page = repo.get_paginated(Some(&paginated)).await; - assert_eq!(page.len(), 1); - assert_eq!(page[0].0, info_hashes[1]); - } + Pagination { limit: 1, offset: 1 } if info_hashes.len() > 1 => { + let page = repo.get_paginated(Some(&paginated)).await; + assert_eq!(page.len(), 1); + assert_eq!(page[0].0, info_hashes[1]); } // the other cases are not yet tested. _ => {} From 7e322eb7bf766f2a6c5ee376b42deae21b28bcd9 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 3 Mar 2026 08:08:11 +0000 Subject: [PATCH 1282/1297] ci: upgrade actions/upload-artifact from v6 to v7 in generate_coverage_pr workflow --- .github/workflows/generate_coverage_pr.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/generate_coverage_pr.yaml b/.github/workflows/generate_coverage_pr.yaml index f762207cf..a3f97dbf2 100644 --- a/.github/workflows/generate_coverage_pr.yaml +++ b/.github/workflows/generate_coverage_pr.yaml @@ -59,13 +59,13 @@ jobs: # Triggered sub-workflow is not able to detect the original commit/PR which is available # in this workflow. - name: Store PR number - uses: actions/upload-artifact@v6 + uses: actions/upload-artifact@v7 with: name: pr_number path: pr_number.txt - name: Store commit SHA - uses: actions/upload-artifact@v6 + uses: actions/upload-artifact@v7 with: name: commit_sha path: commit_sha.txt @@ -74,7 +74,7 @@ jobs: # is executed by a different workflow `upload_coverage.yml`. The reason for this # split is because `on.pull_request` workflows don't have access to secrets. - name: Store coverage report in artifacts - uses: actions/upload-artifact@v6 + uses: actions/upload-artifact@v7 with: name: codecov_report path: ./codecov.json From de471450fb2a555816b111cd59ae03dade2b6fcb Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 3 Mar 2026 18:14:57 +0000 Subject: [PATCH 1283/1297] fix: add sleep after HTTP server stop in health check test to avoid race condition --- packages/axum-health-check-api-server/tests/server/contract.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/axum-health-check-api-server/tests/server/contract.rs b/packages/axum-health-check-api-server/tests/server/contract.rs index 1d1ba3539..af1c0cff9 100644 --- a/packages/axum-health-check-api-server/tests/server/contract.rs +++ b/packages/axum-health-check-api-server/tests/server/contract.rs @@ -202,6 +202,9 @@ mod http { service.server.stop().await.expect("it should stop udp server"); + // Give the OS a moment to fully release the TCP port after the server stops. + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + { let config = configuration.health_check_api.clone(); let env = Started::new(&config.into(), registar).await; From 1228a2b986e41fa195fd5418a5fecd028add1524 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Tue, 7 Apr 2026 19:07:53 +0100 Subject: [PATCH 1284/1297] chore(deps): update dependencies ``` Updating crates.io index Locking 104 packages to latest compatible versions Updating anstream v0.6.21 -> v1.0.0 Updating anstyle v1.0.13 -> v1.0.14 Updating anstyle-parse v0.2.7 -> v1.0.0 Updating arc-swap v1.8.2 -> v1.9.1 Updating astral-tokio-tar v0.5.6 -> v0.6.0 Updating aws-lc-rs v1.16.1 -> v1.16.2 Updating aws-lc-sys v0.38.0 -> v0.39.1 Updating bollard v0.20.1 -> v0.20.2 Updating borsh v1.6.0 -> v1.6.1 Updating borsh-derive v1.6.0 -> v1.6.1 Updating cc v1.2.56 -> v1.2.59 Updating clap v4.5.60 -> v4.6.0 Updating clap_builder v4.5.60 -> v4.6.0 Updating clap_derive v4.5.55 -> v4.6.0 Updating clap_lex v1.0.0 -> v1.1.0 Updating cmake v0.1.57 -> v0.1.58 Updating colorchoice v1.0.4 -> v1.0.5 Updating darling v0.21.3 -> v0.23.0 Updating darling_core v0.21.3 -> v0.23.0 Updating darling_macro v0.21.3 -> v0.23.0 Updating env_filter v1.0.0 -> v1.0.1 Updating env_logger v0.11.9 -> v0.11.10 Updating fastrand v2.3.0 -> v2.4.1 Updating fragile v2.0.1 -> v2.1.0 Updating getrandom v0.4.1 -> v0.4.2 Updating hyper v1.8.1 -> v1.9.0 Updating icu_collections v2.1.1 -> v2.2.0 Updating icu_locale_core v2.1.1 -> v2.2.0 Updating icu_normalizer v2.1.1 -> v2.2.0 Updating icu_normalizer_data v2.1.1 -> v2.2.0 Updating icu_properties v2.1.2 -> v2.2.0 Updating icu_properties_data v2.1.2 -> v2.2.0 Updating icu_provider v2.1.1 -> v2.2.0 Updating indexmap v2.13.0 -> v2.13.1 Updating iri-string v0.7.10 -> v0.7.12 Updating itoa v1.0.17 -> v1.0.18 Removing jni-sys v0.3.0 Adding jni-sys v0.3.1 Adding jni-sys v0.4.1 Adding jni-sys-macros v0.4.1 Updating js-sys v0.3.91 -> v0.3.94 Updating libc v0.2.182 -> v0.2.184 Updating libredox v0.1.14 -> v0.1.15 Updating libsqlite3-sys v0.36.0 -> v0.37.0 Updating libz-sys v1.1.24 -> v1.1.28 Updating litemap v0.8.1 -> v0.8.2 Updating local-ip-address v0.6.10 -> v0.6.11 Updating mio v1.1.1 -> v1.2.0 Updating num-conv v0.2.0 -> v0.2.1 Updating once_cell v1.21.3 -> v1.21.4 Updating openssl v0.10.75 -> v0.10.76 Updating openssl-sys v0.9.111 -> v0.9.112 Updating portable-atomic-util v0.2.5 -> v0.2.6 Updating potential_utf v0.1.4 -> v0.1.5 Updating proc-macro-crate v3.4.0 -> v3.5.0 Updating quinn-proto v0.11.13 -> v0.11.14 Updating quote v1.0.44 -> v1.0.45 Adding r-efi v6.0.0 Updating r2d2_sqlite v0.32.0 -> v0.33.0 Updating rusqlite v0.38.0 -> v0.39.0 Updating rust_decimal v1.40.0 -> v1.41.0 Updating rustc-hash v2.1.1 -> v2.1.2 Updating rustls-webpki v0.103.9 -> v0.103.10 Updating schannel v0.1.28 -> v0.1.29 Updating semver v1.0.27 -> v1.0.28 Updating serde_spanned v1.0.4 -> v1.1.1 Updating serde_with v3.17.0 -> v3.18.0 Updating serde_with_macros v3.17.0 -> v3.18.0 Updating simd-adler32 v0.3.8 -> v0.3.9 Updating socket2 v0.6.2 -> v0.6.3 Updating tempfile v3.26.0 -> v3.27.0 Updating terminal_size v0.4.3 -> v0.4.4 Updating testcontainers v0.27.1 -> v0.27.2 Updating tinystr v0.8.2 -> v0.8.3 Updating tinyvec v1.10.0 -> v1.11.0 Updating tokio v1.49.0 -> v1.51.0 Updating tokio-macros v2.6.1 -> v2.7.0 Adding toml_datetime v1.1.1+spec-1.1.0 Updating toml_edit v0.23.10+spec-1.0.0 -> v0.25.10+spec-1.1.0 Updating toml_parser v1.0.9+spec-1.1.0 -> v1.1.2+spec-1.1.0 Updating toml_writer v1.0.6+spec-1.1.0 -> v1.1.1+spec-1.1.0 Updating tracing-subscriber v0.3.22 -> v0.3.23 Updating unicode-segmentation v1.12.0 -> v1.13.2 Updating ureq v3.2.0 -> v3.3.0 Updating ureq-proto v0.5.3 -> v0.6.0 Removing utf-8 v0.7.6 Adding utf8-zero v0.8.1 Updating uuid v1.21.0 -> v1.23.0 Updating wasm-bindgen v0.2.114 -> v0.2.117 Updating wasm-bindgen-futures v0.4.64 -> v0.4.67 Updating wasm-bindgen-macro v0.2.114 -> v0.2.117 Updating wasm-bindgen-macro-support v0.2.114 -> v0.2.117 Updating wasm-bindgen-shared v0.2.114 -> v0.2.117 Updating web-sys v0.3.91 -> v0.3.94 Removing winnow v0.7.14 Adding winnow v0.7.15 Adding winnow v1.0.1 Updating writeable v0.6.2 -> v0.6.3 Updating yoke v0.8.1 -> v0.8.2 Updating yoke-derive v0.8.1 -> v0.8.2 Updating zerocopy v0.8.40 -> v0.8.48 Updating zerocopy-derive v0.8.40 -> v0.8.48 Updating zerofrom v0.1.6 -> v0.1.7 Updating zerofrom-derive v0.1.6 -> v0.1.7 Updating zerotrie v0.2.3 -> v0.2.4 Updating zerovec v0.11.5 -> v0.11.6 Updating zerovec-derive v0.11.2 -> v0.11.3 note: pass `--verbose` to see 9 unchanged dependencies behind latest ``` --- Cargo.lock | 543 +++++++++++++++++++++++++++++------------------------ 1 file changed, 296 insertions(+), 247 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6894e2bcd..9e0911944 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -84,9 +84,9 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" [[package]] name = "anstream" -version = "0.6.21" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" dependencies = [ "anstyle", "anstyle-parse", @@ -99,15 +99,15 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.13" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" [[package]] name = "anstyle-parse" -version = "0.2.7" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" dependencies = [ "utf8parse", ] @@ -175,9 +175,9 @@ dependencies = [ [[package]] name = "arc-swap" -version = "1.8.2" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f3647c145568cec02c42054e07bdf9a5a698e15b466fb2341bfc393cd24aa5" +checksum = "6a3a1fd6f75306b68087b831f025c712524bcb19aad54e557b1129cfa0a2b207" dependencies = [ "rustversion", ] @@ -190,9 +190,9 @@ checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" [[package]] name = "astral-tokio-tar" -version = "0.5.6" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec179a06c1769b1e42e1e2cbe74c7dcdb3d6383c838454d063eaac5bbb7ebbe5" +checksum = "3c23f3af104b40a3430ccb90ed5f7bd877a8dc5c26fc92fde51a22b40890dcf9" dependencies = [ "filetime", "futures-core", @@ -397,9 +397,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "aws-lc-rs" -version = "1.16.1" +version = "1.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94bffc006df10ac2a68c83692d734a465f8ee6c5b384d8545a636f81d858f4bf" +checksum = "a054912289d18629dc78375ba2c3726a3afe3ff71b4edba9dedfca0e3446d1fc" dependencies = [ "aws-lc-sys", "zeroize", @@ -407,9 +407,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.38.0" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4321e568ed89bb5a7d291a7f37997c2c0df89809d7b6d12062c81ddb54aa782e" +checksum = "83a25cf98105baa966497416dbd42565ce3a8cf8dbfd59803ec9ad46f3126399" dependencies = [ "cc", "cmake", @@ -837,9 +837,9 @@ dependencies = [ [[package]] name = "bollard" -version = "0.20.1" +version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "227aa051deec8d16bd9c34605e7aaf153f240e35483dd42f6f78903847934738" +checksum = "ee04c4c84f1f811b017f2fbb7dd8815c976e7ca98593de9c1e2afad0f636bff4" dependencies = [ "async-stream", "base64 0.22.1", @@ -911,19 +911,20 @@ dependencies = [ [[package]] name = "borsh" -version = "1.6.0" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1da5ab77c1437701eeff7c88d968729e7766172279eab0676857b3d63af7a6f" +checksum = "cfd1e3f8955a5d7de9fab72fc8373fade9fb8a703968cb200ae3dc6cf08e185a" dependencies = [ "borsh-derive", + "bytes", "cfg_aliases", ] [[package]] name = "borsh-derive" -version = "1.6.0" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0686c856aa6aac0c4498f936d7d6a02df690f614c03e4d906d1018062b5c5e2c" +checksum = "bfcfdc083699101d5a7965e49925975f2f55060f94f9a05e7187be95d530ca59" dependencies = [ "once_cell", "proc-macro-crate", @@ -1040,9 +1041,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.56" +version = "1.2.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2" +checksum = "b7a4d3ec6524d28a329fc53654bbadc9bdd7b0431f5d65f1a56ffb28a1ee5283" dependencies = [ "find-msvc-tools", "jobserver", @@ -1150,9 +1151,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.60" +version = "4.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2797f34da339ce31042b27d23607e051786132987f595b02ba4f6a6dffb7030a" +checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351" dependencies = [ "clap_builder", "clap_derive", @@ -1160,9 +1161,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.60" +version = "4.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24a241312cea5059b13574bb9b3861cabf758b879c15190b37b6d6fd63ab6876" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" dependencies = [ "anstream", "anstyle", @@ -1172,9 +1173,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.55" +version = "4.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5" +checksum = "1110bd8a634a1ab8cb04345d8d878267d57c3cf1b38d91b71af6686408bbca6a" dependencies = [ "heck", "proc-macro2", @@ -1184,24 +1185,24 @@ dependencies = [ [[package]] name = "clap_lex" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a822ea5bc7590f9d40f1ba12c0dc3c2760f3482c6984db1573ad11031420831" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" [[package]] name = "cmake" -version = "0.1.57" +version = "0.1.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" dependencies = [ "cc", ] [[package]] name = "colorchoice" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" [[package]] name = "combine" @@ -1485,12 +1486,12 @@ dependencies = [ [[package]] name = "darling" -version = "0.21.3" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" dependencies = [ - "darling_core 0.21.3", - "darling_macro 0.21.3", + "darling_core 0.23.0", + "darling_macro 0.23.0", ] [[package]] @@ -1509,11 +1510,10 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.21.3" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" dependencies = [ - "fnv", "ident_case", "proc-macro2", "quote", @@ -1534,11 +1534,11 @@ dependencies = [ [[package]] name = "darling_macro" -version = "0.21.3" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" dependencies = [ - "darling_core 0.21.3", + "darling_core 0.23.0", "quote", "syn 2.0.117", ] @@ -1705,9 +1705,9 @@ dependencies = [ [[package]] name = "env_filter" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a1c3cc8e57274ec99de65301228b537f1e4eedc1b8e0f9411c6caac8ae7308f" +checksum = "32e90c2accc4b07a8456ea0debdc2e7587bdd890680d71173a15d4ae604f6eef" dependencies = [ "log", "regex", @@ -1715,9 +1715,9 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.11.9" +version = "0.11.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2daee4ea451f429a58296525ddf28b45a3b64f1acf6587e2067437bb11e218d" +checksum = "0621c04f2196ac3f488dd583365b9c09be011a4ab8b9f37248ffcc8f6198b56a" dependencies = [ "env_filter", "log", @@ -1790,9 +1790,9 @@ checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" [[package]] name = "fastrand" -version = "2.3.0" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" [[package]] name = "ferroid" @@ -1913,9 +1913,12 @@ dependencies = [ [[package]] name = "fragile" -version = "2.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dd6caf6059519a65843af8fe2a3ae298b14b80179855aeb4adc2c1934ee619" +checksum = "8878864ba14bb86e818a412bfd6f18f9eabd4ec0f008a28e8f7eb61db532fcf9" +dependencies = [ + "futures-core", +] [[package]] name = "frunk" @@ -2134,20 +2137,20 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi", + "r-efi 5.3.0", "wasip2", "wasm-bindgen", ] [[package]] name = "getrandom" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", "libc", - "r-efi", + "r-efi 6.0.0", "rand_core 0.10.0", "wasip2", "wasip3", @@ -2201,7 +2204,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.13.0", + "indexmap 2.13.1", "slab", "tokio", "tokio-util", @@ -2216,7 +2219,7 @@ checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "cfg-if", "crunchy", - "zerocopy 0.8.40", + "zerocopy 0.8.48", ] [[package]] @@ -2343,9 +2346,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.8.1" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" dependencies = [ "atomic-waker", "bytes", @@ -2358,7 +2361,6 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "pin-utils", "smallvec", "tokio", "want", @@ -2425,7 +2427,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2 0.6.2", + "socket2 0.6.3", "system-configuration", "tokio", "tower-service", @@ -2474,12 +2476,13 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" dependencies = [ "displaydoc", "potential_utf", + "utf8_iter", "yoke", "zerofrom", "zerovec", @@ -2487,9 +2490,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" dependencies = [ "displaydoc", "litemap", @@ -2500,9 +2503,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -2514,15 +2517,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" [[package]] name = "icu_properties" -version = "2.1.2" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" dependencies = [ "icu_collections", "icu_locale_core", @@ -2534,15 +2537,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.1.2" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" [[package]] name = "icu_provider" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" dependencies = [ "displaydoc", "icu_locale_core", @@ -2599,9 +2602,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.13.0" +version = "2.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +checksum = "45a8a2b9cb3e0b0c1803dbb0758ffac5de2f425b23c28f518faabd9d805342ff" dependencies = [ "equivalent", "hashbrown 0.16.1", @@ -2641,9 +2644,9 @@ checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" [[package]] name = "iri-string" -version = "0.7.10" +version = "0.7.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a" +checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20" dependencies = [ "memchr", "serde", @@ -2701,9 +2704,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jni" @@ -2714,7 +2717,7 @@ dependencies = [ "cesu8", "cfg-if", "combine", - "jni-sys", + "jni-sys 0.3.1", "log", "thiserror 1.0.69", "walkdir", @@ -2723,9 +2726,31 @@ dependencies = [ [[package]] name = "jni-sys" -version = "0.3.0" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.117", +] [[package]] name = "jobserver" @@ -2739,10 +2764,12 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.91" +version = "0.3.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c" +checksum = "2e04e2ef80ce82e13552136fabeef8a5ed1f985a96805761cbb9a2c34e7664d9" dependencies = [ + "cfg-if", + "futures-util", "once_cell", "wasm-bindgen", ] @@ -2770,9 +2797,9 @@ checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] name = "libc" -version = "0.2.182" +version = "0.2.184" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" +checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af" [[package]] name = "libloading" @@ -2792,9 +2819,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1744e39d1d6a9948f4f388969627434e31128196de472883b39f148769bfe30a" +checksum = "7ddbf48fd451246b1f8c2610bd3b4ac0cc6e149d89832867093ab69a17194f08" dependencies = [ "bitflags", "libc", @@ -2804,9 +2831,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.36.0" +version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95b4103cffefa72eb8428cb6b47d6627161e51c2739fc5e3b734584157bc642a" +checksum = "b1f111c8c41e7c61a49cd34e44c7619462967221a6443b0ec299e0ac30cfb9b1" dependencies = [ "cc", "pkg-config", @@ -2815,9 +2842,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.24" +version = "1.1.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4735e9cbde5aac84a5ce588f6b23a90b9b0b528f6c5a8db8a4aff300463a0839" +checksum = "fc3a226e576f50782b3305c5ccf458698f92798987f551c6a02efe8276721e22" dependencies = [ "cc", "pkg-config", @@ -2832,15 +2859,15 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litemap" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" [[package]] name = "local-ip-address" -version = "0.6.10" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79ef8c257c92ade496781a32a581d43e3d512cf8ce714ecf04ea80f93ed0ff4a" +checksum = "d4a59a0cb1c7f84471ad5cd38d768c2a29390d17f1ff2827cdf49bc53e8ac70b" dependencies = [ "libc", "neli", @@ -2946,9 +2973,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ "libc", "wasi", @@ -3187,9 +3214,9 @@ dependencies = [ [[package]] name = "num-conv" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050" +checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" [[package]] name = "num-integer" @@ -3242,9 +3269,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.21.3" +version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "once_cell_polyfill" @@ -3260,9 +3287,9 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "openssl" -version = "0.10.75" +version = "0.10.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328" +checksum = "951c002c75e16ea2c65b8c7e4d3d51d5530d8dfa7d060b4776828c88cfb18ecf" dependencies = [ "bitflags", "cfg-if", @@ -3292,9 +3319,9 @@ checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" [[package]] name = "openssl-sys" -version = "0.9.111" +version = "0.9.112" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82cab2d520aa75e3c58898289429321eb788c3106963d0dc886ec7a5f4adc321" +checksum = "57d55af3b3e226502be1526dfdba67ab0e9c96fc293004e79576b2b9edb0dbdb" dependencies = [ "cc", "libc", @@ -3554,18 +3581,18 @@ checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" [[package]] name = "portable-atomic-util" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a9db96d7fa8782dd8c15ce32ffe8680bbd1e978a43bf51a34d39483540495f5" +checksum = "091397be61a01d4be58e7841595bd4bfedb15f1cd54977d79b8271e94ed799a3" dependencies = [ "portable-atomic", ] [[package]] name = "potential_utf" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" dependencies = [ "zerovec", ] @@ -3582,7 +3609,7 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ - "zerocopy 0.8.40", + "zerocopy 0.8.48", ] [[package]] @@ -3633,11 +3660,11 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "3.4.0" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit 0.23.10+spec-1.0.0", + "toml_edit 0.25.10+spec-1.1.0", ] [[package]] @@ -3760,7 +3787,7 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls", - "socket2 0.6.2", + "socket2 0.6.3", "thiserror 2.0.18", "tokio", "tracing", @@ -3769,9 +3796,9 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.13" +version = "0.11.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" dependencies = [ "aws-lc-rs", "bytes", @@ -3798,16 +3825,16 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.6.2", + "socket2 0.6.3", "tracing", "windows-sys 0.60.2", ] [[package]] name = "quote" -version = "1.0.44" +version = "1.0.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" dependencies = [ "proc-macro2", ] @@ -3818,6 +3845,12 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + [[package]] name = "r2d2" version = "0.8.10" @@ -3841,9 +3874,9 @@ dependencies = [ [[package]] name = "r2d2_sqlite" -version = "0.32.0" +version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2ebd03c29250cdf191da93a35118b4567c2ef0eacab54f65e058d6f4c9965f6" +checksum = "5576df16239e4e422c4835c8ed00be806d4491855c7847dba60b7aa8408b469b" dependencies = [ "r2d2", "rusqlite", @@ -3884,7 +3917,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc266eb313df6c5c09c1c7b1fbe2510961e5bcd3add930c1e31f7ed9da0feff8" dependencies = [ "chacha20", - "getrandom 0.4.1", + "getrandom 0.4.2", "rand_core 0.10.0", ] @@ -4200,9 +4233,9 @@ dependencies = [ [[package]] name = "rusqlite" -version = "0.38.0" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1c93dd1c9683b438c392c492109cb702b8090b2bfc8fed6f6e4eb4523f17af3" +checksum = "a0d2b0146dd9661bf67bb107c0bb2a55064d556eeb3fc314151b957f313bcd4e" dependencies = [ "bitflags", "fallible-iterator", @@ -4215,9 +4248,9 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.40.0" +version = "1.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61f703d19852dbf87cbc513643fa81428361eb6940f1ac14fd58155d295a3eb0" +checksum = "2ce901f9a19d251159075a4c37af514c3b8ef99c22e02dd8c19161cf397ee94a" dependencies = [ "arrayvec", "borsh", @@ -4227,6 +4260,7 @@ dependencies = [ "rkyv", "serde", "serde_json", + "wasm-bindgen", ] [[package]] @@ -4237,9 +4271,9 @@ checksum = "b50b8869d9fc858ce7266cce0194bd74df58b9d0e3f6df3a9fc8eb470d95c09d" [[package]] name = "rustc-hash" -version = "2.1.1" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" [[package]] name = "rustc_version" @@ -4330,9 +4364,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] name = "rustls-webpki" -version = "0.103.9" +version = "0.103.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53" +checksum = "df33b2b81ac578cabaf06b89b0631153a3f416b0a886e8a7a1707fb51abbd1ef" dependencies = [ "aws-lc-rs", "ring", @@ -4369,9 +4403,9 @@ checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" [[package]] name = "schannel" -version = "0.1.28" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" dependencies = [ "windows-sys 0.61.2", ] @@ -4446,9 +4480,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.27" +version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "serde" @@ -4507,7 +4541,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2f2d7ff8a2140333718bb329f5c40fc5f0865b84c426183ce14c97d2ab8154f" dependencies = [ "form_urlencoded", - "indexmap 2.13.0", + "indexmap 2.13.1", "itoa", "ryu", "serde_core", @@ -4519,7 +4553,7 @@ version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" dependencies = [ - "indexmap 2.13.0", + "indexmap 2.13.1", "itoa", "memchr", "serde", @@ -4560,9 +4594,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.0.4" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8bbf91e5a4d6315eee45e704372590b30e260ee83af6639d64557f51b067776" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" dependencies = [ "serde_core", ] @@ -4581,15 +4615,15 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.17.0" +version = "3.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "381b283ce7bc6b476d903296fb59d0d36633652b633b27f64db4fb46dcbfc3b9" +checksum = "dd5414fad8e6907dbdd5bc441a50ae8d6e26151a03b1de04d89a5576de61d01f" dependencies = [ "base64 0.22.1", "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.13.0", + "indexmap 2.13.1", "schemars 0.9.0", "schemars 1.2.1", "serde_core", @@ -4600,11 +4634,11 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.17.0" +version = "3.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6d4e30573c8cb306ed6ab1dca8423eec9a463ea0e155f45399455e0368b27e0" +checksum = "d3db8978e608f1fe7357e211969fd9abdcae80bac1ba7a3369bb7eb6b404eb65" dependencies = [ - "darling 0.21.3", + "darling 0.23.0", "proc-macro2", "quote", "syn 2.0.117", @@ -4659,9 +4693,9 @@ dependencies = [ [[package]] name = "simd-adler32" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" +checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" [[package]] name = "simdutf8" @@ -4699,12 +4733,12 @@ dependencies = [ [[package]] name = "socket2" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4885,12 +4919,12 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.26.0" +version = "3.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82a72c767771b47409d2345987fda8628641887d5466101319899796367354a0" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.1", + "getrandom 0.4.2", "once_cell", "rustix", "windows-sys 0.61.2", @@ -4907,12 +4941,12 @@ dependencies = [ [[package]] name = "terminal_size" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60b8cb979cb11c32ce1603f8137b22262a9d131aaa5c37b5678025f22b8becd0" +checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" dependencies = [ "rustix", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4923,9 +4957,9 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "testcontainers" -version = "0.27.1" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1c0624faaa317c56d6d19136580be889677259caf5c897941c6f446b4655068" +checksum = "0bd36b06a2a6c0c3c81a83be1ab05fe86460d054d4d51bf513bc56b3e15bdc22" dependencies = [ "astral-tokio-tar", "async-trait", @@ -5044,9 +5078,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" dependencies = [ "displaydoc", "zerovec", @@ -5064,9 +5098,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" dependencies = [ "tinyvec_macros", ] @@ -5079,25 +5113,25 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.49.0" +version = "1.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86" +checksum = "2bd1c4c0fc4a7ab90fc15ef6daaa3ec3b893f004f915f2392557ed23237820cd" dependencies = [ "bytes", "libc", "mio", "pin-project-lite", "signal-hook-registry", - "socket2 0.6.2", + "socket2 0.6.3", "tokio-macros", "windows-sys 0.61.2", ] [[package]] name = "tokio-macros" -version = "2.6.1" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c55a2eff8b69ce66c84f85e1da1c233edc36ceb85a2058d11b0d6a3c7e7569c" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" dependencies = [ "proc-macro2", "quote", @@ -5156,13 +5190,13 @@ version = "0.9.12+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" dependencies = [ - "indexmap 2.13.0", + "indexmap 2.13.1", "serde_core", - "serde_spanned 1.0.4", + "serde_spanned 1.1.1", "toml_datetime 0.7.5+spec-1.1.0", "toml_parser", "toml_writer", - "winnow", + "winnow 0.7.15", ] [[package]] @@ -5183,39 +5217,48 @@ dependencies = [ "serde_core", ] +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + [[package]] name = "toml_edit" version = "0.22.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ - "indexmap 2.13.0", + "indexmap 2.13.1", "serde", "serde_spanned 0.6.9", "toml_datetime 0.6.11", "toml_write", - "winnow", + "winnow 0.7.15", ] [[package]] name = "toml_edit" -version = "0.23.10+spec-1.0.0" +version = "0.25.10+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84c8b9f757e028cee9fa244aea147aab2a9ec09d5325a9b01e0a49730c2b5269" +checksum = "a82418ca169e235e6c399a84e395ab6debeb3bc90edc959bf0f48647c6a32d1b" dependencies = [ - "indexmap 2.13.0", - "toml_datetime 0.7.5+spec-1.1.0", + "indexmap 2.13.1", + "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", - "winnow", + "winnow 1.0.1", ] [[package]] name = "toml_parser" -version = "1.0.9+spec-1.1.0" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "702d4415e08923e7e1ef96cd5727c0dfed80b4d2fa25db9647fe5eb6f7c5a4c4" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" dependencies = [ - "winnow", + "winnow 1.0.1", ] [[package]] @@ -5226,9 +5269,9 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" [[package]] name = "toml_writer" -version = "1.0.6+spec-1.1.0" +version = "1.1.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607" +checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" [[package]] name = "tonic" @@ -5249,7 +5292,7 @@ dependencies = [ "hyper-util", "percent-encoding", "pin-project", - "socket2 0.6.2", + "socket2 0.6.3", "sync_wrapper", "tokio", "tokio-stream", @@ -5693,7 +5736,7 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ "futures-core", "futures-util", - "indexmap 2.13.0", + "indexmap 2.13.1", "pin-project-lite", "slab", "sync_wrapper", @@ -5796,9 +5839,9 @@ dependencies = [ [[package]] name = "tracing-subscriber" -version = "0.3.22" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" dependencies = [ "nu-ansi-term", "serde", @@ -5857,9 +5900,9 @@ checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" [[package]] name = "unicode-segmentation" -version = "1.12.0" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" +checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" [[package]] name = "unicode-width" @@ -5887,9 +5930,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "ureq" -version = "3.2.0" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdc97a28575b85cfedf2a7e7d3cc64b3e11bd8ac766666318003abbacc7a21fc" +checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0" dependencies = [ "base64 0.22.1", "log", @@ -5897,14 +5940,14 @@ dependencies = [ "rustls", "rustls-pki-types", "ureq-proto", - "utf-8", + "utf8-zero", ] [[package]] name = "ureq-proto" -version = "0.5.3" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d81f9efa9df032be5934a46a068815a10a042b494b6a58cb0a1a97bb5467ed6f" +checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c" dependencies = [ "base64 0.22.1", "http", @@ -5926,10 +5969,10 @@ dependencies = [ ] [[package]] -name = "utf-8" -version = "0.7.6" +name = "utf8-zero" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" [[package]] name = "utf8_iter" @@ -5945,13 +5988,13 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.21.0" +version = "1.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b672338555252d43fd2240c714dc444b8c6fb0a5c5335e65a07bba7742735ddb" +checksum = "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9" dependencies = [ - "getrandom 0.4.1", + "getrandom 0.4.2", "js-sys", - "rand 0.9.2", + "rand 0.10.0", "wasm-bindgen", ] @@ -6024,36 +6067,33 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.114" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e" +checksum = "0551fc1bb415591e3372d0bc4780db7e587d84e2a7e79da121051c5c4b89d0b0" dependencies = [ "cfg-if", "once_cell", "rustversion", + "serde", "wasm-bindgen-macro", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.64" +version = "0.4.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9c5522b3a28661442748e09d40924dfb9ca614b21c00d3fd135720e48b67db8" +checksum = "03623de6905b7206edd0a75f69f747f134b7f0a2323392d664448bf2d3c5d87e" dependencies = [ - "cfg-if", - "futures-util", "js-sys", - "once_cell", "wasm-bindgen", - "web-sys", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.114" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6" +checksum = "7fbdf9a35adf44786aecd5ff89b4563a90325f9da0923236f6104e603c7e86be" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -6061,9 +6101,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.114" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3" +checksum = "dca9693ef2bab6d4e6707234500350d8dad079eb508dca05530c85dc3a529ff2" dependencies = [ "bumpalo", "proc-macro2", @@ -6074,9 +6114,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.114" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16" +checksum = "39129a682a6d2d841b6c429d0c51e5cb0ed1a03829d8b3d1e69a011e62cb3d3b" dependencies = [ "unicode-ident", ] @@ -6098,7 +6138,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" dependencies = [ "anyhow", - "indexmap 2.13.0", + "indexmap 2.13.1", "wasm-encoder", "wasmparser", ] @@ -6111,15 +6151,15 @@ checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ "bitflags", "hashbrown 0.15.5", - "indexmap 2.13.0", + "indexmap 2.13.1", "semver", ] [[package]] name = "web-sys" -version = "0.3.91" +version = "0.3.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9" +checksum = "cd70027e39b12f0849461e08ffc50b9cd7688d942c1c8e3c7b22273236b4dd0a" dependencies = [ "js-sys", "wasm-bindgen", @@ -6469,9 +6509,18 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" [[package]] name = "winnow" -version = "0.7.14" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829" +checksum = "09dac053f1cd375980747450bfc7250c264eaae0583872e845c0c7cd578872b5" dependencies = [ "memchr", ] @@ -6504,7 +6553,7 @@ checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" dependencies = [ "anyhow", "heck", - "indexmap 2.13.0", + "indexmap 2.13.1", "prettyplease", "syn 2.0.117", "wasm-metadata", @@ -6535,7 +6584,7 @@ checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", "bitflags", - "indexmap 2.13.0", + "indexmap 2.13.1", "log", "serde", "serde_derive", @@ -6554,7 +6603,7 @@ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" dependencies = [ "anyhow", "id-arena", - "indexmap 2.13.0", + "indexmap 2.13.1", "log", "semver", "serde", @@ -6566,9 +6615,9 @@ dependencies = [ [[package]] name = "writeable" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" [[package]] name = "wyz" @@ -6597,9 +6646,9 @@ checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" [[package]] name = "yoke" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -6608,9 +6657,9 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" dependencies = [ "proc-macro2", "quote", @@ -6630,11 +6679,11 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.40" +version = "0.8.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a789c6e490b576db9f7e6b6d661bcc9799f7c0ac8352f56ea20193b2681532e5" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" dependencies = [ - "zerocopy-derive 0.8.40", + "zerocopy-derive 0.8.48", ] [[package]] @@ -6650,9 +6699,9 @@ dependencies = [ [[package]] name = "zerocopy-derive" -version = "0.8.40" +version = "0.8.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f65c489a7071a749c849713807783f70672b28094011623e200cb86dcb835953" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" dependencies = [ "proc-macro2", "quote", @@ -6661,18 +6710,18 @@ dependencies = [ [[package]] name = "zerofrom" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" dependencies = [ "zerofrom-derive", ] [[package]] name = "zerofrom-derive" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" dependencies = [ "proc-macro2", "quote", @@ -6688,9 +6737,9 @@ checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" [[package]] name = "zerotrie" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" dependencies = [ "displaydoc", "yoke", @@ -6699,9 +6748,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.5" +version = "0.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" dependencies = [ "yoke", "zerofrom", @@ -6710,9 +6759,9 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" dependencies = [ "proc-macro2", "quote", From 48e9606219dd27e69d1db8620be3dd754cb7a8c2 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 Apr 2026 09:00:06 +0100 Subject: [PATCH 1285/1297] refactor: extract project dictionary from cSpell.json Move the project-specific word list from the inline 'words' array in cSpell.json into a dedicated project-words.txt dictionary file, following the same pattern used in other Torrust organisation repositories. Update packages/metrics/cSpell.json to reference the shared dictionary instead of maintaining its own inline word list. Closes #1484 --- cSpell.json | 217 +++-------------------------------- packages/metrics/cSpell.json | 26 ++--- project-words.txt | 199 ++++++++++++++++++++++++++++++++ 3 files changed, 228 insertions(+), 214 deletions(-) create mode 100644 project-words.txt diff --git a/cSpell.json b/cSpell.json index 81421e050..43eb391d3 100644 --- a/cSpell.json +++ b/cSpell.json @@ -1,208 +1,23 @@ { - "words": [ - "Addrs", - "adduser", - "alekitto", - "appuser", - "Arvid", - "ASMS", - "asyn", - "autoclean", - "AUTOINCREMENT", - "automock", - "Avicora", - "Azureus", - "bdecode", - "bencode", - "bencoded", - "bencoding", - "beps", - "binascii", - "binstall", - "Bitflu", - "bools", - "Bragilevsky", - "bufs", - "buildid", - "Buildx", - "byteorder", - "callgrind", - "camino", - "canonicalize", - "canonicalized", - "certbot", - "chrono", - "Cinstrument", - "ciphertext", - "clippy", - "cloneable", - "codecov", - "codegen", - "completei", - "Condvar", - "connectionless", - "Containerfile", - "conv", - "curr", - "cvar", - "Cyberneering", - "dashmap", - "datagram", - "datetime", - "debuginfo", - "Deque", - "Dijke", - "distroless", - "dockerhub", - "downloadedi", - "dtolnay", - "elif", - "endianness", - "Eray", - "filesd", - "flamegraph", - "formatjson", - "Freebox", - "Frostegård", - "gecos", - "Gibibytes", - "Grcov", - "hasher", - "healthcheck", - "heaptrack", - "hexlify", - "hlocalhost", - "Hydranode", - "hyperthread", - "Icelake", - "iiiiiiiiiiiiiiiiiiiid", - "imdl", - "impls", - "incompletei", - "infohash", - "infohashes", - "infoschema", - "Intermodal", - "intervali", - "Joakim", - "kallsyms", - "Karatay", - "kcachegrind", - "kexec", - "keyout", - "Kibibytes", - "kptr", - "lcov", - "leecher", - "leechers", - "libsqlite", - "libtorrent", - "libz", - "LOGNAME", - "Lphant", - "matchmakes", - "Mebibytes", - "metainfo", - "middlewares", - "misresolved", - "mockall", - "multimap", - "myacicontext", - "ñaca", - "Naim", - "nanos", - "newkey", - "nextest", - "nocapture", - "nologin", - "nonroot", - "Norberg", - "numwant", - "nvCFlJCq7fz7Qx6KoKTDiMZvns8l5Kw7", - "oneshot", - "ostr", - "Pando", - "peekable", - "peerlist", - "programatik", - "proot", - "proto", - "Quickstart", - "Radeon", - "Rakshasa", - "Rasterbar", - "realpath", - "reannounce", - "Registar", - "repr", - "reqs", - "reqwest", - "rerequests", - "ringbuf", - "ringsize", - "rngs", - "rosegment", - "routable", - "rstest", - "rusqlite", - "rustc", - "RUSTDOCFLAGS", - "RUSTFLAGS", - "rustfmt", - "Rustls", - "Ryzen", - "Seedable", - "serde", - "Shareaza", - "sharktorrent", - "SHLVL", - "skiplist", - "slowloris", - "socketaddr", - "sqllite", - "subsec", - "Swatinem", - "Swiftbit", - "taiki", - "tdyne", - "Tebibytes", - "tempfile", - "testcontainers", - "thiserror", - "tlsv", - "Torrentstorm", - "torrust", - "torrustracker", - "trackerid", - "Trackon", - "typenum", - "udpv", - "Unamed", - "underflows", - "Unsendable", - "untuple", - "uroot", - "Vagaa", - "valgrind", - "Vitaly", - "vmlinux", - "Vuze", - "Weidendorfer", - "Werror", - "whitespaces", - "Xacrimon", - "XBTT", - "Xdebug", - "Xeon", - "Xtorrent", - "Xunlei", - "xxxxxxxxxxxxxxxxxxxxd", - "yyyyyyyyyyyyyyyyyyyyd", - "zerocopy" + "$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json", + "version": "0.2", + "dictionaryDefinitions": [ + { + "name": "project-words", + "path": "./project-words.txt", + "addWords": true + } + ], + "dictionaries": [ + "project-words" ], "enableFiletypes": [ "dockerfile", "shellscript", "toml" + ], + "ignorePaths": [ + "target", + "/project-words.txt" ] -} +} \ No newline at end of file diff --git a/packages/metrics/cSpell.json b/packages/metrics/cSpell.json index f04cce9e3..8f5002833 100644 --- a/packages/metrics/cSpell.json +++ b/packages/metrics/cSpell.json @@ -1,21 +1,21 @@ { - "words": [ - "cloneable", - "formatjson", - "Gibibytes", - "Kibibytes", - "Mebibytes", - "ñaca", - "println", - "rstest", - "serde", - "subsec", - "Tebibytes", - "thiserror" + "$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json", + "version": "0.2", + "dictionaryDefinitions": [ + { + "name": "project-words", + "path": "../../project-words.txt", + "addWords": true + } ], + "dictionaries": ["project-words"], "enableFiletypes": [ "dockerfile", "shellscript", "toml" + ], + "ignorePaths": [ + "target", + "/project-words.txt" ] } diff --git a/project-words.txt b/project-words.txt new file mode 100644 index 000000000..c698eea9c --- /dev/null +++ b/project-words.txt @@ -0,0 +1,199 @@ +Addrs +adduser +alekitto +appuser +Arvid +ASMS +asyn +autoclean +AUTOINCREMENT +automock +Avicora +Azureus +bdecode +bencode +bencoded +bencoding +beps +binascii +binstall +Bitflu +bools +Bragilevsky +bufs +buildid +Buildx +byteorder +callgrind +camino +canonicalize +canonicalized +certbot +chrono +Cinstrument +ciphertext +clippy +cloneable +codecov +codegen +completei +Condvar +connectionless +Containerfile +conv +curr +cvar +Cyberneering +dashmap +datagram +datetime +debuginfo +Deque +Dijke +distroless +dockerhub +downloadedi +dtolnay +elif +endianness +Eray +filesd +flamegraph +formatjson +Freebox +Frostegård +gecos +Gibibytes +Grcov +hasher +healthcheck +heaptrack +hexlify +hlocalhost +Hydranode +hyperthread +Icelake +iiiiiiiiiiiiiiiiiiiid +imdl +impls +incompletei +infohash +infohashes +infoschema +Intermodal +intervali +Joakim +kallsyms +Karatay +kcachegrind +kexec +keyout +Kibibytes +kptr +lcov +leecher +leechers +libsqlite +libtorrent +libz +LOGNAME +Lphant +matchmakes +Mebibytes +metainfo +middlewares +misresolved +mockall +multimap +myacicontext +ñaca +Naim +nanos +newkey +nextest +nocapture +nologin +nonroot +Norberg +numwant +nvCFlJCq7fz7Qx6KoKTDiMZvns8l5Kw7 +oneshot +ostr +Pando +peekable +peerlist +programatik +proot +proto +Quickstart +Radeon +Rakshasa +Rasterbar +realpath +reannounce +Registar +repr +reqs +reqwest +rerequests +ringbuf +ringsize +rngs +rosegment +routable +rstest +rusqlite +rustc +RUSTDOCFLAGS +RUSTFLAGS +rustfmt +Rustls +Ryzen +Seedable +serde +Shareaza +sharktorrent +SHLVL +skiplist +slowloris +socketaddr +sqllite +subsec +Swatinem +Swiftbit +taiki +tdyne +Tebibytes +tempfile +testcontainers +thiserror +tlsv +Torrentstorm +torrust +torrustracker +trackerid +Trackon +typenum +udpv +Unamed +underflows +Unsendable +untuple +uroot +Vagaa +valgrind +Vitaly +vmlinux +Vuze +Weidendorfer +Werror +whitespaces +Xacrimon +XBTT +Xdebug +Xeon +Xtorrent +Xunlei +xxxxxxxxxxxxxxxxxxxxd +yyyyyyyyyyyyyyyyyyyyd +zerocopy From c88f66cd42c733fafc5b7b4afeb862b7b3b28329 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 8 Apr 2026 09:19:40 +0000 Subject: [PATCH 1286/1297] chore(deps): bump docker/login-action from 3 to 4 Bumps [docker/login-action](https://github.com/docker/login-action) from 3 to 4. - [Release notes](https://github.com/docker/login-action/releases) - [Commits](https://github.com/docker/login-action/compare/v3...v4) --- updated-dependencies: - dependency-name: docker/login-action dependency-version: '4' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/container.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index 7416df71e..2f2b0780c 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -117,7 +117,7 @@ jobs: - id: login name: Login to Docker Hub - uses: docker/login-action@v3 + uses: docker/login-action@v4 with: username: ${{ secrets.DOCKER_HUB_USERNAME }} password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} @@ -158,7 +158,7 @@ jobs: - id: login name: Login to Docker Hub - uses: docker/login-action@v3 + uses: docker/login-action@v4 with: username: ${{ secrets.DOCKER_HUB_USERNAME }} password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} From 504135d009b2c16768ed13ce4b44ddf50b7d2f2b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 8 Apr 2026 09:19:47 +0000 Subject: [PATCH 1287/1297] chore(deps): bump docker/metadata-action from 5 to 6 Bumps [docker/metadata-action](https://github.com/docker/metadata-action) from 5 to 6. - [Release notes](https://github.com/docker/metadata-action/releases) - [Commits](https://github.com/docker/metadata-action/compare/v5...v6) --- updated-dependencies: - dependency-name: docker/metadata-action dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/container.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index 2f2b0780c..0615ad6be 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -108,7 +108,7 @@ jobs: steps: - id: meta name: Docker Meta - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v6 with: images: | "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" @@ -146,7 +146,7 @@ jobs: steps: - id: meta name: Docker Meta - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v6 with: images: | "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" From 2c78850ab49ede86f36f1d98f93f45b890b98895 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 8 Apr 2026 09:19:32 +0000 Subject: [PATCH 1288/1297] chore(deps): bump docker/setup-buildx-action from 3 to 4 Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 3 to 4. - [Release notes](https://github.com/docker/setup-buildx-action/releases) - [Commits](https://github.com/docker/setup-buildx-action/compare/v3...v4) --- updated-dependencies: - dependency-name: docker/setup-buildx-action dependency-version: '4' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/container.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index 0615ad6be..f09a94bca 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -26,7 +26,7 @@ jobs: steps: - id: setup name: Setup Toolchain - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@v4 - id: build name: Build @@ -124,7 +124,7 @@ jobs: - id: setup name: Setup Toolchain - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@v4 - name: Build and push uses: docker/build-push-action@v6 @@ -165,7 +165,7 @@ jobs: - id: setup name: Setup Toolchain - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@v4 - name: Build and push uses: docker/build-push-action@v6 From 4f3f1956f4a8d1839f95bd697b851ab04df31fbd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 8 Apr 2026 09:19:27 +0000 Subject: [PATCH 1289/1297] chore(deps): bump docker/build-push-action from 6 to 7 Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 6 to 7. - [Release notes](https://github.com/docker/build-push-action/releases) - [Commits](https://github.com/docker/build-push-action/compare/v6...v7) --- updated-dependencies: - dependency-name: docker/build-push-action dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/container.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index f09a94bca..e0857e936 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -30,7 +30,7 @@ jobs: - id: build name: Build - uses: docker/build-push-action@v6 + uses: docker/build-push-action@v7 with: file: ./Containerfile push: false @@ -127,7 +127,7 @@ jobs: uses: docker/setup-buildx-action@v4 - name: Build and push - uses: docker/build-push-action@v6 + uses: docker/build-push-action@v7 with: file: ./Containerfile push: true @@ -168,7 +168,7 @@ jobs: uses: docker/setup-buildx-action@v4 - name: Build and push - uses: docker/build-push-action@v6 + uses: docker/build-push-action@v7 with: file: ./Containerfile push: true From f2612dc1fa0aa242503b0354227b644a12fbe47d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 Apr 2026 12:34:06 +0100 Subject: [PATCH 1290/1297] docs(issue-523): add internal linting implementation plan --- docs/issues/523-internal-linting-tool.md | 141 +++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 docs/issues/523-internal-linting-tool.md diff --git a/docs/issues/523-internal-linting-tool.md b/docs/issues/523-internal-linting-tool.md new file mode 100644 index 000000000..14593e190 --- /dev/null +++ b/docs/issues/523-internal-linting-tool.md @@ -0,0 +1,141 @@ +# Issue #523 Implementation Plan (Internal Linting Tool) + +## Goal + +Replace the MegaLinter idea with Torrust internal linting tooling and integrate it into CI for this repository. + +## Scope + +- Target issue: https://github.com/torrust/torrust-tracker/issues/523 +- CI workflow to modify: .github/workflows/testing.yaml +- External reference workflow: https://raw.githubusercontent.com/torrust/torrust-tracker-deployer/refs/heads/main/.github/workflows/linting.yml + +## Tasks + +### 0) Create a local branch following GitHub branch naming conventions + +- Approved branch name: `523-internal-linting-tool` +- Commands: + - `git fetch --all --prune` + - `git checkout develop` + - `git pull --ff-only` + - `git checkout -b 523-internal-linting-tool` +- Checkpoint: + - `git branch --show-current` should output `523-internal-linting-tool`. + +### 1) Install and run the linting tool locally; verify it passes in this repo + +- Identify/install internal linting package/tool used by Torrust (likely `torrust-linting` or equivalent wrapper). +- Ensure local runtime dependencies are present (if any). +- Note: linter config files (step 2) must exist in the repo root before a full suite run; it is fine to do a first exploratory run first to discover which linters are active. +- Run the internal linting command against this repository. +- Capture the exact command and output summary for reproducibility. +- Checkpoint: + - Linting command exits with code `0`. + +### 2) Add and adapt linter configuration files + +Some linters require a config file in the repo root. Use the deployer configs as reference and adapt values to this repository. + +| File | Linter | Reference | +| -------------------- | ---------------- | ----------------------------------------------------------------------------------------------------- | +| `.markdownlint.json` | markdownlint | https://raw.githubusercontent.com/torrust/torrust-tracker-deployer/refs/heads/main/.markdownlint.json | +| `.taplo.toml` | taplo (TOML fmt) | https://raw.githubusercontent.com/torrust/torrust-tracker-deployer/refs/heads/main/.taplo.toml | +| `.yamllint-ci.yml` | yamllint | https://raw.githubusercontent.com/torrust/torrust-tracker-deployer/refs/heads/main/.yamllint-ci.yml | + +Key adaptations to make per file: + +- `.markdownlint.json`: review line-length rules and Markdown conventions used in this repo's docs. +- `.taplo.toml`: update `exclude` list to match this repo's generated/runtime folders (e.g. `target/**`, `storage/**`) instead of the deployer-specific ones (`build/**`, `data/**`, `envs/**`). +- `.yamllint-ci.yml`: update `ignore` block to reflect this repo's generated/runtime directories instead of cloud-init and deployer folders. + +Commit message: `ci(lint): add linter config files (.markdownlint.json, .taplo.toml, .yamllint-ci.yml)` + +Checkpoint: + +- Config files are present in the repo root. +- Running each individual linter against the repo with the config produces expected/controlled output. + +### 3) If local linting fails, fix all lint errors; commit fixes independently per linter + +- If the linting suite reports failures: + - Group findings by linter (for example: formatting, clippy, docs, spelling, yaml, etc.). + - Fix only one linter category at a time. + - Create one commit per linter category. +- Commit style proposal: + - `fix(lint/): resolve ` +- Constraints: + - Do not mix workflow/tooling changes with source lint fixes in the same commit. + - Keep each commit minimal and reviewable. +- Checkpoint: + - Re-run linting suite; all checks pass before moving to workflow integration. + +### 4) Review existing workflow example using internal linting + +- Read and analyze: + - https://raw.githubusercontent.com/torrust/torrust-tracker-deployer/refs/heads/main/.github/workflows/linting.yml +- Extract and adapt: + - Trigger strategy. + - Tool setup/install method. + - Cache strategy. + - Invocation command and CI fail behavior. +- Checkpoint: + - Document a short mapping from deployer workflow pattern to this repo’s `testing.yaml` job structure. + +### 5) Modify `.github/workflows/testing.yaml` to use the internal linting tool + +- Update the current `check`/lint-related section to run the internal linting command. +- Replace existing lint/check execution path with the internal linting tool in this migration (no parallel transition mode). +- Ensure matrix/toolchain compatibility is explicit (nightly/stable behavior decided and documented). +- Validate workflow syntax before commit. +- Checkpoint: + - Workflow is valid and executes linting through internal tool. + +### 6) Commit workflow changes + +- Commit only workflow-related changes in a dedicated commit. +- Commit message proposal: + - `ci(lint): switch testing workflow to internal linting tool` +- Checkpoint: + - `git show --name-only --stat HEAD` includes only expected workflow files (and any required supporting CI files if intentionally added). + +### 7) Push to remote `josecelano` and open PR into `develop` + +- Verify remote exists: + - `git remote -v` +- Push branch: + - `git push -u josecelano 523-internal-linting-tool` +- Open PR targeting `torrust/torrust-tracker:develop` with head `josecelano:523-internal-linting-tool`. +- PR content should include: + - Why internal linting over MegaLinter. + - Summary of lint-fix commits by linter. + - Summary of workflow change. + - Evidence (local run + CI status). +- Checkpoint: + - PR is open, linked to issue #523, and ready for review. + +## Execution Notes + +- Keep PR review-friendly by separating commits by concern: + 1. Linter config files (step 2) + 2. Per-linter source fixes (step 3, only if needed) + 3. CI workflow migration (step 6) +- Use Conventional Commits for all commits in this implementation. +- If lint checks differ between local and CI, align tool versions and execution flags before merging. +- Avoid broad refactors unrelated to lint failures. + +## Decisions Confirmed + +1. Branch name: `523-internal-linting-tool`. +2. CI strategy: replace existing lint/check path with internal linting. +3. Commit convention: yes, use Conventional Commits. +4. PR target: base `torrust/torrust-tracker:develop`, head `josecelano:523-internal-linting-tool`. + +## Risks and Mitigations + +- Risk: Internal linting wrapper may not be version-pinned and may produce unstable CI behavior. + - Mitigation: Pin tool version in workflow installation step. +- Risk: Internal linting may overlap with existing checks, increasing CI time. + - Mitigation: Remove redundant jobs only after verifying coverage parity. +- Risk: Tool may require secrets or environment assumptions not available in CI. + - Mitigation: Run dry-run in GitHub Actions on branch before requesting review. From fa3b491bb70348be86bc51f80431ece411596554 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 Apr 2026 16:00:55 +0100 Subject: [PATCH 1291/1297] ci(lint): add linter config files --- .markdownlint.json | 18 ++++++++++++++++++ .taplo.toml | 31 +++++++++++++++++++++++++++++++ .yamllint-ci.yml | 16 ++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 .markdownlint.json create mode 100644 .taplo.toml create mode 100644 .yamllint-ci.yml diff --git a/.markdownlint.json b/.markdownlint.json new file mode 100644 index 000000000..19ec47c2e --- /dev/null +++ b/.markdownlint.json @@ -0,0 +1,18 @@ +{ + "default": true, + "MD013": false, + "MD031": true, + "MD032": true, + "MD040": true, + "MD022": true, + "MD009": true, + "MD007": { + "indent": 2 + }, + "MD026": false, + "MD041": false, + "MD034": false, + "MD024": false, + "MD033": false, + "MD060": false +} diff --git a/.taplo.toml b/.taplo.toml new file mode 100644 index 000000000..d0f755dcd --- /dev/null +++ b/.taplo.toml @@ -0,0 +1,31 @@ +# Taplo configuration file for TOML formatting +# Used by the "Even Better TOML" VS Code extension + +# Exclude generated and runtime folders from linting +exclude = [ + "target/**", + "storage/**", + ".coverage/**", +] + +[formatting] +# Preserve blank lines that exist +allowed_blank_lines = 1 +# Don't reorder keys to maintain structure +reorder_keys = false +# Array formatting +array_trailing_comma = true +array_auto_expand = false +array_auto_collapse = false +# Inline table formatting +inline_table_expand = false +compact_inline_tables = false +compact_arrays = false +# Alignment +align_entries = false +align_comments = true +# Indentation +indent_tables = false +indent_entries = false +# Other +trailing_newline = true diff --git a/.yamllint-ci.yml b/.yamllint-ci.yml new file mode 100644 index 000000000..9380b592a --- /dev/null +++ b/.yamllint-ci.yml @@ -0,0 +1,16 @@ +extends: default + +rules: + line-length: + max: 200 # More reasonable for infrastructure code + comments: + min-spaces-from-content: 1 # Allow single space before comments + document-start: disable # Most project YAML files don't require --- + truthy: + allowed-values: ["true", "false", "yes", "no", "on", "off"] # Allow common GitHub Actions values + +# Ignore generated/runtime directories +ignore: | + target/** + storage/** + .coverage/** From bc1f8cc72c0f8752480321860262a4e04f14305f Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 Apr 2026 16:09:21 +0100 Subject: [PATCH 1292/1297] fix(lint/clippy): resolve pedantic duration and style violations --- packages/axum-rest-tracker-api-server/src/server.rs | 4 ++-- .../benches/http_tracker_core_benchmark.rs | 2 +- .../benches/repository_benchmark.rs | 8 ++++---- .../torrent-repository-benchmarking/tests/entry/mod.rs | 5 +++-- .../tests/repository/mod.rs | 5 +++-- packages/tracker-client/src/udp/client.rs | 2 +- .../benches/udp_tracker_core_benchmark.rs | 2 +- packages/udp-tracker-server/src/server/launcher.rs | 2 +- packages/udp-tracker-server/src/statistics/repository.rs | 4 ++-- packages/udp-tracker-server/tests/server/contract.rs | 2 +- 10 files changed, 19 insertions(+), 17 deletions(-) diff --git a/packages/axum-rest-tracker-api-server/src/server.rs b/packages/axum-rest-tracker-api-server/src/server.rs index 05adeae8a..9eef6b71a 100644 --- a/packages/axum-rest-tracker-api-server/src/server.rs +++ b/packages/axum-rest-tracker-api-server/src/server.rs @@ -220,9 +220,9 @@ pub struct Launcher { impl std::fmt::Display for Launcher { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.tls.is_some() { - write!(f, "(with socket): {}, using TLS", self.bind_to,) + write!(f, "(with socket): {}, using TLS", self.bind_to) } else { - write!(f, "(with socket): {}, without TLS", self.bind_to,) + write!(f, "(with socket): {}, without TLS", self.bind_to) } } } diff --git a/packages/http-tracker-core/benches/http_tracker_core_benchmark.rs b/packages/http-tracker-core/benches/http_tracker_core_benchmark.rs index aa50ceeb9..c193c5124 100644 --- a/packages/http-tracker-core/benches/http_tracker_core_benchmark.rs +++ b/packages/http-tracker-core/benches/http_tracker_core_benchmark.rs @@ -12,7 +12,7 @@ fn announce_once(c: &mut Criterion) { let mut group = c.benchmark_group("http_tracker_handle_announce_once"); group.warm_up_time(Duration::from_millis(500)); - group.measurement_time(Duration::from_millis(1000)); + group.measurement_time(Duration::from_secs(1)); group.bench_function("handle_announce_data", |b| { b.iter(|| sync::return_announce_data_once(100)); diff --git a/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs b/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs index a58207492..f5f8e4b28 100644 --- a/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs +++ b/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs @@ -17,7 +17,7 @@ fn add_one_torrent(c: &mut Criterion) { let mut group = c.benchmark_group("add_one_torrent"); group.warm_up_time(Duration::from_millis(500)); - group.measurement_time(Duration::from_millis(1000)); + group.measurement_time(Duration::from_secs(1)); group.bench_function("RwLockStd", |b| { b.iter_custom(sync::add_one_torrent::); @@ -74,7 +74,7 @@ fn add_multiple_torrents_in_parallel(c: &mut Criterion) { //group.sample_size(10); group.warm_up_time(Duration::from_millis(500)); - group.measurement_time(Duration::from_millis(1000)); + group.measurement_time(Duration::from_secs(1)); group.bench_function("RwLockStd", |b| { b.to_async(&rt) @@ -138,7 +138,7 @@ fn update_one_torrent_in_parallel(c: &mut Criterion) { //group.sample_size(10); group.warm_up_time(Duration::from_millis(500)); - group.measurement_time(Duration::from_millis(1000)); + group.measurement_time(Duration::from_secs(1)); group.bench_function("RwLockStd", |b| { b.to_async(&rt) @@ -202,7 +202,7 @@ fn update_multiple_torrents_in_parallel(c: &mut Criterion) { //group.sample_size(10); group.warm_up_time(Duration::from_millis(500)); - group.measurement_time(Duration::from_millis(1000)); + group.measurement_time(Duration::from_secs(1)); group.bench_function("RwLockStd", |b| { b.to_async(&rt) diff --git a/packages/torrent-repository-benchmarking/tests/entry/mod.rs b/packages/torrent-repository-benchmarking/tests/entry/mod.rs index 5cbb3b19c..86ca891d4 100644 --- a/packages/torrent-repository-benchmarking/tests/entry/mod.rs +++ b/packages/torrent-repository-benchmarking/tests/entry/mod.rs @@ -1,5 +1,4 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use std::ops::Sub; use std::time::Duration; use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes}; @@ -430,7 +429,9 @@ async fn it_should_remove_inactive_peers_beyond_cutoff( let now = clock::Working::now(); clock::Stopped::local_set(&now); - peer.updated = now.sub(EXPIRE); + peer.updated = now + .checked_sub(EXPIRE) + .expect("it_should_remove_inactive_peers_beyond_cutoff: EXPIRE must not exceed now"); torrent.upsert_peer(&peer).await; diff --git a/packages/torrent-repository-benchmarking/tests/repository/mod.rs b/packages/torrent-repository-benchmarking/tests/repository/mod.rs index ec7e68bae..fb0b8fcff 100644 --- a/packages/torrent-repository-benchmarking/tests/repository/mod.rs +++ b/packages/torrent-repository-benchmarking/tests/repository/mod.rs @@ -526,7 +526,6 @@ async fn it_should_remove_inactive_peers( repo: Repo, #[case] entries: Entries, ) { - use std::ops::Sub as _; use std::time::Duration; use torrust_tracker_clock::clock::stopped::Stopped as _; @@ -556,7 +555,9 @@ async fn it_should_remove_inactive_peers( let now = clock::Working::now(); clock::Stopped::local_set(&now); - peer.updated = now.sub(EXPIRE); + peer.updated = now + .checked_sub(EXPIRE) + .expect("it_should_remove_inactive_peers_beyond_cutoff: EXPIRE must not exceed now"); } // Insert the infohash and peer into the repository diff --git a/packages/tracker-client/src/udp/client.rs b/packages/tracker-client/src/udp/client.rs index 1c5ffd901..94c882d29 100644 --- a/packages/tracker-client/src/udp/client.rs +++ b/packages/tracker-client/src/udp/client.rs @@ -256,7 +256,7 @@ pub async fn check(service_binding: &ServiceBinding) -> Result { } }; - let sleep = time::sleep(Duration::from_millis(2000)); + let sleep = time::sleep(Duration::from_secs(2)); tokio::pin!(sleep); tokio::select! { diff --git a/packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs b/packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs index 5bd0e27c8..90fc721d0 100644 --- a/packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs +++ b/packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs @@ -9,7 +9,7 @@ use crate::helpers::sync; fn bench_connect_once(c: &mut Criterion) { let mut group = c.benchmark_group("udp_tracker/connect_once"); group.warm_up_time(Duration::from_millis(500)); - group.measurement_time(Duration::from_millis(1000)); + group.measurement_time(Duration::from_secs(1)); group.bench_function("connect_once", |b| { b.iter(|| sync::connect_once(100)); diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index a514921cc..4fd3a95d9 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -54,7 +54,7 @@ impl Launcher { panic!("it should not use udp if using authentication"); } - let socket = tokio::time::timeout(Duration::from_millis(5000), BoundSocket::new(bind_to)) + let socket = tokio::time::timeout(Duration::from_secs(5), BoundSocket::new(bind_to)) .await .expect("it should bind to the socket within five seconds"); diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index 94a86e3ab..c4c995b8a 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -330,7 +330,7 @@ mod tests { // Calculate new average with processing time of 2000ns // This will increment the processed requests counter from 0 to 1 - let processing_time = Duration::from_nanos(2000); + let processing_time = Duration::from_micros(2); let new_avg = repo .recalculate_udp_avg_processing_time_ns(processing_time, &connect_labels, now) .await; @@ -417,7 +417,7 @@ mod tests { let now = CurrentClock::now(); // Test with zero connections (should not panic, should handle division by zero) - let processing_time = Duration::from_nanos(1000); + let processing_time = Duration::from_micros(1); let connect_labels = LabelSet::from([("request_kind", "connect")]); let connect_avg = repo diff --git a/packages/udp-tracker-server/tests/server/contract.rs b/packages/udp-tracker-server/tests/server/contract.rs index e9691c879..350f3b8eb 100644 --- a/packages/udp-tracker-server/tests/server/contract.rs +++ b/packages/udp-tracker-server/tests/server/contract.rs @@ -32,7 +32,7 @@ async fn send_connection_request(transaction_id: TransactionId, client: &UdpTrac match response { Response::Connect(connect_response) => connect_response.connection_id, - _ => panic!("error connecting to udp server {:?}", response), + _ => panic!("error connecting to udp server {response:?}"), } } From f9b59f0c8e3dfbc0d79c0b43efbb10b95a157a6d Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 Apr 2026 16:29:05 +0100 Subject: [PATCH 1293/1297] fix(lint/cspell): configure ignores and dictionary for repo --- .github/workflows/upload_coverage_pr.yaml | 2 +- cspell.json | 27 ++++++++++++ project-words.txt | 53 +++++++++++++++++++++++ 3 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 cspell.json diff --git a/.github/workflows/upload_coverage_pr.yaml b/.github/workflows/upload_coverage_pr.yaml index 8b0006a6d..55de02c62 100644 --- a/.github/workflows/upload_coverage_pr.yaml +++ b/.github/workflows/upload_coverage_pr.yaml @@ -1,7 +1,7 @@ name: Upload Coverage Report (PR) on: - # This workflow is triggered after every successfull execution + # This workflow is triggered after every successful execution # of `Generate Coverage Report` workflow. workflow_run: workflows: ["Generate Coverage Report (PR)"] diff --git a/cspell.json b/cspell.json new file mode 100644 index 000000000..02f29f7f9 --- /dev/null +++ b/cspell.json @@ -0,0 +1,27 @@ +{ + "$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json", + "version": "0.2", + "dictionaryDefinitions": [ + { + "name": "project-words", + "path": "./project-words.txt", + "addWords": true + } + ], + "dictionaries": [ + "project-words" + ], + "enableFiletypes": [ + "dockerfile", + "shellscript", + "toml" + ], + "ignorePaths": [ + "target", + "docs/media/*.svg", + "contrib/bencode/benches/*.bencode", + "contrib/dev-tools/su-exec/**", + ".github/labels.json", + "/project-words.txt" + ] +} \ No newline at end of file diff --git a/project-words.txt b/project-words.txt index c698eea9c..48c9565cc 100644 --- a/project-words.txt +++ b/project-words.txt @@ -197,3 +197,56 @@ Xunlei xxxxxxxxxxxxxxxxxxxxd yyyyyyyyyyyyyyyyyyyyd zerocopy +Aideq +autoremove +CALLSITE +Dihc +Dmqcd +QJSF +Glrg +Irwe +Uninit +Unparker +eventfd +fastrand +fdbased +fdget +fput +iiiiiiiiiiiiiiiippe +iiiiiiiiiiiiiiiipp +iiiiiiiiiiiiiiip +iipp +iiiipp +jdbe +ksys +llist +mmap +mprotect +nonblocking +peersld +pkey +porti +prealloc +println +shellcheck +sockfd +subkey +sysmalloc +sysret +timespec +toki +torru +ttwu +uninit +unparked +unsync +vtable +wakelist +wakeup +actix +iterationsadd +josecelano +mysqladmin +setgroups +taplo +trixie From b654fa5fb18ffa94d167aef3e21becfdac7fbda7 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 Apr 2026 16:40:03 +0100 Subject: [PATCH 1294/1297] fix(lint/markdown): resolve markdownlint violations --- README.md | 18 ++++-------------- contrib/bencode/README.md | 3 ++- contrib/dev-tools/su-exec/README.md | 4 ++-- 3 files changed, 8 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index bb102355b..2fe28db08 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ Others: ## Implemented BitTorrent Enhancement Proposals (BEPs) -> + > _[Learn more about BitTorrent Enhancement Proposals][BEP 00]_ - [BEP 03]: The BitTorrent Protocol. @@ -113,8 +113,8 @@ podman run -it docker.io/torrust/tracker:develop ### Development Version -- Please ensure you have the _**[latest stable (or nightly) version of rust][rust]___. -- Please ensure that your computer has enough RAM. _**Recommended 16GB.___ +- Please ensure you have the \_\*\*[latest stable (or nightly) version of rust][rust]\_\_\_. +- Please ensure that your computer has enough RAM. \_\*\*Recommended 16GB.\_\_\_ #### Checkout, Test and Run @@ -217,7 +217,7 @@ This program is free software: you can redistribute it and/or modify it under th This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the [GNU Affero General Public License][AGPL_3_0] for more details. -You should have received a copy of the *GNU Affero General Public License* along with this program. If not, see . +You should have received a copy of the _GNU Affero General Public License_ along with this program. If not, see . Some files include explicit copyright notices and/or license notices. @@ -250,18 +250,14 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [deployment_wf_b]: ../../actions/workflows/deployment.yaml/badge.svg [testing_wf]: ../../actions/workflows/testing.yaml [testing_wf_b]: ../../actions/workflows/testing.yaml/badge.svg - [bittorrent]: http://bittorrent.org/ [rust]: https://www.rust-lang.org/ [axum]: https://github.com/tokio-rs/axum [newtrackon]: https://newtrackon.com/ [coverage]: https://app.codecov.io/gh/torrust/torrust-tracker [torrust]: https://torrust.com/ - [dockerhub]: https://hub.docker.com/r/torrust/tracker/tags - [torrent_source_felid]: https://github.com/qbittorrent/qBittorrent/discussions/19406 - [BEP 00]: https://www.bittorrent.org/beps/bep_0000.html [BEP 03]: https://www.bittorrent.org/beps/bep_0003.html [BEP 07]: https://www.bittorrent.org/beps/bep_0007.html @@ -269,24 +265,18 @@ This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [D [BEP 23]: https://www.bittorrent.org/beps/bep_0023.html [BEP 27]: https://www.bittorrent.org/beps/bep_0027.html [BEP 48]: https://www.bittorrent.org/beps/bep_0048.html - [containers.md]: ./docs/containers.md - [docs]: https://docs.rs/torrust-tracker/latest/ [api]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/apis/v1 [http]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/http [udp]: https://docs.rs/torrust-tracker/latest/torrust_tracker/servers/udp - [good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 [discussions]: https://github.com/torrust/torrust-tracker/discussions - [guide.md]: https://github.com/torrust/.github/blob/main/info/contributing.md [agreement.md]: https://github.com/torrust/.github/blob/main/info/licensing/contributor_agreement_v01.md - [AGPL_3_0]: ./docs/licenses/LICENSE-AGPL_3_0 [MIT_0]: ./docs/licenses/LICENSE-MIT_0 [FSF]: https://www.fsf.org/ - [nautilus]: https://github.com/orgs/Nautilus-Cyberneering/ [Dutch Bits]: https://dutchbits.nl [Naim A.]: https://github.com/naim94a/udpt diff --git a/contrib/bencode/README.md b/contrib/bencode/README.md index 7a203082b..81c09f691 100644 --- a/contrib/bencode/README.md +++ b/contrib/bencode/README.md @@ -1,4 +1,5 @@ # Bencode + This library allows for the creation and parsing of bencode encodings. -Bencode is the binary encoding used throughout bittorrent technologies from metainfo files to DHT messages. Bencode types include integers, byte arrays, lists, and dictionaries, of which the last two can hold any bencode type (they could be recursively constructed). \ No newline at end of file +Bencode is the binary encoding used throughout bittorrent technologies from metainfo files to DHT messages. Bencode types include integers, byte arrays, lists, and dictionaries, of which the last two can hold any bencode type (they could be recursively constructed). diff --git a/contrib/dev-tools/su-exec/README.md b/contrib/dev-tools/su-exec/README.md index 2b0517377..1dd4108ac 100644 --- a/contrib/dev-tools/su-exec/README.md +++ b/contrib/dev-tools/su-exec/README.md @@ -1,4 +1,5 @@ # su-exec + switch user and group id, setgroups and exec ## Purpose @@ -21,7 +22,7 @@ name separated with colon (e.g. `nobody:ftp`). Numeric uid/gid values can be used instead of names. Example: ```shell -$ su-exec apache:1000 /usr/sbin/httpd -f /opt/www/httpd.conf +su-exec apache:1000 /usr/sbin/httpd -f /opt/www/httpd.conf ``` ## TTY & parent/child handling @@ -43,4 +44,3 @@ PID USER TIME COMMAND This does more or less exactly the same thing as [gosu](https://github.com/tianon/gosu) but it is only 10kb instead of 1.8MB. - From 0e174af960b966e3a6a8d1b69fd306a4fbc07b83 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 Apr 2026 16:53:14 +0100 Subject: [PATCH 1295/1297] fix(lint/yaml): resolve workflow yamllint issues --- .github/workflows/container.yaml | 10 ++++++++-- .github/workflows/coverage.yaml | 4 ++-- .github/workflows/generate_coverage_pr.yaml | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml index e0857e936..7e8ffa442 100644 --- a/.github/workflows/container.yaml +++ b/.github/workflows/container.yaml @@ -80,9 +80,15 @@ jobs: echo "continue=true" >> $GITHUB_OUTPUT echo "On \`develop\` Branch, Type: \`development\`" - elif [[ $(echo "${{ github.ref }}" | grep -P '^(refs\/heads\/releases\/)(v)(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$') ]]; then + elif [[ "${{ github.ref }}" =~ ^refs/heads/releases/ ]]; then + semver_regex='^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(\.(0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(\+([0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*))?$' + version=$(echo "${{ github.ref }}" | sed -n -E 's#^refs/heads/releases/##p') + + if [[ ! "$version" =~ $semver_regex ]]; then + echo "Not a valid release branch semver. Will Not Continue" + exit 0 + fi - version=$(echo "${{ github.ref }}" | sed -n -E 's/^(refs\/heads\/releases\/)//p') echo "version=$version" >> $GITHUB_OUTPUT echo "type=release" >> $GITHUB_OUTPUT echo "continue=true" >> $GITHUB_OUTPUT diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 2c8d63d6c..4c49217c2 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -44,7 +44,7 @@ jobs: - id: coverage name: Generate Coverage Report run: | - cargo clean + cargo clean cargo llvm-cov --all-features --workspace --codecov --output-path ./codecov.json - id: upload @@ -54,4 +54,4 @@ jobs: verbose: true token: ${{ secrets.CODECOV_TOKEN }} files: ${{ github.workspace }}/codecov.json - fail_ci_if_error: true \ No newline at end of file + fail_ci_if_error: true diff --git a/.github/workflows/generate_coverage_pr.yaml b/.github/workflows/generate_coverage_pr.yaml index a3f97dbf2..e07a5a755 100644 --- a/.github/workflows/generate_coverage_pr.yaml +++ b/.github/workflows/generate_coverage_pr.yaml @@ -44,7 +44,7 @@ jobs: - id: coverage name: Generate Coverage Report run: | - cargo clean + cargo clean cargo llvm-cov --all-features --workspace --codecov --output-path ./codecov.json - name: Store PR number and commit SHA From 7085250ee5033b6ed62dfdf92e4c2c57256dbb85 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 Apr 2026 16:55:12 +0100 Subject: [PATCH 1296/1297] fix(lint/toml): normalize taplo formatting across workspace --- .cargo/config.toml | 32 +++++++++---------- .taplo.toml | 18 ++++------- Cargo.toml | 24 +++++++------- console/tracker-client/Cargo.toml | 18 +++++------ contrib/bencode/Cargo.toml | 4 +-- .../axum-health-check-api-server/Cargo.toml | 18 +++++------ packages/axum-http-tracker-server/Cargo.toml | 20 ++++++------ .../axum-rest-tracker-api-server/Cargo.toml | 28 ++++++++-------- packages/axum-server/Cargo.toml | 12 +++---- packages/clock/Cargo.toml | 4 +-- packages/configuration/Cargo.toml | 16 +++++----- packages/events/Cargo.toml | 4 +-- packages/http-protocol/Cargo.toml | 6 ++-- packages/http-tracker-core/Cargo.toml | 6 ++-- packages/located-error/Cargo.toml | 2 +- packages/metrics/Cargo.toml | 8 ++--- packages/primitives/Cargo.toml | 6 ++-- packages/rest-tracker-api-client/Cargo.toml | 10 +++--- packages/rest-tracker-api-core/Cargo.toml | 4 +-- packages/server-lib/Cargo.toml | 8 ++--- .../swarm-coordination-registry/Cargo.toml | 12 +++---- packages/test-helpers/Cargo.toml | 4 +-- .../Cargo.toml | 8 ++--- packages/tracker-client/Cargo.toml | 12 +++---- packages/tracker-core/Cargo.toml | 14 ++++---- packages/udp-protocol/Cargo.toml | 2 +- packages/udp-tracker-core/Cargo.toml | 6 ++-- packages/udp-tracker-server/Cargo.toml | 10 +++--- 28 files changed, 156 insertions(+), 160 deletions(-) diff --git a/.cargo/config.toml b/.cargo/config.toml index 28cde74ec..36a0b3d8c 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -7,20 +7,20 @@ time = "build --timings --all-targets" [build] rustflags = [ - "-D", - "warnings", - "-D", - "future-incompatible", - "-D", - "let-underscore", - "-D", - "nonstandard-style", - "-D", - "rust-2018-compatibility", - "-D", - "rust-2018-idioms", - "-D", - "rust-2021-compatibility", - "-D", - "unused", + "-D", + "warnings", + "-D", + "future-incompatible", + "-D", + "let-underscore", + "-D", + "nonstandard-style", + "-D", + "rust-2018-compatibility", + "-D", + "rust-2018-idioms", + "-D", + "rust-2021-compatibility", + "-D", + "unused", ] diff --git a/.taplo.toml b/.taplo.toml index d0f755dcd..0168711e8 100644 --- a/.taplo.toml +++ b/.taplo.toml @@ -2,11 +2,7 @@ # Used by the "Even Better TOML" VS Code extension # Exclude generated and runtime folders from linting -exclude = [ - "target/**", - "storage/**", - ".coverage/**", -] +exclude = [ ".coverage/**", "storage/**", "target/**" ] [formatting] # Preserve blank lines that exist @@ -14,18 +10,18 @@ allowed_blank_lines = 1 # Don't reorder keys to maintain structure reorder_keys = false # Array formatting -array_trailing_comma = true -array_auto_expand = false array_auto_collapse = false +array_auto_expand = false +array_trailing_comma = true # Inline table formatting -inline_table_expand = false -compact_inline_tables = false compact_arrays = false +compact_inline_tables = false +inline_table_expand = false # Alignment -align_entries = false align_comments = true +align_entries = false # Indentation -indent_tables = false indent_entries = false +indent_tables = false # Other trailing_newline = true diff --git a/Cargo.toml b/Cargo.toml index dbc39bdf8..1eb5f0d35 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,13 +19,13 @@ version.workspace = true name = "torrust_tracker_lib" [workspace.package] -authors = ["Nautilus Cyberneering , Mick van Dijke "] -categories = ["network-programming", "web-programming"] +authors = [ "Nautilus Cyberneering , Mick van Dijke " ] +categories = [ "network-programming", "web-programming" ] description = "A feature rich BitTorrent tracker." documentation = "https://docs.rs/crate/torrust-tracker/" edition = "2021" homepage = "https://torrust.com/" -keywords = ["bittorrent", "file-sharing", "peer-to-peer", "torrent", "tracker"] +keywords = [ "bittorrent", "file-sharing", "peer-to-peer", "torrent", "tracker" ] license = "AGPL-3.0-only" publish = true repository = "https://github.com/torrust/torrust-tracker" @@ -34,19 +34,19 @@ version = "3.0.0-develop" [dependencies] anyhow = "1" -axum-server = { version = "0", features = ["tls-rustls-no-provider"] } +axum-server = { version = "0", features = [ "tls-rustls-no-provider" ] } bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "packages/http-tracker-core" } bittorrent-tracker-core = { version = "3.0.0-develop", path = "packages/tracker-core" } bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "packages/udp-tracker-core" } -chrono = { version = "0", default-features = false, features = ["clock"] } -clap = { version = "4", features = ["derive", "env"] } +chrono = { version = "0", default-features = false, features = [ "clock" ] } +clap = { version = "4", features = [ "derive", "env" ] } rand = "0" regex = "1" -reqwest = { version = "0", features = ["json"] } -serde = { version = "1", features = ["derive"] } -serde_json = { version = "1", features = ["preserve_order"] } +reqwest = { version = "0", features = [ "json" ] } +serde = { version = "1", features = [ "derive" ] } +serde_json = { version = "1", features = [ "preserve_order" ] } thiserror = "2.0.12" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } tokio-util = "0.7.15" torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "packages/axum-health-check-api-server" } torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "packages/axum-http-tracker-server" } @@ -59,7 +59,7 @@ torrust-tracker-configuration = { version = "3.0.0-develop", path = "packages/co torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "packages/swarm-coordination-registry" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "packages/udp-tracker-server" } tracing = "0" -tracing-subscriber = { version = "0", features = ["json"] } +tracing-subscriber = { version = "0", features = [ "json" ] } [dev-dependencies] bittorrent-primitives = "0.1.0" @@ -70,7 +70,7 @@ torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "packages/ torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "packages/test-helpers" } [workspace] -members = ["console/tracker-client", "packages/torrent-repository-benchmarking"] +members = [ "console/tracker-client", "packages/torrent-repository-benchmarking" ] [profile.dev] debug = 1 diff --git a/console/tracker-client/Cargo.toml b/console/tracker-client/Cargo.toml index d4ab7c9e3..8c12227e9 100644 --- a/console/tracker-client/Cargo.toml +++ b/console/tracker-client/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A collection of console clients to make requests to BitTorrent trackers." -keywords = ["bittorrent", "client", "tracker"] +keywords = [ "bittorrent", "client", "tracker" ] license = "LGPL-3.0" name = "torrust-tracker-client" readme = "README.md" @@ -19,21 +19,21 @@ anyhow = "1" aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "../../packages/tracker-client" } -clap = { version = "4", features = ["derive", "env"] } +clap = { version = "4", features = [ "derive", "env" ] } futures = "0" hex-literal = "1" hyper = "1" -reqwest = { version = "0", features = ["json"] } -serde = { version = "1", features = ["derive"] } +reqwest = { version = "0", features = [ "json" ] } +serde = { version = "1", features = [ "derive" ] } serde_bencode = "0" serde_bytes = "0" -serde_json = { version = "1", features = ["preserve_order"] } +serde_json = { version = "1", features = [ "preserve_order" ] } thiserror = "2" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../../packages/configuration" } tracing = "0" -tracing-subscriber = { version = "0", features = ["json"] } -url = { version = "2", features = ["serde"] } +tracing-subscriber = { version = "0", features = [ "json" ] } +url = { version = "2", features = [ "serde" ] } [package.metadata.cargo-machete] -ignored = ["serde_bytes"] +ignored = [ "serde_bytes" ] diff --git a/contrib/bencode/Cargo.toml b/contrib/bencode/Cargo.toml index f6355b6fc..5fab1792d 100644 --- a/contrib/bencode/Cargo.toml +++ b/contrib/bencode/Cargo.toml @@ -1,10 +1,10 @@ [package] description = "(contrib) Efficient decoding and encoding for bencode." -keywords = ["bencode", "contrib", "library"] +keywords = [ "bencode", "contrib", "library" ] name = "torrust-tracker-contrib-bencode" readme = "README.md" -authors = ["Nautilus Cyberneering , Andrew "] +authors = [ "Nautilus Cyberneering , Andrew " ] license = "Apache-2.0" repository = "https://github.com/torrust/bittorrent-infrastructure-project" diff --git a/packages/axum-health-check-api-server/Cargo.toml b/packages/axum-health-check-api-server/Cargo.toml index e0504f7df..cf9d8d9a3 100644 --- a/packages/axum-health-check-api-server/Cargo.toml +++ b/packages/axum-health-check-api-server/Cargo.toml @@ -4,7 +4,7 @@ description = "The Torrust Bittorrent HTTP tracker." documentation.workspace = true edition.workspace = true homepage.workspace = true -keywords = ["axum", "bittorrent", "healthcheck", "http", "server", "torrust", "tracker"] +keywords = [ "axum", "bittorrent", "healthcheck", "http", "server", "torrust", "tracker" ] license.workspace = true name = "torrust-axum-health-check-api-server" publish.workspace = true @@ -14,27 +14,27 @@ rust-version.workspace = true version.workspace = true [dependencies] -axum = { version = "0", features = ["macros"] } -axum-server = { version = "0", features = ["tls-rustls-no-provider"] } +axum = { version = "0", features = [ "macros" ] } +axum-server = { version = "0", features = [ "tls-rustls-no-provider" ] } futures = "0" hyper = "1" -serde = { version = "1", features = ["derive"] } -serde_json = { version = "1", features = ["preserve_order"] } -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +serde = { version = "1", features = [ "derive" ] } +serde_json = { version = "1", features = [ "preserve_order" ] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } +tower-http = { version = "0", features = [ "compression-full", "cors", "propagate-header", "request-id", "trace" ] } tracing = "0" url = "2.5.4" [dev-dependencies] -reqwest = { version = "0", features = ["json"] } +reqwest = { version = "0", features = [ "json" ] } torrust-axum-health-check-api-server = { version = "3.0.0-develop", path = "../axum-health-check-api-server" } torrust-axum-http-tracker-server = { version = "3.0.0-develop", path = "../axum-http-tracker-server" } torrust-axum-rest-tracker-api-server = { version = "3.0.0-develop", path = "../axum-rest-tracker-api-server" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } -tracing-subscriber = { version = "0", features = ["json"] } +tracing-subscriber = { version = "0", features = [ "json" ] } diff --git a/packages/axum-http-tracker-server/Cargo.toml b/packages/axum-http-tracker-server/Cargo.toml index eb2c2cad3..88d073527 100644 --- a/packages/axum-http-tracker-server/Cargo.toml +++ b/packages/axum-http-tracker-server/Cargo.toml @@ -4,7 +4,7 @@ description = "The Torrust Bittorrent HTTP tracker." documentation.workspace = true edition.workspace = true homepage.workspace = true -keywords = ["axum", "bittorrent", "http", "server", "torrust", "tracker"] +keywords = [ "axum", "bittorrent", "http", "server", "torrust", "tracker" ] license.workspace = true name = "torrust-axum-http-tracker-server" publish.workspace = true @@ -15,19 +15,19 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" -axum = { version = "0", features = ["macros"] } +axum = { version = "0", features = [ "macros" ] } axum-client-ip = "0" -axum-server = { version = "0", features = ["tls-rustls-no-provider"] } +axum-server = { version = "0", features = [ "tls-rustls-no-provider" ] } bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "../http-tracker-core" } bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "../http-protocol" } bittorrent-primitives = "0.1.0" bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } -derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } +derive_more = { version = "2", features = [ "as_ref", "constructor", "from" ] } futures = "0" hyper = "1" -reqwest = { version = "0", features = ["json"] } -serde = { version = "1", features = ["derive"] } -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +reqwest = { version = "0", features = [ "json" ] } +serde = { version = "1", features = [ "derive" ] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } tokio-util = "0.7.15" torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } @@ -35,8 +35,8 @@ torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } -tower = { version = "0", features = ["timeout"] } -tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } +tower = { version = "0", features = [ "timeout" ] } +tower-http = { version = "0", features = [ "compression-full", "cors", "propagate-header", "request-id", "trace" ] } tracing = "0" [dev-dependencies] @@ -49,5 +49,5 @@ serde_repr = "0" torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-events = { version = "3.0.0-develop", path = "../events" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } -uuid = { version = "1", features = ["v4"] } +uuid = { version = "1", features = [ "v4" ] } zerocopy = "0.7" diff --git a/packages/axum-rest-tracker-api-server/Cargo.toml b/packages/axum-rest-tracker-api-server/Cargo.toml index 9493b8693..7353e66e8 100644 --- a/packages/axum-rest-tracker-api-server/Cargo.toml +++ b/packages/axum-rest-tracker-api-server/Cargo.toml @@ -4,7 +4,7 @@ description = "The Torrust Tracker API." documentation.workspace = true edition.workspace = true homepage.workspace = true -keywords = ["axum", "bittorrent", "http", "server", "torrust", "tracker"] +keywords = [ "axum", "bittorrent", "http", "server", "torrust", "tracker" ] license.workspace = true name = "torrust-axum-rest-tracker-api-server" publish.workspace = true @@ -15,22 +15,22 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" -axum = { version = "0", features = ["macros"] } -axum-extra = { version = "0", features = ["query"] } -axum-server = { version = "0", features = ["tls-rustls-no-provider"] } +axum = { version = "0", features = [ "macros" ] } +axum-extra = { version = "0", features = [ "query" ] } +axum-server = { version = "0", features = [ "tls-rustls-no-provider" ] } bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "../http-tracker-core" } bittorrent-primitives = "0.1.0" bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "../udp-tracker-core" } -derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } +derive_more = { version = "2", features = [ "as_ref", "constructor", "from" ] } futures = "0" hyper = "1" -reqwest = { version = "0", features = ["json"] } -serde = { version = "1", features = ["derive"] } -serde_json = { version = "1", features = ["preserve_order"] } -serde_with = { version = "3", features = ["json"] } +reqwest = { version = "0", features = [ "json" ] } +serde = { version = "1", features = [ "derive" ] } +serde_json = { version = "1", features = [ "preserve_order" ] } +serde_with = { version = "3", features = [ "json" ] } thiserror = "2" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } torrust-axum-server = { version = "3.0.0-develop", path = "../axum-server" } torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "../rest-tracker-api-client" } torrust-rest-tracker-api-core = { version = "3.0.0-develop", path = "../rest-tracker-api-core" } @@ -41,8 +41,8 @@ torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } torrust-udp-tracker-server = { version = "3.0.0-develop", path = "../udp-tracker-server" } -tower = { version = "0", features = ["timeout"] } -tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } +tower = { version = "0", features = [ "timeout" ] } +tower-http = { version = "0", features = [ "compression-full", "cors", "propagate-header", "request-id", "trace" ] } tracing = "0" url = "2" @@ -51,5 +51,5 @@ local-ip-address = "0" mockall = "0" torrust-rest-tracker-api-client = { version = "3.0.0-develop", path = "../rest-tracker-api-client" } torrust-tracker-test-helpers = { version = "3.0.0-develop", path = "../test-helpers" } -url = { version = "2", features = ["serde"] } -uuid = { version = "1", features = ["v4"] } +url = { version = "2", features = [ "serde" ] } +uuid = { version = "1", features = [ "v4" ] } diff --git a/packages/axum-server/Cargo.toml b/packages/axum-server/Cargo.toml index a60bab885..45eddd3b0 100644 --- a/packages/axum-server/Cargo.toml +++ b/packages/axum-server/Cargo.toml @@ -4,7 +4,7 @@ description = "A wrapper for the Axum server for Torrust HTTP servers to add tim documentation.workspace = true edition.workspace = true homepage.workspace = true -keywords = ["axum", "server", "torrust", "wrapper"] +keywords = [ "axum", "server", "torrust", "wrapper" ] license.workspace = true name = "torrust-axum-server" publish.workspace = true @@ -14,19 +14,19 @@ rust-version.workspace = true version.workspace = true [dependencies] -axum-server = { version = "0", features = ["tls-rustls-no-provider"] } -camino = { version = "1", features = ["serde", "serde1"] } +axum-server = { version = "0", features = [ "tls-rustls-no-provider" ] } +camino = { version = "1", features = [ "serde", "serde1" ] } futures-util = "0" http-body = "1" hyper = "1" -hyper-util = { version = "0", features = ["http1", "http2", "tokio"] } +hyper-util = { version = "0", features = [ "http1", "http2", "tokio" ] } pin-project-lite = "0" thiserror = "2" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } -tower = { version = "0", features = ["timeout"] } +tower = { version = "0", features = [ "timeout" ] } tracing = "0" [dev-dependencies] diff --git a/packages/clock/Cargo.toml b/packages/clock/Cargo.toml index 3bd00d2b0..c0cafff0a 100644 --- a/packages/clock/Cargo.toml +++ b/packages/clock/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library to a clock for the torrust tracker." -keywords = ["clock", "library", "torrents"] +keywords = [ "clock", "library", "torrents" ] name = "torrust-tracker-clock" readme = "README.md" @@ -16,7 +16,7 @@ rust-version.workspace = true version.workspace = true [dependencies] -chrono = { version = "0", default-features = false, features = ["clock"] } +chrono = { version = "0", default-features = false, features = [ "clock" ] } lazy_static = "1" tracing = "0" diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index e213f7c0c..1155ba417 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library to provide configuration to the Torrust Tracker." -keywords = ["config", "library", "settings"] +keywords = [ "config", "library", "settings" ] name = "torrust-tracker-configuration" readme = "README.md" @@ -15,18 +15,18 @@ rust-version.workspace = true version.workspace = true [dependencies] -camino = { version = "1", features = ["serde", "serde1"] } -derive_more = { version = "2", features = ["constructor", "display"] } -figment = { version = "0", features = ["env", "test", "toml"] } -serde = { version = "1", features = ["derive"] } -serde_json = { version = "1", features = ["preserve_order"] } +camino = { version = "1", features = [ "serde", "serde1" ] } +derive_more = { version = "2", features = [ "constructor", "display" ] } +figment = { version = "0", features = [ "env", "test", "toml" ] } +serde = { version = "1", features = [ "derive" ] } +serde_json = { version = "1", features = [ "preserve_order" ] } serde_with = "3" thiserror = "2" toml = "0" torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } tracing = "0" -tracing-subscriber = { version = "0", features = ["json"] } +tracing-subscriber = { version = "0", features = [ "json" ] } url = "2" [dev-dependencies] -uuid = { version = "1", features = ["v4"] } +uuid = { version = "1", features = [ "v4" ] } diff --git a/packages/events/Cargo.toml b/packages/events/Cargo.toml index 1d183cddb..165ecca68 100644 --- a/packages/events/Cargo.toml +++ b/packages/events/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library with functionality to handle events in Torrust tracker packages." -keywords = ["events", "library", "rust", "torrust", "tracker"] +keywords = [ "events", "library", "rust", "torrust", "tracker" ] name = "torrust-tracker-events" readme = "README.md" @@ -16,7 +16,7 @@ version.workspace = true [dependencies] futures = "0" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync", "time"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync", "time" ] } [dev-dependencies] mockall = "0" diff --git a/packages/http-protocol/Cargo.toml b/packages/http-protocol/Cargo.toml index 7803fe78e..78a037b18 100644 --- a/packages/http-protocol/Cargo.toml +++ b/packages/http-protocol/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library with the primitive types and functions for the BitTorrent HTTP tracker protocol." -keywords = ["api", "library", "primitives"] +keywords = [ "api", "library", "primitives" ] name = "bittorrent-http-tracker-protocol" readme = "README.md" @@ -18,10 +18,10 @@ version.workspace = true aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } -derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } +derive_more = { version = "2", features = [ "as_ref", "constructor", "from" ] } multimap = "0" percent-encoding = "2" -serde = { version = "1", features = ["derive"] } +serde = { version = "1", features = [ "derive" ] } serde_bencode = "0" thiserror = "2" torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } diff --git a/packages/http-tracker-core/Cargo.toml b/packages/http-tracker-core/Cargo.toml index 04a6c96b6..c419052f9 100644 --- a/packages/http-tracker-core/Cargo.toml +++ b/packages/http-tracker-core/Cargo.toml @@ -4,7 +4,7 @@ description = "A library with the core functionality needed to implement a BitTo documentation.workspace = true edition.workspace = true homepage.workspace = true -keywords = ["api", "bittorrent", "core", "library", "tracker"] +keywords = [ "api", "bittorrent", "core", "library", "tracker" ] license.workspace = true name = "bittorrent-http-tracker-core" publish.workspace = true @@ -18,11 +18,11 @@ aquatic_udp_protocol = "0" bittorrent-http-tracker-protocol = { version = "3.0.0-develop", path = "../http-protocol" } bittorrent-primitives = "0.1.0" bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } -criterion = { version = "0.5.1", features = ["async_tokio"] } +criterion = { version = "0.5.1", features = [ "async_tokio" ] } futures = "0" serde = "1.0.219" thiserror = "2" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } tokio-util = "0.7.15" torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index 29b0dfb2c..232a6113f 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library to provide error decorator with the location and the source of the original error." -keywords = ["errors", "helper", "library"] +keywords = [ "errors", "helper", "library" ] name = "torrust-tracker-located-error" readme = "README.md" diff --git a/packages/metrics/Cargo.toml b/packages/metrics/Cargo.toml index 0597785f4..b6d327d70 100644 --- a/packages/metrics/Cargo.toml +++ b/packages/metrics/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library with the primitive types shared by the Torrust tracker packages." -keywords = ["api", "library", "metrics"] +keywords = [ "api", "library", "metrics" ] name = "torrust-tracker-metrics" readme = "README.md" @@ -15,9 +15,9 @@ rust-version.workspace = true version.workspace = true [dependencies] -chrono = { version = "0", default-features = false, features = ["clock"] } -derive_more = { version = "2", features = ["constructor"] } -serde = { version = "1", features = ["derive"] } +chrono = { version = "0", default-features = false, features = [ "clock" ] } +derive_more = { version = "2", features = [ "constructor" ] } +serde = { version = "1", features = [ "derive" ] } serde_json = "1.0.140" thiserror = "2" torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index 21fab09bf..c9ce64177 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library with the primitive types shared by the Torrust tracker packages." -keywords = ["api", "library", "primitives"] +keywords = [ "api", "library", "primitives" ] name = "torrust-tracker-primitives" readme = "README.md" @@ -18,8 +18,8 @@ version.workspace = true aquatic_udp_protocol = "0" binascii = "0" bittorrent-primitives = "0.1.0" -derive_more = { version = "2", features = ["constructor"] } -serde = { version = "1", features = ["derive"] } +derive_more = { version = "2", features = [ "constructor" ] } +serde = { version = "1", features = [ "derive" ] } tdyne-peer-id = "1" tdyne-peer-id-registry = "0" thiserror = "2" diff --git a/packages/rest-tracker-api-client/Cargo.toml b/packages/rest-tracker-api-client/Cargo.toml index c01b9c05a..47307df9a 100644 --- a/packages/rest-tracker-api-client/Cargo.toml +++ b/packages/rest-tracker-api-client/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library to interact with the Torrust Tracker REST API." -keywords = ["bittorrent", "client", "tracker"] +keywords = [ "bittorrent", "client", "tracker" ] license = "LGPL-3.0" name = "torrust-rest-tracker-api-client" readme = "README.md" @@ -16,8 +16,8 @@ version.workspace = true [dependencies] hyper = "1" -reqwest = { version = "0", features = ["json", "query"] } -serde = { version = "1", features = ["derive"] } +reqwest = { version = "0", features = [ "json", "query" ] } +serde = { version = "1", features = [ "derive" ] } thiserror = "2" -url = { version = "2", features = ["serde"] } -uuid = { version = "1", features = ["v4"] } +url = { version = "2", features = [ "serde" ] } +uuid = { version = "1", features = [ "v4" ] } diff --git a/packages/rest-tracker-api-core/Cargo.toml b/packages/rest-tracker-api-core/Cargo.toml index be6d493d7..0808c2dd6 100644 --- a/packages/rest-tracker-api-core/Cargo.toml +++ b/packages/rest-tracker-api-core/Cargo.toml @@ -4,7 +4,7 @@ description = "A library with the core functionality needed to implement a BitTo documentation.workspace = true edition.workspace = true homepage.workspace = true -keywords = ["api", "bittorrent", "core", "library", "tracker"] +keywords = [ "api", "bittorrent", "core", "library", "tracker" ] license.workspace = true name = "torrust-rest-tracker-api-core" publish.workspace = true @@ -17,7 +17,7 @@ version.workspace = true bittorrent-http-tracker-core = { version = "3.0.0-develop", path = "../http-tracker-core" } bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "../udp-tracker-core" } -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } tokio-util = "0.7.15" torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } diff --git a/packages/server-lib/Cargo.toml b/packages/server-lib/Cargo.toml index 1d30e7fb5..fbd7a7a7f 100644 --- a/packages/server-lib/Cargo.toml +++ b/packages/server-lib/Cargo.toml @@ -4,7 +4,7 @@ description = "Common functionality used in all Torrust HTTP servers." documentation.workspace = true edition.workspace = true homepage.workspace = true -keywords = ["lib", "server", "torrust"] +keywords = [ "lib", "server", "torrust" ] license.workspace = true name = "torrust-server-lib" publish.workspace = true @@ -14,10 +14,10 @@ rust-version.workspace = true version.workspace = true [dependencies] -derive_more = { version = "2", features = ["as_ref", "constructor", "display", "from"] } -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +derive_more = { version = "2", features = [ "as_ref", "constructor", "display", "from" ] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } -tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] } +tower-http = { version = "0", features = [ "compression-full", "cors", "propagate-header", "request-id", "trace" ] } tracing = "0" [dev-dependencies] diff --git a/packages/swarm-coordination-registry/Cargo.toml b/packages/swarm-coordination-registry/Cargo.toml index 45359ad81..f9513d3c4 100644 --- a/packages/swarm-coordination-registry/Cargo.toml +++ b/packages/swarm-coordination-registry/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library that provides a repository of torrents files and their peers." -keywords = ["library", "repository", "torrents"] +keywords = [ "library", "repository", "torrents" ] name = "torrust-tracker-swarm-coordination-registry" readme = "README.md" @@ -18,12 +18,12 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" -chrono = { version = "0", default-features = false, features = ["clock"] } +chrono = { version = "0", default-features = false, features = [ "clock" ] } crossbeam-skiplist = "0" futures = "0" -serde = { version = "1.0.219", features = ["derive"] } +serde = { version = "1.0.219", features = [ "derive" ] } thiserror = "2.0.12" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } tokio-util = "0.7.15" torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } @@ -33,8 +33,8 @@ torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" tracing = "0" [dev-dependencies] -async-std = { version = "1", features = ["attributes", "tokio1"] } -criterion = { version = "0", features = ["async_tokio"] } +async-std = { version = "1", features = [ "attributes", "tokio1" ] } +criterion = { version = "0", features = [ "async_tokio" ] } mockall = "0" rand = "0" rstest = "0" diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 3495c314a..fb240730d 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library providing helpers for testing the Torrust tracker." -keywords = ["helper", "library", "testing"] +keywords = [ "helper", "library", "testing" ] name = "torrust-tracker-test-helpers" readme = "README.md" @@ -18,4 +18,4 @@ version.workspace = true rand = "0" torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } tracing = "0" -tracing-subscriber = { version = "0", features = ["json"] } +tracing-subscriber = { version = "0", features = [ "json" ] } diff --git a/packages/torrent-repository-benchmarking/Cargo.toml b/packages/torrent-repository-benchmarking/Cargo.toml index 1a93c513c..653ad8102 100644 --- a/packages/torrent-repository-benchmarking/Cargo.toml +++ b/packages/torrent-repository-benchmarking/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library to runt benchmarking for different implementations of a repository of torrents files and their peers." -keywords = ["library", "repository", "torrents"] +keywords = [ "library", "repository", "torrents" ] name = "torrust-tracker-torrent-repository-benchmarking" readme = "README.md" @@ -22,15 +22,15 @@ crossbeam-skiplist = "0" dashmap = "6" futures = "0" parking_lot = "0" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } zerocopy = "0.7" [dev-dependencies] -async-std = { version = "1", features = ["attributes", "tokio1"] } -criterion = { version = "0", features = ["async_tokio"] } +async-std = { version = "1", features = [ "attributes", "tokio1" ] } +criterion = { version = "0", features = [ "async_tokio" ] } rstest = "0" [[bench]] diff --git a/packages/tracker-client/Cargo.toml b/packages/tracker-client/Cargo.toml index ef5cccaa2..0cd419471 100644 --- a/packages/tracker-client/Cargo.toml +++ b/packages/tracker-client/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library with the generic tracker clients." -keywords = ["bittorrent", "client", "tracker"] +keywords = [ "bittorrent", "client", "tracker" ] license = "LGPL-3.0" name = "bittorrent-tracker-client" readme = "README.md" @@ -17,16 +17,16 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" -derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } +derive_more = { version = "2", features = [ "as_ref", "constructor", "from" ] } hyper = "1" percent-encoding = "2" -reqwest = { version = "0", features = ["json"] } -serde = { version = "1", features = ["derive"] } +reqwest = { version = "0", features = [ "json" ] } +serde = { version = "1", features = [ "derive" ] } serde_bencode = "0" serde_bytes = "0" serde_repr = "0" thiserror = "2" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } torrust-tracker-located-error = { version = "3.0.0-develop", path = "../located-error" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } @@ -34,4 +34,4 @@ tracing = "0" zerocopy = "0.7" [package.metadata.cargo-machete] -ignored = ["serde_bytes"] +ignored = [ "serde_bytes" ] diff --git a/packages/tracker-core/Cargo.toml b/packages/tracker-core/Cargo.toml index dfc83e58e..fb864cde7 100644 --- a/packages/tracker-core/Cargo.toml +++ b/packages/tracker-core/Cargo.toml @@ -4,7 +4,7 @@ description = "A library with the core functionality needed to implement a BitTo documentation.workspace = true edition.workspace = true homepage.workspace = true -keywords = ["api", "bittorrent", "core", "library", "tracker"] +keywords = [ "api", "bittorrent", "core", "library", "tracker" ] license.workspace = true name = "bittorrent-tracker-core" publish.workspace = true @@ -16,17 +16,17 @@ version.workspace = true [dependencies] aquatic_udp_protocol = "0" bittorrent-primitives = "0.1.0" -chrono = { version = "0", default-features = false, features = ["clock"] } -derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } +chrono = { version = "0", default-features = false, features = [ "clock" ] } +derive_more = { version = "2", features = [ "as_ref", "constructor", "from" ] } mockall = "0" r2d2 = "0" r2d2_mysql = "25" -r2d2_sqlite = { version = "0", features = ["bundled"] } +r2d2_sqlite = { version = "0", features = [ "bundled" ] } rand = "0" -serde = { version = "1", features = ["derive"] } -serde_json = { version = "1", features = ["preserve_order"] } +serde = { version = "1", features = [ "derive" ] } +serde_json = { version = "1", features = [ "preserve_order" ] } thiserror = "2" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } tokio-util = "0.7.15" torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } diff --git a/packages/udp-protocol/Cargo.toml b/packages/udp-protocol/Cargo.toml index 31fd52af8..3bcde9a95 100644 --- a/packages/udp-protocol/Cargo.toml +++ b/packages/udp-protocol/Cargo.toml @@ -1,6 +1,6 @@ [package] description = "A library with the primitive types and functions for the BitTorrent UDP tracker protocol." -keywords = ["bittorrent", "library", "primitives", "udp"] +keywords = [ "bittorrent", "library", "primitives", "udp" ] name = "bittorrent-udp-tracker-protocol" readme = "README.md" diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml index aa12f898f..828b3aff2 100644 --- a/packages/udp-tracker-core/Cargo.toml +++ b/packages/udp-tracker-core/Cargo.toml @@ -4,7 +4,7 @@ description = "A library with the core functionality needed to implement a BitTo documentation.workspace = true edition.workspace = true homepage.workspace = true -keywords = ["api", "bittorrent", "core", "library", "tracker"] +keywords = [ "api", "bittorrent", "core", "library", "tracker" ] license.workspace = true name = "bittorrent-udp-tracker-core" publish.workspace = true @@ -21,14 +21,14 @@ bittorrent-udp-tracker-protocol = { version = "3.0.0-develop", path = "../udp-pr bloom = "0.3.2" blowfish = "0" cipher = "0.4" -criterion = { version = "0.5.1", features = ["async_tokio"] } +criterion = { version = "0.5.1", features = [ "async_tokio" ] } futures = "0" generic-array = "0" lazy_static = "1" rand = "0" serde = "1.0.219" thiserror = "2" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync", "time"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync", "time" ] } tokio-util = "0.7.15" torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } torrust-tracker-configuration = { version = "3.0.0-develop", path = "../configuration" } diff --git a/packages/udp-tracker-server/Cargo.toml b/packages/udp-tracker-server/Cargo.toml index 160fe58f9..dc66572d8 100644 --- a/packages/udp-tracker-server/Cargo.toml +++ b/packages/udp-tracker-server/Cargo.toml @@ -4,7 +4,7 @@ description = "The Torrust Bittorrent UDP tracker." documentation.workspace = true edition.workspace = true homepage.workspace = true -keywords = ["axum", "bittorrent", "server", "torrust", "tracker", "udp"] +keywords = [ "axum", "bittorrent", "server", "torrust", "tracker", "udp" ] license.workspace = true name = "torrust-udp-tracker-server" publish.workspace = true @@ -19,13 +19,13 @@ bittorrent-primitives = "0.1.0" bittorrent-tracker-client = { version = "3.0.0-develop", path = "../tracker-client" } bittorrent-tracker-core = { version = "3.0.0-develop", path = "../tracker-core" } bittorrent-udp-tracker-core = { version = "3.0.0-develop", path = "../udp-tracker-core" } -derive_more = { version = "2", features = ["as_ref", "constructor", "from"] } +derive_more = { version = "2", features = [ "as_ref", "constructor", "from" ] } futures = "0" futures-util = "0" ringbuf = "0" serde = "1.0.219" thiserror = "2" -tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +tokio = { version = "1", features = [ "macros", "net", "rt-multi-thread", "signal", "sync" ] } tokio-util = "0.7.15" torrust-server-lib = { version = "3.0.0-develop", path = "../server-lib" } torrust-tracker-clock = { version = "3.0.0-develop", path = "../clock" } @@ -35,8 +35,8 @@ torrust-tracker-metrics = { version = "3.0.0-develop", path = "../metrics" } torrust-tracker-primitives = { version = "3.0.0-develop", path = "../primitives" } torrust-tracker-swarm-coordination-registry = { version = "3.0.0-develop", path = "../swarm-coordination-registry" } tracing = "0" -url = { version = "2", features = ["serde"] } -uuid = { version = "1", features = ["v4"] } +url = { version = "2", features = [ "serde" ] } +uuid = { version = "1", features = [ "v4" ] } zerocopy = "0.7" [dev-dependencies] From 1d3ba500e9404c971703f24a3e2132dc62486304 Mon Sep 17 00:00:00 2001 From: Jose Celano Date: Wed, 8 Apr 2026 16:59:16 +0100 Subject: [PATCH 1297/1297] ci(lint): switch testing workflow to internal linting tool --- .github/workflows/testing.yaml | 39 ++++++++++++---------------------- 1 file changed, 13 insertions(+), 26 deletions(-) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index c9328d890..83a290663 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -33,9 +33,10 @@ jobs: run: cargo fmt --check check: - name: Static Analysis + name: Linting runs-on: ubuntu-latest needs: format + timeout-minutes: 15 strategy: matrix: @@ -51,39 +52,25 @@ jobs: uses: dtolnay/rust-toolchain@stable with: toolchain: ${{ matrix.toolchain }} - components: clippy + components: clippy, rustfmt + + - id: node + name: Setup Node.js + uses: actions/setup-node@v5 + with: + node-version: "20" - id: cache name: Enable Workflow Cache uses: Swatinem/rust-cache@v2 - id: tools - name: Install Tools - uses: taiki-e/install-action@v2 - with: - tool: cargo-machete - - - id: check - name: Run Build Checks - run: cargo check --tests --benches --examples --workspace --all-targets --all-features + name: Install Internal Linter + run: cargo install --locked --git https://github.com/torrust/torrust-linting --bin linter - id: lint - name: Run Lint Checks - run: cargo clippy --tests --benches --examples --workspace --all-targets --all-features - - - id: docs - name: Lint Documentation - env: - RUSTDOCFLAGS: "-D warnings" - run: cargo doc --no-deps --bins --examples --workspace --all-features - - - id: clean - name: Clean Build Directory - run: cargo clean - - - id: deps - name: Check Unused Dependencies - run: cargo machete + name: Run All Linters + run: linter all build: name: Build on ${{ matrix.os }} (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